from fastapi import FastAPI, UploadFile, File import numpy as np from PIL import Image import io from tensorflow import keras # Load model model = keras.models.load_model('model.h5') # Class labels (ordered list) class_labels = [ 'Apple__Apple_scab', 'Apple_Black_rot', 'Apple_Cedar_apple_rust', 'Apple__healthy', 'Blueberry__healthy', 'Cherry(including_sour)Powdery_mildew', 'Cherry(including_sour)_healthy', 'Corn_(maize)Cercospora_leaf_spot Gray_leaf_spot', 'Corn(maize)Common_rust', 'Corn_(maize)Northern_Leaf_Blight', 'Corn(maize)healthy', 'Grape__Black_rot', 'Grape__Esca(Black_Measles)', 'Grape__Leaf_blight(Isariopsis_Leaf_Spot)', 'Grape___healthy', 'Orange__Haunglongbing(Citrus_greening)', 'Peach__Bacterial_spot', 'Peach__healthy', 'Pepper,bell_Bacterial_spot', 'Pepper,_bell_healthy', 'Potato_Early_blight', 'Potato__Late_blight', 'Potato__healthy', 'Raspberry_healthy', 'Soybean_healthy', 'Squash__Powdery_mildew', 'Strawberry__Leaf_scorch', 'Strawberry_healthy', 'Tomato_Bacterial_spot', 'Tomato__Early_blight', 'Tomato__Late_blight', 'Tomato_Leaf_Mold', 'Tomato__Septoria_leaf_spot', 'Tomato__Spider_mites Two-spotted_spider_mite', 'Tomato__Target_Spot', 'Tomato__Tomato_Yellow_Leaf_Curl_Virus', 'Tomato_Tomato_mosaic_virus', 'Tomato__healthy' ] # Initialize FastAPI app app = FastAPI() # Preprocess function def preprocess_image(image_bytes): image = Image.open(io.BytesIO(image_bytes)).convert('RGB') image = image.resize((224, 224)) img_array = np.array(image) / 255.0 # normalize (assuming your model was trained with normalization) img_array = np.expand_dims(img_array, axis=0) # add batch dimension return img_array @app.post("/predict") async def predict(file: UploadFile = File(...)): image_bytes = await file.read() img_array = preprocess_image(image_bytes) predictions = model.predict(img_array) predicted_class = class_labels[np.argmax(predictions)] confidence = float(np.max(predictions)) return {"prediction": predicted_class, "confidence": confidence}