dabla commented on code in PR #74536:
URL: https://github.com/apache/airflow/pull/74536#discussion_r4716638043
##########
devel-common/src/docs/provider_conf.py:
##########
@@ -147,6 +148,36 @@
]
)
+# Providers that publish a Markdown copy of every page plus llms.txt for LLMs
and coding agents.
+PROVIDER_PACKAGES_WITH_LLMS_TXT = [
+ "apache-airflow-providers-common-ai",
+]
+
+
+if PACKAGE_NAME in PROVIDER_PACKAGES_WITH_LLMS_TXT:
+ extensions.append("airflow_llms_txt")
+ llms_txt_site_url =
f"https://airflow.apache.org/docs/{PACKAGE_NAME}/{PACKAGE_VERSION}/"
+ _release_tag = f"providers-{PACKAGE_ID.replace('.',
'-')}/{PACKAGE_VERSION}"
+ llms_txt_source_url =
f"https://github.com/apache/airflow/blob/{example_source_ref(_release_tag)}/"
+ llms_txt_release_source_url =
f"https://github.com/apache/airflow/blob/{_release_tag}/"
+ llms_txt_repo_root = AIRFLOW_REPO_ROOT_PATH.as_posix()
+ llms_txt_intro = (
+ f"Install with `pip install {PACKAGE_NAME}`. This index covers version
{PACKAGE_VERSION}. "
+ "Each link is a Markdown copy of a docs page; drop the trailing `.md`
for the HTML page. "
+ "Code samples are excerpts of example Dags, and each one links to the
full file."
+ )
+ llms_txt_root_description = "Package overview, its requirements and what
each optional extra installs."
+ # Long or generic pages an agent rarely needs first.
+ llms_txt_optional_docs = ["_api/**", "changelog", "security",
"installing-providers-from-sources"]
+ # Not useful to an agent at all; their Markdown copies are still published.
+ llms_txt_skip_docs = ["_api/tests/**", "commits"]
+ llms_txt_nested_enabled = False
+ # One Markdown copy per page, ``page.html.md``: what llms.txt and
``rel=alternate`` link to.
+ llms_txt_suffix_mode = "append"
+ # Run the Markdown build after the HTML build, not alongside it: both run
autoapi, which
+ # rewrites the ``_api`` sources in place while the other build may be
reading them.
+ llms_txt_build_parallel = False
Review Comment:
**[nit]** The Markdown build spell-checks every page a second time, and the
result is only right because of hook order.
The docs builder passes `-D airflow_spelling_output=<file>` to the HTML
build (`docs_builder.py` L294-295). sphinx-llm forwards every `-D` override to
its Markdown subprocess ("Preserve command-line configuration overrides from
the primary build", `sphinx_llm/txt.py`, 1.1.0). `airflow_spelling` checks
every page on `doctree-resolved` and does not look at the builder name
(`airflow_spelling.py` L177-193). So the `llms-markdown` build runs the whole
spell check again and writes the same JSON file.
I checked this with a small extension wired the same way (a config value set
through `-D`, a `doctree-resolved` and a `build-finished` handler):
```text
doctree-resolved html index
doctree-resolved llms-markdown index
build-finished llms-markdown
build-finished html
```
The Markdown run writes the file first. The HTML run then overwrites it,
because sphinx-llm waits for the subprocess at `build-finished` priority 101
and `_write_findings` runs at the default 500. The findings are therefore
correct today, but common.ai pays for a second spell check, and the result
depends on an ordering that nothing documents.
`airflow_spelling`'s docstring already says it checks "while the html
builder writes it". A builder check in its `_start` (`app.builder.name ==
"html"`) would make that true and remove the duplicate run.
##########
devel-common/src/sphinx_exts/airflow_llms_txt.py:
##########
@@ -0,0 +1,550 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Publish Markdown copies of each page and an ``llms.txt`` index for LLMs and
coding agents.
+
+`sphinx-llm <https://github.com/NVIDIA/sphinx-llm>`__ does the heavy lifting:
it runs a second
+Sphinx build with a Markdown builder, writes ``page.html.md`` next to every
``page.html`` and
+adds ``<link rel="alternate" type="text/markdown">`` to each HTML page. This
extension adds what
+Airflow docs need on top of it:
+
+* Markdown handlers for nodes the stock translator drops or misrenders:
``mermaid`` diagrams,
+ code-block captions, keyword-only ``*`` markers in API signatures and
toctree captions.
+* License-header comments are removed, so they do not open every page.
+* ``exampleinclude`` headers link to the full example file on GitHub at the
release tag, since
+ the excerpts leave out imports.
+* ``llms.txt`` is rewritten: sections follow the root toctree captions, every
link is absolute,
+ and descriptions come from each page's first paragraph rather than its first
line of text.
+* ``llms-full.txt`` holds the same pages in the same order, each headed by its
URL, with links
+ made absolute so they still work once the pages share one file.
+"""
+
+from __future__ import annotations
+
+import posixpath
+import re
+from collections.abc import Iterator
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, cast
+from urllib.parse import urljoin, urlsplit, urlunsplit
+
+from docutils import nodes
+from sphinx import addnodes
+from sphinx.errors import ExtensionError
+from sphinx.util import logging
+from sphinx.util.matching import Matcher
+from sphinx_llm.markdown_builder import SphinxLlmMarkdownBuilder,
SphinxLlmMarkdownTranslator
+from sphinx_markdown_builder.contexts import IndentContext, SubContext,
SubContextParams, TableContext
+
+from sphinx_exts.redirects import iter_redirects
+
+if TYPE_CHECKING:
+ from sphinx.application import Sphinx
+ from sphinx.domains.std import StandardDomain
+ from sphinx.environment import BuildEnvironment
+
+logger = logging.getLogger(__name__)
+
+MARKDOWN_BUILDER = SphinxLlmMarkdownBuilder.name
+# Pages whose first paragraph is shorter than this get no description rather
than a fragment.
+MIN_DESCRIPTION_LENGTH = 20
+MAX_DESCRIPTION_LENGTH = 240
+_SENTENCE_END = re.compile(r"(?<=[.!?])\s+(?=[A-Z`])")
+# Paragraphs under these are not the page's own opening prose.
+_NOT_PROSE = (
+ nodes.Admonition,
+ nodes.comment,
+ nodes.compound,
+ nodes.list_item,
+ nodes.system_message,
+ nodes.table,
+ nodes.topic,
+ addnodes.desc,
+)
+# llms.txt is built from the HTML build's doctrees, where Sphinx has already
curled the quotes.
+# The files are served without a charset, so keep them ASCII (see
SMARTQUOTES_EXCLUDES).
+_TYPOGRAPHY = str.maketrans(
+ {
+ "\u2018": "'",
+ "\u2019": "'",
+ "\u201c": '"',
+ "\u201d": '"',
+ "\u2013": "-",
+ "\u2014": "-",
+ "\u2026": "...",
+ "\u00a0": " ",
+ }
+)
+_INLINE_CODE = re.compile(r"(`[^`]*`)")
+_MARKDOWN_LINK = re.compile(r"(\]\()([^)\s]+)(\))")
+
+
+class CompactTableContext(TableContext):
+ """
+ A pipe table without the column padding.
+
+ ``tabulate`` pads every cell to the widest one in its column, which is
pure whitespace to a
+ model reading the file: about a tenth of ``llms-full.txt`` before this.
+ """
+
+ def make(self) -> str:
+ ctx = SubContext()
+ prefix = self.internal_context.make()
+ if prefix:
+ ctx.add(prefix)
+ rows = [self.make_row(row) for row in [*self.headers, *self.body]]
+ if rows:
+ width = max(len(row) for row in rows)
+ lines = [
+ "| "
+ + " | ".join(cell.replace("|", r"\|") for cell in [*row, *[""]
* (width - len(row))])
+ + " |"
+ for row in rows
+ ]
+ lines.insert(1, "|" + "---|" * width)
+ ctx.add("\n".join(lines), prefix_eol=2)
+ return ctx.make()
+
+
+class AirflowMarkdownTranslator(SphinxLlmMarkdownTranslator):
+ """Render the Sphinx nodes Airflow docs use that sphinx-markdown-builder
skips or misrenders."""
+
+ def _push_box(self, title: str) -> None:
+ # Admonitions become a quoted block that starts with their label,
rather than an
+ # ``#### NOTE`` heading that breaks the heading order and never says
where the note ends.
+ self._push_context(IndentContext("> ", empty=True,
params=SubContextParams(2, 2)))
+ self.add(f"**{title.capitalize()}:**", suffix_eol=2)
+
+ def _fetch_ref_uri(self, node: nodes.reference) -> str:
+ # A link to a section on the same page (```Confidence`_``) has a refid
but no refuri and
+ # no ``internal`` flag, so the base translators leave its target empty.
+ if node.get("refid") and not node.get("refuri"):
+ return self.builder.link_token(self.builder.current_doc_name,
node["refid"])
+ return super()._fetch_ref_uri(node)
+
+ def visit_meta(self, node: nodes.Element) -> None:
+ raise nodes.SkipNode
+
+ def visit_toctree(self, node: addnodes.toctree) -> None:
+ # Hidden toctrees can reach the writer unresolved; like HTML, show
nothing for them.
+ # Visible ones are resolved into link lists before this, so any left
are unexpected.
+ if not node.get("hidden"):
+ super().unknown_visit(node)
+ raise nodes.SkipNode
+
+ def visit_table(self, node: nodes.Element) -> None:
+ self._push_context(CompactTableContext(params=SubContextParams(2, 1)))
+
+ def depart_table(self, node: nodes.Element) -> None:
+ self._pop_context(node)
+
+ def visit_mermaid(self, node: nodes.Element) -> None:
+ self.add(f"```mermaid\n{node['code'].strip()}\n```", prefix_eol=2,
suffix_eol=2)
+ raise nodes.SkipNode
+
+ def visit_caption(self, node: nodes.Element) -> None:
+ self.add(f"**{node.astext()}**", prefix_eol=2, suffix_eol=1)
+ raise nodes.SkipNode
+
+ # ``abbreviation`` wraps the bare ``*`` that marks keyword-only parameters
in signatures.
+ def visit_abbreviation(self, node: nodes.Element) -> None:
+ pass
+
+ def depart_abbreviation(self, node: nodes.Element) -> None:
+ pass
+
+ def visit_title(self, node: nodes.Element) -> None:
+ # Render navigation captions in bold rather than as section headings.
+ parent = node.parent
+ if (isinstance(parent, addnodes.compact_paragraph) and
parent.get("toctree")) or (
+ isinstance(parent, nodes.compound) and "toctree-wrapper" in
parent.get("classes", [])
+ ):
+ self.add(f"**{node.astext()}**", prefix_eol=2, suffix_eol=1)
+ raise nodes.SkipNode
+
+ super().visit_title(node)
+
+ def depart_title(self, node: nodes.Element) -> None:
+ self._pop_context(node)
+
+
+def _escape_link_text(text: str) -> str:
+ return text.replace("[", r"\[").replace("]", r"\]")
+
+
+def _inline_markdown(node: nodes.Node, env: BuildEnvironment) -> str:
+ """Flatten a title or paragraph to one line of Markdown, keeping inline
code as code."""
+ parts: list[str] = []
+ for child in node.children:
+ if isinstance(child, addnodes.pending_xref) and not
child.get("refexplicit"):
+ parts.append(_xref_title(child, env) or _inline_markdown(child,
env))
+ elif isinstance(child, nodes.literal):
+ parts.append(f"`{child.astext()}`")
+ elif isinstance(child, nodes.Text):
+ parts.append(child.astext())
+ elif isinstance(child, nodes.Element):
+ parts.append(_inline_markdown(child, env))
+ return re.sub(r"\s+", " ", "".join(parts)).strip().translate(_TYPOGRAPHY)
+
+
+def _xref_title(xref: addnodes.pending_xref, env: BuildEnvironment) -> str |
None:
+ """
+ Return the title a ``:doc:`` or ``:ref:`` without explicit text resolves
to.
+
+ Doctrees read back from the environment are unresolved, so such a
reference still holds its
+ raw target (``operators/llm``) rather than the page or section title the
HTML shows.
+ """
+ target = xref.get("reftarget", "")
+ if xref.get("reftype") == "doc":
+ refdoc = xref.get("refdoc", "")
+ docname = (
+ target.lstrip("/")
+ if target.startswith("/")
+ else posixpath.join(posixpath.dirname(refdoc), target)
+ )
+ title = env.titles.get(posixpath.normpath(docname))
+ return _inline_markdown(title, env) if title else None
+ if xref.get("reftype") == "ref":
+ domain = cast("StandardDomain", env.get_domain("std"))
+ label = domain.labels.get(target.lower())
+ return label[2] if label else None
+ return None
+
+
+def _is_markdown_build(app: Sphinx) -> bool:
+ return app.builder is not None and app.builder.name == MARKDOWN_BUILDER
+
+
+def _remember_example_sources(app: Sphinx, doctree: nodes.document) -> None:
+ """Preserve example filenames before exampleinclude replaces its
headers."""
+ from exampleinclude import ExampleHeader
Review Comment:
**[nit]** The function-level import lost the comment that explained it.
The earlier version said: "Imported by bare name, as conf.py loads it:
another import path gives a different class." That explains two things a reader
would otherwise "fix":
- the import is not at module top, because `exampleinclude` is only
importable once `conf.py` has put `sphinx_exts/` on `sys.path`;
- it must not become `from sphinx_exts.exampleinclude import ExampleHeader`.
That import path loads a second module object, its `ExampleHeader` class is a
different class, and `findall` would then match nothing.
Please put the one-line comment back above the import ([PEP 8,
*Comments*](https://peps.python.org/pep-0008/#comments): a comment says why,
when the code cannot).
##########
devel-common/src/sphinx_exts/airflow_llms_txt.py:
##########
@@ -0,0 +1,550 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Publish Markdown copies of each page and an ``llms.txt`` index for LLMs and
coding agents.
+
+`sphinx-llm <https://github.com/NVIDIA/sphinx-llm>`__ does the heavy lifting:
it runs a second
+Sphinx build with a Markdown builder, writes ``page.html.md`` next to every
``page.html`` and
+adds ``<link rel="alternate" type="text/markdown">`` to each HTML page. This
extension adds what
+Airflow docs need on top of it:
+
+* Markdown handlers for nodes the stock translator drops or misrenders:
``mermaid`` diagrams,
+ code-block captions, keyword-only ``*`` markers in API signatures and
toctree captions.
+* License-header comments are removed, so they do not open every page.
+* ``exampleinclude`` headers link to the full example file on GitHub at the
release tag, since
+ the excerpts leave out imports.
+* ``llms.txt`` is rewritten: sections follow the root toctree captions, every
link is absolute,
+ and descriptions come from each page's first paragraph rather than its first
line of text.
+* ``llms-full.txt`` holds the same pages in the same order, each headed by its
URL, with links
+ made absolute so they still work once the pages share one file.
+"""
+
+from __future__ import annotations
+
+import posixpath
+import re
+from collections.abc import Iterator
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, cast
+from urllib.parse import urljoin, urlsplit, urlunsplit
+
+from docutils import nodes
+from sphinx import addnodes
+from sphinx.errors import ExtensionError
+from sphinx.util import logging
+from sphinx.util.matching import Matcher
+from sphinx_llm.markdown_builder import SphinxLlmMarkdownBuilder,
SphinxLlmMarkdownTranslator
+from sphinx_markdown_builder.contexts import IndentContext, SubContext,
SubContextParams, TableContext
+
+from sphinx_exts.redirects import iter_redirects
+
+if TYPE_CHECKING:
+ from sphinx.application import Sphinx
+ from sphinx.domains.std import StandardDomain
+ from sphinx.environment import BuildEnvironment
+
+logger = logging.getLogger(__name__)
+
+MARKDOWN_BUILDER = SphinxLlmMarkdownBuilder.name
+# Pages whose first paragraph is shorter than this get no description rather
than a fragment.
+MIN_DESCRIPTION_LENGTH = 20
+MAX_DESCRIPTION_LENGTH = 240
+_SENTENCE_END = re.compile(r"(?<=[.!?])\s+(?=[A-Z`])")
+# Paragraphs under these are not the page's own opening prose.
+_NOT_PROSE = (
+ nodes.Admonition,
+ nodes.comment,
+ nodes.compound,
+ nodes.list_item,
+ nodes.system_message,
+ nodes.table,
+ nodes.topic,
+ addnodes.desc,
+)
+# llms.txt is built from the HTML build's doctrees, where Sphinx has already
curled the quotes.
+# The files are served without a charset, so keep them ASCII (see
SMARTQUOTES_EXCLUDES).
+_TYPOGRAPHY = str.maketrans(
+ {
+ "\u2018": "'",
+ "\u2019": "'",
+ "\u201c": '"',
+ "\u201d": '"',
+ "\u2013": "-",
+ "\u2014": "-",
+ "\u2026": "...",
+ "\u00a0": " ",
+ }
+)
+_INLINE_CODE = re.compile(r"(`[^`]*`)")
+_MARKDOWN_LINK = re.compile(r"(\]\()([^)\s]+)(\))")
+
+
+class CompactTableContext(TableContext):
+ """
+ A pipe table without the column padding.
+
+ ``tabulate`` pads every cell to the widest one in its column, which is
pure whitespace to a
+ model reading the file: about a tenth of ``llms-full.txt`` before this.
+ """
+
+ def make(self) -> str:
+ ctx = SubContext()
+ prefix = self.internal_context.make()
+ if prefix:
+ ctx.add(prefix)
+ rows = [self.make_row(row) for row in [*self.headers, *self.body]]
+ if rows:
+ width = max(len(row) for row in rows)
+ lines = [
+ "| "
+ + " | ".join(cell.replace("|", r"\|") for cell in [*row, *[""]
* (width - len(row))])
+ + " |"
+ for row in rows
+ ]
+ lines.insert(1, "|" + "---|" * width)
+ ctx.add("\n".join(lines), prefix_eol=2)
+ return ctx.make()
+
+
+class AirflowMarkdownTranslator(SphinxLlmMarkdownTranslator):
+ """Render the Sphinx nodes Airflow docs use that sphinx-markdown-builder
skips or misrenders."""
+
+ def _push_box(self, title: str) -> None:
+ # Admonitions become a quoted block that starts with their label,
rather than an
+ # ``#### NOTE`` heading that breaks the heading order and never says
where the note ends.
+ self._push_context(IndentContext("> ", empty=True,
params=SubContextParams(2, 2)))
+ self.add(f"**{title.capitalize()}:**", suffix_eol=2)
+
+ def _fetch_ref_uri(self, node: nodes.reference) -> str:
+ # A link to a section on the same page (```Confidence`_``) has a refid
but no refuri and
+ # no ``internal`` flag, so the base translators leave its target empty.
+ if node.get("refid") and not node.get("refuri"):
+ return self.builder.link_token(self.builder.current_doc_name,
node["refid"])
+ return super()._fetch_ref_uri(node)
+
+ def visit_meta(self, node: nodes.Element) -> None:
+ raise nodes.SkipNode
+
+ def visit_toctree(self, node: addnodes.toctree) -> None:
+ # Hidden toctrees can reach the writer unresolved; like HTML, show
nothing for them.
+ # Visible ones are resolved into link lists before this, so any left
are unexpected.
+ if not node.get("hidden"):
+ super().unknown_visit(node)
+ raise nodes.SkipNode
+
+ def visit_table(self, node: nodes.Element) -> None:
+ self._push_context(CompactTableContext(params=SubContextParams(2, 1)))
+
+ def depart_table(self, node: nodes.Element) -> None:
+ self._pop_context(node)
+
+ def visit_mermaid(self, node: nodes.Element) -> None:
+ self.add(f"```mermaid\n{node['code'].strip()}\n```", prefix_eol=2,
suffix_eol=2)
+ raise nodes.SkipNode
+
+ def visit_caption(self, node: nodes.Element) -> None:
+ self.add(f"**{node.astext()}**", prefix_eol=2, suffix_eol=1)
+ raise nodes.SkipNode
+
+ # ``abbreviation`` wraps the bare ``*`` that marks keyword-only parameters
in signatures.
+ def visit_abbreviation(self, node: nodes.Element) -> None:
+ pass
+
+ def depart_abbreviation(self, node: nodes.Element) -> None:
+ pass
+
+ def visit_title(self, node: nodes.Element) -> None:
+ # Render navigation captions in bold rather than as section headings.
+ parent = node.parent
+ if (isinstance(parent, addnodes.compact_paragraph) and
parent.get("toctree")) or (
+ isinstance(parent, nodes.compound) and "toctree-wrapper" in
parent.get("classes", [])
+ ):
+ self.add(f"**{node.astext()}**", prefix_eol=2, suffix_eol=1)
+ raise nodes.SkipNode
+
+ super().visit_title(node)
+
+ def depart_title(self, node: nodes.Element) -> None:
+ self._pop_context(node)
+
+
+def _escape_link_text(text: str) -> str:
+ return text.replace("[", r"\[").replace("]", r"\]")
+
+
+def _inline_markdown(node: nodes.Node, env: BuildEnvironment) -> str:
+ """Flatten a title or paragraph to one line of Markdown, keeping inline
code as code."""
+ parts: list[str] = []
+ for child in node.children:
+ if isinstance(child, addnodes.pending_xref) and not
child.get("refexplicit"):
+ parts.append(_xref_title(child, env) or _inline_markdown(child,
env))
+ elif isinstance(child, nodes.literal):
+ parts.append(f"`{child.astext()}`")
+ elif isinstance(child, nodes.Text):
+ parts.append(child.astext())
+ elif isinstance(child, nodes.Element):
+ parts.append(_inline_markdown(child, env))
+ return re.sub(r"\s+", " ", "".join(parts)).strip().translate(_TYPOGRAPHY)
+
+
+def _xref_title(xref: addnodes.pending_xref, env: BuildEnvironment) -> str |
None:
+ """
+ Return the title a ``:doc:`` or ``:ref:`` without explicit text resolves
to.
+
+ Doctrees read back from the environment are unresolved, so such a
reference still holds its
+ raw target (``operators/llm``) rather than the page or section title the
HTML shows.
+ """
+ target = xref.get("reftarget", "")
+ if xref.get("reftype") == "doc":
+ refdoc = xref.get("refdoc", "")
+ docname = (
+ target.lstrip("/")
+ if target.startswith("/")
+ else posixpath.join(posixpath.dirname(refdoc), target)
+ )
+ title = env.titles.get(posixpath.normpath(docname))
+ return _inline_markdown(title, env) if title else None
+ if xref.get("reftype") == "ref":
+ domain = cast("StandardDomain", env.get_domain("std"))
+ label = domain.labels.get(target.lower())
+ return label[2] if label else None
+ return None
+
+
+def _is_markdown_build(app: Sphinx) -> bool:
+ return app.builder is not None and app.builder.name == MARKDOWN_BUILDER
+
+
+def _remember_example_sources(app: Sphinx, doctree: nodes.document) -> None:
+ """Preserve example filenames before exampleinclude replaces its
headers."""
+ from exampleinclude import ExampleHeader
+
+ for header in doctree.findall(ExampleHeader):
+ header.parent["example_source_filename"] = header["filename"]
+
+
+def _link_example_sources(app: Sphinx, doctree: nodes.document, docname: str)
-> None:
+ """Replace rendered example headers with full-source links for Markdown."""
+ if not _is_markdown_build(app):
+ return
+
+ repo_root = Path(app.config.llms_txt_repo_root).resolve()
+ source_url = app.config.llms_txt_source_url.rstrip("/")
+
+ for header in list(doctree.findall(nodes.paragraph)):
+ if (
+ "example-header" not in header.get("classes", [])
+ or "example_source_filename" not in header.parent
+ ):
+ continue
+
+ path = Path(header.parent["example_source_filename"]).resolve()
+ if not source_url or not path.is_relative_to(repo_root):
+ header.parent.remove(header)
+ continue
+
+ repo_path = path.relative_to(repo_root).as_posix()
+ paragraph = nodes.paragraph()
+ paragraph += nodes.Text("Excerpt from ")
+ link = nodes.reference("", "", refuri=f"{source_url}/{repo_path}",
internal=False)
+ link += nodes.literal(repo_path, repo_path)
+ paragraph += link
+ paragraph += nodes.Text(":")
+ header.replace_self(paragraph)
+
+
+def _clean_markdown_doctree(app: Sphinx, doctree: nodes.document, docname:
str) -> None:
Review Comment:
**[warning]** Since the separate doctree cache was removed, the `.html.md`
pages get curly quotes again.
`SMARTQUOTES_EXCLUDES` now lists `llms-markdown` so that the Markdown files
stay ASCII, because they are served without a charset (`conf_constants.py`
L77-79). The exclusion only takes effect when a page is read: Sphinx's
`SphinxSmartQuotes.is_available()` checks the builder name at read time
(`sphinx/transforms/__init__.py`, 9.1.1). With `llms_txt_build_parallel =
False`, which `provider_conf.py` sets, sphinx-llm 1.1.0 passes `-d <HTML
doctreedir>` to the Markdown subprocess (`sphinx_llm/txt.py`, "When building
sequentially we can reuse the doctree directory"). No `env` config value
differs between the two builds, so the Markdown build reuses the doctrees that
the HTML build read with smartquotes on.
To reproduce, use the `rendered_docs` setup with `smartquotes_excludes =
{"builders": ["man", "text", "spelling", "llms-markdown"]}` and the page text
`Don't "quote" this -- dash.`:
| `llms_txt_build_parallel` | `index.html.md` |
|---|---|
| `False` (what common.ai uses) | `Don’t “quote” this – dash.` |
| `True` (separate doctree directory) | `Don't "quote" this -- dash.` |
`_TYPOGRAPHY` (L78-91) already handles this for `llms.txt`, whose comment
says it reads the HTML doctrees "where Sphinx has already curled the quotes".
The pages now need the same treatment. Moving the work after reading, as was
done for the example headers, would keep the cache reuse. For example,
`_clean_markdown_doctree` could run `_TYPOGRAPHY` over the `nodes.Text` that
are not inside a `literal`, `math` or `FixedTextElement` (literal blocks, raw,
math blocks). The other way is to fix it where it is served: once part 2 of
#74376 serves `.md` with `charset=utf-8`, the `llms-markdown` exclusion and
`_TYPOGRAPHY` can both go.
The `llms_txt_reuse_doctrees = False` option that
[NVIDIA/sphinx-llm#214](https://github.com/NVIDIA/sphinx-llm/pull/214) added
after sphinx-llm#203 is not the better fix here. It is unreleased (PyPI is
still at 1.1.0), the `sphinx-llm>=1.1.0,<1.2` pin may exclude the release that
ships it, and it brings back the full second read the shared cache is meant to
avoid. The sphinx-llm maintainer said in that issue that the fix belongs in the
extension: no output-specific transformations at read time. A builder-specific
`smartquotes_excludes` entry is one of those.
Either way, please add `smartquotes_excludes` to the `rendered_docs`
fixture's `conf.py` and assert that a prose apostrophe stays ASCII. Right now
no test sets the exclusion, so nothing catches this.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]