futurefantasy commited on
Commit
3645b58
·
verified ·
1 Parent(s): c768a2e

Restructure benchmark release

Browse files

Move split files to splits/*.json, keep video archives on the Hub, and move evaluation code/docs to GitHub.

.gitattributes CHANGED
@@ -73,3 +73,8 @@ benchmark_splits/test_expert_seen/video_progress_benchmark_file.json filter=lfs
73
  benchmark_splits/test_expert_unseen/video_progress_benchmark_file.json filter=lfs diff=lfs merge=lfs -text
74
  benchmark_splits/test_nonexpert_seen/video_progress_benchmark_file.json filter=lfs diff=lfs merge=lfs -text
75
  benchmark_splits/test_nonexpert_unseen/video_progress_benchmark_file.json filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
73
  benchmark_splits/test_expert_unseen/video_progress_benchmark_file.json filter=lfs diff=lfs merge=lfs -text
74
  benchmark_splits/test_nonexpert_seen/video_progress_benchmark_file.json filter=lfs diff=lfs merge=lfs -text
75
  benchmark_splits/test_nonexpert_unseen/video_progress_benchmark_file.json filter=lfs diff=lfs merge=lfs -text
76
+ splits/train.json filter=lfs diff=lfs merge=lfs -text
77
+ splits/test_expert_seen.json filter=lfs diff=lfs merge=lfs -text
78
+ splits/test_expert_unseen.json filter=lfs diff=lfs merge=lfs -text
79
+ splits/test_nonexpert_seen.json filter=lfs diff=lfs merge=lfs -text
80
+ splits/test_nonexpert_unseen.json filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ TODO: replace this file with the final Video Progress Benchmark dataset license before public release.
2
+
3
+ Do not publish this dataset repository until the license text and usage restrictions have been finalized.
README.md CHANGED
@@ -14,11 +14,11 @@ license: other
14
 
15
  **A video-language benchmark for process-level robot task progress estimation.**
16
 
17
- [Code](https://github.com/InternRobotics/VLAC-cut) · [Paper](<PAPER_URL>) · [VLAC-Cut Model](https://huggingface.co/InternRobotics/VLAC-Cut)
18
 
19
- The **Video Progress Benchmark (VPB)** evaluates whether a model can estimate how a robot task evolves throughout a videonot only whether the final frame looks successful. VPB is built from the held-out portion of the **Progress Annotation Dataset** and explicitly tests advancement, stagnation, regression, and recovery.
20
 
21
- This release provides the official split files, the raw-video subset required by the benchmark protocol, frame-extraction utilities, and scripts for reproducible VLAC-Cut inference and metric computation.
22
 
23
  ## Why VPB?
24
 
@@ -59,148 +59,69 @@ VPB is organized along two axes:
59
 
60
  All views from the same physical execution are assigned to the same split. Held-out progress annotations are excluded from prompt construction, augmentation, in-context demonstration selection, fine-tuning, and checkpoint selection.
61
 
62
- ## Evaluation Protocol
63
 
64
  Annotated semantic keyframes are converted into a canonical reference trajectory by piecewise-linear interpolation. This interpolation is an evaluation convention; it does not assume that physical progress changes linearly between events.
65
 
66
  - global and terminal metrics are computed on the official `1 Hz` evaluation grid;
67
  - local direction metrics are computed directly on adjacent annotated semantic anchors;
68
  - global metrics are first computed per record and then averaged over metric-valid records, preventing long videos from dominating the result;
69
- - prediction coverage is strict by default: missing curve points, terminal predictions, or local-direction anchor predictions stop evaluation unless `--allow-missing` is explicitly used for diagnostics.
70
 
71
  ### Metrics
72
 
73
  | Scope | Metrics | What they measure |
74
  |---|---|---|
75
  | Global trajectory | MAE, PRC, VOC | Absolute calibration and ordering of progress states; VOC is reported only for expert trajectories |
76
- | Terminal state | TSA, successful F1, failed/incomplete F1, Macro-F1 | Whether the final state is complete using the common ` 90` threshold |
77
- | Local direction | AP+, AP, MacroAP | Whether adjacent semantic events are correctly ranked as improvement or regression |
78
 
79
  ## Repository Contents
80
 
81
  ```text
82
- benchmark_splits/
83
- train/video_progress_benchmark_file.json
84
- test_expert_seen/video_progress_benchmark_file.json
85
- test_expert_unseen/video_progress_benchmark_file.json
86
- test_nonexpert_seen/video_progress_benchmark_file.json
87
- test_nonexpert_unseen/video_progress_benchmark_file.json
88
-
89
- scripts/
90
- unpack_data.sh
91
- extract_vlac2_release_frames.py
92
- build_vlac_cut_eval_manifest.py
93
- run_vlac_cut_batch.py
94
- evaluate_vpb_predictions.py
95
- vlac2_release_common.py
96
- vpb_public_eval_utils.py
97
-
98
- docs/
99
- evaluate_vlac_cut_on_vpb.md
100
 
101
  data/
102
  train_videos.tar
103
  test_videos.tar
104
- ```
105
-
106
- ## Quick Start
107
-
108
- ### 1. Unpack the video archives
109
 
110
- ```bash
111
- bash scripts/unpack_data.sh
 
112
  ```
113
 
114
- By default, the archives are extracted under `data/`. To use another location:
115
-
116
- ```bash
117
- bash scripts/unpack_data.sh /path/to/data
118
- ```
119
-
120
- ### 2. Extract benchmark frames
121
-
122
- ```bash
123
- python scripts/extract_vlac2_release_frames.py \
124
- --data-root /path/to/data \
125
- --frames-root /path/to/data_extracted_frames
126
- ```
127
 
128
- The script extracts the benchmark main-view frames. If `--frames-root` is omitted, frames are written to `_extracted_frames/` under the release directory.
129
 
130
- The canonical split JSON files use the path prefix:
131
 
132
  ```text
133
  __VLAC2_FRAMES_ROOT__/
134
  ```
135
 
136
- Resolve this prefix to the absolute extracted-frame directory. For example:
137
 
138
- ```text
139
- __VLAC2_FRAMES_ROOT__/episode/frame.jpg
140
- ```
141
 
142
- becomes:
143
-
144
- ```text
145
- /path/to/data_extracted_frames/episode/frame.jpg
146
- ```
147
-
148
- ### 3. Build the VLAC-Cut evaluation manifest
149
 
150
  ```bash
151
- python scripts/build_vlac_cut_eval_manifest.py \
152
- --benchmark-root benchmark_splits \
153
- --frames-root /path/to/data_extracted_frames \
154
- --out manifests/vlac_cut_vpb_eval.jsonl
155
- ```
156
 
157
- For the reported VLAC-Cut evaluation, the manifest samples model-input frames at `2 Hz`, stores the public `1 Hz` evaluation frames, and materializes the exact `chunk_all` prompt in `vlac_cut_prompt`.
158
-
159
- The `2 Hz` input rate is a VLAC-Cut inference choice, not a benchmark-wide requirement. Official metrics are computed on the released `1 Hz` evaluation grid.
160
-
161
- ### 4. Run VLAC-Cut batch inference
162
-
163
- Download or clone the model release from `InternRobotics/VLAC-Cut`, then run:
164
-
165
- ```bash
166
- python scripts/run_vlac_cut_batch.py \
167
- --model-path /path/to/VLAC-Cut \
168
- --manifest manifests/vlac_cut_vpb_eval.jsonl \
169
- --out predictions/vlac_cut_predictions.jsonl
170
- ```
171
-
172
- Each prediction row uses the following schema:
173
-
174
- ```json
175
- {
176
- "global_episode_id": "...",
177
- "frames": [65, 80, 95],
178
- "response": "时间: 0.0s, 进度: 0%\n时间: 1.0s, 进度: 50%"
179
- }
180
- ```
181
-
182
- Keep the manifest's original `frames` list in each trajectory-level prediction. The evaluator maps predictions by original frame ID and scores only the official `eval_frames`.
183
-
184
- ### 5. Evaluate predictions
185
-
186
- ```bash
187
  python scripts/evaluate_vpb_predictions.py \
188
- --benchmark-root benchmark_splits \
189
  --predictions predictions/vlac_cut_predictions.jsonl \
190
  --out-json reports/vlac_cut_vpb_eval.json \
191
  --out-md reports/vlac_cut_vpb_eval.md
192
  ```
193
 
194
- The evaluator reports:
195
-
196
- - global progress metrics for the four-bucket overall split and each individual bucket;
197
- - terminal metrics for four-bucket overall, seen merged, and unseen merged;
198
- - local direction AP for four-bucket overall, seen merged, and unseen merged.
199
-
200
- By default, the evaluator requires complete predictions for all selected benchmark records. Use `--allow-missing` only when you intentionally want a diagnostic report with coverage and missing-count fields.
201
-
202
- See `docs/evaluate_vlac_cut_on_vpb.md` for accepted prediction formats and complete metric definitions.
203
-
204
  ## Citation
205
 
206
  Please replace the placeholder below with the final paper BibTeX before public release.
 
14
 
15
  **A video-language benchmark for process-level robot task progress estimation.**
16
 
17
+ [Code](https://github.com/InternRobotics/VLAC-Cut) · [Paper](<PAPER_URL>) · [VLAC-Cut Model](https://huggingface.co/InternRobotics/VLAC-Cut)
18
 
19
+ The **Video Progress Benchmark (VPB)** evaluates whether a model can estimate how a robot task evolves throughout a video, not only whether the final frame looks successful. VPB is built from the held-out portion of the **Progress Annotation Dataset** and explicitly tests advancement, stagnation, regression, and recovery.
20
 
21
+ This release provides the official split files and the raw-video subset required by the benchmark. Frame extraction, VLAC-Cut inference, and metric computation scripts are maintained in the GitHub repository.
22
 
23
  ## Why VPB?
24
 
 
59
 
60
  All views from the same physical execution are assigned to the same split. Held-out progress annotations are excluded from prompt construction, augmentation, in-context demonstration selection, fine-tuning, and checkpoint selection.
61
 
62
+ ## Evaluation Setup
63
 
64
  Annotated semantic keyframes are converted into a canonical reference trajectory by piecewise-linear interpolation. This interpolation is an evaluation convention; it does not assume that physical progress changes linearly between events.
65
 
66
  - global and terminal metrics are computed on the official `1 Hz` evaluation grid;
67
  - local direction metrics are computed directly on adjacent annotated semantic anchors;
68
  - global metrics are first computed per record and then averaged over metric-valid records, preventing long videos from dominating the result;
69
+ - prediction coverage is strict by default in the public evaluator.
70
 
71
  ### Metrics
72
 
73
  | Scope | Metrics | What they measure |
74
  |---|---|---|
75
  | Global trajectory | MAE, PRC, VOC | Absolute calibration and ordering of progress states; VOC is reported only for expert trajectories |
76
+ | Terminal state | TSA, successful F1, failed/incomplete F1, Macro-F1 | Whether the final state is complete using the common `>= 90` threshold |
77
+ | Local direction | AP+, AP-, MacroAP | Whether adjacent semantic events are correctly ranked as improvement or regression |
78
 
79
  ## Repository Contents
80
 
81
  ```text
82
+ splits/
83
+ train.json
84
+ test_expert_seen.json
85
+ test_expert_unseen.json
86
+ test_nonexpert_seen.json
87
+ test_nonexpert_unseen.json
 
 
 
 
 
 
 
 
 
 
 
 
88
 
89
  data/
90
  train_videos.tar
91
  test_videos.tar
 
 
 
 
 
92
 
93
+ checksums.sha256
94
+ LICENSE
95
+ THIRD_PARTY_LICENSES.md
96
  ```
97
 
98
+ ## Data Format
 
 
 
 
 
 
 
 
 
 
 
 
99
 
100
+ Each split file is a JSON list. Each record includes the trajectory id, task metadata, frame index, dense progress values, semantic anchors, and optional reference context.
101
 
102
+ The split files use the portable frame prefix:
103
 
104
  ```text
105
  __VLAC2_FRAMES_ROOT__/
106
  ```
107
 
108
+ Resolve this prefix to the absolute extracted-frame directory when running the GitHub tools.
109
 
110
+ ## Evaluation Code
 
 
111
 
112
+ Detailed running commands and the complete metric implementation are provided in the GitHub repository:
 
 
 
 
 
 
113
 
114
  ```bash
115
+ git clone https://github.com/InternRobotics/VLAC-Cut
116
+ cd VLAC-Cut
 
 
 
117
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  python scripts/evaluate_vpb_predictions.py \
119
+ --benchmark-root /path/to/VLAC-Cut-Benchmark/splits \
120
  --predictions predictions/vlac_cut_predictions.jsonl \
121
  --out-json reports/vlac_cut_vpb_eval.json \
122
  --out-md reports/vlac_cut_vpb_eval.md
123
  ```
124
 
 
 
 
 
 
 
 
 
 
 
125
  ## Citation
126
 
127
  Please replace the placeholder below with the final paper BibTeX before public release.
THIRD_PARTY_LICENSES.md ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Third-Party Licenses
2
+
3
+ TODO: list all third-party source datasets, video sources, base annotations, and their required notices before public release.
checksums.sha256 ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ 43c916c9b0c6003b454602743801dd5bbc8e1ebe041d55bcb72373b589ae4951 splits/test_expert_seen.json
2
+ 0a8c7de51a3acaceecfaf14abaf7c97d981c37c8088db54f8ecebeb83afe94d5 splits/test_expert_unseen.json
3
+ 1599d10d8d9b144151aaea1675824dcf58100153a0478576c32b825c10c98c3c splits/test_nonexpert_seen.json
4
+ 73797d1b2869177b10f004ad44b2da14273b7d75ee42cbd1c65e4c000d1965ea splits/test_nonexpert_unseen.json
5
+ ae2ac3b1966872bac2a372335e0465b2b3ac7f14ec07ac33c4583a0e48537f95 splits/train.json
6
+ 318f5eef73d9d6786494ced97be1999973fafbb75306e56fbbc5176f8c3b4670 data/test_videos.tar
7
+ 5cb8ba8a6886678c41a7b3345388448c5a279171b0f09cf16d07802d74d2a4a3 data/train_videos.tar
docs/evaluate_vlac_cut_on_vpb.md DELETED
@@ -1,203 +0,0 @@
1
- # Evaluating VLAC-Cut on Video-Progress Benchmark
2
-
3
- This document describes the public VLAC-Cut evaluation workflow for
4
- Video-Progress Benchmark. It uses only this benchmark release plus the separate
5
- VLAC-Cut model release at <https://huggingface.co/InternRobotics/VLAC-Cut>.
6
-
7
- ## Evaluation Scope
8
-
9
- The benchmark metrics are computed on the released 1Hz evaluation frames
10
- reconstructed from each dense video timeline:
11
-
12
- - split scope: `test_expert_seen`, `test_expert_unseen`,
13
- `test_nonexpert_seen`, `test_nonexpert_unseen`
14
- - view scope: the `metadata.main_path` view only
15
- - evaluation points: `--eval-points time_hz --sample-hz 1.0`
16
- - global progress metrics: `MAE`, `PRC`, and `VOC` for expert bucket rows
17
- - terminal metrics: final progress threshold `90%`
18
- - local direction metrics: `AP+`, `AP-`, and `MacroAP_D` on adjacent
19
- `semantic_anchors` with `tau=0`
20
- - coverage requirement: complete predictions are required by default; use
21
- `--allow-missing` only to produce a diagnostic report for incomplete runs
22
-
23
- For VLAC-Cut evaluation we feed the model frames sampled at 2Hz. This 2Hz input
24
- rate is a VLAC-Cut evaluation setting, not a benchmark-wide protocol
25
- requirement. The evaluator maps VLAC-Cut outputs back to original frame ids and
26
- computes metrics on the public 1Hz evaluation frames.
27
-
28
- ## Workflow
29
-
30
- VLAC-Cut inference requires the model release environment: `torch`,
31
- `transformers` with `Qwen3VLMoeForConditionalGeneration` support, and enough GPU
32
- memory for the 30B checkpoint. The benchmark-side frame extraction, manifest
33
- building, and evaluation scripts are included in this release.
34
-
35
- Unpack videos:
36
-
37
- ```bash
38
- bash scripts/unpack_data.sh /path/to/data
39
- ```
40
-
41
- Extract benchmark frames:
42
-
43
- ```bash
44
- python scripts/extract_vlac2_release_frames.py \
45
- --data-root /path/to/data \
46
- --frames-root /path/to/frames
47
- ```
48
-
49
- Build the VLAC-Cut evaluation manifest:
50
-
51
- ```bash
52
- python scripts/build_vlac_cut_eval_manifest.py \
53
- --benchmark-root benchmark_splits \
54
- --frames-root /path/to/frames \
55
- --out manifests/vlac_cut_vpb_eval.jsonl
56
- ```
57
-
58
- Run VLAC-Cut batch inference:
59
-
60
- ```bash
61
- python scripts/run_vlac_cut_batch.py \
62
- --model-path /path/to/VLAC-Cut \
63
- --manifest manifests/vlac_cut_vpb_eval.jsonl \
64
- --out predictions/vlac_cut_predictions.jsonl
65
- ```
66
-
67
- Evaluate the batch predictions:
68
-
69
- ```bash
70
- python scripts/evaluate_vpb_predictions.py \
71
- --benchmark-root benchmark_splits \
72
- --predictions predictions/vlac_cut_predictions.jsonl \
73
- --out-json reports/vlac_cut_vpb_eval.json \
74
- --out-md reports/vlac_cut_vpb_eval.md
75
- ```
76
-
77
- ## Manifest Fields
78
-
79
- Each trajectory-level manifest row contains the fields needed by the batch
80
- inference script:
81
-
82
- - `global_episode_id`: episode key used to match predictions with GT.
83
- - `frames` / `image_paths`: the 2Hz frame ids and frame images passed to
84
- VLAC-Cut.
85
- - `eval_frames`: the public 1Hz frame ids used for global progress and terminal
86
- metrics.
87
- - `vlac_cut_prompt`: the exact text prompt passed to the Qwen/VLAC-Cut model.
88
- - `prompt_variant`: fixed to `chunk_all`.
89
- - `prompt_source`: fixed to `task_description`.
90
-
91
- The prompt is materialized by the manifest builder as:
92
-
93
- ```text
94
- 任务描述和具体规划: {task_description}
95
-
96
- 请根据任务描述和具体规划,找到并逐点生成视频中的关键动作点和相应的进度标注。输出格式要求:每个关键点一行,格式为:
97
- 时间: X.Xs, 进度: Y%
98
-
99
- 请严格按照上述格式输出,不要输出额外说明。
100
- ```
101
-
102
- `task_description` already contains the task and progress plan, so it is not
103
- prefixed again with `task_instruction`.
104
-
105
- ## Prediction Schema
106
-
107
- `run_vlac_cut_batch.py` writes one JSON object per trajectory:
108
-
109
- ```json
110
- {
111
- "global_episode_id": "ARX-data/.../episode_000000",
112
- "frames": [0, 15, 30, 45, 60],
113
- "response": "时间: 0.5s, 进度: 0%\n时间: 2.0s, 进度: 30%"
114
- }
115
- ```
116
-
117
- This is the public evaluator schema. The evaluator parses `response`, aligns the
118
- parsed keypoints to the provided 2Hz `frames` list using index-normalized curve
119
- alignment, and then evaluates the aligned curve on the benchmark points.
120
-
121
- ## Metrics
122
-
123
- ### Global Progress
124
-
125
- For each trajectory, the evaluator compares predictions against the released
126
- `dense_kinematic_progress` values at the selected 1Hz frames.
127
-
128
- - `MAE`: mean absolute error over valid points in one trajectory, then averaged
129
- equally over trajectories with at least one valid evaluated point.
130
- - `PRC`: Spearman correlation between GT progress and predicted progress in one
131
- trajectory, then averaged equally over valid trajectories.
132
- - `VOC`: Spearman correlation between predicted progress and chronological
133
- frame order in one trajectory, then averaged equally over valid expert-bucket
134
- trajectories.
135
-
136
- The report shows 4-bucket overall and four per-bucket rows. VOC is omitted for
137
- the 4-bucket overall and non-expert bucket rows.
138
-
139
- ### Terminal Success
140
-
141
- Terminal success uses the last selected 1Hz evaluation frame:
142
-
143
- - GT success: final GT progress `>= 90`
144
- - predicted success: final predicted progress `>= 90`
145
- - reported metrics: `TSA`, `F1_S`, `F1_F`, `MacroF1_T`, and `TP/FN/FP/TN`
146
-
147
- The report shows 4-bucket overall, seen merged, and unseen merged rows.
148
-
149
- ### Local Direction AP
150
-
151
- Local direction is computed on adjacent released `semantic_anchors`. For each
152
- transition:
153
-
154
- ```text
155
- Delta_gt = gt_anchor_progress_end - gt_anchor_progress_start
156
- Delta_pred = pred_progress_end - pred_progress_start
157
- ```
158
-
159
- Prediction values at anchor frames are obtained by linear interpolation over the
160
- model's valid predicted curve. The public report uses `tau=0`:
161
-
162
- ```text
163
- AP+ = AP(y = 1[Delta_gt > 0], score = Delta_pred)
164
- AP- = AP(y = 1[Delta_gt < 0], score = -Delta_pred)
165
- MacroAP_D = (AP+ + AP-) / 2
166
- ```
167
-
168
- Stagnation transitions are negatives inside each AP ranking, but are not
169
- averaged as a separate third AP class. The report shows 4-bucket overall, seen
170
- merged, and unseen merged rows.
171
-
172
- ## Diagnostics
173
-
174
- Missing or unparsable prediction rows are not silently filled. The report
175
- includes coverage, missing final counts, duplicate prediction counts, unknown
176
- episode ids, prediction frames outside the selected 1Hz evaluation points, and
177
- counts for predictions outside the nominal `[0, 100]` range. The nominal range
178
- counts are diagnostics only; predictions are not clipped unless `--clip-pred` is
179
- set.
180
-
181
- The evaluator is strict by default: if any selected trajectory lacks required
182
- curve points, terminal predictions, or local-direction anchor predictions, the
183
- command exits with an error before writing outputs. Add `--allow-missing` only
184
- when debugging incomplete prediction files and intentionally writing a
185
- diagnostic report.
186
-
187
- ## Quick Checks
188
-
189
- Run the evaluator self-test:
190
-
191
- ```bash
192
- python scripts/evaluate_vpb_predictions.py --self-test
193
- ```
194
-
195
- Build a small smoke-test manifest:
196
-
197
- ```bash
198
- python scripts/build_vlac_cut_eval_manifest.py \
199
- --benchmark-root benchmark_splits \
200
- --frames-root /path/to/frames \
201
- --out /tmp/vlac_cut_vpb_manifest_smoke.jsonl \
202
- --limit-trajectories 2
203
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
scripts/build_vlac_cut_eval_manifest.py DELETED
@@ -1,325 +0,0 @@
1
- #!/usr/bin/env python3
2
- from __future__ import annotations
3
-
4
- import argparse
5
- import json
6
- import math
7
- import sys
8
- from collections import Counter
9
- from pathlib import Path
10
- from typing import Any
11
-
12
- SCRIPT_DIR = Path(__file__).resolve().parent
13
- if str(SCRIPT_DIR) not in sys.path:
14
- sys.path.insert(0, str(SCRIPT_DIR))
15
-
16
- from vlac2_release_common import absolute_frame_path_from_any
17
- from vpb_public_eval_utils import (
18
- TEST_BUCKETS,
19
- iter_benchmark_rows,
20
- main_view_for_row,
21
- selected_frames_for_row,
22
- )
23
-
24
- PROMPT_VARIANT = "chunk_all"
25
- PROMPT_SOURCE = "task_description"
26
-
27
-
28
- def build_vlac_cut_prompt(task_description: str) -> str:
29
- task_and_plan = str(task_description or "").strip()
30
- return (
31
- f"任务描述和具体规划: {task_and_plan}\n\n"
32
- "请根据任务描述和具体规划,找到并逐点生成视频中的关键动作点和相应的进度标注。"
33
- "输出格式要求:每个关键点一行,格式为:\n"
34
- "时间: X.Xs, 进度: Y%\n\n"
35
- "请严格按照上述格式输出,不要输出额外说明。"
36
- )
37
-
38
-
39
- def parse_args() -> argparse.Namespace:
40
- release_root = SCRIPT_DIR.parent
41
- parser = argparse.ArgumentParser(
42
- description="Build a VLAC-Cut evaluation manifest for the public Video-Progress Benchmark."
43
- )
44
- parser.add_argument(
45
- "--benchmark-root",
46
- type=Path,
47
- default=release_root / "benchmark_splits",
48
- help="Directory containing the benchmark split folders.",
49
- )
50
- parser.add_argument(
51
- "--frames-root",
52
- type=Path,
53
- default=release_root / "_extracted_frames",
54
- help="Root directory produced by extract_vlac2_release_frames.py.",
55
- )
56
- parser.add_argument("--out", type=Path, required=True, help="Output JSONL manifest path.")
57
- parser.add_argument(
58
- "--record-format",
59
- choices=["trajectory", "point"],
60
- default="trajectory",
61
- help="Manifest row format. Use trajectory for video models and point for frame-level models.",
62
- )
63
- parser.add_argument(
64
- "--buckets",
65
- nargs="+",
66
- default=list(TEST_BUCKETS),
67
- choices=list(TEST_BUCKETS),
68
- help="Benchmark buckets to include.",
69
- )
70
- parser.add_argument(
71
- "--eval-points",
72
- choices=["time_hz", "dense", "semantic_anchors"],
73
- default="time_hz",
74
- help="Evaluation frame points. Default time_hz with --sample-hz 1.0 matches the public 1Hz evaluation protocol.",
75
- )
76
- parser.add_argument(
77
- "--sample-hz",
78
- type=float,
79
- default=1.0,
80
- help="Evaluation sampling rate used when --eval-points=time_hz.",
81
- )
82
- parser.add_argument(
83
- "--input-sample-hz",
84
- type=float,
85
- default=2.0,
86
- help="Trajectory-level video input sampling rate. The default is the 2Hz input setting used in our VLAC-Cut evaluation.",
87
- )
88
- parser.add_argument(
89
- "--view",
90
- default=None,
91
- help="Override the view for all rows. By default, the view is inferred from metadata.main_path.",
92
- )
93
- parser.add_argument(
94
- "--limit-trajectories",
95
- type=int,
96
- default=None,
97
- help="Optional smoke-test limit per full manifest, applied after bucket filtering.",
98
- )
99
- parser.add_argument(
100
- "--check-files",
101
- action="store_true",
102
- help="Check whether resolved frame files exist and report missing paths.",
103
- )
104
- return parser.parse_args()
105
-
106
-
107
- def build_record(
108
- *,
109
- bucket: str,
110
- row_idx: int,
111
- row: dict[str, Any],
112
- frame: int,
113
- timestamp_sec: float | None,
114
- image_path: Path,
115
- view: str,
116
- is_terminal_point: bool,
117
- selected_count: int,
118
- eval_points: str,
119
- sample_hz: float,
120
- ) -> dict[str, Any]:
121
- meta = dict(row.get("metadata") or {})
122
- task_description = str(meta.get("task_description") or "")
123
- record: dict[str, Any] = {
124
- "bucket": bucket,
125
- "row_index": row_idx,
126
- "global_episode_id": str(row.get("global_episode_id") or ""),
127
- "frame": int(frame),
128
- "timestamp_sec": timestamp_sec,
129
- "image_path": str(image_path),
130
- "view": view,
131
- "task_instruction": str(meta.get("task_instruction") or ""),
132
- "task_description": task_description,
133
- "vlac_cut_prompt": build_vlac_cut_prompt(task_description),
134
- "prompt_variant": PROMPT_VARIANT,
135
- "prompt_source": PROMPT_SOURCE,
136
- "is_terminal_point": bool(is_terminal_point),
137
- "selected_frame_count": int(selected_count),
138
- "eval_points": eval_points,
139
- }
140
- if eval_points == "time_hz":
141
- record["sample_hz"] = float(sample_hz)
142
- if eval_points != "time_hz" or not math.isclose(float(sample_hz), 1.0):
143
- record["non_strict_eval_input"] = True
144
- return record
145
-
146
-
147
- def build_trajectory_record(
148
- *,
149
- bucket: str,
150
- row_idx: int,
151
- row: dict[str, Any],
152
- input_frames: list[int],
153
- input_timestamps_sec: list[float | None],
154
- input_image_paths: list[Path],
155
- eval_frames: list[int],
156
- eval_timestamps_sec: list[float | None],
157
- view: str,
158
- eval_points: str,
159
- eval_sample_hz: float,
160
- input_sample_hz: float,
161
- ) -> dict[str, Any]:
162
- meta = dict(row.get("metadata") or {})
163
- task_description = str(meta.get("task_description") or "")
164
- record: dict[str, Any] = {
165
- "bucket": bucket,
166
- "row_index": row_idx,
167
- "global_episode_id": str(row.get("global_episode_id") or ""),
168
- "frames": [int(frame) for frame in input_frames],
169
- "timestamps_sec": input_timestamps_sec,
170
- "image_paths": [str(path) for path in input_image_paths],
171
- "input_frames": [int(frame) for frame in input_frames],
172
- "input_timestamps_sec": input_timestamps_sec,
173
- "input_image_paths": [str(path) for path in input_image_paths],
174
- "eval_frames": [int(frame) for frame in eval_frames],
175
- "eval_timestamps_sec": eval_timestamps_sec,
176
- "view": view,
177
- "task_instruction": str(meta.get("task_instruction") or ""),
178
- "task_description": task_description,
179
- "vlac_cut_prompt": build_vlac_cut_prompt(task_description),
180
- "prompt_variant": PROMPT_VARIANT,
181
- "prompt_source": PROMPT_SOURCE,
182
- "terminal_frame": int(eval_frames[-1]) if eval_frames else None,
183
- "selected_frame_count": len(input_frames),
184
- "input_frame_count": len(input_frames),
185
- "eval_frame_count": len(eval_frames),
186
- "eval_points": eval_points,
187
- "input_sample_hz": float(input_sample_hz),
188
- }
189
- if eval_points == "time_hz":
190
- record["sample_hz"] = float(eval_sample_hz)
191
- record["eval_sample_hz"] = float(eval_sample_hz)
192
- if eval_points != "time_hz" or not math.isclose(float(eval_sample_hz), 1.0):
193
- record["non_strict_eval_input"] = True
194
- return record
195
-
196
-
197
- def main() -> None:
198
- args = parse_args()
199
- if args.sample_hz <= 0:
200
- raise SystemExit("--sample-hz must be positive")
201
- if args.input_sample_hz <= 0:
202
- raise SystemExit("--input-sample-hz must be positive")
203
-
204
- args.out.parent.mkdir(parents=True, exist_ok=True)
205
- stats: Counter[str] = Counter()
206
- emitted_trajectories = 0
207
-
208
- with args.out.open("w", encoding="utf-8") as f:
209
- for bucket, row_idx, row in iter_benchmark_rows(args.benchmark_root, args.buckets):
210
- if args.limit_trajectories is not None and emitted_trajectories >= args.limit_trajectories:
211
- break
212
-
213
- eval_selected = selected_frames_for_row(
214
- row,
215
- eval_points=args.eval_points,
216
- sample_hz=float(args.sample_hz),
217
- )
218
- if not eval_selected.frames:
219
- stats["skipped_empty_selection"] += 1
220
- continue
221
- input_selected = selected_frames_for_row(
222
- row,
223
- eval_points="time_hz",
224
- sample_hz=float(args.input_sample_hz),
225
- )
226
- if args.record_format == "trajectory" and not input_selected.frames:
227
- stats["skipped_empty_input_selection"] += 1
228
- continue
229
-
230
- selected_view = str(args.view or main_view_for_row(row) or "").strip()
231
- if not selected_view:
232
- stats["skipped_missing_view"] += 1
233
- continue
234
-
235
- frame_index = dict(row.get("frame_index") or {})
236
- full_eval_frames = eval_selected.frames
237
- terminal_frame = full_eval_frames[-1]
238
- source_selection = input_selected if args.record_format == "trajectory" else eval_selected
239
- resolved_frames: list[int] = []
240
- resolved_timestamps: list[float | None] = []
241
- resolved_paths: list[Path] = []
242
- missing_view = False
243
- for frame, timestamp_sec in zip(source_selection.frames, source_selection.timestamps_sec):
244
- image_map = frame_index.get(str(frame))
245
- if not isinstance(image_map, dict) or selected_view not in image_map:
246
- stats["missing_view_points"] += 1
247
- missing_view = True
248
- continue
249
- image_path = absolute_frame_path_from_any(str(image_map[selected_view]), args.frames_root)
250
- if args.check_files and not image_path.exists():
251
- stats["missing_frame_files"] += 1
252
- resolved_frames.append(frame)
253
- resolved_timestamps.append(timestamp_sec)
254
- resolved_paths.append(image_path)
255
-
256
- if not resolved_frames:
257
- stats["skipped_no_resolved_frames"] += 1
258
- continue
259
- if args.record_format == "trajectory" and missing_view:
260
- stats["skipped_incomplete_trajectory"] += 1
261
- continue
262
-
263
- emitted_for_traj = 0
264
- if args.record_format == "trajectory":
265
- record = build_trajectory_record(
266
- bucket=bucket,
267
- row_idx=row_idx,
268
- row=row,
269
- input_frames=resolved_frames,
270
- input_timestamps_sec=resolved_timestamps,
271
- input_image_paths=resolved_paths,
272
- eval_frames=eval_selected.frames,
273
- eval_timestamps_sec=eval_selected.timestamps_sec,
274
- view=selected_view,
275
- eval_points=args.eval_points,
276
- eval_sample_hz=float(args.sample_hz),
277
- input_sample_hz=float(args.input_sample_hz),
278
- )
279
- f.write(json.dumps(record, ensure_ascii=False) + "\n")
280
- stats["records"] += 1
281
- stats["trajectory_records"] += 1
282
- emitted_for_traj = 1
283
- else:
284
- for frame, timestamp_sec, image_path in zip(
285
- resolved_frames,
286
- resolved_timestamps,
287
- resolved_paths,
288
- ):
289
- record = build_record(
290
- bucket=bucket,
291
- row_idx=row_idx,
292
- row=row,
293
- frame=frame,
294
- timestamp_sec=timestamp_sec,
295
- image_path=image_path,
296
- view=selected_view,
297
- is_terminal_point=(frame == terminal_frame),
298
- selected_count=len(eval_selected.frames),
299
- eval_points=args.eval_points,
300
- sample_hz=float(args.sample_hz),
301
- )
302
- f.write(json.dumps(record, ensure_ascii=False) + "\n")
303
- emitted_for_traj += 1
304
- stats["records"] += 1
305
- stats["point_records"] += 1
306
- if emitted_for_traj:
307
- emitted_trajectories += 1
308
- stats["trajectories"] += 1
309
-
310
- summary = {
311
- "out": str(args.out),
312
- "benchmark_root": str(args.benchmark_root),
313
- "frames_root": str(args.frames_root),
314
- "buckets": list(args.buckets),
315
- "eval_points": args.eval_points,
316
- "sample_hz": float(args.sample_hz) if args.eval_points == "time_hz" else None,
317
- "input_sample_hz": float(args.input_sample_hz),
318
- "record_format": args.record_format,
319
- "stats": dict(stats),
320
- }
321
- print(json.dumps(summary, ensure_ascii=False, indent=2))
322
-
323
-
324
- if __name__ == "__main__":
325
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
scripts/evaluate_vpb_predictions.py DELETED
@@ -1,1138 +0,0 @@
1
- #!/usr/bin/env python3
2
- from __future__ import annotations
3
-
4
- import argparse
5
- import json
6
- import math
7
- import re
8
- import sys
9
- import tempfile
10
- from collections import Counter
11
- from pathlib import Path
12
- from typing import Any
13
-
14
- SCRIPT_DIR = Path(__file__).resolve().parent
15
- if str(SCRIPT_DIR) not in sys.path:
16
- sys.path.insert(0, str(SCRIPT_DIR))
17
-
18
- from vpb_public_eval_utils import (
19
- EXPERT_BUCKETS,
20
- TEST_BUCKETS,
21
- Trajectory,
22
- build_trajectories,
23
- dump_json,
24
- finite_float,
25
- format_metric,
26
- format_percent,
27
- markdown_table,
28
- mean_or_none,
29
- spearman_corr,
30
- )
31
-
32
-
33
- PredMap = dict[str, dict[int, float]]
34
- SIGNED_NUM = r"([+-]?[0-9]+(?:\.[0-9]+)?)"
35
- POINT_TIME_RE = re.compile(r"(?:Time|时间)[::]?\s*([0-9]+(?:\.[0-9]+)?)\s*s?", re.IGNORECASE)
36
- POINT_PROGRESS_LINE_RE = re.compile(rf"(?im)^\s*(?:Progress|进度)[::]?\s*{SIGNED_NUM}\s*%")
37
- INLINE_POINT_RE = re.compile(
38
- rf"(?:Time|时间)[::]?\s*([0-9]+(?:\.[0-9]+)?)\s*s?\s*[,,]?\s*(?:Progress|进度)[::]?\s*{SIGNED_NUM}\s*%",
39
- re.IGNORECASE,
40
- )
41
- SEEN_BUCKETS = ("test_expert_seen", "test_nonexpert_seen")
42
- UNSEEN_BUCKETS = ("test_expert_unseen", "test_nonexpert_unseen")
43
- LOCAL_DIRECTION_TAU_PERCENT = 0.0
44
-
45
-
46
- def parse_args() -> argparse.Namespace:
47
- release_root = SCRIPT_DIR.parent
48
- parser = argparse.ArgumentParser(
49
- description="Evaluate public Video-Progress Benchmark predictions."
50
- )
51
- parser.add_argument(
52
- "--benchmark-root",
53
- type=Path,
54
- default=release_root / "benchmark_splits",
55
- help="Directory containing the benchmark split folders.",
56
- )
57
- parser.add_argument(
58
- "--predictions",
59
- type=Path,
60
- help="VLAC-Cut batch prediction JSONL with global_episode_id, frames, and response.",
61
- )
62
- parser.add_argument("--out-json", type=Path, help="Output JSON report.")
63
- parser.add_argument("--out-md", type=Path, help="Output Markdown report.")
64
- parser.add_argument(
65
- "--buckets",
66
- nargs="+",
67
- default=list(TEST_BUCKETS),
68
- choices=list(TEST_BUCKETS),
69
- help="Benchmark buckets to evaluate.",
70
- )
71
- parser.add_argument(
72
- "--eval-points",
73
- choices=["time_hz", "dense", "semantic_anchors"],
74
- default="time_hz",
75
- help="Evaluation frame points. Default time_hz with --sample-hz 1.0 reconstructs the public 1Hz protocol.",
76
- )
77
- parser.add_argument(
78
- "--sample-hz",
79
- type=float,
80
- default=1.0,
81
- help="Sampling rate used when --eval-points=time_hz.",
82
- )
83
- parser.add_argument(
84
- "--success-threshold",
85
- type=float,
86
- default=90.0,
87
- help="Terminal success threshold in progress percent.",
88
- )
89
- parser.add_argument(
90
- "--clip-pred",
91
- nargs=2,
92
- type=float,
93
- metavar=("MIN", "MAX"),
94
- default=None,
95
- help="Optionally clip predictions before evaluation.",
96
- )
97
- parser.add_argument(
98
- "--interpolate-missing",
99
- action="store_true",
100
- help="Linearly interpolate missing prediction frames within each trajectory. This is not the strict default.",
101
- )
102
- parser.add_argument(
103
- "--allow-missing",
104
- action="store_true",
105
- help="Write a diagnostic report even when predictions do not cover every required evaluation point.",
106
- )
107
- parser.add_argument(
108
- "--self-test",
109
- action="store_true",
110
- help="Run a small synthetic self-test and exit.",
111
- )
112
- return parser.parse_args()
113
-
114
-
115
- def load_prediction_rows(path: Path) -> list[dict[str, Any]]:
116
- text = path.read_text(encoding="utf-8").strip()
117
- if not text:
118
- return []
119
- try:
120
- payload = json.loads(text)
121
- except json.JSONDecodeError:
122
- rows = []
123
- for line_no, line in enumerate(text.splitlines(), start=1):
124
- raw = line.strip()
125
- if not raw:
126
- continue
127
- item = json.loads(raw)
128
- if not isinstance(item, dict):
129
- raise ValueError(f"Prediction line {line_no} is not an object")
130
- rows.append(item)
131
- return rows
132
-
133
- if isinstance(payload, list):
134
- if not all(isinstance(item, dict) for item in payload):
135
- raise ValueError("Prediction JSON list must contain objects")
136
- return list(payload)
137
- if isinstance(payload, dict):
138
- for key in ("predictions", "results", "rows"):
139
- value = payload.get(key)
140
- if isinstance(value, list):
141
- if not all(isinstance(item, dict) for item in value):
142
- raise ValueError(f"Prediction JSON field {key!r} must contain objects")
143
- return list(value)
144
- return [payload]
145
- raise ValueError("Prediction file must be JSONL, a JSON object, or a JSON list")
146
-
147
-
148
- def strip_code_fence(text: str) -> str:
149
- cleaned = str(text or "").strip()
150
- if cleaned.startswith("```") and cleaned.endswith("```"):
151
- lines = cleaned.splitlines()
152
- if len(lines) >= 3:
153
- return "\n".join(lines[1:-1]).strip()
154
- return cleaned
155
-
156
-
157
- def dedupe_sorted_points(times: list[float], values: list[float]) -> tuple[list[float], list[float]]:
158
- if not times:
159
- return [], []
160
- pairs = sorted(zip(times, values), key=lambda item: (item[0], item[1]))
161
- out_times: list[float] = []
162
- out_values: list[float] = []
163
- cur_time = pairs[0][0]
164
- bucket: list[float] = []
165
- for time_val, progress_val in pairs:
166
- if time_val != cur_time:
167
- out_times.append(float(cur_time))
168
- out_values.append(float(sum(bucket) / len(bucket)))
169
- cur_time = time_val
170
- bucket = [float(progress_val)]
171
- else:
172
- bucket.append(float(progress_val))
173
- out_times.append(float(cur_time))
174
- out_values.append(float(sum(bucket) / len(bucket)))
175
- return out_times, out_values
176
-
177
-
178
- def parse_point_blocks(text: str) -> tuple[list[float], list[float]]:
179
- cleaned = strip_code_fence(text)
180
- if not cleaned:
181
- return [], []
182
- inline_matches = INLINE_POINT_RE.findall(cleaned)
183
- if inline_matches:
184
- return dedupe_sorted_points(
185
- [float(time_val) for time_val, _ in inline_matches],
186
- [float(progress_val) for _, progress_val in inline_matches],
187
- )
188
- blocks = re.split(r"(?=(?:Time|时间)[::]?\s*[0-9])", cleaned, flags=re.IGNORECASE)
189
- times: list[float] = []
190
- values: list[float] = []
191
- for block in blocks:
192
- block = block.strip()
193
- if not block:
194
- continue
195
- time_match = POINT_TIME_RE.search(block)
196
- progress_match = POINT_PROGRESS_LINE_RE.search(block)
197
- if time_match and progress_match:
198
- times.append(float(time_match.group(1)))
199
- values.append(float(progress_match.group(1)))
200
- return dedupe_sorted_points(times, values)
201
-
202
-
203
- def align_curve_to_length(raw_times: list[float], raw_values: list[float], target_len: int) -> list[float]:
204
- """Match the formal VLAC evaluator's index-normalized curve alignment."""
205
- if target_len <= 0 or not raw_values:
206
- return []
207
- if len(raw_values) == 1:
208
- return [float(raw_values[0])] * target_len
209
- times, values = dedupe_sorted_points(raw_times, raw_values)
210
- if len(values) == 1:
211
- return [float(values[0])] * target_len
212
- start = float(times[0])
213
- end = float(times[-1])
214
- if math.isclose(start, end):
215
- if len(values) == 1:
216
- positions = [0.0]
217
- else:
218
- positions = [idx * float(target_len - 1) / float(len(values) - 1) for idx in range(len(values))]
219
- else:
220
- positions = [(time_val - start) / (end - start) * float(target_len - 1) for time_val in times]
221
-
222
- aligned: list[float] = []
223
- for target in range(target_len):
224
- target_f = float(target)
225
- if target_f <= positions[0]:
226
- aligned.append(float(values[0]))
227
- continue
228
- if target_f >= positions[-1]:
229
- aligned.append(float(values[-1]))
230
- continue
231
- for idx in range(len(positions) - 1):
232
- if positions[idx] <= target_f <= positions[idx + 1]:
233
- if math.isclose(positions[idx], positions[idx + 1]):
234
- value = float(values[idx])
235
- else:
236
- alpha = (target_f - positions[idx]) / (positions[idx + 1] - positions[idx])
237
- value = float(values[idx]) + alpha * (float(values[idx + 1]) - float(values[idx]))
238
- aligned.append(float(value))
239
- break
240
- return aligned
241
-
242
-
243
- def maybe_clip(value: float, clip_range: tuple[float, float] | None, stats: Counter[str]) -> float:
244
- if clip_range is None:
245
- if value < 0.0 or value > 100.0:
246
- stats["outside_nominal_0_100_predictions"] += 1
247
- return value
248
- lo, hi = clip_range
249
- clipped = min(max(value, lo), hi)
250
- if clipped != value:
251
- stats["clipped_predictions"] += 1
252
- return clipped
253
-
254
-
255
- def add_prediction(
256
- pred_map: PredMap,
257
- *,
258
- gid: str,
259
- frame: int,
260
- value: Any,
261
- clip_range: tuple[float, float] | None,
262
- stats: Counter[str],
263
- ) -> None:
264
- pred_value = finite_float(value)
265
- if pred_value is None:
266
- stats["invalid_prediction_values"] += 1
267
- return
268
- pred_value = maybe_clip(float(pred_value), clip_range, stats)
269
- frame_map = pred_map.setdefault(gid, {})
270
- if int(frame) in frame_map:
271
- stats["duplicate_frame_predictions"] += 1
272
- frame_map[int(frame)] = pred_value
273
- stats["valid_prediction_values"] += 1
274
-
275
-
276
- def add_canonical_vlac_response_predictions(
277
- pred_map: PredMap,
278
- *,
279
- gid: str,
280
- row: dict[str, Any],
281
- clip_range: tuple[float, float] | None,
282
- stats: Counter[str],
283
- ) -> None:
284
- frame_sequence = row.get("frames")
285
- if not isinstance(frame_sequence, list) or not frame_sequence:
286
- stats["canonical_rows_missing_frames"] += 1
287
- return
288
- valid_frames: list[int] = []
289
- for raw_frame in frame_sequence:
290
- frame = finite_float(raw_frame)
291
- if frame is None:
292
- stats["canonical_rows_invalid_frames"] += 1
293
- return
294
- valid_frames.append(int(frame))
295
-
296
- response = row.get("response")
297
- if not isinstance(response, str) or not response.strip():
298
- stats["canonical_rows_missing_response"] += 1
299
- return
300
-
301
- raw_times, raw_values = parse_point_blocks(response)
302
-
303
- if not raw_values:
304
- stats["canonical_response_parse_failed"] += 1
305
- return
306
-
307
- aligned = align_curve_to_length(raw_times, raw_values, len(valid_frames))
308
- if not aligned:
309
- stats["canonical_response_align_failed"] += 1
310
- return
311
-
312
- for frame, value in zip(valid_frames, aligned):
313
- add_prediction(
314
- pred_map,
315
- gid=gid,
316
- frame=frame,
317
- value=value,
318
- clip_range=clip_range,
319
- stats=stats,
320
- )
321
- stats["canonical_response_rows_aligned_by_index"] += 1
322
-
323
-
324
- def load_predictions(
325
- path: Path,
326
- *,
327
- trajectories: list[Trajectory],
328
- clip_range: tuple[float, float] | None,
329
- ) -> tuple[PredMap, dict[str, Any]]:
330
- traj_by_gid = {traj.global_episode_id: traj for traj in trajectories}
331
- pred_map: PredMap = {}
332
- stats: Counter[str] = Counter()
333
- unknown_examples: list[str] = []
334
-
335
- rows = load_prediction_rows(path)
336
- stats["rows"] = len(rows)
337
- for row in rows:
338
- gid = str(row.get("global_episode_id") or "").strip()
339
- if not gid:
340
- stats["rows_missing_global_episode_id"] += 1
341
- continue
342
- traj = traj_by_gid.get(gid)
343
- if traj is None:
344
- stats["unknown_global_episode_id"] += 1
345
- if len(unknown_examples) < 10:
346
- unknown_examples.append(gid)
347
- continue
348
-
349
- add_canonical_vlac_response_predictions(
350
- pred_map,
351
- gid=gid,
352
- row=row,
353
- clip_range=clip_range,
354
- stats=stats,
355
- )
356
-
357
- known_frames = {traj.global_episode_id: set(traj.frames) for traj in trajectories}
358
- extra_frame_count = 0
359
- for gid, frame_map in pred_map.items():
360
- eval_frames = known_frames.get(gid, set())
361
- for frame in frame_map:
362
- if frame not in eval_frames:
363
- extra_frame_count += 1
364
- stats["prediction_frames_outside_eval_points"] = extra_frame_count
365
-
366
- return pred_map, {"stats": dict(stats), "unknown_global_episode_id_examples": unknown_examples}
367
-
368
-
369
- def interpolated_value(frame_map: dict[int, float], frame: int) -> float | None:
370
- if frame in frame_map:
371
- return frame_map[frame]
372
- if not frame_map:
373
- return None
374
- points = sorted(frame_map.items())
375
- if frame <= points[0][0]:
376
- return points[0][1]
377
- if frame >= points[-1][0]:
378
- return points[-1][1]
379
- for (left_frame, left_value), (right_frame, right_value) in zip(points, points[1:]):
380
- if left_frame <= frame <= right_frame:
381
- if right_frame == left_frame:
382
- return left_value
383
- alpha = (frame - left_frame) / float(right_frame - left_frame)
384
- return left_value + alpha * (right_value - left_value)
385
- return None
386
-
387
-
388
- def interpolated_prediction_for_frame(pred_map: PredMap, gid: str, frame: int) -> float | None:
389
- frame_map = pred_map.get(gid)
390
- if not frame_map:
391
- return None
392
- return interpolated_value(frame_map, int(frame))
393
-
394
-
395
- def prediction_at(
396
- pred_map: PredMap,
397
- gid: str,
398
- frame: int,
399
- *,
400
- interpolate_missing: bool,
401
- ) -> float | None:
402
- frame_map = pred_map.get(gid)
403
- if not frame_map:
404
- return None
405
- if frame in frame_map:
406
- return frame_map[frame]
407
- if interpolate_missing:
408
- return interpolated_value(frame_map, frame)
409
- return None
410
-
411
-
412
- def summarize_curve(
413
- trajectories: list[Trajectory],
414
- pred_map: PredMap,
415
- *,
416
- interpolate_missing: bool,
417
- include_voc: bool,
418
- ) -> dict[str, Any]:
419
- base_points = sum(len(traj.frames) for traj in trajectories)
420
- matched_trajs = 0
421
- matched_points = 0
422
- valid_points = 0
423
- traj_with_valid_pred = 0
424
- mae_values: list[float] = []
425
- prc_values: list[float] = []
426
- voc_values: list[float] = []
427
-
428
- for traj in trajectories:
429
- has_predictions = traj.global_episode_id in pred_map
430
- if has_predictions:
431
- matched_trajs += 1
432
- matched_points += len(traj.frames)
433
-
434
- gt_curve: list[float] = []
435
- pred_curve: list[float] = []
436
- for frame, gt in zip(traj.frames, traj.gt_progress):
437
- pred = prediction_at(
438
- pred_map,
439
- traj.global_episode_id,
440
- frame,
441
- interpolate_missing=interpolate_missing,
442
- )
443
- if pred is None or not math.isfinite(float(pred)):
444
- continue
445
- valid_points += 1
446
- gt_curve.append(float(gt))
447
- pred_curve.append(float(pred))
448
-
449
- if gt_curve:
450
- traj_with_valid_pred += 1
451
- mae_values.append(
452
- sum(abs(gt - pred) for gt, pred in zip(gt_curve, pred_curve))
453
- / len(gt_curve)
454
- )
455
-
456
- prc = spearman_corr(gt_curve, pred_curve)
457
- if prc is not None:
458
- prc_values.append(prc)
459
- if include_voc:
460
- voc = spearman_corr(pred_curve, [float(i) for i in range(1, len(pred_curve) + 1)])
461
- if voc is not None:
462
- voc_values.append(voc)
463
-
464
- return {
465
- "traj_base_total": len(trajectories),
466
- "traj_matched": matched_trajs,
467
- "traj_with_valid_pred": traj_with_valid_pred,
468
- "point_base_total": base_points,
469
- "point_total_on_matched": matched_points,
470
- "point_valid": valid_points,
471
- "point_coverage_to_base": (valid_points / base_points) if base_points else None,
472
- "point_coverage_on_matched": (valid_points / matched_points) if matched_points else None,
473
- "mae": mean_or_none(mae_values),
474
- "mae_valid_traj": len(mae_values),
475
- "prc": mean_or_none(prc_values),
476
- "prc_valid_traj": len(prc_values),
477
- "voc": mean_or_none(voc_values) if include_voc else None,
478
- "voc_valid_traj": len(voc_values) if include_voc else 0,
479
- }
480
-
481
-
482
- def average_precision_ranked(items: list[tuple[int, float]]) -> float | None:
483
- positive_total = int(sum(label for label, _ in items))
484
- if not items or positive_total == 0:
485
- return None
486
- ranked = sorted(enumerate(items), key=lambda item: (-float(item[1][1]), item[0]))
487
- hits = 0
488
- precision_sum = 0.0
489
- for rank, (_, (label, _score)) in enumerate(ranked, start=1):
490
- if int(label) == 1:
491
- hits += 1
492
- precision_sum += hits / rank
493
- return precision_sum / positive_total
494
-
495
-
496
- def classify_delta(delta: float, tau_percent: float) -> str:
497
- if delta > tau_percent:
498
- return "positive"
499
- if delta < -tau_percent:
500
- return "negative"
501
- return "neutral"
502
-
503
-
504
- def summarize_local_direction_ap(
505
- trajectories: list[Trajectory],
506
- pred_map: PredMap,
507
- *,
508
- tau_percent: float,
509
- ) -> dict[str, Any]:
510
- transition_total = 0
511
- valid = 0
512
- missing = 0
513
- gt_counts: Counter[str] = Counter()
514
- valid_gt_counts: Counter[str] = Counter()
515
- positive_items: list[tuple[int, float]] = []
516
- negative_items: list[tuple[int, float]] = []
517
-
518
- for traj in trajectories:
519
- frames = traj.semantic_anchor_frames
520
- progress = traj.semantic_anchor_progress
521
- for idx in range(max(0, len(frames) - 1)):
522
- transition_total += 1
523
- gt_delta = float(progress[idx + 1]) - float(progress[idx])
524
- gt_class = classify_delta(gt_delta, tau_percent)
525
- gt_counts[gt_class] += 1
526
-
527
- left = interpolated_prediction_for_frame(pred_map, traj.global_episode_id, frames[idx])
528
- right = interpolated_prediction_for_frame(pred_map, traj.global_episode_id, frames[idx + 1])
529
- if left is None or right is None or not math.isfinite(float(left)) or not math.isfinite(float(right)):
530
- missing += 1
531
- continue
532
-
533
- valid += 1
534
- valid_gt_counts[gt_class] += 1
535
- pred_delta = float(right) - float(left)
536
- positive_items.append((1 if gt_delta > tau_percent else 0, pred_delta))
537
- negative_items.append((1 if gt_delta < -tau_percent else 0, -pred_delta))
538
-
539
- ap_positive = average_precision_ranked(positive_items)
540
- ap_negative = average_precision_ranked(negative_items)
541
- macro_ap = (
542
- 0.5 * (ap_positive + ap_negative)
543
- if ap_positive is not None and ap_negative is not None
544
- else None
545
- )
546
- return {
547
- "tau_percent": float(tau_percent),
548
- "transition_total": int(transition_total),
549
- "valid": int(valid),
550
- "missing": int(missing),
551
- "gt_counts": {key: int(gt_counts.get(key, 0)) for key in ("positive", "neutral", "negative")},
552
- "valid_gt_counts": {key: int(valid_gt_counts.get(key, 0)) for key in ("positive", "neutral", "negative")},
553
- "ap_positive_support": int(sum(label for label, _ in positive_items)),
554
- "ap_negative_support": int(sum(label for label, _ in negative_items)),
555
- "ap_positive": ap_positive,
556
- "ap_negative": ap_negative,
557
- "macro_ap_d": macro_ap,
558
- }
559
-
560
-
561
- def finalize_terminal_counter(counter: Counter[str]) -> dict[str, Any]:
562
- support = int(counter.get("support", 0))
563
- valid_final = int(counter.get("valid_final", 0))
564
- tp = int(counter.get("tp", 0))
565
- fn = int(counter.get("fn", 0))
566
- fp = int(counter.get("fp", 0))
567
- tn = int(counter.get("tn", 0))
568
- gt_success = int(counter.get("gt_success", 0))
569
- gt_failure = int(counter.get("gt_failure", 0))
570
- pred_success = int(counter.get("pred_success", 0))
571
- pred_failure = int(counter.get("pred_failure", 0))
572
- missing_final = int(counter.get("missing_final", 0))
573
- valid_binary = tp + fn + fp + tn
574
-
575
- f1_success = (2 * tp / (2 * tp + fp + fn)) if (2 * tp + fp + fn) else None
576
- f1_failure = (2 * tn / (2 * tn + fp + fn)) if (2 * tn + fp + fn) else None
577
- macro_f1_terminal = (
578
- (f1_success + f1_failure) / 2.0
579
- if f1_success is not None and f1_failure is not None
580
- else None
581
- )
582
- return {
583
- "support": support,
584
- "gt_success": gt_success,
585
- "gt_failure": gt_failure,
586
- "valid_final": valid_final,
587
- "missing_final": missing_final,
588
- "pred_success": pred_success,
589
- "pred_failure": pred_failure,
590
- "tp": tp,
591
- "fn": fn,
592
- "fp": fp,
593
- "tn": tn,
594
- "tsa": ((tp + tn) / valid_binary) if valid_binary else None,
595
- "f1_success": f1_success,
596
- "f1_failure": f1_failure,
597
- "macro_f1_terminal": macro_f1_terminal,
598
- }
599
-
600
-
601
- def summarize_terminal(
602
- trajectories: list[Trajectory],
603
- pred_map: PredMap,
604
- *,
605
- success_threshold: float,
606
- interpolate_missing: bool,
607
- ) -> dict[str, Any]:
608
- counter: Counter[str] = Counter()
609
- for traj in trajectories:
610
- counter["support"] += 1
611
- gt_final = float(traj.gt_progress[-1])
612
- gt_success = gt_final >= success_threshold
613
- if gt_success:
614
- counter["gt_success"] += 1
615
- else:
616
- counter["gt_failure"] += 1
617
-
618
- pred_final = prediction_at(
619
- pred_map,
620
- traj.global_episode_id,
621
- traj.frames[-1],
622
- interpolate_missing=interpolate_missing,
623
- )
624
- if pred_final is None or not math.isfinite(float(pred_final)):
625
- counter["missing_final"] += 1
626
- continue
627
- counter["valid_final"] += 1
628
- pred_success = float(pred_final) >= success_threshold
629
- if pred_success:
630
- counter["pred_success"] += 1
631
- else:
632
- counter["pred_failure"] += 1
633
-
634
- if gt_success and pred_success:
635
- counter["tp"] += 1
636
- elif gt_success and not pred_success:
637
- counter["fn"] += 1
638
- elif (not gt_success) and pred_success:
639
- counter["fp"] += 1
640
- else:
641
- counter["tn"] += 1
642
- return finalize_terminal_counter(counter)
643
-
644
-
645
- def build_report(
646
- *,
647
- trajectories: list[Trajectory],
648
- pred_map: PredMap,
649
- prediction_info: dict[str, Any],
650
- config: dict[str, Any],
651
- ) -> dict[str, Any]:
652
- selected_buckets = list(config["buckets"])
653
- by_bucket = {bucket: [traj for traj in trajectories if traj.bucket == bucket] for bucket in selected_buckets}
654
- interpolate_missing = bool(config["interpolate_missing"])
655
- success_threshold = float(config["success_threshold_percent"])
656
- seen_trajs = [
657
- traj for bucket in SEEN_BUCKETS for traj in by_bucket.get(bucket, [])
658
- ]
659
- unseen_trajs = [
660
- traj for bucket in UNSEEN_BUCKETS for traj in by_bucket.get(bucket, [])
661
- ]
662
-
663
- curve_per_bucket = {
664
- bucket: summarize_curve(
665
- bucket_trajs,
666
- pred_map,
667
- interpolate_missing=interpolate_missing,
668
- include_voc=(bucket in EXPERT_BUCKETS),
669
- )
670
- for bucket, bucket_trajs in by_bucket.items()
671
- }
672
- terminal_per_bucket = {
673
- bucket: summarize_terminal(
674
- bucket_trajs,
675
- pred_map,
676
- success_threshold=success_threshold,
677
- interpolate_missing=interpolate_missing,
678
- )
679
- for bucket, bucket_trajs in by_bucket.items()
680
- }
681
- local_direction_per_bucket = {
682
- bucket: summarize_local_direction_ap(
683
- bucket_trajs,
684
- pred_map,
685
- tau_percent=LOCAL_DIRECTION_TAU_PERCENT,
686
- )
687
- for bucket, bucket_trajs in by_bucket.items()
688
- }
689
-
690
- return {
691
- "config": config,
692
- "benchmark": {
693
- "traj_total": len(trajectories),
694
- "point_total": sum(len(traj.frames) for traj in trajectories),
695
- "buckets": {
696
- bucket: {
697
- "traj_total": len(bucket_trajs),
698
- "point_total": sum(len(traj.frames) for traj in bucket_trajs),
699
- }
700
- for bucket, bucket_trajs in by_bucket.items()
701
- },
702
- },
703
- "prediction_input": prediction_info,
704
- "curve": {
705
- "overall_4bucket": summarize_curve(
706
- trajectories,
707
- pred_map,
708
- interpolate_missing=interpolate_missing,
709
- include_voc=False,
710
- ),
711
- "per_bucket": curve_per_bucket,
712
- },
713
- "terminal": {
714
- "overall_4bucket": summarize_terminal(
715
- trajectories,
716
- pred_map,
717
- success_threshold=success_threshold,
718
- interpolate_missing=interpolate_missing,
719
- ),
720
- "seen_merged": summarize_terminal(
721
- seen_trajs,
722
- pred_map,
723
- success_threshold=success_threshold,
724
- interpolate_missing=interpolate_missing,
725
- ),
726
- "unseen_merged": summarize_terminal(
727
- unseen_trajs,
728
- pred_map,
729
- success_threshold=success_threshold,
730
- interpolate_missing=interpolate_missing,
731
- ),
732
- "per_bucket": terminal_per_bucket,
733
- },
734
- "local_direction_ap": {
735
- "tau_percent": LOCAL_DIRECTION_TAU_PERCENT,
736
- "overall_4bucket": summarize_local_direction_ap(
737
- trajectories,
738
- pred_map,
739
- tau_percent=LOCAL_DIRECTION_TAU_PERCENT,
740
- ),
741
- "seen_merged": summarize_local_direction_ap(
742
- seen_trajs,
743
- pred_map,
744
- tau_percent=LOCAL_DIRECTION_TAU_PERCENT,
745
- ),
746
- "unseen_merged": summarize_local_direction_ap(
747
- unseen_trajs,
748
- pred_map,
749
- tau_percent=LOCAL_DIRECTION_TAU_PERCENT,
750
- ),
751
- "per_bucket": local_direction_per_bucket,
752
- },
753
- }
754
-
755
-
756
- def validate_no_missing(report: dict[str, Any]) -> dict[str, Any]:
757
- errors: list[str] = []
758
-
759
- curve_sources = [("overall_4bucket", report["curve"]["overall_4bucket"])]
760
- curve_sources.extend(
761
- (bucket, item)
762
- for bucket, item in report["curve"]["per_bucket"].items()
763
- )
764
- for scope, item in curve_sources:
765
- if int(item.get("point_valid", 0)) != int(item.get("point_base_total", 0)):
766
- errors.append(
767
- f"curve.{scope}: point_valid={item.get('point_valid')} "
768
- f"point_base_total={item.get('point_base_total')}"
769
- )
770
- if int(item.get("traj_with_valid_pred", 0)) != int(item.get("traj_base_total", 0)):
771
- errors.append(
772
- f"curve.{scope}: traj_with_valid_pred={item.get('traj_with_valid_pred')} "
773
- f"traj_base_total={item.get('traj_base_total')}"
774
- )
775
-
776
- terminal_sources = [
777
- ("overall_4bucket", report["terminal"]["overall_4bucket"]),
778
- ("seen_merged", report["terminal"]["seen_merged"]),
779
- ("unseen_merged", report["terminal"]["unseen_merged"]),
780
- ]
781
- terminal_sources.extend(
782
- (bucket, item)
783
- for bucket, item in report["terminal"]["per_bucket"].items()
784
- )
785
- for scope, item in terminal_sources:
786
- if int(item.get("valid_final", 0)) != int(item.get("support", 0)) or int(item.get("missing_final", 0)) != 0:
787
- errors.append(
788
- f"terminal.{scope}: valid_final={item.get('valid_final')} "
789
- f"support={item.get('support')} missing_final={item.get('missing_final')}"
790
- )
791
-
792
- direction_sources = [
793
- ("overall_4bucket", report["local_direction_ap"]["overall_4bucket"]),
794
- ("seen_merged", report["local_direction_ap"]["seen_merged"]),
795
- ("unseen_merged", report["local_direction_ap"]["unseen_merged"]),
796
- ]
797
- direction_sources.extend(
798
- (bucket, item)
799
- for bucket, item in report["local_direction_ap"]["per_bucket"].items()
800
- )
801
- for scope, item in direction_sources:
802
- if int(item.get("valid", 0)) != int(item.get("transition_total", 0)) or int(item.get("missing", 0)) != 0:
803
- errors.append(
804
- f"local_direction_ap.{scope}: valid={item.get('valid')} "
805
- f"transition_total={item.get('transition_total')} missing={item.get('missing')}"
806
- )
807
-
808
- return {
809
- "no_missing_check": not errors,
810
- "error_count": len(errors),
811
- "errors": errors,
812
- }
813
-
814
-
815
- def point_ratio(item: dict[str, Any]) -> str:
816
- return f"{int(item.get('point_valid', 0))}/{int(item.get('point_base_total', 0))}"
817
-
818
-
819
- def traj_ratio(item: dict[str, Any]) -> str:
820
- return f"{int(item.get('traj_with_valid_pred', 0))}/{int(item.get('traj_base_total', 0))}"
821
-
822
-
823
- def terminal_ratio(item: dict[str, Any]) -> str:
824
- return f"{int(item.get('valid_final', 0))}/{int(item.get('support', 0))}"
825
-
826
-
827
- def build_markdown(report: dict[str, Any]) -> str:
828
- config = report["config"]
829
- selected_buckets = list(config["buckets"])
830
- lines: list[str] = []
831
- lines.append("# Video-Progress Benchmark Evaluation")
832
- lines.append("")
833
- lines.append("## Protocol")
834
- lines.append("")
835
- lines.append(f"- eval_points: `{config['eval_points']}`")
836
- lines.append(f"- sample_hz: `{config['sample_hz']}`")
837
- lines.append(f"- success_threshold: `{config['success_threshold_percent']}`")
838
- lines.append(f"- interpolate_missing: `{config['interpolate_missing']}`")
839
- lines.append(f"- allow_missing: `{config['allow_missing']}`")
840
- lines.append(f"- no_missing_check: `{report['validation']['no_missing_check']}`")
841
- lines.append("- Curve metrics are trajectory-equal means over metric-valid trajectories.")
842
- lines.append("- VOC is reported only for expert bucket rows.")
843
- lines.append("- Local Direction AP uses adjacent released `semantic_anchors`; predictions are linearly interpolated at anchor frames.")
844
- lines.append("- By default, missing curve, terminal, or local-direction predictions stop evaluation; use `--allow-missing` only for diagnostics.")
845
- lines.append("")
846
-
847
- curve_rows: list[list[Any]] = []
848
- curve_sources = [("overall_4bucket", report["curve"]["overall_4bucket"])]
849
- for bucket in selected_buckets:
850
- curve_sources.append((bucket, report["curve"]["per_bucket"][bucket]))
851
- for scope, item in curve_sources:
852
- include_voc = scope in EXPERT_BUCKETS
853
- row = [
854
- scope,
855
- format_percent(item.get("point_coverage_to_base")),
856
- point_ratio(item),
857
- traj_ratio(item),
858
- format_metric(item.get("mae")),
859
- format_metric(item.get("prc")),
860
- ]
861
- if include_voc:
862
- row.append(format_metric(item.get("voc")))
863
- else:
864
- row.append("n/a")
865
- curve_rows.append(
866
- row
867
- )
868
- lines.append("## Curve Metrics")
869
- lines.append("")
870
- lines.append(
871
- markdown_table(
872
- ["scope", "coverage", "point_valid/base", "traj_valid/base", "MAE", "PRC", "VOC"],
873
- curve_rows,
874
- )
875
- )
876
- lines.append("")
877
-
878
- terminal_rows: list[list[Any]] = []
879
- terminal_sources = [
880
- ("overall_4bucket", report["terminal"]["overall_4bucket"]),
881
- ("seen_merged", report["terminal"]["seen_merged"]),
882
- ("unseen_merged", report["terminal"]["unseen_merged"]),
883
- ]
884
- for scope, item in terminal_sources:
885
- terminal_rows.append(
886
- [
887
- scope,
888
- terminal_ratio(item),
889
- format_metric(item.get("tsa")),
890
- format_metric(item.get("f1_success")),
891
- format_metric(item.get("f1_failure")),
892
- format_metric(item.get("macro_f1_terminal")),
893
- int(item.get("tp", 0)),
894
- int(item.get("fn", 0)),
895
- int(item.get("fp", 0)),
896
- int(item.get("tn", 0)),
897
- int(item.get("missing_final", 0)),
898
- ]
899
- )
900
- lines.append("## Terminal Metrics")
901
- lines.append("")
902
- lines.append(
903
- markdown_table(
904
- [
905
- "scope",
906
- "valid_final/support",
907
- "TSA",
908
- "F1_S",
909
- "F1_F",
910
- "MacroF1_T",
911
- "TP",
912
- "FN",
913
- "FP",
914
- "TN",
915
- "missing_final",
916
- ],
917
- terminal_rows,
918
- )
919
- )
920
- lines.append("")
921
-
922
- local_direction_rows: list[list[Any]] = []
923
- local_direction_sources = [
924
- ("overall_4bucket", report["local_direction_ap"]["overall_4bucket"]),
925
- ("seen_merged", report["local_direction_ap"]["seen_merged"]),
926
- ("unseen_merged", report["local_direction_ap"]["unseen_merged"]),
927
- ]
928
- for scope, item in local_direction_sources:
929
- gt_counts = item.get("gt_counts") or {}
930
- local_direction_rows.append(
931
- [
932
- scope,
933
- f"{int(item.get('valid', 0))}/{int(item.get('transition_total', 0))}",
934
- f"{int(gt_counts.get('positive', 0))}/{int(gt_counts.get('neutral', 0))}/{int(gt_counts.get('negative', 0))}",
935
- f"{int(item.get('ap_positive_support', 0))}/{int(item.get('ap_negative_support', 0))}",
936
- format_percent(item.get("ap_positive")),
937
- format_percent(item.get("ap_negative")),
938
- format_percent(item.get("macro_ap_d")),
939
- ]
940
- )
941
- lines.append("## Local Direction AP")
942
- lines.append("")
943
- tau_text = f"{float(report['local_direction_ap']['tau_percent']):g}%"
944
- lines.append(
945
- f"`tau={tau_text}`. "
946
- "`AP+ = AP(y=Delta_gt>tau, score=Delta_pred)`, "
947
- "`AP- = AP(y=Delta_gt<-tau, score=-Delta_pred)`, "
948
- "`MacroAP_D = (AP+ + AP-) / 2`."
949
- )
950
- lines.append("")
951
- lines.append(
952
- markdown_table(
953
- ["scope", "valid/trans", "GT +/0/-", "support +/-", "AP+", "AP-", "MacroAP_D"],
954
- local_direction_rows,
955
- )
956
- )
957
- lines.append("")
958
-
959
- lines.append("## Prediction Diagnostics")
960
- lines.append("")
961
- stats = report["prediction_input"]["stats"]
962
- diagnostic_rows = [[key, value] for key, value in sorted(stats.items())]
963
- lines.append(markdown_table(["key", "value"], diagnostic_rows))
964
- lines.append("")
965
- return "\n".join(lines)
966
-
967
-
968
- def run_self_test() -> None:
969
- def row(gid: str, gt_values: list[float], *, success: bool = True) -> dict[str, Any]:
970
- frames = [0, 30, 60]
971
- if not success:
972
- gt_values = [0.0, 20.0, 50.0]
973
- return {
974
- "global_episode_id": gid,
975
- "metadata": {
976
- "fps": 30.0,
977
- "start_idx": 0,
978
- "main_path": f"ARX-data/mock/videos/chunk-000/observation.images.front/{gid}",
979
- "available_views": ["front"],
980
- "task_instruction": "mock task",
981
- "task_description": "mock task",
982
- },
983
- "frame_index": {
984
- str(frame): {"front": f"__VLAC2_FRAMES_ROOT__/mock/{gid}/{frame}-90.jpg"}
985
- for frame in frames
986
- },
987
- "dense_kinematic_progress": {
988
- str(frame): value for frame, value in zip(frames, gt_values)
989
- },
990
- "semantic_anchors": [
991
- {"frame": frame, "human_annotated_progress": value}
992
- for frame, value in zip(frames, gt_values)
993
- ],
994
- }
995
-
996
- with tempfile.TemporaryDirectory() as tmp_dir:
997
- root = Path(tmp_dir) / "benchmark_splits"
998
- rows_by_bucket = {
999
- "test_expert_seen": [row("traj_success_a", [0.0, 50.0, 100.0])],
1000
- "test_expert_unseen": [row("traj_success_b", [0.0, 40.0, 100.0])],
1001
- "test_nonexpert_seen": [row("traj_failure_a", [0.0, 20.0, 50.0], success=False)],
1002
- "test_nonexpert_unseen": [row("traj_failure_b", [0.0, 10.0, 40.0], success=False)],
1003
- }
1004
- for bucket, rows in rows_by_bucket.items():
1005
- split_dir = root / bucket
1006
- split_dir.mkdir(parents=True)
1007
- (split_dir / "video_progress_benchmark_file.json").write_text(
1008
- json.dumps(rows),
1009
- encoding="utf-8",
1010
- )
1011
- pred_path = Path(tmp_dir) / "predictions.jsonl"
1012
- with pred_path.open("w", encoding="utf-8") as f:
1013
- for rows in rows_by_bucket.values():
1014
- for item in rows:
1015
- points = sorted(
1016
- (int(frame), float(value))
1017
- for frame, value in item["dense_kinematic_progress"].items()
1018
- )
1019
- f.write(
1020
- json.dumps(
1021
- {
1022
- "global_episode_id": item["global_episode_id"],
1023
- "frames": [frame for frame, _value in points],
1024
- "response": "\n".join(
1025
- f"时间: {idx:.1f}s, 进度: {value:g}%"
1026
- for idx, (_frame, value) in enumerate(points)
1027
- ),
1028
- },
1029
- ensure_ascii=False,
1030
- )
1031
- + "\n"
1032
- )
1033
- trajectories = build_trajectories(root, eval_points="time_hz", sample_hz=1.0)
1034
- pred_map, prediction_info = load_predictions(
1035
- pred_path,
1036
- trajectories=trajectories,
1037
- clip_range=None,
1038
- )
1039
- report = build_report(
1040
- trajectories=trajectories,
1041
- pred_map=pred_map,
1042
- prediction_info=prediction_info,
1043
- config={
1044
- "benchmark_root": str(root),
1045
- "predictions": str(pred_path),
1046
- "buckets": list(TEST_BUCKETS),
1047
- "eval_points": "time_hz",
1048
- "sample_hz": 1.0,
1049
- "success_threshold_percent": 90.0,
1050
- "interpolate_missing": False,
1051
- "clip_pred": None,
1052
- },
1053
- )
1054
- assert report["benchmark"]["traj_total"] == 4
1055
- assert report["curve"]["overall_4bucket"]["mae"] == 0.0
1056
- assert report["terminal"]["overall_4bucket"]["tsa"] == 1.0
1057
- assert report["local_direction_ap"]["overall_4bucket"]["ap_positive"] == 1.0
1058
- assert validate_no_missing(report)["no_missing_check"] is True
1059
- print("[self-test] ok")
1060
-
1061
-
1062
- def main() -> None:
1063
- args = parse_args()
1064
- if args.self_test:
1065
- run_self_test()
1066
- return
1067
- if args.predictions is None:
1068
- raise SystemExit("--predictions is required unless --self-test is set")
1069
- if args.out_json is None and args.out_md is None:
1070
- raise SystemExit("At least one of --out-json or --out-md is required")
1071
- if args.sample_hz <= 0:
1072
- raise SystemExit("--sample-hz must be positive")
1073
-
1074
- clip_range = None
1075
- if args.clip_pred is not None:
1076
- lo, hi = args.clip_pred
1077
- if lo > hi:
1078
- raise SystemExit("--clip-pred MIN must be <= MAX")
1079
- clip_range = (float(lo), float(hi))
1080
-
1081
- trajectories = build_trajectories(
1082
- args.benchmark_root,
1083
- buckets=args.buckets,
1084
- eval_points=args.eval_points,
1085
- sample_hz=float(args.sample_hz),
1086
- )
1087
- pred_map, prediction_info = load_predictions(
1088
- args.predictions,
1089
- trajectories=trajectories,
1090
- clip_range=clip_range,
1091
- )
1092
- config = {
1093
- "benchmark_root": str(args.benchmark_root),
1094
- "predictions": str(args.predictions),
1095
- "buckets": list(args.buckets),
1096
- "eval_points": args.eval_points,
1097
- "sample_hz": float(args.sample_hz) if args.eval_points == "time_hz" else None,
1098
- "success_threshold_percent": float(args.success_threshold),
1099
- "interpolate_missing": bool(args.interpolate_missing),
1100
- "allow_missing": bool(args.allow_missing),
1101
- "clip_pred": list(clip_range) if clip_range is not None else None,
1102
- }
1103
- report = build_report(
1104
- trajectories=trajectories,
1105
- pred_map=pred_map,
1106
- prediction_info=prediction_info,
1107
- config=config,
1108
- )
1109
- report["validation"] = validate_no_missing(report)
1110
- if not args.allow_missing and not report["validation"]["no_missing_check"]:
1111
- preview = "\n".join(report["validation"]["errors"][:20])
1112
- raise SystemExit(
1113
- "Predictions do not cover every required evaluation item. "
1114
- "Use --allow-missing only for a diagnostic report.\n"
1115
- f"{preview}"
1116
- )
1117
- if args.out_json is not None:
1118
- dump_json(args.out_json, report)
1119
- if args.out_md is not None:
1120
- args.out_md.parent.mkdir(parents=True, exist_ok=True)
1121
- args.out_md.write_text(build_markdown(report), encoding="utf-8")
1122
-
1123
- print(
1124
- json.dumps(
1125
- {
1126
- "traj_total": report["benchmark"]["traj_total"],
1127
- "point_total": report["benchmark"]["point_total"],
1128
- "curve_overall": report["curve"]["overall_4bucket"],
1129
- "terminal_overall": report["terminal"]["overall_4bucket"],
1130
- },
1131
- ensure_ascii=False,
1132
- indent=2,
1133
- )
1134
- )
1135
-
1136
-
1137
- if __name__ == "__main__":
1138
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
scripts/extract_vlac2_release_frames.py DELETED
@@ -1,394 +0,0 @@
1
- #!/usr/bin/env python3
2
- from __future__ import annotations
3
-
4
- import argparse
5
- import json
6
- import os
7
- import sys
8
- from concurrent.futures import ThreadPoolExecutor, as_completed
9
- from dataclasses import dataclass
10
- from pathlib import Path
11
- from typing import Any
12
-
13
- import tqdm
14
-
15
- SCRIPT_DIR = Path(__file__).resolve().parent
16
- if str(SCRIPT_DIR) not in sys.path:
17
- sys.path.insert(0, str(SCRIPT_DIR))
18
-
19
- from vlac2_release_common import (
20
- discover_benchmark_jsons,
21
- dump_json,
22
- ensure_generated_marker,
23
- infer_main_path_from_row,
24
- load_json,
25
- normalize_main_path,
26
- PORTABLE_IMAGE_ROOT,
27
- )
28
-
29
- try:
30
- import cv2 # type: ignore
31
- except ImportError:
32
- cv2 = None
33
-
34
- try:
35
- import imageio.v2 as imageio # type: ignore
36
- except ImportError:
37
- imageio = None
38
-
39
- try:
40
- import av # type: ignore
41
- except ImportError:
42
- av = None
43
-
44
-
45
- @dataclass(frozen=True)
46
- class EpisodeSpec:
47
- main_path: Path
48
-
49
-
50
- def parse_args() -> argparse.Namespace:
51
- parser = argparse.ArgumentParser(
52
- description="Extract the portable VLAC2 release benchmark episodes into a JPG tree."
53
- )
54
- parser.add_argument(
55
- "--data-root",
56
- type=Path,
57
- required=True,
58
- help="Directory containing the extracted raw benchmark videos.",
59
- )
60
- parser.add_argument(
61
- "--frames-root",
62
- type=Path,
63
- default=PORTABLE_IMAGE_ROOT,
64
- help="Directory where extracted benchmark frames will be written. Defaults to _extracted_frames under the release directory.",
65
- )
66
- parser.add_argument("--jobs", type=int, default=max(1, (os.cpu_count() or 8) // 2))
67
- parser.add_argument(
68
- "--overwrite-existing",
69
- action="store_true",
70
- help="Re-extract even if an output manifest says the target episode-view is already complete.",
71
- )
72
- return parser.parse_args()
73
-
74
-
75
- def bundled_release_root() -> Path:
76
- return SCRIPT_DIR.parent.resolve()
77
-
78
-
79
- def resolve_data_root(raw_arg: Path, release_root: Path) -> Path:
80
- return raw_arg.resolve() if raw_arg.is_absolute() else (release_root / raw_arg).resolve()
81
-
82
-
83
- def resolve_frames_root(raw_arg: Path, release_root: Path) -> Path:
84
- return raw_arg.resolve() if raw_arg.is_absolute() else (release_root / raw_arg).resolve()
85
-
86
-
87
- def require_decoder() -> None:
88
- if cv2 is None and imageio is None and av is None:
89
- raise SystemExit(
90
- "No video decoder available. Install opencv-python, PyAV, or imageio before running frame extraction."
91
- )
92
-
93
-
94
- def benchmark_files_from_root(benchmark_root: Path) -> list[Path]:
95
- files = discover_benchmark_jsons(benchmark_root)
96
- if not files:
97
- raise SystemExit(f"No benchmark json found under {benchmark_root}")
98
- return files
99
-
100
-
101
- def episode_group_key(main_path: Path) -> str:
102
- parts = list(main_path.parts)
103
- for idx, part in enumerate(parts):
104
- if part.startswith("observation.images.") and idx + 1 < len(parts):
105
- return str(Path(*parts[:idx], parts[idx + 1]))
106
- return str(main_path)
107
-
108
-
109
- def collect_episode_specs(benchmark_paths: list[Path]) -> tuple[list[EpisodeSpec], dict[str, Any]]:
110
- grouped: dict[str, tuple[Path, set[str]]] = {}
111
- stats = {
112
- "benchmark_files_total": len(benchmark_paths),
113
- "rows_total": 0,
114
- "rows_missing_main_path": 0,
115
- }
116
-
117
- for benchmark_path in benchmark_paths:
118
- rows = load_json(benchmark_path)
119
- if not isinstance(rows, list):
120
- raise ValueError(f"Expected list json: {benchmark_path}")
121
- stats["rows_total"] += len(rows)
122
- for row in rows:
123
- inferred_main_path = infer_main_path_from_row(row)
124
- if inferred_main_path is None:
125
- stats["rows_missing_main_path"] += 1
126
- continue
127
- normalized = normalize_main_path(inferred_main_path)
128
- # Keep different camera views for the same episode separate. The
129
- # benchmark's main_path can target wrist/head/bird/etc. views, and
130
- # merging by episode drops required frame directories.
131
- key = str(normalized)
132
- if key not in grouped:
133
- grouped[key] = (normalized, {str(benchmark_path)})
134
- else:
135
- grouped[key][1].add(str(benchmark_path))
136
-
137
- specs = [
138
- EpisodeSpec(main_path=main_path)
139
- for _group_key, (main_path, _sources) in sorted(grouped.items())
140
- ]
141
- stats["episodes_unique"] = len(specs)
142
- return specs, stats
143
-
144
-
145
- def resolve_main_video(raw_root: Path, main_path: Path) -> Path:
146
- candidate = raw_root / main_path
147
- if candidate.suffix == ".mp4":
148
- return candidate
149
-
150
- # Keep the full main_path leaf intact when appending ".mp4" so episode
151
- # identifiers containing dots (for example timestamps like "....311186")
152
- # are not truncated. Fall back to with_suffix(".mp4") for compatibility
153
- # with any legacy raw layouts that already dropped the tail suffix.
154
- preferred = Path(f"{candidate}.mp4")
155
- legacy = candidate.with_suffix(".mp4")
156
- if preferred.exists() or preferred == legacy:
157
- return preferred
158
- if legacy.exists():
159
- return legacy
160
- return preferred
161
-
162
-
163
- def discover_view_videos(raw_root: Path, main_path: Path) -> list[Path]:
164
- main_video = resolve_main_video(raw_root, main_path)
165
- if not main_video.exists():
166
- raise FileNotFoundError(f"Missing raw video: {main_video}")
167
- return [main_video]
168
-
169
-
170
- def manifest_path_for(output_dir: Path) -> Path:
171
- return output_dir / ".vlac_extract_manifest.json"
172
-
173
-
174
- def output_dir_from_video(raw_root: Path, output_root: Path, video_path: Path) -> Path:
175
- relative = video_path.relative_to(raw_root).with_suffix("")
176
- return output_root / relative
177
-
178
-
179
- def is_complete(output_dir: Path, source_video: Path) -> bool:
180
- manifest_path = manifest_path_for(output_dir)
181
- if not manifest_path.exists():
182
- return False
183
- try:
184
- manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
185
- except Exception:
186
- return False
187
-
188
- frame_count = int(manifest.get("frame_count") or 0)
189
- if frame_count <= 0:
190
- return False
191
- source_mtime_ns = int(source_video.stat().st_mtime_ns)
192
- source_size = int(source_video.stat().st_size)
193
- if int(manifest.get("source_mtime_ns") or -1) != source_mtime_ns:
194
- return False
195
- if int(manifest.get("source_size") or -1) != source_size:
196
- return False
197
-
198
- jpg_files = sorted(output_dir.glob("*.jpg"))
199
- return len(jpg_files) == frame_count
200
-
201
-
202
- def clear_output_dir(output_dir: Path) -> None:
203
- if not output_dir.exists():
204
- return
205
- for pattern in ("*.jpg", "frame_*.jpg", ".vlac_extract_manifest.json"):
206
- for path in output_dir.glob(pattern):
207
- if path.is_file():
208
- path.unlink()
209
-
210
-
211
- def write_manifest(output_dir: Path, source_video: Path, frame_count: int) -> None:
212
- manifest = {
213
- "source_video": str(source_video),
214
- "source_size": int(source_video.stat().st_size),
215
- "source_mtime_ns": int(source_video.stat().st_mtime_ns),
216
- "frame_count": int(frame_count),
217
- }
218
- manifest_path_for(output_dir).write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
219
-
220
-
221
- def extract_with_cv2(source_video: Path, output_dir: Path) -> int:
222
- assert cv2 is not None
223
- capture = cv2.VideoCapture(str(source_video))
224
- if not capture.isOpened():
225
- raise RuntimeError(f"cv2 failed to open {source_video}")
226
-
227
- temp_paths: list[Path] = []
228
- frame_idx = 0
229
- try:
230
- while True:
231
- ok, frame = capture.read()
232
- if not ok:
233
- break
234
- temp_path = output_dir / f"frame_{frame_idx:06d}.jpg"
235
- if not cv2.imwrite(str(temp_path), frame):
236
- raise RuntimeError(f"cv2 failed to write {temp_path}")
237
- temp_paths.append(temp_path)
238
- frame_idx += 1
239
- finally:
240
- capture.release()
241
-
242
- for idx, temp_path in enumerate(temp_paths):
243
- temp_path.rename(output_dir / f"{idx}-{frame_idx}.jpg")
244
- return frame_idx
245
-
246
-
247
- def extract_with_imageio(source_video: Path, output_dir: Path) -> int:
248
- assert imageio is not None
249
- temp_paths: list[Path] = []
250
- frame_idx = 0
251
- try:
252
- for frame in imageio.get_reader(str(source_video)):
253
- temp_path = output_dir / f"frame_{frame_idx:06d}.jpg"
254
- imageio.imwrite(str(temp_path), frame)
255
- temp_paths.append(temp_path)
256
- frame_idx += 1
257
- except Exception as exc:
258
- if frame_idx == 0:
259
- raise RuntimeError(f"imageio failed to decode {source_video}: {exc}") from exc
260
- raise
261
- for idx, temp_path in enumerate(temp_paths):
262
- temp_path.rename(output_dir / f"{idx}-{frame_idx}.jpg")
263
- return frame_idx
264
-
265
-
266
- def extract_with_av(source_video: Path, output_dir: Path) -> int:
267
- assert av is not None
268
- container = av.open(str(source_video))
269
- temp_paths: list[Path] = []
270
- frame_idx = 0
271
- try:
272
- for frame in container.decode(video=0):
273
- temp_path = output_dir / f"frame_{frame_idx:06d}.jpg"
274
- frame.to_image().save(temp_path, format="JPEG")
275
- temp_paths.append(temp_path)
276
- frame_idx += 1
277
- finally:
278
- container.close()
279
-
280
- for idx, temp_path in enumerate(temp_paths):
281
- temp_path.rename(output_dir / f"{idx}-{frame_idx}.jpg")
282
- return frame_idx
283
-
284
-
285
- def extract_one_video(source_video: Path, output_dir: Path, overwrite_existing: bool) -> dict[str, Any]:
286
- if not overwrite_existing and is_complete(output_dir, source_video):
287
- manifest = json.loads(manifest_path_for(output_dir).read_text(encoding="utf-8"))
288
- return {
289
- "source_video": str(source_video),
290
- "output_dir": str(output_dir),
291
- "frame_count": int(manifest["frame_count"]),
292
- "status": "skipped_existing",
293
- }
294
-
295
- output_dir.mkdir(parents=True, exist_ok=True)
296
- clear_output_dir(output_dir)
297
- if cv2 is not None:
298
- frame_count = extract_with_cv2(source_video, output_dir)
299
- if frame_count == 0 and av is not None:
300
- clear_output_dir(output_dir)
301
- frame_count = extract_with_av(source_video, output_dir)
302
- if frame_count == 0 and imageio is not None:
303
- clear_output_dir(output_dir)
304
- frame_count = extract_with_imageio(source_video, output_dir)
305
- elif av is not None:
306
- frame_count = extract_with_av(source_video, output_dir)
307
- elif imageio is not None:
308
- frame_count = extract_with_imageio(source_video, output_dir)
309
- else:
310
- raise RuntimeError("No available decoder")
311
- if frame_count <= 0:
312
- raise RuntimeError(f"Decoder produced zero frames for {source_video}")
313
- write_manifest(output_dir, source_video, frame_count)
314
- return {
315
- "source_video": str(source_video),
316
- "output_dir": str(output_dir),
317
- "frame_count": frame_count,
318
- "status": "extracted",
319
- }
320
-
321
-
322
-
323
-
324
- def main() -> None:
325
- args = parse_args()
326
- require_decoder()
327
-
328
- release_root = bundled_release_root()
329
- benchmark_root = (release_root / "benchmark_splits").resolve()
330
- if not benchmark_root.exists():
331
- raise SystemExit(f"Missing benchmark_splits under {release_root}")
332
- data_root = resolve_data_root(args.data_root, release_root)
333
- output_root = resolve_frames_root(args.frames_root, release_root)
334
- ensure_generated_marker(output_root)
335
- benchmark_paths = benchmark_files_from_root(benchmark_root)
336
-
337
- specs, stats = collect_episode_specs(benchmark_paths)
338
- jobs: list[tuple[Path, Path]] = []
339
- missing_raw_episodes: list[dict[str, str]] = []
340
- for spec in specs:
341
- try:
342
- view_videos = discover_view_videos(data_root, spec.main_path)
343
- except FileNotFoundError as exc:
344
- missing_raw_episodes.append(
345
- {
346
- "main_path": str(spec.main_path),
347
- "error": str(exc),
348
- }
349
- )
350
- continue
351
- for video_path in view_videos:
352
- jobs.append((video_path, output_dir_from_video(data_root, output_root, video_path)))
353
-
354
- results: list[dict[str, Any]] = []
355
- with ThreadPoolExecutor(max_workers=max(1, args.jobs)) as executor:
356
- future_to_job = {
357
- executor.submit(extract_one_video, video_path, output_dir, args.overwrite_existing): (video_path, output_dir)
358
- for video_path, output_dir in jobs
359
- }
360
- for future in tqdm.tqdm(as_completed(future_to_job), total=len(future_to_job), desc="Extract release frames"):
361
- video_path, output_dir = future_to_job[future]
362
- try:
363
- results.append(future.result())
364
- except Exception as exc:
365
- results.append(
366
- {
367
- "source_video": str(video_path),
368
- "output_dir": str(output_dir),
369
- "status": "error",
370
- "error": str(exc),
371
- }
372
- )
373
-
374
- summary = {
375
- **stats,
376
- "release_root": str(release_root),
377
- "benchmark_root": str(benchmark_root),
378
- "data_root": str(data_root),
379
- "output_root": str(output_root),
380
- "benchmark_files": [str(path) for path in benchmark_paths],
381
- "jobs_total": len(jobs),
382
- "jobs_extracted": sum(1 for row in results if row["status"] == "extracted"),
383
- "jobs_skipped_existing": sum(1 for row in results if row["status"] == "skipped_existing"),
384
- "jobs_failed": sum(1 for row in results if row["status"] == "error"),
385
- "missing_raw_episodes": missing_raw_episodes,
386
- "results": results,
387
- }
388
- summary_path = output_root / "frame_extraction_summary.json"
389
- dump_json(summary_path, summary)
390
- print(f"[frame-extraction] {summary_path}")
391
-
392
-
393
- if __name__ == "__main__":
394
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
scripts/run_vlac_cut_batch.py DELETED
@@ -1,352 +0,0 @@
1
- #!/usr/bin/env python3
2
- from __future__ import annotations
3
-
4
- import argparse
5
- import json
6
- import os
7
- from pathlib import Path
8
- from typing import Any
9
-
10
-
11
- def parse_args() -> argparse.Namespace:
12
- parser = argparse.ArgumentParser(
13
- description="Run VLAC-Cut batch inference from a public VPB evaluation manifest."
14
- )
15
- parser.add_argument(
16
- "--model-path",
17
- type=Path,
18
- required=True,
19
- help="Path to the released VLAC-Cut model directory.",
20
- )
21
- parser.add_argument(
22
- "--manifest",
23
- type=Path,
24
- required=True,
25
- help="JSONL file produced by build_vlac_cut_eval_manifest.py.",
26
- )
27
- parser.add_argument(
28
- "--out",
29
- type=Path,
30
- required=True,
31
- help="Output prediction JSONL path.",
32
- )
33
- parser.add_argument(
34
- "--limit",
35
- type=int,
36
- default=None,
37
- help="Optional maximum number of manifest rows to run.",
38
- )
39
- parser.add_argument(
40
- "--resume",
41
- action="store_true",
42
- help="Append to --out and skip global_episode_id values already present in it.",
43
- )
44
- parser.add_argument(
45
- "--max-new-tokens",
46
- type=int,
47
- default=1024,
48
- help="Generation cap for each response.",
49
- )
50
- parser.add_argument(
51
- "--device-map",
52
- default="auto",
53
- help="Device map passed to Transformers from_pretrained.",
54
- )
55
- parser.add_argument(
56
- "--dtype",
57
- default=None,
58
- help="Torch dtype passed to Transformers. Defaults to auto.",
59
- )
60
- parser.add_argument(
61
- "--attn-implementation",
62
- default=None,
63
- help="Optional attention implementation passed to Transformers, for example flash_attention_2 or sdpa.",
64
- )
65
- parser.add_argument(
66
- "--check-files",
67
- action="store_true",
68
- help="Fail before inference if any manifest image path is missing.",
69
- )
70
- return parser.parse_args()
71
-
72
-
73
- def load_transformers_runtime():
74
- os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
75
- os.environ.setdefault("IMAGE_MAX_TOKEN_NUM", "256")
76
- os.environ.setdefault("VIDEO_MAX_TOKEN_NUM", "256")
77
- os.environ.setdefault("VIDEO_MIN_TOKEN_NUM", "4")
78
- os.environ.setdefault("QWEN_VL_UTILS_MAX_FRAME_LIST", "0")
79
-
80
- try:
81
- import torch
82
- except ImportError as exc:
83
- raise SystemExit("Missing dependency: torch is required for VLAC-Cut inference.") from exc
84
-
85
- try:
86
- from transformers import AutoModelForImageTextToText, AutoProcessor
87
- except ImportError as exc:
88
- raise SystemExit("Missing dependency: transformers is required for VLAC-Cut inference.") from exc
89
-
90
- return torch, AutoModelForImageTextToText, AutoProcessor
91
-
92
-
93
- def iter_jsonl(path: Path):
94
- with path.open("r", encoding="utf-8") as f:
95
- for line_no, line in enumerate(f, start=1):
96
- raw = line.strip()
97
- if not raw:
98
- continue
99
- item = json.loads(raw)
100
- if not isinstance(item, dict):
101
- raise ValueError(f"{path}:{line_no} is not a JSON object")
102
- yield line_no, item
103
-
104
-
105
- def existing_global_episode_ids(path: Path) -> set[str]:
106
- if not path.exists():
107
- return set()
108
- done: set[str] = set()
109
- for _line_no, row in iter_jsonl(path):
110
- gid = str(row.get("global_episode_id") or "").strip()
111
- if gid:
112
- done.add(gid)
113
- return done
114
-
115
-
116
- def require_manifest_row(row: dict[str, Any], line_no: int, *, check_files: bool) -> tuple[str, list[int], list[str], str, float]:
117
- gid = str(row.get("global_episode_id") or "").strip()
118
- if not gid:
119
- raise ValueError(f"manifest line {line_no}: missing global_episode_id")
120
-
121
- frames_raw = row.get("frames")
122
- if not isinstance(frames_raw, list) or not frames_raw:
123
- raise ValueError(f"manifest line {line_no}: missing non-empty frames")
124
- try:
125
- frames = [int(frame) for frame in frames_raw]
126
- except (TypeError, ValueError) as exc:
127
- raise ValueError(f"manifest line {line_no}: frames must be integers") from exc
128
-
129
- image_paths_raw = row.get("image_paths")
130
- if not isinstance(image_paths_raw, list) or len(image_paths_raw) != len(frames):
131
- raise ValueError(f"manifest line {line_no}: image_paths must align with frames")
132
- image_paths = [str(path) for path in image_paths_raw]
133
- if check_files:
134
- missing = [path for path in image_paths if not Path(path).exists()]
135
- if missing:
136
- preview = ", ".join(missing[:3])
137
- raise FileNotFoundError(f"manifest line {line_no}: missing image files: {preview}")
138
-
139
- prompt = str(row.get("vlac_cut_prompt") or "").strip()
140
- if not prompt:
141
- raise ValueError(f"manifest line {line_no}: missing vlac_cut_prompt")
142
-
143
- sample_hz_raw = row.get("input_sample_hz", row.get("sample_hz", 2.0))
144
- try:
145
- sample_hz = float(sample_hz_raw)
146
- except (TypeError, ValueError) as exc:
147
- raise ValueError(f"manifest line {line_no}: invalid input_sample_hz") from exc
148
- if sample_hz <= 0:
149
- raise ValueError(f"manifest line {line_no}: input_sample_hz must be positive")
150
- return gid, frames, image_paths, prompt, sample_hz
151
-
152
-
153
- def load_model_and_processor(
154
- *,
155
- model_path: Path,
156
- device_map: str,
157
- dtype: str | None,
158
- attn_implementation: str | None,
159
- ):
160
- _torch, AutoModelForImageTextToText, AutoProcessor = load_transformers_runtime()
161
- processor = AutoProcessor.from_pretrained(str(model_path))
162
-
163
- model_kwargs: dict[str, Any] = {
164
- "device_map": device_map,
165
- "dtype": dtype or "auto",
166
- }
167
- if attn_implementation:
168
- model_kwargs["attn_implementation"] = attn_implementation
169
-
170
- try:
171
- model = AutoModelForImageTextToText.from_pretrained(str(model_path), **model_kwargs)
172
- except TypeError as exc:
173
- if "dtype" not in str(exc):
174
- raise
175
- model_kwargs["torch_dtype"] = model_kwargs.pop("dtype")
176
- model = AutoModelForImageTextToText.from_pretrained(str(model_path), **model_kwargs)
177
- if getattr(model, "generation_config", None) is not None:
178
- for key in ("temperature", "top_p", "top_k"):
179
- if hasattr(model.generation_config, key):
180
- setattr(model.generation_config, key, None)
181
- model.eval()
182
- return model, processor
183
-
184
-
185
- def infer_one(
186
- *,
187
- model,
188
- processor,
189
- image_paths: list[str],
190
- prompt: str,
191
- sample_hz: float,
192
- max_new_tokens: int,
193
- ) -> str:
194
- messages = [
195
- {
196
- "role": "user",
197
- "content": [
198
- {"type": "video", "video": image_paths},
199
- {"type": "text", "text": prompt},
200
- ],
201
- }
202
- ]
203
- text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
204
- video_metadata = {
205
- "total_num_frames": len(image_paths),
206
- "fps": float(sample_hz),
207
- "frames_indices": list(range(len(image_paths))),
208
- }
209
- inputs = processor(
210
- text=[text],
211
- videos=[[image_paths]],
212
- padding=True,
213
- return_tensors="pt",
214
- return_metadata=True,
215
- do_sample_frames=False,
216
- video_metadata=video_metadata,
217
- )
218
- normalize_qwen3_video_grid(inputs)
219
- inputs = inputs.to(model.device)
220
- inputs.pop("video_metadata", None)
221
-
222
- generated_ids = model.generate(
223
- **inputs,
224
- max_new_tokens=int(max_new_tokens),
225
- do_sample=False,
226
- )
227
- generated_ids_trimmed = [
228
- output_ids[len(input_ids) :] for input_ids, output_ids in zip(inputs.input_ids, generated_ids, strict=True)
229
- ]
230
- return str(
231
- processor.batch_decode(
232
- generated_ids_trimmed,
233
- skip_special_tokens=True,
234
- clean_up_tokenization_spaces=False,
235
- )[0]
236
- )
237
-
238
-
239
- def count_token_type_spans(token_type_ids, token_type: int) -> int:
240
- values = token_type_ids.tolist()
241
- count = 0
242
- previous = None
243
- for value in values:
244
- if value == token_type and previous != token_type:
245
- count += 1
246
- previous = value
247
- return count
248
-
249
-
250
- def normalize_qwen3_video_grid(inputs) -> None:
251
- mm_token_type_ids = inputs.get("mm_token_type_ids")
252
- video_grid_thw = inputs.get("video_grid_thw")
253
- if mm_token_type_ids is None or video_grid_thw is None:
254
- return
255
- if len(mm_token_type_ids) != 1 or len(video_grid_thw) != 1:
256
- return
257
-
258
- video_span_count = count_token_type_spans(mm_token_type_ids[0], 2)
259
- if video_span_count <= 1:
260
- return
261
-
262
- grid = video_grid_thw[0]
263
- temporal = int(grid[0].item())
264
- if temporal % video_span_count != 0:
265
- return
266
-
267
- split_temporal = temporal // video_span_count
268
- expanded = grid.repeat(video_span_count, 1)
269
- expanded[:, 0] = split_temporal
270
- inputs["video_grid_thw"] = expanded
271
-
272
-
273
- def main() -> int:
274
- args = parse_args()
275
- model_path = args.model_path.resolve()
276
- manifest_path = args.manifest.resolve()
277
- out_path = args.out.resolve()
278
-
279
- if not model_path.exists():
280
- raise SystemExit(f"Missing model path: {model_path}")
281
- if not manifest_path.exists():
282
- raise SystemExit(f"Missing manifest: {manifest_path}")
283
- if args.limit is not None and args.limit <= 0:
284
- raise SystemExit("--limit must be positive when provided")
285
-
286
- done = existing_global_episode_ids(out_path) if args.resume else set()
287
- out_path.parent.mkdir(parents=True, exist_ok=True)
288
- mode = "a" if args.resume else "w"
289
-
290
- model, processor = load_model_and_processor(
291
- model_path=model_path,
292
- device_map=str(args.device_map),
293
- dtype=args.dtype,
294
- attn_implementation=args.attn_implementation,
295
- )
296
-
297
- processed = 0
298
- skipped = 0
299
- with out_path.open(mode, encoding="utf-8") as out_f:
300
- for line_no, row in iter_jsonl(manifest_path):
301
- gid, frames, image_paths, prompt, sample_hz = require_manifest_row(
302
- row,
303
- line_no,
304
- check_files=bool(args.check_files),
305
- )
306
- if gid in done:
307
- skipped += 1
308
- continue
309
- if args.limit is not None and processed >= args.limit:
310
- break
311
-
312
- response = infer_one(
313
- model=model,
314
- processor=processor,
315
- image_paths=image_paths,
316
- prompt=prompt,
317
- sample_hz=sample_hz,
318
- max_new_tokens=int(args.max_new_tokens),
319
- )
320
- out_f.write(
321
- json.dumps(
322
- {
323
- "global_episode_id": gid,
324
- "frames": frames,
325
- "response": str(response or ""),
326
- },
327
- ensure_ascii=False,
328
- )
329
- + "\n"
330
- )
331
- out_f.flush()
332
- processed += 1
333
- print(f"processed={processed} global_episode_id={gid}", flush=True)
334
-
335
- print(
336
- json.dumps(
337
- {
338
- "manifest": str(manifest_path),
339
- "out": str(out_path),
340
- "backend": "transformers",
341
- "processed": processed,
342
- "skipped_existing": skipped,
343
- },
344
- ensure_ascii=False,
345
- indent=2,
346
- )
347
- )
348
- return 0
349
-
350
-
351
- if __name__ == "__main__":
352
- raise SystemExit(main())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
scripts/unpack_data.sh DELETED
@@ -1,52 +0,0 @@
1
- #!/usr/bin/env bash
2
- set -euo pipefail
3
-
4
- ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
5
- ARCHIVE_DIR="${ROOT_DIR}/data"
6
- DATA_ROOT="${1:-${ROOT_DIR}/data}"
7
- EXPECTED_BASES=(
8
- "test_videos"
9
- "train_videos"
10
- )
11
-
12
- mkdir -p "${DATA_ROOT}"
13
-
14
- archives=()
15
- for base in "${EXPECTED_BASES[@]}"; do
16
- matches=()
17
- for suffix in ".tar" ".tar.zst"; do
18
- candidate="${ARCHIVE_DIR}/${base}${suffix}"
19
- if [[ -f "${candidate}" ]]; then
20
- matches+=("${candidate}")
21
- fi
22
- done
23
-
24
- if [[ "${#matches[@]}" -eq 0 ]]; then
25
- echo "missing expected archive under ${ARCHIVE_DIR}: ${base}.tar or ${base}.tar.zst" >&2
26
- exit 1
27
- fi
28
- if [[ "${#matches[@]}" -gt 1 ]]; then
29
- echo "found multiple archive variants for ${base} under ${ARCHIVE_DIR}; keep only one of .tar or .tar.zst" >&2
30
- exit 1
31
- fi
32
-
33
- archives+=("${matches[0]}")
34
- done
35
-
36
- for archive in "${archives[@]}"; do
37
- echo "extracting ${archive}"
38
- case "${archive}" in
39
- *.tar.zst)
40
- tar --zstd -xf "${archive}" -C "${DATA_ROOT}"
41
- ;;
42
- *.tar)
43
- tar -xf "${archive}" -C "${DATA_ROOT}"
44
- ;;
45
- *)
46
- echo "unsupported archive format: ${archive}" >&2
47
- exit 1
48
- ;;
49
- esac
50
- done
51
-
52
- echo "raw data extracted into ${DATA_ROOT}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
scripts/vlac2_release_common.py DELETED
@@ -1,261 +0,0 @@
1
- #!/usr/bin/env python3
2
- from __future__ import annotations
3
-
4
- import json
5
- from pathlib import Path
6
- from typing import Any, Callable
7
-
8
-
9
- KNOWN_DATASET_NAMES = (
10
- "ARX-data",
11
- "dex_fold_v2_mix",
12
- "droid_lerobot",
13
- "libero",
14
- "libero_zty50",
15
- "VLABench_5",
16
- )
17
- KNOWN_VIDEO_SUFFIXES = {".mp4", ".avi", ".mov", ".mkv", ".webm"}
18
- PORTABLE_IMAGE_ROOT = Path("_extracted_frames")
19
- LEGACY_PORTABLE_IMAGE_ROOTS = (
20
- Path("extracted_frames"),
21
- Path("progress_data") / "VLAC_preprocessed_data" / "data",
22
- )
23
- GENERATED_MARKER_FILENAME = "_GENERATED"
24
- PUBLIC_BENCHMARK_JSON_NAME = "video_progress_benchmark_file.json"
25
- PUBLIC_RELEASE_ROOT_PLACEHOLDER = "__VLAC2_RELEASE_ROOT__"
26
- PUBLIC_FRAMES_ROOT_PLACEHOLDER = "__VLAC2_FRAMES_ROOT__"
27
- PUBLIC_BENCHMARK_DIRNAME = "benchmark_splits"
28
- LEGACY_BENCHMARK_DIRNAME = "benchmark_json"
29
-
30
-
31
- def portable_image_roots() -> tuple[Path, ...]:
32
- roots = [PORTABLE_IMAGE_ROOT, *LEGACY_PORTABLE_IMAGE_ROOTS]
33
- deduped: list[Path] = []
34
- seen: set[tuple[str, ...]] = set()
35
- for root in roots:
36
- key = root.parts
37
- if key in seen:
38
- continue
39
- seen.add(key)
40
- deduped.append(root)
41
- return tuple(deduped)
42
-
43
-
44
- def load_json(path: Path) -> Any:
45
- return json.loads(path.read_text(encoding="utf-8"))
46
-
47
-
48
- def dump_json(path: Path, payload: Any) -> None:
49
- path.parent.mkdir(parents=True, exist_ok=True)
50
- path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
51
-
52
-
53
- def ensure_generated_marker(output_root: Path) -> Path:
54
- output_root.mkdir(parents=True, exist_ok=True)
55
- marker_path = output_root / GENERATED_MARKER_FILENAME
56
- marker_path.write_text(
57
- "This directory is generated by the VLAC2 public frame-extraction workflow.\n",
58
- encoding="utf-8",
59
- )
60
- return marker_path
61
-
62
-
63
- def ensure_release_tree(release_root: Path) -> dict[str, Path]:
64
- release_root = release_root.resolve()
65
- paths = {
66
- "release_root": release_root,
67
- "raw_root": release_root / "data",
68
- "benchmark_root": release_root / PUBLIC_BENCHMARK_DIRNAME,
69
- "portable_image_root": release_root / PORTABLE_IMAGE_ROOT,
70
- "scripts_root": release_root / "scripts",
71
- }
72
- for key in ("release_root", "raw_root", "benchmark_root", "scripts_root"):
73
- paths[key].mkdir(parents=True, exist_ok=True)
74
- return paths
75
-
76
-
77
- def _normalized_parts(raw_path: str | Path) -> list[str]:
78
- raw = str(raw_path or "").strip().replace("\\", "/")
79
- if not raw:
80
- raise ValueError("empty path")
81
- return [part for part in Path(raw).parts if part not in ("", ".", "/")]
82
-
83
-
84
- def dataset_relative_path(raw_path: str | Path) -> Path:
85
- parts = _normalized_parts(raw_path)
86
-
87
- for idx, part in enumerate(parts):
88
- if part in KNOWN_DATASET_NAMES:
89
- return Path(*parts[idx:])
90
-
91
- for portable_root in portable_image_roots():
92
- marker_parts = list(portable_root.parts)
93
- marker_len = len(marker_parts)
94
- for idx in range(max(0, len(parts) - marker_len + 1)):
95
- if parts[idx : idx + marker_len] == marker_parts:
96
- tail = parts[idx + marker_len :]
97
- if not tail:
98
- break
99
- for tail_idx, part in enumerate(tail):
100
- if part in KNOWN_DATASET_NAMES:
101
- return Path(*tail[tail_idx:])
102
- return Path(*tail)
103
-
104
- return Path(*parts)
105
-
106
-
107
- def normalize_main_path(raw_main_path: str | Path) -> Path:
108
- rel = dataset_relative_path(raw_main_path)
109
- if rel.suffix.lower() in KNOWN_VIDEO_SUFFIXES:
110
- return rel.with_suffix("")
111
- return rel
112
-
113
-
114
- def main_path_from_frame_path(raw_frame_path: str | Path) -> Path:
115
- rel = dataset_relative_path(raw_frame_path)
116
- if rel.suffix:
117
- return rel.parent
118
- return rel
119
-
120
-
121
- def portable_frame_path_from_any(raw_frame_path: str | Path) -> Path:
122
- return PORTABLE_IMAGE_ROOT / dataset_relative_path(raw_frame_path)
123
-
124
-
125
- def placeholder_frame_path_from_any(raw_frame_path: str | Path) -> str:
126
- return f"{PUBLIC_FRAMES_ROOT_PLACEHOLDER}/{dataset_relative_path(raw_frame_path).as_posix()}"
127
-
128
-
129
- def absolute_frame_path_from_any(raw_frame_path: str | Path, frames_root: Path) -> Path:
130
- raw = str(raw_frame_path or "").strip()
131
- if not raw:
132
- raise ValueError("empty frame path")
133
- path = Path(raw)
134
- if path.is_absolute():
135
- return path
136
-
137
- parts = _normalized_parts(raw)
138
- if parts and parts[0] in (PUBLIC_FRAMES_ROOT_PLACEHOLDER, PUBLIC_RELEASE_ROOT_PLACEHOLDER):
139
- parts = parts[1:]
140
-
141
- for portable_root in portable_image_roots():
142
- marker_parts = list(portable_root.parts)
143
- if parts[: len(marker_parts)] == marker_parts:
144
- return frames_root.resolve() / Path(*parts[len(marker_parts) :])
145
- if parts and parts[0] in KNOWN_DATASET_NAMES:
146
- return frames_root.resolve() / Path(*parts)
147
- return frames_root.resolve() / Path(*parts)
148
-
149
-
150
- def rewrite_benchmark_image_paths(
151
- rows: list[dict[str, Any]],
152
- path_rewriter: Callable[[str], str],
153
- ) -> list[dict[str, Any]]:
154
- rewritten_rows: list[dict[str, Any]] = []
155
- for row in rows:
156
- rewritten = dict(row)
157
-
158
- frame_index = dict(row.get("frame_index") or {})
159
- if frame_index:
160
- rewritten_frame_index: dict[str, dict[str, str]] = {}
161
- for frame_idx, images in frame_index.items():
162
- image_map = dict(images or {})
163
- rewritten_frame_index[str(frame_idx)] = {
164
- str(view): path_rewriter(str(image_path))
165
- for view, image_path in image_map.items()
166
- if str(image_path or "").strip()
167
- }
168
- rewritten["frame_index"] = rewritten_frame_index
169
-
170
- reference_context = row.get("reference_context")
171
- if isinstance(reference_context, dict):
172
- rewritten_ref = dict(reference_context)
173
- anchors = list(reference_context.get("reference_anchors") or [])
174
- rewritten_anchors: list[dict[str, Any]] = []
175
- for anchor in anchors:
176
- rewritten_anchor = dict(anchor)
177
- images = dict(anchor.get("images") or {})
178
- if images:
179
- rewritten_anchor["images"] = {
180
- str(view): path_rewriter(str(image_path))
181
- for view, image_path in images.items()
182
- if str(image_path or "").strip()
183
- }
184
- rewritten_anchors.append(rewritten_anchor)
185
- rewritten_ref["reference_anchors"] = rewritten_anchors
186
- rewritten["reference_context"] = rewritten_ref
187
-
188
- videos = row.get("videos")
189
- if isinstance(videos, list):
190
- rewritten_videos: list[Any] = []
191
- for item in videos:
192
- if isinstance(item, list):
193
- rewritten_videos.append(
194
- [path_rewriter(str(path)) for path in item if str(path or "").strip()]
195
- )
196
- elif isinstance(item, str) and item.strip():
197
- rewritten_videos.append(path_rewriter(item))
198
- rewritten["videos"] = rewritten_videos
199
-
200
- images = row.get("images")
201
- if isinstance(images, list):
202
- rewritten["images"] = [
203
- path_rewriter(str(path))
204
- for path in images
205
- if str(path or "").strip()
206
- ]
207
-
208
- rewritten_rows.append(rewritten)
209
- return rewritten_rows
210
-
211
-
212
- def infer_main_path_from_row(row: dict[str, Any]) -> Path | None:
213
- for meta_key in ("metadata", "_meta", "meta"):
214
- meta = row.get(meta_key)
215
- if isinstance(meta, dict):
216
- raw_main_path = str(meta.get("main_path") or "").strip()
217
- if raw_main_path:
218
- return normalize_main_path(raw_main_path)
219
-
220
- frame_index = row.get("frame_index")
221
- if isinstance(frame_index, dict):
222
- for images in frame_index.values():
223
- if not isinstance(images, dict):
224
- continue
225
- for image_path in images.values():
226
- if str(image_path or "").strip():
227
- return main_path_from_frame_path(str(image_path))
228
-
229
- videos = row.get("videos")
230
- if isinstance(videos, list) and videos:
231
- first = videos[0]
232
- if isinstance(first, list) and first:
233
- return main_path_from_frame_path(str(first[0]))
234
- if isinstance(first, str) and first.strip():
235
- return main_path_from_frame_path(first)
236
-
237
- return None
238
-
239
-
240
- def discover_benchmark_jsons(benchmark_root: Path) -> list[Path]:
241
- benchmark_root = benchmark_root.resolve()
242
- candidates: list[Path] = []
243
- seen: set[Path] = set()
244
- for path in sorted(benchmark_root.glob(f"**/{PUBLIC_BENCHMARK_JSON_NAME}")):
245
- resolved = path.resolve()
246
- if resolved in seen:
247
- continue
248
- seen.add(resolved)
249
- candidates.append(resolved)
250
- return candidates
251
-
252
-
253
- def resolve_benchmark_root(release_root: Path) -> Path:
254
- release_root = release_root.resolve()
255
- preferred = release_root / PUBLIC_BENCHMARK_DIRNAME
256
- legacy = release_root / LEGACY_BENCHMARK_DIRNAME
257
- if preferred.exists():
258
- return preferred
259
- if legacy.exists():
260
- return legacy
261
- return preferred
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
scripts/vpb_public_eval_utils.py DELETED
@@ -1,366 +0,0 @@
1
- #!/usr/bin/env python3
2
- from __future__ import annotations
3
-
4
- import json
5
- import math
6
- from dataclasses import dataclass
7
- from pathlib import Path
8
- from typing import Any, Iterable
9
-
10
-
11
- TEST_BUCKETS = (
12
- "test_expert_seen",
13
- "test_expert_unseen",
14
- "test_nonexpert_seen",
15
- "test_nonexpert_unseen",
16
- )
17
- EXPERT_BUCKETS = {"test_expert_seen", "test_expert_unseen"}
18
- BENCHMARK_JSON_NAME = "video_progress_benchmark_file.json"
19
-
20
-
21
- @dataclass(frozen=True)
22
- class SelectedFrames:
23
- frames: list[int]
24
- timestamps_sec: list[float | None]
25
- mode: str
26
- sample_hz: float | None
27
-
28
-
29
- @dataclass(frozen=True)
30
- class Trajectory:
31
- bucket: str
32
- global_episode_id: str
33
- frames: list[int]
34
- gt_progress: list[float]
35
- timestamps_sec: list[float | None]
36
- task_instruction: str
37
- task_description: str
38
- main_view: str | None
39
- fps: float | None
40
- start_idx: int
41
- semantic_anchor_frames: list[int]
42
- semantic_anchor_progress: list[float]
43
-
44
-
45
- def load_json(path: Path) -> Any:
46
- return json.loads(path.read_text(encoding="utf-8"))
47
-
48
-
49
- def dump_json(path: Path, payload: Any) -> None:
50
- path.parent.mkdir(parents=True, exist_ok=True)
51
- path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
52
-
53
-
54
- def iter_benchmark_rows(
55
- benchmark_root: Path,
56
- buckets: Iterable[str] = TEST_BUCKETS,
57
- ) -> Iterable[tuple[str, int, dict[str, Any]]]:
58
- for bucket in buckets:
59
- path = benchmark_root / bucket / BENCHMARK_JSON_NAME
60
- if not path.exists():
61
- raise FileNotFoundError(f"Missing benchmark split: {path}")
62
- rows = load_json(path)
63
- if not isinstance(rows, list):
64
- raise ValueError(f"Expected list in benchmark split: {path}")
65
- for idx, row in enumerate(rows):
66
- if not isinstance(row, dict):
67
- raise ValueError(f"Expected object row in {path} at index {idx}")
68
- yield bucket, idx, row
69
-
70
-
71
- def finite_float(value: Any) -> float | None:
72
- try:
73
- number = float(value)
74
- except (TypeError, ValueError):
75
- return None
76
- return number if math.isfinite(number) else None
77
-
78
-
79
- def mean_or_none(values: Iterable[float | None]) -> float | None:
80
- clean = [float(v) for v in values if v is not None and math.isfinite(float(v))]
81
- if not clean:
82
- return None
83
- return float(sum(clean) / len(clean))
84
-
85
-
86
- def pearson_corr(xs: list[float], ys: list[float]) -> float | None:
87
- if len(xs) != len(ys) or len(xs) < 2:
88
- return None
89
- mean_x = sum(xs) / len(xs)
90
- mean_y = sum(ys) / len(ys)
91
- num = sum((x - mean_x) * (y - mean_y) for x, y in zip(xs, ys))
92
- den_x = sum((x - mean_x) ** 2 for x in xs)
93
- den_y = sum((y - mean_y) ** 2 for y in ys)
94
- if math.isclose(den_x, 0.0, rel_tol=0.0, abs_tol=1e-12):
95
- return None
96
- if math.isclose(den_y, 0.0, rel_tol=0.0, abs_tol=1e-12):
97
- return None
98
- value = num / math.sqrt(den_x * den_y)
99
- return value if math.isfinite(value) else None
100
-
101
-
102
- def average_ranks(values: list[float]) -> list[float]:
103
- order = sorted(range(len(values)), key=lambda idx: values[idx])
104
- ranks = [0.0] * len(values)
105
- i = 0
106
- while i < len(order):
107
- j = i + 1
108
- while (
109
- j < len(order)
110
- and math.isclose(values[order[j]], values[order[i]], rel_tol=0.0, abs_tol=1e-9)
111
- ):
112
- j += 1
113
- rank = (i + j - 1) / 2.0 + 1.0
114
- for pos in order[i:j]:
115
- ranks[pos] = rank
116
- i = j
117
- return ranks
118
-
119
-
120
- def spearman_corr(xs: list[float], ys: list[float]) -> float | None:
121
- return pearson_corr(average_ranks(xs), average_ranks(ys))
122
-
123
-
124
- def extract_view_from_main_path(main_path: str | None) -> str | None:
125
- raw = str(main_path or "").strip()
126
- if not raw:
127
- return None
128
- for part in Path(raw).parts:
129
- if part.startswith("observation.images."):
130
- view = part.split("observation.images.", 1)[1].strip()
131
- return view or None
132
- return None
133
-
134
-
135
- def main_view_for_row(row: dict[str, Any]) -> str | None:
136
- meta = dict(row.get("metadata") or {})
137
- target_view = extract_view_from_main_path(meta.get("main_path"))
138
- available = [str(v) for v in meta.get("available_views", []) if str(v).strip()]
139
- if target_view:
140
- return target_view
141
- if available:
142
- return available[0]
143
- frame_index = row.get("frame_index")
144
- if isinstance(frame_index, dict):
145
- for image_map in frame_index.values():
146
- if isinstance(image_map, dict) and image_map:
147
- return sorted(str(k) for k in image_map.keys())[0]
148
- return None
149
-
150
-
151
- def _nearest_frame(eligible: list[int], target_frame: float) -> int:
152
- best_idx = eligible[0]
153
- best_distance = abs(float(best_idx) - target_frame)
154
- for idx in eligible[1:]:
155
- distance = abs(float(idx) - target_frame)
156
- if distance < best_distance:
157
- best_idx = idx
158
- best_distance = distance
159
- return int(best_idx)
160
-
161
-
162
- def sample_frame_indices_by_hz(
163
- frame_ids: list[int],
164
- *,
165
- start_idx: int,
166
- fps: float,
167
- sample_hz: float,
168
- ) -> tuple[list[int], list[float]]:
169
- if not frame_ids or fps <= 0 or sample_hz <= 0:
170
- return [], []
171
- eligible = [idx for idx in frame_ids if idx >= start_idx]
172
- if not eligible:
173
- eligible = list(frame_ids)
174
- if not eligible:
175
- return [], []
176
-
177
- start_frame = eligible[0]
178
- end_frame = eligible[-1]
179
- duration_sec = max(0.0, (end_frame - start_frame) / fps)
180
- step_sec = 1.0 / sample_hz
181
-
182
- target_times: list[float] = []
183
- current = 0.0
184
- eps = 1e-9
185
- while current <= duration_sec + eps:
186
- target_times.append(round(current, 6))
187
- current += step_sec
188
- if not target_times:
189
- target_times = [0.0]
190
-
191
- selected_indices: list[int] = []
192
- selected_times: list[float] = []
193
- seen: set[int] = set()
194
- for target_time in target_times:
195
- target_frame = start_frame + target_time * fps
196
- idx = _nearest_frame(eligible, target_frame)
197
- if idx in seen:
198
- continue
199
- seen.add(idx)
200
- selected_indices.append(idx)
201
- selected_times.append(round((idx - start_frame) / fps, 6))
202
-
203
- if not selected_indices:
204
- selected_indices = [start_frame]
205
- selected_times = [0.0]
206
- return selected_indices, selected_times
207
-
208
-
209
- def selected_frames_for_row(
210
- row: dict[str, Any],
211
- *,
212
- eval_points: str,
213
- sample_hz: float,
214
- ) -> SelectedFrames:
215
- frame_index = dict(row.get("frame_index") or {})
216
- dense_progress = dict(row.get("dense_kinematic_progress") or {})
217
- frame_ids = sorted(
218
- int(k)
219
- for k in frame_index.keys()
220
- if str(k) in dense_progress and finite_float(dense_progress.get(str(k))) is not None
221
- )
222
- if not frame_ids:
223
- return SelectedFrames([], [], eval_points, sample_hz if eval_points == "time_hz" else None)
224
-
225
- if eval_points == "dense":
226
- return SelectedFrames(frame_ids, [None] * len(frame_ids), "dense", None)
227
-
228
- if eval_points == "semantic_anchors":
229
- anchor_frames: list[int] = []
230
- seen: set[int] = set()
231
- for anchor in row.get("semantic_anchors") or []:
232
- if not isinstance(anchor, dict):
233
- continue
234
- frame = finite_float(anchor.get("frame"))
235
- if frame is None:
236
- continue
237
- idx = int(frame)
238
- if idx in seen or idx not in frame_ids:
239
- continue
240
- seen.add(idx)
241
- anchor_frames.append(idx)
242
- anchor_frames.sort()
243
- return SelectedFrames(anchor_frames, [None] * len(anchor_frames), "semantic_anchors", None)
244
-
245
- if eval_points != "time_hz":
246
- raise ValueError(f"Unsupported eval_points: {eval_points}")
247
-
248
- meta = dict(row.get("metadata") or {})
249
- fps = finite_float(meta.get("fps")) or 0.0
250
- start_idx = int(finite_float(meta.get("start_idx")) or frame_ids[0])
251
- frames, timestamps = sample_frame_indices_by_hz(
252
- frame_ids,
253
- start_idx=start_idx,
254
- fps=fps,
255
- sample_hz=sample_hz,
256
- )
257
- valid = [
258
- (frame, ts)
259
- for frame, ts in zip(frames, timestamps)
260
- if str(frame) in dense_progress and finite_float(dense_progress.get(str(frame))) is not None
261
- ]
262
- return SelectedFrames(
263
- [frame for frame, _ in valid],
264
- [ts for _, ts in valid],
265
- "time_hz",
266
- float(sample_hz),
267
- )
268
-
269
-
270
- def semantic_anchor_points_for_row(row: dict[str, Any]) -> tuple[list[int], list[float]]:
271
- points_by_frame: dict[int, float] = {}
272
- for anchor in row.get("semantic_anchors") or []:
273
- if not isinstance(anchor, dict):
274
- continue
275
- frame = finite_float(anchor.get("frame"))
276
- progress = finite_float(anchor.get("human_annotated_progress"))
277
- if frame is None or progress is None:
278
- continue
279
- points_by_frame[int(frame)] = float(progress)
280
- frames = sorted(points_by_frame)
281
- return frames, [points_by_frame[frame] for frame in frames]
282
-
283
-
284
- def build_trajectories(
285
- benchmark_root: Path,
286
- *,
287
- buckets: Iterable[str] = TEST_BUCKETS,
288
- eval_points: str = "time_hz",
289
- sample_hz: float = 1.0,
290
- ) -> list[Trajectory]:
291
- trajectories: list[Trajectory] = []
292
- seen_gids: set[str] = set()
293
- for bucket, row_idx, row in iter_benchmark_rows(benchmark_root, buckets):
294
- global_episode_id = str(row.get("global_episode_id") or "").strip()
295
- if not global_episode_id:
296
- raise ValueError(f"Missing global_episode_id in {bucket} row {row_idx}")
297
- if global_episode_id in seen_gids:
298
- raise ValueError(f"Duplicate global_episode_id across benchmark splits: {global_episode_id}")
299
- seen_gids.add(global_episode_id)
300
-
301
- selected = selected_frames_for_row(row, eval_points=eval_points, sample_hz=sample_hz)
302
- dense_progress = dict(row.get("dense_kinematic_progress") or {})
303
- gt_progress: list[float] = []
304
- frames: list[int] = []
305
- timestamps: list[float | None] = []
306
- for frame, timestamp in zip(selected.frames, selected.timestamps_sec):
307
- value = finite_float(dense_progress.get(str(frame)))
308
- if value is None:
309
- continue
310
- frames.append(int(frame))
311
- timestamps.append(timestamp)
312
- gt_progress.append(float(value))
313
- if not frames:
314
- continue
315
-
316
- meta = dict(row.get("metadata") or {})
317
- anchor_frames, anchor_progress = semantic_anchor_points_for_row(row)
318
- trajectories.append(
319
- Trajectory(
320
- bucket=bucket,
321
- global_episode_id=global_episode_id,
322
- frames=frames,
323
- gt_progress=gt_progress,
324
- timestamps_sec=timestamps,
325
- task_instruction=str(meta.get("task_instruction") or ""),
326
- task_description=str(meta.get("task_description") or ""),
327
- main_view=main_view_for_row(row),
328
- fps=finite_float(meta.get("fps")),
329
- start_idx=int(finite_float(meta.get("start_idx")) or frames[0]),
330
- semantic_anchor_frames=anchor_frames,
331
- semantic_anchor_progress=anchor_progress,
332
- )
333
- )
334
- return trajectories
335
-
336
-
337
- def format_metric(value: Any, digits: int = 4) -> str:
338
- if value is None:
339
- return "n/a"
340
- if isinstance(value, float):
341
- if not math.isfinite(value):
342
- return "n/a"
343
- return f"{value:.{digits}f}"
344
- return str(value)
345
-
346
-
347
- def format_percent(value: Any, digits: int = 2) -> str:
348
- if value is None:
349
- return "n/a"
350
- try:
351
- number = float(value)
352
- except (TypeError, ValueError):
353
- return "n/a"
354
- if not math.isfinite(number):
355
- return "n/a"
356
- return f"{number * 100.0:.{digits}f}%"
357
-
358
-
359
- def markdown_table(headers: list[str], rows: list[list[Any]]) -> str:
360
- lines = [
361
- "| " + " | ".join(headers) + " |",
362
- "| " + " | ".join(["---"] * len(headers)) + " |",
363
- ]
364
- for row in rows:
365
- lines.append("| " + " | ".join(str(cell) for cell in row) + " |")
366
- return "\n".join(lines)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmark_splits/test_expert_seen/video_progress_benchmark_file.json → splits/test_expert_seen.json RENAMED
File without changes
benchmark_splits/test_expert_unseen/video_progress_benchmark_file.json → splits/test_expert_unseen.json RENAMED
File without changes
benchmark_splits/test_nonexpert_seen/video_progress_benchmark_file.json → splits/test_nonexpert_seen.json RENAMED
File without changes
benchmark_splits/test_nonexpert_unseen/video_progress_benchmark_file.json → splits/test_nonexpert_unseen.json RENAMED
File without changes
benchmark_splits/train/video_progress_benchmark_file.json → splits/train.json RENAMED
File without changes