File size: 47,281 Bytes
a7dedf9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bcf1a8b
277670a
a7dedf9
0e1e36c
ae09b40
 
 
 
e85ffa0
ae09b40
 
 
e85ffa0
ae09b40
 
 
e85ffa0
ae09b40
 
 
e85ffa0
ae09b40
 
 
0e1e36c
a7dedf9
277670a
 
 
e85ffa0
277670a
 
 
 
e85ffa0
 
 
 
 
 
 
 
 
 
277670a
 
 
 
 
 
 
 
 
e85ffa0
 
277670a
61ba3dd
 
277670a
 
 
61ba3dd
277670a
61ba3dd
 
277670a
61ba3dd
 
277670a
 
a7dedf9
 
 
 
 
ccc542d
a7dedf9
 
 
 
 
 
 
 
 
99459bc
 
a7dedf9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d8c6cc
a7dedf9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e85ffa0
a7dedf9
 
 
 
277670a
ef5adb7
61ba3dd
 
 
e85ffa0
 
9cb167a
e85ffa0
 
 
9cb167a
e85ffa0
 
a7dedf9
ccc542d
 
 
 
 
 
 
 
e85ffa0
9cb167a
a7dedf9
61ba3dd
 
 
 
 
 
 
 
 
 
ccc542d
 
 
 
 
 
 
 
 
ae09b40
 
 
 
449e3d1
a7dedf9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9cb167a
a7dedf9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b564f44
 
 
 
 
 
 
a7dedf9
9a7b741
 
 
 
 
a7dedf9
affc2a7
b564f44
 
a7dedf9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9cb167a
 
 
 
 
 
 
 
 
 
 
 
a7dedf9
 
 
 
 
e85ffa0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9cb167a
 
 
b564f44
9cb167a
 
b564f44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf779d9
 
 
 
 
 
fb20bf9
 
 
4a2b023
 
 
 
 
fb20bf9
 
 
 
 
 
cf779d9
b564f44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf779d9
 
 
 
 
 
fb20bf9
 
 
4a2b023
 
 
 
 
fb20bf9
 
 
 
 
 
cf779d9
b564f44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf779d9
 
 
 
 
 
fb20bf9
 
 
4a2b023
 
 
 
 
fb20bf9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf779d9
b564f44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9cb167a
 
 
 
 
 
 
b564f44
9cb167a
 
 
 
b564f44
9cb167a
 
 
 
 
 
b564f44
9cb167a
b564f44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9cb167a
 
 
 
 
 
b564f44
9cb167a
 
b564f44
 
9cb167a
b564f44
 
 
9cb167a
 
 
b564f44
 
 
9cb167a
 
 
 
b564f44
9cb167a
b564f44
 
 
 
9cb167a
 
 
 
b564f44
 
9cb167a
 
b564f44
9cb167a
b564f44
9cb167a
b564f44
9cb167a
b564f44
 
 
9cb167a
 
 
b564f44
9cb167a
 
 
4a2b023
b564f44
4a2b023
b564f44
 
4a2b023
b564f44
 
 
 
 
 
 
 
fb20bf9
 
b564f44
 
 
 
 
 
fb20bf9
0f2ce4d
 
 
 
 
 
 
 
 
 
 
 
 
 
b564f44
 
4a2b023
cf779d9
4a2b023
 
cf779d9
 
fb20bf9
cf779d9
 
fb20bf9
 
4a2b023
 
 
 
cf779d9
 
4a2b023
 
fb20bf9
cf779d9
 
4a2b023
fb20bf9
 
 
 
 
 
cf779d9
 
9cb167a
 
 
b564f44
 
 
4a2b023
 
 
9cb167a
 
 
 
b564f44
9cb167a
b564f44
 
 
 
9cb167a
 
 
 
b564f44
9cb167a
b564f44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a2b023
cf779d9
b564f44
 
 
 
 
 
 
 
9cb167a
 
 
 
b564f44
 
 
 
 
 
 
9cb167a
 
b564f44
 
 
 
 
 
 
9cb167a
 
b564f44
 
9cb167a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e85ffa0
 
9cb167a
 
 
8994c36
9cb167a
 
 
8994c36
9cb167a
8994c36
 
 
 
 
 
9cb167a
 
 
a7dedf9
4a2b023
a7dedf9
4a2b023
 
 
 
 
 
 
 
 
 
9cb167a
4a2b023
 
 
 
 
 
 
b564f44
 
 
 
4a2b023
b564f44
9cb167a
b564f44
 
9cb167a
b564f44
 
 
 
9cb167a
 
4a2b023
9cb167a
 
 
 
 
 
 
 
 
b564f44
9cb167a
 
b564f44
 
 
 
9cb167a
b564f44
9cb167a
 
b564f44
 
 
 
 
3b32643
b564f44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a7dedf9
e85ffa0
 
 
 
9cb167a
 
 
 
 
 
 
 
277670a
 
 
e85ffa0
277670a
 
 
61ba3dd
ef5adb7
61ba3dd
ef5adb7
 
 
a7dedf9
 
e85ffa0
929bf51
a7dedf9
 
9cb167a
 
 
 
 
3b32643
9cb167a
 
 
 
 
11c9ec8
9cb167a
 
 
 
 
 
 
8994c36
9cb167a
 
 
 
 
 
3b32643
8994c36
b564f44
3b32643
 
8994c36
 
b564f44
3b32643
fe5f0a4
 
9cb167a
 
 
 
 
 
 
8994c36
9cb167a
 
 
 
 
8994c36
 
 
 
9cb167a
 
 
 
 
 
 
 
 
 
 
 
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
import torch
from torch import nn
import torch.nn.functional as F
import torchvision.transforms.functional as TF

from torch import Tensor
import spaces

import numpy as np
from PIL import Image
import gradio as gr
from matplotlib import cm
from huggingface_hub import hf_hub_download
from warnings import warn

from models import get_model


mean = (0.485, 0.456, 0.406)
std = (0.229, 0.224, 0.225)
alpha = 0.8
EPS = 1e-8
loaded_model = None
current_model_config = {"variant": None, "dataset": None, "metric": None}

