File size: 92,902 Bytes
ac71c07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5255536
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac71c07
adbfc5d
 
46a10a9
2a1ef7e
ac71c07
5255536
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac71c07
 
 
5b5507b
ac71c07
 
2066a63
5b5507b
ac71c07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adbfc5d
ac71c07
 
 
cfb7d5a
 
 
 
ac71c07
 
 
0ebe26e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac71c07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac40945
 
 
adbfc5d
 
 
 
 
ac71c07
2a1ef7e
 
 
adbfc5d
2066a63
 
 
ac71c07
adbfc5d
ac40945
adbfc5d
 
4ea120d
adbfc5d
 
 
58c2cba
ac40945
adbfc5d
 
 
ac40945
adbfc5d
58c2cba
adbfc5d
 
 
 
 
 
 
 
 
 
ac71c07
adbfc5d
ac71c07
 
2a1ef7e
ac71c07
2a1ef7e
 
ac71c07
2a1ef7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2066a63
 
 
 
cfb7d5a
2066a63
 
 
cfb7d5a
2066a63
 
 
 
 
 
cfb7d5a
2066a63
 
 
 
 
 
cfb7d5a
2066a63
cfb7d5a
58c2cba
 
 
 
 
 
 
4ea120d
 
 
 
 
58c2cba
4ea120d
58c2cba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ea120d
 
58c2cba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ea120d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98cf86d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfb7d5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2066a63
 
 
 
 
5255536
 
 
 
 
 
 
2066a63
 
5255536
2066a63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adbfc5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2066a63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac71c07
8af7be8
2a1ef7e
ac40945
98cf86d
 
 
 
adbfc5d
 
 
 
cfb7d5a
adbfc5d
ac71c07
 
 
2066a63
 
 
 
 
 
 
 
ac71c07
 
46a10a9
ac71c07
98cf86d
 
8af7be8
98cf86d
 
 
 
 
 
 
 
 
 
 
8af7be8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac71c07
 
5b5507b
ac71c07
 
adbfc5d
ac71c07
 
5b5507b
 
 
 
 
 
adbfc5d
 
 
 
0ebe26e
ac71c07
 
 
adbfc5d
0ebe26e
 
adbfc5d
0ebe26e
 
adbfc5d
0ebe26e
 
 
 
adbfc5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfb7d5a
 
 
 
98cf86d
 
 
 
 
 
 
 
 
 
 
adbfc5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac40945
 
 
 
 
adbfc5d
 
 
 
 
 
 
 
 
 
 
 
 
 
8af7be8
 
 
 
 
 
 
 
 
ac71c07
 
 
 
 
46a10a9
 
98cf86d
46a10a9
8af7be8
46a10a9
 
8af7be8
46a10a9
8af7be8
 
 
 
46a10a9
 
ac71c07
 
 
 
 
 
 
 
 
8af7be8
 
98cf86d
 
 
 
 
 
 
 
 
 
adbfc5d
ac71c07
 
adbfc5d
 
 
 
 
 
5255536
 
 
adbfc5d
 
5255536
adbfc5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac71c07
adbfc5d
 
 
5255536
adbfc5d
5255536
adbfc5d
 
 
 
 
 
 
 
 
 
5255536
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac71c07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46a10a9
ac71c07
 
 
 
 
 
 
46a10a9
ac71c07
46a10a9
ac71c07
 
 
 
 
 
 
 
 
 
46a10a9
 
98cf86d
ac71c07
 
 
46a10a9
 
5b5507b
 
 
 
 
ac71c07
 
 
 
 
46a10a9
2a1ef7e
5b5507b
 
ac71c07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46a10a9
ac71c07
 
 
 
 
 
 
8af7be8
 
ac71c07
 
 
 
 
 
 
 
46a10a9
 
98cf86d
 
 
 
ac40945
 
5b5507b
 
2a1ef7e
 
2066a63
 
adbfc5d
 
ac40945
 
cfb7d5a
 
5b5507b
 
98cf86d
 
 
 
 
 
ac71c07
 
 
 
5b5507b
ac71c07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b5507b
 
ac71c07
 
 
adbfc5d
2a1ef7e
 
ac71c07
adbfc5d
 
 
cfb7d5a
 
 
 
 
98cf86d
 
 
 
 
 
 
 
 
ac71c07
 
2a1ef7e
2066a63
ac40945
98cf86d
 
 
ac71c07
 
 
 
 
 
 
 
 
 
cfb7d5a
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
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
#!/usr/bin/env python3
"""
Sign Language Gloss Q&A System - Individual NPZ Version
User inputs gloss, system generates corresponding pose video from individual NPZ files
"""

import torch
from PIL import Image
import numpy as np
import json
import os
import sys
import argparse
from pathlib import Path
import cv2
from tqdm import tqdm
import re
from datetime import datetime
import shutil
import subprocess
from typing import Optional

_DWposeDetector = None
_DWPOSE_IMPORT_ERROR = None


def _ensure_dwpose_imported():
    """Lazy import DWposeDetector to avoid hard dependency unless needed."""
    global _DWposeDetector, _DWPOSE_IMPORT_ERROR  # noqa: PLW0603
    if _DWposeDetector is not None or _DWPOSE_IMPORT_ERROR is not None:
        return
    try:
        from easy_dwpose import DWposeDetector  # type: ignore
        _DWposeDetector = DWposeDetector
    except Exception as exc:  # pylint: disable=broad-except
        _DWPOSE_IMPORT_ERROR = exc

from easy_dwpose.draw.controlnext import draw_pose as draw_pose_controlnext, process_pose_data
from easy_dwpose.draw.openpose import draw_pose as draw_pose_openpose
from utils.npz_interpolation import interpolate_pose_npz, ease_in_out_cubic
import copy

# Fixed configuration (resolve relative to this file so plugins/symlinks work)
BASE_DIR = Path(__file__).resolve().parent
POSE_DICT_ROOT = BASE_DIR / "pose_dict"
JSON_FILE = os.environ.get(
    "STABLE_SIGNER_GLOSS_JSON",
    str(POSE_DICT_ROOT / "WLASL_train.json"),
)  # JSON mapping file
NPZ_DIR = os.environ.get(
    "STABLE_SIGNER_NPZ_DIR",
    str(POSE_DICT_ROOT / "WLASL_train"),
)  # Directory containing NPZ files
OUTPUT_DIR = os.environ.get(
    "STABLE_SIGNER_OUTPUT_DIR",
    str(BASE_DIR / "generated_pose_video"),
)  # Output video directory

_FFMPEG_BINARY = None


def _known_ffmpeg_search_roots() -> list[Path]:
    roots = []
    env_hint = os.environ.get("STABLE_SIGNER_FFMPEG")
    if env_hint:
        roots.append(Path(env_hint).parent if Path(env_hint).is_file() else Path(env_hint))

    env_dir_hint = os.environ.get("STABLE_SIGNER_FFMPEG_DIR")
    if env_dir_hint:
        roots.append(Path(env_dir_hint))

    roots.extend(
        [
            BASE_DIR / "tools",
            Path.home() / "miniforge3",
            Path.home() / "miniconda3",
            Path.home() / "anaconda3",
            Path("/research/cbim/vast/sf895/miniforge3"),
        ]
    )

    # Remove duplicates while preserving order
    seen = set()
    unique_roots = []
    for root in roots:
        if not root:
            continue
        try:
            key = str(root.resolve())
        except Exception:
            key = str(root)
        if key in seen:
            continue
        seen.add(key)
        unique_roots.append(root)
    return unique_roots


def _probe_ffmpeg_in_known_locations() -> Optional[str]:
    patterns = [
        "lib/python*/site-packages/imageio_ffmpeg/binaries/ffmpeg*",
        "envs/*/lib/python*/site-packages/imageio_ffmpeg/binaries/ffmpeg*",
        "site-packages/imageio_ffmpeg/binaries/ffmpeg*",
        "imageio_ffmpeg/binaries/ffmpeg*",
        "ffmpeg*",
    ]
    for root in _known_ffmpeg_search_roots():
        if not root or not root.exists():
            continue
        for pattern in patterns:
            for candidate in root.glob(pattern):
                if candidate.is_file() and os.access(candidate, os.X_OK):
                    return str(candidate)
    return None


def _get_ffmpeg_binary() -> str:
    """Locate an FFmpeg executable that actually works inside this environment."""
    global _FFMPEG_BINARY  # noqa: PLW0603
    if _FFMPEG_BINARY:
        return _FFMPEG_BINARY

    try:
        from imageio_ffmpeg import get_ffmpeg_exe  # type: ignore

        ffmpeg_path = get_ffmpeg_exe()
        if ffmpeg_path and Path(ffmpeg_path).exists():
            _FFMPEG_BINARY = ffmpeg_path
            return ffmpeg_path
    except Exception:
        pass

    probed = _probe_ffmpeg_in_known_locations()
    if probed:
        _FFMPEG_BINARY = probed
        return probed

    fallback = shutil.which("ffmpeg")
    if fallback:
        _FFMPEG_BINARY = fallback
        return fallback

    # Last resort: just return string "ffmpeg" and let subprocess raise a clearer error.
    _FFMPEG_BINARY = "ffmpeg"
    return _FFMPEG_BINARY


