"""StreamingBench JSON 协议下的统一推理脚本. 支持三个子任务: - SQA : 4 选 1 MCQ, 同视频 5 个 question 顺序串联 (oracle history) - Contextual MCU : 4 选 1 MCQ (Misleading) - Contextual ACU : 4 选 1 MCQ (Anomaly) - Proactive PO : 1s grid 流式 yes/no 触发检测 公共逻辑 (对齐 OVO-Bench Forward): - 每个 sample (= 1 video) 已建好 hypergraph - 每个 question 按 q.time_stamp_sec 严格截断 hypergraph: fact / episode 必须 end ≤ ts - 不切视频 (方案 A: 建图阶段 max_seconds 早停) - 推理时 LLM 看到的全是 ts 之前的事实, 绝不泄漏未来 OPENAI_API_KEY 必须由调用方提供. """ from __future__ import annotations import argparse import asyncio import json import logging import os import re import sys import time from typing import Dict, List, Optional, Tuple sys.path.insert(0, "/mnt/tokyo-ai/gst/GST_EGOSERVE/VideoRAG-algorithm") # import ovobench 之前先尝试复用其 hardcoded key (ovobench main() 会在自身入口设置, # 但作为 module import 时不会触发 main; 这里给一个 fallback 让 import 期不要 raise). # 实际 OPENAI key 校验放到 main() 入口. from hypervideo.ovobench_hyper_retrieval import gpt5_2_llm_config2 # noqa: E402 from hypervideo.forward_dataset_loaders import ( # noqa: E402 load_streamingbench_sqa_json, load_streamingbench_proactive_json, load_streamingbench_contextual_json, ) logger = logging.getLogger("sb_eval") logging.basicConfig(level=logging.INFO, format="%(asctime)s | %(levelname)s | %(message)s") # ====================================================================== # 时间解析 / hypergraph 截断 # ====================================================================== def _parse_temporal_to_sec(s: str) -> float: """fact.temporal 形如 'DAY1-00:00:12' / '1-00:00:12' / 'HH:MM:SS' → 相对视频起点的秒. 我们 hypergraph 里 day_num=1, start_seconds=0 起点. """ if not s: return 0.0 m = re.search(r"(\d+):(\d+):(\d+)(?:\.(\d+))?", s) if not m: return 0.0 h, mn, sc = int(m.group(1)), int(m.group(2)), int(m.group(3)) frac = float(f"0.{m.group(4)}") if m.group(4) else 0.0 return h * 3600 + mn * 60 + sc + frac def _truncate_hypergraph(hg: dict, t_cutoff_sec: float) -> Tuple[List[dict], List[dict]]: """按 t_cutoff_sec 严格截断 hypergraph (绝不泄漏未来): - episode: 必须 end_seconds ≤ t_cutoff (完整结束在 ts 之前才进 prompt) episode 跨越 ts 的话直接丢弃 — 用 frame_caption 补足 [last_ep_end, ts] 边界信息 - fact: temporal_sec ≤ t_cutoff 注: 因为我们建图时已经早停 (max_seconds = max(q.ts)), 同一 sample 多个 q 共享一张超图. q.ts < max_seconds 时, hypergraph 里会有 ts 之后的 fact —— 必须 在这里严格过滤. """ eps = [] for ep in hg.get("episodes", {}).values(): start = ep.get("start_seconds", 0.0) end = ep.get("end_seconds", start + 1) if end <= t_cutoff_sec + 1e-6: eps.append(ep) # 跨越 ts 或完全在 ts 之后 → 跳过 eps.sort(key=lambda x: x.get("start_seconds", 0.0)) facts = [] for f in hg.get("facts", {}).values(): t = _parse_temporal_to_sec(f.get("temporal", "")) if t <= t_cutoff_sec + 1e-6: facts.append((t, f)) facts.sort(key=lambda x: x[0]) return eps, [f for _, f in facts] def _filter_frame_captions( all_captions: List[dict], t_cutoff_sec: float, last_ep_end_sec: float = 0.0, max_seconds_back: float = 30.0, ) -> List[dict]: """从 frame_captions.json 取边界 caption: [max(last_ep_end, ts - max_seconds_back), ts]. 用途: episode 严格截断到 last_ep_end (≤ ts), 之后到 ts 之间的视觉信息靠 frame_caption 补足 (类似 OVO-Bench 直接用 frame_caption 的做法). """ out = [] lower = max(last_ep_end_sec, t_cutoff_sec - max_seconds_back) for fc in all_captions: ts = fc.get("time_span", "") # time_span 形如 "1-00:00:10-00:00:12" 或 "DAY1-..." # 用结尾时间判断 # 简化: 取最后一个 H:MM:SS 当 caption 结束时间 all_t = re.findall(r"(\d+):(\d+):(\d+)", ts) if not all_t: continue last = all_t[-1] cap_end = int(last[0]) * 3600 + int(last[1]) * 60 + int(last[2]) if lower <= cap_end <= t_cutoff_sec + 1e-6: out.append(fc) return out def _format_frame_captions(caps: List[dict], max_each: int = 250) -> str: if not caps: return "(no recent frame captions)" lines = [] for c in caps[-15:]: # 最多 15 条避免过长 cap = c.get("caption") or c.get("dense_caption") or c.get("description", "") lines.append(f"[{c.get('time_span','?')}] {str(cap)[:max_each]}") return "\n".join(lines) def _format_episodes(eps: List[dict], max_each_desc: int = 600) -> str: if not eps: return "(no completed episodes yet)" out = [] for ep in eps: out.append( f"[{ep.get('time_span','?')}] {ep.get('subject','')[:80]}\n" f" summary: {(ep.get('summary','') or '')[:300]}\n" f" description: {(ep.get('episode_description','') or '')[:max_each_desc]}" ) return "\n".join(out) def _format_facts(facts: List[dict], max_each: int = 200) -> str: if not facts: return "(no facts)" return "\n".join( f"[{f.get('temporal','?')}] {f.get('content','')[:max_each]}" for f in facts ) def _parse_json_response(r) -> Optional[dict]: if not r: return None if isinstance(r, dict): return r s = str(r) m = re.search(r"\{.*\}", s, re.DOTALL) if m: try: return json.loads(m.group()) except Exception: pass return None # ====================================================================== # Prompt 模板 # ====================================================================== # 三种推理 mode: # dump_all : episode 全 (≤ ts) + fact 全 (≤ ts) + boundary frame_captions, 单次答 # ep_retrieve: 只给 episode 全 + boundary captions, 让 LLM 自行决定是否检索 (1次机会) # agentic : 同上但 prompt 风格更"自主" — 鼓励 LLM 必要时再检索, 对 fact 用 hierarchical 检索 # # 共同基础: episode 严格 end ≤ ts, frame_caption 补 [last_ep_end, ts] 边界 MCQ_PROMPT_DUMP_ALL = """You are answering a multi-choice question about a third-person video. The question is asked at TIME = {qtime} (absolute video time). You can ONLY use information up to that time. QUESTION: {question} OPTIONS: {options_block} VIDEO MEMORY (chronological, truncated to TIME = {qtime}): EPISODES (subject + summary + description, only episodes that completed before {qtime}): {episodes} FACTS (atomic events ≤ {qtime}): {facts} RECENT FRAME CAPTIONS (boundary frames between the last completed episode and {qtime}, useful for the very latest visual state): {frame_captions} {prev_qa_block} Pick the BEST option based ONLY on evidence at or before {qtime}. Do NOT use future content. Output JSON: {{"answer": "A"|"B"|"C"|"D", "reasoning": ""}} Output ONLY the JSON. """ MCQ_PROMPT_EP_RETRIEVE_ROUND1 = """You are answering a multi-choice question about a third-person video. The question is asked at TIME = {qtime} (absolute video time). You can ONLY use information up to that time. QUESTION: {question} OPTIONS: {options_block} VIDEO MEMORY (chronological, truncated to TIME = {qtime}): EPISODES (subject + summary + description, only episodes that completed before {qtime}): {episodes} RECENT FRAME CAPTIONS (boundary frames between last episode end and {qtime}): {frame_captions} {prev_qa_block} You may ALSO retrieve atomic facts from the hypergraph if the episodes/captions above are NOT enough to answer confidently. Decide: - If the episodes + frame captions clearly support one option → directly answer with decision="answer". - If you need more evidence (e.g. specific entity / count / cross-time detail) → decision="need_retrieval", give a focused retrieval_query. Output JSON STRICTLY: {{ "decision": "answer" | "need_retrieval", "answer": "A"|"B"|"C"|"D" | null, "retrieval_query": "", "reasoning": "" }} Output ONLY the JSON. """ MCQ_PROMPT_EP_RETRIEVE_ROUND2 = """You are giving the FINAL answer after retrieval. QUESTION (asked at TIME = {qtime}): {question} OPTIONS: {options_block} ORIGINAL EPISODES (≤ {qtime}): {episodes} ORIGINAL RECENT FRAME CAPTIONS: {frame_captions} RETRIEVED FACTS (this round, filtered to ≤ {qtime}): {retrieved_facts} {prev_qa_block} Pick the BEST option. You MUST output an answer letter now (no more retrieval). Output JSON: {{"answer": "A"|"B"|"C"|"D", "reasoning": ""}} Output ONLY the JSON. """ MCQ_PROMPT_AGENTIC_ROUND1 = """You are an agent answering a multi-choice question about a third-person video. The question is asked at TIME = {qtime} (absolute video time). You can ONLY use information up to that time. QUESTION: {question} OPTIONS: {options_block} You have access to a video memory hypergraph (Topic ⊂ Episode ⊂ Fact) and frame captions. The following minimal context is provided: EPISODES (≤ {qtime}, only those fully completed): {episodes} RECENT FRAME CAPTIONS (boundary): {frame_captions} {prev_qa_block} Two paths: (a) If the episodes + recent captions clearly answer the question → decision="answer". (b) If you genuinely need more evidence (specific entity, count, fine-grained action, anomaly detail) → decision="need_retrieval"; provide a focused retrieval_query that names the entity / event you need. Be efficient: only retrieve when episodes are not specific enough. Don't retrieve to "double check" things that are already obvious from episodes. Output JSON STRICTLY: {{ "decision": "answer" | "need_retrieval", "answer": "A"|"B"|"C"|"D" | null, "retrieval_query": "", "reasoning": "" }} Output ONLY the JSON. """ PO_TRIGGER_PROMPT = """You are watching a third-person video moment by moment. A user asked you the following trigger question earlier in the video; you must decide RIGHT NOW whether the trigger condition has just become true, so you should produce the literal output. QUESTION (asked at {ask_time}): {question} EXPECTED OUTPUT: "{gt_output}" CURRENT TIME: {now_time} (absolute video time). You can ONLY use evidence from [video start, NOW]. VIDEO MEMORY (chronological, truncated to NOW): EPISODES (only those fully completed before NOW): {episodes} FACTS (atomic events ≤ NOW, last 15s): {facts} RECENT FRAME CAPTIONS (boundary frames between last completed episode and NOW — primary signal for trigger detection): {frame_captions} PREVIOUS_DECISIONS at earlier grid points (your own past answers — do NOT repeat triggering if you already triggered): {prev_decisions} Decide: is THIS the right moment to output "{gt_output}"? - Output "yes" only when the trigger condition described in QUESTION has just become true in the most recent frames AND you have not already triggered for it. - Otherwise output "no". Output JSON: {{"decision": "yes"|"no", "reasoning": ""}} Output ONLY the JSON. """ # ====================================================================== # MCQ 子任务 (SQA + Contextual) # ====================================================================== def _format_options_block(opts: List[str]) -> str: if not opts: return "" if isinstance(opts[0], str) and opts[0][:2] in ("A.", "B.", "C.", "D."): # contextual: 已带 'A. ' 前缀 return "\n".join(opts) return "\n".join(f"{chr(65+i)}. {o}" for i, o in enumerate(opts)) def _format_prev_qa_block_sqa(prev: List[dict]) -> str: """SQA oracle history: 把同 sample 已答的 question + GT_answer 拼进 prompt. 官方协议要求把 GT 答案当 context 注入. 这里我们用 oracle GT (论文常用做法). """ if not prev: return "" lines = ["PREVIOUS Q&A (same video, earlier moments — use as context for this question):"] for p in prev: opts = _format_options_block(p["options"]) lines.append( f" At {p['time_stamp']}, Q: {p['question']}\n" f" Options:\n{_indent(opts, 4)}\n" f" GT answer: {p['answer']}" ) return "\n".join(lines) + "\n" def _indent(s: str, n: int) -> str: pad = " " * n return "\n".join(pad + line for line in s.split("\n")) async def _llm_call_raw(prompt: str) -> str: """调一次 gpt-5-mini, 返回原 response 字符串/dict.""" try: resp = await gpt5_2_llm_config2.best_model_func_raw( gpt5_2_llm_config2.best_model_name, prompt, system_prompt=None, history_messages=[], ) return resp except Exception as e: return f"__ERR__: {e}" def _extract_letter(resp) -> Tuple[str, str]: """从 LLM response 抽 A/B/C/D + reasoning.""" pj = _parse_json_response(resp) if pj: a = (pj.get("answer", "") or "").strip().upper() if a and a[0] in "ABCD": return a[0], pj.get("reasoning", "") m = re.search(r"\b([ABCD])\b", str(resp).upper()) return (m.group(1) if m else "?", "fallback regex") def _extract_decision_or_letter(resp) -> Tuple[str, dict]: """两阶段 prompt 的 round1 解析: 返回 (status, payload). status='answer' → payload = {'answer','reasoning'} status='retrieve' → payload = {'retrieval_query','reasoning'} status='?' → payload = {'reasoning': fallback} """ pj = _parse_json_response(resp) if pj: d = (pj.get("decision", "") or "").strip().lower() if d == "answer": a = (pj.get("answer", "") or "").strip().upper() if a and a[0] in "ABCD": return "answer", {"answer": a[0], "reasoning": pj.get("reasoning", "")} if d == "need_retrieval": return "retrieve", { "retrieval_query": pj.get("retrieval_query", ""), "reasoning": pj.get("reasoning", ""), } # fallback: 试着直接抽字母 m = re.search(r"\b([ABCD])\b", str(resp).upper()) if m: return "answer", {"answer": m.group(1), "reasoning": "fallback regex"} return "?", {"reasoning": str(resp)[:120]} def _last_episode_end(eps: List[dict]) -> float: if not eps: return 0.0 return max(ep.get("end_seconds", ep.get("start_seconds", 0)) for ep in eps) async def _retrieve_facts( hyper_vg, query: str, t_cutoff_sec: float, mode: str = "fact_only", top_k: int = 12, ) -> str: """走 HyperVideoGraph 的双索引检索 (BM25+语义 RRF). cutoff_ts 用 day1-HH:MM:SS 格式. 返回格式化好的字符串 (含 retrieved facts). """ cutoff_ts = ( f"DAY1-{int(t_cutoff_sec//3600):02d}:{int((t_cutoff_sec%3600)//60):02d}:" f"{int(t_cutoff_sec%60):02d}" ) try: ret = await hyper_vg.retrieve(query, cutoff_ts, mode=mode) return hyper_vg.format_retrieval_for_llm(ret) except Exception as e: return f"(retrieval error: {e})" def evaluate_mcq_sample( item: dict, hg: dict, is_sqa: bool, prev_results: dict, mode: str = "dump_all", all_frame_captions: Optional[List[dict]] = None, hyper_vg=None, # for retrieval modes ) -> Dict[str, dict]: """对 sample 内所有 question 推理. mode: - "dump_all": 全 fact + 全 episode + boundary frame_caption, 1 次 LLM - "ep_retrieve": 只 episode + boundary, LLM 决定是否检索 fact (1 次机会) - "agentic": 同 ep_retrieve 但 prompt 更"自主", 鼓励有节制地检索 """ out = {} qs = item["questions_list"] qs_sorted = sorted(qs, key=lambda q: q["time_stamp_sec"]) prev_qa_for_sqa: List[dict] = [] all_frame_captions = all_frame_captions or [] for q in qs_sorted: qid = q["qid"] if qid in prev_results and prev_results[qid].get("answer") is not None: out[qid] = prev_results[qid] if is_sqa: prev_qa_for_sqa.append({ "time_stamp": q["time_stamp"], "question": q["question"], "options": q["options"], "answer": q["answer"], }) continue ts = q["time_stamp_sec"] eps, facts = _truncate_hypergraph(hg, ts) last_ep_end = _last_episode_end(eps) boundary_caps = _filter_frame_captions(all_frame_captions, ts, last_ep_end_sec=last_ep_end) eps_str = _format_episodes(eps) caps_str = _format_frame_captions(boundary_caps) opts_block = _format_options_block(q["options"]) prev_qa_block = _format_prev_qa_block_sqa(prev_qa_for_sqa) if is_sqa else "" used_retrieval = False retrieved_text = "" retrieval_query = "" if mode == "dump_all": facts_str = _format_facts(facts) prompt = MCQ_PROMPT_DUMP_ALL.format( qtime=q["time_stamp"], question=q["question"], options_block=opts_block, episodes=eps_str, facts=facts_str, frame_captions=caps_str, prev_qa_block=prev_qa_block, ) resp = asyncio.run(_llm_call_raw(prompt)) pred, reason = _extract_letter(resp) elif mode in ("ep_retrieve", "agentic"): # Round 1: 给 episode + boundary, 让 LLM 决定 tmpl = MCQ_PROMPT_AGENTIC_ROUND1 if mode == "agentic" else MCQ_PROMPT_EP_RETRIEVE_ROUND1 prompt1 = tmpl.format( qtime=q["time_stamp"], question=q["question"], options_block=opts_block, episodes=eps_str, frame_captions=caps_str, prev_qa_block=prev_qa_block, ) resp1 = asyncio.run(_llm_call_raw(prompt1)) status, payload = _extract_decision_or_letter(resp1) if status == "answer": pred, reason = payload["answer"], payload["reasoning"] elif status == "retrieve" and hyper_vg is not None: used_retrieval = True retrieval_query = payload.get("retrieval_query", "") or q["question"] # hierarchical 模式利用 topic→ep→fact 三层约束 (agentic 用); ep_retrieve 用 fact_only ret_mode = "hierarchical" if mode == "agentic" else "fact_only" retrieved_text = asyncio.run( _retrieve_facts(hyper_vg, retrieval_query, ts, mode=ret_mode) ) # Round 2: 给 retrieved facts 强制答 prompt2 = MCQ_PROMPT_EP_RETRIEVE_ROUND2.format( qtime=q["time_stamp"], question=q["question"], options_block=opts_block, episodes=eps_str, frame_captions=caps_str, retrieved_facts=retrieved_text, prev_qa_block=prev_qa_block, ) resp2 = asyncio.run(_llm_call_raw(prompt2)) pred, reason = _extract_letter(resp2) reason = f"[after retrieval: {retrieval_query[:60]}] {reason}" else: # 解析失败兜底: 用全 fact dump 重答一次 facts_str = _format_facts(facts) fallback_prompt = MCQ_PROMPT_DUMP_ALL.format( qtime=q["time_stamp"], question=q["question"], options_block=opts_block, episodes=eps_str, facts=facts_str, frame_captions=caps_str, prev_qa_block=prev_qa_block, ) resp_fb = asyncio.run(_llm_call_raw(fallback_prompt)) pred, reason = _extract_letter(resp_fb) reason = f"[r1 parse fail; dump-all fallback] {reason}" else: raise ValueError(f"未知 mode: {mode}") gt = q["answer"] ok = (pred == gt) out[qid] = { "answer": pred, "gt": gt, "ok": ok, "reasoning": reason, "time_stamp": q["time_stamp"], "mode": mode, "used_retrieval": used_retrieval, "retrieval_query": retrieval_query, } if is_sqa: prev_qa_for_sqa.append({ "time_stamp": q["time_stamp"], "question": q["question"], "options": q["options"], "answer": q["answer"], }) return out # ====================================================================== # Proactive Output 1s grid 流式 # ====================================================================== async def _llm_answer_po(prompt: str) -> Tuple[str, str]: try: resp = await gpt5_2_llm_config2.best_model_func_raw( gpt5_2_llm_config2.best_model_name, prompt, system_prompt=None, history_messages=[], ) pj = _parse_json_response(resp) if pj: d = (pj.get("decision", "") or "").strip().lower() if d in ("yes", "no"): return d, pj.get("reasoning", "") # fallback s = str(resp).lower() if "yes" in s.split()[:5] if s.split() else False: return "yes", "fallback substring" return "no", f"fallback default no: {str(resp)[:60]}" except Exception as e: return "no", f"err: {e}" def _format_prev_decisions(prev: List[dict]) -> str: if not prev: return "(no prior grid points yet)" lines = [] for p in prev[-6:]: # 只取最近 6 个 grid 点, 避免 prompt 超长 lines.append(f" t={p['t']:.0f}s: {p['decision']} ({p['reasoning'][:80]})") return "\n".join(lines) def evaluate_po_sample( item: dict, hg: dict, prev_results: dict, all_frame_captions: Optional[List[dict]] = None, ) -> Dict[str, dict]: """对 PO sample 内每个 question 流式 grid 1s 检测. 截断规则 (与 SQA/Ctx 一致): - episode: 必须 end ≤ t_now (严格) - fact: temporal ≤ t_now - frame_caption: [last_ep_end, t_now] 边界 (补 episode 截断后的边界视觉) Returns: {qid: {answered_time_sec, gt_time_sec, gt_output, decisions: [...]}} """ out = {} qs = item["questions_list"] test_info = item["test_info"] all_frame_captions = all_frame_captions or [] grids_by_qid: Dict[str, List[dict]] = {} for ti in test_info: grids_by_qid.setdefault(ti["qid"], []).append(ti) for q in qs: qid = q["qid"] if qid in prev_results and prev_results[qid].get("done"): out[qid] = prev_results[qid] continue grids = sorted(grids_by_qid.get(qid, []), key=lambda x: x["realtime"]) ask_t = q["time_stamp_sec"] gt_t = q.get("ground_truth_time_stamp_sec", ask_t + 1) gt_output = q.get("ground_truth_output", "") decisions: List[dict] = [] answered_time = None for ti in grids: t_now = ti["realtime"] eps, facts = _truncate_hypergraph(hg, t_now) # 只展示最近的 episode (避免 prompt 过长) eps_recent = eps[-3:] last_ep_end = _last_episode_end(eps_recent) # 只展示最近 15s 内的 fact (PO 高度依赖最新视觉) facts_recent = [f for f in facts if _parse_temporal_to_sec(f.get("temporal", "")) >= t_now - 15.0] if not facts_recent and facts: facts_recent = facts[-10:] # frame_caption 补足 [last_ep_end, t_now] 边界 boundary_caps = _filter_frame_captions( all_frame_captions, t_now, last_ep_end_sec=last_ep_end, max_seconds_back=15.0, ) prompt = PO_TRIGGER_PROMPT.format( ask_time=q["time_stamp"], question=q["question"], gt_output=gt_output, now_time=f"{t_now:.0f}s", episodes=_format_episodes(eps_recent, max_each_desc=300), facts=_format_facts(facts_recent), frame_captions=_format_frame_captions(boundary_caps), prev_decisions=_format_prev_decisions(decisions), ) decision, reason = asyncio.run(_llm_answer_po(prompt)) decisions.append({"t": t_now, "decision": decision, "reasoning": reason}) if decision == "yes": answered_time = t_now break out[qid] = { "qid": qid, "ask_time_sec": ask_t, "gt_time_sec": gt_t, "gt_output": gt_output, "answered_time_sec": answered_time, "answered": answered_time is not None, "abs_offset_sec": (abs(answered_time - gt_t) if answered_time is not None else None), "decisions": decisions, "n_grids": len(decisions), "done": True, } return out # ====================================================================== # 主入口 # ====================================================================== def _load_dataset_for(name: str) -> List[dict]: if name == "sqa": return load_streamingbench_sqa_json() if name == "contextual": return load_streamingbench_contextual_json() if name == "proactive": return load_streamingbench_proactive_json() raise ValueError(f"未知 dataset: {name}") def _score_mcq(out: Dict[str, Dict[str, dict]]) -> dict: """汇总 MCQ 结果.""" n_total = 0; n_correct = 0 by_subtype: Dict[str, dict] = {} for sid, qresults in out.items(): for qid, r in qresults.items(): if "answer" not in r: continue n_total += 1 if r.get("ok"): n_correct += 1 # 按 sample id 前缀分 mcu/acu tag = "all" if sid.startswith("mcu_"): tag = "mcu" elif sid.startswith("acu_"): tag = "acu" by_subtype.setdefault(tag, {"correct": 0, "total": 0}) by_subtype[tag]["total"] += 1 if r.get("ok"): by_subtype[tag]["correct"] += 1 summary = { "total": n_total, "correct": n_correct, "acc": (100 * n_correct / n_total) if n_total else 0, "by_subtype": { k: {"acc": (100 * v["correct"] / v["total"]) if v["total"] else 0, **v} for k, v in by_subtype.items() }, } return summary def _score_po(out: Dict[str, Dict[str, dict]]) -> dict: """PO 评分: 多个偏差容忍窗口.""" n_total = 0; n_answered = 0 n_within_2s = 0; n_within_4s = 0 offsets = [] for sid, qresults in out.items(): for qid, r in qresults.items(): if "done" not in r: continue n_total += 1 if r.get("answered"): n_answered += 1 off = r["abs_offset_sec"] offsets.append(off) if off <= 2.0: n_within_2s += 1 if off <= 4.0: n_within_4s += 1 return { "total_questions": n_total, "answered": n_answered, "answer_rate": (100 * n_answered / n_total) if n_total else 0, "acc_within_2s": (100 * n_within_2s / n_total) if n_total else 0, "acc_within_4s": (100 * n_within_4s / n_total) if n_total else 0, "mean_offset_sec": (sum(offsets) / len(offsets)) if offsets else 0, } def _load_frame_captions(working_dir: str) -> List[dict]: """从 working_dir/frame_captions.json 读 caption 列表 (建图阶段保存).""" fp = os.path.join(working_dir, "frame_captions.json") if not os.path.isfile(fp): return [] try: data = json.load(open(fp)) return data.get("frame_captions", []) if isinstance(data, dict) else (data or []) except Exception: return [] def _maybe_init_hyper_vg(working_dir: str): """检索模式才需要实例化 HyperVideoGraph (走 BM25+语义双索引).""" from hypervideo.hyper_video_graph import HyperVideoGraph from hypervideo.config import HyperVideoConfig from hypervideo.ovobench_hyper_retrieval import gpt5_2_llm_config2 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")), ) return HyperVideoGraph(working_dir=working_dir, llm=gpt5_2_llm_config2, hyper_config=cfg) def main(): # OPENAI key fallback: 不强制由调用方 export. 若未 set, 沿用 ovobench_hyper_retrieval main() 走过同样的 hardcoded key 路径 # (生产环境推荐 export OPENAI_API_KEY=... 由调用方提供) if not os.environ.get("OPENAI_API_KEY"): # ovobench_hyper_retrieval 的 main() 在执行时硬编码这个 key, 这里 import 走 lazy 读源 import re try: with open(__file__.replace("streamingbench_json_eval.py", "ovobench_hyper_retrieval.py")) as f: m = re.search(r'os\.environ\["OPENAI_API_KEY"\]\s*=\s*"(sk-[^"]+)"', f.read()) if m: os.environ["OPENAI_API_KEY"] = m.group(1) logger.info("OPENAI_API_KEY 未 export, 已从 ovobench_hyper_retrieval 复用 hardcoded key") except Exception: pass if not os.environ.get("OPENAI_API_KEY"): raise RuntimeError("请先 export OPENAI_API_KEY=... 再运行本脚本") ap = argparse.ArgumentParser() ap.add_argument("--dataset", choices=["sqa", "contextual", "proactive"], required=True) ap.add_argument( "--mode", choices=["dump_all", "ep_retrieve", "agentic"], default="dump_all", help="MCQ 推理 mode (PO 不受影响). dump_all=全 fact 直答; " "ep_retrieve=只 episode + LLM 决策是否检索 (1次, fact_only); " "agentic=同上但鼓励有节制检索, 用 hierarchical 模式", ) ap.add_argument( "--working_dir_root", type=str, default="/mnt/tokyo-ai/gst/GST_EGOSERVE/all_results", ) ap.add_argument( "--datasets_type", type=str, required=True, help="working_dir 子目录, 例如 streamingbench_sqa_hyper", ) ap.add_argument("--caption_model_name", type=str, default="qwen_api") ap.add_argument("--limit", type=int, default=0, help="只跑前 N samples (0=全部)") ap.add_argument("--output_path", type=str, required=True) ap.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", ) ap.add_argument( '--propagation_mode', type=str, default='residual', choices=['residual', 'hypermem', 'none'], help="嵌入传播: residual (默认) / hypermem / none", ) ap.add_argument( '--propagation_lambda', type=float, default=0.5, ) args = ap.parse_args() # 应用 model + propagation 到 imported gpt5_2_llm_config + env 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) from hypervideo.ovobench_hyper_retrieval import gpt5_2_llm_config1, gpt5_2_llm_config2 gpt5_2_llm_config1.best_model_name = args.answer_model gpt5_2_llm_config2.best_model_name = args.answer_model logger.info(f"[args] answer_model={args.answer_model} propagation_mode={args.propagation_mode} lambda={args.propagation_lambda}") is_sqa = args.dataset == "sqa" is_po = args.dataset == "proactive" needs_retrieval = (not is_po) and args.mode in ("ep_retrieve", "agentic") all_data = _load_dataset_for(args.dataset) if args.limit > 0: all_data = all_data[: args.limit] logger.info( f"加载 {len(all_data)} samples (dataset={args.dataset}, mode={args.mode})" ) out: Dict[str, Dict[str, dict]] = {} if os.path.exists(args.output_path): try: out = json.load(open(args.output_path)) logger.info(f"已加载历史结果 {sum(len(v) for v in out.values())} questions") except Exception: out = {} t_all = time.time() for sample_idx, item in enumerate(all_data): sid = item["id"] wd = os.path.join( args.working_dir_root, args.datasets_type, f"{sid}_{args.caption_model_name}" ) hp = os.path.join(wd, "hypergraph.json") if not os.path.isfile(hp): logger.warning(f"[{sample_idx+1}/{len(all_data)}] {sid} 未建图, 跳过") continue try: hg = json.load(open(hp)) except Exception as e: logger.warning(f"[{sample_idx+1}/{len(all_data)}] {sid} hypergraph 加载失败 {e}") continue all_frame_captions = _load_frame_captions(wd) # 检索模式才实例化 hyper_vg (开销较大) hyper_vg = None if needs_retrieval: try: hyper_vg = _maybe_init_hyper_vg(wd) except Exception as e: logger.warning(f" hyper_vg 加载失败 ({e}), 该 sample 退化到 dump_all") prev = out.get(sid, {}) if is_po: new_results = evaluate_po_sample(item, hg, prev, all_frame_captions=all_frame_captions) else: new_results = evaluate_mcq_sample( item, hg, is_sqa=is_sqa, prev_results=prev, mode=args.mode if hyper_vg is not None or args.mode == "dump_all" else "dump_all", all_frame_captions=all_frame_captions, hyper_vg=hyper_vg, ) out[sid] = new_results # 进度日志 if is_po: n_ans = sum(1 for r in new_results.values() if r.get("answered")) logger.info( f"[{sample_idx+1}/{len(all_data)}] {sid}: " f"{n_ans}/{len(new_results)} answered, " f"avg_offset={sum(r['abs_offset_sec'] for r in new_results.values() if r.get('answered'))/max(n_ans,1):.1f}s" ) else: n_ok = sum(1 for r in new_results.values() if r.get("ok")) logger.info( f"[{sample_idx+1}/{len(all_data)}] {sid}: {n_ok}/{len(new_results)} correct" ) # 持续保存 if (sample_idx + 1) % 5 == 0: json.dump(out, open(args.output_path, "w"), ensure_ascii=False, indent=2) json.dump(out, open(args.output_path, "w"), ensure_ascii=False, indent=2) dt = time.time() - t_all logger.info(f"完成 {len(all_data)} samples, {dt:.0f}s") # 汇总 if is_po: s = _score_po(out) else: s = _score_mcq(out) logger.info(f"=== {args.dataset} 汇总 ===") logger.info(json.dumps(s, indent=2, ensure_ascii=False)) summary_path = args.output_path.replace(".json", "_summary.json") json.dump(s, open(summary_path, "w"), ensure_ascii=False, indent=2) if __name__ == "__main__": main()