-
Notifications
You must be signed in to change notification settings - Fork 217
Expand file tree
/
Copy pathmain.py
More file actions
1422 lines (1230 loc) · 49.6 KB
/
Copy pathmain.py
File metadata and controls
1422 lines (1230 loc) · 49.6 KB
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
ClimateVision API
FastAPI-based REST API for climate monitoring including:
- Deforestation detection
- Arctic ice melting analysis
- Flood detection
- Organization (NGO) management
- Alert and subscription systems
"""
from __future__ import annotations
import json
import logging
import os
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Optional, Literal
from contextlib import asynccontextmanager
from pydantic import field_validator
from fastapi import FastAPI, File, Form, HTTPException, UploadFile, Header, Query, Depends, Request
from fastapi.responses import FileResponse, RedirectResponse
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import Response
from pydantic import BaseModel, Field, EmailStr, model_validator
from climatevision.db import (
get_connection,
init_db,
create_organization,
get_organization,
get_organization_by_api_key,
list_organizations,
create_subscription,
get_subscriptions_for_organization,
create_organization_alert,
get_alerts_for_organization,
get_pending_alerts,
acknowledge_alert,
mark_alert_delivered,
)
from climatevision.inference import run_inference_from_file, run_inference_from_gee
from climatevision.inference.flood_pipeline import run_flood_inference_from_gee
from climatevision.api.auth import require_api_key
from climatevision.governance import explain_prediction, SHAPExplainer
from climatevision.security.api_security import SecurityMiddleware
from climatevision.workers.alert_delivery import AlertDeliveryWorker
logger = logging.getLogger(__name__)
# ===== Type Definitions =====
AnalysisType = Literal["deforestation", "ice_melting", "flooding", "flooding_sar", "drought", "wildfire"]
OrganizationType = Literal["ngo", "government", "research", "corporate"]
NotificationChannel = Literal["email", "webhook", "api", "sms"]
AlertSeverity = Literal["low", "medium", "high", "critical"]
SUPPORTED_ANALYSIS_TYPES: list[dict[str, Any]] = [
{
"name": "deforestation",
"display_name": "Deforestation Detection",
"description": "Monitor forest coverage and detect deforestation events",
"enabled": True,
"bands": ["B04", "B03", "B02", "B08"],
"classes": ["non_forest", "forest"],
},
{
"name": "ice_melting",
"display_name": "Arctic Ice Melting",
"description": "Monitor sea ice extent and melting patterns in polar regions",
"enabled": True,
"bands": ["B02", "B03", "B04", "B11"],
"classes": ["sea_ice", "open_water", "land"],
},
{
"name": "flooding",
"display_name": "Flood Detection",
"description": "Detect and monitor flooding events and affected areas",
"enabled": True,
"bands": ["B03", "B08", "B11"],
"classes": ["water", "flooded", "dry_land"],
},
{
"name": "flooding_sar",
"display_name": "Flood Detection (SAR)",
"description": "All-weather flood detection from Sentinel-1 VV/VH using a physics-based ensemble",
"enabled": True,
"bands": ["VV", "VH"],
"classes": ["dry_land", "permanent_water", "flooded"],
},
{
"name": "drought",
"display_name": "Drought Monitoring",
"description": "Monitor vegetation stress and drought conditions",
"enabled": False,
"bands": ["B04", "B08", "B11", "B12"],
"classes": ["normal", "stressed", "severe_drought"],
},
{
"name": "wildfire",
"display_name": "Wildfire Detection",
"description": "Detect active fires and burned areas",
"enabled": False,
"bands": ["B04", "B08", "B11", "B12"],
"classes": ["unburned", "burned", "active_fire"],
},
]
def _utc_now_iso() -> str:
return datetime.now(timezone.utc).isoformat()
# ===== Request/Response Models =====
class PredictRequest(BaseModel):
kind: str = Field(default="demo")
analysis_type: AnalysisType = Field(default="deforestation")
bbox: Optional[list[float]] = None
start_date: Optional[str] = Field(
default=None,
description="Start date in YYYY-MM-DD format. Must be earlier than end_date.",
)
end_date: Optional[str] = Field(
default=None,
description="End date in YYYY-MM-DD format. Must be later than start_date.",
)
enable_carbon: bool = Field(
default=False,
description="If true, include carbon loss estimates for deforestation runs.",
)
forest_type: Optional[str] = Field(
default=None,
description="Forest type for carbon estimation (e.g. tropical_moist, mangrove).",
)
region: Optional[str] = Field(
default=None,
description="Region for carbon estimation adjustment (e.g. amazon, congo).",
)
@field_validator("bbox")
@classmethod
def validate_bbox(cls, v: Optional[list[float]]) -> Optional[list[float]]:
if v is None:
return v
if len(v) != 4:
raise ValueError("bbox must have exactly 4 values: [west, south, east, north]")
west, south, east, north = v
if not (-180 <= west <= 180 and -180 <= east <= 180):
raise ValueError("bbox longitude values must be between -180 and 180")
if not (-90 <= south <= 90 and -90 <= north <= 90):
raise ValueError("bbox latitude values must be between -90 and 90")
if west >= east:
raise ValueError("bbox west longitude must be less than east longitude")
if south >= north:
raise ValueError("bbox south latitude must be less than north latitude")
return v
@model_validator(mode="after")
def validate_date_range(self) -> "PredictRequest":
if self.start_date and self.end_date:
try:
start = datetime.strptime(self.start_date, "%Y-%m-%d")
end = datetime.strptime(self.end_date, "%Y-%m-%d")
except ValueError:
raise ValueError("start_date and end_date must be in YYYY-MM-DD format")
if start >= end:
raise ValueError("start_date must be earlier than end_date")
return self
class RunRow(BaseModel):
id: int
kind: str
status: str
analysis_type: str = "deforestation"
bbox: Optional[str] = None
start_date: Optional[str] = None
end_date: Optional[str] = None
created_at: str
updated_at: str
class ResultRow(BaseModel):
id: int
run_id: int
payload: dict[str, Any]
mask_path: Optional[str] = None
created_at: str
# ===== Carbon analytics helpers =====
def _extract_deforested_pixels(payload: dict[str, Any]) -> Optional[int]:
"""Pull the deforested-pixel count from a deforestation result payload.
Returns None when the payload does not carry an inference pixel count.
"""
inference = payload.get("inference")
if not isinstance(inference, dict):
return None
pixels = inference.get("non_forest_pixels")
if pixels is None:
return None
try:
return int(pixels)
except (TypeError, ValueError):
return None
def _compute_carbon_estimation(
payload: dict[str, Any],
forest_type: Optional[str] = None,
region: Optional[str] = None,
) -> Optional[dict[str, float]]:
"""Deterministic carbon loss estimate for embedding in a predict response.
Returns None if the carbon module is unavailable or the payload lacks a
pixel count, so the caller can degrade gracefully.
"""
pixels = _extract_deforested_pixels(payload)
if pixels is None:
return None
try:
from climatevision.analytics.carbon import estimate_carbon_loss
estimate = estimate_carbon_loss(
deforested_pixels=pixels,
forest_type=forest_type or "tropical_moist",
region=region or "default",
)
except Exception:
logger.exception("Carbon estimation failed")
return None
return {
"carbon_tonnes": estimate["carbon_tonnes"],
"hectares_lost": estimate["hectares"],
"co2_equivalent": estimate["co2_equivalent"],
"forest_type": forest_type or "tropical_moist",
"region": region or "default",
}
def _validate_forest_type(forest_type: Optional[str]) -> None:
"""Reject an unknown forest_type instead of silently defaulting.
A typo such as ``tropical-moist`` (hyphen) would otherwise fall through
to a generic biomass density and return plausible-looking but wrong
numbers with a 200 OK.
"""
if forest_type is None:
return
from climatevision.analytics.carbon import AGB_DENSITY
if forest_type not in AGB_DENSITY:
raise HTTPException(
status_code=422,
detail=(
f"Unknown forest_type '{forest_type}'. "
f"Valid values: {sorted(AGB_DENSITY)}"
),
)
def _validate_region(region: Optional[str]) -> None:
"""Reject an unknown region instead of silently applying no adjustment.
An unmatched region (e.g. ``Amazon`` capitalised, or ``amazon `` with a
trailing space) would otherwise fall back to a 1.0 factor and return a
confident-looking number that is wrong by the real regional adjustment.
Since these figures are meant to be cited, fail loudly instead.
"""
if region is None:
return
from climatevision.analytics.carbon import REGIONAL_FACTORS
if region not in REGIONAL_FACTORS:
raise HTTPException(
status_code=422,
detail=(
f"Unknown region '{region}'. "
f"Valid values: {sorted(REGIONAL_FACTORS)}"
),
)
# Organization models
class CreateOrganizationRequest(BaseModel):
name: str = Field(..., min_length=2, max_length=200)
type: OrganizationType = Field(default="ngo")
description: Optional[str] = None
contact_email: Optional[EmailStr] = None
website_url: Optional[str] = None
regions_of_interest: Optional[list[str]] = None
class OrganizationResponse(BaseModel):
id: int
name: str
type: str
description: Optional[str] = None
logo_url: Optional[str] = None
website_url: Optional[str] = None
contact_email: Optional[str] = None
active: bool
created_at: str
class OrganizationWithKeyResponse(OrganizationResponse):
api_key: str
class CreateSubscriptionRequest(BaseModel):
name: Optional[str] = None
description: Optional[str] = None
bbox: list[float] = Field(..., min_length=4, max_length=4)
analysis_types: list[AnalysisType] = Field(default=["deforestation"])
alert_threshold: float = Field(default=5.0, ge=0, le=100)
notification_channel: NotificationChannel = Field(default="email")
webhook_url: Optional[str] = None
class SubscriptionResponse(BaseModel):
id: int
organization_id: int
name: Optional[str] = None
bbox: list[float]
analysis_types: list[str]
alert_threshold: float
notification_channel: str
active: bool
created_at: str
class AlertResponse(BaseModel):
id: int
organization_id: int
alert_type: str
severity: str
title: str
message: str
delivered: bool
acknowledged: bool
created_at: str
class CreateAlertRequest(BaseModel):
alert_type: str
severity: AlertSeverity = Field(default="medium")
title: str
message: str
subscription_id: Optional[int] = None
run_id: Optional[int] = None
details: Optional[str] = None
# Explainability models
class ExplainRequest(BaseModel):
run_id: Optional[int] = None
analysis_type: AnalysisType = Field(default="deforestation")
target_class: Optional[int] = None
class BandContribution(BaseModel):
band: str
importance: float
class ExplainResponse(BaseModel):
run_id: Optional[int] = None
analysis_type: str
target_class: int
prediction: int
confidence: float
top_bands: list[BandContribution]
heatmap_path: Optional[str] = None
explainer_type: str
# ===== Helper Functions =====
def _load_template_result(
*,
bbox: Optional[list[float]],
start_date: Optional[str],
end_date: Optional[str],
analysis_type: str = "deforestation",
) -> dict[str, Any]:
"""Load or create a template result for failed inference."""
outputs_dir = Path(__file__).resolve().parents[3] / "outputs"
template_path = outputs_dir / "inference_results.json"
if template_path.exists():
template: dict[str, Any] = json.loads(template_path.read_text(encoding="utf-8"))
else:
# Create analysis-specific template
if analysis_type == "ice_melting":
template = {
"region": {"bbox": bbox or None},
"inference": {
"image_size": [256, 256],
"ice_pixels": 0,
"water_pixels": 0,
"land_pixels": 0,
"ice_percentage": 0.0,
"mean_confidence": 0.0,
},
}
elif analysis_type == "flooding":
template = {
"region": {"bbox": bbox or None},
"inference": {
"image_size": [256, 256],
"flooded_pixels": 0,
"dry_pixels": 0,
"water_pixels": 0,
"flooded_percentage": 0.0,
"mean_confidence": 0.0,
},
}
else: # deforestation (default)
template = {
"region": {"bbox": bbox or None},
"ndvi_stats": {"NDVI_min": 0.0, "NDVI_mean": 0.0, "NDVI_max": 0.0},
"inference": {
"image_size": [256, 256],
"forest_pixels": 0,
"non_forest_pixels": 0,
"forest_percentage": 0.0,
"mean_confidence": 0.0,
},
}
if bbox is not None:
template.setdefault("region", {})["bbox"] = bbox
if start_date and end_date:
template.setdefault("region", {})["date_range"] = f"{start_date} to {end_date}"
template["analysis_type"] = analysis_type
return template
async def _persist_upload(*, run_id: int, file: UploadFile) -> str:
"""Save uploaded file to disk."""
outputs_dir = Path(__file__).resolve().parents[3] / "outputs"
uploads_dir = outputs_dir / "uploads"
uploads_dir.mkdir(parents=True, exist_ok=True)
dest = uploads_dir / f"run_{run_id}_{file.filename}"
dest.write_bytes(await file.read())
return str(dest)
async def get_current_organization(
x_api_key: Optional[str] = Header(None, alias="X-API-Key"),
) -> Optional[dict]:
"""Dependency to get current organization from API key."""
if not x_api_key:
return None
org = get_organization_by_api_key(x_api_key)
if org:
return dict(org)
return None
# ===== Audit Logging Middleware =====
class AuditLogMiddleware(BaseHTTPMiddleware):
"""Log every API request with method, path, status code, and duration."""
async def dispatch(self, request: Request, call_next: Any) -> Response:
start = time.perf_counter()
response: Response = await call_next(request)
duration_ms = round((time.perf_counter() - start) * 1000, 2)
logger.info(
"API request | method=%s path=%s status=%s duration_ms=%s ip=%s",
request.method,
request.url.path,
response.status_code,
duration_ms,
request.client.host if request.client else "unknown",
)
response.headers["X-Response-Time-Ms"] = str(duration_ms)
return response
# ===== Application Factory =====
def create_app() -> FastAPI:
init_db()
# Set up alert delivery worker
alert_worker = AlertDeliveryWorker()
@asynccontextmanager
async def lifespan(_app: FastAPI):
"""Start background workers on app startup, stop on shutdown."""
await alert_worker.start()
logger.info("Alert delivery worker started")
yield
await alert_worker.stop()
logger.info("Alert delivery worker stopped")
app = FastAPI(
title="ClimateVision API",
version="0.2.0",
description="""
Climate monitoring API for detecting deforestation, ice melting, flooding, and more.
## Features
- Multi-type climate analysis (deforestation, ice melting, flooding)
- Organization (NGO) management
- Region subscriptions and alerts
- Satellite imagery processing
""",
docs_url="/docs",
redoc_url="/redoc",
openapi_url="/openapi.json",
lifespan=lifespan,
)
app.add_middleware(AuditLogMiddleware)
# CORS: allow local dev origins plus any origins from CLIMATEVISION_CORS_ORIGINS
default_origins = [
"http://localhost:5173",
"http://127.0.0.1:5173",
"http://localhost:3000",
"http://127.0.0.1:3000",
]
extra_origins = [
origin.strip()
for origin in os.environ.get("CLIMATEVISION_CORS_ORIGINS", "").split(",")
if origin.strip()
]
app.add_middleware(
CORSMiddleware,
allow_origins=list(dict.fromkeys(default_origins + extra_origins)),
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Register the RequestIDMiddleware LAST so it sits OUTERMOST in the
# middleware stack: it must run before every other middleware so the
# request_id ContextVar is set in time for AuditLogMiddleware's logger
# call (and for any inference-pipeline code further down). Starlette
# wraps middleware in reverse add_middleware order, so the last call
# is the outermost wrapper.
from climatevision.api.middleware import RequestIDMiddleware
app.add_middleware(RequestIDMiddleware)
# Wire OWASP-aligned security controls (rate limiting, payload limits, etc.)
app.add_middleware(SecurityMiddleware)
from climatevision.api import admin as _admin
app.include_router(_admin.router)
# ===== Core Endpoints =====
_frontend_dist = Path(__file__).resolve().parents[3] / "frontend" / "dist"
if not (_frontend_dist / "index.html").exists():
@app.get("/")
def root() -> RedirectResponse:
"""Redirect to API docs when no frontend is built."""
return RedirectResponse(url="/docs", status_code=302)
@app.get("/api/health")
def health() -> dict[str, Any]:
"""Health check endpoint with API information and config validation."""
from climatevision.data.band_mapping import get_model_config
enabled_types = [t for t in SUPPORTED_ANALYSIS_TYPES if t["enabled"]]
config_issues: list[dict[str, Any]] = []
for atype in enabled_types:
name = atype["name"]
try:
cfg = get_model_config(name)
expected_channels = len(atype["bands"])
expected_classes = len(atype["classes"])
if cfg.get("in_channels") != expected_channels:
config_issues.append(
{
"analysis_type": name,
"issue": "in_channels mismatch",
"expected": expected_channels,
"got": cfg.get("in_channels"),
}
)
if cfg.get("num_classes") != expected_classes:
config_issues.append(
{
"analysis_type": name,
"issue": "num_classes mismatch",
"expected": expected_classes,
"got": cfg.get("num_classes"),
}
)
except Exception as exc:
config_issues.append(
{"analysis_type": name, "issue": "config missing", "error": str(exc)}
)
health_status = "ok" if not config_issues else "degraded"
return {
"status": health_status,
"version": "0.2.0",
"analysis_types": [t["name"] for t in enabled_types],
"config_valid": len(config_issues) == 0,
"config_issues": config_issues,
}
@app.get("/api/health/models")
def health_models() -> dict[str, Any]:
"""Report which analysis types have trained weights available on disk."""
from climatevision.data.band_mapping import get_model_config
models_status = []
for atype in SUPPORTED_ANALYSIS_TYPES:
name = atype["name"]
cfg = get_model_config(name)
weights_path = cfg.get("weights")
has_weights = False
if weights_path:
has_weights = (Path(__file__).resolve().parents[3] / weights_path).exists()
models_status.append(
{
"analysis_type": name,
"enabled": atype["enabled"],
"has_trained_weights": has_weights,
"weights_path": weights_path,
"note": "production inference" if has_weights else "synthetic/demo fallback",
}
)
ready_count = sum(1 for m in models_status if m["has_trained_weights"])
return {
"status": "ready" if ready_count else "demo_mode",
"models": models_status,
"ready_count": ready_count,
"total_count": len(models_status),
}
@app.get("/api/analysis-types")
def list_analysis_types(enabled_only: bool = True) -> list[dict[str, Any]]:
"""List available analysis types."""
if enabled_only:
return [t for t in SUPPORTED_ANALYSIS_TYPES if t["enabled"]]
return SUPPORTED_ANALYSIS_TYPES
@app.get("/api/analysis-types/{analysis_type}")
def get_analysis_type(analysis_type: str) -> dict[str, Any]:
"""Get details for a specific analysis type."""
for t in SUPPORTED_ANALYSIS_TYPES:
if t["name"] == analysis_type:
return t
raise HTTPException(status_code=404, detail=f"Analysis type '{analysis_type}' not found")
# ===== Run Endpoints =====
@app.get("/api/runs")
def list_runs(
limit: int = Query(default=50, le=200),
offset: int = Query(default=0, ge=0),
status: Optional[str] = None,
analysis_type: Optional[str] = None,
) -> dict[str, Any]:
"""List analysis runs with optional filtering and pagination metadata."""
where_clauses = ["1=1"]
params: list = []
if status:
where_clauses.append("status = ?")
params.append(status)
if analysis_type:
where_clauses.append("analysis_type = ?")
params.append(analysis_type)
where = " AND ".join(where_clauses)
with get_connection() as conn:
total: int = conn.execute(
f"SELECT COUNT(*) FROM runs WHERE {where}", params
).fetchone()[0]
rows = conn.execute(
f"SELECT * FROM runs WHERE {where} ORDER BY id DESC LIMIT ? OFFSET ?",
params + [int(limit), int(offset)],
).fetchall()
return {
"total": total,
"limit": limit,
"offset": offset,
"runs": [RunRow(**dict(r)) for r in rows],
}
@app.get("/api/runs/stats")
def get_run_stats() -> dict[str, Any]:
"""Return aggregated run statistics for dashboard KPI cards."""
with get_connection() as conn:
total = conn.execute("SELECT COUNT(*) FROM runs").fetchone()[0]
by_status = {
row["status"]: row["count"]
for row in conn.execute(
"SELECT status, COUNT(*) as count FROM runs GROUP BY status"
).fetchall()
}
by_analysis_type = {
row["analysis_type"]: row["count"]
for row in conn.execute(
"SELECT analysis_type, COUNT(*) as count FROM runs GROUP BY analysis_type"
).fetchall()
}
recent_completed = conn.execute(
"SELECT COUNT(*) FROM runs WHERE status = 'completed' "
"AND created_at >= datetime('now', '-7 days')"
).fetchone()[0]
alerts_total = conn.execute("SELECT COUNT(*) FROM alerts").fetchone()[0]
alerts_unacknowledged = conn.execute(
"SELECT COUNT(*) FROM alerts WHERE acknowledged = 0"
).fetchone()[0]
return {
"total_runs": total,
"completed_last_7_days": recent_completed,
"by_status": by_status,
"by_analysis_type": by_analysis_type,
"alerts": {
"total": alerts_total,
"unacknowledged": alerts_unacknowledged,
},
}
@app.get("/api/runs/{run_id}")
def get_run(run_id: int) -> dict[str, Any]:
"""Get details for a specific run including results."""
with get_connection() as conn:
run = conn.execute("SELECT * FROM runs WHERE id = ?", (run_id,)).fetchone()
if run is None:
raise HTTPException(status_code=404, detail="Run not found")
result = conn.execute(
"SELECT * FROM results WHERE run_id = ? ORDER BY id DESC LIMIT 1", (run_id,)
).fetchone()
payload: Optional[dict[str, Any]] = None
mask_path: Optional[str] = None
if result is not None:
payload = json.loads(result["payload_json"])
mask_path = result["mask_path"]
return {
"run": dict(run),
"result": None
if result is None
else {
"id": result["id"],
"run_id": result["run_id"],
"payload": payload,
"mask_path": mask_path,
"created_at": result["created_at"],
},
}
@app.get("/api/reports/{run_id}")
def get_report(run_id: int) -> dict[str, Any]:
"""Structured carbon impact report for a completed deforestation run.
Recomputes the estimate (with uncertainty bounds) from the stored
pixel count, so it works whether or not carbon was requested at
prediction time.
"""
with get_connection() as conn:
run = conn.execute("SELECT * FROM runs WHERE id = ?", (run_id,)).fetchone()
if run is None:
raise HTTPException(status_code=404, detail="Run not found")
result = conn.execute(
"SELECT * FROM results WHERE run_id = ? ORDER BY id DESC LIMIT 1", (run_id,)
).fetchone()
if result is None:
raise HTTPException(status_code=404, detail="No result available for run")
payload = json.loads(result["payload_json"])
if payload.get("analysis_type") != "deforestation":
raise HTTPException(
status_code=400,
detail="Impact reports are only available for deforestation runs",
)
pixels = _extract_deforested_pixels(payload)
if pixels is None:
raise HTTPException(
status_code=422, detail="Result payload has no pixel count to report on"
)
# Reuse the forest_type/region chosen at prediction time so the report
# and the /api/predict response describe the same run. Falling back to
# the estimator defaults keeps reports working for runs saved before
# carbon was requested.
carbon_meta = payload.get("carbon_estimation") or {}
forest_type = carbon_meta.get("forest_type", "tropical_moist")
region = carbon_meta.get("region", "default")
_validate_forest_type(forest_type)
_validate_region(region)
try:
from climatevision.analytics.carbon import CarbonEstimator
estimator = CarbonEstimator(forest_type=forest_type, region=region)
estimate = estimator.estimate_from_pixel_count(pixels)
except Exception as exc:
logger.exception("Impact report generation failed for run %s", run_id)
raise HTTPException(
status_code=503, detail="Carbon analytics unavailable"
) from exc
region_bbox = json.loads(run["bbox"]) if run["bbox"] else None
return {
"run_id": run_id,
"hectares_lost": estimate.hectares,
"biomass_tonnes": estimate.biomass_tonnes,
"carbon_tonnes": estimate.carbon_tonnes,
"co2_equivalent": estimate.co2_equivalent,
"confidence_interval": {
"lower": estimate.ci_lower,
"upper": estimate.ci_upper,
"uncertainty_pct": estimate.uncertainty_pct,
"unit": "tCO2e",
},
"region_bbox": region_bbox,
"forest_type": estimate.forest_type,
"region": estimate.region,
}
# ===== Prediction Endpoints =====
@app.post("/api/predict")
async def predict_json(
body: PredictRequest,
org: dict[str, Any] = Depends(require_api_key),
) -> dict[str, Any]:
"""Run prediction using bounding box and date range."""
if body.enable_carbon:
_validate_forest_type(body.forest_type)
_validate_region(body.region)
created_at = _utc_now_iso()
bbox_json = json.dumps(body.bbox) if body.bbox else None
with get_connection() as conn:
cur = conn.execute(
"""
INSERT INTO runs (kind, status, analysis_type, bbox, start_date, end_date, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
""",
(
body.kind,
"running",
body.analysis_type,
bbox_json,
body.start_date,
body.end_date,
created_at,
created_at,
),
)
run_id = int(cur.lastrowid)
# Run inference. SAR flood detection has its own Sentinel-1 + JRC pipeline;
# all other analysis types use the shared Sentinel-2 inference path.
try:
if body.analysis_type == "flooding_sar":
result_payload = run_flood_inference_from_gee(
bbox=body.bbox,
start_date=body.start_date,
end_date=body.end_date,
)
else:
result_payload = run_inference_from_gee(
bbox=body.bbox,
start_date=body.start_date,
end_date=body.end_date,
analysis_type=body.analysis_type,
)
result_payload["analysis_type"] = body.analysis_type
status = "completed"
except Exception as exc:
logger.exception("Inference failed for run %s", run_id)
result_payload = _load_template_result(
bbox=body.bbox,
start_date=body.start_date,
end_date=body.end_date,
analysis_type=body.analysis_type,
)
result_payload["error"] = str(exc)
status = "failed"
# Carbon estimation (feature-flagged). Degrades gracefully if the
# analytics module is unavailable or the payload lacks pixel counts.
if (
body.enable_carbon
and status == "completed"
and body.analysis_type == "deforestation"
):
carbon = _compute_carbon_estimation(
result_payload,
forest_type=body.forest_type,
region=body.region,
)
if carbon is not None:
result_payload["carbon_estimation"] = carbon
# Persist result
result_created_at = _utc_now_iso()
with get_connection() as conn:
conn.execute(
"UPDATE runs SET status = ?, updated_at = ? WHERE id = ?",
(status, result_created_at, run_id),
)
conn.execute(
"""
INSERT INTO results (run_id, payload_json, mask_path, created_at)
VALUES (?, ?, ?, ?)
""",
(run_id, json.dumps(result_payload), None, result_created_at),
)
return {"run_id": run_id, "result": result_payload}
@app.post("/api/predict/upload")
async def predict_upload(
kind: str = Form(default="upload"),
org: dict[str, Any] = Depends(require_api_key),
analysis_type: str = Form(default="deforestation"),
bbox: str | None = Form(default=None),
start_date: str | None = Form(default=None),
end_date: str | None = Form(default=None),
file: UploadFile = File(...),
) -> dict[str, Any]:
"""Run prediction on uploaded satellite imagery file."""
if start_date and end_date and start_date > end_date:
raise HTTPException(status_code=400, detail="start_date must be before end_date")
created_at = _utc_now_iso()
parsed_bbox: Optional[list[float]] = None
if bbox:
try:
parsed_bbox = json.loads(bbox)
except json.JSONDecodeError as e:
raise HTTPException(status_code=400, detail="Invalid bbox JSON") from e
with get_connection() as conn:
cur = conn.execute(
"""
INSERT INTO runs (kind, status, analysis_type, bbox, start_date, end_date, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
""",
(
kind,
"running",
analysis_type,
json.dumps(parsed_bbox) if parsed_bbox else None,
start_date,
end_date,
created_at,
created_at,
),
)
run_id = int(cur.lastrowid)
dest = await _persist_upload(run_id=run_id, file=file)
# Run inference
try:
result_payload = run_inference_from_file(
dest,
bbox=parsed_bbox,
start_date=start_date,
end_date=end_date,
analysis_type=analysis_type,
)