Spaces:
Sleeping
Sleeping
File size: 1,720 Bytes
5dffcf4 6d303e6 0235ab9 a9e03b0 6d303e6 a6a0da8 15a143e 5dffcf4 ef2d27b 015bf69 ef2d27b c999abd 62cd91e d819750 1898bee e7b9294 1898bee d819750 e7b9294 d819750 015bf69 c999abd 015bf69 f84edc7 15a143e 5dffcf4 15a143e 5dffcf4 15a143e 5dffcf4 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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | from fastapi import FastAPI, UploadFile, File, HTTPException, Header
from fastapi.responses import JSONResponse
from PIL import Image
import numpy as np
import tensorflow as tf
import io
import os
app = FastAPI()
# Load your model
import os
import keras
from keras.models import load_model
# Read the model file into memory
with open("2.keras", "rb") as f:
byte_data = f.read()
# Wrap in a BytesIO object
model_file = io.BytesIO(byte_data)
# Load the model, giving a valid .keras filename
model = tf.keras.models.load_model(("2.keras", model_file))
# Now load the model
CLASS_NAMES = ['Fungi', 'Healthy', 'Nematode', 'Pest', 'Phytopthora', 'Virus']
# Define your API key (keep it secret in prod)
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()
# Process the image
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)
# Predict
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)})
|