File size: 62,747 Bytes
9f313a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
StreamingBench (Real_Time_Visual_Understanding) 推理检索入口
—— 使用 HyperVideoGraph 的三层超图检索替代原 VDB/KG 检索

MCQ 数据来自:
    /mnt/tokyo-ai/gst/StreamingBench/StreamingBench/Real_Time_Visual_Understanding.csv

字段: question_id, task_type, question, time_stamp, answer, options,
      frames_required, temporal_clue_type (Prior / Concurrent)

任务分流:
  * Concurrent (~84%)  -> REALTIME:以 time_stamp 附近的 recent captions +
                          截至该时刻的 global captions 直接回答
  * Prior      (~16%)  -> BACKWARD:最多 2 轮 LLM 决策, 需要检索时调用
                          HyperVideoGraph.retrieve(query, time_span_cutoff)
                          做 Topic→Episode→Fact 层次检索

与 ovobench_hyper_retrieval.py 的关键差异:
  1. 数据源是 CSV 而非 JSON, 选项字段是 Python list 字符串
  2. 单视频多问题, 每个问题有自己的 time_stamp 和 temporal_clue_type
  3. time_stamp 是绝对 HH:MM:SS, 需转成 "1-00:HH:MM-HH:MM:SS" 形式供超图
     的时间过滤使用(只检索 time_stamp 之前的 episode/fact)
"""

# Pre-import nano_vectordb before transformers locks libstdc++ (see mmlifelong_week_retrieval_v2.py)
import torch  # noqa: F401
try:
    import nano_vectordb as _nvdb_preload  # noqa: F401
except Exception:
    pass

import os
import sys
import argparse
import asyncio
import ast
import csv
import json
import logging
import re
import time
from collections import defaultdict
from typing import List, Dict, Optional

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

if __name__ == "__main__":
    _pre_parser = argparse.ArgumentParser(add_help=False)
    _pre_parser.add_argument('--cuda', type=str, default='1')
    _pre_args, _ = _pre_parser.parse_known_args()
    os.environ["CUDA_VISIBLE_DEVICES"] = _pre_args.cuda

from videorag._llm import (
    LLMConfig, openai_embedding, bge_m3_embedding,
    gpt_4o_mini_complete,
)
from videorag._utils import always_get_an_event_loop

from hypervideo.hyper_video_graph import HyperVideoGraph
from hypervideo.config import HyperVideoConfig

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


# ==================== temporal_clue_type → 路由 ====================

REALTIME_CLUE_TYPES = {"Concurrent"}  # 直接回答
BACKWARD_CLUE_TYPES = {"Prior"}        # 超图检索


# ==================== LLM 配置 ====================

llm_config_openai = 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,
    # default: gpt-4.1-mini (org-verified, 同 mmlifelong); --answer_model 可改成 gpt-5.4-nano / gpt-5.4-mini
    best_model_name=os.environ.get("HYPERVIDEO_ANSWER_MODEL", "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-4o-mini",
    cheap_model_max_token_size=32768,
    cheap_model_max_async=16,
)

llm_config_bge = LLMConfig(
    embedding_func_raw=bge_m3_embedding,
    embedding_model_name="BAAI/bge-m3",
    embedding_dim=1024,
    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=os.environ.get("HYPERVIDEO_ANSWER_MODEL", "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-4o-mini",
    cheap_model_max_token_size=32768,
    cheap_model_max_async=16,
)


# ==================== Prompt 模板 ====================

STREAMINGBENCH_REALTIME_PROMPT = """
You are a streaming video question-answering assistant designed for the
StreamingBench Real-Time Visual Understanding task.

This is a TRAINING-FREE, DIRECT-ANSWER reasoning process.

You are given:
- RECENT_CAPTIONS: detailed second-level captions from the LAST ~15 seconds
  BEFORE the question time_stamp (the moment the question is asked).
- GLOBAL_CAPTIONS: minute-level summaries covering the video up to the
  question time_stamp.
- TASK_TYPE: one of Object Perception, Action Perception, Attribute Perception,
  Spatial Understanding, Counting, Event Understanding, Text-Rich Understanding,
  Clips Summarize, Causal Reasoning, Prospective Reasoning.
- TEMPORAL_CLUE: "Concurrent" — the answer is observable AT the time_stamp.

You must answer the question directly based on the provided captions.
No retrieval is allowed.

------------------------------------------------------------
Reasoning Requirements
------------------------------------------------------------
- Focus primarily on RECENT_CAPTIONS near the question time_stamp.
- Use GLOBAL_CAPTIONS only for broader context when RECENT_CAPTIONS are insufficient.
- Ground all reasoning in the provided captions.
- Do NOT invent objects, actions, or states not mentioned in captions.
- Choose the option most consistent with available evidence.

------------------------------------------------------------
Output Format (STRICT)
------------------------------------------------------------

{
  "answer": "<single letter: A, B, C, or D>",
  "reasoning": "<concise explanation grounded in captions>"
}

Output ONLY the JSON object. No additional text.
"""

STREAMINGBENCH_BACKWARD_RETRIEVAL_PROMPT = """
You are a streaming video question-answering decision assistant designed for
the StreamingBench Real-Time Visual Understanding task.

This is a TRAINING-FREE, ITERATIVE decision-and-retrieval process that
operates over a three-layer semantic hypergraph (Topic → Episode → Fact)
built from the video's captions up to the question time_stamp.

At most TWO retrieval rounds are allowed.

You are given:
- GLOBAL_CAPTIONS: minute-level summaries covering the video up to the
  question time_stamp.
- RETRIEVED_CONTEXT: facts / episode summaries retrieved from the hypergraph
  in previous rounds (may be empty).
- TASK_TYPE: one of Object Perception, Action Perception, Attribute Perception,
  Spatial Understanding, Counting, Event Understanding, Text-Rich Understanding,
  Clips Summarize, Causal Reasoning, Prospective Reasoning.
- TEMPORAL_CLUE: "Prior" — the answer hinges on something that happened
  BEFORE the question time_stamp.

------------------------------------------------------------
Decision Rules
------------------------------------------------------------

CASE 1 — RETRIEVED_CONTEXT is EMPTY (first round)

You may ANSWER immediately ONLY IF:
- The answer can be clearly determined from GLOBAL_CAPTIONS alone.
- Exactly ONE option is consistent with the evidence.

Otherwise → request retrieval.

CASE 2 — RETRIEVED_CONTEXT EXISTS (after retrieval)

If this is the second retrieval round, you MUST answer.
If this is the first retrieval round, you may request one more retrieval OR answer.

When answering after retrieval:
- Choose the option most consistent with all available evidence.
- Do NOT invent new evidence.

------------------------------------------------------------
Retrieval Query Requirements
------------------------------------------------------------

If requesting retrieval:
- Output ONE concise English sentence as the retrieval query.
- The query MUST specify:
  • The temporal segment or event needed (e.g. "early in the video", "right before the fight")
  • The specific object / person / action / text to look for
  • Include option texts in parentheses for context

------------------------------------------------------------
Output Format (STRICT)
------------------------------------------------------------

Case 1 — Answer:
{
  "decision": "answer",
  "answer": "<single letter: A, B, C, or D>",
  "reasoning": "<concise explanation grounded in captions / retrieved facts>"
}

Case 2 — Need Retrieval:
{
  "decision": "need_retrieval",
  "retrieval_query": "<one-sentence retrieval query including options>"
}

