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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import numpy as np
3
+ import torch
4
+ import torch.nn as nn
5
+ import gradio as gr
6
+ import time
7
+ import spaces
8
+ import timm
9
+ from torchvision.ops import nms, box_iou
10
+ import torch.nn.functional as F
11
+ from torchvision import transforms
12
+ from PIL import Image, ImageDraw, ImageFont, ImageFilter
13
+ from breed_health_info import breed_health_info
14
+ from breed_noise_info import breed_noise_info
15
+ from dog_database import get_dog_description
16
+ from scoring_calculation_system import UserPreferences, calculate_compatibility_score
17
+ from recommendation_html_format import format_recommendation_html, get_breed_recommendations
18
+ from history_manager import UserHistoryManager
19
+ from search_history import create_history_tab, create_history_component
20
+ from styles import get_css_styles
21
+ from breed_detection import create_detection_tab
22
+ from breed_comparison import create_comparison_tab
23
+ from breed_recommendation import create_recommendation_tab
24
+ from breed_visualization import create_visualization_tab
25
+ from html_templates import (
26
+ format_description_html,
27
+ format_single_dog_result,
28
+ format_multiple_breeds_result,
29
+ format_unknown_breed_message,
30
+ format_not_dog_message,
31
+ format_hint_html,
32
+ format_multi_dog_container,
33
+ format_breed_details_html,
34
+ get_color_scheme,
35
+ get_akc_breeds_link
36
+ )
37
+ from model_architecture import BaseModel, dog_breeds
38
+ from urllib.parse import quote
39
+ from ultralytics import YOLO
40
+ import asyncio
41
+ import traceback
42
+
43
+ history_manager = UserHistoryManager()
44
+
45
+ class ModelManager:
46
+ """
47
+ Singleton class for managing model instances and device allocation
48
+ specifically designed for Hugging Face Spaces deployment.
49
+ """
50
+ _instance = None
51
+ _initialized = False
52
+ _yolo_model = None
53
+ _breed_model = None
54
+ _device = None
55
+
56
+ def __new__(cls):
57
+ if cls._instance is None:
58
+ cls._instance = super().__new__(cls)
59
+ return cls._instance
60
+
61
+ def __init__(self):
62
+ if not ModelManager._initialized:
63
+ self._device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
64
+ ModelManager._initialized = True
65
+
66
+ @property
67
+ def device(self):
68
+ if self._device is None:
69
+ self._device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
70
+ return self._device
71
+
72
+ @property
73
+ def yolo_model(self):
74
+ if self._yolo_model is None:
75
+ self._yolo_model = YOLO('yolov8x.pt')
76
+ return self._yolo_model
77
+
78
+ @property
79
+ def breed_model(self):
80
+ if self._breed_model is None:
81
+ self._breed_model = BaseModel(
82
+ num_classes=len(dog_breeds),
83
+ device=self.device
84
+ ).to(self.device)
85
+
86
+ checkpoint = torch.load(
87
+ 'ConvNextV2Base_best_model.pth',
88
+ map_location=self.device
89
+ )
90
+ self._breed_model.load_state_dict(checkpoint['base_model'], strict=False)
91
+ self._breed_model.eval()
92
+ return self._breed_model
93
+
94
+ # Initialize model manager
95
+ model_manager = ModelManager()
96
+
97
+ def preprocess_image(image):
98
+ """Preprocesses images for model input"""
99
+ if isinstance(image, np.ndarray):
100
+ image = Image.fromarray(image)
101
+
102
+ transform = transforms.Compose([
103
+ transforms.Resize((224, 224)),
104
+ transforms.ToTensor(),
105
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
106
+ ])
107
+
108
+ return transform(image).unsqueeze(0)
109
+
110
+ @spaces.GPU
111
+ def predict_single_dog(image):
112
+ """Predicts dog breed for a single image"""
113
+ image_tensor = preprocess_image(image).to(model_manager.device)
114
+
115
+ with torch.no_grad():
116
+ logits = model_manager.breed_model(image_tensor)[0]
117
+ probs = F.softmax(logits, dim=1)
118
+
119
+ top5_prob, top5_idx = torch.topk(probs, k=5)
120
+ breeds = [dog_breeds[idx.item()] for idx in top5_idx[0]]
121
+ probabilities = [prob.item() for prob in top5_prob[0]]
122
+
123
+ sum_probs = sum(probabilities[:3])
124
+ relative_probs = [f"{(prob/sum_probs * 100):.2f}%" for prob in probabilities[:3]]
125
+
126
+ return probabilities[0], breeds[:3], relative_probs
127
+
128
+ def enhanced_preprocess(image, is_standing=False, has_overlap=False):
129
+ """
130
+ Enhanced image preprocessing function with special handling for different poses
131
+ and overlapping cases.
132
+ """
133
+ target_size = 224
134
+ w, h = image.size
135
+
136
+ if is_standing:
137
+ if h > w * 1.5:
138
+ new_h = target_size
139
+ new_w = min(target_size, int(w * (target_size / h)))
140
+ new_w = max(new_w, int(target_size * 0.6))
141
+ elif has_overlap:
142
+ scale = min(target_size/w, target_size/h) * 0.95
143
+ new_w = int(w * scale)
144
+ new_h = int(h * scale)
145
+ else:
146
+ scale = min(target_size/w, target_size/h)
147
+ new_w = int(w * scale)
148
+ new_h = int(h * scale)
149
+
150
+ resized = image.resize((new_w, new_h), Image.Resampling.LANCZOS)
151
+ final_image = Image.new('RGB', (target_size, target_size), (240, 240, 240))
152
+ paste_x = (target_size - new_w) // 2
153
+ paste_y = (target_size - new_h) // 2
154
+ final_image.paste(resized, (paste_x, paste_y))
155
+
156
+ return final_image
157
+
158
+ @spaces.GPU
159
+ def detect_multiple_dogs(image, conf_threshold=0.3, iou_threshold=0.3):
160
+ """
161
+ Enhanced multiple dog detection with improved bounding box handling and
162
+ intelligent boundary adjustments.
163
+ """
164
+ results = model_manager.yolo_model(image, conf=conf_threshold, iou=iou_threshold)[0]
165
+ img_width, img_height = image.size
166
+ detected_boxes = []
167
+
168
+ # Phase 1: Initial detection and processing
169
+ for box in results.boxes:
170
+ if box.cls.item() == 16: # Dog class
171
+ xyxy = box.xyxy[0].tolist()
172
+ confidence = box.conf.item()
173
+ x1, y1, x2, y2 = map(int, xyxy)
174
+ w = x2 - x1
175
+ h = y2 - y1
176
+
177
+ detected_boxes.append({
178
+ 'coords': [x1, y1, x2, y2],
179
+ 'width': w,
180
+ 'height': h,
181
+ 'center_x': (x1 + x2) / 2,
182
+ 'center_y': (y1 + y2) / 2,
183
+ 'area': w * h,
184
+ 'confidence': confidence,
185
+ 'aspect_ratio': w / h if h != 0 else 1
186
+ })
187
+
188
+ if not detected_boxes:
189
+ return [(image, 1.0, [0, 0, img_width, img_height], False)]
190
+
191
+ # Phase 2: Analysis of detection relationships
192
+ avg_height = sum(box['height'] for box in detected_boxes) / len(detected_boxes)
193
+ avg_width = sum(box['width'] for box in detected_boxes) / len(detected_boxes)
194
+ avg_area = sum(box['area'] for box in detected_boxes) / len(detected_boxes)
195
+
196
+ def calculate_iou(box1, box2):
197
+ x1 = max(box1['coords'][0], box2['coords'][0])
198
+ y1 = max(box1['coords'][1], box2['coords'][1])
199
+ x2 = min(box1['coords'][2], box2['coords'][2])
200
+ y2 = min(box1['coords'][3], box2['coords'][3])
201
+
202
+ if x2 <= x1 or y2 <= y1:
203
+ return 0.0
204
+
205
+ intersection = (x2 - x1) * (y2 - y1)
206
+ area1 = box1['area']
207
+ area2 = box2['area']
208
+ return intersection / (area1 + area2 - intersection)
209
+
210
+ # Phase 3: Processing each detection
211
+ processed_boxes = []
212
+ overlap_threshold = 0.2
213
+
214
+ for i, box_info in enumerate(detected_boxes):
215
+ x1, y1, x2, y2 = box_info['coords']
216
+ w = box_info['width']
217
+ h = box_info['height']
218
+ center_x = box_info['center_x']
219
+ center_y = box_info['center_y']
220
+
221
+ # Check for overlaps
222
+ has_overlap = False
223
+ for j, other_box in enumerate(detected_boxes):
224
+ if i != j and calculate_iou(box_info, other_box) > overlap_threshold:
225
+ has_overlap = True
226
+ break
227
+
228
+ # Adjust expansion strategy
229
+ base_expansion = 0.03
230
+ max_expansion = 0.05
231
+
232
+ is_standing = h > 1.5 * w
233
+ is_sitting = 0.8 <= h/w <= 1.2
234
+ is_abnormal_size = (h * w) > (avg_area * 1.5) or (h * w) < (avg_area * 0.5)
235
+
236
+ if has_overlap:
237
+ h_expansion = w_expansion = base_expansion * 0.8
238
+ else:
239
+ if is_standing:
240
+ h_expansion = min(base_expansion * 1.2, max_expansion)
241
+ w_expansion = base_expansion
242
+ elif is_sitting:
243
+ h_expansion = w_expansion = base_expansion
244
+ else:
245
+ h_expansion = w_expansion = base_expansion * 0.9
246
+
247
+ # Position compensation
248
+ if center_x < img_width * 0.2 or center_x > img_width * 0.8:
249
+ w_expansion *= 0.9
250
+
251
+ if is_abnormal_size:
252
+ h_expansion *= 0.8
253
+ w_expansion *= 0.8
254
+
255
+ # Calculate final bounding box
256
+ expansion_w = w * w_expansion
257
+ expansion_h = h * h_expansion
258
+
259
+ new_x1 = max(0, center_x - (w + expansion_w)/2)
260
+ new_y1 = max(0, center_y - (h + expansion_h)/2)
261
+ new_x2 = min(img_width, center_x + (w + expansion_w)/2)
262
+ new_y2 = min(img_height, center_y + (h + expansion_h)/2)
263
+
264
+ # Crop and process image
265
+ cropped_image = image.crop((int(new_x1), int(new_y1),
266
+ int(new_x2), int(new_y2)))
267
+
268
+ processed_image = enhanced_preprocess(
269
+ cropped_image,
270
+ is_standing=is_standing,
271
+ has_overlap=has_overlap
272
+ )
273
+
274
+ processed_boxes.append((
275
+ processed_image,
276
+ box_info['confidence'],
277
+ [new_x1, new_y1, new_x2, new_y2],
278
+ True
279
+ ))
280
+
281
+ return processed_boxes
282
+
283
+ @spaces.GPU
284
+ def predict(image):
285
+ """
286
+ Main prediction function that handles both single and multiple dog detection.
287
+ Args:
288
+ image: PIL Image or numpy array
289
+ Returns:
290
+ tuple: (html_output, annotated_image, initial_state)
291
+ """
292
+ if image is None:
293
+ return format_hint_html("Please upload an image to start."), None, None
294
+
295
+ try:
296
+ if isinstance(image, np.ndarray):
297
+ image = Image.fromarray(image)
298
+
299
+ # 檢測圖片中的物體
300
+ dogs = detect_multiple_dogs(image)
301
+ color_scheme = get_color_scheme(len(dogs) == 1)
302
+
303
+ # 準備標註
304
+ annotated_image = image.copy()
305
+ draw = ImageDraw.Draw(annotated_image)
306
+
307
+ try:
308
+ font = ImageFont.truetype("arial.ttf", 24)
309
+ except:
310
+ font = ImageFont.load_default()
311
+
312
+ dogs_info = ""
313
+
314
+ # 處理每個檢測到的物體
315
+ for i, (cropped_image, detection_confidence, box, is_dog) in enumerate(dogs):
316
+ print(f"Predict processing - Object {i+1}:")
317
+ print(f" Is dog: {is_dog}")
318
+ print(f" Detection confidence: {detection_confidence:.4f}")
319
+
320
+ # 如果是狗且進行品種預測,在這裡也加入打印語句
321
+ if is_dog:
322
+ top1_prob, topk_breeds, relative_probs = predict_single_dog(cropped_image)
323
+ print(f" Breed prediction - Top probability: {top1_prob:.4f}")
324
+ print(f" Top breeds: {topk_breeds[:3]}")
325
+ color = color_scheme if len(dogs) == 1 else color_scheme[i % len(color_scheme)]
326
+
327
+ # 繪製框和標籤
328
+ draw.rectangle(box, outline=color, width=4)
329
+ label = f"Dog {i+1}" if is_dog else f"Object {i+1}"
330
+ label_bbox = draw.textbbox((0, 0), label, font=font)
331
+ label_width = label_bbox[2] - label_bbox[0]
332
+ label_height = label_bbox[3] - label_bbox[1]
333
+
334
+ # 繪製標籤背景和文字
335
+ label_x = box[0] + 5
336
+ label_y = box[1] + 5
337
+ draw.rectangle(
338
+ [label_x - 2, label_y - 2, label_x + label_width + 4, label_y + label_height + 4],
339
+ fill='white',
340
+ outline=color,
341
+ width=2
342
+ )
343
+ draw.text((label_x, label_y), label, fill=color, font=font)
344
+
345
+ try:
346
+ # 首先檢查是否為狗
347
+ if not is_dog:
348
+ dogs_info += format_not_dog_message(color, i+1)
349
+ continue
350
+
351
+ # 如果是狗,進行品種預測
352
+ top1_prob, topk_breeds, relative_probs = predict_single_dog(cropped_image)
353
+ combined_confidence = detection_confidence * top1_prob
354
+
355
+ # 根據信心度決定輸出格式
356
+ if combined_confidence < 0.15:
357
+ dogs_info += format_unknown_breed_message(color, i+1)
358
+ elif top1_prob >= 0.4:
359
+ breed = topk_breeds[0]
360
+ description = get_dog_description(breed)
361
+ if description is None:
362
+ description = {
363
+ "Name": breed,
364
+ "Size": "Unknown",
365
+ "Exercise Needs": "Unknown",
366
+ "Grooming Needs": "Unknown",
367
+ "Care Level": "Unknown",
368
+ "Good with Children": "Unknown",
369
+ "Description": f"Identified as {breed.replace('_', ' ')}"
370
+ }
371
+ dogs_info += format_single_dog_result(breed, description, color)
372
+ else:
373
+ dogs_info += format_multiple_breeds_result(
374
+ topk_breeds,
375
+ relative_probs,
376
+ color,
377
+ i+1,
378
+ lambda breed: get_dog_description(breed) or {
379
+ "Name": breed,
380
+ "Size": "Unknown",
381
+ "Exercise Needs": "Unknown",
382
+ "Grooming Needs": "Unknown",
383
+ "Care Level": "Unknown",
384
+ "Good with Children": "Unknown",
385
+ "Description": f"Identified as {breed.replace('_', ' ')}"
386
+ }
387
+ )
388
+ except Exception as e:
389
+ print(f"Error formatting results for dog {i+1}: {str(e)}")
390
+ dogs_info += format_unknown_breed_message(color, i+1)
391
+
392
+ # 包裝最終的HTML輸出
393
+ html_output = format_multi_dog_container(dogs_info)
394
+
395
+ # 準備初始狀態
396
+ initial_state = {
397
+ "dogs_info": dogs_info,
398
+ "image": annotated_image,
399
+ "is_multi_dog": len(dogs) > 1,
400
+ "html_output": html_output
401
+ }
402
+
403
+ return html_output, annotated_image, initial_state
404
+
405
+ except Exception as e:
406
+ error_msg = f"An error occurred: {str(e)}\n\nTraceback:\n{traceback.format_exc()}"
407
+ print(error_msg)
408
+ return format_hint_html(error_msg), None, None
409
+
410
+
411
+ def show_details_html(choice, previous_output, initial_state):
412
+ """
413
+ Generate detailed HTML view for a selected breed.
414
+
415
+ Args:
416
+ choice: str, Selected breed option
417
+ previous_output: str, Previous HTML output
418
+ initial_state: dict, Current state information
419
+
420
+ Returns:
421
+ tuple: (html_output, gradio_update, updated_state)
422
+ """
423
+ if not choice:
424
+ return previous_output, gr.update(visible=True), initial_state
425
+
426
+ try:
427
+ breed = choice.split("More about ")[-1]
428
+ description = get_dog_description(breed)
429
+ html_output = format_breed_details_html(description, breed)
430
+
431
+ # Update state
432
+ initial_state["current_description"] = html_output
433
+ initial_state["original_buttons"] = initial_state.get("buttons", [])
434
+
435
+ return html_output, gr.update(visible=True), initial_state
436
+
437
+ except Exception as e:
438
+ error_msg = f"An error occurred while showing details: {e}"
439
+ print(error_msg)
440
+ return format_hint_html(error_msg), gr.update(visible=True), initial_state
441
+
442
+ def main():
443
+ with gr.Blocks(css=get_css_styles()) as iface:
444
+ # Header HTML
445
+
446
+ gr.HTML("""
447
+ <header style='text-align: center; padding: 20px; margin-bottom: 20px;'>
448
+ <h1 style='font-size: 2.5em; margin-bottom: 10px; color: #2D3748;'>
449
+ 🐾 PawMatch AI
450
+ </h1>
451
+ <h2 style='font-size: 1.2em; font-weight: normal; color: #4A5568; margin-top: 5px;'>
452
+ Your Smart Dog Breed Guide
453
+ </h2>
454
+ <div style='width: 50px; height: 3px; background: linear-gradient(90deg, #4299e1, #48bb78); margin: 15px auto;'></div>
455
+ <p style='color: #718096; font-size: 0.9em;'>
456
+ Powered by AI • Breed Recognition • Smart Matching • Companion Guide
457
+ </p>
458
+ </header>
459
+ """)
460
+
461
+ # 先創建歷史組件實例(但不創建標籤頁)
462
+ history_component = create_history_component()
463
+
464
+ with gr.Tabs():
465
+ # 1. 品種檢測標籤頁
466
+ example_images = [
467
+ 'Border_Collie.jpg',
468
+ 'Golden_Retriever.jpeg',
469
+ 'Saint_Bernard.jpeg',
470
+ 'Samoyed.jpeg',
471
+ 'French_Bulldog.jpeg'
472
+ ]
473
+ detection_components = create_detection_tab(predict, example_images)
474
+
475
+ # 2. 品種比較標籤頁
476
+ comparison_components = create_comparison_tab(
477
+ dog_breeds=dog_breeds,
478
+ get_dog_description=get_dog_description,
479
+ breed_health_info=breed_health_info,
480
+ breed_noise_info=breed_noise_info
481
+ )
482
+
483
+ # 3. 品種推薦標籤頁
484
+ recommendation_components = create_recommendation_tab(
485
+ UserPreferences=UserPreferences,
486
+ get_breed_recommendations=get_breed_recommendations,
487
+ format_recommendation_html=format_recommendation_html,
488
+ history_component=history_component
489
+ )
490
+
491
+ # 4. 新加入的視覺化標籤頁
492
+ with gr.Tab("Visualization Analysis"):
493
+ create_visualization_tab(
494
+ dog_breeds=dog_breeds,
495
+ get_dog_description=get_dog_description,
496
+ calculate_compatibility_score=calculate_compatibility_score,
497
+ UserPreferences=UserPreferences
498
+ )
499
+
500
+
501
+ # 5. 最後創建歷史記錄標籤頁
502
+ create_history_tab(history_component)
503
+
504
+ # Footer
505
+ gr.HTML('''
506
+ <div style="
507
+ display: flex;
508
+ align-items: center;
509
+ justify-content: center;
510
+ gap: 20px;
511
+ padding: 20px 0;
512
+ ">
513
+ <p style="
514
+ font-family: 'Arial', sans-serif;
515
+ font-size: 14px;
516
+ font-weight: 500;
517
+ letter-spacing: 2px;
518
+ background: linear-gradient(90deg, #555, #007ACC);
519
+ -webkit-background-clip: text;
520
+ -webkit-text-fill-color: transparent;
521
+ margin: 0;
522
+ text-transform: uppercase;
523
+ display: inline-block;
524
+ ">EXPLORE THE CODE →</p>
525
+ <a href="https://github.com/Eric-Chung-0511/Learning-Record/tree/main/Data%20Science%20Projects/PawMatchAI" style="text-decoration: none;">
526
+ <img src="https://img.shields.io/badge/GitHub-PawMatch_AI-007ACC?logo=github&style=for-the-badge">
527
+ </a>
528
+ </div>
529
+ ''')
530
+
531
+ return iface
532
+
533
+ if __name__ == "__main__":
534
+ iface = main()
535
+ iface.launch()