fix(news): unwrap CDATA titles at ingest and on /api/news #62
6 changed files with 154 additions and 1 deletions
|
|
@ -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"],
|
||||
)
|
||||
|
|
|
|||
33
app/news_title.py
Normal file
33
app/news_title.py
Normal file
|
|
@ -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*<!\[CDATA\[(.*?)\]\]>\s*\Z",
|
||||
re.DOTALL,
|
||||
)
|
||||
|
||||
|
||||
def unwrap_cdata_title(title: str | None) -> str | None:
|
||||
"""Strip a surrounding CDATA wrapper. Anything else is unchanged.
|
||||
|
||||
``<![CDATA[Hello]]>`` and ``\\n <![CDATA[Hello]]>`` become
|
||||
``Hello``. Real HTML (``<b>Hello</b>``) 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()
|
||||
|
|
@ -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*<!\[CDATA\[(.*?)\]\]>\s*\Z",
|
||||
re.DOTALL,
|
||||
)
|
||||
|
||||
|
||||
def unwrap_cdata_title(title):
|
||||
"""Strip a surrounding CDATA wrapper. Anything else is unchanged.
|
||||
|
||||
``<![CDATA[Hello]]>`` and ``\\n <![CDATA[Hello]]>`` become
|
||||
``Hello``. Real HTML (``<b>Hello</b>``) 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()
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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 <![CDATA[Hello]]> "
|
||||
_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(
|
||||
"<b>Keep</b>",
|
||||
"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"] == "<b>Keep</b>"
|
||||
|
||||
# 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):
|
||||
|
|
|
|||
|
|
@ -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 <![CDATA[...]]>. A plain title, and real HTML that is
|
||||
# not that wrapper, must pass through unchanged.
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"raw,expected",
|
||||
[
|
||||
("<![CDATA[Hello]]>", "Hello"),
|
||||
("\n <![CDATA[Hello]]>", "Hello"),
|
||||
(
|
||||
"\n <![CDATA[Hello]]> ",
|
||||
"Hello",
|
||||
),
|
||||
("Hello", "Hello"),
|
||||
(" Hello ", " Hello "),
|
||||
("<b>Hello</b>", "<b>Hello</b>"),
|
||||
("See <![CDATA[Hello]]>", "See <![CDATA[Hello]]>"),
|
||||
(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",
|
||||
[
|
||||
("<![CDATA[Hello]]>", "Hello"),
|
||||
("\n <![CDATA[Hello]]>", "Hello"),
|
||||
("Hello", "Hello"),
|
||||
("<b>Hello</b>", "<b>Hello</b>"),
|
||||
],
|
||||
)
|
||||
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
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue