Files
planet/backend/app/services/location/resolvers/wikidata.py
T
linkong e1cc27f13d
ci / backend (push) Canceled after 0s
ci / frontend (push) Canceled after 0s
ci / delivery (push) Canceled after 0s
release: bump version to 0.84.0
2026-12-04 07:07:19 +08:00

196 lines
8.7 KiB
Python

"""Wikidata structured entity lookup for compute-center / facility coordinates (P625 / P276)."""
from __future__ import annotations
import httpx
from ..models import LocationCandidate, LocationQuery, ResolverOutput
from ..text import coerce_str, normalize_country_text, normalize_text, parse_float
WIKIDATA_API_URL = "https://www.wikidata.org/w/api.php"
WIKIDATA_USER_AGENT = "planet-earth-location-resolver/1.0"
WIKIDATA_TIMEOUT_SECONDS = 6.0
async def lookup_wikidata_facility(
query: LocationQuery,
*,
timeout_seconds: float = WIKIDATA_TIMEOUT_SECONDS,
) -> ResolverOutput:
"""Query Wikidata entities for facility-level P625 coordinate claims."""
extra = query.extra or {}
terms: list[str] = []
for raw in [
*(query.aliases or ()),
query.name,
extra.get("site"),
]:
cleaned = coerce_str(raw)
if cleaned and cleaned not in terms:
terms.append(cleaned)
if not terms:
return ResolverOutput()
attempted: list[str] = []
candidates: list[LocationCandidate] = []
seen_qids: set[str] = set()
headers = {"User-Agent": WIKIDATA_USER_AGENT, "Accept": "application/json"}
async with httpx.AsyncClient(timeout=timeout_seconds, headers=headers) as client:
for term in terms[:2]:
attempted.append(f"wikidata:{term}")
try:
search_resp = await client.get(
WIKIDATA_API_URL,
params={
"action": "wbsearchentities",
"search": term,
"language": "en",
"format": "json",
"limit": 4,
},
)
search_resp.raise_for_status()
search_items = (search_resp.json() or {}).get("search") or []
except Exception:
continue
qids = [
str(item.get("id"))
for item in search_items
if isinstance(item, dict) and item.get("id") and item.get("id") not in seen_qids
]
if not qids:
continue
seen_qids.update(qids)
try:
ent_resp = await client.get(
WIKIDATA_API_URL,
params={
"action": "wbgetentities",
"ids": "|".join(qids[:4]),
"props": "labels|descriptions|claims",
"languages": "en|zh",
"format": "json",
},
)
ent_resp.raise_for_status()
entities = (ent_resp.json() or {}).get("entities") or {}
except Exception:
continue
term_tokens = set(normalize_text(term).split())
expected_country = normalize_text(normalize_country_text(query.country))
country_qids: set[str] = set()
if expected_country:
for entity in entities.values():
if not isinstance(entity, dict):
continue
for p17 in (entity.get("claims") or {}).get("P17") or []:
dataval = (((p17.get("mainsnak") or {}).get("datavalue") or {}).get("value") if isinstance(p17, dict) else None)
if isinstance(dataval, dict) and dataval.get("id"):
country_qids.add(str(dataval["id"]))
country_labels: dict[str, list[str]] = {}
if country_qids:
try:
c_resp = await client.get(
WIKIDATA_API_URL,
params={
"action": "wbgetentities",
"ids": "|".join(sorted(country_qids)[:12]),
"props": "labels",
"languages": "en|zh",
"format": "json",
},
)
c_resp.raise_for_status()
for c_qid, c_ent in ((c_resp.json() or {}).get("entities") or {}).items():
if not isinstance(c_ent, dict):
continue
c_labels = c_ent.get("labels") or {}
vals = [
coerce_str((c_labels.get(lang) or {}).get("value"))
for lang in ("en", "zh")
if coerce_str((c_labels.get(lang) or {}).get("value"))
]
if vals:
country_labels[c_qid] = vals
except Exception:
country_labels = {}
for qid, entity in entities.items():
if not isinstance(entity, dict):
continue
labels = entity.get("labels") or {}
label = coerce_str((labels.get("en") or {}).get("value") or (labels.get("zh") or {}).get("value"))
desc = coerce_str(((entity.get("descriptions") or {}).get("en") or {}).get("value")).lower()
if label:
label_tokens = set(normalize_text(label).split())
if term_tokens and not (term_tokens & label_tokens):
continue
if desc and not any(
kw in desc
for kw in ("supercomputer", "data center", "datacenter", "computer", "cluster", "laboratory", "facility", "campus")
):
continue
claims = entity.get("claims") or {}
resolved_p17_countries: list[str] = []
for p17 in claims.get("P17") or []:
dataval = (((p17.get("mainsnak") or {}).get("datavalue") or {}).get("value") if isinstance(p17, dict) else None)
c_qid = str(dataval.get("id") or "") if isinstance(dataval, dict) else ""
for raw_label in country_labels.get(c_qid, []):
norm_c = normalize_country_text(raw_label) or raw_label
if norm_c and norm_c not in resolved_p17_countries:
resolved_p17_countries.append(norm_c)
if expected_country and resolved_p17_countries:
if not any(normalize_text(c) == expected_country for c in resolved_p17_countries):
continue
coord_claims = claims.get("P625") or []
for claim in coord_claims:
mainsnak = claim.get("mainsnak") if isinstance(claim, dict) else None
datavalue = (mainsnak or {}).get("datavalue") or {}
val = datavalue.get("value") if isinstance(datavalue, dict) else None
if not isinstance(val, dict):
continue
lat = parse_float(val.get("latitude"))
lon = parse_float(val.get("longitude"))
if (
lat in (None, 0.0)
or lon in (None, 0.0)
or not (-90.0 <= lat <= 90.0)
or not (-180.0 <= lon <= 180.0)
):
continue
country = (
resolved_p17_countries[0]
if resolved_p17_countries
else normalize_country_text(query.country)
)
candidates.append(
LocationCandidate(
latitude=lat,
longitude=lon,
display_name=label or term,
precision="site",
confidence=0.84,
query=f"wikidata:{term}",
source="wikidata_facility",
source_note=f"Wikidata entity {qid} P625 coordinates ({desc or label})",
matched_fields=("name", "wikidata"),
needs_confirmation=True,
city=query.city or None,
country=country or query.country,
matched_location_name=label or term,
raw_payload={
"wikidata_qid": qid,
"description": desc,
**({"wikidata_country": resolved_p17_countries[0]} if resolved_p17_countries else {}),
},
)
)
break
return ResolverOutput(candidates=tuple(candidates), attempted_queries=tuple(attempted))