osint-dashboard/news/summerizer/tests/test_geo.py

405 lines
13 KiB
Python
Raw Permalink Normal View History

"""Per-article geo: map-block Location/Lat/Lon parsing + offline gazetteer.
Covers the blips pipeline (card t_bc15eb53): parse_map_scores extracts
structured geo per graded block, clamp_coords rejects invalid values, and
the vendored GeoNames gazetteer resolves place-name-only blocks to
proximate coordinates with confidence "approx".
"""
from __future__ import annotations
import math
import pytest
from intel import clamp_coords, parse_map_scores
def _articles(n: int = 1, start: int = 100) -> list[dict]:
return [
{
"id": start + i,
"title": f"title {i}",
"content": "body",
"url": f"https://ex.com/{i}",
"domain": "ex.com",
}
for i in range(n)
]
def _block(n: int, *lines: str, score: int = 55) -> str:
return "\n".join([f"Article {n}:", f"- Score: {score}", *lines])
# ── parse_map_scores: structured geo ──────────────────────────────────────
def test_parses_location_lat_lon_and_confidence():
raw = _block(
1,
"- Location: Kyiv, Ukraine",
"- Lat: 50.45",
"- Lon: 30.52",
"- Confidence: city",
"- Category: politics",
)
blocks, stats = parse_map_scores(raw, articles=_articles())
assert stats["graded"] == 1
b = blocks[0]
assert b["location_name"] == "Kyiv, Ukraine"
assert b["lat"] == pytest.approx(50.45)
assert b["lon"] == pytest.approx(30.52)
assert b["location_confidence"] == "city"
def test_coords_without_confidence_default_to_city():
raw = _block(1, "- Location: Kyiv", "- Lat: 50.45", "- Lon: 30.52")
b = parse_map_scores(raw, articles=_articles())[0][0]
assert b["location_confidence"] == "city"
assert b["lat"] == pytest.approx(50.45)
@pytest.mark.parametrize("confidence", ["exact", "city", "region", "country"])
def test_block_confidence_labels_pass_through(confidence):
raw = _block(
1, "- Location: somewhere", "- Lat: 10", "- Lon: 20",
f"- Confidence: {confidence}",
)
b = parse_map_scores(raw, articles=_articles())[0][0]
assert b["location_confidence"] == confidence
def test_place_name_only_keeps_name_without_coords():
raw = _block(1, "- Location: Odesa, Ukraine")
b = parse_map_scores(raw, articles=_articles())[0][0]
assert b["location_name"] == "Odesa, Ukraine"
assert b["lat"] is None
assert b["lon"] is None
assert b["location_confidence"] is None
@pytest.mark.parametrize("location", ["Unknown", "unknown", "N/A", "None", ""])
def test_unknown_location_yields_no_geo(location):
raw = _block(1, f"- Location: {location}", "- Lat: 50.45", "- Lon: 30.52")
b = parse_map_scores(raw, articles=_articles())[0][0]
assert b["location_name"] is None
# No usable place name: model coords alone are not trusted either.
assert b["lat"] is None
assert b["lon"] is None
assert b["location_confidence"] is None
def test_no_location_line_yields_no_geo():
b = parse_map_scores(_block(1, "- Category: politics"), articles=_articles())[0][0]
assert b["location_name"] is None
assert b["lat"] is None
assert b["lon"] is None
assert b["location_confidence"] is None
def test_out_of_range_coords_are_dropped_but_name_kept():
raw = _block(1, "- Location: Nowhere", "- Lat: 95.0", "- Lon: 30.52")
b = parse_map_scores(raw, articles=_articles())[0][0]
assert b["location_name"] == "Nowhere"
assert b["lat"] is None
assert b["lon"] is None
assert b["location_confidence"] is None
def test_lon_out_of_range_drops_both():
raw = _block(1, "- Location: Nowhere", "- Lat: 10", "- Lon: 181")
b = parse_map_scores(raw, articles=_articles())[0][0]
assert b["lat"] is None and b["lon"] is None
def test_missing_lon_drops_lat_too():
raw = _block(1, "- Location: Kyiv", "- Lat: 50.45")
b = parse_map_scores(raw, articles=_articles())[0][0]
assert b["lat"] is None and b["lon"] is None
def test_non_numeric_coords_drop_both():
raw = _block(1, "- Location: Kyiv", "- Lat: about 50", "- Lon: 30.52")
b = parse_map_scores(raw, articles=_articles())[0][0]
assert b["lat"] is None and b["lon"] is None
def test_hemisphere_suffixes_negate_south_and_west():
raw = _block(
1, "- Location: Sydney", "- Lat: 33.87 S", "- Lon: 151.21 E"
)
b = parse_map_scores(raw, articles=_articles())[0][0]
assert b["lat"] == pytest.approx(-33.87)
assert b["lon"] == pytest.approx(151.21)
raw = _block(1, "- Location: Rio", "- Lat: 22.9 S", "- Lon: 43.2 W")
b = parse_map_scores(raw, articles=_articles())[0][0]
assert b["lat"] == pytest.approx(-22.9)
assert b["lon"] == pytest.approx(-43.2)
def test_hemisphere_letter_of_a_word_is_not_a_suffix():
# "12.3 South Sudan" must NOT negate — the S belongs to a word.
raw = _block(1, "- Location: Juba", "- Lat: 12.3 South Sudan", "- Lon: 31.6")
b = parse_map_scores(raw, articles=_articles())[0][0]
assert b["lat"] == pytest.approx(12.3)
def test_location_name_is_cleaned_and_capped():
raw = _block(1, "- Location: **Kyiv**.")
b = parse_map_scores(raw, articles=_articles())[0][0]
assert b["location_name"] == "Kyiv"
raw = _block(1, "- Location: " + "x" * 300)
b = parse_map_scores(raw, articles=_articles())[0][0]
assert len(b["location_name"]) <= 120
def test_each_block_gets_its_own_geo():
raw = "\n\n".join(
[
_block(1, "- Location: Kyiv", "- Lat: 50.45", "- Lon: 30.52"),
_block(2, "- Location: Tehran", "- Lat: 35.69", "- Lon: 51.39"),
_block(3, "- Location: Unknown"),
]
)
blocks, stats = parse_map_scores(raw, articles=_articles(3))
assert stats["graded"] == 3
assert blocks[0]["lat"] == pytest.approx(50.45)
assert blocks[1]["location_name"] == "Tehran"
assert blocks[1]["lon"] == pytest.approx(51.39)
assert blocks[2]["location_name"] is None
assert blocks[2]["lat"] is None
def test_geo_fields_never_break_score_parsing():
raw = _block(
1, "- Location: Kyiv", "- Lat: 50.45", "- Lon: 30.52",
"- Importance: high", score=83,
)
b = parse_map_scores(raw, articles=_articles())[0][0]
assert b["score"] == 83
assert b["importance"] == "high"
# ── clamp_coords hardening ────────────────────────────────────────────────
@pytest.mark.parametrize(
"lat,lon",
[
(90.1, 0), (-90.1, 0), (0, 180.1), (0, -180.1),
(float("nan"), 0), (0, float("nan")),
(float("inf"), 0), (0, float("-inf")),
("abc", 0), (None, None),
],
)
def test_clamp_coords_rejects_invalid(lat, lon):
assert clamp_coords(lat, lon) is None
def test_clamp_coords_accepts_boundaries():
assert clamp_coords(90, 180) == (90.0, 180.0)
assert clamp_coords(-90, -180) == (-90.0, -180.0)
# ── Offline gazetteer ─────────────────────────────────────────────────────
def test_gazetteer_resolves_known_city():
from gazetteer import resolve_place
coords = resolve_place("Kyiv")
assert coords is not None
lat, lon = coords
assert lat == pytest.approx(50.45, abs=0.1)
assert lon == pytest.approx(30.52, abs=0.1)
def test_gazetteer_resolves_city_with_country_context():
from gazetteer import resolve_place
coords = resolve_place("Kyiv, Ukraine")
assert coords is not None
assert coords[0] == pytest.approx(50.45, abs=0.1)
def test_gazetteer_disambiguates_by_country():
from gazetteer import resolve_place
france = resolve_place("Paris, France")
texas = resolve_place("Paris, Texas")
assert france is not None and texas is not None
assert france[0] == pytest.approx(48.85, abs=0.2)
assert texas[0] == pytest.approx(33.66, abs=0.3)
assert france != texas
def test_gazetteer_resolves_country_to_capital():
from gazetteer import resolve_place
coords = resolve_place("Ukraine")
assert coords is not None
# Capital Kyiv.
assert coords[0] == pytest.approx(50.45, abs=0.1)
assert coords[1] == pytest.approx(30.52, abs=0.1)
def test_gazetteer_handles_diacritics_and_case():
from gazetteer import resolve_place
assert resolve_place("KYIV") is not None
assert resolve_place("Tehrān") is not None or resolve_place("Tehran") is not None
@pytest.mark.parametrize("name", ["Unknown", "", None, " ", "Zzzqx Not A Real Place 999"])
def test_gazetteer_misses_return_none(name):
from gazetteer import resolve_place
assert resolve_place(name) is None
def test_fill_block_geo_resolves_place_name_only_block():
from gazetteer import fill_block_geo
raw = _block(1, "- Location: Kyiv, Ukraine")
b = parse_map_scores(raw, articles=_articles())[0][0]
fill_block_geo(b)
assert b["lat"] == pytest.approx(50.45, abs=0.1)
assert b["lon"] == pytest.approx(30.52, abs=0.1)
assert b["location_confidence"] == "approx"
assert b["location_name"] == "Kyiv, Ukraine"
def test_fill_block_geo_keeps_model_coords():
from gazetteer import fill_block_geo
raw = _block(1, "- Location: Kyiv", "- Lat: 50.45", "- Lon: 30.52")
b = parse_map_scores(raw, articles=_articles())[0][0]
fill_block_geo(b)
assert b["lat"] == pytest.approx(50.45)
assert b["location_confidence"] == "city"
def test_fill_block_geo_omits_when_no_location():
from gazetteer import fill_block_geo
raw = _block(1, "- Location: Unknown")
b = parse_map_scores(raw, articles=_articles())[0][0]
fill_block_geo(b)
assert b["lat"] is None and b["lon"] is None
assert b["location_confidence"] is None
def test_fill_block_geo_omits_when_gazetteer_misses():
from gazetteer import fill_block_geo
raw = _block(1, "- Location: Zzzqx Not A Real Place 999")
b = parse_map_scores(raw, articles=_articles())[0][0]
fill_block_geo(b)
assert b["lat"] is None and b["lon"] is None
assert b["location_confidence"] is None
# The name the model actually wrote is still preserved.
assert b["location_name"] == "Zzzqx Not A Real Place 999"
# ── Persistence carries geo ───────────────────────────────────────────────
def test_persist_article_scores_writes_geo_columns(monkeypatch):
import summarizer
captured: list = []
class _Cur:
def execute(self, sql, params=None):
pass
def executemany(self, sql, rows):
captured.append((" ".join(sql.split()), list(rows)))
def close(self):
pass
class _Conn:
def cursor(self):
return _Cur()
def commit(self):
pass
def close(self):
pass
monkeypatch.setattr(summarizer.psycopg2, "connect", lambda **kw: _Conn())
graded = [
{
"article_id": 1, "score": 80, "category": "politics",
"selected": True, "location_name": "Kyiv, Ukraine",
"lat": 50.45, "lon": 30.52, "location_confidence": "city",
},
{
"article_id": 2, "score": 30, "category": "crime",
"selected": False, "location_name": "Unknown",
"lat": None, "lon": None, "location_confidence": None,
},
]
summarizer.persist_article_scores(graded, summary_id=7, model="m")
assert captured, "no executemany captured"
sql, rows = captured[-1]
for col in ("location_name", "lat", "lon", "location_confidence"):
assert col in sql
by_id = {row[0]: row for row in rows}
assert by_id[1][7] == "Kyiv, Ukraine"
assert by_id[1][8] == pytest.approx(50.45)
assert by_id[1][9] == pytest.approx(30.52)
assert by_id[1][10] == "city"
assert by_id[2][7] is None
assert by_id[2][8] is None
assert by_id[2][9] is None
assert by_id[2][10] is None
def test_persist_article_scores_sanitizes_bad_geo(monkeypatch):
import summarizer
captured: list = []
class _Cur:
def execute(self, sql, params=None):
pass
def executemany(self, sql, rows):
captured.append(list(rows))
def close(self):
pass
class _Conn:
def cursor(self):
return _Cur()
def commit(self):
pass
def close(self):
pass
monkeypatch.setattr(summarizer.psycopg2, "connect", lambda **kw: _Conn())
graded = [
{
"article_id": 1, "score": 80, "selected": True,
"location_name": "Kyiv", "lat": float("nan"), "lon": 30.52,
"location_confidence": "bogus",
},
]
summarizer.persist_article_scores(graded, summary_id=7, model="m")
row = captured[-1][0]
assert row[8] is None and row[9] is None # NaN lat drops the pair
assert row[10] is None # confidence outside the contract vocabulary
def test_map_prompt_asks_for_confidence():
from summarizer import MAP_PROMPT_DEFAULT
assert "Confidence:" in MAP_PROMPT_DEFAULT
assert "exact|city|region|country" in MAP_PROMPT_DEFAULT