From 03477d4353cced2b5d7e64fcaa03398900b39fd3 Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Fri, 23 Jan 2026 20:24:15 +0100 Subject: [PATCH] Add ElevenLabs voice dubbing and improve project setup - Add AI voice dubbing with ElevenLabs (30+ languages) - Add TranslateModal component for language selection - Auto-transcribe dubbed videos for subtitles in new language - Add ElevenLabs API key settings in frontend - Add async_upload parameter to Upload-Post integration - Add MIT LICENSE file - Add CLAUDE.md for AI-assisted development - Update README with dubbing feature and badges Co-Authored-By: Claude Opus 4.5 --- CLAUDE.md | 102 +++++++++ LICENSE | 21 ++ README.md | 14 +- app.py | 118 +++++++++- dashboard/src/App.jsx | 64 ++++++ dashboard/src/components/ResultCard.jsx | 88 ++++++- dashboard/src/components/TranslateModal.jsx | 158 +++++++++++++ subtitles.py | 58 +++++ translate.py | 239 ++++++++++++++++++++ 9 files changed, 854 insertions(+), 8 deletions(-) create mode 100644 CLAUDE.md create mode 100644 LICENSE create mode 100644 dashboard/src/components/TranslateModal.jsx create mode 100644 translate.py diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..093db8a --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,102 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Project Overview + +OpenShorts is an AI-powered vertical video generator that transforms long YouTube videos or local uploads into viral-ready short clips (9:16 format) for TikTok, Instagram Reels, and YouTube Shorts. Uses Google Gemini 2.0 Flash for viral moment detection and title generation. + +## Development Commands + +### Local Development (Docker) +```bash +docker compose up --build # Build and run full stack +``` +- Backend: http://localhost:8000 (FastAPI/Uvicorn) +- Frontend: http://localhost:5175 (Vite proxies API calls to backend) + +### Frontend Only (Dashboard) +```bash +cd dashboard +npm install +npm run dev # Dev server with HMR (port 5173) +npm run build # Production build +npm run lint # ESLint (strict, --max-warnings 0) +``` + +### Backend Only +```bash +pip install -r requirements.txt +uvicorn app:app --host 0.0.0.0 --port 8000 +``` + +## Architecture + +### Core Processing Pipeline +1. **Ingest** - YouTube download (yt-dlp) or local upload +2. **Transcription** - faster-whisper with word-level timestamps +3. **Scene Detection** - PySceneDetect for segment boundaries +4. **AI Analysis** - Gemini identifies 3-15 viral moments (15-60 sec each) +5. **FFmpeg Extraction** - Precise clip cutting +6. **AI Cropping** - Vertical reframing with subject tracking +7. **Effects/Subtitles** - Optional AI-generated FFmpeg filters +8. **Hook Overlay** - Text overlays with styled fonts +9. **Voice Dubbing** - Optional ElevenLabs AI translation (30+ languages) +10. **S3 Backup** - Silent background upload +11. **Social Distribution** - Upload-Post API (async upload) + +### Key Files +| File | Purpose | +|------|---------| +| `main.py` | Core video processing: transcription, scene detection, clip extraction, vertical reframing | +| `app.py` | FastAPI server with async job queue and REST endpoints | +| `editor.py` | Gemini AI integration for dynamic video effects (FFmpeg filter generation) | +| `hooks.py` | Hook text overlay generation with font rendering | +| `s3_uploader.py` | AWS S3 upload with caching | +| `subtitles.py` | SRT generation, FFmpeg subtitle burning, and dubbed video transcription | +| `translate.py` | ElevenLabs dubbing API for AI voice translation | +| `dashboard/src/App.jsx` | Main React component with state management | +| `dashboard/src/components/TranslateModal.jsx` | Voice dubbing UI with language selection | + +### Dual-Mode Video Reframing +- **TRACK Mode** (single subject): MediaPipe face detection + YOLOv8 fallback with "Heavy Tripod" stabilization +- **GENERAL Mode** (groups/landscapes): Blurred background layout preserving full width + +### Key Classes +- `SmoothedCameraman` - Stabilized camera movement with safe zone logic (prevents jitter) +- `SpeakerTracker` - Prevents rapid speaker switching, handles temporary occlusions + +### API Endpoints +| Method | Route | Purpose | +|--------|-------|---------| +| POST | `/api/process` | Submit video for processing | +| GET | `/api/status/{job_id}` | Poll job status and logs | +| POST | `/api/edit` | Apply AI video effects | +| POST | `/api/subtitle` | Generate and apply subtitles (auto-transcribes dubbed videos) | +| POST | `/api/hook` | Add text hook overlays | +| POST | `/api/translate` | AI voice dubbing via ElevenLabs | +| GET | `/api/translate/languages` | List supported dubbing languages | +| POST | `/api/social/post` | Post to social media (async upload) | + +### Concurrency Model +Async job queue with semaphore-based concurrency control. Configure via `MAX_CONCURRENT_JOBS` env var (default: 5). Jobs auto-cleanup after 1 hour. + +## Environment Variables + +**Server-side (.env):** +- `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_REGION`, `AWS_S3_BUCKET` - For S3 backup +- `MAX_CONCURRENT_JOBS` - Concurrent processing limit (default: 5) +- `VITE_API_URL` - Production API URL override + +**Client-side (localStorage, encrypted):** +- `GEMINI_API_KEY` - Google Gemini API key (required) +- `ELEVENLABS_API_KEY` - ElevenLabs API key for voice dubbing (optional) +- `UPLOAD_POST_API_KEY` - Upload-Post API key for social posting (optional) + +> API keys are stored encrypted in the browser and sent via headers only when needed. Never stored server-side. + +## Tech Stack +- **Backend:** Python 3.11, FastAPI, google-genai, faster-whisper, ultralytics (YOLOv8), mediapipe, opencv-python, yt-dlp, FFmpeg, httpx +- **Frontend:** React 18, Vite 4, Tailwind CSS 3.4 +- **External APIs:** Google Gemini, ElevenLabs Dubbing, Upload-Post +- **Infrastructure:** Docker + Docker Compose, AWS S3 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..a5ad963 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 OpenShorts + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index 9707292..4fabb24 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,9 @@ # OpenShorts.app 🚀🎬 +[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) +[![Open Source](https://badges.frapsoft.com/os/v1/open-source.svg?v=103)](https://opensource.org/) +[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](http://makeapullrequest.com) + OpenShorts is an all-in-one open-source solution to automate the creation and distribution of viral vertical content. It transforms long YouTube videos or local files into high-potential short clips optimized for **TikTok**, **Instagram Reels**, and **YouTube Shorts**. ![OpenShorts Demo](https://github.com/kamilstanuch/Autocrop-vertical/blob/main/churchil_queen_vertical_short.gif?raw=true) @@ -30,11 +34,16 @@ OpenShorts leverages state-of-the-art AI to handle the entire content lifecycle: * **Silent Background Upload**: Once clips are generated, they are automatically uploaded to an AWS S3 bucket. * **Seamless Integration**: Operates in the background without affecting processing logs or UI performance. -4. **📲 Direct Social posting:** +4. **📲 Direct Social Posting:** * **Upload-Post Integration**: Share your generated clips directly to TikTok, Instagram, and YouTube with a single click. * **Profile Selector**: Manage multiple social accounts easily through the dashboard. -4. **🎨 Modern Web Dashboard:** +5. **🎙️ AI Voice Dubbing:** + * **ElevenLabs Integration**: Translate your clips to 30+ languages with AI-powered voice dubbing. + * **Voice Cloning**: Preserves the original speaker's voice characteristics in the new language. + * **Auto-Subtitles**: Automatically generates subtitles in the dubbed language. + +6. **🎨 Modern Web Dashboard:** * **Real-time Progress**: Watch clips appear as they are generated with a live results feed. * **Log Streaming**: Follow the technical process with real-time log updates. * **Responsive Design**: A premium, dark-mode glassmorphism interface. @@ -46,6 +55,7 @@ OpenShorts leverages state-of-the-art AI to handle the entire content lifecycle: * **Docker & Docker Compose**. * **Google Gemini API Key** ([Get it for free here](https://aistudio.google.com/app/apikey)). * **Upload-Post API Key** (Optional, for direct social posting. **Free tier available, no credit card required**). +* **ElevenLabs API Key** (Optional, for AI voice dubbing. [Get it here](https://elevenlabs.io)). ### 📲 Social Media Setup (Upload-Post) To enable direct posting, follow these steps: diff --git a/app.py b/app.py index 31fc60f..b3adb95 100644 --- a/app.py +++ b/app.py @@ -363,8 +363,9 @@ async def get_status(job_id: str): } from editor import VideoEditor -from subtitles import generate_srt, burn_subtitles +from subtitles import generate_srt, burn_subtitles, generate_srt_from_video from hooks import add_hook_to_video +from translate import translate_video, get_supported_languages class EditRequest(BaseModel): job_id: str @@ -558,10 +559,22 @@ async def add_subtitles(req: SubtitleRequest): try: # 1. Generate SRT - success = generate_srt(transcript, clip_data['start'], clip_data['end'], srt_path) + # Check if this is a dubbed video - if so, transcribe it fresh + is_dubbed = filename.startswith("translated_") + + if is_dubbed: + print(f"🎙️ Dubbed video detected, transcribing audio for subtitles...") + def run_transcribe_srt(): + return generate_srt_from_video(input_path, srt_path) + + loop = asyncio.get_event_loop() + success = await loop.run_in_executor(None, run_transcribe_srt) + else: + success = generate_srt(transcript, clip_data['start'], clip_data['end'], srt_path) + if not success: raise HTTPException(status_code=400, detail="No words found for this clip range.") - + # 2. Burn Subtitles # Run in thread pool def run_burn(): @@ -682,6 +695,102 @@ async def add_hook(req: HookRequest): "new_video_url": f"/videos/{req.job_id}/{output_filename}" } +class TranslateRequest(BaseModel): + job_id: str + clip_index: int + target_language: str + source_language: Optional[str] = None + input_filename: Optional[str] = None + +@app.get("/api/translate/languages") +async def get_languages(): + """Return supported languages for translation.""" + return {"languages": get_supported_languages()} + +@app.post("/api/translate") +async def translate_clip( + req: TranslateRequest, + x_elevenlabs_key: Optional[str] = Header(None, alias="X-ElevenLabs-Key") +): + """Translate a video clip to a different language using ElevenLabs dubbing.""" + if not x_elevenlabs_key: + raise HTTPException(status_code=400, detail="Missing X-ElevenLabs-Key header") + + if req.job_id not in jobs: + raise HTTPException(status_code=404, detail="Job not found") + + job = jobs[req.job_id] + output_dir = os.path.join(OUTPUT_DIR, req.job_id) + json_files = glob.glob(os.path.join(output_dir, "*_metadata.json")) + + if not json_files: + raise HTTPException(status_code=404, detail="Metadata not found") + + with open(json_files[0], 'r') as f: + data = json.load(f) + + clips = data.get('shorts', []) + if req.clip_index >= len(clips): + raise HTTPException(status_code=404, detail="Clip not found") + + clip_data = clips[req.clip_index] + + # Video Path + if req.input_filename: + filename = os.path.basename(req.input_filename) + else: + filename = clip_data.get('video_url', '').split('/')[-1] + if not filename: + base_name = os.path.basename(json_files[0]).replace('_metadata.json', '') + filename = f"{base_name}_clip_{req.clip_index+1}.mp4" + + input_path = os.path.join(output_dir, filename) + if not os.path.exists(input_path): + raise HTTPException(status_code=404, detail=f"Video file not found: {input_path}") + + # Output video with language suffix + base, ext = os.path.splitext(filename) + output_filename = f"translated_{req.target_language}_{base}{ext}" + output_path = os.path.join(output_dir, output_filename) + + try: + # Run translation in thread pool (blocking API calls) + def run_translate(): + return translate_video( + video_path=input_path, + output_path=output_path, + target_language=req.target_language, + api_key=x_elevenlabs_key, + source_language=req.source_language, + ) + + loop = asyncio.get_event_loop() + await loop.run_in_executor(None, run_translate) + + except Exception as e: + print(f"❌ Translation Error: {e}") + raise HTTPException(status_code=500, detail=str(e)) + + # Update InMemory Jobs + if req.clip_index < len(job['result']['clips']): + job['result']['clips'][req.clip_index]['video_url'] = f"/videos/{req.job_id}/{output_filename}" + + # Update Metadata on Disk + try: + if req.clip_index < len(clips): + clips[req.clip_index]['video_url'] = f"/videos/{req.job_id}/{output_filename}" + data['shorts'] = clips + with open(json_files[0], 'w') as f: + json.dump(data, f, indent=4) + print(f"✅ Metadata updated with translated video for clip {req.clip_index}") + except Exception as e: + print(f"⚠️ Failed to update metadata.json: {e}") + + return { + "success": True, + "new_video_url": f"/videos/{req.job_id}/{output_filename}" + } + class SocialPostRequest(BaseModel): job_id: str clip_index: int @@ -733,7 +842,8 @@ async def post_to_socials(req: SocialPostRequest): data_payload = { "user": req.user_id, "title": final_title, - "platform[]": req.platforms # Pass list directly + "platform[]": req.platforms, # Pass list directly + "async_upload": "true" # Enable async upload } # Add scheduling if present diff --git a/dashboard/src/App.jsx b/dashboard/src/App.jsx index d437797..5c61adf 100644 --- a/dashboard/src/App.jsx +++ b/dashboard/src/App.jsx @@ -134,6 +134,12 @@ function App() { if (stored) return decrypt(stored); return ''; }); + // ElevenLabs API State - Load encrypted + const [elevenLabsKey, setElevenLabsKey] = useState(() => { + const stored = localStorage.getItem('elevenLabsKey_v1'); + if (stored) return decrypt(stored); + return ''; + }); const [uploadUserId, setUploadUserId] = useState(() => localStorage.getItem('uploadUserId') || ''); const [userProfiles, setUserProfiles] = useState([]); // List of {username, connected: []} @@ -175,6 +181,12 @@ function App() { } }, [uploadPostKey, uploadUserId]); + useEffect(() => { + if (elevenLabsKey) { + localStorage.setItem('elevenLabsKey_v1', encrypt(elevenLabsKey)); + } + }, [elevenLabsKey]); + useEffect(() => { if (uploadPostKey && userProfiles.length === 0) { fetchUserProfiles(); @@ -439,6 +451,57 @@ function App() {

