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 <noreply@anthropic.com>
This commit is contained in:
parent
7fe2b6fe1f
commit
a901bd6933
5 changed files with 313 additions and 100 deletions
12
app.py
12
app.py
|
|
@ -509,6 +509,12 @@ class SubtitleRequest(BaseModel):
|
||||||
clip_index: int
|
clip_index: int
|
||||||
position: str = "bottom" # top, middle, bottom
|
position: str = "bottom" # top, middle, bottom
|
||||||
font_size: int = 16
|
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
|
input_filename: Optional[str] = None
|
||||||
|
|
||||||
@app.post("/api/subtitle")
|
@app.post("/api/subtitle")
|
||||||
|
|
@ -586,7 +592,11 @@ async def add_subtitles(req: SubtitleRequest):
|
||||||
# 2. Burn Subtitles
|
# 2. Burn Subtitles
|
||||||
# Run in thread pool
|
# Run in thread pool
|
||||||
def run_burn():
|
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()
|
loop = asyncio.get_event_loop()
|
||||||
await loop.run_in_executor(None, run_burn)
|
await loop.run_in_executor(None, run_burn)
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import React, { useState, useEffect } from 'react';
|
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 KeyInput from './components/KeyInput';
|
||||||
import MediaInput from './components/MediaInput';
|
import MediaInput from './components/MediaInput';
|
||||||
import ResultCard from './components/ResultCard';
|
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
|
// Mock polling function
|
||||||
const pollJob = async (jobId) => {
|
const pollJob = async (jobId) => {
|
||||||
const res = await fetch(getApiUrl(`/api/status/${jobId}`));
|
const res = await fetch(getApiUrl(`/api/status/${jobId}`));
|
||||||
|
|
@ -152,6 +155,8 @@ function App() {
|
||||||
const [processingMedia, setProcessingMedia] = useState(null);
|
const [processingMedia, setProcessingMedia] = useState(null);
|
||||||
const [activeTab, setActiveTab] = useState('dashboard'); // dashboard, settings
|
const [activeTab, setActiveTab] = useState('dashboard'); // dashboard, settings
|
||||||
|
|
||||||
|
const [sessionRecovered, setSessionRecovered] = useState(false);
|
||||||
|
|
||||||
// Sync state for original video playback
|
// Sync state for original video playback
|
||||||
const [syncedTime, setSyncedTime] = useState(0);
|
const [syncedTime, setSyncedTime] = useState(0);
|
||||||
const [isSyncedPlaying, setIsSyncedPlaying] = useState(false);
|
const [isSyncedPlaying, setIsSyncedPlaying] = useState(false);
|
||||||
|
|
@ -167,6 +172,52 @@ function App() {
|
||||||
setIsSyncedPlaying(false);
|
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(() => {
|
useEffect(() => {
|
||||||
// Encrypt Gemini Key too for consistency if desired, but user asked specifically about Social integration not saving well.
|
// 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.
|
// For now keeping gemini plain for compatibility unless requested.
|
||||||
|
|
@ -292,6 +343,7 @@ function App() {
|
||||||
setResults(null);
|
setResults(null);
|
||||||
setLogs([]);
|
setLogs([]);
|
||||||
setProcessingMedia(null);
|
setProcessingMedia(null);
|
||||||
|
localStorage.removeItem(SESSION_KEY);
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- UI Components ---
|
// --- UI Components ---
|
||||||
|
|
@ -412,6 +464,20 @@ function App() {
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
|
{/* Session Recovery Banner */}
|
||||||
|
{sessionRecovered && (
|
||||||
|
<div className="mx-6 mt-2 p-3 bg-primary/10 border border-primary/20 rounded-xl flex items-center justify-between animate-[fadeIn_0.3s_ease-out] shrink-0">
|
||||||
|
<div className="flex items-center gap-2 text-sm text-primary">
|
||||||
|
<RotateCcw size={16} />
|
||||||
|
<span className="font-medium">Session recovered</span>
|
||||||
|
<span className="text-zinc-400 text-xs">Your previous work has been restored.</span>
|
||||||
|
</div>
|
||||||
|
<button onClick={() => setSessionRecovered(false)} className="text-zinc-500 hover:text-white transition-colors">
|
||||||
|
<X size={14} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Main Workspace */}
|
{/* Main Workspace */}
|
||||||
<div className="flex-1 overflow-hidden relative">
|
<div className="flex-1 overflow-hidden relative">
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -106,6 +106,12 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
|
||||||
clip_index: index,
|
clip_index: index,
|
||||||
position: options.position,
|
position: options.position,
|
||||||
font_size: options.fontSize,
|
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()
|
input_filename: currentVideoUrl.split('/').pop()
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,66 @@
|
||||||
import React, { useState } from 'react';
|
import React, { useState } from 'react';
|
||||||
import { X, Type, Loader2 } from 'lucide-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 }) {
|
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 [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;
|
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 (
|
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="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-4xl shadow-2xl relative flex flex-col md:flex-row gap-6 max-h-[90vh]">
|
<div className="bg-[#121214] border border-white/10 p-6 rounded-2xl w-full max-w-4xl shadow-2xl relative flex flex-col md:flex-row gap-6 max-h-[90vh]">
|
||||||
|
|
@ -27,64 +81,132 @@ export default function SubtitleModal({ isOpen, onClose, onGenerate, isProcessin
|
||||||
${position === 'middle' ? 'top-0 bottom-0' : ''}
|
${position === 'middle' ? 'top-0 bottom-0' : ''}
|
||||||
${position === 'bottom' ? 'bottom-20' : ''}
|
${position === 'bottom' ? 'bottom-20' : ''}
|
||||||
`}>
|
`}>
|
||||||
<span
|
<span style={previewStyle}>
|
||||||
className="bg-black/50 text-white font-bold px-2 py-1 rounded shadow-lg backdrop-blur-sm border border-white/10 text-center"
|
|
||||||
style={{
|
|
||||||
fontSize: '14px',
|
|
||||||
maxWidth: '80%'
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
This is how your subtitles<br/>will appear on the video
|
This is how your subtitles<br/>will appear on the video
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Right: Controls */}
|
{/* Right: Controls */}
|
||||||
<div className="w-full md:w-80 flex flex-col">
|
<div className="w-full md:w-80 flex flex-col overflow-y-auto custom-scrollbar">
|
||||||
<h3 className="text-xl font-bold text-white mb-6 flex items-center gap-2">
|
<h3 className="text-xl font-bold text-white mb-6 flex items-center gap-2">
|
||||||
<Type className="text-primary" /> Auto Subtitles
|
<Type className="text-primary" /> Auto Subtitles
|
||||||
</h3>
|
</h3>
|
||||||
|
|
||||||
<div className="space-y-6 flex-1">
|
<div className="space-y-5 flex-1">
|
||||||
{/* Position Selector */}
|
{/* Position Selector */}
|
||||||
<div>
|
<div>
|
||||||
<label className="text-xs font-bold text-zinc-400 uppercase tracking-wider mb-3 block">Position</label>
|
<label className="text-xs font-bold text-zinc-400 uppercase tracking-wider mb-2 block">Position</label>
|
||||||
<div className="grid grid-cols-1 gap-2">
|
<div className="grid grid-cols-3 gap-2">
|
||||||
|
{['top', 'middle', 'bottom'].map((pos) => (
|
||||||
<button
|
<button
|
||||||
onClick={() => setPosition('top')}
|
key={pos}
|
||||||
className={`p-3 rounded-xl border flex items-center gap-3 transition-all ${position === 'top' ? 'bg-primary/20 border-primary text-white' : 'bg-white/5 border-white/5 text-zinc-400 hover:bg-white/10'}`}
|
onClick={() => setPosition(pos)}
|
||||||
|
className={`p-2 rounded-lg border text-center text-xs font-medium transition-all ${position === pos ? 'bg-primary/20 border-primary text-white' : 'bg-white/5 border-white/5 text-zinc-400 hover:bg-white/10'}`}
|
||||||
>
|
>
|
||||||
<div className="w-8 h-8 rounded-lg bg-black/50 border border-white/10 flex items-start justify-center pt-1">
|
{pos.charAt(0).toUpperCase() + pos.slice(1)}
|
||||||
<div className="w-4 h-0.5 bg-white/50 rounded-full"></div>
|
|
||||||
</div>
|
|
||||||
<span className="font-medium">Top</span>
|
|
||||||
</button>
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<button
|
{/* Font Family */}
|
||||||
onClick={() => setPosition('middle')}
|
<div>
|
||||||
className={`p-3 rounded-xl border flex items-center gap-3 transition-all ${position === 'middle' ? 'bg-primary/20 border-primary text-white' : 'bg-white/5 border-white/5 text-zinc-400 hover:bg-white/10'}`}
|
<label className="text-xs font-bold text-zinc-400 uppercase tracking-wider mb-2 block">Font</label>
|
||||||
|
<select
|
||||||
|
value={fontName}
|
||||||
|
onChange={(e) => setFontName(e.target.value)}
|
||||||
|
className="w-full bg-black/40 border border-white/10 rounded-lg p-2 text-sm text-white focus:outline-none focus:border-primary/50"
|
||||||
>
|
>
|
||||||
<div className="w-8 h-8 rounded-lg bg-black/50 border border-white/10 flex items-center justify-center">
|
{FONT_OPTIONS.map((f) => (
|
||||||
<div className="w-4 h-0.5 bg-white/50 rounded-full"></div>
|
<option key={f.value} value={f.value} style={{ fontFamily: f.value }}>{f.label}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
</div>
|
</div>
|
||||||
<span className="font-medium">Center</span>
|
|
||||||
</button>
|
|
||||||
|
|
||||||
|
{/* Text Color */}
|
||||||
|
<div>
|
||||||
|
<label className="text-xs font-bold text-zinc-400 uppercase tracking-wider mb-2 block">Text Color</label>
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{COLOR_PRESETS.map((c) => (
|
||||||
<button
|
<button
|
||||||
onClick={() => setPosition('bottom')}
|
key={c.color}
|
||||||
className={`p-3 rounded-xl border flex items-center gap-3 transition-all ${position === 'bottom' ? 'bg-primary/20 border-primary text-white' : 'bg-white/5 border-white/5 text-zinc-400 hover:bg-white/10'}`}
|
onClick={() => setFontColor(c.color)}
|
||||||
>
|
className={`w-7 h-7 rounded-full border-2 transition-all ${fontColor === c.color ? 'border-white scale-110' : 'border-white/20 hover:border-white/50'}`}
|
||||||
<div className="w-8 h-8 rounded-lg bg-black/50 border border-white/10 flex items-end justify-center pb-1">
|
style={{ backgroundColor: c.color }}
|
||||||
<div className="w-4 h-0.5 bg-white/50 rounded-full"></div>
|
title={c.label}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
<label className="w-7 h-7 rounded-full border-2 border-dashed border-white/20 cursor-pointer flex items-center justify-center hover:border-white/50 transition-all overflow-hidden relative" title="Custom color">
|
||||||
|
<span className="text-[10px] text-zinc-400">+</span>
|
||||||
|
<input type="color" value={fontColor} onChange={(e) => setFontColor(e.target.value)} className="absolute inset-0 opacity-0 cursor-pointer" />
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Border / Outline */}
|
||||||
|
<div>
|
||||||
|
<label className="text-xs font-bold text-zinc-400 uppercase tracking-wider mb-2 block">Border</label>
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<label className="relative w-8 h-8 rounded-lg border border-white/10 cursor-pointer overflow-hidden shrink-0" title="Border color">
|
||||||
|
<div className="w-full h-full" style={{ backgroundColor: borderColor }} />
|
||||||
|
<input type="color" value={borderColor} onChange={(e) => setBorderColor(e.target.value)} className="absolute inset-0 opacity-0 cursor-pointer" />
|
||||||
|
</label>
|
||||||
|
<div className="flex-1">
|
||||||
|
<input
|
||||||
|
type="range"
|
||||||
|
min="0"
|
||||||
|
max="5"
|
||||||
|
value={borderWidth}
|
||||||
|
onChange={(e) => setBorderWidth(parseInt(e.target.value))}
|
||||||
|
className="w-full accent-primary"
|
||||||
|
/>
|
||||||
|
<div className="flex justify-between text-[10px] text-zinc-500">
|
||||||
|
<span>None</span>
|
||||||
|
<span>Thick</span>
|
||||||
</div>
|
</div>
|
||||||
<span className="font-medium">Bottom</span>
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Background Box */}
|
||||||
|
<div>
|
||||||
|
<div className="flex items-center justify-between mb-2">
|
||||||
|
<label className="text-xs font-bold text-zinc-400 uppercase tracking-wider">Background Box</label>
|
||||||
|
<label className="relative inline-flex items-center cursor-pointer">
|
||||||
|
<input type="checkbox" checked={bgOpacity > 0} onChange={(e) => setBgOpacity(e.target.checked ? 0.5 : 0)} className="sr-only peer" />
|
||||||
|
<div className="w-8 h-4 bg-zinc-700 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[0px] after:left-[0px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-primary"></div>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
{bgOpacity > 0 && (
|
||||||
|
<div className="space-y-3 animate-[fadeIn_0.2s_ease-out]">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<label className="relative w-8 h-8 rounded-lg border border-white/10 cursor-pointer overflow-hidden shrink-0" title="Background color">
|
||||||
|
<div className="w-full h-full" style={{ backgroundColor: bgColor }} />
|
||||||
|
<input type="color" value={bgColor} onChange={(e) => setBgColor(e.target.value)} className="absolute inset-0 opacity-0 cursor-pointer" />
|
||||||
|
</label>
|
||||||
|
<div className="flex-1">
|
||||||
|
<input
|
||||||
|
type="range"
|
||||||
|
min="10"
|
||||||
|
max="100"
|
||||||
|
value={Math.round(bgOpacity * 100)}
|
||||||
|
onChange={(e) => setBgOpacity(parseInt(e.target.value) / 100)}
|
||||||
|
className="w-full accent-primary"
|
||||||
|
/>
|
||||||
|
<div className="flex justify-between text-[10px] text-zinc-500">
|
||||||
|
<span>Transparent</span>
|
||||||
|
<span>{Math.round(bgOpacity * 100)}%</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
onClick={() => onGenerate({ position, fontSize })}
|
onClick={() => onGenerate({ position, fontSize, fontName, fontColor, borderColor, borderWidth, bgColor, bgOpacity })}
|
||||||
disabled={isProcessing}
|
disabled={isProcessing}
|
||||||
className="w-full py-4 mt-6 bg-gradient-to-r from-yellow-500 to-orange-500 hover:from-yellow-400 hover:to-orange-400 text-black font-bold rounded-xl shadow-lg shadow-orange-500/20 transition-all active:scale-[0.98] flex items-center justify-center gap-2"
|
className="w-full py-4 mt-6 bg-gradient-to-r from-yellow-500 to-orange-500 hover:from-yellow-400 hover:to-orange-400 text-black font-bold rounded-xl shadow-lg shadow-orange-500/20 transition-all active:scale-[0.98] flex items-center justify-center gap-2"
|
||||||
>
|
>
|
||||||
|
|
@ -100,5 +222,3 @@ export default function SubtitleModal({ isOpen, onClose, onGenerate, isProcessin
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
101
subtitles.py
101
subtitles.py
|
|
@ -133,65 +133,76 @@ def format_srt_block(index, start, end, text):
|
||||||
|
|
||||||
return f"{index}\n{format_time(start)} --> {format_time(end)}\n{text}\n\n"
|
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.
|
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
|
# Position mapping
|
||||||
# FontSize is roughly pixels for 720p? It scales.
|
ass_alignment = 2
|
||||||
# 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
|
|
||||||
align_lower = str(alignment).lower()
|
align_lower = str(alignment).lower()
|
||||||
if align_lower == 'top':
|
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
|
|
||||||
ass_alignment = 6
|
ass_alignment = 6
|
||||||
elif align_lower == 'middle':
|
elif align_lower == 'middle':
|
||||||
ass_alignment = 10
|
ass_alignment = 10
|
||||||
elif align_lower == 'bottom':
|
elif align_lower == 'bottom':
|
||||||
ass_alignment = 2
|
ass_alignment = 2
|
||||||
|
|
||||||
# Font size logic
|
# Font size scaling for ASS virtual resolution (PlayResY=288 default)
|
||||||
# Scale: Libass uses 384x288 virtual resolution unless PlayResX/Y set.
|
# For vertical 1080x1920 video, we need larger text for readability
|
||||||
# The frontend sends a value like 24 (pixels).
|
final_fontsize = int(fontsize * 0.85)
|
||||||
# In 288p land, 24 is HUGE (approx 1/12th of screen height).
|
if final_fontsize < 10:
|
||||||
# We want it to be smaller, around 10-12 units.
|
final_fontsize = 10
|
||||||
# Factor: 0.5 is safe.
|
|
||||||
final_fontsize = int(fontsize * 0.5)
|
|
||||||
if final_fontsize < 8: final_fontsize = 8
|
|
||||||
|
|
||||||
# Path handling for filter string
|
# Path handling for FFmpeg filter syntax
|
||||||
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(':', '\\:')
|
safe_srt_path = srt_path.replace('\\', '/').replace(':', '\\:')
|
||||||
except:
|
|
||||||
safe_srt_path = srt_path
|
|
||||||
|
|
||||||
# Style String
|
# Convert colors to ASS format and build style
|
||||||
# BorderStyle=3 (Opaque Box)
|
primary_colour = hex_to_ass_color(font_color, 1.0)
|
||||||
# OutlineColour is Box Background. Alpha 60 (approx 40% opacity) -> &H60000000
|
|
||||||
# Fontname: 'Verdana' or 'Arial' are safe. 'Verdana' is slightly more "modern/web".
|
if bg_opacity > 0:
|
||||||
# Bold=1
|
# Box mode: opaque background box
|
||||||
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"
|
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"
|
||||||
|
)
|
||||||
|
|
||||||
cmd = [
|
cmd = [
|
||||||
'ffmpeg', '-y',
|
'ffmpeg', '-y',
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue