File size: 63,398 Bytes
6be27f7
 
 
 
 
 
 
 
 
 
2993c13
6be27f7
 
 
 
 
 
1c3b621
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6be27f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c3b621
6be27f7
 
 
 
1c3b621
6be27f7
1c3b621
6be27f7
 
 
 
 
 
1c3b621
6be27f7
 
 
1c3b621
6be27f7
 
 
 
1c3b621
6be27f7
 
 
 
 
 
 
 
 
1c3b621
6be27f7
 
 
 
 
 
 
 
 
 
 
 
1c3b621
6be27f7
 
 
 
 
1c3b621
6be27f7
 
 
1c3b621
6be27f7
 
 
 
 
 
1c3b621
6be27f7
61756ef
6be27f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c3b621
6be27f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c3b621
6be27f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c3b621
 
 
 
 
6d8a6e9
1c3b621
 
 
 
 
 
 
6d8a6e9
1c3b621
 
 
 
6d8a6e9
1c3b621
 
 
 
 
 
 
 
 
6d8a6e9
1c3b621
 
 
6be27f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c3b621
6be27f7
 
 
 
 
 
 
 
 
 
 
 
 
1c3b621
6be27f7
 
 
 
 
 
1c3b621
6be27f7
 
 
 
 
 
 
 
 
1c3b621
6be27f7
 
1c3b621
6be27f7
 
1c3b621
61756ef
6be27f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c3b621
6be27f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c3b621
6be27f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c3b621
6be27f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c3b621
6be27f7
 
 
 
 
 
1c3b621
6be27f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c3b621
6be27f7
 
 
 
1c3b621
6be27f7
 
 
1c3b621
6be27f7
 
 
 
 
 
 
 
 
 
 
 
 
1c3b621
6be27f7
 
 
 
1c3b621
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6be27f7
1c3b621
 
6be27f7
 
 
 
1c3b621
 
 
6be27f7
1c3b621
 
 
6be27f7
 
 
 
 
1c3b621
 
 
6be27f7
 
1c3b621
 
 
6be27f7
 
 
 
1c3b621
6be27f7
 
 
 
 
 
 
1c3b621
 
 
6be27f7
 
 
 
1c3b621
 
 
6be27f7
 
 
 
 
 
 
 
1c3b621
 
 
6be27f7
 
 
 
 
 
 
 
 
 
1c3b621
 
 
6be27f7
 
 
1c3b621
 
 
6be27f7
 
 
1c3b621
 
 
6be27f7
 
 
 
 
 
1c3b621
 
 
6be27f7
 
 
 
 
 
 
 
1c3b621
 
6be27f7
 
 
 
 
 
1c3b621
 
 
6be27f7
 
1c3b621
 
6be27f7
 
1c3b621
6be27f7
 
1c3b621
6be27f7
 
 
 
 
 
 
 
1c3b621
6be27f7
 
1c3b621
 
 
6be27f7
 
1c3b621
6be27f7
1c3b621
6be27f7
1c3b621
 
6be27f7
1c3b621
 
 
 
 
 
 
 
6be27f7
 
 
 
 
 
 
 
 
1c3b621
 
 
6be27f7
 
 
 
 
 
 
 
 
1c3b621
 
 
6be27f7
 
 
1c3b621
 
 
6be27f7
 
 
 
1c3b621
 
 
6be27f7
 
 
 
 
 
1c3b621
 
 
6be27f7
 
 
 
 
1c3b621
 
 
6be27f7
 
 
 
1c3b621
 
 
6be27f7
 
 
 
1c3b621
 
 
6be27f7
1c3b621
 
6be27f7
 
 
 
 
1c3b621
 
6be27f7
 
1c3b621
 
 
6be27f7
 
 
1c3b621
 
 
6be27f7
 
 
 
1c3b621
 
6be27f7
 
 
 
 
1c3b621
 
 
6be27f7
 
1c3b621
 
6be27f7
 
 
 
 
1c3b621
 
6be27f7
 
1c3b621
 
6be27f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c3b621
 
 
 
6be27f7
1c3b621
 
6be27f7
 
 
1c3b621
 
 
 
6be27f7
 
 
 
1c3b621
 
6be27f7
1c3b621
 
6be27f7
1c3b621
6be27f7
 
1c3b621
 
 
6be27f7
1c3b621
 
6be27f7
1c3b621
 
 
6be27f7
 
 
 
 
 
 
 
1c3b621
 
6be27f7
1c3b621
 
6be27f7
1c3b621
6be27f7
1c3b621
 
6be27f7
 
1c3b621
 
6be27f7
 
 
 
 
 
 
 
1c3b621
 
6be27f7
 
 
 
 
 
 
1c3b621
 
 
6be27f7
 
 
 
 
 
 
 