Output ONLY the JSON object. No additional text.
"""


# ==================== 工具函数 ====================

def _parse_llm_json(response: str) -> Optional[dict]:
    """从 LLM 响应中提取 JSON(处理 markdown 代码块)"""
    if not response:
        return None
    cleaned = response.strip()
    if cleaned.startswith("```"):
        lines = cleaned.split("\n")
        cleaned = "\n".join(lines[1:-1]) if len(lines) > 2 else cleaned
    m = re.search(r'\{.*\}', cleaned, re.DOTALL)
    if m:
        try:
            return json.loads(m.group())
        except json.JSONDecodeError:
            pass
    return None


def _parse_options(options_raw: str) -> List[str]:
    """CSV 中的 options 是 Python list 字符串, 如:
    "['A. FIFA and La Liga.', 'B. UEFA and La Liga.', ...]"
    """
    if not options_raw:
        return []
    try:
        parsed = ast.literal_eval(options_raw)
        if isinstance(parsed, list):
            return [str(x) for x in parsed]
    except (ValueError, SyntaxError):
        pass
    # 退回到简单分割
    return [s.strip() for s in options_raw.split(",") if s.strip()]


def _extract_option_letter(text: str, options: List[str] = None) -> Optional[str]:
    """提取选项字母 A/B/C/D(与 ovobench_hyper_retrieval 一致)"""
    if not text:
        return None
    text = text.strip()
    labels = "ABCD"

    m = re.match(r'^[(\s]*([A-Da-d])[).\s:,\-]', text)
    if m:
        return m.group(1).upper()
    if len(text) == 1 and text.upper() in labels:
        return text.upper()
    m = re.match(r'^([A-Da-d])[.:\s)\-]', text)
    if m:
        return m.group(1).upper()

    if options:
        text_lower = text.lower().strip()
        text_clean = re.sub(r'^[(\s]*[A-Da-d][).\s:,\-]+\s*', '', text_lower).strip()
        for i, opt in enumerate(options):
            if i >= len(labels):
                break
            # options 里通常已经带 "A. xxx" 前缀, 先去掉再比较
            opt_body = re.sub(r'^[A-Da-d]\.\s*', '', opt).strip().lower()
            if text_clean == opt_body or text_lower == opt.lower().strip():
                return labels[i]
        # 模糊
        for i, opt in enumerate(options):
            if i >= len(labels):
                break
            opt_body = re.sub(r'^[A-Da-d]\.\s*', '', opt).strip().lower()
            if len(opt_body) > 3 and (opt_body in text_lower or text_clean in opt_body):
                return labels[i]
    return None


def _hms_to_seconds(hms: str) -> int:
    """HH:MM:SS → seconds"""
    if not hms:
        return 0
    try:
        parts = hms.strip().split(":")
        if len(parts) == 3:
            h, m, s = parts
        elif len(parts) == 2:
            h, m, s = "0", parts[0], parts[1]
        else:
            return 0
        return int(h) * 3600 + int(m) * 60 + int(float(s))
    except (ValueError, AttributeError):
        return 0


def _seconds_to_hms(sec: int) -> str:
    sec = max(0, int(sec))
    h = sec // 3600
    m = (sec % 3600) // 60
    s = sec % 60
    return f"{h:02d}:{m:02d}:{s:02d}"


def _build_time_span_cutoff(time_stamp_hms: str) -> str:
    """把 'HH:MM:SS' 转为超图识别的 '1-HH:MM:SS-HH:MM:SS' 形式,
    end 正好就是 time_stamp。
    """
    if not time_stamp_hms:
        return ""
    return f"1-{time_stamp_hms}-{time_stamp_hms}"


def _time_span_end_seconds(time_span: str) -> int:
    """解析 '1-HH:MM:SS-HH:MM:SS', 返回 end 秒数"""
    if not time_span:
        return 0
    parts = time_span.split("-", 1)
    if len(parts) < 2:
        return 0
    times = parts[1].split("-")
    if len(times) < 2:
        return _hms_to_seconds(parts[1])
    return _hms_to_seconds(times[1])


def _filter_captions_up_to(captions: List[dict], cutoff_seconds: int) -> List[dict]:
    """过滤出 end_seconds <= cutoff 的 captions"""
    if cutoff_seconds <= 0:
        return captions
    result = []
    for cap in captions:
        end_s = _time_span_end_seconds(cap.get('time_span', ''))
        if end_s <= cutoff_seconds:
            result.append(cap)
    return result


def _get_recent_captions_before(
    captions: List[dict], cutoff_seconds: int, window_seconds: int = 15,
) -> List[dict]:
    """取 cutoff 之前 window 秒内的 captions"""
    if cutoff_seconds <= 0:
        return captions[-3:] if captions else []
    lo = max(0, cutoff_seconds - window_seconds)
    result = []
    for cap in captions:
        end_s = _time_span_end_seconds(cap.get('time_span', ''))
        if lo < end_s <= cutoff_seconds:
            result.append(cap)
    return result if result else [c for c in captions if _time_span_end_seconds(c.get('time_span', '')) <= cutoff_seconds][-1:]


def _format_captions(captions: List[dict]) -> str:
    return "\n".join(
        f"[{i+1}] Time: {cap.get('time_span', 'N/A')}\n{cap.get('caption', '')}"
        for i, cap in enumerate(captions)
    )


def _format_options_block(options: List[str]) -> str:
    """options 已经带 'A. xxx' 前缀, 直接换行拼接"""
    return "\n".join(options)


def _build_episode_blocks(hyper_vg, current_time_span: str, near_n: int = 5):
    """构建 (all_summaries_text, near_detail_text)。
    - all_summaries_text: cutoff 前所有 episode 的 [time_span] subject - summary
    - near_detail_text: 最近 near_n 个 episode 的 summary + episode_description
    """
    from hypervideo.types import parse_frame_time_to_seconds
    eps_dict = hyper_vg.hypergraph_builder.hypergraph.episodes
    cutoff_sec = None
    if current_time_span:
        cutoff_sec = parse_frame_time_to_seconds(current_time_span, "end")

    eps = []
    for ep in eps_dict.values():
        if cutoff_sec is not None and ep.end_seconds > cutoff_sec:
            continue
        eps.append(ep)
    eps.sort(key=lambda e: e.end_seconds)

    def _subj(ep):
        return getattr(ep, 'subject', None) or getattr(ep, 'title', None) or ''

    def _desc(ep):
        return (
            getattr(ep, 'episode_description', None)
            or getattr(ep, 'description', '') or ''
        )

    all_lines = []
    for ep in eps:
        ts = getattr(ep, 'time_span', '')
        line = f"[{ts}] {_subj(ep)}"
        summ = getattr(ep, 'summary', '') or ''
        if summ:
            line += f" — {summ}"
        all_lines.append(line)
    all_text = "\n".join(all_lines) if all_lines else "(no episodes)"

    near = eps[-near_n:] if eps else []
    near_blocks = []
    for ep in near:
        ts = getattr(ep, 'time_span', '')
        block = f"[{ts}] {_subj(ep)}"
        summ = getattr(ep, 'summary', '') or ''
        d = _desc(ep)
        if summ:
            block += f"\n  summary: {summ}"
        if d:
            block += f"\n  description: {d}"
        near_blocks.append(block)
    near_text = "\n\n".join(near_blocks) if near_blocks else "(no nearby episodes)"
    return all_text, near_text


def _build_full_hypergraph_dump(hyper_vg, current_time_span: str):
    """构造 ALL_EPISODES (summary+description) + ALL_FACTS (chronological)。
    用于 dump_all 无检索 baseline。
    """
    from hypervideo.types import parse_frame_time_to_seconds
    eps_dict = hyper_vg.hypergraph_builder.hypergraph.episodes
    facts_dict = hyper_vg.hypergraph_builder.hypergraph.facts
    cutoff_sec = None
    if current_time_span:
        cutoff_sec = parse_frame_time_to_seconds(current_time_span, "end")

    eps = []
    for ep in eps_dict.values():
        if cutoff_sec is not None and ep.end_seconds > cutoff_sec:
            continue
        eps.append(ep)
    eps.sort(key=lambda e: e.end_seconds)

    ep_blocks = []
    for ep in eps:
        ts = getattr(ep, 'time_span', '')
        subj = getattr(ep, 'subject', None) or getattr(ep, 'title', None) or ''
        summ = getattr(ep, 'summary', '') or ''
        desc = (
            getattr(ep, 'episode_description', None)
            or getattr(ep, 'description', '') or ''
        )
        block = f"[{ts}] {subj}"
        if summ:
            block += f"\n  summary: {summ}"
        if desc:
            block += f"\n  description: {desc}"
        ep_blocks.append(block)
    all_eps_text = "\n\n".join(ep_blocks) if ep_blocks else "(no episodes)"

    facts = []
    for f in facts_dict.values():
        eids = getattr(f, 'episode_ids', None) or []
        if cutoff_sec is not None and eids:
            in_window = False
            for eid in eids:
                ep = eps_dict.get(eid)
                if ep and ep.end_seconds <= cutoff_sec:
                    in_window = True
                    break
            if not in_window:
                continue
        facts.append(f)

    def _key(f):
        try:
            return parse_frame_time_to_seconds(getattr(f, 'temporal', '') or '', "start")
        except Exception:
            return 0.0
    facts.sort(key=_key)

    fact_lines = []
    for f in facts:
        tmp = getattr(f, 'temporal', '') or '?'
        cont = getattr(f, 'content', '') or ''
        spat = getattr(f, 'spatial', '') or ''
        line = f"[{tmp}] {cont}"
        if spat:
            line += f" (loc: {spat})"
        fact_lines.append(line)
    all_facts_text = "\n".join(fact_lines) if fact_lines else "(no facts)"
    return all_eps_text, all_facts_text


SB_FULL_DUMP_PROMPT = """
You are a streaming video question-answering assistant for the StreamingBench
Real-Time Visual Understanding task.

