|
| 1 | +"""Write llms.txt and llms-full.txt for the documentation site. |
| 2 | +
|
| 3 | +``llms.txt`` (see https://llmstxt.org) is a short Markdown file that tells AI assistants |
| 4 | +what the package is, how to use it, and where its documentation lives. ``llms-full.txt`` |
| 5 | +is the whole documentation as plain text, so an assistant can read it in a single fetch. |
| 6 | +
|
| 7 | +The package is small, so ``llms.txt`` is mostly prose: the hand-written ``llms_intro.md`` |
| 8 | +(what it does, a quick start, key points, common mistakes) followed by a generated list |
| 9 | +of links. ``llms-full.txt`` is this Sphinx site rendered by Sphinx's ``text`` builder, so |
| 10 | +the autodoc API reference is included, in the order of the toctrees, which are followed |
| 11 | +from ``index.rst`` through the nested pages. Run after the HTML build:: |
| 12 | +
|
| 13 | + make html llms # from docs/ |
| 14 | +
|
| 15 | +The files are written into ``build/html`` so they are published with the site. |
| 16 | +""" |
| 17 | + |
| 18 | +from __future__ import annotations |
| 19 | + |
| 20 | +import os |
| 21 | +import re |
| 22 | +import shutil |
| 23 | + |
| 24 | +# Used only to re-invoke `sphinx-build`, resolved via shutil.which() below; this is a |
| 25 | +# local/CI docs-build script, not code that runs against untrusted input. |
| 26 | +import subprocess # nosec B404 |
| 27 | +import sys |
| 28 | +from importlib.metadata import metadata |
| 29 | +from pathlib import Path |
| 30 | + |
| 31 | +DOCS = Path(__file__).resolve().parent |
| 32 | +SOURCE = DOCS / "source" |
| 33 | +BUILD = DOCS / "build" |
| 34 | +TEXT = BUILD / "text" |
| 35 | +HTML = BUILD / "html" |
| 36 | +INTRO = DOCS / "llms_intro.md" |
| 37 | + |
| 38 | +# One-line descriptions of the pages listed in the toctrees |
| 39 | +PAGE_NOTES = { |
| 40 | + "index": "overview", |
| 41 | + "intro": "tutorial: building a graph, vertices, edges, plotting, path planning, directed graphs", |
| 42 | + "api": "the API, in three parts: the common methods, vertices and edges, and the policy page", |
| 43 | + "common": "the methods that UGraph and DGraph share, by task", |
| 44 | + "construction": "UGraph, DGraph, Graph, constructors from a dict or an adjacency matrix, distance metrics", |
| 45 | + "modification": "adding and removing vertices and edges", |
| 46 | + "analysis": "counts, adjacency, degree, components, coordinates, spatial queries, subgraphs", |
| 47 | + "representations": "adjacency, incidence, degree and Laplacian matrices", |
| 48 | + "visualization": "plot(), its options, highlighting vertices, edges and paths", |
| 49 | + "export": "writing a graph as GraphViz dot, Mermaid, GraphML, ELK or an image", |
| 50 | + "planning": "path_BFS, path_UCS and path_Astar", |
| 51 | + "edges_vertices": "the data structures: Vertex and Edge, and the edge lists of a vertex", |
| 52 | + "policy": "object lifecycle: what may be done with a vertex or edge outside a graph", |
| 53 | +} |
| 54 | + |
| 55 | +# Links that belong in llms.txt but are not pages of this site |
| 56 | +EXTRA_LINKS = [ |
| 57 | + ("Source code", "https://github.com/petercorke/pgraph-python", "GitHub repository"), |
| 58 | + ("PyPI", "https://pypi.org/project/pgraph-python/", "install with pip install pgraph-python"), |
| 59 | + ("Changelog", "https://github.com/petercorke/pgraph-python/blob/main/CHANGELOG.md", "release history and how to migrate from 0.6"), |
| 60 | + ("Examples", "https://github.com/petercorke/pgraph-python/tree/main/examples", "Queensland and central London route-planning notebooks, and a benchmark"), |
| 61 | + ("RVC ecosystem", "https://github.com/petercorke/rvc-ecosystem", "how pgraph relates to the Robotics and Machine Vision Toolboxes"), |
| 62 | + ("Contributing", "https://github.com/petercorke/pgraph-python/blob/main/AGENTS.md", "repo conventions and workflow, for agents working on pgraph's source code"), |
| 63 | +] |
| 64 | + |
| 65 | + |
| 66 | +def toctree_entries(document: Path) -> list[str]: |
| 67 | + """Document names listed in the toctrees of one document, in order. |
| 68 | +
|
| 69 | + :param document: an ``.rst`` file |
| 70 | + :return: document names such as ``"common"`` |
| 71 | + """ |
| 72 | + entries, in_toctree = [], False |
| 73 | + for line in document.read_text().splitlines(): |
| 74 | + if line.startswith(".. toctree::"): |
| 75 | + in_toctree = True |
| 76 | + elif in_toctree and line.strip() and not line.startswith((" ", "\t")): |
| 77 | + in_toctree = False # the directive's indented body has ended |
| 78 | + elif in_toctree and line.strip() and not line.strip().startswith(":"): |
| 79 | + entries.append(line.strip()) |
| 80 | + return entries |
| 81 | + |
| 82 | + |
| 83 | +def toctree_pages(index: Path) -> list[str]: |
| 84 | + """All the documents below a master document, depth first, in toctree order. |
| 85 | +
|
| 86 | + The pages of this site are nested: ``index`` lists ``api``, which lists |
| 87 | + ``common``, which lists the pages of the common methods. |
| 88 | +
|
| 89 | + :param index: the master document, ``index.rst`` |
| 90 | + :return: document names such as ``"construction"``, each once |
| 91 | + """ |
| 92 | + pages: list[str] = [] |
| 93 | + |
| 94 | + def walk(document: Path) -> None: |
| 95 | + for name in toctree_entries(document): |
| 96 | + if name not in pages: |
| 97 | + pages.append(name) |
| 98 | + child = document.parent / f"{name}.rst" |
| 99 | + if child.exists(): |
| 100 | + walk(child) |
| 101 | + |
| 102 | + walk(index) |
| 103 | + return pages |
| 104 | + |
| 105 | + |
| 106 | +def title(text: str) -> str: |
| 107 | + """The page title: the first non-blank line that isn't an overline of punctuation.""" |
| 108 | + for line in text.splitlines(): |
| 109 | + if line.strip() and not re.fullmatch(r"[*=\-~#^]+", line.strip()): |
| 110 | + return line.strip() |
| 111 | + return "" |
| 112 | + |
| 113 | + |
| 114 | +def main() -> None: |
| 115 | + # Read the name, summary and documentation URL from the installed package's metadata |
| 116 | + # (built from pyproject.toml). Reading pyproject.toml directly would need tomllib, |
| 117 | + # which is Python 3.11+, and the Pages workflow builds the docs on 3.9. |
| 118 | + meta = metadata("pgraph-python") |
| 119 | + urls = dict(u.split(", ", 1) for u in meta.get_all("Project-URL")) |
| 120 | + base = urls["Documentation"].rstrip("/") + "/" |
| 121 | + name, summary = meta["Name"], meta["Summary"] |
| 122 | + |
| 123 | + # SPHINXBUILD matches the override convention of docs/Makefile's |
| 124 | + # `SPHINXBUILD ?= sphinx-build` -- resolved via shutil.which() to a full path. |
| 125 | + sphinxbuild_name = os.environ.get("SPHINXBUILD", "sphinx-build") |
| 126 | + sphinxbuild = shutil.which(sphinxbuild_name) |
| 127 | + if sphinxbuild is None: |
| 128 | + raise SystemExit(f"sphinx-build not found: {sphinxbuild_name!r}") |
| 129 | + subprocess.run( # nosec B603 -- sphinxbuild resolved via shutil.which() above # nosemgrep: python.lang.security.audit.dangerous-subprocess-use-audit.dangerous-subprocess-use-audit |
| 130 | + [sphinxbuild, "-q", "-b", "text", str(SOURCE), str(TEXT)], # nosemgrep: python.lang.security.audit.dangerous-subprocess-use-tainted-env-args.dangerous-subprocess-use-tainted-env-args |
| 131 | + check=True, |
| 132 | + ) |
| 133 | + pages = ["index"] + toctree_pages(SOURCE / "index.rst") |
| 134 | + texts = {p: (TEXT / f"{p}.txt").read_text() for p in pages} |
| 135 | + |
| 136 | + # llms.txt: prose introduction, then links |
| 137 | + index = [ |
| 138 | + f"# {name}", |
| 139 | + "", |
| 140 | + f"> {summary}.", |
| 141 | + "", |
| 142 | + INTRO.read_text().strip(), |
| 143 | + "", |
| 144 | + "## Documentation", |
| 145 | + "", |
| 146 | + f"The whole documentation, including the API reference, is available as a single text file: [llms-full.txt]({base}llms-full.txt).", |
| 147 | + "", |
| 148 | + *(f"- [{title(texts[p])}]({base}{p}.html): {PAGE_NOTES.get(p, '')}" for p in pages), |
| 149 | + "", |
| 150 | + "## Optional", |
| 151 | + "", |
| 152 | + *(f"- [{label}]({url}): {note}" for label, url, note in EXTRA_LINKS), |
| 153 | + "", |
| 154 | + ] |
| 155 | + HTML.mkdir(parents=True, exist_ok=True) |
| 156 | + (HTML / "llms.txt").write_text("\n".join(index)) |
| 157 | + |
| 158 | + # llms-full.txt: the prose introduction, then every page |
| 159 | + def block(url: str, body: str) -> str: |
| 160 | + return f"\n{'=' * 72}\nPage: {url}\n{'=' * 72}\n\n{body.strip()}\n" |
| 161 | + |
| 162 | + parts = [f"# {name}: {summary}\n\nDocumentation: {base}\n\n{INTRO.read_text().strip()}\n"] |
| 163 | + parts += [block(f"{base}{p}.html", texts[p]) for p in pages] |
| 164 | + full = re.sub(r"\n{3,}", "\n\n", "".join(parts)) # the text builder leaves runs of blank lines |
| 165 | + (HTML / "llms-full.txt").write_text(full) |
| 166 | + print(f"llms.txt: {len(pages)} pages; llms-full.txt: {len(full) // 1000} kB", file=sys.stderr) |
| 167 | + |
| 168 | + |
| 169 | +if __name__ == "__main__": |
| 170 | + main() |
0 commit comments