Spaces:
Running

File size: 13,051 Bytes
b83d389
 
 
 
 
 
f01288c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b83d389
 
 
9ed20e4
f01288c
b83d389
 
 
 
f01288c
 
 
 
 
9ed20e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b83d389
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f01288c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b83d389
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f01288c
 
b83d389
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f01288c
 
 
 
 
 
 
 
 
 
 
 
b83d389
f01288c
57cb628
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b2afc3
 
 
 
57cb628
 
 
 
 
 
 
 
 
 
 
 
 
 
4b2afc3
 
57cb628
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.

"""Lightweight ffprobe-based metrics for whole-video and segment clips.

Per-clip **luma / complexity** features (same definitions for whole file and segment extracts):

- **EY** β€” luma texture / spatial complexity: FFmpeg ``siti`` filter *Spatial Information* (SI),
  ITU-style edge energy on the luma plane.
- **h** β€” temporal complexity: ``siti`` *Temporal Information* (TI), frame-to-frame variation.
- **LY** β€” luma brightness: mean of per-frame ``signalstats`` ``YAVG`` (0–255).

Observation dict keys (use these names in code and for agents):

- ``luma_spatial_texture_complexity_EY`` β€” maps to **EY** / SI above
- ``temporal_complexity_h`` β€” maps to **h** / TI above
- ``mean_luma_brightness_LY`` β€” maps to **LY** / mean YAVG above
"""

from __future__ import annotations

import copy
import re
import subprocess
from pathlib import Path
from typing import Any

# Full JSON keys for complexity metrics (paper symbols EY, h, LY kept in the name for traceability).
LUMA_SPATIAL_TEXTURE_COMPLEXITY_EY = "luma_spatial_texture_complexity_EY"
TEMPORAL_COMPLEXITY_H = "temporal_complexity_h"
MEAN_LUMA_BRIGHTNESS_LY = "mean_luma_brightness_LY"

# Populated on ``POST /api/videos/upload``; read by the env on reset/step (no ffmpeg there).
# Process-local only; cleared on server restart.
_video_analysis_memory: dict[str, dict[str, Any]] = {}


def _video_path_key(path: Path) -> str:
    return str(path.resolve())


def store_whole_video_analysis(video_path: Path, data: dict[str, Any]) -> None:
    """Keep ``analyze_video`` output in memory for later observations (keyed by resolved path)."""
    _video_analysis_memory[_video_path_key(video_path)] = copy.deepcopy(data)


def forget_whole_video_analysis(video_path: Path) -> None:
    """Drop cached analysis for ``video_path`` (e.g. after the file is deleted)."""
    _video_analysis_memory.pop(_video_path_key(video_path), None)


def load_whole_video_analysis_for_observation(video_path: Path) -> dict[str, Any]:
    """
    Data for ``VideoEncodeObservation.whole_video_analysis`` without running ffmpeg.

    Returns a copy of the in-memory snapshot from upload if present and file size still matches;
    otherwise ``{}``.
    """
    key = _video_path_key(video_path)
    data = _video_analysis_memory.get(key)
    if data is None:
        return {}
    try:
        sz = video_path.stat().st_size
    except OSError:
        return {}
    fsb = data.get("file_size_bytes")
    if fsb is not None and int(fsb) != sz:
        return {}
    return copy.deepcopy(data)


def _run_ffprobe(args: list[str]) -> subprocess.CompletedProcess[str]:
    return subprocess.run(
        args,
        capture_output=True,
        text=True,
        timeout=120,
        check=False,
    )


def _parse_frame_rate(s: str) -> float | None:
    s = s.strip()
    if not s or s == "0/0":
        return None
    if "/" in s:
        num, den = s.split("/", 1)
        try:
            n, d = float(num), float(den)
            return n / d if d else None
        except ValueError:
            return None
    try:
        return float(s)
    except ValueError:
        return None


def ffprobe_duration_sec(path: Path) -> float:
    r = _run_ffprobe(
        [
            "ffprobe",
            "-v",
            "error",
            "-show_entries",
            "format=duration",
            "-of",
            "default=noprint_wrappers=1:nokey=1",
            str(path),
        ]
    )
    if r.returncode != 0:
        raise RuntimeError(f"ffprobe failed for {path}: {r.stderr}")
    return float(r.stdout.strip())


def ffprobe_video_size(path: Path) -> tuple[int, int]:
    r = _run_ffprobe(
        [
            "ffprobe",
            "-v",
            "error",
            "-select_streams",
            "v:0",
            "-show_entries",
            "stream=width,height",
            "-of",
            "csv=p=0:s=x",
            str(path),
        ]
    )
    if r.returncode != 0:
        raise RuntimeError(f"ffprobe size failed for {path}: {r.stderr}")
    parts = r.stdout.strip().split("x")
    if len(parts) != 2:
        raise RuntimeError(f"unexpected ffprobe size output: {r.stdout!r}")
    return int(parts[0]), int(parts[1])


