"""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 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: title: str url: str extract: str # plain-text extract, HTML stripped def _strip_html(html: str) -> str: text = re.sub(r"<[^>]+>", " ", html) text = ( text.replace("&", "&") .replace(""", '"') .replace("'", "'") .replace("<", "<") .replace(">", ">") .replace(" ", " ") ) return re.sub(r"\s+", " ", text).strip() 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": USER_AGENT, "Accept": "application/json"}, timeout=30, follow_redirects=True, ) resp.raise_for_status() data = resp.json() tfa = data.get("tfa") if not tfa: raise ValueError(f"No featured article (tfa) in feed for {day.isoformat()}") # Prefer the REST "extracts.plain.text" if present, else the summary HTML. extract = "" extracts = tfa.get("extracts") or {} plain = extracts.get("plain") or {} if plain.get("text"): extract = plain["text"] elif tfa.get("extract"): extract = tfa["extract"] elif tfa.get("summary"): extract = _strip_html(tfa["summary"]) extract = _strip_html(extract) if "<" in extract else extract if not extract: raise ValueError(f"Featured article for {day.isoformat()} has no extract text") 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[: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