DawnC commited on
Commit
e398dfd
1 Parent(s): 4207870

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +477 -5
app.py CHANGED
@@ -33,10 +33,477 @@ from html_templates import (
33
  )
34
  from urllib.parse import quote
35
  from ultralytics import YOLO
 
36
  import asyncio
37
  import traceback
38
 
39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  model_yolo = YOLO('yolov8l.pt')
41
 
42
  history_manager = UserHistoryManager()
@@ -98,9 +565,11 @@ class MultiHeadAttention(nn.Module):
98
  return out
99
 
100
  class BaseModel(nn.Module):
 
101
  def __init__(self, num_classes, device='cuda' if torch.cuda.is_available() else 'cpu'):
102
  super().__init__()
103
- self.device = device
 
104
  self.backbone = efficientnet_v2_m(weights=EfficientNet_V2_M_Weights.IMAGENET1K_V1)
105
  self.feature_dim = self.backbone.classifier[1].in_features
106
  self.backbone.classifier = nn.Identity()
@@ -116,6 +585,7 @@ class BaseModel(nn.Module):
116
 
117
  self.to(device)
118
 
 
119
  def forward(self, x):
120
  x = x.to(self.device)
121
  features = self.backbone(x)
@@ -124,15 +594,15 @@ class BaseModel(nn.Module):
124
  return logits, attended_features
125
 
126
  # Initialize model
 
127
  num_classes = len(dog_breeds)
128
- device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
129
 
130
  # Initialize base model
131
  model = BaseModel(num_classes=num_classes, device=device).to(device)
132
 
133
  # Load model path
134
  model_path = '124_best_model_dog.pth'
135
- checkpoint = torch.load(model_path, map_location=device)
136
 
137
  # Load model state
138
  model.load_state_dict(checkpoint['base_model'], strict=False)
@@ -152,7 +622,8 @@ def preprocess_image(image):
152
  ])
153
 
154
  return transform(image).unsqueeze(0)
155
-
 
156
  async def predict_single_dog(image):