You are given the COMPLETE three-layer semantic hypergraph
(Topic → Episode → Fact) of the video so far, dumped in full:
- LATEST_FRAME_CAPTIONS: the last 2 frame-level captions before the question
  time_stamp (most recent visual evidence).
- ALL_EPISODES: chronological list of every episode with summary AND description.
- ALL_FACTS: chronological list of every fact (atomic event), each tagged with
  its temporal position.

You must answer in ONE shot — no retrieval is allowed.

Decision Rules:
- Carefully scan all provided context for evidence.
- Pick the option most consistent with the evidence.
- Prefer a concrete option even from partial evidence.
- Never fabricate evidence.

Output Format (STRICT):

{
  "answer": "<single letter: A, B, C, or D>",
  "reasoning": "<concise grounding>"
}

Output ONLY the JSON object.
"""


SB_BACKWARD_RETRIEVAL_PROMPT = """
You are a streaming video question-answering decision assistant for the
StreamingBench Real-Time Visual Understanding task.

A three-layer semantic hypergraph (Topic → Episode → Fact) has been built from
the video's captions up to the question time_stamp. UP TO TWO retrievals are
allowed (Round 1 → optional retrieval → Round 2 must answer).

You are given:
- LATEST_FRAME_CAPTIONS: the last 2 frame-level captions before time_stamp
  (most recent visual evidence right at the question moment).
