Spaces:
Sleeping
Sleeping
File size: 7,464 Bytes
d47fb92 | 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 | """FastAPI backend for the Fabric Density Analyzer web UI.
Wraps epi_ppi_v4_1.process() into a single POST /analyze endpoint.
The algorithm file (epi_ppi_v4_1.py) is expected to be importable from this
process; deployment scripts either copy it into the container or set PYTHONPATH.
"""
from __future__ import annotations
import os
import sys
import tempfile
from typing import Optional
import numpy as np
from fastapi import BackgroundTasks, FastAPI, File, Form, HTTPException, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
# Register the HEIC/HEIF opener so PIL can read iPhone .HEIC uploads everywhere
# downstream (analyzer + recognizer share this process). Without this, PIL
# raises UnidentifiedImageError on .HEIC files.
try:
import pillow_heif
pillow_heif.register_heif_opener()
except Exception as _e: # pragma: no cover
print(f"[pillow-heif not available, HEIC uploads will fail: {_e}]")
# Allow PYTHONPATH override; default: parent directory of this file's parent
# (i.e. .../fabric/), so `import epi_ppi_v4_1` works in dev.
_DEFAULT_ALGO_DIR = os.path.normpath(
os.path.join(os.path.dirname(__file__), "..", "..")
)
sys.path.insert(0, os.environ.get("FABRIC_ALGO_DIR", _DEFAULT_ALGO_DIR))
import epi_ppi_v6_1 as algo # noqa: E402 (v6.1 = v6 + tick-hierarchy + both-axis k-referees + sub-pixel refine; drop-in)
app = FastAPI(title="Fabric Density Analyzer API", version="0.1.0")
# CORS: configurable; defaults to "*" so the frontend can call from any origin.
# In production, set FABRIC_CORS_ORIGINS to your Pages domain.
_origins = os.environ.get("FABRIC_CORS_ORIGINS", "*").split(",")
app.add_middleware(
CORSMiddleware,
allow_origins=[o.strip() for o in _origins if o.strip()],
allow_methods=["GET", "POST", "OPTIONS"],
allow_headers=["*"],
)
ALLOWED_WEAVES = {"plain", "twill", "satin", "basket", "matt", "rib", "dobby"}
MAX_BYTES = 25 * 1024 * 1024 # 25 MB
# Mount article-recognition routes (frozen-DINOv2 embedding). Imported guardedly
# so the EPI/PPI analyzer keeps working even if torch/timm aren't installed.
try:
from .recognizer_routes import router as _recognizer_router
app.include_router(_recognizer_router)
except Exception as _e: # pragma: no cover
print(f"[recognizer routes not mounted: {_e}]")
@app.on_event("startup")
def _warm_recognizer():
"""Warm the recognizer in a background thread at boot so the ONE-TIME v6
catalog re-embed (auto-migration) runs here instead of blocking a user's first
request. Non-fatal: the EPI/PPI analyzer works regardless."""
import threading
def _go():
try:
from .recognizer_routes import _rec
_rec()
except Exception as e:
print(f"[recognizer warmup skipped: {type(e).__name__}: {e}]")
threading.Thread(target=_go, daemon=True).start()
@app.get("/")
def health():
return {"status": "ok", "algorithm": "epi_ppi_v6_1", "recognition": "fabric_recognize"}
@app.get("/health")
def health_alias():
return {"status": "ok"}
@app.post("/analyze")
async def analyze(
bg: BackgroundTasks,
image: UploadFile = File(...),
weave: str = Form(...),
tick_mm: str = Form("auto"),
epi_repeat: Optional[int] = Form(None),
ppi_repeat: Optional[int] = Form(None),
twill_repeat: Optional[int] = Form(None),
twill_ppi_ascend: Optional[str] = Form(None),
):
weave_norm = (weave or "").strip().lower()
if weave_norm not in ALLOWED_WEAVES:
raise HTTPException(status_code=400,
detail=f"weave must be one of {sorted(ALLOWED_WEAVES)}")
force_tick = None
if tick_mm and tick_mm.lower() != "auto":
try:
force_tick = float(tick_mm)
except ValueError:
raise HTTPException(status_code=400, detail="tick_mm must be 'auto' or a number")
data = await image.read()
if not data:
raise HTTPException(status_code=400, detail="empty file upload")
if len(data) > MAX_BYTES:
raise HTTPException(status_code=413, detail=f"file > {MAX_BYTES // (1024*1024)} MB")
# Write to a temp file because the algorithm opens by path (and supports HEIC via PIL plugin).
suffix = os.path.splitext(image.filename or "upload.jpg")[1] or ".jpg"
with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
tmp.write(data)
tmp_path = tmp.name
try:
kwargs = {
"weave": weave_norm,
"twill_repeat": twill_repeat,
"ppi_ascend_flag": bool(twill_ppi_ascend) and twill_ppi_ascend not in ("false", "0", "off"),
"force_tick_mm": force_tick,
}
if epi_repeat is not None:
kwargs["epi_repeat"] = epi_repeat
if ppi_repeat is not None:
kwargs["ppi_repeat"] = ppi_repeat
result = algo.process(tmp_path, **kwargs)
except Exception as e:
raise HTTPException(status_code=500, detail=f"analysis failed: {type(e).__name__}: {e}")
finally:
try:
os.remove(tmp_path)
except OSError:
pass
out = _serialise(result)
# Log the processed image + readings/confidence to durable storage, then
# mirror to the bucket in the background (non-fatal; never blocks the reply).
try:
from . import persistence as P
P.log_processed(data, image.filename, {
"weave": out.get("weave"), "epi": out.get("epi_round"), "ppi": out.get("ppi_round"),
"epi_confidence": out.get("epi_confidence"), "ppi_confidence": out.get("ppi_confidence"),
"epi_reason": out.get("epi_reason"), "ppi_reason": out.get("ppi_reason"),
"px_per_inch": out.get("px_per_inch"), "tick_mm": out.get("tick_mm"),
})
bg.add_task(P.push)
except Exception as _e:
print(f"[processed-log skipped: {_e}]")
return JSONResponse(out)
def _serialise(r) -> dict:
c = r.calib
q = r.quality
def _f(x):
try:
x = float(x)
return x if np.isfinite(x) else None
except Exception:
return None
out = {
"weave": r.weave,
"epi": _f(r.epi),
"ppi": _f(r.ppi),
"epi_round": r.epi_round,
"ppi_round": r.ppi_round,
"method": r.method,
"scale_unit": getattr(c, "scale_unit", None),
"tick_mm": getattr(c, "tick_mm", None),
"px_per_mm": _f(getattr(c, "px_per_mm", None)),
"px_per_inch": _f(getattr(c, "px_per_inch", None)),
"ruler_kind": getattr(c, "ruler_kind", None),
"best_patch_epi": _f(r.best_patch_epi),
"best_patch_ppi": _f(r.best_patch_ppi),
"n_patches": r.n_patches,
# v5 confidence layer (additive; absent on older algo modules)
"epi_confidence": _f(getattr(r, "epi_confidence", None)),
"ppi_confidence": _f(getattr(r, "ppi_confidence", None)),
"epi_reason": getattr(r, "epi_reason", None),
"ppi_reason": getattr(r, "ppi_reason", None),
"advice": getattr(r, "advice", "") or None,
}
if q is not None:
out["quality"] = {
"label": q.label,
"overall_pct": _f(q.overall_pct),
"epi_pct": _f(q.epi.final_pct) if hasattr(q, "epi") else None,
"ppi_pct": _f(q.ppi.final_pct) if hasattr(q, "ppi") else None,
"warnings": list(q.warnings or []),
}
return out
|