157
  """
158
  Predicts the dog breed using only the classifier.
@@ -183,8 +654,9 @@ async def predict_single_dog(image):
183
  print(f"{breed}: {prob:.4f}")
184
 
185
  return probabilities[0], breeds[:3], relative_probs
 
186
 
187
-
188
  async def detect_multiple_dogs(image, conf_threshold=0.3, iou_threshold=0.55):
189
  results = model_yolo(image, conf=conf_threshold, iou=iou_threshold)[0]
190
  dogs = []
 
33
  )
34
  from urllib.parse import quote
35
  from ultralytics import YOLO
36
+ from device_manager import DeviceManager, device_handler
37
  import asyncio
38
  import traceback
39
 
40
 
41
+ # model_yolo = YOLO('yolov8l.pt')
42
+
43
+ # history_manager = UserHistoryManager()
44
+
45
+ # dog_breeds = ["Afghan_Hound", "African_Hunting_Dog", "Airedale", "American_Staffordshire_Terrier",
46
+ # "Appenzeller", "Australian_Terrier", "Bedlington_Terrier", "Bernese_Mountain_Dog", "Bichon_Frise",
47
+ # "Blenheim_Spaniel", "Border_Collie", "Border_Terrier", "Boston_Bull", "Bouvier_Des_Flandres",
48
+ # "Brabancon_Griffon", "Brittany_Spaniel", "Cardigan", "Chesapeake_Bay_Retriever",
49
+ # "Chihuahua", "Dachshund", "Dandie_Dinmont", "Doberman", "English_Foxhound", "English_Setter",
50
+ # "English_Springer", "EntleBucher", "Eskimo_Dog", "French_Bulldog", "German_Shepherd",
51
+ # "German_Short-Haired_Pointer", "Gordon_Setter", "Great_Dane", "Great_Pyrenees",
52
+ # "Greater_Swiss_Mountain_Dog","Havanese", "Ibizan_Hound", "Irish_Setter", "Irish_Terrier",
53
+ # "Irish_Water_Spaniel", "Irish_Wolfhound", "Italian_Greyhound", "Japanese_Spaniel",
54
+ # "Kerry_Blue_Terrier", "Labrador_Retriever", "Lakeland_Terrier", "Leonberg", "Lhasa",
55
+ # "Maltese_Dog", "Mexican_Hairless", "Newfoundland", "Norfolk_Terrier", "Norwegian_Elkhound",
56
+ # "Norwich_Terrier", "Old_English_Sheepdog", "Pekinese", "Pembroke", "Pomeranian",
57
+ # "Rhodesian_Ridgeback", "Rottweiler", "Saint_Bernard", "Saluki", "Samoyed",
58
+ # "Scotch_Terrier", "Scottish_Deerhound", "Sealyham_Terrier", "Shetland_Sheepdog", "Shiba_Inu",
59
+ # "Shih-Tzu", "Siberian_Husky", "Staffordshire_Bullterrier", "Sussex_Spaniel",
60
+ # "Tibetan_Mastiff", "Tibetan_Terrier", "Walker_Hound", "Weimaraner",
61
+ # "Welsh_Springer_Spaniel", "West_Highland_White_Terrier", "Yorkshire_Terrier",
62
+ # "Affenpinscher", "Basenji", "Basset", "Beagle", "Black-and-Tan_Coonhound", "Bloodhound",
63
+ # "Bluetick", "Borzoi", "Boxer", "Briard", "Bull_Mastiff", "Cairn", "Chow", "Clumber",
64
+ # "Cocker_Spaniel", "Collie", "Curly-Coated_Retriever", "Dhole", "Dingo",
65
+ # "Flat-Coated_Retriever", "Giant_Schnauzer", "Golden_Retriever", "Groenendael", "Keeshond",
66
+ # "Kelpie", "Komondor", "Kuvasz", "Malamute", "Malinois", "Miniature_Pinscher",
67
+ # "Miniature_Poodle", "Miniature_Schnauzer", "Otterhound", "Papillon", "Pug", "Redbone",
68
+ # "Schipperke", "Silky_Terrier", "Soft-Coated_Wheaten_Terrier", "Standard_Poodle",
69
+ # "Standard_Schnauzer", "Toy_Poodle", "Toy_Terrier", "Vizsla", "Whippet",
70
+ # "Wire-Haired_Fox_Terrier"]
71
+
72
+
73
+ # class MultiHeadAttention(nn.Module):
74
+
75
+ # def __init__(self, in_dim, num_heads=8):
76
+ # super().__init__()
77
+ # self.num_heads = num_heads
78
+ # self.head_dim = max(1, in_dim // num_heads)
79
+ # self.scaled_dim = self.head_dim * num_heads
80
+ # self.fc_in = nn.Linear(in_dim, self.scaled_dim)
81
+ # self.query = nn.Linear(self.scaled_dim, self.scaled_dim)
82
+ # self.key = nn.Linear(self.scaled_dim, self.scaled_dim)
83
+ # self.value = nn.Linear(self.scaled_dim, self.scaled_dim)
84
+ # self.fc_out = nn.Linear(self.scaled_dim, in_dim)
85
+
86
+ # def forward(self, x):
87
+ # N = x.shape[0]
88
+ # x = self.fc_in(x)
89
+ # q = self.query(x).view(N, self.num_heads, self.head_dim)
90
+ # k = self.key(x).view(N, self.num_heads, self.head_dim)
91
+ # v = self.value(x).view(N, self.num_heads, self.head_dim)
92
+
93
+ # energy = torch.einsum("nqd,nkd->nqk", [q, k])
94
+ # attention = F.softmax(energy / (self.head_dim ** 0.5), dim=2)
95
+
96
+ # out = torch.einsum("nqk,nvd->nqd", [attention, v])
97
+ # out = out.reshape(N, self.scaled_dim)
98
+ # out = self.fc_out(out)
99
+ # return out
100
+
101
+ # class BaseModel(nn.Module):
102
+ # def __init__(self, num_classes, device='cuda' if torch.cuda.is_available() else 'cpu'):
103
+ # super().__init__()
104
+ # self.device = device
105
+ # self.backbone = efficientnet_v2_m(weights=EfficientNet_V2_M_Weights.IMAGENET1K_V1)
106
+ # self.feature_dim = self.backbone.classifier[1].in_features
107
+ # self.backbone.classifier = nn.Identity()
108
+
109
+ # self.num_heads = max(1, min(8, self.feature_dim // 64))
110
+ # self.attention = MultiHeadAttention(self.feature_dim, num_heads=self.num_heads)
111
+
112
+ # self.classifier = nn.Sequential(
113
+ # nn.LayerNorm(self.feature_dim),
114
+ # nn.Dropout(0.3),
115
+ # nn.Linear(self.feature_dim, num_classes)
116
+ # )
117
+
118
+ # self.to(device)
119
+
120
+ # def forward(self, x):
121
+ # x = x.to(self.device)
122
+ # features = self.backbone(x)
123
+ # attended_features = self.attention(features)
124
+ # logits = self.classifier(attended_features)
125
+ # return logits, attended_features
126
+
127
+ # # Initialize model
128
+ # num_classes = len(dog_breeds)
129
+ # device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
130
+
131
+ # # Initialize base model
132
+ # model = BaseModel(num_classes=num_classes, device=device).to(device)
133
+
134
+ # # Load model path
135
+ # model_path = '124_best_model_dog.pth'
136
+ # checkpoint = torch.load(model_path, map_location=device)
137
+
138
+ # # Load model state
139
+ # model.load_state_dict(checkpoint['base_model'], strict=False)
140
+ # model.eval()
141
+
142
+ # # Image preprocessing function
143
+ # def preprocess_image(image):
144
+ # # If the image is numpy.ndarray turn into PIL.Image
145
+ # if isinstance(image, np.ndarray):
146
+ # image = Image.fromarray(image)
147
+
148
+ # # Use torchvision.transforms to process images
149
+ # transform = transforms.Compose([
150
+ # transforms.Resize((224, 224)),
151
+ # transforms.ToTensor(),
152
+ # transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
153
+ # ])
154
+
155
+ # return transform(image).unsqueeze(0)
156
+
157
+ # async def predict_single_dog(image):
158
+ # """
159
+ # Predicts the dog breed using only the classifier.
160
+ # Args:
161
+ # image: PIL Image or numpy array
162
+ # Returns:
163
+ # tuple: (top1_prob, topk_breeds, relative_probs)
164
+ # """
165
+ # image_tensor = preprocess_image(image).to(device)
166
+
167
+ # with torch.no_grad():
168
+ # # Get model outputs (只使用logits,不需要features)
169
+ # logits = model(image_tensor)[0] # 如果model仍返回tuple,取第一個元素
170
+ # probs = F.softmax(logits, dim=1)
171
+
172
+ # # Classifier prediction
173
+ # top5_prob, top5_idx = torch.topk(probs, k=5)
174
+ # breeds = [dog_breeds[idx.item()] for idx in top5_idx[0]]
175
+ # probabilities = [prob.item() for prob in top5_prob[0]]
176
+
177
+ # # Calculate relative probabilities
178
+ # sum_probs = sum(probabilities[:3]) # 只取前三個來計算相對概率
179
+ # relative_probs = [f"{(prob/sum_probs * 100):.2f}%" for prob in probabilities[:3]]
180
+
181
+ # # Debug output
182
+ # print("\nClassifier Predictions:")
183
+ # for breed, prob in zip(breeds[:5], probabilities[:5]):
184
+ # print(f"{breed}: {prob:.4f}")
185
+
186
+ # return probabilities[0], breeds[:3], relative_probs
187
+
188
+
189
+ # async def detect_multiple_dogs(image, conf_threshold=0.3, iou_threshold=0.55):
190
+ # results = model_yolo(image, conf=conf_threshold, iou=iou_threshold)[0]
191
+ # dogs = []
192
+ # boxes = []
193
+ # for box in results.boxes:
194
+ # if box.cls == 16: # COCO dataset class for dog is 16
195
+ # xyxy = box.xyxy[0].tolist()
196
+ # confidence = box.conf.item()
197
+ # boxes.append((xyxy, confidence))
198
+
199
+ # if not boxes:
200
+ # dogs.append((image, 1.0, [0, 0, image.width, image.height]))
201
+ # else:
202
+ # nms_boxes = non_max_suppression(boxes, iou_threshold)
203
+
204
+ # for box, confidence in nms_boxes:
205
+ # x1, y1, x2, y2 = box
206
+ # w, h = x2 - x1, y2 - y1
207
+ # x1 = max(0, x1 - w * 0.05)
208
+ # y1 = max(0, y1 - h * 0.05)
209
+ # x2 = min(image.width, x2 + w * 0.05)
210
+ # y2 = min(image.height, y2 + h * 0.05)
211
+ # cropped_image = image.crop((x1, y1, x2, y2))
212
+ # dogs.append((cropped_image, confidence, [x1, y1, x2, y2]))
213
+
214
+ # return dogs
215
+
216
+ # def non_max_suppression(boxes, iou_threshold):
217
+ # keep = []
218
+ # boxes = sorted(boxes, key=lambda x: x[1], reverse=True)
219
+ # while boxes:
220
+ # current = boxes.pop(0)
221
+ # keep.append(current)
222
+ # boxes = [box for box in boxes if calculate_iou(current[0], box[0]) < iou_threshold]
223
+ # return keep
224
+
225
+
226
+ # def calculate_iou(box1, box2):
227
+ # x1 = max(box1[0], box2[0])
228
+ # y1 = max(box1[1], box2[1])
229
+ # x2 = min(box1[2], box2[2])
230
+ # y2 = min(box1[3], box2[3])
231
+
232
+ # intersection = max(0, x2 - x1) * max(0, y2 - y1)
233
+ # area1 = (box1[2] - box1[0]) * (box1[3] - box1[1])
234
+ # area2 = (box2[2] - box2[0]) * (box2[3] - box2[1])
235
+
236
+ # iou = intersection / float(area1 + area2 - intersection)
237
+ # return iou
238
+
239
+
240
+
241
+ # def create_breed_comparison(breed1: str, breed2: str) -> dict:
242
+ # breed1_info = get_dog_description(breed1)
243
+ # breed2_info = get_dog_description(breed2)
244
+
245
+ # # 標準化數值轉換
246
+ # value_mapping = {
247
+ # 'Size': {'Small': 1, 'Medium': 2, 'Large': 3, 'Giant': 4},
248
+ # 'Exercise_Needs': {'Low': 1, 'Moderate': 2, 'High': 3, 'Very High': 4},
249
+ # 'Care_Level': {'Low': 1, 'Moderate': 2, 'High': 3},
250
+ # 'Grooming_Needs': {'Low': 1, 'Moderate': 2, 'High': 3}
251
+ # }
252
+
253
+ # comparison_data = {
254
+ # breed1: {},
255
+ # breed2: {}
256
+ # }
257
+
258
+ # for breed, info in [(breed1, breed1_info), (breed2, breed2_info)]:
259
+ # comparison_data[breed] = {
260
+ # 'Size': value_mapping['Size'].get(info['Size'], 2), # 預設 Medium
261
+ # 'Exercise_Needs': value_mapping['Exercise_Needs'].get(info['Exercise Needs'], 2), # 預設 Moderate
262
+ # 'Care_Level': value_mapping['Care_Level'].get(info['Care Level'], 2),
263
+ # 'Grooming_Needs': value_mapping['Grooming_Needs'].get(info['Grooming Needs'], 2),
264
+ # 'Good_with_Children': info['Good with Children'] == 'Yes',
265
+ # 'Original_Data': info
266
+ # }
267
+
268
+ # return comparison_data
269
+
270
+
271
+ # async def predict(image):
272
+ # """
273
+ # Main prediction function that handles both single and multiple dog detection.
274
+
275
+ # Args:
276
+ # image: PIL Image or numpy array
277
+
278
+ # Returns:
279
+ # tuple: (html_output, annotated_image, initial_state)
280
+ # """
281
+ # if image is None:
282
+ # return format_warning_html("Please upload an image to start."), None, None
283
+
284
+ # try:
285
+ # if isinstance(image, np.ndarray):
286
+ # image = Image.fromarray(image)
287
+
288
+ # # Detect dogs in the image
289
+ # dogs = await detect_multiple_dogs(image)
290
+ # color_scheme = get_color_scheme(len(dogs) == 1)
291
+
292
+ # # Prepare for annotation
293
+ # annotated_image = image.copy()
294
+ # draw = ImageDraw.Draw(annotated_image)
295
+
296
+ # try:
297
+ # font = ImageFont.truetype("arial.ttf", 24)
298
+ # except:
299
+ # font = ImageFont.load_default()
300
+
301
+ # dogs_info = ""
302
+
303
+ # # Process each detected dog
304
+ # for i, (cropped_image, detection_confidence, box) in enumerate(dogs):
305
+ # color = color_scheme if len(dogs) == 1 else color_scheme[i % len(color_scheme)]
306
+
307
+ # # Draw box and label on image
308
+ # draw.rectangle(box, outline=color, width=4)
309
+ # label = f"Dog {i+1}"
310
+ # label_bbox = draw.textbbox((0, 0), label, font=font)
311
+ # label_width = label_bbox[2] - label_bbox[0]
312
+ # label_height = label_bbox[3] - label_bbox[1]
313
+
314
+ # # Draw label background and text
315
+ # label_x = box[0] + 5
316
+ # label_y = box[1] + 5
317
+ # draw.rectangle(
318
+ # [label_x - 2, label_y - 2, label_x + label_width + 4, label_y + label_height + 4],
319
+ # fill='white',
320
+ # outline=color,
321
+ # width=2
322
+ # )
323
+ # draw.text((label_x, label_y), label, fill=color, font=font)
324
+
325
+ # # Predict breed
326
+ # top1_prob, topk_breeds, relative_probs = await predict_single_dog(cropped_image)
327
+ # combined_confidence = detection_confidence * top1_prob
328
+
329
+ # # Format results based on confidence with error handling
330
+ # try:
331
+ # if combined_confidence < 0.2:
332
+ # dogs_info += format_error_message(color, i+1)
333
+ # elif top1_prob >= 0.45:
334
+ # breed = topk_breeds[0]
335
+ # description = get_dog_description(breed)
336
+ # # Handle missing breed description
337
+ # if description is None:
338
+ # # 如果沒有描述,創建一個基本描述
339
+ # description = {
340
+ # "Name": breed,
341
+ # "Size": "Unknown",
342
+ # "Exercise Needs": "Unknown",
343
+ # "Grooming Needs": "Unknown",
344
+ # "Care Level": "Unknown",
345
+ # "Good with Children": "Unknown",
346
+ # "Description": f"Identified as {breed.replace('_', ' ')}"
347
+ # }
348
+ # dogs_info += format_single_dog_result(breed, description, color)
349
+ # else:
350
+ # # 修改format_multiple_breeds_result的調用,包含錯誤處理
351
+ # dogs_info += format_multiple_breeds_result(
352
+ # topk_breeds,
353
+ # relative_probs,
354
+ # color,
355
+ # i+1,
356
+ # lambda breed: get_dog_description(breed) or {
357
+ # "Name": breed,
358
+ # "Size": "Unknown",
359
+ # "Exercise Needs": "Unknown",
360
+ # "Grooming Needs": "Unknown",
361
+ # "Care Level": "Unknown",
362
+ # "Good with Children": "Unknown",
363
+ # "Description": f"Identified as {breed.replace('_', ' ')}"
364
+ # }
365
+ # )
366
+ # except Exception as e:
367
+ # print(f"Error formatting results for dog {i+1}: {str(e)}")
368
+ # dogs_info += format_error_message(color, i+1)
369
+
370
+ # # Wrap final HTML output
371
+ # html_output = format_multi_dog_container(dogs_info)
372
+
373
+ # # Prepare initial state
374
+ # initial_state = {
375
+ # "dogs_info": dogs_info,
376
+ # "image": annotated_image,
377
+ # "is_multi_dog": len(dogs) > 1,
378
+ # "html_output": html_output
379
+ # }
380
+
381
+ # return html_output, annotated_image, initial_state
382
+
383
+ # except Exception as e:
384
+ # error_msg = f"An error occurred: {str(e)}\n\nTraceback:\n{traceback.format_exc()}"
385
+ # print(error_msg)
386
+ # return format_warning_html(error_msg), None, None
387
+
388
+
389
+ # def show_details_html(choice, previous_output, initial_state):
390
+ # """
391
+ # Generate detailed HTML view for a selected breed.
392
+
393
+ # Args:
394
+ # choice: str, Selected breed option
395
+ # previous_output: str, Previous HTML output
396
+ # initial_state: dict, Current state information
397
+
398
+ # Returns:
399
+ # tuple: (html_output, gradio_update, updated_state)
400
+ # """
401
+ # if not choice:
402
+ # return previous_output, gr.update(visible=True), initial_state
403
+
404
+ # try:
405
+ # breed = choice.split("More about ")[-1]
406
+ # description = get_dog_description(breed)
407
+ # html_output = format_breed_details_html(description, breed)
408
+
409
+ # # Update state
410
+ # initial_state["current_description"] = html_output
411
+ # initial_state["original_buttons"] = initial_state.get("buttons", [])
412
+
413
+ # return html_output, gr.update(visible=True), initial_state
414
+
415
+ # except Exception as e:
416
+ # error_msg = f"An error occurred while showing details: {e}"
417
+ # print(error_msg)
418
+ # return format_warning_html(error_msg), gr.update(visible=True), initial_state
419
+
420
+ # def main():
421
+ # with gr.Blocks(css=get_css_styles()) as iface:
422
+ # # Header HTML
423
+
424
+ # gr.HTML("""
425
+ # <header style='text-align: center; padding: 20px; margin-bottom: 20px;'>
426
+ # <h1 style='font-size: 2.5em; margin-bottom: 10px; color: #2D3748;'>
427
+ # 🐾 PawMatch AI
428
+ # </h1>
429
+ # <h2 style='font-size: 1.2em; font-weight: normal; color: #4A5568; margin-top: 5px;'>
430
+ # Your Smart Dog Breed Guide
431
+ # </h2>
432
+ # <div style='width: 50px; height: 3px; background: linear-gradient(90deg, #4299e1, #48bb78); margin: 15px auto;'></div>
433
+ # <p style='color: #718096; font-size: 0.9em;'>
434
+ # Powered by AI • Breed Recognition • Smart Matching • Companion Guide
435
+ # </p>
436
+ # </header>
437
+ # """)
438
+
439
+ # # 先創建歷史組件實例(但不創建標籤頁)
440
+ # history_component = create_history_component()
441
+
442
+ # with gr.Tabs():
443
+ # # 1. 品種檢測標籤頁
444
+ # example_images = [
445
+ # 'Border_Collie.jpg',
446
+ # 'Golden_Retriever.jpeg',
447
+ # 'Saint_Bernard.jpeg',
448
+ # 'Samoyed.jpg',
449
+ # 'French_Bulldog.jpeg'
450
+ # ]
451
+ # detection_components = create_detection_tab(predict, example_images)
452
+
453
+ # # 2. 品種比較標籤頁
454
+ # comparison_components = create_comparison_tab(
455
+ # dog_breeds=dog_breeds,
456
+ # get_dog_description=get_dog_description,
457
+ # breed_health_info=breed_health_info,
458
+ # breed_noise_info=breed_noise_info
459
+ # )
460
+
461
+ # # 3. 品種推薦標籤頁
462
+ # recommendation_components = create_recommendation_tab(
463
+ # UserPreferences=UserPreferences,
464
+ # get_breed_recommendations=get_breed_recommendations,
465
+ # format_recommendation_html=format_recommendation_html,
466
+ # history_component=history_component
467
+ # )
468
+
469
+
470
+ # # 4. 最後創建歷史記錄標籤頁
471
+ # create_history_tab(history_component)
472
+
473
+ # # Footer
474
+ # gr.HTML('''
475
+ # <div style="
476
+ # display: flex;
477
+ # align-items: center;
478
+ # justify-content: center;
479
+ # gap: 20px;
480
+ # padding: 20px 0;
481
+ # ">
482
+ # <p style="
483
+ # font-family: 'Arial', sans-serif;
484
+ # font-size: 14px;
485
+ # font-weight: 500;
486
+ # letter-spacing: 2px;
487
+ # background: linear-gradient(90deg, #555, #007ACC);
488
+ # -webkit-background-clip: text;
489
+ # -webkit-text-fill-color: transparent;
490
+ # margin: 0;
491
+ # text-transform: uppercase;
492
+ # display: inline-block;
493
+ # ">EXPLORE THE CODE →</p>
494
+ # <a href="https://github.com/Eric-Chung-0511/Learning-Record/tree/main/Data%20Science%20Projects/PawMatchAI" style="text-decoration: none;">
495
+ # <img src="https://img.shields.io/badge/GitHub-PawMatch_AI-007ACC?logo=github&style=for-the-badge">
496
+ # </a>
497
+ # </div>
498
+ # ''')
499
+
500
+ # return iface
501
+
502
+ # if __name__ == "__main__":
503
+ # iface = main()
504
+ # iface.launch()
505
+
506
+
507
  model_yolo = YOLO('yolov8l.pt')
