File size: 42,644 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
"""
StreamingBench (Real_Time_Visual_Understanding) 建图入口 —— HyperVideoGraph + 三层超图

对齐 HyperMem stage1 的流式边界检测:
  1. 按 interval_seconds 采样 sample_*/video.mp4 的帧
  2. 用 HyperVideoGraph 自己的 VLM (load_caption_model) 每 K 帧生成 dense
     frame captions (key = "DAY1-HH:MM:SS-HH:MM:SS")
  3. 打包 dense_caption dict → hypergraph_builder.process_window_caption:
     内部 _decompose_window 拆为单 FrameCaption → VideoEpisodeSegmenter
     逐帧流式边界检测 → 命中边界 finalize Episode + 主题聚合 + 事实提取
  4. flush 尾部 buffer, 保存 hypergraph.json

与 ovobench_hyper_processing.py 的差异:
  * 输入是 StreamingBench 的 sample 目录 (sample_*/video.mp4)
  * 使用通用视觉 caption prompt(OVO-Bench 的 prompt 已覆盖场景理解,
    questions 字段留空或填多问题合集)
"""

import os
import sys
import argparse
import asyncio
import json
import logging
import time
import gc
import re
from typing import List, Dict, Optional
import torch

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,
)
from videorag._utils import always_get_an_event_loop
from videorag.video_processing import sample_frames_by_interval
from videorag.ovobench_prompt import OVOBENCH_PROMPTS, OUTPUT_FORMAT

from hypervideo.hyper_video_graph import HyperVideoGraph
from hypervideo.config import HyperVideoConfig
from hypervideo.prompts.frame_caption_prompt import (
    FRAME_CAPTION_SINGLE_PROMPT,
    FRAME_CAPTION_WINDOW_DETAILED_PROMPT,
    FRAME_CAPTION_WINDOW_V2_PROMPT,
    FRAME_CAPTION_WINDOW_V2_WITH_PRIOR_PROMPT,
)
from hypervideo.extractors.timing_utils import timed
from concurrent.futures import ThreadPoolExecutor

logging.basicConfig(
    level=logging.INFO,
    format='[%(asctime)s] %(levelname)s: %(message)s',
)
logger = logging.getLogger(__name__)


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-5-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,
)


def clear_gpu_memory():
    if torch.cuda.is_available():
        torch.cuda.empty_cache()
        gc.collect()


def _seconds_to_hms(sec: float) -> 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 _timestamp_num_to_seconds(ts_num) -> float:
    """sample_frames_by_interval 在 time_span_info=None 时返回 HHMMSSCC 整数,
    这里把它解析回秒数。"""
    try:
        ts = int(ts_num)
    except (ValueError, TypeError):
        return float(ts_num) if ts_num else 0.0
    h = ts // 1_000_000
    m = (ts % 1_000_000) // 10_000
    s = (ts % 10_000) // 100
    cs = ts % 100
    return h * 3600 + m * 60 + s + cs / 100.0


def _safe_json_parse(text: str) -> Optional[dict]:
    if not text or not isinstance(text, str):
        return None
    s = text.strip()
    if s.startswith("```"):
        lines = s.split("\n")
        s = "\n".join(lines[1:-1]) if len(lines) > 2 else s
    try:
        return json.loads(s)
    except json.JSONDecodeError:
        m = re.search(r"\{.*\}", s, re.DOTALL)
        if m:
            try:
                return json.loads(m.group(0))
            except json.JSONDecodeError:
                return None
        return None


def _load_sample_questions(sample_dir: str) -> List[str]:
    """读取 sample_*/questions.json 里的问题文本(当作 caption attention hint)"""
    qf = os.path.join(sample_dir, "questions.json")
    if not os.path.exists(qf):
        return []
    try:
        with open(qf, 'r', encoding='utf-8') as f:
            data = json.load(f)
        qs = []
        for entry in data:
            for q in entry.get('questions', []):
                qtext = q.get('question', '')
                if qtext:
                    qs.append(qtext)
        return qs
    except Exception as e:
        logger.warning(f"  读取 {qf} 失败: {e}")
        return []


def _hms_str_to_seconds(ts: str) -> int:
    """'00:13:22' 或 '0:09:35' → 秒数。"""
    parts = ts.strip().split(':')
    return sum(int(p) * 60 ** i for i, p in enumerate(reversed(parts)))


def _load_max_ts_per_sample(json_path: str) -> Dict[str, int]:
    """从 questions_real.json 聚合每个 sample 的 max(time_stamp) 秒数。

    json_path 中每条 entry 的 video_path 形如 './videos/sample_X_real.mp4',
    sample_id 取数字部分 'X'。返回 {sample_id_str: max_ts_seconds}。
    """
    if not os.path.exists(json_path):
        logger.warning(f"questions_real.json 不存在: {json_path}, max_ts 截断将关闭")
        return {}
    try:
        with open(json_path, 'r', encoding='utf-8') as f:
            data = json.load(f)
    except Exception as e:
        logger.warning(f"读取 {json_path} 失败: {e}")
        return {}
    max_ts: Dict[str, int] = {}
    for entry in data:
        vp = entry.get('video_path', '') or ''
        # './videos/sample_348_real.mp4' → '348'
        m = re.search(r'sample_(\d+)', vp)
        if not m:
            continue
        sid = m.group(1)
        for q in entry.get('questions', []):
            ts_str = q.get('time_stamp', '')
            if not ts_str:
                continue
            try:
                secs = _hms_str_to_seconds(ts_str)
            except Exception:
                continue
            if sid not in max_ts or secs > max_ts[sid]:
                max_ts[sid] = secs
    logger.info(f"  [max_ts] 从 {os.path.basename(json_path)} 聚合 {len(max_ts)} 个 sample 的 max(time_stamp)")
    return max_ts


