Spaces:
Running
Running
Upload folder using huggingface_hub
Browse filesFiles changed (8)
- .gitattributes+1
- Dockerfile+4-2
- README.md+6-2
- server/app.py+9-17
- server/video_encode_environment.py+35-5
- server/video_upload.pyAdded+105
- videos/README.mdAdded+5
- videos/sample_video.mp4Added+3
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textvideos/sample_video.mp4 filter=lfs diff=lfs merge=lfs -text
83 unmodified lines8485868788899091929383 unmodified linesENV HOST=0.0.0.0ENV PORT=8000# Install curl for healthcheck (ffmpeg may be added here for encode workloads)RUN apt-get update && \apt-get install -y --no-install-recommends curl && \rm -rf /var/lib/apt/lists/*HEALTHCHECK --interval=30s --timeout=3s --start-period=15s --retries=3 \83 unmodified lines84858687888990919293949583 unmodified linesENV HOST=0.0.0.0ENV PORT=8000# HF / Docker: load clips from the repo’s videos/ directory (see videos/README.md)ENV VIDEO_ENCODE_VIDEOS_DIR=/app/env/videos# curl (healthcheck) + ffmpeg/ffprobe (encode + VMAF)RUN apt-get update && \apt-get install -y --no-install-recommends curl ffmpeg && \rm -rf /var/lib/apt/lists/*HEALTHCHECK --interval=30s --timeout=3s --start-period=15s --retries=3 \
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
15 unmodified lines16171819202116 unmodified lines3839404142434445464 unmodified lines5152535455565758598 unmodified lines6869707172737475767778798081828384858687888990919293949515 unmodified lines- GET /state: Get current environment state- GET /schema: Get action/observation schemas- WS /ws: WebSocket endpoint for persistent sessionsUsage:# Development (with auto-reload):16 unmodified linestry:from ..models import VideoEncodeAction, VideoEncodeObservationfrom .video_encode_environment import VideoEncodeEnvironmentexcept ModuleNotFoundError:from models import VideoEncodeAction, VideoEncodeObservationfrom server.video_encode_environment import VideoEncodeEnvironment# Create the app with web interface and README integration4 unmodified linesenv_name="video_encode",max_concurrent_envs=1, # increase this number to allow more concurrent WebSocket sessions)def main(host: str | None = None, port: int | None = None) -> None:"""Entry point for direct execution via uv run or python -m.8 unmodified linesmultiple workers:uvicorn video_encode.server.app:app --workers 4"""import osimport uvicornh = host if host is not None else os.environ.get("HOST", "0.0.0.0")if port is not None:p = portelse:raw = os.environ.get("PORT", "8000")try:p = int(raw)except ValueError:p = 8000uvicorn.run(app, host=h, port=p)if __name__ == "__main__":import argparseparser = argparse.ArgumentParser()parser.add_argument("--host", default=None)parser.add_argument("--port", type=int, default=None)args = parser.parse_args()main(host=args.host, port=args.port)15 unmodified lines161718192021222316 unmodified lines40414243444546474849504 unmodified lines555657585960616263648 unmodified lines73747576777879808182838485868715 unmodified lines- GET /state: Get current environment state- GET /schema: Get action/observation schemas- WS /ws: WebSocket endpoint for persistent sessions- GET /api/videos: List videos under ``VIDEO_ENCODE_VIDEOS_DIR``- POST /api/videos/upload: Multipart upload into that directory (then call ``/reset``)Usage:# Development (with auto-reload):16 unmodified linestry:from ..models import VideoEncodeAction, VideoEncodeObservationfrom .video_encode_environment import VideoEncodeEnvironmentfrom .video_upload import build_video_upload_routerexcept ModuleNotFoundError:from models import VideoEncodeAction, VideoEncodeObservationfrom server.video_encode_environment import VideoEncodeEnvironmentfrom server.video_upload import build_video_upload_router# Create the app with web interface and README integration4 unmodified linesenv_name="video_encode",max_concurrent_envs=1, # increase this number to allow more concurrent WebSocket sessions)app.include_router(build_video_upload_router())def main(host: str = "0.0.0.0", port: int = 8000):"""Entry point for direct execution via uv run or python -m.8 unmodified linesmultiple workers:uvicorn video_encode.server.app:app --workers 4"""import uvicornuvicorn.run(app, host=host, port=port)if __name__ == "__main__":import argparseparser = argparse.ArgumentParser()parser.add_argument("--port", type=int, default=8000)args = parser.parse_args()main(port=args.port)
15 unmodified lines16171819202122130 unmodified lines15315415515615715815916016124 unmodified lines18618718818919019133 unmodified lines2252262272282292302312326 unmodified lines23924024124224324424515 unmodified linesEnvironment variables:- ``VIDEO_ENCODE_VIDEOS_DIR`` — directory of ``.mp4/.mkv/.mov/.webm`` (default ``videos``)- ``VIDEO_ENCODE_VIDEO_LIST_FILE`` — optional text file, one path per line- ``VIDEO_ENCODE_SEGMENT_SEC`` — reference clip length (default ``3.0``)- ``VIDEO_ENCODE_STEPS_PER_SEGMENT`` — K encode attempts per timeline segment before advancing (default ``10``)- ``VIDEO_ENCODE_FFMPEG_TIMEOUT_SEC`` — subprocess timeout (default ``600``)130 unmodified lineselif os.environ.get("VIDEO_ENCODE_VIDEO_LIST_FILE"):lf = Path(os.environ["VIDEO_ENCODE_VIDEO_LIST_FILE"])self._video_paths = load_video_paths(videos_dir=vd if vd.is_dir() else None,list_file=lf if lf is not None and lf.is_file() else None,)self._segment_duration_sec = float(segment_duration_sec24 unmodified linesself._segment_step_metrics: list[dict[str, Any]] = []self._whole_video_analysis_cache: dict[str, dict[str, Any]] = {}def _observation(self,*,33 unmodified linesreward=reward,)def reset(self) -> VideoEncodeObservation:"""New episode; cycles video index; resets timeline and K-step sub-step counter."""self._state = State(episode_id=str(uuid4()), step_count=0)self._reset_count += 1self._segment_start_sec = 0.06 unmodified linesif n == 0:return self._observation(echoed_message=("No videos loaded. Set VIDEO_ENCODE_VIDEOS_DIR or VIDEO_ENCODE_VIDEO_LIST_FILE."),num_videos=0,current_video_index=0,15 unmodified lines1617181920212223130 unmodified lines15415515615715815916016116216316416516616716816924 unmodified lines19419519619719819920020120220320420520620720820921021121221321433 unmodified lines2482492502512522532542552562572582592602616 unmodified lines26826927027127227327427515 unmodified linesEnvironment variables:- ``VIDEO_ENCODE_VIDEOS_DIR`` — directory of ``.mp4/.mkv/.mov/.webm`` (default ``videos``)- ``VIDEO_ENCODE_VIDEO_LIST_FILE`` — optional text file, one path per line (if set and the file exists, directory scan is not used)- ``VIDEO_ENCODE_UPLOAD_MAX_BYTES`` — max size for ``POST /api/videos/upload`` (default ``2GiB``)- ``VIDEO_ENCODE_SEGMENT_SEC`` — reference clip length (default ``3.0``)- ``VIDEO_ENCODE_STEPS_PER_SEGMENT`` — K encode attempts per timeline segment before advancing (default ``10``)- ``VIDEO_ENCODE_FFMPEG_TIMEOUT_SEC`` — subprocess timeout (default ``600``)130 unmodified lineselif os.environ.get("VIDEO_ENCODE_VIDEO_LIST_FILE"):lf = Path(os.environ["VIDEO_ENCODE_VIDEO_LIST_FILE"])self._videos_dir = vd.expanduser().resolve()self._list_file = lf.expanduser().resolve() if lf is not None else Noneself._video_paths = load_video_paths(videos_dir=self._videos_dir if self._videos_dir.is_dir() else None,list_file=(self._list_fileif self._list_file is not None and self._list_file.is_file()else None),)self._segment_duration_sec = float(segment_duration_sec24 unmodified linesself._segment_step_metrics: list[dict[str, Any]] = []self._whole_video_analysis_cache: dict[str, dict[str, Any]] = {}def _reload_video_paths_from_disk(self) -> None:"""Rescan ``VIDEO_ENCODE_VIDEOS_DIR`` / list file so runtime uploads are visible."""self._video_paths = load_video_paths(videos_dir=self._videos_dir if self._videos_dir.is_dir() else None,list_file=(self._list_fileif self._list_file is not None and self._list_file.is_file()else None),)valid = {str(p.resolve()) for p in self._video_paths}self._whole_video_analysis_cache = {k: v for k, v in self._whole_video_analysis_cache.items() if k in valid}def _observation(self,*,33 unmodified linesreward=reward,)def reset(self,seed: int | None = None,episode_id: str | None = None,**kwargs: Any,) -> VideoEncodeObservation:"""New episode; cycles video index; resets timeline and K-step sub-step counter."""self._reload_video_paths_from_disk()self._state = State(episode_id=str(uuid4()), step_count=0)self._reset_count += 1self._segment_start_sec = 0.06 unmodified linesif n == 0:return self._observation(echoed_message=("No videos loaded. Add .mp4/.mkv/.mov/.webm under VIDEO_ENCODE_VIDEOS_DIR ""(default: ./videos) or set VIDEO_ENCODE_VIDEO_LIST_FILE."),num_videos=0,current_video_index=0,
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105# 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.
"""HTTP routes to upload videos into ``VIDEO_ENCODE_VIDEOS_DIR`` (e.g. Hugging Face Space)."""
from __future__ import annotations
import osfrom pathlib import Path
from fastapi import APIRouter, File, HTTPException, UploadFile
try: from ..video_paths import VIDEO_EXTENSIONS, list_video_filesexcept ImportError: from video_paths import VIDEO_EXTENSIONS, list_video_files
def videos_dir() -> Path: return Path(os.environ.get("VIDEO_ENCODE_VIDEOS_DIR", "videos")).expanduser().resolve()
def default_upload_max_bytes() -> int: raw = os.environ.get("VIDEO_ENCODE_UPLOAD_MAX_BYTES", str(2 * 1024 * 1024 * 1024)) try: return max(1, int(raw)) except ValueError: return 2 * 1024 * 1024 * 1024
def _safe_filename(name: str | None) -> str: if not name: raise HTTPException(status_code=400, detail="Filename required") base = Path(name).name if not base or base in (".", "..") or "/" in base or "\\" in base: raise HTTPException(status_code=400, detail="Invalid filename") suf = Path(base).suffix.lower() if suf not in VIDEO_EXTENSIONS: raise HTTPException( status_code=400, detail=f"Unsupported extension {suf!r}; allowed: {', '.join(VIDEO_EXTENSIONS)}", ) return base
def build_video_upload_router() -> APIRouter: router = APIRouter(tags=["videos"])
@router.get("/api/videos") async def list_uploaded_videos() -> dict: """List video files in ``VIDEO_ENCODE_VIDEOS_DIR`` (non-recursive).""" root = videos_dir() if not root.is_dir(): return {"videos_dir": str(root), "exists": False, "files": []} files = [p.name for p in list_video_files(root)] return {"videos_dir": str(root), "exists": True, "count": len(files), "files": files}
@router.post("/api/videos/upload") async def upload_video(file: UploadFile = File(...)) -> dict: """ Save an uploaded file into ``VIDEO_ENCODE_VIDEOS_DIR``.
Call ``reset()`` on the environment afterward (or start a new session) so the new file is included in the episode video list. """ name = _safe_filename(file.filename) root = videos_dir() root.mkdir(parents=True, exist_ok=True)
dest = root / name max_bytes = default_upload_max_bytes() written = 0
try: with dest.open("wb") as out: while True: chunk = await file.read(1024 * 1024) if not chunk: break written += len(chunk) if written > max_bytes: dest.unlink(missing_ok=True) raise HTTPException( status_code=413, detail=f"File exceeds VIDEO_ENCODE_UPLOAD_MAX_BYTES ({max_bytes})", ) out.write(chunk) except HTTPException: raise except Exception as e: dest.unlink(missing_ok=True) raise HTTPException(status_code=500, detail=str(e)) from e
return { "ok": True, "path": str(dest.resolve()), "filename": name, "size_bytes": written, "hint": "Call POST /reset on the environment (or reconnect) to refresh the video list.", }
return router12345# Input videos (Hugging Face Spaces)
Place **`.mp4`**, **`.mkv`**, **`.mov`**, or **`.webm`** files in this directory and push to your Space. The server uses `VIDEO_ENCODE_VIDEOS_DIR` (default: this folder in the container image).
Non-recursive: only files directly in `videos/` are listed.123version https://git-lfs.github.com/spec/v1oid sha256:9a6e293e0dc3beec08fe17327f0ee5b8e56611d8f7766d4662d2de221346f558size 13268927.gitattributes+1
Dockerfile+4-2
README.md+6-2
server/app.py+9-17
server/video_encode_environment.py+35-5
server/video_upload.pyAdded+105
videos/README.mdAdded+5
videos/sample_video.mp4Added+3