Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Clean HN extracts through the justext pipeline before indexing

Daoud Clarke52db7d520221
diff --git a/mwmbl/crawler/retrieve.py b/mwmbl/crawler/retrieve.py
index 9cbef7a..5d02344 100644
--- a/mwmbl/crawler/retrieve.py
+++ b/mwmbl/crawler/retrieve.py
@@ -151,6 +151,25 @@ def get_new_links(paragraphs: list[Paragraph], current_url):
return new_links, extra_links
+def extract_from_html_text(html_text: str) -> str:
+ """Extract a clean plain-text snippet from an HTML fragment using the justext pipeline."""
+ html_bytes = f"<html><body>{html_text}</body></html>".encode(DEFAULT_ENCODING)
+ try:
+ dom = html_to_dom(html_bytes, DEFAULT_ENCODING, None, DEFAULT_ENC_ERRORS)
+ paragraphs = core.justext_from_dom(dom, utils.get_stoplist("English"))
+ except Exception:
+ return ""
+ extract = ""
+ for paragraph in paragraphs:
+ if paragraph.class_type != "good":
+ continue
+ extract += " " + paragraph.text.strip()
+ if len(extract) > NUM_EXTRACT_CHARS:
+ extract = extract[:NUM_EXTRACT_CHARS - 1] + "…"
+ break
+ return extract.strip()
+
+
def crawl_url(url):
logger.info(url)
js_timestamp = int(time.time() * 1000)
diff --git a/mwmbl/tinysearchengine/super_search_sources/hn.py b/mwmbl/tinysearchengine/super_search_sources/hn.py
index 5e78df4..867075a 100644
--- a/mwmbl/tinysearchengine/super_search_sources/hn.py
+++ b/mwmbl/tinysearchengine/super_search_sources/hn.py
@@ -3,6 +3,7 @@ import logging
import httpx
+from mwmbl.crawler.retrieve import extract_from_html_text
from mwmbl.tinysearchengine.indexer import Document
logger = logging.getLogger(__name__)
@@ -26,7 +27,8 @@ async def search(client: httpx.AsyncClient, query: str, limit: int) -> list[Docu
for hit in payload.get("hits", []):
url = hit.get("url") or f"https://news.ycombinator.com/item?id={hit.get('objectID')}"
title = hit.get("title") or hit.get("story_title") or ""
- extract = hit.get("story_text") or hit.get("comment_text") or ""
+ raw_html = hit.get("story_text") or hit.get("comment_text") or ""
+ extract = extract_from_html_text(raw_html) if raw_html else ""
if not title and not extract:
continue
docs.append(Document(title=title, url=url, extract=extract))