1c3b621
 
6be27f7
1c3b621
6be27f7
 
 
 
 
 
1c3b621
6be27f7
1c3b621
6be27f7
1c3b621
 
6be27f7
 
1c3b621
 
 
 
 
 
6be27f7
1c3b621
 
 
6be27f7
1c3b621
 
 
 
 
 
 
6be27f7
1c3b621
 
 
 
 
 
6be27f7
1c3b621
 
 
 
 
6be27f7
1c3b621
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff9b8c0
 
 
 
 
 
 
 
 
 
6d8a6e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c3b621
6be27f7
3661fa5
 
 
 
 
 
 
 
 
 
 
 
 
 
6d8a6e9
1c3b621
 
 
 
6d8a6e9
1c3b621
6d8a6e9
1c3b621
 
 
6d8a6e9
1c3b621
 
6d8a6e9
1c3b621
 
 
 
 
6d8a6e9
1c3b621
6d8a6e9
1c3b621
 
6d8a6e9
1c3b621
 
 
6d8a6e9
1c3b621
 
 
 
 
 
 
 
 
 
 
6d8a6e9
1c3b621
 
6d8a6e9
1c3b621
 
 
6d8a6e9
1c3b621
 
6d8a6e9
1c3b621
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d8a6e9
1c3b621
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d8a6e9
1c3b621
 
 
 
 
6d8a6e9
1c3b621
 
 
6d8a6e9
1c3b621
 
 
 
 
 
 
 
6d8a6e9
1c3b621
 
 
 
 
 
 
6d8a6e9
1c3b621
 
 
 
 
 
6d8a6e9
1c3b621
 
 
 
 
 
 
6d8a6e9
1c3b621
 
 
 
6d8a6e9
1c3b621
 
 
 
 
 
6d8a6e9
 
1c3b621
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d8a6e9
1c3b621
 
 
 
 
6d8a6e9
1c3b621
 
 
 
 
6d8a6e9
1c3b621
6d8a6e9
 
1c3b621
 
 
 
6d8a6e9
1c3b621
6be27f7
 
1c3b621
 
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
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
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, UserPreferences, get_breed_recommendations, format_recommendation_html
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.2:
        error_message = '''
            <div class="dog-info-card">
                <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 of a dog.
                    </p>
                </div>
            </div>
        '''
        initial_state = {
            "explanation": error_message,
            "image": None,
            "is_multi_dog": False
        }
        return error_message, 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_html(description, breed)  # 使用 format_description_html
        html_content = f'''
            <div class="dog-info-card">
                <div class="breed-info">
                    {formatted_description}
                </div>
            </div>
        '''
        initial_state = {
            "explanation": html_content,
            "image": image,
            "is_multi_dog": False
        }
        return html_content, image, initial_state

    # Case 3: Medium confidence - show top 3 breeds with relative probabilities
    else:
        breeds_html = ""
        for i, (breed, prob) in enumerate(zip(topk_breeds, relative_probs)):
            description = get_dog_description(breed)
            formatted_description = format_description_html(description, breed)  # 使用 format_description_html
            breeds_html += f'''
                <div class="dog-info-card">
                    <div class="breed-info">
                        <div class="breed-header">
                            <span class="breed-name">Breed {i+1}: {breed}</span>
                            <span class="confidence-badge">Confidence: {prob}</span>
                        </div>
                        {formatted_description}
                    </div>
                </div>
            '''

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


