File size: 44,704 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
"""Forward / Proactive 推理脚本.

针对 OVO Forward (CRR/SSR/REC), StreamingBench Proactive Output, ESTP-Bench
三类"先问后答"数据集的推理。

核心流程:
  - 加载 forward_hyper_processing.py 已建好的 hypergraph (含 question-aware fact)
  - 对每个 test_info 时刻 t:
      1. 取所有 fact where t 在 fact.relevant_question_ids 内 + episode 截止 ≤ t
      2. 构造推理 prompt (含 question, prev_answers_history, recent_caption,
         relevant_facts)
      3. LLM 决策: answer / need_retrieval (一次检索机会)
      4. 如 retrieve, fact_only 模式补一次 fact, 再强制 answer
  - 输出按 OVO Forward 标准协议格式 (REC=数字, SSR=Yes/No, CRR=Yes/No)

Usage:
  cd VideoRAG-algorithm
  python -m hypervideo.forward_hyper_retrieval \\
      --data_path /mnt/tokyo-ai/gst/ovo-bench/data/ovo_bench_new.json \\
      --working_dir_root /mnt/tokyo-ai/gst/GST_EGOSERVE/all_results \\
      --datasets_type ovobench_forward_hyper \\
      --caption_model_name qwen_api \\
      --task_filter CRR,SSR,REC \\
      --output_path /mnt/tokyo-ai/gst/GST_EGOSERVE/all_results/forward_results.json
"""
from __future__ import annotations

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

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

from hypervideo.hyper_video_graph import HyperVideoGraph
from hypervideo.config import HyperVideoConfig
from hypervideo.types import parse_frame_time_to_seconds
# 复用 ovobench_hyper_retrieval 已构造好的 LLMConfig (含 embedding_func 等必填字段)
from hypervideo.ovobench_hyper_retrieval import gpt5_2_llm_config2 as gpt5_2_llm_config
from videorag._llm import LLMConfig


# ======================================================================
# Forward 推理 Prompt
# ======================================================================

FORWARD_INFER_PROMPT = """You are answering a streaming / proactive question about a video.

A user asked the question(s) BEFORE this moment. You are now at TIME =
{time_now} seconds (since video start). You can ONLY see information from
[video_start, NOW] — never assume future content.

QUESTION:
{question}

Task type: {task}
Task instruction: {task_description}

------------------------------------------------------------
PREVIOUS_ANSWERS for THIS question (chronological — your own past replies):
------------------------------------------------------------
{prev_answers_block}

------------------------------------------------------------
RECENT_FRAME_CAPTIONS (last {recent_seconds}s before NOW — PRIMARY signal):
------------------------------------------------------------
{recent_captions}

------------------------------------------------------------
RECENT_EPISODE_SUMMARIES (last {recent_eps_n} episodes — gives short-term
context of what just happened):
------------------------------------------------------------
{recent_episodes}

------------------------------------------------------------
RELEVANT_FACTS from hypergraph (filtered to this question's qid, full history
since video start; useful for cross-time reasoning):
------------------------------------------------------------
{relevant_facts}

------------------------------------------------------------
HOW TO ANSWER (per task)
------------------------------------------------------------

REC (counting): the count is monotonic non-decreasing.
  1. RE-COUNT FROM SCRATCH every time: scan RELEVANT_FACTS + RECENT_EPISODE_SUMMARIES +
     RECENT_FRAME_CAPTIONS for COMPLETED occurrences of EXACTLY the queried activity, list
     them mentally with their times, and output that total. Do NOT just increment your
     previous answer — an earlier over/under-count would then stick forever.
  2. STRICT counting rule: count an occurrence ONLY if the evidence clearly shows the exact
     queried action COMPLETED (not merely attempted / partially visible / a similar-looking
     action). When a candidate event is ambiguous, do NOT count it.
  3. PREVIOUS_ANSWERS is a sanity reference only: if your fresh recount differs from the last
     answer, trust the recount (evidence beats momentum); the count must never decrease, so
     take max(recount, last_answer) ONLY when you are confident both are grounded.

SSR (step-yes/no): is the named step happening AT TIME NOW (within the last
few seconds)?
  1. Look at RECENT_FRAME_CAPTIONS: do the latest frames show the step's
     described action?
  2. If yes → "Yes". If clearly a different action / no action → "No".
  3. PREVIOUS_ANSWERS provide step-progress hint (e.g. if previous step was
     already "Yes" 30s ago and is now finished, current step likely shifted).

CRR (clue-sufficient yes/no): does the recent footage near NOW provide enough
information to answer the user question?
  1. Look at RECENT_FRAME_CAPTIONS: do they directly show the entity / event /
     action mentioned in the question?
  2. Yes — "Yes". Otherwise "No".
  3. PREVIOUS_ANSWERS show whether earlier moments were already sufficient.

PROACTIVE / ACTIVE OUTPUT: trigger detection.
  1. Recent captions show the trigger condition met? → output the literal
     output template (e.g. "20") with decision=answer.
  2. Otherwise → "wait".

ESTP: best free-form answer matching the current state.
  - Use RECENT_FRAME_CAPTIONS as primary; refine the answer compared to
    PREVIOUS_ANSWERS as the visual state evolves.

------------------------------------------------------------
RETRIEVAL (rare — only when truly needed)
------------------------------------------------------------

Default: decision = "answer".

Use decision = "need_retrieval" ONLY when the question explicitly asks about
an earlier-time state ("where was X before I picked it", "when did Y first
appear") AND that information is NOT in PREVIOUS_ANSWERS, RECENT_CAPTIONS, or
RELEVANT_FACTS shown above. Otherwise just answer.

------------------------------------------------------------
Output JSON (STRICT):
------------------------------------------------------------

{{
  "decision": "answer" | "need_retrieval",
  "answer": "<formatted answer for the task: integer / Yes / No / output template / free text>",
  "retrieval_query": "<empty if decision=answer>",
  "reasoning": "<1-2 sentences citing the key recent caption / prev answer / fact>"
}}

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


FORWARD_INFER_FINAL_PROMPT = """You are giving the FINAL forward / proactive answer.
This is the last chance — output the answer.

