File size: 26,378 Bytes
9f313a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
"""ESTP-Bench async build entry —— 严格仿照 ``ovobench_async_processing.py``。

设计原则(与 CLAUDE.md 一致:尽量复用、不改动现有代码):
  * 逐帧 caption / HyperVideoGraph / async pipeline(v1/v2/v3)全部复用
    ``ovobench_async_processing._run_one_video_async``,不重写一行流水逻辑。
  * 仅替换三处 ESTP 特有部分:
      1. 数据加载: 读 ESTP 两层 dict json, 抽取 164 个有 QA 的 video_uuid。
      2. 视频路径: full_scale_2fps_max384/{video_uuid}.mp4。
      3. caption prompt: 用 FRAME_CAPTION_WINDOW_ESTP_PROMPT(通过
         _run_one_video_async 已有的 caption_prompt_template 参数注入,
         它在 batch 模式下是最高优先级模板, 无需改 ovobench 代码)。
  * 输出目录: all_results/estp_hyper/{video_uuid}_{caption_model_name}/

运行示例(必须先 export LD_LIBRARY_PATH, 且从 VideoRAG-algorithm 目录用 -m 跑):
  export LD_LIBRARY_PATH=/root/miniconda3/envs/egoserve/lib:$LD_LIBRARY_PATH
  python -m hypervideo.estp_async_processing \
      --caption_model_name qwen_vllm \
      --vllm_base_url http://10.0.0.27:8001/v1 \
      --vllm_model_name Qwen3-VL-8B-Instruct \
      --only_uuids "200a8f32-c44a-463d-ba39-0190a0bddf7a,..." \
      --cuda 0
"""

from __future__ import annotations

import argparse
import json
import logging
import os
import sys
import time
from typing import List, Optional

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from videorag._utils import always_get_an_event_loop  # noqa: E402

from hypervideo.hyper_video_graph import HyperVideoGraph  # noqa: E402
from hypervideo.modules.async_pipeline import AsyncPipelineStats, LLMTimer  # noqa: E402
from hypervideo.config import HyperVideoConfig  # noqa: E402

# 复用 ovobench 的所有流水实现(caption / builder / async pipeline / save)。
from hypervideo.ovobench_async_processing import _run_one_video_async  # noqa: E402
from hypervideo.ovobench_hyper_processing import (  # noqa: E402
    _reset_hyper_vg_working_dir,
    default_llm_config,
    clear_gpu_memory,
)
# ESTP 专用 caption prompt(本次新增, 不改任何现有 prompt)。
from hypervideo.prompts.frame_caption_prompt import (  # noqa: E402
    FRAME_CAPTION_WINDOW_ESTP_PROMPT,
    FRAME_CAPTION_WINDOW_ESTP_QAWARE_PROMPT,
    FRAME_CAPTION_WINDOW_ESTP_QAWARE_V2_PROMPT,
)

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


# =====================================================================
# 数据加载 —— ESTP 两层 dict -> 扁平 video 列表
# =====================================================================

def load_estp_videos(data_path: str) -> List[dict]:
    """[旧, 保留不删] 逐视频整段建图单位(164 个视频, 每个一张超图)。

    建图单位是 video_uuid; QA / segment 信息仅用于日志统计。
    现已被 ``load_estp_clips`` 取代(建图单位改为唯一 clip 区间), 仅为向后兼容保留。"""
    with open(data_path, "r", encoding="utf-8") as f:
        all_data = json.load(f)

    videos: List[dict] = []
    for video_uuid, qa_dict in all_data.items():
        if not qa_dict:  # 没有任何 QA 的视频跳过
            continue
        n_seg = 0
        for _qa_uuid, segs in qa_dict.items():
            if isinstance(segs, list):
                n_seg += len(segs)
        videos.append({
            "id": video_uuid,
            "n_qa": len(qa_dict),
            "n_segments": n_seg,
        })
    return videos


