File size: 108,872 Bytes
a46c532
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
"""Unified MM-Lifelong long-video processing entry (day / week / month).

设计目标(替代旧版 mmlifelong + egolife_egomemreason):

- **三种数据集类型 (--dataset_type)**:
  * day   : MM-Lifelong/day —— 单个《黑神话:悟空》B 站视频
            问题类型:Counting / Object 等(test.json 在 /mnt/tokyo-ai/gst/MM-Lifelong/day/)
            视频路径:/mnt/tokyo-ai/gst/MM-Lifelong/videos/BV1dbyaBZE8n_p1.mp4
            视角:第三人称游戏实况
  * week  : EgoLife A1_JAKE —— 7 天,每天数百个 30s clip 顺序拼接
            评测:/mnt/tokyo-ai/gst/EgoMemReason_hf/annotations_public.jsonl
                  + /mnt/tokyo-ai/gst/MM-Lifelong/week/test.json
            视频根目录:/mnt/tokyo-ai/gst/EgoLife/egolife/A1_JAKE/DAY{N}/
            视角:第一人称(camera-wearer)
            先验:Activity Pattern / 用户日常行为 / 跨天事件回忆
  * month : MM-Lifelong/month —— 多个 YouTube 旅行 vlog,按 video_list.txt 顺序
            评测:/mnt/tokyo-ai/gst/MM-Lifelong/month/{train,val}.json
            视频路径:/mnt/tokyo-ai/gst/MM-Lifelong/videos/<youtube_id>.mp4
            视角:第三人称旅行 vlog(中英混合)
            先验:Counting / Attribute Recognition / Temporal Reasoning

- **caption 生成 (--caption_model_name)**:复用 OVO async pipeline
  * 支持 qwen_api (DashScope) 或 qwen_vllm (本地/远程 vLLM 服务)
  * --caption_concurrency 4 启用并行 caption
  * --enable_audio_in_prompt:把对应时间窗口的 audio transcript 拼进 caption prompt
    (audio 源:sync GT for week / Whisper for month/day)

- **v3 异步建图**:--pipeline_mode {v1, v3}
  默认 v1 = caption ∥ [segmenter+episode_build]
  v3 = caption ∥ segmenter ∥ episode_build (多 pending FIFO)

- **跨视频共享 hypergraph**:同一个 hyper_vg + working_dir 跨 DAY/sub-video 累积,
  每个 sub-video 结束 flush segmenter buffer,避免跨片段污染。

用法示例:
  # day (黑神话)
  python -m hypervideo.mmlifelong_processing \\
    --dataset_type day --caption_model_name qwen_vllm \\
    --vllm_base_url http://10.0.0.3:8000/v1 \\
    --pipeline_mode v3 --caption_concurrency 4

  # week (EgoLife A1_JAKE)
  python -m hypervideo.mmlifelong_processing \\
    --dataset_type week --user_id A1_JAKE \\
    --days 1,2,3,4,5,6,7 \\
    --caption_model_name qwen_vllm --vllm_base_url http://10.0.0.3:8000/v1 \\
    --pipeline_mode v3 --caption_concurrency 4 \\
    --enable_audio_in_prompt --audio_source egolife_sync

  # month (YouTube vlogs)
  python -m hypervideo.mmlifelong_processing \\
    --dataset_type month \\
    --caption_model_name qwen_vllm --vllm_base_url http://10.0.0.3:8000/v1 \\
    --pipeline_mode v3 --caption_concurrency 4
"""

from __future__ import annotations

import argparse
import asyncio
import glob
import json
import logging
import os
import re
import sys
import time
from typing import Dict, List, Optional, Tuple

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from videorag._llm import LLMConfig, openai_embedding, gpt_4o_mini_complete  # noqa: E402
from videorag._utils import always_get_an_event_loop  # noqa: E402

from hypervideo.hyper_video_graph import HyperVideoGraph  # noqa: E402
from hypervideo.config import HyperVideoConfig  # noqa: E402
from hypervideo.modules.profile_aggregator import ProfileAggregator  # noqa: E402
from hypervideo.modules.entity_id import augment_fact_prompt  # noqa: E402
from hypervideo.modules.audio_cues import (  # noqa: E402
    AudioCueExtractor,
    load_existing_egolife_transcript_as_audio_caps,
)
from hypervideo.modules.async_pipeline import (  # noqa: E402
    build_video_async, AsyncPipelineStats, LLMTimer,
)
from hypervideo.modules.async_pipeline.pipeline_v3 import (  # noqa: E402
    build_video_async_v3,
    upgrade_builder_segmenter_to_v3,
)
from hypervideo.modules.async_pipeline.pipeline_v3_dataset import (  # noqa: E402
    build_dataset_async_v3,
    DatasetPipelineStats,
)
from hypervideo.modules.async_pipeline.builder_adapter_v2 import (  # noqa: E402
    make_segment_only_fn,
    make_build_episode_only_fn,
    make_flush_segmenter_fn,
    make_flush_builder_fn,
)
from videorag.video_processing import sample_frames_by_interval  # noqa: E402
from hypervideo.ovobench_hyper_processing import (  # noqa: E402
    _caption_window_batch,
    _seconds_to_hms,
    _timestamp_num_to_seconds,
    clear_gpu_memory,
)
from videorag.ovobench_prompt import OUTPUT_FORMAT  # noqa: E402

