Skip to main content

Video Helper

🇫🇷 · 🇬🇧

CI License: BSD-3-Clause Python Local-first

Video Helper belongs to a collection of libraries called AI Helpers developed for building Artificial Intelligence.

🌍 AI Helpers

logo

Video Helper is a Python library that provides utility functions for processing video files. It includes features like loading, converting, extracting frames as well as working with subtitle formats.

The Promise

Local-first by design. video-helper runs entirely on your machine. Everything is processed locally with open-source tooling (ffmpeg): your data is never uploaded to a third-party service, no telemetry, no account, no cloud lock-in. You own the whole pipeline. Part of the AI Helpers suite: sovereignty over your data through local-first Open Source.

Documentation

💻 Documentation

🗺️ Landscape

📋 Examples

Features

  • Video validation: is_valid_video_file, extension check plus an ffmpeg.probe round-trip.
  • Conversion: video_converter, re-encode, resample fps, resize (aspect-preserving), strip audio.
  • Frame access: extract_frames (generator with time/index range, stabilization, sampling) and dump_frames (list → video).
  • Temporal crop: extract_video_chunk, video_duration.
  • Pipeline primitives: black_video, compress_video, image_loop_to_video, concat_videos, overlay_image, extract_audio_track, mux_audio_video, burn_subtitles.
  • Subtitles: srt2vtt (with companion CSS), extract_unique_colors.

Installation

Prerequisites: Python 3.10–3.13 and git, ffmpeg, cross-platform:

  • 🍎 macOS (Homebrew): brew install python git ffmpeg
  • 🐧 Ubuntu/Debian: sudo apt update && sudo apt install -y python3 python3-pip git ffmpeg
  • 🪟 Windows (PowerShell): winget install Python.Python.3.12 Git.Git Gyan.FFmpeg

We recommend using Python environments. Check this link if you're unfamiliar with setting one up: 🥸 Tech tips.

From PyPI (recommended)

# Core video utilities (library + argparse CLI)
pip install video-helper

# Optional surfaces and backends
pip install "video-helper[pyav]"      # PyAV frame backend
pip install "video-helper[cli]"       # click-based CLI twin
pip install "video-helper[api]"       # FastAPI HTTP surface

From source (no PyPI)

git clone https://github.com/warith-harchaoui/video-helper.git
cd video-helper
pip install -e .

# Optional surfaces and backends
pip install -e ".[pyav]"
pip install -e ".[cli]"
pip install -e ".[api]"

Usage

For the full catalog of recipes, see 📋 EXAMPLES.md.

Here’s an example of how to use Video Helper to load, convert, and extract frames from a video file:

import video_helper as vh

# Check if the video file is valid
video_file = "example.mp4"
valid = vh.is_valid_video_file(video_file) # True or False

# Get video dimensions and details
details = vh.video_dimensions(video_file)
print(details)
# {'width': 1920, 'height': 1080, 'duration': 10.0, 'frame_rate': 30.0, 'has_sound': True}

# Convert the video file to a different format
output_video = "video_tests/example_converted.mp4"
vh.video_converter(video_file, output_video,
                   frame_rate=30, width=640, without_sound = True)

# The images will never be distorted:
# aspect ratios are kept even for arbitrary width and height thanks to black padding if necessary

# Extract frames from the video

start_instant=5 # seconds
# it corresponds to start_index = start_instant * frame_rate = 5 * 30 = 150th frame

end_instant=10 # seconds
# it corresponds to end_index = end_instant * frame_rate = 10 * 30 = 300th frame

frame_step=5 # take one frame every 5
# which corresponds to 1 frame every 5 / frame_rate = 5 / 30 = 0.17 second

# This means that in the video we take 1 frame every 5 from the 150th to the 300th

# List example
frames = list(
    vh.extract_frames(video_file, start_instant=start_instant, end_instant=end_instant, frame_step=frame_step)
)

# For loop example
for frame in vh.extract_frames(
    video_file,
    start_instant=start_instant,
    end_instant=end_instant,
    frame_step=frame_step):
    pass # Replace with your frame processing logic

# Each frame is a numpy array with shape (height, width, channels)
# with pixel values between 0 and 255.

