DawnC commited on
Commit
7f6fbdb
·
1 Parent(s): 82289ff

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +2 -256
app.py CHANGED
@@ -134,25 +134,6 @@ def get_akc_breeds_link():
134
  return "https://www.akc.org/dog-breeds/"
135
 
136
 
137
- # def format_description(description, breed):
138
- # if isinstance(description, dict):
139
- # # 確保每一個描述項目換行顯示
140
- # formatted_description = "\n\n".join([f"**{key}**: {value}" for key, value in description.items()])
141
- # else:
142
- # formatted_description = description
143
-
144
- # akc_link = get_akc_breeds_link()
145
- # formatted_description += 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."
146
-
147
- # disclaimer = ("\n\n*Disclaimer: The external link provided leads to the American Kennel Club (AKC) dog breeds page. "
148
- # "You may need to search for the specific breed on that page. "
149
- # "I am not responsible for the content on external sites. "
150
- # "Please refer to the AKC's terms of use and privacy policy.*")
151
- # formatted_description += disclaimer
152
-
153
- # return formatted_description
154
-
155
-
156
  async def predict_single_dog(image):
157
  image_tensor = preprocess_image(image)
158
  with torch.no_grad():
@@ -266,242 +247,6 @@ async def process_single_dog(image):
266
  return explanation, image, buttons[0], buttons[1], buttons[2], gr.update(visible=True), initial_state
267
 
268
 
