DawnC commited on
Commit
d76831d
ยท
verified ยท
1 Parent(s): e21a7d5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -57
app.py CHANGED
@@ -447,6 +447,8 @@ async def process_single_dog(image):
447
 
448
 
449
 
 
 
450
  async def predict(image):
451
  if image is None:
452
  return "Please upload an image to start.", None, gr.update(visible=False, choices=[]), None
@@ -466,87 +468,52 @@ async def predict(image):
466
  dogs_info = ""
467
 
468
  for i, (cropped_image, detection_confidence, box) in enumerate(dogs):
469
- buttons_html = ""
470
  top1_prob, topk_breeds, topk_probs_percent = await predict_single_dog(cropped_image)
471
  color = color_list[i % len(color_list)]
472
  draw.rectangle(box, outline=color, width=3)
473
  draw.text((box[0] + 5, box[1] + 5), f"Dog {i+1}", fill=color, font=font)
474
-
475
  combined_confidence = detection_confidence * top1_prob
476
  dogs_info += f'<div class="dog-info" style="border-left: 5px solid {color}; margin-bottom: 20px; padding: 15px;">'
477
  dogs_info += f'<h2>Dog {i+1}</h2>'
478
-
479
  if top1_prob >= 0.45:
480
  breed = topk_breeds[0]
481
  description = get_dog_description(breed)
482
  dogs_info += format_description_html(description, breed)
483
-
484
  elif combined_confidence >= 0.15:
485
- # ๅˆ—ๅ‡บๅ‰ไธ‰ๅ€‹ๅฏ่ƒฝ็š„ๅ“็จฎ๏ผŒไธฆๅœจๆฏๅ€‹ๅ“็จฎๆ—็”ŸๆˆๆŒ‰้ˆ•
486
  dogs_info += f"<p>Top 3 possible breeds:</p><ul>"
487
  for j, (breed, prob) in enumerate(zip(topk_breeds[:3], topk_probs_percent[:3])):
488
  prob = float(prob.replace('%', ''))
489
- # ๆฏๅ€‹ๅ“็จฎๅ็จฑๅพŒ้ข็ซ‹ๅณ็”ŸๆˆๆŒ‰้ˆ•
490
- button_id = f"Dog {i+1}: More about {breed}"
491
  dogs_info += f"<li><strong>{breed}</strong> ({prob:.2f}% confidence)"
492
- dogs_info += f'<button style="background-color: #4CAF50; color: white; border: none; padding: 5px 10px; border-radius: 3px; margin-left: 10px;" value="{button_id}" onclick="handle_button_click(\'{button_id}\')">Learn More</button></li>'
493
- buttons.append(button_id)
 
494
  dogs_info += "</ul>"
495
-
496
  else:
497
  dogs_info += "<p>The image is unclear or the breed is not in the dataset. Please upload a clearer image.</p>"
498
-
499
- dogs_info += '</div>' # ็ตๆŸ็•ถๅ‰็‹—็š„่ณ‡่จŠๅ€ๅกŠ
500
-
501
- buttons_html = ""
502
-
503
  html_output = f"""
504
  <style>
505
  .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); }}
506
  .dog-info h2 {{ background-color: #f0f0f0; padding: 10px; margin: -15px -15px 15px -15px; border-radius: 5px 5px 0 0; }}
507
- .breed-buttons {{ margin-top: 10px; }}
508
- .breed-button {{ margin-right: 10px; margin-bottom: 10px; padding: 5px 10px; background-color: #4CAF50; color: white; border: none; border-radius: 3px; cursor: pointer; }}
509
  </style>
510
  {dogs_info}
511
- """
512
-
513
- # ๆ›ดๆ–ฐ JavaScript ่™•็†ๆŒ‰้ˆ•้ปžๆ“Š
514
- html_output += """
515
- <script>
516
- function handle_button_click(button_id) {
517
- const buttons = document.querySelectorAll('input[type=radio]');
518
- buttons.forEach(radio => {
519
- if (radio.value === button_id) {
520
- radio.click();
521
- }
522
- });
523
- }
524
- </script>
525
  """
526
 
527
-
528
-
529
- if buttons:
530
- initial_state = {
531
- "dogs_info": dogs_info,
532
- "buttons": buttons,
533
- "show_back": True,
534
- "image": annotated_image,
535
- "is_multi_dog": len(dogs) > 1,
536
- "html_output": html_output
537
- }
538
- return html_output, annotated_image, gr.update(visible=True, choices=buttons), initial_state
539
- else:
540
- initial_state = {
541
- "dogs_info": dogs_info,
542
- "buttons": [],
543
- "show_back": False,
544
- "image": annotated_image,
545
- "is_multi_dog": len(dogs) > 1,
546
- "html_output": html_output
547
- }
548
- return html_output, annotated_image, gr.update(visible=False, choices=[]), initial_state
549
-
550
 
551
  except Exception as e:
552
  error_msg = f"An error occurred: {str(e)}\n\nTraceback:\n{traceback.format_exc()}"