def _load_questions_with_options_per_sample(json_path: str) -> Dict[str, List[Dict[str, str]]]:
    """从 questions_real.json 聚合每个 sample 的 (question + options + time_stamp) 列表。

    用于问题感知建图: 把所有问题 (含选项) 注入到 caption / fact extraction prompt,
    引导 VLM / LLM 关注与问题相关的视觉证据 / 事实。

    Returns:
        {sample_id: [{"qid": "Q1", "question": "<question + Options block>",
                      "time_stamp": "HH:MM:SS"}, ...]}
    每个 sample 通常有 5 条 question, 按 time_stamp 升序。
    """
    if not os.path.exists(json_path):
        logger.warning(f"questions_real.json 不存在: {json_path}, --question_aware 不可用")
        return {}
    try:
        with open(json_path, 'r', encoding='utf-8') as f:
            data = json.load(f)
    except Exception as e:
        logger.warning(f"读取 {json_path} 失败: {e}")
        return {}

    by_sample: Dict[str, List[Dict[str, str]]] = {}
    for entry in data:
        vp = entry.get('video_path', '') or ''
        m = re.search(r'sample_(\d+)', vp)
        if not m:
            continue
        sid = m.group(1)
        for q in entry.get('questions', []):
            qtext = (q.get('question', '') or '').strip()
            if not qtext:
                continue
            opts = q.get('options', []) or []
            # 选项已带 'A. xxx' 前缀, 用 ' | ' 拼起来
            opts_str = " | ".join(o.strip() for o in opts if isinstance(o, str))
            q_full = f"{qtext}  Options: {opts_str}" if opts_str else qtext
            by_sample.setdefault(sid, []).append({
                "qid": f"Q{len(by_sample[sid]) + 1}",
                "question": q_full,
                "time_stamp": q.get('time_stamp', '') or '',
            })

    # 按 time_stamp 升序排序
    def _ts_to_sec(ts: str) -> int:
        try:
            return _hms_str_to_seconds(ts)
        except Exception:
            return 0
    for sid in by_sample:
        by_sample[sid].sort(key=lambda q: _ts_to_sec(q.get('time_stamp', '')))
        # 重新分配 qid Q1..QN 按时间序
        for i, q in enumerate(by_sample[sid]):
            q['qid'] = f"Q{i+1}"

    logger.info(
        f"  [qaware] 从 {os.path.basename(json_path)} 聚合 {len(by_sample)} 个 sample 的 questions+options"
    )
    return by_sample


def _make_questions_block(questions: List[Dict[str, str]]) -> str:
    """把 [{qid, question, time_stamp}, ...] 渲染成 prompt 用的多行块。

    格式:
      [Q1 @ 00:00:31] What ...?  Options: A. ... | B. ...
      [Q2 @ 00:03:26] Which ...?  Options: ...
    """
    if not questions:
        return "(no active user questions)"
    lines = []
    for q in questions:
        ts = q.get('time_stamp', '') or '?'
        qid = q.get('qid', '') or 'Q?'
        body = q.get('question', '') or ''
        lines.append(f"  [{qid} @ {ts}] {body}")
    return "\n".join(lines)


# ==================== Caption 生成 (两种模式) ====================

def _caption_window_batch(
    hyper_vg: HyperVideoGraph,
    window_b64: List[str],
    window_ranges: List[dict],
    caption_prompt: str,
    max_new_tokens: int,
    day_num: int,
) -> Optional[dict]:
    """批量模式: 一次 VLM 调用返回 K 帧 dense caption。
    返回 caption_dict = {"dense_caption": {...}, "description": "..."} 或 None。"""
    for retry in range(3):
        try:
            caption_text = hyper_vg.mllm_response(
                hyper_vg.video_llm, hyper_vg.processor,
                caption_prompt, None,
                base64_frames=window_b64,
                max_new_tokens=max_new_tokens, has_image=True,
            )
            parsed = _safe_json_parse(caption_text)
            if not (isinstance(parsed, dict) and "frames" in parsed
                    and isinstance(parsed["frames"], dict)):
                logger.warning(f"  [Caption-batch] 格式不合法 retry {retry+1}/3")
                continue
            dense_caption = {}
            for frame_idx_str, frame_caption in parsed["frames"].items():
                try:
                    fi = int(frame_idx_str)
                except ValueError:
                    continue
                if fi < 0 or fi >= len(window_ranges):
                    continue
                f_start = _seconds_to_hms(_timestamp_num_to_seconds(window_ranges[fi]['start']))
                f_end = _seconds_to_hms(_timestamp_num_to_seconds(window_ranges[fi]['end']))
                dense_caption[f"DAY{day_num}-{f_start}-{f_end}"] = str(frame_caption)
            return {
                "dense_caption": dense_caption,
                "description": str(parsed.get("caption", "")),
            }
        except Exception as e:
            logger.error(f"  [Caption-batch] 失败 retry {retry+1}/3: {e}")
            continue
    return None


