File size: 64,656 Bytes
754a044
 
 
dedc13e
 
 
 
 
754a044
dedc13e
7d6b3a1
dedc13e
7d6b3a1
754a044
dedc13e
 
5720515
7d6b3a1
 
5720515
dedc13e
084a06d
660ea47
7d6b3a1
 
660ea47
754a044
 
 
8a79338
084a06d
7d6b3a1
 
 
 
5720515
 
 
 
7d6b3a1
084a06d
 
7d6b3a1
 
ef0676d
 
 
 
fb726ba
 
 
 
 
 
 
 
 
 
 
 
 
 
ef0676d
 
fb726ba
 
 
 
 
 
 
 
 
 
 
 
ef0676d
 
fb726ba
 
 
 
 
 
 
 
 
 
 
 
ef0676d
fb726ba
 
 
 
 
ef0676d
fb726ba
 
 
 
ef0676d
fb726ba
 
 
 
 
 
 
 
ef0676d
084a06d
 
63b1db5
e16fb8e
 
fb726ba
 
 
 
 
 
 
 
 
 
 
93597eb
 
 
 
 
 
 
 
 
0397a11
 
 
 
 
 
 
 
 
 
7d6b3a1
 
e16fb8e
 
 
 
 
 
 
 
 
7d6b3a1
e16fb8e
 
 
084a06d
 
ef0676d
 
 
 
 
 
7d6b3a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63b1db5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7d6b3a1
 
63b1db5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7d6b3a1
 
e16fb8e
 
 
 
 
bbc4023
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef0676d
93597eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef0676d
 
 
93597eb
 
 
 
 
 
 
 
ef0676d
 
0397a11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
754a044
 
 
 
 
 
 
 
 
 
 
 
8a79338
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
084a06d
 
 
660ea47
 
 
7d6b3a1
fb726ba
 
 
5d43dac
 
7d6b3a1
fb726ba
7d6b3a1
 
fb726ba
 
7d6b3a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
660ea47
 
c92a343
 
0397a11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dedc13e
 
7d6b3a1
 
 
 
 
 
 
 
 
 
 
 
dedc13e
 
 
660ea47
 
 
 
dedc13e
7d6b3a1
 
dedc13e
660ea47
 
084a06d
 
660ea47
754a044
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23f4d50
754a044
23f4d50
754a044
 
 
 
 
 
23f4d50
 
 
 
 
 
754a044
 
 
 
23f4d50
 
 
 
754a044
 
 
 
 
 
 
 
 
 
 
 
 
 
23f4d50
 
 
 
 
 
 
 
754a044
 
23f4d50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
754a044
23f4d50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
754a044
 
23f4d50
 
754a044
 
23f4d50
754a044
23f4d50
 
754a044
 
23f4d50
 
 
754a044
23f4d50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
754a044
 
23f4d50
 
754a044
86f68b6
 
7d6b3a1
 
 
 
 
660ea47
 
084a06d
660ea47
 
 
 
 
084a06d
660ea47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
084a06d
660ea47
 
084a06d
660ea47
 
 
 
 
084a06d
 
660ea47
 
5720515
 
 
 
660ea47
5720515
 
7d6b3a1
 
 
 
5720515
7d6b3a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
660ea47
7d6b3a1
 
 
 
660ea47
 
7d6b3a1
 
660ea47
7d6b3a1
 
 
 
 
 
 
 
 
660ea47
7d6b3a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
660ea47
8a79338
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
660ea47
084a06d
 
 
660ea47
754a044
 
 
 
 
 
 
 
 
0397a11
754a044
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0397a11
754a044
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c92a343
 
754a044
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
660ea47
 
 
 
7d6b3a1
 
 
5720515
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7d6b3a1
5720515
084a06d
7d6b3a1
 
 
 
 
 
 
 
 
 
 
 
660ea47
 
65245d5
084a06d
dedc13e
084a06d
5720515
dedc13e
5720515
 
 
 
 
 
 
084a06d
65245d5
5720515
 
 
 
 
 
 
 
 
 
 
084a06d
65245d5
5720515
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dedc13e
084a06d
 
660ea47
5720515
660ea47
084a06d
dedc13e
754a044
 
 
 
 
 
660ea47
 
 
 
 
084a06d
660ea47
084a06d
660ea47
7d6b3a1
 
 
 
 
 
 
 
 
 
 
 
 
 
dedc13e
660ea47
 
754a044
7d6b3a1
 
 
 
 
 
fb726ba
dedc13e
660ea47
084a06d
660ea47
7d6b3a1
 
 
 
 
dedc13e
084a06d
 
 
 
 
660ea47
7d6b3a1
 
 
 
c92a343
 
 
754a044
 
 
 
 
 
 
dedc13e
 
084a06d
7d6b3a1
 
 
 
 
 
 
 
 
 
 
 
 
 
dedc13e
754a044
7d6b3a1
754a044
 
 
 
7d6b3a1
754a044
 
7d6b3a1
660ea47
754a044
 
 
 
 
 
 
 
c92a343
 
 
754a044
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0397a11
754a044
 
 
 
 
 
 
 
 
 
dedc13e
 
 
 
7d6b3a1
 
 
 
 
 
 
 
 
 
 
 
dedc13e
 
 
 
 
084a06d
 
dedc13e
660ea47
084a06d
7d6b3a1
660ea47
 
dedc13e
 
7d6b3a1
 
 
fb726ba
93597eb
dedc13e
 
3e63e5c
 
 
 
 
66454c2
3e63e5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7d6b3a1
660ea47
7d6b3a1
754a044
 
fb726ba
7d6b3a1
084a06d
dedc13e
660ea47
 
dedc13e
7d6b3a1
084a06d
7d6b3a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dedc13e
7d6b3a1
 
dedc13e
084a06d
 
93597eb
7d6b3a1
 
 
 
93597eb
7d6b3a1
 
 
 
 
 
 
 
 
 
 
 
 
 
66454c2
754a044
66454c2
c92a343
66454c2
c92a343
 
7d6b3a1
 
 
 
1d9c995
66454c2
7668ed6
3e63e5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7d6b3a1
 
 
 
 
 
 
 
 
3e63e5c
 
 
 
 
 
 
7d6b3a1
 
 
 
3e63e5c
 
 
 
 
7d6b3a1
 
 
754a044
 
7d6b3a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e63e5c
 
 
 
 
 
7d6b3a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e63e5c
7d6b3a1
 
 
754a044
 
7d6b3a1
 
 
 
 
 
 
 
 
 
754a044
 
7d6b3a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
084a06d
 
c92a343
dedc13e
8a79338
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dedc13e
084a06d
93597eb
 
 
0397a11
c92a343
754a044
 
0397a11
dedc13e
 
084a06d
dedc13e
084a06d
e16fb8e
3e63e5c
ef0676d
3e63e5c
084a06d
 
93597eb
dedc13e
3e63e5c
 
 
 
 
 
 
 
7d6b3a1
3e63e5c
 
e16fb8e
3e63e5c
 
 
 
 
 
e16fb8e
3e63e5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e16fb8e
 
3e63e5c
 
 
 
7d6b3a1
084a06d
dedc13e
084a06d
754a044
 
 
c92a343
754a044
 
 
 
 
 
c92a343
 
754a044
dedc13e
8a79338
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
084a06d
dedc13e
754a044
 
7d6b3a1
754a044
 
 
7d6b3a1
754a044
 
 
 
 
 
7d6b3a1
c92a343
 
dedc13e
754a044
 
dedc13e
 
93597eb
 
084a06d
 
7d6b3a1
c92a343
 
93597eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dedc13e
 
084a06d
dedc13e
3e63e5c
7d6b3a1
 
7668ed6
 
 
 
 
3e63e5c
 
 
 
 
 
 
 
 
 
 
 
 
7d6b3a1
c92a343
 
dedc13e
 
7d6b3a1
 
3e63e5c
66454c2
 
 
3e63e5c
 
 
 
 
 
 
7d6b3a1
 
 
 
 
 
 
 
 
 
 
c92a343
 
7d6b3a1
 
 
 
 
 
 
c92a343
 
7d6b3a1
 
 
 
 
c92a343
 
7d6b3a1
 
 
 
 
c92a343
 
7d6b3a1
 
 
 
 
c92a343
 
7d6b3a1
 
 
 
 
c92a343
 
7d6b3a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c92a343
 
7d6b3a1
 
dedc13e
afa1a9b
 
 
 
 
309c392
 
1d9c995
afa1a9b
309c392
1d9c995
 
 
8a79338
1d9c995
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
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
import os
os.environ["GRADIO_ANALYTICS_ENABLED"] = "False"

import gradio as gr
import cv2
import random
import time
import csv
import json
import uuid
import shutil
from datetime import datetime
from functools import partial
from urllib import parse, request as urlrequest

