diff --git a/app.py b/app.py index bb8aadd..0be3962 100644 --- a/app.py +++ b/app.py @@ -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 diff --git a/dashboard/src/components/ResultCard.jsx b/dashboard/src/components/ResultCard.jsx index 042c403..d03f9a1 100644 --- a/dashboard/src/components/ResultCard.jsx +++ b/dashboard/src/components/ResultCard.jsx @@ -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 + + + + {/* Left: Preview */} +
+
+ + {/* Right: Controls */} +
+

+ Auto Subtitles +

+ +
+ {/* Position Selector */} +
+ +
+ + + + + +
+
+
+ + + +

+ Uses AI word-level timestamps to sync perfectly. +

+
+ + + ); +} + diff --git a/main.py b/main.py index 2ab9e97..13e4e5c 100644 --- a/main.py +++ b/main.py @@ -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) diff --git a/subtitles.py b/subtitles.py new file mode 100644 index 0000000..131feef --- /dev/null +++ b/subtitles.py @@ -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 +