-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoclc_record_matcher.py
More file actions
1917 lines (1617 loc) · 78.9 KB
/
oclc_record_matcher.py
File metadata and controls
1917 lines (1617 loc) · 78.9 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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# Copyright 2024
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
OCLC ISBN Matcher - WorldCat Metadata API Version
This script reads ISBNs from a spreadsheet (Excel, CSV, or TSV), searches the
WorldCat Metadata API for matching records, and adds the OCLC numbers to a new
column in the output Excel file (unless you request MARCXML-only output).
Features:
- Accepts Excel (.xlsx/.xls), UTF-8 CSV, UTF-8 TSV, or MARC (.mrc/.marc) input
- Handles multiple ISBN columns (XML ISBN, HC ISBN, PB ISBN, ePub ISBN, ePDF ISBN)
- Maps format types to appropriate itemSubType parameters for API calls
- Searches WorldCat Metadata API with OAuth 2.0 authentication
- Optional LCSH detection: off by default; pass ``--lcsh`` to call GET /worldcat/bibs/{id} after each match
- Optional: write only combined MARCXML (no Excel) when ``--marcxml-output`` is set without ``-o``
- Adds rate limiting and error handling
- Provides detailed logging and progress tracking
- Creates backup of original file
- Uses environment variables for secure credential management
"""
import openpyxl
import csv
import re
import requests
from requests_oauthlib import OAuth2Session
from oauthlib.oauth2 import BackendApplicationClient
import time
import logging
import shutil
import argparse
from datetime import datetime
from typing import Optional, Dict, Any, List, Tuple
import sys
from pathlib import Path
import os
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('oclc_matcher.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
class OCLCISBNMatcher:
"""Class to handle WorldCat Metadata API searches and tabular input (Excel, CSV, TSV)."""
def __init__(self, base_url: Optional[str] = None,
api_key: Optional[str] = None,
api_secret: Optional[str] = None,
oauth_token_url: Optional[str] = None,
api_logging: Optional[bool] = None,
timeout: Optional[int] = None,
rate_limit_delay: Optional[float] = None,
check_lcsh: bool = False):
"""
Initialize the OCLC ISBN Matcher with WorldCat Metadata API.
Args:
base_url: Base URL for the WorldCat Metadata API (defaults to env var or production URL)
api_key: OCLC API key (defaults to OCLC_API_KEY env var)
api_secret: OCLC API secret (defaults to OCLC_API_SECRET env var)
oauth_token_url: OAuth token URL (defaults to OCLC_OAUTH_TOKEN_URL env var or default)
api_logging: Whether to enable detailed API request/response logging (defaults to env var)
timeout: Request timeout in seconds (defaults to API_TIMEOUT env var or 30)
rate_limit_delay: Delay between requests in seconds (defaults to API_RATE_LIMIT_DELAY env var or 0.5)
check_lcsh: If True, call GET /worldcat/bibs/{id} to detect LCSH after a match.
Default False (no extra bib requests); use CLI ``--lcsh`` to enable.
"""
# Load configuration from environment variables
self.base_url = base_url or os.getenv('OCLC_API_BASE_URL', 'https://metadata.api.oclc.org')
self.api_key = api_key or os.getenv('OCLC_API_KEY')
self.api_secret = api_secret or os.getenv('OCLC_API_SECRET')
self.oauth_token_url = oauth_token_url or os.getenv('OCLC_OAUTH_TOKEN_URL', 'https://oauth.oclc.org/token')
self.api_logging = api_logging if api_logging is not None else os.getenv('API_LOGGING', 'true').lower() == 'true'
self.timeout = timeout or int(os.getenv('API_TIMEOUT', '30'))
self.rate_limit_delay = rate_limit_delay or float(os.getenv('API_RATE_LIMIT_DELAY', '0.5'))
self.check_lcsh = check_lcsh
# Validate required credentials
if not self.api_key or not self.api_secret:
raise ValueError(
"OCLC API credentials are required. "
"Set OCLC_API_KEY and OCLC_API_SECRET environment variables "
"or provide them as arguments. See .env.example for details."
)
# Initialize OAuth 2.0 client credentials flow
self.client = BackendApplicationClient(client_id=self.api_key)
self.oauth = OAuth2Session(client=self.client)
# Get access token
self._refresh_access_token()
# Statistics tracking
self.stats = {
'total_processed': 0,
'successful_matches': 0,
'api_errors': 0,
'empty_isbns': 0,
'no_matches': 0,
'lcsh_found': 0,
'lcsh_not_found': 0,
'api_requests': 0,
'api_responses': 0,
'marcxml_manage_fetches': 0,
'marcxml_manage_failures': 0,
}
self._marcxml_oclc_order: List[str] = []
def _refresh_access_token(self):
"""
Refresh the OAuth 2.0 access token using client credentials flow.
"""
try:
# OCLC OAuth requires Basic Auth with client_id:client_secret
# and grant_type=client_credentials in the body
import base64
auth_string = f"{self.api_key}:{self.api_secret}"
auth_bytes = auth_string.encode('ascii')
auth_b64 = base64.b64encode(auth_bytes).decode('ascii')
headers = {
'Authorization': f'Basic {auth_b64}',
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'
}
data = {
'grant_type': 'client_credentials',
'scope': 'WorldCatMetadataAPI'
}
if self.api_logging:
logger.info(f"OAuth Token Request - URL: {self.oauth_token_url}")
logger.info(f"OAuth Token Request - Headers: {dict(headers)}")
logger.info(f"OAuth Token Request - Data: {data}")
response = requests.post(
self.oauth_token_url,
headers=headers,
data=data,
timeout=self.timeout
)
if self.api_logging:
logger.info(f"OAuth Token Response - Status: {response.status_code}")
logger.info(f"OAuth Token Response - Headers: {dict(response.headers)}")
logger.info(f"OAuth Token Response - Body: {response.text[:500]}")
response.raise_for_status()
token_data = response.json()
# Check if access_token is in the response
if 'access_token' not in token_data:
logger.error(f"OAuth response missing access_token. Full response: {token_data}")
raise ValueError(
f"OAuth response missing access_token. Response keys: {list(token_data.keys())}"
)
self.access_token = token_data['access_token']
if not self.access_token:
logger.error(f"OAuth response has empty access_token. Full response: {token_data}")
raise ValueError("OAuth response has empty access_token")
logger.info("Successfully obtained OAuth access token")
# Log token expiration if available
if 'expires_in' in token_data:
logger.debug(f"Token expires in {token_data['expires_in']} seconds")
except requests.exceptions.RequestException as e:
logger.error(f"HTTP error during OAuth token request: {e}")
if hasattr(e, 'response') and e.response is not None:
logger.error(f"Response status: {e.response.status_code}")
logger.error(f"Response headers: {dict(e.response.headers)}")
try:
error_body = e.response.text
logger.error(f"Response body: {error_body[:500]}")
except:
logger.error("Could not read response body")
raise ValueError(f"Authentication failed: {e}")
except Exception as e:
logger.error(f"Failed to obtain OAuth access token: {e}")
logger.error(f"Exception type: {type(e).__name__}")
import traceback
logger.error(f"Traceback: {traceback.format_exc()}")
raise ValueError(f"Authentication failed: {e}")
def _get_headers(self) -> Dict[str, str]:
"""
Get headers for API requests including OAuth token.
Returns:
Dictionary of HTTP headers
"""
return {
'Accept': 'application/json',
'Authorization': f'Bearer {self.access_token}'
}
def _get_marcxml_headers(self) -> Dict[str, str]:
"""HTTP headers for MARCXML responses from the manage bibs endpoint."""
return {
'Accept': 'application/marcxml+xml',
'Authorization': f'Bearer {self.access_token}',
}
@staticmethod
def _normalize_oclc_number_for_api(value: Any) -> Optional[str]:
"""Return a numeric OCLC identifier string suitable for URL paths, or None."""
if value is None or isinstance(value, bool):
return None
if isinstance(value, int):
return str(value)
if isinstance(value, float):
if value != value: # NaN
return None
rounded = round(value)
if abs(value - rounded) < 1e-9:
return str(int(rounded))
return None
s = str(value).strip()
if not s:
return None
upper = s.upper()
if upper.startswith('OCN'):
s = s[3:].strip()
elif upper.startswith('OCM'):
s = s[3:].strip()
if re.fullmatch(r'\d+', s):
return s
return None
def _register_oclc_for_marcxml_export(self, oclc_number: Any) -> None:
"""Remember an OCLC number written to the sheet for optional MARCXML export."""
sid = self._normalize_oclc_number_for_api(oclc_number)
if sid:
self._marcxml_oclc_order.append(sid)
@staticmethod
def _strip_xml_declaration(xml_text: str) -> str:
"""Remove XML declaration so fragments can be wrapped in a collection."""
t = xml_text.strip()
if t.startswith('<?xml'):
end = t.find('?>')
if end != -1:
return t[end + 2 :].strip()
return t
@staticmethod
def _combine_marcxml_record_bodies(record_bodies: List[str]) -> str:
"""
Wrap stripped MARCXML record fragments in a single MARC21 slim collection.
Args:
record_bodies: Pieces of XML each containing one ``record`` element
Returns:
Full MARCXML document as a UTF-8 string.
"""
lines = [
'<?xml version="1.0" encoding="UTF-8"?>',
'<collection xmlns="http://www.loc.gov/MARC21/slim">',
]
for body in record_bodies:
lines.append(OCLCISBNMatcher._strip_xml_declaration(body))
lines.append('</collection>')
return '\n'.join(lines) + '\n'
def fetch_manage_bib_marcxml(self, oclc_number: str) -> Optional[str]:
"""
Retrieve one bibliographic record as MARCXML from the manage bibs API.
Uses ``GET /worldcat/manage/bibs/{oclcNumber}`` with
``Accept: application/marcxml+xml`` per the WorldCat Metadata API spec.
Requires credentials with ``WorldCatMetadataAPI:manage_bibs`` or
``WorldCatMetadataAPI:view_marc_bib`` on the key.
Args:
oclc_number: OCLC control number
Returns:
Response body (MARCXML), or None if the record is missing or on error.
"""
oclc_id = self._normalize_oclc_number_for_api(oclc_number)
if not oclc_id:
logger.warning('Skipping MARCXML fetch: invalid OCLC number %r', oclc_number)
return None
url = f'{self.base_url}/worldcat/manage/bibs/{oclc_id}'
headers = self._get_marcxml_headers()
if self.api_logging:
logger.info('API Request - Manage Bib MARCXML read')
logger.info(' URL: %s', url)
logger.info(' Headers: %s', headers)
try:
self.stats['api_requests'] += 1
response = requests.get(url, headers=headers, timeout=self.timeout)
if response.status_code == 401:
logger.warning(
'Received 401 Unauthorized on manage bib read, refreshing access token...'
)
self._refresh_access_token()
headers = self._get_marcxml_headers()
response = requests.get(url, headers=headers, timeout=self.timeout)
if self.api_logging:
logger.info('API Response - Manage Bib MARCXML read')
logger.info(' Status Code: %s', response.status_code)
logger.info(' Response Headers: %s', dict(response.headers))
self.stats['api_responses'] += 1
if response.status_code == 404:
logger.warning('No MARCXML for OCLC %s (HTTP 404)', oclc_id)
self.stats['marcxml_manage_failures'] += 1
return None
response.raise_for_status()
body = response.text
if not body or not body.strip():
logger.warning('Empty MARCXML body for OCLC %s', oclc_id)
self.stats['marcxml_manage_failures'] += 1
return None
ct = (response.headers.get('Content-Type') or '').lower()
if 'json' in ct:
logger.error(
'Unexpected JSON from manage bib read for OCLC %s: %s',
oclc_id,
body[:500],
)
self.stats['api_errors'] += 1
self.stats['marcxml_manage_failures'] += 1
return None
self.stats['marcxml_manage_fetches'] += 1
return body
except requests.exceptions.RequestException as exc:
logger.error('Manage bib MARCXML request failed for OCLC %s: %s', oclc_id, exc)
if getattr(exc, 'response', None) is not None:
resp = exc.response
logger.error(' Status: %s', resp.status_code)
try:
err = resp.text
if len(err) > 500:
err = err[:500] + '... [truncated]'
logger.error(' Body: %s', err)
except OSError:
pass
self.stats['api_errors'] += 1
self.stats['marcxml_manage_failures'] += 1
return None
def download_matched_bibs_marcxml(self, output_path: str) -> int:
"""
Download MARCXML for each distinct matched OCLC number and save one file.
Order follows first appearance in the processed spreadsheet. Each bib is
fetched with ``GET /worldcat/manage/bibs/{oclcNumber}``; results are
combined under a single ``collection`` root (MARC21 slim namespace).
Args:
output_path: Path to write the combined ``.xml`` file (UTF-8).
Returns:
Number of records successfully included in the output file.
"""
seen: set = set()
unique_ids: List[str] = []
for raw in self._marcxml_oclc_order:
sid = self._normalize_oclc_number_for_api(raw)
if not sid or sid in seen:
continue
seen.add(sid)
unique_ids.append(sid)
if not unique_ids:
logger.info('No matched OCLC numbers to download for MARCXML export.')
return 0
logger.info(
'Downloading MARCXML for %s distinct OCLC number(s) via manage bibs...',
len(unique_ids),
)
bodies: List[str] = []
for oclc_id in unique_ids:
fragment = self.fetch_manage_bib_marcxml(oclc_id)
if fragment:
bodies.append(fragment)
time.sleep(self.rate_limit_delay)
if not bodies:
logger.warning('MARCXML export skipped: no records retrieved.')
return 0
combined = self._combine_marcxml_record_bodies(bodies)
out = Path(output_path)
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(combined, encoding='utf-8')
logger.info('Wrote combined MARCXML (%s records) to %s', len(bodies), out)
return len(bodies)
def print_api_statistics(self):
"""Print API usage statistics."""
logger.info("=" * 60)
logger.info("API USAGE STATISTICS")
logger.info("=" * 60)
logger.info(f"Total API Requests: {self.stats['api_requests']}")
logger.info(f"Total API Responses: {self.stats['api_responses']}")
logger.info(f"API Errors: {self.stats['api_errors']}")
logger.info(
"Manage-bib MARCXML fetches (successful): %s",
self.stats['marcxml_manage_fetches'],
)
logger.info(
"Manage-bib MARCXML failures: %s",
self.stats['marcxml_manage_failures'],
)
if self.stats['api_requests'] > 0:
success_rate = ((self.stats['api_requests'] - self.stats['api_errors']) / self.stats['api_requests']) * 100
logger.info(f"API Success Rate: {success_rate:.1f}%")
logger.info("=" * 60)
def search_by_isbns(self, isbns: list, format_type: str = None) -> dict:
"""
Search OCLC API for records by multiple ISBNs using OR query.
Args:
isbns: List of ISBNs to search for
format_type: Format type to map to itemSubType parameter
Returns:
Dictionary mapping ISBN to OCLC number (if found)
"""
try:
# Clean and validate ISBNs
clean_isbns = []
isbn_mapping = {} # Maps clean ISBN back to original
for isbn in isbns:
if not isbn or str(isbn).strip() == '':
continue
clean_isbn = str(isbn).replace('-', '').replace(' ', '').strip()
# Validate ISBN length (should be 10 or 13 digits)
if not clean_isbn.isdigit() or len(clean_isbn) not in [10, 13]:
logger.warning(f"Invalid ISBN format: {isbn}")
continue
clean_isbns.append(clean_isbn)
isbn_mapping[clean_isbn] = isbn
if not clean_isbns:
logger.warning("No valid ISBNs provided")
return {}
# Construct OR query for multiple ISBNs
query_parts = [f"bn:{isbn}" for isbn in clean_isbns]
query = " OR ".join(query_parts)
# API endpoint for WorldCat Metadata API search (using brief-bibs endpoint)
url = f"{self.base_url}/worldcat/search/brief-bibs"
# Determine whether to use itemType or itemSubType based on format
if format_type is None:
# No format specified, don't send itemType or itemSubType
params = {
'q': query,
'groupRelatedEditions': 'true',
'inCatalogLanguage': 'eng',
'orderBy': 'mostWidelyHeld',
'limit': 1 # Only need one result since all ISBNs are for the same work
}
elif self._should_use_item_type(format_type):
# Use itemType parameter for formats that don't support itemSubType
item_type = self._get_item_type_for_format(format_type)
params = {
'q': query,
'groupRelatedEditions': 'true',
'inCatalogLanguage': 'eng',
'orderBy': 'mostWidelyHeld',
'itemType': item_type,
'limit': 1 # Only need one result since all ISBNs are for the same work
}
else:
# Use itemSubType parameter for supported formats
item_sub_type = self._map_format_to_item_sub_type(format_type)
params = {
'q': query,
'groupRelatedEditions': 'true',
'inCatalogLanguage': 'eng',
'orderBy': 'mostWidelyHeld',
'itemSubType': item_sub_type,
'limit': 1 # Only need one result since all ISBNs are for the same work
}
# Get headers with OAuth token
headers = self._get_headers()
# Log API request details
if self.api_logging:
logger.info(f"API Request - ISBN Search")
logger.info(f" URL: {url}")
logger.info(f" Query: {query}")
logger.info(f" Parameters: {params}")
logger.info(f" Headers: {headers}")
self.stats['api_requests'] += 1
response = requests.get(url, params=params, headers=headers, timeout=self.timeout)
# Handle 401 Unauthorized - token may have expired
if response.status_code == 401:
logger.warning("Received 401 Unauthorized, refreshing access token...")
self._refresh_access_token()
headers = self._get_headers()
response = requests.get(url, params=params, headers=headers, timeout=self.timeout)
# Log response details
if self.api_logging:
logger.info(f"API Response - ISBN Search")
logger.info(f" Status Code: {response.status_code}")
logger.info(f" Response Headers: {dict(response.headers)}")
logger.info(f" Response Size: {len(response.content)} bytes")
self.stats['api_responses'] += 1
response.raise_for_status()
data = response.json()
# Log response content (truncated for large responses)
if self.api_logging:
response_content = str(data)
if len(response_content) > 1000:
response_content = response_content[:1000] + "... [truncated]"
logger.info(f" Response Content: {response_content}")
# Process results and map back to original ISBNs
# brief-bibs endpoint returns 'briefRecords' array, not 'bibRecords'
results = {}
brief_records = data.get('briefRecords', [])
if brief_records:
brief_record = brief_records[0]
# Extract OCLC number directly from brief record (not nested in identifier)
oclc_number = brief_record.get('oclcNumber')
if oclc_number:
if self.check_lcsh:
has_lcsh = self._check_lcsh_in_bib_record(oclc_number)
else:
has_lcsh = None
# Since all ISBNs in the query are for the same work,
# we can associate the found OCLC number and LCSH status with all of them
for original_isbn in isbns:
results[original_isbn] = {
'oclc_number': oclc_number,
'has_lcsh': has_lcsh
}
logger.debug(f"Found OCLC number: {oclc_number} with LCSH: {has_lcsh}")
logger.debug(f"Found {len(results)} matches out of {len(clean_isbns)} ISBNs")
return results
except requests.exceptions.RequestException as e:
logger.error(f"API request failed for ISBNs {isbns}: {e}")
if hasattr(e, 'response') and e.response is not None:
logger.error(f" Response Status: {e.response.status_code}")
logger.error(f" Response Headers: {dict(e.response.headers)}")
try:
error_content = e.response.text
if len(error_content) > 500:
error_content = error_content[:500] + "... [truncated]"
logger.error(f" Response Content: {error_content}")
except:
logger.error(f" Could not read response content")
self.stats['api_errors'] += 1
return {}
except Exception as e:
logger.error(f"Unexpected error searching for ISBNs {isbns}: {e}")
return {}
def search_by_title_author_publisher(self, title: str, author: str, publisher: str,
publication_date: str, format_type: str = None, other_identifier: str = None) -> dict:
"""
Search OCLC Discovery API using title, author, publisher, and other identifier when no ISBN is available.
First tries with publication date, then retries without date if no results found.
Args:
title: Book title
author: Author name
publisher: Publisher name
publication_date: Publication date (YYYY format)
format_type: Format type to map to itemSubType parameter
other_identifier: Other identifier (e.g., from MARC 024$a)
Returns:
Dictionary with search results
"""
# Build search query components
query_parts = []
if title and str(title).strip():
# Escape special characters for title search
clean_title = str(title).strip().replace('"', '\\"')
query_parts.append(f'te:{clean_title}')
if author and str(author).strip():
# Escape special characters and wrap in quotes for exact phrase matching
clean_author = str(author).strip().replace('"', '\\"')
query_parts.append(f'au:"{clean_author}"')
if publisher and str(publisher).strip():
# Escape special characters and wrap in quotes for exact phrase matching
clean_publisher = str(publisher).strip().replace('"', '\\"')
query_parts.append(f'pb:"{clean_publisher}"')
if other_identifier and str(other_identifier).strip():
# Escape special characters and wrap in quotes for exact phrase matching
clean_other_id = str(other_identifier).strip().replace('"', '\\"')
query_parts.append(f'sn:"{clean_other_id}"')
if not query_parts:
logger.warning("No searchable fields provided (title, author, publisher, other identifier)")
return {'oclc_number': None, 'has_lcsh': False}
# Join with AND operators
query = " AND ".join(query_parts)
logger.debug(f"Searching by title/author/publisher with query: {query}")
# Try search with publication date first, then without if no results
search_attempts = []
# First attempt: with publication date (if available)
if publication_date and str(publication_date).strip():
import re
year_match = re.search(r'\b(19|20)\d{2}\b', str(publication_date))
if year_match:
search_attempts.append(('with date', year_match.group()))
# Second attempt: without publication date
search_attempts.append(('without date', None))
for attempt_name, date_value in search_attempts:
try:
# Determine whether to use itemType or itemSubType based on format
if format_type is None:
# No format specified, don't send itemType or itemSubType
params = {
'q': query,
'groupRelatedEditions': 'true',
'inCatalogLanguage': 'eng',
'orderBy': 'mostWidelyHeld',
'limit': 1
}
elif self._should_use_item_type(format_type):
# Use itemType parameter for formats that don't support itemSubType
item_type = self._get_item_type_for_format(format_type)
params = {
'q': query,
'groupRelatedEditions': 'true',
'inCatalogLanguage': 'eng',
'orderBy': 'mostWidelyHeld',
'itemType': item_type,
'limit': 1
}
else:
# Use itemSubType parameter for supported formats
item_sub_type = self._map_format_to_item_sub_type(format_type)
params = {
'q': query,
'groupRelatedEditions': 'true',
'inCatalogLanguage': 'eng',
'orderBy': 'mostWidelyHeld',
'itemSubType': item_sub_type,
'limit': 1
}
# Add publication date if available for this attempt
if date_value:
params['datePublished'] = date_value
logger.debug(f"Added datePublished parameter: {params['datePublished']}")
# Get headers with OAuth token
headers = self._get_headers()
# Log API request details
# API endpoint for WorldCat Metadata API search (using brief-bibs endpoint)
url = f"{self.base_url}/worldcat/search/brief-bibs"
if self.api_logging:
logger.info(f"API Request - Alternative Search ({attempt_name})")
logger.info(f" URL: {url}")
logger.info(f" Query: {query}")
logger.info(f" Parameters: {params}")
logger.info(f" Headers: {headers}")
self.stats['api_requests'] += 1
response = requests.get(url, params=params, headers=headers, timeout=self.timeout)
# Handle 401 Unauthorized - token may have expired
if response.status_code == 401:
logger.warning("Received 401 Unauthorized, refreshing access token...")
self._refresh_access_token()
headers = self._get_headers()
response = requests.get(url, params=params, headers=headers, timeout=self.timeout)
# Log response details
if self.api_logging:
logger.info(f"API Response - Alternative Search ({attempt_name})")
logger.info(f" Status Code: {response.status_code}")
logger.info(f" Response Headers: {dict(response.headers)}")
logger.info(f" Response Size: {len(response.content)} bytes")
self.stats['api_responses'] += 1
response.raise_for_status()
data = response.json()
# Log response content (truncated for large responses)
if self.api_logging:
response_content = str(data)
if len(response_content) > 1000:
response_content = response_content[:1000] + "... [truncated]"
logger.info(f" Response Content: {response_content}")
# Process results
# brief-bibs endpoint returns 'briefRecords' array, not 'bibRecords'
brief_records = data.get('briefRecords', [])
if brief_records:
brief_record = brief_records[0] # Get first result
# Extract OCLC number directly from brief record (not nested in identifier)
oclc_number = brief_record.get('oclcNumber')
if oclc_number:
has_lcsh = (
self._check_lcsh_in_bib_record(oclc_number)
if self.check_lcsh
else None
)
else:
has_lcsh = False
logger.debug(f"Found match {attempt_name}: OCLC {oclc_number}, LCSH: {has_lcsh}")
return {
'oclc_number': oclc_number,
'has_lcsh': has_lcsh
}
else:
logger.debug(f"No results found for title/author/publisher search {attempt_name}")
# Continue to next attempt if this one had no results
continue
except requests.exceptions.RequestException as e:
logger.error(f"API request failed for title/author/publisher search ({attempt_name}): {e}")
if hasattr(e, 'response') and e.response is not None:
logger.error(f" Response Status: {e.response.status_code}")
logger.error(f" Response Headers: {dict(e.response.headers)}")
try:
error_content = e.response.text
if len(error_content) > 500:
error_content = error_content[:500] + "... [truncated]"
logger.error(f" Response Content: {error_content}")
except:
logger.error(f" Could not read response content")
self.stats['api_errors'] += 1
# Continue to next attempt on API error
continue
except Exception as e:
logger.error(f"Unexpected error in title/author/publisher search ({attempt_name}): {e}")
# Continue to next attempt on unexpected error
continue
# If we get here, no attempts succeeded
logger.debug("No results found for title/author/publisher search after all attempts")
return {
'oclc_number': None,
'has_lcsh': False
}
def _check_lcsh_in_bib_record(self, oclc_number: str) -> bool:
"""
Check if a bib record contains Library of Congress Subject Headings (LCSH).
Fetches the full bibliographic record from the /bibs endpoint to check for LCSH.
Args:
oclc_number: OCLC number of the record to check
Returns:
True if the record contains LCSH subjects, False otherwise
"""
if not oclc_number:
logger.debug("No OCLC number provided for LCSH check")
return False
try:
# Fetch full bibliographic record from /bibs endpoint
url = f"{self.base_url}/worldcat/bibs/{oclc_number}"
headers = self._get_headers()
if self.api_logging:
logger.info(f"API Request - Fetch Full Bib for LCSH Check")
logger.info(f" URL: {url}")
logger.info(f" Headers: {headers}")
self.stats['api_requests'] += 1
response = requests.get(url, headers=headers, timeout=self.timeout)
# Handle 401 Unauthorized - token may have expired
if response.status_code == 401:
logger.warning("Received 401 Unauthorized while fetching full bib, refreshing access token...")
self._refresh_access_token()
headers = self._get_headers()
response = requests.get(url, headers=headers, timeout=self.timeout)
if self.api_logging:
logger.info(f"API Response - Fetch Full Bib for LCSH Check")
logger.info(f" Status Code: {response.status_code}")
logger.info(f" Response Headers: {dict(response.headers)}")
logger.info(f" Response Size: {len(response.content)} bytes")
self.stats['api_responses'] += 1
# If record not found or other error, return False
if response.status_code == 404:
logger.debug(f"Record {oclc_number} not found for LCSH check")
return False
response.raise_for_status()
bib_record = response.json()
# Log response content (truncated for large responses)
if self.api_logging:
response_content = str(bib_record)
if len(response_content) > 1000:
response_content = response_content[:1000] + "... [truncated]"
logger.info(f" Response Content: {response_content}")
# Check for LCSH subjects in the full record
subjects = bib_record.get('subjects', [])
# Check if any subject has LCSH vocabulary
for subject in subjects:
vocabulary = subject.get('vocabulary', '')
if vocabulary and 'LIBRARY OF CONGRESS SUBJECT HEADINGS' in vocabulary.upper():
logger.debug(f"Found LCSH subject: {vocabulary}")
return True
logger.debug(f"No LCSH subjects found in record {oclc_number}")
return False
except requests.exceptions.RequestException as e:
logger.error(f"API request failed while checking LCSH for OCLC {oclc_number}: {e}")
if hasattr(e, 'response') and e.response is not None:
logger.error(f" Response Status: {e.response.status_code}")
logger.error(f" Response Headers: {dict(e.response.headers)}")
try:
error_content = e.response.text
if len(error_content) > 500:
error_content = error_content[:500] + "... [truncated]"
logger.error(f" Response Content: {error_content}")
except:
logger.error(f" Could not read response content")
# Return False on error rather than raising
return False
except Exception as e:
logger.error(f"Unexpected error checking LCSH in bib record {oclc_number}: {e}")
return False
def search_by_isbn(self, isbn: str) -> Optional[str]:
"""
Search OCLC API for a single ISBN (backward compatibility).
Args:
isbn: ISBN to search for
Returns:
OCLC number if found, None otherwise
"""
results = self.search_by_isbns([isbn])
result = results.get(isbn)
if result and isinstance(result, dict):
return result.get('oclc_number')
return result
def _map_format_to_item_sub_type(self, format_type: str) -> str:
"""
Map format type to OCLC itemSubType parameter.
Args:
format_type: Format type from Excel file
Returns:
Corresponding itemSubType parameter for OCLC API
"""
if not format_type:
return 'book-digital' # Default fallback
format_mapping = {
'book-print': 'book-printbook',
'book-digital': 'book-digital',
'book-largeprint': 'book-largeprint',
'print': 'book-printbook',
'hardcover': 'book-printbook',
'paperback': 'book-printbook',
'video': 'video',
'audiobook': 'audiobook',
'music': 'music'
}
# Normalize format type (remove extra spaces, convert to lowercase)
normalized_format = str(format_type).strip().lower()
return format_mapping.get(normalized_format, 'book-digital')
def _should_use_item_type(self, format_type: str) -> bool:
"""
Determine if the format should be sent as itemType parameter instead of itemSubType.
Based on API testing, only certain formats work with itemSubType:
- book-digital and book-largeprint work with itemSubType
- Other formats should use itemType parameter
Args:
format_type: Format type from Excel file
Returns:
True if should use itemType, False if should use itemSubType
"""
if not format_type:
return False # Default to itemSubType
# Normalize format type
normalized_format = str(format_type).strip().lower()
# Only book-digital, book-largeprint, and book-print work with itemSubType
item_sub_type_formats = {
'book-digital',
'book-largeprint',
'book-large-print',
'large-print',
'largeprint',
'book-print',
'print',
'hardcover',
'paperback',
'ebook',
'e-book',
'electronic',
'digital'
}
# Check if this format should use itemSubType
if normalized_format in item_sub_type_formats:
return False # Use itemSubType
# Check for partial matches
for format_key in item_sub_type_formats:
if format_key in normalized_format or normalized_format in format_key:
return False # Use itemSubType
# All other formats should use itemType
return True
def _get_item_type_for_format(self, format_type: str) -> str: