diff --git a/app/main.py b/app/main.py index 8da8fdd..f678e35 100644 --- a/app/main.py +++ b/app/main.py @@ -57,6 +57,7 @@ from camera_scraper import is_public_url from sources import GDELT_API, ingest_rss_feed, ingest_gdelt, ingest_earthquakes, ingest_social_signals from fire_sources import ingest_fires from keystore import KeyFormatError, delete_key, list_keys, set_key +from news_title import unwrap_cdata_title from settings_store import SettingsError, get_app_settings, list_models, set_summary_model from live_layers import ( fetch_aircraft, fetch_fire_incidents, fetch_fire_perimeters, @@ -1348,7 +1349,7 @@ async def list_news( rows = (await session.execute(stmt)).mappings().all() return [ NewsArticleOut( - id=r["id"], title=r["title"], url=r["url"], + id=r["id"], title=unwrap_cdata_title(r["title"]), url=r["url"], content=r["content"] if include_content else None, domain=r["domain"], timestamp=r["timestamp"], ) diff --git a/app/news_title.py b/app/news_title.py new file mode 100644 index 0000000..29ada1d --- /dev/null +++ b/app/news_title.py @@ -0,0 +1,33 @@ +"""News title cleanup for the read path. + +Same rule as ``news/scraper/newsScraper/feed_util.py:unwrap_cdata_title``. +The API image does not include the scraper package, so the function is +copied rather than imported. Existing rows are fixed here on read; this +module does not write. +""" + +from __future__ import annotations + +import re + +# Whole-title CDATA wrapper only. Leading/trailing whitespace around the +# markers belongs to the wrapper, not the title. +_CDATA_WRAPPER = re.compile( + r"\A\s*\s*\Z", + re.DOTALL, +) + + +def unwrap_cdata_title(title: str | None) -> str | None: + """Strip a surrounding CDATA wrapper. Anything else is unchanged. + + ```` and ``\\n `` become + ``Hello``. Real HTML (``Hello``) and a title that merely contains + the markers are returned as-is. Non-strings pass through. + """ + if not isinstance(title, str): + return title + match = _CDATA_WRAPPER.match(title) + if match is None: + return title + return match.group(1).strip() diff --git a/news/scraper/newsScraper/feed_util.py b/news/scraper/newsScraper/feed_util.py index 1cffa17..d42034a 100644 --- a/news/scraper/newsScraper/feed_util.py +++ b/news/scraper/newsScraper/feed_util.py @@ -3,6 +3,7 @@ from __future__ import annotations import datetime +import re from email.utils import parsedate_to_datetime from urllib.parse import urlparse @@ -30,3 +31,26 @@ def article_timestamp(pub_date: str | None) -> datetime.datetime: except ValueError: pass return datetime.datetime.now(datetime.timezone.utc) + + +# Whole-title CDATA wrapper only. Keep in sync with app/news_title.py — +# the scraper image and the API image do not share a package. +_CDATA_WRAPPER = re.compile( + r"\A\s*\s*\Z", + re.DOTALL, +) + + +def unwrap_cdata_title(title): + """Strip a surrounding CDATA wrapper. Anything else is unchanged. + + ```` and ``\\n `` become + ``Hello``. Real HTML (``Hello``) and a title that merely contains + the markers are returned as-is. Non-strings pass through. + """ + if not isinstance(title, str): + return title + match = _CDATA_WRAPPER.match(title) + if match is None: + return title + return match.group(1).strip() diff --git a/news/scraper/newsScraper/pipelines.py b/news/scraper/newsScraper/pipelines.py index 2629372..5a1ab9f 100644 --- a/news/scraper/newsScraper/pipelines.py +++ b/news/scraper/newsScraper/pipelines.py @@ -9,6 +9,8 @@ import psycopg2 import os from scrapy.exceptions import DropItem +from newsScraper.feed_util import unwrap_cdata_title + log = logging.getLogger(__name__) # Feed items dated further ahead than this are event listings (or clock skew @@ -104,6 +106,7 @@ class PostgresPipeline: if url in self.seen_urls: raise DropItem(f"Duplicate URL (in-memory): {url}") self.seen_urls.add(url) + item['title'] = unwrap_cdata_title(item['title']) try: self.cur.execute(""" INSERT INTO articles (title, url, content, domain, timestamp) diff --git a/tests/test_api_news.py b/tests/test_api_news.py index cf7ab77..116571c 100644 --- a/tests/test_api_news.py +++ b/tests/test_api_news.py @@ -176,6 +176,50 @@ def test_api_news_excludes_future_dated_rows(clean_news): assert [a["title"] for a in limited] == ["recent", "recent2"] +@requires_db +def test_api_news_unwraps_stored_cdata_title(clean_news): + """Dirty rows are fixed on read. A plain title, and HTML that is not a + CDATA wrapper, are returned unchanged. No UPDATE of historical rows. + """ + stored = "\n " + _seed_article( + stored, + "https://www.excelsior.com.mx/cdata", + "www.excelsior.com.mx", + "2026-08-24T18:00:00+00:00", + ) + _seed_article( + "Hello", + "https://a.example/plain", + "a.example", + "2026-08-24T17:00:00+00:00", + ) + _seed_article( + "Keep", + "https://a.example/html", + "a.example", + "2026-08-24T16:00:00+00:00", + ) + + body = _get("/api/news").json() + by_url = {row["url"]: row["title"] for row in body} + assert by_url["https://www.excelsior.com.mx/cdata"] == "Hello" + assert by_url["https://a.example/plain"] == "Hello" + assert by_url["https://a.example/html"] == "Keep" + + # Read-path only: the stored row stays dirty. + async def _stored_title() -> str: + conn = await asyncpg.connect(**_conn_kwargs()) + try: + return await conn.fetchval( + "SELECT title FROM articles WHERE url = $1", + "https://www.excelsior.com.mx/cdata", + ) + finally: + await conn.close() + + assert asyncio.run(_stored_title()) == stored + @requires_db def test_api_news_summaries_contract(clean_news): diff --git a/tests/test_news_scraper.py b/tests/test_news_scraper.py index ac335c2..b075ced 100644 --- a/tests/test_news_scraper.py +++ b/tests/test_news_scraper.py @@ -133,3 +133,51 @@ def test_pipeline_keeps_unparseable_timestamp(): assert is_future_dated("not a date") is False assert is_future_dated(None) is False + +# ── CDATA title unwrap (ingest) ─────────────────────────────────────────── +# Excelsior stores the wrapper as text, including the leading newline the +# feed leaves around . A plain title, and real HTML that is +# not that wrapper, must pass through unchanged. + +@pytest.mark.parametrize( + "raw,expected", + [ + ("", "Hello"), + ("\n ", "Hello"), + ( + "\n ", + "Hello", + ), + ("Hello", "Hello"), + (" Hello ", " Hello "), + ("Hello", "Hello"), + ("See ", "See "), + (None, None), + ], +) +def test_unwrap_cdata_title(raw, expected): + from newsScraper.feed_util import unwrap_cdata_title + + assert unwrap_cdata_title(raw) == expected + + +@pytest.mark.parametrize( + "raw,expected", + [ + ("", "Hello"), + ("\n ", "Hello"), + ("Hello", "Hello"), + ("Hello", "Hello"), + ], +) +def test_pipeline_stores_cdata_title_unwrapped(raw, expected): + pipe = _pipeline() + spider = _FakeSpider() + recent = _dt.datetime.now(_dt.timezone.utc) - _dt.timedelta(hours=1) + item = _item(recent) + item["title"] = raw + returned = pipe.process_item(item, spider) + assert returned["title"] == expected + stored = pipe.cur.executed[0][1][0] + assert stored == expected +