Skip to content

Commit 855eead

Browse files
authored
Merge pull request #146 from PyAutoLabs/feature/canonical-key-todo-sweep
chore: canonical-key TODO sweep — 388 → 98, bib dedup + repairs, candidates script
2 parents 965d45f + 46b5da4 commit 855eead

58 files changed

Lines changed: 1298 additions & 1958 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎bibliography/pyautomemory.bib‎

Lines changed: 342 additions & 925 deletions
Large diffs are not rendered by default.
Lines changed: 245 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,245 @@
1+
"""Rank canonical BibTeX candidates for wiki sections whose key is still TODO.
2+
3+
Read-only: emits a candidates report (section -> ranked candidate keys with a
4+
confidence label) and never writes a key into the wiki. Every proposed match
5+
must be verified against the public paper record by a human (or an agent
6+
acting for one) before the section is filled — see ``bibliography/README.md``:
7+
never fabricate, uncertain stays TODO.
8+
9+
Matching order, strongest first: DOI and arXiv id quoted in the section body,
10+
then first-author surname + year (the heading's ``Author Year — tag`` stem),
11+
ranked by overlap between the heading tag and the entry title.
12+
"""
13+
14+
from __future__ import annotations
15+
16+
import argparse
17+
import json
18+
import re
19+
import unicodedata
20+
from dataclasses import dataclass, field
21+
from pathlib import Path
22+
23+
from scripts.validate_literature_citations import (
24+
DEFAULT_BIBLIOGRAPHY,
25+
ROOT,
26+
SOURCE_SECTION,
27+
source_directories,
28+
)
29+
30+
TODO_KEY = re.compile(r"^\*\*Canonical BibTeX key:\*\*\s*TODO\b", re.MULTILINE)
31+
HEADING = re.compile(r"^(?P<author>.+?)\s+(?P<year>(?:18|19|20)\d\d)[a-z]?\b\s*(?:[—–-]+\s*(?P<tag>.*))?$")
32+
INNER_AUTHOR_YEAR = re.compile(r"(?:^|[—–-]\s*)(?P<author>[A-Z][A-Za-zÀ-ÿ'\-]+)(?:\s+(?:&|and)\s+[A-Z][A-Za-zÀ-ÿ'\-]+|\s+et\s+al\.?)?\s+(?P<year>(?:18|19|20)\d\d)[a-z]?\b")
33+
#: Minimum share of a heading's content words that must appear in an entry
34+
#: title before a title-only match is proposed.
35+
TITLE_OVERLAP = 0.6
36+
DOI = re.compile(r"10\.\d{4,9}/[^\s;,)`]+", re.IGNORECASE)
37+
ARXIV = re.compile(r"\b(\d{4}\.\d{4,5}|[a-z-]+(?:\.[A-Z]{2})?/\d{7})(?:v\d+)?\b")
38+
ENTRY_START = re.compile(r"^\s*@(?!comment\b|string\b|preamble\b)[A-Za-z]+\s*[({]\s*([^,\s]+)\s*,", re.MULTILINE | re.IGNORECASE)
39+
FIELD = re.compile(r"^\s*([A-Za-z]+)\s*=\s*(.*?),?\s*$", re.MULTILINE)
40+
41+
STOPWORDS = frozenset(
42+
"a an and as at by for from in into of on or the to with via using new "
43+
"its their is are be we our paper study".split()
44+
)
45+
46+
47+
@dataclass(frozen=True)
48+
class BibEntry:
49+
key: str
50+
first_author: str
51+
year: str
52+
title: str
53+
doi: str = ""
54+
arxiv: str = ""
55+
56+
57+
@dataclass
58+
class TodoSection:
59+
path: Path
60+
line: int
61+
heading: str
62+
author: str = ""
63+
year: str = ""
64+
tag: str = ""
65+
body: str = ""
66+
candidates: list[dict] = field(default_factory=list)
67+
68+
69+
def fold(text: str) -> str:
70+
"""Lower-case ASCII fold, stripping LaTeX accents and braces."""
71+
72+
text = re.sub(r"\\[`'^\"~=.uvHcdbtr]\s*\{?([A-Za-z])\}?", r"\1", text)
73+
text = re.sub(r"\\([oOlL])\b", r"\1", text)
74+
text = text.replace("{", "").replace("}", "")
75+
text = unicodedata.normalize("NFKD", text)
76+
return "".join(c for c in text if not unicodedata.combining(c)).lower()
77+
78+
79+
def surname(author_field: str) -> str:
80+
first = re.split(r"\s+and\s+", author_field.strip(), maxsplit=1)[0]
81+
first = fold(first).strip()
82+
name = first.split(",", 1)[0] if "," in first else (first.split() or [""])[-1]
83+
return re.sub(r"[^a-z]", "", name)
84+
85+
86+
def words(text: str) -> set[str]:
87+
return {w for w in re.findall(r"[a-z0-9]+", fold(text)) if w not in STOPWORDS and len(w) > 1}
88+
89+
90+
def normalize_arxiv(identifier: str) -> str:
91+
"""``arXiv:1302.1873v1`` -> ``1302.1873``; old-style ids keep their archive."""
92+
93+
identifier = re.sub(r"^arxiv:", "", identifier.strip(), flags=re.IGNORECASE)
94+
return re.sub(r"v\d+$", "", identifier).lower()
95+
96+
97+
def parse_entries(text: str) -> list[BibEntry]:
98+
starts = list(ENTRY_START.finditer(text))
99+
entries = []
100+
for index, match in enumerate(starts):
101+
end = starts[index + 1].start() if index + 1 < len(starts) else len(text)
102+
fields = {
103+
name.lower(): value.strip().strip("{}\"").strip()
104+
for name, value in FIELD.findall(text[match.end():end])
105+
}
106+
arxiv = normalize_arxiv(fields.get("arxivid") or fields.get("eprint") or "")
107+
entries.append(
108+
BibEntry(
109+
key=match.group(1),
110+
first_author=surname(fields.get("author", "")),
111+
year=re.sub(r"\D", "", fields.get("year", ""))[:4],
112+
title=fields.get("title", ""),
113+
doi=fields.get("doi", "").lower(),
114+
arxiv=arxiv.lower(),
115+
)
116+
)
117+
return entries
118+
119+
120+
def collect_todo_sections(root: Path) -> list[TodoSection]:
121+
sections = []
122+
for directory in source_directories(root):
123+
for path in sorted(directory.glob("*.md")):
124+
markdown = path.read_text(encoding="utf-8")
125+
for match in SOURCE_SECTION.finditer(markdown):
126+
body = match.group(2)
127+
if not TODO_KEY.search(body):
128+
continue
129+
heading = match.group(1).strip()
130+
section = TodoSection(
131+
path=path.relative_to(root),
132+
line=markdown.count("\n", 0, match.start()) + 1,
133+
heading=heading,
134+
body=body,
135+
)
136+
parsed = HEADING.match(heading)
137+
if parsed:
138+
section.author = re.sub(r"[^a-z]", "", fold(parsed.group("author").split()[0]))
139+
section.year = parsed.group("year")
140+
section.tag = parsed.group("tag") or ""
141+
else:
142+
# "Prefix — Author Year tag" (e.g. "UnRead — Belfiore 2017 MaNGA ...")
143+
inner = INNER_AUTHOR_YEAR.search(heading)
144+
if inner:
145+
section.author = re.sub(r"[^a-z]", "", fold(inner.group("author")))
146+
section.year = inner.group("year")
147+
section.tag = heading[inner.end():].strip(" —–-")
148+
else:
149+
section.tag = heading
150+
sections.append(section)
151+
return sections
152+
153+
154+
def rank(section: TodoSection, entries: list[BibEntry]) -> list[dict]:
155+
found: dict[str, dict] = {}
156+
body = section.body
157+
for doi in {d.lower().rstrip(".") for d in DOI.findall(body)}:
158+
for entry in entries:
159+
if entry.doi and entry.doi == doi:
160+
found[entry.key] = {"key": entry.key, "by": "doi", "confidence": "exact", "score": 1.0, "title": entry.title}
161+
for arxiv in {a.lower() for a in ARXIV.findall(body)}:
162+
for entry in entries:
163+
if entry.arxiv and entry.arxiv == arxiv and entry.key not in found:
164+
found[entry.key] = {"key": entry.key, "by": "arxiv", "confidence": "exact", "score": 1.0, "title": entry.title}
165+
if section.author and section.year:
166+
tag_words = words(section.tag)
167+
same = [e for e in entries if e.first_author == section.author and e.year == section.year]
168+
for entry in same:
169+
if entry.key in found:
170+
continue
171+
overlap = len(tag_words & words(entry.title))
172+
score = overlap / len(tag_words) if tag_words else 0.0
173+
if len(same) == 1:
174+
confidence = "high" if overlap else "medium"
175+
else:
176+
confidence = "medium" if overlap else "low"
177+
found[entry.key] = {
178+
"key": entry.key, "by": "author+year", "confidence": confidence,
179+
"score": round(score, 2), "title": entry.title,
180+
}
181+
if not found and not (section.author and section.year):
182+
tag_words = words(section.tag)
183+
if len(tag_words) >= 3:
184+
for entry in entries:
185+
overlap = len(tag_words & words(entry.title))
186+
score = overlap / len(tag_words)
187+
if score >= TITLE_OVERLAP:
188+
found[entry.key] = {
189+
"key": entry.key, "by": "title",
190+
"confidence": "medium" if score >= 0.8 else "low",
191+
"score": round(score, 2), "title": entry.title,
192+
}
193+
order = {"exact": 0, "high": 1, "medium": 2, "low": 3}
194+
return sorted(found.values(), key=lambda c: (order[c["confidence"]], -c["score"], c["key"]))
195+
196+
197+
def build_report(root: Path, bibliography: Path) -> list[TodoSection]:
198+
entries = parse_entries(bibliography.read_text(encoding="utf-8"))
199+
sections = collect_todo_sections(root)
200+
for section in sections:
201+
section.candidates = rank(section, entries)
202+
return sections
203+
204+
205+
def render_markdown(sections: list[TodoSection]) -> str:
206+
matched = [s for s in sections if s.candidates]
207+
lines = [
208+
"# Canonical-key TODO candidates",
209+
"",
210+
f"TODO sections: {len(sections)}; with at least one candidate: {len(matched)}.",
211+
"Candidates are proposals only — verify each against the public paper record before filling.",
212+
"",
213+
]
214+
for section in sections:
215+
lines.append(f"## {section.path}:{section.line} — {section.heading}")
216+
if not section.candidates:
217+
lines.append("- no candidate")
218+
for candidate in section.candidates:
219+
lines.append(
220+
f"- `{candidate['key']}` [{candidate['confidence']}, {candidate['by']}, "
221+
f"tag overlap {candidate['score']}] {candidate['title']}"
222+
)
223+
lines.append("")
224+
return "\n".join(lines)
225+
226+
227+
def main(argv: list[str] | None = None) -> int:
228+
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
229+
parser.add_argument("--root", type=Path, default=ROOT)
230+
parser.add_argument("--bibliography", type=Path, default=DEFAULT_BIBLIOGRAPHY)
231+
parser.add_argument("--json", action="store_true", help="emit JSON instead of Markdown")
232+
args = parser.parse_args(argv)
233+
sections = build_report(args.root, args.bibliography)
234+
if args.json:
235+
print(json.dumps([
236+
{"path": str(s.path), "line": s.line, "heading": s.heading, "candidates": s.candidates}
237+
for s in sections
238+
], indent=2))
239+
else:
240+
print(render_markdown(sections))
241+
return 0
242+
243+
244+
if __name__ == "__main__":
245+
raise SystemExit(main())
Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
"""Tests for the read-only canonical-key candidates report."""
2+
3+
from pathlib import Path
4+
5+
from scripts.canonical_key_candidates import (
6+
build_report,
7+
fold,
8+
parse_entries,
9+
render_markdown,
10+
surname,
11+
)
12+
13+
BIB = """
14+
@article{Smith2019,
15+
author = {Smith, Jane and Doe, John},
16+
doi = {10.1000/abc.1},
17+
eprint = {1901.00001},
18+
title = {{Supermassive black holes in the early universe}},
19+
year = {2019}
20+
}
21+
22+
@article{Gomez2016,
23+
author = {G{\\'{o}}mez, L. G. and Arg{\\"{u}}elles, C. R.},
24+
title = {{Strong lensing by fermionic dark matter in galaxies}},
25+
year = {2016}
26+
}
27+
28+
@article{Hall2014,
29+
author = {Hall, D. J.},
30+
title = {{Single-trap pumping technique}},
31+
year = {2014}
32+
}
33+
34+
@article{Hall2014a,
35+
author = {Hall, D. J.},
36+
title = {{In situ trap parameter studies}},
37+
year = {2014}
38+
}
39+
"""
40+
41+
TODO = """**Canonical BibTeX key:** TODO — no unique match found in `bibliography/pyautomemory.bib`.
42+
**Reference:** TODO — identify the public paper record.
43+
"""
44+
45+
46+
def _write(tmp_path: Path, page: str) -> Path:
47+
bib = tmp_path / "bibliography" / "pyautomemory.bib"
48+
bib.parent.mkdir(parents=True)
49+
bib.write_text(BIB, encoding="utf-8")
50+
sources = tmp_path / "wiki" / "demo" / "sources"
51+
sources.mkdir(parents=True)
52+
(sources / "page.md").write_text(page, encoding="utf-8")
53+
return bib
54+
55+
56+
def test_fold_and_surname_strip_latex_accents():
57+
assert fold("G{\\'{o}}mez") == "gomez"
58+
assert surname("G{\\'{o}}mez, L. G. and Other, A.") == "gomez"
59+
assert surname("Jane Smith and John Doe") == "smith"
60+
61+
62+
def test_parse_entries_reads_identifiers():
63+
entries = {entry.key: entry for entry in parse_entries(BIB)}
64+
assert entries["Smith2019"].doi == "10.1000/abc.1"
65+
assert entries["Smith2019"].arxiv == "1901.00001"
66+
assert entries["Gomez2016"].first_author == "gomez"
67+
68+
69+
def test_unique_author_year_with_tag_overlap_is_high(tmp_path):
70+
bib = _write(tmp_path, "# P\n\n## Gómez 2016 — fermionic DM\n\n" + TODO)
71+
(section,) = build_report(tmp_path, bib)
72+
assert section.candidates[0]["key"] == "Gomez2016"
73+
assert section.candidates[0]["confidence"] == "high"
74+
75+
76+
def test_doi_in_body_is_exact_and_ranked_first(tmp_path):
77+
page = "# P\n\n## Hall 2014 — anything\n\n" + TODO + "See doi:10.1000/abc.1\n"
78+
bib = _write(tmp_path, page)
79+
(section,) = build_report(tmp_path, bib)
80+
assert section.candidates[0] == {
81+
"key": "Smith2019", "by": "doi", "confidence": "exact", "score": 1.0,
82+
"title": "Supermassive black holes in the early universe",
83+
}
84+
85+
86+
def test_ambiguous_author_year_ranks_by_tag_and_never_high(tmp_path):
87+
bib = _write(tmp_path, "# P\n\n## Hall 2014 — traps in situ\n\n" + TODO)
88+
(section,) = build_report(tmp_path, bib)
89+
assert [c["key"] for c in section.candidates] == ["Hall2014a", "Hall2014"]
90+
assert section.candidates[0]["confidence"] == "medium"
91+
assert section.candidates[1]["confidence"] == "low"
92+
93+
94+
def test_filled_sections_are_ignored_and_report_never_writes(tmp_path):
95+
page = "# P\n\n## Smith 2019 — SMBHs\n\n**Canonical BibTeX key:** `Smith2019`\n"
96+
bib = _write(tmp_path, page)
97+
before = (tmp_path / "wiki/demo/sources/page.md").read_text()
98+
assert build_report(tmp_path, bib) == []
99+
assert "TODO sections: 0" in render_markdown([])
100+
assert (tmp_path / "wiki/demo/sources/page.md").read_text() == before
101+
102+
103+
def test_normalize_arxiv_strips_prefix_and_version():
104+
from scripts.canonical_key_candidates import normalize_arxiv
105+
106+
assert normalize_arxiv("arxiv:1302.1873v1") == "1302.1873"
107+
assert normalize_arxiv("astro-ph/0101213") == "astro-ph/0101213"
108+
109+
110+
def test_title_only_heading_matches_by_normalized_title(tmp_path):
111+
page = "# P\n\n## Strong lensing fermionic dark matter galaxies\n\n" + TODO
112+
bib = _write(tmp_path, page)
113+
(section,) = build_report(tmp_path, bib)
114+
assert section.candidates[0]["key"] == "Gomez2016"
115+
assert section.candidates[0]["by"] == "title"
116+
117+
118+
def test_prefixed_heading_parses_inner_author_year(tmp_path):
119+
bib = _write(tmp_path, "# P\n\n## UnRead — Smith 2019 black holes early universe\n\n" + TODO)
120+
(section,) = build_report(tmp_path, bib)
121+
assert section.author == "smith" and section.year == "2019"
122+
assert section.candidates[0]["key"] == "Smith2019"

0 commit comments

Comments
 (0)