added subtitles

This commit is contained in:
juancarlos.cavero 2025-12-22 18:21:17 +01:00
parent 820239425c
commit c381c624be
5 changed files with 418 additions and 3 deletions

99
app.py
View file

@ -311,6 +311,7 @@ async def get_status(job_id: str):
}
from editor import VideoEditor
from subtitles import generate_srt, burn_subtitles
class EditRequest(BaseModel):
job_id: str
@ -422,6 +423,104 @@ async def edit_clip(
print(f"❌ Edit Error: {e}")
raise HTTPException(status_code=500, detail=str(e))
class SubtitleRequest(BaseModel):
job_id: str
clip_index: int
position: str = "bottom" # top, middle, bottom
font_size: int = 16
@app.post("/api/subtitle")
async def add_subtitles(req: SubtitleRequest):
if req.job_id not in jobs:
raise HTTPException(status_code=404, detail="Job not found")
# Reload job data from disk just in case metadata was updated
job = jobs[req.job_id]
# We need to access metadata.json to get the transcript
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)
transcript = data.get('transcript')
if not transcript:
raise HTTPException(status_code=400, detail="Transcript not found in metadata. Please process a new video.")
clips = data.get('shorts', [])
if req.clip_index >= len(clips):
raise HTTPException(status_code=404, detail="Clip not found")
clip = clips[req.clip_index]
# Video Path
# Handle current video (might have been edited already)
# We use the video_url from job/data. If it points to an edited one, we subtitle THAT one.
# Note: job['result']['clips'] might be in memory, but data is from disk.
# We should trust what's current.
# Let's verify what video_url is in data vs job.
# We'll use the one from disk data as it's fresh? No, job dict is main truth in memory.
# But transcript is only in disk data now.
# Sync: Use data's clips but check job status?
# Actually, job['result'] is populated from disk in run_job.
# But let's assume `data` is correct.
clip_data = clips[req.clip_index]
filename = clip_data.get('video_url', '').split('/')[-1]
if not filename:
# Fallback to standard naming
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):
# 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"
srt_path = os.path.join(output_dir, srt_filename)
# Output video
# We create a new file "subtitled_..."
output_filename = f"subtitled_{filename}"
output_path = os.path.join(output_dir, output_filename)
try:
# 1. Generate SRT
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():
burn_subtitles(input_path, srt_path, output_path, alignment=req.position, fontsize=req.font_size)
loop = asyncio.get_event_loop()
await loop.run_in_executor(None, run_burn)
# 3. Update Result?
# We return the new URL.
new_video_url = f"/videos/{req.job_id}/{output_filename}"
return {
"success": True,
"new_video_url": new_video_url
}
except Exception as e:
print(f"❌ Subtitle Error: {e}")
raise HTTPException(status_code=500, detail=str(e))
class SocialPostRequest(BaseModel):
job_id: str
clip_index: int

View file

