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.
Python 2short-ai-alternativeai-clip-generatorai-clippingauto-clipauto-crophighlight-detectionklap-alternativellmopen-sourceopus-clip-alternativereelsshorts-makersubmagic-alternativetiktokvertical-videovideo-editingvidyo-ai-alternativeviral-clipswhisperyoutube-shorts
Initial commit: AI YouTube Shorts Generator (MuAPI edition)
Anil Matcha282f2cb9bbe6
diff --git a/.env.example b/.env.examplenew file mode 100644index 0000000..93164e4--- /dev/null+++ b/.env.example@@ -0,0 +1 @@+MUAPI_API_KEY=your_muapi_key_herediff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..e189328--- /dev/null+++ b/.gitignore@@ -0,0 +1,8 @@+.env+__pycache__/+*.pyc+.venv/+venv/+output/+*.mp4+.DS_Storediff --git a/README.md b/README.mdnew file mode 100644index 0000000..141f70c--- /dev/null+++ b/README.md@@ -0,0 +1,154 @@+# AI YouTube Shorts Generator — Open-Source Opus Clip Alternative++Turn any long-form YouTube video into multiple viral-ready vertical shorts with one command. Powered end-to-end by [MuAPI](https://muapi.ai) — YouTube download, GPT highlight detection, and smart auto-cropping all run through a single API.++> ### Looking for a fully open-source Opus Clip alternative?+> Check out **[Open-Generative-AI](https://github.com/Anil-matcha/Open-Generative-AI)** — a free, self-hostable Opus Clip alternative that pairs perfectly with this generator. If you want a UI on top of this pipeline, start there.++This is a clean rewrite of [SamurAIGPT/AI-Youtube-Shorts-Generator](https://github.com/SamurAIGPT/AI-Youtube-Shorts-Generator) using the AI clip logic from [ViralVadoo](https://www.vadoo.tv) and the MuAPI platform — no FaceCrop OpenCV pipeline, no Sieve, no managed Whisper backend. Just three API calls plus local Whisper.++---++## Why this exists++Opus Clip is the standard tool for turning podcasts and long videos into shorts, but it is closed-source, expensive, and hides its prompts and ranking logic. This repo is a transparent, hackable alternative:++- **You own the prompts.** The full virality scoring system is in [`shorts_generator/highlights.py`](shorts_generator/highlights.py) — tweak it freely.+- **You own the costs.** Pay-per-call MuAPI pricing instead of monthly seats.+- **You own the output.** All clips returned as direct mp4 URLs.++For an off-the-shelf UI experience, point [Open-Generative-AI](https://github.com/Anil-matcha/Open-Generative-AI) at this backend.++---++## How it works++```+YouTube URL+ │+ ▼+[1] MuAPI /youtube-download → hosted source mp4+ │+ ▼+[2] Local Whisper → timestamped transcript+ │+ ▼+[3] MuAPI /gpt-5-4 → ranked viral highlights (with hooks + scores)+ │+ ▼+[4] MuAPI /autocrop → vertical 9:16 short for each highlight+ │+ ▼+N viral-ready mp4 URLs+```++The highlight prompt is built from a virality framework that ranks signals — hook moments, emotional peaks, opinion bombs, revelation moments, conflict, quotable one-liners, story peaks, and practical value. Long videos (>30 min) are auto-chunked with overlap so nothing gets missed.++---++## Setup++```bash+git clone <this-repo>+cd ai-youtube-shorts-muapi++python -m venv .venv && source .venv/bin/activate+pip install -r requirements.txt++# ffmpeg is required for Whisper+brew install ffmpeg # macOS+# sudo apt install ffmpeg # Ubuntu++cp .env.example .env+# edit .env and set MUAPI_API_KEY=... (get one at https://muapi.ai)+```++---++## Usage++```bash+python main.py "https://www.youtube.com/watch?v=dQw4w9WgXcQ" \+ --num-clips 3 \+ --aspect-ratio 9:16 \+ --whisper-model base+```++Output:++```+========================================================================+Source video: https://cdn.muapi.ai/.../video.mp4+Highlights: 7 candidates → kept top 3+========================================================================++#1 score=92 124.3s → 187.6s+ title: The one mistake that cost me $50K+ hook: "Nobody talks about this, but it killed my first startup..."+ clip: https://cdn.muapi.ai/.../short_1.mp4++#2 score=88 ...+```++### Flags++| Flag | Default | Notes |+|------|---------|-------|+| `--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` | — | Write the full result (transcript + all highlights) to a file |++---++## Use it as a library++```python+from shorts_generator import generate_shorts++result = generate_shorts(+ "https://www.youtube.com/watch?v=...",+ num_clips=5,+ aspect_ratio="9:16",+)++for short in result["shorts"]:+ print(short["score"], short["title"], short["clip_url"])+```++---++## Project structure++```+ai-youtube-shorts-muapi/+├── main.py CLI entry point+├── requirements.txt+├── .env.example+└── shorts_generator/+ ├── __init__.py+ ├── config.py loads MUAPI_API_KEY+ ├── muapi.py generic submit + poll wrapper+ ├── downloader.py /youtube-download+ ├── transcriber.py local Whisper+ ├── highlights.py /gpt-5-4 + virality prompt + chunking + dedupe+ ├── clipper.py /autocrop+ └── pipeline.py end-to-end orchestrator+```++---++## Credits++- Original concept: [SamurAIGPT/AI-Youtube-Shorts-Generator](https://github.com/SamurAIGPT/AI-Youtube-Shorts-Generator)+- AI clip / virality logic: [ViralVadoo](https://www.vadoo.tv)+- Underlying APIs: [MuAPI](https://muapi.ai)+- Companion full-stack Opus Clip alternative: **[Open-Generative-AI](https://github.com/Anil-matcha/Open-Generative-AI)**++---++## License++MITdiff --git a/main.py b/main.pynew file mode 100644index 0000000..3b1e36c--- /dev/null+++ b/main.py@@ -0,0 +1,60 @@+"""CLI entry point.++Usage:+ python main.py "https://www.youtube.com/watch?v=..." \+ --num-clips 3 --aspect-ratio 9:16 --whisper-model base+"""+import argparse+import json+import sys++from shorts_generator import generate_shorts+++def main() -> int:+ parser = argparse.ArgumentParser(description="AI YouTube Shorts Generator (MuAPI edition)")+ parser.add_argument("url", help="YouTube video URL")+ 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()++ try:+ result = generate_shorts(+ youtube_url=args.url,+ 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:+ print(f"\nFAILED: {e}", file=sys.stderr)+ return 1++ print("\n" + "=" * 72)+ print(f"Source video: {result['source_video_url']}")+ print(f"Highlights: {len(result['highlights'])} candidates → kept top {len(result['shorts'])}")+ print("=" * 72)+ for i, s in enumerate(result["shorts"], 1):+ print(f"\n#{i} score={s.get('score')} {s.get('start_time'):.1f}s → {s.get('end_time'):.1f}s")+ print(f" title: {s.get('title')}")+ print(f" hook: {s.get('hook_sentence')}")+ if s.get("clip_url"):+ print(f" clip: {s['clip_url']}")+ else:+ print(f" clip: FAILED ({s.get('error')})")++ if args.output_json:+ with open(args.output_json, "w") as f:+ json.dump(result, f, indent=2)+ print(f"\nFull JSON written to {args.output_json}")++ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/requirements.txt b/requirements.txtnew file mode 100644index 0000000..1c3c7e9--- /dev/null+++ b/requirements.txt@@ -0,0 +1,3 @@+requests>=2.31+python-dotenv>=1.0+openai-whisper>=20231117diff --git a/shorts_generator/__init__.py b/shorts_generator/__init__.pynew file mode 100644index 0000000..cf2a70d--- /dev/null+++ b/shorts_generator/__init__.py@@ -0,0 +1,3 @@+from .pipeline import generate_shorts++__all__ = ["generate_shorts"]diff --git a/shorts_generator/clipper.py b/shorts_generator/clipper.pynew file mode 100644index 0000000..b7961f7--- /dev/null+++ b/shorts_generator/clipper.py@@ -0,0 +1,41 @@+"""Per-clip cropping via MuAPI /autocrop.++Given the source video URL plus a highlight's start/end and a target aspect+ratio, MuAPI returns a vertically-cropped short ready for posting.+"""+from typing import Dict++from . import muapi+from .downloader import _extract_video_url+++def crop_clip(source_video_url: str, start_time: float, end_time: float, aspect_ratio: str = "9:16") -> str:+ """Submit one autocrop job and return the URL of the rendered short."""+ payload = {+ "video_url": source_video_url,+ "start_time": float(start_time),+ "end_time": float(end_time),+ "aspect_ratio": aspect_ratio,+ }+ print(f"[clip] {start_time:.1f}s → {end_time:.1f}s @ {aspect_ratio}", flush=True)+ result = muapi.run("autocrop", payload, label=f"autocrop({start_time:.0f}-{end_time:.0f})")+ return _extract_video_url(result)+++def crop_highlights(source_video_url: str, highlights: list, aspect_ratio: str = "9:16") -> list:+ """Crop every highlight, attaching the resulting URL back onto the dict."""+ out = []+ for i, h in enumerate(highlights, 1):+ print(f"[clip] {i}/{len(highlights)}: {h.get('title', '(untitled)')}", flush=True)+ try:+ url = crop_clip(+ source_video_url,+ h["start_time"],+ h["end_time"],+ aspect_ratio=aspect_ratio,+ )+ out.append({**h, "clip_url": url})+ except Exception as e:+ print(f"[clip] {i} failed: {e}", flush=True)+ out.append({**h, "clip_url": None, "error": str(e)})+ return outdiff --git a/shorts_generator/config.py b/shorts_generator/config.pynew file mode 100644index 0000000..acbebaf--- /dev/null+++ b/shorts_generator/config.py@@ -0,0 +1,19 @@+import os++from dotenv import load_dotenv++load_dotenv()++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"))+++def require_api_key() -> str:+ if not MUAPI_API_KEY:+ raise RuntimeError(+ "MUAPI_API_KEY is not set. Add it to your .env file or export it as an env var."+ )+ return MUAPI_API_KEYdiff --git a/shorts_generator/downloader.py b/shorts_generator/downloader.pynew file mode 100644index 0000000..7462763--- /dev/null+++ b/shorts_generator/downloader.py@@ -0,0 +1,36 @@+"""YouTube source video download via MuAPI /youtube-download."""+from typing import Dict++from . import muapi+++def _extract_video_url(result: Dict) -> str:+ """MuAPI result shapes vary by endpoint — try common keys."""+ for key in ("video_url", "url", "output_url", "result_url"):+ v = result.get(key)+ if isinstance(v, str) and v.startswith("http"):+ return v++ output = result.get("output") or result.get("result") or {}+ if isinstance(output, dict):+ for key in ("video_url", "url", "output_url"):+ v = output.get(key)+ if isinstance(v, str) and v.startswith("http"):+ return v+ if isinstance(output, list) and output and isinstance(output[0], str) and output[0].startswith("http"):+ return output[0]++ raise RuntimeError(f"Could not find downloaded video URL in MuAPI response: {result}")+++def download_youtube(video_url: str, fmt: str = "720") -> str:+ """Hand a YouTube URL to MuAPI; return a hosted mp4 URL we can read from."""+ print(f"[download] requesting {video_url} @ {fmt}p", flush=True)+ result = muapi.run(+ "youtube-download",+ {"video_url": video_url, "format": fmt},+ label="youtube-download",+ )+ out = _extract_video_url(result)+ print(f"[download] ready: {out}", flush=True)+ return outdiff --git a/shorts_generator/highlights.py b/shorts_generator/highlights.pynew file mode 100644index 0000000..5db6ae3--- /dev/null+++ b/shorts_generator/highlights.py@@ -0,0 +1,191 @@+"""Find the most viral-worthy highlights in a transcript via MuAPI gpt-5-4.++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+"""+import json+import re+from typing import Dict, List++from . import muapi+++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).+Respond with JSON only: {"content_type": "...", "density": "..."}"""+++VIRALITY_CRITERIA = """+Virality signals to prioritize (ranked by impact):+1. HOOK MOMENTS — statements that create immediate curiosity ("The secret is...", "Nobody talks about...", "I was completely wrong about...")+2. EMOTIONAL PEAKS — genuine surprise, laughter, anger, vulnerability, excitement; raw unscripted reactions+3. OPINION BOMBS — strong, polarizing or counter-intuitive statements that trigger agree/disagree+4. REVELATION MOMENTS — surprising facts, stats, or confessions that reframe how the viewer thinks+5. CONFLICT/TENSION — disagreement, pushback, or a problem being confronted head-on+6. QUOTABLE ONE-LINERS — a sentence that works as a standalone quote card+7. STORY PEAKS — the climax or twist of an anecdote; the payoff moment+8. PRACTICAL VALUE — a concrete tip, hack, or insight the viewer can immediately apply+"""+++HIGHLIGHT_SYSTEM_PROMPT = """You are an elite short-form video editor who has studied thousands of viral clips on TikTok, Instagram Reels, and YouTube Shorts. You know exactly what makes viewers stop scrolling, watch to the end, and share.++{virality_criteria}++Content type: {content_type} | Density: {density}++Your task: identify the most viral-worthy highlights from the transcript.++Rules:+- Every highlight must open with a strong HOOK — a line that grabs attention within the first 3 seconds+- Duration sweet spot: 45-90 seconds. Go shorter (20-44s) only for a perfect standalone one-liner. Go longer (91-180s) only when a story arc needs full context to land+- Never cut mid-sentence or mid-thought — each clip must feel complete and self-contained+- Clips must not overlap significantly with each other+- Score 0-100 on viral potential (not general quality)+- {num_clips_instruction}+- For each highlight, identify the single best "hook_sentence" — the opening line that would make someone stop scrolling+- Explain in one sentence why this clip is viral ("virality_reason")++Respond ONLY with valid JSON (no markdown, no explanation):+{{"highlights":[{{"title":"string","start_time":float,"end_time":float,"score":int,"hook_sentence":"string","virality_reason":"string"}}]}}"""+++CHUNK_SIZE_SECONDS = 1200 # 20-min chunks for long videos+LONG_VIDEO_THRESHOLD = 1800 # chunk videos longer than 30 min+CHUNK_OVERLAP_SECONDS = 60+++def _call_gpt(prompt: str) -> str:+ """Send a single text prompt to MuAPI gpt-5-4 and return the raw text."""+ result = muapi.run("gpt-5-4", {"prompt": prompt}, label="gpt-5-4")++ for key in ("output", "text", "response", "result", "content"):+ v = result.get(key)+ if isinstance(v, str) and v.strip():+ return v+ if isinstance(v, dict):+ inner = v.get("text") or v.get("content")+ if isinstance(inner, str) and inner.strip():+ return inner+ if isinstance(v, list) and v and isinstance(v[0], str):+ return v[0]++ raise RuntimeError(f"Could not extract gpt-5-4 text from response: {result}")+++def _parse_json_loose(raw: str) -> Dict:+ """gpt-5-4 sometimes wraps JSON in markdown fences — strip and parse."""+ text = raw.strip()+ text = re.sub(r"^```(?:json)?\s*", "", text)+ text = re.sub(r"\s*```$", "", text)+ try:+ return json.loads(text)+ except json.JSONDecodeError:+ start = text.find("{")+ end = text.rfind("}")+ if start != -1 and end != -1:+ return json.loads(text[start:end + 1])+ raise+++def detect_content_type(transcript: Dict) -> 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)+ return _parse_json_loose(raw)+ except Exception:+ return {"content_type": "other", "density": "medium"}+++def build_transcript_text(transcript: Dict) -> str:+ segments = transcript.get("segments", [])+ return "\n".join(f"[{s['start']:.1f}s] {s['text'].strip()}" for s in segments)+++def chunk_transcript(transcript: Dict) -> List[Dict]:+ segments = transcript.get("segments", [])+ duration = transcript.get("duration", segments[-1]["end"] if segments else 0)+ chunks = []+ start = 0+ while start < duration:+ end = min(start + CHUNK_SIZE_SECONDS, duration)+ chunk_segs = [+ s for s in segments+ if s["start"] >= start and s["end"] <= end + CHUNK_OVERLAP_SECONDS+ ]+ if chunk_segs:+ chunk = dict(transcript)+ chunk["segments"] = chunk_segs+ chunk["duration"] = end - start+ chunk["_offset"] = start+ chunks.append(chunk)+ start += CHUNK_SIZE_SECONDS - CHUNK_OVERLAP_SECONDS+ 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))+ system = HIGHLIGHT_SYSTEM_PROMPT.format(+ virality_criteria=VIRALITY_CRITERIA,+ content_type=content_info.get("content_type", "other"),+ density=content_info.get("density", "medium"),+ num_clips_instruction=f"Generate at least {min_clips} highlights",+ )+ full_prompt = f"{system}\n\nTranscript:\n{transcript_text}"+ raw = _call_gpt(full_prompt)+ return _parse_json_loose(raw)+++def dedupe_highlights(highlights: List[Dict]) -> List[Dict]:+ """Drop a highlight if it overlaps >50% with a higher-scoring one already kept."""+ highlights = sorted(highlights, key=lambda x: int(x.get("score", 0)), reverse=True)+ kept: List[Dict] = []+ for h in highlights:+ h_start = float(h["start_time"])+ h_end = float(h["end_time"])+ h_dur = h_end - h_start+ overlapping = False+ for k in kept:+ latest_start = max(h_start, float(k["start_time"]))+ earliest_end = min(h_end, float(k["end_time"]))+ overlap = earliest_end - latest_start+ if overlap > 0 and overlap > 0.5 * h_dur:+ overlapping = True+ break+ if not overlapping:+ kept.append(h)+ return kept+++def get_highlights(transcript: Dict) -> 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:+ chunks = chunk_transcript(transcript)+ print(f"[highlights] long video — splitting into {len(chunks)} chunks", flush=True)+ all_highlights: List[Dict] = []+ for i, chunk in enumerate(chunks):+ 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)+ for h in result.get("highlights", []):+ h["start_time"] = float(h["start_time"]) + offset+ h["end_time"] = float(h["end_time"]) + offset+ all_highlights.append(h)+ highlights = dedupe_highlights(all_highlights)+ else:+ text = build_transcript_text(transcript)+ result = call_highlight_api(text, content_info, duration)+ highlights = dedupe_highlights(result.get("highlights", []))++ return {"highlights": highlights}diff --git a/shorts_generator/muapi.py b/shorts_generator/muapi.pynew file mode 100644index 0000000..d7a8e7a--- /dev/null+++ b/shorts_generator/muapi.py@@ -0,0 +1,77 @@+"""Thin MuAPI client: submit a job, poll until it finishes, return the result."""+import time+from typing import Any, Dict, Optional++import requests++from .config import (+ MUAPI_BASE_URL,+ POLL_INTERVAL_SECONDS,+ POLL_TIMEOUT_SECONDS,+ require_api_key,+)+++class MuAPIError(RuntimeError):+ pass+++def _headers() -> Dict[str, str]:+ return {+ "Content-Type": "application/json",+ "x-api-key": require_api_key(),+ }+++def submit(endpoint: str, payload: Dict[str, Any]) -> str:+ """POST to /api/v1/{endpoint} and return the request_id."""+ url = f"{MUAPI_BASE_URL}/{endpoint.lstrip('/')}"+ resp = requests.post(url, json=payload, headers=_headers(), timeout=60)+ if resp.status_code >= 400:+ raise MuAPIError(f"{endpoint} submit failed [{resp.status_code}]: {resp.text}")+ data = resp.json()+ request_id = data.get("request_id") or data.get("id")+ if not request_id:+ raise MuAPIError(f"{endpoint} response had no request_id: {data}")+ return str(request_id)+++def fetch_result(request_id: str) -> Dict[str, Any]:+ """GET the latest result for a request_id."""+ url = f"{MUAPI_BASE_URL}/predictions/{request_id}/result"+ resp = requests.get(url, headers=_headers(), timeout=30)+ if resp.status_code >= 400:+ raise MuAPIError(f"poll failed [{resp.status_code}]: {resp.text}")+ return resp.json()+++def poll(+ request_id: str,+ interval: float = POLL_INTERVAL_SECONDS,+ timeout: float = POLL_TIMEOUT_SECONDS,+ label: Optional[str] = None,+) -> Dict[str, Any]:+ """Block until the prediction is done; return the final payload."""+ deadline = time.time() + timeout+ last_status = None+ while time.time() < deadline:+ data = fetch_result(request_id)+ status = (data.get("status") or "").lower()+ if status and status != last_status:+ print(f"[muapi] {label or request_id}: {status}", flush=True)+ last_status = status++ if status in ("completed", "succeeded", "success"):+ return data+ if status in ("failed", "error"):+ raise MuAPIError(f"{label or request_id} failed: {data}")++ time.sleep(interval)++ 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]:+ """Submit then poll. Returns the final result payload."""+ request_id = submit(endpoint, payload)+ return poll(request_id, label=label or endpoint)diff --git a/shorts_generator/pipeline.py b/shorts_generator/pipeline.pynew file mode 100644index 0000000..73e6f4a--- /dev/null+++ b/shorts_generator/pipeline.py@@ -0,0 +1,55 @@+"""End-to-end orchestrator.++YouTube URL → MuAPI download → local Whisper transcript+ → MuAPI gpt-5-4 highlights → MuAPI autocrop clips+"""+from typing import Dict, List, Optional++from .clipper import crop_highlights+from .downloader import download_youtube+from .highlights import get_highlights+from .transcriber import transcribe+++def generate_shorts(+ youtube_url: str,+ 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.++ Returns:+ {+ "source_video_url": str, # MuAPI-hosted mp4+ "transcript": {...},+ "highlights": [...], # all candidates ranked+ "shorts": [...], # top `num_clips` with clip_url+ }+ """+ source_url = download_youtube(youtube_url, fmt=download_format)++ transcript = transcribe(source_url, model_size=whisper_model, language=language)+ if not transcript["segments"]:+ raise RuntimeError(+ "Whisper produced no segments. The video may have no detectable speech."+ )++ highlights_result = get_highlights(transcript)+ 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] cropping {len(top)} of {len(all_highlights)} candidates", flush=True)++ shorts = crop_highlights(source_url, top, aspect_ratio=aspect_ratio)++ return {+ "source_video_url": source_url,+ "transcript": transcript,+ "highlights": all_highlights,+ "shorts": shorts,+ }diff --git a/shorts_generator/transcriber.py b/shorts_generator/transcriber.pynew file mode 100644index 0000000..dcb98fb--- /dev/null+++ b/shorts_generator/transcriber.py@@ -0,0 +1,88 @@+"""Local Whisper transcription.++Takes the hosted mp4 URL returned by MuAPI's /youtube-download, streams it to+disk, runs OpenAI's open-source Whisper model locally, and emits the segment+shape expected by the highlight generator: {duration, segments[start,end,text]}.+"""+import os+import shutil+import tempfile+from typing import Dict, Optional++import requests+++_WHISPER_MODEL = None+++def _load_model(model_size: str):+ """Lazy-load whisper. Cached across calls so we only pay model-load cost once."""+ global _WHISPER_MODEL+ if _WHISPER_MODEL is not None:+ return _WHISPER_MODEL++ try:+ import whisper+ except ImportError as e:+ raise RuntimeError(+ "openai-whisper is not installed. Run: pip install -U openai-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"+ )++ print(f"[transcribe] loading whisper model '{model_size}' (first run downloads weights)", flush=True)+ _WHISPER_MODEL = whisper.load_model(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 Whisper on a hosted media URL. Returns {duration, segments[...]}.++ model_size: tiny | base | small | medium | large — 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)+ result = model.transcribe(+ local_path,+ language=language,+ verbose=False,+ )+ finally:+ try:+ os.remove(local_path)+ except OSError:+ pass++ segments = []+ for s in result.get("segments", []):+ segments.append({+ "start": float(s["start"]),+ "end": float(s["end"]),+ "text": (s.get("text") or "").strip(),+ })++ duration = 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}