farm_die_class / app.py
Vinit710's picture
Update app.py
84c7c12 verified
import tensorflow as tf
from tensorflow import keras
import numpy as np
from tensorflow.keras.utils import load_img, img_to_array
import gradio as gr
# Define class names in the order used during training
class_names = [
'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'
]
# Load the pre-trained model (make sure the model file is in your repo)
model_path = "my_keras_model.keras" # Adjust the path if necessary
model = keras.models.load_model(model_path)
def predict_plant_disease(image):
"""
Process the uploaded image and return the predicted class along with the top 5 probabilities.
"""
# Resize the image to match model input
img = tf.image.resize(image, (224, 224))
# Convert to array and scale pixel values
img_array = img_to_array(img) / 255.0
img_array = np.expand_dims(img_array, axis=0)
# Make prediction
predictions = model.predict(img_array)
predicted_class_index = np.argmax(predictions, axis=1)[0]
predicted_label = class_names[predicted_class_index]
# Get top 5 predictions
top5_indices = np.argsort(predictions[0])[-5:][::-1]
top5_info = [(class_names[i], float(predictions[0][i])) for i in top5_indices]
# Build result string
result = f"Predicted: {predicted_label}\n\nTop 5 Predictions:\n"
for label, prob in top5_info:
result += f"{label}: {prob:.4f}\n"
return result
# Create the Gradio interface
title = "Plant Disease Classifier"
description = (
"Upload an image of a plant leaf to predict the disease using a pre-trained TensorFlow/Keras model. "
"The model outputs the predicted class along with the top 5 probabilities."
)
iface = gr.Interface(
fn=predict_plant_disease,
inputs=gr.Image(type="numpy", label="Upload Plant Image"),
outputs="text",
title=title,
description=description,
)
if __name__ == "__main__":
iface.launch()