sihyun-yu commited on
Commit
dd56ce1
·
0 Parent(s):

VSTAT dataset release

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +2 -0
  2. LICENSE +13 -0
  3. README.md +209 -0
  4. redactions.json +37 -0
  5. scripts/build_resolution_map.py +92 -0
  6. scripts/download_youtube.py +485 -0
  7. scripts/redact.sh +134 -0
  8. videos/self_recorded/book/0001_pt1.mp4 +3 -0
  9. videos/self_recorded/book/0002_pt1.mp4 +3 -0
  10. videos/self_recorded/book/0003_pt1.mp4 +3 -0
  11. videos/self_recorded/book/0004_pt1.mp4 +3 -0
  12. videos/self_recorded/book/0005_pt1.mp4 +3 -0
  13. videos/self_recorded/book/0006_pt1.mp4 +3 -0
  14. videos/self_recorded/book/0007_pt1.mp4 +3 -0
  15. videos/self_recorded/book/0008_pt1.mp4 +3 -0
  16. videos/self_recorded/book/0009_pt1.mp4 +3 -0
  17. videos/self_recorded/book/0010_pt1.mp4 +3 -0
  18. videos/self_recorded/cup_stacking/0001_pt1.mp4 +3 -0
  19. videos/self_recorded/cup_stacking/0002_pt1.mp4 +3 -0
  20. videos/self_recorded/cup_stacking/0003_pt1.mp4 +3 -0
  21. videos/self_recorded/cup_stacking/0004_pt1.mp4 +3 -0
  22. videos/self_recorded/cup_stacking/0005_pt1.mp4 +3 -0
  23. videos/self_recorded/cup_stacking/0006_pt1.mp4 +3 -0
  24. videos/self_recorded/cup_stacking/0007_pt1.mp4 +3 -0
  25. videos/self_recorded/cup_stacking/0008_pt1.mp4 +3 -0
  26. videos/self_recorded/cup_stacking/0009_pt1.mp4 +3 -0
  27. videos/self_recorded/cup_stacking/0010_pt1.mp4 +3 -0
  28. videos/self_recorded/keyboard/0001_pt1.mp4 +3 -0
  29. videos/self_recorded/keyboard/0002_pt1.mp4 +3 -0
  30. videos/self_recorded/keyboard/0003_pt1.mp4 +3 -0
  31. videos/self_recorded/keyboard/0004_pt1.mp4 +3 -0
  32. videos/self_recorded/keyboard/0005_pt1.mp4 +3 -0
  33. videos/self_recorded/keyboard/0006_pt1.mp4 +3 -0
  34. videos/self_recorded/keyboard/0007_pt1.mp4 +3 -0
  35. videos/self_recorded/keyboard/0008_pt1.mp4 +3 -0
  36. videos/self_recorded/keyboard/0009_pt1.mp4 +3 -0
  37. videos/self_recorded/keyboard/0010_pt1.mp4 +3 -0
  38. videos/self_recorded/morse/0001_pt1.mp4 +3 -0
  39. videos/self_recorded/morse/0002_pt1.mp4 +3 -0
  40. videos/self_recorded/morse/0003_pt1.mp4 +3 -0
  41. videos/self_recorded/morse/0004_pt1.mp4 +3 -0
  42. videos/self_recorded/morse/0005_pt1.mp4 +3 -0
  43. videos/self_recorded/morse/0006_pt1.mp4 +3 -0
  44. videos/self_recorded/morse/0007_pt1.mp4 +3 -0
  45. videos/self_recorded/morse/0008_pt1.mp4 +3 -0
  46. videos/self_recorded/morse/0009_pt1.mp4 +3 -0
  47. videos/self_recorded/morse/0010_pt1.mp4 +3 -0
  48. videos/self_recorded/numberpad/0001_pt1.mp4 +3 -0
  49. videos/self_recorded/numberpad/0002_pt1.mp4 +3 -0
  50. videos/self_recorded/numberpad/0003_pt1.mp4 +3 -0