@@ -571,7 +538,6 @@ def show_details_html(choice, previous_output, initial_state):
571
  """
572
 
573
  initial_state["current_description"] = html_output
574
- initial_state["original_buttons"] = initial_state.get("buttons", [])
575
 
576
  return html_output, gr.update(visible=True), initial_state
577
  except Exception as e:
@@ -598,14 +564,14 @@ def format_description_html(description, breed):
598
  def go_back(state):
599
  buttons = state.get("buttons", [])
600
  return (
601
- state["html_output"],
602
  state["image"],
603
  gr.update(visible=True, choices=buttons),
604
  gr.update(visible=False),
605
  state
606
  )
607
 
608
-
609
  with gr.Blocks() as iface:
610
  gr.HTML("<h1 style='text-align: center;'>๐Ÿถ Dog Breed Classifier ๐Ÿ”</h1>")
611
  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>")
@@ -650,3 +616,4 @@ with gr.Blocks() as iface:
650
 
651
  if __name__ == "__main__":
652
  iface.launch()
 
 
447
 
448
 
449
 
450
+
451
+ # ๅ‡ฝๆ•ธ้ƒจๅˆ†
452
  async def predict(image):
453
  if image is None:
454
  return "Please upload an image to start.", None, gr.update(visible=False, choices=[]), None
 
468
  dogs_info = ""
469
 
470
  for i, (cropped_image, detection_confidence, box) in enumerate(dogs):
 
471
  top1_prob, topk_breeds, topk_probs_percent = await predict_single_dog(cropped_image)
472
  color = color_list[i % len(color_list)]
473
  draw.rectangle(box, outline=color, width=3)
474
  draw.text((box[0] + 5, box[1] + 5), f"Dog {i+1}", fill=color, font=font)
475
+
476
  combined_confidence = detection_confidence * top1_prob
477
  dogs_info += f'<div class="dog-info" style="border-left: 5px solid {color}; margin-bottom: 20px; padding: 15px;">'
478
  dogs_info += f'<h2>Dog {i+1}</h2>'
479
+
480
  if top1_prob >= 0.45:
481
  breed = topk_breeds[0]
482
  description = get_dog_description(breed)
483
  dogs_info += format_description_html(description, breed)
484
+
485
  elif combined_confidence >= 0.15:
 
486
  dogs_info += f"<p>Top 3 possible breeds:</p><ul>"
487
  for j, (breed, prob) in enumerate(zip(topk_breeds[:3], topk_probs_percent[:3])):
488
  prob = float(prob.replace('%', ''))
489
+ # ๅŠ ๅ…ฅๆฏๅ€‹ๅ“็จฎ็š„ๆŒ‰้ˆ•
 
490
  dogs_info += f"<li><strong>{breed}</strong> ({prob:.2f}% confidence)"
491
+ button_id = f"Dog {i+1}: More about {breed}"
492
+ buttons.append(button_id) # ็‚บๆฏๅ€‹ๅ“็จฎๅŠ ๅ…ฅๆŒ‰้ˆ•
493
+ dogs_info += f'<button value="{button_id}" class="gr-button" style="margin-left: 10px;">Learn More</button></li>'
494
  dogs_info += "</ul>"
495
+
496
  else:
497
  dogs_info += "<p>The image is unclear or the breed is not in the dataset. Please upload a clearer image.</p>"
498
+
499
+ dogs_info += '</div>'
500
+
 
 
501
  html_output = f"""
502
  <style>
503
  .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); }}
504
  .dog-info h2 {{ background-color: #f0f0f0; padding: 10px; margin: -15px -15px 15px -15px; border-radius: 5px 5px 0 0; }}
505
+ .gr-button {{ margin-right: 10px; margin-bottom: 10px; padding: 5px 10px; background-color: #4CAF50; color: white; border: none; border-radius: 3px; cursor: pointer; }}
 
506
  </style>
507
  {dogs_info}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
508
  """
509
 
510
+ initial_state = {
511
+ "dogs_info": dogs_info,
512
+ "buttons": buttons,
513
+ "image": annotated_image
514
+ }
515
+
516
+ return html_output, annotated_image, gr.update(visible=True, choices=buttons), initial_state
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
517
 
518
  except Exception as e:
519
  error_msg = f"An error occurred: {str(e)}\n\nTraceback:\n{traceback.format_exc()}"
 
538
  """
539
 
540
  initial_state["current_description"] = html_output
 
541
 
542
  return html_output, gr.update(visible=True), initial_state
543
  except Exception as e:
 
564
  def go_back(state):
565
  buttons = state.get("buttons", [])
566
  return (
567
+ state["dogs_info"],
568
  state["image"],
569
  gr.update(visible=True, choices=buttons),
570
  gr.update(visible=False),
571
  state
572
  )
573
 
574
+ # ไธป่ฆ็š„ Gradio ไป‹้ข
575
  with gr.Blocks() as iface:
576
  gr.HTML("<h1 style='text-align: center;'>๐Ÿถ Dog Breed Classifier ๐Ÿ”</h1>")
577
  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>")
 
616
 
617
  if __name__ == "__main__":
618
  iface.launch()
619
+