def create_breed_comparison(breed1: str, breed2: str) -> dict:
    """比較兩個狗品種的特性"""
    breed1_info = get_dog_description(breed1)
    breed2_info = get_dog_description(breed2)

    # 標準化數值轉換
    value_mapping = {
        'Size': {'Small': 1, 'Medium': 2, 'Large': 3, 'Giant': 4},
        'Exercise_Needs': {'Low': 1, 'Moderate': 2, 'High': 3, 'Very High': 4},
        'Care_Level': {'Low': 1, 'Moderate': 2, 'High': 3},
        'Grooming_Needs': {'Low': 1, 'Moderate': 2, 'High': 3}
    }

    comparison_data = {
        breed1: {},
        breed2: {}
    }

    for breed, info in [(breed1, breed1_info), (breed2, breed2_info)]:
        comparison_data[breed] = {
            'Size': value_mapping['Size'].get(info['Size'], 2),  # 預設 Medium
            'Exercise_Needs': value_mapping['Exercise_Needs'].get(info['Exercise Needs'], 2),  # 預設 Moderate
            'Care_Level': value_mapping['Care_Level'].get(info['Care Level'], 2),
            'Grooming_Needs': value_mapping['Grooming_Needs'].get(info['Grooming Needs'], 2),
            'Good_with_Children': info['Good with Children'] == 'Yes',
            'Original_Data': info
        }

    return comparison_data


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',  # 珊瑚紅
        '#28A745',  # 深綠色
        '#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.2:
                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="tooltip tooltip-left">
                                    <span class="icon">📏</span>
                                    <span class="label">Size:</span>
                                    <span class="tooltip-icon">ⓘ</span>
                                    <span class="tooltip-text">
                                        <strong>Size Categories:</strong><br>
                                        • Small: Under 20 pounds<br>
                                        • Medium: 20-60 pounds<br>
                                        • Large: Over 60 pounds<br>
                                        • Giant: Over 100 pounds<br>
                                        • Varies: Depends on variety
                                    </span>
                                </span>
                                <span class="value">{description['Size']}</span>
                            </div>
                            <div class="info-item">
                                <span class="tooltip">
                                    <span class="icon">⏳</span>
                                    <span class="label">Lifespan:</span>
                                    <span class="tooltip-icon">ⓘ</span>
                                    <span class="tooltip-text">
                                        <strong>Average Lifespan:</strong><br>
                                        • Short: 6-8 years<br>
                                        • Average: 10-15 years<br>
                                        • Long: 12-20 years<br>
                                        • Varies by size: Larger breeds typically have shorter lifespans
                                    </span>
                                </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="tooltip">
                                <span class="value">{description['Temperament']}</span>
                                <span class="tooltip-icon">ⓘ</span>
                                <span class="tooltip-text">
                                    <strong>Temperament Guide:</strong><br>
                                    • Describes the dog's natural behavior and personality<br>
                                    • Important for matching with owner's lifestyle<br>
                                    • Can be influenced by training and socialization
                                </span>
                            </span>
                        </div>

                        <h2 class="section-title">
                            <span class="icon">💪</span> CARE REQUIREMENTS
                        </h2>
                        <div class="care-section">
                            <div class="info-item">
                                <span class="tooltip tooltip-left">
                                    <span class="icon">🏃</span>
                                    <span class="label">Exercise:</span>
                                    <span class="tooltip-icon">ⓘ</span>
                                    <span class="tooltip-text">
                                        <strong>Exercise Needs:</strong><br>
                                        • Low: Short walks and play sessions<br>
                                        • Moderate: 1-2 hours of daily activity<br>
                                        • High: Extensive exercise (2+ hours/day)<br>
                                        • Very High: Constant activity and mental stimulation needed
                                    </span>
                                </span>
                                <span class="value">{description['Exercise Needs']}</span>
                            </div>
                            <div class="info-item">
                                <span class="tooltip">
                                    <span class="icon">✂️</span>
                                    <span class="label">Grooming:</span>
                                    <span class="tooltip-icon">ⓘ</span>
                                    <span class="tooltip-text">
                                        <strong>Grooming Requirements:</strong><br>
                                        • Low: Basic brushing, occasional baths<br>
                                        • Moderate: Weekly brushing, occasional grooming<br>
                                        • High: Daily brushing, frequent professional grooming needed<br>
                                        • Professional care recommended for all levels
                                    </span>
                                </span>
                                <span class="value">{description['Grooming Needs']}</span>
                            </div>
                            <div class="info-item">
                                <span class="tooltip">
                                    <span class="icon">⭐</span>
                                    <span class="label">Care Level:</span>
                                    <span class="tooltip-icon">ⓘ</span>
                                    <span class="tooltip-text">
                                        <strong>Care Level Explained:</strong><br>
                                        • Low: Basic care and attention needed<br>
                                        • Moderate: Regular care and routine needed<br>
                                        • High: Significant time and attention needed<br>
                                        • Very High: Extensive care, training and attention required
                                    </span>
                                </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="tooltip">
                                    <span class="icon"></span>
                                    <span class="label">Good with Children:</span>
                                    <span class="tooltip-icon">ⓘ</span>
                                    <span class="tooltip-text">
                                        <strong>Child Compatibility:</strong><br>
                                        • Yes: Excellent with kids, patient and gentle<br>
                                        • Moderate: Good with older children<br>
                                        • No: Better suited for adult households
                                    </span>
                                </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 uncertainty-mode">
                            <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"""
            <div class="dog-info-card">
                {dogs_info}
            </div>
        """

        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():
            if key != "Breed":  # 跳過重複的品種顯示
                if key == "Size":
                    html += f'''
                        <li style='margin-bottom: 10px;'>
                            <span class="tooltip">
                                <strong>{key}:</strong>
                                <span class="tooltip-icon">ⓘ</span>
                                <span class="tooltip-text">
                                    <strong>Size Categories:</strong><br>
                                    • Small: Under 20 pounds<br>
                                    • Medium: 20-60 pounds<br>
                                    • Large: Over 60 pounds
                                </span>
                            </span> {value}
                        </li>
                    '''
                elif key == "Exercise Needs":
                    html += f'''
                        <li style='margin-bottom: 10px;'>
                            <span class="tooltip">
                                <strong>{key}:</strong>
                                <span class="tooltip-icon">ⓘ</span>
                                <span class="tooltip-text">
                                    <strong>Exercise Needs:</strong><br>
                                    • High: 2+ hours of daily exercise<br>
                                    • Moderate: 1-2 hours of daily activity<br>
                                    • Low: Short walks and play sessions
                                </span>
                            </span> {value}
                        </li>
                    '''
                elif key == "Grooming Needs":
                    html += f'''
                        <li style='margin-bottom: 10px;'>
                            <span class="tooltip">
                                <strong>{key}:</strong>
                                <span class="tooltip-icon">ⓘ</span>
                                <span class="tooltip-text">
                                    <strong>Grooming Requirements:</strong><br>
                                    • High: Daily brushing, regular professional care<br>
                                    • Moderate: Weekly brushing, occasional grooming<br>
                                    • Low: Minimal brushing, basic maintenance
                                </span>
                            </span> {value}
                        </li>
                    '''
                elif key == "Care Level":
                    html += f'''
                        <li style='margin-bottom: 10px;'>
                            <span class="tooltip">
                                <strong>{key}:</strong>
                                <span class="tooltip-icon">ⓘ</span>
                                <span class="tooltip-text">
                                    <strong>Care Level Explained:</strong><br>
                                    • High: Needs significant training and attention<br>
                                    • Moderate: Regular care and routine needed<br>
                                    • Low: More independent, basic care sufficient
                                </span>
                            </span> {value}
                        </li>
                    '''
                elif key == "Good with Children":
                    html += f'''
                        <li style='margin-bottom: 10px;'>
                            <span class="tooltip">
                                <strong>{key}:</strong>
                                <span class="tooltip-icon">ⓘ</span>
                                <span class="tooltip-text">
                                    <strong>Child Compatibility:</strong><br>
                                    • Yes: Excellent with kids, patient and gentle<br>
                                    • Moderate: Good with older children<br>
                                    • No: Better suited for adult households
                                </span>
                            </span> {value}
                        </li>
                    '''
                elif key == "Lifespan":
                    html += f'''
                        <li style='margin-bottom: 10px;'>
                            <span class="tooltip">
                                <strong>{key}:</strong>
                                <span class="tooltip-icon">ⓘ</span>
                                <span class="tooltip-text">
                                    <strong>Average Lifespan:</strong><br>
                                    • Short: 6-8 years<br>
                                    • Average: 10-15 years<br>
                                    • Long: 12-20 years
                                </span>
                            </span> {value}
                        </li>
                    '''
                elif key == "Temperament":
                    html += f'''
                        <li style='margin-bottom: 10px;'>
                            <span class="tooltip">
                                <strong>{key}:</strong>
                                <span class="tooltip-icon">ⓘ</span>
                                <span class="tooltip-text">
                                    <strong>Temperament Guide:</strong><br>
                                    • Describes the dog's natural behavior<br>
                                    • Important for matching with owner
                                </span>
                            </span> {value}
                        </li>
                    '''
                else:
                    # 其他欄位保持原樣顯示
                    html += f"<li style='margin-bottom: 10px;'><strong>{key}:</strong> {value}</li>"
    else:
        html += f"<li>{description}</li>"
    html += "</ul>"

    # 添加AKC連結
    html += f'''
        <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>
    '''
    return html


