|
| 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()) |
0 commit comments