File size: 27,547 Bytes
8b87358
 
 
 
 
 
745b3ae
8b87358
 
1044c24
678ff71
81d7def
c9e5868
7bde2e9
b663fd0
c9e5868
3c27777
789716b
c9e5868
8b87358
21b74d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b87358
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
979a7b6
8b87358
 
bbd78ec
8b87358
 
 
 
bbd78ec
8b87358
 
 
bbd78ec
8b87358
 
 
 
 
 
 
 
81d7def
8196c90
 
 
 
 
866dbcd
4f8052f
cb2b5ac
1fabe7c
 
cb2b5ac
 
0df9d3f
cb2b5ac
 
8df4d67
 
 
 
 
 
 
0df9d3f
1fabe7c
5f20703
d19b943
 
 
 
8471d74
789716b
 
 
d19b943
 
 
 
789716b
d19b943
789716b
 
d1effc1
 
 
 
 
d19b943
789716b
d19b943
 
 
a0c885f
789716b
 
 
 
 
 
 
 
 
30ec533
789716b
 
 
 
 
 
 
 
 
 
 
 
 
 
8c21c35
8df4d67
 
 
697b62b
8c21c35
 
2c0def4
 
8c21c35
8df4d67
8c21c35
 
8df4d67
 
697b62b
8df4d67
8c21c35
 
 
2c0def4
 
8c21c35
8df4d67
 
 
8c21c35
8df4d67
 
 
 
 
 
8c21c35
8df4d67
2c0def4
 
8c21c35
8df4d67
 
e296e0a
d7ed8db
0c0eff1
 
8df4d67
6e5026c
0c0eff1
 
 
6e5026c
0c0eff1
ccffdae
 
b7d5372
 
 
 
 
 
 
 
 
 
 
 
0c0eff1
 
f8d361b
d7ed8db
7ea9e6f
d7ed8db
 
d9da78c
0c0eff1
6451d26
2156e3a
f8d361b
7ea9e6f
d26da0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ed0708
d26da0f
 
7ea9e6f
 
f8d361b
d7ed8db
 
7ea9e6f
2ed0708
 
 
 
d7ed8db
 
8df4d67
63b2431
2c3db84
d7ed8db
f8d361b
2ed0708
 
 
7ea9e6f
d7ed8db
2ed0708
 
 
 
 
 
 
 
f8d361b
2ed0708
 
 
 
f8d361b
2ed0708
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f8d361b
2ed0708
 
 
 
f8d361b
2ed0708
 
 
 
 
 
 
 
 
 
f8d361b
 
2ed0708
 
 
 
 
 
 
 
 
 
 
 
 
f8d361b
d7ed8db
 
a37898e
d26da0f
 
 
 
 
 
2ed0708
d26da0f
 
 
2ed0708
d26da0f
 
 
 
 
2ed0708
 
 
 
 
 
 
 
 
d26da0f
 
 
 
2ed0708
d26da0f
 
86a506d
10b5f22
a37898e
a10b184
 
 
 
 
 
 
 
 
 
10b5f22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f288a0e
10b5f22
 
 
 
 
 
 
 
 
f288a0e
10b5f22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7d5372
10b5f22
 
 
 
 
 
 
b7d5372
10b5f22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37d85f8
1f2f07c
f8d361b
2ed0708
 
 
1f2f07c
1ce85e8
1f2f07c
1ce85e8
b663fd0
5773c54
1ce85e8
5a1d841
 
 
 
 
 
 
 
50c8543
1f2f07c
 
 
 
b663fd0
1ce85e8
cb2b5ac
1f2f07c
 
 
 
 
 
 
65b44b5
 
 
1f2f07c
 
 
 
 
8196c90
1f2f07c
 
 
 
d8c1250
a312d58
8df4d67
2ed0708
aff8ba5
73cee42
 
4f1e4cb
 
083c145
8df4d67
1f2f07c
196f0d8
215a635
1ce85e8
1f2f07c
8df4d67
196f0d8
481f48f
f979cb1
 
 
 
