Upload app.py
Browse files
app.py
CHANGED
@@ -15,112 +15,86 @@ logger = logging.getLogger(__name__)
|
|
15 |
MODEL_REPO = "Ahmedhassan54/Image-Classification"
|
16 |
MODEL_FILE = "best_model.h5"
|
17 |
|
18 |
-
#
|
19 |
-
|
|
|
|
|
|
|
20 |
try:
|
21 |
-
logger.info("
|
22 |
-
|
23 |
-
# Check if model exists in cache
|
24 |
model_path = hf_hub_download(
|
25 |
repo_id=MODEL_REPO,
|
26 |
filename=MODEL_FILE,
|
27 |
cache_dir=".",
|
28 |
-
force_download=True
|
29 |
)
|
30 |
-
logger.info(f"Model
|
31 |
|
32 |
-
#
|
33 |
-
|
|
|
|
|
|
|
34 |
model = tf.keras.models.load_model(model_path)
|
35 |
-
logger.info("Model loaded successfully!")
|
36 |
-
return model
|
37 |
|
38 |
except Exception as e:
|
39 |
-
logger.error(f"Model loading failed: {str(e)}")
|
40 |
-
|
|
|
41 |
|
42 |
-
# Load model when
|
43 |
-
|
44 |
-
model = load_model_from_hf()
|
45 |
-
except Exception as e:
|
46 |
-
model = None
|
47 |
-
logger.error(f"Proceeding without model due to: {str(e)}")
|
48 |
|
49 |
def classify_image(image):
|
50 |
try:
|
51 |
-
logger.info("\nClassification started...")
|
52 |
-
|
53 |
-
# Debug: Check input type
|
54 |
-
logger.info(f"Input type: {type(image)}")
|
55 |
-
|
56 |
if image is None:
|
57 |
-
raise
|
|
|
|
|
58 |
|
59 |
-
# Convert
|
60 |
if isinstance(image, np.ndarray):
|
61 |
-
logger.info("Converting numpy array to PIL Image")
|
62 |
image = Image.fromarray(image)
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
# Preprocess image
|
67 |
-
logger.info("Preprocessing image...")
|
68 |
image = image.resize((150, 150))
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
|
75 |
-
logger.info(f"Image array shape: {image_array.shape}")
|
76 |
-
|
77 |
-
# Make prediction
|
78 |
-
logger.info("Making prediction...")
|
79 |
if model is None:
|
80 |
-
raise gr.Error("Model
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
confidence
|
86 |
-
|
87 |
-
|
88 |
-
# Format outputs
|
89 |
-
label_output = {
|
90 |
"Cat": round(1 - confidence, 4),
|
91 |
"Dog": round(confidence, 4)
|
92 |
}
|
93 |
|
94 |
-
# Create dataframe for bar plot
|
95 |
plot_data = pd.DataFrame({
|
96 |
'Class': ['Cat', 'Dog'],
|
97 |
'Confidence': [1 - confidence, confidence]
|
98 |
})
|
99 |
|
100 |
-
|
101 |
-
logger.info(f"Results: {label_output}")
|
102 |
-
|
103 |
-
return label_output, plot_data
|
104 |
|
105 |
except Exception as e:
|
106 |
-
logger.error(f"
|
107 |
-
raise gr.Error(f"
|
108 |
|
109 |
-
# Custom CSS
|
110 |
css = """
|
111 |
-
.gradio-container {
|
112 |
-
|
113 |
-
}
|
114 |
-
footer {
|
115 |
-
visibility: hidden
|
116 |
-
}
|
117 |
-
.error-message {
|
118 |
-
color: red !important;
|
119 |
-
font-weight: bold !important;
|
120 |
-
}
|
121 |
"""
|
122 |
|
123 |
-
# Build the interface
|
124 |
with gr.Blocks(css=css, theme=gr.themes.Soft()) as demo:
|
125 |
gr.Markdown("""
|
126 |
# ๐พ Cat vs Dog Classifier ๐ฆฎ
|
@@ -131,23 +105,18 @@ with gr.Blocks(css=css, theme=gr.themes.Soft()) as demo:
|
|
131 |
with gr.Column():
|
132 |
image_input = gr.Image(label="Upload Image", type="pil")
|
133 |
with gr.Row():
|
134 |
-
submit_btn = gr.Button("Classify", variant="primary")
|
135 |
-
clear_btn = gr.Button("Clear")
|
136 |
|
137 |
with gr.Column():
|
138 |
-
label_output = gr.Label(label="Predictions"
|
139 |
confidence_bar = gr.BarPlot(
|
140 |
pd.DataFrame({'Class': ['Cat', 'Dog'], 'Confidence': [0.5, 0.5]}),
|
141 |
-
x="Class",
|
142 |
-
|
143 |
-
y_lim=[0,1],
|
144 |
-
title="Confidence Scores",
|
145 |
-
width=400,
|
146 |
-
height=300,
|
147 |
-
container=False
|
148 |
)
|
149 |
|
150 |
-
#
|
151 |
gr.Examples(
|
152 |
examples=[
|
153 |
["https://upload.wikimedia.org/wikipedia/commons/1/15/Cat_August_2010-4.jpg"],
|
@@ -156,8 +125,7 @@ with gr.Blocks(css=css, theme=gr.themes.Soft()) as demo:
|
|
156 |
inputs=image_input,
|
157 |
outputs=[label_output, confidence_bar],
|
158 |
fn=classify_image,
|
159 |
-
cache_examples=True
|
160 |
-
label="Try these examples:"
|
161 |
)
|
162 |
|
163 |
# Button actions
|
@@ -165,16 +133,14 @@ with gr.Blocks(css=css, theme=gr.themes.Soft()) as demo:
|
|
165 |
fn=classify_image,
|
166 |
inputs=image_input,
|
167 |
outputs=[label_output, confidence_bar],
|
168 |
-
api_name="
|
169 |
)
|
170 |
|
171 |
clear_btn.click(
|
172 |
fn=lambda: [None, pd.DataFrame({'Class': ['Cat', 'Dog'], 'Confidence': [0.5, 0.5]})],
|
173 |
inputs=None,
|
174 |
-
outputs=[image_input, confidence_bar]
|
175 |
-
show_progress=False
|
176 |
)
|
177 |
|
178 |
-
# Launch the app
|
179 |
if __name__ == "__main__":
|
180 |
demo.launch(debug=True)
|
|
|
15 |
MODEL_REPO = "Ahmedhassan54/Image-Classification"
|
16 |
MODEL_FILE = "best_model.h5"
|
17 |
|
18 |
+
# Initialize model to None
|
19 |
+
model = None
|
20 |
+
|
21 |
+
def load_model():
|
22 |
+
global model
|
23 |
try:
|
24 |
+
logger.info("โณ Downloading model...")
|
|
|
|
|
25 |
model_path = hf_hub_download(
|
26 |
repo_id=MODEL_REPO,
|
27 |
filename=MODEL_FILE,
|
28 |
cache_dir=".",
|
29 |
+
force_download=True
|
30 |
)
|
31 |
+
logger.info(f"๐ Model path: {model_path}")
|
32 |
|
33 |
+
# Verify file exists
|
34 |
+
if not os.path.exists(model_path):
|
35 |
+
raise FileNotFoundError(f"Model file not found at {model_path}")
|
36 |
+
|
37 |
+
logger.info("๐ Loading TensorFlow model...")
|
38 |
model = tf.keras.models.load_model(model_path)
|
39 |
+
logger.info("โ
Model loaded successfully!")
|
|
|
40 |
|
41 |
except Exception as e:
|
42 |
+
logger.error(f"โ Model loading failed: {str(e)}")
|
43 |
+
model = None
|
44 |
+
raise gr.Error(f"Model loading failed. Check logs for details.")
|
45 |
|
46 |
+
# Load model when app starts
|
47 |
+
load_model()
|
|
|
|
|
|
|
|
|
48 |
|
49 |
def classify_image(image):
|
50 |
try:
|
|
|
|
|
|
|
|
|
|
|
51 |
if image is None:
|
52 |
+
raise gr.Error("Please upload an image first")
|
53 |
+
|
54 |
+
logger.info("๐ผ๏ธ Processing image...")
|
55 |
|
56 |
+
# Convert to PIL Image if numpy array
|
57 |
if isinstance(image, np.ndarray):
|
|
|
58 |
image = Image.fromarray(image)
|
59 |
+
|
60 |
+
# Resize and normalize
|
|
|
|
|
|
|
61 |
image = image.resize((150, 150))
|
62 |
+
img_array = np.array(image) / 255.0
|
63 |
+
if len(img_array.shape) == 3:
|
64 |
+
img_array = np.expand_dims(img_array, axis=0)
|
65 |
+
|
66 |
+
logger.info(f"๐ Input shape: {img_array.shape}")
|
67 |
|
|
|
|
|
|
|
|
|
68 |
if model is None:
|
69 |
+
raise gr.Error("Model not loaded - using demo mode")
|
70 |
+
return {"Cat": 0.5, "Dog": 0.5}, pd.DataFrame({'Class': ['Cat', 'Dog'], 'Confidence': [0.5, 0.5]})
|
71 |
+
|
72 |
+
pred = model.predict(img_array, verbose=0)
|
73 |
+
confidence = float(pred[0][0])
|
74 |
+
logger.info(f"๐ฎ Prediction confidence: {confidence}")
|
75 |
+
|
76 |
+
results = {
|
|
|
|
|
77 |
"Cat": round(1 - confidence, 4),
|
78 |
"Dog": round(confidence, 4)
|
79 |
}
|
80 |
|
|
|
81 |
plot_data = pd.DataFrame({
|
82 |
'Class': ['Cat', 'Dog'],
|
83 |
'Confidence': [1 - confidence, confidence]
|
84 |
})
|
85 |
|
86 |
+
return results, plot_data
|
|
|
|
|
|
|
87 |
|
88 |
except Exception as e:
|
89 |
+
logger.error(f"๐ฅ Classification error: {str(e)}")
|
90 |
+
raise gr.Error(f"Error processing image: {str(e)}")
|
91 |
|
|
|
92 |
css = """
|
93 |
+
.gradio-container { max-width: 900px; margin: auto; }
|
94 |
+
footer { visibility: hidden; }
|
95 |
+
.progress-bar { color: #ff4d4d !important; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
96 |
"""
|
97 |
|
|
|
98 |
with gr.Blocks(css=css, theme=gr.themes.Soft()) as demo:
|
99 |
gr.Markdown("""
|
100 |
# ๐พ Cat vs Dog Classifier ๐ฆฎ
|
|
|
105 |
with gr.Column():
|
106 |
image_input = gr.Image(label="Upload Image", type="pil")
|
107 |
with gr.Row():
|
108 |
+
submit_btn = gr.Button("Classify ๐", variant="primary")
|
109 |
+
clear_btn = gr.Button("Clear ๐๏ธ")
|
110 |
|
111 |
with gr.Column():
|
112 |
+
label_output = gr.Label(label="Predictions")
|
113 |
confidence_bar = gr.BarPlot(
|
114 |
pd.DataFrame({'Class': ['Cat', 'Dog'], 'Confidence': [0.5, 0.5]}),
|
115 |
+
x="Class", y="Confidence", y_lim=[0,1],
|
116 |
+
title="Confidence Scores", width=400, height=300
|
|
|
|
|
|
|
|
|
|
|
117 |
)
|
118 |
|
119 |
+
# Examples
|
120 |
gr.Examples(
|
121 |
examples=[
|
122 |
["https://upload.wikimedia.org/wikipedia/commons/1/15/Cat_August_2010-4.jpg"],
|
|
|
125 |
inputs=image_input,
|
126 |
outputs=[label_output, confidence_bar],
|
127 |
fn=classify_image,
|
128 |
+
cache_examples=True
|
|
|
129 |
)
|
130 |
|
131 |
# Button actions
|
|
|
133 |
fn=classify_image,
|
134 |
inputs=image_input,
|
135 |
outputs=[label_output, confidence_bar],
|
136 |
+
api_name="predict"
|
137 |
)
|
138 |
|
139 |
clear_btn.click(
|
140 |
fn=lambda: [None, pd.DataFrame({'Class': ['Cat', 'Dog'], 'Confidence': [0.5, 0.5]})],
|
141 |
inputs=None,
|
142 |
+
outputs=[image_input, confidence_bar]
|
|
|
143 |
)
|
144 |
|
|
|
145 |
if __name__ == "__main__":
|
146 |
demo.launch(debug=True)
|