DawnC commited on
Commit
12d9306
1 Parent(s): e805d38

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -36
app.py CHANGED
@@ -204,29 +204,6 @@ def get_akc_breeds_link():
204
  # except Exception as e:
205
  # return f"An error occurred: {e}"
206
 
207
- # 返回特定狗品種的描述函數
208
- def get_breed_info(breed):
209
- description = get_dog_description(breed)
210
- akc_link = get_akc_breeds_link()
211
-
212
- if isinstance(description, dict):
213
- description_str = "\n\n".join([f"**{key}**: {value}" for key, value in description.items()])
214
- else:
215
- description_str = description
216
-
217
- # 添加AKC連結
218
- description_str += f"\n\n**Want to learn more about dog breeds?** [Visit the AKC dog breeds page]({akc_link}) and search for {breed} to find detailed information."
219
-
220
- # 添加免責聲明
221
- disclaimer = ("\n\n*Disclaimer: The external link provided leads to the American Kennel Club (AKC) dog breeds page. "
222
- "You may need to search for the specific breed on that page. "
223
- "I am not responsible for the content on external sites. "
224
- "Please refer to the AKC's terms of use and privacy policy.*")
225
- description_str += disclaimer
226
-
227
- return description_str
228
-
229
- # 原始的預測函數,增加了按鈕來觸發品種描述的顯示
230
  def predict(image):
231
  try:
232
  image_tensor = preprocess_image(image)
@@ -237,37 +214,68 @@ def predict(image):
237
  else:
238
  logits = output
239
 
 
240
  probabilities = F.softmax(logits, dim=1)
241
  topk_probs, topk_indices = torch.topk(probabilities, k=3)
242
- top1_prob = topk_probs[0][0].item()
243
 
244
- if top1_prob < 0.2:
245
- return "The image does not appear to be a dog. Please upload a clearer or different dog image."
246
 
247
  if top1_prob >= 0.5:
 
248
  predicted = topk_indices[0][0]
249
  breed = dog_breeds[predicted.item()]
250
- return get_breed_info(breed)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
251
 
252
  else:
253
- # 如果模型無法確定,列出 top 3 品種按鈕
254
  topk_breeds = [dog_breeds[idx.item()] for idx in topk_indices[0]]
255
  topk_probs_percent = [f"{prob.item() * 100:.2f}%" for prob in topk_probs[0]]
256
 
257
- # 用按鈕來返回品種描述
258
- buttons = [gr.Button(f"Click here to view more about {breed} ({prob})", variant="primary")
259
- for breed, prob in zip(topk_breeds, topk_probs_percent)]
260
-
261
- return f"The model couldn't confidently identify the breed. Here are the top 3 possible breeds:", buttons
262
-
 
 
 
 
 
 
 
 
 
263
  except Exception as e:
264
  return f"An error occurred: {e}"
265
 
266
-
267
  iface = gr.Interface(
268
  fn=predict,
269
  inputs=gr.Image(label="Upload a dog image", type="numpy"),
270
- outputs=[gr.Markdown(label="Prediction Results"), gr.Button(value="See More Details")],
271
  title="<h1 style='font-family:Roboto; font-weight:bold; color:#2C3E50; text-align:center;'>🐶 Dog Breed Classifier 🔍</h1>",
272
  article= 'For more details on this project and other work, feel free to visit my GitHub [Dog Breed Classifier](https://github.com/Eric-Chung-0511/Learning-Record/tree/main/Data%20Science%20Projects/Dog%20Breed%20Classifier)',
273
  description="<p style='font-family:Open Sans; color:#34495E; text-align:center;'>Upload a picture of a dog, and model will predict its breed, provide detailed information, and include an extra information link!</p>",
 
204
  # except Exception as e:
205
  # return f"An error occurred: {e}"
206
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
207
  def predict(image):
208
  try:
209
  image_tensor = preprocess_image(image)
 
214
  else:
215
  logits = output
216
 
217
+ # 取得預測的top k結果
218
  probabilities = F.softmax(logits, dim=1)
219
  topk_probs, topk_indices = torch.topk(probabilities, k=3)
 
220
 
221
+ # 檢查最高的預測機率
222
+ top1_prob = topk_probs[0][0].item()
223
 
224
  if top1_prob >= 0.5:
225
+ # 正確辨識時,返回該品種資訊
226
  predicted = topk_indices[0][0]
227
  breed = dog_breeds[predicted.item()]
228
+ description = get_dog_description(breed)
229
+ akc_link = get_akc_breeds_link()
230
+
231
+ if isinstance(description, dict):
232
+ description_str = "\n\n".join([f"**{key}**: {value}" for key, value in description.items()])
233
+ else:
234
+ description_str = description
235
+
236
+ # 添加AKC連結
237
+ description_str += f"\n\n**Want to learn more about dog breeds?** [Visit the AKC dog breeds page]({akc_link}) and search for {breed} to find detailed information."
238
+
239
+ # 添加免責聲明
240
+ disclaimer = ("\n\n*Disclaimer: The external link provided leads to the American Kennel Club (AKC) dog breeds page. "
241
+ "You may need to search for the specific breed on that page. "
242
+ "I am not responsible for the content on external sites. "
243
+ "Please refer to the AKC's terms of use and privacy policy.*")
244
+ description_str += disclaimer
245
+
246
+ return description_str
247
+
248
+ elif top1_prob < 0.1:
249
+ # 如果信心度低於 0.1,返回提示請上傳更清晰的圖片
250
+ return "The image is too unclear or the dog breed is not in the dataset. Please upload a clearer image of the dog."
251
 
252
  else:
253
+ # 不確定時,返回top 3的預測結果,並且允許點擊查看詳細資訊
254
  topk_breeds = [dog_breeds[idx.item()] for idx in topk_indices[0]]
255
  topk_probs_percent = [f"{prob.item() * 100:.2f}%" for prob in topk_probs[0]]
256
 
257
+ # 用粗體返回品種和機率,並為每個品種添加點擊連結
258
+ topk_results = "\n\n".join([
259
+ f"**{i+1}. [Click here to view more about {breed}]()** ({prob} confidence)"
260
+ for i, (breed, prob) in enumerate(zip(topk_breeds, topk_probs_percent))
261
+ ])
262
+
263
+ # 提供說明
264
+ explanation = (
265
+ f"The model couldn't confidently identify the breed. Here are the top 3 possible breeds:\n\n{topk_results}\n\n"
266
+ "This can happen if the image quality is low or the breed is rare in the dataset. "
267
+ "Please try uploading a clearer image or a different angle of the dog. "
268
+ "For more accurate results, ensure the dog is the main subject of the photo."
269
+ )
270
+
271
+ return explanation
272
  except Exception as e:
273
  return f"An error occurred: {e}"
274
 
 
275
  iface = gr.Interface(
276
  fn=predict,
277
  inputs=gr.Image(label="Upload a dog image", type="numpy"),
278
+ outputs=gr.Markdown(label="Prediction Results"),
279
  title="<h1 style='font-family:Roboto; font-weight:bold; color:#2C3E50; text-align:center;'>🐶 Dog Breed Classifier 🔍</h1>",
280
  article= 'For more details on this project and other work, feel free to visit my GitHub [Dog Breed Classifier](https://github.com/Eric-Chung-0511/Learning-Record/tree/main/Data%20Science%20Projects/Dog%20Breed%20Classifier)',
281
  description="<p style='font-family:Open Sans; color:#34495E; text-align:center;'>Upload a picture of a dog, and model will predict its breed, provide detailed information, and include an extra information link!</p>",