8df4d67
3fa059c
4486636
53df7ea
8c21c35
6451d26
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
import os
import numpy as np
import torch
import torch.nn as nn
import gradio as gr
from torchvision.models import efficientnet_v2_m, EfficientNet_V2_M_Weights
from torchvision.ops import nms, box_iou
import torch.nn.functional as F
from torchvision import transforms
from PIL import Image, ImageDraw, ImageFont, ImageFilter
from data_manager import get_dog_description
from urllib.parse import quote
from ultralytics import YOLO
import asyncio
import traceback


model_yolo = YOLO('yolov8l.pt')  


dog_breeds = ["Afghan_Hound", "African_Hunting_Dog", "Airedale", "American_Staffordshire_Terrier", 
              "Appenzeller", "Australian_Terrier", "Bedlington_Terrier", "Bernese_Mountain_Dog", 
              "Blenheim_Spaniel", "Border_Collie", "Border_Terrier", "Boston_Bull", "Bouvier_Des_Flandres", 
              "Brabancon_Griffon", "Brittany_Spaniel", "Cardigan", "Chesapeake_Bay_Retriever", 
              "Chihuahua", "Dandie_Dinmont", "Doberman", "English_Foxhound", "English_Setter", 
              "English_Springer", "EntleBucher", "Eskimo_Dog", "French_Bulldog", "German_Shepherd", 
              "German_Short-Haired_Pointer", "Gordon_Setter", "Great_Dane", "Great_Pyrenees", 
              "Greater_Swiss_Mountain_Dog", "Ibizan_Hound", "Irish_Setter", "Irish_Terrier", 
              "Irish_Water_Spaniel", "Irish_Wolfhound", "Italian_Greyhound", "Japanese_Spaniel", 
              "Kerry_Blue_Terrier", "Labrador_Retriever", "Lakeland_Terrier", "Leonberg", "Lhasa", 
              "Maltese_Dog", "Mexican_Hairless", "Newfoundland", "Norfolk_Terrier", "Norwegian_Elkhound", 
              "Norwich_Terrier", "Old_English_Sheepdog", "Pekinese", "Pembroke", "Pomeranian", 
              "Rhodesian_Ridgeback", "Rottweiler", "Saint_Bernard", "Saluki", "Samoyed", 
              "Scotch_Terrier", "Scottish_Deerhound", "Sealyham_Terrier", "Shetland_Sheepdog", 
              "Shih-Tzu", "Siberian_Husky", "Staffordshire_Bullterrier", "Sussex_Spaniel", 
              "Tibetan_Mastiff", "Tibetan_Terrier", "Walker_Hound", "Weimaraner", 
              "Welsh_Springer_Spaniel", "West_Highland_White_Terrier", "Yorkshire_Terrier", 
              "Affenpinscher", "Basenji", "Basset", "Beagle", "Black-and-Tan_Coonhound", "Bloodhound", 
              "Bluetick", "Borzoi", "Boxer", "Briard", "Bull_Mastiff", "Cairn", "Chow", "Clumber", 
              "Cocker_Spaniel", "Collie", "Curly-Coated_Retriever", "Dhole", "Dingo", 
              "Flat-Coated_Retriever", "Giant_Schnauzer", "Golden_Retriever", "Groenendael", "Keeshond", 
              "Kelpie", "Komondor", "Kuvasz", "Malamute", "Malinois", "Miniature_Pinscher", 
              "Miniature_Poodle", "Miniature_Schnauzer", "Otterhound", "Papillon", "Pug", "Redbone", 
              "Schipperke", "Silky_Terrier", "Soft-Coated_Wheaten_Terrier", "Standard_Poodle", 
              "Standard_Schnauzer", "Toy_Poodle", "Toy_Terrier", "Vizsla", "Whippet", 
              "Wire-Haired_Fox_Terrier"]

