taryya commited on
Commit
b4e315f
·
verified ·
1 Parent(s): 76039bd

Add remaining runningbench_handoff scripts (9) covering each layer per-layer repairs, plus 3 general early-era infra scripts

Browse files
multi_video_cross_video_methodology/README.md CHANGED
@@ -143,6 +143,35 @@ P03: 18段 · 同上 · Traj01/02/03
143
  **顺序值得记住**:`whole_video`先生成(每段录像自己的标注),`cross_video`是**用多段`whole_video`标注拼出来的**——
144
  两层共用同一次"全局遍历"的产出,不是两条独立流水线。
145
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
  ---
147
 
148
  ## 5. 闸门是怎么做的(5步,顺序不可改)
@@ -213,11 +242,23 @@ source_docs/
213
  master_index_1526_reviewed.jsonl 1,526题人工复核集的权威索引(真实5种unit的数据来源, 见§2)
214
  录像清单.csv 55条录像的完整元数据(participant/speed/lighting/route_id/shape/turnaround_sec等)
215
  cut_window_clips.py 切180秒窗口用的脚本(480p, 服务whole_video/cross_video的time_index证据)
 
 
 
 
 
 
 
 
 
216
  pilot_scripts_20260824/ 全项目最早的Gemini视频标注试点(v1/v2的原型, 见§2.5)
217
  gemini_video_pilot.py 单次调用最小样例
218
  run_gemini_annotation_pilot.py 批量编排: 切片→调Gemini→组装成可复核JSONL
219
  apply_gemini_pilot_reviews.py 合并人工复核意见, 同时保留Gemini原始提案供审计
220
  make_video_clip.py 更早的切片工具: 做隐私更安全、码率更低的试点用片段
 
 
 
221
  ```
222
 
223
  原始位置(conductor):`s3://yuedong/cvhci_video_understanding/bundles/runningbench_handoff/`
 
143
  **顺序值得记住**:`whole_video`先生成(每段录像自己的标注),`cross_video`是**用多段`whole_video`标注拼出来的**——
144
  两层共用同一次"全局遍历"的产出,不是两条独立流水线。
145
 
146
+ ### 4.3 `04_脚本/` 目录里其余9个脚本——覆盖了每一层各自的短板
147
+
148
+ `generate_cross_video_qa.py`和`build_fullvideo_annotations.py`只是这个目录的一部分。补全后能看出
149
+ 这条流水线其实是"哪层测出问题就专门写脚本修哪层",不是一次性设计好的:
150
+
151
+ - **`blind_test_segments.py`**——测出`segments_60s`真实盲猜率48.6%(不是官方宣称的17.6%, 那个数字只是
152
+ "选项字母分布均匀",不是"题需要看视频");**`repair_segment_distractors.py`**——照着测出来的问题重造干扰项,
153
+ 就是`segments_60s_gemini_verification/`里`blind_gate_repair_20260906/`那批脚本的同一条思路,但这里是
154
+ 更早的一版实现;**`export_segment_bundle.py`**——把修好的segment题打包成本地可跑闸门的自包含单元。
155
+ - **`annotate_missing_hf_60s.py`**——补7段HuggingFace录像缺失的60秒粒度标注,缺失不是随机的:
156
+ 同一场景的快/慢速版本都在,只有中间某个速度缺了60秒描述,像是标注批次中途断了没续上。
157
+ - **`annotate_windows_from_video.py`**——推翻了第一版180秒窗口题的做法:直接用已有60秒caption拼凑出的
158
+ 180秒标注写题,盲猜率68.4%,比它想改进的segment语料还差(复核本身没问题,3/76矛盾,纯粹是题目好猜)。
159
+ 改成让模型**真正看完整个180秒窗口**再写标注,才有了`build_window_questions.py`这层的题。
160
+ - **`build_window_questions.py`**——180秒窗口这层存在的理由:60秒只有一个阶段出不了转弯题,整段录像
161
+ 10-33分钟又太长,180秒正好落在"结构开始出现"的区间(摘录实验测过:产出率从1分钟42%涨到4分钟60%)。
162
+ - **`expand_mcq.py`**——纯文本扩充干扰项数量/每段题量,不解码不上传任何视频,读的是已有的`dense_annotations`。
163
+ - **`package_full_release.py`** / **`package_gdrive_release.py`**——两种打包范围: 全量(含HuggingFace+VideoBench,
164
+ covers剩下9,925道未判定题里的5,324道) vs 仅Google Drive子集(只有这个来源才带`scene_id`/`route_id`/
165
+ `turnaround_sec`这类路线元数据,路线类题目就是靠这个校验的)。
166
+
167
+ `cut_window_clips.py`(180秒窗口切片,见文件清单)也在这个目录,服务上面`build_window_questions.py`这条线。
168
+
169
+ ### 4.4 补充的通用早期脚本
170
+
171
+ `pilot_scripts_20260824/`除了原来的4个Gemini试点脚本,还补了3个同期的通用基础设施:
172
+ `build_manifest.py`(给CVHCI录像集建元数据清单)、`download_gdrive_ranges.py`(Google Drive大文件下载遇到
173
+ 限额页时按HTTP Range分片续传的兜底方案)、`make_contact_sheet.py`(从视频里等间隔抽帧拼联络表,人工核对用)。
174
+
175
  ---
176
 
177
  ## 5. 闸门是怎么做的(5步,顺序不可改)
 
242
  master_index_1526_reviewed.jsonl 1,526题人工复核集的权威索引(真实5种unit的数据来源, 见§2)
243
  录像清单.csv 55条录像的完整元数据(participant/speed/lighting/route_id/shape/turnaround_sec等)
244
  cut_window_clips.py 切180秒窗口用的脚本(480p, 服务whole_video/cross_video的time_index证据)
245
+ blind_test_segments.py 测出segments_60s真实盲猜率48.6%(见§4.3)
246
+ repair_segment_distractors.py 照测出的问题重造segments_60s干扰项(见§4.3)
247
+ export_segment_bundle.py 把修好的segment题打包成本地可跑闸门的自包含单元
248
+ annotate_missing_hf_60s.py 补7段HuggingFace录像缺失的60秒粒度标注
249
+ annotate_windows_from_video.py 让模型真正看完180秒窗口再写标注(取代盲猜率68.4%的第一版做法)
250
+ build_window_questions.py 180秒窗口这层的出题脚本(见§4.3, 为什么是180秒)
251
+ expand_mcq.py 纯文本扩充干扰项数量/每段题量, 不碰视频
252
+ package_full_release.py 全量打包(含HuggingFace+VideoBench, 给全体未判定题的人工筛选用)
253
+ package_gdrive_release.py 仅Google Drive子集打包(唯一带route_id等路线元数据的来源)
254
  pilot_scripts_20260824/ 全项目最早的Gemini视频标注试点(v1/v2的原型, 见§2.5)
255
  gemini_video_pilot.py 单次调用最小样例
256
  run_gemini_annotation_pilot.py 批量编排: 切片→调Gemini→组装成可复核JSONL
257
  apply_gemini_pilot_reviews.py 合并人工复核意见, 同时保留Gemini原始提案供审计
258
  make_video_clip.py 更早的切片工具: 做隐私更安全、码率更低的试点用片段
259
+ build_manifest.py 给CVHCI录像集建元数据清单
260
+ download_gdrive_ranges.py Google Drive大文件下载遇限额时按HTTP Range续传的兜底方案
261
+ make_contact_sheet.py 从视频等间隔抽帧拼联络表, 人工核对用
262
  ```
263
 
264
  原始位置(conductor):`s3://yuedong/cvhci_video_understanding/bundles/runningbench_handoff/`
