Files
planet/backend/app/services/ai/semantic_delta.py
T

264 lines
9.7 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.
"""Deterministic snapshot semantic delta engine (F-16) and candidate evidence extractor (F-23)."""
from __future__ import annotations
from datetime import UTC, datetime
import hashlib
import json
import re
from typing import Any, Literal
SemanticDeltaVerdict = Literal[
"new_change",
"ongoing_impact",
"recovery_progress",
"stable",
"indeterminate",
]
def _parse_iso(ts: str | datetime | None) -> datetime | None:
if isinstance(ts, datetime):
return ts if ts.tzinfo else ts.replace(tzinfo=UTC)
if not ts or not isinstance(ts, str):
return None
try:
normalized = ts.replace("Z", "+00:00")
parsed = datetime.fromisoformat(normalized)
return parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)
except ValueError:
return None
def snapshot_fingerprint(snapshot: dict[str, Any]) -> str:
canonical: dict[str, Any] = {
"active_keys": sorted(str(item) for item in (snapshot.get("active_keys") or [])),
"metrics": snapshot.get("metrics") or {},
"status": snapshot.get("status"),
}
digests = snapshot.get("incident_digests")
if digests:
canonical["incident_digests"] = digests
return hashlib.sha256(json.dumps(canonical, sort_keys=True).encode("utf-8")).hexdigest()
def classify_snapshot_delta(
previous_snapshot: dict[str, Any] | None,
current_snapshot: dict[str, Any] | None,
*,
now: datetime | None = None,
stale_after_seconds: int = 7200,
min_coverage_ratio: float = 0.6,
ignore_coverage_drop: bool = False,
seen_fingerprints: set[str] | None = None,
) -> dict[str, Any]:
"""Compare `current_snapshot` against `previous_snapshot` without mistaking source failures for stability."""
reference_now = now or datetime.now(UTC)
if not current_snapshot or current_snapshot.get("status") != "success":
reason = (current_snapshot or {}).get("error") or "source_fetch_failed_or_missing"
return {
"verdict": "indeterminate",
"preserve_previous_snapshot": True,
"emit_event": False,
"reason": str(reason),
"added_keys": [],
"updated_keys": [],
"resolved_keys": [],
"continuing_keys": [],
}
completed_at = _parse_iso(current_snapshot.get("completed_at"))
if completed_at and (reference_now - completed_at).total_seconds() > stale_after_seconds:
return {
"verdict": "indeterminate",
"preserve_previous_snapshot": True,
"emit_event": False,
"reason": "snapshot_expired_beyond_freshness_window",
"added_keys": [],
"updated_keys": [],
"resolved_keys": [],
"continuing_keys": [],
}
prev_count = int((previous_snapshot or {}).get("record_count") or 0)
curr_count = int(current_snapshot.get("record_count") or 0)
if not ignore_coverage_drop and prev_count >= 10 and curr_count < prev_count * min_coverage_ratio:
return {
"verdict": "indeterminate",
"preserve_previous_snapshot": True,
"emit_event": False,
"reason": "insufficient_source_coverage_drop",
"added_keys": [],
"updated_keys": [],
"resolved_keys": [],
"continuing_keys": [],
}
curr_fp = current_snapshot.get("fingerprint") or snapshot_fingerprint(current_snapshot)
curr_active = {str(k) for k in (current_snapshot.get("active_keys") or [])}
prev_active = {str(k) for k in ((previous_snapshot or {}).get("active_keys") or [])}
if seen_fingerprints is not None and curr_fp in seen_fingerprints:
verdict: SemanticDeltaVerdict = "ongoing_impact" if curr_active else "stable"
return {
"verdict": verdict,
"preserve_previous_snapshot": False,
"emit_event": False,
"is_duplicate_retry": True,
"fingerprint": curr_fp,
"reason": "duplicate_snapshot_fingerprint_suppressed",
"added_keys": [],
"updated_keys": [],
"resolved_keys": [],
"continuing_keys": sorted(curr_active),
}
if seen_fingerprints is not None:
seen_fingerprints.add(curr_fp)
added = sorted(curr_active - prev_active)
resolved = sorted(prev_active - curr_active)
continuing = sorted(curr_active & prev_active)
prev_digests = (previous_snapshot or {}).get("incident_digests") or {}
curr_digests = current_snapshot.get("incident_digests") or {}
updated = sorted(
key
for key in continuing
if key in prev_digests and key in curr_digests and prev_digests[key] != curr_digests[key]
)
metric_shifts: dict[str, float] = {}
prev_metrics = (previous_snapshot or {}).get("metrics") or {}
curr_metrics = current_snapshot.get("metrics") or {}
for key, curr_val in curr_metrics.items():
prev_val = prev_metrics.get(key)
if isinstance(curr_val, (int, float)) and isinstance(prev_val, (int, float)):
diff = round(float(curr_val) - float(prev_val), 2)
if abs(diff) >= 2.0:
metric_shifts[str(key)] = diff
if added or updated or metric_shifts:
verdict = "new_change"
emit_event = True
reason = "new_anomalies_or_material_metric_shift"
elif resolved:
verdict = "recovery_progress"
emit_event = True
reason = "previously_active_impacts_resolved"
elif continuing:
verdict = "ongoing_impact"
emit_event = False
reason = "active_impacts_persisting"
else:
verdict = "stable"
emit_event = False
reason = "verified_healthy_snapshot_with_no_active_anomalies"
return {
"verdict": verdict,
"preserve_previous_snapshot": False,
"emit_event": emit_event,
"is_duplicate_retry": False,
"fingerprint": curr_fp,
"reason": reason,
"added_keys": added,
"updated_keys": updated,
"resolved_keys": resolved,
"continuing_keys": continuing,
"metric_shifts": metric_shifts,
}
_SHARE_PATTERN = re.compile(
r"(?P<country>美国|中国|日本)\s*(?:全球)?(?P<metric>智能算力|总算力|算力)份额[^\d]{0,10}(?P<value>\d{1,2}(?:\.\d+)?)\s*%"
)
_CHIP_INFLOW_ZH_PATTERN = re.compile(
r"(?P<country>美国|中国|日本)\s*(?:高端)?(?:AI)?(?:算力)?芯片(?:新增)?流向(?:算力)?份额[^\d]{0,12}(?P<value>\d{1,2}(?:\.\d+)?)\s*%"
)
_CHIP_INFLOW_CONTEXT_RE = re.compile(
r"\b(?:h100e?|h20|ai\s+chip|chip\s+import|chip\s+inflow|world\s+arrivals|cumulative\s+world\s+arrivals)\b",
re.IGNORECASE,
)
_CHIP_INFLOW_EN_TO_PATTERN = re.compile(
r"\b(?P<country>United States|U\.S\.|US|China|Japan)(?:['’]s|['’])?\s+share\b[^,;]{0,90}?\bto\s+(?P<value>\d{1,2}(?:\.\d+)?)\s*%",
re.IGNORECASE,
)
_CHIP_INFLOW_EN_RECEIVED_PATTERN = re.compile(
r"\b(?P<country>United States|U\.S\.|US|China|Japan)\s+(?:received|accounted for|captured)\s+(?:about\s+|approximately\s+|roughly\s+)?(?P<value>\d{1,2}(?:\.\d+)?)\s*%\s+of\s+(?:that\s+|global\s+|world\s+)?(?:compute|arrivals|inflow)",
re.IGNORECASE,
)
_COUNTRY_MAP = {
"美国": "US",
"中国": "CN",
"日本": "JP",
"united states": "US",
"u.s.": "US",
"us": "US",
"china": "CN",
"japan": "JP",
}
def extract_compute_candidates_deterministic(
excerpt: str,
*,
year: int,
source_meta: dict[str, Any],
period_label: str | None = None,
) -> list[dict[str, Any]]:
"""Deterministic extractor fallback producing reviewable `ComputeEvidenceCandidate` dicts."""
text = excerpt or ""
by_metric: dict[str, dict[str, float]] = {}
for match in _SHARE_PATTERN.finditer(text):
code = _COUNTRY_MAP.get(match.group("country"))
if not code:
continue
metric_key = "intelligent_share" if "智能" in match.group("metric") else "global_share"
value = float(match.group("value"))
if 0 <= value <= 100:
by_metric.setdefault(metric_key, {})[code] = value
for match in _CHIP_INFLOW_ZH_PATTERN.finditer(text):
code = _COUNTRY_MAP.get(match.group("country"))
if not code:
continue
value = float(match.group("value"))
if 0 <= value <= 100:
by_metric.setdefault("chip_inflow_share", {})[code] = value
if _CHIP_INFLOW_CONTEXT_RE.search(text):
for pattern in (_CHIP_INFLOW_EN_TO_PATTERN, _CHIP_INFLOW_EN_RECEIVED_PATTERN):
for match in pattern.finditer(text):
code = _COUNTRY_MAP.get(match.group("country").lower())
if not code:
continue
value = float(match.group("value"))
if 0 <= value <= 100 and code not in by_metric.get("chip_inflow_share", {}):
by_metric.setdefault("chip_inflow_share", {})[code] = value
clean_period = (period_label or "").strip() or None
candidates: list[dict[str, Any]] = []
for metric_key, values in by_metric.items():
if sum(values.values()) > 100.0:
continue
proposed: dict[str, Any] = {
"year": year,
"metric": metric_key,
"source_id": source_meta.get("id") or f"candidate-src-{year}",
"values": values,
}
if clean_period is not None:
proposed["period_label"] = clean_period
candidates.append(
{
"candidate_type": "observation",
"proposed_payload": proposed,
"source_payload": source_meta,
"confidence": 0.86,
"extractor_note": f"从报告摘录自动提取 {year} 年 {metric_key} 候选值,待管理员人工核验后入库。",
}
)
return candidates