Spaces:
Sleeping
Sleeping
File size: 11,867 Bytes
f927995 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 | """
Endpoints for sector listing and live supply shock events.
Powers the ShockMap sector selector and live feed on the landing page.
"""
import json
import logging
from datetime import datetime
from pathlib import Path
from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel, Field
from ..deps import get_demo_mode_service, get_war_room_service
from ..config import settings
logger = logging.getLogger("backend.sectors")
router = APIRouter(prefix="/api/v1", tags=["sectors", "shocks"])
BASE_DIR = Path(__file__).parent.parent.parent.parent # project root
SHOCKS_FILE = BASE_DIR / "data" / "shocks.json"
LEGACY_SHOCKS_FILE = BASE_DIR / "data" / "seed" / "live_shocks.json"
RARE_EARTHS_FILE = BASE_DIR / "data" / "seed" / "rare_earths.json"
DRUGS_FILE = BASE_DIR / "data" / "seed" / "drugs.json"
# ---------------------------------------------------------------------------
# Pydantic models
# ---------------------------------------------------------------------------
class SectorInfo(BaseModel):
id: str
name: str
icon: str
status: str # "active" | "phase2"
input_count: int
description: str
active_shocks: int
criticality_avg: float
class LiveShock(BaseModel):
id: str
sector: str
title: str
summary: str
province: Optional[str] = None
event_type: Optional[str] = None
severity: str
source: str
source_url: Optional[str] = None
published_at: Optional[str] = None
detected_at: str
gdelt_sources: int = 1
data_mode: str = "live"
affected_entities: List[str] = Field(default_factory=list)
class ActionSimulationRequest(BaseModel):
action_id: str
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _load_json(path: Path) -> list:
if not path.exists():
return []
try:
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
except Exception as e:
logger.warning(f"Failed to load {path}: {e}")
return []
def _get_live_shocks(demo_service=None) -> list[dict]:
shocks = _load_json(SHOCKS_FILE)
legacy = _load_json(LEGACY_SHOCKS_FILE)
current: list[dict] = []
seen_ids: set[str] = set()
for source in (shocks, legacy):
for item in source:
item_id = str(item.get("id", "")).strip()
if item_id and item_id in seen_ids:
continue
if item_id:
seen_ids.add(item_id)
current.append(item)
if settings.DEMO_MODE and demo_service is not None and demo_service.count() > 0:
merged = list(current)
for item in demo_service.list_shocks():
item_id = str(item.get("id", "")).strip()
if item_id and item_id in seen_ids:
continue
if item_id:
seen_ids.add(item_id)
merged.append(item)
return merged
return current
def _parse_dt(value: Optional[str]) -> datetime:
if not value:
return datetime.min
try:
return datetime.fromisoformat(value.replace("Z", "+00:00"))
except Exception:
return datetime.min
# ---------------------------------------------------------------------------
# Routes
# ---------------------------------------------------------------------------
@router.get("/sectors", response_model=List[SectorInfo])
async def get_sectors(demo_service=Depends(get_demo_mode_service)) -> List[SectorInfo]:
"""
Returns the list of all sectors with status (active/phase2),
input counts, average criticality, and active shock counts.
"""
shocks = _get_live_shocks(demo_service)
shock_by_sector: dict[str, int] = {}
for s in shocks:
sec = s.get("sector", "pharma")
shock_by_sector[sec] = shock_by_sector.get(sec, 0) + 1
# Pharma
drugs = _load_json(DRUGS_FILE)
pharma_crit = sum((d.get("criticality_score") or 0.5) for d in drugs) / max(len(drugs), 1)
# Rare Earths
rare_earths = _load_json(RARE_EARTHS_FILE)
re_crit = sum((r.get("criticality") or 0.5) for r in rare_earths) / max(len(rare_earths), 1)
return [
SectorInfo(
id="pharma",
name="Pharma",
icon="π",
status="active",
input_count=len(drugs),
description="API & essential medicines β India imports ~70% from China",
active_shocks=shock_by_sector.get("pharma", 0),
criticality_avg=round(pharma_crit, 2),
),
SectorInfo(
id="rare_earth",
name="Rare Earths",
icon="βοΈ",
status="active",
input_count=len(rare_earths),
description="Critical minerals for EV, defence & electronics β 94% China controlled",
active_shocks=shock_by_sector.get("rare_earth", 0),
criticality_avg=round(re_crit, 2),
),
SectorInfo(
id="semiconductor",
name="Semiconductor",
icon="π»",
status="phase2",
input_count=0,
description="Chip substrates, fab chemicals β coming Phase 2",
active_shocks=0,
criticality_avg=0.0,
),
SectorInfo(
id="solar",
name="Solar Energy",
icon="βοΈ",
status="phase2",
input_count=0,
description="Polysilicon, solar wafers β coming Phase 2",
active_shocks=0,
criticality_avg=0.0,
),
SectorInfo(
id="ev_battery",
name="EV Battery",
icon="π",
status="phase2",
input_count=0,
description="Lithium, cobalt, battery cathode β coming Phase 2",
active_shocks=0,
criticality_avg=0.0,
),
SectorInfo(
id="defence",
name="Defence Inputs",
icon="π‘οΈ",
status="phase2",
input_count=0,
description="Titanium, tungsten, specialty alloys β coming Phase 2",
active_shocks=0,
criticality_avg=0.0,
),
]
@router.get("/shocks", response_model=List[LiveShock])
async def get_live_shocks(
sector: Optional[str] = Query(default=None),
severity: Optional[str] = Query(default=None),
limit: int = Query(default=20, le=50),
demo_service=Depends(get_demo_mode_service),
) -> List[LiveShock]:
"""
Returns the latest live shock events detected by the GDELT pipeline.
Optionally filter by sector or severity.
Updated every 15 minutes by the ingestion/shock_detector.py cron.
"""
shocks = _get_live_shocks(demo_service)
if sector:
shocks = [s for s in shocks if s.get("sector") == sector]
if severity:
shocks = [s for s in shocks if s.get("severity") == severity.upper()]
# Sort: severity first, then by detected_at/published_at descending.
sev_order = {"CRITICAL": 0, "HIGH": 1, "MEDIUM": 2, "LOW": 3}
shocks.sort(
key=lambda s: (
sev_order.get(s.get("severity", "LOW"), 4),
-_parse_dt(s.get("detected_at") or s.get("published_at")).timestamp()
if _parse_dt(s.get("detected_at") or s.get("published_at")) != datetime.min
else float("inf"),
)
)
shocks = shocks[:limit]
return [
LiveShock(
id=s.get("id", ""),
sector=s.get("sector", "pharma"),
title=s.get("title", ""),
summary=s.get("summary", s.get("title", "")),
province=s.get("province"),
event_type=s.get("event_type"),
severity=s.get("severity", "LOW"),
source=s.get("source", "GDELT"),
source_url=None if s.get("data_mode") == "demo" else s.get("source_url"),
published_at=s.get("published_at"),
detected_at=s.get("detected_at", datetime.utcnow().isoformat()),
gdelt_sources=s.get("gdelt_sources", 1),
data_mode=s.get("data_mode", "live"),
affected_entities=s.get("affected_entities", []),
)
for s in shocks
]
@router.get("/shocks/{shock_id}")
async def get_shock_detail(
shock_id: str,
demo_service=Depends(get_demo_mode_service),
) -> dict:
"""
Returns a single shock event by ID with full Engine 1/2/3 context:
- NER-extracted entities (Engine 1)
- PageRank propagation trace (Engine 2)
- Community cluster info (Engine 2)
- Affected inputs with risk scores
"""
shocks = _get_live_shocks(demo_service)
shock = next((s for s in shocks if s.get("id") == shock_id), None)
if not shock:
raise HTTPException(status_code=404, detail=f"Shock '{shock_id}' not found")
# Enrich with Engine 2 data if province is known
province = shock.get("province")
if province:
try:
from ..deps import get_graph_service, get_shock_propagator
graph_service = get_graph_service()
propagator = get_shock_propagator()
# PageRank propagation
combined_risks = graph_service.compute_combined_risk(
province, shock.get("sector", "pharma")
)
shock["propagation"] = {
"method": "personalized_pagerank",
"formula": "R_i = PR_i(shock) * (1 - S_i) * exp(-B_i / tau) * C_community",
"affected_nodes": dict(list(combined_risks.items())[:10]),
"total_affected": len(combined_risks),
}
# Community info
community_id = graph_service.get_node_community(province)
if community_id is not None:
communities = graph_service.get_communities()
for c in communities.get("communities", []):
if c["id"] == community_id:
shock["community"] = {
"id": community_id,
"label": c["label"],
"size": c["size"],
"provinces": c["provinces"],
"co_affected_inputs": c["inputs"][:5],
}
break
# Affected drugs list
affected = graph_service.get_drugs_dependent_on_province(province)
shock["affected_drugs"] = affected
except Exception as e:
logger.warning(f"Engine 2 enrichment failed for shock {shock_id}: {e}")
return shock
@router.get("/shocks/{shock_id}/war-room")
async def get_shock_war_room(
shock_id: str,
demo_service=Depends(get_demo_mode_service),
war_room_service=Depends(get_war_room_service),
) -> dict:
shocks = _get_live_shocks(demo_service)
shock = next((s for s in shocks if s.get("id") == shock_id), None)
if not shock:
raise HTTPException(status_code=404, detail=f"Shock '{shock_id}' not found")
return war_room_service.build(shock)
@router.post("/shocks/{shock_id}/simulate-action")
async def simulate_shock_action(
shock_id: str,
request: ActionSimulationRequest,
demo_service=Depends(get_demo_mode_service),
war_room_service=Depends(get_war_room_service),
) -> dict:
shocks = _get_live_shocks(demo_service)
shock = next((s for s in shocks if s.get("id") == shock_id), None)
if not shock:
raise HTTPException(status_code=404, detail=f"Shock '{shock_id}' not found")
try:
return war_room_service.simulate_action(shock, request.action_id)
except KeyError:
raise HTTPException(status_code=404, detail=f"Action '{request.action_id}' not found for shock '{shock_id}'")
|