An open source, non-profit web search engine
Crawler: fall back to meta description / first paragraph for extract
Daoud Clarked1c26ea26ba8
diff --git a/mwmbl/crawler/retrieve.py b/mwmbl/crawler/retrieve.pyindex 71ca35e..553c15e 100644--- a/mwmbl/crawler/retrieve.py+++ b/mwmbl/crawler/retrieve.py@@ -37,6 +37,10 @@ MAX_NEW_LINKS = 50MAX_EXTRA_LINKS = 50NUM_TITLE_CHARS = 65NUM_EXTRACT_CHARS = 155+# Fallback extract (first-paragraph) tuning: ignore paragraphs shorter than this+# or whose text is mostly link anchors (nav/breadcrumbs rather than prose).+MIN_FALLBACK_PARAGRAPH_CHARS = 20+MAX_FALLBACK_PARAGRAPH_LINK_DENSITY = 0.5DEFAULT_ENCODING = 'utf8'DEFAULT_ENC_ERRORS = 'replace'MAX_SITE_URLS = 100@@ -266,6 +270,39 @@ def get_og_meta(dom) -> tuple[str, str]:return og_title, og_desc+def get_meta_description(dom) -> str:+ """Return the <meta name="description"> content, or empty string."""+ for meta in dom.xpath("//meta[@name and @content]"):+ if (meta.get("name") or "").strip().lower() == "description":+ return (meta.get("content") or "").strip()+ return ""+++def get_first_paragraph(dom) -> str:+ """Return the text of the first substantive <p> element, or empty string.++ A last-resort fallback for pages where justext finds no 'good' content — most+ commonly non-English pages, where the English stoplist gives ~0 stopword+ density so genuine prose is classified as boilerplate. Paragraphs that are too+ short or dominated by link text (nav/breadcrumbs) are skipped so the snippet+ is real body text.+ """+ for p in dom.xpath("//p"):+ text = " ".join(" ".join(p.itertext()).split())+ if len(text) < MIN_FALLBACK_PARAGRAPH_CHARS:+ continue+ link_text = " ".join(" ".join(a.itertext()) for a in p.xpath(".//a"))+ link_chars = len(" ".join(link_text.split()))+ if link_chars > len(text) * MAX_FALLBACK_PARAGRAPH_LINK_DENSITY:+ continue+ return text+ return ""+++def _truncate(text: str, limit: int) -> str:+ return text[:limit - 1] + '…' if len(text) > limit else text++def crawl_url(url, redis: Redis):logger.info(url)js_timestamp = int(time.time() * 1000)@@ -372,14 +409,18 @@ def crawl_url(url, redis: Redis):extract = extract[:NUM_EXTRACT_CHARS - 1] + '…'break- # For JS-first pages (e.g. Discord, SPAs) justext finds no body content.- # Fall back to Open Graph meta tags so these pages are still indexable.+ # justext finds no body content for JS-first pages (e.g. Discord, SPAs) and+ # for non-English pages (the English stoplist classifies real prose as+ # boilerplate). Fall back, in order, to Open Graph tags, the meta description,+ # and finally the first substantive paragraph so these pages stay indexable.if not title or not extract:og_title, og_desc = get_og_meta(dom)if not title and og_title:- title = og_title[:NUM_TITLE_CHARS - 1] + '…' if len(og_title) > NUM_TITLE_CHARS else og_title- if not extract and og_desc:- extract = og_desc[:NUM_EXTRACT_CHARS - 1] + '…' if len(og_desc) > NUM_EXTRACT_CHARS else og_desc+ title = _truncate(og_title, NUM_TITLE_CHARS)+ if not extract:+ fallback = og_desc or get_meta_description(dom) or get_first_paragraph(dom)+ if fallback:+ extract = _truncate(fallback, NUM_EXTRACT_CHARS)return {'url': url,diff --git a/test/test_retrieve_extract.py b/test/test_retrieve_extract.pynew file mode 100644index 0000000..f0ad9d7--- /dev/null+++ b/test/test_retrieve_extract.py@@ -0,0 +1,93 @@+"""Tests for the extract fallbacks in mwmbl.crawler.retrieve.++justext yields no 'good' content for JS-first pages and for non-English pages+(the English stoplist classifies real prose as boilerplate). crawl_url then+falls back, in order, to Open Graph tags, the meta description, and the first+substantive paragraph. These tests cover the helpers and that fallback chain.+"""+import fakeredis++from mwmbl.crawler import retrieve+from mwmbl.crawler.retrieve import (+ get_first_paragraph,+ get_meta_description,+)+from mwmbl.justext.core import html_to_dom+++def _dom(html: str):+ return html_to_dom(html.encode("utf8"), "utf8", None, "replace")+++def test_get_meta_description():+ dom = _dom('<html><head>'+ '<meta name="Description" content=" A short summary. ">'+ '</head><body></body></html>')+ assert get_meta_description(dom) == "A short summary."+++def test_get_meta_description_absent():+ assert get_meta_description(_dom("<html><body><p>x</p></body></html>")) == ""+++def test_get_first_paragraph_returns_first_substantive():+ dom = _dom("<html><body>"+ "<p>Hi</p>" # too short, skipped+ "<p>This is the first real paragraph of body content.</p>"+ "<p>A later paragraph.</p>"+ "</body></html>")+ assert get_first_paragraph(dom) == "This is the first real paragraph of body content."+++def test_get_first_paragraph_skips_link_heavy():+ dom = _dom("<html><body>"+ '<p><a href="/a">Home</a> <a href="/b">Products</a> <a href="/c">About us</a></p>'+ "<p>The actual descriptive prose for this page lives here.</p>"+ "</body></html>")+ assert get_first_paragraph(dom) == "The actual descriptive prose for this page lives here."+++def test_get_first_paragraph_collapses_whitespace_and_nested_tags():+ dom = _dom("<html><body>"+ "<p>From <b>Proto-Finnic</b>\n *kic'as. Cognate with Finnish.</p>"+ "</body></html>")+ assert get_first_paragraph(dom) == "From Proto-Finnic *kic'as. Cognate with Finnish."+++def test_get_first_paragraph_none_when_no_body_prose():+ dom = _dom("<html><body><p>Hi</p><div>Not a paragraph element</div></body></html>")+ assert get_first_paragraph(dom) == ""+++def _crawl_html(monkeypatch, html: str) -> dict:+ monkeypatch.setattr(retrieve, "robots_allowed", lambda url, redis: True)+ monkeypatch.setattr(retrieve, "fetch", lambda url: (200, html.encode("utf8")))+ return retrieve.crawl_url("https://example.test/page", fakeredis.FakeStrictRedis())+++def test_crawl_url_falls_back_to_first_paragraph(monkeypatch):+ # No justext 'good' content (single short non-English line) and no meta tags,+ # so the extract must come from the first substantive paragraph.+ html = ("<html><head><title>kitsas</title></head><body>"+ "<p>kitsas (genitive kitsa, partitive kitsast, comparative kitsam)</p>"+ "</body></html>")+ content = _crawl_html(monkeypatch, html)["content"]+ assert content is not None+ assert content["extract"].startswith("kitsas (genitive kitsa")+++def test_crawl_url_prefers_meta_description_over_first_paragraph(monkeypatch):+ html = ('<html><head><title>t</title>'+ '<meta name="description" content="The meta summary.">'+ "</head><body><p>Some other first paragraph text here.</p></body></html>")+ content = _crawl_html(monkeypatch, html)["content"]+ assert content["extract"] == "The meta summary."+++def test_crawl_url_prefers_og_description(monkeypatch):+ html = ('<html><head><title>t</title>'+ '<meta property="og:description" content="The OG summary.">'+ '<meta name="description" content="The meta summary.">'+ "</head><body><p>Some other first paragraph text here.</p></body></html>")+ content = _crawl_html(monkeypatch, html)["content"]+ assert content["extract"] == "The OG summary."