-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathupdate_access_models.py
More file actions
316 lines (263 loc) · 10.7 KB
/
Copy pathupdate_access_models.py
File metadata and controls
316 lines (263 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
#!/usr/bin/env python3
"""
Apply canonical access model descriptions across Alma IZs/NZ.
Supports both code tables:
- PublicAccessModel (patron-facing, shown in Primo)
- PQAccessModel (internal, shown on PO lines)
By default, processes whichever tables have a canonical JSON file
present in the script directory. Use --table to target one table.
Usage:
python update_access_models.py # dry run (default)
python update_access_models.py --apply # apply changes
python update_access_models.py --apply --iz 01EXAMPLE_IZ # single IZ
python update_access_models.py --table PQAccessModel # internal only
python update_access_models.py --export --iz 01EXAMPLE_IZ # bootstrap both
python update_access_models.py --export --iz 01EXAMPLE_IZ --table PublicAccessModel
python update_access_models.py --region eu # European institutions
"""
import argparse
import csv
import json
import sys
import time
from pathlib import Path
import requests
API_REGIONS = {
"na": "https://api-na.hosted.exlibrisgroup.com",
"eu": "https://api-eu.hosted.exlibrisgroup.com",
"ap": "https://api-ap.hosted.exlibrisgroup.com",
"aps": "https://api-aps.hosted.exlibrisgroup.com",
"ca": "https://api-ca.hosted.exlibrisgroup.com",
"cn": "https://api-cn.hosted.exlibrisgroup.com.cn",
}
TABLES = {
"PublicAccessModel": "public_access_model.json",
"PQAccessModel": "pq_access_model.json",
}
SCRIPT_DIR = Path(__file__).parent
KEYS_FILE = SCRIPT_DIR / "api_keys.csv"
def load_api_keys(keys_file: Path, filter_iz: str | None = None) -> list[dict]:
"""Load institution API keys from CSV. Returns list of {iz, apikey} dicts."""
rows = []
with open(keys_file, newline="") as f:
reader = csv.DictReader(f)
for row in reader:
iz = row["iz"].strip()
apikey = row["apikey"].strip()
if not apikey:
continue
if filter_iz and iz != filter_iz:
continue
rows.append({"iz": iz, "apikey": apikey})
return rows
def load_canonical(canonical_file: Path) -> dict[str, str]:
"""Load canonical code -> description mapping from JSON."""
with open(canonical_file) as f:
return json.load(f)
def alma_get(endpoint: str, apikey: str, api_base: str) -> dict:
"""GET JSON from an Alma API endpoint."""
url = f"{api_base}{endpoint}"
resp = requests.get(url, params={"apikey": apikey, "format": "json"},
headers={"Accept": "application/json"})
resp.raise_for_status()
return resp.json()
def alma_put(endpoint: str, apikey: str, api_base: str, data: dict) -> dict:
"""PUT JSON to an Alma API endpoint."""
url = f"{api_base}{endpoint}"
resp = requests.put(url, params={"apikey": apikey, "format": "json"},
headers={"Accept": "application/json",
"Content-Type": "application/json"},
json=data)
resp.raise_for_status()
return resp.json()
def export_table(iz: str, apikey: str, api_base: str, table_name: str) -> dict:
"""Fetch a code table for one IZ and return as {code: description} dict."""
endpoint = f"/almaws/v1/conf/code-tables/{table_name}"
try:
table = alma_get(endpoint, apikey, api_base)
except requests.HTTPError as e:
print(f"ERROR fetching {table_name} for {iz}: {e.response.status_code} - "
f"{e.response.text[:200]}", file=sys.stderr)
sys.exit(1)
except requests.RequestException as e:
print(f"ERROR fetching {table_name} for {iz}: {e}", file=sys.stderr)
sys.exit(1)
canonical = {}
for row in table.get("row", []):
canonical[row["code"]] = row.get("description", "")
return canonical
def process_table(iz: str, apikey: str, api_base: str, table_name: str,
canonical: dict[str, str], apply: bool) -> bool:
"""
Fetch a code table for one institution, apply canonical
descriptions, and optionally PUT the result back.
Returns True if changes were found (and applied, if --apply).
"""
endpoint = f"/almaws/v1/conf/code-tables/{table_name}"
try:
table = alma_get(endpoint, apikey, api_base)
except requests.HTTPError as e:
print(f" ERROR fetching {table_name}: {e.response.status_code} - "
f"{e.response.text[:200]}")
return False
except requests.RequestException as e:
print(f" ERROR fetching {table_name}: {e}")
return False
rows = table.get("row", [])
changes = []
unknown_codes = []
for row in rows:
code = row["code"]
old_desc = row.get("description", "")
if code not in canonical:
unknown_codes.append((code, old_desc))
continue
new_desc = canonical[code]
if new_desc != old_desc:
changes.append((code, old_desc, new_desc))
row["description"] = new_desc
if unknown_codes:
print(f"\n WARNING: {len(unknown_codes)} code(s) not in canonical file:")
for code, desc in unknown_codes:
print(f" {code:10s} {desc!r}")
print()
if not changes:
print(f" {table_name}: no changes needed.")
return False
print(f" {table_name}: {len(changes)} description(s) to update:\n")
for code, old, new in changes:
print(f" {code:10s} {old!r}")
print(f" {'':10s} -> {new!r}\n")
if not apply:
print(" [DRY RUN] No changes applied.")
return True
try:
alma_put(endpoint, apikey, api_base, table)
print(f" {table_name}: changes applied successfully.")
return True
except requests.HTTPError as e:
print(f" ERROR applying changes to {table_name}: {e.response.status_code}")
print(f" Response: {e.response.text[:500]}")
return False
except requests.RequestException as e:
print(f" ERROR applying changes to {table_name}: {e}")
return False
def resolve_tables(table_filter: str | None) -> list[str]:
"""Return which table names to process based on --table flag."""
if table_filter:
return [table_filter]
return list(TABLES.keys())
def main():
parser = argparse.ArgumentParser(
description="Apply canonical access model descriptions across Alma IZs."
)
parser.add_argument(
"--apply",
action="store_true",
help="Actually apply changes. Without this flag, runs in dry-run mode.",
)
parser.add_argument(
"--export",
action="store_true",
help="Export an IZ's current descriptions as JSON to stdout. Requires --iz.",
)
parser.add_argument(
"--table",
choices=TABLES.keys(),
default=None,
help="Process only this table. Default: all tables with a canonical file present.",
)
parser.add_argument(
"--iz",
type=str,
default=None,
help="Process only this institution zone (must match 'iz' column in api_keys.csv).",
)
parser.add_argument(
"--region",
choices=API_REGIONS.keys(),
default="na",
help="Alma API region (default: na).",
)
parser.add_argument(
"--keys-file",
type=Path,
default=KEYS_FILE,
help=f"Path to API keys CSV (default: {KEYS_FILE.name}).",
)
args = parser.parse_args()
api_base = API_REGIONS[args.region]
if not args.keys_file.exists():
print(f"ERROR: Keys file not found: {args.keys_file}")
print("Copy api_keys.csv.example to api_keys.csv and fill in your API keys.")
sys.exit(1)
# --- Export mode ---
if args.export:
if not args.iz:
print("ERROR: --export requires --iz to specify which institution to export from.")
sys.exit(1)
institutions = load_api_keys(args.keys_file, filter_iz=args.iz)
if not institutions:
print(f"ERROR: No API key found for {args.iz} in {args.keys_file}.")
sys.exit(1)
inst = institutions[0]
tables_to_export = resolve_tables(args.table)
for table_name in tables_to_export:
canonical = export_table(inst["iz"], inst["apikey"], api_base, table_name)
filename = TABLES[table_name]
filepath = SCRIPT_DIR / filename
with open(filepath, "w") as f:
json.dump(canonical, f, indent=2, ensure_ascii=False)
f.write("\n")
print(f"Exported {len(canonical)} codes from {inst['iz']} "
f"{table_name} -> {filename}", file=sys.stderr)
return
# --- Update mode ---
tables_to_process = resolve_tables(args.table)
# Filter to tables that have a canonical file
active_tables = {}
for table_name in tables_to_process:
canonical_file = SCRIPT_DIR / TABLES[table_name]
if canonical_file.exists():
active_tables[table_name] = load_canonical(canonical_file)
if not active_tables:
if args.table:
print(f"ERROR: Canonical file not found: {TABLES[args.table]}")
else:
print("ERROR: No canonical files found.")
print("Use --export --iz YOUR_IZ to generate them from an existing institution.")
sys.exit(1)
institutions = load_api_keys(args.keys_file, filter_iz=args.iz)
if not institutions:
print("ERROR: No institutions found in keys file (or --iz filter matched nothing).")
sys.exit(1)
mode = "APPLY" if args.apply else "DRY RUN"
print(f"Mode: {mode}")
print(f"Region: {args.region} ({api_base})")
print(f"Institutions: {len(institutions)}")
for table_name, canonical in active_tables.items():
print(f"Table: {table_name} ({len(canonical)} codes from {TABLES[table_name]})")
changed_count = 0
error_count = 0
for inst in institutions:
print(f"\n{'='*60}")
print(f" {inst['iz']}")
print(f"{'='*60}")
for table_name, canonical in active_tables.items():
try:
changed = process_table(inst["iz"], inst["apikey"], api_base,
table_name, canonical, args.apply)
if changed:
changed_count += 1
except Exception as e:
print(f" UNEXPECTED ERROR for {inst['iz']} {table_name}: {e}")
error_count += 1
# Brief pause between institutions to be kind to the API
if len(institutions) > 1:
time.sleep(0.5)
print(f"\n{'='*60}")
print(f"Done. {changed_count} table(s) with changes, {error_count} error(s).")
if not args.apply and changed_count > 0:
print("Re-run with --apply to commit changes to Alma.")
if __name__ == "__main__":
main()