""" main.py - ACRA FastAPI Backend Adaptive Color Re-Encoding System Endpoints --------- POST /process Upload image → run CVD pipeline → return job GET /jobs List all active jobs for authenticated user GET /jobs/{job_id} Full job detail with metrics + boxes GET /jobs/{job_id}/metrics One job's metrics as CSV or JSON GET /metrics/export Every job and test run, including fails and no-conflict images DELETE /jobs/{job_id} Delete job and its images GET /health Server / model health check POST /test-runs Store diagnostic metrics; images expire after 24h GET /test-runs List all test runs for user GET /test-runs/analytics Aggregate stats + per-metric distributions DELETE /test-runs/{run_id} Delete one test run DELETE /test-runs Clear all test runs for user Run locally: cd code uvicorn main:app --reload --port 8000 """ from __future__ import annotations import asyncio import io import os import sys import threading import time import uuid # NumPy (OpenBLAS) and ONNX Runtime each ship an OpenMP runtime. On Windows the # second native call (the second image) can access-violate (0xC0000005) and # kill the process. The browser then sits until its timeout. These must be set # before either library loads. os.environ.setdefault("KMP_DUPLICATE_LIB_OK", "TRUE") os.environ.setdefault("OMP_NUM_THREADS", "1") os.environ.setdefault("OPENBLAS_NUM_THREADS", "1") os.environ.setdefault("MKL_NUM_THREADS", "1") from concurrent.futures import ThreadPoolExecutor from contextlib import asynccontextmanager from datetime import datetime, timedelta, timezone from pathlib import Path from typing import Any, Dict, List, Optional import httpx import numpy as np from PIL import Image, ImageOps # Teach Pillow to open HEIC/HEIF. Pillow has no built-in decoder for it, so # without this registration Image.open() raises UnidentifiedImageError on every # photo straight off an iPhone -- after the upload had already been accepted. # Kept non-fatal: a missing optional wheel should degrade one format, not stop # the whole service from booting. try: import pillow_heif pillow_heif.register_heif_opener() HEIF_OK = True except Exception as _heif_exc: # pragma: no cover - depends on the wheel HEIF_OK = False print(f"[ACRA] HEIC/HEIF support unavailable: {_heif_exc}") from dotenv import load_dotenv load_dotenv(Path(__file__).parent / ".env") load_dotenv(Path(__file__).parent.parent / ".env") from fastapi import FastAPI, File, Form, HTTPException, Query, Request, UploadFile from fastapi.responses import Response from fastapi.middleware.cors import CORSMiddleware BASE_DIR = Path(__file__).parent sys.path.insert(0, str(BASE_DIR)) from pipeline.segmentation import resolve_seg_model, _load_model as _load_seg_model import local_store SEG_MODEL_PATH: Optional[str] = resolve_seg_model() # ── Config ───────────────────────────────────────────────────────────────────── # Default to OFF. A missing environment variable must never be the thing that # disables authentication: anyone running this code without setting SKIP_AUTH # would otherwise get an API that accepts every request. Local development sets # SKIP_AUTH=true explicitly. SKIP_AUTH = os.getenv("SKIP_AUTH", "false").lower() == "true" SUPABASE_URL = os.getenv("SUPABASE_URL", "") SUPABASE_JWT_SECRET = os.getenv("SUPABASE_JWT_SECRET", "") SUPABASE_SERVICE_KEY = os.getenv("SUPABASE_SERVICE_ROLE_KEY", "") STORAGE_BUCKET = os.getenv("STORAGE_BUCKET", "acra-images") BASE_URL = os.getenv("BASE_URL", "http://localhost:8000").rstrip("/") DATA_DIR = Path(os.getenv("DATA_DIR") or BASE_DIR) JOB_EXPIRY_HOURS = 24 PURGE_INTERVAL_S = min(60, max(1, int(os.getenv("PURGE_INTERVAL_SECONDS", "60")))) CORS_ORIGINS = [ o.strip() for o in os.getenv( "CORS_ORIGINS", "http://localhost:5173,http://localhost:3000", ).split(",") if o.strip() ] # Security: a browser forbids allow-credentials with a wildcard origin, so the # old live config set CORS_ORIGINS="*" which FastAPI turns into "reflect any # origin" -- strictly worse, because it lets ANY site make authenticated calls # as a logged-in user. Refuse to run in that shape. If someone really wants an # open, credential-less API they must set ALLOW_CREDENTIALS=false explicitly. ALLOW_CREDENTIALS = os.getenv("ALLOW_CREDENTIALS", "true").lower() == "true" if "*" in CORS_ORIGINS and ALLOW_CREDENTIALS: raise RuntimeError( "CORS_ORIGINS='*' with credentials enabled lets any website call this " "API as a logged-in user. Set CORS_ORIGINS to your real frontend " "origin(s), or set ALLOW_CREDENTIALS=false for a public, cookie-less API." ) # Hide interactive API docs in production -- they map the whole attack surface # for free. On by default only when EXPOSE_DOCS=true. EXPOSE_DOCS = os.getenv("EXPOSE_DOCS", "false").lower() == "true" MAX_IMAGE_BYTES = 10 * 1024 * 1024 ALLOWED_MIMES = { "image/jpeg", "image/png", "image/webp", "image/gif", "image/bmp", "image/tiff", "image/avif", "image/heic", "image/heif", } # The browser fills in a file's MIME type from the OS table, and Windows has no # entry for .heic -- so an iPhone photo arrives as "" or application/octet-stream # and a MIME-only check rejects a format that is in the list above. Fall back to # the filename when the type is missing or generic. ALLOWED_UPLOAD_EXTS = { ".jpg", ".jpeg", ".jfif", ".png", ".webp", ".gif", ".bmp", ".dib", ".tif", ".tiff", ".avif", ".heic", ".heif", } _VAGUE_MIMES = {"", "application/octet-stream", "binary/octet-stream"} def _is_allowed_upload(upload) -> bool: ctype = (getattr(upload, "content_type", "") or "").split(";")[0].strip().lower() if ctype in ALLOWED_MIMES: return True if ctype and ctype not in _VAGUE_MIMES: return False # a real, specific type that we do not accept name = (getattr(upload, "filename", "") or "").lower() return Path(name).suffix in ALLOWED_UPLOAD_EXTS # Local SQLite + static/ when Supabase is not configured (default for local dev). USE_LOCAL = not (SUPABASE_URL and SUPABASE_SERVICE_KEY) STATIC_DIR: Path DB_PATH: Path if USE_LOCAL: STATIC_DIR, DB_PATH = local_store.init_paths(DATA_DIR) print(f"[ACRA] Local storage mode - db={DB_PATH} static={STATIC_DIR}") else: STATIC_DIR = DATA_DIR / "static" DB_PATH = DATA_DIR / "jobs.db" print("[ACRA] Supabase storage mode") # ── Thread pool ──────────────────────────────────────────────────────────────── _executor = ThreadPoolExecutor(max_workers=2) # ── YOLO model cache ─────────────────────────────────────────────────────────── _yolo_model = None _model_loaded = False _startup_time = time.time() def _load_yolo() -> None: _ensure_yolo_loaded() def _ensure_yolo_loaded() -> bool: global _yolo_model, _model_loaded, SEG_MODEL_PATH if _model_loaded and _yolo_model is not None and SEG_MODEL_PATH: return True SEG_MODEL_PATH = resolve_seg_model() if not SEG_MODEL_PATH: print("[ACRA] No YOLO model found - place acra_medium_v7_best.onnx in code/ or set SEG_MODEL_PATH") _model_loaded = False return False try: _yolo_model = _load_seg_model(SEG_MODEL_PATH) _model_loaded = True print(f"[ACRA] Model loaded: {SEG_MODEL_PATH}") return True except Exception as exc: print(f"[ACRA] Warning: could not load model: {exc}") _model_loaded = False return False # ── Supabase client ──────────────────────────────────────────────────────────── _sb_client = None def _get_sb(): global _sb_client if _sb_client is not None: return _sb_client if not SUPABASE_URL or not SUPABASE_SERVICE_KEY: raise RuntimeError( "SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY must be configured as environment variables" ) from supabase import create_client _sb_client = create_client(SUPABASE_URL, SUPABASE_SERVICE_KEY) return _sb_client def _ensure_private_storage() -> None: if USE_LOCAL: return storage = _get_sb().storage bucket = storage.get_bucket(STORAGE_BUCKET) if bucket.public: storage.update_bucket(STORAGE_BUCKET, {"public": False}) if storage.get_bucket(STORAGE_BUCKET).public: raise RuntimeError("The image storage bucket must be private.") # ── Image helpers ────────────────────────────────────────────────────────────── def _img_to_jpeg_bytes(img_np: np.ndarray, quality: int = 92) -> bytes: buf = io.BytesIO() Image.fromarray(img_np).save(buf, format="JPEG", quality=quality) return buf.getvalue() # Longest side of the small preview saved beside each result. Storage cards used # to load the full corrected image to fill a ~300 px tile: measured 289-499 KB # per card against 38-55 KB for a 480 px thumbnail, so a 12-card page pulled # 4-6 MB it did not need. 480 still looks sharp on a 2x (retina) screen. THUMB_MAX_SIDE = 480 def _thumbnail(img_np: np.ndarray) -> np.ndarray: im = Image.fromarray(img_np) im.thumbnail((THUMB_MAX_SIDE, THUMB_MAX_SIDE)) return np.asarray(im) def _thumb_url(corrected_url: Optional[str]) -> Optional[str]: """Where the thumbnail lives, derived from the corrected image's URL. Derived, not stored, so no database column is needed. Jobs saved before thumbnails existed have no file at this address; the frontend falls back to the full image when the thumbnail fails to load. """ if not corrected_url or "/corrected.jpg" not in corrected_url: return None return corrected_url.replace("/corrected.jpg", "/thumb.jpg") def _sb_retry(fn, *args, **kwargs): """Retry a Supabase call once if the connection was already dead. _sb_client (_get_sb) is created ONCE and its underlying httpx connections are kept alive and reused for the server's entire lifetime. Supabase can close an idle one from its side at any moment; the next request to reuse it fails before a single byte reaches Supabase, as httpx.RemoteProtocolError("Server disconnected without sending a response") -- exactly what a batch job reported. It is not a real failure of that request: httpx drops the dead connection and opens a fresh one on retry, and a batch is exactly when this bites, since several uploads fire back to back and one lands on a connection that went stale between jobs. """ try: return fn(*args, **kwargs) except httpx.TransportError: return fn(*args, **kwargs) def _upload_image(img_np: np.ndarray, storage_path: str, quality: int = 92) -> str: data = _img_to_jpeg_bytes(img_np, quality) if USE_LOCAL: local_store.save_image(STATIC_DIR, storage_path, data) return f"/images/{storage_path}" sb = _get_sb() _sb_retry( sb.storage.from_(STORAGE_BUCKET).upload, path=storage_path, file=data, file_options={"content-type": "image/jpeg", "upsert": "true"}, ) return f"/images/{storage_path}" def _delete_images(prefix: str) -> None: if USE_LOCAL: local_store.delete_images(STATIC_DIR, prefix) return _get_sb().storage.from_(STORAGE_BUCKET).remove( [f"{prefix}/original.jpg", f"{prefix}/corrected.jpg", f"{prefix}/thumb.jpg"] ) def _insert_row(table: str, row: dict) -> None: if USE_LOCAL: if table == "jobs": local_store.insert_job(DB_PATH, row) elif table == "test_runs": local_store.insert_test_run(DB_PATH, row) else: raise ValueError(f"Unknown table: {table}") return _sb_retry(_get_sb().table(table).insert(row).execute) async def _to_thread(fn, *args): loop = asyncio.get_running_loop() return await loop.run_in_executor(_executor, fn, *args) async def _persist_images_and_row( prefix: str, orig: np.ndarray, corr: np.ndarray, table: str, row: dict, ) -> dict: """Upload original, corrected and a thumbnail in parallel, then insert. Compensating delete on failure. The thumbnail's URL is not stored -- see _thumb_url -- so it adds no column and no migration. """ orig_path = f"{prefix}/original.jpg" corr_path = f"{prefix}/corrected.jpg" try: orig_url, corrected_url, _ = await asyncio.gather( _to_thread(_upload_image, orig, orig_path), _to_thread(_upload_image, corr, corr_path), _to_thread(_upload_image, _thumbnail(corr), f"{prefix}/thumb.jpg", 80), ) row = {**row, "original_url": orig_url, "corrected_url": corrected_url} await _to_thread(_insert_row, table, row) return row except Exception: await _to_thread(_delete_images, prefix) raise def _page_bounds(limit: int, offset: int, default: int, maximum: int) -> tuple: lim = default if limit is None else int(limit) off = 0 if offset is None else int(offset) return max(1, min(maximum, lim)), max(0, off) # ── Lifespan ─────────────────────────────────────────────────────────────────── async def _purge_loop() -> None: while True: try: await _to_thread(_purge_expired) except asyncio.CancelledError: break except Exception as exc: print(f"[ACRA] Purge error: {exc}") try: await asyncio.sleep(PURGE_INTERVAL_S) except asyncio.CancelledError: break @asynccontextmanager async def lifespan(app: FastAPI): loop = asyncio.get_running_loop() await loop.run_in_executor(_executor, _ensure_private_storage) await loop.run_in_executor(_executor, _load_yolo) purge_task = asyncio.create_task(_purge_loop()) try: yield finally: purge_task.cancel() try: await purge_task except asyncio.CancelledError: pass _executor.shutdown(wait=False, cancel_futures=True) # ── App ──────────────────────────────────────────────────────────────────────── app = FastAPI( title="ACRA", version="1.0.0", lifespan=lifespan, docs_url="/docs" if EXPOSE_DOCS else None, redoc_url="/redoc" if EXPOSE_DOCS else None, openapi_url="/openapi.json" if EXPOSE_DOCS else None, ) app.add_middleware( CORSMiddleware, allow_origins=CORS_ORIGINS, allow_credentials=ALLOW_CREDENTIALS, allow_methods=["GET", "POST", "DELETE", "OPTIONS"], allow_headers=["Authorization", "Content-Type"], ) # ── Security headers ──────────────────────────────────────────────────────────── # Sent on every response. These tell the browser to stop guessing MIME types, # refuse to render the API inside an iframe (clickjacking), and not leak the # full URL in the Referer header. HSTS forces HTTPS for two years. @app.middleware("http") async def _security_headers(request: Request, call_next): resp = await call_next(request) resp.headers["X-Content-Type-Options"] = "nosniff" resp.headers["X-Frame-Options"] = "DENY" resp.headers["Referrer-Policy"] = "strict-origin-when-cross-origin" resp.headers["Strict-Transport-Security"] = "max-age=63072000; includeSubDomains" # no-store is right for JSON holding a user's data, but on generated images # it forbids the browser cache, so every view re-downloads the file and # re-spends rate-limit budget. Job images are already unguessable URLs, so # let the BROWSER keep them ("private") while shared proxies still may not. if request.url.path.startswith("/static/"): resp.headers["Cache-Control"] = "private, max-age=300" else: resp.headers["Cache-Control"] = "no-store" return resp # ── Rate limiting ─────────────────────────────────────────────────────────────── # A single logged-in account should not be able to fire hundreds of inference # jobs a minute -- each one burns CPU and, on password/email paths, project # quota. This is a plain in-process sliding window keyed by client IP. # ponytail: per-replica counter. HF Spaces can run more than one replica, so the # real global limit is (this number x replica count). Good enough to stop casual # abuse; swap for Redis if a determined attacker matters. import time as _time from collections import defaultdict, deque # 240, not 60: the results page polls job status about once a second and pulls # several panels per job, so a 60 budget locked out ordinary use. The point of # the limit is to stop someone queueing hundreds of INFERENCE jobs a minute, # which is the expensive path -- not to ration normal page loads. RATE_MAX = int(os.getenv("RATE_LIMIT_PER_MIN", "240")) # requests RATE_WINDOW_S = 60 _hits: dict[str, deque] = defaultdict(deque) _RATE_EXEMPT = {"/", "/health"} # Serving an already-generated image is a cheap disk read, not model compute. # Counting them was what broke image viewing: one results page can pull dozens # of files and trip the limiter before the user has done anything unusual. _RATE_EXEMPT_PREFIXES = ("/static/",) @app.middleware("http") async def _rate_limit(request: Request, call_next): if (request.url.path in _RATE_EXEMPT or request.url.path.startswith(_RATE_EXEMPT_PREFIXES) or request.method == "OPTIONS"): return await call_next(request) ip = (request.headers.get("x-forwarded-for", "").split(",")[0].strip() or (request.client.host if request.client else "unknown")) now = _time.monotonic() dq = _hits[ip] while dq and dq[0] < now - RATE_WINDOW_S: dq.popleft() if len(dq) >= RATE_MAX: from fastapi.responses import JSONResponse return JSONResponse( {"detail": "Too many requests. Slow down and try again shortly."}, status_code=429, headers={"Retry-After": str(RATE_WINDOW_S)}, ) dq.append(now) return await call_next(request) # ── Auth ─────────────────────────────────────────────────────────────────────── def _extract_user_id(request: Request) -> str: auth = request.headers.get("Authorization", "") token = auth.removeprefix("Bearer ").strip() if SKIP_AUTH: if token.startswith("mock-token-"): return "local-dev-user" if token: # Derive a stable user id from the JWT sub claim without full verification try: import base64, json as _json payload_b64 = token.split(".")[1] payload_b64 += "=" * (-len(payload_b64) % 4) sub = _json.loads(base64.urlsafe_b64decode(payload_b64)).get("sub", "") if sub: return sub except Exception: pass return "local-dev-user" if not token: raise HTTPException(status_code=401, detail="Missing authorization token") try: import jwt as pyjwt from jwt import PyJWKClient if SUPABASE_URL: try: jwks_client = PyJWKClient(f"{SUPABASE_URL}/auth/v1/.well-known/jwks.json") signing_key = jwks_client.get_signing_key_from_jwt(token) # Only the asymmetric algorithms here. Accepting HS256 alongside # a key fetched from JWKS invites algorithm confusion: an # attacker signs a token with HS256 using the *public* key as # the shared secret. PyJWT blocks that combination, but the # safe list is not something to rely on a library to enforce. payload = pyjwt.decode( token, signing_key.key, algorithms=["ES256", "RS256"], options={"verify_aud": False}, ) return payload.get("sub", "unknown") except Exception: pass if SUPABASE_JWT_SECRET: payload = pyjwt.decode( token, SUPABASE_JWT_SECRET, algorithms=["HS256"], options={"verify_aud": False}, ) return payload.get("sub", "unknown") raise HTTPException(status_code=401, detail="No JWT verification method configured") except HTTPException: raise except Exception: raise HTTPException(status_code=401, detail="Invalid or expired token") # ── Class mapping ────────────────────────────────────────────────────────────── def _map_class(class_name: str) -> str: KNOWN = {"roi-color", "roi-object", "roi-text", "roi-symbol", "exclude-person"} canonical = class_name.lower().strip().replace("_", "-").replace(" ", "-") if canonical in KNOWN: return canonical name = class_name.lower() if any(k in name for k in ("person", "human", "face", "people")): return "exclude-person" if any(k in name for k in ("symbol", "icon", "logo", "mark", "check", "sign")): return "roi-symbol" if any(k in name for k in ("color", "colour", "swatch", "palette")): return "roi-color" if any(k in name for k in ("text", "word", "letter", "label")): return "roi-text" return "roi-object" # ── Pipeline runner (blocking - runs in thread pool) ────────────────────────── # Native pipeline (OpenBLAS + ONNX) is not safe to run on two images at once. _pipeline_lock = threading.Lock() def _run_pipeline_sync( img_np: np.ndarray, cvd_type: str, severity: float, conf_threshold: float, use_segmentation: bool = True, seg_soft: float = 3.5, n_clusters: Optional[int] = None, seg_clusters_per_roi: Optional[int] = None, ) -> tuple: from pipeline import run_full_pipeline with _pipeline_lock: return _run_pipeline_locked( img_np, cvd_type, severity, conf_threshold, use_segmentation, seg_soft, n_clusters, seg_clusters_per_roi, run_full_pipeline, ) def _run_pipeline_locked( img_np, cvd_type, severity, conf_threshold, use_segmentation, seg_soft, n_clusters, seg_clusters_per_roi, run_full_pipeline, ): seg_ready = use_segmentation and _ensure_yolo_loaded() corrected_uint8, raw_metrics = run_full_pipeline( img_np, severity, cvd_type, n_clusters=n_clusters, use_segmentation=seg_ready, seg_model=SEG_MODEL_PATH, seg_conf=conf_threshold, seg_soft=seg_soft, seg_clusters_per_roi=seg_clusters_per_roi, max_proc_pixels=1_500_000, ) timings = raw_metrics.get("_stage_timings") if timings: print(f"[ACRA] stage timings (s): {timings}") boxes: List[Dict] = [ {**box, "class": _map_class(box.get("class", ""))} for box in (raw_metrics.get("yolo_boxes") or []) ] metrics = { "delta_e_improvement": float(raw_metrics.get("de_improvement", 0.0)), "de_before_mean": float(raw_metrics.get("de_before_mean", 0.0)), "de_after_mean": float(raw_metrics.get("de_after_mean", 0.0)), "conflict_resolution_rate": float(raw_metrics.get("conflict_resolution_rate", 0.0)), "naturalness_preservation": float(raw_metrics.get("naturalness_preservation", 0.0)), "boxes_detected": len(boxes), "conflicts_found": int(raw_metrics.get("n_conflicts_total", 0)), "auto_clusters": int(raw_metrics.get("auto_clusters", 0)), "inference_ms": float(raw_metrics.get("inference_ms", 0.0)), "segmentation_active": seg_ready, "seg_class_names": raw_metrics.get("seg_class_names"), "already_accessible": bool(raw_metrics.get("already_accessible", False)), "pass_de_improvement": bool(raw_metrics.get("pass_de_improvement", False)), "pass_resolution_rate": bool(raw_metrics.get("pass_resolution_rate", False)), "pass_naturalness": bool(raw_metrics.get("pass_naturalness", False)), "conflict_diagnostics": raw_metrics.get("conflict_diagnostics", {}), } return corrected_uint8, metrics, boxes # ── Upload validation ────────────────────────────────────────────────────────── async def _validate_upload( image: UploadFile, cvd_type: str, severity: float, conf_threshold: float, seg_soft: float, use_segmentation: int, n_clusters: Optional[int], seg_clusters_per_roi: Optional[int], max_dim: Optional[int] = None, ) -> tuple: if not _is_allowed_upload(image): raise HTTPException(400, detail="Unsupported image format. Accepted: JPEG, PNG, WebP, GIF, BMP, TIFF, AVIF, HEIC.") raw_bytes = await image.read() if len(raw_bytes) > MAX_IMAGE_BYTES: raise HTTPException(400, detail="File size must be under 10 MB.") if cvd_type not in ("protan", "deutan"): raise HTTPException(400, detail="cvd_type must be 'protan' or 'deutan'.") params = { "severity": max(0.0, min(1.0, float(severity))), "conf_threshold": max(0.1, min(0.9, float(conf_threshold))), "seg_soft": max(0.0, min(8.0, float(seg_soft))), "use_seg_bool": bool(use_segmentation), "n_clusters": max(2, min(100, int(n_clusters))) if n_clusters is not None else None, "seg_clusters_per_roi": max(2, min(8, int(seg_clusters_per_roi))) if seg_clusters_per_roi is not None else None, } try: pil_img = Image.open(io.BytesIO(raw_bytes)) # Phone cameras store the photo in the sensor's native orientation and # add an EXIF tag saying how to rotate it. Without this the detector # sees every portrait photo lying on its side. Must run BEFORE convert() # -- convert() drops the EXIF block along with the tag. pil_img = ImageOps.exif_transpose(pil_img) pil_img = pil_img.convert("RGB") if max_dim is not None and max(pil_img.size) > max_dim: pil_img.thumbnail((max_dim, max_dim), Image.Resampling.LANCZOS) img_np = np.array(pil_img, dtype=np.uint8) except Exception: raise HTTPException(400, detail="Could not decode image file.") return img_np, params # ── Response serializers ─────────────────────────────────────────────────────── def _image_deadline(row: dict) -> datetime: deadline = datetime.fromisoformat(row["created_at"]) + timedelta(hours=24) if row.get("expires_at"): deadline = min(deadline, datetime.fromisoformat(row["expires_at"])) return deadline def _image_url(row: dict, collection: str, filename: str) -> Optional[str]: if _image_deadline(row) <= datetime.now(timezone.utc): return None identifier = row["job_id"] if collection == "jobs" else row["run_id"] return f"/images/{collection}/{identifier}/{filename}" def _job_to_response(row: dict) -> Dict[str, Any]: return { "job_id": row["job_id"], "cvd_type": row["cvd_type"], "severity": row["severity"], "conf_threshold": row["conf_threshold"], "use_segmentation": bool(row.get("use_segmentation", True)), "seg_soft": row.get("seg_soft", 3.5), "n_clusters": row.get("n_clusters"), "seg_clusters_per_roi": row.get("seg_clusters_per_roi", 3), "created_at": row["created_at"], "expires_at": row["expires_at"], "original_url": _image_url(row, "jobs", "original.jpg"), "corrected_url": _image_url(row, "jobs", "corrected.jpg"), "thumb_url": _image_url(row, "jobs", "thumb.jpg"), "metrics": row["metrics"], "boxes": row["boxes"], } def _run_to_response(row: dict) -> Dict[str, Any]: return { "run_id": row["run_id"], "filename": row["filename"], "cvd_type": row["cvd_type"], "severity": row["severity"], "conf_threshold": row["conf_threshold"], "use_segmentation": bool(row.get("use_segmentation", True)), "seg_soft": row.get("seg_soft", 3.5), "n_clusters": row.get("n_clusters"), "seg_clusters_per_roi": row.get("seg_clusters_per_roi", 3), "created_at": row["created_at"], "original_url": _image_url(row, "test-runs", "original.jpg"), "corrected_url": _image_url(row, "test-runs", "corrected.jpg"), "metrics": row["metrics"], "boxes": row["boxes"], } # ── Metrics export ───────────────────────────────────────────────────────────── def _export_body(rows: List[dict], fmt: str) -> Response: import metrics_export kind = (fmt or "csv").lower() if kind not in ("csv", "json"): raise HTTPException(400, detail="format must be 'csv' or 'json'.") if kind == "json": body = metrics_export.to_json(rows) media = "application/json" filename = "acra-metrics.json" else: body = metrics_export.to_csv(rows) media = "text/csv; charset=utf-8" filename = "acra-metrics.csv" return Response( content=body, media_type=media, headers={"Content-Disposition": f'attachment; filename="{filename}"'}, ) def _remote_user_rows(table: str, user_id: str, page_size: int = 200) -> List[dict]: rows: List[dict] = [] offset = 0 while True: result = ( _get_sb().table(table) .select("*") .eq("user_id", user_id) .order("created_at", desc=True) .order("job_id" if table == "jobs" else "run_id") .range(offset, offset + page_size - 1) .execute() ) batch = result.data or [] rows.extend(batch) if len(batch) < page_size: break offset += page_size return rows async def _metrics_export_rows(request: Request) -> List[dict]: import metrics_export user_id = _extract_user_id(request) now = datetime.now(timezone.utc).isoformat() if USE_LOCAL: jobs = await _to_thread(local_store.list_jobs, DB_PATH, user_id) runs = await _to_thread(local_store.list_all_test_runs, DB_PATH, user_id) else: jobs = await _to_thread(_remote_user_rows, "jobs", user_id) runs = await _to_thread(_remote_user_rows, "test_runs", user_id) rows = [ metrics_export.metric_row("job", job) for job in jobs if (job.get("expires_at") or "") > now ] rows.extend(metrics_export.metric_row("test_run", run) for run in runs) rows.sort(key=lambda row: row.get("created_at") or "", reverse=True) return rows # ── Routes ───────────────────────────────────────────────────────────────────── @app.get("/") def root(): return { "status": "ok", "service": "ACRA Backend", "health": "/health", "docs": "/docs", } @app.get('/device-engine', include_in_schema=False) def device_engine(request: Request): _extract_user_id(request) from device_engine import engine_response return engine_response(SEG_MODEL_PATH) @app.get("/health") def health(): return { "status": "ok", "model_loaded": _model_loaded, "model_path": SEG_MODEL_PATH, "segmentation_ready": bool(SEG_MODEL_PATH and Path(SEG_MODEL_PATH).is_file()), "uptime_seconds": round(time.time() - _startup_time, 1), } @app.post("/process") async def process_image( request: Request, image: UploadFile = File(...), cvd_type: str = Form(...), severity: float = Form(...), conf_threshold: float = Form(...), use_segmentation: int = Form(1), seg_soft: float = Form(3.5), n_clusters: Optional[int] = Form(None), seg_clusters_per_roi: Optional[int] = Form(None), ): user_id = _extract_user_id(request) img_np, params = await _validate_upload( image, cvd_type, severity, conf_threshold, seg_soft, use_segmentation, n_clusters, seg_clusters_per_roi, max_dim=1920, ) severity = params["severity"] conf_threshold = params["conf_threshold"] seg_soft = params["seg_soft"] use_seg_bool = params["use_seg_bool"] n_clusters = params["n_clusters"] seg_clusters_per_roi = params["seg_clusters_per_roi"] t0 = time.time() try: corrected_uint8, metrics, boxes = await _to_thread( _run_pipeline_sync, img_np, cvd_type, severity, conf_threshold, use_seg_bool, seg_soft, n_clusters, seg_clusters_per_roi, ) except Exception as exc: raise HTTPException(500, detail=f"Pipeline error: {exc}") metrics["inference_ms"] = round((time.time() - t0) * 1000, 1) job_id = str(uuid.uuid4()) now = datetime.now(timezone.utc) expires_at = now + timedelta(hours=JOB_EXPIRY_HOURS) row = { "job_id": job_id, "user_id": user_id, "cvd_type": cvd_type, "severity": severity, "conf_threshold": conf_threshold, "use_segmentation": use_seg_bool, "seg_soft": seg_soft, "n_clusters": n_clusters, "seg_clusters_per_roi": seg_clusters_per_roi if seg_clusters_per_roi is not None else 3, "created_at": now.isoformat(), "expires_at": expires_at.isoformat(), "metrics": metrics, "boxes": boxes, } try: row = await _persist_images_and_row(f"jobs/{job_id}", img_np, corrected_uint8, "jobs", row) except Exception as exc: raise HTTPException(500, detail=f"Failed to save job: {exc}") return _job_to_response(row) @app.get("/metrics/export") async def export_metrics(request: Request, format: str = Query("csv")): """Every stored image for this user. Failed pass flags and images with zero conflicts are included. Expired jobs are left out because their rows are already gone from the active list. """ rows = await _metrics_export_rows(request) return _export_body(rows, format) @app.get("/jobs") async def list_jobs(request: Request): user_id = _extract_user_id(request) # No cleanup here any more. _purge_expired used to run first on EVERY visit # to Storage -- a select plus a delete against Supabase, plus a storage # delete per expired job -- and the list waited on all of it before a # single card could render. _purge_loop already runs the same cleanup in # the background every PURGE_INTERVAL_S. Expired jobs are simply filtered # out of the query below, so the user still never sees one. now = datetime.now(timezone.utc).isoformat() if USE_LOCAL: rows = await _to_thread(local_store.list_jobs, DB_PATH, user_id) return [_job_to_response(r) for r in rows if r["expires_at"] > now] def _query(uid=user_id): return ( _get_sb().table("jobs") .select("*") .eq("user_id", uid) .gt("expires_at", now) .order("created_at", desc=True) .execute() ) result = await _to_thread(_query) return [_job_to_response(r) for r in result.data] @app.get("/jobs/{job_id}/metrics") async def export_job_metrics(job_id: str, request: Request, format: str = Query("csv")): user_id = _extract_user_id(request) if USE_LOCAL: row = await _to_thread(local_store.get_job, DB_PATH, job_id, user_id) else: def _query(jid=job_id, uid=user_id): return ( _get_sb().table("jobs") .select("*") .eq("job_id", jid) .eq("user_id", uid) .execute() ) result = await _to_thread(_query) row = result.data[0] if result.data else None if not row or (row.get("expires_at") or "") <= datetime.now(timezone.utc).isoformat(): raise HTTPException(404, detail="Job not found or has expired.") import metrics_export return _export_body([metrics_export.metric_row("job", row)], format) @app.get("/jobs/{job_id}") async def get_job(job_id: str, request: Request): user_id = _extract_user_id(request) if USE_LOCAL: row = await _to_thread(local_store.get_job, DB_PATH, job_id, user_id) if not row or _image_deadline(row) <= datetime.now(timezone.utc): raise HTTPException(404, detail="Job not found or has expired.") return _job_to_response(row) def _query(jid=job_id, uid=user_id): return ( _get_sb().table("jobs") .select("*") .eq("job_id", jid) .eq("user_id", uid) .execute() ) result = await _to_thread(_query) if not result.data or _image_deadline(result.data[0]) <= datetime.now(timezone.utc): raise HTTPException(404, detail="Job not found or has expired.") return _job_to_response(result.data[0]) @app.get("/images/{collection}/{record_id}/{filename}") async def get_private_image(collection: str, record_id: str, filename: str, request: Request): user_id = _extract_user_id(request) if collection not in {"jobs", "test-runs"} or filename not in {"original.jpg", "corrected.jpg", "thumb.jpg"}: raise HTTPException(404, detail="Image not found or has expired.") table = "jobs" if collection == "jobs" else "test_runs" key = "job_id" if collection == "jobs" else "run_id" if USE_LOCAL: lookup = local_store.get_job if table == "jobs" else local_store.get_test_run row = await _to_thread(lookup, DB_PATH, record_id, user_id) else: def lookup(): result = (_get_sb().table(table).select("*").eq(key, record_id) .eq("user_id", user_id).execute()) return result.data[0] if result.data else None row = await _to_thread(lookup) if not row or _image_deadline(row) <= datetime.now(timezone.utc): raise HTTPException(404, detail="Image not found or has expired.") # Derive the path from the owned record, never from a stored external URL. path = f"{collection}/{row[key]}/{filename}" try: if USE_LOCAL: data = await _to_thread((STATIC_DIR / path).read_bytes) else: data = await _to_thread(_get_sb().storage.from_(STORAGE_BUCKET).download, path) except FileNotFoundError: raise HTTPException(404, detail="Image not found or has expired.") except Exception: raise HTTPException(503, detail="Image storage is temporarily unavailable.") return Response(data, media_type="image/jpeg", headers={ "Cache-Control": "private, no-store", "Vary": "Authorization", }) @app.delete("/jobs/{job_id}") async def delete_job(job_id: str, request: Request): user_id = _extract_user_id(request) if USE_LOCAL: row = await _to_thread(local_store.get_job, DB_PATH, job_id, user_id) if not row: raise HTTPException(404, detail="Job not found.") await _to_thread(_delete_images, f"jobs/{job_id}") await _to_thread(local_store.delete_job, DB_PATH, job_id) return {"deleted": job_id} def _lookup(jid=job_id, uid=user_id): return ( _get_sb().table("jobs") .select("job_id") .eq("job_id", jid) .eq("user_id", uid) .execute() ) result = await _to_thread(_lookup) if not result.data: raise HTTPException(404, detail="Job not found.") def _delete(jid=job_id, uid=user_id): # The owner filter is repeated here deliberately. The lookup above # already refuses to continue for someone else's job, so this is belt # and braces -- but the backend talks to Supabase with the service-role # key, which carries BYPASSRLS and skips every row level security # policy. A delete statement with no owner filter therefore has NOTHING # behind it: any future caller reaching this line deletes whatever id # it was handed. Scope the statement itself, not just the path to it. _get_sb().table("jobs").delete().eq("job_id", jid).eq("user_id", uid).execute() await _to_thread(_delete_images, f"jobs/{job_id}") await _to_thread(_delete) return {"deleted": job_id} @app.delete("/account") async def delete_account(request: Request): """Erase everything belonging to the caller, then the login itself. The privacy policy promises erasure in writing, so this has to actually erase: the stored image FILES first, then the rows, then the auth user. Order matters -- delete the rows first and the job ids are gone, leaving orphaned images in the bucket that nothing points at and nobody will ever clean up. Deleting the auth user last means a failure part-way through leaves the account still usable and the request repeatable, rather than locking someone out of data that is still sitting there. """ user_id = _extract_user_id(request) if USE_LOCAL: for row in await _to_thread(local_store.list_jobs, DB_PATH, user_id): await _to_thread(_delete_images, f"jobs/{row['job_id']}") await _to_thread(local_store.delete_job, DB_PATH, row["job_id"]) for row in await _to_thread(local_store.list_all_test_runs, DB_PATH, user_id): await _to_thread(_delete_images, f"test-runs/{row['run_id']}") await _to_thread(local_store.clear_test_runs, DB_PATH, user_id) return {"deleted": True, "jobs": "all", "note": "local mode: no auth user to remove"} sb = _get_sb() def _list_jobs(uid=user_id): return sb.table("jobs").select("job_id").eq("user_id", uid).execute() jobs = (await _to_thread(_list_jobs)).data or [] for row in jobs: await _to_thread(_delete_images, f"jobs/{row['job_id']}") runs = await _to_thread(_remote_user_rows, "test_runs", user_id) for row in runs: await _to_thread(_delete_images, f"test-runs/{row['run_id']}") def _wipe_rows(uid=user_id): sb.table("jobs").delete().eq("user_id", uid).execute() sb.table("test_runs").delete().eq("user_id", uid).execute() await _to_thread(_wipe_rows) # Removing the auth user needs the service-role key, which this process # already holds. Without this the email stays registered and the person # cannot sign up again with it -- which is not deletion. def _drop_user(uid=user_id): sb.auth.admin.delete_user(uid) try: await _to_thread(_drop_user) except Exception as exc: print(f"[ACRA] Auth user delete failed for {user_id}: {exc}") raise HTTPException( 500, detail="Your images and records were deleted, but the login itself " "could not be removed. Please contact us so we can finish it.", ) return {"deleted": True, "jobs_removed": len(jobs)} # ── Test-runs ────────────────────────────────────────────────────────────────── @app.post("/test-runs") async def create_test_run( request: Request, image: UploadFile = File(...), cvd_type: str = Form(...), severity: float = Form(...), conf_threshold: float = Form(...), use_segmentation: int = Form(1), seg_soft: float = Form(3.5), n_clusters: Optional[int] = Form(None), seg_clusters_per_roi: Optional[int] = Form(None), ): user_id = _extract_user_id(request) filename = image.filename or "image.jpg" img_np, params = await _validate_upload( image, cvd_type, severity, conf_threshold, seg_soft, use_segmentation, n_clusters, seg_clusters_per_roi, ) severity = params["severity"] conf_threshold = params["conf_threshold"] seg_soft = params["seg_soft"] use_seg_bool = params["use_seg_bool"] n_clusters = params["n_clusters"] seg_clusters_per_roi = params["seg_clusters_per_roi"] t0 = time.time() try: corrected_uint8, metrics, boxes = await _to_thread( _run_pipeline_sync, img_np, cvd_type, severity, conf_threshold, use_seg_bool, seg_soft, n_clusters, seg_clusters_per_roi, ) except Exception as exc: raise HTTPException(500, detail=f"Pipeline error: {exc}") metrics["inference_ms"] = round((time.time() - t0) * 1000, 1) run_id = str(uuid.uuid4()) now = datetime.now(timezone.utc) row = { "run_id": run_id, "user_id": user_id, "filename": filename, "cvd_type": cvd_type, "severity": severity, "conf_threshold": conf_threshold, "use_segmentation": use_seg_bool, "seg_soft": seg_soft, "n_clusters": n_clusters, "seg_clusters_per_roi": seg_clusters_per_roi if seg_clusters_per_roi is not None else 3, "created_at": now.isoformat(), "metrics": metrics, "boxes": boxes, "de_improvement": float(metrics.get("delta_e_improvement", 0.0)), "conflict_resolution": float(metrics.get("conflict_resolution_rate", 0.0)), "naturalness": float(metrics.get("naturalness_preservation", 0.0)), "conflicts_found": int(metrics.get("conflicts_found", 0)), "boxes_detected": int(metrics.get("boxes_detected", 0)), "inference_ms": float(metrics.get("inference_ms", 0)), "pass_de": bool(metrics.get("pass_de_improvement", False)), "pass_resolution": bool(metrics.get("pass_resolution_rate", False)), "pass_naturalness": bool(metrics.get("pass_naturalness", False)), } try: row = await _persist_images_and_row( f"test-runs/{run_id}", img_np, corrected_uint8, "test_runs", row, ) except Exception as exc: raise HTTPException(500, detail=f"Failed to save test run: {exc}") return _run_to_response(row) _ANALYTICS_COLS = ( "run_id,filename,cvd_type,severity,conf_threshold,created_at,metrics," "de_improvement,conflict_resolution,naturalness," "pass_de,pass_resolution,pass_naturalness,conflicts_found,boxes_detected,inference_ms" ) def _run_to_analytics(row: dict) -> Dict[str, Any]: return { "run_id": row["run_id"], "filename": row.get("filename"), "cvd_type": row["cvd_type"], "severity": row["severity"], "conf_threshold": row["conf_threshold"], "created_at": row["created_at"], "metrics": row.get("metrics") or {}, } @app.get("/test-runs/analytics") async def test_analytics(request: Request, limit: int = 100, offset: int = 0): user_id = _extract_user_id(request) limit, offset = _page_bounds(limit, offset, default=100, maximum=200) if USE_LOCAL: rows = await _to_thread(local_store.analytics_rows, DB_PATH, user_id) page_rows = await _to_thread(local_store.analytics_page, DB_PATH, user_id, limit, offset) else: def _agg(uid=user_id): return ( _get_sb().table("test_runs") .select("de_improvement,conflict_resolution,naturalness,pass_de,pass_resolution,pass_naturalness") .eq("user_id", uid) .execute() ) def _page(uid=user_id, lim=limit, off=offset): return ( _get_sb().table("test_runs") .select(_ANALYTICS_COLS) .eq("user_id", uid) .order("created_at", desc=True) .range(off, off + lim - 1) .execute() ) agg_result, page_result = await asyncio.gather(_to_thread(_agg), _to_thread(_page)) rows = agg_result.data page_rows = page_result.data if not rows: return {"total": 0, "limit": limit, "offset": offset, "runs": []} total = len(rows) def col(name): return [r[name] for r in rows if r.get(name) is not None] def avg(vals): return sum(vals) / len(vals) if vals else 0.0 def mn(vals): return min(vals) if vals else 0.0 def mx(vals): return max(vals) if vals else 0.0 de_vals = col("de_improvement") res_vals = col("conflict_resolution") nat_vals = col("naturalness") return { "total": total, "limit": limit, "offset": offset, "averages": { "de_improvement": round(avg(de_vals), 2), "conflict_resolution": round(avg(res_vals), 4), "naturalness": round(avg(nat_vals), 2), }, "minimums": { "de_improvement": round(mn(de_vals), 2), "conflict_resolution": round(mn(res_vals), 4), "naturalness": round(mn(nat_vals), 2), }, "maximums": { "de_improvement": round(mx(de_vals), 2), "conflict_resolution": round(mx(res_vals), 4), "naturalness": round(mx(nat_vals), 2), }, "pass_rates": { "de_improvement": round(sum(1 for r in rows if r.get("pass_de")) / total, 4), "conflict_resolution": round(sum(1 for r in rows if r.get("pass_resolution")) / total, 4), "naturalness": round(sum(1 for r in rows if r.get("pass_naturalness")) / total, 4), }, "targets": { "de_improvement": 15.0, "conflict_resolution": 0.80, "naturalness": 12.0, }, "runs": [_run_to_analytics(r) for r in page_rows], } @app.get("/test-runs") async def list_test_runs(request: Request, limit: int = 50, offset: int = 0): user_id = _extract_user_id(request) limit, offset = _page_bounds(limit, offset, default=50, maximum=100) if USE_LOCAL: rows = await _to_thread(local_store.list_test_runs, DB_PATH, user_id, limit, offset) return [_run_to_response(r) for r in rows] def _query(uid=user_id, lim=limit, off=offset): return ( _get_sb().table("test_runs") .select("*") .eq("user_id", uid) .order("created_at", desc=True) .range(off, off + lim - 1) .execute() ) result = await _to_thread(_query) return [_run_to_response(r) for r in result.data] @app.delete("/test-runs/{run_id}") async def delete_test_run(run_id: str, request: Request): user_id = _extract_user_id(request) if USE_LOCAL: row = await _to_thread(local_store.get_test_run, DB_PATH, run_id, user_id) if not row: raise HTTPException(404, detail="Test run not found.") await _to_thread(_delete_images, f"test-runs/{run_id}") await _to_thread(local_store.delete_test_run, DB_PATH, run_id) return {"deleted": run_id} def _lookup(rid=run_id, uid=user_id): return ( _get_sb().table("test_runs") .select("run_id") .eq("run_id", rid) .eq("user_id", uid) .execute() ) result = await _to_thread(_lookup) if not result.data: raise HTTPException(404, detail="Test run not found.") def _delete(rid=run_id, uid=user_id): # Same reasoning as delete_job: the service-role key ignores row level # security, so this filter is the only thing scoping the statement. _get_sb().table("test_runs").delete().eq("run_id", rid).eq("user_id", uid).execute() await _to_thread(_delete_images, f"test-runs/{run_id}") await _to_thread(_delete) return {"deleted": run_id} @app.delete("/test-runs") async def clear_test_runs(request: Request): user_id = _extract_user_id(request) if USE_LOCAL: rows = await _to_thread(local_store.list_all_test_runs, DB_PATH, user_id) ids = [row["run_id"] for row in rows] for rid in ids: await _to_thread(_delete_images, f"test-runs/{rid}") await _to_thread(local_store.clear_test_runs, DB_PATH, user_id) return {"cleared": len(ids)} def _lookup(uid=user_id): return ( _get_sb().table("test_runs") .select("run_id") .eq("user_id", uid) .execute() ) result = await _to_thread(_lookup) def _clear(uid=user_id): _get_sb().table("test_runs").delete().eq("user_id", uid).execute() for r in result.data: await _to_thread(_delete_images, f"test-runs/{r['run_id']}") await _to_thread(_clear) return {"cleared": len(result.data)} # ── Expiry cleanup ───────────────────────────────────────────────────────────── def _purge_expired() -> None: if USE_LOCAL: try: local_store.purge_expired(DB_PATH, STATIC_DIR) except Exception as exc: print(f"[ACRA] Purge error: {exc}") return now = datetime.now(timezone.utc).isoformat() try: sb = _get_sb() expired = sb.table("jobs").select("job_id").lte("expires_at", now).execute() for r in expired.data: _delete_images(f"jobs/{r['job_id']}") sb.table("jobs").delete().eq("job_id", r["job_id"]).execute() cutoff = (datetime.now(timezone.utc) - timedelta(hours=24)).isoformat() expired_runs = (sb.table("test_runs").select("run_id").lte("created_at", cutoff) .neq("original_url", "").execute()) for r in expired_runs.data: _delete_images(f"test-runs/{r['run_id']}") sb.table("test_runs").update({"original_url": "", "corrected_url": ""}).eq("run_id", r["run_id"]).execute() except Exception as exc: print(f"[ACRA] Purge error: {exc}")