DawnC commited on
Commit
c6aafa1
·
1 Parent(s): 6471bf7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -50
app.py CHANGED
@@ -204,6 +204,29 @@ def get_akc_breeds_link():
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,80 +237,37 @@ def predict(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
- # 假設低於 20% 機率為非狗或不確定的圖片
225
  if top1_prob < 0.2:
226
- return (
227
- "The model couldn't confidently identify a dog breed. "
228
- "It seems like the image may not contain a dog, or the image quality is too low. "
229
- "Please upload a clearer picture or ensure the subject is a dog."
230
- )
231
 
232
- # 當信心高於 50% 時,直接返回該品種資訊
233
  if top1_prob >= 0.5:
234
  predicted = topk_indices[0][0]
235
  breed = dog_breeds[predicted.item()]
236
  return get_breed_info(breed)
237
 
238
  else:
239
- # 信心不足50%,返回top 3的預測結果,並且當點擊時能查看詳細資訊
240
  topk_breeds = [dog_breeds[idx.item()] for idx in topk_indices[0]]
241
  topk_probs_percent = [f"{prob.item() * 100:.2f}%" for prob in topk_probs[0]]
242
 
243
- # 提供每個品種的回調函數
244
- topk_results = "\n\n".join(
245
- [f"**{i+1}. [Click here to view more about {breed}](#) ({prob} confidence)**"
246
- for i, (breed, prob) in enumerate(zip(topk_breeds, topk_probs_percent))]
247
- )
248
 
249
- # 提供說明
250
- explanation = (
251
- f"The model couldn't confidently identify the breed. Here are the top 3 possible breeds:\n\n{topk_results}\n\n"
252
- "This can happen if the image quality is low or the breed is rare in the dataset. "
253
- "Please try uploading a clearer image or a different angle of the dog. "
254
- "For more accurate results, ensure the dog is the main subject of the photo."
255
- )
256
-
257
- return explanation
258
 
259
  except Exception as e:
260
  return f"An error occurred: {e}"
261
 
262
- def get_breed_info(breed):
263
- """
264
- 返回指定狗品種的詳細資訊,類似於 >=50% 信心時的結果。
265
- """
266
- description = get_dog_description(breed)
267
- akc_link = get_akc_breeds_link()
268
-
269
- if isinstance(description, dict):
270
- description_str = "\n\n".join([f"**{key}**: {value}" for key, value in description.items()])
271
- else:
272
- description_str = description
273
-
274
- # 添加AKC連結
275
- 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."
276
-
277
- # 添加免責聲明
278
- disclaimer = ("\n\n*Disclaimer: The external link provided leads to the American Kennel Club (AKC) dog breeds page. "
279
- "You may need to search for the specific breed on that page. "
280
- "I am not responsible for the content on external sites. "
281
- "Please refer to the AKC's terms of use and privacy policy.*")
282
- description_str += disclaimer
283
-
284
- return description_str
285
-
286
 
287
  iface = gr.Interface(
288
  fn=predict,
289
  inputs=gr.Image(label="Upload a dog image", type="numpy"),
290
- outputs=gr.Markdown(label="Prediction Results"),
291
  title="<h1 style='font-family:Roboto; font-weight:bold; color:#2C3E50; text-align:center;'>🐶 Dog Breed Classifier 🔍</h1>",
292
  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)',
293
  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
+ # 返回特定狗品種的描述函數
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
  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.Component(type="button")],
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>",