|
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 |
|
|
|
|
|
zip_path = "best_model_saved.zip" |
|
extract_path = "best_model_saved" |
|
|
|
|
|
if not os.path.exists(extract_path): |
|
with zipfile.ZipFile(zip_path, 'r') as zip_ref: |
|
zip_ref.extractall(".") |
|
|
|
|
|
best_model = TFSMLayer(extract_path, call_endpoint="serving_default") |
|
print("✅ Model loaded successfully!") |
|
|
|
|
|
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. |
|
""" |
|
|
|
img = input_image.resize((250, 250)) |
|
img_array = image.img_to_array(img) / 255.0 |
|
img_array = np.expand_dims(img_array, axis=0) |
|
|
|
|
|
pred_dict = best_model(img_array) |
|
|
|
|
|
output_key = list(pred_dict.keys())[0] |
|
preds = pred_dict[output_key] |
|
|
|
|
|
probs = preds.numpy()[0] |
|
|
|
|
|
prob_str = ", ".join([f"{class_mapping[i]}: {probs[i]:.2f}" for i in range(len(class_mapping))]) |
|
|
|
|
|
pred_idx = np.argmax(probs) |
|
pred_class = class_mapping[pred_idx] |
|
|
|
|
|
return f"Predicted Class: {pred_class}\nProbabilities: {prob_str}" |
|
|
|
|
|
iface = gr.Interface( |
|
fn=classify_leaf, |
|
inputs=gr.Image(type="pil"), |
|
outputs="text", |
|
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." |
|
) |
|
|
|
|
|
if __name__ == "__main__": |
|
iface.launch() |
|
|