DawnC commited on
Commit
58dad53
·
verified ·
1 Parent(s): 2aef774

Delete app.py

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