# ๐ŸŽฌ Video Processor **A Modern Python Library for Professional Video Processing** [![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/) [![Built with uv](https://img.shields.io/badge/built%20with-uv-green)](https://github.com/astral-sh/uv) [![Code style: ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff) [![Type Checked](https://img.shields.io/badge/type%20checked-mypy-blue)](http://mypy-lang.org/) [![Tests](https://img.shields.io/badge/tests-pytest-yellow)](https://pytest.org/) *Extracted from the demostar Django application, now a standalone powerhouse for video encoding, thumbnail generation, and sprite creation.* [Features](#-features) โ€ข [Installation](#-installation) โ€ข [Quick Start](#-quick-start) โ€ข [Examples](#-examples) โ€ข [API Reference](#-api-reference)
--- ## โœจ Features
### ๐ŸŽฅ **Video Encoding** - **Multi-format support**: MP4 (H.264), WebM (VP9), OGV (Theora) - **Two-pass encoding** for optimal quality - **Professional presets**: Low, Medium, High, Ultra - **Customizable bitrates** and quality settings ### ๐Ÿ–ผ๏ธ **Thumbnails & Sprites** - **Smart thumbnail extraction** at any timestamp - **Seekbar sprite sheets** with WebVTT files - **Configurable intervals** and dimensions - **Mobile-optimized** output options
### โšก **Background Processing** - **Procrastinate integration** for async tasks - **PostgreSQL job queue** management - **Scalable worker architecture** - **Progress tracking** and error handling ### ๐Ÿ› ๏ธ **Modern Development** - **Type-safe** with full type hints - **Pydantic V2** configuration validation - **uv** for lightning-fast dependency management - **ruff** for code quality and formatting
### ๐ŸŒ **360ยฐ Video Support** *(Optional)* - **Spherical video detection** and metadata extraction - **Projection conversions** (equirectangular, cubemap, stereographic) - **360ยฐ thumbnail generation** with multiple viewing angles - **Spatial audio processing** for immersive experiences
--- ## ๐Ÿ“ฆ Installation ### Quick Install ```bash # Basic installation (standard video processing) uv add video-processor # With 360ยฐ video support uv add "video-processor[video-360]" # With spatial audio processing uv add "video-processor[spatial-audio]" # Complete 360ยฐ feature set uv add "video-processor[video-360-full]" # Or using pip pip install video-processor pip install "video-processor[video-360-full]" ``` ### Optional Features #### ๐ŸŒ 360ยฐ Video Processing For immersive video processing capabilities: - **`video-360`**: Core 360ยฐ video processing (py360convert, opencv, numpy, scipy) - **`spatial-audio`**: Spatial audio processing (librosa, soundfile) - **`metadata-360`**: Enhanced 360ยฐ metadata extraction (exifread) - **`video-360-full`**: Complete 360ยฐ package (includes all above) #### ๐Ÿ“ฆ Dependency Details ```bash # Core 360ยฐ processing uv add "video-processor[video-360]" # Includes: py360convert, opencv-python, numpy, scipy # Spatial audio support uv add "video-processor[spatial-audio]" # Includes: librosa, soundfile # Complete 360ยฐ experience uv add "video-processor[video-360-full]" # Includes: All 360ยฐ dependencies + exifread ``` ### โšก Procrastinate Migration (2.x โ†’ 3.x) This library supports both **Procrastinate 2.x** and **3.x** for smooth migration: #### ๐Ÿ”„ Automatic Version Detection ```python from video_processor.tasks.compat import get_version_info, IS_PROCRASTINATE_3_PLUS version_info = get_version_info() print(f"Using Procrastinate {version_info['procrastinate_version']}") print(f"Features available: {list(version_info['features'].keys())}") # Version-aware setup if IS_PROCRASTINATE_3_PLUS: # Use 3.x features like improved performance, graceful shutdown pass ``` #### ๐Ÿ“‹ Migration Steps 1. **Install compatible version**: ```bash uv add "procrastinate>=3.5.2,<4.0.0" # Or keep 2.x support: ">=2.15.1,<4.0.0" ``` 2. **Apply database migrations**: ```bash # Procrastinate 3.x (two-step process) procrastinate schema --apply --mode=pre # Before deploying # Deploy new code procrastinate schema --apply --mode=post # After deploying # Procrastinate 2.x (single step) procrastinate schema --apply ``` 3. **Use migration helper**: ```python from video_processor.tasks.migration import migrate_database # Automatic version-aware migration success = await migrate_database("postgresql://localhost/mydb") ``` 4. **Update worker configuration**: ```python from video_processor.tasks import get_worker_kwargs # Automatically normalizes options for your version worker_options = get_worker_kwargs( concurrency=4, timeout=5, # Maps to fetch_job_polling_interval in 3.x remove_error=True, # Maps to remove_failed in 3.x ) ``` #### ๐Ÿ†• Procrastinate 3.x Benefits - **Better performance** with improved job fetching - **Graceful shutdown** with `shutdown_graceful_timeout` - **Enhanced error handling** and job cancellation - **Schema compatibility** improvements (3.5.2+) ### Development Setup ```bash git clone cd video_processor # Install with all development dependencies uv sync --dev # Install with dev + 360ยฐ features uv sync --dev --extra video-360-full # Verify installation uv run pytest ``` --- ## ๐Ÿš€ Quick Start ### Basic Video Processing ```python from pathlib import Path from video_processor import VideoProcessor, ProcessorConfig # ๐Ÿ“‹ Configure your processor config = ProcessorConfig( base_path=Path("/tmp/video_output"), output_formats=["mp4", "webm"], quality_preset="high" # ๐ŸŽฏ Professional quality ) # ๐ŸŽฌ Initialize and process processor = VideoProcessor(config) result = processor.process_video( input_path="input_video.mp4", output_dir="outputs" ) # ๐Ÿ“Š Results print(f"๐ŸŽฅ Video ID: {result.video_id}") print(f"๐Ÿ“ Formats: {list(result.encoded_files.keys())}") print(f"๐Ÿ–ผ๏ธ Thumbnail: {result.thumbnail_file}") print(f"๐ŸŽž๏ธ Sprites: {result.sprite_files}") ``` ### Async Background Processing ```python import asyncio from video_processor.tasks import setup_procrastinate async def process_in_background(): # ๐Ÿ—„๏ธ Connect to PostgreSQL app = setup_procrastinate("postgresql://user:pass@localhost/db") # ๐Ÿ“ค Submit job job = await app.tasks.process_video_async.defer_async( input_path="/path/to/video.mp4", output_dir="/path/to/output", config_dict={"quality_preset": "ultra"} ) print(f"โœ… Job queued: {job.id}") asyncio.run(process_in_background()) ``` --- ## โš™๏ธ Configuration ### Quality Presets Comparison
| ๐ŸŽฏ Preset | ๐Ÿ“บ Video Bitrate | ๐Ÿ”Š Audio Bitrate | ๐ŸŽจ CRF | ๐Ÿ’ก Best For | |-----------|------------------|------------------|---------|-------------| | **Low** | 1,000k | 128k | 28 | ๐Ÿ“ฑ Mobile, limited bandwidth | | **Medium** | 2,500k | 192k | 23 | ๐ŸŒ Standard web delivery | | **High** | 5,000k | 256k | 18 | ๐ŸŽฌ High-quality streaming | | **Ultra** | 10,000k | 320k | 15 | ๐Ÿ›๏ธ Archive, professional use |
### Advanced Configuration ```python from video_processor import ProcessorConfig from pathlib import Path config = ProcessorConfig( # ๐Ÿ“‚ Storage & Paths base_path=Path("/media/videos"), storage_backend="local", # ๐Ÿ”ฎ S3 coming soon! # ๐ŸŽฅ Video Settings output_formats=["mp4", "webm", "ogv"], quality_preset="ultra", # ๐Ÿ–ผ๏ธ Thumbnails & Sprites thumbnail_timestamp=30, # ๐Ÿ“ 30 seconds in sprite_interval=5.0, # ๐ŸŽž๏ธ Every 5 seconds # ๐Ÿ› ๏ธ System ffmpeg_path="/usr/local/bin/ffmpeg" # ๐Ÿ”ง Custom FFmpeg ) ``` --- ## ๐Ÿ’ก Examples Explore our comprehensive examples in the [`examples/`](examples/) directory: ### ๐Ÿ“ Available Examples | Example | Description | Features | |---------|-------------|-----------| | [`basic_usage.py`](examples/basic_usage.py) | ๐ŸŽฏ Simple synchronous processing | Configuration, encoding, thumbnails | | [`async_processing.py`](examples/async_processing.py) | โšก Background task processing | Procrastinate, job queuing, monitoring | | [`custom_config.py`](examples/custom_config.py) | ๐Ÿ› ๏ธ Advanced configuration scenarios | Quality presets, validation, custom paths | | [`docker_demo.py`](examples/docker_demo.py) | ๐Ÿณ Complete containerized demo | Docker, PostgreSQL, async workers | | [`web_demo.py`](examples/web_demo.py) | ๐ŸŒ Flask web interface | Browser-based processing, job submission | ### ๐Ÿณ Docker Quick Start Get up and running in seconds with our complete Docker environment: ```bash # Start all services (PostgreSQL, Redis, app, workers) docker-compose up -d # View logs from the demo application docker-compose logs -f app # Access web demo at http://localhost:8080 docker-compose up demo # Run tests in Docker docker-compose run test # Clean up docker-compose down -v ``` **Services included:** - ๐Ÿ—„๏ธ **PostgreSQL** - Database with Procrastinate job queue - ๐ŸŽฌ **App** - Main video processor demo - โšก **Worker** - Background job processor - ๐Ÿงช **Test** - Automated testing environment - ๐ŸŒ **Demo** - Web interface for browser-based testing ### ๐ŸŽฌ Real-World Usage Patterns
๐Ÿข Production Video Pipeline ```python # Multi-format encoding for video platform config = ProcessorConfig( base_path=Path("/var/media/uploads"), output_formats=["mp4", "webm"], # Cross-browser support quality_preset="high", sprite_interval=10.0 # Balanced performance ) processor = VideoProcessor(config) result = processor.process_video(user_upload, output_dir) # Generate multiple qualities for quality in ["medium", "high"]: config.quality_preset = quality processor = VideoProcessor(config) # Process to different quality folders... ```
๐Ÿ“ฑ Mobile-Optimized Processing ```python # Lightweight encoding for mobile delivery mobile_config = ProcessorConfig( base_path=Path("/tmp/mobile_videos"), output_formats=["mp4"], # Mobile-friendly format quality_preset="low", # Reduced bandwidth sprite_interval=15.0 # Fewer sprites ) ```
--- ## ๐Ÿ“š API Reference ### ๐ŸŽฌ VideoProcessor The main orchestrator for all video processing operations. #### ๐Ÿ”ง Methods ```python # Process video to all configured formats result = processor.process_video( input_path: Path | str, output_dir: Path | str | None = None, video_id: str | None = None ) -> VideoProcessingResult # Encode to specific format output_path = processor.encode_video( input_path: Path, output_dir: Path, format_name: str, video_id: str ) -> Path # Generate thumbnail at timestamp thumbnail = processor.generate_thumbnail( video_path: Path, output_dir: Path, timestamp: int, video_id: str ) -> Path # Create sprite sheet and WebVTT sprites = processor.generate_sprites( video_path: Path, output_dir: Path, video_id: str ) -> tuple[Path, Path] ``` ### โš™๏ธ ProcessorConfig Type-safe configuration with automatic validation. #### ๐Ÿ“‹ Essential Fields ```python class ProcessorConfig: base_path: Path # ๐Ÿ“‚ Base directory output_formats: list[str] # ๐ŸŽฅ Video formats quality_preset: str # ๐ŸŽฏ Quality level storage_backend: str # ๐Ÿ’พ Storage type ffmpeg_path: str # ๐Ÿ› ๏ธ FFmpeg binary thumbnail_timestamp: int # ๐Ÿ–ผ๏ธ Thumbnail position sprite_interval: float # ๐ŸŽž๏ธ Sprite frequency ``` ### ๐Ÿ“Š VideoProcessingResult Comprehensive result object with all output information. ```python @dataclass class VideoProcessingResult: video_id: str # ๐Ÿ†” Unique identifier encoded_files: dict[str, Path] # ๐Ÿ“ Format โ†’ file mapping thumbnail_file: Path | None # ๐Ÿ–ผ๏ธ Thumbnail image sprite_files: tuple[Path, Path] | None # ๐ŸŽž๏ธ Sprite + WebVTT metadata: VideoMetadata # ๐Ÿ“Š Video properties ``` --- ## ๐Ÿงช Development ### ๐Ÿ› ๏ธ Development Commands ```bash # ๐Ÿ“ฆ Install dependencies uv sync # ๐Ÿงช Run test suite uv run pytest -v # ๐Ÿ“Š Test coverage uv run pytest --cov=video_processor # โœจ Code formatting uv run ruff format . # ๐Ÿ” Linting uv run ruff check . # ๐ŸŽฏ Type checking uv run mypy src/ ``` ### ๐Ÿ“ˆ Test Coverage Our comprehensive test suite covers: - โœ… **Configuration** validation and type checking - โœ… **Path utilities** and file operations - โœ… **FFmpeg integration** and error handling - โœ… **Video metadata** extraction - โœ… **Background task** processing - โœ… **Procrastinate compatibility** (2.x/3.x versions) - โœ… **Database migrations** with version detection - โœ… **Worker configuration** and option mapping - โœ… **360ยฐ video processing** (when dependencies available) ```bash ========================== test session starts ========================== tests/test_config.py โœ…โœ…โœ…โœ…โœ… [15%] tests/test_utils.py โœ…โœ…โœ…โœ…โœ…โœ…โœ…โœ… [30%] tests/test_procrastinate_compat.py โœ…โœ…โœ…โœ…โœ…โœ…โœ…โœ…โœ…โœ…โœ…โœ…โœ…โœ…โœ…โœ…โœ… [85%] tests/test_procrastinate_migration.py โœ…โœ…โœ…โœ…โœ…โœ…โœ…โœ…โœ…โœ…โœ…โœ…โœ… [100%] ======================== 43 passed in 0.52s ======================== ``` --- ## ๐Ÿ“ฆ Dependencies ### ๐ŸŽฏ Core Dependencies | Package | Purpose | Why We Use It | |---------|---------|---------------| | `ffmpeg-python` | FFmpeg integration | ๐ŸŽฌ Professional video processing | | `msprites2` | Sprite generation | ๐ŸŽž๏ธ Seekbar thumbnails (forked for fixes) | | `procrastinate` | Background tasks | โšก Scalable async processing | | `pydantic` | Configuration | โš™๏ธ Type-safe settings validation | | `pillow` | Image processing | ๐Ÿ–ผ๏ธ Thumbnail manipulation | ### ๐Ÿ”ง Development Tools | Tool | Purpose | Benefits | |------|---------|----------| | `uv` | Package management | ๐Ÿš€ Ultra-fast dependency resolution | | `ruff` | Linting & formatting | โšก Lightning-fast code quality | | `pytest` | Testing framework | ๐Ÿงช Reliable test execution | | `mypy` | Type checking | ๐ŸŽฏ Static type analysis | | `coverage` | Test coverage | ๐Ÿ“Š Quality assurance | --- ## ๐ŸŒŸ Why Video Processor?
### ๐Ÿ†š Comparison with Alternatives | Feature | Video Processor | FFmpeg CLI | moviepy | OpenCV | |---------|----------------|------------|---------|--------| | **Two-pass encoding** | โœ… | โœ… | โŒ | โŒ | | **Multiple formats** | โœ… | โœ… | โœ… | โŒ | | **Background processing** | โœ… | โŒ | โŒ | โŒ | | **Type safety** | โœ… | โŒ | โŒ | โŒ | | **Sprite generation** | โœ… | โŒ | โŒ | โŒ | | **Modern Python** | โœ… | N/A | โŒ | โŒ |
--- ## ๐Ÿ“‹ Requirements ### ๐Ÿ–ฅ๏ธ System Requirements - **Python 3.11+** - Modern Python features - **FFmpeg** - Video processing engine - **PostgreSQL** - Background job processing (optional) ### ๐Ÿง Installation Commands ```bash # Ubuntu/Debian sudo apt install ffmpeg postgresql-client # macOS brew install ffmpeg postgresql # Arch Linux sudo pacman -S ffmpeg postgresql ``` --- ## ๐Ÿค Contributing We welcome contributions! Here's how to get started: ### ๐Ÿš€ Quick Contribution Guide 1. **๐Ÿด Fork** the repository 2. **๐ŸŒฟ Create** a feature branch (`git checkout -b feature/amazing-feature`) 3. **๐Ÿ“ Make** your changes with tests 4. **๐Ÿงช Test** everything (`uv run pytest`) 5. **โœจ Format** code (`uv run ruff format .`) 6. **๐Ÿ“ค Submit** a pull request ### ๐ŸŽฏ Areas We'd Love Help With - ๐ŸŒ **S3 storage backend** implementation - ๐ŸŽž๏ธ **Additional video formats** (AV1, HEVC) - ๐Ÿ“Š **Progress tracking** and monitoring - ๐Ÿณ **Docker integration** examples - ๐Ÿ“– **Documentation** improvements --- ## ๐Ÿ“œ License This project is licensed under the **MIT License** - see the [LICENSE](LICENSE) file for details. --- ## ๐ŸŽ‰ Changelog ### ๐Ÿš€ v0.2.0 - Procrastinate 3.x Migration & Docker Support - ๐Ÿ”„ **Procrastinate 3.x compatibility** with backward support for 2.x - ๐ŸŽฏ **Automatic version detection** and feature flagging - ๐Ÿ“‹ **Database migration utilities** with pre/post migration support - ๐Ÿณ **Complete Docker environment** with multi-service orchestration - ๐ŸŒ **Web demo interface** with Flask-based UI - โšก **Worker compatibility layer** with unified CLI - ๐Ÿงช **30+ comprehensive tests** covering all compatibility scenarios - ๐Ÿ“Š **uv caching optimization** following Docker best practices ### ๐ŸŒŸ v0.1.0 - Initial Release - โœจ **Multi-format encoding**: MP4, WebM, OGV support - ๐Ÿ–ผ๏ธ **Thumbnail generation** with customizable timestamps - ๐ŸŽž๏ธ **Sprite sheet creation** with WebVTT files - โšก **Background processing** with Procrastinate integration - โš™๏ธ **Type-safe configuration** with Pydantic V2 - ๐Ÿ› ๏ธ **Modern tooling**: uv, ruff, pytest integration - ๐Ÿ“š **Comprehensive documentation** and examples ---
### ๐Ÿ™‹โ€โ™€๏ธ Questions? Issues? Ideas? **Found a bug?** [Open an issue](https://github.com/your-repo/issues/new/choose) **Have a feature request?** [Start a discussion](https://github.com/your-repo/discussions) **Want to contribute?** Check out our [contribution guide](#-contributing) --- **Built with โค๏ธ for the video processing community** *Making professional video encoding accessible to everyone*