DawnC commited on
Commit
86a506d
โ€ข
1 Parent(s): 69161cd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -85
app.py CHANGED
@@ -453,7 +453,7 @@ async def process_single_dog(image):
453
 
454
  async def predict(image):
455
  if image is None:
456
- return "Please upload an image to start.", None, gr.update(visible=False, choices=[]), None
457
 
458
  try:
459
  if isinstance(image, np.ndarray):
@@ -467,9 +467,8 @@ async def predict(image):
467
  font = ImageFont.load_default()
468
 
469
  dogs_info = ""
470
- buttons = [] # ๅ„ฒๅญ˜ๅ”ฏไธ€็š„ๆŒ‰้ˆ• ID
471
 
472
- # ๅœจๆฏๅ€‹ๅ“็จฎๆ—้‚Š็”ŸๆˆๆŒ‰้ˆ•
473
  for i, (cropped_image, detection_confidence, box) in enumerate(dogs):
474
  top1_prob, topk_breeds, topk_probs_percent = await predict_single_dog(cropped_image)
475
  color = color_list[i % len(color_list)]
@@ -484,70 +483,38 @@ async def predict(image):
484
  breed = topk_breeds[0]
485
  description = get_dog_description(breed)
486
  dogs_info += format_description_html(description, breed)
487
-
488
  elif combined_confidence >= 0.15:
489
  dogs_info += f"<p>Top 3 possible breeds:</p><ul>"
490
  for j, (breed, prob) in enumerate(zip(topk_breeds[:3], topk_probs_percent[:3])):
491
  prob = float(prob.replace('%', ''))
492
  button_id = f"Dog {i+1}: More about {breed}"
493
- dogs_info += f"<li><strong>{breed}</strong> ({prob:.2f}% confidence)"
494
- # ๅฐ‡ Learn More ๆŒ‰้ˆ•ๆ”น็‚บๆŒ‰้ˆ•้‚่ผฏ
495
- dogs_info += f'<button class="breed-button" style="background-color: #4CAF50; color: white; padding: 5px 10px; border-radius: 3px; margin-left: 10px;" onclick="document.querySelector(\'input[value=\'{button_id}\']\').click()">Learn More</button></li>'
496
  dogs_info += "</ul>"
497
-
498
  else:
499
  dogs_info += "<p>The image is unclear or the breed is not in the dataset. Please upload a clearer image.</p>"
500
 
501
  dogs_info += '</div>'
502
-
503
- # ๅœจ็”ŸๆˆๅพŒ้™„ๅŠ  JavaScript ่™•็†ๆŒ‰้ˆ•้ปžๆ“Šไบ‹ไปถ
504
- # ็”Ÿๆˆ JavaScript ่™•็†ๆŒ‰้ˆ•้ปžๆ“Šไบ‹ไปถ
505
  html_output = f"""
506
  <style>
507
  .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); }}
508
  .dog-info h2 {{ background-color: #f0f0f0; padding: 10px; margin: -15px -15px 15px -15px; border-radius: 5px 5px 0 0; }}
509
- .breed-button {{ background-color: #4CAF50; color: white; padding: 5px 10px; border-radius: 3px; border: none; cursor: pointer; margin-left: 10px; }}
510
- .breed-button:hover {{ background-color: #45a049; }}
511
  </style>
512
 
513
  {dogs_info}
514
-
515
- <script>
516
- document.querySelectorAll('button[id^="Dog"]').forEach(button => {{
517
- console.log('Attaching event to button: ' + button.id);
518
- button.addEventListener('click', () => {{
519
- const button_id = button.id;
520
- console.log('Button clicked: ' + button_id);
521
- const radio = document.querySelector('input[type=radio][value="' + button_id + '"]');
522
- if (radio) {{
523
- radio.click();
524
- console.log('Radio button clicked for: ' + button_id);
525
- }} else {{
526
- console.error("Radio button not found for: ' + button_id);
527
- }}
528
- }});
529
- }});
530
- </script>
531
  """
