Files
planet/backend/app/services/ai/entity_resolver.py
T
linkong 1c0066edc6
ci / backend (push) Waiting to run
ci / frontend (push) Waiting to run
release: bump version to 0.85.0
2026-12-06 22:47:23 +08:00

1406 lines
56 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Read-time federated entity & relation resolver (Gate 1 · zero duplicate mirror tables)."""
from __future__ import annotations
from datetime import UTC, datetime
from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field
from app.core.logging import get_logger
from app.services.compute_catalog import PARTICIPANTS
logger = get_logger(__name__, service="ontology_resolver")
class EntityRef(BaseModel):
model_config = ConfigDict(extra="forbid")
entity_id: str = Field(min_length=1, max_length=160)
entity_type: Literal[
"country",
"region_group",
"national_hub",
"bgp_incident",
"asn",
"ip_prefix",
"bgp_collector",
"submarine_cable",
"cable_landing_point",
"satellite",
"vessel",
"aircraft",
"gps_jamming_cell",
"earth_layer",
]
label: str
label_en: str = ""
country_code: str | None = None
lat: float | None = None
lon: float | None = None
source_domain: str = "planet"
class RelationCandidate(BaseModel):
model_config = ConfigDict(extra="forbid")
from_id: str
to_id: str
relation_type: Literal[
"bilateral_compute_corridor",
"east_west_green_synergy",
"logical_as_propagation",
"collector_observation",
"geographic_proximity_cable",
"cable_landing_link",
"orbital_regime_membership",
"maritime_corridor_presence",
"cross_domain_overview",
]
relation_status: Literal["verified_observation", "policy_design", "candidate_clue"]
note: str
def resolve_compute_entities(
codes: list[str],
series_payload: dict[str, Any],
*,
include_hubs: bool = False,
) -> tuple[list[EntityRef], list[RelationCandidate]]:
"""Project compute catalog participants and 8 national hubs into unified `EntityRef`s on the fly."""
entities: list[EntityRef] = []
relations: list[RelationCandidate] = []
for code in codes:
meta = PARTICIPANTS.get(code)
if not meta:
continue
is_group = bool(meta.get("members") and len(meta["members"]) > 1)
entities.append(
EntityRef(
entity_id=code,
entity_type="region_group" if is_group else "country",
label=str(meta.get("name_zh") or code),
label_en=str(meta.get("name_en") or code),
country_code=code if not is_group else None,
source_domain="compute_catalog",
)
)
if "CN" in codes and "US" in codes:
relations.append(
RelationCandidate(
from_id="CN",
to_id="US",
relation_type="bilateral_compute_corridor",
relation_status="verified_observation",
note="中美双边算力平价指数(RPI)与智算结构对照走廊",
)
)
if include_hubs or "CN" in codes:
for hub in (series_payload.get("national_hubs") or [])[:8]:
hid = str(hub.get("id") or "")
if not hid:
continue
entities.append(
EntityRef(
entity_id=hid,
entity_type="national_hub",
label=str(hub.get("name_zh") or hid),
label_en=str(hub.get("name_en") or hid),
country_code="CN",
lat=hub.get("lat"),
lon=hub.get("lon"),
source_domain="compute_history",
)
)
if include_hubs and str(hub.get("role") or "") == "west_green_training":
relations.append(
RelationCandidate(
from_id="CN",
to_id=hid,
relation_type="east_west_green_synergy",
relation_status="policy_design",
note=f"西部绿电训推协同枢纽(目标 PUE {hub.get('target_pue', '≤1.20')})",
)
)
return entities, relations
def resolve_incident_entities(
incident: dict[str, Any],
) -> tuple[list[EntityRef], list[RelationCandidate]]:
"""Project real BGPIncident ASNs, prefixes, collectors, and candidate proximity cables without false causality."""
entities: list[EntityRef] = []
relations: list[RelationCandidate] = []
inc_key = str(incident.get("incident_key") or "unknown-incident")
entities.append(
EntityRef(
entity_id=inc_key,
entity_type="bgp_incident",
label=str(incident.get("title") or inc_key),
label_en=str(incident.get("title") or inc_key),
source_domain=str(incident.get("source") or "bgp_incidents"),
)
)
for asn in (incident.get("affected_asns") or [])[:8]:
asn_id = f"AS{asn}"
entities.append(
EntityRef(
entity_id=asn_id,
entity_type="asn",
label=asn_id,
label_en=asn_id,
source_domain="bgp_incidents",
)
)
relations.append(
RelationCandidate(
from_id=inc_key,
to_id=asn_id,
relation_type="logical_as_propagation",
relation_status="verified_observation",
note="控制面 BGP UPDATE 报文观测到的涉事自治系统(逻辑路由层,非物理海缆层)",
)
)
for prefix in (incident.get("affected_prefixes") or [])[:6]:
p_str = str(prefix)
entities.append(
EntityRef(
entity_id=p_str,
entity_type="ip_prefix",
label=p_str,
label_en=p_str,
source_domain="bgp_incidents",
)
)
for col in (incident.get("affected_collectors") or [])[:6]:
col_str = str(col)
entities.append(
EntityRef(
entity_id=col_str,
entity_type="bgp_collector",
label=col_str,
label_en=col_str,
source_domain="bgp_collector_locations",
)
)
relations.append(
RelationCandidate(
from_id=col_str,
to_id=inc_key,
relation_type="collector_observation",
relation_status="verified_observation",
note=f"观测站 {col_str} 捕获异常路由通告(代表采集器观测视角,不等同于终端中断热区)",
)
)
for cable_hint in (incident.get("related_cables") or [])[:6]:
if isinstance(cable_hint, dict):
names = cable_hint.get("cable_names") or []
lp = str(cable_hint.get("landing_point") or cable_hint.get("city") or "邻近登陆站")
dist = cable_hint.get("distance_km")
label = f"{', '.join(names[:2])} ({lp})" if names else lp
cid = f"cable-clue:{lp}"
dist_note = f"(距观测点约 {dist} km)" if dist is not None else ""
else:
label = str(cable_hint)
cid = f"cable-clue:{label}"
dist_note = ""
entities.append(
EntityRef(
entity_id=cid,
entity_type="submarine_cable",
label=label,
label_en=label,
source_domain="arcgis_cables",
)
)
relations.append(
RelationCandidate(
from_id=inc_key,
to_id=cid,
relation_type="geographic_proximity_cable",
relation_status="candidate_clue",
note=f"地理邻近基础设施候选线索{dist_note};尚无独立海缆断缆或光功率告警确认物理层因果。",
)
)
return entities, relations
# ---------------------------------------------------------------------------
# §3.7 Federated Read-Time Ontology Resolver (`{type}:{id}` across 12 domains)
# ---------------------------------------------------------------------------
SUPPORTED_ONTOLOGY_TYPES: tuple[str, ...] = (
"aircraft",
"vessel",
"cable",
"landing_point",
"asn",
"gps_jamming_cell",
"disaster_event",
"chokepoint",
"port",
"compute_center",
"country",
"interactable",
)
_TYPE_TO_FRESHNESS_DOMAIN: dict[str, str] = {
"aircraft": "aircraft",
"vessel": "vessels",
"cable": "cables",
"landing_point": "cables",
"asn": "bgp",
"gps_jamming_cell": "gps_jamming",
"disaster_event": "disasters",
"compute_center": "compute",
"chokepoint": "vessels",
"port": "vessels",
}
_STATIC_COUNTRIES: dict[str, dict[str, Any]] = {
"CN": {"name": "中国", "name_en": "China", "lat": 35.86, "lon": 104.19},
"US": {"name": "美国", "name_en": "United States", "lat": 39.83, "lon": -98.58},
"JP": {"name": "日本", "name_en": "Japan", "lat": 36.20, "lon": 138.25},
"KR": {"name": "韩国", "name_en": "South Korea", "lat": 35.91, "lon": 127.77},
"SG": {"name": "新加坡", "name_en": "Singapore", "lat": 1.35, "lon": 103.82},
"GB": {"name": "英国", "name_en": "United Kingdom", "lat": 55.38, "lon": -3.44},
"DE": {"name": "德国", "name_en": "Germany", "lat": 51.16, "lon": 10.45},
"FR": {"name": "法国", "name_en": "France", "lat": 46.23, "lon": 2.21},
"AE": {"name": "阿联酋", "name_en": "United Arab Emirates", "lat": 23.42, "lon": 53.85},
"EG": {"name": "埃及", "name_en": "Egypt", "lat": 26.82, "lon": 30.80},
"MY": {"name": "马来西亚", "name_en": "Malaysia", "lat": 4.21, "lon": 101.98},
"ID": {"name": "印度尼西亚", "name_en": "Indonesia", "lat": -0.79, "lon": 113.92},
"IN": {"name": "印度", "name_en": "India", "lat": 20.59, "lon": 78.96},
"TW": {"name": "中国台湾", "name_en": "Taiwan", "lat": 23.70, "lon": 120.96},
"SA": {"name": "沙特阿拉伯", "name_en": "Saudi Arabia", "lat": 23.89, "lon": 45.08},
"OM": {"name": "阿曼", "name_en": "Oman", "lat": 21.47, "lon": 55.98},
"TR": {"name": "土耳其", "name_en": "Turkey", "lat": 38.96, "lon": 35.24},
"ES": {"name": "西班牙", "name_en": "Spain", "lat": 40.46, "lon": -3.75},
"PA": {"name": "巴拿马", "name_en": "Panama", "lat": 8.54, "lon": -80.78},
"DJ": {"name": "吉布提", "name_en": "Djibouti", "lat": 11.83, "lon": 42.59},
"YE": {"name": "也门", "name_en": "Yemen", "lat": 15.55, "lon": 48.52},
"IR": {"name": "伊朗", "name_en": "Iran", "lat": 32.43, "lon": 53.69},
}
def format_object_id(object_type: str, raw_id: Any) -> str:
otype = str(object_type or "").strip().lower()
if otype not in SUPPORTED_ONTOLOGY_TYPES:
raise ValueError(f"Unsupported ontology object type: {object_type}")
ident = str(raw_id or "").strip()
if not ident:
raise ValueError("Ontology object identifier is required")
return f"{otype}:{ident}"
def parse_object_id(object_id: str) -> tuple[str, str]:
raw = str(object_id or "").strip()
if ":" not in raw:
raise ValueError(f"Ontology object_id must follow '{{type}}:{{id}}': {object_id}")
otype, ident = raw.split(":", 1)
otype = otype.strip().lower()
ident = ident.strip()
if otype not in SUPPORTED_ONTOLOGY_TYPES or not ident:
raise ValueError(f"Unsupported ontology object_id: {object_id}")
return otype, ident
def _coerce_utc_dt(value: Any) -> datetime | None:
if value is None:
return None
if isinstance(value, datetime):
return value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
if isinstance(value, str) and value.strip():
try:
parsed = datetime.fromisoformat(value.strip().replace("Z", "+00:00"))
return parsed.replace(tzinfo=UTC) if parsed.tzinfo is None else parsed.astimezone(UTC)
except ValueError:
return None
return None
def _compute_item_freshness(
object_type: str,
observed_at: Any,
ingested_at: Any = None,
) -> dict[str, Any]:
from app.core.time import to_iso8601_utc
from app.services.source_freshness import DOMAIN_SPEC_BY_KEY
domain = _TYPE_TO_FRESHNESS_DOMAIN.get(object_type)
spec = DOMAIN_SPEC_BY_KEY.get(domain) if domain else None
threshold = spec.threshold_seconds if spec else None
obs_dt = _coerce_utc_dt(observed_at)
ing_dt = _coerce_utc_dt(ingested_at)
now = datetime.now(UTC)
if object_type in {"chokepoint", "port", "country"}:
return {
"domain": domain or "static_reference",
"state": "fresh",
"is_stale": False,
"age_seconds": 0,
"threshold_seconds": threshold,
"observed_at": to_iso8601_utc(obs_dt) if obs_dt else None,
"ingested_at": to_iso8601_utc(ing_dt) if ing_dt else None,
}
ref_dt = obs_dt or ing_dt
if ref_dt is None:
return {
"domain": domain,
"state": "offline",
"is_stale": True,
"age_seconds": None,
"threshold_seconds": threshold,
"observed_at": None,
"ingested_at": None,
}
age = max(0, int((now - ref_dt).total_seconds()))
if threshold is None:
state = "fresh"
is_stale = False
elif age <= threshold:
state = "fresh"
is_stale = False
elif age <= threshold * 4:
state = "stale"
is_stale = True
else:
state = "very_stale"
is_stale = True
return {
"domain": domain,
"state": state,
"is_stale": is_stale,
"age_seconds": age,
"threshold_seconds": threshold,
"observed_at": to_iso8601_utc(obs_dt) if obs_dt else None,
"ingested_at": to_iso8601_utc(ing_dt) if ing_dt else None,
}
def _polygon_centroid(ring: list[list[float]]) -> tuple[float | None, float | None]:
pts = [pt for pt in (ring or []) if isinstance(pt, (list, tuple)) and len(pt) >= 2]
if not pts:
return None, None
lon = sum(float(pt[0]) for pt in pts) / len(pts)
lat = sum(float(pt[1]) for pt in pts) / len(pts)
return round(lat, 5), round(lon, 5)
def _cable_centroid(extra: dict[str, Any]) -> tuple[float | None, float | None]:
coords = extra.get("coordinates") or (extra.get("geometry") or {}).get("coordinates")
pts: list[tuple[float, float]] = []
if isinstance(coords, list) and coords:
if isinstance(coords[0], (list, tuple)) and coords[0] and isinstance(coords[0][0], (int, float)):
for pt in coords:
if isinstance(pt, (list, tuple)) and len(pt) >= 2:
pts.append((float(pt[1]), float(pt[0])))
else:
for line in coords:
if isinstance(line, list):
for pt in line:
if isinstance(pt, (list, tuple)) and len(pt) >= 2:
pts.append((float(pt[1]), float(pt[0])))
if not pts:
return None, None
mid = pts[len(pts) // 2]
return round(mid[0], 5), round(mid[1], 5)
def _country_code_from_name(country_val: str | None) -> str | None:
if not country_val:
return None
val = str(country_val).strip()
upper = val.upper()
if upper in _STATIC_COUNTRIES or upper in PARTICIPANTS:
return upper
low = val.lower()
for code, meta in PARTICIPANTS.items():
if len(code) <= 3 and (
str(meta.get("name_zh") or "").lower() == low
or str(meta.get("name_en") or "").lower() == low
):
return code
for code, meta in _STATIC_COUNTRIES.items():
if meta["name"].lower() == low or meta["name_en"].lower() == low:
return code
return None
async def _load_aliases_for_object(db: Any, object_id: str) -> list[dict[str, Any]]:
if not hasattr(db, "execute"):
return []
from sqlalchemy import select
from app.models.ontology import OntologyEntityAlias
try:
rows = list(
(
await db.execute(
select(OntologyEntityAlias).where(OntologyEntityAlias.object_id == object_id)
)
)
.scalars()
.all()
)
return [r.to_dict() for r in rows]
except Exception:
return []
async def resolve_alias_to_object_ids(db: Any, alias_text: str) -> list[str]:
"""Look up canonical `{type}:{id}` identifiers associated with a curated alias."""
if not hasattr(db, "execute"):
return []
from sqlalchemy import func as sql_func, select
from app.models.ontology import OntologyEntityAlias
cleaned = str(alias_text or "").strip().lower()
if not cleaned:
return []
try:
rows = list(
(
await db.execute(
select(OntologyEntityAlias.object_id).where(
sql_func.lower(OntologyEntityAlias.alias) == cleaned
)
)
)
.scalars()
.all()
)
return list(dict.fromkeys(str(r) for r in rows if r))
except Exception:
return []
async def resolve_ontology_object(db: Any, object_id: str) -> dict[str, Any] | None:
"""Resolve a canonical `{type}:{id}` (or curated alias) on the fly across 12 domains."""
from sqlalchemy import desc, select
raw = str(object_id or "").strip()
if ":" not in raw:
aliased = await resolve_alias_to_object_ids(db, raw)
if not aliased:
return None
raw = aliased[0]
otype, ident = parse_object_id(raw)
resolved: dict[str, Any] | None = None
if otype == "aircraft" and hasattr(db, "execute"):
from app.models.aircraft import AircraftCurrentState
row = (
await db.execute(
select(AircraftCurrentState).where(AircraftCurrentState.icao24 == ident.lower())
)
).scalars().first() or (
await db.execute(
select(AircraftCurrentState).where(AircraftCurrentState.icao24 == ident)
)
).scalars().first()
if row:
data = row.to_dict()
resolved = {
"object_id": format_object_id("aircraft", row.icao24),
"object_type": "aircraft",
"label": str(row.callsign or row.icao24),
"label_en": str(row.callsign or row.icao24),
"lat": float(row.lat),
"lon": float(row.lon),
"attributes": data,
"provenance": {
"source": row.source,
"observed_at": data["observed_at"],
"ingested_at": data["ingested_at"],
},
"freshness": _compute_item_freshness("aircraft", row.observed_at, row.ingested_at),
}
elif otype == "vessel" and hasattr(db, "execute"):
from app.models.vessel import VesselCurrentState
from app.services.maritime_geography import find_chokepoint_for_point
from app.services.vessel_types import classify_military_vessel, is_cable_repair_vessel
try:
mmsi_val = int(ident)
except ValueError:
mmsi_val = None
if mmsi_val is not None:
row = (
await db.execute(select(VesselCurrentState).where(VesselCurrentState.mmsi == mmsi_val))
).scalars().first()
if row:
from app.core.time import to_iso8601_utc
m_role, m_src = classify_military_vessel(
vessel_type=row.vessel_type_name or row.vessel_type,
name=row.name,
callsign=row.callsign,
)
is_cs, cs_src = is_cable_repair_vessel(vessel_type=row.vessel_type, name=row.name)
cp = find_chokepoint_for_point(float(row.lat), float(row.lon))
attrs = row.to_dict()
attrs["received_at"] = to_iso8601_utc(row.observed_at)
attrs["observed_at"] = attrs["received_at"]
attrs["military_role"] = m_role
attrs["military_source"] = m_src
attrs["is_warship"] = m_role is not None
attrs["is_cable_ship"] = bool(is_cs)
attrs["cable_ship_source"] = cs_src
attrs["chokepoint_id"] = cp["id"] if cp else None
resolved = {
"object_id": format_object_id("vessel", row.mmsi),
"object_type": "vessel",
"label": str(row.name or row.mmsi),
"label_en": str(row.name or row.mmsi),
"lat": float(row.lat),
"lon": float(row.lon),
"attributes": attrs,
"provenance": {
"source": row.source,
"observed_at": attrs["observed_at"],
"ingested_at": to_iso8601_utc(row.updated_at),
},
"freshness": _compute_item_freshness("vessel", row.observed_at, row.updated_at),
}
elif otype == "cable" and hasattr(db, "execute"):
from app.core.time import to_iso8601_utc
from app.models.collected_data import CollectedData
rows = list(
(
await db.execute(
select(CollectedData)
.where(CollectedData.source == "arcgis_cables", CollectedData.is_current.is_(True))
.limit(1500)
)
)
.scalars()
.all()
)
matched_row = None
for r in rows:
extra = r.extra_data or {}
cand_ids = {
str(extra.get("cable_id") or "").strip(),
str(extra.get("id") or "").strip(),
str(r.source_id or "").strip(),
str(r.name or "").strip(),
}
if ident in cand_ids or ident.lower() in {c.lower() for c in cand_ids if c}:
matched_row = r
break
if matched_row:
extra = matched_row.extra_data or {}
lat, lon = _cable_centroid(extra)
cid = str(extra.get("cable_id") or matched_row.source_id or matched_row.name or ident)
resolved = {
"object_id": format_object_id("cable", cid),
"object_type": "cable",
"label": str(matched_row.name or cid),
"label_en": str(matched_row.name or cid),
"lat": lat,
"lon": lon,
"attributes": {
"cable_id": cid,
"name": matched_row.name,
"owners": extra.get("owners"),
"rfs": extra.get("rfs"),
"length": extra.get("length"),
"is_planned": extra.get("is_planned"),
"geometry_type": (extra.get("geometry") or {}).get("type"),
},
"provenance": {
"source": matched_row.source,
"observed_at": to_iso8601_utc(matched_row.reference_date or matched_row.collected_at),
"ingested_at": to_iso8601_utc(matched_row.collected_at),
},
"freshness": _compute_item_freshness("cable", matched_row.reference_date or matched_row.collected_at, matched_row.collected_at),
}
elif otype == "landing_point" and hasattr(db, "execute"):
from app.core.time import to_iso8601_utc
from app.models.collected_data import CollectedData
rows = list(
(
await db.execute(
select(CollectedData)
.where(CollectedData.source == "arcgis_landing_points", CollectedData.is_current.is_(True))
.limit(2500)
)
)
.scalars()
.all()
)
matched_row = None
for r in rows:
extra = r.extra_data or {}
cand_ids = {
str(extra.get("city_id") or "").strip(),
str(extra.get("id") or "").strip(),
str(r.source_id or "").strip(),
str(r.name or "").strip(),
}
if ident in cand_ids or ident.lower() in {c.lower() for c in cand_ids if c}:
matched_row = r
break
if matched_row:
extra = matched_row.extra_data or {}
lat = float(extra["latitude"]) if extra.get("latitude") is not None else None
lon = float(extra["longitude"]) if extra.get("longitude") is not None else None
lid = str(extra.get("city_id") or matched_row.source_id or matched_row.name or ident)
resolved = {
"object_id": format_object_id("landing_point", lid),
"object_type": "landing_point",
"label": str(matched_row.name or lid),
"label_en": str(matched_row.name or lid),
"lat": lat,
"lon": lon,
"attributes": {
"city_id": extra.get("city_id"),
"country": extra.get("country"),
"city_name": matched_row.name,
},
"provenance": {
"source": matched_row.source,
"observed_at": to_iso8601_utc(matched_row.collected_at),
"ingested_at": to_iso8601_utc(matched_row.collected_at),
},
"freshness": _compute_item_freshness("landing_point", matched_row.collected_at, matched_row.collected_at),
}
elif otype == "asn" and hasattr(db, "execute"):
from app.core.time import to_iso8601_utc
from app.models.bgp_incident import BGPIncident
from app.models.collected_data import CollectedData
clean_num = ident.upper().removeprefix("AS").strip()
canonical_asn = f"AS{clean_num}"
incidents = list(
(await db.execute(select(BGPIncident).order_by(desc(BGPIncident.started_at)).limit(100)))
.scalars()
.all()
)
matched_incidents = [
inc
for inc in incidents
if clean_num in [str(a).upper().removeprefix("AS") for a in (inc.affected_asns or [])]
]
geo_rows = list(
(
await db.execute(
select(CollectedData)
.where(
CollectedData.source == "iptoasn_prefix_geo",
CollectedData.is_current.is_(True),
)
.limit(500)
)
)
.scalars()
.all()
)
matched_geo = [
r for r in geo_rows
if str((r.extra_data or {}).get("asn") or r.source_id or "").upper().removeprefix("AS") == clean_num
]
if matched_incidents or matched_geo:
first_inc = matched_incidents[0] if matched_incidents else None
first_geo = matched_geo[0] if matched_geo else None
obs_ts = first_inc.started_at if first_inc else (first_geo.collected_at if first_geo else None)
extra = first_geo.extra_data or {} if first_geo else {}
resolved = {
"object_id": format_object_id("asn", canonical_asn),
"object_type": "asn",
"label": str(extra.get("as_name") or canonical_asn),
"label_en": str(extra.get("as_name") or canonical_asn),
"lat": float(extra["latitude"]) if extra.get("latitude") is not None else None,
"lon": float(extra["longitude"]) if extra.get("longitude") is not None else None,
"attributes": {
"asn": canonical_asn,
"country": extra.get("country"),
"incident_count": len(matched_incidents),
"latest_incident_key": first_inc.incident_key if first_inc else None,
},
"provenance": {
"source": "bgp_incidents" if first_inc else "iptoasn_prefix_geo",
"observed_at": to_iso8601_utc(obs_ts),
"ingested_at": to_iso8601_utc(first_inc.created_at if first_inc else (first_geo.collected_at if first_geo else None)),
},
"freshness": _compute_item_freshness("asn", obs_ts, obs_ts),
}
elif otype == "gps_jamming_cell" and hasattr(db, "execute"):
from app.models.gps_jamming import GPSJammingCell
row = (
await db.execute(
select(GPSJammingCell)
.where(GPSJammingCell.h3_index == ident)
.order_by(desc(GPSJammingCell.observed_date))
.limit(1)
)
).scalars().first()
if row:
data = row.to_dict()
resolved = {
"object_id": format_object_id("gps_jamming_cell", row.h3_index),
"object_type": "gps_jamming_cell",
"label": f"GNSS Jamming {row.h3_index} ({row.level})",
"label_en": f"GNSS Jamming {row.h3_index} ({row.level})",
"lat": float(row.lat),
"lon": float(row.lon),
"attributes": data,
"provenance": {
"source": row.source,
"observed_at": row.observed_date,
"ingested_at": data["ingested_at"],
},
"freshness": _compute_item_freshness("gps_jamming_cell", row.ingested_at, row.ingested_at),
}
elif otype == "disaster_event" and hasattr(db, "execute"):
from app.models.disaster import DisasterEvent
row = None
if ident.isdigit():
row = (
await db.execute(select(DisasterEvent).where(DisasterEvent.id == int(ident)))
).scalars().first()
if row is None:
row = (
await db.execute(
select(DisasterEvent).where(DisasterEvent.source_event_id == ident)
)
).scalars().first()
if row:
data = row.to_dict()
resolved = {
"object_id": format_object_id("disaster_event", row.id),
"object_type": "disaster_event",
"label": row.title,
"label_en": row.title,
"lat": float(row.lat),
"lon": float(row.lon),
"attributes": data,
"provenance": {
"source": row.source,
"observed_at": data["observed_at"],
"ingested_at": data["ingested_at"],
},
"freshness": _compute_item_freshness("disaster_event", row.observed_at, row.ingested_at),
}
elif otype == "chokepoint":
from app.services.maritime_geography import load_chokepoints
for cp in load_chokepoints():
if (
str(cp.get("id") or "").lower() == ident.lower()
or str(cp.get("name") or "").lower() == ident.lower()
or str(cp.get("name_en") or "").lower() == ident.lower()
):
lat, lon = _polygon_centroid(cp.get("polygon") or [])
resolved = {
"object_id": format_object_id("chokepoint", cp["id"]),
"object_type": "chokepoint",
"label": str(cp.get("name_zh") or cp.get("name") or cp["id"]),
"label_en": str(cp.get("name") or cp["id"]),
"lat": lat,
"lon": lon,
"attributes": cp,
"provenance": {
"source": str(cp.get("source") or "maritime_chokepoints"),
"observed_at": None,
"ingested_at": None,
},
"freshness": _compute_item_freshness("chokepoint", None, None),
}
break
elif otype == "port":
from app.services.maritime_geography import load_strategic_ports
for port in load_strategic_ports():
if (
str(port.get("id") or "").lower() == ident.lower()
or str(port.get("name") or "").lower() == ident.lower()
or str(port.get("name_en") or "").lower() == ident.lower()
):
resolved = {
"object_id": format_object_id("port", port["id"]),
"object_type": "port",
"label": str(port.get("name_zh") or port.get("name") or port["id"]),
"label_en": str(port.get("name") or port["id"]),
"lat": float(port["lat"]),
"lon": float(port["lon"]),
"attributes": port,
"provenance": {
"source": str(port.get("source") or "strategic_ports"),
"observed_at": None,
"ingested_at": None,
},
"freshness": _compute_item_freshness("port", None, None),
}
break
elif otype == "compute_center" and hasattr(db, "execute"):
from app.core.time import to_iso8601_utc
from app.models.compute_center_location import ComputeCenterLocationRecord
row = None
if ident.isdigit():
row = (
await db.execute(
select(ComputeCenterLocationRecord).where(
ComputeCenterLocationRecord.id == int(ident)
)
)
).scalars().first()
if row is None:
row = (
await db.execute(
select(ComputeCenterLocationRecord)
.where(ComputeCenterLocationRecord.source_id == ident)
.limit(1)
)
).scalars().first()
if row:
attrs = row.to_location_dict()
resolved = {
"object_id": format_object_id("compute_center", row.id),
"object_type": "compute_center",
"label": str(row.name or row.source_id),
"label_en": str(row.name or row.source_id),
"lat": float(row.latitude) if row.latitude is not None else None,
"lon": float(row.longitude) if row.longitude is not None else None,
"attributes": attrs,
"provenance": {
"source": row.source,
"observed_at": to_iso8601_utc(row.verified_at or row.updated_at),
"ingested_at": to_iso8601_utc(row.updated_at or row.created_at),
},
"freshness": _compute_item_freshness("compute_center", row.verified_at or row.updated_at, row.updated_at),
}
elif otype == "country":
code = ident.upper()
part = PARTICIPANTS.get(code)
static = _STATIC_COUNTRIES.get(code)
if part or static:
resolved = {
"object_id": format_object_id("country", code),
"object_type": "country",
"label": str((part or {}).get("name_zh") or (static or {}).get("name") or code),
"label_en": str((part or {}).get("name_en") or (static or {}).get("name_en") or code),
"lat": (static or {}).get("lat"),
"lon": (static or {}).get("lon"),
"attributes": {"country_code": code, **(part or {}), **(static or {})},
"provenance": {
"source": "compute_catalog_participants" if part else "country_reference",
"observed_at": None,
"ingested_at": None,
},
"freshness": _compute_item_freshness("country", None, None),
}
elif otype == "interactable" and hasattr(db, "execute"):
from app.core.time import to_iso8601_utc
from app.models.earth_interactable import EarthInteractable
row = (
await db.execute(
select(EarthInteractable).where(
EarthInteractable.id == ident,
EarthInteractable.is_deleted.is_(False),
)
)
).scalars().first()
if row:
resolved = {
"object_id": format_object_id("interactable", row.id),
"object_type": "interactable",
"label": str(row.label or row.id),
"label_en": str(row.label or row.id),
"lat": float(row.latitude),
"lon": float(row.longitude),
"attributes": {
"id": row.id,
"layer": row.layer,
"kind": row.kind,
"description": row.description,
"altitude": row.altitude,
"properties": row.properties or {},
"revision": row.revision,
},
"provenance": {
"source": str((row.properties or {}).get("source") or f"earth_interactable:{row.kind}"),
"observed_at": to_iso8601_utc(row.updated_at or row.created_at),
"ingested_at": to_iso8601_utc(row.created_at),
},
"freshness": _compute_item_freshness("interactable", row.updated_at or row.created_at, row.created_at),
}
if resolved is None:
return None
resolved["aliases"] = await _load_aliases_for_object(db, resolved["object_id"])
return resolved
async def _derive_one_hop(
db: Any,
node: dict[str, Any],
*,
radius_km: float,
limit: int,
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
"""Derive 1-hop topology, spatial, and analyst-asserted neighbors for a resolved node."""
from sqlalchemy import or_, select
from app.models.aircraft import AircraftCurrentState
from app.models.collected_data import CollectedData
from app.models.compute_center_location import ComputeCenterLocationRecord
from app.models.disaster import DisasterEvent
from app.models.earth_interactable import EarthInteractable
from app.models.gps_jamming import GPSJammingCell
from app.models.ontology import AnalystLink
from app.models.vessel import VesselCurrentState
from app.services.maritime_geography import (
load_chokepoints,
load_strategic_ports,
point_in_polygon,
)
from app.services.nga_advisories import haversine_km
oid = str(node["object_id"])
otype = str(node["object_type"])
lat = node.get("lat")
lon = node.get("lon")
attrs = node.get("attributes") or {}
neighbors: dict[str, dict[str, Any]] = {}
edges: list[dict[str, Any]] = []
seen_edges: set[tuple[str, str, str, str]] = set()
async def _attach(target_id: str, rel_type: str, rel_source: str, note: str, evidence_ids: list[str] | None = None) -> None:
if len(edges) >= limit or target_id == oid:
return
sig = (oid, target_id, rel_type, rel_source)
if sig in seen_edges:
return
if target_id not in neighbors:
target_obj = await resolve_ontology_object(db, target_id)
if not target_obj:
return
neighbors[target_id] = target_obj
seen_edges.add(sig)
edges.append(
{
"from_object_id": oid,
"to_object_id": target_id,
"relation_type": rel_type,
"relation_source": rel_source,
"note": note,
"evidence_ids": evidence_ids or [],
}
)
# 1. Analyst-asserted links (always merged cleanly)
if hasattr(db, "execute"):
try:
analyst_rows = list(
(
await db.execute(
select(AnalystLink).where(
AnalystLink.status == "active",
or_(
AnalystLink.from_object_id == oid,
AnalystLink.to_object_id == oid,
),
)
)
)
.scalars()
.all()
)
for link in analyst_rows:
other_id = link.to_object_id if link.from_object_id == oid else link.from_object_id
if other_id not in neighbors:
resolved_other = await resolve_ontology_object(db, other_id)
if not resolved_other:
# Preserve curated reference placeholder if underlying external entity isn't in local DB
parsed_type = other_id.split(":", 1)[0] if ":" in other_id else "interactable"
resolved_other = {
"object_id": other_id,
"object_type": parsed_type,
"label": other_id,
"label_en": other_id,
"lat": None,
"lon": None,
"attributes": {},
"aliases": [],
"provenance": {"source": "analyst_link", "observed_at": None, "ingested_at": None},
"freshness": _compute_item_freshness(parsed_type, None, None),
}
neighbors[other_id] = resolved_other
edges.append(
{
"id": f"analyst:{link.id}",
"from_object_id": link.from_object_id,
"to_object_id": link.to_object_id,
"relation_type": link.relation_type,
"relation_source": "analyst_asserted",
"note": link.note,
"evidence_ids": list(link.evidence_ids or []),
}
)
except Exception as exc:
logger.debug_event(
"Skipped analyst link lookup",
event="ontology.analyst_links.skipped",
context={"object_id": oid, "error": str(exc)},
)
# 2. Derived topology edges (cable <-> landing_point <-> country <-> compute_center / asn)
if otype == "cable" and hasattr(db, "execute"):
cable_id = str(attrs.get("cable_id") or oid.split(":", 1)[1])
rel_rows = list(
(
await db.execute(
select(CollectedData).where(
CollectedData.source == "arcgis_cable_landing_relation",
CollectedData.is_current.is_(True),
)
)
)
.scalars()
.all()
)
for rel in rel_rows:
extra = rel.extra_data or {}
if str(extra.get("cable_id") or "") == cable_id and extra.get("city_id") is not None:
await _attach(
format_object_id("landing_point", extra["city_id"]),
"cable_lands_at",
"derived_topology",
"海底光缆-登陆站拓扑关系",
)
elif otype == "landing_point":
country_code = _country_code_from_name(attrs.get("country"))
if country_code:
await _attach(
format_object_id("country", country_code),
"located_in_country",
"derived_topology",
"登陆站所属国家/地区",
)
city_id = str(attrs.get("city_id") or oid.split(":", 1)[1])
if hasattr(db, "execute"):
rel_rows = list(
(
await db.execute(
select(CollectedData).where(
CollectedData.source == "arcgis_cable_landing_relation",
CollectedData.is_current.is_(True),
)
)
)
.scalars()
.all()
)
for rel in rel_rows:
extra = rel.extra_data or {}
if str(extra.get("city_id") or "") == city_id and extra.get("cable_id") is not None:
await _attach(
format_object_id("cable", extra["cable_id"]),
"cable_lands_at",
"derived_topology",
"登陆站承载海底光缆",
)
elif otype == "compute_center":
cc = _country_code_from_name(attrs.get("country"))
if cc:
await _attach(
format_object_id("country", cc),
"hosted_in_country",
"derived_topology",
"算力中心所属国家/地区",
)
elif otype == "asn":
cc = _country_code_from_name(attrs.get("country"))
if cc:
await _attach(
format_object_id("country", cc),
"asn_registered_in_country",
"derived_topology",
"自治系统注册国家/地区",
)
elif otype == "country" and hasattr(db, "execute"):
cc = oid.split(":", 1)[1].upper()
lp_rows = list(
(
await db.execute(
select(CollectedData).where(
CollectedData.source == "arcgis_landing_points",
CollectedData.is_current.is_(True),
).limit(500)
)
)
.scalars()
.all()
)
for lp in lp_rows:
extra = lp.extra_data or {}
if _country_code_from_name(extra.get("country")) == cc:
lid = str(extra.get("city_id") or lp.source_id or lp.name or "")
if lid:
await _attach(
format_object_id("landing_point", lid),
"located_in_country",
"derived_topology",
"境内海缆登陆站",
)
comp_rows = list(
(await db.execute(select(ComputeCenterLocationRecord).limit(300))).scalars().all()
)
for comp in comp_rows:
if _country_code_from_name(comp.country) == cc:
await _attach(
format_object_id("compute_center", comp.id),
"hosted_in_country",
"derived_topology",
"境内算力中心",
)
for port in load_strategic_ports():
if str(port.get("country") or "").upper() == cc:
await _attach(
format_object_id("port", port["id"]),
"port_in_country",
"derived_topology",
"境内战略港口",
)
geo_rows = list(
(
await db.execute(
select(CollectedData)
.where(
CollectedData.source == "iptoasn_prefix_geo",
CollectedData.is_current.is_(True),
)
.limit(400)
)
)
.scalars()
.all()
)
seen_asns: set[str] = set()
for gr in geo_rows:
extra = gr.extra_data or {}
if _country_code_from_name(extra.get("country")) == cc:
raw_asn = str(extra.get("asn") or gr.source_id or "").upper().removeprefix("AS").strip()
if raw_asn and raw_asn not in seen_asns:
seen_asns.add(raw_asn)
await _attach(
format_object_id("asn", f"AS{raw_asn}"),
"asn_registered_in_country",
"derived_topology",
"境内注册自治系统",
)
elif otype == "port":
cc = _country_code_from_name(attrs.get("country"))
if cc:
await _attach(
format_object_id("country", cc),
"port_in_country",
"derived_topology",
"港口所属国家",
)
# 3. Derived spatial edges when object has coordinates
if isinstance(lat, (int, float)) and isinstance(lon, (int, float)):
for cp in load_chokepoints():
cp_id = str(cp.get("id") or "")
if not cp_id or (otype == "chokepoint" and oid == f"chokepoint:{cp_id}"):
continue
if point_in_polygon(float(lat), float(lon), cp.get("polygon") or []):
await _attach(
format_object_id("chokepoint", cp_id),
"inside_chokepoint",
"derived_spatial",
"位于咽喉要道多边形范围内",
)
else:
cp_lat, cp_lon = _polygon_centroid(cp.get("polygon") or [])
if cp_lat is not None and cp_lon is not None and haversine_km(float(lat), float(lon), cp_lat, cp_lon) <= radius_km:
await _attach(
format_object_id("chokepoint", cp_id),
"near_chokepoint",
"derived_spatial",
f"距离咽喉要道 <= {int(radius_km)} km",
)
for port in load_strategic_ports():
if haversine_km(float(lat), float(lon), float(port["lat"]), float(port["lon"])) <= radius_km:
await _attach(
format_object_id("port", port["id"]),
"near_port",
"derived_spatial",
f"距离战略港口 <= {int(radius_km)} km",
)
if hasattr(db, "execute"):
for ac in list((await db.execute(select(AircraftCurrentState).limit(250))).scalars().all()):
if haversine_km(float(lat), float(lon), float(ac.lat), float(ac.lon)) <= radius_km:
await _attach(
format_object_id("aircraft", ac.icao24),
"spatial_co_location",
"derived_spatial",
f"空间邻近飞行器 (<= {int(radius_km)} km)",
)
for vs in list((await db.execute(select(VesselCurrentState).limit(250))).scalars().all()):
if haversine_km(float(lat), float(lon), float(vs.lat), float(vs.lon)) <= radius_km:
await _attach(
format_object_id("vessel", vs.mmsi),
"spatial_co_location",
"derived_spatial",
f"空间邻近船舶 (<= {int(radius_km)} km)",
)
for gz in list((await db.execute(select(GPSJammingCell).limit(150))).scalars().all()):
if haversine_km(float(lat), float(lon), float(gz.lat), float(gz.lon)) <= radius_km:
await _attach(
format_object_id("gps_jamming_cell", gz.h3_index),
"spatial_co_location",
"derived_spatial",
f"邻近 GNSS 干扰网格 (<= {int(radius_km)} km)",
)
for ds in list((await db.execute(select(DisasterEvent).where(DisasterEvent.duplicate_of.is_(None)).limit(150))).scalars().all()):
if haversine_km(float(lat), float(lon), float(ds.lat), float(ds.lon)) <= radius_km:
await _attach(
format_object_id("disaster_event", ds.id),
"spatial_co_location",
"derived_spatial",
f"邻近自然灾害事件 (<= {int(radius_km)} km)",
)
for comp in list((await db.execute(select(ComputeCenterLocationRecord).limit(150))).scalars().all()):
if comp.latitude is not None and comp.longitude is not None:
if haversine_km(float(lat), float(lon), float(comp.latitude), float(comp.longitude)) <= radius_km:
await _attach(
format_object_id("compute_center", comp.id),
"spatial_co_location",
"derived_spatial",
f"邻近算力中心 (<= {int(radius_km)} km)",
)
for obj in list((await db.execute(select(EarthInteractable).where(EarthInteractable.is_deleted.is_(False)).limit(150))).scalars().all()):
if haversine_km(float(lat), float(lon), float(obj.latitude), float(obj.longitude)) <= radius_km:
await _attach(
format_object_id("interactable", obj.id),
"spatial_co_location",
"derived_spatial",
f"邻近地球标绘对象 (<= {int(radius_km)} km)",
)
if otype != "cable":
cable_rows = list(
(
await db.execute(
select(CollectedData)
.where(CollectedData.source == "arcgis_cables", CollectedData.is_current.is_(True))
.limit(300)
)
)
.scalars()
.all()
)
for c_row in cable_rows:
extra = c_row.extra_data or {}
clat, clon = _cable_centroid(extra)
if clat is not None and clon is not None and haversine_km(float(lat), float(lon), clat, clon) <= max(radius_km, 250.0):
cid = str(extra.get("cable_id") or c_row.source_id or c_row.name or "")
if cid:
await _attach(
format_object_id("cable", cid),
"near_submarine_cable",
"derived_spatial",
"邻近海底光缆路径(仅空间邻近线索)",
)
return list(neighbors.values()), edges
async def resolve_ontology_neighborhood(
db: Any,
object_id: str,
*,
depth: int = 1,
radius_km: float = 150.0,
limit: int = 40,
) -> dict[str, Any] | None:
"""Resolve 1-to-2 hop ontology neighborhood with explicit `relation_source` tags."""
root = await resolve_ontology_object(db, object_id)
if root is None:
return None
clamped_depth = max(1, min(int(depth or 1), 2))
nodes_map: dict[str, dict[str, Any]] = {root["object_id"]: root}
all_edges: list[dict[str, Any]] = []
seen_edge_keys: set[tuple[str, str, str, str]] = set()
frontier: list[dict[str, Any]] = [root]
visited: set[str] = {root["object_id"]}
for _hop in range(clamped_depth):
next_frontier: list[dict[str, Any]] = []
for current in frontier:
hop_nodes, hop_edges = await _derive_one_hop(
db, current, radius_km=radius_km, limit=limit
)
for node in hop_nodes:
nid = str(node["object_id"])
if nid not in nodes_map:
nodes_map[nid] = node
if nid not in visited:
visited.add(nid)
next_frontier.append(node)
for edge in hop_edges:
key = (
str(edge["from_object_id"]),
str(edge["to_object_id"]),
str(edge["relation_type"]),
str(edge["relation_source"]),
)
if key not in seen_edge_keys:
seen_edge_keys.add(key)
all_edges.append(edge)
frontier = next_frontier[:15]
if not frontier:
break
return {
"root": root,
"depth": clamped_depth,
"nodes": list(nodes_map.values()),
"edges": all_edges,
"relation_sources": sorted({e["relation_source"] for e in all_edges}),
}