DawnC commited on
Commit
98dff0d
·
1 Parent(s): 91e3c91

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +122 -91
app.py CHANGED
@@ -243,7 +243,116 @@ 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
 
@@ -261,43 +370,8 @@ async def predict(image):
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
-
298
-
299
  for i, (cropped_image, detection_confidence, box) in enumerate(dogs):
300
- buttons_html = "" # 每次迴圈重置按鈕 HTML
301
  top1_prob, topk_breeds, topk_probs_percent = await predict_single_dog(cropped_image)
302
  color = color_list[i % len(color_list)]
303
  draw.rectangle(box, outline=color, width=3)
@@ -311,39 +385,28 @@ async def predict(image):
311
  breed = topk_breeds[0]
312
  description = get_dog_description(breed)
313
  dogs_info += format_description_html(description, breed)
 
314
  elif combined_confidence >= 0.15:
315
  dogs_info += f"<p>Top 3 possible breeds:</p><ul>"
316
  for j, (breed, prob) in enumerate(zip(topk_breeds[:3], topk_probs_percent[:3])):
317
  prob = float(prob.replace('%', ''))
318
  dogs_info += f"<li><strong>{breed}</strong> ({prob:.2f}% confidence)</li>"
319
  dogs_info += "</ul>"
320
-
321
- # 生成與品種對應的 Radio 控件,放置在該品種描述區塊內
322
- radio_options = []
323
  for breed in topk_breeds[:3]:
324
  button_id = f"Dog {i+1}: More about {breed}"
325
- radio_options.append(button_id)
326
  buttons.append(button_id)
327
-
328
- # 更新 Radio 控件
329
- buttons_html = f'<div class="breed-buttons">{radio_options}</div>'
330
-
331
- # 將按鈕插入當前狗的品種描述後
332
- dogs_info += f'{buttons_html}'
333
-
334
  else:
335
  dogs_info += "<p>The image is unclear or the breed is not in the dataset. Please upload a clearer image.</p>"
336
-
337
- dogs_info += '</div>' # 結束當前狗的資訊區塊
338
-
339
- # 確保渲染到正確位置,更新 Radio 控件的選項:
340
- html_output, annotated_image, gr.update(visible=True, choices=buttons), initial_state
341
 
 
342
 
343
-
344
-
345
- buttons_html = ""
346
-
347
  html_output = f"""
348
  <style>
349
  .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); }}
@@ -353,48 +416,16 @@ async def predict(image):
353
  </style>
354
  {dogs_info}
355
  """
356
-
357
-
358
- if buttons:
359
- html_output += """
360
- <script>
361
- function handle_button_click(button_id) {
362
- const radio = document.querySelector('input[type=radio][value="' + button_id + '"]');
363
- if (radio) {
364
- radio.click();
365
- } else {
366
- console.error("Radio button not found:", button_id);
367
- }
368
- }
369
- </script>
370
- """
371
- initial_state = {
372
- "dogs_info": dogs_info,
373
- "buttons": buttons,
374
- "show_back": True,
375
- "image": annotated_image,
376
- "is_multi_dog": len(dogs) > 1,
377
- "html_output": html_output
378
- }
379
- return html_output, annotated_image, gr.update(visible=True, choices=buttons), initial_state
380
- else:
381
- initial_state = {
382
- "dogs_info": dogs_info,
383
- "buttons": [],
384
- "show_back": False,
385
- "image": annotated_image,
386
- "is_multi_dog": len(dogs) > 1,
387
- "html_output": html_output
388
- }
389
- return html_output, annotated_image, gr.update(visible=False, choices=[]), initial_state
390
 
 
391
 
392
  except Exception as e:
393
- error_msg = f"An error occurred: {str(e)}\n\nTraceback:\n{traceback.format_exc()}"
394
  print(error_msg)
395
  return error_msg, None, gr.update(visible=False, choices=[]), None
396
 
397
 
 
398
  def show_details_html(choice, previous_output, initial_state):
399
  if not choice:
