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 🚀🎬
+[](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:
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.
+