# --- Configuration ---
DATASET_FOLDER = "./dataset"
PART1_CSV_FILE = "emotion_responses_part1.csv"
PART2_CSV_FILE = "emotion_responses_part2.csv"
METADATA_FILE = os.path.join(DATASET_FOLDER, "stimuli_metadata.csv")

# --- Advanced Features Config ---
URL_PARAM_PARTICIPANT_ID = "pid"
# Keep emotion order fixed across all participants.
RANDOMIZE_EMOTION_ORDER_DEFAULT = False
RANDOMIZE_EMOTION_ORDER_PARAM = "randomize"
TURNSTILE_SITE_KEY_ENV = "TURNSTILE_SITE_KEY"
TURNSTILE_SECRET_KEY_ENV = "TURNSTILE_SECRET_KEY"
TURNSTILE_VERIFY_URL = "https://challenges.cloudflare.com/turnstile/v0/siteverify"
DOWNLOAD_PASSWORD_ENV = "CSV_DOWNLOAD_PASSWORD"

# --- Sampling Config ---
BALANCE_SUBSET_DEFAULT = True
MAX_PER_STRATUM = None  # Optionally set to an int to cap trials per (type, emotion)
ALLOWED_ANGLES = {"forward"}  # Restrict to front-facing stimuli.
FACE_CROP_TARGET_RATIO = 0.5  # Keep detected faces at a similar scale within the square crop.
FACE_CROP_Y_BIAS = 0.08  # Shift the crop slightly upward to keep more forehead than torso.
EYE_DISTANCE_TARGET_RATIO = 0.3  # Prefer a stable eye-to-frame width ratio when eyes are detected.
EYE_LINE_POSITION_RATIO = 0.40  # Place the detected eye line around 40%% down from the top of the crop.

# --- CSS STYLES ---
APP_CSS = f"""
#start_btn > button, 
#next_btn > button {{
  font-size: 20px !important;
  padding: 12px 22px !important;
  min-height: 48px !important;
}}
#emotion_choice {{
  max-width: 760px;
  margin: 0 auto;
  background: transparent !important;
  border: none !important;
  box-shadow: none !important;
}}
#emotion_choice > div,
#emotion_choice fieldset,
#emotion_choice .form {{
  background: transparent !important;
  border: none !important;
  box-shadow: none !important;
  padding: 0 !important;
}}
#emotion_choice .wrap {{
  display: grid !important;
  grid-template-columns: repeat(2, minmax(220px, 1fr));
  gap: 18px !important;
  width: 100%;
  background: transparent !important;
}}
#emotion_choice input[type="radio"] {{
  position: absolute;
  opacity: 0;
  pointer-events: none;
}}
#emotion_choice .wrap label {{
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  width: 100% !important;
  min-height: 120px !important;
  margin: 0 !important;
  padding: 20px !important;
  border: 2px solid #4b5563 !important;
  border-radius: 22px !important;
  background: #6b7280 !important;
  color: #ffffff !important;
  box-sizing: border-box;
  cursor: pointer;
  transition: transform 0.15s ease, border-color 0.15s ease, background 0.15s ease, box-shadow 0.15s ease;
}}
#emotion_choice .wrap label:hover {{
  transform: translateY(-1px);
  border-color: #374151 !important;
  background: #5b6472 !important;
  box-shadow: 0 8px 20px rgba(31, 41, 55, 0.22);
}}
#emotion_choice .wrap label:has(input[type="radio"]:checked) {{
  background: #374151 !important;
  border-color: #111827 !important;
  box-shadow: 0 10px 24px rgba(17, 24, 39, 0.28);
}}
#emotion_choice .wrap span {{
  display: block;
  width: 100%;
  text-align: center;
  font-size: 34px !important;
  font-weight: 700 !important;
  line-height: 1.1;
  color: #ffffff !important;
}}

@media (max-width: 640px) {{
  #img_anim {{
    width: min(92vw, 360px) !important;
  }}
  #emotion_choice .wrap {{
    grid-template-columns: repeat(2, minmax(140px, 1fr));
    gap: 12px !important;
  }}
  #emotion_choice .wrap label {{
    min-height: 96px !important;
    padding: 16px !important;
  }}
  #emotion_choice .wrap span {{
    font-size: 26px !important;
  }}
  #app_title h1 {{
    font-size: 24px !important;
  }}
  #instructions_heading h1 {{
    font-size: 28px !important;
  }}
  #instructions_heading h2 {{
    font-size: 18px !important;
  }}
  #study_consent {{
    padding: 18px 16px;
    border-radius: 16px;
  }}
  #study_consent h2 {{
    font-size: 24px !important;
  }}
  #study_consent p {{
    font-size: 15px !important;
  }}
}}

#img_anim,
#part2_image {{
  width: min(100%, 420px);
  margin: 0 auto;
}}

#img_anim img,
#part2_image img {{
  display: block;
  width: 100%;
  height: auto !important;
  aspect-ratio: 1 / 1;
  object-fit: cover;
}}

#progress_text {{
  font-size: 36px;
  text-align: center;
  line-height: 1.2;
}}

#part2_section {{
  padding: 16px 20px;
  box-sizing: border-box;
}}

#part2_section h1,
#part2_section h2 {{
  font-size: 44px !important;
}}

#part2_instructions_section {{
  text-align: center;
}}

#part2_instructions_section h1 {{
  font-size: 64px !important;
  margin-bottom: 8px !important;
}}

#part2_instructions_section h2 {{
  font-size: 28px !important;
}}

#part2_start_btn > button {{
  font-size: 22px !important;
  padding: 12px 26px !important;
}}

#part2_completion_text {{
  text-align: center;
}}

#part2_completion_text h1 {{
  font-size: 140px !important;
  margin: 0 !important;
  line-height: 1 !important;
}}

#part2_completion_text h2 {{
  font-size: 48px !important;
  margin-top: 8px !important;
}}

#part2_section input[type="number"] {{
  font-size: 30px !important;
  font-weight: 700 !important;
}}

#part2_section label,
#part2_section .wrap label,
#part2_section .wrap span {{
  font-size: 20px !important;
}}

#part2_section .wrap {{
  display: flex !important;
  flex-direction: row !important;
  flex-wrap: wrap !important;
  gap: 8px 12px;
}}

#part2_section .wrap label {{
  display: inline-flex !important;
  align-items: center !important;
  justify-content: center !important;
  min-width: 56px;
  min-height: 56px !important;
  padding: 0 !important;
  border: 1px solid #64748b !important;
  border-radius: 14px !important;
  background: #5b6472 !important;
  color: #ffffff !important;
  box-sizing: border-box;
  transition: background 0.15s ease, border-color 0.15s ease, transform 0.15s ease, box-shadow 0.15s ease;
}}

#part2_section .wrap label:hover {{
  background: #4b5563 !important;
  border-color: #334155 !important;
  transform: translateY(-1px);
  box-shadow: 0 8px 18px rgba(15, 23, 42, 0.18);
}}

#part2_section .wrap label.selected {{
  background: #1f2937 !important;
  border-color: #0f172a !important;
  box-shadow: 0 10px 20px rgba(15, 23, 42, 0.26);
}}

#part2_section .wrap label > input[type="radio"] {{
  display: none !important;
}}

#part2_section .wrap label > span {{
  margin-left: 0 !important;
  width: 100%;
  text-align: center;
  font-weight: 700;
  line-height: 1;
}}

#part2_artifact_radio [data-testid="block-info"] {{
  white-space: pre-line;
  max-width: 100%;
}}

@media (max-width: 640px) {{
  #part2_image {{
    width: min(78vw, 320px) !important;
  }}
  #part2_section .wrap {{
    display: grid !important;
    grid-template-columns: repeat(4, minmax(0, 1fr));
    gap: 8px !important;
    justify-content: stretch;
  }}
  #part2_section .wrap label {{
    width: 100% !important;
    min-width: 0 !important;
    min-height: 52px !important;
    padding: 0 !important;
    font-size: 15px !important;
    white-space: nowrap;
  }}
  #part2_section .wrap label > span {{
    font-size: 15px !important;
  }}
  #part2_section h1 {{
    font-size: 32px !important;
    line-height: 1.05 !important;
  }}
  #part2_section h2 {{
    font-size: 18px !important;
  }}
}}

#app_title {{
  margin: 0 0 6px 0 !important;
  padding: 0 !important;
  text-align: center;
  overflow: visible !important;
}}

#app_title > div {{
  overflow: visible !important;
}}

#app_title h1 {{
  margin: 0 !important;
  font-size: 28px !important;
  font-weight: 700 !important;
  line-height: 1.1 !important;
}}

#instructions_section {{
  max-width: 760px;
  margin: 0 auto;
}}

#instructions_heading {{
  text-align: center;
}}

#instructions_heading h1 {{
  font-size: 40px !important;
  margin: 0 0 8px !important;
}}

#instructions_heading h2 {{
  font-size: 24px !important;
  margin: 0 !important;
}}

#study_consent {{
  max-width: 760px;
  margin: 20px auto 0 auto;
  padding: 24px 28px;
  border: 1px solid #d1d5db;
  border-radius: 20px;
  background: #f8fafc;
  box-shadow: 0 12px 30px rgba(15, 23, 42, 0.08);
}}

#study_consent h2 {{
  margin-top: 0 !important;
  margin-bottom: 16px !important;
  font-size: 30px !important;
  color: #0f172a !important;
}}

#study_consent p {{
  margin: 0 0 14px 0 !important;
  line-height: 1.6 !important;
  font-size: 16px !important;
  color: #0f172a !important;
}}

#study_consent strong {{
  color: #0f172a !important;
}}

#study_consent a {{
  color: #1d4ed8 !important;
  text-decoration: underline !important;
}}

#study_consent a:hover {{
  color: #1e40af !important;
}}

#human_check_wrap {{
  margin-top: 16px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}}

#human_check_wrap .cf-turnstile {{
  margin: 0 auto;
}}

#download_sidebar {{
  border-left: 1px solid #d1d5db;
}}

#download_sidebar h2 {{
  margin-top: 0 !important;
}}

#unlock_downloads_btn > button {{
  width: 100%;
}}

#download_status {{
  min-height: 24px;
}}

"""

