diff --git a/.env.example b/.env.example index 5554240..a6cbcde 100644 --- a/.env.example +++ b/.env.example @@ -23,3 +23,11 @@ WIKIPEDIA_LANG=en # Optional: require ?token= (or header trmnl-token: ) on # /trmnl.json so only your TRMNL device can poll it. Empty = open (public jokes). TRMNL_TOKEN= + +# Optional: scrape the full featured-article page through Firecrawl for +# richer joke material. Leave FIRECRAWL_API_URL empty (or unset) to keep +# the default behaviour (short extract from the Wikipedia REST feed). +# If Firecrawl is configured but fails, the app falls back to the feed +# extract automatically. +FIRECRAWL_API_URL=https://firecrawl.obahan.xyz +FIRECRAWL_API_KEY= diff --git a/README.md b/README.md index a2012ed..923505c 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,8 @@ docker compose up -d --build | `RETRY_MINUTES` | `15` | Retry interval | | `SLOW_RETRY_MINUTES` | `60` | Cooldown after budget exhausted, then retries resume | | `WIKIPEDIA_LANG` | `en` | Wikipedia language for the feed | +| `FIRECRAWL_API_URL` | *(empty)* | Firecrawl instance URL; if set, the full featured-article page is scraped via Firecrawl for richer joke material. Unset = feed extract only (original behaviour) | +| `FIRECRAWL_API_KEY` | *(empty)* | Firecrawl bearer token (optional) | | `DB_PATH` | `/data/jokes.db` | SQLite location (volume-mounted) | ## Endpoints diff --git a/app/config.py b/app/config.py index 66f1a2b..74b204e 100644 --- a/app/config.py +++ b/app/config.py @@ -39,6 +39,16 @@ class Settings: wikipedia_lang: str = field( default_factory=lambda: os.environ.get("WIKIPEDIA_LANG", "en") ) + firecrawl_api_url: str = field( + default_factory=lambda: os.environ.get("FIRECRAWL_API_URL", "").rstrip("/") + ) + firecrawl_api_key: str = field( + default_factory=lambda: os.environ.get("FIRECRAWL_API_KEY", "") + ) + + @property + def firecrawl_enabled(self) -> bool: + return bool(self.firecrawl_api_url) settings = Settings() diff --git a/app/wiki_client.py b/app/wiki_client.py index 5b57d39..73bd31d 100644 --- a/app/wiki_client.py +++ b/app/wiki_client.py @@ -1,4 +1,15 @@ -"""Fetch Wikipedia's 'Today's Featured Article' via the REST API feed.""" +"""Fetch Wikipedia's 'Today's Featured Article'. + +Two content paths: +- Base path (always used): the REST feed identifies the day's featured + article (title, URL) and provides a short plain-text extract. +- Firecrawl path (optional): if FIRECRAWL_API_URL is configured, the full + article page is scraped through Firecrawl for richer material. Any + Firecrawl failure falls back to the feed extract, so the app keeps + working exactly as before when Firecrawl is unset or down. +""" +import json +import logging import re from dataclasses import dataclass from datetime import date @@ -7,10 +18,17 @@ import httpx from .config import settings +log = logging.getLogger("jokes.wiki") + FEED_URL = ( "https://{lang}.wikipedia.org/api/rest_v1/feed/featured/{year:04d}/{month:02d}/{day:02d}" ) +USER_AGENT = "wiki-jokes/1.0 (daily joke generator; contact: admin@example.com)" + +# Cap the extract so the prompt stays bounded (~4000 chars). +MAX_EXTRACT_CHARS = 4000 + @dataclass class FeaturedArticle: @@ -32,16 +50,14 @@ def _strip_html(html: str) -> str: return re.sub(r"\s+", " ", text).strip() -def get_featured_article(day: date) -> FeaturedArticle: +def _feed_article(day: date) -> FeaturedArticle: + """Original path: featured article metadata + extract from the REST feed.""" url = FEED_URL.format( lang=settings.wikipedia_lang, year=day.year, month=day.month, day=day.day ) resp = httpx.get( url, - headers={ - "User-Agent": "wiki-jokes/1.0 (daily joke generator; contact: admin@example.com)", - "Accept": "application/json", - }, + headers={"User-Agent": USER_AGENT, "Accept": "application/json"}, timeout=30, follow_redirects=True, ) @@ -67,13 +83,81 @@ def get_featured_article(day: date) -> FeaturedArticle: if not extract: raise ValueError(f"Featured article for {day.isoformat()} has no extract text") - # Cap the extract so the prompt stays bounded (~4000 chars). - extract = extract[:4000] - display = (tfa.get("displaytitle") or tfa.get("title", "Unknown article")) display = _strip_html(display).replace("_", " ") return FeaturedArticle( title=display, url=tfa.get("content_urls", {}).get("desktop", {}).get("page", url), - extract=extract, + extract=extract[:MAX_EXTRACT_CHARS], ) + + +def _markdown_to_text(markdown: str) -> str: + """Reduce scraped page markdown to plain prose for the prompt.""" + text = markdown + # Drop images entirely: ![alt](url) + text = re.sub(r"!\[[^\]]*\]\([^)]*\)", " ", text) + # Drop bare URL tails left by nested brackets: ](https://...) + text = re.sub(r"\]\((?:https?://[^)]*|/[^)]*)\)", " ", text) + # Keep link text, drop the URL: [text](url) -> text + text = re.sub(r"\[([^\]]*)\]\([^)]*\)", r"\1", text) + # Drop reference markers like [1], [note 1] + text = re.sub(r"\[[^\]]{1,12}\]", " ", text) + # Drop any stray brackets left by nested/malformed links + text = text.replace("[", " ").replace("]", " ") + # Strip heading/list/blockquote markers + text = re.sub(r"^#{1,6}\s+", "", text, flags=re.MULTILINE) + text = re.sub(r"^\s*[=-]{3,}\s*$", " ", text, flags=re.MULTILINE) # setext underlines + text = re.sub(r"^\s*[-*+]\s+", "", text, flags=re.MULTILINE) + text = re.sub(r"^>\s?", "", text, flags=re.MULTILINE) + # Strip bold/italic/inline-code markers + text = re.sub(r"[*_`]+", "", text) + # Collapse whitespace + return re.sub(r"\s+", " ", text).strip() + + +def _scrape_via_firecrawl(page_url: str) -> str: + """Scrape a page through the configured Firecrawl instance; returns text.""" + endpoint = f"{settings.firecrawl_api_url}/v1/scrape" + headers = {"Content-Type": "application/json"} + if settings.firecrawl_api_key: + headers["Authorization"] = f"Bearer {settings.firecrawl_api_key}" + body = {"url": page_url, "formats": ["markdown"], "onlyMainContent": True} + resp = httpx.post(endpoint, headers=headers, json=body, timeout=120) + resp.raise_for_status() + payload = resp.json() + if not payload.get("success"): + raise ValueError(f"Firecrawl reported failure: {str(payload)[:200]}") + markdown = (payload.get("data") or {}).get("markdown") or "" + if not markdown.strip(): + raise ValueError("Firecrawl returned empty markdown") + return _markdown_to_text(markdown) + + +def get_featured_article(day: date) -> FeaturedArticle: + article = _feed_article(day) + + if not settings.firecrawl_enabled: + return article + + try: + full_text = _scrape_via_firecrawl(article.url) + if len(full_text) > len(article.extract): + log.info( + "Firecrawl scrape of %s yielded %d chars (feed extract had %d)", + article.title, len(full_text), len(article.extract), + ) + article.extract = full_text[:MAX_EXTRACT_CHARS] + else: + log.info( + "Firecrawl scrape of %s was not richer than the feed extract; " + "keeping feed extract", + article.title, + ) + except Exception as exc: # noqa: BLE001 — always fall back to the feed extract + log.warning( + "Firecrawl scrape failed for %s (%s); falling back to feed extract", + article.url, exc, + ) + + return article diff --git a/docker-compose.yml b/docker-compose.yml index 00b4ddf..6c511cd 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -15,8 +15,11 @@ services: GENERATE_MINUTE: ${GENERATE_MINUTE:-0} MAX_ATTEMPTS: ${MAX_ATTEMPTS:-3} RETRY_MINUTES: ${RETRY_MINUTES:-15} + SLOW_RETRY_MINUTES: ${SLOW_RETRY_MINUTES:-60} WIKIPEDIA_LANG: ${WIKIPEDIA_LANG:-en} TRMNL_TOKEN: ${TRMNL_TOKEN:-} + FIRECRAWL_API_URL: ${FIRECRAWL_API_URL:-} + FIRECRAWL_API_KEY: ${FIRECRAWL_API_KEY:-} DB_PATH: /data/jokes.db volumes: - jokes-data:/data