Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,48 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
import torch
|
3 |
from utils.inference_utils import preprocess_image, predict
|
4 |
from utils.train_utils import initialize_model
|
5 |
from utils.data import CLASS_NAMES
|
6 |
|
7 |
-
#
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
|
|
|
|
|
|
|
|
|
|
12 |
|
13 |
-
|
14 |
-
|
15 |
-
model.
|
16 |
-
|
17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
18 |
|
19 |
-
def classify_image(image):
|
20 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
try:
|
22 |
-
|
23 |
-
|
24 |
-
|
|
|
25 |
image_tensor = preprocess_image(image, (224, 224)).to(device)
|
26 |
-
|
27 |
# Perform inference
|
28 |
-
|
29 |
-
|
|
|
|
|
30 |
predicted_class = CLASS_NAMES[preds.item()]
|
31 |
-
|
|
|
|
|
|
|
|
|
|
|
32 |
return f"Predicted class: {predicted_class}"
|
|
|
|
|
|
|
|
|
|
|
33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
34 |
except Exception as e:
|
35 |
-
|
|
|
|
|
36 |
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
)
|
|
|
|
|
|
|
45 |
|
46 |
if __name__ == "__main__":
|
47 |
-
|
48 |
-
demo.launch()
|
|
|
1 |
+
import os
|
2 |
+
import logging
|
3 |
+
import time
|
4 |
+
import traceback
|
5 |
+
|
6 |
import gradio as gr
|
7 |
import torch
|
8 |
from utils.inference_utils import preprocess_image, predict
|
9 |
from utils.train_utils import initialize_model
|
10 |
from utils.data import CLASS_NAMES
|
11 |
|
12 |
+
# Configure logging
|
13 |
+
logging.basicConfig(
|
14 |
+
level=logging.INFO,
|
15 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
16 |
+
handlers=[
|
17 |
+
logging.FileHandler('pokemon_classifier.log'),
|
18 |
+
logging.StreamHandler()
|
19 |
+
]
|
20 |
+
)
|
21 |
+
logger = logging.getLogger(__name__)
|
22 |
|
23 |
+
def setup_model():
|
24 |
+
"""
|
25 |
+
Initialize and load the model with comprehensive error handling.
|
26 |
+
|
27 |
+
Returns:
|
28 |
+
torch.nn.Module: Loaded and prepared model
|
29 |
+
"""
|
30 |
+
try:
|
31 |
+
# Configure model parameters
|
32 |
+
model_name = "resnet"
|
33 |
+
model_weights = "./pokemon_resnet.pth"
|
34 |
+
num_classes = 150
|
35 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
36 |
+
|
37 |
+
# Log device information
|
38 |
+
logger.info(f"Using device: {device}")
|
39 |
+
|
40 |
+
# Validate model weights file exists
|
41 |
+
if not os.path.exists(model_weights):
|
42 |
+
raise FileNotFoundError(f"Model weights file not found: {model_weights}")
|
43 |
+
|
44 |
+
# Initialize and load model
|
45 |
+
start_time = time.time()
|
46 |
+
model = initialize_model(model_name, num_classes).to(device)
|
47 |
+
model.load_state_dict(torch.load(model_weights, map_location=device))
|
48 |
+
model.eval() # Set the model to evaluation mode
|
49 |
+
|
50 |
+
logger.info(f"Model initialization completed in {time.time() - start_time:.2f} seconds")
|
51 |
+
return model, device
|
52 |
+
|
53 |
+
except Exception as e:
|
54 |
+
logger.error(f"Model initialization failed: {e}")
|
55 |
+
logger.error(traceback.format_exc())
|
56 |
+
raise
|
57 |
|
58 |
+
def classify_image(image, model, device):
|
59 |
+
"""
|
60 |
+
Classify an uploaded image with comprehensive error handling and logging.
|
61 |
+
|
62 |
+
Args:
|
63 |
+
image (PIL.Image): Uploaded image
|
64 |
+
model (torch.nn.Module): Loaded model
|
65 |
+
device (torch.device): Computation device
|
66 |
+
|
67 |
+
Returns:
|
68 |
+
str: Prediction result or error message
|
69 |
+
"""
|
70 |
+
if image is None:
|
71 |
+
return "No image uploaded"
|
72 |
+
|
73 |
try:
|
74 |
+
start_time = time.time()
|
75 |
+
|
76 |
+
# Preprocess image
|
77 |
+
logger.info('Preprocessing image...')
|
78 |
image_tensor = preprocess_image(image, (224, 224)).to(device)
|
79 |
+
|
80 |
# Perform inference
|
81 |
+
logger.info('Running inference...')
|
82 |
+
with torch.no_grad(): # Disable gradient computation for inference
|
83 |
+
preds = torch.max(predict(model, image_tensor), 1)[1]
|
84 |
+
|
85 |
predicted_class = CLASS_NAMES[preds.item()]
|
86 |
+
|
87 |
+
# Log performance metrics
|
88 |
+
inference_time = time.time() - start_time
|
89 |
+
logger.info(f"Image classification completed in {inference_time:.4f} seconds")
|
90 |
+
logger.info(f"Predicted class: {predicted_class}")
|
91 |
+
|
92 |
return f"Predicted class: {predicted_class}"
|
93 |
+
|
94 |
+
except Exception as e:
|
95 |
+
logger.error(f"Classification error: {e}")
|
96 |
+
logger.error(traceback.format_exc())
|
97 |
+
return f"Error processing image: {str(e)}"
|
98 |
|
99 |
+
def create_gradio_app():
|
100 |
+
"""
|
101 |
+
Create and configure the Gradio interface.
|
102 |
+
|
103 |
+
Returns:
|
104 |
+
gr.Interface: Configured Gradio interface
|
105 |
+
"""
|
106 |
+
try:
|
107 |
+
# Initialize model once
|
108 |
+
model, device = setup_model()
|
109 |
+
|
110 |
+
# Create a wrapper function that includes the model and device
|
111 |
+
def classify_wrapper(image):
|
112 |
+
return classify_image(image, model, device)
|
113 |
+
|
114 |
+
demo = gr.Interface(
|
115 |
+
fn=classify_wrapper,
|
116 |
+
inputs=gr.components.Image(type="pil", label="Upload Pokemon Image"),
|
117 |
+
outputs=gr.components.Textbox(label="Prediction"),
|
118 |
+
title="Pokemon Classifier",
|
119 |
+
description="Upload an image of a Pokemon, and the model will predict its class.",
|
120 |
+
allow_flagging="never" # Disable flagging to simplify UI
|
121 |
+
)
|
122 |
+
|
123 |
+
return demo
|
124 |
+
|
125 |
except Exception as e:
|
126 |
+
logger.critical(f"Failed to create Gradio app: {e}")
|
127 |
+
logger.critical(traceback.format_exc())
|
128 |
+
raise
|
129 |
|
130 |
+
def main():
|
131 |
+
try:
|
132 |
+
demo = create_gradio_app()
|
133 |
+
demo.launch(
|
134 |
+
server_name="0.0.0.0", # Important for Docker
|
135 |
+
server_port=7860, # Standard Hugging Face Spaces port
|
136 |
+
share=False
|
137 |
+
)
|
138 |
+
except Exception as e:
|
139 |
+
logger.critical(f"Application launch failed: {e}")
|
140 |
+
logger.critical(traceback.format_exc())
|
141 |
|
142 |
if __name__ == "__main__":
|
143 |
+
main()
|
|