Adding data prep script

#24
by lapchann - opened
Files changed (2) hide show
  1. scripts/RUN_LMUData.md +434 -0
  2. scripts/run_lmudata.py +1674 -0
scripts/RUN_LMUData.md ADDED
@@ -0,0 +1,434 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Preparing VANTAGE-Bench data for inference (`run_lmudata.py`)
2
+ A beginner-friendly guide to turning the public **VANTAGE-Bench** Hugging Face
3
+ dataset into a local **LMUData** folder you can run VANTAGE-Bench's evaluation
4
+ toolkit inference against.
5
+ > **TL;DR** — most participants just run:
6
+ > ```bash
7
+ > hf auth login # once
8
+ > python scripts/run_lmudata.py --all --lmu-root ~/LMUData
9
+ > ```
10
+ > Run inference with `--mode infer`.
11
+ >
12
+ > Running this from a clone of the **PhysicalAI-VANTAGE-Bench dataset repo**? It
13
+ > auto-uses the local `data/` folder — see *"Where are you running this from?"*.
14
+
15
+ ---
16
+
17
+ ## A. What this script does
18
+
19
+ `run_lmudata.py` downloads the **public, no-ground-truth** VANTAGE-Bench dataset
20
+ from Hugging Face (`nvidia/PhysicalAI-VANTAGE-Bench`) and reshapes it into the
21
+ exact folder layout that VANTAGE-Bench's evaluation toolkit's dataset loaders expect (called
22
+ **LMUData**).
23
+
24
+ - It prepares data **for inference and submission generation**.
25
+ - It is **not** for local scoring. Ground-truth answers are withheld from the
26
+ public dataset; scoring happens **server-side** on the leaderboard.
27
+ - It never fabricates answers. Evaluation-only columns are simply not written.
28
+
29
+ You run this once per machine. After it finishes, you run your model with
30
+ VANTAGE-Bench's evaluation toolkit in `--mode infer`, which produces a **submission JSONL**
31
+ you can submit.
32
+
33
+ ---
34
+
35
+ ## B. The mental model (how the pieces fit)
36
+
37
+ ```
38
+ Hugging Face dataset repo (nvidia/PhysicalAI-VANTAGE-Bench)
39
+ │ download
40
+
41
+ Local HF cache (~/.cache/huggingface/ — files reused)
42
+ │ run_lmudata.py reshapes + links/copies
43
+
44
+ LMUData/ (datasets/<TASK>/… — what toolkit reads)
45
+ │ python run.py --mode infer
46
+
47
+ Predictions ─► submission JSONL (submit to VANTAGE-Bench for scoring)
48
+ ```
49
+
50
+ Key idea: the HF cache is the real local copy of the media. By **default**, your
51
+ LMUData folder *symlinks* into that cache instead of duplicating tens of GB.
52
+
53
+ ---
54
+
55
+ ## Where are you running this from?
56
+
57
+ This same script ships in **two** repos and picks its data source automatically.
58
+ The source is shown in the run summary as `Source: …`.
59
+
60
+ **Source resolution priority:**
61
+ 1. `--local-source PATH` (explicit) — use that local checkout's `data/` folder.
62
+ 2. **Auto-local** — if the script *file itself* lives inside a valid
63
+ PhysicalAI-VANTAGE-Bench checkout (detected by walking the script's own
64
+ parent folders — **no filesystem search**).
65
+ 3. **HF remote** — download from `--hf-repo` (default
66
+ `nvidia/PhysicalAI-VANTAGE-Bench`) via the HF cache.
67
+
68
+ ### A. Running from the VANTAGE-Bench's Github repo
69
+
70
+ - Default: **HF remote**. Pulls data through the HF cache.
71
+ - Nothing special to do — this is the normal path.
72
+ ```bash
73
+ python scripts/run_lmudata.py --all --lmu-root ~/LMUData
74
+ ```
75
+
76
+ ### B. Running from the PhysicalAI-VANTAGE-Bench dataset repo
77
+
78
+ - If you cloned the dataset repo and run its bundled copy of this script, it
79
+ **auto-detects** the repo and reads `data/` **locally** — no re-download of the
80
+ primary dataset.
81
+ ```bash
82
+ python scripts/run_lmudata.py --all --lmu-root ~/LMUData
83
+ # Source: local-auto:/path/to/PhysicalAI-VANTAGE-Bench
84
+ ```
85
+ - **SOT and Grounding still need network.** The dataset repo ships the SOT
86
+ benchmark + prep script and the RefDrone prep script, but **not** the SOT
87
+ source camera videos (from `nvidia/PhysicalAI-SmartSpaces`) or the VisDrone
88
+ images. Those still download. Local mode only avoids re-fetching the primary
89
+ VANTAGE data.
90
+
91
+ ### C. Explicit local source
92
+
93
+ ```bash
94
+ python scripts/run_lmudata.py --all --lmu-root ~/LMUData \
95
+ --local-source /path/to/PhysicalAI-VANTAGE-Bench
96
+ ```
97
+ - Takes precedence over auto-detect and `--hf-repo`.
98
+ - The checkout must be **complete and post-PR** (validated per task).
99
+
100
+ ### D. Warnings for local mode
101
+
102
+ - **Stale / pre-PR clone fails validation.** Each task checks for its expected
103
+ post-PR paths (e.g. `data/pointing/VANTAGE_2DPointing.jsonl`,
104
+ `data/event_verification/data_jsons/annotations/`). A missing marker fails
105
+ *that task* with a clear message — it never silently serves the wrong layout.
106
+ - **Missing Git LFS files** (videos/images not pulled) will fail media checks.
107
+ Run `git lfs pull` in the clone first.
108
+ - **Symlink mode points into the clone.** In local mode the default symlinks
109
+ reference files inside your dataset clone; moving or `git clean`-ing the clone
110
+ breaks them. Use `--copy` for a portable LMUData.
111
+ - **`--hf-repo` is ignored** when a local source is active (a warning is logged).
112
+
113
+ ---
114
+
115
+ ## C. Before you start (checklist)
116
+
117
+ 1. **Python environment** with the project installed and `huggingface_hub`
118
+ available. If a snapshot fails with `huggingface_hub is required`, run
119
+ `pip install huggingface_hub`.
120
+ 2. **Hugging Face login** (recommended): `hf auth login`. The script
121
+ auto-detects this token — you won't need to pass `--hf-token`.
122
+ 3. **ffmpeg** — only needed for the **SOT** task (frame extraction). Skip if you
123
+ aren't preparing SOT. Easiest install: `conda install -c conda-forge ffmpeg`.
124
+ 4. **Disk space** — symlink mode (default) needs little extra space (media stays
125
+ in the HF cache, ~40 GB there). `--copy` mode duplicates that media into
126
+ LMUData. SOT adds ~16 GB of source videos to the HF cache.
127
+ 5. **Choose an LMUData location** — an absolute path you control, e.g.
128
+ `~/LMUData` or `/data/LMUData`. Pass it with `--lmu-root`. The script never
129
+ writes to the current working directory by default.
130
+
131
+ ---
132
+
133
+ ## D. What is the HF cache?
134
+
135
+ When `huggingface_hub` downloads files, it stores them in a local **cache**,
136
+ usually:
137
+
138
+ ```
139
+ ~/.cache/huggingface/
140
+ ```
141
+
142
+ (overridable with the `HF_HOME` env var or this script's `--hf-cache`).
143
+
144
+ - Downloads are **reused**: re-running the script, or preparing another task
145
+ that shares files, won't re-download what's already cached.
146
+ - **Symlink mode (default) depends on this cache.** Your LMUData media entries
147
+ are symlinks pointing into the cache. If you delete or move the HF cache,
148
+ those symlinks break. (Fix: re-run the prep, or use `--copy`.)
149
+
150
+ ---
151
+
152
+ ## Disk Space Requirements
153
+
154
+ ### Why disk usage varies
155
+
156
+ How much disk you need depends mostly on the **media mode**:
157
+
158
+ - **`--symlink` (default):** LMUData itself stays small — its media entries are
159
+ symlinks into the HF cache (or, in local mode, into your dataset clone). The
160
+ real bytes live in the cache/clone, which must **remain in place** for the
161
+ symlinks to keep working.
162
+ - **`--copy`:** LMUData contains real copied media, so it uses **more** disk but
163
+ is portable/self-contained and unaffected by HF-cache cleanup.
164
+
165
+ Hugging Face downloads are cached locally, usually under:
166
+
167
+ ```text
168
+ ~/.cache/huggingface/
169
+ ```
170
+
171
+ (overridable with `HF_HOME` or `--hf-cache`). Cached files are reused across
172
+ runs, so you generally download each file only once.
173
+
174
+ ### Approximate per-task disk usage
175
+
176
+ These are **rough** estimates and may change as the dataset evolves.
177
+
178
+ | Task | Approx. disk impact | Notes |
179
+ |---|---:|---|
180
+ | VQA | ~7–8 GB | Video files |
181
+ | Event Verification | ~1–3 GB | Referenced videos only |
182
+ | DVC | ~5–6 GB | Video files |
183
+ | Temporal Localization | ~2–5 GB | Video files |
184
+ | 2D Pointing | <1 GB | Images |
185
+ | Astro2D | <1 GB | Images + empty placeholder labels |
186
+ | 2D Grounding / RefDrone | ~300 MB retained, ~600 MB temporary | Downloads VisDrone/RefDrone image archive, extracts images, deletes zip |
187
+ | SOT | ~16 GB HF SmartSpaces cache + extracted frame outputs | Downloads source camera videos and extracts frames |
188
+
189
+ ### Total disk recommendation
190
+
191
+ For a full `--all` run using the default symlink mode, plan for roughly:
192
+
193
+ - ~21–22 GB for the VANTAGE HF dataset cache
194
+ - ~16 GB for the SmartSpaces/SOT source-video cache
195
+ - ~300 MB retained Grounding workdir/images
196
+ - SOT extracted frames and task metadata
197
+ - relatively small LMUData task folders because most media are symlinked
198
+
199
+ Recommended free disk for **default symlink mode**:
200
+
201
+ - minimum: ~50–60 GB free
202
+ - safer: ~70+ GB free
203
+
204
+ For **`--copy` mode**:
205
+
206
+ - LMUData contains real copied media in addition to the HF cache
207
+ - plan for roughly ~80–100 GB free
208
+ - safer on shared/HPC systems: 100+ GB free
209
+
210
+ These figures are approximate and may shift as the benchmark grows.
211
+
212
+ ### SOT runtime note
213
+
214
+ SOT is the slowest task to prepare. It downloads source camera videos from
215
+ SmartSpaces and uses `ffmpeg` to extract sequence frames. Depending on network
216
+ speed and storage speed, this may take a long time. It is normal for SOT
217
+ preparation to run much longer than the other tasks.
218
+
219
+ ### Check local disk usage
220
+
221
+ ```bash
222
+ df -h
223
+ du -sh ~/.cache/huggingface 2>/dev/null || true
224
+ du -sh ~/LMUData 2>/dev/null || true
225
+ ```
226
+
227
+ ### Advanced disk-space notes
228
+
229
+ - If disk is limited, use the default symlink mode.
230
+ - If portability is important, use `--copy`.
231
+ - Do not delete the HF cache if using symlink mode, because symlinks may break.
232
+
233
+ ---
234
+
235
+ ## E. Recommended participant command (default: symlink)
236
+
237
+ ```bash
238
+ python scripts/run_lmudata.py \
239
+ --all \
240
+ --lmu-root /path/to/LMUData
241
+ ```
242
+
243
+ - `--all` prepares all eight tasks.
244
+ - Media is **symlinked** from the HF cache (disk-efficient).
245
+ - Already-prepared tasks are skipped automatically (safe to re-run).
246
+
247
+ If you only want some tasks (e.g. skip the large SOT download):
248
+
249
+ ```bash
250
+ python scripts/run_lmudata.py \
251
+ --tasks vqa,event_verification,dvc,temporal,pointing,astro2d,grounding \
252
+ --lmu-root /path/to/LMUData
253
+ ```
254
+
255
+ ---
256
+
257
+ ## F. Portable / self-contained command (copy mode)
258
+
259
+ Use `--copy` when you want a LMUData folder with **real media files** inside it —
260
+ portable across machines, and unaffected by HF-cache cleanup:
261
+
262
+ ```bash
263
+ python scripts/run_lmudata.py \
264
+ --all \
265
+ --lmu-root /path/to/LMUData \
266
+ --copy
267
+ ```
268
+
269
+ Trade-off: this duplicates tens of GB of media into LMUData.
270
+
271
+ ---
272
+
273
+ ## G. Dry-run (simulation, no writes)
274
+
275
+ Preview exactly what would happen — **no downloads, no files written**, the
276
+ LMUData folder isn't even created:
277
+
278
+ ```bash
279
+ python scripts/run_lmudata.py \
280
+ --all \
281
+ --lmu-root /path/to/LMUData \
282
+ --dry-run
283
+ ```
284
+
285
+ The summary header shows the media mode (`media=symlink` by default), and each
286
+ task prints the HF files it would fetch and the paths it would write.
287
+
288
+ ---
289
+
290
+ ## H. SOT-specific prerequisites
291
+
292
+ SOT (single-object tracking) is the heaviest task. It downloads source camera
293
+ videos from
294
+ [`nvidia/PhysicalAI-SmartSpaces`](https://huggingface.co/datasets/nvidia/PhysicalAI-SmartSpaces)
295
+ and extracts frames.
296
+
297
+ - **ffmpeg is required** for frame extraction. The shipped prep script has no
298
+ ffmpeg-free path. The wrapper auto-discovers ffmpeg on your `PATH` **and** in
299
+ common conda envs (`~/miniconda3/envs/*/bin`, `/opt/conda/envs/*/bin`, …) and
300
+ bridges it onto the subprocess automatically.
301
+ - **HF token is auto-detected** in this order: `--hf-token` → `HF_TOKEN` env →
302
+ the token from `hf auth login`. If you've logged in, nothing to pass.
303
+ - **Source videos:** ~16 GB pulled into the HF cache; expect a multi-minute run.
304
+ - **`gt.json` contains only the public `init_bbox`** — no hidden per-frame
305
+ trajectories.
306
+ **If ffmpeg is missing**, you'll get a clear message with install options:
307
+ ```
308
+ conda install -c conda-forge ffmpeg # recommended; auto-detected
309
+ sudo apt-get install -y ffmpeg # Debian/Ubuntu
310
+ # or a static build from https://johnvansickle.com/ffmpeg/
311
+ ```
312
+ **If no token is found**, the message lists the three ways to provide one
313
+ (`hf auth login`, `HF_TOKEN`, `--hf-token`).
314
+ ---
315
+ ## I. RefDrone / Grounding prerequisites
316
+ The grounding task materializes 1503 VisDrone images via the shipped
317
+ `prep_refdrone_data.py`.
318
+ | Requirement | Needed? | Notes |
319
+ |---|---|---|
320
+ | Internet access | yes | Downloads from `github.com` + `huggingface.co`. |
321
+ | GitHub HTTPS mirror | primary | Ultralytics release (~311 MB), size + SHA-256 verified. **Sufficient on its own.** |
322
+ | Google Drive / `gdown` | **optional** | Fallback only, used if the HTTPS mirror fails. Install with `pip install gdown` only then. |
323
+ | Disk | ~600 MB transient | Zip downloaded, images extracted, **zip then deleted** (~290 MB remains). |
324
+ | System packages | none | Pure-Python extraction. |
325
+
326
+ If you already have the images staged, pass `--skip-grounding-images` to write
327
+ `annotations.json` without re-downloading.
328
+
329
+ ---
330
+
331
+ ## J. Common troubleshooting
332
+
333
+ - **Wrong LMUData path / Toolkit can't find data.** VANTAGE-Bench's evaluation
334
+ toolkit resolves `LMUDataRoot()` from `$LMUData` (if it points to an
335
+ existing dir), else `~/LMUData`. Make them match:
336
+ ```bash
337
+ export LMUData=/path/to/LMUData
338
+ python -c "from vlmeval.smp import LMUDataRoot; print(LMUDataRoot())"
339
+ ```
340
+ - **Broken / dangling symlinks.** In symlink mode, deleting or moving the HF
341
+ cache breaks LMUData media links. Fix by re-running the prep, or rebuild with
342
+ `--copy` for a self-contained folder.
343
+ - **Missing ffmpeg (SOT).** Install via conda/apt (see section H). A conda-env
344
+ ffmpeg is auto-detected.
345
+ - **HF auth / token issues.** Run `hf auth login`, or `export HF_TOKEN=hf_xxx`,
346
+ or pass `--hf-token`. If a download 401/403s, confirm any required dataset
347
+ license acceptance and that your token has read access.
348
+ - **Use `--mode infer`, not `--mode all`.** These TSVs are inference-only and
349
+ omit GT columns. `--mode all` would call `evaluate()` and crash; scoring is
350
+ server-side anyway.
351
+
352
+ ---
353
+
354
+ ## K. What gets created under LMUData
355
+
356
+ ```
357
+ LMUData/
358
+ └── datasets/
359
+ ├── VANTAGE_VQA/ VANTAGE_VQA.tsv + videos/
360
+ ├── VANTAGE_EventVerification/ VANTAGE_EventVerification.tsv + videos/
361
+ ├── VANTAGE_DVC/ VANTAGE_DVC.tsv + videos/
362
+ ├── VANTAGE_Temporal/ VANTAGE_Temporal.tsv + videos/
363
+ ├── VANTAGE_2DPointing/ VANTAGE_2DPointing.tsv + images_annotated/
364
+ ├── Astro2D/ images/ + labels/ (empty placeholders)
365
+ ├── VANTAGE_2DGrounding/ annotations.json + images/
366
+ └── VANTAGE_SOT/ <seq>/gt.json + <seq>/frames/f0X.png
367
+ ```
368
+
369
+ Inference-only TSV schemas (no GT columns):
370
+
371
+ | Task | Columns |
372
+ |---|---|
373
+ | VANTAGE_VQA | `index, video, question, options` |
374
+ | VANTAGE_EventVerification | `index, video, system_prompt, question` |
375
+ | VANTAGE_DVC | `index, video, question` |
376
+ | VANTAGE_Temporal | `index, video, question` (video = bare stem, no `.mp4`) |
377
+ | VANTAGE_2DPointing | `index, question_id, image_path, question, A, B, C, D` |
378
+ - **Astro2D `labels/*.txt` are intentionally empty** — they exist only so the
379
+ loader doesn't drop images; they contain no ground truth.
380
+ - **VANTAGE_2DGrounding `annotations.json` omits `bboxes`** — the loader takes
381
+ its no-GT branch.
382
+ > **Note:** a `LMUData/images/` folder may appear **later** — that is the toolkit's
383
+ *runtime* artifact (frame caching / image dumping during
384
+ > inference), **not** produced by this prep script. It's safe to ignore.
385
+ ---
386
+ ## L. Advanced options
387
+ | Flag | Purpose |
388
+ |---|---|
389
+ | `--tasks a,b,c` | Prepare a subset. Choices: `vqa, event_verification, dvc, temporal, pointing, astro2d, grounding, sot`. |
390
+ | `--all` | Prepare all eight tasks (default if neither `--tasks` nor `--all` given). |
391
+ | `--lmu-root PATH` | Output root (absolute). Default `~/LMUData`. Never CWD. |
392
+ | `--local-source PATH` | Use a local PhysicalAI-VANTAGE-Bench checkout's `data/` instead of HF. Wins over `--hf-repo`. Auto-enabled when the script lives inside such a repo. |
393
+ | `--symlink` | **Default.** Symlink media (from the HF cache, or the local checkout in local mode). |
394
+ | `--copy` | Copy real media into LMUData (portable, self-contained; uses more disk). |
395
+ | `--force` | Rebuild the index file even if the task already looks complete; re-places missing media. |
396
+ | `--force-clean` | **Destructive.** Wipe a task's media dir before re-staging. |
397
+ | `--dry-run` | Print the plan; no HF calls, no writes. |
398
+ | `--hf-token TOKEN` | HF token. Optional — auto-detected from `HF_TOKEN` / `hf auth login`. Needed for SOT. |
399
+ | `--hf-repo REPO` | Source repo override (testing/simulation only). Production default: `nvidia/PhysicalAI-VANTAGE-Bench`. |
400
+ | `--skip-grounding-images` | For grounding: write `annotations.json` but don't download VisDrone images. |
401
+ | `--write-manifest` | Write `.vantage_prep_manifest.json` telemetry at the LMU root (off by default). |
402
+ | `--verbose` / `-v` | Debug logging (snapshot paths, per-file decisions). |
403
+
404
+ `--symlink` and `--copy` are mutually exclusive.
405
+
406
+ ### Idempotency & safety
407
+
408
+ - **Re-running is safe.** A task that already passes its integrity check is
409
+ **skipped** (no download, no writes) unless you pass `--force`.
410
+ - **Interrupted runs recover.** A partial task fails its integrity check, so the
411
+ next normal run rebuilds just that task. SOT resumes cheaply — already
412
+ downloaded videos and extracted frames are reused from the HF cache.
413
+ - **Non-destructive by default.** Without `--force-clean`, the script only adds
414
+ missing files and (under `--force`) overwrites the index file. It never
415
+ deletes media on its own.
416
+
417
+ ### Per-task failure isolation
418
+
419
+ Each task runs independently. If one fails (missing source, no token, no
420
+ ffmpeg, mirror down), it's marked `failed` in the summary **and the other tasks
421
+ continue**. The process exits non-zero if any task failed, zero otherwise.
422
+
423
+ ---
424
+
425
+ ## After preparing: run inference
426
+
427
+ ```bash
428
+ export LMUData=/path/to/LMUData
429
+ python run.py --data VANTAGE_VQA --model <YourModel> --mode infer
430
+ ```
431
+
432
+ Repeat per task (or pass multiple to `--data`). Each run emits a
433
+ `*.submission.jsonl` next to the prediction file — that's what you submit.
434
+ Scoring is done server-side against the withheld ground truth.
scripts/run_lmudata.py ADDED
@@ -0,0 +1,1674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ run_lmudata.py — Prepare a VLMEvalKit-compatible LMUData layout from
4
+ ``nvidia/PhysicalAI-VANTAGE-Bench`` (HF dataset).
5
+
6
+ PHASE 2A implemented:
7
+ - VANTAGE_VQA, VANTAGE_EventVerification, VANTAGE_DVC,
8
+ VANTAGE_Temporal, VANTAGE_2DPointing
9
+ PHASE 2B implemented:
10
+ - Astro2D, VANTAGE_2DGrounding, VANTAGE_SOT
11
+
12
+ The target LMUData layout per task (matched against loader expectations
13
+ in vlmeval/dataset/vantage_*.py and vlmeval/dataset/image_mcq.py):
14
+
15
+ $LMU_ROOT/datasets/
16
+ VANTAGE_VQA/ VANTAGE_VQA.tsv videos/*.mp4
17
+ VANTAGE_EventVerification/ VANTAGE_EventVerification.tsv videos/*.mp4
18
+ VANTAGE_DVC/ VANTAGE_DVC.tsv videos/*.mp4
19
+ VANTAGE_Temporal/ VANTAGE_Temporal.tsv videos/*.mp4
20
+ VANTAGE_2DPointing/ VANTAGE_2DPointing.tsv images_annotated/*.jpg
21
+ Astro2D/ images/<flat>.jpg labels/<flat>.txt (empty)
22
+ VANTAGE_2DGrounding/ annotations.json images/*.jpg
23
+ VANTAGE_SOT/ <seq>/gt.json <seq>/frames/f0X.png
24
+
25
+ No GT fields are fabricated. ``answer`` is an empty string where the
26
+ public source omits it; ``duration`` falls back to 30.0; ``category``
27
+ falls back to ``"Unknown"``.
28
+
29
+ Runtime source: HF repo ``nvidia/PhysicalAI-VANTAGE-Bench``
30
+ (repo_type=dataset). No local repo is read at runtime.
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import argparse
36
+ import csv
37
+ import datetime
38
+ import json
39
+ import logging
40
+ import os
41
+ import re
42
+ import shutil
43
+ import subprocess
44
+ import sys
45
+ from dataclasses import dataclass, field
46
+ from pathlib import Path
47
+ from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple
48
+
49
+ # Production runtime source — DO NOT change this default.
50
+ # Override only for testing/simulation via the --hf-repo CLI flag.
51
+ HF_REPO_ID = "nvidia/PhysicalAI-VANTAGE-Bench"
52
+ HF_REPO_TYPE = "dataset"
53
+
54
+ DEFAULT_LMU_ROOT = Path("~/LMUData").expanduser()
55
+ MANIFEST_FILENAME = ".vantage_prep_manifest.json"
56
+
57
+ # Top-level files/dirs that mark a PhysicalAI-VANTAGE-Bench checkout.
58
+ REPO_TOP_MARKERS = ["data", "README.md", "LICENSE.md"]
59
+
60
+ # Per-task required paths (relative to repo root) for a LOCAL source to be
61
+ # usable. These encode the post-PR layout; a stale/pre-PR clone that lacks the
62
+ # marker fails validation for that task with a clear message rather than
63
+ # silently producing wrong data.
64
+ LOCAL_TASK_MARKERS: Dict[str, List[str]] = {
65
+ "vqa": ["data/vqa/data_jsons/annotations"],
66
+ "event_verification": ["data/event_verification/data_jsons/annotations"],
67
+ "dvc": ["data/dense_captioning/metadata.jsonl"],
68
+ "temporal": ["data/temporal_localization/data_jsons/annotations"],
69
+ "pointing": ["data/pointing/VANTAGE_2DPointing.jsonl"],
70
+ "astro2d": ["data/2dbbox/metadata.jsonl"],
71
+ "grounding": [
72
+ "data/referring/refdrone_test_llava.json",
73
+ "data/referring/prep_refdrone_data.py",
74
+ ],
75
+ "sot": [
76
+ "data/tracking/sot_benchmark.jsonl",
77
+ "data/tracking/prepare_sot_dataset.py",
78
+ ],
79
+ }
80
+
81
+ IMPLEMENTED_TASKS = [
82
+ "vqa", "event_verification", "dvc", "temporal", "pointing",
83
+ "astro2d", "grounding", "sot",
84
+ ]
85
+ DEFERRED_TASKS: List[str] = []
86
+ ALL_TASKS = IMPLEMENTED_TASKS + DEFERRED_TASKS
87
+
88
+ # nvidia/PhysicalAI-SmartSpaces is the source for SOT camera videos.
89
+ # Access requires HF token + license acceptance at:
90
+ # https://huggingface.co/datasets/nvidia/PhysicalAI-SmartSpaces
91
+ SOT_SOURCE_REPO_ID = "nvidia/PhysicalAI-SmartSpaces"
92
+ SOT_SOURCE_REPO_SUBDIR = "MTMC_Tracking_2025"
93
+
94
+ log = logging.getLogger("vantage-prep")
95
+
96
+
97
+ # ---------------------------------------------------------------------------
98
+ # Options + result containers
99
+ # ---------------------------------------------------------------------------
100
+
101
+ @dataclass
102
+ class Options:
103
+ lmu_root: Path
104
+ hf_cache: Optional[Path]
105
+ hf_token: Optional[str]
106
+ symlink: bool
107
+ force: bool
108
+ force_clean: bool
109
+ dry_run: bool
110
+ verbose: bool
111
+ hf_repo: str = HF_REPO_ID
112
+ skip_grounding_images: bool = False
113
+ write_manifest: bool = False
114
+ local_source: Optional[Path] = None
115
+
116
+
117
+ @dataclass
118
+ class TaskResult:
119
+ task: str
120
+ lmu_name: str
121
+ target_dir: Path
122
+ status: str # "skipped" | "built" | "rebuilt" | "deferred" | "failed" | "dry-run"
123
+ rows: int = 0
124
+ media_count: int = 0
125
+ source_files: List[str] = field(default_factory=list)
126
+ notes: List[str] = field(default_factory=list)
127
+ source_mode: str = "" # "local-explicit" | "local-auto" | "hf" | ""
128
+
129
+
130
+ # ---------------------------------------------------------------------------
131
+ # Per-task config
132
+ # ---------------------------------------------------------------------------
133
+
134
+ TASK_CONFIG: Dict[str, Dict[str, Any]] = {
135
+ "vqa": {
136
+ "lmu_name": "VANTAGE_VQA",
137
+ "index_file": "VANTAGE_VQA.tsv",
138
+ "media_dir": "videos",
139
+ "media_glob": "*.mp4",
140
+ "hf_patterns": [
141
+ "data/vqa/data_jsons/annotations/*.json",
142
+ "data/vqa/videos/*",
143
+ ],
144
+ },
145
+ "event_verification": {
146
+ "lmu_name": "VANTAGE_EventVerification",
147
+ "index_file": "VANTAGE_EventVerification.tsv",
148
+ "media_dir": "videos",
149
+ "media_glob": "*.mp4",
150
+ "hf_patterns": [
151
+ "data/event_verification/data_jsons/annotations/*.json",
152
+ "data/event_verification/videos/*",
153
+ ],
154
+ },
155
+ "dvc": {
156
+ "lmu_name": "VANTAGE_DVC",
157
+ "index_file": "VANTAGE_DVC.tsv",
158
+ "media_dir": "videos",
159
+ "media_glob": "*.mp4",
160
+ "hf_patterns": [
161
+ "data/dense_captioning/metadata.jsonl",
162
+ "data/dense_captioning/prompt.json",
163
+ "data/dense_captioning/videos/*",
164
+ ],
165
+ },
166
+ "temporal": {
167
+ "lmu_name": "VANTAGE_Temporal",
168
+ "index_file": "VANTAGE_Temporal.tsv",
169
+ "media_dir": "videos",
170
+ "media_glob": "*.mp4",
171
+ "hf_patterns": [
172
+ "data/temporal_localization/data_jsons/annotations/*.json",
173
+ "data/temporal_localization/videos/*",
174
+ ],
175
+ },
176
+ "pointing": {
177
+ "lmu_name": "VANTAGE_2DPointing",
178
+ "index_file": "VANTAGE_2DPointing.tsv",
179
+ "media_dir": "images_annotated",
180
+ "media_glob": "*",
181
+ "hf_patterns": [
182
+ "data/pointing/VANTAGE_2DPointing.jsonl",
183
+ "data/pointing/images_annotated/*",
184
+ ],
185
+ },
186
+ # ---- PHASE 2B ----
187
+ "astro2d": {
188
+ "lmu_name": "Astro2D",
189
+ # Astro2D has no top-level index file; loader reads images/ and labels/ directly.
190
+ "index_file": None,
191
+ "media_dir": "images",
192
+ "media_glob": "*",
193
+ "hf_patterns": [
194
+ "data/2dbbox/metadata.jsonl",
195
+ "data/2dbbox/prompt.json",
196
+ "data/2dbbox/sequence_a/images/*",
197
+ "data/2dbbox/sequence_b/images/*",
198
+ "data/2dbbox/sequence_c/images/*",
199
+ ],
200
+ },
201
+ "grounding": {
202
+ "lmu_name": "VANTAGE_2DGrounding",
203
+ "index_file": "annotations.json",
204
+ "media_dir": "images",
205
+ "media_glob": "*",
206
+ "hf_patterns": [
207
+ "data/referring/refdrone_test_llava.json",
208
+ "data/referring/prep_refdrone_data.py",
209
+ "data/referring/RUN.md",
210
+ ],
211
+ },
212
+ "sot": {
213
+ "lmu_name": "VANTAGE_SOT",
214
+ # SOT has no top-level index file; integrity check is per-sequence.
215
+ "index_file": None,
216
+ "media_dir": ".", # per-sequence dirs live at the task root
217
+ "media_glob": "*",
218
+ "hf_patterns": [
219
+ "data/tracking/sot_benchmark.jsonl",
220
+ "data/tracking/prepare_sot_dataset.py",
221
+ "data/tracking/README.md",
222
+ ],
223
+ },
224
+ }
225
+
226
+
227
+ # ---------------------------------------------------------------------------
228
+ # Logging + path helpers
229
+ # ---------------------------------------------------------------------------
230
+
231
+ def _setup_logging(verbose: bool) -> None:
232
+ level = logging.DEBUG if verbose else logging.INFO
233
+ logging.basicConfig(
234
+ level=level,
235
+ format="%(asctime)s %(levelname)-7s %(message)s",
236
+ datefmt="%H:%M:%S",
237
+ )
238
+
239
+
240
+ def _resolve_lmu_root(arg_value: Optional[str]) -> Path:
241
+ if arg_value:
242
+ root = Path(arg_value).expanduser().resolve()
243
+ else:
244
+ root = DEFAULT_LMU_ROOT
245
+ if not root.is_absolute():
246
+ raise SystemExit(f"--lmu-root must be absolute (got: {root})")
247
+ return root
248
+
249
+
250
+ def _target_dir(lmu_root: Path, task: str) -> Path:
251
+ return lmu_root / "datasets" / TASK_CONFIG[task]["lmu_name"]
252
+
253
+
254
+ # ---------------------------------------------------------------------------
255
+ # HF snapshot
256
+ # ---------------------------------------------------------------------------
257
+
258
+ def _snapshot(task: str, opts: Options) -> Path:
259
+ """Download (or reuse cached) HF snapshot restricted to this task's patterns."""
260
+ try:
261
+ from huggingface_hub import snapshot_download
262
+ except ImportError as e:
263
+ raise SystemExit(
264
+ "huggingface_hub is required. Install with: pip install huggingface_hub"
265
+ ) from e
266
+
267
+ cfg = TASK_CONFIG[task]
268
+ patterns = list(cfg["hf_patterns"])
269
+ log.info("[%s] snapshot from %s (patterns=%d)", task, opts.hf_repo, len(patterns))
270
+ kwargs: Dict[str, Any] = dict(
271
+ repo_id=opts.hf_repo,
272
+ repo_type=HF_REPO_TYPE,
273
+ allow_patterns=patterns,
274
+ )
275
+ if opts.hf_cache is not None:
276
+ kwargs["cache_dir"] = str(opts.hf_cache)
277
+ if opts.hf_token:
278
+ kwargs["token"] = opts.hf_token
279
+ snap_dir = snapshot_download(**kwargs)
280
+ log.debug("[%s] snapshot dir: %s", task, snap_dir)
281
+ return Path(snap_dir)
282
+
283
+
284
+ # ---------------------------------------------------------------------------
285
+ # Source resolution: local dataset repo vs HF remote
286
+ # ---------------------------------------------------------------------------
287
+
288
+ def _task_data_subdir(task: str) -> str:
289
+ """Return the `data/<subdir>` name for a task (e.g. dvc -> dense_captioning),
290
+ derived from the task's first HF pattern so there is one source of truth."""
291
+ first = TASK_CONFIG[task]["hf_patterns"][0] # e.g. "data/dense_captioning/metadata.jsonl"
292
+ parts = first.split("/")
293
+ return parts[1] if len(parts) > 1 else task
294
+
295
+
296
+ def _is_valid_local_repo(path: Path, task: Optional[str] = None) -> Tuple[bool, str]:
297
+ """Validate that `path` is a PhysicalAI-VANTAGE-Bench checkout.
298
+
299
+ Top-level: must contain data/, README.md, LICENSE.md.
300
+ Per-task (when `task` given): the post-PR marker paths in LOCAL_TASK_MARKERS
301
+ must all exist. A stale/pre-PR clone missing a marker fails here with a
302
+ clear reason instead of silently serving the wrong layout.
303
+ """
304
+ if not path.is_dir():
305
+ return False, f"not a directory: {path}"
306
+ for m in REPO_TOP_MARKERS:
307
+ if not (path / m).exists():
308
+ return False, f"missing top-level marker: {m}"
309
+ if task is not None:
310
+ for rel in LOCAL_TASK_MARKERS.get(task, []):
311
+ if not (path / rel).exists():
312
+ return False, f"missing {task} marker: {rel}"
313
+ return True, "ok"
314
+
315
+
316
+ # Cache the (single) auto-detected root so we don't walk parents per task.
317
+ _AUTODETECT_CACHE: Dict[str, Optional[Path]] = {}
318
+
319
+
320
+ def _autodetect_local_root() -> Optional[Path]:
321
+ """Return the dataset-repo root iff the script itself lives inside one.
322
+
323
+ Walks only Path(__file__).resolve().parents — never searches arbitrary
324
+ filesystem locations. Top-level markers only (per-task checks happen in
325
+ _resolve_source). Returns None when the script is not inside a valid repo
326
+ (e.g. when shipped in the VLMEvalKit repo).
327
+ """
328
+ if "root" in _AUTODETECT_CACHE:
329
+ return _AUTODETECT_CACHE["root"]
330
+ here = Path(__file__).resolve()
331
+ found: Optional[Path] = None
332
+ for parent in here.parents:
333
+ ok, _why = _is_valid_local_repo(parent, task=None)
334
+ if ok:
335
+ found = parent
336
+ break
337
+ _AUTODETECT_CACHE["root"] = found
338
+ return found
339
+
340
+
341
+ def _resolve_source(task: str, opts: Options) -> Tuple[Optional[Path], str]:
342
+ """Decide where this task's source data comes from.
343
+
344
+ Priority:
345
+ 1. --local-source PATH -> ("local-explicit")
346
+ 2. script inside a repo -> ("local-auto")
347
+ 3. HF remote (--hf-repo) -> ("hf")
348
+
349
+ Returns (source_root, source_mode). For "hf", source_root is the snapshot
350
+ dir — downloaded here for a real run, but left None during --dry-run so no
351
+ network/cache work happens. For local modes, source_root is the repo root
352
+ and is validated (per-task) before returning.
353
+ """
354
+ # 1. Explicit local source.
355
+ if opts.local_source is not None:
356
+ root = opts.local_source
357
+ ok, why = _is_valid_local_repo(root, task)
358
+ if not ok:
359
+ raise SystemExit(
360
+ f"[{task}] --local-source {root} is not a usable dataset repo: {why}. "
361
+ f"Ensure it is a complete, post-PR PhysicalAI-VANTAGE-Bench checkout "
362
+ f"(and that Git LFS media is pulled)."
363
+ )
364
+ return root, "local-explicit"
365
+
366
+ # 2. Auto-local: only when the script itself sits inside a valid repo.
367
+ auto = _autodetect_local_root()
368
+ if auto is not None:
369
+ ok, why = _is_valid_local_repo(auto, task)
370
+ if not ok:
371
+ raise SystemExit(
372
+ f"[{task}] local dataset repo detected at {auto} but it is missing "
373
+ f"required layout: {why}. The clone looks stale or pre-PR. Update it, "
374
+ f"or run from the VLMEvalKit repo to use the HF remote."
375
+ )
376
+ return auto, "local-auto"
377
+
378
+ # 3. HF remote. Defer the actual download during dry-run.
379
+ if opts.dry_run:
380
+ return None, "hf"
381
+ return _snapshot(task, opts), "hf"
382
+
383
+
384
+ # ---------------------------------------------------------------------------
385
+ # File operations (idempotent + non-destructive)
386
+ # ---------------------------------------------------------------------------
387
+
388
+ def _ensure_dir(p: Path, dry_run: bool) -> None:
389
+ if p.exists():
390
+ return
391
+ log.debug("mkdir -p %s", p)
392
+ if not dry_run:
393
+ p.mkdir(parents=True, exist_ok=True)
394
+
395
+
396
+ def _link_or_copy_file(src: Path, dst: Path, opts: Options) -> bool:
397
+ """Place src at dst as symlink (default) or copy. Returns True if action taken."""
398
+ if dst.exists() or dst.is_symlink():
399
+ return False
400
+ if opts.dry_run:
401
+ log.debug("would %s %s -> %s", "symlink" if opts.symlink else "copy", src, dst)
402
+ return True
403
+ dst.parent.mkdir(parents=True, exist_ok=True)
404
+ if opts.symlink:
405
+ os.symlink(os.fspath(src.resolve()), os.fspath(dst))
406
+ else:
407
+ shutil.copy2(src, dst)
408
+ return True
409
+
410
+
411
+ def _link_or_copy_dir(src_dir: Path, dst_dir: Path, opts: Options) -> int:
412
+ """Mirror src_dir into dst_dir. Returns count of new entries placed."""
413
+ if not src_dir.exists():
414
+ log.warning("source media dir missing: %s", src_dir)
415
+ return 0
416
+ placed = 0
417
+ _ensure_dir(dst_dir, opts.dry_run)
418
+ for src in sorted(src_dir.iterdir()):
419
+ if not src.is_file():
420
+ continue
421
+ dst = dst_dir / src.name
422
+ if _link_or_copy_file(src, dst, opts):
423
+ placed += 1
424
+ return placed
425
+
426
+
427
+ def _wipe_dir(p: Path, dry_run: bool) -> None:
428
+ if not p.exists():
429
+ return
430
+ log.warning("--force-clean: removing %s", p)
431
+ if dry_run:
432
+ return
433
+ shutil.rmtree(p)
434
+
435
+
436
+ def _write_tsv(path: Path, rows: List[Dict[str, Any]], columns: List[str], dry_run: bool) -> None:
437
+ log.info("write TSV %s (%d rows, %d cols)", path, len(rows), len(columns))
438
+ if dry_run:
439
+ return
440
+ path.parent.mkdir(parents=True, exist_ok=True)
441
+ with open(path, "w", newline="", encoding="utf-8") as f:
442
+ writer = csv.DictWriter(
443
+ f, fieldnames=columns, delimiter="\t",
444
+ quoting=csv.QUOTE_MINIMAL, lineterminator="\n",
445
+ )
446
+ writer.writeheader()
447
+ for r in rows:
448
+ writer.writerow({c: r.get(c, "") for c in columns})
449
+
450
+
451
+ # ---------------------------------------------------------------------------
452
+ # Integrity check (mirrors loader check_integrity predicates)
453
+ # ---------------------------------------------------------------------------
454
+
455
+ def _check_integrity(task: str, target_dir: Path) -> Tuple[bool, str]:
456
+ # Per-task overrides for layouts that don't fit "index file + media dir".
457
+ if task == "astro2d":
458
+ images = target_dir / "images"
459
+ labels = target_dir / "labels"
460
+ if not images.exists() or not any(images.iterdir()):
461
+ return False, "images/ empty/missing"
462
+ if not labels.exists() or not any(labels.iterdir()):
463
+ return False, "labels/ empty/missing (placeholders required)"
464
+ return True, "ok"
465
+ if task == "sot":
466
+ if not target_dir.exists():
467
+ return False, "target dir missing"
468
+ seq_dirs = [d for d in target_dir.iterdir()
469
+ if d.is_dir() and (d / "gt.json").exists() and (d / "frames").is_dir()]
470
+ if not seq_dirs:
471
+ return False, "no valid sequence dirs (need <seq>/gt.json + frames/)"
472
+ return True, f"{len(seq_dirs)} sequence dirs"
473
+
474
+ cfg = TASK_CONFIG[task]
475
+ idx_name = cfg["index_file"]
476
+ if idx_name is None:
477
+ # Shouldn't happen — handled above per-task.
478
+ return False, "no integrity check defined"
479
+ idx = target_dir / idx_name
480
+ media = target_dir / cfg["media_dir"]
481
+ if not idx.exists():
482
+ return False, f"index file missing: {idx.name}"
483
+ if idx.stat().st_size == 0:
484
+ return False, f"index file empty: {idx.name}"
485
+ if not media.exists() or not any(media.iterdir()):
486
+ return False, f"media dir empty/missing: {media.name}"
487
+ return True, "ok"
488
+
489
+
490
+ # ---------------------------------------------------------------------------
491
+ # Common helpers for prep functions
492
+ # ---------------------------------------------------------------------------
493
+
494
+ def _normalize_category(cat: Optional[str]) -> str:
495
+ if not cat:
496
+ return "Unknown"
497
+ s = str(cat).strip()
498
+ if not s:
499
+ return "Unknown"
500
+ if s == "Smart Spaces":
501
+ return "Smart_Spaces"
502
+ return s
503
+
504
+
505
+ def _strip_mp4(name: str) -> str:
506
+ return name[:-4] if name.endswith(".mp4") else name
507
+
508
+
509
+ def _ensure_mp4(name: str) -> str:
510
+ return name if name.endswith(".mp4") else name + ".mp4"
511
+
512
+
513
+ def _bare_stem(name: str) -> str:
514
+ """Strip a leading dir and trailing .mp4 from a HF file_name field."""
515
+ base = os.path.basename(name)
516
+ return _strip_mp4(base)
517
+
518
+
519
+ def _strip_video_ext(name: str) -> str:
520
+ """Strip one trailing .json OR .mp4 extension (matches VANTAGE_VQA loader's logic).
521
+
522
+ q_uid values in VQA annotations come in two flavors:
523
+ "concat_wh_52_2925_4.mp4" -> "concat_wh_52_2925_4"
524
+ "temporal_cb00ec82cd.json" -> "temporal_cb00ec82cd"
525
+ """
526
+ base = os.path.basename(name)
527
+ for ext in (".json", ".mp4"):
528
+ if base.endswith(ext):
529
+ return base[: -len(ext)]
530
+ return base
531
+
532
+
533
+ def _load_json(path: Path) -> Any:
534
+ with open(path, "r", encoding="utf-8") as f:
535
+ return json.load(f)
536
+
537
+
538
+ def _load_jsonl(path: Path) -> List[Dict[str, Any]]:
539
+ out: List[Dict[str, Any]] = []
540
+ with open(path, "r", encoding="utf-8") as f:
541
+ for ln, line in enumerate(f, 1):
542
+ line = line.strip()
543
+ if not line:
544
+ continue
545
+ try:
546
+ out.append(json.loads(line))
547
+ except json.JSONDecodeError as e:
548
+ log.warning("jsonl parse error %s:%d %s", path.name, ln, e)
549
+ return out
550
+
551
+
552
+ # ---------------------------------------------------------------------------
553
+ # VQA
554
+ # ---------------------------------------------------------------------------
555
+
556
+ VQA_QUESTION_PREFIX = "You are analyzing a surveillance or traffic monitoring video. Watch the video carefully before answering. Answer based only on what you observe in the video."
557
+
558
+ # Mirror of VANTAGE_VQA.generate_question (vlmeval/dataset/vantage_vqa.py)
559
+ def _vqa_format_question(base_question: str, options: List[str]) -> str:
560
+ labels = ["A", "B", "C", "D"]
561
+ out = "Question: " + base_question + "\n"
562
+ out += "Select your answer from the choices below:\n"
563
+ for i, lab in enumerate(labels[: len(options)]):
564
+ out += f"{lab}. {options[i]}\n"
565
+ out += (
566
+ "Respond with ONLY the letter corresponding to your answer (A, B, C, or D). "
567
+ "Do not provide any explanation or other text.\n"
568
+ )
569
+ return out
570
+
571
+
572
+ def _vqa_process_item(item: Dict[str, Any]) -> Optional[Dict[str, Any]]:
573
+ video = item.get("q_uid") or item.get("vid") or ""
574
+ if not video:
575
+ return None
576
+ # q_uid may end in .json (template file ref) or .mp4 (video ref) or nothing.
577
+ # Match the loader's _process_annotation_item logic: strip one of those.
578
+ video = _ensure_mp4(_strip_video_ext(video))
579
+ question = item.get("question", "")
580
+ if not question:
581
+ return None
582
+ raw_opts = item.get("options", []) or []
583
+ options: List[str] = []
584
+ for opt in raw_opts:
585
+ if isinstance(opt, str):
586
+ # Strip leading "A: " / "B: " labels if present (matches loader)
587
+ parts = opt.split(": ", 1)
588
+ options.append(parts[1] if len(parts) == 2 else opt)
589
+ else:
590
+ options.append(str(opt))
591
+ if not options:
592
+ return None
593
+ formatted = _vqa_format_question(question, options)
594
+ category = _normalize_category(item.get("industry") or item.get("category"))
595
+ return {
596
+ "video": video,
597
+ "question": formatted,
598
+ "answer": "",
599
+ "options": json.dumps(options, ensure_ascii=False),
600
+ "category": category,
601
+ "_qid": item.get("question_id", ""),
602
+ }
603
+
604
+
605
+ def _prep_vqa(snap_dir: Path, target_dir: Path, opts: Options) -> TaskResult:
606
+ res = TaskResult(task="vqa", lmu_name="VANTAGE_VQA", target_dir=target_dir, status="dry-run")
607
+ ann_dir = snap_dir / "data" / "vqa" / "data_jsons" / "annotations"
608
+ src_videos = snap_dir / "data" / "vqa" / "videos"
609
+ if not ann_dir.exists():
610
+ raise SystemExit(f"VQA annotations dir missing in snapshot: {ann_dir}")
611
+
612
+ rows: List[Dict[str, Any]] = []
613
+ seen: set = set()
614
+ for jf in sorted(ann_dir.glob("*.json")):
615
+ data = _load_json(jf)
616
+ if not isinstance(data, list):
617
+ log.debug("VQA: skipping non-list JSON %s", jf.name)
618
+ continue
619
+ res.source_files.append(jf.name)
620
+ for item in data:
621
+ proc = _vqa_process_item(item)
622
+ if proc is None:
623
+ continue
624
+ dedup_key = (proc["video"], proc["_qid"] or proc["question"][:80])
625
+ if dedup_key in seen:
626
+ continue
627
+ seen.add(dedup_key)
628
+ rows.append(proc)
629
+
630
+ rows.sort(key=lambda r: (r["video"], r["_qid"]))
631
+ for i, r in enumerate(rows):
632
+ r["index"] = i
633
+ r.pop("_qid", None)
634
+
635
+ # Inference-only schema: GT columns (answer, category) are dropped.
636
+ # build_prompt needs question + options; submission emit needs index + video.
637
+ columns = ["index", "video", "question", "options"]
638
+ tsv = target_dir / "VANTAGE_VQA.tsv"
639
+ media_dst = target_dir / "videos"
640
+
641
+ if opts.dry_run:
642
+ res.rows = len(rows)
643
+ res.media_count = sum(1 for _ in src_videos.glob("*.mp4")) if src_videos.exists() else 0
644
+ res.notes.append(f"plan: write {tsv} and link {res.media_count} videos")
645
+ return res
646
+
647
+ if opts.force_clean:
648
+ _wipe_dir(media_dst, opts.dry_run)
649
+ _write_tsv(tsv, rows, columns, opts.dry_run)
650
+ placed = _link_or_copy_dir(src_videos, media_dst, opts)
651
+ res.rows = len(rows)
652
+ res.media_count = placed
653
+ res.status = "built"
654
+ return res
655
+
656
+
657
+ # ---------------------------------------------------------------------------
658
+ # Event Verification
659
+ # ---------------------------------------------------------------------------
660
+
661
+ EV_DEFAULT_SYSTEM_PROMPT = (
662
+ "You are a warehouse safety monitoring system analyzing surveillance video. "
663
+ "Determine if a near-miss incident has occurred between a person and a forklift. "
664
+ "A near-miss is defined as a situation where a person and an operating forklift "
665
+ "come into dangerously close proximity without a collision occurring — for example, "
666
+ "a person crossing the path of a moving forklift, a forklift passing close behind "
667
+ "or in front of a person, or a person narrowly avoiding being struck. "
668
+ "Answer \"Yes\" if a near-miss is clearly visible. Otherwise, answer \"No\"."
669
+ )
670
+
671
+
672
+ def _ev_load_items(path: Path) -> List[Dict[str, Any]]:
673
+ raw = _load_json(path)
674
+ if isinstance(raw, dict) and "bcq" in raw:
675
+ return list(raw["bcq"])
676
+ if isinstance(raw, list):
677
+ return raw
678
+ log.warning("EV: unrecognized JSON shape in %s", path.name)
679
+ return []
680
+
681
+
682
+ def _prep_event_verification(snap_dir: Path, target_dir: Path, opts: Options) -> TaskResult:
683
+ res = TaskResult(task="event_verification", lmu_name="VANTAGE_EventVerification",
684
+ target_dir=target_dir, status="dry-run")
685
+ ann_dir = snap_dir / "data" / "event_verification" / "data_jsons" / "annotations"
686
+ src_videos = snap_dir / "data" / "event_verification" / "videos"
687
+ if not ann_dir.exists():
688
+ raise SystemExit(f"EV annotations dir missing in snapshot: {ann_dir}")
689
+
690
+ rows: List[Dict[str, Any]] = []
691
+ seen: set = set()
692
+ for jf in sorted(ann_dir.glob("*.json")):
693
+ items = _ev_load_items(jf)
694
+ if not items:
695
+ continue
696
+ res.source_files.append(jf.name)
697
+ for item in items:
698
+ video = item.get("video") or item.get("video_id") or ""
699
+ if not video:
700
+ continue
701
+ video = _ensure_mp4(os.path.basename(video))
702
+ question = item.get("question", "")
703
+ if not question:
704
+ continue
705
+ iid = item.get("id", "")
706
+ key = (video, iid or question[:80])
707
+ if key in seen:
708
+ continue
709
+ seen.add(key)
710
+ sys_prompt = item.get("system_prompt") or EV_DEFAULT_SYSTEM_PROMPT
711
+ category = _normalize_category(item.get("category"))
712
+ rows.append({
713
+ "video": video,
714
+ "system_prompt": sys_prompt,
715
+ "question": question,
716
+ "answer": "",
717
+ "category": category,
718
+ "_id": iid,
719
+ })
720
+
721
+ rows.sort(key=lambda r: (r["video"], r["_id"]))
722
+ for i, r in enumerate(rows):
723
+ r["index"] = i
724
+ r.pop("_id", None)
725
+
726
+ # Inference-only schema: GT columns (answer, category) dropped.
727
+ # system_prompt is REQUIRED — build_prompt reads line['system_prompt']
728
+ # unconditionally and it is prompt framing, not ground truth.
729
+ columns = ["index", "video", "system_prompt", "question"]
730
+ tsv = target_dir / "VANTAGE_EventVerification.tsv"
731
+ media_dst = target_dir / "videos"
732
+
733
+ if opts.dry_run:
734
+ res.rows = len(rows)
735
+ res.media_count = sum(1 for _ in src_videos.glob("*.mp4")) if src_videos.exists() else 0
736
+ res.notes.append(f"plan: write {tsv} and link {res.media_count} videos")
737
+ return res
738
+
739
+ if opts.force_clean:
740
+ _wipe_dir(media_dst, opts.dry_run)
741
+ _write_tsv(tsv, rows, columns, opts.dry_run)
742
+ placed = _link_or_copy_dir(src_videos, media_dst, opts)
743
+ res.rows = len(rows)
744
+ res.media_count = placed
745
+ res.status = "built"
746
+ return res
747
+
748
+
749
+ # ---------------------------------------------------------------------------
750
+ # DVC
751
+ # ---------------------------------------------------------------------------
752
+
753
+ def _prep_dvc(snap_dir: Path, target_dir: Path, opts: Options) -> TaskResult:
754
+ res = TaskResult(task="dvc", lmu_name="VANTAGE_DVC", target_dir=target_dir, status="dry-run")
755
+ meta_path = snap_dir / "data" / "dense_captioning" / "metadata.jsonl"
756
+ src_videos = snap_dir / "data" / "dense_captioning" / "videos"
757
+ if not meta_path.exists():
758
+ raise SystemExit(f"DVC metadata.jsonl missing in snapshot: {meta_path}")
759
+
760
+ items = _load_jsonl(meta_path)
761
+ res.source_files.append(meta_path.name)
762
+
763
+ rows: List[Dict[str, Any]] = []
764
+ for item in items:
765
+ file_name = item.get("file_name") or item.get("video") or ""
766
+ if not file_name:
767
+ continue
768
+ video = _ensure_mp4(os.path.basename(file_name))
769
+ prompt = item.get("prompt") or item.get("question") or ""
770
+ if not prompt:
771
+ continue
772
+ rows.append({
773
+ "video": video,
774
+ "question": prompt,
775
+ "answer": "",
776
+ "category": "Unknown",
777
+ })
778
+
779
+ rows.sort(key=lambda r: r["video"])
780
+ for i, r in enumerate(rows):
781
+ r["index"] = i
782
+
783
+ # Inference-only schema: GT columns (answer, category) dropped.
784
+ # DVC build_prompt uses a constant query; question is kept for readability.
785
+ columns = ["index", "video", "question"]
786
+ tsv = target_dir / "VANTAGE_DVC.tsv"
787
+ media_dst = target_dir / "videos"
788
+
789
+ if opts.dry_run:
790
+ res.rows = len(rows)
791
+ res.media_count = sum(1 for _ in src_videos.glob("*.mp4")) if src_videos.exists() else 0
792
+ res.notes.append(f"plan: write {tsv} and link {res.media_count} videos")
793
+ return res
794
+
795
+ if opts.force_clean:
796
+ _wipe_dir(media_dst, opts.dry_run)
797
+ _write_tsv(tsv, rows, columns, opts.dry_run)
798
+ placed = _link_or_copy_dir(src_videos, media_dst, opts)
799
+ res.rows = len(rows)
800
+ res.media_count = placed
801
+ res.status = "built"
802
+ return res
803
+
804
+
805
+ # ---------------------------------------------------------------------------
806
+ # Temporal
807
+ # ---------------------------------------------------------------------------
808
+
809
+ TEMPORAL_QUESTION_PREFIX = (
810
+ "Localize a series of activity events in the video, output the start and end "
811
+ "timestamp for each event. Provide the result in json format with 'mm:ss.ff' "
812
+ "format for time depiction for this event. Use keywords 'start' and 'end' in "
813
+ "the json output."
814
+ )
815
+
816
+
817
+ def _prep_temporal(snap_dir: Path, target_dir: Path, opts: Options) -> TaskResult:
818
+ res = TaskResult(task="temporal", lmu_name="VANTAGE_Temporal", target_dir=target_dir, status="dry-run")
819
+ ann_dir = snap_dir / "data" / "temporal_localization" / "data_jsons" / "annotations"
820
+ src_videos = snap_dir / "data" / "temporal_localization" / "videos"
821
+ if not ann_dir.exists():
822
+ raise SystemExit(f"Temporal annotations dir missing in snapshot: {ann_dir}")
823
+
824
+ rows: List[Dict[str, Any]] = []
825
+ seen_qids: set = set()
826
+ for jf in sorted(ann_dir.glob("*.json")):
827
+ data = _load_json(jf)
828
+ if not isinstance(data, list):
829
+ log.debug("Temporal: skipping non-list JSON %s", jf.name)
830
+ continue
831
+ res.source_files.append(jf.name)
832
+ for item in data:
833
+ vid = item.get("vid") or item.get("video") or ""
834
+ if not vid:
835
+ continue
836
+ # Loader appends ".mp4" itself, so store bare stem.
837
+ vid = _strip_mp4(os.path.basename(vid))
838
+ base_q = item.get("question", "")
839
+ if not base_q:
840
+ continue
841
+ qid = item.get("question_id", "")
842
+ if qid and qid in seen_qids:
843
+ continue
844
+ if qid:
845
+ seen_qids.add(qid)
846
+ duration = item.get("duration", 30.0)
847
+ try:
848
+ duration = float(duration)
849
+ except (TypeError, ValueError):
850
+ duration = 30.0
851
+ question = TEMPORAL_QUESTION_PREFIX + "\n" + base_q
852
+ category = _normalize_category(item.get("category"))
853
+ rows.append({
854
+ "video": vid,
855
+ "question": question,
856
+ "answer": "",
857
+ "duration": duration,
858
+ "category": category,
859
+ "_qid": qid or f"{vid}_0",
860
+ })
861
+
862
+ rows.sort(key=lambda r: (r["video"], r["_qid"]))
863
+ for i, r in enumerate(rows):
864
+ r["index"] = i
865
+ r.pop("_qid", None)
866
+
867
+ # Inference-only schema: GT columns (answer, category) and the
868
+ # evaluation-only 'duration' field are dropped. build_prompt reads only
869
+ # question + video; duration is consumed solely by evaluate().
870
+ columns = ["index", "video", "question"]
871
+ tsv = target_dir / "VANTAGE_Temporal.tsv"
872
+ media_dst = target_dir / "videos"
873
+
874
+ if opts.dry_run:
875
+ res.rows = len(rows)
876
+ res.media_count = sum(1 for _ in src_videos.glob("*.mp4")) if src_videos.exists() else 0
877
+ res.notes.append(f"plan: write {tsv} and link {res.media_count} videos")
878
+ return res
879
+
880
+ if opts.force_clean:
881
+ _wipe_dir(media_dst, opts.dry_run)
882
+ _write_tsv(tsv, rows, columns, opts.dry_run)
883
+ placed = _link_or_copy_dir(src_videos, media_dst, opts)
884
+ res.rows = len(rows)
885
+ res.media_count = placed
886
+ res.status = "built"
887
+ return res
888
+
889
+
890
+ # ---------------------------------------------------------------------------
891
+ # 2DPointing (JSONL -> TSV)
892
+ # ---------------------------------------------------------------------------
893
+
894
+ POINTING_COLUMNS = ["index", "question_id", "image_path", "question", "A", "B", "C", "D"]
895
+
896
+
897
+ def _prep_pointing(snap_dir: Path, target_dir: Path, opts: Options) -> TaskResult:
898
+ res = TaskResult(task="pointing", lmu_name="VANTAGE_2DPointing",
899
+ target_dir=target_dir, status="dry-run")
900
+ jsonl_path = snap_dir / "data" / "pointing" / "VANTAGE_2DPointing.jsonl"
901
+ src_images = snap_dir / "data" / "pointing" / "images_annotated"
902
+ if not jsonl_path.exists():
903
+ raise SystemExit(
904
+ f"Pointing JSONL missing in snapshot: {jsonl_path}\n"
905
+ "The script targets the post-PR layout where pointing is JSONL. If the "
906
+ "live nvidia/PhysicalAI-VANTAGE-Bench still ships a TSV, this task will "
907
+ "fail until the PR merges."
908
+ )
909
+ res.source_files.append(jsonl_path.name)
910
+
911
+ items = _load_jsonl(jsonl_path)
912
+ rows: List[Dict[str, Any]] = []
913
+ missing_images: List[str] = []
914
+ for i, item in enumerate(items):
915
+ row = {col: item.get(col, "") for col in POINTING_COLUMNS}
916
+ # Re-index for safety in case source skips indices.
917
+ row["index"] = item.get("index", i)
918
+ # Sanity: image_path should resolve under images_annotated/
919
+ ip = str(row.get("image_path", ""))
920
+ if not ip.startswith("images_annotated/"):
921
+ res.notes.append(f"unexpected image_path prefix: {ip}")
922
+ else:
923
+ rel = ip[len("images_annotated/"):]
924
+ if src_images.exists() and not (src_images / rel).exists():
925
+ missing_images.append(rel)
926
+ rows.append(row)
927
+
928
+ if missing_images:
929
+ res.notes.append(f"{len(missing_images)} image paths not resolvable in snapshot")
930
+ if opts.verbose:
931
+ for m in missing_images[:5]:
932
+ log.warning("pointing: missing image %s", m)
933
+
934
+ tsv = target_dir / "VANTAGE_2DPointing.tsv"
935
+ media_dst = target_dir / "images_annotated"
936
+
937
+ if opts.dry_run:
938
+ res.rows = len(rows)
939
+ res.media_count = sum(1 for p in src_images.iterdir() if p.is_file()) if src_images.exists() else 0
940
+ res.notes.append(f"plan: write {tsv} and link {res.media_count} images")
941
+ return res
942
+
943
+ if opts.force_clean:
944
+ _wipe_dir(media_dst, opts.dry_run)
945
+ _write_tsv(tsv, rows, POINTING_COLUMNS, opts.dry_run)
946
+ placed = _link_or_copy_dir(src_images, media_dst, opts)
947
+ res.rows = len(rows)
948
+ res.media_count = placed
949
+ res.status = "built"
950
+ return res
951
+
952
+
953
+ # ---------------------------------------------------------------------------
954
+ # Astro2D
955
+ # ---------------------------------------------------------------------------
956
+
957
+ # The KITTI labels are NOT publicly released. The VLMEvalKit loader
958
+ # (vlmeval/dataset/vantage2d/astro_2d_dataset.py:_build_data_structure) silently
959
+ # DROPS any image that lacks a matching labels/<base>.txt file. To keep all
960
+ # images visible to the loader for inference, we emit zero-byte placeholder
961
+ # label files. They are NOT inferred or fabricated GT — parse_kitti_label on
962
+ # an empty file returns an empty object list, which is the no-GT semantic.
963
+ ASTRO2D_SEQUENCES = ("sequence_a", "sequence_b", "sequence_c")
964
+
965
+
966
+ def _prep_astro2d(snap_dir: Path, target_dir: Path, opts: Options) -> TaskResult:
967
+ res = TaskResult(task="astro2d", lmu_name="Astro2D", target_dir=target_dir, status="dry-run")
968
+ src_root = snap_dir / "data" / "2dbbox"
969
+ if not src_root.exists():
970
+ raise SystemExit(f"Astro2D source missing in snapshot: {src_root}")
971
+
972
+ images_dst = target_dir / "images"
973
+ labels_dst = target_dir / "labels"
974
+
975
+ if opts.force_clean:
976
+ _wipe_dir(images_dst, opts.dry_run)
977
+ _wipe_dir(labels_dst, opts.dry_run)
978
+ _ensure_dir(images_dst, opts.dry_run)
979
+ _ensure_dir(labels_dst, opts.dry_run)
980
+
981
+ image_count = 0
982
+ label_count = 0
983
+ res.source_files.append("sequence_a/b/c/images/*")
984
+ for seq in ASTRO2D_SEQUENCES:
985
+ seq_dir = src_root / seq / "images"
986
+ if not seq_dir.exists():
987
+ res.notes.append(f"missing source: {seq}/images")
988
+ continue
989
+ for img in sorted(seq_dir.iterdir()):
990
+ if not img.is_file():
991
+ continue
992
+ ext = img.suffix.lower()
993
+ if ext not in {".jpg", ".jpeg", ".png", ".bmp", ".tiff"}:
994
+ continue
995
+ # Prefix with sequence name to avoid cross-sequence basename collisions.
996
+ flat_name = f"{seq}_{img.name}"
997
+ img_dst = images_dst / flat_name
998
+ _link_or_copy_file(img, img_dst, opts)
999
+ image_count += 1
1000
+ # Empty placeholder label (NOT inferred GT — see header comment).
1001
+ stem = Path(flat_name).stem
1002
+ lbl_dst = labels_dst / f"{stem}.txt"
1003
+ if not lbl_dst.exists() and not opts.dry_run:
1004
+ lbl_dst.touch()
1005
+ label_count += 1
1006
+ elif not lbl_dst.exists() and opts.dry_run:
1007
+ label_count += 1
1008
+
1009
+ res.media_count = image_count
1010
+ res.notes.append(f"emitted {label_count} empty label placeholders (no-GT)")
1011
+ res.status = "built"
1012
+ return res
1013
+
1014
+
1015
+ # ---------------------------------------------------------------------------
1016
+ # Grounding (VANTAGE_2DGrounding)
1017
+ # ---------------------------------------------------------------------------
1018
+
1019
+ def _grounding_build_annotations(llava_path: Path) -> List[Dict[str, Any]]:
1020
+ """Convert HF refdrone_test_llava.json -> loader-compatible no-GT entries.
1021
+
1022
+ Output schema (per loader vlmeval/dataset/vantage2d/grounding_2d_dataset.py
1023
+ parse_refcoco_annotations no-GT branch):
1024
+ {image, sentence, width, height, category}
1025
+ No `bboxes` key is emitted (loader's no-GT branch is triggered when the
1026
+ first item lacks `bboxes`).
1027
+ """
1028
+ raw = _load_json(llava_path)
1029
+ if not isinstance(raw, list):
1030
+ raise SystemExit(f"unexpected grounding annotation shape in {llava_path}")
1031
+ out: List[Dict[str, Any]] = []
1032
+ for item in raw:
1033
+ meta = item.get("_meta", {}) or {}
1034
+ sentence = meta.get("sentence") or ""
1035
+ if not sentence:
1036
+ # Try to recover sentence from human conversation if _meta is absent.
1037
+ for conv in item.get("conversations", []):
1038
+ if conv.get("from") == "human":
1039
+ txt = conv.get("value", "")
1040
+ m = re.search(r'"(.+?)"', txt)
1041
+ if m:
1042
+ sentence = m.group(1)
1043
+ break
1044
+ if not sentence:
1045
+ continue
1046
+ media = item.get("media") or ""
1047
+ image = os.path.basename(media) if media else ""
1048
+ if not image:
1049
+ continue
1050
+ out.append({
1051
+ "image": image,
1052
+ "sentence": sentence,
1053
+ "width": meta.get("image_width"),
1054
+ "height": meta.get("image_height"),
1055
+ "category": meta.get("object_category", ""),
1056
+ })
1057
+ return out
1058
+
1059
+
1060
+ def _run_refdrone_prep_script(script_src: Path, work_root: Path, force: bool,
1061
+ opts: Options) -> Path:
1062
+ """Stage prep_refdrone_data.py in a writable workdir at the depth it
1063
+ expects (<work_root>/scripts/refdrone/...), run it, and return the
1064
+ resulting images dir.
1065
+
1066
+ The script hard-codes REPO_ROOT = __file__.parent.parent.parent, so the
1067
+ output ends up at <work_root>/LMUData/Spatial/2d_referring_expressions/refdrone/.
1068
+ """
1069
+ script_dir = work_root / "scripts" / "refdrone"
1070
+ script_dir.mkdir(parents=True, exist_ok=True)
1071
+ staged = script_dir / "prep_refdrone_data.py"
1072
+ if not staged.exists() or force:
1073
+ shutil.copy2(script_src, staged)
1074
+ cmd = [sys.executable, str(staged)]
1075
+ if force:
1076
+ cmd.append("--force")
1077
+ log.info("[grounding] running %s", " ".join(cmd))
1078
+ try:
1079
+ # Stream output so the user sees download progress.
1080
+ subprocess.run(cmd, check=True, cwd=str(work_root))
1081
+ except subprocess.CalledProcessError as e:
1082
+ raise SystemExit(
1083
+ f"[grounding] prep_refdrone_data.py failed (exit {e.returncode}). "
1084
+ f"VisDrone mirrors may be down or unreachable. Re-run with --skip-grounding-images "
1085
+ f"if you already have images/, or retry later."
1086
+ ) from e
1087
+ except FileNotFoundError as e:
1088
+ raise SystemExit(f"[grounding] failed to launch prep script: {e}") from e
1089
+
1090
+ images_dir = work_root / "LMUData" / "Spatial" / "2d_referring_expressions" / "refdrone" / "images"
1091
+ if not images_dir.exists() or not any(images_dir.iterdir()):
1092
+ raise SystemExit(f"[grounding] prep script produced no images at {images_dir}")
1093
+ return images_dir
1094
+
1095
+
1096
+ def _prep_grounding(snap_dir: Path, target_dir: Path, opts: Options) -> TaskResult:
1097
+ res = TaskResult(task="grounding", lmu_name="VANTAGE_2DGrounding",
1098
+ target_dir=target_dir, status="dry-run")
1099
+ src_root = snap_dir / "data" / "referring"
1100
+ llava_path = src_root / "refdrone_test_llava.json"
1101
+ prep_script = src_root / "prep_refdrone_data.py"
1102
+ if not llava_path.exists():
1103
+ raise SystemExit(f"Grounding annotation missing in snapshot: {llava_path}")
1104
+ if not prep_script.exists() and not opts.skip_grounding_images:
1105
+ raise SystemExit(
1106
+ f"Grounding prep script missing in snapshot: {prep_script}\n"
1107
+ "Pass --skip-grounding-images if you have pre-staged images."
1108
+ )
1109
+ res.source_files.append(llava_path.name)
1110
+
1111
+ # 1) Convert annotations (no-GT entries).
1112
+ entries = _grounding_build_annotations(llava_path)
1113
+ ann_dst = target_dir / "annotations.json"
1114
+ log.info("write %s (%d entries, no-GT)", ann_dst, len(entries))
1115
+ if not opts.dry_run:
1116
+ ann_dst.parent.mkdir(parents=True, exist_ok=True)
1117
+ with open(ann_dst, "w", encoding="utf-8") as f:
1118
+ json.dump(entries, f, indent=2, ensure_ascii=False)
1119
+
1120
+ # 2) Materialize images.
1121
+ images_dst = target_dir / "images"
1122
+ if opts.force_clean:
1123
+ _wipe_dir(images_dst, opts.dry_run)
1124
+ _ensure_dir(images_dst, opts.dry_run)
1125
+
1126
+ if opts.skip_grounding_images:
1127
+ res.notes.append("--skip-grounding-images: images/ left as-is")
1128
+ # Count whatever is already there for reporting.
1129
+ if images_dst.exists():
1130
+ res.media_count = sum(1 for p in images_dst.iterdir() if p.is_file())
1131
+ else:
1132
+ work_root = target_dir.parent.parent / ".work" / "grounding"
1133
+ work_root.mkdir(parents=True, exist_ok=True)
1134
+ try:
1135
+ src_images = _run_refdrone_prep_script(prep_script, work_root, opts.force, opts)
1136
+ except SystemExit:
1137
+ raise
1138
+ placed = _link_or_copy_dir(src_images, images_dst, opts)
1139
+ res.media_count = placed
1140
+ res.notes.append(f"linked {placed} VisDrone images from prep workdir")
1141
+
1142
+ res.rows = len(entries)
1143
+ res.status = "built"
1144
+ return res
1145
+
1146
+
1147
+ # ---------------------------------------------------------------------------
1148
+ # SOT
1149
+ # ---------------------------------------------------------------------------
1150
+
1151
+ def _sot_write_gt_jsons(benchmark_path: Path, target_dir: Path, opts: Options) -> Tuple[int, int]:
1152
+ """For each entry in sot_benchmark.jsonl, write <target>/<seq_id>/gt.json
1153
+ with public init_bbox only (no hidden trajectories).
1154
+
1155
+ Returns (gt_written, frames_present).
1156
+ """
1157
+ items = _load_jsonl(benchmark_path)
1158
+ gt_written = 0
1159
+ frames_present = 0
1160
+ for item in items:
1161
+ seq_id = item.get("seq_id")
1162
+ if not seq_id:
1163
+ continue
1164
+ seq_dir = target_dir / seq_id
1165
+ if not seq_dir.exists():
1166
+ # prepare_sot_dataset.py may have skipped this seq (download failure, etc.)
1167
+ continue
1168
+ canonical = item.get("canonical_frame_ids") or []
1169
+ n_frames = len(canonical) if canonical else 8
1170
+ init_bbox = item.get("init_bbox")
1171
+ if init_bbox is None:
1172
+ log.warning("SOT: %s has no init_bbox in benchmark — skipping gt.json", seq_id)
1173
+ continue
1174
+ # NOTE: only frame 0 (init) gets a public bbox. Other frames are
1175
+ # absent on purpose — server-side scoring uses hidden trajectories.
1176
+ gt = {
1177
+ "label": f"{item.get('scene','')}/{item.get('camera','')}/"
1178
+ f"{item.get('init_frame_id','')}/obj{item.get('object_id','')}",
1179
+ "scene": item.get("scene", ""),
1180
+ "camera": item.get("camera", ""),
1181
+ "object_id": str(item.get("object_id", "")),
1182
+ "object_type": item.get("object_type", "object"),
1183
+ "frame_ids": list(range(n_frames)),
1184
+ "source_frame_ids": canonical,
1185
+ "init_bbox": init_bbox,
1186
+ "gt_bboxes": {"0": init_bbox},
1187
+ }
1188
+ gt_path = seq_dir / "gt.json"
1189
+ if not opts.dry_run:
1190
+ with open(gt_path, "w", encoding="utf-8") as f:
1191
+ json.dump(gt, f, indent=2)
1192
+ gt_written += 1
1193
+ frames_dir = seq_dir / "frames"
1194
+ if frames_dir.is_dir():
1195
+ frames_present += sum(1 for p in frames_dir.iterdir() if p.suffix == ".png")
1196
+ return gt_written, frames_present
1197
+
1198
+
1199
+ def _discover_ffmpeg_dir() -> Optional[str]:
1200
+ """Return a directory containing an ffmpeg binary, or None.
1201
+
1202
+ Searches PATH first, then common conda-env bin dirs (the prep script's own
1203
+ find_ffmpeg() does NOT look inside conda envs, so we bridge that gap by
1204
+ prepending the discovered dir to the subprocess PATH).
1205
+ """
1206
+ found = shutil.which("ffmpeg")
1207
+ if found:
1208
+ return os.path.dirname(found)
1209
+ import glob
1210
+ patterns = [
1211
+ os.path.expanduser("~/miniconda3/envs/*/bin/ffmpeg"),
1212
+ os.path.expanduser("~/anaconda3/envs/*/bin/ffmpeg"),
1213
+ "/opt/conda/envs/*/bin/ffmpeg",
1214
+ os.path.expanduser("~/miniconda3/bin/ffmpeg"),
1215
+ os.path.expanduser("~/anaconda3/bin/ffmpeg"),
1216
+ "/opt/conda/bin/ffmpeg",
1217
+ ]
1218
+ for pat in patterns:
1219
+ hits = sorted(glob.glob(pat))
1220
+ if hits:
1221
+ return os.path.dirname(hits[0])
1222
+ return None
1223
+
1224
+
1225
+ def _resolve_hf_token(cli_token: Optional[str]) -> Optional[str]:
1226
+ """Resolve an HF token: --hf-token, then HF_TOKEN env, then the token
1227
+ saved by `hf auth login` (huggingface_hub.get_token())."""
1228
+ if cli_token:
1229
+ return cli_token
1230
+ env = os.environ.get("HF_TOKEN")
1231
+ if env:
1232
+ return env
1233
+ try:
1234
+ from huggingface_hub import get_token
1235
+ tok = get_token()
1236
+ if tok:
1237
+ return tok
1238
+ except Exception:
1239
+ pass
1240
+ return None
1241
+
1242
+
1243
+ def _run_sot_prep_script(script_path: Path, benchmark_path: Path, output_dir: Path,
1244
+ opts: Options) -> None:
1245
+ """Invoke prepare_sot_dataset.py to download videos + extract frames."""
1246
+ token = opts.hf_token # already resolved (cli/env/stored) in main()
1247
+ if not token:
1248
+ raise SystemExit(
1249
+ "[sot] No HF token found. Provide one of:\n"
1250
+ " - run `hf auth login` (token is then auto-detected), or\n"
1251
+ " - export HF_TOKEN=hf_xxx, or\n"
1252
+ " - pass --hf-token hf_xxx\n"
1253
+ f"Source videos come from {SOT_SOURCE_REPO_ID}. If it is gated, accept\n"
1254
+ f"the license at https://huggingface.co/datasets/{SOT_SOURCE_REPO_ID}"
1255
+ )
1256
+ # ffmpeg check — the prep script requires it for frame extraction.
1257
+ ffmpeg_dir = _discover_ffmpeg_dir()
1258
+ if ffmpeg_dir is None:
1259
+ raise SystemExit(
1260
+ "[sot] ffmpeg not found. Frame extraction in prepare_sot_dataset.py "
1261
+ "requires it. Easiest installs:\n"
1262
+ " - conda install -c conda-forge ffmpeg\n"
1263
+ " - (Debian/Ubuntu) sudo apt-get install -y ffmpeg\n"
1264
+ " - or a static build from https://johnvansickle.com/ffmpeg/\n"
1265
+ "Then re-run. (Tip: an ffmpeg inside a conda env is auto-detected.)"
1266
+ )
1267
+ # Bridge conda-env ffmpeg onto the subprocess PATH (the prep script's
1268
+ # find_ffmpeg does not search conda envs).
1269
+ child_env = os.environ.copy()
1270
+ if shutil.which("ffmpeg") is None:
1271
+ child_env["PATH"] = ffmpeg_dir + os.pathsep + child_env.get("PATH", "")
1272
+ log.info("[sot] using ffmpeg from %s", ffmpeg_dir)
1273
+ cmd = [
1274
+ sys.executable, str(script_path),
1275
+ "--benchmark", str(benchmark_path),
1276
+ "--output-dir", str(output_dir),
1277
+ "--hf-token", token,
1278
+ "--repo-id", SOT_SOURCE_REPO_ID,
1279
+ "--repo-subdir", SOT_SOURCE_REPO_SUBDIR,
1280
+ ]
1281
+ if opts.hf_cache is not None:
1282
+ cmd += ["--hf-cache-dir", str(opts.hf_cache)]
1283
+ log.info("[sot] running %s", " ".join(cmd[:6] + ["..."]))
1284
+ try:
1285
+ subprocess.run(cmd, check=True, env=child_env)
1286
+ except subprocess.CalledProcessError as e:
1287
+ # Most common failure: 401/403 from HF (gated dataset).
1288
+ raise SystemExit(
1289
+ f"[sot] prepare_sot_dataset.py failed (exit {e.returncode}). "
1290
+ f"If HTTP 401/403: confirm license acceptance at "
1291
+ f"https://huggingface.co/datasets/{SOT_SOURCE_REPO_ID} and that your "
1292
+ f"HF token has read access."
1293
+ ) from e
1294
+
1295
+
1296
+ def _prep_sot(snap_dir: Path, target_dir: Path, opts: Options) -> TaskResult:
1297
+ res = TaskResult(task="sot", lmu_name="VANTAGE_SOT",
1298
+ target_dir=target_dir, status="dry-run")
1299
+ src_root = snap_dir / "data" / "tracking"
1300
+ benchmark = src_root / "sot_benchmark.jsonl"
1301
+ prep_script = src_root / "prepare_sot_dataset.py"
1302
+ if not benchmark.exists():
1303
+ raise SystemExit(f"SOT benchmark missing in snapshot: {benchmark}")
1304
+ if not prep_script.exists():
1305
+ raise SystemExit(f"SOT prep script missing in snapshot: {prep_script}")
1306
+ res.source_files.append(benchmark.name)
1307
+
1308
+ if opts.force_clean:
1309
+ # Wipe per-seq dirs (but keep target_dir itself).
1310
+ if target_dir.exists():
1311
+ for child in list(target_dir.iterdir()):
1312
+ if child.is_dir():
1313
+ _wipe_dir(child, opts.dry_run)
1314
+ _ensure_dir(target_dir, opts.dry_run)
1315
+
1316
+ # 1) Run the prep script (downloads videos + extracts frames).
1317
+ _run_sot_prep_script(prep_script, benchmark, target_dir, opts)
1318
+
1319
+ # 2) Write per-sequence gt.json from public init_bbox.
1320
+ gt_written, frames_present = _sot_write_gt_jsons(benchmark, target_dir, opts)
1321
+ res.rows = gt_written
1322
+ res.media_count = frames_present
1323
+ res.notes.append(f"wrote {gt_written} gt.json files (init_bbox only, no hidden trajectories)")
1324
+ res.notes.append(f"{frames_present} frame .png files present")
1325
+ res.status = "built"
1326
+ return res
1327
+
1328
+
1329
+ # ---------------------------------------------------------------------------
1330
+ # Deferred-task stubs
1331
+ # ---------------------------------------------------------------------------
1332
+
1333
+ # (No deferred stubs in PHASE 2B — all eight tasks are implemented.)
1334
+
1335
+
1336
+ # ---------------------------------------------------------------------------
1337
+ # Dispatch
1338
+ # ---------------------------------------------------------------------------
1339
+
1340
+ PREP_FNS: Dict[str, Callable[..., TaskResult]] = {
1341
+ "vqa": _prep_vqa,
1342
+ "event_verification": _prep_event_verification,
1343
+ "dvc": _prep_dvc,
1344
+ "temporal": _prep_temporal,
1345
+ "pointing": _prep_pointing,
1346
+ "astro2d": _prep_astro2d,
1347
+ "grounding": _prep_grounding,
1348
+ "sot": _prep_sot,
1349
+ }
1350
+
1351
+
1352
+ def _dry_run_plan(task: str, target_dir: Path, opts: Options,
1353
+ source_mode: str, source_root: Optional[Path]) -> TaskResult:
1354
+ """Pure dry-run summary. No disk writes. For hf mode no download happens."""
1355
+ cfg = TASK_CONFIG[task]
1356
+ res = TaskResult(
1357
+ task=task,
1358
+ lmu_name=cfg["lmu_name"],
1359
+ target_dir=target_dir,
1360
+ status="dry-run",
1361
+ )
1362
+ if source_mode in ("local-explicit", "local-auto"):
1363
+ res.notes.append(f"source: {source_mode}:{source_root}")
1364
+ # Per-task markers already validated by _resolve_source.
1365
+ res.notes.append(f"would read from local data/{_task_data_subdir(task)}/ "
1366
+ f"(no HF download)")
1367
+ else:
1368
+ res.notes.append(f"source: hf:{opts.hf_repo}")
1369
+ res.notes.append(f"would download HF patterns: {cfg['hf_patterns']}")
1370
+ if task == "astro2d":
1371
+ res.notes.append(f"would flatten sequence_{{a,b,c}}/images -> {target_dir}/images/")
1372
+ res.notes.append(f"would emit empty placeholder labels at {target_dir}/labels/ (no-GT)")
1373
+ elif task == "grounding":
1374
+ res.notes.append(f"would write {target_dir}/annotations.json (no-GT)")
1375
+ if opts.skip_grounding_images:
1376
+ res.notes.append("would skip VisDrone image download (--skip-grounding-images)")
1377
+ else:
1378
+ res.notes.append("would invoke prep_refdrone_data.py to download VisDrone (~297 MB)")
1379
+ res.notes.append(f"would populate: {target_dir}/images/")
1380
+ elif task == "sot":
1381
+ res.notes.append(f"would invoke prepare_sot_dataset.py against {SOT_SOURCE_REPO_ID}")
1382
+ res.notes.append(f"would write per-seq <seq>/gt.json under {target_dir}/")
1383
+ token = opts.hf_token # resolved (cli/env/stored) in main()
1384
+ if token:
1385
+ res.notes.append("preflight: HF token detected")
1386
+ else:
1387
+ res.notes.append("PREFLIGHT FAIL: no HF token (run `hf auth login`, "
1388
+ "export HF_TOKEN, or pass --hf-token)")
1389
+ ffdir = _discover_ffmpeg_dir()
1390
+ if ffdir:
1391
+ res.notes.append(f"preflight: ffmpeg found ({ffdir})")
1392
+ else:
1393
+ res.notes.append("PREFLIGHT FAIL: ffmpeg not found "
1394
+ "(conda install -c conda-forge ffmpeg)")
1395
+ else:
1396
+ idx_name = cfg.get("index_file")
1397
+ if idx_name:
1398
+ res.notes.append(f"would write: {target_dir / idx_name}")
1399
+ res.notes.append(f"would populate: {target_dir / cfg['media_dir']}/")
1400
+ return res
1401
+
1402
+
1403
+ def _run_task(task: str, opts: Options) -> TaskResult:
1404
+ target_dir = _target_dir(opts.lmu_root, task)
1405
+
1406
+ # Idempotency: skip if integrity passes and not forcing
1407
+ if not opts.force and target_dir.exists():
1408
+ ok, why = _check_integrity(task, target_dir)
1409
+ if ok:
1410
+ log.info("[%s] skip — already populated at %s", task, target_dir)
1411
+ return TaskResult(
1412
+ task=task,
1413
+ lmu_name=TASK_CONFIG[task]["lmu_name"],
1414
+ target_dir=target_dir,
1415
+ status="skipped",
1416
+ notes=[why],
1417
+ )
1418
+ else:
1419
+ log.info("[%s] partial state (%s) — will rebuild", task, why)
1420
+
1421
+ # Resolve where the source data comes from (validates local sources;
1422
+ # for hf mode this downloads, unless dry-run, in which case it returns None).
1423
+ source_root, source_mode = _resolve_source(task, opts)
1424
+
1425
+ # Dry-run short-circuits before any disk write.
1426
+ if opts.dry_run:
1427
+ log.info("[%s] dry-run (source=%s) — no writes", task, source_mode)
1428
+ res = _dry_run_plan(task, target_dir, opts, source_mode, source_root)
1429
+ res.source_mode = source_mode
1430
+ return res
1431
+
1432
+ _ensure_dir(target_dir, opts.dry_run)
1433
+ fn = PREP_FNS[task]
1434
+ res = fn(source_root, target_dir, opts)
1435
+ res.source_mode = source_mode
1436
+ if opts.force and res.status == "built":
1437
+ res.status = "rebuilt"
1438
+
1439
+ if res.status in ("built", "rebuilt"):
1440
+ ok, why = _check_integrity(task, target_dir)
1441
+ if not ok:
1442
+ res.notes.append(f"post-build integrity check FAILED: {why}")
1443
+ res.status = "failed"
1444
+ else:
1445
+ res.notes.append(f"integrity ok: {why}")
1446
+ return res
1447
+
1448
+
1449
+ # ---------------------------------------------------------------------------
1450
+ # Manifest
1451
+ # ---------------------------------------------------------------------------
1452
+
1453
+ def _write_manifest(lmu_root: Path, results: List[TaskResult], opts: Options) -> None:
1454
+ manifest_path = lmu_root / MANIFEST_FILENAME
1455
+ payload = {
1456
+ "generated_at": datetime.datetime.now(datetime.timezone.utc).isoformat(),
1457
+ "hf_repo": opts.hf_repo,
1458
+ "hf_repo_production_default": HF_REPO_ID,
1459
+ "hf_repo_type": HF_REPO_TYPE,
1460
+ "lmu_root": str(lmu_root),
1461
+ "local_source": str(opts.local_source) if opts.local_source else None,
1462
+ "options": {
1463
+ "media_mode": "symlink" if opts.symlink else "copy",
1464
+ "force": opts.force,
1465
+ "force_clean": opts.force_clean,
1466
+ "dry_run": opts.dry_run,
1467
+ "skip_grounding_images": opts.skip_grounding_images,
1468
+ },
1469
+ "tasks": [
1470
+ {
1471
+ "task": r.task,
1472
+ "lmu_name": r.lmu_name,
1473
+ "target_dir": str(r.target_dir),
1474
+ "status": r.status,
1475
+ "source_mode": r.source_mode,
1476
+ "rows": r.rows,
1477
+ "media_count": r.media_count,
1478
+ "source_files": r.source_files,
1479
+ "notes": r.notes,
1480
+ }
1481
+ for r in results
1482
+ ],
1483
+ }
1484
+ if opts.dry_run:
1485
+ log.info("would write manifest %s (--write-manifest)", manifest_path)
1486
+ return
1487
+ log.info("write manifest %s", manifest_path)
1488
+ lmu_root.mkdir(parents=True, exist_ok=True)
1489
+ with open(manifest_path, "w", encoding="utf-8") as f:
1490
+ json.dump(payload, f, indent=2)
1491
+
1492
+
1493
+ # ---------------------------------------------------------------------------
1494
+ # CLI
1495
+ # ---------------------------------------------------------------------------
1496
+
1497
+ def _parse_tasks(raw: Optional[str], all_flag: bool) -> List[str]:
1498
+ if all_flag:
1499
+ return list(IMPLEMENTED_TASKS) # deferred tasks intentionally excluded
1500
+ if not raw:
1501
+ return list(IMPLEMENTED_TASKS)
1502
+ out: List[str] = []
1503
+ for tok in raw.split(","):
1504
+ t = tok.strip().lower()
1505
+ if not t:
1506
+ continue
1507
+ if t == "all":
1508
+ return list(IMPLEMENTED_TASKS)
1509
+ if t not in ALL_TASKS:
1510
+ raise SystemExit(f"unknown task '{t}' (choose from: {','.join(ALL_TASKS)})")
1511
+ out.append(t)
1512
+ if not out:
1513
+ raise SystemExit("no tasks selected")
1514
+ return out
1515
+
1516
+
1517
+ def _parse_args(argv: Optional[List[str]] = None) -> argparse.Namespace:
1518
+ p = argparse.ArgumentParser(
1519
+ prog="run_lmudata.py",
1520
+ description=(
1521
+ "Prepare an LMUData layout for VLMEvalKit from "
1522
+ "nvidia/PhysicalAI-VANTAGE-Bench (no-GT inference layout)."
1523
+ ),
1524
+ )
1525
+ p.add_argument("--tasks", type=str, default=None,
1526
+ help=f"comma-separated tasks (choices: {','.join(ALL_TASKS)}). Default = all implemented.")
1527
+ p.add_argument("--all", action="store_true",
1528
+ help="alias for --tasks=all (implemented tasks only)")
1529
+ p.add_argument("--lmu-root", type=str, default=None,
1530
+ help=f"LMUData output root (default: {DEFAULT_LMU_ROOT})")
1531
+ p.add_argument("--local-source", type=str, default=None,
1532
+ help="Path to a local PhysicalAI-VANTAGE-Bench checkout. Use its data/ "
1533
+ "folder directly instead of downloading from HF. Takes precedence "
1534
+ "over --hf-repo. (Auto-enabled when this script lives inside such a repo.)")
1535
+ p.add_argument("--hf-repo", type=str, default=HF_REPO_ID,
1536
+ help=(f"HF dataset repo id (default: {HF_REPO_ID}). "
1537
+ "Override is for testing/simulation only — production runs MUST use the default. "
1538
+ "Ignored when a local source is active."))
1539
+ p.add_argument("--hf-cache", type=str, default=None,
1540
+ help="Override HF hub cache_dir")
1541
+ p.add_argument("--hf-token", type=str, default=None,
1542
+ help=("HF token (or set HF_TOKEN env). Required for the SOT task, "
1543
+ "which downloads source camera videos from the gated "
1544
+ "nvidia/PhysicalAI-SmartSpaces dataset."))
1545
+ media = p.add_mutually_exclusive_group()
1546
+ media.add_argument("--symlink", dest="symlink", action="store_true",
1547
+ help="symlink media into the HF cache (default) — saves disk, "
1548
+ "but LMUData depends on the HF cache staying in place")
1549
+ media.add_argument("--copy", dest="symlink", action="store_false",
1550
+ help="copy media files into LMUData instead of symlinking "
1551
+ "(self-contained / portable; duplicates tens of GB of media)")
1552
+ p.set_defaults(symlink=True)
1553
+ p.add_argument("--force", action="store_true",
1554
+ help="rebuild index files even if integrity check passes")
1555
+ p.add_argument("--force-clean", action="store_true",
1556
+ help="wipe existing media dirs before relinking (destructive)")
1557
+ p.add_argument("--dry-run", action="store_true",
1558
+ help="print plan, do not write files or call HF")
1559
+ p.add_argument("--skip-grounding-images", action="store_true",
1560
+ help="skip VisDrone image download for grounding (use pre-staged images/)")
1561
+ p.add_argument("--write-manifest", action="store_true",
1562
+ help="write a .vantage_prep_manifest.json telemetry file at the LMU root "
1563
+ "(off by default; participant LMUData stays clean)")
1564
+ p.add_argument("--verbose", "-v", action="store_true")
1565
+ return p.parse_args(argv)
1566
+
1567
+
1568
+ def main(argv: Optional[List[str]] = None) -> int:
1569
+ args = _parse_args(argv)
1570
+ _setup_logging(args.verbose)
1571
+
1572
+ local_source = None
1573
+ if args.local_source:
1574
+ local_source = Path(args.local_source).expanduser().resolve()
1575
+
1576
+ opts = Options(
1577
+ lmu_root=_resolve_lmu_root(args.lmu_root),
1578
+ hf_cache=Path(args.hf_cache).expanduser().resolve() if args.hf_cache else None,
1579
+ hf_token=_resolve_hf_token(args.hf_token),
1580
+ symlink=args.symlink,
1581
+ force=args.force,
1582
+ force_clean=args.force_clean,
1583
+ dry_run=args.dry_run,
1584
+ verbose=args.verbose,
1585
+ hf_repo=args.hf_repo,
1586
+ skip_grounding_images=args.skip_grounding_images,
1587
+ write_manifest=args.write_manifest,
1588
+ local_source=local_source,
1589
+ )
1590
+
1591
+ # Determine the effective source for logging/summary (per-task validation
1592
+ # still happens in _resolve_source).
1593
+ auto_root = None if opts.local_source else _autodetect_local_root()
1594
+ if opts.local_source:
1595
+ source_label = f"local-explicit:{opts.local_source}"
1596
+ local_active = True
1597
+ elif auto_root is not None:
1598
+ source_label = f"local-auto:{auto_root}"
1599
+ local_active = True
1600
+ else:
1601
+ source_label = f"hf:{opts.hf_repo}"
1602
+ local_active = False
1603
+
1604
+ if local_active and opts.hf_repo != HF_REPO_ID:
1605
+ log.warning("--hf-repo %s is IGNORED because a local source is active (%s).",
1606
+ opts.hf_repo, source_label)
1607
+ elif opts.hf_repo != HF_REPO_ID:
1608
+ log.warning("--hf-repo override active: %s (production default: %s)",
1609
+ opts.hf_repo, HF_REPO_ID)
1610
+
1611
+ tasks = _parse_tasks(args.tasks, args.all)
1612
+
1613
+ log.info("VANTAGE prep — source=%s lmu_root=%s tasks=%s dry_run=%s media=%s force=%s",
1614
+ source_label, opts.lmu_root, ",".join(tasks), opts.dry_run,
1615
+ "symlink" if opts.symlink else "copy", opts.force)
1616
+ if not opts.dry_run:
1617
+ opts.lmu_root.mkdir(parents=True, exist_ok=True)
1618
+ (opts.lmu_root / "datasets").mkdir(parents=True, exist_ok=True)
1619
+
1620
+ results: List[TaskResult] = []
1621
+ for task in tasks:
1622
+ try:
1623
+ res = _run_task(task, opts)
1624
+ except SystemExit as e:
1625
+ # Per-task SystemExits (missing source dir, missing HF token, etc.)
1626
+ # become per-task failures so other tasks can still proceed.
1627
+ msg = str(e) if str(e) else f"SystemExit code {e.code!r}"
1628
+ log.error("[%s] %s", task, msg)
1629
+ res = TaskResult(
1630
+ task=task,
1631
+ lmu_name=TASK_CONFIG.get(task, {}).get("lmu_name", task),
1632
+ target_dir=_target_dir(opts.lmu_root, task) if task in TASK_CONFIG else opts.lmu_root,
1633
+ status="failed",
1634
+ notes=[msg[:500]],
1635
+ )
1636
+ except Exception as e:
1637
+ log.exception("[%s] failed: %s", task, e)
1638
+ res = TaskResult(
1639
+ task=task,
1640
+ lmu_name=TASK_CONFIG.get(task, {}).get("lmu_name", task),
1641
+ target_dir=_target_dir(opts.lmu_root, task) if task in TASK_CONFIG else opts.lmu_root,
1642
+ status="failed",
1643
+ notes=[f"exception: {e!r}"],
1644
+ )
1645
+ results.append(res)
1646
+
1647
+ if opts.write_manifest:
1648
+ _write_manifest(opts.lmu_root, results, opts)
1649
+
1650
+ # Summary
1651
+ print()
1652
+ print("=" * 78)
1653
+ print("VANTAGE prep summary"
1654
+ + (" [TEST OVERRIDE]" if (not local_active and opts.hf_repo != HF_REPO_ID) else ""))
1655
+ print(f"Source: {source_label}")
1656
+ print(f"LMU root: {opts.lmu_root}")
1657
+ print(f"Mode: {'DRY-RUN' if opts.dry_run else 'WRITE'} "
1658
+ f"media={'symlink' if opts.symlink else 'copy'} "
1659
+ f"force={opts.force} force_clean={opts.force_clean}")
1660
+ print("-" * 78)
1661
+ print(f"{'task':<28}{'status':<12}{'rows':>8}{'media':>10}")
1662
+ print("-" * 78)
1663
+ for r in results:
1664
+ print(f"{r.lmu_name:<28}{r.status:<12}{r.rows:>8}{r.media_count:>10}")
1665
+ for note in r.notes:
1666
+ print(f" - {note}")
1667
+ print("=" * 78)
1668
+ if opts.write_manifest:
1669
+ print(f"Manifest: {opts.lmu_root / MANIFEST_FILENAME}")
1670
+ return 0 if all(r.status in ("built", "rebuilt", "skipped", "deferred", "dry-run") for r in results) else 1
1671
+
1672
+
1673
+ if __name__ == "__main__":
1674
+ sys.exit(main())