Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,23 +5,39 @@ import json
|
|
| 5 |
from tensorflow.keras.preprocessing.image import img_to_array
|
| 6 |
from tensorflow.keras.applications.vgg16 import preprocess_input
|
| 7 |
from PIL import Image
|
| 8 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
# ---------- Load the Model (.keras format) ----------
|
| 11 |
-
# The model file 'fruits_classifier.keras' should be in the same directory
|
| 12 |
model_path = 'fruits_classifier.keras'
|
| 13 |
model = tf.keras.models.load_model(model_path)
|
| 14 |
print("Model loaded successfully!")
|
| 15 |
|
| 16 |
# ---------- Load Class Names ----------
|
| 17 |
-
# Load the class index mapping saved from the training generator
|
| 18 |
with open('class_indices.json', 'r') as f:
|
| 19 |
class_names_dict = json.load(f)
|
| 20 |
|
| 21 |
-
# Convert dictionary to list for easy index-based
|
| 22 |
-
# Example: {"0": "apple", "1": "banana"} -> ["apple", "banana"]
|
| 23 |
class_names_list = [class_names_dict[str(i)] for i in range(len(class_names_dict))]
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
# ---------- Prediction Function ----------
|
| 27 |
def predict_image(image):
|
|
@@ -29,7 +45,7 @@ def predict_image(image):
|
|
| 29 |
Takes an input image, preprocesses it for VGG16, runs inference,
|
| 30 |
and returns the predicted class name and confidence.
|
| 31 |
"""
|
| 32 |
-
# Resize image to match model's
|
| 33 |
img = image.resize((64, 64))
|
| 34 |
# Convert PIL image to numpy array
|
| 35 |
img_array = img_to_array(img)
|
|
@@ -38,19 +54,38 @@ def predict_image(image):
|
|
| 38 |
# Apply VGG16-specific preprocessing (scaling and mean subtraction)
|
| 39 |
img_array = preprocess_input(img_array)
|
| 40 |
|
| 41 |
-
#
|
| 42 |
predictions = model.predict(img_array)
|
| 43 |
predicted_index = np.argmax(predictions, axis=-1)[0]
|
| 44 |
confidence = np.max(predictions, axis=-1)[0]
|
| 45 |
|
| 46 |
-
# Get the
|
| 47 |
-
|
|
|
|
|
|
|
| 48 |
confidence_percentage = float(confidence) * 100
|
| 49 |
|
| 50 |
return predicted_class, f"{confidence_percentage:.2f}%"
|
| 51 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
# ---------- Gradio Interface Setup ----------
|
| 53 |
-
# Define the Gradio UI
|
| 54 |
interface = gr.Interface(
|
| 55 |
fn=predict_image,
|
| 56 |
inputs=gr.Image(type="pil", label="Upload Fruit Image"),
|
|
@@ -59,7 +94,7 @@ interface = gr.Interface(
|
|
| 59 |
gr.Textbox(label="π Confidence")
|
| 60 |
],
|
| 61 |
title="π Fruit Classification Using Transfer Learning",
|
| 62 |
-
description=
|
| 63 |
)
|
| 64 |
|
| 65 |
# ---------- Launch the App ----------
|
|
|
|
| 5 |
from tensorflow.keras.preprocessing.image import img_to_array
|
| 6 |
from tensorflow.keras.applications.vgg16 import preprocess_input
|
| 7 |
from PIL import Image
|
| 8 |
+
import re
|
| 9 |
+
|
| 10 |
+
# ---------- Helper Function: Clean Class Names ----------
|
| 11 |
+
def clean_class_name(raw_name):
|
| 12 |
+
"""
|
| 13 |
+
Converts raw class names like 'apple_red_1' to 'Apple Red'
|
| 14 |
+
and 'pear_1' to 'Pear'.
|
| 15 |
+
"""
|
| 16 |
+
# Remove the trailing underscore and number (e.g., '_1', '_2')
|
| 17 |
+
# Using regex to remove '_' followed by digits at the end
|
| 18 |
+
cleaned = re.sub(r'_\d+$', '', raw_name)
|
| 19 |
+
# Replace underscores with spaces
|
| 20 |
+
cleaned = cleaned.replace('_', ' ')
|
| 21 |
+
# Capitalize each word
|
| 22 |
+
cleaned = cleaned.title()
|
| 23 |
+
return cleaned
|
| 24 |
|
| 25 |
# ---------- Load the Model (.keras format) ----------
|
|
|
|
| 26 |
model_path = 'fruits_classifier.keras'
|
| 27 |
model = tf.keras.models.load_model(model_path)
|
| 28 |
print("Model loaded successfully!")
|
| 29 |
|
| 30 |
# ---------- Load Class Names ----------
|
|
|
|
| 31 |
with open('class_indices.json', 'r') as f:
|
| 32 |
class_names_dict = json.load(f)
|
| 33 |
|
| 34 |
+
# Convert dictionary to a list for easy index-based access
|
|
|
|
| 35 |
class_names_list = [class_names_dict[str(i)] for i in range(len(class_names_dict))]
|
| 36 |
+
|
| 37 |
+
# ---------- Create a list of cleaned class names for display ----------
|
| 38 |
+
# Format: ["Apple Red", "Apple Braeburn", "Cucumber", ...]
|
| 39 |
+
cleaned_class_names = [clean_class_name(name) for name in class_names_list]
|
| 40 |
+
print(f"Total classes loaded: {len(cleaned_class_names)}")
|
| 41 |
|
| 42 |
# ---------- Prediction Function ----------
|
| 43 |
def predict_image(image):
|
|
|
|
| 45 |
Takes an input image, preprocesses it for VGG16, runs inference,
|
| 46 |
and returns the predicted class name and confidence.
|
| 47 |
"""
|
| 48 |
+
# Resize image to match the model's input shape (64x64)
|
| 49 |
img = image.resize((64, 64))
|
| 50 |
# Convert PIL image to numpy array
|
| 51 |
img_array = img_to_array(img)
|
|
|
|
| 54 |
# Apply VGG16-specific preprocessing (scaling and mean subtraction)
|
| 55 |
img_array = preprocess_input(img_array)
|
| 56 |
|
| 57 |
+
# Run inference
|
| 58 |
predictions = model.predict(img_array)
|
| 59 |
predicted_index = np.argmax(predictions, axis=-1)[0]
|
| 60 |
confidence = np.max(predictions, axis=-1)[0]
|
| 61 |
|
| 62 |
+
# Get the raw class name
|
| 63 |
+
raw_class_name = class_names_list[predicted_index]
|
| 64 |
+
# Clean the class name for display
|
| 65 |
+
predicted_class = clean_class_name(raw_class_name)
|
| 66 |
confidence_percentage = float(confidence) * 100
|
| 67 |
|
| 68 |
return predicted_class, f"{confidence_percentage:.2f}%"
|
| 69 |
|
| 70 |
+
# ---------- Create a formatted list of categories for display ----------
|
| 71 |
+
# Format: "Apple, Apple Braeburn, Apple Crimson Snow, ..."
|
| 72 |
+
categories_list = sorted(cleaned_class_names) # Sort alphabetically
|
| 73 |
+
categories_text = ", ".join(categories_list) # Join with commas
|
| 74 |
+
|
| 75 |
+
# Create the description with categories
|
| 76 |
+
description_text = f"""
|
| 77 |
+
### π Upload an image of a fruit.
|
| 78 |
+
|
| 79 |
+
**The model can predict the following {len(categories_list)} categories:**
|
| 80 |
+
|
| 81 |
+
{', '.join(categories_list)}
|
| 82 |
+
|
| 83 |
+
---
|
| 84 |
+
|
| 85 |
+
*Model: VGG16-based Transfer Learning trained on Fruits-360 dataset.*
|
| 86 |
+
"""
|
| 87 |
+
|
| 88 |
# ---------- Gradio Interface Setup ----------
|
|
|
|
| 89 |
interface = gr.Interface(
|
| 90 |
fn=predict_image,
|
| 91 |
inputs=gr.Image(type="pil", label="Upload Fruit Image"),
|
|
|
|
| 94 |
gr.Textbox(label="π Confidence")
|
| 95 |
],
|
| 96 |
title="π Fruit Classification Using Transfer Learning",
|
| 97 |
+
description=description_text,
|
| 98 |
)
|
| 99 |
|
| 100 |
# ---------- Launch the App ----------
|