DawnC commited on
Commit
17ce59d
·
verified ·
1 Parent(s): d6a55ae

Delete app.py

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