from pathlib import Path from fastapi import FastAPI, File, Form, HTTPException, UploadFile from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import FileResponse, JSONResponse from starlette.middleware.base import BaseHTTPMiddleware from starlette.requests import Request import detect from detect_limiter import DetectBusyError, DetectTimeoutError, estimate_detect_timeout_sec, limiter APP_VERSION = "1.0.0" STATIC_PATH = Path(__file__).resolve().parent / "static" # 25 MB upload cap — enough for high-res phone photos, blocks abuse. MAX_UPLOAD_BYTES = 25 * 1024 * 1024 class CrossOriginIsolationMiddleware(BaseHTTPMiddleware): async def dispatch(self, request: Request, call_next): response = await call_next(request) response.headers["Cross-Origin-Opener-Policy"] = "same-origin" response.headers["Cross-Origin-Embedder-Policy"] = "require-corp" return response app = FastAPI( title="NPI Pipe Count PWA", description="Offline-first pipe counting PWA with in-browser ONNX inference", version=APP_VERSION, ) app.add_middleware(CrossOriginIsolationMiddleware) app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"], ) @app.get("/health") async def health_check(): model_path = STATIC_PATH / "models" / "countmodel.onnx" queue = await limiter.status() return JSONResponse( { "status": "ok", "version": APP_VERSION, "mode": "static-pwa", "model_present": model_path.is_file(), "server_detect": detect.is_available(), "queue": queue, } ) @app.post("/detect") async def detect_endpoint( file: UploadFile = File(...), tiling: bool = Form(False), auto_tile: bool = Form(True), outliers: bool = Form(False), ): """Server-side detection fallback for devices that can't run the model locally.""" if not detect.is_available(): raise HTTPException(status_code=503, detail="Server-side detection is not available") data = await file.read() if not data: raise HTTPException(status_code=400, detail="Empty upload") if len(data) > MAX_UPLOAD_BYTES: raise HTTPException(status_code=413, detail="Image too large") try: timeout_sec = estimate_detect_timeout_sec(len(data)) result = await limiter.run( detect.detect_bytes, data, use_tiling=True if tiling else None, auto_tile=auto_tile, filter_outliers_flag=outliers, timeout_sec=timeout_sec, ) except DetectBusyError: queue = await limiter.status() raise HTTPException( status_code=429, detail={ "message": "Server is busy. Try again in a few seconds.", "queue": queue, }, ) except DetectTimeoutError as exc: raise HTTPException( status_code=504, detail=f"Detection timed out after {exc.timeout_sec:.0f}s", ) except ValueError as exc: raise HTTPException(status_code=400, detail=str(exc)) except Exception as exc: # noqa: BLE001 - surface a clean 500 to the client raise HTTPException(status_code=500, detail=f"Detection failed: {exc}") return JSONResponse(result) @app.get("/{filename:path}") async def serve_file(filename: str): if not filename: filename = "index.html" file_path = (STATIC_PATH / filename).resolve() if not str(file_path).startswith(str(STATIC_PATH.resolve())): raise HTTPException(status_code=403, detail="Forbidden") if file_path.is_file(): return FileResponse(file_path) # SPA fallback index = STATIC_PATH / "index.html" if index.is_file(): return FileResponse(index) raise HTTPException(status_code=404, detail="File not found")