pretrained_models = [
    "ZIP-B @ ShanghaiTech A @ MAE", "ZIP-B @ ShanghaiTech A @ NAE",
    "ZIP-B @ ShanghaiTech B @ MAE", "ZIP-B @ ShanghaiTech B @ NAE",
    "ZIP-B @ UCF-QNRF @ MAE", "ZIP-B @ UCF-QNRF @ NAE",
    "ZIP-B @ NWPU-Crowd @ MAE", "ZIP-B @ NWPU-Crowd @ NAE",
    "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
    "ZIP-S @ ShanghaiTech A @ MAE", "ZIP-S @ ShanghaiTech A @ NAE",
    "ZIP-S @ ShanghaiTech B @ MAE", "ZIP-S @ ShanghaiTech B @ NAE",
    "ZIP-S @ UCF-QNRF @ MAE", "ZIP-S @ UCF-QNRF @ NAE",
    "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
    "ZIP-T @ ShanghaiTech A @ MAE", "ZIP-T @ ShanghaiTech A @ NAE",
    "ZIP-T @ ShanghaiTech B @ MAE", "ZIP-T @ ShanghaiTech B @ NAE",
    "ZIP-T @ UCF-QNRF @ MAE", "ZIP-T @ UCF-QNRF @ NAE",
    "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
    "ZIP-N @ ShanghaiTech A @ MAE", "ZIP-N @ ShanghaiTech A @ NAE",
    "ZIP-N @ ShanghaiTech B @ MAE", "ZIP-N @ ShanghaiTech B @ NAE",
    "ZIP-N @ UCF-QNRF @ MAE", "ZIP-N @ UCF-QNRF @ NAE",
    "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
    "ZIP-P @ ShanghaiTech A @ MAE", "ZIP-P @ ShanghaiTech A @ NAE",
    "ZIP-P @ ShanghaiTech B @ MAE", "ZIP-P @ ShanghaiTech B @ NAE",
    "ZIP-P @ UCF-QNRF @ MAE", "ZIP-P @ UCF-QNRF @ NAE",
]

# -----------------------------
# Model management functions
# -----------------------------
def update_model_if_needed(variant_dataset_metric: str):
    """
    Load a new model only if the configuration has changed.
    """
    global loaded_model, current_model_config
    
    # 如果是分割线,则跳过
    if "━━━━━━" in variant_dataset_metric:
        return "Please select a valid model configuration"
    
    parts = variant_dataset_metric.split(" @ ")
    if len(parts) != 3:
        return "Invalid model configuration format"
        
    variant, dataset, metric = parts[0], parts[1], parts[2].lower()

    if dataset == "ShanghaiTech A":
        dataset_name = "sha"
    elif dataset == "ShanghaiTech B":
        dataset_name = "shb"
    elif dataset == "UCF-QNRF":
        dataset_name = "qnrf"
    elif dataset == "NWPU-Crowd":
        dataset_name = "nwpu"
    else:
        return f"Unknown dataset: {dataset}"

    # 只更新配置,不在主进程中加载模型
    if (current_model_config["variant"] != variant or 
        current_model_config["dataset"] != dataset_name or 
        current_model_config["metric"] != metric):
        
        print(f"Model configuration updated: {variant} @ {dataset} with {metric} metric")
        current_model_config = {"variant": variant, "dataset": dataset_name, "metric": metric}
        loaded_model = None  # 重置模型,将在GPU进程中重新加载
        return f"Model configuration set: {variant} @ {dataset} ({metric})"
    else:
        print(f"Model configuration unchanged: {variant} @ {dataset} with {metric} metric")
        return f"Model configuration: {variant} @ {dataset} ({metric})"


# -----------------------------
# Define the model architecture
# -----------------------------
def load_model(variant: str, dataset: str = "ShanghaiTech B", metric: str = "mae"):
    """ Load the model weights from the Hugging Face Hub."""
    # global loaded_model
    # Build model

    model_info_path = hf_hub_download(
        repo_id=f"Yiming-M/{variant}",
        filename=f"checkpoints/{dataset}/best_{metric}.pth",
    )

    model = get_model(model_info_path=model_info_path)
    model.eval()
    # loaded_model = model
    return model


def _calc_size(
    img_w: int,
    img_h: int,
    min_size: int,
    max_size: int,
    base: int = 32
):
    """
    This function generates a new size for an image while keeping the aspect ratio. The new size should be within the given range (min_size, max_size).

    Args:
        img_w (int): The width of the image.
        img_h (int): The height of the image.
        min_size (int): The minimum size of the edges of the image.
        max_size (int): The maximum size of the edges of the image.
        # base (int): The base number to which the new size should be a multiple of.
    """
    assert min_size % base == 0, f"min_size ({min_size}) must be a multiple of {base}"
    if max_size != float("inf"):
        assert max_size % base == 0, f"max_size ({max_size}) must be a multiple of {base} if provided"

    assert min_size <= max_size, f"min_size ({min_size}) must be less than or equal to max_size ({max_size})"

    aspect_ratios = (img_w / img_h, img_h / img_w)
    if min_size / max_size <= min(aspect_ratios) <= max(aspect_ratios) <= max_size / min_size:  # possible to resize and preserve the aspect ratio
        if min_size <= min(img_w, img_h) <= max(img_w, img_h) <= max_size:  # already within the range, no need to resize
            ratio = 1.
        elif min(img_w, img_h) < min_size:  # smaller than the minimum size, resize to the minimum size
            ratio = min_size / min(img_w, img_h)
        else:  # larger than the maximum size, resize to the maximum size
            ratio = max_size / max(img_w, img_h)

        new_w, new_h = int(round(img_w * ratio / base) * base), int(round(img_h * ratio / base) * base)
        new_w = max(min_size, min(max_size, new_w))
        new_h = max(min_size, min(max_size, new_h))
        return new_w, new_h

    else:  # impossible to resize and preserve the aspect ratio
        msg = f"Impossible to resize {img_w}x{img_h} image while preserving the aspect ratio to a size within the range ({min_size}, {max_size}). Will not limit the maximum size."
        warn(msg)
        return _calc_size(img_w, img_h, min_size, float("inf"), base)
    

# -----------------------------
# Preprocessing function
# -----------------------------
# Adjust the image transforms to match what your model expects.
def transform(image: Image.Image, dataset_name: str) -> Tensor:
    assert isinstance(image, Image.Image), "Input must be a PIL Image"
    image_tensor = TF.to_tensor(image)

    if dataset_name == "sha":
        min_size = 448
        max_size = float("inf")
    elif dataset_name == "shb":
        min_size = 448
        max_size = float("inf")
    elif dataset_name == "qnrf":
        min_size = 448
        max_size = 2048
    elif dataset_name == "nwpu":
        min_size = 448
        max_size = 3072

    image_height, image_width = image_tensor.shape[-2:]
    new_width, new_height = _calc_size(
        img_w=image_width,
        img_h=image_height,
        min_size=min_size,
        max_size=max_size,
        base=32
    )
    if new_height != image_height or new_width != image_width:
        image_tensor = TF.resize(image_tensor, size=(new_height, new_width), interpolation=TF.InterpolationMode.BICUBIC, antialias=True)

    image_tensor = TF.normalize(image_tensor, mean=mean, std=std)
    return image_tensor.unsqueeze(0)  # Add batch dimension