@ -1,9 +1,11 @@
import React, { useState } from 'react';
import { Download, Share2, Instagram, Youtube, Video, CheckCircle, AlertCircle, X, Loader2, Copy, Wand2 } from 'lucide-react';
import { Download, Share2, Instagram, Youtube, Video, CheckCircle, AlertCircle, X, Loader2, Copy, Wand2, Type } from 'lucide-react';
import { getApiUrl } from '../config';
import SubtitleModal from './SubtitleModal';
export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUserId, geminiApiKey, onPlay, onPause }) {
const [showModal, setShowModal] = useState(false);
const [showSubtitleModal, setShowSubtitleModal] = useState(false);
const videoRef = React.useRef(null);
const [currentVideoUrl, setCurrentVideoUrl] = useState(getApiUrl(clip.video_url));
@ -16,6 +18,7 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
const [postResult, setPostResult] = useState(null);
const [isEditing, setIsEditing] = useState(false);
const [isSubtitling, setIsSubtitling] = useState(false);
const [editError, setEditError] = useState(null);
const handleAutoEdit = async () => {
@ -70,6 +73,43 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
}
};
const handleSubtitle = async (options) => {
setIsSubtitling(true);
setEditError(null);
try {
const res = await fetch(getApiUrl('/api/subtitle'), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
job_id: jobId,
clip_index: index,
position: options.position,
font_size: options.fontSize
})
});
if (!res.ok) {
const errText = await res.text();
throw new Error(errText);
}
const data = await res.json();
if (data.new_video_url) {
setCurrentVideoUrl(getApiUrl(data.new_video_url));
if (videoRef.current) {
videoRef.current.load();
}
setShowSubtitleModal(false);
}
} catch (e) {
setEditError(e.message);
setTimeout(() => setEditError(null), 5000);
} finally {
setIsSubtitling(false);
}
};
const handlePost = async () => {
if (!uploadPostKey || !uploadUserId) {
setPostResult({ success: false, msg: "Missing API Key or User ID." });
@ -211,10 +251,19 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
<button
onClick={handleAutoEdit}
disabled={isEditing}
className="col-span-2 py-2 bg-gradient-to-r from-purple-600 to-indigo-600 hover:from-purple-500 hover:to-indigo-500 text-white rounded-lg text-xs font-bold shadow-lg shadow-purple-500/20 transition-all active:scale-[0.98] flex items-center justify-center gap-2 mb-1"
className="col-span-1 py-2 bg-gradient-to-r from-purple-600 to-indigo-600 hover:from-purple-500 hover:to-indigo-500 text-white rounded-lg text-xs font-bold shadow-lg shadow-purple-500/20 transition-all active:scale-[0.98] flex items-center justify-center gap-2 mb-1 truncate px-1"
>
{isEditing ? <Loader2 size={14} className="animate-spin" /> : <Wand2 size={14} />}
{isEditing ? 'Editing with AI...' : 'Auto Edit with AI'}
{isEditing ? 'Editing...' : 'Auto Edit'}
</button>
<button
onClick={() => setShowSubtitleModal(true)}
disabled={isSubtitling}
className="col-span-1 py-2 bg-gradient-to-r from-yellow-600 to-orange-600 hover:from-yellow-500 hover:to-orange-500 text-white rounded-lg text-xs font-bold shadow-lg shadow-orange-500/20 transition-all active:scale-[0.98] flex items-center justify-center gap-2 mb-1 truncate px-1"
>
{isSubtitling ? <Loader2 size={14} className="animate-spin" /> : <Type size={14} />}
{isSubtitling ? 'Adding...' : 'Subtitles'}
</button>
<button
@ -303,6 +352,14 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
</div>
</div>
)}
<SubtitleModal
isOpen={showSubtitleModal}
onClose={() => setShowSubtitleModal(false)}
onGenerate={handleSubtitle}
isProcessing={isSubtitling}
videoUrl={currentVideoUrl}
/>
</div>
);
}

View file

@ -0,0 +1,103 @@
import React, { useState } from 'react';
import { X, Type, Loader2 } from 'lucide-react';
export default function SubtitleModal({ isOpen, onClose, onGenerate, isProcessing, videoUrl }) {
const [position, setPosition] = useState('bottom'); // bottom, middle, top
const [fontSize, setFontSize] = useState(24);
if (!isOpen) return null;
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-4xl shadow-2xl relative flex flex-col md:flex-row gap-6 max-h-[90vh]">
<button
onClick={onClose}
className="absolute top-4 right-4 text-zinc-500 hover:text-white z-10"
>
<X size={20} />
</button>
{/* Left: Preview */}
<div className="flex-1 flex flex-col items-center justify-center bg-black rounded-lg border border-white/5 overflow-hidden relative aspect-[9/16] max-h-[600px]">
<video src={videoUrl} className="w-full h-full object-contain opacity-50" muted playsInline />
{/* Subtitle Overlay Preview */}
<div className={`absolute w-full px-8 text-center transition-all duration-300 pointer-events-none flex flex-col items-center justify-center
${position === 'top' ? 'top-20' : ''}
${position === 'middle' ? 'top-0 bottom-0' : ''}
${position === 'bottom' ? 'bottom-20' : ''}
`}>
<span
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
</span>
</div>
</div>
{/* Right: Controls */}
<div className="w-full md:w-80 flex flex-col">
<h3 className="text-xl font-bold text-white mb-6 flex items-center gap-2">
<Type className="text-primary" /> Auto Subtitles
</h3>
<div className="space-y-6 flex-1">
{/* Position Selector */}
<div>
<label className="text-xs font-bold text-zinc-400 uppercase tracking-wider mb-3 block">Position</label>
<div className="grid grid-cols-1 gap-2">
<button
onClick={() => setPosition('top')}
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'}`}
>
<div className="w-8 h-8 rounded-lg bg-black/50 border border-white/10 flex items-start justify-center pt-1">
<div className="w-4 h-0.5 bg-white/50 rounded-full"></div>
</div>
<span className="font-medium">Top</span>
</button>
<button
onClick={() => setPosition('middle')}
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'}`}
>
<div className="w-8 h-8 rounded-lg bg-black/50 border border-white/10 flex items-center justify-center">
<div className="w-4 h-0.5 bg-white/50 rounded-full"></div>
</div>
<span className="font-medium">Center</span>
</button>
<button
onClick={() => setPosition('bottom')}
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'}`}
>
<div className="w-8 h-8 rounded-lg bg-black/50 border border-white/10 flex items-end justify-center pb-1">
<div className="w-4 h-0.5 bg-white/50 rounded-full"></div>
</div>
<span className="font-medium">Bottom</span>
</button>
</div>
</div>
</div>
<button
onClick={() => onGenerate({ position, fontSize })}
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"
>
{isProcessing ? <Loader2 size={20} className="animate-spin" /> : <Type size={20} />}
{isProcessing ? 'Generating...' : 'Generate Subtitles'}
</button>
<p className="text-[10px] text-zinc-500 text-center mt-3">
Uses AI word-level timestamps to sync perfectly.
</p>
</div>
</div>
</div>
);
}