def _estp_item_clip_range(item: dict):
    """从单个 QA item 取 (clip_start_sec, clip_end_sec)。

    ESTP json 里有两种 item schema:
      A) {'clip_start_time', 'clip_end_time', 'Task Type', 'question', 'qa_id', ...}
      B) {'start_time', 'end_time', 'duration', 'video_uid', 'Task Type', ...}
    两者都表示一个 clip 时间区间, 统一抽出。"""
    if "clip_start_time" in item:
        return float(item["clip_start_time"]), float(item["clip_end_time"])
    return float(item["start_time"]), float(item["end_time"])


def load_estp_clips(data_path: str) -> List[dict]:
    """读取 ESTP json({video_uuid: {segment_uuid: [qa_item, ...]}}), 按
    **唯一 clip 区间** 返回建图单位列表。

    建图单位 = 唯一 (video_uuid, clip_start_time, clip_end_time) 三元组,
    而不是整视频, 也不是单条 QA。同一 clip 下的多个 QA 共用一张图。

    返回每项:
      {
        'id'              : 用作 working_dir 区分的唯一键 (含 video + clip 区间),
        'video_uuid'      : 视频 uuid (用于定位 mp4),
        'clip_start_time' : float 秒,
        'clip_end_time'   : float 秒,
        'segment_uuid'    : 代表性 segment_uuid (若一个 clip 跨多个则取首个),
        'segment_uuids'   : 该 clip 命中的全部 segment_uuid 列表,
        'n_qa'            : 该 clip 覆盖的 QA 数,
      }

    注意: 同一 clip 区间可能被多个 segment_uuid 引用; 此处按区间去重, 一个区间只
    建一张图。"""
    with open(data_path, "r", encoding="utf-8") as f:
        all_data = json.load(f)

    # key=(video_uuid, clip_start, clip_end) -> 聚合信息
    agg = {}
    for video_uuid, seg_dict in all_data.items():
        if not seg_dict:
            continue
        for segment_uuid, items in seg_dict.items():
            if not isinstance(items, list):
                continue
            for it in items:
                try:
                    cs, ce = _estp_item_clip_range(it)
                except (KeyError, TypeError, ValueError):
                    logger.warning(f"  跳过缺时间区间的 item: video={video_uuid} seg={segment_uuid}")
                    continue
                key = (video_uuid, cs, ce)
                rec = agg.get(key)
                if rec is None:
                    rec = {
                        "video_uuid": video_uuid,
                        "clip_start_time": cs,
                        "clip_end_time": ce,
                        "segment_uuids": [],
                        "n_qa": 0,
                        # q-aware 建图用: 收集该 clip 覆盖的全部 (qa_id, question)。
                        "questions": [],
                    }
                    agg[key] = rec
                if segment_uuid not in rec["segment_uuids"]:
                    rec["segment_uuids"].append(segment_uuid)
                rec["n_qa"] += 1
                # 收集问题文本(开放式, 无 options)。两种 schema:
                #   A) 有显式 'question' 字段。
                #   B) 无 'question', 问题在 conversation 第一条 role=user 的 content 里
                #      (assistant 那条是答案, 绝不取, 避免泄露)。
                qtext = (it.get("question") or "").strip()
                if not qtext:
                    conv = it.get("conversation")
                    if isinstance(conv, list):
                        for turn in conv:
                            if isinstance(turn, dict) and turn.get("role") == "user":
                                qtext = (turn.get("content") or "").strip()
                                break
                if qtext:
                    rec["questions"].append({
                        "qid": str(it.get("qa_id", "")),
                        "question": qtext,
                    })

    clips: List[dict] = []
    for (video_uuid, cs, ce), rec in agg.items():
        seg0 = rec["segment_uuids"][0] if rec["segment_uuids"] else "noseg"
        # 用 video + 区间(整数秒) 作为稳定唯一键, 避免同视频多 clip 互相覆盖
        clip_id = f"{video_uuid}_{int(round(cs))}_{int(round(ce))}"
        clips.append({
            "id": clip_id,
            "video_uuid": video_uuid,
            "clip_start_time": cs,
            "clip_end_time": ce,
            "segment_uuid": seg0,
            "segment_uuids": rec["segment_uuids"],
            "n_qa": rec["n_qa"],
            "questions": rec.get("questions", []),
        })
    # 稳定排序: 先 video, 再起始时间
    clips.sort(key=lambda c: (c["video_uuid"], c["clip_start_time"]))
    return clips


