Skip to content

Open-source alternative to Opus Clip, Vidyo.ai, Klap & SubMagic. Turn long-form YouTube videos into viral 9:16 shorts using LLM highlight detection, Whisper transcription, and auto vertical cropping — free, no watermarks, no per-clip credits.

Add --mode local: yt-dlp + faster-whisper + OpenAI + ffmpeg pipeline

Anil Matcha262148e4675c
diff --git a/README.md b/README.md
index 6846c7b..d88a3eb 100644
--- a/README.md
+++ b/README.md
@@ -27,15 +27,16 @@ Built for creators, agencies, and developers who don't want to pay $20–$300/mo
## Features
- **🎬 YouTube In, Vertical Out**: Hand it any YouTube URL — get back N viral-ready 9:16 mp4s
+- **🔀 Two Modes — API (fast) or Local (offline)**: Default `--mode api` uses MuAPI for download/transcription/cropping; `--mode local` runs entirely on your machine with `yt-dlp`, `faster-whisper`, OpenAI, and `ffmpeg`/`opencv` — pick what fits
- **🤖 Virality-Aware Highlight Selection**: Clips ranked on hooks, emotional peaks, opinion bombs, revelation moments, conflict, quotable lines, story peaks, and practical value — not just generic "interesting"
- **📈 Score + Hook + Reason for Every Clip**: Each highlight comes with a viral score, an opening hook line, and a one-sentence explanation of why it works
-- **🎤 Cloud Whisper Transcription**: Audio is transcribed via MuAPI's `/openai-whisper` endpoint — no local model download, no GPU needed
+- **🎤 Whisper Transcription, Your Choice**: Cloud (`/openai-whisper` via MuAPI) or local (`faster-whisper`, CPU or CUDA) — same downstream output shape
- **🧩 Long-Video Aware**: Videos over 30 minutes are auto-chunked with overlap so nothing gets missed
- **♻️ Smart Dedupe**: Overlapping highlights are collapsed by score so you never get two near-duplicate clips
-- **🎯 Smart Vertical Crop**: Auto-cropping handles face tracking and screen recordings automatically — no Haar cascades, no OpenCV setup
+- **🎯 Smart Vertical Crop**: API mode uses MuAPI's auto-crop; local mode runs OpenCV face tracking with motion smoothing
- **📱 Any Aspect Ratio**: 9:16 for TikTok/Reels/Shorts, 1:1 for square, anything else by flag
- **🧰 CLI + Python Library**: Use it from the shell or import `generate_shorts(...)` into your own pipeline
-- **📦 JSON Output**: `--output-json` dumps the full result (transcript + every candidate highlight + final clip URLs) for downstream automation
+- **📦 JSON Output**: `--output-json` dumps the full result (transcript + every candidate highlight + final clip URLs/paths) for downstream automation
## Quick Start (No Setup)
@@ -48,7 +49,8 @@ Don't want to self-host? The [AI Clipping API](https://muapi.ai/playground/ai-cl
### Prerequisites
- Python 3.10+
-- A MuAPI key (powers download, transcription, highlight ranking, and clipping)
+- For **API mode (default)**: a MuAPI key — powers download, transcription, highlight ranking, and clipping in a single dependency
+- For **Local mode** (`--mode local`): `ffmpeg` on your PATH and an `OPENAI_API_KEY` (only the LLM step is remote; everything else runs offline)
### Steps
@@ -67,27 +69,46 @@ Don't want to self-host? The [AI Clipping API](https://muapi.ai/playground/ai-cl
3. **Install Python dependencies:**
```bash
pip install -r requirements.txt
+ # Only if you plan to use --mode local:
+ pip install -r requirements-local.txt
```
4. **Set up environment variables:**
- Create a `.env` file in the project root (copy from `.env.example`):
+ Create a `.env` file in the project root:
```bash
- MUAPI_API_KEY=your_api_key_here
+ # API mode (default)
+ MUAPI_API_KEY=your_muapi_key_here
+
+ # Local mode (--mode local) — only the OPENAI key is required
+ OPENAI_API_KEY=your_openai_key_here
+ OPENAI_MODEL=gpt-4o-mini # optional, default gpt-4o-mini
+ LOCAL_WHISPER_MODEL=base # tiny / base / small / medium / large-v3
+ LOCAL_WHISPER_DEVICE=auto # auto / cpu / cuda
+ LOCAL_OUTPUT_DIR=output # where local mp4s land
```
## Usage
-### Single video
+### Single video (API mode — default)
```bash
python main.py "https://www.youtube.com/watch?v=VIDEO_ID"
```
+### Single video (Local mode — runs offline except for the LLM call)
+
+```bash
+python main.py "https://www.youtube.com/watch?v=VIDEO_ID" --mode local
+```
+
+Local mode writes the rendered shorts to `./output/short_01.mp4`, `short_02.mp4`, … (override with `LOCAL_OUTPUT_DIR`).
+
### With options
```bash
python main.py "https://www.youtube.com/watch?v=VIDEO_ID" \
+ --mode api \
--num-clips 5 \
--aspect-ratio 9:16 \
--output-json result.json
@@ -121,12 +142,24 @@ xargs -a urls.txt -I{} python main.py "{}"
| Flag | Default | Notes |
|------|---------|-------|
+| `--mode` | `api` | `api` (MuAPI, fast, no setup) or `local` (yt-dlp + faster-whisper + OpenAI + ffmpeg) |
| `--num-clips` | `3` | How many shorts to render |
| `--aspect-ratio` | `9:16` | Any ratio; `9:16` for TikTok/Reels, `1:1` for square |
| `--format` | `720` | Source download resolution: `360` / `480` / `720` / `1080` |
| `--language` | auto | Force Whisper language code (e.g. `en`) |
| `--output-json` | — | Dump the full result (transcript + all candidates) to a file |
+### API mode vs Local mode
+
+| Step | API mode (`--mode api`) | Local mode (`--mode local`) |
+|---|---|---|
+| Download | MuAPI `/youtube-download` | `yt-dlp` |
+| Transcription | MuAPI `/openai-whisper` | `faster-whisper` (CPU or CUDA) |
+| Highlight LLM | MuAPI `gpt-5-mini` | OpenAI (`gpt-4o-mini` by default) |
+| Vertical crop | MuAPI `/autocrop` | `ffmpeg` + OpenCV face tracking |
+| Output | hosted URLs | local mp4 paths |
+| Required keys | `MUAPI_API_KEY` | `OPENAI_API_KEY` (+ `ffmpeg` on PATH) |
+
## How It Works
1. **Download**: Fetches the source video from YouTube
@@ -201,16 +234,22 @@ Audio is transcribed by MuAPI's `/openai-whisper` endpoint (server-side `whisper
```
AI-Youtube-Shorts-Generator/
├── main.py CLI entry point
-├── requirements.txt
+├── requirements.txt core deps (api mode)
+├── requirements-local.txt optional deps for --mode local
├── .env.example
└── shorts_generator/
- ├── config.py env / settings
+ ├── config.py env / settings (MuAPI + OpenAI + Whisper)
├── muapi.py generic submit + poll wrapper
- ├── downloader.py YouTube source download
- ├── transcriber.py MuAPI /openai-whisper client
- ├── highlights.py LLM virality ranking + chunking + dedupe
- ├── clipper.py vertical auto-crop
- └── pipeline.py end-to-end orchestrator
+ ├── downloader.py API mode: YouTube download via MuAPI
+ ├── transcriber.py API mode: MuAPI /openai-whisper client
+ ├── highlights.py shared LLM virality ranking (pluggable backend)
+ ├── clipper.py API mode: MuAPI /autocrop
+ ├── pipeline.py mode dispatcher (api ↔ local)
+ └── local/ --mode local backends (offline)
+ ├── downloader.py yt-dlp download
+ ├── transcriber.py faster-whisper transcription
+ ├── llm.py OpenAI chat-completions client
+ └── clipper.py ffmpeg cut + OpenCV vertical crop
```
## Troubleshooting
diff --git a/main.py b/main.py
index f5b998e..431187b 100644
--- a/main.py
+++ b/main.py
@@ -12,8 +12,14 @@ from shorts_generator import generate_shorts
def main() -> int:
- parser = argparse.ArgumentParser(description="AI YouTube Shorts Generator (MuAPI edition)")
+ parser = argparse.ArgumentParser(description="AI YouTube Shorts Generator")
parser.add_argument("url", help="YouTube video URL")
+ parser.add_argument(
+ "--mode",
+ choices=["api", "local"],
+ default="api",
+ help="api (default, MuAPI) or local (yt-dlp + faster-whisper + OpenAI + ffmpeg).",
+ )
parser.add_argument("--num-clips", type=int, default=3, help="How many shorts to render (default: 3)")
parser.add_argument("--aspect-ratio", default="9:16", help="Output aspect ratio (default: 9:16)")
parser.add_argument("--format", default="720", help="Source download resolution: 360 / 480 / 720 / 1080 (default: 720)")
@@ -28,12 +34,14 @@ def main() -> int:
aspect_ratio=args.aspect_ratio,
download_format=args.format,
language=args.language,
+ mode=args.mode,
)
except Exception as e:
print(f"\nFAILED: {e}", file=sys.stderr)
return 1
print("\n" + "=" * 72)
+ print(f"Mode: {result.get('mode', args.mode)}")
print(f"Source video: {result['source_video_url']}")
print(f"Highlights: {len(result['highlights'])} candidates → kept top {len(result['shorts'])}")
print("=" * 72)
diff --git a/requirements-local.txt b/requirements-local.txt
new file mode 100644
index 0000000..0d28b31
--- /dev/null
+++ b/requirements-local.txt
@@ -0,0 +1,8 @@
+# Optional dependencies for --mode local.
+# Install on top of requirements.txt: pip install -r requirements-local.txt
+yt-dlp>=2024.1.1
+faster-whisper>=1.0.0
+openai>=1.0.0
+opencv-python>=4.8.0
+# torch is only needed if you want CUDA Whisper. CPU works without it.
+# torch>=2.0
diff --git a/shorts_generator/config.py b/shorts_generator/config.py
index 2554c9b..fdefbdf 100644
--- a/shorts_generator/config.py
+++ b/shorts_generator/config.py
@@ -10,6 +10,13 @@ MUAPI_BASE_URL = os.getenv("MUAPI_BASE_URL", "https://api.muapi.ai/api/v1").rstr
POLL_INTERVAL_SECONDS = float(os.getenv("MUAPI_POLL_INTERVAL", "5"))
POLL_TIMEOUT_SECONDS = float(os.getenv("MUAPI_POLL_TIMEOUT", "600"))
+# Local-mode (--mode local) settings — only consulted when running offline.
+OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "").strip()
+OPENAI_MODEL = os.getenv("OPENAI_MODEL", "gpt-4o-mini")
+LOCAL_WHISPER_MODEL = os.getenv("LOCAL_WHISPER_MODEL", "base")
+LOCAL_WHISPER_DEVICE = os.getenv("LOCAL_WHISPER_DEVICE", "auto") # auto / cpu / cuda
+LOCAL_OUTPUT_DIR = os.getenv("LOCAL_OUTPUT_DIR", "output")
+
def require_api_key() -> str:
if not MUAPI_API_KEY:
@@ -17,3 +24,12 @@ def require_api_key() -> str:
"MUAPI_API_KEY is not set. Add it to your .env file or export it as an env var."
)
return MUAPI_API_KEY
+
+
+def require_openai_key() -> str:
+ if not OPENAI_API_KEY:
+ raise RuntimeError(
+ "OPENAI_API_KEY is not set. Local mode needs an OpenAI key for highlight ranking. "
+ "Add it to your .env or export it, or switch back to --mode api."
+ )
+ return OPENAI_API_KEY
diff --git a/shorts_generator/highlights.py b/shorts_generator/highlights.py
index fba625c..6560fdb 100644
--- a/shorts_generator/highlights.py
+++ b/shorts_generator/highlights.py
@@ -1,18 +1,25 @@
-"""Find the most viral-worthy highlights in a transcript via MuAPI gpt-5-4.
+"""Find the most viral-worthy highlights in a transcript.
Logic ported from ViralVadoo's transcript_analysis/highlight_generator.py:
- content-type / density detection
- chunking for long videos with overlap
- virality-criteria prompt
- score-based dedupe with overlap suppression
+
+The LLM call is pluggable via the `llm_fn` argument so the same prompts can
+drive either MuAPI (default, --mode api) or a direct OpenAI client
+(--mode local).
"""
import json
import re
-from typing import Dict, List
+from typing import Callable, Dict, List, Optional
from . import muapi
+LLMFn = Callable[[str], str]
+
+
CONTENT_TYPE_PROMPT = """Analyze this video transcript sample and classify the content type.
Choose one: podcast, interview, tutorial, lecture, commentary, debate, vlog, other.
Also estimate content density: low (mostly filler/chit-chat), medium, or high (dense info/stories).
@@ -60,8 +67,8 @@ CHUNK_OVERLAP_SECONDS = 60
GPT_CALL_TIMEOUT_SECONDS = 300 # cap LLM polls at 5 min — a wedged call should fail fast
-def _call_gpt(prompt: str) -> str:
- """Send a single text prompt to MuAPI gpt-5-mini and return the raw text."""
+def call_muapi_llm(prompt: str) -> str:
+ """Default LLM backend: MuAPI gpt-5-mini."""
result = muapi.run(
"gpt-5-mini",
{"prompt": prompt},
@@ -102,12 +109,12 @@ def _parse_json_loose(raw: str) -> Dict:
raise
-def detect_content_type(transcript: Dict) -> Dict[str, str]:
+def detect_content_type(transcript: Dict, llm_fn: LLMFn = call_muapi_llm) -> Dict[str, str]:
segments = transcript.get("segments", [])
sample = " ".join(s["text"] for s in segments[:25])[:3000]
prompt = f"{CONTENT_TYPE_PROMPT}\n\nTranscript sample:\n{sample}"
try:
- raw = _call_gpt(prompt)
+ raw = llm_fn(prompt)
return _parse_json_loose(raw)
except Exception:
return {"content_type": "other", "density": "medium"}
@@ -145,6 +152,7 @@ def call_highlight_api(
duration: float,
num_clips: int,
is_chunk: bool = False,
+ llm_fn: LLMFn = call_muapi_llm,
) -> Dict:
# Ask for ~2× the user's target so dedupe has headroom, but cap so the model
# doesn't have to generate a huge JSON payload (which times out gpt-5-mini).
@@ -158,7 +166,7 @@ def call_highlight_api(
num_clips_instruction=f"Generate at least {min_clips} highlights",
)
full_prompt = f"{system}\n\nTranscript:\n{transcript_text}"
- raw = _call_gpt(full_prompt)
+ raw = llm_fn(full_prompt)
return _parse_json_loose(raw)
@@ -183,10 +191,19 @@ def dedupe_highlights(highlights: List[Dict]) -> List[Dict]:
return kept
-def get_highlights(transcript: Dict, num_clips: int = 3) -> Dict:
- """Main entry point — returns {highlights: [...]} sorted by score."""
+def get_highlights(
+ transcript: Dict,
+ num_clips: int = 3,
+ llm_fn: Optional[LLMFn] = None,
+) -> Dict:
+ """Main entry point — returns {highlights: [...]} sorted by score.
+
+ `llm_fn` swaps the underlying LLM. Defaults to MuAPI gpt-5-mini; local
+ mode passes in an OpenAI-backed callable.
+ """
+ llm_fn = llm_fn or call_muapi_llm
duration = transcript.get("duration", 0)
- content_info = detect_content_type(transcript)
+ content_info = detect_content_type(transcript, llm_fn=llm_fn)
print(f"[highlights] content={content_info.get('content_type')} density={content_info.get('density')} duration={duration:.0f}s", flush=True)
if duration >= LONG_VIDEO_THRESHOLD:
@@ -197,7 +214,7 @@ def get_highlights(transcript: Dict, num_clips: int = 3) -> Dict:
offset = chunk.get("_offset", 0)
text = build_transcript_text(chunk)
print(f"[highlights] chunk {i + 1}/{len(chunks)} (offset {offset:.0f}s)", flush=True)
- result = call_highlight_api(text, content_info, chunk["duration"], num_clips=num_clips, is_chunk=True)
+ result = call_highlight_api(text, content_info, chunk["duration"], num_clips=num_clips, is_chunk=True, llm_fn=llm_fn)
for h in result.get("highlights", []):
h["start_time"] = float(h["start_time"]) + offset
h["end_time"] = float(h["end_time"]) + offset
@@ -205,7 +222,7 @@ def get_highlights(transcript: Dict, num_clips: int = 3) -> Dict:
highlights = dedupe_highlights(all_highlights)
else:
text = build_transcript_text(transcript)
- result = call_highlight_api(text, content_info, duration, num_clips=num_clips)
+ result = call_highlight_api(text, content_info, duration, num_clips=num_clips, llm_fn=llm_fn)
highlights = dedupe_highlights(result.get("highlights", []))
return {"highlights": highlights}
diff --git a/shorts_generator/local/__init__.py b/shorts_generator/local/__init__.py
new file mode 100644
index 0000000..3f938b3
--- /dev/null
+++ b/shorts_generator/local/__init__.py
@@ -0,0 +1,6 @@
+"""Local-mode backends — no MuAPI calls, runs on your machine.
+
+Used when the pipeline is invoked with mode="local". Requires the optional
+deps in requirements-local.txt (yt-dlp, faster-whisper, openai, opencv,
+moviepy) plus an OPENAI_API_KEY for highlight ranking.
+"""
diff --git a/shorts_generator/local/clipper.py b/shorts_generator/local/clipper.py
new file mode 100644
index 0000000..931f99c
--- /dev/null
+++ b/shorts_generator/local/clipper.py
@@ -0,0 +1,167 @@
+"""Local clipping: ffmpeg subclip + OpenCV face-aware vertical crop.
+
+Two stages per highlight:
+ 1. Cut the source video to [start, end] with ffmpeg (re-encoded, audio kept).
+ 2. Reframe the cut to the target aspect ratio. For 9:16 we slide a vertical
+ window horizontally across the frame to keep faces centred (Haar
+ cascade — same approach as the original repo, no external models).
+"""
+import os
+import subprocess
+from typing import Dict, List, Optional, Tuple
+
+from ..config import LOCAL_OUTPUT_DIR
+
+
+def _ratio(aspect_ratio: str) -> float:
+ """Parse '9:16' → 9/16, '1:1' → 1.0."""
+ try:
+ w, h = aspect_ratio.split(":")
+ return float(w) / float(h)
+ except (ValueError, ZeroDivisionError):
+ return 9.0 / 16.0
+
+
+def _cut_subclip(source_path: str, start: float, end: float, out_path: str) -> str:
+ """ffmpeg -ss start -to end → re-encoded mp4 with audio."""
+ cmd = [
+ "ffmpeg", "-y", "-loglevel", "error",
+ "-i", source_path,
+ "-ss", f"{start:.3f}",
+ "-to", f"{end:.3f}",
+ "-c:v", "libx264", "-preset", "fast", "-crf", "20",
+ "-c:a", "aac", "-b:a", "128k",
+ out_path,
+ ]
+ subprocess.run(cmd, check=True)
+ return out_path
+
+
+def _reframe_vertical(in_path: str, out_path: str, aspect_ratio: str) -> str:
+ """Crop the cut clip to the target aspect ratio, tracking faces if possible."""
+ try:
+ import cv2 # type: ignore
+ except ImportError as e:
+ raise RuntimeError(
+ "opencv-python is required for --mode local. Install it with:\n"
+ " pip install -r requirements-local.txt"
+ ) from e
+
+ target_ratio = _ratio(aspect_ratio)
+ cap = cv2.VideoCapture(in_path)
+ if not cap.isOpened():
+ raise RuntimeError(f"could not open {in_path}")
+
+ src_w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
+ src_h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
+ fps = cap.get(cv2.CAP_PROP_FPS) or 30.0
+
+ # Compute the largest crop that fits inside the frame at the target ratio.
+ if target_ratio < src_w / src_h:
+ crop_h = src_h
+ crop_w = int(crop_h * target_ratio)
+ else:
+ crop_w = src_w
+ crop_h = int(crop_w / target_ratio)
+ crop_w = max(2, crop_w - (crop_w % 2))
+ crop_h = max(2, crop_h - (crop_h % 2))
+
+ face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
+
+ silent_path = out_path + ".silent.mp4"
+ fourcc = cv2.VideoWriter_fourcc(*"mp4v")
+ writer = cv2.VideoWriter(silent_path, fourcc, fps, (crop_w, crop_h))
+
+ last_center: Optional[Tuple[int, int]] = None
+ smoothing = 0.15 # how aggressively to chase a new face position
+ while True:
+ ret, frame = cap.read()
+ if not ret:
+ break
+
+ gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
+ faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(40, 40))
+ if len(faces) > 0:
+ # Pick the largest face — usually the speaker.
+ x, y, w, h = max(faces, key=lambda f: f[2] * f[3])
+ cx = x + w // 2
+ cy = y + h // 2
+ if last_center is None:
+ last_center = (cx, cy)
+ else:
+ lx, ly = last_center
+ last_center = (
+ int(lx + (cx - lx) * smoothing),
+ int(ly + (cy - ly) * smoothing),
+ )
+ if last_center is None:
+ last_center = (src_w // 2, src_h // 2)
+
+ cx, cy = last_center
+ x0 = max(0, min(src_w - crop_w, cx - crop_w // 2))
+ y0 = max(0, min(src_h - crop_h, cy - crop_h // 2))
+ cropped = frame[y0:y0 + crop_h, x0:x0 + crop_w]
+ writer.write(cropped)
+
+ cap.release()
+ writer.release()
+
+ # Mux audio from the cut clip back onto the silent reframed video.
+ cmd = [
+ "ffmpeg", "-y", "-loglevel", "error",
+ "-i", silent_path,
+ "-i", in_path,
+ "-c:v", "copy",
+ "-c:a", "aac", "-b:a", "128k",
+ "-map", "0:v:0", "-map", "1:a:0?",
+ "-shortest",
+ out_path,
+ ]
+ subprocess.run(cmd, check=True)
+ os.remove(silent_path)
+ return out_path
+
+
+def crop_clip_local(
+ source_path: str,
+ start_time: float,
+ end_time: float,
+ aspect_ratio: str,
+ out_path: str,
+) -> str:
+ """Cut + reframe one highlight, returning the local mp4 path."""
+ cut_path = out_path + ".cut.mp4"
+ try:
+ _cut_subclip(source_path, start_time, end_time, cut_path)
+ _reframe_vertical(cut_path, out_path, aspect_ratio)
+ finally:
+ if os.path.exists(cut_path):
+ os.remove(cut_path)
+ return out_path
+
+
+def crop_highlights_local(
+ source_path: str,
+ highlights: List[Dict],
+ aspect_ratio: str = "9:16",
+ out_dir: Optional[str] = None,
+) -> List[Dict]:
+ out_dir = out_dir or LOCAL_OUTPUT_DIR
+ os.makedirs(out_dir, exist_ok=True)
+ results: List[Dict] = []
+ for i, h in enumerate(highlights, 1):
+ out_path = os.path.join(out_dir, f"short_{i:02d}.mp4")
+ print(f"[clip/local] {i}/{len(highlights)}: {h.get('title', '(untitled)')}", flush=True)
+ try:
+ crop_clip_local(
+ source_path,
+ float(h["start_time"]),
+ float(h["end_time"]),
+ aspect_ratio,
+ out_path,
+ )
+ results.append({**h, "clip_url": out_path})
+ except Exception as e:
+ print(f"[clip/local] {i} failed: {e}", flush=True)
+ results.append({**h, "clip_url": None, "error": str(e)})
+ return results
diff --git a/shorts_generator/local/downloader.py b/shorts_generator/local/downloader.py
new file mode 100644
index 0000000..8e2dea7
--- /dev/null
+++ b/shorts_generator/local/downloader.py
@@ -0,0 +1,63 @@
+"""Local YouTube download via yt-dlp.
+
+Returns a local mp4 path so the rest of the local pipeline can read it
+directly off disk.
+"""
+import os
+from typing import Optional
+
+from ..config import LOCAL_OUTPUT_DIR
+
+
+def _import_ytdlp():
+ try:
+ import yt_dlp # type: ignore
+ except ImportError as e:
+ raise RuntimeError(
+ "yt-dlp is required for --mode local. Install it with:\n"
+ " pip install -r requirements-local.txt"
+ ) from e
+ return yt_dlp
+
+
+def _format_for(fmt: str) -> str:
+ """Map our '720' / '1080' shorthand to a yt-dlp format selector."""
+ try:
+ height = int(fmt)
+ except ValueError:
+ height = 720
+ return (
+ f"bestvideo[height<={height}][ext=mp4]+bestaudio[ext=m4a]/"
+ f"best[height<={height}][ext=mp4]/best"
+ )
+
+
+def download_youtube_local(video_url: str, fmt: str = "720", out_dir: Optional[str] = None) -> str:
+ """Download to disk and return the local mp4 path."""
+ yt_dlp = _import_ytdlp()
+ out_dir = out_dir or LOCAL_OUTPUT_DIR
+ os.makedirs(out_dir, exist_ok=True)
+
+ print(f"[download/local] {video_url} @ {fmt}p → {out_dir}/", flush=True)
+ ydl_opts = {
+ "format": _format_for(fmt),
+ "outtmpl": os.path.join(out_dir, "source_%(id)s.%(ext)s"),
+ "merge_output_format": "mp4",
+ "quiet": True,
+ "no_warnings": True,
+ "noprogress": True,
+ }
+
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
+ info = ydl.extract_info(video_url, download=True)
+ path = ydl.prepare_filename(info)
+ # merge_output_format may rename the extension after merge
+ if not os.path.exists(path):
+ stem, _ = os.path.splitext(path)
+ for ext in (".mp4", ".mkv", ".webm"):
+ if os.path.exists(stem + ext):
+ path = stem + ext
+ break
+
+ print(f"[download/local] ready: {path}", flush=True)
+ return path
diff --git a/shorts_generator/local/llm.py b/shorts_generator/local/llm.py
new file mode 100644
index 0000000..1a39946
--- /dev/null
+++ b/shorts_generator/local/llm.py
@@ -0,0 +1,21 @@
+"""Local LLM backend — calls OpenAI directly so no MuAPI account is needed."""
+from ..config import OPENAI_MODEL, require_openai_key
+
+
+def call_openai_llm(prompt: str) -> str:
+ """OpenAI Chat Completions backend used by --mode local."""
+ try:
+ from openai import OpenAI # type: ignore
+ except ImportError as e:
+ raise RuntimeError(
+ "openai is required for --mode local. Install it with:\n"
+ " pip install -r requirements-local.txt"
+ ) from e
+
+ client = OpenAI(api_key=require_openai_key())
+ response = client.chat.completions.create(
+ model=OPENAI_MODEL,
+ temperature=0.7,
+ messages=[{"role": "user", "content": prompt}],
+ )
+ return response.choices[0].message.content or ""
diff --git a/shorts_generator/local/transcriber.py b/shorts_generator/local/transcriber.py
new file mode 100644
index 0000000..458d94b
--- /dev/null
+++ b/shorts_generator/local/transcriber.py
@@ -0,0 +1,54 @@
+"""Local transcription via faster-whisper.
+
+Reads a local media file and returns the same shape the highlight generator
+expects: {duration, segments[start, end, text]}.
+"""
+from typing import Dict, Optional
+
+from ..config import LOCAL_WHISPER_DEVICE, LOCAL_WHISPER_MODEL
+
+
+def _resolve_device() -> str:
+ if LOCAL_WHISPER_DEVICE != "auto":
+ return LOCAL_WHISPER_DEVICE
+ try:
+ import torch # type: ignore
+ return "cuda" if torch.cuda.is_available() else "cpu"
+ except ImportError:
+ return "cpu"
+
+
+def transcribe_local(media_path: str, language: Optional[str] = None) -> Dict:
+ """Run faster-whisper on a local file path."""
+ try:
+ from faster_whisper import WhisperModel # type: ignore
+ except ImportError as e:
+ raise RuntimeError(
+ "faster-whisper is required for --mode local. Install it with:\n"
+ " pip install -r requirements-local.txt"
+ ) from e
+
+ device = _resolve_device()
+ compute_type = "float16" if device == "cuda" else "int8"
+ print(f"[transcribe/local] faster-whisper model={LOCAL_WHISPER_MODEL} device={device}", flush=True)
+
+ model = WhisperModel(LOCAL_WHISPER_MODEL, device=device, compute_type=compute_type)
+ segments_iter, info = model.transcribe(
+ media_path,
+ language=language,
+ beam_size=5,
+ vad_filter=True,
+ condition_on_previous_text=False,
+ )
+
+ segments = []
+ for s in segments_iter:
+ segments.append({
+ "start": float(s.start),
+ "end": float(s.end),
+ "text": (s.text or "").strip(),
+ })
+
+ duration = float(getattr(info, "duration", 0.0)) or (segments[-1]["end"] if segments else 0.0)
+ print(f"[transcribe/local] {len(segments)} segments, {duration:.0f}s of audio", flush=True)
+ return {"duration": duration, "segments": segments}
diff --git a/shorts_generator/pipeline.py b/shorts_generator/pipeline.py
index 1fdbdab..82a8e2a 100644
--- a/shorts_generator/pipeline.py
+++ b/shorts_generator/pipeline.py
@@ -1,33 +1,65 @@
"""End-to-end orchestrator.
-YouTube URL → MuAPI download → MuAPI /openai-whisper transcript
- → MuAPI gpt-5-4 highlights → MuAPI autocrop clips
+Two modes:
+ * mode="api" (default) — MuAPI does download / transcribe / LLM / autocrop.
+ Fast, no local deps, pay-per-call.
+ * mode="local" — yt-dlp + faster-whisper + OpenAI + ffmpeg/opencv.
+ Self-hosted, OPENAI_API_KEY required for the LLM.
"""
from typing import Dict, List, Optional
from .clipper import crop_highlights
from .downloader import download_youtube
-from .highlights import get_highlights
+from .highlights import call_muapi_llm, get_highlights
from .transcriber import transcribe
-def generate_shorts(
+def _run_local(
youtube_url: str,
- num_clips: int = 3,
- aspect_ratio: str = "9:16",
- download_format: str = "720",
- language: Optional[str] = None,
+ num_clips: int,
+ aspect_ratio: str,
+ download_format: str,
+ language: Optional[str],
) -> Dict:
- """Run the full pipeline and return a structured result.
+ from .local.clipper import crop_highlights_local
+ from .local.downloader import download_youtube_local
+ from .local.llm import call_openai_llm
+ from .local.transcriber import transcribe_local
- Returns:
- {
- "source_video_url": str, # MuAPI-hosted mp4
- "transcript": {...},
- "highlights": [...], # all candidates ranked
- "shorts": [...], # top `num_clips` with clip_url
- }
- """
+ source_path = download_youtube_local(youtube_url, fmt=download_format)
+
+ transcript = transcribe_local(source_path, language=language)
+ if not transcript["segments"]:
+ raise RuntimeError(
+ "Whisper produced no segments. The video may have no detectable speech."
+ )
+
+ highlights_result = get_highlights(transcript, num_clips=num_clips, llm_fn=call_openai_llm)
+ all_highlights: List[Dict] = highlights_result.get("highlights", [])
+ if not all_highlights:
+ raise RuntimeError("Highlight generator returned zero clips.")
+
+ top = sorted(all_highlights, key=lambda h: int(h.get("score", 0)), reverse=True)[:num_clips]
+ print(f"[pipeline/local] cropping {len(top)} of {len(all_highlights)} candidates", flush=True)
+
+ shorts = crop_highlights_local(source_path, top, aspect_ratio=aspect_ratio)
+
+ return {
+ "mode": "local",
+ "source_video_url": source_path,
+ "transcript": transcript,
+ "highlights": all_highlights,
+ "shorts": shorts,
+ }
+
+
+def _run_api(
+ youtube_url: str,
+ num_clips: int,
+ aspect_ratio: str,
+ download_format: str,
+ language: Optional[str],
+) -> Dict:
source_url = download_youtube(youtube_url, fmt=download_format)
transcript = transcribe(source_url, language=language)
@@ -36,7 +68,7 @@ def generate_shorts(
"Whisper produced no segments. The video may have no detectable speech."
)
- highlights_result = get_highlights(transcript, num_clips=num_clips)
+ highlights_result = get_highlights(transcript, num_clips=num_clips, llm_fn=call_muapi_llm)
all_highlights: List[Dict] = highlights_result.get("highlights", [])
if not all_highlights:
raise RuntimeError("Highlight generator returned zero clips.")
@@ -47,8 +79,45 @@ def generate_shorts(
shorts = crop_highlights(source_url, top, aspect_ratio=aspect_ratio)
return {
+ "mode": "api",
"source_video_url": source_url,
"transcript": transcript,
"highlights": all_highlights,
"shorts": shorts,
}
+
+
+def generate_shorts(
+ youtube_url: str,
+ num_clips: int = 3,
+ aspect_ratio: str = "9:16",
+ download_format: str = "720",
+ language: Optional[str] = None,
+ mode: str = "api",
+) -> Dict:
+ """Run the full pipeline and return a structured result.
+
+ Args:
+ youtube_url: source URL.
+ num_clips: how many shorts to render.
+ aspect_ratio: e.g. "9:16", "1:1".
+ download_format: source resolution ("360" / "480" / "720" / "1080").
+ language: ISO-639-1 to force Whisper language detection.
+ mode: "api" (default, MuAPI) or "local" (yt-dlp + faster-whisper +
+ OpenAI + ffmpeg).
+
+ Returns:
+ {
+ "mode": "api" | "local",
+ "source_video_url": str, # hosted URL (api) or local path (local)
+ "transcript": {...},
+ "highlights": [...], # all candidates ranked
+ "shorts": [...], # top `num_clips` with clip_url / local path
+ }
+ """
+ mode = (mode or "api").lower()
+ if mode == "local":
+ return _run_local(youtube_url, num_clips, aspect_ratio, download_format, language)
+ if mode == "api":
+ return _run_api(youtube_url, num_clips, aspect_ratio, download_format, language)
+ raise ValueError(f"Unknown mode: {mode!r}. Use 'api' or 'local'.")