DawnC commited on
Commit
61c1ceb
·
1 Parent(s): 7b60fa3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -138
app.py CHANGED
@@ -243,111 +243,6 @@ 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):
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
-
351
  async def predict(image):
352
  if image is None:
353
  return "Please upload an image to start.", None, gr.update(visible=False, choices=[]), None
@@ -359,7 +254,7 @@ async def predict(image):
359
  dogs = await detect_multiple_dogs(image)
360
 
361
  color_list = ['#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#00FFFF', '#FF00FF', '#800080', '#FFA500']
362
- all_buttons = []
363
  annotated_image = image.copy()
364
  draw = ImageDraw.Draw(annotated_image)
365
  font = ImageFont.load_default()
@@ -367,6 +262,7 @@ async def predict(image):
367
  dogs_info = ""
368
 
369
  for i, (cropped_image, detection_confidence, box) in enumerate(dogs):
 
370
  top1_prob, topk_breeds, topk_probs_percent = await predict_single_dog(cropped_image)
371
  color = color_list[i % len(color_list)]
372
  draw.rectangle(box, outline=color, width=3)
@@ -383,53 +279,67 @@ async def predict(image):
383
 
384
  elif combined_confidence >= 0.15:
385
  dogs_info += f"<p>Top 3 possible breeds:</p><ul>"
386
- dog_buttons = [] # Reset buttons for each dog
387
  for j, (breed, prob) in enumerate(zip(topk_breeds[:3], topk_probs_percent[:3])):
388
  prob = float(prob.replace('%', ''))
389
- button_id = f"Dog {i+1}: More about {breed}"
390
- dogs_info += f"""
391
- <li>
392
- <strong>{breed}</strong> ({prob:.2f}% confidence)
393
- <button class="breed-button" onclick="handle_button_click('{button_id}')">{breed}</button>
394
- </li>
395
- """
396
- dog_buttons.append(button_id)
397
  dogs_info += "</ul>"
398
- all_buttons.extend(dog_buttons) # Add this dog's buttons to the overall list
 
 
 
 
399
 
400
  else:
401
  dogs_info += "<p>The image is unclear or the breed is not in the dataset. Please upload a clearer image.</p>"
402
 
403
- dogs_info += '</div>'
404
-
 
 
405
  html_output = f"""
406
  <style>
407
  .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); }}
408
  .dog-info h2 {{ background-color: #f0f0f0; padding: 10px; margin: -15px -15px 15px -15px; border-radius: 5px 5px 0 0; }}
409
- .breed-button {{ margin-left: 10px; padding: 2px 5px; 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("Radio button not found:", button_id);
419
- }}
420
- }}
421
- </script>
422
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
423
 
424
- initial_state = {
425
- "dogs_info": dogs_info,
426
- "buttons": all_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=all_buttons), initial_state
433
 
434
  except Exception as e:
435
  error_msg = f"An error occurred: {str(e)}\n\nTraceback:\n{traceback.format_exc()}"
 
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
 
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()
 
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)
 
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()}"