# --- Constants & Mappings ---
UNKNOWN_LABEL = "unknown"
FILENAME_FIELD_ORDER = ["emotion"]

# Fixed emotion set and order for all trials.
EMOTION_CHOICES = [
    ("Happy", "happy"),
    ("Sad", "sad"),
    ("Angry", "anger"),
    ("Afraid", "fear"),
]
EMOTION_CHOICES_ORDER = [value for _, value in EMOTION_CHOICES]
ALLOWED_EMOTIONS = set(EMOTION_CHOICES_ORDER)
EMOTION_ALIASES = {
    "afraid": "fear",
    "fearful": "fear",
}

# --- Stimulus Types ---
STIMULUS_TYPE_REAL = "real_kdef"
STIMULUS_TYPE_AI = "ai_kdef_like"

# --- Ratings Config (Part 2) ---
RATING_SCALE_MIN = 1
RATING_SCALE_MAX = 7
SCALE_CHOICES = list(range(RATING_SCALE_MIN, RATING_SCALE_MAX + 1))

# --- Part 2 Rating Keys ---
PART2_KEYS = ["age", "masc", "attr", "quality", "artifact"]

# Part-specific outputs: one row per image per part, with minimal metadata.
PART1_HEADERS = [
    "participant_id",
    "session_id",
    "stimulus_id",
    "stimulus_type",
    "target_emotion",
    "emotion_trial_index",
    "emotion_rt_ms",
    "selected_emotion",
    "accuracy",
    "emotion_timestamp",
]

PART2_HEADERS = [
    "participant_id",
    "session_id",
    "stimulus_id",
    "stimulus_type",
    "target_emotion",
    "matching_trial_index",
    "match_age_rating",
    "match_masc_rating",
    "match_attr_rating",
    "match_quality_rating",
    "match_artifact_rating",
    "matching_timestamp",
]

VERIFIED_SESSION_IDS = set()

STUDY_CONSENT_MARKDOWN = """
## Thank you for participating in the study!

**Purpose of the Study:** You are invited to participate in a research study investigating face perception. Your honest responses to each question are extremely valuable and help us understand how people process images of human faces. All adults (at least 18 years of age) are eligible to participate, regardless of background.

**Procedures:** If you choose to participate, you will answer multiple-choice questions about different faces. This study is expected to take approximately 10 minutes to complete.

**Potential Risks and Benefits:** It is unlikely that you will experience any risks or discomfort beyond what you would experience in everyday life by participating. There are no specific benefits associated with participating.

**Confidentiality:** The data collected in this study is completely anonymous. No personally identifiable information will be collected, and the information you choose to provide in this study cannot be connected back to you. Survey data (numerical data arrays) will be made available in publications, but without information that could identify participants. Uppsala University is responsible for the secure storage and handling of personal data on a locally secured computer. Data will be saved for 10 years. Your answers and results will be processed to prevent unauthorized access.

**Voluntary Participation:** Your participation in this study is voluntary, and you may choose to end your participation at any time. If you decide not to participate or wish to end your participation, you do not need to state why, and it will not affect your future care or treatment.

**Project Results:** Information about the results of the study will be published in academic peer-reviewed journals and linked on the department's website, [https://www.uu.se/en/department/game-design/research/games--society-lab](https://www.uu.se/en/department/game-design/research/games--society-lab)

**Ethical Approval:** The methods and protocol of the study are conducted in accordance with the standards specified in the 1964 Declaration of Helsinki and approved by the local ethics committee, The Swedish Ethical Review Authority.

By clicking **Next**, you acknowledge that you have read and understood the information provided above and voluntarily agree to participate in this study. Thank you for your participation!
"""

# --- Data Structure ---
class ImageData:
    def __init__(
        self,
        path,
        source,
        emotion,
        sex=UNKNOWN_LABEL,
        ethnicity=UNKNOWN_LABEL,
        angle=UNKNOWN_LABEL,
        face_type=UNKNOWN_LABEL,
        stimulus_type=UNKNOWN_LABEL,
        stimulus_id="",
    ):
        self.path = path
        self.source = source
        self.emotion = emotion
        self.sex = sex
        self.ethnicity = ethnicity
        self.angle = angle
        self.face_type = face_type
        self.name = os.path.basename(path)
        self.stimulus_id = stimulus_id or os.path.splitext(self.name)[0].strip().lower()
        self.stimulus_type = stimulus_type or UNKNOWN_LABEL

# --- Helper Functions ---
def normalize_label(value):
    if value is None: return ""
    return str(value).strip().lower().replace(" ", "-")

def turnstile_site_key():
    return os.getenv(TURNSTILE_SITE_KEY_ENV, "").strip()

def turnstile_secret_key():
    return os.getenv(TURNSTILE_SECRET_KEY_ENV, "").strip()

def turnstile_is_enabled():
    return bool(turnstile_site_key() and turnstile_secret_key())

def turnstile_is_partially_configured():
    return bool(turnstile_site_key()) ^ bool(turnstile_secret_key())

def render_turnstile_widget():
    if not turnstile_is_enabled():
        return ""
    return """
<div id="human_check_wrap">
  <div id="turnstile_widget"></div>
</div>
"""

TURNSTILE_HEAD = """
<script>
(() => {
  const siteKey = %s;
  let turnstileWidgetId = null;
  let renderedNode = null;
  let observer = null;
  let renderScheduled = false;

  function getTurnstileInput() {
    return document.querySelector("#turnstile_token textarea, #turnstile_token input");
  }

  function getTurnstileMount() {
    return document.querySelector("#turnstile_widget");
  }

  function dispatchTurnstileValue(value) {
    const input = getTurnstileInput();
    if (!input) return;
    input.value = value || "";
    input.dispatchEvent(new Event("input", { bubbles: true }));
    input.dispatchEvent(new Event("change", { bubbles: true }));
  }

  window.onTurnstileSuccess = function(token) {
    dispatchTurnstileValue(token);
  };

  window.onTurnstileExpired = function() {
    dispatchTurnstileValue("");
    if (window.turnstile && turnstileWidgetId !== null) {
      try {
        window.turnstile.reset(turnstileWidgetId);
        return;
      } catch (_error) {
      }
    }
    window.renderTurnstileWidget();
  };

  window.onTurnstileError = function(errorCode) {
    console.error("Turnstile error:", errorCode);
    dispatchTurnstileValue("");
    return false;
  };

  function clearWidgetReference() {
    turnstileWidgetId = null;
    renderedNode = null;
  }

  function renderTurnstileWidget() {
    const mount = getTurnstileMount();
    if (!mount || !siteKey) return false;
    if (!window.turnstile || typeof window.turnstile.render !== "function") return false;

    if (renderedNode && renderedNode !== mount) {
      try {
        if (turnstileWidgetId !== null) {
          window.turnstile.remove(turnstileWidgetId);
        }
      } catch (_error) {
      }
      clearWidgetReference();
    }

    if (renderedNode === mount && turnstileWidgetId !== null) {
      return true;
    }

    dispatchTurnstileValue("");
    mount.replaceChildren();

    try {
      turnstileWidgetId = window.turnstile.render(mount, {
        sitekey: siteKey,
        callback: window.onTurnstileSuccess,
        "expired-callback": window.onTurnstileExpired,
        "error-callback": window.onTurnstileError,
      });
      renderedNode = mount;
      return true;
    } catch (error) {
      console.error("Turnstile render failed:", error);
      clearWidgetReference();
      return false;
    }
  }

  function scheduleTurnstileRender() {
    if (renderScheduled) return;
    renderScheduled = true;
    window.requestAnimationFrame(() => {
      renderScheduled = false;
      renderTurnstileWidget();
    });
  }

  window.onTurnstileApiLoad = function() {
    scheduleTurnstileRender();
  };

  window.renderTurnstileWidget = scheduleTurnstileRender;

  window.resetTurnstileWidget = function() {
    dispatchTurnstileValue("");
    if (window.turnstile && turnstileWidgetId !== null) {
      try {
        window.turnstile.reset(turnstileWidgetId);
        return;
      } catch (_error) {
      }
    }
    clearWidgetReference();
    scheduleTurnstileRender();
  };

  function startTurnstileObserver() {
    if (observer) return;
    const root = document.documentElement || document.body;
    if (!root) return;
    observer = new MutationObserver(() => {
      scheduleTurnstileRender();
    });
    observer.observe(root, { childList: true, subtree: true });
  }

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", () => {
      startTurnstileObserver();
      scheduleTurnstileRender();
    }, { once: true });
  } else {
    startTurnstileObserver();
    scheduleTurnstileRender();
  }

  window.addEventListener("load", scheduleTurnstileRender);
})();
</script>
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit&onload=onTurnstileApiLoad" defer></script>
""" % json.dumps(turnstile_site_key()) if turnstile_site_key() else None

