Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import torch
|
3 |
+
import torchvision.models as models
|
4 |
+
from torchvision.models import EfficientNet_B0_Weights # Or the specific version used
|
5 |
+
from PIL import Image
|
6 |
+
from torchvision import transforms
|
7 |
+
import json
|
8 |
+
from huggingface_hub import hf_hub_download
|
9 |
+
import os
|
10 |
+
|
11 |
+
# --- Configuration ---
|
12 |
+
# This should be the ID of the repository where your MODEL is stored
|
13 |
+
MODEL_REPO_ID = "bhumong/fruit-classifier-efficientnet-b0" # <-- REPLACE if different
|
14 |
+
MODEL_FILENAME = "pytorch_model.bin"
|
15 |
+
CONFIG_FILENAME = "config.json"
|
16 |
+
|
17 |
+
# --- 1. Load Model and Config ---
|
18 |
+
# (Using the function defined previously to load from Hub)
|
19 |
+
def load_model_from_hf(repo_id, model_filename, config_filename):
|
20 |
+
"""Loads model state_dict and config from Hugging Face Hub."""
|
21 |
+
try:
|
22 |
+
config_path = hf_hub_download(repo_id=repo_id, filename=config_filename)
|
23 |
+
with open(config_path, 'r') as f:
|
24 |
+
config = json.load(f)
|
25 |
+
print("Config loaded:", config) # Debug print
|
26 |
+
except Exception as e:
|
27 |
+
print(f"Error loading config from {repo_id}/{config_filename}: {e}")
|
28 |
+
raise # Re-raise error if config fails
|
29 |
+
|
30 |
+
num_labels = config.get('num_labels')
|
31 |
+
id2label = config.get('id2label')
|
32 |
+
|
33 |
+
if num_labels is None or id2label is None:
|
34 |
+
raise ValueError("Config file must contain 'num_labels' and 'id2label'")
|
35 |
+
|
36 |
+
# Instantiate the correct architecture (EfficientNet-B0)
|
37 |
+
model = models.efficientnet_b0(weights=None) # Load architecture only
|
38 |
+
|
39 |
+
# Modify the classifier head
|
40 |
+
try:
|
41 |
+
num_ftrs = model.classifier[1].in_features
|
42 |
+
model.classifier[1] = torch.nn.Linear(num_ftrs, num_labels)
|
43 |
+
except Exception as e:
|
44 |
+
print(f"Error modifying model classifier: {e}")
|
45 |
+
raise
|
46 |
+
|
47 |
+
# Download and load model weights
|
48 |
+
try:
|
49 |
+
model_path = hf_hub_download(repo_id=repo_id, filename=model_filename)
|
50 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
51 |
+
state_dict = torch.load(model_path, map_location=device)
|
52 |
+
model.load_state_dict(state_dict)
|
53 |
+
model.to(device) # Move model to device
|
54 |
+
model.eval() # Set to evaluation mode
|
55 |
+
print(f"Model loaded successfully from {repo_id} to device {device}.")
|
56 |
+
return model, config, id2label, device
|
57 |
+
except Exception as e:
|
58 |
+
print(f"Error loading model weights from {repo_id}/{model_filename}: {e}")
|
59 |
+
raise
|
60 |
+
|
61 |
+
# Load the model globally when the script starts
|
62 |
+
try:
|
63 |
+
model, config, id2label, device = load_model_from_hf(MODEL_REPO_ID, MODEL_FILENAME, CONFIG_FILENAME)
|
64 |
+
except Exception as e:
|
65 |
+
print(f"FATAL: Could not load model or config. Gradio app cannot start. Error: {e}")
|
66 |
+
# Optionally, exit or raise a specific error for Gradio to catch if possible
|
67 |
+
model, config, id2label, device = None, None, None, None # Prevent further errors
|
68 |
+
|
69 |
+
|
70 |
+
# --- 2. Define Preprocessing ---
|
71 |
+
IMG_SIZE = (224, 224)
|
72 |
+
mean=[0.485, 0.456, 0.406]
|
73 |
+
std=[0.229, 0.224, 0.225]
|
74 |
+
|
75 |
+
preprocess = transforms.Compose([
|
76 |
+
transforms.Resize(IMG_SIZE),
|
77 |
+
transforms.ToTensor(),
|
78 |
+
transforms.Normalize(mean=mean, std=std),
|
79 |
+
])
|
80 |
+
|
81 |
+
# --- 3. Define Prediction Function ---
|
82 |
+
def predict(inp_image):
|
83 |
+
"""Takes a PIL image, preprocesses, predicts, and returns label confidences."""
|
84 |
+
if model is None or id2label is None:
|
85 |
+
return {"Error": 1.0, "Message": "Model not loaded"} # Handle model load failure
|
86 |
+
|
87 |
+
if inp_image is None:
|
88 |
+
return {"Error": 1.0, "Message": "No image provided"}
|
89 |
+
|
90 |
+
try:
|
91 |
+
# Ensure image is RGB
|
92 |
+
img = inp_image.convert("RGB")
|
93 |
+
input_tensor = preprocess(img)
|
94 |
+
input_batch = input_tensor.unsqueeze(0) # Add batch dimension
|
95 |
+
input_batch = input_batch.to(device) # Move tensor to the correct device
|
96 |
+
|
97 |
+
with torch.no_grad():
|
98 |
+
output = model(input_batch)
|
99 |
+
probabilities = torch.nn.functional.softmax(output[0], dim=0)
|
100 |
+
|
101 |
+
# Prepare output for Gradio Label component (dictionary {label: probability})
|
102 |
+
confidences = {id2label[str(i)]: float(probabilities[i]) for i in range(len(id2label))}
|
103 |
+
return confidences
|
104 |
+
|
105 |
+
except Exception as e:
|
106 |
+
print(f"Error during prediction: {e}")
|
107 |
+
return {"Error": 1.0, "Message": f"Prediction failed: {e}"}
|
108 |
+
|
109 |
+
|
110 |
+
# --- 4. Create Gradio Interface ---
|
111 |
+
|
112 |
+
# Add example images (Make sure these paths exist within your Space repo!)
|
113 |
+
# Create an 'images' folder in your Space and upload some examples.
|
114 |
+
example_list = [
|
115 |
+
["images/example_apple.jpg"], # <-- REPLACE with actual paths in your Space repo
|
116 |
+
["images/example_banana.jpg"], # <-- REPLACE with actual paths in your Space repo
|
117 |
+
["images/example_strawberry.jpg"] # <-- REPLACE with actual paths in your Space repo
|
118 |
+
]
|
119 |
+
# Check if example files exist, otherwise provide empty list
|
120 |
+
if not all(os.path.exists(ex[0]) for ex in example_list):
|
121 |
+
print("Warning: Example image paths not found. Clearing examples.")
|
122 |
+
example_list = []
|
123 |
+
|
124 |
+
|
125 |
+
# Define Title, Description, and Article for the Gradio app
|
126 |
+
title = "Fruit Classifier πππ"
|
127 |
+
description = """
|
128 |
+
Upload an image of a fruit or use one of the examples below.
|
129 |
+
This demo uses an EfficientNet-B0 model fine-tuned on the Fruits-360 dataset
|
130 |
+
(with merged classes) to predict the fruit type.
|
131 |
+
Model hosted on Hugging Face Hub: [{MODEL_REPO_ID}](https://huggingface.co/{MODEL_REPO_ID})
|
132 |
+
""".format(MODEL_REPO_ID=MODEL_REPO_ID) # Format description with repo ID
|
133 |
+
article = """
|
134 |
+
<div style='text-align: center;'>
|
135 |
+
Model trained using PyTorch and tracked with Neptune.ai. |
|
136 |
+
<a href='https://huggingface.co/{MODEL_REPO_ID}' target='_blank'>Model Repository</a> |
|
137 |
+
Built with Gradio
|
138 |
+
</div>
|
139 |
+
""".format(MODEL_REPO_ID=MODEL_REPO_ID)
|
140 |
+
|
141 |
+
# Create and launch the interface
|
142 |
+
if model is not None: # Only launch if model loaded successfully
|
143 |
+
iface = gr.Interface(
|
144 |
+
fn=predict,
|
145 |
+
inputs=gr.Image(type="pil", label="Upload Fruit Image"),
|
146 |
+
outputs=gr.Label(num_top_classes=5, label="Predictions"), # Show top 5 predictions
|
147 |
+
title=title,
|
148 |
+
description=description,
|
149 |
+
article=article,
|
150 |
+
examples=example_list,
|
151 |
+
allow_flagging="never" # Optional: disable flagging
|
152 |
+
)
|
153 |
+
|
154 |
+
iface.launch()
|
155 |
+
else:
|
156 |
+
print("Gradio interface not launched due to model loading failure.")
|
157 |
+
|