Upload app.py
Browse files
app.py
CHANGED
@@ -7,41 +7,68 @@ import os
|
|
7 |
import pandas as pd
|
8 |
|
9 |
# Configuration
|
10 |
-
MODEL_REPO = "Ahmedhassan54/Image-Classification"
|
11 |
MODEL_FILE = "best_model.h5"
|
12 |
|
13 |
# Download model from Hugging Face Hub
|
14 |
def load_model_from_hf():
|
15 |
try:
|
|
|
16 |
if not os.path.exists(MODEL_FILE):
|
17 |
-
print("
|
18 |
model_path = hf_hub_download(
|
19 |
repo_id=MODEL_REPO,
|
20 |
filename=MODEL_FILE,
|
21 |
cache_dir="."
|
22 |
)
|
|
|
23 |
os.system(f"cp {model_path} {MODEL_FILE}")
|
|
|
24 |
|
25 |
-
|
|
|
|
|
|
|
26 |
except Exception as e:
|
|
|
27 |
raise gr.Error(f"Model loading failed: {str(e)}")
|
28 |
|
29 |
-
model
|
|
|
|
|
|
|
|
|
|
|
30 |
|
31 |
def classify_image(image):
|
32 |
try:
|
|
|
|
|
|
|
|
|
|
|
33 |
# Convert image if needed
|
34 |
if isinstance(image, np.ndarray):
|
|
|
35 |
image = Image.fromarray(image)
|
36 |
|
37 |
# Preprocess image
|
|
|
38 |
image = image.resize((150, 150))
|
39 |
image_array = np.array(image) / 255.0
|
40 |
image_array = np.expand_dims(image_array, axis=0)
|
41 |
|
42 |
# Make prediction
|
43 |
-
|
44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
45 |
|
46 |
# Format outputs
|
47 |
label_output = {
|
@@ -55,10 +82,13 @@ def classify_image(image):
|
|
55 |
'Confidence': [1 - confidence, confidence]
|
56 |
})
|
57 |
|
|
|
|
|
|
|
58 |
return label_output, plot_data
|
59 |
|
60 |
except Exception as e:
|
61 |
-
print(f"Error: {str(e)}")
|
62 |
raise gr.Error(f"Classification error: {str(e)}")
|
63 |
|
64 |
# Custom CSS
|
@@ -69,17 +99,29 @@ css = """
|
|
69 |
footer {
|
70 |
visibility: hidden
|
71 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
72 |
"""
|
73 |
|
74 |
# Build the interface
|
75 |
with gr.Blocks(css=css, theme=gr.themes.Soft()) as demo:
|
76 |
-
gr.Markdown("
|
77 |
-
|
|
|
|
|
78 |
|
79 |
with gr.Row():
|
80 |
with gr.Column():
|
81 |
image_input = gr.Image(label="Upload Image", type="pil")
|
82 |
-
|
|
|
|
|
83 |
|
84 |
with gr.Column():
|
85 |
label_output = gr.Label(label="Predictions", num_top_classes=2)
|
@@ -103,16 +145,25 @@ with gr.Blocks(css=css, theme=gr.themes.Soft()) as demo:
|
|
103 |
inputs=image_input,
|
104 |
outputs=[label_output, confidence_bar],
|
105 |
fn=classify_image,
|
106 |
-
cache_examples=True
|
|
|
107 |
)
|
108 |
|
109 |
-
# Button
|
110 |
submit_btn.click(
|
111 |
fn=classify_image,
|
112 |
inputs=image_input,
|
113 |
outputs=[label_output, confidence_bar],
|
114 |
api_name="classify"
|
115 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
116 |
|
|
|
117 |
if __name__ == "__main__":
|
118 |
demo.launch(debug=True)
|
|
|
7 |
import pandas as pd
|
8 |
|
9 |
# Configuration
|
10 |
+
MODEL_REPO = "Ahmedhassan54/Image-Classification"
|
11 |
MODEL_FILE = "best_model.h5"
|
12 |
|
13 |
# Download model from Hugging Face Hub
|
14 |
def load_model_from_hf():
|
15 |
try:
|
16 |
+
print("Attempting to load model...")
|
17 |
if not os.path.exists(MODEL_FILE):
|
18 |
+
print("Model file not found locally. Downloading...")
|
19 |
model_path = hf_hub_download(
|
20 |
repo_id=MODEL_REPO,
|
21 |
filename=MODEL_FILE,
|
22 |
cache_dir="."
|
23 |
)
|
24 |
+
print(f"Model downloaded to: {model_path}")
|
25 |
os.system(f"cp {model_path} {MODEL_FILE}")
|
26 |
+
print("Model copied to working directory")
|
27 |
|
28 |
+
print("Loading model...")
|
29 |
+
model = tf.keras.models.load_model(MODEL_FILE)
|
30 |
+
print("Model loaded successfully!")
|
31 |
+
return model
|
32 |
except Exception as e:
|
33 |
+
print(f"Model loading failed: {str(e)}")
|
34 |
raise gr.Error(f"Model loading failed: {str(e)}")
|
35 |
|
36 |
+
# Load model when the app starts
|
37 |
+
try:
|
38 |
+
model = load_model_from_hf()
|
39 |
+
except:
|
40 |
+
model = None
|
41 |
+
print("Proceeding without model - for debugging purposes")
|
42 |
|
43 |
def classify_image(image):
|
44 |
try:
|
45 |
+
print("\nClassification started...")
|
46 |
+
|
47 |
+
# Debug: Check input type
|
48 |
+
print(f"Input type: {type(image)}")
|
49 |
+
|
50 |
# Convert image if needed
|
51 |
if isinstance(image, np.ndarray):
|
52 |
+
print("Converting numpy array to PIL Image")
|
53 |
image = Image.fromarray(image)
|
54 |
|
55 |
# Preprocess image
|
56 |
+
print("Preprocessing image...")
|
57 |
image = image.resize((150, 150))
|
58 |
image_array = np.array(image) / 255.0
|
59 |
image_array = np.expand_dims(image_array, axis=0)
|
60 |
|
61 |
# Make prediction
|
62 |
+
print("Making prediction...")
|
63 |
+
if model is None:
|
64 |
+
# For debugging when model fails to load
|
65 |
+
confidence = 0.75 # Mock value
|
66 |
+
print("Using mock prediction (model not loaded)")
|
67 |
+
else:
|
68 |
+
prediction = model.predict(image_array, verbose=0)
|
69 |
+
confidence = float(prediction[0][0])
|
70 |
+
|
71 |
+
print(f"Raw confidence: {confidence}")
|
72 |
|
73 |
# Format outputs
|
74 |
label_output = {
|
|
|
82 |
'Confidence': [1 - confidence, confidence]
|
83 |
})
|
84 |
|
85 |
+
print("Classification successful!")
|
86 |
+
print(f"Results: {label_output}")
|
87 |
+
|
88 |
return label_output, plot_data
|
89 |
|
90 |
except Exception as e:
|
91 |
+
print(f"Error during classification: {str(e)}")
|
92 |
raise gr.Error(f"Classification error: {str(e)}")
|
93 |
|
94 |
# Custom CSS
|
|
|
99 |
footer {
|
100 |
visibility: hidden
|
101 |
}
|
102 |
+
.animate-pulse {
|
103 |
+
animation: pulse 2s infinite;
|
104 |
+
}
|
105 |
+
@keyframes pulse {
|
106 |
+
0% { opacity: 1; }
|
107 |
+
50% { opacity: 0.5; }
|
108 |
+
100% { opacity: 1; }
|
109 |
+
}
|
110 |
"""
|
111 |
|
112 |
# Build the interface
|
113 |
with gr.Blocks(css=css, theme=gr.themes.Soft()) as demo:
|
114 |
+
gr.Markdown("""
|
115 |
+
# 🐾 Cat vs Dog Classifier 🦮
|
116 |
+
Upload an image to classify whether it's a cat or dog
|
117 |
+
""")
|
118 |
|
119 |
with gr.Row():
|
120 |
with gr.Column():
|
121 |
image_input = gr.Image(label="Upload Image", type="pil")
|
122 |
+
with gr.Row():
|
123 |
+
submit_btn = gr.Button("Classify", variant="primary")
|
124 |
+
clear_btn = gr.Button("Clear")
|
125 |
|
126 |
with gr.Column():
|
127 |
label_output = gr.Label(label="Predictions", num_top_classes=2)
|
|
|
145 |
inputs=image_input,
|
146 |
outputs=[label_output, confidence_bar],
|
147 |
fn=classify_image,
|
148 |
+
cache_examples=True,
|
149 |
+
label="Try these examples:"
|
150 |
)
|
151 |
|
152 |
+
# Button actions
|
153 |
submit_btn.click(
|
154 |
fn=classify_image,
|
155 |
inputs=image_input,
|
156 |
outputs=[label_output, confidence_bar],
|
157 |
api_name="classify"
|
158 |
)
|
159 |
+
|
160 |
+
clear_btn.click(
|
161 |
+
fn=lambda: [None, None, None],
|
162 |
+
inputs=None,
|
163 |
+
outputs=[image_input, label_output, confidence_bar],
|
164 |
+
show_progress=False
|
165 |
+
)
|
166 |
|
167 |
+
# For debugging in Hugging Face Spaces
|
168 |
if __name__ == "__main__":
|
169 |
demo.launch(debug=True)
|