DawnC commited on
Commit
6f8b9bb
1 Parent(s): df133bb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +5 -47
app.py CHANGED
@@ -271,11 +271,10 @@ Please refer to the AKC's terms of use and privacy policy.*
271
  """
272
  return formatted_description
273
 
274
- # 預測單隻狗的品種
275
  async def predict_single_dog(image):
276
  image_tensor = preprocess_image(image)
277
  with torch.no_grad():
278
- output = model(image_tensor)
279
  logits = output[0] if isinstance(output, tuple) else output
280
  probabilities = F.softmax(logits, dim=1)
281
  topk_probs, topk_indices = torch.topk(probabilities, k=3)
@@ -309,7 +308,7 @@ async def predict(image):
309
  if isinstance(image, np.ndarray):
310
  image = Image.fromarray(image)
311
 
312
- # First, try to predict without YOLO
313
  top1_prob, topk_breeds, topk_probs_percent = await predict_single_dog(image)
314
 
315
  if top1_prob >= 0.5:
@@ -329,50 +328,9 @@ async def predict(image):
329
  breed_buttons = [f"More about {breed}" for breed in topk_breeds[:3]]
330
  return explanation, image, gr.update(visible=True, choices=breed_buttons), gr.update(visible=False), gr.update(visible=False)
331
 
332
- elif top1_prob < 0.2:
333
- # Only use YOLO if the confidence is very low
334
- dogs = await detect_multiple_dogs(image)
335
-
336
- if len(dogs) > 1:
337
- # Multiple dogs detected, process each one
338
- explanations = []
339
- buttons = []
340
- annotated_image = image.copy()
341
- draw = ImageDraw.Draw(annotated_image)
342
- font = ImageFont.load_default()
343
-
344
- for i, (cropped_image, _, box) in enumerate(dogs, 1):
345
- top1_prob, topk_breeds, topk_probs_percent = await predict_single_dog(cropped_image)
346
-
347
- draw.rectangle(box, outline="red", width=3)
348
- draw.text((box[0], box[1]), f"Dog {i}", fill="yellow", font=font)
349
-
350
- if top1_prob >= 0.5:
351
- breed = topk_breeds[0]
352
- description = get_dog_description(breed)
353
- explanations.append(format_description(description, breed, is_multi_dog=True, dog_number=i))
354
- else:
355
- explanation = f"""
356
- Dog {i}: Detected with moderate confidence. Here are the top 3 possible breeds:
357
- 1. **{topk_breeds[0]}** ({topk_probs_percent[0]})
358
- 2. **{topk_breeds[1]}** ({topk_probs_percent[1]})
359
- 3. **{topk_breeds[2]}** ({topk_probs_percent[2]})
360
- """
361
- explanations.append(explanation)
362
- for breed in topk_breeds:
363
- buttons.append(f"More about Dog {i}: {breed}")
364
-
365
- final_explanation = "\n\n---\n\n".join(explanations)
366
-
367
- if buttons:
368
- return final_explanation, annotated_image, gr.update(visible=True, choices=buttons), gr.update(visible=False), gr.update(visible=False)
369
- else:
370
- return final_explanation, annotated_image, gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
371
-
372
- else:
373
- # No dogs detected or only one dog with low confidence
374
- return "The image is unclear or the breed is not in the dataset. Please upload a clearer image of a dog.", None, gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
375
-
376
  except Exception as e:
377
  return f"An error occurred: {e}", None, gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
378
 
 
271
  """
272
  return formatted_description
273
 
 
274
  async def predict_single_dog(image):
275
  image_tensor = preprocess_image(image)
276
  with torch.no_grad():
277
+ output = model(image_tensor.to(device))
278
  logits = output[0] if isinstance(output, tuple) else output
279
  probabilities = F.softmax(logits, dim=1)
280
  topk_probs, topk_indices = torch.topk(probabilities, k=3)
 
308
  if isinstance(image, np.ndarray):
309
  image = Image.fromarray(image)
310
 
311
+ # Always start with single dog prediction
312
  top1_prob, topk_breeds, topk_probs_percent = await predict_single_dog(image)
313
 
314
  if top1_prob >= 0.5:
 
328
  breed_buttons = [f"More about {breed}" for breed in topk_breeds[:3]]
329
  return explanation, image, gr.update(visible=True, choices=breed_buttons), gr.update(visible=False), gr.update(visible=False)
330
 
331
+ else: # top1_prob < 0.2
332
+ return "The image is unclear or the breed is not in the dataset. Please upload a clearer image of a dog.", None, gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
333
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
334
  except Exception as e:
335
  return f"An error occurred: {e}", None, gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
336