269
- # async def predict(image):
270
- # if image is None:
271
- # return "Please upload an image to start.", None, gr.update(visible=False, choices=[]), None
272
-
273
- # try:
274
- # if isinstance(image, np.ndarray):
275
- # image = Image.fromarray(image)
276
-
277
- # dogs = await detect_multiple_dogs(image)
278
-
279
- # color_list = ['#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#00FFFF', '#FF00FF', '#800080', '#FFA500']
280
- # explanations = []
281
- # buttons = []
282
- # annotated_image = image.copy()
283
- # draw = ImageDraw.Draw(annotated_image)
284
- # font = ImageFont.load_default()
285
-
286
- # for i, (cropped_image, detection_confidence, box) in enumerate(dogs):
287
- # top1_prob, topk_breeds, topk_probs_percent = await predict_single_dog(cropped_image)
288
- # color = color_list[i % len(color_list)]
289
- # draw.rectangle(box, outline=color, width=3)
290
- # draw.text((box[0] + 5, box[1] + 5), f"Dog {i+1}", fill=color, font=font) # Adjust the mark place
291
-
292
-
293
- # combined_confidence = detection_confidence * top1_prob
294
-
295
- # if top1_prob >= 0.45:
296
- # breed = topk_breeds[0]
297
- # description = get_dog_description(breed)
298
- # formatted_description = format_description(description, breed)
299
- # explanations.append(f"Dog {i+1}: {formatted_description}")
300
- # elif combined_confidence >= 0.15:
301
- # dog_explanation = f"Dog {i+1}: Top 3 possible breeds:\n"
302
- # dog_explanation += "\n".join([f"{j+1}. **{breed}** ({prob} confidence)" for j, (breed, prob) in enumerate(zip(topk_breeds[:3], topk_probs_percent[:3]))])
303
- # explanations.append(dog_explanation)
304
- # buttons.extend([f"Dog {i+1}: More about {breed}" for breed in topk_breeds[:3]])
305
- # else:
306
- # explanations.append(f"{i+1} The image is unclear or the breed is not in the dataset. Please upload a clearer image.")
307
-
308
-
309
- # final_explanation = "\n\n".join(explanations)
310
- # if buttons:
311
- # final_explanation += "\n\nClick on a button to view more information about the breed."
312
- # initial_state = {
313
- # "explanation": final_explanation,
314
- # "buttons": buttons,
315
- # "show_back": True,
316
- # "image": annotated_image,
317
- # "is_multi_dog": len(dogs) > 1,
318
- # "dogs_info": explanations
319
- # }
320
- # return final_explanation, annotated_image, gr.update(visible=True, choices=buttons), initial_state
321
- # else:
322
- # initial_state = {
323
- # "explanation": final_explanation,
324
- # "buttons": [],
325
- # "show_back": False,
326
- # "image": annotated_image,
327
- # "is_multi_dog": len(dogs) > 1,
328
- # "dogs_info": explanations
329
- # }
330
- # return final_explanation, annotated_image, gr.update(visible=False, choices=[]), initial_state
331
-
332
- # except Exception as e:
333
- # error_msg = f"An error occurred: {str(e)}\n\nTraceback:\n{traceback.format_exc()}"
334
- # print(error_msg)
335
- # return error_msg, None, gr.update(visible=False, choices=[]), None
336
-
337
-
338
- # def show_details(choice, previous_output, initial_state):
339
- # if not choice:
340
- # return previous_output, gr.update(visible=True), initial_state
341
-
342
- # try:
343
- # breed = choice.split("More about ")[-1]
344
- # description = get_dog_description(breed)
345
- # formatted_description = format_description(description, breed)
346
-
347
- # initial_state["current_description"] = formatted_description
348
- # initial_state["original_buttons"] = initial_state.get("buttons", [])
349
-
350
- # return formatted_description, gr.update(visible=True), initial_state
351
- # except Exception as e:
352
- # error_msg = f"An error occurred while showing details: {e}"
353
- # print(error_msg)
354
- # return error_msg, gr.update(visible=True), initial_state
355
-
356
- # def go_back(state):
357
- # buttons = state.get("buttons", [])
358
- # return (
359
- # state["explanation"],
360
- # state["image"],
361
- # gr.update(visible=True, choices=buttons),
362
- # gr.update(visible=False),
363
- # state
364
- # )
365
-
366
- # with gr.Blocks() as iface:
367
- # gr.HTML("<h1 style='text-align: center;'>🐶 Dog Breed Classifier 🔍</h1>")
368
- # gr.HTML("<p style='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>")
369
-
370
- # with gr.Row():
371
- # input_image = gr.Image(label="Upload a dog image", type="pil")
372
- # output_image = gr.Image(label="Annotated Image")
373
-
374
- # output = gr.Markdown(label="Prediction Results")
375
-
376
- # breed_buttons = gr.Radio(choices=[], label="More Information", visible=False)
377
-
378
- # back_button = gr.Button("Back", visible=False)
379
-
380
- # initial_state = gr.State()
381
-
382
- # input_image.change(
383
- # predict,
384
- # inputs=input_image,
385
- # outputs=[output, output_image, breed_buttons, initial_state]
386
- # )
387
-
388
- # breed_buttons.change(
389
- # show_details,
390
- # inputs=[breed_buttons, output, initial_state],
391
- # outputs=[output, back_button, initial_state]
392
- # )
393
-
394
- # back_button.click(
395
- # go_back,
396
- # inputs=[initial_state],
397
- # outputs=[output, output_image, breed_buttons, back_button, initial_state]
398
- # )
399
-
400
- # gr.Examples(
401
- # examples=['Border_Collie.jpg', 'Golden_Retriever.jpeg', 'Saint_Bernard.jpeg', 'French_Bulldog.jpeg', 'Samoyed.jpg'],
402
- # inputs=input_image
403
- # )
404
-
405
- # 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_Breed_Classifier">Dog Breed Classifier</a>')
406
-
407
-
408
- # async def predict(image):
409
- # if image is None:
410
- # return "Please upload an image to start.", None, gr.update(visible=False, choices=[]), None
411
-
412
- # try:
413
- # if isinstance(image, np.ndarray):
414
- # image = Image.fromarray(image)
415
-
416
- # dogs = await detect_multiple_dogs(image)
417
-
418
- # color_list = ['#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#00FFFF', '#FF00FF', '#800080', '#FFA500']
419
- # html_output = """
420
- # <style>
421
- # .dog-info { border: 1px solid #ddd; margin-bottom: 20px; padding: 15px; border-radius: 5px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }
422
- # .dog-info h2 { background-color: #f0f0f0; padding: 10px; margin: -15px -15px 15px -15px; border-radius: 5px 5px 0 0; }
423
- # .breed-buttons { margin-top: 10px; }
424
- # .breed-button { margin-right: 10px; margin-bottom: 10px; padding: 5px 10px; background-color: #4CAF50; color: white; border: none; border-radius: 3px; cursor: pointer; }
425
- # </style>
426
- # """
427
- # buttons = []
428
- # annotated_image = image.copy()
429
- # draw = ImageDraw.Draw(annotated_image)
430
- # font = ImageFont.load_default()
431
-
432
- # for i, (cropped_image, detection_confidence, box) in enumerate(dogs):
433
- # top1_prob, topk_breeds, topk_probs_percent = await predict_single_dog(cropped_image)
434
- # color = color_list[i % len(color_list)]
435
- # draw.rectangle(box, outline=color, width=3)
436
- # draw.text((box[0] + 5, box[1] + 5), f"Dog {i+1}", fill=color, font=font)
437
-
438
- # combined_confidence = detection_confidence * top1_prob
439
- # html_output += f'<div class="dog-info" style="border-left: 5px solid {color};">'
440
- # html_output += f'<h2>Dog {i+1}</h2>'
441
-
442
- # if top1_prob >= 0.45:
443
- # breed = topk_breeds[0]
444
- # description = get_dog_description(breed)
445
- # html_output += f"<p><strong>{breed}</strong> ({top1_prob:.2%} confidence)</p>"
446
- # html_output += format_description_html(description, breed)
447
- # button_id = f"Dog {i+1}: More about {breed}"
448
- # html_output += f'<div class="breed-buttons"><button class="breed-button" onclick="handle_button_click(\'{button_id}\')">{breed}</button></div>'
449
- # buttons.append(button_id)
450
- # elif combined_confidence >= 0.15:
451
- # html_output += f"<p>Top 3 possible breeds:</p><ul>"
452
- # for j, (breed, prob) in enumerate(zip(topk_breeds[:3], topk_probs_percent[:3])):
453
- # html_output += f"<li><strong>{breed}</strong> ({prob} confidence)</li>"
454
- # html_output += "</ul>"
455
- # html_output += '<div class="breed-buttons">'
456
- # for breed in topk_breeds[:3]:
457
- # button_id = f"Dog {i+1}: More about {breed}"
458
- # html_output += f'<button class="breed-button" onclick="handle_button_click(\'{button_id}\')">{breed}</button>'
459
- # buttons.append(button_id)
460
- # html_output += '</div>'
461
- # else:
462
- # html_output += "<p>The image is unclear or the breed is not in the dataset. Please upload a clearer image.</p>"
463
-
464
- # html_output += '</div>'
465
-
466
- # if buttons:
467
- # html_output += """
468
- # <script>
469
- # function handle_button_click(button_id) {
470
- # const radio = document.querySelector('input[type=radio][value="' + button_id + '"]');
471
- # if (radio) {
472
- # radio.click();
473
- # } else {
474
- # console.error("Radio button not found:", button_id);
475
- # }
476
- # }
477
- # </script>
478
- # """
479
- # initial_state = {
480
- # "explanation": html_output,
481
- # "buttons": buttons,
482
- # "show_back": True,
483
- # "image": annotated_image,
484
- # "is_multi_dog": len(dogs) > 1,
485
- # "dogs_info": html_output
486
- # }
487
- # return html_output, annotated_image, gr.update(visible=True, choices=buttons), initial_state
488
- # else:
489
- # initial_state = {
490
- # "explanation": html_output,
491
- # "buttons": [],
492
- # "show_back": False,
493
- # "image": annotated_image,
494
- # "is_multi_dog": len(dogs) > 1,
495
- # "dogs_info": html_output
496
- # }
497
- # return html_output, annotated_image, gr.update(visible=False, choices=[]), initial_state
498
-
499
- # except Exception as e:
500
- # error_msg = f"An error occurred: {str(e)}\n\nTraceback:\n{traceback.format_exc()}"
501
- # print(error_msg)
502
- # return error_msg, None, gr.update(visible=False, choices=[]), None
503
-
504
-
505
  async def predict(image):
