Spaces:
Running

video_encode / CLAUDE.md
keshav142's picture
Upload folder using huggingface_hub
57cb628 verified
|
Raw History Blame Contribute Delete
15.5 kB

Video Encode Environment β€” CLAUDE.md

Project-level context, architecture notes, development plans, and conventions for AI-assisted work. Update this file whenever significant context changes.


Project Overview

What it is: An RL (reinforcement learning) environment where an agent learns to choose optimal libx264 encoding parameters (crf, preset) for short video segments, balancing quality (VMAF/SSIM), file size (bitrate), and encoding speed.

OpenEnv framework: Built on openenv-core, which provides the FastAPI HTTP/WebSocket server scaffolding, Environment base class, Action/Observation types, and the EnvClient + Docker deployment helpers. The project runs as a Docker container or Hugging Face Space.

Deployed at: https://keshav142-video-encode.hf.space (default; override with VIDEO_ENCODE_DEFAULT_HF_URL or VIDEO_ENCODE_HF_URL).


Repository Layout

video_encode_env/
β”œβ”€β”€ models.py                        # VideoEncodeAction, VideoEncodeObservation (Pydantic)
β”œβ”€β”€ segment_utils.py                 # FFmpeg helpers: probe, extract, encode, VMAF, SSIM, bitrate
β”œβ”€β”€ video_analysis.py                # Whole-video & per-segment analysis (EY/h/LY complexity)
β”œβ”€β”€ video_paths.py                   # Video file discovery (directory scan or list file)
β”œβ”€β”€ data_collection.py               # Offline grid-sweep dataset builder (CRF Γ— preset Γ— resolution)
β”œβ”€β”€ inference.py                     # LLM agent inference loop (OpenAI-compat SDK β†’ HF router)
β”œβ”€β”€ __init__.py                      # Package re-exports: VideoEncodeAction, VideoEncodeEnv
β”œβ”€β”€ server/
β”‚   β”œβ”€β”€ app.py                       # FastAPI app (openenv create_app + video upload router)
β”‚   β”œβ”€β”€ video_encode_environment.py  # Core Environment class: reset(), step(), _observation()
β”‚   β”œβ”€β”€ reward.py                    # compute_segment_reward() β€” pure function, no side effects
β”‚   β”œβ”€β”€ video_upload.py              # POST /api/videos/upload, DELETE /api/videos/{filename}
β”‚   └── requirements.txt / pyproject.toml
β”œβ”€β”€ videos/                          # Default video directory (VIDEO_ENCODE_VIDEOS_DIR)
β”œβ”€β”€ Dockerfile
β”œβ”€β”€ openenv.yaml                     # OpenEnv Space config
└── pyproject.toml                   # Package: openenv-video_encode, entry points: server, inference

Data Flow (one step())

Agent sends VideoEncodeAction(crf, preset, video_index)
  β”‚
  β–Ό
VideoEncodeEnvironment.step()
  β”œβ”€ ffprobe_duration_sec(ref_video)            [segment_utils.py]
  β”œβ”€ tempfile.TemporaryDirectory
  β”‚   β”œβ”€ extract_segment(ref_video β†’ ref_clip)  [CRF-18 ultrafast reference extract]
  β”‚   β”œβ”€ ffprobe_video_size(ref_clip)           β†’ ew, eh
  β”‚   β”œβ”€ analyze_segment_clip(ref_clip)         β†’ seg_analysis  ← RECENTLY ADDED
  β”‚   β”œβ”€ encode_segment(ref_clip β†’ enc_path, crf=action.crf, preset=action.preset)
  β”‚   β”œβ”€ ffprobe_bitrate_kbps(enc_path)         β†’ bitrate
  β”‚   β”œβ”€ vmaf_score(enc_path, ref_clip)         β†’ vmaf
  β”‚   └─ ssim_score(enc_path, ref_clip)         β†’ ssim (only if vmaf is None)
  β”‚
  β”œβ”€ compute_segment_reward(vmaf, ssim, enc_time, bitrate, …)  [server/reward.py]
  └─ _observation(…, segment_analysis=seg_analysis, …)  β†’ VideoEncodeObservation

