Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .github/workflows/pages.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
11 changes: 11 additions & 0 deletions docs/paper-folder.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,17 @@ 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, and a
paper without a `[lean] source` gets no file. 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
Expand Down
82 changes: 82 additions & 0 deletions tests/test_literature_links.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
"""Each passage becomes one Literature Links annotation."""

import sys
import tempfile
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_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__":
unittest.main()
84 changes: 84 additions & 0 deletions tools/literature_links.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
"""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:
"""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))
path.write_text("".join(lines), encoding="utf-8")
2 changes: 2 additions & 0 deletions tools/paper.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand Down