APP_THEME = gr.themes.Soft()

def canonicalize_emotion(label):
    norm = normalize_label(label)
    if not norm:
        return ""
    return EMOTION_ALIASES.get(norm, norm)

def load_metadata(metadata_path):
    if not os.path.exists(metadata_path): return {}
    metadata = {}
    with open(metadata_path, newline='') as f:
        reader = csv.DictReader(f)
        for row in reader:
            name = row.get("image_name") or row.get("filename") or row.get("image")
            if not name: continue
            key = name.strip().lower()
            entry = {
                "emotion": normalize_label(row.get("emotion")),
                "sex": normalize_label(row.get("sex")),
                "ethnicity": normalize_label(row.get("ethnicity")),
                "angle": normalize_label(row.get("angle")),
                "face_type": normalize_label(row.get("face_type") or row.get("type") or row.get("source")),
            }
            metadata[key] = entry
            stem = os.path.splitext(key)[0]
            metadata.setdefault(stem, entry)
    return metadata

def parse_filename_fields(image_path):
    base_name = os.path.splitext(os.path.basename(image_path))[0]
    parts = base_name.split('_')
    if len(parts) < 2: return {}
    fields = {}
    for field in FILENAME_FIELD_ORDER:
        if not parts: break
        fields[field] = normalize_label(parts.pop())
    return fields

def resolve_field(metadata, filename_fields, key, default=UNKNOWN_LABEL):
    value = ""
    if metadata: value = normalize_label(metadata.get(key))
    if not value: value = filename_fields.get(key, "")
    return value or default

def resolve_face_type(metadata, default=UNKNOWN_LABEL):
    if metadata and metadata.get("face_type"):
        return normalize_label(metadata.get("face_type"))
    return normalize_label(default) or UNKNOWN_LABEL

def resolve_stimulus_type(face_type):
    ft = normalize_label(face_type)
    if ft in {"human", "real", "real-kdef", "real_kdef"}:
        return STIMULUS_TYPE_REAL
    if ft in {"ai", "synthetic", "ai-kdef-like", "ai_kdef_like"}:
        return STIMULUS_TYPE_AI
    return UNKNOWN_LABEL

def make_stimulus_id(filename):
    stem = os.path.splitext(os.path.basename(filename))[0]
    return stem.strip().lower()

def select_balanced_subset(images, max_per_stratum=None):
    if not images:
        return []
    strata = {}
    for img in images:
        key = (img.stimulus_type, img.emotion)
        strata.setdefault(key, []).append(img)
    counts = {k: len(v) for k, v in strata.items()}
    if not counts:
        return images
    min_count = min(counts.values())
    if max_per_stratum is not None:
        min_count = min(min_count, int(max_per_stratum))
    if min_count <= 0:
        return images

    sampled = []
    for key, items in strata.items():
        if len(items) <= min_count:
            sampled.extend(items)
        else:
            sampled.extend(random.sample(items, k=min_count))
    random.shuffle(sampled)
    print(f"[DEBUG] Balanced subset: {len(sampled)} trials across {len(strata)} strata (per-stratum={min_count}).")
    return sampled

def build_row_template(state, image_data):
    # Minimal row template: only fields that are written to the part CSVs.
    return {
        "participant_id": state.get("participant_id", ""),
        "session_id": state.get("session_id", ""),
        "stimulus_id": image_data.stimulus_id,
        "stimulus_type": image_data.stimulus_type,
        "target_emotion": image_data.emotion,
        # Part 1 fields (filled in later).
        "emotion_trial_index": "",
        "emotion_rt_ms": "",
        "selected_emotion": "",
        "accuracy": "",
        "emotion_timestamp": "",
        # Part 2 fields (filled in later).
        "matching_trial_index": "",
        "match_age_rating": "",
        "match_masc_rating": "",
        "match_attr_rating": "",
        "match_quality_rating": "",
        "match_artifact_rating": "",
        "matching_timestamp": "",
    }

def ensure_csv_file_for(file_path, headers):
    if not os.path.exists(file_path):
        with open(file_path, "w", newline="") as f:
            writer = csv.writer(f)
            writer.writerow(headers)
        return file_path, ""

    with open(file_path, newline="") as f:
        reader = csv.reader(f)
        existing_header = next(reader, None)
    if existing_header != headers:
        base, ext = os.path.splitext(file_path)
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        backup_file = f"{base}_{timestamp}{ext or '.csv'}"
        try:
            shutil.copy2(file_path, backup_file)
            backup_msg = f"Copied existing results to: {backup_file}"
        except Exception as e:
            backup_msg = f"Could not copy existing results ({e})."

        # Reinitialize the base file with the expected header.
        with open(file_path, "w", newline="") as f:
            writer = csv.writer(f)
            writer.writerow(headers)
        return file_path, f"{backup_msg}\nReinitialized results file: {file_path}"
    return file_path, ""

def ensure_csv_files():
    part1_file, part1_status = ensure_csv_file_for(PART1_CSV_FILE, PART1_HEADERS)
    part2_file, part2_status = ensure_csv_file_for(PART2_CSV_FILE, PART2_HEADERS)
    statuses = [s for s in [part1_status, part2_status] if s]
    status_lines = [
        f"Part 1 file: {part1_file}",
        f"Part 2 file: {part2_file}",
    ]
    status_lines.extend(statuses)
    status_msg = "\n".join(status_lines)
    return part1_file, part2_file, status_msg

def get_downloadable_csv_files():
    return [path for path in [PART1_CSV_FILE, PART2_CSV_FILE, METADATA_FILE] if os.path.exists(path)]

def unlock_downloads(password):
    expected = str(os.getenv(DOWNLOAD_PASSWORD_ENV) or "").strip()
    if not expected:
        return (
            gr.update(value=f"Download access is not configured. Set `{DOWNLOAD_PASSWORD_ENV}` on the server.", visible=True),
            gr.update(value=None, visible=False),
            gr.update(value=""),
        )

    if str(password or "") != expected:
        return (
            gr.update(value="Incorrect password.", visible=True),
            gr.update(value=None, visible=False),
            gr.update(value=""),
        )

    files = get_downloadable_csv_files()
    if not files:
        return (
            gr.update(value="No CSV files are available yet.", visible=True),
            gr.update(value=None, visible=False),
            gr.update(value=""),
        )

    return (
        gr.update(value=f"Downloads unlocked. {len(files)} file(s) available.", visible=True),
        gr.update(value=files, visible=True),
        gr.update(value=""),
    )

def get_participant_id(request):
    if request is None: return ""
    pid = request.query_params.get(URL_PARAM_PARTICIPANT_ID)
    return str(pid).strip() if pid else ""

def get_request_ip(request):
    if request is None:
        return ""
    client = getattr(request, "client", None)
    host = getattr(client, "host", None)
    return str(host).strip() if host else ""

def turnstile_status_text():
    if turnstile_is_enabled():
        return "Complete the human check to enable Next."
    if turnstile_is_partially_configured():
        return (
            f"Turnstile is misconfigured. Set both `{TURNSTILE_SITE_KEY_ENV}` "
            f"and `{TURNSTILE_SECRET_KEY_ENV}` to enable bot protection."
        )
    return (
        f"Bot protection is currently off. Add `{TURNSTILE_SITE_KEY_ENV}` "
        f"and `{TURNSTILE_SECRET_KEY_ENV}` to enable Cloudflare Turnstile."
    )