QUESTION:
{question}

Task type: {task} ({task_description})
TIME = {time_now} seconds.

PREVIOUS_ANSWERS for THIS question:
{prev_answers_block}

ORIGINAL RELEVANT_FACTS:
{relevant_facts}

ADDITIONAL FACTS retrieved this round:
{retrieved_facts}

RECENT_FRAME_CAPTIONS:
{recent_captions}

You MUST output the answer in the format expected for the task type:
- REC: single integer.
- SSR: "Yes" or "No".
- CRR: "Yes" or "No".
- ESTP / Proactive: free-form text matching current visual state.

Output JSON (STRICT):
{{
  "answer": "<final answer>",
  "reasoning": "<1-2 sentences>"
}}

Output ONLY the JSON.
"""


TASK_DESCRIPTIONS = {
    "REC": "count how many times the activity has been completed since video start; output an integer.",
    "SSR": "decide whether the named step is currently being performed at TIME NOW; output Yes or No.",
    "CRR": "decide whether the recent frames near TIME NOW provide enough information to answer the user question; output Yes or No.",
    "Proactive Output": "if the trigger described in the question has been met, output the literal output template; otherwise output 'wait'.",
    "Active Output": "same as Proactive Output.",
    "ESTP": "give the best free-form answer matching the current visual state; the answer evolves over time.",
    "proassist": (
        "you are a proactive task-guidance assistant. At TIME NOW, given the recent visual state "
        "and the task knowledge (steps), decide what to say to the user — either point out the next "
        "step they should do, confirm progress, warn about a mistake/missing tool, or say 'wait' if "
        "no intervention is needed yet. Answer should be a short natural-language utterance."
    ),
}


# ======================================================================
# Helpers
# ======================================================================

def _parse_temporal_to_sec(s: str) -> Optional[float]:
    if not s:
        return None
    try:
        return parse_frame_time_to_seconds(s, "start")
    except Exception:
        return None


def _filter_facts_for_question(hyper_vg: HyperVideoGraph, qid: str, t_now_sec: float) -> List[dict]:
    """从 hypergraph 取所有 fact 满足:
    1. qid in fact.relevant_question_ids
    2. fact.temporal 解析到的秒数 ≤ t_now (相对视频起点)
    返回 [{content, temporal, spatial, time_sec}, ...] 按 time_sec 排序
    """
    out = []
    facts = hyper_vg.hypergraph_builder.hypergraph.facts
    DAY_BASE = 86400.0
    for f in facts.values():
        rqi = getattr(f, "relevant_question_ids", []) or []
        if qid not in rqi:
            continue
        t_abs = _parse_temporal_to_sec(getattr(f, "temporal", "") or "")
        if t_abs is None:
            continue
        t_rel = t_abs - DAY_BASE
        if t_rel > t_now_sec:
            continue
        out.append({
            "content": f.content,
            "temporal": f.temporal,
            "spatial": f.spatial or "",
            "time_sec": t_rel,
        })
    out.sort(key=lambda x: x["time_sec"])
    return out


def _format_facts(facts: List[dict]) -> str:
    if not facts:
        return "(no relevant facts so far)"
    return "\n".join(
        f"[{f['temporal']}] {f['content']}" + (f"  (loc: {f['spatial']})" if f['spatial'] else "")
        for f in facts
    )


def _get_recent_captions(all_frame_captions: List[dict], t_now_sec: float, k_seconds: float = 10.0) -> List[dict]:
    """从 frame_captions.json 取最近 k_seconds 内的 caption (相对视频起点的秒)。"""
    out = []
    for fc in all_frame_captions:
        ts = fc.get("time_span", "")
        t_abs = _parse_temporal_to_sec(ts)
        if t_abs is None:
            continue
        t_rel = t_abs - 86400.0
        if t_now_sec - k_seconds <= t_rel <= t_now_sec:
            out.append({"time_span": ts, "caption": fc.get("caption", ""), "time_sec": t_rel})
    return out


def _format_captions(caps: List[dict]) -> str:
    if not caps:
        return "(no recent frames)"
    return "\n".join(f"[{c['time_span']}] {c['caption']}" for c in caps)


def _get_recent_episodes(hyper_vg: HyperVideoGraph, t_now_sec: float, n: int = 3) -> List[dict]:
    """取截止 t_now 之前最近 n 个 episode 的 summary+description"""
    eps = []
    DAY_BASE = 86400.0
    for ep in hyper_vg.hypergraph_builder.hypergraph.episodes.values():
        end_sec = ep.end_seconds - DAY_BASE
        if end_sec > t_now_sec:
            continue
        eps.append(ep)
    eps.sort(key=lambda e: e.end_seconds)
    eps = eps[-n:]
    out = []
    for ep in eps:
        out.append({
            "time_span": ep.time_span,
            "subject": getattr(ep, "subject", "") or "",
            "summary": getattr(ep, "summary", "") or "",
            "description": (
                getattr(ep, "episode_description", None)
                or getattr(ep, "description", "")
                or ""
            ),
        })
    return out


def _format_episodes(eps: List[dict]) -> str:
    if not eps:
        return "(no completed episodes yet)"
    blocks = []
    for ep in eps:
        block = f"[{ep['time_span']}] {ep['subject']}"
        if ep["summary"]:
            block += f"\n  summary: {ep['summary']}"
        if ep["description"]:
            block += f"\n  description: {ep['description']}"
        blocks.append(block)
    return "\n\n".join(blocks)


def _format_prev_answers(prev: List[dict]) -> str:
    if not prev:
        return "(no previous answers)"
    return "\n".join(f"[t={p['time']:.1f}s] {p['answer']}" for p in prev)


def _parse_llm_json(response: str) -> Optional[dict]:
    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:
            try:
                # tolerant repair
                from json_repair import repair_json
                return json.loads(repair_json(m.group()))
            except Exception:
                pass
    return None


# ======================================================================
# Forward Agentic 多轮自主检索 (新增, 不影响上面的固定 pipeline)
# ======================================================================
#
# 设计原则 (对齐 merge2 在 OVO backward 上验证的规律):
#   - 固定喂底座: all_episode_summaries 骨架 + recent_frame_captions(最近N秒) +
#     relevant_facts(按 qid 过滤)。这些足以回答大多数 forward 主动响应题。
#   - over-retrieve 有害 (realtime 上反复验证): 当前画面/最近活动能答就直接答,
#     只在缺"具体历史细节"时才调 search。
#   - 工具集: get_recent_episodes + search_fact_only/episode_fact/hierarchical。
#     每轮 ≤1 工具; search 工具重复时 fallback 换一个; 最后一轮强制答。

FORWARD_AGENTIC_TOOLS_DOC = """\
You are answering a STREAMING / PROACTIVE question at a fixed moment in a video, using
a memory graph (Topic > Episode > Fact). You can ONLY see [video_start, NOW] — never the future.

