Arpan Tripathi commited on
Commit
fe6b545
·
unverified ·
1 Parent(s): 9b424ca

remove randomisation from VMAF calculation in competitions (#185)

Browse files
scripts/competition_data_generator/download_modal_output.sh ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+
5
+ profile="${1:-profile}"
6
+ volume="${2:-vidaio-compression-comp-inp-volume}"
7
+ destination="${3:-./output}"
8
+ source="${4:-./batches/000010/inputs}"
9
+
10
+ command -v modal >/dev/null || {
11
+ echo "Modal CLI not found. Install it with: pip install modal" >&2
12
+ exit 1
13
+ }
14
+
15
+ mkdir -p "$destination"
16
+ MODAL_PROFILE="$profile" modal volume get \
17
+ --env dev --force "$volume" "$source" "$destination"
scripts/competition_data_generator/extract_video_clips.py ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Extract multiple zero-timestamped clips from one or more videos.
3
+
4
+ The script deliberately uses ffmpeg stream copy (``-c copy``), so extraction is
5
+ fast and requires very little CPU. Cuts therefore occur near codec keyframes;
6
+ they are not guaranteed to be frame-exact. MP4 edit lists are disabled and
7
+ negative composition offsets are retained so every video timeline starts at
8
+ zero without re-encoding.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import random
15
+ import shutil
16
+ import subprocess
17
+ import sys
18
+ from pathlib import Path
19
+
20
+
21
+ REPO_ROOT = Path(__file__).resolve().parents[2]
22
+ DEFAULT_INPUTS = (
23
+ REPO_ROOT / "vid1.mp4",
24
+ REPO_ROOT / "vid2.mp4",
25
+ REPO_ROOT / "vid3.mp4",
26
+ )
27
+
28
+
29
+ def video_duration(path: Path) -> float:
30
+ result = subprocess.run(
31
+ [
32
+ "ffprobe",
33
+ "-v",
34
+ "error",
35
+ "-show_entries",
36
+ "format=duration",
37
+ "-of",
38
+ "default=noprint_wrappers=1:nokey=1",
39
+ str(path),
40
+ ],
41
+ check=True,
42
+ capture_output=True,
43
+ text=True,
44
+ )
45
+ return float(result.stdout.strip())
46
+
47
+
48
+ def video_start_time(path: Path) -> float:
49
+ result = subprocess.run(
50
+ [
51
+ "ffprobe",
52
+ "-v",
53
+ "error",
54
+ "-select_streams",
55
+ "v:0",
56
+ "-show_entries",
57
+ "stream=start_time",
58
+ "-of",
59
+ "default=noprint_wrappers=1:nokey=1",
60
+ str(path),
61
+ ],
62
+ check=True,
63
+ capture_output=True,
64
+ text=True,
65
+ )
66
+ return float(result.stdout.strip())
67
+
68
+
69
+ def clip_windows(
70
+ source_duration: float,
71
+ count: int,
72
+ min_duration: float,
73
+ max_duration: float,
74
+ rng: random.Random,
75
+ ) -> list[tuple[float, float]]:
76
+ """Create windows spread evenly over the usable source timeline."""
77
+ if source_duration < min_duration:
78
+ raise ValueError(
79
+ f"source is {source_duration:.2f}s, shorter than the minimum "
80
+ f"clip duration ({min_duration:.2f}s)"
81
+ )
82
+
83
+ longest = min(max_duration, source_duration)
84
+ windows: list[tuple[float, float]] = []
85
+ for index in range(count):
86
+ duration = rng.uniform(min_duration, longest)
87
+ latest_start = max(0.0, source_duration - duration)
88
+ # Put one start in each equal timeline bucket, with seeded jitter.
89
+ bucket_start = latest_start * index / count
90
+ bucket_end = latest_start * (index + 1) / count
91
+ start = rng.uniform(bucket_start, bucket_end) if bucket_end > bucket_start else 0.0
92
+ windows.append((start, duration))
93
+ return windows
94
+
95
+
96
+ def extract_clip(source: Path, output: Path, start: float, duration: float) -> None:
97
+ output.parent.mkdir(parents=True, exist_ok=True)
98
+ subprocess.run(
99
+ [
100
+ "ffmpeg",
101
+ "-hide_banner",
102
+ "-loglevel",
103
+ "error",
104
+ "-ss",
105
+ f"{start:.3f}",
106
+ "-i",
107
+ str(source),
108
+ "-t",
109
+ f"{duration:.3f}",
110
+ "-map",
111
+ "0",
112
+ "-c",
113
+ "copy",
114
+ "-avoid_negative_ts",
115
+ "disabled",
116
+ "-movflags",
117
+ "+faststart+negative_cts_offsets",
118
+ "-use_editlist",
119
+ "0",
120
+ "-y",
121
+ str(output),
122
+ ],
123
+ check=True,
124
+ )
125
+
126
+
127
+ def extract_validated_clip(
128
+ source: Path,
129
+ output: Path,
130
+ start: float,
131
+ requested_duration: float,
132
+ min_duration: float,
133
+ max_duration: float,
134
+ ) -> float:
135
+ """Extract and compensate for keyframe-induced stream-copy duration drift."""
136
+ duration = requested_duration
137
+ for _ in range(3):
138
+ extract_clip(source, output, start, duration)
139
+ actual = video_duration(output)
140
+ if min_duration - 0.01 <= actual <= max_duration + 0.01:
141
+ start_time = video_start_time(output)
142
+ if abs(start_time) > 0.000001:
143
+ raise RuntimeError(
144
+ f"output video timeline starts at {start_time:.6f}s instead of zero"
145
+ )
146
+ return actual
147
+ # With input-side seeking, an earlier keyframe can make the file longer
148
+ # than -t. Adjusting -t retains stream copy and is still very cheap.
149
+ boundary = min_duration if actual < min_duration else max_duration
150
+ duration = max(0.1, duration + boundary - actual - 0.02)
151
+ raise RuntimeError(f"output duration remained outside bounds (last: {actual:.3f}s)")
152
+
153
+
154
+ def parse_args() -> argparse.Namespace:
155
+ parser = argparse.ArgumentParser(
156
+ description="Extract 10-30 second clips using ffmpeg stream copy."
157
+ )
158
+ parser.add_argument(
159
+ "inputs",
160
+ nargs="*",
161
+ type=Path,
162
+ default=list(DEFAULT_INPUTS),
163
+ help="input videos (defaults to the three MP4s in the repository root)",
164
+ )
165
+ parser.add_argument("-o", "--output-dir", type=Path, default=REPO_ROOT / "video_clips")
166
+ parser.add_argument("-n", "--clips-per-video", type=int, default=20)
167
+ parser.add_argument("--min-duration", type=float, default=10.0)
168
+ parser.add_argument("--max-duration", type=float, default=30.0)
169
+ parser.add_argument("--seed", type=int, default=2026, help="seed for reproducible selections")
170
+ parser.add_argument("--dry-run", action="store_true", help="print selections without running ffmpeg")
171
+ return parser.parse_args()
172
+
173
+
174
+ def main() -> int:
175
+ args = parse_args()
176
+ if args.clips_per_video < 1:
177
+ raise SystemExit("--clips-per-video must be at least 1")
178
+ if args.min_duration <= 0 or args.max_duration < args.min_duration:
179
+ raise SystemExit("durations must satisfy 0 < min-duration <= max-duration")
180
+ if not args.dry_run:
181
+ for command in ("ffmpeg", "ffprobe"):
182
+ if shutil.which(command) is None:
183
+ raise SystemExit(f"required command not found: {command}")
184
+
185
+ output_dir = args.output_dir.expanduser().resolve()
186
+ rng = random.Random(args.seed)
187
+ failures = 0
188
+ for raw_source in args.inputs:
189
+ source = raw_source.expanduser().resolve()
190
+ if not source.is_file():
191
+ print(f"ERROR: input does not exist: {source}", file=sys.stderr)
192
+ failures += 1
193
+ continue
194
+ try:
195
+ duration = video_duration(source)
196
+ windows = clip_windows(
197
+ duration,
198
+ args.clips_per_video,
199
+ args.min_duration,
200
+ args.max_duration,
201
+ rng,
202
+ )
203
+ except (ValueError, subprocess.CalledProcessError) as error:
204
+ print(f"ERROR: cannot process {source}: {error}", file=sys.stderr)
205
+ failures += 1
206
+ continue
207
+
208
+ source_dir = output_dir / source.stem
209
+ print(f"{source.name}: {duration:.2f}s -> {len(windows)} clips in {source_dir}")
210
+ for number, (start, clip_duration) in enumerate(windows, start=1):
211
+ output = source_dir / f"{source.stem}_clip_{number:02d}.mp4"
212
+ print(f" {number:02d}: start={start:9.3f}s duration={clip_duration:6.3f}s")
213
+ if args.dry_run:
214
+ continue
215
+ try:
216
+ actual = extract_validated_clip(
217
+ source,
218
+ output,
219
+ start,
220
+ clip_duration,
221
+ args.min_duration,
222
+ args.max_duration,
223
+ )
224
+ print(f" wrote {output.name} ({actual:.3f}s)")
225
+ except (RuntimeError, subprocess.CalledProcessError, ValueError) as error:
226
+ print(f"ERROR: failed to create {output}: {error}", file=sys.stderr)
227
+ failures += 1
228
+
229
+ return 1 if failures else 0
230
+
231
+
232
+ if __name__ == "__main__":
233
+ raise SystemExit(main())
tests/competition/test_phase4.py CHANGED
@@ -78,6 +78,7 @@ from vidaio_subnet_core.competition.scoring import (
78
  CompetitionItemScorer,
79
  ItemScoringError,
80
  ScoredItem,
 
81
  compute_aggregates,
82
  length_weight,
83
  )
@@ -2278,6 +2279,25 @@ class FakeInspector:
2278
 
2279
 
2280
  class Phase4ScoringTests(unittest.TestCase):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2281
  def test_current_modal_sandbox_rates_and_gpu_name_mapping(self) -> None:
2282
  self.assertEqual(
2283
  set(GPU_PRICE_PER_SECOND_USD),
 
78
  CompetitionItemScorer,
79
  ItemScoringError,
80
  ScoredItem,
81
+ _default_vmaf,
82
  compute_aggregates,
83
  length_weight,
84
  )
 
2279
 
2280
 
2281
  class Phase4ScoringTests(unittest.TestCase):
2282
+ @patch("services.scoring.vmaf_metric.vmaf_metric_ffmpeg", return_value=97.25)
2283
+ def test_default_vmaf_scores_every_frame(self, vmaf_metric) -> None:
2284
+ score = _default_vmaf(
2285
+ Path("source.mp4"),
2286
+ Path("output.mp4"),
2287
+ sample_count=10,
2288
+ frame_count=300,
2289
+ scoring_seed=123,
2290
+ )
2291
+
2292
+ self.assertEqual(score, 97.25)
2293
+ vmaf_metric.assert_called_once_with(
2294
+ "output.mp4",
2295
+ "source.mp4",
2296
+ skip_frames=0,
2297
+ n_subsample=1,
2298
+ neg_model=True,
2299
+ )
2300
+
2301
  def test_current_modal_sandbox_rates_and_gpu_name_mapping(self) -> None:
2302
  self.assertEqual(
2303
  set(GPU_PRICE_PER_SECOND_USD),
vidaio_subnet_core/competition/scoring.py CHANGED
@@ -84,14 +84,12 @@ def _default_vmaf(
84
  ) -> float:
85
  from services.scoring.vmaf_metric import vmaf_metric_ffmpeg
86
 
87
- n_subsample = max(1, frame_count // max(1, sample_count))
88
- deterministic_offset = scoring_seed % n_subsample
89
  return float(
90
  vmaf_metric_ffmpeg(
91
  str(output),
92
  str(source),
93
- skip_frames=deterministic_offset,
94
- n_subsample=n_subsample,
95
  neg_model=True,
96
  )
97
  )
 
84
  ) -> float:
85
  from services.scoring.vmaf_metric import vmaf_metric_ffmpeg
86
 
 
 
87
  return float(
88
  vmaf_metric_ffmpeg(
89
  str(output),
90
  str(source),
91
+ skip_frames=0,
92
+ n_subsample=1,
93
  neg_model=True,
94
  )
95
  )