royajaygit
udated main.py+ download
cca5b9a
Raw History Blame Contribute Delete
1.98 kB
# api/main.py
from fastapi import FastAPI, UploadFile, File, Form
from fastapi.responses import JSONResponse,HTMLResponse
from fastapi.middleware.cors import CORSMiddleware
from PIL import Image
import io
import base64
# Ensure model and data files are downloaded before app starts
import download_files
from .model_service import predict_snake, generate_image_from_text
app = FastAPI(title="Snake AI Detection API")
# Allow all origins (for Hugging Face Spaces compatibility)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"]
)
@app.get("/")
def home():
return HTMLResponse("<h2>🐍 Snake AI Detection API is running!</h2>")
@app.post("/predict-image")
async def predict_image_endpoint(file: UploadFile = File(...)):
"""Predict snake species and venom info from uploaded image."""
try:
image_data = await file.read()
image = Image.open(io.BytesIO(image_data)).convert("RGB")
prediction_result = predict_snake(image)
return JSONResponse(content=prediction_result)
except Exception as e:
return JSONResponse(
content={"error": "Prediction failed", "detail": str(e)},
status_code=500
)
@app.post("/generate-and-predict")
async def generate_and_predict_endpoint(description: str = Form(...)):
"""Generate an image from text and predict its snake species."""
try:
image_bytes, gen_image_pil = generate_image_from_text(description)
prediction_result = predict_snake(gen_image_pil)
base64_image = base64.b64encode(image_bytes).decode("utf-8")
return JSONResponse(content={
"generated_image_base64": base64_image,
"prediction": prediction_result
})
except Exception as e:
return JSONResponse(
content={"error": "Generation/prediction failed", "detail": str(e)},
status_code=500
)