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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 timm
|
| 8 |
+
from torchvision.ops import nms, box_iou
|
| 9 |
+
import torch.nn.functional as F
|
| 10 |
+
from torchvision import transforms
|
| 11 |
+
from PIL import Image, ImageDraw, ImageFont, ImageFilter
|
| 12 |
+
from breed_health_info import breed_health_info
|
| 13 |
+
from breed_noise_info import breed_noise_info
|
| 14 |
+
from dog_database import get_dog_description
|
| 15 |
+
from scoring_calculation_system import UserPreferences
|
| 16 |
+
from recommendation_html_format import format_recommendation_html, get_breed_recommendations
|
| 17 |
+
from history_manager import UserHistoryManager
|
| 18 |
+
from search_history import create_history_tab, create_history_component
|
| 19 |
+
from styles import get_css_styles
|
| 20 |
+
from breed_detection import create_detection_tab
|
| 21 |
+
from breed_comparison import create_comparison_tab
|
| 22 |
+
from breed_recommendation import create_recommendation_tab
|
| 23 |
+
from html_templates import (
|
| 24 |
+
format_description_html,
|
| 25 |
+
format_single_dog_result,
|
| 26 |
+
format_multiple_breeds_result,
|
| 27 |
+
format_error_message,
|
| 28 |
+
format_warning_html,
|
| 29 |
+
format_multi_dog_container,
|
| 30 |
+
format_breed_details_html,
|
| 31 |
+
get_color_scheme,
|
| 32 |
+
get_akc_breeds_link
|
| 33 |
+
)
|
| 34 |
+
from model_architecture import BaseModel, dog_breeds
|
| 35 |
+
from urllib.parse import quote
|
| 36 |
+
from ultralytics import YOLO
|
| 37 |
+
import asyncio
|
| 38 |
+
import traceback
|
| 39 |
+
|
| 40 |
+
history_manager = UserHistoryManager()
|
| 41 |
+
|
| 42 |
+
class ModelManager:
|
| 43 |
+
"""
|
| 44 |
+
Singleton class for managing model instances and device allocation
|
| 45 |
+
specifically designed for Hugging Face Spaces deployment.
|
| 46 |
+
"""
|
| 47 |
+
_instance = None
|
| 48 |
+
_initialized = False
|
| 49 |
+
_yolo_model = None
|
| 50 |
+
_breed_model = None
|
| 51 |
+
_device = None
|
| 52 |
+
|
| 53 |
+
def __new__(cls):
|
| 54 |
+
if cls._instance is None:
|
| 55 |
+
cls._instance = super().__new__(cls)
|
| 56 |
+
return cls._instance
|
| 57 |
+
|
| 58 |
+
def __init__(self):
|
| 59 |
+
if not ModelManager._initialized:
|
| 60 |
+
self._device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 61 |
+
ModelManager._initialized = True
|
| 62 |
+
|
| 63 |
+
@property
|
| 64 |
+
def device(self):
|
| 65 |
+
if self._device is None:
|
| 66 |
+
self._device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 67 |
+
return self._device
|
| 68 |
+
|
| 69 |
+
@property
|
| 70 |
+
def yolo_model(self):
|
| 71 |
+
if self._yolo_model is None:
|
| 72 |
+
self._yolo_model = YOLO('yolov8x.pt')
|
| 73 |
+
return self._yolo_model
|
| 74 |
+
|
| 75 |
+
@property
|
| 76 |
+
def breed_model(self):
|
| 77 |
+
if self._breed_model is None:
|
| 78 |
+
self._breed_model = BaseModel(
|
| 79 |
+
num_classes=len(dog_breeds),
|
| 80 |
+
device=self.device
|
| 81 |
+
).to(self.device)
|
| 82 |
+
|
| 83 |
+
checkpoint = torch.load(
|
| 84 |
+
'ConvNextV2Base_best_model.pth',
|
| 85 |
+
map_location=self.device
|
| 86 |
+
)
|
| 87 |
+
self._breed_model.load_state_dict(checkpoint['base_model'], strict=False)
|
| 88 |
+
self._breed_model.eval()
|
| 89 |
+
return self._breed_model
|
| 90 |
+
|
| 91 |
+
# Initialize model manager
|
| 92 |
+
model_manager = ModelManager()
|
| 93 |
+
|
| 94 |
+
def preprocess_image(image):
|
| 95 |
+
"""Preprocesses images for model input"""
|
| 96 |
+
if isinstance(image, np.ndarray):
|
| 97 |
+
image = Image.fromarray(image)
|
| 98 |
+
|
| 99 |
+
transform = transforms.Compose([
|
| 100 |
+
transforms.Resize((224, 224)),
|
| 101 |
+
transforms.ToTensor(),
|
| 102 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
|
| 103 |
+
])
|
| 104 |
+
|
| 105 |
+
return transform(image).unsqueeze(0)
|
| 106 |
+
|
| 107 |
+
@spaces.GPU
|
| 108 |
+
def predict_single_dog(image):
|
| 109 |
+
"""Predicts dog breed for a single image"""
|
| 110 |
+
image_tensor = preprocess_image(image).to(model_manager.device)
|
| 111 |
+
|
| 112 |
+
with torch.no_grad():
|
| 113 |
+
logits = model_manager.breed_model(image_tensor)[0]
|
| 114 |
+
probs = F.softmax(logits, dim=1)
|
| 115 |
+
|
| 116 |
+
top5_prob, top5_idx = torch.topk(probs, k=5)
|
| 117 |
+
breeds = [dog_breeds[idx.item()] for idx in top5_idx[0]]
|
| 118 |
+
probabilities = [prob.item() for prob in top5_prob[0]]
|
| 119 |
+
|
| 120 |
+
sum_probs = sum(probabilities[:3])
|
| 121 |
+
relative_probs = [f"{(prob/sum_probs * 100):.2f}%" for prob in probabilities[:3]]
|
| 122 |
+
|
| 123 |
+
return probabilities[0], breeds[:3], relative_probs
|
| 124 |
+
|
| 125 |
+
def enhanced_preprocess(image, is_standing=False, has_overlap=False):
|
| 126 |
+
"""
|
| 127 |
+
Enhanced image preprocessing function with special handling for different poses
|
| 128 |
+
and overlapping cases.
|
| 129 |
+
"""
|
| 130 |
+
target_size = 224
|
| 131 |
+
w, h = image.size
|
| 132 |
+
|
| 133 |
+
if is_standing:
|
| 134 |
+
if h > w * 1.5:
|
| 135 |
+
new_h = target_size
|
| 136 |
+
new_w = min(target_size, int(w * (target_size / h)))
|
| 137 |
+
new_w = max(new_w, int(target_size * 0.6))
|
| 138 |
+
elif has_overlap:
|
| 139 |
+
scale = min(target_size/w, target_size/h) * 0.95
|
| 140 |
+
new_w = int(w * scale)
|
| 141 |
+
new_h = int(h * scale)
|
| 142 |
+
else:
|
| 143 |
+
scale = min(target_size/w, target_size/h)
|
| 144 |
+
new_w = int(w * scale)
|
| 145 |
+
new_h = int(h * scale)
|
| 146 |
+
|
| 147 |
+
resized = image.resize((new_w, new_h), Image.Resampling.LANCZOS)
|
| 148 |
+
final_image = Image.new('RGB', (target_size, target_size), (240, 240, 240))
|
| 149 |
+
paste_x = (target_size - new_w) // 2
|
| 150 |
+
paste_y = (target_size - new_h) // 2
|
| 151 |
+
final_image.paste(resized, (paste_x, paste_y))
|
| 152 |
+
|
| 153 |
+
return final_image
|
| 154 |
+
|
| 155 |
+
@spaces.GPU
|
| 156 |
+
def detect_multiple_dogs(image, conf_threshold=0.3, iou_threshold=0.3):
|
| 157 |
+
"""
|
| 158 |
+
Enhanced multiple dog detection with improved bounding box handling and
|
| 159 |
+
intelligent boundary adjustments.
|
| 160 |
+
"""
|
| 161 |
+
results = model_manager.yolo_model(image, conf=conf_threshold, iou=iou_threshold)[0]
|
| 162 |
+
img_width, img_height = image.size
|
| 163 |
+
detected_boxes = []
|
| 164 |
+
|
| 165 |
+
# Phase 1: Initial detection and processing
|
| 166 |
+
for box in results.boxes:
|
| 167 |
+
if box.cls.item() == 16: # Dog class
|
| 168 |
+
xyxy = box.xyxy[0].tolist()
|
| 169 |
+
confidence = box.conf.item()
|
| 170 |
+
x1, y1, x2, y2 = map(int, xyxy)
|
| 171 |
+
w = x2 - x1
|
| 172 |
+
h = y2 - y1
|
| 173 |
+
|
| 174 |
+
detected_boxes.append({
|
| 175 |
+
'coords': [x1, y1, x2, y2],
|
| 176 |
+
'width': w,
|
| 177 |
+
'height': h,
|
| 178 |
+
'center_x': (x1 + x2) / 2,
|
| 179 |
+
'center_y': (y1 + y2) / 2,
|
| 180 |
+
'area': w * h,
|
| 181 |
+
'confidence': confidence,
|
| 182 |
+
'aspect_ratio': w / h if h != 0 else 1
|
| 183 |
+
})
|
| 184 |
+
|
| 185 |
+
if not detected_boxes:
|
| 186 |
+
return [(image, 1.0, [0, 0, img_width, img_height], False)]
|
| 187 |
+
|
| 188 |
+
# Phase 2: Analysis of detection relationships
|
| 189 |
+
avg_height = sum(box['height'] for box in detected_boxes) / len(detected_boxes)
|
| 190 |
+
avg_width = sum(box['width'] for box in detected_boxes) / len(detected_boxes)
|
| 191 |
+
avg_area = sum(box['area'] for box in detected_boxes) / len(detected_boxes)
|
| 192 |
+
|
| 193 |
+
def calculate_iou(box1, box2):
|
| 194 |
+
x1 = max(box1['coords'][0], box2['coords'][0])
|
| 195 |
+
y1 = max(box1['coords'][1], box2['coords'][1])
|
| 196 |
+
x2 = min(box1['coords'][2], box2['coords'][2])
|
| 197 |
+
y2 = min(box1['coords'][3], box2['coords'][3])
|
| 198 |
+
|
| 199 |
+
if x2 <= x1 or y2 <= y1:
|
| 200 |
+
return 0.0
|
| 201 |
+
|
| 202 |
+
intersection = (x2 - x1) * (y2 - y1)
|
| 203 |
+
area1 = box1['area']
|
| 204 |
+
area2 = box2['area']
|
| 205 |
+
return intersection / (area1 + area2 - intersection)
|
| 206 |
+
|
| 207 |
+
# Phase 3: Processing each detection
|
| 208 |
+
processed_boxes = []
|
| 209 |
+
overlap_threshold = 0.2
|
| 210 |
+
|
| 211 |
+
for i, box_info in enumerate(detected_boxes):
|
| 212 |
+
x1, y1, x2, y2 = box_info['coords']
|
| 213 |
+
w = box_info['width']
|
| 214 |
+
h = box_info['height']
|
| 215 |
+
center_x = box_info['center_x']
|
| 216 |
+
center_y = box_info['center_y']
|
| 217 |
+
|
| 218 |
+
# Check for overlaps
|
| 219 |
+
has_overlap = False
|
| 220 |
+
for j, other_box in enumerate(detected_boxes):
|
| 221 |
+
if i != j and calculate_iou(box_info, other_box) > overlap_threshold:
|
| 222 |
+
has_overlap = True
|
| 223 |
+
break
|
| 224 |
+
|
| 225 |
+
# Adjust expansion strategy
|
| 226 |
+
base_expansion = 0.03
|
| 227 |
+
max_expansion = 0.05
|
| 228 |
+
|
| 229 |
+
is_standing = h > 1.5 * w
|
| 230 |
+
is_sitting = 0.8 <= h/w <= 1.2
|
| 231 |
+
is_abnormal_size = (h * w) > (avg_area * 1.5) or (h * w) < (avg_area * 0.5)
|
| 232 |
+
|
| 233 |
+
if has_overlap:
|
| 234 |
+
h_expansion = w_expansion = base_expansion * 0.8
|
| 235 |
+
else:
|
| 236 |
+
if is_standing:
|
| 237 |
+
h_expansion = min(base_expansion * 1.2, max_expansion)
|
| 238 |
+
w_expansion = base_expansion
|
| 239 |
+
elif is_sitting:
|
| 240 |
+
h_expansion = w_expansion = base_expansion
|
| 241 |
+
else:
|
| 242 |
+
h_expansion = w_expansion = base_expansion * 0.9
|
| 243 |
+
|
| 244 |
+
# Position compensation
|
| 245 |
+
if center_x < img_width * 0.2 or center_x > img_width * 0.8:
|
| 246 |
+
w_expansion *= 0.9
|
| 247 |
+
|
| 248 |
+
if is_abnormal_size:
|
| 249 |
+
h_expansion *= 0.8
|
| 250 |
+
w_expansion *= 0.8
|
| 251 |
+
|
| 252 |
+
# Calculate final bounding box
|
| 253 |
+
expansion_w = w * w_expansion
|
| 254 |
+
expansion_h = h * h_expansion
|
| 255 |
+
|
| 256 |
+
new_x1 = max(0, center_x - (w + expansion_w)/2)
|
| 257 |
+
new_y1 = max(0, center_y - (h + expansion_h)/2)
|
| 258 |
+
new_x2 = min(img_width, center_x + (w + expansion_w)/2)
|
| 259 |
+
new_y2 = min(img_height, center_y + (h + expansion_h)/2)
|
| 260 |
+
|
| 261 |
+
# Crop and process image
|
| 262 |
+
cropped_image = image.crop((int(new_x1), int(new_y1),
|
| 263 |
+
int(new_x2), int(new_y2)))
|
| 264 |
+
|
| 265 |
+
processed_image = enhanced_preprocess(
|
| 266 |
+
cropped_image,
|
| 267 |
+
is_standing=is_standing,
|
| 268 |
+
has_overlap=has_overlap
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
processed_boxes.append((
|
| 272 |
+
processed_image,
|
| 273 |
+
box_info['confidence'],
|
| 274 |
+
[new_x1, new_y1, new_x2, new_y2],
|
| 275 |
+
True
|
| 276 |
+
))
|
| 277 |
+
|
| 278 |
+
return processed_boxes
|
| 279 |
+
|
| 280 |
+
@spaces.GPU
|
| 281 |
+
def predict(image):
|
| 282 |
+
"""
|
| 283 |
+
Main prediction function that handles both single and multiple dog detection.
|
| 284 |
+
Args:
|
| 285 |
+
image: PIL Image or numpy array
|
| 286 |
+
Returns:
|
| 287 |
+
tuple: (html_output, annotated_image, initial_state)
|
| 288 |
+
"""
|
| 289 |
+
if image is None:
|
| 290 |
+
return format_hint_html("Please upload an image to start."), None, None
|
| 291 |
+
|
| 292 |
+
try:
|
| 293 |
+
if isinstance(image, np.ndarray):
|
| 294 |
+
image = Image.fromarray(image)
|
| 295 |
+
|
| 296 |
+
# 檢測圖片中的物體
|
| 297 |
+
dogs = detect_multiple_dogs(image)
|
| 298 |
+
color_scheme = get_color_scheme(len(dogs) == 1)
|
| 299 |
+
|
| 300 |
+
# 準備標註
|
| 301 |
+
annotated_image = image.copy()
|
| 302 |
+
draw = ImageDraw.Draw(annotated_image)
|
| 303 |
+
|
| 304 |
+
try:
|
| 305 |
+
font = ImageFont.truetype("arial.ttf", 24)
|
| 306 |
+
except:
|
| 307 |
+
font = ImageFont.load_default()
|
| 308 |
+
|
| 309 |
+
dogs_info = ""
|
| 310 |
+
|
| 311 |
+
# 處理每個檢測到的物體
|
| 312 |
+
for i, (cropped_image, detection_confidence, box, is_dog) in enumerate(dogs):
|
| 313 |
+
print(f"Predict processing - Object {i+1}:")
|
| 314 |
+
print(f" Is dog: {is_dog}")
|
| 315 |
+
print(f" Detection confidence: {detection_confidence:.4f}")
|
| 316 |
+
|
| 317 |
+
# 如果是狗且進行品種預測,在這裡也加入打印語句
|
| 318 |
+
if is_dog:
|
| 319 |
+
top1_prob, topk_breeds, relative_probs = predict_single_dog(cropped_image)
|
| 320 |
+
print(f" Breed prediction - Top probability: {top1_prob:.4f}")
|
| 321 |
+
print(f" Top breeds: {topk_breeds[:3]}")
|
| 322 |
+
color = color_scheme if len(dogs) == 1 else color_scheme[i % len(color_scheme)]
|
| 323 |
+
|
| 324 |
+
# 繪製框和標籤
|
| 325 |
+
draw.rectangle(box, outline=color, width=4)
|
| 326 |
+
label = f"Dog {i+1}" if is_dog else f"Object {i+1}"
|
| 327 |
+
label_bbox = draw.textbbox((0, 0), label, font=font)
|
| 328 |
+
label_width = label_bbox[2] - label_bbox[0]
|
| 329 |
+
label_height = label_bbox[3] - label_bbox[1]
|
| 330 |
+
|
| 331 |
+
# 繪製標籤背景和文字
|
| 332 |
+
label_x = box[0] + 5
|
| 333 |
+
label_y = box[1] + 5
|
| 334 |
+
draw.rectangle(
|
| 335 |
+
[label_x - 2, label_y - 2, label_x + label_width + 4, label_y + label_height + 4],
|
| 336 |
+
fill='white',
|
| 337 |
+
outline=color,
|
| 338 |
+
width=2
|
| 339 |
+
)
|
| 340 |
+
draw.text((label_x, label_y), label, fill=color, font=font)
|
| 341 |
+
|
| 342 |
+
try:
|
| 343 |
+
# 首先檢查是否為狗
|
| 344 |
+
if not is_dog:
|
| 345 |
+
dogs_info += format_not_dog_message(color, i+1)
|
| 346 |
+
continue
|
| 347 |
+
|
| 348 |
+
# 如果是狗,進行品種預測
|
| 349 |
+
top1_prob, topk_breeds, relative_probs = predict_single_dog(cropped_image)
|
| 350 |
+
combined_confidence = detection_confidence * top1_prob
|
| 351 |
+
|
| 352 |
+
# 根據信心度決定輸出格式
|
| 353 |
+
if combined_confidence < 0.15:
|
| 354 |
+
dogs_info += format_unknown_breed_message(color, i+1)
|
| 355 |
+
elif top1_prob >= 0.4:
|
| 356 |
+
breed = topk_breeds[0]
|
| 357 |
+
description = get_dog_description(breed)
|
| 358 |
+
if description is None:
|
| 359 |
+
description = {
|
| 360 |
+
"Name": breed,
|
| 361 |
+
"Size": "Unknown",
|
| 362 |
+
"Exercise Needs": "Unknown",
|
| 363 |
+
"Grooming Needs": "Unknown",
|
| 364 |
+
"Care Level": "Unknown",
|
| 365 |
+
"Good with Children": "Unknown",
|
| 366 |
+
"Description": f"Identified as {breed.replace('_', ' ')}"
|
| 367 |
+
}
|
| 368 |
+
dogs_info += format_single_dog_result(breed, description, color)
|
| 369 |
+
else:
|
| 370 |
+
dogs_info += format_multiple_breeds_result(
|
| 371 |
+
topk_breeds,
|
| 372 |
+
relative_probs,
|
| 373 |
+
color,
|
| 374 |
+
i+1,
|
| 375 |
+
lambda breed: get_dog_description(breed) or {
|
| 376 |
+
"Name": breed,
|
| 377 |
+
"Size": "Unknown",
|
| 378 |
+
"Exercise Needs": "Unknown",
|
| 379 |
+
"Grooming Needs": "Unknown",
|
| 380 |
+
"Care Level": "Unknown",
|
| 381 |
+
"Good with Children": "Unknown",
|
| 382 |
+
"Description": f"Identified as {breed.replace('_', ' ')}"
|
| 383 |
+
}
|
| 384 |
+
)
|
| 385 |
+
except Exception as e:
|
| 386 |
+
print(f"Error formatting results for dog {i+1}: {str(e)}")
|
| 387 |
+
dogs_info += format_unknown_breed_message(color, i+1)
|
| 388 |
+
|
| 389 |
+
# 包裝最終的HTML輸出
|
| 390 |
+
html_output = format_multi_dog_container(dogs_info)
|
| 391 |
+
|
| 392 |
+
# 準備初始狀態
|
| 393 |
+
initial_state = {
|
| 394 |
+
"dogs_info": dogs_info,
|
| 395 |
+
"image": annotated_image,
|
| 396 |
+
"is_multi_dog": len(dogs) > 1,
|
| 397 |
+
"html_output": html_output
|
| 398 |
+
}
|
| 399 |
+
|
| 400 |
+
return html_output, annotated_image, initial_state
|
| 401 |
+
|
| 402 |
+
except Exception as e:
|
| 403 |
+
error_msg = f"An error occurred: {str(e)}\n\nTraceback:\n{traceback.format_exc()}"
|
| 404 |
+
print(error_msg)
|
| 405 |
+
return format_hint_html(error_msg), None, None
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
def show_details_html(choice, previous_output, initial_state):
|
| 409 |
+
"""
|
| 410 |
+
Generate detailed HTML view for a selected breed.
|
| 411 |
+
|
| 412 |
+
Args:
|
| 413 |
+
choice: str, Selected breed option
|
| 414 |
+
previous_output: str, Previous HTML output
|
| 415 |
+
initial_state: dict, Current state information
|
| 416 |
+
|
| 417 |
+
Returns:
|
| 418 |
+
tuple: (html_output, gradio_update, updated_state)
|
| 419 |
+
"""
|
| 420 |
+
if not choice:
|
| 421 |
+
return previous_output, gr.update(visible=True), initial_state
|
| 422 |
+
|
| 423 |
+
try:
|
| 424 |
+
breed = choice.split("More about ")[-1]
|
| 425 |
+
description = get_dog_description(breed)
|
| 426 |
+
html_output = format_breed_details_html(description, breed)
|
| 427 |
+
|
| 428 |
+
# Update state
|
| 429 |
+
initial_state["current_description"] = html_output
|
| 430 |
+
initial_state["original_buttons"] = initial_state.get("buttons", [])
|
| 431 |
+
|
| 432 |
+
return html_output, gr.update(visible=True), initial_state
|
| 433 |
+
|
| 434 |
+
except Exception as e:
|
| 435 |
+
error_msg = f"An error occurred while showing details: {e}"
|
| 436 |
+
print(error_msg)
|
| 437 |
+
return format_hint_html(error_msg), gr.update(visible=True), initial_state
|
| 438 |
+
|
| 439 |
+
def main():
|
| 440 |
+
with gr.Blocks(css=get_css_styles()) as iface:
|
| 441 |
+
# Header HTML
|
| 442 |
+
|
| 443 |
+
gr.HTML("""
|
| 444 |
+
<header style='text-align: center; padding: 20px; margin-bottom: 20px;'>
|
| 445 |
+
<h1 style='font-size: 2.5em; margin-bottom: 10px; color: #2D3748;'>
|
| 446 |
+
🐾 PawMatch AI
|
| 447 |
+
</h1>
|
| 448 |
+
<h2 style='font-size: 1.2em; font-weight: normal; color: #4A5568; margin-top: 5px;'>
|
| 449 |
+
Your Smart Dog Breed Guide
|
| 450 |
+
</h2>
|
| 451 |
+
<div style='width: 50px; height: 3px; background: linear-gradient(90deg, #4299e1, #48bb78); margin: 15px auto;'></div>
|
| 452 |
+
<p style='color: #718096; font-size: 0.9em;'>
|
| 453 |
+
Powered by AI • Breed Recognition • Smart Matching • Companion Guide
|
| 454 |
+
</p>
|
| 455 |
+
</header>
|
| 456 |
+
""")
|
| 457 |
+
|
| 458 |
+
# 先創建歷史組件實例(但不創建標籤頁)
|
| 459 |
+
history_component = create_history_component()
|
| 460 |
+
|
| 461 |
+
with gr.Tabs():
|
| 462 |
+
# 1. 品種檢測標籤頁
|
| 463 |
+
example_images = [
|
| 464 |
+
'Border_Collie.jpg',
|
| 465 |
+
'Golden_Retriever.jpeg',
|
| 466 |
+
'Saint_Bernard.jpeg',
|
| 467 |
+
'Samoyed.jpeg',
|
| 468 |
+
'French_Bulldog.jpeg'
|
| 469 |
+
]
|
| 470 |
+
detection_components = create_detection_tab(predict, example_images)
|
| 471 |
+
|
| 472 |
+
# 2. 品種比較標籤頁
|
| 473 |
+
comparison_components = create_comparison_tab(
|
| 474 |
+
dog_breeds=dog_breeds,
|
| 475 |
+
get_dog_description=get_dog_description,
|
| 476 |
+
breed_health_info=breed_health_info,
|
| 477 |
+
breed_noise_info=breed_noise_info
|
| 478 |
+
)
|
| 479 |
+
|
| 480 |
+
# 3. 品種推薦標籤頁
|
| 481 |
+
recommendation_components = create_recommendation_tab(
|
| 482 |
+
UserPreferences=UserPreferences,
|
| 483 |
+
get_breed_recommendations=get_breed_recommendations,
|
| 484 |
+
format_recommendation_html=format_recommendation_html,
|
| 485 |
+
history_component=history_component
|
| 486 |
+
)
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
# 4. 最後創建歷史記錄標籤頁
|
| 490 |
+
create_history_tab(history_component)
|
| 491 |
+
|
| 492 |
+
# Footer
|
| 493 |
+
gr.HTML('''
|
| 494 |
+
<div style="
|
| 495 |
+
display: flex;
|
| 496 |
+
align-items: center;
|
| 497 |
+
justify-content: center;
|
| 498 |
+
gap: 20px;
|
| 499 |
+
padding: 20px 0;
|
| 500 |
+
">
|
| 501 |
+
<p style="
|
| 502 |
+
font-family: 'Arial', sans-serif;
|
| 503 |
+
font-size: 14px;
|
| 504 |
+
font-weight: 500;
|
| 505 |
+
letter-spacing: 2px;
|
| 506 |
+
background: linear-gradient(90deg, #555, #007ACC);
|
| 507 |
+
-webkit-background-clip: text;
|
| 508 |
+
-webkit-text-fill-color: transparent;
|
| 509 |
+
margin: 0;
|
| 510 |
+
text-transform: uppercase;
|
| 511 |
+
display: inline-block;
|
| 512 |
+
">EXPLORE THE CODE →</p>
|
| 513 |
+
<a href="https://github.com/Eric-Chung-0511/Learning-Record/tree/main/Data%20Science%20Projects/PawMatchAI" style="text-decoration: none;">
|
| 514 |
+
<img src="https://img.shields.io/badge/GitHub-PawMatch_AI-007ACC?logo=github&style=for-the-badge">
|
| 515 |
+
</a>
|
| 516 |
+
</div>
|
| 517 |
+
''')
|
| 518 |
+
|
| 519 |
+
return iface
|
| 520 |
+
|
| 521 |
+
if __name__ == "__main__":
|
| 522 |
+
iface = main()
|
| 523 |
+
iface.launch()
|
model_architecture.py
ADDED
|
@@ -0,0 +1,315 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
import timm
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
dog_breeds = ["Afghan_Hound", "African_Hunting_Dog", "Airedale", "American_Staffordshire_Terrier",
|
| 9 |
+
"Appenzeller", "Australian_Terrier", "Bedlington_Terrier", "Bernese_Mountain_Dog", "Bichon_Frise",
|
| 10 |
+
"Blenheim_Spaniel", "Border_Collie", "Border_Terrier", "Boston_Bull", "Bouvier_Des_Flandres",
|
| 11 |
+
"Brabancon_Griffon", "Brittany_Spaniel", "Cardigan", "Chesapeake_Bay_Retriever",
|
| 12 |
+
"Chihuahua", "Dachshund", "Dandie_Dinmont", "Doberman", "English_Foxhound", "English_Setter",
|
| 13 |
+
"English_Springer", "EntleBucher", "Eskimo_Dog", "French_Bulldog", "German_Shepherd",
|
| 14 |
+
"German_Short-Haired_Pointer", "Gordon_Setter", "Great_Dane", "Great_Pyrenees",
|
| 15 |
+
"Greater_Swiss_Mountain_Dog","Havanese", "Ibizan_Hound", "Irish_Setter", "Irish_Terrier",
|
| 16 |
+
"Irish_Water_Spaniel", "Irish_Wolfhound", "Italian_Greyhound", "Japanese_Spaniel",
|
| 17 |
+
"Kerry_Blue_Terrier", "Labrador_Retriever", "Lakeland_Terrier", "Leonberg", "Lhasa",
|
| 18 |
+
"Maltese_Dog", "Mexican_Hairless", "Newfoundland", "Norfolk_Terrier", "Norwegian_Elkhound",
|
| 19 |
+
"Norwich_Terrier", "Old_English_Sheepdog", "Pekinese", "Pembroke", "Pomeranian",
|
| 20 |
+
"Rhodesian_Ridgeback", "Rottweiler", "Saint_Bernard", "Saluki", "Samoyed",
|
| 21 |
+
"Scotch_Terrier", "Scottish_Deerhound", "Sealyham_Terrier", "Shetland_Sheepdog", "Shiba_Inu",
|
| 22 |
+
"Shih-Tzu", "Siberian_Husky", "Staffordshire_Bullterrier", "Sussex_Spaniel",
|
| 23 |
+
"Tibetan_Mastiff", "Tibetan_Terrier", "Walker_Hound", "Weimaraner",
|
| 24 |
+
"Welsh_Springer_Spaniel", "West_Highland_White_Terrier", "Yorkshire_Terrier",
|
| 25 |
+
"Affenpinscher", "Basenji", "Basset", "Beagle", "Black-and-Tan_Coonhound", "Bloodhound",
|
| 26 |
+
"Bluetick", "Borzoi", "Boxer", "Briard", "Bull_Mastiff", "Cairn", "Chow", "Clumber",
|
| 27 |
+
"Cocker_Spaniel", "Collie", "Curly-Coated_Retriever", "Dhole", "Dingo",
|
| 28 |
+
"Flat-Coated_Retriever", "Giant_Schnauzer", "Golden_Retriever", "Groenendael", "Keeshond",
|
| 29 |
+
"Kelpie", "Komondor", "Kuvasz", "Malamute", "Malinois", "Miniature_Pinscher",
|
| 30 |
+
"Miniature_Poodle", "Miniature_Schnauzer", "Otterhound", "Papillon", "Pug", "Redbone",
|
| 31 |
+
"Schipperke", "Silky_Terrier", "Soft-Coated_Wheaten_Terrier", "Standard_Poodle",
|
| 32 |
+
"Standard_Schnauzer", "Toy_Poodle", "Toy_Terrier", "Vizsla", "Whippet",
|
| 33 |
+
"Wire-Haired_Fox_Terrier"]
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class MorphologicalFeatureExtractor(nn.Module):
|
| 37 |
+
|
| 38 |
+
def __init__(self, in_features):
|
| 39 |
+
super().__init__()
|
| 40 |
+
|
| 41 |
+
# 基礎特徵維度設置
|
| 42 |
+
self.reduced_dim = in_features // 4
|
| 43 |
+
self.spatial_size = max(7, int(np.sqrt(self.reduced_dim // 64)))
|
| 44 |
+
|
| 45 |
+
# 1. 特徵空間轉換器:將一維特徵轉換為二維空間表示
|
| 46 |
+
self.dimension_transformer = nn.Sequential(
|
| 47 |
+
nn.Linear(in_features, self.spatial_size * self.spatial_size * 64),
|
| 48 |
+
nn.LayerNorm(self.spatial_size * self.spatial_size * 64),
|
| 49 |
+
nn.ReLU()
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
# 2. 形態特徵分析器:分析具體的形態特徵
|
| 53 |
+
self.morphological_analyzers = nn.ModuleDict({
|
| 54 |
+
# 體型分析器:分析整體比例和大小
|
| 55 |
+
'body_proportion': nn.Sequential(
|
| 56 |
+
# 使用大卷積核捕捉整體體型特徵
|
| 57 |
+
nn.Conv2d(64, 128, kernel_size=7, padding=3),
|
| 58 |
+
nn.BatchNorm2d(128),
|
| 59 |
+
nn.ReLU(),
|
| 60 |
+
# 使用較小的卷積核精煉特徵
|
| 61 |
+
nn.Conv2d(128, 128, kernel_size=3, padding=1),
|
| 62 |
+
nn.BatchNorm2d(128),
|
| 63 |
+
nn.ReLU()
|
| 64 |
+
),
|
| 65 |
+
|
| 66 |
+
# 頭部特徵分析器:關注耳朵、臉部等
|
| 67 |
+
'head_features': nn.Sequential(
|
| 68 |
+
# 中等大小的卷積核,適合分析頭部結構
|
| 69 |
+
nn.Conv2d(64, 128, kernel_size=5, padding=2),
|
| 70 |
+
nn.BatchNorm2d(128),
|
| 71 |
+
nn.ReLU(),
|
| 72 |
+
# 小卷積核捕捉細節
|
| 73 |
+
nn.Conv2d(128, 128, kernel_size=3, padding=1),
|
| 74 |
+
nn.BatchNorm2d(128),
|
| 75 |
+
nn.ReLU()
|
| 76 |
+
),
|
| 77 |
+
|
| 78 |
+
# 尾部特徵分析器
|
| 79 |
+
'tail_features': nn.Sequential(
|
| 80 |
+
nn.Conv2d(64, 128, kernel_size=5, padding=2),
|
| 81 |
+
nn.BatchNorm2d(128),
|
| 82 |
+
nn.ReLU(),
|
| 83 |
+
nn.Conv2d(128, 128, kernel_size=3, padding=1),
|
| 84 |
+
nn.BatchNorm2d(128),
|
| 85 |
+
nn.ReLU()
|
| 86 |
+
),
|
| 87 |
+
|
| 88 |
+
# 毛髮特徵分析器:分析毛髮長度、質地等
|
| 89 |
+
'fur_features': nn.Sequential(
|
| 90 |
+
# 使用多個小卷積核捕捉毛髮紋理
|
| 91 |
+
nn.Conv2d(64, 128, kernel_size=3, padding=1),
|
| 92 |
+
nn.BatchNorm2d(128),
|
| 93 |
+
nn.ReLU(),
|
| 94 |
+
nn.Conv2d(128, 128, kernel_size=3, padding=1),
|
| 95 |
+
nn.BatchNorm2d(128),
|
| 96 |
+
nn.ReLU()
|
| 97 |
+
),
|
| 98 |
+
|
| 99 |
+
# 顏色特徵分析器:分析顏色分佈
|
| 100 |
+
'color_pattern': nn.Sequential(
|
| 101 |
+
# 第一層:捕捉基本顏色分布
|
| 102 |
+
nn.Conv2d(64, 128, kernel_size=3, padding=1),
|
| 103 |
+
nn.BatchNorm2d(128),
|
| 104 |
+
nn.ReLU(),
|
| 105 |
+
|
| 106 |
+
# 第二層:分析顏色模式和花紋
|
| 107 |
+
nn.Conv2d(128, 128, kernel_size=3, padding=1),
|
| 108 |
+
nn.BatchNorm2d(128),
|
| 109 |
+
nn.ReLU(),
|
| 110 |
+
|
| 111 |
+
# 第三層:整合顏色信息
|
| 112 |
+
nn.Conv2d(128, 128, kernel_size=1),
|
| 113 |
+
nn.BatchNorm2d(128),
|
| 114 |
+
nn.ReLU()
|
| 115 |
+
)
|
| 116 |
+
})
|
| 117 |
+
|
| 118 |
+
# 3. 特徵注意力機制:動態關注不同特徵
|
| 119 |
+
self.feature_attention = nn.MultiheadAttention(
|
| 120 |
+
embed_dim=128,
|
| 121 |
+
num_heads=8,
|
| 122 |
+
dropout=0.1,
|
| 123 |
+
batch_first=True
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
# 4. 特徵關係分析器:分析不同特徵之間的關係
|
| 127 |
+
self.relation_analyzer = nn.Sequential(
|
| 128 |
+
nn.Linear(128 * 5, 256), # 4個特徵分析器的輸出
|
| 129 |
+
nn.LayerNorm(256),
|
| 130 |
+
nn.ReLU(),
|
| 131 |
+
nn.Linear(256, 128),
|
| 132 |
+
nn.LayerNorm(128),
|
| 133 |
+
nn.ReLU()
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
# 5. 特徵整合器:將所有特徵智能地組合在一起
|
| 137 |
+
self.feature_integrator = nn.Sequential(
|
| 138 |
+
nn.Linear(128 * 6, in_features), # 5個原始特徵 + 1個關係特徵
|
| 139 |
+
nn.LayerNorm(in_features),
|
| 140 |
+
nn.ReLU()
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
def forward(self, x):
|
| 144 |
+
batch_size = x.size(0)
|
| 145 |
+
|
| 146 |
+
# 1. 將特徵轉換為空間形式
|
| 147 |
+
spatial_features = self.dimension_transformer(x).view(
|
| 148 |
+
batch_size, 64, self.spatial_size, self.spatial_size
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
# 2. 分析各種形態特徵
|
| 152 |
+
morphological_features = {}
|
| 153 |
+
for name, analyzer in self.morphological_analyzers.items():
|
| 154 |
+
# 提取特定形態特徵
|
| 155 |
+
features = analyzer(spatial_features)
|
| 156 |
+
# 使用自適應池化統一特徵大小
|
| 157 |
+
pooled_features = F.adaptive_avg_pool2d(features, (1, 1))
|
| 158 |
+
# 重塑特徵為向量形式
|
| 159 |
+
morphological_features[name] = pooled_features.view(batch_size, -1)
|
| 160 |
+
|
| 161 |
+
# 3. 特徵注意力處理
|
| 162 |
+
# 將所有特徵堆疊成序列
|
| 163 |
+
stacked_features = torch.stack(list(morphological_features.values()), dim=1)
|
| 164 |
+
# 應用注意力機制
|
| 165 |
+
attended_features, _ = self.feature_attention(
|
| 166 |
+
stacked_features, stacked_features, stacked_features
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
# 4. 分析特徵之間的關係
|
| 170 |
+
# 將所有特徵連接起來
|
| 171 |
+
combined_features = torch.cat(list(morphological_features.values()), dim=1)
|
| 172 |
+
# 提取特徵間的關係
|
| 173 |
+
relation_features = self.relation_analyzer(combined_features)
|
| 174 |
+
|
| 175 |
+
# 5. 特徵整合
|
| 176 |
+
# 將原始特徵和關係特徵結合
|
| 177 |
+
final_features = torch.cat([
|
| 178 |
+
*morphological_features.values(),
|
| 179 |
+
relation_features
|
| 180 |
+
], dim=1)
|
| 181 |
+
|
| 182 |
+
# 6. 最終整合
|
| 183 |
+
integrated_features = self.feature_integrator(final_features)
|
| 184 |
+
|
| 185 |
+
# 添加殘差連接
|
| 186 |
+
return integrated_features + x
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
class MultiHeadAttention(nn.Module):
|
| 190 |
+
|
| 191 |
+
def __init__(self, in_dim, num_heads=8):
|
| 192 |
+
"""
|
| 193 |
+
Initializes the MultiHeadAttention module.
|
| 194 |
+
Args:
|
| 195 |
+
in_dim (int): Dimension of the input features.
|
| 196 |
+
num_heads (int): Number of attention heads. Defaults to 8.
|
| 197 |
+
"""
|
| 198 |
+
super().__init__()
|
| 199 |
+
self.num_heads = num_heads
|
| 200 |
+
self.head_dim = max(1, in_dim // num_heads)
|
| 201 |
+
self.scaled_dim = self.head_dim * num_heads
|
| 202 |
+
self.fc_in = nn.Linear(in_dim, self.scaled_dim)
|
| 203 |
+
self.query = nn.Linear(self.scaled_dim, self.scaled_dim) # Query projection
|
| 204 |
+
self.key = nn.Linear(self.scaled_dim, self.scaled_dim) # Key projection
|
| 205 |
+
self.value = nn.Linear(self.scaled_dim, self.scaled_dim) # Value projection
|
| 206 |
+
self.fc_out = nn.Linear(self.scaled_dim, in_dim) # Linear layer to project output back to in_dim
|
| 207 |
+
|
| 208 |
+
def forward(self, x):
|
| 209 |
+
"""
|
| 210 |
+
Forward pass for multi-head attention mechanism.
|
| 211 |
+
Args:
|
| 212 |
+
x (Tensor): Input tensor of shape (batch_size, input_dim).
|
| 213 |
+
x 是 (N,D), N:批次大小, D:輸入特徵維度
|
| 214 |
+
Returns:
|
| 215 |
+
Tensor: Output tensor after applying attention mechanism.
|
| 216 |
+
"""
|
| 217 |
+
N = x.shape[0] # Batch size
|
| 218 |
+
x = self.fc_in(x) # Project input to scaled_dim
|
| 219 |
+
q = self.query(x).view(N, self.num_heads, self.head_dim) # Compute queries
|
| 220 |
+
k = self.key(x).view(N, self.num_heads, self.head_dim) # Compute keys
|
| 221 |
+
v = self.value(x).view(N, self.num_heads, self.head_dim) # Compute values
|
| 222 |
+
|
| 223 |
+
# Calculate attention scores
|
| 224 |
+
energy = torch.einsum("nqd,nkd->nqk", [q, k])
|
| 225 |
+
attention = F.softmax(energy / (self.head_dim ** 0.5), dim=2) # Apply softmax with scaling
|
| 226 |
+
|
| 227 |
+
# Compute weighted sum of values based on attention scores
|
| 228 |
+
out = torch.einsum("nqk,nvd->nqd", [attention, v])
|
| 229 |
+
out = out.reshape(N, self.scaled_dim) # Concatenate all heads
|
| 230 |
+
out = self.fc_out(out) # Project back to original input dimension
|
| 231 |
+
return out
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
class BaseModel(nn.Module):
|
| 235 |
+
|
| 236 |
+
def __init__(self, num_classes, device='cuda' if torch.cuda.is_available() else 'cpu'):
|
| 237 |
+
super().__init__()
|
| 238 |
+
self.device = device
|
| 239 |
+
|
| 240 |
+
# 1. Initialize backbone
|
| 241 |
+
self.backbone = timm.create_model(
|
| 242 |
+
'convnextv2_base',
|
| 243 |
+
pretrained=True,
|
| 244 |
+
num_classes=0
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
# 2. 使用測試數據來確定實際的特徵維度
|
| 248 |
+
with torch.no_grad():
|
| 249 |
+
dummy_input = torch.randn(1, 3, 224, 224)
|
| 250 |
+
features = self.backbone(dummy_input)
|
| 251 |
+
|
| 252 |
+
if len(features.shape) > 2:
|
| 253 |
+
features = features.mean([-2, -1])
|
| 254 |
+
|
| 255 |
+
self.feature_dim = features.shape[1]
|
| 256 |
+
|
| 257 |
+
print(f"Feature Dimension from V2 backbone: {self.feature_dim}")
|
| 258 |
+
|
| 259 |
+
# 3. Setup multi-head attention layer
|
| 260 |
+
self.num_heads = max(1, min(8, self.feature_dim // 64))
|
| 261 |
+
self.attention = MultiHeadAttention(self.feature_dim, num_heads=self.num_heads)
|
| 262 |
+
|
| 263 |
+
# 4. Setup classifier
|
| 264 |
+
self.classifier = nn.Sequential(
|
| 265 |
+
nn.LayerNorm(self.feature_dim),
|
| 266 |
+
nn.Dropout(0.3),
|
| 267 |
+
nn.Linear(self.feature_dim, num_classes)
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
self.morphological_extractor = MorphologicalFeatureExtractor(
|
| 271 |
+
in_features=self.feature_dim
|
| 272 |
+
)
|
| 273 |
+
|
| 274 |
+
self.feature_fusion = nn.Sequential(
|
| 275 |
+
nn.Linear(self.feature_dim * 3, self.feature_dim),
|
| 276 |
+
nn.LayerNorm(self.feature_dim),
|
| 277 |
+
nn.ReLU(),
|
| 278 |
+
nn.Linear(self.feature_dim, self.feature_dim),
|
| 279 |
+
nn.LayerNorm(self.feature_dim),
|
| 280 |
+
nn.ReLU()
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
def forward(self, x):
|
| 284 |
+
"""
|
| 285 |
+
Forward propagation process, combining V2's FCCA and multi-head attention mechanism
|
| 286 |
+
Args:
|
| 287 |
+
x (Tensor): Input image tensor of shape [batch_size, channels, height, width]
|
| 288 |
+
Returns:
|
| 289 |
+
Tuple[Tensor, Tensor]: Classification logits and attention features
|
| 290 |
+
"""
|
| 291 |
+
x = x.to(self.device)
|
| 292 |
+
|
| 293 |
+
# 1. Extract base features
|
| 294 |
+
features = self.backbone(x)
|
| 295 |
+
if len(features.shape) > 2:
|
| 296 |
+
features = features.mean([-2, -1])
|
| 297 |
+
|
| 298 |
+
# 2. Extract morphological features (including all detail features)
|
| 299 |
+
morphological_features = self.morphological_extractor(features)
|
| 300 |
+
|
| 301 |
+
# 3. Feature fusion (note dimension alignment with new fusion layer)
|
| 302 |
+
combined_features = torch.cat([
|
| 303 |
+
features, # Original features
|
| 304 |
+
morphological_features, # Morphological features
|
| 305 |
+
features * morphological_features # Feature interaction information
|
| 306 |
+
], dim=1)
|
| 307 |
+
fused_features = self.feature_fusion(combined_features)
|
| 308 |
+
|
| 309 |
+
# 4. Apply attention mechanism
|
| 310 |
+
attended_features = self.attention(fused_features)
|
| 311 |
+
|
| 312 |
+
# 5. Final classifier
|
| 313 |
+
logits = self.classifier(attended_features)
|
| 314 |
+
|
| 315 |
+
return logits, attended_features
|