532
 
533
-
534
- initial_state = {
535
- "dogs_info": dogs_info,
536
- "buttons": buttons,
537
- "image": annotated_image
538
- }
539
-
540
- return html_output, annotated_image, gr.update(visible=True, choices=buttons), initial_state
541
 
542
  except Exception as e:
543
  error_msg = f"An error occurred: {str(e)}\n\nTraceback:\n{traceback.format_exc()}"
544
  print(error_msg)
545
- return error_msg, None, gr.update(visible=False, choices=[]), None
546
-
547
 
548
- def show_details_html(choice, previous_output, initial_state):
549
  if not choice:
550
- return previous_output, gr.update(visible=True), initial_state
551
 
552
  try:
553
  breed = choice.split("More about ")[-1]
@@ -561,41 +528,13 @@ def show_details_html(choice, previous_output, initial_state):
561
  </div>
562
  """
563
 
564
- initial_state["current_description"] = html_output
565
-
566
- return html_output, gr.update(visible=True), initial_state
567
  except Exception as e:
568
  error_msg = f"An error occurred while showing details: {e}"
569
  print(error_msg)
570
- return f"<p style='color: red;'>{error_msg}</p>", gr.update(visible=True), initial_state
571
-
572
 
573
- def format_description_html(description, breed):
574
- html = "<ul style='list-style-type: none; padding-left: 0;'>"
575
- if isinstance(description, dict):
576
- for key, value in description.items():
577
- html += f"<li style='margin-bottom: 10px;'><strong>{key}:</strong> {value}</li>"
578
- elif isinstance(description, str):
579
- html += f"<li>{description}</li>"
580
- else:
581
- html += f"<li>No description available for {breed}</li>"
582
- html += "</ul>"
583
- akc_link = get_akc_breeds_link()
584
- html += f'<p><a href="{akc_link}" target="_blank">Learn more about {breed} on the AKC website</a></p>'
585
- return html
586
-
587
-
588
- def go_back(state):
589
- buttons = state.get("buttons", [])
590
- return (
591
- state["dogs_info"],
592
- state["image"],
593
- gr.update(visible=True, choices=buttons),
594
- gr.update(visible=False),
595
- state
596
- )
597
-
598
- # ไธป่ฆ็š„ Gradio ไป‹้ข
599
  with gr.Blocks() as iface:
600
  gr.HTML("<h1 style='text-align: center;'>๐Ÿถ Dog Breed Classifier ๐Ÿ”</h1>")
601
  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>")
@@ -604,30 +543,29 @@ with gr.Blocks() as iface:
604
  input_image = gr.Image(label="Upload a dog image", type="pil")
605
  output_image = gr.Image(label="Annotated Image")
606
 
607
- output = gr.HTML(label="Prediction Results")
 
608
 
609
  breed_buttons = gr.Radio(choices=[], label="More Information", visible=False)
610
 
611
- back_button = gr.Button("Back", visible=False)
612
-
613
- initial_state = gr.State()
614
 
615
  input_image.change(
616
  predict,
617
- inputs=input_image,
618
- outputs=[output, output_image, breed_buttons, initial_state]
619
  )
620
 
621
  breed_buttons.change(
622
- show_details_html,
623
- inputs=[breed_buttons, output, initial_state],
624
- outputs=[output, back_button, initial_state]
625
  )
626
 
627
  back_button.click(
628
- go_back,
629
- inputs=[initial_state],
630
- outputs=[output, output_image, breed_buttons, back_button, initial_state]
631
  )
632
 
633
  gr.Examples(
 
453
 
454
  async def predict(image):
455
  if image is None:
456
+ return "Please upload an image to start.", None, gr.update(visible=False), gr.update(visible=False)
457
 
458
  try:
459
  if isinstance(image, np.ndarray):
 
467
  font = ImageFont.load_default()
468
 
469
  dogs_info = ""
470
+ buttons = []
471
 
 
472
  for i, (cropped_image, detection_confidence, box) in enumerate(dogs):
473
  top1_prob, topk_breeds, topk_probs_percent = await predict_single_dog(cropped_image)
474
  color = color_list[i % len(color_list)]
 
483
  breed = topk_breeds[0]
484
  description = get_dog_description(breed)
485
  dogs_info += format_description_html(description, breed)
 
486
  elif combined_confidence >= 0.15:
487
  dogs_info += f"<p>Top 3 possible breeds:</p><ul>"
488
  for j, (breed, prob) in enumerate(zip(topk_breeds[:3], topk_probs_percent[:3])):
489
  prob = float(prob.replace('%', ''))
490
  button_id = f"Dog {i+1}: More about {breed}"
491
+ buttons.append(button_id)
492
+ dogs_info += f"<li><strong>{breed}</strong> ({prob:.2f}% confidence)</li>"
 
493
  dogs_info += "</ul>"
 
494
  else:
495
  dogs_info += "<p>The image is unclear or the breed is not in the dataset. Please upload a clearer image.</p>"
496
 
497
  dogs_info += '</div>'
498
+
 
 
499
  html_output = f"""