def verify_turnstile_token(token, request):
    if not turnstile_is_enabled():
        return True, ""

    token = str(token or "").strip()
    if not token:
        return False, "Please complete the human check before continuing."

    payload = {
        "secret": turnstile_secret_key(),
        "response": token,
    }
    remote_ip = get_request_ip(request)
    if remote_ip:
        payload["remoteip"] = remote_ip

    verify_request = urlrequest.Request(
        TURNSTILE_VERIFY_URL,
        data=parse.urlencode(payload).encode("utf-8"),
        method="POST",
        headers={"Content-Type": "application/x-www-form-urlencoded"},
    )
    try:
        with urlrequest.urlopen(verify_request, timeout=10) as response:
            body = json.loads(response.read().decode("utf-8"))
    except Exception as exc:
        print(f"Turnstile verification request failed: {exc}")
        return False, "Could not verify the human check. Please try again."

    if body.get("success"):
        return True, ""

    error_codes = body.get("error-codes") or []
    print(f"Turnstile verification failed: {error_codes}")
    return False, "Human check expired or failed. Please try again."

def is_verified_session(state):
    if not turnstile_is_enabled():
        return True
    if not state:
        return False
    session_id = str(state.get("session_id") or "").strip()
    return bool(session_id) and session_id in VERIFIED_SESSION_IDS and bool(state.get("human_verified"))

def _blocked_start_response(state, message, start_interactive=False):
    return (
        state,
        gr.update(visible=True),
        gr.update(visible=True, interactive=start_interactive),
        gr.update(visible=False),
        gr.update(),
        gr.update(value=message),
        gr.update(visible=False, interactive=False),
        gr.update(value=""),
        gr.update(visible=False, interactive=False),
        gr.update(visible=False, interactive=False),
    )

def _blocked_main_response(state, message="Complete the human check to continue."):
    return (
        state,
        gr.update(visible=False, interactive=False),
        message,
        gr.update(visible=False, interactive=False),
        gr.update(visible=False, interactive=False),
    )

def scan_images():
    images = []
    emotions = set()
    metadata = load_metadata(METADATA_FILE)
    skipped_missing_emotion = []
    skipped_angle = []
    skipped_emotion = []
    if not os.path.exists(DATASET_FOLDER):
        return images, emotions

    for filename in os.listdir(DATASET_FOLDER):
        if not filename.lower().endswith((".jpg", ".jpeg", ".png")):
            continue
        path = os.path.join(DATASET_FOLDER, filename)
        if not os.path.isfile(path):
            continue

        meta_key = filename.lower()
        meta = metadata.get(meta_key) or metadata.get(os.path.splitext(meta_key)[0]) or {}
        filename_fields = parse_filename_fields(path)

        emotion_raw = resolve_field(meta, filename_fields, "emotion", "")
        emotion = canonicalize_emotion(emotion_raw)
        if not emotion or emotion == UNKNOWN_LABEL:
            skipped_missing_emotion.append(filename)
            continue
        if emotion not in ALLOWED_EMOTIONS:
            skipped_emotion.append((filename, emotion_raw))
            continue

        sex = resolve_field(meta, filename_fields, "sex", UNKNOWN_LABEL)
        ethnicity = resolve_field(meta, filename_fields, "ethnicity", UNKNOWN_LABEL)
        angle = resolve_field(meta, filename_fields, "angle", UNKNOWN_LABEL)
        if ALLOWED_ANGLES and angle not in ALLOWED_ANGLES:
            skipped_angle.append((filename, angle))
            continue
        face_type = resolve_face_type(meta)
        stimulus_type = resolve_stimulus_type(face_type)
        stimulus_id = make_stimulus_id(filename)

        emotions.add(emotion)
        images.append(
            ImageData(
                path,
                face_type,
                emotion,
                sex=sex,
                ethnicity=ethnicity,
                angle=angle,
                face_type=face_type,
                stimulus_type=stimulus_type,
                stimulus_id=stimulus_id,
            )
        )
    
    if skipped_missing_emotion:
        print(f"[DEBUG] Skipped {len(skipped_missing_emotion)} images without emotion label.")
    if skipped_angle:
        print(
            f"[DEBUG] Filtered out {len(skipped_angle)} images due to angle "
            f"(allowed={sorted(ALLOWED_ANGLES)})."
        )
    if skipped_emotion:
        print(
            f"[DEBUG] Filtered out {len(skipped_emotion)} images due to emotion "
            f"(allowed={EMOTION_CHOICES_ORDER})."
        )
    return images, emotions

def crop_face(image_path, target_size=512):
    if not os.path.exists(image_path): return None
    img = cv2.imread(image_path)
    if img is None: return None

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    cascade_path = cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
    img_h, img_w = img.shape[:2]

    side = min(img_w, img_h)
    center_x = img_w / 2
    center_y = img_h / 2

    if os.path.exists(cascade_path):
        face_cascade = cv2.CascadeClassifier(cascade_path)
        detection_inputs = [gray, cv2.equalizeHist(gray)]
        faces = ()
        for detection_gray in detection_inputs:
            faces = face_cascade.detectMultiScale(
                detection_gray,
                scaleFactor=1.1,
                minNeighbors=5,
            )
            if len(faces) > 0:
                break

        if len(faces) > 0:
            x, y, w, h = max(faces, key=lambda f: f[2] * f[3])
            center_x = x + (w / 2)
            center_y = y + (h / 2) - (FACE_CROP_Y_BIAS * h)

            eye_pair = None
            eye_region = gray[y:y + int(h * 0.7), x:x + w]
            if eye_region.size > 0:
                for eye_cascade_name in ("haarcascade_eye_tree_eyeglasses.xml", "haarcascade_eye.xml"):
                    eye_cascade_path = cv2.data.haarcascades + eye_cascade_name
                    if not os.path.exists(eye_cascade_path):
                        continue

                    eye_cascade = cv2.CascadeClassifier(eye_cascade_path)
                    eyes = eye_cascade.detectMultiScale(
                        eye_region,
                        scaleFactor=1.05,
                        minNeighbors=6,
                    )
                    eye_candidates = []
                    for ex, ey, ew, eh in eyes:
                        cx = x + ex + (ew / 2)
                        cy = y + ey + (eh / 2)
                        if cy >= y + (h * 0.62):
                            continue
                        eye_candidates.append((cx, cy, ew, eh))

                    best_score = None
                    for i in range(len(eye_candidates)):
                        for j in range(i + 1, len(eye_candidates)):
                            left, right = sorted((eye_candidates[i], eye_candidates[j]), key=lambda eye: eye[0])
                            dx = right[0] - left[0]
                            dy = abs(right[1] - left[1])
                            if dx <= w * 0.2 or dx >= w * 0.9:
                                continue
                            size_diff = abs((left[2] * left[3]) - (right[2] * right[3])) / max(left[2] * left[3], right[2] * right[3], 1)
                            score = dx - (2.5 * dy) - (dx * size_diff)
                            if best_score is None or score > best_score:
                                best_score = score
                                eye_pair = (left, right)

                    if eye_pair is not None:
                        break

            if eye_pair is not None:
                left_eye, right_eye = eye_pair
                eye_mid_x = (left_eye[0] + right_eye[0]) / 2
                eye_mid_y = (left_eye[1] + right_eye[1]) / 2
                eye_distance = right_eye[0] - left_eye[0]
                eye_ratio = max(0.1, min(0.9, EYE_DISTANCE_TARGET_RATIO))
                side = min(int(round(eye_distance / eye_ratio)), img_w, img_h)
                eye_line = max(0.1, min(0.9, EYE_LINE_POSITION_RATIO))
                center_x = eye_mid_x
                center_y = eye_mid_y + ((0.5 - eye_line) * side)
            else:
                face_size = max(w, h)
                target_ratio = max(0.1, min(0.95, FACE_CROP_TARGET_RATIO))
                side = min(int(round(face_size / target_ratio)), img_w, img_h)

    side = max(1, side)
    x1 = int(round(center_x - (side / 2)))
    y1 = int(round(center_y - (side / 2)))
    x1 = max(0, min(img_w - side, x1))
    y1 = max(0, min(img_h - side, y1))
    x2 = x1 + side
    y2 = y1 + side

    cropped = img[y1:y2, x1:x2]
    if cropped.size == 0:
        return None

    interpolation = cv2.INTER_AREA if side >= target_size else cv2.INTER_CUBIC
    resized_img = cv2.resize(cropped, (target_size, target_size), interpolation=interpolation)

    return cv2.cvtColor(resized_img, cv2.COLOR_BGR2RGB)

# --- Backend Logic ---

