From 40151e1708100327f647bdd190adcf4808838a60 Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Fri, 17 Jul 2026 18:59:22 +0200 Subject: [PATCH] feat: karaoke subtitles, deterministic Auto-Edit v2, emoji hooks, retries (PR #50 block 1) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ported from PR #50 (Themegaindex) onto current main, adapted to the billing-mode app.py and the Lumen dashboard: - subtitles.py: karaoke ASS generation (word-level highlight, glow/pop/box effects, dim/uppercase), whisper continuation-word merging, env-configurable whisper model, ASS/font input sanitization, faststart - editor.py + edit_builder.py: Auto-Edit v2 — Gemini returns a structured edit-decision list and the FFmpeg filter is built deterministically with hard caps (no raw filter strings from the LLM), 2s dry-run + one self-repair round, caption-safe mode blocks zooms on subtitled clips - app.py: /api/subtitle karaoke fields + re-subtitle prefix walk-back (fixes double subtitles), has_captions passed to Auto-Edit - hooks.py: emoji rendering (color-emoji font with strip fallback), char-level hard wrap, unique temp PNGs, ffmpeg timeouts; keeps the duration/enable overlay from b1113d7 - translate.py: exponential-backoff retries for transient ElevenLabs errors - dashboard: 11 caption presets in SubtitleModal; karaoke burns server-side - tests/: 50 pytest tests; .github/workflows/ci.yml runs them + fe build Encode settings kept at CRF 18 (medium for post-process steps) per f791a74. Co-authored-by: Themegaindex --- .github/workflows/ci.yml | 39 ++ app.py | 46 +- dashboard/src/components/ResultCard.jsx | 9 +- dashboard/src/components/SubtitleModal.jsx | 86 ++++ edit_builder.py | 159 +++++++ editor.py | 364 +++++++++++----- hooks.py | 180 ++++++-- subtitles.py | 484 +++++++++++++++++---- tests/conftest.py | 5 + tests/test_edit_builder.py | 118 +++++ tests/test_hooks.py | 44 ++ tests/test_subtitles.py | 207 +++++++++ tests/test_translate.py | 43 ++ translate.py | 86 +++- 14 files changed, 1597 insertions(+), 273 deletions(-) create mode 100644 .github/workflows/ci.yml create mode 100644 edit_builder.py create mode 100644 tests/conftest.py create mode 100644 tests/test_edit_builder.py create mode 100644 tests/test_hooks.py create mode 100644 tests/test_subtitles.py create mode 100644 tests/test_translate.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..670db39 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,39 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +jobs: + backend-tests: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + # Tests only touch light modules (subtitles/hooks/translate/edit_builder), + # so we install just what they import instead of the full requirements.txt + # (faster-whisper/ultralytics/mediapipe are too heavy for CI). + - name: Install test dependencies + run: pip install pytest pillow httpx pydantic + - name: Run tests + run: pytest tests/ -v + + frontend-build: + runs-on: ubuntu-latest + defaults: + run: + working-directory: dashboard + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: "20" + cache: npm + cache-dependency-path: dashboard/package-lock.json + - name: Install dependencies + run: npm ci + - name: Build + run: npm run build diff --git a/app.py b/app.py index 794a0f6..90db74c 100644 --- a/app.py +++ b/app.py @@ -749,7 +749,7 @@ async def get_status(job_id: str, request: Request): } from editor import VideoEditor -from subtitles import generate_srt, burn_subtitles, generate_srt_from_video +from subtitles import generate_srt, generate_ass, burn_subtitles, generate_srt_from_video from hooks import add_hook_to_video from translate import translate_video, get_supported_languages from thumbnail import analyze_video_for_titles, refine_titles, generate_thumbnail, generate_youtube_description @@ -848,7 +848,11 @@ async def edit_clip( print(f"âš ī¸ Could not load transcript for editing context: {e}") # 3. Get Plan (Filter String) - filter_data = editor.get_ffmpeg_filter(vid_file, duration, fps=fps, width=width, height=height, transcript=transcript) + # Zooms would crop burned-in captions/hooks off screen, so tell + # the editor when the source already carries them. `filename` is + # the original clip name (safe_input_path is an ASCII temp copy). + has_captions = ("subtitled_" in filename) or ("hook_" in filename) + filter_data = editor.get_ffmpeg_filter(vid_file, duration, fps=fps, width=width, height=height, transcript=transcript, has_captions=has_captions) # 4. Apply # Use safe output name first @@ -908,6 +912,11 @@ class SubtitleRequest(BaseModel): border_width: int = 2 bg_color: str = "#000000" bg_opacity: float = 0.0 + style: str = "classic" # classic (uniform color) or karaoke (word highlight) + highlight_color: str = "#FFD700" + effect: str = "none" # none | glow | pop | box (karaoke only) + base_opacity: float = 1.0 # opacity of non-active words (dimmed modern look) + uppercase: bool = False input_filename: Optional[str] = None @@ -1156,20 +1165,39 @@ async def add_subtitles(req: SubtitleRequest, request: Request): if not filename: base_name = os.path.basename(json_files[0]).replace('_metadata.json', '') filename = f"{base_name}_clip_{req.clip_index+1}.mp4" - + + # Re-subtitling must replace previous subtitles instead of burning over + # them: walk subtitled__ prefixes back to the pre-subtitle file. + while True: + m = re.match(r'^subtitled_\d+_(.+)$', filename) + if not m or not os.path.exists(os.path.join(output_dir, m.group(1))): + break + filename = m.group(1) + input_path = os.path.join(output_dir, filename) if not os.path.exists(input_path): # Try looking for edited version if url implied it? # Just fail if not found. raise HTTPException(status_code=404, detail=f"Video file not found: {input_path}") - + # Define outputs - srt_filename = f"subs_{req.clip_index}_{int(time.time())}.srt" + generation_id = int(time.time()) + is_karaoke = req.style == "karaoke" + srt_filename = f"subs_{req.clip_index}_{generation_id}.{'ass' if is_karaoke else 'srt'}" srt_path = os.path.join(output_dir, srt_filename) - + + # Style options shared by the karaoke ASS generator paths. + karaoke_opts = dict( + alignment=req.position, fontsize=req.font_size, font_name=req.font_name, + font_color=req.font_color, border_color=req.border_color, + border_width=req.border_width, highlight_color=req.highlight_color, + bg_color=req.bg_color, bg_opacity=req.bg_opacity, + effect=req.effect, base_opacity=req.base_opacity, uppercase=req.uppercase, + ) + # Output video # We create a new file "subtitled_..." - output_filename = f"subtitled_{filename}" + output_filename = f"subtitled_{generation_id}_{filename}" output_path = os.path.join(output_dir, output_filename) # Meter the FFmpeg re-encode (and any dubbed-video re-transcription) so it @@ -1186,10 +1214,14 @@ async def add_subtitles(req: SubtitleRequest, request: Request): if is_dubbed: print(f"đŸŽ™ī¸ Dubbed video detected, transcribing audio for subtitles...") def run_transcribe_srt(): + if is_karaoke: + return generate_srt_from_video(input_path, srt_path, style="karaoke", **karaoke_opts) return generate_srt_from_video(input_path, srt_path) loop = asyncio.get_event_loop() success = await loop.run_in_executor(None, run_transcribe_srt) + elif is_karaoke: + success = generate_ass(transcript, clip_data['start'], clip_data['end'], srt_path, **karaoke_opts) else: success = generate_srt(transcript, clip_data['start'], clip_data['end'], srt_path) diff --git a/dashboard/src/components/ResultCard.jsx b/dashboard/src/components/ResultCard.jsx index 050dd32..b4af91b 100644 --- a/dashboard/src/components/ResultCard.jsx +++ b/dashboard/src/components/ResultCard.jsx @@ -185,7 +185,9 @@ export default function ResultCard({ clip, index, jobId, durableUrl, uploadPostK setIsSubtitling(true); setEditError(null); try { - if (options.remotion) { + // Karaoke styles are burned server-side (ASS word-highlight render); + // the in-browser Remotion path only handles classic styles. + if (options.remotion && options.style !== 'karaoke') { // Accumulate layer and render all layers together const newLayers = { ...activeLayers, subtitles: options.remotion }; setActiveLayers(newLayers); @@ -217,6 +219,11 @@ export default function ResultCard({ clip, index, jobId, durableUrl, uploadPostK border_width: options.borderWidth, bg_color: options.bgColor, bg_opacity: options.bgOpacity, + style: options.style || 'classic', + highlight_color: options.highlightColor || '#FFD700', + effect: options.effect || 'none', + base_opacity: options.baseOpacity ?? 1.0, + uppercase: options.uppercase || false, input_filename: currentVideoUrl.split('/').pop() }) }); diff --git a/dashboard/src/components/SubtitleModal.jsx b/dashboard/src/components/SubtitleModal.jsx index 9783339..4514f0c 100644 --- a/dashboard/src/components/SubtitleModal.jsx +++ b/dashboard/src/components/SubtitleModal.jsx @@ -44,6 +44,22 @@ const POSITION_OPTIONS = [ { value: 'bottom', label: 'bottom' }, ]; +// Ready-made caption looks burned server-side as karaoke ASS (word highlight): +// dimmed base text + strong active word, optional glow/pop/box effect. +const CAPTION_PRESETS = [ + { id: 'tiktok', label: 'TikTok', style: 'karaoke', effect: 'none', highlightColor: '#FE2C55', baseOpacity: 0.75, uppercase: false, fontName: 'Verdana', borderWidth: 2 }, + { id: 'reels', label: 'Reels', style: 'karaoke', effect: 'none', highlightColor: '#E1306C', baseOpacity: 0.7, uppercase: false, fontName: 'Verdana', borderWidth: 2 }, + { id: 'shorts', label: 'Shorts Pop', style: 'karaoke', effect: 'pop', highlightColor: '#FF0000', baseOpacity: 0.7, uppercase: false, fontName: 'Verdana', borderWidth: 2 }, + { id: 'gold', label: 'Gold Glow', style: 'karaoke', effect: 'glow', highlightColor: '#FFD700', baseOpacity: 0.6, uppercase: false, fontName: 'Verdana', borderWidth: 2 }, + { id: 'neon', label: 'Neon', style: 'karaoke', effect: 'glow', highlightColor: '#00FF88', baseOpacity: 0.55, uppercase: false, fontName: 'Verdana', borderWidth: 2 }, + { id: 'cyber', label: 'Cyber', style: 'karaoke', effect: 'glow', highlightColor: '#00FFFF', baseOpacity: 0.5, uppercase: false, fontName: 'Verdana', borderWidth: 2 }, + { id: 'karaoke', label: 'Karaoke', style: 'karaoke', effect: 'none', highlightColor: '#FF6B6B', baseOpacity: 0.6, uppercase: false, fontName: 'Verdana', borderWidth: 2 }, + { id: 'minimal', label: 'Minimal', style: 'karaoke', effect: 'none', highlightColor: '#FFFFFF', baseOpacity: 0.65, uppercase: false, fontName: 'Verdana', borderWidth: 1 }, + { id: 'beast', label: 'Beast', style: 'karaoke', effect: 'pop', highlightColor: '#FFD700', baseOpacity: 1.0, uppercase: true, fontName: 'Impact', borderWidth: 3 }, + { id: 'boxed', label: 'Boxed', style: 'karaoke', effect: 'box', highlightColor: '#7C3AED', baseOpacity: 0.85, uppercase: false, fontName: 'Verdana', borderWidth: 2 }, + { id: 'classic', label: 'Classic', style: 'classic', effect: 'none', highlightColor: '#FFD700', baseOpacity: 1.0, uppercase: false, fontName: 'Verdana', borderWidth: 2 }, +]; + const swatchClass = (selected) => `w-6 h-6 rounded-full transition-all ${selected ? 'ring-2 ring-[color:var(--color-accent)] ring-offset-2 ring-offset-[color:var(--color-paper-2)]' @@ -62,6 +78,28 @@ export default function SubtitleModal({ isOpen, onClose, onGenerate, isProcessin const [animation, setAnimation] = useState('pop'); const [showTextEditor, setShowTextEditor] = useState(false); + // Karaoke (server-side ASS burn) state + const [style, setStyle] = useState('classic'); // classic | karaoke + const [effect, setEffect] = useState('none'); // none | glow | pop | box + const [baseOpacity, setBaseOpacity] = useState(1.0); + const [uppercase, setUppercase] = useState(false); + const [activePreset, setActivePreset] = useState(null); + + const applyPreset = (p) => { + setActivePreset(p.id); + setStyle(p.style); + setEffect(p.effect); + setHighlightColor(p.highlightColor); + setBaseOpacity(p.baseOpacity); + setUppercase(p.uppercase); + setFontName(p.fontName); + setBorderWidth(p.borderWidth); + setFontColor('#FFFFFF'); + setBgOpacity(0); + // Keep the Remotion preview roughly in sync with the burned look + setAnimation(p.style === 'karaoke' ? (p.effect === 'pop' ? 'pop' : p.effect === 'glow' ? 'word-highlight' : 'karaoke') : 'none'); + }; + // Remotion preview state const [captions, setCaptions] = useState([]); const [originalCaptions, setOriginalCaptions] = useState([]); @@ -198,6 +236,52 @@ export default function SubtitleModal({ isOpen, onClose, onGenerate, isProcessin {/* Right: Controls */}
+ {/* Caption presets (server-side karaoke burn) */} +
+

Preset

+
+ {CAPTION_PRESETS.map((p) => ( + + ))} +
+ {style === 'karaoke' && ( +
+
+ UPPERCASE + +
+
+
+ Dim inactive words + {Math.round(baseOpacity * 100)}% +
+ setBaseOpacity(parseInt(e.target.value) / 100)} + className="w-full accent-[var(--color-accent)]" + /> +
+
+ )} +
+ {/* Position Selector */}

Position

@@ -362,6 +446,8 @@ export default function SubtitleModal({ isOpen, onClose, onGenerate, isProcessin