Spaces:
Running
Running
Upload folder using huggingface_hub
Browse filesFiles changed (14)
- CLAUDE.mdAdded+346
- Dockerfile+2
- LICENSEAdded+21
- README.md+6-2
- inference.py+90-44
- models.py+18-1
- openenv.yaml+22-7
- openenv_video_encode.egg-info/PKG-INFO+2
- openenv_video_encode.egg-info/SOURCES.txt+4
- segment_utils.py+3
- server/app.py+1-1
- server/graders.pyAdded+70
- server/video_encode_environment.py+57-6
- video_analysis.py+78
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346# Video Encode Environment — CLAUDE.md
Project-level context, architecture notes, development plans, and conventions for AI-assistedwork. Update this file whenever significant context changes.
---
## Project Overview
**What it is:** An RL (reinforcement learning) environment where an agent learns to choose optimallibx264 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 serverscaffolding, `Environment` base class, `Action`/`Observation` types, and the `EnvClient` + Dockerdeployment 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-stepcounter resets.
---
## Action Schema
```pythonVideoEncodeAction: 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
```pythonVideoEncodeObservation: # 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` | — | 0 (disabled) |
**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) | Optional override; default is `3 × segment_duration_sec` || `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
```bash# Install depsuv sync
# Run server locally (port 8000)uv run server# oruvicorn server.app:app --reload --host 0.0.0.0 --port 8000
# Run inference against local serveruv run inference --local
# Run inference against HF Spaceexport 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 imagedocker build -t video_encode-env:latest -f Dockerfile .
# Deploy to HF Spacesopenenv push```
---
## Key Patterns & Conventions
### Adding a new per-segment feature1. 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 failure3. 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 term1. Add a `normalized_<term>()` function in `server/reward.py`2. Add the term to `compute_segment_reward()` signature and formula3. 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 field1. 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()` body4. Populate it in `step()` and/or `reset()` as appropriate
### Import dual-path patternAll 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 ownprior steps *within the current segment*. `_segment_step_metrics` (already maintained) holds thisdata. 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 feedbackon 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 |108 unmodified lines109110111112113114108 unmodified linesffmpeg -version | head -1 && \ffmpeg -filters 2>&1 | grep -q libvmafHEALTHCHECK --interval=30s --timeout=3s --start-period=15s --retries=3 \CMD curl -sf "http://127.0.0.1:${PORT:-8000}/health" || exit 1108 unmodified lines109110111112113114115116108 unmodified linesffmpeg -version | head -1 && \ffmpeg -filters 2>&1 | grep -q libvmafHEALTHCHECK --interval=30s --timeout=3s --start-period=15s --retries=3 \CMD curl -sf "http://127.0.0.1:${PORT:-8000}/health" || exit 1
123456789101112131415161718192021MIT License
Copyright (c) 2026 kabhirajasp-bot
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.115 unmodified lines116117118119120121122123124125126115 unmodified lines- **Health Check** at `/health` - Container health monitoring- **WebSocket** at `/ws` - Persistent session endpoint for low-latency interactions## Environment Details### Action**VideoEncodeAction**: Contains a single field- `message` (str) - The message to echo back### Observation**VideoEncodeObservation**: Contains the echo response and metadata115 unmodified lines116117118119120121122123124125126127128129130115 unmodified lines- **Health Check** at `/health` - Container health monitoring- **WebSocket** at `/ws` - Persistent session endpoint for low-latency interactions### Videos on Hugging Face SpacesCommit input clips under the repo’s **`videos/`** directory (`.mp4`, `.mkv`, `.mov`, `.webm`). The Docker image sets **`VIDEO_ENCODE_VIDEOS_DIR=/app/env/videos`**, so the Space loads those files at startup—no client-side paths required.## Environment Details### Action**VideoEncodeAction**: encoding parameters- `crf`, `preset`, optional `video_index`### Observation**VideoEncodeObservation**: Contains the echo response and metadata
39 unmodified lines40414243444553 unmodified lines99100101102103104105165 unmodified lines2712722732742752762772782792802812822832842852862872882897 unmodified lines29729829930030130230391 unmodified lines39539639739839940040111 unmodified lines41341441541641741841942042142242342442542654 unmodified lines4814824834844854864874881 unmodified line4904914924934944954964974984994 unmodified lines50450550650750850929 unmodified lines53954054154254354454554654754854955055155255355455555612 unmodified lines56957057157257357457575 unmodified lines65165265365465565665765865966066133 unmodified lines6956966976986997007017027037047057067077087097107117127137147157167177188 unmodified lines72772872973073173273373473573673773873974074174274374474574674774874975026 unmodified lines77777877978078178278339 unmodified lines- ``INFERENCE_JSON_OBJECT_MODE`` — Default ``0``. Keep off when using delimiter markers: ``json_object``mode forces a bare JSON reply and **prevents** the ``<<<VIDEO_ENCODE_ACTION_JSON>>>`` lines. Set to ``1``only if you use a different parser (not recommended with current client).STDOUT FORMAT (exactly these line types)- ``[ENV]`` once: how the RL env is reached (Space URL, ``repo_id``, local, or Docker).53 unmodified lines"false","no",)SUCCESS_SCORE_THRESHOLD = float(os.getenv("SUCCESS_SCORE_THRESHOLD", "0.1"))# Normalize score: assume typical |reward| per step ≤ this for rough [0,1] scaling_MAX_REWARD_ABS_PER_STEP = float(os.getenv("VIDEO_ENCODE_SCORE_MAX_ABS_REWARD_PER_STEP", "3.0"))165 unmodified lines) -> None:"""Log where the Video Encode RL server is reached (HF Space URL, repo, local, or Docker)."""if docker_image:print(f"[ENV] mode=docker_image image={docker_image}", flush=True)elif repo_id:print(f"[ENV] mode=hf_repo repo_id={repo_id} (OpenEnv from_env)", flush=True)elif base_url:print(f"[ENV] mode=http url={base_url}", flush=True)else:print("[ENV] mode=unknown", flush=True)def log_user_prompt(step: int, user_prompt: str) -> None:if not _PRINT_USER_PROMPT:returnprint(f"[USER_PROMPT] step={step}\n{user_prompt}\n", flush=True)def log_step(step: int, action: str, reward: float, done: bool, error: Optional[str]) -> None:7 unmodified linesdef log_end(success: bool, steps: int, score: float, rewards: List[float]) -> None:rewards_str = ",".join(f"{r:.2f}" for r in rewards)print(f"[END] success={str(success).lower()} steps={steps} score={score:.3f} rewards={rewards_str}",flush=True,)91 unmodified linesreturn datadef parse_model_output_to_action(text: str, num_videos: int) -> VideoEncodeAction:"""Parse LLM text into a VideoEncodeAction; fall back to safe defaults on failure."""data = _parse_action_dict_from_text(text)if not isinstance(data, dict):11 unmodified linesvideo_index = max(0, min(video_index, num_videos - 1))try:return VideoEncodeAction(crf=crf, preset=preset, video_index=video_index)except ValidationError:return fallback_action(num_videos)def fallback_action(num_videos: int) -> VideoEncodeAction:vi: int | None = 0 if num_videos > 0 else Nonereturn VideoEncodeAction(crf=23, preset="medium", video_index=vi)def _normalize_assistant_text_field(raw: Any) -> str:54 unmodified linesreturn "", ""def _chat_completion_create(client: OpenAI, **kwargs: Any) -> Any:"""Call chat.completions.create. ``json_object`` mode is optional — it conflicts with delimiter markers."""if INFERENCE_JSON_OBJECT_MODE:try:return client.chat.completions.create(1 unmodified lineresponse_format={"type": "json_object"},)except Exception as exc:print(f"[DEBUG] response_format json_object failed ({exc!r}); retrying without it",flush=True,)return client.chat.completions.create(**kwargs)4 unmodified lineslast_reward: float,history: List[str],num_videos: int,) -> VideoEncodeAction:user_prompt = build_user_prompt(step, observation_dict, last_reward, history, max_tokens=MAX_TOKENS29 unmodified lines# "[DEBUG] Stopped at max_tokens — JSON may be truncated. Increase MAX_TOKENS or shorten JSON.",# flush=True,# )if len(text) > 500:print(f"[DEBUG] Model text (head): {text}...", flush=True)else:print(f"[DEBUG] Model text: {text!r}", flush=True)return parse_model_output_to_action(text, num_videos=num_videos)except Exception as exc:print(f"[DEBUG] Model request or parse failed: {exc}", flush=True)print("[DEBUG] Using fallback action: crf=23, preset=medium, video_index=0 ""(or null when no videos). Fix MODEL_NAME/API_BASE_URL/HF_TOKEN or model output.",flush=True,)return fallback_action(num_videos)12 unmodified linesnew_netloc = p.netloc.replace(h, nh, 1)out = urlunparse(p._replace(netloc=new_netloc)).rstrip("/")if out != u.rstrip("/"):print(f"[DEBUG] Normalized HF Space URL (use hyphens, not underscores): {u!r} -> {out!r}", flush=True)return out75 unmodified linesasync def run_inference(args: argparse.Namespace) -> None:if not API_KEY:print("Warning: Set HF_TOKEN (or OPENAI_API_KEY) to your Hugging Face token for ""google/flan-t5-small on router.huggingface.co — requests may fail without it.",file=sys.stderr,)# HF router accepts Bearer token; placeholder only for local smoke without network.client = OpenAI(base_url=API_BASE_URL, api_key=API_KEY or "hf")33 unmodified linesobs = result.observationlast_reward = float(result.reward or 0.0)for step in range(1, max_steps + 1):if getattr(result, "done", False):breakobs_dict = obs.model_dump()action = get_model_action(client,step,obs_dict,last_reward,history,num_videos=obs.num_videos,)action_str = _action_to_log_str(action)result = await env.step(action)obs = result.observationreward = float(result.reward if result.reward is not None else 0.0)done = bool(result.done)err = _observation_error(obs)8 unmodified linesif done:breakif rewards:mean_r = sum(rewards) / len(rewards)# Map roughly into [0,1] using typical scale (tunable via env)score = abs(mean_r) / max(_MAX_REWARD_ABS_PER_STEP, 1e-6)score = min(max(score, 0.0), 1.0)else:score = 0.0success = score >= SUCCESS_SCORE_THRESHOLDexcept Exception as e:print(f"[DEBUG] inference loop error: {e}", flush=True)success = Falsefinally:if env is not None:try:await env.close()except Exception as e:print(f"[DEBUG] env.close() error: {e}", flush=True)log_end(success=success, steps=steps_taken, score=score, rewards=rewards)26 unmodified linestry:asyncio.run(run_inference(args))except ValueError as e:print(f"Error: {e}", file=sys.stderr)return 2return 039 unmodified lines40414243444546474853 unmodified lines102103104105106107108109110111112113114165 unmodified lines2802812822832842852862872882892902912922932942952962972982993003013027 unmodified lines31031131231331431531691 unmodified lines40840941041141241341411 unmodified lines42642742842943043143243343443543643743843954 unmodified lines4944954964974984995005015025035045055065075085095105115125135145151 unmodified line5175185195205215225235245255265274 unmodified lines53253353453553653753829 unmodified lines56856957057157257357457557657757857958058158258358458512 unmodified lines59859960060160260360460575 unmodified lines68168268368468568668768868969069169233 unmodified lines7267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657668 unmodified lines77577677777877978078178278378478578678778878979079179279379479579626 unmodified lines82382482582682782882939 unmodified lines- ``INFERENCE_JSON_OBJECT_MODE`` — Default ``0``. Keep off when using delimiter markers: ``json_object``mode forces a bare JSON reply and **prevents** the ``<<<VIDEO_ENCODE_ACTION_JSON>>>`` lines. Set to ``1``only if you use a different parser (not recommended with current client).- ``INFERENCE_DISABLE_THINKING`` — Default ``1``. When set, the client sends ``enable_thinking: false`` in``extra_body`` (Qwen3 / OpenAI-compatible) so the model prefers a direct reply over long reasoning.Set to ``0`` if your provider rejects unknown fields or you want thinking enabled.STDOUT FORMAT (exactly these line types)- ``[ENV]`` once: how the RL env is reached (Space URL, ``repo_id``, local, or Docker).53 unmodified lines"false","no",)# Qwen3-style APIs: pass enable_thinking=false via extra_body (HF router / vLLM / many OpenAI-compat servers).INFERENCE_DISABLE_THINKING = os.getenv("INFERENCE_DISABLE_THINKING", "1").strip().lower() not in ("0","false","no",)SUCCESS_SCORE_THRESHOLD = float(os.getenv("SUCCESS_SCORE_THRESHOLD", "0.85"))# Normalize score: assume typical |reward| per step ≤ this for rough [0,1] scaling_MAX_REWARD_ABS_PER_STEP = float(os.getenv("VIDEO_ENCODE_SCORE_MAX_ABS_REWARD_PER_STEP", "3.0"))165 unmodified lines) -> None:"""Log where the Video Encode RL server is reached (HF Space URL, repo, local, or Docker)."""if docker_image:# print(f"[ENV] mode=docker_image image={docker_image}", flush=True)passelif repo_id:# print(f"[ENV] mode=hf_repo repo_id={repo_id} (OpenEnv from_env)", flush=True)passelif base_url:# print(f"[ENV] mode=http url={base_url}", flush=True)passelse:# print("[ENV] mode=unknown", flush=True)passdef log_user_prompt(step: int, user_prompt: str) -> None:if not _PRINT_USER_PROMPT:return# print(f"[USER_PROMPT] step={step}\n{user_prompt}\n", flush=True)def log_step(step: int, action: str, reward: float, done: bool, error: Optional[str]) -> None:7 unmodified linesdef log_end(success: bool, steps: int, score: float, rewards: List[float]) -> None:rewards_str = ",".join(f"{r:.2f}" for r in rewards)print(f"[END] success={str(success).lower()} steps={steps} score={score:.2f} rewards={rewards_str}",flush=True,)91 unmodified linesreturn datadef parse_model_output_to_action(text: str, num_videos: int, task_id: str) -> VideoEncodeAction:"""Parse LLM text into a VideoEncodeAction; fall back to safe defaults on failure."""data = _parse_action_dict_from_text(text)if not isinstance(data, dict):11 unmodified linesvideo_index = max(0, min(video_index, num_videos - 1))try:return VideoEncodeAction(crf=crf, preset=preset, video_index=video_index, task_id=task_id)except ValidationError:return fallback_action(num_videos)def fallback_action(num_videos: int) -> VideoEncodeAction:vi: int | None = 0 if num_videos > 0 else Nonereturn VideoEncodeAction(crf=23, preset="medium", video_index=vi, task_id="easy")def _normalize_assistant_text_field(raw: Any) -> str:54 unmodified linesreturn "", ""def _merge_disable_thinking_extra_body(kwargs: dict[str, Any]) -> dict[str, Any]:"""Merge ``enable_thinking: false`` into ``extra_body`` for Qwen3-style routers."""if not INFERENCE_DISABLE_THINKING:return kwargsthinking = {"enable_thinking": False}extra = kwargs.get("extra_body")if isinstance(extra, dict):merged = {**extra, **thinking}else:merged = thinkingreturn {**kwargs, "extra_body": merged}def _chat_completion_create(client: OpenAI, **kwargs: Any) -> Any:"""Call chat.completions.create. ``json_object`` mode is optional — it conflicts with delimiter markers."""kwargs = _merge_disable_thinking_extra_body(kwargs)if INFERENCE_JSON_OBJECT_MODE:try:return client.chat.completions.create(1 unmodified lineresponse_format={"type": "json_object"},)except Exception as exc:# print(# f"[DEBUG] response_format json_object failed ({exc!r}); retrying without it",# flush=True,# )passreturn client.chat.completions.create(**kwargs)4 unmodified lineslast_reward: float,history: List[str],num_videos: int,task_id: int,) -> VideoEncodeAction:user_prompt = build_user_prompt(step, observation_dict, last_reward, history, max_tokens=MAX_TOKENS29 unmodified lines# "[DEBUG] Stopped at max_tokens — JSON may be truncated. Increase MAX_TOKENS or shorten JSON.",# flush=True,# )# if len(text) > 500:# print(f"[DEBUG] Model text (head): {text}...", flush=True)# else:# print(f"[DEBUG] Model text: {text!r}", flush=True)return parse_model_output_to_action(text, num_videos, task_id)except Exception as exc:# print(f"[DEBUG] Model request or parse failed: {exc}", flush=True)# print(# "[DEBUG] Using fallback action: crf=23, preset=medium, video_index=0 "# "(or null when no videos). Fix MODEL_NAME/API_BASE_URL/HF_TOKEN or model output.",# flush=True,# )return fallback_action(num_videos)12 unmodified linesnew_netloc = p.netloc.replace(h, nh, 1)out = urlunparse(p._replace(netloc=new_netloc)).rstrip("/")if out != u.rstrip("/"):pass# print(f"[DEBUG] Normalized HF Space URL (use hyphens, not underscores): {u!r} -> {out!r}", flush=True)return out75 unmodified linesasync def run_inference(args: argparse.Namespace) -> None:if not API_KEY:# print(# "Warning: Set HF_TOKEN (or OPENAI_API_KEY) to your Hugging Face token for "# "google/flan-t5-small on router.huggingface.co — requests may fail without it.",# file=sys.stderr,# )pass# HF router accepts Bearer token; placeholder only for local smoke without network.client = OpenAI(base_url=API_BASE_URL, api_key=API_KEY or "hf")33 unmodified linesobs = result.observationlast_reward = float(result.reward or 0.0)episode_policy = {"easy": [0.0,0.5],"medium": [0.5,0.8],"hard": [0.8,1.0]}for step in range(1, max_steps + 1):percent_idx = step / (max_steps+1)task_id = "easy"for task, pc in episode_policy.items():if pc[0] <= percent_idx <= pc[1]:task_id = taskbreakif getattr(result, "done", False):breakobs_dict = obs.model_dump()# print(obs_dict)action = get_model_action(client,step,obs_dict,last_reward,history,obs.num_videos,task_id)action_str = _action_to_log_str(action)result = await env.step(action)obs = result.observationreward = float(result.reward if result.reward is not None else 0.00001)done = bool(result.done)err = _observation_error(obs)8 unmodified linesif done:breakmean_r = sum(rewards) / len(rewards)# Map roughly into [0,1] using typical scale (tunable via env)score = abs(mean_r)score = min(max(score, 0.0), 1.0)success = Trueexcept Exception as e:# print(f"[DEBUG] inference loop error: {e}", flush=True)success = Falsefinally:if env is not None:try:await env.close()except Exception as e:pass# print(f"[DEBUG] env.close() error: {e}", flush=True)log_end(success=success, steps=steps_taken, score=score, rewards=rewards)26 unmodified linestry:asyncio.run(run_inference(args))except ValueError as e:# print(f"Error: {e}", file=sys.stderr)return 2return 0
10 unmodified lines111213141516174 unmodified lines22232425262735 unmodified lines63646566676810 unmodified linesand ffprobe-based whole-video analysis dicts."""from typing import Any, Dict, Optionalfrom openenv.core.env_server.types import Action, Observationfrom pydantic import Field4 unmodified linescrf: int = Field(23, ge=0, le=51, description="libx264 CRF")preset: str = Field("medium", description="libx264 preset, e.g. fast, medium, slow")video_index: Optional[int] = Field(None,description="Index into the init video list; default uses current episode video from reset",35 unmodified lines"upload time; empty dict if the file was not analyzed in this process."),)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")bitrate_kbps: Optional[float] = Field(default=None, description="Average bitrate of encoded output")10 unmodified lines111213141516174 unmodified lines2223242526272829303135 unmodified lines6768697071727374757677787980818283848510 unmodified linesand ffprobe-based whole-video analysis dicts."""from typing import Any, Dict, Literal, Optionalfrom openenv.core.env_server.types import Action, Observationfrom pydantic import Field4 unmodified linescrf: int = Field(23, ge=0, le=51, description="libx264 CRF")preset: str = Field("medium", description="libx264 preset, e.g. fast, medium, slow")task_id: Literal["easy", "medium", "hard"] = Field("hard",description="Grader level: 'easy' (encode validity), 'medium' (rate-distortion efficiency), 'hard' (full quality-time-bitrate reward)",)video_index: Optional[int] = Field(None,description="Index into the init video list; default uses current episode video from reset",35 unmodified lines"upload time; empty dict if the file was not analyzed in this process."),)segment_analysis: Dict[str, Any] = Field(default_factory=dict,description=("Per-segment features computed on the extracted reference clip for this step. ""Always-present keys (may be None on probe failure): width, height, duration_sec, ""fps, bitrate_kbps, file_size_bytes. ""Complexity keys (when analysis succeeds): ""luma_spatial_texture_complexity_EY (SI), temporal_complexity_h (TI), ""mean_luma_brightness_LY. ""Empty dict when no clip was extracted this step (e.g. reset, end-of-video, ""or pre-extraction error)."),)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")bitrate_kbps: Optional[float] = Field(default=None, description="Average bitrate of encoded output")
5 unmodified lines67891011121314155 unmodified linesport: 8000graders:- id: easybenchmark: video_encode_easy- id: mediumbenchmark: video_encode_medium- id: hardbenchmark: video_encode_hard5 unmodified lines67891011121314151617181920212223242526272829305 unmodified linesport: 8000tasks:- id: task_easydifficulty: easymax_steps: 10grader:type: llmprompt_template: "Score this response 0.0 to 1.0 based on accuracy..."- id: task_mediumdifficulty: mediummax_steps: 15grader:type: llmprompt_template: "Score this response 0.0 to 1.0 based on..."- id: task_harddifficulty: hardmax_steps: 20grader:type: llmprompt_template: "Score this response 0.0 to 1.0 based on..."
2 unmodified lines3456789102 unmodified linesVersion: 0.1.0Summary: Video Encode environment for OpenEnvRequires-Python: >=3.10Requires-Dist: openenv-core[core]>=0.2.2Requires-Dist: openai>=1.0.0Provides-Extra: devRequires-Dist: pytest>=8.0.0; extra == "dev"Requires-Dist: pytest-cov>=4.0.0; extra == "dev"2 unmodified lines34567891011122 unmodified linesVersion: 0.1.0Summary: Video Encode environment for OpenEnvRequires-Python: >=3.10License-File: LICENSERequires-Dist: openenv-core[core]>=0.2.2Requires-Dist: openai>=1.0.0Provides-Extra: devRequires-Dist: pytest>=8.0.0; extra == "dev"Requires-Dist: pytest-cov>=4.0.0; extra == "dev"Dynamic: license-file
12345675 unmodified lines1314151617186 unmodified lines252627282930README.md__init__.pyclient.pydata_collection.pymodels.pypyproject.tomlrun_smoke_test.py5 unmodified lines./data_collection.py./inference.py./models.py./run_smoke_test.py./segment_utils.py./video_analysis.py6 unmodified linesopenenv_video_encode.egg-info/top_level.txtserver/__init__.pyserver/app.pyserver/reward.pyserver/video_encode_environment.pyserver/video_upload.py1234567895 unmodified lines151617181920216 unmodified lines28293031323334LICENSEREADME.md__init__.pyclient.pydata_collection.pyinference.pymodels.pypyproject.tomlrun_smoke_test.py5 unmodified lines./data_collection.py./inference.py./models.py./run_hf_random_client.py./run_smoke_test.py./segment_utils.py./video_analysis.py6 unmodified linesopenenv_video_encode.egg-info/top_level.txtserver/__init__.pyserver/app.pyserver/graders.pyserver/reward.pyserver/video_encode_environment.pyserver/video_upload.py
325 unmodified lines326327328325 unmodified lines"height": h,"file_size_bytes": segment_path.stat().st_size,}325 unmodified lines326327328329330331325 unmodified lines"height": h,"file_size_bytes": segment_path.stat().st_size,}if __name__ == "__main__":vmaf_score("./videos/sample_video.mp4", "./videos/sample_video.mp4", 1000)
87 unmodified lines8889909192939487 unmodified linesport = args.portelse:port = int(os.environ.get("PORT", "8000"))uvicorn.run(app, host=host, port=port)if __name__ == "__main__":87 unmodified lines8889909192939487 unmodified linesport = args.portelse:port = int(os.environ.get("PORT", "8000"))uvicorn.run(app, host=host, port=port, log_level="debug")if __name__ == "__main__":
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970# 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.
"""Per-step grader functions for the Video Encode RL environment.
Each returns a score in [0, 1] based on a single step's measurable outcomes.These are verifiable, Markovian signals suitable for use as shaped training rewards.
easy_step_score — structural validity: encode success + minimum watchable quality medium_step_score — rate-distortion efficiency: quality-per-bit tradeoff"""
from __future__ import annotations
def easy_step_score( vmaf: float | None, encoding_time_sec: float | None, segment_duration_sec: float, encode_aborted: bool, *, vmaf_floor: float = 45.0, time_budget_multiplier: float = 2.0,) -> float: """ Score in [0, 1] for structural validity of one encode step.
Deductions (result clipped to [0, 1]): encode_aborted or vmaf is None → −0.5 (encode did not complete) vmaf < vmaf_floor → −0.3 (video is unwatchable) enc_time > multiplier × seg_len → −0.2 (encode far too slow) """ score = 1.0 if encode_aborted or vmaf is None: score -= 0.5 elif vmaf < vmaf_floor: score -= 0.3 if ( encoding_time_sec is not None and segment_duration_sec > 0 and encoding_time_sec > time_budget_multiplier * segment_duration_sec ): score -= 0.2 return max(0.0, min(1.0, score))
def medium_step_score( vmaf: float | None, bitrate_kbps: float | None, *, bitrate_cap_kbps: float = 2000.0, vmaf_max: float = 100.0,) -> float: """ Score in [0, 1] for rate-distortion efficiency of one encode step.
R_medium = (vmaf / vmaf_max) × (1 − clip(bitrate / bitrate_cap, 0, 1))
High score requires simultaneously high quality AND low bitrate. Returns 0.0 when vmaf or bitrate is unavailable. """ if vmaf is None or bitrate_kbps is None: return 0.0 q = max(0.0, min(1.0, vmaf / vmaf_max)) s = max(0.0, min(1.0, bitrate_kbps / bitrate_cap_kbps)) return q * (1.0 - s)50 unmodified lines5152535455564 unmodified lines616263646566676869704 unmodified lines7576777879808148 unmodified lines1301311321331341351364 unmodified lines14114214314414514614714814980 unmodified lines2302312322332342353 unmodified lines2392402412422432444 unmodified lines249250251252253254177 unmodified lines4324334344354364371 unmodified line43944044144244344422 unmodified lines46746846947047147223 unmodified lines49649749849950050128 unmodified lines5305315325335345352 unmodified lines5385395405415425435441 unmodified line54654754854955055155255355455541 unmodified lines59759859960060160250 unmodified linestry:from ..models import VideoEncodeAction, VideoEncodeObservationfrom .reward import compute_segment_rewardfrom ..segment_utils import (encode_segment,4 unmodified linesssim_score,vmaf_score,)from ..video_analysis import load_whole_video_analysis_for_observationfrom ..video_paths import load_video_pathsexcept ImportError:from models import VideoEncodeAction, VideoEncodeObservationfrom server.reward import compute_segment_rewardfrom segment_utils import (encode_segment,4 unmodified linesssim_score,vmaf_score,)from video_analysis import load_whole_video_analysis_for_observationfrom video_paths import load_video_pathslogger = logging.getLogger(__name__)48 unmodified linesdef _timeout_from_env() -> float | None:raw = os.environ.get("VIDEO_ENCODE_FFMPEG_TIMEOUT_SEC", "600")if raw.strip() == "":return Nonereturn float(raw)4 unmodified lines"lambda_q": float(os.environ.get("VIDEO_ENCODE_REWARD_LAMBDA_Q", "1.0")),"lambda_t": float(os.environ.get("VIDEO_ENCODE_REWARD_LAMBDA_T", "0.5")),"lambda_s": float(os.environ.get("VIDEO_ENCODE_REWARD_LAMBDA_S", "0.3")),"vmaf_max": float(os.environ.get("VIDEO_ENCODE_REWARD_VMAF_MAX", "100")),"time_max_sec": float(os.environ.get("VIDEO_ENCODE_REWARD_TIME_MAX_SEC", "60")),"bitrate_max_kbps": float(os.environ.get("VIDEO_ENCODE_REWARD_BITRATE_MAX_KBPS", "20000")),}80 unmodified linesencode_step_index: int,prev_segment_predictions: dict[str, Any] | None,whole_video_analysis: dict[str, Any],vmaf_score: float | None,ssim_score: float | None,bitrate_kbps: float | None,3 unmodified linesmetadata: dict[str, Any] | None = None,) -> VideoEncodeObservation:pp = copy.deepcopy(prev_segment_predictions)return VideoEncodeObservation(echoed_message=echoed_message,num_videos=num_videos,4 unmodified linessteps_per_segment=self._steps_per_segment,prev_segment_predictions=pp,whole_video_analysis=whole_video_analysis,vmaf_score=vmaf_score,ssim_score=ssim_score,bitrate_kbps=bitrate_kbps,177 unmodified linesstart_sec,seg_len,)with tempfile.TemporaryDirectory() as tmp:tmp_path = Path(tmp)ref_clip = tmp_path / "ref.mp4"1 unmodified linetry:extract_segment(ref_video, start_sec, seg_len, ref_clip, timeout=to)ew, eh = ffprobe_video_size(ref_clip)encode_budget = _encode_time_budget_sec(seg_len, to)try:enc_time = encode_segment(22 unmodified linesencode_step_index=encode_step_this,prev_segment_predictions=prev_for_obs,whole_video_analysis=whole_video_analysis,vmaf_score=None,ssim_score=None,bitrate_kbps=None,23 unmodified linesencode_step_index=encode_step_this,prev_segment_predictions=prev_for_obs,whole_video_analysis=whole_video_analysis,vmaf_score=None,ssim_score=None,bitrate_kbps=None,28 unmodified linesencode_step_index=encode_step_this,prev_segment_predictions=prev_for_obs,whole_video_analysis=whole_video_analysis,vmaf_score=None,ssim_score=None,bitrate_kbps=None,2 unmodified linesmetadata={"error": str(e)},)reward, r_components = compute_segment_reward(vmaf=vmaf,ssim=ssim,encoding_time_sec=enc_time,1 unmodified linelambda_q=self._reward_cfg["lambda_q"],lambda_t=self._reward_cfg["lambda_t"],lambda_s=self._reward_cfg["lambda_s"],vmaf_max=self._reward_cfg["vmaf_max"],time_max_sec=self._reward_cfg["time_max_sec"],bitrate_max_kbps=self._reward_cfg["bitrate_max_kbps"],)logger.debug("step: reward=%s components=%s", reward, r_components)self._segment_step_metrics.append(41 unmodified linesencode_step_index=encode_step_this,prev_segment_predictions=prev_for_obs,whole_video_analysis=whole_video_analysis,vmaf_score=vmaf,ssim_score=ssim,bitrate_kbps=bitrate,50 unmodified lines515253545556574 unmodified lines62636465666768697071724 unmodified lines7778798081828348 unmodified lines1321331341351361371384 unmodified lines14314414514614714814915015115280 unmodified lines2332342352362372382393 unmodified lines2432442452462472482494 unmodified lines254255256257258259260177 unmodified lines4384394404414424434444451 unmodified line44744844945045145245322 unmodified lines47647747847948048148223 unmodified lines50650750850951051151228 unmodified lines5415425435445455465472 unmodified lines5505515525535545555565575585595605615625635645651 unmodified line56756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460541 unmodified lines64764864965065165265350 unmodified linestry:from ..models import VideoEncodeAction, VideoEncodeObservationfrom .graders import easy_step_score, medium_step_scorefrom .reward import compute_segment_rewardfrom ..segment_utils import (encode_segment,4 unmodified linesssim_score,vmaf_score,)from ..video_analysis import analyze_segment_clip, load_whole_video_analysis_for_observationfrom ..video_paths import load_video_pathsexcept ImportError:from models import VideoEncodeAction, VideoEncodeObservationfrom server.graders import easy_step_score, medium_step_scorefrom server.reward import compute_segment_rewardfrom segment_utils import (encode_segment,4 unmodified linesssim_score,vmaf_score,)from video_analysis import analyze_segment_clip, load_whole_video_analysis_for_observationfrom video_paths import load_video_pathslogger = logging.getLogger(__name__)48 unmodified linesdef _timeout_from_env() -> float | None:raw = os.environ.get("VIDEO_ENCODE_FFMPEG_TIMEOUT_SEC", "7000")if raw.strip() == "":return Nonereturn float(raw)4 unmodified lines"lambda_q": float(os.environ.get("VIDEO_ENCODE_REWARD_LAMBDA_Q", "1.0")),"lambda_t": float(os.environ.get("VIDEO_ENCODE_REWARD_LAMBDA_T", "0.5")),"lambda_s": float(os.environ.get("VIDEO_ENCODE_REWARD_LAMBDA_S", "0.3")),"lambda_c": float(os.environ.get("VIDEO_ENCODE_REWARD_LAMBDA_C", "0.1")),"vmaf_max": float(os.environ.get("VIDEO_ENCODE_REWARD_VMAF_MAX", "100")),"bitrate_max_kbps": float(os.environ.get("VIDEO_ENCODE_REWARD_BITRATE_MAX_KBPS", "20000")),"grader_medium_bitrate_cap_kbps": float(os.environ.get("VIDEO_ENCODE_GRADER_MEDIUM_BITRATE_CAP", "2000.0")),}80 unmodified linesencode_step_index: int,prev_segment_predictions: dict[str, Any] | None,whole_video_analysis: dict[str, Any],segment_analysis: dict[str, Any] | None = None,vmaf_score: float | None,ssim_score: float | None,bitrate_kbps: float | None,3 unmodified linesmetadata: dict[str, Any] | None = None,) -> VideoEncodeObservation:pp = copy.deepcopy(prev_segment_predictions)sa = copy.deepcopy(segment_analysis) if segment_analysis is not None else {}return VideoEncodeObservation(echoed_message=echoed_message,num_videos=num_videos,4 unmodified linessteps_per_segment=self._steps_per_segment,prev_segment_predictions=pp,whole_video_analysis=whole_video_analysis,segment_analysis=sa,vmaf_score=vmaf_score,ssim_score=ssim_score,bitrate_kbps=bitrate_kbps,177 unmodified linesstart_sec,seg_len,)# Populated after ref_clip extraction; {} on any pre-extraction failure path.seg_analysis: dict[str, Any] = {}with tempfile.TemporaryDirectory() as tmp:tmp_path = Path(tmp)ref_clip = tmp_path / "ref.mp4"1 unmodified linetry:extract_segment(ref_video, start_sec, seg_len, ref_clip, timeout=to)ew, eh = ffprobe_video_size(ref_clip)seg_analysis = analyze_segment_clip(ref_clip, timeout=to)encode_budget = _encode_time_budget_sec(seg_len, to)try:enc_time = encode_segment(22 unmodified linesencode_step_index=encode_step_this,prev_segment_predictions=prev_for_obs,whole_video_analysis=whole_video_analysis,segment_analysis=seg_analysis,vmaf_score=None,ssim_score=None,bitrate_kbps=None,23 unmodified linesencode_step_index=encode_step_this,prev_segment_predictions=prev_for_obs,whole_video_analysis=whole_video_analysis,segment_analysis=seg_analysis,vmaf_score=None,ssim_score=None,bitrate_kbps=None,28 unmodified linesencode_step_index=encode_step_this,prev_segment_predictions=prev_for_obs,whole_video_analysis=whole_video_analysis,segment_analysis=seg_analysis,vmaf_score=None,ssim_score=None,bitrate_kbps=None,2 unmodified linesmetadata={"error": str(e)},)prev_crf_avg = (self._prev_segment_summary.get("crf_avg")if self._prev_segment_summary is not Noneelse None)# time_max_sec: use explicit env override if set, otherwise 3× the segment duration# so the T̄ term has meaningful gradient for typical short segments._raw_tmax = os.environ.get("VIDEO_ENCODE_REWARD_TIME_MAX_SEC")time_max_sec = float(_raw_tmax) if _raw_tmax else 3.0 * seg_lenhard_reward, r_components = compute_segment_reward(vmaf=vmaf,ssim=ssim,encoding_time_sec=enc_time,1 unmodified linelambda_q=self._reward_cfg["lambda_q"],lambda_t=self._reward_cfg["lambda_t"],lambda_s=self._reward_cfg["lambda_s"],lambda_c=self._reward_cfg["lambda_c"],crf=action.crf,prev_crf_avg=prev_crf_avg,vmaf_max=self._reward_cfg["vmaf_max"],time_max_sec=time_max_sec,bitrate_max_kbps=self._reward_cfg["bitrate_max_kbps"],)g_easy = easy_step_score(vmaf=vmaf,encoding_time_sec=enc_time,segment_duration_sec=seg_len,encode_aborted=False,)g_medium = medium_step_score(vmaf=vmaf,bitrate_kbps=bitrate,bitrate_cap_kbps=self._reward_cfg["grader_medium_bitrate_cap_kbps"],vmaf_max=self._reward_cfg["vmaf_max"],)r_components["easy_score"] = g_easyr_components["medium_score"] = g_mediumr_components["task_id"] = action.task_idif action.task_id == "easy":reward = g_easyelif action.task_id == "medium":reward = g_mediumelse: # "hard"reward = hard_rewardif reward <= 0.0:reward = 0.0001if reward == 1.0:reward = 0.9999logger.debug("step: reward=%s components=%s", reward, r_components)self._segment_step_metrics.append(41 unmodified linesencode_step_index=encode_step_this,prev_segment_predictions=prev_for_obs,whole_video_analysis=whole_video_analysis,segment_analysis=seg_analysis,vmaf_score=vmaf,ssim_score=ssim,bitrate_kbps=bitrate,
326 unmodified lines327328329326 unmodified linesout[MEAN_LUMA_BRIGHTNESS_LY] = Nonereturn out326 unmodified lines327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407326 unmodified linesout[MEAN_LUMA_BRIGHTNESS_LY] = Nonereturn outdef 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 beforeencoding (the CRF-18 ultrafast reference), so the cost is low (~1–2 s fora 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 diskKeys 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 keywordarguments 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"] = wout["height"] = hexcept RuntimeError:out["width"] = Noneout["height"] = Nonetry:out["duration_sec"] = ffprobe_duration_sec(path)except RuntimeError:out["duration_sec"] = Noneout["fps"] = ffprobe_avg_frame_rate(path)try:out["bitrate_kbps"] = ffprobe_bitrate_kbps(path)except RuntimeError:out["bitrate_kbps"] = Nonetry:out["file_size_bytes"] = path.stat().st_sizeexcept OSError:out["file_size_bytes"] = Noneif 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.0try: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] = Noneout[TEMPORAL_COMPLEXITY_H] = Noneout[MEAN_LUMA_BRIGHTNESS_LY] = Nonereturn out
CLAUDE.mdAdded+346
Dockerfile+2
LICENSEAdded+21
README.md+6-2
inference.py+90-44
models.py+18-1
openenv.yaml+22-7
openenv_video_encode.egg-info/PKG-INFO+2
openenv_video_encode.egg-info/SOURCES.txt+4
segment_utils.py+3
server/app.py+1-1
server/graders.pyAdded+70
server/video_encode_environment.py+57-6
video_analysis.py+78