Update app.py
Browse files
app.py
CHANGED
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import tensorflow as tf
|
3 |
+
import numpy as np
|
4 |
+
import builtins
|
5 |
+
from tensorflow.keras.models import load_model
|
6 |
+
from tensorflow.keras.preprocessing import image
|
7 |
+
from PIL import Image
|
8 |
+
|
9 |
+
# Ensure TensorFlow is available globally for the Lambda layer
|
10 |
+
builtins.tf = tf
|
11 |
+
|
12 |
+
# Define the function to replace the anonymous lambda from the model
|
13 |
+
def expand_dims_func(x):
|
14 |
+
import tensorflow as tf
|
15 |
+
return tf.expand_dims(x, axis=1)
|
16 |
+
|
17 |
+
# Load your trained model
|
18 |
+
best_model_path = "best_model.h5" # Ensure this file is uploaded to the Hugging Face Space
|
19 |
+
best_model = load_model(best_model_path, custom_objects={"<lambda>": expand_dims_func})
|
20 |
+
|
21 |
+
# Define class mapping (index -> class label)
|
22 |
+
class_mapping = {0: "Early_Blight", 1: "Healthy", 2: "Late_Blight"}
|
23 |
+
|
24 |
+
def classify_leaf(input_image):
|
25 |
+
"""
|
26 |
+
Takes an input image (PIL format from Gradio), preprocesses it,
|
27 |
+
and returns the predicted class with probabilities.
|
28 |
+
"""
|
29 |
+
# Resize and normalize the image
|
30 |
+
img = input_image.resize((250, 250))
|
31 |
+
img_array = image.img_to_array(img) / 255.0
|
32 |
+
img_array = np.expand_dims(img_array, axis=0) # shape (1, 250, 250, 3)
|
33 |
+
|
34 |
+
# Get predictions
|
35 |
+
preds = best_model.predict(img_array)
|
36 |
+
probs = preds[0] # shape (3,)
|
37 |
+
|
38 |
+
# Format the output string with each class probability
|
39 |
+
prob_str = ", ".join([f"{class_mapping[i]}: {probs[i]:.2f}" for i in range(len(class_mapping))])
|
40 |
+
|
41 |
+
# Determine the predicted class
|
42 |
+
pred_idx = np.argmax(probs)
|
43 |
+
pred_class = class_mapping[pred_idx]
|
44 |
+
|
45 |
+
# Return a formatted string showing the predicted class and probabilities
|
46 |
+
return f"Predicted Class: {pred_class}\nProbabilities: {prob_str}"
|
47 |
+
|
48 |
+
# Build the Gradio interface
|
49 |
+
iface = gr.Interface(
|
50 |
+
fn=classify_leaf,
|
51 |
+
inputs=gr.Image(type="pil"), # Expecting an uploaded image
|
52 |
+
outputs="text", # Output text with the predicted class and probabilities
|
53 |
+
title="Potato Leaf Disease Classifier",
|
54 |
+
description="Upload an image of a potato leaf. The model will predict if it's Early_Blight, Healthy, or Late_Blight."
|
55 |
+
)
|
56 |
+
|
57 |
+
# Launch the app
|
58 |
+
if __name__ == "__main__":
|
59 |
+
iface.launch()
|