Upload app.py with huggingface_hub
Browse files
app.py
CHANGED
|
@@ -1,41 +1,42 @@
|
|
| 1 |
-
#
|
| 2 |
import sys
|
| 3 |
|
| 4 |
-
# Patch client_utils BEFORE gradio
|
| 5 |
-
def
|
| 6 |
-
#
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
# Fix the get_type function that causes TypeError
|
| 10 |
-
original_get_type = client_utils.get_type
|
| 11 |
-
def fixed_get_type(schema):
|
| 12 |
-
if not isinstance(schema, dict):
|
| 13 |
-
return "Any"
|
| 14 |
-
return original_get_type(schema)
|
| 15 |
-
client_utils.get_type = fixed_get_type
|
| 16 |
-
|
| 17 |
-
# Also fix _json_schema_to_python_type
|
| 18 |
-
original_json_schema = client_utils._json_schema_to_python_type
|
| 19 |
-
def fixed_json_schema(schema, defs=None):
|
| 20 |
-
if not isinstance(schema, dict):
|
| 21 |
-
return "Any"
|
| 22 |
-
return original_json_schema(schema, defs)
|
| 23 |
-
client_utils._json_schema_to_python_type = fixed_json_schema
|
| 24 |
|
| 25 |
-
# Import gradio
|
| 26 |
import gradio as gr
|
| 27 |
import gradio.routes as routes_module
|
|
|
|
| 28 |
|
| 29 |
-
# Patch
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
-
#
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
import os
|
| 41 |
import shutil
|
|
@@ -79,7 +80,7 @@ class FoodClassifier:
|
|
| 79 |
ToTensorV2()
|
| 80 |
])
|
| 81 |
|
| 82 |
-
print(f"Model loaded! Classes: {num_classes}")
|
| 83 |
|
| 84 |
def predict(self, image, top_k=5):
|
| 85 |
if image is None:
|
|
@@ -101,7 +102,7 @@ class FoodClassifier:
|
|
| 101 |
for i, idx in enumerate(top_indices)
|
| 102 |
])
|
| 103 |
|
| 104 |
-
# Attention
|
| 105 |
img_np = np.array(image.resize((224, 224)))
|
| 106 |
cnn_att = cv2.resize(attention_maps['cnn_attention'].cpu().numpy()[0, 0], (224, 224))
|
| 107 |
cnn_att = (cnn_att - cnn_att.min()) / (cnn_att.max() - cnn_att.min() + 1e-8)
|
|
@@ -110,7 +111,7 @@ class FoodClassifier:
|
|
| 110 |
|
| 111 |
fig, axes = plt.subplots(1, 3, figsize=(15, 5))
|
| 112 |
axes[0].imshow(img_np)
|
| 113 |
-
axes[0].set_title('Original')
|
| 114 |
axes[0].axis('off')
|
| 115 |
axes[1].imshow(img_np)
|
| 116 |
axes[1].imshow(cnn_att, alpha=0.6, cmap='jet')
|
|
@@ -131,25 +132,57 @@ class FoodClassifier:
|
|
| 131 |
|
| 132 |
return results, attention_img
|
| 133 |
|
| 134 |
-
print("Downloading model...")
|
| 135 |
ckpt_path = hf_hub_download(repo_id=REPO_ID, filename="best_model.pth")
|
| 136 |
mapping_path = hf_hub_download(repo_id=REPO_ID, filename="real_class_mapping.json")
|
| 137 |
shutil.copy(mapping_path, "real_class_mapping.json")
|
|
|
|
| 138 |
|
| 139 |
classifier = FoodClassifier(ckpt_path)
|
| 140 |
|
|
|
|
| 141 |
demo = gr.Interface(
|
| 142 |
fn=classifier.predict,
|
| 143 |
inputs=[
|
| 144 |
-
gr.Image(type="pil", label="Upload Food Image"),
|
| 145 |
-
gr.Slider(1, 10, 5, step=1, label="Top K")
|
| 146 |
],
|
| 147 |
outputs=[
|
| 148 |
-
gr.Textbox(label="Results", lines=10),
|
| 149 |
-
gr.Image(label="Attention Maps", height=400)
|
| 150 |
],
|
| 151 |
-
title="Food Classifier",
|
| 152 |
-
description="
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
)
|
| 154 |
|
|
|
|
| 155 |
demo.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
| 1 |
+
# ULTIMATE FIX - Patch everything before Gradio loads
|
| 2 |
import sys
|
| 3 |
|
| 4 |
+
# Patch client_utils BEFORE gradio import
|
| 5 |
+
def patch_before_gradio():
|
| 6 |
+
# We'll patch after gradio loads but before it's used
|
| 7 |
+
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
+
# Import gradio
|
| 10 |
import gradio as gr
|
| 11 |
import gradio.routes as routes_module
|
| 12 |
+
from gradio_client import utils as client_utils
|
| 13 |
|
| 14 |
+
# Patch 1: Fix client_utils.get_type() - THE ACTUAL BUG
|
| 15 |
+
original_get_type = client_utils.get_type
|
| 16 |
+
def safe_get_type(schema):
|
| 17 |
+
if not isinstance(schema, dict):
|
| 18 |
+
return "Any"
|
| 19 |
+
try:
|
| 20 |
+
return original_get_type(schema)
|
| 21 |
+
except (TypeError, AttributeError):
|
| 22 |
+
return "Any"
|
| 23 |
+
client_utils.get_type = safe_get_type
|
| 24 |
|
| 25 |
+
# Patch 2: Fix _json_schema_to_python_type
|
| 26 |
+
original_json_schema = client_utils._json_schema_to_python_type
|
| 27 |
+
def safe_json_schema(schema, defs=None):
|
| 28 |
+
if not isinstance(schema, dict):
|
| 29 |
+
return "Any"
|
| 30 |
+
try:
|
| 31 |
+
return original_json_schema(schema, defs)
|
| 32 |
+
except (TypeError, AttributeError):
|
| 33 |
+
return "Any"
|
| 34 |
+
client_utils._json_schema_to_python_type = safe_json_schema
|
| 35 |
+
|
| 36 |
+
# Patch 3: Disable API generation
|
| 37 |
+
def empty_api_info(*args, **kwargs):
|
| 38 |
+
return {"api": {}}
|
| 39 |
+
routes_module.api_info = empty_api_info
|
| 40 |
|
| 41 |
import os
|
| 42 |
import shutil
|
|
|
|
| 80 |
ToTensorV2()
|
| 81 |
])
|
| 82 |
|
| 83 |
+
print(f"β
Model loaded successfully! Classes: {num_classes}")
|
| 84 |
|
| 85 |
def predict(self, image, top_k=5):
|
| 86 |
if image is None:
|
|
|
|
| 102 |
for i, idx in enumerate(top_indices)
|
| 103 |
])
|
| 104 |
|
| 105 |
+
# Attention visualization
|
| 106 |
img_np = np.array(image.resize((224, 224)))
|
| 107 |
cnn_att = cv2.resize(attention_maps['cnn_attention'].cpu().numpy()[0, 0], (224, 224))
|
| 108 |
cnn_att = (cnn_att - cnn_att.min()) / (cnn_att.max() - cnn_att.min() + 1e-8)
|
|
|
|
| 111 |
|
| 112 |
fig, axes = plt.subplots(1, 3, figsize=(15, 5))
|
| 113 |
axes[0].imshow(img_np)
|
| 114 |
+
axes[0].set_title('Original Image')
|
| 115 |
axes[0].axis('off')
|
| 116 |
axes[1].imshow(img_np)
|
| 117 |
axes[1].imshow(cnn_att, alpha=0.6, cmap='jet')
|
|
|
|
| 132 |
|
| 133 |
return results, attention_img
|
| 134 |
|
| 135 |
+
print("π₯ Downloading model from Hugging Face Hub...")
|
| 136 |
ckpt_path = hf_hub_download(repo_id=REPO_ID, filename="best_model.pth")
|
| 137 |
mapping_path = hf_hub_download(repo_id=REPO_ID, filename="real_class_mapping.json")
|
| 138 |
shutil.copy(mapping_path, "real_class_mapping.json")
|
| 139 |
+
print("β
Model files downloaded successfully!")
|
| 140 |
|
| 141 |
classifier = FoodClassifier(ckpt_path)
|
| 142 |
|
| 143 |
+
# Create Gradio Interface
|
| 144 |
demo = gr.Interface(
|
| 145 |
fn=classifier.predict,
|
| 146 |
inputs=[
|
| 147 |
+
gr.Image(type="pil", label="π· Upload Food Image", height=300),
|
| 148 |
+
gr.Slider(1, 10, 5, step=1, label="π Top K Predictions")
|
| 149 |
],
|
| 150 |
outputs=[
|
| 151 |
+
gr.Textbox(label="π― Classification Results", lines=10),
|
| 152 |
+
gr.Image(label="ποΈ Attention Maps", height=400)
|
| 153 |
],
|
| 154 |
+
title="π Food Image Classifier",
|
| 155 |
+
description="""
|
| 156 |
+
# π AI-Powered Food Classification System
|
| 157 |
+
|
| 158 |
+
This application uses a **Hybrid CNN-ViT Architecture** to classify food images into 101 different categories.
|
| 159 |
+
|
| 160 |
+
## π How to Use:
|
| 161 |
+
1. **Upload** a food image (or drag & drop)
|
| 162 |
+
2. **Adjust** the "Top K" slider to see more/less predictions
|
| 163 |
+
3. **View** the results:
|
| 164 |
+
- **Classification Results**: Top food categories with confidence scores
|
| 165 |
+
- **Attention Maps**: Visual representation of what the AI focuses on
|
| 166 |
+
|
| 167 |
+
## π§ Model Architecture:
|
| 168 |
+
- **CNN Branch**: ResNet50 (spatial feature extraction)
|
| 169 |
+
- **ViT Branch**: DeiT-Base (global context understanding)
|
| 170 |
+
- **Fusion Module**: Adaptive attention-based fusion
|
| 171 |
+
|
| 172 |
+
## π Performance:
|
| 173 |
+
- **101 Food Categories** from Food-101 dataset
|
| 174 |
+
- **Validation Accuracy**: ~82.5%
|
| 175 |
+
- **Top-5 Accuracy**: >95%
|
| 176 |
+
|
| 177 |
+
## π― Model Capabilities:
|
| 178 |
+
The model can classify various food types including:
|
| 179 |
+
- Pizza, Burger, Sushi, Pasta, Salad, and 96 more categories!
|
| 180 |
+
|
| 181 |
+
**Try uploading a food image now!** π½οΈ
|
| 182 |
+
""",
|
| 183 |
+
theme=gr.themes.Soft(),
|
| 184 |
+
examples=None # No examples to avoid cache issues
|
| 185 |
)
|
| 186 |
|
| 187 |
+
print("π Starting Gradio interface...")
|
| 188 |
demo.launch(server_name="0.0.0.0", server_port=7860)
|