fix(map): geofence delete, vessel snapshots, sentinel cache, news briefs
Geofences could be drawn but not removed. VesselAPI Hormuz dots vanished
on restart and DVR skipped between the 5 daily polls. Sentinel-1 re-hit
STAC on every pan and often painted a neighbouring swath. Executive
briefs truncated; ticker stayed empty unless something was critical.
- Layer-panel list + polygon popup DELETE /api/geofences/{id}
- Persist VesselAPI polls to vessels (UTC-day purge, DVR as-of, boot hydrate)
- Cache Sentinel-1 by 2° cell; pick covering scene; clip Leaflet tiles
- Retry truncated LLM JSON; ticker falls back to medium/low; 3-min HUD poll
This commit is contained in:
parent
fdf5969e27
commit
c48788d4b6
20 changed files with 669 additions and 57 deletions
|
|
@ -7,6 +7,7 @@ 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"<think>.*?</think>", re.DOTALL)
|
||||
_FENCE_RE = re.compile(r"```(?:json)?", re.IGNORECASE)
|
||||
|
||||
|
|
@ -58,19 +59,29 @@ def _trimmed_headline(row: dict, limit: int) -> str:
|
|||
|
||||
|
||||
def select_ticker(rows: list) -> list:
|
||||
out = []
|
||||
flagged = []
|
||||
medium = []
|
||||
low = []
|
||||
for row in rows:
|
||||
if row.get("importance") not in _KEEP:
|
||||
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
|
||||
out.append(item)
|
||||
if len(out) >= TICKER_CAP:
|
||||
if imp in _KEEP:
|
||||
flagged.append(item)
|
||||
elif imp == "medium":
|
||||
medium.append(item)
|
||||
else:
|
||||
low.append(item)
|
||||
if len(flagged) >= TICKER_CAP:
|
||||
break
|
||||
return out
|
||||
if flagged:
|
||||
return flagged[:TICKER_CAP]
|
||||
return (medium + low)[:TICKER_CAP]
|
||||
|
||||
|
||||
def select_map(items: list) -> list:
|
||||
|
|
|
|||
|
|
@ -8,6 +8,10 @@ import httpx
|
|||
|
||||
_DEFAULT_UA = "osint-dashboard-news-summarizer"
|
||||
_DEFAULT_BASE = "https://inference-api.nousresearch.com/v1"
|
||||
_JSON_SYSTEM = (
|
||||
"You are an OSINT executive briefer. Reply with a single complete JSON object. "
|
||||
"Never truncate mid-sentence. If you run out of room, drop the lowest-priority item."
|
||||
)
|
||||
|
||||
|
||||
def chat(prompt, *, api_key, model, base_url, json_mode=False) -> str:
|
||||
|
|
@ -17,20 +21,37 @@ def chat(prompt, *, api_key, model, base_url, json_mode=False) -> str:
|
|||
"Authorization": f"Bearer {api_key}",
|
||||
"User-Agent": os.environ.get("OSINT_USER_AGENT") or _DEFAULT_UA,
|
||||
}
|
||||
max_tokens = 8192 if json_mode else 4096
|
||||
timeout = 120.0 if json_mode else 60.0
|
||||
messages = [{"role": "user", "content": prompt}]
|
||||
if json_mode:
|
||||
messages = [
|
||||
{"role": "system", "content": _JSON_SYSTEM},
|
||||
{"role": "user", "content": prompt},
|
||||
]
|
||||
payload = {
|
||||
"model": model,
|
||||
"messages": [{"role": "user", "content": prompt}],
|
||||
"messages": messages,
|
||||
"temperature": 0.2,
|
||||
"max_tokens": 4096,
|
||||
"max_tokens": max_tokens,
|
||||
}
|
||||
if json_mode:
|
||||
payload["response_format"] = {"type": "json_object"}
|
||||
last_content = ""
|
||||
try:
|
||||
with httpx.Client(timeout=60.0) as client:
|
||||
resp = client.post(url, headers=headers, json=payload)
|
||||
if resp.status_code == 401 or resp.status_code >= 500:
|
||||
return ""
|
||||
data = resp.json()
|
||||
return data["choices"][0]["message"]["content"]
|
||||
for attempt in range(2):
|
||||
with httpx.Client(timeout=timeout) as client:
|
||||
resp = client.post(url, headers=headers, json=payload)
|
||||
if resp.status_code == 401 or resp.status_code >= 500:
|
||||
return ""
|
||||
data = resp.json()
|
||||
choice = (data.get("choices") or [{}])[0]
|
||||
last_content = (choice.get("message") or {}).get("content") or ""
|
||||
finish = choice.get("finish_reason")
|
||||
if finish == "length" and attempt == 0:
|
||||
payload["max_tokens"] = min(int(payload["max_tokens"]) * 2, 16384)
|
||||
continue
|
||||
return last_content
|
||||
return last_content
|
||||
except Exception:
|
||||
return ""
|
||||
|
|
|
|||
|
|
@ -94,7 +94,7 @@ FUTURES_TICKERS = {
|
|||
MAP_PROMPT_DEFAULT = """\
|
||||
You are a precise, factual OSINT news processor. Your ONLY source of information is the articles provided below. Do NOT add external knowledge, assumptions, training data, or invented facts.
|
||||
|
||||
Focus on breaking important news (geopolitical, military/conflict, security, disasters, major political developments). Ignore futures prices, commodity tape, ticker chatter, and routine market moves unless they themselves are the breaking event.
|
||||
Focus on breaking important news (geopolitical, military/conflict, security, disasters, major political developments). Ignore futures prices, commodity tape, ticker chatter, and routine market moves unless they themselves are the breaking event. If the batch has no critical/high stories, still extract minor incidents and crime reports.
|
||||
|
||||
Write every field in English. Translate if the article is not English.
|
||||
|
||||
|
|
@ -133,7 +133,11 @@ You are writing an English operator HUD brief from the article facts in DATA bel
|
|||
|
||||
Always write a real summary_en that recaps the most important stories present in DATA. Rank geopolitics, military/conflict, security, disasters, and major political developments first. Ignore futures prices, commodity tape, ticker chatter, and routine market data — do not treat price ticks as news.
|
||||
|
||||
ticker and map_items may be empty if nothing is critical or high. Never replace summary_en with a canned empty-brief sentence when DATA contains article facts.
|
||||
Lead with critical and high breaking events. If DATA has no critical/high stories, fill the brief with minor incidents and crime reports rather than writing an empty or unfinished brief. Never truncate mid-sentence; finish every sentence. If you run out of room, drop the lowest-priority item instead of cutting a line short.
|
||||
|
||||
ticker: prefer critical and high. If nothing is critical or high, fill ticker with medium then low incidents and crime so the HUD is not blank.
|
||||
|
||||
map_items may be empty if no located critical/high event is explicit in the data.
|
||||
|
||||
Demand a single JSON object (no markdown fences) with this exact shape:
|
||||
|
||||
|
|
@ -143,9 +147,9 @@ Demand a single JSON object (no markdown fences) with this exact shape:
|
|||
"map_items": [{"headline": "", "importance": "critical", "location_name": "", "lat": 0, "lon": 0, "location_confidence": "city", "category": "military/conflict", "url": ""}]
|
||||
}
|
||||
|
||||
ticker: only critical and high, max 12, ≤140 chars, no markdown.
|
||||
map_items: only critical and high where a real-world location is explicit in the data. Estimate lat/lon. If location is Unknown or not in the data, omit the item. Never invent a place. Max 20.
|
||||
summary_en: English markdown brief of breaking important news for an operator HUD (bullets or short paragraphs). Cover the actual stories in DATA.
|
||||
ticker: max 12, ≤140 chars, no markdown. Rank critical > high > medium > low.
|
||||
map_items: only where a real-world location is explicit in the data. Estimate lat/lon. If location is Unknown or not in the data, omit the item. Never invent a place. Max 20.
|
||||
summary_en: English markdown executive brief for an operator HUD (4–8 complete bullets or short paragraphs). Cover the actual stories in DATA. Complete — never an unfinished sentence.
|
||||
|
||||
DATA:
|
||||
{final_input}
|
||||
|
|
@ -156,7 +160,9 @@ You are writing a daily recap of the last 24 hours of news for an OSINT operator
|
|||
|
||||
Always write a real summary_en daily recap of the most important stories in DATA. Rank geopolitics, military/conflict, security, disasters, and major political developments first. Ignore futures prices, commodity tape, ticker chatter, and routine market data — do not treat price ticks as news.
|
||||
|
||||
ticker and map_items may be empty if nothing is critical or high. Never replace summary_en with a canned empty-brief sentence when DATA contains article facts.
|
||||
Lead with critical and high breaking events. If DATA has no critical/high stories, fill the recap with minor incidents and crime reports rather than writing an empty or unfinished recap. Never truncate mid-sentence; finish every sentence.
|
||||
|
||||
ticker: prefer critical and high. If nothing is critical or high, fill ticker with medium then low incidents and crime so the HUD is not blank.
|
||||
|
||||
Demand a single JSON object (no markdown fences) with this exact shape:
|
||||
|
||||
|
|
@ -166,9 +172,9 @@ Demand a single JSON object (no markdown fences) with this exact shape:
|
|||
"map_items": [{"headline": "", "importance": "critical", "location_name": "", "lat": 0, "lon": 0, "location_confidence": "city", "category": "military/conflict", "url": ""}]
|
||||
}
|
||||
|
||||
ticker: only critical and high, max 12, ≤140 chars, no markdown.
|
||||
map_items: only critical and high where a real-world location is explicit in the data. Estimate lat/lon. If location is Unknown or not in the data, omit the item. Never invent a place. Max 20.
|
||||
summary_en: English markdown daily recap of the last 24 hours of breaking important news. Cover the actual stories in DATA.
|
||||
ticker: max 12, ≤140 chars, no markdown. Rank critical > high > medium > low.
|
||||
map_items: only where a real-world location is explicit in the data. Estimate lat/lon. If location is Unknown or not in the data, omit the item. Never invent a place. Max 20.
|
||||
summary_en: English markdown daily recap of the last 24 hours. Complete sentences. Cover the actual stories in DATA.
|
||||
|
||||
DATA:
|
||||
{final_input}
|
||||
|
|
|
|||
|
|
@ -32,6 +32,16 @@ def test_select_ticker_keeps_critical_high_caps_12():
|
|||
assert len(out) == 12
|
||||
assert all(r["importance"] in ("critical", "high") for r in out)
|
||||
|
||||
|
||||
def test_select_ticker_falls_back_to_medium_low_when_nothing_flagged():
|
||||
rows = [
|
||||
{"headline": "shop theft", "importance": "low"},
|
||||
{"headline": "highway crash", "importance": "medium"},
|
||||
{"headline": "none", "importance": "none"},
|
||||
]
|
||||
out = select_ticker(rows)
|
||||
assert [r["headline"] for r in out] == ["highway crash", "shop theft"]
|
||||
|
||||
def test_select_map_requires_valid_coords_and_flag():
|
||||
items = [
|
||||
{"headline": "A", "importance": "critical", "lat": 50.45, "lon": 30.52, "location_name": "Kyiv"},
|
||||
|
|
|
|||
|
|
@ -67,6 +67,33 @@ def test_json_mode_sets_response_format(monkeypatch):
|
|||
captured = _install_fake(monkeypatch, lambda *a: _ok_response("{}"))
|
||||
chat("p", api_key="k", model="m", base_url=BASE, json_mode=True)
|
||||
assert captured["json"]["response_format"] == {"type": "json_object"}
|
||||
assert captured["json"]["max_tokens"] >= 8192
|
||||
roles = [m["role"] for m in captured["json"]["messages"]]
|
||||
assert "system" in roles
|
||||
assert "user" in roles
|
||||
|
||||
|
||||
def test_retries_once_when_finish_reason_is_length(monkeypatch):
|
||||
calls = {"n": 0}
|
||||
|
||||
def post_impl(*a):
|
||||
calls["n"] += 1
|
||||
if calls["n"] == 1:
|
||||
resp = MagicMock()
|
||||
resp.status_code = 200
|
||||
resp.json.return_value = {
|
||||
"choices": [{
|
||||
"message": {"content": "{\"summary_en\": \"cut off"},
|
||||
"finish_reason": "length",
|
||||
}]
|
||||
}
|
||||
return resp
|
||||
return _ok_response('{"summary_en": "complete brief."}')
|
||||
|
||||
_install_fake(monkeypatch, post_impl)
|
||||
out = chat("p", api_key="k", model="m", base_url=BASE, json_mode=True)
|
||||
assert calls["n"] == 2
|
||||
assert "complete brief" in out
|
||||
|
||||
|
||||
def test_401_returns_empty_string(monkeypatch):
|
||||
|
|
|
|||
|
|
@ -22,6 +22,14 @@ def test_summary_prompt_focuses_on_breaking_news_not_futures():
|
|||
assert "commodity" in p or "market" in p
|
||||
|
||||
|
||||
def test_summary_prompt_covers_critical_then_incidents():
|
||||
p = SUMMARY_PROMPT_DEFAULT.lower()
|
||||
assert "critical" in p
|
||||
assert "crime" in p
|
||||
assert "incident" in p
|
||||
assert "complete" in p or "truncat" in p or "unfinished" in p or "mid-sentence" in p
|
||||
|
||||
|
||||
def test_summary_prompt_does_not_bail_out_with_canned_empty_brief():
|
||||
p = SUMMARY_PROMPT_DEFAULT
|
||||
assert "AND STOP" not in p
|
||||
|
|
|
|||
Loading…
Reference in a new issue