Spaces:
Sleeping
Sleeping
Robby commited on
Commit ·
9ca09e9
1
Parent(s): ca56ff2
feat: add word-by-word subtitles and vlog style animation
Browse files4 unmodified lines567891011121314151617181920212 unmodified lines242526272829303132333435363738391 unmodified line4142434445464748495051525354555657585960616263646566676869707172737411 unmodified lines86878889909192939495969798991001011021031041051061071081091101114 unmodified lines1161171181191201211224 unmodified linesimport tempfileimport subprocess# Load Whisper modelprint("Loading Whisper model (base)...")model = whisper.load_model("base")# Subtitle Style Presets (FFmpeg force_style strings)STYLE_PRESETS = {"Classic White": "Fontname=Arial,Fontsize=20,PrimaryColour=&H00FFFFFF,OutlineColour=&H00000000,BorderStyle=1,Outline=2,Shadow=1,Alignment=2","Social Yellow": "Fontname=Arial,Fontsize=22,PrimaryColour=&H0000FFFF,OutlineColour=&H00000000,BorderStyle=1,Outline=2,Shadow=1,Alignment=2","Large Bold": "Fontname=Arial,Fontsize=26,Bold=1,PrimaryColour=&H00FFFFFF,OutlineColour=&H00000000,BorderStyle=1,Outline=3,Shadow=0,Alignment=2","Clean Netflix": "Fontname=Arial,Fontsize=20,PrimaryColour=&H00FFFFFF,OutlineColour=&H00000000,BorderStyle=1,Outline=0,Shadow=2,Alignment=2","Boxed Text": "Fontname=Arial,Fontsize=18,PrimaryColour=&H00FFFFFF,BackColour=&H80000000,BorderStyle=3,Outline=0,Shadow=0,Alignment=2"}def format_timestamp(seconds: float):2 unmodified lineshours = total_seconds // 3600minutes = (total_seconds % 3600) // 60secs = total_seconds % 60millis = int(td.microseconds / 1000)return f"{hours:02d}:{minutes:02d}:{secs:02d},{millis:03d}"def create_srt(segments):output = ""for i, segment in enumerate(segments):start = format_timestamp(segment['start'])end = format_timestamp(segment['end'])text = segment['text'].strip()output += f"{i + 1}\n{start} --> {end}\n{text}\n\n"return outputdef process_auto_caption(video_path, style_name):1 unmodified linereturn Nonetry:# 1. Transcribe with Whisperprint(f"Transcribing: {video_path}")result = model.transcribe(video_path)# 2. Create SRT filetemp_dir = tempfile.gettempdir()srt_path = os.path.join(temp_dir, f"captions_{os.getpid()}.srt")with open(srt_path, "w", encoding="utf-8") as f:f.write(create_srt(result['segments']))# 3. Burn Subtitles with Styleoutput_video_path = os.path.join(temp_dir, f"output_{os.getpid()}.mp4")# FFmpeg escaping for Linux/HFescaped_srt_path = srt_path.replace("\\", "/").replace(":", "\\:")style_string = STYLE_PRESETS.get(style_name, STYLE_PRESETS["Classic White"])# FFmpeg commandcommand = ["ffmpeg", "-y","-i", video_path,"-vf", f"subtitles='{escaped_srt_path}':force_style='{style_string}'","-c:a", "copy","-preset", "veryfast", # Faster encoding for HF CPUoutput_video_path]print(f"Running FFmpeg Style: {style_name}")subprocess.run(command, check=True)return output_video_path11 unmodified linesbutton_primary_background_fill_hover="linear-gradient(135deg, #059669 0%, #2563eb 100%)",)with gr.Blocks(theme=theme, title="AutoCap AI Pro") as demo:gr.Markdown("""# 🎬 AutoCap AI ProTempel subtitle otomatis ke video Anda dengan berbagai pilihan gaya menarik.""")with gr.Row():with gr.Column():video_input = gr.Video(label="1. Unggah Video")style_opt = gr.Dropdown(choices=list(STYLE_PRESETS.keys()),value="Classic White",label="2. Pilih Gaya Subtitle")submit_btn = gr.Button("⚡ Proses Video Sekarang", variant="primary")with gr.Column():video_output = gr.Video(label="3. Hasil Video + Subtitle")submit_btn.click(fn=process_auto_caption,4 unmodified linesgr.Markdown("""---**Tips:** Proses transkripsi dan penempelan video dilakukan sepenuhnya oleh AI. Harap tunggu beberapa saat hingga video hasil muncul di kolom kanan.""")4 unmodified lines5678910111213141516171819202 unmodified lines232425262728293031323334353637383940414243444546474849505152535455561 unmodified line58596061626364656667686970717273747576777879808182838485868788899091929311 unmodified lines1051061071081091101111121131141151161171181191201211221231241251261271281291304 unmodified lines1351361371381391401411421431444 unmodified linesimport tempfileimport subprocess# Load Whisper model with word-level timestamps capability# Note: 'base' is good, but for better word-level accuracy, you might consider 'small' if the server allows.print("Loading Whisper model (base)...")model = whisper.load_model("base")# Subtitle Style Presets (FFmpeg force_style strings)STYLE_PRESETS = {"Vlog Style (Yellow)": "Fontname=Arial,Fontsize=24,Bold=1,PrimaryColour=&H0000FFFF,OutlineColour=&H00000000,BorderStyle=1,Outline=2,Shadow=0,Alignment=10","Modern White": "Fontname=Arial,Fontsize=22,Bold=1,PrimaryColour=&H00FFFFFF,OutlineColour=&H00000000,BorderStyle=1,Outline=2,Shadow=0,Alignment=10","Boxed Word": "Fontname=Arial,Fontsize=20,PrimaryColour=&H00FFFFFF,BackColour=&H80000000,BorderStyle=3,Outline=0,Shadow=0,Alignment=10",}def format_timestamp(seconds: float):2 unmodified lineshours = total_seconds // 3600minutes = (total_seconds % 3600) // 60secs = total_seconds % 60# Whisper might give micro-secondsmillis = int((seconds % 1) * 1000)return f"{hours:02d}:{minutes:02d}:{secs:02d},{millis:03d}"def create_word_level_srt(segments):"""Creates an SRT where each word appears individually.Useful for 'karaoke' or 'vlog' style captions."""output = ""index = 1for segment in segments:# Check if word-level timestamps are availableif 'words' in segment:for word in segment['words']:start = format_timestamp(word['start'])end = format_timestamp(word['end'])text = word['word'].strip()if not text: continueoutput += f"{index}\n{start} --> {end}\n{text}\n\n"index += 1else:# Fallback to segment if words are missing (e.g. very short segments)start = format_timestamp(segment['start'])end = format_timestamp(segment['end'])text = segment['text'].strip()output += f"{index}\n{start} --> {end}\n{text}\n\n"index += 1return outputdef process_auto_caption(video_path, style_name):1 unmodified linereturn Nonetry:# 1. Transcribe with Whisper (requesting word timestamps)print(f"Transcribing (Word Level): {video_path}")result = model.transcribe(video_path, word_timestamps=True)# 2. Create Word-Level SRT filetemp_dir = tempfile.gettempdir()pid = os.getpid()srt_path = os.path.join(temp_dir, f"words_{pid}.srt")with open(srt_path, "w", encoding="utf-8") as f:f.write(create_word_level_srt(result['segments']))# 3. Burn Subtitles with Animation Simulation (High-speed word appearances)output_video_path = os.path.join(temp_dir, f"vlog_output_{pid}.mp4")# FFmpeg escapingescaped_srt_path = srt_path.replace("\\", "/").replace(":", "\\:")style_string = STYLE_PRESETS.get(style_name, STYLE_PRESETS["Vlog Style (Yellow)"])# FFmpeg command# Alignment=10 means center-middle for that "popup" feelcommand = ["ffmpeg", "-y","-i", video_path,"-vf", f"subtitles='{escaped_srt_path}':force_style='{style_string}'","-c:a", "copy","-preset", "ultrafast", # Faster for Hugging Faceoutput_video_path]print(f"Burning word-level subtitles...")subprocess.run(command, check=True)return output_video_path11 unmodified linesbutton_primary_background_fill_hover="linear-gradient(135deg, #059669 0%, #2563eb 100%)",)with gr.Blocks(theme=theme, title="AutoCap AI: Vlog Edition") as demo:gr.Markdown("""# 🎬 AutoCap AI: Word-by-Word AnimationUbah video Anda menjadi gaya Vlog/Reels dengan teks yang muncul **kata demi kata** mengikuti suara.""")with gr.Row():with gr.Column():video_input = gr.Video(label="1. Unggah Video Anda")style_opt = gr.Dropdown(choices=list(STYLE_PRESETS.keys()),value="Vlog Style (Yellow)",label="2. Pilih Gaya Animasi")submit_btn = gr.Button("🚀 Generate Word-by-Word", variant="primary")with gr.Column():video_output = gr.Video(label="3. Hasil Video (Subtitles Burned)")submit_btn.click(fn=process_auto_caption,4 unmodified linesgr.Markdown("""---**Apa yang baru?**- **Word-by-Word**: Teks tidak lagi panjang, tapi muncul satu per satu mengikuti ucapan.- **Vlog Style**: Posisi teks di tengah layar agar lebih 'eyecatching' seperti video TikTok/Reels.- **Faster AI**: Menggunakan algoritma word-timestamps untuk presisi waktu yang lebih tajam.""")
app.py+56-34