Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Super Search v2: query-invariance gate in canonical smoke test + 22 HTML recipes

Daoud Clarkeca273ed32f56
diff --git a/mwmbl/tinysearchengine/super_search_sources/recipes/asciinema_org.yaml b/mwmbl/tinysearchengine/super_search_sources/recipes/asciinema_org.yaml
new file mode 100644
index 0000000..e2ed44f
--- /dev/null
+++ b/mwmbl/tinysearchengine/super_search_sources/recipes/asciinema_org.yaml
@@ -0,0 +1,19 @@
+name: asciinema_org
+domain: asciinema.org
+field: technology
+request:
+ url: https://asciinema.org/search
+ params:
+ q: '{query}'
+response:
+ format: html
+ results: h3
+ base_url: https://asciinema.org
+ fields:
+ title: a
+ url:
+ selector: a
+ attr: href
+smoke:
+ query: docker
+ expect_title_contains: docker
diff --git a/mwmbl/tinysearchengine/super_search_sources/recipes/codeblog_jonskeet_uk.yaml b/mwmbl/tinysearchengine/super_search_sources/recipes/codeblog_jonskeet_uk.yaml
new file mode 100644
index 0000000..3cc117d
--- /dev/null
+++ b/mwmbl/tinysearchengine/super_search_sources/recipes/codeblog_jonskeet_uk.yaml
@@ -0,0 +1,19 @@
+name: codeblog_jonskeet_uk
+domain: codeblog.jonskeet.uk
+field: programming
+request:
+ url: https://codeblog.jonskeet.uk/
+ params:
+ s: '{query}'
+response:
+ format: html
+ results: h1.entry-title
+ base_url: https://codeblog.jonskeet.uk
+ fields:
+ title: a
+ url:
+ selector: a
+ attr: href
+smoke:
+ query: design
+ expect_title_contains: design
diff --git a/mwmbl/tinysearchengine/super_search_sources/recipes/cyber_harvard_edu.yaml b/mwmbl/tinysearchengine/super_search_sources/recipes/cyber_harvard_edu.yaml
new file mode 100644
index 0000000..32a534c
--- /dev/null
+++ b/mwmbl/tinysearchengine/super_search_sources/recipes/cyber_harvard_edu.yaml
@@ -0,0 +1,19 @@
+name: cyber_harvard_edu
+domain: cyber.harvard.edu
+field: academia
+request:
+ url: https://cyber.harvard.edu/search/node
+ params:
+ keys: '{query}'
+response:
+ format: html
+ results: .views-field-title
+ base_url: https://cyber.harvard.edu
+ fields:
+ title: a
+ url:
+ selector: a
+ attr: href
+smoke:
+ query: internet
+ expect_title_contains: internet
diff --git a/mwmbl/tinysearchengine/super_search_sources/recipes/diff_wikimedia_org.yaml b/mwmbl/tinysearchengine/super_search_sources/recipes/diff_wikimedia_org.yaml
new file mode 100644
index 0000000..723999d
--- /dev/null
+++ b/mwmbl/tinysearchengine/super_search_sources/recipes/diff_wikimedia_org.yaml
@@ -0,0 +1,19 @@
+name: diff_wikimedia_org
+domain: diff.wikimedia.org
+field: tech
+request:
+ url: https://diff.wikimedia.org/
+ params:
+ s: '{query}'
+response:
+ format: html
+ results: h3.entry-title
+ base_url: https://diff.wikimedia.org
+ fields:
+ title: a
+ url:
+ selector: a
+ attr: href
+smoke:
+ query: history
+ expect_title_contains: history
diff --git a/mwmbl/tinysearchengine/super_search_sources/recipes/home_cern.yaml b/mwmbl/tinysearchengine/super_search_sources/recipes/home_cern.yaml
new file mode 100644
index 0000000..d6ff789
--- /dev/null
+++ b/mwmbl/tinysearchengine/super_search_sources/recipes/home_cern.yaml
@@ -0,0 +1,19 @@
+name: home_cern
+domain: home.cern
+field: science
+request:
+ url: https://home.cern/
+ params:
+ s: '{query}'
+response:
+ format: html
+ results: li.search-result-item
+ base_url: https://home.cern
+ fields:
+ title: a
+ url:
+ selector: a
+ attr: href
+smoke:
+ query: science
+ expect_title_contains: science
diff --git a/mwmbl/tinysearchengine/super_search_sources/recipes/itch_io.yaml b/mwmbl/tinysearchengine/super_search_sources/recipes/itch_io.yaml
new file mode 100644
index 0000000..659b6f1
--- /dev/null
+++ b/mwmbl/tinysearchengine/super_search_sources/recipes/itch_io.yaml
@@ -0,0 +1,19 @@
+name: itch_io
+domain: itch.io
+field: gaming
+request:
+ url: https://itch.io/search
+ params:
+ q: '{query}'
+response:
+ format: html
+ results: div.game_title
+ base_url: https://itch.io
+ fields:
+ title: a
+ url:
+ selector: a
+ attr: href
+smoke:
+ query: game
+ expect_title_contains: game
diff --git a/mwmbl/tinysearchengine/super_search_sources/recipes/journals_plos_org.yaml b/mwmbl/tinysearchengine/super_search_sources/recipes/journals_plos_org.yaml
new file mode 100644
index 0000000..43254c1
--- /dev/null
+++ b/mwmbl/tinysearchengine/super_search_sources/recipes/journals_plos_org.yaml
@@ -0,0 +1,19 @@
+name: journals_plos_org
+domain: journals.plos.org
+field: academia
+request:
+ url: https://plos.org
+ params:
+ s: '{query}'
+response:
+ format: html
+ results: span.post-list__post-title
+ base_url: https://journals.plos.org
+ fields:
+ title: a
+ url:
+ selector: a
+ attr: href
+smoke:
+ query: research
+ expect_title_contains: research
diff --git a/mwmbl/tinysearchengine/super_search_sources/recipes/link_springer_com.yaml b/mwmbl/tinysearchengine/super_search_sources/recipes/link_springer_com.yaml
new file mode 100644
index 0000000..f08669a
--- /dev/null
+++ b/mwmbl/tinysearchengine/super_search_sources/recipes/link_springer_com.yaml
@@ -0,0 +1,19 @@
+name: link_springer_com
+domain: link.springer.com
+field: academia
+request:
+ url: https://link.springer.com/search
+ params:
+ query: '{query}'
+response:
+ format: html
+ results: div.app-author-list.app-author-list--truncated
+ base_url: https://link.springer.com
+ fields:
+ title: a
+ url:
+ selector: a
+ attr: href
+smoke:
+ query: research
+ expect_title_contains: research
diff --git a/mwmbl/tinysearchengine/super_search_sources/recipes/phys_org.yaml b/mwmbl/tinysearchengine/super_search_sources/recipes/phys_org.yaml
new file mode 100644
index 0000000..b17a582
--- /dev/null
+++ b/mwmbl/tinysearchengine/super_search_sources/recipes/phys_org.yaml
@@ -0,0 +1,19 @@
+name: phys_org
+domain: phys.org
+field: science
+request:
+ url: https://phys.org/search/
+ params:
+ search: '{query}'
+response:
+ format: html
+ results: h4.mb-2
+ base_url: https://phys.org
+ fields:
+ title: a
+ url:
+ selector: a
+ attr: href
+smoke:
+ query: music
+ expect_title_contains: music
diff --git a/mwmbl/tinysearchengine/super_search_sources/recipes/spectrum_ieee_org.yaml b/mwmbl/tinysearchengine/super_search_sources/recipes/spectrum_ieee_org.yaml
new file mode 100644
index 0000000..9d447cc
--- /dev/null
+++ b/mwmbl/tinysearchengine/super_search_sources/recipes/spectrum_ieee_org.yaml
@@ -0,0 +1,19 @@
+name: spectrum_ieee_org
+domain: spectrum.ieee.org
+field: tech
+request:
+ url: https://spectrum.ieee.org/search/
+ params:
+ q: '{query}'
+response:
+ format: html
+ results: h2.widget__headline.h2
+ base_url: https://spectrum.ieee.org
+ fields:
+ title: a
+ url:
+ selector: a
+ attr: href
+smoke:
+ query: music
+ expect_title_contains: music
diff --git a/mwmbl/tinysearchengine/super_search_sources/recipes/theconversation_com.yaml b/mwmbl/tinysearchengine/super_search_sources/recipes/theconversation_com.yaml
new file mode 100644
index 0000000..e5b5a82
--- /dev/null
+++ b/mwmbl/tinysearchengine/super_search_sources/recipes/theconversation_com.yaml
@@ -0,0 +1,19 @@
+name: theconversation_com
+domain: theconversation.com
+field: news-politics
+request:
+ url: https://theconversation.com/uk/search
+ params:
+ q: '{query}'
+response:
+ format: html
+ results: h3.legacy
+ base_url: https://theconversation.com
+ fields:
+ title: a
+ url:
+ selector: a
+ attr: href
+smoke:
+ query: history
+ expect_title_contains: history
diff --git a/mwmbl/tinysearchengine/super_search_sources/recipes/unherd_com.yaml b/mwmbl/tinysearchengine/super_search_sources/recipes/unherd_com.yaml
new file mode 100644
index 0000000..94e9bb6
--- /dev/null
+++ b/mwmbl/tinysearchengine/super_search_sources/recipes/unherd_com.yaml
@@ -0,0 +1,19 @@
+name: unherd_com
+domain: unherd.com
+field: news-politics
+request:
+ url: https://unherd.com/
+ params:
+ s: '{query}'
+response:
+ format: html
+ results: h1
+ base_url: https://unherd.com
+ fields:
+ title: a
+ url:
+ selector: a
+ attr: href
+smoke:
+ query: music
+ expect_title_contains: music
diff --git a/mwmbl/tinysearchengine/super_search_sources/recipes/webaim_org.yaml b/mwmbl/tinysearchengine/super_search_sources/recipes/webaim_org.yaml
new file mode 100644
index 0000000..294a1c9
--- /dev/null
+++ b/mwmbl/tinysearchengine/super_search_sources/recipes/webaim_org.yaml
@@ -0,0 +1,19 @@
+name: webaim_org
+domain: webaim.org
+field: tech
+request:
+ url: https://webaim.org/search/
+ params:
+ q: '{query}'
+response:
+ format: html
+ results: h3
+ base_url: https://webaim.org
+ fields:
+ title: a
+ url:
+ selector: a
+ attr: href
+smoke:
+ query: history
+ expect_title_contains: history
diff --git a/mwmbl/tinysearchengine/super_search_sources/recipes/webkit_org.yaml b/mwmbl/tinysearchengine/super_search_sources/recipes/webkit_org.yaml
new file mode 100644
index 0000000..63c8f8c
--- /dev/null
+++ b/mwmbl/tinysearchengine/super_search_sources/recipes/webkit_org.yaml
@@ -0,0 +1,19 @@
+name: webkit_org
+domain: webkit.org
+field: programming
+request:
+ url: https://webkit.org/
+ params:
+ s: '{query}'
+response:
+ format: html
+ results: h2
+ base_url: https://webkit.org
+ fields:
+ title: a
+ url:
+ selector: a
+ attr: href
+smoke:
+ query: music
+ expect_title_contains: music
diff --git a/mwmbl/tinysearchengine/super_search_sources/recipes/www2_sqlite_org.yaml b/mwmbl/tinysearchengine/super_search_sources/recipes/www2_sqlite_org.yaml
new file mode 100644
index 0000000..ea97de6
--- /dev/null
+++ b/mwmbl/tinysearchengine/super_search_sources/recipes/www2_sqlite_org.yaml
@@ -0,0 +1,19 @@
+name: www2_sqlite_org
+domain: www2.sqlite.org
+field: programming
+request:
+ url: https://www2.sqlite.org/search
+ params:
+ q: '{query}'
+response:
+ format: html
+ results: div.nounderline
+ base_url: https://www2.sqlite.org
+ fields:
+ title: a
+ url:
+ selector: a
+ attr: href
+smoke:
+ query: history
+ expect_title_contains: history
diff --git a/mwmbl/tinysearchengine/super_search_sources/recipes/www_bellingcat_com.yaml b/mwmbl/tinysearchengine/super_search_sources/recipes/www_bellingcat_com.yaml
new file mode 100644
index 0000000..5014916
--- /dev/null
+++ b/mwmbl/tinysearchengine/super_search_sources/recipes/www_bellingcat_com.yaml
@@ -0,0 +1,19 @@
+name: www_bellingcat_com
+domain: www.bellingcat.com
+field: news-politics
+request:
+ url: https://www.bellingcat.com/
+ params:
+ s: '{query}'
+response:
+ format: html
+ results: h3
+ base_url: https://www.bellingcat.com
+ fields:
+ title: a
+ url:
+ selector: a
+ attr: href
+smoke:
+ query: history
+ expect_title_contains: history
diff --git a/mwmbl/tinysearchengine/super_search_sources/recipes/www_esa_int.yaml b/mwmbl/tinysearchengine/super_search_sources/recipes/www_esa_int.yaml
new file mode 100644
index 0000000..0cf759b
--- /dev/null
+++ b/mwmbl/tinysearchengine/super_search_sources/recipes/www_esa_int.yaml
@@ -0,0 +1,19 @@
+name: www_esa_int
+domain: www.esa.int
+field: science
+request:
+ url: https://www.esa.int/esearch
+ params:
+ q: '{query}'
+response:
+ format: html
+ results: div.grid-item.story
+ base_url: https://www.esa.int
+ fields:
+ title: a
+ url:
+ selector: a
+ attr: href
+smoke:
+ query: science
+ expect_title_contains: science
diff --git a/mwmbl/tinysearchengine/super_search_sources/recipes/www_etymonline_com.yaml b/mwmbl/tinysearchengine/super_search_sources/recipes/www_etymonline_com.yaml
new file mode 100644
index 0000000..ce545ef
--- /dev/null
+++ b/mwmbl/tinysearchengine/super_search_sources/recipes/www_etymonline_com.yaml
@@ -0,0 +1,19 @@
+name: www_etymonline_com
+domain: www.etymonline.com
+field: books-literature
+request:
+ url: https://www.etymonline.com/search
+ params:
+ q: '{query}'
+response:
+ format: html
+ results: div.flex.p-3
+ base_url: https://www.etymonline.com
+ fields:
+ title: a
+ url:
+ selector: a
+ attr: href
+smoke:
+ query: book
+ expect_title_contains: book
diff --git a/mwmbl/tinysearchengine/super_search_sources/recipes/www_howtogeek_com.yaml b/mwmbl/tinysearchengine/super_search_sources/recipes/www_howtogeek_com.yaml
new file mode 100644
index 0000000..bd727c5
--- /dev/null
+++ b/mwmbl/tinysearchengine/super_search_sources/recipes/www_howtogeek_com.yaml
@@ -0,0 +1,19 @@
+name: www_howtogeek_com
+domain: www.howtogeek.com
+field: tech
+request:
+ url: https://www.howtogeek.com/search/
+ params:
+ q: '{query}'
+response:
+ format: html
+ results: h5.display-card-title
+ base_url: https://www.howtogeek.com
+ fields:
+ title: a
+ url:
+ selector: a
+ attr: href
+smoke:
+ query: history
+ expect_title_contains: history
diff --git a/mwmbl/tinysearchengine/super_search_sources/recipes/www_neh_gov.yaml b/mwmbl/tinysearchengine/super_search_sources/recipes/www_neh_gov.yaml
new file mode 100644
index 0000000..46d2e4a
--- /dev/null
+++ b/mwmbl/tinysearchengine/super_search_sources/recipes/www_neh_gov.yaml
@@ -0,0 +1,19 @@
+name: www_neh_gov
+domain: www.neh.gov
+field: academia
+request:
+ url: https://www.neh.gov/search
+ params:
+ keywords: '{query}'
+response:
+ format: html
+ results: div.views-field.views-field-field-formatted-title
+ base_url: https://www.neh.gov
+ fields:
+ title: a
+ url:
+ selector: a
+ attr: href
+smoke:
+ query: research
+ expect_title_contains: research
diff --git a/mwmbl/tinysearchengine/super_search_sources/recipes/www_springer_com.yaml b/mwmbl/tinysearchengine/super_search_sources/recipes/www_springer_com.yaml
new file mode 100644
index 0000000..2c3764d
--- /dev/null
+++ b/mwmbl/tinysearchengine/super_search_sources/recipes/www_springer_com.yaml
@@ -0,0 +1,19 @@
+name: www_springer_com
+domain: www.springer.com
+field: academia
+request:
+ url: https://link.springer.com/search
+ params:
+ query: '{query}'
+response:
+ format: html
+ results: div.app-author-list.app-author-list--truncated
+ base_url: https://www.springer.com
+ fields:
+ title: a
+ url:
+ selector: a
+ attr: href
+smoke:
+ query: research
+ expect_title_contains: research
diff --git a/mwmbl/tinysearchengine/super_search_sources/recipes/www_whitehouse_gov.yaml b/mwmbl/tinysearchengine/super_search_sources/recipes/www_whitehouse_gov.yaml
new file mode 100644
index 0000000..92c25bb
--- /dev/null
+++ b/mwmbl/tinysearchengine/super_search_sources/recipes/www_whitehouse_gov.yaml
@@ -0,0 +1,19 @@
+name: www_whitehouse_gov
+domain: www.whitehouse.gov
+field: law-government
+request:
+ url: https://www.whitehouse.gov
+ params:
+ s: '{query}'
+response:
+ format: html
+ results: h2.has-reduced-mobile-size.wp-block-post-title
+ base_url: https://www.whitehouse.gov
+ fields:
+ title: a
+ url:
+ selector: a
+ attr: href
+smoke:
+ query: history
+ expect_title_contains: history
diff --git a/mwmbl/tinysearchengine/super_search_sources/smoke.py b/mwmbl/tinysearchengine/super_search_sources/smoke.py
new file mode 100644
index 0000000..d204e46
--- /dev/null
+++ b/mwmbl/tinysearchengine/super_search_sources/smoke.py
@@ -0,0 +1,85 @@
+"""Shared smoke-check logic for Super Search recipes.
+
+Single source of truth used by both the canonical live test
+(``test/test_super_search_smoke.py``) and the dev scripts (``smoke_recipe.py``,
+``auto_recipe_html.py``). A recipe passes if, for its ``smoke.query``, it
+returns at least one result whose title contains ``smoke.expect_title_contains``
+AND its result set is *query-sensitive*: an unrelated control query must return
+a substantially different set of URLs. A recipe that's really scraping
+nav/boilerplate returns the same links regardless of query, so a high overlap
+with the control query's results is a failure.
+"""
+from __future__ import annotations
+
+import httpx
+
+from mwmbl.tinysearchengine.super_search_sources.recipe import (
+ Recipe,
+ search_with_recipe,
+)
+
+# An unrelated control query used to prove the recipe actually *searches*. A
+# genuine search returns (almost) nothing for this gibberish.
+CONTROL_QUERY = "vrtkqlzxmn"
+# Max allowed overlap (Jaccard of result URLs) between the real query and the
+# control query before we call the recipe query-invariant boilerplate.
+MAX_CONTROL_OVERLAP = 0.5
+
+
+def control_overlap(docs, control_docs) -> float | None:
+ """Jaccard overlap of result URLs between the real and control queries.
+
+ Returns ``None`` when the control query returned nothing — we can't measure
+ overlap, and a genuinely empty control result is the strongest evidence the
+ recipe is searching rather than scraping boilerplate.
+ """
+ a = {d.url for d in docs}
+ b = {d.url for d in control_docs}
+ if not b:
+ return None
+ return len(a & b) / len(a | b)
+
+
+async def check_recipe(
+ client: httpx.AsyncClient,
+ recipe: Recipe,
+ top_n: int = 10,
+ control_query: str | None = None,
+) -> tuple[bool, str]:
+ """Run a recipe's smoke check. Returns ``(ok, reason)``.
+
+ ``reason`` is ``""`` on success, otherwise a human-readable description of
+ why the recipe failed. ``search_with_recipe`` swallows transport/parse
+ errors and returns ``[]``, so a blocked or reformatted site surfaces here as
+ a "no results" failure rather than an exception.
+ """
+ smoke = recipe.smoke or {}
+ query = smoke.get("query")
+ expect = (smoke.get("expect_title_contains") or "").lower()
+ control = control_query or smoke.get("control_query", CONTROL_QUERY)
+ if not query or not expect:
+ return False, "missing smoke.query / expect_title_contains"
+
+ docs = await search_with_recipe(client, recipe, query, top_n)
+ if not docs:
+ return False, f"no results for {query!r}"
+ if not docs[0].url or not docs[0].title:
+ return False, f"top result missing url/title: {docs[0]!r}"
+ if not any(expect in (d.title or "").lower() for d in docs):
+ titles = ", ".join((d.title or "")[:40] for d in docs[:3])
+ return False, f"no title contains {expect!r} (got: {titles})"
+
+ # Query-invariance check: if an unrelated control query returns essentially
+ # the same URLs, the recipe is scraping boilerplate, not searching.
+ try:
+ control_docs = await search_with_recipe(client, recipe, control, top_n)
+ except Exception: # noqa: BLE001
+ control_docs = []
+ overlap = control_overlap(docs, control_docs)
+ if overlap is not None and overlap >= MAX_CONTROL_OVERLAP:
+ return False, (
+ f"results barely change for control query {control!r} "
+ f"(URL overlap {overlap:.0%}) — likely scraping nav/boilerplate, "
+ f"not search results"
+ )
+ return True, ""
diff --git a/scripts/auto_recipe_html.py b/scripts/auto_recipe_html.py
new file mode 100644
index 0000000..75afe51
--- /dev/null
+++ b/scripts/auto_recipe_html.py
@@ -0,0 +1,200 @@
+#!/usr/bin/env python3
+"""Auto-generate HTML-scrape recipes from harvested search URLs.
+
+Companion to auto_recipe.py (which handles formulaic JSON APIs). This consumes
+the form/OpenSearch search-URL templates harvested by prescreen_sites.py and,
+for each, tries to detect the repeated result container on a real search page
+and emit a working HTML recipe -- so the ~115 reachable HTML-scrape sites get
+authored deterministically instead of one-by-one.
+
+For each domain it probes the search URL with a few generic queries. On a page
+it groups every plausible result link (anchor with href + reasonable text) by
+its immediate parent's (tag, class) signature; the most common such group with
+>= MIN_RESULTS members is taken to be the result list. It builds a recipe
+(results = that container selector, title = the anchor, url = the anchor href)
+and validates it in-process with the SAME smoke check as smoke_recipe.py:
+>= MIN_RESULTS docs AND the probe word echoed in some title. First passing
+(query, container) wins; the YAML is written. Existing recipes are not touched.
+
+JavaScript-only search pages (Sphinx `search.html`, framework SPAs) naturally
+fail -- the server returns no result anchors -- so they're skipped automatically.
+
+Input is the worklist JSON written by the caller: a list of
+[domain, field, kind, url_template] where url_template contains `{query}`.
+
+Usage:
+ DATABASE_URL="postgres://daoud@" uv run python scripts/auto_recipe_html.py /tmp/htmlwork.json
+"""
+from __future__ import annotations
+
+import asyncio
+import json
+import os
+import sys
+from collections import Counter
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(REPO_ROOT))
+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mwmbl.settings_dev")
+
+import django # noqa: E402
+import logging # noqa: E402
+
+django.setup()
+logging.getLogger("httpx").setLevel(logging.WARNING)
+logging.getLogger("mwmbl.tinysearchengine.super_search_sources.recipe").setLevel(
+ logging.ERROR)
+
+import httpx # noqa: E402
+import yaml # noqa: E402
+from bs4 import BeautifulSoup # noqa: E402
+
+from mwmbl.tinysearchengine.super_search_sources.recipe import ( # noqa: E402
+ Recipe, search_with_recipe,
+)
+from scripts.auto_recipe import FIELD_WORD, GENERIC_WORDS, _name # noqa: E402
+from mwmbl.tinysearchengine.super_search_sources.smoke import ( # noqa: E402
+ CONTROL_QUERY, MAX_CONTROL_OVERLAP, control_overlap,
+)
+
+RECIPES_DIR = REPO_ROOT / "mwmbl" / "tinysearchengine" / "super_search_sources" / "recipes"
+MIN_RESULTS = 3
+CONCURRENCY = 10
+TIMEOUT = 15.0
+# Bare generic tags (no class) match nav/sidebar/footer items indiscriminately;
+# only headings or class-bearing selectors reliably isolate real result rows.
+HEADING_TAGS = {"h1", "h2", "h3", "h4", "h5"}
+
+
+def _probe_words(field: str) -> list[str]:
+ words = [FIELD_WORD[field]] if field in FIELD_WORD else []
+ for w in GENERIC_WORDS:
+ if w not in words:
+ words.append(w)
+ return words[:5]
+
+
+def _class_sig(el) -> str:
+ classes = el.get("class") or []
+ if classes:
+ return el.name + "".join("." + c for c in classes[:2])
+ return el.name
+
+
+def _candidate_selectors(html: str) -> list[str]:
+ """Rank result-container selectors by how many titled links they hold."""
+ soup = BeautifulSoup(html, "html.parser")
+ groups: Counter[str] = Counter()
+ for a in soup.find_all("a", href=True):
+ href = a.get("href", "")
+ if not href or href.startswith("#") or href.startswith("javascript"):
+ continue
+ if len(a.get_text(" ", strip=True)) < 15:
+ continue
+ parent = a.parent
+ if parent is None:
+ continue
+ groups[_class_sig(parent)] += 1
+ # Keep only selectors that can isolate a result row: a heading tag, or any
+ # selector carrying a class. Reject bare generic tags (li/div/p/td/...) and
+ # obvious nav/menu chrome.
+ ranked = [(sel, n) for sel, n in groups.most_common()
+ if n >= MIN_RESULTS
+ and ("." in sel or sel in HEADING_TAGS)
+ and not any(bad in sel.lower()
+ for bad in ("menu", "nav", "footer", "header"))]
+ return [sel for sel, _ in ranked[:3]]
+
+
+async def _author(client: httpx.AsyncClient, dom: str, field: str, url_tmpl: str) -> dict:
+ name = _name(dom)
+ if (RECIPES_DIR / f"{name}.yaml").exists():
+ return {"domain": dom, "status": "exists"}
+ base = f"https://{dom}"
+ for word in _probe_words(field):
+ try:
+ r = await client.get(url_tmpl.replace("{query}", word))
+ html = r.text
+ except Exception: # noqa: BLE001
+ break # network dead -> give up on this domain
+ for selector in _candidate_selectors(html):
+ response = {
+ "format": "html", "results": selector, "base_url": base,
+ "fields": {"title": "a", "url": {"selector": "a", "attr": "href"}},
+ }
+ # Reconstruct request the same way the engine will (params from the
+ # template's query string) by just pointing url at the templated form.
+ request = {"url": url_tmpl.split("?")[0],
+ "params": _params_from(url_tmpl)}
+ recipe = Recipe(name=name, request=request, response=response,
+ domain=dom, field=field)
+ try:
+ docs = await search_with_recipe(client, recipe, word, 10)
+ except Exception: # noqa: BLE001
+ docs = []
+ if len(docs) < MIN_RESULTS or not any(
+ word in (d.title or "").lower() for d in docs):
+ continue
+ # Query-invariance guard (same as the hardened smoke gate): reject
+ # selectors that return the same URLs for an unrelated control query.
+ try:
+ control = await search_with_recipe(client, recipe, CONTROL_QUERY, 10)
+ except Exception: # noqa: BLE001
+ control = []
+ overlap = control_overlap(docs, control)
+ if overlap is not None and overlap >= MAX_CONTROL_OVERLAP:
+ continue
+ doc = {"name": name, "domain": dom, "field": field,
+ "request": request, "response": response,
+ "smoke": {"query": word, "expect_title_contains": word}}
+ (RECIPES_DIR / f"{name}.yaml").write_text(
+ yaml.safe_dump(doc, sort_keys=False, allow_unicode=True))
+ return {"domain": dom, "status": "pass",
+ "selector": selector, "word": word, "n": len(docs)}
+ return {"domain": dom, "status": "fail"}
+
+
+def _params_from(url_tmpl: str) -> dict:
+ """Turn the query string of a templated URL into a recipe params map."""
+ from urllib.parse import urlsplit, parse_qsl
+ qs = urlsplit(url_tmpl).query
+ params = {}
+ for k, v in parse_qsl(qs, keep_blank_values=True):
+ # parse_qsl URL-decodes, so the templated value comes back as "{query}".
+ params[k] = "{query}" if "{query}" in v else v
+ return params
+
+
+async def _run(work: list[list]) -> list[dict]:
+ sem = asyncio.Semaphore(CONCURRENCY)
+ async with httpx.AsyncClient(
+ follow_redirects=True, timeout=TIMEOUT,
+ headers={"User-Agent": "mwmbl-super-search-smoke/0.1 (+https://mwmbl.org)"},
+ ) as client:
+ async def guarded(w):
+ async with sem:
+ return await _author(client, w[0], w[1], w[3])
+ return await asyncio.gather(*[guarded(w) for w in work])
+
+
+def main() -> int:
+ if len(sys.argv) != 2:
+ print("usage: auto_recipe_html.py <worklist.json>", file=sys.stderr)
+ return 2
+ work = json.loads(Path(sys.argv[1]).read_text())
+ # Drop JS-only doc search and off-site search engines up front.
+ work = [w for w in work if "search.html" not in w[3] and "google.com" not in w[3]]
+ print(f"Authoring HTML recipes for {len(work)} candidates...")
+ results = asyncio.run(_run(work))
+ passes = [r for r in results if r["status"] == "pass"]
+ for r in passes:
+ print(f"PASS {r['domain']} (results={r['selector']!r}, q={r['word']!r}, {r['n']})")
+ print(f"\n{len(passes)} passed, "
+ f"{sum(1 for r in results if r['status']=='exists')} existed, "
+ f"{sum(1 for r in results if r['status']=='fail')} failed.")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/smoke_recipe.py b/scripts/smoke_recipe.py
index ca6db30..034b063 100644
--- a/scripts/smoke_recipe.py
+++ b/scripts/smoke_recipe.py
@@ -1,8 +1,13 @@
#!/usr/bin/env python3
"""Live smoke-test a single Super Search recipe YAML file.
-Loads the recipe, runs it against the real site with its `smoke.query`, and
-checks that some result's title contains `smoke.expect_title_contains`.
+Thin dev wrapper around the shared check in
+``mwmbl.tinysearchengine.super_search_sources.smoke`` — the SAME logic the
+canonical live test (``test/test_super_search_smoke.py``) enforces in CI. Loads
+the recipe, runs it against the real site with its `smoke.query`, checks that
+some result's title contains `smoke.expect_title_contains`, and that the result
+set actually changes for an unrelated control query (so nav/boilerplate
+scrapers are rejected).
Usage:
uv run python scripts/smoke_recipe.py path/to/recipe.yaml
@@ -24,39 +29,22 @@ django.setup()
import httpx # noqa: E402
-from mwmbl.tinysearchengine.super_search_sources.recipe import ( # noqa: E402
- load_recipe,
- search_with_recipe,
-)
+from mwmbl.tinysearchengine.super_search_sources.recipe import load_recipe # noqa: E402
+from mwmbl.tinysearchengine.super_search_sources.smoke import check_recipe # noqa: E402
async def _run(path: str) -> int:
recipe = load_recipe(path)
- name = recipe.name
- smoke = recipe.smoke or {}
- query = smoke.get("query")
- expect = (smoke.get("expect_title_contains") or "").lower()
- if not query or not expect:
- print(f"FAIL {name}: missing smoke.query / expect_title_contains")
- return 1
- try:
- async with httpx.AsyncClient(
- follow_redirects=True, timeout=15.0,
- headers={"User-Agent": "mwmbl-super-search-smoke/0.1 (+https://mwmbl.org)"},
- ) as client:
- docs = await search_with_recipe(client, recipe, query, 10)
- except Exception as e: # noqa: BLE001
- print(f"FAIL {name}: request error {e!r}")
- return 1
- if not docs:
- print(f"FAIL {name}: no results for {query!r}")
- return 1
- if not any(expect in (d.title or "").lower() for d in docs):
- titles = ", ".join((d.title or "")[:40] for d in docs[:3])
- print(f"FAIL {name}: no title contains {expect!r} (got: {titles})")
- return 1
- print(f"PASS {name}: {len(docs)} results")
- return 0
+ async with httpx.AsyncClient(
+ follow_redirects=True, timeout=15.0,
+ headers={"User-Agent": "mwmbl-super-search-smoke/0.1 (+https://mwmbl.org)"},
+ ) as client:
+ ok, reason = await check_recipe(client, recipe)
+ if ok:
+ print(f"PASS {recipe.name}")
+ return 0
+ print(f"FAIL {recipe.name}: {reason}")
+ return 1
def main() -> int:
diff --git a/test/test_super_search_smoke.py b/test/test_super_search_smoke.py
index 9db77e4..21ae8f1 100644
--- a/test/test_super_search_smoke.py
+++ b/test/test_super_search_smoke.py
@@ -16,7 +16,8 @@ assertions below turn into a clear failure.
import httpx
import pytest
-from mwmbl.tinysearchengine.super_search_sources.recipe import load_recipes, search_with_recipe
+from mwmbl.tinysearchengine.super_search_sources.recipe import load_recipes
+from mwmbl.tinysearchengine.super_search_sources.smoke import check_recipe
pytestmark = pytest.mark.live
@@ -29,15 +30,8 @@ def _client() -> httpx.AsyncClient:
return httpx.AsyncClient(timeout=20.0, headers={"User-Agent": USER_AGENT})
-def _assert_usable(docs, expected_title_substr: str):
- assert docs, "recipe returned no results — the site may have changed its format or blocked us"
- assert docs[0].url and docs[0].title, f"top result missing url/title: {docs[0]!r}"
- assert any(expected_title_substr in d.title for d in docs), \
- f"no result title contains {expected_title_substr!r}; titles={[d.title for d in docs]}"
-
-
@pytest.mark.parametrize("recipe", RECIPES.values(), ids=lambda r: r.name)
async def test_recipe_live(recipe):
async with _client() as client:
- docs = await search_with_recipe(client, recipe, recipe.smoke["query"], 5)
- _assert_usable(docs, recipe.smoke["expect_title_contains"])
+ ok, reason = await check_recipe(client, recipe)
+ assert ok, reason