Skip to content

About

Multitrack NLE video editor & AI Arabic/Darija caption studio featuring Whisper + Gemini alignment, local RVM ONNX matting, GSUB RTL rendering, and 1:1 FFmpeg export parity.

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

MedSub Studio

Multitrack Non-Linear Video Editor (NLE) & AI Arabic/Darija Short-Form Caption Studio

MedSub Studio (MedSub-studio/) is a full-stack video editing and automated captioning studio built for short-form creators (9:16 Reels/Shorts/TikTok, 16:9 widescreen, 1:1 square, and custom sequences). It combines a Premiere-inspired multitrack browser/Electron NLE with a Python FastAPI, FFmpeg, OpenCV, and ONNX Runtime backend for Arabic RTL/GSUB subtitle rendering, hybrid AI transcription & translation, local neural background matting, green-screen chroma keying, and EBU R128 audio mastering.


Problem Statement & Motivation

Producing high-retention short-form videos in Algerian Darija, Modern Standard Arabic (ar_fusha), French, and English typically requires chaining multiple disconnected tools:

  • Whisper transcription tools struggle with Darija/French/English code-switching.
  • Standard video editors often break Arabic contextual shaping (GSUB) and mixed-direction (BiDi) word-level highlights.
  • Background replacement, face-tracked punch-in zoom, silence jump-cuts, and multitrack export parity usually require heavy desktop suites.

MedSub Studio unifies these workflows into a single local-first studio with 1:1 mathematical parity between live browser preview and native FFmpeg export.


Key Features

1. Multitrack NLE Timeline & Editing Engine

  • Integer-Frame Unified Sequence Model: Frame-accurate timeline (SequenceConfig with authoritative sequence FPS 24–120, zero per-clip FPS drift) across Video (V1, V2, V3+), Audio (A1, A2+), and Subtitle (S1) tracks.
  • Professional Editing Tools: Universal Razor/Split (C), Sync-Locked Ripple Delete (Shift+Del), non-destructive Trim & Roll edits, Slip & Slide modes, Clip Linking (Ctrl+L), Grouping, Timeline Markers (M), Magnetic Snapping guides, and a 50-step per-sequence Undo/Redo stack.
  • Multi-Sequence Tabs & Track Controls: Independent sequence tabs (9:16, 16:9, 1:1, custom) with Track Lock, Visibility (Eye), Mute, Solo, Track Targeting, Sync Lock, resizable track heights, and virtualized multi-LOD SVG audio waveforms & filmstrip thumbnails.

2. Preview-to-Export Layout Parity (NormalizedSequenceLayout v1.0.0)

  • Shared layout specification (shared/specs/layout_spec_v1.json) implemented identically in TypeScript (normalizedLayout.ts) and Python (normalized_layout.py).
  • Supports fill, fit, fit_blur, stretch, and custom background framing with pan, scale, rotation, and crop—verified by deterministic golden layout vectors and OpenCV PSNR parity checks (> 32 dB).

