From 0cf395439e80ffbd172e4a041ea448394f33391f Mon Sep 17 00:00:00 2001 From: Jack McCarthy <37917934+Deicyde@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:53:19 -0500 Subject: [PATCH 1/2] Write each paper's links as Literature Links annotations paper.py build now writes literature-links.jsonl beside each paper's data, one annotation per passage in links.json: the passage is the subject (a quote on its PDF page, or a generic end holding the Markdown heading, block and quotation) and its Lean declarations are the object, in the project and commit that [lean] source names. The workflow checks the files with the Literature Links checker at v1.0.2. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/pages.yml | 5 +++ docs/paper-folder.md | 10 +++++ tests/test_literature_links.py | 76 ++++++++++++++++++++++++++++++++ tools/literature_links.py | 79 ++++++++++++++++++++++++++++++++++ tools/paper.py | 2 + 5 files changed, 172 insertions(+) create mode 100644 tests/test_literature_links.py create mode 100644 tools/literature_links.py diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index 75c4ee35..37d86bfd 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -36,6 +36,11 @@ jobs: python tools/paper.py check "$(basename "$folder")" done python tools/paper.py build + # Each paper's links as Literature Links annotations, which the build writes. + - name: Check the Literature Links annotations + run: | + python -m pip install --quiet "literature-links @ git+https://github.com/mathlib-initiative/literature-links@e7eeafb823eb3bc64a8ab2077cd3569f572d459f" # v1.0.2 + literature-links scan web/public/papers --include '*/literature-links.jsonl' - run: npm run build working-directory: web env: diff --git a/docs/paper-folder.md b/docs/paper-folder.md index 0c217399..0d57bc6b 100644 --- a/docs/paper-folder.md +++ b/docs/paper-folder.md @@ -79,6 +79,16 @@ passage names them, such as lemmas used only inside proofs, so that the index an inside a proof can open them. A project whose declaration report is too large to keep can commit `generated/lean.json.gz` in place of `generated/lean.json`. +## Literature Links + +`paper.py build` also writes `literature-links.jsonl` beside the paper's data, with one +[Literature Links](https://github.com/mathlib-initiative/literature-links) annotation +for each passage in `links.json`. The passage is the subject and its Lean declarations +are the object. A PDF passage is a quote on its page, and a quote that runs over a page +break stops the build. A Markdown passage keeps its heading, block and quotation. The +Lean is the project that `[lean] source` names, at the commit in that address. The +workflow checks these files with the Literature Links checker. + ## Comparator runs A page can show a [Comparator](https://github.com/leanprover/comparator) run. Name the diff --git a/tests/test_literature_links.py b/tests/test_literature_links.py new file mode 100644 index 00000000..bedb6f79 --- /dev/null +++ b/tests/test_literature_links.py @@ -0,0 +1,76 @@ +"""Each passage becomes one Literature Links annotation.""" + +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "tools")) +import literature_links + +SHA = "0" * 64 +COMMIT = "a" * 40 + + +def edition(kind, passages, source=f"https://github.com/owner/repo/tree/{COMMIT}"): + return { + "source": {"kind": kind, "sha256": SHA}, + "lean": {"source": source}, + "declarations": [{"id": "Foo.bar", "file": "lean/Foo/Basic.lean"}, + {"id": "Foo.baz", "file": "lean/Foo/Other.lean"}], + "claims": [{"id": "main", "title": "The main theorem", "passage": "p1"}], + "passages": passages, + } + + +def pdf_passage(**fields): + return {"id": "p1", "role": "states", "quote": "every bar\nis baz", "lean": ["Foo.bar"], + "page": 3, "last_page": 3, **fields} + + +class Annotations(unittest.TestCase): + def test_a_pdf_passage_is_a_quote_on_its_page(self): + [found] = literature_links.annotations(edition("pdf", [pdf_passage()])) + self.assertEqual(found, { + "subject": [{"type": "pdf", "uri": "paper.pdf", + "location": {"page": 3, "quote": {"exact": "every bar is baz"}}, + "sha256": SHA, "role": "states", "title": "The main theorem"}], + "object": [{"type": "lean", "uri": "https://github.com/owner/repo", "version": COMMIT, + "location": {"declaration": "Foo.bar", "module": "Foo.Basic"}}], + "id": "p1"}) + + def test_a_markdown_passage_keeps_its_heading_block_and_quote(self): + passage = {"id": "m1", "role": "explains", "quote": "shown", "source_quote": "raw `quote`", + "anchor": {"heading": "Intro", "block": 2}, "lean": ["Foo.bar"], "title": "A title"} + [found] = literature_links.annotations(edition("markdown", [passage])) + self.assertEqual(found["subject"], [{ + "type": "generic", "uri": "source.md", + "location": {"profile": literature_links.MARKDOWN_PROFILE, "heading": "Intro", "block": 2, + "quote": "raw `quote`"}, + "sha256": SHA, "role": "explains", "title": "A title"}]) + + def test_a_project_in_a_folder_keeps_the_folder(self): + folder = f"https://github.com/owner/repo/tree/{COMMIT}/lean" + [found] = literature_links.annotations(edition("pdf", [pdf_passage()], source=folder)) + self.assertEqual((found["object"][0]["uri"], found["object"][0]["version"]), (folder, COMMIT)) + + def test_lines_narrow_only_the_first_declaration(self): + [found] = literature_links.annotations(edition("pdf", [pdf_passage(lean=["Foo.bar", "Foo.baz"], lines=[4, 6])])) + self.assertEqual([end["location"] for end in found["object"]], [ + {"declaration": "Foo.bar", "module": "Foo.Basic", "lines": [4, 6]}, + {"declaration": "Foo.baz", "module": "Foo.Other"}]) + + def test_an_unlinked_passage_has_an_empty_object(self): + [found] = literature_links.annotations(edition("pdf", [pdf_passage(lean=[])])) + self.assertEqual(found["object"], []) + + def test_a_quote_over_a_page_break_is_refused(self): + with self.assertRaises(ValueError): + literature_links.annotations(edition("pdf", [pdf_passage(last_page=4)])) + + def test_the_project_needs_an_address(self): + with self.assertRaises(ValueError): + literature_links.annotations(edition("pdf", [pdf_passage()], source="")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/literature_links.py b/tools/literature_links.py new file mode 100644 index 00000000..33480d22 --- /dev/null +++ b/tools/literature_links.py @@ -0,0 +1,79 @@ +"""A paper's links as Literature Links annotations. + +`paper.py build` writes literature-links.jsonl beside each paper's data: one +annotation for each passage in links.json, with the passage as the subject and its +Lean declarations as the object. The format and its checker are at +https://github.com/mathlib-initiative/literature-links. + +Standard library only. +""" +from __future__ import annotations + +import json +import re +from pathlib import Path + +FILE = "literature-links.jsonl" +# The names `paper.py build` gives the source beside this file. +PDF, MARKDOWN = "paper.pdf", "source.md" +# How a passage of a Markdown source is found: an exact quotation that occurs once in +# the source, inside the numbered block under the heading. +MARKDOWN_PROFILE = "https://github.com/wcook04/proof-reader/blob/main/docs/paper-folder.md#markdown-papers" +# A folder of a GitHub repository at a commit, as `[lean] source` names a project. +GITHUB_TREE = re.compile(r"(https://github\.com/[^/]+/[^/]+)/tree/([0-9a-f]{40})(/.+)?") +# The format's white space; a quote writes each run of it as one space. +WHITE_SPACE = re.compile("[\t-\r \x85\xa0  - 

   ]+") + + +def lean_end(source: str) -> dict: + """The Lean project. A project at the root of its repository is the repository at + that commit; one in a folder keeps the folder's address.""" + if not source: + raise ValueError("[lean] source must give the Lean project's address for Literature Links") + tree = GITHUB_TREE.fullmatch(source) + if not tree: + return {"type": "lean", "uri": source} + return {"type": "lean", "uri": source if tree[3] else tree[1], "version": tree[2]} + + +def subject(built: dict, passage: dict, title: str | None) -> dict: + if built["source"]["kind"] == "pdf": + if passage["last_page"] != passage["page"]: + raise ValueError(f"passage {passage['id']}: runs from page {passage['page']} to page {passage['last_page']}, " + "but a Literature Links quote stays on one page") + end = {"type": "pdf", "uri": PDF, "location": { + "page": passage["page"], "quote": {"exact": WHITE_SPACE.sub(" ", passage["quote"]).strip()}}} + else: + end = {"type": "generic", "uri": MARKDOWN, "location": { + "profile": MARKDOWN_PROFILE, "heading": passage["anchor"]["heading"], + "block": passage["anchor"]["block"], "quote": passage["source_quote"]}} + end["sha256"] = built["source"]["sha256"] + end["role"] = passage["role"] + if title: + end["title"] = title + return end + + +def annotations(built: dict) -> list[dict]: + """One annotation for each passage of a built edition, in reading order.""" + project = lean_end(built["lean"].get("source", "")) + modules = {d["id"]: d["file"].removeprefix("lean/").removesuffix(".lean").replace("/", ".") + for d in built["declarations"]} + titles = {claim["passage"]: claim["title"] for claim in built["claims"]} + found = [] + for passage in built["passages"]: + ends = [] + for index, name in enumerate(passage["lean"]): + location = {"declaration": name, "module": modules[name]} + # A passage's lines narrow its first declaration. + if index == 0 and passage.get("lines"): + location["lines"] = passage["lines"] + ends.append({**project, "location": location}) + title = passage.get("title") or titles.get(passage["id"]) + found.append({"subject": [subject(built, passage, title)], "object": ends, "id": passage["id"]}) + return found + + +def write(built: dict, folder: Path) -> None: + lines = (json.dumps(a, ensure_ascii=False, separators=(",", ":")) + "\n" for a in annotations(built)) + (folder / FILE).write_text("".join(lines), encoding="utf-8") diff --git a/tools/paper.py b/tools/paper.py index 174e09b5..7e5aa264 100644 --- a/tools/paper.py +++ b/tools/paper.py @@ -30,6 +30,7 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) +import literature_links # noqa: E402 import reading as reading_copy # noqa: E402 import physlib_map # noqa: E402 @@ -1163,6 +1164,7 @@ def build(slugs: list[str]) -> None: folder = PAPERS / slug out = PUBLIC / slug out.mkdir(exist_ok=True) + literature_links.write(built, out) page = built.pop("reading_html") (out / "reading.html").unlink(missing_ok=True) if page: From 69cff3dd2dbeef797f5e1f1bd36374acb7314bfa Mon Sep 17 00:00:00 2001 From: Jack McCarthy <37917934+Deicyde@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:09:23 -0500 Subject: [PATCH 2/2] Write no Literature Links file for a paper without [lean] source [lean] source is optional, and test_markdown's papers leave it out, so the build skips the file for such a paper instead of stopping. Co-Authored-By: Claude Opus 5.5 --- docs/paper-folder.md | 5 +++-- tests/test_literature_links.py | 12 +++++++++--- tools/literature_links.py | 7 ++++++- 3 files changed, 18 insertions(+), 6 deletions(-) diff --git a/docs/paper-folder.md b/docs/paper-folder.md index 0d57bc6b..c41061de 100644 --- a/docs/paper-folder.md +++ b/docs/paper-folder.md @@ -86,8 +86,9 @@ commit `generated/lean.json.gz` in place of `generated/lean.json`. for each passage in `links.json`. The passage is the subject and its Lean declarations are the object. A PDF passage is a quote on its page, and a quote that runs over a page break stops the build. A Markdown passage keeps its heading, block and quotation. The -Lean is the project that `[lean] source` names, at the commit in that address. The -workflow checks these files with the Literature Links checker. +Lean is the project that `[lean] source` names, at the commit in that address, and a +paper without a `[lean] source` gets no file. The workflow checks these files with the +Literature Links checker. ## Comparator runs diff --git a/tests/test_literature_links.py b/tests/test_literature_links.py index bedb6f79..95be3870 100644 --- a/tests/test_literature_links.py +++ b/tests/test_literature_links.py @@ -1,6 +1,7 @@ """Each passage becomes one Literature Links annotation.""" import sys +import tempfile import unittest from pathlib import Path @@ -67,9 +68,14 @@ def test_a_quote_over_a_page_break_is_refused(self): with self.assertRaises(ValueError): literature_links.annotations(edition("pdf", [pdf_passage(last_page=4)])) - def test_the_project_needs_an_address(self): - with self.assertRaises(ValueError): - literature_links.annotations(edition("pdf", [pdf_passage()], source="")) + def test_a_paper_whose_project_has_no_address_gets_no_file(self): + with tempfile.TemporaryDirectory() as scratch: + stale = Path(scratch) / literature_links.FILE + stale.write_text("{}\n", encoding="utf-8") + literature_links.write(edition("pdf", [pdf_passage()], source=""), Path(scratch)) + self.assertFalse(stale.exists()) + literature_links.write(edition("pdf", [pdf_passage()]), Path(scratch)) + self.assertEqual(len(stale.read_text(encoding="utf-8").splitlines()), 1) if __name__ == "__main__": diff --git a/tools/literature_links.py b/tools/literature_links.py index 33480d22..bdb9b42b 100644 --- a/tools/literature_links.py +++ b/tools/literature_links.py @@ -75,5 +75,10 @@ def annotations(built: dict) -> list[dict]: def write(built: dict, folder: Path) -> None: + """Write the annotations; a paper whose Lean project has no address gets none.""" + path = folder / FILE + path.unlink(missing_ok=True) + if not built["lean"].get("source"): + return lines = (json.dumps(a, ensure_ascii=False, separators=(",", ":")) + "\n" for a in annotations(built)) - (folder / FILE).write_text("".join(lines), encoding="utf-8") + path.write_text("".join(lines), encoding="utf-8")