"""Pure parser for the news-summarizer map grading / reduce JSON / geo contract."""
from __future__ import annotations
import json
import re
_EMPTY = {"summary_en": "", "ticker": [], "map_items": []}
_KEEP = frozenset({"critical", "high"})
_RANK = {"critical": 0, "high": 1, "medium": 2, "low": 3}
_THINK_RE = re.compile(r".*?", re.DOTALL)
_FENCE_RE = re.compile(r"```(?:json)?", re.IGNORECASE)
TICKER_HEADLINE_MAX = 140
MAP_HEADLINE_MAX = 160
TICKER_CAP = 12
MAP_CAP = 20
# ── Map-phase grading (score parsing + selection, pure) ────────────────────
# Importance label → stand-in score, used when the map model omits Score:.
IMPORTANCE_SCORE = {"critical": 95, "high": 78, "medium": 50, "low": 22, "none": 5}
NEUTRAL_SCORE = 50
_ARTICLE_RE = re.compile(r"^[ \t>*_#\-]*Article[ \t]+(\d{1,3})[ \t]*:", re.IGNORECASE | re.MULTILINE)
_SCORE_RE = re.compile(r"Score:\s*(\d{1,3})", re.IGNORECASE)
_IMPORTANCE_RE = re.compile(r"Importance:\s*(critical|high|medium|low|none)", re.IGNORECASE)
_CATEGORY_RE = re.compile(r"Category:\s*(.+)", re.IGNORECASE)
def parse_reduce_json(raw: str) -> dict:
try:
text = _THINK_RE.sub("", raw or "")
text = _FENCE_RE.sub("", text)
start = text.find("{")
end = text.rfind("}")
if start == -1 or end == -1 or end < start:
return dict(_EMPTY)
data = json.loads(text[start : end + 1])
if not isinstance(data, dict):
return dict(_EMPTY)
summary = data.get("summary_en", "")
ticker = data.get("ticker", [])
map_items = data.get("map_items", [])
return {
"summary_en": summary if isinstance(summary, str) else "",
"ticker": ticker if isinstance(ticker, list) else [],
"map_items": map_items if isinstance(map_items, list) else [],
}
except Exception:
return dict(_EMPTY)
def clamp_coords(lat, lon) -> tuple[float, float] | None:
try:
lat_f = float(lat)
lon_f = float(lon)
except (TypeError, ValueError):
return None
if not (-90 <= lat_f <= 90 and -180 <= lon_f <= 180):
return None
return (lat_f, lon_f)
def _trimmed_headline(row: dict, limit: int) -> str:
headline = row.get("headline") or ""
if not isinstance(headline, str):
headline = str(headline)
return headline.strip()[:limit]
def select_ticker(rows: list) -> list:
flagged = []
medium = []
low = []
for row in rows:
imp = row.get("importance")
if imp not in _RANK:
continue
headline = _trimmed_headline(row, TICKER_HEADLINE_MAX)
if not headline:
continue
item = dict(row)
item["headline"] = headline
if imp in _KEEP:
flagged.append(item)
elif imp == "medium":
medium.append(item)
else:
low.append(item)
if len(flagged) >= TICKER_CAP:
break
if flagged:
return flagged[:TICKER_CAP]
return (medium + low)[:TICKER_CAP]
def select_map(items: list) -> list:
out = []
for row in items:
if row.get("importance") not in _KEEP:
continue
headline = _trimmed_headline(row, MAP_HEADLINE_MAX)
if not headline:
continue
coords = clamp_coords(row.get("lat"), row.get("lon"))
if coords is None:
continue
item = dict(row)
item["headline"] = headline
item["lat"], item["lon"] = coords
out.append(item)
if len(out) >= MAP_CAP:
break
return out
# ── Map grading ────────────────────────────────────────────────────────────
def _clamp_score(value: int) -> int:
return max(0, min(100, int(value)))
def _score_from_block(text: str) -> tuple[int, bool]:
"""Score for one article block. Second element True when a fallback was used."""
match = _SCORE_RE.search(text)
if match:
try:
return _clamp_score(int(match.group(1))), False
except (TypeError, ValueError):
pass
match = _IMPORTANCE_RE.search(text)
if match:
return IMPORTANCE_SCORE.get(match.group(1).lower(), NEUTRAL_SCORE), True
return NEUTRAL_SCORE, True
def _category_from_block(text: str) -> str | None:
match = _CATEGORY_RE.search(text)
if not match:
return None
value = match.group(1).strip().strip("*_` ").rstrip(".").strip()
return value[:40] or None
def parse_map_scores(
raw: str, *, articles: list[dict], batch_index: int = 0, batch_size: int = 1
) -> tuple[list[dict], dict]:
"""Split one map response into scored per-article blocks.
Pure: no DB, no logging. Block ``n`` of batch ``b`` is attributed to
``articles[b * batch_size + n - 1]``. Blocks whose ``Article `` number does
not land inside this batch (model omitted/reordered articles) are counted in
``stats["unattributed"]`` and dropped — there is no article row to attribute
them to. Never raises.
Returns ``(blocks, stats)`` where each block is::
{"n", "article", "article_id", "score", "importance", "category",
"text", "position"}
"""
text = raw or ""
matches = list(_ARTICLE_RE.finditer(text))
blocks: list[dict] = []
seen: set[int] = set()
fallback = 0
unattributed = 0
size = max(1, int(batch_size))
for pos, match in enumerate(matches):
try:
n = int(match.group(1))
except (TypeError, ValueError):
unattributed += 1
continue
if n in seen:
unattributed += 1
continue
seen.add(n)
end = matches[pos + 1].start() if pos + 1 < len(matches) else len(text)
block_text = text[match.start():end].strip()
offset = int(batch_index) * size + n - 1
article = articles[offset] if 0 <= offset < len(articles) else None
if article is None or not block_text:
unattributed += 1
continue
score, used_fallback = _score_from_block(block_text)
fallback += 1 if used_fallback else 0
importance = None
imp_match = _IMPORTANCE_RE.search(block_text)
if imp_match:
importance = imp_match.group(1).lower()
blocks.append(
{
"n": n,
"article": article,
"article_id": article.get("id"),
"score": score,
"importance": importance,
"category": _category_from_block(block_text),
"text": block_text,
"position": offset,
}
)
stats = {
"blocks": len(matches),
"graded": len(blocks),
"fallback": fallback,
"unattributed": unattributed,
}
return blocks, stats
def select_graded(
blocks: list[dict], *, min_score: int, top_n: int, fallback_top: int
) -> tuple[list[dict], bool]:
"""Rank blocks best-first and return the ones the reduce phase should see.
Keeps ``score >= min_score`` capped at ``top_n`` (stable on ties: original
order). When nothing clears the bar, returns the top ``fallback_top`` blocks
and True; ``fallback_top == 0`` yields an empty selection.
"""
ordered = sorted(blocks, key=lambda b: -int(b.get("score") or 0))
limit = max(0, int(top_n))
clearing = [b for b in ordered if int(b.get("score") or 0) >= int(min_score)]
if clearing:
return clearing[:limit], False
fallback_limit = max(0, int(fallback_top))
if fallback_limit <= 0:
return [], False
return ordered[:fallback_limit], bool(ordered)
def join_blocks(blocks: list[dict]) -> str:
"""Reduce-phase DATA text: only these blocks, original text, best-first."""
return "\n\n".join(b["text"] for b in blocks)