Another example is about subtitles

Convert SRT subtitles to WebVTT with color preservation:

import video_helper as vh

srt_file = "subtitles.srt"
vtt_file = "subtitles.vtt"
css_file = "subtitles.css"

vh.srt2vtt(srt_file, vtt_file, css_file)

Multi-surface exposure

Every public function is reachable from five surfaces, all systematically wired (nothing is CLI-only or library-only):

Surface Install Entry point
Python library pip install video-helper import video_helper as vh
Argparse CLI (stdlib) pip install video-helper video-helper --help
Click CLI pip install 'video-helper[cli]' video-helper-click --help
FastAPI HTTP + GUI pip install 'video-helper[api]' uvicorn video_helper.api:app
MCP pip install 'video-helper[mcp]' video-helper-mcp (same app + /mcp)

The FastAPI app also serves a minimal browser GUI ("video bench") at GET /gui (and GET / redirects there): drop a clip, pick one operation, run it against the same HTTP endpoints, preview input vs output in an in-browser <video> / <img> player, and download the result. It is a single self-contained page (Tailwind via CDN + vanilla JS, no build step) defined in video_helper/gui.py.

pip install 'video-helper[api]'
uvicorn video_helper.api:app --port 8000
# open http://localhost:8000/gui  (or just http://localhost:8000/)

The Dockerfile at the repo root ships .[api,pyav] by default on python:3.11-slim with ffmpeg and libass: one docker build && docker run -p 8000:8000 gives you the HTTP + GUI surfaces immediately.

For the exhaustive catalogue of what triggers each operation (natural-language phrasings, commands, functions, file types), see TRIGGERS.md.

See GUI.md for the roadmap toward a richer GUI (Recipe Canvas, frame-first comparator, batch drop zone: the minimal /gui bench above is the first step).

API Reference

