DawnC commited on
Commit
9c3253b
1 Parent(s): 3b2d17e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -33
app.py CHANGED
@@ -4,26 +4,29 @@ from PIL import Image
4
  import gradio as gr
5
  import os
6
 
7
- # Use CPU
8
  device = torch.device('cpu')
9
 
10
- # Define ResNet-50 Architecture
11
  model = models.resnet50(weights=None)
12
 
13
- # Revise fully connected layer to output 37 classes (num_classes = 37)
14
  model.fc = torch.nn.Linear(2048, 37)
15
 
 
16
  model.load_state_dict(torch.load('./resnet50_model_weights.pth', map_location=device))
17
 
 
18
  model.eval()
19
 
 
20
  transform = transforms.Compose([
21
  transforms.Resize((224, 224)),
22
  transforms.ToTensor(),
23
  transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
24
  ])
25
 
26
- # List of class names (37 dog and cat breeds)
27
  class_names = ['Abyssinian (阿比西尼亞貓)', 'American Bulldog (美國鬥牛犬)', 'American Pit Bull Terrier (美國比特鬥牛梗)',
28
  'Basset Hound (巴吉度獵犬)', 'Beagle (米格魯)', 'Bengal (孟加拉貓)', 'Birman (緬甸貓)', 'Bombay (孟買貓)',
29
  'Boxer (拳師犬)', 'British Shorthair (英國短毛貓)', 'Chihuahua (吉娃娃)', 'Egyptian Mau (埃及貓)',
@@ -35,47 +38,41 @@ class_names = ['Abyssinian (阿比西尼亞貓)', 'American Bulldog (美國鬥
35
  'Siamese (暹羅貓)', 'Sphynx (無毛貓)', 'Staffordshire Bull Terrier (史塔福郡鬥牛犬)',
36
  'Wheaten Terrier (小麥色梗)', 'Yorkshire Terrier (約克夏犬)']
37
 
38
- # Prediction function
39
  def classify_image(image):
40
- # Apply transformation and add batch dimension
41
- image = transform(image).unsqueeze(0).to(device)
42
  with torch.no_grad():
43
- # Make predictions using the model
44
  outputs = model(image)
45
- # Apply softmax to get probabilities
46
- probabilities = torch.nn.functional.softmax(outputs, dim=1)
47
- # Get the top 3 predictions
48
- probabilities, indices = torch.topk(probabilities, k=3)
49
- # Return the class names with their corresponding probabilities
50
  predictions = [(class_names[idx], prob.item()) for idx, prob in zip(indices[0], probabilities[0])]
51
- return {class_name: prob for class_name, prob in predictions} # Return raw float numbers
52
 
53
- # Path to the folder containing example images
54
  examples_path = './examples'
55
 
56
- # Check if the example images folder exists
57
  if os.path.exists(examples_path):
58
  print(f"[INFO] Found examples folder at {examples_path}")
59
  else:
60
  print(f"[ERROR] Examples folder not found at {examples_path}")
61
 
62
- # Load example images from the folder
63
  examples = [[examples_path + "/" + img] for img in os.listdir(examples_path)]
64
 
65
- # Create dropdown menu for users to see available classes (as reference, no direct connection to prediction)
66
- dropdown = gr.Dropdown(choices=class_names, label="Recognizable Breeds", type="value")
67
 
68
- # Define Gradio Interface
69
- with gr.Blocks() as demo_with_dropdown:
70
- gr.Markdown("# Oxford Pet 🐾 Recognizable Breeds")
71
- dropdown # 顯示下拉選單
72
- demo = gr.Interface(
73
- fn=classify_image,
74
- inputs=gr.Image(type="pil"), # 只使用圖片輸入進行預測
75
- outputs=gr.Label(num_top_classes=3, label="Top 3 Predictions"), # 輸出前三個預測
76
- examples=examples,
77
- title='Oxford Pet 🐈🐕',
78
- description='A ResNet50-based model for classifying 37 different pet breeds.',
79
- article='[Oxford Project](https://github.com/Eric-Chung-0511/Learning-Record/tree/main/Data%20Science%20Projects/The%20Oxford-IIIT%20Pet%20Project)'
80
- )
81
- demo.launch()
 
4
  import gradio as gr
5
  import os
6
 
7
+ # 使用 CPU
8
  device = torch.device('cpu')
9
 
10
+ # 定義 ResNet-50 模型架構(不使用預訓練權重)
11
  model = models.resnet50(weights=None)
12
 
13
+ # 修改模型的全連接層,輸出 37 個類別
14
  model.fc = torch.nn.Linear(2048, 37)
15
 
16
+ # 加載模型權重
17
  model.load_state_dict(torch.load('./resnet50_model_weights.pth', map_location=device))
18
 
19
+ # 設置模型為評估模式
20
  model.eval()
21
 
22
+ # 定義影像預處理
23
  transform = transforms.Compose([
24
  transforms.Resize((224, 224)),
25
  transforms.ToTensor(),
26
  transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
27
  ])
28
 
29
+ # 定義類別名稱
30
  class_names = ['Abyssinian (阿比西尼亞貓)', 'American Bulldog (美國鬥牛犬)', 'American Pit Bull Terrier (美國比特鬥牛梗)',
31
  'Basset Hound (巴吉度獵犬)', 'Beagle (米格魯)', 'Bengal (孟加拉貓)', 'Birman (緬甸貓)', 'Bombay (孟買貓)',
32
  'Boxer (拳師犬)', 'British Shorthair (英國短毛貓)', 'Chihuahua (吉娃娃)', 'Egyptian Mau (埃及貓)',
 
38
  'Siamese (暹羅貓)', 'Sphynx (無毛貓)', 'Staffordshire Bull Terrier (史塔福郡鬥牛犬)',
39
  'Wheaten Terrier (小麥色梗)', 'Yorkshire Terrier (約克夏犬)']
40
 
41
+ # 定義預測函數
42
  def classify_image(image):
43
+ image = transform(image).unsqueeze(0).to(device) # 確保影像資料處理在 CPU
 
44
  with torch.no_grad():
 
45
  outputs = model(image)
46
+ probabilities, indices = torch.topk(outputs, k=3) # 取得前3個預測
47
+ probabilities = torch.nn.functional.softmax(probabilities, dim=1) # 將結果轉換為機率
 
 
 
48
  predictions = [(class_names[idx], prob.item()) for idx, prob in zip(indices[0], probabilities[0])]
49
+ return {class_name: f"{prob * 100:.2f}%" for class_name, prob in predictions}
50
 
51
+ # 設置 examples 路徑
52
  examples_path = './examples'
53
 
 
54
  if os.path.exists(examples_path):
55
  print(f"[INFO] Found examples folder at {examples_path}")
56
  else:
57
  print(f"[ERROR] Examples folder not found at {examples_path}")
58
 
59
+ # Gradio 介面
60
  examples = [[examples_path + "/" + img] for img in os.listdir(examples_path)]
61
 
62
+ # 使用 Markdown 顯示 37 個品種
63
+ breed_list = "### Recognizable Breeds\n" + "\n".join([f"- {breed}" for breed in class_names])
64
 
65
+ demo = gr.Blocks()
66
+
67
+ with demo:
68
+ gr.Markdown("# Oxford Pet 🐕🐈 Recognizable Breeds")
69
+ gr.Markdown(breed_list) # 用 Markdown 顯示品種列表
70
+ gr.Interface(fn=classify_image,
71
+ inputs=gr.Image(type="pil"), # 只需要圖片輸入
72
+ outputs=[gr.Label(num_top_classes=3, label="Top 3 Predictions")],
73
+ examples=examples,
74
+ title='Oxford Pet 🐈🐕',
75
+ description='A ResNet50-based model for classifying 37 different pet breeds.',
76
+ article="[Oxford Project](https://github.com/Eric-Chung-0511/Learning-Record/tree/main/Data%20Science%20Projects/The%20Oxford-IIIT%20Pet%20Project)").launch()
77
+
78
+ demo.launch()