Segment advance logic: Each timeline segment gets K encode attempts (steps_per_segment, default 10). After K steps, _summarize_completed_segment() builds prev_segment_predictions (means of all K steps), the timeline cursor advances by segment_duration_sec, and the sub-step counter resets.


Action Schema

VideoEncodeAction:
  crf: int          # 0–51; lower = higher quality + larger file. Typical range 18–28.
  preset: str       # libx264 speed: ultrafast|superfast|veryfast|faster|fast|medium|slow|slower|veryslow
  video_index: int | None   # 0..num_videos-1; None = use episode default from reset()

Observation Schema

VideoEncodeObservation:
  # Episode state
  echoed_message: str              # "ok" on success; error text otherwise
  num_videos: int
  current_video_index: int
  reset_index: int                 # increments each reset()
  segment_index: int               # timeline position (advances after K encodes)
  encode_step_index: int           # 0..steps_per_segment-1 within current segment
  steps_per_segment: int           # K

  # History
  prev_segment_predictions: dict | None   # means over K steps of last completed segment
    # keys: vmaf_score, ssim_score, bitrate_kbps, encoding_time_sec, crf_avg,
    #        presets_used, reward_avg, steps_per_segment, steps_averaged

  # Content analysis (static per video, cached at upload)
  whole_video_analysis: dict        # duration_sec, width, height, fps, bitrate_kbps,
                                    # file_size_bytes, luma_spatial_texture_complexity_EY,
                                    # temporal_complexity_h, mean_luma_brightness_LY

  # Per-segment analysis on extracted ref_clip (RECENTLY ADDED)
  segment_analysis: dict            # width, height, duration_sec, fps, bitrate_kbps,
                                    # file_size_bytes, luma_spatial_texture_complexity_EY,
                                    # temporal_complexity_h, mean_luma_brightness_LY
                                    # (empty dict before extraction / on pre-extraction error)

  # Current step metrics
  vmaf_score: float | None
  ssim_score: float | None          # only when vmaf is None
  bitrate_kbps: float | None
  encoding_time_sec: float | None

  done: bool
  reward: float

Reward Function

Formula: R = Ξ»_QΒ·QΜ„ βˆ’ Ξ»_TΒ·TΜ„ βˆ’ Ξ»_SΒ·SΜ„ βˆ’ Ξ»_CΒ·CΜ„

Term Variable Formula Env var Default
Quality QΜ„ vmaf / vmaf_max (or ssim raw) VIDEO_ENCODE_REWARD_VMAF_MAX 100
Encode time TΜ„ min(time / time_max, 1) VIDEO_ENCODE_REWARD_TIME_MAX_SEC 3 Γ— seg_len
Bitrate SΜ„ min(bitrate / bitrate_max, 1) VIDEO_ENCODE_REWARD_BITRATE_MAX_KBPS 20000
CRF stability CΜ„ ramp when ` crf βˆ’ prev_crf_avg /prev_crf_avg > threshold`

Weights: Ξ»_Q=1.0, Ξ»_T=0.5, Ξ»_S=0.3, Ξ»_C=0.0 (all env vars: VIDEO_ENCODE_REWARD_LAMBDA_*)

Key file: server/reward.py β€” pure function, no I/O, easy to unit-test.


Environment Variables (complete reference)

Video source

Variable Default Notes
VIDEO_ENCODE_VIDEOS_DIR videos Directory to scan for .mp4/.mkv/.mov/.webm
VIDEO_ENCODE_VIDEO_LIST_FILE (unset) If set, overrides directory scan
VIDEO_ENCODE_UPLOAD_MAX_BYTES 2 GiB Max upload size
VIDEO_ENCODE_UPLOAD_ANALYSIS_TIMEOUT_SEC 600 ffmpeg budget for upload analysis

Episode parameters

Variable Default Notes
VIDEO_ENCODE_SEGMENT_SEC 3.0 Reference clip length per step
VIDEO_ENCODE_STEPS_PER_SEGMENT 10 K encodes before timeline advances
VIDEO_ENCODE_FFMPEG_TIMEOUT_SEC 600 Global subprocess timeout

Reward weights & normalization