Function Signature Description
is_valid_video_file (video_file: str) -> bool True iff the file exists, has a known video extension, and ffmpeg.probe finds a video stream.
video_dimensions (video_file: str, http_headers: dict | None = None) -> dict Returns {width, height, duration, frame_rate, has_sound} via ffmpeg.probe. video_file accepts a URL; http_headers forwards to ffprobe for URLs that need them.
video_duration (input_video: str) -> float Duration in seconds (thin wrapper over video_dimensions).
video_converter (input_video, output_video=None, frame_rate=None, width=None, height=None, without_sound=False) Re-encode with optional fps, resize (aspect-preserving black padding when both width and height are given), and audio stripping.
extract_frames (video_path, start_index=None, end_index=None, start_instant=None, end_instant=None, stabilize=False, frame_step=1, frame_interval=None, frame_indices=None, frame_times=None, backend="auto", hwaccel=None, http_headers=None, output_width=None, output_height=None, pad_color="black", destination="numpy", device="cpu", batch_size=None, layout="image") -> Iterator Multi-backend dispatcher (VidGear / PyAV / ffmpeg-pipe). destination: "numpy" (HWC BGR), "torch" (CHW RGB), or "pil" (PIL.Image RGB, size=(W, H)). batch_size+layout yields NHWC/NCHW or THWC/CTHW. frame_indices/frame_times = sparse access via PyAV keyframe-seek. http_headers forwards User-Agent/Referer/Cookie to PyAV / ffmpeg-pipe (needed for yt-dlp-resolved YouTube live, members-only, age-gated). output_width+output_height → exact size with pad_color-padded letterbox/pillarbox; one of them alone → aspect-preserving scale. pad_color="transparent" is not implemented yet: it raises, since it would need 4-channel BGRA/RGBA output, breaking the (H, W, 3) contract on every destination. See SPEED_ANALYSIS.md and EXAMPLES.md.
dump_frames (frames_list, output_movie, fps=30) Write a list of BGR frames (OpenCV convention, same as extract_frames yields) to a video file.
extract_video_chunk (input_video, sample_start, sample_end, output_video, *, copy=False) Temporal crop from sample_start to sample_end (seconds). copy=True stream-copies instead of re-encoding: fast and lossless, but only frame-accurate when every frame of the input is a keyframe.
black_video (duration, width, height, output_video, frame_rate=30) Generate a silent solid-black video. Odd dimensions are rounded down.
compress_video (input_video, output_video=None, *, target_size_mb=97.0, audio_bitrate="128k", vcodec="libx265", min_video_bitrate_kbps=200, overwrite=True) -> str Two-pass ffmpeg encode that solves for the video bitrate needed to hit target_size_mb given the source duration, then encodes at that bitrate. Defaults to HEVC (libx265) tagged hvc1 (ffmpeg's default hev1 tag is not recognized by QuickTime/Apple players) with +faststart. Built for "the compressed file that gets embedded in a web video player", not an archival master.
image_loop_to_video (image, duration, output_video, frame_rate=30, width=None, height=None) Loop a still image into a silent video; optional letterboxing.
concat_videos (input_videos, output_video, reencode=True, frame_rate=None) Concatenate clips end-to-end via the ffmpeg concat demuxer.
overlay_image (input_video, image, output_video, x="0", y="0", scale_width=None) Overlay a PNG/JPG (alpha supported); x / y accept ffmpeg expressions for time-varying motion.
extract_audio_track (input_video, output_audio, sample_rate=44100, channels=2, encoding="pcm_s16le") Pull the audio stream out of a video file.
mux_audio_video (input_video, input_audio, output_video, audio_codec="aac", audio_bitrate="192k", shortest=False) Replace the audio track of a (typically silent) video.
burn_subtitles (input_video, subtitles_file, output_video, force_style=None) Burn .srt / .vtt / .ass / .ssa into the video frames (requires ffmpeg built with libass).
srt2vtt (srt_file_path, vtt_file_path=None, css_file_path=None) Convert SRT → WebVTT, lifting <font color> tags into a sidecar CSS file.
extract_unique_colors (srt_file_path: str) -> Set[str] Set of unique hex colors found in <font color> tags of an SRT.

By default frames are BGR numpy.ndarray of shape (H, W, 3) with pixel values in [0, 255]. See EXAMPLES.md → Destination for the full shape × colorspace table including torch (CHW/NCHW/CTHW RGB) and PIL (RGB, size=(W, H)).

Author

Acknowledgements

Special thanks to Mohamed Chelali and Bachir Zerroug for fruitful discussions.

License

This project is licensed under the BSD-3-Clause License: see the LICENSE file for details.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

video_helper-2.2.0.tar.gz (106.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

video_helper-2.2.0-py3-none-any.whl (88.8 kB view details)

Uploaded Python 3

File details

Details for the file video_helper-2.2.0.tar.gz.

File metadata

  • Download URL: video_helper-2.2.0.tar.gz
  • Upload date:
  • Size: 106.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.13

File hashes

Hashes for video_helper-2.2.0.tar.gz
Algorithm Hash digest
SHA256 b7b5782d4242942fce056846b7516cf444d4aca8e399c51c9df748c27c64ad4c
MD5 cdce171cbca1f5730f38b30d697494d8
BLAKE2b-256 5fb9d82b8eaf42981f55685182aca15faf8c7b85ab386efaf8b5eeff939732a2

See more details on using hashes here.

File details

Details for the file video_helper-2.2.0-py3-none-any.whl.

File metadata

  • Download URL: video_helper-2.2.0-py3-none-any.whl
  • Upload date:
  • Size: 88.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.13

File hashes

Hashes for video_helper-2.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 89353c93d67260d212f24782fa12b3d26e0f6e5b17b62246b6a386641f178c72
MD5 ddeb39277318b89d9b16844b7495d8bc
BLAKE2b-256 4acbd097fe6df2689129cd23ff9dce66322f58f4579796afac694d1161e30022

See more details on using hashes here.

Release history Release notifications | RSS feed

2.4.1

2 files

2.4.0

2 files

2.3.3

2 files

2.3.2

2 files

2.3.1

2 files

This release

2.2.0 This release

2 files

2.1.1

2 files

2.1.0

2 files

2.0.1

2 files

2.0.0

2 files

1.8.1

2 files

1.8.0

2 files

1.7.0

2 files

1.6.5

2 files

1.6.4

2 files

1.6.3

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page