508
 
509
  history_manager = UserHistoryManager()
 
565
  return out
566
 
567
  class BaseModel(nn.Module):
568
+
569
  def __init__(self, num_classes, device='cuda' if torch.cuda.is_available() else 'cpu'):
570
  super().__init__()
571
+ self.device_mgr = DeviceManager()
572
+ self.device = self.device_mgr.get_optimal_device()
573
  self.backbone = efficientnet_v2_m(weights=EfficientNet_V2_M_Weights.IMAGENET1K_V1)
574
  self.feature_dim = self.backbone.classifier[1].in_features
575
  self.backbone.classifier = nn.Identity()
 
585
 
586
  self.to(device)
587
 
588
+ @device_handler
589
  def forward(self, x):
590
  x = x.to(self.device)
591
  features = self.backbone(x)
 
594
  return logits, attended_features
595
 
596
  # Initialize model
597
+ device_mgr = DeviceManager()
598
  num_classes = len(dog_breeds)
 
599
 
600
  # Initialize base model
601
  model = BaseModel(num_classes=num_classes, device=device).to(device)
602
 
603
  # Load model path
604
  model_path = '124_best_model_dog.pth'
605
+ checkpoint = torch.load(model_path, map_location=device_mgr.get_optimal_device())
606
 
607
  # Load model state
608
  model.load_state_dict(checkpoint['base_model'], strict=False)
 
622
  ])
623
 
624
  return transform(image).unsqueeze(0)
625
+
626
+ @device_handler
627
  async def predict_single_dog(image):
628
  """
629
  Predicts the dog breed using only the classifier.
 
654
  print(f"{breed}: {prob:.4f}")
655
 
656
  return probabilities[0], breeds[:3], relative_probs
657
+
658
 
659
+ @device_handler
660
  async def detect_multiple_dogs(image, conf_threshold=0.3, iou_threshold=0.55):
661
  results = model_yolo(image, conf=conf_threshold, iou=iou_threshold)[0]
662
  dogs = []