def _caption_single_frame(
    hyper_vg: HyperVideoGraph,
    frame_b64: str,
    max_new_tokens: int,
) -> Optional[str]:
    """单帧模式: 对一帧调用 VLM, 返回该帧的 caption 文本 (或 None)。"""
    for retry in range(3):
        try:
            resp = hyper_vg.mllm_response(
                hyper_vg.video_llm, hyper_vg.processor,
                FRAME_CAPTION_SINGLE_PROMPT, None,
                base64_frames=[frame_b64],
                max_new_tokens=max_new_tokens, has_image=True,
            )
            parsed = _safe_json_parse(resp)
            if isinstance(parsed, dict) and "caption" in parsed:
                return str(parsed["caption"])
            if isinstance(resp, str) and resp.strip():
                return resp.strip()
        except Exception as e:
            logger.warning(f"  [Caption-single] 失败 retry {retry+1}/3: {e}")
    return None


def _caption_window_per_frame(
    hyper_vg: HyperVideoGraph,
    window_b64: List[str],
    window_ranges: List[dict],
    max_new_tokens: int,
    day_num: int,
    concurrency: int = 5,
) -> Optional[dict]:
    """逐帧独立 caption, 5 帧并发。返回 caption_dict 结构与 batch 模式兼容。"""
    if not window_b64:
        return None

    dense_caption: Dict[str, str] = {}
    # 线程池并发 (VLM 推理可重入; HF generate 的 GIL 释放允许并发)
    with ThreadPoolExecutor(max_workers=min(concurrency, len(window_b64))) as pool:
        futures = {
            pool.submit(_caption_single_frame, hyper_vg, fb, max_new_tokens): i
            for i, fb in enumerate(window_b64)
        }
        results: Dict[int, Optional[str]] = {}
        for fut in futures:
            i = futures[fut]
            try:
                results[i] = fut.result()
            except Exception as e:
                logger.error(f"  [Caption-per_frame] frame {i} 失败: {e}")
                results[i] = None

    for i, caption_text in results.items():
        if not caption_text:
            continue
        f_start = _seconds_to_hms(_timestamp_num_to_seconds(window_ranges[i]['start']))
        f_end = _seconds_to_hms(_timestamp_num_to_seconds(window_ranges[i]['end']))
        dense_caption[f"DAY{day_num}-{f_start}-{f_end}"] = caption_text

    if not dense_caption:
        return None

    return {
        "dense_caption": dense_caption,
        "description": "",  # per-frame 模式不合成 window 级 description
    }


def _caption_window_v2(
    hyper_vg: HyperVideoGraph,
    window_b64: List[str],
    window_ranges: List[dict],
    max_new_tokens: int,
    day_num: int,
    desc_min_sentences: int = 2,
    desc_max_sentences: int = 3,
    prior_frame_captions: Optional[List[str]] = None,
    qaware_prefix: Optional[str] = None,
) -> Optional[dict]:
    """V2 caption: 一次 batch VLM 调用,同时输出 5 个 2s frame captions + 整体 description。

    Args:
        prior_frame_captions: 上一个 window 的末尾 1-2 个 frame caption 文本
            (形如 `"[DAY1-00:00:08-00:00:10] <caption>"`)。
            非空时使用 ``FRAME_CAPTION_WINDOW_V2_WITH_PRIOR_PROMPT``,
            供 VLM 跨 window 保持命名一致性。
            为 None 或空列表时退回到不带 prior 的 V2 默认 prompt。

    返回:
      caption_dict = {
        "dense_caption": {"DAY1-...-...": "<2s caption>", ...},
        "description":   "<10s 整体描述>",
      }
    """
    if not window_b64:
        return None

    num_frames = len(window_b64)
    last_frame_index = num_frames - 1
    window_seconds = max(2 * num_frames, 2)  # 兜底(实际是 _timestamp 计算的 ~10s)

    if prior_frame_captions:
        prior_text = "\n".join(prior_frame_captions)
        prompt = FRAME_CAPTION_WINDOW_V2_WITH_PRIOR_PROMPT.format(
            num_frames=num_frames,
            last_frame_index=last_frame_index,
            window_seconds=window_seconds,
            desc_min=desc_min_sentences,
            desc_max=desc_max_sentences,
            prior_frame_context=prior_text,
        )
    else:
        prompt = FRAME_CAPTION_WINDOW_V2_PROMPT.format(
            num_frames=num_frames,
            last_frame_index=last_frame_index,
            window_seconds=window_seconds,
            desc_min=desc_min_sentences,
            desc_max=desc_max_sentences,
        )

    # 问题感知模式: 把用户问题 + 选项预先拼到 prompt 前, 引导 VLM 关注相关视觉证据
    # qaware_prefix 由 run_streaming_hyper_construction 传入, 仅 --question_aware 时生效
    # 不修改 V2 prompt 常量本身, 只在外层做字符串拼接
    if qaware_prefix:
        prompt = qaware_prefix + "\n\n" + prompt

    for retry in range(3):
        try:
            with timed("vlm_caption"):
                caption_text = hyper_vg.mllm_response(
                    hyper_vg.video_llm, hyper_vg.processor,
                    prompt, None,
                    base64_frames=window_b64,
                    max_new_tokens=max_new_tokens, has_image=True,
                )
            parsed = _safe_json_parse(caption_text)
            if not (isinstance(parsed, dict) and "frames" in parsed
                    and isinstance(parsed["frames"], dict)):
                logger.warning(f"  [Caption-v2] 格式不合法 retry {retry+1}/3")
                continue

            description = str(parsed.get("description") or "").strip()
            if not description:
                logger.warning(f"  [Caption-v2] 缺 description retry {retry+1}/3")
                # 不直接 retry,下面用 frame caption 拼接兜底
                # 但若 description 缺失,downstream 边界判断质量会下降,所以先重试
                continue

            dense_caption: Dict[str, str] = {}
            for frame_idx_str, frame_caption in parsed["frames"].items():
                try:
                    fi = int(frame_idx_str)
                except ValueError:
                    continue
                if fi < 0 or fi >= len(window_ranges):
                    continue
                f_start = _seconds_to_hms(_timestamp_num_to_seconds(window_ranges[fi]['start']))
                f_end = _seconds_to_hms(_timestamp_num_to_seconds(window_ranges[fi]['end']))
                dense_caption[f"DAY{day_num}-{f_start}-{f_end}"] = str(frame_caption)

            if not dense_caption:
                logger.warning(f"  [Caption-v2] frames 解析为空 retry {retry+1}/3")
                continue

            return {
                "dense_caption": dense_caption,
                "description": description,
            }
        except Exception as e:
            logger.error(f"  [Caption-v2] 失败 retry {retry+1}/3: {e}")
            continue
    return None


