Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
app.py
CHANGED
@@ -204,78 +204,157 @@ def get_akc_breeds_link():
|
|
204 |
# except Exception as e:
|
205 |
# return f"An error occurred: {e}"
|
206 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
207 |
def predict(image):
|
208 |
try:
|
209 |
image_tensor = preprocess_image(image)
|
210 |
with torch.no_grad():
|
211 |
output = model(image_tensor)
|
212 |
-
|
|
|
|
|
|
|
213 |
|
|
|
214 |
probabilities = F.softmax(logits, dim=1)
|
215 |
topk_probs, topk_indices = torch.topk(probabilities, k=3)
|
216 |
|
|
|
217 |
top1_prob = topk_probs[0][0].item()
|
218 |
-
topk_breeds = [dog_breeds[idx.item()] for idx in topk_indices[0]]
|
219 |
-
topk_probs_percent = [f"{prob.item() * 100:.2f}%" for prob in topk_probs[0]]
|
220 |
|
221 |
if top1_prob >= 0.5:
|
222 |
-
#
|
223 |
-
|
|
|
224 |
description = get_dog_description(breed)
|
|
|
|
|
225 |
if isinstance(description, dict):
|
226 |
-
|
227 |
else:
|
228 |
-
|
229 |
|
230 |
-
|
231 |
-
|
232 |
|
|
|
233 |
disclaimer = ("\n\n*Disclaimer: The external link provided leads to the American Kennel Club (AKC) dog breeds page. "
|
234 |
"You may need to search for the specific breed on that page. "
|
235 |
"I am not responsible for the content on external sites. "
|
236 |
"Please refer to the AKC's terms of use and privacy policy.*")
|
237 |
-
|
238 |
|
239 |
-
return
|
240 |
|
241 |
elif top1_prob < 0.1:
|
242 |
-
#
|
243 |
-
return
|
244 |
-
|
245 |
else:
|
246 |
-
#
|
247 |
-
|
|
|
|
|
|
|
248 |
explanation = (
|
249 |
-
f"The model couldn't confidently identify the breed. Here are the top 3 possible breeds:\n
|
250 |
-
"
|
|
|
|
|
|
|
251 |
)
|
252 |
-
return explanation, gr.update(choices=topk_breeds, visible=True)
|
253 |
|
|
|
254 |
except Exception as e:
|
255 |
-
return f"An error occurred: {e}"
|
256 |
|
257 |
-
def
|
258 |
description = get_dog_description(breed)
|
|
|
|
|
259 |
if isinstance(description, dict):
|
260 |
-
|
261 |
else:
|
262 |
-
|
263 |
|
264 |
-
|
265 |
-
|
266 |
|
|
|
267 |
disclaimer = ("\n\n*Disclaimer: The external link provided leads to the American Kennel Club (AKC) dog breeds page. "
|
268 |
"You may need to search for the specific breed on that page. "
|
269 |
"I am not responsible for the content on external sites. "
|
270 |
"Please refer to the AKC's terms of use and privacy policy.*")
|
271 |
-
|
272 |
|
273 |
-
return
|
274 |
|
|
|
275 |
iface = gr.Interface(
|
276 |
fn=predict,
|
277 |
inputs=gr.Image(label="Upload a dog image", type="numpy"),
|
278 |
-
outputs=gr.Markdown(label="Prediction Results"),
|
279 |
title="<h1 style='font-family:Roboto; font-weight:bold; color:#2C3E50; text-align:center;'>🐶 Dog Breed Classifier 🔍</h1>",
|
280 |
article= 'For more details on this project and other work, feel free to visit my GitHub [Dog Breed Classifier](https://github.com/Eric-Chung-0511/Learning-Record/tree/main/Data%20Science%20Projects/Dog%20Breed%20Classifier)',
|
281 |
description="<p style='font-family:Open Sans; color:#34495E; text-align:center;'>Upload a picture of a dog, and model will predict its breed, provide detailed information, and include an extra information link!</p>",
|
@@ -326,10 +405,15 @@ iface = gr.Interface(
|
|
326 |
object-fit: cover;
|
327 |
}
|
328 |
""",
|
329 |
-
theme='default'
|
|
|
330 |
|
|
|
|
|
|
|
|
|
331 |
|
332 |
-
|
333 |
-
# Launch the app
|
334 |
if __name__ == "__main__":
|
335 |
iface.launch()
|
|
|
|
204 |
# except Exception as e:
|
205 |
# return f"An error occurred: {e}"
|
206 |
|
207 |
+
# iface = gr.Interface(
|
208 |
+
# fn=predict,
|
209 |
+
# inputs=gr.Image(label="Upload a dog image", type="numpy"),
|
210 |
+
# outputs=gr.Markdown(label="Prediction Results"),
|
211 |
+
# title="<h1 style='font-family:Roboto; font-weight:bold; color:#2C3E50; text-align:center;'>🐶 Dog Breed Classifier 🔍</h1>",
|
212 |
+
# article= 'For more details on this project and other work, feel free to visit my GitHub [Dog Breed Classifier](https://github.com/Eric-Chung-0511/Learning-Record/tree/main/Data%20Science%20Projects/Dog%20Breed%20Classifier)',
|
213 |
+
# description="<p style='font-family:Open Sans; color:#34495E; text-align:center;'>Upload a picture of a dog, and model will predict its breed, provide detailed information, and include an extra information link!</p>",
|
214 |
+
# examples=['Border_Collie.jpg',
|
215 |
+
# 'Golden_Retriever.jpeg',
|
216 |
+
# 'Saint_Bernard.jpeg',
|
217 |
+
# 'French_Bulldog.jpeg',
|
218 |
+
# 'Samoyed.jpg'],
|
219 |
+
# css = """
|
220 |
+
# .container {
|
221 |
+
# max-width: 900px;
|
222 |
+
# margin: 0 auto;
|
223 |
+
# padding: 20px;
|
224 |
+
# background-color: rgba(255, 255, 255, 0.9);
|
225 |
+
# border-radius: 15px;
|
226 |
+
# box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
|
227 |
+
# }
|
228 |
+
|
229 |
+
# .gr-form {
|
230 |
+
# display: flex;
|
231 |
+
# flex-direction: column;
|
232 |
+
# align-items: center;
|
233 |
+
# }
|
234 |
+
|
235 |
+
# .gr-box {
|
236 |
+
# width: 100%;
|
237 |
+
# max-width: 500px;
|
238 |
+
# }
|
239 |
+
|
240 |
+
# .output-markdown, .output-image {
|
241 |
+
# margin-top: 20px;
|
242 |
+
# padding: 15px;
|
243 |
+
# background-color: #f5f5f5;
|
244 |
+
# border-radius: 10px;
|
245 |
+
# }
|
246 |
+
|
247 |
+
# .examples {
|
248 |
+
# display: flex;
|
249 |
+
# justify-content: center;
|
250 |
+
# flex-wrap: wrap;
|
251 |
+
# gap: 10px;
|
252 |
+
# margin-top: 20px;
|
253 |
+
# }
|
254 |
+
|
255 |
+
# .examples img {
|
256 |
+
# width: 100px;
|
257 |
+
# height: 100px;
|
258 |
+
# object-fit: cover;
|
259 |
+
# }
|
260 |
+
# """,
|
261 |
+
# theme='default')
|
262 |
+
|
263 |
+
|
264 |
+
|
265 |
+
# # Launch the app
|
266 |
+
# if __name__ == "__main__":
|
267 |
+
# iface.launch()
|
268 |
+
|
269 |
def predict(image):
|
270 |
try:
|
271 |
image_tensor = preprocess_image(image)
|
272 |
with torch.no_grad():
|
273 |
output = model(image_tensor)
|
274 |
+
if isinstance(output, tuple):
|
275 |
+
logits = output[0]
|
276 |
+
else:
|
277 |
+
logits = output
|
278 |
|
279 |
+
# 取得預測的top k結果
|
280 |
probabilities = F.softmax(logits, dim=1)
|
281 |
topk_probs, topk_indices = torch.topk(probabilities, k=3)
|
282 |
|
283 |
+
# 檢查最高的預測機率
|
284 |
top1_prob = topk_probs[0][0].item()
|
|
|
|
|
285 |
|
286 |
if top1_prob >= 0.5:
|
287 |
+
# 正確辨識時,返回該品種資訊
|
288 |
+
predicted = topk_indices[0][0]
|
289 |
+
breed = dog_breeds[predicted.item()]
|
290 |
description = get_dog_description(breed)
|
291 |
+
akc_link = get_akc_breeds_link()
|
292 |
+
|
293 |
if isinstance(description, dict):
|
294 |
+
description_str = "\n\n".join([f"**{key}**: {value}" for key, value in description.items()])
|
295 |
else:
|
296 |
+
description_str = description
|
297 |
|
298 |
+
# 添加AKC連結
|
299 |
+
description_str += f"\n\n**Want to learn more about dog breeds?** [Visit the AKC dog breeds page]({akc_link}) and search for {breed} to find detailed information."
|
300 |
|
301 |
+
# 添加免責聲明
|
302 |
disclaimer = ("\n\n*Disclaimer: The external link provided leads to the American Kennel Club (AKC) dog breeds page. "
|
303 |
"You may need to search for the specific breed on that page. "
|
304 |
"I am not responsible for the content on external sites. "
|
305 |
"Please refer to the AKC's terms of use and privacy policy.*")
|
306 |
+
description_str += disclaimer
|
307 |
|
308 |
+
return description_str, gr.Button.update(visible=False), gr.Button.update(visible=False), gr.Button.update(visible=False)
|
309 |
|
310 |
elif top1_prob < 0.1:
|
311 |
+
# 如果信心度低於 0.1,返回提示請上傳更清晰的圖片
|
312 |
+
return "The image is too unclear or the dog breed is not in the dataset. Please upload a clearer image of the dog.", gr.Button.update(visible=False), gr.Button.update(visible=False), gr.Button.update(visible=False)
|
313 |
+
|
314 |
else:
|
315 |
+
# 不確定時,返回top 3的預測結果,並且允許點擊查看詳細資訊
|
316 |
+
topk_breeds = [dog_breeds[idx.item()] for idx in topk_indices[0]]
|
317 |
+
topk_probs_percent = [f"{prob.item() * 100:.2f}%" for prob in topk_probs[0]]
|
318 |
+
|
319 |
+
# 提供說明
|
320 |
explanation = (
|
321 |
+
f"The model couldn't confidently identify the breed. Here are the top 3 possible breeds:\n"
|
322 |
+
f"1. {topk_breeds[0]} ({topk_probs_percent[0]} confidence)\n"
|
323 |
+
f"2. {topk_breeds[1]} ({topk_probs_percent[1]} confidence)\n"
|
324 |
+
f"3. {topk_breeds[2]} ({topk_probs_percent[2]} confidence)\n\n"
|
325 |
+
"Click on a button to view more information about the breed."
|
326 |
)
|
|
|
327 |
|
328 |
+
return explanation, gr.Button.update(visible=True, value=f"More about {topk_breeds[0]}"), gr.Button.update(visible=True, value=f"More about {topk_breeds[1]}"), gr.Button.update(visible=True, value=f"More about {topk_breeds[2]}")
|
329 |
except Exception as e:
|
330 |
+
return f"An error occurred: {e}", gr.Button.update(visible=False), gr.Button.update(visible=False), gr.Button.update(visible=False)
|
331 |
|
332 |
+
def show_details(breed):
|
333 |
description = get_dog_description(breed)
|
334 |
+
akc_link = get_akc_breeds_link()
|
335 |
+
|
336 |
if isinstance(description, dict):
|
337 |
+
description_str = "\n\n".join([f"**{key}**: {value}" for key, value in description.items()])
|
338 |
else:
|
339 |
+
description_str = description
|
340 |
|
341 |
+
# 添加AKC連結
|
342 |
+
description_str += f"\n\n**Want to learn more about dog breeds?** [Visit the AKC dog breeds page]({akc_link}) and search for {breed} to find detailed information."
|
343 |
|
344 |
+
# 添加免責聲明
|
345 |
disclaimer = ("\n\n*Disclaimer: The external link provided leads to the American Kennel Club (AKC) dog breeds page. "
|
346 |
"You may need to search for the specific breed on that page. "
|
347 |
"I am not responsible for the content on external sites. "
|
348 |
"Please refer to the AKC's terms of use and privacy policy.*")
|
349 |
+
description_str += disclaimer
|
350 |
|
351 |
+
return description_str
|
352 |
|
353 |
+
# Gradio Interface
|
354 |
iface = gr.Interface(
|
355 |
fn=predict,
|
356 |
inputs=gr.Image(label="Upload a dog image", type="numpy"),
|
357 |
+
outputs=[gr.Markdown(label="Prediction Results"), gr.Button(value="View More 1", visible=False), gr.Button(value="View More 2", visible=False), gr.Button(value="View More 3", visible=False)],
|
358 |
title="<h1 style='font-family:Roboto; font-weight:bold; color:#2C3E50; text-align:center;'>🐶 Dog Breed Classifier 🔍</h1>",
|
359 |
article= 'For more details on this project and other work, feel free to visit my GitHub [Dog Breed Classifier](https://github.com/Eric-Chung-0511/Learning-Record/tree/main/Data%20Science%20Projects/Dog%20Breed%20Classifier)',
|
360 |
description="<p style='font-family:Open Sans; color:#34495E; text-align:center;'>Upload a picture of a dog, and model will predict its breed, provide detailed information, and include an extra information link!</p>",
|
|
|
405 |
object-fit: cover;
|
406 |
}
|
407 |
""",
|
408 |
+
theme='default'
|
409 |
+
)
|
410 |
|
411 |
+
# 定義按鈕的點擊事件
|
412 |
+
iface.add_event_listener('View More 1', fn=lambda: show_details(topk_breeds[0]))
|
413 |
+
iface.add_event_listener('View More 2', fn=lambda: show_details(topk_breeds[1]))
|
414 |
+
iface.add_event_listener('View More 3', fn=lambda: show_details(topk_breeds[2]))
|
415 |
|
416 |
+
# 啟動 Gradio 應用
|
|
|
417 |
if __name__ == "__main__":
|
418 |
iface.launch()
|
419 |
+
|