def ffprobe_bitrate_kbps(path: Path) -> float:
    r = _run_ffprobe(
        [
            "ffprobe",
            "-v",
            "error",
            "-show_entries",
            "format=bit_rate",
            "-of",
            "default=noprint_wrappers=1:nokey=1",
            str(path),
        ]
    )
    if r.returncode != 0:
        raise RuntimeError(f"ffprobe bitrate failed: {r.stderr}")
    line = r.stdout.strip()
    if not line or line == "N/A":
        size = path.stat().st_size
        dur = ffprobe_duration_sec(path)
        if dur <= 0:
            return 0.0
        return (size * 8) / dur / 1000.0
    return float(line) / 1000.0


_YAVG_RE = re.compile(r"lavfi\.signalstats\.YAVG=([0-9.+-eE]+)")


def _parse_siti_spatial_temporal_averages(stderr: str) -> tuple[float | None, float | None]:
    """Return (SI average, TI average) from ``siti=print_summary=1`` stderr."""
    si: float | None = None
    ti: float | None = None
    section: str | None = None
    for line in stderr.splitlines():
        if "Spatial Information:" in line:
            section = "spatial"
        elif "Temporal Information:" in line:
            section = "temporal"
        elif line.strip().startswith("Average:"):
            try:
                val = float(line.split(":", 1)[1].strip())
            except (ValueError, IndexError):
                continue
            if section == "spatial":
                si = val
                section = None
            elif section == "temporal":
                ti = val
                section = None
    return si, ti


def _mean_signalstats_yavg(stdout: str) -> float | None:
    vals = [float(m.group(1)) for m in _YAVG_RE.finditer(stdout)]
    if not vals:
        return None
    return sum(vals) / len(vals)


def _run_ffmpeg_luma_complexity_metrics(
    path: Path,
    *,
    complexity_timeout_sec: float,
) -> dict[str, float | None]:
    """Compute EY (SI), h (TI), LY (mean YAVG) via two ffmpeg passes."""
    luma_spatial_texture_complexity_EY: float | None = None
    temporal_complexity_h: float | None = None
    mean_luma_brightness_LY: float | None = None

    r_siti = subprocess.run(
        [
            "ffmpeg",
            "-hide_banner",
            "-nostats",
            "-i",
            str(path),
            "-vf",
            "siti=print_summary=1",
            "-f",
            "null",
            "-",
        ],
        capture_output=True,
        text=True,
        timeout=complexity_timeout_sec,
        check=False,
    )
    si, ti = _parse_siti_spatial_temporal_averages(r_siti.stderr)
    luma_spatial_texture_complexity_EY = si
    temporal_complexity_h = ti

    r_stat = subprocess.run(
        [
            "ffmpeg",
            "-hide_banner",
            "-nostats",
            "-i",
            str(path),
            "-vf",
            "signalstats,metadata=print:file=-",
            "-f",
            "null",
            "-",
        ],
        capture_output=True,
        text=True,
        timeout=complexity_timeout_sec,
        check=False,
    )
    if r_stat.returncode == 0:
        mean_luma_brightness_LY = _mean_signalstats_yavg(r_stat.stdout)

    return {
        LUMA_SPATIAL_TEXTURE_COMPLEXITY_EY: luma_spatial_texture_complexity_EY,
        TEMPORAL_COMPLEXITY_H: temporal_complexity_h,
        MEAN_LUMA_BRIGHTNESS_LY: mean_luma_brightness_LY,
    }


def ffprobe_avg_frame_rate(path: Path) -> float | None:
    r = _run_ffprobe(
        [
            "ffprobe",
            "-v",
            "error",
            "-select_streams",
            "v:0",
            "-show_entries",
            "stream=avg_frame_rate,r_frame_rate",
            "-of",
            "csv=p=0",
            str(path),
        ]
    )
    if r.returncode != 0:
        return None
    line = r.stdout.strip()
    if not line:
        return None
    for p in line.split(","):
        fr = _parse_frame_rate(p)
        if fr is not None and fr > 0:
            return fr
    return None