You are ALWAYS given (below, as fixed context — NOT tool calls):
  - ALL_EPISODE_SUMMARIES: chronological skeleton of every episode up to NOW.
  - RECENT_FRAME_CAPTIONS: second-level captions of the last few seconds before NOW (PRIMARY signal).
  - RELEVANT_FACTS: hypergraph facts filtered to THIS question's id, full history since video start.

Tools (call AT MOST ONE per round, ONLY when a specific detail is genuinely missing):
  get_recent_episodes                            - full detail (summary+description) of the LAST few
        episodes before NOW. Use for "what just happened / recent activity" beyond the raw captions.
  search_fact_only(semantic_query, keywords)     - global search over atomic facts (precise detail).
  search_episode_fact(semantic_query, keywords)  - locate the scene first, then its facts.
  search_hierarchical(semantic_query, keywords)  - top-down topic->episode->fact (broad/vague).

PLAN THE QUERY for the search tools (do NOT copy the question verbatim):
  - semantic_query: ONE natural-language, event-level phrase capturing the concrete object / action /
    earlier-time state you are missing.
  - keywords: ONLY concrete, visually-groundable terms (objects / physical actions / spatial cues),
    comma-separated. No abstract/meta words, no full sentences.

Strategy (WHEN to retrieve — read carefully, OVER-RETRIEVING HURTS):
- The RECENT_FRAME_CAPTIONS + ALL_EPISODE_SUMMARIES + RELEVANT_FACTS ALREADY answer most forward
  questions. For "is the step happening NOW" (SSR), "do recent frames suffice" (CRR), proactive
  trigger detection, and "what am I doing now" — ANSWER DIRECTLY, do NOT call any search tool.
- REC (counting): rely on PREVIOUS_ANSWERS (latest count) + recent captions for NEW occurrences.
  Call a search tool ONLY to verify whether a borderline earlier event was already counted.
- Call a search tool ONLY when the question needs a SPECIFIC earlier-time detail (a particular
  object/name/count/"when did X first appear") that is genuinely missing from the context above."""


FORWARD_AGENTIC_ROUND_PROMPT = """\
You are answering a streaming / proactive question about a video at TIME = {time_now} seconds
(since video start). You can ONLY see information from [video_start, NOW].

{tools}

QUESTION:
{question}

Task type: {task}
Task instruction: {task_description}

============================================================
PREVIOUS_ANSWERS for THIS question (chronological — your own past replies)
============================================================
{prev_answers_block}

============================================================
ALL_EPISODE_SUMMARIES (chronological skeleton up to NOW)
============================================================
{all_eps}

============================================================
RECENT_FRAME_CAPTIONS (last {recent_seconds}s before NOW — PRIMARY signal)
============================================================
{recent_captions}

============================================================
RELEVANT_FACTS (filtered to this question's id, full history since video start)
============================================================
{relevant_facts}

============================================================
RETRIEVED_EVIDENCE (from your earlier tool calls this question-moment)
============================================================
{evidence}

ANSWER FORMAT (per task type):
- REC: a single integer (count is monotonic non-decreasing vs PREVIOUS_ANSWERS).
- SSR: "Yes" or "No" (is the named step happening AT NOW).
- CRR: "Yes" or "No" (do recent frames near NOW suffice to answer the user question).
- Proactive / Active Output: the literal output template if triggered, else "wait".
- ESTP / free-form: best free-form answer matching the current visual state.

Round {round}/{max_rounds}. Decide:
- If the context above already supports an answer — ESPECIALLY for SSR / CRR / proactive / "current
  state" questions — ANSWER NOW. Do NOT retrieve just to be safe; over-retrieval makes it WORSE.
- Retrieve ONLY when a specific earlier-time detail you need is genuinely missing.
- output to gather: {{"action":"tools","calls":[{{"tool":"<name>","args":{{...}}}}]}}
    search_* args: {{"semantic_query":"...","keywords":"..."}} ; get_recent_episodes args: {{}}
- output to answer: {{"action":"answer","answer":"<formatted answer for the task>","reasoning":"<one sentence>"}}
- On the FINAL round you MUST output action=answer.
Output STRICT JSON only."""


_FWD_SEARCH_TOOLS = {"search_fact_only", "search_episode_fact", "search_hierarchical"}
# 统一工具集(2026-06-25): episodes=摘要, captions=秒级帧, 跨 solver 语义一致。
_FWD_RECENT_TOOLS = {"get_recent_episodes", "get_recent_captions"}
_FWD_ALL_TOOLS = _FWD_SEARCH_TOOLS | _FWD_RECENT_TOOLS

# agentic2 (2026-07-17): + 通道B。search_entities 进工具集; 当下感知窗固定注入。
_FWD2_ALL_TOOLS = _FWD_ALL_TOOLS | {"search_entities"}

FORWARD_AGENTIC2_TOOLS_ADDON = """
  search_entities(keywords)  - point-lookup over a structured per-moment perception log of the
        WHOLE video so far: object inventory ("[time] Nx object [attributes] @location"),
        on-screen TEXT, and atomic events at EARLIER moments. For REC counting, this log lists
        past occurrences of the activity directly — search it with the activity's concrete
        object/action terms to count or verify past events; also good for a concrete object's
        earlier location/count/colour or exact on-screen text. keywords = concrete terms."""

FORWARD_AGENTIC2_SP_HEADER = ("\n\nSTRUCTURED_PERCEPTION (same recent moment, machine-extracted "
                              "object/text/event log — exact counts, attributes, on-screen text):\n")


def _t_now_to_time_span(t_now_sec: float) -> str:
    """t_now(相对视频起点的秒)-> '1-HH:MM:SS-HH:MM:SS' (start=end=t_now)。
    HyperToolBank / retrieve 都用 which='end' 解析, 得到 cutoff = t_now + 86400 (DAY1 基准)。
    """
    s = int(max(0, t_now_sec))
    hms = f"{s // 3600:02d}:{(s % 3600) // 60:02d}:{s % 60:02d}"
    return f"1-{hms}-{hms}"


async def _fwd_dispatch(bank, tool: str, args: dict, question: str) -> str:
    """把 LLM 选的工具 dispatch 到 HyperToolBank (统一工具集, 仿 merge2._dispatch)。"""
    if tool == "get_recent_episodes":
        return bank.get_recent_episodes()   # episode 级 summary+description
    if tool == "get_recent_captions":
        return bank.get_recent_captions()   # 秒级帧 caption(当前画面)
    sq = args.get("semantic_query") or args.get("query") or question
    kw = args.get("keywords", "") or ""
    if tool == "search_entities":
        return bank.search_entities(keywords=kw, semantic_query=sq)   # 通道B点查(同步)
    if tool in _FWD_SEARCH_TOOLS:
        return await getattr(bank, tool)(sq, kw)
    return f"[unknown tool {tool}]"


async def agentic_forward_answer(
    question: str,
    qid: str,
    t_now: float,
    hyper_vg: HyperVideoGraph,
    all_frame_captions: List[dict],
    llm_config: LLMConfig,
    task: str,
    prev_answers: List[dict],
    max_rounds: int = 3,
    recent_seconds: float = 10.0,
    recent_eps_n: int = 3,
    use_cb: bool = False,
) -> dict:
    """对单个 forward 时刻 t_now 做 agentic ORA loop (仿 merge2.agentic_answer)。
    use_cb=True (agentic2, 2026-07-17): 通道B当下感知注入 RECENT_FRAME_CAPTIONS 块 +
    search_entities 进工具集(REC 计数/CRR 物体验证, OVO realtime/HLD 已验证的两招)。

    每轮: 构造 prompt(底座 + 已收集 evidence) -> LLM 决策 {action: tools|answer} ->
    若 answer 或最后一轮则返回; 否则每轮 ≤1 工具, dispatch 到 HyperToolBank,
    search 工具重复时 fallback 换一个未用过的 mode。

    Returns dict, 字段与固定 pipeline 的 results.append 对齐:
        {answer, reasoning, tools_used, rounds, decision, retrieved, n_relevant_facts}
    """
    from hypervideo.agentic_tools import HyperToolBank

    task_desc = TASK_DESCRIPTIONS.get(task, task)

    # ---- 固定底座 ----
    relevant_facts = _filter_facts_for_question(hyper_vg, qid, t_now)
    recent_caps = _get_recent_captions(all_frame_captions, t_now, recent_seconds)
    relevant_facts_text = _format_facts(relevant_facts)
    recent_captions_text = _format_captions(recent_caps)
    prev_block = _format_prev_answers(prev_answers)

    # HyperToolBank: 用 3-part time_span, which='end' 得到 cutoff = t_now
    ts = _t_now_to_time_span(t_now)
    bank = HyperToolBank(hyper_vg, current_time_span=ts)
    all_eps_text, _nearby = bank.build_baseline_context()

    # agentic2: 通道B当下感知固定注入 + search_entities 工具
    tools_doc = FORWARD_AGENTIC_TOOLS_DOC
    allowed_tools = _FWD_ALL_TOOLS
    if use_cb:
        tools_doc = FORWARD_AGENTIC_TOOLS_DOC + FORWARD_AGENTIC2_TOOLS_ADDON
        allowed_tools = _FWD2_ALL_TOOLS
        try:
            _sp = bank.get_current_perception(last_sec=recent_seconds + 2.0)
        except Exception:
            _sp = ""
        if _sp:
            recent_captions_text = recent_captions_text + FORWARD_AGENTIC2_SP_HEADER + _sp

    evidence_blocks: List[str] = []
    history: List[str] = []

    for rnd in range(1, max_rounds + 1):
        ev = "\n\n".join(evidence_blocks) or "(none yet — answer from the context above, or use a tool)"
        prompt = FORWARD_AGENTIC_ROUND_PROMPT.format(
            tools=tools_doc,
            time_now=f"{t_now:.1f}",
            question=question,
            task=task,
            task_description=task_desc,
            prev_answers_block=prev_block,
            all_eps=all_eps_text[:10000],
            recent_seconds=int(recent_seconds),
            recent_captions=recent_captions_text,
            relevant_facts=relevant_facts_text[:6000],
            evidence=ev[:8000],
            round=rnd,
            max_rounds=max_rounds,
        )
        used = [t for t in history if t in _FWD_SEARCH_TOOLS]
        if used:
            prompt += f"\n(You already searched: {sorted(set(used))}. If searching again, pick a DIFFERENT mode.)"
        force = (rnd == max_rounds)
        if force:
            prompt += "\nThis is the FINAL round — you MUST output action=answer."

        try:
            resp = await llm_config.best_model_func_raw(
                llm_config.best_model_name, prompt, system_prompt=None, history_messages=[]
            )
        except Exception as e:
            logger.error(f"  [agentic] LLM 调用失败 t={t_now} rnd={rnd}: {e}")
            return {
                "answer": "", "reasoning": str(e), "tools_used": history, "rounds": rnd,
                "decision": "answer", "retrieved": bool(evidence_blocks),
                "n_relevant_facts": len(relevant_facts),
            }

        d = _parse_llm_json(resp or "") or {}
        if d.get("action") == "answer" or force:
            return {
                "answer": str(d.get("answer", "") or ""),
                "reasoning": d.get("reasoning", ""),
                "tools_used": history,
                "rounds": rnd,
                "decision": ("need_retrieval" if history else "answer"),
                "retrieved": bool(evidence_blocks),
                "n_relevant_facts": len(relevant_facts),
            }

        # 每轮 ≤1 工具 (calls[:1])
        for call in (d.get("calls") or [])[:1]:
            tool = call.get("tool", "")
            if tool not in allowed_tools:
                continue
            # search 工具重复 -> fallback 换一个没用过的 mode
            if tool in _FWD_SEARCH_TOOLS and tool in history:
                alt = [t for t in _FWD_SEARCH_TOOLS if t not in history]
                if alt:
                    tool = alt[0]
            try:
                obs = await _fwd_dispatch(bank, tool, call.get("args", {}) or {}, question)
            except Exception as e:
                obs = f"[{tool} error: {e}]"
            evidence_blocks.append(f"### {tool} ->\n{str(obs)[:2500]}")
            history.append(tool)

    # 理论上不可达 (最后一轮 force return)
    return {
        "answer": "", "reasoning": "no answer", "tools_used": history, "rounds": max_rounds,
        "decision": "answer", "retrieved": bool(evidence_blocks),
        "n_relevant_facts": len(relevant_facts),
    }


def infer_one_question_stream_agentic(
    video_data: dict,
    hyper_vg: HyperVideoGraph,
    all_frame_captions: List[dict],
    qid: str,
    question: str,
    test_info: List[dict],
    task: str,
    llm_config: LLMConfig,
    recent_seconds: float = 10.0,
    recent_eps_n: int = 3,
    max_rounds: int = 3,
    use_cb: bool = False,
) -> List[dict]:
    """agentic 版的流式推理: 对每个 test_info 时刻调 agentic_forward_answer, 维护 prev_answers。
    返回结构与 infer_one_question_stream 一致。
    """
    prev_answers: List[dict] = []
    results: List[dict] = []

    for ti in test_info:
        t_now = float(ti.get("realtime", 0))
        out = asyncio.run(agentic_forward_answer(
            question=question,
            qid=qid,
            t_now=t_now,
            hyper_vg=hyper_vg,
            all_frame_captions=all_frame_captions,
            llm_config=llm_config,
            task=task,
            prev_answers=prev_answers,
            max_rounds=max_rounds,
            recent_seconds=recent_seconds,
            recent_eps_n=recent_eps_n,
            use_cb=use_cb,
        ))
        ans = str(out.get("answer", "") or "")
        prev_answers.append({"time": t_now, "answer": ans})

        results.append({
            "realtime": t_now,
            "answer": ans,
            "decision": out.get("decision", "answer"),
            "reasoning": out.get("reasoning", ""),
            "retrieved": out.get("retrieved", False),
            "n_relevant_facts": out.get("n_relevant_facts", 0),
            "tools_used": out.get("tools_used", []),
            "rounds": out.get("rounds", 0),
        })

    return results


# ======================================================================
# 单 question 推理 (流式 test_info)
# ======================================================================

def infer_one_question_stream(
    video_data: dict,
    hyper_vg: HyperVideoGraph,
    all_frame_captions: List[dict],
    qid: str,
    question: str,
    test_info: List[dict],
    task: str,
    llm_config: LLMConfig,
    recent_seconds: float = 10.0,
    recent_eps_n: int = 3,
    enable_retrieval: bool = True,
) -> List[dict]:
    """对一个 question 流式推理所有 test_info 时刻, 维护 prev_answers 上下文。

    Returns: 每个 test_info 时刻的结果列表
        [{realtime, answer, decision, reasoning, retrieved}, ...]
    """
    prev_answers: List[dict] = []  # [{time, answer}, ...]
    results: List[dict] = []

    task_desc = TASK_DESCRIPTIONS.get(task, task)

    for ti in test_info:
        t_now = float(ti.get("realtime", 0))

        # ---- 取上下文 ----
        relevant_facts = _filter_facts_for_question(hyper_vg, qid, t_now)
        recent_caps = _get_recent_captions(all_frame_captions, t_now, recent_seconds)
        recent_eps = _get_recent_episodes(hyper_vg, t_now, recent_eps_n)

        prompt = FORWARD_INFER_PROMPT.format(
            time_now=f"{t_now:.1f}",
            question=question,
            task=task,
            task_description=task_desc,
            prev_answers_block=_format_prev_answers(prev_answers),
            relevant_facts=_format_facts(relevant_facts),
            recent_seconds=int(recent_seconds),
            recent_captions=_format_captions(recent_caps),
            recent_eps_n=recent_eps_n,
            recent_episodes=_format_episodes(recent_eps),
        )

        try:
            response = asyncio.run(llm_config.best_model_func_raw(
                llm_config.best_model_name,
                prompt,
                system_prompt=None,
                history_messages=[],
            ))
            decision = _parse_llm_json(response) if isinstance(response, str) else response
            if decision is None:
                decision = {"decision": "answer", "answer": "", "reasoning": f"parse fail: {response}"}
        except Exception as e:
            logger.error(f"  LLM 调用失败 t={t_now}: {e}")
            decision = {"decision": "answer", "answer": "", "reasoning": str(e)}

        d = (decision.get("decision") or "answer").lower()
        retrieved_text = ""

        if d == "need_retrieval" and enable_retrieval:
            rq = decision.get("retrieval_query") or question
            try:
                cutoff_ts = f"DAY1-{int(t_now//3600):02d}:{int((t_now%3600)//60):02d}:{int(t_now%60):02d}"
                ret_result = asyncio.run(hyper_vg.retrieve(rq, cutoff_ts, mode="fact_only"))
                retrieved_text = hyper_vg.format_retrieval_for_llm(ret_result)
            except Exception as e:
                retrieved_text = f"(retrieval error: {e})"

            # 强制最终答
            final_prompt = FORWARD_INFER_FINAL_PROMPT.format(
                question=question,
                task=task,
                task_description=task_desc,
                time_now=f"{t_now:.1f}",
                prev_answers_block=_format_prev_answers(prev_answers),
                relevant_facts=_format_facts(relevant_facts),
                retrieved_facts=retrieved_text or "(retrieval returned nothing)",
                recent_captions=_format_captions(recent_caps),
            )
            try:
                response2 = asyncio.run(llm_config.best_model_func_raw(
                    llm_config.best_model_name,
                    final_prompt,
                    system_prompt=None,
                    history_messages=[],
                ))
                final_dec = _parse_llm_json(response2) if isinstance(response2, str) else response2
                if final_dec is None:
                    final_dec = {"answer": decision.get("answer", ""), "reasoning": "final parse fail"}
                decision["answer"] = final_dec.get("answer", decision.get("answer", ""))
                decision["reasoning"] = final_dec.get("reasoning", decision.get("reasoning", ""))
            except Exception as e:
                logger.error(f"  final LLM 调用失败: {e}")

        ans = str(decision.get("answer", "") or "")
        prev_answers.append({"time": t_now, "answer": ans})

        results.append({
            "realtime": t_now,
            "answer": ans,
            "decision": d,
            "reasoning": decision.get("reasoning", ""),
            "retrieved": bool(retrieved_text),
            "n_relevant_facts": len(relevant_facts),
        })

    return results


# ======================================================================
# 单视频处理
# ======================================================================

def process_one_video(video_data: dict, args) -> Optional[dict]:
    vid = video_data["id"]
    task = video_data.get("task", "?")
    working_dir = (
        f"{args.working_dir_root}/{args.datasets_type}/{vid}_{args.caption_model_name}"
    )
    if not os.path.isdir(working_dir):
        # SB Proactive(2026-07-17): 题目id形如 "Active Output_sample_1_3", 图按视频级
        # "sample_1_qwen_api" 命名(一个sample一张图, 多题共享)。提取 sample_N 回退。
        m = re.search(r"(sample_\d+)", str(vid))
        if m:
            alt = f"{args.working_dir_root}/{args.datasets_type}/{m.group(1)}_{args.caption_model_name}"
            if os.path.isdir(alt):
                working_dir = alt
    if not os.path.isdir(working_dir):
        logger.warning(f"  Working dir 不存在: {working_dir}")
        return {"id": vid, "task": task, "error": "working_dir_not_found"}

    hp_path = os.path.join(working_dir, "hypergraph.json")
    if not os.path.exists(hp_path):
        return {"id": vid, "task": task, "error": "hypergraph_not_found"}

    fc_path = os.path.join(working_dir, "frame_captions.json")
    if not os.path.exists(fc_path):
        return {"id": vid, "task": task, "error": "frame_captions_not_found"}

    with open(fc_path, "r", encoding="utf-8") as f:
        fc_data = json.load(f)
    all_frame_captions = fc_data.get("frame_captions", [])

    # forward 模式 cfg (传 propagation_mode 让 dual_index 用对应方式做嵌入传播)
    hyper_cfg = HyperVideoConfig(
        dataset_mode="forward",
        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=gpt5_2_llm_config, hyper_config=hyper_cfg)
    stats = hyper_vg.hypergraph_builder.hypergraph.get_stats()
    logger.info(f"  [{vid}] task={task}, hyper_stats={stats}")

    # 重建 question (forward 数据集独有)
    from hypervideo.forward_hyper_processing import build_forward_questions
    forward_qs, viewpoint = build_forward_questions(video_data)
    if not forward_qs:
        return {"id": vid, "task": task, "error": "no_question"}

    test_info = video_data.get("test_info", [])
    if not test_info:
        return {"id": vid, "task": task, "error": "no_test_info"}

    # 多 question (SSR 可能多 step) 不在这里, 单 question 直接拿 forward_qs[0]
    qid = forward_qs[0]["qid"]
    question_text = forward_qs[0]["question"]

    # ---- solver 分流: fixed (固定 pipeline, 默认) vs agentic (多轮自主检索) ----
    solver = getattr(args, "solver", "fixed")
    max_rounds = getattr(args, "max_rounds", 3)

    def _run_stream(_qid, _question, _test_info, _task):
        """按 args.solver 选择固定/agentic 流式推理, 返回同结构 results。"""
        if solver in ("agentic", "agentic2"):
            return infer_one_question_stream_agentic(
                video_data=video_data,
                hyper_vg=hyper_vg,
                all_frame_captions=all_frame_captions,
                qid=_qid,
                question=_question,
                test_info=_test_info,
                task=_task,
                llm_config=gpt5_2_llm_config,
                max_rounds=max_rounds,
                use_cb=(solver == "agentic2"),
            )
        return infer_one_question_stream(
            video_data=video_data,
            hyper_vg=hyper_vg,
            all_frame_captions=all_frame_captions,
            qid=_qid,
            question=_question,
            test_info=_test_info,
            task=_task,
            llm_config=gpt5_2_llm_config,
        )

    # SSR: question 是按 step 走的,每个 test_info 自己的 step
    if task == "SSR":
        # 每个 test_info 一个 step, 把 step 作为 question
        per_ti_results = []
        for ti in test_info:
            step = ti.get("step", "")
            step_q = f"Is the person currently performing the step '{step}'?"
            sub_results = _run_stream(qid, step_q, [ti], "SSR")
            for r in sub_results:
                r["step"] = step
                r["type"] = ti.get("type")
            per_ti_results.extend(sub_results)
        results_per_qid = {qid: per_ti_results}
    else:
        # CRR / REC 单 question 流式
        results_per_qid = {}
        per_ti_results = _run_stream(qid, question_text, test_info, task)
        for i, r in enumerate(per_ti_results):
            ti = test_info[i]
            r["type"] = ti.get("type") if "type" in ti else None
            r["count"] = ti.get("count") if "count" in ti else None
        results_per_qid[qid] = per_ti_results

    return {
        "id": vid,
        "task": task,
        "question": question_text,
        "test_info": test_info,
        "results_per_qid": results_per_qid,
    }


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

def main():
    parser = argparse.ArgumentParser(
        description="Forward / Proactive 推理 (基于 question-aware hypergraph)"
    )
    parser.add_argument(
        "--data_path", type=str,
        default="/mnt/tokyo-ai/gst/ovo-bench/data/ovo_bench_new.json",
    )
    parser.add_argument(
        "--working_dir_root", type=str,
        default="/mnt/tokyo-ai/gst/GST_EGOSERVE/hyper_video_results",
    )
    parser.add_argument(
        "--datasets_type", type=str,
        default="ovobench_forward_hyper",
    )
    parser.add_argument(
        "--caption_model_name", type=str, default="qwen_api",
    )
    parser.add_argument(
        "--task_filter", type=str, default="CRR,SSR,REC",
        help="只跑指定 task 类型, 逗号分隔",
    )
    parser.add_argument(
        "--only_ids", type=str, default=None,
    )
    parser.add_argument(
        "--output_path", type=str,
        default="/mnt/tokyo-ai/gst/GST_EGOSERVE/all_results/ovobench_forward_results.json",
    )
    parser.add_argument(
        "--dataset", type=str, default="ovo_forward",
        choices=["ovo_forward", "streamingbench_proactive", "estp"],
    )
    parser.add_argument(
        "--proactive_dir", type=str,
        default="/mnt/tokyo-ai/gst/StreamingBench/Proactive_Output",
    )
    parser.add_argument(
        "--estp_video_dir", type=str,
        default="/mnt/tokyo-ai/gst/ESTP-IT/ESTP-Bench/full_scale_2fps_max384",
    )
    parser.add_argument(
        "--proassist_data", type=str,
        default="/mnt/tokyo-ai/gst/ProAssist/processed_data/ego4d/prepared/dialog-klg_test_L0_I1.jsonl",
    )
    parser.add_argument(
        "--proassist_video_root", type=str,
        default="/mnt/tokyo-ai/gst/ESTP-IT/ESTP-Bench/full_scale_2fps_max384",
    )
    parser.add_argument(
        "--video_dir", type=str,
        default="/mnt/tokyo-ai/gst/OVO-Bench/chunked_videos",
    )
    parser.add_argument("--cuda", type=str, default="0")
    parser.add_argument(
        '--answer_model', type=str, default='gpt-4.1-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,
    )
    parser.add_argument(
        '--solver', type=str, default='fixed', choices=['fixed', 'agentic', 'agentic2'],
        help="推理方式: fixed (默认) / agentic (多轮自主检索) / agentic2 (+通道B当下感知与search_entities, 2026-07-17)",
    )
    parser.add_argument(
        '--max_rounds', type=int, default=3,
        help="agentic solver 的最大轮数 (仅 --solver agentic 生效)",
    )
    parser.add_argument(
        '--limit', type=int, default=None,
        help="只跑前 N 条样本 (dry-run 用)",
    )
    args = parser.parse_args()

    # 应用 model + propagation 到 imported config + env (HyperVideoConfig 创建时读)
    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)
    gpt5_2_llm_config.best_model_name = args.answer_model
    logger.info(f"[args] answer_model={args.answer_model} propagation_mode={args.propagation_mode} lambda={args.propagation_lambda} solver={args.solver} max_rounds={args.max_rounds}")

    os.environ["CUDA_VISIBLE_DEVICES"] = args.cuda
    # 从 .env 加载 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")

    from hypervideo.forward_dataset_loaders import (
        load_ovo_forward,
        load_streamingbench_proactive,
        load_estp_bench,
        load_proassist,
    )
    if args.dataset == "ovo_forward":
        all_data = load_ovo_forward(
            data_path=args.data_path,
            video_dir=args.video_dir,
            task_filter=(args.task_filter.split(",") if args.task_filter else None),
        )
    elif args.dataset == "streamingbench_proactive":
        all_data = load_streamingbench_proactive(proactive_dir=args.proactive_dir)
    elif args.dataset == "estp":
        all_data = load_estp_bench(data_path=args.data_path, video_dir=args.estp_video_dir)
    elif args.dataset == "proassist":
        all_data = load_proassist(
            data_path=args.proassist_data,
            video_root=args.proassist_video_root,
        )
    else:
        raise ValueError(f"未知 dataset: {args.dataset}")

    logger.info(f"加载 {len(all_data)} 条 forward 样本 (dataset={args.dataset})")

    if args.only_ids:
        wanted = {s.strip() for s in args.only_ids.split(",") if s.strip()}
        all_data = [d for d in all_data if str(d["id"]) in wanted]
        logger.info(f"按 only_ids 过滤剩 {len(all_data)} 条")

    if args.limit is not None:
        all_data = all_data[:args.limit]
        logger.info(f"按 --limit 截断到 {len(all_data)} 条")

    out: Dict[str, dict] = {}
    if os.path.exists(args.output_path):
        try:
            with open(args.output_path, "r", encoding="utf-8") as f:
                out = json.load(f)
            logger.info(f"加载已有结果: {len(out)} 条")
        except Exception:
            out = {}

    t_all = time.time()
    for idx, video_data in enumerate(all_data):
        vid_str = str(video_data["id"])
        if vid_str in out and "error" not in out[vid_str]:
            logger.info(f"[{idx+1}/{len(all_data)}] id={vid_str} 已完成, 跳过")
            continue
        t0 = time.time()
        logger.info(f"[{idx+1}/{len(all_data)}] id={vid_str} task={video_data.get('task')}")
        try:
            res = process_one_video(video_data, args)
            if res:
                out[vid_str] = res
        except Exception as e:
            logger.error(f"  failed: {e}")
            out[vid_str] = {"id": vid_str, "task": video_data.get("task"), "error": str(e)}
        dt = time.time() - t0
        logger.info(f"  done in {dt:.1f}s")

        if (idx + 1) % 5 == 0:
            with open(args.output_path, "w", encoding="utf-8") as f:
                json.dump(out, f, ensure_ascii=False, indent=2)

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

    total = time.time() - t_all
    logger.info(f"\n完成 {len(out)} 条, 总耗时 {total:.1f}s ({total/60:.1f}min)")


if __name__ == "__main__":
    main()