from fastapi import FastAPI, UploadFile, File, HTTPException from fastapi.middleware.cors import CORSMiddleware from starlette.responses import JSONResponse from app.model import analyze_image from app.utils import read_image from app.caption_model import caption_image # Fixed import name app = FastAPI(title="Image Analyzer API", version="1.0.0") # ✅ Add CORS Middleware app.add_middleware( CORSMiddleware, allow_origins=["*"], # Change to ["https://your-frontend.com"] for production allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) @app.post("/analyze") async def analyze(file: UploadFile = File(...)): if not file or not file.filename: raise HTTPException(status_code=400, detail="No file uploaded.") try: image = read_image(file) except Exception as e: raise HTTPException(status_code=400, detail=f"Failed to read image: {str(e)}") if not file.content_type.startswith('image/'): raise HTTPException(status_code=400, detail="File must be an image") try: result = analyze_image(image) return JSONResponse(content=result) except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) except RuntimeError as e: raise HTTPException(status_code=500, detail=str(e)) except Exception as e: raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}") @app.post("/caption") async def generate_image_caption(file: UploadFile = File(...)): if not file or not file.filename: raise HTTPException(status_code=400, detail="No file uploaded.") if not file.content_type.startswith('image/'): raise HTTPException(status_code=400, detail="File must be an image") try: image = read_image(file) result = caption_image(image) # Fixed function name return JSONResponse(content=result) except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) except Exception as e: raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}") @app.get("/") def read_root(): return {"message": "Image Analyzer API is running"}