def analyze_video(path: Path, *, complexity_timeout_sec: float = 120.0) -> dict[str, Any]:
    """Whole-file metrics (duration, resolution, fps, bitrate, size, luma/complexity keys)."""
    out: dict[str, Any] = {"path": str(path.resolve())}
    try:
        out["duration_sec"] = ffprobe_duration_sec(path)
    except RuntimeError as e:
        out["duration_sec"] = None
        out["error"] = str(e)
        return out
    try:
        w, h = ffprobe_video_size(path)
        out["width"] = w
        out["height"] = h
    except RuntimeError:
        out["width"] = None
        out["height"] = None
    try:
        out["bitrate_kbps"] = ffprobe_bitrate_kbps(path)
    except RuntimeError:
        out["bitrate_kbps"] = None
    out["fps"] = ffprobe_avg_frame_rate(path)
    try:
        out["file_size_bytes"] = path.stat().st_size
    except OSError:
        out["file_size_bytes"] = None

    try:
        metrics = _run_ffmpeg_luma_complexity_metrics(
            path,
            complexity_timeout_sec=complexity_timeout_sec,
        )
        out[LUMA_SPATIAL_TEXTURE_COMPLEXITY_EY] = metrics[LUMA_SPATIAL_TEXTURE_COMPLEXITY_EY]
        out[TEMPORAL_COMPLEXITY_H] = metrics[TEMPORAL_COMPLEXITY_H]
        out[MEAN_LUMA_BRIGHTNESS_LY] = metrics[MEAN_LUMA_BRIGHTNESS_LY]
    except (TimeoutError, subprocess.TimeoutExpired, OSError):
        out[LUMA_SPATIAL_TEXTURE_COMPLEXITY_EY] = None
        out[TEMPORAL_COMPLEXITY_H] = None
        out[MEAN_LUMA_BRIGHTNESS_LY] = None

    return out


def analyze_segment_clip(
    path: Path,
    *,
    timeout: float | None = None,
    compute_complexity: bool = True,
) -> dict[str, Any]:
    """
    Per-segment features computed on an already-extracted reference clip.

    Designed to be called on the short clip that the environment extracts before
    encoding (the CRF-18 ultrafast reference), so the cost is low (~1–2 s for
    a 3 s segment at 1080p).

    Always-present keys (value may be ``None`` on probe failure):
    - ``width``, ``height``         β€” frame dimensions
    - ``duration_sec``              β€” clip duration from container metadata
    - ``fps``                       β€” average frame rate
    - ``bitrate_kbps``              β€” bitrate of the reference (CRF-18) extract
    - ``file_size_bytes``           β€” byte size on disk

    Keys added when ``compute_complexity=True`` (default):
    - ``luma_spatial_texture_complexity_EY``  β€” spatial information (SI) via ``siti``
    - ``temporal_complexity_h``               β€” temporal information (TI) via ``siti``
    - ``mean_luma_brightness_LY``             β€” mean per-frame luma (YAVG) via ``signalstats``

    Reserved for future passes (not yet implemented; controlled by future keyword
    arguments that will be added here):
    - scene-cut count / flag        (``compute_scene_cuts``)
    - I/P/B frame-type ratio        (``compute_frame_types``)
    - quality-sensitivity baseline  (``compute_quality_baseline``)
    """
    out: dict[str, Any] = {}

    try:
        w, h = ffprobe_video_size(path)
        out["width"] = w
        out["height"] = h
    except RuntimeError:
        out["width"] = None
        out["height"] = None

    try:
        out["duration_sec"] = ffprobe_duration_sec(path)
    except RuntimeError:
        out["duration_sec"] = None

    try:
        out["fps"] = ffprobe_avg_frame_rate(path)
    except Exception:
        out["fps"] = None

    try:
        out["bitrate_kbps"] = ffprobe_bitrate_kbps(path)
    except RuntimeError:
        out["bitrate_kbps"] = None

    try:
        out["file_size_bytes"] = path.stat().st_size
    except OSError:
        out["file_size_bytes"] = None

    if compute_complexity:
        # Cap the per-segment complexity pass at 30 s regardless of the global timeout.
        # A well-extracted 3 s clip typically finishes well under 5 s.
        # complexity_timeout = min(30.0, float(timeout)) if timeout is not None else 30.0
        complexity_timeout = 600
        try:
            metrics = _run_ffmpeg_luma_complexity_metrics(
                path,
                complexity_timeout_sec=complexity_timeout,
            )
            out[LUMA_SPATIAL_TEXTURE_COMPLEXITY_EY] = metrics[LUMA_SPATIAL_TEXTURE_COMPLEXITY_EY]
            out[TEMPORAL_COMPLEXITY_H] = metrics[TEMPORAL_COMPLEXITY_H]
            out[MEAN_LUMA_BRIGHTNESS_LY] = metrics[MEAN_LUMA_BRIGHTNESS_LY]
        except (TimeoutError, subprocess.TimeoutExpired, OSError):
            out[LUMA_SPATIAL_TEXTURE_COMPLEXITY_EY] = None
            out[TEMPORAL_COMPLEXITY_H] = None
            out[MEAN_LUMA_BRIGHTNESS_LY] = None

    return out