def initialize_experiment(request: gr.Request):
    os.makedirs(DATASET_FOLDER, exist_ok=True)
    images, emotions = scan_images()
    
    if not images:
        return (
            None,
            "Error: No images found.",
            gr.update(interactive=False),
            gr.update(value=turnstile_status_text()),
        )

    session_id = str(uuid.uuid4())
    participant_id = get_participant_id(request)
    if not participant_id:
        participant_id = f"anon-{session_id}"
        msg = f"Participant ID: {participant_id}"
    else:
        msg = f"Participant ID: {participant_id}"

    csv_file_part1, csv_file_part2, csv_status = ensure_csv_files()

    # Optionally select a balanced subset across (stimulus_type, emotion).
    selected_images = images
    if BALANCE_SUBSET_DEFAULT:
        balanced = select_balanced_subset(images, MAX_PER_STRATUM)
        if balanced:
            selected_images = balanced

    available_emotions = {img.emotion for img in selected_images}
    missing_emotions = [e for e in EMOTION_CHOICES_ORDER if e not in available_emotions]
    if missing_emotions:
        print(f"[DEBUG] No stimuli found for emotions: {missing_emotions}")
    random.shuffle(selected_images)
    initial_state = {
        "participant_id": participant_id,
        "session_id": session_id,
        "human_verified": not turnstile_is_enabled(),
        "csv_file": csv_file_part1,
        "csv_file_part1": csv_file_part1,
        "csv_file_part2": csv_file_part2,
        "all_images": selected_images,
        "part2_images": [],
        # Fixed order across participants.
        "emotions": list(EMOTION_CHOICES),
        "current_index": -1,
        "current_choices": [],
        "randomize_emotions": RANDOMIZE_EMOTION_ORDER_DEFAULT,
        "start_time": None,
        "phase": "emotion",
        "part2_started": False,
        "part2_index": -1,
        "part2_start_time": None,
        "part2_touched": {k: False for k in PART2_KEYS},
    }
    
    if request:
        val = request.query_params.get(RANDOMIZE_EMOTION_ORDER_PARAM)
        if val and val.lower() in ['0','false','no']:
            initial_state["randomize_emotions"] = False

    part2_images = list(selected_images)
    random.shuffle(part2_images)
    initial_state["part2_images"] = part2_images

    if not turnstile_is_enabled():
        VERIFIED_SESSION_IDS.add(session_id)

    start_enabled = bool(images) and not turnstile_is_enabled() and not turnstile_is_partially_configured()
    return (
        initial_state,
        f"{msg}\n{csv_status}",
        gr.update(interactive=start_enabled),
        gr.update(value=turnstile_status_text()),
    )

def start_interface(state):
    if not state: 
        return (
            gr.update(visible=True),
            gr.update(visible=True),
            gr.update(visible=False),
            gr.update(visible=False),
            gr.update(visible=False),
        )
    return (
        gr.update(visible=False),
        gr.update(visible=False),
        gr.update(visible=True),
        gr.update(visible=False),
        gr.update(visible=False),
    )

def begin_study(state, turnstile_token, request: gr.Request):
    if not state:
        return _blocked_start_response(state, "Error: study state is missing.", start_interactive=False)

    if turnstile_is_partially_configured():
        return _blocked_start_response(
            state,
            f"Turnstile is misconfigured. Set both `{TURNSTILE_SITE_KEY_ENV}` and `{TURNSTILE_SECRET_KEY_ENV}`.",
            start_interactive=False,
        )

    verified, message = verify_turnstile_token(turnstile_token, request)
    if not verified:
        return _blocked_start_response(
            state,
            message,
            start_interactive=bool(str(turnstile_token or "").strip()),
        )

    session_id = str(state.get("session_id") or "").strip()
    if session_id:
        VERIFIED_SESSION_IDS.add(session_id)
    state["human_verified"] = True

    next_state, image_update, progress_value, choice_update, next_btn_update = show_next_image(state)
    return (
        next_state,
        gr.update(visible=False),
        gr.update(visible=False),
        gr.update(visible=True),
        gr.update(),
        gr.update(value="Human check passed."),
        image_update,
        gr.update(value=progress_value),
        choice_update,
        next_btn_update,
    )

def on_turnstile_token_change(token):
    if turnstile_is_partially_configured():
        return (
            gr.update(interactive=False),
            gr.update(
                value=(
                    f"Turnstile is misconfigured. Set both `{TURNSTILE_SITE_KEY_ENV}` "
                    f"and `{TURNSTILE_SECRET_KEY_ENV}`."
                )
            ),
        )
    if not turnstile_is_enabled():
        return (
            gr.update(interactive=True),
            gr.update(value=turnstile_status_text()),
        )

    has_token = bool(str(token or "").strip())
    return (
        gr.update(interactive=has_token),
        gr.update(
            value="Human check complete. Click Next." if has_token else "Complete the human check to enable Next."
        ),
    )

def show_next_image(state):
    # Returns: [state, img_anim_update, progress_text, choices_update, next_btn_update]
    if not state:
        return _blocked_main_response(state, "Error")
    if not is_verified_session(state):
        return _blocked_main_response(state)

    state["current_index"] += 1
    index = state["current_index"]

    if index >= len(state["all_images"]):
        state["part2_started"] = False
        state["part2_index"] = -1
        state["part2_start_time"] = None
        state["part2_touched"] = {k: False for k in PART2_KEYS}
        state["phase"] = "part2_instructions"
        return (
            state,
            gr.update(visible=False),
            "",
            gr.update(visible=False, interactive=False),
            gr.update(visible=False, interactive=False),
        )

    image_data = state["all_images"][index]
    cropped_image = crop_face(image_data.path)
    
    if cropped_image is None:
        # Recursive skip if image fails to load
        return show_next_image(state)

    state["start_time"] = time.monotonic()
    
    # Keep emotion order fixed across all trials and participants.
    choices = list(state["emotions"])
    state["current_choices"] = choices

    return (
        state,
        gr.update(value=cropped_image, visible=True, interactive=False),
        f"Image {index + 1} of {len(state['all_images'])}",
        gr.update(choices=choices, value=None, visible=True, interactive=True),
        gr.update(interactive=False, visible=False),
    )

def advance_main_phase(state):
    next_state, image_update, progress_update, choice_update, next_btn_update = show_next_image(state)
    phase = next_state.get("phase") if next_state else None
    show_intro = phase == "part2_instructions"
    if show_intro:
        print("[DEBUG] Transitioned from Part 1 to Part 2 instructions.")
    return (
        next_state,
        image_update,
        gr.update(value=progress_update, visible=not show_intro),
        choice_update,
        next_btn_update,
        gr.update(visible=show_intro),
        gr.update(visible=show_intro),
        gr.update(visible=False),
        gr.update(visible=False),
        gr.update(value="", visible=False),
        gr.update(value="", visible=False),
        gr.update(value="", visible=False),
        gr.update(visible=False),
        gr.update(visible=False),
        gr.update(visible=False),
        gr.update(visible=False),
        gr.update(visible=False),
        gr.update(visible=False),
    )

def on_emotion_select(state, selected_emotion):
    # Returns: [state, image_update, choices_interactive, next_btn_interactive]
    if not is_verified_session(state):
        return state, gr.update(), gr.update(interactive=False), gr.update(interactive=False)
    if not state or not selected_emotion:
        return state, gr.update(), gr.update(), gr.update()
    
    try:
        start_time = state.get("start_time") or time.monotonic()
        response_time_ms = int(round((time.monotonic() - start_time) * 1000))
        image_data = state["all_images"][state["current_index"]]
        normalized_sel = canonicalize_emotion(selected_emotion)
        accuracy = "correct" if normalized_sel == image_data.emotion else "incorrect"
        trial_index = state.get("current_index", -1) + 1

        row = build_row_template(
            state,
            image_data,
        )
        row["selected_emotion"] = normalized_sel
        row["accuracy"] = accuracy

        row["emotion_trial_index"] = trial_index
        row["emotion_rt_ms"] = response_time_ms
        row["emotion_timestamp"] = datetime.now().isoformat()

        part1_file = state.get("csv_file_part1") or state.get("csv_file")
        with open(part1_file, "a", newline="") as f:
            writer = csv.writer(f)
            writer.writerow([row[h] for h in PART1_HEADERS])
        print(f"[DEBUG] Saved Part 1 rating ({normalized_sel}, {response_time_ms}ms) -> {part1_file}")
    except Exception as e:
        print(f"Error saving CSV: {e}")

    # Freeze the current response while the follow-up event advances automatically.
    return (
        state,
        gr.update(visible=True, interactive=False),
        gr.update(interactive=False),
        gr.update(interactive=False, visible=False),
    )

# --- Part 2 Helpers ---

def _to_int(value):
    if value is None or value == "":
        return ""
    try:
        return int(value)
    except Exception:
        return ""

# --- Part 2: Face Rating Logic ---

