Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,65 +3,65 @@ import tensorflow as tf
|
|
| 3 |
import numpy as np
|
| 4 |
from PIL import Image
|
| 5 |
|
| 6 |
-
#
|
| 7 |
-
print("
|
| 8 |
model = tf.keras.models.load_model('finetuned_food_270.keras')
|
| 9 |
-
print("Model
|
| 10 |
|
| 11 |
-
#
|
| 12 |
with open('labels.txt', 'r', encoding='utf-8') as f:
|
| 13 |
class_names = [line.strip() for line in f.readlines()]
|
| 14 |
-
print(f"{len(class_names)}
|
| 15 |
|
| 16 |
-
# --- 1.
|
| 17 |
-
#
|
| 18 |
IMG_SIZE = (224, 224)
|
| 19 |
|
| 20 |
def preprocess_image(image):
|
| 21 |
-
"""
|
| 22 |
|
| 23 |
-
# PIL Image
|
| 24 |
if isinstance(image, np.ndarray):
|
| 25 |
img = Image.fromarray(image)
|
| 26 |
else:
|
| 27 |
img = image
|
| 28 |
|
| 29 |
-
# RGB'
|
| 30 |
img = img.convert('RGB')
|
| 31 |
|
| 32 |
-
# Resize (
|
| 33 |
img = img.resize(IMG_SIZE)
|
| 34 |
|
| 35 |
-
# Numpy array
|
| 36 |
img_array = np.array(img, dtype=np.float32)
|
| 37 |
|
| 38 |
-
#
|
| 39 |
img_array = np.expand_dims(img_array, axis=0)
|
| 40 |
|
| 41 |
-
# --- 2.
|
| 42 |
-
# EfficientNetV2 (B2)
|
| 43 |
-
#
|
| 44 |
# img_array = tf.keras.applications.efficientnet.preprocess_input(img_array)
|
| 45 |
|
| 46 |
-
#
|
| 47 |
return img_array
|
| 48 |
|
| 49 |
def predict(image):
|
| 50 |
-
"""
|
| 51 |
try:
|
| 52 |
-
#
|
| 53 |
processed_image = preprocess_image(image)
|
| 54 |
|
| 55 |
-
#
|
| 56 |
predictions = model.predict(processed_image, verbose=0)
|
| 57 |
|
| 58 |
-
#
|
| 59 |
predictions = predictions[0]
|
| 60 |
|
| 61 |
-
#
|
| 62 |
top_indices = np.argsort(predictions)[-5:][::-1]
|
| 63 |
|
| 64 |
-
#
|
| 65 |
results = {}
|
| 66 |
for idx in top_indices:
|
| 67 |
label = class_names[idx]
|
|
@@ -70,53 +70,77 @@ def predict(image):
|
|
| 70 |
|
| 71 |
return results
|
| 72 |
except Exception as e:
|
| 73 |
-
print(f"
|
| 74 |
-
return {"
|
| 75 |
|
| 76 |
-
# --- Gradio
|
| 77 |
with gr.Blocks(title="Food 270 Classifier") as demo:
|
| 78 |
-
#
|
| 79 |
gr.Markdown("""
|
| 80 |
-
# 🍽️ Food 270
|
| 81 |
-
**
|
| 82 |
-
📸
|
| 83 |
""")
|
|
|
|
|
|
|
| 84 |
with gr.Row():
|
|
|
|
| 85 |
with gr.Column(scale=1):
|
| 86 |
-
input_image = gr.Image(label="
|
|
|
|
|
|
|
| 87 |
with gr.Row():
|
| 88 |
-
clear_btn = gr.Button("🗑️
|
| 89 |
-
submit_btn = gr.Button("🔍
|
|
|
|
|
|
|
| 90 |
with gr.Column(scale=1):
|
| 91 |
-
output = gr.Label(label="
|
|
|
|
|
|
|
| 92 |
gr.Markdown("""
|
| 93 |
-
### 📊
|
| 94 |
-
- **
|
| 95 |
-
-
|
| 96 |
-
- **Top 5**
|
| 97 |
""")
|
|
|
|
|
|
|
| 98 |
with gr.Row():
|
| 99 |
gr.Markdown("""
|
| 100 |
-
### 💡
|
| 101 |
-
-
|
| 102 |
-
-
|
| 103 |
-
-
|
| 104 |
""")
|
|
|
|
|
|
|
| 105 |
gr.Markdown("""
|
| 106 |
---
|
| 107 |
-
### 🤖 Model
|
| 108 |
- **Model**: EfficientNetV2B2 (Fine-tuned)
|
| 109 |
- **Dataset**: Food 270
|
| 110 |
-
- **
|
| 111 |
-
- **
|
| 112 |
-
*
|
| 113 |
""")
|
| 114 |
-
|
| 115 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
|
| 117 |
-
#
|
| 118 |
if __name__ == "__main__":
|
| 119 |
demo.launch(
|
| 120 |
-
share=False,
|
| 121 |
-
debug=False
|
| 122 |
)
|
|
|
|
| 3 |
import numpy as np
|
| 4 |
from PIL import Image
|
| 5 |
|
| 6 |
+
# Load the model
|
| 7 |
+
print("Loading model...")
|
| 8 |
model = tf.keras.models.load_model('finetuned_food_270.keras')
|
| 9 |
+
print("Model loaded successfully!")
|
| 10 |
|
| 11 |
+
# Load the class names
|
| 12 |
with open('labels.txt', 'r', encoding='utf-8') as f:
|
| 13 |
class_names = [line.strip() for line in f.readlines()]
|
| 14 |
+
print(f"{len(class_names)} classes loaded")
|
| 15 |
|
| 16 |
+
# --- 1. ADJUSTMENT: IMAGE SIZE ---
|
| 17 |
+
# Enter the size you trained the model with
|
| 18 |
IMG_SIZE = (224, 224)
|
| 19 |
|
| 20 |
def preprocess_image(image):
|
| 21 |
+
"""Prepare the image for the model"""
|
| 22 |
|
| 23 |
+
# Convert to PIL Image and ensure RGB
|
| 24 |
if isinstance(image, np.ndarray):
|
| 25 |
img = Image.fromarray(image)
|
| 26 |
else:
|
| 27 |
img = image
|
| 28 |
|
| 29 |
+
# Convert to RGB (in case it's grayscale)
|
| 30 |
img = img.convert('RGB')
|
| 31 |
|
| 32 |
+
# Resize (to the size used during training)
|
| 33 |
img = img.resize(IMG_SIZE)
|
| 34 |
|
| 35 |
+
# Convert to Numpy array (should be dtype=float32)
|
| 36 |
img_array = np.array(img, dtype=np.float32)
|
| 37 |
|
| 38 |
+
# Add batch dimension
|
| 39 |
img_array = np.expand_dims(img_array, axis=0)
|
| 40 |
|
| 41 |
+
# --- 2. ADJUSTMENT: V2 PREPROCESSING ---
|
| 42 |
+
# EfficientNetV2 (B2) does NOT use this V1 preprocessing function.
|
| 43 |
+
# DELETE or COMMENT OUT this line:
|
| 44 |
# img_array = tf.keras.applications.efficientnet.preprocess_input(img_array)
|
| 45 |
|
| 46 |
+
# Since your model is V2, it expects input in the [0, 255] range (which it is now).
|
| 47 |
return img_array
|
| 48 |
|
| 49 |
def predict(image):
|
| 50 |
+
"""Food prediction function"""
|
| 51 |
try:
|
| 52 |
+
# Process the image
|
| 53 |
processed_image = preprocess_image(image)
|
| 54 |
|
| 55 |
+
# Make a prediction
|
| 56 |
predictions = model.predict(processed_image, verbose=0)
|
| 57 |
|
| 58 |
+
# Get the softmax output (first batch)
|
| 59 |
predictions = predictions[0]
|
| 60 |
|
| 61 |
+
# Find top 5 predictions
|
| 62 |
top_indices = np.argsort(predictions)[-5:][::-1]
|
| 63 |
|
| 64 |
+
# Prepare the results
|
| 65 |
results = {}
|
| 66 |
for idx in top_indices:
|
| 67 |
label = class_names[idx]
|
|
|
|
| 70 |
|
| 71 |
return results
|
| 72 |
except Exception as e:
|
| 73 |
+
print(f"Error: {e}")
|
| 74 |
+
return {"Error": str(e)}
|
| 75 |
|
| 76 |
+
# --- Gradio Interface ---
|
| 77 |
with gr.Blocks(title="Food 270 Classifier") as demo:
|
| 78 |
+
# Title and description
|
| 79 |
gr.Markdown("""
|
| 80 |
+
# 🍽️ Food 270 Classifier
|
| 81 |
+
**An AI model that can recognize 270 different types of food**
|
| 82 |
+
📸 Upload a photo of food and let it guess what it is!
|
| 83 |
""")
|
| 84 |
+
|
| 85 |
+
# Main row
|
| 86 |
with gr.Row():
|
| 87 |
+
# Left column - Input
|
| 88 |
with gr.Column(scale=1):
|
| 89 |
+
input_image = gr.Image(label="Food Photo", type="numpy")
|
| 90 |
+
|
| 91 |
+
# Buttons
|
| 92 |
with gr.Row():
|
| 93 |
+
clear_btn = gr.Button("🗑️ Clear", variant="secondary")
|
| 94 |
+
submit_btn = gr.Button("🔍 Predict", variant="primary")
|
| 95 |
+
|
| 96 |
+
# Right column - Output
|
| 97 |
with gr.Column(scale=1):
|
| 98 |
+
output = gr.Label(label="Prediction Results", num_top_classes=5, show_label=True)
|
| 99 |
+
|
| 100 |
+
# Additional info
|
| 101 |
gr.Markdown("""
|
| 102 |
+
### 📊 Result Explanation
|
| 103 |
+
- The **highest score** is the most likely food type
|
| 104 |
+
- Scores represent the confidence level **between 0-1**
|
| 105 |
+
- The **Top 5** most likely predictions are shown
|
| 106 |
""")
|
| 107 |
+
|
| 108 |
+
# Bottom section - Tips and info
|
| 109 |
with gr.Row():
|
| 110 |
gr.Markdown("""
|
| 111 |
+
### 💡 Tips
|
| 112 |
+
- Clear and well-lit photos give better results
|
| 113 |
+
- A full view of the food improves the prediction
|
| 114 |
+
- Photos containing a single type of food are ideal
|
| 115 |
""")
|
| 116 |
+
|
| 117 |
+
# Model info
|
| 118 |
gr.Markdown("""
|
| 119 |
---
|
| 120 |
+
### 🤖 Model Information
|
| 121 |
- **Model**: EfficientNetV2B2 (Fine-tuned)
|
| 122 |
- **Dataset**: Food 270
|
| 123 |
+
- **Number of Classes**: 270 different foods
|
| 124 |
+
- **Training Size**: 224x224
|
| 125 |
+
*Developer: Berker Üveyik*
|
| 126 |
""")
|
| 127 |
+
|
| 128 |
+
# Event handlers
|
| 129 |
+
submit_btn.click(
|
| 130 |
+
fn=predict,
|
| 131 |
+
inputs=input_image,
|
| 132 |
+
outputs=output
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
clear_btn.click(
|
| 136 |
+
lambda: (None, None),
|
| 137 |
+
inputs=None,
|
| 138 |
+
outputs=[input_image, output]
|
| 139 |
+
)
|
| 140 |
|
| 141 |
+
# Launch the application
|
| 142 |
if __name__ == "__main__":
|
| 143 |
demo.launch(
|
| 144 |
+
share=False, # Should be False on Spaces
|
| 145 |
+
debug=False # Should be False in production
|
| 146 |
)
|