multi_video_cross_video_methodology/source_docs/annotate_missing_hf_60s.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Cut and caption the seven HuggingFace recordings that never got a 60-second pass.
3
+
4
+ The 60s layer covers 65 of the 72 HuggingFace recordings on disk. The seven left out are
5
+ not random: kit_scc_hochhaus has both its fast and normal runs missing, sinzheim_city both
6
+ its normal and slow -- while other speeds of the same scene were done. That pattern reads
7
+ as a batch that died partway and was never resumed, not as unusable footage. They do have
8
+ 180s and whole-video descriptions, so the gap is specifically the fine granularity.
9
+
10
+ Reuses annotate_60s() from repair_runningbench_annotations.py so these segments come out
11
+ byte-compatible with the 1,342 that already exist -- same CAPTION_MODEL, same two-step
12
+ caption then structure pass, same five-field schema. Reimplementing the prompt would give
13
+ captions that read differently from every other row in the corpus.
14
+
15
+ Two things that module hardcodes for Google Drive have to be corrected here:
16
+ - source_video_id is written as "google_drive/<participant>/<file>"; these are
17
+ huggingface, and mislabelling provenance is what made the earlier source census wrong.
18
+ - discover_sources() expects <root>/<participant>/<file>, but this footage nests one
19
+ level deeper (Alec/sinzheim_city/sinzheim_city_slow.MOV), so the sources are passed
20
+ in explicitly instead of discovered.
21
+
22
+ Usage: annotate_missing_hf_60s.py [--dry-run] [--only STEM]
23
+ """
24
+ import argparse
25
+ import importlib.util
26
+ import json
27
+ import os
28
+ import sys
29
+ import types
30
+ from pathlib import Path
31
+
32
+ BASE = Path("/mnt/task_runtime/bolt/gdrive_relay")
33
+ HF_ROOT = Path("/mnt/data/cvhci_video_understanding/raw/huggingface")
34
+ WORK = Path("/mnt/data/data_anno/runningbench_hf_gapfill")
35
+ FFMPEG = Path("/mnt/data/data_anno/ffmpeg-7.0.2-amd64-static/ffmpeg")
36
+ FFPROBE = Path("/mnt/data/data_anno/ffmpeg-7.0.2-amd64-static/ffprobe")
37
+
38
+ # Explicit, because the layout nests deeper than discover_sources() expects.
39
+ MISSING = [
40
+ "Markus/BLB-Euro_Fast_260518_200852.mp4",
41
+ "Markus/Kiesweg_Fast_260518_202851.mp4",
42
+ "Alec/kit_mensa_scc/kit_mensa_scc_slow.mov",
43
+ "Alec/kit_scc_hochhaus/kit_scc_hochhaus_fast.mov",
44
+ "Alec/kit_scc_hochhaus/kit_scc_hochhaus_normal.mov",
45
+ "Alec/sinzheim_city/sinzheim_city_normal.mov",
46
+ "Alec/sinzheim_city/sinzheim_city_slow.MOV",
47
+ ]
48
+
49
+
50
+ def load(name, path):
51
+ spec = importlib.util.spec_from_file_location(name, path)
52
+ mod = importlib.util.module_from_spec(spec)
53
+ spec.loader.exec_module(mod)
54
+ return mod
55
+
56
+
57
+ def main():
58
+ ap = argparse.ArgumentParser()
59
+ ap.add_argument("--dry-run", action="store_true")
60
+ ap.add_argument("--only", help="process just the recording whose stem matches")
61
+ a = ap.parse_args()
62
+
63
+ gen = load("gen", BASE / "repair_runningbench_annotations.py")
64
+
65
+ sources = []
66
+ for rel in MISSING:
67
+ p = HF_ROOT / rel
68
+ if not p.exists():
69
+ print(f" !! missing on disk: {rel}", flush=True)
70
+ continue
71
+ if a.only and a.only not in p.stem:
72
+ continue
73
+ sources.append(p)
74
+
75
+ total_segments = 0
76
+ for p in sources:
77
+ secs = gen.duration(FFPROBE, p)
78
+ n = int(-(-secs // 60))
79
+ total_segments += n
80
+ print(f" {p.stem:44s} {secs:7.1f}s -> {n:2d} segments", flush=True)
81
+ print(f"\n{len(sources)} recordings · {total_segments} segments", flush=True)
82
+ if a.dry_run:
83
+ return 0
84
+
85
+ # Correct the provenance string the reused module writes. Patching the module's own
86
+ # helper keeps annotate_60s() untouched, so its resume logic and schema stay intact.
87
+ original_write = gen.write_json
88
+
89
+ def write_json(path, payload):
90
+ src = payload.get("original_video_path") or ""
91
+ if "huggingface" in src:
92
+ rel = os.path.relpath(src, HF_ROOT)
93
+ payload["source_video_id"] = f"huggingface/{rel}"
94
+ payload["provenance"] = "huggingface"
95
+ return original_write(path, payload)
96
+
97
+ gen.write_json = write_json
98
+
99
+ api = gen.Floodgate(os.environ.get("FLOODGATE_PROJECT_TOKEN", ""))
100
+ args = types.SimpleNamespace(work=WORK, ffmpeg=FFMPEG, ffprobe=FFPROBE)
101
+ WORK.mkdir(parents=True, exist_ok=True)
102
+
103
+ for i, source in enumerate(sources, 1):
104
+ # The "participant" is only used to name output subdirectories; for this footage
105
+ # the top-level HuggingFace folder (Alec / Markus) is the meaningful grouping.
106
+ participant = os.path.relpath(source, HF_ROOT).split(os.sep)[0]
107
+ print(f"\nsource {i}/{len(sources)}: {participant}/{source.name}", flush=True)
108
+ try:
109
+ gen.annotate_60s(args, api, source, participant)
110
+ except Exception as exc:
111
+ print(f" !! {type(exc).__name__}: {exc}", flush=True)
112
+
113
+ done = sorted(WORK.glob("annotations_60s/**/*.json"))
114
+ print(f"\n{len(done)} annotations -> {WORK}/annotations_60s")
115
+ ok = sum(1 for f in done if (json.loads(f.read_text()).get("dense_annotations")))
116
+ print(f" with dense_annotations: {ok}/{len(done)}")
117
+ return 0
118
+
119
+
120
+ if __name__ == "__main__":
121
+ sys.exit(main())
multi_video_cross_video_methodology/source_docs/annotate_windows_from_video.py ADDED
@@ -0,0 +1,518 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Annotate the 180-second windows by WATCHING them, then build questions from that.
3
+
4
+ Why this replaces the previous attempt. The first pass wrote questions from the existing
5
+ 180s annotations, which are aggregations of three 60s captions -- `derived_from` names
6
+ them -- and the pilot came back at 68.4% blind-guessable (CI [57.3, 77.8]), worse than the
7
+ segment corpus it was meant to improve on. The re-check gate was fine: only 3 of 76 were
8
+ contradicted. The questions were simply easy to guess, and by question type the failure was
9
+ total where it should have been strongest -- window-turn-sequence scored 0/19.
10
+
11
+ Aggregation is what broke it. Merging three minute-long captions flattens exactly what a
12
+ three-minute question needs: a pedestrian in a blue bucket hat becomes "a pedestrian", a
13
+ specific turn at a specific marker becomes "the path curves". Generic ground truth can only
14
+ produce generic options, and then "which option sounds most coherent" is a winning strategy
15
+ without watching anything.
16
+
17
+ So the annotation is made from the footage at the scale the questions are asked at. Two
18
+ things carry over from the full-video pipeline, which reaches 7.3% blind on 8-option multi:
19
+
20
+ 1. Its structural schema -- route_phases, turns, revisited_landmarks, environment_stages,
21
+ dynamic_events -- rather than the 60s pass's frame-level five fields. Order and
22
+ progression are what three minutes supports asking about.
23
+ 2. A clock burned into the top-left corner, one frame per second, showing true recording
24
+ time. The model reads timestamps instead of estimating them; the full-video pass found
25
+ estimates drifting +240 s over a 448 s video, and a question about what happened first
26
+ is worthless if the annotation's own ordering is guesswork.
27
+
28
+ Usage:
29
+ annotate_windows_from_video.py --clips-only # re-cut with the clock, no API
30
+ annotate_windows_from_video.py --pilot 8 # annotate + questions + gates
31
+ annotate_windows_from_video.py --all --jobs 2
32
+ """
33
+ import argparse
34
+ import base64
35
+ import collections
36
+ import concurrent.futures
37
+ import glob
38
+ import hashlib
39
+ import importlib.util
40
+ import json
41
+ import math
42
+ import os
43
+ import random
44
+ import re
45
+ import shutil
46
+ import subprocess
47
+ import sys
48
+ import threading
49
+ from pathlib import Path
50
+
51
+ BASE = Path("/mnt/task_runtime/bolt/gdrive_relay")
52
+ SRC = "/mnt/data/data_anno/runningbench_gap_repair/annotations_180s"
53
+ OUT = Path("/mnt/data/data_anno/runningbench_windows_v2")
54
+ CLIPS = OUT / "clips_clock_480p"
55
+ FFMPEG = "/mnt/data/data_anno/ffmpeg-7.0.2-amd64-static/ffmpeg"
56
+ INLINE_CAP = 11 * 1024 * 1024
57
+ QUOTA_PER_SECOND = 0.45
58
+ SEED = 20260831
59
+
60
+ TYPES = ("window-event-order", "window-turn-sequence",
61
+ "window-environment-shift", "window-object-timing")
62
+
63
+ LEAK = ("trial", "traj", ".mov", ".mp4", "filename", "annotation",
64
+ "described", "the description", "the evidence", "per the", "according to the")
65
+
66
+ OUT_OF_SCENE = ("beach", "highway", "motorway", "forest", "woods", "indoor", "shopping mall",
67
+ "airport terminal", "subway", "train station", "stadium", "boardwalk",
68
+ "desert", "mountain trail", "swimming", "driving", "dashboard", "cockpit")
69
+
70
+ ANNOTATE_PROMPT = """You are watching a {length}-second stretch of a first-person walking/running recording,
71
+ anonymous id {vid}. The stretch covers {p0}-{p1} seconds of the full recording. Do not infer
72
+ anything from a filename -- you have none.
73
+
74
+ A clock in the TOP-LEFT corner shows the true recording time as MM:SS. READ every time you
75
+ report from that clock and convert to seconds; never estimate time from pacing.
76
+
77
+ Your job is the STRUCTURE of this stretch, in order, and the DISTINCTIVE detail that
78
+ identifies each place. Both matter: order alone gives questions no grounding, and detail
79
+ alone gives no order to ask about.
80
+
81
+ Return one JSON object:
82
+ {{
83
+ "route_phases": [ {{"start_sec": {p0}, "end_sec": 0, "description": "...",
84
+ "landmarks": ["specific, identifying, not 'a building'"],
85
+ "surface": "asphalt|gravel|paved|dirt|mixed", "setting": "..."}} ],
86
+ "turns": [ {{"time_sec": 0, "direction": "left|right|u-turn|straight-on",
87
+ "sharpness": "gentle|moderate|sharp", "evidence": "what marks it"}} ],
88
+ "revisited_landmarks": [ {{"landmark": "...", "first_sec": 0, "second_sec": 0,
89
+ "direction_change": "same|opposite|unclear"}} ],
90
+ "environment_stages": ["how the surroundings progress, in order"],
91
+ "dynamic_events": [ {{"time_sec": 0, "description": "...",
92
+ "kind": "person|vehicle|animal|obstacle|other"}} ],
93
+ "distinctive_objects": [ {{"object": "...", "attributes": ["colour", "material", "..."],
94
+ "side": "left|right|ahead|overhead", "seen_sec": 0}} ],
95
+ "uncertainties": ["..."]
96
+ }}
97
+
98
+ Phases must tile {p0}-{p1} seconds in order: each end_sec equals the next start_sec, the
99
+ first start_sec is {p0}, the last end_sec is {p1}.
100
+
101
+ Name landmarks and objects specifically enough that someone could recognise this exact
102
+ place -- "a red and white striped warning pole", not "a pole". Use only what is visible."""
103
+
104
+ Q_PROMPT = """Write exactly {n} benchmark questions about ONE {length}-second stretch of a first-person
105
+ walking/running video, anonymous id {vid}, covering {p0}-{p1} seconds of the recording.
106
+
107
+ ANNOTATION (the only ground truth; it was written while watching this exact stretch):
108
+ {annotation}
109
+
110
+ Each question must need the WHOLE stretch. A question answerable from one frame, or from any
111
+ single minute of it, does not belong here: ask about order, about change across the stretch,
112
+ about what happened before or after what.
113
+
114
+ Use these types, spread evenly: {types}
115
+ window-event-order the sequence in which events occur across the stretch
116
+ window-turn-sequence the trajectory: which turns, in which order, how sharp
117
+ window-environment-shift how the surroundings change from the start to the end
118
+ window-object-timing which objects appear in which part of the stretch
119
+
120
+ FORMAT -- exactly 8 options, of which exactly 3 are correct. Return the three correct ones
121
+ first; they get shuffled afterwards.
122
+
123
+ THE FIVE WRONG OPTIONS ARE THE HARD PART. An earlier version of this task returned 68% of
124
+ its questions answerable with no video at all, and every one of its turn-sequence questions
125
+ failed. Read all of this.
126
+
127
+ A wrong option must be wrong ONLY because the video says otherwise -- never because a reader
128
+ can rule it out from the setting. Someone who knows this is a person on foot outdoors, and
129
+ nothing else, must find all eight equally possible. So:
130
+
131
+ - Build them from THIS stretch's own specifics: the landmarks, objects and turns the
132
+ annotation names. Use the identifying detail -- "the red and white striped pole", not
133
+ "a pole" -- in wrong options as much as in right ones. Generic wrong options next to
134
+ specific correct ones is the single clearest tell.
135
+ - Make them wrong by COMPOSITION, not by content: the right things in the wrong order, an
136
+ event placed in the wrong phase, two landmarks swapped, a turn given the wrong direction
137
+ or the wrong sharpness, an object moved to the other side of the path.
138
+ - Do NOT write each wrong option as a correct one with a single detail edited. If every
139
+ wrong option is one edit from a right one, then on each detail the correct value is the
140
+ majority value, and the answer can be recovered by taking the most common colour, count
141
+ or side -- no video needed. A set built that way once drove blind guessing from 48.6%
142
+ to 75%.
143
+ - Vary which details differ and how many: change two or three at once, in different
144
+ combinations, so no option sits at the centre of the set.
145
+ - Keep all eight the same length and specificity. The correct options must not be the
146
+ longest or the most detailed -- picking the longest option alone wins 42.2% of
147
+ single-answer questions in an earlier corpus.
148
+
149
+ Every question carries evidence_spans in seconds of the FULL recording, inside {p0}-{p1}.
150
+
151
+ Return only:
152
+ {{"questions": [{{"question": "...", "question_type": "...",
153
+ "options": ["correct 1", "correct 2", "correct 3", "wrong 1", "wrong 2", "wrong 3", "wrong 4", "wrong 5"],
154
+ "evidence_spans": [{{"start_seconds": 0, "end_seconds": 0, "description": "..."}}],
155
+ "why_hard": "what a viewer must track across the stretch to answer"}}]}}"""
156
+
157
+ RECHECK_PROMPT = """Verify one benchmark question against the clip, which is exactly the stretch the
158
+ question is about.
159
+
160
+ QUESTION: {question}
161
+ OPTIONS: {options}
162
+ MARKED CORRECT: {answer}
163
+
164
+ Watch the clip. Decide whether the marked options -- all of them, and no others -- are the
165
+ correct answer.
166
+
167
+ - "supported" the marked options are right and the unmarked ones are wrong
168
+ - "contradicted" the clip shows something else; say what in notes
169
+ - "insufficient" the clip does not settle it
170
+
171
+ Judge only what the clip shows. If a detail is legible, it counts, whatever the encode.
172
+
173
+ Return only: {{"verdict": "...", "correct_answer_if_different": null, "notes": "..."}}"""
174
+
175
+
176
+ def wilson(k, n, z=1.96):
177
+ if not n:
178
+ return (0.0, 0.0)
179
+ p = k / n
180
+ d = 1 + z * z / n
181
+ c = p + z * z / (2 * n)
182
+ h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n))
183
+ return (100 * (c - h) / d, 100 * (c + h) / d)
184
+
185
+
186
+ def load(name, path):
187
+ spec = importlib.util.spec_from_file_location(name, path)
188
+ mod = importlib.util.module_from_spec(spec)
189
+ spec.loader.exec_module(mod)
190
+ return mod
191
+
192
+
193
+ def clock_frames(tmpdir, start, length):
194
+ """One PNG per second showing true recording time, for overlay onto the clip."""
195
+ from PIL import Image, ImageDraw, ImageFont
196
+ tmpdir.mkdir(parents=True, exist_ok=True)
197
+ try:
198
+ font = ImageFont.load_default(size=26)
199
+ except TypeError:
200
+ font = ImageFont.load_default()
201
+ for k in range(int(length) + 2):
202
+ t = int(start) + k
203
+ img = Image.new("RGB", (118, 36), (0, 0, 0))
204
+ ImageDraw.Draw(img).text((8, 4), f"{t // 60:02d}:{t % 60:02d}", fill=(255, 255, 255), font=font)
205
+ img.save(tmpdir / f"tc_{k:05d}.png")
206
+ return tmpdir / "tc_%05d.png"
207
+
208
+
209
+ def cut_with_clock(source, start, length, dst):
210
+ if dst.exists() and 4096 < dst.stat().st_size <= INLINE_CAP:
211
+ return "skip"
212
+ dst.parent.mkdir(parents=True, exist_ok=True)
213
+ tmp = dst.parent / f".tc_{dst.stem}"
214
+ try:
215
+ pattern = clock_frames(tmp, start, length)
216
+ budget = int(INLINE_CAP * 8 * 0.88 / max(length, 1) / 1000)
217
+ for h, kbps in ((480, budget), (432, int(budget * 0.97)), (360, int(budget * 0.95))):
218
+ r = subprocess.run(
219
+ [FFMPEG, "-y", "-ss", str(start), "-t", str(length), "-i", str(source),
220
+ "-framerate", "1", "-i", str(pattern),
221
+ "-filter_complex", f"[0:v]scale=-2:{h}[v];[v][1:v]overlay=6:6:shortest=1",
222
+ "-c:v", "libx264", "-preset", "veryfast", "-b:v", f"{kbps}k",
223
+ "-maxrate", f"{int(kbps * 1.15)}k", "-bufsize", f"{kbps * 2}k",
224
+ "-an", "-movflags", "+faststart", str(dst)],
225
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
226
+ if r.returncode == 0 and dst.exists() and dst.stat().st_size <= INLINE_CAP:
227
+ return "ok"
228
+ return "oversize"
229
+ finally:
230
+ shutil.rmtree(tmp, ignore_errors=True)
231
+
232
+
233
+ def video_part(path):
234
+ data = Path(path).read_bytes()
235
+ if len(data) > INLINE_CAP:
236
+ raise ValueError(f"clip is {len(data)/2**20:.1f} MiB, over the inline cap")
237
+ return {"inlineData": {"mimeType": "video/mp4", "data": base64.b64encode(data).decode("ascii")}}
238
+
239
+
240
+ def validate_annotation(d, p0, p1):
241
+ ph = d.get("route_phases")
242
+ if not isinstance(ph, list) or not ph:
243
+ raise ValueError("route_phases required")
244
+ prev = None
245
+ for p in ph:
246
+ a, b = float(p["start_sec"]), float(p["end_sec"])
247
+ if not (p0 - 2 <= a < b <= p1 + 2):
248
+ raise ValueError(f"phase {a}-{b} outside window {p0}-{p1}")
249
+ if prev is not None and abs(a - prev) > 2:
250
+ raise ValueError(f"phases must tile: gap at {prev} -> {a}")
251
+ prev = b
252
+ if not p.get("landmarks"):
253
+ raise ValueError("each phase needs landmarks")
254
+ for k in ("turns", "revisited_landmarks", "environment_stages",
255
+ "dynamic_events", "distinctive_objects"):
256
+ if not isinstance(d.get(k), list):
257
+ raise ValueError(f"{k} must be a list")
258
+
259
+
260
+ def make_q_validator(n, p0, p1):
261
+ def check(d):
262
+ qs = d.get("questions")
263
+ if not isinstance(qs, list) or len(qs) != n:
264
+ raise ValueError(f"need exactly {n} questions, got {len(qs) if isinstance(qs, list) else '?'}")
265
+ for q in qs:
266
+ stem = (q.get("question") or "").strip()
267
+ if not stem:
268
+ raise ValueError("empty question")
269
+ low = stem.lower()
270
+ for bad in LEAK:
271
+ if bad in low:
272
+ raise ValueError(f"question leaks {bad!r}: {stem[:60]}")
273
+ if q.get("question_type") not in TYPES:
274
+ raise ValueError(f"bad question_type {q.get('question_type')!r}")
275
+ opts = q.get("options")
276
+ if not isinstance(opts, list) or len(opts) != 8:
277
+ raise ValueError(f"need exactly 8 options, got {len(opts) if isinstance(opts, list) else '?'}")
278
+ seen = set()
279
+ for o in opts:
280
+ if not isinstance(o, str) or not o.strip():
281
+ raise ValueError("options must be non-empty strings")
282
+ if "\n" in o:
283
+ raise ValueError("one option per string; this one contains a newline")
284
+ key = o.strip().lower()
285
+ if key in seen:
286
+ raise ValueError(f"duplicate option: {o[:40]!r}")
287
+ seen.add(key)
288
+ for bad in OUT_OF_SCENE:
289
+ if bad in key:
290
+ raise ValueError(f"option names out-of-scene {bad!r}: {o[:50]}")
291
+ lengths = [len(o) for o in opts]
292
+ if sorted(range(8), key=lambda i: -lengths[i])[:3] == [0, 1, 2]:
293
+ raise ValueError("the three correct options are the three longest")
294
+ spans = q.get("evidence_spans")
295
+ if not isinstance(spans, list) or not spans:
296
+ raise ValueError("evidence_spans required")
297
+ for s in spans:
298
+ a, b = s.get("start_seconds"), s.get("end_seconds")
299
+ if not isinstance(a, (int, float)) or not isinstance(b, (int, float)) or b <= a:
300
+ raise ValueError(f"bad span {s}")
301
+ if b < p0 - 5 or a > p1 + 5:
302
+ raise ValueError(f"span {a}-{b} outside window {p0}-{p1}")
303
+ return check
304
+
305
+
306
+ def validate_verdict(d):
307
+ if d.get("verdict") not in ("supported", "contradicted", "insufficient"):
308
+ raise ValueError(f"bad verdict {d.get('verdict')!r}")
309
+
310
+
311
+ def shuffle(q):
312
+ texts = q["options"]
313
+ correct = set(range(3))
314
+ order = list(range(len(texts)))
315
+ random.Random(hashlib.sha256(q["question"].encode("utf-8")).hexdigest()).shuffle(order)
316
+ q["options"] = {chr(ord("A") + i): texts[s] for i, s in enumerate(order)}
317
+ q["answer"] = sorted(chr(ord("A") + i) for i, s in enumerate(order) if s in correct)
318
+ q["option_order"] = "shuffled"
319
+
320
+
321
+ def collect():
322
+ rows = []
323
+ for path in sorted(glob.glob(f"{SRC}/**/*.json", recursive=True)):
324
+ rec = json.load(open(path))
325
+ source = rec.get("original_video_path") or ""
326
+ if not source or not os.path.exists(source):
327
+ continue
328
+ stem = os.path.basename(source).rsplit(".", 1)[0]
329
+ idx = int(rec.get("chunk_index", 0))
330
+ p0 = float(rec["start_time_sec"])
331
+ p1 = float(rec["end_time_sec"])
332
+ rows.append({"video": stem, "chunk": idx, "source": source, "p0": p0, "p1": p1,
333
+ "clip": CLIPS / stem / f"{stem}_w{idx}.clock.mp4"})
334
+ return rows
335
+
336
+
337
+ def main():
338
+ ap = argparse.ArgumentParser()
339
+ ap.add_argument("--clips-only", action="store_true")
340
+ ap.add_argument("--pilot", type=int, default=0)
341
+ ap.add_argument("--all", action="store_true")
342
+ ap.add_argument("--n-per-window", type=int, default=4)
343
+ ap.add_argument("--jobs", type=int, default=2)
344
+ ap.add_argument("--out", default=str(OUT / "questions.json"))
345
+ a = ap.parse_args()
346
+
347
+ rows = collect()
348
+ print(f"{len(rows)} windows from {len({r['video'] for r in rows})} recordings", flush=True)
349
+
350
+ if a.clips_only:
351
+ tally = collections.Counter()
352
+ with concurrent.futures.ThreadPoolExecutor(max_workers=6) as pool:
353
+ futs = {pool.submit(cut_with_clock, r["source"], r["p0"], r["p1"] - r["p0"], r["clip"]): r
354
+ for r in rows}
355
+ for i, f in enumerate(concurrent.futures.as_completed(futs), 1):
356
+ tally[f.result()] += 1
357
+ if i % 20 == 0 or i == len(rows):
358
+ size = sum(p.stat().st_size for p in CLIPS.rglob("*.mp4")) / 2**30
359
+ print(f" {i}/{len(rows)} {dict(tally)} {size:.2f} GiB", flush=True)
360
+ print(f"done: {dict(tally)} -> {CLIPS}")
361
+ return 0
362
+
363
+ if not (a.pilot or a.all):
364
+ ap.error("pass --clips-only, --pilot N, or --all")
365
+
366
+ rows = [r for r in rows if r["clip"].exists()]
367
+ print(f"{len(rows)} windows have a clock clip", flush=True)
368
+ if a.pilot:
369
+ rng = random.Random(SEED)
370
+ by_video = collections.defaultdict(list)
371
+ for r in rows:
372
+ by_video[r["video"]].append(r)
373
+ picked = []
374
+ for v in sorted(by_video):
375
+ g = by_video[v]
376
+ rng.shuffle(g)
377
+ picked.append(g[0])
378
+ rng.shuffle(picked)
379
+ rows = picked[:a.pilot]
380
+ print(f"pilot: {len(rows)} windows", flush=True)
381
+
382
+ fv = load("fv", BASE / "build_fullvideo_annotations.py")
383
+ gen = load("gen", BASE / "repair_runningbench_annotations.py")
384
+ api = gen.Floodgate("")
385
+ api.session = fv.PacedSession(api.session, fv.RateLimiter(QUOTA_PER_SECOND))
386
+ OUT.mkdir(parents=True, exist_ok=True)
387
+
388
+ questions = []
389
+ done = set()
390
+ if os.path.exists(a.out):
391
+ try:
392
+ prev = json.load(open(a.out))
393
+ questions = prev.get("questions", [])
394
+ done = {(q["video"], q["chunk"]) for q in questions}
395
+ print(f"resuming: {len(questions)} questions over {len(done)} windows", flush=True)
396
+ except Exception:
397
+ pass
398
+ rows = [r for r in rows if (r["video"], r["chunk"]) not in done]
399
+ print(f"to do: {len(rows)}", flush=True)
400
+
401
+ lock = threading.Lock()
402
+ counter = {"n": 0}
403
+
404
+ def work(r):
405
+ length = r["p1"] - r["p0"]
406
+ try:
407
+ parts = [{"text": ANNOTATE_PROMPT.format(length=int(length), vid=r["video"],
408
+ p0=int(r["p0"]), p1=int(r["p1"]))},
409
+ video_part(r["clip"])]
410
+ ann = gen.clean_json(api.generate(gen.CAPTION_MODEL, parts, 16384, json_mode=True))
411
+ validate_annotation(ann, r["p0"], r["p1"])
412
+ except Exception as exc:
413
+ return [], None, f"annotate: {type(exc).__name__}: {exc}"
414
+
415
+ try:
416
+ data = gen.generate_valid_json(
417
+ api,
418
+ Q_PROMPT.format(n=a.n_per_window, length=int(length), vid=r["video"],
419
+ p0=int(r["p0"]), p1=int(r["p1"]),
420
+ annotation=json.dumps(ann, ensure_ascii=False),
421
+ types=", ".join(TYPES)),
422
+ make_q_validator(a.n_per_window, r["p0"], r["p1"]), 32768)
423
+ except Exception as exc:
424
+ return [], ann, f"questions: {type(exc).__name__}: {exc}"
425
+
426
+ out = []
427
+ for q in data["questions"]:
428
+ shuffle(q)
429
+ q.update({"video": r["video"], "chunk": r["chunk"],
430
+ "window_sec": [r["p0"], r["p1"]], "clip": str(r["clip"])})
431
+ gates = {"structure": "pass", "leak_scan": "pass"}
432
+ arity = "Exactly three options are correct."
433
+ hits, guesses = 0, []
434
+ for t in range(3):
435
+ try:
436
+ bg = gen.generate_valid_json(
437
+ api, fv.BLIND_PROMPT.format(question=q["question"],
438
+ options=json.dumps(q["options"], ensure_ascii=False),
439
+ arity=f"{arity} (attempt {t+1})"),
440
+ fv.validate_blind, 4096)
441
+ g = sorted(bg["answer"])
442
+ except Exception:
443
+ g = ["?"]
444
+ guesses.append(g)
445
+ hits += g == sorted(q["answer"])
446
+ gates["blind_guess"] = {"guesses": guesses, "hits_of_3": hits, "matches_gold": hits >= 2}
447
+ if gates["blind_guess"]["matches_gold"]:
448
+ gates["visual_recheck"] = {"verdict": "skipped", "notes": "blind-guessable"}
449
+ else:
450
+ try:
451
+ parts = [{"text": RECHECK_PROMPT.format(
452
+ question=q["question"],
453
+ options=json.dumps(q["options"], ensure_ascii=False),
454
+ answer=json.dumps(q["answer"]))},
455
+ video_part(r["clip"])]
456
+ gates["visual_recheck"] = gen.clean_json(
457
+ api.generate(gen.CAPTION_MODEL, parts, 8192, json_mode=True))
458
+ validate_verdict(gates["visual_recheck"])
459
+ except Exception as exc:
460
+ gates["visual_recheck"] = {"verdict": "error", "notes": type(exc).__name__}
461
+ q["gates"] = gates
462
+ out.append(q)
463
+ return out, ann, None
464
+
465
+ anns = {}
466
+ with concurrent.futures.ThreadPoolExecutor(max_workers=a.jobs) as pool:
467
+ for got, ann, err in pool.map(work, rows):
468
+ with lock:
469
+ counter["n"] += 1
470
+ i = counter["n"]
471
+ if err:
472
+ print(f" !! window {i}: {err}", flush=True)
473
+ if ann:
474
+ anns[i] = ann
475
+ questions += got
476
+ usable = sum(1 for q in questions
477
+ if q["gates"].get("visual_recheck", {}).get("verdict") == "supported"
478
+ and not q["gates"]["blind_guess"].get("matches_gold"))
479
+ blind = sum(1 for q in questions if q["gates"]["blind_guess"].get("matches_gold"))
480
+ print(f" {i}/{len(rows)} · {len(questions)} q · {usable} usable · {blind} blind",
481
+ flush=True)
482
+ json.dump({"n": len(questions), "questions": questions},
483
+ open(a.out, "w"), ensure_ascii=False, indent=1)
484
+
485
+ total = len(questions)
486
+ if not total:
487
+ print("no questions produced")
488
+ return 1
489
+ usable = [q for q in questions
490
+ if q["gates"].get("visual_recheck", {}).get("verdict") == "supported"
491
+ and not q["gates"]["blind_guess"].get("matches_gold")]
492
+ blind = sum(1 for q in questions if q["gates"]["blind_guess"].get("matches_gold"))
493
+ lo, hi = wilson(len(usable), total)
494
+ bl, bh = wilson(blind, total)
495
+ print(f"\n=== {total} questions -> {a.out}")
496
+ print(f"usable {len(usable)}/{total} = {100*len(usable)/total:.1f}% 95% CI [{lo:.1f}, {hi:.1f}]")
497
+ print(f"blind-guessed {blind}/{total} = {100*blind/total:.1f}% 95% CI [{bl:.1f}, {bh:.1f}]")
498
+ print(f" aggregated-annotation attempt: 68.4% blind [57.3, 77.8]")
499
+ print(f" segment corpus 48.6% · full-video 8-option multi 7.3%")
500
+ v = collections.Counter()
501
+ for q in questions:
502
+ rc = q["gates"].get("visual_recheck", {})
503
+ v[rc.get("verdict") if isinstance(rc, dict) else rc] += 1
504
+ print(f"recheck {dict(v)}")
505
+ by_t = collections.defaultdict(collections.Counter)
506
+ for q in questions:
507
+ by_t[q["question_type"]]["ok" if q in usable else "no"] += 1
508
+ for t, c in sorted(by_t.items()):
509
+ n = c["ok"] + c["no"]
510
+ print(f" {t:26s} {c['ok']:3d}/{n:3d} {100*c['ok']/n:3.0f}% (aggregated: "
511
+ f"{'0%' if t == 'window-turn-sequence' else '11-63%'})")
512
+ if total < 100:
513
+ print(f"\nNOTE: n={total}. Read the intervals, not the point estimates.")
514
+ return 0
515
+
516
+
517
+ if __name__ == "__main__":
518
+ sys.exit(main())
multi_video_cross_video_methodology/source_docs/blind_test_segments.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Measure how guessable the 60-second segment questions actually are.
3
+
4
+ The segment corpus has never faced a blind model. Its published "17.6% blind
5
+ baseline" is only the answer-letter distribution -- it shows the shuffle removed
6
+ positional bias, not that the questions need the video. The full-video corpus,
7
+ which does run this test, found 6-option single-choice questions hit 41% blind:
8
+ 2.5x the 16.7% random baseline, and the leak is semantic, not positional.
9
+
10
+ So this runs the identical procedure the full-video gates use -- same prompt,
11
+ same three-vote rule, guessable at >=2/3 -- over a stratified sample, and reports
12
+ a Wilson interval.
13
+
14
+ Usage: blind_test_segments.py [--n 800] [--out report.json]
15
+ """
16
+ import argparse
17
+ import collections
18
+ import glob
19
+ import importlib.util
20
+ import json
21
+ import math
22
+ import random
23
+ import sys
24
+ from pathlib import Path
25
+
26
+ SEG_ROOT = "/mnt/data/data_anno/runningbench_qa_expansion/annotations_60s"
27
+ BASE = Path("/mnt/task_runtime/bolt/gdrive_relay")
28
+ QUOTA_PER_SECOND = 0.45
29
+ SEED = 20260830
30
+
31
+
32
+ def load(name, path):
33
+ spec = importlib.util.spec_from_file_location(name, path)
34
+ mod = importlib.util.module_from_spec(spec)
35
+ spec.loader.exec_module(mod)
36
+ return mod
37
+
38
+
39
+ def wilson(k, n, z=1.96):
40
+ if not n:
41
+ return (0.0, 0.0)
42
+ p = k / n
43
+ d = 1 + z * z / n
44
+ c = p + z * z / (2 * n)
45
+ h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n))
46
+ return ((c - h) / d, (c + h) / d)
47
+
48
+
49
+ def main():
50
+ ap = argparse.ArgumentParser()
51
+ ap.add_argument("--n", type=int, default=800)
52
+ ap.add_argument("--out", default="/mnt/data/data_anno/runningbench_qa_expansion/blind_test.json")
53
+ a = ap.parse_args()
54
+
55
+ fv = load("fv", BASE / "build_fullvideo_annotations.py")
56
+ gen = fv.load_generator()
57
+
58
+ pool = []
59
+ for path in sorted(glob.glob(f"{SEG_ROOT}/**/*.json", recursive=True)):
60
+ try:
61
+ record = json.load(open(path))
62
+ except Exception:
63
+ continue
64
+ for item in record.get("qa_pairs") or []:
65
+ opts, ans = item.get("options"), item.get("answer")
66
+ if not isinstance(opts, dict) or not opts or not isinstance(ans, list) or not ans:
67
+ continue
68
+ pool.append({"question": item["question"], "options": opts, "answer": sorted(ans),
69
+ "type": item.get("type"), "n_opt": len(opts), "n_ans": len(ans),
70
+ "file": path})
71
+ print(f"pool: {len(pool)} objective questions", flush=True)
72
+
73
+ # Stratify by (option count, single/multi) so the sample mirrors the corpus.
74
+ strata = collections.defaultdict(list)
75
+ for q in pool:
76
+ strata[(q["n_opt"], q["n_ans"] > 1)].append(q)
77
+ rng = random.Random(SEED)
78
+ sample = []
79
+ for key, group in sorted(strata.items()):
80
+ take = max(1, round(a.n * len(group) / len(pool)))
81
+ rng.shuffle(group)
82
+ sample += group[:take]
83
+ rng.shuffle(sample)
84
+ print(f"sample: {len(sample)} over {len(strata)} strata", flush=True)
85
+
86
+ api = gen.Floodgate("")
87
+ api.session = fv.PacedSession(api.session, fv.RateLimiter(QUOTA_PER_SECOND))
88
+
89
+ results = []
90
+ for i, q in enumerate(sample, 1):
91
+ arity = ("Exactly one option is correct." if q["n_ans"] == 1
92
+ else "More than one option is correct.")
93
+ guesses, hits = [], 0
94
+ for attempt in range(3):
95
+ try:
96
+ raw = gen.generate_valid_json(
97
+ api,
98
+ fv.BLIND_PROMPT.format(question=q["question"],
99
+ options=json.dumps(q["options"], ensure_ascii=False),
100
+ arity=f"{arity} (attempt {attempt + 1})"),
101
+ fv.validate_blind, 4096)
102
+ g = sorted(raw["answer"])
103
+ except Exception as exc:
104
+ g = [f"ERROR:{type(exc).__name__}"]
105
+ guesses.append(g)
106
+ hits += g == q["answer"]
107
+ results.append({**{k: q[k] for k in ("question", "type", "n_opt", "n_ans", "answer")},
108
+ "guesses": guesses, "hits_of_3": hits, "guessable": hits >= 2})
109
+ if i % 25 == 0 or i == len(sample):
110
+ g = sum(1 for r in results if r["guessable"])
111
+ print(f" {i}/{len(sample)} guessable {g} ({100 * g / i:.1f}%)", flush=True)
112
+ json.dump({"n": len(results), "results": results}, open(a.out, "w"), ensure_ascii=False)
113
+
114
+ # ---- report -----------------------------------------------------------
115
+ def rate(rows):
116
+ if not rows:
117
+ return None
118
+ k = sum(1 for r in rows if r["guessable"])
119
+ lo, hi = wilson(k, len(rows))
120
+ return k, len(rows), 100 * k / len(rows), 100 * lo, 100 * hi
121
+
122
+ print("\n=== blind-guess rate (>=2 of 3 votes match) ===")
123
+ k, n, p, lo, hi = rate(results)
124
+ print(f"overall {k}/{n} = {p:.1f}% 95% CI [{lo:.1f}, {hi:.1f}]")
125
+ for key, label in (((6, False), "6-option single"), ((8, True), "8-option multi")):
126
+ rows = [r for r in results if (r["n_opt"], r["n_ans"] > 1) == key]
127
+ if rows:
128
+ k, n, p, lo, hi = rate(rows)
129
+ rand = 100 / math.comb(key[0], rows[0]["n_ans"]) if key[1] else 100 / key[0]
130
+ print(f"{label:18s}{k}/{n} = {p:.1f}% 95% CI [{lo:.1f}, {hi:.1f}] random ~{rand:.1f}%")
131
+ print("\nby question type:")
132
+ for t in sorted({r["type"] for r in results}):
133
+ rows = [r for r in results if r["type"] == t]
134
+ k, n, p, lo, hi = rate(rows)
135
+ print(f" {str(t):30s} {k:3d}/{n:3d} = {p:5.1f}% [{lo:.1f}, {hi:.1f}]")
136
+ print(f"\nwrote {a.out}")
137
+
138
+
139
+ if __name__ == "__main__":
140
+ sys.exit(main())
multi_video_cross_video_methodology/source_docs/build_window_questions.py ADDED
@@ -0,0 +1,427 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Benchmark questions from the 180-second window annotations.
3
+
4
+ Why this layer. The 60s segments hold one phase and no turn, so the only questions they
5
+ support are "what is in the frame" -- a blind model beats 48.6% of them. Whole videos
6
+ support route questions but run 10-33 minutes. The 180s windows sit where structure
7
+ starts: the excerpt study measured yield rising from 42% at 1 minute to 60% at 4, and
8
+ three minutes is inside that band. Each window already carries a description of its own
9
+ trajectory, turns and environment shifts, so the expensive viewing pass is already paid
10
+ for; only the questions and the gates cost quota.
11
+
12
+ What this layer is NOT. These annotations are aggregations of three 60s captions --
13
+ their `derived_from` field names them -- not independent viewings. Every question written
14
+ from them inherits whatever the 60s pass got wrong, which is exactly what the 480p
15
+ re-check gate exists to catch. Treat an ungated question from here as unverified.
16
+
17
+ Format. Eight options, three correct. Measured, not assumed: on the segment corpus a
18
+ blind model scores 64.7% against single-answer questions and 25.3% against multi-answer
19
+ ones, and on the full-video corpus 8-option multi runs 7.3%. Single-answer questions
20
+ leak two ways at once -- picking the longest option alone wins 42.2% of them -- and
21
+ repairing one leak leaves the other, so the format is chosen up front rather than fixed
22
+ later.
23
+
24
+ Gates, in this order:
25
+
26
+ 1. shuffle deterministic, seeded on the question text
27
+ 2. structure arity, distinct options, no empty text
28
+ 3. leak scan filename/speed/"per the description" blacklist
29
+ 4. blind guess x3 answer with no video; >=2 hits of 3 drops the question
30
+ 5. visual recheck 480p clip of that exact window; only "supported" survives
31
+
32
+ Order is not arbitrary. Shuffling must precede the blind test: generators favour putting
33
+ the answer first and blind models favour picking first, and testing before the shuffle
34
+ once produced a 56.6% guess rate that was an artifact of position, not leakage. The blind
35
+ test must precede the re-check because a question that fails it needs no video call --
36
+ the most expensive step in the pipeline.
37
+
38
+ Usage:
39
+ build_window_questions.py --pilot 20 # 20 windows, full gates, reports CIs
40
+ build_window_questions.py --all --jobs 2
41
+ """
42
+ import argparse
43
+ import base64
44
+ import collections
45
+ import concurrent.futures
46
+ import glob
47
+ import hashlib
48
+ import importlib.util
49
+ import json
50
+ import math
51
+ import os
52
+ import random
53
+ import re
54
+ import sys
55
+ import threading
56
+ from pathlib import Path
57
+
58
+ BASE = Path("/mnt/task_runtime/bolt/gdrive_relay")
59
+ SRC = "/mnt/data/data_anno/runningbench_gap_repair/annotations_180s"
60
+ CLIPS = Path("/mnt/data/data_anno/runningbench_windows/clips_480p")
61
+ OUT = Path("/mnt/data/data_anno/runningbench_windows")
62
+ QUOTA_PER_SECOND = 0.45
63
+ SEED = 20260831
64
+
65
+ TYPES = ("window-event-order", "window-turn-sequence",
66
+ "window-environment-shift", "window-object-timing")
67
+
68
+ # Words that would let a reader answer from the question text or from artifacts of how
69
+ # the corpus was built, rather than from the video.
70
+ # Kept deliberately narrow. These are corpus artifacts -- filename fragments, and phrases
71
+ # that point at the written annotation instead of the footage. Words that merely describe
72
+ # what is on screen do not belong here: an earlier version blacklisted "segment", which
73
+ # rejected the entirely fair phrasing "the video segment from 06:00 to 09:00" and burned a
74
+ # retry on every occurrence. A leak filter that fights natural English costs quota and
75
+ # teaches the generator nothing.
76
+ LEAK = ("trial", "traj", ".mov", ".mp4", "filename", "annotation",
77
+ "described", "the description", "the evidence", "per the", "according to the")
78
+
79
+ # Scenery this corpus does not contain. A distractor naming one of these is not a
80
+ # distractor -- anyone who knows the setting drops it without watching. This list is the
81
+ # defence the segment corpus never had, and its absence is why options there offered
82
+ # engine noise and dashboard views for a question about someone running.
83
+ OUT_OF_SCENE = ("beach", "highway", "motorway", "forest", "woods", "indoor", "shopping mall",
84
+ "airport terminal", "subway", "train station", "stadium", "boardwalk",
85
+ "desert", "mountain trail", "swimming", "driving", "dashboard", "cockpit")
86
+
87
+ Q_PROMPT = """Write exactly {n} benchmark questions about ONE 180-second stretch of a first-person
88
+ walking/running video, anonymous id {vid}. The stretch runs from {t0} to {t1} of that recording.
89
+
90
+ EVIDENCE — everything known about this stretch:
91
+ {evidence}
92
+
93
+ Each question must need the WHOLE three minutes. A question answerable from any single
94
+ frame, or from any one minute of it, does not belong here: ask about order, about change
95
+ across the stretch, about what happened before or after what.
96
+
97
+ Use these types, spread evenly: {types}
98
+ window-event-order the sequence in which events occur across the stretch
99
+ window-turn-sequence the trajectory: which turns, in which order, how sharp
100
+ window-environment-shift how the surroundings change from the start to the end
101
+ window-object-timing which objects appear in which part of the stretch
102
+
103
+ FORMAT — exactly 8 options, of which exactly 3 are correct. Return the three correct ones
104
+ first; they get shuffled afterwards.
105
+
106
+ THE FIVE WRONG OPTIONS ARE THE HARD PART. Read all of this.
107
+
108
+ A wrong option must be wrong ONLY because the video says otherwise — never because a
109
+ reader can rule it out from the setting. Someone who knows this is a person on foot
110
+ outdoors, and nothing else, must find all eight equally possible. So:
111
+
112
+ - Build them from THIS stretch's own vocabulary: its objects, its paths, its turns. A
113
+ wrong option that names something absent from the evidence — a beach, a dashboard, an
114
+ indoor hall — is worthless.
115
+ - Make them wrong by COMPOSITION, not by content: the right things in the wrong order,
116
+ an event placed in the wrong third, two objects swapped, a turn given the wrong
117
+ direction or the wrong sharpness.
118
+ - Do NOT write each wrong option as a correct one with a single detail edited. If every
119
+ wrong option is one edit from a right one, then on each detail the correct value is
120
+ the majority value, and the whole answer can be recovered by taking the most common
121
+ colour, the most common count, the most common side — no video needed. This is the
122
+ single most common way a question set leaks; a set built that way once drove blind
123
+ guessing from 48.6% to 75%.
124
+ - Vary which details differ and how many: change two or three at once, in different
125
+ combinations, so no option sits at the centre of the set.
126
+ - Keep all eight the same length and the same specificity. The correct options must not
127
+ be the longest or the most detailed — picking the longest option alone wins 42.2% of
128
+ single-answer questions in an earlier corpus, and the same habit leaks here.
129
+
130
+ Every question must also carry evidence_spans: the seconds within the FULL recording
131
+ (not within this stretch) that show the answer, so the claim can be re-checked.
132
+
133
+ Return only:
134
+ {{"questions": [{{"question": "...", "question_type": "...",
135
+ "options": ["correct 1", "correct 2", "correct 3", "wrong 1", "wrong 2", "wrong 3", "wrong 4", "wrong 5"],
136
+ "evidence_spans": [{{"start_seconds": 0, "end_seconds": 0, "description": "..."}}],
137
+ "why_hard": "what a viewer must track across the three minutes to answer"}}]}}"""
138
+
139
+ RECHECK_PROMPT = """Verify one benchmark question against the clip, which is exactly the stretch the
140
+ question is about.
141
+
142
+ QUESTION: {question}
143
+ OPTIONS: {options}
144
+ MARKED CORRECT: {answer}
145
+
146
+ Watch the clip. Decide whether the marked options — all of them, and no others — are the
147
+ correct answer.
148
+
149
+ - "supported" the marked options are right and the unmarked ones are wrong
150
+ - "contradicted" the clip shows something else; say what in notes
151
+ - "insufficient" the clip does not settle it
152
+
153
+ Judge only what the clip shows. If a detail is legible, it counts, whatever the encode.
154
+
155
+ Return only: {{"verdict": "...", "correct_answer_if_different": null, "notes": "..."}}"""
156
+
157
+
158
+ def wilson(k, n, z=1.96):
159
+ if not n:
160
+ return (0.0, 0.0)
161
+ p = k / n
162
+ d = 1 + z * z / n
163
+ c = p + z * z / (2 * n)
164
+ h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n))
165
+ return (100 * (c - h) / d, 100 * (c + h) / d)
166
+
167
+
168
+ INLINE_CAP = 11 * 1024 * 1024
169
+
170
+
171
+ def video_part(path):
172
+ """Inline one clip. The API rejects a request whose inline payload exceeds 11 MiB."""
173
+ data = Path(path).read_bytes()
174
+ if len(data) > INLINE_CAP:
175
+ raise ValueError(f"clip is {len(data)/2**20:.1f} MiB, over the {INLINE_CAP/2**20:.0f} MiB inline cap")
176
+ return {"inlineData": {"mimeType": "video/mp4", "data": base64.b64encode(data).decode("ascii")}}
177
+
178
+
179
+ def load(name, path):
180
+ spec = importlib.util.spec_from_file_location(name, path)
181
+ mod = importlib.util.module_from_spec(spec)
182
+ spec.loader.exec_module(mod)
183
+ return mod
184
+
185
+
186
+ def mmss(sec):
187
+ return f"{int(sec) // 60:02d}:{int(sec) % 60:02d}"
188
+
189
+
190
+ def scene_vocabulary(evidence):
191
+ return set(re.findall(r"[a-z]{4,}", json.dumps(evidence, ensure_ascii=False).lower()))
192
+
193
+
194
+ def make_validator(n, t0, t1, vocab):
195
+ def check(d):
196
+ qs = d.get("questions")
197
+ if not isinstance(qs, list) or len(qs) != n:
198
+ raise ValueError(f"need exactly {n} questions, got {len(qs) if isinstance(qs, list) else '?'}")
199
+ for q in qs:
200
+ stem = (q.get("question") or "").strip()
201
+ if not stem:
202
+ raise ValueError("empty question")
203
+ low = stem.lower()
204
+ for bad in LEAK:
205
+ if bad in low:
206
+ raise ValueError(f"question leaks {bad!r}: {stem[:60]}")
207
+ if q.get("question_type") not in TYPES:
208
+ raise ValueError(f"bad question_type {q.get('question_type')!r}")
209
+ opts = q.get("options")
210
+ if not isinstance(opts, list) or len(opts) != 8:
211
+ raise ValueError(f"need exactly 8 options, got {len(opts) if isinstance(opts, list) else '?'}")
212
+ seen = set()
213
+ for o in opts:
214
+ if not isinstance(o, str) or not o.strip():
215
+ raise ValueError("options must be non-empty strings")
216
+ if "\n" in o:
217
+ raise ValueError("one option per string; this one contains a newline")
218
+ key = o.strip().lower()
219
+ if key in seen:
220
+ raise ValueError(f"duplicate option: {o[:40]!r}")
221
+ seen.add(key)
222
+ for bad in OUT_OF_SCENE:
223
+ if bad in key:
224
+ raise ValueError(f"option names out-of-scene {bad!r}: {o[:50]}")
225
+ # The correct three are returned first; they must not be the longest three.
226
+ lengths = [len(o) for o in opts]
227
+ if sorted(range(8), key=lambda i: -lengths[i])[:3] == [0, 1, 2]:
228
+ raise ValueError("the three correct options are the three longest")
229
+ spans = q.get("evidence_spans")
230
+ if not isinstance(spans, list) or not spans:
231
+ raise ValueError("evidence_spans required")
232
+ for s in spans:
233
+ a, b = s.get("start_seconds"), s.get("end_seconds")
234
+ if not isinstance(a, (int, float)) or not isinstance(b, (int, float)) or b <= a:
235
+ raise ValueError(f"bad span {s}")
236
+ if b < t0 - 5 or a > t1 + 5:
237
+ raise ValueError(f"span {a}-{b} outside window {t0}-{t1}")
238
+ return check
239
+
240
+
241
+ def validate_verdict(d):
242
+ if d.get("verdict") not in ("supported", "contradicted", "insufficient"):
243
+ raise ValueError(f"bad verdict {d.get('verdict')!r}")
244
+
245
+
246
+ def shuffle(q):
247
+ texts = q["options"]
248
+ correct = set(range(3)) # generator returns the correct three first
249
+ order = list(range(len(texts)))
250
+ random.Random(hashlib.sha256(q["question"].encode("utf-8")).hexdigest()).shuffle(order)
251
+ q["options"] = {chr(ord("A") + i): texts[src] for i, src in enumerate(order)}
252
+ q["answer"] = sorted(chr(ord("A") + i) for i, src in enumerate(order) if src in correct)
253
+ q["option_order"] = "shuffled"
254
+
255
+
256
+ def collect():
257
+ rows = []
258
+ for path in sorted(glob.glob(f"{SRC}/**/*.json", recursive=True)):
259
+ rec = json.load(open(path))
260
+ source = rec.get("original_video_path") or ""
261
+ stem = os.path.basename(source).rsplit(".", 1)[0]
262
+ idx = int(rec.get("chunk_index", 0))
263
+ clip = CLIPS / stem / f"{stem}_w{idx}.480p.mp4"
264
+ rows.append({"file": path, "video": stem, "chunk": idx,
265
+ "t0": float(rec["start_time_sec"]), "t1": float(rec["end_time_sec"]),
266
+ "evidence": rec.get("dense_annotations"),
267
+ "open_qa": rec.get("qa_pairs") or [],
268
+ "clip": str(clip) if clip.exists() else None})
269
+ return rows
270
+
271
+
272
+ def main():
273
+ ap = argparse.ArgumentParser()
274
+ ap.add_argument("--pilot", type=int, default=0, help="how many windows to run")
275
+ ap.add_argument("--all", action="store_true")
276
+ ap.add_argument("--n-per-window", type=int, default=4)
277
+ # The distractor repair is usually holding most of the 0.45 req/s quota; two workers
278
+ # here share it rather than starving both runs into 429 backoff.
279
+ ap.add_argument("--jobs", type=int, default=2)
280
+ ap.add_argument("--out", default=str(OUT / "questions.json"))
281
+ a = ap.parse_args()
282
+ if not (a.pilot or a.all):
283
+ ap.error("pass --pilot N or --all")
284
+
285
+ fv = load("fv", BASE / "build_fullvideo_annotations.py")
286
+ gen = load("gen", BASE / "repair_runningbench_annotations.py")
287
+
288
+ rows = collect()
289
+ print(f"{len(rows)} windows; {sum(1 for r in rows if r['clip'])} have a 480p clip", flush=True)
290
+ if a.pilot:
291
+ rng = random.Random(SEED)
292
+ by_video = collections.defaultdict(list)
293
+ for r in rows:
294
+ by_video[r["video"]].append(r)
295
+ picked = []
296
+ for vid in sorted(by_video):
297
+ group = by_video[vid]
298
+ rng.shuffle(group)
299
+ picked += group[:max(1, round(a.pilot / len(by_video)))]
300
+ rng.shuffle(picked)
301
+ rows = picked[:a.pilot]
302
+ print(f"pilot: {len(rows)} windows from {len({r['video'] for r in rows})} videos", flush=True)
303
+
304
+ api = gen.Floodgate("")
305
+ api.session = fv.PacedSession(api.session, fv.RateLimiter(QUOTA_PER_SECOND))
306
+ OUT.mkdir(parents=True, exist_ok=True)
307
+
308
+ done = {}
309
+ if os.path.exists(a.out):
310
+ try:
311
+ prev = json.load(open(a.out))
312
+ done = {(q["video"], q["chunk"]) for q in prev.get("questions", [])}
313
+ questions = prev.get("questions", [])
314
+ print(f"resuming: {len(questions)} questions over {len(done)} windows", flush=True)
315
+ except Exception:
316
+ questions = []
317
+ else:
318
+ questions = []
319
+ rows = [r for r in rows if (r["video"], r["chunk"]) not in done]
320
+ print(f"to do: {len(rows)} windows", flush=True)
321
+
322
+ lock = threading.Lock()
323
+ counter = {"n": 0}
324
+
325
+ def work(r):
326
+ vocab = scene_vocabulary(r["evidence"])
327
+ try:
328
+ data = gen.generate_valid_json(
329
+ api,
330
+ Q_PROMPT.format(n=a.n_per_window, vid=r["video"], t0=mmss(r["t0"]), t1=mmss(r["t1"]),
331
+ evidence=json.dumps(r["evidence"], ensure_ascii=False),
332
+ types=", ".join(TYPES)),
333
+ make_validator(a.n_per_window, r["t0"], r["t1"], vocab), 32768)
334
+ except Exception as exc:
335
+ return [], f"{type(exc).__name__}: {exc}"
336
+
337
+ out = []
338
+ for q in data["questions"]:
339
+ shuffle(q)
340
+ q.update({"video": r["video"], "chunk": r["chunk"], "window_sec": [r["t0"], r["t1"]],
341
+ "clip": r["clip"]})
342
+ gates = {"structure": "pass", "leak_scan": "pass"}
343
+
344
+ arity = "Exactly three options are correct."
345
+ hits, guesses = 0, []
346
+ for t in range(3):
347
+ try:
348
+ bg = gen.generate_valid_json(
349
+ api, fv.BLIND_PROMPT.format(question=q["question"],
350
+ options=json.dumps(q["options"], ensure_ascii=False),
351
+ arity=f"{arity} (attempt {t + 1})"),
352
+ fv.validate_blind, 4096)
353
+ g = sorted(bg["answer"])
354
+ except Exception:
355
+ g = ["?"]
356
+ guesses.append(g)
357
+ hits += g == sorted(q["answer"])
358
+ gates["blind_guess"] = {"guesses": guesses, "hits_of_3": hits, "matches_gold": hits >= 2}
359
+
360
+ if gates["blind_guess"]["matches_gold"]:
361
+ # Guessable without video; the re-check is the most expensive call in the
362
+ # pipeline and would only confirm a question already lost.
363
+ gates["visual_recheck"] = {"verdict": "skipped", "notes": "blind-guessable"}
364
+ elif not r["clip"]:
365
+ gates["visual_recheck"] = {"verdict": "skipped", "notes": "no clip on disk"}
366
+ else:
367
+ try:
368
+ parts = [{"text": RECHECK_PROMPT.format(
369
+ question=q["question"],
370
+ options=json.dumps(q["options"], ensure_ascii=False),
371
+ answer=json.dumps(q["answer"]))},
372
+ video_part(r["clip"])]
373
+ gates["visual_recheck"] = gen.clean_json(
374
+ api.generate(gen.CAPTION_MODEL, parts, 8192, json_mode=True))
375
+ validate_verdict(gates["visual_recheck"])
376
+ except Exception as exc:
377
+ gates["visual_recheck"] = {"verdict": "error", "notes": type(exc).__name__}
378
+ q["gates"] = gates
379
+ out.append(q)
380
+ return out, None
381
+
382
+ with concurrent.futures.ThreadPoolExecutor(max_workers=a.jobs) as pool:
383
+ for got, err in pool.map(work, rows):
384
+ with lock:
385
+ counter["n"] += 1
386
+ i = counter["n"]
387
+ if err:
388
+ print(f" !! window {i}: {err}", flush=True)
389
+ questions += got
390
+ usable = sum(1 for q in questions
391
+ if q["gates"].get("visual_recheck", {}).get("verdict") == "supported"
392
+ and not q["gates"]["blind_guess"].get("matches_gold"))
393
+ print(f" {i}/{len(rows)} windows · {len(questions)} questions · {usable} usable", flush=True)
394
+ json.dump({"n": len(questions), "questions": questions},
395
+ open(a.out, "w"), ensure_ascii=False, indent=1)
396
+
397
+ total = len(questions)
398
+ usable = [q for q in questions
399
+ if q["gates"].get("visual_recheck", {}).get("verdict") == "supported"
400
+ and not q["gates"]["blind_guess"].get("matches_gold")]
401
+ blind = sum(1 for q in questions if q["gates"]["blind_guess"].get("matches_gold"))
402
+ print(f"\n=== {total} questions from {len(rows)} windows -> {a.out}")
403
+ if total:
404
+ lo, hi = wilson(len(usable), total)
405
+ bl, bh = wilson(blind, total)
406
+ print(f"usable {len(usable)}/{total} = {100*len(usable)/total:.1f}% 95% CI [{lo:.1f}, {hi:.1f}]")
407
+ print(f"blind-guessed {blind}/{total} = {100*blind/total:.1f}% 95% CI [{bl:.1f}, {bh:.1f}]")
408
+ print(f" (segment corpus 48.6%, full-video 8-option multi 7.3%)")
409
+ by_v = collections.Counter()
410
+ for q in questions:
411
+ v = q["gates"].get("visual_recheck", {})
412
+ by_v[v.get("verdict") if isinstance(v, dict) else v] += 1
413
+ print(f"recheck {dict(by_v)}")
414
+ by_t = collections.defaultdict(collections.Counter)
415
+ for q in questions:
416
+ ok = q in usable
417
+ by_t[q["question_type"]]["ok" if ok else "no"] += 1
418
+ for t, c in sorted(by_t.items()):
419
+ n = c["ok"] + c["no"]
420
+ print(f" {t:26s} {c['ok']:3d}/{n:3d} {100*c['ok']/n:3.0f}%")
421
+ if total < 100:
422
+ print(f"\nNOTE: n={total} is small. Distinguishing a ~7-point difference in guess rate "
423
+ f"needs about 800 per group; read these intervals, not the point estimates.")
424
+
425
+
426
+ if __name__ == "__main__":
427
+ sys.exit(main())
multi_video_cross_video_methodology/source_docs/expand_mcq.py ADDED
@@ -0,0 +1,435 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Expand the RunningBench MCQ pool: more distractors per question, more questions per segment.
3
+
4
+ Both modes are text-only — they read the existing `dense_annotations`; no video is
5
+ decoded or uploaded. Output goes to a separate work directory and the source
6
+ annotations are never modified.
7
+
8
+ The Floodgate quota measured on this project is a hard 0.5 requests/second
9
+ (30/min) regardless of concurrency, so the design minimises CALL COUNT rather
10
+ than adding workers: every stage batches all of a segment's questions into one
11
+ request, and a shared token bucket paces sending just under the quota so time is
12
+ not wasted in 429 backoff.
13
+
14
+ --expand-options pad every choice question up to the target option count,
15
+ keeping only distractors a second pass judges to be
16
+ contradicted by the evidence.
17
+ --more-questions generate additional questions per segment, deliberately
18
+ different in focus from the ones already present.
19
+
20
+ Usage:
21
+ python3 expand_mcq.py --expand-options --more-questions --dry-run
22
+ python3 expand_mcq.py --expand-options --more-questions --pilot P01_SlowWalk_Day_Traj01
23
+ python3 expand_mcq.py --expand-options --more-questions
24
+ """
25
+ import argparse, hashlib, importlib.util, json, os, random, sys, threading, time
26
+ from collections import Counter
27
+ from concurrent.futures import ThreadPoolExecutor, as_completed
28
+ from pathlib import Path
29
+
30
+ HERE = Path(__file__).resolve().parent
31
+ SEG_DIRS = [
32
+ Path("/mnt/data/data_anno/conductor_release/annotations_60s"),
33
+ Path("/mnt/data/data_anno/runningbench_gap_repair/annotations_60s"),
34
+ ]
35
+ DEFAULT_WORK = Path("/mnt/data/data_anno/runningbench_qa_expansion")
36
+
37
+ TARGET_SINGLE = 6 # A-F, random baseline 16.7%
38
+ TARGET_MULTI = 8 # A-H
39
+ NEW_QUESTIONS_PER_SEGMENT = 3 # on top of the 3 already there
40
+ QUOTA_PER_SECOND = 0.48 # measured ceiling is 0.50; stay just under it
41
+
42
+ LEAK_PHRASES = (
43
+ "explicitly described", "as described", "described in the video", "described throughout",
44
+ "according to the description", "the description", "mentioned in", "stated in",
45
+ "the evidence", "the annotation", "based on the text", "the provided",
46
+ )
47
+
48
+ DISTRACTOR_PROMPT = """You are extending video-understanding benchmark questions with extra wrong options.
49
+
50
+ EVIDENCE (the only ground truth; one segment of a first-person walking/running video):
51
+ {evidence}
52
+
53
+ For each question below, write exactly the requested number of NEW options. Every new option must be:
54
+ - plausible for this kind of video, similar in length and style to the existing options;
55
+ - DEFINITIVELY CONTRADICTED by the evidence above — never merely unmentioned, never partly true;
56
+ - clearly distinct from every existing option and from your other new options.
57
+
58
+ QUESTIONS:
59
+ {questions}
60
+
61
+ Return only a JSON object keyed by question id:
62
+ {{"new_options": {{"q1": ["...", "..."], "q2": ["..."]}}}}"""
63
+
64
+ VERIFY_PROMPT = """Judge each numbered statement against the evidence from a first-person video segment.
65
+
66
+ EVIDENCE:
67
+ {evidence}
68
+
69
+ STATEMENTS:
70
+ {statements}
71
+
72
+ For each statement answer strictly:
73
+ - "contradicted" if the evidence positively rules it out;
74
+ - "supported" if the evidence indicates it is true;
75
+ - "unclear" if the evidence neither confirms nor rules it out.
76
+
77
+ Return only a JSON object with one verdict per statement, in the same order:
78
+ {{"verdicts": ["contradicted", "unclear", ...]}}"""
79
+
80
+ QUESTION_PROMPT = """Create exactly {count} NEW English benchmark questions from the evidence below.
81
+
82
+ EVIDENCE (the only ground truth; one segment of a first-person walking/running video):
83
+ {evidence}
84
+
85
+ QUESTIONS ALREADY ASKED about this segment — yours must test something different:
86
+ {existing}
87
+
88
+ Return only a JSON object with the key `qa_pairs`. Every question must contain
89
+ question, options, answer, is_multiple_choice and type.
90
+ - `type` is one of trajectory-qa, visual-grounded-qa, spatial-temporal-reasoning.
91
+ - `options` is a JSON OBJECT keyed by consecutive uppercase letters starting at A,
92
+ e.g. {{"A": "...", "B": "..."}} — not a list.
93
+ - Exactly {n_single} questions are single choice with {target_single} options and exactly one answer.
94
+ - The rest are multiple choice with {target_multi} options and at least two answers.
95
+ - `answer` is a non-empty list of option letters.
96
+
97
+ Use only the supplied evidence, but write every question as if asking someone who is
98
+ WATCHING THE VIDEO and has never seen this text. Never refer to the evidence itself:
99
+ no "as described", "explicitly described", "described in the video", "mentioned",
100
+ "according to the description", "the evidence". Ask about what happens on screen.
101
+
102
+ Distractors must be plausible but unambiguously false."""
103
+
104
+
105
+ class RateLimiter:
106
+ """Shared token bucket: the server quota, not worker count, is the bottleneck."""
107
+
108
+ def __init__(self, per_second: float):
109
+ self.interval = 1.0 / per_second
110
+ self.lock = threading.Lock()
111
+ self.next_slot = time.monotonic()
112
+
113
+ def acquire(self) -> None:
114
+ with self.lock:
115
+ now = time.monotonic()
116
+ wait = max(0.0, self.next_slot - now)
117
+ self.next_slot = max(now, self.next_slot) + self.interval
118
+ if wait:
119
+ time.sleep(wait)
120
+
121
+
122
+ class PacedSession:
123
+ """Wrap a requests.Session so the quota paces every outbound attempt.
124
+
125
+ Pacing only the logical call is not enough: generate() and
126
+ generate_valid_json() retry internally, and those retries would otherwise
127
+ bypass the limiter, hit 429 and burn 5-120s of backoff each.
128
+ """
129
+
130
+ def __init__(self, session, limiter):
131
+ self._session = session
132
+ self._limiter = limiter
133
+
134
+ def post(self, *args, **kwargs):
135
+ self._limiter.acquire()
136
+ return self._session.post(*args, **kwargs)
137
+
138
+ def __getattr__(self, name):
139
+ return getattr(self._session, name)
140
+
141
+
142
+ def load_generator():
143
+ spec = importlib.util.spec_from_file_location(
144
+ "repair_runningbench_annotations", HERE / "repair_runningbench_annotations.py"
145
+ )
146
+ module = importlib.util.module_from_spec(spec)
147
+ sys.modules[spec.name] = module
148
+ spec.loader.exec_module(module)
149
+ return module
150
+
151
+
152
+ def shortfall_of(item) -> int:
153
+ options, answer = item.get("options"), item.get("answer") or []
154
+ if not isinstance(options, dict) or not options:
155
+ return 0
156
+ if sorted(options) != [chr(ord("A") + i) for i in range(len(options))]:
157
+ return 0 # corrupted keys: leave alone
158
+ want = TARGET_MULTI if len(answer) > 1 else TARGET_SINGLE
159
+ return max(0, want - len(options))
160
+
161
+
162
+ def make_distractor_validator(wanted: dict):
163
+ def validate(data):
164
+ block = data.get("new_options")
165
+ if not isinstance(block, dict):
166
+ raise ValueError("new_options must be an object keyed by question id")
167
+ for qid, count in wanted.items():
168
+ options = block.get(qid)
169
+ if not isinstance(options, list) or len(options) != count:
170
+ raise ValueError(f"{qid} needs exactly {count} new options")
171
+ if any(not isinstance(o, str) or not o.strip() for o in options):
172
+ raise ValueError(f"{qid} has an empty option")
173
+ if len({o.strip().lower() for o in options}) != count:
174
+ raise ValueError(f"{qid} has duplicate new options")
175
+ return validate
176
+
177
+
178
+ def make_verdict_validator(count):
179
+ def validate(data):
180
+ verdicts = data.get("verdicts")
181
+ if not isinstance(verdicts, list) or len(verdicts) != count:
182
+ raise ValueError(f"verdicts must be a list of exactly {count} entries")
183
+ if any(v not in ("contradicted", "supported", "unclear") for v in verdicts):
184
+ raise ValueError("each verdict must be contradicted, supported or unclear")
185
+ return validate
186
+
187
+
188
+ def make_question_validator(count):
189
+ def validate(data):
190
+ qa = data.get("qa_pairs")
191
+ if not isinstance(qa, list) or len(qa) != count:
192
+ raise ValueError(f"qa_pairs must contain exactly {count} questions")
193
+ for item in qa:
194
+ # The model reliably answers with a positional list of option strings
195
+ # rather than a letter-keyed object. Normalise instead of retrying:
196
+ # position already carries the letter, so the mapping is lossless.
197
+ if isinstance(item.get("options"), list) and all(
198
+ isinstance(o, str) for o in item["options"]):
199
+ item["options"] = {chr(ord("A") + i): o for i, o in enumerate(item["options"])}
200
+ options, answer = item.get("options"), item.get("answer")
201
+ if not item.get("question"):
202
+ raise ValueError("question text is required")
203
+ if item.get("type") not in ("trajectory-qa", "visual-grounded-qa", "spatial-temporal-reasoning"):
204
+ raise ValueError("invalid type")
205
+ if not isinstance(options, dict):
206
+ raise ValueError("options must be an object")
207
+ if sorted(options) != [chr(ord("A") + i) for i in range(len(options))]:
208
+ raise ValueError("option keys must be consecutive from A")
209
+ if not isinstance(answer, list) or not answer or not set(answer) <= set(options):
210
+ raise ValueError("invalid answer")
211
+ item["is_multiple_choice"] = len(answer) > 1
212
+ want = TARGET_MULTI if len(answer) > 1 else TARGET_SINGLE
213
+ if len(options) != want:
214
+ raise ValueError(f"expected {want} options for this answer arity, got {len(options)}")
215
+ lowered = item["question"].lower()
216
+ leaked = [p for p in LEAK_PHRASES if p in lowered]
217
+ if leaked:
218
+ # Citing the description makes the question unanswerable from the video.
219
+ raise ValueError(f"question refers to the evidence text ({leaked[0]!r})")
220
+ if not any(len(i["answer"]) == 1 for i in qa):
221
+ raise ValueError("need at least one single-choice question")
222
+ return validate
223
+
224
+
225
+ def reletter(item, texts, correct_texts, salt):
226
+ order = list(range(len(texts)))
227
+ seed = hashlib.sha256((item["question"] + salt).encode("utf-8")).hexdigest()
228
+ random.Random(seed).shuffle(order)
229
+ item["options"] = {chr(ord("A") + i): texts[j] for i, j in enumerate(order)}
230
+ item["answer"] = sorted(chr(ord("A") + i) for i, j in enumerate(order) if texts[j] in correct_texts)
231
+
232
+
233
+ def collect(pilot):
234
+ out = []
235
+ for directory in SEG_DIRS:
236
+ for path in sorted(directory.glob("**/*_segment_*_annotation.json")):
237
+ if pilot and pilot not in path.name:
238
+ continue
239
+ try:
240
+ record = json.loads(path.read_text(encoding="utf-8"))
241
+ except Exception:
242
+ continue
243
+ if record.get("dense_annotations") and record.get("qa_pairs"):
244
+ out.append((path, record))
245
+ return out
246
+
247
+
248
+ def target_dir(work, source: Path) -> Path:
249
+ tail = source.parts[source.parts.index("annotations_60s") + 1:]
250
+ return work.joinpath("annotations_60s", *tail)
251
+
252
+
253
+ def main() -> int:
254
+ parser = argparse.ArgumentParser()
255
+ parser.add_argument("--work", type=Path, default=DEFAULT_WORK)
256
+ parser.add_argument("--expand-options", action="store_true")
257
+ parser.add_argument("--more-questions", action="store_true")
258
+ parser.add_argument("--pilot")
259
+ parser.add_argument("--workers", type=int, default=3)
260
+ parser.add_argument("--rate", type=float, default=QUOTA_PER_SECOND)
261
+ parser.add_argument("--dry-run", action="store_true")
262
+ args = parser.parse_args()
263
+ if not (args.expand_options or args.more_questions):
264
+ raise SystemExit("pass --expand-options and/or --more-questions")
265
+
266
+ gen = load_generator()
267
+ records = collect(args.pilot)
268
+ calls = len(records) * ((2 if args.expand_options else 0) + (1 if args.more_questions else 0))
269
+ print(f"segments in scope: {len(records)}")
270
+ print(f"batched calls: {calls} (~{calls / args.rate / 3600:.1f} h at {args.rate}/s)")
271
+ if args.dry_run:
272
+ return 0
273
+
274
+ token = os.environ.get("FLOODGATE_PROJECT_TOKEN")
275
+ if not token:
276
+ raise SystemExit("FLOODGATE_PROJECT_TOKEN is required")
277
+
278
+ limiter = RateLimiter(args.rate)
279
+ stats = Counter()
280
+ lock = threading.Lock()
281
+ local = threading.local()
282
+
283
+ def call(prompt, validator, max_tokens):
284
+ if not hasattr(local, "api"):
285
+ local.api = gen.Floodgate(token) # requests.Session is not thread-safe
286
+ local.api.session = PacedSession(local.api.session, limiter)
287
+ return gen.generate_valid_json(local.api, prompt, validator, max_tokens)
288
+
289
+ def bump(key, amount=1):
290
+ with lock:
291
+ stats[key] += amount
292
+
293
+ def process(number, path, record):
294
+ out_path = target_dir(args.work, path)
295
+ if out_path.exists():
296
+ try:
297
+ if json.loads(out_path.read_text(encoding="utf-8")).get("expansion_complete"):
298
+ bump("segments_skipped")
299
+ return
300
+ except Exception:
301
+ pass
302
+ evidence = json.dumps(record["dense_annotations"], ensure_ascii=False)
303
+
304
+ if args.expand_options:
305
+ targets = {}
306
+ for index, item in enumerate(record["qa_pairs"], 1):
307
+ need = shortfall_of(item)
308
+ if need:
309
+ targets[f"q{index}"] = (item, need)
310
+ elif isinstance(item.get("options"), dict):
311
+ bump("questions_already_wide")
312
+ if targets:
313
+ listing = "\n\n".join(
314
+ f"{qid} (needs {need} new options)\nQUESTION: {item['question']}\n"
315
+ + "EXISTING OPTIONS (do not repeat or paraphrase):\n"
316
+ + "\n".join(f"- {item['options'][k]}" for k in sorted(item["options"]))
317
+ for qid, (item, need) in targets.items()
318
+ )
319
+ try:
320
+ proposed = call(
321
+ DISTRACTOR_PROMPT.format(evidence=evidence, questions=listing),
322
+ make_distractor_validator({q: n for q, (_, n) in targets.items()}),
323
+ 4096)["new_options"]
324
+ except Exception as exc:
325
+ proposed = None
326
+ bump("distractor_call_failed")
327
+ print(f" distractor call failed {path.name}: {type(exc).__name__}", flush=True)
328
+
329
+ if proposed:
330
+ flat = [(qid, text) for qid in targets for text in proposed[qid]]
331
+ bump("distractors_proposed", len(flat))
332
+ numbered = "\n".join(f"{i + 1}. {t}" for i, (_, t) in enumerate(flat))
333
+ try:
334
+ verdicts = call(
335
+ VERIFY_PROMPT.format(evidence=evidence, statements=numbered),
336
+ make_verdict_validator(len(flat)), 2048)["verdicts"]
337
+ except Exception as exc:
338
+ # Never promote an unverified distractor.
339
+ verdicts = None
340
+ bump("verify_call_failed")
341
+ print(f" verify call failed {path.name}: {type(exc).__name__}", flush=True)
342
+
343
+ if verdicts:
344
+ accepted = {qid: [] for qid in targets}
345
+ for (qid, text), verdict in zip(flat, verdicts):
346
+ bump(f"verdict_{verdict}")
347
+ if verdict == "contradicted":
348
+ accepted[qid].append(text)
349
+ retry = {qid: need for qid, (item, need) in targets.items() if not accepted[qid]}
350
+ if retry:
351
+ # All candidates were rejected; ask once more before giving up.
352
+ again = "\n\n".join(
353
+ f"{qid} (needs {need} new options)\nQUESTION: {targets[qid][0]['question']}\n"
354
+ + "EXISTING OPTIONS (do not repeat or paraphrase):\n"
355
+ + "\n".join(f"- {targets[qid][0]['options'][k]}" for k in sorted(targets[qid][0]["options"]))
356
+ for qid, need in retry.items())
357
+ try:
358
+ more = call(DISTRACTOR_PROMPT.format(evidence=evidence, questions=again),
359
+ make_distractor_validator(retry), 4096)["new_options"]
360
+ flat2 = [(qid, t) for qid in retry for t in more[qid]]
361
+ bump("distractors_proposed", len(flat2))
362
+ v2 = call(VERIFY_PROMPT.format(
363
+ evidence=evidence,
364
+ statements="\n".join(f"{i + 1}. {t}" for i, (_, t) in enumerate(flat2))),
365
+ make_verdict_validator(len(flat2)), 2048)["verdicts"]
366
+ for (qid, text), verdict in zip(flat2, v2):
367
+ bump(f"verdict_{verdict}")
368
+ if verdict == "contradicted":
369
+ accepted[qid].append(text)
370
+ bump("second_round_used")
371
+ except Exception as exc:
372
+ bump("second_round_failed")
373
+ print(f" second widen round failed {path.name}: {type(exc).__name__}", flush=True)
374
+ for qid, (item, _) in targets.items():
375
+ if not accepted[qid]:
376
+ bump("questions_not_widened")
377
+ continue
378
+ keys = sorted(item["options"])
379
+ correct = {item["options"][k] for k in item["answer"]}
380
+ texts = [item["options"][k] for k in keys] + accepted[qid]
381
+ reletter(item, texts, correct, "|expanded")
382
+ item["option_count_expanded_to"] = len(texts)
383
+ bump("questions_widened")
384
+ bump("distractors_added", len(accepted[qid]))
385
+
386
+ if args.more_questions:
387
+ count = NEW_QUESTIONS_PER_SEGMENT
388
+ asked = "\n".join(f"- {q['question']}" for q in record["qa_pairs"])
389
+ try:
390
+ extra = call(
391
+ QUESTION_PROMPT.format(count=count, evidence=evidence, existing=asked,
392
+ n_single=count - count // 2,
393
+ target_single=TARGET_SINGLE, target_multi=TARGET_MULTI),
394
+ make_question_validator(count), 8192)
395
+ # New questions come back with the correct option written first, like the
396
+ # originals did; shuffle them too or the 61% blind baseline returns.
397
+ gen.shuffle_options(extra["qa_pairs"])
398
+ for item in extra["qa_pairs"]:
399
+ item["generated_by"] = "expand_mcq/more-questions"
400
+ item["new_question_shuffled"] = True
401
+ record["qa_pairs"].extend(extra["qa_pairs"])
402
+ bump("questions_generated", len(extra["qa_pairs"]))
403
+ except Exception as exc:
404
+ bump("question_call_failed")
405
+ print(f" question generation failed {path.name}: {type(exc).__name__}", flush=True)
406
+
407
+ record["option_order"] = "shuffled"
408
+ record["mcq_schema_version"] = "runningbench-mcq-v4-expanded"
409
+ record["expanded_from"] = str(path)
410
+ record["expansion_complete"] = True
411
+ record["expansion_spec"] = {
412
+ "target_single": TARGET_SINGLE, "target_multi": TARGET_MULTI,
413
+ "added_questions_per_segment": NEW_QUESTIONS_PER_SEGMENT if args.more_questions else 0,
414
+ }
415
+ gen.write_json(out_path, record)
416
+ bump("segments_written")
417
+ print(f"[{number}/{len(records)}] {path.name} -> {len(record['qa_pairs'])} questions", flush=True)
418
+
419
+ started = time.monotonic()
420
+ with ThreadPoolExecutor(max_workers=args.workers) as pool:
421
+ futures = {pool.submit(process, n, p, r): p for n, (p, r) in enumerate(records, 1)}
422
+ for future in as_completed(futures):
423
+ try:
424
+ future.result()
425
+ except Exception as exc:
426
+ bump("segments_failed") # one bad segment must not end the run
427
+ print(f" segment failed {futures[future].name}: {type(exc).__name__}: {exc}", flush=True)
428
+
429
+ print(f"\nelapsed {(time.monotonic() - started) / 60:.1f} min")
430
+ print(json.dumps(dict(sorted(stats.items())), indent=1))
431
+ return 0
432
+
433
+
434
+ if __name__ == "__main__":
435
+ raise SystemExit(main())
multi_video_cross_video_methodology/source_docs/export_segment_bundle.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Export the repaired segment questions plus their clips as one self-contained bundle.
3
+
4
+ Only the distractor rebuild runs on the Gemini quota. The two gates that follow --
5
+ blind-guess voting and the visual re-check -- are left for a local model, so this
6
+ writes what those gates need and nothing else: one question per record, the 480p clip
7
+ that shows it, and the evidence the answer came from.
8
+
9
+ Gate order matters and is easy to get wrong. Shuffle BEFORE measuring guessability:
10
+ generators favour putting the answer first and blind models favour picking first, so
11
+ testing an unshuffled set reports a guess rate that is too high for the wrong reason.
12
+ These questions are already shuffled (deterministically, seeded on the question text).
13
+
14
+ Usage: export_segment_bundle.py [--repaired pilot.json] [--out bundle/]
15
+ """
16
+ import argparse
17
+ import collections
18
+ import glob
19
+ import json
20
+ import os
21
+ import re
22
+ import sys
23
+ from pathlib import Path
24
+
25
+ REPAIR_ROOT = Path("/mnt/data/data_anno/runningbench_segment_repair")
26
+ CLIPS = REPAIR_ROOT / "clips_480p"
27
+ SEG_ROOT = "/mnt/data/data_anno/runningbench_qa_expansion/annotations_60s"
28
+
29
+
30
+ def main():
31
+ ap = argparse.ArgumentParser()
32
+ ap.add_argument("--repaired", default=str(REPAIR_ROOT / "repaired_all.json"))
33
+ ap.add_argument("--out", default=str(REPAIR_ROOT / "bundle"))
34
+ a = ap.parse_args()
35
+
36
+ out = Path(a.out)
37
+ out.mkdir(parents=True, exist_ok=True)
38
+ repaired = json.load(open(a.repaired))["repaired"]
39
+
40
+ # Segment metadata, keyed by the file the question came from.
41
+ meta = {}
42
+ for path in glob.glob(f"{SEG_ROOT}/**/*.json", recursive=True):
43
+ try:
44
+ rec = json.load(open(path))
45
+ except Exception:
46
+ continue
47
+ raw = rec.get("original_video_path") or ""
48
+ stem = re.sub(r"_segment_\d+$", "", os.path.basename(raw).rsplit(".", 1)[0])
49
+ meta[path] = {"video": stem, "segment_index": rec.get("segment_index"),
50
+ "start_time_sec": rec.get("start_time_sec"),
51
+ "end_time_sec": rec.get("end_time_sec"),
52
+ "evidence": rec.get("dense_annotations") or rec.get("annotation_raw")}
53
+
54
+ rows, missing_clip = [], 0
55
+ for r in repaired:
56
+ m = meta.get(r["file"])
57
+ if not m:
58
+ continue
59
+ clip = CLIPS / m["video"] / f"{m['video']}_segment_{m['segment_index']}.480p.mp4"
60
+ if not clip.exists():
61
+ missing_clip += 1
62
+ clip = None
63
+ item = r["item"]
64
+ rows.append({
65
+ "id": f"{m['video']}_seg{m['segment_index']}_q{r['index']}",
66
+ "video": m["video"],
67
+ "segment_index": m["segment_index"],
68
+ "span_sec": [m["start_time_sec"], m["end_time_sec"]],
69
+ "clip": str(clip) if clip else None,
70
+ "question": item["question"],
71
+ "options": item["options"],
72
+ "answer": item["answer"],
73
+ "arity": "single" if len(item["answer"]) == 1 else "multi",
74
+ "type": item.get("type"),
75
+ "option_order": "shuffled",
76
+ "distractors_rebuilt": item.get("distractors_rebuilt", 0),
77
+ "evidence": m["evidence"],
78
+ })
79
+
80
+ json.dump({"n": len(rows),
81
+ "note": "distractors rebuilt with Gemini; blind-guess and visual re-check gates NOT run",
82
+ "questions": rows},
83
+ open(out / "questions.json", "w"), ensure_ascii=False, indent=1)
84
+
85
+ fmt = collections.Counter((r["arity"], len(r["options"])) for r in rows)
86
+ with open(out / "README.md", "w") as fh:
87
+ fh.write(f"""# 段级题修复包
88
+
89
+ {len(rows)} 道题,干扰项已用 Gemini 重造并逐条验证「被证据明确否定」。
90
+ **盲猜闸门和回看闸门都没跑** —— 留给本地模型。
91
+
92
+ ## 内容
93
+
94
+ - `questions.json` — 每题一条记录,含 `clip` 指向该段的 480p 片段
95
+ - 片段在 `{CLIPS}`,1,332 段,480p/crf30
96
+
97
+ ## 字段
98
+
99
+ | 字段 | 说明 |
100
+ |---|---|
101
+ | `clip` | 该题对应的 60 秒片段路径,回看闸门用 |
102
+ | `evidence` | 出题时用的结构化标注,验证干扰项用 |
103
+ | `options` / `answer` | **已打乱**,answer 是字母列表 |
104
+ | `distractors_rebuilt` | 本次重造并通过验证的干扰项个数 |
105
+
106
+ ## 建议的闸门顺序
107
+
108
+ 1. **盲猜 ×3**:只给 question + options,不给视频,答三次;≥2 次命中即淘汰
109
+ 2. **回看**:把 `clip` 和题目一起给模型,问画面是否支持 `answer`;只留 supported
110
+
111
+ 顺序不能颠倒 —— 选项已经打乱过了,直接跑盲猜即可。若你重新打乱,务必打乱后再测。
112
+
113
+ ## 已知基线(同一批语料,修复前)
114
+
115
+ | | 可猜率 |
116
+ |---|---|
117
+ | 单选(主体 6 选项) | 64.7% |
118
+ | 多选(主体 8 选项) | 25.3% |
119
+ | 整体 | 48.6%(801 道抽样,95%CI [45.1, 52.0]) |
120
+
121
+ 修复后应显著低于这些数字,否则说明重造没起作用。
122
+
123
+ ## 格式分布
124
+
125
+ """ + "\n".join(f"- {k[0]} {k[1]} 选项: {v}" for k, v in sorted(fmt.items())) + "\n")
126
+
127
+ print(f"wrote {len(rows)} questions -> {out}/questions.json")
128
+ print(f" formats: {dict(fmt)}")
129
+ if missing_clip:
130
+ print(f" WARNING: {missing_clip} questions have no clip on disk")
131
+
132
+
133
+ if __name__ == "__main__":
134
+ sys.exit(main())
multi_video_cross_video_methodology/source_docs/package_full_release.py ADDED
@@ -0,0 +1,327 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Package every question and caption in the corpus, both video sources, for human screening.
3
+
4
+ An earlier package covered only the Google Drive subset, because the annotators were
5
+ expected to have only that footage. The screening task is larger than that: of the 9,925
6
+ questions that have never been judged, 5,324 come from HuggingFace recordings and
7
+ Video Bench, so a Drive-only export hands the screeners under half of their own workload.
8
+
9
+ Deduplication matters here and is easy to get wrong. The corpus keeps six older copies of
10
+ the segment questions in separate directories -- conductor_release, gdrive_videos_annotations,
11
+ shaky_videos_annotations, and others -- with 10,566 rows between them and not one question
12
+ the current corpus lacks. Counting files instead of question texts inflates the total by
13
+ 2.5x. Rows are keyed on a hash of the question text, first writer wins, and the authoritative
14
+ directory for each layer is listed first.
15
+
16
+ Provenance also cannot be read from a path prefix. Mikail and Markus are HuggingFace
17
+ subfolders whose older records still carry a /shaky_videos/ working-directory path, while
18
+ `shaky_videos_segmented/` is where clips from EVERY source were written -- so matching on
19
+ "shaky_videos" alone labels Google Drive recordings as HuggingFace. Only
20
+ original_video_path decides, and the raw-vs-segmented distinction is explicit.
21
+
22
+ Usage: package_full_release.py [--out DIR]
23
+ """
24
+ import argparse
25
+ import collections
26
+ import glob
27
+ import hashlib
28
+ import json
29
+ import os
30
+ import re
31
+ import sys
32
+ from pathlib import Path
33
+
34
+ SCENES = "/mnt/data/cvhci_video_understanding/metadata/route_manifest/scene_manifest.json"
35
+ DEFAULT_OUT = Path("/mnt/data/data_anno/runningbench_full_release")
36
+
37
+ # Authoritative directory per layer, in priority order. Anything not listed is an older
38
+ # copy: verified to contribute zero questions the current corpus does not already hold.
39
+ CAPTION_SOURCES = [
40
+ ("segments_60s", ["/mnt/data/data_anno/runningbench_qa_expansion/annotations_60s/**/*.json",
41
+ "/mnt/data/data_anno/runningbench_hf_gapfill/annotations_60s/**/*.json"]),
42
+ ("windows_180s", ["/mnt/data/data_anno/runningbench_gap_repair/annotations_180s/**/*.json"]),
43
+ ("windows_180s_aggregated",
44
+ ["/mnt/data/data_anno/runningbench_aggregate_fill/annotations_180s/**/*.json"]),
45
+ ("whole_video", ["/mnt/data/data_anno/runningbench_gap_repair/annotations_whole/**/*.json"]),
46
+ ("whole_video_aggregated",
47
+ ["/mnt/data/data_anno/runningbench_aggregate_fill/annotations_whole/**/*.json"]),
48
+ ]
49
+
50
+
51
+ def qhash(text):
52
+ return hashlib.sha256((text or "").strip().lower().encode("utf-8")).hexdigest()[:16]
53
+
54
+
55
+ def gdrive_stems():
56
+ return {os.path.basename(r["file"]).rsplit(".", 1)[0]
57
+ for r in json.load(open(SCENES))["runs"] if "google_drive" in (r.get("file") or "")}
58
+
59
+
60
+ def provenance(path):
61
+ """Google Drive or HuggingFace, from the ORIGINAL path only.
62
+
63
+ `/shaky_videos/Mikail/` is HuggingFace footage under its old working-directory path;
64
+ `/shaky_videos_segmented/` is the clip output directory shared by all sources and says
65
+ nothing about origin. Testing for "shaky_videos" without that distinction is what made
66
+ an earlier census report four sources where there are two.
67
+ """
68
+ if "google_drive" in path or "GDrive_Data" in path:
69
+ return "google_drive"
70
+ if "huggingface" in path.lower():
71
+ return "huggingface"
72
+ if re.search(r"/shaky_videos/(Mikail|Markus|Alec)/", path):
73
+ return "huggingface"
74
+ return "unknown"
75
+
76
+
77
+ def load_items(path):
78
+ try:
79
+ doc = json.load(open(path))
80
+ except Exception:
81
+ return None, []
82
+ if not isinstance(doc, dict):
83
+ return None, []
84
+ items = []
85
+ for field in ("qa_pairs", "questions"):
86
+ v = doc.get(field)
87
+ if isinstance(v, list):
88
+ items += [x for x in v if isinstance(x, dict)]
89
+ return doc, items
90
+
91
+
92
+ def is_objective(item):
93
+ opts = item.get("options") or item.get("choices")
94
+ ans = item.get("answer")
95
+ has = (isinstance(opts, dict) and opts) or (isinstance(opts, list) and opts)
96
+ return bool(has) and ans not in (None, "", [])
97
+
98
+
99
+ def gate_status(item):
100
+ g = item.get("gates") or {}
101
+ if not g:
102
+ return "ungated", None, None
103
+ blind = bool((g.get("blind_guess") or {}).get("matches_gold"))
104
+ rc = g.get("visual_recheck") or {}
105
+ verdict = rc.get("verdict") if isinstance(rc, dict) else rc
106
+ if blind:
107
+ return "rejected_blind_guessable", verdict, (g.get("blind_guess") or {}).get("hits_of_3")
108
+ if verdict == "supported":
109
+ return "usable", verdict, (g.get("blind_guess") or {}).get("hits_of_3")
110
+ return f"rejected_{verdict}", verdict, (g.get("blind_guess") or {}).get("hits_of_3")
111
+
112
+
113
+ def main():
114
+ ap = argparse.ArgumentParser()
115
+ ap.add_argument("--out", default=str(DEFAULT_OUT))
116
+ a = ap.parse_args()
117
+ out = Path(a.out)
118
+ gd = gdrive_stems()
119
+ seen = set()
120
+ stats = collections.OrderedDict()
121
+
122
+ def write(rel, rows):
123
+ p = out / rel
124
+ p.parent.mkdir(parents=True, exist_ok=True)
125
+ with open(p, "w") as fh:
126
+ for r in rows:
127
+ fh.write(json.dumps(r, ensure_ascii=False) + "\n")
128
+ stats[rel] = {"rows": len(rows), "bytes": p.stat().st_size}
129
+ return len(rows)
130
+
131
+ # ---------------- captions ----------------
132
+ for label, pats in CAPTION_SOURCES:
133
+ rows = []
134
+ for pat in pats:
135
+ for f in sorted(glob.glob(pat, recursive=True)):
136
+ doc, _ = load_items(f)
137
+ if not doc:
138
+ continue
139
+ cap = doc.get("dense_annotations") or doc.get("annotation_raw")
140
+ if not cap:
141
+ continue
142
+ src = doc.get("original_video_path") or ""
143
+ video = os.path.basename(src).rsplit(".", 1)[0]
144
+ idx = doc.get("segment_index", doc.get("chunk_index", 0))
145
+ key = (label, video, idx)
146
+ if key in seen:
147
+ continue
148
+ seen.add(key)
149
+ rows.append({
150
+ "id": f"{video}_{label}_{idx}", "video": video,
151
+ "provenance": provenance(src), "index": idx,
152
+ "span_sec": [doc.get("start_time_sec"), doc.get("end_time_sec")],
153
+ "model": doc.get("model_name"),
154
+ "aggregated_without_video": bool(doc.get("aggregated_without_video")),
155
+ "derived_from": [os.path.basename(x) for x in (doc.get("derived_from") or [])],
156
+ "caption": cap,
157
+ })
158
+ write(f"captions/{label}.jsonl", rows)
159
+
160
+ # whole-video structural annotations (the full-video line's own pass)
161
+ rows = []
162
+ for f in sorted(glob.glob("/mnt/data/data_anno/runningbench_fullvideo/**/annotations/*.json",
163
+ recursive=True)):
164
+ rec = json.load(open(f))
165
+ stem = os.path.basename(f).rsplit(".", 1)[0]
166
+ rows.append({"id": stem, "video": stem,
167
+ "provenance": "google_drive" if stem in gd else "huggingface",
168
+ "scene_id": rec.get("scene_id"), "route_id": rec.get("route_id"),
169
+ "duration_sec": rec.get("duration_sec"), "model": rec.get("global_model"),
170
+ "run_meta": rec.get("run_meta"),
171
+ "route_phases": rec.get("route_phases"),
172
+ "environment_stages": rec.get("environment_stages"),
173
+ "dynamic_events": rec.get("dynamic_events"),
174
+ "revisited_landmarks": rec.get("revisited_landmarks"),
175
+ "start_end_relation": rec.get("start_end_relation")})
176
+ write("captions/fullvideo_structural.jsonl", rows)
177
+
178
+ # ---------------- questions ----------------
179
+ qseen = set()
180
+ tally = collections.Counter()
181
+
182
+ def emit(item, doc, unit, layer, video_ids=None, forced_provenance=None):
183
+ h = qhash(item.get("question"))
184
+ if h in qseen:
185
+ return None
186
+ qseen.add(h)
187
+ opts = item.get("options") or item.get("choices")
188
+ ans = item.get("answer")
189
+ status, verdict, hits = gate_status(item)
190
+ src = (doc or {}).get("original_video_path") or ""
191
+ if video_ids:
192
+ prov = "google_drive" if all(v in gd for v in video_ids) else "huggingface"
193
+ video = video_ids if len(video_ids) > 1 else video_ids[0]
194
+ else:
195
+ prov = forced_provenance or provenance(src)
196
+ video = os.path.basename(src).rsplit(".", 1)[0] if src else None
197
+ n_ans = len(ans) if isinstance(ans, list) else 1
198
+ row = {
199
+ "id": h, "layer": layer, "unit": unit, "provenance": prov, "video": video,
200
+ "span_sec": [(doc or {}).get("start_time_sec"), (doc or {}).get("end_time_sec")],
201
+ "question": item.get("question"),
202
+ "question_type": item.get("question_type") or item.get("type"),
203
+ "options": opts, "answer": ans,
204
+ "arity": "multi" if n_ans > 1 else "single",
205
+ "n_options": len(opts) if isinstance(opts, (dict, list)) else None,
206
+ "option_order": item.get("option_order") or (doc or {}).get("option_order") or "unknown",
207
+ "evidence_spans": item.get("evidence_spans"),
208
+ "why_hard": item.get("why_hard"),
209
+ "screening_status": status,
210
+ "gates": ({"blind_guess_hits_of_3": hits, "visual_recheck": verdict,
211
+ "recheck_notes": ((item.get("gates") or {}).get("visual_recheck") or {}).get("notes")
212
+ if isinstance((item.get("gates") or {}).get("visual_recheck"), dict) else None}
213
+ if item.get("gates") else None),
214
+ }
215
+ tally[(layer, status)] += 1
216
+ tally[(prov, "total")] += 1
217
+ return row
218
+
219
+ seg = []
220
+ for pat in ("/mnt/data/data_anno/runningbench_qa_expansion/annotations_60s/**/*.json",
221
+ "/mnt/data/data_anno/runningbench_hf_gapfill/annotations_60s/**/*.json"):
222
+ for f in sorted(glob.glob(pat, recursive=True)):
223
+ doc, items = load_items(f)
224
+ for it in items:
225
+ if not is_objective(it):
226
+ continue
227
+ r = emit(it, doc, "60s_segment", "segment_60s")
228
+ if r:
229
+ seg.append(r)
230
+ write("questions/segments_60s.jsonl", seg)
231
+
232
+ fv, cv = [], []
233
+ for f in sorted(glob.glob("/mnt/data/data_anno/runningbench_fullvideo/route_*/questions/*.json")):
234
+ doc, items = load_items(f)
235
+ for it in items:
236
+ if not is_objective(it):
237
+ continue
238
+ raw = it.get("video_id") or it.get("video_ids")
239
+ vids = ([raw] if isinstance(raw, str)
240
+ else list(raw.values()) if isinstance(raw, dict) else list(raw or []))
241
+ if not vids:
242
+ continue
243
+ unit = "cross_video" if len(vids) > 1 else "whole_video"
244
+ r = emit(it, doc, unit, "fullvideo", vids)
245
+ if r:
246
+ r["video_ids"] = raw if isinstance(raw, dict) else None
247
+ (cv if unit == "cross_video" else fv).append(r)
248
+ write("questions/whole_video.jsonl", fv)
249
+ write("questions/cross_video.jsonl", cv)
250
+
251
+ exc = []
252
+ for f in sorted(glob.glob("/mnt/data/data_anno/runningbench_excerpts/fullvideo/*/questions/*.json")):
253
+ doc, items = load_items(f)
254
+ for it in items:
255
+ if not is_objective(it):
256
+ continue
257
+ raw = it.get("video_id") or it.get("video_ids")
258
+ vids = ([raw] if isinstance(raw, str)
259
+ else list(raw.values()) if isinstance(raw, dict) else list(raw or []))
260
+ r = emit(it, doc, "excerpt", "excerpt", vids or None)
261
+ if r:
262
+ exc.append(r)
263
+ write("questions/excerpts.jsonl", exc)
264
+
265
+ vb = []
266
+ for pat in ("/mnt/data/data_anno/videobench_rebalanced/videobench_main.json",
267
+ "/mnt/data/data_anno/videobench_rebalanced/per_video/**/*.json"):
268
+ for f in sorted(glob.glob(pat, recursive=True)):
269
+ doc, items = load_items(f)
270
+ for it in items:
271
+ if not is_objective(it):
272
+ continue
273
+ # Video Bench rows carry no original_video_path, so provenance() returns
274
+ # "unknown"; the footage is the HuggingFace set. Fix it before the tally
275
+ # counts it, not after -- the manifest reads the counter, not these rows.
276
+ r = emit(it, doc, "25s_segment", "videobench", forced_provenance="huggingface")
277
+ if r:
278
+ r["family"] = it.get("family")
279
+ r["difficulty"] = it.get("difficulty")
280
+ r["answer_format"] = it.get("answer_format")
281
+ vb.append(r)
282
+ write("questions/videobench.jsonl", vb)
283
+
284
+ # repaired distractors, kept apart: same questions, new options, never re-tested
285
+ rep = []
286
+ src = "/mnt/data/data_anno/runningbench_segment_repair/repaired_multi.json"
287
+ if os.path.exists(src):
288
+ for x in json.load(open(src))["repaired"]:
289
+ it = x["item"]
290
+ rep.append({"id": qhash(it.get("question")), "question": it.get("question"),
291
+ "options": it.get("options"), "answer": it.get("answer"),
292
+ "distractors_rebuilt": it.get("distractors_rebuilt", 0),
293
+ "fully_reverted": it.get("distractors_rebuilt", 0) == 0,
294
+ "screening_status": "ungated",
295
+ "note": "distractors rebuilt from the text annotation; no video, no gates"})
296
+ write("questions/segments_60s_repaired_distractors.jsonl", rep)
297
+
298
+ total_q = len(seg) + len(fv) + len(cv) + len(exc) + len(vb)
299
+ by_status = collections.Counter()
300
+ for (layer, status), n in tally.items():
301
+ if status in ("total",):
302
+ continue
303
+ by_status[status] += n
304
+
305
+ manifest = {
306
+ "release": "runningbench-full-v1",
307
+ "sources": ["google_drive", "huggingface"],
308
+ "questions_total_deduplicated": total_q,
309
+ "by_status": dict(by_status),
310
+ "by_provenance": {k: v for (k, s), v in tally.items() if s == "total"},
311
+ "files": dict(stats),
312
+ "note": "Question rows are deduplicated on question text. Older duplicate copies of "
313
+ "the segment corpus (conductor_release, gdrive_videos_annotations, "
314
+ "shaky_videos_annotations*) contribute nothing and are excluded.",
315
+ }
316
+ (out / "manifest.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=1))
317
+
318
+ print(f"{'file':52s} {'rows':>7s} {'size':>9s}")
319
+ for k, v in stats.items():
320
+ print(f" {k:50s} {v['rows']:7d} {v['bytes']/2**20:8.2f}M")
321
+ print(f"\nquestions {total_q} · by status {dict(by_status)}")
322
+ print(f"by provenance {manifest['by_provenance']}")
323
+ print(f"-> {out}")
324
+
325
+
326
+ if __name__ == "__main__":
327
+ sys.exit(main())
multi_video_cross_video_methodology/source_docs/package_gdrive_release.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Package the Google-Drive-sourced captions and QA pairs as one release directory.
3
+
4
+ The corpus draws on four separate video sources -- a controlled Google Drive collection
5
+ plus footage from HuggingFace and two contributors' folders -- and only the Drive subset
6
+ carries the structural metadata (scene_id, route_id, turnaround_sec) that the route
7
+ questions are built and checked against. This exports that subset alone, so a reader is
8
+ never left guessing which rows have route metadata behind them and which do not.
9
+
10
+ Provenance is taken from scene_manifest.json, not from filename shape: the run list there
11
+ is the authority on which recording came from where, and inferring it from a "P01_" prefix
12
+ would silently include or drop files the manifest disagrees with.
13
+
14
+ Everything is written as JSONL, one record per line, so a 4,764-row question file can be
15
+ streamed instead of loaded whole.
16
+
17
+ Usage: package_gdrive_release.py [--out DIR] [--copy-clips]
18
+ """
19
+ import argparse
20
+ import collections
21
+ import json
22
+ import glob
23
+ import os
24
+ import shutil
25
+ import sys
26
+ from pathlib import Path
27
+
28
+ SCENES = "/mnt/data/cvhci_video_understanding/metadata/route_manifest/scene_manifest.json"
29
+ SEG60 = "/mnt/data/data_anno/runningbench_qa_expansion/annotations_60s"
30
+ GAP = "/mnt/data/data_anno/runningbench_gap_repair"
31
+ FULL = "/mnt/data/data_anno/runningbench_fullvideo"
32
+ DEFAULT_OUT = Path("/mnt/data/data_anno/runningbench_gdrive_release")
33
+
34
+
35
+ def gdrive_runs():
36
+ """run_id -> run record, for the Google Drive subset only."""
37
+ out = {}
38
+ for r in json.load(open(SCENES))["runs"]:
39
+ if "google_drive" in (r.get("file") or ""):
40
+ out[os.path.basename(r["file"]).rsplit(".", 1)[0]] = r
41
+ return out
42
+
43
+
44
+ def stem_of(rec):
45
+ p = rec.get("original_video_path") or rec.get("video_path") or ""
46
+ return os.path.basename(p).rsplit(".", 1)[0] if p else None
47
+
48
+
49
+ def write_jsonl(path, rows):
50
+ path.parent.mkdir(parents=True, exist_ok=True)
51
+ with open(path, "w") as fh:
52
+ for r in rows:
53
+ fh.write(json.dumps(r, ensure_ascii=False) + "\n")
54
+ return len(rows), path.stat().st_size
55
+
56
+
57
+ def main():
58
+ ap = argparse.ArgumentParser()
59
+ ap.add_argument("--out", default=str(DEFAULT_OUT))
60
+ ap.add_argument("--copy-clips", action="store_true",
61
+ help="also copy the 480p re-check clips (adds several GiB)")
62
+ a = ap.parse_args()
63
+ out = Path(a.out)
64
+ runs = gdrive_runs()
65
+ print(f"Google Drive subset: {len(runs)} recordings", flush=True)
66
+
67
+ stats = collections.OrderedDict()
68
+
69
+ # ---- 60 s dense captions + their multiple-choice questions ----
70
+ cap60, qa60 = [], []
71
+ for f in sorted(glob.glob(f"{SEG60}/**/*.json", recursive=True)):
72
+ try:
73
+ rec = json.load(open(f))
74
+ except Exception:
75
+ continue
76
+ stem = stem_of(rec)
77
+ if stem not in runs:
78
+ continue
79
+ seg = rec.get("segment_index")
80
+ cap60.append({
81
+ "id": f"{stem}_seg{seg}",
82
+ "video": stem, "segment_index": seg,
83
+ "span_sec": [rec.get("start_time_sec"), rec.get("end_time_sec")],
84
+ "model": rec.get("model_name"),
85
+ "caption": rec.get("dense_annotations") or rec.get("annotation_raw"),
86
+ })
87
+ for i, item in enumerate(rec.get("qa_pairs") or []):
88
+ opts, ans = item.get("options"), item.get("answer")
89
+ if not (isinstance(opts, dict) and opts and isinstance(ans, list) and ans):
90
+ continue
91
+ qa60.append({
92
+ "id": f"{stem}_seg{seg}_q{i}",
93
+ "video": stem, "segment_index": seg,
94
+ "span_sec": [rec.get("start_time_sec"), rec.get("end_time_sec")],
95
+ "question": item.get("question"),
96
+ "options": opts, "answer": ans,
97
+ "arity": "single" if len(ans) == 1 else "multi",
98
+ "type": item.get("type"),
99
+ "option_order": rec.get("option_order", "unknown"),
100
+ })
101
+ stats["captions/segments_60s.jsonl"] = write_jsonl(out / "captions/segments_60s.jsonl", cap60)
102
+ stats["qa/segments_60s.jsonl"] = write_jsonl(out / "qa/segments_60s.jsonl", qa60)
103
+
104
+ # ---- 180 s windows and whole-video open-ended descriptions ----
105
+ for label, sub, gran in (("windows_180s", "annotations_180s", "180s"),
106
+ ("whole_video", "annotations_whole", "whole")):
107
+ caps, qas = [], []
108
+ for f in sorted(glob.glob(f"{GAP}/{sub}/**/*.json", recursive=True)):
109
+ try:
110
+ rec = json.load(open(f))
111
+ except Exception:
112
+ continue
113
+ stem = stem_of(rec)
114
+ if stem not in runs:
115
+ continue
116
+ idx = rec.get("chunk_index", 0)
117
+ caps.append({
118
+ "id": f"{stem}_{gran}{idx}", "video": stem, "granularity": gran,
119
+ "chunk_index": idx,
120
+ "span_sec": [rec.get("start_time_sec"), rec.get("end_time_sec")],
121
+ "model": rec.get("model_name"),
122
+ "caption": rec.get("dense_annotations") or rec.get("annotation_raw"),
123
+ "derived_from_60s": [os.path.basename(x) for x in (rec.get("derived_from") or [])],
124
+ })
125
+ for i, item in enumerate(rec.get("qa_pairs") or []):
126
+ qas.append({
127
+ "id": f"{stem}_{gran}{idx}_q{i}", "video": stem, "granularity": gran,
128
+ "span_sec": [rec.get("start_time_sec"), rec.get("end_time_sec")],
129
+ "question": item.get("question"),
130
+ "answer": item.get("answer"), # free text, no options
131
+ "type": item.get("type"), "format": "open_ended",
132
+ })
133
+ stats[f"captions/{label}.jsonl"] = write_jsonl(out / f"captions/{label}.jsonl", caps)
134
+ stats[f"qa/{label}_open.jsonl"] = write_jsonl(out / f"qa/{label}_open.jsonl", qas)
135
+
136
+ # ---- whole-video structural annotations and their gated questions ----
137
+ fv_caps = []
138
+ for f in sorted(glob.glob(f"{FULL}/**/annotations/*.json", recursive=True)):
139
+ rec = json.load(open(f))
140
+ stem = os.path.basename(f).rsplit(".", 1)[0]
141
+ if stem not in runs:
142
+ continue
143
+ fv_caps.append({
144
+ "id": stem, "video": stem,
145
+ "scene_id": rec.get("scene_id"), "route_id": rec.get("route_id"),
146
+ "duration_sec": rec.get("duration_sec"),
147
+ "model": rec.get("global_model"),
148
+ "run_meta": rec.get("run_meta"),
149
+ "route_phases": rec.get("route_phases"),
150
+ "environment_stages": rec.get("environment_stages"),
151
+ "dynamic_events": rec.get("dynamic_events"),
152
+ "revisited_landmarks": rec.get("revisited_landmarks"),
153
+ "start_end_relation": rec.get("start_end_relation"),
154
+ })
155
+ stats["captions/fullvideo_structural.jsonl"] = write_jsonl(
156
+ out / "captions/fullvideo_structural.jsonl", fv_caps)
157
+
158
+ fv_qa = []
159
+ for f in sorted(glob.glob(f"{FULL}/**/questions/*.json", recursive=True)):
160
+ doc = json.load(open(f))
161
+ for q in doc.get("questions") or []:
162
+ # Whole-video questions carry `video_id`; cross-video ones carry `video_ids`
163
+ # (with `required_video_ids` alongside) and leave `video_id` null. Reading only
164
+ # the singular field silently drops every cross-video question -- all 347 of
165
+ # them -- which is the one part of this corpus nothing else replaces.
166
+ # Three shapes in one corpus. A whole-video question carries `video_id` as a
167
+ # string. A cross-video question leaves that null and carries `video_ids` as a
168
+ # LABEL->recording map ({"M": "P03_FastWalk_...", ...}) with `required_video_ids`
169
+ # listing the labels, not the recordings -- so reading either as a list of
170
+ # recordings yields label letters and matches nothing. Both earlier attempts
171
+ # dropped all 347 cross-video questions, the one part of this corpus that
172
+ # nothing else replaces.
173
+ raw = q.get("video_id") or q.get("video_ids")
174
+ if isinstance(raw, str):
175
+ vids, labels = [raw], None
176
+ elif isinstance(raw, dict):
177
+ vids, labels = list(raw.values()), raw
178
+ else:
179
+ vids, labels = list(raw or []), None
180
+ # A cross-video question belongs to the release only if every recording it
181
+ # compares is in the subset; a partial one cannot be answered from what ships.
182
+ if not vids or any(v not in runs for v in vids):
183
+ continue
184
+ g = q.get("gates") or {}
185
+ rc = g.get("visual_recheck")
186
+ verdict = rc.get("verdict") if isinstance(rc, dict) else rc
187
+ blind = bool((g.get("blind_guess") or {}).get("matches_gold"))
188
+ fv_qa.append({
189
+ "id": f"{'+'.join(vids)}_{abs(hash(q.get('question'))) % 10**8}",
190
+ "video_id": q.get("video_id"),
191
+ "video_ids": labels,
192
+ "scene_id": q.get("scene_id"), "route_id": q.get("route_id"),
193
+ "unit": "cross_video" if len(vids) > 1 else "whole_video",
194
+ "question": q.get("question"), "question_type": q.get("question_type"),
195
+ "options": q.get("options"), "answer": q.get("answer"),
196
+ "option_order": q.get("option_order"),
197
+ "evidence_spans": q.get("evidence_spans"),
198
+ "why_hard": q.get("why_hard"),
199
+ "gates": {"blind_guess_hits_of_3": (g.get("blind_guess") or {}).get("hits_of_3"),
200
+ "blind_guessable": blind,
201
+ "visual_recheck": verdict,
202
+ "recheck_notes": rc.get("notes") if isinstance(rc, dict) else None},
203
+ "usable": verdict == "supported" and not blind,
204
+ })
205
+ stats["qa/fullvideo_gated.jsonl"] = write_jsonl(out / "qa/fullvideo_gated.jsonl", fv_qa)
206
+
207
+ if a.copy_clips:
208
+ dst = out / "clips_480p_180s"
209
+ n = 0
210
+ for src in glob.glob("/mnt/data/data_anno/runningbench_windows/clips_480p/**/*.mp4", recursive=True):
211
+ stem = os.path.basename(os.path.dirname(src))
212
+ if stem not in runs:
213
+ continue
214
+ (dst / stem).mkdir(parents=True, exist_ok=True)
215
+ shutil.copy2(src, dst / stem / os.path.basename(src))
216
+ n += 1
217
+ print(f"copied {n} clips", flush=True)
218
+
219
+ manifest = {
220
+ "release": "runningbench-gdrive-v1",
221
+ "source": "Google Drive controlled collection (scene_manifest.json subset)",
222
+ "recordings": len(runs),
223
+ "total_hours": round(sum(r.get("duration_sec") or 0 for r in runs.values()) / 3600, 2),
224
+ "participants": sorted({r.get("participant") for r in runs.values() if r.get("participant")}),
225
+ "files": {k: {"rows": v[0], "bytes": v[1]} for k, v in stats.items()},
226
+ "usable_fullvideo_questions": sum(1 for q in fv_qa if q["usable"]),
227
+ }
228
+ (out / "manifest.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=1))
229
+
230
+ print(f"\n{'file':44s} {'rows':>7s} {'size':>10s}")
231
+ for k, (rows, size) in stats.items():
232
+ print(f" {k:42s} {rows:7d} {size/2**20:9.2f}M")
233
+ print(f"\n{len(runs)} recordings · {manifest['total_hours']} h · "
234
+ f"participants {manifest['participants']}")
235
+ print(f"usable gated full-video questions: {manifest['usable_fullvideo_questions']}")
236
+ print(f"-> {out}")
237
+
238
+
239
+ if __name__ == "__main__":
240
+ sys.exit(main())
multi_video_cross_video_methodology/source_docs/pilot_scripts_20260824/build_manifest.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Build a metadata manifest for the CVHCI running video collection."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ import re
9
+ from collections import Counter
10
+ from pathlib import Path
11
+
12
+ import av
13
+
14
+
15
+ NAME_RE = re.compile(
16
+ r"^(?P<participant>P\d{2})_"
17
+ r"(?P<activity>FastWalk|SlowWalk|Running)_"
18
+ r"(?P<lighting>Day|Night)_"
19
+ r"(?:(?:Traj(?P<trajectory>\d{2}))(?:_Trial(?P<trial_after_traj>\d{2}))?"
20
+ r"|(?:Trial(?P<trial>\d{2})))$"
21
+ )
22
+
23
+
24
+ def probe(path: Path) -> dict:
25
+ with av.open(str(path)) as container:
26
+ video = next((stream for stream in container.streams if stream.type == "video"), None)
27
+ audio = next((stream for stream in container.streams if stream.type == "audio"), None)
28
+ metadata_keys = {key.lower() for key in container.metadata}
29
+ return {
30
+ "duration_s": round(float(container.duration / av.time_base), 6)
31
+ if container.duration
32
+ else None,
33
+ "size_bytes": path.stat().st_size,
34
+ "bit_rate": container.bit_rate,
35
+ "video_codec": video.codec_context.name if video else None,
36
+ "width": video.codec_context.width if video else None,
37
+ "height": video.codec_context.height if video else None,
38
+ "fps": round(float(video.average_rate), 6)
39
+ if video and video.average_rate
40
+ else None,
41
+ "video_frames": video.frames if video else None,
42
+ "has_audio": audio is not None,
43
+ "audio_codec": audio.codec_context.name if audio else None,
44
+ "audio_sample_rate": audio.codec_context.sample_rate if audio else None,
45
+ "audio_channels": audio.codec_context.channels if audio else None,
46
+ # Record privacy-risk flags without copying sensitive values such
47
+ # as coordinates or capture timestamps into the derived manifest.
48
+ "has_location_metadata": any("location" in key for key in metadata_keys),
49
+ "has_creation_time_metadata": any("creation" in key for key in metadata_keys),
50
+ "stream_types": [stream.type for stream in container.streams],
51
+ }
52
+
53
+
54
+ def parse_labels(path: Path) -> dict:
55
+ match = NAME_RE.fullmatch(path.stem)
56
+ if not match:
57
+ return {"parse_ok": False}
58
+ labels = match.groupdict()
59
+ trajectory = labels.pop("trajectory")
60
+ trial = labels.pop("trial")
61
+ trial_after_traj = labels.pop("trial_after_traj")
62
+ trial = trial or trial_after_traj
63
+ # The source naming is inconsistent: P01 uses Traj, P02 uses Trial, and
64
+ # P03 uses both. Preserve those semantics and expose only a neutral
65
+ # sequence index for balancing; do not assume that Trial means route.
66
+ sequence_index = int(trajectory or trial)
67
+ return {
68
+ "parse_ok": True,
69
+ **labels,
70
+ "trajectory_index": int(trajectory) if trajectory else None,
71
+ "trial_index": int(trial) if trial else None,
72
+ "sequence_index": sequence_index,
73
+ }
74
+
75
+
76
+ def main() -> None:
77
+ parser = argparse.ArgumentParser()
78
+ parser.add_argument("root", type=Path)
79
+ parser.add_argument("--output-dir", type=Path, required=True)
80
+ args = parser.parse_args()
81
+
82
+ paths = sorted(args.root.rglob("*.mp4"))
83
+ args.output_dir.mkdir(parents=True, exist_ok=True)
84
+ rows = []
85
+ failures = []
86
+ for path in paths:
87
+ relative_path = path.relative_to(args.root).as_posix()
88
+ row = {"id": path.stem, "relative_path": relative_path, **parse_labels(path)}
89
+ try:
90
+ row.update(probe(path))
91
+ except Exception as exc: # Keep a manifest row for corrupt/partial files.
92
+ row["probe_error"] = f"{type(exc).__name__}: {exc}"
93
+ failures.append(relative_path)
94
+ rows.append(row)
95
+
96
+ manifest_path = args.output_dir / "manifest.jsonl"
97
+ with manifest_path.open("w", encoding="utf-8") as handle:
98
+ for row in rows:
99
+ handle.write(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n")
100
+
101
+ labeled = [row for row in rows if row.get("parse_ok")]
102
+ summary = {
103
+ "root": str(args.root.resolve()),
104
+ "video_count": len(rows),
105
+ "parse_failures": [row["relative_path"] for row in rows if not row.get("parse_ok")],
106
+ "probe_failures": failures,
107
+ "total_size_bytes": sum(row.get("size_bytes", 0) for row in rows),
108
+ "total_duration_s": round(sum(row.get("duration_s") or 0 for row in rows), 6),
109
+ "participants": dict(sorted(Counter(row["participant"] for row in labeled).items())),
110
+ "activities": dict(sorted(Counter(row["activity"] for row in labeled).items())),
111
+ "lighting": dict(sorted(Counter(row["lighting"] for row in labeled).items())),
112
+ "sequence_indices": dict(
113
+ sorted(Counter(str(row["sequence_index"]) for row in labeled).items())
114
+ ),
115
+ "codecs": dict(sorted(Counter(row.get("video_codec") for row in rows).items(), key=str)),
116
+ "resolutions": dict(
117
+ sorted(Counter(f"{row.get('width')}x{row.get('height')}" for row in rows).items())
118
+ ),
119
+ "videos_with_audio": sum(bool(row.get("has_audio")) for row in rows),
120
+ "videos_with_location_metadata": sum(
121
+ bool(row.get("has_location_metadata")) for row in rows
122
+ ),
123
+ "videos_with_creation_time_metadata": sum(
124
+ bool(row.get("has_creation_time_metadata")) for row in rows
125
+ ),
126
+ }
127
+ (args.output_dir / "summary.json").write_text(
128
+ json.dumps(summary, ensure_ascii=False, indent=2, sort_keys=True) + "\n",
129
+ encoding="utf-8",
130
+ )
131
+ print(json.dumps(summary, ensure_ascii=False, indent=2, sort_keys=True))
132
+
133
+
134
+ if __name__ == "__main__":
135
+ main()
multi_video_cross_video_methodology/source_docs/pilot_scripts_20260824/download_gdrive_ranges.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Resume public Google Drive files through validated HTTP range requests.
3
+
4
+ This is a fallback for large shared files when the normal download endpoint
5
+ intermittently returns a quota HTML page. Chunks are accepted only when both
6
+ HTTP Content-Range and byte length match the request.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import os
14
+ import random
15
+ import re
16
+ import time
17
+ import urllib.error
18
+ import urllib.parse
19
+ import urllib.request
20
+ from concurrent.futures import ThreadPoolExecutor, as_completed
21
+ from pathlib import Path
22
+
23
+
24
+ CHUNK_SIZE = 16 * 1024 * 1024
25
+ CONTENT_RANGE_RE = re.compile(r"bytes (\d+)-(\d+)/(\d+)")
26
+
27
+
28
+ def drive_id(url: str) -> str:
29
+ values = urllib.parse.parse_qs(urllib.parse.urlparse(url).query).get("id")
30
+ if not values:
31
+ raise ValueError(f"No id in URL: {url}")
32
+ return values[0]
33
+
34
+
35
+ def request_range(file_id: str, start: int, end: int, attempts: int = 60) -> tuple[bytes, int]:
36
+ url = (
37
+ "https://drive.usercontent.google.com/download?"
38
+ + urllib.parse.urlencode({"id": file_id, "export": "download", "confirm": "t"})
39
+ )
40
+ expected = end - start + 1
41
+ last_error = "unknown"
42
+ for attempt in range(attempts):
43
+ request = urllib.request.Request(url, headers={"Range": f"bytes={start}-{end}"})
44
+ try:
45
+ with urllib.request.urlopen(request, timeout=90) as response:
46
+ data = response.read()
47
+ match = CONTENT_RANGE_RE.fullmatch(response.headers.get("Content-Range", ""))
48
+ if match:
49
+ got_start, got_end, total = map(int, match.groups())
50
+ if got_start == start and got_end == end and len(data) == expected:
51
+ return data, total
52
+ last_error = (
53
+ f"status={response.status} bytes={len(data)} "
54
+ f"content_range={response.headers.get('Content-Range')}"
55
+ )
56
+ except (OSError, urllib.error.URLError) as exc:
57
+ last_error = f"{type(exc).__name__}: {exc}"
58
+ delay = min(2.0, 0.25 * (attempt + 1)) + random.random()
59
+ time.sleep(delay)
60
+ raise RuntimeError(f"range {start}-{end} failed after {attempts} attempts: {last_error}")
61
+
62
+
63
+ def get_total(file_id: str) -> int:
64
+ _, total = request_range(file_id, 0, 0)
65
+ return total
66
+
67
+
68
+ def save_state(path: Path, completed: set[int]) -> None:
69
+ temporary = path.with_suffix(path.suffix + ".tmp")
70
+ temporary.write_text(json.dumps(sorted(completed)) + "\n", encoding="utf-8")
71
+ os.replace(temporary, path)
72
+
73
+
74
+ def download_one(root: Path, relative_path: str, file_id: str) -> str:
75
+ target = root / relative_path
76
+ target.parent.mkdir(parents=True, exist_ok=True)
77
+ total = get_total(file_id)
78
+ if target.exists() and target.stat().st_size == total:
79
+ return f"skip complete: {relative_path}"
80
+
81
+ part = target.with_suffix(target.suffix + ".part")
82
+ state = target.with_suffix(target.suffix + ".part.state.json")
83
+ if state.exists():
84
+ completed = set(json.loads(state.read_text(encoding="utf-8")))
85
+ else:
86
+ completed = set()
87
+ with part.open("wb") as handle:
88
+ handle.truncate(total)
89
+
90
+ chunk_count = (total + CHUNK_SIZE - 1) // CHUNK_SIZE
91
+ with part.open("r+b", buffering=0) as handle:
92
+ for index in range(chunk_count):
93
+ if index in completed:
94
+ continue
95
+ start = index * CHUNK_SIZE
96
+ end = min(total - 1, start + CHUNK_SIZE - 1)
97
+ data, reported_total = request_range(file_id, start, end)
98
+ if reported_total != total:
99
+ raise RuntimeError(
100
+ f"size changed for {relative_path}: {total} -> {reported_total}"
101
+ )
102
+ handle.seek(start)
103
+ handle.write(data)
104
+ completed.add(index)
105
+ save_state(state, completed)
106
+ print(f"{relative_path}: {len(completed)}/{chunk_count} chunks", flush=True)
107
+ os.fsync(handle.fileno())
108
+
109
+ if part.stat().st_size != total or len(completed) != chunk_count:
110
+ raise RuntimeError(f"incomplete file: {relative_path}")
111
+ os.replace(part, target)
112
+ state.unlink(missing_ok=True)
113
+ return f"complete: {relative_path} ({total} bytes)"
114
+
115
+
116
+ def main() -> None:
117
+ parser = argparse.ArgumentParser()
118
+ parser.add_argument("listing", type=Path)
119
+ parser.add_argument("root", type=Path)
120
+ parser.add_argument("--workers", type=int, default=2)
121
+ args = parser.parse_args()
122
+
123
+ entries = json.loads(args.listing.read_text(encoding="utf-8"))
124
+ jobs = [(entry["path"], drive_id(entry["url"])) for entry in entries]
125
+ failures = []
126
+ with ThreadPoolExecutor(max_workers=args.workers) as executor:
127
+ futures = {
128
+ executor.submit(download_one, args.root, relative_path, file_id): relative_path
129
+ for relative_path, file_id in jobs
130
+ }
131
+ for future in as_completed(futures):
132
+ relative_path = futures[future]
133
+ try:
134
+ print(future.result(), flush=True)
135
+ except Exception as exc:
136
+ failures.append(relative_path)
137
+ print(f"FAILED {relative_path}: {exc}", flush=True)
138
+ if failures:
139
+ raise SystemExit(f"{len(failures)} downloads failed")
140
+
141
+
142
+ if __name__ == "__main__":
143
+ main()
multi_video_cross_video_methodology/source_docs/pilot_scripts_20260824/make_contact_sheet.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Extract evenly spaced frames from one or more videos into a contact sheet."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ from pathlib import Path
8
+
9
+ import av
10
+ from PIL import Image, ImageDraw
11
+
12
+
13
+ def sample_frames(path: Path, positions: tuple[float, ...]) -> list[tuple[float, Image.Image]]:
14
+ results = []
15
+ with av.open(str(path)) as container:
16
+ duration_s = float(container.duration / av.time_base)
17
+ stream = container.streams.video[0]
18
+ for position in positions:
19
+ target_s = duration_s * position
20
+ timestamp = int(target_s / float(stream.time_base))
21
+ container.seek(timestamp, stream=stream, backward=True)
22
+ frame = next(container.decode(stream))
23
+ results.append((target_s, frame.to_image()))
24
+ return results
25
+
26
+
27
+ def main() -> None:
28
+ parser = argparse.ArgumentParser()
29
+ parser.add_argument("videos", type=Path, nargs="+")
30
+ parser.add_argument("--output", type=Path, required=True)
31
+ parser.add_argument(
32
+ "--positions",
33
+ default="0.1,0.5,0.9",
34
+ help="Comma-separated relative positions from 0 to 1.",
35
+ )
36
+ args = parser.parse_args()
37
+
38
+ positions = tuple(float(value) for value in args.positions.split(","))
39
+ if not positions or any(value < 0 or value > 1 for value in positions):
40
+ raise ValueError("positions must be between 0 and 1")
41
+ tile_size = (480, 270)
42
+ label_height = 40
43
+ canvas = Image.new(
44
+ "RGB", (tile_size[0] * len(positions), (tile_size[1] + label_height) * len(args.videos)), "white"
45
+ )
46
+ draw = ImageDraw.Draw(canvas)
47
+ for row, path in enumerate(args.videos):
48
+ for column, (target_s, frame) in enumerate(sample_frames(path, positions)):
49
+ frame.thumbnail(tile_size)
50
+ x = column * tile_size[0]
51
+ y = row * (tile_size[1] + label_height)
52
+ canvas.paste(frame, (x, y))
53
+ draw.text((x + 6, y + tile_size[1] + 6), f"{path.name} @ {target_s:.1f}s", fill="black")
54
+ args.output.parent.mkdir(parents=True, exist_ok=True)
55
+ canvas.save(args.output, quality=90)
56
+
57
+
58
+ if __name__ == "__main__":
59
+ main()
multi_video_cross_video_methodology/source_docs/repair_segment_distractors.py ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Rebuild segment-question distractors as near-misses, and measure whether it worked.
3
+
4
+ A blind model scores 48.6% on this corpus (801-question sample, 95% CI [45.1, 52.0]),
5
+ and 41.6% of the time it agrees with itself three times out of three. Reading the
6
+ questions it beats shows two construction faults, both downstream of the original
7
+ rule -- "DEFINITIVELY CONTRADICTED by the evidence":
8
+
9
+ 1. The correct option is the most specific one. Distractors name generic props
10
+ ("a yellow school bus"), the answer reports what was actually seen ("a white van
11
+ among parked vehicles and a large dark trash dumpster"). Pick the longest, most
12
+ detailed option and you are usually right.
13
+ 2. Distractors are impossible rather than merely false. Asked what signals the
14
+ wearer's movement, the wrong options offer engine noise and a dashboard view --
15
+ ruled out by knowing this is a first-person running video, no watching required.
16
+
17
+ "Contradicted" guarantees an option is wrong. It does not guarantee it is tempting.
18
+ So this regenerates distractors as near-misses of the answer itself -- same objects and
19
+ actions, one attribute changed -- with the length band the full-video pipeline enforces
20
+ (where the same blind test scores 7.3% on 8-option multi against this corpus's 27.8%).
21
+
22
+ The gold option's text is never touched, only the distractors around it.
23
+
24
+ Usage: repair_segment_distractors.py --pilot 250 (repair, then blind-test)
25
+ repair_segment_distractors.py --all
26
+ """
27
+ import argparse
28
+ import collections
29
+ import concurrent.futures
30
+ import glob
31
+ import hashlib
32
+ import importlib.util
33
+ import json
34
+ import math
35
+ import os
36
+ import random
37
+ import re
38
+ import sys
39
+ import threading
40
+ from pathlib import Path
41
+
42
+ BASE = Path("/mnt/task_runtime/bolt/gdrive_relay")
43
+ SEG_ROOT = "/mnt/data/data_anno/runningbench_qa_expansion/annotations_60s"
44
+ OUT = Path("/mnt/data/data_anno/runningbench_segment_repair")
45
+ QUOTA_PER_SECOND = 0.45
46
+ SEED = 20260831
47
+
48
+ REPAIR_PROMPT = """Rewrite the WRONG options of one benchmark question about a 60-second first-person
49
+ walking/running video. The correct option is fixed — never change, paraphrase or restate it.
50
+
51
+ EVIDENCE (the only ground truth):
52
+ {evidence}
53
+
54
+ QUESTION: {question}
55
+ CORRECT OPTION(S), verbatim and unchangeable:
56
+ {correct}
57
+
58
+ Write exactly {n} wrong options, and treat the whole SET as the thing you are designing.
59
+
60
+ The trap to avoid, above everything else: if every wrong option is the correct one with a
61
+ single detail edited, then on each detail the correct value is the majority value, and the
62
+ answer can be recovered by taking the most common colour, the most common count, the most
63
+ common side — no video needed. A set like this is worthless:
64
+
65
+ dark grey / multi-story / glass light yellow / single-story / glass
66
+ light yellow / multi-story / glass <-- correct, and the majority on every axis
67
+ dark red / multi-story / glass light yellow / multi-story / wooden
68
+
69
+ So:
70
+ - Change TWO OR MORE details at once in most wrong options, and change different combinations
71
+ in different options. No detail of the correct option may appear in more than half the set.
72
+ - Make the wrong options near-misses OF EACH OTHER too, not only of the correct one. A reader
73
+ who cannot see the video must find no option more "central" or more self-consistent than
74
+ the others.
75
+ - Stay inside the world of this video. A wrong option that a person rules out just by knowing
76
+ this is a first-person walking/running recording is useless: no dashboards, no engine noise,
77
+ no indoor scenes unless the evidence has them.
78
+ - Be CONTRADICTED by the evidence: it must positively rule the option out. Not merely
79
+ unmentioned, not partly true.
80
+ - Match the correct option's specificity and length: between {lo} and {hi} characters, and the
81
+ correct option must not be the longest or the most detailed one in the set.
82
+
83
+ Return only: {{"options": ["...", "..."]}}
84
+
85
+ Each option is ONE plain string in that array. Do not prefix them with "-" or a bullet,
86
+ do not put a newline inside one, and do not pack several options into a single string —
87
+ returning the whole list as one item is the most common way this call fails."""
88
+
89
+ VERIFY_PROMPT = """Judge each numbered statement against the evidence from a first-person video segment.
90
+
91
+ EVIDENCE:
92
+ {evidence}
93
+
94
+ STATEMENTS:
95
+ {statements}
96
+
97
+ Answer strictly per statement:
98
+ - "contradicted" if the evidence positively rules it out;
99
+ - "supported" if the evidence indicates it is true;
100
+ - "unclear" if the evidence neither confirms nor rules it out.
101
+
102
+ Return only: {{"verdicts": ["contradicted", "unclear", ...]}}"""
103
+
104
+
105
+ def wilson(k, n, z=1.96):
106
+ if not n:
107
+ return (0.0, 0.0)
108
+ p = k / n
109
+ d = 1 + z * z / n
110
+ c = p + z * z / (2 * n)
111
+ h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n))
112
+ return (100 * (c - h) / d, 100 * (c + h) / d)
113
+
114
+
115
+ def load(name, path):
116
+ spec = importlib.util.spec_from_file_location(name, path)
117
+ mod = importlib.util.module_from_spec(spec)
118
+ spec.loader.exec_module(mod)
119
+ return mod
120
+
121
+
122
+ def clean_option(o):
123
+ """Strip a markdown bullet if the model wrapped its list items in one."""
124
+ return re.sub(r"^\s*[-*\u2022]\s+", "", o).strip() if isinstance(o, str) else o
125
+
126
+
127
+ def make_repair_validator(n, lo, hi, correct):
128
+ gold = {c.strip().lower() for c in correct}
129
+
130
+ def check(d):
131
+ opts = d.get("options")
132
+ if not isinstance(opts, list) or len(opts) != n:
133
+ raise ValueError(f"need exactly {n} options, got {len(opts) if isinstance(opts, list) else '?'}")
134
+ # Normalise in place so the caller sees cleaned text, not the bulleted form.
135
+ d["options"] = opts = [clean_option(o) for o in opts]
136
+ seen = set()
137
+ for o in opts:
138
+ if not isinstance(o, str) or not o.strip():
139
+ raise ValueError("options must be non-empty strings")
140
+ if "\n" in o:
141
+ raise ValueError("one option per string; this one contains a newline")
142
+ key = o.strip().lower()
143
+ if key in gold:
144
+ raise ValueError("a wrong option repeats the correct option")
145
+ if key in seen:
146
+ raise ValueError("duplicate options")
147
+ seen.add(key)
148
+ if not (lo * 0.8 <= len(o) <= hi * 1.25):
149
+ raise ValueError(f"option length {len(o)} outside {int(lo)}..{int(hi)}: {o[:40]!r}")
150
+ return check
151
+
152
+
153
+ def make_verdict_validator(n):
154
+ def check(d):
155
+ v = d.get("verdicts")
156
+ if not isinstance(v, list) or len(v) != n:
157
+ raise ValueError(f"need {n} verdicts")
158
+ for x in v:
159
+ if x not in ("contradicted", "supported", "unclear"):
160
+ raise ValueError(f"bad verdict {x!r}")
161
+ return check
162
+
163
+
164
+ def shuffle(item):
165
+ keys = sorted(item["options"])
166
+ texts = [item["options"][k] for k in keys]
167
+ correct = {keys.index(k) for k in item["answer"]}
168
+ order = list(range(len(texts)))
169
+ random.Random(hashlib.sha256(item["question"].encode("utf-8")).hexdigest()).shuffle(order)
170
+ item["options"] = {chr(ord("A") + i): texts[src] for i, src in enumerate(order)}
171
+ item["answer"] = sorted(chr(ord("A") + i) for i, src in enumerate(order) if src in correct)
172
+
173
+
174
+ def collect():
175
+ rows = []
176
+ for path in sorted(glob.glob(f"{SEG_ROOT}/**/*.json", recursive=True)):
177
+ try:
178
+ rec = json.load(open(path))
179
+ except Exception:
180
+ continue
181
+ ev = rec.get("dense_annotations") or rec.get("annotation_raw")
182
+ for idx, item in enumerate(rec.get("qa_pairs") or []):
183
+ o, a = item.get("options"), item.get("answer")
184
+ if isinstance(o, dict) and o and isinstance(a, list) and a:
185
+ rows.append({"file": path, "index": idx, "evidence": ev, "item": item})
186
+ return rows
187
+
188
+
189
+ def main():
190
+ ap = argparse.ArgumentParser()
191
+ ap.add_argument("--pilot", type=int, default=0, help="repair a stratified sample and blind-test it")
192
+ ap.add_argument("--all", action="store_true")
193
+ ap.add_argument("--multi-only", action="store_true",
194
+ help="repair only multi-answer questions. Single-choice sits at 65.2%% blind "
195
+ "before repair and 54.5%% after, so rebuilding it buys a corpus that is "
196
+ "still unusable; multi-answer runs 27.8%% -> 21.1%% from a far better start.")
197
+ ap.add_argument("--no-blind", action="store_true", help="repair only; leave the gates to a local model")
198
+ # A repair call takes ~11 s, so one worker issues only ~0.13 req/s against a 0.45 req/s
199
+ # quota -- the run is latency-bound, not quota-bound. Three workers fill the quota
200
+ # without exceeding it; the shared RateLimiter still serialises every attempt.
201
+ ap.add_argument("--jobs", type=int, default=3)
202
+ ap.add_argument("--out", default=str(OUT / "pilot.json"))
203
+ a = ap.parse_args()
204
+ if not (a.pilot or a.all):
205
+ ap.error("pass --pilot N or --all")
206
+
207
+ fv = load("fv", BASE / "build_fullvideo_annotations.py")
208
+ gen = load("gen", BASE / "repair_runningbench_annotations.py")
209
+
210
+ rows = collect()
211
+ print(f"corpus: {len(rows)} objective questions", flush=True)
212
+ if a.multi_only:
213
+ rows = [r for r in rows if len(r["item"]["answer"]) > 1]
214
+ print(f"multi-answer only: {len(rows)}", flush=True)
215
+ rng = random.Random(SEED)
216
+ if a.pilot:
217
+ strata = collections.defaultdict(list)
218
+ for r in rows:
219
+ strata[(len(r["item"]["options"]), len(r["item"]["answer"]) > 1)].append(r)
220
+ sample = []
221
+ for key, group in sorted(strata.items()):
222
+ take = max(1, round(a.pilot * len(group) / len(rows)))
223
+ rng.shuffle(group)
224
+ sample += group[:take]
225
+ rng.shuffle(sample)
226
+ rows = sample
227
+ print(f"pilot sample: {len(rows)}", flush=True)
228
+
229
+ api = gen.Floodgate("")
230
+ api.session = fv.PacedSession(api.session, fv.RateLimiter(QUOTA_PER_SECOND))
231
+
232
+ OUT.mkdir(parents=True, exist_ok=True)
233
+ repaired, results = [], []
234
+ # Resume: a 4-hour run should not restart from zero after an interruption.
235
+ done_keys = set()
236
+ if os.path.exists(a.out):
237
+ try:
238
+ prev = json.load(open(a.out))
239
+ repaired = prev.get("repaired", [])
240
+ results = prev.get("blind", [])
241
+ done_keys = {(r["file"], r["index"]) for r in repaired}
242
+ print(f"resuming: {len(done_keys)} already repaired", flush=True)
243
+ except Exception:
244
+ print("could not read previous output; starting fresh", flush=True)
245
+ rows = [r for r in rows if (r["file"], r["index"]) not in done_keys]
246
+ print(f"to do: {len(rows)}", flush=True)
247
+
248
+ lock = threading.Lock()
249
+ counter = {"n": 0}
250
+
251
+ def work(r):
252
+ item = json.loads(json.dumps(r["item"]))
253
+ keys = sorted(item["options"])
254
+ # One question in 8,148 has an answer letter with no matching option -- the
255
+ # generator emitted a literal "..." as an option key. Skip it rather than take
256
+ # the whole run down; a KeyError inside a pool worker kills every other thread.
257
+ absent = [k for k in item["answer"] if k not in item["options"]]
258
+ if absent:
259
+ return None, f"malformed: answer {absent} has no option (keys={keys})"
260
+ correct = [item["options"][k] for k in item["answer"]]
261
+ wrong_n = len(keys) - len(correct)
262
+ clen = [len(c) for c in correct]
263
+ lo, hi = min(clen) * 0.75, max(clen) * 1.05
264
+ try:
265
+ data = gen.generate_valid_json(
266
+ api,
267
+ REPAIR_PROMPT.format(evidence=json.dumps(r["evidence"], ensure_ascii=False),
268
+ question=item["question"],
269
+ correct="\n".join(f"- {c}" for c in correct),
270
+ n=wrong_n, lo=int(lo), hi=int(hi)),
271
+ make_repair_validator(wrong_n, lo, hi, correct), 8192)
272
+ new_wrong = data["options"]
273
+ verdicts = gen.generate_valid_json(
274
+ api,
275
+ VERIFY_PROMPT.format(evidence=json.dumps(r["evidence"], ensure_ascii=False),
276
+ statements="\n".join(f"{j+1}. {o}" for j, o in enumerate(new_wrong))),
277
+ make_verdict_validator(wrong_n), 4096)["verdicts"]
278
+ except Exception as exc:
279
+ return None, f"{type(exc).__name__}: {exc}"
280
+ # Keep only distractors the evidence positively rules out; fall back to the
281
+ # original wording for the rest rather than shipping an unverified option.
282
+ old_wrong = [item["options"][k] for k in keys if k not in item["answer"]]
283
+ kept = [o for o, v in zip(new_wrong, verdicts) if v == "contradicted"]
284
+ final_wrong = kept + old_wrong[len(kept):]
285
+ texts = correct + final_wrong
286
+ item["options"] = {chr(ord("A") + j): t for j, t in enumerate(texts)}
287
+ item["answer"] = [chr(ord("A") + j) for j in range(len(correct))]
288
+ shuffle(item)
289
+ item["distractors_rebuilt"] = len(kept)
290
+ if {item["options"][k] for k in item["answer"]} != set(correct):
291
+ return None, "gold text changed"
292
+ return {"file": r["file"], "index": r["index"], "item": item}, None
293
+
294
+ with concurrent.futures.ThreadPoolExecutor(max_workers=a.jobs) as pool:
295
+ for out_row, err in pool.map(work, rows):
296
+ with lock:
297
+ counter["n"] += 1
298
+ i = counter["n"]
299
+ if err:
300
+ print(f" !! {i}: {err}", flush=True)
301
+ else:
302
+ repaired.append(out_row)
303
+ if i % 20 == 0 or i == len(rows):
304
+ print(f" {i}/{len(rows)} repaired {len(repaired)}", flush=True)
305
+ json.dump({"repaired": repaired, "blind": results},
306
+ open(a.out, "w"), ensure_ascii=False)
307
+
308
+ json.dump({"repaired": repaired, "blind": results}, open(a.out, "w"), ensure_ascii=False)
309
+ print(f"\nrepaired {len(repaired)}/{len(rows)} -> {a.out}")
310
+ if results:
311
+ k, n = sum(1 for x in results if x["guessable"]), len(results)
312
+ lo, hi = wilson(k, n)
313
+ print(f"\n=== blind-guess after repair ===")
314
+ print(f"overall {k}/{n} = {100*k/n:.1f}% 95% CI [{lo:.1f}, {hi:.1f}] (before: 48.6% [45.1, 52.0])")
315
+ for key, label in (((6, False), "6-option single"), ((8, True), "8-option multi")):
316
+ s = [x for x in results if (x["n_opt"], x["n_ans"] > 1) == key]
317
+ if s:
318
+ kk = sum(1 for x in s if x["guessable"])
319
+ l, h = wilson(kk, len(s))
320
+ print(f"{label:18s}{kk}/{len(s)} = {100*kk/len(s):.1f}% [{l:.1f}, {h:.1f}]")
321
+ print("before: 6-option single 65.2%, 8-option multi 27.8%")
322
+
323
+
324
+ if __name__ == "__main__":
325
+ sys.exit(main())