Automatic movie clipping for YouTube Shorts — intelligently extracts the best moments from full-length movies, crops them to 9:16 vertical format, adds proper subtitles, and prepares them for YouTube Shorts publishing.
Built with PySceneDetect, faster-whisper, FFmpeg, and LLM scoring (Yandex AI Studio DeepSeek V4 / Gemini / OpenRouter / OpenCode Zen).
🌐 English | Русский
MovieShort AI automatically extracts the best moments from full-length movies and prepares them for YouTube Shorts:
- Scene detection → transcription → LLM scoring → vertical crop → subtitles
- AI-powered clip selection with knowledge-aware scoring (1-10)
- Fully automated pipeline — just select a movie and pick the best clips
- Smart scene detection — PySceneDetect finds scene boundaries, merges short scenes, splits by dialogue pauses
- AI-powered clip selection — LLM (DeepSeek / Gemini) scores each scene (1-10) with names, uses knowledge about the movie
- Person tracking — OpenCV detects faces (frontal+profile) and persons (HOG), centers crop on the most active person
- Vertical crop (9:16) — Professional vertical format for YouTube Shorts with blurred background
- Word-level subtitles — faster-whisper transcription with word-level timestamps, customizable font/size/color/position
- Batch processing — Process multiple movies in sequence with full progress tracking
- Smart centering — For long scenes, finds the dialogue-dense window to start the clip
- Diversity filter — Evenly distributes clips across the full movie runtime
- Bilingual interface — English and Russian UI, translatable LLM prompts
- Anti-copyright mode — Horizontal flip + contrast correction to avoid Content ID flags
# 1. Install (one-time)
setup.bat
# 2. Run
run.batOpens at http://localhost:7860.
![]() |
If you find this project useful, you can support it:
- Python 3.9+ (if missing,
setup.batshows a download link to python.org) - FFmpeg (auto-installed via
setup.bat) - NVIDIA GPU (optional, speeds up transcription 5-10x)
| Mode | Description |
|---|---|
| Contextual (LLM) | Default. Block-based pipeline: scenes merged into ~120s super-blocks with dialogue, cut count, RMS envelope. LLM batches by 4 for 1M models (deepseek-v4-flash, nemotron-3-ultra-free), 3 for 190-262K (big-pickle, mimo-v2.5-free, hy3-free, nemotron-3.5-lightning-free), 2 default blocks, returns clips with absolute timestamps. Validation + smart centering fallback. |
| Standard (no LLM) | Random scene selection. No API key required. No clip names generated. |
| Manual | Enter custom timestamps — clips are cut exactly at those points. |
| Option | Default | Description |
|---|---|---|
| Subtitles | On | Speech recognition + subtitle overlay |
| Smart centering | On | Person detection (faces + HOG), centers frame on active person |
| Banner areas | On | Top/bottom padding for banners (300px configurable) |
| Blurred background | On | Fills empty space with blurred video |
| Anti-copyright | On | Mirror + contrast for Content ID avoidance |
- Get an API key from Yandex AI Studio
- Go to Settings in the app → Provider: Yandex AI Studio
- Enter API Key and Folder ID, select model (e.g.,
deepseek-v4-flash) - Click Verify key
- Get an API key from Google AI Studio
- Go to Settings > Gemini and paste the key
- Get an API key from OpenRouter
- Go to Settings in the app → Provider: OpenRouter
- Enter API Key, select model (default
stealth/ox-alpha) - Click Verify key
- Get an API key from OpenCode Zen
- Go to Settings in the app → Provider: OpenCode Zen
- Enter API Key, select model (default
nemotron-3-ultra-free) - Click Verify key
- Scene detection — PySceneDetect finds boundaries by frame changes
- Short scene merging — Buffer algorithm merges short scenes (max 120s)
- Transcription — faster-whisper (medium) once for the full movie
- Block assembly — Scenes carry metadata: dialogue pauses, cut count (action proxy), audio RMS envelope. Adjacent blocks are merged into ~120s super-blocks.
- Silent block filter — Blocks without dialogue are excluded entirely (no clips from silent scenes).
- Batch LLM processing — Super-blocks are grouped in batches of 4 for 1M models (deepseek-v4-flash, nemotron-3-ultra-free), 3 for 190-262K (big-pickle, mimo-v2.5-free, hy3-free, nemotron-3.5-lightning-free), 2 default. A single prompt
PROMPT_BATCH_TO_CLIPSlists blocks with full dialogue, cut count, and pauses. LLM returns JSON with absolute timestamps and per-block indices. - Validation + fallback — Per-block validation (duration 20-75s, score 1-10, within block bounds). If LLM returns no clips for a block but dialogue exists →
_find_best_window()(smart centering). - Clip selection — Score ≥ 7, diversity filter spreads clips across movie, deduplication (min gap 120s), short clip expansion.
- FFmpeg processing — Cut → 9:16 crop → subtitles → blurred background → 1080×1920
MIT — free to use, modify, and distribute.
MovieShort AI — автоматическая нарезка фильмов на YouTube Shorts. Интеллектуально извлекает лучшие моменты из полнометражных фильмов, обрезает их в вертикальный формат 9:16, добавляет субтитры и готовит к публикации.
Сделано с PySceneDetect, faster-whisper, FFmpeg и скорингом через LLM (Yandex AI Studio DeepSeek V4 / Gemini / OpenRouter / OpenCode Zen).
- Умный поиск сцен — PySceneDetect находит границы сцен, объединяет короткие, делит по паузам в диалогах
- AI-выбор клипов — LLM (DeepSeek / Gemini) оценивает каждую сцену (1-10) и даёт название, используя знания о фильме
- Person tracking — OpenCV находит лица (фронтальные+профильные) и людей (HOG), центрирует кадр по самому активному человеку
- Вертикальный кроп (9:16) — Профессиональный формат YouTube Shorts с размытым фоном
- Субтитры по словам — faster-whisper с таймстемпами на уровне слов; шрифт, размер, цвет, положение настраиваются
- Пакетная обработка — Несколько фильмов подряд с полным отслеживанием прогресса
- Smart centering — Для длинных сцен находит окно с максимальной плотностью диалога
- Diversity-фильтр — Равномерно распределяет клипы по всему фильму
- Двуязычный интерфейс — Русский и английский язык интерфейса, промпты LLM на языке фильма
- Anti-copyright — Зеркало + коррекция контраста для обхода Content ID
# 1. Установка (один раз)
setup.bat
# 2. Запуск
run.batОткроется http://localhost:7860.
![]() |
Если проект оказался полезным, поддержать можно так:
- Python 3.9+ (если нет —
setup.batпокажет ссылку на python.org) - FFmpeg (установится автоматически через
setup.bat) - NVIDIA GPU (опционально, ускоряет транскрипцию в 5-10×)
| Режим | Описание |
|---|---|
| Контекстный (LLM) | По умолчанию. Block-based pipeline: сцены сливаются в супер-блоки ~120с с диалогом, сменами кадра, RMS. LLM батчами по 4 для 1M-моделей (deepseek, nemotron), по 3 для 190-262K, по 2 по умолчанию, возвращает клипы с абсолютными таймстемпами. Валидация + smart centering fallback. |
| Стандартный (без LLM) | Случайный выбор сцен. Не требует API-ключа. Названия не генерируются. |
| Ручной | Укажи таймкоды — программа нарежет клипы по ним. |
| Опция | По умолч. | Описание |
|---|---|---|
| Субтитры | Вкл | Распознавание речи + наложение субтитров |
| Smart centering | Вкл | Детекция лиц, центровка кадра |
| Баннерные поля | Вкл | Поля сверху/снизу для баннеров (300px) |
| Размытый фон | Вкл | Заполняет пустое пространство размытым видео |
| Anti-copyright | Вкл | Зеркало + контраст для обхода Content ID |
- Получи ключ: Yandex AI Studio → создать сервисный аккаунт
- В интерфейсе: Settings → провайдер Yandex AI Studio
- Введи API Key, Folder ID, выбери модель (например,
deepseek-v4-flash) - Нажми Verify key — зелёный = работает
- Получи ключ: Google AI Studio
- Вставь API-ключ в Settings > Gemini — приложение само определит OpenRouter или Google AI
- Получи ключ: OpenRouter
- В интерфейсе: Settings → провайдер OpenRouter
- Введи API Key, выбери модель (по умолчанию
stealth/ox-alpha) - Нажми Verify key — зелёный = работает
- Получи ключ: OpenCode Zen
- В интерфейсе: Settings → провайдер OpenCode Zen
- Введи API Key, выбери модель (по умолчанию
nemotron-3-ultra-free) - Нажми Verify key — зелёный = работает
- Детекция сцен — PySceneDetect находит границы сцен по изменению кадра
- Слияние коротких сцен — Буферный алгоритм объединяет короткие сцены (макс. 120с)
- Транскрипция — faster-whisper (medium) распознаёт речь 1 раз для всего фильма
- Сборка блоков — Сцены получают метаданные: паузы в диалоге, количество смен кадра (косвенный показатель экшна), RMS-огибающая аудио. Соседние блоки сливаются в супер-блоки ~120с.
- Фильтр тихих блоков — Блоки без диалога полностью исключаются (клипы из них не делаются).
- Батч LLM — Супер-блоки группируются батчами по 4 для 1M-моделей (deepseek, nemotron), по 3 для 190-262K, по 2 по умолчанию. Один промпт
PROMPT_BATCH_TO_CLIPSсодержит блоки с полным диалогом, сменами кадра и паузами. LLM возвращает JSON с абсолютными таймстемпами и индексами блоков. - Валидация + fallback — Поблочная проверка (длительность 20-75с, оценка 1-10, в границах блока). Если LLM не дала клипов для блока, но есть диалог →
_find_best_window()(smart centering). - Выбор клипов — Оценка ≥ 7, diversity-фильтр распределяет по фильму, дедупликация (мин. 120с), расширение коротких клипов.
- FFmpeg обработка — Нарезка → кроп 9:16 → субтитры → размытый фон → 1080×1920
MovieShort-AI/
├── main.py # Точка входа (+ monkey-patch gradio_client)
├── config.py # Конфигурация (Whisper, FFmpeg, API, баннеры)
├── core/
│ ├── pipeline.py # Пайплайн обработки одного клипа
│ ├── processor.py # Person tracking (faces + HOG) + вертикальный кроп
│ ├── batch.py # Пакетная обработка фильма
│ └── subtitle.py # Генерация SRT (word-group, JSON persistence)
├── analyzers/
│ ├── detector.py # Стандартный режим (без LLM)
│ ├── scene_analyzer.py# Детекция сцен, слияние, транскрипция
│ └── text_analyzer.py # LLM анализ (промпты, API, парсинг)
├── gui/
│ └── app.py # Gradio веб-интерфейс
├── utils/
│ ├── ffmpeg_utils.py # FFmpeg команды
│ ├── user_config.py # Сохранение настроек
│ └── log_capture.py # Захват лога для GUI
├── models/
│ └── haarcascade_frontalface_default.xml
├── output/ # Выходные файлы (создаётся автоматически)
├── requirements.txt # Зависимости
├── setup.bat # Установка (venv + CUDA)
└── run.bat # Запуск
- Полный кадр — исходное 16:9 масштабируется до 1080×1320 (контентная область)
- Размытый фон (вкл/выкл) — контент накладывается на размытый full-frame фон (1080×1920)
- Баннерные поля (вкл/выкл, настраивается) — поля сверху/снизу для баннеров
- Anti-copyright (вкл/выкл) — горизонтальный флип + коррекция контраста/яркости
- Word-group SRT — группировка слов по 2-4, одна строка без переносов
- Выше баннера — субтитры подняты на
position_ypx от низа - Точная синхронизация — по word-level таймстемпам Whisper
- Транскрипция фильма делается 1 раз, сохраняется в JSON, переиспользуется для всех клипов
Для длинных сцен (>60с) алгоритм ищет окно с максимальной плотностью слов — клип начинается там, где самый насыщенный диалог. Шаг скользящего окна — 1с.
При запуске Whisper: проверка CUDA → проба compute types (float16 → int8_float16 → CPU int8) → печать модели GPU и расчётного времени.
Буферный алгоритм: короткие сцены (<15с) объединяются, но никогда не расширяют уже готовую сцену. Паузы >2с создают границу. Итог: осмысленные фрагменты 15-120с вместо гигантских 400-секундных сцен.
MIT — можно свободно использовать, модифицировать и распространять.

