Skip to main content

Professional video processing pipeline with computer vision analysis, 360ยฐ processing, adaptive streaming, and AI-powered transcription (msprites2)

Project description

๐ŸŽฌ Video Processor

A Modern Python Library for Professional Video Processing

Python 3.11+ Built with uv Code style: ruff Type Checked Tests Version

Extracted from the demostar Django application, now a standalone powerhouse for video encoding, thumbnail generation, and sprite creation.

๐Ÿš€ LATEST: v0.4.0 - Complete Multimedia Platform!

๐Ÿ”ญ Computer Vision Analysis โ€ข ๐ŸŽฅ AV1/HEVC/HDR โ€ข ๐Ÿ“ก Adaptive Streaming โ€ข ๐ŸŒ 360ยฐ Video Processing โ€ข โœ… Production Ready

๐Ÿ“š Full Documentation โ€ข ๐Ÿš€ Features โ€ข โšก Quick Start โ€ข ๐Ÿ’ป Examples โ€ข ๐Ÿ”„ Upgrade


๐Ÿ“š Documentation

Complete Documentation Suite Available in docs/

Documentation Description
๐Ÿ“– User Guide Complete getting started guides and feature overviews
๐Ÿ”„ Migration Upgrade instructions and migration guides
๐Ÿ› ๏ธ Development Technical implementation details and architecture
๐Ÿ“‹ Reference API references, roadmaps, and feature lists
๐Ÿ’ป Examples 11 comprehensive examples covering all features

Quick Links


โœจ 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

# 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

# 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

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:

    uv add "procrastinate>=3.5.2,<4.0.0"  # Or keep 2.x support: ">=2.15.1,<4.0.0"
    
  2. Apply database migrations:

    # 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:

    from video_processor.tasks.migration import migrate_database
    
    # Automatic version-aware migration
    success = await migrate_database("postgresql://localhost/mydb")
    
  4. Update worker configuration:

    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

git clone <repository>
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

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

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

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
)

๐Ÿงช Testing

๐ŸŽฏ NEW in v0.3.0: Comprehensive Test Infrastructure

Video Processor now includes a world-class testing framework with 108+ video fixtures and perfect test compatibility!

โšก Quick Testing

# Run all tests
make test

# Unit tests only (fast)
uv run pytest tests/unit/

# Integration tests with Docker
make test-docker

# Test specific categories
uv run pytest -m "smoke"        # Quick smoke tests
uv run pytest -m "edge_cases"   # Edge case scenarios  
uv run pytest -m "codecs"       # Codec compatibility

๐ŸŽฌ Test Video Fixtures

Our comprehensive test suite includes:

  • Edge Cases: Single frame videos, unusual resolutions (16x16, 1920x2), extreme aspect ratios
  • Multiple Codecs: H.264, H.265, VP8, VP9, Theora, MPEG4 with various profiles
  • Audio Variations: Mono/stereo, different sample rates, no audio, audio-only files
  • Visual Patterns: SMPTE bars, RGB test patterns, YUV test, checkerboard patterns
  • Motion Tests: Rotation, camera shake, scene changes, complex motion
  • Stress Tests: High complexity scenes, noise patterns, encoding challenges

๐Ÿ“Š Test Results

โœ… 52 passing tests (0 failures!)
โœ… 108+ test video fixtures  
โœ… Complete Docker integration
โœ… Perfect API compatibility

๐Ÿณ Docker Integration Testing

# Complete integration testing environment
make test-docker

# Test specific services  
make test-db-migration    # Database migration testing
make test-worker         # Procrastinate worker testing
make clean-docker        # Clean up test environment

๐Ÿ”ง Advanced Testing

# Generate/update test video fixtures
uv run python tests/fixtures/test_suite_manager.py --setup

# Validate test suite integrity
uv run python tests/fixtures/test_suite_manager.py --validate

# Generate synthetic videos for edge cases
uv run python tests/fixtures/generate_synthetic_videos.py

# Download open source test videos
uv run python tests/fixtures/download_test_videos.py

๐ŸŽจ Test Categories

Category Description Video Count
smoke Quick validation tests 2 videos
basic Standard functionality 5 videos
codecs Format compatibility 9 videos
edge_cases Boundary conditions 12+ videos
stress Performance testing 2+ videos
full Complete test suite 108+ videos

๐Ÿ’ก Examples

Explore our comprehensive examples in the examples/ directory:

๐Ÿ“ Available Examples

Example Description Features
basic_usage.py ๐ŸŽฏ Simple synchronous processing Configuration, encoding, thumbnails
async_processing.py โšก Background task processing Procrastinate, job queuing, monitoring
custom_config.py ๐Ÿ› ๏ธ Advanced configuration scenarios Quality presets, validation, custom paths
docker_demo.py ๐Ÿณ Complete containerized demo Docker, PostgreSQL, async workers
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:

# 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
# 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
# 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

# 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

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.

@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

# ๐Ÿ“ฆ 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)
========================== 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

# 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 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

๐Ÿ”„ Migration to v0.4.0

Upgrading from Previous Versions

Video Processor v0.4.0 maintains 100% backward compatibility while adding powerful new features:

# Your existing code continues to work unchanged
processor = VideoProcessor(config)
result = await processor.process_video("video.mp4", "./output/")

# But now you get additional features automatically:
if result.is_360_video:
    print(f"360ยฐ projection: {result.video_360.projection_type}")

if result.quality_analysis:
    print(f"Quality score: {result.quality_analysis.overall_quality:.1f}/10")

New Features Available

  • ๐Ÿ”ญ Computer Vision Analysis: Automatic scene detection and quality assessment
  • ๐ŸŽฅ Modern Codecs: AV1, HEVC, and HDR support
  • ๐Ÿ“ก Streaming: HLS and DASH adaptive streaming
  • ๐ŸŒ 360ยฐ Processing: Complete immersive video pipeline

Migration Resources


๐Ÿ™‹โ€โ™€๏ธ Questions? Issues? Ideas?

Found a bug? Open an issue Have a feature request? Start a discussion
Want to contribute? Check out our contribution guide


Built with โค๏ธ for the video processing community

Making professional video encoding accessible to everyone

Project details


Download files

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

Source Distribution

advanced_video_processor-0.6.0.tar.gz (278.2 kB view details)

Uploaded Source

Built Distribution

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

advanced_video_processor-0.6.0-py3-none-any.whl (173.8 kB view details)

Uploaded Python 3

File details

Details for the file advanced_video_processor-0.6.0.tar.gz.

File metadata

  • Download URL: advanced_video_processor-0.6.0.tar.gz
  • Upload date:
  • Size: 278.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.5

File hashes

Hashes for advanced_video_processor-0.6.0.tar.gz
Algorithm Hash digest
SHA256 f4e088985835f3ce4cdc658308ed6089d44385aab2ef99d3cbbb525a970ed5c4
MD5 478545b1989b9ff1a086d29fd73ea37d
BLAKE2b-256 62330e164608059a3dfe92188e4883971597fe564198d8164056c2b61c704185

See more details on using hashes here.

File details

Details for the file advanced_video_processor-0.6.0-py3-none-any.whl.

File metadata

File hashes

Hashes for advanced_video_processor-0.6.0-py3-none-any.whl
Algorithm Hash digest
SHA256 5b1c6c9ecaaecae2e162a989b631a9800772236c2932b8f5ecb0b276c63a808c
MD5 de553aa86bf8662a68776bee9703ba7c
BLAKE2b-256 bf495780dec6421151937f773db618b7bff62093caa196d01c40f528b88bd65c

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page