class MultiHeadAttention(nn.Module):

    def __init__(self, in_dim, num_heads=8):
        super().__init__()
        self.num_heads = num_heads
        self.head_dim = max(1, in_dim // num_heads)
        self.scaled_dim = self.head_dim * num_heads
        self.fc_in = nn.Linear(in_dim, self.scaled_dim)
        self.query = nn.Linear(self.scaled_dim, self.scaled_dim)
        self.key = nn.Linear(self.scaled_dim, self.scaled_dim)
        self.value = nn.Linear(self.scaled_dim, self.scaled_dim)
        self.fc_out = nn.Linear(self.scaled_dim, in_dim)

    def forward(self, x):
        N = x.shape[0]
        x = self.fc_in(x)
        q = self.query(x).view(N, self.num_heads, self.head_dim)
        k = self.key(x).view(N, self.num_heads, self.head_dim)
        v = self.value(x).view(N, self.num_heads, self.head_dim)

        energy = torch.einsum("nqd,nkd->nqk", [q, k])
        attention = F.softmax(energy / (self.head_dim ** 0.5), dim=2)

        out = torch.einsum("nqk,nvd->nqd", [attention, v])
        out = out.reshape(N, self.scaled_dim)
        out = self.fc_out(out)
        return out

class BaseModel(nn.Module):
    def __init__(self, num_classes, device='cuda' if torch.cuda.is_available() else 'cpu'):
        super().__init__()
        self.device = device
        self.backbone = efficientnet_v2_m(weights=EfficientNet_V2_M_Weights.IMAGENET1K_V1)
        self.feature_dim = self.backbone.classifier[1].in_features
        self.backbone.classifier = nn.Identity()

        self.num_heads = max(1, min(8, self.feature_dim // 64))
        self.attention = MultiHeadAttention(self.feature_dim, num_heads=self.num_heads)

        self.classifier = nn.Sequential(
            nn.LayerNorm(self.feature_dim),
            nn.Dropout(0.3),
            nn.Linear(self.feature_dim, num_classes)
        )

        self.to(device)

    def forward(self, x):
        x = x.to(self.device)
        features = self.backbone(x)
        attended_features = self.attention(features)
        logits = self.classifier(attended_features)
        return logits, attended_features


num_classes = 120
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = BaseModel(num_classes=num_classes, device=device)

checkpoint = torch.load('best_model_81_dog.pth', map_location=torch.device('cpu'))
model.load_state_dict(checkpoint['model_state_dict'])

# evaluation mode
model.eval()

# Image preprocessing function
def preprocess_image(image):
    # If the image is numpy.ndarray turn into PIL.Image
    if isinstance(image, np.ndarray):
        image = Image.fromarray(image)

    # Use torchvision.transforms to process images
    transform = transforms.Compose([
        transforms.Resize((224, 224)),
        transforms.ToTensor(),
        transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
    ])

    return transform(image).unsqueeze(0)


def get_akc_breeds_link(breed):
    base_url = "https://www.akc.org/dog-breeds/"
    breed_url = breed.lower().replace('_', '-')
    return f"{base_url}{breed_url}/"


async def predict_single_dog(image):
    image_tensor = preprocess_image(image)
    with torch.no_grad():
        output = model(image_tensor)
        logits = output[0] if isinstance(output, tuple) else output
        probabilities = F.softmax(logits, dim=1)
        topk_probs, topk_indices = torch.topk(probabilities, k=3)
        top1_prob = topk_probs[0][0].item()
        topk_breeds = [dog_breeds[idx.item()] for idx in topk_indices[0]]
        
        # Calculate relative probabilities for display
        raw_probs = [prob.item() for prob in topk_probs[0]]
        sum_probs = sum(raw_probs)
        relative_probs = [f"{(prob/sum_probs * 100):.2f}%" for prob in raw_probs]
        
    return top1_prob, topk_breeds, relative_probs
    

async def detect_multiple_dogs(image, conf_threshold=0.3, iou_threshold=0.45):
    results = model_yolo(image, conf=conf_threshold, iou=iou_threshold)[0]
    dogs = []
    boxes = []
    for box in results.boxes:
        if box.cls == 16:  # COCO dataset class for dog is 16 
            xyxy = box.xyxy[0].tolist()
            confidence = box.conf.item()
            boxes.append((xyxy, confidence))
    
    if not boxes:
        dogs.append((image, 1.0, [0, 0, image.width, image.height]))
    else:
        nms_boxes = non_max_suppression(boxes, iou_threshold)
        
        for box, confidence in nms_boxes:
            x1, y1, x2, y2 = box
            w, h = x2 - x1, y2 - y1
            x1 = max(0, x1 - w * 0.05)
            y1 = max(0, y1 - h * 0.05)
            x2 = min(image.width, x2 + w * 0.05)
            y2 = min(image.height, y2 + h * 0.05)
            cropped_image = image.crop((x1, y1, x2, y2))
            dogs.append((cropped_image, confidence, [x1, y1, x2, y2]))
    
    return dogs


def non_max_suppression(boxes, iou_threshold):
    keep = []
    boxes = sorted(boxes, key=lambda x: x[1], reverse=True)
    while boxes:
        current = boxes.pop(0)
        keep.append(current)
        boxes = [box for box in boxes if calculate_iou(current[0], box[0]) < iou_threshold]
    return keep

    
def calculate_iou(box1, box2):
    x1 = max(box1[0], box2[0])
    y1 = max(box1[1], box2[1])
    x2 = min(box1[2], box2[2])
    y2 = min(box1[3], box2[3])
    
    intersection = max(0, x2 - x1) * max(0, y2 - y1)
    area1 = (box1[2] - box1[0]) * (box1[3] - box1[1])
    area2 = (box2[2] - box2[0]) * (box2[3] - box2[1])
    
    iou = intersection / float(area1 + area2 - intersection)
    return iou


async def process_single_dog(image):
    top1_prob, topk_breeds, relative_probs = await predict_single_dog(image)
    
    # Case 1: Low confidence - unclear image or breed not in dataset
    if top1_prob < 0.15:
        initial_state = {
            "explanation": "The image is unclear or the breed is not in the dataset. Please upload a clearer image of a dog.",
            "image": None,
            "is_multi_dog": False
        }
        return initial_state["explanation"], None, initial_state

    breed = topk_breeds[0]
    
    # Case 2: High confidence - single breed result
    if top1_prob >= 0.45:
        description = get_dog_description(breed)
        formatted_description = format_description(description, breed)
        initial_state = {
            "explanation": formatted_description,
            "image": image,
            "is_multi_dog": False
        }
        return formatted_description, image, initial_state
        
    # Case 3: Medium confidence - show top 3 breeds with relative probabilities
    else:
        breeds_info = ""
        for i, (breed, prob) in enumerate(zip(topk_breeds, relative_probs)):
            description = get_dog_description(breed)
            formatted_description = format_description(description, breed)
            breeds_info += f"\n\nBreed {i+1}: **{breed}** (Confidence: {prob})\n{formatted_description}"

        initial_state = {
            "explanation": breeds_info,
            "image": image,
            "is_multi_dog": False
        }
        return breeds_info, image, initial_state
        


async def predict(image):
    if image is None:
        return "Please upload an image to start.", None, None

    try:
        if isinstance(image, np.ndarray):
            image = Image.fromarray(image)

        dogs = await detect_multiple_dogs(image)
        # ๆ›ดๆ–ฐ้ก่‰ฒ็ต„ๅˆ
        single_dog_color = '#34C759'  # ๆธ…็ˆฝ็š„็ถ ่‰ฒไฝœ็‚บๅ–ฎ็‹—้ก่‰ฒ
        color_list = [
        '#FF5733',  # ็Š็‘š็ด…
        '#33FF57',  # ่–„่ท็ถ 
        '#3357FF',  # ๅฏถ่—่‰ฒ
        '#FF33F5',  # ็ฒ‰็ดซ่‰ฒ
        '#FFB733',  # ๆฉ™้ปƒ่‰ฒ
        '#33FFF5',  # ้’่—่‰ฒ
        '#A233FF',  # ็ดซ่‰ฒ
        '#FF3333',  # ็ด…่‰ฒ
        '#33FFB7',  # ้’็ถ ่‰ฒ
        '#FFE033'   # ้‡‘้ปƒ่‰ฒ 
        ]
        annotated_image = image.copy()
        draw = ImageDraw.Draw(annotated_image)

        try:
            font = ImageFont.truetype("arial.ttf", 24)
        except:
            font = ImageFont.load_default()

        dogs_info = ""

        for i, (cropped_image, detection_confidence, box) in enumerate(dogs):
            color = single_dog_color if len(dogs) == 1 else color_list[i % len(color_list)]
            
            # ๅ„ชๅŒ–ๅœ–็‰‡ไธŠ็š„ๆจ™่จ˜
            draw.rectangle(box, outline=color, width=4)
            label = f"Dog {i+1}"
            label_bbox = draw.textbbox((0, 0), label, font=font)
            label_width = label_bbox[2] - label_bbox[0]
            label_height = label_bbox[3] - label_bbox[1]
            
            label_x = box[0] + 5
            label_y = box[1] + 5
            draw.rectangle(
                [label_x - 2, label_y - 2, label_x + label_width + 4, label_y + label_height + 4],
                fill='white',
                outline=color,
                width=2
            )
            draw.text((label_x, label_y), label, fill=color, font=font)
        
            top1_prob, topk_breeds, relative_probs = await predict_single_dog(cropped_image)
            combined_confidence = detection_confidence * top1_prob
            
            # ้–‹ๅง‹่ณ‡่จŠๅก็‰‡
            dogs_info += f'<div class="dog-info-card" style="border-left: 6px solid {color};">'
            
            if combined_confidence < 0.15:
                dogs_info += f'''
                    <div class="dog-info-header" style="background-color: {color}10;">
                        <span class="dog-label" style="color: {color};">Dog {i+1}</span>
                    </div>
                    <div class="breed-info">
                        <p class="warning-message">
                            <span class="icon">โš ๏ธ</span>
                            The image is unclear or the breed is not in the dataset. Please upload a clearer image.
                        </p>
                    </div>
                '''
            elif top1_prob >= 0.45:
                breed = topk_breeds[0]
                description = get_dog_description(breed)
                dogs_info += f'''
                    <div class="dog-info-header" style="background-color: {color}10;">
                        <span class="dog-label" style="color: {color};">
                            <span class="icon">๐Ÿ†</span> {breed}
                        </span>
                    </div>
                    <div class="breed-info">
                        <h2 class="section-title">
                            <span class="icon">๐Ÿ“‹</span> BASIC INFORMATION
                        </h2>
                        <div class="info-section">
                            <div class="info-item">
                                <span class="icon">๐Ÿ“</span>
                                <span class="label">Size:</span>
                                <span class="value">{description['Size']}</span>
                            </div>
                            <div class="info-item">
                                <span class="icon">โณ</span>
                                <span class="label">Lifespan:</span>
                                <span class="value">{description['Lifespan']}</span>
                            </div>
                        </div>

                        <h2 class="section-title">
                            <span class="icon">๐Ÿ•</span> TEMPERAMENT & PERSONALITY
                        </h2>
                        <div class="temperament-section">
                            <span class="value">{description['Temperament']}</span>
                        </div>

                        <h2 class="section-title">
                            <span class="icon">๐Ÿ’ช</span> CARE REQUIREMENTS
                        </h2>
                        <div class="care-section">
                            <div class="info-item">
                                <span class="icon">๐Ÿƒ</span>
                                <span class="label">Exercise:</span>
                                <span class="value">{description['Exercise Needs']}</span>
                            </div>
                            <div class="info-item">
                                <span class="icon">โœ‚๏ธ</span>
                                <span class="label">Grooming:</span>
                                <span class="value">{description['Grooming Needs']}</span>
                            </div>
                            <div class="info-item">
                                <span class="icon">โญ</span>
                                <span class="label">Care Level:</span>
                                <span class="value">{description['Care Level']}</span>
                            </div>
                        </div>

                        <h2 class="section-title">
                            <span class="icon">๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ</span> FAMILY COMPATIBILITY
                        </h2>
                        <div class="family-section">
                            <div class="info-item">
                                <span class="icon">๐Ÿ‘ถ</span>
                                <span class="label">Good with Children:</span>
                                <span class="value">{description['Good with Children']}</span>
                            </div>
                        </div>

                        <h2 class="section-title">
                            <span class="icon">๐Ÿ“</span> DESCRIPTION
                        </h2>
                        <div class="description-section">
                            <p>{description.get('Description', '')}</p>
                        </div>

                        <div class="action-section">
                            <a href="{get_akc_breeds_link(breed)}" target="_blank" class="akc-button">
                                <span class="icon">๐ŸŒ</span>
                                Learn more about {breed} on AKC website
                            </a>
                        </div>
                    </div>
                '''
            else:
                dogs_info += f'''
                    <div class="dog-info-header" style="background-color: {color}10;">
                        <span class="dog-label" style="color: {color};">Dog {i+1}</span>
                    </div>
                    <div class="breed-info">
                        <div class="model-uncertainty-note">
                            <span class="icon">โ„น๏ธ</span>
                            Note: The model is showing some uncertainty in its predictions. 
                            Here are the most likely breeds based on the available visual features.
                        </div>
                        <div class="breeds-list">
                '''
                
                for j, (breed, prob) in enumerate(zip(topk_breeds, relative_probs)):
                    description = get_dog_description(breed)
                    dogs_info += f'''
                        <div class="breed-option">
                            <div class="breed-header">
                                <span class="option-number">Option {j+1}</span>
                                <span class="breed-name">{breed}</span>
                                <span class="confidence-badge" style="background-color: {color}20; color: {color};">
                                    Confidence: {prob}
                                </span>
                            </div>
                            <div class="breed-content">
                                {format_description_html(description, breed)}
                            </div>
                        </div>
                    '''
                dogs_info += '</div></div>'
            
            dogs_info += '</div>'


        html_output = f"""
        <style>
        .dog-info-card {{ 
            border: 1px solid #e1e4e8; 
            margin: 32px 0;
            padding: 0; 
            border-radius: 12px; 
            box-shadow: 0 2px 12px rgba(0,0,0,0.08);
            overflow: hidden;
            transition: all 0.3s ease;
            background: white;
        }}
        
        .dog-info-card:hover {{
            box-shadow: 0 4px 16px rgba(0,0,0,0.12);
        }}
        
        .dog-info-header {{ 
            padding: 20px 24px;
            margin: 0;
            font-size: 22px;
            font-weight: bold;
            border-bottom: 1px solid #e1e4e8;
        }}
        
        .breed-info {{
            padding: 24px;
            line-height: 1.6;
        }}
        
        .section-title {{
            font-size: 1.2em;
            font-weight: 700;
            color: #2c3e50;
            margin: 28px 0 16px 0;
            padding-bottom: 8px;
            border-bottom: 2px solid #e1e4e8;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            display: flex;
            align-items: center;
            gap: 8px;
        }}
        
        .icon {{
            font-size: 1.2em;
            display: inline-flex;
            align-items: center;
            justify-content: center;
        }}
        
        .info-section, .care-section, .family-section {{
            display: flex;
            flex-wrap: wrap;
            gap: 16px;
            margin-bottom: 20px;
        }}
        
        .info-item {{
            background: #f8f9fa;
            padding: 12px 16px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            gap: 8px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.05);
        }}
        
        .label {{
            color: #666;
            font-weight: 600;
        }}
        
        .value {{
            color: #2c3e50;
        }}
        
        .temperament-section {{
            background: #f8f9fa;
            padding: 16px;
            border-radius: 8px;
            margin-bottom: 20px;
            color: #444;
        }}
        
        .description-section {{
            background: #f8f9fa;
            padding: 16px;
            border-radius: 8px;
            margin: 20px 0;
            line-height: 1.8;
            color: #444;
        }}
        
        .action-section {{
            margin-top: 24px;
            text-align: center;
        }}
        
        .akc-button {{
            display: inline-flex;
            align-items: center;
            padding: 12px 24px;
            background-color: #00509E; 
            color: white;
            border-radius: 8px;
            text-decoration: none;
            gap: 8px;
            transition: all 0.3s ease;
            font-weight: 500;
        }}
        
        .akc-button:hover {{
            background-color: #003F7F;
            transform: translateY(-1px);
            color: white;
        }}
        
        .warning-message {{
            display: flex;
            align-items: center;
            gap: 8px;
            color: #ff3b30;
            font-weight: 500;
            margin: 0;
            padding: 16px;
            background: #fff5f5;
            border-radius: 8px;
        }}
        
        .model-uncertainty-note {{
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 16px;
            background-color: #f8f9fa;
            border-left: 4px solid #6c757d;
            margin-bottom: 20px;
            color: #495057;
            border-radius: 4px;
        }}
        
        .breeds-list {{
            display: flex;
            flex-direction: column;
            gap: 20px;
        }}
        
        .breed-option {{
            background: white;
            border: 1px solid #e1e4e8;
            border-radius: 8px;
            overflow: hidden;
        }}
        
        .breed-header {{
            display: flex;
            align-items: center;
            padding: 16px;
            background: #f8f9fa;
            gap: 12px;
            border-bottom: 1px solid #e1e4e8;
        }}
        
        .option-number {{
            font-weight: 600;
            color: #666;
            padding: 4px 8px;
            background: #e1e4e8;
            border-radius: 4px;
        }}
        
        .breed-name {{
            font-size: 1.1em;
            font-weight: bold;
            color: #2c3e50;
            flex-grow: 1;
        }}
        
        .confidence-badge {{
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.9em;
            font-weight: 500;
        }}
        
        .breed-content {{
            padding: 20px;
        }}
        
        ul {{
            padding-left: 0;
            margin: 0;
            list-style-type: none;
        }}
        
        li {{
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 8px;
        }}

        .akc-link {{
            color: #357ABD;
            text-decoration: none;
            font-weight: 500;
            transition: all 0.3s ease;
        }}
        
        .akc-link:hover {{
            text-decoration: underline;
            color: #2C6AA0;
        }}
        </style>
        {dogs_info}
        """

        initial_state = {
            "dogs_info": dogs_info,
            "image": annotated_image,
            "is_multi_dog": len(dogs) > 1,
            "html_output": html_output
        }
        
        return html_output, annotated_image, initial_state

    except Exception as e:
        error_msg = f"An error occurred: {str(e)}\n\nTraceback:\n{traceback.format_exc()}"
        print(error_msg)
        return error_msg, None, None
        






def show_details_html(choice, previous_output, initial_state):
    if not choice:
        return previous_output, gr.update(visible=True), initial_state

    try:
        breed = choice.split("More about ")[-1]
        description = get_dog_description(breed)
        formatted_description = format_description_html(description, breed)
        
        html_output = f"""
        <div class="dog-info">
            <h2>{breed}</h2>
            {formatted_description}
        </div>
        """
        
        initial_state["current_description"] = html_output
        initial_state["original_buttons"] = initial_state.get("buttons", [])
        
        return html_output, gr.update(visible=True), initial_state
    except Exception as e:
        error_msg = f"An error occurred while showing details: {e}"
        print(error_msg)
        return f"<p style='color: red;'>{error_msg}</p>", gr.update(visible=True), initial_state


def format_description_html(description, breed):
    html = "<ul style='list-style-type: none; padding-left: 0;'>"
    if isinstance(description, dict):
        for key, value in description.items():
            # ่ทณ้Ž Breed ่ณ‡่จŠ
            if key != "Breed":
                html += f"<li style='margin-bottom: 10px;'><strong>{key}:</strong> {value}</li>"
    elif isinstance(description, str):
        html += f"<li>{description}</li>"
    else:
        html += f"<li>No description available for {breed}</li>"
    html += "</ul>"
    akc_link = get_akc_breeds_link(breed)
    html += f'<p><a href="{akc_link}" target="_blank">Learn more about {breed} on the AKC website</a></p>'
    return html


with gr.Blocks() as iface:
    gr.HTML("<h1 style='text-align: center;'>๐Ÿถ Dog Breed Classifier ๐Ÿ”</h1>")
    gr.HTML("<p style='text-align: center;'>Upload a picture of a dog, and the model will predict its breed and provide detailed information!</p>")
    gr.HTML("<p style='text-align: center; color: #666; font-size: 0.9em;'>Note: The model's predictions may not always be 100% accurate, and it is recommended to use the results as a reference.</p>")
    
    
    with gr.Row():
        input_image = gr.Image(label="Upload a dog image", type="pil")
        output_image = gr.Image(label="Annotated Image")
    
    output = gr.HTML(label="Prediction Results")
    initial_state = gr.State()
    
    input_image.change(
        predict,
        inputs=input_image,
        outputs=[output, output_image, initial_state]
    )
    
    gr.Examples(
        examples=['Border_Collie.jpg', 'Golden_Retriever.jpeg', 'Saint_Bernard.jpeg', 'French_Bulldog.jpeg', 'Samoyed.jpg'],
        inputs=input_image
    )
    
    gr.HTML('For more details on this project and other work, feel free to visit my GitHub <a href="https://github.com/Eric-Chung-0511/Learning-Record/tree/main/Data%20Science%20Projects/Dog_Breed_Classifier">Dog Breed Classifier</a>')


if __name__ == "__main__":
    iface.launch()