POP / app.py
iSushant's picture
Update app.py
db67448 verified
import os
import zipfile
import gradio as gr
import tensorflow as tf
import numpy as np
from tensorflow.keras.preprocessing import image
from tensorflow.keras.layers import TFSMLayer
from PIL import Image
# Define paths
zip_path = "best_model_saved.zip"
extract_path = "best_model_saved"
# Check if extracted folder exists, if not, extract it
if not os.path.exists(extract_path):
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
zip_ref.extractall(".")
# Load the model using TFSMLayer
best_model = TFSMLayer(extract_path, call_endpoint="serving_default")
print("✅ Model loaded successfully!")
# Define class mapping (index -> class label)
class_mapping = {0: "Early_Blight", 1: "Healthy", 2: "Late_Blight"}
def classify_leaf(input_image):
"""
Takes an input image (PIL format from Gradio), preprocesses it,
and returns the predicted class with probabilities.
"""
# Resize and normalize the image
img = input_image.resize((250, 250))
img_array = image.img_to_array(img) / 255.0
img_array = np.expand_dims(img_array, axis=0) # shape (1, 250, 250, 3)
# Make a prediction
pred_dict = best_model(img_array) # Get dictionary output
# Extract the correct tensor output from the dictionary
output_key = list(pred_dict.keys())[0] # Get first output key
preds = pred_dict[output_key] # Extract tensor
# Convert tensor to numpy array
probs = preds.numpy()[0] # Convert to NumPy and extract first batch
# Format probabilities as a string
prob_str = ", ".join([f"{class_mapping[i]}: {probs[i]:.2f}" for i in range(len(class_mapping))])
# Determine predicted class
pred_idx = np.argmax(probs)
pred_class = class_mapping[pred_idx]
# Return formatted result
return f"Predicted Class: {pred_class}\nProbabilities: {prob_str}"
# Build the Gradio interface
iface = gr.Interface(
fn=classify_leaf,
inputs=gr.Image(type="pil"), # Expecting an uploaded image
outputs="text", # Output text with the predicted class and probabilities
title="Potato Leaf Disease Classifier",
description="Upload an image of a potato leaf. The model will predict if it's Early_Blight, Healthy, or Late_Blight."
)
# Launch the app
if __name__ == "__main__":
iface.launch()