def start_part2(state):
    if not is_verified_session(state):
        return state
    if not state or state.get("phase") != "part2_instructions":
        return state

    state["phase"] = "part2"
    state["part2_started"] = True
    state["part2_index"] = -1
    state["part2_start_time"] = None
    state["part2_touched"] = {k: False for k in PART2_KEYS}
    print("[DEBUG] Starting Part 2.")
    return state

def begin_part2(state):
    next_state = start_part2(state)
    part2_outputs = show_next_part2_image(next_state)
    phase = part2_outputs[0].get("phase") if part2_outputs[0] else None
    show_part2 = phase in {"part2", "complete"}
    return (
        part2_outputs[0],
        gr.update(visible=False),
        gr.update(value="", visible=False),
        gr.update(visible=False, interactive=False),
        gr.update(visible=False, interactive=False),
        gr.update(visible=False),
        gr.update(visible=False),
        gr.update(visible=show_part2),
        *part2_outputs[1:],
    )

def _no_part2_updates(state):
    # Returns: [state, part2_image, part2_progress_text, part2_status_text, part2_completion_text,
    #           part2_age_radio, part2_masc_radio, part2_attr_radio, part2_quality_radio, part2_artifact_radio,
    #           part2_next_btn]
    return (
        state,
        gr.update(visible=False),
        gr.update(value="", visible=False),
        gr.update(value="", visible=False),
        gr.update(value="", visible=False),
        gr.update(visible=False, interactive=False),
        gr.update(visible=False, interactive=False),
        gr.update(visible=False, interactive=False),
        gr.update(visible=False, interactive=False),
        gr.update(visible=False, interactive=False),
        gr.update(visible=False, interactive=False),
    )

def _part2_reset_updates():
    return (
        gr.update(value=None, interactive=True, visible=True),  # part2_age_radio
        gr.update(value=None, interactive=True, visible=True),  # part2_masc_radio
        gr.update(value=None, interactive=True, visible=True),  # part2_attr_radio
        gr.update(value=None, interactive=True, visible=True),  # part2_quality_radio
        gr.update(value=None, interactive=True, visible=True),  # part2_artifact_radio
    )

def show_next_part2_image(state):
    if not is_verified_session(state):
        return _no_part2_updates(state)
    if not state or state.get("phase") != "part2" or not state.get("part2_started"):
        return _no_part2_updates(state)

    images = state.get("part2_images") or state.get("all_images") or []
    state["part2_index"] = state.get("part2_index", -1) + 1
    index = state["part2_index"]

    if index >= len(images):
        state["phase"] = "complete"
        completion_md = "# ✅\n## Complete!"
        return (
            state,
            gr.update(value=None, visible=False),
            gr.update(value="", visible=False),
            gr.update(value="", visible=False),
            gr.update(value=completion_md, visible=True),
            gr.update(interactive=False, visible=False),
            gr.update(interactive=False, visible=False),
            gr.update(interactive=False, visible=False),
            gr.update(interactive=False, visible=False),
            gr.update(interactive=False, visible=False),
            gr.update(interactive=False, visible=False),
        )

    image_data = images[index]
    cropped_image = crop_face(image_data.path)
    if cropped_image is None:
        return show_next_part2_image(state)

    state["part2_start_time"] = time.monotonic()
    state["part2_touched"] = {k: False for k in PART2_KEYS}
    reset_updates = _part2_reset_updates()

    return (
        state,
        gr.update(value=cropped_image, visible=True),
        gr.update(value=f"Image {index + 1} of {len(images)}", visible=True),
        gr.update(value="Rate all five items to enable Next.", visible=True),
        gr.update(value="", visible=False),
        reset_updates[0],
        reset_updates[1],
        reset_updates[2],
        reset_updates[3],
        reset_updates[4],
        gr.update(interactive=False, visible=True),
    )

def _mark_part2_touched(state, _value, key):
    if not is_verified_session(state):
        return state, gr.update(interactive=False), gr.update("Complete the human check to continue."), gr.update()
    if not state or state.get("phase") != "part2" or not state.get("part2_started"):
        return state, gr.update(), gr.update(), gr.update()
    touched = dict(state.get("part2_touched") or {})
    touched[key] = _value not in (None, "")
    state["part2_touched"] = touched
    ready = all(touched.get(k, False) for k in PART2_KEYS)
    message = "All items answered. Click Next." if ready else "Rate all five items to continue."
    return state, gr.update(interactive=ready), gr.update(message), gr.update()

def advance_part2(state, age_rating, masc_rating, attr_rating, quality_rating, artifact_rating):
    if not is_verified_session(state):
        return _no_part2_updates(state)
    if not state or state.get("phase") != "part2" or not state.get("part2_started"):
        return _no_part2_updates(state)

    values = {
        "age": age_rating,
        "masc": masc_rating,
        "attr": attr_rating,
        "quality": quality_rating,
        "artifact": artifact_rating,
    }
    missing = [k for k, v in values.items() if v in (None, "")]
    if missing:
        state["part2_touched"] = {k: (values[k] not in (None, "")) for k in PART2_KEYS}
        return (
            state,
            gr.update(),
            gr.update(),
            gr.update("Please answer all five items before continuing."),
            gr.update(),
            gr.update(),
            gr.update(),
            gr.update(),
            gr.update(),
            gr.update(),
            gr.update(interactive=False),
        )

    images = state.get("part2_images") or state.get("all_images") or []
    index = state.get("part2_index", -1)
    if index < 0 or index >= len(images):
        return (
            state,
            gr.update(),
            gr.update(),
            gr.update("No rating target available."),
            gr.update(),
            gr.update(),
            gr.update(),
            gr.update(),
            gr.update(),
            gr.update(),
            gr.update(interactive=False),
        )

    start_time = state.get("part2_start_time") or time.monotonic()
    response_time_ms = int(round((time.monotonic() - start_time) * 1000))
    image_data = images[index]
    trial_index = index + 1

    try:
        row = build_row_template(
            state,
            image_data,
        )
        row["match_age_rating"] = _to_int(age_rating)
        row["match_masc_rating"] = _to_int(masc_rating)
        row["match_attr_rating"] = _to_int(attr_rating)
        row["match_quality_rating"] = _to_int(quality_rating)
        row["match_artifact_rating"] = _to_int(artifact_rating)

        row["matching_trial_index"] = trial_index
        row["matching_timestamp"] = datetime.now().isoformat()

        part2_file = state.get("csv_file_part2") or state.get("csv_file")
        with open(part2_file, "a", newline="") as f:
            writer = csv.writer(f)
            writer.writerow([row[h] for h in PART2_HEADERS])
        print(f"[DEBUG] Saved Part 2 ratings ({response_time_ms}ms) -> {part2_file}")
    except Exception as e:
        print(f"Error saving Part 2 CSV: {e}")
        return (
            state,
            gr.update(),
            gr.update(),
            gr.update(f"Error saving ratings: {e}"),
            gr.update(),
            gr.update(),
            gr.update(),
            gr.update(),
            gr.update(),
            gr.update(),
            gr.update(interactive=True),
        )

    return show_next_part2_image(state)

