Coverage for app / knowledge / web_extract.py: 97%
204 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
1"""
2Turning a crawled page into markdown that keeps its links, and telling a
3page's content links from its chrome.
5Two problems this solves for website knowledge sources:
7**Links were lost.** trafilatura is excellent at pulling an article's prose
8out of a page, but it treats link-dense regions as boilerplate — so a listing,
9index or aggregator page (a blog index, a docs contents page, the Hacker News
10front page) came back as bare titles with every URL gone, and an agent could
11only cite the listing itself. For those pages ``LinkedMarkdown`` converts the
12page's structure directly: every kept link as ``[text](absolute url)``, a
13table row as one line (so an item's title, source and score stay together).
14``extract_markdown`` picks whichever of the two keeps the page's content and
15its links.
17**Crawls wandered into chrome.** A page's links are mostly not content: vote
18and hide buttons, login and profile pages, images and feeds. ``classify_link``
19names what a link is from its URL alone, so the crawler can skip the kinds
20that are never knowledge and the extractor can drop their anchor text
21("hide", "flag") from the markdown.
22"""
24from __future__ import annotations
26import posixpath
27import re
28import urllib.parse
29from dataclasses import dataclass
30from html.parser import HTMLParser
31from typing import Literal
33from app.knowledge import passage_text
35LinkCategory = Literal[
36 "content", # a page on another site, or this site's own content
37 "action", # does something when followed: vote, hide, share, log out
38 "account", # login, sign-up, profiles, settings
39 "asset", # images, scripts, archives, media
40 "feed", # RSS / Atom
41]
43#: Categories the crawler never follows and the extractor never links.
44NON_CONTENT: frozenset[str] = frozenset({"action", "account", "asset", "feed"})
46#: Path segments that name an action. Matched against the first or last
47#: segment only — ``/posts/12/edit`` is an action, ``/docs/edit-mode`` is not.
48_ACTION_SEGMENTS = frozenset(
49 {
50 "vote", "upvote", "downvote", "flag", "hide", "unhide", "fave",
51 "favorite", "favourite", "unfave", "bookmark", "reply", "submit",
52 "edit", "delete", "remove", "report", "share", "print", "subscribe",
53 "unsubscribe", "follow", "unfollow", "like", "unlike", "react", "rate",
54 "cart", "basket", "checkout", "add-to-cart", "wishlist", "compare",
55 "wp-admin", "xmlrpc", "logout", "log-out", "signout", "sign-out",
56 }
57) # fmt: skip
58#: First path segments that lead into accounts rather than content.
59_ACCOUNT_SEGMENTS = frozenset(
60 {
61 "login", "log-in", "signin", "sign-in", "signup", "sign-up",
62 "register", "join", "auth", "oauth", "sso", "account", "accounts",
63 "user", "users", "profile", "profiles", "member", "members", "u",
64 "settings", "preferences", "password", "forgot", "reset", "session",
65 "sessions", "my", "me", "wp-login",
66 }
67) # fmt: skip
68#: Query keys that make a URL an action or an auth hop whatever its path.
69_ACTION_QUERY_KEYS = frozenset(
70 {
71 "auth", "token", "csrf", "csrf_token", "nonce", "action", "do",
72 "goto", "redirect", "redirect_uri", "redirect_url", "return",
73 "returnto", "return_to", "returnurl", "next", "logout", "replytocom",
74 "share", "print", "vote",
75 }
76) # fmt: skip
77_ASSET_EXTENSIONS = frozenset(
78 {
79 "jpg", "jpeg", "png", "gif", "webp", "avif", "svg", "ico", "bmp",
80 "css", "js", "mjs", "map", "woff", "woff2", "ttf", "otf", "eot",
81 "zip", "gz", "tgz", "tar", "rar", "7z", "bz2", "xz", "exe", "dmg",
82 "msi", "pkg", "deb", "rpm", "apk", "iso", "bin", "mp3", "wav",
83 "ogg", "flac", "mp4", "mov", "avi", "mkv", "webm", "m4a", "m4v",
84 }
85) # fmt: skip
86_FEED_EXTENSIONS = frozenset({"rss", "atom"})
87_FEED_SEGMENTS = frozenset({"feed", "feeds", "rss", "atom"})
89#: Tracking parameters stripped from every URL, so a page reached through a
90#: campaign link is the same page as one reached directly.
91_TRACKING_PARAMS = frozenset(
92 {
93 "fbclid", "gclid", "dclid", "gbraid", "wbraid", "msclkid", "yclid",
94 "mc_cid", "mc_eid", "igshid", "ref_src", "ref_url", "_hsenc",
95 "_hsmi", "mkt_tok", "spm", "si",
96 }
97) # fmt: skip
100def strip_tracking(query: str) -> str:
101 """``query`` without tracking parameters (``utm_*`` and friends)."""
102 if not query:
103 return ""
104 kept = [
105 (key, value)
106 for key, value in urllib.parse.parse_qsl(query, keep_blank_values=True)
107 if not key.lower().startswith("utm_") and key.lower() not in _TRACKING_PARAMS
108 ]
109 return urllib.parse.urlencode(kept, doseq=True)
112def _host(url: str) -> str:
113 host = (urllib.parse.urlsplit(url).hostname or "").lower()
114 return host[4:] if host.startswith("www.") else host
117def classify_link(url: str, page_url: str) -> LinkCategory:
118 """What a link is, judged from its URL.
120 Deliberately conservative: a link is only called action / account /
121 asset / feed on a clear signal. Everything else is ``content`` — the
122 crawler's scope and patterns decide the rest.
123 """
124 parts = urllib.parse.urlsplit(url)
125 segments = [s.lower() for s in parts.path.split("/") if s]
126 first = segments[0] if segments else ""
127 last = segments[-1] if segments else ""
128 stem = lambda s: s.rsplit(".", 1)[0] # noqa: E731 — /login.php → login
129 ext = posixpath.splitext(last)[1].lstrip(".").lower() if last else ""
131 if ext in _ASSET_EXTENSIONS:
132 return "asset"
133 if (
134 ext in _FEED_EXTENSIONS
135 or last in _FEED_SEGMENTS
136 or stem(last) in _FEED_SEGMENTS
137 ):
138 return "feed"
139 query_keys = {
140 k.lower()
141 for k, _ in urllib.parse.parse_qsl(parts.query, keep_blank_values=True)
142 }
143 if query_keys & _ACTION_QUERY_KEYS:
144 return "action"
145 if {stem(first), stem(last)} & _ACTION_SEGMENTS:
146 return "action"
147 if stem(first) in _ACCOUNT_SEGMENTS:
148 return "account"
149 return "content"
152@dataclass(frozen=True)
153class PageLink:
154 url: str
155 text: str
156 category: LinkCategory
157 #: Inside the page's content rather than its navigation, header, footer
158 #: or sidebar — the strongest signal of a link worth following.
159 in_content: bool
160 #: Another site — a candidate for one-hop "linked page" crawling.
161 external: bool
164# ---------------------------------------------------------------------------
165# Link-preserving HTML → markdown
166# ---------------------------------------------------------------------------
168_SKIP = frozenset(
169 {
170 "script", "style", "noscript", "svg", "template", "iframe", "object",
171 "embed", "canvas", "select", "button", "form", "head", "math",
172 }
173) # fmt: skip
174#: Page chrome: its text is skipped, and its links are not "in content".
175_CHROME = frozenset({"nav", "header", "footer", "aside"})
176_BLOCK = frozenset(
177 {
178 "p", "div", "section", "article", "main", "blockquote", "pre",
179 "table", "tbody", "thead", "tfoot", "ul", "ol", "dl", "dt", "dd",
180 "figure", "figcaption", "details", "summary", "hr", "br",
181 }
182) # fmt: skip
185class LinkedMarkdown(HTMLParser):
186 """A page's structure as markdown, with its content links kept.
188 Not a general converter — just enough structure for retrieval: headings,
189 paragraphs, list items, one line per table row, emphasis dropped, and
190 every link that is content written as ``[text](absolute url)``. Links
191 that are actions (``hide``, ``vote``) lose their text too; that text is
192 interface, not knowledge.
193 """
195 def __init__(self, base_url: str) -> None:
196 super().__init__(convert_charrefs=True)
197 self.base_url = base_url
198 self.out: list[str] = []
199 self.links: list[PageLink] = []
200 self.title = ""
201 self._skip = 0
202 self._chrome = 0
203 self._in_title = False
204 self._anchor: dict | None = None
205 self._row_cells = 0
207 # -- helpers -------------------------------------------------------------
209 def _emit(self, text: str) -> None:
210 if self._anchor is not None:
211 self._anchor["text"].append(text)
212 else:
213 self.out.append(text)
215 def _resolve(self, href: str) -> str | None:
216 href = href.strip()
217 if not href or href.startswith(
218 ("#", "javascript:", "mailto:", "tel:", "data:")
219 ):
220 return None
221 from app.knowledge.web import canonical_url
223 return canonical_url(urllib.parse.urljoin(self.base_url, href))
225 # -- parser --------------------------------------------------------------
227 def handle_starttag(self, tag: str, attrs: list) -> None: # type: ignore[override]
228 tag = tag.lower()
229 attributes = dict(attrs)
230 if tag == "base" and attributes.get("href"):
231 self.base_url = urllib.parse.urljoin(self.base_url, attributes["href"])
232 if tag == "title":
233 self._in_title = True
234 if tag in _SKIP:
235 self._skip += 1
236 return
237 if tag in _CHROME:
238 self._chrome += 1
239 if self._skip:
240 return
241 if self._anchor is not None and tag != "img":
242 # Markup inside a link (a <div> in a vote button, a <span> in a
243 # title) is part of that link, not a break in the text.
244 return
245 if tag in ("h1", "h2", "h3", "h4", "h5", "h6"):
246 self.out.append("\n\n" + "#" * int(tag[1]) + " ")
247 elif tag == "li":
248 self.out.append("\n- ")
249 elif tag == "tr":
250 self.out.append("\n")
251 self._row_cells = 0
252 elif tag in ("td", "th"):
253 if self._row_cells:
254 self.out.append(" · ")
255 self._row_cells += 1
256 elif tag in _BLOCK:
257 self.out.append("\n")
258 elif tag == "img" and self._anchor is not None and attributes.get("alt"):
259 self._anchor["text"].append(attributes["alt"])
260 elif tag == "a" and self._anchor is None:
261 url = self._resolve(attributes.get("href") or "")
262 rel = (attributes.get("rel") or "").lower()
263 self._anchor = {"url": url, "text": [], "nofollow": "nofollow" in rel}
265 def handle_endtag(self, tag: str) -> None:
266 tag = tag.lower()
267 if tag == "title":
268 self._in_title = False
269 if tag in _SKIP:
270 self._skip = max(0, self._skip - 1)
271 return
272 if tag in _CHROME:
273 self._chrome = max(0, self._chrome - 1)
274 if self._skip:
275 return
276 if tag == "a" and self._anchor is not None:
277 anchor, self._anchor = self._anchor, None
278 text = re.sub(r"\s+", " ", " ".join(anchor["text"])).strip()
279 url = anchor["url"]
280 if not url:
281 self.out.append(text)
282 return
283 category = classify_link(url, self.base_url)
284 if anchor["nofollow"]:
285 # The site asks crawlers not to follow it: keep the words,
286 # never the link.
287 self.out.append(text)
288 return
289 self.links.append(
290 PageLink(
291 url=url,
292 text=text,
293 category=category,
294 in_content=not self._chrome,
295 external=_host(url) != _host(self.base_url),
296 )
297 )
298 if self._chrome:
299 return
300 if category == "action":
301 return # "hide", "flag", "vote": interface, not content
302 if category in NON_CONTENT or anchor["nofollow"] or not text:
303 self.out.append(text)
304 else:
305 self.out.append(f"[{text.replace(']', ')')}]({url})")
306 elif self._anchor is not None:
307 return
308 elif tag in _BLOCK or tag in ("li", "tr", "h1", "h2", "h3", "h4", "h5", "h6"):
309 self.out.append("\n")
311 def handle_data(self, data: str) -> None:
312 if self._in_title and not self.title:
313 self.title = data.strip()
314 if self._skip or self._chrome:
315 return
316 # Whitespace-only text is still a word break ("daveoc64 <a>4 hours
317 # ago</a>") — collapse it rather than drop it.
318 self._emit(re.sub(r"\s+", " ", data))
320 def markdown(self) -> str:
321 text = "".join(self.out)
322 lines = []
323 for raw in text.split("\n"):
324 line = re.sub(r"[ \t]+", " ", raw).strip()
325 # A row whose cells were all empty or all chrome.
326 if not line or re.fullmatch(r"[·|\-\s]*", line):
327 if lines and lines[-1] != "":
328 lines.append("")
329 continue
330 line = re.sub(r"^(· )+|( ·)+$", "", line)
331 line = re.sub(r"(\s*·\s*){2,}", " · ", line)
332 # A list rank in its own cell: "1. · Title" reads as "1. Title".
333 line = re.sub(r"^(\d+\.)\s*·\s*", r"\1 ", line)
334 # "| hide |" with the action dropped leaves "| |".
335 line = re.sub(r"(\s*\|\s*){2,}", " | ", line)
336 line = re.sub(r"^\|\s*|\s*\|$", "", line).strip()
337 line = re.sub(r"\(\s+", "(", re.sub(r"\s+\)", ")", line))
338 lines.append(line)
339 return "\n".join(lines).strip()
342def linked_markdown(html: str, base_url: str) -> tuple[str, str, list[PageLink]]:
343 """``(markdown, title, links)`` for a page, links kept inline."""
344 parser = LinkedMarkdown(base_url)
345 try:
346 parser.feed(html)
347 parser.close()
348 except Exception: # noqa: BLE001 — malformed markup: keep what parsed
349 pass
350 return parser.markdown(), parser.title, parser.links
353_MD_LINK = re.compile(r"\[([^\]]*)\]\((https?://[^)\s]+)\)")
356def markdown_links(markdown: str) -> list[tuple[str, str]]:
357 """``(text, url)`` for each link written in markdown, in order."""
358 return [(m.group(1), m.group(2)) for m in _MD_LINK.finditer(markdown)]
361def _visible_chars(markdown: str) -> int:
362 return len(re.sub(r"\s+", " ", _MD_LINK.sub(r"\1", markdown)).strip())
365#: The least an article extraction must hold to be preferred as the page.
366ARTICLE_MIN_CHARS = 200
369def extract_markdown(
370 html: str, page_url: str, *, prefer_article: bool = False
371) -> tuple[str, str | None, str | None]:
372 """The page's content as markdown with its links, ``(markdown, title,
373 published)``.
375 trafilatura when it captured the page's content *and* kept its links —
376 prose pages, docs. The structural conversion otherwise: listing, index
377 and aggregator pages, where trafilatura keeps the titles and drops the
378 URLs that make them worth reading.
380 ``prefer_article``: the caller knows the page is one article — a feed listed
381 it. Then trafilatura's text wins whenever it found any real content: the
382 link test exists to protect listings, and on an article the links it
383 "drops" are the site's navigation, which the structural conversion
384 would index into every page (a cookie banner, a menu) instead.
385 """
386 structural, title, links = linked_markdown(html, page_url)
387 content_links = {
388 link.url for link in links if link.in_content and link.category == "content"
389 }
391 article, published = "", None
392 try:
393 import trafilatura
395 article = (
396 trafilatura.extract(
397 html,
398 url=page_url,
399 output_format="markdown",
400 include_tables=True,
401 include_comments=False,
402 include_links=True,
403 include_formatting=True,
404 )
405 or ""
406 )
407 # trafilatura resolves in-page anchors against the host, not the page
408 # (``https://site#section``); they are not links worth keeping.
409 article = re.sub(r"\[([^\]]*)\]\(https?://[^)\s]*#[^)\s]*\)", r"\1", article)
410 meta = trafilatura.extract_metadata(html, default_url=page_url)
411 if meta is not None:
412 title = meta.title or title
413 published = meta.date
414 except Exception: # noqa: BLE001 — extraction is best-effort
415 article = ""
417 # Without the navigation an extraction keeps the markup of: a skip link
418 # and headings with no words (``passage_text.tidy_lines``).
419 if prefer_article and _visible_chars(article) >= ARTICLE_MIN_CHARS:
420 return passage_text.tidy_lines(article), title or None, published
421 kept = {url for _, url in markdown_links(article)} & content_links
422 article_is_complete = _visible_chars(article) >= max(
423 300, 0.5 * _visible_chars(structural)
424 )
425 keeps_links = len(content_links) < 5 or len(kept) >= 0.25 * len(content_links)
426 if article and article_is_complete and keeps_links:
427 return passage_text.tidy_lines(article), title or None, published
428 return passage_text.tidy_lines(structural), title or None, published