Spaces:
Sleeping
Sleeping
File size: 1,227 Bytes
47b6c1c | 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 | from fastapi import FastAPI, UploadFile, File
from fastapi.responses import JSONResponse
import tensorflow as tf
from PIL import Image
import numpy as np
import io
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
# Allow CORS for all origins (adjust as needed)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Load model
def load_model():
return tf.keras.models.load_model("growlens_efficientnet_model.h5")
model = load_model()
class_names = [
"ants", "bees", "beetle", "catterpillar", "earthworms", "earwig",
"grasshopper", "moth", "slug", "snail", "wasp", "weevil"
]
@app.post("/predict")
async def predict(file: UploadFile = File(...)):
image_bytes = await file.read()
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
image = image.resize((224, 224)) # Adjust size as per your model
img_array = np.array(image) / 255.0
img_array = np.expand_dims(img_array, axis=0)
preds = model.predict(img_array)
pred_class = class_names[np.argmax(preds)]
confidence = float(np.max(preds))
return JSONResponse({"class": pred_class, "confidence": confidence})
|