# --- Gradio App ---
with gr.Blocks() as app:
    state = gr.State()

    with gr.Sidebar(label="Data Downloads", open=False, position="right", width=340, elem_id="download_sidebar"):
        gr.Markdown(
            "## Data Downloads\n"
            "Enter the password to unlock the CSV files."
        )
        download_password = gr.Textbox(
            label="Password",
            type="password",
            placeholder="Enter download password",
            elem_id="download_password",
        )
        unlock_downloads_btn = gr.Button("Unlock Downloads", variant="secondary", elem_id="unlock_downloads_btn")
        download_status = gr.Markdown("", visible=False, elem_id="download_status")
        download_files = gr.File(
            label="Available CSV files",
            file_count="multiple",
            interactive=False,
            visible=False,
        )
    
    # 1. Landing Page
    with gr.Column(visible=True, elem_id="instructions_section") as instructions_section:
        gr.HTML("<h1>Face Emotion Recognition Study</h1>", elem_id="app_title")
        gr.Markdown("# Instructions\n ## Identify the emotion shown in each face.", elem_id="instructions_heading")
        gr.Markdown(STUDY_CONSENT_MARKDOWN, elem_id="study_consent")
        turnstile_token = gr.Textbox(value="", visible="hidden", elem_id="turnstile_token", render=True)
        human_check_widget = gr.HTML(render_turnstile_widget(), visible=turnstile_is_enabled())
        human_check_status = gr.Markdown("")
        start_btn = gr.Button("Next", variant="primary", elem_id="start_btn", interactive=False)
        status_text = gr.Markdown("")

    # 2. Main Experiment Interface
    with gr.Column(visible=False) as main_section:
        with gr.Group():
            image_anim = gr.Image(label="", elem_id="img_anim", interactive=False, show_label=False, visible=True)

        progress_text = gr.Markdown("", elem_id="progress_text")

        # Controls
        emotion_choice = gr.Radio(choices=[], label="Select the emotion", visible=False, interactive=True, elem_id="emotion_choice")
        next_image_btn = gr.Button("Next Image ▶", variant="secondary", visible=False, interactive=False, elem_id="next_btn")

        with gr.Column(elem_id="part2_instructions_section"):
            part2_intro_text = gr.Markdown(
                "# Part 2\n"
                "## You will now rate each face on several dimensions.\n"
                "## Use the 1–7 scale for each item, then click Next Face ▶.",
                visible="hidden",
            )
            part2_start_btn = gr.Button("Start Part 2 ▶", variant="primary", elem_id="part2_start_btn", visible="hidden")

        with gr.Column(elem_id="part2_section"):
            part2_title = gr.Markdown(
                "# Rate The Images",
                visible="hidden",
            )
            with gr.Row():
                with gr.Column(scale=1):
                    part2_image = gr.Image(
                        label="",
                        elem_id="part2_image",
                        interactive=False,
                        show_label=False,
                        visible="hidden",
                    )
                    part2_progress_text = gr.Markdown("", visible="hidden")
                    part2_status_text = gr.Markdown("", visible="hidden")
                    part2_completion_text = gr.Markdown("", elem_id="part2_completion_text", visible="hidden")
                with gr.Column(scale=1):
                    part2_age_radio = gr.Radio(
                        choices=SCALE_CHOICES,
                        value=None,
                        label="Perceived age (1 = very young, 7 = very old)",
                        visible="hidden",
                    )
                    part2_masc_radio = gr.Radio(
                        choices=SCALE_CHOICES,
                        value=None,
                        label="Femininity–masculinity (1 = very feminine, 7 = very masculine)",
                        visible="hidden",
                    )
                    part2_attr_radio = gr.Radio(
                        choices=SCALE_CHOICES,
                        value=None,
                        label="Attractiveness (1 = not at all, 7 = very attractive)",
                        visible="hidden",
                    )
                    part2_quality_radio = gr.Radio(
                        choices=SCALE_CHOICES,
                        value=None,
                        label="Image quality (1 = very poor, 7 = excellent)",
                        visible="hidden",
                    )
                    part2_artifact_radio = gr.Radio(
                        choices=SCALE_CHOICES,
                        value=None,
                        label="This image contains visual glitches or unnatural details.\n(1 = strongly disagree, 7 = strongly agree)",
                        elem_id="part2_artifact_radio",
                        visible="hidden",
                    )

                    part2_next_btn = gr.Button("Next Face ▶", variant="primary", interactive=False, visible="hidden")

    # --- Event Wiring ---

    # App Load
    app.load(
        fn=initialize_experiment,
        outputs=[state, status_text, start_btn, human_check_status],
        api_visibility="private",
    )

    turnstile_token.change(
        fn=on_turnstile_token_change,
        inputs=[turnstile_token],
        outputs=[start_btn, human_check_status],
        show_progress="hidden",
        api_visibility="private",
    )

    unlock_downloads_btn.click(
        fn=unlock_downloads,
        inputs=[download_password],
        outputs=[download_status, download_files, download_password],
        show_progress="hidden",
        api_visibility="private",
    )

    download_password.submit(
        fn=unlock_downloads,
        inputs=[download_password],
        outputs=[download_status, download_files, download_password],
        show_progress="hidden",
        api_visibility="private",
    )

    # Start Button -> Show Interface -> Load First Image -> Trigger Animation
    start_btn.click(
        fn=begin_study,
        inputs=[state, turnstile_token],
        outputs=[
            state,
            instructions_section,
            start_btn,
            main_section,
            status_text,
            human_check_status,
            image_anim,
            progress_text,
            emotion_choice,
            next_image_btn,
        ],
        show_progress="hidden",
        api_visibility="private",
    ).then(
        fn=None,
        js="() => { if (window.resetTurnstileWidget) window.resetTurnstileWidget(); }",
    )

    # Emotion Selected -> Save Data -> Advance automatically
    emotion_choice.input(
        fn=on_emotion_select, 
        inputs=[state, emotion_choice], 
        outputs=[state, image_anim, emotion_choice, next_image_btn],
        show_progress="hidden",
        api_visibility="private",
    ).then(
        fn=advance_main_phase,
        inputs=[state],
        outputs=[
            state,
            image_anim,
            progress_text,
            emotion_choice,
            next_image_btn,
            part2_intro_text,
            part2_start_btn,
            part2_title,
            part2_image,
            part2_progress_text,
            part2_status_text,
            part2_completion_text,
            part2_age_radio,
            part2_masc_radio,
            part2_attr_radio,
            part2_quality_radio,
            part2_artifact_radio,
            part2_next_btn,
        ],
        show_progress="hidden",
        api_visibility="private",
    )

    # Next Button -> Load New Image -> Reset Layout -> Trigger Animation
    next_image_btn.click(
        fn=advance_main_phase,
        inputs=[state],
        outputs=[
            state,
            image_anim,
            progress_text,
            emotion_choice,
            next_image_btn,
            part2_intro_text,
            part2_start_btn,
            part2_title,
            part2_image,
            part2_progress_text,
            part2_status_text,
            part2_completion_text,
            part2_age_radio,
            part2_masc_radio,
            part2_attr_radio,
            part2_quality_radio,
            part2_artifact_radio,
            part2_next_btn,
        ],
        show_progress="hidden",
        api_visibility="private",
    )

    # Part 2 Start -> Show ratings block -> Load first rating image
    part2_start_btn.click(
        fn=begin_part2,
        inputs=[state],
        outputs=[
            state,
            image_anim,
            progress_text,
            emotion_choice,
            next_image_btn,
            part2_intro_text,
            part2_start_btn,
            part2_title,
            part2_image,
            part2_progress_text,
            part2_status_text,
            part2_completion_text,
            part2_age_radio,
            part2_masc_radio,
            part2_attr_radio,
            part2_quality_radio,
            part2_artifact_radio,
            part2_next_btn,
        ],
        show_progress="hidden",
        api_visibility="private",
    )

    # Part 2 gating: require interaction with all five ratings
    part2_age_radio.change(
        fn=partial(_mark_part2_touched, key="age"),
        inputs=[state, part2_age_radio],
        outputs=[state, part2_next_btn, part2_status_text, part2_completion_text],
        show_progress="hidden",
        api_visibility="private",
    )
    part2_masc_radio.change(
        fn=partial(_mark_part2_touched, key="masc"),
        inputs=[state, part2_masc_radio],
        outputs=[state, part2_next_btn, part2_status_text, part2_completion_text],
        show_progress="hidden",
        api_visibility="private",
    )
    part2_attr_radio.change(
        fn=partial(_mark_part2_touched, key="attr"),
        inputs=[state, part2_attr_radio],
        outputs=[state, part2_next_btn, part2_status_text, part2_completion_text],
        show_progress="hidden",
        api_visibility="private",
    )
    part2_quality_radio.change(
        fn=partial(_mark_part2_touched, key="quality"),
        inputs=[state, part2_quality_radio],
        outputs=[state, part2_next_btn, part2_status_text, part2_completion_text],
        show_progress="hidden",
        api_visibility="private",
    )
    part2_artifact_radio.change(
        fn=partial(_mark_part2_touched, key="artifact"),
        inputs=[state, part2_artifact_radio],
        outputs=[state, part2_next_btn, part2_status_text, part2_completion_text],
        show_progress="hidden",
        api_visibility="private",
    )

    # Part 2 Next -> Save and advance
    part2_next_btn.click(
        fn=advance_part2,
        inputs=[state, part2_age_radio, part2_masc_radio, part2_attr_radio, part2_quality_radio, part2_artifact_radio],
        outputs=[
            state,
            part2_image,
            part2_progress_text,
            part2_status_text,
            part2_completion_text,
            part2_age_radio,
            part2_masc_radio,
            part2_attr_radio,
            part2_quality_radio,
            part2_artifact_radio,
            part2_next_btn,
        ],
        show_progress="hidden",
        api_visibility="private",
    )

if __name__ == "__main__":
    # Gradio 6 performs a HEAD request against the local root URL during launch.
    # On Hugging Face Spaces this check can fail even after startup-events succeed,
    # which aborts launch before the app is served. share=True skips that check,
    # and Gradio immediately disables actual share tunnels on Spaces.
    launch_share = bool(os.getenv("SPACE_ID"))
    # Support reverse proxies that publish the app under a subpath such as /facelab.
    launch_root_path = os.getenv("GRADIO_ROOT_PATH") or None
    app.launch(
        share=launch_share,
        root_path=launch_root_path,
        theme=APP_THEME,
        css=APP_CSS,
        head=TURNSTILE_HEAD,
        footer_links=["gradio"],
    )