DawnC commited on
Commit
3a0553e
·
verified ·
1 Parent(s): 5839567

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +137 -47
app.py CHANGED
@@ -243,9 +243,113 @@ async def process_single_dog(image):
243
  return explanation, image, buttons[0], buttons[1], buttons[2], gr.update(visible=True), initial_state
244
 
245
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
246
  async def predict(image):
247
  if image is None:
248
- return "Please upload an image to start.", None, gr.update(visible=False, choices=[]), None
249
 
250
  try:
251
  if isinstance(image, np.ndarray):
@@ -262,7 +366,6 @@ async def predict(image):
262
  dogs_info = ""
263
 
264
  for i, (cropped_image, detection_confidence, box) in enumerate(dogs):
265
- buttons_html = ""
266
  top1_prob, topk_breeds, topk_probs_percent = await predict_single_dog(cropped_image)
267
  color = color_list[i % len(color_list)]
268
  draw.rectangle(box, outline=color, width=3)
@@ -270,7 +373,7 @@ async def predict(image):
270
 
271
  combined_confidence = detection_confidence * top1_prob
272
  dogs_info += f'<div class="dog-info" style="border-left: 5px solid {color}; margin-bottom: 20px; padding: 15px;">'
273
- dogs_info += f'<h2>Dog {i+1}</h2>'
274
 
275
  if top1_prob >= 0.45:
276
  breed = topk_breeds[0]
@@ -278,24 +381,26 @@ async def predict(image):
278
  dogs_info += format_description_html(description, breed)
279
 
280
  elif combined_confidence >= 0.15:
281
- dogs_info += f"<p>Top 3 possible breeds:</p><ul>"
282
  for j, (breed, prob) in enumerate(zip(topk_breeds[:3], topk_probs_percent[:3])):
283
  prob = float(prob.replace('%', ''))
284
- dogs_info += f"<li><strong>{breed}</strong> ({prob:.2f}% confidence)</li>"
285
  dogs_info += "</ul>"
286
 
 
 
287
  for breed in topk_breeds[:3]:
288
- button_id = f"Dog {i+1}: More about {breed}"
289
- buttons_html += f'<button class="breed-button" onclick="handle_button_click(\'{button_id}\')">{breed}</button>'
290
  buttons.append(button_id)
 
291
 
292
  else:
293
- dogs_info += "<p>The image is unclear or the breed is not in the dataset. Please upload a clearer image.</p>"
294
 
295
- dogs_info += '</div>'
296
-
297
- buttons_html = ""
298
-
299
  html_output = f"""
300
  <style>
301
  .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); }}
@@ -304,45 +409,30 @@ async def predict(image):
304
  .breed-button {{ margin-right: 10px; margin-bottom: 10px; padding: 5px 10px; background-color: #4CAF50; color: white; border: none; border-radius: 3px; cursor: pointer; }}
305
  </style>
306
  {dogs_info}
 
 
 
 
 
 
 
 
 
 
307
  """
308
-
309
-
310
- if buttons:
311
- html_output += """
312
- <script>
313
- function handle_button_click(button_id) {
314
- const radio = document.querySelector('input[type=radio][value="' + button_id + '"]');
315
- if (radio) {
316
- radio.click();
317
- } else {
318
- console.error("Radio button not found:", button_id);
319
- }
320
- }
321
- </script>
322
- """
323
- initial_state = {
324
- "dogs_info": dogs_info,
325
- "buttons": buttons,
326
- "show_back": True,
327
- "image": annotated_image,
328
- "is_multi_dog": len(dogs) > 1,
329
- "html_output": html_output
330
- }
331
- return html_output, annotated_image, gr.update(visible=True, choices=buttons), initial_state
332
- else:
333
- initial_state = {
334
- "dogs_info": dogs_info,
335
- "buttons": [],
336
- "show_back": False,
337
- "image": annotated_image,
338
- "is_multi_dog": len(dogs) > 1,
339
- "html_output": html_output
340
- }
341
- return html_output, annotated_image, gr.update(visible=False, choices=[]), initial_state
342
 
 
 
 
 
 
 
 
 
 
343
 
344
  except Exception as e:
345
- error_msg = f"An error occurred: {str(e)}\n\nTraceback:\n{traceback.format_exc()}"
346
  print(error_msg)
347
  return error_msg, None, gr.update(visible=False, choices=[]), None
