-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheck_doi_bib.py
More file actions
executable file
·1211 lines (1030 loc) · 39.6 KB
/
Copy pathcheck_doi_bib.py
File metadata and controls
executable file
·1211 lines (1030 loc) · 39.6 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
"""Deterministic DOI-vs-.bib title/author diff script.
Verifies that DOIs in a BibTeX (.bib) file resolve to works whose title and
authors match the .bib entry, rather than merely resolving.
A resolving DOI pointing to a different work is a signature of LLM citation
fabrication (see shared/writing/citations.md: "A resolving DOI is not a correct
DOI").
Features:
- Parses BibTeX entries (.bib) and extracts DOI, title, author, year fields.
- Optionally scopes verification to keys cited in LaTeX (.tex), Quarto (.qmd),
RMarkdown (.rmd), or Markdown (.md) source files (following \\input/\\include).
- Resolves DOIs via Crossref (https://api.crossref.org/works/<doi>),
falling back to OpenAlex on HTTP 429 / rate limits, and CSL-JSON for non-Crossref DOIs.
- Deterministically diffs resolved title and first author against the .bib entry
using fuzzy matching (tolerant of punctuation, subtitles, LaTeX markup, and accents).
- Reports MATCH (valid), MISMATCH (fabrication signature / defect), NOT_RESOLVED (defect),
UNVERIFIABLE (network failure), and NO_DOI / SKIPPED (informational).
- Emits human-readable summaries or machine-parseable JSON.
Exit codes:
0: All checked entries with DOIs resolved and matched (or only NO_DOI / SKIPPED).
1: One or more entries had MISMATCH or NOT_RESOLVED defects.
2: Usage error, missing files, or network failure when network is required.
"""
from __future__ import annotations
import argparse
import difflib
import json
import re
import sys
import unicodedata
import urllib.error
import urllib.parse
import urllib.request
from dataclasses import asdict, dataclass, field
from enum import Enum
from pathlib import Path
from typing import Any, Callable
# Default Crossref API polite pool identification
DEFAULT_USER_AGENT = (
"check-doi-bib/1.0 (https://github.com/Morrison-Lab/ai-config; mailto:ai-config@morrison-lab.org)"
)
class CheckStatus(str, Enum):
MATCH = "MATCH" # DOI resolves, metadata matches
MISMATCH = "MISMATCH" # DOI resolves, but title or author mismatch (fabrication signature)
NOT_RESOLVED = "NOT_RESOLVED" # DOI does not resolve (404 / invalid DOI)
UNVERIFIABLE = "UNVERIFIABLE" # Network error, timeout, or rate-limited without resolution
NO_DOI = "NO_DOI" # Entry contains no DOI field (informational)
SKIPPED = "SKIPPED" # Entry not cited in document (when scoped to cited keys)
@dataclass
class BibEntry:
key: str
entry_type: str
doi: str | None = None
title: str | None = None
author: str | None = None
year: str | None = None
journal: str | None = None
raw_fields: dict[str, str] = field(default_factory=dict)
@dataclass
class ResolvedMetadata:
doi: str
title: str | None = None
first_author_family: str | None = None
first_author_given: str | None = None
all_authors: list[str] = field(default_factory=list)
year: str | None = None
container_title: str | None = None
source: str = "crossref" # crossref, openalex, csl, mock
status: CheckStatus = CheckStatus.MATCH
error_message: str | None = None
@dataclass
class EntryCheckResult:
key: str
entry_type: str
doi: str | None
status: CheckStatus
bib_title: str | None = None
resolved_title: str | None = None
title_similarity: float = 0.0
title_match: bool = False
bib_first_author: str | None = None
resolved_first_author: str | None = None
author_similarity: float = 0.0
author_match: bool = False
bib_year: str | None = None
resolved_year: str | None = None
year_match: bool = True
resolver_source: str | None = None
message: str | None = None
@dataclass
class BibCheckSummary:
total_entries: int = 0
checked_count: int = 0
matches: int = 0
mismatches: int = 0
not_resolved: int = 0
unverifiable: int = 0
no_doi: int = 0
skipped: int = 0
results: list[EntryCheckResult] = field(default_factory=list)
@property
def has_defects(self) -> bool:
return self.mismatches > 0 or self.not_resolved > 0
# --- LaTeX / Text Normalization ---
_LATEX_ACCENTS = [
(re.compile(r'\\"[aA]'), "ä"),
(re.compile(r'\\"[eE]'), "ë"),
(re.compile(r'\\"[iI]'), "ï"),
(re.compile(r'\\"[oO]'), "ö"),
(re.compile(r'\\"[uU]'), "ü"),
(re.compile(r'\\"[yY]'), "ÿ"),
(re.compile(r"\\'[aA]"), "á"),
(re.compile(r"\\'[eE]"), "é"),
(re.compile(r"\\'[iI]"), "í"),
(re.compile(r"\\'[oO]"), "ó"),
(re.compile(r"\\'[uU]"), "ú"),
(re.compile(r"\\'[yY]"), "ý"),
(re.compile(r"\\`[aA]"), "à"),
(re.compile(r"\\`[eE]"), "è"),
(re.compile(r"\\`[iI]"), "ì"),
(re.compile(r"\\`[oO]"), "ò"),
(re.compile(r"\\`[uU]"), "ù"),
(re.compile(r"\\\^[aA]"), "â"),
(re.compile(r"\\\^[eE]"), "ê"),
(re.compile(r"\\\^[iI]"), "î"),
(re.compile(r"\\\^[oO]"), "ô"),
(re.compile(r"\\\^[uU]"), "û"),
(re.compile(r"\\~[aA]"), "ã"),
(re.compile(r"\\~[oO]"), "õ"),
(re.compile(r"\\~[nN]"), "ñ"),
(re.compile(r"\\c\{c\}"), "ç"),
(re.compile(r"\\c\{C\}"), "Ç"),
(re.compile(r"\\v\{s\}"), "š"),
(re.compile(r"\\v\{S\}"), "Š"),
(re.compile(r"\\v\{c\}"), "č"),
(re.compile(r"\\v\{C\}"), "Č"),
(re.compile(r"\\v\{z\}"), "ž"),
(re.compile(r"\\v\{Z\}"), "Ž"),
(re.compile(r"\\v\{([a-zA-Z])\}"), r"\1"),
(re.compile(r"\\u\{([a-zA-Z])\}"), r"\1"),
(re.compile(r"\\k\{([a-zA-Z])\}"), r"\1"),
(re.compile(r"\\r\{([a-zA-Z])\}"), r"\1"),
(re.compile(r"\\H\{([a-zA-Z])\}"), r"\1"),
(re.compile(r"\\l\b\s*"), "l"),
(re.compile(r"\\L\b\s*"), "L"),
(re.compile(r"\\o\b\s*"), "ø"),
(re.compile(r"\\O\b\s*"), "Ø"),
(re.compile(r"\\aa\b\s*"), "å"),
(re.compile(r"\\AA\b\s*"), "Å"),
(re.compile(r"\\ae\b\s*"), "æ"),
(re.compile(r"\\AE\b\s*"), "Æ"),
(re.compile(r"\\oe\b\s*"), "œ"),
(re.compile(r"\\OE\b\s*"), "Œ"),
(re.compile(r"\\ss\b\s*"), "ß"),
]
def clean_latex(text: str | None) -> str:
"""Unescape LaTeX accents, strip macros, and normalize LaTeX markup."""
if not text:
return ""
s = text.strip()
# Apply known LaTeX accent replacements
for pattern, replacement in _LATEX_ACCENTS:
s = pattern.sub(replacement, s)
# Strip command wrappers like \textbf{x}, \emph{x}, \enquote{x}, \mathrm{x}
s = re.sub(r"\\[a-zA-Z]+\{([^{}]*)\}", r"\1", s)
# Strip standalone commands like \LaTeX, \TeX
s = re.sub(r"\\[a-zA-Z]+", " ", s)
# Strip HTML/XML tags if any (e.g. <jats:p>, <i>, <b>)
s = re.sub(r"<[^>]+>", " ", s)
# Strip curly braces
s = s.replace("{", "").replace("}", "")
# Normalize whitespace
s = re.sub(r"\s+", " ", s).strip()
return s
def normalize_text_for_comparison(text: str | None) -> str:
"""Normalize text into ASCII lowercase alphanumeric tokens for robust comparison."""
if not text:
return ""
cleaned = clean_latex(text)
# Decompose unicode to separate base characters and diacritics
nfkd = unicodedata.normalize("NFKD", cleaned)
# Remove combining marks (diacritics)
no_accents = "".join(c for c in nfkd if not unicodedata.combining(c))
# Replace non-alphanumeric with space
alphanumeric = re.sub(r"[^a-zA-Z0-9]+", " ", no_accents).lower()
return re.sub(r"\s+", " ", alphanumeric).strip()
def normalize_doi(doi: str | None) -> str:
"""Normalize DOI string by stripping URL prefixes, resolver URLs, and whitespace."""
if not doi:
return ""
d = doi.strip()
d = re.sub(r"^https?://(?:dx\.)?doi\.org/", "", d, flags=re.IGNORECASE)
d = re.sub(r"^doi:\s*", "", d, flags=re.IGNORECASE)
return d.strip().strip("/")
def split_bibtex_authors(author_str: str) -> list[str]:
"""Split BibTeX author string by 'and' taking braces into account."""
s = author_str.strip()
# Strip outer redundant braces if wrapped around the entire author list
if s.startswith("{") and s.endswith("}"):
# Check if first brace closes only at the end
depth = 0
closes_at_end = False
for idx, char in enumerate(s):
if char == "{":
depth += 1
elif char == "}":
depth -= 1
if depth == 0:
closes_at_end = (idx == len(s) - 1)
break
if closes_at_end:
inner = s[1:-1].strip()
# If inner contains nested braced blocks separated by 'and', use inner
if "{" in inner and " and " in inner.lower():
s = inner
authors: list[str] = []
current: list[str] = []
depth = 0
i = 0
n = len(s)
while i < n:
char = s[i]
if char == "{":
depth += 1
current.append(char)
i += 1
elif char == "}":
depth = max(0, depth - 1)
current.append(char)
i += 1
elif depth == 0 and s[i : i + 5].lower() == " and ":
auth = "".join(current).strip()
if auth:
authors.append(auth)
current = []
i += 5
else:
current.append(char)
i += 1
remaining = "".join(current).strip()
if remaining:
authors.append(remaining)
return authors
def extract_first_author_surname(author_field: str | None) -> str:
"""Extract the first author's surname / family name from BibTeX author field."""
if not author_field:
return ""
authors = split_bibtex_authors(author_field)
if not authors:
return ""
first_author = authors[0].strip()
if not first_author:
return ""
# Check if first author is a braced institutional author, e.g. {World Health Organization}
if first_author.startswith("{") and first_author.endswith("}"):
inner = first_author[1:-1].strip()
if "," not in inner:
return clean_latex(inner)
first_author = inner
cleaned = clean_latex(first_author)
# Check if format is "Last, First"
if "," in cleaned:
surname = cleaned.split(",")[0].strip()
else:
# Check if "van / von / de / da / del" prefixes exist
parts = cleaned.split()
if len(parts) >= 2 and parts[-2].lower() in ("van", "von", "de", "da", "del", "der", "du"):
surname = f"{parts[-2]} {parts[-1]}"
else:
surname = parts[-1].strip() if parts else cleaned
return surname
# --- BibTeX Parser ---
def parse_bib_entries(bib_content: str) -> list[BibEntry]:
"""Parse BibTeX entries from file content into BibEntry dataclasses.
Handles multiline values, nested braces, quoted values, and comments.
"""
entries: list[BibEntry] = []
# Strip line comments starting with %
lines = [
re.sub(r"(?<!\\)%.*$", "", line) for line in bib_content.splitlines()
]
cleaned_content = "\n".join(lines)
# Find entries starting with @type{
entry_pattern = re.compile(
r"@([a-zA-Z]+)\s*[\{\(]\s*([^,\s]+)\s*,", re.MULTILINE
)
idx = 0
content_len = len(cleaned_content)
while idx < content_len:
match = entry_pattern.search(cleaned_content, idx)
if not match:
break
entry_type = match.group(1).lower()
key = match.group(2).strip()
# Skip non-entry blocks like @comment or @preamble
if entry_type in ("comment", "preamble", "string"):
idx = match.end()
continue
# Find the closing matching brace for this entry
brace_level = 1
pos = match.end()
field_start = pos
while pos < content_len and brace_level > 0:
char = cleaned_content[pos]
if char == "{" or char == "(":
brace_level += 1
elif char == "}" or char == ")":
brace_level -= 1
pos += 1
entry_body = cleaned_content[field_start : pos - 1]
idx = pos
# Parse fields within entry_body
raw_fields = _parse_bib_fields(entry_body)
doi = raw_fields.get("doi")
title = raw_fields.get("title")
author = raw_fields.get("author")
year = raw_fields.get("year") or raw_fields.get("date")
if year:
# Extract 4-digit year if date string
year_match = re.search(r"\b(19\d\d|20\d\d)\b", year)
if year_match:
year = year_match.group(1)
journal = raw_fields.get("journal") or raw_fields.get("booktitle")
entries.append(
BibEntry(
key=key,
entry_type=entry_type,
doi=normalize_doi(doi) if doi else None,
title=clean_latex(title) if title else None,
author=clean_latex(author) if author else None,
year=year.strip() if year else None,
journal=clean_latex(journal) if journal else None,
raw_fields=raw_fields,
)
)
return entries
def _parse_bib_fields(body: str) -> dict[str, str]:
"""Parse field = value pairs from a BibTeX entry body."""
fields: dict[str, str] = {}
pos = 0
body_len = len(body)
while pos < body_len:
# Find field name
field_match = re.search(r"([a-zA-Z0-9_\-]+)\s*=", body[pos:])
if not field_match:
break
field_name = field_match.group(1).lower()
val_start = pos + field_match.end()
# Skip leading whitespace
while val_start < body_len and body[val_start].isspace():
val_start += 1
if val_start >= body_len:
break
first_char = body[val_start]
val_end = val_start
if first_char == "{":
brace_level = 1
val_end = val_start + 1
while val_end < body_len and brace_level > 0:
if body[val_end] == "{":
brace_level += 1
elif body[val_end] == "}":
brace_level -= 1
val_end += 1
val = body[val_start + 1 : val_end - 1]
elif first_char == '"':
val_end = val_start + 1
while val_end < body_len:
if body[val_end] == '"' and body[val_end - 1] != "\\":
val_end += 1
break
val_end += 1
val = body[val_start + 1 : val_end - 1]
else:
# Unquoted value (number or string macro), read until comma or newline
while val_end < body_len and body[val_end] not in (",", "\n", "\r"):
val_end += 1
val = body[val_start:val_end].strip()
fields[field_name] = val.strip()
pos = val_end
# Skip trailing comma if present
while pos < body_len and (body[pos].isspace() or body[pos] == ","):
pos += 1
return fields
# --- Citation Extraction for Project Scoping ---
_CITE_PATTERNS = [
# LaTeX citation commands: \cite{a}, \citep{a,b}, \autocite{c}, etc.
re.compile(
r"\\(?:auto|paren|text|foot|no)?cite[a-zA-Z*]*\{([^}]+)\}",
re.MULTILINE,
),
# Quarto / Pandoc markdown citations: [@key1; @key2] or @key1
re.compile(r"\[\s*@([a-zA-Z0-9_:.#$%&-]+)", re.MULTILINE),
re.compile(r";\s*@([a-zA-Z0-9_:.#$%&-]+)", re.MULTILINE),
re.compile(r"(?:^|[\s(])@([a-zA-Z0-9_:.#$%&-]+)", re.MULTILINE),
]
def extract_cited_keys(project_root_or_file: Path) -> set[str]:
"""Scan source files (.tex, .qmd, .rmd, .md) to extract cited keys."""
cited_keys: set[str] = set()
if project_root_or_file.is_file():
files_to_scan = [project_root_or_file]
elif project_root_or_file.is_dir():
files_to_scan = []
for ext in ("*.tex", "*.qmd", "*.rmd", "*.md", "*.ltx"):
files_to_scan.extend(project_root_or_file.glob(f"**/{ext}"))
else:
return cited_keys
seen_files: set[Path] = set()
for file_path in files_to_scan:
if file_path in seen_files or not file_path.is_file():
continue
seen_files.add(file_path)
try:
content = file_path.read_text(encoding="utf-8", errors="ignore")
except Exception:
continue
# Extract citations
for pattern in _CITE_PATTERNS:
for match in pattern.finditer(content):
raw_keys = match.group(1)
for key in re.split(r"[,;]\s*", raw_keys):
k = key.strip().lstrip("@")
# Strip trailing punctuation like . , ; : ? ! ) ]
k = re.sub(r"[.,;:?!)\],]+$", "", k).strip()
if k:
cited_keys.add(k)
return cited_keys
# --- DOI Metadata Resolution & Fallbacks ---
def resolve_doi_crossref(
doi: str,
email: str | None = None,
timeout: float = 10.0,
) -> tuple[int, dict[str, Any] | None]:
"""Query Crossref API for DOI metadata."""
encoded_doi = urllib.parse.quote(doi, safe="")
url = f"https://api.crossref.org/works/{encoded_doi}"
if email:
url += f"?mailto={urllib.parse.quote(email)}"
headers = {
"User-Agent": DEFAULT_USER_AGENT
if not email
else f"check-doi-bib/1.0 (mailto:{email})",
"Accept": "application/json",
}
req = urllib.request.Request(url, headers=headers)
try:
with urllib.request.urlopen(req, timeout=timeout) as response:
status_code = response.getcode()
data = json.loads(response.read().decode("utf-8"))
return status_code, data
except urllib.error.HTTPError as exc:
return exc.code, None
except Exception:
return 0, None
def resolve_doi_openalex(
doi: str,
email: str | None = None,
timeout: float = 10.0,
) -> tuple[int, dict[str, Any] | None]:
"""Query OpenAlex API as fallback for rate-limited Crossref requests."""
encoded_doi = urllib.parse.quote(doi, safe="")
url = f"https://api.openalex.org/works/https://doi.org/{encoded_doi}"
if email:
url += f"?mailto={urllib.parse.quote(email)}"
headers = {
"User-Agent": DEFAULT_USER_AGENT
if not email
else f"check-doi-bib/1.0 (mailto:{email})",
"Accept": "application/json",
}
req = urllib.request.Request(url, headers=headers)
try:
with urllib.request.urlopen(req, timeout=timeout) as response:
status_code = response.getcode()
data = json.loads(response.read().decode("utf-8"))
return status_code, data
except urllib.error.HTTPError as exc:
return exc.code, None
except Exception:
return 0, None
def resolve_doi_csl(
doi: str,
timeout: float = 10.0,
) -> tuple[int, dict[str, Any] | None]:
"""Query DOI Content Negotiation for CSL-JSON (covers DataCite / non-Crossref DOIs)."""
encoded_doi = urllib.parse.quote(doi, safe="")
url = f"https://doi.org/{encoded_doi}"
headers = {
"User-Agent": DEFAULT_USER_AGENT,
"Accept": "application/vnd.citationstyles.csl+json, application/json",
}
req = urllib.request.Request(url, headers=headers)
try:
with urllib.request.urlopen(req, timeout=timeout) as response:
status_code = response.getcode()
data = json.loads(response.read().decode("utf-8"))
return status_code, data
except urllib.error.HTTPError as exc:
return exc.code, None
except Exception:
return 0, None
def resolve_doi(
doi: str,
email: str | None = None,
timeout: float = 10.0,
) -> ResolvedMetadata:
"""Resolve DOI metadata using Crossref, with OpenAlex and CSL fallbacks."""
clean_doi = normalize_doi(doi)
if not clean_doi:
return ResolvedMetadata(
doi="",
status=CheckStatus.NOT_RESOLVED,
error_message="Empty or invalid DOI",
)
# 1. Try Crossref
status_code, data = resolve_doi_crossref(clean_doi, email, timeout)
if status_code == 200 and data:
msg = data.get("message", {})
titles = msg.get("title", [])
title = titles[0] if titles else None
# Append subtitle if present
subtitles = msg.get("subtitle", [])
if subtitles and title:
title = f"{title}: {subtitles[0]}"
authors_data = msg.get("author", [])
first_author_family = None
first_author_given = None
all_authors: list[str] = []
for idx, auth in enumerate(authors_data):
fam = auth.get("family") or auth.get("name")
given = auth.get("given")
if idx == 0:
first_author_family = fam
first_author_given = given
name_str = f"{fam}, {given}" if fam and given else (fam or given or "")
if name_str:
all_authors.append(name_str)
# Extract year
year = None
for date_key in ("published-print", "published-online", "published", "issued", "created"):
dp = msg.get(date_key, {}).get("date-parts")
if dp and dp[0] and len(dp[0]) > 0:
year = str(dp[0][0])
break
container_title = None
ct = msg.get("container-title", [])
if ct:
container_title = ct[0]
return ResolvedMetadata(
doi=clean_doi,
title=title,
first_author_family=first_author_family,
first_author_given=first_author_given,
all_authors=all_authors,
year=year,
container_title=container_title,
source="crossref",
status=CheckStatus.MATCH,
)
# 2. Fallback to OpenAlex on HTTP 429 (rate limit) or 5xx
if status_code in (429, 500, 502, 503, 504):
oa_status, oa_data = resolve_doi_openalex(clean_doi, email, timeout)
if oa_status == 200 and oa_data:
title = oa_data.get("title") or oa_data.get("display_name")
authorships = oa_data.get("authorships", [])
first_fam = None
first_given = None
all_auths: list[str] = []
for idx, a_entry in enumerate(authorships):
author_obj = a_entry.get("author", {})
disp_name = author_obj.get("display_name", "")
if idx == 0:
parts = disp_name.split()
first_fam = parts[-1] if parts else disp_name
first_given = " ".join(parts[:-1]) if len(parts) > 1 else None
if disp_name:
all_auths.append(disp_name)
pub_year = oa_data.get("publication_year")
year = str(pub_year) if pub_year else None
return ResolvedMetadata(
doi=clean_doi,
title=title,
first_author_family=first_fam,
first_author_given=first_given,
all_authors=all_auths,
year=year,
source="openalex",
status=CheckStatus.MATCH,
)
# 3. Fallback to CSL-JSON for DataCite or other non-Crossref registries
if status_code in (404, 0, 429):
csl_status, csl_data = resolve_doi_csl(clean_doi, timeout)
if csl_status == 200 and csl_data:
title = csl_data.get("title")
authors_data = csl_data.get("author", [])
first_author_family = None
first_author_given = None
all_authors = []
for idx, auth in enumerate(authors_data):
fam = auth.get("family") or auth.get("literal") or auth.get("name")
given = auth.get("given")
if idx == 0:
first_author_family = fam
first_author_given = given
name_str = f"{fam}, {given}" if fam and given else (fam or given or "")
if name_str:
all_authors.append(name_str)
issued = csl_data.get("issued", {}).get("date-parts")
year = str(issued[0][0]) if issued and issued[0] else None
return ResolvedMetadata(
doi=clean_doi,
title=title,
first_author_family=first_author_family,
first_author_given=first_author_given,
all_authors=all_authors,
year=year,
source="csl-json",
status=CheckStatus.MATCH,
)
if status_code == 404:
return ResolvedMetadata(
doi=clean_doi,
status=CheckStatus.NOT_RESOLVED,
error_message="DOI returned HTTP 404 (Not Found)",
)
# Unverifiable network error or persistent failure
return ResolvedMetadata(
doi=clean_doi,
status=CheckStatus.UNVERIFIABLE,
error_message=f"Resolver unreachable or failed (HTTP status {status_code})",
)
# --- Deterministic Fuzzy Metadata Matching ---
def fuzzy_match_title(
bib_title: str | None,
resolved_title: str | None,
threshold: float = 0.70,
) -> tuple[bool, float]:
"""Compare .bib title against resolved title with fuzzy matching."""
if not bib_title or not resolved_title:
return False, 0.0
norm_b = normalize_text_for_comparison(bib_title)
norm_r = normalize_text_for_comparison(resolved_title)
if not norm_b or not norm_r:
return False, 0.0
if norm_b == norm_r:
return True, 1.0
# Sequence similarity ratio
ratio = difflib.SequenceMatcher(None, norm_b, norm_r).ratio()
# Token overlap and length metrics
tokens_b = set(norm_b.split())
tokens_r = set(norm_r.split())
if not tokens_b or not tokens_r:
return ratio >= threshold, ratio
intersection = tokens_b & tokens_r
union = tokens_b | tokens_r
jaccard = len(intersection) / len(union) if union else 0.0
len_min = min(len(norm_b), len(norm_r))
len_max = max(len(norm_b), len(norm_r))
len_ratio = len_min / len_max if len_max > 0 else 0.0
# Match if sequence ratio exceeds threshold, or token Jaccard is high with proportional length
# (handling word-order inversions and slight subtitle additions)
is_match = (
ratio >= threshold
or (jaccard >= 0.60 and len_ratio >= 0.60)
or (jaccard >= 0.50 and ratio >= 0.65 and len_ratio >= 0.50)
)
score = max(ratio, jaccard)
return is_match, score
def fuzzy_match_author(
bib_author_field: str | None,
resolved_first_author_family: str | None,
threshold: float = 0.80,
) -> tuple[bool, float]:
"""Compare .bib first author surname against resolved first author surname."""
if not bib_author_field or not resolved_first_author_family:
return False, 0.0
bib_surname = extract_first_author_surname(bib_author_field)
norm_b = normalize_text_for_comparison(bib_surname)
norm_r = normalize_text_for_comparison(resolved_first_author_family)
if not norm_b or not norm_r:
return False, 0.0
if norm_b == norm_r:
return True, 1.0
# Handle multi-word surnames or prefixes (e.g. "van Dijk" vs "Dijk")
if norm_b in norm_r.split() or norm_r in norm_b.split():
return True, 0.95
# Sequence similarity ratio
ratio = difflib.SequenceMatcher(None, norm_b, norm_r).ratio()
return ratio >= threshold, ratio
def check_bib_entry(
entry: BibEntry,
resolver: Callable[[str], ResolvedMetadata] = resolve_doi,
title_threshold: float = 0.70,
author_threshold: float = 0.80,
is_cited: bool = True,
) -> EntryCheckResult:
"""Verify a single BibEntry against DOI resolver metadata."""
if not is_cited:
return EntryCheckResult(
key=entry.key,
entry_type=entry.entry_type,
doi=entry.doi,
status=CheckStatus.SKIPPED,
bib_title=entry.title,
bib_first_author=extract_first_author_surname(entry.author),
message="Entry omitted because key is not cited in project documents",
)
if not entry.doi:
return EntryCheckResult(
key=entry.key,
entry_type=entry.entry_type,
doi=None,
status=CheckStatus.NO_DOI,
bib_title=entry.title,
bib_first_author=extract_first_author_surname(entry.author),
message="No DOI field in .bib entry",
)
meta = resolver(entry.doi)
if meta.status == CheckStatus.NOT_RESOLVED:
return EntryCheckResult(
key=entry.key,
entry_type=entry.entry_type,
doi=entry.doi,
status=CheckStatus.NOT_RESOLVED,
bib_title=entry.title,
bib_first_author=extract_first_author_surname(entry.author),
resolver_source=meta.source,
message=meta.error_message or "DOI does not resolve (HTTP 404)",
)
if meta.status == CheckStatus.UNVERIFIABLE:
return EntryCheckResult(
key=entry.key,
entry_type=entry.entry_type,
doi=entry.doi,
status=CheckStatus.UNVERIFIABLE,
bib_title=entry.title,
bib_first_author=extract_first_author_surname(entry.author),
resolver_source=meta.source,
message=meta.error_message or "Resolver network error / unverifiable",
)
# Perform metadata comparison
title_match, title_sim = fuzzy_match_title(
entry.title, meta.title, threshold=title_threshold
)
author_match, author_sim = fuzzy_match_author(
entry.author, meta.first_author_family, threshold=author_threshold
)
# Year comparison (informative check)
year_match = True
if entry.year and meta.year:
try:
year_match = abs(int(entry.year) - int(meta.year)) <= 1
except ValueError:
year_match = True
bib_first_author = extract_first_author_surname(entry.author)
if title_match and author_match:
status = CheckStatus.MATCH
msg = f"Resolved metadata matches .bib entry (source: {meta.source})"
else:
reasons = []
if not title_match:
reasons.append(
f"title mismatch (bib: '{entry.title}', resolved: '{meta.title}')"
)
if not author_match:
reasons.append(
f"author mismatch (bib: '{bib_first_author}', resolved: '{meta.first_author_family}')"
)
status = CheckStatus.MISMATCH
msg = (
f"FABRICATION SIGNATURE: DOI resolves to a different work; {', '.join(reasons)}"
)
return EntryCheckResult(
key=entry.key,
entry_type=entry.entry_type,
doi=entry.doi,
status=status,
bib_title=entry.title,
resolved_title=meta.title,
title_similarity=round(title_sim, 3),
title_match=title_match,
bib_first_author=bib_first_author,
resolved_first_author=meta.first_author_family,
author_similarity=round(author_sim, 3),
author_match=author_match,
bib_year=entry.year,
resolved_year=meta.year,
year_match=year_match,
resolver_source=meta.source,
message=msg,
)
def check_bib(
bib_content: str,
resolver: Callable[[str], ResolvedMetadata] = resolve_doi,
cited_keys: set[str] | None = None,
title_threshold: float = 0.70,
author_threshold: float = 0.80,
) -> BibCheckSummary:
"""Run DOI-vs-.bib verification over all entries in BibTeX content."""
entries = parse_bib_entries(bib_content)
summary = BibCheckSummary(total_entries=len(entries))
for entry in entries:
is_cited = True if cited_keys is None else (entry.key in cited_keys)
res = check_bib_entry(
entry,
resolver=resolver,
title_threshold=title_threshold,
author_threshold=author_threshold,
is_cited=is_cited,
)
summary.results.append(res)
if res.status == CheckStatus.SKIPPED:
summary.skipped += 1
else:
summary.checked_count += 1
if res.status == CheckStatus.MATCH:
summary.matches += 1
elif res.status == CheckStatus.MISMATCH:
summary.mismatches += 1
elif res.status == CheckStatus.NOT_RESOLVED:
summary.not_resolved += 1
elif res.status == CheckStatus.UNVERIFIABLE:
summary.unverifiable += 1
elif res.status == CheckStatus.NO_DOI:
summary.no_doi += 1
return summary
# --- CLI & Reporting ---
def format_summary_text(summary: BibCheckSummary, quiet: bool = False) -> str:
"""Format check results into a human-readable report."""
lines: list[str] = []
if not quiet:
lines.append("=" * 72)
lines.append("DOI-VS-.BIB METADATA VERIFICATION REPORT")
lines.append("=" * 72)
for res in summary.results:
if quiet and res.status in (
CheckStatus.MATCH,
CheckStatus.NO_DOI,
CheckStatus.SKIPPED,
):
continue