199 lines
7.2 KiB
Python
199 lines
7.2 KiB
Python
"""Interpret the geographic grain of Epoch AI's official ``Location`` field."""
|
||
|
||
from __future__ import annotations
|
||
|
||
from dataclasses import dataclass
|
||
import math
|
||
import re
|
||
from typing import Any
|
||
|
||
from app.core.countries import normalize_country
|
||
|
||
|
||
_COUNTRY_LABEL_OVERRIDES = {
|
||
"korea republic of": "韩国",
|
||
}
|
||
_REGION_ONLY_LABELS = {
|
||
"europe",
|
||
"iowa",
|
||
"maryland",
|
||
"new mexico",
|
||
"texas",
|
||
"the nordics",
|
||
"virginia",
|
||
"washington",
|
||
}
|
||
_UNLOCATABLE_LABELS = {'"on prem" for tesla', "on prem for tesla"}
|
||
_HEMISPHERE_COORDINATE_PATTERN = re.compile(
|
||
r"(?P<degrees>\d{1,3})(?:[°º]|\s)\s*(?P<minutes>\d{1,2})(?:['′]|\s)"
|
||
r"(?P<seconds>\d{1,2}(?:\.\d+)?)?[\"″]?\s*(?P<hemisphere>[NSEW])",
|
||
re.IGNORECASE,
|
||
)
|
||
_LABELED_COORDINATE_PAIR_PATTERN = re.compile(
|
||
r"\b(?:lat|latitude)\b\s*[:=]?\s*(?P<latitude>-?\d{1,2}(?:\.\d+)?)"
|
||
r".{0,40}\b(?:lon|lng|longitude)\b\s*[:=]?\s*"
|
||
r"(?P<longitude>-?\d{1,3}(?:\.\d+)?)",
|
||
re.IGNORECASE | re.DOTALL,
|
||
)
|
||
_DECIMAL_COORDINATE_PAIR_PATTERN = re.compile(
|
||
r"^\s*[\[(]?\s*(-?\d{1,2}\.\d+)\s*[,;]\s*"
|
||
r"(-?\d{1,3}\.\d+)\s*[\])]?\s*$"
|
||
)
|
||
_NUMBERED_STREET_PATTERN = re.compile(
|
||
r"(?:\b(?:no\.?\s*)?\d+[a-z]?\s+(?:[\w.'’\-]+\s+){0,6}"
|
||
r"(?:road|rd|street|st|avenue|ave|boulevard|blvd|drive|dr|lane|ln|"
|
||
r"highway|hwy|way|parkway|pkwy|chome)\b|"
|
||
r"\b(?:via|rue|calle|plaça|strasse|straße)\b[^,\n]{0,80},?\s*\d)",
|
||
re.IGNORECASE,
|
||
)
|
||
_POSTAL_CODE_PATTERN = re.compile(
|
||
r"(?:\b\d{5}(?:-\d{4})?\b|\b\d{3}-\d{4}\b|"
|
||
r"\b[A-Z]{1,2}\d[A-Z\d]?\s*\d[A-Z]{2}\b)",
|
||
re.IGNORECASE,
|
||
)
|
||
_SITE_CONTEXT_PATTERN = re.compile(
|
||
r"\b(?:campus|building|cluster|data\s+cent(?:er|re)|facility|institute|"
|
||
r"laborator(?:y|ies)|science\s+park|supercomputing\s+cent(?:er|re))\b",
|
||
re.IGNORECASE,
|
||
)
|
||
_COORDINATE_CUE_PATTERN = re.compile(
|
||
r"(?:\b(?:lat|latitude|lon|lng|longitude)\b|[°º].*[NSEW])",
|
||
re.IGNORECASE | re.DOTALL,
|
||
)
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class EpochLocationAssessment:
|
||
precision: str
|
||
reason: str
|
||
|
||
@property
|
||
def is_renderable(self) -> bool:
|
||
return self.precision in {"precise", "site", "city"}
|
||
|
||
|
||
def _normalized_label(value: Any) -> str:
|
||
return re.sub(r"[^a-z0-9]+", " ", str(value or "").casefold()).strip()
|
||
|
||
|
||
def _country_from_label(value: Any) -> str | None:
|
||
return normalize_country(value) or _COUNTRY_LABEL_OVERRIDES.get(
|
||
_normalized_label(value)
|
||
)
|
||
|
||
|
||
def _coordinate(mapping: dict[str, Any], keys: tuple[str, ...], bound: float) -> float | None:
|
||
raw = next((mapping.get(key) for key in keys if mapping.get(key) not in (None, "")), None)
|
||
if isinstance(raw, bool):
|
||
return None
|
||
try:
|
||
number = float(raw)
|
||
except (TypeError, ValueError):
|
||
return None
|
||
return number if math.isfinite(number) and abs(number) <= bound else None
|
||
|
||
|
||
def _has_explicit_coordinate_pair(text: str) -> bool:
|
||
hemispheres = {}
|
||
for match in _HEMISPHERE_COORDINATE_PATTERN.finditer(text):
|
||
hemisphere = match.group("hemisphere").upper()
|
||
degrees = int(match.group("degrees"))
|
||
minutes = int(match.group("minutes"))
|
||
seconds = float(match.group("seconds") or 0)
|
||
bound = 90 if hemisphere in {"N", "S"} else 180
|
||
if degrees <= bound and minutes < 60 and seconds < 60:
|
||
hemispheres[hemisphere] = degrees
|
||
if ({"N", "S"} & hemispheres.keys()) and ({"E", "W"} & hemispheres.keys()):
|
||
return True
|
||
labeled_pair = _LABELED_COORDINATE_PAIR_PATTERN.search(text)
|
||
if labeled_pair:
|
||
latitude = float(labeled_pair.group("latitude"))
|
||
longitude = float(labeled_pair.group("longitude"))
|
||
return abs(latitude) <= 90 and abs(longitude) <= 180
|
||
decimal_pair = _DECIMAL_COORDINATE_PAIR_PATTERN.match(text)
|
||
if not decimal_pair:
|
||
return False
|
||
latitude, longitude = map(float, decimal_pair.groups())
|
||
return abs(latitude) <= 90 and abs(longitude) <= 180
|
||
|
||
|
||
def _has_address_evidence(text: str) -> bool:
|
||
if _NUMBERED_STREET_PATTERN.search(text):
|
||
return True
|
||
return bool(
|
||
_POSTAL_CODE_PATTERN.search(text)
|
||
and ("\n" in text or text.count(",") >= 2)
|
||
and _SITE_CONTEXT_PATTERN.search(text)
|
||
)
|
||
|
||
|
||
def assess_epoch_location(
|
||
location: Any,
|
||
*,
|
||
country: Any = None,
|
||
raw_country: Any = None,
|
||
) -> EpochLocationAssessment:
|
||
"""Classify source coordinates without upgrading their source text.
|
||
|
||
Epoch's CSV supplies coordinates even when ``Location`` contains only a
|
||
country. Those coordinates are useful source evidence, but are not a
|
||
facility point and must not enter the renderable location pipeline.
|
||
"""
|
||
if isinstance(location, dict):
|
||
latitude = _coordinate(location, ("lat", "latitude"), 90)
|
||
longitude = _coordinate(location, ("lon", "lng", "longitude"), 180)
|
||
has_coordinates = latitude is not None and longitude is not None
|
||
return EpochLocationAssessment(
|
||
"precise" if has_coordinates else "unknown",
|
||
"complete explicit coordinate object"
|
||
if has_coordinates
|
||
else "coordinate object lacks a complete valid latitude/longitude pair",
|
||
)
|
||
|
||
text = str(location or "").strip()
|
||
if not text:
|
||
return EpochLocationAssessment("unknown", "Epoch Location is empty")
|
||
|
||
normalized = _normalized_label(text)
|
||
normalized_country = normalize_country(country)
|
||
source_country = normalize_country(raw_country)
|
||
location_country = _country_from_label(text)
|
||
if location_country or (
|
||
raw_country and normalized == _normalized_label(raw_country)
|
||
):
|
||
matched = location_country or source_country or normalized_country
|
||
return EpochLocationAssessment(
|
||
"country",
|
||
f"Epoch Location identifies country only: {matched or text}",
|
||
)
|
||
if normalized in _REGION_ONLY_LABELS:
|
||
return EpochLocationAssessment(
|
||
"region", f"Epoch Location identifies region/state only: {text}"
|
||
)
|
||
comma_parts = [part.strip() for part in text.split(",") if part.strip()]
|
||
if (
|
||
len(comma_parts) == 2
|
||
and _normalized_label(comma_parts[0]) in _REGION_ONLY_LABELS
|
||
and _country_from_label(comma_parts[1])
|
||
):
|
||
return EpochLocationAssessment(
|
||
"region", f"Epoch Location identifies region/state only: {text}"
|
||
)
|
||
if normalized in _UNLOCATABLE_LABELS:
|
||
return EpochLocationAssessment("unknown", "Epoch Location has no geographic place")
|
||
if normalized.isdigit():
|
||
return EpochLocationAssessment("unknown", "Epoch Location is only a numeric label")
|
||
if _has_explicit_coordinate_pair(text):
|
||
return EpochLocationAssessment(
|
||
"precise", "Epoch Location contains a complete valid coordinate pair"
|
||
)
|
||
if _COORDINATE_CUE_PATTERN.search(text):
|
||
return EpochLocationAssessment(
|
||
"unknown", "Epoch Location contains an incomplete or invalid coordinate pair"
|
||
)
|
||
if _has_address_evidence(text):
|
||
return EpochLocationAssessment("precise", "Epoch Location contains an address")
|
||
if "\n" in text or _SITE_CONTEXT_PATTERN.search(text):
|
||
return EpochLocationAssessment("site", "Epoch Location names a facility or campus")
|
||
return EpochLocationAssessment("city", "Epoch Location identifies a locality")
|