.gitattributes ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ *.mp4 filter=lfs diff=lfs merge=lfs -text
2
+ *.mov filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Creative Commons Attribution 4.0 International (CC BY 4.0)
2
+
3
+ Copyright (c) 2026 The VSTAT Authors
4
+
5
+ Annotations and self-recorded videos in this dataset are licensed under
6
+ CC BY 4.0: https://creativecommons.org/licenses/by/4.0/
7
+
8
+ Synthetic Blender-rendered videos are licensed under CC BY 4.0.
9
+
10
+ YouTube videos referenced via URL/timestamp are NOT redistributed and
11
+ remain under the original uploaders' licenses (typically Standard YouTube
12
+ License). Users must download YouTube clips themselves and comply with
13
+ YouTube's Terms of Service.
README.md ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc-by-4.0
3
+ language:
4
+ - en
5
+ tags:
6
+ - video
7
+ - multimodal
8
+ - benchmark
9
+ - video-question-answering
10
+ - visual-state-tracking
11
+ size_categories:
12
+ - 1K<n<10K
13
+ ---
14
+
15
+ # VSTAT: Visual State Tracking Benchmark
16
+
17
+ VSTAT is a video-based benchmark for evaluating the **visual state tracking**
18
+ capability of Multimodal Large Language Models (MLLMs). It contains 834 video
19
+ clips paired with 1,500 questions whose answers cannot be inferred from any
20
+ single keyframe or short segment.
21
+
22
+ ## Dataset Composition
23
+
24
+ | Split | Videos | Questions |
25
+ |----------------|-------:|----------:|
26
+ | synthetic | 450 | 550 |
27
+ | self_recorded | 80 | 100 |
28
+ | youtube | 304 | 850 |
29
+ | **Total** | **834** | **1,500** |
30
+
31
+ ## Files
32
+
33
+ - `vstat_qa_clean.json` — all 1,500 question-answer pairs with taxonomy labels
34
+ - `youtube_metadata.json` — YouTube URLs + start/end timestamps (one entry per chunk)
35
+ - `youtube_resolutions.json` — per-clip target (W, H, fps) used by the
36
+ downloader to reproduce the official release pixel layout
37
+ - `redactions.json` — declarative privacy-redaction regions applied after trim
38
+ - `scripts/download_youtube.py` — fetches & trims the 304 YouTube clips
39
+ - `scripts/redact.sh` — applies the privacy black-boxes from `redactions.json`
40
+ - `scripts/build_resolution_map.py` — utility to (re)build `youtube_resolutions.json`
41
+ from a reference render
42
+ - `videos/synthetic/<category>/<id>.mp4` — Blender-rendered videos (hosted)
43
+ - `videos/self_recorded/<category>/<id>.mp4` — author-recorded clips, hands only,
44
+ audio removed (hosted)
45
+ - `videos/youtube/<category>/<id>.mp4` — **NOT redistributed**; you must
46
+ download these yourself with the provided script (see *Quick start* below)
47
+
48
+ ## Quick start
49
+
50
+ ### 1. Get the repo
51
+
52
+ Pick whichever method you prefer:
53
+
54
+ ```bash
55
+ # A. huggingface-cli (recommended, supports LFS)
56
+ pip install -U "huggingface_hub[cli]"
57
+ huggingface-cli download nyu-visionx/vstat \
58
+ --repo-type=dataset \
59
+ --local-dir vstat
60
+ cd vstat
61
+
62
+ # B. git clone (requires git-lfs installed)
63
+ git lfs install
64
+ git clone https://huggingface.co/datasets/nyu-visionx/vstat vstat
65
+ cd vstat
66
+ ```
67
+
68
+ After this, you have all annotations and the synthetic + self_recorded
69
+ videos. The YouTube clips are still missing — fetch them next.
70
+
71
+ ### 2. Download and redact the YouTube clips
72
+
73
+ The downloader reads `youtube_metadata.json` and downloads each source
74
+ video once with `yt-dlp`, then trims it into the chunks expected by
75
+ `vstat_qa_clean.json`. Pass `--resolution-map youtube_resolutions.json`
76
+ so each chunk lands at the exact `(width, height, fps)` of the official
77
+ release. After trimming, `scripts/redact.sh` applies the privacy
78
+ black-boxes (matches `redactions.json`) to the affected clips in place.
79
+
80
+ > **Important — reproducing the official release.** The benchmark
81
+ > numbers in our paper were obtained on the clips produced by exactly
82
+ > this two-step pipeline (`download_youtube.py --resolution-map …` →
83
+ > `redact.sh`). The downloader picks the smallest YouTube format that
84
+ > matches each clip's target dimensions and frame rate so the trim
85
+ > avoids any resampling drift. Skip the resolution map only for
86
+ > ablations on input resolution.
87
+
88
+ ```bash
89
+ # Install dependencies
90
+ pip install -U yt-dlp
91
+ # macOS: brew install ffmpeg
92
+ # Ubuntu: sudo apt install ffmpeg
93
+
94
+ # 1. Fetch and trim every YouTube clip to its release-spec dims
95
+ python scripts/download_youtube.py --resolution-map youtube_resolutions.json
96
+
97
+ # 2. Apply privacy redactions in place (idempotent)
98
+ bash scripts/redact.sh
99
+ ```
100
+
101
+ Common flags for the downloader:
102
+
103
+ ```bash
104
+ # Faster: 4 parallel downloads
105
+ python scripts/download_youtube.py --resolution-map youtube_resolutions.json --workers 4
106
+
107
+ # Test on a few videos first
108
+ python scripts/download_youtube.py --resolution-map youtube_resolutions.json --limit 5
109
+
110
+ # Keep the full source videos around (faster re-trim, more disk)
111
+ python scripts/download_youtube.py --resolution-map youtube_resolutions.json --keep-fulls
112
+
113
+ # Print plan without doing anything
114
+ python scripts/download_youtube.py --resolution-map youtube_resolutions.json --dry-run
115
+
116
+ # Cap source download size (default uncapped — required for portrait sources)
117
+ python scripts/download_youtube.py --resolution-map youtube_resolutions.json --source-cap 1080
118
+ ```
119
+
120
+ Re-running the downloader is safe: it skips clips that already exist
121
+ on disk and writes a `download_report.json` listing any failures (rare,
122
+ usually due to YouTube link rot — affected clips can be reported to
123
+ the authors via the dataset issue tracker). Re-running `redact.sh` is
124
+ also idempotent and replaces any earlier redaction with the canonical
125
+ set defined in `redactions.json`.
126
+
127
+ ### 3. Load the data
128
+
129
+ ```python
130
+ import json
131
+
132
+ with open("vstat_qa_clean.json") as f:
133
+ data = json.load(f)
134
+
135
+ for cat, entries in data["data"].items():
136
+ for e in entries:
137
+ print(e["video_id"], e["video_path"], e["video_source"])
138
+ ```
139
+
140
+ Each entry has these fields:
141
+
142
+ | Field | Description |
143
+ |----------------------------|-------------------------------------------------------------|
144
+ | `video_id` | Unique identifier (e.g. `0001_pt1_q1`) |
145
+ | `video_path` | Relative path under `videos/` |
146
+ | `video_source` | `synthetic` / `self_recorded` / `youtube` |
147
+ | `source_task` | Coarse category (e.g. `basketball`, `dice`, `shell_game`) |
148
+ | `question` | Question text. For MCQ items, choices are inline `(A)(B)…` |
149
+ | `answer_type` | `mcq` or `numeric` |
150
+ | `answer` | Letter (`A`/`B`/`C`/`D`) for MCQ; integer for numeric |
151
+ | `choices` | List of MCQ option strings (empty for numeric) |
152
+ | `answer_index` | 0-based index into `choices` (null for numeric) |
153
+ | `perceptual_complexity` | List of perceptual challenge tags (see Taxonomy) |
154
+ | `state_element_type` | `count` / `location` / `attribute` |
155
+ | `state_structure` | `atomic` / `sequence` / `set` / `dictionary` |
156
+ | `youtube_url`, `youtube_id`, `start_time`, `end_time`, `start_sec`, `end_sec` | Present only for `video_source == "youtube"` |
157
+
158
+ ### 4. Run an evaluation
159
+
160
+ A minimal MCQ scoring loop (numeric questions are scored with mean
161
+ relative accuracy in our paper; see Section 3.1 for details):
162
+
163
+ ```python
164
+ def score(entry, model_pred):
165
+ if entry["answer_type"] == "mcq":
166
+ return int(model_pred.strip().upper() == entry["answer"])
167
+ # numeric
168
+ try:
169
+ return int(int(model_pred) == int(entry["answer"]))
170
+ except ValueError:
171
+ return 0
172
+ ```
173
+
174
+ ## Taxonomy
175
+
176
+ Each question is annotated with:
177
+
178
+ - `perceptual_complexity` (multi-label, paper Section 2.2):
179
+ `action_ambiguity`, `camera_motion`, `homogeneity`,
180
+ `multi_entity_attribution`, `occlusion`, `symbolic_decoding`
181
+ - `state_element_type` (single label): `count`, `location`, `attribute`
182
+ - `state_structure` (single label): `atomic`, `sequence`, `set`, `dictionary`
183
+
184
+ ## License
185
+
186
+ - Annotations and self-recorded / synthetic videos: **CC BY 4.0**
187
+ - YouTube videos: NOT redistributed; subject to original uploader's license
188
+ - See `LICENSE` for full terms
189
+
190
+ ## Privacy & consent
191
+
192
+ - Self-recorded videos contain only the authors' hands; no faces, voices,
193
+ or other identifiable persons. Audio tracks were stripped before release.
194
+ - Authors consented to public release of their hand footage.
195
+ - For YouTube clips, only URLs and timestamps are redistributed; original
196
+ uploaders retain control over their content. The `redact.sh` step
197
+ applies black-boxes over scoreboards / on-screen text in a small
198
+ number of clips per `redactions.json`, matching the official release.
199
+
200
+ ## Citation
201
+
202
+ ```bibtex
203
+ @article{vstat2026,
204
+ title={Benchmarking Visual State Tracking in Multimodal Video Understanding},
205
+ author={Sihyun Yu and Nanye Ma and Pinzhi Huang and Hyunseok Lee and Shusheng Yang and June Suk Choi and Ellis Brown and Oscar Michel and Boyang Zheng and Jinwoo Shin and Saining Xie},
206
+ year={2026},
207
+ journal={arXiv preprint arXiv:2606.03920},
208
+ }
209
+ ```
redactions.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "description": "Per-source-video privacy redactions applied to YouTube clips. Coordinates are in the OUTPUT resolution (640x360, the official VSTAT release spec). Each redaction draws a solid black box (drawbox filter, t=fill) over the listed region in every chunk of the matching source video.",
3
+ "coordinate_space": "640x360 (post-scale)",
4
+ "redactions": [
5
+ {
6
+ "match": {"category": "tennis", "local_id": "0001"},
7
+ "boxes": [
8
+ {"x": 32, "y": 306, "w": 134, "h": 38}
9
+ ]
10
+ },
11
+ {
12
+ "match": {"category": "tennis", "local_id": "0002"},
13
+ "boxes": [
14
+ {"x": 32, "y": 306, "w": 134, "h": 38}
15
+ ]
16
+ },
17
+ {
18
+ "match": {"category": "basketball", "local_id": "0002"},
19
+ "boxes": [
20
+ {"x": 98, "y": 323, "w": 443, "h": 37}
21
+ ]
22
+ },
23
+ {
24
+ "match": {"category": "basketball", "local_id": "0003"},
25
+ "boxes": [
26
+ {"x": 22, "y": 285, "w": 125, "h": 63}
27
+ ]
28
+ },
29
+ {
30
+ "match": {"category": "soccer", "local_id": "0002"},
31
+ "boxes": [
32
+ {"x": 0, "y": 0, "w": 122, "h": 19},
33
+ {"x": 140, "y": 320, "w": 360, "h": 40}
34
+ ]
35
+ }
36
+ ]
37
+ }
scripts/build_resolution_map.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Build a per-clip resolution map from an existing render of `videos/youtube/`.
3
+
4
+ Walks a reference directory laid out like `<ref>/<category>/<file>.mp4`,
5
+ runs ffprobe on each clip, and writes a JSON map keyed by
6
+ `videos/youtube/<category>/<file>.mp4` (matching `video_path` in
7
+ `youtube_metadata.json`). The map is consumed by `download_youtube.py
8
+ --resolution-map` to reproduce the exact width/height/fps of each clip.
9
+
10
+ Usage:
11
+ python scripts/build_resolution_map.py ~/Desktop/ytb/processed
12
+ python scripts/build_resolution_map.py REF_DIR -o youtube_resolutions.json
13
+ """
14
+ from __future__ import annotations
15
+ import argparse
16
+ import json
17
+ import subprocess
18
+ import sys
19
+ from concurrent.futures import ThreadPoolExecutor
20
+ from pathlib import Path
21
+
22
+
23
+ def probe(path: Path) -> dict | None:
24
+ try:
25
+ out = subprocess.run(
26
+ ["ffprobe", "-v", "error", "-select_streams", "v:0",
27
+ "-show_entries", "stream=width,height,r_frame_rate",
28
+ "-show_entries", "format=duration",
29
+ "-of", "json", str(path)],
30
+ capture_output=True, text=True, check=True, timeout=30,
31
+ ).stdout
32
+ except (subprocess.CalledProcessError, subprocess.TimeoutExpired):
33
+ return None
34
+ try:
35
+ info = json.loads(out)
36
+ except json.JSONDecodeError:
37
+ return None
38
+ s = (info.get("streams") or [{}])[0]
39
+ f = info.get("format", {})
40
+ fr = s.get("r_frame_rate", "0/1")
41
+ try:
42
+ n, d = (int(x) for x in fr.split("/"))
43
+ fps = round(n / d, 4) if d else None
44
+ except ValueError:
45
+ fps = None
46
+ if not (s.get("width") and s.get("height")):
47
+ return None
48
+ return {
49
+ "width": int(s["width"]),
50
+ "height": int(s["height"]),
51
+ "fps": fps,
52
+ "duration": round(float(f["duration"]), 4) if f.get("duration") else None,
53
+ }
54
+
55
+
56
+ def main() -> int:
57
+ ap = argparse.ArgumentParser(description=__doc__,
58
+ formatter_class=argparse.RawDescriptionHelpFormatter)
59
+ ap.add_argument("ref_dir", help="reference directory (e.g. ~/Desktop/ytb/processed)")
60
+ ap.add_argument("-o", "--out", default="youtube_resolutions.json",
61
+ help="output JSON path (default: youtube_resolutions.json)")
62
+ ap.add_argument("--workers", type=int, default=8)
63
+ args = ap.parse_args()
64
+
65
+ ref = Path(args.ref_dir).expanduser()
66
+ if not ref.is_dir():
67
+ sys.exit(f"ERROR: {ref} is not a directory")
68
+
69
+ paths = sorted(ref.glob("*/*.mp4"))
70
+ print(f"probing {len(paths)} files under {ref}…", file=sys.stderr)
71
+
72
+ out: dict[str, dict] = {}
73
+ bad: list[str] = []
74
+ with ThreadPoolExecutor(max_workers=max(1, args.workers)) as ex:
75
+ for p, info in zip(paths, ex.map(probe, paths)):
76
+ key = f"videos/youtube/{p.parent.name}/{p.name}"
77
+ if info is None:
78
+ bad.append(key)
79
+ continue
80
+ out[key] = info
81
+
82
+ out_path = Path(args.out)
83
+ out_path.write_text(json.dumps(out, indent=2, sort_keys=True))
84
+ print(f"wrote {out_path} ({len(out)} entries; {len(bad)} probe failures)",
85
+ file=sys.stderr)
86
+ if bad:
87
+ print(" failures:", *bad[:10], "…" if len(bad) > 10 else "", file=sys.stderr)
88
+ return 0
89
+
90
+
91
+ if __name__ == "__main__":
92
+ raise SystemExit(main())
scripts/download_youtube.py ADDED
@@ -0,0 +1,485 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ VSTAT — YouTube clip downloader
4
+
5
+ Reads `youtube_metadata.json` and, for each entry, downloads the source
6
+ YouTube video (with yt-dlp) and extracts the specified time range
7
+ (with ffmpeg) into the `videos/youtube/<category>/<id>.mp4` path
8
+ expected by `vstat_qa_clean.json`.
9
+
10
+ Resolution handling:
11
+ --height H scale every clip to height H, width preserves aspect
12
+ (default 360 → 640x360 for 16:9; ≈202x360 for 9:16).
13
+ --resolution-map FILE preferred per-clip exact-match mode. Reads a JSON
14
+ map (built by `scripts/build_resolution_map.py`)
15
+ keyed by `videos/youtube/<cat>/<file>.mp4` with
16
+ {"width", "height", "fps"} per entry, and scales
17
+ each trim to exactly W×H@fps.
18
+ --reference-dir DIR live alternative to --resolution-map: for each
19
+ clip we probe DIR/<cat>/<file>.mp4 directly. Use
20
+ --resolution-map when possible (no per-run probe).
21
+ --source-cap N in reference mode, cap yt-dlp source download to
22
+ height ≤ N. Default is uncapped so portrait
23
+ sources (whose pixel height is the long side) are
24
+ still selectable; ffmpeg always downscales the
25
+ source to the exact per-clip target.
26
+
27
+ Usage:
28
+ python download_youtube.py
29
+ python download_youtube.py --metadata youtube_metadata.json --out videos/youtube
30
+ python download_youtube.py --workers 4
31
+ python download_youtube.py --keep-fulls # keep full source videos in cache/
32
+ python download_youtube.py --dry-run
33
+
34
+ # Reproduce per-video resolutions from a saved map (preferred):
35
+ python scripts/build_resolution_map.py ~/Desktop/ytb/processed \
36
+ -o youtube_resolutions.json
37
+ python download_youtube.py --resolution-map youtube_resolutions.json
38
+
39
+ # Or probe a reference tree live:
40
+ python download_youtube.py --reference-dir ~/Desktop/ytb/processed
41
+
42
+ Requirements:
43
+ yt-dlp (pip install -U yt-dlp)
44
+ ffmpeg (system: brew install ffmpeg / apt install ffmpeg)
45
+ """
46
+ from __future__ import annotations
47
+ import argparse
48
+ import concurrent.futures
49
+ import json
50
+ import os
51
+ import shutil
52
+ import subprocess
53
+ import sys
54
+ import time
55
+ from collections import defaultdict
56
+ from pathlib import Path
57
+
58
+ # ---------- helpers ----------
59
+
60
+ def have(cmd: str) -> bool:
61
+ return shutil.which(cmd) is not None
62
+
63
+ def hms_to_sec(s) -> float | None:
64
+ if s is None:
65
+ return None
66
+ s = str(s).strip()
67
+ if not s or s.lower() in ("none", "null", "n/a"):
68
+ return None
69
+ parts = s.split(":")
70
+ try:
71
+ parts = [float(p) for p in parts]
72
+ except ValueError:
73
+ return None
74
+ if len(parts) == 3: return parts[0]*3600 + parts[1]*60 + parts[2]
75
+ if len(parts) == 2: return parts[0]*60 + parts[1]
76
+ if len(parts) == 1: return parts[0]
77
+ return None
78
+
79
+ def log(msg: str, prefix: str = ""):
80
+ print(f"{prefix}{msg}", flush=True)
81
+
82
+ def probe_resolution(path: Path) -> tuple[int, int, float] | None:
83
+ """Return (width, height, fps) of `path`'s first video stream, or None."""
84
+ if not path.exists():
85
+ return None
86
+ try:
87
+ out = subprocess.run(
88
+ ["ffprobe", "-v", "error", "-select_streams", "v:0",
89
+ "-show_entries", "stream=width,height,r_frame_rate",
90
+ "-of", "default=nw=1:nk=1", str(path)],
91
+ capture_output=True, text=True, check=True,
92
+ ).stdout.strip().splitlines()
93
+ except (subprocess.CalledProcessError, FileNotFoundError):
94
+ return None
95
+ if len(out) < 3:
96
+ return None
97
+ try:
98
+ w, h = int(out[0]), int(out[1])
99
+ n, d = out[2].split("/")
100
+ fps = float(n) / float(d) if float(d) else 0.0
101
+ except (ValueError, ZeroDivisionError):
102
+ return None
103
+ return w, h, fps
104
+
105
+ # ---------- core operations ----------
106
+
107
+ def download_full(youtube_url: str, dst: Path, max_height: int | None = 360,
108
+ max_fps: int | None = None,
109
+ retries: int = 3) -> tuple[bool, str]:
110
+ """Download the full source video to dst (mp4).
111
+
112
+ If max_height is given, picks the best stream with pixel height <=
113
+ max_height. If max_height is None, picks bestvideo+bestaudio with no
114
+ cap — required when the target is a portrait clip whose source is
115
+ served by YouTube at a height (long side) larger than the clip target.
116
+
117
+ If max_fps is given, also constrains source fps <= max_fps. Important
118
+ when the target clip is e.g. 30fps but YouTube has a 60fps version of
119
+ the source: ffmpeg's fps-drop chooses different keyframes than the
120
+ reference pipeline, causing visible per-frame drift. Matching source
121
+ fps eliminates that drift.
122
+
123
+ Idempotent — skips if dst already exists."""
124
+ if dst.exists() and dst.stat().st_size > 0:
125
+ return True, "cached"
126
+ dst.parent.mkdir(parents=True, exist_ok=True)
127
+ h = f"[height<={max_height}]" if max_height is not None else ""
128
+ f = f"[fps<={max_fps}]" if max_fps is not None else ""
129
+ if not h and not f:
130
+ fmt = (
131
+ "bestvideo[ext=mp4]+bestaudio[ext=m4a]/"
132
+ "best[ext=mp4]/"
133
+ "bestvideo+bestaudio/best"
134
+ )
135
+ else:
136
+ fmt = (
137
+ f"bestvideo[ext=mp4]{h}{f}+bestaudio[ext=m4a]/"
138
+ f"best[ext=mp4]{h}{f}/"
139
+ f"bestvideo{h}{f}+bestaudio/"
140
+ f"best{h}{f}/best{h}/best"
141
+ )
142
+ cmd = [
143
+ "yt-dlp",
144
+ "-f", fmt,
145
+ "--merge-output-format", "mp4",
146
+ "--no-playlist",
147
+ "-q",
148
+ "--no-warnings",
149
+ "-o", str(dst),
150
+ youtube_url,
151
+ ]
152
+ last_err = ""
153
+ for attempt in range(1, retries + 1):
154
+ res = subprocess.run(cmd, capture_output=True, text=True)
155
+ if res.returncode == 0 and dst.exists() and dst.stat().st_size > 0:
156
+ return True, f"downloaded (attempt {attempt})"
157
+ last_err = (res.stderr or res.stdout or "")[:200]
158
+ time.sleep(2 * attempt)
159
+ return False, f"yt-dlp failed: {last_err}"
160
+
161
+ def trim_clip(src: Path, dst: Path, start_sec: float, end_sec: float | None,
162
+ target_height: int = 360,
163
+ target_width: int | None = None,
164
+ target_fps: float | None = None,
165
+ source_dims: tuple[int, int] | None = None) -> tuple[bool, str]:
166
+ """Cut [start, end) from src to dst, re-encoded to H.264.
167
+
168
+ If source_dims == (target_width, target_height), no scale/crop filter
169
+ is applied — letting ffmpeg do a straight decode→encode preserves frame
170
+ alignment with reference pipelines that also avoided rescaling.
171
+ Otherwise we centre-crop to the target's aspect ratio and scale to W×H."""
172
+ dst.parent.mkdir(parents=True, exist_ok=True)
173
+ if dst.exists() and dst.stat().st_size > 0:
174
+ return True, "cached"
175
+ skip_scale = (
176
+ target_width is not None
177
+ and source_dims is not None
178
+ and source_dims == (target_width, target_height)
179
+ )
180
+ vf_parts: list[str] = []
181
+ if target_width and not skip_scale:
182
+ # Center-crop source to the target's aspect ratio first, then scale.
183
+ # When source aspect already matches target aspect the crop is a
184
+ # no-op (the crop expression yields the full source dims). When
185
+ # they differ — e.g. landscape source → square output — this
186
+ # matches ytb/processed which centre-crops before resizing.
187
+ W, H = target_width, target_height
188
+ vf_parts.append(f"crop=min(iw\\,ih*{W}/{H}):min(ih\\,iw*{H}/{W})")
189
+ vf_parts.append(f"scale={W}:{H}")
190
+ elif not target_width:
191
+ vf_parts.append(f"scale=-2:{target_height}")
192
+ if target_fps and target_fps > 0 and not skip_scale:
193
+ vf_parts.append(f"fps={target_fps}")
194
+ vf = ",".join(vf_parts)
195
+ # Match ytb/processed pipeline: -ss BEFORE -i (fast seek), default video
196
+ # encoder (libx264 preset=medium crf=23 profile=high, ffmpeg's defaults),
197
+ # no -movflags +faststart, audio dropped (-an) since the original scraper
198
+ # pulled video-only mp4 in most cases.
199
+ cmd = ["ffmpeg", "-y", "-loglevel", "error", "-nostdin",
200
+ "-ss", f"{start_sec:.3f}",
201
+ "-i", str(src)]
202
+ if end_sec is not None and end_sec > start_sec:
203
+ cmd += ["-t", f"{end_sec - start_sec:.3f}"]
204
+ if vf:
205
+ cmd += ["-vf", vf]
206
+ cmd += ["-an", str(dst)]
207
+ res = subprocess.run(cmd, capture_output=True, text=True)
208
+ ok = res.returncode == 0 and dst.exists() and dst.stat().st_size > 0
209
+ return ok, "trimmed" if ok else f"ffmpeg failed: {(res.stderr or '')[:200]}"
210
+
211
+ # ---------- pipeline ----------
212
+
213
+ def process_video_group(
214
+ yt_id: str,
215
+ yt_url: str,
216
+ chunks: list[dict],
217
+ out_root: Path,
218
+ cache_dir: Path,
219
+ keep_fulls: bool,
220
+ dry_run: bool,
221
+ target_height: int = 360,
222
+ reference_dir: Path | None = None,
223
+ resolution_map: dict[str, dict] | None = None,
224
+ source_cap: int | None = None,
225
+ ) -> dict:
226
+ """Download one YouTube video then trim all its chunks.
227
+
228
+ Per-clip target (W, H, fps) lookup precedence:
229
+ 1. resolution_map[<video_path>] (preferred — saved JSON)
230
+ 2. probe of reference_dir/<rel>.mp4 (live ffprobe fallback)
231
+ 3. (None, target_height, None) (default --height behaviour)
232
+
233
+ Source download (per yt_id):
234
+ - default mode (no map / no ref): cap at --height (legacy behaviour).
235
+ - reference mode: cap at source_cap if set, else uncapped (so portrait
236
+ sources whose pixel height is much larger than the clip target are
237
+ still selectable). ffmpeg downscales to the exact target W×H."""
238
+ full_path = cache_dir / f"{yt_id}.mp4"
239
+ result = {"youtube_id": yt_id, "url": yt_url,
240
+ "n_chunks": len(chunks), "ok": 0, "fail": 0, "errors": []}
241
+
242
+ ref_mode = resolution_map is not None or reference_dir is not None
243
+
244
+ # Resolve per-clip resolution targets.
245
+ per_clip: list[tuple[dict, int | None, int, float | None]] = []
246
+ for ch in chunks:
247
+ ref_w = ref_h = None
248
+ ref_fps = None
249
+ vp = ch["video_path"]
250
+ if resolution_map is not None and vp in resolution_map:
251
+ entry = resolution_map[vp]
252
+ ref_w = int(entry["width"])
253
+ ref_h = int(entry["height"])
254
+ ref_fps = float(entry["fps"]) if entry.get("fps") else None
255
+ elif reference_dir is not None:
256
+ rel = vp.replace("videos/youtube/", "")
257
+ probed = probe_resolution(reference_dir / rel)
258
+ if probed is not None:
259
+ ref_w, ref_h, ref_fps = probed
260
+ if ref_h is not None:
261
+ per_clip.append((ch, ref_w, ref_h, ref_fps))
262
+ else:
263
+ per_clip.append((ch, None, target_height, None))
264
+
265
+ # Source download cap.
266
+ if ref_mode:
267
+ if source_cap is not None:
268
+ dl_cap = source_cap
269
+ else:
270
+ # Pick the smallest YouTube tier that still fits all per-clip
271
+ # target heights for this yt_id. Picking a tier larger than
272
+ # needed forces ffmpeg to downscale and introduces sub-pixel
273
+ # drift in action scenes (basketball, soccer); matching the
274
+ # tier exactly lets us trim without rescaling.
275
+ target_heights = [h for _, _, h, _ in per_clip if h]
276
+ dl_cap = max(target_heights) if target_heights else target_height
277
+ else:
278
+ dl_cap = target_height
279
+ # FPS cap: ceil of max per-clip target fps, so yt-dlp picks a source
280
+ # whose native fps matches the trim — avoids drift from frame-dropping
281
+ # a 60fps source down to a 30fps target.
282
+ fps_cap: int | None = None
283
+ if ref_mode:
284
+ target_fpses = [fps for _, _, _, fps in per_clip if fps and fps > 0]
285
+ if target_fpses:
286
+ import math
287
+ fps_cap = math.ceil(max(target_fpses))
288
+
289
+ if dry_run:
290
+ cap_str = f"<= {dl_cap}p" if dl_cap is not None else "uncapped"
291
+ fps_str = f", <= {fps_cap}fps" if fps_cap is not None else ""
292
+ log(f"[DRY] would download {yt_url} (source {cap_str}{fps_str}) -> {full_path} "
293
+ f"({len(chunks)} chunks)")
294
+ for ch, w, h, fps in per_clip:
295
+ tgt = f"{w or '-2'}×{h}" + (f"@{fps:.3f}fps" if fps else "")
296
+ log(f" [DRY] {ch['video_path']} -> {tgt}")
297
+ return result
298
+
299
+ ok, msg = download_full(yt_url, full_path, max_height=dl_cap, max_fps=fps_cap)
300
+ if not ok:
301
+ result["fail"] = len(chunks)
302
+ result["errors"].append(f"download: {msg}")
303
+ log(f"[FAIL] {yt_id}: {msg}")
304
+ return result
305
+ cap_str = f"<= {dl_cap}p" if dl_cap is not None else "uncapped"
306
+ log(f"[OK ] downloaded {yt_id} ({msg}); trimming {len(chunks)} chunks "
307
+ f"(source {cap_str})")
308
+
309
+ src_probe = probe_resolution(full_path)
310
+ src_dims = (src_probe[0], src_probe[1]) if src_probe else None
311
+
312
+ for ch, ref_w, ref_h, ref_fps in per_clip:
313
+ rel = ch["video_path"] # videos/youtube/<cat>/<id>.mp4
314
+ dst = out_root / rel.replace("videos/youtube/", "")
315
+ start = ch.get("start_sec")
316
+ end = ch.get("end_sec")
317
+ if start is None:
318
+ start = hms_to_sec(ch.get("start_time")) or 0.0
319
+ if end is None:
320
+ end = hms_to_sec(ch.get("end_time"))
321
+ ok, msg = trim_clip(
322
+ full_path, dst, start, end,
323
+ target_height=ref_h,
324
+ target_width=ref_w,
325
+ target_fps=ref_fps,
326
+ source_dims=src_dims,
327
+ )
328
+ if ok:
329
+ result["ok"] += 1
330
+ else:
331
+ result["fail"] += 1
332
+ result["errors"].append(f"{rel}: {msg}")
333
+ log(f" [FAIL] {rel}: {msg}")
334
+
335
+ # Optionally drop the full video to save space.
336
+ if not keep_fulls:
337
+ try:
338
+ full_path.unlink()
339
+ except FileNotFoundError:
340
+ pass
341
+
342
+ return result
343
+
344
+ def main():
345
+ ap = argparse.ArgumentParser(description=__doc__,
346
+ formatter_class=argparse.RawDescriptionHelpFormatter)
347
+ ap.add_argument("--metadata", default="youtube_metadata.json",
348
+ help="path to youtube_metadata.json")
349
+ ap.add_argument("--out", default="videos/youtube",
350
+ help="output root for trimmed clips (videos/youtube)")
351
+ ap.add_argument("--cache", default=".cache/full_videos",
352
+ help="where to cache downloaded full videos")
353
+ ap.add_argument("--workers", type=int, default=2,
354
+ help="parallel YouTube downloads (1 video at a time per worker)")
355
+ ap.add_argument("--height", type=int, default=360,
356
+ help="target video height in pixels; both yt-dlp format "
357
+ "selection and ffmpeg re-encode use this. VSTAT's "
358
+ "original release used 360 (640x360). Default: 360")
359
+ ap.add_argument("--resolution-map", default=None,
360
+ help="path to a JSON resolution map "
361
+ "(see scripts/build_resolution_map.py). Each entry "
362
+ "is keyed by `videos/youtube/<cat>/<file>.mp4` with "
363
+ "{'width','height','fps'}. Clips found in the map "
364
+ "are scaled to that exact W×H@fps; others fall "
365
+ "back to --height.")
366
+ ap.add_argument("--reference-dir", default=None,
367
+ help="live alternative to --resolution-map: directory "
368
+ "laid out like videos/youtube/. Each run re-probes "
369
+ "with ffprobe. Prefer --resolution-map.")
370
+ ap.add_argument("--source-cap", type=int, default=None,
371
+ help="in reference mode, cap source-download height to N "
372
+ "(default uncapped — required for portrait sources).")
373
+ ap.add_argument("--keep-fulls", action="store_true",
374
+ help="keep full source videos in cache after trimming")
375
+ ap.add_argument("--limit", type=int, default=None,
376
+ help="only process the first N YouTube videos (debug)")
377
+ ap.add_argument("--filter-id", action="append", default=None,
378
+ help="only process given youtube_id (repeatable)")
379
+ ap.add_argument("--dry-run", action="store_true",
380
+ help="don't download or trim — just print what would happen")
381
+ args = ap.parse_args()
382
+
383
+ if not have("yt-dlp"):
384
+ sys.exit("ERROR: yt-dlp not installed. Run: pip install -U yt-dlp")
385
+ if not have("ffmpeg"):
386
+ sys.exit("ERROR: ffmpeg not installed. Run: brew install ffmpeg (or apt install ffmpeg)")
387
+ if args.reference_dir and not have("ffprobe"):
388
+ sys.exit("ERROR: --reference-dir requires ffprobe (ships with ffmpeg).")
389
+
390
+ reference_dir = Path(args.reference_dir).expanduser() if args.reference_dir else None
391
+ if reference_dir is not None and not reference_dir.is_dir():
392
+ sys.exit(f"ERROR: --reference-dir {reference_dir} is not a directory")
393
+
394
+ resolution_map: dict[str, dict] | None = None
395
+ if args.resolution_map:
396
+ rm_path = Path(args.resolution_map).expanduser()
397
+ if not rm_path.is_file():
398
+ sys.exit(f"ERROR: --resolution-map {rm_path} not found")
399
+ with open(rm_path) as fh:
400
+ resolution_map = json.load(fh)
401
+ log(f"Loaded resolution map: {len(resolution_map)} entries from {rm_path}")
402
+
403
+ meta_path = Path(args.metadata)
404
+ if not meta_path.exists():
405
+ sys.exit(f"ERROR: {meta_path} not found")
406
+
407
+ with open(meta_path) as f:
408
+ meta = json.load(f)
409
+ videos = meta.get("videos", meta if isinstance(meta, list) else [])
410
+ log(f"Loaded {len(videos)} chunk entries from {meta_path}")
411
+
412
+ # Group chunks by youtube_id (so each source video downloads once)
413
+ groups: dict[str, list[dict]] = defaultdict(list)
414
+ for v in videos:
415
+ yid = v.get("youtube_id")
416
+ if not yid:
417
+ continue
418
+ if args.filter_id and yid not in args.filter_id:
419
+ continue
420
+ groups[yid].append(v)
421
+
422
+ yt_ids = sorted(groups.keys())
423
+ if args.limit:
424
+ yt_ids = yt_ids[:args.limit]
425
+ log(f"Unique YouTube source videos: {len(yt_ids)}")
426
+
427
+ out_root = Path(args.out)
428
+ cache_dir = Path(args.cache)
429
+ out_root.mkdir(parents=True, exist_ok=True)
430
+ cache_dir.mkdir(parents=True, exist_ok=True)
431
+
432
+ # Run with a worker pool
433
+ results: list[dict] = []
434
+ t0 = time.time()
435
+ with concurrent.futures.ThreadPoolExecutor(max_workers=max(1, args.workers)) as ex:
436
+ futures = []
437
+ for yid in yt_ids:
438
+ chunks = groups[yid]
439
+ yt_url = chunks[0]["youtube_url"]
440
+ futures.append(ex.submit(
441
+ process_video_group,
442
+ yid, yt_url, chunks, out_root, cache_dir,
443
+ args.keep_fulls, args.dry_run, args.height,
444
+ reference_dir, resolution_map, args.source_cap,
445
+ ))
446
+ for fut in concurrent.futures.as_completed(futures):
447
+ results.append(fut.result())
448
+
449
+ elapsed = time.time() - t0
450
+ total_ok = sum(r["ok"] for r in results)
451
+ total_fail = sum(r["fail"] for r in results)
452
+ n_failed_videos = sum(1 for r in results if r["fail"] > 0)
453
+
454
+ print()
455
+ print("=" * 60)
456
+ print(f"DONE in {elapsed:.1f}s")
457
+ print(f" YouTube videos processed: {len(results)}")
458
+ print(f" Chunks OK: {total_ok}")
459
+ print(f" Chunks FAILED: {total_fail}")
460
+ print(f" Videos with failures: {n_failed_videos}")
461
+ print("=" * 60)
462
+
463
+ # Write a summary report alongside the metadata
464
+ report = {
465
+ "elapsed_seconds": elapsed,
466
+ "n_videos": len(results),
467
+ "n_chunks_ok": total_ok,
468
+ "n_chunks_failed": total_fail,
469
+ "failures": [
470
+ {"youtube_id": r["youtube_id"], "url": r["url"], "errors": r["errors"]}
471
+ for r in results if r["fail"] > 0
472
+ ],
473
+ }
474
+ rp = Path("download_report.json")
475
+ with open(rp, "w") as f:
476
+ json.dump(report, f, indent=2, ensure_ascii=False)
477
+ log(f"\nReport -> {rp}")
478
+
479
+ if total_fail:
480
+ log("Some clips failed. Re-run the script to retry only the failed ones "
481
+ "(successful clips are skipped automatically).")
482
+ sys.exit(1)
483
+
484
+ if __name__ == "__main__":
485
+ main()
scripts/redact.sh ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ #
3
+ # VSTAT — Apply privacy redactions (black boxes) to YouTube clips.
4
+ #
5
+ # Coordinates are in 640x360 (post-scale) space, matching the official
6
+ # VSTAT release. After this script runs, every redaction-target chunk
7
+ # lives at the canonical `videos/youtube/<cat>/<id>_pt*.mp4` path with
8
+ # the black boxes baked in. Any leftover `*_redacted.mp4` siblings from
9
+ # earlier runs are removed.
10
+ #
11
+ # Usage (run from vstat/ root):
12
+ # ./scripts/redact.sh
13
+ # ./scripts/redact.sh --dry-run
14
+ #
15
+
16
+ set -eo pipefail
17
+
18
+ DRY=0
19
+ for arg in "$@"; do
20
+ case "$arg" in
21
+ --dry-run) DRY=1 ;;
22
+ -h|--help) sed -n '2,15p' "$0"; exit 0 ;;
23
+ *) echo "Unknown arg: $arg" >&2; exit 1 ;;
24
+ esac
25
+ done
26
+
27
+ # Format: "<canonical-glob>|<ffmpeg drawbox filter>"
28
+ RULES=(
29
+ # tennis 0001
30
+ "videos/youtube/tennis/0001_pt*.mp4|drawbox=x=32:y=306:w=134:h=38:color=black:t=fill"
31
+ # tennis 0002
32
+ "videos/youtube/tennis/0002_pt*.mp4|drawbox=x=32:y=306:w=134:h=38:color=black:t=fill"
33
+ # basketball 0002
34
+ "videos/youtube/basketball/0002_pt*.mp4|drawbox=x=98:y=323:w=443:h=37:color=black:t=fill"
35
+ # basketball 0003
36
+ "videos/youtube/basketball/0003_pt*.mp4|drawbox=x=22:y=285:w=125:h=63:color=black:t=fill"
37
+ # soccer 0002 (two boxes)
38
+ "videos/youtube/soccer/0002_pt*.mp4|drawbox=x=0:y=0:w=122:h=19:color=black:t=fill,drawbox=x=140:y=320:w=360:h=40:color=black:t=fill"
39
+ )
40
+
41
+ if ! command -v ffmpeg >/dev/null 2>&1; then
42
+ echo "ERROR: ffmpeg not installed. brew install ffmpeg / apt install ffmpeg" >&2
43
+ exit 1
44
+ fi
45
+
46
+ # Expand a canonical glob to the union of canonical paths it covers,
47
+ # accounting for files that currently live with `_redacted` suffix.
48
+ # Compatible with bash 3.2 (macOS default) — no associative arrays.
49
+ canonical_paths_for_glob() {
50
+ glob="$1"
51
+ dir=$(dirname "$glob")
52
+ pat=$(basename "$glob") # 0001_pt*.mp4
53
+ shopt -s nullglob
54
+ results=""
55
+ for f in "$dir"/$pat "$dir"/${pat%.mp4}_redacted.mp4; do
56
+ [ -e "$f" ] || continue
57
+ case "$f" in
58
+ *_redacted.mp4) base="${f%_redacted.mp4}.mp4" ;;
59
+ *) base="$f" ;;
60
+ esac
61
+ results="${results}${base}"$'\n'
62
+ done
63
+ shopt -u nullglob
64
+ printf '%s' "$results" | sort -u | sed '/^$/d'
65
+ }
66
+
67
+ total=0; ok=0; fail=0; missing=0
68
+
69
+ for rule in "${RULES[@]}"; do
70
+ glob="${rule%%|*}"
71
+ filt="${rule#*|}"
72
+ echo
73
+ echo "=== $glob ==="
74
+ echo " filter: $filt"
75
+
76
+ paths=$(canonical_paths_for_glob "$glob")
77
+ if [ -z "$paths" ]; then
78
+ echo " (no matching files)"
79
+ continue
80
+ fi
81
+
82
+ while IFS= read -r canon; do
83
+ [ -z "$canon" ] && continue
84
+ total=$((total+1))
85
+ redacted_sibling="${canon%.mp4}_redacted.mp4"
86
+
87
+ # Pick input: prefer existing _redacted sibling, fall back to canonical.
88
+ if [ -f "$redacted_sibling" ]; then
89
+ input="$redacted_sibling"
90
+ elif [ -f "$canon" ]; then
91
+ input="$canon"
92
+ else
93
+ echo " ! missing both $canon and $redacted_sibling"
94
+ missing=$((missing+1))
95
+ continue
96
+ fi
97
+
98
+ if [ "$DRY" -eq 1 ]; then
99
+ echo " [DRY] $input =[$filt]=> $canon"
100
+ ok=$((ok+1))
101
+ continue
102
+ fi
103
+
104
+ # Write to a temp file then atomically swap.
105
+ # `-nostdin` is REQUIRED here: without it ffmpeg consumes characters
106
+ # from the surrounding `while read` loop's stdin, mangling later paths.
107
+ tmp="${canon%.mp4}.redact.tmp.mp4"
108
+ if ! ffmpeg -y -loglevel error -nostdin -i "$input" -vf "$filt" -c:a copy "$tmp"; then
109
+ echo " ! ffmpeg failed: $input"
110
+ fail=$((fail+1))
111
+ continue
112
+ fi
113
+ if cp -f "$tmp" "$canon" && rm -f "$tmp"; then
114
+ :
115
+ else
116
+ echo " ! could not write $canon (kept tmp at $tmp)"
117
+ fail=$((fail+1))
118
+ continue
119
+ fi
120
+ # Drop misleading `_redacted.mp4` sibling now that the canonical file
121
+ # holds the actually-redacted content.
122
+ if [ -f "$redacted_sibling" ] && [ "$redacted_sibling" != "$canon" ]; then
123
+ rm -f "$redacted_sibling" 2>/dev/null || true
124
+ fi
125
+ ok=$((ok+1))
126
+ echo " -> $canon"
127
+ done <<< "$paths"
128
+ done
129
+
130
+ echo
131
+ echo "============================================================"
132
+ echo " total: $total ok: $ok fail: $fail missing: $missing"
133
+ echo "============================================================"
134
+ [ "$fail" -eq 0 ] && [ "$missing" -eq 0 ]
videos/self_recorded/book/0001_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7e23199e689bed794b92b70b163cd0cfb0d13517a76f576b6d410f4be00dc009
3
+ size 8819418
videos/self_recorded/book/0002_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:edbd5f88761b0c984054ced5ed4bd76b701aac7437c3c80001cc7574575a0088
3
+ size 8739866
videos/self_recorded/book/0003_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:042b5afa19aaec02e6bd25d1646007f68db69b6f97f5b6921dd91124d4c4bc47
3
+ size 9093355
videos/self_recorded/book/0004_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4bf84cea1bb608d6061be02b5b26e70e5bfb41b0fef4ad957741c256760762ed
3
+ size 7567652
videos/self_recorded/book/0005_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cead3f7cd00547801bbe03a387a7ae0a4adbe15a8c070e1f7be070337ad77976
3
+ size 11909270
videos/self_recorded/book/0006_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a160b3ad466b7cf2b3c83e39c13f4161099ef2087c22ccb3350b448aad11b938
3
+ size 9852910
videos/self_recorded/book/0007_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:da759ccd0794e5d55812c9ac4bb796a115da820230fcfae0cb4886c36bec58fc
3
+ size 11537660
videos/self_recorded/book/0008_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eb275d1a1ad0230adb6c71812a1c792c25706745297b89937bdc696695ba802e
3
+ size 12228041
videos/self_recorded/book/0009_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9752f371e1d844c55c6f41076f5ae66b32f6161ebc61e1113d725144c75770d5
3
+ size 11899390
videos/self_recorded/book/0010_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:df0bbc76c936cc57730cb8066ed34f57d7c411b20fa207817a2c45a3ae078a6e
3
+ size 12259720
videos/self_recorded/cup_stacking/0001_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c8ea24a5232de154a0b42dac03d8ec8320d28a3646c0f2c84e941052905a57c3
3
+ size 7853078
videos/self_recorded/cup_stacking/0002_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:87117666ed8c705e9b3816f51f4777e1964b19e27ee8407442a741c736f041ba
3
+ size 6253120
videos/self_recorded/cup_stacking/0003_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b8cf6c140fd3292ca9f1b1383b8b22487012f6e139fca28f4d5ed682f1e92ff4
3
+ size 11822179
videos/self_recorded/cup_stacking/0004_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:11c9aad87be2ac680fdd440ad0e8528b56cd3c2644902c0b46f57cbe9ddc341b
3
+ size 10320277
videos/self_recorded/cup_stacking/0005_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e8fddf7ab1eb08252448caef9497995d97ebbf24fbcd185f6d8ee11e2158c687
3
+ size 10564190
videos/self_recorded/cup_stacking/0006_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e1f597b2b1943a6bc2c748e15f6ba36bb08937f4367a220572345a144702f909
3
+ size 11151561
videos/self_recorded/cup_stacking/0007_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8e685de2092186f6f762c566f2b347c06e5f21cb1a5a605b0422a35eef80f85c
3
+ size 10928178
videos/self_recorded/cup_stacking/0008_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bff79786e04265e1dc0ff3007689609063b41a570e12fdbb06acc4ed0528efaa
3
+ size 11099668
videos/self_recorded/cup_stacking/0009_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:38af26c6b13133b5cb85cc08b261c3e854bd262023e63c926db0b62afbb9a081
3
+ size 11809239
videos/self_recorded/cup_stacking/0010_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0f243f31fe60a1118a3f2bb07928b930eed9600bcd54c8bf147ce27bf5c554aa
3
+ size 10751368
videos/self_recorded/keyboard/0001_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:29906936a7eb6aa473aaffdcad313b2274c47dd3a38fbdd5e3a5184d947f7e77
3
+ size 3833649
videos/self_recorded/keyboard/0002_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1958f375f9c19bc3a8a06279562772fe74b29b6975834e1ce7af349fb2960ddd
3
+ size 3930910
videos/self_recorded/keyboard/0003_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d5fb2600aadf15301ab14491aabee2a65c28f0155729ac786689dc67bd6ce6e5
3
+ size 4514933
videos/self_recorded/keyboard/0004_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3b661d65184e101d63bfc16ae4654aac45ea2179756877629f73d9671aa735ff
3
+ size 6691558
videos/self_recorded/keyboard/0005_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cd87bde34474ae539e31280edd8a0d6e66c56969e086b78a07ca29e06ee56872
3
+ size 5103554
videos/self_recorded/keyboard/0006_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d1ed94f1b83df3b27f9acf0aef97dd8347f3e2cd7cc0b7b9b8e4125168b5c7a0
3
+ size 3997713
videos/self_recorded/keyboard/0007_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1f46486bbcf9dc3f7e3af168655909c5ef7da73e235ec2c28aff23ff1fabb53c
3
+ size 7412067
videos/self_recorded/keyboard/0008_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d7c41db184fe0e8fda6d61296228b70ce82f39ca05bfdd2649dd070d1655c743
3
+ size 3656426
videos/self_recorded/keyboard/0009_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f18b2035ae10fdd5297bf6727a7ce2a76dbc6a420124cac4b698b66bc277b469
3
+ size 4440764
videos/self_recorded/keyboard/0010_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c46b378728f8450feec02eeed2dfd35dfe0b255416d67a6244b117278d94eecc
3
+ size 6633008
videos/self_recorded/morse/0001_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c61400e0b40885eb4c01ffa9a5613395119debd0088dafba6282b29164ecc647
3
+ size 7293389
videos/self_recorded/morse/0002_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:662e8f3b6fd3a7ace6bd54bf96f55ad5431e7f828bb0b056667a678f74b2e731
3
+ size 6930512
videos/self_recorded/morse/0003_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4caa204c75dbc00c4950f518b6621bb30a6cfcf5700a01b6efa3543549432d2d
3
+ size 6719657
videos/self_recorded/morse/0004_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c4dab31c514a425b01970ba9446c58aeefe8d720b6229602ad425ebfa5dd2a87
3
+ size 6384910
videos/self_recorded/morse/0005_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4d63f6239d244eb6b071903e54efeacb21df52c4a086fae62f2d242adea43b5e
3
+ size 6691792
videos/self_recorded/morse/0006_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f6b96c1e8b573f20191eeb048fc82f1ea3727b1de7efb31b03c958e304b44a22
3
+ size 8573960
videos/self_recorded/morse/0007_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6a598e3cc6ef698ddf1a0b9903d5b54e1bf91343583b15f847fcf597fbdaa06d
3
+ size 5335238
videos/self_recorded/morse/0008_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7ac791f8f173fd0448915a557695ca2db71a90660b483abe87bac5ba8573d35c
3
+ size 6388731
videos/self_recorded/morse/0009_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0462fa4c2091227e6718fed1cc1c373d59631eb448825e9ea2ef27fd57cb8ae9
3
+ size 6846647
videos/self_recorded/morse/0010_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:644ee0ef91b0068e8147e4dab2a18a70a194ca39457f3a01b45755c7cdc09bb6
3
+ size 7409935
videos/self_recorded/numberpad/0001_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8742b4eb0a5ac7306b7cc243ab989389f04e64f3bacccdabd2bd8afd73f25b8d
3
+ size 7297044
videos/self_recorded/numberpad/0002_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4a92a5cd88e5444e55e6d0659607eeb11cf223047ed6977bf910e60050b6fa09
3
+ size 4085420
videos/self_recorded/numberpad/0003_pt1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:228236f4a94a850c3f235410abc1101bcf9aa08782d831233f7bb3aab327bc63
3
+ size 5145359