SameerMesiah97 commented on code in PR #74536:
URL: https://github.com/apache/airflow/pull/74536#discussion_r4728491467


##########
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:
   _clean_markdown doctree now normalizes punctuation just before Markdown 
output:



-- 
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]

Reply via email to