500
  <style>
501
  .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); }}
502
  .dog-info h2 {{ background-color: #f0f0f0; padding: 10px; margin: -15px -15px 15px -15px; border-radius: 5px 5px 0 0; }}
 
 
503
  </style>
504
 
505
  {dogs_info}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
506
  """
507
 
508
+ return html_output, annotated_image, gr.update(visible=True, choices=buttons), gr.update(visible=False)
 
 
 
 
 
 
 
509
 
510
  except Exception as e:
511
  error_msg = f"An error occurred: {str(e)}\n\nTraceback:\n{traceback.format_exc()}"
512
  print(error_msg)
513
+ return error_msg, None, gr.update(visible=False), gr.update(visible=False)
 
514
 
515
+ def show_breed_info(choice):
516
  if not choice:
517
+ return "", gr.update(visible=False)
518
 
519
  try:
520
  breed = choice.split("More about ")[-1]
 
528
  </div>
529
  """
530
 
531
+ return html_output, gr.update(visible=True)
 
 
532
  except Exception as e:
533
  error_msg = f"An error occurred while showing details: {e}"
534
  print(error_msg)
535
+ return f"<p style='color: red;'>{error_msg}</p>", gr.update(visible=True)
 
536
 
537
+ # Main Gradio interface
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
538
  with gr.Blocks() as iface:
539
  gr.HTML("<h1 style='text-align: center;'>๐Ÿถ Dog Breed Classifier ๐Ÿ”</h1>")
540
  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>")
 
543
  input_image = gr.Image(label="Upload a dog image", type="pil")
544
  output_image = gr.Image(label="Annotated Image")
545
 
546
+ output = gr.HTML(label="Prediction Results")
547
+ breed_info = gr.HTML(label="Breed Information")
548
 
549
  breed_buttons = gr.Radio(choices=[], label="More Information", visible=False)
550
 
551
+ back_button = gr.Button("Back to Results", visible=False)
 
 
552
 
553
  input_image.change(
554
  predict,
555
+ inputs=[input_image],
556
+ outputs=[output, output_image, breed_buttons, back_button]
557
  )
558
 
559
  breed_buttons.change(
560
+ show_breed_info,
561
+ inputs=[breed_buttons],
562
+ outputs=[breed_info, back_button]
563
  )
564
 
565
  back_button.click(
566
+ lambda: (gr.update(visible=True), gr.update(visible=True), gr.update(visible=True),
567
+ gr.update(visible=False), gr.update(visible=False)),
568
+ outputs=[output, output_image, breed_buttons, breed_info, back_button]
569
  )
570
 
571
  gr.Examples(