From a901bd6933ade95e8ae1999f39609a6d176fcbfd Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Sat, 7 Mar 2026 19:49:27 +0100 Subject: [PATCH] Add session recovery and subtitle customization UI - Session recovery: persist job state to localStorage, auto-restore on page refresh with recovery banner (1h TTL matching server retention) - Subtitle customization: font selection, text color presets + custom picker, border color/width slider, background box toggle with color/opacity controls, live preview in modal - Backend: new SubtitleRequest fields (font_name, font_color, border_color, border_width, bg_color, bg_opacity), hex-to-ASS color conversion, outline vs box rendering modes - Fix font size scaling from 0.5x to 0.85x for readable vertical video Co-Authored-By: Claude Opus 4.6 --- app.py | 12 +- dashboard/src/App.jsx | 68 ++++++- dashboard/src/components/ResultCard.jsx | 6 + dashboard/src/components/SubtitleModal.jsx | 212 ++++++++++++++++----- subtitles.py | 115 ++++++----- 5 files changed, 313 insertions(+), 100 deletions(-) diff --git a/app.py b/app.py index 0a534a9..57983bd 100644 --- a/app.py +++ b/app.py @@ -509,6 +509,12 @@ class SubtitleRequest(BaseModel): clip_index: int position: str = "bottom" # top, middle, bottom font_size: int = 16 + font_name: str = "Verdana" + font_color: str = "#FFFFFF" + border_color: str = "#000000" + border_width: int = 2 + bg_color: str = "#000000" + bg_opacity: float = 0.0 input_filename: Optional[str] = None @app.post("/api/subtitle") @@ -586,7 +592,11 @@ async def add_subtitles(req: SubtitleRequest): # 2. Burn Subtitles # Run in thread pool def run_burn(): - burn_subtitles(input_path, srt_path, output_path, alignment=req.position, fontsize=req.font_size) + burn_subtitles(input_path, srt_path, output_path, + 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, + bg_color=req.bg_color, bg_opacity=req.bg_opacity) loop = asyncio.get_event_loop() await loop.run_in_executor(None, run_burn) diff --git a/dashboard/src/App.jsx b/dashboard/src/App.jsx index c5d00a5..767c2f2 100644 --- a/dashboard/src/App.jsx +++ b/dashboard/src/App.jsx @@ -1,5 +1,5 @@ import React, { useState, useEffect } from 'react'; -import { Upload, FileVideo, Sparkles, Youtube, Instagram, Share2, LogOut, ChevronDown, Check, Activity, LayoutDashboard, Settings, PlusCircle, History, Menu, X, Terminal, Shield, LayoutGrid, Image, Globe } from 'lucide-react'; +import { Upload, FileVideo, Sparkles, Youtube, Instagram, Share2, LogOut, ChevronDown, Check, Activity, LayoutDashboard, Settings, PlusCircle, History, Menu, X, Terminal, Shield, LayoutGrid, Image, Globe, RotateCcw } from 'lucide-react'; import KeyInput from './components/KeyInput'; import MediaInput from './components/MediaInput'; import ResultCard from './components/ResultCard'; @@ -120,6 +120,9 @@ const UserProfileSelector = ({ profiles, selectedUserId, onSelect }) => { ); }; +const SESSION_KEY = 'openshorts_session'; +const SESSION_MAX_AGE = 3600000; // 1 hour (matches server job retention) + // Mock polling function const pollJob = async (jobId) => { const res = await fetch(getApiUrl(`/api/status/${jobId}`)); @@ -152,6 +155,8 @@ function App() { const [processingMedia, setProcessingMedia] = useState(null); const [activeTab, setActiveTab] = useState('dashboard'); // dashboard, settings + const [sessionRecovered, setSessionRecovered] = useState(false); + // Sync state for original video playback const [syncedTime, setSyncedTime] = useState(0); const [isSyncedPlaying, setIsSyncedPlaying] = useState(false); @@ -167,6 +172,52 @@ function App() { setIsSyncedPlaying(false); }; + // Session Recovery: Restore on mount + useEffect(() => { + try { + const saved = localStorage.getItem(SESSION_KEY); + if (!saved) return; + const session = JSON.parse(saved); + if (Date.now() - session.timestamp > SESSION_MAX_AGE) { + localStorage.removeItem(SESSION_KEY); + return; + } + if (session.jobId && session.status && session.status !== 'idle') { + setJobId(session.jobId); + setResults(session.results || null); + if (session.processingMedia) setProcessingMedia(session.processingMedia); + if (session.activeTab) setActiveTab(session.activeTab); + // If was processing, resume polling; if complete/error, just show results + setStatus(session.status === 'processing' ? 'processing' : session.status); + setSessionRecovered(true); + setTimeout(() => setSessionRecovered(false), 5000); + } + } catch (e) { + localStorage.removeItem(SESSION_KEY); + } + }, []); + + // Session Recovery: Save state changes + useEffect(() => { + if (status === 'idle') { + localStorage.removeItem(SESSION_KEY); + return; + } + try { + const sessionData = { + jobId, + status, + results, + processingMedia: processingMedia?.type === 'url' ? processingMedia : null, + activeTab, + timestamp: Date.now() + }; + localStorage.setItem(SESSION_KEY, JSON.stringify(sessionData)); + } catch (e) { + // localStorage full or serialization error - ignore + } + }, [jobId, status, results, activeTab]); + useEffect(() => { // Encrypt Gemini Key too for consistency if desired, but user asked specifically about Social integration not saving well. // For now keeping gemini plain for compatibility unless requested. @@ -292,6 +343,7 @@ function App() { setResults(null); setLogs([]); setProcessingMedia(null); + localStorage.removeItem(SESSION_KEY); }; // --- UI Components --- @@ -412,6 +464,20 @@ function App() { + {/* Session Recovery Banner */} + {sessionRecovered && ( +
+
+ + Session recovered + Your previous work has been restored. +
+ +
+ )} + {/* Main Workspace */}
diff --git a/dashboard/src/components/ResultCard.jsx b/dashboard/src/components/ResultCard.jsx index c418b03..74a0d90 100644 --- a/dashboard/src/components/ResultCard.jsx +++ b/dashboard/src/components/ResultCard.jsx @@ -106,6 +106,12 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs clip_index: index, position: options.position, font_size: options.fontSize, + font_name: options.fontName, + font_color: options.fontColor, + border_color: options.borderColor, + border_width: options.borderWidth, + bg_color: options.bgColor, + bg_opacity: options.bgOpacity, input_filename: currentVideoUrl.split('/').pop() }) }); diff --git a/dashboard/src/components/SubtitleModal.jsx b/dashboard/src/components/SubtitleModal.jsx index f9ffb04..d5c5dac 100644 --- a/dashboard/src/components/SubtitleModal.jsx +++ b/dashboard/src/components/SubtitleModal.jsx @@ -1,12 +1,66 @@ import React, { useState } from 'react'; import { X, Type, Loader2 } from 'lucide-react'; +const FONT_OPTIONS = [ + { value: 'Verdana', label: 'Verdana' }, + { value: 'Arial', label: 'Arial' }, + { value: 'Impact', label: 'Impact' }, + { value: 'Helvetica', label: 'Helvetica' }, + { value: 'Georgia', label: 'Georgia' }, + { value: 'Courier New', label: 'Courier New' }, +]; + +const COLOR_PRESETS = [ + { color: '#FFFFFF', label: 'White' }, + { color: '#FFFF00', label: 'Yellow' }, + { color: '#00FFFF', label: 'Cyan' }, + { color: '#00FF00', label: 'Green' }, + { color: '#FF0000', label: 'Red' }, + { color: '#FF69B4', label: 'Pink' }, +]; + export default function SubtitleModal({ isOpen, onClose, onGenerate, isProcessing, videoUrl }) { - const [position, setPosition] = useState('bottom'); // bottom, middle, top + const [position, setPosition] = useState('bottom'); const [fontSize, setFontSize] = useState(24); + const [fontName, setFontName] = useState('Verdana'); + const [fontColor, setFontColor] = useState('#FFFFFF'); + const [borderColor, setBorderColor] = useState('#000000'); + const [borderWidth, setBorderWidth] = useState(2); + const [bgColor, setBgColor] = useState('#000000'); + const [bgOpacity, setBgOpacity] = useState(0.0); if (!isOpen) return null; + // Scale border width for preview (preview font is small, so amplify the effect) + const bw = Math.max(borderWidth, 0); + const bc = borderColor; + // Build outline text-shadow (8-direction) — always applied for visibility + const outlineShadow = bw > 0 ? [ + `-${bw}px -${bw}px 0 ${bc}`, `${bw}px -${bw}px 0 ${bc}`, + `-${bw}px ${bw}px 0 ${bc}`, `${bw}px ${bw}px 0 ${bc}`, + `0 -${bw}px 0 ${bc}`, `0 ${bw}px 0 ${bc}`, + `-${bw}px 0 0 ${bc}`, `${bw}px 0 0 ${bc}`, + ].join(', ') : 'none'; + + const previewStyle = { + fontFamily: fontName, + color: fontColor, + fontSize: '20px', + fontWeight: 'bold', + maxWidth: '85%', + padding: '6px 12px', + borderRadius: '4px', + textAlign: 'center', + lineHeight: '1.3', + ...(bgOpacity > 0 + ? { + backgroundColor: `${bgColor}${Math.round(bgOpacity * 255).toString(16).padStart(2, '0')}`, + textShadow: 'none', + } + : { textShadow: outlineShadow } + ), + }; + return (
@@ -20,78 +74,146 @@ export default function SubtitleModal({ isOpen, onClose, onGenerate, isProcessin {/* Left: Preview */}
{/* Right: Controls */} -
+

Auto Subtitles

-
+
{/* Position Selector */}
- -
- - - - - + +
+ {['top', 'middle', 'bottom'].map((pos) => ( + + ))}
+ + {/* Font Family */} +
+ + +
+ + {/* Text Color */} +
+ +
+ {COLOR_PRESETS.map((c) => ( +
+
+ + {/* Border / Outline */} +
+ +
+
+ + {/* Background Box */} +
+
+ + +
+ {bgOpacity > 0 && ( +
+
+
+ )} +
- +

Uses AI word-level timestamps to sync perfectly.

@@ -100,5 +222,3 @@ export default function SubtitleModal({ isOpen, onClose, onGenerate, isProcessin
); } - - diff --git a/subtitles.py b/subtitles.py index 166ca79..f961a0a 100644 --- a/subtitles.py +++ b/subtitles.py @@ -133,66 +133,77 @@ def format_srt_block(index, start, end, text): return f"{index}\n{format_time(start)} --> {format_time(end)}\n{text}\n\n" -def burn_subtitles(video_path, srt_path, output_path, alignment=2, fontsize=16): +def hex_to_ass_color(hex_color, opacity=1.0): + """Convert #RRGGBB to ASS &HAABBGGRR format. opacity: 0.0=transparent, 1.0=opaque""" + hex_color = hex_color.lstrip('#') + if len(hex_color) != 6: + hex_color = "FFFFFF" + r = int(hex_color[0:2], 16) + g = int(hex_color[2:4], 16) + b = int(hex_color[4:6], 16) + alpha = round((1.0 - opacity) * 255) + return f"&H{alpha:02X}{b:02X}{g:02X}{r:02X}" + + +def burn_subtitles(video_path, srt_path, output_path, alignment=2, fontsize=16, + font_name="Verdana", font_color="#FFFFFF", + border_color="#000000", border_width=2, + bg_color="#000000", bg_opacity=0.0): """ Burns subtitles into the video using FFmpeg. - Alignment: 2 (Bottom), 5 (Middle), 8 (Top) + Supports two modes: + - Outline mode (bg_opacity=0): Text with colored outline/border + - Box mode (bg_opacity>0): Text with semi-transparent background box """ - # Convert styling options to ASS format - # FontSize is roughly pixels for 720p? It scales. - # For 1080x1920, fontsize 16 is tiny. - # Let's assume standard vertical resolution (1080w). - # Try a larger default or let it be scaled. - # We will accept a 'scale' factor or just big font. - # Default 16 in ASS is small. - # Let's use a reasonable default if user says "small/medium/large". - - # Mapping alignment: - # Top: 6 or 10? ASS: 8 = Top Center. 2 = Bottom Center. 5 = Middle Center. - - # Position mapping (Numpad) - ass_alignment = 2 # Default Bottom Center + # Position mapping + ass_alignment = 2 align_lower = str(alignment).lower() - if align_lower == 'top': - ass_alignment = 6 # 6 is Top-Center in libass (legacy mode usually 6, standard is 8. Let's force 2 (bottom) 10 (center) ? No. - # Actually libass follows SSA/ASS V4+. - # 1=Left, 2=Center, 3=Right (Subtitles Filter treats these as "Bottom") - # 5=Top-Left, 6=Top-Center, 7=Top-Right ?? - # 9=Mid-Left, 10=Mid-Center, 11=Mid-Right ?? - # Standard: 2=Bottom, 6=Top, 10=Middle + if align_lower == 'top': ass_alignment = 6 - elif align_lower == 'middle': + elif align_lower == 'middle': ass_alignment = 10 - elif align_lower == 'bottom': + elif align_lower == 'bottom': ass_alignment = 2 - # Font size logic - # Scale: Libass uses 384x288 virtual resolution unless PlayResX/Y set. - # The frontend sends a value like 24 (pixels). - # In 288p land, 24 is HUGE (approx 1/12th of screen height). - # We want it to be smaller, around 10-12 units. - # Factor: 0.5 is safe. - final_fontsize = int(fontsize * 0.5) - if final_fontsize < 8: final_fontsize = 8 + # Font size scaling for ASS virtual resolution (PlayResY=288 default) + # For vertical 1080x1920 video, we need larger text for readability + final_fontsize = int(fontsize * 0.85) + if final_fontsize < 10: + final_fontsize = 10 - # Path handling for filter string - try: - # Use absolute path but replace special chars for FFmpeg filter syntax - # : -> \: and \ -> / (forward slash is safer on windows too usually in ffmpeg filters if escaped) - # But for standard os paths on linux/mac: /path/to/file.srt - # FFmpeg expects: subtitles='/path/to/file.srt' - # If there are colons (e.g. C:), they need escaping: C\: - safe_srt_path = srt_path.replace('\\', '/').replace(':', '\\:') - except: - safe_srt_path = srt_path + # Path handling for FFmpeg filter syntax + safe_srt_path = srt_path.replace('\\', '/').replace(':', '\\:') + + # Convert colors to ASS format and build style + primary_colour = hex_to_ass_color(font_color, 1.0) + + if bg_opacity > 0: + # Box mode: opaque background box + border_style = 3 + outline_colour = hex_to_ass_color(bg_color, bg_opacity) + outline_width = 1 + else: + # Outline mode: text border/outline + border_style = 1 + outline_colour = hex_to_ass_color(border_color, 1.0) + outline_width = max(1, border_width) + + back_colour = hex_to_ass_color("#000000", 0.0) + + style_string = ( + f"Alignment={ass_alignment}," + f"Fontname={font_name}," + f"Fontsize={final_fontsize}," + f"PrimaryColour={primary_colour}," + f"OutlineColour={outline_colour}," + f"BackColour={back_colour}," + f"BorderStyle={border_style}," + f"Outline={outline_width}," + f"Shadow=0," + f"MarginV=25," + f"Bold=1" + ) - # Style String - # BorderStyle=3 (Opaque Box) - # OutlineColour is Box Background. Alpha 60 (approx 40% opacity) -> &H60000000 - # Fontname: 'Verdana' or 'Arial' are safe. 'Verdana' is slightly more "modern/web". - # Bold=1 - style_string = f"Alignment={ass_alignment},Fontname=Verdana,Fontsize={final_fontsize},PrimaryColour=&H00FFFFFF,OutlineColour=&H60000000,BackColour=&H00000000,BorderStyle=3,Outline=1,Shadow=0,MarginV=25,Bold=1" - cmd = [ 'ffmpeg', '-y', '-i', video_path, @@ -201,10 +212,10 @@ def burn_subtitles(video_path, srt_path, output_path, alignment=2, fontsize=16): '-c:v', 'libx264', '-preset', 'fast', '-crf', '23', output_path ] - + print(f"🎬 Burning subtitles: {' '.join(cmd)}") result = subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) - + if result.returncode != 0: print(f"❌ FFmpeg Subtitle Error: {result.stderr.decode()}") raise Exception(f"FFmpeg failed: {result.stderr.decode()}")