File size: 1,977 Bytes
5d5bfad
fdc2547
cca5b9a
4d071cd
fdc2547
5d5bfad
def435c
fdc2547
def435c
ea0cc14
4d071cd
fdc2547
 
 
def435c
fdc2547
 
dbaf575
4d071cd
 
 
fdc2547
 
dbaf575
1acc187
 
dbaf575
fdc2547
 
def435c
fdc2547
 
4d071cd
fdc2547
 
 
4d071cd
5d5bfad
4d071cd
 
fdc2547
 
 
def435c
fdc2547
 
 
dbaf575
def435c
5d5bfad
fdc2547
 
5d5bfad
fdc2547
4d071cd
5d5bfad
4d071cd
 
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
# 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
        )