news: per-article proximate geolocation + GET /api/news/blips
Every graded article now carries best-effort geo on article_scores: - parse_map_scores extracts Location/Lat/Lon/Confidence per block (clamp_coords-validated; Unknown -> no geo; never invent a place) - place-name-only blocks resolve via a vendored offline GeoNames gazetteer (cities15000 + admin1 + country->capital), confidence approx - nullable location_name/lat/lon/location_confidence columns (alembic 014, single head; idempotent ensure_tables mirror) + partial bbox index - GET /api/news/blips: frozen contract, dedup by article id (latest geo wins), finite coords only, created_at DESC, bbox/since/limit, default 1000 max 5000, public read like /api/news/map - critical/high map pins, ticker, grading thresholds, dedupe unchanged Tests: 50 new summarizer geo tests (161 total), 18 new blips API contract tests; alembic upgrade heads proven on fresh DBs both start orders; forced batch on test DB yielded 10 non-critical blips with geo. Card: t_bc15eb53
This commit is contained in:
parent
5ea43a3d0b
commit
ca1c73e1a6
16 changed files with 39639 additions and 10 deletions
|
|
@ -26,6 +26,84 @@ _ARTICLE_RE = re.compile(r"^[ \t>*_#\-]*Article[ \t]+(\d{1,3})[ \t]*:", re.IGNOR
|
|||
_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)
|
||||
_LOCATION_RE = re.compile(r"Location:[ \t]*(.+)", re.IGNORECASE)
|
||||
_CONFIDENCE_RE = re.compile(
|
||||
r"Confidence:[ \t]*(exact|city|region|country|approx)", re.IGNORECASE
|
||||
)
|
||||
# Numeric token, optional degree sign, optional hemisphere letter. The
|
||||
# trailing lookahead keeps "12.3 South Sudan" from reading the S of a word
|
||||
# as a south marker (and from truncating the number to dodge it).
|
||||
_LAT_RE = re.compile(
|
||||
r"Lat:[ \t]*([+-]?\d+(?:\.\d+)?)[ \t]*°?[ \t]*([NS])?(?![A-Za-z\d.])", re.IGNORECASE
|
||||
)
|
||||
_LON_RE = re.compile(
|
||||
r"Lon:[ \t]*([+-]?\d+(?:\.\d+)?)[ \t]*°?[ \t]*([EW])?(?![A-Za-z\d.])", re.IGNORECASE
|
||||
)
|
||||
|
||||
LOCATION_NAME_MAX = 120
|
||||
_UNKNOWN_LOCATIONS = frozenset(
|
||||
{"unknown", "n/a", "none", "null", "unspecified", "not specified"}
|
||||
)
|
||||
GEO_CONFIDENCES = frozenset({"exact", "city", "region", "country", "approx"})
|
||||
|
||||
|
||||
def clean_location_name(raw) -> str | None:
|
||||
"""Normalise a model-written place name; Unknown/empty -> None.
|
||||
|
||||
Strips markdown decoration and trailing periods, caps the length.
|
||||
Never invents a place: a name the model did not write stays None.
|
||||
"""
|
||||
if not isinstance(raw, str):
|
||||
return None
|
||||
value = raw.strip().rstrip(".").strip().strip("*_`").strip()
|
||||
if not value:
|
||||
return None
|
||||
lowered = value.lower()
|
||||
if lowered in _UNKNOWN_LOCATIONS or lowered.startswith("unknown"):
|
||||
return None
|
||||
return value[:LOCATION_NAME_MAX]
|
||||
|
||||
|
||||
def _coord_from_block(text: str, kind: str) -> float | None:
|
||||
"""One Lat:/Lon: value from a block; hemisphere S/W negates."""
|
||||
match = (_LAT_RE if kind == "lat" else _LON_RE).search(text)
|
||||
if not match:
|
||||
return None
|
||||
try:
|
||||
value = float(match.group(1))
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
hemisphere = (match.group(2) or "").upper()
|
||||
if hemisphere in ("S", "W") and value > 0:
|
||||
value = -value
|
||||
return value
|
||||
|
||||
|
||||
def _geo_from_block(text: str) -> dict:
|
||||
"""Structured geo for one article block (pure).
|
||||
|
||||
Model coords are only trusted alongside a real place name — coords
|
||||
next to ``Location: Unknown`` are dropped (never invent a place).
|
||||
Missing/invalid coords leave lat/lon None for the offline gazetteer
|
||||
step; confidence defaults to "city" when the model gave coords but
|
||||
no Confidence line.
|
||||
"""
|
||||
loc_match = _LOCATION_RE.search(text)
|
||||
location_name = clean_location_name(loc_match.group(1) if loc_match else None)
|
||||
lat = lon = None
|
||||
confidence = None
|
||||
if location_name is not None:
|
||||
coords = clamp_coords(_coord_from_block(text, "lat"), _coord_from_block(text, "lon"))
|
||||
if coords is not None:
|
||||
lat, lon = coords
|
||||
conf_match = _CONFIDENCE_RE.search(text)
|
||||
confidence = conf_match.group(1).lower() if conf_match else "city"
|
||||
return {
|
||||
"location_name": location_name,
|
||||
"lat": lat,
|
||||
"lon": lon,
|
||||
"location_confidence": confidence,
|
||||
}
|
||||
|
||||
|
||||
def parse_reduce_json(raw: str) -> dict:
|
||||
|
|
@ -157,7 +235,14 @@ def parse_map_scores(
|
|||
Returns ``(blocks, stats)`` where each block is::
|
||||
|
||||
{"n", "article", "article_id", "score", "importance", "category",
|
||||
"location_name", "lat", "lon", "location_confidence",
|
||||
"text", "position"}
|
||||
|
||||
Geo is best-effort: ``location_name`` is the model's place name
|
||||
(Unknown -> None), ``lat``/``lon`` are clamp_coords-validated model
|
||||
coordinates (None when absent/invalid — the caller may resolve them
|
||||
via the offline gazetteer), ``location_confidence`` is the block's
|
||||
label or "city" when coords came without one.
|
||||
"""
|
||||
text = raw or ""
|
||||
matches = list(_ARTICLE_RE.finditer(text))
|
||||
|
|
@ -198,6 +283,7 @@ def parse_map_scores(
|
|||
"score": score,
|
||||
"importance": importance,
|
||||
"category": _category_from_block(block_text),
|
||||
**_geo_from_block(block_text),
|
||||
"text": block_text,
|
||||
"position": offset,
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue