Spaces:
Sleeping
Sleeping
Robby commited on
Commit ·
ca56ff2
1
Parent(s): 7a0c34e
feat: simplify UI and add subtitle style options
Browse files8 unmodified lines9101112131412 unmodified lines2728293031323334352 unmodified lines38394041424344454647484950515253545556575859606162636465666768697071727374757677783 unmodified lines8283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191208 unmodified linesprint("Loading Whisper model (base)...")model = whisper.load_model("base")def format_timestamp(seconds: float):td = datetime.timedelta(seconds=seconds)total_seconds = int(td.total_seconds())12 unmodified linesoutput += f"{i + 1}\n{start} --> {end}\n{text}\n\n"return outputdef transcribe_video(video_path):if not video_path:return "Please upload a video file.", None, Nonetry:# 1. Transcribe with Whisper2 unmodified lines# 2. Create SRT filetemp_dir = tempfile.gettempdir()srt_path = os.path.join(temp_dir, "captions.srt")with open(srt_path, "w", encoding="utf-8") as f:f.write(create_srt(result['segments']))# 3. Burn Subtitles into Video using FFmpegoutput_video_path = os.path.join(temp_dir, "output_with_captions.mp4")# Escape path for FFmpeg (Windows vs Linux handling)# On Hugging Face (Linux), we need to be careful with the subtitle path formattingescaped_srt_path = srt_path.replace("\\", "/").replace(":", "\\:")# FFmpeg command to "burn" subtitles# -vf "subtitles=filename" is the standard filtercommand = ["ffmpeg", "-y","-i", video_path,"-vf", f"subtitles='{escaped_srt_path}'","-c:a", "copy", # Copy audio without re-encoding for speedoutput_video_path]print(f"Running FFmpeg: {' '.join(command)}")subprocess.run(command, check=True)# 4. Format transcript for displaydisplay_transcript = ""for s in result['segments']:display_transcript += f"[{format_timestamp(s['start'])}] {s['text']}\n"return display_transcript, output_video_path, srt_pathexcept Exception as e:print(f"Error: {e}")return f"Error: {str(e)}", None, None# Design themetheme = gr.themes.Soft(primary_hue="emerald",secondary_hue="blue",3 unmodified linesbutton_primary_background_fill_hover="linear-gradient(135deg, #059669 0%, #2563eb 100%)",)with gr.Blocks(theme=theme, title="AutoCap AI") as demo:gr.Markdown("""# 🎬 AutoCap AI (Video Subtitle Burner)Upload video dan AI akan otomatis menambahkan subtitle langsung ke dalam videonya.""")with gr.Row():with gr.Column():video_input = gr.Video(label="Upload Video")submit_btn = gr.Button("Mulai Proses AI", variant="primary")with gr.Column():video_output = gr.Video(label="Hasil Video + Subtitle")srt_file_output = gr.File(label="Download File .SRT (Opsional)")transcript_output = gr.Textbox(label="Preview Teks", lines=5, interactive=False)submit_btn.click(fn=transcribe_video,inputs=[video_input],outputs=[transcript_output, video_output, srt_file_output])gr.Markdown("""### Cara Kerja:1. **Upload**: Masukkan video Anda.2. **AI Transcribe**: Whisper AI akan membaca suara di video tersebut.3. **Burning**: FFmpeg akan menempelkan teks subtitle tersebut secara permanen ke video Anda.4. **Download**: Ambil hasilnya dalam format MP4.*Note: Proses 'burning' mungkin memakan waktu tambahan tergantung durasi video.*""")8 unmodified lines9101112131415161718192021222312 unmodified lines3637383940414243442 unmodified lines4748495051525354555657585960616263646566676869707172737475767778798081823 unmodified lines86878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211228 unmodified linesprint("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):td = datetime.timedelta(seconds=seconds)total_seconds = int(td.total_seconds())12 unmodified linesoutput += f"{i + 1}\n{start} --> {end}\n{text}\n\n"return outputdef process_auto_caption(video_path, style_name):if not video_path:return Nonetry:# 1. Transcribe with Whisper2 unmodified lines# 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_pathexcept Exception as e:print(f"Error: {e}")return None# UI Implementationtheme = gr.themes.Soft(primary_hue="emerald",secondary_hue="blue",3 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,inputs=[video_input, style_opt],outputs=[video_output])gr.Markdown("""---**Tips:** Proses transkripsi dan penempelan video dilakukan sepenuhnya oleh AI. Harap tunggu beberapa saat hingga video hasil muncul di kolom kanan.""")
app.py+40-38