-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
691 lines (609 loc) · 28.2 KB
/
Copy pathserver.py
File metadata and controls
691 lines (609 loc) · 28.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
"""App-level HTTP API: one thin layer between a web front end and the agent.
The Streamlit app (app/frontend) calls :class:`AgentController` in-process.
A browser front end cannot do that, so this module exposes the same run
pipeline over HTTP without changing any of the pieces underneath it.
Why a job + poll instead of one long POST: a bi-temporal run on the GPU takes
~85 s and a quick cloudflared tunnel drops requests that outstay its request
timeout; short polls are immune to that, and they make the progress indicator
in the UI *real* (the server reports the stage it is actually in) instead of a
clock pretending.
The model server (models/serving/colab_api.py) and the serving factory are
untouched: this module is a consumer of both, exactly as app/frontend is.
Run it with:
uvicorn app.webapi.server:app --host 0.0.0.0 --port 8000
"""
from __future__ import annotations
import json
import os
import re
import secrets
import shutil
import threading
import time
import traceback
import uuid
from pathlib import Path
from typing import Any
from fastapi import FastAPI, File, Form, HTTPException, Request, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse
ROOT = Path(__file__).resolve().parents[2]
from agent.planner import AgentController, TaskType # noqa: E402
from agent.planner.classifier import classify # noqa: E402
from agent.validators import validate # noqa: E402
from app.frontend.explain import ( # noqa: E402
answer_in_plain_words,
caveats,
confidence_words,
evidence_caption,
understood_as,
what_the_system_did,
)
from app.frontend.meta import ( # noqa: E402
GLOSSARY,
GLOSSARY_HI,
SAMPLE_QUERIES,
SAMPLE_QUERIES_HI,
)
from app.frontend.report import build_pdf # noqa: E402
from app.webapi import locations as locmod # noqa: E402
from app.webapi.locations import LocationError # noqa: E402
UPLOAD_EXTENSIONS = {".tif", ".tiff", ".png", ".jpg", ".jpeg"}
MAX_IMAGES = 2
MAX_UPLOAD_BYTES = 64 * 1024 * 1024
RUN_TTL_S = 12 * 3600
DEFAULT_ADAPTER = ROOT / "adapters" / "m3c-full-a6796d97783f0fec" / "checkpoint-1590"
FUSION_HEAD = ROOT / "models" / "fusion" / "fusion_head.pt"
DEMO_ASSETS_DIR = ROOT / "demo_assets"
RUNS_ROOT = ROOT / "outputs" / "api_runs"
app = FastAPI(title="SatQuery AI", version="1.0.0")
# --- access control --------------------------------------------------------
# The front end is a static bundle on Cloudflare Pages and this server is
# wherever the tunnel happens to point, so every call is cross-origin and the
# allow-list has to name the front end explicitly.
#
# What an allow-list does NOT do is stop someone using your GPU. CORS is
# enforced by browsers, on reads: `curl https://<tunnel>/api/query` ignores it
# completely. The control that actually gates access is SATQUERY_API_TOKEN
# below. Both are here because they solve different problems -- the allow-list
# stops a random page in a visitor's browser from quietly driving their tunnel,
# the token stops anyone who simply has the URL.
ALLOWED_ORIGINS = [
"https://satquery-ai.pages.dev", # production front end (Cloudflare Pages)
"https://satquery-ai-ps26167.netlify.app", # fallback deploy (Netlify) --
# stood up 2026-09-02 because wrangler's interactive login wasn't
# completed in time; see CLAUDE.md for why two production URLs exist.
"http://localhost:3000", # next dev server
"http://127.0.0.1:3000",
]
ALLOWED_ORIGINS += [o.strip() for o in
os.environ.get("SATQUERY_ALLOWED_ORIGINS", "").split(",")
if o.strip()]
# Cloudflare Pages and Netlify both give every branch/preview build its own
# subdomain, so those are matched rather than enumerated.
ALLOWED_ORIGIN_REGEX = (
r"https://[a-z0-9-]+\.satquery-ai\.pages\.dev"
r"|https://[a-z0-9-]+--satquery-ai-ps26167\.netlify\.app"
)
API_TOKEN = os.environ.get("SATQUERY_API_TOKEN", "").strip()
# Registered BEFORE the CORS middleware on purpose. Starlette runs the most
# recently added middleware outermost, so this ordering puts CORS outside the
# token check -- which means a 401 still comes back with CORS headers on it.
# The other way round, the browser reports an opaque CORS failure and hides the
# 401 completely, which is a genuinely awful thing to debug.
@app.middleware("http")
async def _require_token(request: Request, call_next):
"""Shared-secret gate, active only when SATQUERY_API_TOKEN is set.
Unset (the default) leaves the server open, so the zero-config demo path
keeps working. Set it when you are exposing your own GPU and would rather
a leaked tunnel URL not be an open invitation.
"""
if API_TOKEN and request.url.path.startswith("/api/"):
# Preflight requests carry no custom headers by definition, so they
# have to pass through or the browser never sends the real request.
if request.method != "OPTIONS":
# Header for fetch(); query param for <img src>, which cannot set
# headers and is how evidence images are loaded.
sent = (request.headers.get("x-satquery-token")
or request.query_params.get("token") or "")
if not secrets.compare_digest(sent, API_TOKEN):
return JSONResponse(
{"detail": "missing or invalid API token; set it in the "
"connection bar"},
status_code=401)
return await call_next(request)
app.add_middleware(
CORSMiddleware,
allow_origins=ALLOWED_ORIGINS,
allow_origin_regex=ALLOWED_ORIGIN_REGEX,
allow_methods=["GET", "POST", "OPTIONS"],
allow_headers=["content-type", "x-satquery-token"],
)
# ---------------------------------------------------------------------------
# Run state + controller
# ---------------------------------------------------------------------------
class _Run:
"""One query run, from submission to trace, in memory."""
def __init__(self, run_id: str, query: str, image_paths: list[str]) -> None:
self.id = run_id
self.query = query
self.image_paths = image_paths
self.state = "running" # running | done | error
self.stage = "queued"
self.stage_history: list[str] = []
self.error = ""
self.trace: dict[str, Any] | None = None
self.interpretation: dict[str, Any] = {}
self.evidence: list[dict[str, Any]] = []
self.run_dir: Path | None = None
self.created = time.time()
_runs: dict[str, _Run] = {}
class _LocationJob:
"""One background location fetch, so a slow first fetch can be polled."""
def __init__(self, job_id: str, bbox, name: str) -> None:
self.id = job_id
self.bbox = bbox
self.name = name
self.state = "running"
self.stage = "searching the STAC catalogue"
self.result: dict | None = None
self.error = ""
self._t0 = time.time()
@property
def elapsed_ms(self) -> float:
return (time.time() - self._t0) * 1000
def run(self) -> None:
try:
self.result = locmod.fetch_timeline(self.bbox, self.name)
self.state = "done"
except LocationError as exc:
self.state, self.error = "error", str(exc)
except Exception as exc: # noqa: BLE001
self.state = "error"
self.error = f"{type(exc).__name__}: {exc}"
_location_jobs: dict[str, _LocationJob] = {}
_controller: AgentController | None = None
_controller_lock = threading.Lock()
def get_controller() -> AgentController:
"""One controller per process; the backend factory caches by kind too.
MODEL_BACKEND decides where the model runs (stub / local in-process /
remote URL), exactly as the Streamlit app resolves it.
"""
global _controller
with _controller_lock:
if _controller is None:
from models.serving.factory import get_backend
adapter = os.environ.get("ADAPTER_PATH")
if not adapter and DEFAULT_ADAPTER.exists():
adapter = str(DEFAULT_ADAPTER)
run_root = RUNS_ROOT / uuid.uuid4().hex[:8]
run_root.mkdir(parents=True, exist_ok=True)
_controller = AgentController(
backend=get_backend(),
report_dir=run_root,
adapter_path=adapter,
fusion_head_path=str(FUSION_HEAD) if FUSION_HEAD.exists() else None,
)
return _controller
def _prune_runs() -> None:
"""Drop runs older than the TTL so a long session does not grow unbounded."""
cutoff = time.time() - RUN_TTL_S
for rid in [rid for rid, run in _runs.items() if run.created < cutoff]:
_runs.pop(rid, None)
def interpret(trace) -> dict:
"""Plain-language strings, straight from the same explain.py the Streamlit
app renders and the test suite pins — no second copy of the wording."""
t = trace.model_dump()
paths = list(t.get("visual_evidence_paths") or [])
return {
"answer": answer_in_plain_words(t),
"understood_as": understood_as(t),
"what_the_system_did": what_the_system_did(t),
"caveats": caveats(t),
"confidence": {
"value": t.get("overall_confidence", 0.0),
"words": confidence_words(t.get("overall_confidence", 0.0)),
},
"alerts": change_alerts(t),
}
#: Change-alert thresholds, applied at the presentation layer only. The
#: change tool reports the changed fraction of the scene in its own summary
#: sentence ("The change map marks 26.4% of the scene, ..."); the regex reads
#: that, it does not re-derive anything about the mask. Anything the tool did
#: not measure is never turned into an alert here.
_ALERT_FRACTION_RE = re.compile(r"marks (\d+(?:\.\d+)?)% of the scene")
ALERT_STRONG = (0.15, 0.60) # >=15% changed and confidence >= 0.60
ALERT_NOTE = (0.05,) # worth pointing at 5%+ of the scene
def change_alerts(trace_dict: dict) -> list[dict]:
"""Confidence-based change alerts for a finished trace."""
out = []
conf = float(trace_dict.get("overall_confidence") or 0.0)
for step in trace_dict.get("steps") or []:
if step.get("tool_name") != "change_analysis" or step.get("status") != "success":
continue
m = _ALERT_FRACTION_RE.search(step.get("output_summary") or "")
if not m:
continue
fraction = float(m.group(1)) / 100.0
if fraction >= ALERT_STRONG[0] and conf >= ALERT_STRONG[1]:
level = "alert"
elif fraction >= ALERT_NOTE[0]:
level = "note"
else:
continue
out.append({
"level": level,
"changed_fraction": fraction,
"confidence": conf,
"message": (f"{m.group(1)}% of the scene changed between the two "
f"dates at model confidence {conf:.2f}"),
})
return out
# ---------------------------------------------------------------------------
# Demo asset resolution (same manifest the Streamlit app reads)
# ---------------------------------------------------------------------------
def demo_role_paths(roles: list[str]) -> list[str]:
"""Map role names from demo_assets/manifest.json, in role order.
For the bi-temporal pair the caller's order *is* the answer (early, late);
that is why roles are followed literally instead of sorted.
"""
if not roles:
return []
manifest_path = DEMO_ASSETS_DIR / "manifest.json"
if not manifest_path.exists():
raise HTTPException(
status_code=503,
detail="demo_assets/manifest.json is missing on the API server — "
"run scripts/fetch_real_demo_assets.py, or upload images")
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
by_role: dict[str, str] = {}
base = manifest_path.parent
assets = manifest.get("assets") or {}
for _key, entry in assets.items():
rel = entry.get("file") or entry.get("path") or ""
# The manifest keys assets BY role (one entry per role); a legacy
# shape with an explicit roles list is supported too.
if entry.get("roles"):
for role in entry["roles"]:
by_role.setdefault(role, str(base / rel))
else:
by_role.setdefault(str(_key), str(base / rel))
missing = [r for r in roles if r not in by_role]
if missing:
raise HTTPException(
status_code=404,
detail=f"no demo asset for role(s) {missing}; available: {sorted(by_role)}")
paths = [by_role[r] for r in roles]
# Two identical files (e.g. the same image listed twice) would fail the
# pair check confusingly; dedupe while keeping caller order.
return list(dict.fromkeys(paths))
# ---------------------------------------------------------------------------
# Upload handling
# ---------------------------------------------------------------------------
def save_uploads(files: list[UploadFile], dest: Path) -> list[str]:
dest.mkdir(parents=True, exist_ok=True)
paths: list[str] = []
for f in files:
original = Path(f.filename or "upload")
if original.suffix.lower() not in UPLOAD_EXTENSIONS:
raise HTTPException(
status_code=415,
detail=f"unsupported file type '{original.suffix or original.name}'; "
"accepted: GeoTIFF/TIFF, PNG, JPEG")
out = dest / f"{uuid.uuid4().hex[:8]}_{original.name}"
size = 0
with out.open("wb") as fh:
while chunk := f.file.read(1024 * 1024):
size += len(chunk)
if size > MAX_UPLOAD_BYTES:
fh.close()
out.unlink(missing_ok=True)
raise HTTPException(status_code=413,
detail="image larger than 64 MB")
fh.write(chunk)
paths.append(str(out))
return paths
# ---------------------------------------------------------------------------
# The run itself (background thread)
# ---------------------------------------------------------------------------
def _run_query_job(run: _Run) -> None:
try:
ctrl = get_controller()
run.run_dir = Path(ctrl._report_dir).parent / run.id
run.run_dir.mkdir(parents=True, exist_ok=True)
def progress(stage: str) -> None:
run.stage = stage
run.stage_history.append(stage)
ctrl._report_dir = run.run_dir # evidence + PDF land with this run
trace = ctrl.run(run.query, run.image_paths, None, progress=progress)
run.trace = trace.model_dump()
run.evidence = [
{"index": i, "caption": evidence_caption(p), "path": str(p),
"url": f"/api/run/{run.id}/evidence/{i}"}
for i, p in enumerate(trace.visual_evidence_paths)
if Path(p).exists()
]
run.interpretation = interpret(trace)
# Persist downloads alongside the run so the report link survives.
(run.run_dir / "trace.json").write_text(trace.to_json(), encoding="utf-8")
(run.run_dir / "report.pdf").write_bytes(build_pdf(trace.model_dump()))
run.state = "done"
except Exception as exc: # noqa: BLE001 - the API must answer, not die
run.state = "error"
run.error = "".join(
traceback.format_exception_only(type(exc), exc)).strip()
run.stage = "error"
# ---------------------------------------------------------------------------
# Endpoints
# ---------------------------------------------------------------------------
@app.get("/api/health")
def api_health() -> dict:
"""Connection state for the front end's status widget."""
from models.serving.factory import get_backend
mode = os.environ.get("MODEL_BACKEND", "local").lower()
info: dict[str, Any] = {"mode": mode, "state": "unknown", "detail": ""}
if mode == "remote":
url = os.environ.get("SATQUERY_REMOTE_URL", "").strip()
if not url:
info.update(state="not_configured",
detail="SATQUERY_REMOTE_URL is not set")
else:
try:
health = get_backend().health()
if health.get("reachable"):
remote = health.get("remote") or {}
info.update(state="connected", remote=remote,
detail=f"{url} — {remote.get('model_id', '?')} on "
f"{remote.get('device', '?')}")
else:
info.update(state="unreachable",
detail=str(health.get("error")
or "HTTP " + str(health.get("status_code"))))
except Exception as exc: # noqa: BLE001
info.update(state="unreachable",
detail=f"{type(exc).__name__}: {exc}")
elif mode == "stub":
info.update(state="stub", detail="stub backend — no weights loaded")
else:
# In-process model. "connected" has to mean "you reached a server that
# can answer you", because that is the only question the browser's chip
# is really asking. The old code reported state="local" here, which the
# front end painted amber as "local backend" -- so a user who pasted a
# perfectly good tunnel URL saw a warning chip and reasonably concluded
# the app had ignored the URL and was still talking to something on
# their own machine. MODEL_BACKEND=local is what both launcher scripts
# set, so that was every Colab and every own-GPU run: the green chip was
# unreachable on the documented happy path.
#
# health() is deliberately cheap -- LocalBackend.health() reports from
# describe() and never triggers a model load -- so this stays a probe.
try:
health = get_backend().health()
if health.get("torch") is None:
info.update(state="degraded",
detail="reached this server, but torch is not "
"installed here so it cannot run the model")
else:
device = (health.get("gpu")
or ("cuda" if health.get("cuda_available") else "cpu"))
adapted = bool(health.get("rs_adapted"))
info.update(
state="connected",
rs_adapted=adapted,
detail=f"in-process {health.get('model_id') or 'model'} on "
f"{device}"
+ ("" if adapted else " — no LoRA adapter attached, "
"answers will not be RS-adapted"))
except Exception as exc: # noqa: BLE001
info.update(state="degraded",
detail=f"reached this server, but it cannot report on "
f"its model: {type(exc).__name__}: {exc}")
info["runs_active"] = sum(1 for r in _runs.values() if r.state == "running")
return info
@app.get("/api/meta")
def api_meta() -> dict:
"""Sample queries + glossary, so UI and API agree by construction."""
return {
"samples": [
{"index": i, "query": q, "need": n, "hint": h, "roles": list(r)}
for i, (q, n, h, r) in enumerate(SAMPLE_QUERIES)],
"glossary": [{"term": t, "definition": d} for t, d in GLOSSARY],
# Bilingual UI: Hindi variants aligned by index. The model's answers
# stay in English; only the interface is translated.
"samples_hi": [
{"index": i, "query": q, "need": n, "hint": h, "roles": list(r)}
for i, (q, n, h, r) in enumerate(SAMPLE_QUERIES_HI)],
"glossary_hi": [{"term": t, "definition": d} for t, d in GLOSSARY_HI],
}
@app.get("/api/places")
def api_places(q: str = "") -> dict:
"""Place-name candidates for the location search box."""
try:
return {"places": locmod.search_places(q)}
except LocationError as exc:
raise HTTPException(status_code=502, detail=str(exc)) from exc
@app.post("/api/location")
async def api_location(place: str = Form(...)) -> dict:
"""Fetch fresh imagery for a chosen place: one scene per timeline year
plus the latest. Runs the same STAC pipeline as the demo assets."""
try:
hit = json.loads(place)
except json.JSONDecodeError as exc:
raise HTTPException(status_code=400,
detail="place must be a JSON place hit from /api/places") from exc
name = str(hit.get("name") or "").strip()
if not name:
raise HTTPException(status_code=400, detail="place name is empty")
bbox = locmod.bbox_for(hit)
# A first-time fetch pulls five scenes off the STAC catalogue and takes
# 2-3 minutes -- well past the ~100 s a cloudflared tunnel will hold a
# request open, which surfaced as a 502 with no explanation. Run it as a
# job and let the client poll, exactly as queries already do. A cached
# place still answers immediately, so the common path is unchanged.
cached = locmod.cached_timeline(bbox, name)
if cached is not None:
return {"state": "done", "result": cached}
job_id = uuid.uuid4().hex[:12]
job = _LocationJob(job_id, bbox, name)
_location_jobs[job_id] = job
threading.Thread(target=job.run, daemon=True).start()
return {"state": "running", "job": job_id,
"poll": f"/api/location/job/{job_id}"}
@app.get("/api/location/job/{job_id}")
def api_location_job(job_id: str) -> dict:
"""Poll a location fetch started by POST /api/location."""
job = _location_jobs.get(job_id)
if job is None:
raise HTTPException(status_code=404, detail="no such location job")
if job.state == "running":
return {"state": "running", "elapsed_ms": job.elapsed_ms,
"stage": job.stage}
if job.state == "error":
return {"state": "error", "error": job.error}
return {"state": "done", "result": job.result}
@app.get("/api/location/{loc_id}/preview/{fname}")
def api_location_preview(loc_id: str, fname: str) -> FileResponse:
"""PNG preview of a fetched scene (validated inside the location store)."""
stem, _, suffix = fname.partition(".")
if not loc_id.replace("-", "").replace("_", "").isalnum() \
or not stem.isalnum() or suffix.lower() != "png":
raise HTTPException(status_code=400, detail="bad location preview path")
p = (locmod.LOCATIONS_ROOT / loc_id / fname).resolve()
if not str(p).startswith(str(locmod.LOCATIONS_ROOT.resolve())) or not p.exists():
raise HTTPException(status_code=404, detail="no such preview")
return FileResponse(p, media_type="image/png",
headers={"Cache-Control": "public, max-age=86400"})
def resolve_images(files: list[UploadFile], demo_roles: str,
image_refs: str) -> list[str]:
"""The one place image sources are turned into server paths.
Priority: uploaded files, then demo roles, then refs to scenes stored by
the live-location fetch. Refs are validated to stay inside the location
store, so a caller cannot point the agent at an arbitrary server path.
"""
if files:
tmp = RUNS_ROOT / "uploads" / uuid.uuid4().hex[:8]
return save_uploads(files, tmp)
if demo_roles:
return demo_role_paths(json.loads(demo_roles))
if image_refs:
try:
return locmod.resolve_refs(json.loads(image_refs))
except LocationError as exc:
raise HTTPException(status_code=404, detail=str(exc)) from exc
return []
@app.post("/api/inspect")
async def api_inspect(
query: str = Form(""),
files: list[UploadFile] = File(default=[]),
demo_roles: str = Form(""),
image_refs: str = Form(""),
) -> dict:
"""Compatibility check before paying for an inference: what the files are
and whether this query looks routable. Cheap; never touches the model."""
tmp = RUNS_ROOT / "inspect" / uuid.uuid4().hex[:8]
files_to_clean = bool(files)
try:
if files:
paths = save_uploads(files, tmp)
elif demo_roles:
paths = demo_role_paths(json.loads(demo_roles))
elif image_refs:
paths = resolve_images(None, "", image_refs)
else:
return {"has_images": False}
peek = validate(paths, TaskType.UNSUPPORTED)
cls = classify(query or "", n_images=len(paths),
modalities=peek.modalities)
recs = [rec.model_dump() for rec in peek.images]
return {
"has_images": True,
"metadata": recs,
"modalities": list(peek.modalities),
"pair_checks": peek.pair_checks,
"will_be_rejected": not peek.ok,
"error_code": peek.error_code,
"error_message": peek.error_message,
"routing": {"task": cls.task.value, "confidence": cls.confidence,
"method": cls.method},
}
finally:
if files_to_clean:
shutil.rmtree(tmp, ignore_errors=True)
@app.post("/api/query")
async def api_query(
query: str = Form(...),
files: list[UploadFile] = File(default=[]),
demo_roles: str = Form(""),
image_refs: str = Form(""),
) -> dict:
"""Start a run. Returns immediately with a run_id; poll /api/run/{id}."""
_prune_runs()
if not query.strip():
raise HTTPException(status_code=400, detail="query is empty")
paths = resolve_images(files, demo_roles, image_refs)
if not paths:
raise HTTPException(
status_code=400,
detail="no images: upload files, pick demo roles, or fetch a location")
if len(paths) > MAX_IMAGES:
raise HTTPException(
status_code=400,
detail=f"at most {MAX_IMAGES} images per run; got {len(paths)}")
run_id = uuid.uuid4().hex[:12]
run = _Run(run_id, query.strip(), paths)
_runs[run_id] = run
threading.Thread(target=_run_query_job, args=(run,), daemon=True,
name=f"satquery-run-{run_id}").start()
return {"run_id": run_id, "poll": f"/api/run/{run_id}"}
@app.get("/api/run/{run_id}")
def api_run(run_id: str) -> dict:
run = _runs.get(run_id)
if run is None:
raise HTTPException(status_code=404, detail="no such run")
if run.state == "running":
return {"state": "running", "stage": run.stage,
"stages_done": run.stage_history[:-1],
"elapsed_ms": round((time.time() - run.created) * 1000)}
if run.state == "error":
return {"state": "error", "error": run.error}
evidence = [{**e, "url": f"/api/run/{run_id}/evidence/{e['index']}"}
for e in run.evidence]
return {
"state": "done",
"run_id": run_id,
"status": (run.trace or {}).get("status"),
"trace": run.trace,
"interpretation": run.interpretation,
"evidence": evidence,
"downloads": {
"trace_json": f"/api/run/{run_id}/trace.json",
"report_pdf": f"/api/run/{run_id}/report.pdf",
},
"elapsed_ms": round((time.time() - run.created) * 1000),
}
@app.get("/api/run/{run_id}/evidence/{index}")
def api_evidence(run_id: str, index: int) -> FileResponse:
run = _runs.get(run_id)
if run is None or run.state != "done":
raise HTTPException(status_code=404, detail="no such run")
if index < 0 or index >= len(run.evidence):
raise HTTPException(status_code=404, detail="no such evidence image")
return FileResponse(run.evidence[index]["path"], media_type="image/png",
headers={"Cache-Control": "public, max-age=3600"})
@app.get("/api/run/{run_id}/trace.json")
def api_trace_json(run_id: str) -> FileResponse:
run = _runs.get(run_id)
if run is None or run.state != "done":
raise HTTPException(status_code=404, detail="no such run")
return FileResponse(run.run_dir / "trace.json", media_type="application/json",
filename="trace.json")
@app.get("/api/run/{run_id}/report.pdf")
def api_report_pdf(run_id: str) -> FileResponse:
run = _runs.get(run_id)
if run is None or run.state != "done":
raise HTTPException(status_code=404, detail="no such run")
return FileResponse(run.run_dir / "report.pdf", media_type="application/pdf",
filename="report.pdf")
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("APP_PORT", "8000")))