Variable Default
VIDEO_ENCODE_REWARD_LAMBDA_Q 1.0
VIDEO_ENCODE_REWARD_LAMBDA_T 0.5
VIDEO_ENCODE_REWARD_LAMBDA_S 0.3
VIDEO_ENCODE_REWARD_LAMBDA_C 0.1
VIDEO_ENCODE_REWARD_VMAF_MAX 100
VIDEO_ENCODE_REWARD_TIME_MAX_SEC (unset)
VIDEO_ENCODE_REWARD_BITRATE_MAX_KBPS 20000

Inference

Variable Default Notes
HF_TOKEN / OPENAI_API_KEY β€” HF user token (same value, two names)
API_BASE_URL https://router.huggingface.co/v1 OpenAI-compat endpoint
MODEL_NAME Qwen/Qwen2.5-72B-Instruct Exact HF model id
MAX_STEPS 8 Steps per episode in inference loop
INFERENCE_TEMPERATURE 0.3
MAX_TOKENS 4024
VIDEO_ENCODE_DEFAULT_HF_URL https://keshav142-video-encode.hf.space Default Space URL

Development Commands

# Install deps
uv sync

# Run server locally (port 8000)
uv run server
# or
uvicorn server.app:app --reload --host 0.0.0.0 --port 8000

# Run inference against local server
uv run inference --local

# Run inference against HF Space
export HF_TOKEN=hf_...
uv run inference

# Collect offline dataset (CRF Γ— preset Γ— resolution grid)
uv run python -m video_encode.data_collection --videos-dir videos/ --data-root data/

# Build Docker image
docker build -t video_encode-env:latest -f Dockerfile .

# Deploy to HF Spaces
openenv push

Key Patterns & Conventions

Adding a new per-segment feature

  1. Add a compute_<feature>: bool = False kwarg to analyze_segment_clip() in video_analysis.py
  2. Add the computation inside an if compute_<feature>: block with try/except for graceful failure
  3. Set the new kwarg to True in the analyze_segment_clip(ref_clip, …) call in server/video_encode_environment.py
  4. Document the new key(s) in the VideoEncodeObservation.segment_analysis field description in models.py

Adding a new reward term

  1. Add a normalized_<term>() function in server/reward.py
  2. Add the term to compute_segment_reward() signature and formula
  3. Add a lambda_<term> key in _reward_config_from_env() in video_encode_environment.py
  4. Add the VIDEO_ENCODE_REWARD_LAMBDA_<TERM> env var with a sensible default

Adding a new observation field

  1. Add to VideoEncodeObservation in models.py with default_factory=dict or default=None
  2. Add as a parameter to _observation() in video_encode_environment.py (keyword-only, with default)
  3. Pass it through to VideoEncodeObservation(...) in _observation() body
  4. Populate it in step() and/or reset() as appropriate

Import dual-path pattern

All server-side modules use a try/except import pattern to work both as a package (from ..models import …) and when run directly (from models import …). Always maintain both.


Completed Work

βœ… Wire lambda_c β€” CRF instability penalty

Date: 2026-04-07

  • server/video_encode_environment.py: Added lambda_c to _reward_config_from_env() reading VIDEO_ENCODE_REWARD_LAMBDA_C (default 0.1). In step(), reads prev_crf_avg from self._prev_segment_summary and passes crf=action.crf, prev_crf_avg, lambda_c to compute_segment_reward(). The penalty was fully wired in server/reward.py already.

βœ… Fix time_max_sec calibration (TΜ„ near-zero gradient)

Date: 2026-04-07

  • server/video_encode_environment.py: Removed time_max_sec from _reward_config_from_env(). In step(), computes time_max_sec = 3.0 Γ— seg_len dynamically (or uses VIDEO_ENCODE_REWARD_TIME_MAX_SEC env var if explicitly set as an override). A 0.3 s encode of a 3 s segment now scores TΜ„ β‰ˆ 0.033 (vs β‰ˆ 0.005 before), giving the time term real gradient.

βœ… Per-segment features on extracted clip (segment_analysis)

