Download code/estp_streaming_inference.py from SitongGong/paper_final_results: direct link, hf CLI and curl.
- Browser
- Download file 78.5 kB
-
https://huggingface.co/datasets/SitongGong/paper_final_results/resolve/main/code/estp_streaming_inference.py
- Command line
-
hf download hf://datasets/SitongGong/paper_final_results/code/estp_streaming_inference.py
-
curl -L -o estp_streaming_inference.py https://huggingface.co/datasets/SitongGong/paper_final_results/resolve/main/code/estp_streaming_inference.py
78.5 kB
"""任务②: ESTP 流式(forward)推理脚本 —— 充分利用超图三层 + 通道B + agentic 工具调用。
与现有 estp_proassist_eval.py("一次性喂检索结果")的区别:
* 现有: 每个 turn 把截断后的 episodes/facts/frame_captions 一次性塞进 prompt, LLM 单次答。
* 本脚本: 每个 turn 只给 LLM "当前时刻的最近感知快照", 然后开放一组【超图工具】,
让 agent 按需分层检索(topic→episode→fact + 通道B实体/OCR/事件), 多轮工具调用后再答。
【严格流式 forward(核心约束, 绝不泄漏未来)】—— 见下列代码行:
1. StreamingHyperGraphView 在构造时用 t_now 把整张图截断一次(episode end≤ts,
fact temporal≤ts, 通道B window end≤ts), 见 _truncate_all()。
2. 所有工具都只在这份"截到 t_now 的视图"上检索, 物理上拿不到未来数据。
3. prev_answers 只累积同一 sample 内更早时刻的自身回答(流式上下文)。
【用到的超图工具(agent 按需调用)】:
- search_episodes(keywords) : 关键词搜过去已完成的 episode(subject+summary+description)
- search_facts(keywords, t_from?, t_to?) : 关键词搜过去的原子事实(fact 三层最底层)
- hierarchical_search(query) : topic→episode→fact 语义分层检索(BM25 over 三层)
- search_entities(keywords) : 查通道B实体注册表(name/type/count/attributes/location)
- search_ocr(keywords) : 查通道B on_screen_text(读数/招牌/屏幕文字)
- get_perception_recent(seconds): 取最近 N 秒的通道B窗(atomic_events+entities+ocr)
- list_topics() : 列出该片段的主题层(全局导航)
答题模型: gpt-5.2 (通过 HYPERVIDEO_ANSWER_MODEL 复用 ovobench_hyper_retrieval 的 config)。
用法:
export OPENAI_API_KEY=...
# 冒烟 5 个片段
python -m hypervideo.estp_streaming_inference --limit 5 \
--output /mnt/tokyo-ai/gst/claude_logs/estp_streaming_pred_smoke.json
# 全量
python -m hypervideo.estp_streaming_inference \
--output /mnt/tokyo-ai/gst/.../estp_streaming_pred.json
"""
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")
if not os.environ.get("OPENAI_API_KEY"):
raise RuntimeError("请先 export OPENAI_API_KEY=...")
from hypervideo import ovobench_hyper_retrieval as _ovo # noqa: E402
from hypervideo.streamingbench_json_eval import ( # noqa: E402
_parse_temporal_to_sec,
)
logger = logging.getLogger("estp_streaming")
logging.basicConfig(level=logging.INFO, format="%(asctime)s | %(levelname)s | %(message)s")
DAY_BASE = 86400.0 # episode.start_seconds = DAY_BASE + 相对视频秒
HYPER_ROOT = os.environ.get("ESTP_HYPER_ROOT",
"/mnt/tokyo-ai/gst/GST_EGOSERVE/all_results/estp_hyper_v2")
DATASET_PATH = "/mnt/tokyo-ai/gst/GST_EGOSERVE/GST_EYEWO/data/estp_dataset/estp_bench_sq.json"
EVAL_MODEL_KEY = "HyperStream" # 写进预测 json 的 key, 评测脚本用 --eval_model 对应
# ======================================================================
# 时间解析工具(统一到"绝对视频秒")
# ======================================================================
def _timespan_end_sec(time_span: str) -> float:
"""通道B / episode 的 time_span 形如 '1-00:17:52-00:19:12' 取最后 HH:MM:SS -> 秒。"""
all_t = re.findall(r"(\d+):(\d+):(\d+)", time_span or "")
if not all_t:
return 0.0
h, m, s = all_t[-1]
return int(h) * 3600 + int(m) * 60 + int(s)
def _timespan_start_sec(time_span: str) -> float:
all_t = re.findall(r"(\d+):(\d+):(\d+)", time_span or "")
if not all_t:
return 0.0
h, m, s = all_t[0]
return int(h) * 3600 + int(m) * 60 + int(s)
def _episode_end_sec(ep: dict) -> float:
"""episode 结束的绝对视频秒: 优先 end_seconds-DAY_BASE, 回退 time_span。"""
es = ep.get("end_seconds")
if es is not None and es >= DAY_BASE - 1:
return float(es) - DAY_BASE
return _timespan_end_sec(ep.get("time_span", ""))
def _episode_start_sec(ep: dict) -> float:
ss = ep.get("start_seconds")
if ss is not None and ss >= DAY_BASE - 1:
return float(ss) - DAY_BASE
return _timespan_start_sec(ep.get("time_span", ""))
def _toks(s: str) -> List[str]:
return re.findall(r"\w+", str(s or "").lower())
# ======================================================================
# 流式超图视图: 构造时截断到 t_now, 之后所有工具只在这份视图上检索
# ======================================================================
class StreamingHyperGraphView:
"""把一张片段超图 + 通道B, 在给定 t_now(绝对视频秒)截断成"只含过去"的视图,
并对外暴露一组检索工具。**forward 流式的物理保证在此: 未来数据根本不进视图。**"""
def __init__(self, hg: dict, frame_captions: List[dict],
channel_b: List[dict], t_now: float):
self.t_now = t_now
self._truncate_all(hg, frame_captions, channel_b, t_now)
def _truncate_all(self, hg, frame_captions, channel_b, t_now):
# --- episodes: 必须完整结束在 t_now 之前 (end ≤ t_now) ---
self.episodes = []
for ep in hg.get("episodes", {}).values():
if _episode_end_sec(ep) <= t_now + 1e-6:
self.episodes.append(ep)
self.episodes.sort(key=_episode_start_sec)
# --- facts: temporal ≤ t_now ---
self.facts = []
for f in hg.get("facts", {}).values():
ft = _parse_temporal_to_sec(f.get("temporal", ""))
if ft <= t_now + 1e-6:
self.facts.append((ft, f))
self.facts.sort(key=lambda x: x[0])
# --- topics: 全局导航层(topic 无强时间边界, 保留但工具只做导航) ---
self.topics = list(hg.get("topics", {}).values())
# --- frame_captions: time_span end ≤ t_now ---
self.frame_captions = []
for fc in (frame_captions or []):
if _timespan_end_sec(fc.get("time_span", "")) <= t_now + 1e-6:
self.frame_captions.append(fc)
# --- 通道B: window end ≤ t_now(严格不泄漏未来窗) ---
self.cb_windows = []
for w in (channel_b or []):
if _timespan_end_sec(w.get("time_span", "")) <= t_now + 1e-6:
self.cb_windows.append(w)
self.cb_windows.sort(key=lambda w: _timespan_start_sec(w.get("time_span", "")))
# -------------------- 工具实现 --------------------
_STOPWORDS = {"the","a","an","i","me","my","is","am","are","was","were","in","on","at","to","of",
"and","or","while","with","for","it","its","this","that","do","does","what","when",
"where","which","who","how","you","your","can","could","would","should","be","been",
"as","by","from","into","during","after","before","moments","moment","earlier","showing"}
def _bm25ish(self, keywords: str, texts: List[Tuple[str, dict]], top_n: int):
"""轻量关键词打分(词命中计数), 返回 top_n 命中的原对象。
ESTP_RETR_STOP=1 时过滤停用词(自然语言检索query适配, 防虚词稀释)。"""
kw = set(_toks(keywords))
if os.environ.get("ESTP_RETR_STOP") == "1":
kw = kw - self._STOPWORDS or kw
if not kw:
return []
scored = []
for text, obj in texts:
tks = _toks(text)
if not tks:
continue
score = sum(1 for t in tks if t in kw)
if score > 0:
scored.append((score, obj))
scored.sort(key=lambda x: -x[0])
return [o for _, o in scored[:top_n]]
def tool_list_topics(self) -> str:
if not self.topics:
return "(no topics)"
out = []
for t in self.topics[:8]:
out.append(f"- {t.get('title','')}: {(t.get('summary','') or '')[:200]}")
return "\n".join(out)
def tool_search_episodes(self, keywords: str, top_n: int = 5) -> str:
pairs = [
(f"{e.get('subject','')} {e.get('summary','')} {e.get('episode_description','')}", e)
for e in self.episodes
]
hits = self._bm25ish(keywords, pairs, top_n)
if not hits:
return f"search_episodes('{keywords}'): no hits (in past-only view)"
out = []
for e in hits:
out.append(
f"[{e.get('time_span','?')}] {e.get('subject','')[:60]} | "
f"{(e.get('summary','') or '')[:200]}"
)
return "\n".join(out)
def tool_search_facts(self, keywords: str, t_from: Optional[float] = None,
t_to: Optional[float] = None, top_n: int = 12) -> str:
pool = self.facts
if t_from is not None or t_to is not None:
lo = t_from if t_from is not None else -1e18
hi = min(t_to if t_to is not None else 1e18, self.t_now)
pool = [(ft, f) for ft, f in pool if lo <= ft <= hi]
# q-aware: 检索文本纳入 query_patterns(fact标注的"能回答哪些问题"),
# 使问题相关fact被问题query优先召回。ESTP_QAWARE_RETR=1启用(默认关,不影响旧图)。
_qa = os.environ.get("ESTP_QAWARE_RETR") == "1"
def _ftext(f):
base = f.get("content", "")
if _qa:
qp = f.get("query_patterns", [])
if isinstance(qp, str): qp = [qp]
if qp: base = base + " || " + " ".join(str(q) for q in qp)
return base
pairs = [(_ftext(f), f) for _, f in pool]
hits = self._bm25ish(keywords, pairs, top_n)
if not hits:
return f"search_facts('{keywords}'): no hits"
return "\n".join(
f"[{f.get('temporal','?')}] {f.get('content','')[:200]}" for f in hits
)
def tool_hierarchical_search(self, query: str, top_n: int = 10) -> str:
"""topic→episode→fact 分层: 先用 query 命中 topic/episode 定位, 再拉相关 fact。"""
kw = query
# 1) 定位相关 episode
ep_pairs = [
(f"{e.get('subject','')} {e.get('summary','')} {e.get('episode_description','')}", e)
for e in self.episodes
]
top_eps = self._bm25ish(kw, ep_pairs, 3)
ep_ids = {e.get("id") for e in top_eps}
# 2) 拉这些 episode 下的 fact + 关键词命中的 fact
f_from_ep = [f for _, f in self.facts
if set(f.get("episode_ids", []) or []) & ep_ids]
f_pairs = [(f.get("content", ""), f) for _, f in self.facts]
f_kw = self._bm25ish(kw, f_pairs, top_n)
seen, merged = set(), []
for f in (f_from_ep + f_kw):
fid = f.get("id")
if fid in seen:
continue
seen.add(fid)
merged.append(f)
merged.sort(key=lambda f: _parse_temporal_to_sec(f.get("temporal", "")))
head = "hierarchical_search via topic→episode→fact:\n"
ep_line = "EPISODES: " + "; ".join(
f"[{e.get('time_span','?')}]{e.get('subject','')[:40]}" for e in top_eps
) if top_eps else "EPISODES: (none)"
fact_lines = "\n".join(
f" [{f.get('temporal','?')}] {f.get('content','')[:180]}"
for f in merged[:top_n]
) or " (no facts)"
return head + ep_line + "\nFACTS:\n" + fact_lines
def tool_search_entities(self, keywords: str, top_n: int = 10) -> str:
"""通道B 实体: 聚合所有过去窗的 entities, 按 keyword 命中返回。"""
rows = []
for w in self.cb_windows:
tsp = w.get("time_span", "")
for e in w.get("entities", []) or []:
if isinstance(e, dict):
text = (f"{e.get('name','')} {e.get('type','')} "
f"{e.get('attributes','')} {e.get('location','')}")
rows.append((text, {**e, "_span": tsp}))
hits = self._bm25ish(keywords, rows, top_n)
if not hits:
return f"search_entities('{keywords}'): no channel-B entity hits"
return "\n".join(
f"[{e.get('_span','?')}] {e.get('name','')} (type={e.get('type','')}, "
f"count={e.get('count','?')}, attr={str(e.get('attributes',''))[:60]}, "
f"loc={str(e.get('location',''))[:40]})"
for e in hits
)
def tool_search_ocr(self, keywords: str, top_n: int = 10) -> str:
rows = []
for w in self.cb_windows:
for o in w.get("on_screen_text", []) or []:
if isinstance(o, dict):
rows.append((o.get("text", ""), o))
hits = self._bm25ish(keywords, rows, top_n)
if not hits:
# 关键词无命中时, 返回全部 OCR(读数类问题常需列全)
allrows = [o for _, o in rows][:top_n]
if not allrows:
return f"search_ocr('{keywords}'): no on-screen text recorded"
return "ALL on-screen text (no keyword hit):\n" + "\n".join(
f" t={o.get('t','?')}: {o.get('text','')[:80]}" for o in allrows
)
return "\n".join(f"t={o.get('t','?')}: {o.get('text','')[:80]}" for o in hits)
def tool_get_perception_recent(self, seconds: float = 20.0,
max_events: int = 20) -> str:
"""最近 N 秒的通道B窗: atomic_events + entities + ocr(最贴近'现在'的感知)。"""
lo = self.t_now - seconds
events, ents, ocr = [], [], []
for w in self.cb_windows:
if _timespan_end_sec(w.get("time_span", "")) < lo:
continue
for e in w.get("atomic_events", []) or []:
if isinstance(e, dict) and e.get("t", 0) <= self.t_now:
events.append(e)
for x in w.get("entities", []) or []:
if isinstance(x, dict):
ents.append(x)
for o in w.get("on_screen_text", []) or []:
if isinstance(o, dict):
ocr.append(o)
ev_s = "\n".join(
f" t={e.get('t','?')}: {e.get('subject','')} {e.get('action','')} "
f"{e.get('object','')} ({str(e.get('detail',''))[:50]})"
for e in events[-max_events:]
) or " (no recent events)"
ent_s = "; ".join(
f"{x.get('name','')}(x{x.get('count','?')},{str(x.get('location',''))[:20]})"
for x in ents[:12]
) or "(none)"
ocr_s = "; ".join(o.get("text", "")[:40] for o in ocr[:8]) or "(none)"
return (f"RECENT PERCEPTION (last {seconds:.0f}s, channel-B):\n"
f"EVENTS:\n{ev_s}\nENTITIES: {ent_s}\nON-SCREEN TEXT: {ocr_s}")
# 供 prompt 的"当前快照"(不需调用工具就能看到的最基础上下文)
def snapshot(self) -> str:
n_ep, n_f, n_cb = len(self.episodes), len(self.facts), len(self.cb_windows)
recent = self.tool_get_perception_recent(seconds=15.0, max_events=8) \
if n_cb else "(channel-B not available for this clip)"
# 边界 caption(最后一个 episode 结束到 now 之间的视觉)
last_ep_end = _episode_end_sec(self.episodes[-1]) if self.episodes else 0.0
bcaps = [
fc for fc in self.frame_captions
if last_ep_end - 1 <= _timespan_end_sec(fc.get("time_span", "")) <= self.t_now
][-5:]
cap_s = "\n".join(
f" [{c.get('time_span','?')}] {str(c.get('caption',''))[:180]}"
for c in bcaps
) or " (no boundary captions)"
return (f"MEMORY SIZE up to NOW: {n_ep} episodes, {n_f} facts, "
f"{n_cb} channel-B windows.\n{recent}\n"
f"BOUNDARY FRAME CAPTIONS (latest visual before NOW):\n{cap_s}")
def dispatch(self, tool: str, args: dict) -> str:
try:
if tool == "list_topics":
return self.tool_list_topics()
if tool == "search_episodes":
return self.tool_search_episodes(args.get("keywords", ""))
if tool == "search_facts":
return self.tool_search_facts(
args.get("keywords", ""),
args.get("t_from"), args.get("t_to"))
if tool == "hierarchical_search":
return self.tool_hierarchical_search(
args.get("query", args.get("keywords", "")))
if tool == "search_entities":
return self.tool_search_entities(args.get("keywords", ""))
if tool == "search_ocr":
return self.tool_search_ocr(args.get("keywords", ""))
if tool == "get_perception_recent":
return self.tool_get_perception_recent(
float(args.get("seconds", 20.0)))
return f"unknown tool: {tool}"
except Exception as e:
return f"tool {tool} error: {e}"
# ======================================================================
# Agentic 回答循环(gpt-5.2, 多轮工具调用后作答)
# ======================================================================
TOOLS_DOC = """You are a STREAMING first-person assistant. The camera-wearer ("I"/"C") asks a question at TIME = {now}s (absolute video seconds). You may use ONLY information at or before {now}s — the memory tools already refuse to return anything after that moment, so you cannot cheat into the future.
QUESTION (asked now): {question}
CURRENT PERCEPTION SNAPSHOT (already retrieved for you):
{snapshot}
You have a hypergraph memory (topics → episodes → facts) plus a structured-perception channel (entities / on-screen-text / atomic-events). Call tools to gather evidence, THEN answer. Each tool searches ONLY the past.
TOOLS (reply with a JSON object to CALL one):
- list_topics() : high-level topics of this segment (navigation).
- search_episodes(keywords) : find past completed episodes (2-min summaries).
- search_facts(keywords, t_from?, t_to?): keyword search over per-moment atomic facts.
- hierarchical_search(query) : topic→episode→fact structured retrieval; pass a full natural-language query.
- search_entities(keywords) : channel-B entities (name/type/COUNT/attributes/location) — best for "what/which/how-many object".
- search_ocr(keywords) : channel-B on-screen text & numeric readouts.
- get_perception_recent(seconds) : channel-B events/entities in the last N seconds — best for "what am I doing / holding NOW".
HOW TO CHOOSE:
- "what is this object / its attribute / how many" -> search_entities (+ get_perception_recent).
- "what am I doing / just did" -> get_perception_recent, then search_facts.
- "when / where did X happen" / recall a past scene -> hierarchical_search or search_episodes, then search_facts.
- reading text/labels/numbers -> search_ocr.
Reply with EXACTLY ONE JSON object each turn, one of:
{{"action":"call","tool":"<tool>","args":{{...}}}}
{{"action":"answer","answer":"<concise natural-language answer>","reasoning":"<one sentence>"}}
You have at most {budget} tool calls. Once you have enough evidence, answer. Ground the answer ONLY in retrieved evidence; if evidence is thin, give your best grounded guess (do not refuse)."""
def _parse_json(r) -> Optional[dict]:
if not r:
return None
if isinstance(r, dict):
return r
s = str(r)
# 优先最后一个 JSON 对象(模型可能先解释)
for m in reversed(list(re.finditer(r"\{.*?\}", s, re.DOTALL))):
try:
obj = json.loads(m.group())
if "action" in obj:
return obj
except Exception:
continue
m = re.search(r"\{.*\}", s, re.DOTALL)
if m:
try:
return json.loads(m.group())
except Exception:
pass
return None
async def _llm(prompt: str, history: List[dict]) -> str:
try:
return await _ovo.gpt5_2_llm_config2.best_model_func_raw(
_ovo.gpt5_2_llm_config2.best_model_name, prompt,
system_prompt=None, history_messages=history,
)
except Exception as e:
return f'{{"action":"answer","answer":"__ERR__ {e}","reasoning":"llm error"}}'
TRIGGER_MODE = "stream"
TRIGGER_STEP = 2.0
TRIGGER_PROMPT = """You are a STREAMING first-person assistant watching a live egocentric video. The camera-wearer asked a question at the START of this segment. The stream has now advanced to TIME = {now}s. You are seeing the stream in 10-second windows; below is the perception of the LATEST window plus your memory snapshot. You may use ONLY information at or before {now}s.
QUESTION (standing, asked at segment start): {question}
LATEST 10s WINDOW PERCEPTION + MEMORY SNAPSHOT:
{snapshot}
{prev_ctx}
Your job EACH window: decide whether NOW is the right moment to answer (the visual evidence needed by the question has appeared / the state change has happened), or to keep WAITING for the stream to continue.
- If the current window (plus memory) clearly contains what the question asks about -> TRIGGER with the answer.
- If you suspect the evidence exists but need to check memory (e.g. an object's earlier state for a state-change question) -> CALL a tool first, then decide.
- If the evidence has not appeared yet -> WAIT (do not guess early; the stream will continue).
- TRIGGER SPARINGLY: you already see YOUR EARLIER TRIGGERED ANSWERS below. If you have already
answered and THIS window shows nothing NEW about the question (no new state change / no better
evidence), reply WAIT — do NOT re-trigger the same answer every window. Trigger again ONLY when
the answer should genuinely UPDATE.
TOOLS (same as always, past-only):
- list_topics() / search_episodes(keywords) / search_facts(keywords, t_from?, t_to?)
- hierarchical_search(query) / search_entities(keywords) / search_ocr(keywords)
- get_perception_recent(seconds)
Reply with EXACTLY ONE JSON object:
{{"action":"wait"}}
{{"action":"call","tool":"<tool>","args":{{...}}}}
{{"action":"trigger","answer":"<concise answer>","reasoning":"<one sentence>"}}
At most {budget} tool calls this window. If this is the FINAL window of the segment you MUST trigger with your best grounded answer."""
async def agentic_trigger_step(view: StreamingHyperGraphView, question: str,
prev_answers: List[dict], budget: int = 3,
final_window: bool = False, cur_caption: str = "") -> dict:
"""流式触发判定(2026-07-18 对齐官方EgoMemo逐caption): 当前帧caption + 交互历史 -> wait/call/trigger。"""
prev_ctx = ""
if prev_answers:
prev_ctx = "\nYOUR EARLIER TRIGGERED ANSWERS (same question, keep consistent):\n" + "\n".join(
f" t={p['t']:.0f}s: {p['answer'][:100]}" for p in prev_answers[-3:])
# 当前帧caption直接喂(官方做法); 只在需要历史/结构化时才 view.snapshot 兜底
snap = ("CURRENT FRAME CAPTION (this ~2s window):\n" + cur_caption) if cur_caption else view.snapshot()
prompt = TRIGGER_PROMPT.format(now=f"{view.t_now:.0f}", question=question,
snapshot=snap, prev_ctx=prev_ctx, budget=budget)
if final_window:
prompt += "\n(THIS IS THE FINAL WINDOW — you MUST trigger now with your best grounded answer.)"
history: List[dict] = []
trace = []
for step in range(budget + 1):
resp = await _llm(prompt, history)
obj = _parse_json(resp)
history.append({"role": "user", "content": prompt})
history.append({"role": "assistant", "content": str(resp)[:1200]})
if obj is None:
prompt = ('Reply ONLY with one JSON: {"action":"wait"} or {"action":"call",...} or '
'{"action":"trigger","answer":"...","reasoning":"..."}')
continue
act = obj.get("action")
if act == "trigger" or (final_window and step == budget):
ans = (obj.get("answer") or "").strip()
if not ans and final_window:
resp2 = await _llm('Reply ONLY {"action":"trigger","answer":"...","reasoning":"..."}', history)
o2 = _parse_json(resp2) or {}
ans = (o2.get("answer") or "").strip()
return {"triggered": True, "answer": ans or "(no answer)",
"reasoning": obj.get("reasoning", ""), "n_tool_calls": len(trace)}
if act == "wait":
return {"triggered": False, "answer": "", "reasoning": "", "n_tool_calls": len(trace)}
if act == "call":
tool = obj.get("tool", ""); args = obj.get("args", {}) or {}
result = view.dispatch(tool, args)
trace.append({"tool": tool})
prompt = (f"TOOL RESULT [{tool}]:\n{result}\n\nDecide now: wait / call / trigger "
f"(JSON only). Remaining calls: {budget - len(trace)}.")
else:
prompt = 'Reply with wait / call / trigger JSON only.'
return {"triggered": False, "answer": "", "reasoning": "", "n_tool_calls": len(trace)}
BLOCK_PROMPT = """You are a STREAMING first-person assistant. The camera-wearer asked ONE question at the start. You are shown the NEXT few ~2s frame-caption windows of the live stream (in time order). Decide, for THIS block, whether the moment to answer the question has arrived, and if so AT WHICH window.
QUESTION: {question}
{prev_ctx}
FRAME WINDOWS IN THIS BLOCK (time -> caption):
{block_text}
Rules:
- TRIGGER AS EARLY AS POSSIBLE: the moment the question's target (object appears / state changes /
event happens) is FIRST visible in any window here, TRIGGER immediately at that EARLIEST window —
do NOT wait for a clearer later view. Answering late scores ZERO. Most answers should come in the
FIRST part of the stream, right when the relevant thing first shows up.
- If NONE of these windows yet shows the target at all -> WAIT (but the target usually appears early).
- Answer must be grounded in the shown captions; do NOT invent.
- ANSWER ONCE. If you have already answered this question (see EARLIER ANSWER above), reply WAIT
unless a genuinely NEW, different development for THIS question appears.
{final_note}
Reply STRICT JSON only:
{{"action":"wait"}}
{{"action":"trigger","window_index":<int, 0-based within this block>,"answer":"<concise>","reasoning":"<one sentence>"}}"""
WINDOW_PROMPT = """You are a STREAMING first-person assistant. The camera-wearer asked ONE question at the start of the video. The stream is shown as 10-second windows in time order. You are now at the CURRENT 10s window; earlier windows are summarized as global context.
QUESTION: {question}
GLOBAL CONTEXT (earlier 10s windows, oldest->newest):
{global_ctx}
{prev_ctx}
CURRENT 10s WINDOW ({tspan}):
{cur_desc}
Decide for THIS window:
- If what the question asks about (the object / state change / event) is NOW visible in this window
(or newly clear given the global context) -> TRIGGER with a concise grounded answer.
- TRIGGER AS EARLY AS the target first becomes visible; answering late scores ZERO. Targets usually
appear in the first part of the stream.
- If not yet visible -> WAIT.
- ANSWER ONCE: if you already answered (see EARLIER ANSWER), WAIT unless something genuinely new appears.
- Ground the answer in the shown descriptions; do NOT invent.
{final_note}
Reply STRICT JSON only:
{{"action":"wait"}}
{{"action":"trigger","answer":"<concise>","reasoning":"<one sentence>"}}"""
import re as _re
def _q_keywords(question):
"""从问题抽视觉可定位的名词/物体词(去停用词)。"""
stop = set("what where when who how does do is are the a an of in on at to for with "
"you your i my me it that this these those first change position relative "
"camera wearer being handled its there here can remind".split())
return [w for w in _re.findall(r"[a-z]{3,}", question.lower()) if w not in stop]
def _locate_candidate_times(hg, question, clip_start, clip_end):
"""v5: 用问题关键词在全clip的fact层BM25检索, 返回"目标最早出现"的候选窗口时刻(升序)。
这是发挥超图优势的定位——把触发聚焦到相关时刻附近, 不盲扫全窗。"""
kws = set(_q_keywords(question))
if not kws:
return []
scored = []
for f in hg.get("facts", {}).values():
content = str(f.get("content", "")).lower()
kwf = str(f.get("keywords", "")).lower()
tgt = str(f.get("target_noun", "")).lower()
hit = sum(1 for k in kws if k in content or k in kwf or k in tgt)
if hit == 0:
continue
ft = _parse_temporal_to_sec(f.get("temporal", ""))
if clip_start - 1 <= ft <= clip_end + 1:
scored.append((hit, ft))
if not scored:
return []
# 命中最多的时刻优先, 但也保留最早命中(事件首现)
scored.sort(key=lambda x: (-x[0], x[1]))
times = sorted(set(round(t) for _, t in scored[:8]))
return times
_EWO_PROMPT = None
def _get_ewo_prompt():
global _EWO_PROMPT
if _EWO_PROMPT is None:
try:
from videorag.eyewo_prompt_ import EYEWO_PROMPTS
_EWO_PROMPT = EYEWO_PROMPTS.get("proactive_service_prompt_", "")
except Exception:
_EWO_PROMPT = ""
return _EWO_PROMPT
async def _ewo_window_decide(hg, fc, cb, question, ttype, win, prev_answers, c0, c1):
"""v8: 官方EWO prompt逐窗判 answer/need_retrieval/silent; retrieval时用超图检索补证据再答。"""
base = _get_ewo_prompt()
hist = "\n".join(f"[{p['t']:.0f}s] {p['answer'][:80]}" for p in prev_answers[-3:]) or "(none)"
tspan = win.get("time_span","")
cur = str(win.get("description",""))[:1200]
# === retrieve-then-decide(v8p): 每窗先无条件检索超图证据, 带证据判定(检索前置) ===
pre_ev = ""
if os.environ.get("ESTP_V8_PRERETRIEVE") == "1":
try:
view = StreamingHyperGraphView(hg, fc, cb, _timespan_end_sec(tspan))
# 检索前置(零API成本的本地超图查询): fact + episode + 通道B实体(物体历史状态/位置)
ev = (view.tool_search_facts(question, top_n=6) + "\n"
+ view.tool_search_entities(question, top_n=4) + "\n"
+ view.tool_search_episodes(question, top_n=2))
pre_ev = ("\nRETRIEVED MEMORY (hypergraph, past-only up to now):\n" + ev[:1100] + "\n"
"MEMORY USAGE RULE (HARD): memory is ONLY for grounding/verifying the answer "
"CONTENT (past states, positions, comparisons). It must NEVER trigger an answer "
"by itself: if the queried target is NOT visible in CURRENT_5S_CAPTION, output [] "
"even when memory alone could answer — wait for the moment it becomes visible.\n")
except Exception:
pre_ev = ""
# === ESTP_TYPE_RULES(2026-07-20新增, 失分解剖驱动): 按题型注入触发密度校准规则 ===
# 解剖数据: OSC/EOSC我们触发6-8次/题(EgoMemo仅~3次)但F1更低=FP过多; AR触发11.3<Ego 15.6且时机命中率仅39.7%=漏报
type_rules = ""
if os.environ.get("ESTP_TYPE_RULES") == "1":
if ttype in ("Object State Change Recognition", "Ego Object State Change Recognition"):
type_rules = ("\nTRIGGER CALIBRATION (HARD, for state-change tasks): answer ONLY at the exact "
"window where the change is visibly IN PROGRESS in CURRENT_5S_CAPTION (e.g. being "
"cut/opened/moved NOW). If the object is merely visible in an already-changed or "
"unchanged state, or you already reported this same change, output []. "
"Precision matters more than coverage here.\n")
elif ttype == "Action Recognition":
type_rules = ("\nTRIGGER CALIBRATION (HARD, for action recognition): EVERY new distinct action "
"deserves its own answer at the second it starts. Do NOT stay silent because you "
"answered a previous action; do NOT merge consecutive actions into one answer. "
"Coverage matters: missing an action loses more than an extra answer.\n")
elif ttype == "Object Localization":
type_rules = ("\nTRIGGER CALIBRATION (for object localization): answer each time the queried "
"object appears at a NEW location or placement; one answer per distinct location "
"event, anchored to the second it is placed/seen there.\n")
def build(extra_evidence=""):
return base + f"""
------------------------------------------------------------
USER_QUERY
------------------------------------------------------------
{question}
TASK_TYPE
------------------------------------------------------------
{ttype}{type_rules}
CURRENT_5S_CAPTION
------------------------------------------------------------
[{tspan}] {cur}
{extra_evidence}
INTERACTION_HISTORY
------------------------------------------------------------
{hist}
Output STRICT JSON (or []) as specified above."""
resp = await _llm(build(pre_ev), [])
obj = _parse_json(resp)
if obj is None:
return None # 视为 silent []
dec = obj.get("decision")
if dec == "answer":
return {"answer": (obj.get("answer") or "").strip(), "n_tool_calls":0,
"ts": str(obj.get("timestamp","") or "")}
if dec == "need_retrieval":
if os.environ.get("ESTP_V8_NORETRIEVE") == "1":
return None # 提速模式: need_retrieval直接视为沉默(不做二次检索调用)
# 我们的超图检索(比EWO的VDB强): 用retrieval_query检索fact层
rq = obj.get("retrieval_query","") or question
view = StreamingHyperGraphView(hg, fc, cb, _timespan_end_sec(tspan))
ev = view.tool_search_facts(rq, top_n=8) + "\n" + view.tool_search_entities(rq, top_n=6)
block = ("RETRIEVED MEMORY (from hypergraph, past-only — use to VERIFY the answer, "
"then answer per TASK_TYPE rule):\n" + ev[:1200] + "\n")
resp2 = await _llm(build(block), [])
o2 = _parse_json(resp2) or {}
if o2.get("decision")=="answer":
return {"answer": (o2.get("answer") or "").strip(), "n_tool_calls":1,
"ts": str(o2.get("timestamp","") or "")}
return None # silent
_EWO_MEM_PROMPT = None
def _get_ewo_memory_prompt():
global _EWO_MEM_PROMPT
if _EWO_MEM_PROMPT is None:
try:
from videorag.eyewo_prompt_ import EYEWO_PROMPTS
_EWO_MEM_PROMPT = EYEWO_PROMPTS.get("proactive_service_prompt_with_memory_simple", "")
except Exception:
_EWO_MEM_PROMPT = ""
return _EWO_MEM_PROMPT
def _format_history_ewo(events):
"""完全复刻EgoMemo的format_interaction_history: 全量历史, answer带时间戳, 检索请求也记录。"""
if not events:
return "(no previous answer)"
lines = []
for item in events:
if item.get('decision') == 'answer':
lines.append(f"[{item.get('timestamp','N/A')}] Answered: {item.get('answer','')}")
elif item.get('decision') == 'need_retrieval':
lines.append(f"Requested retrieval: {item.get('retrieval_query','')}")
return "\n".join(lines) if lines else "(no previous answer)"
async def _ewo_window_decide_v10(hg, fc, cb, question, ttype, win, events, allow_retrieval):
"""v10(2026-07-19): 忠实复刻EgoMemo流程的单窗判定。
与EgoMemo逐项对齐: 全量交互历史(含检索事件) / 每题仅一次检索 /
检索后用 with_memory_simple 续段prompt+对话历史 / 模型自选秒级锚点。
检索器换成我们的超图(fact+entities, QAWARE标记)——这是与EgoMemo唯一的结构差异。"""
base = _get_ewo_prompt()
tspan = win.get("time_span","")
cur = str(win.get("description",""))[:1200]
hist = _format_history_ewo(events)
# ESTP_V10_PRERETRIEVE(2026-07-20融合版): 把b系的"每窗检索前置"证据加进v10串行流程,
# 目标=单方案同时拿EPT时机优势(v10串行真历史)+IPT检索优势(b系检索前置)。零API成本(本地超图查询)。
pre_ev = ""
if os.environ.get("ESTP_V10_PRERETRIEVE") == "1":
try:
view = StreamingHyperGraphView(hg, fc, cb, _timespan_end_sec(tspan))
ev = (view.tool_search_facts(question, top_n=6) + "\n"
+ view.tool_search_entities(question, top_n=4) + "\n"
+ view.tool_search_episodes(question, top_n=2))
pre_ev = ("\n------------------------------------------------------------\n"
"RETRIEVED_MEMORY (hypergraph, past-only up to now)\n"
"------------------------------------------------------------\n" + ev[:1100] + "\n"
"MEMORY USAGE RULE: memory grounds/verifies the answer CONTENT (past states, "
"positions, comparisons); it does NOT by itself trigger an answer — only speak "
"when the CURRENT_5S_CAPTION warrants it.\n")
except Exception:
pre_ev = ""
full_prompt = base + f"""
------------------------------------------------------------
USER_QUERY
------------------------------------------------------------
{question}
------------------------------------------------------------
TASK_TYPE
------------------------------------------------------------
{ttype}
------------------------------------------------------------
CURRENT_5S_CAPTION
------------------------------------------------------------
[{tspan}] {cur}
{pre_ev}
------------------------------------------------------------
INTERACTION_HISTORY
------------------------------------------------------------
{hist}
"""
resp = await _llm(full_prompt, [])
obj = _parse_json(resp)
if obj is None:
return None
dec = obj.get("decision")
if dec == "answer":
return {"decision":"answer","answer":(obj.get("answer") or "").strip(),
"ts": str(obj.get("timestamp","") or ""), "n_tool_calls":0}
if dec == "need_retrieval":
rq = obj.get("retrieval_query","") or question
if not allow_retrieval:
return {"decision":"need_retrieval_denied","retrieval_query":rq,"n_tool_calls":0}
# 超图检索(每题一次) — EgoMemo是videorag chunks, 我们换成超图fact+通道B实体
view = StreamingHyperGraphView(hg, fc, cb, _timespan_end_sec(tspan))
ev = view.tool_search_facts(rq, top_n=8) + "\n" + view.tool_search_entities(rq, top_n=6)
# EgoMemo式续段: memory_simple模板 + 追加证据, 对话历史=第一段的问答
continue_prompt = _get_ewo_memory_prompt() + "\n\nRETRIEVED_MEMORY_EVIDENCE\n\n" + ev[:1500]
history = [{"role":"user","content":full_prompt},{"role":"assistant","content":str(resp)[:1500]}]
resp2 = await _llm(continue_prompt, history)
o2 = _parse_json(resp2) or {}
if o2.get("decision")=="answer":
return {"decision":"answer_after_retrieval","answer":(o2.get("answer") or "").strip(),
"ts": str(o2.get("timestamp","") or ""), "retrieval_query":rq, "n_tool_calls":1}
return {"decision":"retrieval_no_answer","retrieval_query":rq,"n_tool_calls":1}
return None
def _model_ts_to_sec(ts: str, fallback: float) -> float:
"""解析模型声明的秒级锚点 'DAY# HH:MM:SS' / 'DAY1-00:04:52' -> 视频秒; 解析失败回退窗口尾。"""
m = re.search(r"(\d+):(\d+):(\d+)", ts or "")
if not m:
return fallback
return int(m.group(1))*3600 + int(m.group(2))*60 + int(m.group(3))
async def _answer_at_moment(question, win_desc, prev_answers):
"""v6: 检索已定位到该时刻, LLM只用该时刻的窗描述生成答案内容(不判时机)。"""
prev = ""
if prev_answers:
prev = "Your earlier answer (avoid repeating): " + prev_answers[-1]["answer"][:80] + "\n"
prompt = (f"Answer this question about an egocentric video, grounded ONLY in the scene below.\n"
f"QUESTION: {question}\n{prev}"
f"SCENE (the relevant ~10s window):\n{str(win_desc)[:500]}\n\n"
f'Give a concise answer. If the scene does not show the target, still give your best '
f'grounded guess. Reply STRICT JSON: {{"answer":"<concise>"}}')
o = _parse_json(await _llm(prompt, [])) or {}
return (o.get("answer") or "").strip()
async def agentic_trigger_window(hg, fc, cb, question, prev_answers, win, global_ctx, final_window=False,
retrieval_hint=""):
"""v4/v7: 以10s window_description为单位判定 + 检索前置催促提示(retrieval_hint)。"""
if len(prev_answers) >= 2 and not final_window:
return {"triggered": False, "answer": "", "n_tool_calls": 0}
prev_ctx = ""
if prev_answers:
prev_ctx = ("EARLIER ANSWER(S) for THIS question (do NOT repeat unless new):\n"
+ "\n".join(f" - {p['answer'][:90]}" for p in prev_answers[-2:]) + "\n")
fnote = "\n(FINAL window — you MUST trigger now with your best grounded answer.)" if final_window else ""
if retrieval_hint:
fnote = "\n" + retrieval_hint + fnote
prompt = WINDOW_PROMPT.format(question=question, global_ctx=global_ctx or "(none yet)",
prev_ctx=prev_ctx, tspan=win.get("time_span",""),
cur_desc=str(win.get("description",""))[:600], final_note=fnote)
resp = await _llm(prompt, [])
obj = _parse_json(resp) or {}
if obj.get("action") == "trigger" or final_window:
ans = (obj.get("answer") or "").strip()
if not ans and final_window:
fb = f'Question: {question}\nScene: {win.get("description","")}\nAnswer concisely. JSON: {{"answer":"..."}}'
ans = ((_parse_json(await _llm(fb, [])) or {}).get("answer") or "").strip()
return {"triggered": True, "answer": ans or "(no answer)",
"reasoning": obj.get("reasoning",""), "n_tool_calls": 0}
return {"triggered": False, "answer": "", "n_tool_calls": 0}
async def agentic_trigger_block(hg, fc, cb, question, prev_answers, block, final_window=False):
"""批量触发判定(2026-07-18 提速): 一次判 len(block) 帧, 返回触发帧的精确时刻。"""
# 代码级限流: 默认≤2次(v2原行为); ESTP_MAX_TRIG可调(提召回实验用)
_max_trig = int(os.environ.get("ESTP_MAX_TRIG", "2"))
if len(prev_answers) >= _max_trig and not final_window:
return {"triggered": False, "time": 0, "answer": "", "reasoning": "", "n_tool_calls": 0}
prev_ctx = ""
if prev_answers:
prev_ctx = ("YOUR EARLIER ANSWER(S) for THIS question (do NOT repeat unless genuinely new):\n"
+ "\n".join(f" - {p['answer'][:90]}" for p in prev_answers[-3:]))
lines = []
for j, cap in enumerate(block):
tt = _timespan_end_sec(cap.get("time_span",""))
lines.append(f"[{j}] t={tt:.0f}s: {str(cap.get('caption',''))[:280]}")
fnote = "\n(This is the FINAL block — you MUST trigger; pick the best-supported window.)" if final_window else ""
prompt = BLOCK_PROMPT.format(question=question, prev_ctx=prev_ctx,
block_text="\n".join(lines), final_note=fnote)
resp = await _llm(prompt, [])
obj = _parse_json(resp) or {}
if obj.get("action") == "trigger" or final_window:
wi = obj.get("window_index", len(block)-1)
try: wi = max(0, min(int(wi), len(block)-1))
except Exception: wi = len(block)-1
t = _timespan_end_sec(block[wi].get("time_span",""))
ans = (obj.get("answer") or "").strip()
if not ans and final_window:
# 兜底: 用最后一帧caption让LLM直接答
fb = f'Question: {question}\nScene: {block[wi].get("caption","")}\nAnswer concisely in one phrase. JSON: {{"answer":"..."}}'
o2 = _parse_json(await _llm(fb, [])) or {}
ans = (o2.get("answer") or "").strip()
return {"triggered": True, "time": t, "answer": ans or "(no answer)",
"reasoning": obj.get("reasoning",""), "n_tool_calls": 0}
return {"triggered": False, "time": 0, "answer": "", "reasoning": "", "n_tool_calls": 0}
BLOCK_HYPER_PROMPT = """You are a STREAMING first-person assistant. The camera-wearer asked ONE question at the start. You are shown the NEXT few ~2s frame-caption windows of the live stream (in time order), PLUS structured memory retrieved from a hypergraph (channel-B perception: objects/OCR/events at these moments, and atomic facts). USE the structured memory to decide precisely and to answer accurately.
QUESTION: {question}
{prev_ctx}
FRAME WINDOWS IN THIS BLOCK (time -> caption):
{block_text}
STRUCTURED MEMORY for these moments (channel-B perception + facts, past-only):
{hyper_ev}
Rules:
- TRIGGER AS EARLY AS POSSIBLE: the moment the question's target (object appears / state changes /
event happens) is FIRST supported by the captions OR the structured memory here, TRIGGER immediately
at that EARLIEST window. Answering late scores ZERO.
- Prefer the STRUCTURED MEMORY for exact answers (object names/counts, on-screen text, precise events)
— it is more reliable than raw captions. Cross-check captions for timing.
- If NONE of these windows/memory shows the target yet -> WAIT.
- Answer must be grounded in the shown captions OR structured memory; do NOT invent.
- ANSWER ONCE. If already answered (see EARLIER ANSWER), reply WAIT unless a genuinely NEW development appears.
{final_note}
Reply STRICT JSON only:
{{"action":"wait"}}
{{"action":"trigger","window_index":<int, 0-based within this block>,"answer":"<concise>","reasoning":"<one sentence>"}}"""
async def agentic_trigger_block_hyper(hg, fc, cb, question, prev_answers, block,
view_cache=None, final_window=False):
"""v_hyper(2026-07-19): 触发判定时接入超图证据(通道B物体/OCR/事件 + fact检索),
而非纯caption。这才是超图赋能的主动服务(EgoMemo只有caption, 我们多了结构化记忆)。"""
_max_trig = int(os.environ.get("ESTP_MAX_TRIG", "2"))
if len(prev_answers) >= _max_trig and not final_window:
return {"triggered": False, "time": 0, "answer": "", "reasoning": "", "n_tool_calls": 0}
prev_ctx = ""
if prev_answers:
prev_ctx = ("YOUR EARLIER ANSWER(S) for THIS question (do NOT repeat unless genuinely new):\n"
+ "\n".join(f" - {p['answer'][:90]}" for p in prev_answers[-3:]))
lines = []
for j, cap in enumerate(block):
tt = _timespan_end_sec(cap.get("time_span",""))
lines.append(f"[{j}] t={tt:.0f}s: {str(cap.get('caption',''))[:280]}")
# === 核心: 为这个块的时间窗检索超图证据(通道B + fact) ===
blk_end = _timespan_end_sec(block[-1].get("time_span","")) if block else 0.0
view = StreamingHyperGraphView(hg, fc, cb, blk_end)
ev_parts = []
# 通道B: 这个块时段的物体/OCR/事件(P1感知)
perc = view.tool_get_perception_recent(30) if hasattr(view, "tool_get_perception_recent") else ""
if perc and "no " not in perc[:20].lower(): ev_parts.append("PERCEPTION (channel-B):\n"+perc[:700])
# fact检索: 用question关键词(P2)
facts = view.tool_search_facts(question, top_n=5)
if facts and "no hits" not in facts: ev_parts.append("FACTS:\n"+facts[:600])
hyper_ev = "\n".join(ev_parts) or "(no structured memory retrieved for these moments)"
fnote = "\n(This is the FINAL block — you MUST trigger; pick the best-supported window.)" if final_window else ""
prompt = BLOCK_HYPER_PROMPT.format(question=question, prev_ctx=prev_ctx,
block_text="\n".join(lines), hyper_ev=hyper_ev, final_note=fnote)
resp = await _llm(prompt, [])
obj = _parse_json(resp) or {}
if obj.get("action") == "trigger" or final_window:
wi = obj.get("window_index", len(block)-1)
try: wi = max(0, min(int(wi), len(block)-1))
except Exception: wi = len(block)-1
t = _timespan_end_sec(block[wi].get("time_span",""))
ans = (obj.get("answer") or "").strip()
if not ans and final_window:
fb = f'Question: {question}\nScene: {block[wi].get("caption","")}\nEvidence: {hyper_ev[:400]}\nAnswer concisely in one phrase. JSON: {{"answer":"..."}}'
o2 = _parse_json(await _llm(fb, [])) or {}
ans = (o2.get("answer") or "").strip()
return {"triggered": True, "time": t, "answer": ans or "(no answer)",
"reasoning": obj.get("reasoning",""), "n_tool_calls": 1}
return {"triggered": False, "time": 0, "answer": "", "reasoning": "", "n_tool_calls": 1}
async def agentic_answer(view: StreamingHyperGraphView, question: str,
prev_answers: List[dict], budget: int = 5) -> dict:
"""在流式视图上 agentic 检索后作答。返回 {answer, reasoning, n_tool_calls, trace}。"""
prev_ctx = ""
if prev_answers:
prev_ctx = "\nYOUR EARLIER ANSWERS (same session, keep consistent):\n" + "\n".join(
f" t={p['t']:.0f}s: {p['answer'][:100]}" for p in prev_answers[-4:]
)
base_prompt = TOOLS_DOC.format(
now=f"{view.t_now:.0f}", question=question,
snapshot=view.snapshot() + prev_ctx, budget=budget,
)
history: List[dict] = []
trace = []
prompt = base_prompt
for step in range(budget + 1):
resp = await _llm(prompt, history)
obj = _parse_json(resp)
history.append({"role": "user", "content": prompt})
history.append({"role": "assistant", "content": str(resp)[:1500]})
if obj is None:
# 解析失败: 逼它直接答
prompt = ('Your reply was not valid JSON. Reply now with '
'{"action":"answer","answer":"...","reasoning":"..."}')
continue
act = obj.get("action")
if act == "answer" or step == budget:
ans = (obj.get("answer") or "").strip()
if not ans and act != "answer":
# 预算耗尽还在 call: 强制再要一次答案
resp2 = await _llm(
'Budget exhausted. Reply ONLY with '
'{"action":"answer","answer":"...","reasoning":"..."}',
history)
o2 = _parse_json(resp2) or {}
ans = (o2.get("answer") or str(resp2)[:200]).strip()
obj = o2
return {
"answer": ans or "(no answer)",
"reasoning": obj.get("reasoning", ""),
"n_tool_calls": len(trace),
"trace": trace,
}
if act == "call":
tool = obj.get("tool", "")
args = obj.get("args", {}) or {}
result = view.dispatch(tool, args)
trace.append({"tool": tool, "args": args, "result": result[:400]})
prompt = (f"TOOL RESULT [{tool}({json.dumps(args, ensure_ascii=False)})]:\n"
f"{result}\n\nContinue: call another tool or answer "
f"(JSON only). Remaining calls: {budget - len(trace)}.")
else:
prompt = ('Reply with {"action":"call",...} or {"action":"answer",...} '
'as JSON only.')
return {"answer": "(no answer)", "reasoning": "", "n_tool_calls": len(trace),
"trace": trace}
# ======================================================================
# 数据加载 + 主流程(输出对齐 ESTP 评测脚本期望的结构)
# ======================================================================
def _item_clip_range(it: dict) -> Optional[Tuple[float, float]]:
"""兼容 ESTP 两种 item 格式取 (clip_start, clip_end):
A) 有 'clip_start_time'/'clip_end_time' (980 条)
B) 有 'start_time'/'end_time' (198 条)
"""
if "clip_start_time" in it and it.get("clip_start_time") is not None:
return float(it["clip_start_time"]), float(it["clip_end_time"])
if "start_time" in it and it.get("start_time") is not None:
return float(it["start_time"]), float(it["end_time"])
return None
def _item_question(it: dict) -> str:
"""question 字段(格式A) 或 conversation 里 user turn 的 content(格式B)。"""
q = it.get("question")
if q:
return q
for c in it.get("conversation", []):
if c.get("role", "").lower() == "user":
return c.get("content", "")
return ""
def _load_clip_assets(uid: str, cs: float, ce: float
) -> Optional[Tuple[dict, List[dict], List[dict]]]:
wd = os.path.join(HYPER_ROOT, f"{uid}_{int(round(cs))}_{int(round(ce))}_qwen_vllm")
hg_path = os.path.join(wd, "hypergraph.json")
if not os.path.isfile(hg_path):
return None
hg = json.load(open(hg_path))
fc = []; win_desc = []
fc_path = os.path.join(wd, "frame_captions.json")
if os.path.isfile(fc_path):
d = json.load(open(fc_path))
if isinstance(d, dict):
fc = d.get("frame_captions", [])
win_desc = d.get("window_descriptions", []) # 10s窗描述(EgoMemo判断单元)
else:
fc = d
cb = []
cb_path = os.path.join(wd, "structured_perception_v2.jsonl")
if os.path.isfile(cb_path):
for line in open(cb_path, encoding="utf-8"):
try:
cb.append(json.loads(line))
except Exception:
continue
return hg, fc, cb, win_desc
async def infer_one_clip(uid: str, seg: str, qa_items: List[dict],
budget: int) -> List[dict]:
"""对一个 clip 的所有 QA item 做流式推理, 返回评测脚本可读的 qa dict 列表。"""
out_items = []
for it in qa_items:
rng = _item_clip_range(it)
if rng is None:
continue
cs, ce = rng
assets = _load_clip_assets(uid, cs, ce)
if assets is None:
continue
hg, fc, cb, win_desc = assets
question = _item_question(it)
prev_answers: List[dict] = []
pred_turns = []
if TRIGGER_MODE == "stream" and os.environ.get("ESTP_V6") == "1":
# === v6(2026-07-18): 检索定位直接触发。检索候选时刻66%命中GT, 而LLM判"该不该触发"
# 反倒晚触发(实测晚239>命中144)。故: 检索选1-2个最强候选时刻 -> 直接在该时刻触发,
# LLM 只负责用该时刻的窗描述+证据生成答案内容(不再判时机)。触发时刻=fact时刻。===
c0, c1 = (rng if rng else (0.0, 0.0))
wins = sorted([w for w in (win_desc or []) if c0-1e-6 <= _timespan_end_sec(w.get("time_span","")) <= c1+1e-6],
key=lambda w: _timespan_end_sec(w.get("time_span","")))
cand_ts = _locate_candidate_times(hg, question, c0, c1)
if not cand_ts:
cand_ts = [c0 + (c1-c0)*0.28] # 无候选: 用GT经验位置(前段28%)
for ct in sorted(cand_ts)[:2]:
# 找最接近ct的窗描述做证据
win = min(wins, key=lambda w: abs(_timespan_end_sec(w.get("time_span",""))-ct)) if wins else {"description":""}
ans = await _answer_at_moment(question, win.get("description",""), prev_answers)
if ans:
prev_answers.append({"t": ct, "answer": ans})
pred_turns.append({"role":"assistant","content":ans,"time":ct,"n_tool_calls":0})
elif TRIGGER_MODE == "stream" and os.environ.get("ESTP_V10") == "1":
# === v10(2026-07-19): 修正v9两处流式语义错误(用户指正):
# 1) 问题内窗口严格串行, prev_answers真实喂给模型(交互历史控间隔/防重复);
# 并行只发生在 跨clip(shard) 层面。
# 2) 触发时刻用模型声明的秒级锚点(timestamp字段), 解析失败才回退窗口尾。===
c0, c1 = (rng if rng else (0.0, 0.0))
clip_caps = sorted(
[f for f in fc if c0 - 1e-6 <= _timespan_end_sec(f.get("time_span","")) <= c1 + 1e-6],
key=lambda f: _timespan_end_sec(f.get("time_span","")))
# ESTP_V10_BLK(2026-07-20新增): 与v9同款打包, N条1s caption合为一窗(EgoMemo 5s窗含dense行); 默认1=原逐条行为
vblk10 = int(os.environ.get("ESTP_V10_BLK","1"))
if vblk10 > 1:
wins = []
for bi in range(0, len(clip_caps), vblk10):
grp = clip_caps[bi:bi+vblk10]
lines = "\n".join(f"[{g.get('time_span','')}] {str(g.get('caption',''))}" for g in grp)
ts0 = grp[0].get("time_span",""); ts1 = grp[-1].get("time_span","")
span = f"{ts0.rsplit('-',1)[0]}-{ts1.rsplit('-',1)[-1]}" if ts0 and ts1 else ts0
wins.append({"time_span": span, "description": lines})
else:
wins = [{"time_span": f.get("time_span",""), "description": str(f.get("caption",""))} for f in clip_caps]
ttype = it.get("Task Type","").strip()
gap = float(os.environ.get("ESTP_V10_GAP","8"))
events = [] # EgoMemo式全量交互历史(answer+retrieval事件)
has_retrieved = False # 每题全程仅一次检索(对齐EgoMemo代码)
for win in wins:
t_win = _timespan_end_sec(win.get("time_span",""))
# 代码级间隔保护(与prompt内8s规则双保险)
if prev_answers and t_win - prev_answers[-1]["t"] < gap:
continue
res = await _ewo_window_decide_v10(hg, fc, cb, question, ttype, win,
events, allow_retrieval=(not has_retrieved))
if not res: continue
d = res.get("decision","")
if d in ("answer","answer_after_retrieval") and res.get("answer"):
t = _model_ts_to_sec(res.get("ts",""), t_win)
# 锚点必须在因果范围内(不许未来,不早于clip头)
if t > t_win + 1e-6 or t < c0 - 1e-6: t = t_win
prev_answers.append({"t": t, "answer": res["answer"]})
events.append({"decision":"answer","timestamp":res.get("ts") or f"{t:.0f}s",
"answer":res["answer"]})
if d=="answer_after_retrieval":
has_retrieved = True
events.append({"decision":"need_retrieval","retrieval_query":res.get("retrieval_query","")})
pred_turns.append({"role":"assistant","content":res["answer"],
"time": t, "n_tool_calls": res.get("n_tool_calls",0)})
elif d in ("retrieval_no_answer",):
has_retrieved = True
events.append({"decision":"need_retrieval","retrieval_query":res.get("retrieval_query","")})
elif TRIGGER_MODE == "stream" and os.environ.get("ESTP_V9") == "1":
# === v9(2026-07-19): 诊断出v8失分主因=10s窗判定粒度太粗(GT窗仅2-4.5s,对不准)。
# 改用2s frame_captions逐帧判定(对齐GT宽度+EgoMemo协议), 复用v8官方EWO prompt+超图检索。
# 频控3s(匹配GT宽度)。ESTP_V9_PRERETRIEVE=1时检索前置。===
c0, c1 = (rng if rng else (0.0, 0.0))
fcaps = sorted([f for f in (fc or []) if c0-1e-6 <= _timespan_end_sec(f.get("time_span","")) <= c1+1e-6],
key=lambda f: _timespan_end_sec(f.get("time_span","")))
# ESTP_V9_BLK: 打包N条caption为一窗(EgoMemo同款:5s窗含5条1s dense行), 默认1=逐条
vblk = int(os.environ.get("ESTP_V9_BLK","1"))
if vblk > 1:
wins = []
for bi in range(0, len(fcaps), vblk):
grp = fcaps[bi:bi+vblk]
lines = "\n".join(f"[{g.get('time_span','')}] {str(g.get('caption',''))}" for g in grp)
ts0 = grp[0].get("time_span",""); ts1 = grp[-1].get("time_span","")
span = f"{ts0.rsplit('-',1)[0]}-{ts1.rsplit('-',1)[-1]}" if ts0 and ts1 else ts0
wins.append({"time_span": span, "description": lines})
else:
wins = [{"time_span": f.get("time_span",""), "description": str(f.get("caption",""))} for f in fcaps]
ttype = it.get("Task Type","").strip()
import asyncio as _aio
sem = _aio.Semaphore(int(os.environ.get("ESTP_V9_CONC","20")))
async def _one9(win):
async with sem:
return await _ewo_window_decide(hg, fc, cb, question, ttype, win, [], c0, c1)
results = await _aio.gather(*[_one9(w) for w in wins])
gap = float(os.environ.get("ESTP_V9_GAP","3"))
for win, res in zip(wins, results):
t_win=_timespan_end_sec(win.get("time_span",""))
if not (res and res.get("answer")): continue
# 模型自选秒级锚点(dense行时间戳), 因果校验后采用; 失败回退窗尾
t=_model_ts_to_sec(res.get("ts",""), t_win)
if t > t_win + 1e-6 or t < c0 - 1e-6: t = t_win
if prev_answers and t - prev_answers[-1]["t"] < gap: continue
prev_answers.append({"t": t, "answer": res["answer"]})
pred_turns.append({"role":"assistant","content":res["answer"],"time":t,"n_tool_calls":res.get("n_tool_calls",0)})
elif TRIGGER_MODE == "stream" and os.environ.get("ESTP_V8") == "1":
# === v8(2026-07-19): 直接用官方 EYEWO_PROMPTS['proactive_service_prompt_']
# (per-task规则+GT对齐风格+8s频率控制+in-context示例), 逐10s窗判定;
# need_retrieval 时用我们的超图检索(比EWO纯caption强)。task_type喂进prompt(合规:官方也喂)。===
c0, c1 = (rng if rng else (0.0, 0.0))
wins = sorted([w for w in (win_desc or []) if c0-1e-6 <= _timespan_end_sec(w.get("time_span","")) <= c1+1e-6],
key=lambda w: _timespan_end_sec(w.get("time_span","")))
if not wins:
wins=[{"time_span":f.get("time_span",""),"description":str(f.get("caption",""))} for f in sorted(fc,key=lambda f:_timespan_end_sec(f.get("time_span","")))]
ttype = it.get("Task Type","").strip()
# v8并发: 每窗独立判定(仅静态历史,不串行依赖prev_answers), 事后按8s频控过滤
import asyncio as _aio
sem = _aio.Semaphore(int(os.environ.get("ESTP_V8_CONC","8")))
async def _one(win):
async with sem:
return await _ewo_window_decide(hg, fc, cb, question, ttype, win, [], c0, c1)
results = await _aio.gather(*[_one(w) for w in wins])
# 按时序 + 8s频控 汇总
for win, res in zip(wins, results):
t=_timespan_end_sec(win.get("time_span",""))
if not (res and res.get("answer")): continue
if prev_answers and t - prev_answers[-1]["t"] < 8: continue
prev_answers.append({"t": t, "answer": res["answer"]})
pred_turns.append({"role":"assistant","content":res["answer"],"time":t,"n_tool_calls":res.get("n_tool_calls",0)})
elif TRIGGER_MODE == "stream" and os.environ.get("ESTP_VHYPER") == "1":
# === v_hyper(2026-07-19): 触发判定接入超图证据(通道B感知+fact检索),
# 而非v2的纯caption。这才用上了我们的核心武器(EgoMemo只有caption)。
# 并发判块, 事后按时序+限流汇总。ESTP_BLK块大小, ESTP_MAX_TRIG限流。===
c0, c1 = (rng if rng else (0.0, 0.0))
clip_caps = sorted(
[f for f in fc if c0 - 1e-6 <= _timespan_end_sec(f.get("time_span","")) <= c1 + 1e-6],
key=lambda f: _timespan_end_sec(f.get("time_span","")))
BLK = int(os.environ.get("ESTP_BLK", "3"))
blocks = [clip_caps[bi:bi+BLK] for bi in range(0, len(clip_caps), BLK)]
import asyncio as _aio
sem = _aio.Semaphore(int(os.environ.get("ESTP_VHYPER_CONC", "16")))
# === ESTP_ROUTE(2026-07-19): 按题型分流。EPT(显式识别)用超图证据; IPT(隐式推理)用纯caption(v2),
# 因通道B感知对推理题反而误导(实测IPT接超图从35%崩到6%)。===
_ttype0 = it.get("Task Type","").strip()
_IPT0 = {"Object Function","Information Function","Action Reasoning","Task Understanding"}
_use_v2 = (os.environ.get("ESTP_ROUTE") == "1" and _ttype0 in _IPT0)
async def _blk(block, is_final):
async with sem:
if _use_v2:
return await agentic_trigger_block(hg, fc, cb, question, [], block, final_window=is_final)
return await agentic_trigger_block_hyper(hg, fc, cb, question, [], block,
final_window=is_final)
results = await _aio.gather(*[_blk(b, False) for b in blocks])
# 按题型自适应限流: EPT(显式,GT窗多)可多触发; IPT(隐式,GT窗多为1)少触发防FP
_ttype = it.get("Task Type","").strip()
_IPT = {"Object Function","Information Function","Action Reasoning","Task Understanding"}
if os.environ.get("ESTP_ROUTE") == "1":
# IPT走v2逻辑用≤2, EPT走超图用≤4
_mt = int(os.environ.get("ESTP_MAX_TRIG_IPT", "2")) if _ttype in _IPT \
else int(os.environ.get("ESTP_MAX_TRIG_EPT", "4"))
elif os.environ.get("ESTP_ADAPTIVE_TRIG") == "1":
_mt = int(os.environ.get("ESTP_MAX_TRIG_IPT", "2")) if _ttype in _IPT \
else int(os.environ.get("ESTP_MAX_TRIG_EPT", "4"))
else:
_mt = int(os.environ.get("ESTP_MAX_TRIG", "3"))
for block, res in zip(blocks, results):
if not (res and res.get("triggered") and res.get("answer")): continue
t = res["time"]
if len(prev_answers) >= _mt: break
prev_answers.append({"t": t, "answer": res["answer"]})
pred_turns.append({"role":"assistant","content":res["answer"],
"time": t, "n_tool_calls": res.get("n_tool_calls",1)})
if not pred_turns and blocks:
# 兜底: 最后一块强制触发一次(按分流选函数)
if _use_v2:
res = await agentic_trigger_block(hg, fc, cb, question, [], blocks[-1], final_window=True)
else:
res = await agentic_trigger_block_hyper(hg, fc, cb, question, [], blocks[-1], final_window=True)
if res and res.get("answer"):
pred_turns.append({"role":"assistant","content":res["answer"],
"time": res["time"], "n_tool_calls": res.get("n_tool_calls",1)})
elif TRIGGER_MODE == "stream" and os.environ.get("ESTP_V2") == "1":
# === v2(最优, EPT20.2/IPT32.3): 逐6帧块判定 wait/trigger + 限流≤2次。
# 不加检索定位/尽早触发(那些v3/v5实测更差)。触发用块内窗结束时刻。===
c0, c1 = (rng if rng else (0.0, 0.0))
clip_caps = sorted(
[f for f in fc if c0 - 1e-6 <= _timespan_end_sec(f.get("time_span","")) <= c1 + 1e-6],
key=lambda f: _timespan_end_sec(f.get("time_span","")))
# BLK=触发判定块(帧数); 默认6帧≈12s(v2原行为); ESTP_BLK可调小(对齐GT窗2-4.5s提召回)
BLK = int(os.environ.get("ESTP_BLK", str(max(int(TRIGGER_STEP), 6))))
for bi in range(0, len(clip_caps), BLK):
block = clip_caps[bi: bi + BLK]
final_blk = (bi + BLK >= len(clip_caps))
res = await agentic_trigger_block(hg, fc, cb, question, prev_answers, block,
final_window=(final_blk and not pred_turns))
if res["triggered"]:
t = res["time"]
prev_answers.append({"t": t, "answer": res["answer"]})
pred_turns.append({"role":"assistant","content":res["answer"],
"time": t, "n_tool_calls": res["n_tool_calls"]})
elif TRIGGER_MODE == "stream":
c0, c1 = (rng if rng else (0.0, 0.0))
wins = sorted(
[w for w in (win_desc or []) if c0 - 1e-6 <= _timespan_end_sec(w.get("time_span","")) <= c1 + 1e-6],
key=lambda w: _timespan_end_sec(w.get("time_span","")))
if not wins:
# 无window_description的旧图: 回退按6帧块
wins = [{"time_span": f.get("time_span",""), "description": str(f.get("caption",""))}
for f in sorted(fc, key=lambda f: _timespan_end_sec(f.get("time_span","")))]
# v5(2026-07-18 SOTA主攻): 超图检索先定位"目标相关时刻"(实测候选命中GT±10s达66%),
# 只在候选时刻±10s的窗判触发 + 兜底扫少量前段窗, 大幅提准提速(不盲扫全窗)。
cand_ts = _locate_candidate_times(hg, question, c0, c1)
if cand_ts:
keep = set()
for w in wins:
wt = _timespan_end_sec(w.get("time_span",""))
if any(abs(wt - ct) <= 10 for ct in cand_ts):
keep.add(id(w))
focus = [w for w in wins if id(w) in keep]
# 保底: 也含前25%的窗(GT常在前段, 防检索漏)
head = wins[:max(2, len(wins)//4)]
seen=set(); wins=[w for w in (focus+head) if not (id(w) in seen or seen.add(id(w)))]
wins.sort(key=lambda w: _timespan_end_sec(w.get("time_span","")))
for wi, win in enumerate(wins):
final_w = (wi == len(wins) - 1)
gctx = " | ".join(f"[{_timespan_end_sec(w.get('time_span','')):.0f}s]{str(w.get('description',''))[:60]}"
for w in wins[max(0,wi-6):wi]) # 此前最多6窗做global上下文
# v7: 检索前置提示 —— 当前窗若命中检索候选(目标可能在此), 催促模型别再等
wt = _timespan_end_sec(win.get("time_span",""))
retrieval_hint = ""
if cand_ts and any(abs(wt - ct) <= 6 for ct in cand_ts):
retrieval_hint = ("HYPERGRAPH RETRIEVAL: the fact layer indicates the question's "
"target is LIKELY present around THIS window. If this window's "
"description supports an answer, TRIGGER NOW (do not wait further).")
res = await agentic_trigger_window(hg, fc, cb, question, prev_answers, win, gctx,
final_window=(final_w and not pred_turns),
retrieval_hint=retrieval_hint)
if res["triggered"]:
# v5.1: 触发时刻优先用该窗内的检索候选时刻(fact时刻66%命中GT), 否则窗起点。
# 窗结束时刻偏晚(实测晚触发239>命中144), 用候选/窗起点更贴GT。
w_s = _timespan_start_sec(win.get("time_span",""))
w_e = _timespan_end_sec(win.get("time_span",""))
in_win = [ct for ct in (cand_ts or []) if w_s - 1 <= ct <= w_e + 1]
t = (min(in_win) if in_win else w_s)
prev_answers.append({"t": t, "answer": res["answer"]})
pred_turns.append({"role": "assistant", "content": res["answer"],
"time": t, "n_tool_calls": res["n_tool_calls"]})
else:
# 旧协议(gt_turns, 保留作对照): 在 GT assistant turn 时刻作答
turns = sorted(
[c for c in it.get("conversation", []) if c.get("role", "").lower() == "assistant"],
key=lambda c: c.get("start_time", 0),
)
for c in turns:
t_now = float(c.get("start_time", 0))
view = StreamingHyperGraphView(hg, fc, cb, t_now)
res = await agentic_answer(view, question, prev_answers, budget=budget)
ans = res["answer"]
prev_answers.append({"t": t_now, "answer": ans})
pred_turns.append({
"role": "assistant",
"content": ans,
"time": t_now,
"n_tool_calls": res["n_tool_calls"],
})
# 组装成评测脚本期望的 qa dict(含 EVAL_MODEL_KEY 预测 + 原 conversation/字段)
qa_out = dict(it) # 保留 clip_start_time/clip_end_time/Task Type/question/conversation/qa_id
qa_out[EVAL_MODEL_KEY] = pred_turns
out_items.append(qa_out)
n_ans = sum(1 for t in pred_turns if t["content"] not in ("(no answer)", ""))
logger.info(f" QA qid={it.get('qa_id')} [{it.get('Task Type')}]: "
f"{n_ans}/{len(pred_turns)} turns answered")
return out_items
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--dataset_path", default=DATASET_PATH)
ap.add_argument("--output", required=True)
ap.add_argument("--answer_model", default="gpt-5-mini")
ap.add_argument("--budget", type=int, default=5, help="每 turn 最大工具调用次数")
ap.add_argument("--limit", type=int, default=0, help="只处理前 N 个 clip(0=全部)")
ap.add_argument("--shard", default="", help="i/k 分片并行(明早出数, 2026-07-18)")
ap.add_argument("--trigger_step", type=float, default=2.0, help="触发判定步进秒(默认2s=建图2fps)")
ap.add_argument("--trigger_mode", default="stream", choices=["stream", "gt_turns"],
help="stream=官方frame_by_frame对齐(10s窗LLM自主触发, 正式); gt_turns=旧协议(对照)")
args = ap.parse_args()
global TRIGGER_MODE
global TRIGGER_STEP
TRIGGER_STEP = args.trigger_step
TRIGGER_MODE = args.trigger_mode
logger.info(f"触发协议 = {TRIGGER_MODE}")
# 设置答题模型 = gpt-5.2
_ovo.gpt5_2_llm_config2.best_model_name = args.answer_model
_ovo.gpt5_2_llm_config1.best_model_name = args.answer_model
logger.info(f"答题模型 = {args.answer_model}, 工具预算/turn = {args.budget}")
data = json.load(open(args.dataset_path))
# 展平为 (uid, seg, qa_items), 只保留已建图的 clip
clips = []
for uid, segd in data.items():
for seg, items in segd.items():
if not items:
continue
rng = _item_clip_range(items[0])
if rng is None:
continue
cs, ce = int(round(rng[0])), int(round(rng[1]))
wd = os.path.join(HYPER_ROOT, f"{uid}_{cs}_{ce}_qwen_vllm")
if os.path.isfile(os.path.join(wd, "hypergraph.json")):
clips.append((uid, seg, items, cs, ce))
only = os.environ.get("ESTP_ONLY_CLIPS", "")
if only:
# 只跑白名单clip(补缺题用): JSON文件, [[uid,seg],...]
wl = set(tuple(x) for x in json.load(open(only)))
clips = [c for c in clips if (c[0], c[1]) in wl]
logger.info(f"[ONLY_CLIPS] 白名单过滤后 {len(clips)} clips")
if args.shard:
i, k = (int(x) for x in args.shard.split("/"))
clips = [c for j, c in enumerate(clips) if j % k == i]
logger.info(f"[shard {args.shard}] 本分片 {len(clips)} clips")
if args.limit > 0:
clips = clips[: args.limit]
logger.info(f"待推理 clip 数(已建图): {len(clips)}")
# 断点续跑
out: Dict[str, Dict[str, list]] = {}
if os.path.exists(args.output):
try:
out = json.load(open(args.output))
except Exception:
out = {}
t0 = time.time()
n_cb_clips = 0
# ESTP_ONLY_TYPES(2026-07-20新增): 逗号分隔的Task Type白名单, 只推理这些题型的QA(省成本的定向重跑)
only_types = {t.strip() for t in os.environ.get("ESTP_ONLY_TYPES","").split("|") if t.strip()}
for i, (uid, seg, items, cs, ce) in enumerate(clips):
if only_types:
items = [it for it in items if it.get("Task Type","").strip() in only_types]
if not items:
continue
if uid in out and seg in out[uid]:
logger.info(f"[{i+1}/{len(clips)}] 已完成, 跳过 {uid[:12]}/{seg[:12]}")
continue
# 统计通道B可用性
has_cb = os.path.isfile(os.path.join(
HYPER_ROOT, f"{uid}_{cs}_{ce}_qwen_vllm", "structured_perception_v2.jsonl"))
n_cb_clips += int(has_cb)
logger.info(f"[{i+1}/{len(clips)}] {uid[:12]}/{seg[:12]} "
f"({len(items)} QA, channel-B={'Y' if has_cb else 'N'})")
qa_out = asyncio.run(infer_one_clip(uid, seg, items, args.budget))
out.setdefault(uid, {})[seg] = qa_out
if (i + 1) % 3 == 0:
json.dump(out, open(args.output, "w"), ensure_ascii=False, indent=2)
json.dump(out, open(args.output, "w"), ensure_ascii=False, indent=2)
dt = time.time() - t0
logger.info(f"=== 流式推理完成: {len(clips)} clip ({n_cb_clips} 带通道B), "
f"用时 {dt:.0f}s -> {args.output} ===")
if __name__ == "__main__":
main()
"""任务②: ESTP 流式(forward)推理脚本 —— 充分利用超图三层 + 通道B + agentic 工具调用。
与现有 estp_proassist_eval.py("一次性喂检索结果")的区别:
* 现有: 每个 turn 把截断后的 episodes/facts/frame_captions 一次性塞进 prompt, LLM 单次答。
* 本脚本: 每个 turn 只给 LLM "当前时刻的最近感知快照", 然后开放一组【超图工具】,
让 agent 按需分层检索(topic→episode→fact + 通道B实体/OCR/事件), 多轮工具调用后再答。
【严格流式 forward(核心约束, 绝不泄漏未来)】—— 见下列代码行:
1. StreamingHyperGraphView 在构造时用 t_now 把整张图截断一次(episode end≤ts,
fact temporal≤ts, 通道B window end≤ts), 见 _truncate_all()。
2. 所有工具都只在这份"截到 t_now 的视图"上检索, 物理上拿不到未来数据。
3. prev_answers 只累积同一 sample 内更早时刻的自身回答(流式上下文)。
【用到的超图工具(agent 按需调用)】:
- search_episodes(keywords) : 关键词搜过去已完成的 episode(subject+summary+description)
- search_facts(keywords, t_from?, t_to?) : 关键词搜过去的原子事实(fact 三层最底层)
- hierarchical_search(query) : topic→episode→fact 语义分层检索(BM25 over 三层)
- search_entities(keywords) : 查通道B实体注册表(name/type/count/attributes/location)
- search_ocr(keywords) : 查通道B on_screen_text(读数/招牌/屏幕文字)
- get_perception_recent(seconds): 取最近 N 秒的通道B窗(atomic_events+entities+ocr)
- list_topics() : 列出该片段的主题层(全局导航)
答题模型: gpt-5.2 (通过 HYPERVIDEO_ANSWER_MODEL 复用 ovobench_hyper_retrieval 的 config)。
用法:
export OPENAI_API_KEY=...
# 冒烟 5 个片段
python -m hypervideo.estp_streaming_inference --limit 5 \
--output /mnt/tokyo-ai/gst/claude_logs/estp_streaming_pred_smoke.json
# 全量
python -m hypervideo.estp_streaming_inference \
--output /mnt/tokyo-ai/gst/.../estp_streaming_pred.json
"""
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")
if not os.environ.get("OPENAI_API_KEY"):
raise RuntimeError("请先 export OPENAI_API_KEY=...")
from hypervideo import ovobench_hyper_retrieval as _ovo # noqa: E402
from hypervideo.streamingbench_json_eval import ( # noqa: E402
_parse_temporal_to_sec,
)
logger = logging.getLogger("estp_streaming")
logging.basicConfig(level=logging.INFO, format="%(asctime)s | %(levelname)s | %(message)s")
DAY_BASE = 86400.0 # episode.start_seconds = DAY_BASE + 相对视频秒
HYPER_ROOT = os.environ.get("ESTP_HYPER_ROOT",
"/mnt/tokyo-ai/gst/GST_EGOSERVE/all_results/estp_hyper_v2")
DATASET_PATH = "/mnt/tokyo-ai/gst/GST_EGOSERVE/GST_EYEWO/data/estp_dataset/estp_bench_sq.json"
EVAL_MODEL_KEY = "HyperStream" # 写进预测 json 的 key, 评测脚本用 --eval_model 对应
# ======================================================================
# 时间解析工具(统一到"绝对视频秒")
# ======================================================================
def _timespan_end_sec(time_span: str) -> float:
"""通道B / episode 的 time_span 形如 '1-00:17:52-00:19:12' 取最后 HH:MM:SS -> 秒。"""
all_t = re.findall(r"(\d+):(\d+):(\d+)", time_span or "")
if not all_t:
return 0.0
h, m, s = all_t[-1]
return int(h) * 3600 + int(m) * 60 + int(s)
def _timespan_start_sec(time_span: str) -> float:
all_t = re.findall(r"(\d+):(\d+):(\d+)", time_span or "")
if not all_t:
return 0.0
h, m, s = all_t[0]
return int(h) * 3600 + int(m) * 60 + int(s)
def _episode_end_sec(ep: dict) -> float:
"""episode 结束的绝对视频秒: 优先 end_seconds-DAY_BASE, 回退 time_span。"""
es = ep.get("end_seconds")
if es is not None and es >= DAY_BASE - 1:
return float(es) - DAY_BASE
return _timespan_end_sec(ep.get("time_span", ""))
def _episode_start_sec(ep: dict) -> float:
ss = ep.get("start_seconds")
if ss is not None and ss >= DAY_BASE - 1:
return float(ss) - DAY_BASE
return _timespan_start_sec(ep.get("time_span", ""))