DawnC commited on
Commit
37f5b46
·
verified ·
1 Parent(s): ab0922f

Delete app.py

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