506
  if image is None:
507
  return "Please upload an image to start.", None, gr.update(visible=False, choices=[]), None
@@ -539,7 +284,8 @@ async def predict(image):
539
  elif combined_confidence >= 0.15:
540
  dogs_info += f"<p>Top 3 possible breeds:</p><ul>"
541
  for j, (breed, prob) in enumerate(zip(topk_breeds[:3], topk_probs_percent[:3])):
542
- dogs_info += f"<li><strong>{breed}</strong> ({prob} confidence)</li>"
 
543
  dogs_info += "</ul>"
544
  buttons_html = '<div class="breed-buttons">' #new
545
  for breed in topk_breeds[:3]:
 
134
  return "https://www.akc.org/dog-breeds/"
135
 
136
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
  async def predict_single_dog(image):
138
  image_tensor = preprocess_image(image)
139
  with torch.no_grad():
 
247
  return explanation, image, buttons[0], buttons[1], buttons[2], gr.update(visible=True), initial_state
248
 
249
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
250
  async def predict(image):
251
  if image is None:
252
  return "Please upload an image to start.", None, gr.update(visible=False, choices=[]), None
 
284
  elif combined_confidence >= 0.15:
285
  dogs_info += f"<p>Top 3 possible breeds:</p><ul>"
286
  for j, (breed, prob) in enumerate(zip(topk_breeds[:3], topk_probs_percent[:3])):
287
+ #dogs_info += f"<li><strong>{breed}</strong> ({prob} confidence)</li>"
288
+ dogs_info += f"<li><strong>{breed}</strong> ({prob:.2f}% confidence)</li>"
289
  dogs_info += "</ul>"
290
  buttons_html = '<div class="breed-buttons">' #new
291
  for breed in topk_breeds[:3]: