bibaudit 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
bibaudit/__init__.py ADDED
@@ -0,0 +1,54 @@
1
+ """bibaudit — deterministic, field-level verification of bibliographies.
2
+
3
+ Checks that every reference exists *and* that every stored field matches the
4
+ publisher's record, against Crossref, DataCite, PubMed and, for books, Open
5
+ Library. Every reference that resolves is separately checked for retraction
6
+ status against Retraction Watch's own export and PubMed's expression-of-concern
7
+ cross-reference, independent of whatever a publisher deposited with Crossref.
8
+ No language model is involved at any point, so verdicts are reproducible and
9
+ each one can be re-derived by hand from the cached registry response.
10
+
11
+ The tool reports; it never rewrites a bibliography. Adopting a registry value
12
+ wholesale — what most "bibliography fixers" do — destroys the evidence that
13
+ there was a discrepancy at all, and registries are themselves wrong often
14
+ enough that the evidence is worth keeping.
15
+
16
+ What it cannot do: judge whether a cited work supports the claim it is attached
17
+ to. That requires reading the paper, and no metadata check substitutes for it.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from .audit import AuditOptions, audit
23
+ from .compare import Thresholds, compare, verdict_for
24
+ from .model import FAILING_VERDICTS, VERDICTS, Issue, Name, Record, Reference, Result
25
+ from .report import LIMITS_NOTICE, Summary, render_json, render_text
26
+ from .suppress import Suppressions, load_suppressions
27
+
28
+ __all__ = [
29
+ "FAILING_VERDICTS",
30
+ "LIMITS_NOTICE",
31
+ "VERDICTS",
32
+ "AuditOptions",
33
+ "Issue",
34
+ "Name",
35
+ "Record",
36
+ "Reference",
37
+ "Result",
38
+ "Summary",
39
+ "Suppressions",
40
+ "Thresholds",
41
+ "audit",
42
+ "compare",
43
+ "load_suppressions",
44
+ "render_json",
45
+ "render_text",
46
+ "verdict_for",
47
+ ]
48
+
49
+ try: # pragma: no cover - trivial, and absent only in a source checkout
50
+ from importlib.metadata import version as _version
51
+
52
+ __version__ = _version("bibaudit")
53
+ except Exception: # pragma: no cover
54
+ __version__ = "0.0.0.dev0"
@@ -0,0 +1,9 @@
1
+ """Readers that turn a citation surface into :class:`~bibaudit.model.Reference`.
2
+
3
+ An adapter's only job is faithful extraction: parse what is stored, record where
4
+ it was found, and change nothing. Adapters never contact a registry and never
5
+ judge whether a value is correct.
6
+
7
+ Every adapter opens its source read-only. The Zotero adapter in particular
8
+ operates on a live database that the user's own application is writing to.
9
+ """
@@ -0,0 +1,426 @@
1
+ """Read a BibTeX (``.bib``) file into :class:`~bibaudit.model.Reference` objects.
2
+
3
+ Three public functions:
4
+
5
+ ``read_bibtex(path)``
6
+ Parse *path* with :mod:`bibtexparser` (v2) and return one Reference per
7
+ successfully parsed entry.
8
+
9
+ ``entry_locator(path, key)``
10
+ Map a citekey back to a ``"filename:line"`` string, independent of any
11
+ particular parse — a report can call this for any key it already knows
12
+ about without holding a parsed library around.
13
+
14
+ ``duplicate_report(refs)``
15
+ Find references that are probably the same work cited more than once:
16
+ a shared DOI, a reused citekey, or a near-identical title.
17
+
18
+ BibTeX itself does not require one entry per line: v2's block parser handles
19
+ that correctly (confirmed against a real 438-entry file with only 250 lines
20
+ starting in column 1 — the rest are entries opening mid-indentation or
21
+ following another entry's closing brace on the same line), so nothing here
22
+ splits the file on newlines or on ``^@``.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import pathlib
28
+ import re
29
+ import warnings
30
+ from collections import defaultdict
31
+ from collections.abc import Sequence
32
+ from typing import Any
33
+
34
+ import bibtexparser
35
+ from bibtexparser.model import DuplicateBlockKeyBlock, Entry, ParsingFailedBlock
36
+ from rapidfuzz import fuzz
37
+
38
+ from ..model import Name, Reference
39
+ from ..names import parse_name_list
40
+ from ..normalize import (
41
+ clean,
42
+ extract_dois,
43
+ fold,
44
+ normalize_doi,
45
+ normalize_kind,
46
+ normalize_pmid,
47
+ parse_year,
48
+ )
49
+
50
+ __all__ = ["duplicate_report", "entry_locator", "read_bibtex"]
51
+
52
+
53
+ def read_bibtex(path: pathlib.Path) -> list[Reference]:
54
+ """Parse *path* as BibTeX and return one Reference per parsed entry.
55
+
56
+ Uses bibtexparser's default middleware stack (string resolution + one
57
+ layer of enclosing-brace removal per field) rather than a bespoke one:
58
+ that default is what strips the outer ``{...}``/``"..."`` BibTeX wraps
59
+ every field in without touching braces *inside* a value, which is what
60
+ keeps an inner ``{GWAS}`` (capitalisation protection) or a fully braced
61
+ single author (``{World Health Organization}``) intact for
62
+ :func:`~bibaudit.names.parse_name_list` to see.
63
+
64
+ A block bibtexparser could not attach to the library — most often two
65
+ entries sharing one citekey, where the second is dropped from
66
+ ``library.entries`` entirely — is never silently swallowed: each one
67
+ raises a :class:`RuntimeWarning` naming the file, line and reason, so the
68
+ defect is visible even though the reference it belongs to cannot be
69
+ built.
70
+ """
71
+ path = pathlib.Path(path)
72
+ # bibtexparser re-exports parse_file from .entrypoint without listing it
73
+ # in __init__.py's own __all__, which mypy --strict's implicit-reexport
74
+ # check flags even though it is documented top-level API.
75
+ library = bibtexparser.parse_file(str(path)) # type: ignore[attr-defined]
76
+ _warn_failed_blocks(path, library.failed_blocks)
77
+ return [_entry_to_reference(path, entry) for entry in library.entries]
78
+
79
+
80
+ # ---------------------------------------------------------------------------
81
+ # Entry -> Reference
82
+ # ---------------------------------------------------------------------------
83
+
84
+
85
+ def _select_creators(fields: dict[str, str]) -> tuple[list[Name], str]:
86
+ """Creators for one entry, and the role marker if they came from ``editor``.
87
+
88
+ An edited volume ("Methods in Biobanking", cited by its editors) has no
89
+ ``author`` field at all — that is correct BibTeX, not a defect — so
90
+ falling back to ``editor`` when ``author`` is absent is the right read of
91
+ the entry rather than reporting zero authors. The returned role is
92
+ empty for the ordinary case, matching
93
+ ``adapters.zotero._select_creator_role``'s convention, so a comparison
94
+ downstream sees the same ``raw["creator_role"] == "editor"`` marker
95
+ regardless of which adapter produced the Reference.
96
+ """
97
+ author_field = fields.get("author")
98
+ if author_field and author_field.strip():
99
+ return parse_name_list(author_field), ""
100
+ editor_field = fields.get("editor")
101
+ if editor_field and editor_field.strip():
102
+ return parse_name_list(editor_field), "editor"
103
+ return [], ""
104
+
105
+
106
+ def _extract_doi(fields: dict[str, str]) -> str | None:
107
+ """The entry's DOI, preferring the dedicated field over one buried in a URL.
108
+
109
+ Crossref's BibTeX export writes the same DOI twice on many entries —
110
+ once in ``DOI``, once as a resolver link in ``url`` — and the two
111
+ commonly disagree only in case
112
+ (``10.1158/1055-9965.EPI-20-0378`` vs. the url's
113
+ ``...epi-20-0378``). Preferring the dedicated field means that
114
+ disagreement is never even evaluated; falling back to ``url`` only when
115
+ ``DOI`` is absent covers entries (mostly older ones) that carry a
116
+ doi.org link but no separate DOI field.
117
+
118
+ ``extract_dois`` (not a bare ``normalize_doi``) is used on *both* fields
119
+ so a placeholder some reference managers write into ``doi`` — ``N/A``,
120
+ ``TBD``, an empty pair of braces that survives as whitespace — is
121
+ recognised as not-a-DOI and falls through to ``url`` instead of being
122
+ normalised into a confident-looking fake like ``"n/a"`` that a registry
123
+ lookup would then report as a bad identifier on an otherwise-fine entry.
124
+ """
125
+ doi_field = fields.get("doi")
126
+ if doi_field and doi_field.strip():
127
+ found = extract_dois(doi_field)
128
+ if found:
129
+ return found[0]
130
+ url_field = fields.get("url")
131
+ if url_field:
132
+ found = extract_dois(url_field)
133
+ if found:
134
+ return found[0]
135
+ return None
136
+
137
+
138
+ #: What ``eprinttype`` (BibLaTeX) or ``archiveprefix`` (the older spelling,
139
+ #: still emitted by tools that predate it) says when the companion ``eprint``
140
+ #: field holds a PMID rather than some other repository's number.
141
+ _PUBMED_EPRINT_TYPES = frozenset({"pubmed", "pmid"})
142
+
143
+
144
+ def _extract_pmid(fields: dict[str, str]) -> str | None:
145
+ """The entry's PMID, from ``pmid`` or from a PubMed-typed ``eprint``.
146
+
147
+ Both spellings reach a ``.bib`` file from ordinary tools: PubMed's own
148
+ "Send to > Citation manager" route arrives, once converted, as a dedicated
149
+ ``pmid = {28520842}``, while BibLaTeX-flavoured exports write
150
+ ``eprint = {28520842}`` beside ``eprinttype = {pubmed}``.
151
+
152
+ The type gate is load-bearing, not ceremony. ``eprint`` is a shared slot
153
+ with no meaning of its own — the same field carries an arXiv id, an SSRN
154
+ working-paper number or a HAL id depending on its companion — and an SSRN
155
+ number is exactly as bare-numeric as a PMID. Reading one as the other
156
+ would send a sound entry to PubMed under an identifier drawn from another
157
+ registry's numbering, where it resolves to a different paper or to none.
158
+
159
+ ``normalize_pmid`` (rather than the field's value as typed) is applied on
160
+ both routes for the reason ``_extract_doi`` uses ``extract_dois``: a
161
+ reference manager writing ``N/A`` or an empty pair of braces into ``pmid``
162
+ must fall through as "no PMID recorded", not become a confident-looking
163
+ identifier the audit then reports as bad.
164
+ """
165
+ pmid = normalize_pmid(fields.get("pmid"))
166
+ if pmid:
167
+ return pmid
168
+ if fold(fields.get("eprinttype") or fields.get("archiveprefix")) in _PUBMED_EPRINT_TYPES:
169
+ return normalize_pmid(fields.get("eprint"))
170
+ return None
171
+
172
+
173
+ def _entry_to_reference(path: pathlib.Path, entry: Entry) -> Reference:
174
+ """Build one Reference from a parsed bibtexparser Entry.
175
+
176
+ Field names arrive from bibtexparser in whatever case the source file
177
+ used (``DOI``, ``ISSN``, ``url`` all appear in the same real file); every
178
+ lookup here goes through *fields*, a lowercase-keyed copy, while *raw*
179
+ keeps the original casing intact as "untouched adapter output".
180
+ """
181
+ raw: dict[str, Any] = {name: field.value for name, field in entry.fields_dict.items()}
182
+ fields = {name.lower(): value for name, value in raw.items()}
183
+
184
+ authors, role = _select_creators(fields)
185
+ if role:
186
+ raw["creator_role"] = role
187
+
188
+ # "journal" covers @article; "booktitle" covers @inbook/@incollection —
189
+ # an entry has at most one of the two, never both, so this is not a
190
+ # judgement call about which field wins.
191
+ container = fields.get("journal") or fields.get("booktitle")
192
+
193
+ return Reference(
194
+ key=entry.key,
195
+ locator=entry_locator(path, entry.key),
196
+ kind=normalize_kind(entry.entry_type),
197
+ doi=_extract_doi(fields),
198
+ pmid=_extract_pmid(fields),
199
+ isbn=clean(fields["isbn"]) if fields.get("isbn") else None,
200
+ url=clean(fields["url"]) if fields.get("url") else None,
201
+ title=clean(fields["title"]) if fields.get("title") else None,
202
+ authors=authors,
203
+ # BibTeX conventionally uses "year"; a "date" field (Zotero's Better
204
+ # BibTeX export, some CSL-flavoured .bib files) is the fallback
205
+ # parse_year handles on its own once handed the right string.
206
+ year=parse_year(fields.get("year")) or parse_year(fields.get("date")),
207
+ container=clean(container) if container else None,
208
+ volume=clean(fields["volume"]) if fields.get("volume") else None,
209
+ issue=clean(fields["number"]) if fields.get("number") else None,
210
+ pages=clean(fields["pages"]) if fields.get("pages") else None,
211
+ publisher=clean(fields["publisher"]) if fields.get("publisher") else None,
212
+ raw=raw,
213
+ )
214
+
215
+
216
+ def _warn_failed_blocks(path: pathlib.Path, failed_blocks: list[ParsingFailedBlock]) -> None:
217
+ """Raise a RuntimeWarning per block bibtexparser could not parse.
218
+
219
+ A duplicate-citekey block is bibtexparser's own way of catching a real
220
+ defect (two entries claiming the same key): it does not raise, it just
221
+ quietly excludes the second entry from ``library.entries`` and records a
222
+ :class:`DuplicateBlockKeyBlock` here instead. Treating that as nothing to
223
+ report would make ``read_bibtex`` return 437 references from a 438-entry
224
+ file with no indication why — the exact "not something to swallow"
225
+ failure this function exists to prevent. ``warnings.warn`` matches
226
+ ``adapters.zotero``'s convention for a non-fatal defect the caller must
227
+ still see.
228
+ """
229
+ # stacklevel=3: frame 1 is this function's own warnings.warn() call,
230
+ # frame 2 is read_bibtex() (the only caller), so frame 3 is whoever
231
+ # called read_bibtex() — the actual "user" adapters.zotero's convention
232
+ # means to point at. Leaving this at 2 (right for a warning raised
233
+ # directly in a public function, which is zotero's case) would blame the
234
+ # line inside read_bibtex that calls this helper instead of the caller's
235
+ # own code, which is not something to swallow either.
236
+ stacklevel = 3
237
+ for block in failed_blocks:
238
+ line = block.start_line
239
+ location = f"{path.name}:{line + 1}" if line is not None else path.name
240
+ if isinstance(block, DuplicateBlockKeyBlock):
241
+ warnings.warn(
242
+ f"{location}: duplicate citekey {block.key!r} — the second "
243
+ "entry using this key was discarded and is not in the audit",
244
+ RuntimeWarning,
245
+ stacklevel=stacklevel,
246
+ )
247
+ continue
248
+ # BlockAbortedException (bibtexparser's usual syntax-error exception)
249
+ # carries its message in .abort_reason, not in str(exc) — the base
250
+ # Exception is constructed without one, so str() alone is blank.
251
+ reason = getattr(block.error, "abort_reason", None) or str(block.error) or repr(block.error)
252
+ warnings.warn(
253
+ f"{location}: block failed to parse ({reason})", RuntimeWarning, stacklevel=stacklevel
254
+ )
255
+
256
+
257
+ # ---------------------------------------------------------------------------
258
+ # entry_locator
259
+ # ---------------------------------------------------------------------------
260
+
261
+ #: An entry opens with "@type{key," (or, rarely, "@type{key}" for a
262
+ #: field-less entry). The key class excludes comma/whitespace/close-brace
263
+ #: rather than allowlisting characters, because real citekeys use ':', '.'
264
+ #: and '/' (DOI-derived keys, Better BibTeX's "auto-export" keys) that an
265
+ #: allowlist would have to keep growing to cover.
266
+ _ENTRY_OPEN_RE = re.compile(r"@([A-Za-z]+)\s*\{\s*([^,\s}]+)\s*[,}]")
267
+
268
+ #: "@word{" also opens a @string macro, @comment or @preamble block. None of
269
+ #: those has a citekey worth indexing, and skipping them means a macro name
270
+ #: that happens to collide with a real citekey can never shadow the entry's
271
+ #: own line.
272
+ _NON_ENTRY_BLOCK_TYPES = frozenset({"string", "comment", "preamble"})
273
+
274
+ #: (resolved path, mtime_ns) -> {citekey: 1-based line number}. entry_locator
275
+ #: is called once per reference — hundreds of times in one read_bibtex() run
276
+ #: — so the file is regex-scanned once per (path, mtime) rather than once per
277
+ #: call; without this, locating N references would cost O(N * file size)
278
+ #: instead of O(file size + N).
279
+ _LINE_CACHE: dict[tuple[str, int], dict[str, int]] = {}
280
+
281
+
282
+ def _citekey_lines(path: pathlib.Path) -> dict[str, int]:
283
+ """citekey -> 1-based line number for every entry in *path*, cached by mtime."""
284
+ resolved = path.resolve()
285
+ cache_key = (str(resolved), resolved.stat().st_mtime_ns)
286
+ cached = _LINE_CACHE.get(cache_key)
287
+ if cached is not None:
288
+ return cached
289
+
290
+ text = resolved.read_text(encoding="utf-8")
291
+ n = len(text)
292
+ lines: dict[str, int] = {}
293
+ line_no = 1
294
+ pos = 0 # last position line_no has been advanced to
295
+ scan_from = 0
296
+ # Repeated search-and-skip rather than a flat finditer(): a bare
297
+ # _ENTRY_OPEN_RE.finditer(text) matches "@type{key," anywhere in the raw
298
+ # text, including *inside* another entry's own title — "A study
299
+ # mentioning @article{other-key, as an example}" — and when that fake
300
+ # occurrence comes first in the file, lines.setdefault keeps it and the
301
+ # real "other-key" entry is reported at the wrong line. So once a match
302
+ # is found, its own body is skipped by counting braces from *that
303
+ # match's* opening brace only — never across the free text between
304
+ # blocks, which BibTeX's implicit-comment rule leaves unbalanced by
305
+ # design (a stray "{" in a note is not a defect) and which a whole-file
306
+ # depth counter would misread as "still inside a block" forever after.
307
+ while True:
308
+ match = _ENTRY_OPEN_RE.search(text, scan_from)
309
+ if match is None:
310
+ break
311
+ start = match.start()
312
+ if match.group(1).lower() not in _NON_ENTRY_BLOCK_TYPES:
313
+ line_no += text.count("\n", pos, start)
314
+ pos = start
315
+ # First occurrence wins. A duplicate citekey's second block never
316
+ # reaches library.entries (see _warn_failed_blocks), so its line
317
+ # must not overwrite the line of the entry actually in the audit.
318
+ lines.setdefault(match.group(2), line_no)
319
+
320
+ # The regex's own "\s*\{\s*" already consumed the block's opening
321
+ # brace, so the first "{" at or after `start` is exactly that one.
322
+ depth = 1
323
+ i = text.index("{", start) + 1
324
+ while i < n and depth > 0:
325
+ c = text[i]
326
+ if c == "{":
327
+ depth += 1
328
+ elif c == "}":
329
+ depth -= 1
330
+ i += 1
331
+ # depth == 0 means i now sits just past this block's real closing
332
+ # brace. A block whose braces never balance is a syntax error
333
+ # bibtexparser will already have reported via _warn_failed_blocks;
334
+ # resuming right after its opener (rather than scanning to EOF as
335
+ # "still inside") keeps that one bad block from hiding every entry
336
+ # that follows it, at the cost of possibly re-scanning its own
337
+ # (already broken) interior — the same fallback a flat scan would
338
+ # give.
339
+ scan_from = i if depth == 0 else start + 1
340
+
341
+ # Drop any earlier snapshot of this same path so a long-lived process
342
+ # that re-reads a file across edits does not accumulate one cache entry
343
+ # per edit forever.
344
+ for stale_key in [k for k in _LINE_CACHE if k[0] == cache_key[0] and k != cache_key]:
345
+ del _LINE_CACHE[stale_key]
346
+ _LINE_CACHE[cache_key] = lines
347
+ return lines
348
+
349
+
350
+ def entry_locator(path: pathlib.Path, key: str) -> str:
351
+ """A clickable ``"filename:line"`` locator for citekey *key* in *path*.
352
+
353
+ Only the basename is used, matching the exact form ``Reference.locator``
354
+ itself documents for a bibliography ("references.bib:412"): unlike a
355
+ per-page ``.qmd`` locator, where the directory disambiguates one page
356
+ among hundreds, a bibliography is normally one shared file, and a full
357
+ path would just repeat the same prefix on every line of a report.
358
+ """
359
+ path = pathlib.Path(path)
360
+ line = _citekey_lines(path).get(key)
361
+ if line is None:
362
+ # A key that came from read_bibtex() on this same file always has a
363
+ # line; this only fires for a key looked up against a file that
364
+ # changed (or never contained it), and "filename:?" is a better
365
+ # failure than a KeyError aborting an otherwise-successful report.
366
+ return f"{path.name}:?"
367
+ return f"{path.name}:{line}"
368
+
369
+
370
+ # ---------------------------------------------------------------------------
371
+ # duplicate_report
372
+ # ---------------------------------------------------------------------------
373
+
374
+ #: rapidfuzz's fuzz.ratio() is on a 0-100 scale; this is the contract's 0.95
375
+ #: threshold expressed on that scale.
376
+ _TITLE_SIMILARITY_THRESHOLD = 95.0
377
+
378
+
379
+ def duplicate_report(refs: Sequence[Reference]) -> dict[str, list[str]]:
380
+ """Group *refs* into three kinds of probable accidental duplication.
381
+
382
+ Always returns exactly the keys ``"doi"``, ``"key"`` and ``"title"``,
383
+ each a list of one human-readable line per colliding group (empty when
384
+ nothing collided in that category). A duplicate DOI under two different
385
+ citekeys is a common, real defect (a paper pasted into the bibliography
386
+ twice under two different keys, once by hand and once from an export) —
387
+ distinct from a duplicate *citekey*, which bibtexparser itself already
388
+ prevents from reaching a single ``read_bibtex()`` call's output (see
389
+ ``read_bibtex``'s failed-block handling); the "key" category exists for
390
+ callers that merge references from more than one source, where the same
391
+ key can legitimately reappear.
392
+ """
393
+ report: dict[str, list[str]] = {"doi": [], "key": [], "title": []}
394
+
395
+ by_doi: dict[str, list[Reference]] = defaultdict(list)
396
+ for ref in refs:
397
+ if ref.doi:
398
+ by_doi[normalize_doi(ref.doi)].append(ref)
399
+ for doi, group in sorted(by_doi.items()):
400
+ if len(group) > 1:
401
+ where = ", ".join(f"{r.key} ({r.locator})" for r in group)
402
+ report["doi"].append(f"{doi}: {where}")
403
+
404
+ by_key: dict[str, list[Reference]] = defaultdict(list)
405
+ for ref in refs:
406
+ by_key[ref.key].append(ref)
407
+ for key, group in sorted(by_key.items()):
408
+ if len(group) > 1:
409
+ where = ", ".join(r.locator for r in group)
410
+ report["key"].append(f"{key}: {where}")
411
+
412
+ # Folded once per reference up front so an O(n^2) comparison pays for
413
+ # fold() O(n) times, not O(n) times per candidate pair.
414
+ titled = [(ref, fold(ref.title)) for ref in refs if ref.title and fold(ref.title)]
415
+ for i, (left, left_folded) in enumerate(titled):
416
+ for right, right_folded in titled[i + 1 :]:
417
+ if right.key == left.key:
418
+ continue
419
+ score = fuzz.ratio(left_folded, right_folded)
420
+ if score >= _TITLE_SIMILARITY_THRESHOLD:
421
+ report["title"].append(
422
+ f"{left.key} ({left.locator}) ~ {right.key} ({right.locator}) "
423
+ f"[{score:.0f}%]: {clean(left.title)}"
424
+ )
425
+
426
+ return report