File size: 1,939 Bytes
dd98c93 5846c5c 82ccd05 630eb59 5846c5c f947f52 630eb59 212b656 5846c5c 212b656 630eb59 212b656 82ccd05 630eb59 5846c5c 630eb59 5846c5c 630eb59 5846c5c 630eb59 5846c5c dd98c93 | 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 | import os
import numpy as np
import tensorflow as tf
import gradio as gr
# Load model
model_path = 'plantvillage_efficientnet_b0.keras'
if os.path.exists(model_path):
try:
model = tf.keras.models.load_model(model_path, compile=False)
print("Model loaded successfully!")
except Exception as e:
print(f"Error loading model: {e}")
model = None
else:
print(f"File not found: {model_path}")
model = None
classes = [
'Pepper__bell___Bacterial_spot', 'Pepper__bell___healthy', 'Potato___Early_blight',
'Potato___Late_blight', 'Potato___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_YellowLeaf__Curl_Virus',
'Tomato__Tomato_mosaic_virus', 'Tomato_healthy'
]
def predict(image):
if model is None:
raise gr.Error("Model is not loaded. Check model file path in your Space.")
if image is None:
return {}
try:
# Preprocess input image
img = tf.image.resize(image, (224, 224))
img = tf.cast(img, tf.float32)
img = tf.keras.applications.efficientnet.preprocess_input(img)
img = tf.expand_dims(img, axis=0)
# Run inference
preds = model.predict(img, verbose=0)[0]
# Format predictions dict
return {classes[i]: float(preds[i]) for i in range(len(classes))}
except Exception as err:
print(f"Prediction Error: {err}")
raise gr.Error(f"Prediction error: {str(err)}")
demo = gr.Interface(
fn=predict,
inputs=gr.Image(type="numpy", label="Upload Leaf Image"),
outputs=gr.Label(num_top_classes=3, label="Predictions"),
title="Plant Disease Detector",
description="Upload a crop leaf image to identify diseases."
)
if __name__ == '__main__':
demo.launch() |