+ +
+
+

Video Translation

+ Optional +
+

+ Translate your clips to different languages using ElevenLabs AI dubbing. + Automatically translates speech while preserving the original voice characteristics. +

+
+ +
+ setElevenLabsKey(e.target.value)} + className="input-field" + placeholder="sk_..." + /> + +
+

+ Get your API key from ElevenLabs to enable video translation. +

+ + 1. Sign Up + Create account + + + 2. API Key + Generate key + +
+
+ + Keys are only stored in your browser. They are sent to the backend only to process your request, never stored server-side. + +

+
+
)} @@ -556,6 +619,7 @@ function App() { uploadPostKey={uploadPostKey} uploadUserId={uploadUserId} geminiApiKey={apiKey} + elevenLabsKey={elevenLabsKey} onPlay={(time) => handleClipPlay(time)} onPause={handleClipPause} /> diff --git a/dashboard/src/components/ResultCard.jsx b/dashboard/src/components/ResultCard.jsx index 676e397..c418b03 100644 --- a/dashboard/src/components/ResultCard.jsx +++ b/dashboard/src/components/ResultCard.jsx @@ -1,10 +1,11 @@ import React, { useState, useEffect } from 'react'; -import { Download, Share2, Instagram, Youtube, Video, CheckCircle, AlertCircle, X, Loader2, Copy, Wand2, Type, Calendar, Clock } from 'lucide-react'; +import { Download, Share2, Instagram, Youtube, Video, CheckCircle, AlertCircle, X, Loader2, Copy, Wand2, Type, Calendar, Clock, Languages } from 'lucide-react'; import { getApiUrl } from '../config'; import SubtitleModal from './SubtitleModal'; import HookModal from './HookModal'; +import TranslateModal from './TranslateModal'; -export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUserId, geminiApiKey, onPlay, onPause }) { +export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUserId, geminiApiKey, elevenLabsKey, onPlay, onPause }) { const [showModal, setShowModal] = useState(false); const [showSubtitleModal, setShowSubtitleModal] = useState(false); const videoRef = React.useRef(null); @@ -26,7 +27,9 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs const [isEditing, setIsEditing] = useState(false); const [isSubtitling, setIsSubtitling] = useState(false); const [isHooking, setIsHooking] = useState(false); + const [isTranslating, setIsTranslating] = useState(false); const [showHookModal, setShowHookModal] = useState(false); + const [showTranslateModal, setShowTranslateModal] = useState(false); const [editError, setEditError] = useState(null); // Initialize/Reset form when modal opens @@ -173,6 +176,69 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs } }; + const handleTranslate = async (options) => { + console.log('[Translate] Starting translation with options:', options); + setIsTranslating(true); + setEditError(null); + try { + const apiKey = elevenLabsKey; + console.log('[Translate] API Key available:', !!apiKey); + + if (!apiKey) { + throw new Error("ElevenLabs API Key is missing. Please set it in Settings."); + } + + const requestBody = { + job_id: jobId, + clip_index: index, + target_language: options.targetLanguage, + input_filename: currentVideoUrl.split('/').pop() + }; + console.log('[Translate] Request body:', requestBody); + console.log('[Translate] Sending request to /api/translate'); + + const res = await fetch(getApiUrl('/api/translate'), { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-ElevenLabs-Key': apiKey + }, + body: JSON.stringify(requestBody) + }); + + console.log('[Translate] Response status:', res.status); + + if (!res.ok) { + const errText = await res.text(); + console.error('[Translate] Error response:', errText); + try { + const jsonErr = JSON.parse(errText); + throw new Error(jsonErr.detail || errText); + } catch (e) { + if (e.message !== errText) throw e; + throw new Error(errText); + } + } + + const data = await res.json(); + console.log('[Translate] Success response:', data); + if (data.new_video_url) { + setCurrentVideoUrl(getApiUrl(data.new_video_url)); + if (videoRef.current) { + videoRef.current.load(); + } + setShowTranslateModal(false); + } + + } catch (e) { + console.error('[Translate] Exception:', e); + setEditError(e.message); + setTimeout(() => setEditError(null), 5000); + } finally { + setIsTranslating(false); + } + }; + const handlePost = async () => { if (!uploadPostKey || !uploadUserId) { setPostResult({ success: false, msg: "Missing API Key or User ID." }); @@ -354,6 +420,15 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs {isHooking ? 'Adding...' : 'Viral Hook'} + + + +
+
+ +
+
+

Dub Voice

+

AI voice translation by ElevenLabs

+
+
+ + {!hasApiKey && ( +
+ +
Configure ElevenLabs API Key in Settings first.
+
+ )} + + {/* Preview */} +
+
+ + ); +} diff --git a/subtitles.py b/subtitles.py index 131feef..166ca79 100644 --- a/subtitles.py +++ b/subtitles.py @@ -1,6 +1,64 @@ import os import subprocess + +def transcribe_audio(video_path): + """ + Transcribe audio from a video file using faster-whisper. + Returns transcript in the same format as main.py for compatibility. + """ + from faster_whisper import WhisperModel + + print(f"🎙️ Transcribing audio from: {video_path}") + + # Run on CPU with INT8 quantization for speed + model = WhisperModel("base", device="cpu", compute_type="int8") + + segments, info = model.transcribe(video_path, word_timestamps=True) + + transcript = { + "segments": [], + "language": info.language + } + + for segment in segments: + seg_data = { + "start": segment.start, + "end": segment.end, + "text": segment.text, + "words": [] + } + if segment.words: + for word in segment.words: + seg_data["words"].append({ + "word": word.word.strip(), + "start": word.start, + "end": word.end + }) + transcript["segments"].append(seg_data) + + print(f"✅ Transcription complete. Language: {info.language}") + return transcript + + +def generate_srt_from_video(video_path, output_path, max_chars=20, max_duration=2.0): + """ + Transcribe a video and generate SRT directly. + Used for dubbed videos that don't have a pre-existing transcript. + """ + transcript = transcribe_audio(video_path) + + # Get video duration to use as clip_end + import cv2 + cap = cv2.VideoCapture(video_path) + fps = cap.get(cv2.CAP_PROP_FPS) + frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) + duration = frame_count / fps if fps else 0 + cap.release() + + return generate_srt(transcript, 0, duration, output_path, max_chars, max_duration) + + def generate_srt(transcript, clip_start, clip_end, output_path, max_chars=20, max_duration=2.0): """ Generates an SRT file from the transcript for a specific time range. diff --git a/translate.py b/translate.py new file mode 100644 index 0000000..d8bc703 --- /dev/null +++ b/translate.py @@ -0,0 +1,239 @@ +""" +ElevenLabs Video Translation/Dubbing Module + +Uses ElevenLabs Dubbing API to translate video audio to different languages. +""" + +import os +import time +import httpx +from typing import Optional + +ELEVENLABS_API_BASE = "https://api.elevenlabs.io/v1" + +# Supported target languages for dubbing +SUPPORTED_LANGUAGES = { + "en": "English", + "es": "Spanish", + "fr": "French", + "de": "German", + "it": "Italian", + "pt": "Portuguese", + "pl": "Polish", + "hi": "Hindi", + "ja": "Japanese", + "ko": "Korean", + "zh": "Chinese", + "ar": "Arabic", + "ru": "Russian", + "tr": "Turkish", + "nl": "Dutch", + "sv": "Swedish", + "id": "Indonesian", + "fil": "Filipino", + "ms": "Malay", + "vi": "Vietnamese", + "th": "Thai", + "uk": "Ukrainian", + "el": "Greek", + "cs": "Czech", + "fi": "Finnish", + "ro": "Romanian", + "da": "Danish", + "bg": "Bulgarian", + "hr": "Croatian", + "sk": "Slovak", + "ta": "Tamil", +} + + +def create_dubbing_project( + video_path: str, + target_language: str, + api_key: str, + source_language: Optional[str] = None, +) -> dict: + """ + Create a new dubbing project with ElevenLabs. + + Args: + video_path: Path to the video file + target_language: Target language code (e.g., 'es', 'fr', 'de') + api_key: ElevenLabs API key + source_language: Source language code (auto-detected if None) + + Returns: + dict with dubbing_id and expected_duration_sec + """ + url = f"{ELEVENLABS_API_BASE}/dubbing" + + headers = { + "xi-api-key": api_key, + } + + # Prepare form data + data = { + "target_lang": target_language, + "mode": "automatic", + "num_speakers": "0", + "watermark": "false", + } + + if source_language: + data["source_lang"] = source_language + + # Open and send the video file + with open(video_path, "rb") as video_file: + files = { + "file": (os.path.basename(video_path), video_file, "video/mp4") + } + + print(f"[ElevenLabs] Creating dubbing project for {target_language}...") + with httpx.Client(timeout=300.0) as client: + response = client.post(url, headers=headers, data=data, files=files) + + if response.status_code not in [200, 201]: + error_msg = response.text + try: + error_data = response.json() + error_msg = error_data.get("detail", {}).get("message", response.text) + except: + pass + raise Exception(f"ElevenLabs API error: {error_msg}") + + result = response.json() + print(f"[ElevenLabs] Dubbing project created: {result.get('dubbing_id')}") + return result + + +def get_dubbing_status(dubbing_id: str, api_key: str) -> dict: + """ + Check the status of a dubbing project. + + Returns: + dict with status ('dubbing', 'dubbed', 'failed') and other metadata + """ + url = f"{ELEVENLABS_API_BASE}/dubbing/{dubbing_id}" + + headers = { + "xi-api-key": api_key, + } + + with httpx.Client(timeout=30.0) as client: + response = client.get(url, headers=headers) + + if response.status_code != 200: + raise Exception(f"Failed to get dubbing status: {response.text}") + + return response.json() + + +def download_dubbed_video( + dubbing_id: str, + target_language: str, + output_path: str, + api_key: str +) -> str: + """ + Download the dubbed video file. + + Args: + dubbing_id: The dubbing project ID + target_language: Target language code + output_path: Where to save the dubbed video + api_key: ElevenLabs API key + + Returns: + Path to the downloaded file + """ + url = f"{ELEVENLABS_API_BASE}/dubbing/{dubbing_id}/audio/{target_language}" + + headers = { + "xi-api-key": api_key, + } + + print(f"[ElevenLabs] Downloading dubbed video...") + with httpx.Client(timeout=120.0) as client: + with client.stream("GET", url, headers=headers) as response: + if response.status_code != 200: + raise Exception(f"Failed to download dubbed video: {response.text}") + + with open(output_path, "wb") as f: + for chunk in response.iter_bytes(chunk_size=8192): + f.write(chunk) + + print(f"[ElevenLabs] Dubbed video saved to: {output_path}") + return output_path + + +def translate_video( + video_path: str, + output_path: str, + target_language: str, + api_key: str, + source_language: Optional[str] = None, + max_wait_seconds: int = 600, + poll_interval: int = 5, +) -> str: + """ + Translate a video to a target language using ElevenLabs dubbing. + + This is a blocking call that waits for the dubbing to complete. + + Args: + video_path: Path to input video + output_path: Path to save translated video + target_language: Target language code + api_key: ElevenLabs API key + source_language: Source language code (auto-detected if None) + max_wait_seconds: Maximum time to wait for dubbing (default 10 min) + poll_interval: Seconds between status checks + + Returns: + Path to the translated video + """ + # Create dubbing project + project = create_dubbing_project( + video_path=video_path, + target_language=target_language, + api_key=api_key, + source_language=source_language, + ) + + dubbing_id = project["dubbing_id"] + expected_duration = project.get("expected_duration_sec", 60) + + print(f"[ElevenLabs] Dubbing ID: {dubbing_id}, Expected duration: {expected_duration}s") + + # Poll for completion + start_time = time.time() + while True: + elapsed = time.time() - start_time + if elapsed > max_wait_seconds: + raise Exception(f"Dubbing timed out after {max_wait_seconds} seconds") + + status = get_dubbing_status(dubbing_id, api_key) + current_status = status.get("status", "unknown") + + print(f"[ElevenLabs] Status: {current_status} (elapsed: {int(elapsed)}s)") + + if current_status == "dubbed": + # Download the result + return download_dubbed_video( + dubbing_id=dubbing_id, + target_language=target_language, + output_path=output_path, + api_key=api_key, + ) + + elif current_status == "failed": + error = status.get("error", "Unknown error") + raise Exception(f"Dubbing failed: {error}") + + # Still processing, wait and poll again + time.sleep(poll_interval) + + +def get_supported_languages() -> dict: + """Return dict of supported language codes and names.""" + return SUPPORTED_LANGUAGES.copy()