- ALL_EPISODE_SUMMARIES: chronological skeleton of every episode (every
  episode's title + one-line summary) up to time_stamp.
- NEARBY_EPISODES: the most recent N episodes with full summary AND
  description (more visual / textual detail).
- RETRIEVED_CONTEXT: facts / episode details retrieved from the hypergraph
  in earlier rounds (empty in Round 1).

Task Types: Object Perception, Action Perception, Attribute Perception,
Spatial Understanding, Counting, Event Understanding, Text-Rich Understanding,
Causal Reasoning, Prospective Reasoning, Clips Summarize.

Decision Rules:

NON-FINAL ROUND (you may answer OR request retrieval)
- Answer immediately when LATEST_CAPTIONS + ALL_EPISODE_SUMMARIES + NEARBY_EPISODES
  + (RETRIEVED_CONTEXT) is sufficient to pick exactly one option.
- Only request retrieval when existing evidence is genuinely insufficient
  (e.g. fine count / detail / object NOT mentioned anywhere).
- Do NOT request retrieval just to be safe.

FINAL ROUND (you MUST answer)
- DEFAULT: pick the option most consistent with available evidence.
- Make a best guess from partial evidence — do not refuse just because evidence
  is incomplete.
- Never fabricate new evidence.

Retrieval Query Requirements (only when decision = need_retrieval):
- ONE concise English sentence.
- Must specify: temporal segment + specific object/person/action/count.
- Include answer options in parentheses.

Output Format (STRICT):

Answer:
{"decision": "answer", "answer": "<A|B|C|D>", "reasoning": "<concise>"}

Need Retrieval (only in non-final rounds):
{"decision": "need_retrieval", "retrieval_query": "<one sentence with options>"}

Output ONLY the JSON object.
"""


def _handle_dump_all(
    question: str,
    task_type: str,
    options: List[str],
    second_captions: list,
    cutoff_sec: int,
    llm_config: LLMConfig,
    hyper_vg: HyperVideoGraph,
) -> dict:
    """方式 1 (dump_all): 不检索, 全量喂入 LATEST_2_CAPTIONS + ALL_EPISODES (summary+desc) + ALL_FACTS"""
    options_text = _format_options_block(options)
    # 最近 2 个 frame caption (cutoff 之前)
    filtered_sec = _filter_captions_up_to(second_captions, cutoff_sec)
    latest_2 = filtered_sec[-2:] if filtered_sec else []
    latest_text = _format_captions(latest_2) if latest_2 else "(none)"

    time_span_cutoff = _build_time_span_cutoff(_seconds_to_hms(cutoff_sec))
    all_eps_text, all_facts_text = _build_full_hypergraph_dump(hyper_vg, time_span_cutoff)

    full_prompt = f"""{SB_FULL_DUMP_PROMPT}

------------------------------------------------------------
TASK_TYPE
------------------------------------------------------------
{task_type}

------------------------------------------------------------
QUESTION
------------------------------------------------------------
{question}

------------------------------------------------------------
OPTIONS
------------------------------------------------------------
{options_text}

------------------------------------------------------------
LATEST_FRAME_CAPTIONS (last 2 captions before question time_stamp)
------------------------------------------------------------
{latest_text}

------------------------------------------------------------
ALL_EPISODES (every episode in the video so far, summary + description)
------------------------------------------------------------
{all_eps_text}

------------------------------------------------------------
ALL_FACTS (every fact in the video so far, chronologically)
------------------------------------------------------------
{all_facts_text}
"""
    try:
        response = asyncio.run(llm_config.best_model_func_raw(
            llm_config.best_model_name, full_prompt,
            system_prompt=None, history_messages=[],
        ))
        logger.info(f"    LLM response: {str(response)[:200]}...")
        parsed = _parse_llm_json(response) if isinstance(response, str) else response
        if parsed is None:
            parsed = {"answer": "", "reasoning": str(response)}
    except Exception as e:
        logger.error(f"    LLM 调用失败: {e}")
        parsed = {"answer": "", "reasoning": str(e)}

    return {
        'answer': parsed.get('answer', ''),
        'reasoning': parsed.get('reasoning', ''),
        'round': 1,
        'mode': 'dump_all_no_retrieval',
        'retrieved_context': [],
        'retrieval_history': [{"mode": "dump_all", **parsed}],
    }


def _handle_backward_with_retrieval(
    question: str,
    task_type: str,
    options: List[str],
    second_captions: list,
    cutoff_sec: int,
    llm_config: LLMConfig,
    hyper_vg: HyperVideoGraph,
    max_rounds: int = 2,
    near_n: int = 5,
    retrieval_mode: str = "hierarchical",
    recent_window_sec: int = 0,
) -> dict:
    """方式 2/3/4 (检索): LATEST_2_CAPTIONS + ALL_EPISODE_SUMMARIES + NEARBY_EPISODES.
    LLM 决策 → 需要检索时按 retrieval_mode 调用 (fact_only / episode_fact / hierarchical) → 最多 2 轮.
    recent_window_sec>0 (merge2 式): 把 LATEST_2 改成"最近 N 秒帧 caption"(merge2/rt2 洞察:
        当前帧证据要喂足够帧, 只喂 2 帧太少)。
    """
    options_text = _format_options_block(options)
    filtered_sec = _filter_captions_up_to(second_captions, cutoff_sec)
    if recent_window_sec > 0:
        latest_2 = _get_recent_captions_before(second_captions, cutoff_sec, window_seconds=recent_window_sec)
    else:
        latest_2 = filtered_sec[-2:] if filtered_sec else []
    latest_text = _format_captions(latest_2) if latest_2 else "(none)"

    time_span_cutoff = _build_time_span_cutoff(_seconds_to_hms(cutoff_sec))
    all_eps_text, nearby_eps_text = _build_episode_blocks(
        hyper_vg, time_span_cutoff, near_n=near_n,
    )

    retrieved_contexts = []
    retrieval_history = []
    loop = always_get_an_event_loop()

    for round_idx in range(1, max_rounds + 1):
        logger.info(f"    [Backward-{retrieval_mode}] Round {round_idx}/{max_rounds}")

        retrieved_text = ""
        if retrieved_contexts:
            retrieved_text = "\n\n".join(
                f"[Retrieved {i+1}]\n{ctx}"
                for i, ctx in enumerate(retrieved_contexts)
            )

        retrievals_left = max_rounds - round_idx
        if round_idx >= max_rounds:
            round_marker = (
                f"FINAL ROUND ({round_idx}/{max_rounds}) — you MUST output an "
                "answer. No more retrieval allowed."
            )
        else:
            round_marker = (
                f"Round {round_idx}/{max_rounds} — {retrievals_left} retrieval(s) "
                "remaining. Answer if evidence suffices, else request retrieval."
            )

        full_prompt = f"""{SB_BACKWARD_RETRIEVAL_PROMPT}

------------------------------------------------------------
ROUND_STATUS
------------------------------------------------------------
{round_marker}

------------------------------------------------------------
TASK_TYPE
------------------------------------------------------------
{task_type}

------------------------------------------------------------
QUESTION
------------------------------------------------------------
{question}

------------------------------------------------------------
OPTIONS
------------------------------------------------------------
{options_text}

------------------------------------------------------------
LATEST_FRAME_CAPTIONS (last 2 captions before question time_stamp)
------------------------------------------------------------
{latest_text}

------------------------------------------------------------
ALL_EPISODE_SUMMARIES (chronological skeleton)
------------------------------------------------------------
{all_eps_text}

------------------------------------------------------------
NEARBY_EPISODES (last {near_n} episodes with full detail)
------------------------------------------------------------
{nearby_eps_text}

------------------------------------------------------------
RETRIEVED_CONTEXT
------------------------------------------------------------
{retrieved_text if retrieved_text else "None (first round)"}
"""
        try:
            response = asyncio.run(llm_config.best_model_func_raw(
                llm_config.best_model_name, full_prompt,
                system_prompt=None, history_messages=[],
            ))
            logger.info(f"    LLM response: {str(response)[:200]}...")
            decision = _parse_llm_json(response) if isinstance(response, str) else response
            if decision is None:
                logger.error(f"    JSON 解析失败: {response}")
                decision = {"decision": "error", "error": str(response)}
        except Exception as e:
            logger.error(f"    LLM 调用失败: {e}")
            decision = {"decision": "error", "error": str(e)}

        decision['round'] = round_idx
        retrieval_history.append(decision)
        d = decision.get('decision', '')

        def _build_result(answer, reasoning):
            return {
                'answer': answer,
                'reasoning': reasoning,
                'round': round_idx,
                'mode': f'backward_{retrieval_mode}',
                'retrieved_context': retrieved_contexts.copy(),
                'retrieval_history': retrieval_history,
            }

        if d in ('answer', 'forced_answer'):
            logger.info(f"    Round {round_idx}: 直接回答")
            return _build_result(
                decision.get('answer', ''),
                decision.get('reasoning', ''),
            )
        elif d == 'need_retrieval':
            if round_idx >= max_rounds:
                logger.warning(f"    Round {round_idx}: 已达最大轮次, 强制回答")
                return _build_result(
                    decision.get('answer', ''),
                    'Max retrieval rounds reached',
                )
            retrieval_query = decision.get('retrieval_query', '')
            logger.info(f"    Round {round_idx}: 需检索, query: {retrieval_query}")
            try:
                retrieval_result = loop.run_until_complete(
                    hyper_vg.retrieve(
                        retrieval_query, time_span_cutoff, mode=retrieval_mode,
                    )
                )
                retrieved_text_ctx = hyper_vg.format_retrieval_for_llm(retrieval_result)
                if not retrieved_text_ctx:
                    retrieved_text_ctx = "No relevant facts/episodes found."
                logger.info(
                    f"    Retrieval done: topics={len(retrieval_result.topics)}, "
                    f"episodes={len(retrieval_result.episodes)}, "
                    f"facts={len(retrieval_result.facts)}"
                )
                retrieved_contexts.append(retrieved_text_ctx)
            except Exception as e:
                logger.error(f"    Retrieval failed: {e}")
                retrieved_contexts.append(f"Retrieval failed: {str(e)}")
        else:
            logger.error(f"    未知 decision: {d}")
            if round_idx >= max_rounds:
                return _build_result('', 'Max rounds with unknown decision')

    logger.warning("    所有轮次完成但无答案")
    return {
        'answer': '',
        'reasoning': 'Retrieval done without clear answer',
        'round': max_rounds,
        'mode': f'backward_{retrieval_mode}',
        'retrieved_context': retrieved_contexts.copy(),
        'retrieval_history': retrieval_history,
    }


# ==================== Realtime 任务 ====================

def _handle_realtime(
    question: str,
    task_type: str,
    temporal_clue: str,
    options: List[str],
    recent_text: str,
    global_text: str,
    llm_config: LLMConfig,
) -> dict:
    options_text = _format_options_block(options)
    full_prompt = f"""{STREAMINGBENCH_REALTIME_PROMPT}

------------------------------------------------------------
TASK_TYPE
------------------------------------------------------------
{task_type}

------------------------------------------------------------
TEMPORAL_CLUE
------------------------------------------------------------
{temporal_clue}

------------------------------------------------------------
QUESTION
------------------------------------------------------------
{question}

------------------------------------------------------------
OPTIONS
------------------------------------------------------------
{options_text}

------------------------------------------------------------
RECENT_CAPTIONS (last ~15 seconds before time_stamp)
------------------------------------------------------------
{recent_text}

------------------------------------------------------------
GLOBAL_CAPTIONS (up to time_stamp)
------------------------------------------------------------
{global_text}
"""
    try:
        response = asyncio.run(llm_config.best_model_func_raw(
            llm_config.best_model_name,
            full_prompt,
            system_prompt=None,
            history_messages=[],
        ))
        logger.info(f"    LLM response: {str(response)[:200]}...")
        parsed = _parse_llm_json(response) if isinstance(response, str) else response
        if parsed is None:
            parsed = {"answer": "", "reasoning": str(response)}
    except Exception as e:
        logger.error(f"    LLM 调用失败: {e}")
        parsed = {"answer": "", "reasoning": str(e)}

    return {
        'answer': parsed.get('answer', ''),
        'reasoning': parsed.get('reasoning', ''),
        'round': 0,
        'mode': 'realtime_direct',
        'retrieved_context': [],
        'retrieval_history': [{"mode": "realtime_direct", **parsed}],
    }


# ==================== Backward 任务(超图检索) ====================

def _handle_backward(
    question: str,
    task_type: str,
    temporal_clue: str,
    options: List[str],
    global_text: str,
    time_span_cutoff: str,
    llm_config: LLMConfig,
    hyper_vg: HyperVideoGraph,
    max_rounds: int = 2,
) -> dict:
    options_text = _format_options_block(options)
    retrieved_contexts = []
    retrieval_history = []

    loop = always_get_an_event_loop()

    for round_idx in range(1, max_rounds + 1):
        logger.info(f"    [Backward] Round {round_idx}/{max_rounds}")

        retrieved_text = ""
        if retrieved_contexts:
            retrieved_text = "\n\n".join(
                f"[Retrieved {i+1}]\n{ctx}"
                for i, ctx in enumerate(retrieved_contexts)
            )

        full_prompt = f"""{STREAMINGBENCH_BACKWARD_RETRIEVAL_PROMPT}

------------------------------------------------------------
TASK_TYPE
------------------------------------------------------------
{task_type}

------------------------------------------------------------
TEMPORAL_CLUE
------------------------------------------------------------
{temporal_clue}

------------------------------------------------------------
QUESTION
------------------------------------------------------------
{question}

------------------------------------------------------------
OPTIONS
------------------------------------------------------------
{options_text}

------------------------------------------------------------
GLOBAL_CAPTIONS (up to time_stamp)
------------------------------------------------------------
{global_text}

------------------------------------------------------------
RETRIEVED_CONTEXT
------------------------------------------------------------
{retrieved_text if retrieved_text else "None (first round)"}
"""
        try:
            response = asyncio.run(llm_config.best_model_func_raw(
                llm_config.best_model_name,
                full_prompt,
                system_prompt=None,
                history_messages=[],
            ))
            logger.info(f"    LLM response: {str(response)[:200]}...")
            decision = _parse_llm_json(response) if isinstance(response, str) else response
            if decision is None:
                logger.error(f"    JSON 解析失败: {response}")
                decision = {"decision": "error", "error": str(response)}
        except Exception as e:
            logger.error(f"    LLM 调用失败: {e}")
            decision = {"decision": "error", "error": str(e)}

        decision['round'] = round_idx
        retrieval_history.append(decision)
        d = decision.get('decision', '')

        def _build_result(answer, reasoning):
            return {
                'answer': answer,
                'reasoning': reasoning,
                'round': round_idx,
                'mode': 'backward_hyper_retrieval',
                'retrieved_context': retrieved_contexts.copy(),
                'retrieval_history': retrieval_history,
            }

        if d in ('answer', 'forced_answer'):
            logger.info(f"    Round {round_idx}: 直接回答 (decision={d})")
            return _build_result(
                decision.get('answer', ''),
                decision.get('reasoning', ''),
            )

        elif d == 'need_retrieval':
            if round_idx >= max_rounds:
                logger.warning(f"    Round {round_idx}: 已达最大轮次, 强制回答")
                return _build_result(
                    decision.get('answer', ''),
                    'Max retrieval rounds reached, answering with available info',
                )

            retrieval_query = decision.get('retrieval_query', '')
            logger.info(f"    Round {round_idx}: 需要检索, query: {retrieval_query}")

            try:
                retrieval_result = loop.run_until_complete(
                    hyper_vg.retrieve(retrieval_query, time_span_cutoff)
                )
                retrieved_text_ctx = hyper_vg.format_retrieval_for_llm(retrieval_result)
                if not retrieved_text_ctx:
                    retrieved_text_ctx = (
                        "No relevant facts or episodes found in the hypergraph."
                    )
                logger.info(
                    f"    Hyper retrieval done: topics={len(retrieval_result.topics)}, "
                    f"episodes={len(retrieval_result.episodes)}, "
                    f"facts={len(retrieval_result.facts)}"
                )
                retrieved_contexts.append(retrieved_text_ctx)
            except Exception as e:
                logger.error(f"    Retrieval failed: {e}")
                retrieved_contexts.append(f"Retrieval failed: {str(e)}")

        else:
            logger.error(f"    未知 decision: {d}")
            if round_idx >= max_rounds:
                return _build_result('', 'Max rounds reached with unknown decision')

    logger.warning("    所有检索轮次完成但未得到答案")
    return {
        'answer': '',
        'reasoning': 'Retrieval completed without clear answer',
        'round': max_rounds,
        'mode': 'backward_hyper_retrieval',
        'retrieved_context': retrieved_contexts.copy(),
        'retrieval_history': retrieval_history,
    }


# ==================== 单问题处理 ====================

def process_single_question(
    row: dict,
    sample_id: str,
    args,
) -> dict:
    """处理一条 MCQ row(来自 CSV)。"""
    question_id = row['question_id']
    task_type = row.get('task_type', '?')
    question = row.get('question', '')
    time_stamp = row.get('time_stamp', '')
    gt_letter = row.get('answer', '').strip().upper()
    options = _parse_options(row.get('options', ''))
    temporal_clue = row.get('temporal_clue_type', 'Concurrent')

    working_dir = (
        f"{args.save_root}/"
        f"{args.datasets_type}/{sample_id}_{args.caption_model_name}"
    )

    def _err_result(msg, err_code):
        return {
            'question_id': question_id,
            'sample_id': sample_id,
            'task_type': task_type,
            'temporal_clue_type': temporal_clue,
            'question': question,
            'options': options,
            'time_stamp': time_stamp,
            'answer': '',
            'reasoning': msg,
            'gt_letter': gt_letter,
            'pred_letter': None,
            'is_correct': None,
            'error': err_code,
        }

    if not os.path.exists(working_dir):
        logger.warning(f"  Working dir 不存在: {working_dir}")
        return _err_result(f'Working dir not found: {working_dir}', 'working_dir_not_found')

    fc_path = os.path.join(working_dir, "frame_captions.json")
    if not os.path.exists(fc_path):
        logger.error(f"  frame_captions 不存在: {fc_path}")
        return _err_result(
            f'frame_captions not found: {fc_path}', 'frame_captions_not_found'
        )

    with open(fc_path, 'r', encoding='utf-8') as f:
        fc_data = json.load(f)

    second_captions = fc_data.get('frame_captions', [])
    min_captions = fc_data.get('window_descriptions', [])

    # 时间过滤: 只使用 time_stamp 之前的 captions
    cutoff_sec = _hms_to_seconds(time_stamp)
    time_span_cutoff = _build_time_span_cutoff(time_stamp)

    filtered_sec = _filter_captions_up_to(second_captions, cutoff_sec)
    filtered_min = _filter_captions_up_to(min_captions, cutoff_sec)
    global_text = _format_captions(filtered_min) if filtered_min else _format_captions(min_captions[:5])

    # 建图固定 openai text-embedding-3-small, 保持一致
    llm_config = llm_config_openai
    # 下面原 vdb_chunks.json 选择逻辑保留但默认不触发
    vdb_chunks_path = os.path.join(working_dir, "vdb_chunks.json")
    if os.path.exists(vdb_chunks_path):
        try:
            with open(vdb_chunks_path, 'r') as f:
                meta = json.load(f)
            if meta.get("embedding_dim", 1536) == 1024:
                llm_config = llm_config_bge
                logger.info("  embedding_dim=1024, 使用 bge-m3")
            else:
                logger.info("  embedding_dim=1536, 使用 text-embedding-3-small")
        except Exception:
            pass

    # ---- 4 种检索模式 路由 ----
    # retrieval_mode 取值:
    #   - "dump_all"     : 不检索, 全量喂 ALL_EPISODES + ALL_FACTS (+ latest 2 captions)
    #   - "fact_only"    : 检索, 只在 fact 层做 BM25+embedding (+ episode summaries)
    #   - "episode_fact" : 检索, episode 层入口 → 扩展到 fact
    #   - "hierarchical" : 检索, topic → episode → fact (默认 3 阶段)
    # 所有模式都对 Prior + Concurrent 都适用 (打通建图后的统一推理路径)
    retrieval_mode = getattr(args, "retrieval_mode", "dump_all")
    near_n = getattr(args, "near_n", 5)

    from hypervideo.config import HyperVideoConfig
    hyper_cfg = HyperVideoConfig(
        embedding_propagation_mode=os.environ.get("HYPERVIDEO_PROPAGATION_MODE", "residual"),
        embedding_propagation_lambda=float(os.environ.get("HYPERVIDEO_PROPAGATION_LAMBDA", "0.5")),
    )
    hyper_vg = HyperVideoGraph(working_dir=working_dir, llm=llm_config, hyper_config=hyper_cfg)
    stats = hyper_vg.hypergraph_builder.hypergraph.get_stats()
    logger.info(
        f"  [{retrieval_mode}] task={task_type} clue={temporal_clue} "
        f"cutoff={time_stamp} hyper={stats}"
    )

    if stats.get("episodes", 0) == 0:
        logger.warning("  超图为空, 回退到 realtime 直接回答")
        recent_caps = _get_recent_captions_before(
            second_captions, cutoff_sec, window_seconds=15
        )
        result = _handle_realtime(
            question=question,
            task_type=task_type,
            temporal_clue=temporal_clue,
            options=options,
            recent_text=_format_captions(recent_caps),
            global_text=global_text,
            llm_config=llm_config,
        )
        result['mode'] = 'fallback_realtime_empty_hypergraph'
    elif getattr(args, "use_skills", False) and task_type in (
            "Counting", "Causal Reasoning", "Spatial Understanding"):
        # 类型化 skill (基线弱项三类), 默认关闭; skill 返回 None 则退回原模式路径
        from hypervideo.streamingbench_skills import (
            SKILL_DISPATCH, SKILL_DISPATCH_V2, SKILL_DISPATCH_V3)
        _ver = getattr(args, "skills_version", "v1")
        _table = {"v1": SKILL_DISPATCH, "v2": SKILL_DISPATCH_V2,
                  "v3": SKILL_DISPATCH_V3}[_ver]
        if task_type not in _table:
            _table = {}  # 该版本不接管此题型
        recent_caps = _get_recent_captions_before(
            second_captions, cutoff_sec, window_seconds=15)
        _kw = dict(question=question, task_type=task_type,
                   options_text=_format_options_block(options),
                   recent_text=_format_captions(recent_caps),
                   cutoff_sec=cutoff_sec, llm_config=llm_config, hyper_vg=hyper_vg)
        _fn = _table.get(task_type)
        if _fn is not None and _fn.__name__ == 'handle_sb_vlm_frames':
            _kw['sample_id'] = sample_id
        result = _fn(**_kw) if _fn is not None else None
        if result is None:
            result = _handle_backward_with_retrieval(
                question=question, task_type=task_type, options=options,
                second_captions=second_captions, cutoff_sec=cutoff_sec,
                llm_config=llm_config, hyper_vg=hyper_vg,
                max_rounds=args.max_rounds, near_n=near_n,
                retrieval_mode="hierarchical")
    elif retrieval_mode == "sb_agentic":
        # 真·agentic: 模型自主选工具(get_recent_episodes/search_*)、自主决定轮数 (merge2 思路)
        from hypervideo.agentic_solver_sb import agentic_answer as _sb_agentic_answer
        from hypervideo.agentic_tools import HyperToolBank
        _ts = _build_time_span_cutoff(_seconds_to_hms(cutoff_sec))
        _bank = HyperToolBank(hyper_vg, current_time_span=_ts)
        _opts_text = _format_options_block(options)
        _loop = always_get_an_event_loop()
        _r = _loop.run_until_complete(_sb_agentic_answer(question, _opts_text, _bank, llm_config,
                                         max_rounds=args.max_rounds, task_type=task_type))
        result = {'answer': _r.get('answer',''), 'reasoning': _r.get('reasoning',''),
                  'round': _r.get('rounds',0), 'mode': 'sb_agentic',
                  'retrieved_context': [], 'retrieval_history': [{'tools': _r.get('tools_used',[])}]}
    elif retrieval_mode in ("sb_s1", "sb_s2", "sb_s3", "sb_s4", "sb_s5", "sb_s6", "sb_s7", "sb_s8", "sb_s9", "sb_s10", "sb_s12", "sb_s13"):
        # SB 三方案: 内容用 SB 自己的函数组装(和 _handle_backward 86% 完全一致), 传给 solver。
        # solver 只按 scheme 分配 固定喂 vs get_recent 工具 + agentic 决策。
        from hypervideo.agentic_solver_sb3 import agentic_answer as _sb3_answer
        from hypervideo.agentic_tools import HyperToolBank
        _scheme = int(retrieval_mode.split("_s")[-1])   # 支持两位数 scheme(sb_s10)
        _ts = _build_time_span_cutoff(_seconds_to_hms(cutoff_sec))
        _all_eps, _nearby = _build_episode_blocks(hyper_vg, _ts, near_n=near_n)
        # caption 窗口秒数: 命令行 --recent_window_sec 控制(网格扫 3/5/7/10...), 默认 12 保持旧行为
        _rw = int(getattr(args, "recent_window_sec", 0) or 12)
        _recent_cap = _format_captions(_get_recent_captions_before(second_captions, cutoff_sec, window_seconds=_rw))
        _bank = HyperToolBank(hyper_vg, current_time_span=_ts)
        _opts_text = _format_options_block(options)
        # s13(SB版rt3): 固定喂通道B当下结构化感知(单变量, 比s7多一块)
        _cur_perc = ""
        if _scheme == 13:
            try:
                _cur_perc = _bank.get_current_perception(last_sec=12.0) or ""
            except Exception:
                _cur_perc = ""
        _loop = always_get_an_event_loop()
        _r = _loop.run_until_complete(_sb3_answer(question, _opts_text, _bank, llm_config,
                                       max_rounds=args.max_rounds, task_type=task_type, scheme=_scheme,
                                       all_eps=_all_eps, nearby_ep=_nearby, recent_cap=_recent_cap,
                                       cur_perc=_cur_perc))
        result = {'answer': _r.get('answer',''), 'reasoning': _r.get('reasoning',''),
                  'round': _r.get('rounds',0), 'mode': retrieval_mode,
                  'retrieved_context': [], 'retrieval_history': [{'tools': _r.get('tools_used',[])}]}
    elif retrieval_mode == "sb_merge2":
        # 方案C: OVO merge2 原版挂 SB — 底座 episode summary 骨架(固定喂) +
        # get_recent_episodes 工具(最近 episode summary+desc, 模型按需调) + search, 自主多轮
        from hypervideo.agentic_solver_merge2 import agentic_answer as _merge2_answer
        from hypervideo.agentic_tools import HyperToolBank
        _ts = _build_time_span_cutoff(_seconds_to_hms(cutoff_sec))
        _bank = HyperToolBank(hyper_vg, current_time_span=_ts)
        _opts_text = _format_options_block(options)
        _loop = always_get_an_event_loop()
        _r = _loop.run_until_complete(_merge2_answer(question, _opts_text, _bank, llm_config,
                                       max_rounds=args.max_rounds))
        result = {'answer': _r.get('answer',''), 'reasoning': _r.get('reasoning',''),
                  'round': _r.get('rounds',0), 'mode': 'sb_merge2',
                  'retrieved_context': [], 'retrieval_history': [{'tools': _r.get('tools_used',[])}]}
    elif retrieval_mode == "dump_all":
        result = _handle_dump_all(
            question=question,
            task_type=task_type,
            options=options,
            second_captions=second_captions,
            cutoff_sec=cutoff_sec,
            llm_config=llm_config,
            hyper_vg=hyper_vg,
        )
    elif retrieval_mode in ("fact_only", "episode_fact", "hierarchical"):
        result = _handle_backward_with_retrieval(
            question=question,
            task_type=task_type,
            options=options,
            second_captions=second_captions,
            cutoff_sec=cutoff_sec,
            llm_config=llm_config,
            hyper_vg=hyper_vg,
            max_rounds=args.max_rounds,
            near_n=near_n,
            retrieval_mode=retrieval_mode,
        )
    elif retrieval_mode == "merge2":
        # merge2 适配: agentic 自主检索(hierarchical 底层) + RECENT 喂最近 ~12s 帧 caption(不只2帧)
        result = _handle_backward_with_retrieval(
            question=question,
            task_type=task_type,
            options=options,
            second_captions=second_captions,
            cutoff_sec=cutoff_sec,
            llm_config=llm_config,
            hyper_vg=hyper_vg,
            max_rounds=args.max_rounds,
            near_n=near_n,
            retrieval_mode="hierarchical",
            recent_window_sec=12,
        )
    else:
        logger.error(f"  未知 retrieval_mode={retrieval_mode}, 跳过")
        result = {
            'answer': '', 'reasoning': f'unknown retrieval_mode={retrieval_mode}',
            'round': 0, 'mode': f'error_unknown_mode_{retrieval_mode}',
            'retrieved_context': [], 'retrieval_history': [],
        }

    pred_letter = _extract_option_letter(str(result.get('answer', '')), options=options)
    is_correct = (
        pred_letter is not None and gt_letter and pred_letter == gt_letter
    )

    result.update({
        'question_id': question_id,
        'sample_id': sample_id,
        'task_type': task_type,
        'temporal_clue_type': temporal_clue,
        'question': question,
        'options': options,
        'time_stamp': time_stamp,
        'gt_letter': gt_letter,
        'pred_letter': pred_letter,
        'is_correct': is_correct,
    })
    return result


# ==================== 结果保存 ====================

def save_output_results(output_results: dict, output_path: str):
    """保存结果 + 每任务类型 / 每 temporal_clue_type 的准确率统计"""
    global_correct = 0
    global_total = 0
    task_stats = {}
    clue_stats = {}

    for qid, r in output_results.items():
        if qid == "__global_summary__":
            continue
        if r.get('is_correct') is None:
            continue

        task = r.get('task_type', 'unknown')
        clue = r.get('temporal_clue_type', 'unknown')

        for key, stats in ((task, task_stats), (clue, clue_stats)):
            if key not in stats:
                stats[key] = {'correct': 0, 'total': 0}
            stats[key]['total'] += 1
            if r.get('is_correct'):
                stats[key]['correct'] += 1

        global_total += 1
        if r.get('is_correct'):
            global_correct += 1

    for stats in (task_stats, clue_stats):
        for key in stats:
            s = stats[key]
            s['accuracy'] = s['correct'] / s['total'] if s['total'] > 0 else 0.0

    output_results["__global_summary__"] = {
        "total_questions": global_total,
        "total_correct": global_correct,
        "accuracy": global_correct / global_total if global_total > 0 else 0.0,
        "per_task": task_stats,
        "per_temporal_clue": clue_stats,
    }

    with open(output_path, "w", encoding="utf-8") as f:
        json.dump(output_results, f, ensure_ascii=False, indent=2)

    if global_total > 0:
        logger.info(
            f"已保存结果到 {output_path} "
            f"(total={global_total}, correct={global_correct}, "
            f"accuracy={global_correct/global_total:.2%})"
        )
    else:
        logger.info(f"已保存结果到 {output_path} (暂无结果)")

    for task in sorted(task_stats.keys()):
        s = task_stats[task]
        logger.info(f"  [task] {task}: {s['correct']}/{s['total']} = {s['accuracy']:.2%}")
    for clue in sorted(clue_stats.keys()):
        s = clue_stats[clue]
        logger.info(f"  [clue] {clue}: {s['correct']}/{s['total']} = {s['accuracy']:.2%}")


# ==================== 主入口 ====================

def _parse_sample_id_from_qid(question_id: str) -> str:
    """'Real-Time Visual Understanding_sample_1_1' -> 'sample_1'"""
    # qid 里有下划线和连字符, 找最后一个形如 sample_<N> 的部分
    m = re.search(r'sample_(\d+)', question_id)
    if m:
        return f"sample_{m.group(1)}"
    return ""


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="StreamingBench RTVU HyperVideo 推理与评估"
    )
    parser.add_argument(
        "--csv_path", type=str,
        default="/mnt/tokyo-ai/gst/StreamingBench-/StreamingBench/Real_Time_Visual_Understanding.csv",
        help="官方 MCQ CSV 路径",
    )
    parser.add_argument(
        "--save_root", type=str,
        default="/mnt/tokyo-ai/gst/GST_EGOSERVE/all_results",
        help="建图结果根目录(与 streamingbench_hyper_processing.py 保持一致)",
    )
    parser.add_argument(
        "--datasets_type", type=str, default="streamingbench_rt_full_qwenapi",
    )
    parser.add_argument("--caption_model_name", type=str, default="qwen_api")
    parser.add_argument(
        "--output_path", type=str,
        default="/mnt/tokyo-ai/gst/GST_EGOSERVE/output_results_streamingbench_rtvu_hyper.json",
    )
    parser.add_argument("--max_rounds", type=int, default=1)
    parser.add_argument(
        "--recent_window_sec", type=int, default=12,
        help="sb_s* 方案: RECENT_CAPTIONS 取问题时刻前 N 秒的帧 caption (网格扫 3/5/7/10), 默认12",
    )
    parser.add_argument(
        "--retrieval_mode", type=str, default="sb_s1",
        choices=["dump_all", "fact_only", "episode_fact", "hierarchical", "merge2", "sb_agentic", "sb_merge2", "sb_s1", "sb_s2", "sb_s3", "sb_s4", "sb_s5", "sb_s6", "sb_s7", "sb_s8", "sb_s9", "sb_s10", "sb_s12", "sb_s13"],
        help="4 种推理方式: dump_all (不检索, 全量喂); fact_only (只检索 fact); "
             "episode_fact (episode→fact); hierarchical (topic→episode→fact, 默认 3 阶段)",
    )
    parser.add_argument(
        "--near_n", type=int, default=5,
        help="近 N 个 episode 给完整 summary+description (其余只 summary)",
    )
    parser.add_argument('--cuda', type=str, default='0')
    parser.add_argument(
        '--only_qids', type=str, default=None,
        help="仅处理指定 question_id, 分号分隔",
    )
    parser.add_argument(
        '--skills_version', type=str, default='v1', choices=['v1','v2','v3'],
        help="v1=文本skill; v2=Counting/Spatial 走 VLM 看帧 (Qwen3-VL)")
    parser.add_argument(
        '--use_skills', action='store_true',
        help="Counting/Causal/Spatial 走类型化 skill (见 streamingbench_skills.py). "
             "默认 False, 原模式路径不变")
    parser.add_argument(
        '--only_sample_ids', type=str, default=None,
        help="仅处理指定 sample 数字 id, 逗号分隔, 如 '1,2,3'",
    )
    parser.add_argument(
        '--only_clue', type=str, default=None,
        help="仅处理指定 temporal_clue_type (Prior / Concurrent)",
    )
    parser.add_argument(
        '--answer_model', type=str, default='gpt-5-mini',
        help="LLM 推理模型. 候选: gpt-4.1-mini (default) / gpt-5.4-nano / gpt-5.4-mini",
    )
    parser.add_argument(
        '--propagation_mode', type=str, default='residual',
        choices=['residual', 'hypermem', 'none'],
        help="嵌入传播: residual (默认) / hypermem / none",
    )
    parser.add_argument(
        '--propagation_lambda', type=float, default=0.5,
    )
    args = parser.parse_args()

    os.environ["HYPERVIDEO_ANSWER_MODEL"] = args.answer_model
    os.environ["HYPERVIDEO_PROPAGATION_MODE"] = args.propagation_mode
    os.environ["HYPERVIDEO_PROPAGATION_LAMBDA"] = str(args.propagation_lambda)
    llm_config_openai.best_model_name = args.answer_model
    llm_config_bge.best_model_name = args.answer_model
    logger.info(f"[args] answer_model={args.answer_model} propagation_mode={args.propagation_mode} lambda={args.propagation_lambda}")

    os.environ["CUDA_VISIBLE_DEVICES"] = args.cuda
    logger.info(f"CUDA_VISIBLE_DEVICES={args.cuda}")

    # OPENAI key: 从 .env 加载 (不再硬编码)
    if not os.environ.get("OPENAI_API_KEY"):
        try:
            from dotenv import load_dotenv
            load_dotenv("/mnt/tokyo-ai/gst/GST_EGOSERVE/.env")
        except ImportError:
            pass
    if not os.environ.get("OPENAI_API_KEY"):
        raise RuntimeError("OPENAI_API_KEY 未设置. 请确认 /mnt/tokyo-ai/gst/GST_EGOSERVE/.env")

    # 读 CSV
    with open(args.csv_path, 'r', encoding='utf-8') as f:
        reader = csv.DictReader(f)
        all_rows = list(reader)
    logger.info(f"共加载 {len(all_rows)} 条 MCQ")

    # 过滤
    if args.only_qids:
        wanted = {s.strip() for s in args.only_qids.split(';') if s.strip()}
        all_rows = [r for r in all_rows if r['question_id'] in wanted]
        logger.info(f"按 --only_qids 过滤后剩余 {len(all_rows)} 条")
    if args.only_sample_ids:
        wanted = {s.strip() for s in args.only_sample_ids.split(',') if s.strip()}
        all_rows = [
            r for r in all_rows
            if _parse_sample_id_from_qid(r['question_id']).split('_')[-1] in wanted
        ]
        logger.info(f"按 --only_sample_ids 过滤后剩余 {len(all_rows)} 条")
    if args.only_clue:
        all_rows = [r for r in all_rows if r.get('temporal_clue_type') == args.only_clue]
        logger.info(f"按 --only_clue={args.only_clue} 过滤后剩余 {len(all_rows)} 条")

    # 按 sample 分组, 方便排序调试
    by_sample = defaultdict(list)
    for r in all_rows:
        sid = _parse_sample_id_from_qid(r['question_id'])
        by_sample[sid].append(r)

    # 断点续传
    output_results = {}
    if os.path.exists(args.output_path):
        try:
            with open(args.output_path, 'r', encoding='utf-8') as f:
                output_results = json.load(f)
            logger.info(f"加载已有结果: {len(output_results)} 条 ({args.output_path})")
        except Exception as e:
            logger.warning(f"加载旧结果失败: {e}, 从头开始")
            output_results = {}

    _ERROR_PATTERNS = (
        "RetryError", "RateLimitError", "APIError", "TimeoutError",
        "ConnectionError", "Retrieval failed", "checkpoint_not_found",
        "working_dir_not_found",
    )

    def _is_error_result(r: dict) -> bool:
        for field in ("reasoning", "error"):
            v = r.get(field)
            if isinstance(v, str):
                for pat in _ERROR_PATTERNS:
                    if pat in v:
                        return True
        return False

    t_all = time.time()
    processing_times = []
    total_q = len(all_rows)

    for loop_idx, row in enumerate(all_rows):
        qid = row['question_id']
        sid = _parse_sample_id_from_qid(qid)

        if qid in output_results and qid != "__global_summary__":
            existing = output_results[qid]
            if existing.get('is_correct') is not None and not _is_error_result(existing):
                logger.info(f"[{loop_idx+1}/{total_q}] {qid} 已完成, 跳过")
                continue
            else:
                logger.info(f"[{loop_idx+1}/{total_q}] {qid} 有错误, 重新处理")

        t0 = time.time()
        logger.info(
            f"[{loop_idx+1}/{total_q}] Processing qid={qid} sample={sid} "
            f"task={row.get('task_type')} clue={row.get('temporal_clue_type')}"
        )
        logger.info(f"  Q: {row.get('question', '')[:120]}")

        try:
            result = process_single_question(row, sid, args)
            output_results[qid] = result
            dt = time.time() - t0
            processing_times.append(dt)
            logger.info(
                f"[{loop_idx+1}/{total_q}] {qid} done | time={dt:.1f}s | "
                f"pred={result.get('pred_letter')} gt={result.get('gt_letter')} | "
                f"correct={result.get('is_correct')} | "
                f"mode={result.get('mode')} round={result.get('round')}"
            )
            if (loop_idx + 1) % 10 == 0:
                save_output_results(output_results, args.output_path)
        except Exception as e:
            dt = time.time() - t0
            logger.error(f"[{loop_idx+1}/{total_q}] {qid} 失败: {e} (time={dt:.1f}s)")
            output_results[qid] = {
                'question_id': qid,
                'sample_id': sid,
                'task_type': row.get('task_type', ''),
                'temporal_clue_type': row.get('temporal_clue_type', ''),
                'question': row.get('question', ''),
                'options': _parse_options(row.get('options', '')),
                'time_stamp': row.get('time_stamp', ''),
                'answer': '',
                'reasoning': str(e),
                'gt_letter': row.get('answer', '').strip().upper(),
                'pred_letter': None,
                'is_correct': None,
                'error': str(e),
            }

    save_output_results(output_results, args.output_path)

    total_time = time.time() - t_all
    gs = output_results.get("__global_summary__", {})
    logger.info(f"\n{'=' * 80}")
    logger.info(f"StreamingBench RTVU HyperVideo 推理完成!")
    logger.info(f"{'=' * 80}")
    logger.info(f"  总耗时: {total_time:.1f}s ({total_time/60:.2f} min)")
    logger.info(f"  Total: {gs.get('total_questions', 0)}")
    logger.info(f"  Correct: {gs.get('total_correct', 0)}")
    logger.info(f"  Accuracy: {gs.get('accuracy', 0):.2%}")
    if processing_times:
        logger.info(
            f"  Avg: {sum(processing_times)/len(processing_times):.2f}s/question"
        )
        logger.info(f"  Fastest: {min(processing_times):.2f}s")
        logger.info(f"  Slowest: {max(processing_times):.2f}s")
    logger.info(f"  Results: {args.output_path}")
    logger.info(f"{'=' * 80}\n")