348
 
 
243
  return explanation, image, buttons[0], buttons[1], buttons[2], gr.update(visible=True), initial_state
244
 
245
 
246
+ # async def predict(image):
247
+ # if image is None:
248
+ # return "Please upload an image to start.", None, gr.update(visible=False, choices=[]), None
249
+
250
+ # try:
251
+ # if isinstance(image, np.ndarray):
252
+ # image = Image.fromarray(image)
253
+
254
+ # dogs = await detect_multiple_dogs(image)
255
+
256
+ # color_list = ['#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#00FFFF', '#FF00FF', '#800080', '#FFA500']
257
+ # buttons = []
258
+ # annotated_image = image.copy()
259
+ # draw = ImageDraw.Draw(annotated_image)
260
+ # font = ImageFont.load_default()
261
+
262
+ # dogs_info = ""
263
+
264
+ # for i, (cropped_image, detection_confidence, box) in enumerate(dogs):
265
+ # buttons_html = ""
266
+ # top1_prob, topk_breeds, topk_probs_percent = await predict_single_dog(cropped_image)
267
+ # color = color_list[i % len(color_list)]
268
+ # draw.rectangle(box, outline=color, width=3)
269
+ # draw.text((box[0] + 5, box[1] + 5), f"Dog {i+1}", fill=color, font=font)
270
+
271
+ # combined_confidence = detection_confidence * top1_prob
272
+ # dogs_info += f'<div class="dog-info" style="border-left: 5px solid {color}; margin-bottom: 20px; padding: 15px;">'
273
+ # dogs_info += f'<h2>Dog {i+1}</h2>'
274
+
275
+ # if top1_prob >= 0.45:
276
+ # breed = topk_breeds[0]
277
+ # description = get_dog_description(breed)
278
+ # dogs_info += format_description_html(description, breed)
279
+
280
+ # elif combined_confidence >= 0.15:
281
+ # dogs_info += f"<p>Top 3 possible breeds:</p><ul>"
282
+ # for j, (breed, prob) in enumerate(zip(topk_breeds[:3], topk_probs_percent[:3])):
283
+ # prob = float(prob.replace('%', ''))
284
+ # dogs_info += f"<li><strong>{breed}</strong> ({prob:.2f}% confidence)</li>"
285
+ # dogs_info += "</ul>"
286
+
287
+ # for breed in topk_breeds[:3]:
288
+ # button_id = f"Dog {i+1}: More about {breed}"
289
+ # buttons_html += f'<button class="breed-button" onclick="handle_button_click(\'{button_id}\')">{breed}</button>'
290
+ # buttons.append(button_id)
291
+
292
+ # else:
293
+ # dogs_info += "<p>The image is unclear or the breed is not in the dataset. Please upload a clearer image.</p>"
294
+
295
+ # dogs_info += '</div>'
296
+
297
+ # buttons_html = ""
298
+
299
+ # html_output = f"""
300
+ # <style>
301
+ # .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); }}
302
+ # .dog-info h2 {{ background-color: #f0f0f0; padding: 10px; margin: -15px -15px 15px -15px; border-radius: 5px 5px 0 0; }}
303
+ # .breed-buttons {{ margin-top: 10px; }}
304
+ # .breed-button {{ margin-right: 10px; margin-bottom: 10px; padding: 5px 10px; background-color: #4CAF50; color: white; border: none; border-radius: 3px; cursor: pointer; }}
305
+ # </style>
306
+ # {dogs_info}
307
+ # """
308
+
309
+
310
+ # if buttons:
311
+ # html_output += """
312
+ # <script>
313
+ # function handle_button_click(button_id) {
314
+ # const radio = document.querySelector('input[type=radio][value="' + button_id + '"]');
315
+ # if (radio) {
316
+ # radio.click();
317
+ # } else {
318
+ # console.error("Radio button not found:", button_id);
319
+ # }
320
+ # }
321
+ # </script>
322
+ # """
323
+ # initial_state = {
324
+ # "dogs_info": dogs_info,
325
+ # "buttons": buttons,
326
+ # "show_back": True,
327
+ # "image": annotated_image,
328
+ # "is_multi_dog": len(dogs) > 1,
329
+ # "html_output": html_output
330
+ # }
331
+ # return html_output, annotated_image, gr.update(visible=True, choices=buttons), initial_state
332
+ # else:
333
+ # initial_state = {
334
+ # "dogs_info": dogs_info,
335
+ # "buttons": [],
336
+ # "show_back": False,
337
+ # "image": annotated_image,
338
+ # "is_multi_dog": len(dogs) > 1,
339
+ # "html_output": html_output
340
+ # }
341
+ # return html_output, annotated_image, gr.update(visible=False, choices=[]), initial_state
342
+
343
+
344
+ # except Exception as e:
345
+ # error_msg = f"An error occurred: {str(e)}\n\nTraceback:\n{traceback.format_exc()}"
346
+ # print(error_msg)
347
+ # return error_msg, None, gr.update(visible=False, choices=[]), None
348
+
349
+
350
  async def predict(image):
