Upload app.py with huggingface_hub
Browse files
app.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import tensorflow as tf
|
| 4 |
+
import numpy as np
|
| 5 |
+
from datasets import load_dataset
|
| 6 |
+
from PIL import Image
|
| 7 |
+
|
| 8 |
+
# Define the preprocessing function
|
| 9 |
+
def preprocess_inference_image(image):
|
| 10 |
+
# Ensure image is a tensor
|
| 11 |
+
image = tf.convert_to_tensor(image, dtype=tf.float32)
|
| 12 |
+
# Convert image to RGB if it has 4 channels (RGBA)
|
| 13 |
+
if tf.shape(image)[-1] == 4:
|
| 14 |
+
image = image[..., :3] # Select first 3 channels (RGB)
|
| 15 |
+
# Normalize to [0,1]
|
| 16 |
+
image = tf.image.convert_image_dtype(image, tf.float32)
|
| 17 |
+
# Resize to MobileNetV3 input size
|
| 18 |
+
image = tf.image.resize(image, [224, 224])
|
| 19 |
+
# Add batch dimension
|
| 20 |
+
image = tf.expand_dims(image, axis=0)
|
| 21 |
+
return image
|
| 22 |
+
|
| 23 |
+
# Load the trained model
|
| 24 |
+
model = tf.keras.models.load_model('maize_disease_model.keras')
|
| 25 |
+
|
| 26 |
+
# Load the dataset to get label names
|
| 27 |
+
ds = load_dataset("aquib1011/maize-leaf-disease", cache_dir=None)
|
| 28 |
+
label_names = ds['train'].features['label'].names
|
| 29 |
+
|
| 30 |
+
def predict_maize_disease(image):
|
| 31 |
+
# Convert PIL Image to numpy array
|
| 32 |
+
image = np.array(image)
|
| 33 |
+
# Apply preprocessing to the input image
|
| 34 |
+
processed_image = preprocess_inference_image(image)
|
| 35 |
+
|
| 36 |
+
# Make a prediction
|
| 37 |
+
predictions = model.predict(processed_image)
|
| 38 |
+
|
| 39 |
+
# Return the results as a dictionary for Gradio's Label component
|
| 40 |
+
return {label_names[i]: float(predictions[0][i]) for i in range(len(label_names))}
|
| 41 |
+
|
| 42 |
+
# Create the Gradio interface
|
| 43 |
+
iface = gr.Interface(
|
| 44 |
+
fn=predict_maize_disease,
|
| 45 |
+
inputs=gr.Image(type="pil"),
|
| 46 |
+
outputs=gr.Label(),
|
| 47 |
+
title="Maize Leaf Disease Classifier",
|
| 48 |
+
description="Upload an image of a maize leaf to get a prediction of the disease."
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
if __name__ == "__main__":
|
| 52 |
+
iface.launch()
|