def _sliding_window_predict(
    model: nn.Module,
    image: Tensor,
    window_size: int,
    stride: int, 
    max_num_windows: int = 256
):
    assert len(image.shape) == 4, f"Image must be a 4D tensor (1, c, h, w), got {image.shape}"
    window_size = (int(window_size), int(window_size)) if isinstance(window_size, (int, float)) else window_size
    stride = (int(stride), int(stride)) if isinstance(stride, (int, float)) else stride
    window_size = tuple(window_size)
    stride = tuple(stride)
    assert isinstance(window_size, tuple) and len(window_size) == 2 and window_size[0] > 0 and window_size[1] > 0, f"Window size must be a positive integer tuple (h, w), got {window_size}"
    assert isinstance(stride, tuple) and len(stride) == 2 and stride[0] > 0 and stride[1] > 0, f"Stride must be a positive integer tuple (h, w), got {stride}"
    assert stride[0] <= window_size[0] and stride[1] <= window_size[1], f"Stride must be smaller than window size, got {stride} and {window_size}"

    image_height, image_width = image.shape[-2:]
    window_height, window_width = window_size
    assert image_height >= window_height and image_width >= window_width, f"Image size must be larger than window size, got image size {image.shape} and window size {window_size}"
    stride_height, stride_width = stride

    num_rows = int(np.ceil((image_height - window_height) / stride_height) + 1)
    num_cols = int(np.ceil((image_width - window_width) / stride_width) + 1)

    if hasattr(model, "block_size"):
        block_size = model.block_size
    elif hasattr(model, "module") and hasattr(model.module, "block_size"):
        block_size = model.module.block_size
    else:
        raise ValueError("Model must have block_size attribute")
    assert window_height % block_size == 0 and window_width % block_size == 0, f"Window size must be divisible by block size, got {window_size} and {block_size}"

    windows = []
    for i in range(num_rows):
        for j in range(num_cols):
            x_start, y_start = i * stride_height, j * stride_width
            x_end, y_end = x_start + window_height, y_start + window_width
            if x_end > image_height:
                x_start, x_end = image_height - window_height, image_height
            if y_end > image_width:
                y_start, y_end = image_width - window_width, image_width

            window = image[:, :, x_start:x_end, y_start:y_end]
            windows.append(window)

    windows = torch.cat(windows, dim=0).to(image.device)  # batched windows, shape: (num_windows, c, h, w)
    
    model.eval()
    pi_maps, lambda_maps = [], []
    for i in range(0, len(windows), max_num_windows):
        with torch.no_grad():
            image_feats = model.backbone(windows[i: min(i + max_num_windows, len(windows))])
            pi_image_feats, lambda_image_feats = model.pi_head(image_feats), model.lambda_head(image_feats)
            pi_image_feats = F.normalize(pi_image_feats.permute(0, 2, 3, 1), p=2, dim=-1)  # shape (B, H, W, C)
            lambda_image_feats = F.normalize(lambda_image_feats.permute(0, 2, 3, 1), p=2, dim=-1)  # shape (B, H, W, C)

            pi_text_feats, lambda_text_feats = model.pi_text_feats, model.lambda_text_feats
            pi_logit_scale, lambda_logit_scale = model.pi_logit_scale.exp(), model.lambda_logit_scale.exp()

            pi_logit_map = pi_logit_scale * pi_image_feats @ pi_text_feats.t()  # (B, H, W, 2), logits per image
            lambda_logit_map = lambda_logit_scale * lambda_image_feats @ lambda_text_feats.t()  # (B, H, W, N - 1), logits per image

            pi_logit_map =  pi_logit_map.permute(0, 3, 1, 2)  # (B, 2, H, W)
            lambda_logit_map = lambda_logit_map.permute(0, 3, 1, 2)  # (B, N - 1, H, W)

            lambda_map = (lambda_logit_map.softmax(dim=1) * model.bin_centers[:, 1:]).sum(dim=1, keepdim=True)  # (B, 1, H, W)
            pi_map = pi_logit_map.softmax(dim=1)[:, 0:1]  # (B, 1, H, W)

            pi_maps.append(pi_map.cpu().numpy())
            lambda_maps.append(lambda_map.cpu().numpy())

    # assemble the density map
    pi_maps = np.concatenate(pi_maps, axis=0)  # shape: (num_windows, 1, H, W)
    lambda_maps = np.concatenate(lambda_maps, axis=0)  # shape: (num_windows, 1, H, W)
    assert pi_maps.shape == lambda_maps.shape, f"pi_maps and lambda_maps must have the same shape, got {pi_maps.shape} and {lambda_maps.shape}"

    pi_map = np.zeros((pi_maps.shape[1], image_height // block_size, image_width // block_size), dtype=np.float32)
    lambda_map = np.zeros((lambda_maps.shape[1], image_height // block_size, image_width // block_size), dtype=np.float32)
    count_map = np.zeros((pi_maps.shape[1], image_height // block_size, image_width // block_size), dtype=np.float32)
    idx = 0
    for i in range(num_rows):
        for j in range(num_cols):
            x_start, y_start = i * stride_height, j * stride_width
            x_end, y_end = x_start + window_height, y_start + window_width
            if x_end > image_height:
                x_start, x_end = image_height - window_height, image_height
            if y_end > image_width:
                y_start, y_end = image_width - window_width, image_width

            pi_map[:, (x_start // block_size): (x_end // block_size), (y_start // block_size): (y_end // block_size)] += pi_maps[idx, :, :, :]
            lambda_map[:, (x_start // block_size): (x_end // block_size), (y_start // block_size): (y_end // block_size)] += lambda_maps[idx, :, :, :]
            count_map[:, (x_start // block_size): (x_end // block_size), (y_start // block_size): (y_end // block_size)] += 1.
            idx += 1

    # average the density map
    pi_map /= count_map
    lambda_map /= count_map
    
    # convert to Tensor and reshape
    pi_map = torch.from_numpy(pi_map).unsqueeze(0)  # shape: (1, 1, H // block_size, W // block_size)
    lambda_map = torch.from_numpy(lambda_map).unsqueeze(0)  # shape: (1, 1, H // block_size, W // block_size)
    return pi_map, lambda_map


# -----------------------------
# Inference function
# -----------------------------
@spaces.GPU(duration=120)
def predict(image: Image.Image, variant_dataset_metric: str):
    """
    Given an input image, preprocess it, run the model to obtain a density map,
    compute the total crowd count, and prepare the density map for display.
    """
    global loaded_model, current_model_config
    
    # 在GPU进程中定义device
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    
    # 如果选择的是分割线,返回错误信息
    if "━━━━━━" in variant_dataset_metric:
        return image, None, None, "⚠️ Please select a valid model configuration", None, None, None
    
    parts = variant_dataset_metric.split(" @ ")
    if len(parts) != 3:
        return image, None, None, "❌ Invalid model configuration format", None, None, None
        
    variant, dataset, metric = parts[0], parts[1], parts[2].lower()

    if dataset == "ShanghaiTech A":
        dataset_name = "sha"
    elif dataset == "ShanghaiTech B":
        dataset_name = "shb"
    elif dataset == "UCF-QNRF":
        dataset_name = "qnrf"
    elif dataset == "NWPU-Crowd":
        dataset_name = "nwpu"
    else:
        return image, None, None, f"❌ Unknown dataset: {dataset}", None, None, None

    # 在GPU进程中加载模型(如果需要)
    if (loaded_model is None or 
        current_model_config["variant"] != variant or 
        current_model_config["dataset"] != dataset_name or 
        current_model_config["metric"] != metric):
        
        print(f"Loading model in GPU process: {variant} @ {dataset} with {metric} metric")
        loaded_model = load_model(variant=variant, dataset=dataset_name, metric=metric)
        current_model_config = {"variant": variant, "dataset": dataset_name, "metric": metric}

    if not hasattr(loaded_model, "input_size"):
        if dataset_name == "sha":
            loaded_model.input_size = 224
        elif dataset_name == "shb":
            loaded_model.input_size = 448
        elif dataset_name == "qnrf":
            loaded_model.input_size = 672
        elif dataset_name == "nwpu":
            loaded_model.input_size = 672
    elif isinstance(loaded_model.input_size, (list, tuple)):
        loaded_model.input_size = loaded_model.input_size[0]  # Use the first element if it's a list or tuple
    else:
        assert isinstance(loaded_model.input_size, (int, float)), f"input_size must be an int or float, got {type(loaded_model.input_size)}"

    loaded_model.to(device)

    # Preprocess the image
    input_width, input_height = image.size
    image_tensor = transform(image, dataset_name).to(device)  # shape: (1, 3, H, W)

    input_size = loaded_model.input_size
    image_height, image_width = image_tensor.shape[-2:]
    aspect_ratio = image_width / image_height
    if image_height < input_size:
        new_height = input_size
        new_width = int(new_height * aspect_ratio)
        image_tensor = F.interpolate(image_tensor, size=(new_height, new_width), mode="bicubic", align_corners=False, antialias=True)
        image_height, image_width = new_height, new_width
    if image_width < input_size:
        new_width = input_size
        new_height = int(new_width / aspect_ratio)
        image_tensor = F.interpolate(image_tensor, size=(new_height, new_width), mode="bicubic", align_corners=False, antialias=True)
        image_height, image_width = new_height, new_width
    
    with torch.no_grad():
        if hasattr(loaded_model, "num_vpt") and loaded_model.num_vpt is not None and loaded_model.num_vpt > 0:  # For ViT models, use sliding window prediction
            # For ViT models with VPT
            pi_map, lambda_map = _sliding_window_predict(
                model=loaded_model,
                image=image_tensor,
                window_size=input_size,
                stride=input_size
            )
        
        elif hasattr(loaded_model, "pi_text_feats") and hasattr(loaded_model, "lambda_text_feats") and loaded_model.pi_text_feats is not None and loaded_model.lambda_text_feats is not None:  # For other CLIP-based models
            image_feats = loaded_model.backbone(image_tensor)
            # image_feats = F.normalize(image_feats.permute(0, 2, 3, 1), p=2, dim=-1)  # shape (B, H, W, C)
            pi_image_feats, lambda_image_feats = loaded_model.pi_head(image_feats), loaded_model.lambda_head(image_feats)
            pi_image_feats = F.normalize(pi_image_feats.permute(0, 2, 3, 1), p=2, dim=-1)  # shape (B, H, W, C)
            lambda_image_feats = F.normalize(lambda_image_feats.permute(0, 2, 3, 1), p=2, dim=-1)  # shape (B, H, W, C)

            pi_text_feats, lambda_text_feats = loaded_model.pi_text_feats, loaded_model.lambda_text_feats
            pi_logit_scale, lambda_logit_scale = loaded_model.pi_logit_scale.exp(), loaded_model.lambda_logit_scale.exp()

            pi_logit_map = pi_logit_scale * pi_image_feats @ pi_text_feats.t()  # (B, H, W, 2), logits per image
            lambda_logit_map = lambda_logit_scale * lambda_image_feats @ lambda_text_feats.t()  # (B, H, W, N - 1), logits per image

            pi_logit_map =  pi_logit_map.permute(0, 3, 1, 2)  # (B, 2, H, W)
            lambda_logit_map = lambda_logit_map.permute(0, 3, 1, 2)  # (B, N - 1, H, W)

            lambda_map = (lambda_logit_map.softmax(dim=1) * loaded_model.bin_centers[:, 1:]).sum(dim=1, keepdim=True)  # (B, 1, H, W)
            pi_map = pi_logit_map.softmax(dim=1)[:, 0:1]  # (B, 1, H, W)
        
        else: # For non-CLIP models
            x = loaded_model.backbone(image_tensor)
            logit_pi_map = loaded_model.pi_head(x)  # shape: (B, 2, H, W)
            logit_map = loaded_model.bin_head(x)  # shape: (B, C, H, W)
            lambda_map= (logit_map.softmax(dim=1) * loaded_model.bin_centers[:, 1:]).sum(dim=1, keepdim=True)  # shape: (B, 1, H, W)
            pi_map = logit_pi_map.softmax(dim=1)[:, 0:1]  # shape: (B, 1, H, W)

        
        den_map = (1.0 - pi_map) * lambda_map  # shape: (B, 1, H, W)
        count = den_map.sum().item()

        strucrual_zero_map = F.interpolate(
            pi_map, size=(input_height, input_width), mode="bilinear", align_corners=False, antialias=True
        ).cpu().squeeze().numpy()

        lambda_map = F.interpolate(
            lambda_map, size=(input_height, input_width), mode="bilinear", align_corners=False, antialias=True
        ).cpu().squeeze().numpy()

        den_map = F.interpolate(
            den_map, size=(input_height, input_width), mode="bilinear", align_corners=False, antialias=True
        ).cpu().squeeze().numpy()
    
    sampling_zero_map = (1.0 - strucrual_zero_map) * np.exp(-lambda_map)
    complete_zero_map = strucrual_zero_map + sampling_zero_map

    # Normalize maps for display purposes
    def normalize_map(x: np.ndarray) -> np.ndarray:
        """ Normalize the map to [0, 1] range for visualization. """
        x_min = np.min(x)
        x_max = np.max(x)
        if x_max - x_min < EPS:
            return np.zeros_like(x)
        return (x - x_min) / (x_max - x_min + EPS)
    
    # strucrual_zero_map = normalize_map(strucrual_zero_map)
    # sampling_zero_map = normalize_map(sampling_zero_map)
    # lambda_map = normalize_map(lambda_map)
    # den_map = normalize_map(den_map)
    # complete_zero_map = normalize_map(complete_zero_map)
    
    # Apply a colormap for better visualization
    # Options: 'viridis', 'plasma', 'hot', 'inferno', 'jet' (recommended)
    colormap = cm.get_cmap("jet")

    # The colormap returns values in [0,1]. Scale to [0,255] and convert to uint8.
    den_map = (colormap(den_map) * 255).astype(np.uint8)
    strucrual_zero_map = (colormap(strucrual_zero_map) * 255).astype(np.uint8)
    sampling_zero_map = (colormap(sampling_zero_map) * 255).astype(np.uint8)
    lambda_map = (colormap(lambda_map) * 255).astype(np.uint8)
    complete_zero_map = (colormap(complete_zero_map) * 255).astype(np.uint8)

    # Convert to PIL images
    den_map = Image.fromarray(den_map).convert("RGBA")
    strucrual_zero_map = Image.fromarray(strucrual_zero_map).convert("RGBA")
    sampling_zero_map = Image.fromarray(sampling_zero_map).convert("RGBA")
    lambda_map = Image.fromarray(lambda_map).convert("RGBA")
    complete_zero_map = Image.fromarray(complete_zero_map).convert("RGBA")
    
    # Ensure the original image is in RGBA format.
    image_rgba = image.convert("RGBA")

    den_map = Image.blend(image_rgba, den_map, alpha=alpha)
    strucrual_zero_map = Image.blend(image_rgba, strucrual_zero_map, alpha=alpha)
    sampling_zero_map = Image.blend(image_rgba, sampling_zero_map, alpha=alpha)
    lambda_map = Image.blend(image_rgba, lambda_map, alpha=alpha)
    complete_zero_map = Image.blend(image_rgba, complete_zero_map, alpha=alpha)
    
    # 格式化计数显示
    count_display = f"👥 {round(count, 2)} people detected"
    if count < 1:
        count_display = "👤 Less than 1 person detected"
    elif count == 1:
        count_display = "👤 1 person detected"
    elif count < 10:
        count_display = f"👥 {round(count, 1)} people detected"
    else:
        count_display = f"👥 {round(count)} people detected"
    
    return image, den_map, lambda_map, count_display, strucrual_zero_map, sampling_zero_map, complete_zero_map


# -----------------------------
# Build Gradio Interface using Blocks for a two-column layout
# -----------------------------
css = """
/* 分割线样式 - 灰色不可选择 */
.dropdown select option[value*="━━━━━━"] {
    color: #999 !important;
    background-color: #f0f0f0 !important;
    font-style: italic !important;
    text-align: center !important;
    pointer-events: none !important;
    cursor: not-allowed !important;
    border: none !important;
}

/* Gradio下拉菜单中的分割线样式 */
.gr-dropdown .choices__item[data-value*="━━━━━━"] {
    color: #999 !important;
    background-color: #f0f0f0 !important;
    font-style: italic !important;
    text-align: center !important;
    pointer-events: none !important;
    cursor: not-allowed !important;
    user-select: none !important;
    opacity: 0.6 !important;
}

/* 悬停时保持灰色 */
.gr-dropdown .choices__item[data-value*="━━━━━━"]:hover {
    background-color: #f0f0f0 !important;
    color: #999 !important;
    cursor: not-allowed !important;
}

/* 通用的分割线样式 */
option:disabled {
    color: #999 !important;
    background-color: #f0f0f0 !important;
    font-style: italic !important;
}

/* 为包含分割线字符的选项添加样式 */
option[value*="━━━━━━"], 
select option[value*="━━━━━━"] {
    color: #999 !important;
    background-color: #f0f0f0 !important;
    cursor: not-allowed !important;
    pointer-events: none !important;
    text-align: center !important;
    opacity: 0.6 !important;
}

/* 整体主题美化 */
.gradio-container {
    max-width: 1600px !important;
    margin: 0 auto !important;
    font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif !important;
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%) !important;
    min-height: 100vh !important;
    padding: 20px !important;
}

/* 响应式布局 - 自动调整列宽 */
@media (max-width: 1400px) {
    .gradio-container {
        max-width: 1200px !important;
        padding: 18px !important;
    }
}

@media (max-width: 1200px) {
    .gradio-container {
        max-width: 100% !important;
        padding: 16px !important;
    }
    
    /* 在中等屏幕上,将第二行改为垂直布局 */
    .gr-row:nth-of-type(2) {
        flex-direction: column !important;
    }
    
    .gr-row:nth-of-type(2) .gr-column {
        width: 100% !important;
        margin-bottom: 20px !important;
    }
    
    /* 重置中等屏幕上的组件高度 */
    .gr-row:nth-of-type(2) .gr-group,
    .gr-row:nth-of-type(3) .gr-group {
        height: auto !important;
        min-height: auto !important;
        position: static !important;
    }
    
    .gr-row:nth-of-type(3) .gr-column:first-child .gr-group {
        position: static !important;
    }
    
    .gr-row:nth-of-type(3) .gr-column:first-child .gr-button {
        position: static !important;
        bottom: auto !important;
        left: auto !important;
        right: auto !important;
        width: auto !important;
        margin-top: 16px !important;
    }
}

@media (max-width: 900px) {
    /* 在小屏幕上,将第三行也改为垂直布局 */
    .gr-row:nth-of-type(3) {
        flex-direction: column !important;
    }
    
    .gr-row:nth-of-type(3) .gr-column {
        width: 100% !important;
        margin-bottom: 20px !important;
    }
    
    /* Zero Analysis 在小屏幕上也改为垂直布局 */
    .gr-group .gr-row {
        flex-direction: column !important;
    }
    
    .gr-group .gr-row .gr-column {
        width: 100% !important;
        margin-bottom: 16px !important;
    }
    
    /* 重置小屏幕上的组件高度 */
    .gr-row:nth-of-type(2) .gr-group,
    .gr-row:nth-of-type(3) .gr-group {
        height: auto !important;
        min-height: auto !important;
        position: static !important;
    }
    
    .gr-row:nth-of-type(3) .gr-column:first-child .gr-group {
        position: static !important;
    }
    
    .gr-row:nth-of-type(3) .gr-column:first-child .gr-button {
        position: static !important;
        bottom: auto !important;
        left: auto !important;
        right: auto !important;
        width: auto !important;
        margin-top: 16px !important;
    }
}

@media (max-width: 768px) {
    .gradio-container {
        padding: 12px !important;
    }
    
    .gr-column {
        margin-bottom: 16px !important;
        padding: 0 4px !important;
    }
    
    .gr-markdown h1 {
        font-size: 2rem !important;
    }
    
    .gr-group {
        padding: 16px !important;
    }
    
    .gr-button {
        padding: 12px 24px !important;
        font-size: 1rem !important;
    }
    
    /* 图像高度在小屏幕上调整 */
    .gr-image {
        height: 300px !important;
    }
    
    .zero-analysis-image {
        height: 300px !important;
    }
    
    /* 小屏幕上重置组件高度 */
    .gr-row:nth-of-type(2) .gr-group,
    .gr-row:nth-of-type(3) .gr-group {
        height: auto !important;
        min-height: auto !important;
        position: static !important;
    }
    
    .gr-row:nth-of-type(3) .gr-column:first-child .gr-group {
        position: static !important;
    }
    
    .gr-row:nth-of-type(3) .gr-column:first-child .gr-button {
        position: static !important;
        bottom: auto !important;
        left: auto !important;
        right: auto !important;
        width: auto !important;
        margin-top: 16px !important;
    }
    
    .gr-row:nth-of-type(2) .gr-textbox,
    .gr-row:nth-of-type(2) .gr-dropdown {
        min-height: auto !important;
        max-height: none !important;
    }
    
    .gr-row:nth-of-type(3) .gr-image {
        height: 300px !important;
        min-height: auto !important;
        max-height: none !important;
        flex: none !important;
    }
}

/* 超宽屏幕优化 */
@media (min-width: 1600px) {
    .gradio-container {
        max-width: 1800px !important;
        padding: 24px !important;
    }
    
    .gr-image {
        height: 450px !important;
    }
    
    .zero-analysis-image {
        height: 450px !important;
    }
}

/* 标题样式 */
.gr-markdown h1 {
    text-align: center !important;
    color: #2563eb !important;
    font-weight: 700 !important;
    font-size: 3rem !important;
    margin-bottom: 0.5rem !important;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
    -webkit-background-clip: text !important;
    -webkit-text-fill-color: transparent !important;
    text-shadow: 0 4px 8px rgba(0,0,0,0.1) !important;
}

/* 副标题样式 */
.gr-markdown p {
    text-align: center !important;
    color: #6b7280 !important;
    font-size: 1.2rem !important;
    margin-bottom: 2rem !important;
    font-weight: 500 !important;
}

/* 主要布局组美化 */
.gr-group {
    background: rgba(255, 255, 255, 0.9) !important;
    backdrop-filter: blur(10px) !important;
    border-radius: 20px !important;
    padding: 24px !important;
    margin: 16px 0 !important;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1) !important;
    border: 1px solid rgba(255, 255, 255, 0.2) !important;
    transition: all 0.3s ease !important;
}

.gr-group:hover {
    transform: translateY(-4px) !important;
    box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15) !important;
}

/* 按钮美化 */
.gr-button {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
    border: none !important;
    border-radius: 12px !important;
    color: white !important;
    font-weight: 600 !important;
    font-size: 1.1rem !important;
    padding: 16px 32px !important;
    transition: all 0.3s ease !important;
    box-shadow: 0 6px 20px rgba(102, 126, 234, 0.3) !important;
    text-transform: uppercase !important;
    letter-spacing: 0.5px !important;
}

.gr-button:hover {
    transform: translateY(-3px) !important;
    box-shadow: 0 10px 30px rgba(102, 126, 234, 0.4) !important;
    background: linear-gradient(135deg, #5a67d8 0%, #6b46c1 100%) !important;
}

/* 输入框样式 */
.gr-textbox, .gr-dropdown {
    border-radius: 12px !important;
    border: 2px solid #e5e7eb !important;
    transition: all 0.3s ease !important;
    background: rgba(255, 255, 255, 0.8) !important;
    font-size: 1rem !important;
    padding: 12px 16px !important;
}

.gr-textbox:focus, .gr-dropdown:focus {
    border-color: #667eea !important;
    box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1) !important;
    background: rgba(255, 255, 255, 1) !important;
}

/* 图像容器美化 - 统一尺寸 */
.gr-image {
    border-radius: 16px !important;
    overflow: hidden !important;
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15) !important;
    transition: all 0.3s ease !important;
    background: white !important;
    height: 400px !important;
    width: 100% !important;
}

.gr-image:hover {
    box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2) !important;
    transform: translateY(-2px) !important;
}

/* 确保第二行组件等高 - 重新调整为三列等宽 */
.gr-row:nth-of-type(2) .gr-group {
    min-height: 180px !important;
    display: flex !important;
    flex-direction: column !important;
    justify-content: center !important;
}

.gr-row:nth-of-type(2) .gr-group > * {
    flex: 1 !important;
}

/* 确保第二行的文本框具有相同的高度 */
.gr-row:nth-of-type(2) .gr-textbox {
    min-height: 100px !important;
    max-height: 100px !important;
    display: flex !important;
    align-items: center !important;
}

/* 确保第二行下拉菜单区域等高 */
.gr-row:nth-of-type(2) .gr-dropdown {
    min-height: 80px !important;
}

/* 确保下拉框可以正常展开 */
.gr-dropdown {
    position: relative !important;
    z-index: 1000 !important;
}

.gr-dropdown .choices {
    position: absolute !important;
    z-index: 1001 !important;
    width: 100% !important;
    max-height: 300px !important;
    overflow-y: auto !important;
}

/* 确保第三行组件等高 - 重新调整高度 */
.gr-row:nth-of-type(3) .gr-group {
    height: 520px !important;
    min-height: 520px !important;
    display: flex !important;
    flex-direction: column !important;
    justify-content: flex-start !important;
}

/* 第三行的图像容器统一高度 */
.gr-row:nth-of-type(3) .gr-image {
    height: 400px !important;
    min-height: 400px !important;
    max-height: 400px !important;
    flex: 0 0 400px !important;
}

/* 第三行的按钮固定在底部 - 只对第一列(Image Input)应用 */
.gr-row:nth-of-type(3) .gr-column:first-child .gr-group {
    position: relative !important;
}

.gr-row:nth-of-type(3) .gr-column:first-child .gr-button {
    position: absolute !important;
    bottom: 24px !important;
    left: 24px !important;
    right: 24px !important;
    margin: 0 !important;
    width: calc(100% - 48px) !important;
}

/* 列间距优化 */
.gr-column {
    padding: 0 8px !important;
    margin-bottom: 16px !important;
}

/* 第二行特殊布局调整 - 移除,现在是三列等宽 */
.gr-row:nth-of-type(2) .gr-column {
    padding: 0 8px !important;
}

/* 标签美化 */
.gr-label {
    font-weight: 700 !important;
    color: #374151 !important;
    margin-bottom: 12px !important;
    font-size: 1.1rem !important;
    text-transform: uppercase !important;
    letter-spacing: 0.5px !important;
}

/* 模型状态框特殊样式 */
.gr-textbox[data-testid*="model-status"] {
    background: linear-gradient(135deg, #ecfdf5 0%, #d1fae5 100%) !important;
    font-family: 'Monaco', 'Menlo', monospace !important;
    font-size: 0.95rem !important;
    font-weight: 600 !important;
    border: 2px solid #10b981 !important;
}

/* Zero Analysis 特殊布局 */
.gr-row:has(.gr-image[label*="Zero"]) {
    background: linear-gradient(135deg, rgba(255,255,255,0.95) 0%, rgba(248,250,252,0.95) 100%) !important;
    border-radius: 20px !important;
    padding: 24px !important;
    margin: 20px 0 !important;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1) !important;
}

/* Zero Analysis 图像特殊样式 - 统一尺寸 */
.zero-analysis-image {
    border: 3px solid transparent !important;
    background: linear-gradient(white, white) padding-box, 
                linear-gradient(135deg, #667eea, #764ba2) border-box !important;
    border-radius: 16px !important;
    transition: all 0.3s ease !important;
    height: 400px !important;
    width: 100% !important;
}

.zero-analysis-image:hover {
    transform: scale(1.02) !important;
    box-shadow: 0 12px 35px rgba(102, 126, 234, 0.2) !important;
}

/* 确保所有行的组件等高 */
.gr-row .gr-group {
    min-height: 100% !important;
    display: flex !important;
    flex-direction: column !important;
}

.gr-row .gr-column {
    height: 100% !important;
}

/* 第二行内部子行等高处理 - 移除,现在不需要内部子行 */

/* 统计信息卡片美化 */
.gr-textbox[label*="Count"] {
    background: linear-gradient(135deg, #ecfcff 0%, #cffafe 100%) !important;
    border: 2px solid #06b6d4 !important;
    font-size: 1.2rem !important;
    font-weight: 700 !important;
    text-align: center !important;
    color: #0e7490 !important;
}

/* 示例区域美化 */
.gr-examples {
    background: linear-gradient(135deg, rgba(255,255,255,0.9) 0%, rgba(248,250,252,0.9) 100%) !important;
    backdrop-filter: blur(10px) !important;
    border-radius: 20px !important;
    padding: 30px !important;
    margin-top: 30px !important;
    border: 1px solid rgba(255, 255, 255, 0.2) !important;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1) !important;
}

/* Accordion 美化 */
.gr-accordion {
    background: rgba(255, 255, 255, 0.8) !important;
    border-radius: 16px !important;
    margin: 16px 0 !important;
    border: 1px solid rgba(255, 255, 255, 0.2) !important;
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.08) !important;
}

/* 响应式设计 - 移除旧的媒体查询,已在上方重新定义 */

/* 加载动画 */
@keyframes pulse {
    0%, 100% { opacity: 1; }
    50% { opacity: 0.5; }
}

.gr-loading .gr-image {
    animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite !important;
}

/* 成功状态指示 */
.status-success {
    color: #059669 !important;
    background-color: #d1fae5 !important;
    border: 1px solid #a7f3d0 !important;
}

/* 错误状态指示 */
.status-error {
    color: #dc2626 !important;
    background-color: #fee2e2 !important;
    border: 1px solid #fecaca !important;
}
"""

with gr.Blocks(css=css, theme=gr.themes.Soft(), title="ZIP Crowd Counting") as demo:
    gr.Markdown("""
    # 🎯 Crowd Counting by ZIP
    ### Upload an image and get precise crowd density predictions with ZIP models!
    """)
    
    # 添加信息面板
    with gr.Accordion("ℹ️ About ZIP", open=False):
        gr.Markdown("""
        **ZIP (Zero-Inflated Poisson)** is a framework designed for crowd counting, a task where the goal is to estimate how many people are present in an image. It was introduced in the paper [ZIP: Scalable Crowd Counting via Zero-Inflated Poisson Modeling](https://arxiv.org/abs/2506.19955).
        ZIP is based on a simple idea: not all empty areas in an image mean the same thing. Some regions are empty because there are truly no people there (like walls or sky), while others are places where people could appear but just happen not to in this particular image. ZIP separates these two cases using two prediction heads:
        - **Structural Zeros**: These are regions that naturally never contain people (e.g., the background or torso areas). These are handled by the π head.
        - **Sampling Zeros**: These are regions where people could appear but don't in this image. These are modeled by the λ head.
        
        By separating *where* people are likely to be from *how many* are present, ZIP produces more accurate and interpretable crowd estimates, especially in scenes with large empty spaces or varied crowd densities.
        
        Choose from different model variants: **ZIP-B** (Base), **ZIP-S** (Small), **ZIP-T** (Tiny), **ZIP-N** (Nano), **ZIP-P** (Pico)
        """)

    # 第二行:模型配置、状态和预测结果(三列等宽)
    with gr.Row():
        with gr.Column(scale=1):
            with gr.Group():
                model_dropdown = gr.Dropdown(
                    choices=pretrained_models,
                    value="ZIP-B @ NWPU-Crowd @ MAE",
                    label="🎛️ Select Model & Dataset",
                    info="Choose model variant, dataset, and evaluation metric"
                )
        
        with gr.Column(scale=1):
            with gr.Group():
                model_status = gr.Textbox(
                    label="📊 Model Status",
                    value="🔄 No model loaded",
                    interactive=False,
                    elem_classes=["status-display"],
                    lines=3
                )
        
        with gr.Column(scale=1):
            with gr.Group():
                output_text = gr.Textbox(
                    label="🧙 Predicted Count",
                    value="",
                    interactive=False,
                    info="Total number of people detected",
                    lines=3
                )

    # 第三行:主要图像(输入图像、密度图、Lambda图)
    with gr.Row():
        with gr.Column(scale=1):
            with gr.Group():
                input_img = gr.Image(
                    label="📸 Upload Image", 
                    sources=["upload", "clipboard"], 
                    type="pil",
                    height=400
                )
                submit_btn = gr.Button(
                    "🚀 Analyze Crowd", 
                    variant="primary",
                    size="lg"
                )
        
        with gr.Column(scale=1):
            with gr.Group():
                output_den_map = gr.Image(
                    label="🎯 Predicted Density Map", 
                    type="pil", 
                    height=400
                )
        
        with gr.Column(scale=1):
            with gr.Group():
                output_lambda_map = gr.Image(
                    label="📈 Lambda Map", 
                    type="pil", 
                    height=400
                )
    
    # 第四行:Zero Analysis - 全宽,内部三列等宽
    with gr.Group():
        gr.Markdown("### 🔍 Zero Analysis")
        gr.Markdown("*Explore different types of zero predictions in crowd analysis*")
        with gr.Row():
            with gr.Column(scale=1):
                output_structural_zero_map = gr.Image(
                    label="🏗️ Structural Zero Map", 
                    type="pil", 
                    height=400,
                    elem_classes=["zero-analysis-image"]
                )
            
            with gr.Column(scale=1):
                output_sampling_zero_map = gr.Image(
                    label="📊 Sampling Zero Map", 
                    type="pil", 
                    height=400,
                    elem_classes=["zero-analysis-image"]
                )
            
            with gr.Column(scale=1):
                output_complete_zero_map = gr.Image(
                    label="👺 Complete Zero Map", 
                    type="pil", 
                    height=400,
                    elem_classes=["zero-analysis-image"]
                )

    # 当模型变化时,自动更新模型
    def on_model_change(variant_dataset_metric):
        # 如果选择的是分割线,保持当前选择不变
        if "━━━━━━" in variant_dataset_metric:
            return "⚠️ Please select a valid model configuration"
        result = update_model_if_needed(variant_dataset_metric)
        if "Model loaded:" in result:
            return f"✅ {result}"
        elif "Model already loaded:" in result:
            return f"🔄 {result}"
        else:
            return f"❌ {result}"
    
    model_dropdown.change(
        fn=on_model_change,
        inputs=[model_dropdown],
        outputs=[model_status]
    )

    # 页面加载时设置默认模型配置(不在主进程中加载模型)
    demo.load(
        fn=lambda: f"✅ {update_model_if_needed('ZIP-B @ NWPU-Crowd @ MAE')}",
        outputs=[model_status]
    )

    submit_btn.click(
        fn=predict,
        inputs=[input_img, model_dropdown],
        outputs=[input_img, output_den_map, output_lambda_map, output_text, output_structural_zero_map, output_sampling_zero_map, output_complete_zero_map]
    )

    # 美化示例区域
    with gr.Accordion("🖼️ Try Example Images", open=True):
        gr.Markdown("**Click on any example below to test the model:**")
        gr.Examples(
            examples=[
                ["example1.jpg"], ["example2.jpg"], ["example3.jpg"], ["example4.jpg"],
                ["example5.jpg"], ["example6.jpg"], ["example7.jpg"], ["example8.jpg"],
                ["example9.jpg"], ["example10.jpg"], ["example11.jpg"], ["example12.jpg"]
            ],
            inputs=input_img,
            label="📚 Example Gallery",
            examples_per_page=12
        )
    
    # 添加使用说明
    with gr.Accordion("📖 How to Use", open=False):
        gr.Markdown("""
        ### Step-by-step Guide:
        
        1. **🎛️ Select Model**: Choose your preferred model variant, pre-trained dataset, and evaluation metric from the dropdown
        2. **📸 Upload Image**: Click the image area to upload your crowd photo or use clipboard
        3. **🚀 Analyze**: Click the "Analyze Crowd" button to start processing
        4. **📊 View Results**: Examine the density maps and crowd count in the output panels
        
        ### Understanding the Outputs:
        
        **📊 Main Results:**
        - **🎯 Density Map**: Shows where people are located with color intensity, modeled by (1-π) * λ
        - **🧙 Predicted Count**: Total number of people detected in the image
        
        **🔍 Zero Analysis:**
        - **🏗️ Structural Zero Map**: Indicates regions that structurally cannot contain head annotations (e.g., walls, sky, torso, or background). These are governed by the π head, which estimates the probability that a region never contains people.
        - **📊 Sampling Zero Map**: Shows areas where people could be present but happen not to appear in the current image. These zeros are modeled by (1-π) * exp(-λ), where the expected count λ is near zero.
        - **👺 Complete Zero Map**: A combined visualization of zero probabilities, capturing both structural and sampling zeros. This map reflects overall non-crowd likelihood per region.
        
        **🔥 Hotspots:**
        - **📈 Lambda Map**: Highlights areas with high expected crowd density. Each value represents the expected number of people in that region, modeled by the Poisson intensity (λ). This map focuses on *how many* people are likely to be present, **WITHOUT** assuming people could appear there. ⚠️ Lambda Map **NEEDS** to be combined with Structural Zero Map by (1-π) * λ to produce the final density map.
        """)
    
    # 添加技术信息
    with gr.Accordion("🔬 Technical Details", open=False):
        gr.Markdown("""
        ### Model Variants:
        - **ZIP-B**: Base model with best performance
        - **ZIP-S**: Small model for faster inference
        - **ZIP-T**: Tiny model for resource-constrained environments
        - **ZIP-N**: Nano model for mobile applications
        - **ZIP-P**: Pico model for edge devices
        
        ### Datasets:
        - **ShanghaiTech A**: Dense, low-resolution crowd scenes
        - **ShanghaiTech B**: Sparse, high-resolution crowd scenes
        - **UCF-QNRF**: Dense, ultra high-resolution crowd images
        - **NWPU-Crowd**: Largest ultra high-resolution crowd counting dataset
        
        ### Metrics:
        - **MAE**: Mean Absolute Error - average counting error
        - **NAE**: Normalized Absolute Error - relative counting error
        """)

demo.launch(
    server_name="0.0.0.0",
    server_port=7860,
    show_api=False,
    share=False
)