Date: 2026-04-07

  • video_analysis.py: Added analyze_segment_clip(path, *, timeout, compute_complexity) β€” computes per-segment width/height/fps/bitrate/file_size + EY/h/LY complexity on the already-extracted reference clip. Reuses _run_ffmpeg_luma_complexity_metrics (existing). Complexity capped at 30 s. Docstring names 3 future extension points: compute_scene_cuts, compute_frame_types, compute_quality_baseline.
  • models.py: Added segment_analysis: Dict[str, Any] field to VideoEncodeObservation (placed between whole_video_analysis and the metric fields).
  • server/video_encode_environment.py: Imports analyze_segment_clip; initializes seg_analysis={} before tmpdir; populates after ffprobe_video_size(ref_clip); passes to all 4 post-extraction _observation() calls. Pre-extraction paths get {} via the None default on _observation().

Immediate Next Tasks (Priority Order)

1. Add current_segment_history to observation (remove partial observability)

Files: models.py, server/video_encode_environment.py

The agent sees prev_segment_predictions (last completed segment) but has no record of its own prior steps within the current segment. _segment_step_metrics (already maintained) holds this data. Add current_segment_history: List[Dict[str, Any]] to the observation.

2. Quality term shaping (gamma correction)

Files: server/reward.py

Linear QΜ„ = vmaf/100 underweights the high-quality regime. Replace with QΜ„ = clip(vmaf/vmaf_max) ** (1/Ξ³) where Ξ³=1.5 (concave). Also fix SSIM fallback scale: SSIM clusters 0.85–0.99 so use (ssim βˆ’ SSIM_MIN) / (1 βˆ’ SSIM_MIN) with SSIM_MIN=0.70.

3. Intra-segment Pareto summary in prev_segment_predictions

Files: server/video_encode_environment.py

_summarize_completed_segment() currently only reports means. Add best_vmaf_step and most_efficient_step (highest vmaf/bitrate ratio) so the agent gets supervised-style feedback on which actions were best in the last segment.


Short-term Plans (next 2–4 sessions)

  • Rate-distortion efficiency bonus: Add RD term QΜ„ / (SΜ„ + Ξ΅) as an optional reward component via VIDEO_ENCODE_REWARD_LAMBDA_RD (default 0). Rewards finding the Pareto frontier.

  • Encode speed ratio in observation: Expose realtime_speed_ratio = segment_duration / enc_time in step metadata. Values < 1.0 mean slower-than-realtime (undesirable for live streaming).

  • Quality floor penalty: Binary hard penalty when VMAF < threshold (e.g. 70), separate from the continuous QΜ„ gradient. Controlled by VIDEO_ENCODE_REWARD_VMAF_FLOOR (default 0 = off).

  • Future analyze_segment_clip passes (already reserved in docstring):

    • compute_scene_cuts β€” scene change count via ffprobe select='gt(scene,0.3)'
    • compute_frame_types β€” I/P/B frame ratio via ffprobe -show_frames
    • compute_quality_baseline β€” PSNR/SSIM at CRF-18 as upper-bound reference

Long-term Vision

  • Resolution as action dimension: Add scale_factor: float (0.25–1.0) to VideoEncodeAction for resolution-adaptive encoding (ABR streaming use case).

  • Target bitrate mode (ABR): Add target_bitrate_kbps: int | None β€” when set, use -b:v instead of -crf. Reward proximity to target bitrate.

  • Codec variety: Add codec: str (h264/h265/av1) to the action. Requires codec availability check in the environment at step time.

  • Multi-pass encoding: Optional two-pass encode for better rate control at target bitrates.

  • Offline dataset integration: data_collection.py builds a CRF Γ— preset Γ— resolution grid. Long-term goal: train a quality-prediction model from this data that the agent can query as an "oracle feature" (predicted VMAF before encoding).


Known Issues / Technical Debt

Issue Location Priority
ffprobe_duration_sec and ffprobe_video_size duplicated in segment_utils.py and video_analysis.py Both files Low
max_concurrent_envs=1 hardcoded server/app.py:58 Low
whole_video_analysis deep-copied every step even when unchanged video_encode_environment.py Low
SSIM only computed when VMAF fails; both have complementary diagnostic value video_encode_environment.py Medium