logging.basicConfig(level=logging.INFO,
                    format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger(__name__)


# ----------------------------------------------------------------------
# Default LLM config
# ----------------------------------------------------------------------
default_llm_config = LLMConfig(
    embedding_func_raw=openai_embedding,
    embedding_model_name="text-embedding-3-small",
    embedding_dim=1536,
    embedding_max_token_size=8192,
    embedding_batch_num=32,
    embedding_func_max_async=16,
    query_better_than_threshold=0.2,
    best_model_func_raw=gpt_4o_mini_complete,
    best_model_name="gpt-4.1-mini",
    best_model_max_token_size=32768,
    best_model_max_async=16,
    cheap_model_func_raw=gpt_4o_mini_complete,
    cheap_model_name="gpt-4.1-mini",
    cheap_model_max_token_size=32768,
    cheap_model_max_async=16,
)


# ======================================================================
# 数据集类型 -> 视频清单 (sub_video_id, video_path, day_num) 列表
# ======================================================================

_DAY_VIDEO_FILE = "BV1dbyaBZE8n_p1.mp4"


def _parse_month_yids(video_list_path: str) -> List[str]:
    """从 video_list.txt 的 'Month Scale' 段按出现顺序提取 YouTube IDs。"""
    if not os.path.exists(video_list_path):
        raise FileNotFoundError(f"video_list.txt not found: {video_list_path}")
    text = open(video_list_path, "r", encoding="utf-8").read()
    if "Month Scale" not in text:
        raise ValueError(f"'Month Scale' section missing in {video_list_path}")
    month_section = text.split("Month Scale", 1)[1]
    return re.findall(r"v=([\w-]+)", month_section)


def _ensure_video_chunks(video_path: str, chunk_dir: str,
                         chunk_seconds: int = 600) -> List[Tuple[str, float]]:
    """把长视频用 ffmpeg stream-copy 预切成 ~chunk_seconds 的小段 (不重编码, IO 速度).

    动机: _run_one_sub_video_async 会对整个 sub-video 一次性预采样且全帧驻内存,
    month 的 vlog 最长 12h, 直接喂会卡死数小时且 checkpoint 粒度是整个视频。
    切片后每段当一个 sub-video, 复用 week/day 的 clip_start_seconds 偏移机制,
    自然获得细粒度 checkpoint + 低内存 + 快加载。

    返回 [(chunk_path, start_seconds), ...] 按时间序; 已切过则直接读缓存清单。
    注: -c copy 在关键帧切割, 各段时长略有浮动, 用 segment_list csv 的真实起始秒。
    """
    import csv
    import subprocess
    os.makedirs(chunk_dir, exist_ok=True)
    list_csv = os.path.join(chunk_dir, "segments.csv")
    if os.path.exists(list_csv):
        out = []
        with open(list_csv) as f:
            for row in csv.reader(f):
                if len(row) >= 2:
                    out.append((os.path.join(chunk_dir, row[0]), float(row[1])))
        if out:
            return out
    import imageio_ffmpeg
    exe = imageio_ffmpeg.get_ffmpeg_exe()
    cmd = [exe, "-hide_banner", "-loglevel", "error", "-i", video_path,
           "-c", "copy", "-map", "0",
           "-f", "segment", "-segment_time", str(chunk_seconds),
           "-segment_list", list_csv,
           "-reset_timestamps", "1",
           os.path.join(chunk_dir, "chunk_%05d.mp4")]
    logger.info(f"[chunk] 切片 {os.path.basename(video_path)} -> {chunk_dir} "
                f"({chunk_seconds}s/段, stream-copy)")
    subprocess.run(cmd, check=True, timeout=3600)
    out = []
    with open(list_csv) as f:
        for row in csv.reader(f):
            if len(row) >= 2:
                out.append((os.path.join(chunk_dir, row[0]), float(row[1])))
    logger.info(f"[chunk] {len(out)} 段")
    return out


def _list_egolife_clips_for_day(
    video_root: str, user_id: str, day_num: int,
) -> List[str]:
    """列出 EgoLife <video_root>/<user_id>/DAY{N}/*.mp4 按文件名时间戳排序。
    文件名形如: DAY{N}_<user_id>_<HHMMSSFF>.mp4
    返回完整路径列表,按时间顺序。"""
    day_dir = os.path.join(video_root, user_id, f"DAY{day_num}")
    if not os.path.isdir(day_dir):
        logger.warning(f"[week] dir missing: {day_dir}")
        return []
    pattern = os.path.join(day_dir, f"DAY{day_num}_{user_id}_*.mp4")
    files = sorted(glob.glob(pattern))
    return files


def _parse_egolife_clip_start_seconds(clip_path: str) -> int:
    """从 EgoLife clip 文件名解析其绝对起始秒数 (相对所在 DAY 的 00:00:00)。

    文件名格式: DAY{N}_<user>_<HHMMSSFF>.mp4 (HH MM SS FF 各占 2 位)
    e.g. DAY1_A1_JAKE_11094208.mp4 -> 11:09:42 -> 40182s (FF 帧序忽略, 帧偏移
    在 sample_frames 时已涵盖)。"""
    base = os.path.splitext(os.path.basename(clip_path))[0]
    # 取最后一个下划线后的 8 位数字
    parts = base.rsplit("_", 1)
    if len(parts) != 2 or len(parts[1]) < 6 or not parts[1].isdigit():
        logger.warning(f"[week] 无法解析 clip 时间戳: {clip_path}")
        return 0
    ts = parts[1]
    hh = int(ts[0:2])
    mm = int(ts[2:4])
    ss = int(ts[4:6])
    return hh * 3600 + mm * 60 + ss


def get_sub_videos_for_dataset(
    dataset_type: str,
    args,
) -> List[Tuple[str, str, int, int]]:
    """返回 (sub_video_id, video_path, day_num, clip_start_seconds) 列表,按时间顺序。

    sub_video_id 用作 hypergraph 内部追踪每段视频归属;
    day_num 用作 segmenter 内部 DAY 编号(跨 day 时强制分割 episode);
    clip_start_seconds 是 EgoLife clip 在所在 DAY 内的绝对起始秒数,
    用于把 clip 内 0 偏移的帧时间戳还原到 wall-clock 绝对时间。
    对 day/month 该值固定为 0(每个视频独立 day_num,时间从 0 开始)。
    """
    if dataset_type == "day":
        # MM-Lifelong day: B 站多分P视频 (BV1dbyaBZE8n_p1..p32, 共 ~24.7h)。
        # 题目 clue_intervals 是跨分P的连续累计秒, 因此所有分P共用 day_num=1,
        # 用 clip_start_seconds 传累计偏移把各分P帧时间戳拼成连续时间轴。
        # (旧版只有 p1 时代的单视频逻辑, 已扩展; 只有 p1 存在时行为等价旧版)
        import glob as _glob
        part_re = re.compile(r'_p(\d+)\.mp4$')
        parts = []
        for f in _glob.glob(os.path.join(args.video_dir, "BV1dbyaBZE8n_p*.mp4")):
            m = part_re.search(f)
            if m:
                parts.append((int(m.group(1)), f))
        parts.sort()
        if not parts:
            raise FileNotFoundError(f"[day] no BV1dbyaBZE8n_p*.mp4 in {args.video_dir}")
        result: List[Tuple[str, str, int, int]] = []
        offset = 0.0
        chunk_sec = int(getattr(args, "chunk_seconds", 600) or 0)
        chunk_root = os.path.join(args.video_dir, "_chunks")
        from moviepy.editor import VideoFileClip
        for pn, path in parts:
            if chunk_sec <= 0:
                # 不切片 (旧行为): 整个分P一个 sub-video, 仅拼累计偏移
                result.append((f"day_p{pn}", path, 1, int(offset)))
                try:
                    _c = VideoFileClip(path)
                    offset += float(_c.duration or 0)
                    _c.close()
                except Exception as e:
                    logger.warning(f"[day] 探测 {os.path.basename(path)} 时长失败: {e}")
                continue
            # 分P 也预切片 (最长 64min): 控制单 sub-video 预采样内存 + checkpoint 粒度
            chunks = _ensure_video_chunks(
                path, os.path.join(chunk_root, f"day_p{pn}"), chunk_sec)
            for ci, (cpath, cstart) in enumerate(chunks):
                result.append((f"day_p{pn}_c{ci:05d}", cpath, 1, int(offset + cstart)))
            # 累计偏移: 分P真实时长 = 最后一段起始 + 该段时长 (moviepy 探测最后一段, 便宜)
            try:
                _c = VideoFileClip(chunks[-1][0])
                offset += chunks[-1][1] + float(_c.duration or 0)
                _c.close()
            except Exception as e:
                logger.warning(f"[day] 探测 {os.path.basename(path)} 末段时长失败: {e}")
        logger.info(f"[day] {len(parts)} 个分P -> {len(result)} chunks, "
                    f"总时长 {offset/3600:.1f}h, 连续时间轴")
        return result

    if dataset_type == "week":
        # EgoLife A1_JAKE: 跨 day 跨 clip 维护绝对时间轴
        # 每个 clip 的绝对起始时间由文件名 HHMMSSFF 解析,segmenter 看到的
        # 时间戳是 DAY{day_num} 的 HH:MM:SS 绝对值;跨 clip / 跨 day 的边界
        # 由 segmenter 的 hard_boundary (gap_threshold=60s 或 day 变化) 自动处理。
        result: List[Tuple[str, str, int, int]] = []
        days = [int(d.strip()) for d in args.days.split(",") if d.strip()]
        for d in days:
            clips = _list_egolife_clips_for_day(
                args.video_dir, args.user_id, d,
            )
            if not clips:
                logger.warning(f"[week] DAY{d} no clips, skip")
                continue
            for clip_path in clips:
                clip_name = os.path.splitext(os.path.basename(clip_path))[0]
                clip_start_sec = _parse_egolife_clip_start_seconds(clip_path)
                result.append((clip_name, clip_path, d, clip_start_sec))
        if not result:
            raise FileNotFoundError(
                f"[week] no clips matched under {args.video_dir}/{args.user_id}/DAY{{...}}"
            )
        logger.info(
            f"[week] {len(result)} clips across {len(days)} days "
            f"(first={result[0][0]}@{result[0][3]}s, last={result[-1][0]}@{result[-1][3]}s)"
        )
        return result

    if dataset_type == "month":
        if args.video_list is None:
            raise ValueError("--video_list required for dataset_type=month")
        yids = _parse_month_yids(args.video_list)
        result: List[Tuple[str, str, int, int]] = []
        day_num = 1
        n_avail = 0
        chunk_sec = int(getattr(args, "chunk_seconds", 600) or 0)
        chunk_root = os.path.join(args.video_dir, "_chunks")
        for yid in yids:
            fname = f"{yid}.mp4"
            full_path = os.path.join(args.video_dir, fname)
            if os.path.exists(full_path):
                if chunk_sec <= 0:
                    # 不切片 (旧行为): 整个视频一个 sub-video
                    result.append((yid, full_path, day_num, 0))
                else:
                    # 长视频预切片 (最长 12h, 整段预采样会卡死): 每段一个 sub-video,
                    # 同一 vlog 的所有段共用 day_num, clip_start_seconds 传段内偏移
                    chunks = _ensure_video_chunks(
                        full_path, os.path.join(chunk_root, yid), chunk_sec)
                    for ci, (cpath, cstart) in enumerate(chunks):
                        result.append((f"{yid}_c{ci:05d}", cpath, day_num, int(cstart)))
                n_avail += 1
                day_num += 1
            else:
                logger.warning(f"[month] missing video, skip: {fname}")
        if not result:
            raise FileNotFoundError(
                f"[month] no videos present in {args.video_dir}"
            )
        logger.info(f"[month] {n_avail}/{len(yids)} videos -> {len(result)} chunks "
                    f"({chunk_sec}s/段)")
        return result

    raise ValueError(f"unknown dataset_type: {dataset_type!r}")


# ======================================================================
# Dataset-specific caption prompt (融合 question type 先验)
# ======================================================================

# week=EgoLife 第一人称 (BASE 版): 与 EgoMemReason / MM-Lifelong week 题型对齐的最小 prompt,
# 不带 drink/sit/phone/entity 等专属 cue。--use_enhanced_week_prompt 开关切换到增强版。
FRAME_CAPTION_PROMPT_WEEK = """You are a visual evidence recorder for a first-person daily-life video segment (EgoLife dataset, camera-wearer's point of view, shared house with multiple roommates).

This footage will be queried later for questions about the camera-wearer's habitual activities, daily routines, social interactions, what they ate / wore / did, who they talked to, and cross-day patterns (e.g. "What do I most often eat for breakfast?", "What is my most common activity?", "What am I likely to do after lunch?"). Any everyday-life detail you omit can become a question you cannot answer.

There are {num_frames} sampled frames at {interval_sec}s intervals, covering wall-clock window {abs_start}-{abs_end} (~{window_seconds}s).

{audio_context_block}

For EACH frame describe (2-3 sentences):

1. **Activity / action**: what the camera-wearer is doing right now (eating, cooking, talking, walking, using phone, watching TV, etc.). Use action verbs.
2. **Object / food / item being interacted with**: name specific objects in the wearer's hands or directly in front. Food: name the dish (pancake / rice / dumplings / burger ...). Devices: laptop / phone / camera. Be specific - "pancake" not "food".
3. **People + interaction**: how many other people are visible, what they appear to be doing, whether they are talking with the wearer. If a name was mentioned in audio above, you may use it.
4. **Place / scene**: kitchen / dining table / bedroom / outdoor / vehicle / store / etc. Note furniture, decorations, signs.

Rules:
- First-person POV: refer to the camera-wearer as "I" / "the camera-wearer".
- No vague nouns: avoid "something", "an object", "an item" — always name the concrete thing.
- Anti-repetition: only describe what CHANGED from the previous frame; do not restate static background.
- Quote on-screen text verbatim if visible (subtitles, signs, phone screen).
- Mention durations / sequence cues when natural ("just finished eating", "about to leave").

First frame example timestamp: {first_ts_example}. Last frame example timestamp: {last_ts_example}.

Return JSON in this exact format:
{output_format}
"""


# week=EgoLife 第一人称 (ENHANCED 版): 全面覆盖 EgoMemReason + MM-Lifelong week 题型,
# 并显式引出 drink / sit / phone-use / preference / entity_id 累积模块所需的 cue。
# --use_enhanced_week_prompt 开启。
#
# 设计原则: 长视频中"什么会被问"无法预知, 必须把每帧的所有显著物体、文字、状态都记录下来,
# 不能只描述当下动作。EgoMemReason/MM-Lifelong 的题经常问背景里某个玻璃杯、某张海报上的字、
# 某个角落里的椅子的状态 —— 这类细节 VLM 默认不会主动提, 必须在 prompt 里强制要求。
FRAME_CAPTION_PROMPT_WEEK_ENHANCED = """You are a visual evidence recorder for a first-person daily-life video segment (EgoLife dataset, camera-wearer's point of view, shared house with multiple roommates).

This footage will be queried later by TWO benchmarks (EgoMemReason + MM-Lifelong week). The questions are *unknown at recording time*: they may probe any specific glass on the table 3 days later, any sign on the wall in the background, any chair's position relative to the projector screen. **Your only job is to record EVERYTHING factual now**. Anything you omit becomes an unanswerable question.

[CORE RULE — EXHAUSTIVE RECORDING]

You MUST do TWO things per frame:

  **(A) Foreground action description** — what the camera-wearer + visible people are doing.
  **(B) Background entity census** — list ALL distinct visible objects, even those not involved in the action: glasses / cups / bottles / wine / vases / plush toys / chairs / chair positions / pillows / bags / laptops / phones / decorations / posters / clothes / appliances / plants / boxes / books / shoes — each with its CURRENT POSITION and CURRENT STATE.

If you only describe (A) and skip (B), the build is incomplete.

[OCR RULE — QUOTE EVERY VISIBLE PIECE OF TEXT]

Every piece of text visible in the frame MUST be transcribed verbatim:
  - Signs / billboards / shop names
  - Menus / labels / brand logos
  - Phone / laptop / TV screens
  - Subtitles / overlay text
  - Whiteboards / paper notes
  - Clothing prints
Preserve original language (Chinese / English / mixed). If text is partially visible, still quote what is readable.

[QUESTION TYPES — these are the kinds of questions that will be asked later]

1. **Counting / Temporal Counting**: For salient categories (people, chairs, cups, bottles, laptops, dishes), give EXACT integer when ≤10. Always include item counts even if no one in the scene cares about them right now.
2. **Attribute Recognition**: For each visible person: clothing color + type, hairstyle, accessories. For objects: color, brand, size, on-screen labels.
3. **Entity Recognition / Social Interaction**: Identify each visible person by name when revealed by context. Note who interacts with whom.
4. **Language Content Recall**: Quote what each person SAYS verbatim, preserve original language. Also quote anything PRINTED in the frame (see OCR RULE above).
5. **Event Ordering / Event Recognition / Event Tracking**: Describe each action with verb + object + recipient. Note sequential cues ("just finished X", "about to Y", "after returning from kitchen").
6. **Spatial Preference**: Always name the room/location (kitchen / dining room / bedroom / living room / 1st floor / 2nd floor / outdoor balcony / etc.). Note furniture cues that fix the location.
7. **Cumulative State Tracking** ("where was this wine when we had a meeting yesterday?"): For EVERY moveable object visible (vase / bottle / chair / decorative item / plush / bag / book / device), record its CURRENT POSITION and CURRENT STATE. These questions specifically test whether you noted the object's location at this exact moment.
8. **Activity Pattern** ("what do I most often eat for breakfast?"): What is the camera-wearer doing + what specific food/object? Name the dish exactly. Include meal context (breakfast / lunch / dinner / snack) when inferrable from time of day.
9. **Causal Reasoning** (cross-event linking): When one action triggers another, note both ("she points to the cup, he picks it up"). When a stated reason is visible (text, sign, gesture), record it.
10. **Hallucination Detection**: Be strictly factual. Do NOT invent details that are not actually visible.

[MEMORY MODULES — accumulated structures, mark when applicable]

11. **DRINK event** (是否超过 2h 不喝水): When camera-wearer takes a sip (raises cup/bottle/glass to mouth), write the exact phrase **"I drink from <cup/bottle/glass>"** — parsed verbatim by the extractor.
12. **SIT event** (久坐检测): When camera-wearer sits down or stands up, write **"I sit down at <place>"** or **"I stand up from <place>"**.
13. **PHONE-USE event** (频繁刷手机): When camera-wearer looks at phone screen, write **"I check my phone"** + what app/content is visible.
14. **USER PREFERENCE cue**: Note recurring choices when visible — favorite seat, preferred food, frequent activity ("again sits at the corner table", "another mug of coffee").
15. **ENTITY ID** (跨天可识别): For each named person, also describe their visual identifiers (clothing + hair + accessories) so they can be re-identified across days. For named/distinctive objects (specific wine bottle, laptop with stickers, lion plush toy), describe distinguishing visual features (color, shape, label) so they can be tracked over time.

[FORMAT]

There are {num_frames} sampled frames at {interval_sec}s intervals, covering wall-clock window {abs_start}-{abs_end} (~{window_seconds}s).

{audio_context_block}

For EACH frame, write 4-6 sentences. Structure:
  1. Activity sentence: who is doing what (+ DRINK/SIT/PHONE marker when applicable).
  2. People sentence: each visible person's clothing + name + position.
  3. **Background object census sentence**: list ALL distinct movable objects visible in this frame with their current location and state (e.g. "On the dining table: red-and-white checkered cloth, a vase with pink flowers, two silver laptops (one closed near edge, one open with screen showing slack), a black smartphone face-down, a glass of yellow juice, a notebook open on right side").
  4. **On-screen text sentence**: verbatim transcription of every visible piece of text in the frame.
  5. Place / scene sentence: room/location + furniture cues + lighting.
  6. (optional) Linking sentence: how this frame relates to the previous one (object moved, person arrived/left, light changed).

Rules:
- First-person POV: "I" = camera-wearer.
- ANTI-REPETITION across frames is OUR enemy here — if a glass that was on the table at frame N+1 is still there, repeat its position. Repetition is fine; missing it is fatal. Only static backgrounds (wall color, floor pattern) can be omitted after the first frame.
- No vague nouns: never "something", "someone" → name the concrete object/person.
- Be strictly factual: do not invent details that are not visible.
- DRINK / SIT / PHONE markers MUST use the exact phrasings above.

First frame example timestamp: {first_ts_example}. Last frame example timestamp: {last_ts_example}.

Return JSON in this exact format:
{output_format}
"""

# month=YouTube vlog 第三人称 + Counting/Attribute/Temporal Reasoning 类
# 关键先验:streamer 旅行 vlog,需要数物品、辨颜色/服装、时序
FRAME_CAPTION_PROMPT_MONTH = """You are a visual evidence recorder for a third-person travel/vlog video segment (MM-Lifelong month-scale, YouTube travel vlog of a streamer touring China; mixed Chinese-English speech).

This footage will be queried later for questions about: counts of items in a scene, attributes of people/objects (colors, clothing, model names, brand names), temporal ordering of activities across days/locations, what songs the streamer sang and where. Any visual detail you omit can become a question you cannot answer.

There are {num_frames} sampled frames at {interval_sec}s intervals, covering wall-clock window {abs_start}-{abs_end} (~{window_seconds}s).

{audio_context_block}

For EACH frame describe (2-4 sentences):

1. **Counts**: count visible items in salient categories — people, laptops/phones/screens, food dishes, vehicles, tables, chairs, animals. Use exact numbers when ≤10, "many" otherwise. ALWAYS count when ≥2 are visible.
2. **Attributes**: for any person — clothing color + type ("woman in red pants and white shirt"), hairstyle, accessories. For objects — color, brand, size cues, on-screen labels.
3. **Action & temporal cue**: what the streamer or visible people are doing right now (singing, ordering food, walking through market, riding car). Include any visible time/location signs ("Chongqing", "Day 3", clock readings).
4. **Place / scene**: city / street / restaurant / stage / car interior / etc. Mention recognizable landmarks.

Rules:
- Third-person POV. The streamer is one specific person (typically male, narrating in English).
- No vague nouns: "a man" → "a man in a black hoodie and glasses".
- Quote on-screen text exactly (signs in Chinese / English / subtitles / brand names).
- Anti-repetition across frames: only describe what CHANGED from the previous frame.

First frame example timestamp: {first_ts_example}. Last frame example timestamp: {last_ts_example}.

Return JSON in this exact format:
{output_format}
"""

# month V1 (新增, 不覆盖旧版): 按 month val.json 实际题型分布重写
#   Counting 135 / Entity 108 / Causal 107 / Temporal 72 / EventRec 54 /
#   LangRecall 46 / Halluc 44 / Attribute 26 / Social 23
# 设计依据 (week 上 recall 指标验证的结论):
#   1. 简略风格优于详尽罗列 (BM25/embedding 判别性更强) -> 沿用 BASE 结构 2-4 句/帧
#   2. 旧版完全没覆盖 Causal (107题, 占17%) -> 新增因果/动机 cue
#   3. Entity/跨视频时序需要 城市/地标/人名 锚点 -> 强化 place anchor
#   4. LangRecall 依赖 audio transcript 引用 -> 显式要求引用说唱内容
# --prompt_version v1 启用 (month), 默认 v0 仍是旧版
FRAME_CAPTION_PROMPT_MONTH_V1 = """You are a visual evidence recorder for a third-person travel-vlog video segment (MM-Lifelong month-scale: a streamer's multi-week tour of China across many cities; mixed Chinese-English speech).

This footage will be queried later for questions about: how many times / how many items (counting), who and what appeared (entities: people met, landmarks, shops, dishes, songs), WHY the streamer did something (causes, motivations, triggers he states or reacts to), the order of activities across cities and days, what was said or sung and where (verbatim recall), and attributes (clothing, colors, brands). Any of these details you omit becomes a question you cannot answer.

There are {num_frames} sampled frames at {interval_sec}s intervals, covering video window {abs_start}-{abs_end} (~{window_seconds}s).

{audio_context_block}

For EACH frame describe (2-4 sentences):

1. **Action + cause**: what the streamer / visible people are doing right now (action verbs). When a reason, trigger or motivation is stated in audio or visible (a sign he reads, food he reacts to, a person who calls him over), record it: "he enters the shop BECAUSE the owner waved him in".
2. **Entities + counts + interactions**: name every identifiable entity — people he meets (use names revealed in audio), dishes (name the exact dish), landmarks, shops, vehicles, animals. Count salient categories with exact integers when ≤10 and ≥2 visible. Note WHO interacts with WHOM and how (vendor bargaining, fan greeting, friend joining). When something CHANGES state vs earlier (food finished, weather turned, item bought/lost, clothing changed), record the change explicitly.
3. **Place anchor**: city / district / venue (restaurant, night market, train station, hotel, stage, car interior). Quote location signs verbatim — these anchor cross-video ordering questions.
4. **Speech / text / song**: quote notable spoken lines from the audio context verbatim (preserve original language), note when he SINGS and which song; transcribe on-screen text exactly (signs, menus, subtitles, prices).

Rules:
- Third-person POV: "the streamer" = the main vlogger narrating in English.
- Concise and discriminative: 2-4 sentences per frame; no exhaustive background inventories.
- No vague nouns: "a dish" -> "a bowl of spicy hotpot with tripe"; "a man" -> "a middle-aged shop owner in a blue apron".
- Anti-repetition: only describe what CHANGED from the previous frame; do not restate static scenery.
- Strictly factual: never invent details not visible/audible (questions specifically test hallucination).

First frame example timestamp: {first_ts_example}. Last frame example timestamp: {last_ts_example}.

Return JSON in this exact format:
{output_format}
"""


# day=黑神话 第三人称游戏:复用 OVOBENCH 视觉密集 prompt 但加 audio
FRAME_CAPTION_PROMPT_DAY = """You are a visual evidence recorder for a third-person Chinese game commentary video segment (Black Myth: Wukong Bilibili stream).

This footage will be queried later for questions about: count of small monsters defeated before a major encounter, weapon / item / spell used, location names from in-game UI (e.g. Black Wind Mountain), order of boss fights, items collected. Any UI / combat detail you omit can become a question you cannot answer.

There are {num_frames} sampled frames at {interval_sec}s intervals, covering wall-clock window {abs_start}-{abs_end} (~{window_seconds}s).

{audio_context_block}

For EACH frame describe (2-4 sentences):

1. **Combat / interaction**: what the player character is doing (attacking, dodging, casting, idling). Name the enemy explicitly if visible (small monster vs named boss). Quote any boss name / HP bar text exactly.
2. **UI text**: read on-screen text verbatim — quest title, dialogue, location label, "黑风山" etc. (preserve Chinese characters when present).
3. **Counts**: if multiple enemies on screen, count them.
4. **Place / scene**: in-game biome (mountain path, temple, cave, courtyard), notable landmarks.

Rules:
- Third-person POV (game camera).
- Quote on-screen Chinese / English text verbatim — these are direct answer evidence.
- Anti-repetition: only describe what CHANGED from previous frame.

First frame example timestamp: {first_ts_example}. Last frame example timestamp: {last_ts_example}.

Return JSON in this exact format:
{output_format}
"""


# day V1 (新增, 不覆盖旧版): 按 day test.json 实际题型分布重写
#   Counting 40 / Entity 31 / Temporal 31 / Hallucination 31 / Causal 20 /
#   EventTracking 12 / StateChange 12 / EventRec 11 / LangRecall 6 / Attr 6
# 相比旧版新增: State Change cue (12题, 旧版没有) + Causal cue (20题) +
#   章节/boss 时序锚点; 沿用简略风格 (week recall 实证)。--prompt_version v1 启用
FRAME_CAPTION_PROMPT_DAY_V1 = """You are a visual evidence recorder for a third-person Chinese game playthrough video segment (Black Myth: Wukong, Bilibili walkthrough with commentary; mixed Chinese-English).

This footage will be queried later for questions about: how many enemies/items/attempts (counting), which monster/boss/NPC/weapon/spell appeared (entities), the order of bosses and chapters (temporal), WHY something happened (causes: what killed the player, what triggered a phase change, why he backtracked), and how states CHANGED over time (HP, transformations, equipment swaps, unlocked abilities, boss phases). Any of these you omit becomes a question you cannot answer.

There are {num_frames} sampled frames at {interval_sec}s intervals, covering video window {abs_start}-{abs_end} (~{window_seconds}s).

{audio_context_block}

For EACH frame describe (2-4 sentences):

1. **Combat / action + cause**: what the player character is doing (attacking, dodging, casting, transforming, dying, looting). Name the enemy EXACTLY (named boss vs small monster; quote the boss-name/HP-bar text verbatim). When a cause is visible or narrated, record it: "the player DIES BECAUSE the boss's fire AOE hit during the dodge".
2. **Counts**: exact integers when ≤10 — enemies on screen, items picked up, death/retry count cues.
3. **State change**: note any change vs the previous frame — HP bar level, new weapon/armor equipped, transformation active, boss entering a new phase, a door/path newly opened, item acquired. Use explicit "changed from X to Y" wording.
4. **UI text + place anchor**: read on-screen text verbatim (the CURRENT on-screen location label — copy it EXACTLY as shown, never reuse a location from earlier context; chapter title cards, quest text, item names, dialogue subtitles; preserve Chinese). Name the in-game biome/landmark — chapter/location anchors order questions.

Rules:
- Third-person POV (game camera). The protagonist is the Destined One (天命人).
- Concise and discriminative: 2-4 sentences per frame; no exhaustive scenery inventories.
- No vague nouns: "an enemy" -> "a wolf-headed spear-wielding small monster"; "an item" -> "the item pickup text shows 仙丹".
- Anti-repetition: only describe what CHANGED from the previous frame.
- Strictly factual: never invent enemies, items or events not visible/audible (questions specifically test hallucination).

First frame example timestamp: {first_ts_example}. Last frame example timestamp: {last_ts_example}.

Return JSON in this exact format:
{output_format}
"""


# ============================================================================
# WEEK 增强版 v1 (2026-05-23): 针对 MM-Lifelong 200 题分析得出的强化方向
#
# 200 题分布: Counting 30%, Temporal 18%, Entity Recognition 12%,
#             Causal 8%, Event Recognition 8%, Language Content Recall 8%,
#             Hallucination 5%, Social 4%, Attribute 4%, Event Tracking 3%
#
# v1 关键强化点 (4 个), 基于 v1 baseline 50 题错因分析:
#   (A) ACTOR-CENTRIC 必须区分 'I (camera-wearer)' 和别人, 之前混淆导致
#       Social/Entity Recognition 24 题人称错位.
#   (B) EXHAUSTIVE COUNTING 强制写整数 (1 / 2 / 3 / 4 / 5), 严禁 "some" / "a few".
#       Counting 占 30%, 数错就 0 分.
#   (C) OCR HARD RULE: 所有可读文字必须逐字 (Chinese/English), 包含 logo / 屏幕 /
#       菜单 / 白板. Language Content Recall + Entity (app/brand) 全靠 OCR.
#   (D) COLOR-CLOTHING-NAME triple: 每个出现的人必须写 [hair color, top color/type,
#       bottom color/type, accessories], GT 答案常是 "the girl in the red dress".
#
# 不加: 音频/SRT (用户明确不要), question-aware 先验 (会污染数据).
# ============================================================================
FRAME_CAPTION_PROMPT_WEEK_ENHANCED_V1 = """\
You are a visual evidence recorder for a first-person daily-life video segment \
(EgoLife dataset, camera-wearer POV, shared house with multiple roommates).

This footage will be queried later by MM-Lifelong Week benchmark covering questions about:
COUNTING (30%), TEMPORAL REASONING (18%), ENTITY RECOGNITION (12%), CAUSAL REASONING (8%),
EVENT RECOGNITION (8%), LANGUAGE CONTENT RECALL (8%), HALLUCINATION DETECTION (5%),
SOCIAL INTERACTION (4%), ATTRIBUTE RECOGNITION (4%), EVENT TRACKING (3%).

The actual questions are HIDDEN. Anything you omit in this caption becomes an
unanswerable question.

═══════════════════════════════════════════════════════════════════════════════
[A] ACTOR-CENTRIC: distinguish "I" from other people — CRITICAL
═══════════════════════════════════════════════════════════════════════════════

"I" / "the camera-wearer" = the person holding the camera. You see their HANDS,
not their face. The camera-wearer's actions are seen through THEIR perspective.

EVERY action sentence must explicitly attribute the actor — never use ambiguous
phrasing like "someone does X". Use one of these structures:
  - "I (camera-wearer) <verb> ..."          (when the verb is performed by the wearer)
  - "<person attribute> <verb> ..."          (when performed by another person)
  - "<Person A> and I <verb> ..."            (joint action)

Example PASS (correct attribution):
  "I (camera-wearer) pick up a red mug from the dining table. The girl in the
   pink hair and white t-shirt walks past behind me toward the kitchen."

Example FAIL (ambiguous):
  "Someone picks up a red mug; the kitchen is visible."   ← BAD: who?

When the wearer's role is unclear (e.g. only their hand is visible), assume "I"
unless evidence shows otherwise. NEVER attribute the wearer's action to a
third party.

═══════════════════════════════════════════════════════════════════════════════
[B] EXHAUSTIVE COUNTING — counts must be exact integers when ≤ 10
═══════════════════════════════════════════════════════════════════════════════

For these salient categories ALWAYS give an EXACT INTEGER count when there
are ≤ 10 visible — never "a few" / "some" / "several" / "many":
  - people in the frame
  - chairs / stools / sofas
  - cups / mugs / glasses / bottles (subtype each: glass-of-water / coffee-cup / wine-bottle)
  - plates / bowls / dishes (subtype: empty / with food / half-eaten)
  - laptops / phones / tablets / screens (subtype: open / closed / on / off)
  - bags / boxes / containers
  - food items on the table (subtype each dish by visible name/color)
  - decoration items: vases, plush toys, posters, candles

Example PASS:
  "On the dining table I see 2 silver laptops (one open showing a Slack-like
   blue-and-white chat, one closed), 3 ceramic mugs (white, red with a smiley,
   blue), 1 vase with pink tulips, 4 stacked rice bowls (empty), 2 chopsticks
   pairs."

Example FAIL:
  "Some laptops and several mugs on the table."   ← BAD: how many of each?

If a category has > 10 items, write "more than 10 <category>" and still list
the most prominent few.

═══════════════════════════════════════════════════════════════════════════════
[C] OCR HARD RULE — every visible piece of text MUST be transcribed verbatim
═══════════════════════════════════════════════════════════════════════════════

Transcribe ALL visible text in the frame, character-by-character, preserving
the original language (Chinese / English / mixed):

  - Shop signs / billboards / store names (with their Chinese characters)
  - Brand logos: 抖音 / Douyin / 美团 / 京东 / 微信 / KFC / Starbucks / 麦当劳 /
    iPhone / Lenovo / ThinkPad / DELL / Apple / Sony / Nintendo / Steam / etc.
  - Phone / laptop / TV / projector screens — quote app names, chat content,
    page titles, URLs if visible
  - Menus / receipts / labels — every line item if legible
  - Whiteboards / paper notes / handwritten lists
  - Clothing prints / accessory text
  - Subtitles / overlay text in the video
  - Numbers visible on packaging, screens, signs (prices, codes, dates)

Example PASS:
  "On the laptop screen I see the title bar '飞书 · A1_JAKE_DAY1 共享文档', a
   table column header reading '日期', and a chat message from '张三' saying
   '好的'. The brown shopping bag has '盒马鲜生' (Hema Fresh) printed in
   teal letters on its front. The whiteboard has hand-written Chinese:
   '11:00 起床, 13:00 吃饭, 14:00 开会'."

Example FAIL:
  "The laptop shows a chat app. There is some Chinese writing on the whiteboard."
  ← BAD: lost all critical evidence.

═══════════════════════════════════════════════════════════════════════════════
[D] COLOR + CLOTHING + HAIR + ACCESSORIES — full identification triple
═══════════════════════════════════════════════════════════════════════════════

For EVERY visible person (camera-wearer optional, others mandatory), in EVERY
frame, give the full visual signature:

  [hair attribute] + [top color & type] + [bottom color & type] +
  [accessories: glasses / hat / jewelry / shoes / bag if visible] + [position]

Then if context reveals a NAME (someone calls them, on-screen subtitle, etc.),
attach the name.

Why: GT answers in this benchmark are typically "the girl in the red dress" or
"the boy with curly hair" — NOT names. Visual attributes are the answer evidence.

Example PASS:
  "Three roommates visible at the dining table:
   - A woman with long pink hair, white t-shirt with black 'PEACE' print,
     ripped blue jeans, silver hoop earrings — seated on the far left.
   - A man with short curly black hair, gray sweater, black sweatpants,
     wearing round glasses — seated opposite me, holding a cup.
   - A woman with shoulder-length straight black hair, mint-green long-sleeve
     shirt with cat embroidery, black skirt, no visible accessories — seated
     to the man's right.
   Names mentioned by camera-wearer in earlier captions: Jake (= the curly-hair man)."

Example FAIL:
  "Three roommates are at the table eating dinner."   ← BAD.

═══════════════════════════════════════════════════════════════════════════════
[E] BACKGROUND ENTITY CENSUS — list every distinct visible object
═══════════════════════════════════════════════════════════════════════════════

Beyond the action and people, list ALL distinct movable objects you see, with
their current LOCATION and STATE. This is mandatory because Counting / Entity
Recognition / Cumulative State questions ask about objects that are NOT central
to the current action.

Categories to scan: cups, bottles, plates, bowls, utensils, food items,
laptops, phones, tablets, chargers, headphones, books, notebooks, pens,
remote controls, plush toys, vases, candles, lamps, plants, posters,
clothes left around, bags, shoes, boxes, devices.

For each: [count] + [color / material] + [location on which surface] +
[state: open/closed, full/empty, plugged/unplugged].

═══════════════════════════════════════════════════════════════════════════════
[F] EVENTS — temporal cues + causality
═══════════════════════════════════════════════════════════════════════════════

Each action sentence should carry a temporal cue:
  - "just finished ...", "about to ...", "while ...", "after returning from ..."

When one action triggers another, note BOTH explicitly:
  - "Jake points at the whiteboard (showing the schedule), and I write '11:00
     起床' on it."

═══════════════════════════════════════════════════════════════════════════════
[G] HALLUCINATION-FREE — strict factual recording
═══════════════════════════════════════════════════════════════════════════════

If a detail is uncertain or only partly visible, mark it explicitly:
  - "the bottle (label partially obscured, possibly Coca-Cola)"
  - "a poster on the wall (text too small to read)"

NEVER invent details to fill gaps. Hallucination Detection questions specifically
penalize made-up facts.

═══════════════════════════════════════════════════════════════════════════════
[H] MEMORY MARKERS — exact phrases for the post-processor
═══════════════════════════════════════════════════════════════════════════════

When applicable, use these EXACT verbatim phrases (the extractor parses them):

  - When the camera-wearer drinks from a vessel:
    **"I drink from <cup/bottle/glass>"**
  - When the camera-wearer sits down or stands up:
    **"I sit down at <place>"**     /    **"I stand up from <place>"**
  - When the camera-wearer looks at their phone:
    **"I check my phone"** + (app/content visible)

═══════════════════════════════════════════════════════════════════════════════
[FORMAT]

There are {num_frames} sampled frames at {interval_sec}s intervals, covering
wall-clock window {abs_start}-{abs_end} (~{window_seconds}s).

{audio_context_block}

For EACH frame, write 5-7 sentences in this order:

  1. **Activity sentence**: actor (I or named/described person) + verb + object + temporal cue
     [+ DRINK/SIT/PHONE marker when applicable].
  2. **People sentence**: each visible person with FULL visual signature
     [hair + top + bottom + accessories + position], plus name if known.
  3. **Background entity census sentence**: every distinct movable object on surfaces with
     [count + color + location + state]. Include items NOT involved in current action.
  4. **On-screen text sentence**: verbatim quotes of every readable piece of text in the frame
     (Chinese characters preserved as-is).
  5. **Scene sentence**: room/location, lighting, ambient details (fish tank? plants? AC on?).
  6. (optional) **Linking sentence**: how this frame differs from previous one
     (someone arrived/left, object moved, light changed, screen content updated).
  7. (optional) **Causal/social sentence**: when one person's action triggers another's, or
     when there is visible give-and-take/joint activity.

Rules:
- First-person POV: "I" = camera-wearer (the person holding the camera). Never confuse with others.
- ANTI-REPETITION across frames is OUR ENEMY: if a cup that was on the table is still there in
  the next frame, RE-LIST it. Stable backgrounds (wall, floor) can be omitted after first frame.
- No vague nouns ("something", "someone", "a thing") — always name the concrete object/person.
- Be strictly factual: don't invent. Mark uncertainty explicitly.
- Counts MUST be exact integers when ≤ 10.
- DRINK / SIT / PHONE markers MUST use the EXACT phrasings above.

First frame example timestamp: {first_ts_example}. Last frame example timestamp: {last_ts_example}.

Return JSON in this exact format:
{output_format}
"""


def _get_prompt_for_dataset(dataset_type: str, use_enhanced_week: bool = False,
                              prompt_version: str = "v0") -> str:
    if dataset_type == "week":
        if prompt_version == "v1":
            return FRAME_CAPTION_PROMPT_WEEK_ENHANCED_V1
        return FRAME_CAPTION_PROMPT_WEEK_ENHANCED if use_enhanced_week else FRAME_CAPTION_PROMPT_WEEK
    if dataset_type == "month" and prompt_version == "v1":
        # month V1: 按 val.json 题型分布重写 (Causal/Entity/LangRecall 补强, 简略风格)
        return FRAME_CAPTION_PROMPT_MONTH_V1
    if dataset_type == "day" and prompt_version == "v1":
        # day V1: 按 test.json 题型分布重写 (StateChange/Causal 补强, 章节锚点)
        return FRAME_CAPTION_PROMPT_DAY_V1
    return {
        "month": FRAME_CAPTION_PROMPT_MONTH,
        "day": FRAME_CAPTION_PROMPT_DAY,
    }[dataset_type]


# ======================================================================
# Audio context: 给定 (start_sec, end_sec) 返回该时间窗口内的 transcript 文本
# ======================================================================

class AudioContextProvider:
    """简单的时间索引:给定 (day_num, start_sec, end_sec) 返回该窗口的 audio
    transcript(拼接成一段文本)。entries 是 AudioCueExtractor / EgoLife sync
    返回的 list[{time_span, caption, speaker, text}]。

    time_span 格式: "{day}-HH:MM:SS-HH:MM:SS"
    """

    def __init__(self, entries_by_day: Dict[int, List[dict]]):
        self._by_day = entries_by_day  # day_num -> list of entries sorted by start

    @classmethod
    def empty(cls) -> "AudioContextProvider":
        return cls({})

    def lookup(self, day_num: int, start_sec: float, end_sec: float,
               max_lines: int = 6) -> str:
        """返回该 (day, [start,end] 秒区间) 内的 audio transcript 拼接字符串。
        无 audio 数据则返回空串。"""
        entries = self._by_day.get(day_num, [])
        if not entries:
            return ""
        hits: List[str] = []
        for e in entries:
            es = e.get("_start_sec")
            ee = e.get("_end_sec")
            if es is None:
                continue
            # 区间相交
            if ee < start_sec - 1.0:
                continue
            if es > end_sec + 1.0:
                break  # entries 按 start 排序,后续都更晚
            txt = e.get("text") or e.get("caption") or ""
            sp = e.get("speaker") or "SPEAKER_UNK"
            hits.append(f"[{sp}] {txt}".strip())
            if len(hits) >= max_lines:
                break
        return "\n".join(hits)


def _parse_time_span_to_seconds(time_span: str) -> Tuple[int, float, float]:
    """'1-21:35:59-21:36:00' -> (1, 77759.0, 77760.0)"""
    parts = time_span.split("-")
    if len(parts) < 3:
        return (1, 0.0, 0.0)
    day_num = int(parts[0])
    # time HH:MM:SS may itself have ':' so re-split safely
    start_str = parts[1]
    end_str = parts[2]
    def _to_sec(s: str) -> float:
        h, m, sec = s.split(":")
        return int(h) * 3600 + int(m) * 60 + float(sec)
    return day_num, _to_sec(start_str), _to_sec(end_str)


def build_audio_context(
    dataset_type: str,
    enabled: bool,
    args,
    sub_videos: List[Tuple[str, str, int, int]],
) -> AudioContextProvider:
    """根据 audio_source 加载 audio entries 并按 day 归组、为 lookup 预填入秒数。

    audio_source 选项:
      egolife_sync : EgoLifeCap/Sync/<user>_DAY{n}_*.json 中的 transcript 条目(week 默认)
      whisper      : 对每个 sub_video 跑 Whisper(day/month 默认)
      off          : 不启用
    """
    if not enabled:
        return AudioContextProvider.empty()

    src = (args.audio_source or "").lower()
    if not src:
        # 默认按 dataset_type 选
        src = "egolife_sync" if dataset_type == "week" else "whisper"
    by_day: Dict[int, List[dict]] = {}

    if src == "egolife_sync":
        # 收集 sync 目录下对应 day 的所有 transcript
        days_seen = sorted({m[2] for m in sub_videos})
        for day_num in days_seen:
            pattern = os.path.join(
                args.egolife_sync_dir,
                f"{args.user_id}_DAY{day_num}_*.json",
            )
            entries: List[dict] = []
            for fpath in sorted(glob.glob(pattern)):
                try:
                    entries.extend(
                        load_existing_egolife_transcript_as_audio_caps(
                            fpath, day_num=day_num,
                        )
                    )
                except Exception as e:
                    logger.warning(f"[audio sync] {fpath} load failed: {e}")
            # 注入 _start_sec/_end_sec 供 lookup 用
            for e in entries:
                _, ss, ee = _parse_time_span_to_seconds(e["time_span"])
                e["_start_sec"] = ss
                e["_end_sec"] = ee
            entries.sort(key=lambda x: x["_start_sec"])
            by_day[day_num] = entries
            logger.info(f"[audio sync] DAY{day_num}: {len(entries)} transcript turns")
        return AudioContextProvider(by_day)

    if src == "whisper":
        extractor = AudioCueExtractor(
            asr_backend=args.asr_backend,
            whisper_model_size=args.whisper_model_size,
            hf_token=args.hf_token,
            device="cuda" if args.cuda else "cpu",
            do_diarization=args.diarize,
            asr_initial_prompt=_asr_initial_prompt_for_dataset(dataset_type),
            asr_vad_min_silence_ms=300 if dataset_type == "month" else 500,
        )
        # 逐 sub_video 跑 whisper,把 entries 按 day 累计
        for sub_id, vpath, day_num, _ in sub_videos:
            try:
                entries = extractor.extract(
                    vpath, day_num=day_num,
                    language=_asr_language_for_dataset(dataset_type),
                )
                for e in entries:
                    _, ss, ee = _parse_time_span_to_seconds(e["time_span"])
                    e["_start_sec"] = ss
                    e["_end_sec"] = ee
                by_day.setdefault(day_num, []).extend(entries)
                logger.info(f"[audio whisper] {sub_id}: {len(entries)} segs")
            except Exception as e:
                logger.warning(f"[audio whisper] {sub_id} failed: {e}")
        for day_num in by_day:
            by_day[day_num].sort(key=lambda x: x["_start_sec"])
        return AudioContextProvider(by_day)

    logger.warning(f"unknown audio_source {src!r}, disabled")
    return AudioContextProvider.empty()


def _asr_initial_prompt_for_dataset(dataset_type: str) -> str:
    return {
        "day": ("以下是《黑神话:悟空》中文游戏实况解说,包含游戏内打斗、妖怪、"
                "法术、装备等专业术语,以及主播的中文解说和评论。"),
        "month": ("A travel vlog of a streamer touring China, with English "
                  "commentary from the streamer and ambient Chinese conversations "
                  "from locals and other speakers."),
        "week": ("First-person daily-life recording of a roommate group. Speakers "
                 "address each other by name (Alice / Jake / ...). Mixed English-Chinese."),
    }.get(dataset_type, "")


def _asr_language_for_dataset(dataset_type: str) -> Optional[str]:
    return {"day": "zh", "month": None, "week": None}.get(dataset_type, None)


# ======================================================================
# Per-sub-video async build (复刻 ovobench_async 的 _run_one_video_async,
# 但 prompt 模板按 dataset_type 选,并注入 audio context)
# ======================================================================

# ======================================================================
# Caption clip 工厂 (dataset-level pipeline 用): 接 clip meta 返回 sync 函数,
# sync 函数内部跑视频采样 + N 个 window 的 VLM caption, 返回 List[payload]
# (供 segmenter 按时间序消费)。
# ======================================================================

def make_caption_clip_fn(
    *,
    hyper_vg: HyperVideoGraph,
    interval_seconds: float,
    window_frames: int,
    max_new_tokens: int,
    caption_prompt_template: str,
    audio_provider: AudioContextProvider,
    sp_extractor=None,
    hyper_time_range: Optional[Tuple[float, float]] = None,
):
    """返回 sync `caption_clip_fn(idx, meta)` -> Optional[List[payload]]。
    meta 包含: sub_id, video_path, day_num, clip_start_seconds。

    sp_extractor (可选, 默认 None=行为不变): 通道B结构化感知
    (modules/structured_perception.StructuredPerceptionExtractor)。非 None 时
    每个窗口 caption 成功后用同一批帧再抽一份结构化实体/事件 JSON, 失败只 warn。

    hyper_time_range (2026-07-10 分段并行建图): (lo, hi) 绝对秒
    (day*86400+当日秒)。clip 起点不在范围内 -> 整个 clip 跳过 (不抽帧不
    caption)。多进程各建一段超图, 事后合并+topic全局重建。默认 None=原行为。
    """
    from videorag.video_processing import (
        _seconds_to_timestamp_number as _sec_to_tsn,
    )

    def caption_clip_fn(idx: int, meta: dict) -> Optional[List[dict]]:
        video_path = meta["video_path"]
        sub_id = meta["sub_id"]
        day_num = meta["day_num"]
        clip_start_seconds = meta["clip_start_seconds"]

        # 分段并行: clip 起点在范围外 -> 直接跳过 (段边界按 clip 粒度对齐)
        if hyper_time_range is not None:
            _abs = day_num * 86400 + float(clip_start_seconds)
            if not (hyper_time_range[0] <= _abs < hyper_time_range[1]):
                return None

        if not os.path.exists(video_path):
            logger.error(f"[caption_clip] {sub_id}: video not found {video_path}")
            return None

        try:
            base64_frames, _, time_ranges = sample_frames_by_interval(
                video_path,
                interval_seconds=interval_seconds,
                output_format='base64',
                time_span_info=None,
            )
        except Exception as e:
            logger.error(f"[caption_clip] {sub_id} sample_frames failed: {e}")
            return None

        n_frames = len(base64_frames)
        if n_frames == 0:
            logger.warning(f"[caption_clip] {sub_id}: 0 frames")
            return None
        n_windows = (n_frames + window_frames - 1) // window_frames

        payloads: List[dict] = []
        for w_idx in range(n_windows):
            s = w_idx * window_frames
            e = min(s + window_frames, n_frames)
            window_frames_b64 = base64_frames[s:e]
            window_ranges = time_ranges[s:e]
            win_start_sec = (
                _timestamp_num_to_seconds(window_ranges[0]['start']) + clip_start_seconds
            )
            win_end_sec = (
                _timestamp_num_to_seconds(window_ranges[-1]['end']) + clip_start_seconds
            )
            win_time_span = (
                f"{day_num}-{_seconds_to_hms(win_start_sec)}-{_seconds_to_hms(win_end_sec)}"
            )

            audio_text = audio_provider.lookup(day_num, win_start_sec, win_end_sec)
            audio_block = (
                "Audio transcript heard during this window. INTEGRATE it into the caption: "
                "QUOTE the key spoken lines VERBATIM with the speaker (e.g. Jake says \"来者不善\"), note songs/singing, and use names/topics it reveals. Key dialogue lines are answer evidence — do not drop them:\n"
                f"{audio_text}\n"
            ) if audio_text else ""

            n_w = len(window_frames_b64)
            window_seconds = max(
                int(round(win_end_sec - win_start_sec)),
                int(interval_seconds) * n_w,
            )
            abs_start = f"DAY{day_num}-{_seconds_to_hms(win_start_sec)}"
            abs_end = f"DAY{day_num}-{_seconds_to_hms(win_end_sec)}"
            first_ts_abs = (
                _timestamp_num_to_seconds(window_ranges[0]['start']) + clip_start_seconds
            )
            last_ts_abs = (
                _timestamp_num_to_seconds(window_ranges[-1]['start']) + clip_start_seconds
            )
            first_ts_example = f"DAY{day_num}-{_seconds_to_hms(first_ts_abs)}"
            last_ts_example = f"DAY{day_num}-{_seconds_to_hms(last_ts_abs)}"
            try:
                caption_prompt = caption_prompt_template.format(
                    output_format=OUTPUT_FORMAT,
                    num_frames=n_w,
                    interval_sec=int(interval_seconds),
                    window_seconds=window_seconds,
                    abs_start=abs_start,
                    abs_end=abs_end,
                    first_ts_example=first_ts_example,
                    last_ts_example=last_ts_example,
                    audio_context_block=audio_block,
                )
            except KeyError as ke:
                logger.warning(f"[caption_clip] {sub_id} 模板缺占位符 {ke}, fallback")
                from hypervideo.prompts.frame_caption_prompt import (
                    FRAME_CAPTION_WINDOW_OVOBENCH_PROMPT,
                )
                caption_prompt = FRAME_CAPTION_WINDOW_OVOBENCH_PROMPT.format(
                    output_format=OUTPUT_FORMAT,
                    num_frames=n_w,
                    interval_sec=int(interval_seconds),
                    window_seconds=window_seconds,
                    abs_start=abs_start,
                    abs_end=abs_end,
                    first_ts_example=first_ts_example,
                    last_ts_example=last_ts_example,
                )

            # 把 window_ranges 的秒数 shift 到 wall-clock, 让 _caption_window_batch
            # 内部产生的 dense_caption keys 也是 DAY 绝对时间
            if clip_start_seconds > 0:
                shifted_ranges = []
                for r in window_ranges:
                    sa = _timestamp_num_to_seconds(r['start']) + clip_start_seconds
                    ea = _timestamp_num_to_seconds(r['end']) + clip_start_seconds
                    shifted_ranges.append({
                        'start': _sec_to_tsn(sa),
                        'end': _sec_to_tsn(ea),
                    })
            else:
                shifted_ranges = window_ranges

            t0 = time.time()
            caption_dict = _caption_window_batch(
                hyper_vg=hyper_vg,
                window_b64=window_frames_b64,
                window_ranges=shifted_ranges,
                caption_prompt=caption_prompt,
                max_new_tokens=max_new_tokens,
                day_num=day_num,
            )
            dt = time.time() - t0
            if not caption_dict:
                logger.error(f"[caption_clip] {sub_id} window {w_idx+1}/{n_windows} 失败")
                continue
            logger.info(
                f"[caption_clip] {sub_id} {w_idx+1}/{n_windows} "
                f"({win_time_span}) {n_w} 帧 耗时 {dt:.1f}s"
                f"{' [+audio]' if audio_text else ''}"
            )
            # 通道B (可选): 同帧再抽结构化实体/事件, 独立存 jsonl, 失败不影响主通道
            if sp_extractor is not None:
                sp_extractor.extract_window(
                    window_frames_b64, win_time_span, day_num,
                )
            payloads.append({
                "caption_dict": caption_dict,
                "time_span": win_time_span,
                "day_num": day_num,
                "window_frames_b64": window_frames_b64,
                "sub_id": sub_id,
            })

        return payloads if payloads else None

    return caption_clip_fn


# ======================================================================
# Segment-one wrapper (dataset-level pipeline 用): 收 payload, 调 segmenter +
# add_episode_node 入图。复用 builder_adapter_v2.make_segment_only_fn 同逻辑。
# ======================================================================

def make_segment_one_fn_for_dataset(builder):
    """跟 builder_adapter_v2.make_segment_only_fn 一样, 但签名是
    `async (payload) -> Optional[Episode]`, 没有 w_idx 参数, 适配
    pipeline_v3_dataset.SegmentOneFn."""
    segment_window_fn = make_segment_only_fn(builder)

    async def _segment_one(payload):
        # builder_adapter_v2.make_segment_only_fn 内部其实只用到 payload, w_idx
        # 仅作为日志参数, 透传一个占位值。
        return await segment_window_fn(payload.get("sub_id", "?"), payload)

    return _segment_one


def make_visual_index_fn_for_dataset(builder):
    """sync. 接 payload, 调 index_window_visual。"""
    def _vi(payload):
        try:
            builder.index_window_visual(
                payload["time_span"], payload["window_frames_b64"],
            )
        except Exception as e:
            logger.warning(f"[visual_index] {payload.get('sub_id')}: {e}")
    return _vi


async def _run_one_sub_video_async(
    *,
    hyper_vg: HyperVideoGraph,
    video_path: str,
    sub_video_id: str,
    day_num: int,
    clip_start_seconds: int,
    interval_seconds: float,
    window_frames: int,
    max_new_tokens: int,
    caption_prompt_template: str,
    audio_provider: AudioContextProvider,
    pipeline_mode: str,
    caption_concurrency: int,
    llm_timer: Optional[LLMTimer] = None,
    final_flush: bool = True,
    hyper_time_range: Optional[Tuple[float, float]] = None,
) -> AsyncPipelineStats:
    """单 sub-video 异步建图。caption 阶段会从 audio_provider 取当前窗口的
    audio transcript 填进 prompt 的 {audio_context_block} 占位符。

    hyper_time_range (2026-07-10 分段并行建图): (lo_abs, hi_abs) 绝对秒
    (day*86400+当日秒)。设置后仅该范围内的窗口进 segmenter/超图, 范围外窗口
    caption 后直接丢弃。用于多进程分段并行重建超图, 默认 None=原行为。"""

    if not os.path.exists(video_path):
        raise FileNotFoundError(f"video not found: {video_path}")

    logger.info(f"  [Sample] {os.path.basename(video_path)}, interval={interval_seconds}s")
    base64_frames, _, time_ranges = sample_frames_by_interval(
        video_path,
        interval_seconds=interval_seconds,
        output_format='base64',
        time_span_info=None,
    )
    n_frames = len(base64_frames)
    logger.info(f"  [Sample] {n_frames} 帧")
    if n_frames == 0:
        return AsyncPipelineStats(n_windows=0)

    n_windows = (n_frames + window_frames - 1) // window_frames

    # ---------- caption stage ----------
    # 关键: clip 内 sample_frames 给出的秒数是相对 clip 起始 (0). 在 EgoLife week
    # 模式下我们要把这个值加上 clip_start_seconds, 让 segmenter 看到的时间戳
    # 是 DAY{n} 的 wall-clock 绝对值, 这样跨 clip 时间连续 + 跨 clip gap >=60s
    # 时 segmenter 的 _check_hard_boundary 会自动切断 episode.
    def caption_window_fn(w_idx: int) -> Optional[dict]:
        s = w_idx * window_frames
        e = min(s + window_frames, n_frames)
        window_frames_b64 = base64_frames[s:e]
        window_ranges = time_ranges[s:e]
        # 分段并行建图: 窗口起点不在 hyper_time_range 内 -> 跳过 (caption 也不打)
        if hyper_time_range is not None:
            _ws = (_timestamp_num_to_seconds(window_ranges[0]['start'])
                   + clip_start_seconds)
            _abs = day_num * 86400 + _ws
            if not (hyper_time_range[0] <= _abs < hyper_time_range[1]):
                return None
        # 相对 clip 起始的秒数 -> 加 offset 得到 DAY{day_num} 绝对秒数
        win_start_sec = (
            _timestamp_num_to_seconds(window_ranges[0]['start']) + clip_start_seconds
        )
        win_end_sec = (
            _timestamp_num_to_seconds(window_ranges[-1]['end']) + clip_start_seconds
        )
        win_time_span = (
            f"{day_num}-{_seconds_to_hms(win_start_sec)}-{_seconds_to_hms(win_end_sec)}"
        )

        # audio_provider 也按绝对秒数 lookup (entries 已经按 DAY 内 wall-clock 索引)
        audio_text = audio_provider.lookup(day_num, win_start_sec, win_end_sec)
        if audio_text:
            audio_block = (
                "Audio transcript heard during this window. INTEGRATE it into the caption: "
                "QUOTE the key spoken lines VERBATIM with the speaker (e.g. Jake says \"来者不善\"), note songs/singing, and use names/topics it reveals. Key dialogue lines are answer evidence — do not drop them:\n"
                f"{audio_text}\n"
            )
        else:
            audio_block = ""

        n_w = len(window_frames_b64)
        window_seconds = max(
            int(round(win_end_sec - win_start_sec)),
            int(interval_seconds) * n_w,
        )
        abs_start = f"DAY{day_num}-{_seconds_to_hms(win_start_sec)}"
        abs_end = f"DAY{day_num}-{_seconds_to_hms(win_end_sec)}"
        first_ts_abs = (
            _timestamp_num_to_seconds(window_ranges[0]['start']) + clip_start_seconds
        )
        last_ts_abs = (
            _timestamp_num_to_seconds(window_ranges[-1]['start']) + clip_start_seconds
        )
        first_ts_example = f"DAY{day_num}-{_seconds_to_hms(first_ts_abs)}"
        last_ts_example = f"DAY{day_num}-{_seconds_to_hms(last_ts_abs)}"
        try:
            caption_prompt = caption_prompt_template.format(
                output_format=OUTPUT_FORMAT,
                num_frames=n_w,
                interval_sec=int(interval_seconds),
                window_seconds=window_seconds,
                abs_start=abs_start,
                abs_end=abs_end,
                first_ts_example=first_ts_example,
                last_ts_example=last_ts_example,
                audio_context_block=audio_block,
            )
        except KeyError as ke:
            logger.warning(f"  [Caption] prompt 模板占位符缺失 {ke}, 退到原 OVOBENCH 模板")
            from hypervideo.prompts.frame_caption_prompt import (
                FRAME_CAPTION_WINDOW_OVOBENCH_PROMPT,
            )
            caption_prompt = FRAME_CAPTION_WINDOW_OVOBENCH_PROMPT.format(
                output_format=OUTPUT_FORMAT,
                num_frames=n_w,
                interval_sec=int(interval_seconds),
                window_seconds=window_seconds,
                abs_start=abs_start,
                abs_end=abs_end,
                first_ts_example=first_ts_example,
                last_ts_example=last_ts_example,
            )

        # 给 window_ranges 的 start/end 加 clip offset, 让 _caption_window_batch
        # 内部生成的 dense_caption keys (DAY{n}-HH:MM:SS-HH:MM:SS) 走的是
        # DAY 绝对 wall-clock 时间.
        if clip_start_seconds > 0:
            from videorag.video_processing import (
                _seconds_to_timestamp_number as _sec_to_tsn,
            )
            shifted_window_ranges = []
            for r in window_ranges:
                sa = _timestamp_num_to_seconds(r['start']) + clip_start_seconds
                ea = _timestamp_num_to_seconds(r['end']) + clip_start_seconds
                shifted_window_ranges.append({
                    'start': _sec_to_tsn(sa),
                    'end': _sec_to_tsn(ea),
                })
        else:
            shifted_window_ranges = window_ranges

        t0 = time.time()
        caption_dict = _caption_window_batch(
            hyper_vg=hyper_vg,
            window_b64=window_frames_b64,
            window_ranges=shifted_window_ranges,
            caption_prompt=caption_prompt,
            max_new_tokens=max_new_tokens,
            day_num=day_num,
        )
        dt = time.time() - t0
        if not caption_dict:
            logger.error(f"  [Caption] {sub_video_id} window {w_idx+1}/{n_windows} 失败")
            return None
        logger.info(
            f"  [Caption-batch] {sub_video_id} window {w_idx+1}/{n_windows} "
            f"({win_time_span}) {n_w} 帧 -> {len(caption_dict['dense_caption'])} caps "
            f"耗时 {dt:.1f}s{' [+audio]' if audio_text else ''}"
        )
        return {
            "caption_dict": caption_dict,
            "time_span": win_time_span,
            "day_num": day_num,
            "window_frames_b64": window_frames_b64,
        }

    async def builder_call_fn(w_idx: int, payload: dict) -> None:
        await hyper_vg.hypergraph_builder.process_window_caption_v2(
            caption_dict=payload["caption_dict"],
            time_span=payload["time_span"],
            day_num=payload["day_num"],
        )

    def visual_index_fn(w_idx: int, payload: dict) -> None:
        hyper_vg.hypergraph_builder.index_window_visual(
            payload["time_span"], payload["window_frames_b64"],
        )

    async def flush_fn() -> None:
        # 不在每个 sub-video 结束 save,main 循环最后统一 save
        await hyper_vg.hypergraph_builder.flush()

    def save_fn() -> None:
        pass  # 跨 sub-video 不 save 中间状态,避免反复 I/O

    if llm_timer is not None:
        ctx = llm_timer.patch(hyper_vg.llm)
    else:
        from contextlib import nullcontext
        ctx = nullcontext()

    with ctx:
        if pipeline_mode == "v3":
            upgrade_builder_segmenter_to_v3(hyper_vg.hypergraph_builder)
            segment_only_fn = make_segment_only_fn(hyper_vg.hypergraph_builder)
            build_episode_only_fn = make_build_episode_only_fn(hyper_vg.hypergraph_builder)
            flush_segmenter_fn = make_flush_segmenter_fn(hyper_vg.hypergraph_builder)
            flush_builder_fn = make_flush_builder_fn(hyper_vg.hypergraph_builder)
            stats = await build_video_async_v3(
                n_windows=n_windows,
                caption_window_fn=caption_window_fn,
                segment_only_fn=segment_only_fn,
                build_episode_only_fn=build_episode_only_fn,
                visual_index_fn=visual_index_fn,
                flush_segmenter_fn=flush_segmenter_fn,
                flush_builder_fn=flush_builder_fn,
                save_fn=save_fn,
                progress_log_every=20,
                caption_concurrency=caption_concurrency,
                episode_queue_size=8,
                final_flush=final_flush,
            )
        else:
            stats = await build_video_async(
                n_windows=n_windows,
                caption_window_fn=caption_window_fn,
                builder_call_fn=builder_call_fn,
                visual_index_fn=visual_index_fn,
                flush_fn=flush_fn,
                save_fn=save_fn,
                progress_log_every=20,
                queue_size=2,
                caption_concurrency=caption_concurrency,
                final_flush=final_flush,
            )
    return stats


# ======================================================================
# 工具:entity_id / profile / final save
# ======================================================================

def _augment_fact_extractor_inplace(hyper_vg: HyperVideoGraph) -> None:
    extractor = hyper_vg.hypergraph_builder._fact_extractor
    if getattr(extractor._llm_func, "_entity_aware_wrapped", False):
        return
    orig = extractor._llm_func

    async def wrapped(prompt, *args, **kwargs):
        return await orig(augment_fact_prompt(prompt), *args, **kwargs)

    wrapped._entity_aware_wrapped = True
    extractor._llm_func = wrapped
    logger.info("[entity_id] fact-extractor LLM wrapped")


def _flush_builder(hyper_vg: HyperVideoGraph) -> None:
    loop = always_get_an_event_loop()
    try:
        loop.run_until_complete(hyper_vg.hypergraph_builder.flush())
    except Exception as e:
        logger.warning(f"[flush] failed: {e}")


# ======================================================================
# Main
# ======================================================================

def main():
    parser = argparse.ArgumentParser(
        description="Unified mmlifelong processing: day/week/month + v3 + audio prompt",
    )
    parser.add_argument(
        "--dataset_type", default="day", choices=["day", "week", "month"],
        help="day=黑神话; week=EgoLife A1_JAKE; month=YouTube vlogs",
    )

    # ---- 视频路径 ----
    parser.add_argument(
        "--video_dir", type=str,
        default="/mnt/tokyo-ai/gst/MM-Lifelong/videos",
        help="视频根目录。day/month: /mnt/tokyo-ai/gst/MM-Lifelong/videos; "
             "week: /mnt/tokyo-ai/gst/EgoLife/egolife (会用 user_id/DAY{n}/ 下面)",
    )
    parser.add_argument(
        "--video_list", type=str,
        default="/mnt/tokyo-ai/gst/MM-Lifelong/video_list.txt",
        help="month dataset_type 用:YouTube IDs 顺序表",
    )
    parser.add_argument(
        "--user_id", type=str, default="A1_JAKE",
        help="week dataset_type 用:EgoLife user 子目录名",
    )
    parser.add_argument(
        "--days", type=str, default="1,2,3,4,5,6,7",
        help="week 用:要处理的天数列表(逗号分隔)",
    )

    # ---- save ----
    parser.add_argument(
        "--save_root", type=str,
        default="/mnt/tokyo-ai/gst/GST_EGOSERVE/all_results",
    )
    parser.add_argument(
        "--datasets_type", type=str, default="mmlifelong_day_v1",
        help="working_dir 命名后缀,默认 = mmlifelong_<dataset_type>",
    )

    # ---- caption ----
    parser.add_argument(
        "--caption_model_name", type=str, default="qwen_vllm",
        choices=["qwen_api", "qwen_vllm"],
    )
    parser.add_argument("--qwen_api_model", type=str, default="qwen-vl-max")
    parser.add_argument(
        "--qwen_api_key", type=str, default="YOUR_API_KEY",
    )
    parser.add_argument(
        "--vllm_base_url", type=str,
        default=os.environ.get("VLLM_BASE_URL", "http://10.0.0.27:8000/v1"),
    )
    parser.add_argument(
        "--vllm_model_name", type=str,
        default=os.environ.get("VLLM_MODEL_NAME", "Qwen3-VL-8B-Instruct"),
    )
    parser.add_argument("--interval_seconds", type=float, default=5.0)
    parser.add_argument("--gap_threshold_seconds", type=float, default=60.0,
        help="时间间隙硬边界阈值(秒)。day/month 单视频连续, 设极大(如 1e9)禁用, 避免 chunk 拼接假间隙导致 segmenter 反复强制分割/builder死锁")
    parser.add_argument("--max_buffer_seconds", type=float, default=120.0,
        help="episode 最长时长上限 (秒)。month 建议 300 (用户指定 5min), 默认 120 不变")
    parser.add_argument("--chunk_seconds", type=int, default=600,
        help="day/month 长视频预切片段长 (秒, stream-copy)。整段预采样会卡死 10h+ 视频")
    parser.add_argument("--legacy_per_video_pipeline", action="store_true",
        help="day/month 走旧的逐 sub-video 路径 (每视频强制 flush, episode 不跨段; 仅回滚用)")
    parser.add_argument("--window_frames", type=int, default=6)
    parser.add_argument("--max_new_tokens", type=int, default=2048)
    parser.add_argument("--defer_topic_aggregation", action="store_true",
        help="建图期跳过 topic 聚合 (只抽 fact),避免超长连续 topic 的 role/coherence "
             "超线性重算瓶颈。fact 挂占位 topic,topic 留到最后用 rebuild_topics_light "
             "全局重建。drain 阶段可提速 3-5 倍。默认关闭保持原行为。")
    parser.add_argument("--hyper_time_range", type=str, default="",
        help="分段并行建图: 'lo,hi' 绝对秒(day*86400+当日秒)。仅该范围内窗口"
             "caption+建图, 范围外跳过。多进程各建一段, 事后合并+topic重建。"
             "默认空=原行为")
    parser.add_argument(
        "--caption_concurrency", type=int, default=4,
        help="并行 caption 调用数。默认 4。vLLM 服务负载允许的话可上 8。",
    )

    # ---- audio in prompt ----
    parser.add_argument(
        "--enable_audio_in_prompt", action="store_true",
        help="把对应窗口的 audio transcript 拼进 caption prompt 的 audio_context_block",
    )
    parser.add_argument(
        "--audio_source", type=str, default="whisper",
        choices=[None, "egolife_sync", "whisper"],
        help="audio 数据源。默认 week→egolife_sync, day/month→whisper",
    )
    parser.add_argument(
        "--egolife_sync_dir", type=str,
        default="/mnt/tokyo-ai/gst/EgoLife/egolife/EgoLifeCap/Sync",
    )
    parser.add_argument(
        "--asr_backend", type=str, default="faster_whisper",
        choices=["faster_whisper", "openai_whisper"],
    )
    parser.add_argument("--whisper_model_size", type=str, default="large-v3")
    parser.add_argument("--diarize", action="store_true")
    parser.add_argument(
        "--hf_token", type=str,
        default=os.environ.get("HUGGINGFACE_TOKEN", ""),
    )
    # key 从 .env 加载 (旧硬编码 key 已失效, 改为 dotenv)
    try:
        from dotenv import load_dotenv
        load_dotenv("/mnt/tokyo-ai/gst/GST_EGOSERVE/.env")
    except ImportError:
        pass
    parser.add_argument(
        "--openai_api_key", type=str,
        default=os.environ.get("OPENAI_API_KEY", ""),
        help="OpenAI key for builder LLM (topic/fact). 默认从 .env / 环境变量读取.",
    )

    # ---- pipeline mode ----
    parser.add_argument(
        "--pipeline_mode", type=str, default="v3", choices=["v1", "v3"],
        help="v1=plan A 单 consumer; v3=plan B 多 pending FIFO 三段流水(推荐)",
    )

    # ---- optional features (消融实验开关) ----
    # 物体/人物实体识别: 在 fact_extractor prompt 里追加 entity_aware addon, 让 fact 节点
    # 多带 entity_id 字段 (跨天可索引同一个人/同一个物体)。EgoMemReason 的
    # Entity Recognition / Cumulative State Tracking 题型受益于这个。
    parser.add_argument(
        "--enable_entity_id", action="store_true",
        help="启用物体/人物实体识别 (fact prompt 增强), week 模式推荐开。",
    )
    # 用户偏好聚合: 跨 episode 维护 ProfileAggregator, 抽取 favorite_food / typical_seat
    # / 频繁活动 等长期偏好。EgoMemReason 的 Activity Pattern / Spatial Preference 受益。
    parser.add_argument(
        "--enable_profile", action="store_true",
        help="启用用户偏好聚合 (ProfileAggregator), 仅 week 有意义 (同一 camera-wearer 跨天累积)。",
    )
    parser.add_argument(
        "--profile_periodic_interval", type=int, default=30,
        help="profile_aggregator 每 N 个 episode 触发一次 update (仅与 --enable_profile 一起用)。",
    )
    # 累积事件 (drink/sit/phone_use): 在每个 episode 完成后并行抽取 drink / sit_start /
    # phone_use_start 等时间点事件, 存进 hypergraph.accumulative_events。
    # 这是 "是否 2h 不喝水 / 久坐 / 频繁刷手机" 这类习惯题型的数据基础。
    # 默认开启 (因为 config.egolife_accumulative_event_enabled=True), 加 --disable 关掉。
    parser.add_argument(
        "--disable_accumulative_event", action="store_true",
        help="关闭累积事件 (drink/sit/phone_use) 抽取。仅 week 模式才有意义。",
    )
    # 增强版 caption prompt: 显式列出 EgoMemReason / MM-Lifelong week 16 个题型 +
    # drink/sit/phone/preference/entity_id 的具体 cue。默认关 (用 BASE), 加开关启用。
    parser.add_argument(
        "--use_enhanced_week_prompt", action="store_true",
        help="week 模式使用增强版 caption prompt (覆盖 16 个题型 + 累积事件/偏好/实体识别 cue)。",
    )
    parser.add_argument(
        "--prompt_version", type=str, default="v1",
        choices=["v0", "v1"],
        help="caption prompt 版本: v0=旧版 (依赖 --use_enhanced_week_prompt 开关), "
             "v1=2026-05-23 强化版 (actor-centric + exhaustive counting + OCR hard rule + "
             "color/clothing identification)",
    )
    # 通道B 结构化感知 (2026-07-05 用户定稿): 每窗口同帧再抽一份结构化 JSON
    # (实体清单+原子事件+逐字OCR) 存 working_dir/structured_perception.jsonl。
    # counting 题的原子记录层, caption 漏记时的补救通道。默认关, 不影响原行为。
    parser.add_argument(
        "--enable_structured_perception", action="store_true",
        help="启用通道B: 每窗口额外一次 VLM 调用抽结构化实体/事件 (jsonl 独立存储)。",
    )
    parser.add_argument(
        "--sp_vllm_base_url", type=str, default="",
        help="通道B用的 vLLM 服务地址; 空=与 caption 同一服务。有第二台 vLLM 时"
             "指向它可避免通道B拖慢 caption 吞吐。",
    )
    parser.add_argument(
        "--sp_max_new_tokens", type=int, default=3000,
        help="通道B单窗口输出 token 上限。",
    )
    parser.add_argument("--cuda", type=str, default="0")

    # ---- 限制 ----
    parser.add_argument(
        "--max_sub_videos", type=int, default=0,
        help=">0 时只处理前 N 个 sub_video(调试用)",
    )
    parser.add_argument(
        "--save_every_n_episodes", type=int, default=10,
        help="week 模式下每 N 个 episode 完成后做一次 hypergraph 持久化, "
             "避免长视频中途中断丢失全部进度。默认 10。",
    )

    args = parser.parse_args()

    os.environ["CUDA_VISIBLE_DEVICES"] = args.cuda
    if args.openai_api_key:
        os.environ["OPENAI_API_KEY"] = args.openai_api_key

    # ---- default 路径处理 ----
    if args.video_dir is None:
        args.video_dir = {
            "day": "/mnt/tokyo-ai/gst/MM-Lifelong/videos",
            "week": "/mnt/tokyo-ai/gst/EgoLife/egolife",
            "month": "/mnt/tokyo-ai/gst/MM-Lifelong/videos",
        }[args.dataset_type]
    if args.datasets_type is None:
        args.datasets_type = f"mmlifelong_{args.dataset_type}"
    if args.dataset_type == "week" and args.audio_source is None:
        args.audio_source = "egolife_sync" if args.enable_audio_in_prompt else None

    # ---- 1) sub video list ----
    sub_videos = get_sub_videos_for_dataset(args.dataset_type, args)
    if args.max_sub_videos > 0:
        sub_videos = sub_videos[:args.max_sub_videos]
        logger.info(f"[debug] truncated to {len(sub_videos)} sub_videos")

    # ---- 2) 共享 hyper_vg ----
    working_dir = os.path.join(args.save_root, args.datasets_type, "shared_hyper")
    os.makedirs(working_dir, exist_ok=True)
    logger.info(f"[shared] working_dir={working_dir}")

    dataset_mode = "egolife" if args.dataset_type == "week" else "thirdperson"  # day/month 第三人称(游戏/vlog), 避免 camera-wearer 污染
    # 累积事件 (drink/sit/phone_use): 仅 egolife mode 在 builder 内部生效。
    # 默认开 (因为 config 的 egolife_accumulative_event_enabled=True),
    # --disable_accumulative_event 可关掉。
    accumulative_enabled = (dataset_mode == "egolife") and not args.disable_accumulative_event
    hyper_cfg = HyperVideoConfig(
        dataset_mode=dataset_mode,
        caption_granularity="per_window",
        boundary_strategy="stream",
        caption_window_seconds=float(args.window_frames) * args.interval_seconds,
        caption_frame_interval_sec=args.interval_seconds,
        caption_mode="batch",
        egolife_accumulative_event_enabled=accumulative_enabled,
        max_buffer_seconds=float(args.max_buffer_seconds),
        gap_threshold_seconds=float(args.gap_threshold_seconds),
        defer_topic_aggregation=bool(getattr(args, "defer_topic_aggregation", False)),
    )
    if getattr(args, "defer_topic_aggregation", False):
        logger.info("[defer_topic] topic 聚合已跳过 (只抽 fact),topic 留待最后全局重建")
    if dataset_mode == "egolife":
        logger.info(
            f"[ablation] entity_id={args.enable_entity_id}, "
            f"profile_aggregator={args.enable_profile}, "
            f"accumulative_event={accumulative_enabled}, "
            f"enhanced_week_prompt={args.use_enhanced_week_prompt}"
        )
    hyper_vg = HyperVideoGraph(
        working_dir=working_dir,
        llm=default_llm_config,
        hyper_config=hyper_cfg,
    )
    if args.caption_model_name == "qwen_api":
        hyper_vg.load_caption_model(
            "qwen_api",
            api_model_name=args.qwen_api_model,
            api_key=args.qwen_api_key,
        )
    elif args.caption_model_name == "qwen_vllm":
        hyper_vg.load_caption_model(
            "qwen_vllm",
            vllm_base_url=args.vllm_base_url,
            vllm_model_name=args.vllm_model_name,
        )
        logger.info(f"  vllm_base_url={args.vllm_base_url} model={args.vllm_model_name}")
    else:
        raise ValueError(f"unknown caption_model_name: {args.caption_model_name!r}")

    if args.enable_entity_id:
        _augment_fact_extractor_inplace(hyper_vg)

    # ---- Resume: 加载已有 hypergraph + builder_state + clip_checkpoint ----
    # 如果 working_dir 已经存在历史 build 产物 (上次中断), 这里 load 出来,
    # 跑 recover_pending_episode_if_any 把上次 pending 但没 commit 的 episode 入图,
    # 然后从 clip_checkpoint 记录的位置继续。
    resume_from_clip_idx = 0
    clip_checkpoint_path = os.path.join(working_dir, "clip_checkpoint.json")
    try:
        hyper_vg.hypergraph_builder.load(working_dir)
    except Exception as e:
        logger.warning(f"[resume] load hypergraph 失败 (新建空图): {e}")

    if os.path.exists(clip_checkpoint_path):
        try:
            with open(clip_checkpoint_path, "r", encoding="utf-8") as f:
                ckpt = json.load(f)
            last_done = int(ckpt.get("last_completed_clip_idx", -1))
            stored_dataset = ckpt.get("dataset_type")
            stored_user = ckpt.get("user_id")
            stored_days = ckpt.get("days")
            # 校验 checkpoint 跟当前命令兼容
            mismatch = []
            if stored_dataset and stored_dataset != args.dataset_type:
                mismatch.append(f"dataset_type {stored_dataset!r}!={args.dataset_type!r}")
            if args.dataset_type == "week":
                if stored_user and stored_user != args.user_id:
                    mismatch.append(f"user_id {stored_user!r}!={args.user_id!r}")
                if stored_days and stored_days != args.days:
                    mismatch.append(f"days {stored_days!r}!={args.days!r}")
            if mismatch:
                logger.warning(
                    f"[resume] checkpoint 配置不匹配 ({', '.join(mismatch)}), "
                    f"忽略 checkpoint, 从头开始"
                )
            else:
                resume_from_clip_idx = last_done + 1
                logger.info(
                    f"[resume] checkpoint 加载: last_completed_clip_idx={last_done}, "
                    f"从 clip_idx={resume_from_clip_idx} 继续"
                )
        except Exception as e:
            logger.warning(f"[resume] 读取 checkpoint 失败: {e}, 从头开始")

    # recover pending episode (上次中断点正好在 _process_completed_episode 中间)
    try:
        recovered = always_get_an_event_loop().run_until_complete(
            hyper_vg.hypergraph_builder.recover_pending_episode_if_any()
        )
        if recovered:
            logger.info(f"[resume] 恢复 pending episode: {recovered.subject}")
    except Exception as e:
        logger.warning(f"[resume] recover_pending_episode_if_any failed: {e}")

    # 预热 save: 占位 kv_store_llm_response_cache.json 等文件 (上面 load 之后 working_dir
    # 一定存在, save 一次让所有占位文件就位, 避免后续增量写出 No such file warning).
    try:
        hyper_vg.save_hypergraph()
    except Exception as e:
        logger.warning(f"[prewarm] save_hypergraph failed (harmless): {e}")

    # ---- 3) audio context (one-shot 预加载) ----
    audio_provider = build_audio_context(
        args.dataset_type, args.enable_audio_in_prompt, args, sub_videos,
    )

    # ---- 4) profile aggregator (week only) ----
    profile_agg = None
    if args.enable_profile:
        profile_path = os.path.join(working_dir, "global_user_profile.json")

        async def _llm_call(prompt):
            return await default_llm_config.best_model_func_raw(
                default_llm_config.best_model_name, prompt,
                system_prompt=None, history_messages=[],
            )

        profile_agg = ProfileAggregator(
            llm_func=_llm_call,
            profile_path=profile_path,
            user_id=args.user_id if args.dataset_type == "week" else f"mmlifelong_{args.dataset_type}",
            periodic_episode_interval=args.profile_periodic_interval,
        )

    # ---- 5) 主循环 ----
    prompt_template = _get_prompt_for_dataset(
        args.dataset_type, use_enhanced_week=args.use_enhanced_week_prompt,
        prompt_version=args.prompt_version,
    )
    t_all = time.time()
    llm_timer = LLMTimer()
    timings: List[dict] = []

    # day/month 也走数据集级流水 (2026-06-07): 旧的逐 sub-video 路径会在每个
    # sub-video 结束 final_flush, 强切 episode —— day 的分P连续性被破坏, 预切片
    # 后更是每 600s 断一次。数据集级流水的边界由 day_num 驱动:
    #   week: 7 天 7 桶; day: 全部 day_num=1 连续时间轴; month: 每视频一桶,
    #   跨视频 day_num 变化 -> segmenter 硬分割 (等价 EgoLife 跨天)。
    # 回滚开关: --legacy_per_video_pipeline 走旧逐视频路径。
    use_dataset_level = (args.pipeline_mode == "v3"
                         and not args.legacy_per_video_pipeline)
    if use_dataset_level:
        # clip-level 并发 caption + segmenter 按时间序消费 + builder 串行三段流水。
        # 所有 clip/chunk 共享同一个 segmenter 状态。
        logger.info(
            f"[{args.dataset_type}] dataset-level v3 pipeline: {len(sub_videos)} clips, "
            f"caption_concurrency={args.caption_concurrency}"
        )

        # 升级 segmenter 到 v3 (一次, 跨整个 dataset)
        if args.pipeline_mode == "v3":
            upgrade_builder_segmenter_to_v3(hyper_vg.hypergraph_builder)

        # 通道B (可选): 结构化感知 extractor, 只在 dataset-level v3 路径接入
        sp_extractor = None
        if args.enable_structured_perception:
            from hypervideo.modules.structured_perception import (
                StructuredPerceptionExtractor, get_sp_prompt_for_dataset,
            )
            sp_extractor = StructuredPerceptionExtractor(
                vllm_base_url=args.sp_vllm_base_url or args.vllm_base_url,
                vllm_model_name=args.vllm_model_name,
                working_dir=working_dir,
                prompt_template=get_sp_prompt_for_dataset(args.dataset_type),
                interval_seconds=args.interval_seconds,
                max_new_tokens=args.sp_max_new_tokens,
            )

        # 工厂函数: caption / segment / build / flush / save
        caption_clip_fn = make_caption_clip_fn(
            hyper_vg=hyper_vg,
            interval_seconds=args.interval_seconds,
            window_frames=args.window_frames,
            max_new_tokens=args.max_new_tokens,
            caption_prompt_template=prompt_template,
            audio_provider=audio_provider,
            sp_extractor=sp_extractor,
            hyper_time_range=(
                tuple(float(x) for x in args.hyper_time_range.split(","))
                if getattr(args, "hyper_time_range", "") else None),
        )
        segment_one_fn = make_segment_one_fn_for_dataset(hyper_vg.hypergraph_builder)
        _raw_build_episode_only_fn = make_build_episode_only_fn(hyper_vg.hypergraph_builder)
        flush_segmenter_fn = make_flush_segmenter_fn(hyper_vg.hypergraph_builder)
        flush_builder_fn = make_flush_builder_fn(hyper_vg.hypergraph_builder)
        visual_index_fn = make_visual_index_fn_for_dataset(hyper_vg.hypergraph_builder)

        # Wrapper: build episode 完成后向 profile_agg 注册这个 episode (供后续 update 用)
        # profile_agg.maybe_trigger 内部 append 到 pending_episode_ids,
        # update 必须有 pending_episode_ids 非空才会真跑 LLM。
        async def build_episode_only_fn(episode):
            # watchdog (2026-07-06): 实测 A1 build 中单次 episode 构建的 LLM 调用
            # 偶发永久挂死(无超时), 冻结整条流水线且 segmenter 超时降级后状态损坏
            # (D1-18:32 后全部 episode 丢失)。超时=丢弃该 episode 保流水线存活。
            try:
                await asyncio.wait_for(_raw_build_episode_only_fn(episode),
                                       timeout=900)
            except asyncio.TimeoutError:
                # 2026-07-19: 原逻辑 return 丢弃 episode 但 pipeline 以为成功 ->
                # checkpoint 推进过该 clip -> episode 永久丢失。改为 raise, 让
                # pipeline 的 first_failed_clip 保护生效 (checkpoint 不越过, 续跑重建)。
                logger.error(
                    f"[builder-watchdog] episode "
                    f"{getattr(episode, 'subject', '?')!r} 构建超时900s, "
                    f"raise 以触发 checkpoint 封顶 (续跑会重建此 clip)")
                raise
            if profile_agg is not None:
                try:
                    # 取该 episode 关联的 fact 内容供 profile preference 检测
                    eid = episode.episode_id
                    facts_for_ep = []
                    for fid, f in hyper_vg.hypergraph_builder.hypergraph.facts.items():
                        ep_ids = getattr(f, 'episode_ids', None) or []
                        if eid in ep_ids:
                            facts_for_ep.append({
                                "content": getattr(f, "content", ""),
                                "keywords": getattr(f, "keywords", []) or [],
                                "temporal": getattr(f, "temporal", ""),
                            })
                    profile_agg.maybe_trigger(
                        new_episode_id=eid,
                        new_episode_summary=getattr(episode, "summary", "") or "",
                        new_episode_facts=facts_for_ep,
                    )
                except Exception as e:
                    logger.warning(f"[profile.maybe_trigger] failed (harmless): {e}")

        # profile_agg.update 是 sync, 每次 save 时顺带跑一次 (跨 episode 累积偏好)
        def save_fn():
            hyper_vg.save_hypergraph()
            if profile_agg is not None:
                try:
                    profile_agg.update(
                        hyper_vg=hyper_vg,
                        trigger_reason="week_periodic_save",
                        current_temporal=f"week_{args.user_id}",
                    )
                except Exception as e:
                    logger.warning(f"[profile.update] failed (harmless): {e}")

        # checkpoint_fn: 每次 save 之后 pipeline 调一次, 告诉我们哪个 clip_idx
        # 之前的所有 episode 都已经持久化, 下次 resume 可以从 idx+1 开始
        def checkpoint_fn(last_completed_clip_idx: int):
            try:
                with open(clip_checkpoint_path, "w", encoding="utf-8") as f:
                    json.dump({
                        "last_completed_clip_idx": int(last_completed_clip_idx),
                        "dataset_type": args.dataset_type,
                        "user_id": args.user_id if args.dataset_type == "week" else None,
                        "days": args.days if args.dataset_type == "week" else None,
                        "n_total_clips": len(clip_metas),
                    }, f, ensure_ascii=False, indent=2)
            except Exception as e:
                logger.warning(f"[checkpoint write] {e}")

        clip_metas = [
            {
                "sub_id": sub_id,
                "video_path": vpath,
                "day_num": day_num,
                "clip_start_seconds": clip_start_sec,
            }
            for (sub_id, vpath, day_num, clip_start_sec) in sub_videos
        ]

        # patch LLM timer
        with llm_timer.patch(hyper_vg.llm):
            llm_timer.reset()
            loop = always_get_an_event_loop()
            ds_stats = loop.run_until_complete(build_dataset_async_v3(
                clip_metas=clip_metas,
                caption_clip_fn=caption_clip_fn,
                segment_one_fn=segment_one_fn,
                build_episode_only_fn=build_episode_only_fn,
                flush_segmenter_fn=flush_segmenter_fn,
                flush_builder_fn=flush_builder_fn,
                save_fn=save_fn,
                visual_index_fn=visual_index_fn,
                caption_concurrency=args.caption_concurrency,
                episode_queue_size=8,
                progress_log_every=max(1, len(clip_metas) // 50),
                save_every_n_episodes=args.save_every_n_episodes,
                checkpoint_fn=checkpoint_fn,
                skip_clip_idx_lt=resume_from_clip_idx,
            ))
        timings.append({
            "kind": "dataset_v3",
            "total_clips": ds_stats.n_clips,
            "skipped_clips": ds_stats.skipped_clips,
            "n_windows": ds_stats.n_windows,
            "n_episodes": ds_stats.n_episodes,
            "total_seconds": ds_stats.total_seconds,
            "caption_seconds_sum": ds_stats.caption_seconds,
            "segmenter_seconds": ds_stats.segmenter_seconds,
            "builder_seconds": ds_stats.builder_seconds,
            "flush_seconds": ds_stats.flush_seconds,
            "max_pending_queue_observed": ds_stats.max_pending_queue_observed,
            "llm_summary": llm_timer.summary(),
            "sp_windows_ok": getattr(sp_extractor, "n_ok", None),
            "sp_windows_fail": getattr(sp_extractor, "n_fail", None),
        })
        clear_gpu_memory()
    else:
        # legacy 路径 (--legacy_per_video_pipeline 或 pipeline_mode=v1):
        # 逐 sub_video 处理, 每个结束强制 flush -> episode 不跨 sub-video 边界
        for idx, (sub_id, vpath, day_num, clip_start_sec) in enumerate(sub_videos):
            logger.info(
                f"\n{'='*70}\n"
                f"[{idx+1}/{len(sub_videos)}] sub_id={sub_id} day={day_num} "
                f"clip_start={clip_start_sec}s ({os.path.basename(vpath)})\n"
                f"{'='*70}"
            )
            t0 = time.time()
            try:
                llm_timer.reset()
                loop = always_get_an_event_loop()
                stats = loop.run_until_complete(_run_one_sub_video_async(
                    hyper_vg=hyper_vg,
                    video_path=vpath,
                    sub_video_id=sub_id,
                    day_num=day_num,
                    clip_start_seconds=clip_start_sec,
                    interval_seconds=args.interval_seconds,
                    window_frames=args.window_frames,
                    max_new_tokens=args.max_new_tokens,
                    caption_prompt_template=prompt_template,
                    audio_provider=audio_provider,
                    pipeline_mode=args.pipeline_mode,
                    caption_concurrency=args.caption_concurrency,
                    llm_timer=llm_timer,
                    final_flush=True,
                    hyper_time_range=(
                        tuple(float(x) for x in args.hyper_time_range.split(","))
                        if getattr(args, "hyper_time_range", "") else None),
                ))
                _flush_builder(hyper_vg)
                if profile_agg is not None:
                    profile_agg.update(
                        hyper_vg=hyper_vg,
                        trigger_reason=f"{args.dataset_type}_per_video_end",
                        current_temporal=f"DAY{day_num}_{sub_id}",
                    )
                elapsed = time.time() - t0
                timings.append({
                    "sub_id": sub_id,
                    "day_num": day_num,
                    "elapsed_s": elapsed,
                    "n_windows": stats.n_windows,
                    "n_episodes": getattr(stats, "n_episodes", "-"),
                    "caption_seconds": getattr(stats, "caption_seconds", 0),
                    "builder_seconds": getattr(stats, "builder_seconds", 0),
                    "llm_summary": llm_timer.summary(),
                })
                logger.info(
                    f"[{idx+1}/{len(sub_videos)}] {sub_id} 耗时 {elapsed:.1f}s "
                    f"| LLM cheap={llm_timer.summary()['cheap_model']['n_calls']}calls"
                )
            except Exception as e:
                logger.error(f"[{idx+1}/{len(sub_videos)}] {sub_id} failed: {e}", exc_info=True)
                continue
            finally:
                clear_gpu_memory()

    # ---- 6) 最终保存 ----
    # week 模式下 segmenter 最后那个 clip 已经按 final_flush=True 跑过, 直接 save。
    try:
        hyper_vg.save_hypergraph()
        logger.info(f"[final] hypergraph saved to {working_dir}")
    except Exception as e:
        logger.error(f"[final] save_hypergraph failed: {e}", exc_info=True)

    # 写 timing 报告
    timing_path = os.path.join(working_dir, "timings.json")
    try:
        with open(timing_path, "w", encoding="utf-8") as f:
            json.dump({
                "dataset_type": args.dataset_type,
                "pipeline_mode": args.pipeline_mode,
                "caption_concurrency": args.caption_concurrency,
                "audio_in_prompt": args.enable_audio_in_prompt,
                "audio_source": args.audio_source,
                "total_seconds": time.time() - t_all,
                "n_sub_videos": len(timings),
                "per_video": timings,
            }, f, indent=2, ensure_ascii=False)
        logger.info(f"[final] timings -> {timing_path}")
    except Exception as e:
        logger.warning(f"timings write failed: {e}")

    logger.info(
        f"\n{'='*70}\n"
        f"[{args.dataset_type}] all done in {time.time()-t_all:.1f}s "
        f"({len(timings)}/{len(sub_videos)} ok)\n"
        f"{'='*70}"
    )


if __name__ == "__main__":
    main()