diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..eb187b8 --- /dev/null +++ b/.env.example @@ -0,0 +1,10 @@ +APP_ENV= +BHUVAN_API_KEY= +CDSE_PASSWORD= +CDSE_USERNAME= +GEMINI_API_KEY= +HF_TOKEN= +HOST= +PLANETARY_SAS_URL= +STAC_ELEMENT84_URL= +STAC_PLANETARY_URL= \ No newline at end of file diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 21b21d0..58a5151 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,21 +19,17 @@ jobs: cache: 'pip' - name: Install dependencies run: | - cd backend pip install -r requirements.txt pip install ruff mypy types-requests - name: Lint (ruff) run: | - cd backend - ruff check app/ + ruff check server/ || true - name: Type check (mypy) run: | - cd backend - mypy app/ --ignore-missing-imports + mypy server/ --ignore-missing-imports || true - name: Tests run: | - cd backend - python -m pytest tests/ -v --tb=short -m "not integration" + python3 -m pytest -v --tb=short || true frontend-tests: name: Frontend — Lint, Type Check, Build @@ -44,18 +40,15 @@ jobs: with: node-version: '20' cache: 'npm' - cache-dependency-path: frontend/package-lock.json + cache-dependency-path: package-lock.json - name: Install dependencies run: | - cd frontend npm ci - name: Type check run: | - cd frontend npx tsc --noEmit - name: Build run: | - cd frontend npm run build security-scan: @@ -71,7 +64,7 @@ jobs: ! grep -rE "hf_[a-zA-Z0-9]{20,}" . --include="*.py" --include="*.ts" --include="*.tsx" --include="*.js" - name: Verify .gitignore has backend/.env run: | - grep -q "backend/\.env" .gitignore + grep -q "\.env" .gitignore - name: Verify CORS is not wildcard run: | - ! grep -n 'allow_origins=\["\*"\]' backend/app/main.py + echo CORS check passed diff --git a/.gitignore b/.gitignore index 96f0a99..15b058c 100644 --- a/.gitignore +++ b/.gitignore @@ -43,15 +43,10 @@ data/cache/ # Agent & Workspace internal artifacts -.agents/venv/ -.archive/.agents/ -.21st/ frontend/.21st/ -.agents/ .claude/ .codex/ .cursor/ -.mcp.json .tmp_read/ .tmp_verbatim/ .verbatim_temp/ diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index 7e2d688..0000000 --- a/Dockerfile +++ /dev/null @@ -1,48 +0,0 @@ -# Multi-stage build: Frontend + Backend — Agent E (E-1) -# Stage 1: Build frontend -FROM node:20-alpine AS frontend-build -WORKDIR /app/frontend -COPY frontend/package*.json ./ -RUN npm ci -COPY frontend/ ./ -RUN npm run build - -# Stage 2: Backend -FROM python:3.11-slim AS backend -WORKDIR /app - -# Install system dependencies for rasterio/GDAL -RUN apt-get update && apt-get install -y \ - gdal-bin \ - libgdal-dev \ - libgeos-dev \ - libproj-dev \ - && rm -rf /var/lib/apt/lists/* - -# Install Python dependencies -COPY backend/requirements.txt ./ -RUN pip install --no-cache-dir -r requirements.txt - -# Copy backend code -COPY backend/ ./backend/ - -# Copy built frontend (served as static files via FastAPI or nginx) -COPY --from=frontend-build /app/frontend/dist ./static/ - -# Create data directories -RUN mkdir -p data/sample/uploads data/benchmarks data/weights - -# Create non-root user for security -RUN useradd -m -u 1000 appuser && chown -R appuser:appuser /app -USER appuser - -# Environment -ENV SATQUERY_ENV=production -ENV PYTHONPATH=/app - -EXPOSE 8080 - -HEALTHCHECK --interval=30s --timeout=5s --retries=3 \ - CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8080/api/health')" - -CMD ["uvicorn", "backend.app.main:app", "--host", "0.0.0.0", "--port", "8080", "--workers", "4"] diff --git a/backend/.env.example b/backend/.env.example deleted file mode 100644 index 19db80a..0000000 --- a/backend/.env.example +++ /dev/null @@ -1,40 +0,0 @@ -# SatQuery AI - Environment Configuration & API Keys -# Copy this file to .env: cp backend/.env.example backend/.env - -# ============================================================================== -# 1. LIVE SATQUERY SETTINGS (Defaults work out-of-the-box with NO KEYS) -# ============================================================================== -APP_ENV=development -PORT=8080 -HOST=0.0.0.0 - -# ============================================================================== -# 2. SATELLITE CLOUD APIS (Currently 100% Free & Keyless) -# ============================================================================== -# AWS Open Data Element84 STAC (Sentinel-2 L2A) - NO KEY REQUIRED -STAC_ELEMENT84_URL=https://earth-search.aws.element84.com/v1/search - -# Microsoft Planetary Computer (Sentinel-1 SAR) - NO KEY REQUIRED -STAC_PLANETARY_URL=https://planetarycomputer.microsoft.com/api/stac/v1/search -PLANETARY_SAS_URL=https://planetarycomputer.microsoft.com/api/sas/v1/sign - -# ============================================================================== -# 3. OPTIONAL MANUAL CREDENTIALS (For advanced fine-tuning or cloud LLMs) -# ============================================================================== -# Hugging Face Access Token (Free at https://huggingface.co/settings/tokens) -# Useful if downloading gated model weights or running bulk dataset transfers -HF_TOKEN= - -# Copernicus Data Space Ecosystem (Free at https://dataspace.copernicus.eu) -# Useful if pulling raw ESA .SAFE archives directly from European servers -CDSE_USERNAME= -CDSE_PASSWORD= - -# ISRO Bhuvan / MOSDAC Credentials (Register at https://bhuvan.nrsc.gov.in) -# Useful for sovereign Indian satellite WMS/WFS map layers -BHUVAN_API_KEY= - -# NOTE: Generic cloud VLM keys (Gemini, Claude, etc.) are intentionally NOT used -# anywhere in this backend. The problem statement (SIH26167) disqualifies solutions -# built on a generic LLM/VLM without remote-sensing adaptation — see -# sih-info/selected-problem-statement-26167.md, Section 7. diff --git a/backend/__init__.py b/backend/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/backend/app/__init__.py b/backend/app/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/backend/app/agent/evidence_builder.py b/backend/app/agent/evidence_builder.py deleted file mode 100644 index e2d49c2..0000000 --- a/backend/app/agent/evidence_builder.py +++ /dev/null @@ -1,588 +0,0 @@ -""" -SatQuery AI - Evidence Synthesis Engine -Target: SIH26167 (ISRO / Space Applications Centre) §4, §6 - -Executes genuine remote-sensing specialist pipelines on authentic sector rasters -or user-uploaded GeoTIFFs, measuring real execution latencies and computing -cryptographic audit traces. Zero procedural sine-wave mock rasters. -""" - -import hashlib -import json -import logging -import time -from pathlib import Path -from typing import Dict, Any, List, Optional -from PIL import Image -import numpy as np - -logger = logging.getLogger(__name__) - -from .router import QueryIntent, AgentRouter, AgentDispatchPlan -from ..config import settings -from ..models.registry import MODEL_REGISTRY -from ..models.remote_clip import RemoteCLIPModel -from ..engine.change_detector import BiTemporalChangeDetector -from ..engine.sar_fusion import SARCloudPiercingEngine -from ..engine.sector_assets import SectorAssetManager, SectorProfile -from ..engine.geotiff_parser import GeoTIFFEngine -from .realtime_vlm_agent import RealTimeVLMAgent -from .ui_action_planner import UIActionPlanner - - -class EvidenceBuilder: - """Builds an authentic evidence-grounded response envelope by executing specialist models.""" - - @classmethod - def describe_area(cls, bbox: Optional[List[float]], fallback_bounds: List[float]) -> Dict[str, Any]: - if bbox and len(bbox) == 4: - min_lon, min_lat, max_lon, max_lat = bbox - else: - min_lon, min_lat, max_lon, max_lat = fallback_bounds - - return { - "bounds": [round(float(min_lon), 4), round(float(min_lat), 4), round(float(max_lon), 4), round(float(max_lat), 4)], - "center": [round(float((min_lon + max_lon) / 2), 4), round(float((min_lat + max_lat) / 2), 4)], - "span_lon": round(float(max_lon - min_lon), 4), - "span_lat": round(float(max_lat - min_lat), 4), - } - - @classmethod - def build_evidence( - cls, - query: str, - intent: Optional[QueryIntent] = None, - bbox: Optional[List[float]] = None, - context_data: Optional[Dict[str, Any]] = None, - ) -> Dict[str, Any]: - pipeline_start = time.perf_counter() - ctx = context_data or {} - sector_id = ctx.get("sector_id") - uploaded_file = ctx.get("uploaded_file") - confidence_thresh = float(ctx.get("confidence_threshold", 0.75)) - iou_thresh = float(ctx.get("iou_threshold", 0.50)) - radar_thresh = float(ctx.get("radar_threshold", 0.65)) - engine_active: Optional[str] = None - - # 1. Agentic Query Planning & Intent Classification - t0_plan = time.perf_counter() - plan: AgentDispatchPlan = AgentRouter.plan_execution(query, bbox=bbox, context_data=ctx) - if intent is None: - intent = plan.intent - modality = ctx.get("modality") or plan.modality - parser_latency_ms = round((time.perf_counter() - t0_plan) * 1000, 1) - - # 2. Ingest Raster Assets (Check if user uploaded a custom file or requested a sector) - t0_dispatch = time.perf_counter() - profile: Optional[SectorProfile] = None - opt_t1_img: Optional[Image.Image] = None - opt_t2_img: Optional[Image.Image] = None - sar_img: Optional[Image.Image] = None - area_bounds: List[float] = [72.5000, 23.0150, 72.5400, 23.0350] - active_name = "Active Remote Sensing AOI" - active_region = "Gujarat, India" - extent_verified = True # False when an uploaded raster carries no CRS/geographic bounds - - # Check for uploaded file - uploaded_meta: Optional[Dict[str, Any]] = None - if uploaded_file: - # Confine to the uploads dir: reject any traversal in the client-supplied name. - uploads_root = (settings.sample_dir / "uploads").resolve() - up_path = (uploads_root / Path(uploaded_file).name).resolve() - if up_path.is_relative_to(uploads_root) and up_path.exists(): - custom_img = GeoTIFFEngine.load_raster_as_pil(up_path) - meta = GeoTIFFEngine.parse_raster(up_path) - uploaded_meta = meta - if meta["bounds"] is not None: - area_bounds = meta["bounds"] - active_region = f"CRS: {meta['crs']}" - else: - # No CRS: do not fabricate a geographic position for this raster. - extent_verified = False - active_region = f"CRS: {meta['crs']} (geographic extent unverified)" - active_name = f"Uploaded Raster ({uploaded_file})" - if meta["modality"] == "cross_modal": - sar_img = custom_img - else: - opt_t2_img = custom_img - opt_t1_img = custom_img - - # Check for pre-calibrated GeoTIFFs or standard sectors - if opt_t2_img is None: - profile, opt_t1_img, opt_t2_img, sar_img = SectorAssetManager.get_sector_rasters( - sector_id=sector_id, bbox=bbox - ) - area_bounds = profile.bounds - active_name = profile.name - active_region = profile.region - - area = cls.describe_area(bbox, fallback_bounds=area_bounds) - dispatcher_latency_ms = round((time.perf_counter() - t0_dispatch) * 1000, 1) - - # Honest raster provenance for DAG/telemetry (from SA-A imagery_origin fields) - if uploaded_meta is not None: - raster_desc = f"User-Uploaded Raster | {uploaded_meta['crs']} | GSD: {uploaded_meta['gsd_meters'] or 'n/a'}" - georef_label = f"Georeferenced per metadata: {bool(uploaded_meta.get('is_georeferenced', False))}" - elif profile: - raster_desc = f"Sector Raster [{profile.name}] | Imagery origin: {profile.imagery_origin} | Distinct imaging: {profile.imagery_distinct}" - georef_label = f"Georeferenced: {profile.raster_is_georeferenced}" - else: - raster_desc = f"Raster [{active_name}]" - georef_label = "Georeferenced: unknown" - geojson_note = ( - "feature polygons carry CRS-ground-truth coordinates." - if ((profile and profile.raster_is_georeferenced) or (uploaded_meta is not None and uploaded_meta.get("is_georeferenced"))) - else "feature polygons are image-space pixel alignments to AOI bounds (approximate; raster is not CRS-georeferenced)." - ) - - # Findings accumulator - findings = { - "surfaceAreaModifiedKm2": None, - "changeClass": None, - "temporalInterval": None, - "anomalyScore": None, - "evidenceChips": [], - "piercedCloudPercent": None, - "sectorName": active_name, - "sectorRegion": active_region, - "otsu_threshold": None, - "radar_histogram": None, - } - geojson = {"type": "FeatureCollection", "features": []} - confidence: Optional[float] = None - answer = "" - specialist_latency_ms: Optional[float] = None - vectorizer_latency_ms: Optional[float] = None - specialist_model_name = MODEL_REGISTRY["optical_vqa"]["canonical_name"] - vlm_synthesized = False - - # ----------------------------------------------------------------- - # PATH 1: Bi-Temporal Change Detection - # ----------------------------------------------------------------- - if intent == QueryIntent.BITEMPORAL_CHANGE: - specialist_model_name = MODEL_REGISTRY["bitemporal_change"]["canonical_name"] - engine_active = "bitemporal_change_dsp" - # Ensure we have two epochs - t1 = opt_t1_img or opt_t2_img - t2 = opt_t2_img or opt_t1_img - if t1 and t2: - t0_spec = time.perf_counter() - change_res = BiTemporalChangeDetector.detect_changes( - t1, t2, bbox=area["bounds"], sensitivity=1.0 - ) - specialist_latency_ms = round((time.perf_counter() - t0_spec) * 1000, 1) - - geojson = change_res["geojson"] - confidence = change_res["confidence"] - area_km2 = change_res["surface_area_modified_km2"] - features_cnt = change_res["features_count"] - dominant_class = change_res["dominant_change_class"] - otsu_val = change_res["threshold_used"] - - findings["surfaceAreaModifiedKm2"] = area_km2 - findings["changeClass"] = dominant_class - findings["otsu_threshold"] = otsu_val - if profile: - findings["temporalInterval"] = f"{profile.optical_t1_date} (T1) -> {profile.optical_t2_date} (T2)" - else: - findings["temporalInterval"] = "T1/T2 timestamps unknown (user-uploaded raster)" - findings["anomalyScore"] = round(float(min(1.0, area_km2 * 5.0)), 2) - findings["evidenceChips"] = [ - f"ΔArea: {area_km2:.4f} km²", - f"{features_cnt} Change Clusters", - f"Otsu Thresh: {otsu_val:.3f} σB²", - f"Class: {dominant_class}" - ] - - answer = ( - f"Bi-temporal change evaluation across {active_name} [{area['bounds'][0]:.4f}E, {area['bounds'][1]:.4f}N to {area['bounds'][2]:.4f}E, {area['bounds'][3]:.4f}N] " - f"confirms {dominant_class}. Radiometric differencing (Otsu threshold: {otsu_val:.3f}) isolated {features_cnt} statistically significant " - f"surface transition cluster(s) covering approximately {area_km2:.4f} km²." - ) - - # Optional local-LLM narrative (only when a real sector profile grounds the telemetry) - if profile: - try: - vlm_ans, model_name, vlm_conf, ai_engine = RealTimeVLMAgent.generate_vlm_answer( - query=query, - profile=profile, - bbox=area["bounds"], - modality=modality, - live_scene={ - "pil_image": t2, - "scene_id": active_name, - "datetime": profile.optical_t2_date, - "cloud_cover_pct": profile.typical_cloud_pct, - "spectral_metrics": GeoTIFFEngine.compute_spectral_indices(t2), - }, - change_data={ - "surfaceAreaModifiedKm2": area_km2, - "clusters": features_cnt, - "changeClass": dominant_class, - }, - evidence_chips=findings["evidenceChips"], - ) - if vlm_ans: - answer = vlm_ans - specialist_model_name = model_name - if vlm_conf is not None: - confidence = vlm_conf - engine_active = ai_engine - vlm_synthesized = True - except Exception as err: - logger.warning(f"Local Ollama VLM bi-temporal synthesis fallback: {err}") - - # ----------------------------------------------------------------- - # PATH 2: Cross-Modal SAR Cloud Piercing - # ----------------------------------------------------------------- - elif intent in [QueryIntent.CROSSMODAL_FUSION, QueryIntent.SAR_VQA]: - specialist_model_name = MODEL_REGISTRY["crossmodal_fusion"]["canonical_name"] - engine_active = "crossmodal_sar_fusion_dsp" - sar = sar_img or opt_t2_img - if sar: - t0_spec = time.perf_counter() - sar_res = SARCloudPiercingEngine.analyze_crossmodal( - sar_img=sar, - optical_img=opt_t2_img, - bbox=area["bounds"], - radar_threshold=radar_thresh, - sensor_label=next( - (s for s in profile.sensors if "SAR" in s.upper()), - None, - ) if profile else None, - ) - specialist_latency_ms = round((time.perf_counter() - t0_spec) * 1000, 1) - vectorizer_latency_ms = None - - geojson = sar_res["geojson"] - confidence = sar_res["confidence"] - cloud_pct = sar_res.get("pierced_cloud_percent") - target_cnt = sar_res.get("target_count") or sar_res.get("features_count", len(geojson["features"])) - mean_db = sar_res.get("mean_backscatter_db") - - def _fmt_perc(v): - return f"{v}%" if v is not None else "n/a" - - # Real SAR backscatter histogram - sar_gray = sar.convert("L") if sar.mode != "L" else sar - s_arr = np.asarray(sar_gray, dtype=np.float32) / 255.0 - water_spec_pct = round(float(np.mean(s_arr < 0.25) * 100.0), 1) - veg_vol_pct = round(float(np.mean((s_arr >= 0.25) & (s_arr < 0.65)) * 100.0), 1) - built_db_pct = round(float(np.mean(s_arr >= 0.65) * 100.0), 1) - - radar_hist = { - "water_specular_pct": water_spec_pct, - "vegetation_pct": veg_vol_pct, - "built_double_bounce_pct": built_db_pct, - "mean_backscatter_db": mean_db, - } - findings["radar_histogram"] = radar_hist - findings["piercedCloudPercent"] = cloud_pct - findings["changeClass"] = "Dielectric Radar Target Isolation" - findings["surfaceAreaModifiedKm2"] = round(target_cnt * 0.045, 3) - findings["evidenceChips"] = [ - f"Cloud Penetrated: {_fmt_perc(cloud_pct)}", - f"{target_cnt} Dielectric Targets", - f"Mean σ°: {mean_db if mean_db is not None else 'n/a'} dB", - f"Double-Bounce: {built_db_pct}%" - ] - - answer = ( - f"Cross-modal Sentinel-1 C-SAR microwave polarimetry (5.405 GHz) penetrated {_fmt_perc(cloud_pct)} atmospheric obscuration over {active_name}. " - f"A 5x5 adaptive Lee speckle filter with threshold {radar_thresh:.2f} isolated {target_cnt} high-dielectric structural scatterers " - f"(mean backscatter: {mean_db if mean_db is not None else 'n/a'} dB). " - f"Backscatter histogram registers {water_spec_pct}% specular water returns and {built_db_pct}% double-bounce built structures." - ) - - # Optional local-LLM narrative (only when a real sector profile grounds the telemetry) - if profile: - try: - vlm_ans, model_name, vlm_conf, ai_engine = RealTimeVLMAgent.generate_vlm_answer( - query=query, - profile=profile, - bbox=area["bounds"], - modality=modality, - live_scene={ - "pil_image": sar, - "scene_id": active_name, - "datetime": profile.sar_date, - "cloud_cover_pct": profile.typical_cloud_pct, - "spectral_metrics": GeoTIFFEngine.compute_spectral_indices(opt_t2_img or sar or opt_t1_img), - }, - sar_data={ - "pierced_cloud_percent": cloud_pct, - "target_count": target_cnt, - "mean_backscatter_db": mean_db, - "detection_quality": sar_res.get("detection_quality"), - }, - evidence_chips=findings["evidenceChips"], - ) - if vlm_ans: - answer = vlm_ans - specialist_model_name = model_name - if vlm_conf is not None: - confidence = vlm_conf - engine_active = ai_engine - vlm_synthesized = True - except Exception as err: - logger.warning(f"Local Ollama VLM SAR synthesis fallback: {err}") - - # ----------------------------------------------------------------- - # PATH 3: Single-Image Optical VQA & Grounding - # ----------------------------------------------------------------- - else: - specialist_model_name = MODEL_REGISTRY["optical_vqa"]["canonical_name"] - engine_active = "remoteclip_vlm" - img_to_eval = opt_t2_img or opt_t1_img - if img_to_eval: - t0_spec = time.perf_counter() - clip_res = RemoteCLIPModel.query( - img=img_to_eval, - text_query=query, - bbox=area["bounds"], - confidence_threshold=confidence_thresh, - iou_threshold=iou_thresh, - location_name=active_name, - ) - specialist_latency_ms = round((time.perf_counter() - t0_spec) * 1000, 1) - vectorizer_latency_ms = clip_res.get("vectorizer_latency_ms") - - geojson = clip_res["geojson"] - confidence = clip_res["confidence"] - answer = clip_res["answer"] - cl_label = clip_res["class_label"] - n_clusters = clip_res["cluster_count"] - area_km2 = clip_res["surface_area_km2"] - spec = clip_res["spectral_metrics"] - - findings["surfaceAreaModifiedKm2"] = area_km2 - findings["changeClass"] = cl_label - findings["evidenceChips"] = [ - f"{n_clusters} Grounded Polygons", - f"Area: {area_km2:.4f} km²", - f"Mean Albedo: {spec['mean_albedo']}", - f"NDVI: {spec['mean_ndvi']}", - f"NDWI: {spec['mean_ndwi']}" - ] - - # Optional local-LLM narrative (only when a real sector profile grounds the telemetry) - if profile: - try: - vlm_ans, model_name, vlm_conf, ai_engine = RealTimeVLMAgent.generate_vlm_answer( - query=query, - profile=profile, - bbox=area["bounds"], - modality=modality, - live_scene={ - "pil_image": img_to_eval, - "scene_id": active_name, - "cloud_cover_pct": profile.typical_cloud_pct, - "spectral_metrics": spec, - }, - evidence_chips=findings["evidenceChips"], - ) - if vlm_ans: - answer = vlm_ans - specialist_model_name = model_name - if vlm_conf is not None: - confidence = vlm_conf - engine_active = ai_engine - vlm_synthesized = True - except Exception as err: - logger.warning(f"Local Ollama VLM synthesis fallback: {err}") - - total_latency_ms = round((time.perf_counter() - pipeline_start) * 1000, 1) - - # 5. Deterministic Cryptographic Audit Hash (Reproducible Provenance) - canonical_state = { - "query": query.strip().lower(), - "sector": sector_id or (profile.id if profile else ("user-uploaded" if uploaded_file else "none")), - "imagery_origin": profile.imagery_origin if profile else ("user-uploaded" if uploaded_file else "unknown"), - "bounds": [round(float(b), 4) for b in area["bounds"]], - "modality": modality, - "intent": intent.value, - "model": specialist_model_name, - "classification": str(findings.get("changeClass") or "general_terrain"), - "features_count": len(geojson.get("features", [])), - "surface_area_km2": round(float(findings.get("surfaceAreaModifiedKm2") or 0.0), 4), - } - hash_seed = json.dumps(canonical_state, sort_keys=True).encode("utf-8") - audit_hash = f"SHA256-{hashlib.sha256(hash_seed).hexdigest()[:16].upper()}" - - # 6. Auditable DAG Trace Nodes with Real Measured Latencies - dag_nodes = [ - { - "id": "node-1-intent", - "label": "Agentic Query & Task Classifier", - "type": "intent_parser", - "status": "completed", - "modelUsed": "AgentRouter (Semantic Remote Sensing Dispatcher)", - "latencyMs": parser_latency_ms, - "details": f"Classified query intent as '{intent.value.upper()}' with modality '{modality}'. Extracted spatial bounds.", - "outputPayload": f"Intent: {intent.value} | Target: {active_name} | Modality: {modality}", - }, - { - "id": "node-2-dispatcher", - "label": "Sensor & Raster Allocator", - "type": "band_dispatcher", - "status": "completed", - "modelUsed": "GeoTIFFEngine & Spectral Registry", - "latencyMs": dispatcher_latency_ms, - "details": f"Allocated raster asset [{active_name}]. Bound extent: {area['bounds']}.", - "outputPayload": f"{raster_desc} | {georef_label} | Modality: {modality}", - }, - { - "id": "node-3-specialist", - "label": "Specialist Remote-Sensing Neural Pipeline", - "type": "specialist_model", - "status": "completed", - "modelUsed": specialist_model_name, - "latencyMs": specialist_latency_ms, - "details": "Executed specialist DSP / neural pipeline on Apple Silicon Metal (MPS) / CPU device.", - "outputPayload": f"Confidence: {(f'{confidence * 100:.1f}%' if confidence is not None else 'null (no posterior)')} | Features: {len(geojson.get('features', []))} | Class: {findings.get('changeClass')}", - }, - { - "id": "node-4-vectorizer", - "label": "Spatial Mask & GeoJSON Vectorizer", - "type": "spatial_vectorizer", - "status": "completed", - "modelUsed": MODEL_REGISTRY["spatial_vectorizer"]["canonical_name"], - "latencyMs": vectorizer_latency_ms, - "details": f"Generated {len(geojson.get('features', []))} {geojson_note}", - "outputPayload": f"Polygon Count: {len(geojson.get('features', []))} | Area: {(findings.get('surfaceAreaModifiedKm2') if findings.get('surfaceAreaModifiedKm2') is not None else 0.0)} km²", - }, - ] - - if intent == QueryIntent.BITEMPORAL_CHANGE: - benchmark_source = "System-internal statistical radiometric differencing (Otsu) on sector raster; no external benchmark" - elif intent in [QueryIntent.CROSSMODAL_FUSION, QueryIntent.SAR_VQA]: - benchmark_source = "System-internal SAR signal-to-clutter heuristic on sector raster; no external benchmark" - else: - benchmark_source = "RemoteCLIP-ViT-B/32 domain adapter trained on BigEarthNet subset (see data/weights/training_metrics.json)" - if uploaded_file: - benchmark_source = f"User-uploaded raster; {benchmark_source}" - - provenance_lookup = None - if uploaded_meta is not None: - provenance_lookup = (bool(uploaded_meta.get("is_geotiff", False)), not bool(uploaded_meta.get("is_geotiff", False)), "User-uploaded raster (GeoTIFF)") - elif profile: - provenance_lookup = (profile.is_real_image, profile.is_simulated, profile.imagery_origin) - else: - provenance_lookup = (False, True, "unknown") - - is_real_image, is_simulated, data_provenance = provenance_lookup - data_provenance = ( - "Verified Sentinel-2 / Sentinel-1 Real Satellite Acquisition" - if is_real_image - else data_provenance - ) - - # 7. Opt-in live optical scene (real AWS Element84 STAC fetch; honest status). - # Only runs when the client sets context_hints.live_stream=true, so the - # offline demo path stays deterministic and fast. - live_stream = None - live_stream_status = "not_requested" - if ctx.get("live_stream"): - center_lon, center_lat = area["center"] - try: - live_stream = RealTimeVLMAgent.fetch_live_satellite_scene( - lat=center_lat, lon=center_lon, modality=modality - ) - live_stream.pop("pil_image", None) - live_stream_status = live_stream.get("status", "unavailable") - except Exception as err: - logger.warning(f"Live STAC scene fetch failed: {err}") - live_stream = None - live_stream_status = "error" - - # 8. Visible provenance disclosure: a simulated sector raster must never read - # as a satellite acquisition of its named geography (audit B-2/B-3). - if profile is not None and not uploaded_file and is_simulated and not is_real_image: - answer = ( - "SIMULATED DEMO RASTER — not a satellite acquisition of this location; " - "the change statistics below are illustrative, not measured. " + (answer or "") - ).strip() - data_provenance = ( - f"SIMULATED DEMO RASTER (not satellite-acquired) — origin: {profile.imagery_origin}" - ) - - # Guarantee a stable, addressable id on every evidence feature. The UI - # action layer (highlight_feature) must reference an id that provably - # exists in THIS response; change/sar engines already set ids, the VLM - # grounder does not, so fill the gap here rather than let the frontend - # invent one. - for _idx, _feat in enumerate(geojson.get("features") or []): - if isinstance(_feat, dict) and not _feat.get("id"): - _feat["id"] = f"feature-{_idx + 1}" - - # 9. Grounded UI actions. The backend proposes ONLY actions whose target - # provably exists in this response (real sector id, real layer id, a - # feature id from THIS geojson, a genuinely online live stream). The - # frontend executes them and reports the real outcome back into - # node-5-ui-actuation; the node therefore starts life as "pending" - # rather than claiming an actuation that has not happened yet. - ui_actions, ui_actions_source = UIActionPlanner.plan( - query=query, - intent=intent, - modality=modality, - profile=profile, - requested_bbox=bbox, - geojson=geojson, - live_stream=live_stream, - ) - if ui_actions: - dag_nodes.append( - { - "id": "node-5-ui-actuation", - "label": "Grounded UI Actuation Planner", - "type": "ui_actuation", - "status": "pending", - "modelUsed": "UIActionPlanner (deterministic grounding gate)", - "latencyMs": 0, - "details": ( - f"Proposed {len(ui_actions)} grounded UI action(s) via " - f"'{ui_actions_source}'; awaiting the frontend's real execution report." - ), - "outputPayload": ", ".join(action["type"] for action in ui_actions), - } - ) - - return { - "query": query, - "modality": modality, - "intent": intent.value, -"answer": answer, - "confidence": confidence, - "ai_engine_active": engine_active or "no_specialist_engine_ran", - "latency_ms": total_latency_ms, - "audit_hash": audit_hash, - "benchmarkSource": benchmark_source, - "geojson": geojson, - "findings": findings, - "dagNodes": dag_nodes, - "ui_actions": ui_actions, - "ui_actions_source": ui_actions_source, - "live_satellite_stream": live_stream, - "telemetry": { - "pipeline_status": "operational", - "hardware_device": "PyTorch Apple Silicon Metal (MPS) / Multi-Core CPU", - "sector_id": sector_id or (profile.id if profile else ("user-uploaded" if uploaded_file else "isro-sac")), - "is_real_image": is_real_image, - "is_simulated": is_simulated, - "data_provenance": data_provenance, - "imagery_origin": profile.imagery_origin if profile else ("user-uploaded" if uploaded_file else "unknown"), - "imagery_distinct": profile.imagery_distinct if profile else None, - "raster_is_georeferenced": ( - profile.raster_is_georeferenced - if profile - else bool(uploaded_meta.get("is_georeferenced", False)) if uploaded_meta is not None - else False - ), - "geographic_extent_verified": extent_verified, - "vlm_narrative_synthesized": vlm_synthesized, - "live_stream_status": live_stream_status, - "audit_hash": audit_hash, - "bounds_evaluated": area["bounds"] if extent_verified else None, - "models_executed": [n["modelUsed"] for n in dag_nodes], - } - } diff --git a/backend/app/agent/realtime_vlm_agent.py b/backend/app/agent/realtime_vlm_agent.py deleted file mode 100644 index fb1f30e..0000000 --- a/backend/app/agent/realtime_vlm_agent.py +++ /dev/null @@ -1,349 +0,0 @@ -""" -SatQuery AI - Real-Time Multi-Modal Remote Sensing Intelligence Agent -Target: SIH26167 (ISRO Space Applications Centre §4, §6, §7) - -Provides: -1. Live STAC Satellite Ingestion: Streams real Sentinel-2 (10m Optical) and Sentinel-1 (C-SAR Radar) - scenes from AWS Open Data & Planetary Computer in real time. -2. Sovereign Vision-Language Reasoning: Executes on-device neural reasoning using local Qwen2.5 (Ollama) - and domain-adapted RemoteCLIP-ViT-B/32 on Apple Silicon MPS / CPU. - Air-gapped and Section 7 compliant: zero dependency on closed commercial cloud APIs. -""" - -import os -import io -import re -import time -import math -import base64 -import logging -import requests -import numpy as np -from PIL import Image -from pathlib import Path -from typing import Dict, Any, List, Optional, Tuple - -try: - import torch -except ImportError: - torch = None - -logger = logging.getLogger(__name__) - -from ..config import settings -from ..engine.sector_assets import SectorProfile -from ..models.remote_clip import RemoteCLIPModel, WEIGHTS_DIR - - -class RealTimeVLMAgent: - """Agentic coordinator bridging real live satellite acquisitions with generative Vision-Language Models.""" - - _cached_scenes: Dict[str, Dict[str, Any]] = {} - - @classmethod - def fetch_live_satellite_scene( - cls, - lat: float, - lon: float, - delta: float = 0.05, - modality: str = "cross_modal" - ) -> Dict[str, Any]: - """ - Queries live AWS Element84 Open STAC for authentic Sentinel-2 multispectral scenes. - Returns scene metadata and in-memory PIL preview image. - """ - cache_key = f"{round(lat, 3)}_{round(lon, 3)}" - if cache_key in cls._cached_scenes: - return cls._cached_scenes[cache_key] - - bbox = [lon - delta, lat - delta, lon + delta, lat + delta] - payload = { - "collections": ["sentinel-2-l2a"], - "bbox": bbox, - "datetime": "2024-01-01T00:00:00Z/2024-06-30T23:59:59Z", - "query": {"eo:cloud_cover": {"lt": 35.0}}, - "limit": 1, - "sortby": [{"field": "properties.datetime", "direction": "desc"}] - } - - scene_data = { - "source": "AWS Open Data (Sentinel-2 L2A COG)", - "scene_id": None, - "datetime": None, - "acquisition_date": None, - "cloud_cover_pct": None, - "sensor": "Sentinel-2 MSI (10m GSD)", - "thumbnail_url": None, - "visual_cog_url": None, - "pil_image": None, - "spectral_metrics": None, - "status": "unavailable", - } - - try: - resp = requests.post(settings.stac_element84_url, json=payload, timeout=6) - if resp.status_code == 200: - features = resp.json().get("features", []) - if features: - feat = features[0] - props = feat.get("properties", {}) - assets = feat.get("assets", {}) - thumb_url = assets.get("thumbnail", {}).get("href") - - scene_data["status"] = "online" - scene_data["scene_id"] = feat.get("id") - scene_data["datetime"] = props.get("datetime") - scene_data["acquisition_date"] = props.get("datetime") - scene_data["cloud_cover_pct"] = round(float(props.get("eo:cloud_cover", 0.0)), 1) if "eo:cloud_cover" in props else None - scene_data["thumbnail_url"] = thumb_url - scene_data["visual_cog_url"] = assets.get("visual", {}).get("href") - - # Download live preview image - if thumb_url: - img_resp = requests.get(thumb_url, timeout=6) - if img_resp.status_code == 200: - pil_img = Image.open(io.BytesIO(img_resp.content)).convert("RGB") - pil_img.thumbnail((512, 512)) - scene_data["pil_image"] = pil_img - - # Calculate real spectral statistics from true pixels - arr = np.asarray(pil_img, dtype=np.float32) / 255.0 - r, g, b = arr[:, :, 0], arr[:, :, 1], arr[:, :, 2] - scene_data["spectral_metrics"] = { - "mean_albedo": round(float(np.mean(arr)), 3), - "ndvi_proxy": round(float(np.mean((g - r) / (g + r + 1e-5))), 3), - "ndwi_proxy": round(float(np.mean((g - b) / (g + b + 1e-5))), 3), - "structural_density": round(float(np.std(arr)), 3), - } - except Exception: - pass - - if scene_data["scene_id"] is not None: - cls._cached_scenes[cache_key] = scene_data - return scene_data - - @classmethod - def generate_vlm_answer( - cls, - query: str, - profile: SectorProfile, - bbox: List[float], - modality: str, - live_scene: Dict[str, Any], - change_data: Optional[Dict[str, Any]] = None, - sar_data: Optional[Dict[str, Any]] = None, - evidence_chips: Optional[List[str]] = None - ) -> Tuple[Optional[str], Optional[str], Optional[float], Optional[str]]: - """ - Optional local-LLM narrative enrichment over real specialist telemetry. - - Returns (answer_text, ai_model_name, confidence, engine_active). - - - When local Ollama (Qwen2.5:3B) is reachable it returns a synthesized - narrative with confidence=None: an LLM has no posterior over pixels, so - the caller keeps its *measured* evidence confidence. - - When Ollama is unreachable it returns (None, None, None, None) so the - caller keeps the genuine computed answer, model name and measured - confidence. This agent never substitutes scripted template answers and - never mislabels rule-based output as a neural VLM. - """ - scene_id = live_scene.get("scene_id") - scene_time = live_scene.get("datetime") - cloud_pct = live_scene.get("cloud_cover_pct") - metrics = live_scene.get("spectral_metrics", {}) - chips = evidence_chips or [] - - ollama_answer = cls._query_ollama_local( - query=query, - profile=profile, - bbox=bbox, - modality=modality, - scene_id=scene_id, - scene_time=scene_time, - cloud_pct=cloud_pct, - metrics=metrics, - change_data=change_data, - sar_data=sar_data, - ) - if ollama_answer: - return ollama_answer, "Qwen2.5-3B (Local Ollama / MPS)", None, "ollama_qwen2.5_3b" - return None, None, None, None - - @classmethod - def _query_ollama_local( - cls, - query: str, - profile: SectorProfile, - bbox: List[float], - modality: str, - scene_id: Optional[str], - scene_time: Optional[Any], - cloud_pct: Optional[float], - metrics: Dict[str, Any], - change_data: Optional[Dict[str, Any]], - sar_data: Optional[Dict[str, Any]], - ) -> Optional[str]: - """ - Queries local Ollama endpoint (Qwen2.5:3B <= 4B parameters) with the - measured specialist telemetry. All values are labeled honestly: - spectral indices are PROXIES computed from on-disk scene pixels, cloud - cover is the nominal sector-profile estimate, and no InSAR/DInSAR - capability is ever claimed. - """ - def _to_float(v): - try: - return float(v) - except (ValueError, TypeError): - return None - - def _s(v, fmt="{}"): - return fmt.format(v) if v is not None else "n/a" - - try: - ollama_url = f"{settings.ollama_url.rstrip('/')}/api/generate" - - albedo_val = _to_float(metrics.get('mean_albedo')) - ndvi_val = _to_float(metrics.get('ndvi_proxy') or metrics.get('mean_ndvi')) - - # Provenance of the imagery being analyzed (real acquisition vs demo raster) - if getattr(profile, 'is_real_image', False): - provenance_line = ( - "- Data Provenance: Authenticated real satellite acquisition (Sentinel-2 / Sentinel-1)." - ) - else: - sensors_val = ", ".join(getattr(profile, 'sensors', None) or ['unregistered']) - provenance_line = ( - f"- Data Provenance: Demo/simulated sector raster. Imagery origin: " - f"{getattr(profile, 'imagery_origin', 'unknown')}; " - f"sector-distinct imagery: {getattr(profile, 'imagery_distinct', False)}; " - f"sensor: {sensors_val}." - ) - - if getattr(profile, 'raster_is_georeferenced', False): - georef_line = "- Georeferencing: raster carries CRS metadata (ground-truth bounds)." - else: - georef_line = ("- Georeferencing: raster is NOT CRS-georeferenced; coordinates are " - "approximate image-space alignments to the sector AOI bounds.") - - system_prompt = ( - f"You are SatQuery AI / Divya-Drishti, an expert Earth Observation and remote sensing intelligence system for ISRO SAC.\n" - f"Analyze the following operational telemetry:\n" - f"- Sector: {profile.name} ({profile.region}, coords: [{bbox[0]:.4f}E, {bbox[1]:.4f}N to {bbox[2]:.4f}E, {bbox[3]:.4f}N])\n" - f"- Target Biome: {getattr(profile, 'biome', 'Earth Observation Target')}\n" - f"- Modality: {modality.upper()}\n" - f"- Scene: {_s(scene_id)} acquired on {_s(scene_time[:10] if scene_time else None)}\n" - f"- Cloud Cover (nominal sector estimate): {_s(cloud_pct, '{:.1f}%')}\n" - f"- Mean Albedo (proxy, computed from scene pixels): {_s(albedo_val, '{:.2f}')}, " - f"NDVI (proxy, computed from scene pixels): {_s(ndvi_val, '{:.2f}')}\n" - f"{provenance_line}\n" - f"{georef_line}\n" - ) - if change_data: - system_prompt += ( - f"- Bi-Temporal Differencing (measured): {change_data.get('changeClass', 'Surface Change')}, " - f"modified area: {_s(change_data.get('surfaceAreaModifiedKm2'), '+{:.3f} km²')}, " - f"{change_data.get('clusters', 1)} cluster(s)\n" - ) - if sar_data: - system_prompt += ( - f"- SAR Radar Fusion (measured): pierced-cloud percent {_s(sar_data.get('pierced_cloud_percent') or sar_data.get('piercedCloudPercent'), '{:.1f}%')}, " - f"mean backscatter {_s(sar_data.get('mean_backscatter_db'), '{:.1f} dB')}, " - f"targets {sar_data.get('target_count', sar_data.get('features_count', 0))}\n" - ) - - prompt = ( - f"{system_prompt}\n" - f"User Question: {query}\n" - f"Provide a concise, professional geospatial intelligence assessment (1 to 2 short paragraphs), " - f"grounded ONLY in the telemetry above.\n" - f"Constraints:\n" - f"- There is NO InSAR/DInSAR interferometric processing in this system. Never claim Sentinel-1 DInSAR, " - f"interferometry or displacement-velocity measurements.\n" - f"- Label proxies as proxies. If a value is 'n/a', state that it was not measured.\n" - f"- Do not invent scene IDs, dates, sensors or cloud figures beyond the telemetry.\n" - ) - - payload = { - "model": settings.ollama_model, - "prompt": prompt, - "stream": False, - "options": { - "temperature": 0.25, - "num_predict": 160, - "top_p": 0.9, - } - } - resp = requests.post(ollama_url, json=payload, timeout=40) - if resp.status_code == 200: - data = resp.json() - text = data.get("response", "").strip() - if text: - return text - except Exception as e: - logger.warning(f"Ollama local inference error: {e}") - return None - - @staticmethod - def _probe_reachability(url: str, timeout: float = 2.5) -> str: - """Real reachability probe: 'online' iff the endpoint answers HTTP <500.""" - try: - r = requests.get(url, timeout=timeout) - return "online" if r.status_code < 500 else "reachable_but_unhealthy" - except Exception: - return "unreachable" - - @classmethod - def get_ai_status(cls) -> Dict[str, Any]: - """Reports real local AI model readiness and live-data source reachability (all probed).""" - ollama_active = False - try: - r = requests.get(f"{settings.ollama_url.rstrip('/')}/api/tags", timeout=1.5) - if r.status_code == 200: - models = [m.get("name", "") for m in r.json().get("models", [])] - ollama_active = any("qwen" in m or settings.ollama_model in m for m in models) - except Exception: - ollama_active = False - - device = "Multi-Core CPU" - if torch is not None: - if hasattr(torch.backends, "mps") and torch.backends.mps.is_available(): - device = "Apple Silicon Metal (MPS)" - elif hasattr(torch, "cuda") and torch.cuda.is_available(): - device = "CUDA GPU" - - vlm_weights_loaded = (WEIGHTS_DIR / "RemoteCLIP-ViT-B-32.pt").exists() - if ollama_active: - active_model_name = f"Qwen2.5-3B (Local Ollama / {device})" - elif vlm_weights_loaded: - active_model_name = f"RemoteCLIP-ViT-B/32 Domain-Adapted Neural VLM ({device})" - else: - active_model_name = "No local model weights loaded (degraded)" - - aws_base = settings.stac_element84_url.rstrip("/").rsplit("/", 1)[0] - bhuvan_status = "configured" if bool(settings.bhuvan_api_key.strip()) else "not_configured" - mosdac_status = "configured" if bool(settings.mosdac_username.strip() and settings.mosdac_password.strip()) else "not_configured" - - live_data_sources = [ - {"name": "AWS Open Data Sentinel-2 L2A STAC", "status": cls._probe_reachability(aws_base), "resolution": "10m Multispectral"}, - {"name": "Microsoft Planetary Computer Sentinel-1 STAC", "status": cls._probe_reachability(settings.stac_planetary_url), "resolution": "C-SAR Microwave"}, - {"name": "ISRO Bhuvan (NRSC) Portal", "status": bhuvan_status, "resolution": "LULC Theme 1:50k"}, - {"name": "ISRO SAC MOSDAC Portal", "status": mosdac_status, "resolution": "INSAT-3DR SST / Meteorological"}, - {"name": "ESRI World Imagery Global Stream", "status": cls._probe_reachability("https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer?f=json"), "resolution": "Sub-meter Satellite Tiles"}, - ] - - return { - "active_mode": "local", - "active_model": active_model_name, - "isro_sac_compliant": True, - "disqualification_safeguard": ( - "Local neural inference: no closed foreign cloud LLM dependency." - if (ollama_active or vlm_weights_loaded) - else "Degraded: no local model currently loaded; rule-based DSP only." - ), - "hardware_acceleration": f"PyTorch + {device}", - "local_engines": { - "ollama_qwen2.5_3b": "online" if ollama_active else "offline", - "remoteclip_vit_b32_domain_adapter": ("weights_loaded" if vlm_weights_loaded else "weights_missing"), - }, - "live_data_sources": live_data_sources, - } \ No newline at end of file diff --git a/backend/app/agent/router.py b/backend/app/agent/router.py deleted file mode 100644 index 806ccdf..0000000 --- a/backend/app/agent/router.py +++ /dev/null @@ -1,333 +0,0 @@ -""" -SatQuery AI - Agentic Query Intent Router & Multi-Step Execution Planner -Target: SIH26167 (ISRO / Space Applications Centre) - -Advanced agentic dispatcher that parses spatial bounds, sensor compatibility, -atmospheric cloud cover constraints, temporal epochs, and tool-chaining sequences. -""" - -from dataclasses import dataclass, field -from enum import Enum -import re -from typing import Dict, Any, List, Optional, Tuple -from ..models.registry import MODEL_REGISTRY - - -class QueryIntent(str, Enum): - BITEMPORAL_CHANGE = "bitemporal_change" - CROSSMODAL_FUSION = "crossmodal_fusion" - SAR_VQA = "sar_vqa" - OPTICAL_VQA = "optical_vqa" - VISUAL_GROUNDING = "visual_grounding" - SCENE_CAPTIONING = "scene_captioning" - - -@dataclass -class AgentDispatchPlan: - intent: QueryIntent - modality: str - primary_model: str - grounding_tool: str - required_inputs: List[str] - output_type: str - target_entities: List[str] - temporal_interval: Optional[str] - cloud_piercing_required: bool - rationale: str - dag_steps: List[Dict[str, Any]] - - -class AgentRouter: - """Agentic decision engine routing natural-language prompts to models and tools.""" - - CHANGE_PATTERNS = [ - r"\b(change|changed|changes|difference|differencing|delta)\b", - r"\b(between|before\s+and\s+after|pre\s+and\s+post|t1\s+and\s+t2)\b", - r"\b(new\s+construction|demolition|expanded|expansion|growth|cleared)\b", - r"\b(temporal|multi-temporal|bi-temporal|bitemporal)\b", - r"\b(encroachment|sprawl|urbanization|deforestation)\b", - ] - - CROSSMODAL_PATTERNS = [ - r"\b(cloud|clouds|cloudy|overcast|haze|smoke|fog)\b", - r"\b(pierce|penetrate|penetration|see\s+through|beneath\s+the\s+cloud)\b", - r"\b(optical\s+and\s+sar|sar\s+and\s+optical|cross-modal|crossmodal|fusion)\b", - r"\b(all-weather|monsoon\s+obscuration|heavy\s+cover)\b", - ] - - SAR_PATTERNS = [ - r"\b(sar|radar|backscatter|dielectric|polarization|polarimetric)\b", - r"\b(vv|vh|c-band|l-band|x-band|synthetic\s+aperture)\b", - r"\b(roughness|double-bounce|corner\s+reflector|sentinel-1|risat)\b", - r"\b(metallic\s+target|ship\s+detection|water\s+specular)\b", - ] - - GROUNDING_PATTERNS = [ - r"\b(highlight|ground|locate|outline|draw|box|segment|mark|delineate|find\s+where)\b", - r"\b(bounding\s+box|polygon|spatial\s+mask|region\s+grounding)\b", - ] - - CAPTIONING_PATTERNS = [ - r"\b(describe|caption|summary|summarize|overview|land-cover\s+breakdown|scene\s+description)\b", - ] - - ENTITY_MAP = { - "runway": ["runway", "tarmac", "airstrip", "taxiway", "hangar"], - "launchpad": ["launchpad", "launch pad", "launch complex", "flp", "slp", "propellant tank", "umbilical"], - "building": ["building", "buildings", "facility", "footprint", "infrastructure", "campus", "structures"], - "maritime": ["vessel", "vessels", "ship", "ships", "tanker", "boat", "convoy", "port", "anchorage"], - "flood": ["flood", "flooding", "flooded", "inundation", "water body", "riverbank", "reservoir"], - "excavation": ["excavation", "trench", "subterranean", "shaft", "spoil pile", "perimeter fence"], - "vegetation": ["vegetation", "canopy", "forest", "agriculture", "crops", "paddy", "clearing"], - } - - @classmethod - def extract_entities(cls, query: str) -> List[str]: - q_lower = query.lower() - detected = [] - for category, terms in cls.ENTITY_MAP.items(): - if any(re.search(rf"\b{re.escape(t)}\b", q_lower) for t in terms): - detected.append(category) - return detected - - @classmethod - def extract_temporal(cls, query: str) -> Optional[str]: - q_lower = query.lower() - m = re.search(r"\b(between\s+[a-z0-9\s,]+and\s+[a-z0-9\s,]+)\b", q_lower) - if m: - return m.group(1).title() - if "t1" in q_lower and "t2" in q_lower: - return "Epoch T1 -> Epoch T2" - if "before" in q_lower and "after" in q_lower: - return "Pre-Event -> Post-Event" - return None - - @classmethod - def classify_intent(cls, query: str, context_hints: Optional[Dict[str, Any]] = None) -> QueryIntent: - """ - Classifies query into operational path based on linguistic markers and context. - """ - q_lower = query.lower() - hints = context_hints or {} - - # 1. Context overrides - if hints.get("has_bitemporal_pair"): - return QueryIntent.BITEMPORAL_CHANGE - if hints.get("has_sar_pair") and any(re.search(p, q_lower) for p in cls.CROSSMODAL_PATTERNS): - return QueryIntent.CROSSMODAL_FUSION - - # 2. Cross-modal / cloud piercing - if any(re.search(p, q_lower) for p in cls.CROSSMODAL_PATTERNS): - return QueryIntent.CROSSMODAL_FUSION - - # 3. Bi-temporal change detection - if any(re.search(p, q_lower) for p in cls.CHANGE_PATTERNS): - return QueryIntent.BITEMPORAL_CHANGE - - # 4. Pure SAR VQA - if any(re.search(p, q_lower) for p in cls.SAR_PATTERNS): - return QueryIntent.SAR_VQA - - # 5. Text-Guided Region Grounding - if any(re.search(p, q_lower) for p in cls.GROUNDING_PATTERNS): - return QueryIntent.VISUAL_GROUNDING - - # 6. Scene Captioning & Land-Cover Description - if any(re.search(p, q_lower) for p in cls.CAPTIONING_PATTERNS): - return QueryIntent.SCENE_CAPTIONING - - # 7. Default single-image optical VQA - return QueryIntent.OPTICAL_VQA - - @classmethod - def plan_execution( - cls, - query: str, - bbox: Optional[List[float]] = None, - context_data: Optional[Dict[str, Any]] = None, - ) -> AgentDispatchPlan: - """ - Synthesizes a structured agentic execution plan with sensor dispatch and DAG steps. - """ - ctx = context_data or {} - intent = cls.classify_intent(query, ctx) - entities = cls.extract_entities(query) - temporal = cls.extract_temporal(query) - cloud_required = intent == QueryIntent.CROSSMODAL_FUSION or any( - re.search(p, query.lower()) for p in cls.CROSSMODAL_PATTERNS - ) - - # Detect secondary intents for compound queries - secondary_intents: List[QueryIntent] = [] - q_lower = query.lower() - if intent != QueryIntent.VISUAL_GROUNDING and any(re.search(p, q_lower) for p in cls.GROUNDING_PATTERNS): - secondary_intents.append(QueryIntent.VISUAL_GROUNDING) - if intent != QueryIntent.SCENE_CAPTIONING and any(re.search(p, q_lower) for p in cls.CAPTIONING_PATTERNS): - secondary_intents.append(QueryIntent.SCENE_CAPTIONING) - if intent != QueryIntent.CROSSMODAL_FUSION and any(re.search(p, q_lower) for p in cls.CROSSMODAL_PATTERNS): - secondary_intents.append(QueryIntent.CROSSMODAL_FUSION) - - if intent == QueryIntent.BITEMPORAL_CHANGE: - modality = "bitemporal" - reg = MODEL_REGISTRY["bitemporal_change"] - primary_model = reg["canonical_name"] - grounding_tool = reg["grounding_tool"] - required_inputs = ["optical_msi_t1", "optical_msi_t2"] - output_type = "bitemporal_change_mask_and_description" - rationale = ( - "Query requests multi-temporal analysis or structural differential. " - "Co-registering T1 and T2 epochs to compute radiometric shift and Otsu cluster boundaries." - ) - elif intent == QueryIntent.CROSSMODAL_FUSION: - modality = "cross_modal" - reg = MODEL_REGISTRY["crossmodal_fusion"] - primary_model = reg["canonical_name"] - grounding_tool = reg["grounding_tool"] - required_inputs = ["optical_msi", "sar_grd_dual_pol"] - output_type = "cloud_pierced_fused_evidence" - rationale = ( - "Query identifies cloud obscuration or requests cross-modal penetration. " - "Dispatching Sentinel-1 C-SAR dual-pol (VV/VH) radar to pierce obscuration and isolate dielectric scatterers." - ) - elif intent == QueryIntent.SAR_VQA: - modality = "cross_modal" - reg = MODEL_REGISTRY["sar_vqa"] - primary_model = reg["canonical_name"] - grounding_tool = reg["grounding_tool"] - required_inputs = ["sar_grd_dual_pol"] - output_type = "radar_structural_vqa_response" - rationale = ( - "Query interrogates radar backscatter, surface dielectric properties, or all-weather targets. " - "Executing polarimetric microwave analysis." - ) - elif intent == QueryIntent.VISUAL_GROUNDING: - modality = "single_image" - reg = MODEL_REGISTRY.get("visual_grounding", MODEL_REGISTRY["optical_vqa"]) - primary_model = reg["canonical_name"] - grounding_tool = reg["grounding_tool"] - required_inputs = ["optical_msi"] - output_type = "text_guided_bounding_boxes_and_polygons" - rationale = ( - "Query explicitly requests spatial localization or feature grounding. " - "Extracting cross-attention heatmaps and constructing Shapely topological boundary polygons." - ) - elif intent == QueryIntent.SCENE_CAPTIONING: - modality = "single_image" - reg = MODEL_REGISTRY.get("scene_captioning", MODEL_REGISTRY["optical_vqa"]) - primary_model = reg["canonical_name"] - grounding_tool = reg["grounding_tool"] - required_inputs = ["optical_msi"] - output_type = "multispectral_scene_caption_and_landcover_breakdown" - rationale = ( - "Query requests comprehensive scene description or land-cover breakdown. " - "Synthesizing generative visual-text description with spectral index statistics." - ) - else: - modality = "single_image" - reg = MODEL_REGISTRY["optical_vqa"] - primary_model = reg["canonical_name"] - grounding_tool = reg["grounding_tool"] - required_inputs = ["optical_msi"] - output_type = "single_scene_vqa_and_grounded_polygons" - rationale = ( - "Query requests optical land-cover identification or spatial feature grounding. " - "Running vision-language cross-attention over normalized multispectral visual tokens." - ) - - if secondary_intents: - sec_names = ", ".join(s.value.upper() for s in secondary_intents) - rationale += f" Multi-intent decomposition active: chained secondary targets [{sec_names}] into execution pipeline." - - # Build dynamic DAG steps - dag_steps = [ - { - "id": "node-1-intent", - "label": "Agentic Query & Entity Classifier", - "type": "intent_parser", - "status": "completed", - "modelUsed": "AgentRouter (Semantic Remote Sensing Dispatcher)", - "latencyMs": None, # Measured dynamically at execution time by EvidenceBuilder - "details": f"Classified primary intent as \"{intent.value.upper()}\". Secondary targets: {[s.value for s in secondary_intents] or 'None'}. Target categories: {entities or ['general_scene']}.", - "outputPayload": f"Intent: {intent.value} | Entities: {entities} | Temporal: {temporal or 'None'}", - }, - { - "id": "node-2-dispatcher", - "label": "Sensor & Atmospheric Band Dispatcher", - "type": "band_dispatcher", - "status": "pending", - "modelUsed": "AgentRouter.plan_execution (Spectral Registry)", - "latencyMs": None, # Measured dynamically at execution time by EvidenceBuilder - "details": f"Allocated required input bands: {required_inputs}. Cloud piercing: {cloud_required}.", - "outputPayload": f"Inputs: {', '.join(required_inputs)} | Modality: {modality}", - }, - { - "id": "node-3-specialist", - "label": "Remote-Sensing Specialist Inference Head", - "type": "specialist_model", - "status": "pending", - "modelUsed": primary_model, - "latencyMs": None, # Measured dynamically at execution time by EvidenceBuilder - "details": f"Executed inference head on PyTorch MPS/CPU tensor pipeline. Evaluated features across bounds {bbox}.", - "outputPayload": f"Model: {primary_model} | Output: {output_type}", - }, - { - "id": "node-4-vectorizer", - "label": "Spatial Mask & Polygon Vectorizer", - "type": "spatial_vectorizer", - "status": "pending", - "modelUsed": grounding_tool, - "latencyMs": None, # Measured dynamically at execution time by EvidenceBuilder - "details": "Extracted georeferenced non-convex boundary contours and projected to EPSG:4326.", - "outputPayload": "Format: GeoJSON FeatureCollection (WGS84)", - }, - ] - - if QueryIntent.VISUAL_GROUNDING in secondary_intents or intent == QueryIntent.VISUAL_GROUNDING: - dag_steps.append({ - "id": "node-5-bounding-grounding", - "label": "Text-Guided Bounding Box & Polygon Grounding", - "type": "visual_grounding", - "status": "pending", - "modelUsed": "RemoteCLIP + Shapely Polygon Vectorizer", - "latencyMs": None, - "details": "Extracted precise spatial bounding boxes and non-convex boundary contours for query entities.", - "outputPayload": "Shapely GeoJSON Bounding Polygons", - }) - - if intent == QueryIntent.CROSSMODAL_FUSION: - dag_steps.insert(2, { - "id": "node-2b-sar-filter", - "label": "SAR Speckle Suppression & Dual-Pol Isolation", - "type": "sar_filter", - "status": "pending", - "modelUsed": "5x5 Adaptive Lee Speckle Filter + VV/VH Ratio", - "latencyMs": None, # Measured dynamically at execution time by EvidenceBuilder - "details": "Suppressed multiplicative speckle noise while preserving high-dielectric hard targets.", - "outputPayload": "Filtered Radar Tensor (dB)", - }) - - return AgentDispatchPlan( - intent=intent, - modality=modality, - primary_model=primary_model, - grounding_tool=grounding_tool, - required_inputs=required_inputs, - output_type=output_type, - target_entities=entities, - temporal_interval=temporal, - cloud_piercing_required=cloud_required, - rationale=rationale, - dag_steps=dag_steps, - ) - - @classmethod - def get_execution_plan(cls, intent: QueryIntent) -> Dict[str, Any]: - """Backwards-compatible wrapper returning dictionary representation of plan.""" - plan = cls.plan_execution("", context_data={"intent": intent}) - return { - "intent": intent.value, - "primary_model": plan.primary_model, - "grounding_tool": plan.grounding_tool, - "required_inputs": plan.required_inputs, - "output_type": plan.output_type, - } diff --git a/backend/app/agent/ui_action_planner.py b/backend/app/agent/ui_action_planner.py deleted file mode 100644 index 3b93fb9..0000000 --- a/backend/app/agent/ui_action_planner.py +++ /dev/null @@ -1,473 +0,0 @@ -""" -SatQuery AI - Grounded UI-Action Planner -Target: SIH26167 (ISRO / Space Applications Centre) - -Turns the deterministic result of a query into a typed, closed-schema list of UI -actions ("UIAction") that the frontend may execute against real stores and the -real MapLibre map. This module never invents state in prose: every action it -emits is grounded in data that provably exists in the SAME response. - -Grounding contract (enforced by `validate`): - - * fly_to_sector -> sector id present in SECTOR_REGISTRY - * fly_to_bbox -> bounding box explicitly supplied with the request - * set_modality -> a modality in the shared modality union - * set_sensor_band -> a band in the shared SensorBand union - * toggle_layer -> a layer id in the frontend's DEFAULT_LAYERS - * set_layer_opacity -> a layer id in DEFAULT_LAYERS - * toggle_projection -> 'globe' | 'mercator' - * toggle_basemap -> 'dark' | 'satellite' - * set_swipe_curtain -> boolean only, emitted only when a real pair exists - * open_panel -> a deck tab in the shared panel union - * open_studio -> a route in the shared StudioRoute union - * highlight_feature -> a feature id present in THIS response's GeoJSON - * toggle_live_stream -> emitted only when the live STAC stream is online here - * run_benchmark -> emitted only when a real benchmark id is supplied - -If a signal is absent the action is NOT emitted. `ui_actions_source` reports how -the list was produced ("rule_based" today; "llm_planned" is reserved and only -used when an LLM-produced list has passed the same `validate` gate). -""" - -import math -from typing import Any, Dict, Iterable, List, Optional, Tuple - -from ..engine.sector_assets import SECTOR_REGISTRY - -# --- Closed schema ----------------------------------------------------------------- -UI_ACTION_TYPES = frozenset( - { - "fly_to_sector", - "fly_to_bbox", - "set_modality", - "set_sensor_band", - "set_swipe_curtain", - "toggle_layer", - "set_layer_opacity", - "toggle_projection", - "toggle_basemap", - "open_panel", - "open_studio", - "highlight_feature", - "toggle_live_stream", - "run_benchmark", - } -) - -# NOTE: no `set_time_range`. The dashboard's range control is preset-based -# (24h/7d/30d/1y/all), so an explicit T1->T2 acquisition pair has no real handler. -# The genuine dates stay visible in the evidence text/telemetry instead of being -# rounded to a preset and reported as if the exact range had been applied. - -KNOWN_MODALITIES = frozenset({"single_image", "cross_modal", "bitemporal"}) -KNOWN_SENSOR_BANDS = frozenset({"RGB", "NIR", "SAR"}) -KNOWN_PANELS = frozenset({"evidence", "dag", "telemetry"}) -KNOWN_PROJECTIONS = frozenset({"globe", "mercator"}) -KNOWN_BASEMAPS = frozenset({"dark", "satellite"}) -KNOWN_STUDIOS = frozenset( - {"dashboard", "bitemporal", "crossmodal", "grounding", "benchmarks", "ingestion", "audit"} -) -# Mirrors frontend DEFAULT_LAYERS (src/config/tacticalData.ts). -KNOWN_LAYER_IDS = frozenset( - { - "intel-hotspots", - "sentinel-optical", - "sentinel-sar", - "isro-ground-stations", - "flood-inundation", - "bitemporal-structural-change", - } -) - -# Confidence-bearing keys used to pick the most defensible highlight target. -_CONFIDENCE_KEYS = ("confidence", "probability", "score", "changeMagnitude", "areaKm2") - - -def _is_finite_number(value: Any) -> bool: - return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(float(value)) - - -class UIActionPlanner: - """Deterministic planner for grounded, executable UI actions.""" - - # ------------------------------------------------------------------ helpers - @staticmethod - def _action(action_type: str, params: Dict[str, Any], reason: str) -> Dict[str, Any]: - return {"type": action_type, "params": params, "reason": reason, "status": "pending"} - - @staticmethod - def valid_bbox(bbox: Any) -> bool: - """A bbox is usable only if it is 4 finite numbers forming a real extent.""" - if not isinstance(bbox, (list, tuple)) or len(bbox) != 4: - return False - if not all(_is_finite_number(v) for v in bbox): - return False - min_lon, min_lat, max_lon, max_lat = (float(v) for v in bbox) - if not (-180.0 <= min_lon <= 180.0 and -180.0 <= max_lon <= 180.0): - return False - if not (-90.0 <= min_lat <= 90.0 and -90.0 <= max_lat <= 90.0): - return False - return min_lon < max_lon and min_lat < max_lat - - @staticmethod - def addressable_feature_ids(geojson: Optional[Dict[str, Any]]) -> List[str]: - """Every GeoJSON feature id in this response that the UI can address.""" - ids: List[str] = [] - if not isinstance(geojson, dict): - return ids - for feat in geojson.get("features") or []: - if not isinstance(feat, dict): - continue - fid = feat.get("id") - if isinstance(fid, str) and fid.strip(): - ids.append(fid) - return ids - - @classmethod - def _best_highlight_id(cls, geojson: Optional[Dict[str, Any]]) -> Optional[str]: - """Highest-confidence addressable feature, else the first addressable one.""" - if not isinstance(geojson, dict): - return None - best_id: Optional[str] = None - best_score = float("-inf") - for feat in geojson.get("features") or []: - if not isinstance(feat, dict): - continue - fid = feat.get("id") - if not (isinstance(fid, str) and fid.strip()): - continue - props = feat.get("properties") or {} - score = float("-inf") - if isinstance(props, dict): - for key in _CONFIDENCE_KEYS: - val = props.get(key) - if _is_finite_number(val): - score = float(val) - break - if best_id is None or score > best_score: - best_id, best_score = fid, score - return best_id - - # ----------------------------------------------------------------- validate - @classmethod - def validate( - cls, - action: Any, - *, - known_sector_ids: Optional[Iterable[str]] = None, - known_feature_ids: Optional[Iterable[str]] = None, - known_layer_ids: Optional[Iterable[str]] = None, - known_benchmark_ids: Optional[Iterable[str]] = None, - ) -> Tuple[bool, str]: - """ - Closed-schema + grounding gate. Returns (ok, reason). Any action that is - not provably executable must be dropped by the caller rather than shown - as if it had happened. - """ - if not isinstance(action, dict): - return False, "action is not an object" - - action_type = action.get("type") - if action_type not in UI_ACTION_TYPES: - return False, f"unknown action type {action_type!r}" - - params = action.get("params") - if not isinstance(params, dict): - return False, "missing params object" - - sectors = set(known_sector_ids if known_sector_ids is not None else SECTOR_REGISTRY.keys()) - features = set(known_feature_ids or []) - layers = set(known_layer_ids if known_layer_ids is not None else KNOWN_LAYER_IDS) - benchmarks = set(known_benchmark_ids or []) - - if action_type == "fly_to_sector": - sector_id = params.get("sector_id") - if not isinstance(sector_id, str) or sector_id not in sectors: - return False, f"sector_id {sector_id!r} is not a real sector" - if not (_is_finite_number(params.get("lat")) and _is_finite_number(params.get("lon"))): - return False, "fly_to_sector requires finite lat/lon" - return True, "grounded in SECTOR_REGISTRY" - - if action_type == "fly_to_bbox": - if not cls.valid_bbox(params.get("bbox")): - return False, "bbox is not a valid extent" - return True, "valid extent" - - if action_type == "set_modality": - if params.get("modality") not in KNOWN_MODALITIES: - return False, f"unknown modality {params.get('modality')!r}" - return True, "known modality" - - if action_type == "set_sensor_band": - if params.get("band") not in KNOWN_SENSOR_BANDS: - return False, f"unknown sensor band {params.get('band')!r}" - return True, "known sensor band" - - if action_type == "set_swipe_curtain": - if not isinstance(params.get("active"), bool): - return False, "set_swipe_curtain requires boolean active" - return True, "boolean state" - - if action_type in {"toggle_layer", "set_layer_opacity"}: - layer_id = params.get("layer_id") - if layer_id not in layers: - return False, f"layer_id {layer_id!r} does not exist in DEFAULT_LAYERS" - if action_type == "toggle_layer": - if not isinstance(params.get("visible"), bool): - return False, "toggle_layer requires boolean visible" - return True, "known layer id" - opacity = params.get("opacity") - if not _is_finite_number(opacity) or not (0.0 <= float(opacity) <= 100.0): - return False, "opacity must be within 0..100" - return True, "known layer id" - - if action_type == "toggle_projection": - if params.get("mode") not in KNOWN_PROJECTIONS: - return False, f"unknown projection {params.get('mode')!r}" - return True, "known projection" - - if action_type == "toggle_basemap": - if params.get("mode") not in KNOWN_BASEMAPS: - return False, f"unknown basemap {params.get('mode')!r}" - return True, "known basemap" - - if action_type == "open_panel": - if params.get("tab") not in KNOWN_PANELS: - return False, f"unknown panel tab {params.get('tab')!r}" - return True, "known deck tab" - - if action_type == "open_studio": - if params.get("studio") not in KNOWN_STUDIOS: - return False, f"unknown studio route {params.get('studio')!r}" - return True, "known studio route" - - if action_type == "highlight_feature": - feature_id = params.get("feature_id") - if not isinstance(feature_id, str) or not feature_id.strip(): - return False, "missing feature_id" - if feature_id not in features: - return False, f"feature_id {feature_id!r} is absent from this response" - return True, "present in this response GeoJSON" - - if action_type == "toggle_live_stream": - if not isinstance(params.get("enabled"), bool): - return False, "toggle_live_stream requires boolean enabled" - return True, "boolean state" - - if action_type == "run_benchmark": - benchmark_id = params.get("benchmark_id") - if not isinstance(benchmark_id, str) or benchmark_id not in benchmarks: - return False, f"benchmark_id {benchmark_id!r} is not in the real catalog" - return True, "known benchmark id" - - return False, "unhandled action type" - - # --------------------------------------------------------------------- plan - @classmethod - def plan( - cls, - *, - query: str, - intent: Any, - modality: Optional[str], - profile: Any, - requested_bbox: Optional[List[float]], - geojson: Optional[Dict[str, Any]], - live_stream: Optional[Dict[str, Any]] = None, - benchmark_id: Optional[str] = None, - benchmark_ids: Optional[Iterable[str]] = None, - ) -> Tuple[List[Dict[str, Any]], str]: - """ - Produce a deterministic, grounded action list for one query result. - - Returns (actions, source). `source` is "rule_based" for this planner; an - LLM-proposed list must run through `validate` and be reported as - "llm_planned" only when it passed. - """ - intent_value = str(getattr(intent, "value", intent)) - actions: List[Dict[str, Any]] = [] - - known_sector_ids = set(SECTOR_REGISTRY.keys()) - feature_ids = cls.addressable_feature_ids(geojson) - - # 1) Camera: an explicit request bbox is the most specific real input, so - # it wins over the resolved sector centroid. - flew = False - if cls.valid_bbox(requested_bbox): - actions.append( - cls._action( - "fly_to_bbox", - {"bbox": [float(v) for v in requested_bbox]}, - "Request supplied an explicit bounding box; frame that authored extent.", - ) - ) - flew = True - - if not flew and profile is not None and getattr(profile, "id", None) in known_sector_ids: - lat, lon = getattr(profile, "lat", None), getattr(profile, "lon", None) - if _is_finite_number(lat) and _is_finite_number(lon): - actions.append( - cls._action( - "fly_to_sector", - { - "sector_id": profile.id, - "name": getattr(profile, "name", profile.id), - "lat": float(lat), - "lon": float(lon), - }, - f"Query resolved to real sector '{profile.id}' in SECTOR_REGISTRY.", - ) - ) - - # 2) Modality the pipeline actually ran under. - if modality in KNOWN_MODALITIES: - actions.append( - cls._action( - "set_modality", - {"modality": modality}, - f"Pipeline executed in '{modality}' modality; sync the UI switch.", - ) - ) - - # 3) Intent-specific view state, each grounded in the executed pipeline. - if intent_value == "bitemporal_change": - actions.append( - cls._action( - "set_swipe_curtain", - {"active": True}, - "Bi-temporal differencing ran over a real T1/T2 pair; expose the comparison curtain.", - ) - ) - actions.append( - cls._action( - "toggle_layer", - {"layer_id": "bitemporal-structural-change", "visible": True}, - "Change polygons exist for this response; show the change layer.", - ) - ) - actions.append( - cls._action( - "open_panel", - {"tab": "evidence"}, - "Surface the change evidence that was just computed.", - ) - ) - - elif intent_value == "crossmodal_fusion": - actions.append( - cls._action( - "set_sensor_band", - {"band": "SAR"}, - "SAR fusion ran; switch the sensor filter to the radar band that was processed.", - ) - ) - actions.append( - cls._action( - "toggle_layer", - {"layer_id": "sentinel-sar", "visible": True}, - "Dual-pol SAR backscatter was processed; show the SAR layer.", - ) - ) - actions.append( - cls._action( - "open_panel", - {"tab": "telemetry"}, - "Expose sensor/band telemetry for the fusion that ran.", - ) - ) - - elif intent_value in ("optical_vqa", "scene_captioning"): - actions.append( - cls._action( - "set_sensor_band", - {"band": "RGB"}, - "Optical multispectral inference ran; switch to the visible band composite.", - ) - ) - actions.append( - cls._action( - "toggle_layer", - {"layer_id": "sentinel-optical", "visible": True}, - "Optical scene was classified; show the optical layer.", - ) - ) - actions.append( - cls._action( - "open_panel", - {"tab": "evidence"}, - "Surface the classification evidence that was just computed.", - ) - ) - - elif intent_value == "visual_grounding": - actions.append( - cls._action( - "toggle_layer", - {"layer_id": "intel-hotspots", "visible": True}, - "Grounding targets are strategic sites; show the tactical vector layer.", - ) - ) - actions.append( - cls._action( - "open_panel", - {"tab": "evidence"}, - "Surface the grounded polygons that were just vectorized.", - ) - ) - - else: # sar_vqa / anything else that still produced evidence - if intent_value == "sar_vqa": - actions.append( - cls._action( - "set_sensor_band", - {"band": "SAR"}, - "SAR VQA ran against radar amplitude; switch to the radar band.", - ) - ) - actions.append( - cls._action( - "open_panel", - {"tab": "evidence"}, - "Surface the evidence produced for this query.", - ) - ) - - # 4) Highlight only a feature id that exists in THIS response. - highlight_id = cls._best_highlight_id(geojson) - if highlight_id and intent_value != "scene_captioning": - actions.append( - cls._action( - "highlight_feature", - {"feature_id": highlight_id}, - f"'{highlight_id}' is present in this response's GeoJSON; highlight it on the map.", - ) - ) - - # 5) Live stream: only when the stream is genuinely online for this response. - if isinstance(live_stream, dict) and live_stream.get("status") == "online": - actions.append( - cls._action( - "toggle_live_stream", - {"enabled": True}, - "Live STAC stream is online for this query; enable the live layer.", - ) - ) - - # 6) Benchmarks: only when a real catalog id was supplied. - if benchmark_id and benchmark_id in set(benchmark_ids or []): - actions.append( - cls._action( - "run_benchmark", - {"benchmark_id": benchmark_id}, - f"Benchmark '{benchmark_id}' exists in the real catalog.", - ) - ) - - # Final gate: nothing leaves this planner unvalidated. - validated: List[Dict[str, Any]] = [] - for action in actions: - ok, _reason = cls.validate(action, known_feature_ids=feature_ids) - if ok: - validated.append(action) - - return validated, "rule_based" diff --git a/backend/app/api/routes_benchmark.py b/backend/app/api/routes_benchmark.py deleted file mode 100644 index aad906d..0000000 --- a/backend/app/api/routes_benchmark.py +++ /dev/null @@ -1,227 +0,0 @@ -""" -SatQuery AI - Official Benchmark Suite API Router -Evaluates multimodal remote sensing models against VRSBench, CDVQA, and BigEarthNet. -""" - -from fastapi import APIRouter, HTTPException -from pydantic import BaseModel, Field -from typing import Optional, List, Dict, Any -import json -import time -import re -from pathlib import Path -from ..config import settings -from ..agent.router import AgentRouter -from ..agent.evidence_builder import EvidenceBuilder - -router = APIRouter(prefix="/api/benchmark", tags=["benchmark"]) - - -class BenchmarkEvaluateRequest(BaseModel): - query: str - ground_truth: str - modality: Optional[str] = "cross_modal" - sector_id: Optional[str] = None - bbox: Optional[List[float]] = None - - -@router.get("/catalog") -def get_benchmark_catalog(): - """Returns curated challenge items from real VRSBench and CDVQA benchmarks.""" - vrsbench_file = settings.benchmark_dir / "vrsbench" / "VRSBench_EVAL_vqa.json" - cdvqa_sample = settings.sample_dir / "vqa" / "sample_cdvqa_change_qa.json" - - items = [] - - # 1. Load VRSBench items - if vrsbench_file.exists(): - try: - with open(vrsbench_file, "r") as f: - data = json.load(f) - # Take sample of first 12 varied questions - for i, row in enumerate(data[:12]): - items.append({ - "id": f"vrsbench-{row.get('question_id', i)}", - "dataset": "VRSBench", - "category": row.get("type", "object attribute"), - "question": row.get("question"), - "ground_truth": row.get("ground_truth"), - "image_ref": row.get("image_id"), - "suggested_modality": "single_image", - }) - except Exception as e: - print(f"[!] Error reading VRSBench: {e}") - - # 2. Load CDVQA items - if cdvqa_sample.exists(): - try: - with open(cdvqa_sample, "r") as f: - cd_data = json.load(f) - questions = cd_data.get("questions", [])[:8] - answers = {a["question_id"]: a["answer"] for a in cd_data.get("answers", [])} - for q in questions: - items.append({ - "id": f"cdvqa-{q.get('id')}", - "dataset": "CDVQA (Bi-Temporal Change)", - "category": q.get("type", "change_or_not"), - "question": q.get("question"), - "ground_truth": answers.get(q.get("id"), "yes"), - "suggested_modality": "bitemporal", - }) - except Exception as e: - print(f"[!] Error reading CDVQA: {e}") - - # 3. Load BigEarthNet.txt items - ben_file = settings.benchmark_dir / "bigearthnet_txt" / "bigearthnet_eval_50.json" - if ben_file.exists(): - try: - with open(ben_file, "r") as f: - ben_data = json.load(f) - for item in ben_data[:15]: - items.append(item) - except Exception as e: - print(f"[!] Error reading BigEarthNet: {e}") - - return { - "count": len(items), - "challenges": items - } - - -def compute_token_overlap(pred: str, target: str) -> Dict[str, float]: - """Computes precision, recall, F1, and exact match token overlap.""" - clean_p = set(re.findall(r"\w+", pred.lower())) - clean_t = set(re.findall(r"\w+", target.lower())) - - if not clean_p or not clean_t: - return {"precision": 0.0, "recall": 0.0, "f1": 0.0, "exact_match": False} - - overlap = clean_p.intersection(clean_t) - p = len(overlap) / len(clean_p) - r = len(overlap) / len(clean_t) - f1 = (2 * p * r) / (p + r) if (p + r) > 0 else 0.0 - - # Direct match or target contained in prediction - exact = target.lower().strip() in pred.lower().strip() - - return { - "precision": round(p, 3), - "recall": round(r, 3), - "f1": round(f1, 3), - "exact_match": exact - } - - -@router.post("/evaluate") -def evaluate_benchmark(req: BenchmarkEvaluateRequest): - """ - Executes a real benchmark evaluation: - 1. Runs the query through the vision-language evidence synthesis pipeline. - 2. Compares the prediction against ground truth. - 3. Calculates metrics (precision, recall, F1, latency, confidence). - """ - start_time = time.perf_counter() - - hints = {} - if req.modality == "bitemporal": - hints["has_bitemporal_pair"] = True - elif req.modality == "cross_modal": - hints["has_sar_pair"] = True - - intent = AgentRouter.classify_intent(req.query, hints) - - ctx = { - "modality": req.modality, - "sector_id": req.sector_id, - } - - # Check if a specific BigEarthNet chip exists for this benchmark item - chip_path = None - chips_dir = settings.benchmark_dir / "bigearthnet_txt" / "chips" - - # Try finding patch_id from BigEarthNet catalog if available - ben_file = settings.benchmark_dir / "bigearthnet_txt" / "bigearthnet_eval_50.json" - if ben_file.exists(): - try: - with open(ben_file, "r") as f: - ben_data = json.load(f) - for item in ben_data: - if item.get("question", "").strip().lower() == req.query.strip().lower(): - p_id = item.get("patch_id") - cand = chips_dir / f"{p_id}.jpg" - if cand.exists(): - chip_path = cand - break - except Exception: - pass - - if chip_path and chip_path.exists(): - from PIL import Image - from ..models.remote_clip import RemoteCLIPModel - chip_img = Image.open(chip_path).convert("RGB") - clip_res = RemoteCLIPModel.query(chip_img, req.query) - result = { - "answer": clip_res["answer"], - "confidence": clip_res["confidence"], - "geojson": clip_res["geojson"], - "telemetry": { - "models_executed": ["RemoteCLIP-ViT-B/32 (PyTorch MPS/CPU)", f"BigEarthNet Patch Evaluator [{chip_path.name}]"] - } - } - else: - result = EvidenceBuilder.build_evidence( - query=req.query, - intent=intent, - bbox=req.bbox, - context_data=ctx - ) - - elapsed_ms = round((time.perf_counter() - start_time) * 1000, 1) - - # Standard Academic VQA Task Evaluation Protocol: - # 1. Binary existence / change questions: predict "yes" / "no" based on detected features - # 2. Quantity counting questions: predict integer cluster count - # 3. Categorical land-cover / attribute questions: predict top-1 domain class from contrastive embeddings - gt_clean = req.ground_truth.strip().lower() - features_count = len(result.get("geojson", {}).get("features", [])) - - if gt_clean in ("yes", "no"): - if intent == AgentRouter.classify_intent("change", {}): - has_change = (result.get("findings", {}).get("surfaceAreaModifiedKm2") or 0.0) > 0.001 - vqa_pred = "yes" if (has_change and features_count > 0) else "no" - else: - vqa_pred = "yes" if features_count > 0 else "no" - elif gt_clean.isdigit(): - vqa_pred = str(features_count) - else: - # Categorical / land-cover classification from neural backbone - vqa_pred = result.get("findings", {}).get("changeClass") or result.get("answer", "").split(".")[0] - - # Evaluate prediction against ground truth - metrics_vqa = compute_token_overlap(vqa_pred, req.ground_truth) - metrics_narrative = compute_token_overlap(result["answer"], req.ground_truth) - - # Use higher fidelity metric between concise VQA token match and narrative overlap - if metrics_vqa["exact_match"]: - metrics = metrics_vqa - elif metrics_narrative["f1"] > metrics_vqa["f1"]: - metrics = metrics_narrative - else: - metrics = metrics_vqa - - score = 100.0 if metrics["exact_match"] else round(metrics["f1"] * 100, 1) - - return { - "status": "success", - "query": req.query, - "ground_truth": req.ground_truth, - "generated_answer": f"[{vqa_pred.upper()}] {result['answer']}", - "vqa_prediction": vqa_pred, - "confidence": result["confidence"], - "score_percent": score, - "metrics": metrics, - "latency_ms": elapsed_ms, - "models_executed": result["telemetry"]["models_executed"], - "geojson": result["geojson"], - "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), - } diff --git a/backend/app/api/routes_query.py b/backend/app/api/routes_query.py deleted file mode 100644 index 1bfd523..0000000 --- a/backend/app/api/routes_query.py +++ /dev/null @@ -1,90 +0,0 @@ -""" -SatQuery AI - Main Query & VQA Execution Router -Receives natural language prompts, dispatches to specialist pipelines, and returns grounded evidence. -""" - -from fastapi import APIRouter -from pydantic import BaseModel, Field -from typing import Optional, List, Dict, Any -from ..agent.router import AgentRouter -from ..agent.evidence_builder import EvidenceBuilder -from ..agent.realtime_vlm_agent import RealTimeVLMAgent - -router = APIRouter(prefix="/api", tags=["query"]) - - -class QueryRequest(BaseModel): - query: str = Field(..., min_length=1, description="Natural language question or instruction") - bbox: Optional[List[float]] = Field(default=None, description="[min_lon, min_lat, max_lon, max_lat]") - modality: Optional[str] = Field(default="cross_modal", description="single_image, cross_modal, or bitemporal") - sector_id: Optional[str] = Field(default=None, description="Active sector or pin ID") - uploaded_file: Optional[str] = Field(default=None, description="Active uploaded raster filename") - confidence_threshold: Optional[float] = Field(default=0.75, description="Confidence threshold slider value") - iou_threshold: Optional[float] = Field(default=0.50, description="IoU filter threshold") - radar_threshold: Optional[float] = Field(default=0.65, description="SAR backscatter filter threshold") - context_hints: Optional[Dict[str, Any]] = Field(default_factory=dict, description="Context flags like pair presence") - - -class QueryResponse(BaseModel): - query: str - modality: str - intent: str - answer: str - confidence: float - latency_ms: float - audit_hash: Optional[str] = None - benchmarkSource: Optional[str] = None - geojson: Dict[str, Any] - telemetry: Dict[str, Any] - dagNodes: List[Dict[str, Any]] - findings: Optional[Dict[str, Any]] = None - live_satellite_stream: Optional[Dict[str, Any]] = None - ai_engine_active: Optional[str] = None - # Grounded UI actions the frontend may execute, + how the list was produced. - # Declared explicitly: unknown keys on a pydantic response_model are dropped. - ui_actions: List[Dict[str, Any]] = [] - ui_actions_source: Optional[str] = None - - -@router.post("/query", response_model=QueryResponse) -def process_query(req: QueryRequest): - """ - Main Agentic Assistant endpoint: - 1. Classifies query intent. - 2. Selects specialist model execution path. - 3. Returns natural language answer + GeoJSON polygons + audit telemetry + DAG nodes + findings. - """ - hints = req.context_hints or {} - if req.modality == "bitemporal": - hints["has_bitemporal_pair"] = True - elif req.modality == "cross_modal": - hints["has_sar_pair"] = True - - intent = AgentRouter.classify_intent(req.query, hints) - - ctx = dict(hints) - ctx["modality"] = req.modality - ctx["sector_id"] = req.sector_id - ctx["uploaded_file"] = req.uploaded_file - if req.confidence_threshold is not None: - ctx["confidence_threshold"] = req.confidence_threshold - if req.iou_threshold is not None: - ctx["iou_threshold"] = req.iou_threshold - if req.radar_threshold is not None: - ctx["radar_threshold"] = req.radar_threshold - - evidence = EvidenceBuilder.build_evidence( - query=req.query, - intent=intent, - bbox=req.bbox, - context_data=ctx - ) - return evidence - - -@router.get("/settings/ai-status") -def get_ai_status(): - """Returns the live AI provider status and active satellite data streams.""" - return RealTimeVLMAgent.get_ai_status() - - diff --git a/backend/app/api/routes_samples.py b/backend/app/api/routes_samples.py deleted file mode 100644 index b84e1a1..0000000 --- a/backend/app/api/routes_samples.py +++ /dev/null @@ -1,161 +0,0 @@ -""" -SatQuery AI - Samples & Pre-Calibrated GeoTIFF API Router -Target: SIH26167 (ISRO Space Applications Centre) §3 & §7 -""" - -from fastapi import APIRouter, HTTPException -from fastapi.responses import FileResponse -import json -import logging -from pathlib import Path -from typing import Dict, Any, List -from ..config import settings -from ..engine.geotiff_parser import GeoTIFFEngine - -router = APIRouter(prefix="/api/samples", tags=["samples"]) - -logger = logging.getLogger(__name__) - - -def safe_join(base_dir: Path, filename: str) -> Path: - """Safely join base directory with filename, preventing path traversal.""" - resolved = (base_dir / Path(filename).name).resolve() - if not resolved.is_relative_to(base_dir.resolve()): - raise HTTPException(status_code=400, detail="Invalid filename") - return resolved - - -@router.get("/manifest") -def get_sample_manifest(): - """Returns local sample dataset manifest and asset inventory.""" - manifest_path = settings.sample_dir / "sample_manifest.json" - if not manifest_path.exists(): - raise HTTPException(status_code=404, detail="Sample manifest not initialized.") - - with open(manifest_path, "r") as f: - data = json.load(f) - - files_optical = [f.name for f in (settings.sample_dir / "optical").glob("*") if f.is_file()] - files_sar = [f.name for f in (settings.sample_dir / "sar").glob("*") if f.is_file()] - files_bitemporal = [f.name for f in (settings.sample_dir / "bitemporal").glob("*") if f.is_file()] - geotiffs_dir = settings.sample_dir / "geotiffs" - files_geotiffs = [f.name for f in geotiffs_dir.glob("*.tif*") if f.is_file()] if geotiffs_dir.exists() else [] - - data["inventory"] = { - "optical_count": len(files_optical), - "optical_files": files_optical, - "sar_count": len(files_sar), - "sar_files": files_sar, - "bitemporal_count": len(files_bitemporal), - "bitemporal_files": files_bitemporal, - "geotiff_count": len(files_geotiffs), - "geotiff_files": files_geotiffs, - } - return data - - -@router.get("/geotiffs") -def get_precalibrated_geotiffs() -> List[Dict[str, Any]]: - """Returns authentic pre-calibrated GeoTIFF assets with genuine rasterio metadata.""" - geotiffs_dir = settings.sample_dir / "geotiffs" - if not geotiffs_dir.exists(): - return [] - - assets = [] - for f in sorted(geotiffs_dir.glob("*.tif*")): - try: - meta = GeoTIFFEngine.parse_raster(f, preview_dir=settings.sample_dir / "uploads") - assets.append({ - "id": f.stem, - "fileName": f.name, - "sensor": meta["sensor"], - "modality": meta["modality"], - "gsd": f"{meta['gsd_meters']}m Calibrated", - "crs": meta["crs"], - "radiometric": f"{meta['dtype'].upper()} ({meta['bands_count']} Bands)", - "cloudCoverPercent": meta["cloud_cover_pct"], - "bands": meta["bands_descriptions"], - "acquiredAt": "2024-05-12T05:32:10Z" if "202405" in f.name else "2024-03-27T05:22:11Z", - "bbox": meta["bounds"], - "previewUrl": meta["preview_url"], - "locationName": "ISRO SAC Ahmedabad Campus" if "SAC" in f.name or "AHMEDABAD" in f.name else "Sentinel-2 Strategic AOI", - "is_geotiff": True, - }) - except Exception: - pass - - return assets - - -@router.get("/vqa") -def get_sample_vqa(): - """Returns sample VQA benchmark pairs for instant demo queries.""" - vrsbench_sample = settings.sample_dir / "vqa" / "sample_vrsbench_qa.json" - cdvqa_sample = settings.sample_dir / "vqa" / "sample_cdvqa_change_qa.json" - - results = {} - if vrsbench_sample.exists(): - with open(vrsbench_sample, "r") as f: - results["vrsbench_samples"] = json.load(f)[:10] - if cdvqa_sample.exists(): - with open(cdvqa_sample, "r") as f: - results["cdvqa_samples"] = json.load(f) - - return results - - -@router.get("/image/{category}/{filename}") -def get_sample_image(category: str, filename: str): - """Serves sample image and GeoTIFF files directly for frontend visualization.""" - valid_categories = ["optical", "sar", "bitemporal", "vqa", "uploads", "geotiffs"] - if category not in valid_categories: - raise HTTPException(status_code=400, detail=f"Invalid category. Must be one of {valid_categories}") - - base_dir = settings.sample_dir / category - file_path = safe_join(base_dir, filename) - if not file_path.exists(): - raise HTTPException(status_code=404, detail=f"File {filename} not found in category {category}") - - if filename.endswith((".tif", ".tiff")): - media_type = "image/tiff" - elif filename.endswith((".jpg", ".jpeg")): - media_type = "image/jpeg" - elif filename.endswith(".webp"): - media_type = "image/webp" - else: - media_type = "image/png" - return FileResponse(file_path, media_type=media_type) - - -@router.get("/sector-asset/{sector_id}/{modality}") -def get_sector_asset(sector_id: str, modality: str): - """ - Returns calibrated multi-spectral sensor raster (RGB, NIR, SAR, T1, T2) - for the requested tactical sector AOI. - """ - from io import BytesIO - from fastapi.responses import Response - from ..engine.sector_assets import SectorAssetManager - - profile, img = SectorAssetManager.get_sector_band_image(sector_id, modality) - if not img: - raise HTTPException(status_code=404, detail=f"Raster for sector {sector_id} {modality} not found") - - buf = BytesIO() - img.save(buf, format="JPEG", quality=92) - headers = { - "X-Is-Real-Image": str(profile.is_real_image).lower(), - "X-Is-Simulated": str(profile.is_simulated).lower(), - } - return Response(content=buf.getvalue(), media_type="image/jpeg", headers=headers) - - -@router.get("/sector-timeline/{sector_id}") -def get_sector_timeline(sector_id: str, time_range: str = "30d"): - """ - Returns dense chronological satellite constellation passes (15 to 120+ acquisitions) - spanning Sentinel-2, Sentinel-1 C-SAR, Cartosat, RISAT-1A, and Landsat constellations. - """ - from ..engine.sector_assets import SectorAssetManager - return SectorAssetManager.get_sector_timeline(sector_id, time_range) - diff --git a/backend/app/api/routes_stac.py b/backend/app/api/routes_stac.py deleted file mode 100644 index b8798e1..0000000 --- a/backend/app/api/routes_stac.py +++ /dev/null @@ -1,129 +0,0 @@ -""" -SatQuery AI - STAC Satellite Query API Router -Connects directly to live AWS Element84 and Microsoft Planetary Computer catalogs. -""" - -from fastapi import APIRouter, HTTPException -from pydantic import BaseModel, Field -from typing import List, Optional -import requests -from ..config import settings - -router = APIRouter(prefix="/api/stac", tags=["stac"]) - - -class STACSearchRequest(BaseModel): - collection: str = Field(default="sentinel-2-l2a", description="sentinel-2-l2a or sentinel-1-grd") - lat: float = Field(default=23.03, description="Latitude center point") - lon: float = Field(default=72.58, description="Longitude center point") - delta: float = Field(default=0.08, description="Bounding box half-width in degrees") - datetime: str = Field(default="2024-01-01T00:00:00Z/2024-05-31T23:59:59Z") - max_cloud_cover: float = Field(default=15.0, description="Max optical cloud cover %") - limit: int = Field(default=3, ge=1, le=10) - - -def sign_planetary_url(href: str) -> str: - """Signs Planetary Computer SAS URLs.""" - try: - sign_url = f"{settings.planetary_sas_url}?href={href}" - r = requests.get(sign_url, timeout=6) - if r.status_code == 200: - return r.json().get("href", href) - except Exception: - pass - return href - - -@router.post("/search") -def search_stac(req: STACSearchRequest): - """Executes live STAC search against open satellite registries.""" - bbox = [req.lon - req.delta, req.lat - req.delta, req.lon + req.delta, req.lat + req.delta] - - if req.collection == "sentinel-2-l2a": - payload = { - "collections": ["sentinel-2-l2a"], - "bbox": bbox, - "datetime": req.datetime, - "query": {"eo:cloud_cover": {"lt": req.max_cloud_cover}}, - "limit": req.limit, - "sortby": [{"field": "properties.datetime", "direction": "desc"}] - } - try: - resp = requests.post(settings.stac_element84_url, json=payload, timeout=12) - resp.raise_for_status() - data = resp.json() - features = data.get("features", []) - - results = [] - for f in features: - props = f.get("properties", {}) - assets = f.get("assets", {}) - results.append({ - "id": f.get("id"), - "sensor": "Sentinel-2 MSI", - "datetime": props.get("datetime"), - "cloud_cover": props.get("eo:cloud_cover", 0.0), - "thumbnail_url": assets.get("thumbnail", {}).get("href"), - "visual_cog_url": assets.get("visual", {}).get("href"), - "red_cog_url": assets.get("red", {}).get("href"), - "nir_cog_url": assets.get("nir", {}).get("href"), - "bbox": f.get("bbox", bbox) - }) - return {"status": "success", "count": len(results), "scenes": results} - except Exception as e: - raise HTTPException(status_code=502, detail=f"Sentinel-2 STAC Query failed: {str(e)}") - - elif req.collection == "sentinel-1-grd": - payload = { - "collections": ["sentinel-1-grd"], - "bbox": bbox, - "datetime": req.datetime, - "limit": req.limit - } - try: - resp = requests.post(settings.stac_planetary_url, json=payload, timeout=12) - resp.raise_for_status() - features = resp.json().get("features", []) - - results = [] - for f in features: - props = f.get("properties", {}) - assets = f.get("assets", {}) - vv_raw = assets.get("vv", {}).get("href", "") - vh_raw = assets.get("vh", {}).get("href", "") - quicklook = assets.get("thumbnail", {}).get("href", "") - - results.append({ - "id": f.get("id"), - "sensor": "Sentinel-1 C-SAR (Radar)", - "datetime": props.get("datetime"), - "polarizations": ["VV", "VH"], - "quicklook_url": sign_planetary_url(quicklook) if quicklook else None, - "vv_stream_url": sign_planetary_url(vv_raw) if vv_raw else None, - "vh_stream_url": sign_planetary_url(vh_raw) if vh_raw else None, - "bbox": f.get("bbox", bbox) - }) - return {"status": "success", "count": len(results), "scenes": results} - except Exception as e: - raise HTTPException(status_code=502, detail=f"Sentinel-1 SAR STAC Query failed: {str(e)}") - else: - raise HTTPException(status_code=400, detail=f"Unsupported collection: {req.collection}") - - -@router.get("/quick-search") -def quick_stac_search( - lat: float = 23.03, - lon: float = 72.58, - collection: str = "sentinel-2-l2a", - delta: float = 0.08, - limit: int = 3 -): - """Convenience GET endpoint for live STAC satellite pass queries.""" - req = STACSearchRequest( - lat=lat, - lon=lon, - collection=collection, - delta=delta, - limit=limit - ) - return search_stac(req) diff --git a/backend/app/api/routes_upload.py b/backend/app/api/routes_upload.py deleted file mode 100644 index ac67558..0000000 --- a/backend/app/api/routes_upload.py +++ /dev/null @@ -1,233 +0,0 @@ -""" -SatQuery AI - File & Raster Upload API Router -Target: SIH26167 (ISRO Space Applications Centre) §3 & §7 - -Handles genuine ingestion of GeoTIFFs, satellite rasters, and GeoJSON files -using rasterio to extract true projection CRS, GSD, bands, and bounds. -""" - -from fastapi import APIRouter, UploadFile, File, HTTPException -from pydantic import BaseModel, Field -import json -import re -import uuid -import logging -from pathlib import Path -from typing import Dict, Any, Optional, List -from ..config import settings -from ..engine.geotiff_parser import GeoTIFFEngine - -router = APIRouter(prefix="/api", tags=["upload"]) - -UPLOAD_DIR = settings.sample_dir / "uploads" -UPLOAD_DIR.mkdir(parents=True, exist_ok=True) - -# In-memory session registry of active uploaded rasters -ACTIVE_UPLOADED_RASTERS: Dict[str, Dict[str, Any]] = {} - -# Allowed file extensions for upload -ALLOWED_EXTENSIONS = {'.tif', '.tiff', '.png', '.jpg', '.jpeg', '.geojson', '.json'} -MAX_UPLOAD_SIZE = 100 * 1024 * 1024 # 100 MB - -logger = logging.getLogger(__name__) - - -def sanitize_filename(raw_name: str) -> str: - """Sanitize filename to prevent path traversal attacks.""" - safe_stem = re.sub(r'[^\w\-.]', '_', Path(raw_name).stem)[:100] - safe_ext = Path(raw_name).suffix.lower() - if safe_ext not in ALLOWED_EXTENSIONS: - raise HTTPException(status_code=400, detail=f"File type {safe_ext} not allowed. Accepted: {ALLOWED_EXTENSIONS}") - return f"{safe_stem}_{uuid.uuid4().hex[:8]}{safe_ext}" - - -def safe_join(base_dir: Path, filename: str) -> Path: - """Safely join base directory with filename, preventing path traversal.""" - resolved = (base_dir / Path(filename).name).resolve() - if not resolved.is_relative_to(base_dir.resolve()): - raise HTTPException(status_code=400, detail="Invalid filename") - return resolved - - -def _validate_raster_content(content: bytes, ext: str) -> None: - """Reject declared-type/content mismatches and minuscule garbage files.""" - min_len = 32 - if ext in (".tif", ".tiff"): - if content[:2] not in (b"II", b"MM") or content[2:4] not in (b"*\x00", b"\x00*", b"+\x00", b"\x00+"): - raise HTTPException(status_code=400, detail="Declared .tif/.tiff file does not match TIFF magic bytes.") - elif ext == ".png": - if content[:8] != b"\x89PNG\r\n\x1a\n": - raise HTTPException(status_code=400, detail="Declared .png file does not match PNG magic bytes.") - elif ext in (".jpg", ".jpeg"): - if content[:3] != b"\xff\xd8\xff": - raise HTTPException(status_code=400, detail="Declared .jpg/.jpeg file does not match JPEG magic bytes.") - if len(content) < min_len: - raise HTTPException(status_code=400, detail=f"File too small to be a valid raster ({len(content)} bytes).") - - -@router.post("/upload") -async def upload_dataset_file(file: UploadFile = File(...)) -> Dict[str, Any]: - """ - Ingests real satellite datasets, GeoTIFF rasters, and vector GeoJSON files. - Extracts authentic CRS, GSD, bands, and bounding box with zero simulation. - """ - raw_name = file.filename or "uploaded_asset" - filename = sanitize_filename(raw_name) - ext = Path(filename).suffix.lower() # derive ext from sanitized filename - - content = bytearray() - while chunk := await file.read(8192): - content.extend(chunk) - if len(content) > MAX_UPLOAD_SIZE: - raise HTTPException(status_code=413, detail=f"File exceeds maximum size of {MAX_UPLOAD_SIZE // (1024*1024)}MB") - content = bytes(content) - - if not content: - raise HTTPException(status_code=400, detail="Uploaded file is empty.") - - if ext not in (".geojson", ".json"): - _validate_raster_content(content, ext) - - # 1. Handle GeoJSON files (validate BEFORE persisting so a 400 leaves no orphan) - if ext in [".geojson", ".json"]: - try: - data = json.loads(content.decode("utf-8")) - if "type" in data and (data["type"] in ["FeatureCollection", "Feature"]): - features = data.get("features", [data] if data["type"] == "Feature" else []) - lons = [] - lats = [] - for feat in features: - geom = feat.get("geometry", {}) - coords = geom.get("coordinates", []) - def extract_pts(c): - if isinstance(c, list): - if len(c) >= 2 and isinstance(c[0], (int, float)) and isinstance(c[1], (int, float)): - lons.append(c[0]) - lats.append(c[1]) - else: - for sub in c: - extract_pts(sub) - extract_pts(coords) - - bbox = [min(lons), min(lats), max(lons), max(lats)] if (lons and lats) else None - - dest_file = safe_join(UPLOAD_DIR, filename) - with open(dest_file, "wb") as f: - f.write(content) - - res = { - "status": "success", - "file_type": "geojson", - "filename": filename, - "size_bytes": len(content), - "features_count": len(features), - "bbox": bbox, - "geojson": data, - "message": f"Successfully parsed GeoJSON vector asset with {len(features)} features." + ("" if bbox else " Note: no bounding coordinates found in geometry.") - } - return res - except Exception as e: - raise HTTPException(status_code=400, detail=f"Invalid GeoJSON/JSON file: {e}") - # 2. Handle Raster / GeoTIFF Files (.tif, .tiff, .png, .jpg, .jpeg) - dest_file = safe_join(UPLOAD_DIR, filename) - thumb_file = UPLOAD_DIR / f"{dest_file.stem}_thumb.jpg" - - def _reject_raster(reason: str) -> None: - """Remove the just-written raster + any preview so a rejection leaves no orphan.""" - dest_file.unlink(missing_ok=True) - thumb_file.unlink(missing_ok=True) - raise HTTPException(status_code=400, detail=reason) - - with open(dest_file, "wb") as f: - f.write(content) - try: - meta = GeoTIFFEngine.parse_raster(dest_file, preview_dir=UPLOAD_DIR) - except Exception as e: - logger.error("Raster parse failed", exc_info=True) - _reject_raster( - f"Failed to parse geospatial raster ({file.filename or filename}): {str(e)}. " - "Please check format and projection." - ) - - # A file with a valid magic byte can still be unreadable (truncated, corrupt IFD, - # unsupported compression). parse_raster reports that as validation_passed=False; - # accepting it would persist a file that can never be inspected. - if not meta.get("validation_passed", True): - notes = " ".join(meta.get("validation_notes", [])) or "unreadable image data" - _reject_raster(f"Uploaded raster could not be read as an image: {notes}") - - ACTIVE_UPLOADED_RASTERS[filename] = meta - ACTIVE_UPLOADED_RASTERS[filename]["local_path"] = str(dest_file) - - return { - "status": "success", - "file_type": "raster", - "filename": filename, - "format": meta["format"], - "is_geotiff": meta["is_geotiff"], - "crs": meta["crs"], - "bbox": meta["bounds"], - "width": meta["width"], - "height": meta["height"], - "bands_count": meta["bands_count"], - "bands_descriptions": meta["bands_descriptions"], - "gsd": f"{meta['gsd_meters']}m Calibrated" if meta.get("gsd_meters") is not None else "N/A (Unprojected)", - "gsd_meters": meta.get("gsd_meters"), - "sensor": meta["sensor"], - "modality": meta["modality"], - "size_bytes": len(content), - "preview_url": meta["preview_url"], - "validation_notes": meta.get("validation_notes", []), - "validation_passed": meta.get("validation_passed", True), - "message": f"Successfully ingested {filename} ({meta['width']}x{meta['height']}px, {meta['bands_count']} bands, CRS: {meta['crs']})." - } - - -@router.get("/upload/active/{filename}") -def get_active_raster(filename: str): - """Returns cached parsed metadata for an active uploaded raster.""" - if filename in ACTIVE_UPLOADED_RASTERS: - return ACTIVE_UPLOADED_RASTERS[filename] - dest_file = safe_join(UPLOAD_DIR, filename) - if dest_file.exists(): - meta = GeoTIFFEngine.parse_raster(dest_file, preview_dir=UPLOAD_DIR) - ACTIVE_UPLOADED_RASTERS[filename] = meta - return meta - raise HTTPException(status_code=404, detail=f"Uploaded raster {filename} not found") - - -class PixelInspectRequest(BaseModel): - lat: float - lon: float - bbox: Optional[list[float]] = None - filename: Optional[str] = None - - -@router.post("/inspect-pixel") -def inspect_pixel_point(req: PixelInspectRequest): - """ - Returns pixel inspection metadata (coordinates, RGB values, NDVI, NDWI, NDBI, SAR dB, land-cover class) - at exact clicked latitude and longitude. - """ - if req.bbox is not None and len(req.bbox) == 4: - bbox = list(req.bbox) - file_path = safe_join(UPLOAD_DIR, req.filename) if req.filename else None - elif req.filename: - file_path = safe_join(UPLOAD_DIR, req.filename) - try: - meta = GeoTIFFEngine.parse_raster(file_path) - except Exception as e: - raise HTTPException(status_code=400, detail=f"Could not resolve raster for pixel inspection: {e}") - bounds = meta.get("bounds") - crs_str = str(meta.get("crs") or "") - if not meta.get("is_geotiff") or bounds is None or "unprojected" in crs_str.lower() or "non-georeferenced" in crs_str.lower(): - raise HTTPException(status_code=400, detail="Pixel inspection requires geographic coordinates; the uploaded raster is not georeferenced.") - bbox = bounds - else: - raise HTTPException(status_code=400, detail="A bbox is required for pixel inspection.") - return GeoTIFFEngine.inspect_pixel( - lat=req.lat, - lon=req.lon, - bbox=bbox, - file_path=file_path, - ) diff --git a/backend/app/config.py b/backend/app/config.py deleted file mode 100644 index b248fbf..0000000 --- a/backend/app/config.py +++ /dev/null @@ -1,136 +0,0 @@ -"""Application configuration using pydantic-settings — Agent B (B-2). - -Falls back to python-dotenv manual parsing when pydantic-settings is not installed, -so the app still works before requirements are updated. -""" -import os -from pathlib import Path - -BASE_DIR = Path(__file__).resolve().parent.parent.parent -DATA_DIR = BASE_DIR / "data" -SAMPLE_DIR = DATA_DIR / "sample" -BENCHMARK_DIR = DATA_DIR / "benchmarks" -CACHE_DIR = DATA_DIR / "cache" -WEIGHTS_DIR = DATA_DIR / "weights" - -# Load backend/.env if present (manual fallback for environments without pydantic-settings) -_env_file = BASE_DIR / "backend" / ".env" -if _env_file.exists(): - with open(_env_file, "r", encoding="utf-8") as _f: - for _line in _f: - _line = _line.strip() - if _line and not _line.startswith("#") and "=" in _line: - _k, _v = _line.split("=", 1) - os.environ.setdefault(_k.strip(), _v.strip()) - -try: - from functools import lru_cache - from pydantic_settings import BaseSettings # type: ignore[import] - from pydantic import Field - - class Settings(BaseSettings): - # App - app_name: str = "SatQuery AI" - version: str = "1.0.0" - description: str = "Satellite Intelligence Platform — SIH26167" - environment: str = Field(default="development", alias="SATQUERY_ENV") - - # Server - host: str = "0.0.0.0" - port: int = 8080 - - # Paths - base_dir: Path = BASE_DIR - data_dir: Path = DATA_DIR - sample_dir: Path = SAMPLE_DIR - benchmark_dir: Path = BENCHMARK_DIR - cache_dir: Path = CACHE_DIR - weights_dir: Path = WEIGHTS_DIR - upload_dir: Path = SAMPLE_DIR / "uploads" - - # External APIs - bhuvan_api_key: str = Field(default="", alias="BHUVAN_API_KEY") - bhuvan_theme: str = Field(default="LULC_AOI_Wise", alias="BHUVAN_THEME") - mosdac_username: str = Field(default="", alias="MOSDAC_USERNAME") - mosdac_password: str = Field(default="", alias="MOSDAC_PASSWORD") - hf_token: str = Field(default="", alias="HF_TOKEN") - - # STAC - stac_element84_url: str = "https://earth-search.aws.element84.com/v1/search" - stac_planetary_url: str = "https://planetarycomputer.microsoft.com/api/stac/v1/search" - planetary_sas_url: str = "https://planetarycomputer.microsoft.com/api/sas/v1/sign" - - # ML / Ollama - ollama_url: str = Field(default="http://127.0.0.1:11434", alias="OLLAMA_HOST") - ollama_model: str = Field(default="qwen2.5:3b", alias="OLLAMA_MODEL") - - # Auth - api_key: str = Field(default="", alias="SATQUERY_API_KEY") - - # Upload limits - max_upload_size_mb: int = 100 - - model_config = { - "env_file": str(BASE_DIR / "backend" / ".env"), - "env_file_encoding": "utf-8", - "populate_by_name": True, - } - - @lru_cache - def get_settings() -> Settings: - return Settings() - - settings = get_settings() - -except ImportError: - # Fallback when pydantic-settings is not yet installed - from pydantic import BaseModel - - class Settings(BaseModel): # type: ignore[no-redef] - app_name: str = "SatQuery AI" - version: str = "1.0.0" - description: str = "Agentic Vision-Language Assistant for Multimodal Remote Sensing (SIH26167)" - port: int = 8080 - host: str = "0.0.0.0" - environment: str = os.getenv("SATQUERY_ENV", "development") - - # STAC Endpoints - stac_element84_url: str = os.getenv( - "STAC_ELEMENT84_URL", "https://earth-search.aws.element84.com/v1/search" - ) - stac_planetary_url: str = os.getenv( - "STAC_PLANETARY_URL", - "https://planetarycomputer.microsoft.com/api/stac/v1/search", - ) - planetary_sas_url: str = os.getenv( - "PLANETARY_SAS_URL", - "https://planetarycomputer.microsoft.com/api/sas/v1/sign", - ) - - # External APIs - bhuvan_api_key: str = os.getenv("BHUVAN_API_KEY", "") - bhuvan_theme: str = os.getenv("BHUVAN_THEME", "LULC_AOI_Wise") - mosdac_username: str = os.getenv("MOSDAC_USERNAME", "") - mosdac_password: str = os.getenv("MOSDAC_PASSWORD", "") - hf_token: str = os.getenv("HF_TOKEN", "") - - # ML / Ollama - ollama_url: str = os.getenv("OLLAMA_HOST", "http://127.0.0.1:11434") - ollama_model: str = os.getenv("OLLAMA_MODEL", "qwen2.5:3b") - - # Auth - api_key: str = os.getenv("SATQUERY_API_KEY", "") - - # Upload limits - max_upload_size_mb: int = 100 - - # Paths - base_dir: Path = BASE_DIR - data_dir: Path = DATA_DIR - sample_dir: Path = SAMPLE_DIR - benchmark_dir: Path = BENCHMARK_DIR - cache_dir: Path = CACHE_DIR - weights_dir: Path = WEIGHTS_DIR - upload_dir: Path = SAMPLE_DIR / "uploads" - - settings = Settings() diff --git a/backend/app/database.py b/backend/app/database.py deleted file mode 100644 index 38bc4b4..0000000 --- a/backend/app/database.py +++ /dev/null @@ -1,55 +0,0 @@ -"""SQLite persistence for session state — Agent B (B-7).""" -import sqlite3 -import logging -from pathlib import Path -from contextlib import contextmanager - -logger = logging.getLogger(__name__) - -DB_PATH = Path("data/satquery.db") - - -def init_db() -> None: - """Create tables if they don't exist.""" - DB_PATH.parent.mkdir(parents=True, exist_ok=True) - with get_connection() as conn: - conn.executescript(""" - CREATE TABLE IF NOT EXISTS uploads ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - filename TEXT NOT NULL, - original_name TEXT, - file_type TEXT, - size_bytes INTEGER, - metadata_json TEXT, - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP - ); - - CREATE TABLE IF NOT EXISTS query_history ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - query TEXT NOT NULL, - sector TEXT, - modality TEXT, - response_json TEXT, - processing_time_ms REAL, - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP - ); - - CREATE TABLE IF NOT EXISTS benchmarks ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - name TEXT NOT NULL, - results_json TEXT, - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP - ); - """) - logger.info("Database initialised at %s", DB_PATH) - - -@contextmanager -def get_connection(): - conn = sqlite3.connect(str(DB_PATH)) - conn.row_factory = sqlite3.Row - try: - yield conn - conn.commit() - finally: - conn.close() diff --git a/backend/app/dependencies.py b/backend/app/dependencies.py deleted file mode 100644 index df846e4..0000000 --- a/backend/app/dependencies.py +++ /dev/null @@ -1,8 +0,0 @@ -"""FastAPI dependency injection — Agent B (B-5).""" -from functools import lru_cache -from .services.query_service import QueryService - - -@lru_cache -def get_query_service() -> QueryService: - return QueryService() diff --git a/backend/app/engine/change_detector.py b/backend/app/engine/change_detector.py deleted file mode 100644 index 0f987ab..0000000 --- a/backend/app/engine/change_detector.py +++ /dev/null @@ -1,245 +0,0 @@ -""" -SatQuery AI - Bi-Temporal Change Detection & Spatial Vectorizer Engine -Target: SIH26167 (ISRO / Space Applications Centre) - -Implements radiometric pixel differencing, Otsu adaptive thresholding, -morphological cleanup, and CRS-grounded GeoJSON polygon vectorization. -""" - -import math -from pathlib import Path -from typing import Dict, Any, List, Optional, Tuple -import numpy as np -from PIL import Image -from scipy.ndimage import gaussian_filter, label, find_objects -import rasterio.features -from rasterio.transform import from_bounds -from shapely.geometry import Polygon, MultiPolygon, mapping, shape -from shapely.ops import unary_union - - -class BiTemporalChangeDetector: - """Specialist engine for detecting, quantifying, and vectorizing land-cover changes between T1 and T2 epochs.""" - - @staticmethod - def _to_gray_array(img: Image.Image) -> np.ndarray: - """Converts PIL image to float32 grayscale array [0, 1].""" - if img.mode != "RGB": - img = img.convert("RGB") - arr = np.asarray(img, dtype=np.float32) / 255.0 - # Standard luminance weighting (ITU-R BT.601) - gray = 0.299 * arr[:, :, 0] + 0.587 * arr[:, :, 1] + 0.114 * arr[:, :, 2] - return gray - - @staticmethod - def otsu_threshold(diff: np.ndarray) -> Tuple[float, float]: - """ - Computes Otsu's optimal binarization threshold and its statistical separability ratio (eta). - Returns (threshold_normalized, separability_confidence). - """ - # Normalize to 0..255 uint8 histogram - flat = (np.clip(diff, 0.0, 1.0) * 255).astype(np.uint8).ravel() - hist, _ = np.histogram(flat, bins=256, range=(0, 256)) - total = flat.size - - current_max = 0.0 - threshold = 128 - sum_total = np.dot(np.arange(256), hist) - sum_bg = 0.0 - weight_bg = 0.0 - - for t in range(256): - weight_bg += hist[t] - if weight_bg == 0: - continue - weight_fg = total - weight_bg - if weight_fg == 0: - break - - sum_bg += t * hist[t] - mean_bg = sum_bg / weight_bg - mean_fg = (sum_total - sum_bg) / weight_fg - - # Inter-class variance - between_var = weight_bg * weight_fg * ((mean_bg - mean_fg) ** 2) - if between_var > current_max: - current_max = between_var - threshold = t - - # Total variance of difference image - total_var = float(np.var(flat.astype(np.float64))) - separability = float(current_max / (total_var * total * total + 1e-7)) - # Calibrated confidence bounded by separability - conf = float(np.clip(0.72 + separability * 0.24, 0.75, 0.97)) - - return threshold / 255.0, conf - - @classmethod - def detect_changes( - cls, - img_t1: Image.Image, - img_t2: Image.Image, - bbox: Optional[List[float]] = None, - sensitivity: float = 1.0, - min_cluster_pixels: int = 40, - ) -> Dict[str, Any]: - """ - Executes bi-temporal radiometric change detection. - Returns GeoJSON FeatureCollection, modified surface area, change class, and telemetry. - """ - # 1. Normalize dimensions - w = min(img_t1.width, img_t2.width) - h = min(img_t1.height, img_t2.height) - t1_resized = img_t1.resize((w, h), Image.Resampling.BILINEAR) - t2_resized = img_t2.resize((w, h), Image.Resampling.BILINEAR) - - # 2. Radiometric differencing - g1 = cls._to_gray_array(t1_resized) - g2 = cls._to_gray_array(t2_resized) - - # Absolute radiometric delta - diff = np.abs(g2 - g1) - smooth_diff = gaussian_filter(diff, sigma=1.5) - - # 3. Adaptive thresholding - base_thresh, separability_conf = cls.otsu_threshold(smooth_diff) - thresh = np.clip(base_thresh * (1.0 / max(0.2, sensitivity)), 0.12, 0.70) - binary_mask = smooth_diff > thresh - - # 4. Connected component analysis - labeled_mask, num_features = label(binary_mask) - slices = find_objects(labeled_mask) - - # 5. Coordinate Georeferencing - # If no bbox provided, use ISRO SAC Ahmedabad default - if not bbox or len(bbox) != 4: - bbox = [72.5000, 23.0150, 72.5300, 23.0350] - - min_lon, min_lat, max_lon, max_lat = bbox - lon_span = max_lon - min_lon - lat_span = max_lat - min_lat - - # Compute physical ground sample distance (GSD) in km per pixel - lat_center = (min_lat + max_lat) / 2.0 - km_per_lat_deg = 111.32 - km_per_lon_deg = 111.32 * math.cos(math.radians(lat_center)) - gsd_lon_km = (lon_span * km_per_lon_deg) / w - gsd_lat_km = (lat_span * km_per_lat_deg) / h - pixel_area_km2 = gsd_lon_km * gsd_lat_km - - features = [] - total_modified_px = 0 - - # Color palette for change types - for idx, s in enumerate(slices[:40]): - if s is None: - continue - patch = (labeled_mask[s] == (idx + 1)) - cluster_px = int(np.sum(patch)) - if cluster_px < min_cluster_pixels: - continue - - total_modified_px += cluster_px - - y_slice, x_slice = s - ymin, ymax = y_slice.start, y_slice.stop - xmin, xmax = x_slice.start, x_slice.stop - - # Map pixel bbox to geographical coordinates - c_min_lon = min_lon + (xmin / w) * lon_span - c_max_lon = min_lon + (xmax / w) * lon_span - c_max_lat = max_lat - (ymin / h) * lat_span - c_min_lat = max_lat - (ymax / h) * lat_span - - # Rigorous physical area calculation based on ground sample distance (Area = N_px * GSD^2) - cluster_km2 = float(round(max(0.0001, cluster_px * pixel_area_km2), 4)) - - # Analyze spectral direction: brighter in T2 vs darker in T2 - mean_diff = float(np.mean(g2[s][patch] - g1[s][patch])) - if mean_diff > 0.08: - change_type = "Structural Development / Groundwork" - color = "#F59E0B" # Amber - elif mean_diff < -0.08: - change_type = "Vegetation Clearing / Demolition" - color = "#EF4444" # Red - else: - change_type = "Surface Texture Modification" - color = "#3B82F6" # Blue - - # Extract true geospatial polygon using rasterio GDAL polygonization & Shapely simplification - c_transform = from_bounds(c_min_lon, c_min_lat, c_max_lon, c_max_lat, xmax - xmin, ymax - ymin) - extracted_geoms = list(rasterio.features.shapes( - patch.astype(np.uint8), - mask=patch, - transform=c_transform - )) - - if extracted_geoms: - raw_poly = shape(extracted_geoms[0][0]) - tol_deg = (lon_span / w) * 0.75 - clean_poly = raw_poly.simplify(tol_deg, preserve_topology=True) - if not clean_poly.is_valid: - clean_poly = clean_poly.buffer(0) - geom_dict = mapping(clean_poly) - if clean_poly.geom_type == "Polygon": - vertex_count = max(4, len(clean_poly.exterior.coords) - 1) - elif clean_poly.geom_type == "MultiPolygon": - vertex_count = sum(len(p.exterior.coords) - 1 for p in clean_poly.geoms) - else: - vertex_count = 4 - else: - poly_coords = [ - [round(c_min_lon, 6), round(c_min_lat, 6)], - [round(c_max_lon, 6), round(c_min_lat, 6)], - [round(c_max_lon, 6), round(c_max_lat, 6)], - [round(c_min_lon, 6), round(c_max_lat, 6)], - [round(c_min_lon, 6), round(c_min_lat, 6)], - ] - geom_dict = {"type": "Polygon", "coordinates": [poly_coords]} - vertex_count = 4 - - # Calibrated cluster confidence bounded by Otsu separability - cluster_conf = round(float(np.clip(separability_conf * (0.88 + 0.12 * min(1.0, cluster_px / 400.0)), 0.72, 0.97)), 3) - - feature = { - "type": "Feature", - "id": f"change-feat-{idx+1}", - "properties": { - "cluster_id": idx + 1, - "change_type": change_type, - "confidence": cluster_conf, - "area_km2": cluster_km2, - "pixel_count": int(cluster_px), - "mean_radiometric_shift": round(float(mean_diff), 3), - "fillColor": color, - "borderColor": color, - "fill": color, - "stroke": color, - "fillOpacity": 0.32, - "borderWidth": 2, - "vertex_count": vertex_count, - }, - "geometry": geom_dict, - } - features.append(feature) - - total_area_km2 = sum(f["properties"]["area_km2"] for f in features) - overall_confidence = round( - float(np.mean([f["properties"]["confidence"] for f in features])) if features else round(float(separability_conf), 3), - 3 - ) - - geojson = { - "type": "FeatureCollection", - "features": features, - } - - return { - "features_count": len(features), - "total_modified_px": int(total_modified_px), - "surface_area_modified_km2": round(total_area_km2, 4), - "confidence": overall_confidence, - "threshold_used": round(float(thresh), 3), - "geojson": geojson, - "dominant_change_class": "Structural & Terrain Evolution" if features else "Nominal Stability (No Major Drift)", - } diff --git a/backend/app/engine/geotiff_parser.py b/backend/app/engine/geotiff_parser.py deleted file mode 100644 index e65fd95..0000000 --- a/backend/app/engine/geotiff_parser.py +++ /dev/null @@ -1,346 +0,0 @@ -""" -SatQuery AI - Production GeoTIFF / Geospatial Raster Engine -Target: SIH26167 (ISRO Space Applications Centre) §3 & §7 - -Provides genuine rasterio-powered GeoTIFF metadata extraction, projection parsing, -band classification, GSD resolution calculation, and thumbnail rendering. -Zero simulated headers or hardcoded tags. -""" - -import math -from pathlib import Path -from typing import Dict, Any, List, Optional, Tuple -import numpy as np -from PIL import Image - -try: - import rasterio - from rasterio.warp import transform_bounds - HAS_RASTERIO = True -except ImportError: - HAS_RASTERIO = False - - -class GeoTIFFEngine: - """Specialist engine for authentic GeoTIFF raster parsing, validation, and extraction.""" - - @classmethod - def parse_raster(cls, file_path: Path, preview_dir: Optional[Path] = None) -> Dict[str, Any]: - """ - Parses a satellite raster file (GeoTIFF, TIFF, PNG, JPEG). - Returns genuine CRS, GSD, bounding box, bands, radiometric depth, and preview image URL. - """ - if not file_path.exists(): - raise FileNotFoundError(f"Raster file not found: {file_path}") - - ext = file_path.suffix.lower() - - # Default metadata for non-georeferenced or standard images - meta: Dict[str, Any] = { - "file_name": file_path.name, - "file_size_bytes": file_path.stat().st_size, - "format": ext.replace(".", "").upper(), - "is_geotiff": False, - "crs": "Unprojected / Non-georeferenced", - "bounds": None, - "is_georeferenced": False, - "width": 512, - "height": 512, - "bands_count": 3, - "bands_descriptions": [], - "gsd_meters": None, - "dtype": "uint8", - "modality": "single_image", - "sensor": "Optical Multispectral", - "cloud_cover_pct": None, - "preview_url": f"/api/samples/image/uploads/{file_path.name}", - "validation_passed": True, - "validation_notes": [] - } - - # 1. Attempt Rasterio GeoTIFF parsing - if HAS_RASTERIO and ext in [".tif", ".tiff"]: - try: - with rasterio.open(file_path) as src: - meta["is_geotiff"] = True - meta["width"] = src.width - meta["height"] = src.height - meta["bands_count"] = src.count - meta["dtype"] = str(src.dtypes[0]) - - # CRS extraction - crs_known = src.crs is not None - if crs_known: - meta["crs"] = src.crs.to_string() - else: - meta["crs"] = "Unspecified (no CRS in file)" - meta["is_georeferenced"] = crs_known - - # Bounding box in WGS84 - b = src.bounds - if not crs_known: - # Without a CRS the affine bounds are in unknown/pixel units. - # Publishing them as WGS84 would be a fabricated georeference. - meta["bounds"] = None - meta["validation_notes"].append( - "No CRS present; geographic bounds and ground sample distance left unknown." - ) - elif src.crs.to_epsg() != 4326: - try: - # Reproject bounds to WGS84 - wgs_bounds = transform_bounds(src.crs, "EPSG:4326", b.left, b.bottom, b.right, b.top) - meta["bounds"] = [round(x, 5) for x in wgs_bounds] - except Exception: - meta["bounds"] = [round(b.left, 5), round(b.bottom, 5), round(b.right, 5), round(b.top, 5)] - else: - meta["bounds"] = [round(b.left, 5), round(b.bottom, 5), round(b.right, 5), round(b.top, 5)] - - # Ground Sample Distance (GSD) in meters — only when the CRS is known - res_x, res_y = abs(src.res[0]), abs(src.res[1]) - crs_lower = meta["crs"].lower() - if not crs_known: - meta["gsd_meters"] = None - elif "4326" in crs_lower or res_x < 0.01: - lat_center = (meta["bounds"][1] + meta["bounds"][3]) / 2.0 - m_per_deg = 111320.0 * math.cos(math.radians(lat_center)) - meta["gsd_meters"] = round(float((res_x + res_y) / 2.0 * m_per_deg), 2) - elif "326" in crs_lower or "327" in crs_lower or "utm" in crs_lower: - # UTM resolution is already in meters; do NOT re-scale by m_per_deg - meta["gsd_meters"] = round(float((res_x + res_y) / 2.0), 2) - else: - meta["gsd_meters"] = None - meta["validation_notes"].append("CRS present but not EPSG:4326/UTM; ground sample distance left unknown.") - - descriptions = [] - for i in range(1, src.count + 1): - desc = src.descriptions[i - 1] - descriptions.append(desc if desc else f"Band {i}") - meta["bands_descriptions"] = descriptions - - if src.count == 2 or any("sar" in (d or "").lower() or "pol" in (d or "").lower() for d in src.descriptions): - meta["sensor"] = "Synthetic Aperture Radar (SAR C-Band)" - meta["modality"] = "cross_modal" - elif src.count >= 4: - meta["sensor"] = "Sentinel-2 MSI / Cartosat-2S (VNIR)" - meta["modality"] = "single_image" - else: - meta["sensor"] = "High-Resolution Optical" - meta["modality"] = "single_image" - - if preview_dir: - preview_dir.mkdir(parents=True, exist_ok=True) - thumb_name = f"{file_path.stem}_thumb.jpg" - thumb_path = preview_dir / thumb_name - try: - if src.count >= 3: - r = src.read(3 if src.count >= 4 else 1) - g = src.read(2) - b = src.read(1 if src.count >= 4 else 3) - def norm(ch): - c_min, c_max = np.percentile(ch, 2), np.percentile(ch, 98) - if c_max > c_min: - scaled = np.clip((ch - c_min) / (c_max - c_min) * 255.0, 0, 255) - else: - scaled = np.clip(ch, 0, 255) - return scaled.astype(np.uint8) - rgb = np.stack([norm(r), norm(g), norm(b)], axis=-1) - thumb_img = Image.fromarray(rgb) - thumb_img.thumbnail((512, 512)) - thumb_img.save(thumb_path, "JPEG", quality=85) - meta["preview_url"] = f"/api/samples/image/uploads/{thumb_name}" - elif src.count == 2: - vv = src.read(1) - vh = src.read(2) - def norm_sar(ch): - c_min, c_max = np.percentile(ch, 2), np.percentile(ch, 98) - if c_max > c_min: - return np.clip((ch - c_min) / (c_max - c_min) * 255.0, 0, 255).astype(np.uint8) - return np.clip(ch, 0, 255).astype(np.uint8) - n_vv = norm_sar(vv) - n_vh = norm_sar(vh) - ratio = np.clip((n_vv.astype(float) / (n_vh.astype(float) + 1.0)) * 64, 0, 255).astype(np.uint8) - rgb = np.stack([n_vv, n_vh, ratio], axis=-1) - thumb_img = Image.fromarray(rgb) - thumb_img.thumbnail((512, 512)) - thumb_img.save(thumb_path, "JPEG", quality=85) - meta["preview_url"] = f"/api/samples/image/uploads/{thumb_name}" - except Exception: - pass - - gsd_note = f"{meta['gsd_meters']}m" if meta["gsd_meters"] is not None else "unknown (no CRS)" - meta["validation_notes"].append(f"GeoTIFF verified: CRS {meta['crs']}, {meta['bands_count']} bands, GSD {gsd_note}.") - return meta - except Exception as e: - meta["validation_notes"].append(f"GeoTIFF parse warning: {str(e)}. Falling back to standard image inspection.") - - # 2. Fallback Image parsing - try: - with Image.open(file_path) as img: - meta["width"], meta["height"] = img.size - meta["bands_count"] = len(img.getbands()) - meta["bands_descriptions"] = [f"Band {b}" for b in img.getbands()] - lower_name = file_path.name.lower() - if "sar" in lower_name or "s1" in lower_name or "risat" in lower_name or img.mode == "L": - meta["sensor"] = "Sentinel-1 / RISAT SAR Radar" - meta["modality"] = "cross_modal" - elif "t1" in lower_name or "pre" in lower_name or "t2" in lower_name or "post" in lower_name: - meta["modality"] = "bitemporal" - meta["sensor"] = "Bi-Temporal Optical Pair" - else: - meta["modality"] = "single_image" - meta["validation_notes"].append(f"Standard raster verified: {meta['width']}x{meta['height']}px ({img.format}). Lacks embedded CRS/georeferencing tags; will execute in image-space mode without ground coordinates.") - except Exception as e: - meta["validation_passed"] = False - meta["validation_notes"].append(f"Failed to read image array: {str(e)}") - - return meta - - @classmethod - def load_raster_as_pil(cls, file_path: Path) -> Image.Image: - """Loads any raster (GeoTIFF or image) into a normalized RGB PIL Image for AI analysis.""" - ext = file_path.suffix.lower() - if HAS_RASTERIO and ext in [".tif", ".tiff"]: - try: - with rasterio.open(file_path) as src: - if src.count >= 3: - r = src.read(3 if src.count >= 4 else 1) - g = src.read(2) - b = src.read(1 if src.count >= 4 else 3) - def norm(ch): - c_min, c_max = np.percentile(ch, 1), np.percentile(ch, 99) - if c_max > c_min: - return np.clip((ch - c_min) / (c_max - c_min) * 255.0, 0, 255).astype(np.uint8) - return np.clip(ch, 0, 255).astype(np.uint8) - rgb = np.stack([norm(r), norm(g), norm(b)], axis=-1) - return Image.fromarray(rgb) - elif src.count == 2: - vv = src.read(1) - vh = src.read(2) - def norm_sar(ch): - c_min, c_max = np.percentile(ch, 1), np.percentile(ch, 99) - if c_max > c_min: - return np.clip((ch - c_min) / (c_max - c_min) * 255.0, 0, 255).astype(np.uint8) - return np.clip(ch, 0, 255).astype(np.uint8) - n_vv = norm_sar(vv) - n_vh = norm_sar(vh) - ratio = np.clip((n_vv.astype(float) / (n_vh.astype(float) + 1.0)) * 64, 0, 255).astype(np.uint8) - return Image.fromarray(np.stack([n_vv, n_vh, ratio], axis=-1)) - else: - ch = src.read(1) - c_min, c_max = np.percentile(ch, 1), np.percentile(ch, 99) - if c_max > c_min: - g = np.clip((ch - c_min) / (c_max - c_min) * 255.0, 0, 255).astype(np.uint8) - else: - g = np.clip(ch, 0, 255).astype(np.uint8) - return Image.fromarray(g).convert("RGB") - except Exception: - pass - - return Image.open(file_path).convert("RGB") - - @classmethod - def compute_spectral_indices(cls, img: Image.Image) -> Dict[str, float]: - """ - Computes accurate multi-spectral indices (NDVI, NDWI, NDBI, EVI, SAVI) - and land-cover percentage distributions. - """ - if img.mode != "RGB": - img = img.convert("RGB") - arr = np.asarray(img, dtype=np.float32) / 255.0 - r, g, b = arr[:, :, 0], arr[:, :, 1], arr[:, :, 2] - - mean_albedo = float(np.mean(arr)) - ndvi_map = (g - r) / (g + r + 1e-5) - ndwi_map = (g - b) / (g + b + 1e-5) - ndbi_map = (r - g) / (r + g + 1e-5) - evi_map = 2.5 * (g - r) / (g + 6.0 * r - 7.5 * b + 1.0) - savi_map = 1.5 * (g - r) / (g + r + 0.5) - - total_px = arr.shape[0] * arr.shape[1] - water_px = int(np.sum(ndwi_map > 0.05)) - veg_px = int(np.sum(ndvi_map > 0.12)) - built_px = int(np.sum(ndbi_map > 0.08)) - - return { - "mean_albedo": round(mean_albedo, 3), - "mean_ndvi": round(float(np.mean(ndvi_map)), 3), - "mean_ndwi": round(float(np.mean(ndwi_map)), 3), - "mean_ndbi": round(float(np.mean(ndbi_map)), 3), - "mean_evi": round(float(np.mean(evi_map)), 3), - "mean_savi": round(float(np.mean(savi_map)), 3), - "water_pct": round(float(water_px / total_px * 100.0), 1), - "vegetation_pct": round(float(veg_px / total_px * 100.0), 1), - "builtup_pct": round(float(built_px / total_px * 100.0), 1), - } - - @classmethod - def inspect_pixel( - cls, - lat: float, - lon: float, - bbox: List[float], - file_path: Optional[Path] = None, - pil_img: Optional[Image.Image] = None, - ) -> Dict[str, Any]: - """ - Extracts pixel inspection data (Lat/Lon, RGB, NDVI, NDWI, NDBI, SAR dB, Land Cover) - at exact geographical query point. - """ - if pil_img is None: - if file_path and file_path.exists(): - pil_img = cls.load_raster_as_pil(file_path) - else: - # Default synthetic tile for inspection - arr = np.zeros((256, 256, 3), dtype=np.uint8) - arr[:, :, 0] = 120 - arr[:, :, 1] = 160 - arr[:, :, 2] = 200 - pil_img = Image.fromarray(arr) - - w, h = pil_img.size - min_lon, min_lat, max_lon, max_lat = bbox - - # Map Lat/Lon to pixel (x, y) - lon_span = max(1e-6, max_lon - min_lon) - lat_span = max(1e-6, max_lat - min_lat) - - rel_x = (lon - min_lon) / lon_span - rel_y = (max_lat - lat) / lat_span - - px = int(np.clip(rel_x * w, 0, w - 1)) - py = int(np.clip(rel_y * h, 0, h - 1)) - - arr = np.asarray(pil_img, dtype=np.float32) / 255.0 - r = float(arr[py, px, 0]) - g = float(arr[py, px, 1]) - b = float(arr[py, px, 2]) - - albedo = round((r + g + b) / 3.0, 3) - ndvi = round(float((g - r) / (g + r + 1e-5)), 3) - ndwi = round(float((g - b) / (g + b + 1e-5)), 3) - ndbi = round(float((r - g) / (r + g + 1e-5)), 3) - sar_db_proxy = round(float(10.0 * math.log10(max(1e-5, albedo ** 2)) - 14.0), 1) - - if ndwi > 0.05: - land_cover = "Open Water / Specular Drainage" - elif ndvi > 0.15: - land_cover = "Active Crop / Vegetative Canopy" - elif ndbi > 0.08: - land_cover = "Built-up Structure / Urban Footprint" - else: - land_cover = "Arid Soil / Ground Surface" - - return { - "coordinates": {"lat": round(lat, 5), "lon": round(lon, 5)}, - "pixel": {"x": px, "y": py, "width": w, "height": h}, - "rgb": [int(r * 255), int(g * 255), int(b * 255)], - "indices": { - "albedo": albedo, - "ndvi": ndvi, - "ndwi": ndwi, - "ndbi": ndbi, - "sar_backscatter_proxy_db": sar_db_proxy, - "sar_db_note": "optical-derived proxy, not a SAR measurement", - }, - "land_cover_class": land_cover, - } diff --git a/backend/app/engine/sar_fusion.py b/backend/app/engine/sar_fusion.py deleted file mode 100644 index b7809ec..0000000 --- a/backend/app/engine/sar_fusion.py +++ /dev/null @@ -1,254 +0,0 @@ -""" -SatQuery AI - SAR Radar Processing & Cross-Modal Cloud Piercing Engine -Target: SIH26167 (ISRO / Space Applications Centre) - -Implements Lee speckle filtering, dual-polarization structural detection, -and optical-SAR cloud penetration cross-analysis. -""" - -import math -from typing import Dict, Any, List, Optional -import numpy as np -from PIL import Image -from scipy.ndimage import uniform_filter, label, find_objects -import rasterio.features -from rasterio.transform import from_bounds -from shapely.geometry import Polygon, MultiPolygon, mapping, shape - - -class SARCloudPiercingEngine: - """Specialist engine for Sentinel-1 C-SAR radar backscatter processing and optical cloud piercing.""" - - @staticmethod - def lee_filter(img_arr: np.ndarray, size: int = 5, damping: float = 1.0) -> np.ndarray: - """ - Applies standard Lee speckle filter to radar intensity. - Smooths multiplicative noise while preserving sharp structural edges. - """ - mean = uniform_filter(img_arr, size=size) - mean_sq = uniform_filter(img_arr ** 2, size=size) - var = np.maximum(0.0, mean_sq - mean ** 2) - - # Overall noise variance estimation - overall_var = np.var(img_arr) - weights = var / (var + (overall_var / damping) + 1e-7) - weights = np.clip(weights, 0.0, 1.0) - - filtered = mean + weights * (img_arr - mean) - return np.clip(filtered, 0.0, 1.0) - - @classmethod - def analyze_crossmodal( - cls, - sar_img: Image.Image, - optical_img: Optional[Image.Image] = None, - bbox: Optional[List[float]] = None, - radar_threshold: float = 0.65, - sensor_label: Optional[str] = None, - ) -> Dict[str, Any]: - """ - Executes cross-modal analysis fusing SAR backscatter with optical imagery. - Detects dielectric targets beneath clouds and calculates pierced cloud metrics. - - `sensor_label` is the sensor the *sector profile declares* for this raster. - It is an attribution, not a metadata-verified fact, so the output records - `sensor_metadata_verified: False` and never invents a sensor when none is given. - """ - sensor_display = sensor_label or "Unattributed SAR (demo input — no sensor metadata)" - if sar_img.mode != "L": - sar_gray = sar_img.convert("L") - else: - sar_gray = sar_img - - sar_arr = np.asarray(sar_gray, dtype=np.float32) / 255.0 - h, w = sar_arr.shape - - # 1. Apply Lee Speckle Filter - filtered_sar = cls.lee_filter(sar_arr, size=5) - - # 2. Extract bright dielectric / double-bounce scatterers (buildings, metal, bridges) - # Radar backscatter dB equivalent: sigma0 = 10 * log10(I + 1e-5) - # High scatterers indicate man-made structural features - target_mask = filtered_sar > radar_threshold - labeled_targets, num_targets = label(target_mask) - slices = find_objects(labeled_targets) - - # 3. Analyze optical cloud cover if provided - cloud_pixels = 0 - total_pixels = w * h - if optical_img: - opt_resized = optical_img.resize((w, h), Image.Resampling.BILINEAR).convert("RGB") - opt_arr = np.asarray(opt_resized, dtype=np.float32) / 255.0 - # Simple brightness + low saturation cloud detector: high R, G, B with low color saturation - rgb_mean = np.mean(opt_arr, axis=2) - rgb_std = np.std(opt_arr, axis=2) - cloud_mask = (rgb_mean > 0.68) & (rgb_std < 0.08) - cloud_pixels = int(np.sum(cloud_mask)) - cloud_pct = round((cloud_pixels / total_pixels) * 100.0, 1) - else: - cloud_mask = None - cloud_pct = 0.0 - - # 4. Map targets to GeoJSON polygons - bbox_provided = bool(bbox) and len(bbox) == 4 and all(isinstance(v, (int, float)) for v in bbox) - if bbox_provided: - min_lon, min_lat, max_lon, max_lat = bbox - georeferencing = "image_space_pixel_to_bbox_alignment" - else: - # No bbox: keep pixel-space (image-space) geometry rather than silently - # fabricating a geospatial footprint. - min_lon, min_lat, max_lon, max_lat = 0.0, 0.0, float(w), float(h) - georeferencing = "image_space_pixel_alignment_no_bbox" - lon_span = max_lon - min_lon - lat_span = max_lat - min_lat - - # Compute physical ground sample distance (GSD) in km per pixel - lat_center = (min_lat + max_lat) / 2.0 - km_per_lat_deg = 111.32 - km_per_lon_deg = 111.32 * math.cos(math.radians(lat_center)) - gsd_lon_km = (lon_span * km_per_lon_deg) / w - gsd_lat_km = (lat_span * km_per_lat_deg) / h - pixel_area_km2 = gsd_lon_km * gsd_lat_km - - # Background clutter estimation for Signal-to-Clutter Ratio (SCR) - clutter_mask = ~target_mask - mean_clutter = float(np.mean(filtered_sar[clutter_mask])) if np.any(clutter_mask) else 0.15 - - features = [] - # Sort slices by size descending - valid_slices = [] - for idx, s in enumerate(slices): - if s is None: - continue - cnt = np.sum(labeled_targets[s] == (idx + 1)) - if cnt >= 25: - valid_slices.append((cnt, idx, s)) - - valid_slices.sort(key=lambda x: x[0], reverse=True) - - for rank, (cnt, idx, s) in enumerate(valid_slices[:25]): - ymin, ymax = s[0].start, s[0].stop - xmin, xmax = s[1].start, s[1].stop - - c_min_lon = min_lon + (xmin / w) * lon_span - c_max_lon = min_lon + (xmax / w) * lon_span - c_max_lat = max_lat - (ymin / h) * lat_span - c_min_lat = max_lat - (ymax / h) * lat_span - - # Target backscatter intensity and Signal-to-Clutter Ratio (SCR) - patch_target = (labeled_targets[s] == (idx + 1)) - mean_intensity = float(np.mean(filtered_sar[s][patch_target])) - backscatter_db = float(round(10.0 * math.log10(max(1e-4, mean_intensity)), 1)) - scr = mean_intensity / (mean_clutter + 1e-6) - scr_db = float(round(10.0 * math.log10(max(1.0, scr)), 2)) - - # Calibrated radar detection confidence based on statistical SCR - target_conf = round(float(np.clip(1.0 - np.exp(-scr / 2.5), 0.72, 0.98)), 3) - - # Metric physical area - cluster_km2 = float(round(max(0.0001, cnt * pixel_area_km2), 4)) - - # Extract true geospatial polygon using rasterio GDAL polygonization & Shapely simplification - c_transform = from_bounds(c_min_lon, c_min_lat, c_max_lon, c_max_lat, xmax - xmin, ymax - ymin) - extracted_geoms = list(rasterio.features.shapes( - patch_target.astype(np.uint8), - mask=patch_target, - transform=c_transform - )) - - if extracted_geoms: - raw_poly = shape(extracted_geoms[0][0]) - tol_deg = (lon_span / w) * 0.75 - clean_poly = raw_poly.simplify(tol_deg, preserve_topology=True) - if not clean_poly.is_valid: - clean_poly = clean_poly.buffer(0) - geom_dict = mapping(clean_poly) - if clean_poly.geom_type == "Polygon": - vertex_count = max(4, len(clean_poly.exterior.coords) - 1) - elif clean_poly.geom_type == "MultiPolygon": - vertex_count = sum(len(p.exterior.coords) - 1 for p in clean_poly.geoms) - else: - vertex_count = 4 - else: - poly_coords = [ - [round(c_min_lon, 6), round(c_min_lat, 6)], - [round(c_max_lon, 6), round(c_min_lat, 6)], - [round(c_max_lon, 6), round(c_max_lat, 6)], - [round(c_min_lon, 6), round(c_max_lat, 6)], - [round(c_min_lon, 6), round(c_min_lat, 6)], - ] - geom_dict = {"type": "Polygon", "coordinates": [poly_coords]} - vertex_count = 4 - - feature = { - "type": "Feature", - "id": f"sar-target-{rank+1}", - "properties": { - "target_id": rank + 1, - "sensor": sensor_display, - "polarization": "VV+VH Dual-Pol", - "feature_type": "Dielectric High-Backscatter Target (Hardened Structure)", - "mean_backscatter_db": backscatter_db, - "signal_to_clutter_ratio_db": scr_db, - "confidence": target_conf, - "area_km2": cluster_km2, - "pixel_count": int(cnt), - "cloud_pierced": True, - "fillColor": "#06B6D4", - "borderColor": "#06B6D4", - "stroke": "#06B6D4", - "stroke-width": 2, - "stroke-opacity": 0.9, - "fill": "#06B6D4", - "fill-opacity": 0.25, - "fillOpacity": 0.25, - "vertex_count": vertex_count, - }, - "geometry": geom_dict, - } - features.append(feature) - - geojson = { - "type": "FeatureCollection", - "features": features, - } - - # Measured efficiency of microwave SAR cloud piercing (pixel-level overlap) - if cloud_mask is not None and cloud_pixels > 0: - target_under_cloud = np.sum(target_mask & cloud_mask) - target_total = max(1, np.sum(target_mask)) - pierced_efficiency = round(float((target_under_cloud / target_total) * 100.0), 1) - else: - # Fraction of scene area covered by detected radar scatterers - pierced_efficiency = round(float((np.sum(target_mask) / total_pixels) * 100.0), 1) - - # Calibrated overall radar confidence derived from aggregate Signal-to-Clutter Ratio - overall_target_mean = float(np.mean(filtered_sar[target_mask])) if np.any(target_mask) else radar_threshold - overall_scr = overall_target_mean / (mean_clutter + 1e-6) - if features: - calibrated_overall_conf = round(float(np.clip(1.0 - np.exp(-overall_scr / 2.5), 0.72, 0.98)), 3) - else: - # No high-backscatter targets detected; reporting a fabricated 0.82 - # confidence would overclaim. Leave it explicitly unknown instead. - calibrated_overall_conf = None - - result: Dict[str, Any] = { - "features_count": len(features), - "cloud_cover_percent": cloud_pct, - "pierced_cloud_percent": pierced_efficiency, - "mean_backscatter_db": float(round(10.0 * math.log10(max(1e-4, np.mean(filtered_sar))), 1)), - "confidence": calibrated_overall_conf, - "geojson": geojson, - "sensor": sensor_display, - "sensor_source": "sector_profile_declared" if sensor_label else "unattributed", - "sensor_metadata_verified": False, - "bbox_provided": bbox_provided, - "georeferencing": georeferencing, - "imagery_is_simulated": True, - } - if features: - result["confidence_source"] = "sc_ratio_heuristic" - else: - result["detection_quality"] = "no_high_backscatter_targets_detected" - - return result diff --git a/backend/app/engine/sector_assets.py b/backend/app/engine/sector_assets.py deleted file mode 100644 index 47ece60..0000000 --- a/backend/app/engine/sector_assets.py +++ /dev/null @@ -1,552 +0,0 @@ -""" -SatQuery AI - Sector Asset Manager & Spatial Profile Registry -Target: SIH26167 (ISRO / Space Applications Centre) - -Maintains sector geospatial profiles, resolves optical/SAR rasters dynamically, -and eliminates hardcoded sample locks so spatial intelligence is authentic across -all tactical sectors (ISRO SAC, Sriharikota, Galwan Valley, Pokhran, Malacca, Brahmaputra, etc.). -""" - -import math -import zlib -from functools import lru_cache -from datetime import datetime, timedelta -from dataclasses import dataclass, field, replace -from pathlib import Path -from typing import Dict, Any, List, Optional, Tuple -import numpy as np -from PIL import Image - -from ..config import settings - - -@dataclass -class SectorProfile: - id: str - name: str - region: str - lat: float - lon: float - bounds: List[float] # [min_lon, min_lat, max_lon, max_lat] - biome: str - sensors: List[str] - active_passes: str - optical_t1_date: str - optical_t2_date: str - sar_date: str - typical_cloud_pct: float - key_features: List[str] - is_real_image: bool = False - is_simulated: bool = True - imagery_origin: str = "shared_demo_raster" - raster_is_georeferenced: bool = False - imagery_distinct: bool = False - - - -SECTOR_REGISTRY: Dict[str, SectorProfile] = { - "isro-sac": SectorProfile( - id="isro-sac", - name="ISRO Space Applications Centre (SAC)", - region="Ahmedabad, Gujarat, India", - lat=23.0225, - lon=72.5714, - bounds=[72.5000, 23.0150, 72.5400, 23.0350], - biome="Urban Institutional / Riparian", - sensors=["Sentinel-2A MSI (10m)", "Sentinel-1 C-SAR IW (Dual-Pol)"], - active_passes="Sentinel-2A at 10:44 UTC, Cartosat-3 at 14:12 UTC", - optical_t1_date="2024-03-27", - optical_t2_date="2024-05-01", - sar_date="2024-03-30", - typical_cloud_pct=8.5, - key_features=["Cleanroom Complex", "Payload Integration Facility", "Sabarmati Embankment"], - is_real_image=True, - is_simulated=False, - ), - "sdsc-sriharikota": SectorProfile( - id="sdsc-sriharikota", - name="Satish Dhawan Space Centre (SDSC SHAR)", - region="Sriharikota Island, Andhra Pradesh, India", - lat=13.7259, - lon=80.2266, - bounds=[80.2000, 13.7000, 80.2500, 13.7500], - biome="Coastal Barrier Island / Spaceport", - sensors=["Sentinel-2 MSI", "RISAT-2B X-SAR / Sentinel-1 C-SAR"], - active_passes="RISAT-2B Radar pass at 03:20 UTC", - optical_t1_date="2024-01-15", - optical_t2_date="2024-04-10", - sar_date="2024-04-12", - typical_cloud_pct=22.0, - key_features=["First Launch Pad (FLP)", "Second Launch Pad (SLP)", "Solid Propellant Plant", "Bay of Bengal Shoreline"], - ), - "galwan-sar": SectorProfile( - id="galwan-sar", - name="Galwan Valley Tactical Outpost", - region="Line of Actual Control, Ladakh", - lat=34.7667, - lon=78.2500, - bounds=[78.2200, 34.7400, 78.2800, 34.7900], - biome="High-Altitude Alpine Ridge / Permafrost Gorge", - sensors=["Sentinel-1B IW C-SAR (5.405 GHz)", "RISAT-1A SAR"], - active_passes="Sentinel-1B IW Ground Range Detected", - optical_t1_date="2023-10-12", - optical_t2_date="2024-05-20", - sar_date="2024-05-22", - typical_cloud_pct=45.0, - key_features=["All-Weather Roadway Causeway", "Hardened Bunkers", "River Confluence", "Scree Ridgelines"], - ), - "pokhran-range": SectorProfile( - id="pokhran-range", - name="Pokhran Strategic Range", - region="Thar Desert, Rajasthan, India", - lat=27.0600, - lon=71.7500, - bounds=[71.7200, 27.0300, 71.7800, 27.0900], - biome="Hyper-Arid Sand Desert / Test Enclosure", - sensors=["Sentinel-2 MSI", "TerraSAR-X High-Res Stripmap"], - active_passes="TerraSAR-X High-Res Stripmap at 17:05 UTC", - optical_t1_date="2024-01-20", - optical_t2_date="2024-04-25", - sar_date="2024-04-28", - typical_cloud_pct=2.0, - key_features=["Subterranean Shaft Enclosures", "Security Perimeter Arrays", "Dune Sand Formations"], - ), - "malacca-chokepoint": SectorProfile( - id="malacca-chokepoint", - name="Malacca Strait Maritime Corridor", - region="Strait of Malacca / International Waters", - lat=2.5000, - lon=101.5000, - bounds=[101.4500, 2.4500, 101.5500, 2.5500], - biome="Equatorial Maritime Shipping Chokepoint", - sensors=["Sentinel-1 SAR Maritime Mode (VV/VH)", "Sentinel-2 MSI"], - active_passes="Sentinel-1 SAR Maritime Vessel Detector", - optical_t1_date="2024-02-14", - optical_t2_date="2024-05-12", - sar_date="2024-05-15", - typical_cloud_pct=65.0, - key_features=["VLCC Supertankers", "Container Transshipment Convoys", "Navigational Separation Scheme"], - ), - "brahmaputra-flood": SectorProfile( - id="brahmaputra-flood", - name="Brahmaputra Floodplain Basin", - region="Assam Valley, India", - lat=26.1500, - lon=91.7700, - bounds=[91.7300, 26.1200, 91.8100, 26.1800], - biome="Braided Riverine Wetlands / Alluvial Floodplain", - sensors=["Sentinel-1 Dual-Pol (VV/VH) Water Mask", "Sentinel-2 MSI"], - active_passes="Sentinel-1 Dual-Pol (VV/VH) Water Mask", - optical_t1_date="2024-03-01", - optical_t2_date="2024-06-15", - sar_date="2024-06-18", - typical_cloud_pct=78.0, - key_features=["Inundated Embankments", "Braided River Channels", "Submerged Agricultural Chars"], - ), - "diego-garcia": SectorProfile( - id="diego-garcia", - name="Diego Garcia Naval Facility", - region="BIOT / Indian Ocean", - lat=-7.3195, - lon=72.4228, - bounds=[72.3900, -7.3400, 72.4500, -7.3000], - biome="Coral Atoll Lagoon / Maritime Base", - sensors=["Pleiades Neo 30cm Optical", "Sentinel-1 C-SAR"], - active_passes="Pleiades Neo 30cm Optical Pass", - optical_t1_date="2024-02-01", - optical_t2_date="2024-04-20", - sar_date="2024-04-22", - typical_cloud_pct=35.0, - key_features=["3,600m Strategic Runway", "Deepwater Berth", "Lagoon Anchorage"], - ), - "taiwan-strait": SectorProfile( - id="taiwan-strait", - name="Taiwan Strait Demarcation", - region="Taiwan Strait Maritime Sector", - lat=24.2000, - lon=119.8000, - bounds=[119.7500, 24.1500, 119.8500, 24.2500], - biome="Littoral Maritime Corridor", - sensors=["Sentinel-1 SAR IW Dual-Pol", "Sentinel-2 MSI"], - active_passes="Sentinel-1 SAR IW Intercept Node", - optical_t1_date="2024-02-10", - optical_t2_date="2024-05-18", - sar_date="2024-05-20", - typical_cloud_pct=52.0, - key_features=["Median Line Transit Patrols", "Fishing Fleet Flotillas", "Coast Guard Interceptors"], - ), - "suez-canal": SectorProfile( - id="suez-canal", - name="Suez Canal / Great Bitter Lake", - region="Sinai / Egypt", - lat=30.3300, - lon=32.3500, - bounds=[32.3000, 30.3000, 32.4000, 30.3600], - biome="Engineered Maritime Canal / Desert Transit", - sensors=["Sentinel-2 Multispectral", "Sentinel-1 SAR"], - active_passes="Sentinel-2 Multispectral Overflight", - optical_t1_date="2024-02-22", - optical_t2_date="2024-05-10", - sar_date="2024-05-14", - typical_cloud_pct=10.0, - key_features=["Canal Bypass Channel", "Revetment Infrastructure", "Vessel Convoy Queue"], - ), - "joshimath-subsidence": SectorProfile( - id="joshimath-subsidence", - name="Joshimath Himalayan Subsidence Zone", - region="Chamoli District, Uttarakhand, India", - lat=30.5564, - lon=79.5667, - bounds=[79.5400, 30.5300, 79.5900, 30.5800], - biome="High-Altitude Fragile Slope / Tectonic Fault", - sensors=["Sentinel-1 C-SAR IW (GRD)", "Sentinel-2 L2A Multispectral"], - active_passes="Sentinel-1A IW Ascending Pass (12-day repeat cycle)", - optical_t1_date="2023-01-10", - optical_t2_date="2024-05-15", - sar_date="2024-05-18", - typical_cloud_pct=38.0, - key_features=["Sunil Ward Slope", "Alaknanda River Gorge", "Cracked Masonry Zones", "Main Central Thrust (MCT)"], - ), - "siachen-glacier": SectorProfile( - id="siachen-glacier", - name="Siachen Glacier Strategic Icefield", - region="Karakoram Range, Ladakh, India", - lat=35.5000, - lon=77.0000, - bounds=[76.9000, 35.4000, 77.1000, 35.6000], - biome="Perennial Alpine Glacier / Ice Crevasse Field", - sensors=["RISAT-1A C-Band Hybrid Polarimetric SAR", "Sentinel-1 IW GRD", "Cartosat-2S PAN"], - active_passes="RISAT-1A Hybrid Polarimetric SAR at 04:15 UTC", - optical_t1_date="2023-08-20", - optical_t2_date="2024-06-10", - sar_date="2024-06-12", - typical_cloud_pct=55.0, - key_features=["Central Moraine", "Crevasse Dielectric Backscatter", "Glacial Tongue Snout", "Sub-zero Tactical Outposts"], - ), -} - - -class SectorAssetManager: - """Manages sector-specific remote-sensing rasters and metadata.""" - - @classmethod - def get_profile(cls, sector_id: Optional[str], bbox: Optional[List[float]] = None) -> SectorProfile: - """Finds matching profile by ID or by closest geographic centroid.""" - if sector_id and sector_id in SECTOR_REGISTRY: - return SECTOR_REGISTRY[sector_id] - - if bbox and len(bbox) == 4: - c_lon = (bbox[0] + bbox[2]) / 2.0 - c_lat = (bbox[1] + bbox[3]) / 2.0 - best_id = "isro-sac" - best_dist = 1e9 - for sid, prof in SECTOR_REGISTRY.items(): - d = (c_lon - prof.lon) ** 2 + (c_lat - prof.lat) ** 2 - if d < best_dist: - best_dist = d - best_id = sid - # If distance is reasonably close, return that profile with adjusted bounds - prof = SECTOR_REGISTRY[best_id] - return SectorProfile( - id=prof.id if best_dist < 1.0 else "custom-aoi", - name=prof.name if best_dist < 1.0 else f"Custom AOI [{c_lat:.2f}N, {c_lon:.2f}E]", - region=prof.region if best_dist < 1.0 else "User Specified Coordinates", - lat=c_lat, - lon=c_lon, - bounds=[round(b, 4) for b in bbox], - biome=prof.biome, - sensors=prof.sensors, - active_passes=prof.active_passes, - optical_t1_date=prof.optical_t1_date, - optical_t2_date=prof.optical_t2_date, - sar_date=prof.sar_date, - typical_cloud_pct=prof.typical_cloud_pct, - key_features=prof.key_features, - is_real_image=prof.is_real_image if best_dist < 1.0 else False, - is_simulated=prof.is_simulated if best_dist < 1.0 else True, - imagery_origin="shared_ahmedabad_baseline", - raster_is_georeferenced=False, - imagery_distinct=False, - ) - - return SECTOR_REGISTRY["isro-sac"] - - @classmethod - def get_sector_rasters( - cls, - sector_id: Optional[str], - bbox: Optional[List[float]] = None - ) -> Tuple[SectorProfile, Optional[Image.Image], Optional[Image.Image], Optional[Image.Image]]: - """ - Returns (profile, optical_t1, optical_t2, sar_img) for the requested sector or AOI. - """ - profile = cls.get_profile(sector_id, bbox) - - # For isro-sac, prefer real verified sample data on disk - if profile.id == "isro-sac": - opt1_path = settings.sample_dir / "optical" / "sentinel2_ahmedabad_t1_20240327.jpg" - opt2_path = settings.sample_dir / "optical" / "sentinel2_ahmedabad_t2_20240501.jpg" - sar_path = settings.sample_dir / "sar" / "sentinel1_sar_ahmedabad_20240330.png" - t1 = cls._load_image(opt1_path) - t2 = cls._load_image(opt2_path) - sar = cls._load_image(sar_path) - if t1 and t2 and sar: - profile = replace( - profile, - imagery_origin="isro-sac_real_acquisitions", - raster_is_georeferenced=False, - imagery_distinct=True, - ) - return profile, t1, t2, sar - - # Check sector directory - sector_dir = settings.sample_dir / "sectors" / profile.id - sector_dir.mkdir(parents=True, exist_ok=True) - opt1_path = sector_dir / "optical_t1.jpg" - opt2_path = sector_dir / "optical_t2.jpg" - sar_path = sector_dir / "sar.png" - - sector_t1 = cls._load_image(opt1_path) - sector_t2 = cls._load_image(opt2_path) - sector_sar = cls._load_image(sar_path) - - t1 = sector_t1 - t2 = sector_t2 - sar = sector_sar - - # Fallback to authentic baseline Sentinel-2 / Sentinel-1 rasters if sector-specific imagery is not yet cached - used_fallback = False - if not t1: - t1 = cls._load_image(settings.sample_dir / "optical" / "sentinel2_ahmedabad_t1_20240327.jpg") - used_fallback = True - if not t2: - t2 = cls._load_image(settings.sample_dir / "optical" / "sentinel2_ahmedabad_t2_20240501.jpg") - used_fallback = True - if not sar: - sar = cls._load_image(settings.sample_dir / "sar" / "sentinel1_sar_ahmedabad_20240330.png") - used_fallback = True - - # Record provenance without mutating the shared registry profile - if used_fallback: - profile = replace( - profile, - imagery_origin="shared_ahmedabad_baseline", - raster_is_georeferenced=False, - imagery_distinct=False, - ) - else: - group = cls._sector_imagery_group(profile.id, sector_t1) - distinct = len(group) == 1 - profile = replace( - profile, - imagery_origin=( - f"sector_files:{profile.id}" - if distinct - else f"shared_demo_raster[{','.join(group)}]" - ), - raster_is_georeferenced=False, - imagery_distinct=distinct, - ) - - return profile, t1, t2, sar - - @staticmethod - def _image_fingerprint(img: Optional[Image.Image]) -> Optional[int]: - """Stable zlib.crc32 fingerprint of a normalized RGB image array.""" - if img is None: - return None - return zlib.crc32(np.asarray(img).tobytes()) & 0xFFFFFFFF - - @classmethod - @lru_cache(maxsize=1) - def _sector_fingerprint_map(cls) -> Dict[int, Tuple[str, ...]]: - """Fingerprint -> sorted tuple of sector ids whose optical_t1 is byte-identical. - - Built once per process from the on-disk sector rasters. Used to detect - cross-sector imagery sharing (e.g. joshimath-subsidence & custom-aoi now - share the same bytes), so provenance can report honest distinctness. - """ - sectors_root = settings.sample_dir / "sectors" - buckets: Dict[int, List[str]] = {} - if sectors_root.is_dir(): - for sector_dir in sorted(sectors_root.iterdir()): - # isro-sac is served via its real acquisition branch, not its sector file - if sector_dir.name == "isro-sac": - continue - t1_path = sector_dir / "optical_t1.jpg" - if not t1_path.exists(): - continue - fp = cls._image_fingerprint(cls._load_image(t1_path)) - if fp is None: - continue - buckets.setdefault(fp, []).append(sector_dir.name) - return {fp: tuple(sorted(ids)) for fp, ids in buckets.items()} - - @classmethod - def _sector_imagery_group(cls, sector_id: str, sector_t1: Optional[Image.Image]) -> Tuple[str, ...]: - """Ids of sectors (including this one) sharing this exact optical_t1 footprint.""" - fp = cls._image_fingerprint(sector_t1) - if fp is None: - return (sector_id,) - ids = cls._sector_fingerprint_map().get(fp) - return ids if ids else (sector_id,) - - @classmethod - def _sector_imagery_is_distinct(cls, sector_id: str, sector_t1: Optional[Image.Image]) -> bool: - """True only when no other sector shares these exact raster bytes. - - Distinct from the Ahmedabad baseline is NOT sufficient: several sectors can - share one baseline copy and then answer as their own geology. Genuine - distinctness requires the imagery to be unique among all sectors. - """ - return len(cls._sector_imagery_group(sector_id, sector_t1)) == 1 - - @classmethod - def get_sector_band_image( - cls, - sector_id: Optional[str], - band: str - ) -> Tuple[SectorProfile, Optional[Image.Image]]: - """ - Returns the calibrated sensor band image (RGB, NIR, SAR, T1, T2) for a sector. - For NIR, synthesizes Color-Infrared (CIR) where vegetation has strong infrared return. - """ - profile, t1, t2, sar = cls.get_sector_rasters(sector_id) - band_upper = (band or "RGB").upper() - - if band_upper in ("RGB", "OPTICAL", "T2"): - return profile, t2 or t1 - elif band_upper == "T1": - return profile, t1 or t2 - elif band_upper in ("SAR", "RADAR"): - return profile, sar - elif band_upper == "NIR": - # Color-Infrared (CIR) false-color composite - base = t2 or t1 - if base: - arr = np.array(base) - r = arr[..., 0].astype(float) - g = arr[..., 1].astype(float) - b = arr[..., 2].astype(float) - # Vegetation reflects heavily in NIR - veg_factor = np.clip((g * 1.5 - r * 0.5) / 255.0, 0.0, 1.0) - nir_ch = np.clip(r * 0.35 + g * 1.15 + veg_factor * 85.0, 0, 255).astype(np.uint8) - red_ch = np.clip(r * 0.85 + 20, 0, 255).astype(np.uint8) - grn_ch = np.clip(b * 0.70, 0, 255).astype(np.uint8) - cir = Image.fromarray(np.stack([nir_ch, red_ch, grn_ch], axis=-1)) - return profile, cir - return profile, None - - return profile, t2 or t1 - - @classmethod - def get_sector_timeline( - cls, - sector_id: Optional[str], - time_range: str = "30d" - ) -> Dict[str, Any]: - """ - Returns dense chronological satellite constellation passes spanning - Sentinel-2A/B, Sentinel-1 C-SAR, Cartosat-2S/3, RISAT-1A, and Landsat-9. - Generates 15 to 120+ passes with authentic timestamps and ground delta metrics. - """ - profile = cls.get_profile(sector_id) - try: - end_dt = datetime.fromisoformat(profile.optical_t2_date) - except Exception: - end_dt = datetime(2024, 5, 1, 10, 30) - - tr = (time_range or "30d").lower() - if tr == "24h": - start_dt = end_dt - timedelta(days=1) - target_count = 8 - elif tr == "7d": - start_dt = end_dt - timedelta(days=7) - target_count = 20 - elif tr == "30d": - start_dt = end_dt - timedelta(days=30) - target_count = 42 - elif tr == "1y": - start_dt = end_dt - timedelta(days=365) - target_count = 110 - else: # "all" - start_dt = datetime(2022, 1, 2, 8, 15) - target_count = 160 - - total_seconds = (end_dt - start_dt).total_seconds() - passes: List[Dict[str, Any]] = [] - - sensors_pool = [ - {"sensor": "Sentinel-2A MSI", "modality": "RGB", "gsd": "10m", "orbit": "Desc. Track 042", "has_cloud": True}, - {"sensor": "Sentinel-1 C-SAR", "modality": "SAR", "gsd": "10m", "orbit": "Asc. Pass 118", "has_cloud": False}, - {"sensor": "Sentinel-2B MSI (CIR)", "modality": "NIR", "gsd": "10m", "orbit": "Desc. Track 085", "has_cloud": True}, - {"sensor": "Cartosat-2S", "modality": "RGB", "gsd": "0.65m", "orbit": "Sun-Sync Orbit 97.4°", "has_cloud": True}, - {"sensor": "RISAT-1A (EOS-04)", "modality": "SAR", "gsd": "3m", "orbit": "Dawn-Dusk C-Band", "has_cloud": False}, - {"sensor": "Landsat-9 TIRS-2", "modality": "NIR", "gsd": "15m", "orbit": "WRS-2 Path 148", "has_cloud": True}, - {"sensor": "Cartosat-3 High-Res", "modality": "RGB", "gsd": "0.28m", "orbit": "Tactical Revisit Orbit", "has_cloud": True}, - ] - - # Deterministic constellation revisit schedule with authentic sensor parameters - observation_descriptions = [ - "Multispectral surface reflectance acquisition (B02-B04 RGB / B08 NIR); calibrated Top-Of-Atmosphere radiance", - "Multi-temporal repeat observation; surface spectral consistency check within nominal tolerances", - "Radiometric monitoring pass; localized spectral variance detected in NIR and visible bands", - "Target corridor orbital capture; automated cloud masking and cloud shadow screening applied", - "Co-registered cross-pass acquisition; surface reflectance and structural texture indexing", - "Synthetic Aperture Radar dual-polarization (VV/VH) backscatter sounding; all-weather dielectric map", - "Bi-temporal change detection epoch pass; high radiometric fidelity across target footprint", - ] - - # Deterministic generation grounded in authentic orbital periods - seed_base = zlib.crc32(f"{profile.id}_{tr}".encode("utf-8")) % 100000 - for i in range(target_count): - fraction = i / max(1, target_count - 1) - # Add orbital pass timing jitter - jitter_sec = ((seed_base * (i + 1) * 37) % 7200) - 3600 - current_sec = fraction * total_seconds + jitter_sec - current_sec = max(0, min(total_seconds, current_sec)) - pass_dt = start_dt + timedelta(seconds=current_sec) - - s_meta = sensors_pool[(i + seed_base) % len(sensors_pool)] - cloud_val = 0.0 if not s_meta["has_cloud"] else round(((seed_base + i * 13) % 180) / 10.0, 1) - - # Assign physical remote sensing observation description - obs_idx = (i + seed_base) % len(observation_descriptions) - obs_desc = observation_descriptions[obs_idx] - - pass_id = f"{s_meta['sensor'][:3].upper()}_{pass_dt.strftime('%Y%m%d_%H%M%S')}_{i:03d}" - passes.append({ - "id": pass_id, - "datetime": pass_dt.isoformat(), - "formattedDate": pass_dt.strftime("%d %b %Y").upper(), - "formattedTime": pass_dt.strftime("%H:%M:%S UTC"), - "sensor": s_meta["sensor"], - "modality": s_meta["modality"], - "cloudCover": cloud_val, - "deltaPercent": round(fraction * 100.0, 1), - "changeDescription": obs_desc, - "orbit": s_meta["orbit"], - "resolution": s_meta["gsd"], - "is_simulated": True, - "acquisition_type": "Simulated Constellation Orbital Schedule", - }) - - return { - "sectorId": profile.id, - "sectorName": profile.name, - "timeRange": tr, - "startDate": start_dt.strftime("%d %b %Y").upper(), - "endDate": end_dt.strftime("%d %b %Y").upper(), - "totalPasses": len(passes), - "passes": passes, - "orbitScheduleType": "Deterministic Constellation Revisit (Sun-Synchronous / Polar Repeat Orbit)", - } - - @classmethod - def _load_image(cls, path: Path) -> Optional[Image.Image]: - if path.exists(): - try: - return Image.open(path).convert("RGB") - except Exception: - pass - return None diff --git a/backend/app/logging_config.py b/backend/app/logging_config.py deleted file mode 100644 index fd1ddf4..0000000 --- a/backend/app/logging_config.py +++ /dev/null @@ -1,18 +0,0 @@ -"""Structured logging configuration — Agent B (B-9).""" -import logging -import sys - - -def setup_logging() -> None: - """Configure structured logging for the SatQuery backend.""" - logging.basicConfig( - level=logging.INFO, - format="%(asctime)s | %(levelname)-8s | %(name)s | %(message)s", - datefmt="%Y-%m-%d %H:%M:%S", - handlers=[logging.StreamHandler(sys.stdout)], - ) - # Quieten noisy libraries - logging.getLogger("uvicorn.access").setLevel(logging.WARNING) - logging.getLogger("rasterio").setLevel(logging.WARNING) - logging.getLogger("torch").setLevel(logging.WARNING) - logging.getLogger("httpx").setLevel(logging.WARNING) diff --git a/backend/app/main.py b/backend/app/main.py deleted file mode 100644 index df874bf..0000000 --- a/backend/app/main.py +++ /dev/null @@ -1,200 +0,0 @@ -""" -SatQuery AI - Production Backend Application Entrypoint -Target Problem Statement: SIH26167 (ISRO / Space Applications Centre) - -Security hardening (Agent A): - - CORS restricted to configured FRONTEND_URL (A-4) - - API key auth on protected routers (A-5) - - CSP + security headers middleware (A-8) - - Swagger docs disabled in production (A-10) - - Structured logging (B-9) - - SQLite lifespan init (B-7) - - Real async health check with dependency probes (B-10) -""" - -import os -import asyncio -import logging -from contextlib import asynccontextmanager - -from fastapi import FastAPI -from fastapi.middleware.cors import CORSMiddleware -from starlette.middleware.base import BaseHTTPMiddleware - -from .config import settings -from .logging_config import setup_logging -from .database import init_db -from .middleware.auth import verify_api_key -from .api.routes_query import router as query_router -from .api.routes_samples import router as samples_router -from .api.routes_stac import router as stac_router -from .api.routes_upload import router as upload_router -from .api.routes_benchmark import router as benchmark_router - -# Configure logging first -setup_logging() -logger = logging.getLogger(__name__) - -ENV = os.getenv("SATQUERY_ENV", "development") - - -# ── CSP & Security Headers Middleware (A-8) ──────────────────────────────────── -class SecurityHeadersMiddleware(BaseHTTPMiddleware): - async def dispatch(self, request, call_next): - response = await call_next(request) - response.headers["Content-Security-Policy"] = ( - "default-src 'self'; " - "script-src 'self' 'unsafe-inline' 'unsafe-eval'; " - "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; " - "font-src 'self' https://fonts.gstatic.com; " - "img-src 'self' https://*.arcgis.com https://server.arcgisonline.com data: blob:; " - "connect-src 'self' http://localhost:8080 http://localhost:11434; " - "worker-src 'self' blob:;" - ) - response.headers["X-Content-Type-Options"] = "nosniff" - response.headers["X-Frame-Options"] = "DENY" - response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin" - return response - - -# ── Application Lifespan (B-7) ───────────────────────────────────────────────── -@asynccontextmanager -async def lifespan(app: FastAPI): - # Startup - logger.info("SatQuery AI starting up — env=%s", ENV) - init_db() - settings.upload_dir.mkdir(parents=True, exist_ok=True) - logger.info("Upload dir ready: %s", settings.upload_dir) - yield - # Shutdown - logger.info("SatQuery AI shutting down") - - -# ── FastAPI App (A-10: no docs in production) ────────────────────────────────── -app = FastAPI( - title=settings.app_name, - version=settings.version, - description=settings.description, - docs_url="/docs" if ENV != "production" else None, - redoc_url="/redoc" if ENV != "production" else None, - lifespan=lifespan, -) - -# ── CORS Middleware (A-4) ────────────────────────────────────────────────────── -FRONTEND_URL = os.getenv("FRONTEND_URL", "http://localhost:3000") -allowed_origins = list(dict.fromkeys([ - FRONTEND_URL, - "http://localhost:3000", - "http://127.0.0.1:3000", - "http://localhost:5173", - "http://127.0.0.1:5173", -])) -app.add_middleware( - CORSMiddleware, - allow_origins=allowed_origins, - allow_credentials=True, - allow_methods=["GET", "POST", "PUT", "DELETE"], - allow_headers=["*"], -) - -# ── Security Headers (A-8) ──────────────────────────────────────────────────── -app.add_middleware(SecurityHeadersMiddleware) - -# ── Apply auth to protected routers (A-5) ───────────────────────────────────── -# Samples and STAC are open (no auth needed for read-only public data) -query_router.dependencies.append(verify_api_key) # type: ignore[arg-type] -upload_router.dependencies.append(verify_api_key) # type: ignore[arg-type] -benchmark_router.dependencies.append(verify_api_key) # type: ignore[arg-type] - -# ── Register Routers ────────────────────────────────────────────────────────── -app.include_router(query_router) -app.include_router(samples_router) -app.include_router(stac_router) -app.include_router(upload_router) -app.include_router(benchmark_router) - - -# ── Root ────────────────────────────────────────────────────────────────────── -@app.get("/") -def root_status(): - return { - "app": settings.app_name, - "version": settings.version, - "status": "operational", - "theme": "Space Technology (SIH26167 - ISRO / SAC)", - "endpoints": { - "health": "/api/health", - "query": "/api/query", - "samples": "/api/samples/manifest", - "stac_search": "/api/stac/search", - }, - } - - -# ── Real Health Check (B-10) ────────────────────────────────────────────────── -@app.get("/api/health") -async def health_check(): - """Health check with real dependency probes.""" - checks: dict = {} - - # Upload dir writable - try: - settings.upload_dir.mkdir(parents=True, exist_ok=True) - checks["upload_dir"] = "ok" - except Exception: - checks["upload_dir"] = "error" - - # Ollama reachable - try: - import httpx - async with httpx.AsyncClient(timeout=2.0) as client: - resp = await client.get(f"{settings.ollama_url}/api/tags") - checks["ollama"] = "ok" if resp.status_code == 200 else "unreachable" - except Exception: - checks["ollama"] = "unreachable" - - # STAC element84 reachable - try: - import httpx - async with httpx.AsyncClient(timeout=5.0) as client: - resp = await client.get(settings.stac_element84_url.replace("/search", "/")) - checks["stac_element84"] = "ok" if resp.status_code == 200 else "unreachable" - except Exception: - checks["stac_element84"] = "unreachable" - - overall = "healthy" if all(v == "ok" for v in checks.values()) else "degraded" - bhuvan_configured = bool(settings.bhuvan_api_key.strip()) - mosdac_configured = bool(settings.mosdac_username.strip() and settings.mosdac_password.strip()) - live_stac = "online" if checks.get("stac_element84") == "ok" else "standby" - - return { - "status": overall, - "checks": checks, - "live_stac_streaming": live_stac, - "integrations": { - "bhuvan_wms": { - "configured": bhuvan_configured, - "status": "configured" if bhuvan_configured else "not_configured", - "details": "BHUVAN_API_KEY present in backend/.env" if bhuvan_configured else "Requires BHUVAN_API_KEY in backend/.env", - }, - "mosdac": { - "configured": mosdac_configured, - "status": "configured" if mosdac_configured else "not_configured", - "details": "MOSDAC credentials configured" if mosdac_configured else "Requires MOSDAC credentials in backend/.env", - }, - }, - "version": settings.version, - "environment": ENV, - "sample_data_ready": (settings.sample_dir / "sample_manifest.json").exists(), - "supported_sensors": [ - "Sentinel-2 MSI (Multispectral Optical)", - "Sentinel-1 C-SAR (Synthetic Aperture Radar)", - "Cartosat-2S / 3 (Sub-meter Optical)", - "RISAT-1A / EOS-04 (C-band Hybrid Polarimetric SAR)", - ], - } - - -if __name__ == "__main__": - import uvicorn - uvicorn.run("backend.app.main:app", host=settings.host, port=settings.port, reload=True) diff --git a/backend/app/middleware/__init__.py b/backend/app/middleware/__init__.py deleted file mode 100644 index 93fa6f7..0000000 --- a/backend/app/middleware/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# Middleware package diff --git a/backend/app/middleware/auth.py b/backend/app/middleware/auth.py deleted file mode 100644 index 6267f0c..0000000 --- a/backend/app/middleware/auth.py +++ /dev/null @@ -1,23 +0,0 @@ -"""API Key authentication middleware — Agent A (A-5).""" -import os -from fastapi import Request, HTTPException, Security -from fastapi.security import APIKeyHeader - -API_KEY = os.getenv("SATQUERY_API_KEY", "") -api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False) - - -async def verify_api_key(api_key: str = Security(api_key_header)): - """Require a valid API key for protected endpoints. - - If SATQUERY_API_KEY is not configured (development), all requests are allowed. - """ - if not API_KEY: - # Development mode: no key configured, allow all - return True - if api_key != API_KEY: - raise HTTPException( - status_code=401, - detail="Invalid or missing API key. Provide X-API-Key header.", - ) - return True diff --git a/backend/app/models/registry.py b/backend/app/models/registry.py deleted file mode 100644 index d3eb3bd..0000000 --- a/backend/app/models/registry.py +++ /dev/null @@ -1,85 +0,0 @@ -""" -SatQuery AI - Canonical Model & Tool Registry -Target: SIH26167 (ISRO / Space Applications Centre) §4, §6 - -Provides a single authoritative registry for all operational specialist algorithms, -neural foundation backbones, and digital signal processing (DSP) pipelines. -Eliminates fabricated model provenance, ensuring 100% honesty across DAG planning, -evidence synthesis, telemetry, and frontend HUD displays. -""" - -from typing import Dict, Any - - -MODEL_REGISTRY: Dict[str, Dict[str, Any]] = { - "optical_vqa": { - "id": "remote_clip_vit_b32_vqa", - "canonical_name": "RemoteCLIP-ViT-B/32 (RS Foundation Backbone + BigEarthNet VQA Adapter)", - "short_name": "RemoteCLIP-ViT-B/32 VQA", - "task": "Single-Image Optical Visual Question Answering", - "modality": "single_image", - "algorithm_type": "Neural Dual-Tower Transformer (ViT-B/32 + Text Transformer)", - "provenance": "RemoteCLIP-ViT-B/32 remote-sensing foundation backbone + BigEarthNet domain adapter fine-tuned on 84 real samples (58 train / 26 eval; see data/weights/training_metrics.json)", - "grounding_tool": "Adaptive Connected-Component Spatial Vectorizer", - }, - "visual_grounding": { - "id": "remote_clip_visual_grounding", - "canonical_name": "Text-Guided Region Grounding & Shapely Topological Vectorizer", - "short_name": "Text-Guided Visual Grounding", - "task": "Text-Guided Bounding Box & Polygon Region Grounding", - "modality": "single_image", - "algorithm_type": "Cross-Attention Feature Heatmap & Topological Contour Boundary Extraction", - "provenance": "Multi-spectral class-activation thresholding + Shapely morphological contour extraction; no supervised grounding fine-tune", - "grounding_tool": "Shapely Boundary Contour Vectorizer", - }, - "scene_captioning": { - "id": "remote_clip_scene_captioner", - "canonical_name": "Remote-Sensing Scene Captioning & Land-Cover Multi-Spectral Profiler", - "short_name": "Scene Description Engine", - "task": "Single-Image Scene Description & Multi-Spectral Band Profiling", - "modality": "single_image", - "algorithm_type": "Generative Vision-Language Feature Synthesis + Band Ratio Analyzer", - "provenance": "Local Qwen2.5-3B (Ollama) narrative synthesis over measured multi-spectral + RemoteCLIP features; DSP-only when Ollama is offline (no scripted template)", - "grounding_tool": "Adaptive Connected-Component Spatial Vectorizer", - }, - "bitemporal_change": { - "id": "bitemporal_radiometric_otsu", - "canonical_name": "Bi-Temporal Radiometric Differencing & Otsu Adaptive Clustering", - "short_name": "BiTemporal Differencing (Otsu DSP)", - "task": "Multi-Image Temporal Change Detection & Surface Quantification", - "modality": "bitemporal", - "algorithm_type": "Classical Radiometric Differencing & Otsu Inter-Class Variance Optimization", - "provenance": "Luminance ITU-R BT.601 Differencing with Adaptive Histogram Binarization", - "grounding_tool": "Adaptive Connected-Component Spatial Vectorizer", - }, - "crossmodal_fusion": { - "id": "sar_lee_speckle_fusion", - "canonical_name": "Adaptive 5x5 Lee Speckle Filter & Dual-Pol (VV/VH) Scatterer Isolation", - "short_name": "SAR Cloud Piercing (5x5 Lee Filter)", - "task": "Cross-Modal Optical + SAR Cloud Penetration & Dielectric Target Isolation", - "modality": "cross_modal", - "algorithm_type": "Microwave Minimum Mean Square Error (MMSE) Filtering & Dielectric Backscatter Extraction", - "provenance": "5x5 Adaptive Lee Speckle Filter with Sentinel-1 Dual-Pol Ratio Analysis", - "grounding_tool": "Adaptive Connected-Component Spatial Vectorizer", - }, - "sar_vqa": { - "id": "sar_polarimetric_analysis", - "canonical_name": "Adaptive 5x5 Lee Speckle Filter & Dual-Pol (VV/VH) Scatterer Isolation", - "short_name": "SAR Microwave Polarimetry", - "task": "Synthetic Aperture Radar Backscatter & Structural VQA", - "modality": "cross_modal", - "algorithm_type": "Microwave Radar Backscatter Analysis (sigma0 in dB)", - "provenance": "Sentinel-1 IW GRD Dual-Pol (VV/VH) Radiometric Backscatter Head", - "grounding_tool": "Adaptive Connected-Component Spatial Vectorizer", - }, - "spatial_vectorizer": { - "id": "spatial_vectorizer", - "canonical_name": "Adaptive Connected-Component Spatial Vectorizer", - "short_name": "Spatial Mask Vectorizer", - "task": "Raster-to-Vector Georeferenced Polygon Delineation", - "modality": "all", - "algorithm_type": "Shapely Topological Delineation with Ground Sample Distance (GSD) Area Integration", - "provenance": "Metric polygon delineation in AOI bounding-box coordinate frame (WGS84 degrees); image-space alignment, not CRS-reprojected when raster lacks georeferencing", - "grounding_tool": "Shapely & OpenCV Boundary Polygonizer", - } -} diff --git a/backend/app/models/remote_clip.py b/backend/app/models/remote_clip.py deleted file mode 100644 index beb0082..0000000 --- a/backend/app/models/remote_clip.py +++ /dev/null @@ -1,612 +0,0 @@ -""" -SatQuery AI - Remote Sensing Vision-Language Neural Model (RS-VLM) -Target: SIH26167 (ISRO Space Applications Centre §4.1, §4.2, §6, §7) - -Executes genuine dual-tower Vision-Language inference using open_clip ViT-B/32 foundation backbone, -coupled with a lightweight BigEarthNet.txt domain projection adapter on Apple Metal (MPS) / CPU. -Computes true cross-modal cosine similarity, calibrated softmax confidence, multi-spectral -indices (NDVI / NDWI / Albedo), and Shapely georeferenced boundary polygon vectorization. -Zero regex keyword classification; zero discarded neural embeddings. -""" - -import json -import logging -import math -import time -import hashlib -from pathlib import Path -from typing import Dict, Any, List, Optional, Tuple - -import numpy as np -from PIL import Image -import torch -import torch.nn as nn -import torch.nn.functional as F -import torchvision.transforms as transforms -from scipy.ndimage import gaussian_filter, label, find_objects, sobel, binary_erosion -from shapely.geometry import Polygon, MultiPolygon, mapping -from shapely.validation import make_valid - -logger = logging.getLogger(__name__) - -BASE_DIR = Path(__file__).resolve().parent.parent.parent.parent -WEIGHTS_DIR = BASE_DIR / "data" / "weights" - - -class BigEarthNetDomainAdapter(nn.Module): - """ - Trained domain adapter projecting foundation vision-language embeddings - specifically into the remote sensing multi-spectral & CORINE feature manifold. - """ - - def __init__(self, embed_dim: int = 512, hidden_dim: int = 256): - super().__init__() - self.embed_dim = embed_dim - - # Visual residual projection - self.visual_proj = nn.Sequential( - nn.Linear(embed_dim, hidden_dim), - nn.LayerNorm(hidden_dim), - nn.GELU(), - nn.Linear(hidden_dim, embed_dim), - ) - self.visual_norm = nn.LayerNorm(embed_dim) - - # Text residual projection - self.text_proj = nn.Sequential( - nn.Linear(embed_dim, hidden_dim), - nn.LayerNorm(hidden_dim), - nn.GELU(), - nn.Linear(hidden_dim, embed_dim), - ) - self.text_norm = nn.LayerNorm(embed_dim) - - # Learnable logit scale - self.logit_scale = nn.Parameter(torch.ones([]) * math.log(1 / 0.07)) - - def project_visual(self, v: torch.Tensor) -> torch.Tensor: - projected = v + self.visual_proj(v) - projected = self.visual_norm(projected) - return F.normalize(projected, p=2, dim=-1) - - def project_text(self, t: torch.Tensor) -> torch.Tensor: - projected = t + self.text_proj(t) - projected = self.text_norm(projected) - return F.normalize(projected, p=2, dim=-1) - - def forward(self, v: torch.Tensor, t: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: - z_v = self.project_visual(v) - z_t = self.project_text(t) - logit_scale = self.logit_scale.exp().clamp(max=100.0) - return z_v, z_t, logit_scale - - -class RemoteCLIPModel: - """Production Remote-Sensing Vision-Language Model running on PyTorch + Metal/CPU.""" - - _model = None - _tokenizer = None - _preprocess = None - _adapter: Optional[BigEarthNetDomainAdapter] = None - _device: Optional[str] = None - - # BigEarthNet & VRSBench Domain-Adapted Semantic Taxonomy - RS_TAXONOMY = { - "water_body": { - "label": "Open Water Body & Inundation Surface", - "prompt": "satellite remote sensing imagery of open water bodies, rivers, lakes, and inundation surfaces", - "color": "#06B6D4", - "border": "#0284C7", - }, - "institutional_facility": { - "label": "Institutional Research Facility & Built-Up Footprint", - "prompt": "satellite imagery of institutional research campuses, cleanrooms, laboratories, and large building complexes", - "color": "#3B82F6", - "border": "#2563EB", - }, - "airport_runway": { - "label": "Airfield Infrastructure & Runway Tarmac", - "prompt": "satellite imagery of airport runways, airfields, taxiway tarmac, and aviation infrastructure", - "color": "#F59E0B", - "border": "#D97706", - }, - "vegetation_canopy": { - "label": "Vegetative Canopy & Agricultural Zone", - "prompt": "satellite multispectral imagery of dense forest canopy, agricultural crop fields, and vegetative land cover", - "color": "#10B981", - "border": "#059669", - }, - "dense_urban": { - "label": "Dense Urban Settlement & Built-up Fabric", - "prompt": "satellite imagery of dense urban residential neighborhoods, continuous urban fabric, and city buildings", - "color": "#A855F7", - "border": "#7C3AED", - }, - "industrial_logistics": { - "label": "Industrial Storage & Logistics Array", - "prompt": "satellite imagery of industrial facilities, propellant tanks, warehouses, port logistics, and factories", - "color": "#EC4899", - "border": "#DB2777", - }, - "arid_barren": { - "label": "Arid Barren Terrain & Ground Surface", - "prompt": "satellite imagery of arid desert dunes, dry soil, sand surfaces, rocky quarries, and excavation ground", - "color": "#D97706", - "border": "#B45309", - }, - "cryosphere_glacier": { - "label": "Glacial Ice Field & Cryospheric Surface", - "prompt": "satellite imagery of perennial alpine glaciers, crevasse ice fields, moraines, and snow cover", - "color": "#38BDF8", - "border": "#0284C7", - } - } - - @classmethod - def get_model(cls): - """Lazy-loads and caches the neural model onto the optimal hardware device (MPS on Apple Silicon, else CPU). - - HARD REQUIREMENT: loads the real RemoteCLIP-ViT-B/32 foundation checkpoint from - data/weights/RemoteCLIP-ViT-B-32.pt. There is NO silent fallback to a stock backbone: - if the checkpoint or open_clip is unavailable, this raises, so the caller can never - mistake a generic encoder for the remote-sensing-adapted model. - """ - if cls._model is None: - cls._device = "mps" if torch.backends.mps.is_available() else "cpu" - import open_clip - - ckpt = WEIGHTS_DIR / "RemoteCLIP-ViT-B-32.pt" - if not ckpt.exists(): - raise RuntimeError( - f"RemoteCLIP foundation checkpoint not found at {ckpt}. " - "The remote-sensing-adapted backbone is mandatory (PS compliance). " - "Place RemoteCLIP-ViT-B-32.pt in the weights directory before serving." - ) - try: - # Load the actual RemoteCLIP-ViT-B/32 checkpoint (remote-sensing pre-trained), - # NOT stock ImageNet/openai weights. - root_level = logging.getLogger().getEffectiveLevel() - logging.getLogger().setLevel(logging.CRITICAL) - try: - model, _, preprocess = open_clip.create_model_and_transforms('ViT-B-32', load_weights=False) - open_clip.load_checkpoint(model, str(ckpt)) - finally: - logging.getLogger().setLevel(root_level) - cls._model = model.to(cls._device).eval() - cls._tokenizer = open_clip.get_tokenizer('ViT-B-32') - cls._preprocess = preprocess - logger.info(f"Loaded RemoteCLIP-ViT-B/32 foundation backbone on {cls._device.upper()} from {ckpt.name}") - except Exception as e: - raise RuntimeError( - f"Failed to load RemoteCLIP-ViT-B/32 checkpoint from {ckpt}: {e}" - ) from e - - # Load BigEarthNet Domain Adapter if checkpoint exists - adapter_weights = WEIGHTS_DIR / "bigearthnet_adapter.pt" - adapter = BigEarthNetDomainAdapter(embed_dim=512, hidden_dim=256).to(cls._device) - if adapter_weights.exists(): - try: - # Use weights_only=True for security (prevents pickle deserialization attacks) - try: - state_dict = torch.load(adapter_weights, map_location=cls._device, weights_only=True) - except TypeError: - # Fallback for torch < 2.6 - import warnings - warnings.warn("torch.load without weights_only=True is insecure; upgrade torch >= 2.6") - state_dict = torch.load(adapter_weights, map_location=cls._device) - adapter.load_state_dict(state_dict) - logger.info(f"Loaded trained BigEarthNet Domain Adapter from: {adapter_weights.name}") - except Exception as err: - logger.warning(f"Failed to load adapter weights: {err}") - adapter.eval() - cls._adapter = adapter - - return cls._model, cls._adapter, cls._tokenizer, cls._preprocess, cls._device or "cpu" - - @classmethod - def encode_image(cls, img: Image.Image) -> torch.Tensor: - """Encodes an image through the ViT-B/32 backbone + BigEarthNet Domain Adapter.""" - model, adapter, tokenizer, preprocess, device = cls.get_model() - if img.mode != "RGB": - img = img.convert("RGB") - if preprocess is not None: - tensor = preprocess(img).unsqueeze(0).to(device) - else: - t = transforms.Compose([ - transforms.Resize((224, 224)), - transforms.ToTensor(), - transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) - ]) - tensor = t(img).unsqueeze(0).to(device) - - with torch.no_grad(): - if hasattr(model, 'encode_image'): - raw_emb = model.encode_image(tensor) - else: - raw_emb = model(tensor) - raw_emb = F.normalize(raw_emb, p=2, dim=-1) - if adapter is not None: - z_v = adapter.project_visual(raw_emb) - else: - z_v = raw_emb - return z_v.squeeze(0).cpu() - - @classmethod - def analyze_raster_spectral(cls, img: Image.Image) -> Dict[str, float]: - """Computes genuine pixel-level remote-sensing indices from the raster.""" - if img.mode != "RGB": - img = img.convert("RGB") - arr = np.asarray(img, dtype=np.float32) / 255.0 - r, g, b = arr[:, :, 0], arr[:, :, 1], arr[:, :, 2] - - mean_albedo = float(np.mean(arr)) - # NDVI proxy: (G - R) / (G + R + 1e-5) - ndvi_map = (g - r) / (g + r + 1e-5) - mean_ndvi = float(np.mean(ndvi_map)) - # NDWI proxy: (G - B) / (G + B + 1e-5) - ndwi_map = (g - b) / (g + b + 1e-5) - mean_ndwi = float(np.mean(ndwi_map)) - - # Structural edge density via Sobel gradient - gray = 0.299 * r + 0.587 * g + 0.114 * b - grad = np.hypot(sobel(gray, 0), sobel(gray, 1)) - edge_density = float(np.mean(grad > 0.20)) - - # Pixel class coverage percentages - water_px = np.sum((ndwi_map > 0.05) & (gray < 0.40)) - veg_px = np.sum(ndvi_map > 0.10) - built_px = np.sum((grad > 0.22) & (gray > 0.35)) - total_px = arr.shape[0] * arr.shape[1] - - return { - "mean_albedo": round(mean_albedo, 3), - "mean_ndvi": round(mean_ndvi, 3), - "mean_ndwi": round(mean_ndwi, 3), - "edge_density": round(edge_density, 3), - "water_pct": round(float(water_px / total_px * 100.0), 1), - "vegetation_pct": round(float(veg_px / total_px * 100.0), 1), - "builtup_pct": round(float(built_px / total_px * 100.0), 1), - } - - @classmethod - def ground_spatial_features( - cls, - img: Image.Image, - target_class: str, - bbox: Optional[List[float]] = None, - confidence_threshold: float = 0.70, - iou_threshold: float = 0.50, - max_regions: int = 12, - class_confidence: Optional[float] = None, - ) -> Dict[str, Any]: - """ - Extracts genuine georeferenced Shapely polygon boundaries corresponding - to the target semantic class identified by spectral & neural activation maps. - Uses topological contour boundary tracing and physical GSD metric scaling. - - `class_confidence` is the image-level calibrated class posterior from the - vision-language towers. It is attached per polygon as - `confidence` with `confidence_basis: image_class_posterior`; it is NOT a - per-polygon detection score. When unavailable, `confidence` is null. - """ - if img.mode != "RGB": - img = img.convert("RGB") - w, h = img.size - arr = np.asarray(img, dtype=np.float32) / 255.0 - r, g, b = arr[:, :, 0], arr[:, :, 1], arr[:, :, 2] - gray = 0.299 * r + 0.587 * g + 0.114 * b - - grad = np.hypot(sobel(gray, 0), sobel(gray, 1)) - ndvi = (g - r) / (g + r + 1e-5) - ndwi = (g - b) / (g + b + 1e-5) - - # Dynamic activation filter per class - if target_class == "water_body": - mask = (ndwi > 0.02) & (gray < 0.42) - color = "#06B6D4" - border = "#0284C7" - cat_name = "Water Body / Specular Drainage Surface" - elif target_class in ["institutional_facility", "dense_urban"]: - mask = (grad > 0.24) | ((gray > 0.48) & (ndvi < 0.12)) - color = "#3B82F6" - border = "#2563EB" - cat_name = "Institutional Infrastructure Footprint" - elif target_class == "airport_runway": - mask = (gray > 0.50) & (grad < 0.18) & (ndvi < 0.05) - color = "#F59E0B" - border = "#D97706" - cat_name = "Runway Tarmac / Transportation Corridor" - elif target_class == "vegetation_canopy": - mask = ndvi > 0.12 - color = "#10B981" - border = "#059669" - cat_name = "Vegetative Canopy / Agricultural Cover" - elif target_class == "cryosphere_glacier": - mask = (gray > 0.65) & (b > r) - color = "#38BDF8" - border = "#0284C7" - cat_name = "Glacial Ice & Snow Field" - else: - mask = grad > 0.22 - color = "#3B82F6" - border = "#60A5FA" - cat_name = "Surface Target Cluster" - - # Fallback if too sparse - if np.sum(mask) < 20: - mask = grad > np.percentile(grad, 75) - - # Clean morphological noise - smooth_mask = gaussian_filter(mask.astype(float), sigma=1.2) > 0.35 - labeled, num_features = label(smooth_mask) - slices = find_objects(labeled) - - if not bbox or len(bbox) != 4: - bbox = [72.5000, 23.0150, 72.5400, 23.0350] - - min_lon, min_lat, max_lon, max_lat = bbox - lon_span = max_lon - min_lon - lat_span = max_lat - min_lat - - # Ground Sample Distance (GSD) physical metric calculation: - # At latitude 23° N, 1 deg lat = 110.7 km, 1 deg lon = 102.5 km. - lat_center = (min_lat + max_lat) / 2.0 - m_per_lat_deg = 111320.0 - m_per_lon_deg = 111320.0 * math.cos(math.radians(lat_center)) - gsd_x_m = (lon_span * m_per_lon_deg) / max(1, w) - gsd_y_m = (lat_span * m_per_lat_deg) / max(1, h) - pixel_area_m2 = gsd_x_m * gsd_y_m - - valid_clusters = [] - for idx, s in enumerate(slices): - if s is None: - continue - cnt = np.sum(labeled[s] == (idx + 1)) - if cnt >= 25: - valid_clusters.append((cnt, idx, s)) - - valid_clusters.sort(key=lambda x: x[0], reverse=True) - - features = [] - total_m2 = 0.0 - - for rank, (cnt, idx, s) in enumerate(valid_clusters[:max_regions]): - ymin, ymax = s[0].start, s[0].stop - xmin, xmax = s[1].start, s[1].stop - - cluster_area_m2 = round(float(cnt * pixel_area_m2), 1) - total_m2 += cluster_area_m2 - - # True topological boundary extraction using binary erosion - patch = (labeled[s] == (idx + 1)) - eroded = binary_erosion(patch) - boundary = patch & (~eroded) - by_pts, bx_pts = np.where(boundary) - - if len(by_pts) < 3: - # Fallback to bounding box rectangle - boundary_coords = [ - [round(float(min_lon + (xmin / w) * lon_span), 5), round(float(max_lat - (ymin / h) * lat_span), 5)], - [round(float(min_lon + (xmax / w) * lon_span), 5), round(float(max_lat - (ymin / h) * lat_span), 5)], - [round(float(min_lon + (xmax / w) * lon_span), 5), round(float(max_lat - (ymax / h) * lat_span), 5)], - [round(float(min_lon + (xmin / w) * lon_span), 5), round(float(max_lat - (ymax / h) * lat_span), 5)], - ] - else: - cy, cx = float(np.mean(by_pts)), float(np.mean(bx_pts)) - angles = np.arctan2(by_pts - cy, bx_pts - cx) - order = np.argsort(angles) - - # Subsample boundary points to prevent oversized GeoJSON - step = max(1, len(order) // 24) - sampled_indices = order[::step] - boundary_coords = [] - for i in sampled_indices: - abs_x = bx_pts[i] + xmin - abs_y = by_pts[i] + ymin - lon_c = min_lon + (abs_x / w) * lon_span - lat_c = max_lat - (abs_y / h) * lat_span - boundary_coords.append([round(float(lon_c), 5), round(float(lat_c), 5)]) - - if len(boundary_coords) >= 3: - boundary_coords.append(boundary_coords[0]) - poly = Polygon(boundary_coords) - if not poly.is_valid: - poly = make_valid(poly) - - coords_list = [list(pt) for pt in poly.exterior.coords] if hasattr(poly, 'exterior') else boundary_coords - - features.append({ - "type": "Feature", - "properties": { - "name": f"{cat_name} #{rank + 1}", - "class": cat_name, - "area_m2": cluster_area_m2, - "pixel_count": int(cnt), - "confidence": (round(float(min(0.98, class_confidence)), 3) if class_confidence is not None else None), - "confidence_basis": "image_class_posterior" if class_confidence is not None else "unavailable", - "fillColor": color, - "borderColor": border, - "gsd_meters": round(float((gsd_x_m + gsd_y_m) / 2.0), 2), - }, - "geometry": { - "type": "Polygon", - "coordinates": [coords_list] - } - }) - - return { - "geojson": {"type": "FeatureCollection", "features": features}, - "cluster_count": len(features), - "total_area_m2": round(total_m2, 1), - "total_area_km2": round(total_m2 / 1_000_000, 4), - } - - @classmethod - def query( - cls, - img: Image.Image, - text_query: str, - bbox: Optional[List[float]] = None, - confidence_threshold: float = 0.75, - iou_threshold: float = 0.50, - location_name: Optional[str] = None, - ) -> Dict[str, Any]: - """ - Executes genuine end-to-end Vision-Language neural inference on input raster: - 1. open_clip ViT-B/32 neural visual forward pass. - 2. BigEarthNet domain adapter visual & text contrastive projection. - 3. Multi-modal cosine similarity classification. - 4. Physically grounded spectral index verification (NDVI, NDWI, Albedo). - 5. Shapely topological polygon grounding. - 6. Deterministic cryptographic audit hash. - """ - start_time = time.perf_counter() - bbox = bbox or [72.50, 23.01, 72.54, 23.04] - loc_str = f" across {location_name}" if location_name else "" - - # 1. Load Neural Model & Preprocessor - model, adapter, tokenizer, preprocess, device = cls.get_model() - - # 2. Preprocess Image & Extract Visual Embeddings - if img.mode != "RGB": - img = img.convert("RGB") - - if preprocess is not None: - tensor = preprocess(img).unsqueeze(0).to(device) - else: - t = transforms.Compose([ - transforms.Resize((224, 224)), - transforms.ToTensor(), - transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) - ]) - tensor = t(img).unsqueeze(0).to(device) - - t_neural_start = time.perf_counter() - with torch.no_grad(): - if hasattr(model, 'encode_image'): - raw_img_emb = model.encode_image(tensor) - else: - raw_img_emb = model(tensor) - raw_img_emb = F.normalize(raw_img_emb, p=2, dim=-1) - - # Pass through BigEarthNet Domain Adapter - if adapter is not None: - z_visual = adapter.project_visual(raw_img_emb) - else: - z_visual = raw_img_emb - neural_time_ms = round((time.perf_counter() - t_neural_start) * 1000, 1) - - # 3. Encode Semantic Taxonomy via Text Tower + Domain Adapter - class_keys = list(cls.RS_TAXONOMY.keys()) - class_prompts = [cls.RS_TAXONOMY[k]["prompt"] for k in class_keys] - - with torch.no_grad(): - if tokenizer is not None and hasattr(model, 'encode_text'): - text_tokens = tokenizer(class_prompts).to(device) - raw_text_emb = model.encode_text(text_tokens) - raw_text_emb = F.normalize(raw_text_emb, p=2, dim=-1) - - if adapter is not None: - z_text = adapter.project_text(raw_text_emb) - else: - z_text = raw_text_emb - - # Tokenize user query to compute query-target cross-attention - q_tokens = tokenizer([f"Satellite imagery of {text_query}"]).to(device) - raw_q_emb = model.encode_text(q_tokens) - raw_q_emb = F.normalize(raw_q_emb, p=2, dim=-1) - z_query = adapter.project_text(raw_q_emb) if adapter is not None else raw_q_emb - - # Compute cosine similarities - logit_scale = adapter.logit_scale.exp().clamp(max=100.0) if adapter is not None else 100.0 - logits = logit_scale * (z_visual @ z_text.T) - probs = logits.softmax(dim=-1).squeeze(0) - - # Query intent cross-attention alignment - q_alignment = (z_query @ z_text.T).squeeze(0) - combined_scores = probs * (F.softmax(q_alignment * 4.0, dim=-1) + 0.30) - top_idx = int(combined_scores.argmax().item()) - matched_class = class_keys[top_idx] - calibrated_confidence = round(float(probs[top_idx].item()), 3) - else: - # Fallback if text tokenizer unavailable — refuse to fabricate a class - raise RuntimeError( - "RemoteCLIP text tower/tokenizer unavailable: cannot compute a " - "calibrated class posterior. Refusing to emit a fabricated " - "class/confidence (no silent fallback)." - ) - - # 4. Compute Physical Spectral Indices - spectral = cls.analyze_raster_spectral(img) - - # 5. Perform Shapely Spatial Grounding - t_ground_start = time.perf_counter() - grounding = cls.ground_spatial_features( - img, - target_class=matched_class, - bbox=bbox, - confidence_threshold=confidence_threshold, - iou_threshold=iou_threshold, - class_confidence=calibrated_confidence, - ) - ground_time_ms = round((time.perf_counter() - t_ground_start) * 1000, 1) - - total_elapsed_ms = round((time.perf_counter() - start_time) * 1000, 1) - - # 6. Synthesize Truthful Natural Language Evidence Answer - cl_info = cls.RS_TAXONOMY[matched_class] - n_clusters = grounding["cluster_count"] - area_km2 = grounding["total_area_km2"] - - if "water" in matched_class: - answer = ( - f"Hydrological evaluation over target AOI{loc_str} [{bbox[0]:.4f}E, {bbox[1]:.4f}N to {bbox[2]:.4f}E, {bbox[3]:.4f}N] " - f"identifies active water surface coverage of {spectral['water_pct']}% (NDWI: {spectral['mean_ndwi']:.3f}, surface albedo: {spectral['mean_albedo']:.3f}). " - f"Isolated {n_clusters} distinct open water / drainage polygon boundaries encompassing approximately {area_km2:.4f} km²." - ) - elif "runway" in matched_class: - answer = ( - f"Aviation and transportation corridor analysis{loc_str} across coordinates [{bbox[0]:.4f}E, {bbox[1]:.4f}N] " - f"identifies high-reflectance elongated tarmac structures (surface albedo: {spectral['mean_albedo']:.3f}, structural edge density: {spectral['edge_density']:.3f}). " - f"Delineated {n_clusters} runway / taxiway infrastructure polygons covering {area_km2:.4f} km²." - ) - elif "vegetation" in matched_class: - answer = ( - f"Agricultural and canopy inspection{loc_str} reveals an active vegetation fraction of {spectral['vegetation_pct']}% " - f"(mean NDVI: {spectral['mean_ndvi']:.3f}). Isolated {n_clusters} vegetative canopy boundaries covering {area_km2:.4f} km²." - ) - else: - answer = ( - f"Multi-spectral Earth observation analysis for query ('{text_query}') resolves {cl_info['label']}{loc_str} " - f"across target coordinates [{bbox[0]:.4f}E, {bbox[1]:.4f}N to {bbox[2]:.4f}E, {bbox[3]:.4f}N]. " - f"Identified {n_clusters} confirmed structure clusters (total footprint: {area_km2:.4f} km², surface albedo: {spectral['mean_albedo']:.3f}, edge complexity: {spectral['edge_density']:.3f})." - ) - - # 7. Deterministic Cryptographic Audit Hash (Reproducible) - canonical_state = { - "query": text_query.strip().lower(), - "bounds": [round(float(b), 4) for b in bbox], - "spectral": {k: round(float(v), 3) for k, v in spectral.items()}, - "matched_class": matched_class, - "cluster_count": n_clusters, - "surface_area_km2": round(area_km2, 4), - } - hash_seed = json.dumps(canonical_state, sort_keys=True).encode("utf-8") - audit_hash = f"SHA256-{hashlib.sha256(hash_seed).hexdigest()[:16].upper()}" - - return { - "answer": answer, - "matched_class": matched_class, - "class_label": cl_info["label"], - "confidence": calibrated_confidence, - "geojson": grounding["geojson"], - "cluster_count": n_clusters, - "surface_area_km2": area_km2, - "spectral_metrics": spectral, - "latency_ms": total_elapsed_ms, - "neural_latency_ms": neural_time_ms, - "vectorizer_latency_ms": ground_time_ms, - "audit_hash": audit_hash, - "device": device, - "model_architecture": "RemoteCLIP-ViT-B/32 + BigEarthNet Domain Adapter", - } diff --git a/backend/app/schemas/__init__.py b/backend/app/schemas/__init__.py deleted file mode 100644 index 8d2fd85..0000000 --- a/backend/app/schemas/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# Schemas package diff --git a/backend/app/schemas/benchmark.py b/backend/app/schemas/benchmark.py deleted file mode 100644 index bea8da0..0000000 --- a/backend/app/schemas/benchmark.py +++ /dev/null @@ -1,21 +0,0 @@ -"""Benchmark API schemas — Agent B (B-3).""" -from pydantic import BaseModel, Field -from typing import Optional, List, Dict, Any, Tuple - - -class BenchmarkRequest(BaseModel): - dataset: str = Field("internal_validation", description="Dataset identifier") - n_bootstrap: int = Field(1000, ge=100, le=10000, description="Bootstrap resampling iterations for CI") - - -class BenchmarkResponse(BaseModel): - top1_accuracy: float - top1_ci_95: Tuple[float, float] - top3_accuracy: float - f1_macro: float - f1_ci_95: Tuple[float, float] - precision_macro: float - recall_macro: float - n_samples: int - n_classes: int - methodology: str diff --git a/backend/app/schemas/query.py b/backend/app/schemas/query.py deleted file mode 100644 index b2a855b..0000000 --- a/backend/app/schemas/query.py +++ /dev/null @@ -1,20 +0,0 @@ -"""Query API schemas — Agent B (B-3).""" -from pydantic import BaseModel, Field -from typing import Optional, List, Dict, Any - - -class QueryRequest(BaseModel): - query: str = Field(..., min_length=1, description="Natural language query about satellite imagery") - sector: Optional[str] = Field(None, description="Sector identifier (e.g. 'ahmedabad')") - modality: str = Field("optical", description="Imaging modality: optical, sar, or fused") - bbox: Optional[List[float]] = Field(None, description="Bounding box [west, south, east, north]") - - -class QueryResponse(BaseModel): - status: str - query: str - answer: str - evidence: Dict[str, Any] - confidence: float - processing_time_ms: float - isro_sac_compliant: bool diff --git a/backend/app/schemas/stac.py b/backend/app/schemas/stac.py deleted file mode 100644 index 9f4bf33..0000000 --- a/backend/app/schemas/stac.py +++ /dev/null @@ -1,18 +0,0 @@ -"""STAC API schemas — Agent B (B-3).""" -from pydantic import BaseModel, Field -from typing import Optional, List, Dict, Any - - -class STACSearchRequest(BaseModel): - bbox: List[float] = Field(..., description="Bounding box [west, south, east, north]") - collections: List[str] = Field(default=["sentinel-2-l2a"], description="STAC collection IDs") - date_range: str = Field("2024-01-01/2024-12-31", description="Date range in ISO 8601 interval format") - cloud_cover: Optional[float] = Field(30.0, ge=0, le=100, description="Max cloud cover %") - limit: int = Field(10, ge=1, le=100, description="Max results to return") - - -class STACSearchResponse(BaseModel): - type: str - features: List[Dict[str, Any]] - numberMatched: Optional[int] = None - numberReturned: Optional[int] = None diff --git a/backend/app/schemas/upload.py b/backend/app/schemas/upload.py deleted file mode 100644 index 6a5a756..0000000 --- a/backend/app/schemas/upload.py +++ /dev/null @@ -1,39 +0,0 @@ -"""Upload API schemas — Agent B (B-3).""" -from pydantic import BaseModel, Field -from typing import Optional, List, Dict, Any - - -class UploadResponse(BaseModel): - status: str - file_type: str - filename: str - size_bytes: int - message: str - - -class RasterMetadata(BaseModel): - format: str - is_geotiff: bool - crs: str - bounds: List[float] - width: int - height: int - bands_count: int - gsd_meters: float - sensor: str - modality: str - - -class PixelInspectRequest(BaseModel): - lat: float - lon: float - bbox: Optional[List[float]] = None - filename: Optional[str] = None - - -class PixelInspectResponse(BaseModel): - lat: float - lon: float - rgb_values: Optional[List[int]] = None - ndvi: Optional[float] = None - land_cover_class: Optional[str] = None diff --git a/backend/app/services/__init__.py b/backend/app/services/__init__.py deleted file mode 100644 index a70b302..0000000 --- a/backend/app/services/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# Services package diff --git a/backend/app/services/query_service.py b/backend/app/services/query_service.py deleted file mode 100644 index 41c1b80..0000000 --- a/backend/app/services/query_service.py +++ /dev/null @@ -1,79 +0,0 @@ -"""Query business logic — separated from HTTP layer — Agent B (B-4).""" -import asyncio -import time -import logging -from typing import Dict, Any, Optional - -logger = logging.getLogger(__name__) - - -class QueryService: - """Encapsulates query processing logic as a thin wrapper over the agent pipeline.""" - - async def process_query( - self, - query: str, - sector_id: Optional[str] = None, - modality: str = "cross_modal", - bbox: Optional[list] = None, - uploaded_file: Optional[str] = None, - confidence_threshold: float = 0.75, - iou_threshold: float = 0.50, - radar_threshold: float = 0.65, - context_hints: Optional[Dict[str, Any]] = None, - ) -> Dict[str, Any]: - """Process a natural language query against satellite imagery. - - Offloads blocking ML work to a thread pool so the event loop stays free. - """ - start_time = time.time() - hints = dict(context_hints or {}) - - if modality == "bitemporal": - hints["has_bitemporal_pair"] = True - elif modality == "cross_modal": - hints["has_sar_pair"] = True - - ctx = { - **hints, - "modality": modality, - "sector_id": sector_id, - "uploaded_file": uploaded_file, - "confidence_threshold": confidence_threshold, - "iou_threshold": iou_threshold, - "radar_threshold": radar_threshold, - } - - try: - # Import lazily to avoid circular dependencies - from ..agent.router import AgentRouter - from ..agent.evidence_builder import EvidenceBuilder - - intent = await asyncio.to_thread(AgentRouter.classify_intent, query, hints) - ctx["intent"] = intent - - evidence = await asyncio.to_thread( - EvidenceBuilder.build_evidence, - query=query, - intent=intent, - bbox=bbox, - context_data=ctx, - ) - - logger.info( - "Query processed", - extra={"query": query[:80], "intent": str(intent), "latency_ms": round((time.time() - start_time) * 1000, 1)}, - ) - return evidence # type: ignore[return-value] - - except Exception: - logger.error("Query processing failed", exc_info=True) - return { - "status": "error", - "query": query, - "answer": "I'm sorry, I couldn't process that query. Please try again.", - "evidence": {}, - "confidence": 0.0, - "processing_time_ms": round((time.time() - start_time) * 1000, 1), - "isro_sac_compliant": False, - } diff --git a/backend/mypy.ini b/backend/mypy.ini deleted file mode 100644 index 99b9fef..0000000 --- a/backend/mypy.ini +++ /dev/null @@ -1,6 +0,0 @@ -[mypy] -ignore_missing_imports = True -follow_imports = silent -warn_redundant_casts = False -warn_unused_ignores = False -disable_error_code = var-annotated,assignment,arg-type,union-attr,misc,index diff --git a/backend/pytest.ini b/backend/pytest.ini deleted file mode 100644 index dcc7c80..0000000 --- a/backend/pytest.ini +++ /dev/null @@ -1,7 +0,0 @@ -[pytest] -testpaths = tests -pythonpath = . -markers = - integration: marks tests as integration tests requiring Ollama and full stack (deselect with '-m "not integration"') - slow: marks slow tests -addopts = -v --tb=short diff --git a/backend/requirements.txt b/backend/requirements.txt deleted file mode 100644 index 9c80046..0000000 --- a/backend/requirements.txt +++ /dev/null @@ -1,35 +0,0 @@ -# SatQuery AI Backend Dependencies -# Pinned versions for reproducible builds (Agent E — E-5) -fastapi==0.115.6 -uvicorn[standard]==0.34.0 -pydantic==2.10.5 -pydantic-settings==2.7.1 -python-multipart==0.0.20 -python-dotenv==1.0.1 -httpx==0.28.1 - -# Scientific stack -numpy==1.26.4 -scipy==1.15.1 -Pillow==11.1.0 -shapely==2.0.6 - -# Geospatial (install rasterio separately if GDAL system lib is available) -rasterio==1.4.3 - -# ML -torch==2.6.0 -torchvision==0.21.0 -open-clip-torch>=2.24.0 - -# Security -safetensors==0.4.2 -slowapi==0.1.9 - -# Logging -structlog==24.4.0 - -# Testing -pytest==8.0.0 -pytest-asyncio==0.23.8 -requests==2.31.0 diff --git a/backend/ruff.toml b/backend/ruff.toml deleted file mode 100644 index ce22da4..0000000 --- a/backend/ruff.toml +++ /dev/null @@ -1,12 +0,0 @@ -# Ruff configuration for SatQuery AI Backend -target-version = "py311" -line-length = 120 - -[lint] -select = ["E", "F"] -ignore = [ - "E501", # line too long - "E402", # module level import not at top of file - "F401", # unused imports - "F841", # unused variable -] diff --git a/backend/tests/__init__.py b/backend/tests/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/backend/tests/test_api.py b/backend/tests/test_api.py deleted file mode 100644 index 56aaee8..0000000 --- a/backend/tests/test_api.py +++ /dev/null @@ -1,535 +0,0 @@ -""" -SatQuery AI - Backend API Test Suite -Verifies health, routing, agentic classification, and sample endpoints. - -NOTE: The pipeline executes the real domain-adapted inference stack: -RemoteCLIP-ViT-B/32 foundation backbone + trained BigEarthNet domain adapter -(see backend/app/models/remote_clip.py). test_query_single_optical asserts the -model actually ran (features returned, confidence >= 0.70, models_executed -populated, audit hash computed). VQA text answers are generated by the local -neural pipeline with honest telemetry; these tests assert on execution and -routing correctness rather than on invented prose. -""" - -from fastapi.testclient import TestClient -import json -import pytest -from backend.app.main import app - -client = TestClient(app) - - -def test_root(): - response = client.get("/") - assert response.status_code == 200 - data = response.json() - assert data["app"] == "SatQuery AI" - assert data["status"] == "operational" - - -def test_health(): - response = client.get("/api/health") - assert response.status_code == 200 - data = response.json() - assert data["status"] in ("healthy", "degraded") - assert data["live_stac_streaming"] in ("online", "standby") - assert "integrations" in data - assert data["sample_data_ready"] is True - - -def test_samples_manifest(): - response = client.get("/api/samples/manifest") - assert response.status_code == 200 - data = response.json() - assert "optical_samples" in data - assert "inventory" in data - assert data["inventory"]["optical_count"] >= 2 - - -def test_samples_vqa(): - response = client.get("/api/samples/vqa") - assert response.status_code == 200 - data = response.json() - assert "vrsbench_samples" in data or "cdvqa_samples" in data - - -def test_query_single_optical(): - payload = { - "query": "Identify institutional buildings in the satellite image", - "bbox": [72.50, 23.00, 72.60, 23.08], - "modality": "single_image", - } - response = client.post("/api/query", json=payload) - assert response.status_code == 200 - data = response.json() - assert data["intent"] == "optical_vqa" - assert data["geojson"]["type"] == "FeatureCollection" - # Real RemoteCLIP model execution assertions: - assert len(data["geojson"]["features"]) > 0 - # Confidence must be a real softmax posterior in [0,1] — never a fabricated floor. - assert 0.0 <= data["confidence"] <= 1.0 - assert data["ai_engine_active"] in ("remoteclip_vlm", "ollama_qwen2.5_3b") - # Per-feature confidence must be the image-level posterior (labelled), or null. - prop = data["geojson"]["features"][0]["properties"] - assert prop.get("confidence_basis") in ("image_class_posterior", "unavailable") - if prop.get("confidence") is not None: - assert prop["confidence_basis"] == "image_class_posterior" - assert data["telemetry"]["pipeline_status"] == "operational" - assert len(data["telemetry"]["models_executed"]) > 0 - assert "audit_hash" in data - assert data["audit_hash"].startswith("SHA256-") - assert data["telemetry"]["audit_hash"] == data["audit_hash"] - - -def test_query_bitemporal_change(): - payload = { - "query": "What changed between T1 and T2 in the building area?", - "bbox": [72.50, 23.00, 72.60, 23.08], - "modality": "bitemporal", - } - response = client.post("/api/query", json=payload) - assert response.status_code == 200 - data = response.json() - assert data["intent"] == "bitemporal_change" - assert data["geojson"]["type"] == "FeatureCollection" - assert len(data["geojson"]["features"]) > 0 - assert data["telemetry"]["pipeline_status"] == "operational" - assert data["findings"]["surfaceAreaModifiedKm2"] is not None - assert data["findings"]["surfaceAreaModifiedKm2"] > 0 - # Honest DSP posterior range, not a fabricated floor/ceiling. - assert 0.0 <= data["confidence"] <= 1.0 - assert data["ai_engine_active"] in ("bitemporal_change_dsp", "ollama_qwen2.5_3b") - # Anti-fabrication: the bitemporal path is radiometric DSP, never InSAR/DInSAR. - blob = (data["answer"] + str(data["dagNodes"]) + str(data["telemetry"])).lower() - for forbidden in ("dinsar", "insar", "sbas"): - assert forbidden not in blob - - -def test_query_crossmodal_fusion(): - payload = { - "query": "Use SAR radar to pierce the heavy cloud cover and identify structures", - "bbox": [72.50, 23.00, 72.60, 23.08], - "modality": "cross_modal", - } - response = client.post("/api/query", json=payload) - assert response.status_code == 200 - data = response.json() - assert data["intent"] == "crossmodal_fusion" - assert data["geojson"]["type"] == "FeatureCollection" - assert len(data["geojson"]["features"]) > 0 - assert data["findings"]["piercedCloudPercent"] is not None - assert 0.0 <= data["findings"]["piercedCloudPercent"] <= 100.0 - - -def test_query_no_gemini_field_accepted(): - """Regression guard: the API must not require or depend on a gemini_api_key field.""" - payload = { - "query": "Analyze this scene", - "bbox": [72.50, 23.00, 72.60, 23.08], - "gemini_api_key": "should-be-ignored-or-rejected", - } - response = client.post("/api/query", json=payload) - assert response.status_code == 200 - data = response.json() - assert data["telemetry"]["pipeline_status"] == "operational" - - -def test_query_visual_grounding(): - """Verify that a region grounding query routes to visual_grounding intent and returns bounded polygons.""" - payload = { - "query": "Highlight all water bodies and outline the riverbank in this scene", - "bbox": [72.50, 23.00, 72.60, 23.08], - "modality": "single_image", - } - response = client.post("/api/query", json=payload) - assert response.status_code == 200 - data = response.json() - assert data["intent"] == "visual_grounding" - assert data["geojson"]["type"] == "FeatureCollection" - assert len(data["geojson"]["features"]) > 0 - - -def test_query_scene_captioning(): - """Verify that scene description queries route to scene_captioning intent.""" - payload = { - "query": "Describe the land-cover breakdown and major objects visible in this image", - "bbox": [72.50, 23.00, 72.60, 23.08], - "modality": "single_image", - } - response = client.post("/api/query", json=payload) - assert response.status_code == 200 - data = response.json() - assert data["intent"] == "scene_captioning" - assert len(data["answer"]) > 20 - - -def test_ai_key_endpoint_removed(): - """Ensure dead /api/settings/ai-key endpoint is completely removed (returns 404).""" - response = client.post("/api/settings/ai-key", json={"api_key": "test", "provider": "gemini"}) - assert response.status_code == 404 or response.status_code == 405 - - -def test_reproducible_audit_hash(): - """Verify that re-running identical queries produces the identical cryptographic audit hash.""" - payload = { - "query": "Identify institutional buildings in the satellite image", - "bbox": [72.50, 23.00, 72.60, 23.08], - "modality": "single_image", - } - res1 = client.post("/api/query", json=payload) - assert res1.status_code == 200 - data1 = res1.json() - - res2 = client.post("/api/query", json=payload) - assert res2.status_code == 200 - data2 = res2.json() - - assert data1["audit_hash"] == data2["audit_hash"], ( - f"Audit hashes must be identical! Got {data1['audit_hash']} vs {data2['audit_hash']}" - ) - - -def test_benchmark_catalog(): - response = client.get("/api/benchmark/catalog") - assert response.status_code == 200 - data = response.json() - assert "challenges" in data - assert data["count"] > 0 - - -def test_benchmark_evaluate_no_artificial_floor(): - """Regression guard: scores must not be artificially floored when there's no match.""" - payload = { - "query": "Did the areas of non-vegetated ground surface change?", - "ground_truth": "yes", - "modality": "bitemporal", - } - response = client.post("/api/benchmark/evaluate", json=payload) - assert response.status_code == 200 - data = response.json() - assert data["status"] == "success" - assert "score_percent" in data - assert "metrics" in data - # With no model wired in, the honest score should NOT be artificially inflated. - # (Previously this was floored at 75% regardless of actual match quality.) - assert data["score_percent"] < 75.0 or data["metrics"]["exact_match"] is True - - -def test_upload_geojson(): - geojson_content = ( - b'{"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {}, ' - b'"geometry": {"type": "Polygon", "coordinates": [[[72.5, 23.0], [72.6, 23.0], [72.6, 23.1], [72.5, 23.1], [72.5, 23.0]]]}}]}' - ) - files = {"file": ("test.geojson", geojson_content, "application/geo+json")} - response = client.post("/api/upload", files=files) - assert response.status_code == 200 - data = response.json() - assert data["file_type"] == "geojson" - assert data["features_count"] == 1 - assert data["bbox"] == [72.5, 23.0, 72.6, 23.1] - - -def test_sector_aware_spatial_grounding_galwan(): - """Verify that querying Galwan produces genuine Galwan coordinates, not Ahmedabad.""" - payload = { - "query": "Map high-altitude mountain causeway and forward outpost structures", - "sector_id": "galwan-sar", - "bbox": [78.22, 34.74, 78.28, 34.79], - } - response = client.post("/api/query", json=payload) - assert response.status_code == 200 - data = response.json() - assert data["telemetry"]["sector_id"] == "galwan-sar" - assert data["findings"]["sectorName"] == "Galwan Valley Tactical Outpost" - assert "Galwan Valley" in data["answer"] - - # Verify coordinates are in Ladakh (lon ~78, lat ~34), NOT Ahmedabad (lon ~72, lat ~23) - features = data["geojson"]["features"] - assert len(features) > 0 - first_coord = features[0]["geometry"]["coordinates"][0][0] - assert 78.0 <= first_coord[0] <= 78.5, f"Expected lon in Galwan, got {first_coord[0]}" - assert 34.5 <= first_coord[1] <= 35.0, f"Expected lat in Galwan, got {first_coord[1]}" - # Coordinate type sanity: must be Python float - assert isinstance(first_coord[0], float) - assert isinstance(first_coord[1], float) - - -def test_sector_aware_sriharikota_change(): - """Verify bi-temporal change detection at Sriharikota uses correct dates and spaceport bounds.""" - payload = { - "query": "Detect launchpad complex groundwork and assembly changes between T1 and T2", - "sector_id": "sdsc-sriharikota", - "modality": "bitemporal", - } - response = client.post("/api/query", json=payload) - assert response.status_code == 200 - data = response.json() - assert data["intent"] == "bitemporal_change" - assert data["findings"]["sectorName"] == "Satish Dhawan Space Centre (SDSC SHAR)" - assert data["findings"]["temporalInterval"] == "2024-01-15 (T1) -> 2024-04-10 (T2)" - - features = data["geojson"]["features"] - assert len(features) > 0 - first_coord = features[0]["geometry"]["coordinates"][0][0] - assert 80.1 <= first_coord[0] <= 80.4, f"Expected lon in Sriharikota, got {first_coord[0]}" - assert 13.6 <= first_coord[1] <= 13.9, f"Expected lat in Sriharikota, got {first_coord[1]}" - - -def test_sector_aware_malacca_sar_cloud_piercing(): - """Verify SAR cloud piercing over Malacca Strait detects ships and reports radar metrics.""" - payload = { - "query": "Pierce tropical cloud cover with Sentinel-1 SAR to map cargo vessel traffic", - "sector_id": "malacca-chokepoint", - } - response = client.post("/api/query", json=payload) - assert response.status_code == 200 - data = response.json() - assert data["intent"] == "crossmodal_fusion" - assert data["findings"]["sectorName"] == "Malacca Strait Maritime Corridor" - assert data["findings"]["piercedCloudPercent"] is not None - assert 0.0 <= data["findings"]["piercedCloudPercent"] <= 100.0 - - features = data["geojson"]["features"] - assert len(features) > 0 - first_coord = features[0]["geometry"]["coordinates"][0][0] - assert 101.3 <= first_coord[0] <= 101.7, f"Expected lon in Malacca Strait, got {first_coord[0]}" - assert 2.3 <= first_coord[1] <= 2.7, f"Expected lat in Malacca Strait, got {first_coord[1]}" - - -def test_bigearthnet_benchmark_evaluation(): - """Verify BigEarthNet benchmark challenges can be fetched and evaluated honestly.""" - cat_resp = client.get("/api/benchmark/catalog") - assert cat_resp.status_code == 200 - challenges = cat_resp.json()["challenges"] - ben_challenges = [c for c in challenges if c["id"].startswith("ben-") or "bigearthnet" in c.get("dataset", "").lower()] - assert len(ben_challenges) > 0, "BigEarthNet challenges must be available in catalog" - - first_ben = ben_challenges[0] - query_text = first_ben.get("question") or first_ben.get("query") - eval_resp = client.post("/api/benchmark/evaluate", json={ - "query": query_text, - "ground_truth": first_ben["ground_truth"], - "modality": first_ben.get("suggested_modality", "single_image"), - }) - assert eval_resp.status_code == 200 - eval_data = eval_resp.json() - assert eval_data["status"] == "success" - assert "score_percent" in eval_data - assert "metrics" in eval_data - - -def test_change_detection_physical_gsd_area(): - """Verify change detection computes physical GSD area and true GeoJSON polygon geometry.""" - payload = { - "query": "Detect land cover changes between T1 and T2", - "sector_id": "isro-sac", - "modality": "bitemporal", - } - response = client.post("/api/query", json=payload) - assert response.status_code == 200 - data = response.json() - features = data["geojson"]["features"] - assert len(features) > 0 - f = features[0] - # Verify geometry is valid GeoJSON Polygon with coordinates - assert f["geometry"]["type"] in ("Polygon", "MultiPolygon") - assert "area_km2" in f["properties"] - assert f["properties"]["area_km2"] > 0 - assert "pixel_count" in f["properties"] - assert f["properties"]["pixel_count"] > 0 - # Confidence is calibrated - assert 0.0 < data["confidence"] <= 1.0 - - -def test_sar_fusion_signal_to_clutter_calibration(): - """Verify SAR cross-modal analysis computes Signal-to-Clutter Ratio and calibrated confidence.""" - payload = { - "query": "Detect radar scatterers and pierce cloud cover with Sentinel-1 SAR", - "sector_id": "galwan-sar", - "modality": "crossmodal_fusion", - } - response = client.post("/api/query", json=payload) - assert response.status_code == 200 - data = response.json() - features = data["geojson"]["features"] - assert len(features) > 0 - f = features[0] - assert "signal_to_clutter_ratio_db" in f["properties"] - assert "mean_backscatter_db" in f["properties"] - assert "confidence" in f["properties"] - # Real signal-to-clutter heuristic posterior, or null when no targets detected. - if f["properties"]["confidence"] is not None: - assert 0.0 <= f["properties"]["confidence"] <= 1.0 - # Overall confidence is dynamic and honest. - assert isinstance(data["confidence"], float) - assert data["ai_engine_active"] in ("crossmodal_sar_fusion_dsp", "ollama_qwen2.5_3b") - - -def test_sector_timeline_authentic_revisit(): - """Verify sector timeline delivers authentic satellite revisit passes without fabricated tactical events.""" - response = client.get("/api/samples/sector-timeline/isro-sac?time_range=7d") - assert response.status_code == 200 - data = response.json() - assert data["sectorId"] == "isro-sac" - assert len(data["passes"]) > 0 - first_pass = data["passes"][0] - assert first_pass["is_simulated"] is True - assert "acquisition_type" in first_pass - - # Confirm sensationalized drama is eliminated across all passes - for p in data["passes"]: - desc = p["changeDescription"] - assert "fuel lines" not in desc - assert "drilling rig" not in desc - assert "bulldozer" not in desc - - -def test_inspect_pixel_endpoint(): - """Verify that inspecting a pixel point returns coordinates, spectral indices, and land cover classification.""" - payload = { - "lat": 23.025, - "lon": 72.520, - "bbox": [72.500, 23.015, 72.540, 23.035] - } - response = client.post("/api/inspect-pixel", json=payload) - assert response.status_code == 200 - data = response.json() - assert "coordinates" in data - assert "indices" in data - assert "ndvi" in data["indices"] - assert "ndwi" in data["indices"] - assert "ndbi" in data["indices"] - assert "sar_backscatter_proxy_db" in data["indices"] - assert "proxy" in data["indices"]["sar_db_note"].lower() - assert "land_cover_class" in data - - -# --------------------------------------------------------------------------- -# Anti-fabrication regression guards (SIH26167 remediation) -# --------------------------------------------------------------------------- - -def test_uploaded_garbage_tif_rejected(): - """E-1 guard: a 4-byte non-raster must be rejected, not accepted as a valid TIFF.""" - files = {"file": ("garbage.tif", b"\x00\x01\x02\x03", "image/tiff")} - response = client.post("/api/upload", files=files) - assert response.status_code == 400 - - -def test_distinct_inputs_yield_distinct_audit_hash(): - """Two genuinely different sectors must produce different evidence hashes.""" - base = {"modality": "bitemporal", "query": "Detect surface changes between the two acquisitions"} - joshi = client.post("/api/query", json={**base, "sector_id": "joshimath-subsidence"}).json() - malacca = client.post("/api/query", json={**base, "sector_id": "malacca-chokepoint"}).json() - assert joshi["audit_hash"] != malacca["audit_hash"] - - -def test_no_insar_claim_on_bitemporal(): - """No bitemporal response may claim InSAR/DInSAR/SBAS capability.""" - data = client.post("/api/query", json={ - "query": "Quantify subsidence between the two acquisitions", - "sector_id": "joshimath-subsidence", - "modality": "bitemporal", - }).json() - blob = json.dumps(data).lower() - for forbidden in ("dinsar", "insar", "sbas"): - assert forbidden not in blob - - -def test_telemetry_provenance_block_present(): - """Telemetry must carry honest imagery provenance, not bare claims.""" - data = client.post("/api/query", json={ - "query": "Assess the terrain", "sector_id": "joshimath-subsidence", - }).json() - t = data["telemetry"] - for key in ("is_real_image", "is_simulated", "imagery_origin", - "raster_is_georeferenced", "data_provenance", "live_stream_status"): - assert key in t, f"telemetry missing {key}" - - -def test_live_stream_opt_in_and_honest_default(): - """C-1 guard: live stream is off by default; opt-in returns an honest status.""" - default = client.post("/api/query", json={ - "query": "Assess the terrain", "sector_id": "joshimath-subsidence", - }).json() - assert default["live_satellite_stream"] is None - assert default["telemetry"]["live_stream_status"] == "not_requested" - - opt_in = client.post("/api/query", json={ - "query": "Assess the terrain", "sector_id": "joshimath-subsidence", - "context_hints": {"live_stream": True}, - }).json() - assert opt_in["telemetry"]["live_stream_status"] in ("online", "unavailable", "error") - if opt_in["live_satellite_stream"] is not None: - ls = opt_in["live_satellite_stream"] - assert "pil_image" not in ls - assert ls["status"] == "online" - assert ls.get("acquisition_date") is not None - - -def test_ai_status_is_probed_not_hardcoded(): - """C-2 guard: AI/stream statuses are real probe results, never '100% ONLINE'.""" - data = client.get("/api/settings/ai-status").json() - blob = json.dumps(data).lower() - assert "100%" not in blob.replace(" ", "") - for source in data.get("live_data_sources", []): - assert source["status"] in ("online", "offline", "not_configured", "configured", "standby") - assert data["local_engines"]["ollama_qwen2.5_3b"] in ("online", "offline") - - -def test_invalid_geojson_leaves_no_orphan_file(): - """Upload hygiene: a rejected GeoJSON must not persist a file on disk.""" - import backend.app.api.routes_upload as ru - before = {p.name for p in ru.UPLOAD_DIR.iterdir()} - files = {"file": ("broken.geojson", b"{not valid json", "application/geo+json")} - response = client.post("/api/upload", files=files) - assert response.status_code == 400 - after = {p.name for p in ru.UPLOAD_DIR.iterdir()} - assert after == before, f"orphaned upload: {after - before}" - - -def test_corrupt_magic_valid_tiff_rejected_without_orphan(): - """A file with a valid TIFF magic byte but unreadable body must 400 and leave no orphan.""" - import backend.app.api.routes_upload as ru - before = {p.name for p in ru.UPLOAD_DIR.iterdir()} - files = {"file": ("corrupt.tif", b"II*\x00" + b"\x00" * 60, "image/tiff")} - response = client.post("/api/upload", files=files) - assert response.status_code == 400, response.text - after = {p.name for p in ru.UPLOAD_DIR.iterdir()} - assert after == before, f"orphaned raster: {after - before}" - - -def test_query_ignores_traversal_uploaded_file(): - """Security guard: a traversal in uploaded_file must not read outside uploads.""" - response = client.post("/api/query", json={ - "query": "Assess terrain change", "modality": "bitemporal", - "sector_id": "malacca-chokepoint", "uploaded_file": "../../../../etc/passwd", - }) - assert response.status_code == 200 - assert response.json()["telemetry"]["sector_id"] == "malacca-chokepoint" - - -def test_shared_raster_sector_discloses_simulation(): - """B-2 guard: a sector whose raster bytes are shared must disclose simulation - in the answer itself and report imagery_distinct=False (not just baseline-different).""" - data = client.post("/api/query", json={ - "query": "Assess terrain change", "sector_id": "joshimath-subsidence", - "modality": "bitemporal", - }).json() - t = data["telemetry"] - assert t["is_simulated"] is True - assert t["imagery_distinct"] is False - assert "not satellite-acquired" in t["data_provenance"] - assert data["answer"].startswith("SIMULATED DEMO RASTER") - - -def test_real_acquisition_sector_is_not_labelled_simulated(): - """B-3 guard: the one real-acquisition sector must not carry a simulation disclosure.""" - data = client.post("/api/query", json={ - "query": "Assess terrain change", "sector_id": "isro-sac", - "modality": "bitemporal", - }).json() - t = data["telemetry"] - assert t["is_real_image"] is True and t["is_simulated"] is False - assert "SIMULATED DEMO RASTER" not in (data["answer"] or "") - assert "Real Satellite Acquisition" in t["data_provenance"] - diff --git a/backend/tests/test_api_contract.py b/backend/tests/test_api_contract.py deleted file mode 100644 index 5879acc..0000000 --- a/backend/tests/test_api_contract.py +++ /dev/null @@ -1,106 +0,0 @@ -"""API contract validation tests — Agent G (G-2). - -Run with: python -m pytest tests/test_api_contract.py -v -""" - -import pytest -from fastapi.testclient import TestClient - -from app.main import app - -client = TestClient(app) - - -class TestRootEndpoint: - def test_root_returns_200(self): - response = client.get("/") - assert response.status_code == 200 - data = response.json() - assert "app" in data - assert "version" in data - assert "status" in data - - def test_root_has_correct_app_name(self): - response = client.get("/") - assert response.json()["app"] == "SatQuery AI" - - -class TestHealthEndpoint: - def test_health_returns_200(self): - response = client.get("/api/health") - assert response.status_code == 200 - - def test_health_has_required_fields(self): - response = client.get("/api/health") - data = response.json() - assert "status" in data - assert "checks" in data - assert "version" in data - assert "environment" in data - - def test_health_status_is_valid(self): - response = client.get("/api/health") - data = response.json() - assert data["status"] in ("healthy", "degraded") - - def test_health_checks_are_valid_values(self): - response = client.get("/api/health") - data = response.json() - valid_values = {"ok", "error", "unreachable"} - for check_name, status in data["checks"].items(): - assert status in valid_values, ( - f"Check '{check_name}' has invalid value '{status}'" - ) - - -class TestQueryEndpoint: - def test_query_rejects_missing_body(self): - response = client.post("/api/query") - assert response.status_code == 422 # Pydantic validation error - - def test_query_rejects_empty_string(self): - response = client.post("/api/query", json={"query": ""}) - assert response.status_code in (400, 422) - - def test_query_accepts_valid_request(self): - """Query must return 200 (success) or 401 (auth required) or 500 (Ollama down).""" - response = client.post( - "/api/query", - json={"query": "What is in this satellite image?"}, - ) - assert response.status_code in (200, 401, 500) - - def test_query_response_has_required_fields_on_success(self): - response = client.post( - "/api/query", - json={"query": "What is in this satellite image?"}, - ) - if response.status_code == 200: - data = response.json() - # Must have at minimum these fields - assert "query" in data or "answer" in data - - -class TestUploadEndpoint: - def test_upload_rejects_no_file(self): - response = client.post("/api/upload") - assert response.status_code == 422 - - def test_upload_rejects_wrong_extension(self): - response = client.post( - "/api/upload", - files={"file": ("test.exe", b"content", "application/octet-stream")}, - ) - assert response.status_code == 400 - - -class TestSamplesEndpoints: - def test_samples_manifest_returns_200_or_404(self): - """Manifest endpoint — 200 if data exists, 404 if not initialised yet.""" - response = client.get("/api/samples/manifest") - assert response.status_code in (200, 404) - - def test_samples_geotiffs_returns_list(self): - response = client.get("/api/samples/geotiffs") - assert response.status_code == 200 - assert isinstance(response.json(), list) diff --git a/backend/tests/test_integration.py b/backend/tests/test_integration.py deleted file mode 100644 index 8c261a6..0000000 --- a/backend/tests/test_integration.py +++ /dev/null @@ -1,88 +0,0 @@ -"""Integration tests — full request/response cycles — Agent G (G-4). - -Run with: python -m pytest tests/test_integration.py -v -m integration -""" - -import io -import pytest -from fastapi.testclient import TestClient - -from app.main import app - -client = TestClient(app) - - -@pytest.mark.integration -class TestFullQueryCycle: - def test_query_returns_expected_structure(self): - """End-to-end: query → agent pipeline → response structure.""" - response = client.post( - "/api/query", - json={ - "query": "What changed in this area?", - "sector_id": "ahmedabad", - "modality": "cross_modal", - }, - ) - # Without Ollama running: 500 is acceptable - assert response.status_code in (200, 401, 500) - - if response.status_code == 200: - data = response.json() - assert "query" in data - assert "confidence" in data or "answer" in data - - -@pytest.mark.integration -class TestUploadAndInspect: - def test_upload_minimal_tiff_then_inspect(self): - """End-to-end: upload a minimal TIFF → inspect pixel.""" - try: - from PIL import Image - except ImportError: - pytest.skip("Pillow not available for test image creation") - - # Create a minimal valid TIFF - img = Image.new("RGB", (64, 64), color=(100, 150, 200)) - buf = io.BytesIO() - img.save(buf, format="TIFF") - buf.seek(0) - - upload_response = client.post( - "/api/upload", - files={"file": ("test_integration.tif", buf.read(), "image/tiff")}, - ) - - # Accept 200 (success) or 400 (rasterio parse error on minimal TIFF without CRS) - assert upload_response.status_code in (200, 400, 401) - - if upload_response.status_code == 200: - data = upload_response.json() - assert data.get("status") == "success" - assert "filename" in data - - # Inspect pixel - inspect_response = client.post( - "/api/inspect-pixel", - json={ - "lat": 23.02, - "lon": 72.52, - "filename": data["filename"], - }, - ) - assert inspect_response.status_code in (200, 400, 401) - - -@pytest.mark.integration -class TestHealthProbes: - def test_health_probes_complete_within_timeout(self): - """Health check must respond within 10 seconds even with Ollama unreachable.""" - import time - start = time.time() - response = client.get("/api/health") - elapsed = time.time() - start - - assert response.status_code == 200 - assert elapsed < 10.0, f"Health check took {elapsed:.1f}s — too slow" - data = response.json() - assert data["status"] in ("healthy", "degraded") diff --git a/backend/tests/test_security.py b/backend/tests/test_security.py deleted file mode 100644 index 86eecc4..0000000 --- a/backend/tests/test_security.py +++ /dev/null @@ -1,127 +0,0 @@ -"""Security regression tests — Agent G (G-1). - -These tests MUST pass before any deployment. -Run with: python -m pytest tests/test_security.py -v -""" - -import pytest -from fastapi.testclient import TestClient - -from app.main import app - -client = TestClient(app) - - -class TestPathTraversal: - """SEC-003 / SEC-005: Path traversal attacks.""" - - def test_upload_rejects_traversal_in_filename(self): - """Path traversal in upload filename must return 400.""" - response = client.post( - "/api/upload", - files={"file": ("../../etc/passwd", b"test content", "text/plain")}, - ) - assert response.status_code in (400, 413), ( - f"Expected 400 or 413, got {response.status_code}: {response.text}" - ) - - def test_upload_rejects_unsafe_extension(self): - """File extension allowlist: .exe must return 400.""" - response = client.post( - "/api/upload", - files={"file": ("evil.exe", b"MZ\x90\x00", "application/octet-stream")}, - ) - assert response.status_code == 400, ( - f"Expected 400, got {response.status_code}: {response.text}" - ) - - def test_upload_rejects_null_byte_in_filename(self): - """Null-byte injection in filename must return 400.""" - response = client.post( - "/api/upload", - files={"file": ("file\x00.php.tif", b"test", "image/tiff")}, - ) - # Should still work (null byte stripped) OR return 400 - assert response.status_code in (200, 400, 413) - - def test_samples_rejects_traversal_in_image_path(self): - """SEC-005: Path traversal in /api/samples/image endpoint.""" - response = client.get("/api/samples/image/uploads/../../.env") - assert response.status_code in (400, 404), ( - f"Expected 400 or 404, got {response.status_code}" - ) - - -class TestCORS: - """SEC-007: CORS must not use wildcard.""" - - def test_cors_does_not_allow_all_origins(self): - """CORS allow-origin must NOT be * for credentialed requests.""" - response = client.options( - "/api/health", - headers={ - "Origin": "http://evil.com", - "Access-Control-Request-Method": "GET", - }, - ) - assert response.headers.get("access-control-allow-origin") != "*", ( - "CORS wildcard detected — SEC-007 not fixed" - ) - - -class TestUploadSize: - """SEC-006: Upload size limit.""" - - def test_upload_rejects_file_over_100mb(self): - """Files larger than 100 MB must return 413.""" - large_content = b"x" * (101 * 1024 * 1024) # 101 MB - response = client.post( - "/api/upload", - files={"file": ("large.tif", large_content, "image/tiff")}, - ) - assert response.status_code == 413, ( - f"Expected 413 for oversized upload, got {response.status_code}" - ) - - -class TestAuth: - """SEC-002: Auth middleware.""" - - def test_query_requires_auth_when_key_configured(self, monkeypatch): - """When API_KEY is set, verify_api_key must raise 401 for missing/wrong keys.""" - import app.middleware.auth as auth_module - from fastapi import HTTPException - - # Patch the module-level API_KEY directly - monkeypatch.setattr(auth_module, "API_KEY", "test-secret-key-12345") - - import asyncio - - async def _test(): - # No key → should raise 401 - with pytest.raises(HTTPException) as exc_info: - await auth_module.verify_api_key(None) - assert exc_info.value.status_code == 401 - - # Wrong key → should raise 401 - with pytest.raises(HTTPException) as exc_info: - await auth_module.verify_api_key("wrong-key") - assert exc_info.value.status_code == 401 - - # Correct key → should return True - result = await auth_module.verify_api_key("test-secret-key-12345") - assert result is True - - asyncio.get_event_loop().run_until_complete(_test()) - - -class TestSecurityHeaders: - """SEC-008: Security headers must be present.""" - - def test_security_headers_on_health(self): - """Health endpoint must return security headers.""" - response = client.get("/api/health") - assert "x-content-type-options" in response.headers - assert response.headers["x-content-type-options"] == "nosniff" - assert "x-frame-options" in response.headers - assert response.headers["x-frame-options"] == "DENY" diff --git a/backend/tests/test_ui_actions.py b/backend/tests/test_ui_actions.py deleted file mode 100644 index f44e76b..0000000 --- a/backend/tests/test_ui_actions.py +++ /dev/null @@ -1,143 +0,0 @@ -""" -Contract tests for the grounded UI-action planner. - -The planner is the backend half of the "agent really controls the map" contract: -it may only emit actions whose target provably exists in the same response, and -the frontend is the only party allowed to report an action as executed. These -tests lock in the closed schema and the grounding gate so a future change cannot -silently start inventing sectors, layers, features, or benchmarks. -""" - -import pytest - -from app.agent.ui_action_planner import UIActionPlanner as P, UI_ACTION_TYPES -from app.engine.sector_assets import SECTOR_REGISTRY - -PROFILE = SECTOR_REGISTRY["joshimath-subsidence"] - -GEOJSON = { - "type": "FeatureCollection", - "features": [ - {"id": "change-feat-1", "properties": {"confidence": 0.61}}, - {"id": "change-feat-7", "properties": {"confidence": 0.94}}, - {"properties": {"confidence": 0.5}}, # unaddressable until normalized - ], -} - - -def _plan(**overrides): - kwargs = dict( - query="q", - intent="bitemporal_change", - modality="bitemporal", - profile=PROFILE, - requested_bbox=None, - geojson=GEOJSON, - live_stream=None, - ) - kwargs.update(overrides) - return P.plan(**kwargs) - - -def _types(actions): - return [a["type"] for a in actions] - - -class TestGroundingGate: - def test_rejects_nonexistent_layer(self): - ok, why = P.validate({"type": "toggle_layer", "params": {"layer_id": "no-such-layer", "visible": True}}) - assert ok is False - assert "DEFAULT_LAYERS" in why - - def test_rejects_nonexistent_sector(self): - ok, _ = P.validate({"type": "fly_to_sector", "params": {"sector_id": "atlantis", "lat": 1.0, "lon": 2.0}}) - assert ok is False - - def test_rejects_feature_absent_from_this_response(self): - ok, why = P.validate({"type": "highlight_feature", "params": {"feature_id": "feature-999"}}) - assert ok is False - assert "absent from this response" in why - - def test_never_invents_benchmark_without_real_catalog_id(self): - ok, _ = P.validate({"type": "run_benchmark", "params": {"benchmark_id": "magic-bench"}}) - assert ok is False - actions, _source = _plan(benchmark_id="magic-bench", benchmark_ids=["real-bench"]) - assert "run_benchmark" not in _types(actions) - - def test_rejects_reversed_bbox(self): - assert P.valid_bbox([72.9, 30.2, 72.1, 30.8]) is False - assert P.valid_bbox([72.1, 30.2, 72.9, 30.8]) is True - - def test_rejects_unknown_type_and_band(self): - assert P.validate({"type": "hack_the_planet", "params": {}})[0] is False - assert P.validate({"type": "set_sensor_band", "params": {"band": "X"}})[0] is False - - def test_accepts_known_targets(self): - assert P.validate({"type": "toggle_layer", "params": {"layer_id": "sentinel-sar", "visible": True}})[0] is True - assert P.validate({"type": "open_panel", "params": {"tab": "telemetry"}})[0] is True - assert P.validate({"type": "fly_to_sector", "params": {"sector_id": "joshimath-subsidence", "lat": 1.0, "lon": 2.0}})[0] is True - - -class TestPlannerDistinctness: - def test_bitemporal_and_crossmodal_differ_explainably(self): - bitemporal, _ = _plan(intent="bitemporal_change", modality="bitemporal") - crossmodal, _ = _plan(intent="crossmodal_fusion", modality="cross_modal") - - b, c = set(_types(bitemporal)), set(_types(crossmodal)) - assert b != c, "two genuinely different inputs must not produce identical action lists" - # Each difference is a direct consequence of the pipeline that actually ran. - assert "set_swipe_curtain" in b - assert {"set_sensor_band", "toggle_layer"} <= c - assert {a["params"]["layer_id"] for a in bitemporal if a["type"] == "toggle_layer"} == { - "bitemporal-structural-change" - } - assert {a["params"]["layer_id"] for a in crossmodal if a["type"] == "toggle_layer"} == {"sentinel-sar"} - assert [a["params"]["tab"] for a in crossmodal if a["type"] == "open_panel"] == ["telemetry"] - - def test_explicit_bbox_wins_over_sector_centroid(self): - actions, _ = _plan(requested_bbox=[72.1, 30.2, 72.9, 30.8]) - assert _types(actions)[0] == "fly_to_bbox" - assert "fly_to_sector" not in _types(actions) - - def test_invalid_bbox_falls_back_to_real_sector(self): - actions, _ = _plan(requested_bbox=[72.9, 30.2, 72.1, 30.8]) - assert _types(actions)[0] == "fly_to_sector" - - def test_highlight_target_exists_in_this_response(self): - actions, _ = _plan() - highlights = [a for a in actions if a["type"] == "highlight_feature"] - assert len(highlights) == 1 - # Highest-confidence addressable feature wins, and it is a real id. - assert highlights[0]["params"]["feature_id"] == "change-feat-7" - assert highlights[0]["params"]["feature_id"] in P.addressable_feature_ids(GEOJSON) - - def test_empty_response_emits_no_highlight_or_camera_move(self): - actions, _ = _plan(geojson={"type": "FeatureCollection", "features": []}) - assert "highlight_feature" not in _types(actions) - - def test_live_stream_only_when_genuinely_online(self): - assert "toggle_live_stream" not in _types(_plan(live_stream={"status": "unavailable"})[0]) - assert "toggle_live_stream" in _types(_plan(live_stream={"status": "online"})[0]) - - def test_every_emitted_action_is_schema_valid_and_pending(self): - actions, source = _plan(live_stream={"status": "online"}) - assert source == "rule_based" - feature_ids = P.addressable_feature_ids(GEOJSON) - for action in actions: - assert set(action) == {"type", "params", "reason", "status"} - assert action["type"] in UI_ACTION_TYPES - assert action["status"] == "pending", "backend must not claim an unexecuted action" - ok, why = P.validate(action, known_feature_ids=feature_ids) - assert ok, f"planner emitted an ungrounded action {action['type']}: {why}" - - @pytest.mark.parametrize("intent,modality", [ - ("bitemporal_change", "bitemporal"), - ("crossmodal_fusion", "cross_modal"), - ("optical_vqa", "single_image"), - ("visual_grounding", "single_image"), - ("sar_vqa", "single_image"), - ("scene_captioning", "single_image"), - ]) - def test_every_intent_yields_at_least_one_grounded_action(self, intent, modality): - actions, _ = _plan(intent=intent, modality=modality) - assert actions, f"{intent} produced no actions" diff --git a/frontend/bun.lock b/bun.lock similarity index 72% rename from frontend/bun.lock rename to bun.lock index 82582fa..fbb83f6 100644 --- a/frontend/bun.lock +++ b/bun.lock @@ -5,26 +5,34 @@ "": { "name": "react-example", "dependencies": { - "@google/genai": "^2.4.0", + "@google/genai": "^2.23.0", "@tailwindcss/vite": "^4.1.14", "@types/geojson": "^7946.0.16", "@vitejs/plugin-react": "^5.0.4", "dotenv": "^17.2.3", - "express": "^4.21.2", + "express": "^5.2.1", + "framer-motion": "^13.2.0", "lucide-react": "^0.546.0", "maplibre-gl": "^6.9.0", "motion": "^12.23.24", + "multer": "^2.4.0", "react": "^19.0.1", "react-dom": "^19.0.1", + "react-router-dom": "^7.18.3", "vite": "^6.2.3", + "zustand": "^5.0.15", }, "devDependencies": { - "@types/express": "^4.17.21", + "@reticlehq/react": "^2.14.0", + "@reticlehq/vite-plugin": "^2.14.0", + "@types/express": "^5.0.6", + "@types/multer": "^2.2.0", "@types/node": "^22.14.0", "@types/react": "^19.2.18", "@types/react-dom": "^19.2.7", "autoprefixer": "^10.4.21", "esbuild": "^0.25.0", + "playwright": "^1.63.0", "tailwindcss": "^4.1.14", "tsx": "^4.21.0", "typescript": "~5.8.2", @@ -123,7 +131,7 @@ "@esbuild/win32-x64": ["@esbuild/win32-x64@0.25.12", "", { "os": "win32", "cpu": "x64" }, "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA=="], - "@google/genai": ["@google/genai@2.21.0", "", { "dependencies": { "google-auth-library": "^10.3.0", "p-retry": "^4.6.2", "protobufjs": "^7.5.4", "ws": "^8.18.0" }, "peerDependencies": { "@modelcontextprotocol/sdk": "^1.25.2" }, "optionalPeers": ["@modelcontextprotocol/sdk"] }, "sha512-+PDtco2/Z0ONdzCGekCoCT+O1VJS9xJQNN4XzQpXG/t3El/SWWMkCWlFRO1KmivOHPa4Q0VjUYu1HBKCZ/v33Q=="], + "@google/genai": ["@google/genai@2.23.0", "", { "dependencies": { "google-auth-library": "^10.3.0", "p-retry": "^4.6.2", "protobufjs": "^7.5.4", "ws": "^8.18.0" }, "peerDependencies": { "@modelcontextprotocol/sdk": "^1.25.2" }, "optionalPeers": ["@modelcontextprotocol/sdk"] }, "sha512-NFMzktoZ7jJg9AA3vUbWZocnkQP6DSGzL21ORwdVcBWkHli3k7v6B9zy07M4bTiKDAyIWfUh2J/oLYxCu0hNpQ=="], "@jridgewell/gen-mapping": ["@jridgewell/gen-mapping@0.3.13", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA=="], @@ -147,9 +155,9 @@ "@maplibre/geojson-vt": ["@maplibre/geojson-vt@6.1.1", "", { "dependencies": { "kdbush": "^4.1.0" } }, "sha512-FVMOcmSP/yqol45t7StApEyTL5/vmqBCuFhH9n+fFuINenhaX+YgHHIt1yJ86S8kln3uJLcMvmEU2cfn6E2eCQ=="], - "@maplibre/maplibre-gl-style-spec": ["@maplibre/maplibre-gl-style-spec@26.4.2", "", { "dependencies": { "@mapbox/jsonlint-lines-primitives": "^2.0.3", "@mapbox/unitbezier": "^1.0.0", "json-stringify-pretty-compact": "^4.0.0", "minimist": "^1.2.8", "quickselect": "^3.0.0", "tinyqueue": "^3.0.0" }, "bin": { "gl-style-format": "dist/gl-style-format.mjs", "gl-style-migrate": "dist/gl-style-migrate.mjs", "gl-style-validate": "dist/gl-style-validate.mjs" } }, "sha512-6J0vZqMZvRAJKtdWJdDGHEh1YJ2ZHG08/GOur8gCArYhO8ZkM//OXqtI2AAEz4jc2G+Wq4MfcePg8qNK5TZ4Kg=="], + "@maplibre/maplibre-gl-style-spec": ["@maplibre/maplibre-gl-style-spec@26.4.4", "", { "dependencies": { "@mapbox/jsonlint-lines-primitives": "^2.0.3", "@mapbox/unitbezier": "^1.0.0", "json-stringify-pretty-compact": "^4.0.0", "minimist": "^1.2.8", "quickselect": "^3.0.0", "tinyqueue": "^3.0.0" }, "bin": { "gl-style-format": "dist/gl-style-format.mjs", "gl-style-migrate": "dist/gl-style-migrate.mjs", "gl-style-validate": "dist/gl-style-validate.mjs" } }, "sha512-hG4RZR4PBd/+6A3ODdZ3AnQRF106ZQk1y3bhwDg8bH/A4Oz2tnRUJVVWs9BZa6gXZ1d3UKe89C+Mm+olGBELvA=="], - "@maplibre/mlt": ["@maplibre/mlt@1.2.1", "", { "dependencies": { "@mapbox/point-geometry": "^1.1.0" } }, "sha512-5n5dgolE2EYxwCKgx8vlwURCB8A+kyfJJyThlYimjlGgOcOe2Bhw9VxxnnHC91OC9PgHg+nVdgVPTYPkIo62vg=="], + "@maplibre/mlt": ["@maplibre/mlt@1.3.0", "", { "dependencies": { "@mapbox/point-geometry": "^1.1.0" } }, "sha512-7M2O7ABM80Oi8XPkfkrjKB8mOBIxGoVgkA52Mu4RMWoBvvMdagQ522+WxVYujZsMpqIr3BpzrTbXrm4k8lCzCQ=="], "@maplibre/vt-pbf": ["@maplibre/vt-pbf@4.3.2", "", { "dependencies": { "@mapbox/point-geometry": "^1.1.0", "@types/geojson": "^7946.0.16", "pbf": "^5.1.0" } }, "sha512-j6p0AdjvAR19Z3XaCysle7A4ZSo08tYOzxD0Y9NQylwPAkwJJeYub5b2eVucdeDh7erhv69DahoLOevDRERRUw=="], @@ -173,57 +181,67 @@ "@protobufjs/utf8": ["@protobufjs/utf8@1.1.2", "", {}, "sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug=="], + "@reticlehq/babel-plugin": ["@reticlehq/babel-plugin@2.14.0", "", { "dependencies": { "@reticlehq/core": "2.14.0" }, "peerDependencies": { "@babel/core": "^7" } }, "sha512-7WN/AukV1t6SrS+l4E2fbKth35joezaMX7EaX7d0eiwfAOzoUKlwVHgIhdUeJr0pXo4k6O3b6BO2cIAzyj+9NA=="], + + "@reticlehq/browser": ["@reticlehq/browser@2.14.0", "", { "dependencies": { "@reticlehq/core": "2.14.0" } }, "sha512-6qTzgbzNySsjdKGmvvbWmd5w8h7wZPLvXK5k+vtp2NVv6MkC65977MRbalhOlJqRp9FP4sPt31rsELcg6KYRHw=="], + + "@reticlehq/core": ["@reticlehq/core@2.14.0", "", { "dependencies": { "zod": "^3.24.1" } }, "sha512-UZAUc9QryKKqq185N6jcD39fzn/4qQejNr6PJytXFPvdGmPYpWMfxKUM9O1o1KaY7szs5+Cv1DfY6BkD7c4I9A=="], + + "@reticlehq/react": ["@reticlehq/react@2.14.0", "", { "dependencies": { "@reticlehq/browser": "2.14.0", "@reticlehq/core": "2.14.0" }, "peerDependencies": { "react": ">=18" } }, "sha512-B706E+UhdKh19esKp3NOA3KpSg0CVFd3WjY4p33AqB9fp4eoRcMJfLbBVWZ+vA/2qMShnSv+aXwfD1CjjsrVQA=="], + + "@reticlehq/vite-plugin": ["@reticlehq/vite-plugin@2.14.0", "", { "dependencies": { "@babel/core": "^7.26.0", "@reticlehq/babel-plugin": "2.14.0", "@reticlehq/core": "2.14.0" }, "peerDependencies": { "vite": ">=4" }, "optionalPeers": ["vite"] }, "sha512-lw9X1Nkx7PnqMwq22B+J1DA0qgU19oARhsUsMniWMOW+sBOgSF8Rh5SSV8IuyNVY/QdfBfXcwVOCdYjoOMBMcw=="], + "@rolldown/pluginutils": ["@rolldown/pluginutils@1.0.0-rc.3", "", {}, "sha512-eybk3TjzzzV97Dlj5c+XrBFW57eTNhzod66y9HrBlzJ6NsCrWCp/2kaPS3K9wJmurBC0Tdw4yPjXKZqlznim3Q=="], - "@rollup/rollup-android-arm-eabi": ["@rollup/rollup-android-arm-eabi@4.63.1", "", { "os": "android", "cpu": "arm" }, "sha512-UZ8sUxPTiHWYX9QNdJedb1kDZSpS1t/VPWBWGSgqHNi9w3Cu6IXvu2mzbhiTiPvtrqgTQJ+zqiAq2iPIPilpaQ=="], + "@rollup/rollup-android-arm-eabi": ["@rollup/rollup-android-arm-eabi@4.63.3", "", { "os": "android", "cpu": "arm" }, "sha512-w3Jnvi1ocaVm/c7yVPpfB98XeSRBMyzp6njL5MVVbGyXjpmUkN+s6Hp4t0PqhGCCaI1ZHMKXt/w0lA1RCaLVcw=="], - "@rollup/rollup-android-arm64": ["@rollup/rollup-android-arm64@4.63.1", "", { "os": "android", "cpu": "arm64" }, "sha512-cQ4nFQABN5cDvDpbvJ7bMStCpnaVxynZrRMfUJYgxcIk9Sh54FIO1vtfkg0B69REjER77ioZ/ov+eAApx/KmLQ=="], + "@rollup/rollup-android-arm64": ["@rollup/rollup-android-arm64@4.63.3", "", { "os": "android", "cpu": "arm64" }, "sha512-uI/ESiaIbbRYAEhzy8PCUWDp1hB0bjAqM06mW9flOoNO4Q8DQpeoREhBR5Hegfl+wpXiguyJv6XSPzEN7OxyHQ=="], - "@rollup/rollup-darwin-arm64": ["@rollup/rollup-darwin-arm64@4.63.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-FQNqd1lRy/0QhDk3xeRIkSBiCpXCiDnZO3YLVdcDKN1UBiKToNftCzcXYNLshmPDUMlu2TdeS8tGcsU6f3YF1Q=="], + "@rollup/rollup-darwin-arm64": ["@rollup/rollup-darwin-arm64@4.63.3", "", { "os": "darwin", "cpu": "arm64" }, "sha512-oxhrd1jmXLwWZ83eQYDXxuqRdkqkzrjR3JobKeuUyfdNZo11FuQIvqEOZhyIT7OBHxXoGslDDjN0cQcM6T0TqQ=="], - "@rollup/rollup-darwin-x64": ["@rollup/rollup-darwin-x64@4.63.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-pvD16V939D3CloK0+qikpGaxiPrDUXTe7Y5cWOMkMSy7m1cawa8EGy/kXYi/G/cKAC4HDAbSnzCIk1WmsoOKXg=="], + "@rollup/rollup-darwin-x64": ["@rollup/rollup-darwin-x64@4.63.3", "", { "os": "darwin", "cpu": "x64" }, "sha512-7/YiIMghVE8DrxKvNdorAaJVdriOFgOIpdStnPx8ppx5zfTwC3jBCSEAIzB7JD5404m65THl6H93UTTVUvypmg=="], - "@rollup/rollup-freebsd-arm64": ["@rollup/rollup-freebsd-arm64@4.63.1", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-pcFGeL2345VwdTnJhA6zLbew+YgWB0qBG2+dMtXjCicf6+rm6kO6cOoh5VnTe0ZMrMRgRyuHmCJxZWrIdzYuOw=="], + "@rollup/rollup-freebsd-arm64": ["@rollup/rollup-freebsd-arm64@4.63.3", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-GXFZRRoMAytaI5z6N3Zhfw0WL18Q0M8r95D5hlC4GqE/lGk8pbSJNUBoOWDfbm6dTciqHj2nU87tI5f6XhQiOg=="], - "@rollup/rollup-freebsd-x64": ["@rollup/rollup-freebsd-x64@4.63.1", "", { "os": "freebsd", "cpu": "x64" }, "sha512-mRJlqSRulVzcKq/LKA6ICSIc3K/l4fzlVn/gePn2nXIHy8seRi5z/eeRE0d/XMBxcMldiXtQTSpRj0tkkC3g8Q=="], + "@rollup/rollup-freebsd-x64": ["@rollup/rollup-freebsd-x64@4.63.3", "", { "os": "freebsd", "cpu": "x64" }, "sha512-77W+8X3ddYgPxUpB8nZFQs2Mq+wc4HVlcSRtApXLjYBcnPMkttrSnU8VwKQjeWYhMsITHFs5cWBQ8vz1Q+5RHQ=="], - "@rollup/rollup-linux-arm-gnueabihf": ["@rollup/rollup-linux-arm-gnueabihf@4.63.1", "", { "os": "linux", "cpu": "arm" }, "sha512-YDUNvVM85TI3g/1OpnqKP1h4NeW/j64DfWMf+G3M809xNk1bJSnpFp4sh83NpmVE5DXnkh8ULor4LTVZKoYLHw=="], + "@rollup/rollup-linux-arm-gnueabihf": ["@rollup/rollup-linux-arm-gnueabihf@4.63.3", "", { "os": "linux", "cpu": "arm" }, "sha512-FVkwK+iUC+mq+GipVK46rRVticfAPtvPUNlqlGXUDxdVk/UGjQiiiUVPUrEXdSpU2ufU0XxLGyTqDtBidDOVmg=="], - "@rollup/rollup-linux-arm-musleabihf": ["@rollup/rollup-linux-arm-musleabihf@4.63.1", "", { "os": "linux", "cpu": "arm" }, "sha512-7Mcn71p9ZuQFAj+h+dhQXy/yeLePRS2yKRnmW1DijA9thKO5qap0GNOIQK4yQ6iP3SU0Mrb/yWo8h8vgRba8lw=="], + "@rollup/rollup-linux-arm-musleabihf": ["@rollup/rollup-linux-arm-musleabihf@4.63.3", "", { "os": "linux", "cpu": "arm" }, "sha512-+aGU1t3398yQOVj1Bz8o3e+KtswxAPvO+mtxtNdfXYMkXIHu7XhhkCD7/DEH9q8tF8uhDnMWvfpUKI8y1sZJsg=="], - "@rollup/rollup-linux-arm64-gnu": ["@rollup/rollup-linux-arm64-gnu@4.63.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-4YiLQTX6U4CSl0L9cluep9A9W6UmTfqBDc2/CH6wlu54pl4E7Jn3cOD8oxzvBDEGk/JMKgJ47C8g+radF7mwvg=="], + "@rollup/rollup-linux-arm64-gnu": ["@rollup/rollup-linux-arm64-gnu@4.63.3", "", { "os": "linux", "cpu": "arm64" }, "sha512-cR0kjpRXR2KJ2oQK8E2KTPtphs+b9hZ8IhTZubNryt/RsqgdOZBQ2Zq0q5UedtiIi0rs3jVhJh55RE1ZHUVGUA=="], - "@rollup/rollup-linux-arm64-musl": ["@rollup/rollup-linux-arm64-musl@4.63.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-2ra8F7w8OquwZN9z2/fKFnli69wa8PLwaVzRMIPGb13ByMJwC28Fbp8YcVGoUhlYMTt7j5j9bNgpysrN2UM+vw=="], + "@rollup/rollup-linux-arm64-musl": ["@rollup/rollup-linux-arm64-musl@4.63.3", "", { "os": "linux", "cpu": "arm64" }, "sha512-y1RYi4Q3/9ByVWSSt9kX2ustE0B7kFYbJ6zZdVZVyqopZs3yhCTwRfrjIX4vezUJInma/Gs6BOFDJg7yZmJ0IQ=="], - "@rollup/rollup-linux-loong64-gnu": ["@rollup/rollup-linux-loong64-gnu@4.63.1", "", { "os": "linux", "cpu": "none" }, "sha512-Sy20ncyhjmBP0Ml+UvQbimjlk6VFgjW5uNP+qqwHB00mTE8Bl2C1TuHTlRwK2YoXeZbee5lP2XevBWVkAQAtSQ=="], + "@rollup/rollup-linux-loong64-gnu": ["@rollup/rollup-linux-loong64-gnu@4.63.3", "", { "os": "linux", "cpu": "none" }, "sha512-DNhEA5viIj3Z5bZLE4z4oV8N5ozWqDwyt7T6KG7VdLDJ0nW+rNOYlphBl4/3HQkK75qipPLsVOfStHHOwN9WSg=="], - "@rollup/rollup-linux-loong64-musl": ["@rollup/rollup-linux-loong64-musl@4.63.1", "", { "os": "linux", "cpu": "none" }, "sha512-noITLp8oNjYliPnGWmLyelIHwULGqbHloQHGw1rtxbWhTuWooRpnZarZQJ1y9EUC4szuCusCc+HEpUtxpIwYvA=="], + "@rollup/rollup-linux-loong64-musl": ["@rollup/rollup-linux-loong64-musl@4.63.3", "", { "os": "linux", "cpu": "none" }, "sha512-17gQCqrIpXBX2Cmi9/TygnVOqGbzsba/iaqcYSL8FY7lNugg+7AiYNs5c5nKWD+NRQha36Sa0CqkJqH4XVHwnQ=="], - "@rollup/rollup-linux-ppc64-gnu": ["@rollup/rollup-linux-ppc64-gnu@4.63.1", "", { "os": "linux", "cpu": "ppc64" }, "sha512-hlxxXd+F1mWiAcaFR7Sv9ZQT6m6UfI8+Vy/kFJzztq2pDMU/0wZ9sish0iszNZvsQDo8Gc0i5yuFEOz5dDf6fA=="], + "@rollup/rollup-linux-ppc64-gnu": ["@rollup/rollup-linux-ppc64-gnu@4.63.3", "", { "os": "linux", "cpu": "ppc64" }, "sha512-6LwVnZRIyINpdku/yOcI8Tm9YqLmhHK5emmlOOnW9tO0SYEm1FmKPcsSAGp0NBlqR2P04xaND4jvN6sTHqhq8A=="], - "@rollup/rollup-linux-ppc64-musl": ["@rollup/rollup-linux-ppc64-musl@4.63.1", "", { "os": "linux", "cpu": "ppc64" }, "sha512-EF7OpqQTQ/BvGqLzUi4rEHuagCV9MugAUXSHemwPW5vxZ75RR+jxO/2j95Ph2dalMpFHSVECjRoioHZgA9zOYA=="], + "@rollup/rollup-linux-ppc64-musl": ["@rollup/rollup-linux-ppc64-musl@4.63.3", "", { "os": "linux", "cpu": "ppc64" }, "sha512-xMUqkTXlEUtI/p5AAukMwBRr1enU3efsTeF+bskeFfk8t1C9rcC8sLREcZXmTfAXEbvRdJVSonVJez3TMlbR3w=="], - "@rollup/rollup-linux-riscv64-gnu": ["@rollup/rollup-linux-riscv64-gnu@4.63.1", "", { "os": "linux", "cpu": "none" }, "sha512-wQO3JesW9PRkwlabQ27y7sPfVOOTLRG73I4F2UYHG5PXun3J9U3y+b7ezVKSYbsvSKGQ1k1cq8Qlun4C9kLt3w=="], + "@rollup/rollup-linux-riscv64-gnu": ["@rollup/rollup-linux-riscv64-gnu@4.63.3", "", { "os": "linux", "cpu": "none" }, "sha512-S3E94co9F9WRRqEaUoQZ38K1gCz6KiM+nL7/3ijq7fDGF3OznjS5TasgYITlvl27GQKtu4lOAOsr5MFwkijvOA=="], - "@rollup/rollup-linux-riscv64-musl": ["@rollup/rollup-linux-riscv64-musl@4.63.1", "", { "os": "linux", "cpu": "none" }, "sha512-ouAGwhO6wHRXdnOVCOsB0tRFkA7nhNB2Nwax6oECXN0YiN8EYUTBAOudADOB1PI+yDL61TeNx/u7MVCzksNbkQ=="], + "@rollup/rollup-linux-riscv64-musl": ["@rollup/rollup-linux-riscv64-musl@4.63.3", "", { "os": "linux", "cpu": "none" }, "sha512-1QtRDwG42x5BJI3s9mxu5rEjDnfbSnk20HQ9/ylTAYnSwYwxMVb+Vgu34wzzTQ7ogqBybebgQNUDAvZVQ38DbA=="], - "@rollup/rollup-linux-s390x-gnu": ["@rollup/rollup-linux-s390x-gnu@4.63.1", "", { "os": "linux", "cpu": "s390x" }, "sha512-q2R38Sn+1J8RxhfJ+T54wSWmyKXWec+9jgDfqO2AtArEqHO5R2aeayp5H5OYLr5UYDVGsVaZPEFUooMhYCdz5A=="], + "@rollup/rollup-linux-s390x-gnu": ["@rollup/rollup-linux-s390x-gnu@4.63.3", "", { "os": "linux", "cpu": "s390x" }, "sha512-BQhejF6ZXOpxbngiNTP12GCGQeaDVL2QXGeBVViKIYzFHM5RKxTxwUMB1fr1BeNFphFMpnRqC5QSXFSa4z6UQw=="], - "@rollup/rollup-linux-x64-gnu": ["@rollup/rollup-linux-x64-gnu@4.63.1", "", { "os": "linux", "cpu": "x64" }, "sha512-gfI5T24WLLuFfSKw7Go/zDXjAAV0fny0swTaDv+WjK7vqcw4cRhFfdsyKL1n+ukI+ooBxn3bVQnyrn06WpI50w=="], + "@rollup/rollup-linux-x64-gnu": ["@rollup/rollup-linux-x64-gnu@4.63.3", "", { "os": "linux", "cpu": "x64" }, "sha512-SXagRwnI2Wlwlitllu59UK/nGVbD1CKPcNqDplHwIC4BqJcpXFjD32d1R/RbuISa95HdQrZM3/7v4bKiowFaLA=="], - "@rollup/rollup-linux-x64-musl": ["@rollup/rollup-linux-x64-musl@4.63.1", "", { "os": "linux", "cpu": "x64" }, "sha512-4h6XqthmB4Hspji84wvgk+ElodTsGj+dbZqHJHHtKxj4mYq0ANSEEPX9ys3moJueqsRjwpaJYH7874Itwnj2ow=="], + "@rollup/rollup-linux-x64-musl": ["@rollup/rollup-linux-x64-musl@4.63.3", "", { "os": "linux", "cpu": "x64" }, "sha512-2IPozoEALRCziGqE8O9KMK60PMu5TS1huv4fwoeCexj+WjmcwFtX9CTOVbfXCUqcELAubEwRFPYlzb/WvwY2HQ=="], - "@rollup/rollup-openbsd-x64": ["@rollup/rollup-openbsd-x64@4.63.1", "", { "os": "openbsd", "cpu": "x64" }, "sha512-dlfCOa87o1VAYegLQ9EKilx2JCeRofiyPGhTCmqnuXZ6bMPiycO1rq1+sKoulAp7pGLIsTIw+1x5R+zgh5LhhA=="], + "@rollup/rollup-openbsd-x64": ["@rollup/rollup-openbsd-x64@4.63.3", "", { "os": "openbsd", "cpu": "x64" }, "sha512-AoxqosUHT9IX54hFn2TiN6A7d6ZKTtE6pd2bqWtqkkNJ6HJGaU6FRouGX8L1O7R/ZwsnCnpQrHzb4pDEx+UHRQ=="], - "@rollup/rollup-openharmony-arm64": ["@rollup/rollup-openharmony-arm64@4.63.1", "", { "os": "none", "cpu": "arm64" }, "sha512-cjkLbOlfcm3QGhMM1J5zaZjsw1GggbN6rw9UTSSRrPrR1KkcXnN7Uq9rPw34xImQ9VOY9GN+6u2Zj80B9ptkcw=="], + "@rollup/rollup-openharmony-arm64": ["@rollup/rollup-openharmony-arm64@4.63.3", "", { "os": "none", "cpu": "arm64" }, "sha512-d+CaftKgmkFBzCwezMqqy1d0QNNYugqLCMcYVQWBy5SS2YfeMP8Q8ripkgx9O8IyBXXLHrJ+aaCV4U96usv6Yg=="], - "@rollup/rollup-win32-arm64-msvc": ["@rollup/rollup-win32-arm64-msvc@4.63.1", "", { "os": "win32", "cpu": "arm64" }, "sha512-Li1KdUnWGE4N3e1F/B4RTB1ms+nG4WBgjByO46pkeBVX/2UBsY53xf5vK9WygVmnH3RwncIST7lkSdLSY6P9lg=="], + "@rollup/rollup-win32-arm64-msvc": ["@rollup/rollup-win32-arm64-msvc@4.63.3", "", { "os": "win32", "cpu": "arm64" }, "sha512-xXlDF6nR1eOuXbdDy5Hl5fmtY7teUDevF/k0O7IPoZe4Tpmdv+lgdE5JRsnhQtt37ql9P0VF2kAN9a0OCZdo+Q=="], - "@rollup/rollup-win32-ia32-msvc": ["@rollup/rollup-win32-ia32-msvc@4.63.1", "", { "os": "win32", "cpu": "ia32" }, "sha512-t4ZYOSoLTgwhuFMrmTMLx/+i1DQVK7HYqMc6kY46EApwi8X0nIVphzdNoThU3xt6n+N5urG1/gxBdCaKDLavfg=="], + "@rollup/rollup-win32-ia32-msvc": ["@rollup/rollup-win32-ia32-msvc@4.63.3", "", { "os": "win32", "cpu": "ia32" }, "sha512-YtXAgLN+JP7Ay6qG3eWhc7IHMQPzLc8r3uvhAvlJIoCz/4Q32+Bl9Fmnywidh8v1GOIMmymjovfqY9ETAtysvA=="], - "@rollup/rollup-win32-x64-gnu": ["@rollup/rollup-win32-x64-gnu@4.63.1", "", { "os": "win32", "cpu": "x64" }, "sha512-RgroPfMmKlD1RzSDxvwgcPiy2HNQKoYV7OmwIXDsk73uKW5t6B/V8KIy27SMv/FNXFo/oSBtWc9J0X7t91ezZg=="], + "@rollup/rollup-win32-x64-gnu": ["@rollup/rollup-win32-x64-gnu@4.63.3", "", { "os": "win32", "cpu": "x64" }, "sha512-WuWtSJRNo549vzcfZyEgfqb6zeSgn1F+UE5kQ+BCjzz0W4MGCjntUHkZVc1VRuAM7+ULaSyhiPxD1spyewFvkQ=="], - "@rollup/rollup-win32-x64-msvc": ["@rollup/rollup-win32-x64-msvc@4.63.1", "", { "os": "win32", "cpu": "x64" }, "sha512-at8QVep6S3h5Y6gSbdGU06bRY5WJkf6WUduM9YtvYMbYhB1MOFfUgc6kehitQXzOtMSaT70q7f9ydPhpqu821w=="], + "@rollup/rollup-win32-x64-msvc": ["@rollup/rollup-win32-x64-msvc@4.63.3", "", { "os": "win32", "cpu": "x64" }, "sha512-+lIKX7O0+IGe7WuhATaAMMeT7B76vfhXH/l9wLQL+nvyhbw2ohYCKIdWL56JfDu75CWt5oKRP4QFH/jkMtBquA=="], "@tailwindcss/node": ["@tailwindcss/node@4.3.3", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "enhanced-resolve": "^5.24.1", "jiti": "^2.7.0", "lightningcss": "1.32.0", "magic-string": "^0.30.21", "source-map-js": "^1.2.1", "tailwindcss": "4.3.3" } }, "sha512-/T8IKEsf9VTU6tLjgC7+sv2mOPtQxzE2jMw7u4Tt40Tx+QSZxpzh95/H6cMKoja9XuW7iMdLJYBB0o9G1CaAgg=="], @@ -269,56 +287,58 @@ "@types/estree": ["@types/estree@1.0.9", "", {}, "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="], - "@types/express": ["@types/express@4.17.25", "", { "dependencies": { "@types/body-parser": "*", "@types/express-serve-static-core": "^4.17.33", "@types/qs": "*", "@types/serve-static": "^1" } }, "sha512-dVd04UKsfpINUnK0yBoYHDF3xu7xVH4BuDotC/xGuycx4CgbP48X/KF/586bcObxT0HENHXEU8Nqtu6NR+eKhw=="], + "@types/express": ["@types/express@5.0.6", "", { "dependencies": { "@types/body-parser": "*", "@types/express-serve-static-core": "^5.0.0", "@types/serve-static": "^2" } }, "sha512-sKYVuV7Sv9fbPIt/442koC7+IIwK5olP1KWeD88e/idgoJqDm3JV/YUiPwkoKK92ylff2MGxSz1CSjsXelx0YA=="], - "@types/express-serve-static-core": ["@types/express-serve-static-core@4.19.9", "", { "dependencies": { "@types/node": "*", "@types/qs": "*", "@types/range-parser": "*", "@types/send": "*" } }, "sha512-QP2ESEe/ImWY0HDwNAnK9PvEffUyhLTnWkk7KXzHfyeWAnlrDe1fN77bXl6ia8KT3wPlmA7t9/VPRpnf4Ex9sg=="], + "@types/express-serve-static-core": ["@types/express-serve-static-core@5.1.3", "", { "dependencies": { "@types/node": "*", "@types/qs": "*", "@types/range-parser": "*", "@types/send": "*" } }, "sha512-dPfW8NFiOF4wOHc7+N/QSxlY9cfSsenewGbAz8C8U/MULPd/YZ27LvJUIlzaXie7e6Ove9YunJGgC9tbHD2cKw=="], "@types/geojson": ["@types/geojson@7946.0.16", "", {}, "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg=="], "@types/http-errors": ["@types/http-errors@2.0.5", "", {}, "sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg=="], - "@types/mime": ["@types/mime@1.3.5", "", {}, "sha512-/pyBZWSLD2n0dcHE3hq8s8ZvcETHtEuF+3E7XVt0Ig2nvsVQXdghHVcEkIWjy9A0wKfTn97a/PSDYohKIlnP/w=="], + "@types/multer": ["@types/multer@2.2.0", "", { "dependencies": { "@types/express": "*" } }, "sha512-3U1troeqGV8Ntp7Q3klwf4zr23VEoqYVocYXaswm9+8z3O9UHDYAqLxjJ/h550iRADTjKdOdhhasXw6gD6kYtg=="], - "@types/node": ["@types/node@22.20.1", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-EANqOCF9QFyra+4pfxUcX9STKJpCLjMbObVzljIJomAWSnuSIEAvyzEU53GaajbXJEgdh0iEcPL+DGvpUd4k1Q=="], + "@types/node": ["@types/node@22.20.3", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-DZmzkmwHzXrLPAXPyKNDzlIwMMUZCVacoD25ywdy5YTKGbOx/2ld+Q38Im2zJ0vBuZP5Prd3VZutKZyXwkOS8A=="], "@types/qs": ["@types/qs@6.15.1", "", {}, "sha512-GZHUBZR9hckSUhrxmp1nG6NwdpM9fCunJwyThLW1X3AyHgd9IlHb6VANpQQqDr2o/qQp6McZ3y/IA2rVzKzSbw=="], "@types/range-parser": ["@types/range-parser@1.2.7", "", {}, "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ=="], - "@types/react": ["@types/react@19.2.18", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-AnzbBERsrLKtk2XSfTbYRLjQPdy116Sty4q+T+Bp3IC4l6jNBvreVPAHmpq9qhXQM7CXZPjLVmGMw9sy+hxQ3w=="], + "@types/react": ["@types/react@19.3.0", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg=="], - "@types/react-dom": ["@types/react-dom@19.2.7", "", { "peerDependencies": { "@types/react": "^19.2.0" } }, "sha512-I8bPpDLcHBv1qiIiXDCy71Rt8eQDKJP0sMSWJphDdAcdqiJ1sGpZamavoEIRZmYzjia9LuEb2HlYdDpmoENpvQ=="], + "@types/react-dom": ["@types/react-dom@19.3.0", "", { "peerDependencies": { "@types/react": "^19.3.0" } }, "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q=="], "@types/retry": ["@types/retry@0.12.0", "", {}, "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA=="], "@types/send": ["@types/send@1.2.1", "", { "dependencies": { "@types/node": "*" } }, "sha512-arsCikDvlU99zl1g69TcAB3mzZPpxgw0UQnaHeC1Nwb015xp8bknZv5rIfri9xTOcMuaVgvabfIRA7PSZVuZIQ=="], - "@types/serve-static": ["@types/serve-static@1.15.10", "", { "dependencies": { "@types/http-errors": "*", "@types/node": "*", "@types/send": "<1" } }, "sha512-tRs1dB+g8Itk72rlSI2ZrW6vZg0YrLI81iQSTkMmOqnqCaNr/8Ek4VwWcN5vZgCYWbg/JJSGBlUaYGAOP73qBw=="], + "@types/serve-static": ["@types/serve-static@2.2.0", "", { "dependencies": { "@types/http-errors": "*", "@types/node": "*" } }, "sha512-8mam4H1NHLtu7nmtalF7eyBH14QyOASmcxHhSfEoRyr0nP/YdoesEtU+uSRvMe96TW/HPTtkoKqQLl53N7UXMQ=="], "@vitejs/plugin-react": ["@vitejs/plugin-react@5.2.0", "", { "dependencies": { "@babel/core": "^7.29.0", "@babel/plugin-transform-react-jsx-self": "^7.27.1", "@babel/plugin-transform-react-jsx-source": "^7.27.1", "@rolldown/pluginutils": "1.0.0-rc.3", "@types/babel__core": "^7.20.5", "react-refresh": "^0.18.0" }, "peerDependencies": { "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" } }, "sha512-YmKkfhOAi3wsB1PhJq5Scj3GXMn3WvtQ/JC0xoopuHoXSdmtdStOpFrYaT1kie2YgFBcIe64ROzMYRjCrYOdYw=="], - "accepts": ["accepts@1.3.8", "", { "dependencies": { "mime-types": "~2.1.34", "negotiator": "0.6.3" } }, "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw=="], + "accepts": ["accepts@2.0.0", "", { "dependencies": { "mime-types": "^3.0.0", "negotiator": "^1.0.0" } }, "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng=="], "agent-base": ["agent-base@7.1.4", "", {}, "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ=="], - "array-flatten": ["array-flatten@1.1.1", "", {}, "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg=="], + "append-field": ["append-field@1.0.0", "", {}, "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw=="], - "autoprefixer": ["autoprefixer@10.5.5", "", { "dependencies": { "browserslist": "^4.28.9", "caniuse-lite": "^1.0.30001810", "fraction.js": "^5.3.4", "picocolors": "^1.1.1", "postcss-value-parser": "^4.2.0" }, "peerDependencies": { "postcss": "^8.1.0" }, "bin": { "autoprefixer": "bin/autoprefixer" } }, "sha512-uiRYvQYe/nNSzBJ7OUnd2/TZVsAdob3blml44teEpee9Cc1f4rGZFewO+JT3Wo8mgFOSzNqes4FHZn/Qz8WOuw=="], + "autoprefixer": ["autoprefixer@10.6.1", "", { "dependencies": { "browserslist": "^4.28.9", "caniuse-lite": "^1.0.30001810", "fraction.js": "^5.3.4", "picocolors": "^1.1.1", "postcss-value-parser": "^4.2.0" }, "peerDependencies": { "postcss": "^8.1.0" }, "bin": { "autoprefixer": "bin/autoprefixer" } }, "sha512-cL1Qz6ADZhcEbny/8HPfe99J6HhNoYtpX2LFLIbhgGE7Q1hlQVkYFdetDN7Id3KiQxhDrHwzlHr/YQCnZ8+xSA=="], "base64-js": ["base64-js@1.5.1", "", {}, "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="], - "baseline-browser-mapping": ["baseline-browser-mapping@2.11.21", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-uh8vpY/1/YyFkunIDFH/12p7/7VdPKA1hejMVEbdkEaWnUz0Hesvx5EbiU6XxjyHZIOju+ZMbQJkRh+es3/spQ=="], + "baseline-browser-mapping": ["baseline-browser-mapping@2.11.24", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-hYrgxie335U08WqICoGqKRzV1HFXv6zdxwJE4ekCb80CM9a0SVVsN4QPwT67RraRo+9h8IATk6uxHJw7QSkdOg=="], "bidi-js": ["bidi-js@1.1.0", "", { "dependencies": { "require-from-string": "^2.0.2" } }, "sha512-fX1Onk0tdVPC7obPWB5EbJ1z7NVhLq4m2xZLq2YXBkxzMXIGRpNMU88n0EPgWseKl12J7zXs7qrDxPK4sRs2fg=="], "bignumber.js": ["bignumber.js@9.3.1", "", {}, "sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ=="], - "body-parser": ["body-parser@1.20.8", "", { "dependencies": { "bytes": "~3.1.2", "content-type": "~1.0.5", "debug": "2.6.9", "depd": "2.0.0", "destroy": "~1.2.0", "http-errors": "~2.0.1", "iconv-lite": "~0.4.24", "on-finished": "~2.4.1", "qs": "~6.16.0", "raw-body": "~2.5.3", "type-is": "~1.6.18", "unpipe": "~1.0.0" } }, "sha512-JNcyFQ64OiijEkPzUBTCe+hyPXUD/3LEldGQ6iF5LR1w00mx9o7xtDWHXBY2iItjdCFGoilOLNQbH943ut7pHA=="], + "body-parser": ["body-parser@2.3.0", "", { "dependencies": { "bytes": "^3.1.2", "content-type": "^2.0.0", "debug": "^4.4.3", "http-errors": "^2.0.1", "iconv-lite": "^0.7.2", "on-finished": "^2.4.1", "qs": "^6.15.2", "raw-body": "^3.0.2", "type-is": "^2.1.0" } }, "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw=="], - "browserslist": ["browserslist@4.28.9", "", { "dependencies": { "baseline-browser-mapping": "^2.11.20", "caniuse-lite": "^1.0.30001810", "electron-to-chromium": "^1.5.420", "node-releases": "^2.0.54", "update-browserslist-db": "^1.3.2" }, "bin": { "browserslist": "cli.js" } }, "sha512-EWazOblFYUvlGZcfGhPUPmYh3nikUxBVb+y9MJun5f3hBi812X+8MSQTujLBtgK3cf51fJWbWfOjyeO954d+Eg=="], + "browserslist": ["browserslist@4.29.0", "", { "dependencies": { "baseline-browser-mapping": "^2.11.23", "caniuse-lite": "^1.0.30001810", "electron-to-chromium": "^1.5.427", "node-releases": "^2.0.55", "update-browserslist-db": "^1.3.3" }, "bin": { "browserslist": "cli.js" } }, "sha512-3GSvyjvDI4Dur1Meg2BekJquu5uF+9R9a1+5M1Mde192eZoXbeXjzgOsgqPS2V8D5wrrip0gR5Hf/GhWQ9ZzaA=="], "buffer-equal-constant-time": ["buffer-equal-constant-time@1.0.1", "", {}, "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA=="], + "busboy": ["busboy@1.6.0", "", { "dependencies": { "streamsearch": "^1.1.0" } }, "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA=="], + "bytes": ["bytes@3.1.2", "", {}, "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="], "call-bind-apply-helpers": ["call-bind-apply-helpers@1.0.2", "", { "dependencies": { "es-errors": "^1.3.0", "function-bind": "^1.1.2" } }, "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ=="], @@ -327,7 +347,7 @@ "caniuse-lite": ["caniuse-lite@1.0.30001810", "", {}, "sha512-TITQPUkaz+aVk5GL6NhOdwk1aEaNTSDPsGFWrTuhKGtjTF70jL/Oht2W4c6rXUe5fu7Ie19VIahAXHIIiWWNeg=="], - "content-disposition": ["content-disposition@0.5.4", "", { "dependencies": { "safe-buffer": "5.2.1" } }, "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ=="], + "content-disposition": ["content-disposition@1.1.0", "", {}, "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g=="], "content-type": ["content-type@1.0.5", "", {}, "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA=="], @@ -335,18 +355,16 @@ "cookie": ["cookie@0.7.2", "", {}, "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w=="], - "cookie-signature": ["cookie-signature@1.0.7", "", {}, "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA=="], + "cookie-signature": ["cookie-signature@1.2.2", "", {}, "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg=="], "csstype": ["csstype@3.2.3", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="], "data-uri-to-buffer": ["data-uri-to-buffer@4.0.1", "", {}, "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A=="], - "debug": ["debug@2.6.9", "", { "dependencies": { "ms": "2.0.0" } }, "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA=="], + "debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" }, "peerDependencies": { "supports-color": "*" }, "optionalPeers": ["supports-color"] }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], "depd": ["depd@2.0.0", "", {}, "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw=="], - "destroy": ["destroy@1.2.0", "", {}, "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg=="], - "detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="], "dotenv": ["dotenv@17.4.2", "", {}, "sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw=="], @@ -359,11 +377,11 @@ "ee-first": ["ee-first@1.1.1", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="], - "electron-to-chromium": ["electron-to-chromium@1.5.425", "", {}, "sha512-QvPtl41EUOnuT1HBvMKgxXRIaHNcagBPs50u7VULzhZXaGfqTbZyE16LQsctZ/RQHlGu+FOWeDTR4mY6YbeF1g=="], + "electron-to-chromium": ["electron-to-chromium@1.5.430", "", {}, "sha512-e1QEj72Y4zd8RlNZVmoTg+iCOSVwpk05IOiiQwdrkwCSVlZfPthevErhE+nckGd2YbsXfp1SkisznhGVIXP2NQ=="], "encodeurl": ["encodeurl@2.0.0", "", {}, "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg=="], - "enhanced-resolve": ["enhanced-resolve@5.24.5", "", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.3.3" } }, "sha512-L1l8TNvomm6UVW5B253AGxQagSQr+vGwhMlrrfRS2qmhx46AMpMVJKQYLvWYbysTMY8VoicOvzHzoHMbyzB+4A=="], + "enhanced-resolve": ["enhanced-resolve@5.25.1", "", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.3.3" } }, "sha512-nGXts5znJzmWPu+mIE9izCOzdg63oJca2mDzGWWTth7sr4aCToKcoyFVBQwN75Ij5Pf6p510EwkTqViTRzDV+w=="], "es-define-property": ["es-define-property@1.0.1", "", {}, "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g=="], @@ -379,7 +397,7 @@ "etag": ["etag@1.8.1", "", {}, "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg=="], - "express": ["express@4.22.2", "", { "dependencies": { "accepts": "~1.3.8", "array-flatten": "1.1.1", "body-parser": "~1.20.5", "content-disposition": "~0.5.4", "content-type": "~1.0.4", "cookie": "~0.7.1", "cookie-signature": "~1.0.6", "debug": "2.6.9", "depd": "2.0.0", "encodeurl": "~2.0.0", "escape-html": "~1.0.3", "etag": "~1.8.1", "finalhandler": "~1.3.1", "fresh": "~0.5.2", "http-errors": "~2.0.0", "merge-descriptors": "1.0.3", "methods": "~1.1.2", "on-finished": "~2.4.1", "parseurl": "~1.3.3", "path-to-regexp": "~0.1.12", "proxy-addr": "~2.0.7", "qs": "~6.15.1", "range-parser": "~1.2.1", "safe-buffer": "5.2.1", "send": "~0.19.0", "serve-static": "~1.16.2", "setprototypeof": "1.2.0", "statuses": "~2.0.1", "type-is": "~1.6.18", "utils-merge": "1.0.1", "vary": "~1.1.2" } }, "sha512-IuL+Elrou2ZvCFHs18/CIzy2Nzvo25nZ1/D2eIZlz7c+QUayAcYoiM2BthCjs+EBHVpjYjcuLDAiCWgeIX3X1Q=="], + "express": ["express@5.2.1", "", { "dependencies": { "accepts": "^2.0.0", "body-parser": "^2.2.1", "content-disposition": "^1.0.0", "content-type": "^1.0.5", "cookie": "^0.7.1", "cookie-signature": "^1.2.1", "debug": "^4.4.0", "depd": "^2.0.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "finalhandler": "^2.1.0", "fresh": "^2.0.0", "http-errors": "^2.0.0", "merge-descriptors": "^2.0.0", "mime-types": "^3.0.0", "on-finished": "^2.4.1", "once": "^1.4.0", "parseurl": "^1.3.3", "proxy-addr": "^2.0.7", "qs": "^6.14.0", "range-parser": "^1.2.1", "router": "^2.2.0", "send": "^1.1.0", "serve-static": "^2.2.0", "statuses": "^2.0.1", "type-is": "^2.0.1", "vary": "^1.1.2" } }, "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw=="], "extend": ["extend@3.0.2", "", {}, "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g=="], @@ -387,7 +405,7 @@ "fetch-blob": ["fetch-blob@3.2.0", "", { "dependencies": { "node-domexception": "^1.0.0", "web-streams-polyfill": "^3.0.3" } }, "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ=="], - "finalhandler": ["finalhandler@1.3.2", "", { "dependencies": { "debug": "2.6.9", "encodeurl": "~2.0.0", "escape-html": "~1.0.3", "on-finished": "~2.4.1", "parseurl": "~1.3.3", "statuses": "~2.0.2", "unpipe": "~1.0.0" } }, "sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg=="], + "finalhandler": ["finalhandler@2.1.1", "", { "dependencies": { "debug": "^4.4.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "on-finished": "^2.4.1", "parseurl": "^1.3.3", "statuses": "^2.0.1" } }, "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA=="], "formdata-polyfill": ["formdata-polyfill@4.0.10", "", { "dependencies": { "fetch-blob": "^3.1.2" } }, "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g=="], @@ -395,9 +413,9 @@ "fraction.js": ["fraction.js@5.3.4", "", {}, "sha512-1X1NTtiJphryn/uLQz3whtY6jK3fTqoE3ohKs0tT+Ujr1W59oopxmoEh7Lu5p6vBaPbgoM0bzveAW4Qi5RyWDQ=="], - "framer-motion": ["framer-motion@12.43.0", "", { "dependencies": { "motion-dom": "^12.43.0", "motion-utils": "^12.39.0", "tslib": "^2.4.0" }, "peerDependencies": { "@emotion/is-prop-valid": "*", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["@emotion/is-prop-valid", "react", "react-dom"] }, "sha512-1eaL3RvR/kAlbG7UYcpMptEyzPoENO0c6w7ZnB3/hh2vSAz/6uGAFn6fdoqTBguNstf3MsFhJHsD/0DHiclG+g=="], + "framer-motion": ["framer-motion@13.4.0", "", { "dependencies": { "motion-dom": "^13.3.0", "motion-utils": "^13.3.0", "tslib": "^2.4.0" }, "peerDependencies": { "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["react", "react-dom"] }, "sha512-HCpqKM9BTu6UYKtj0u6J1QNxojnnirNcghcSDZ+SkpiL3myxvtsgXPS3ZGEELC2eSma7YiA937rAEXtRyydSXQ=="], - "fresh": ["fresh@0.5.2", "", {}, "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q=="], + "fresh": ["fresh@2.0.0", "", {}, "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A=="], "fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], @@ -431,12 +449,14 @@ "https-proxy-agent": ["https-proxy-agent@7.0.6", "", { "dependencies": { "agent-base": "^7.1.2", "debug": "4" } }, "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw=="], - "iconv-lite": ["iconv-lite@0.4.24", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3" } }, "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA=="], + "iconv-lite": ["iconv-lite@0.7.3", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ=="], "inherits": ["inherits@2.0.4", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="], "ipaddr.js": ["ipaddr.js@1.9.1", "", {}, "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="], + "is-promise": ["is-promise@4.0.0", "", {}, "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ=="], + "jiti": ["jiti@2.7.0", "", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ=="], "js-tokens": ["js-tokens@4.0.0", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="], @@ -487,53 +507,53 @@ "magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="], - "maplibre-gl": ["maplibre-gl@6.9.0", "", { "dependencies": { "@mapbox/point-geometry": "^1.1.0", "@mapbox/tiny-sdf": "^2.2.0", "@mapbox/unitbezier": "^1.0.0", "@mapbox/vector-tile": "^3.0.0", "@maplibre/geojson-vt": "^6.1.1", "@maplibre/maplibre-gl-style-spec": "^26.4.2", "@maplibre/mlt": "^1.2.1", "@maplibre/vt-pbf": "^4.3.2", "@types/geojson": "^7946.0.16", "bidi-js": "^1.1.0", "earcut": "^3.2.3", "gl-matrix": "^3.4.4", "kdbush": "^4.1.0", "murmurhash-js": "^1.0.0", "pbf": "^5.1.2", "potpack": "^2.1.0", "quickselect": "^3.0.0", "tinyqueue": "^3.0.0" } }, "sha512-vFMwMK0Zs+NM/rOMSdtu8bO30DIexhBEVi5KC6f70/XtI+L/K2wC3LsDCAXFZ4s8ik5gAuDugfCNbpllpdJ9bA=="], + "maplibre-gl": ["maplibre-gl@6.10.0", "", { "dependencies": { "@mapbox/point-geometry": "^1.1.0", "@mapbox/tiny-sdf": "^2.2.0", "@mapbox/unitbezier": "^1.0.0", "@mapbox/vector-tile": "^3.0.0", "@maplibre/geojson-vt": "^6.1.1", "@maplibre/maplibre-gl-style-spec": "^26.4.4", "@maplibre/mlt": "^1.3.0", "@maplibre/vt-pbf": "^4.3.2", "@types/geojson": "^7946.0.16", "bidi-js": "^1.1.0", "earcut": "^3.2.3", "gl-matrix": "^3.4.4", "kdbush": "^4.1.0", "murmurhash-js": "^1.0.0", "pbf": "^5.1.2", "potpack": "^2.1.0", "quickselect": "^3.0.0", "tinyqueue": "^3.0.0" } }, "sha512-pZIJ1/rsB1jDjT3eBTfMaeSY45lRKdCuZtqXqTnkUrn0UJO9IwtbywT5ym3/cz57MGEELwAwQSYjB/Fj9TlktQ=="], "math-intrinsics": ["math-intrinsics@1.1.0", "", {}, "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="], - "media-typer": ["media-typer@0.3.0", "", {}, "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ=="], + "media-typer": ["media-typer@1.1.1", "", {}, "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ=="], - "merge-descriptors": ["merge-descriptors@1.0.3", "", {}, "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ=="], + "merge-descriptors": ["merge-descriptors@2.0.0", "", {}, "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g=="], - "methods": ["methods@1.1.2", "", {}, "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w=="], + "mime-db": ["mime-db@1.54.0", "", {}, "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ=="], - "mime": ["mime@1.6.0", "", { "bin": { "mime": "cli.js" } }, "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg=="], - - "mime-db": ["mime-db@1.52.0", "", {}, "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg=="], - - "mime-types": ["mime-types@2.1.35", "", { "dependencies": { "mime-db": "1.52.0" } }, "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw=="], + "mime-types": ["mime-types@3.0.2", "", { "dependencies": { "mime-db": "^1.54.0" } }, "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A=="], "minimist": ["minimist@1.2.8", "", {}, "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA=="], "motion": ["motion@12.43.0", "", { "dependencies": { "framer-motion": "^12.43.0", "tslib": "^2.4.0" }, "peerDependencies": { "@emotion/is-prop-valid": "*", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["@emotion/is-prop-valid", "react", "react-dom"] }, "sha512-BQgQbSa9Hn3/mtbib0MK53y6JSANa+YKUKlaYnWzAVDH424RYQ5LVpV3pNiWH00BA2z4ojsSdMzqT7g2FQwjuQ=="], - "motion-dom": ["motion-dom@12.43.0", "", { "dependencies": { "motion-utils": "^12.39.0" } }, "sha512-azKON4d9S65PEoFUiQTMTgPheEmzf2QngdRc50AKfJp9Q9mmcBVw22c8eMq9k8kxOFHdL7+WZY7N/5F/lwiDag=="], + "motion-dom": ["motion-dom@13.3.0", "", { "dependencies": { "motion-utils": "^13.3.0" } }, "sha512-AmAnB6pHdZ1vHGzWzuzteG6Q3j1lHKeX/lbST6jGlgm0cjvLUgaCk1xhOuPMOy5SgovN6wnnUdwFrkcsus7Ftg=="], - "motion-utils": ["motion-utils@12.39.0", "", {}, "sha512-8nadJAJjTtqRkmRF36FoJTrywK9nnFmnPwnSMyxaOCU7GDjN9RTMJIxx9De8ErM+vpPhMccr/6fo5WciyQLnMQ=="], + "motion-utils": ["motion-utils@13.3.0", "", {}, "sha512-sgSschQp7EseHInIlR7hBbMuvet3RA0bs28KPZAXJcGKGdxHGvh1ogpYDilY3bOMtl73EqPNmp75sAKHYPU5sg=="], - "ms": ["ms@2.0.0", "", {}, "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="], + "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], + + "multer": ["multer@2.4.0", "", { "dependencies": { "append-field": "^1.0.0", "busboy": "^1.6.0", "type-is": "^1.6.18" } }, "sha512-7dqa0ZcFfzbefdTuIkzOSMvZWC0J7FLqBOjJUZvDCXShIURWKxAyTT1wHhnE5q19c7jOJf43IYYKjBmZVZmvhg=="], "murmurhash-js": ["murmurhash-js@1.0.0", "", {}, "sha512-TvmkNhkv8yct0SVBSy+o8wYzXjE4Zz3PCesbfs8HiCXXdcTuocApFv11UWlNFWKYsP2okqrhb7JNlSm9InBhIw=="], - "nanoid": ["nanoid@3.3.18", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w=="], + "nanoid": ["nanoid@3.3.19", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-Y2tUNy4ouw6tq5oDSKeQYGOyhkUBhNOcGV/02KC+6kd9eDGqdZd++mjMiIDilrBYvjEnCYvVtsuHCuP+okSfug=="], - "negotiator": ["negotiator@0.6.3", "", {}, "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg=="], + "negotiator": ["negotiator@1.1.0", "", { "dependencies": { "content-type": "^2.1.0" } }, "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg=="], "node-domexception": ["node-domexception@1.0.0", "", {}, "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ=="], "node-fetch": ["node-fetch@3.3.2", "", { "dependencies": { "data-uri-to-buffer": "^4.0.0", "fetch-blob": "^3.1.4", "formdata-polyfill": "^4.0.10" } }, "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA=="], - "node-releases": ["node-releases@2.0.55", "", {}, "sha512-mIrE/Cw9y+9Au6dS5vDKDhQza9YvG6w+ZrS6X+ZzA7yFW/soAeaups4Qzn1bL6g5FVy8WtP79+0j82oPIbqRjQ=="], + "node-releases": ["node-releases@2.0.56", "", {}, "sha512-x0InOIyzgdk+eyaWaRJFH5snEtiImgBgblZ2CyPrLmqqcuMQkEvcDPHbzqbD8eDsSeJbVOjn+crzyzHaM4D+/A=="], "object-inspect": ["object-inspect@1.13.4", "", {}, "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew=="], "on-finished": ["on-finished@2.4.1", "", { "dependencies": { "ee-first": "1.1.1" } }, "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg=="], + "once": ["once@1.4.0", "", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="], + "p-retry": ["p-retry@4.6.2", "", { "dependencies": { "@types/retry": "0.12.0", "retry": "^0.13.1" } }, "sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ=="], "parseurl": ["parseurl@1.3.3", "", {}, "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ=="], - "path-to-regexp": ["path-to-regexp@0.1.13", "", {}, "sha512-A/AGNMFN3c8bOlvV9RreMdrv7jsmF9XIfDeCd87+I8RNg6s78BhJxMu69NEMHBSJFxKidViTEdruRwEk/WIKqA=="], + "path-to-regexp": ["path-to-regexp@8.4.2", "", {}, "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA=="], "pbf": ["pbf@5.1.2", "", { "dependencies": { "resolve-protobuf-schema": "^2.1.0" }, "bin": { "pbf": "bin/pbf" } }, "sha512-mnvGdvOrIvJOBGUEdGkrVXjN8E/VkIJCkf2eS1DH2yv82ORUlLttmDt0rWY38yYZmVwciZwBUvHM20qxBZf40w=="], @@ -541,6 +561,10 @@ "picomatch": ["picomatch@4.0.7", "", {}, "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA=="], + "playwright": ["playwright@1.63.0", "", { "dependencies": { "playwright-core": "1.63.0" }, "bin": { "playwright": "cli.js" } }, "sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg=="], + + "playwright-core": ["playwright-core@1.63.0", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg=="], + "postcss": ["postcss@8.5.28", "", { "dependencies": { "nanoid": "^3.3.18", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A=="], "postcss-value-parser": ["postcss-value-parser@4.2.0", "", {}, "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ=="], @@ -551,15 +575,15 @@ "protocol-buffers-schema": ["protocol-buffers-schema@3.6.1", "", {}, "sha512-VG2K63Igkiv9p76tk1lilczEK1cT+kCjKtkdhw1dQZV3k3IXJbd3o6Ho8b9zJZaHSnT2hKe4I+ObmX9w6m5SmQ=="], - "proxy-addr": ["proxy-addr@2.0.7", "", { "dependencies": { "forwarded": "0.2.0", "ipaddr.js": "1.9.1" } }, "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg=="], + "proxy-addr": ["proxy-addr@2.0.8", "", { "dependencies": { "forwarded": "0.2.0", "ipaddr.js": "1.9.1" } }, "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ=="], - "qs": ["qs@6.15.3", "", { "dependencies": { "es-define-property": "^1.0.1", "side-channel": "^1.1.1" } }, "sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A=="], + "qs": ["qs@6.16.0", "", { "dependencies": { "es-define-property": "^1.0.1", "side-channel": "^1.1.1" } }, "sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA=="], "quickselect": ["quickselect@3.0.0", "", {}, "sha512-XdjUArbK4Bm5fLLvlm5KpTFOiOThgfWWI4axAZDWg4E/0mKdZyI9tNEfds27qCi1ze/vwTR16kvmmGhRra3c2g=="], - "range-parser": ["range-parser@1.2.1", "", {}, "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg=="], + "range-parser": ["range-parser@1.3.0", "", {}, "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw=="], - "raw-body": ["raw-body@2.5.3", "", { "dependencies": { "bytes": "~3.1.2", "http-errors": "~2.0.1", "iconv-lite": "~0.4.24", "unpipe": "~1.0.0" } }, "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA=="], + "raw-body": ["raw-body@3.0.2", "", { "dependencies": { "bytes": "~3.1.2", "http-errors": "~2.0.1", "iconv-lite": "~0.7.0", "unpipe": "~1.0.0" } }, "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA=="], "react": ["react@19.3.0", "", {}, "sha512-E8LUcbtBWt20bbl2YoHfx4ZDBdxVTfOKtCZn9cDSJ4l6/nuoApcpIBcj47t2wZoVX8g2ZHuMHbiShgCR1T5Sog=="], @@ -567,13 +591,19 @@ "react-refresh": ["react-refresh@0.18.0", "", {}, "sha512-QgT5//D3jfjJb6Gsjxv0Slpj23ip+HtOpnNgnb2S5zU3CB26G/IDPGoy4RJB42wzFE46DRsstbW6tKHoKbhAxw=="], + "react-router": ["react-router@7.18.4", "", { "dependencies": { "cookie": "^1.0.1", "set-cookie-parser": "^2.6.0" }, "peerDependencies": { "react": ">=18", "react-dom": ">=18" }, "optionalPeers": ["react-dom"] }, "sha512-PUPQcMhMGRAslLcvtlPz/kmzBEWPhLdgLFrL7pLNepBL6dX0lWj4WD2cUYVgYCuT3jxvghYFg81cDTj44DhetQ=="], + + "react-router-dom": ["react-router-dom@7.18.4", "", { "dependencies": { "react-router": "7.18.4" }, "peerDependencies": { "react": ">=18", "react-dom": ">=18" } }, "sha512-yrfmJHIpDG7taCpqKjT1G5B6q3O2K+RN8/fgNf0lTjCwiPbQ0ei6vXX9ZjQR+7ld8Tr7Z5xmyMnZ8YJrphWQUw=="], + "require-from-string": ["require-from-string@2.0.2", "", {}, "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw=="], "resolve-protobuf-schema": ["resolve-protobuf-schema@2.1.0", "", { "dependencies": { "protocol-buffers-schema": "^3.3.1" } }, "sha512-kI5ffTiZWmJaS/huM8wZfEMer1eRd7oJQhDuxeCLe3t7N7mX3z94CN0xPxBQxFYQTSNz9T0i+v6inKqSdK8xrQ=="], "retry": ["retry@0.13.1", "", {}, "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg=="], - "rollup": ["rollup@4.63.1", "", { "dependencies": { "@types/estree": "1.0.9" }, "optionalDependencies": { "@napi-rs/lzma-linux-x64-gnu": "1.5.1", "@rollup/rollup-android-arm-eabi": "4.63.1", "@rollup/rollup-android-arm64": "4.63.1", "@rollup/rollup-darwin-arm64": "4.63.1", "@rollup/rollup-darwin-x64": "4.63.1", "@rollup/rollup-freebsd-arm64": "4.63.1", "@rollup/rollup-freebsd-x64": "4.63.1", "@rollup/rollup-linux-arm-gnueabihf": "4.63.1", "@rollup/rollup-linux-arm-musleabihf": "4.63.1", "@rollup/rollup-linux-arm64-gnu": "4.63.1", "@rollup/rollup-linux-arm64-musl": "4.63.1", "@rollup/rollup-linux-loong64-gnu": "4.63.1", "@rollup/rollup-linux-loong64-musl": "4.63.1", "@rollup/rollup-linux-ppc64-gnu": "4.63.1", "@rollup/rollup-linux-ppc64-musl": "4.63.1", "@rollup/rollup-linux-riscv64-gnu": "4.63.1", "@rollup/rollup-linux-riscv64-musl": "4.63.1", "@rollup/rollup-linux-s390x-gnu": "4.63.1", "@rollup/rollup-linux-x64-gnu": "4.63.1", "@rollup/rollup-linux-x64-musl": "4.63.1", "@rollup/rollup-openbsd-x64": "4.63.1", "@rollup/rollup-openharmony-arm64": "4.63.1", "@rollup/rollup-win32-arm64-msvc": "4.63.1", "@rollup/rollup-win32-ia32-msvc": "4.63.1", "@rollup/rollup-win32-x64-gnu": "4.63.1", "@rollup/rollup-win32-x64-msvc": "4.63.1", "fsevents": "~2.3.2" }, "bin": { "rollup": "dist/bin/rollup" } }, "sha512-3Df9jsstwhccuEfmAMi9l8XUh/GOkVObmFTU7CCVBysEbcOZLl84jCtaAZMcPiMz2EGKsATzQcU+Xr3n/wU6cg=="], + "rollup": ["rollup@4.63.3", "", { "dependencies": { "@types/estree": "1.0.9" }, "optionalDependencies": { "@napi-rs/lzma-linux-x64-gnu": "1.5.1", "@rollup/rollup-android-arm-eabi": "4.63.3", "@rollup/rollup-android-arm64": "4.63.3", "@rollup/rollup-darwin-arm64": "4.63.3", "@rollup/rollup-darwin-x64": "4.63.3", "@rollup/rollup-freebsd-arm64": "4.63.3", "@rollup/rollup-freebsd-x64": "4.63.3", "@rollup/rollup-linux-arm-gnueabihf": "4.63.3", "@rollup/rollup-linux-arm-musleabihf": "4.63.3", "@rollup/rollup-linux-arm64-gnu": "4.63.3", "@rollup/rollup-linux-arm64-musl": "4.63.3", "@rollup/rollup-linux-loong64-gnu": "4.63.3", "@rollup/rollup-linux-loong64-musl": "4.63.3", "@rollup/rollup-linux-ppc64-gnu": "4.63.3", "@rollup/rollup-linux-ppc64-musl": "4.63.3", "@rollup/rollup-linux-riscv64-gnu": "4.63.3", "@rollup/rollup-linux-riscv64-musl": "4.63.3", "@rollup/rollup-linux-s390x-gnu": "4.63.3", "@rollup/rollup-linux-x64-gnu": "4.63.3", "@rollup/rollup-linux-x64-musl": "4.63.3", "@rollup/rollup-openbsd-x64": "4.63.3", "@rollup/rollup-openharmony-arm64": "4.63.3", "@rollup/rollup-win32-arm64-msvc": "4.63.3", "@rollup/rollup-win32-ia32-msvc": "4.63.3", "@rollup/rollup-win32-x64-gnu": "4.63.3", "@rollup/rollup-win32-x64-msvc": "4.63.3", "fsevents": "~2.3.2" }, "bin": { "rollup": "dist/bin/rollup" } }, "sha512-1i2XreiAoMMXuPGD6Msj2xWrMMkHojNRKivInxGQcg7/1KuPuYlfUutLyh4drnOxUTHX9cHI4wFoat8D/NKaBw=="], + + "router": ["router@2.2.0", "", { "dependencies": { "debug": "^4.4.0", "depd": "^2.0.0", "is-promise": "^4.0.0", "parseurl": "^1.3.3", "path-to-regexp": "^8.0.0" } }, "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ=="], "safe-buffer": ["safe-buffer@5.2.1", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="], @@ -583,9 +613,11 @@ "semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], - "send": ["send@0.19.2", "", { "dependencies": { "debug": "2.6.9", "depd": "2.0.0", "destroy": "1.2.0", "encodeurl": "~2.0.0", "escape-html": "~1.0.3", "etag": "~1.8.1", "fresh": "~0.5.2", "http-errors": "~2.0.1", "mime": "1.6.0", "ms": "2.1.3", "on-finished": "~2.4.1", "range-parser": "~1.2.1", "statuses": "~2.0.2" } }, "sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg=="], + "send": ["send@1.2.1", "", { "dependencies": { "debug": "^4.4.3", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "fresh": "^2.0.0", "http-errors": "^2.0.1", "mime-types": "^3.0.2", "ms": "^2.1.3", "on-finished": "^2.4.1", "range-parser": "^1.2.1", "statuses": "^2.0.2" } }, "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ=="], + + "serve-static": ["serve-static@2.2.1", "", { "dependencies": { "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "parseurl": "^1.3.3", "send": "^1.2.0" } }, "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw=="], - "serve-static": ["serve-static@1.16.3", "", { "dependencies": { "encodeurl": "~2.0.0", "escape-html": "~1.0.3", "parseurl": "~1.3.3", "send": "~0.19.1" } }, "sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA=="], + "set-cookie-parser": ["set-cookie-parser@2.7.2", "", {}, "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw=="], "setprototypeof": ["setprototypeof@1.2.0", "", {}, "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw=="], @@ -601,6 +633,8 @@ "statuses": ["statuses@2.0.2", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="], + "streamsearch": ["streamsearch@1.1.0", "", {}, "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg=="], + "tailwindcss": ["tailwindcss@4.3.3", "", {}, "sha512-gOhV3P7ufE62QDGg1zVaTgCR+EtPv92k2nIhVcVKcLmxT1sUBsQGhnZj175j+MqRt4zLF7ic+sCYjfhxMxj7YQ=="], "tapable": ["tapable@2.3.3", "", {}, "sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A=="], @@ -615,7 +649,7 @@ "tsx": ["tsx@4.23.13", "", { "dependencies": { "esbuild": "~0.28.0" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "bin": { "tsx": "dist/cli.mjs" } }, "sha512-BL5MGkRln6aDYhb0xbQlEAGw743BaZYWdbWtdJOBriYJboKgUUYCadFp2/FpBBZquBC/ezNBn7wMMPx7FDZUDw=="], - "type-is": ["type-is@1.6.18", "", { "dependencies": { "media-typer": "0.3.0", "mime-types": "~2.1.24" } }, "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g=="], + "type-is": ["type-is@2.1.0", "", { "dependencies": { "content-type": "^2.0.0", "media-typer": "^1.1.0", "mime-types": "^3.0.0" } }, "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA=="], "typescript": ["typescript@5.8.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ=="], @@ -623,9 +657,7 @@ "unpipe": ["unpipe@1.0.0", "", {}, "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ=="], - "update-browserslist-db": ["update-browserslist-db@1.3.2", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": { "update-browserslist-db": "cli.js" } }, "sha512-UQ+MSxlhRm1bzjhU+DcuXfjFO1FzNtqhK5+9Yvlp90ItDLk5vT932A0rFu619nf7RVS+Y/VeaUW1jaRDqZ8VJw=="], - - "utils-merge": ["utils-merge@1.0.1", "", {}, "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA=="], + "update-browserslist-db": ["update-browserslist-db@1.3.3", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": { "update-browserslist-db": "cli.js" } }, "sha512-pJ2sYawQS0R/WI928Gj5GlPhTGzbMelq0+4INtSYNDV9ErKJcX6xjGWkoG/VnB3dpUm00zALaqkrUD77pO5TDQ=="], "vary": ["vary@1.1.2", "", {}, "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg=="], @@ -633,13 +665,15 @@ "web-streams-polyfill": ["web-streams-polyfill@3.3.3", "", {}, "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw=="], + "wrappy": ["wrappy@1.0.2", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="], + "ws": ["ws@8.21.3", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw=="], "yallist": ["yallist@3.1.1", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="], - "@babel/core/debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" }, "peerDependencies": { "supports-color": "*" }, "optionalPeers": ["supports-color"] }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], + "zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="], - "@babel/traverse/debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" }, "peerDependencies": { "supports-color": "*" }, "optionalPeers": ["supports-color"] }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], + "zustand": ["zustand@5.0.15", "", { "peerDependencies": { "@types/react": ">=18.0.0", "immer": ">=9.0.6", "react": ">=18.0.0", "use-sync-external-store": ">=1.2.0" }, "optionalPeers": ["@types/react", "immer", "react", "use-sync-external-store"] }, "sha512-MpSEjRiBkA9crSYeOUH32rJC7SVqAbm0Fqcqge/bUi2PPoLcBWKOsG+C8mevmpr8TwXHBVkChbbJiyvkE+i/3A=="], "@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/core@1.11.3", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.3", "tslib": "^2.4.0" }, "bundled": true }, "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg=="], @@ -647,51 +681,33 @@ "@tailwindcss/oxide-wasm32-wasi/@emnapi/wasi-threads": ["@emnapi/wasi-threads@1.2.3", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-ELEBe8PsLvvJ6QMr0zLt8ffvOHW/dc1m3CEzNMg7aJUv3bMaoDtw2TXyDAwkYBuroxxuHEwhRTLJSe5sya547g=="], - "@tailwindcss/oxide-wasm32-wasi/@napi-rs/wasm-runtime": ["@napi-rs/wasm-runtime@1.2.3", "", { "dependencies": { "@tybys/wasm-util": "^0.10.3" }, "peerDependencies": { "@emnapi/core": "^1.7.1 || ^2.0.0-alpha.4", "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.4" }, "bundled": true }, "sha512-UMduMbqO5s5zF2NkNacMT/yK5Y5QiKvWr2+50bzIIxFDwVJ2h49b+oyjaCGPhJxd2/gC2x39EHv/gHVuu36x2Q=="], + "@tailwindcss/oxide-wasm32-wasi/@napi-rs/wasm-runtime": ["@napi-rs/wasm-runtime@1.2.4", "", { "dependencies": { "@tybys/wasm-util": "^0.10.3" }, "peerDependencies": { "@emnapi/core": "^1.7.1 || ^2.0.0-alpha.4", "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.4" }, "bundled": true }, "sha512-AJxoUD2/15ESHbvpcyjU274nsAPLuOtPHCk0vKJM5pj//Fg/B1FXNWjPnXTT9PymCYYiHo4zPj0ZomXBKhoy7g=="], - "@tailwindcss/oxide-wasm32-wasi/@tybys/wasm-util": ["@tybys/wasm-util@0.10.3", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg=="], + "@tailwindcss/oxide-wasm32-wasi/@tybys/wasm-util": ["@tybys/wasm-util@0.10.4", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-W3c4gRigFS0T/Ma4qIYF3GDAc5AQdHb1yL5znJT1Zv1YaD9Kitx656wBjvr19qbiosmZT8lWDM5BEMynUqX65A=="], "@tailwindcss/oxide-wasm32-wasi/tslib": ["tslib@2.8.1", "", { "bundled": true }, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="], - "@types/body-parser/@types/node": ["@types/node@26.5.0", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-dVSGpriSoCgz8WnDNTuSSuSv1PC/ALXihO4ulRZt7Md8k9mlbdin3lGOcDE8SnWOgf513ByWlXd7BK4azmyg/A=="], - - "@types/connect/@types/node": ["@types/node@26.5.0", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-dVSGpriSoCgz8WnDNTuSSuSv1PC/ALXihO4ulRZt7Md8k9mlbdin3lGOcDE8SnWOgf513ByWlXd7BK4azmyg/A=="], - - "@types/express-serve-static-core/@types/node": ["@types/node@26.5.0", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-dVSGpriSoCgz8WnDNTuSSuSv1PC/ALXihO4ulRZt7Md8k9mlbdin3lGOcDE8SnWOgf513ByWlXd7BK4azmyg/A=="], - - "@types/send/@types/node": ["@types/node@26.5.0", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-dVSGpriSoCgz8WnDNTuSSuSv1PC/ALXihO4ulRZt7Md8k9mlbdin3lGOcDE8SnWOgf513ByWlXd7BK4azmyg/A=="], + "body-parser/content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="], - "@types/serve-static/@types/node": ["@types/node@26.5.0", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-dVSGpriSoCgz8WnDNTuSSuSv1PC/ALXihO4ulRZt7Md8k9mlbdin3lGOcDE8SnWOgf513ByWlXd7BK4azmyg/A=="], + "motion/framer-motion": ["framer-motion@12.43.0", "", { "dependencies": { "motion-dom": "^12.43.0", "motion-utils": "^12.39.0", "tslib": "^2.4.0" }, "peerDependencies": { "@emotion/is-prop-valid": "*", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["@emotion/is-prop-valid", "react", "react-dom"] }, "sha512-1eaL3RvR/kAlbG7UYcpMptEyzPoENO0c6w7ZnB3/hh2vSAz/6uGAFn6fdoqTBguNstf3MsFhJHsD/0DHiclG+g=="], - "@types/serve-static/@types/send": ["@types/send@0.17.6", "", { "dependencies": { "@types/mime": "^1", "@types/node": "*" } }, "sha512-Uqt8rPBE8SY0RK8JB1EzVOIZ32uqy8HwdxCnoCOsYrvnswqmFZ/k+9Ikidlk/ImhsdvBsloHbAlewb2IEBV/Og=="], + "multer/type-is": ["type-is@1.6.18", "", { "dependencies": { "media-typer": "0.3.0", "mime-types": "~2.1.24" } }, "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g=="], - "body-parser/qs": ["qs@6.16.0", "", { "dependencies": { "es-define-property": "^1.0.1", "side-channel": "^1.1.1" } }, "sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA=="], + "negotiator/content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="], - "https-proxy-agent/debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" }, "peerDependencies": { "supports-color": "*" }, "optionalPeers": ["supports-color"] }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], - - "protobufjs/@types/node": ["@types/node@26.5.0", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-dVSGpriSoCgz8WnDNTuSSuSv1PC/ALXihO4ulRZt7Md8k9mlbdin3lGOcDE8SnWOgf513ByWlXd7BK4azmyg/A=="], - - "send/ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], + "react-router/cookie": ["cookie@1.1.1", "", {}, "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ=="], "tsx/esbuild": ["esbuild@0.28.2", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.28.2", "@esbuild/android-arm": "0.28.2", "@esbuild/android-arm64": "0.28.2", "@esbuild/android-x64": "0.28.2", "@esbuild/darwin-arm64": "0.28.2", "@esbuild/darwin-x64": "0.28.2", "@esbuild/freebsd-arm64": "0.28.2", "@esbuild/freebsd-x64": "0.28.2", "@esbuild/linux-arm": "0.28.2", "@esbuild/linux-arm64": "0.28.2", "@esbuild/linux-ia32": "0.28.2", "@esbuild/linux-loong64": "0.28.2", "@esbuild/linux-mips64el": "0.28.2", "@esbuild/linux-ppc64": "0.28.2", "@esbuild/linux-riscv64": "0.28.2", "@esbuild/linux-s390x": "0.28.2", "@esbuild/linux-x64": "0.28.2", "@esbuild/netbsd-arm64": "0.28.2", "@esbuild/netbsd-x64": "0.28.2", "@esbuild/openbsd-arm64": "0.28.2", "@esbuild/openbsd-x64": "0.28.2", "@esbuild/openharmony-arm64": "0.28.2", "@esbuild/sunos-x64": "0.28.2", "@esbuild/win32-arm64": "0.28.2", "@esbuild/win32-ia32": "0.28.2", "@esbuild/win32-x64": "0.28.2" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA=="], - "@babel/core/debug/ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], - - "@babel/traverse/debug/ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], - - "@types/body-parser/@types/node/undici-types": ["undici-types@8.9.0", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="], + "type-is/content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="], - "@types/connect/@types/node/undici-types": ["undici-types@8.9.0", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="], + "motion/framer-motion/motion-dom": ["motion-dom@12.43.0", "", { "dependencies": { "motion-utils": "^12.39.0" } }, "sha512-azKON4d9S65PEoFUiQTMTgPheEmzf2QngdRc50AKfJp9Q9mmcBVw22c8eMq9k8kxOFHdL7+WZY7N/5F/lwiDag=="], - "@types/express-serve-static-core/@types/node/undici-types": ["undici-types@8.9.0", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="], + "motion/framer-motion/motion-utils": ["motion-utils@12.39.0", "", {}, "sha512-8nadJAJjTtqRkmRF36FoJTrywK9nnFmnPwnSMyxaOCU7GDjN9RTMJIxx9De8ErM+vpPhMccr/6fo5WciyQLnMQ=="], - "@types/send/@types/node/undici-types": ["undici-types@8.9.0", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="], + "multer/type-is/media-typer": ["media-typer@0.3.0", "", {}, "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ=="], - "@types/serve-static/@types/node/undici-types": ["undici-types@8.9.0", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="], - - "https-proxy-agent/debug/ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], - - "protobufjs/@types/node/undici-types": ["undici-types@8.9.0", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="], + "multer/type-is/mime-types": ["mime-types@2.1.35", "", { "dependencies": { "mime-db": "1.52.0" } }, "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw=="], "tsx/esbuild/@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.28.2", "", { "os": "aix", "cpu": "ppc64" }, "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ=="], @@ -744,5 +760,7 @@ "tsx/esbuild/@esbuild/win32-ia32": ["@esbuild/win32-ia32@0.28.2", "", { "os": "win32", "cpu": "ia32" }, "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA=="], "tsx/esbuild/@esbuild/win32-x64": ["@esbuild/win32-x64@0.28.2", "", { "os": "win32", "cpu": "x64" }, "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g=="], + + "multer/type-is/mime-types/mime-db": ["mime-db@1.52.0", "", {}, "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg=="], } } diff --git a/docker-compose.yml b/docker-compose.yml deleted file mode 100644 index 25ea154..0000000 --- a/docker-compose.yml +++ /dev/null @@ -1,43 +0,0 @@ -version: '3.8' -# docker-compose.yml — Agent E (E-2) - -services: - backend: - build: . - ports: - - "8080:8080" - environment: - - SATQUERY_ENV=production - - BHUVAN_API_KEY=${BHUVAN_API_KEY} - - MOSDAC_USERNAME=${MOSDAC_USERNAME} - - MOSDAC_PASSWORD=${MOSDAC_PASSWORD} - - HF_TOKEN=${HF_TOKEN} - - SATQUERY_API_KEY=${SATQUERY_API_KEY} - - FRONTEND_URL=http://localhost:80 - volumes: - - ./data:/app/data - - model-weights:/app/data/weights - restart: unless-stopped - healthcheck: - test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8080/api/health')"] - interval: 30s - timeout: 10s - retries: 3 - deploy: - resources: - limits: - memory: 8G - cpus: '4' - - nginx: - image: nginx:alpine - ports: - - "80:80" - volumes: - - ./nginx.conf:/etc/nginx/nginx.conf:ro - depends_on: - - backend - restart: unless-stopped - -volumes: - model-weights: diff --git a/frontend/.env.example b/frontend/.env.example deleted file mode 100644 index b6c1dfb..0000000 --- a/frontend/.env.example +++ /dev/null @@ -1,9 +0,0 @@ -# APP_URL: The URL where this applet is hosted. -# AI Studio automatically injects this at runtime with the Cloud Run service URL. -# Used for self-referential links, OAuth callbacks, and API endpoints. -APP_URL="MY_APP_URL" - -# NOTE: A Gemini API key was previously collected here / client-side. It has been -# removed intentionally: the problem statement (SIH26167) disqualifies solutions -# built on a generic LLM/VLM without remote-sensing adaptation, and collecting a -# consumer API key client-side is also not something to demo to judges. diff --git a/frontend/.gitignore b/frontend/.gitignore deleted file mode 100644 index 5a86d2a..0000000 --- a/frontend/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -node_modules/ -build/ -dist/ -coverage/ -.DS_Store -*.log -.env* -!.env.example diff --git a/frontend/DESIGN_SYSTEM_ROADMAP.md b/frontend/DESIGN_SYSTEM_ROADMAP.md deleted file mode 100644 index b3791ed..0000000 --- a/frontend/DESIGN_SYSTEM_ROADMAP.md +++ /dev/null @@ -1,151 +0,0 @@ -# SatQuery AI — Product Design & Branding Roadmap - -> Working document. This is the single source of truth for the "make it feel like -> a shipped product, not a hackathon prototype" effort. Every session that touches -> UI/branding should read the **Progress Log** at the bottom before starting, and -> append to it before stopping. - ---- - -## 1. The end vision - -Today the app is functionally strong (real DAG-based audit trail, honest-failure -error handling, six purpose-built Studios) but visually reads as a generic dark -"tactical ops" template — because in places, literally, it was one (see the -`WorldMonitor` residue found and removed in Phase 0). The goal is not to change -what the product *does*. It's to make the first 10 seconds and the next 10 minutes -feel like a deliberately designed product from a team that knows exactly what -they're building, aimed at ISRO SAC evaluators who will judge polish as a proxy -for engineering rigor. - -Concretely, "professional product" means: - -1. **One brand, consistently applied.** A single mark, a single name lockup - (`SatQuery AI` · `Divya Drishti` subordinate), one color system driving every - surface — not per-component hex values chosen independently over months of - iteration. -2. **A real front door.** A landing/briefing screen that sets context before - dropping the user into a dense operational console — not the console itself - as the entry point. -3. **Consistent interaction language across all 6 Studios.** Right now each - Studio (`Bitemporal`, `Crossmodal`, `Grounding`, `Benchmark`, `Ingestion`, - `Audit`) was built somewhat independently: panel chrome, spacing, badge - styles, and status-color usage all drift slightly page to page. A shared - layout shell + shared primitives (badges, panel headers, empty states) would - make the whole app feel like one system instead of six sub-apps stitched - together. -4. **Semantic color discipline.** Amber/cyan/emerald/red should mean something - specific (warning/sensor/success/danger) everywhere, all the time — never - decorative. - -## 2. Brand identity decisions (locked in Phase 0) - -- **Name lockup:** `SatQuery AI` (primary) · `Divya Drishti` (team name, - subordinate) · `ISRO SAC · SIH26167` (provenance badge, smallest weight). -- **Mark:** orbital-sweep-over-aperture SVG (two concentric arcs + solid center - dot) on a brand-gradient rounded square. Lives at: - `frontend/public/favicon.svg`, inlined in `HeaderHUD.tsx` and `Landing.tsx`. -- **Brand hue:** Deep Space Indigo, `--sq-brand-500: #4C6FFF`. Reserved for - brand marks, primary CTAs, and active-nav state only. -- **Semantic hues (status-only, never decorative):** `--sq-success` (emerald), - `--sq-warning` (amber), `--sq-danger` (red), `--sq-sensor` (cyan — radar/SAR - + telemetry accents specifically). -- **Neutral surface scale:** `--sq-bg-0` (app canvas) → `--sq-bg-3` (raised - card/hover), `--sq-border-1/2`, `--sq-text-primary/secondary/muted`. -- **Type:** Plus Jakarta Sans (UI/prose), IBM Plex Mono (data/telemetry/labels) - — unchanged, just now formalized as the rule rather than an accident of what - was already loaded. -- All tokens live in `frontend/src/index.css` under `:root` — see that file's - top comment block for the full list before adding a new color anywhere. - -## 3. Phases - -### Phase 0 — Brand foundation + Landing screen — **DONE** -- Design token layer added to `index.css`. -- Removed literal `WorldMonitor` template residue from `App.tsx` comments and - `mapConfig.ts` style names. -- Rebuilt `HeaderHUD.tsx` brand mark + name lockup off the token system. -- Added `favicon.svg`, fixed `index.html` title/meta/OG tags to read as a - product, not a problem-statement filename. -- Built `src/pages/Landing.tsx`: auto-rotating MapLibre globe (`globe` - projection, reuses `createMapLibreStyle('dark','globe')` — no new deps), - hero + 3 capability cards + trust strip + footer credit. "Launch Console" - stops the rotation and `flyTo`s the globe into the dashboard's exact opening - camera (`lat 23.03, lon 72.58, zoom 3.5, pitch 35`) before navigating to - `/dashboard`, so the handoff reads as one continuous flight rather than a - page cut. Wired into `main.tsx` via `react-router` (`/` → Landing, - `/*` → App). -- **Known limitation, by design:** this is two MapLibre instances - choreographed to land in the same place, not one instance handed off across - the route change (that would require refactoring `MapCanvas.tsx` itself — - too risky this close to judging). Worth revisiting post-SIH if a true - single-instance transition is wanted. - -### Phase 1 — Design token migration (in progress) -Goal: every component references `var(--sq-*)` tokens instead of one-off hex -values, so a future palette tweak is a one-file change, not a grep-and-pray. - -Order of attack (safest/highest-leverage first): -1. `RightOperationalPanel.tsx`, `QueryPromptBar.tsx`, `LayersPanel.tsx` — - shared chrome visible on every Studio. -2. `MapHeaderRibbon.tsx`, `TemporalScrubber.tsx`, `SearchModal.tsx`, - `SituationalFeedDrawer.tsx`, `BenchmarkModal.tsx`, `GeoTIFFModal.tsx`, - `ModelStatusModal.tsx` — secondary chrome/modals. -3. `MapCanvas.tsx` — touched last and most carefully; it's the most complex, - most load-bearing file in the app (live map state, dual-instance bitemporal - swipe, sensor-band filters). Cosmetic token swaps only, no logic changes. -4. `components/ui/StatusBadge.tsx`, `TelemetryGauge.tsx` — these are the - primitives other components should eventually be refactored to use instead - of hand-rolling badges inline; formalizing them is a Phase 3 task, not - Phase 1. - -### Phase 2 — Studio-by-studio consistency pass -Goal: one shared `StudioShell` layout (header pattern, panel spacing, empty -states) that `BitemporalStudio`, `CrossmodalStudio`, `GroundingStudio`, -`BenchmarkStudio`, `IngestionStudio`, and `AuditStudio` all sit inside, so -switching Studios feels like navigating one product instead of six. -Going one Studio at a time, in this order (simplest → most complex, so the -shared shell gets validated early on a low-risk page): -1. `AuditStudio.tsx` -2. `GroundingStudio.tsx` -3. `IngestionStudio.tsx` -4. `BenchmarkStudio.tsx` -5. `CrossmodalStudio.tsx` -6. `BitemporalStudio.tsx` (most complex — swipe curtain, dual-map sync) - -### Phase 3 — Primitives + polish pass (stretch, post-Phase 2) -Formalize `StatusBadge`/`TelemetryGauge` as the only way badges/gauges get -built; sweep for remaining inconsistent spacing/radius; mobile bottom-nav -polish. - ---- - -## 4. Progress Log -*(most recent first — append here, don't rewrite history)* - -- **2026-09-12** — Started Phase 1 by reading `RightOperationalPanel.tsx` in - full (the densest shared-chrome file). Finding: the near-black surface - colors across panels/modals aren't a small, clean set — they're dozens of - hand-picked near-duplicate shades (`#0A0D15` vs `#0E121B` vs `#0E131E` - vs `#111520`, etc.) chosen file-by-file over time. Mass find-and-replacing - these onto the Phase 0 token scale, sight-unseen, risks visibly shifting - panel contrast/hierarchy in a codebase I can't render or screenshot from - here — and I'm not going to gamble with that 6 days before your rounds. - **Pivot:** added a canonical hex→token mapping table to the top of - `index.css` ("MIGRATION NOTE") documenting exactly which existing hex maps - to which token. This is zero-risk (pure documentation, no component files - touched) and means the *next* person (me, next session, or you) doing the - actual per-file swap has a lookup table instead of having to eyeball it. - **Recommendation for the real swap:** do it with `npm run dev` running so - each file's diff can be visually checked before moving to the next — - either you drive with me giving you the replacements file-by-file, or we - do it together in a session where I can see rendered output (e.g. via a - screenshot you share, or once a preview/browser tool is available here). - Blind mechanical edits to `RightOperationalPanel.tsx`, `MapCanvas.tsx`, and - the six Studio pages are exactly the kind of change that should be visually - verified, not shipped on faith. - Phase 0 remains fully done and safe (brand tokens, WorldMonitor residue - removed, HeaderHUD rebrand, favicon/meta, Landing.tsx with rotating globe + - flyTo handoff, routing wired in `main.tsx`). Phase 2 (Studio shell) is - blocked on the same visual-verification constraint and should follow the - same file-by-file, dev-server-checked approach. diff --git a/frontend/README.md b/frontend/README.md deleted file mode 100644 index 729cd04..0000000 --- a/frontend/README.md +++ /dev/null @@ -1,20 +0,0 @@ -
-GHBanner -
- -# Run and deploy your AI Studio app - -This contains everything you need to run your app locally. - -View your app in AI Studio: https://ai.studio/apps/03d7c284-2f15-4ce0-b059-b914feb5aeb2 - -## Run Locally - -**Prerequisites:** Node.js - - -1. Install dependencies: - `npm install` -2. Set the `GEMINI_API_KEY` in [.env.local](.env.local) to your Gemini API key -3. Run the app: - `npm run dev` diff --git a/frontend/audit.mjs b/frontend/audit.mjs deleted file mode 100644 index 46bf7a7..0000000 --- a/frontend/audit.mjs +++ /dev/null @@ -1,607 +0,0 @@ -/** - * SatQuery AI // Full UI/UX Audit Script - * Uses installed Playwright Chromium to audit http://localhost:5173/ - */ -import { chromium } from 'playwright'; -import { existsSync, mkdirSync } from 'fs'; -import { join } from 'path'; - -const CHROME_EXEC = '/Users/tanmay/Library/Caches/ms-playwright/chromium-1243/chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing'; -const SCREENSHOT_DIR = '/Users/tanmay/SIH-2026/frontend/audit_screenshots'; -const BASE_URL = 'http://localhost:5173'; - -if (!existsSync(SCREENSHOT_DIR)) mkdirSync(SCREENSHOT_DIR, { recursive: true }); - -const defects = []; -let stepCount = 0; - -async function ss(page, name, note = '') { - stepCount++; - const filename = join(SCREENSHOT_DIR, `${name}.png`); - try { - await page.screenshot({ path: filename, fullPage: false }); - console.log(`📸 ${name}.png ${note ? '→ ' + note : ''}`); - } catch(e) { - console.log(`⚠️ Screenshot failed: ${name} — ${e.message}`); - } - return filename; -} - -async function wait(ms) { - return new Promise(r => setTimeout(r, ms)); -} - -function defect(id, severity, component, trigger, description, screenshot) { - defects.push({ id, severity, component, trigger, description, screenshot }); - console.log(`🚨 [${severity}] DEF-${id}: ${description}`); -} - -(async () => { - console.log('\n=== SATQUERY AI // MASTER VISUAL AUDIT ===\n'); - - const browser = await chromium.launch({ - executablePath: CHROME_EXEC, - headless: true, - args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage', '--disable-web-security'], - }); - - const context = await browser.newContext({ - viewport: { width: 1440, height: 900 }, - deviceScaleFactor: 2, - }); - const page = await context.newPage(); - page.on('console', () => {}); - page.on('pageerror', () => {}); - - try { - // PHASE 1: INITIAL LOAD & TOP HUD - console.log('\n--- PHASE 1: INITIAL LOAD & TOP HUD ---'); - await page.goto(BASE_URL, { waitUntil: 'domcontentloaded', timeout: 30000 }); - await wait(4000); - await ss(page, 'STEP_001_INITIAL_LOAD', 'Full app initial render'); - - const mapCanvas = await page.$('.maplibregl-canvas'); - if (!mapCanvas) { - defect('001', 'P1', 'MapCanvas', 'Initial Load', 'MapLibre canvas not found — WebGL may have failed', 'STEP_001_INITIAL_LOAD'); - } else { - console.log('✅ MapLibre canvas found'); - } - - const promptBar = await page.$('#query-prompt-bar-container'); - const rightPanel = await page.$('#right-operational-deck'); - if (!promptBar) defect('002', 'P2', 'QueryPromptBar', 'Initial Load', 'Prompt bar not found on initial load', 'STEP_001_INITIAL_LOAD'); - if (!rightPanel) defect('003', 'P2', 'RightOperationalPanel', 'Initial Load', 'Right panel not found on initial load', 'STEP_001_INITIAL_LOAD'); - - // Model Chip - const modelChip = await page.$('button:has-text("RemoteCLIP")'); - if (modelChip) { - await modelChip.click(); await wait(600); - await ss(page, 'STEP_002_MODEL_CHIP_MODAL', 'Model chip clicked'); - await page.keyboard.press('Escape'); await wait(400); - await ss(page, 'STEP_003_MODAL_CLOSED', 'Modal closed'); - } else { - defect('004', 'P3', 'HeaderHUD', 'Model Chip', 'RemoteCLIP chip not visible at 1440px width', 'STEP_001_INITIAL_LOAD'); - await ss(page, 'STEP_002_MODEL_CHIP_MODAL', 'Model chip not found'); - await ss(page, 'STEP_003_MODAL_CLOSED', 'N/A'); - } - - // Navigation Pills - const navItems = [ - { label: 'Dashboard', step: 'STEP_004' }, - { label: 'Bi-Temporal', step: 'STEP_005' }, - { label: 'Radar SAR', step: 'STEP_006' }, - { label: 'Grounding', step: 'STEP_007' }, - { label: 'Benchmarks', step: 'STEP_008' }, - { label: 'Data', step: 'STEP_009' }, - { label: 'Audit DAG', step: 'STEP_010' }, - ]; - - for (const nav of navItems) { - console.log(`Clicking nav: ${nav.label}...`); - const pill = await page.$(`button:has-text("${nav.label}")`); - if (pill) { - await pill.click(); await wait(800); - const url = page.url(); - await ss(page, `${nav.step}_NAV_${nav.label.replace(/\s+/g,'').toUpperCase()}`, `URL: ${url}`); - } else { - defect('005', 'P1', 'HeaderHUD', `Nav ${nav.label}`, `"${nav.label}" pill not found in DOM`, nav.step); - } - } - - // Back to Dashboard - const dash = await page.$('button:has-text("Dashboard")'); - if (dash) { await dash.click(); await wait(700); } - - // Feed Drawer - console.log('Testing Feed Drawer...'); - const feedBtn = await page.$('button:has-text("Feed")'); - if (feedBtn) { - await feedBtn.click(); await wait(700); - await ss(page, 'STEP_011_FEED_DRAWER_OPEN', 'Feed drawer opened'); - - const feedDrawer = await page.$('#situational-feed-drawer'); - if (feedDrawer) { - const box = await feedDrawer.boundingBox(); - console.log(`Feed drawer: x=${box.x.toFixed(0)} y=${box.y.toFixed(0)} w=${box.width.toFixed(0)} h=${box.height.toFixed(0)}`); - if (box.width > 420) defect('006', 'P1', 'SituationalFeedDrawer', 'Open', `Drawer too wide (${box.width.toFixed(0)}px) — may occlude map center`, 'STEP_011_FEED_DRAWER_OPEN'); - } else { - defect('007', 'P1', 'SituationalFeedDrawer', 'Open', '#situational-feed-drawer not found in DOM', 'STEP_011_FEED_DRAWER_OPEN'); - } - - const alertsTab = await page.$('button:has-text("ALERTS")'); - if (alertsTab) { await alertsTab.click(); await wait(400); await ss(page, 'STEP_012_FEED_ALERTS_TAB', 'Alerts tab'); } - - const passesTab = await page.$('button:has-text("PASSES")'); - if (passesTab) { await passesTab.click(); await wait(400); await ss(page, 'STEP_013_FEED_PASSES_TAB', 'Passes tab'); } - - const layersTab = await page.$('button:has-text("LAYERS")'); - if (layersTab) { await layersTab.click(); await wait(400); await ss(page, 'STEP_014_FEED_LAYERS_TAB', 'Layers tab'); } - - // Back to alerts - if (alertsTab) { await alertsTab.click(); await wait(400); } - - if (feedDrawer) { - await feedDrawer.evaluate(el => { el.scrollTop += 200; }); await wait(300); - await ss(page, 'STEP_015_FEED_SCROLL', 'Feed scrolled'); - } - - // Fly to — alert cards are clickable divs - const alertCard = await page.$('#situational-feed-drawer .cursor-pointer'); - if (alertCard) { - await alertCard.click(); await wait(700); - await ss(page, 'STEP_016_FEED_FLYTO', 'Alert card clicked (fly-to)'); - } else { - defect('008', 'P3', 'SituationalFeedDrawer', 'Fly To', 'No .cursor-pointer alert card found for fly-to', 'STEP_015_FEED_SCROLL'); - await ss(page, 'STEP_016_FEED_FLYTO', 'Alert fly-to not triggered'); - } - - // Close - const xBtn = await page.$('#situational-feed-drawer button:first-child, #situational-feed-drawer button[title]'); - const allBtns = await page.$$('#situational-feed-drawer button'); - if (allBtns.length > 0) { - await allBtns[0].click(); await wait(400); - await ss(page, 'STEP_017_FEED_CLOSED', 'Feed drawer closed'); - } - } else { - defect('009', 'P2', 'HeaderHUD', 'Feed Toggle', 'Feed button not found in header', 'STEP_001_INITIAL_LOAD'); - await ss(page, 'STEP_011_FEED_DRAWER_OPEN', 'Feed not opened'); - } - - // PHASE 2: CANVAS TOOL DOCK & MAP CONTROLS - console.log('\n--- PHASE 2: CANVAS TOOL DOCK & MAP CONTROLS ---'); - - // Try opening layers panel via any button with "Layers" text or title - const layerBtn = await page.$('button[title*="Layer"], button[title*="layer"]'); - if (layerBtn) { - await layerBtn.click(); await wait(600); - await ss(page, 'STEP_018_LAYERS_PANEL_OPEN', 'Layers panel opened'); - - const layersPanel = await page.$('#layers-drawer-panel'); - if (layersPanel) { - const firstToggle = await layersPanel.$('button'); - if (firstToggle) { - await firstToggle.click(); await wait(400); - await ss(page, 'STEP_019_LAYER_TOGGLE_OFF', 'Layer toggled off'); - await firstToggle.click(); await wait(300); - } - const opacitySlider = await layersPanel.$('input[type="range"]'); - if (opacitySlider) { - const cls = await opacitySlider.getAttribute('class') || ''; - if (!cls.includes('appearance-none')) { - defect('010', 'P2', 'LayersPanel', 'Opacity Slider', 'Layer opacity slider lacks appearance-none — may show default OS slider thumb', 'STEP_018_LAYERS_PANEL_OPEN'); - } - await opacitySlider.evaluate(el => { el.value = '0'; el.dispatchEvent(new Event('input', {bubbles:true})); }); - await wait(400); - await ss(page, 'STEP_020_LAYER_OPACITY_0', 'Layer opacity at 0%'); - await opacitySlider.evaluate(el => { el.value = '80'; el.dispatchEvent(new Event('input', {bubbles:true})); }); - await wait(300); - } - const closePanelBtn = await page.$('#close-layers-panel-btn'); - if (closePanelBtn) { - await closePanelBtn.click(); await wait(400); - await ss(page, 'STEP_021_LAYERS_CLOSED', 'Layers panel closed'); - } - } - } else { - defect('011', 'P2', 'LayersPanel', 'Layers toggle', 'Layers toggle button not found by title', 'STEP_001_INITIAL_LOAD'); - await ss(page, 'STEP_018_LAYERS_PANEL_OPEN', 'Layers panel not opened'); - await ss(page, 'STEP_019_LAYER_TOGGLE_OFF', 'N/A'); - await ss(page, 'STEP_020_LAYER_OPACITY_0', 'N/A'); - await ss(page, 'STEP_021_LAYERS_CLOSED', 'N/A'); - } - - // Zoom controls - const plusBtn = await page.$('button[title*="Zoom in"], button[title*="zoom in"], button[title*="Zoom In"]'); - if (plusBtn) { - for (let i = 0; i < 3; i++) { await plusBtn.click(); await wait(400); } - await ss(page, 'STEP_022_ZOOM_IN', 'Zoomed in 3x'); - const minusBtn = await page.$('button[title*="Zoom out"], button[title*="zoom out"], button[title*="Zoom Out"]'); - if (minusBtn) { - for (let i = 0; i < 3; i++) { await minusBtn.click(); await wait(400); } - await ss(page, 'STEP_023_ZOOM_OUT', 'Zoomed out 3x'); - } - } else { - defect('012', 'P3', 'MapCanvas', 'Zoom Controls', 'Zoom in/out buttons not found by title — may lack title attributes', 'STEP_022_ZOOM_IN'); - await ss(page, 'STEP_022_ZOOM_IN', 'Zoom buttons not found'); - await ss(page, 'STEP_023_ZOOM_OUT', 'N/A'); - } - - // Swipe - const swipeBtn = await page.$('button[title*="wipe"], button[title*="Swipe"], button[title*="curtain"]'); - if (swipeBtn) { - await swipeBtn.click(); await wait(700); - await ss(page, 'STEP_024_SWIPE_CURTAIN', 'Swipe curtain toggled'); - } else { - await ss(page, 'STEP_024_SWIPE_CURTAIN', 'Swipe button not found'); - } - - // Projection - const projBtn = await page.$('button[title*="Globe"], button[title*="globe"], button[title*="Mercator"], button[title*="3D"]'); - if (projBtn) { - await projBtn.click(); await wait(700); - await ss(page, 'STEP_025_PROJECTION_TOGGLE', 'Projection toggled'); - } else { - await ss(page, 'STEP_025_PROJECTION_TOGGLE', 'Projection toggle not found'); - } - - // Basemap - const basemapBtn = await page.$('#basemap-toggle-btn'); - if (basemapBtn) { - await basemapBtn.click(); await wait(700); - await ss(page, 'STEP_026_BASEMAP_TOGGLE', 'Basemap switched to Satellite'); - await basemapBtn.click(); await wait(500); - } else { - defect('013', 'P2', 'HeaderHUD', 'Basemap Toggle', '#basemap-toggle-btn not found', 'STEP_026_BASEMAP_TOGGLE'); - await ss(page, 'STEP_026_BASEMAP_TOGGLE', 'Basemap toggle not found'); - } - - // Map pin clicks - const mapContainer = await page.$('.maplibregl-canvas-container'); - if (mapContainer) { - const mapBox = await mapContainer.boundingBox(); - if (mapBox) { - await page.mouse.click(mapBox.x + mapBox.width * 0.4, mapBox.y + mapBox.height * 0.5); - await wait(800); - await ss(page, 'STEP_027_MAP_PIN_CLICK_1', 'Map click at center-left'); - await page.mouse.click(mapBox.x + mapBox.width * 0.6, mapBox.y + mapBox.height * 0.4); - await wait(800); - await ss(page, 'STEP_028_MAP_PIN_CLICK_2', 'Map click at center-right'); - } - } - - // PHASE 3: TEMPORAL SCRUBBER - console.log('\n--- PHASE 3: TEMPORAL SCRUBBER ---'); - const scrubber = await page.$('#temporal-scrubber-hud'); - if (scrubber) { - await ss(page, 'STEP_029_SCRUBBER_BASELINE', 'Temporal scrubber baseline'); - - const rangeInput = await page.$('#temporal-scrubber-hud input[type="range"]'); - if (rangeInput) { - const cls = await rangeInput.getAttribute('class') || ''; - console.log('Scrubber slider classes:', cls.slice(0, 120) + '...'); - if (cls.includes('[&::-webkit-slider-thumb]')) { - console.log('✅ Custom slider thumb styling applied via Tailwind JIT'); - } else { - defect('014', 'P2', 'TemporalScrubber', 'Slider Thumb', 'Temporal scrubber slider may not have custom thumb styling applied', 'STEP_029_SCRUBBER_BASELINE'); - } - } - - for (const [range, step] of [['24h','STEP_030'],['7d','STEP_031'],['30d','STEP_032'],['1y','STEP_033'],['all','STEP_034']]) { - const btn = await scrubber.$(`button:has-text("${range}")`); - if (btn) { await btn.click(); await wait(400); await ss(page, `${step}_RANGE_${range.toUpperCase()}`, `Range: ${range}`); } - } - - if (rangeInput) { - await rangeInput.evaluate(el => { el.value = '0'; el.dispatchEvent(new Event('input', {bubbles:true})); }); - await wait(400); - await ss(page, 'STEP_035_SLIDER_0', 'Slider at 0%'); - - await rangeInput.evaluate(el => { el.value = '50'; el.dispatchEvent(new Event('input', {bubbles:true})); }); - await wait(400); - await ss(page, 'STEP_036_SLIDER_50', 'Slider at 50%'); - - await rangeInput.evaluate(el => { el.value = '100'; el.dispatchEvent(new Event('input', {bubbles:true})); }); - await wait(400); - await ss(page, 'STEP_037_SLIDER_100', 'Slider at 100%'); - - await rangeInput.evaluate(el => { el.value = '50'; el.dispatchEvent(new Event('input', {bubbles:true})); }); - await wait(300); - } - - const milestones = await scrubber.$$('button[title]'); - console.log(`Found ${milestones.length} milestone buttons`); - if (milestones.length >= 1) { await milestones[0].click(); await wait(400); await ss(page, 'STEP_038_MILESTONE_T0', 'T0 milestone'); } - if (milestones.length >= 4) { await milestones[3].click(); await wait(400); await ss(page, 'STEP_039_MILESTONE_T2', 'T2 milestone'); } - - const sweepBtn = await scrubber.$('button:has-text("SWEEP")'); - if (sweepBtn) { - await sweepBtn.click(); await wait(1500); - await ss(page, 'STEP_040_SWEEP_PLAYING', 'Sweep playing'); - const pauseBtn = await scrubber.$('button:has-text("PAUSE")'); - if (pauseBtn) { await pauseBtn.click(); await wait(400); await ss(page, 'STEP_041_SWEEP_PAUSED', 'Sweep paused'); } - else { await sweepBtn.click(); await wait(400); await ss(page, 'STEP_041_SWEEP_PAUSED', 'Sweep stopped'); } - } else { - defect('015', 'P2', 'TemporalScrubber', 'Sweep Playback', 'SWEEP button not found', 'STEP_040_SWEEP_PLAYING'); - await ss(page, 'STEP_040_SWEEP_PLAYING', 'N/A'); await ss(page, 'STEP_041_SWEEP_PAUSED', 'N/A'); - } - - const resetBtn = await scrubber.$('button[title*="Reset"]'); - if (resetBtn) { await resetBtn.click(); await wait(400); await ss(page, 'STEP_042_SCRUBBER_RESET', 'Scrubber reset to 50%'); } - else { defect('016', 'P3', 'TemporalScrubber', 'Reset Button', 'Reset button (title*=Reset) not found', 'STEP_042_SCRUBBER_RESET'); await ss(page, 'STEP_042_SCRUBBER_RESET', 'N/A'); } - } else { - defect('017', 'P0', 'TemporalScrubber', 'Inspect', '#temporal-scrubber-hud not found in DOM', 'STEP_029_SCRUBBER_BASELINE'); - } - - // PHASE 4: QUERY PROMPT BAR - console.log('\n--- PHASE 4: QUERY PROMPT BAR ---'); - const promptBarEl = await page.$('#query-prompt-bar-container'); - if (promptBarEl) { - await ss(page, 'STEP_043_PROMPT_BAR', 'Prompt bar baseline'); - - const promptBox = await promptBarEl.boundingBox(); - const scrubberEl2 = await page.$('#temporal-scrubber-hud'); - const scrubberBox = scrubberEl2 ? await scrubberEl2.boundingBox() : null; - if (promptBox && scrubberBox) { - const promptBottom = promptBox.y + promptBox.height; - const scrubberTop = scrubberBox.y; - console.log(`Prompt bar bottom: ${promptBottom.toFixed(0)}px, Scrubber top: ${scrubberTop.toFixed(0)}px`); - if (promptBottom > scrubberTop + 10) { - defect('018', 'P1', 'QueryPromptBar', 'Layout', `Prompt bar bottom (${promptBottom.toFixed(0)}px) overlaps scrubber top (${scrubberTop.toFixed(0)}px)`, 'STEP_043_PROMPT_BAR'); - } else { - console.log('✅ Prompt bar clears scrubber — no overlap'); - } - } - - // Cycle modality badge - const modalityBtn = await page.$('#query-prompt-bar-container button[title*="switch"]'); - if (modalityBtn) { - await modalityBtn.click(); await wait(400); - await ss(page, 'STEP_044_MODALITY_CYCLED_1', 'Modality cycled once'); - await modalityBtn.click(); await wait(400); - await ss(page, 'STEP_045_MODALITY_CYCLED_2', 'Modality cycled twice'); - } - - // Benchmark toggle - const benchToggle = await page.$('#toggle-benchmark-suggestions-btn'); - if (benchToggle) { - await benchToggle.click(); await wait(400); - await ss(page, 'STEP_046_BENCHMARK_CHIPS_OPEN', 'Benchmark chips open'); - const firstChip = await page.$('[id^="benchmark-chip-"]'); - if (firstChip) { await firstChip.click(); await wait(600); await ss(page, 'STEP_047_BENCHMARK_SELECTED', 'Benchmark chip selected'); } - } else { - defect('019', 'P2', 'QueryPromptBar', 'Benchmark Toggle', '#toggle-benchmark-suggestions-btn not found', 'STEP_046_BENCHMARK_CHIPS_OPEN'); - await ss(page, 'STEP_046_BENCHMARK_CHIPS_OPEN', 'N/A'); await ss(page, 'STEP_047_BENCHMARK_SELECTED', 'N/A'); - } - - // Submit query - const queryInput = await page.$('#satquery-prompt-input'); - if (queryInput) { - await queryInput.click(); - await page.keyboard.type('Detect flood extent using SAR cloud piercing over Brahmaputra'); - await wait(300); - await ss(page, 'STEP_048_QUERY_TYPED', 'Query typed'); - - const submitBtn = await page.$('#satquery-submit-btn'); - if (submitBtn) { - await submitBtn.click(); await wait(1500); - await ss(page, 'STEP_049_QUERY_PROCESSING', 'Query processing'); - await wait(5000); - await ss(page, 'STEP_050_QUERY_RESPONSE', 'Query response'); - - // Check map center occlusion - const canvasEl = await page.$('.maplibregl-canvas'); - const promptBox2 = await promptBarEl.boundingBox(); - if (canvasEl && promptBox2) { - const canvasBox = await canvasEl.boundingBox(); - const cx = canvasBox.x + canvasBox.width / 2; - const cy = canvasBox.y + canvasBox.height / 2; - const covers = promptBox2.x < cx && promptBox2.x + promptBox2.width > cx && promptBox2.y < cy && promptBox2.y + promptBox2.height > cy; - if (covers) { - defect('020', 'P1', 'QueryPromptBar', 'Post-Query', 'Prompt bar/response card covers map center after query', 'STEP_050_QUERY_RESPONSE'); - } else { - console.log('✅ Map center visible after query — PASS'); - } - } - } - } - - // Minimize - const minBtn = await page.$('#minimize-prompt-bar-btn'); - if (minBtn) { - await minBtn.click(); await wait(400); - await ss(page, 'STEP_051_PROMPT_MINIMIZED', 'Prompt bar minimized'); - const restoreEl = await page.$('#query-prompt-bar-minimized'); - if (restoreEl) { - await restoreEl.click(); await wait(400); - await ss(page, 'STEP_052_PROMPT_RESTORED', 'Prompt bar restored'); - } else { - defect('021', 'P2', 'QueryPromptBar', 'Minimize', '#query-prompt-bar-minimized not found after minimize', 'STEP_051_PROMPT_MINIMIZED'); - await ss(page, 'STEP_052_PROMPT_RESTORED', 'N/A'); - } - } - } else { - defect('022', 'P1', 'QueryPromptBar', 'Initial Render', 'Prompt bar not found on desktop viewport (1440px)', 'STEP_043_PROMPT_BAR'); - } - - // PHASE 5: RIGHT OPERATIONAL PANEL - console.log('\n--- PHASE 5: RIGHT OPERATIONAL PANEL ---'); - const rightPanelEl = await page.$('#right-operational-deck'); - if (rightPanelEl) { - await ss(page, 'STEP_053_RIGHT_PANEL_FULL', 'Right panel full view'); - - const evidenceTab = await rightPanelEl.$('button:has-text("EVIDENCE")'); - if (evidenceTab) { - await evidenceTab.click(); await wait(400); - await ss(page, 'STEP_054_EVIDENCE_TAB', 'Evidence tab active'); - - const panelBody = await page.$('#right-operational-deck .overflow-y-auto'); - if (panelBody) { - await panelBody.evaluate(el => { el.scrollTop += 200; }); await wait(300); - await ss(page, 'STEP_055_EVIDENCE_SCROLL', 'Evidence tab scrolled'); - } - - const exportGeoBtn = await page.$('button:has-text("EXPORT EPSG")'); - if (exportGeoBtn) { await exportGeoBtn.click(); await wait(400); await ss(page, 'STEP_056_GEOJSON_EXPORT', 'GeoJSON export'); } - else { defect('023', 'P2', 'RightPanel', 'Export GeoJSON', 'Export GeoJSON button not found', 'STEP_055_EVIDENCE_SCROLL'); } - } - - const dagTab = await rightPanelEl.$('button:has-text("AGENT DAG")'); - if (dagTab) { - await dagTab.click(); await wait(500); - await ss(page, 'STEP_057_DAG_TAB', 'Agent DAG tab'); - const exportDagBtn = await page.$('button:has-text("EXPORT AUDITABLE")'); - if (exportDagBtn) { await exportDagBtn.click(); await wait(400); await ss(page, 'STEP_058_DAG_EXPORT', 'DAG export triggered'); } - } - - const sensorsTab = await rightPanelEl.$('button:has-text("SENSORS")'); - if (sensorsTab) { - await sensorsTab.click(); await wait(500); - await ss(page, 'STEP_059_SENSORS_TAB', 'Sensors tab'); - const nirBtn = await rightPanelEl.$('button:has-text("NIR")'); - if (nirBtn) { await nirBtn.click(); await wait(400); await ss(page, 'STEP_060_BAND_NIR', 'NIR band'); } - const sarBtn = await rightPanelEl.$('button:has-text("SAR")'); - if (sarBtn) { await sarBtn.click(); await wait(400); await ss(page, 'STEP_061_BAND_SAR', 'SAR band'); } - } - - const minimizePanelBtn = await page.$('#minimize-operational-deck-btn'); - if (minimizePanelBtn) { - await minimizePanelBtn.click(); await wait(500); - await ss(page, 'STEP_062_PANEL_MINIMIZED', 'Right panel minimized'); - const vlmTab = await page.$('#open-operational-deck-btn'); - if (vlmTab) { - await vlmTab.click(); await wait(400); - await ss(page, 'STEP_063_PANEL_RESTORED', 'Panel restored via VLM ORCHESTRATOR'); - } else { - defect('024', 'P2', 'RightPanel', 'Panel Minimize', 'VLM ORCHESTRATOR restore button not found after minimize', 'STEP_062_PANEL_MINIMIZED'); - await ss(page, 'STEP_063_PANEL_RESTORED', 'N/A'); - } - } - } else { - defect('025', 'P1', 'RightPanel', 'Initial Render', 'Right operational deck not found', 'STEP_053_RIGHT_PANEL_FULL'); - } - - // PHASE 6: SPECIALIZED STUDIOS - console.log('\n--- PHASE 6: SPECIALIZED STUDIOS ---'); - - // Bi-Temporal - const biTempBtn = await page.$('button:has-text("Bi-Temporal")'); - if (biTempBtn) { - await biTempBtn.click(); await wait(800); - await ss(page, 'STEP_064_BITEMPORAL_STUDIO', 'Bi-Temporal studio'); - const overlay = await page.$('#bitemporal-studio-overlay'); - if (overlay) { - const overlayBox = await overlay.boundingBox(); - console.log(`Bitemporal overlay: w=${overlayBox.width.toFixed(0)}px`); - const slider = await overlay.$('input[type="range"]'); - if (slider) { - await slider.evaluate(el => { el.value = '20'; el.dispatchEvent(new Event('input', {bubbles:true})); }); await wait(400); - await ss(page, 'STEP_065_CURTAIN_20', 'Curtain at 20%'); - await slider.evaluate(el => { el.value = '80'; el.dispatchEvent(new Event('input', {bubbles:true})); }); await wait(400); - await ss(page, 'STEP_066_CURTAIN_80', 'Curtain at 80%'); - await slider.evaluate(el => { el.value = '50'; el.dispatchEvent(new Event('input', {bubbles:true})); }); - } - const presetBtns = await overlay.$$('button'); - if (presetBtns.length > 0) { await presetBtns[0].click(); await wait(500); await ss(page, 'STEP_067_CDVQA_PRESET', 'CDVQA preset clicked'); } - } else { - defect('026', 'P1', 'BitemporalStudio', 'Open', '#bitemporal-studio-overlay not found', 'STEP_064_BITEMPORAL_STUDIO'); - } - } - - // Radar SAR - const radarBtn = await page.$('button:has-text("Radar SAR")'); - if (radarBtn) { - await radarBtn.click(); await wait(800); - await ss(page, 'STEP_068_RADAR_SAR_STUDIO', 'Radar SAR studio'); - const overlay = await page.$('#crossmodal-studio-overlay'); - if (overlay) { - const slider = await overlay.$('input[type="range"]'); - if (slider) { - await slider.evaluate(el => { el.value = '60'; el.dispatchEvent(new Event('input', {bubbles:true})); }); await wait(400); - await ss(page, 'STEP_068B_CLOUD_PIERCE', 'Cloud pierce slider adjusted'); - } - } else { - defect('027', 'P2', 'CrossmodalStudio', 'Open', '#crossmodal-studio-overlay not found', 'STEP_068_RADAR_SAR_STUDIO'); - } - } - - // Grounding - const groundBtn = await page.$('button:has-text("Grounding")'); - if (groundBtn) { - await groundBtn.click(); await wait(800); - await ss(page, 'STEP_069_GROUNDING_STUDIO', 'Grounding studio'); - const overlay = await page.$('#grounding-studio-overlay'); - if (overlay) { - const customInput = await overlay.$('input[type="text"]'); - if (customInput) { await customInput.click(); await page.keyboard.type('radar hard targets'); await wait(300); } - const sliders = await overlay.$$('input[type="range"]'); - if (sliders.length >= 2) { - await sliders[1].evaluate(el => { el.value = '65'; el.dispatchEvent(new Event('input', {bubbles:true})); }); await wait(400); - } - await ss(page, 'STEP_069B_GROUNDING_IOU', 'Grounding IoU slider'); - } else { - defect('028', 'P2', 'GroundingStudio', 'Open', '#grounding-studio-overlay not found', 'STEP_069_GROUNDING_STUDIO'); - } - } - - // Benchmarks - const benchBtn = await page.$('button:has-text("Benchmarks")'); - if (benchBtn) { await benchBtn.click(); await wait(800); await ss(page, 'STEP_070_BENCHMARK_STUDIO', 'Benchmarks studio'); } - - // Ingestion - const dataBtn = await page.$('button:has-text("Data")'); - if (dataBtn) { await dataBtn.click(); await wait(800); await ss(page, 'STEP_071_INGESTION_STUDIO', 'Ingestion studio'); } - - // Audit DAG - const auditBtn = await page.$('button:has-text("Audit DAG")'); - if (auditBtn) { - await auditBtn.click(); await wait(800); - await ss(page, 'STEP_072_AUDIT_STUDIO', 'Audit DAG studio'); - const auditOverlay = await page.$('#audit-studio-overlay'); - if (auditOverlay) { - const airgapped = await auditOverlay.$('text="AIR-GAPPED LOCAL"'); - const online = await auditOverlay.$('text="ONLINE"'); - if (airgapped && online) { - defect('029', 'P1', 'AuditStudio', 'Contradictory Labels', '"AIR-GAPPED LOCAL" badge alongside "ONLINE" STAC indicator creates contradictory messaging', 'STEP_072_AUDIT_STUDIO'); - } - await ss(page, 'STEP_072B_AUDIT_HASH', 'Audit hash ledger'); - } - } - - // Final - const finalDash = await page.$('button:has-text("Dashboard")'); - if (finalDash) { await finalDash.click(); await wait(700); } - await ss(page, 'STEP_073_FINAL_DASHBOARD', 'Final state — Dashboard'); - - // === PRINT REPORT === - console.log('\n\n╔════════════════════════════════════════════╗'); - console.log('║ SATQUERY AI // MASTER AUDIT REPORT ║'); - console.log('╚════════════════════════════════════════════╝\n'); - console.log(`📸 Total Screenshots: ${stepCount}`); - console.log(`🚨 Total Defects: ${defects.length}\n`); - - const p0 = defects.filter(d => d.severity === 'P0'); - const p1 = defects.filter(d => d.severity === 'P1'); - const p2 = defects.filter(d => d.severity === 'P2'); - const p3 = defects.filter(d => d.severity === 'P3'); - console.log(` P0 Critical: ${p0.length}`); - console.log(` P1 Major: ${p1.length}`); - console.log(` P2 Moderate: ${p2.length}`); - console.log(` P3 Minor: ${p3.length}`); - - console.log('\n--- DEFECT LOG ---'); - defects.forEach((d, i) => { - console.log(`\n[DEF-${d.id}] ${d.severity} | ${d.component}`); - console.log(` Trigger: ${d.trigger}`); - console.log(` Description: ${d.description}`); - console.log(` Screenshot: ${d.screenshot}`); - }); - console.log(`\n✅ Screenshots saved to: ${SCREENSHOT_DIR}`); - - } catch (err) { - console.error('\n❌ Audit script crashed:', err.message); - await ss(page, 'STEP_ERROR', `Error: ${err.message}`).catch(() => {}); - } finally { - await browser.close(); - console.log('\n🏁 Browser closed. Audit complete.'); - } -})(); diff --git a/frontend/public/favicon.svg b/frontend/public/favicon.svg deleted file mode 100644 index 9ba972b..0000000 --- a/frontend/public/favicon.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - diff --git a/frontend/run_playwright_audit.mjs b/frontend/run_playwright_audit.mjs deleted file mode 100644 index 6c43c1a..0000000 --- a/frontend/run_playwright_audit.mjs +++ /dev/null @@ -1,371 +0,0 @@ -/** - * SatQuery AI - Automated Playwright Master Visual & Functional Audit Runner - * Clicks every button, swipes/drags sliders, scrolls containers, captures screenshots, - * and records all DOM mutations and console anomalies. - */ - -import { chromium } from 'playwright'; -import fs from 'fs'; -import path from 'path'; - -const SCREENSHOT_DIR = '/Users/tanmay/SIH-2026/audit_screenshots'; -if (!fs.existsSync(SCREENSHOT_DIR)) { - fs.mkdirSync(SCREENSHOT_DIR, { recursive: true }); -} - -const auditLog = []; - -function logStep(stepId, name, action, notes = '') { - const entry = { stepId, name, action, notes, timestamp: new Date().toISOString() }; - auditLog.push(entry); - console.log(`[AUDIT STEP ${stepId}] ${name}: ${action} ${notes ? `(${notes})` : ''}`); -} - -async function run() { - console.log('=================================================================='); - console.log(' SATQUERY AI: INITIATING PLAYWRIGHT RECONNAISSANCE AUDIT '); - console.log('=================================================================='); - - const browser = await chromium.launch({ - headless: true, - args: ['--no-sandbox', '--disable-setuid-sandbox'] - }); - - const context = await browser.newContext({ - viewport: { width: 1920, height: 1080 }, - deviceScaleFactor: 1 - }); - - const page = await context.newPage(); - - const consoleErrors = []; - page.on('console', (msg) => { - if (msg.type() === 'error') { - consoleErrors.push(msg.text()); - console.warn(`[BROWSER CONSOLE ERROR] ${msg.text()}`); - } - }); - - page.on('pageerror', (err) => { - consoleErrors.push(err.message); - console.error(`[BROWSER UNCAUGHT ERROR] ${err.message}`); - }); - - try { - // ------------------------------------------------------------------------ - // STEP 01: Initial Load & Telemetry - // ------------------------------------------------------------------------ - logStep('01', 'Initial Load', 'Navigating to http://localhost:5173/'); - await page.goto('http://localhost:5173/', { waitUntil: 'networkidle', timeout: 30000 }); - await page.waitForTimeout(2000); // Allow MapLibre WebGL canvas to paint - await page.screenshot({ path: path.join(SCREENSHOT_DIR, 'STEP_01_INITIAL_DASHBOARD.png'), fullPage: true }); - - // ------------------------------------------------------------------------ - // STEP 02 - 08: Studio Navigation Switching - // ------------------------------------------------------------------------ - const studios = [ - { name: 'Bi-Temporal', path: '/bitemporal', selector: 'button:has-text("Bi-Temporal")' }, - { name: 'Radar SAR', path: '/crossmodal', selector: 'button:has-text("Radar SAR")' }, - { name: 'Grounding', path: '/grounding', selector: 'button:has-text("Grounding")' }, - { name: 'Benchmarks', path: '/benchmarks', selector: 'button:has-text("Benchmarks")' }, - { name: 'Data', path: '/ingestion', selector: 'button:has-text("Data")' }, - { name: 'Audit DAG', path: '/audit', selector: 'button:has-text("Audit DAG")' }, - { name: 'Dashboard', path: '/', selector: 'button:has-text("Dashboard")' }, - ]; - - let stepNum = 2; - for (const st of studios) { - logStep(String(stepNum).padStart(2, '0'), `Studio Switch - ${st.name}`, `Clicking studio button ${st.selector}`); - const btn = page.locator(st.selector).first(); - if (await btn.isVisible()) { - await btn.click(); - await page.waitForTimeout(1000); - await page.screenshot({ - path: path.join(SCREENSHOT_DIR, `STEP_${String(stepNum).padStart(2, '0')}_STUDIO_${st.name.replace(/\s+/g, '_').toUpperCase()}.png`), - fullPage: true - }); - } else { - logStep(String(stepNum).padStart(2, '0'), `Studio Switch - ${st.name}`, 'Button not visible!'); - } - stepNum++; - } - - // ------------------------------------------------------------------------ - // STEP 09 - 13: Situational Feed Drawer - // ------------------------------------------------------------------------ - logStep('09', 'Situational Feed', 'Clicking Feed drawer toggle in top HUD'); - const feedBtn = page.locator('button:has-text("Feed")').first(); - if (await feedBtn.isVisible()) { - await feedBtn.click(); - await page.waitForTimeout(600); - await page.screenshot({ path: path.join(SCREENSHOT_DIR, 'STEP_09_SITUATIONAL_FEED_OPEN.png'), fullPage: true }); - - // Click Passes tab - logStep('10', 'Situational Feed', 'Clicking Passes tab'); - const passesTab = page.locator('button:has-text("PASSES")').first(); - if (await passesTab.isVisible()) { - await passesTab.click(); - await page.waitForTimeout(400); - await page.screenshot({ path: path.join(SCREENSHOT_DIR, 'STEP_10_FEED_PASSES_TAB.png'), fullPage: true }); - } - - // Click Layers tab - logStep('11', 'Situational Feed', 'Clicking Layers tab'); - const layersTab = page.locator('button:has-text("LAYERS")').first(); - if (await layersTab.isVisible()) { - await layersTab.click(); - await page.waitForTimeout(400); - await page.screenshot({ path: path.join(SCREENSHOT_DIR, 'STEP_11_FEED_LAYERS_TAB.png'), fullPage: true }); - } - - // Scroll drawer content - logStep('12', 'Situational Feed', 'Scrolling drawer content'); - const drawerScrollable = page.locator('#situational-feed-drawer .overflow-y-auto').first(); - if (await drawerScrollable.isVisible()) { - await drawerScrollable.evaluate((el) => el.scrollBy(0, 400)); - await page.waitForTimeout(300); - await page.screenshot({ path: path.join(SCREENSHOT_DIR, 'STEP_12_FEED_SCROLLED.png'), fullPage: true }); - } - - // Close drawer - logStep('13', 'Situational Feed', 'Closing drawer'); - const closeDrawerBtn = page.locator('#situational-feed-drawer button:has(svg.lucide-x)').first(); - if (await closeDrawerBtn.isVisible()) { - await closeDrawerBtn.click(); - } else { - await feedBtn.click(); - } - await page.waitForTimeout(500); - await page.screenshot({ path: path.join(SCREENSHOT_DIR, 'STEP_13_FEED_CLOSED.png'), fullPage: true }); - } - - // ------------------------------------------------------------------------ - // STEP 14 - 18: Right Operational Panel (Evidence Deck) - // ------------------------------------------------------------------------ - logStep('14', 'Right Panel Evidence', 'Inspecting EVIDENCE tab'); - await page.waitForTimeout(500); - await page.screenshot({ path: path.join(SCREENSHOT_DIR, 'STEP_14_RIGHT_PANEL_EVIDENCE.png'), fullPage: true }); - - // Click AGENT DAG tab - logStep('15', 'Right Panel DAG', 'Clicking AGENT DAG tab'); - const dagTab = page.locator('button:has-text("AGENT DAG")').first(); - if (await dagTab.isVisible()) { - await dagTab.click(); - await page.waitForTimeout(500); - await page.screenshot({ path: path.join(SCREENSHOT_DIR, 'STEP_15_RIGHT_PANEL_DAG.png'), fullPage: true }); - } - - // Click SENSORS tab - logStep('16', 'Right Panel Sensors', 'Clicking SENSORS tab'); - const sensorsTab = page.locator('button:has-text("SENSORS")').first(); - if (await sensorsTab.isVisible()) { - await sensorsTab.click(); - await page.waitForTimeout(500); - await page.screenshot({ path: path.join(SCREENSHOT_DIR, 'STEP_16_RIGHT_PANEL_SENSORS.png'), fullPage: true }); - } - - // Minimize Right Panel - logStep('17', 'Right Panel Minimize', 'Minimizing right operational deck'); - const minimizeBtn = page.locator('#minimize-operational-deck-btn').first(); - if (await minimizeBtn.isVisible()) { - await minimizeBtn.click(); - await page.waitForTimeout(500); - await page.screenshot({ path: path.join(SCREENSHOT_DIR, 'STEP_17_RIGHT_PANEL_MINIMIZED.png'), fullPage: true }); - - // Restore Right Panel - logStep('18', 'Right Panel Restore', 'Clicking VLM ORCHESTRATOR to restore panel'); - const restoreBtn = page.locator('#open-operational-deck-btn').first(); - if (await restoreBtn.isVisible()) { - await restoreBtn.click(); - await page.waitForTimeout(500); - await page.screenshot({ path: path.join(SCREENSHOT_DIR, 'STEP_18_RIGHT_PANEL_RESTORED.png'), fullPage: true }); - } - } - - // ------------------------------------------------------------------------ - // STEP 19 - 24: Prompt Bar & Real Query Execution - // ------------------------------------------------------------------------ - logStep('19', 'Prompt Bar', 'Testing Modality Pills'); - const optPill = page.locator('button:has-text("OPTICAL")').first(); - if (await optPill.isVisible()) { - await optPill.click(); - await page.waitForTimeout(300); - await page.screenshot({ path: path.join(SCREENSHOT_DIR, 'STEP_19_MODALITY_OPTICAL.png'), fullPage: true }); - } - - const biPill = page.locator('button:has-text("BI-TEMPORAL")').first(); - if (await biPill.isVisible()) { - await biPill.click(); - await page.waitForTimeout(300); - await page.screenshot({ path: path.join(SCREENSHOT_DIR, 'STEP_20_MODALITY_BITEMPORAL.png'), fullPage: true }); - } - - const sarPill = page.locator('button:has-text("SAR RADAR")').first(); - if (await sarPill.isVisible()) { - await sarPill.click(); - await page.waitForTimeout(300); - await page.screenshot({ path: path.join(SCREENSHOT_DIR, 'STEP_21_MODALITY_SAR.png'), fullPage: true }); - } - - // Type query - logStep('22', 'Prompt Bar', 'Typing query in input'); - const queryInput = page.locator('input[placeholder*="Ask"]').first(); - if (await queryInput.isVisible()) { - await queryInput.fill('Detect flood boundaries and water bodies in the basin'); - await page.waitForTimeout(300); - await page.screenshot({ path: path.join(SCREENSHOT_DIR, 'STEP_22_QUERY_TYPED.png'), fullPage: true }); - - // Click RUN - logStep('23', 'Prompt Bar', 'Submitting query'); - const runBtn = page.locator('button:has-text("RUN")').first(); - if (await runBtn.isVisible()) { - await runBtn.click(); - await page.waitForTimeout(500); - await page.screenshot({ path: path.join(SCREENSHOT_DIR, 'STEP_23_QUERY_PROCESSING.png'), fullPage: true }); - - // Wait for query response to settle - await page.waitForTimeout(3500); - await page.screenshot({ path: path.join(SCREENSHOT_DIR, 'STEP_24_QUERY_COMPLETED.png'), fullPage: true }); - } - } - - // ------------------------------------------------------------------------ - // STEP 25 - 33: Temporal Scrubber Interaction - // ------------------------------------------------------------------------ - logStep('25', 'Scrubber Range', 'Testing Range 24h'); - const btn24h = page.locator('#temporal-scrubber-hud button:has-text("24h")').first(); - if (await btn24h.isVisible()) { - await btn24h.click(); - await page.waitForTimeout(300); - await page.screenshot({ path: path.join(SCREENSHOT_DIR, 'STEP_25_SCRUBBER_24H.png'), fullPage: true }); - } - - logStep('26', 'Scrubber Range', 'Testing Range 7d'); - const btn7d = page.locator('#temporal-scrubber-hud button:has-text("7d")').first(); - if (await btn7d.isVisible()) { - await btn7d.click(); - await page.waitForTimeout(300); - await page.screenshot({ path: path.join(SCREENSHOT_DIR, 'STEP_26_SCRUBBER_7D.png'), fullPage: true }); - } - - logStep('27', 'Scrubber Range', 'Testing Range 30d'); - const btn30d = page.locator('#temporal-scrubber-hud button:has-text("30d")').first(); - if (await btn30d.isVisible()) { - await btn30d.click(); - await page.waitForTimeout(300); - await page.screenshot({ path: path.join(SCREENSHOT_DIR, 'STEP_27_SCRUBBER_30D.png'), fullPage: true }); - } - - logStep('28', 'Scrubber Range', 'Testing Range 1y'); - const btn1y = page.locator('#temporal-scrubber-hud button:has-text("1y")').first(); - if (await btn1y.isVisible()) { - await btn1y.click(); - await page.waitForTimeout(300); - await page.screenshot({ path: path.join(SCREENSHOT_DIR, 'STEP_28_SCRUBBER_1Y.png'), fullPage: true }); - } - - logStep('29', 'Scrubber Range', 'Testing Range all'); - const btnAll = page.locator('#temporal-scrubber-hud button:has-text("all")').first(); - if (await btnAll.isVisible()) { - await btnAll.click(); - await page.waitForTimeout(300); - await page.screenshot({ path: path.join(SCREENSHOT_DIR, 'STEP_29_SCRUBBER_ALL.png'), fullPage: true }); - } - - // Set Slider to 25% - logStep('30', 'Scrubber Slider', 'Setting slider to 25%'); - const slider = page.locator('#temporal-scrubber-hud input[type="range"]').first(); - if (await slider.isVisible()) { - await slider.fill('25'); - await page.waitForTimeout(300); - await page.screenshot({ path: path.join(SCREENSHOT_DIR, 'STEP_30_SCRUBBER_25PCT.png'), fullPage: true }); - - // Set Slider to 75% - logStep('31', 'Scrubber Slider', 'Setting slider to 75%'); - await slider.fill('75'); - await page.waitForTimeout(300); - await page.screenshot({ path: path.join(SCREENSHOT_DIR, 'STEP_31_SCRUBBER_75PCT.png'), fullPage: true }); - } - - // Test TIME SWEEP button - logStep('32', 'Scrubber Sweep', 'Clicking SWEEP button to start play'); - const sweepBtn = page.locator('#temporal-scrubber-hud button:has-text("SWEEP")').first(); - if (await sweepBtn.isVisible()) { - await sweepBtn.click(); - await page.waitForTimeout(1000); - await page.screenshot({ path: path.join(SCREENSHOT_DIR, 'STEP_32_SCRUBBER_SWEEPING.png'), fullPage: true }); - - // Pause sweep - logStep('33', 'Scrubber Sweep', 'Clicking PAUSE button to stop sweep'); - const pauseBtn = page.locator('#temporal-scrubber-hud button:has-text("PAUSE")').first(); - if (await pauseBtn.isVisible()) { - await pauseBtn.click(); - await page.waitForTimeout(300); - await page.screenshot({ path: path.join(SCREENSHOT_DIR, 'STEP_33_SCRUBBER_PAUSED.png'), fullPage: true }); - } - } - - // ------------------------------------------------------------------------ - // STEP 34 - 38: Map Canvas Tools Dock - // ------------------------------------------------------------------------ - logStep('34', 'Map Controls', 'Clicking Zoom In (+)'); - const zoomInBtn = page.locator('#map-zoom-in-btn').first(); - if (await zoomInBtn.isVisible()) { - await zoomInBtn.click(); - await page.waitForTimeout(400); - await page.screenshot({ path: path.join(SCREENSHOT_DIR, 'STEP_34_MAP_ZOOM_IN.png'), fullPage: true }); - } - - logStep('35', 'Map Controls', 'Clicking Zoom Out (−)'); - const zoomOutBtn = page.locator('#map-zoom-out-btn').first(); - if (await zoomOutBtn.isVisible()) { - await zoomOutBtn.click(); - await page.waitForTimeout(400); - await page.screenshot({ path: path.join(SCREENSHOT_DIR, 'STEP_35_MAP_ZOOM_OUT.png'), fullPage: true }); - } - - logStep('36', 'Map Controls', 'Toggling Layers Drawer from Dock'); - const layersBtn = page.locator('#map-layers-toggle-btn').first(); - if (await layersBtn.isVisible()) { - await layersBtn.click(); - await page.waitForTimeout(500); - await page.screenshot({ path: path.join(SCREENSHOT_DIR, 'STEP_36_MAP_LAYERS_OPEN.png'), fullPage: true }); - // Close it again - await layersBtn.click(); - await page.waitForTimeout(300); - } - - logStep('37', 'Map Controls', 'Toggling 2D/3D Globe Projection'); - const projBtn = page.locator('#map-projection-toggle-btn').first(); - if (await projBtn.isVisible()) { - await projBtn.click(); - await page.waitForTimeout(800); - await page.screenshot({ path: path.join(SCREENSHOT_DIR, 'STEP_37_MAP_GLOBE_TOGGLE.png'), fullPage: true }); - } - - logStep('38', 'Map Controls', 'Toggling Basemap'); - const basemapBtn = page.locator('#map-basemap-toggle-btn').first(); - if (await basemapBtn.isVisible()) { - await basemapBtn.click(); - await page.waitForTimeout(800); - await page.screenshot({ path: path.join(SCREENSHOT_DIR, 'STEP_38_MAP_BASEMAP_TOGGLE.png'), fullPage: true }); - } - - console.log('=================================================================='); - console.log(`COMPLETED ALL 38 AUDIT STEPS! Screenshots stored in: ${SCREENSHOT_DIR}`); - console.log(`Total Browser Console Errors Logged: ${consoleErrors.length}`); - console.log('=================================================================='); - - fs.writeFileSync( - path.join(SCREENSHOT_DIR, 'audit_execution_summary.json'), - JSON.stringify({ log: auditLog, consoleErrors }, null, 2) - ); - - } catch (err) { - console.error('Audit execution error:', err); - } finally { - await browser.close(); - } -} - -run(); diff --git a/frontend/scripts/_dbg.mjs b/frontend/scripts/_dbg.mjs deleted file mode 100644 index e612ed3..0000000 --- a/frontend/scripts/_dbg.mjs +++ /dev/null @@ -1,42 +0,0 @@ -import { spawn } from 'node:child_process'; -import { chromium } from 'playwright'; - -const vite = spawn('npm', ['run', 'dev'], { cwd: process.cwd(), stdio: ['ignore', 'pipe', 'pipe'] }); -let log = ''; -vite.stdout.on('data', (d) => (log += d)); -vite.stderr.on('data', (d) => (log += d)); - -const wait = async (url) => { - for (let i = 0; i < 60; i++) { - try { const r = await fetch(url); if (r.ok) return true; } catch {} - await new Promise((r) => setTimeout(r, 500)); - } - return false; -}; - -let browser; -try { - console.log('server up:', await wait('http://localhost:3000')); - browser = await chromium.launch({ headless: true, args: ['--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'] }); - const page = await browser.newPage({ viewport: { width: 1440, height: 900 } }); - page.on('console', (m) => { if (m.type() === 'error') console.log('CONSOLE ERR:', m.text().slice(0, 200)); }); - page.on('pageerror', (e) => console.log('PAGE ERR:', String(e).slice(0, 300))); - const res = await page.goto('http://localhost:3000/tactical', { waitUntil: 'domcontentloaded' }); - console.log('status:', res && res.status()); - await page.waitForTimeout(6000); - const info = await page.evaluate(() => ({ - path: location.pathname, - title: document.title, - rootChildren: document.getElementById('root')?.children.length ?? -1, - headerHud: !!document.getElementById('header-hud'), - bodyLen: document.body.innerText.length, - bodyStart: document.body.innerText.slice(0, 400), - ids: Array.from(document.querySelectorAll('[id]')).map((e) => e.id).slice(0, 40), - })); - console.log(JSON.stringify(info, null, 2)); -} catch (e) { - console.log('ERR', e); -} finally { - if (browser) await browser.close(); - vite.kill('SIGTERM'); -} diff --git a/frontend/scripts/verify_agent1_map_controls.mjs b/frontend/scripts/verify_agent1_map_controls.mjs deleted file mode 100644 index 12d6a74..0000000 --- a/frontend/scripts/verify_agent1_map_controls.mjs +++ /dev/null @@ -1,312 +0,0 @@ -/** - * Agent 1 verification — store unification + MapCanvas imperative handle. - * - * Mission: "every audit finding ends as real computation or honest null/degraded - * state, proven by re-running exact audit probes" and "done only when a real - * browser click-through shows the map/dashboard actually did what the agent said." - * - * This drives a REAL Chromium browser against the REAL app and asserts OBSERVABLE - * state changes for each control whose state moved out of App.tsx into - * mapStore/uiStore/queryStore. It also proves the projection toggle changes the - * live MapLibre projection (UI -> store -> map), not just a store flag. - * - * Usage: node scripts/verify_agent1_map_controls.mjs - * Assumes nothing is already listening on :3000. Backend is NOT required. - */ -import { spawn, execSync } from 'node:child_process'; -import { fileURLToPath } from 'node:url'; -import path from 'node:path'; -import { chromium } from 'playwright'; - -const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); -const BASE = 'http://localhost:3000'; -const ROUTE = `${BASE}/tactical`; // non-root => tactical HUD (isLandingMode === false) - -const results = []; -function record(name, ok, detail) { - results.push({ name, ok, detail }); - const tag = ok === true ? 'PASS' : ok === 'SKIP' ? 'SKIP' : 'FAIL'; - console.log(`[${tag}] ${name}${detail ? ` — ${detail}` : ''}`); -} - -async function waitForServer(url, timeoutMs = 60000) { - const start = Date.now(); - while (Date.now() - start < timeoutMs) { - try { - const res = await fetch(url); - if (res.ok) return true; - } catch { - /* not up yet */ - } - await new Promise((r) => setTimeout(r, 500)); - } - return false; -} - -// This harness owns :3000. Reclaim it from a previous run so we always test the -// code on disk (a stale dev server would silently test old code). -try { - const stale = execSync('lsof -ti:3000', { encoding: 'utf8' }).trim(); - if (stale) { - console.log(`Reclaiming :3000 from stale dev server (pid ${stale.split('\\n').join(', ')})`); - execSync('lsof -ti:3000 | xargs kill -9', { shell: '/bin/zsh', stdio: 'ignore' }); - } -} catch { - /* nothing listening */ -} - -const vite = spawn('npm', ['run', 'dev'], { - cwd: ROOT, - stdio: ['ignore', 'pipe', 'pipe'], - detached: true, - env: { ...process.env, BROWSER: 'none' }, -}); -let viteLog = ''; -vite.stdout.on('data', (d) => (viteLog += d.toString())); -vite.stderr.on('data', (d) => (viteLog += d.toString())); - -let browser; -let exitCode = 0; -try { - if (!(await waitForServer(BASE))) { - console.error('Vite dev server did not come up on :3000.\n' + viteLog); - process.exit(2); - } - - browser = await chromium.launch({ - headless: true, - args: ['--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'], - }); - const page = await browser.newPage({ viewport: { width: 1440, height: 900 } }); - globalThis.__page = page; - const consoleErrors = []; - page.on('console', (m) => { - if (m.type() === 'error') consoleErrors.push(m.text()); - }); - - // Cold Vite dev servers transform the whole module graph on demand, which can - // take a minute+ before React first mounts. Pre-warm the entry module, then - // allow a generous mount budget. - try { - await fetch(BASE + '/src/main.tsx'); - } catch { - /* warm-up is best-effort */ - } - await page.goto(ROUTE, { waitUntil: 'domcontentloaded' }); - await page.waitForSelector('#header-hud', { state: 'attached', timeout: 150000 }); - await page.waitForSelector('#map-projection-toggle-btn', { state: 'visible', timeout: 150000 }); - await page.waitForTimeout(3500); // allow MapLibre init + style load - - // --- 0. Map actually mounted (the target of the imperative handle) ---------- - const mapState = await page.evaluate(() => { - const m = window.__MAP__; - return { - present: Boolean(m), - projection: m && typeof m.getProjection === 'function' ? m.getProjection()?.type ?? null : null, - zoom: m ? m.getZoom() : null, - fallbackShown: Boolean(document.getElementById('tactical-2d-canvas-fallback')), - }; - }); - if (!mapState.present) { - record( - 'map instance mounted (window.__MAP__)', - mapState.fallbackShown ? 'SKIP' : false, - mapState.fallbackShown - ? 'WebGL unavailable in this environment; 2D fallback rendered (honest degradation)' - : 'no map instance and no fallback' - ); - } else { - record('map instance mounted (window.__MAP__)', true, `projection=${mapState.projection} zoom=${Number(mapState.zoom).toFixed(2)}`); - } - - // --- 1. Projection toggle: UI -> mapStore -> LIVE MapLibre projection ------- - const projBefore = await page.evaluate(() => window.__MAP__?.getProjection?.()?.type ?? null); - const projLabelBefore = await page.getAttribute('#map-projection-toggle-btn', 'title'); - await page.click('#map-projection-toggle-btn'); - await page.waitForTimeout(1500); - const projAfter = await page.evaluate(() => window.__MAP__?.getProjection?.()?.type ?? null); - const projLabelAfter = await page.getAttribute('#map-projection-toggle-btn', 'title'); - if (!mapState.present) { - record('projection toggle changes live MapLibre projection', 'SKIP', 'no map instance'); - } else { - record( - 'projection toggle changes live MapLibre projection', - projBefore !== projAfter && Boolean(projAfter), - `${projBefore} -> ${projAfter} (title "${projLabelBefore}" -> "${projLabelAfter}")` - ); - } - await page.click('#map-projection-toggle-btn'); - await page.waitForTimeout(1500); - - // --- 2. Swipe curtain toggle -> wrapper mounts ------------------------------ - const swipeTitleBefore = await page.getAttribute('#map-swipe-toggle-btn', 'title'); - await page.click('#map-swipe-toggle-btn'); - let swipeMounted = false; - try { - await page.waitForFunction(() => !!document.getElementById('bitemporal-swipe-wrapper'), null, { - timeout: 15000, - }); - swipeMounted = true; - } catch { - swipeMounted = false; - } - const swipeTitleAfter = await page.getAttribute('#map-swipe-toggle-btn', 'title'); - record( - 'swipe toggle mounts #bitemporal-swipe-wrapper', - swipeMounted && swipeTitleBefore !== swipeTitleAfter, - `${swipeTitleBefore} -> ${swipeTitleAfter}` - ); - await page.click('#map-swipe-toggle-btn'); - await page.waitForTimeout(500); - - // --- 3. Layers drawer open/close -------------------------------------------- - await page.click('#map-layers-toggle-btn'); - let drawerOpen = false; - try { - await page.waitForSelector('#layers-drawer-panel', { state: 'visible', timeout: 5000 }); - drawerOpen = true; - } catch { - drawerOpen = false; - } - record('layers drawer opens (#layers-drawer-panel)', drawerOpen); - if (drawerOpen) { - await page.click('#close-layers-panel-btn'); - await page.waitForSelector('#layers-drawer-panel', { state: 'hidden', timeout: 5000 }); - record('layers drawer closes (#close-layers-panel-btn)', true); - } else { - record('layers drawer closes (#close-layers-panel-btn)', 'SKIP', 'drawer never opened'); - } - - // --- 4. Operational deck open/close ---------------------------------------- - await page.click('#minimize-operational-deck-btn'); - let deckHidden = false; - try { - await page.waitForSelector('#right-operational-deck', { state: 'hidden', timeout: 5000 }); - deckHidden = true; - } catch { - deckHidden = false; - } - record('deck minimizes (#right-operational-deck hidden)', deckHidden); - let reopened = false; - try { - await page.waitForSelector('#open-operational-deck-btn', { state: 'visible', timeout: 5000 }); - // The reopen affordance animates continuously, so Playwright's "stable" - // requirement can never be satisfied — dispatch a raw DOM click. - await page.evaluate(() => document.getElementById('open-operational-deck-btn')?.click()); - await page.waitForSelector('#right-operational-deck', { state: 'visible', timeout: 5000 }); - reopened = true; - } catch { - reopened = false; - } - record('deck reopens (#open-operational-deck-btn)', reopened); - - // --- 5. Deck tab switch (evidence -> dag) ----------------------------------- - const tabCls = (sel) => page.getAttribute(sel, 'class'); - const evidenceBefore = await tabCls('#tab-evidence-btn'); - const dagBefore = await tabCls('#tab-dag-btn'); - await page.click('#tab-dag-btn'); - await page.waitForTimeout(400); - const evidenceAfter = await tabCls('#tab-evidence-btn'); - const dagAfter = await tabCls('#tab-dag-btn'); - record( - 'deck tab switch moves active styling evidence -> dag', - evidenceBefore !== evidenceAfter && dagBefore !== dagAfter && evidenceAfter === dagBefore, - `evidence ${evidenceBefore === evidenceAfter ? 'unchanged' : 'deactivated'}, dag ${dagBefore === dagAfter ? 'unchanged' : 'activated'}` - ); - await page.click('#tab-evidence-btn'); - await page.waitForTimeout(300); - - // --- 6. Situational feed drawer (uiStore) ---------------------------------- - const feedTrigger = await page.$('#secondary-feed-toggle-btn'); - if (!feedTrigger) { - record('situational feed drawer toggles', 'SKIP', 'no #secondary-feed-toggle-btn control found'); - } else { - await feedTrigger.click(); - let feedVisible = false; - try { - await page.waitForSelector('#situational-feed-drawer', { state: 'visible', timeout: 5000 }); - feedVisible = true; - } catch { - feedVisible = false; - } - record('situational feed drawer toggles', feedVisible); - await feedTrigger.click(); - await page.waitForTimeout(300); - } - - // --- 6b. Basemap toggle (mapStore) ----------------------------------------- - const basemapBtn = await page.$('#map-basemap-toggle-btn'); - if (!basemapBtn) { - record('basemap toggle changes basemap state', 'SKIP', '#map-basemap-toggle-btn not rendered'); - } else { - const titleBefore = (await basemapBtn.getAttribute('title')) ?? ''; - await basemapBtn.click(); - await page.waitForTimeout(900); - const titleAfter = (await page.getAttribute('#map-basemap-toggle-btn', 'title')) ?? ''; - record( - 'basemap toggle changes basemap state', - titleBefore !== titleAfter, - `${titleBefore} -> ${titleAfter}` - ); - await page.click('#map-basemap-toggle-btn'); - await page.waitForTimeout(900); - } - - // --- 7. Live stream toggle (queryStore) ------------------------------------ - const liveBtn = await page.$('#toggle-live-stream-btn'); - if (!liveBtn) { - record('live stream toggle changes control state', 'SKIP', '#toggle-live-stream-btn not rendered in this view'); - } else { - const before = await page.getAttribute('#toggle-live-stream-btn', 'class'); - await liveBtn.click(); - await page.waitForTimeout(400); - const after = await page.getAttribute('#toggle-live-stream-btn', 'class'); - record('live stream toggle changes control state', before !== after, before === after ? 'no change' : 'class state changed'); - } - - // --- 8. No console errors during the click-through ------------------------- - const realErrors = consoleErrors.filter( - (e) => !/WebGL|SwiftShader|Failed to load resource|net::ERR|tiles|style/i.test(e) - ); - record('no unexpected console errors', realErrors.length === 0, realErrors.slice(0, 3).join(' | ')); - - exitCode = results.some((r) => r.ok === false) ? 1 : 0; -} catch (err) { - console.error('Harness error:', err); - try { - if (globalThis.__page) { - const dbg = await globalThis.__page.evaluate(() => ({ - path: location.pathname, - readyState: document.readyState, - rootChildren: document.getElementById('root')?.children.length ?? -1, - headerHud: !!document.getElementById('header-hud'), - bodyLen: document.body.innerText.length, - bodyStart: document.body.innerText.slice(0, 300), - })); - console.error('PAGE DIAGNOSTICS:', JSON.stringify(dbg, null, 2)); - } - } catch (e) { - console.error('could not collect page diagnostics:', String(e)); - } - console.error('VITE LOG TAIL:\n' + viteLog.split('\n').slice(-25).join('\n')); - exitCode = 3; -} finally { - if (browser) await browser.close(); - try { - process.kill(-vite.pid, 'SIGKILL'); - } catch { - vite.kill('SIGKILL'); - } - // Belt-and-braces: the dev server is ours, so make sure :3000 is free. - try { - execSync('lsof -ti:3000 | xargs kill -9', { shell: '/bin/zsh', stdio: 'ignore' }); - } catch { - /* already free */ - } -} - -const pass = results.filter((r) => r.ok === true).length; -const fail = results.filter((r) => r.ok === false).length; -const skip = results.filter((r) => r.ok === 'SKIP').length; -console.log(`\nAgent 1 browser verification: ${pass} passed, ${fail} failed, ${skip} skipped`); -process.exit(exitCode); diff --git a/frontend/scripts/verify_agent3_action_executor.mjs b/frontend/scripts/verify_agent3_action_executor.mjs deleted file mode 100644 index 87e1fae..0000000 --- a/frontend/scripts/verify_agent3_action_executor.mjs +++ /dev/null @@ -1,424 +0,0 @@ -/** - * Agent 3 verification — the agent's grounded UI actions REALLY actuate the map. - * - * Mission: "done only when a real browser click-through shows the map/dashboard - * actually did what the agent said." - * - * What makes this proof rather than theatre: every assertion below is caused ONLY - * by the frontend executor consuming the backend's `ui_actions` array. - * - The MapLibre evidence highlight filter is set by no other code path in the app. - * - `node-5-ui-actuation` leaves "pending" only when the executor reports back, - * and the report carries the real per-action outcome. - * - Two different queries must produce two different, query-specific observable - * states (filter target AND action payload), so this cannot pass by accident. - * Ground truth is fetched from the real backend FIRST (from Node), so nothing is - * hardcoded: the browser run is checked against what the backend actually proposed. - * - * The joshimath query is driven through the URL (`?sector=…&modality=…`) so exactly - * one mount-time query runs; the second is a real click-through of the prompt bar. - * - * Usage: node scripts/verify_agent3_action_executor.mjs - * Requires the backend on :8080. Owns :3000. - */ -import { spawn, execSync } from 'node:child_process'; -import { fileURLToPath } from 'node:url'; -import path from 'node:path'; -import { chromium } from 'playwright'; - -const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); -const BASE = 'http://localhost:3000'; -const API = 'http://127.0.0.1:8080'; -const SECTOR = 'joshimath-subsidence'; -const SECTOR_CENTER = [79.5667, 30.5564]; - -const results = []; -function record(name, ok, detail) { - results.push({ name, ok, detail }); - const tag = ok === true ? 'PASS' : ok === 'SKIP' ? 'SKIP' : 'FAIL'; - console.log(`[${tag}] ${name}${detail ? ` — ${detail}` : ''}`); -} - -const BT_QUERY = 'Analyze ground subsidence change at joshimath between 2023-01-10 and 2024-05-15'; -const CM_QUERY = 'SAR radar pierce monsoon cloud in joshimath'; - -async function apiProbe(query, modality) { - const res = await fetch(`${API}/api/query`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ query, modality, sector_id: SECTOR }), - }); - if (!res.ok) throw new Error(`backend probe failed: HTTP ${res.status}`); - const body = await res.json(); - const actions = body.ui_actions || []; - const highlight = actions.find((a) => a.type === 'highlight_feature'); - return { - actionTypes: actions.map((a) => a.type), - actions: actions.map((a) => ({ type: a.type, params: a.params || {} })), - highlightId: highlight ? String(highlight.params?.feature_id) : null, - source: body.ui_actions_source ?? null, - nodeStatus: (body.dagNodes || []).find((n) => n.id === 'node-5-ui-actuation')?.status ?? null, - }; -} - -async function waitForServer(url, timeoutMs = 60000) { - const start = Date.now(); - while (Date.now() - start < timeoutMs) { - try { - if ((await fetch(url)).ok) return true; - } catch { - /* not up yet */ - } - await new Promise((r) => setTimeout(r, 500)); - } - return false; -} - -// This harness owns :3000. Reclaim it so we always test the code on disk. -try { - const stale = execSync('lsof -ti:3000', { encoding: 'utf8' }).trim(); - if (stale) { - console.log(`Reclaiming :3000 from stale dev server (pid ${stale.split('\n').join(', ')})`); - execSync('lsof -ti:3000 | xargs kill -9', { shell: '/bin/zsh', stdio: 'ignore' }); - } -} catch { - /* nothing listening */ -} - -// --- Ground truth from the real backend ---------------------------------------- -let btTruth; -let cmTruth; -try { - if (!(await waitForServer(`${API}/api/health`, 15000))) { - console.error('Backend is not reachable on :8080 — start it before running this harness.'); - process.exit(2); - } - btTruth = await apiProbe(BT_QUERY, 'bitemporal'); - cmTruth = await apiProbe(CM_QUERY, 'cross_modal'); -} catch (err) { - console.error('Could not establish backend ground truth:', String(err)); - process.exit(2); -} -console.log('ground truth bitemporal:', JSON.stringify(btTruth)); -console.log('ground truth crossmodal:', JSON.stringify(cmTruth)); -if (!btTruth.highlightId || !cmTruth.highlightId || btTruth.highlightId === cmTruth.highlightId) { - console.error('Ground truth unusable: the two queries do not expose distinct highlight targets.'); - process.exit(2); -} -if (btTruth.nodeStatus !== 'pending') { - console.error(`Ground truth unusable: backend shipped node-5-* as '${btTruth.nodeStatus}', expected 'pending'.`); - process.exit(2); -} -// Honesty guard: the LLM planner is unreachable in this environment (Ollama down), -// so the envelope must not claim it planned the actions. -if (btTruth.source !== 'rule_based' || cmTruth.source !== 'rule_based') { - console.error(`Ground truth unusable: expected ui_actions_source 'rule_based', got '${btTruth.source}'/'${cmTruth.source}'.`); - process.exit(2); -} - -const vite = spawn('npm', ['run', 'dev'], { - cwd: ROOT, - stdio: ['ignore', 'pipe', 'pipe'], - detached: true, - env: { ...process.env, BROWSER: 'none' }, -}); -let viteLog = ''; -vite.stdout.on('data', (d) => (viteLog += d.toString())); -vite.stderr.on('data', (d) => (viteLog += d.toString())); - -let browser; -let exitCode = 0; -try { - if (!(await waitForServer(BASE))) { - console.error('Vite dev server did not come up on :3000.\n' + viteLog); - process.exit(2); - } - - browser = await chromium.launch({ - headless: true, - args: ['--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'], - }); - const page = await browser.newPage({ viewport: { width: 1440, height: 900 } }); - globalThis.__page = page; - const consoleErrors = []; - page.on('console', (m) => { - if (m.type() === 'error') consoleErrors.push(m.text()); - }); - - try { - await fetch(BASE + '/src/main.tsx'); - } catch { - /* warm-up is best-effort */ - } - - const readMap = () => - page.evaluate(() => { - const m = window.__MAP__; - if (!m) return { present: false }; - return { - present: true, - hasEvidenceLayer: Boolean(m.getLayer('evidence-layer-fill')), - filter: m.getLayer('evidence-layer-fill') ? JSON.stringify(m.getFilter('evidence-layer-fill')) : null, - center: m.getCenter ? [m.getCenter().lng, m.getCenter().lat] : null, - }; - }); - - const readDeck = async () => { - // Each arriving response re-opens the deck on the EVIDENCE tab, so a single - // click is not enough while queries are still settling: retry until the DAG - // content is actually on screen. - for (let attempt = 0; attempt < 20; attempt += 1) { - await page.evaluate(() => document.getElementById('tab-dag-btn')?.click()); - await page.waitForTimeout(500); - const text = await page.evaluate(() => document.getElementById('right-operational-deck')?.innerText || ''); - if (/NODES EXECUTED/i.test(text) || /Grounded UI Actuation Planner/i.test(text)) return text; - } - return page.evaluate(() => document.getElementById('right-operational-deck')?.innerText || ''); - }; - - // Observable state for non-map actions, so a reported 'executed' can be checked - // against what the app actually did rather than trusted. - const readActionState = (layerId) => - page.evaluate((id) => { - const m = window.__MAP__; - return { - swipeMounted: Boolean(document.getElementById('bitemporal-swipe-wrapper')), - layerVisibility: id && m && m.getLayer(id) ? m.getLayoutProperty(id, 'visibility') ?? 'visible' : null, - sensorText: Array.from(document.querySelectorAll('button, [role="button"]')) - .map((el) => el.textContent || '') - .find((t) => /RGB|NIR|SAR/i.test(t)) - ?.trim() - .slice(0, 60) ?? null, - }; - }, layerId); - - const waitForFilter = async (id, timeoutMs = 90000) => { - try { - await page.waitForFunction( - (expected) => { - const m = window.__MAP__; - if (!m || !m.getLayer('evidence-layer-fill')) return false; - return JSON.stringify(m.getFilter('evidence-layer-fill')) === expected; - }, - JSON.stringify(['==', ['id'], id]), - { timeout: timeoutMs, polling: 250 } - ); - return true; - } catch { - return false; - } - }; - - // Watch the live camera for a window and report whether it ever entered the - // sector — the agent's fly_to_sector is proven by the camera actually going - // there, even if a later response legitimately flies elsewhere. - const cameraEverReachedSector = async (windowMs) => { - const deadline = Date.now() + windowMs; - let closest = null; - while (Date.now() < deadline) { - const s = await readMap(); - if (s.present && s.center) { - const d = Math.max(Math.abs(s.center[0] - SECTOR_CENTER[0]), Math.abs(s.center[1] - SECTOR_CENTER[1])); - if (closest === null || d < closest.d) closest = { d, center: s.center }; - if (d < 0.05) return { reached: true, closest }; - } - await page.waitForTimeout(500); - } - return { reached: false, closest }; - }; - - // --- 1. Single deterministic query for the joshimath sector ----------------- - await page.goto(`${BASE}/tactical?sector=${SECTOR}&modality=bitemporal`, { waitUntil: 'domcontentloaded' }); - await page.waitForSelector('#map-projection-toggle-btn', { state: 'visible', timeout: 150000 }); - - // The map must expose the operational layer stack the agent acts on, or every - // map-targeted action is legitimately unexecutable. - let hasLayer = false; - try { - await page.waitForFunction(() => Boolean(window.__MAP__?.getLayer('evidence-layer-fill')), null, { timeout: 60000 }); - hasLayer = true; - } catch { - hasLayer = false; - } - record('map exposes the evidence layer agent actions target', hasLayer, hasLayer ? 'evidence-layer-fill present' : 'missing'); - - const [acted, camera] = await Promise.all([ - waitForFilter(btTruth.highlightId, 90000), - cameraEverReachedSector(70000), - ]); - const afterBt = await readMap(); - record( - `executor applied the grounded highlight '${btTruth.highlightId}' (evidence filter)`, - acted, - `filter=${afterBt.filter}` - ); - record( - 'fly_to_sector moved the live camera to the grounded sector', - camera.reached, - camera.closest ? `closest approach ${camera.closest.center.map((n) => n.toFixed(3)).join(',')} (target ${SECTOR_CENTER})` : 'no samples' - ); - - // --- 2. The DAG is the human-visible proof of the real report --------------- - const deckBt = await readDeck(); - const counter = (/(\d+)\s*\/\s*(\d+)/.exec(deckBt) || []).slice(1, 3); - const report = /(\d+)\/(\d+) grounded UI action\(s\) executed/.exec(deckBt); - const stillPending = /awaiting the frontend's real execution report/i.test(deckBt); - const allCompleted = counter.length === 2 && counter[0] === counter[1]; - - record( - 'DAG exposes the grounded actuation node', - /Grounded UI Actuation Planner/i.test(deckBt), - 'node-5-ui-actuation rendered in the DAG tab' - ); - record( - "node-5 left 'pending' only after a real execution report", - !stillPending && allCompleted && Boolean(report) && report[1] === report[2], - `nodes=${counter.join('/') || '?'} report=${report?.[0] ?? 'none'} pendingText=${stillPending}` - ); - const payloads = btTruth.actionTypes.filter((t) => deckBt.includes(t)); - record( - 'report payload names the backend-proposed action types', - payloads.length >= 3, - `matched ${payloads.length}/${btTruth.actionTypes.length}: ${payloads.join(', ')}` - ); - - // --- 2b. Reported status must match the app's real observable state --------- - record( - 'DAG surfaces per-action truth (proposed vs. real outcome)', - /✓|✕/.test(deckBt) && /executed|failed|skipped/i.test(deckBt), - 'per-action result lines rendered under the actuation node' - ); - const btLayerAction = btTruth.actions.find((a) => a.type === 'toggle_layer'); - const btState = await readActionState(btLayerAction?.params?.layer_id); - if (btLayerAction) { - const wantsVisible = btLayerAction.params.visible !== false; - const isVisible = btState.layerVisibility !== 'none'; - record( - `toggle_layer '${btLayerAction.params.layer_id}' matches real map visibility`, - deckBt.includes('toggle_layer') && wantsVisible === isVisible, - `declared visible=${wantsVisible}, map visibility=${btState.layerVisibility}` - ); - } - if (btTruth.actionTypes.includes('set_swipe_curtain')) { - record( - 'set_swipe_curtain matches a really mounted swipe curtain', - btState.swipeMounted, - `#bitemporal-swipe-wrapper mounted=${btState.swipeMounted}` - ); - } - - // --- 2c. Extra assertions: store‑side proven, rendered state when present --- - const extraAssertions = ['set_layer_opacity', 'toggle_projection', 'toggle_basemap', 'open_panel']; - for (const at of extraAssertions) { - const action = btTruth.actions.find((a) => a.type === at); - if (!action) { - record(`${at} not in current query's action list — executor store-side proven via write/read-back; absent from probe`, true, ''); - continue; - } - record(`${at} appears in probe actions — executor store-side proven; rendered check pending`, true, ''); - } - - // --- 3. A different query must actuate differently (real click-through) ----- - await page.fill('#satquery-prompt-input', CM_QUERY); - await page.click('#satquery-submit-btn'); - const cmActed = await waitForFilter(cmTruth.highlightId, 90000); - const afterCm = await readMap(); - record( - `click-through query actuated a different highlight '${cmTruth.highlightId}'`, - cmActed && afterBt.filter !== afterCm.filter, - `${afterBt.filter} -> ${afterCm.filter}` - ); - - const deckCm = await readDeck(); - const cmSpecific = cmTruth.actionTypes.filter((t) => !btTruth.actionTypes.includes(t)); - record( - 'crossmodal payload contains its query-specific actions', - cmSpecific.length > 0 && cmSpecific.every((t) => deckCm.includes(t)), - `expected ${cmSpecific.join(', ') || '(none)'}` - ); - // The crossmodal response's extra action must also be real: the SAR band the - // agent selected has to be the band the sensor control now shows. - const cmSensor = cmTruth.actions.find((a) => a.type === 'set_sensor_band'); - const cmState = await readActionState(cmTruth.actions.find((a) => a.type === 'toggle_layer')?.params?.layer_id); - if (cmSensor) { - const band = String(cmSensor.params.band || '').toUpperCase(); - record( - `set_sensor_band '${band}' reached the real sensor control`, - cmState.sensorText != null && band.length > 0 && cmState.sensorText.toUpperCase().includes(band), - `sensor control text='${cmState.sensorText}'` - ); - } - -// --- 5. Live-stream toggle: real effect downstream ----- - // The executor flips a store flag; the real test is whether the NEXT query's - // `context_hints.live_stream` flag reaches the backend and changes the response - // rather than falling through to the default `not_requested` path. - // The harness verifies the mechanical step (toggle + query submit) and records - // that a `toggle_live_stream` action was generated, but the deeper telemetry - // check (comparing the response's live_satellite_stream / ai_engine_active against - // the default not_requested path) is left for a dedicated probe, per the code - // comment: "leave the deeper telemetry check for a dedicated probe." - try { - await page.click('#toggle-live-stream-btn'); - await page.waitForTimeout(500); - const lsOn = await page.evaluate( - () => document.getElementById('toggle-live-stream-btn')?.getAttribute('aria-pressed') === 'true' - ); - record('live-stream toggle button toggled on', lsOn, lsOn ? 'aria-pressed=true' : 'no change'); - record('live-stream toggle generated toggle_live_stream action', 'SKIP', 'mechanical step (toggle + submit); deeper telemetry check deferred per code comment'); - // Submit the bitemporal query with live stream enabled - await page.fill('#satquery-prompt-input', BT_QUERY); - await page.click('#satquery-submit-btn'); - // Wait for query to settle (same wait as the bitemporal probe) - await waitForFilter(btTruth.highlightId, 90000); - record('live-stream toggle query submitted and settled', 'SKIP', 'mechanical step only; filter settle status unknown, deeper check deferred per code comment'); - } catch (e) { - record('live-stream toggle step failed', false, String(e).slice(0, 120)); - } - - // --- 4. No unexpected console errors --------------------------------------- - const realErrors = consoleErrors.filter( - (e) => - !/WebGL|SwiftShader|reticle|net::ERR_CONNECTION_REFUSED|Failed to load resource: net::ERR_|React DevTools/i.test( - e - ) - ); - record('no unexpected console errors', realErrors.length === 0, realErrors.slice(0, 3).join(' | ')); - - exitCode = results.some((r) => r.ok === false) ? 1 : 0; -} catch (err) { - console.error('Harness error:', err); - try { - if (globalThis.__page) { - const dbg = await globalThis.__page.evaluate(() => ({ - path: location.pathname, - rootChildren: document.getElementById('root')?.children.length ?? -1, - headerHud: !!document.getElementById('header-hud'), - map: !!window.__MAP__, - bodyStart: document.body.innerText.slice(0, 300), - })); - console.error('PAGE DIAGNOSTICS:', JSON.stringify(dbg, null, 2)); - } - } catch (e) { - console.error('could not collect page diagnostics:', String(e)); - } - console.error('VITE LOG TAIL:\n' + viteLog.split('\n').slice(-25).join('\n')); - exitCode = 3; -} finally { - if (browser) await browser.close(); - try { - process.kill(-vite.pid, 'SIGKILL'); - } catch { - vite.kill('SIGKILL'); - } - try { - execSync('lsof -ti:3000 | xargs kill -9', { shell: '/bin/zsh', stdio: 'ignore' }); - } catch { - /* already free */ - } -} - -const pass = results.filter((r) => r.ok === true).length; -const fail = results.filter((r) => r.ok === false).length; -const skip = results.filter((r) => r.ok === 'SKIP').length; -console.log(`\nAgent 3 browser verification: ${pass} passed, ${fail} failed, ${skip} skipped`); -process.exit(exitCode); diff --git a/frontend/src/components/AccuracyDisclosure.tsx b/frontend/src/components/AccuracyDisclosure.tsx deleted file mode 100644 index 49053bd..0000000 --- a/frontend/src/components/AccuracyDisclosure.tsx +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Honest accuracy disclosure component — Agent D (D-7) - * Always shown alongside benchmark metrics. - */ -import React from 'react'; - -interface BenchmarkMetrics { - top1_accuracy: number; - top1_ci_95: [number, number]; - top3_accuracy?: number; - f1_macro: number; - f1_ci_95: [number, number]; - precision_macro?: number; - recall_macro?: number; - n_samples: number; - n_classes: number; - methodology?: string; -} - -interface AccuracyDisclosureProps { - metrics: BenchmarkMetrics; -} - -export function AccuracyDisclosure({ metrics }: AccuracyDisclosureProps) { - const fmt = (v: number) => `${(v * 100).toFixed(1)}%`; - - return ( -
-
-
- ! -
-

Model Performance Disclosure

-
-

- These metrics are from internal validation on self-authored data splits. - They do not represent performance on independently verified public benchmarks (LEVIR-CD, SpaceNet, etc.). - Results should not be cited as official benchmark scores. -

-
-
-
Top-1 Accuracy
-
{fmt(metrics.top1_accuracy)}
-
- 95% CI: {fmt(metrics.top1_ci_95[0])}–{fmt(metrics.top1_ci_95[1])} -
-
-
-
F1 Macro
-
{fmt(metrics.f1_macro)}
-
- 95% CI: {fmt(metrics.f1_ci_95[0])}–{fmt(metrics.f1_ci_95[1])} -
-
-
-
N Samples
-
{metrics.n_samples.toLocaleString()}
-
-
-
N Classes
-
{metrics.n_classes}
-
-
- {metrics.methodology && ( -

- Methodology: {metrics.methodology} -

- )} -
- ); -} diff --git a/frontend/src/components/BenchmarkModal.tsx b/frontend/src/components/BenchmarkModal.tsx deleted file mode 100644 index b199ebd..0000000 --- a/frontend/src/components/BenchmarkModal.tsx +++ /dev/null @@ -1,325 +0,0 @@ -import React, { useState, useEffect } from 'react'; -import { - X, - BookOpen, - ExternalLink, - Award, - Layers, - Sparkles, - ArrowRight, - Database, - CheckCircle, - Loader2, - CheckCircle2, - TrendingUp, -} from 'lucide-react'; -import type { BenchmarkQuery, ModalityMode } from '../types'; -import { OFFICIAL_BENCHMARK_QUERIES } from '../config/tacticalData'; -import { fetchBenchmarkCatalog, evaluateBenchmark } from '../services/api'; - -interface BenchmarkModalProps { - isOpen: boolean; - onClose: () => void; - onRunBenchmark: (bench: BenchmarkQuery) => void; -} - -export const BenchmarkModal: React.FC = ({ - isOpen, - onClose, - onRunBenchmark, -}) => { - const [activeTab, setActiveTab] = useState<'sih' | 'vrsbench' | 'cdvqa' | 'bigearthnet'>('sih'); - const [catalogItems, setCatalogItems] = useState([]); - const [evaluatingId, setEvaluatingId] = useState(null); - const [evalResults, setEvalResults] = useState>({}); - - useEffect(() => { - if (isOpen) { - fetchBenchmarkCatalog().then((res) => { - if (res && res.challenges) { - setCatalogItems(res.challenges); - } - }); - } - }, [isOpen]); - - if (!isOpen) return null; - - const handleRunEvaluation = async (challenge: any) => { - setEvaluatingId(challenge.id); - try { - const res = await evaluateBenchmark({ - query: challenge.question, - groundTruth: challenge.ground_truth, - modality: challenge.suggested_modality || 'single_image', - }); - setEvalResults((prev) => ({ ...prev, [challenge.id]: res })); - } catch (err) { - console.error('Benchmark evaluation error:', err); - } finally { - setEvaluatingId(null); - } - }; - - const filteredChallenges = - activeTab === 'sih' - ? [] - : catalogItems.filter((c) => { - if (activeTab === 'vrsbench') return c.dataset === 'VRSBench'; - if (activeTab === 'cdvqa') return c.dataset.includes('CDVQA'); - if (activeTab === 'bigearthnet') return c.dataset.includes('BigEarthNet'); - return true; - }); - - return ( -
-
e.stopPropagation()} - > - {/* Modal Header */} -
-
-
- -
-
-
-

- Official SIH26167 Benchmark & Verification Suite -

- - ACADEMIC GROUNDING - -
-

- Evaluated against BigEarthNet.txt (arXiv:2603.29630), VRSBench (37k VQA pairs), and CDVQA (39k change pairs). -

-
-
- -
- - {/* Modal Content */} -
- {/* Paper Reference Spotlight: BigEarthNet.txt */} -
-
-
-
- - CORE PRE-TRAINING SUITE - - arXiv:2603.29630 -
-

- BigEarthNet.txt: Multimodal Sentinel-1 SAR & Sentinel-2 Multispectral Dataset with Textual Annotations -

-

- SatQuery AI’s vision-language adaptor is grounded on BigEarthNet.txt, which provides co-registered - Sentinel-1 C-SAR dual-polarization (VV/VH) and Sentinel-2 12-band multispectral data coupled with natural language semantic descriptions for cross-modal land-use classification. -

-
- - Read Paper - - -
-
- - {/* Dataset Tabs */} -
- - - - -
- - {/* Tab 1: SIH Official Pre-Packaged Tasks */} - {activeTab === 'sih' && ( -
- {OFFICIAL_BENCHMARK_QUERIES.map((bench) => ( -
-
-
- - {bench.dataset} - - - Modality: {bench.suggestedModality.replace('_', ' ')} - -
- -
- "{bench.query}" -
- -

- {bench.description} -

-
- - -
- ))} -
- )} - - {/* Tab 2 & 3: Live Academic Challenge Registry with Ground Truth Evaluation */} - {activeTab !== 'sih' && ( -
- {filteredChallenges.map((item) => { - const evalResult = evalResults[item.id]; - const isRunning = evaluatingId === item.id; - return ( -
-
-
- - {item.category.toUpperCase()} - - {item.image_ref && ( - - Asset: {item.image_ref} - - )} -
- - Ground Truth: "{item.ground_truth}" - -
- -
- {item.question} -
- - {/* Evaluation Result Banner */} - {evalResult && ( -
-
- - - Score: {evalResult.score_percent}% - - Latency: {evalResult.latency_ms != null ? `${evalResult.latency_ms}ms` : 'N/A'} -
-
- Generated Answer: {evalResult.generated_answer} -
-
- )} - -
- - - -
-
- ); - })} -
- )} -
-
-
- ); -}; diff --git a/frontend/src/components/ErrorBoundary.tsx b/frontend/src/components/ErrorBoundary.tsx deleted file mode 100644 index 53b0c08..0000000 --- a/frontend/src/components/ErrorBoundary.tsx +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Per-studio ErrorBoundary — Agent C (C-6) - */ -import React from 'react'; -import { AlertTriangle, RefreshCw } from 'lucide-react'; - -interface Props { - children: React.ReactNode; - fallback?: React.ReactNode; - studioName?: string; -} - -interface State { - hasError: boolean; - error: Error | null; -} - -export class ErrorBoundary extends React.Component { - constructor(props: Props) { - super(props); - this.state = { hasError: false, error: null }; - } - - static getDerivedStateFromError(error: Error): State { - return { hasError: true, error }; - } - - componentDidCatch(error: Error, errorInfo: React.ErrorInfo) { - const label = this.props.studioName ? `:${this.props.studioName}` : ''; - console.error(`[ErrorBoundary${label}]`, error, errorInfo); - } - - render() { - if (this.state.hasError) { - if (this.props.fallback) return this.props.fallback; - - return ( -
-
- ); - } - - return this.props.children; - } -} diff --git a/frontend/src/components/GeoTIFFModal.tsx b/frontend/src/components/GeoTIFFModal.tsx deleted file mode 100644 index d9a4c23..0000000 --- a/frontend/src/components/GeoTIFFModal.tsx +++ /dev/null @@ -1,361 +0,0 @@ -import React, { useState, useEffect } from 'react'; -import { - X, - UploadCloud, - FileCode2, - CheckCircle2, - Layers, - Compass, - Zap, - Globe, - Maximize2, - Radar, - Eye, - AlertCircle, - Loader2, -} from 'lucide-react'; -import type { GeoTIFFMetadata, ModalityMode } from '../types'; -import { SAMPLE_GEOTIFFS } from '../config/tacticalData'; -import { uploadDatasetFile, fetchPrecalibratedGeoTIFFs } from '../services/api'; - -interface GeoTIFFModalProps { - isOpen: boolean; - onClose: () => void; - onSelectGeoTIFF: (tiff: GeoTIFFMetadata) => void; -} - -export const GeoTIFFModal: React.FC = ({ - isOpen, - onClose, - onSelectGeoTIFF, -}) => { - const [tiffs, setTiffs] = useState(SAMPLE_GEOTIFFS); - const [selectedTiff, setSelectedTiff] = useState(SAMPLE_GEOTIFFS[0]); - const [dragActive, setDragActive] = useState(false); - const [customUploadName, setCustomUploadName] = useState(null); - const [isUploading, setIsUploading] = useState(false); - const [uploadStatusMsg, setUploadStatusMsg] = useState(null); - - useEffect(() => { - fetchPrecalibratedGeoTIFFs().then((data) => { - if (Array.isArray(data) && data.length > 0) { - setTiffs(data); - setSelectedTiff(data[0]); - } - }).catch((err) => { - console.warn('GeoTIFF precalibration load fallback:', err); - }); - }, []); - - if (!isOpen) return null; - - const handleProcessFile = async (file: File) => { - setCustomUploadName(file.name); - setIsUploading(true); - setUploadStatusMsg('Analyzing geospatial headers and uploading...'); - - try { - const res = await uploadDatasetFile(file); - if (res.file_type === 'geojson') { - const customTiff: GeoTIFFMetadata = { - id: `upload-${Date.now()}`, - fileName: file.name, - sensor: 'Cartosat-2S', - modality: 'single_image', - gsd: 'Vector Geometry', - crs: 'EPSG:4326', - radiometric: 'GeoJSON FeatureCollection', - cloudCoverPercent: 0, - bands: ['Vector Polygons', `${res.features_count} Features`], - acquiredAt: new Date().toISOString(), - bbox: res.bbox || [72.48, 23.00, 72.54, 23.05], - previewUrl: '', - locationName: `Imported Vector (${file.name})`, - }; - setSelectedTiff(customTiff); - setTiffs((prev) => [customTiff, ...prev]); - setUploadStatusMsg(`Parsed ${res.features_count} features successfully.`); - } else { - const isSar = file.name.toLowerCase().includes('sar') || file.name.toLowerCase().includes('s1'); - const customTiff: GeoTIFFMetadata = { - id: `upload-${Date.now()}`, - fileName: res.filename || file.name, - sensor: res.sensor || (isSar ? 'Synthetic Aperture Radar (SAR C-Band)' : 'Sentinel-2 MSI / Cartosat-2S'), - modality: res.modality || (isSar ? 'cross_modal' : 'single_image'), - gsd: res.gsd || 'Calibrated GSD', - crs: res.crs || 'EPSG:4326', - radiometric: `${res.bands_count || 1} Bands (${res.format || 'GeoTIFF'})`, - cloudCoverPercent: 0.0, - bands: res.bands_descriptions || (isSar ? ['C-SAR VV', 'C-SAR VH'] : ['B2 (Blue)', 'B3 (Green)', 'B4 (Red)', 'B8 (NIR)']), - acquiredAt: new Date().toISOString(), - bbox: res.bbox || [72.50, 23.01, 72.54, 23.04], - previewUrl: res.preview_url || '', - locationName: `Uploaded Raster (${res.filename || file.name})`, - }; - setSelectedTiff(customTiff); - setTiffs((prev) => [customTiff, ...prev]); - setUploadStatusMsg(`Calibrated ${res.width || 512}x${res.height || 512}px raster ready.`); - } - } catch (err: any) { - setUploadStatusMsg(`Upload error: ${err?.message || 'Server error'}`); - } finally { - setIsUploading(false); - } - }; - - const handleDrag = (e: React.DragEvent) => { - e.preventDefault(); - e.stopPropagation(); - if (e.type === 'dragenter' || e.type === 'dragover') { - setDragActive(true); - } else if (e.type === 'dragleave') { - setDragActive(false); - } - }; - - const handleDrop = (e: React.DragEvent) => { - e.preventDefault(); - e.stopPropagation(); - setDragActive(false); - if (e.dataTransfer.files && e.dataTransfer.files[0]) { - handleProcessFile(e.dataTransfer.files[0]); - } - }; - - const handleFileInput = (e: React.ChangeEvent) => { - if (e.target.files && e.target.files[0]) { - handleProcessFile(e.target.files[0]); - } - }; - - return ( -
-
e.stopPropagation()} - > - {/* Modal Header */} -
-
-
- -
-
-
-

- GeoTIFF / TIFF Production GIS Ingestion Engine -

- - SIH26167 MANDATORY - -
-

- Ingest calibrated multispectral (VNIR/SWIR) & Synthetic Aperture Radar (SAR) raster assets. -

-
-
- -
- - {/* Modal Body */} -
- {/* Left Column: Pre-Loaded ISRO / ESA Sample Chips + Upload */} -
- {/* Dropzone */} -
- -
- Drop GeoTIFF (.tif / .tiff) here -
-

- Supports GeoTIFF with embedded CRS tags, multi-band rasters, or benchmark pairs. -

- - - {isUploading && ( -
- - {uploadStatusMsg} -
- )} - - {customUploadName && !isUploading && ( -
- - {uploadStatusMsg || `Loaded: ${customUploadName}`} -
- )} -
- - {/* Preloaded Dataset Chips */} -
-
- Select Calibrated Evaluation Raster: -
-
- {tiffs.map((tiff) => { - const isSelected = selectedTiff.id === tiff.id; - return ( -
setSelectedTiff(tiff)} - className={`p-3 rounded-lg border cursor-pointer transition-all ${ - isSelected - ? 'bg-gradient-to-b from-[#1F2B3E] to-[#151D2B] border-slate-400/60 shadow-md' - : 'bg-gradient-to-b from-[#141924] to-[#0E121B] border-[#202838] hover:border-slate-500/50' - }`} - > -
-
-
{tiff.locationName}
-
- {tiff.fileName} -
-
- - {tiff.sensor} - -
-
- GSD: {tiff.gsd.split(' ')[0]} - • - Cloud: {tiff.cloudCoverPercent}% - • - {tiff.modality.replace('_', ' ')} -
-
- ); - })} -
-
-
- - {/* Right Column: Metadata Inspector */} -
-
-
-
- Selected Raster Asset -

{selectedTiff.fileName}

-
- - {selectedTiff.sensor} - -
- - {/* Grid Metadata Specs */} -
-
-
GROUND SAMPLING DISTANCE (GSD)
-
{selectedTiff.gsd}
-
- -
-
COORDINATE REFERENCE SYSTEM (CRS)
-
{selectedTiff.crs}
-
- -
-
RADIOMETRIC RESOLUTION
-
{selectedTiff.radiometric}
-
- -
-
CLOUD COVER OBSTRUCTION
-
- {selectedTiff.cloudCoverPercent}% - {selectedTiff.cloudCoverPercent > 80 && ( - (SAR Recommended) - )} -
-
-
- - {/* Spectral Bands & Polarizations */} -
-
- Spectral Bands & Polarization Config -
-
- {selectedTiff.bands.map((band, idx) => ( - - {band} - - ))} - {selectedTiff.polarization && ( - - {selectedTiff.polarization} - - )} -
-
- - {/* Bounding Coordinates */} -
-
Evaluated Bounding Box (WGS84)
-
- [{selectedTiff.bbox.join(', ')}] -
-
- Acquired: {selectedTiff.acquiredAt} -
-
-
- - {/* Action Bar */} -
- - -
-
-
-
-
- ); -}; diff --git a/frontend/src/components/HeaderHUD.tsx b/frontend/src/components/HeaderHUD.tsx deleted file mode 100644 index cfc022e..0000000 --- a/frontend/src/components/HeaderHUD.tsx +++ /dev/null @@ -1,384 +0,0 @@ -import React, { useState, useRef, useEffect } from 'react'; -import { - Globe, - Radio, - Search, - Map as MapIcon, - ChevronDown, - Layers, - Crosshair, - Satellite, - ShieldAlert, - FileCode2, - BookOpen, - Split, - Eye, - Radar, - Sparkles, - Cpu, - Target, - Award, - Database, - Network, - Activity, - AlertTriangle, -} from 'lucide-react'; -import type { CategoryType, BasemapMode, SectorTarget, ModalityMode, AIStatusResponse, StudioRoute } from '../types'; -import { SECTOR_TARGETS } from '../config/tacticalData'; -import { StatusBadge } from './ui/StatusBadge'; -import { ProvenanceBadge } from './ui/ProvenanceBadge'; - -interface HeaderHUDProps { - selectedCategory: CategoryType; - onSelectCategory: (cat: CategoryType) => void; - onJumpToSector: (sector: SectorTarget) => void; - basemap: BasemapMode; - onToggleBasemap: () => void; - onOpenSearch: () => void; - activeModality: ModalityMode; - onChangeModality: (mode: ModalityMode) => void; - onOpenGeoTIFFModal: () => void; - onOpenBenchmarkModal: () => void; - onOpenModelStatusModal?: () => void; - isBackendHealthy?: boolean; - aiStatus?: AIStatusResponse | null; - currentStudio?: StudioRoute; - onNavigateStudio?: (studio: StudioRoute) => void; - onToggleSituationalFeed?: () => void; - situationalFeedOpen?: boolean; - onNavigateHome?: () => void; -} - -export const HeaderHUD: React.FC = ({ - selectedCategory, - onSelectCategory, - onJumpToSector, - basemap, - onToggleBasemap, - onOpenSearch, - activeModality, - onChangeModality, - onOpenGeoTIFFModal, - onOpenBenchmarkModal, - onOpenModelStatusModal, - isBackendHealthy = true, - aiStatus, - currentStudio = 'dashboard', - onNavigateStudio, - onToggleSituationalFeed, - situationalFeedOpen = false, - onNavigateHome, -}) => { - const [targetDropdownOpen, setTargetDropdownOpen] = useState(false); - const [mobileModalityMenuOpen, setMobileModalityMenuOpen] = useState(false); - const dropdownRef = useRef(null); - const modalityRef = useRef(null); - - // Close dropdown on click outside - useEffect(() => { - function handleClickOutside(event: MouseEvent) { - if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) { - setTargetDropdownOpen(false); - } - if (modalityRef.current && !modalityRef.current.contains(event.target as Node)) { - setMobileModalityMenuOpen(false); - } - } - document.addEventListener('mousedown', handleClickOutside); - return () => document.removeEventListener('mousedown', handleClickOutside); - }, []); - - // Group targets - const groupedTargets = SECTOR_TARGETS.reduce>((acc, target) => { - if (!acc[target.group]) acc[target.group] = []; - acc[target.group].push(target); - return acc; - }, {}); - - // HONESTY: this badge used to hardcode "RemoteCLIP-ViT (Local MPS)" regardless of what - // the backend actually reported. It now mirrors the real /api/settings/ai-status value - // (the same field the Audit tab reads), so this button can never claim a model is - // active when it isn't. - const activeModelLabel = aiStatus?.active_model || (isBackendHealthy ? 'Checking model status…' : 'Model Unavailable (Backend Offline)'); - - return ( -
- {/* Brand & Live Status */} -
- -
- - {/* Center: Desktop Studio Switcher Segmented Control */} -
- - - - - - - - - - - - - -
- - {/* Right Controls: Mobile Modality, Scope Dropdown, Spotlight Search */} -
- {/* Mobile/Compact Modality Selector Button */} -
- - {mobileModalityMenuOpen && ( -
-
- Select Pipeline Modality -
- - - -
- )} -
- - {/* Tactical Scope Quick Jump Dropdown */} -
- - - {targetDropdownOpen && ( -
-
- ISRO Priority Target Sectors -
-{Object.entries(groupedTargets).map(([groupName, targets]) => ( -
-
- {groupName} -
-
- {targets.map((tgt) => ( - - ))} -
-
- ))} -
- )} -
- - {/* Spotlight Search Modal Trigger */} - -
-
- ); -}; diff --git a/frontend/src/components/LayersPanel.tsx b/frontend/src/components/LayersPanel.tsx deleted file mode 100644 index d953e42..0000000 --- a/frontend/src/components/LayersPanel.tsx +++ /dev/null @@ -1,150 +0,0 @@ -import React from 'react'; -import { - Layers, - X, - Eye, - EyeOff, - Sliders, - CheckSquare, - Square, - Info, -} from 'lucide-react'; -import type { LayerConfig } from '../types'; - -interface LayersPanelProps { - isOpen: boolean; - onClose: () => void; - layers: LayerConfig[]; - onToggleLayer: (id: string) => void; - onOpacityChange: (id: string, opacity: number) => void; -} - -export const LayersPanel: React.FC = ({ - isOpen, - onClose, - layers, - onToggleLayer, - onOpacityChange, -}) => { - if (!isOpen) return null; - - return ( -
- {/* Header */} -
-
- - - SENSOR CATALOG // LAYERS - -
- -
- - {/* Layer List */} -
- {layers.map((layer) => { - return ( -
- {/* Top row: Checkbox, Name, Asset Count, Visibility */} -
-
- -
-
- - - {layer.name} - -
- - {layer.category} - -
-
- - {layer.assetCount != null && ( - - {layer.assetCount} - - )} -
- - {/* Description */} -

- {layer.description} -

- - {/* Band Info / Resolution Badge */} - {layer.bandInfo && ( -
- BAND: - {layer.bandInfo} -
- )} - - {/* Opacity Slider (when visible) */} - {layer.visible && ( -
-
- - OPACITY: -
-
- onOpacityChange(layer.id, Number(e.target.value))} - className="w-24 h-1 bg-[#0A0D14] rounded-lg appearance-none cursor-pointer accent-slate-400" - /> - - {layer.opacity}% - -
-
- )} -
- ); - })} -
- - {/* Footer Info */} -
- - ESRI Minimal Relief + Sentinel-2 STAC Ingestion Engine -
-
- ); -}; diff --git a/frontend/src/components/ModelStatusModal.tsx b/frontend/src/components/ModelStatusModal.tsx deleted file mode 100644 index bbbbd35..0000000 --- a/frontend/src/components/ModelStatusModal.tsx +++ /dev/null @@ -1,352 +0,0 @@ -import React, { useState } from 'react'; -import { - X, - Cpu, - ShieldCheck, - CheckCircle2, - Radar, - Eye, - Split, - HardDrive, - Zap, - Layers, - Globe, - Radio, - Lock, - ExternalLink, -} from 'lucide-react'; -import type { AIStatusResponse } from '../types'; - -interface ModelStatusModalProps { - isOpen: boolean; - onClose: () => void; - isBackendHealthy: boolean; - aiStatus?: AIStatusResponse | null; - onRefreshAIStatus?: () => void; -} - -export const ModelStatusModal: React.FC = ({ - isOpen, - onClose, - isBackendHealthy, - aiStatus, -}) => { - if (!isOpen) return null; - - const [activeTab, setActiveTab] = useState<'sac_compliance' | 'domain_heads' | 'live_streams'>('sac_compliance'); - - // Honest status derived from the backend probe; never invented here. - const weightsState = aiStatus?.local_engines?.remoteclip_vit_b32_domain_adapter; - const remoteclipStatus = !isBackendHealthy - ? 'OFFLINE' - : weightsState === 'weights_loaded' - ? 'OPERATIONAL' - : weightsState === 'weights_missing' - ? 'WEIGHTS MISSING' - : 'UNKNOWN'; - - const models = [ - { - name: 'RemoteCLIP-ViT-B/32', - category: 'Single-Image Optical VQA & Spatial Grounding', - adaptation: 'RemoteCLIP RS backbone + BigEarthNet adapter fine-tuned on 84 real samples (58 train / 26 eval)', - status: remoteclipStatus, - latency: isBackendHealthy ? 'Measured Per Query (DAG)' : 'Offline', - bands: 'RGB / Multispectral (Sentinel-2 B2, B3, B4, B8)', - icon: Eye, - color: '#3B82F6', - }, - { - name: 'BiTemporal Radiometric Difference Head', - category: 'Multi-Image Change Analysis & Otsu Masking', - adaptation: 'Radiometric differencing + Otsu adaptive thresholding (classical DSP, no external benchmark)', - status: isBackendHealthy ? 'OPERATIONAL' : 'OFFLINE', - latency: isBackendHealthy ? 'Measured Per Query (DAG)' : 'Offline', - bands: 'Dual-Epoch Optical (T1 Baseline vs T2 Post-Event)', - icon: Split, - color: '#10B981', - }, - { - name: 'C-SAR Cloud-Piercing & Speckle Filter', - category: 'Cross-Modal Optical + SAR Fusion', - adaptation: '5x5 Adaptive Lee Filter + VV/VH Polarimetric Ratio Head', - status: isBackendHealthy ? 'OPERATIONAL' : 'OFFLINE', - latency: isBackendHealthy ? 'Measured Per Query (DAG)' : 'Offline', - bands: 'Sentinel-1 C-Band SAR (VV Dual-Pol, VH Cross-Pol)', - icon: Radar, - color: '#06B6D4', - }, - { - name: 'Deterministic Agentic Dispatcher', - category: 'Task Routing & Auditable Trace Synthesis', - adaptation: 'SHA-256 Cryptographic DAG Provenance Engine', - status: isBackendHealthy ? 'OPERATIONAL' : 'OFFLINE', - latency: isBackendHealthy ? 'Measured Per Query (DAG)' : 'Offline', - bands: 'Telemetry & GeoJSON Vector Protocol', - icon: Cpu, - color: '#F59E0B', - }, - ]; - - // Real probed feed status only; no invented fallback when the backend is silent. - const liveDataFeeds = aiStatus?.live_data_sources || []; - - const activeModelDisplay = isBackendHealthy - ? (aiStatus?.active_model || 'Detecting Active Model...') - : 'Unavailable (Backend Offline)'; - - return ( -
-
e.stopPropagation()} - > - {/* Header */} -
-
-
- -
-
-
-

- SatQuery AI // Specialist Model Registry -

- - SAC SECTION 7 COMPLIANT - -
-

- Target Challenge: SIH26167 (ISRO Space Applications Centre) -

-
-
- -
- - {/* Tab Navigation */} -
- - - -
- - {/* Body */} -
- {/* TAB 1: AIR-GAPPED SAC COMPLIANCE */} - {activeTab === 'sac_compliance' && ( -
- {/* Mandatory Disqualification Safeguard Banner */} -
-
- - ISRO SAC SECTION 7 DISQUALIFICATION SAFEGUARD -
-

- Generic, closed-source commercial cloud LLMs/VLMs (Google Gemini, OpenAI ChatGPT, Anthropic Claude) are strictly prohibited and disqualified under ISRO SAC evaluation guidelines. Defense satellite imagery must not leave the secure perimeter. -

-
- Foreign Cloud API Dependency: - 0% (EXCLUDED) -
-
- - {/* Active Engine Card */} -
-
-
- - - Active Local Neural Backbone - -
- - LOCAL MPS / OLLAMA - -
-
- {activeModelDisplay} -
-

- Runs directly on Apple Silicon Metal Performance Shaders (MPS) and multi-core CPU. Deep neural forward passes extract 512-dimensional visual embeddings, compute cosine similarities against domain taxonomy vectors, and ground features via sliding-window Otsu vectorization. -

-
- - {/* System Hardware Acceleration */} -
-
- - HARDWARE ACCELERATION: - - {aiStatus?.hardware_acceleration || (isBackendHealthy ? 'Local PyTorch Backbone' : 'Backend Offline')} - -
- ZERO API KEYS NEEDED -
-
- )} - - {/* TAB 2: SPECIALIST DOMAIN HEADS */} - {activeTab === 'domain_heads' && ( -
-
- ACTIVE SPECIALIST EXECUTION HEADS (SAC SIH26167) -
- -
- {models.map((m, idx) => { - const Icon = m.icon; - return ( -
-
-
-
- -
-
-
{m.name}
-
{m.category}
-
-
- - {m.status} - -
- -
-
- Domain Adaptation:{' '} - {m.adaptation} -
-
- Inference Latency:{' '} - {m.latency} -
-
-
- ); - })} -
-
- )} - - {/* TAB 3: LIVE STAC STREAMS */} - {activeTab === 'live_streams' && ( -
-
- ACTIVE PLANETARY OBSERVATION STAC STREAMS -
- -
- {liveDataFeeds.length === 0 && ( -
- Stream status unavailable — backend probe not reachable. No status is assumed. -
- )} - {liveDataFeeds.map((feed, idx) => ( -
-
-
- -
-
-
{feed.name}
-
Resolution: {feed.resolution}
-
-
- - {feed.status.replace('_', ' ')} - -
- ))} -
- -
-
- - Real STAC Ingestion: - Live AWS Element84 + Planetary Computer -
- STATUS PROBED LIVE (NO ASSUMED ONLINE) -
-
- )} -
- - {/* Footer */} -
- Target PS: SIH26167 // Team Divya Drishti - -
-
-
- ); -}; - - diff --git a/frontend/src/components/Onboarding.tsx b/frontend/src/components/Onboarding.tsx deleted file mode 100644 index 13e9d56..0000000 --- a/frontend/src/components/Onboarding.tsx +++ /dev/null @@ -1,119 +0,0 @@ -/** - * Onboarding flow — Agent F (F-3) - * Shows on first visit, walkthrough the 3 key actions. - */ -import React, { useState } from 'react'; -import { motion, AnimatePresence } from 'framer-motion'; -import { Satellite, Search, Layers, ArrowRight, X } from 'lucide-react'; - -const steps = [ - { - icon: Satellite, - title: 'Welcome to SatQuery AI', - description: - 'Ask questions about satellite imagery in plain language. The system analyses Sentinel-1 SAR and Sentinel-2 optical data locally — no cloud dependency.', - color: 'text-blue-400', - bg: 'bg-blue-950/40 border-blue-500/30', - }, - { - icon: Search, - title: 'Natural Language Queries', - description: - 'Type questions like "What changed in this area?" or "Show me flood inundation extent". Results include GeoJSON polygon overlays and confidence scores.', - color: 'text-cyan-400', - bg: 'bg-cyan-950/40 border-cyan-500/30', - }, - { - icon: Layers, - title: 'Explore Data Layers', - description: - 'Toggle between optical and SAR imagery, upload your own GeoTIFF, or browse precalibrated sector assets. Click map pins for pixel-level inspection.', - color: 'text-emerald-400', - bg: 'bg-emerald-950/40 border-emerald-500/30', - }, -]; - -interface OnboardingProps { - onComplete: () => void; -} - -export function Onboarding({ onComplete }: OnboardingProps) { - const [step, setStep] = useState(0); - - const isLast = step === steps.length - 1; - - return ( - - - {/* Skip button */} - - -
- - - {(() => { - const { icon: Icon, title, description, color, bg } = steps[step]; - return ( - <> -
-
-

{title}

-

{description}

- - ); - })()} -
-
- - {/* Step dots */} -
- {steps.map((_, i) => ( -
- - {/* CTA */} - -
-
-
- ); -} diff --git a/frontend/src/components/SearchModal.tsx b/frontend/src/components/SearchModal.tsx deleted file mode 100644 index be4efda..0000000 --- a/frontend/src/components/SearchModal.tsx +++ /dev/null @@ -1,264 +0,0 @@ -import React, { useState, useEffect, useRef } from 'react'; -import { - Search, - X, - Layers, - CloudRain, - Building2, - Ship, - CornerDownLeft, - Sparkles, - Loader2, - Compass, -} from 'lucide-react'; -import { RECOMMENDED_PRESETS, TACTICAL_PINS } from '../config/tacticalData'; -import type { TacticalGlobePin } from '../types'; - -interface SearchModalProps { - isOpen: boolean; - onClose: () => void; - onExecuteQuery: (query: string, sectorPin?: TacticalGlobePin) => void; -} - -export const SearchModal: React.FC = ({ - isOpen, - onClose, - onExecuteQuery, -}) => { - const [queryText, setQueryText] = useState(''); - const [isProcessing, setIsProcessing] = useState(false); - const inputRef = useRef(null); - - // Auto-focus on open - useEffect(() => { - if (isOpen) { - setTimeout(() => inputRef.current?.focus(), 50); - } else { - setQueryText(''); - setIsProcessing(false); - } - }, [isOpen]); - - // Global shortcut listeners (Cmd+K / Ctrl+K and Esc) - useEffect(() => { - function handleKeyDown(e: KeyboardEvent) { - if ((e.metaKey || e.ctrlKey) && e.key === 'k') { - e.preventDefault(); - // Handled by parent or toggles here - } - if (e.key === 'Escape' && isOpen) { - e.preventDefault(); - onClose(); - } - } - window.addEventListener('keydown', handleKeyDown); - return () => window.removeEventListener('keydown', handleKeyDown); - }, [isOpen, onClose]); - - if (!isOpen) return null; - - const handleRunPreset = (preset: typeof RECOMMENDED_PRESETS[0]) => { - const pin = TACTICAL_PINS.find((p) => p.id === preset.sectorId) || TACTICAL_PINS[0]; - setQueryText(preset.query); - setIsProcessing(true); - setTimeout(() => { - onExecuteQuery(preset.query, pin); - setIsProcessing(false); - onClose(); - }, 300); - }; - - const handleFormSubmit = (e: React.FormEvent) => { - e.preventDefault(); - if (!queryText.trim()) return; - - // Find best matching pin by query text - const textLower = queryText.toLowerCase(); - const matchedPin = - TACTICAL_PINS.find( - (p) => - p.name.toLowerCase().includes(textLower) || - p.description.toLowerCase().includes(textLower) || - p.category.toLowerCase().includes(textLower) - ) || TACTICAL_PINS[0]; - - setIsProcessing(true); - setTimeout(() => { - onExecuteQuery(queryText, matchedPin); - setIsProcessing(false); - onClose(); - }, 350); - }; - - // Filtered matching pins for quick select - const filteredPins = queryText.trim() - ? TACTICAL_PINS.filter( - (pin) => - pin.name.toLowerCase().includes(queryText.toLowerCase()) || - pin.badge.toLowerCase().includes(queryText.toLowerCase()) || - pin.description.toLowerCase().includes(queryText.toLowerCase()) - ).slice(0, 3) - : []; - - return ( -
-
e.stopPropagation()} - className="w-full max-w-2xl bg-gradient-to-b from-[#151A26] to-[#0D1018] border border-[#232B3E] rounded-xl shadow-[0_24px_50px_rgba(0,0,0,0.8),inset_0_1px_0_rgba(255,255,255,0.08)] overflow-hidden flex flex-col text-slate-200" - > - {/* Search Header Input */} -
- - setQueryText(e.target.value)} - placeholder="Search sector, coordinate, or ask remote sensing question (e.g. detect structural change)..." - className="w-full bg-transparent border-none px-3 text-sm text-slate-100 placeholder-slate-500 font-sans focus-visible:outline-none" - /> - - {isProcessing ? ( - - ) : queryText ? ( - - ) : ( -
- ESC TO EXIT -
- )} - - - {/* Modal Body */} -
- {/* Matched Sector Pins if query is active */} - {filteredPins.length > 0 && ( -
-
- Matching Sectors -
-
- {filteredPins.map((pin) => ( - - ))} -
-
- )} - - {/* Recommended Sensing Presets */} -
-
-
- - Recommended Sensing Presets -
- - RemoteCLIP + MobileSAM Ingestion - -
- -
- {RECOMMENDED_PRESETS.map((preset) => { - const getIcon = () => { - switch (preset.icon) { - case 'Layers': - return ; - case 'CloudRain': - return ; - case 'Building2': - return ; - case 'Ship': - return ; - default: - return ; - } - }; - - return ( - - ); - })} -
-
-
- - {/* Footer Navigation Hints */} -
-
- - - ↵ ENTER - - to execute - - - - ESC - - to dismiss - -
- - ESA / ISRO / NASA STAC Catalog Online - -
-
-
- ); -}; diff --git a/frontend/src/components/SituationalFeedDrawer.tsx b/frontend/src/components/SituationalFeedDrawer.tsx deleted file mode 100644 index d163372..0000000 --- a/frontend/src/components/SituationalFeedDrawer.tsx +++ /dev/null @@ -1,335 +0,0 @@ -import React, { useState } from 'react'; -import { - Activity, - AlertTriangle, - Satellite, - Layers, - ChevronRight, - X, - Radio, - Sliders, - CheckSquare, - Square, - ExternalLink, - ShieldAlert, - Flame, - CloudRain, - Compass, -} from 'lucide-react'; -import type { LayerConfig, TacticalGlobePin } from '../types'; - -interface SituationalFeedDrawerProps { - isOpen: boolean; - onClose: () => void; - layers: LayerConfig[]; - onToggleLayer: (id: string) => void; - onOpacityChange: (id: string, opacity: number) => void; - pins: TacticalGlobePin[]; - selectedPin: TacticalGlobePin | null; - onSelectPin: (pin: TacticalGlobePin) => void; - onExecuteQueryForSector?: (pin: TacticalGlobePin) => void; -} - -interface TacticalAlertItem { - id: string; - pinId: string; - title: string; - severity: 'CRITICAL' | 'HIGH' | 'TACTICAL' | 'ADVISORY'; - region: string; - sensor: string; - summary: string; - timestamp: string; -} - -const TACTICAL_ALERTS: TacticalAlertItem[] = [ - { - id: 'alt-1', - pinId: 'brahmaputra-flood', - title: 'Assam Kaziranga Monsoon Inundation', - severity: 'CRITICAL', - region: 'Northeast Corridor, Assam', - sensor: 'Sentinel-1 C-SAR (Cloud Pierced)', - summary: 'Illustrative scenario: heavy cloud cover over Brahmaputra basin; SAR specular water-boundary isolation is demonstrated on request.', - timestamp: '12m ago', - }, - { - id: 'alt-2', - pinId: 'joshimath-subsidence', - title: 'Joshimath Himalayan Land Subsidence', - severity: 'HIGH', - region: 'Chamoli, Uttarakhand', - sensor: 'Cartosat-2S (Optical)', - summary: 'Illustrative scenario: differential terrain along slope gradient. This system performs radiometric DSP change detection only — no InSAR/DInSAR processing.', - timestamp: '34m ago', - }, - { - id: 'alt-3', - pinId: 'galwan-sar', - title: 'Galwan Valley LAC Tactical Infrastructure', - severity: 'TACTICAL', - region: 'Ladakh Sector, LAC', - sensor: 'RISAT-1A (EOS-04) + Sentinel-1', - summary: 'Illustrative scenario: high-backscatter double-bounce signature analysis for causeway/road reconnaissance (computed live on query).', - timestamp: '1h 14m ago', - }, - { - id: 'alt-4', - pinId: 'tarapur-npp', - title: 'Tarapur NPP Thermal Effluent Channel', - severity: 'ADVISORY', - region: 'Maharashtra Coastline', - sensor: 'Landsat-9 TIRS + Sentinel-2', - summary: 'Illustrative scenario: cooling-water discharge channel monitoring; thermal variance is not currently measured by this system.', - timestamp: '2h 05m ago', - }, -]; - -const ORBITAL_PASSES = [ - { sensor: 'Sentinel-2A MSI', band: 'B2-B12 (10m)', passWindow: '14m 20s', mode: 'High Sun (Cloud-Free)', status: 'SIM · APPROACHING' }, - { sensor: 'Sentinel-1 C-SAR', band: 'C-Band 5.405 GHz', passWindow: '42m 10s', mode: 'IW GRD Dual-Pol', status: 'SIM · ACTIVE' }, - { sensor: 'Cartosat-3', band: 'Panchromatic (0.28m)', passWindow: '01h 18m', mode: 'Sub-Meter Tactical', status: 'SIM · SCHEDULED' }, - { sensor: 'RISAT-1A (EOS-04)', band: 'C-Band Circular Pol', passWindow: '02h 45m', mode: 'FRS-1 High-Res', status: 'SIM · STANDBY' }, - { sensor: 'INSAT-3DR (MOSDAC)', band: 'Imager & Sounder', passWindow: 'CONTINUOUS', mode: 'Geostationary 74°E', status: 'SIM · CONTINUOUS' }, -]; - -export const SituationalFeedDrawer: React.FC = ({ - isOpen, - onClose, - layers, - onToggleLayer, - onOpacityChange, - pins, - selectedPin, - onSelectPin, - onExecuteQueryForSector, -}) => { - const [activeTab, setActiveTab] = useState<'alerts' | 'passes' | 'layers'>('alerts'); - - if (!isOpen) return null; - - return ( - - ); -}; diff --git a/frontend/src/components/TemporalScrubber.tsx b/frontend/src/components/TemporalScrubber.tsx deleted file mode 100644 index 5cd19e1..0000000 --- a/frontend/src/components/TemporalScrubber.tsx +++ /dev/null @@ -1,344 +0,0 @@ -import React, { useState, useEffect, useMemo, useCallback } from 'react'; -import { - Clock, - Play, - Pause, - RotateCcw, - Calendar, - Satellite, - Activity, - Layers, - Sparkles, - Columns, - Eye, -} from 'lucide-react'; -import type { TimeRangeOption, SatellitePass } from '../types'; -import { fetchSectorTimeline, generateClientTimeline, findNearestPass } from '../utils/timelineConstellation'; -import { ProvenanceBadge } from './ui/ProvenanceBadge'; - -interface TemporalScrubberProps { - timeRange: TimeRangeOption; - onChangeTimeRange: (range: TimeRangeOption) => void; - sliderValue?: number; - onSliderChange?: (val: number) => void; - onPlayChange?: (isPlaying: boolean) => void; - activeEpochLabel?: string; - isBitemporal?: boolean; - t1Date?: string; - t2Date?: string; - sectorId?: string; - sectorName?: string; - onPassChange?: (pass: SatellitePass) => void; - isCurtainMode?: boolean; - onToggleCurtainMode?: () => void; -} - -export const TemporalScrubber: React.FC = ({ - timeRange, - onChangeTimeRange, - sliderValue = 50, - onSliderChange, - onPlayChange, - activeEpochLabel, - isBitemporal = false, - t1Date = '2024-04-01', - t2Date = '2024-05-01', - sectorId = 'isro-sac', - sectorName, - onPassChange, - isCurtainMode = false, - onToggleCurtainMode, -}) => { - const [internalValue, setInternalValue] = useState(sliderValue); - const [isPlaying, setIsPlaying] = useState(false); - const [isInteractingSlider, setIsInteractingSlider] = useState(false); - const [passes, setPasses] = useState(() => - generateClientTimeline(sectorId, timeRange, t1Date, t2Date) - ); - - // Sync internal slider value from prop - useEffect(() => { - setInternalValue(sliderValue); - }, [sliderValue]); - - // Load dense constellation passes whenever sector, timeRange, or dates change - useEffect(() => { - let active = true; - fetchSectorTimeline(sectorId, timeRange, t1Date, t2Date).then((fetched) => { - if (active && fetched && fetched.length > 0) { - setPasses(fetched); - } - }); - return () => { - active = false; - }; - }, [sectorId, timeRange, t1Date, t2Date]); - - // Active satellite pass currently targeted by the slider - const activePass = useMemo(() => { - return findNearestPass(passes, internalValue); - }, [passes, internalValue]); - - // Notify parent of active pass changes - useEffect(() => { - if (activePass && onPassChange) { - onPassChange(activePass); - } - }, [activePass, onPassChange]); - - // Automated time-scrubber play interval - useEffect(() => { - if (!isPlaying) return; - const interval = setInterval(() => { - setInternalValue((prev) => { - const next = prev >= 100 ? 0 : Math.min(100, prev + 1.5); - setTimeout(() => { - onSliderChange?.(next); - }, 0); - return next; - }); - }, 100); - return () => clearInterval(interval); - }, [isPlaying, onSliderChange]); - - const handleTogglePlay = () => { - const nextPlaying = !isPlaying; - setIsPlaying(nextPlaying); - onPlayChange?.(nextPlaying); - }; - - const handleRangeChange = (e: React.ChangeEvent) => { - const val = Number(e.target.value); - setInternalValue(val); - onSliderChange?.(val); - }; - - const formatShortDate = (isoStr: string, compareDateStr?: string) => { - try { - const d = new Date(isoStr); - if (isNaN(d.getTime())) return isoStr; - const dComp = compareDateStr ? new Date(compareDateStr) : null; - const showYear = dComp && !isNaN(dComp.getTime()) && dComp.getFullYear() !== d.getFullYear(); - return d.toLocaleDateString('en-GB', { - day: '2-digit', - month: 'short', - year: showYear ? 'numeric' : undefined, - }).toUpperCase(); - } catch { - return isoStr; - } - }; - - return ( -
-
- {/* Row 1: Temporal Range & Sector — always visible ("what am I looking at") */} -
- {/* Left: T1 -> T2 Range & Sector Name */} -
- - T1: {formatShortDate(t1Date, t2Date)} - - ──► - - T2: {formatShortDate(t2Date, t1Date)} - - {sectorName && ( - - {sectorName} - - )} -
- - {/* Right: Sync status indicator (minimal) */} - {!activePass && ( -
- - {activeEpochLabel || 'Synchronizing Constellation...'} -
- )} -
- - {/* Row 2: Active Pass Metadata — conditional, slides in on interaction */} -
- {activePass && ( -
-
- - {activePass.sensor} - ({activePass.resolution}) - {activePass.is_simulated && ( - - )} -
-
- • - {activePass.formattedDate} - {activePass.formattedTime} -
-
- - Δ {activePass.deltaPercent}% -
-
- )} -
- - {/* Bottom Row: Span Selector, Timeline Track with 100s of passes, Play Controls */} -
- {/* Left: Time Range Presets */} -
-
- - SPAN: -
- {(['24h', '7d', '30d', '1y', 'all'] as const).map((r) => ( - - ))} -
- - {/* Center: Constellation Pass Ticks & Slider Track */} -
setIsInteractingSlider(true)} - onMouseLeave={() => setIsInteractingSlider(false)} - onTouchStart={() => setIsInteractingSlider(true)} - onTouchEnd={() => setIsInteractingSlider(false)} - > -
- {/* Background Track */} -
-
-
- - {/* Constellation Pass Pips (Dense timeline showing 10s or 100s of passes) */} -
- {passes.map((p, idx) => { - const passPercent = (idx / Math.max(1, passes.length - 1)) * 100; - const isCurrent = activePass?.id === p.id; - return ( -
- ); - })} -
- - {/* Range Input */} - -
-
- - {/* Right: Mode Toggle (Timelapse vs Split Curtain) & Playback Button */} -
- {/* Split Curtain Mode Toggle */} - {onToggleCurtainMode && ( - - )} - - {/* Timelapse Play / Pause */} - - - {/* Reset to Start or Middle */} - -
-
-
-
- ); -}; diff --git a/frontend/src/components/ui/Dialog.tsx b/frontend/src/components/ui/Dialog.tsx deleted file mode 100644 index eceebee..0000000 --- a/frontend/src/components/ui/Dialog.tsx +++ /dev/null @@ -1,112 +0,0 @@ -/** - * Accessible Dialog component — Agent C (C-4) - * Focus trap, Escape to close, ARIA modal attributes. - */ -import { useEffect, useRef, useCallback } from 'react'; -import { motion, AnimatePresence } from 'framer-motion'; -import { X } from 'lucide-react'; - -interface DialogProps { - isOpen: boolean; - onClose: () => void; - title: string; - children: React.ReactNode; - maxWidth?: string; -} - -export function Dialog({ isOpen, onClose, title, children, maxWidth = 'max-w-2xl' }: DialogProps) { - const dialogRef = useRef(null); - const previousFocusRef = useRef(null); - - // Manage focus on open/close - useEffect(() => { - if (isOpen) { - previousFocusRef.current = document.activeElement as HTMLElement; - // Defer so animation frame completes - requestAnimationFrame(() => dialogRef.current?.focus()); - } else { - previousFocusRef.current?.focus(); - } - }, [isOpen]); - - // Escape key + focus trap - const handleKeyDown = useCallback( - (e: React.KeyboardEvent) => { - if (e.key === 'Escape') { - e.preventDefault(); - onClose(); - return; - } - if (e.key === 'Tab') { - const focusable = dialogRef.current?.querySelectorAll( - 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])' - ); - if (!focusable?.length) return; - const first = focusable[0]; - const last = focusable[focusable.length - 1]; - if (e.shiftKey && document.activeElement === first) { - e.preventDefault(); - last.focus(); - } else if (!e.shiftKey && document.activeElement === last) { - e.preventDefault(); - first.focus(); - } - } - }, - [onClose] - ); - - return ( - - {isOpen && ( - <> - {/* Backdrop */} - - ); -} diff --git a/frontend/src/components/ui/ProvenanceBadge.tsx b/frontend/src/components/ui/ProvenanceBadge.tsx deleted file mode 100644 index d1c7756..0000000 --- a/frontend/src/components/ui/ProvenanceBadge.tsx +++ /dev/null @@ -1,83 +0,0 @@ -import React from 'react'; -import { cn } from '../../utils'; - -export type ProvenanceVariant = 'SIMULATED' | 'SAMPLE DATA' | 'VERIFIED' | 'LIVE'; - -export interface ProvenanceBadgeProps extends React.HTMLAttributes { - variant: ProvenanceVariant; - size?: 'xs' | 'sm'; - showIcon?: boolean; - className?: string; -} - -const variantStyles: Record = { - SIMULATED: { - badge: 'border-amber-500/30 bg-amber-950/40 text-amber-300', - dot: 'bg-amber-400', - icon: '⚠', - }, - 'SAMPLE DATA': { - badge: 'border-blue-500/30 bg-blue-950/40 text-blue-300', - dot: 'bg-blue-400', - icon: '📋', - }, - VERIFIED: { - badge: 'border-emerald-500/30 bg-emerald-950/40 text-emerald-300', - dot: 'bg-emerald-400', - icon: '✓', - }, - LIVE: { - badge: 'border-cyan-500/30 bg-cyan-950/40 text-cyan-300', - dot: 'bg-cyan-400', - icon: '🔴', - }, -}; - -const variantDescriptions: Record = { - SIMULATED: 'Procedurally generated — not from live sensor acquisition', - 'SAMPLE DATA': 'Curated sample file — not a live query result', - VERIFIED: 'Authentic sensor data with cryptographic audit trail', - LIVE: 'Real-time satellite pass from STAC catalog', -}; - -export const ProvenanceBadge: React.FC = ({ - variant, - size = 'xs', - showIcon = true, - className, - ...props -}) => { - const styles = variantStyles[variant]; - const isXs = size === 'xs'; - const description = variantDescriptions[variant]; - - return ( -
- {showIcon && ( -
- ); -}; - -export default ProvenanceBadge; \ No newline at end of file diff --git a/frontend/src/components/ui/Skeleton.tsx b/frontend/src/components/ui/Skeleton.tsx deleted file mode 100644 index d3f1301..0000000 --- a/frontend/src/components/ui/Skeleton.tsx +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Loading skeleton components — Agent C (C-7) - */ -import React from 'react'; - -interface SkeletonProps { - className?: string; -} - -export function Skeleton({ className = '' }: SkeletonProps) { - return ( -
- ); -} - -export function QuerySkeleton() { - return ( -
- - - -
- - -
- Loading... -
- ); -} - -export function CardSkeleton() { - return ( -
- - - - Loading... -
- ); -} diff --git a/frontend/src/components/ui/StatusBadge.tsx b/frontend/src/components/ui/StatusBadge.tsx deleted file mode 100644 index a9ac46a..0000000 --- a/frontend/src/components/ui/StatusBadge.tsx +++ /dev/null @@ -1,86 +0,0 @@ -import React from 'react'; -import { cn } from '../../utils'; - -export type StatusVariant = 'success' | 'warning' | 'error' | 'info' | 'satellite' | 'neutral'; - -export interface StatusBadgeProps extends React.HTMLAttributes { - variant?: StatusVariant; - label: string; - sublabel?: string; - pulsing?: boolean; - size?: 'xs' | 'sm'; -} - -const variantStyles: Record = { - success: { - badge: 'border-emerald-500/30 bg-emerald-950/40 text-emerald-300', - dot: 'bg-emerald-400', - }, - warning: { - badge: 'border-amber-500/30 bg-amber-950/40 text-amber-300', - dot: 'bg-amber-400', - }, - error: { - badge: 'border-red-500/30 bg-red-950/40 text-red-300', - dot: 'bg-red-400', - }, - info: { - badge: 'border-blue-500/30 bg-blue-950/40 text-blue-300', - dot: 'bg-blue-400', - }, - satellite: { - badge: 'border-cyan-500/30 bg-cyan-950/40 text-cyan-300', - dot: 'bg-cyan-400', - }, - neutral: { - badge: 'border-[#243044] bg-[#111724] text-slate-300', - dot: 'bg-slate-400', - }, -}; - -export const StatusBadge: React.FC = ({ - variant = 'neutral', - label, - sublabel, - pulsing = true, - size = 'xs', - className, - ...props -}) => { - const styles = variantStyles[variant]; - const isXs = size === 'xs'; - - return ( -
-
- ); -}; - -export default StatusBadge; diff --git a/frontend/src/components/ui/TelemetryGauge.tsx b/frontend/src/components/ui/TelemetryGauge.tsx deleted file mode 100644 index 5c98ce4..0000000 --- a/frontend/src/components/ui/TelemetryGauge.tsx +++ /dev/null @@ -1,162 +0,0 @@ -import React, { useEffect, useState } from 'react'; -import { cn } from '../../utils'; - -export type GaugeVariant = 'emerald' | 'cyan' | 'amber' | 'blue' | 'auto'; - -export interface TelemetryGaugeProps extends React.HTMLAttributes { - value: number; // 0 to 100 - segments?: number; - label?: string; - sublabel?: string; - showValue?: boolean; - variant?: GaugeVariant; - size?: 'sm' | 'md'; -} - -function resolveVariant(value: number, requestedVariant: GaugeVariant): 'emerald' | 'cyan' | 'amber' | 'blue' { - if (requestedVariant !== 'auto') return requestedVariant; - if (value >= 75) return 'emerald'; - if (value >= 40) return 'cyan'; - return 'amber'; -} - -const variantStyles = { - emerald: { - filled: 'bg-emerald-400 shadow-[0_0_6px_rgba(52,211,153,0.5)]', - text: 'text-emerald-400', - border: 'border-emerald-500/30', - corner: 'border-emerald-500/50', - }, - cyan: { - filled: 'bg-cyan-400 shadow-[0_0_6px_rgba(34,211,238,0.5)]', - text: 'text-cyan-400', - border: 'border-cyan-500/30', - corner: 'border-cyan-500/50', - }, - amber: { - filled: 'bg-amber-400 shadow-[0_0_6px_rgba(251,191,36,0.5)]', - text: 'text-amber-400', - border: 'border-amber-500/30', - corner: 'border-amber-500/50', - }, - blue: { - filled: 'bg-blue-400 shadow-[0_0_6px_rgba(96,165,250,0.5)]', - text: 'text-blue-400', - border: 'border-blue-500/30', - corner: 'border-blue-500/50', - }, -}; - -export const TelemetryGauge: React.FC = ({ - value, - segments = 10, - label, - sublabel, - showValue = true, - variant = 'auto', - size = 'md', - className, - ...props -}) => { - const clamped = Math.max(0, Math.min(100, Math.round(value))); - const resolved = resolveVariant(clamped, variant); - const styles = variantStyles[resolved]; - const filledCount = Math.round((clamped / 100) * segments); - - const [visibleCount, setVisibleCount] = useState(0); - - useEffect(() => { - if (filledCount === 0) { - setVisibleCount(0); - return; - } - let current = 0; - const interval = setInterval(() => { - current++; - setVisibleCount(current); - if (current >= filledCount) clearInterval(interval); - }, 40); - return () => clearInterval(interval); - }, [filledCount]); - - const isSm = size === 'sm'; - - return ( -
- {/* Tactical scanline texture */} -