File size: 4,052 Bytes
0e0cc3e
 
06bdaca
0e0cc3e
 
 
 
 
06bdaca
d16c4ed
06bdaca
0e0cc3e
 
 
06bdaca
 
 
0e0cc3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a34f575
0e0cc3e
 
 
 
 
 
06bdaca
a34f575
0e0cc3e
 
 
 
06bdaca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d16c4ed
a34f575
 
06bdaca
 
 
 
d16c4ed
06bdaca
a34f575
 
 
 
 
 
 
 
 
d16c4ed
a34f575
 
d16c4ed
a34f575
06bdaca
 
 
 
 
 
 
 
0e0cc3e
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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")