""" StreamingBench (Real_Time_Visual_Understanding) 推理检索入口 —— 使用 HyperVideoGraph 的三层超图检索替代原 VDB/KG 检索 MCQ 数据来自: /mnt/tokyo-ai/gst/StreamingBench/StreamingBench/Real_Time_Visual_Understanding.csv 字段: question_id, task_type, question, time_stamp, answer, options, frames_required, temporal_clue_type (Prior / Concurrent) 任务分流: * Concurrent (~84%) -> REALTIME:以 time_stamp 附近的 recent captions + 截至该时刻的 global captions 直接回答 * Prior (~16%) -> BACKWARD:最多 2 轮 LLM 决策, 需要检索时调用 HyperVideoGraph.retrieve(query, time_span_cutoff) 做 Topic→Episode→Fact 层次检索 与 ovobench_hyper_retrieval.py 的关键差异: 1. 数据源是 CSV 而非 JSON, 选项字段是 Python list 字符串 2. 单视频多问题, 每个问题有自己的 time_stamp 和 temporal_clue_type 3. time_stamp 是绝对 HH:MM:SS, 需转成 "1-00:HH:MM-HH:MM:SS" 形式供超图 的时间过滤使用(只检索 time_stamp 之前的 episode/fact) """ # Pre-import nano_vectordb before transformers locks libstdc++ (see mmlifelong_week_retrieval_v2.py) import torch # noqa: F401 try: import nano_vectordb as _nvdb_preload # noqa: F401 except Exception: pass import os import sys import argparse import asyncio import ast import csv import json import logging import re import time from collections import defaultdict from typing import List, Dict, Optional sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) if __name__ == "__main__": _pre_parser = argparse.ArgumentParser(add_help=False) _pre_parser.add_argument('--cuda', type=str, default='1') _pre_args, _ = _pre_parser.parse_known_args() os.environ["CUDA_VISIBLE_DEVICES"] = _pre_args.cuda from videorag._llm import ( LLMConfig, openai_embedding, bge_m3_embedding, gpt_4o_mini_complete, ) from videorag._utils import always_get_an_event_loop from hypervideo.hyper_video_graph import HyperVideoGraph from hypervideo.config import HyperVideoConfig logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # ==================== temporal_clue_type → 路由 ==================== REALTIME_CLUE_TYPES = {"Concurrent"} # 直接回答 BACKWARD_CLUE_TYPES = {"Prior"} # 超图检索 # ==================== LLM 配置 ==================== llm_config_openai = LLMConfig( embedding_func_raw=openai_embedding, embedding_model_name="text-embedding-3-small", embedding_dim=1536, embedding_max_token_size=8192, embedding_batch_num=32, embedding_func_max_async=16, query_better_than_threshold=0.2, best_model_func_raw=gpt_4o_mini_complete, # default: gpt-4.1-mini (org-verified, 同 mmlifelong); --answer_model 可改成 gpt-5.4-nano / gpt-5.4-mini best_model_name=os.environ.get("HYPERVIDEO_ANSWER_MODEL", "gpt-4.1-mini"), best_model_max_token_size=32768, best_model_max_async=16, cheap_model_func_raw=gpt_4o_mini_complete, cheap_model_name="gpt-4o-mini", cheap_model_max_token_size=32768, cheap_model_max_async=16, ) llm_config_bge = LLMConfig( embedding_func_raw=bge_m3_embedding, embedding_model_name="BAAI/bge-m3", embedding_dim=1024, embedding_max_token_size=8192, embedding_batch_num=32, embedding_func_max_async=16, query_better_than_threshold=0.2, best_model_func_raw=gpt_4o_mini_complete, best_model_name=os.environ.get("HYPERVIDEO_ANSWER_MODEL", "gpt-4.1-mini"), best_model_max_token_size=32768, best_model_max_async=16, cheap_model_func_raw=gpt_4o_mini_complete, cheap_model_name="gpt-4o-mini", cheap_model_max_token_size=32768, cheap_model_max_async=16, ) # ==================== Prompt 模板 ==================== STREAMINGBENCH_REALTIME_PROMPT = """ You are a streaming video question-answering assistant designed for the StreamingBench Real-Time Visual Understanding task. This is a TRAINING-FREE, DIRECT-ANSWER reasoning process. You are given: - RECENT_CAPTIONS: detailed second-level captions from the LAST ~15 seconds BEFORE the question time_stamp (the moment the question is asked). - GLOBAL_CAPTIONS: minute-level summaries covering the video up to the question time_stamp. - TASK_TYPE: one of Object Perception, Action Perception, Attribute Perception, Spatial Understanding, Counting, Event Understanding, Text-Rich Understanding, Clips Summarize, Causal Reasoning, Prospective Reasoning. - TEMPORAL_CLUE: "Concurrent" — the answer is observable AT the time_stamp. You must answer the question directly based on the provided captions. No retrieval is allowed. ------------------------------------------------------------ Reasoning Requirements ------------------------------------------------------------ - Focus primarily on RECENT_CAPTIONS near the question time_stamp. - Use GLOBAL_CAPTIONS only for broader context when RECENT_CAPTIONS are insufficient. - Ground all reasoning in the provided captions. - Do NOT invent objects, actions, or states not mentioned in captions. - Choose the option most consistent with available evidence. ------------------------------------------------------------ Output Format (STRICT) ------------------------------------------------------------ { "answer": "", "reasoning": "" } Output ONLY the JSON object. No additional text. """ STREAMINGBENCH_BACKWARD_RETRIEVAL_PROMPT = """ You are a streaming video question-answering decision assistant designed for the StreamingBench Real-Time Visual Understanding task. This is a TRAINING-FREE, ITERATIVE decision-and-retrieval process that operates over a three-layer semantic hypergraph (Topic → Episode → Fact) built from the video's captions up to the question time_stamp. At most TWO retrieval rounds are allowed. You are given: - GLOBAL_CAPTIONS: minute-level summaries covering the video up to the question time_stamp. - RETRIEVED_CONTEXT: facts / episode summaries retrieved from the hypergraph in previous rounds (may be empty). - TASK_TYPE: one of Object Perception, Action Perception, Attribute Perception, Spatial Understanding, Counting, Event Understanding, Text-Rich Understanding, Clips Summarize, Causal Reasoning, Prospective Reasoning. - TEMPORAL_CLUE: "Prior" — the answer hinges on something that happened BEFORE the question time_stamp. ------------------------------------------------------------ Decision Rules ------------------------------------------------------------ CASE 1 — RETRIEVED_CONTEXT is EMPTY (first round) You may ANSWER immediately ONLY IF: - The answer can be clearly determined from GLOBAL_CAPTIONS alone. - Exactly ONE option is consistent with the evidence. Otherwise → request retrieval. CASE 2 — RETRIEVED_CONTEXT EXISTS (after retrieval) If this is the second retrieval round, you MUST answer. If this is the first retrieval round, you may request one more retrieval OR answer. When answering after retrieval: - Choose the option most consistent with all available evidence. - Do NOT invent new evidence. ------------------------------------------------------------ Retrieval Query Requirements ------------------------------------------------------------ If requesting retrieval: - Output ONE concise English sentence as the retrieval query. - The query MUST specify: • The temporal segment or event needed (e.g. "early in the video", "right before the fight") • The specific object / person / action / text to look for • Include option texts in parentheses for context ------------------------------------------------------------ Output Format (STRICT) ------------------------------------------------------------ Case 1 — Answer: { "decision": "answer", "answer": "", "reasoning": "" } Case 2 — Need Retrieval: { "decision": "need_retrieval", "retrieval_query": "" } Output ONLY the JSON object. No additional text. """ # ==================== 工具函数 ==================== def _parse_llm_json(response: str) -> Optional[dict]: """从 LLM 响应中提取 JSON(处理 markdown 代码块)""" if not response: return None cleaned = response.strip() if cleaned.startswith("```"): lines = cleaned.split("\n") cleaned = "\n".join(lines[1:-1]) if len(lines) > 2 else cleaned m = re.search(r'\{.*\}', cleaned, re.DOTALL) if m: try: return json.loads(m.group()) except json.JSONDecodeError: pass return None def _parse_options(options_raw: str) -> List[str]: """CSV 中的 options 是 Python list 字符串, 如: "['A. FIFA and La Liga.', 'B. UEFA and La Liga.', ...]" """ if not options_raw: return [] try: parsed = ast.literal_eval(options_raw) if isinstance(parsed, list): return [str(x) for x in parsed] except (ValueError, SyntaxError): pass # 退回到简单分割 return [s.strip() for s in options_raw.split(",") if s.strip()] def _extract_option_letter(text: str, options: List[str] = None) -> Optional[str]: """提取选项字母 A/B/C/D(与 ovobench_hyper_retrieval 一致)""" if not text: return None text = text.strip() labels = "ABCD" m = re.match(r'^[(\s]*([A-Da-d])[).\s:,\-]', text) if m: return m.group(1).upper() if len(text) == 1 and text.upper() in labels: return text.upper() m = re.match(r'^([A-Da-d])[.:\s)\-]', text) if m: return m.group(1).upper() if options: text_lower = text.lower().strip() text_clean = re.sub(r'^[(\s]*[A-Da-d][).\s:,\-]+\s*', '', text_lower).strip() for i, opt in enumerate(options): if i >= len(labels): break # options 里通常已经带 "A. xxx" 前缀, 先去掉再比较 opt_body = re.sub(r'^[A-Da-d]\.\s*', '', opt).strip().lower() if text_clean == opt_body or text_lower == opt.lower().strip(): return labels[i] # 模糊 for i, opt in enumerate(options): if i >= len(labels): break opt_body = re.sub(r'^[A-Da-d]\.\s*', '', opt).strip().lower() if len(opt_body) > 3 and (opt_body in text_lower or text_clean in opt_body): return labels[i] return None def _hms_to_seconds(hms: str) -> int: """HH:MM:SS → seconds""" if not hms: return 0 try: parts = hms.strip().split(":") if len(parts) == 3: h, m, s = parts elif len(parts) == 2: h, m, s = "0", parts[0], parts[1] else: return 0 return int(h) * 3600 + int(m) * 60 + int(float(s)) except (ValueError, AttributeError): return 0 def _seconds_to_hms(sec: int) -> str: sec = max(0, int(sec)) h = sec // 3600 m = (sec % 3600) // 60 s = sec % 60 return f"{h:02d}:{m:02d}:{s:02d}" def _build_time_span_cutoff(time_stamp_hms: str) -> str: """把 'HH:MM:SS' 转为超图识别的 '1-HH:MM:SS-HH:MM:SS' 形式, end 正好就是 time_stamp。 """ if not time_stamp_hms: return "" return f"1-{time_stamp_hms}-{time_stamp_hms}" def _time_span_end_seconds(time_span: str) -> int: """解析 '1-HH:MM:SS-HH:MM:SS', 返回 end 秒数""" if not time_span: return 0 parts = time_span.split("-", 1) if len(parts) < 2: return 0 times = parts[1].split("-") if len(times) < 2: return _hms_to_seconds(parts[1]) return _hms_to_seconds(times[1]) def _filter_captions_up_to(captions: List[dict], cutoff_seconds: int) -> List[dict]: """过滤出 end_seconds <= cutoff 的 captions""" if cutoff_seconds <= 0: return captions result = [] for cap in captions: end_s = _time_span_end_seconds(cap.get('time_span', '')) if end_s <= cutoff_seconds: result.append(cap) return result def _get_recent_captions_before( captions: List[dict], cutoff_seconds: int, window_seconds: int = 15, ) -> List[dict]: """取 cutoff 之前 window 秒内的 captions""" if cutoff_seconds <= 0: return captions[-3:] if captions else [] lo = max(0, cutoff_seconds - window_seconds) result = [] for cap in captions: end_s = _time_span_end_seconds(cap.get('time_span', '')) if lo < end_s <= cutoff_seconds: result.append(cap) return result if result else [c for c in captions if _time_span_end_seconds(c.get('time_span', '')) <= cutoff_seconds][-1:] def _format_captions(captions: List[dict]) -> str: return "\n".join( f"[{i+1}] Time: {cap.get('time_span', 'N/A')}\n{cap.get('caption', '')}" for i, cap in enumerate(captions) ) def _format_options_block(options: List[str]) -> str: """options 已经带 'A. xxx' 前缀, 直接换行拼接""" return "\n".join(options) def _build_episode_blocks(hyper_vg, current_time_span: str, near_n: int = 5): """构建 (all_summaries_text, near_detail_text)。 - all_summaries_text: cutoff 前所有 episode 的 [time_span] subject - summary - near_detail_text: 最近 near_n 个 episode 的 summary + episode_description """ from hypervideo.types import parse_frame_time_to_seconds eps_dict = hyper_vg.hypergraph_builder.hypergraph.episodes cutoff_sec = None if current_time_span: cutoff_sec = parse_frame_time_to_seconds(current_time_span, "end") eps = [] for ep in eps_dict.values(): if cutoff_sec is not None and ep.end_seconds > cutoff_sec: continue eps.append(ep) eps.sort(key=lambda e: e.end_seconds) def _subj(ep): return getattr(ep, 'subject', None) or getattr(ep, 'title', None) or '' def _desc(ep): return ( getattr(ep, 'episode_description', None) or getattr(ep, 'description', '') or '' ) all_lines = [] for ep in eps: ts = getattr(ep, 'time_span', '') line = f"[{ts}] {_subj(ep)}" summ = getattr(ep, 'summary', '') or '' if summ: line += f" — {summ}" all_lines.append(line) all_text = "\n".join(all_lines) if all_lines else "(no episodes)" near = eps[-near_n:] if eps else [] near_blocks = [] for ep in near: ts = getattr(ep, 'time_span', '') block = f"[{ts}] {_subj(ep)}" summ = getattr(ep, 'summary', '') or '' d = _desc(ep) if summ: block += f"\n summary: {summ}" if d: block += f"\n description: {d}" near_blocks.append(block) near_text = "\n\n".join(near_blocks) if near_blocks else "(no nearby episodes)" return all_text, near_text def _build_full_hypergraph_dump(hyper_vg, current_time_span: str): """构造 ALL_EPISODES (summary+description) + ALL_FACTS (chronological)。 用于 dump_all 无检索 baseline。 """ from hypervideo.types import parse_frame_time_to_seconds eps_dict = hyper_vg.hypergraph_builder.hypergraph.episodes facts_dict = hyper_vg.hypergraph_builder.hypergraph.facts cutoff_sec = None if current_time_span: cutoff_sec = parse_frame_time_to_seconds(current_time_span, "end") eps = [] for ep in eps_dict.values(): if cutoff_sec is not None and ep.end_seconds > cutoff_sec: continue eps.append(ep) eps.sort(key=lambda e: e.end_seconds) ep_blocks = [] for ep in eps: ts = getattr(ep, 'time_span', '') subj = getattr(ep, 'subject', None) or getattr(ep, 'title', None) or '' summ = getattr(ep, 'summary', '') or '' desc = ( getattr(ep, 'episode_description', None) or getattr(ep, 'description', '') or '' ) block = f"[{ts}] {subj}" if summ: block += f"\n summary: {summ}" if desc: block += f"\n description: {desc}" ep_blocks.append(block) all_eps_text = "\n\n".join(ep_blocks) if ep_blocks else "(no episodes)" facts = [] for f in facts_dict.values(): eids = getattr(f, 'episode_ids', None) or [] if cutoff_sec is not None and eids: in_window = False for eid in eids: ep = eps_dict.get(eid) if ep and ep.end_seconds <= cutoff_sec: in_window = True break if not in_window: continue facts.append(f) def _key(f): try: return parse_frame_time_to_seconds(getattr(f, 'temporal', '') or '', "start") except Exception: return 0.0 facts.sort(key=_key) fact_lines = [] for f in facts: tmp = getattr(f, 'temporal', '') or '?' cont = getattr(f, 'content', '') or '' spat = getattr(f, 'spatial', '') or '' line = f"[{tmp}] {cont}" if spat: line += f" (loc: {spat})" fact_lines.append(line) all_facts_text = "\n".join(fact_lines) if fact_lines else "(no facts)" return all_eps_text, all_facts_text SB_FULL_DUMP_PROMPT = """ You are a streaming video question-answering assistant for the StreamingBench Real-Time Visual Understanding task. You are given the COMPLETE three-layer semantic hypergraph (Topic → Episode → Fact) of the video so far, dumped in full: - LATEST_FRAME_CAPTIONS: the last 2 frame-level captions before the question time_stamp (most recent visual evidence). - ALL_EPISODES: chronological list of every episode with summary AND description. - ALL_FACTS: chronological list of every fact (atomic event), each tagged with its temporal position. You must answer in ONE shot — no retrieval is allowed. Decision Rules: - Carefully scan all provided context for evidence. - Pick the option most consistent with the evidence. - Prefer a concrete option even from partial evidence. - Never fabricate evidence. Output Format (STRICT): { "answer": "", "reasoning": "" } Output ONLY the JSON object. """ SB_BACKWARD_RETRIEVAL_PROMPT = """ You are a streaming video question-answering decision assistant for the StreamingBench Real-Time Visual Understanding task. A three-layer semantic hypergraph (Topic → Episode → Fact) has been built from the video's captions up to the question time_stamp. UP TO TWO retrievals are allowed (Round 1 → optional retrieval → Round 2 must answer). You are given: - LATEST_FRAME_CAPTIONS: the last 2 frame-level captions before time_stamp (most recent visual evidence right at the question moment). - ALL_EPISODE_SUMMARIES: chronological skeleton of every episode (every episode's title + one-line summary) up to time_stamp. - NEARBY_EPISODES: the most recent N episodes with full summary AND description (more visual / textual detail). - RETRIEVED_CONTEXT: facts / episode details retrieved from the hypergraph in earlier rounds (empty in Round 1). Task Types: Object Perception, Action Perception, Attribute Perception, Spatial Understanding, Counting, Event Understanding, Text-Rich Understanding, Causal Reasoning, Prospective Reasoning, Clips Summarize. Decision Rules: NON-FINAL ROUND (you may answer OR request retrieval) - Answer immediately when LATEST_CAPTIONS + ALL_EPISODE_SUMMARIES + NEARBY_EPISODES + (RETRIEVED_CONTEXT) is sufficient to pick exactly one option. - Only request retrieval when existing evidence is genuinely insufficient (e.g. fine count / detail / object NOT mentioned anywhere). - Do NOT request retrieval just to be safe. FINAL ROUND (you MUST answer) - DEFAULT: pick the option most consistent with available evidence. - Make a best guess from partial evidence — do not refuse just because evidence is incomplete. - Never fabricate new evidence. Retrieval Query Requirements (only when decision = need_retrieval): - ONE concise English sentence. - Must specify: temporal segment + specific object/person/action/count. - Include answer options in parentheses. Output Format (STRICT): Answer: {"decision": "answer", "answer": "", "reasoning": ""} Need Retrieval (only in non-final rounds): {"decision": "need_retrieval", "retrieval_query": ""} Output ONLY the JSON object. """ def _handle_dump_all( question: str, task_type: str, options: List[str], second_captions: list, cutoff_sec: int, llm_config: LLMConfig, hyper_vg: HyperVideoGraph, ) -> dict: """方式 1 (dump_all): 不检索, 全量喂入 LATEST_2_CAPTIONS + ALL_EPISODES (summary+desc) + ALL_FACTS""" options_text = _format_options_block(options) # 最近 2 个 frame caption (cutoff 之前) filtered_sec = _filter_captions_up_to(second_captions, cutoff_sec) latest_2 = filtered_sec[-2:] if filtered_sec else [] latest_text = _format_captions(latest_2) if latest_2 else "(none)" time_span_cutoff = _build_time_span_cutoff(_seconds_to_hms(cutoff_sec)) all_eps_text, all_facts_text = _build_full_hypergraph_dump(hyper_vg, time_span_cutoff) full_prompt = f"""{SB_FULL_DUMP_PROMPT} ------------------------------------------------------------ TASK_TYPE ------------------------------------------------------------ {task_type} ------------------------------------------------------------ QUESTION ------------------------------------------------------------ {question} ------------------------------------------------------------ OPTIONS ------------------------------------------------------------ {options_text} ------------------------------------------------------------ LATEST_FRAME_CAPTIONS (last 2 captions before question time_stamp) ------------------------------------------------------------ {latest_text} ------------------------------------------------------------ ALL_EPISODES (every episode in the video so far, summary + description) ------------------------------------------------------------ {all_eps_text} ------------------------------------------------------------ ALL_FACTS (every fact in the video so far, chronologically) ------------------------------------------------------------ {all_facts_text} """ try: response = asyncio.run(llm_config.best_model_func_raw( llm_config.best_model_name, full_prompt, system_prompt=None, history_messages=[], )) logger.info(f" LLM response: {str(response)[:200]}...") parsed = _parse_llm_json(response) if isinstance(response, str) else response if parsed is None: parsed = {"answer": "", "reasoning": str(response)} except Exception as e: logger.error(f" LLM 调用失败: {e}") parsed = {"answer": "", "reasoning": str(e)} return { 'answer': parsed.get('answer', ''), 'reasoning': parsed.get('reasoning', ''), 'round': 1, 'mode': 'dump_all_no_retrieval', 'retrieved_context': [], 'retrieval_history': [{"mode": "dump_all", **parsed}], } def _handle_backward_with_retrieval( question: str, task_type: str, options: List[str], second_captions: list, cutoff_sec: int, llm_config: LLMConfig, hyper_vg: HyperVideoGraph, max_rounds: int = 2, near_n: int = 5, retrieval_mode: str = "hierarchical", recent_window_sec: int = 0, ) -> dict: """方式 2/3/4 (检索): LATEST_2_CAPTIONS + ALL_EPISODE_SUMMARIES + NEARBY_EPISODES. LLM 决策 → 需要检索时按 retrieval_mode 调用 (fact_only / episode_fact / hierarchical) → 最多 2 轮. recent_window_sec>0 (merge2 式): 把 LATEST_2 改成"最近 N 秒帧 caption"(merge2/rt2 洞察: 当前帧证据要喂足够帧, 只喂 2 帧太少)。 """ options_text = _format_options_block(options) filtered_sec = _filter_captions_up_to(second_captions, cutoff_sec) if recent_window_sec > 0: latest_2 = _get_recent_captions_before(second_captions, cutoff_sec, window_seconds=recent_window_sec) else: latest_2 = filtered_sec[-2:] if filtered_sec else [] latest_text = _format_captions(latest_2) if latest_2 else "(none)" time_span_cutoff = _build_time_span_cutoff(_seconds_to_hms(cutoff_sec)) all_eps_text, nearby_eps_text = _build_episode_blocks( hyper_vg, time_span_cutoff, near_n=near_n, ) retrieved_contexts = [] retrieval_history = [] loop = always_get_an_event_loop() for round_idx in range(1, max_rounds + 1): logger.info(f" [Backward-{retrieval_mode}] Round {round_idx}/{max_rounds}") retrieved_text = "" if retrieved_contexts: retrieved_text = "\n\n".join( f"[Retrieved {i+1}]\n{ctx}" for i, ctx in enumerate(retrieved_contexts) ) retrievals_left = max_rounds - round_idx if round_idx >= max_rounds: round_marker = ( f"FINAL ROUND ({round_idx}/{max_rounds}) — you MUST output an " "answer. No more retrieval allowed." ) else: round_marker = ( f"Round {round_idx}/{max_rounds} — {retrievals_left} retrieval(s) " "remaining. Answer if evidence suffices, else request retrieval." ) full_prompt = f"""{SB_BACKWARD_RETRIEVAL_PROMPT} ------------------------------------------------------------ ROUND_STATUS ------------------------------------------------------------ {round_marker} ------------------------------------------------------------ TASK_TYPE ------------------------------------------------------------ {task_type} ------------------------------------------------------------ QUESTION ------------------------------------------------------------ {question} ------------------------------------------------------------ OPTIONS ------------------------------------------------------------ {options_text} ------------------------------------------------------------ LATEST_FRAME_CAPTIONS (last 2 captions before question time_stamp) ------------------------------------------------------------ {latest_text} ------------------------------------------------------------ ALL_EPISODE_SUMMARIES (chronological skeleton) ------------------------------------------------------------ {all_eps_text} ------------------------------------------------------------ NEARBY_EPISODES (last {near_n} episodes with full detail) ------------------------------------------------------------ {nearby_eps_text} ------------------------------------------------------------ RETRIEVED_CONTEXT ------------------------------------------------------------ {retrieved_text if retrieved_text else "None (first round)"} """ try: response = asyncio.run(llm_config.best_model_func_raw( llm_config.best_model_name, full_prompt, system_prompt=None, history_messages=[], )) logger.info(f" LLM response: {str(response)[:200]}...") decision = _parse_llm_json(response) if isinstance(response, str) else response if decision is None: logger.error(f" JSON 解析失败: {response}") decision = {"decision": "error", "error": str(response)} except Exception as e: logger.error(f" LLM 调用失败: {e}") decision = {"decision": "error", "error": str(e)} decision['round'] = round_idx retrieval_history.append(decision) d = decision.get('decision', '') def _build_result(answer, reasoning): return { 'answer': answer, 'reasoning': reasoning, 'round': round_idx, 'mode': f'backward_{retrieval_mode}', 'retrieved_context': retrieved_contexts.copy(), 'retrieval_history': retrieval_history, } if d in ('answer', 'forced_answer'): logger.info(f" Round {round_idx}: 直接回答") return _build_result( decision.get('answer', ''), decision.get('reasoning', ''), ) elif d == 'need_retrieval': if round_idx >= max_rounds: logger.warning(f" Round {round_idx}: 已达最大轮次, 强制回答") return _build_result( decision.get('answer', ''), 'Max retrieval rounds reached', ) retrieval_query = decision.get('retrieval_query', '') logger.info(f" Round {round_idx}: 需检索, query: {retrieval_query}") try: retrieval_result = loop.run_until_complete( hyper_vg.retrieve( retrieval_query, time_span_cutoff, mode=retrieval_mode, ) ) retrieved_text_ctx = hyper_vg.format_retrieval_for_llm(retrieval_result) if not retrieved_text_ctx: retrieved_text_ctx = "No relevant facts/episodes found." logger.info( f" Retrieval done: topics={len(retrieval_result.topics)}, " f"episodes={len(retrieval_result.episodes)}, " f"facts={len(retrieval_result.facts)}" ) retrieved_contexts.append(retrieved_text_ctx) except Exception as e: logger.error(f" Retrieval failed: {e}") retrieved_contexts.append(f"Retrieval failed: {str(e)}") else: logger.error(f" 未知 decision: {d}") if round_idx >= max_rounds: return _build_result('', 'Max rounds with unknown decision') logger.warning(" 所有轮次完成但无答案") return { 'answer': '', 'reasoning': 'Retrieval done without clear answer', 'round': max_rounds, 'mode': f'backward_{retrieval_mode}', 'retrieved_context': retrieved_contexts.copy(), 'retrieval_history': retrieval_history, } # ==================== Realtime 任务 ==================== def _handle_realtime( question: str, task_type: str, temporal_clue: str, options: List[str], recent_text: str, global_text: str, llm_config: LLMConfig, ) -> dict: options_text = _format_options_block(options) full_prompt = f"""{STREAMINGBENCH_REALTIME_PROMPT} ------------------------------------------------------------ TASK_TYPE ------------------------------------------------------------ {task_type} ------------------------------------------------------------ TEMPORAL_CLUE ------------------------------------------------------------ {temporal_clue} ------------------------------------------------------------ QUESTION ------------------------------------------------------------ {question} ------------------------------------------------------------ OPTIONS ------------------------------------------------------------ {options_text} ------------------------------------------------------------ RECENT_CAPTIONS (last ~15 seconds before time_stamp) ------------------------------------------------------------ {recent_text} ------------------------------------------------------------ GLOBAL_CAPTIONS (up to time_stamp) ------------------------------------------------------------ {global_text} """ try: response = asyncio.run(llm_config.best_model_func_raw( llm_config.best_model_name, full_prompt, system_prompt=None, history_messages=[], )) logger.info(f" LLM response: {str(response)[:200]}...") parsed = _parse_llm_json(response) if isinstance(response, str) else response if parsed is None: parsed = {"answer": "", "reasoning": str(response)} except Exception as e: logger.error(f" LLM 调用失败: {e}") parsed = {"answer": "", "reasoning": str(e)} return { 'answer': parsed.get('answer', ''), 'reasoning': parsed.get('reasoning', ''), 'round': 0, 'mode': 'realtime_direct', 'retrieved_context': [], 'retrieval_history': [{"mode": "realtime_direct", **parsed}], } # ==================== Backward 任务(超图检索) ==================== def _handle_backward( question: str, task_type: str, temporal_clue: str, options: List[str], global_text: str, time_span_cutoff: str, llm_config: LLMConfig, hyper_vg: HyperVideoGraph, max_rounds: int = 2, ) -> dict: options_text = _format_options_block(options) retrieved_contexts = [] retrieval_history = [] loop = always_get_an_event_loop() for round_idx in range(1, max_rounds + 1): logger.info(f" [Backward] Round {round_idx}/{max_rounds}") retrieved_text = "" if retrieved_contexts: retrieved_text = "\n\n".join( f"[Retrieved {i+1}]\n{ctx}" for i, ctx in enumerate(retrieved_contexts) ) full_prompt = f"""{STREAMINGBENCH_BACKWARD_RETRIEVAL_PROMPT} ------------------------------------------------------------ TASK_TYPE ------------------------------------------------------------ {task_type} ------------------------------------------------------------ TEMPORAL_CLUE ------------------------------------------------------------ {temporal_clue} ------------------------------------------------------------ QUESTION ------------------------------------------------------------ {question} ------------------------------------------------------------ OPTIONS ------------------------------------------------------------ {options_text} ------------------------------------------------------------ GLOBAL_CAPTIONS (up to time_stamp) ------------------------------------------------------------ {global_text} ------------------------------------------------------------ RETRIEVED_CONTEXT ------------------------------------------------------------ {retrieved_text if retrieved_text else "None (first round)"} """ try: response = asyncio.run(llm_config.best_model_func_raw( llm_config.best_model_name, full_prompt, system_prompt=None, history_messages=[], )) logger.info(f" LLM response: {str(response)[:200]}...") decision = _parse_llm_json(response) if isinstance(response, str) else response if decision is None: logger.error(f" JSON 解析失败: {response}") decision = {"decision": "error", "error": str(response)} except Exception as e: logger.error(f" LLM 调用失败: {e}") decision = {"decision": "error", "error": str(e)} decision['round'] = round_idx retrieval_history.append(decision) d = decision.get('decision', '') def _build_result(answer, reasoning): return { 'answer': answer, 'reasoning': reasoning, 'round': round_idx, 'mode': 'backward_hyper_retrieval', 'retrieved_context': retrieved_contexts.copy(), 'retrieval_history': retrieval_history, } if d in ('answer', 'forced_answer'): logger.info(f" Round {round_idx}: 直接回答 (decision={d})") return _build_result( decision.get('answer', ''), decision.get('reasoning', ''), ) elif d == 'need_retrieval': if round_idx >= max_rounds: logger.warning(f" Round {round_idx}: 已达最大轮次, 强制回答") return _build_result( decision.get('answer', ''), 'Max retrieval rounds reached, answering with available info', ) retrieval_query = decision.get('retrieval_query', '') logger.info(f" Round {round_idx}: 需要检索, query: {retrieval_query}") try: retrieval_result = loop.run_until_complete( hyper_vg.retrieve(retrieval_query, time_span_cutoff) ) retrieved_text_ctx = hyper_vg.format_retrieval_for_llm(retrieval_result) if not retrieved_text_ctx: retrieved_text_ctx = ( "No relevant facts or episodes found in the hypergraph." ) logger.info( f" Hyper retrieval done: topics={len(retrieval_result.topics)}, " f"episodes={len(retrieval_result.episodes)}, " f"facts={len(retrieval_result.facts)}" ) retrieved_contexts.append(retrieved_text_ctx) except Exception as e: logger.error(f" Retrieval failed: {e}") retrieved_contexts.append(f"Retrieval failed: {str(e)}") else: logger.error(f" 未知 decision: {d}") if round_idx >= max_rounds: return _build_result('', 'Max rounds reached with unknown decision') logger.warning(" 所有检索轮次完成但未得到答案") return { 'answer': '', 'reasoning': 'Retrieval completed without clear answer', 'round': max_rounds, 'mode': 'backward_hyper_retrieval', 'retrieved_context': retrieved_contexts.copy(), 'retrieval_history': retrieval_history, } # ==================== 单问题处理 ==================== def process_single_question( row: dict, sample_id: str, args, ) -> dict: """处理一条 MCQ row(来自 CSV)。""" question_id = row['question_id'] task_type = row.get('task_type', '?') question = row.get('question', '') time_stamp = row.get('time_stamp', '') gt_letter = row.get('answer', '').strip().upper() options = _parse_options(row.get('options', '')) temporal_clue = row.get('temporal_clue_type', 'Concurrent') working_dir = ( f"{args.save_root}/" f"{args.datasets_type}/{sample_id}_{args.caption_model_name}" ) def _err_result(msg, err_code): return { 'question_id': question_id, 'sample_id': sample_id, 'task_type': task_type, 'temporal_clue_type': temporal_clue, 'question': question, 'options': options, 'time_stamp': time_stamp, 'answer': '', 'reasoning': msg, 'gt_letter': gt_letter, 'pred_letter': None, 'is_correct': None, 'error': err_code, } if not os.path.exists(working_dir): logger.warning(f" Working dir 不存在: {working_dir}") return _err_result(f'Working dir not found: {working_dir}', 'working_dir_not_found') fc_path = os.path.join(working_dir, "frame_captions.json") if not os.path.exists(fc_path): logger.error(f" frame_captions 不存在: {fc_path}") return _err_result( f'frame_captions not found: {fc_path}', 'frame_captions_not_found' ) with open(fc_path, 'r', encoding='utf-8') as f: fc_data = json.load(f) second_captions = fc_data.get('frame_captions', []) min_captions = fc_data.get('window_descriptions', []) # 时间过滤: 只使用 time_stamp 之前的 captions cutoff_sec = _hms_to_seconds(time_stamp) time_span_cutoff = _build_time_span_cutoff(time_stamp) filtered_sec = _filter_captions_up_to(second_captions, cutoff_sec) filtered_min = _filter_captions_up_to(min_captions, cutoff_sec) global_text = _format_captions(filtered_min) if filtered_min else _format_captions(min_captions[:5]) # 建图固定 openai text-embedding-3-small, 保持一致 llm_config = llm_config_openai # 下面原 vdb_chunks.json 选择逻辑保留但默认不触发 vdb_chunks_path = os.path.join(working_dir, "vdb_chunks.json") if os.path.exists(vdb_chunks_path): try: with open(vdb_chunks_path, 'r') as f: meta = json.load(f) if meta.get("embedding_dim", 1536) == 1024: llm_config = llm_config_bge logger.info(" embedding_dim=1024, 使用 bge-m3") else: logger.info(" embedding_dim=1536, 使用 text-embedding-3-small") except Exception: pass # ---- 4 种检索模式 路由 ---- # retrieval_mode 取值: # - "dump_all" : 不检索, 全量喂 ALL_EPISODES + ALL_FACTS (+ latest 2 captions) # - "fact_only" : 检索, 只在 fact 层做 BM25+embedding (+ episode summaries) # - "episode_fact" : 检索, episode 层入口 → 扩展到 fact # - "hierarchical" : 检索, topic → episode → fact (默认 3 阶段) # 所有模式都对 Prior + Concurrent 都适用 (打通建图后的统一推理路径) retrieval_mode = getattr(args, "retrieval_mode", "dump_all") near_n = getattr(args, "near_n", 5) from hypervideo.config import HyperVideoConfig hyper_cfg = HyperVideoConfig( embedding_propagation_mode=os.environ.get("HYPERVIDEO_PROPAGATION_MODE", "residual"), embedding_propagation_lambda=float(os.environ.get("HYPERVIDEO_PROPAGATION_LAMBDA", "0.5")), ) hyper_vg = HyperVideoGraph(working_dir=working_dir, llm=llm_config, hyper_config=hyper_cfg) stats = hyper_vg.hypergraph_builder.hypergraph.get_stats() logger.info( f" [{retrieval_mode}] task={task_type} clue={temporal_clue} " f"cutoff={time_stamp} hyper={stats}" ) if stats.get("episodes", 0) == 0: logger.warning(" 超图为空, 回退到 realtime 直接回答") recent_caps = _get_recent_captions_before( second_captions, cutoff_sec, window_seconds=15 ) result = _handle_realtime( question=question, task_type=task_type, temporal_clue=temporal_clue, options=options, recent_text=_format_captions(recent_caps), global_text=global_text, llm_config=llm_config, ) result['mode'] = 'fallback_realtime_empty_hypergraph' elif getattr(args, "use_skills", False) and task_type in ( "Counting", "Causal Reasoning", "Spatial Understanding"): # 类型化 skill (基线弱项三类), 默认关闭; skill 返回 None 则退回原模式路径 from hypervideo.streamingbench_skills import ( SKILL_DISPATCH, SKILL_DISPATCH_V2, SKILL_DISPATCH_V3) _ver = getattr(args, "skills_version", "v1") _table = {"v1": SKILL_DISPATCH, "v2": SKILL_DISPATCH_V2, "v3": SKILL_DISPATCH_V3}[_ver] if task_type not in _table: _table = {} # 该版本不接管此题型 recent_caps = _get_recent_captions_before( second_captions, cutoff_sec, window_seconds=15) _kw = dict(question=question, task_type=task_type, options_text=_format_options_block(options), recent_text=_format_captions(recent_caps), cutoff_sec=cutoff_sec, llm_config=llm_config, hyper_vg=hyper_vg) _fn = _table.get(task_type) if _fn is not None and _fn.__name__ == 'handle_sb_vlm_frames': _kw['sample_id'] = sample_id result = _fn(**_kw) if _fn is not None else None if result is None: result = _handle_backward_with_retrieval( question=question, task_type=task_type, options=options, second_captions=second_captions, cutoff_sec=cutoff_sec, llm_config=llm_config, hyper_vg=hyper_vg, max_rounds=args.max_rounds, near_n=near_n, retrieval_mode="hierarchical") elif retrieval_mode == "sb_agentic": # 真·agentic: 模型自主选工具(get_recent_episodes/search_*)、自主决定轮数 (merge2 思路) from hypervideo.agentic_solver_sb import agentic_answer as _sb_agentic_answer from hypervideo.agentic_tools import HyperToolBank _ts = _build_time_span_cutoff(_seconds_to_hms(cutoff_sec)) _bank = HyperToolBank(hyper_vg, current_time_span=_ts) _opts_text = _format_options_block(options) _loop = always_get_an_event_loop() _r = _loop.run_until_complete(_sb_agentic_answer(question, _opts_text, _bank, llm_config, max_rounds=args.max_rounds, task_type=task_type)) result = {'answer': _r.get('answer',''), 'reasoning': _r.get('reasoning',''), 'round': _r.get('rounds',0), 'mode': 'sb_agentic', 'retrieved_context': [], 'retrieval_history': [{'tools': _r.get('tools_used',[])}]} elif retrieval_mode in ("sb_s1", "sb_s2", "sb_s3", "sb_s4", "sb_s5", "sb_s6", "sb_s7", "sb_s8", "sb_s9", "sb_s10", "sb_s12", "sb_s13"): # SB 三方案: 内容用 SB 自己的函数组装(和 _handle_backward 86% 完全一致), 传给 solver。 # solver 只按 scheme 分配 固定喂 vs get_recent 工具 + agentic 决策。 from hypervideo.agentic_solver_sb3 import agentic_answer as _sb3_answer from hypervideo.agentic_tools import HyperToolBank _scheme = int(retrieval_mode.split("_s")[-1]) # 支持两位数 scheme(sb_s10) _ts = _build_time_span_cutoff(_seconds_to_hms(cutoff_sec)) _all_eps, _nearby = _build_episode_blocks(hyper_vg, _ts, near_n=near_n) # caption 窗口秒数: 命令行 --recent_window_sec 控制(网格扫 3/5/7/10...), 默认 12 保持旧行为 _rw = int(getattr(args, "recent_window_sec", 0) or 12) _recent_cap = _format_captions(_get_recent_captions_before(second_captions, cutoff_sec, window_seconds=_rw)) _bank = HyperToolBank(hyper_vg, current_time_span=_ts) _opts_text = _format_options_block(options) # s13(SB版rt3): 固定喂通道B当下结构化感知(单变量, 比s7多一块) _cur_perc = "" if _scheme == 13: try: _cur_perc = _bank.get_current_perception(last_sec=12.0) or "" except Exception: _cur_perc = "" _loop = always_get_an_event_loop() _r = _loop.run_until_complete(_sb3_answer(question, _opts_text, _bank, llm_config, max_rounds=args.max_rounds, task_type=task_type, scheme=_scheme, all_eps=_all_eps, nearby_ep=_nearby, recent_cap=_recent_cap, cur_perc=_cur_perc)) result = {'answer': _r.get('answer',''), 'reasoning': _r.get('reasoning',''), 'round': _r.get('rounds',0), 'mode': retrieval_mode, 'retrieved_context': [], 'retrieval_history': [{'tools': _r.get('tools_used',[])}]} elif retrieval_mode == "sb_merge2": # 方案C: OVO merge2 原版挂 SB — 底座 episode summary 骨架(固定喂) + # get_recent_episodes 工具(最近 episode summary+desc, 模型按需调) + search, 自主多轮 from hypervideo.agentic_solver_merge2 import agentic_answer as _merge2_answer from hypervideo.agentic_tools import HyperToolBank _ts = _build_time_span_cutoff(_seconds_to_hms(cutoff_sec)) _bank = HyperToolBank(hyper_vg, current_time_span=_ts) _opts_text = _format_options_block(options) _loop = always_get_an_event_loop() _r = _loop.run_until_complete(_merge2_answer(question, _opts_text, _bank, llm_config, max_rounds=args.max_rounds)) result = {'answer': _r.get('answer',''), 'reasoning': _r.get('reasoning',''), 'round': _r.get('rounds',0), 'mode': 'sb_merge2', 'retrieved_context': [], 'retrieval_history': [{'tools': _r.get('tools_used',[])}]} elif retrieval_mode == "dump_all": result = _handle_dump_all( question=question, task_type=task_type, options=options, second_captions=second_captions, cutoff_sec=cutoff_sec, llm_config=llm_config, hyper_vg=hyper_vg, ) elif retrieval_mode in ("fact_only", "episode_fact", "hierarchical"): result = _handle_backward_with_retrieval( question=question, task_type=task_type, options=options, second_captions=second_captions, cutoff_sec=cutoff_sec, llm_config=llm_config, hyper_vg=hyper_vg, max_rounds=args.max_rounds, near_n=near_n, retrieval_mode=retrieval_mode, ) elif retrieval_mode == "merge2": # merge2 适配: agentic 自主检索(hierarchical 底层) + RECENT 喂最近 ~12s 帧 caption(不只2帧) result = _handle_backward_with_retrieval( question=question, task_type=task_type, options=options, second_captions=second_captions, cutoff_sec=cutoff_sec, llm_config=llm_config, hyper_vg=hyper_vg, max_rounds=args.max_rounds, near_n=near_n, retrieval_mode="hierarchical", recent_window_sec=12, ) else: logger.error(f" 未知 retrieval_mode={retrieval_mode}, 跳过") result = { 'answer': '', 'reasoning': f'unknown retrieval_mode={retrieval_mode}', 'round': 0, 'mode': f'error_unknown_mode_{retrieval_mode}', 'retrieved_context': [], 'retrieval_history': [], } pred_letter = _extract_option_letter(str(result.get('answer', '')), options=options) is_correct = ( pred_letter is not None and gt_letter and pred_letter == gt_letter ) result.update({ 'question_id': question_id, 'sample_id': sample_id, 'task_type': task_type, 'temporal_clue_type': temporal_clue, 'question': question, 'options': options, 'time_stamp': time_stamp, 'gt_letter': gt_letter, 'pred_letter': pred_letter, 'is_correct': is_correct, }) return result # ==================== 结果保存 ==================== def save_output_results(output_results: dict, output_path: str): """保存结果 + 每任务类型 / 每 temporal_clue_type 的准确率统计""" global_correct = 0 global_total = 0 task_stats = {} clue_stats = {} for qid, r in output_results.items(): if qid == "__global_summary__": continue if r.get('is_correct') is None: continue task = r.get('task_type', 'unknown') clue = r.get('temporal_clue_type', 'unknown') for key, stats in ((task, task_stats), (clue, clue_stats)): if key not in stats: stats[key] = {'correct': 0, 'total': 0} stats[key]['total'] += 1 if r.get('is_correct'): stats[key]['correct'] += 1 global_total += 1 if r.get('is_correct'): global_correct += 1 for stats in (task_stats, clue_stats): for key in stats: s = stats[key] s['accuracy'] = s['correct'] / s['total'] if s['total'] > 0 else 0.0 output_results["__global_summary__"] = { "total_questions": global_total, "total_correct": global_correct, "accuracy": global_correct / global_total if global_total > 0 else 0.0, "per_task": task_stats, "per_temporal_clue": clue_stats, } with open(output_path, "w", encoding="utf-8") as f: json.dump(output_results, f, ensure_ascii=False, indent=2) if global_total > 0: logger.info( f"已保存结果到 {output_path} " f"(total={global_total}, correct={global_correct}, " f"accuracy={global_correct/global_total:.2%})" ) else: logger.info(f"已保存结果到 {output_path} (暂无结果)") for task in sorted(task_stats.keys()): s = task_stats[task] logger.info(f" [task] {task}: {s['correct']}/{s['total']} = {s['accuracy']:.2%}") for clue in sorted(clue_stats.keys()): s = clue_stats[clue] logger.info(f" [clue] {clue}: {s['correct']}/{s['total']} = {s['accuracy']:.2%}") # ==================== 主入口 ==================== def _parse_sample_id_from_qid(question_id: str) -> str: """'Real-Time Visual Understanding_sample_1_1' -> 'sample_1'""" # qid 里有下划线和连字符, 找最后一个形如 sample_ 的部分 m = re.search(r'sample_(\d+)', question_id) if m: return f"sample_{m.group(1)}" return "" if __name__ == "__main__": parser = argparse.ArgumentParser( description="StreamingBench RTVU HyperVideo 推理与评估" ) parser.add_argument( "--csv_path", type=str, default="/mnt/tokyo-ai/gst/StreamingBench-/StreamingBench/Real_Time_Visual_Understanding.csv", help="官方 MCQ CSV 路径", ) parser.add_argument( "--save_root", type=str, default="/mnt/tokyo-ai/gst/GST_EGOSERVE/all_results", help="建图结果根目录(与 streamingbench_hyper_processing.py 保持一致)", ) parser.add_argument( "--datasets_type", type=str, default="streamingbench_rt_full_qwenapi", ) parser.add_argument("--caption_model_name", type=str, default="qwen_api") parser.add_argument( "--output_path", type=str, default="/mnt/tokyo-ai/gst/GST_EGOSERVE/output_results_streamingbench_rtvu_hyper.json", ) parser.add_argument("--max_rounds", type=int, default=1) parser.add_argument( "--recent_window_sec", type=int, default=12, help="sb_s* 方案: RECENT_CAPTIONS 取问题时刻前 N 秒的帧 caption (网格扫 3/5/7/10), 默认12", ) parser.add_argument( "--retrieval_mode", type=str, default="sb_s1", choices=["dump_all", "fact_only", "episode_fact", "hierarchical", "merge2", "sb_agentic", "sb_merge2", "sb_s1", "sb_s2", "sb_s3", "sb_s4", "sb_s5", "sb_s6", "sb_s7", "sb_s8", "sb_s9", "sb_s10", "sb_s12", "sb_s13"], help="4 种推理方式: dump_all (不检索, 全量喂); fact_only (只检索 fact); " "episode_fact (episode→fact); hierarchical (topic→episode→fact, 默认 3 阶段)", ) parser.add_argument( "--near_n", type=int, default=5, help="近 N 个 episode 给完整 summary+description (其余只 summary)", ) parser.add_argument('--cuda', type=str, default='0') parser.add_argument( '--only_qids', type=str, default=None, help="仅处理指定 question_id, 分号分隔", ) parser.add_argument( '--skills_version', type=str, default='v1', choices=['v1','v2','v3'], help="v1=文本skill; v2=Counting/Spatial 走 VLM 看帧 (Qwen3-VL)") parser.add_argument( '--use_skills', action='store_true', help="Counting/Causal/Spatial 走类型化 skill (见 streamingbench_skills.py). " "默认 False, 原模式路径不变") parser.add_argument( '--only_sample_ids', type=str, default=None, help="仅处理指定 sample 数字 id, 逗号分隔, 如 '1,2,3'", ) parser.add_argument( '--only_clue', type=str, default=None, help="仅处理指定 temporal_clue_type (Prior / Concurrent)", ) parser.add_argument( '--answer_model', type=str, default='gpt-5-mini', help="LLM 推理模型. 候选: gpt-4.1-mini (default) / gpt-5.4-nano / gpt-5.4-mini", ) parser.add_argument( '--propagation_mode', type=str, default='residual', choices=['residual', 'hypermem', 'none'], help="嵌入传播: residual (默认) / hypermem / none", ) parser.add_argument( '--propagation_lambda', type=float, default=0.5, ) args = parser.parse_args() os.environ["HYPERVIDEO_ANSWER_MODEL"] = args.answer_model os.environ["HYPERVIDEO_PROPAGATION_MODE"] = args.propagation_mode os.environ["HYPERVIDEO_PROPAGATION_LAMBDA"] = str(args.propagation_lambda) llm_config_openai.best_model_name = args.answer_model llm_config_bge.best_model_name = args.answer_model logger.info(f"[args] answer_model={args.answer_model} propagation_mode={args.propagation_mode} lambda={args.propagation_lambda}") os.environ["CUDA_VISIBLE_DEVICES"] = args.cuda logger.info(f"CUDA_VISIBLE_DEVICES={args.cuda}") # OPENAI key: 从 .env 加载 (不再硬编码) if not os.environ.get("OPENAI_API_KEY"): try: from dotenv import load_dotenv load_dotenv("/mnt/tokyo-ai/gst/GST_EGOSERVE/.env") except ImportError: pass if not os.environ.get("OPENAI_API_KEY"): raise RuntimeError("OPENAI_API_KEY 未设置. 请确认 /mnt/tokyo-ai/gst/GST_EGOSERVE/.env") # 读 CSV with open(args.csv_path, 'r', encoding='utf-8') as f: reader = csv.DictReader(f) all_rows = list(reader) logger.info(f"共加载 {len(all_rows)} 条 MCQ") # 过滤 if args.only_qids: wanted = {s.strip() for s in args.only_qids.split(';') if s.strip()} all_rows = [r for r in all_rows if r['question_id'] in wanted] logger.info(f"按 --only_qids 过滤后剩余 {len(all_rows)} 条") if args.only_sample_ids: wanted = {s.strip() for s in args.only_sample_ids.split(',') if s.strip()} all_rows = [ r for r in all_rows if _parse_sample_id_from_qid(r['question_id']).split('_')[-1] in wanted ] logger.info(f"按 --only_sample_ids 过滤后剩余 {len(all_rows)} 条") if args.only_clue: all_rows = [r for r in all_rows if r.get('temporal_clue_type') == args.only_clue] logger.info(f"按 --only_clue={args.only_clue} 过滤后剩余 {len(all_rows)} 条") # 按 sample 分组, 方便排序调试 by_sample = defaultdict(list) for r in all_rows: sid = _parse_sample_id_from_qid(r['question_id']) by_sample[sid].append(r) # 断点续传 output_results = {} if os.path.exists(args.output_path): try: with open(args.output_path, 'r', encoding='utf-8') as f: output_results = json.load(f) logger.info(f"加载已有结果: {len(output_results)} 条 ({args.output_path})") except Exception as e: logger.warning(f"加载旧结果失败: {e}, 从头开始") output_results = {} _ERROR_PATTERNS = ( "RetryError", "RateLimitError", "APIError", "TimeoutError", "ConnectionError", "Retrieval failed", "checkpoint_not_found", "working_dir_not_found", ) def _is_error_result(r: dict) -> bool: for field in ("reasoning", "error"): v = r.get(field) if isinstance(v, str): for pat in _ERROR_PATTERNS: if pat in v: return True return False t_all = time.time() processing_times = [] total_q = len(all_rows) for loop_idx, row in enumerate(all_rows): qid = row['question_id'] sid = _parse_sample_id_from_qid(qid) if qid in output_results and qid != "__global_summary__": existing = output_results[qid] if existing.get('is_correct') is not None and not _is_error_result(existing): logger.info(f"[{loop_idx+1}/{total_q}] {qid} 已完成, 跳过") continue else: logger.info(f"[{loop_idx+1}/{total_q}] {qid} 有错误, 重新处理") t0 = time.time() logger.info( f"[{loop_idx+1}/{total_q}] Processing qid={qid} sample={sid} " f"task={row.get('task_type')} clue={row.get('temporal_clue_type')}" ) logger.info(f" Q: {row.get('question', '')[:120]}") try: result = process_single_question(row, sid, args) output_results[qid] = result dt = time.time() - t0 processing_times.append(dt) logger.info( f"[{loop_idx+1}/{total_q}] {qid} done | time={dt:.1f}s | " f"pred={result.get('pred_letter')} gt={result.get('gt_letter')} | " f"correct={result.get('is_correct')} | " f"mode={result.get('mode')} round={result.get('round')}" ) if (loop_idx + 1) % 10 == 0: save_output_results(output_results, args.output_path) except Exception as e: dt = time.time() - t0 logger.error(f"[{loop_idx+1}/{total_q}] {qid} 失败: {e} (time={dt:.1f}s)") output_results[qid] = { 'question_id': qid, 'sample_id': sid, 'task_type': row.get('task_type', ''), 'temporal_clue_type': row.get('temporal_clue_type', ''), 'question': row.get('question', ''), 'options': _parse_options(row.get('options', '')), 'time_stamp': row.get('time_stamp', ''), 'answer': '', 'reasoning': str(e), 'gt_letter': row.get('answer', '').strip().upper(), 'pred_letter': None, 'is_correct': None, 'error': str(e), } save_output_results(output_results, args.output_path) total_time = time.time() - t_all gs = output_results.get("__global_summary__", {}) logger.info(f"\n{'=' * 80}") logger.info(f"StreamingBench RTVU HyperVideo 推理完成!") logger.info(f"{'=' * 80}") logger.info(f" 总耗时: {total_time:.1f}s ({total_time/60:.2f} min)") logger.info(f" Total: {gs.get('total_questions', 0)}") logger.info(f" Correct: {gs.get('total_correct', 0)}") logger.info(f" Accuracy: {gs.get('accuracy', 0):.2%}") if processing_times: logger.info( f" Avg: {sum(processing_times)/len(processing_times):.2f}s/question" ) logger.info(f" Fastest: {min(processing_times):.2f}s") logger.info(f" Slowest: {max(processing_times):.2f}s") logger.info(f" Results: {args.output_path}") logger.info(f"{'=' * 80}\n")