3. Hybrid AI Transcription, Translation & Arabic RTL Rendering

  • Dual-Stage ASR + LLM Alignment:
    • Step 1 (Word Timestamps): Groq whisper-large-v3 API with automatic local faster-whisper fallback when GROQ_API_KEY is not configured.
    • Step 2 (Multimodal Correction & Translation): Google Gemini (gemini-2.5-flash) aligns audio + raw word windows for darija_mixed, ar_fusha, fr, and en.
  • Pure-Python Arabic GSUB Shaping: Builds presentation-form patched fonts (_shaped/*.pf1) via fontTools, arabic-reshaper, and python-bidi without requiring libraqm or FriBiDi system libraries.
  • Kinetic Word-by-Word Highlighting: Animated active-word boxes, outlines, shadows, custom .ttf/.otf font uploads, and transparent qtrle .mov or green-screen .mp4 exports.

4. Local AI Matting (RVM ONNX) & Green-Screen Background Studio

  • Offline Neural Background Removal: Uses Robust Video Matting (rvm_mobilenetv3_fp32.onnx) via ONNX Runtime (CUDAExecutionProvider -> DmlExecutionProvider -> CPUExecutionProvider) with SHA-256 cached grayscale alpha mattes, live WebGL/Canvas preview (LiveChromaCanvas), and adjustable edge refine/feather sliders.
  • 6-Stage FFmpeg Chroma Key: Multi-patch green/blue backdrop detection, spill suppression, and edge decontamination.
  • Background Studio & AI Scene Matching: Curated built-in studio/outdoor/cinematic backdrops, custom image & video (.mp4/.mov/.webm) backgrounds, color grading/blur/vignette controls, and Gemini-assisted scene matching (scene_matcher.py).

5. Smart Cut, Face-Tracked Camera Rig & Audio Mastering

  • Smart Silence Jump-Cut: FFmpeg silence detection with EDL cue remapping (cut_service.py).
  • 10Hz Face-Tracked Camera Rig: Lightweight YCrCb skin-tone + spatial-prior trajectory tracker (camera_rig.py) for smooth counter-panning and dynamic punch-in zoom.
  • 48kHz Audio & SFX Pipeline: Synthesized peak-aligned sound effects (whoosh, pop, cash, error, click), multitrack FFmpeg adelay/atrim mixing, and EBU R128 loudness mastering (-14 LUFS).

Architecture & Workflow

flowchart LR
    subgraph Client["Frontend (React 19 + Vite + Zustand / Electron)"]
        UI["NLE Timeline & PreviewMonitor"]
        Stores["sequenceStore / timelineStore / historyStore"]
        LayoutTS["normalizedLayout.ts (v1.0.0)"]
        Chroma["LiveChromaCanvas"]
        UI --> Stores
        Stores --> LayoutTS
        Stores --> Chroma
    end

    subgraph API["Backend (FastAPI + Uvicorn)"]
        Main["app/main.py & routers/media.py"]
        Cache["cache_service.py (SHA-256 Disk Cache)"]
        ASR["audio_transcriber.py (Groq / faster-whisper + Gemini)"]
        Matte["ai_matte_service.py (RVM ONNX) & matting_engine.py"]
        BG["background_engine.py & scene_matcher.py"]
        Pipeline["video_pipeline.py + frame_renderer.py + sfx_mixer.py"]
        LayoutPY["normalized_layout.py (v1.0.0)"]
    end

    subgraph External["Local Engines & Optional Cloud APIs"]
        FFmpeg["FFmpeg (System or imageio-ffmpeg)"]
        ONNX["ONNX Runtime (CUDA / DirectML / CPU)"]
        Cloud["Groq / Gemini / Unsplash (Optional)"]
    end

    UI -- "REST / Range Streaming" --> Main
    Main --> Cache
    Main --> ASR
    Main --> Matte
    Main --> BG
    Main --> Pipeline
    Pipeline --> LayoutPY
    Matte --> ONNX
    Pipeline --> FFmpeg
    Cache --> FFmpeg
    ASR -.-> Cloud
    BG -.-> Cloud
Loading

Tech Stack

Layer Technologies
Frontend React 19, TypeScript 5.7, Vite 8, Tailwind CSS v4, Zustand 5, Electron 45 (optional desktop shell)
Backend Python 3.12 (3.11+ Docker), FastAPI, Uvicorn, Pydantic v2
Video, Vision & Audio FFmpeg (imageio-ffmpeg or system ffmpeg), OpenCV (opencv-python-headless), Pillow, NumPy, SciPy, ONNX Runtime (onnxruntime-directml on Windows, onnxruntime on Linux/macOS)
Arabic Typography arabic-reshaper, python-bidi, fontTools
AI & Stock Media groq, google-genai, faster-whisper, httpx, requests (Unsplash / Pixabay / Pexels / Coverr / Wikimedia / Openverse / Internet Archive)
Testing Vitest, Playwright (Chromium), Python unittest

Project Structure

MedSub-studio/
├── app.py                          # Hugging Face Spaces Gradio/Uvicorn entrypoint
├── Dockerfile                      # Multi-stage Docker build (Node 20 + Python 3.11 + FFmpeg)
├── render.yaml                     # Render.com Docker blueprint
├── requirements.txt                # Delegates to backend/requirements.txt
├── CONTRIBUTING.md
├── backend/
│   ├── app/
│   │   ├── config.py               # Paths, render defaults, preset fonts, FFmpeg & API key loaders
│   │   ├── main.py                 # FastAPI app, render jobs, AI, font & background endpoints
│   │   ├── models.py               # Pydantic schemas (SequenceConfig, TimelineSpec, RenderConfig)
│   │   ├── routers/media.py        # /api/media/waveform, /thumbnails, /matte streaming endpoints
│   │   ├── services/
│   │   │   ├── ai_director.py      # Gemini / heuristic visual cue planner
│   │   │   ├── ai_matte_service.py # RVM ONNX model auto-downloader, inference & cache
│   │   │   ├── audio_transcriber.py# Groq Whisper / faster-whisper + Gemini Darija alignment
│   │   │   ├── background_engine.py# Studio room library, custom media & optical effects
│   │   │   ├── broll_fetcher.py    # Multi-provider stock B-roll waterfall
│   │   │   ├── cache_service.py    # SHA-256 disk cache for waveforms, thumbnails & mattes
│   │   │   ├── camera_rig.py       # 10Hz YCrCb face trajectory & dynamic zoom rig
│   │   │   ├── card_compositor.py  # SVG icon & editorial motion-card compositor
│   │   │   ├── cut_service.py      # Smart silence detection & EDL remapping
│   │   │   ├── font_manager.py     # Google Font auto-downloader & GSUB presentation patcher
│   │   │   ├── frame_renderer.py   # Kinetic subtitle & word-highlight frame renderer
│   │   │   ├── kit_math.py         # Easing & spring motion curves
│   │   │   ├── matting_engine.py   # 6-stage FFmpeg chroma-key & despill filtergraphs
│   │   │   ├── motion_graphics.py  # Motion graphic overlay helpers
│   │   │   ├── normalized_layout.py# Layout Spec v1.0.0 Python reference
│   │   │   ├── rtl_layout.py       # Arabic/mixed-BiDi shaping & line layout
│   │   │   ├── scene_matcher.py    # Foreground/background lighting & color matching
│   │   │   ├── sfx_mixer.py        # 48kHz synthesized SFX & peak-aligned mixer
│   │   │   ├── srt_parser.py       # SRT parsing & word timing distribution
│   │   │   └── video_pipeline.py   # Multitrack video/audio compositing & FFmpeg export
│   │   └── utils/color_utils.py
│   ├── assets/
│   │   ├── backgrounds/            # Curated built-in studio & outdoor backdrops
│   │   ├── brand/                  # Vector brand SVG
│   │   ├── fonts/                  # Auto-cached Google Fonts & custom uploads (gitignored)
│   │   ├── icons/                  # Vector SVG icons for motion cards
│   │   ├── models/                 # Auto-downloaded RVM ONNX weights (gitignored)
│   │   └── sfx/                    # Auto-synthesized WAV sound effects (gitignored)
│   ├── tests/                      # Python unit, bugfix, AI matte, PSNR & Tier-4 render tests
│   ├── check_env.py                # Read-only dependency & FFmpeg verification script
│   ├── verify_merged_pipeline.py   # 6-stage end-to-end CPU pipeline benchmark
│   ├── server.py                   # Headless Uvicorn server entrypoint
│   └── .env.example                # Environment variable template
├── frontend/
│   ├── src/
│   │   ├── App.tsx                 # Main studio workspace & backend integration
│   │   ├── components/             # PreviewMonitor, LayerCompositor, TimelinePanel, Studio panels
│   │   ├── services/               # editingEngine.ts, timelineDragController.ts
│   │   ├── store/                  # Zustand stores (sequence, timeline, navigation, history)
│   │   ├── types/                  # TypeScript clip, marker, project & sequence contracts
│   │   └── utils/                  # normalizedLayout.ts, timecode.ts, rippleEdit.ts, shortcuts
│   ├── electron/                   # Electron main & preload IPC bridge for desktop packaging
│   ├── tests/                      # Vitest unit & regression tests
│   └── e2e/                        # Playwright Chromium E2E & performance tests
├── shared/
│   ├── specs/layout_spec_v1.json   # Formal NormalizedSequenceLayout v1.0.0 specification
│   ├── test_vectors/               # 14 deterministic golden layout vectors
│   └── tests/test_golden_layout.py # Golden vector parity test suite
└── deploy/oracle/                  # Oracle Cloud VM Docker Compose + Caddy HTTPS config

Installation & Setup

Prerequisites

  • Python 3.12 (recommended; 3.11+ supported)
  • Node.js 20+ and npm
  • FFmpeg: Uses system ffmpeg on PATH if present, otherwise falls back automatically to the binary bundled with imageio-ffmpeg (or override via MEDSUB_FFMPEG).

1. Backend Setup

# Windows PowerShell
cd backend
py -3.12 -m venv .venv
.\.venv\Scripts\Activate.ps1
pip install -r requirements.txt
Copy-Item .env.example .env
# macOS / Linux
cd backend
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
cp .env.example .env

Verify the Python environment:

python check_env.py

2. Frontend Setup

cd frontend
npm ci

Configuration

Edit backend/.env (copied from backend/.env.example). All AI API keys are optional—local fallbacks exist for transcription (faster-whisper), AI Director heuristics, and zero-key B-roll providers:

Variable Required Default Description
GROQ_API_KEY Optional — Groq whisper-large-v3 word-level ASR (falls back to local faster-whisper)
GEMINI_API_KEY Optional — Google Gemini for Darija multimodal alignment, translation, AI Director & scene matching
UNSPLASH_ACCESS_KEY Optional — Unsplash stock photo search for animated Ken Burns B-roll
PIXABAY_API_KEY Optional — Optional Pixabay stock video search
PEXELS_API_KEY Optional — Optional Pexels stock video search
GEMINI_MODEL Optional gemini-2.5-flash Gemini model identifier
WHISPER_LOCAL_MODEL Optional small Local faster-whisper model size
MEDSUB_MAX_RENDERS Optional 2 Maximum concurrent render jobs
MEDSUB_X264_PRESET Optional veryfast FFmpeg H.264 encode preset
MEDSUB_X264_CRF Optional 18 FFmpeg H.264 quality CRF
MEDSUB_CORS_ORIGINS Optional * Allowed CORS origins (comma-separated)

How to Run

Development Mode (Web UI + API)

Start the backend (port 8000):

cd backend
uvicorn app.main:app --host 127.0.0.1 --port 8000 --reload

In a second terminal, start the Vite dev server (port 5173, proxies /api and /outputs to 127.0.0.1:8000):

cd frontend
npm run dev

Open http://localhost:5173 in your browser (interactive API docs are available at http://localhost:8000/docs).

Single-Origin Production Build

cd frontend
npm run build
cd ../backend
uvicorn app.main:app --host 0.0.0.0 --port 8000

Electron Desktop App (Optional)

cd frontend
npm run build
npm run electron:start

Docker

docker build -t medsub-studio .
docker run --rm -p 7860:7860 --env-file backend/.env medsub-studio

Assets & Auto-Downloaded Models

To keep the repository lightweight, large weights and reproducible runtime assets are excluded from Git and provisioned automatically on demand:

  1. Robust Video Matting Model (rvm_mobilenetv3_fp32.onnx, ~14.3 MB):
    • Automatically downloaded from RobustVideoMatting Releases v1.0.0 and verified against SHA-256 (88d45312...cbbd2828) by ai_matte_service.py.
    • To pre-fetch manually before going offline:
      cd backend
      python -c "from app.services.ai_matte_service import ensure_rvm_model; print(ensure_rvm_model())"
  2. Preset Google Arabic Fonts (Cairo-Bold, Tajawal-Bold, Almarai-ExtraBold, Changa-Bold):
    • Downloaded automatically into backend/assets/fonts/ and GSUB-patched into backend/assets/fonts/_shaped/ by font_manager.py.
    • Additional studio font slots (Thmanyah-Bold, DINNextLTArabic-Bold, LyonArabic-Bold) are optional and can be uploaded via the UI (/api/upload-font) or placed in backend/assets/fonts/.
  3. 48kHz Sound Effects (backend/assets/sfx/*.wav):
    • Automatically synthesized on startup/first render using NumPy and SciPy by sfx_mixer.py.

Testing & Verification

Run the automated test suites:

# 1. Shared Golden Layout Parity Vectors
python -m unittest shared/tests/test_golden_layout.py -v

# 2. Backend Unit, Regression, AI Matte, PSNR Parity & Tier-4 Production Render Tests
cd backend
python -m unittest discover -s tests -p "test_*.py" -v

# 3. 6-Stage Unified CPU Pipeline Smoke Verification
python verify_merged_pipeline.py

# 4. Frontend Typecheck, Unit Tests & Production Build
cd ../frontend
npx tsc --noEmit
npx vitest run
npm run build

# 5. Playwright Chromium E2E Suite
npx playwright test --reporter=list

Verified Test Results

Suite Scope Result
Shared Golden Layout (test_golden_layout.py) 14 layout vectors across background, foreground, overlay, subtitle & alpha warp 7 / 7 passed
Backend unittest (tests/test_*.py) Models, caching, bugfixes, AI matte (DirectML/CPU), chroma/transparent MOV, Tier-4 9:16 / 16:9 / 1:1 renders & OpenCV PSNR parity (34.53–34.97 dB) 49 / 49 passed
Unified Pipeline Check (verify_merged_pipeline.py) Fonts/GSUB, kit_math + SVG cards, 48kHz SFX, chroma graph, silence detection, 5-layer 6s render 6 / 6 stages passed
Frontend Typecheck (tsc --noEmit) Strict TypeScript compilation 0 errors
Frontend Unit Suite (vitest run) Migration, AI matte, bugfixes, history reversibility, Tier 1–3 NLE operations 7 / 7 files, 59 / 59 tests passed
Frontend Production Build (npm run build) Vite 8 bundle (58 modules) Passed

Note on Playwright E2E Benchmarks: In frontend/e2e/timeline.spec.ts, the 5-second requestAnimationFrame stress test asserts p95 <= 16.67ms, which measures 16.80ms on 60 Hz headless Chromium due to Chromium's 0.1ms DOMHighResTimeStamp quantization floor (see TEST_READY.md). Also, external cloud AI calls (Groq, Gemini, stock APIs) require valid API keys in backend/.env and network connectivity.


Limitations & Future Improvements

  • E2E rAF Benchmark Granularity: Switching e2e/timeline.spec.ts from 0.1ms-quantized rAF timestamps to microsecond CDP Tracing timestamps would avoid false-positive failures at 60 Hz.
  • Code Splitting: The Vite production JS bundle (~674 kB) can be split via dynamic imports for faster initial browser load.
  • Electron Packaging Verification: Automated CI covers web/Chromium and backend tests; packaged NSIS installer (npm run electron:dist) testing remains manual on Windows.

License

This project is licensed under the MIT License — see LICENSE for details.

About

Multitrack NLE video editor & AI Arabic/Darija caption studio featuring Whisper + Gemini alignment, local RVM ONNX matting, GSUB RTL rendering, and 1:1 FFmpeg export parity.

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages