Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
app.py
CHANGED
|
@@ -271,52 +271,27 @@ def predict(image):
|
|
| 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 |
-
|
| 289 |
-
breed = dog_breeds[predicted.item()]
|
| 290 |
description = get_dog_description(breed)
|
| 291 |
-
|
| 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 |
-
#
|
| 312 |
-
return "The image is too unclear or the dog breed is not in the dataset. Please upload a clearer image of the dog.",
|
| 313 |
-
|
| 314 |
else:
|
| 315 |
-
#
|
| 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"
|
|
@@ -324,24 +299,20 @@ def predict(image):
|
|
| 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.
|
| 331 |
|
| 332 |
-
def
|
| 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 |
-
|
| 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. "
|
|
@@ -350,20 +321,11 @@ def show_details(breed):
|
|
| 350 |
|
| 351 |
return description_str
|
| 352 |
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 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>",
|
| 361 |
-
examples=['Border_Collie.jpg',
|
| 362 |
-
'Golden_Retriever.jpeg',
|
| 363 |
-
'Saint_Bernard.jpeg',
|
| 364 |
-
'French_Bulldog.jpeg',
|
| 365 |
-
'Samoyed.jpg'],
|
| 366 |
-
css = """
|
| 367 |
.container {
|
| 368 |
max-width: 900px;
|
| 369 |
margin: 0 auto;
|
|
@@ -372,25 +334,14 @@ iface = gr.Interface(
|
|
| 372 |
border-radius: 15px;
|
| 373 |
box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
|
| 374 |
}
|
| 375 |
-
|
| 376 |
-
.gr-
|
| 377 |
-
display: flex;
|
| 378 |
-
flex-direction: column;
|
| 379 |
-
align-items: center;
|
| 380 |
-
}
|
| 381 |
-
|
| 382 |
-
.gr-box {
|
| 383 |
-
width: 100%;
|
| 384 |
-
max-width: 500px;
|
| 385 |
-
}
|
| 386 |
-
|
| 387 |
.output-markdown, .output-image {
|
| 388 |
margin-top: 20px;
|
| 389 |
padding: 15px;
|
| 390 |
background-color: #f5f5f5;
|
| 391 |
border-radius: 10px;
|
| 392 |
}
|
| 393 |
-
|
| 394 |
.examples {
|
| 395 |
display: flex;
|
| 396 |
justify-content: center;
|
|
@@ -398,22 +349,38 @@ iface = gr.Interface(
|
|
| 398 |
gap: 10px;
|
| 399 |
margin-top: 20px;
|
| 400 |
}
|
| 401 |
-
|
| 402 |
.examples img {
|
| 403 |
width: 100px;
|
| 404 |
height: 100px;
|
| 405 |
object-fit: cover;
|
| 406 |
}
|
| 407 |
-
"""
|
| 408 |
-
|
| 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 |
|
|
|
|
| 271 |
image_tensor = preprocess_image(image)
|
| 272 |
with torch.no_grad():
|
| 273 |
output = model(image_tensor)
|
| 274 |
+
logits = output[0] if isinstance(output, tuple) else output
|
|
|
|
|
|
|
|
|
|
| 275 |
|
|
|
|
| 276 |
probabilities = F.softmax(logits, dim=1)
|
| 277 |
topk_probs, topk_indices = torch.topk(probabilities, k=3)
|
| 278 |
|
|
|
|
| 279 |
top1_prob = topk_probs[0][0].item()
|
| 280 |
+
topk_breeds = [dog_breeds[idx.item()] for idx in topk_indices[0]]
|
| 281 |
+
topk_probs_percent = [f"{prob.item() * 100:.2f}%" for prob in topk_probs[0]]
|
| 282 |
|
| 283 |
if top1_prob >= 0.5:
|
| 284 |
+
# High confidence prediction
|
| 285 |
+
breed = topk_breeds[0]
|
|
|
|
| 286 |
description = get_dog_description(breed)
|
| 287 |
+
return format_description(description, breed), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 288 |
|
| 289 |
elif top1_prob < 0.1:
|
| 290 |
+
# Very low confidence prediction
|
| 291 |
+
return ("The image is too unclear or the dog breed is not in the dataset. Please upload a clearer image of the dog.",
|
| 292 |
+
gr.update(visible=False), gr.update(visible=False), gr.update(visible=False))
|
| 293 |
else:
|
| 294 |
+
# Medium confidence prediction
|
|
|
|
|
|
|
|
|
|
|
|
|
| 295 |
explanation = (
|
| 296 |
f"The model couldn't confidently identify the breed. Here are the top 3 possible breeds:\n"
|
| 297 |
f"1. {topk_breeds[0]} ({topk_probs_percent[0]} confidence)\n"
|
|
|
|
| 299 |
f"3. {topk_breeds[2]} ({topk_probs_percent[2]} confidence)\n\n"
|
| 300 |
"Click on a button to view more information about the breed."
|
| 301 |
)
|
| 302 |
+
return explanation, gr.update(visible=True, value=f"More about {topk_breeds[0]}"), gr.update(visible=True, value=f"More about {topk_breeds[1]}"), gr.update(visible=True, value=f"More about {topk_breeds[2]}")
|
| 303 |
|
|
|
|
| 304 |
except Exception as e:
|
| 305 |
+
return f"An error occurred: {e}", gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
|
| 306 |
|
| 307 |
+
def format_description(description, breed):
|
|
|
|
|
|
|
|
|
|
| 308 |
if isinstance(description, dict):
|
| 309 |
description_str = "\n\n".join([f"**{key}**: {value}" for key, value in description.items()])
|
| 310 |
else:
|
| 311 |
description_str = description
|
| 312 |
|
| 313 |
+
akc_link = get_akc_breeds_link()
|
| 314 |
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."
|
| 315 |
|
|
|
|
| 316 |
disclaimer = ("\n\n*Disclaimer: The external link provided leads to the American Kennel Club (AKC) dog breeds page. "
|
| 317 |
"You may need to search for the specific breed on that page. "
|
| 318 |
"I am not responsible for the content on external sites. "
|
|
|
|
| 321 |
|
| 322 |
return description_str
|
| 323 |
|
| 324 |
+
def show_details(breed):
|
| 325 |
+
description = get_dog_description(breed)
|
| 326 |
+
return format_description(description, breed)
|
| 327 |
+
|
| 328 |
+
with gr.Blocks(css="""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 329 |
.container {
|
| 330 |
max-width: 900px;
|
| 331 |
margin: 0 auto;
|
|
|
|
| 334 |
border-radius: 15px;
|
| 335 |
box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
|
| 336 |
}
|
| 337 |
+
.gr-form { display: flex; flex-direction: column; align-items: center; }
|
| 338 |
+
.gr-box { width: 100%; max-width: 500px; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 339 |
.output-markdown, .output-image {
|
| 340 |
margin-top: 20px;
|
| 341 |
padding: 15px;
|
| 342 |
background-color: #f5f5f5;
|
| 343 |
border-radius: 10px;
|
| 344 |
}
|
|
|
|
| 345 |
.examples {
|
| 346 |
display: flex;
|
| 347 |
justify-content: center;
|
|
|
|
| 349 |
gap: 10px;
|
| 350 |
margin-top: 20px;
|
| 351 |
}
|
|
|
|
| 352 |
.examples img {
|
| 353 |
width: 100px;
|
| 354 |
height: 100px;
|
| 355 |
object-fit: cover;
|
| 356 |
}
|
| 357 |
+
""") as iface:
|
| 358 |
+
|
| 359 |
+
gr.HTML("<h1 style='font-family:Roboto; font-weight:bold; color:#2C3E50; text-align:center;'>🐶 Dog Breed Classifier 🔍</h1>")
|
| 360 |
+
gr.HTML("<p style='font-family:Open Sans; color:#34495E; text-align:center;'>Upload a picture of a dog, and the model will predict its breed, provide detailed information, and include an extra information link!</p>")
|
| 361 |
+
|
| 362 |
+
with gr.Row():
|
| 363 |
+
input_image = gr.Image(label="Upload a dog image", type="numpy")
|
| 364 |
+
output = gr.Markdown(label="Prediction Results")
|
| 365 |
+
|
| 366 |
+
with gr.Row():
|
| 367 |
+
btn1 = gr.Button("View More 1", visible=False)
|
| 368 |
+
btn2 = gr.Button("View More 2", visible=False)
|
| 369 |
+
btn3 = gr.Button("View More 3", visible=False)
|
| 370 |
+
|
| 371 |
+
input_image.change(predict, inputs=input_image, outputs=[output, btn1, btn2, btn3])
|
| 372 |
+
|
| 373 |
+
btn1.click(show_details, inputs=btn1, outputs=output)
|
| 374 |
+
btn2.click(show_details, inputs=btn2, outputs=output)
|
| 375 |
+
btn3.click(show_details, inputs=btn3, outputs=output)
|
| 376 |
+
|
| 377 |
+
gr.Examples(
|
| 378 |
+
examples=['Border_Collie.jpg', 'Golden_Retriever.jpeg', 'Saint_Bernard.jpeg', 'French_Bulldog.jpeg', 'Samoyed.jpg'],
|
| 379 |
+
inputs=input_image
|
| 380 |
+
)
|
| 381 |
|
| 382 |
+
gr.HTML('For more details on this project and other work, feel free to visit my GitHub <a href="https://github.com/Eric-Chung-0511/Learning-Record/tree/main/Data%20Science%20Projects/Dog%20Breed%20Classifier">Dog Breed Classifier</a>')
|
|
|
|
|
|
|
|
|
|
| 383 |
|
|
|
|
| 384 |
if __name__ == "__main__":
|
| 385 |
iface.launch()
|
| 386 |
|