# =====================================================================
# Per-sample wrapper —— 仿 ovobench process_one_video_async, 改路径 + prompt
# =====================================================================

def process_one_video_async(
    video_data: dict,
    hyper_vg: HyperVideoGraph,
    args,
    llm_timer: Optional[LLMTimer] = None,
) -> tuple:
    """与 ovobench_async_processing.process_one_video_async 同契约, 仅:
      * 视频路径用 full_scale_2fps_max384/{uuid}.mp4
      * caption_prompt_template 传 FRAME_CAPTION_WINDOW_ESTP_PROMPT
      * 输出目录 estp_hyper/{uuid}_{model}
    其余(async pipeline / 落盘 frame_captions.json + hypergraph.json)全复用。

    返回 (did_work, async_stats_or_None)。

    建图单位为 clip 区间: video_data 含 video_uuid + clip_start_time/clip_end_time,
    working_dir 用 clip 粒度的 ``id`` 区分(同视频多 clip 不会互相覆盖), 并把
    clip 区间通过 clip_start_sec/clip_end_sec 传给底层 sampler, 只对该时间窗采帧。"""
    clip_id = video_data["id"]
    video_uuid = video_data.get("video_uuid", clip_id)
    clip_start = video_data.get("clip_start_time")
    clip_end = video_data.get("clip_end_time")
    working_dir = (
        f"{args.save_root}/{args.datasets_type}/{clip_id}_{args.caption_model_name}"
    )
    hypergraph_path = os.path.join(working_dir, "hypergraph.json")

    # 断点续建: 仅当 hypergraph.json 存在【且非空壳(>1KB)】才算已建好。
    # 修(2026-06-26): 旧版只判 exists, 把 190B 空壳(之前 vllm 中断留下)误判已完成而跳过。
    if os.path.exists(hypergraph_path) and os.path.getsize(hypergraph_path) > 1000:
        logger.info(f"跳过 id={clip_id}(hypergraph.json 已建好)")
        return False, None

    video_path = os.path.join(args.video_path, f"{video_uuid}.mp4")
    if not os.path.exists(video_path):
        logger.error(f"  视频不存在: {video_path}")
        return False, None

    os.makedirs(working_dir, exist_ok=True)
    _reset_hyper_vg_working_dir(hyper_vg, working_dir)

    # ------------------------------------------------------------------
    # q-aware 建图(--qaware): ESTP 问题在视频开始前即给出, 故合规。
    #   * caption: 用带 {questions_block} 的 q-aware 模板 + question_with_option。
    #   * fact   : 通过 forward_questions 注入 dataset_mode=estpbench_qaware 的 prompt。
    # 非 qaware(默认): 完全保持原行为(空问题 + 原 ESTP 模板 + estpbench)。
    # ------------------------------------------------------------------
    qaware = getattr(args, "qaware", False)
    clip_questions = video_data.get("questions", []) or []
    if qaware and clip_questions:
        # 该 clip 的全部开放式 question 拼成一个 block(无 options, 不泄露答案)。
        q_with_opts = "\n".join(
            q.get("question", "") for q in clip_questions if q.get("question")
        )
        try:
            hyper_vg.hypergraph_builder._config.forward_questions = clip_questions
            hyper_vg.hypergraph_builder._fact_extractor._forward_questions = clip_questions
        except Exception as e:
            logger.warning(f"  [qaware] 注入 forward_questions 失败: {e}")
        # caption_prompt_version=v2: GT 对齐版(第一人称 I + dense 秒级锚点 + 短事实句),
        # 输出 {"dense_caption":..., "description":...}, 解析端已加别名兼容。默认 v1 不变。
        if getattr(args, "caption_prompt_version", "v1") == "v2":
            caption_template = FRAME_CAPTION_WINDOW_ESTP_QAWARE_V2_PROMPT
        else:
            caption_template = FRAME_CAPTION_WINDOW_ESTP_QAWARE_PROMPT
    else:
        q_with_opts = ""
        caption_template = FRAME_CAPTION_WINDOW_ESTP_PROMPT

    if llm_timer is not None:
        llm_timer.reset()

    loop = always_get_an_event_loop()
    try:
        async_stats = loop.run_until_complete(_run_one_video_async(
            hyper_vg=hyper_vg,
            video_path=video_path,
            # q-aware 时把该 clip 问题喂进 caption(填 {questions_block}); 否则空。
            question_with_option=q_with_opts,
            interval_seconds=args.interval_seconds,
            window_frames=args.window_frames,
            max_new_tokens=args.max_new_tokens,
            day_num=1,
            # 关键: 注入 ESTP prompt(_run_one_video_async 在 batch 模式下
            # 把非 None 的 caption_prompt_template 作为最高优先级模板使用)
            caption_prompt_template=caption_template,
            frame_captions_out_path=os.path.join(working_dir, "frame_captions.json"),
            caption_mode=args.caption_mode,
            per_frame_concurrency=args.per_frame_concurrency,
            llm_timer=llm_timer,
            caption_max_image_side=getattr(args, "caption_max_image_side", 0),
            caption_jpeg_quality=getattr(args, "caption_jpeg_quality", 85),
            use_fast_prompt=False,
            caption_concurrency=getattr(args, "caption_concurrency", 1),
            pipeline_mode=getattr(args, "pipeline_mode", "v1"),
            # 只对该 clip 的时间窗 [clip_start, clip_end] 采帧, 时间轴不平移
            clip_start_sec=clip_start,
            clip_end_sec=clip_end,
        ))
        # ----------------------------------------------------------------
        # 关键修复: _run_one_video_async 的 save_fn 只调用 save_hypergraph(),
        # 它落盘的是「空的」dual_index(建图阶段从不计算 embedding, embed=0calls),
        # 导致 hypergraph_embeddings.npz files=[] / 向量总数=0, 检索完全失效。
        #
        # OVO 路径之所以 npz 非空, 是因为它建完图后还会跑 retrieval, 由
        # retrieve()->ensure_retrieval_index() 惰性 rebuild+save 填充 npz。
        # ESTP 是「只建图」流程, 没有后续 retrieval, 故必须在建图收尾时主动
        # 触发一次 embedding 计算并落盘。ensure_retrieval_index() 内部:
        #   index_dirty(建图已置 True) -> dual_index.rebuild(hypergraph)
        #   -> 对 facts/episodes/topics 调 embedding_func(随 default_llm_config,
        #      与 OVO 一致) -> save() 覆盖 npz。
        # 该调用仅作用于本 clip 的 hyper_vg(已 _reset 到本 clip 的 working_dir),
        # 不触及 OVO 共享流水, 不会回归 OVO 行为。
        loop.run_until_complete(hyper_vg.ensure_retrieval_index())
        emb_stats = hyper_vg.dual_index._emb_index._embeddings.get_stats()
        logger.info(
            f"  [Embed] id={clip_id} 建图后已计算并落盘 embedding, stats={emb_stats}"
        )
        return True, async_stats
    except Exception as e:
        logger.error(f"  建图失败 id={clip_id}: {e}")
        return False, None
    finally:
        clear_gpu_memory()