351
  if image is None:
352
+ return "請上傳一張圖片開始。", None, gr.update(visible=False, choices=[]), None
353
 
354
  try:
355
  if isinstance(image, np.ndarray):
 
366
  dogs_info = ""
367
 
368
  for i, (cropped_image, detection_confidence, box) in enumerate(dogs):
 
369
  top1_prob, topk_breeds, topk_probs_percent = await predict_single_dog(cropped_image)
370
  color = color_list[i % len(color_list)]
371
  draw.rectangle(box, outline=color, width=3)
 
373
 
374
  combined_confidence = detection_confidence * top1_prob
375
  dogs_info += f'<div class="dog-info" style="border-left: 5px solid {color}; margin-bottom: 20px; padding: 15px;">'
376
+ dogs_info += f'<h2>狗狗 {i+1}</h2>'
377
 
378
  if top1_prob >= 0.45:
379
  breed = topk_breeds[0]
 
381
  dogs_info += format_description_html(description, breed)
382
 
383
  elif combined_confidence >= 0.15:
384
+ dogs_info += f"<p>前3個可能的品種:</p><ul>"
385
  for j, (breed, prob) in enumerate(zip(topk_breeds[:3], topk_probs_percent[:3])):
386
  prob = float(prob.replace('%', ''))
387
+ dogs_info += f"<li><strong>{breed}</strong> ({prob:.2f}% 信心度)</li>"
388
  dogs_info += "</ul>"
389
 
390
+ # 修改:直接在每隻狗的資訊下方添加按鈕
391
+ dogs_info += '<div class="breed-buttons">'
392
  for breed in topk_breeds[:3]:
393
+ button_id = f"狗狗 {i+1}: 更多關於 {breed}"
394
+ dogs_info += f'<button class="breed-button" onclick="handle_button_click(\'{button_id}\')">{breed}</button>'
395
  buttons.append(button_id)
396
+ dogs_info += '</div>'
397
 
398
  else:
399
+ dogs_info += "<p>圖像不清晰或該品種不在數據集中。請上傳一張更清晰的圖片。</p>"
400
 
401
+ dogs_info += '</div>'
402
+
403
+ # 修改:更新HTML輸出,包含內聯的按鈕和處理點擊的JavaScript
 
404
  html_output = f"""
405
  <style>
406
  .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); }}
 
409
  .breed-button {{ margin-right: 10px; margin-bottom: 10px; padding: 5px 10px; background-color: #4CAF50; color: white; border: none; border-radius: 3px; cursor: pointer; }}
410
  </style>
411
  {dogs_info}
412
+ <script>
413
+ function handle_button_click(button_id) {{
414
+ const radio = document.querySelector('input[type=radio][value="' + button_id + '"]');
415
+ if (radio) {{
416
+ radio.click();
417
+ }} else {{
418
+ console.error("找不到對應的單選按鈕:", button_id);
419
+ }}
420
+ }}
421
+ </script>
422
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
423
 
424
+ initial_state = {
425
+ "dogs_info": dogs_info,
426
+ "buttons": buttons,
427
+ "show_back": True,
428
+ "image": annotated_image,
429
+ "is_multi_dog": len(dogs) > 1,
430
+ "html_output": html_output
431
+ }
432
+ return html_output, annotated_image, gr.update(visible=True, choices=buttons), initial_state
433
 
434
  except Exception as e:
435
+ error_msg = f"發生錯誤:{str(e)}\n\n追蹤信息:\n{traceback.format_exc()}"
436
  print(error_msg)
437
  return error_msg, None, gr.update(visible=False, choices=[]), None
438