with gr.Blocks(css="""
        .dog-info-card {
            border: 1px solid #e1e4e8;
            margin: 40px 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: 24px 28px;  /* 增加內距 */
            margin: 0;
            font-size: 22px;
            font-weight: bold;
            border-bottom: 1px solid #e1e4e8;
        }

        .breed-info {
            padding: 28px;  /* 增加整體內距 */
            line-height: 1.6;
        }

        .section-title {
            font-size: 1.3em;
            font-weight: 700;
            color: #2c3e50;
            margin: 32px 0 20px 0;
            padding: 12px 0;
            border-bottom: 2px solid #e1e4e8;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            display: flex;
            align-items: center;
            gap: 8px;
            position: relative;
        }

        .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: 28px;  /* 增加底部間距 */
            padding: 20px;  /* 增加內距 */
            background: #f8f9fa;
            border-radius: 12px;
            border: 1px solid #e1e4e8;  /* 添加邊框 */
        }

        .info-item {
            background: white;  /* 改為白色背景 */
            padding: 14px 18px;  /* 增加內距 */
            border-radius: 8px;
            display: flex;
            align-items: center;
            gap: 10px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
            border: 1px solid #e1e4e8;
            flex: 1 1 auto;
            min-width: 200px;
        }

        .label {
            color: #666;
            font-weight: 600;
            font-size: 1.1rem;
        }

        .value {
            color: #2c3e50;
            font-weight: 500;
            font-size: 1.1rem;
        }

        .temperament-section {
            background: #f8f9fa;
            padding: 20px;  /* 增加內距 */
            border-radius: 12px;
            margin-bottom: 28px;  /* 增加間距 */
            color: #444;
            border: 1px solid #e1e4e8;  /* 添加邊框 */
        }

        .description-section {
            background: #f8f9fa;
            padding: 24px;  /* 增加內距 */
            border-radius: 12px;
            margin: 28px 0;  /* 增加上下間距 */
            line-height: 1.8;
            color: #444;
            border: 1px solid #e1e4e8;  /* 添加邊框 */
            fontsize: 1.1rem;
        }
        .description-section p {
            margin: 0;
            padding: 0;
            text-align: justify;  /* 文字兩端對齊 */
            word-wrap: break-word;  /* 確保長單字會換行 */
            white-space: pre-line;  /* 保留換行但合併空白 */
            max-width: 100%;  /* 確保不會超出容器 */
        }

        .action-section {
            margin-top: 24px;
            text-align: center;
        }

        .akc-button,
        .breed-section .akc-link,
        .breed-option .akc-link {
            display: inline-flex;
            align-items: center;
            padding: 14px 28px;
            background: linear-gradient(145deg, #00509E, #003F7F);
            color: white;
            border-radius: 12px;  /* 增加圓角 */
            text-decoration: none;
            gap: 12px;  /* 增加圖標和文字間距 */
            transition: all 0.3s ease;
            font-weight: 600;
            font-size: 1.1em;
            box-shadow:
                0 2px 4px rgba(0,0,0,0.1),
                inset 0 1px 1px rgba(255,255,255,0.1);
            border: 1px solid rgba(255,255,255,0.1);
        }

        .akc-button:hover,
        .breed-section .akc-link:hover,
        .breed-option .akc-link:hover {
            background: linear-gradient(145deg, #003F7F, #00509E);
            transform: translateY(-2px);
            color: white;
            box-shadow:
                0 6px 12px rgba(0,0,0,0.2),
                inset 0 1px 1px rgba(255,255,255,0.2);
            border: 1px solid rgba(255,255,255,0.2);
        }
        .icon {
            font-size: 1.3em;
            filter: drop-shadow(0 1px 1px rgba(0,0,0,0.2));
        }

        .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.5em;
            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;
        }
        .breed-content li {
            margin-bottom: 8px;
            display: flex;
            align-items: flex-start;  /* 改為頂部對齊 */
            gap: 8px;
            flex-wrap: wrap;  /* 允許內容換行 */
        }
        .breed-content li strong {
            flex: 0 0 auto;  /* 不讓標題縮放 */
            min-width: 100px;  /* 給標題一個固定最小寬度 */
        }

        ul {
            padding-left: 0;
            margin: 0;
            list-style-type: none;
        }

        li {
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .akc-link {
            color: white;
            text-decoration: none;
            font-weight: 600;
            font-size: 1.1em;
            transition: all 0.3s ease;
        }

        .akc-link:hover {
            text-decoration: underline;
            color: #D3E3F0;
        }
        .tooltip {
            position: relative;
            display: inline-flex;
            align-items: center;
            gap: 4px;
            cursor: help;
        }
        .tooltip .tooltip-icon {
            font-size: 14px;
            color: #666;
        }
        .tooltip .tooltip-text {
            visibility: hidden;
            width: 250px;
            background-color: rgba(44, 62, 80, 0.95);
            color: white;
            text-align: left;
            border-radius: 8px;
            padding: 8px 10px;
            position: absolute;
            z-index: 100;
            bottom: 150%;
            left: 50%;
            transform: translateX(-50%);
            opacity: 0;
            transition: all 0.3s ease;
            font-size: 14px;
            line-height: 1.3;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.1)
            margin-bottom: 10px;
        }
        .tooltip.tooltip-left .tooltip-text {
            left: 0;
            transform: translateX(0);
        }
        .tooltip.tooltip-right .tooltip-text {
            left: auto;
            right: 0;
            transform: translateX(0);
        }
        .tooltip-text strong {
            color: white !important;
            background-color: transparent !important;
            display: block;  /* 讓標題獨立一行 */
            margin-bottom: 2px;  /* 增加標題下方間距 */
            padding-bottom: 2px; /* 加入小間距 */
            border-bottom: 1px solid rgba(255,255,255,0.2);
        }
        .tooltip-text {
            font-size: 13px;  /* 稍微縮小字體 */
        }

        /* 調整列表符號和文字的間距 */
        .tooltip-text ul {
            margin: 0;
            padding-left: 15px;  /* 減少列表符號的縮進 */
        }

        .tooltip-text li {
            margin-bottom: 1px;  /* 減少列表項目間的間距 */
        }
        .tooltip-text br {
            line-height: 1.2;  /* 減少行距 */
        }

        .tooltip .tooltip-text::after {
            content: "";
            position: absolute;
            top: 100%;
            left: 20%;  /* 調整箭頭位置 */
            margin-left: -5px;
            border-width: 5px;
            border-style: solid;
            border-color: rgba(44, 62, 80, 0.95) transparent transparent transparent;
        }
        .tooltip-left .tooltip-text::after {
            left: 20%;
        }

        /* 右側箭頭 */
        .tooltip-right .tooltip-text::after {
            left: 80%;
        }
        .tooltip:hover .tooltip-text {
            visibility: visible;
            opacity: 1;
        }
        .tooltip .tooltip-text::after {
            content: "";
            position: absolute;
            top: 100%;
            left: 50%;
            transform: translateX(-50%);
            border-width: 8px;
            border-style: solid;
            border-color: rgba(44, 62, 80, 0.95) transparent transparent transparent;
        }
        .uncertainty-mode .tooltip .tooltip-text {
            position: absolute;
            left: 100%;
            bottom: auto;
            top: 50%;
            transform: translateY(-50%);
            margin-left: 10px;
            z-index: 1000;  /* 確保提示框在最上層 */
        }

        .uncertainty-mode .tooltip .tooltip-text::after {
            content: "";
            position: absolute;
            top: 50%;
            right: 100%;
            transform: translateY(-50%);
            border-width: 5px;
            border-style: solid;
            border-color: transparent rgba(44, 62, 80, 0.95) transparent transparent;
        }
        .uncertainty-mode .breed-content {
            font-size: 1.1rem;  /* 增加字體大小 */
        }
        .description-section,
        .description-section p,
        .temperament-section,
        .temperament-section .value,
        .info-item,
        .info-item .value,
        .breed-content {
            font-size: 1.1rem !important;  /* 使用 !important 確保覆蓋其他樣式 */
        }

        .recommendation-card {
            margin-bottom: 40px;
        }

        .compatibility-scores {
            background: #f8f9fa;
            padding: 24px;
            border-radius: 12px;
            margin: 20px 0;
        }

        .score-item {
            margin: 15px 0;
        }

        .progress-bar {
            height: 12px;
            background-color: #e9ecef;
            border-radius: 6px;
            overflow: hidden;
            margin: 8px 0;
        }

        .progress {
            height: 100%;
            background: linear-gradient(90deg, #34C759, #30B350);
            border-radius: 6px;
            transition: width 0.6s ease;
        }

        .percentage {
            float: right;
            color: #34C759;
            font-weight: 600;
        }

        .breed-details-section {
            margin: 30px 0;
        }

        .subsection-title {
            font-size: 1.2em;
            color: #2c3e50;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .details-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            background: #f8f9fa;
            padding: 20px;
            border-radius: 12px;
            border: 1px solid #e1e4e8;
        }

        .detail-item {
            background: white;
            padding: 15px;
            border-radius: 8px;
            border: 1px solid #e1e4e8;
        }

        .description-text {
            line-height: 1.8;
            color: #444;
            margin: 0;
            padding: 24px 30px;  /* 調整內部間距,從 20px 改為 24px 30px */
            background: #f8f9fa;
            border-radius: 12px;
            border: 1px solid #e1e4e8;
            text-align: justify;  /* 添加文字對齊 */
            word-wrap: break-word;  /* 確保長文字會換行 */
            word-spacing: 1px;  /* 加入字間距 */
        }

        /* 工具提示改進 */
        .tooltip {
            position: relative;
            display: inline-flex;
            align-items: center;
            gap: 4px;
            cursor: help;
            padding: 5px 0;
        }

        .tooltip .tooltip-text {
            visibility: hidden;
            width: 280px;
            background-color: rgba(44, 62, 80, 0.95);
            color: white;
            text-align: left;
            border-radius: 8px;
            padding: 12px 15px;
            position: absolute;
            z-index: 1000;
            bottom: calc(100% + 15px);
            left: 50%;
            transform: translateX(-50%);
            opacity: 0;
            transition: all 0.3s ease;
            font-size: 14px;
            line-height: 1.4;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.2);
            white-space: normal;
        }

        .tooltip:hover .tooltip-text {
            visibility: visible;
            opacity: 1;
        }

        .score-badge {
            background-color: #34C759;
            color: white;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 0.9em;
            margin-left: 10px;
            font-weight: 500;
            box-shadow: 0 2px 4px rgba(52, 199, 89, 0.2);
        }

        .bonus-score .tooltip-text {
            width: 250px;
            line-height: 1.4;
            padding: 10px;
        }

        .bonus-score .progress {
            background: linear-gradient(90deg, #48bb78, #68d391);
        }

        .health-section {
            margin: 25px 0;
            padding: 24px;
            background-color: #f8f9fb;
            border-radius: 12px;
            border: 1px solid #e1e4e8;
        }

        .health-section .subsection-title {
            font-size: 1.3em;
            font-weight: 600;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 8px;
            color: #2c3e50;
        }

        .health-info {
            background-color: white;
            padding: 24px;
            border-radius: 8px;
            margin: 15px 0;
            border: 1px solid #e1e4e8;
        }

        .health-details {
            font-size: 1.1rem;
            line-height: 1.6;
        }

        .health-details h4 {
            color: #2c3e50;
            font-size: 1.15rem;
            font-weight: 600;
            margin: 20px 0 15px 0;
        }

        .health-details h4:first-child {
            margin-top: 0;
        }

        .health-details ul {
            list-style-type: none;
            padding-left: 0;
            margin: 0 0 25px 0;
        }

        .health-details ul li {
            margin-bottom: 12px;
            padding-left: 20px;
            position: relative;
        }

        .health-details ul li:before {
            content: "•";
            position: absolute;
            left: 0;
            color: #2c3e50;
        }

        .health-disclaimer {
            margin-top: 20px;
            color: #666;
            font-size: 1.05rem;
            line-height: 1.6;
            padding-top: 20px;
            border-top: 1px solid #e1e4e8;
        }

        .health-disclaimer p {
            margin: 8px 0;
            padding-left: 15px;
            position: relative;
        }

        .health-disclaimer p:before {
            content: "»";
            position: absolute;
            left: 0;
            color: #666;
        }

        """) as iface:

        gr.HTML("""
        <header style='text-align: center; padding: 20px; margin-bottom: 20px;'>
            <h1 style='font-size: 2.5em; margin-bottom: 10px; color: #2D3748;'>
                🐾 PawMatch AI
            </h1>
            <h2 style='font-size: 1.2em; font-weight: normal; color: #4A5568; margin-top: 5px;'>
                Your Smart Dog Breed Guide
            </h2>
            <div style='width: 50px; height: 3px; background: linear-gradient(90deg, #4299e1, #48bb78); margin: 15px auto;'></div>
            <p style='color: #718096; font-size: 0.9em;'>
                Powered by AI • Breed Recognition • Smart Matching • Companion Guide
            </p>
        </header>
        """)

        # 使用 Tabs 來分隔兩個功能
        with gr.Tabs():
            # 第一個 Tab:原有的辨識功能
            with gr.TabItem("Breed Detection"):
                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
                )

            # 第二個 Tab:品種比較功能
            with gr.TabItem("Breed Comparison"):
                gr.HTML("<p style='text-align: center;'>Select two dog breeds to compare their characteristics and care requirements.</p>")

                with gr.Row():
                    breed1_dropdown = gr.Dropdown(
                        choices=dog_breeds,
                        label="Select First Breed",
                        value="Golden_Retriever"
                    )
                    breed2_dropdown = gr.Dropdown(
                        choices=dog_breeds,
                        label="Select Second Breed",
                        value="Border_Collie"
                    )

                compare_btn = gr.Button("Compare Breeds")
                comparison_output = gr.HTML(label="Comparison Results")

                def show_comparison(breed1, breed2):
                    if not breed1 or not breed2:
                        return "Please select two breeds to compare"

                    breed1_info = get_dog_description(breed1)
                    breed2_info = get_dog_description(breed2)

                    html_output = f"""
                    <div class="dog-info-card">
                        <div class="comparison-grid" style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                            <div class="breed-info">
                                <h2 class="section-title">
                                    <span class="icon">🐕</span> {breed1.replace('_', ' ')}
                                </h2>
                                <div class="info-section">
                                    <div class="info-item">
                                        <span class="tooltip">
                                            <span class="icon">📏</span>
                                            <span class="label">Size:</span>
                                            <span class="value">{breed1_info['Size']}</span>
                                        </span>
                                    </div>
                                    <div class="info-item">
                                        <span class="tooltip">
                                            <span class="icon">🏃</span>
                                            <span class="label">Exercise Needs:</span>
                                            <span class="value">{breed1_info['Exercise Needs']}</span>
                                        </span>
                                    </div>
                                    <div class="info-item">
                                        <span class="tooltip">
                                            <span class="icon">✂️</span>
                                            <span class="label">Grooming:</span>
                                            <span class="value">{breed1_info['Grooming Needs']}</span>
                                        </span>
                                    </div>
                                    <div class="info-item">
                                        <span class="tooltip">
                                            <span class="icon">👨‍👩‍👧‍👦</span>
                                            <span class="label">Good with Children:</span>
                                            <span class="value">{breed1_info['Good with Children']}</span>
                                        </span>
                                    </div>
                                </div>
                            </div>

                            <div class="breed-info">
                                <h2 class="section-title">
                                    <span class="icon">🐕</span> {breed2.replace('_', ' ')}
                                </h2>
                                <div class="info-section">
                                    <div class="info-item">
                                        <span class="tooltip">
                                            <span class="icon">📏</span>
                                            <span class="label">Size:</span>
                                            <span class="value">{breed2_info['Size']}</span>
                                        </span>
                                    </div>
                                    <div class="info-item">
                                        <span class="tooltip">
                                            <span class="icon">🏃</span>
                                            <span class="label">Exercise Needs:</span>
                                            <span class="value">{breed2_info['Exercise Needs']}</span>
                                        </span>
                                    </div>
                                    <div class="info-item">
                                        <span class="tooltip">
                                            <span class="icon">✂️</span>
                                            <span class="label">Grooming:</span>
                                            <span class="value">{breed2_info['Grooming Needs']}</span>
                                        </span>
                                    </div>
                                    <div class="info-item">
                                        <span class="tooltip">
                                            <span class="icon">👨‍👩‍👧‍👦</span>
                                            <span class="label">Good with Children:</span>
                                            <span class="value">{breed2_info['Good with Children']}</span>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    """
                    return html_output

                compare_btn.click(
                    show_comparison,
                    inputs=[breed1_dropdown, breed2_dropdown],
                    outputs=comparison_output
                )

            # 第三個 Tab:品種推薦功能
            with gr.TabItem("Breed Recommendation"):
                gr.HTML("<p style='text-align: center;'>Tell us about your lifestyle, and we'll recommend the perfect dog breeds for you!</p>")

                with gr.Row():
                    with gr.Column():
                        living_space = gr.Radio(
                            choices=["apartment", "house_small", "house_large"],
                            label="What type of living space do you have?",
                            info="Choose your current living situation",
                            value="apartment"
                        )

                        exercise_time = gr.Slider(
                            minimum=0,
                            maximum=180,
                            value=60,
                            label="Daily exercise time (minutes)",
                            info="Consider walks, play time, and training"
                        )

                        grooming_commitment = gr.Radio(
                            choices=["low", "medium", "high"],
                            label="Grooming commitment level",
                            info="Low: monthly, Medium: weekly, High: daily",
                            value="medium"
                        )

                    with gr.Column():
                        experience_level = gr.Radio(
                            choices=["beginner", "intermediate", "advanced"],
                            label="Dog ownership experience",
                            info="Be honest - this helps find the right match",
                            value="beginner"
                        )

                        has_children = gr.Checkbox(
                            label="Have children at home",
                            info="Helps recommend child-friendly breeds"
                        )

                        noise_tolerance = gr.Radio(
                            choices=["low", "medium", "high"],
                            label="Noise tolerance level",
                            info="Some breeds are more vocal than others",
                            value="medium"
                        )


                # 設置按鈕的點擊事件
                get_recommendations_btn = gr.Button("Find My Perfect Match! 🔍", variant="primary")
                recommendation_output = gr.HTML(label="Breed Recommendations")

                def process_recommendations(living_space, exercise_time, grooming_commitment,
                        experience_level, has_children, noise_tolerance):
                    try:
                        user_prefs = UserPreferences(
                            living_space=living_space,
                            exercise_time=exercise_time,
                            grooming_commitment=grooming_commitment,
                            experience_level=experience_level,
                            has_children=has_children,
                            noise_tolerance=noise_tolerance,
                            space_for_play=True if living_space != "apartment" else False,
                            other_pets=False,
                            climate="moderate"
                        )

                        recommendations = get_breed_recommendations(user_prefs)
                        return format_recommendation_html(recommendations)
                    except Exception as e:
                        print(f"Error in process_recommendations: {str(e)}")
                        return f"An error occurred: {str(e)}"

                # 這行是關鍵 - 確保按鈕點擊事件有正確連接到處理函數
                get_recommendations_btn.click(
                    fn=process_recommendations,  # 處理函數
                    inputs=[
                        living_space,
                        exercise_time,
                        grooming_commitment,
                        experience_level,
                        has_children,
                        noise_tolerance
                    ],
                    outputs=recommendation_output  # 輸出結果的位置
                )

        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(share=True)