Download graph_construction_code/entry/captaincook4d_hyper_processing.py from SitongGong/paper_final_results: direct link, hf CLI and curl.
- Browser
- Download file 31.6 kB
-
https://huggingface.co/datasets/SitongGong/paper_final_results/resolve/main/graph_construction_code/entry/captaincook4d_hyper_processing.py
- Command line
-
hf download hf://datasets/SitongGong/paper_final_results/graph_construction_code/entry/captaincook4d_hyper_processing.py
-
curl -L -o captaincook4d_hyper_processing.py https://huggingface.co/datasets/SitongGong/paper_final_results/resolve/main/graph_construction_code/entry/captaincook4d_hyper_processing.py
31.6 kB
| """HoloAssist 建图入口 — 每视频一次性建三层超图(含 correctness / error 字段) | |
| 与 EgoLife 的关键差异: | |
| 1. 每个样本是**一个完整视频(一个完整的任务会话,通常 3-10 分钟)**,不跨段 | |
| 2. 走 V2 流式路径: interval 抽帧 → 10s window → caption → hypergraph_builder | |
| 3. HyperVideoConfig.dataset_mode="holoassist" 让 fact_extractor 切到 | |
| FACT_EXTRACTION_WITH_ROLES_PROMPT_HOLOASSIST,输出 action_verb / | |
| target_noun / correctness / error_description / severity 等字段 | |
| 4. caption prompt 走 FRAME_CAPTION_WINDOW_HOLOASSIST_PROMPT (手部/工具/工件) | |
| 5. 不做积累事件抽取(holoassist 没有 drink/sit 这类习惯行为) | |
| 用法: | |
| # 从 val split 随机挑 3 个视频跑 | |
| python -m hypervideo.holoassist_hyper_processing \\ | |
| --holoassist_root /mnt/tokyo-ai/gst/HoloAssist \\ | |
| --num_videos 3 \\ | |
| --save_root /mnt/tokyo-ai/gst/GST_EGOSERVE/all_results \\ | |
| --datasets_type holoassist_hyper_v2 \\ | |
| --caption_model qwen_api \\ | |
| --qwen_api_model qwen-vl-max | |
| # 指定 video_names | |
| ... --video_names R0027-12-GoPro,R033-12July-GoPro | |
| # 本地 VLM | |
| ... --caption_model qwenvl_3_8b_instruct --cuda 0 | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import base64 | |
| import gc | |
| import io | |
| import json | |
| import logging | |
| import os | |
| import random | |
| import sys | |
| import time | |
| from dataclasses import asdict | |
| from typing import Dict, List, Optional | |
| import cv2 | |
| import numpy as np | |
| import torch | |
| from PIL import Image | |
| sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | |
| from videorag._llm import ( | |
| LLMConfig, openai_embedding, gpt_4o_mini_complete, | |
| ) | |
| from videorag._utils import always_get_an_event_loop | |
| from videorag.video_processing import sample_frames_by_interval | |
| from hypervideo.hyper_video_graph import HyperVideoGraph | |
| from hypervideo.config import HyperVideoConfig | |
| from hypervideo.prompts.frame_caption_prompt import ( | |
| FRAME_CAPTION_WINDOW_HOLOASSIST_PROMPT, | |
| FRAME_CAPTION_WINDOW_HOLOASSIST_WITH_PRIOR_PROMPT, | |
| ) | |
| logging.basicConfig( | |
| level=logging.INFO, | |
| format='[%(asctime)s] %(levelname)s: %(message)s', | |
| ) | |
| logger = logging.getLogger(__name__) | |
| # ============================================================ | |
| # LLM 配置 | |
| # ============================================================ | |
| default_llm_config = LLMConfig( | |
| embedding_func_raw=openai_embedding, | |
| embedding_model_name="text-embedding-3-small", | |
| embedding_dim=1536, | |
| embedding_max_token_size=8192, | |
| embedding_batch_num=32, | |
| embedding_func_max_async=16, | |
| query_better_than_threshold=0.2, | |
| best_model_func_raw=gpt_4o_mini_complete, | |
| best_model_name="gpt-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-4.1-mini", | |
| cheap_model_max_token_size=32768, | |
| cheap_model_max_async=16, | |
| ) | |
| # ============================================================ | |
| # 工具 | |
| # ============================================================ | |
| def _seconds_to_hms(sec: float) -> str: | |
| s = max(0, int(sec)) | |
| h = s // 3600 | |
| m = (s % 3600) // 60 | |
| ss = s % 60 | |
| return f"{h:02d}:{m:02d}:{ss:02d}" | |
| def _timestamp_num_to_seconds(ts_num) -> float: | |
| """sample_frames_by_interval 在 time_span_info=None 时返回 HHMMSSCC 整数。 | |
| 这里实际是相对秒数的百分秒表示; 除以 100 得到秒。 | |
| """ | |
| ts = int(ts_num) | |
| return ts / 100.0 | |
| def _safe_json_parse(text: str) -> Optional[dict]: | |
| import re as _re | |
| try: | |
| return json.loads(text) | |
| except Exception: | |
| pass | |
| m = _re.search(r"```(?:json)?\s*\n(.*?)\n?```", text, _re.DOTALL | _re.IGNORECASE) | |
| if m: | |
| try: | |
| return json.loads(m.group(1).strip()) | |
| except Exception: | |
| pass | |
| m = _re.search(r"(\{.*\})", text, _re.DOTALL) | |
| if m: | |
| try: | |
| return json.loads(m.group(1).strip()) | |
| except Exception: | |
| pass | |
| return None | |
| def _load_val_video_names(holoassist_root: str) -> List[str]: | |
| """CaptainCook4D: 视频列表 = service_annotations 的 87 个 recording_id | |
| (与评测 common 集一致)。holoassist_root 此处复用为 service_annotations 路径。""" | |
| p = holoassist_root # 传入 captaincook4d_service_annotations.json 路径 | |
| names = [] | |
| if os.path.isfile(p): | |
| with open(p) as f: | |
| data = json.load(f) | |
| seen = set() | |
| for e in (data if isinstance(data, list) else []): | |
| rid = e.get("recording_id", "") | |
| if rid and rid not in seen: | |
| seen.add(rid) | |
| names.append(rid) | |
| return names | |
| # CaptainCook4D 视频目录 (gopro 360p) | |
| _CC4D_VIDEO_DIR = "/mnt/workspace/gst/CaptionCook4D/downloader/data/captain_cook_4d/gopro/resolution_360p" | |
| def _video_path_for(holoassist_root: str, video_name: str) -> Optional[str]: | |
| # CaptainCook4D: {recording_id}_360p.mp4 | |
| cands = [ | |
| os.path.join(_CC4D_VIDEO_DIR, f"{video_name}_360p.mp4"), | |
| os.path.join(_CC4D_VIDEO_DIR, f"{video_name}.mp4"), | |
| ] | |
| for p in cands: | |
| if os.path.isfile(p): | |
| return p | |
| return None | |
| # ============================================================ | |
| # 每 window 一次 VLM(HoloAssist caption) | |
| # ============================================================ | |
| def _caption_holoassist_window( | |
| hyper_vg: HyperVideoGraph, | |
| window_b64: List[str], | |
| window_ranges: List[dict], | |
| interval_sec: float, | |
| day_num: int, | |
| desc_min_sentences: int, | |
| desc_max_sentences: int, | |
| max_new_tokens: int, | |
| max_retries: int = 3, | |
| prior_frame_captions: Optional[List[str]] = None, | |
| ) -> Optional[dict]: | |
| """HoloAssist 专用 caption: 一个 window 一次 VLM 调用。 | |
| 支持 prior_frame_captions(上一窗尾部 1-2 条)用于跨窗工具/零件命名一致性。 | |
| 有 prior -> 走 HOLOASSIST_WITH_PRIOR_PROMPT (timestamp-key 输出) | |
| 无 prior -> 走原版 HOLOASSIST_PROMPT (index-key 输出) | |
| parser 两种 key 格式都支持。 | |
| """ | |
| if not window_b64: | |
| return None | |
| num_frames = len(window_b64) | |
| win_start_sec = _timestamp_num_to_seconds(window_ranges[0]['start']) | |
| win_end_sec = _timestamp_num_to_seconds(window_ranges[-1]['end']) | |
| abs_start = f"DAY{day_num}-{_seconds_to_hms(win_start_sec)}" | |
| abs_end = f"DAY{day_num}-{_seconds_to_hms(win_end_sec)}" | |
| window_seconds = max(int(round(win_end_sec - win_start_sec)), int(interval_sec) * num_frames) | |
| # 各帧的期望时间戳 key(供 with-prior 版 parser 使用) → 帧索引 fi | |
| expected_ts_to_fi: Dict[str, int] = {} | |
| for fi in range(num_frames): | |
| f_start_str = _seconds_to_hms(_timestamp_num_to_seconds(window_ranges[fi]['start'])) | |
| ts_key = f"DAY{day_num}-{f_start_str}" | |
| expected_ts_to_fi[ts_key] = fi | |
| first_ts_example = f"DAY{day_num}-{_seconds_to_hms(_timestamp_num_to_seconds(window_ranges[0]['start']))}" | |
| last_ts_example = f"DAY{day_num}-{_seconds_to_hms(_timestamp_num_to_seconds(window_ranges[-1]['start']))}" | |
| common_kwargs = dict( | |
| window_seconds=window_seconds, | |
| abs_start=abs_start, | |
| abs_end=abs_end, | |
| num_frames=num_frames, | |
| interval_sec=int(interval_sec), | |
| desc_min=desc_min_sentences, | |
| desc_max=desc_max_sentences, | |
| first_ts_example=first_ts_example, | |
| last_ts_example=last_ts_example, | |
| ) | |
| if prior_frame_captions: | |
| prompt = FRAME_CAPTION_WINDOW_HOLOASSIST_WITH_PRIOR_PROMPT.format( | |
| prior_frame_context="\n".join(prior_frame_captions), | |
| **common_kwargs, | |
| ) | |
| else: | |
| prompt = FRAME_CAPTION_WINDOW_HOLOASSIST_PROMPT.format(**common_kwargs) | |
| def _key_to_fi(raw_key: str) -> Optional[int]: | |
| # 整数索引 key | |
| try: | |
| fi = int(raw_key) | |
| if 0 <= fi < num_frames: | |
| return fi | |
| except ValueError: | |
| pass | |
| # timestamp key (DAYd-HH:MM:SS[...]) | |
| import re as _re | |
| m = _re.match(r"\s*(DAY\d+-\d{2}:\d{2}:\d{2})", raw_key) | |
| if m: | |
| ts = m.group(1) | |
| if ts in expected_ts_to_fi: | |
| return expected_ts_to_fi[ts] | |
| return None | |
| for retry in range(max_retries): | |
| try: | |
| text = hyper_vg.mllm_response( | |
| hyper_vg.video_llm, hyper_vg.processor, | |
| prompt, None, | |
| base64_frames=window_b64, | |
| max_new_tokens=max_new_tokens, has_image=True, | |
| ) | |
| parsed = _safe_json_parse(text) | |
| if not (isinstance(parsed, dict) and "frames" in parsed | |
| and isinstance(parsed["frames"], dict)): | |
| logger.warning(f" [Caption] invalid JSON retry {retry+1}/{max_retries}") | |
| continue | |
| desc = str(parsed.get("description") or "").strip() | |
| if not desc: | |
| logger.warning(f" [Caption] empty description retry {retry+1}/{max_retries}") | |
| continue | |
| dense_caption: Dict[str, str] = {} | |
| seen_fis = set() | |
| for raw_key, cap_text in parsed["frames"].items(): | |
| fi = _key_to_fi(raw_key) | |
| if fi is None or fi in seen_fis: | |
| continue | |
| seen_fis.add(fi) | |
| f_start = _seconds_to_hms(_timestamp_num_to_seconds(window_ranges[fi]['start'])) | |
| f_end = _seconds_to_hms(_timestamp_num_to_seconds(window_ranges[fi]['end'])) | |
| dense_caption[f"DAY{day_num}-{f_start}-{f_end}"] = str(cap_text) | |
| if not dense_caption: | |
| logger.warning(f" [Caption] empty dense_caption retry {retry+1}/{max_retries}") | |
| continue | |
| return {"dense_caption": dense_caption, "description": desc} | |
| except Exception as e: | |
| logger.error(f" [Caption] VLM error retry {retry+1}/{max_retries}: {e}") | |
| continue | |
| return None | |
| # ============================================================ | |
| # 主循环: 单视频建图 | |
| # ============================================================ | |
| def run_holoassist_video_construction( | |
| hyper_vg: HyperVideoGraph, | |
| video_path: str, | |
| video_name: str, | |
| interval_sec: float, | |
| window_frames: int, | |
| max_new_tokens: int, | |
| day_num: int = 1, | |
| frame_captions_out_path: Optional[str] = None, | |
| sp_extractor=None, | |
| ): | |
| loop = always_get_an_event_loop() | |
| logger.info(f"[HoloAssist] building {video_name} from {video_path}") | |
| # 1) 全视频抽帧 | |
| base64_frames, _, time_ranges = sample_frames_by_interval( | |
| video_path, | |
| interval_seconds=interval_sec, | |
| output_format='base64', | |
| time_span_info=None, | |
| ) | |
| n_frames = len(base64_frames) | |
| logger.info(f" sampled {n_frames} frames @ every {interval_sec}s") | |
| if n_frames == 0: | |
| logger.warning(f" no frames decoded from {video_path}") | |
| return | |
| all_frame_captions: List[dict] = [] | |
| window_descriptions: List[dict] = [] | |
| # 上一窗尾部 1-2 条 caption, 用于跨窗工具/零件命名一致性 | |
| prev_tail_captions: List[str] = [] | |
| N_PRIOR = 2 | |
| try: | |
| hyper_vg.hypergraph_builder.reset_timing() | |
| except Exception: | |
| pass | |
| # 2) 按 window_frames 切块,每块一次 VLM | |
| n_windows = (n_frames + window_frames - 1) // window_frames | |
| for w_idx in range(n_windows): | |
| s = w_idx * window_frames | |
| e = min(s + window_frames, n_frames) | |
| window_b64 = base64_frames[s:e] | |
| window_ranges = time_ranges[s:e] | |
| win_start_sec = _timestamp_num_to_seconds(window_ranges[0]['start']) | |
| win_end_sec = _timestamp_num_to_seconds(window_ranges[-1]['end']) | |
| win_time_span = f"{day_num}-{_seconds_to_hms(win_start_sec)}-{_seconds_to_hms(win_end_sec)}" | |
| t0 = time.time() | |
| caption_dict = _caption_holoassist_window( | |
| hyper_vg=hyper_vg, | |
| window_b64=window_b64, | |
| window_ranges=window_ranges, | |
| interval_sec=interval_sec, | |
| day_num=day_num, | |
| desc_min_sentences=2, | |
| desc_max_sentences=3, | |
| max_new_tokens=max_new_tokens, | |
| prior_frame_captions=prev_tail_captions or None, | |
| ) | |
| dt = time.time() - t0 | |
| if sp_extractor is not None and caption_dict is not None: | |
| try: | |
| sp_extractor.extract_window(window_b64, win_time_span, day_num) | |
| except Exception as _spe: | |
| logger.warning(f" [SP] win {w_idx+1} 通道B失败(忽略): {_spe}") | |
| if caption_dict is None: | |
| logger.error(f" [Caption] win {w_idx+1}/{n_windows} ({win_time_span}) VLM failed — recorded as placeholder") | |
| window_descriptions.append({ | |
| "time_span": win_time_span, | |
| "description": "[VLM_FAILED]", | |
| "vlm_failed": True, | |
| "frame_count": len(window_b64), | |
| }) | |
| continue | |
| logger.info( | |
| f" [Caption] win {w_idx+1}/{n_windows} ({win_time_span}) " | |
| f"{len(window_b64)} frames, {len(caption_dict['dense_caption'])} captions, " | |
| f"prior={len(prev_tail_captions)}, {dt:.1f}s" | |
| ) | |
| for fk, fv in caption_dict["dense_caption"].items(): | |
| all_frame_captions.append({"time_span": fk, "caption": fv}) | |
| window_descriptions.append({ | |
| "time_span": win_time_span, | |
| "description": caption_dict["description"], | |
| }) | |
| # 更新 prev_tail_captions | |
| dc = caption_dict["dense_caption"] | |
| tail_keys = sorted(dc.keys())[-N_PRIOR:] | |
| prev_tail_captions = [f"[{k}] {dc[k]}" for k in tail_keys] | |
| try: | |
| loop.run_until_complete( | |
| hyper_vg.hypergraph_builder.process_window_caption_v2( | |
| caption_dict=caption_dict, | |
| time_span=win_time_span, | |
| day_num=day_num, | |
| ) | |
| ) | |
| except Exception as e: | |
| logger.error(f" [Hyper] win {w_idx+1}/{n_windows} process failed: {e}") | |
| continue | |
| try: | |
| hyper_vg.hypergraph_builder.index_window_visual(win_time_span, window_b64) | |
| except Exception: | |
| pass | |
| if (w_idx + 1) % 10 == 0: | |
| stats = hyper_vg.hypergraph_builder.hypergraph.get_stats() | |
| logger.info(f" [Progress] {w_idx+1}/{n_windows} windows, stats={stats}") | |
| # flush | |
| try: | |
| loop.run_until_complete(hyper_vg.hypergraph_builder.flush()) | |
| except Exception as e: | |
| logger.error(f" Flush failed: {e}") | |
| try: | |
| hyper_vg.save_hypergraph() | |
| except Exception as e: | |
| logger.error(f" Save hypergraph failed: {e}") | |
| try: | |
| hyper_vg.hypergraph_builder.log_timing_summary(prefix="(final)") | |
| except Exception: | |
| pass | |
| if frame_captions_out_path: | |
| try: | |
| with open(frame_captions_out_path, 'w', encoding='utf-8') as f: | |
| json.dump({ | |
| "video_name": video_name, | |
| "video_path": video_path, | |
| "interval_seconds": interval_sec, | |
| "window_frames": window_frames, | |
| "day_num": day_num, | |
| "frame_captions": all_frame_captions, | |
| "window_descriptions": window_descriptions, | |
| }, f, ensure_ascii=False, indent=2) | |
| logger.info(f" [Save] frame_captions.json -> {frame_captions_out_path}") | |
| except Exception as e: | |
| logger.error(f" Save frame_captions failed: {e}") | |
| # 打印 anomaly fact 数量 | |
| hg = hyper_vg.hypergraph_builder.hypergraph | |
| n_wrong = sum( | |
| 1 for fn in hg.facts.values() | |
| if fn.correctness and fn.correctness.startswith("wrong") | |
| ) | |
| logger.info( | |
| f" [Done] hypergraph built, stats={hg.get_stats()}, " | |
| f"anomaly_facts(wrong_*)={n_wrong}" | |
| ) | |
| # ============================================================ | |
| # HyperVideoGraph working_dir 切换(多视频复用同一 caption model) | |
| # ============================================================ | |
| def _reset_hyper_vg_working_dir(hyper_vg: HyperVideoGraph, new_working_dir: str): | |
| """切换 hyper_vg 到新的 working_dir,重置 hypergraph/index,保留 caption_model。 | |
| 逻辑与 streamingbench_hyper_processing._reset_hyper_vg_working_dir 保持一致。 | |
| """ | |
| from dataclasses import asdict | |
| from videorag._storage import JsonKVStorage, NanoVectorDBVideoSegmentStorage | |
| from hypervideo.extractors.hypergraph_builder import VideoHypergraphBuilder | |
| from hypervideo.index.dual_index import DualIndex | |
| from hypervideo.retrieval.hierarchical_retriever import HierarchicalRetriever | |
| hyper_vg.working_dir = new_working_dir | |
| os.makedirs(new_working_dir, exist_ok=True) | |
| hyper_vg.video_segments = hyper_vg.key_string_value_json_storage_cls( | |
| namespace="video_segments", global_config=asdict(hyper_vg) | |
| ) | |
| if hyper_vg.enable_llm_cache: | |
| hyper_vg.llm_response_cache = hyper_vg.key_string_value_json_storage_cls( | |
| namespace="llm_response_cache", global_config=asdict(hyper_vg) | |
| ) | |
| hyper_vg.video_segment_feature_vdb = hyper_vg.vs_vector_db_storage_cls( | |
| namespace="video_segment_feature", | |
| global_config=asdict(hyper_vg), | |
| embedding_func=None, | |
| ) | |
| async def _llm_wrapper(prompt: str) -> str: | |
| return await hyper_vg.llm.cheap_model_func(prompt) | |
| hyper_vg.hypergraph_builder = VideoHypergraphBuilder( | |
| llm_func=_llm_wrapper, | |
| embedding_func=hyper_vg.embedding_func, | |
| config=hyper_vg.hyper_config, | |
| working_dir=hyper_vg.working_dir, | |
| ) | |
| hyper_vg.dual_index = DualIndex( | |
| embedding_func=hyper_vg.embedding_func, | |
| config=hyper_vg.hyper_config, | |
| ) | |
| hyper_vg.retriever = HierarchicalRetriever( | |
| hypergraph=hyper_vg.hypergraph_builder.hypergraph, | |
| dual_index=hyper_vg.dual_index, | |
| config=hyper_vg.hyper_config, | |
| ) | |
| hyper_vg.hypergraph_builder.load(new_working_dir) | |
| # ============================================================ | |
| # CLI | |
| # ============================================================ | |
| def main(): | |
| parser = argparse.ArgumentParser(description="HoloAssist 建图入口") | |
| parser.add_argument("--holoassist_root", type=str, | |
| default="/mnt/workspace/gst/EgoServe_release/CaptainCook4D/captaincook4d_service_annotations.json", | |
| help="CaptainCook4D: service_annotations.json 路径(定87个视频列表)") | |
| parser.add_argument("--video_names", type=str, default=None, | |
| help="逗号分隔的 video_name 列表(覆盖 --num_videos)") | |
| parser.add_argument("--num_videos", type=int, default=-1, | |
| help="从 val split 中随机挑几个跑(默认 3)") | |
| parser.add_argument("--seed", type=int, default=42, help="随机种子") | |
| parser.add_argument("--save_root", type=str, | |
| default="/mnt/tokyo-ai/gst/GST_EGOSERVE/all_results", | |
| help="输出根目录") | |
| parser.add_argument("--datasets_type", type=str, default="captaincook4d_hyper_v2") | |
| parser.add_argument("--caption_model", type=str, default="qwen_api", | |
| help="caption 模型: qwen_api / qwenvl_3_8b_instruct / gpt_api / gemini_api") | |
| parser.add_argument("--qwen_api_model", type=str, default="qwen-vl-max") | |
| parser.add_argument("--vllm_base_url", type=str, default="http://localhost:8007/v1", | |
| help="本地vLLM caption服务 (caption_model=qwen_vllm 时用)") | |
| parser.add_argument("--vllm_model_name", type=str, default="Qwen3.6-35B-A3B-FP8") | |
| parser.add_argument("--enable_structured_perception", action="store_true", | |
| help="通道B: 每窗结构化感知(工具/部件计数+操作动作+错误迹象)") | |
| parser.add_argument("--sp_max_new_tokens", type=int, default=3000) | |
| parser.add_argument("--qwen_api_key", type=str, | |
| default="YOUR_API_KEY") | |
| parser.add_argument("--openai_key", type=str, | |
| default="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") | |
| parser.add_argument("--gemini_key", type=str, | |
| default="AIzaSyCOzZCneNLi8Aoj4odDSHuZskan2Pa1fVE") | |
| parser.add_argument("--cuda", type=str, default="0") | |
| parser.add_argument("--interval_seconds", type=float, default=1.0, | |
| help="抽帧间隔秒(HoloAssist 默认 1; 视频较短,子步骤密集)") | |
| parser.add_argument("--window_frames", type=int, default=10, | |
| help="每个 caption window 的帧数(默认 10, 即 10s 窗口; " | |
| "需要这个跨度以便 episode 内含多帧足以识别 wrong-order/retry 模式)") | |
| parser.add_argument("--max_new_tokens", type=int, default=2048) | |
| args = parser.parse_args() | |
| os.environ["CUDA_VISIBLE_DEVICES"] = args.cuda | |
| if args.openai_key and not args.openai_key.startswith("sk-proj-vUcaG"): | |
| os.environ["OPENAI_API_KEY"] = args.openai_key | |
| # 否则保留 shell 导出的 OPENAI_API_KEY(EgoServe/MMLifelong 一直在用的有效key) | |
| # 1) 选视频 | |
| if args.video_names: | |
| video_names = [n.strip() for n in args.video_names.split(",") if n.strip()] | |
| logger.info(f"Using explicit video_names: {video_names}") | |
| else: | |
| val = _load_val_video_names(args.holoassist_root) | |
| logger.info(f"val split has {len(val)} videos") | |
| # 只保留那些有文件的 | |
| val_ok = [n for n in val if _video_path_for(args.holoassist_root, n) is not None] | |
| logger.info(f"{len(val_ok)} videos have Video_compress.mp4 on disk") | |
| # num_videos=-1 表示全量, 否则随机抽 N 个 | |
| if args.num_videos is not None and args.num_videos > 0: | |
| random.seed(args.seed) | |
| random.shuffle(val_ok) | |
| video_names = val_ok[:args.num_videos] | |
| logger.info(f"Selected {len(video_names)} (random sample) videos") | |
| else: | |
| # 全量按 val 文件原顺序处理 (resume 友好) | |
| video_names = val_ok | |
| logger.info(f"Processing ALL {len(video_names)} val videos in original order") | |
| if not video_names: | |
| logger.error("no videos to process; exiting.") | |
| return | |
| # 2) 构造 HyperVideoConfig + HyperVideoGraph (第一个 working_dir) | |
| first_name = video_names[0] | |
| first_working_dir = os.path.join( | |
| args.save_root, f"{first_name}-{args.datasets_type}-{args.caption_model}" | |
| ) | |
| os.makedirs(first_working_dir, exist_ok=True) | |
| config = HyperVideoConfig( | |
| dataset_mode="holoassist", | |
| caption_prompt_profile="holoassist", | |
| caption_window_seconds=float(args.window_frames) * args.interval_seconds, | |
| caption_frame_interval_sec=args.interval_seconds, | |
| caption_granularity="per_window", | |
| boundary_strategy="stream", | |
| # HoloAssist: episode = 单个子步骤,典型 20-90s。max_buffer=90s 强制硬切, | |
| # 防止 LLM 边界判断过于保守导致单 episode 覆盖多个子步骤。 | |
| max_buffer_seconds=90.0, | |
| # 至少积累 15 帧 (= 15s @ interval=1s) 再考虑切分, | |
| # 让 episode 跨度足够 fact extractor 看到 wrong-order/retry 模式。 | |
| min_buffer_frames=15, | |
| # HoloAssist fact 抽取不并行走 EgoLife 积累事件路径 | |
| egolife_accumulative_event_enabled=False, | |
| ) | |
| hyper_vg = HyperVideoGraph( | |
| working_dir=first_working_dir, | |
| llm=default_llm_config, | |
| hyper_config=config, | |
| ) | |
| # 3) 加载 caption 模型(一次,多视频共用) | |
| if args.caption_model == "qwen_api": | |
| hyper_vg.load_caption_model( | |
| "qwen_api", | |
| api_model_name=args.qwen_api_model, | |
| api_key=args.qwen_api_key, | |
| ) | |
| elif args.caption_model == "qwen_vllm": | |
| hyper_vg.load_caption_model( | |
| "qwen_vllm", | |
| vllm_base_url=args.vllm_base_url, | |
| vllm_model_name=args.vllm_model_name, | |
| ) | |
| elif args.caption_model == "gpt_api": | |
| hyper_vg.load_caption_model("gpt_api") | |
| elif args.caption_model == "gemini_api": | |
| hyper_vg.load_caption_model( | |
| "gemini_api", | |
| api_model_name="gemini-2.5-pro", | |
| api_key=args.gemini_key, | |
| ) | |
| else: | |
| hyper_vg.load_caption_model(args.caption_model) | |
| # 4) 加载 task knowledge (taskType per video + 常见错误清单 per taskType) | |
| # 给 fact LLM 在错误检测时提供该任务的"已知错误模式",方向性很强且无需改 caption。 | |
| task_type_by_video = {} | |
| task_error_patterns = {} | |
| task_correct_steps_map = {} | |
| try: | |
| # CaptainCook4D: taskType = activity_id (每菜谱). recording_id -> activity_id | |
| # 从 error_to_dialogue GT 建映射 (做饭流程是公开菜谱知识, 非评测答案)。 | |
| gt_json_path = "/mnt/workspace/gst/CaptionCook4D/annotations/annotation_json/error_to_dialogue_results_consolidated.json" | |
| if os.path.isfile(gt_json_path): | |
| with open(gt_json_path) as f: | |
| gt_data = json.load(f) | |
| for d in gt_data: | |
| rid = d.get("recording_id", "") | |
| act = d.get("activity_id") | |
| if rid and act is not None: | |
| task_type_by_video[rid] = str(act) | |
| # CaptainCook4D: 注入【全局通用错误类型清单】(8类, 所有视频共用一份)。 | |
| # 这是"做饭常见哪几类错误"的领域知识, 不绑定具体视频/步骤, 不泄露答案 | |
| # (哪个视频哪一步出错才是评测答案, 那个绝不注入)。 | |
| etypes_path = os.path.join( | |
| os.path.dirname(__file__), "data", "cc4d_error_types.json" | |
| ) | |
| cc4d_global_error_types = [] | |
| if os.path.isfile(etypes_path): | |
| with open(etypes_path) as f: | |
| et_raw = json.load(f) | |
| cc4d_global_error_types = [ | |
| f"{e['type']}: {e['desc']}" for e in et_raw.get("error_types", []) | |
| ] | |
| # 每个视频都用同一份全局错误类型 (放进 task_error_patterns, key=activity_id) | |
| for tt in set(task_type_by_video.values()): | |
| task_error_patterns[tt] = cc4d_global_error_types | |
| steps_path = os.path.join( | |
| os.path.dirname(__file__), "data", "cc4d_task_correct_steps.json" | |
| ) | |
| if os.path.isfile(steps_path): | |
| with open(steps_path) as f: | |
| steps_raw = json.load(f) | |
| for tt, lst in steps_raw.items(): | |
| if tt.startswith("_"): continue | |
| if isinstance(lst, list): | |
| task_correct_steps_map[tt] = lst | |
| logger.info(f"[task knowledge] loaded {len(task_type_by_video)} taskType mappings, " | |
| f"{len(task_error_patterns)} error pattern hints, " | |
| f"{len(task_correct_steps_map)} correct-step canonical sequences") | |
| except Exception as e: | |
| logger.warning(f"[task knowledge] failed to load (will fallback to no hints): {e}") | |
| # 5) 逐视频建图 (resume 友好: 已完整跑完的视频写 _BUILD_DONE 标记, 重跑跳过) | |
| DONE_MARKER = "_BUILD_DONE" | |
| for i, vn in enumerate(video_names): | |
| vp = _video_path_for(args.holoassist_root, vn) | |
| if vp is None: | |
| logger.warning(f"[{i+1}/{len(video_names)}] {vn}: video file not found, skip") | |
| continue | |
| wd = os.path.join(args.save_root, f"{vn}-{args.datasets_type}-{args.caption_model}") | |
| done_marker = os.path.join(wd, DONE_MARKER) | |
| if os.path.isfile(done_marker): | |
| logger.info(f"[{i+1}/{len(video_names)}] {vn}: already done (marker present), skip") | |
| continue | |
| if os.path.isdir(wd) and os.listdir(wd): | |
| logger.info(f"[{i+1}/{len(video_names)}] {vn}: working_dir exists but no DONE marker → 重新建图(将覆盖)") | |
| # 简单起见: 不做 partial-resume(HoloAssist 一个视频通常 5-15 分钟, 重头跑可接受); | |
| # 把 wd 清掉以避免与旧的 hypergraph.json 混 | |
| try: | |
| import shutil | |
| shutil.rmtree(wd) | |
| except Exception as e: | |
| logger.warning(f" failed to clean stale wd: {e}") | |
| logger.info(f"[{i+1}/{len(video_names)}] switching working_dir -> {wd}") | |
| _reset_hyper_vg_working_dir(hyper_vg, wd) | |
| # 注入该视频的 taskType + 常见错误 hint + 正确步骤序列 给 fact_extractor | |
| # (run-to-run mutates the same VideoFactExtractor instance) | |
| try: | |
| cur_task_type = task_type_by_video.get(vn, "unknown") | |
| cur_hints = task_error_patterns.get(cur_task_type, []) | |
| cur_steps = task_correct_steps_map.get(cur_task_type, []) | |
| fe = hyper_vg.hypergraph_builder._fact_extractor # type: ignore[attr-defined] | |
| fe._task_type = cur_task_type | |
| fe._task_error_hints = cur_hints | |
| fe._task_correct_steps = cur_steps | |
| logger.info( | |
| f" task_type={cur_task_type!r}, " | |
| f"injected {len(cur_hints)} error hints + {len(cur_steps)} correct steps" | |
| ) | |
| except Exception as e: | |
| logger.warning(f" failed to inject task hints: {e}") | |
| sp_extractor = None | |
| if args.enable_structured_perception: | |
| from hypervideo.modules.structured_perception import ( | |
| StructuredPerceptionExtractor, get_sp_prompt_for_dataset) | |
| sp_extractor = StructuredPerceptionExtractor( | |
| vllm_base_url=args.vllm_base_url, | |
| vllm_model_name=args.vllm_model_name, | |
| working_dir=wd, | |
| prompt_template=get_sp_prompt_for_dataset("captaincook4d"), | |
| interval_seconds=args.interval_seconds, | |
| max_new_tokens=args.sp_max_new_tokens, | |
| ) | |
| try: | |
| run_holoassist_video_construction( | |
| hyper_vg=hyper_vg, | |
| video_path=vp, | |
| video_name=vn, | |
| interval_sec=args.interval_seconds, | |
| window_frames=args.window_frames, | |
| max_new_tokens=args.max_new_tokens, | |
| day_num=1, | |
| frame_captions_out_path=os.path.join(wd, "frame_captions.json"), | |
| sp_extractor=sp_extractor, | |
| ) | |
| # 视频完整跑完 -> 写 DONE 标记 | |
| try: | |
| with open(done_marker, "w") as f: | |
| f.write(time.strftime("%Y-%m-%d %H:%M:%S\n")) | |
| except Exception as e: | |
| logger.warning(f" failed to write DONE marker: {e}") | |
| except KeyboardInterrupt: | |
| logger.warning(f"[{i+1}/{len(video_names)}] {vn}: interrupted — DONE marker NOT written, will rerun next time") | |
| raise | |
| except Exception as e: | |
| logger.exception(f"[{i+1}/{len(video_names)}] {vn}: failed — DONE marker NOT written: {e}") | |
| # 继续下一个视频, 不中断整个 batch | |
| # 5) 释放 GPU | |
| try: | |
| hyper_vg.caption_model = None | |
| hyper_vg.video_llm = None | |
| gc.collect() | |
| if torch.cuda.is_available(): | |
| torch.cuda.empty_cache() | |
| except Exception: | |
| pass | |
| logger.info("[HoloAssist] all done.") | |
| if __name__ == "__main__": | |
| main() | |