-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoclc_record_matcher.py
More file actions
1508 lines (1254 loc) · 64.3 KB
/
oclc_record_matcher.py
File metadata and controls
1508 lines (1254 loc) · 64.3 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 an Excel file, searches the WorldCat Metadata API
for matching records, and adds the OCLC numbers to a new column in the spreadsheet.
Features:
- 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
- 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 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 Excel file processing."""
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):
"""
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)
"""
# 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'))
# 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
}
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 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']}")
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:
# Check for LCSH subjects by fetching full record from /bibs endpoint
has_lcsh = self._check_lcsh_in_bib_record(oclc_number)
# 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')
# Check for LCSH subjects by fetching full record from /bibs endpoint
has_lcsh = self._check_lcsh_in_bib_record(oclc_number) if oclc_number else 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:
"""
Get the appropriate itemType for formats that don't support itemSubType.
Args:
format_type: Format type from Excel file
Returns:
Corresponding itemType parameter for OCLC API
"""
if not format_type:
return 'book' # Default fallback
# Normalize format type
normalized_format = str(format_type).strip().lower()
# Map formats to their appropriate itemType
item_type_mapping = {
'video': 'video',
'video-recording': 'video',
'motion-picture': 'video',
'film': 'video',
'dvd': 'video',
'blu-ray': 'video',
'audiobook': 'audiobook',
'audio-book': 'audiobook',
'audio': 'audiobook',
'sound-recording': 'audiobook',
'spoken-word': 'audiobook',
'music': 'music',
'musical-recording': 'music',
'sound-recording-music': 'music',
'cd': 'music',
'vinyl': 'music',
'record': 'music',
'compfile': 'compfile',
'computer-file': 'compfile',
'computer': 'compfile',
'game': 'game',
'computer-game': 'game',
'video-game': 'game',
'print': 'book',
'hardcover': 'book',
'paperback': 'book'
}
# Direct lookup first
if normalized_format in item_type_mapping:
return item_type_mapping[normalized_format]
# Partial matching for variations
for key, item_type in item_type_mapping.items():
if key in normalized_format or normalized_format in key:
return item_type
# Fallback based on common patterns
if any(term in normalized_format for term in ['video', 'film', 'movie', 'dvd', 'blu-ray']):
return 'video'
elif any(term in normalized_format for term in ['audio', 'sound', 'spoken', 'audiobook']):
return 'audiobook'
elif any(term in normalized_format for term in ['music', 'song', 'album', 'cd', 'vinyl']):
return 'music'
elif any(term in normalized_format for term in ['game', 'computer-game', 'video-game']):
return 'game'
elif any(term in normalized_format for term in ['computer', 'compfile', 'software', 'program']):
return 'compfile'
elif any(term in normalized_format for term in ['book', 'print', 'hardcover', 'paperback']):
return 'book'
# Final fallback
return 'book'
def find_format_column(self, worksheet) -> Optional[int]:
"""
Find the format column in the worksheet.
Args:
worksheet: OpenPyXL worksheet object
Returns:
Column index of format column, or None if not found
"""
# Look for common format column names (case-insensitive matching)
format_column_names = [
'Format', 'Format Type', 'Type'
]
# Normalize to lowercase for case-insensitive comparison
format_column_names_lower = {name.lower() for name in format_column_names}
# Check the first row for column headers
for col in range(1, worksheet.max_column + 1):
cell_value = worksheet.cell(row=1, column=col).value
if cell_value:
cell_value_str = str(cell_value).strip()
if cell_value_str.lower() in format_column_names_lower:
logger.info(f"Found format column: {cell_value} at column {col}")
return col
logger.warning("No format column found - will use default itemSubType")
return None
def find_description_column(self, worksheet) -> Optional[int]:
"""
Find the description column in the worksheet.
Args:
worksheet: OpenPyXL worksheet object
Returns:
Column index of description column, or None if not found
"""
# Look for common description column names (case-insensitive matching)
description_column_names = [
'Description', 'Physical Description', 'PhysicalDesc', 'Desc'
]
# Normalize to lowercase for case-insensitive comparison
description_column_names_lower = {name.lower() for name in description_column_names}
# Check the first row for column headers
for col in range(1, worksheet.max_column + 1):
cell_value = worksheet.cell(row=1, column=col).value
if cell_value:
cell_value_str = str(cell_value).strip()
if cell_value_str.lower() in description_column_names_lower:
logger.info(f"Found description column: {cell_value} at column {col}")
return col
logger.debug("No description column found")
return None
def determine_final_format(self, format_value: str, description_value: str = None) -> str:
"""
Determine the final format to use, checking description field last.
If description contains 'computer' and 'game', set format to 'game'.
If description contains 'computer' (but not 'game'), set format to 'compfile'.
If description contains 'audio media player', set format to None.
Args:
format_value: Format value from format column
description_value: Description value from description column
Returns:
Final format to use for API calls, or None if audio media player
"""
# First, use the format value if available
if format_value and str(format_value).strip():
format_str = str(format_value).strip()
else:
format_str = None
# Check description field last for specific overrides
if description_value and str(description_value).strip():
description_str = str(description_value).strip().lower()
# Check for computer + game combination first (more specific)
if 'computer' in description_str and 'game' in description_str:
logger.info(f"Description contains 'computer' and 'game', setting format to 'game' (was: {format_str})")
return 'game'
elif 'computer' in description_str:
logger.info(f"Description contains 'computer', setting format to 'compfile' (was: {format_str})")
return 'compfile'
elif 'audio media player' in description_str:
logger.info(f"Description contains 'audio media player', setting format to None (was: {format_str})")
return None
# Return the original format value or default
return format_str if format_str else 'book-digital'
def find_column_by_name(self, worksheet, column_names: list) -> Optional[int]:
"""
Find a column by name in the worksheet (case-insensitive matching).
Args:
worksheet: OpenPyXL worksheet object
column_names: List of possible column names to search for
Returns:
Column index of the column, or None if not found
"""
# Normalize to lowercase for case-insensitive comparison
column_names_lower = {name.lower() if isinstance(name, str) else str(name).lower() for name in column_names}
for col in range(1, worksheet.max_column + 1):
cell_value = worksheet.cell(row=1, column=col).value
if cell_value:
cell_value_str = str(cell_value).strip()
if cell_value_str.lower() in column_names_lower:
logger.debug(f"Found column: {cell_value} at column {col}")
return col
return None
def find_isbn_columns(self, worksheet) -> List[Tuple[int, str]]:
"""
Find all columns containing ISBNs by checking if column name contains "ISBN"
(case-insensitive substring matching).
Args:
worksheet: OpenPyXL worksheet object
Returns:
List of tuples (column_index, column_name) containing ISBNs
"""
isbn_columns = []
# Check the first row for column headers
for col in range(1, worksheet.max_column + 1):
cell_value = worksheet.cell(row=1, column=col).value
if cell_value:
cell_value_str = str(cell_value).strip()
# Check if column name contains "ISBN" (case-insensitive)
if 'isbn' in cell_value_str.lower():
isbn_columns.append((col, cell_value_str))
logger.info(f"Found ISBN column: {cell_value} at column {col}")
if not isbn_columns:
logger.warning("No ISBN column headers found")
return isbn_columns
def create_backup(self, input_file: str) -> str:
"""Create a backup of the input file."""
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_file = f"{input_file}.backup_{timestamp}"
shutil.copy2(input_file, backup_file)
logger.info(f"Created backup: {backup_file}")
return backup_file
def process_excel_file(self, input_file: str, output_file: str, create_backup: bool = True):
"""
Process Excel file to add OCLC numbers using OR queries for ISBNs from the same row.
Args:
input_file: Path to input Excel file
output_file: Path to output Excel file
create_backup: Whether to create a backup of the input file
"""
try:
# Create backup if requested