from fastapi import FastAPI, UploadFile, File, HTTPException from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse from PIL import Image import io import logging from app.services.analyzer import ImageAnalyzer logger = logging.getLogger(__name__) # Upload limits (frontend advertises "Max 10MB") MAX_UPLOAD_BYTES = 10 * 1024 * 1024 MAX_PIXELS = 50_000_000 # ~50 MP; rejects decompression bombs ALLOWED_FORMATS = ["JPEG", "PNG", "WEBP", "GIF"] app = FastAPI( title="FrameMatch API", description="Analyze reference images and provide recreation guides", version="1.0.0" ) app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=False, # no cookies/auth used; never combine with "*" allow_methods=["GET", "POST"], allow_headers=["*"], ) analyzer = ImageAnalyzer() @app.get("/api/health") async def health_check(): return {"status": "healthy", "service": "framematch-api"} @app.post("/api/analyze") async def analyze_image(image: UploadFile = File(...)): if not image.content_type or not image.content_type.startswith("image/"): raise HTTPException(status_code=400, detail="File must be an image") # Read at most MAX_UPLOAD_BYTES + 1 so oversized uploads are rejected contents = await image.read(MAX_UPLOAD_BYTES + 1) if len(contents) > MAX_UPLOAD_BYTES: raise HTTPException(status_code=413, detail="Image too large (max 10MB)") # Validate the actual file content, not the client-supplied content type. # Restricting formats keeps Pillow's rarer (and more bug-prone) decoders unreachable. try: with Image.open(io.BytesIO(contents), formats=ALLOWED_FORMATS) as probe: width, height = probe.size except Exception: raise HTTPException(status_code=400, detail="Unsupported image format (use JPEG, PNG, WebP or GIF)") if width * height > MAX_PIXELS: raise HTTPException(status_code=413, detail="Image dimensions too large") try: result = analyzer.analyze(io.BytesIO(contents)) return JSONResponse(content=result) except Exception: logger.exception("Analysis failed") raise HTTPException(status_code=500, detail="Analysis failed") if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8000)