File size: 10,963 Bytes
406922d
 
 
 
 
 
 
 
 
2b82929
853de85
406922d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2439595
406922d
 
922691a
406922d
 
 
 
922691a
406922d
 
 
922691a
406922d
 
 
 
 
 
 
 
853de85
7babadc
 
4a1799c
406922d
 
 
 
ad1101d
 
 
 
 
406922d
922691a
853de85
406922d
7babadc
853de85
406922d
922691a
406922d
 
853de85
922691a
7babadc
922691a
 
7babadc
 
 
 
922691a
853de85
406922d
 
 
 
853de85
406922d
 
853de85
 
 
 
2439595
 
 
 
 
853de85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34f44fd
406922d
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
import os
import numpy as np
import torch
import torch.nn as nn
import gradio as gr
from torchvision.models import efficientnet_v2_m, EfficientNet_V2_M_Weights
import torch.nn.functional as F
from torchvision import transforms
from PIL import Image
from data_manager import get_dog_description
from urllib.parse import quote

dog_breeds = ["Afghan_Hound(阿富汗獵犬)", "African_Hunting_Dog(非洲野犬)", "Airedale(艾爾谷犬)",
            "American_Staffordshire_Terrier(美國斯塔福郡梗)", "Appenzeller(亞賓澤爾犬)",
            "Australian_Terrier(澳大利亞梗)", "Bedlington_Terrier(貝德靈頓梗)",
            "Bernese_Mountain_Dog(伯恩山犬)", "Blenheim_Spaniel(布萊尼姆獵犬)",
            "Border_Collie(邊境牧羊犬)", "Border_Terrier(邊境梗)", "Boston_Bull(波士頓梗)",
            "Bouvier_Des_Flandres(法蘭德斯牧羊犬)", "Brabancon_Griffon(布魯塞爾格里芬犬)",
            "Brittany_Spaniel(布列塔尼獵犬)", "Cardigan(卡迪根威爾士柯基犬)",
            "Chesapeake_Bay_Retriever(切薩皮克灣獵犬)", "Chihuahua(吉娃娃)",
            "Dandie_Dinmont(丹第丁蒙梗)", "Doberman(杜賓犬)", "English_Foxhound(英國獵狐犬)",
            "English_Setter(英國雪達犬)", "English_Springer(英國跳獵犬)",
            "EntleBucher(恩特雷布赫山地犬)", "Eskimo_Dog(愛斯基摩犬)", "French_Bulldog(法國鬥牛犬)",
            "German_Shepherd(德國牧羊犬)", "German_Short-Haired_Pointer(德國短毛指示犬)",
            "Gordon_Setter(戈登雪達犬)", "Great_Dane(大丹犬)", "Great_Pyrenees(大白熊犬)",
            "Greater_Swiss_Mountain_Dog(大瑞士山地犬)", "Ibizan_Hound(依比沙獵犬)",
            "Irish_Setter(愛爾蘭雪達犬)", "Irish_Terrier(愛爾蘭梗)",
            "Irish_Water_Spaniel(愛爾蘭水獵犬)", "Irish_Wolfhound(愛爾蘭獵狼犬)",
            "Italian_Greyhound(義大利灰狗)", "Japanese_Spaniel(日本狆)",
            "Kerry_Blue_Terrier(凱利藍梗)", "Labrador_Retriever(拉布拉多尋回犬)",
            "Lakeland_Terrier(湖畔梗)", "Leonberg(獅毛狗)", "Lhasa(拉薩犬)",
            "Maltese_Dog(馬爾濟斯犬)", "Mexican_Hairless(墨西哥無毛犬)", "Newfoundland(紐芬蘭犬)",
            "Norfolk_Terrier(諾福克梗)", "Norwegian_Elkhound(挪威獵麋犬)",
            "Norwich_Terrier(諾利治梗)", "Old_English_Sheepdog(古代英國牧羊犬)",
            "Pekinese(北京犬)", "Pembroke(威爾士柯基犬)", "Pomeranian(博美犬)",
            "Rhodesian_Ridgeback(羅得西亞脊背犬)", "Rottweiler(羅威納犬)",
            "Saint_Bernard(聖伯納犬)", "Saluki(薩路基獵犬)", "Samoyed(薩摩耶犬)",
            "Scotch_Terrier(蘇格蘭梗)", "Scottish_Deerhound(蘇格蘭獵鹿犬)",
            "Sealyham_Terrier(錫利哈姆梗)", "Shetland_Sheepdog(設得蘭牧羊犬)",
            "Shih-Tzu(西施犬)", "Siberian_Husky(西伯利亞哈士奇)",
            "Staffordshire_Bullterrier(斯塔福郡鬥牛梗)", "Sussex_Spaniel(蘇塞克斯獵犬)",
            "Tibetan_Mastiff(藏獒)", "Tibetan_Terrier(西藏梗)", "Walker_Hound(沃克獵犬)",
            "Weimaraner(威瑪犬)", "Welsh_Springer_Spaniel(威爾士跳獵犬)",
            "West_Highland_White_Terrier(西高地白梗)", "Yorkshire_Terrier(約克夏梗)",
            "Affenpinscher(猴犬)", "Basenji(巴辛吉犬)", "Basset(巴吉度獵犬)", "Beagle(比格犬)",
            "Black-and-Tan_Coonhound(黑褐獵浣熊犬)", "Bloodhound(尋血獵犬)",
            "Bluetick(布魯提克獵犬)", "Borzoi(俄羅斯獵狼犬)", "Boxer(拳師犬)", "Briard(布里亞犬)",
            "Bull_Mastiff(獒犬)", "Cairn(凱恩梗)", "Chow(鬆獅犬)", "Clumber(克倫伯獵犬)",
            "Cocker_Spaniel(可卡獵犬)", "Collie(柯利牧羊犬)", "Curly-Coated_Retriever(捲毛尋回犬)",
            "Dhole(豺)", "Dingo(澳洲野犬)", "Flat-Coated_Retriever(平毛尋回犬)",
            "Giant_Schnauzer(大型雪納瑞犬)", "Golden_Retriever(黃金獵犬)",
            "Groenendael(比利時牧羊犬)", "Keeshond(荷蘭毛獅犬)", "Kelpie(澳洲卡爾比犬)",
            "Komondor(匈牙利牧羊犬)", "Kuvasz(庫瓦茲犬)", "Malamute(阿拉斯加雪橇犬)",
            "Malinois(比利時瑪利諾犬)", "Miniature_Pinscher(迷你杜賓犬)",
            "Miniature_Poodle(迷你貴賓犬)", "Miniature_Schnauzer(迷你雪納瑞犬)",
            "Otterhound(水獺獵犬)", "Papillon(蝴蝶犬)", "Pug(巴哥犬)", "Redbone(紅骨獵浣熊犬)",
            "Schipperke(舒柏奇犬)", "Silky_Terrier(絲毛梗)",
            "Soft-Coated_Wheaten_Terrier(愛爾蘭軟毛梗)", "Standard_Poodle(標準貴賓犬)",
            "Standard_Schnauzer(標準雪納瑞犬)", "Toy_Poodle(玩具貴賓犬)", "Toy_Terrier(玩具梗)",
            "Vizsla(維茲拉犬)", "Whippet(惠比特犬)", "Wire-Haired_Fox_Terrier(硬毛獵狐梗)"]