class SignLanguageQA:
    def __init__(self, max_candidates=10):
        self.gloss_data = None
        self.load_json_mapping()
        self.detector = None  # Lazy load DWpose detector when needed
        self.max_candidates = max_candidates

    def load_json_mapping(self):
        """Load JSON mapping file"""
        try:
            json_path = Path(JSON_FILE)
            if not json_path.exists():
                print(f"❌ JSON file does not exist: {JSON_FILE}")
                sys.exit(1)

            print(f"📚 Loading JSON mapping: {JSON_FILE}")
            with open(json_path, 'r', encoding='utf-8') as f:
                self.gloss_data = json.load(f)

            print(f"✅ JSON loaded successfully!")
            print(f"   📊 Total glosses: {len(self.gloss_data)}")
            
            # Create gloss to video_ids mapping
            self.gloss_to_videos = {}
            for item in self.gloss_data:
                gloss = item['gloss'].upper()
                if gloss not in self.gloss_to_videos:
                    self.gloss_to_videos[gloss] = []
                for instance in item['instances']:
                    self.gloss_to_videos[gloss].append(instance['video_id'])

        except Exception as e:
            print(f"❌ JSON loading failed: {e}")
            sys.exit(1)

    def find_gloss_videos(self, gloss):
        """Find video_ids for a given gloss"""
        gloss_upper = gloss.upper()
        
        # Direct match
        if gloss_upper in self.gloss_to_videos:
            return self.gloss_to_videos[gloss_upper]
        
        # Fuzzy match
        matched_videos = []
        for g, videos in self.gloss_to_videos.items():
            if gloss_upper in g or g in gloss_upper:
                matched_videos.extend(videos)
        
        return list(set(matched_videos))  # Remove duplicates

    def load_video_npz(self, video_id):
        """Load NPZ file for a specific video"""
        npz_path = Path(NPZ_DIR) / f"{video_id}.npz"
        
        if not npz_path.exists():
            print(f"   ⚠️  NPZ file not found in Pose Dict: {npz_path}")
            return None
            
        try:
            npz_file = np.load(npz_path, allow_pickle=True)
            npz_dict = {key: npz_file[key] for key in npz_file.files}
            npz_file.close()
            return npz_dict
        except Exception as e:
            print(f"   ⚠️  Failed to load NPZ: {e}")
            return None
    
    def check_frame_quality(self, frame_data):
        """Check if a frame has valid pose data based on confidence scores"""
        if not frame_data:
            return False
        
        # Check hand scores (most critical for sign language)
        if 'hands_scores' in frame_data:
            hands_scores = frame_data['hands_scores']
            if hands_scores is not None and len(hands_scores) > 0:
                # Check if more than 80% of hand points have negative confidence
                valid_scores = hands_scores[hands_scores >= 0]
                if len(valid_scores) < len(hands_scores) * 0.2:
                    return False
        
        # Check body scores
        if 'body_scores' in frame_data:
            body_scores = frame_data['body_scores']
            if body_scores is not None and len(body_scores) > 0:
                valid_scores = body_scores[body_scores >= 0]
                if len(valid_scores) < len(body_scores) * 0.2:
                    return False
        
        return True
    
    def check_video_quality(self, npz_data, check_frames=5, extended_check_frames=30):
        """Check video quality by examining start and end frames"""
        total_frames = self.get_total_frames(npz_data)
        if total_frames == 0:
            return False, "No frames found"
        
        # Check first and last N frames
        problematic_start = 0
        problematic_end = 0
        
        # Check start frames
        for i in range(1, min(check_frames + 1, total_frames + 1)):
            frame_data = self.get_frame_data(npz_data, i)
            if not self.check_frame_quality(frame_data):
                problematic_start += 1
        
        # Check end frames
        for i in range(max(1, total_frames - check_frames + 1), total_frames + 1):
            frame_data = self.get_frame_data(npz_data, i)
            if not self.check_frame_quality(frame_data):
                problematic_end += 1
        
        # If more than 3 frames are problematic, do extended check
        if problematic_start >= 3 or problematic_end >= 3:
            print(f"   ⚠️  Initial check found {problematic_start} bad start frames, {problematic_end} bad end frames")
            
            # Extended check
            problematic_start_extended = 0
            problematic_end_extended = 0
            
            for i in range(1, min(extended_check_frames + 1, total_frames + 1)):
                frame_data = self.get_frame_data(npz_data, i)
                if not self.check_frame_quality(frame_data):
                    problematic_start_extended += 1
            
            for i in range(max(1, total_frames - extended_check_frames + 1), total_frames + 1):
                frame_data = self.get_frame_data(npz_data, i)
                if not self.check_frame_quality(frame_data):
                    problematic_end_extended += 1
            
            # If too many bad frames, reject video
            if problematic_start_extended > extended_check_frames * 0.5 or \
               problematic_end_extended > extended_check_frames * 0.5:
                return False, f"Too many bad frames: {problematic_start_extended} start, {problematic_end_extended} end"
        
        return True, f"Quality check passed (bad frames: {problematic_start} start, {problematic_end} end)"
    
    def get_valid_frame_range(self, npz_data, margin=5):
        """Get the range of valid frames, excluding bad frames at start/end"""
        total_frames = self.get_total_frames(npz_data)
        if total_frames == 0:
            return 1, 0
        
        # Find first valid frame
        start_frame = 1
        for i in range(1, min(margin + 1, total_frames + 1)):
            frame_data = self.get_frame_data(npz_data, i)
            if self.check_frame_quality(frame_data):
                start_frame = i
                break
            else:
                start_frame = i + 1
        
        # Find last valid frame
        end_frame = total_frames
        for i in range(total_frames, max(0, total_frames - margin), -1):
            frame_data = self.get_frame_data(npz_data, i)
            if self.check_frame_quality(frame_data):
                end_frame = i
                break
            else:
                end_frame = i - 1
        
        return start_frame, end_frame

    def get_frame_data(self, npz_data, frame_num):
        """Extract frame data from NPZ"""
        frame_key = f"frame_{frame_num:08d}"
        
        frame_data = {}
        # Extract all components for this frame
        for suffix in ['bodies', 'body_scores', 'hands', 'hands_scores', 'faces', 'faces_scores']:
            key = f"{frame_key}_{suffix}"
            if key in npz_data:
                frame_data[suffix] = npz_data[key]
        
        return frame_data if frame_data else None

    def get_total_frames(self, npz_data):
        """Get total number of frames in NPZ file"""
        frame_keys = [k for k in npz_data.keys() if k.startswith('frame_') and k.endswith('_bodies')]
        return len(frame_keys)

    def create_pose_frame(self, frame_data, width=480, height=480, scale_x=1.0, scale_y=1.0,
                          hide_torso_lines=False, y_offset=0, draw_style='controlnext',
                          conf_threshold=0.6):
        """Create single frame pose image with progressive scaling and optional y offset

        Args:
            draw_style: 'controlnext' or 'openpose'
        """
        try:
            # Apply progressive scaling if needed
            if scale_x != 1.0 or scale_y != 1.0:
                frame_data = self.apply_progressive_scaling(frame_data, scale_x, scale_y)

            # Apply y offset if provided
            if y_offset != 0:
                frame_data = self.apply_y_offset(frame_data, y_offset)

            if draw_style == 'openpose':
                filtered_frame = self.filter_pose_for_openpose(frame_data, conf_threshold=conf_threshold, update_subset=True)
                # Use OpenPose style (simpler, no processing needed)
                vis_img = draw_pose_openpose(
                    pose=filtered_frame,
                    height=height,
                    width=width,
                    include_face=True,
                    include_hands=True,
                    conf_threshold=conf_threshold
                )
                return vis_img
            else:
                filtered_frame = self.filter_pose_for_openpose(frame_data, conf_threshold=conf_threshold, update_subset=False)
                # Use ControlNeXt style (default, with advanced features)
                processed_pred = process_pose_data(filtered_frame, height, width)

                vis_img = draw_pose_controlnext(
                    pose=processed_pred,
                    H=height,
                    W=width,
                    include_body=True,
                    include_hand=True,
                    include_face=True,
                    hide_torso_lines=hide_torso_lines
                )

                return vis_img.transpose(1, 2, 0)

        except Exception as e:
            import traceback
            print(f"⚠️  Failed to create pose frame: {e}")
            print("Traceback:")
            traceback.print_exc()
            return None
    
    def apply_progressive_scaling(self, frame_data, scale_x, scale_y):
        """Apply progressive scaling - minimal at top, maximal at bottom"""
        scaled_data = copy.deepcopy(frame_data)
        
        # Process bodies
        if 'bodies' in scaled_data and scaled_data['bodies'] is not None:
            bodies = scaled_data['bodies'].copy()
            
            # Debug: check shape
            # print(f"Bodies shape: {bodies.shape}")
            
            # Find the top point (minimum Y) to use as anchor
            y_values = bodies[:, 1]
            valid_mask = y_values > 0
            valid_y = y_values[valid_mask]
            if len(valid_y) > 0:
                min_y = np.min(valid_y)
                max_y = np.max(valid_y)
                y_range = max_y - min_y if max_y > min_y else 1.0
                
                # Apply progressive scaling
                for i in range(len(bodies)):
                    if bodies[i, 1] > 0:  # Valid point
                        # Calculate progress from top to bottom (0 to 1)
                        progress = (bodies[i, 1] - min_y) / y_range
                        
                        # Progressive Y scaling: 1.0 at top, scale_y at bottom
                        y_scale = 1.0 + (scale_y - 1.0) * progress
                        
                        # Progressive X scaling: adjust to maintain proportions
                        x_scale = 1.0 + (scale_x - 1.0) * progress
                        
                        # Apply scaling relative to the top anchor point
                        # Y: scale from the top point
                        bodies[i, 1] = min_y + (bodies[i, 1] - min_y) * y_scale
                        
                        # X: scale from center of the pose
                        center_x = 0.5  # Assume normalized coordinates
                        bodies[i, 0] = center_x + (bodies[i, 0] - center_x) * x_scale
                
                scaled_data['bodies'] = bodies
        
        # Apply same scaling to hands
        if 'hands' in scaled_data and scaled_data['hands'] is not None:
            hands = scaled_data['hands'].copy()
            
            # Debug: check hands shape
            # print(f"Hands shape: {hands.shape}")
            
            # Find reference points for hands
            if 'bodies' in frame_data and frame_data['bodies'] is not None and len(frame_data['bodies']) > 0:
                # Use the same min_y from bodies
                y_values = frame_data['bodies'][:, 1]
                valid_mask = y_values > 0
                valid_y = y_values[valid_mask]
                if len(valid_y) > 0:
                    min_y = np.min(valid_y)
                    max_y = np.max(valid_y)
                    y_range = max_y - min_y if max_y > min_y else 1.0
                    
                    # Hands might be shape (2, 21, 2) or similar - iterate over hands
                    if len(hands.shape) == 3:
                        # Multiple hands
                        for h in range(hands.shape[0]):
                            for i in range(hands.shape[1]):
                                y_val = float(hands[h, i, 1])
                                if y_val > 0:  # Valid point
                                    progress = (y_val - min_y) / y_range
                                    progress = np.clip(progress, 0, 1)
                                    
                                    y_scale = 1.0 + (scale_y - 1.0) * progress
                                    x_scale = 1.0 + (scale_x - 1.0) * progress
                                    
                                    x_val = float(hands[h, i, 0])
                                    hands[h, i, 1] = min_y + (y_val - min_y) * y_scale
                                    center_x = 0.5
                                    hands[h, i, 0] = center_x + (x_val - center_x) * x_scale
                    else:
                        # Single array of points
                        for i in range(len(hands)):
                            y_val = float(hands[i, 1])
                            if y_val > 0:  # Valid point
                                progress = (y_val - min_y) / y_range
                                progress = np.clip(progress, 0, 1)
                                
                                y_scale = 1.0 + (scale_y - 1.0) * progress
                                x_scale = 1.0 + (scale_x - 1.0) * progress
                                
                                x_val = float(hands[i, 0])
                                hands[i, 1] = min_y + (y_val - min_y) * y_scale
                                center_x = 0.5
                                hands[i, 0] = center_x + (x_val - center_x) * x_scale
                    
                    scaled_data['hands'] = hands
        
        # Apply same scaling to faces
        if 'faces' in scaled_data and scaled_data['faces'] is not None:
            faces = scaled_data['faces'].copy()
            
            # Debug: check faces shape
            # print(f"Faces shape: {faces.shape}")
            
            # Faces are usually at the top, so apply minimal scaling
            if 'bodies' in frame_data and frame_data['bodies'] is not None and len(frame_data['bodies']) > 0:
                y_values = frame_data['bodies'][:, 1]
                valid_mask = y_values > 0
                valid_y = y_values[valid_mask]
                if len(valid_y) > 0:
                    min_y = np.min(valid_y)
                    max_y = np.max(valid_y)
                    y_range = max_y - min_y if max_y > min_y else 1.0
                    
                    # Faces might be shape (1, 68, 2) or similar - iterate properly
                    if len(faces.shape) == 3:
                        # Multiple faces
                        for f in range(faces.shape[0]):
                            for i in range(faces.shape[1]):
                                y_val = float(faces[f, i, 1])
                                if y_val > 0:  # Valid point
                                    progress = (y_val - min_y) / y_range
                                    progress = np.clip(progress, 0, 1)
                                    
                                    y_scale = 1.0 + (scale_y - 1.0) * progress
                                    x_scale = 1.0 + (scale_x - 1.0) * progress
                                    
                                    x_val = float(faces[f, i, 0])
                                    faces[f, i, 1] = min_y + (y_val - min_y) * y_scale
                                    center_x = 0.5
                                    faces[f, i, 0] = center_x + (x_val - center_x) * x_scale
                    else:
                        # Single array of points
                        for i in range(len(faces)):
                            y_val = float(faces[i, 1])
                            if y_val > 0:  # Valid point
                                progress = (y_val - min_y) / y_range
                                progress = np.clip(progress, 0, 1)
                                
                                y_scale = 1.0 + (scale_y - 1.0) * progress
                                x_scale = 1.0 + (scale_x - 1.0) * progress
                                
                                x_val = float(faces[i, 0])
                                faces[i, 1] = min_y + (y_val - min_y) * y_scale
                                center_x = 0.5
                                faces[i, 0] = center_x + (x_val - center_x) * x_scale
                    
                    scaled_data['faces'] = faces
        
        return scaled_data
    
    def apply_y_offset(self, frame_data, y_offset):
        """Apply vertical offset to all pose points"""
        offset_data = copy.deepcopy(frame_data)

        # Apply offset to bodies
        if 'bodies' in offset_data and offset_data['bodies'] is not None:
            offset_data['bodies'][:, 1] += y_offset

        # Apply offset to hands
        if 'hands' in offset_data and offset_data['hands'] is not None:
            if len(offset_data['hands'].shape) == 3:
                offset_data['hands'][:, :, 1] += y_offset
            else:
                offset_data['hands'][:, 1] += y_offset

        # Apply offset to faces
        if 'faces' in offset_data and offset_data['faces'] is not None:
            if len(offset_data['faces'].shape) == 3:
                offset_data['faces'][:, :, 1] += y_offset
            else:
                offset_data['faces'][:, 1] += y_offset

        return offset_data

    def filter_pose_for_openpose(self, frame_data, conf_threshold=0.6, update_subset=True):
        """Filter low-confidence joints before rendering to avoid ghost limbs

        Args:
            conf_threshold: minimum confidence needed to keep a joint
            update_subset: when True, rewrite body_scores as OpenPose subset (-1 removes joints)
        """
        filtered = copy.deepcopy(frame_data)

        # Bodies
        bodies = filtered.get('bodies', None)
        body_scores = filtered.get('body_scores', None)
        if bodies is not None:
            bodies = bodies.copy()
            min_valid = 1e-6

            coord_mask = (bodies[:, 0] > min_valid) & (bodies[:, 1] > min_valid)

            conf_mask = None
            if body_scores is not None:
                scores = np.array(body_scores, copy=False)
                if scores.ndim == 2:
                    score_vec = scores.reshape(-1)
                else:
                    score_vec = scores
                score_vec = score_vec.astype(float)
                conf_mask = score_vec < conf_threshold
                if conf_mask.shape[0] < bodies.shape[0]:
                    conf_mask = np.pad(conf_mask, (0, bodies.shape[0] - conf_mask.shape[0]), constant_values=False)
                elif conf_mask.shape[0] > bodies.shape[0]:
                    conf_mask = conf_mask[:bodies.shape[0]]
            if conf_mask is None:
                valid_mask = coord_mask
            else:
                valid_mask = coord_mask & (~conf_mask)

            bodies[~valid_mask, :] = 0
            filtered['bodies'] = bodies

            if update_subset:
                if body_scores is not None:
                    subset = np.array(body_scores, copy=True)
                    if subset.ndim == 1:
                        subset = subset.reshape(1, -1)
                else:
                    subset = np.arange(bodies.shape[0], dtype=float).reshape(1, -1)

                if subset.shape[1] < bodies.shape[0]:
                    subset = np.pad(subset, ((0, 0), (0, bodies.shape[0] - subset.shape[1])), constant_values=-1)
                elif subset.shape[1] > bodies.shape[0]:
                    subset = subset[:, :bodies.shape[0]]

                subset[:, ~valid_mask] = -1
                filtered['body_scores'] = subset

        # Hands
        hands = filtered.get('hands', None)
        hand_scores = filtered.get('hands_scores', None)
        if hands is not None and hand_scores is not None:
            scores = np.array(hand_scores)
            hands = hands.copy()
            if hands.ndim == 3 and scores.ndim == 3:
                for h in range(hands.shape[0]):
                    mask = (scores[h] < conf_threshold) | (scores[h] <= 0)
                    hands[h][mask, :] = 0
            elif hands.ndim == 3 and scores.ndim == 2:
                for h in range(hands.shape[0]):
                    mask = (scores[h] < conf_threshold) | (scores[h] <= 0)
                    hands[h][mask, :] = 0
            elif hands.ndim == 2 and scores.ndim == 2:
                mask = (scores < conf_threshold) | (scores <= 0)
                hands[mask, :] = 0
            elif hands.ndim == 2 and scores.ndim == 1:
                mask = (scores < conf_threshold) | (scores <= 0)
                hands[mask, :] = 0
            filtered['hands'] = hands

        # Faces
        faces = filtered.get('faces', None)
        face_scores = filtered.get('faces_scores', None)
        if faces is not None and face_scores is not None:
            scores = np.array(face_scores)
            faces = faces.copy()
            if faces.ndim == 3 and scores.ndim == 3:
                for f in range(faces.shape[0]):
                    mask = (scores[f] < conf_threshold) | (scores[f] <= 0)
                    faces[f][mask, :] = 0
            elif faces.ndim == 2 and scores.ndim == 2:
                mask = (scores < conf_threshold) | (scores <= 0)
                faces[mask, :] = 0
            elif faces.ndim == 2 and scores.ndim == 1:
                mask = (scores < conf_threshold) | (scores <= 0)
                faces[mask, :] = 0
            filtered['faces'] = faces

        return filtered

    def _is_valid_point(self, point):
        return point is not None and len(point) >= 2 and point[0] > 0 and point[1] > 0

    def _face_points_and_mask(self, faces):
        if faces is None:
            return None, None, None
        if faces.ndim == 3:
            if faces.shape[0] == 0:
                return None, None, None
            points = faces[0]
            owner = 0
        else:
            points = faces
            owner = None
        if points is None or len(points) == 0:
            return None, None, None
        mask = (points[:, 0] > 0) & (points[:, 1] > 0)
        if np.count_nonzero(mask) < 4:
            return None, None, None
        return points, mask, owner

    def _face_scale(self, points, mask):
        valid = points[mask, :2]
        if len(valid) < 4:
            return None
        min_xy = np.min(valid, axis=0)
        max_xy = np.max(valid, axis=0)
        scale = np.linalg.norm(max_xy - min_xy)
        return scale if scale > 1e-6 else None

    def _translate_nearest_hand_to_wrist_delta(self, frame_data, original_wrists, wrist_deltas):
        hands = frame_data.get('hands', None)
        if hands is None:
            return

        def choose_delta(root):
            candidates = []
            for wrist_name, wrist in original_wrists.items():
                if self._is_valid_point(wrist):
                    candidates.append((np.linalg.norm(root[:2] - wrist[:2]), wrist_deltas[wrist_name]))
            if not candidates:
                return None
            return min(candidates, key=lambda item: item[0])[1]

        if hands.ndim == 3:
            for hand_idx in range(hands.shape[0]):
                root = hands[hand_idx, 0]
                if not self._is_valid_point(root):
                    continue
                delta = choose_delta(root)
                if delta is not None:
                    valid = (hands[hand_idx, :, 0] > 0) & (hands[hand_idx, :, 1] > 0)
                    hands[hand_idx, valid, :2] += delta
        elif hands.ndim == 2 and len(hands) > 0:
            root = hands[0]
            if self._is_valid_point(root):
                delta = choose_delta(root)
                if delta is not None:
                    valid = (hands[:, 0] > 0) & (hands[:, 1] > 0)
                    hands[valid, :2] += delta

        hands[..., 0] = np.clip(hands[..., 0], 0.0, 1.0)
        hands[..., 1] = np.clip(hands[..., 1], 0.0, 1.0)
        frame_data['hands'] = hands

    def build_signer_template(self, npz_data, start_frame=1, end_frame=None):
        """Build a fixed signer template from a clip.

        The template stores median body keypoints, first-signer bone lengths, and
        face center/scale. It is intentionally conservative: torso/head/shoulders
        remain stable, while arms can later inherit directions from each word.
        """
        total_frames = self.get_total_frames(npz_data)
        if total_frames == 0:
            return None
        if end_frame is None:
            end_frame = total_frames
        start_frame = max(1, start_frame)
        end_frame = min(total_frames, end_frame)

        body_samples = []
        face_centers = []
        face_scales = []
        for frame_num in range(start_frame, end_frame + 1):
            frame_data = self.get_frame_data(npz_data, frame_num)
            if not frame_data:
                continue
            bodies = frame_data.get('bodies', None)
            if bodies is not None and len(bodies) >= 18:
                body_samples.append(bodies[:, :2].copy())
            faces = frame_data.get('faces', None)
            if faces is not None:
                points, mask, _owner = self._face_points_and_mask(faces)
                if points is not None:
                    face_centers.append(np.mean(points[mask, :2], axis=0))
                    scale = self._face_scale(points, mask)
                    if scale is not None:
                        face_scales.append(scale)

        if not body_samples:
            return None

        stack = np.stack(body_samples, axis=0)
        valid = (stack[..., 0] > 0) & (stack[..., 1] > 0)
        template_body = np.zeros((18, 2), dtype=np.float32)
        for j in range(18):
            m = valid[:, j]
            if np.any(m):
                template_body[j] = np.median(stack[m, j, :2], axis=0)

        body_bones = [
            (1, 0), (1, 2), (2, 3), (3, 4),
            (1, 5), (5, 6), (6, 7),
            (1, 8), (8, 9), (9, 10),
            (1, 11), (11, 12), (12, 13),
            (0, 14), (0, 15), (14, 16), (15, 17),
        ]
        lengths = {}
        for parent, child in body_bones:
            if self._is_valid_point(template_body[parent]) and self._is_valid_point(template_body[child]):
                length = float(np.linalg.norm(template_body[child] - template_body[parent]))
                if 0.002 < length < 0.8:
                    lengths[(parent, child)] = length

        template = {
            'body': template_body,
            'lengths': lengths,
            'face_center': np.median(face_centers, axis=0).astype(np.float32) if face_centers else None,
            'face_scale': float(np.median(face_scales)) if face_scales else None,
        }
        print("   🧍 First-signer template built")
        print(f"      Body template joints: {np.count_nonzero((template_body[:, 0] > 0) & (template_body[:, 1] > 0))}/18")
        if template['face_center'] is not None:
            print(f"      Face center: ({template['face_center'][0]:.3f}, {template['face_center'][1]:.3f})")
        return template

    def _retarget_arm_to_template(self, bodies, template_body, lengths, shoulder_idx, elbow_idx, wrist_idx):
        out = template_body.copy()
        shoulder = template_body[shoulder_idx]
        if not self._is_valid_point(shoulder):
            return out

        def direction(a, b, fallback):
            if self._is_valid_point(a) and self._is_valid_point(b):
                v = b[:2] - a[:2]
                n = np.linalg.norm(v)
                if n > 1e-6:
                    return v / n
            if self._is_valid_point(fallback[0]) and self._is_valid_point(fallback[1]):
                v = fallback[1] - fallback[0]
                n = np.linalg.norm(v)
                if n > 1e-6:
                    return v / n
            return np.array([0.0, 1.0], dtype=np.float32)

        upper_dir = direction(bodies[shoulder_idx], bodies[elbow_idx], (template_body[shoulder_idx], template_body[elbow_idx]))
        lower_dir = direction(bodies[elbow_idx], bodies[wrist_idx], (template_body[elbow_idx], template_body[wrist_idx]))
        upper_len = lengths.get((shoulder_idx, elbow_idx), np.linalg.norm(template_body[elbow_idx] - template_body[shoulder_idx]))
        lower_len = lengths.get((elbow_idx, wrist_idx), np.linalg.norm(template_body[wrist_idx] - template_body[elbow_idx]))
        out[elbow_idx] = shoulder + upper_dir * upper_len
        out[wrist_idx] = out[elbow_idx] + lower_dir * lower_len
        return out

    def retarget_pose_data_to_first_signer(self, npz_data, template, start_frame=1, end_frame=None, face_mode='retarget'):
        """Retarget a clip to the first signer's skeleton while preserving arm/hand motion.

        Torso/head/shoulders/hips use the first signer template. Elbow/wrist use
        the current clip's arm directions with first-signer bone lengths. Hands
        are translated by wrist deltas. Face local shape may come from the clip,
        but its center/scale is aligned to the first signer.
        """
        if template is None or template.get('body') is None:
            return npz_data
        total_frames = self.get_total_frames(npz_data)
        if total_frames == 0:
            return npz_data
        if end_frame is None:
            end_frame = total_frames
        start_frame = max(1, start_frame)
        end_frame = min(total_frames, end_frame)

        template_body = template['body']
        lengths = template.get('lengths', {})
        face_center = template.get('face_center')
        face_scale = template.get('face_scale')

        print("   🧍 Retargeting clip to first signer template")
        for frame_num in range(start_frame, end_frame + 1):
            frame_key = f"frame_{frame_num:08d}"
            bodies_key = f"{frame_key}_bodies"
            if bodies_key not in npz_data or npz_data[bodies_key] is None:
                continue
            bodies = npz_data[bodies_key].copy()
            if len(bodies) < 18:
                continue
            original_wrists = {
                'right': bodies[4, :2].copy() if len(bodies) > 4 else None,
                'left': bodies[7, :2].copy() if len(bodies) > 7 else None,
            }

            new_body_xy = template_body.copy()
            right_arm = self._retarget_arm_to_template(bodies, template_body, lengths, 2, 3, 4)
            left_arm = self._retarget_arm_to_template(bodies, template_body, lengths, 5, 6, 7)
            new_body_xy[[3, 4]] = right_arm[[3, 4]]
            new_body_xy[[6, 7]] = left_arm[[6, 7]]

            new_bodies = bodies.copy()
            valid_template = (new_body_xy[:, 0] > 0) & (new_body_xy[:, 1] > 0)
            new_bodies[valid_template, :2] = new_body_xy[valid_template]
            new_bodies[:, 0] = np.clip(new_bodies[:, 0], 0.0, 1.0)
            new_bodies[:, 1] = np.clip(new_bodies[:, 1], 0.0, 1.0)
            npz_data[bodies_key] = new_bodies

            wrist_deltas = {
                'right': new_bodies[4, :2] - original_wrists['right'] if original_wrists['right'] is not None and len(new_bodies) > 4 else np.zeros(2),
                'left': new_bodies[7, :2] - original_wrists['left'] if original_wrists['left'] is not None and len(new_bodies) > 7 else np.zeros(2),
            }
            frame_data = self.get_frame_data(npz_data, frame_num)
            if frame_data:
                self._translate_nearest_hand_to_wrist_delta(frame_data, original_wrists, wrist_deltas)
                hands_key = f"{frame_key}_hands"
                if hands_key in npz_data and 'hands' in frame_data:
                    npz_data[hands_key] = frame_data['hands']

            faces_key = f"{frame_key}_faces"
            if face_mode != 'none' and face_center is not None and faces_key in npz_data and npz_data[faces_key] is not None:
                faces = npz_data[faces_key].copy()
                points, mask, owner = self._face_points_and_mask(faces)
                if points is not None:
                    current_center = np.mean(points[mask, :2], axis=0)
                    scaled_points = points.copy()
                    if face_scale is not None:
                        current_scale = self._face_scale(points, mask)
                        if current_scale is not None and current_scale > 1e-6:
                            scaled_points[mask, :2] = current_center + (points[mask, :2] - current_center) * (face_scale / current_scale)
                    shifted_center = np.mean(scaled_points[mask, :2], axis=0)
                    scaled_points[mask, :2] += face_center - shifted_center
                    if owner is None:
                        faces = scaled_points
                    else:
                        faces[owner] = scaled_points
                    faces[..., 0] = np.clip(faces[..., 0], 0.0, 1.0)
                    faces[..., 1] = np.clip(faces[..., 1], 0.0, 1.0)
                    npz_data[faces_key] = faces

        return npz_data

    def stabilize_pose_data(self, npz_data, start_frame=1, end_frame=None, body_smoothing_alpha=0.75):
        """Stabilize a pose clip with fixed body bone lengths and fixed face scale."""
        total_frames = self.get_total_frames(npz_data)
        if total_frames == 0:
            return npz_data
        if end_frame is None:
            end_frame = total_frames
        start_frame = max(1, start_frame)
        end_frame = min(total_frames, end_frame)
        if start_frame > end_frame:
            return npz_data

        body_bones = [
            (1, 0),
            (1, 2), (2, 3), (3, 4),
            (1, 5), (5, 6), (6, 7),
            (1, 8), (8, 9), (9, 10),
            (1, 11), (11, 12), (12, 13),
            (0, 14), (0, 15), (14, 16), (15, 17),
        ]

        bone_lengths = {bone: [] for bone in body_bones}
        face_scales = []

        for frame_num in range(start_frame, end_frame + 1):
            frame_data = self.get_frame_data(npz_data, frame_num)
            if not frame_data or 'bodies' not in frame_data:
                continue
            bodies = frame_data['bodies']
            if bodies is not None:
                for parent, child in body_bones:
                    if parent < len(bodies) and child < len(bodies):
                        if self._is_valid_point(bodies[parent]) and self._is_valid_point(bodies[child]):
                            length = np.linalg.norm(bodies[child, :2] - bodies[parent, :2])
                            if 0.002 < length < 0.8:
                                bone_lengths[(parent, child)].append(length)

            faces = frame_data.get('faces', None)
            if faces is not None:
                points, mask, _owner = self._face_points_and_mask(faces)
                if points is not None:
                    scale = self._face_scale(points, mask)
                    if scale is not None and 0.002 < scale < 0.8:
                        face_scales.append(scale)

        median_lengths = {
            bone: float(np.median(lengths))
            for bone, lengths in bone_lengths.items()
            if lengths
        }
        median_face_scale = float(np.median(face_scales)) if face_scales else None

        if not median_lengths and median_face_scale is None:
            print("   ⚠️  Skeleton stabilization skipped: insufficient valid body/face data")
            return npz_data

        print("   🦴 Skeleton stabilization enabled")
        if median_lengths:
            print(f"      Fixed body bones: {len(median_lengths)}")
        if median_face_scale is not None:
            print(f"      Fixed face scale: {median_face_scale:.3f}")

        for frame_num in range(start_frame, end_frame + 1):
            frame_key = f"frame_{frame_num:08d}"
            bodies_key = f"{frame_key}_bodies"
            if bodies_key in npz_data and npz_data[bodies_key] is not None:
                bodies = npz_data[bodies_key].copy()
                original_wrists = {
                    'right': bodies[4, :2].copy() if len(bodies) > 4 else None,
                    'left': bodies[7, :2].copy() if len(bodies) > 7 else None,
                }

                for parent, child in body_bones:
                    target_len = median_lengths.get((parent, child))
                    if target_len is None or parent >= len(bodies) or child >= len(bodies):
                        continue
                    if not self._is_valid_point(bodies[parent]) or not self._is_valid_point(bodies[child]):
                        continue
                    direction = bodies[child, :2] - bodies[parent, :2]
                    current_len = np.linalg.norm(direction)
                    if current_len <= 1e-6:
                        continue
                    bodies[child, :2] = bodies[parent, :2] + direction / current_len * target_len

                bodies[:, 0] = np.clip(bodies[:, 0], 0.0, 1.0)
                bodies[:, 1] = np.clip(bodies[:, 1], 0.0, 1.0)
                npz_data[bodies_key] = bodies

                wrist_deltas = {
                    'right': bodies[4, :2] - original_wrists['right'] if original_wrists['right'] is not None and len(bodies) > 4 else np.zeros(2),
                    'left': bodies[7, :2] - original_wrists['left'] if original_wrists['left'] is not None and len(bodies) > 7 else np.zeros(2),
                }
                frame_data = self.get_frame_data(npz_data, frame_num)
                if frame_data:
                    self._translate_nearest_hand_to_wrist_delta(frame_data, original_wrists, wrist_deltas)
                    hands_key = f"{frame_key}_hands"
                    if hands_key in npz_data and 'hands' in frame_data:
                        npz_data[hands_key] = frame_data['hands']

            faces_key = f"{frame_key}_faces"
            if median_face_scale is not None and faces_key in npz_data and npz_data[faces_key] is not None:
                faces = npz_data[faces_key].copy()
                points, mask, owner = self._face_points_and_mask(faces)
                if points is not None:
                    current_scale = self._face_scale(points, mask)
                    if current_scale is not None and current_scale > 1e-6:
                        center = np.mean(points[mask, :2], axis=0)
                        scaled_points = points.copy()
                        scaled_points[mask, :2] = center + (points[mask, :2] - center) * (median_face_scale / current_scale)
                        if owner is None:
                            faces = scaled_points
                        else:
                            faces[owner] = scaled_points
                        faces[..., 0] = np.clip(faces[..., 0], 0.0, 1.0)
                        faces[..., 1] = np.clip(faces[..., 1], 0.0, 1.0)
                        npz_data[faces_key] = faces

        previous_bodies = None
        for frame_num in range(start_frame, end_frame + 1):
            frame_key = f"frame_{frame_num:08d}"
            bodies_key = f"{frame_key}_bodies"
            if bodies_key not in npz_data or npz_data[bodies_key] is None:
                continue
            bodies = npz_data[bodies_key].copy()
            if previous_bodies is not None and previous_bodies.shape == bodies.shape:
                original_wrists = {
                    'right': bodies[4, :2].copy() if len(bodies) > 4 else None,
                    'left': bodies[7, :2].copy() if len(bodies) > 7 else None,
                }
                valid = (
                    (bodies[:, 0] > 0) & (bodies[:, 1] > 0) &
                    (previous_bodies[:, 0] > 0) & (previous_bodies[:, 1] > 0)
                )
                bodies[valid, :2] = (
                    body_smoothing_alpha * bodies[valid, :2] +
                    (1.0 - body_smoothing_alpha) * previous_bodies[valid, :2]
                )
                bodies[:, 0] = np.clip(bodies[:, 0], 0.0, 1.0)
                bodies[:, 1] = np.clip(bodies[:, 1], 0.0, 1.0)
                npz_data[bodies_key] = bodies

                wrist_deltas = {
                    'right': bodies[4, :2] - original_wrists['right'] if original_wrists['right'] is not None and len(bodies) > 4 else np.zeros(2),
                    'left': bodies[7, :2] - original_wrists['left'] if original_wrists['left'] is not None and len(bodies) > 7 else np.zeros(2),
                }
                frame_data = self.get_frame_data(npz_data, frame_num)
                if frame_data:
                    self._translate_nearest_hand_to_wrist_delta(frame_data, original_wrists, wrist_deltas)
                    hands_key = f"{frame_key}_hands"
                    if hands_key in npz_data and 'hands' in frame_data:
                        npz_data[hands_key] = frame_data['hands']

            previous_bodies = bodies.copy()

        return npz_data

    def normalize_pose_data(self, npz_data, reference_point='neck', scale_by='shoulders',
                             target_shoulder_width=0.35, target_shoulder_y=0.45):
        """
        Normalize pose data to a standard coordinate system
        This ensures different videos are in the same coordinate space

        Args:
            npz_data: NPZ data containing pose information
            reference_point: 'neck' or 'hips' - point to center on (default: 'neck')
            scale_by: 'shoulders' or 'height' - measure for scaling (default: 'shoulders')
            target_shoulder_width: Desired horizontal distance between shoulders after normalization
            target_shoulder_y: Desired Y coordinate for the shoulder line

        Returns:
            Normalized NPZ data (modifies in-place)
        """
        total_frames = self.get_total_frames(npz_data)
        if total_frames == 0:
            return npz_data

        # Collect reference points, scale factors, and shoulder heights across all frames
        reference_positions = []
        scale_factors = []
        shoulder_y_positions = []

        for frame_num in range(1, total_frames + 1):
            frame_data = self.get_frame_data(npz_data, frame_num)
            if not frame_data or 'bodies' not in frame_data:
                continue

            bodies = frame_data['bodies']
            if bodies is None or len(bodies) == 0:
                continue

            # Calculate reference point
            if reference_point == 'neck':
                # Neck is typically index 1 in body keypoints
                if len(bodies) > 1 and bodies[1, 0] > 0 and bodies[1, 1] > 0:
                    ref_pos = bodies[1, :2].copy()
                else:
                    continue
            elif reference_point == 'hips':
                # Hip center: average of left hip (11) and right hip (12)
                if len(bodies) > 12:
                    left_hip = bodies[11, :2]
                    right_hip = bodies[12, :2]
                    if left_hip[0] > 0 and right_hip[0] > 0:
                        ref_pos = (left_hip + right_hip) / 2
                    else:
                        continue
                else:
                    continue
            else:
                continue

            reference_positions.append(ref_pos)

            # Calculate scale factor
            if scale_by == 'shoulders':
                # Shoulder width: distance between left shoulder (5) and right shoulder (2)
                if len(bodies) > 5:
                    left_shoulder = bodies[5, :2]
                    right_shoulder = bodies[2, :2]
                    if left_shoulder[0] > 0 and right_shoulder[0] > 0:
                        shoulder_width = np.linalg.norm(left_shoulder - right_shoulder)
                        if shoulder_width > 0.01:  # Avoid division by very small numbers
                            scale_factors.append(shoulder_width)
                            shoulder_mid_y = (left_shoulder[1] + right_shoulder[1]) / 2
                            shoulder_y_positions.append(shoulder_mid_y)
            elif scale_by == 'height':
                # Approximate height: distance from neck to hip center
                if len(bodies) > 12:
                    neck = bodies[1, :2]
                    left_hip = bodies[11, :2]
                    right_hip = bodies[12, :2]
                    if neck[1] > 0 and left_hip[0] > 0 and right_hip[0] > 0:
                        hip_center = (left_hip + right_hip) / 2
                        height = np.linalg.norm(neck - hip_center)
                        if height > 0.01:
                            scale_factors.append(height)

        if not reference_positions or not scale_factors:
            print("   ⚠️  Normalization skipped: insufficient valid frames")
            return npz_data

        # Use median reference position and scale factor for robustness
        median_ref_pos = np.median(reference_positions, axis=0)
        median_scale = np.median(scale_factors)

        median_shoulder_y = np.median(shoulder_y_positions) if shoulder_y_positions else median_ref_pos[1]

        print(f"   📏 Normalization: ref={reference_point}, scale={scale_by}")
        print(f"      Reference position: ({median_ref_pos[0]:.3f}, {median_ref_pos[1]:.3f})")
        print(f"      Median shoulder y: {median_shoulder_y:.3f}")
        print(f"      Median shoulder width: {median_scale:.3f} → target {target_shoulder_width:.3f}")

        # Determine uniform scaling factor so shoulders match the desired width
        width_scale = target_shoulder_width / median_scale if median_scale > 0 else 1.0

        # Neck-centered offset already moves the neck to 0.5; compute extra offset so shoulders sit at desired y
        shoulder_delta_from_neck = median_shoulder_y - median_ref_pos[1]
        normalized_shoulder_y = 0.5 + shoulder_delta_from_neck * width_scale
        vertical_offset = target_shoulder_y - normalized_shoulder_y

        # Apply normalization to all frames
        for frame_num in range(1, total_frames + 1):
            frame_key = f"frame_{frame_num:08d}"

            # Normalize bodies
            bodies_key = f"{frame_key}_bodies"
            if bodies_key in npz_data:
                bodies = npz_data[bodies_key].copy()
                if bodies is not None and len(bodies) > 0:
                    # Center on reference point
                    for i in range(len(bodies)):
                        if bodies[i, 0] > 0 and bodies[i, 1] > 0:
                            bodies[i, :2] = (bodies[i, :2] - median_ref_pos) * width_scale + 0.5
                            bodies[i, 1] += vertical_offset

                    # Clamp to drawing range
                    bodies[:, 0] = np.clip(bodies[:, 0], 0.0, 1.0)
                    bodies[:, 1] = np.clip(bodies[:, 1], 0.0, 1.0)
                    npz_data[bodies_key] = bodies

            # Normalize hands
            hands_key = f"{frame_key}_hands"
            if hands_key in npz_data:
                hands = npz_data[hands_key].copy()
                if hands is not None:
                    if len(hands.shape) == 3:
                        # Multiple hands
                        for h in range(hands.shape[0]):
                            for i in range(hands.shape[1]):
                                if hands[h, i, 0] > 0 and hands[h, i, 1] > 0:
                                    hands[h, i, :2] = (hands[h, i, :2] - median_ref_pos) * width_scale + 0.5
                                    hands[h, i, 1] += vertical_offset
                    else:
                        # Single array
                        for i in range(len(hands)):
                            if hands[i, 0] > 0 and hands[i, 1] > 0:
                                hands[i, :2] = (hands[i, :2] - median_ref_pos) * width_scale + 0.5
                                hands[i, 1] += vertical_offset

                    hands[..., 0] = np.clip(hands[..., 0], 0.0, 1.0)
                    hands[..., 1] = np.clip(hands[..., 1], 0.0, 1.0)
                    npz_data[hands_key] = hands

            # Normalize faces
            faces_key = f"{frame_key}_faces"
            if faces_key in npz_data:
                faces = npz_data[faces_key].copy()
                if faces is not None:
                    if len(faces.shape) == 3:
                        # Multiple faces
                        for f in range(faces.shape[0]):
                            for i in range(faces.shape[1]):
                                if faces[f, i, 0] > 0 and faces[f, i, 1] > 0:
                                    faces[f, i, :2] = (faces[f, i, :2] - median_ref_pos) * width_scale + 0.5
                                    faces[f, i, 1] += vertical_offset
                    else:
                        # Single array
                        for i in range(len(faces)):
                            if faces[i, 0] > 0 and faces[i, 1] > 0:
                                faces[i, :2] = (faces[i, :2] - median_ref_pos) * width_scale + 0.5
                                faces[i, 1] += vertical_offset

                    faces[..., 0] = np.clip(faces[..., 0], 0.0, 1.0)
                    faces[..., 1] = np.clip(faces[..., 1], 0.0, 1.0)
                    npz_data[faces_key] = faces

        return npz_data
    
    def get_reference_head_top(self, ref_image_path, width, height):
        """Get the top of head position from reference image"""
        try:
            # Lazy load detector
            _ensure_dwpose_imported()
            if _DWposeDetector is None:
                if _DWPOSE_IMPORT_ERROR:
                    print(f"⚠️  DWposeDetector unavailable: {_DWPOSE_IMPORT_ERROR}")
                else:
                    print("⚠️  DWposeDetector module not available")
                return None
            if self.detector is None:
                device = "cuda:0" if torch.cuda.is_available() else "cpu"
                self.detector = _DWposeDetector(device=device)
            
            # Load and detect pose in reference image
            ref_image = Image.open(ref_image_path).convert("RGB")
            
            # Resize reference image to match target dimensions
            ref_image = ref_image.resize((width, height), Image.LANCZOS)
            
            # Detect pose
            pose_data = self.detector(ref_image, draw_pose=False)
            
            # Find head top from face points
            if 'faces' in pose_data and pose_data['faces'] is not None and len(pose_data['faces']) > 0:
                faces = pose_data['faces']
                if len(faces.shape) == 3:
                    # Multiple faces, use first one
                    face_points = faces[0]
                else:
                    face_points = faces
                
                # Get all valid Y coordinates
                y_coords = face_points[:, 1]
                valid_y = y_coords[y_coords > 0]
                
                if len(valid_y) > 0:
                    # Head top is the minimum Y coordinate (top of the image)
                    head_top_y = np.min(valid_y)
                    return head_top_y
            
            # If no face found, try to use body points
            if 'bodies' in pose_data and pose_data['bodies'] is not None:
                bodies = pose_data['bodies']
                # Look for head-related points (eyes, ears, nose)
                # Indices 0=nose, 14=right eye, 15=left eye, 16=right ear, 17=left ear
                head_indices = [0, 14, 15, 16, 17]
                head_y_coords = []
                
                for idx in head_indices:
                    if idx < len(bodies) and bodies[idx, 1] > 0:
                        head_y_coords.append(bodies[idx, 1])
                
                if head_y_coords:
                    return min(head_y_coords)
            
            return None
            
        except Exception as e:
            print(f"⚠️  Failed to get reference head position: {e}")
            return None

    def calculate_neck_centrality_score(self, npz_data):
        """Calculate how centered the neck position is in the video

        Returns a score from 0 to 1, where 1 means perfectly centered
        Lower score means the person is more off-center
        """
        neck_x_positions = []

        # Sample frames throughout the video
        total_frames = self.get_total_frames(npz_data)
        sample_frames = [0, total_frames // 4, total_frames // 2, 3 * total_frames // 4, total_frames - 1]

        for frame_num in sample_frames:
            if frame_num >= total_frames:
                continue

            frame_data = self.get_frame_data(npz_data, frame_num)
            if frame_data and 'bodies' in frame_data:
                bodies = frame_data['bodies']
                # Neck is typically index 1 in body keypoints
                if len(bodies) > 1 and bodies[1, 0] > 0:
                    neck_x_positions.append(bodies[1, 0])

        if not neck_x_positions:
            return 0.0  # No valid neck positions found

        # Calculate average neck X position
        avg_neck_x = np.mean(neck_x_positions)

        # Calculate distance from center (0.5)
        # Score is higher when closer to center
        distance_from_center = abs(avg_neck_x - 0.5)
        centrality_score = 1.0 - (distance_from_center * 2)  # Scale to 0-1

        return max(0.0, centrality_score)  # Ensure non-negative

    def get_pose_head_top(self, frame_data):
        """Get the top of head position from pose frame data"""
        # Try faces first
        if 'faces' in frame_data and frame_data['faces'] is not None:
            faces = frame_data['faces']
            if len(faces.shape) == 3:
                # Multiple faces, use first one
                face_points = faces[0]
            else:
                face_points = faces
            
            # Get all valid Y coordinates
            y_coords = face_points[:, 1]
            valid_y = y_coords[y_coords > 0]
            
            if len(valid_y) > 0:
                return np.min(valid_y)
        
        # Fall back to body points
        if 'bodies' in frame_data and frame_data['bodies'] is not None:
            bodies = frame_data['bodies']
            # Look for head-related points
            head_indices = [0, 14, 15, 16, 17]  # nose, eyes, ears
            head_y_coords = []
            
            for idx in head_indices:
                if idx < len(bodies) and bodies[idx, 1] > 0:
                    head_y_coords.append(bodies[idx, 1])
            
            if head_y_coords:
                return min(head_y_coords)
        
        return None

    def generate_video_from_glosses(self, gloss_list, output_path, fps=25, width=480, height=480,
                                    smoothing_frames=5, smoothing_method='none', npz_interpolation_frames=0,
                                    scale_x=1.0, scale_y=1.0, hide_torso_lines=False, ref_image_path=None,
                                    draw_style='controlnext', normalize_pose=True, draw_conf_threshold=0.6,
                                    stabilize_skeleton=False, npz_interpolation_method='body-anchor',
                                    retarget_to_first_signer=True, retarget_face_mode='retarget',
                                    frame_callback=None):
        """Generate video from gloss list with optional progressive scaling and head alignment

        Args:
            draw_style: 'controlnext' (default) or 'openpose' - drawing style for pose visualization
            normalize_pose: Whether to normalize pose data to standard coordinate system (default: True)
        """
        # Create output directory
        output_path.parent.mkdir(parents=True, exist_ok=True)
        
        # Get reference head position if provided
        ref_head_top = None
        y_offset = 0
        if ref_image_path:
            ref_head_top = self.get_reference_head_top(ref_image_path, width, height)
            if ref_head_top is not None:
                print(f"📏 Reference head top position: {ref_head_top:.2f}")
        
        # Collect all frames from all glosses
        all_pose_frames = []
        all_npz_data = []  # Store NPZ data for interpolation
        video_info = []
        first_signer_template = None
        streamed_frame_count = 0
        incremental_stream = frame_callback is not None and smoothing_method == 'none'

        def emit_stream_frame(frame, total_frames=None):
            nonlocal streamed_frame_count
            if frame_callback is None or frame is None:
                return
            try:
                frame_callback(streamed_frame_count, frame, total_frames or 0)
                streamed_frame_count += 1
            except Exception as cb_err:
                print(f"⚠️  Frame callback failed at {streamed_frame_count}: {cb_err}")

        def build_interpolated_visual_frames(prev_info, curr_info):
            if npz_interpolation_frames <= 0:
                return []
            npz1 = prev_info['npz_data']
            npz2 = curr_info['npz_data']
            end_frame1 = prev_info.get('end_frame', self.get_total_frames(npz1))
            start_frame2 = curr_info.get('start_frame', 1)
            interpolated_npz_frames = interpolate_pose_npz(
                npz1, npz2,
                num_frames=npz_interpolation_frames,
                method=npz_interpolation_method,
                frame1_num=end_frame1,
                frame2_num=start_frame2
            )
            interpolated_frames = []
            for interp_data in interpolated_npz_frames:
                frame_keys = [k for k in interp_data.keys() if k.endswith('_bodies')]
                if not frame_keys:
                    continue
                frame_key = frame_keys[0]
                frame_num = int(frame_key.split('_')[1])
                frame_data = {}
                for suffix in ['bodies', 'body_scores', 'hands', 'hands_scores', 'faces', 'faces_scores']:
                    key = f"frame_{frame_num:08d}_{suffix}"
                    if key in interp_data:
                        frame_data[suffix] = interp_data[key]
                if not frame_data:
                    continue
                pose_frame = self.create_pose_frame(
                    frame_data, width, height, scale_x, scale_y,
                    hide_torso_lines, y_offset, draw_style,
                    conf_threshold=draw_conf_threshold
                )
                if pose_frame is not None:
                    interpolated_frames.append(pose_frame)
            return interpolated_frames

        for gloss in gloss_list:
            matched_videos = self.find_gloss_videos(gloss)
            total_matches = len(matched_videos)
            
            if not matched_videos:
                print(f"❌ '{gloss}' -> No matching Pose unit found")
                continue
            
            if self.max_candidates and total_matches > self.max_candidates:
                print(f"   ℹ️ Limiting candidates to first {self.max_candidates} (out of {total_matches}) for efficiency")
                matched_videos = matched_videos[:self.max_candidates]
            
            print(f"🎯 '{gloss}' -> Found {total_matches} Unit in Pose Dict")
            print(f"   🔍 Evaluating {len(matched_videos)} candidate(s)")

            # Evaluate all videos and select the best one based on quality and centering
            candidate_videos = []

            for idx, video_id in enumerate(matched_videos):
                npz_data = self.load_video_npz(video_id)
                if npz_data is not None:
                    total_frames = self.get_total_frames(npz_data)

                    # Check video quality
                    is_good_quality, quality_msg = self.check_video_quality(npz_data)

                    if not is_good_quality:
                        continue

                    # Get valid frame range
                    start_frame, end_frame = self.get_valid_frame_range(npz_data)
                    if start_frame > end_frame:
                        continue

                    # Calculate neck centrality score
                    centrality_score = self.calculate_neck_centrality_score(npz_data)

                    candidate_videos.append({
                        'video_id': video_id,
                        'npz_data': npz_data,
                        'total_frames': total_frames,
                        'start_frame': start_frame,
                        'end_frame': end_frame,
                        'quality_msg': quality_msg,
                        'centrality_score': centrality_score
                    })

            if not candidate_videos:
                print(f"   ❌ No good quality poses dict found for '{gloss}'")
                continue

            # Select video with best centrality score
            best_video = max(candidate_videos, key=lambda x: x['centrality_score'])
            video_id = best_video['video_id']
            npz_data = best_video['npz_data']
            total_frames = best_video['total_frames']
            start_frame = best_video['start_frame']
            end_frame = best_video['end_frame']
            quality_msg = best_video['quality_msg']
            centrality_score = best_video['centrality_score']

            print(f"   📹 {video_id}: {total_frames} frames")
            print(f"   ✅ {quality_msg}")
            print(f"   🎯 Centrality score: {centrality_score:.2f} (selected from {len(candidate_videos)} candidates)")
            print(f"   📊 Using frames {start_frame} to {end_frame} (out of {total_frames})")

            # Apply normalization if enabled
            if normalize_pose:
                npz_data = self.normalize_pose_data(npz_data, reference_point='neck', scale_by='shoulders')

            if stabilize_skeleton:
                npz_data = self.stabilize_pose_data(npz_data, start_frame=start_frame, end_frame=end_frame)

            if retarget_to_first_signer:
                if first_signer_template is None:
                    first_signer_template = self.build_signer_template(npz_data, start_frame=start_frame, end_frame=end_frame)
                npz_data = self.retarget_pose_data_to_first_signer(
                    npz_data, first_signer_template, start_frame=start_frame, end_frame=end_frame,
                    face_mode=retarget_face_mode
                )

            # Store NPZ data for potential interpolation
            all_npz_data.append(npz_data)

            # Extract frames within valid range
            gloss_frames = []
            for frame_num in range(start_frame, end_frame + 1):
                frame_data = self.get_frame_data(npz_data, frame_num)
                if frame_data and self.check_frame_quality(frame_data):
                    # Calculate y offset for first frame if reference provided
                    if ref_head_top is not None and y_offset == 0 and frame_num == start_frame:
                        # Get head top from current pose
                        current_head_top = self.get_pose_head_top(frame_data)
                        if current_head_top is not None:
                            y_offset = ref_head_top - current_head_top
                            print(f"📐 Calculated Y offset: {y_offset:.2f}")

                    pose_frame = self.create_pose_frame(
                        frame_data, width, height, scale_x, scale_y,
                        hide_torso_lines, y_offset, draw_style,
                        conf_threshold=draw_conf_threshold
                    )
                    if pose_frame is not None:
                        gloss_frames.append(pose_frame)

            if gloss_frames:
                all_pose_frames.append(gloss_frames)
                video_info.append({
                    'gloss': gloss,
                    'video_id': video_id,
                    'frame_count': len(gloss_frames),
                    'npz_data': npz_data,
                    'start_frame': start_frame,
                    'end_frame': end_frame
                })
                print(f"   ✅ Generated {len(gloss_frames)} pose frames")

                if incremental_stream:
                    if len(video_info) > 1 and npz_interpolation_frames > 0:
                        prev_info = video_info[-2]
                        interp_frames = build_interpolated_visual_frames(prev_info, video_info[-1])
                        for pose_frame in interp_frames:
                            emit_stream_frame(pose_frame)
                    for pose_frame in gloss_frames:
                        emit_stream_frame(pose_frame)
        
        if not all_pose_frames:
            print("❌ No frames generated")
            return False
        
        # Apply NPZ interpolation if requested
        if npz_interpolation_frames > 0 and len(all_pose_frames) > 1:
            print(f"🔄 Applying NPZ interpolation with {npz_interpolation_frames} frames ({npz_interpolation_method})...")
            interpolated_pose_frames = []

            for i in range(len(all_pose_frames)):
                interpolated_pose_frames.extend(all_pose_frames[i])

                if i < len(all_pose_frames) - 1:
                    interp_frames = build_interpolated_visual_frames(video_info[i], video_info[i + 1])
                    interpolated_pose_frames.extend(interp_frames)
                    print(f"   ✅ Added {len(interp_frames)} interpolated frames between '{video_info[i]['gloss']}' and '{video_info[i+1]['gloss']}'")

            all_pose_frames = [interpolated_pose_frames]  # Treat as single sequence
        
        # Apply smoothing if needed
        if smoothing_method != 'none' and len(all_pose_frames) > 1:
            final_frames = self.apply_smoothing(all_pose_frames, smoothing_frames, smoothing_method)
        else:
            # Concatenate all frames
            final_frames = []
            for group in all_pose_frames:
                final_frames.extend(group)
        
        # For smoothed outputs, stream after final assembly because playback order changes.
        if frame_callback is not None and not incremental_stream:
            print("📡 Streaming preview frames...")
            total_preview_frames = len(final_frames)
            for stream_idx, stream_frame in enumerate(final_frames):
                try:
                    frame_callback(stream_idx, stream_frame, total_preview_frames)
                    streamed_frame_count += 1
                except Exception as cb_err:
                    print(f"⚠️  Frame callback failed at {stream_idx}: {cb_err}")
                    break

        # Write video using FFmpeg directly for better compatibility
        print("💾 Writing video file...")
        
        # Try to use FFmpeg pipe for direct H.264 encoding
        use_ffmpeg_pipe = True
        try:
            import subprocess
            import threading

            ffmpeg_path = _get_ffmpeg_binary()
            print(f"   ▶ Using FFmpeg binary: {ffmpeg_path}")

            # Create FFmpeg command for pipe input
            ffmpeg_cmd = [
                ffmpeg_path,
                '-y',  # Overwrite output file
                '-f', 'rawvideo',
                '-vcodec', 'rawvideo',
                '-s', f'{width}x{height}',
                '-pix_fmt', 'rgb24',
                '-r', str(fps),
                '-i', '-',  # Read from pipe
                '-c:v', 'libx264',
                '-crf', '23',
                '-pix_fmt', 'yuv420p',
                '-movflags', '+faststart',
                str(output_path)
            ]

            # Start FFmpeg process with proper stderr handling
            process = subprocess.Popen(
                ffmpeg_cmd,
                stdin=subprocess.PIPE,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                bufsize=10**8  # Large buffer to prevent blocking
            )

            # Collect stderr in background to prevent pipe blocking
            stderr_data = []
            def read_stderr():
                for line in process.stderr:
                    stderr_data.append(line)

            stderr_thread = threading.Thread(target=read_stderr)
            stderr_thread.daemon = True
            stderr_thread.start()

            # Write frames to FFmpeg
            for pose_frame in tqdm(final_frames, desc="Writing frames"):
                try:
                    # FFmpeg expects RGB format
                    process.stdin.write(pose_frame.tobytes())
                except BrokenPipeError:
                    # FFmpeg died, check why
                    process.wait()
                    stderr_output = b''.join(stderr_data).decode('utf-8', errors='replace')
                    print(f"⚠️  FFmpeg died during write. Error output:")
                    print(stderr_output[-500:] if len(stderr_output) > 500 else stderr_output)
                    raise

            # Close pipe and wait for FFmpeg to finish
            process.stdin.close()
            process.wait(timeout=30)

            if process.returncode == 0:
                print(f"✅ Video generated successfully with H.264 codec!")
            else:
                stderr_output = b''.join(stderr_data).decode('utf-8', errors='replace')
                print(f"⚠️  FFmpeg failed with return code {process.returncode}")
                print(f"   Last 500 chars of error: {stderr_output[-500:] if len(stderr_output) > 500 else stderr_output}")
                use_ffmpeg_pipe = False
        except Exception as e:
            print(f"⚠️  FFmpeg pipe method failed: {e}")
            use_ffmpeg_pipe = False
        
        # Fallback to OpenCV if FFmpeg pipe fails
        if not use_ffmpeg_pipe:
            print("⚠️  Falling back to OpenCV writer...")
            tmp_output_path = output_path.with_name(f"{output_path.stem}_mp4v_tmp{output_path.suffix}")
            fourcc = cv2.VideoWriter_fourcc(*'mp4v')
            video_writer = cv2.VideoWriter(str(tmp_output_path), fourcc, fps, (width, height))
            
            if not video_writer.isOpened():
                print("❌ Unable to create video file")
                return False
            
            for pose_frame in tqdm(final_frames, desc="Writing frames"):
                pose_frame_bgr = cv2.cvtColor(pose_frame, cv2.COLOR_RGB2BGR)
                video_writer.write(pose_frame_bgr)
            
            video_writer.release()
            print("✅ Video generated successfully (raw MP4V). Re-encoding to H.264 for browser compatibility...")

            try:
                ffmpeg_bin = _get_ffmpeg_binary()
                print(f"   ▶ Using FFmpeg binary: {ffmpeg_bin}")
                reencode_cmd = [
                    ffmpeg_bin,
                    '-y',
                    '-i', str(tmp_output_path),
                    '-c:v', 'libx264',
                    '-pix_fmt', 'yuv420p',
                    '-movflags', '+faststart',
                    str(output_path)
                ]
                result = subprocess.run(
                    reencode_cmd,
                    stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE,
                    check=True
                )
                tmp_output_path.unlink(missing_ok=True)
                print("✅ Re-encoded video with libx264 successfully!")
                if result.stderr:
                    stderr_tail = result.stderr.decode('utf-8', errors='ignore')[-300:]
                    if stderr_tail.strip():
                        print(stderr_tail)
            except Exception as re_err:
                print(f"⚠️  H.264 re-encode failed: {re_err}")
                print("    Keeping MP4V file; some browsers may not play it.")
                if tmp_output_path.exists():
                    shutil.move(str(tmp_output_path), str(output_path))
        
        print(f"   📁 File: {output_path}")
        print(f"   📊 {len(final_frames)} frames, {fps}fps, {width}x{height}")
        if output_path.exists():
            print(f"   💾 Size: {output_path.stat().st_size / 1024 / 1024:.2f} MB")
        
        # Show video details
        print(f"\n📈 Video details:")
        for info in video_info:
            print(f"   {info['gloss']}: {info['video_id']} ({info['frame_count']} frames)")
        
        return True

    def apply_smoothing(self, frame_groups, smoothing_frames, method):
        """Apply smoothing between gloss groups"""
        print(f"🌊 Applying {method} smoothing ({smoothing_frames} frames)...")
        
        if method == 'fade':
            return self.apply_fade_smoothing(frame_groups, smoothing_frames)
        elif method == 'blend':
            return self.apply_blend_smoothing(frame_groups, smoothing_frames)
        elif method == 'pause':
            return self.apply_pause_smoothing(frame_groups, smoothing_frames)
        else:
            final_frames = []
            for group in frame_groups:
                final_frames.extend(group)
            return final_frames

    def apply_fade_smoothing(self, frame_groups, fade_frames):
        """Apply fade in/out smoothing"""
        smoothed_frames = []
        
        for i, group in enumerate(frame_groups):
            if i == 0:
                # First group: fade in
                for f in range(fade_frames):
                    alpha = f / fade_frames
                    black_frame = np.zeros_like(group[0])
                    faded_frame = (black_frame * (1 - alpha) + group[0] * alpha).astype(np.uint8)
                    smoothed_frames.append(faded_frame)
            
            smoothed_frames.extend(group)
            
            if i < len(frame_groups) - 1:
                # Transition between groups
                next_group = frame_groups[i + 1]
                current_last = group[-1]
                next_first = next_group[0]
                
                for f in range(fade_frames):
                    alpha = f / fade_frames
                    blended_frame = (current_last * (1 - alpha) + next_first * alpha).astype(np.uint8)
                    smoothed_frames.append(blended_frame)
        
        return smoothed_frames

    def apply_blend_smoothing(self, frame_groups, blend_frames):
        """Apply blend smoothing"""
        smoothed_frames = []
        
        for i, group in enumerate(frame_groups):
            smoothed_frames.extend(group)
            
            if i < len(frame_groups) - 1:
                next_group = frame_groups[i + 1]
                current_last = group[-1]
                next_first = next_group[0]
                
                for f in range(1, blend_frames + 1):
                    alpha = f / (blend_frames + 1)
                    blended_frame = (current_last * (1 - alpha) + next_first * alpha).astype(np.uint8)
                    smoothed_frames.append(blended_frame)
        
        return smoothed_frames

    def apply_pause_smoothing(self, frame_groups, pause_frames):
        """Apply pause smoothing"""
        smoothed_frames = []
        
        for i, group in enumerate(frame_groups):
            smoothed_frames.extend(group)
            
            if i < len(frame_groups) - 1:
                last_frame = group[-1]
                for _ in range(pause_frames):
                    smoothed_frames.append(last_frame.copy())
        
        return smoothed_frames

    def show_available_glosses(self, limit=20):
        """Show available glosses"""
        glosses = list(self.gloss_to_videos.keys())
        print(f"\n📋 Available Glosses ({len(glosses)}):")
        for i, gloss in enumerate(glosses[:limit]):
            videos = self.gloss_to_videos[gloss]
            print(f"  {gloss} -> {len(videos)} videos")
        if len(glosses) > limit:
            print(f"  ... and {len(glosses) - limit} more")

    def run_interactive(self):
        """Run interactive Q&A system"""
        print("\n" + "=" * 60)
        print("🤖 Sign Language Gloss Q&A System (Individual NPZ)")
        print("=" * 60)
        print("💬 Enter gloss to convert, separate multiple words with spaces")
        print("📋 Enter 'list' to view available glosses")
        print("🔧 Enter 'help' to view help")
        print("👋 Enter 'quit' to exit system")
        print("=" * 60)

        while True:
            try:
                user_input = input("\n🤖 Please enter gloss: ").strip()

                if not user_input:
                    continue
                elif user_input.lower() == 'quit':
                    print("👋 Thank you for using!")
                    break
                elif user_input.lower() == 'list':
                    self.show_available_glosses()
                    continue
                elif user_input.lower() == 'help':
                    self.show_help()
                    continue

                # Parse input glosses
                gloss_list = user_input.upper().split()
                print(f"\n🎯 Query: {' + '.join(gloss_list)}")

                # Generate timestamp for filename
                timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
                gloss_str = "_".join(gloss_list)
                
                # Ask for smoothing options if multiple glosses
                smoothing_method = 'none'
                smoothing_frames = 0
                npz_interpolation_frames = 0
                
                if len(gloss_list) > 1:
                    print(f"\n🌊 Multiple glosses detected, choose smoothing method:")
                    print(f"   1. none - No smoothing (direct concatenation)")
                    print(f"   2. fade - Fade in/out transition")
                    print(f"   3. blend - Frame blending transition")
                    print(f"   4. pause - Add pause interval")
                    print(f"   5. npz - NPZ interpolation (smoothest transition)")
                    
                    smooth_choice = input(f"Choose smoothing method [1-5, default 1]: ").strip()
                    
                    if smooth_choice == '2':
                        smoothing_method = 'fade'
                        smoothing_frames = int(input("Fade frames [default 5]: ").strip() or "5")
                    elif smooth_choice == '3':
                        smoothing_method = 'blend'
                        smoothing_frames = int(input("Blend frames [default 3]: ").strip() or "3")
                    elif smooth_choice == '4':
                        smoothing_method = 'pause'
                        smoothing_frames = int(input("Pause frames [default 10]: ").strip() or "10")
                    elif smooth_choice == '5':
                        npz_interpolation_frames = int(input("NPZ interpolation frames [default 10]: ").strip() or "10")
                        print(f"📊 Using body-anchor NPZ interpolation for smooth transitions")
                
                # Generate output filename
                suffix = f"_{smoothing_method}" if smoothing_method != 'none' else ""
                if npz_interpolation_frames > 0:
                    suffix = f"_npz{npz_interpolation_frames}"
                
                draw_style = 'controlnext'
                print(f"🎨 Using {draw_style} drawing style")
                style_suffix = f"_{draw_style}_style"
                output_file = Path(OUTPUT_DIR) / f"{gloss_str}_{timestamp}{suffix}{style_suffix}.mp4"
                
                # Generate video
                success = self.generate_video_from_glosses(
                    gloss_list, output_file,
                    smoothing_frames=smoothing_frames,
                    smoothing_method=smoothing_method,
                    npz_interpolation_frames=npz_interpolation_frames,
                    hide_torso_lines=False,
                    draw_style=draw_style
                )

            except KeyboardInterrupt:
                print("\n\n👋 System exited")
                break
            except Exception as e:
                print(f"❌ Error occurred: {e}")

    def show_help(self):
        """Show help information"""
        print("\n" + "=" * 50)
        print("📖 Help Information")
        print("=" * 50)
        print("🔹 Enter single gloss: HELLO")
        print("🔹 Enter multiple glosses: HELLO WORLD GOODBYE")
        print("🔹 View available content: list")
        print("🔹 System will match sign language videos from NPZ files")
        print(f"🔹 Generated videos are saved in {OUTPUT_DIR}/ directory")
        print("🔹 Smoothing options:")
        print("   - fade: Fade in/out transition")
        print("   - blend: Frame blending transition")
        print("   - pause: Add pause interval")
        print("   - npz: NPZ-level interpolation (smoothest, uses Catmull-Rom splines)")
        print("=" * 50)


def main():
    parser = argparse.ArgumentParser(description='Sign Language Gloss Q&A System - Individual NPZ')
    parser.add_argument('--gloss', '-g',
                        help='Directly input gloss to generate video, separated by spaces')
    parser.add_argument('--fps', type=int, default=25,
                        help='Video frame rate (default: 25)')
    parser.add_argument('--width', type=int, default=480,
                        help='Video width (default: 480)')
    parser.add_argument('--height', type=int, default=480,
                        help='Video height (default: 480)')
    parser.add_argument('--smoothing', choices=['none', 'fade', 'blend', 'pause'],
                        default='none', help='Smoothing method (default: none)')
    parser.add_argument('--smoothing-frames', type=int, default=5,
                        help='Smoothing frames (default: 5)')
    parser.add_argument('--npz-interpolation', type=int, default=0,
                        help='Number of NPZ interpolation frames between glosses (default: 0)')
    parser.add_argument('--npz-interpolation-method',
                        choices=['body-anchor', 'catmull-rom', 'linear', 'cubic'],
                        default='body-anchor',
                        help='NPZ transition method. body-anchor keeps hand/face local shapes and only retargets them to interpolated wrists/neck. (default: body-anchor)')
    parser.add_argument('--scale-x', type=float, default=1.4,
                        help='Progressive X-axis scaling factor (default: 1.4)')
    parser.add_argument('--scale-y', type=float, default=1.5,
                        help='Progressive Y-axis scaling factor (default: 1.5)')
    parser.add_argument('--hide-torso-lines', type=str, choices=['true', 'false'], default='false',
                        help='Hide torso lines from neck to hips (set to black). Choices: true/false (default: false)')
    parser.add_argument('--ref-image-path', type=str, default=None,
                        help='Reference image path for head alignment')
    parser.add_argument('--draw-style', type=str, choices=['controlnext', 'openpose'], default='controlnext',
                        help='Drawing style for pose visualization. controlnext: advanced features with confidence-based coloring. openpose: simpler classic style. (default: controlnext)')
    parser.add_argument('--draw-threshold', type=float, default=0.6,
                        help='Confidence threshold for drawing joints (default: 0.6)')
    parser.add_argument('--normalize-pose', type=str, choices=['true', 'false'], default='true',
                        help='Normalize pose data to standard coordinate system. This ensures different videos are in the same coordinate space, reducing inconsistency from different video sources. (default: true)')
    parser.add_argument('--max-candidates', type=int, default=10,
                        help='Maximum number of NPZ candidates evaluated per gloss (default: 10, set 0 for unlimited)')
    parser.add_argument('--stabilize-skeleton', type=str, choices=['true', 'false'], default='false',
                        help='Stabilize body bone lengths and face scale before rendering (default: false)')
    parser.add_argument('--retarget-to-first-signer', type=str, choices=['true', 'false'], default='true',
                        help='Retarget every gloss clip to the first selected signer skeleton. Only arms/hands change across words. (default: true)')
    parser.add_argument('--retarget-face-mode', choices=['retarget', 'none'], default='retarget',
                        help='Face handling when retargeting: retarget keeps local face shape but aligns center/scale to first signer; none leaves face unchanged. (default: retarget)')

    args = parser.parse_args()

    # Initialize QA system
    qa_system = SignLanguageQA(max_candidates=max(0, args.max_candidates))

    # If gloss parameter provided, process directly
    if args.gloss:
        gloss_list = args.gloss.upper().split()
        print(f"🎯 Processing gloss: {' + '.join(gloss_list)}")

        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        gloss_str = "_".join(gloss_list)
        suffix = f"_{args.smoothing}" if args.smoothing != 'none' else ""
        
        # Include video IDs in filename
        video_ids = []
        for gloss in gloss_list:
            videos = qa_system.find_gloss_videos(gloss)
            if videos:
                video_ids.append(videos[0])  # Take first video
        
        video_id_str = "_".join(video_ids) if video_ids else "novideo"
        style_suffix = f"_{args.draw_style}_style"
        output_file = Path(OUTPUT_DIR) / f"{gloss_str}_{video_id_str}_{timestamp}{suffix}{style_suffix}.mp4"

        if args.smoothing != 'none':
            print(f"🌊 Using {args.smoothing} smoothing ({args.smoothing_frames} frames)")

        if args.scale_x != 1.0 or args.scale_y != 1.0:
            print(f"📏 Using progressive scaling: X={args.scale_x}, Y={args.scale_y}")

        if args.draw_style != 'controlnext':
            print(f"🎨 Using {args.draw_style} drawing style")

        if args.normalize_pose == 'true':
            print(f"📏 Pose normalization enabled")
        else:
            print(f"⚠️  Pose normalization disabled")

        if args.stabilize_skeleton == 'true':
            print(f"🦴 Skeleton stabilization enabled")

        if args.npz_interpolation > 0:
            print(f"🔄 NPZ interpolation method: {args.npz_interpolation_method}")

        if args.retarget_to_first_signer == 'true':
            print(f"🧍 Retargeting all glosses to first signer skeleton (face={args.retarget_face_mode})")

        success = qa_system.generate_video_from_glosses(
            gloss_list, output_file, args.fps, args.width, args.height,
            args.smoothing_frames, args.smoothing, args.npz_interpolation,
            args.scale_x, args.scale_y, args.hide_torso_lines == 'true',
            args.ref_image_path, args.draw_style, args.normalize_pose == 'true',
            args.draw_threshold, args.stabilize_skeleton == 'true',
            args.npz_interpolation_method,
            args.retarget_to_first_signer == 'true', args.retarget_face_mode
        )

        if not success:
            print("❌ Video generation failed")
    else:
        # Start interactive system
        qa_system.run_interactive()


if __name__ == "__main__":
    main()