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.

feat: replace local Whisper with MuAPI /openai-whisper, tighten LLM timeouts

Anil Matcha57e261e6d44e
diff --git a/.claude/skills/youtube-shorts-generator/SKILL.md b/.claude/skills/youtube-shorts-generator/SKILL.md
index a160597..a7c8789 100644
--- a/.claude/skills/youtube-shorts-generator/SKILL.md
+++ b/.claude/skills/youtube-shorts-generator/SKILL.md
@@ -1,6 +1,6 @@
---
name: youtube-shorts-generator
-description: Generate viral 9:16 YouTube Shorts (or TikTok/Reels clips) from a long-form YouTube URL or local video. Triggers on requests like "make shorts from this video", "extract viral clips from this YouTube link", "auto-clip this podcast", "find the best moments and crop vertical". Pipeline downloads the source, transcribes with local Whisper, ranks highlights through a virality framework (hook / emotional peak / opinion bomb / revelation / conflict / quotable / story peak / practical value), dedupes overlapping candidates, and vertically auto-crops the top N as mp4s.
+description: Generate viral 9:16 YouTube Shorts (or TikTok/Reels clips) from a long-form YouTube URL or local video. Triggers on requests like "make shorts from this video", "extract viral clips from this YouTube link", "auto-clip this podcast", "find the best moments and crop vertical". Pipeline downloads the source, transcribes via MuAPI /openai-whisper, ranks highlights through a virality framework (hook / emotional peak / opinion bomb / revelation / conflict / quotable / story peak / practical value), dedupes overlapping candidates, and vertically auto-crops the top N as mp4s.
---
# YouTube Shorts Generator
@@ -24,17 +24,15 @@ Ask once, then proceed:
1. **Source** — YouTube URL (preferred) or path/URL to an mp4
2. **`num_clips`** — default 3
3. **`aspect_ratio`** — default `9:16` (also: `1:1`, `4:5`)
-4. **`whisper_model`** — default `base` (`tiny` / `base` / `small` / `medium` / `large`)
-5. **`language`** — default auto-detect
-6. **Output JSON path** — optional; if set, dump full result there
+4. **`language`** — default auto-detect (forwarded to MuAPI Whisper as ISO-639-1)
+5. **Output JSON path** — optional; if set, dump full result there
If the user gave a URL and nothing else, use defaults and don't block on questions.
## Prerequisites (verify before first run)
- Python 3.10+
-- `ffmpeg` on PATH (`brew install ffmpeg` on macOS, `apt install ffmpeg` on Ubuntu)
-- A clipping/highlight backend API key — set `MUAPI_API_KEY` in `.env`. If missing, stop and ask the user for it; do not invent one.
+- A MuAPI key — set `MUAPI_API_KEY` in `.env`. Powers download, transcription, highlight ranking, and clipping. If missing, stop and ask the user for it; do not invent one.
- `pip install -r requirements.txt` inside a venv
If the repo isn't cloned yet, clone `https://github.com/SamurAIGPT/AI-Youtube-Shorts-Generator.git` into the working directory.
@@ -44,7 +42,7 @@ If the repo isn't cloned yet, clone `https://github.com/SamurAIGPT/AI-Youtube-Sh
Run the eight stages in order. Each maps to a module in `shorts_generator/`.
1. **Download** (`downloader.py`) — pull the source video at the requested resolution (`360`/`480`/`720`/`1080`, default `720`).
-2. **Transcribe** (`transcriber.py`) — local Whisper produces timestamped segments. Don't ship audio to a managed API; stays on the machine.
+2. **Transcribe** (`transcriber.py`) — MuAPI `/openai-whisper` runs Whisper server-side and returns timestamped `verbose_json` segments. Billed per minute of audio.
3. **Classify content type** — LLM tags the video (podcast / interview / tutorial / vlog / lecture / monologue) and density. Tune the highlight prompt per type.
4. **Chunk if long** (`highlights.py`) — videos > `LONG_VIDEO_THRESHOLD` (1800s default) are split into `CHUNK_SIZE_SECONDS` (1200s default) windows with `CHUNK_OVERLAP_SECONDS` (60s default) overlap so cross-boundary highlights aren't missed.
5. **Rank highlights** — LLM scans each chunk through `VIRALITY_CRITERIA`:
@@ -69,7 +67,6 @@ CLI (the standard path):
python main.py "<YOUTUBE_URL>" \
--num-clips 5 \
--aspect-ratio 9:16 \
- --whisper-model base \
--output-json result.json
```
@@ -82,7 +79,6 @@ result = generate_shorts(
"<URL>",
num_clips=5,
aspect_ratio="9:16",
- whisper_model="base",
)
for short in result["shorts"]:
print(short["score"], short["title"], short["clip_url"])
@@ -101,7 +97,6 @@ xargs -a urls.txt -I{} python main.py "{}"
| `--num-clips` | `3` | How many shorts to render |
| `--aspect-ratio` | `9:16` | `9:16` for TikTok/Reels, `1:1` square, anything else by flag |
| `--format` | `720` | Source download resolution |
-| `--whisper-model` | `base` | `tiny` / `base` / `small` / `medium` / `large` |
| `--language` | auto | Whisper language code (e.g. `en`) |
| `--output-json` | — | Dump full result (transcript + all candidates + clip URLs) |
@@ -140,18 +135,13 @@ When reporting back to the user, surface for each clip: rank, score, time range,
- `MUAPI_POLL_INTERVAL` — 5s
- `MUAPI_POLL_TIMEOUT` — 1800s
-## Whisper model selection
+## Whisper transcription
-- `tiny` / `base` — fast, English-leaning, fine for clean studio audio
-- `small` / `medium` — better for accents and music beds
-- `large` — highest accuracy, much slower; only worth it on a GPU
-
-Pick `base` unless the user complains about transcript quality, then bump to `medium`.
+Audio is transcribed by MuAPI's `/openai-whisper` endpoint (server-side `whisper-1`, billed per minute). The CLI passes `--language` straight through; leave it empty for auto-detection, or pass an ISO-639-1 code (e.g. `en`) to lock it.
## Failure modes — handle, don't paper over
-- **`ffmpeg not found on PATH`** — stop and tell the user how to install. Don't try to skip it; Whisper needs it for audio decoding.
-- **Whisper produced no segments** — likely no detectable speech or a hard language. Retry with `--whisper-model medium --language <code>` before declaring failure.
+- **Whisper produced no segments** — likely no detectable speech or a hard language. Retry with `--language <code>` (correct ISO-639-1) before declaring failure.
- **API key missing or rejected** — surface the exact error; never fabricate a key.
- **Job timed out** — bump `MUAPI_POLL_TIMEOUT` and retry; don't silently truncate.
- **Highlight ranker returned <`num_clips`** — return what survived dedupe with a note; don't pad with low-score filler.
diff --git a/README.md b/README.md
index 6775a7f..79b8fd4 100644
--- a/README.md
+++ b/README.md
@@ -15,7 +15,7 @@ https://muapi.ai/playground/ai-clipping
- **🎬 YouTube In, Vertical Out**: Hand it any YouTube URL — get back N viral-ready 9:16 mp4s
- **🤖 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
-- **🎤 Local Whisper Transcription**: No managed transcription service — your audio stays on your machine
+- **🎤 Cloud Whisper Transcription**: Audio is transcribed via MuAPI's `/openai-whisper` endpoint — no local model download, no GPU needed
- **🧩 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
@@ -34,8 +34,7 @@ Want better results without the setup? The [AI Clipping API](https://muapi.ai/pl
### Prerequisites
- Python 3.10+
-- FFmpeg (required by Whisper)
-- An API key for the clipping/highlight backend
+- A MuAPI key (powers download, transcription, highlight ranking, and clipping)
### Steps
@@ -45,33 +44,18 @@ Want better results without the setup? The [AI Clipping API](https://muapi.ai/pl
cd AI-Youtube-Shorts-Generator
```
-2. **Install system dependencies:**
-
- **Ubuntu/Debian:**
- ```bash
- sudo apt install -y ffmpeg
- ```
-
- **macOS:**
- ```bash
- brew install ffmpeg
- ```
-
- **Windows:**
- - Install [FFmpeg](https://ffmpeg.org/download.html) and add it to PATH
-
-3. **Create and activate a virtual environment:**
+2. **Create and activate a virtual environment:**
```bash
python3.10 -m venv venv
source venv/bin/activate
```
-4. **Install Python dependencies:**
+3. **Install Python dependencies:**
```bash
pip install -r requirements.txt
```
-5. **Set up environment variables:**
+4. **Set up environment variables:**
Create a `.env` file in the project root (copy from `.env.example`):
```bash
@@ -92,7 +76,6 @@ python main.py "https://www.youtube.com/watch?v=VIDEO_ID"
python main.py "https://www.youtube.com/watch?v=VIDEO_ID" \
--num-clips 5 \
--aspect-ratio 9:16 \
- --whisper-model base \
--output-json result.json
```
@@ -127,14 +110,13 @@ xargs -a urls.txt -I{} python main.py "{}"
| `--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` |
-| `--whisper-model` | `base` | `tiny` / `base` / `small` / `medium` / `large` |
| `--language` | auto | Force Whisper language code (e.g. `en`) |
| `--output-json` | — | Dump the full result (transcript + all candidates) to a file |
## How It Works
1. **Download**: Fetches the source video from YouTube
-2. **Transcribe**: Local Whisper produces a timestamped transcript
+2. **Transcribe**: MuAPI `/openai-whisper` produces a timestamped transcript (verbose_json segments)
3. **Detect content type**: An LLM classifies the video (podcast, interview, tutorial, vlog, etc.) and density, so the prompt can be tuned per content style
4. **Long-video chunking**: Videos > 30 min are split into 20-min overlapping chunks
5. **Highlight ranking**: An LLM scans the transcript through a virality framework — hook moments, emotional peaks, opinion bombs, revelations, conflict, quotables, story peaks, practical value — and emits ranked candidates with scores 0–100
@@ -197,10 +179,8 @@ Edit `shorts_generator/config.py` (or set env vars):
- `MUAPI_POLL_INTERVAL` (default 5s) — seconds between job-status polls
- `MUAPI_POLL_TIMEOUT` (default 1800s) — give up after this long
-### Whisper model size
-- `tiny` / `base` — fast, English-leaning, fine for clean speech
-- `small` / `medium` — better for accents, music backgrounds
-- `large` — highest accuracy, much slower; recommended only with a GPU
+### Whisper transcription
+Audio is transcribed by MuAPI's `/openai-whisper` endpoint (server-side `whisper-1`). Pass `--language <code>` to lock the recognition to a specific language; otherwise it auto-detects.
## Project Structure
@@ -213,7 +193,7 @@ AI-Youtube-Shorts-Generator/
├── config.py env / settings
├── muapi.py generic submit + poll wrapper
├── downloader.py YouTube source download
- ├── transcriber.py local Whisper
+ ├── transcriber.py MuAPI /openai-whisper client
├── highlights.py LLM virality ranking + chunking + dedupe
├── clipper.py vertical auto-crop
└── pipeline.py end-to-end orchestrator
@@ -221,11 +201,8 @@ AI-Youtube-Shorts-Generator/
## Troubleshooting
-### `ffmpeg not found on PATH`
-Whisper needs ffmpeg for audio decoding. Install it with `brew install ffmpeg` (macOS) or `sudo apt install ffmpeg` (Ubuntu).
-
### Whisper produced no segments
-The video may have no detectable speech, or it may be in a language Whisper struggles with. Try `--whisper-model medium` and `--language en` (or the correct language code).
+The video may have no detectable speech, or it may be in a language Whisper struggles with. Try passing `--language en` (or the correct ISO-639-1 code) to skip auto-detection.
### Looking for better results?
The [AI Clipping API](https://muapi.ai/playground/ai-clipping) uses an improved algorithm that produces higher-quality clips with better highlight detection.
diff --git a/main.py b/main.py
index 3b1e36c..f5b998e 100644
--- a/main.py
+++ b/main.py
@@ -2,7 +2,7 @@
Usage:
python main.py "https://www.youtube.com/watch?v=..." \
- --num-clips 3 --aspect-ratio 9:16 --whisper-model base
+ --num-clips 3 --aspect-ratio 9:16
"""
import argparse
import json
@@ -17,7 +17,6 @@ def main() -> int:
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)")
- parser.add_argument("--whisper-model", default="base", help="Whisper size: tiny | base | small | medium | large (default: base)")
parser.add_argument("--language", default=None, help="Force Whisper language code, e.g. 'en' (default: auto-detect)")
parser.add_argument("--output-json", default=None, help="Write the full result JSON to this path")
args = parser.parse_args()
@@ -28,7 +27,6 @@ def main() -> int:
num_clips=args.num_clips,
aspect_ratio=args.aspect_ratio,
download_format=args.format,
- whisper_model=args.whisper_model,
language=args.language,
)
except Exception as e:
diff --git a/requirements.txt b/requirements.txt
index edb59eb..5160da3 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,3 +1,2 @@
requests>=2.31
python-dotenv>=1.0
-faster-whisper>=1.0.0
diff --git a/shorts_generator/config.py b/shorts_generator/config.py
index acbebaf..2554c9b 100644
--- a/shorts_generator/config.py
+++ b/shorts_generator/config.py
@@ -8,7 +8,7 @@ MUAPI_API_KEY = os.getenv("MUAPI_API_KEY", "").strip()
MUAPI_BASE_URL = os.getenv("MUAPI_BASE_URL", "https://api.muapi.ai/api/v1").rstrip("/")
POLL_INTERVAL_SECONDS = float(os.getenv("MUAPI_POLL_INTERVAL", "5"))
-POLL_TIMEOUT_SECONDS = float(os.getenv("MUAPI_POLL_TIMEOUT", "1800"))
+POLL_TIMEOUT_SECONDS = float(os.getenv("MUAPI_POLL_TIMEOUT", "600"))
def require_api_key() -> str:
diff --git a/shorts_generator/highlights.py b/shorts_generator/highlights.py
index 8ac6977..fba625c 100644
--- a/shorts_generator/highlights.py
+++ b/shorts_generator/highlights.py
@@ -57,11 +57,17 @@ Respond ONLY with valid JSON (no markdown, no explanation):
CHUNK_SIZE_SECONDS = 1200 # 20-min chunks for long videos
LONG_VIDEO_THRESHOLD = 1800 # chunk videos longer than 30 min
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."""
- result = muapi.run("gpt-5-mini", {"prompt": prompt}, label="gpt-5-mini")
+ result = muapi.run(
+ "gpt-5-mini",
+ {"prompt": prompt},
+ label="gpt-5-mini",
+ timeout=GPT_CALL_TIMEOUT_SECONDS,
+ )
outputs = result.get("outputs")
if isinstance(outputs, list) and outputs and isinstance(outputs[0], str) and outputs[0].strip():
@@ -133,8 +139,18 @@ def chunk_transcript(transcript: Dict) -> List[Dict]:
return chunks
-def call_highlight_api(transcript_text: str, content_info: Dict, duration: float, is_chunk: bool = False) -> Dict:
- min_clips = max(2 if is_chunk else 3, int(duration / 90))
+def call_highlight_api(
+ transcript_text: str,
+ content_info: Dict,
+ duration: float,
+ num_clips: int,
+ is_chunk: bool = False,
+) -> 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).
+ target = max(num_clips * 2, 5)
+ natural_max = max(2 if is_chunk else 3, int(duration / 90))
+ min_clips = min(target, natural_max, 8)
system = HIGHLIGHT_SYSTEM_PROMPT.format(
virality_criteria=VIRALITY_CRITERIA,
content_type=content_info.get("content_type", "other"),
@@ -167,13 +183,13 @@ def dedupe_highlights(highlights: List[Dict]) -> List[Dict]:
return kept
-def get_highlights(transcript: Dict) -> Dict:
+def get_highlights(transcript: Dict, num_clips: int = 3) -> Dict:
"""Main entry point — returns {highlights: [...]} sorted by score."""
duration = transcript.get("duration", 0)
content_info = detect_content_type(transcript)
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:
+ if duration >= LONG_VIDEO_THRESHOLD:
chunks = chunk_transcript(transcript)
print(f"[highlights] long video — splitting into {len(chunks)} chunks", flush=True)
all_highlights: List[Dict] = []
@@ -181,7 +197,7 @@ def get_highlights(transcript: Dict) -> 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"], is_chunk=True)
+ result = call_highlight_api(text, content_info, chunk["duration"], num_clips=num_clips, is_chunk=True)
for h in result.get("highlights", []):
h["start_time"] = float(h["start_time"]) + offset
h["end_time"] = float(h["end_time"]) + offset
@@ -189,7 +205,7 @@ def get_highlights(transcript: Dict) -> Dict:
highlights = dedupe_highlights(all_highlights)
else:
text = build_transcript_text(transcript)
- result = call_highlight_api(text, content_info, duration)
+ result = call_highlight_api(text, content_info, duration, num_clips=num_clips)
highlights = dedupe_highlights(result.get("highlights", []))
return {"highlights": highlights}
diff --git a/shorts_generator/muapi.py b/shorts_generator/muapi.py
index 095400a..7c079a2 100644
--- a/shorts_generator/muapi.py
+++ b/shorts_generator/muapi.py
@@ -85,7 +85,13 @@ def poll(
raise MuAPIError(f"{label or request_id} timed out after {timeout}s")
-def run(endpoint: str, payload: Dict[str, Any], label: Optional[str] = None) -> Dict[str, Any]:
+def run(
+ endpoint: str,
+ payload: Dict[str, Any],
+ label: Optional[str] = None,
+ interval: float = POLL_INTERVAL_SECONDS,
+ timeout: float = POLL_TIMEOUT_SECONDS,
+) -> Dict[str, Any]:
"""Submit then poll. Returns the final result payload."""
request_id = submit(endpoint, payload)
- return poll(request_id, label=label or endpoint)
+ return poll(request_id, interval=interval, timeout=timeout, label=label or endpoint)
diff --git a/shorts_generator/pipeline.py b/shorts_generator/pipeline.py
index 73e6f4a..1fdbdab 100644
--- a/shorts_generator/pipeline.py
+++ b/shorts_generator/pipeline.py
@@ -1,6 +1,6 @@
"""End-to-end orchestrator.
-YouTube URL → MuAPI download → local Whisper transcript
+YouTube URL → MuAPI download → MuAPI /openai-whisper transcript
→ MuAPI gpt-5-4 highlights → MuAPI autocrop clips
"""
from typing import Dict, List, Optional
@@ -16,7 +16,6 @@ def generate_shorts(
num_clips: int = 3,
aspect_ratio: str = "9:16",
download_format: str = "720",
- whisper_model: str = "base",
language: Optional[str] = None,
) -> Dict:
"""Run the full pipeline and return a structured result.
@@ -31,13 +30,13 @@ def generate_shorts(
"""
source_url = download_youtube(youtube_url, fmt=download_format)
- transcript = transcribe(source_url, model_size=whisper_model, language=language)
+ transcript = transcribe(source_url, language=language)
if not transcript["segments"]:
raise RuntimeError(
"Whisper produced no segments. The video may have no detectable speech."
)
- highlights_result = get_highlights(transcript)
+ highlights_result = get_highlights(transcript, num_clips=num_clips)
all_highlights: List[Dict] = highlights_result.get("highlights", [])
if not all_highlights:
raise RuntimeError("Highlight generator returned zero clips.")
diff --git a/shorts_generator/transcriber.py b/shorts_generator/transcriber.py
index 7538eb3..faa8fe2 100644
--- a/shorts_generator/transcriber.py
+++ b/shorts_generator/transcriber.py
@@ -1,101 +1,76 @@
-"""Local Whisper transcription.
+"""Transcription via MuAPI /openai-whisper.
-Takes the hosted mp4 URL returned by MuAPI's /youtube-download, streams it to
-disk, runs faster-whisper locally, and emits the segment shape expected by the
-highlight generator: {duration, segments[start,end,text]}.
-
-Uses faster-whisper instead of openai-whisper: resumable HF downloads, no
-SHA256 self-validation loop on a partial file, and faster CPU inference.
+Sends a hosted media URL to MuAPI's Whisper endpoint and returns the segment
+shape expected by the highlight generator: {duration, segments[start,end,text]}.
+The API runs verbose_json server-side, so we get per-segment timestamps for free.
"""
-import os
-import shutil
-import tempfile
+import json
from typing import Dict, Optional
-import requests
-
-
-_WHISPER_MODEL = None
-_WHISPER_MODEL_SIZE = None
-
-
-def _load_model(model_size: str):
- """Lazy-load faster-whisper. Cached across calls so we only pay model-load cost once."""
- global _WHISPER_MODEL, _WHISPER_MODEL_SIZE
- if _WHISPER_MODEL is not None and _WHISPER_MODEL_SIZE == model_size:
- return _WHISPER_MODEL
-
- try:
- from faster_whisper import WhisperModel
- except ImportError as e:
- raise RuntimeError(
- "faster-whisper is not installed. Run: pip install -U faster-whisper\n"
- "It also needs ffmpeg available on PATH."
- ) from e
-
- if shutil.which("ffmpeg") is None:
- raise RuntimeError(
- "ffmpeg not found on PATH. Whisper needs ffmpeg to decode media.\n"
- " macOS: brew install ffmpeg\n"
- " Ubuntu: sudo apt install ffmpeg"
- )
-
- cache_dir = os.path.join(os.path.expanduser("~"), ".cache", "faster-whisper")
- os.makedirs(cache_dir, exist_ok=True)
+from . import muapi
- print(f"[transcribe] loading faster-whisper model '{model_size}' (first run downloads weights)", flush=True)
- _WHISPER_MODEL = WhisperModel(
- model_size,
- device="cpu",
- compute_type="int8",
- download_root=cache_dir,
- )
- _WHISPER_MODEL_SIZE = model_size
- return _WHISPER_MODEL
-
-def _download_to_temp(media_url: str) -> str:
- suffix = os.path.splitext(media_url.split("?")[0])[1] or ".mp4"
- fd, path = tempfile.mkstemp(suffix=suffix, prefix="shorts_src_")
- os.close(fd)
- print(f"[transcribe] downloading source to {path}", flush=True)
- with requests.get(media_url, stream=True, timeout=120) as r:
- r.raise_for_status()
- with open(path, "wb") as f:
- for chunk in r.iter_content(chunk_size=1 << 20):
- if chunk:
- f.write(chunk)
- return path
-
-
-def transcribe(media_url: str, model_size: str = "base", language: Optional[str] = None) -> Dict:
- """Run local faster-whisper on a hosted media URL. Returns {duration, segments[...]}.
-
- model_size: tiny | base | small | medium | large-v3 — bigger = more accurate, slower.
- """
- model = _load_model(model_size)
- local_path = _download_to_temp(media_url)
- try:
- print(f"[transcribe] running whisper on {local_path}", flush=True)
- segments_iter, info = model.transcribe(
- local_path,
- language=language,
- beam_size=5,
- vad_filter=True,
- )
- segments = []
- for s in segments_iter:
- segments.append({
- "start": float(s.start),
- "end": float(s.end),
- "text": (s.text or "").strip(),
- })
- finally:
+def _coerce_verbose(raw) -> Dict:
+ """The /openai-whisper result can land as a dict or a JSON string depending on
+ how the worker stored it. Normalise to a dict with `duration` and `segments`."""
+ if isinstance(raw, str):
try:
- os.remove(local_path)
- except OSError:
- pass
-
- duration = float(getattr(info, "duration", 0.0)) or (segments[-1]["end"] if segments else 0.0)
+ return json.loads(raw)
+ except (TypeError, ValueError):
+ return {}
+ if isinstance(raw, dict):
+ return raw
+ return {}
+
+
+def _extract_verbose_payload(result: Dict) -> Dict:
+ """MuAPI wraps results inconsistently across endpoints. Hunt for the
+ verbose_json blob (which has `segments` + `duration`)."""
+ for key in ("output", "result", "outputs"):
+ v = result.get(key)
+ if isinstance(v, dict) and "segments" in v:
+ return v
+ if isinstance(v, list) and v:
+ first = v[0]
+ decoded = _coerce_verbose(first)
+ if "segments" in decoded:
+ return decoded
+ if isinstance(v, str):
+ decoded = _coerce_verbose(v)
+ if "segments" in decoded:
+ return decoded
+
+ if "segments" in result:
+ return result
+
+ raise RuntimeError(f"Could not find Whisper segments in MuAPI response: {result}")
+
+
+def transcribe(media_url: str, language: Optional[str] = None) -> Dict:
+ """Run MuAPI /openai-whisper on a hosted media URL.
+
+ Returns {duration: float, segments: [{start, end, text}, ...]} so it slots
+ straight into the highlight generator.
+ """
+ print(f"[transcribe] muapi /openai-whisper on {media_url}", flush=True)
+ payload = {
+ "audio_url": media_url,
+ "response_format": "verbose_json",
+ }
+ if language:
+ payload["language"] = language
+
+ result = muapi.run("openai-whisper", payload, label="openai-whisper")
+ verbose = _extract_verbose_payload(result)
+
+ segments = []
+ for s in verbose.get("segments") or []:
+ segments.append({
+ "start": float(s.get("start", 0.0)),
+ "end": float(s.get("end", 0.0)),
+ "text": (s.get("text") or "").strip(),
+ })
+
+ duration = float(verbose.get("duration") or (segments[-1]["end"] if segments else 0.0))
print(f"[transcribe] {len(segments)} segments, {duration:.0f}s of audio", flush=True)
return {"duration": duration, "segments": segments}