# ==================== 流式建图核心 ====================

def run_streaming_hyper_construction(
    hyper_vg: HyperVideoGraph,
    video_path: str,
    sample_dir: str,
    interval_seconds: float = 2.0,
    window_frames: int = 5,
    max_new_tokens: int = 1024,
    day_num: int = 1,
    frame_captions_out_path: Optional[str] = None,
    caption_mode: str = "batch",
    per_frame_concurrency: int = 5,
    max_seconds: Optional[float] = None,
    qaware_prefix: Optional[str] = None,
):
    """流式建图: 按 interval 采样 → window_frames 一批送 VLM → 打包送超图。

    caption_mode:
      * "batch"     — 一次 VLM 调用产出 window 的多帧 dense caption (默认)
      * "per_frame" — 每帧一次独立调用, 帧间并发 (per_frame_concurrency 控制)

    max_seconds:
      * None — 处理整段视频
      * float — 只处理 [0, max_seconds] 这段(按 frame.start 秒数过滤)。
        用于 SB Real-Time: 没必要建到视频结尾, max(question.time_stamp) 之后
        的内容不会被任何问题问到。
    """
    if not os.path.exists(video_path):
        raise FileNotFoundError(f"Video not found: {video_path}")

    loop = always_get_an_event_loop()

    logger.info(f"  [Sample] video={os.path.basename(sample_dir)}, 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_raw = len(base64_frames)

    # max_seconds 截断: 保留 frame.start <= max_seconds 的帧
    if max_seconds is not None and max_seconds > 0:
        keep = [
            i for i, tr in enumerate(time_ranges)
            if _timestamp_num_to_seconds(tr['start']) <= max_seconds
        ]
        if keep:
            cut = keep[-1] + 1
            base64_frames = base64_frames[:cut]
            time_ranges = time_ranges[:cut]
            logger.info(
                f"  [Truncate] max_seconds={max_seconds:.1f}s → 保留 {cut}/{n_frames_raw} 帧 "
                f"(节省 {(1 - cut / n_frames_raw) * 100:.1f}%)"
            )
        else:
            logger.warning(f"  [Truncate] max_seconds={max_seconds:.1f}s 太小, 无可用帧, 跳过")
            return

    n_frames = len(base64_frames)
    logger.info(f"  [Sample] 共采样 {n_frames} 帧")
    if n_frames == 0:
        logger.warning("  没有可用帧")
        return

    # ---- V2 / V1 路径分派 ----
    # V2: caption_granularity="per_window" + boundary_strategy="stream"
    #     使用 FRAME_CAPTION_WINDOW_V2_PROMPT,一次 batch 同时输出 5 个 2s caption + 1 个 description
    #     边界检测每 window 1 次(流式 binary)
    # V1: 保留旧的 per_frame / batch 路径
    cfg = hyper_vg.hyper_config
    use_v2 = (cfg.caption_granularity == "per_window" and cfg.boundary_strategy == "stream")

    if use_v2:
        logger.info("  [Mode] V2: per_window caption + stream boundary")
        caption_prompt = None  # V2 模式 prompt 在 _caption_window_v2 内部 format
    elif caption_mode == "batch":
        caption_prompt = FRAME_CAPTION_WINDOW_DETAILED_PROMPT.format(
            output_format=OUTPUT_FORMAT,
        )
    else:
        caption_prompt = None  # per_frame 模式由 _caption_single_frame 内部使用简化 prompt

    all_frame_captions: List[dict] = []
    window_descriptions: List[dict] = []

    # 重置计时统计(每个 video 独立)
    try:
        hyper_vg.hypergraph_builder.reset_timing()
    except Exception:
        pass

    # V2 模式专用:跨 window 的 naming-context。保存上一个 window 的末尾 N_PRIOR 条
    # frame caption 文本(含时间戳前缀),作为当前 window VLM 的 prior context。
    # 目的:让 VLM 在命名(球员名字、物体标签)上跨 window 保持一致。
    prev_tail_captions: List[str] = []
    N_PRIOR = 2  # 只传最后 2 条

    n_windows = (n_frames + window_frames - 1) // window_frames
    for w_idx in range(n_windows):
        s = w_idx * window_frames
        e = min(s + window_frames, n_frames)
        window_b64 = base64_frames[s:e]
        window_ranges = time_ranges[s:e]

        win_start_sec = _timestamp_num_to_seconds(window_ranges[0]['start'])
        win_end_sec = _timestamp_num_to_seconds(window_ranges[-1]['end'])
        win_time_span = (
            f"{day_num}-{_seconds_to_hms(win_start_sec)}-{_seconds_to_hms(win_end_sec)}"
        )

        # 根据模式分派 caption 调用
        t0 = time.time()
        if use_v2:
            caption_dict = _caption_window_v2(
                hyper_vg=hyper_vg,
                window_b64=window_b64,
                window_ranges=window_ranges,
                max_new_tokens=max_new_tokens,
                day_num=day_num,
                prior_frame_captions=prev_tail_captions or None,
                qaware_prefix=qaware_prefix,
            )
            mode_tag = "v2_qaware" if qaware_prefix else "v2"
        elif caption_mode == "per_frame":
            caption_dict = _caption_window_per_frame(
                hyper_vg=hyper_vg,
                window_b64=window_b64,
                window_ranges=window_ranges,
                max_new_tokens=max_new_tokens,
                day_num=day_num,
                concurrency=per_frame_concurrency,
            )
            mode_tag = "per_frame"
        else:
            caption_dict = _caption_window_batch(
                hyper_vg=hyper_vg,
                window_b64=window_b64,
                window_ranges=window_ranges,
                caption_prompt=caption_prompt,
                max_new_tokens=max_new_tokens,
                day_num=day_num,
            )
            mode_tag = "batch"
        dt = time.time() - t0

        if not caption_dict:
            logger.error(f"  [Caption] win {w_idx+1}/{n_windows} 最终失败, 跳过")
            continue

        logger.info(
            f"  [Caption-{mode_tag}] win {w_idx+1}/{n_windows} ({win_time_span}) "
            f"{len(window_b64)} 帧, {len(caption_dict['dense_caption'])} captions, {dt:.1f}s"
        )

        # 记录 frame captions + window descriptions
        for fk, fv in caption_dict["dense_caption"].items():
            all_frame_captions.append({"time_span": fk, "caption": fv})
        window_descriptions.append({
            "time_span": win_time_span,
            "description": caption_dict["description"],
        })

        # V2: 更新 prior context —— 取当前 window 末尾 N_PRIOR 条 frame captions,
        # 带时间戳前缀,供下一个 window 的 VLM 作命名一致性参考
        if use_v2:
            dc = caption_dict["dense_caption"]
            # dense_caption dict 的 key 是 frame time_span 字符串,按字典序排序
            # ≈ 时间顺序(同一 window 内时间戳字符串前缀相同)
            sorted_keys = sorted(dc.keys())
            tail_keys = sorted_keys[-N_PRIOR:]
            prev_tail_captions = [f"[{k}] {dc[k]}" for k in tail_keys]

        # 送 hypergraph builder:V2 走新入口
        try:
            if use_v2:
                loop.run_until_complete(
                    hyper_vg.hypergraph_builder.process_window_caption_v2(
                        caption_dict=caption_dict,
                        time_span=win_time_span,
                        day_num=day_num,
                    )
                )
            else:
                loop.run_until_complete(
                    hyper_vg.hypergraph_builder.process_window_caption(
                        caption_dict=caption_dict,
                        time_span=win_time_span,
                        day_num=day_num,
                    )
                )
        except Exception as e:
            logger.error(f"  [Hyper] win {w_idx+1}/{n_windows} process 失败: {e}")
            continue

        # Visual embedding: 在 caption 完成后顺手过 ImageBind 一次,复用 window_b64
        # 未启用时是 no-op,不影响流程
        try:
            hyper_vg.hypergraph_builder.index_window_visual(win_time_span, window_b64)
        except Exception as e:
            logger.warning(f"  [Visual] win {w_idx+1}/{n_windows} 索引失败: {e}")

        if (w_idx + 1) % 10 == 0:
            stats = hyper_vg.hypergraph_builder.hypergraph.get_stats()
            logger.info(f"  [Progress] {w_idx+1}/{n_windows} windows, stats={stats}")
            # 每 10 个 window 打一次 timing 中间汇总
            try:
                hyper_vg.hypergraph_builder.log_timing_summary(
                    prefix=f"(after {w_idx+1}/{n_windows} windows)"
                )
            except Exception:
                pass

    # flush
    try:
        loop.run_until_complete(hyper_vg.hypergraph_builder.flush())
    except Exception as e:
        logger.error(f"  Flush 失败: {e}")

    try:
        hyper_vg.save_hypergraph()
    except Exception as e:
        logger.error(f"  保存超图失败: {e}")

    # 最终 timing 汇总
    try:
        hyper_vg.hypergraph_builder.log_timing_summary(prefix="(final)")
    except Exception:
        pass

    if frame_captions_out_path:
        try:
            with open(frame_captions_out_path, 'w', encoding='utf-8') as f:
                json.dump({
                    "frame_captions": all_frame_captions,
                    "window_descriptions": window_descriptions,
                    "interval_seconds": interval_seconds,
                    "window_frames": window_frames,
                    "day_num": day_num,
                }, f, ensure_ascii=False, indent=2)
            logger.info(f"  [Save] frame_captions.json -> {frame_captions_out_path}")
        except Exception as e:
            logger.error(f"  保存 frame_captions 失败: {e}")

    stats = hyper_vg.hypergraph_builder.hypergraph.get_stats()
    logger.info(f"  [Done] 超图构建完成, stats={stats}")


# ==================== 单样本处理 ====================

def _reset_hyper_vg_working_dir(hyper_vg: HyperVideoGraph, new_working_dir: str):
    """重定向 working_dir + 重置所有存储/超图/索引, 保留 caption_model。"""
    from dataclasses import asdict
    from videorag._storage import JsonKVStorage, NanoVectorDBVideoSegmentStorage
    from hypervideo.extractors.hypergraph_builder import VideoHypergraphBuilder
    from hypervideo.index.dual_index import DualIndex
    from hypervideo.retrieval.hierarchical_retriever import HierarchicalRetriever

    hyper_vg.working_dir = new_working_dir
    os.makedirs(new_working_dir, exist_ok=True)

    hyper_vg.video_segments = hyper_vg.key_string_value_json_storage_cls(
        namespace="video_segments", global_config=asdict(hyper_vg)
    )
    if hyper_vg.enable_llm_cache:
        hyper_vg.llm_response_cache = hyper_vg.key_string_value_json_storage_cls(
            namespace="llm_response_cache", global_config=asdict(hyper_vg)
        )
    hyper_vg.video_segment_feature_vdb = hyper_vg.vs_vector_db_storage_cls(
        namespace="video_segment_feature",
        global_config=asdict(hyper_vg),
        embedding_func=None,
    )

    async def _llm_wrapper(prompt: str) -> str:
        return await hyper_vg.llm.cheap_model_func(prompt)

    hyper_vg.hypergraph_builder = VideoHypergraphBuilder(
        llm_func=_llm_wrapper,
        embedding_func=hyper_vg.embedding_func,
        config=hyper_vg.hyper_config,
        working_dir=hyper_vg.working_dir,
    )
    hyper_vg.dual_index = DualIndex(
        embedding_func=hyper_vg.embedding_func,
        config=hyper_vg.hyper_config,
    )
    hyper_vg.retriever = HierarchicalRetriever(
        hypergraph=hyper_vg.hypergraph_builder.hypergraph,
        dual_index=hyper_vg.dual_index,
        config=hyper_vg.hyper_config,
    )
    hyper_vg.hypergraph_builder.load(new_working_dir)


def process_one_sample(
    sample_dir: str,
    hyper_vg: HyperVideoGraph,
    args,
    max_ts_lookup: Optional[Dict[str, int]] = None,
    qaware_lookup: Optional[Dict[str, List[Dict[str, str]]]] = None,
):
    sample_id = os.path.basename(sample_dir)
    working_dir = (
        f"{args.save_root}/{args.datasets_type}/{sample_id}_{args.caption_model_name}"
    )
    hypergraph_path = os.path.join(working_dir, "hypergraph.json")
    if os.path.exists(hypergraph_path):
        logger.info(f"跳过 {sample_id}(hypergraph.json 已存在)")
        return False

    video_path = os.path.join(sample_dir, "video.mp4")
    if not os.path.exists(video_path):
        logger.error(f"  视频不存在: {video_path}")
        return False

    # 计算 max_seconds: 从 sample_id 数字部分查 max_ts_lookup, 加 buffer
    max_seconds: Optional[float] = None
    sid_num = None
    m = re.search(r'sample_(\d+)', sample_id)
    if m:
        sid_num = m.group(1)
    if max_ts_lookup and sid_num is not None:
        mts = max_ts_lookup.get(sid_num)
        if mts is not None:
            max_seconds = float(mts) + float(args.max_ts_buffer_seconds)
            logger.info(
                f"  [max_ts] sample_{sid_num}: max(ts)={mts}s, "
                f"截断至 {max_seconds:.1f}s (buffer={args.max_ts_buffer_seconds}s)"
            )
        else:
            logger.warning(f"  [max_ts] sample_{sid_num} 不在 questions_real.json 中, 不截断")

    # ---- 问题感知模式: 把 sample 的所有问题 (含 options) 注入到 hyper_cfg.forward_questions
    # episode_segmenter / fact_extractor 会自动切到 _FORWARD prompt (走现有框架机制),
    # 同时构造 qaware_prefix 拼到 caption prompt 头部 (不改原 V2 prompt)。
    qaware_prefix: Optional[str] = None
    if getattr(args, "question_aware", False) and qaware_lookup and sid_num is not None:
        qs = qaware_lookup.get(sid_num) or []
        if qs:
            # 注入到 cfg, builder 在 _reset 时会把 forward_questions 传给 segmenter / fact_extractor
            hyper_vg.hyper_config.forward_questions = qs
            hyper_vg.hyper_config.forward_viewpoint = "third_person"
            # caption 前置块
            qb = _make_questions_block(qs)
            qaware_prefix = (
                "USER QUESTIONS (with options) the viewer will be asked about this video:\n"
                f"{qb}\n\n"
                "When describing frames below, prioritise visual evidence that helps "
                "answer these questions. Do NOT mention the questions or options in "
                "your captions; just describe what is visible, paying extra attention "
                "to details (objects, counts, colors, on-screen text, actions, "
                "spatial layout) relevant to the questions above."
            )
            logger.info(
                f"  [qaware] sample_{sid_num}: 注入 {len(qs)} 个 question 到 caption + fact prompt"
            )
        else:
            logger.warning(f"  [qaware] sample_{sid_num} 在 questions_real.json 中无问题, 退化到普通模式")
            hyper_vg.hyper_config.forward_questions = None
    else:
        # 通用模式: 清空 forward_questions, 走原 V2 prompt (与 question_aware=False 时行为一致)
        hyper_vg.hyper_config.forward_questions = None

    os.makedirs(working_dir, exist_ok=True)
    _reset_hyper_vg_working_dir(hyper_vg, working_dir)

    try:
        run_streaming_hyper_construction(
            hyper_vg=hyper_vg,
            video_path=video_path,
            sample_dir=sample_dir,
            interval_seconds=args.interval_seconds,
            window_frames=args.window_frames,
            max_new_tokens=args.max_new_tokens,
            day_num=1,
            frame_captions_out_path=os.path.join(working_dir, "frame_captions.json"),
            caption_mode=args.caption_mode,
            per_frame_concurrency=args.per_frame_concurrency,
            max_seconds=max_seconds,
            qaware_prefix=qaware_prefix,
        )
        return True
    except Exception as e:
        logger.error(f"  建图失败 {sample_id}: {e}")
        return False
    finally:
        clear_gpu_memory()


# ==================== CLI ====================

def main():
    parser = argparse.ArgumentParser(
        description="StreamingBench RTVU HyperVideo 建图(HyperMem 风格)"
    )
    parser.add_argument(
        "--rtvu_root", type=str,
        default="/mnt/tokyo-ai/gst/StreamingBench-/Real-Time_Visual_Understanding_videos",
        help="包含 sample_*/video.mp4 的目录。默认是完整版 (Real-Time_Visual_Understanding_videos), "
             "另一个目录 Real_Time_Visual_Understanding/ 里的视频是被截短的版本, "
             "对长视频 max(ts) 会越界, 不要用。",
    )
    parser.add_argument(
        "--save_root", type=str,
        default="/mnt/tokyo-ai/gst/GST_EGOSERVE/all_results",
    )
    parser.add_argument(
        "--caption_model_name", type=str, default="qwenvl_3_8b_instruct",
    )
    parser.add_argument("--datasets_type", type=str, default="streamingbench_rtvu_hyper_v2")
    parser.add_argument("--cuda", type=str, default="0")
    parser.add_argument("--interval_seconds", type=float, default=2.0)
    parser.add_argument("--window_frames", type=int, default=5)
    parser.add_argument("--max_new_tokens", type=int, default=2048)
    parser.add_argument(
        "--caption_mode", type=str, default="batch",
        choices=["batch", "per_frame"],
        help="caption 生成模式: batch=每 window 一次 VLM 调用 (默认); "
             "per_frame=每帧独立调用 (简化 prompt + 并发)",
    )
    parser.add_argument(
        "--per_frame_concurrency", type=int, default=5,
        help="caption_mode=per_frame 时的线程池并发度",
    )
    parser.add_argument(
        "--boundary_detection_mode", type=str, default="window",
        choices=["frame", "window", "window_binary"],
        help="V1 边界检测模式: frame=逐帧 probe; window=window + split_at_frame; "
             "window_binary=window 2 选 1。仅在 --pipeline_version=v1 时生效",
    )
    parser.add_argument(
        "--pipeline_version", type=str, default="v2",
        choices=["v1", "v2"],
        help=(
            "处理管线版本。"
            "v2 (默认): per_window 一次 VLM batch 出 5 个 2s caption + 整体 10s "
            "description, stream 边界检测每 10s 判一次, fact 按 episode 紧圈。"
            "v1: 使用 --caption_mode / --boundary_detection_mode 的旧路径。"
        ),
    )
    parser.add_argument(
        "--caption_granularity", type=str, default=None,
        choices=[None, "per_window", "per_frame", "window_batch"],
        help="显式指定 caption 粒度,会覆盖 --pipeline_version 推导出的默认值。"
             "一般用于做对照实验。",
    )
    parser.add_argument(
        "--boundary_strategy", type=str, default=None,
        choices=[None, "stream", "frame", "window", "window_binary"],
        help="显式指定边界策略,会覆盖 --pipeline_version 推导出的默认值。",
    )
    parser.add_argument(
        "--sample_ids", type=str, default=None,
        help="仅处理指定 sample id, 逗号分隔, 如 '1,2,3'",
    )
    parser.add_argument(
        "--questions_real_json", type=str,
        default="/mnt/tokyo-ai/gst/StreamingBench/src/data/questions_real.json",
        help="官方 questions_real.json 路径, 用于查每个 sample 的 max(time_stamp). "
             "传空字符串 '' 关闭 max_ts 截断, 走整段视频建图。",
    )
    parser.add_argument(
        "--max_ts_buffer_seconds", type=float, default=10.0,
        help="max(time_stamp) 之外再多建几秒 buffer (防止边界检测/检索吃边)",
    )
    parser.add_argument(
        "--question_aware", action="store_true",
        help="问题感知建图: 从 questions_real.json 取出 sample 的全部 5 个 question + options, "
             "注入到 caption prompt (前置 USER QUESTIONS 块) 和 fact_extractor / episode_summary "
             "(走现有 _FORWARD prompt + forward_questions cfg). 默认 False, 走通用建图。",
    )
    parser.add_argument(
        "--openai_api_key", type=str,
        default="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",
    )
    args = parser.parse_args()

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

    # 枚举 sample_* 目录
    all_samples = sorted(
        [
            os.path.join(args.rtvu_root, d)
            for d in os.listdir(args.rtvu_root)
            if d.startswith("sample_") and os.path.isdir(os.path.join(args.rtvu_root, d))
        ],
        key=lambda p: int(os.path.basename(p).split("_")[-1]),
    )
    logger.info(f"发现 {len(all_samples)} 个 sample")

    if args.sample_ids:
        wanted = {s.strip() for s in args.sample_ids.split(',') if s.strip()}
        all_samples = [
            p for p in all_samples
            if os.path.basename(p).split("_")[-1] in wanted
        ]
        logger.info(f"按 --sample_ids 过滤后剩余 {len(all_samples)} 条")

    unprocessed = []
    for p in all_samples:
        sid = os.path.basename(p)
        hg_path = os.path.join(
            args.save_root, args.datasets_type,
            f"{sid}_{args.caption_model_name}", "hypergraph.json",
        )
        if not os.path.exists(hg_path):
            unprocessed.append(p)
    skipped = len(all_samples) - len(unprocessed)
    if skipped > 0:
        logger.info(f"跳过已完成 {skipped} 条, 剩余 {len(unprocessed)} 条")
    if not unprocessed:
        logger.info("全部已处理完毕")
        return

    # 初始化 hyper_vg + caption model(仅一次)
    init_working_dir = os.path.join(
        args.save_root, args.datasets_type, f"_init_{args.caption_model_name}"
    )
    os.makedirs(init_working_dir, exist_ok=True)

    # ---- pipeline 版本推导 ----
    # v2 默认:per_window caption + stream boundary
    # v1 默认:走用户传入的 --caption_mode / --boundary_detection_mode
    if args.pipeline_version == "v2":
        cg_default = "per_window"
        bs_default = "stream"
    else:
        # v1:caption_granularity 映射自 caption_mode;boundary_strategy 映射自 boundary_detection_mode
        cg_default = "per_frame" if args.caption_mode == "per_frame" else "window_batch"
        bs_default = args.boundary_detection_mode

    # 用户可显式覆盖
    caption_granularity = args.caption_granularity or cg_default
    boundary_strategy = args.boundary_strategy or bs_default

    hyper_cfg = HyperVideoConfig(
        boundary_detection_mode=args.boundary_detection_mode,
        caption_mode=args.caption_mode,
        caption_granularity=caption_granularity,
        boundary_strategy=boundary_strategy,
    )
    logger.info(
        f"模式: pipeline_version={args.pipeline_version}, "
        f"caption_granularity={caption_granularity}, "
        f"boundary_strategy={boundary_strategy}, "
        f"(legacy: caption_mode={args.caption_mode}, "
        f"boundary_detection_mode={args.boundary_detection_mode})"
    )
    hyper_vg = HyperVideoGraph(
        working_dir=init_working_dir,
        llm=default_llm_config,
        hyper_config=hyper_cfg,
    )
    logger.info(f"加载 caption model: {args.caption_model_name}")
    hyper_vg.load_caption_model(args.caption_model_name)
    logger.info(f"HyperVideoGraph 初始化完成, stats={hyper_vg.hypergraph_builder.hypergraph.get_stats()}")

    # 加载 questions_real.json → max(time_stamp) per sample
    max_ts_lookup: Dict[str, int] = {}
    qaware_lookup: Dict[str, List[Dict[str, str]]] = {}
    if args.questions_real_json:
        max_ts_lookup = _load_max_ts_per_sample(args.questions_real_json)
        if args.question_aware:
            qaware_lookup = _load_questions_with_options_per_sample(args.questions_real_json)

    t_all = time.time()
    ok = 0
    for idx, sample_dir in enumerate(unprocessed):
        t0 = time.time()
        sid = os.path.basename(sample_dir)
        logger.info(f"[{idx+1}/{len(unprocessed)}] {sid}")
        try:
            did = process_one_sample(
                sample_dir, hyper_vg, args,
                max_ts_lookup=max_ts_lookup,
                qaware_lookup=qaware_lookup,
            )
            if did:
                ok += 1
        except Exception as e:
            logger.error(f"  样本 {sid} 处理异常: {e}")
            continue
        dt = time.time() - t0
        logger.info(f"[{idx+1}/{len(unprocessed)}] {sid} 耗时 {dt:.1f}s")

    total = time.time() - t_all
    logger.info(
        f"\n{'='*80}\n建图完成: 成功 {ok}/{len(unprocessed)}, "
        f"总耗时 {total:.1f}s ({total/60:.1f}min)\n{'='*80}"
    )


if __name__ == "__main__":
    main()