Spaces:
Running
Running
Upload folder using huggingface_hub
Browse filesFiles changed (6)
- client.py-1
- models.py+6-6
- run_smoke_test.py+1-1
- server/app.py+2-2
- server/video_encode_environment.py+62-21
- video_analysis.py+130-15
54 unmodified lines5556575858596054 unmodified lines steps_per_segment=obs_data.get("steps_per_segment", 10), prev_segment_predictions=obs_data.get("prev_segment_predictions"), whole_video_analysis=obs_data.get("whole_video_analysis") or {}, segment_analysis=obs_data.get("segment_analysis") or {}, vmaf_score=obs_data.get("vmaf_score"), ssim_score=obs_data.get("ssim_score"), bitrate_kbps=obs_data.get("bitrate_kbps"),7 unmodified lines8910111112131441 unmodified lines565758596061626359606162636465667 unmodified linesData models for the Video Encode Environment.
Observations include segment index, DQ-style previous-segment predictions,and ffprobe-based whole-video vs current-segment analysis dicts.and ffprobe-based whole-video analysis dicts."""
from typing import Any, Dict, Optional41 unmodified lines ) whole_video_analysis: Dict[str, Any] = Field( default_factory=dict, description="ffprobe-style metrics for the full source file", ) segment_analysis: Dict[str, Any] = Field( default_factory=dict, description="ffprobe-style metrics for the current reference clip + segment start/duration", description=( "Metrics for the full source file (duration, resolution, …) plus " "luma_spatial_texture_complexity_EY, temporal_complexity_h, mean_luma_brightness_LY " "(see video_analysis module constants)" ), ) vmaf_score: Optional[float] = Field(default=None, description="VMAF pooled mean vs reference segment") ssim_score: Optional[float] = Field(default=None, description="SSIM All if VMAF unavailable")54 unmodified lines555657585859606154 unmodified lines print(f" {key}:\n{json.dumps(d[key], indent=4)}") elif key in d: print(f" {key}: {d[key]}") for key in ("whole_video_analysis", "segment_analysis"): for key in ("whole_video_analysis",): if d.get(key): print(f" {key}:\n{json.dumps(d[key], indent=2)}") for key in ("vmaf_score", "ssim_score", "bitrate_kbps", "encoding_time_sec"):10 unmodified lines1112131415141516171810 unmodified linesover HTTP and WebSocket endpoints, compatible with EnvClient.
Endpoints: - POST /reset: Reset the environment - POST /step: Execute an action - POST /reset: Reset the environment (new env instance per request; state does not persist to the next HTTP call) - POST /step: Execute an action (same; use WebSocket /ws + EnvClient for persistent episode state) - GET /state: Get current environment state - GET /schema: Get action/observation schemas - WS /ws: WebSocket endpoint for persistent sessions56 unmodified lines57585960606162637 unmodified lines717273747475767795 unmodified lines17317417517617717817918040 unmodified lines22122222322222422522613 unmodified lines24024124224224324424531 unmodified lines2772782792802802812825 unmodified lines2882892902922912922932942952962974 unmodified lines3023033043033053063076 unmodified lines3143153163173183193203213223233243253263273283293303313323333342 unmodified lines3373383393253403413423 unmodified lines3463473483493503513526 unmodified lines3593603613473623633644 unmodified lines3693703713583723733743753763773783793803813823833842 unmodified lines3873883893723903913925 unmodified lines3983994004014024034044054064074084092 unmodified lines4124134143924154164176 unmodified lines42442542642742842943043143243343443543643715 unmodified lines4534544554564574584594604614624634644654 unmodified lines4704714724364734744752 unmodified lines4784794804454464474484494504514814824836 unmodified lines4904914924934944954968 unmodified lines5055065075085095105115125135145156 unmodified lines5225235245255265275285295305315325335342 unmodified lines53753853949854054154256 unmodified lines ssim_score, vmaf_score, ) from ..video_analysis import analyze_segment_clip, analyze_video from ..video_analysis import analyze_video from ..video_paths import load_video_pathsexcept ImportError: from models import VideoEncodeAction, VideoEncodeObservation7 unmodified lines ssim_score, vmaf_score, ) from video_analysis import analyze_segment_clip, analyze_video from video_analysis import analyze_video from video_paths import load_video_paths
logger = logging.getLogger(__name__)95 unmodified lines self._ffmpeg_timeout_sec = ( ffmpeg_timeout_sec if ffmpeg_timeout_sec is not None else _timeout_from_env() ) _to = self._ffmpeg_timeout_sec self._complexity_analysis_timeout_sec = float(_to) if _to is not None else 600.0 self._reward_cfg = _reward_config_from_env() self._steps_per_segment = max( 1,40 unmodified lines encode_step_index: int, prev_segment_predictions: dict[str, Any] | None, whole_video_analysis: dict[str, Any], segment_analysis: dict[str, Any], vmaf_score: float | None, ssim_score: float | None, bitrate_kbps: float | None,13 unmodified lines steps_per_segment=self._steps_per_segment, prev_segment_predictions=pp, whole_video_analysis=whole_video_analysis, segment_analysis=segment_analysis, vmaf_score=vmaf_score, ssim_score=ssim_score, bitrate_kbps=bitrate_kbps,31 unmodified lines encode_step_index=0, prev_segment_predictions=None, whole_video_analysis={}, segment_analysis={}, vmaf_score=None, ssim_score=None, bitrate_kbps=None,5 unmodified lines ref_path = self._video_paths[self._current_video_idx] key = str(ref_path.resolve()) if key not in self._whole_video_analysis_cache: self._whole_video_analysis_cache[key] = analyze_video(ref_path) self._whole_video_analysis_cache[key] = analyze_video( ref_path, complexity_timeout_sec=self._complexity_analysis_timeout_sec, )
wv = copy.deepcopy(self._whole_video_analysis_cache[key]) return self._observation(4 unmodified lines encode_step_index=0, prev_segment_predictions=None, whole_video_analysis=wv, segment_analysis={}, vmaf_score=None, ssim_score=None, bitrate_kbps=None,6 unmodified lines """K encode attempts per timeline segment; advance file cursor only after K steps.""" self._state.step_count += 1 n = len(self._video_paths) logger.info( "step begin: step_count=%s reset_index=%s crf=%s preset=%s video_index=%s num_videos=%s " "segment_index=%s encode_step_index=%s/%s", self._state.step_count, self._reset_count, action.crf, action.preset, action.video_index, n, self._segment_index, self._step_in_segment, self._steps_per_segment, ) if n == 0: logger.warning("step: no videos loaded") return self._observation( echoed_message="No videos loaded.", num_videos=0,2 unmodified lines encode_step_index=self._step_in_segment, prev_segment_predictions=copy.deepcopy(self._prev_segment_summary), whole_video_analysis={}, segment_analysis={}, vmaf_score=None, ssim_score=None, bitrate_kbps=None,3 unmodified lines
idx = action.video_index if action.video_index is not None else self._current_video_idx if idx < 0 or idx >= n: logger.warning("step: invalid video_index=%s (valid 0..%s)", idx, n - 1) return self._observation( echoed_message=f"Invalid video_index {idx} (need 0..{n - 1})", num_videos=n,6 unmodified lines str(self._video_paths[self._current_video_idx].resolve()), {} ) ), segment_analysis={}, vmaf_score=None, ssim_score=None, bitrate_kbps=None,4 unmodified lines ref_video = self._video_paths[idx] key = str(ref_video.resolve()) if key not in self._whole_video_analysis_cache: self._whole_video_analysis_cache[key] = analyze_video(ref_video) self._whole_video_analysis_cache[key] = analyze_video( ref_video, complexity_timeout_sec=self._complexity_analysis_timeout_sec, ) whole_video_analysis = copy.deepcopy(self._whole_video_analysis_cache[key])
try: dur = ffprobe_duration_sec(ref_video) except RuntimeError as e: logger.warning("step: ffprobe duration failed for %s: %s", key, e) return self._observation( echoed_message=str(e), num_videos=n,2 unmodified lines encode_step_index=self._step_in_segment, prev_segment_predictions=copy.deepcopy(self._prev_segment_summary), whole_video_analysis=whole_video_analysis, segment_analysis={}, vmaf_score=None, ssim_score=None, bitrate_kbps=None,5 unmodified lines start_sec = self._segment_start_sec seg_len = min(self._segment_duration_sec, max(0.0, dur - start_sec)) if seg_len < 0.1: logger.info( "step: end of video (start_sec=%.3f dur=%.3f seg_len=%.3f)", start_sec, dur, seg_len, ) return self._observation( echoed_message="No more segment data (end of video).", num_videos=n,2 unmodified lines encode_step_index=self._step_in_segment, prev_segment_predictions=copy.deepcopy(self._prev_segment_summary), whole_video_analysis=whole_video_analysis, segment_analysis={}, vmaf_score=None, ssim_score=None, bitrate_kbps=None,6 unmodified lines encode_step_this = self._step_in_segment
to = self._ffmpeg_timeout_sec logger.info( "step: encode segment video=%s timeline_seg=%s substep=%s start_sec=%.3f duration_sec=%.3f", ref_video.name, timeline_idx, encode_step_this, start_sec, seg_len, ) with tempfile.TemporaryDirectory() as tmp: tmp_path = Path(tmp) ref_clip = tmp_path / "ref.mp4"15 unmodified lines ssim: float | None = None if vmaf is None: ssim = ssim_score(enc_path, ref_clip, timeout=to) logger.info( "step: metrics vmaf=%s ssim=%s bitrate_kbps=%s encode_time_sec=%s", vmaf, ssim, bitrate, enc_time, ) except Exception as e: # pragma: no cover - ffmpeg logger.exception("step encode failed") return self._observation(4 unmodified lines encode_step_index=encode_step_this, prev_segment_predictions=prev_for_obs, whole_video_analysis=whole_video_analysis, segment_analysis={}, vmaf_score=None, ssim_score=None, bitrate_kbps=None,2 unmodified lines metadata={"error": str(e)}, )
# Must run while ref_clip still exists (temp dir is deleted after this block). segment_analysis = analyze_segment_clip( ref_clip, start_sec=start_sec, duration_sec=seg_len, )
reward, r_components = compute_segment_reward( vmaf=vmaf, ssim=ssim,6 unmodified lines time_max_sec=self._reward_cfg["time_max_sec"], bitrate_max_kbps=self._reward_cfg["bitrate_max_kbps"], ) logger.info("step: reward=%s components=%s", reward, r_components)
self._segment_step_metrics.append( {8 unmodified lines ) self._step_in_segment += 1 if self._step_in_segment >= self._steps_per_segment: logger.info( "step: completed K=%s encodes for timeline segment %s; advancing timeline", self._steps_per_segment, timeline_idx, ) self._prev_segment_summary = _summarize_completed_segment( self._segment_step_metrics, timeline_segment_index=timeline_idx,6 unmodified lines self._segment_index += 1 self._step_in_segment = 0
logger.info( "step end: step_count=%s segment_index=%s next_encode_step_index=%s reward=%s", self._state.step_count, self._segment_index, self._step_in_segment, reward, ) return self._observation( echoed_message="ok", num_videos=n,2 unmodified lines encode_step_index=encode_step_this, prev_segment_predictions=prev_for_obs, whole_video_analysis=whole_video_analysis, segment_analysis=segment_analysis, vmaf_score=vmaf, ssim_score=ssim, bitrate_kbps=bitrate,3 unmodified lines45677891011121314151617181920212223242526272829303132333435363788 unmodified lines12612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422521 unmodified lines24724824913613725025125225325417 unmodified lines2722732741612752762772782792802812822832842852862872881641651661671681691701711721731742893 unmodified lines# 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.""""""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 reimport subprocessfrom pathlib import Pathfrom 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"
def _run_ffprobe(args: list[str]) -> subprocess.CompletedProcess[str]: return subprocess.run(88 unmodified lines 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( [21 unmodified lines return None
def analyze_video(path: Path) -> dict[str, Any]: """Whole-file metrics (duration, resolution, fps, bitrate, size)."""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)17 unmodified lines out["file_size_bytes"] = path.stat().st_size except OSError: out["file_size_bytes"] = None return out
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
def analyze_segment_clip( path: Path, *, start_sec: float, duration_sec: float,) -> dict[str, Any]: """Metrics for an extracted segment file plus timeline hints.""" base = analyze_video(path) base["segment_start_sec"] = start_sec base["segment_duration_sec"] = duration_sec return base return outclient.py-1
models.py+6-6
run_smoke_test.py+1-1
server/app.py+2-2
server/video_encode_environment.py+62-21
video_analysis.py+130-15