class MultiHeadAttention(nn.Module):

    def __init__(self, in_dim, num_heads=8):
        super().__init__()
        self.num_heads = num_heads
        self.head_dim = max(1, in_dim // num_heads)
        self.scaled_dim = self.head_dim * num_heads
        self.fc_in = nn.Linear(in_dim, self.scaled_dim)
        self.query = nn.Linear(self.scaled_dim, self.scaled_dim)
        self.key = nn.Linear(self.scaled_dim, self.scaled_dim)
        self.value = nn.Linear(self.scaled_dim, self.scaled_dim)
        self.fc_out = nn.Linear(self.scaled_dim, in_dim)

    def forward(self, x):
        N = x.shape[0]
        x = self.fc_in(x)
        q = self.query(x).view(N, self.num_heads, self.head_dim)
        k = self.key(x).view(N, self.num_heads, self.head_dim)
        v = self.value(x).view(N, self.num_heads, self.head_dim)

        energy = torch.einsum("nqd,nkd->nqk", [q, k])
        attention = F.softmax(energy / (self.head_dim ** 0.5), dim=2)

        out = torch.einsum("nqk,nvd->nqd", [attention, v])
        out = out.reshape(N, self.scaled_dim)
        out = self.fc_out(out)
        return out

class BaseModel(nn.Module):
    def __init__(self, num_classes, device='cuda' if torch.cuda.is_available() else 'cpu'):
        super().__init__()
        self.device = device
        self.backbone = efficientnet_v2_m(weights=EfficientNet_V2_M_Weights.IMAGENET1K_V1)
        self.feature_dim = self.backbone.classifier[1].in_features
        self.backbone.classifier = nn.Identity()

        self.num_heads = max(1, min(8, self.feature_dim // 64))
        self.attention = MultiHeadAttention(self.feature_dim, num_heads=self.num_heads)

        self.classifier = nn.Sequential(
            nn.LayerNorm(self.feature_dim),
            nn.Dropout(0.3),
            nn.Linear(self.feature_dim, num_classes)
        )

        self.to(device)

    def forward(self, x):
        x = x.to(self.device)
        features = self.backbone(x)
        attended_features = self.attention(features)
        logits = self.classifier(attended_features)
        return logits, attended_features


num_classes = 120
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = BaseModel(num_classes=num_classes, device=device)

checkpoint = torch.load('best_model_81_dog.pth', map_location=torch.device('cpu'))
model.load_state_dict(checkpoint['model_state_dict'])

# evaluation mode
model.eval()

# Image preprocessing function
def preprocess_image(image):
    # If the image is numpy.ndarray turn into PIL.Image
    if isinstance(image, np.ndarray):
        image = Image.fromarray(image)

    # Use torchvision.transforms to process images
    transform = transforms.Compose([
        transforms.Resize((224, 224)),
        transforms.ToTensor(),
        transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
    ])

    return transform(image).unsqueeze(0)


def get_akc_breeds_link():
    return "https://www.akc.org/dog-breeds/"

def predict(image):
    try:
        image_tensor = preprocess_image(image)
        with torch.no_grad():
            output = model(image_tensor)
            if isinstance(output, tuple):
                logits = output[0]
            else:
                logits = output
            _, predicted = torch.max(logits, 1)
        breed = dog_breeds[predicted.item()]
        
        description = get_dog_description(breed)
        akc_link = get_akc_breeds_link()
        
        if isinstance(description, dict):
            description_str = "\n\n".join([f"**{key}**: {value}" for key, value in description.items()])
        else:
            description_str = description
        
        # Add AKC link as an option
        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."
        
        # Add disclaimer
        disclaimer = ("\n\n*Disclaimer: The external link provided leads to the American Kennel Club (AKC) dog breeds page. "
                      "You may need to search for the specific breed on that page. "
                      "I am not responsible for the content on external sites. "
                      "Please refer to the AKC's terms of use and privacy policy.*")
        description_str += disclaimer
        
        return description_str
    except Exception as e:
        return f"An error occurred: {e}"


iface = gr.Interface(
    fn=predict,
    inputs=gr.Image(label="Upload a dog image", type="numpy"),
    outputs=gr.Markdown(label="Prediction Results"),
    title="<h1 style='font-family:Roboto; font-weight:bold; color:#2C3E50; text-align:center;'>🐶 Dog Breed Classifier 🔍</h1>",
    description="<p style='font-family:Open Sans; color:#34495E; text-align:center;'>Upload a picture of a dog, and AI will predict its breed, provide detailed information, and include a Wikipedia link!</p>",
    examples=['Border_Collie.jpg',
              'Golden_Retriever.jpeg',
              'Saint_Bernard.jpeg',
              'French_Bulldog.jpeg',
              'Samoyed.jpg'],
     css = """
    .container {
        max-width: 900px;
        margin: 0 auto;
        padding: 20px;
        background-color: rgba(255, 255, 255, 0.9);
        border-radius: 15px;
        box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
    }
    
    .gr-form {
        display: flex;
        flex-direction: column;
        align-items: center;
    }
    
    .gr-box {
        width: 100%;
        max-width: 500px;
    }
    
    .output-markdown, .output-image {
        margin-top: 20px;
        padding: 15px;
        background-color: #f5f5f5;
        border-radius: 10px;
    }
    
    .examples {
        display: flex;
        justify-content: center;
        flex-wrap: wrap;
        gap: 10px;
        margin-top: 20px;
    }
    
    .examples img {
        width: 100px;
        height: 100px;
        object-fit: cover;
    }
    """,
    theme='default')



# Launch the app
if __name__ == "__main__":
    iface.launch()