Spaces:
Sleeping
Sleeping
File size: 1,374 Bytes
5dffcf4 6d303e6 0235ab9 6d303e6 4e2e70c 62cd91e e7b9294 d2a282e e7b9294 15a143e 5dffcf4 15a143e 5dffcf4 15a143e 6d303e6 5dffcf4 15a143e 6d303e6 15a143e | 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 | from fastapi import FastAPI, UploadFile, File, HTTPException, Header
from fastapi.responses import JSONResponse
from PIL import Image
import numpy as np
import io
from keras.models import load_model
import os
model_path = os.path.join(os.path.dirname(__file__), "converted_model.keras")
model = load_model(model_path)
app = FastAPI()
CLASS_NAMES = ['Fungi', 'Healthy', 'Nematode', 'Pest', 'Phytopthora', 'Virus']
API_KEY = "mysecretkey"
@app.post("/predict")
async def predict(file: UploadFile = File(...), x_api_key: str = Header(None)):
if x_api_key != API_KEY:
raise HTTPException(status_code=401, detail="Invalid or missing API Key")
try:
contents = await file.read()
image = Image.open(io.BytesIO(contents)).convert("RGB")
image = image.resize((224, 224))
img_array = np.array(image).astype("float32")
img_array = np.expand_dims(img_array, axis=0)
prediction = model.predict(img_array)
predicted_class = int(np.argmax(prediction[0]))
predicted_label = CLASS_NAMES[predicted_class]
return {
"prediction": predicted_label,
"probabilities": {
CLASS_NAMES[i]: float(round(prediction[0][i], 4)) for i in range(6)
}
}
except Exception as e:
return JSONResponse(status_code=500, content={"error": str(e)})
|