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 <noreply@anthropic.com>
This commit is contained in:
parent
d44dc3ed00
commit
03477d4353
9 changed files with 854 additions and 8 deletions
102
CLAUDE.md
Normal file
102
CLAUDE.md
Normal file
|
|
@ -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
|
||||
21
LICENSE
Normal file
21
LICENSE
Normal file
|
|
@ -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.
|
||||
14
README.md
14
README.md
|
|
@ -1,5 +1,9 @@
|
|||
# OpenShorts.app 🚀🎬
|
||||
|
||||
[](https://opensource.org/licenses/MIT)
|
||||
[](https://opensource.org/)
|
||||
[](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**.
|
||||
|
||||

|
||||
|
|
@ -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:
|
||||
|
|
|
|||
118
app.py
118
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
|
||||
|
|
|
|||
|
|
@ -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() {
|
|||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="glass-panel p-6 mt-8">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h2 className="text-lg font-semibold">Video Translation</h2>
|
||||
<span className="text-[10px] bg-white/5 border border-white/5 px-2 py-0.5 rounded text-zinc-500 uppercase tracking-wider">Optional</span>
|
||||
</div>
|
||||
<p className="text-xs text-zinc-500 mb-6 leading-relaxed">
|
||||
Translate your clips to different languages using <strong>ElevenLabs</strong> AI dubbing.
|
||||
Automatically translates speech while preserving the original voice characteristics.
|
||||
</p>
|
||||
<div className="space-y-4">
|
||||
<label className="block text-sm text-zinc-400">ElevenLabs API Key</label>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
type="password"
|
||||
value={elevenLabsKey}
|
||||
onChange={(e) => setElevenLabsKey(e.target.value)}
|
||||
className="input-field"
|
||||
placeholder="sk_..."
|
||||
/>
|
||||
<button
|
||||
onClick={() => {
|
||||
if (elevenLabsKey) {
|
||||
localStorage.setItem('elevenLabsKey_v1', encrypt(elevenLabsKey));
|
||||
alert('ElevenLabs API Key saved!');
|
||||
}
|
||||
}}
|
||||
className="btn-primary py-2 px-4 text-sm"
|
||||
>
|
||||
Save
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-xs text-zinc-500 leading-relaxed">
|
||||
Get your API key from ElevenLabs to enable video translation.
|
||||
<div className="mt-3 grid grid-cols-1 sm:grid-cols-2 gap-2">
|
||||
<a href="https://elevenlabs.io/sign-up" target="_blank" rel="noopener noreferrer" className="p-2 border border-white/5 rounded-lg hover:bg-white/5 transition-colors flex flex-col gap-1">
|
||||
<span className="text-zinc-400 font-medium">1. Sign Up</span>
|
||||
<span className="text-[10px] text-zinc-600">Create account</span>
|
||||
</a>
|
||||
<a href="https://elevenlabs.io/app/settings/api-keys" target="_blank" rel="noopener noreferrer" className="p-2 border border-white/5 rounded-lg hover:bg-white/5 transition-colors flex flex-col gap-1">
|
||||
<span className="text-zinc-400 font-medium">2. API Key</span>
|
||||
<span className="text-[10px] text-zinc-600">Generate key</span>
|
||||
</a>
|
||||
</div>
|
||||
<br />
|
||||
<span className="text-zinc-600 italic">
|
||||
Keys are only stored in your browser. They are sent to the backend only to process your request, never stored server-side.
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
|
@ -556,6 +619,7 @@ function App() {
|
|||
uploadPostKey={uploadPostKey}
|
||||
uploadUserId={uploadUserId}
|
||||
geminiApiKey={apiKey}
|
||||
elevenLabsKey={elevenLabsKey}
|
||||
onPlay={(time) => handleClipPlay(time)}
|
||||
onPause={handleClipPause}
|
||||
/>
|
||||
|
|
|
|||
|
|
@ -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'}
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => setShowTranslateModal(true)}
|
||||
disabled={isTranslating}
|
||||
className="col-span-1 py-2 bg-gradient-to-r from-green-500 to-teal-600 hover:from-green-400 hover:to-teal-500 text-white rounded-lg text-xs font-bold shadow-lg shadow-green-500/20 transition-all active:scale-[0.98] flex items-center justify-center gap-2 mb-1 truncate px-1"
|
||||
>
|
||||
{isTranslating ? <Loader2 size={14} className="animate-spin" /> : <Languages size={14} />}
|
||||
{isTranslating ? 'Translating...' : 'Dub Voice'}
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => setShowModal(true)}
|
||||
className="col-span-1 py-2 bg-primary hover:bg-blue-600 text-white rounded-lg text-xs font-bold shadow-lg shadow-primary/20 transition-all active:scale-[0.98] flex items-center justify-center gap-2 truncate px-2"
|
||||
|
|
@ -514,6 +589,15 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
|
|||
videoUrl={currentVideoUrl}
|
||||
initialText={clip.viral_hook_text}
|
||||
/>
|
||||
|
||||
<TranslateModal
|
||||
isOpen={showTranslateModal}
|
||||
onClose={() => setShowTranslateModal(false)}
|
||||
onTranslate={handleTranslate}
|
||||
isProcessing={isTranslating}
|
||||
videoUrl={currentVideoUrl}
|
||||
hasApiKey={!!elevenLabsKey}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
158
dashboard/src/components/TranslateModal.jsx
Normal file
158
dashboard/src/components/TranslateModal.jsx
Normal file
|
|
@ -0,0 +1,158 @@
|
|||
import React, { useState, useEffect } from 'react';
|
||||
import { X, Loader2, Globe, Languages, AlertCircle } from 'lucide-react';
|
||||
import { getApiUrl } from '../config';
|
||||
|
||||
const LANGUAGES = {
|
||||
"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",
|
||||
"en": "English",
|
||||
};
|
||||
|
||||
export default function TranslateModal({ isOpen, onClose, onTranslate, isProcessing, videoUrl, hasApiKey }) {
|
||||
const [targetLanguage, setTargetLanguage] = useState('es');
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
const handleSubmit = () => {
|
||||
console.log('[TranslateModal] handleSubmit called, targetLanguage:', targetLanguage);
|
||||
onTranslate({ targetLanguage });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm animate-[fadeIn_0.2s_ease-out]">
|
||||
<div className="bg-[#121214] border border-white/10 p-6 rounded-2xl w-full max-w-md shadow-2xl relative">
|
||||
<button
|
||||
onClick={onClose}
|
||||
disabled={isProcessing}
|
||||
className="absolute top-4 right-4 text-zinc-500 hover:text-white disabled:opacity-50"
|
||||
>
|
||||
<X size={20} />
|
||||
</button>
|
||||
|
||||
<div className="flex items-center gap-3 mb-6">
|
||||
<div className="w-10 h-10 rounded-xl bg-gradient-to-br from-green-500 to-teal-600 flex items-center justify-center">
|
||||
<Languages size={20} className="text-white" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-lg font-bold text-white">Dub Voice</h3>
|
||||
<p className="text-xs text-zinc-500">AI voice translation by ElevenLabs</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!hasApiKey && (
|
||||
<div className="mb-4 p-3 bg-yellow-500/10 border border-yellow-500/20 text-yellow-200 text-xs rounded-lg flex items-start gap-2">
|
||||
<AlertCircle size={14} className="mt-0.5 shrink-0" />
|
||||
<div>Configure ElevenLabs API Key in Settings first.</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Preview */}
|
||||
<div className="mb-6 rounded-xl overflow-hidden bg-black aspect-video relative">
|
||||
<video
|
||||
src={videoUrl}
|
||||
className="w-full h-full object-contain"
|
||||
muted
|
||||
playsInline
|
||||
/>
|
||||
<div className="absolute inset-0 bg-gradient-to-t from-black/60 to-transparent pointer-events-none" />
|
||||
</div>
|
||||
|
||||
{/* Language Selection */}
|
||||
<div className="mb-6">
|
||||
<label className="block text-sm font-medium text-zinc-400 mb-2">
|
||||
<Globe size={14} className="inline mr-2" />
|
||||
Target Language
|
||||
</label>
|
||||
<select
|
||||
value={targetLanguage}
|
||||
onChange={(e) => setTargetLanguage(e.target.value)}
|
||||
className="w-full bg-black/40 border border-white/10 rounded-lg p-3 text-sm text-white focus:outline-none focus:border-green-500/50 appearance-none cursor-pointer"
|
||||
disabled={isProcessing}
|
||||
>
|
||||
{Object.entries(LANGUAGES).sort((a, b) => a[1].localeCompare(b[1])).map(([code, name]) => (
|
||||
<option key={code} value={code}>
|
||||
{name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Info */}
|
||||
<div className="mb-6 p-3 bg-green-500/10 border border-green-500/20 rounded-lg">
|
||||
<p className="text-xs text-green-400">
|
||||
The audio will be dubbed with AI-generated voice in the selected language, matching the original speaker's characteristics.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Processing State */}
|
||||
{isProcessing && (
|
||||
<div className="mb-4 p-4 bg-white/5 rounded-lg border border-white/10">
|
||||
<div className="flex items-center gap-3">
|
||||
<Loader2 size={20} className="text-green-400 animate-spin" />
|
||||
<div>
|
||||
<p className="text-sm text-white font-medium">Dubbing audio...</p>
|
||||
<p className="text-xs text-zinc-500">This may take a few minutes</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex gap-3">
|
||||
<button
|
||||
onClick={onClose}
|
||||
disabled={isProcessing}
|
||||
className="flex-1 py-3 bg-white/5 hover:bg-white/10 text-zinc-300 rounded-xl font-medium transition-colors disabled:opacity-50"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
onClick={handleSubmit}
|
||||
disabled={isProcessing || !hasApiKey}
|
||||
className="flex-1 py-3 bg-gradient-to-r from-green-500 to-teal-600 hover:from-green-400 hover:to-teal-500 text-white rounded-xl font-bold transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
|
||||
>
|
||||
{isProcessing ? (
|
||||
<>
|
||||
<Loader2 size={16} className="animate-spin" />
|
||||
Dubbing...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Languages size={16} />
|
||||
Dub Voice
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
58
subtitles.py
58
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.
|
||||
|
|
|
|||
239
translate.py
Normal file
239
translate.py
Normal file
|
|
@ -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()
|
||||
Loading…
Reference in a new issue