# =====================================================================
# Main —— 仿 ovobench main, 改数据加载 + 默认路径
# =====================================================================

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--data_path", type=str,
        default="/mnt/tokyo-ai/gst/ESTP-IT/ESTP-Bench/estp_dataset/estp_bench_sq.json",
    )
    parser.add_argument(
        "--video_path", type=str,
        default="/mnt/tokyo-ai/gst/ESTP-IT/ESTP-Bench/full_scale_2fps_max384",
    )
    parser.add_argument(
        "--save_root", type=str,
        default="/mnt/tokyo-ai/gst/GST_EGOSERVE/all_results",
    )
    parser.add_argument(
        "--caption_model_name", type=str, default="qwen_api",
        help="qwen_api (DashScope) / qwen_vllm (本地或远程 vLLM server)",
    )
    parser.add_argument("--qwen_api_model", type=str, default="qwen-vl-max")
    parser.add_argument(
        "--vllm_base_url", type=str,
        default=os.environ.get("VLLM_BASE_URL", "http://localhost:8000/v1"),
        help="vLLM OpenAI 兼容端点; 仅当 --caption_model_name=qwen_vllm 时使用。",
    )
    parser.add_argument(
        "--vllm_model_name", type=str,
        default=os.environ.get("VLLM_MODEL_NAME", "Qwen3-VL-8B-Instruct"),
        help="必须与 vLLM server 的 --served-model-name 一致。",
    )
    parser.add_argument(
        "--qwen_api_key", type=str,
        default="YOUR_API_KEY",
    )
    parser.add_argument("--datasets_type", type=str, default="estp_hyper")
    parser.add_argument("--cuda", type=str, default="0")
    # ESTP 视频已是 2fps; window_frames=5 => 每窗 ~2.5s, 与 ovobench 默认一致。
    parser.add_argument("--interval_seconds", type=float, default=2.0)
    parser.add_argument("--window_frames", type=int, default=5)
    parser.add_argument("--max_new_tokens", type=int, default=2048)
    parser.add_argument("--caption_mode", type=str, default="batch", choices=["batch", "per_frame"])
    parser.add_argument("--per_frame_concurrency", type=int, default=5)
    parser.add_argument("--qaware", action="store_true",
                        help="带问题建图: 把该 clip 的 question 喂进 caption+fact prompt "
                             "(ESTP 问题在视频前即给出, 合规)。默认关闭=原开放式建图。")
    parser.add_argument("--caption_prompt_version", type=str, default="v1",
                        choices=["v1", "v2"],
                        help="qaware caption prompt 版本: v1=第三人称详述(默认); "
                             "v2=GT对齐版(第一人称I+dense秒级锚点+短事实句)。仅 --qaware 时生效。")
    parser.add_argument("--only_uuids", type=str, default=None,
                        help="仅处理指定 video_uuid, 逗号分隔(小批量验证用)")
    parser.add_argument("--limit", type=int, default=0,
                        help="若 >0, 只处理前 N 个未完成视频(小批量验证用)")
    parser.add_argument(
        "--caption_max_image_side", type=int, default=0,
        help="若 >0 把每帧缩放至 max(W,H)<=该值。ESTP 已是 max384, 默认 0 不缩放。",
    )
    parser.add_argument("--caption_jpeg_quality", type=int, default=85)
    parser.add_argument(
        "--caption_concurrency", type=int, default=1,
        help="同时在飞行的 caption API 调用数。1=串行; 本地 vLLM 可上 4-8。",
    )
    parser.add_argument(
        "--pipeline_mode", type=str, default="v1", choices=["v1", "v2", "v3"],
        help="v1=plan A / v2=plan E / v3=plan B(同 ovobench 含义)。",
    )
    parser.add_argument(
        "--openai_api_key", type=str,
        default=os.environ.get("OPENAI_API_KEY", "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"),
    )
    parser.add_argument(
        "--timing_out_path", type=str, default=None,
        help="若设置, 输出每个 video 的耗时 + async 各 stage 耗时 JSON。",
    )
    parser.add_argument("--only_ids", type=str, default=None,
                        help="仅处理指定 clip id(含区间, 如 uuid_0_30), 逗号分隔"
                             "(冒烟验证用, 比 --only_uuids 更精细)")
    args = parser.parse_args()

    os.environ["CUDA_VISIBLE_DEVICES"] = args.cuda
    # 只在传了真实 key 时覆盖; 硬编码错 default(结尾6QcA)或没 key 时, 从 .env 取对 key
    if args.openai_api_key and not args.openai_api_key.endswith("6QcA"):
        os.environ["OPENAI_API_KEY"] = args.openai_api_key
    if (not os.environ.get("OPENAI_API_KEY")) or os.environ.get("OPENAI_API_KEY", "").endswith("6QcA"):
        from dotenv import load_dotenv
        load_dotenv("/mnt/tokyo-ai/gst/GST_EGOSERVE/.env")

    # 1. 加载 ESTP clip 列表(建图单位 = 唯一 clip 区间, 每个 clip 一张超图)
    all_videos = load_estp_clips(args.data_path)
    n_videos = len({c["video_uuid"] for c in all_videos})
    logger.info(
        f"共加载 {len(all_videos)} 个唯一 clip 区间(来自 {n_videos} 个 video), "
        f"QA 总数={sum(c['n_qa'] for c in all_videos)}"
    )

    if args.only_uuids:
        # 按 video_uuid 过滤(一个 video 可能含多个 clip)
        wanted = {s.strip() for s in args.only_uuids.split(",") if s.strip()}
        all_videos = [x for x in all_videos if x["video_uuid"] in wanted]
        logger.info(f"按 --only_uuids 过滤后剩余 {len(all_videos)} 个 clip")

    if args.only_ids:
        wanted_ids = {s.strip() for s in args.only_ids.split(",") if s.strip()}
        all_videos = [x for x in all_videos if x["id"] in wanted_ids]
        logger.info(f"按 --only_ids 过滤后剩余 {len(all_videos)} 个 clip")

    # 跳过已建图(按 clip 粒度的 id)
    unprocessed = []
    for item in all_videos:
        hg_path = os.path.join(
            args.save_root, args.datasets_type,
            f"{item['id']}_{args.caption_model_name}", "hypergraph.json",
        )
        # 修(2026-06-26): 空壳(<=1KB)视为未建, 需重建 (旧版只判 exists 把空壳误跳过)。
        if not (os.path.exists(hg_path) and os.path.getsize(hg_path) > 1000):
            unprocessed.append(item)
    skipped = len(all_videos) - len(unprocessed)
    if skipped > 0:
        logger.info(f"跳过已完成 {skipped} 个 clip, 剩余 {len(unprocessed)} 个")

    if args.limit and args.limit > 0:
        unprocessed = unprocessed[: args.limit]
        logger.info(f"按 --limit 截断到前 {len(unprocessed)} 个 clip")

    if not unprocessed:
        logger.info("全部已处理完毕")
        return

    # 2. 初始化 HyperVideoGraph(一次性, 跨视频共享; 逐视频 _reset working_dir)
    init_working_dir = os.path.join(
        args.save_root, args.datasets_type, f"_init_{args.caption_model_name}"
    )
    os.makedirs(init_working_dir, exist_ok=True)
    # q-aware 时用 estpbench_qaware(仅 fact_extractor 走 q-aware prompt,
    # segmenter/topic_aggregator 经 hypergraph_builder 别名仍按 estpbench 行为)。
    _ds_mode = "estpbench_qaware" if getattr(args, "qaware", False) else "estpbench"
    hyper_cfg = HyperVideoConfig(
        dataset_mode=_ds_mode,  # ESTP 专用三层 prompt(fact/episode/topic)
        caption_granularity="per_window",
        boundary_strategy="stream",
        caption_window_seconds=float(args.window_frames) * args.interval_seconds,
        caption_frame_interval_sec=args.interval_seconds,
        caption_mode=args.caption_mode,
    )
    logger.info(
        f"模式: caption_mode={args.caption_mode}, per_window, stream (V2 async), "
        f"caption prompt=FRAME_CAPTION_WINDOW_ESTP_PROMPT"
    )
    hyper_vg = HyperVideoGraph(
        working_dir=init_working_dir,
        llm=default_llm_config,
        hyper_config=hyper_cfg,
    )
    logger.info(f"加载 caption model: {args.caption_model_name}")
    if args.caption_model_name == "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_name == "qwen_vllm":
        hyper_vg.load_caption_model(
            "qwen_vllm",
            vllm_base_url=args.vllm_base_url,
            vllm_model_name=args.vllm_model_name,
        )
        logger.info(f"  vllm_base_url={args.vllm_base_url} model={args.vllm_model_name}")
    else:
        hyper_vg.load_caption_model(args.caption_model_name)
    logger.info(
        f"HyperVideoGraph 初始化完成, "
        f"stats={hyper_vg.hypergraph_builder.hypergraph.get_stats()}"
    )

    llm_timer = LLMTimer()

    # 3. 逐 clip 建图
    t_all = time.time()
    ok_count = 0
    timings: List[dict] = []
    for idx, video_data in enumerate(unprocessed):
        t0 = time.time()
        vid = video_data["id"]
        logger.info(
            f"[{idx+1}/{len(unprocessed)}] id={vid} "
            f"clip=[{video_data['clip_start_time']:.1f}, {video_data['clip_end_time']:.1f}]s "
            f"n_qa={video_data['n_qa']} seg={video_data['segment_uuid']}"
        )
        try:
            did_work, async_stats = process_one_video_async(
                video_data, hyper_vg, args, llm_timer=llm_timer,
            )
            if did_work:
                ok_count += 1
        except Exception as e:
            logger.error(f"  样本 id={vid} 处理异常: {e}")
            timings.append({"id": vid, "error": str(e), "elapsed_s": time.time() - t0})
            continue
        elapsed = time.time() - t0
        per_video_llm = llm_timer.summary()
        logger.info(
            f"[{idx+1}/{len(unprocessed)}] id={vid} 耗时 {elapsed:.1f}s | "
            f"LLM: best={per_video_llm['best_model']['n_calls']}calls/{per_video_llm['best_model']['total_s']:.1f}s "
            f"cheap={per_video_llm['cheap_model']['n_calls']}calls/{per_video_llm['cheap_model']['total_s']:.1f}s "
            f"embed={per_video_llm['embedding']['n_calls']}calls/{per_video_llm['embedding']['total_s']:.1f}s"
        )
        timings.append({
            "id": vid,
            "elapsed_s": elapsed,
            "llm_stats": per_video_llm,
            "async_stats": async_stats.as_dict() if async_stats is not None else None,
        })

    total = time.time() - t_all
    logger.info(
        f"\n{'='*80}\nESTP 建图完成 (async): 成功 {ok_count}/{len(unprocessed)}, "
        f"总耗时 {total:.1f}s ({total/60:.1f}min)\n{'='*80}"
    )

    if args.timing_out_path:
        try:
            os.makedirs(os.path.dirname(args.timing_out_path) or ".", exist_ok=True)
            with open(args.timing_out_path, "w", encoding="utf-8") as f:
                json.dump({
                    "datasets_type": args.datasets_type,
                    "total_seconds": total,
                    "ok_count": ok_count,
                    "total_videos": len(unprocessed),
                    "per_video": timings,
                }, f, ensure_ascii=False, indent=2)
            logger.info(f"Timing summary -> {args.timing_out_path}")
        except Exception as e:
            logger.error(f"保存 timing 失败: {e}")


if __name__ == "__main__":
    main()