View file

@ -880,6 +880,7 @@ if __name__ == '__main__':
print(f"🔥 Found {len(clips_data['shorts'])} viral clips!")
# Save metadata
clips_data['transcript'] = transcript # Save full transcript for subtitles
metadata_file = os.path.join(output_dir, f"{video_title}_metadata.json")
with open(metadata_file, 'w') as f:
json.dump(clips_data, f, indent=2)

155
subtitles.py Normal file
View file

@ -0,0 +1,155 @@
import os
import subprocess
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.
Groups words into short lines suitable for vertical video.
"""
words = []
# 1. Extract and flatten words within range
for segment in transcript.get('segments', []):
for word_info in segment.get('words', []):
# Check overlap
if word_info['end'] > clip_start and word_info['start'] < clip_end:
words.append(word_info)
if not words:
return False
srt_content = ""
index = 1
current_block = []
block_start = None
for i, word in enumerate(words):
# Adjust times relative to clip
start = max(0, word['start'] - clip_start)
end = max(0, word['end'] - clip_start)
# Clip to video duration logic handled by ffmpeg usually, but good to be safe
if not current_block:
current_block.append(word)
block_start = start
else:
# Decide whether to close block
current_text_len = sum(len(w['word']) + 1 for w in current_block)
duration = end - block_start
if current_text_len + len(word['word']) > max_chars or duration > max_duration:
# Finalize current block
# End time of block is start of this word (gap) or end of last word?
# Usually end of last word.
block_end = current_block[-1]['end'] - clip_start
text = " ".join([w['word'] for w in current_block]).strip()
srt_content += format_srt_block(index, block_start, block_end, text)
index += 1
current_block = [word]
block_start = start
else:
current_block.append(word)
# Final block
if current_block:
block_end = current_block[-1]['end'] - clip_start
text = " ".join([w['word'] for w in current_block]).strip()
srt_content += format_srt_block(index, block_start, block_end, text)
with open(output_path, 'w', encoding='utf-8') as f:
f.write(srt_content)
return True
def format_srt_block(index, start, end, text):
def format_time(seconds):
hours = int(seconds // 3600)
minutes = int((seconds % 3600) // 60)
secs = int(seconds % 60)
millis = int((seconds - int(seconds)) * 1000)
return f"{hours:02d}:{minutes:02d}:{secs:02d},{millis:03d}"
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):
"""
Burns subtitles into the video using FFmpeg.
Alignment: 2 (Bottom), 5 (Middle), 8 (Top)
"""
# 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
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
ass_alignment = 6
elif align_lower == 'middle':
ass_alignment = 10
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
# 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
# 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,
'-vf', f"subtitles='{safe_srt_path}':force_style='{style_string}'",
'-c:a', 'copy',
'-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()}")
return True