400
  return previous_output, gr.update(visible=True), initial_state
 
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
+
298
+ # buttons_html = ""
299
+
300
+ # html_output = f"""
301
+ # <style>
302
+ # .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); }}
303
+ # .dog-info h2 {{ background-color: #f0f0f0; padding: 10px; margin: -15px -15px 15px -15px; border-radius: 5px 5px 0 0; }}
304
+ # .breed-buttons {{ margin-top: 10px; }}
305
+ # .breed-button {{ margin-right: 10px; margin-bottom: 10px; padding: 5px 10px; background-color: #4CAF50; color: white; border: none; border-radius: 3px; cursor: pointer; }}
306
+ # </style>
307
+ # {dogs_info}
308
+ # """
309
+
310
+
311
+ # if buttons:
312
+ # html_output += """
313
+ # <script>
314
+ # function handle_button_click(button_id) {
315
+ # const radio = document.querySelector('input[type=radio][value="' + button_id + '"]');
316
+ # if (radio) {
317
+ # radio.click();
318
+ # } else {
319
+ # console.error("Radio button not found:", button_id);
320
+ # }
321
+ # }
322
+ # </script>
323
+ # """
324
+ # initial_state = {
325
+ # "dogs_info": dogs_info,
326
+ # "buttons": buttons,
327
+ # "show_back": True,
328
+ # "image": annotated_image,
329
+ # "is_multi_dog": len(dogs) > 1,
330
+ # "html_output": html_output
331
+ # }
332
+ # return html_output, annotated_image, gr.update(visible=True, choices=buttons), initial_state
333
+ # else:
334
+ # initial_state = {
335
+ # "dogs_info": dogs_info,
336
+ # "buttons": [],
337
+ # "show_back": False,
338
+ # "image": annotated_image,
339
+ # "is_multi_dog": len(dogs) > 1,
340
+ # "html_output": html_output
341
+ # }
342
+ # return html_output, annotated_image, gr.update(visible=False, choices=[]), initial_state
343
+
344
+
345
+ # except Exception as e:
346
+ # error_msg = f"An error occurred: {str(e)}\n\nTraceback:\n{traceback.format_exc()}"
347
+ # print(error_msg)
348
+ # return error_msg, None, gr.update(visible=False, choices=[]), None
349
+
350
+
351
+
352
  async def predict(image):
353
+ # 定義初始值,避免未賦值錯誤
354
+ html_output = ""
355
+
356
  if image is None:
357
  return "Please upload an image to start.", None, gr.update(visible=False, choices=[]), None
358
 
 
370
 
371
  dogs_info = ""
372
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
373
  for i, (cropped_image, detection_confidence, box) in enumerate(dogs):
374
+ buttons_html = ""
375
  top1_prob, topk_breeds, topk_probs_percent = await predict_single_dog(cropped_image)
376
  color = color_list[i % len(color_list)]
377
  draw.rectangle(box, outline=color, width=3)
 
385
  breed = topk_breeds[0]
386
  description = get_dog_description(breed)
387
  dogs_info += format_description_html(description, breed)
388
+
389
  elif combined_confidence >= 0.15:
390
  dogs_info += f"<p>Top 3 possible breeds:</p><ul>"
391
  for j, (breed, prob) in enumerate(zip(topk_breeds[:3], topk_probs_percent[:3])):
392
  prob = float(prob.replace('%', ''))
393
  dogs_info += f"<li><strong>{breed}</strong> ({prob:.2f}% confidence)</li>"
394
  dogs_info += "</ul>"
395
+
 
 
396
  for breed in topk_breeds[:3]:
397
  button_id = f"Dog {i+1}: More about {breed}"
398
+ buttons_html += f'<button class="breed-button" onclick="handle_button_click(\'{button_id}\')">{breed}</button>'
399
  buttons.append(button_id)
400
+
401
+ # 確保按鈕插入在品種列表內部
402
+ dogs_info += f'<div class="breed-buttons">{buttons_html}</div>'
403
+
 
 
 
404
  else:
405
  dogs_info += "<p>The image is unclear or the breed is not in the dataset. Please upload a clearer image.</p>"
 
 
 
 
 
406
 
407
+ dogs_info += '</div>' # 結束當前狗的資訊區塊
408
 
409
+ # 確保 `html_output` 有賦值
 
 
 
410
  html_output = f"""
411
  <style>
412
  .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); }}
 
416
  </style>
417
  {dogs_info}
418
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
419
 
420
+ return html_output, annotated_image, gr.update(visible=True, choices=buttons), initial_state
421
 
422
  except Exception as e:
423
+ error_msg = f"An error occurred: {str(e)}"
424
  print(error_msg)
425
  return error_msg, None, gr.update(visible=False, choices=[]), None
426
 
427
 
428
+
429
  def show_details_html(choice, previous_output, initial_state):
430
  if not choice:
431
  return previous_output, gr.update(visible=True), initial_state