Spaces:
Sleeping
Sleeping
Robby commited on
Commit ·
59eae1f
1
Parent(s): 33d7fa5
UI Optimization: 1080x1920 quality with scaled-down UI players
Browse files6 unmodified lines7891011121329 unmodified lines4344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001012 unmodified lines10410510610710810911011158 unmodified lines1701711721731741751761771785 unmodified lines1841851861871881891901916 unmodified lines1981992002012022032045 unmodified lines2102112122132142152162172182192202212222232242252262272282292302312322332342352363 unmodified lines2402412422432442452469 unmodified lines2562572582592602612622632642652662672682692702712722732746 unmodified linesimport librosaimport numpy as np# Load Whisper model (Small is much more accurate than Base, especially for Indonesian/varying accents)print("Loading Whisper model (small)...")model = whisper.load_model("small")29 unmodified linescentis = 0return f"{hours}:{minutes:02d}:{secs:02d}.{centis:02d}"# Dummy data with word-level structure to ensure preview matches real output exactlyDUMMY_TRANSCRIPT = {"segments": [{"start": 0.0, "end": 2.0, "text": "THE QUICK BROWN FOX","words": [{"word": "THE", "start": 0.0, "end": 0.4},{"word": "QUICK", "start": 0.4, "end": 0.8},{"word": "BROWN", "start": 0.8, "end": 1.2},{"word": "FOX", "start": 1.2, "end": 2.0}]},{"start": 2.0, "end": 4.0, "text": "JUMPS OVER THE LAZY DOG","words": [{"word": "JUMPS", "start": 2.0, "end": 2.5},{"word": "OVER", "start": 2.5, "end": 3.0},{"word": "THE", "start": 3.0, "end": 3.3},{"word": "LAZY", "start": 3.3, "end": 3.7},{"word": "DOG", "start": 3.7, "end": 4.0}]}]}# PRESETS for 720x1280 (9:16) - Margins scaled to 720 widthPRESETS = {"Viral Word-by-Word (Yellow)": {"style": "Style: Main,Impact,100,&H0000FFFF,&H000000FF,&H00000000,&H00000000,1,0,0,0,100,100,0,0,1,8,3,2,70,70,250,1","effect": "word-by-word"},"Hormozi Dynamic (Red)": {"style": "Style: Main,Impact,95,&H00FFFFFF,&H000000FF,&H000000FF,&H00000000,1,0,0,0,100,100,2,0,1,8,4,2,70,70,270,1","effect": "dynamic"},"Kinetic Power (Blue)": {"style": "Style: Main,Arial,85,&H00FFCC00,&H000000FF,&H00FFFFFF,&H00000000,1,0,0,0,100,100,0,0,1,6,3,2,70,70,300,1","effect": "kinetic"},"Pop Neon (Green)": {"style": "Style: Main,Arial,95,&H0000FF00,&H000000FF,&H0000FF00,&H0000FF00,1,0,0,0,100,100,0,0,1,4,10,2,70,70,250,1","effect": "zoom"},"Minimal Slide (White)": {"style": "Style: Main,Arial,75,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,3,3,2,70,70,240,1","effect": "fade"},"Karaoke Fire (Orange)": {"style": "Style: Main,Arial,95,&H00FFFFFF,&H000000FF,&H000080FF,&H00000000,1,0,0,0,100,100,0,0,1,6,3,2,70,70,250,1","effect": "karaoke"},"Boxed News (Black)": {"style": "Style: Main,Arial,60,&H00FFFFFF,&H000000FF,&H00000000,&H80000000,1,0,0,0,100,100,0,0,3,0,0,2,70,70,250,1","effect": "static"}}2 unmodified linesconfig = PRESETS[preset_name]header = f"""[Script Info]ScriptType: v4.00+PlayResX: 720PlayResY: 1280ScaledBorderAndShadow: yes[V4+ Styles]58 unmodified linestags = "{\\t(0,100,\\fscx105\\fscy105)\\t(100,200,\\fscx100\\fscy100)}"f.write(f"Dialogue: 0,{format_timestamp_ass(chunk[0]['start'])},{format_timestamp_ass(chunk[-1]['end'])},Main,,0,0,0,,{tags}{text}\n")# Dummy data for instant previewsDUMMY_TRANSCRIPT = {"segments": [{"start": 0.0, "end": 2.0, "text": "THE QUICK BROWN FOX"}, {"start": 2.0, "end": 4.0, "text": "JUMPS OVER THE LAZY DOG"}]}def get_demo_preview(preset_name):5 unmodified linesdummy_s = os.path.join(temp_dir, f"dummy_s_{pid}.ass")out_v = os.path.join(temp_dir, f"demo_prv_{pid}.mp4")subprocess.run(["ffmpeg", "-y", "-f", "lavfi", "-i", "anullsrc=channel_layout=stereo:sample_rate=44100", "-t", "3", dummy_a], check=True)# 720x1280 (9:16)subprocess.run(["ffmpeg", "-y", "-f", "lavfi", "-i", "color=c=black:s=720x1280:d=3", "-i", dummy_a, "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", dummy_v], check=True)create_preset_ass(DUMMY_TRANSCRIPT['segments'], dummy_a, preset_name, dummy_s)esc_ass = dummy_s.replace("\\", "/").replace(":", "\\:")subprocess.run(["ffmpeg", "-y", "-i", dummy_v, "-vf", f"ass='{esc_ass}'", "-c:a", "copy", "-preset", "ultrafast", out_v], check=True)6 unmodified linesif not video: return None, "Please upload a video."try:print("Starting Transcription...")# fp16=False is REQUIRED on CPU to avoid tensor size mismatch errorsresult = model.transcribe(video, word_timestamps=True, fp16=False)det = result.get('language', 'unknown')return result, f"✅ Done! (Language: {det}). Select a style."5 unmodified linesreturn get_demo_preview(preset_name), f"✨ Style Preview: {preset_name}"def process_video_preset(video_path, preset_name, transcript):if not video_path or preset_name == "-- Select Style --":return Noneif not transcript:print("Error: No transcript found. Please wait for upload to finish.")return Noneprint(f"--- Processing Full Video: {preset_name} ---")try:temp_dir = tempfile.gettempdir()pid = os.getpid()audio_p = os.path.join(temp_dir, f"aud_{pid}.wav")ass_p = os.path.join(temp_dir, f"sub_{pid}.ass")out_v = os.path.join(temp_dir, f"final_{pid}.mp4")# Robust audio extractionsubprocess.run(["ffmpeg", "-y", "-i", video_path, "-vn", "-acodec", "pcm_s16le", "-ar", "22050", "-ac", "1", "-f", "wav", audio_p], check=True)# Use existing transcript instead of re-transcribing (Fixes Whisper tensor error)create_preset_ass(transcript['segments'], audio_p, preset_name, ass_p)esc_ass = ass_p.replace("\\", "/").replace(":", "\\:")subprocess.run(["ffmpeg", "-y", "-i", video_path, "-vf", f"ass='{esc_ass}'", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "copy", out_v], check=True)return out_v3 unmodified linescustom_css = """footer {display: none !important;}.main-player video { max-height: 80vh !important; width: auto !important; aspect-ratio: 9 / 16 !important; }.preview-box { border: 1px solid #373a40; border-radius: 8px; padding: 10px; background: #1a1b1e; }"""9 unmodified linesp_out = gr.Video(label="Style Demo (Black BG)", interactive=False)status = gr.Markdown("*Ready*")sub_btn = gr.Button("🔥 Generate FULL Video", variant="primary", size="lg")with gr.Column(scale=2):gr.Markdown("### 🎬 3. Final Result")v_out = gr.Video(label="Output Video (720x1280)", elem_classes="main-player")v_in.upload(fn=on_video_upload, inputs=[v_in], outputs=[t_state, status])p_drop.change(fn=handle_preset_select, inputs=[p_drop], outputs=[p_out, status])# Updated: Pass t_state to avoid re-transcription errorsub_btn.click(fn=process_video_preset,inputs=[v_in, p_drop, t_state],outputs=[v_out])if __name__ == "__main__":demo.queue(default_concurrency_limit=2)6 unmodified lines7891011121329 unmodified lines434445464748495051525354555657585960616263646566676869707172737475762 unmodified lines798081828384858658 unmodified lines1451461471481491501511521531541551561571581591601611621631641651661671681691701711721735 unmodified lines1791801811821831841851866 unmodified lines1931941951961971981995 unmodified lines2052062072082092102112122132142152162172182192203 unmodified lines2242252262272282292302312322332342359 unmodified lines2452462472482492502512522532542552562576 unmodified linesimport librosaimport numpy as np# Load Whisper model (Small is much more accurate than Base)print("Loading Whisper model (small)...")model = whisper.load_model("small")29 unmodified linescentis = 0return f"{hours}:{minutes:02d}:{secs:02d}.{centis:02d}"# PRESETS for 1080x1920PRESETS = {"Viral Word-by-Word (Yellow)": {"style": "Style: Main,Impact,150,&H0000FFFF,&H000000FF,&H00000000,&H00000000,1,0,0,0,100,100,0,0,1,12,4,2,100,100,400,1","effect": "word-by-word"},"Hormozi Dynamic (Red)": {"style": "Style: Main,Impact,140,&H00FFFFFF,&H000000FF,&H000000FF,&H00000000,1,0,0,0,100,100,2,0,1,12,6,2,100,100,400,1","effect": "dynamic"},"Kinetic Power (Blue)": {"style": "Style: Main,Arial,130,&H00FFCC00,&H000000FF,&H00FFFFFF,&H00000000,1,0,0,0,100,100,0,0,1,10,5,2,100,100,450,1","effect": "kinetic"},"Pop Neon (Green)": {"style": "Style: Main,Arial,140,&H0000FF00,&H000000FF,&H0000FF00,&H0000FF00,1,0,0,0,100,100,0,0,1,6,15,2,100,100,400,1","effect": "zoom"},"Minimal Slide (White)": {"style": "Style: Main,Arial,110,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,4,4,2,100,100,400,1","effect": "fade"},"Karaoke Fire (Orange)": {"style": "Style: Main,Arial,140,&H00FFFFFF,&H000000FF,&H000080FF,&H00000000,1,0,0,0,100,100,0,0,1,10,5,2,100,100,400,1","effect": "karaoke"},"Boxed News (Black)": {"style": "Style: Main,Arial,90,&H00FFFFFF,&H000000FF,&H00000000,&H80000000,1,0,0,0,100,100,0,0,3,0,0,2,100,100,400,1","effect": "static"}}2 unmodified linesconfig = PRESETS[preset_name]header = f"""[Script Info]ScriptType: v4.00+PlayResX: 1080PlayResY: 1920ScaledBorderAndShadow: yes[V4+ Styles]58 unmodified linestags = "{\\t(0,100,\\fscx105\\fscy105)\\t(100,200,\\fscx100\\fscy100)}"f.write(f"Dialogue: 0,{format_timestamp_ass(chunk[0]['start'])},{format_timestamp_ass(chunk[-1]['end'])},Main,,0,0,0,,{tags}{text}\n")# Dummy data with word-level structureDUMMY_TRANSCRIPT = {"segments": [{"start": 0.0, "end": 2.0, "text": "THE QUICK BROWN FOX","words": [{"word": "THE", "start": 0.0, "end": 0.4},{"word": "QUICK", "start": 0.4, "end": 0.8},{"word": "BROWN", "start": 0.8, "end": 1.2},{"word": "FOX", "start": 1.2, "end": 2.0}]},{"start": 2.0, "end": 4.0, "text": "JUMPS OVER THE LAZY DOG","words": [{"word": "JUMPS", "start": 2.0, "end": 2.5},{"word": "OVER", "start": 2.5, "end": 3.0},{"word": "THE", "start": 3.0, "end": 3.3},{"word": "LAZY", "start": 3.3, "end": 3.7},{"word": "DOG", "start": 3.7, "end": 4.0}]}]}def get_demo_preview(preset_name):5 unmodified linesdummy_s = os.path.join(temp_dir, f"dummy_s_{pid}.ass")out_v = os.path.join(temp_dir, f"demo_prv_{pid}.mp4")subprocess.run(["ffmpeg", "-y", "-f", "lavfi", "-i", "anullsrc=channel_layout=stereo:sample_rate=44100", "-t", "3", dummy_a], check=True)# 1080x1920 (9:16)subprocess.run(["ffmpeg", "-y", "-f", "lavfi", "-i", "color=c=black:s=1080x1920:d=3", "-i", dummy_a, "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", dummy_v], check=True)create_preset_ass(DUMMY_TRANSCRIPT['segments'], dummy_a, preset_name, dummy_s)esc_ass = dummy_s.replace("\\", "/").replace(":", "\\:")subprocess.run(["ffmpeg", "-y", "-i", dummy_v, "-vf", f"ass='{esc_ass}'", "-c:a", "copy", "-preset", "ultrafast", out_v], check=True)6 unmodified linesif not video: return None, "Please upload a video."try:print("Starting Transcription...")# fp16=False is REQUIRED on CPUresult = model.transcribe(video, word_timestamps=True, fp16=False)det = result.get('language', 'unknown')return result, f"✅ Done! (Language: {det}). Select a style."5 unmodified linesreturn get_demo_preview(preset_name), f"✨ Style Preview: {preset_name}"def process_video_preset(video_path, preset_name, transcript):if not video_path or preset_name == "-- Select Style --": return Noneif not transcript: return Nonetry:temp_dir = tempfile.gettempdir()pid = os.getpid()audio_p = os.path.join(temp_dir, f"aud_{pid}.wav")ass_p = os.path.join(temp_dir, f"sub_{pid}.ass")out_v = os.path.join(temp_dir, f"final_{pid}.mp4")subprocess.run(["ffmpeg", "-y", "-i", video_path, "-vn", "-acodec", "pcm_s16le", "-ar", "22050", "-ac", "1", "-f", "wav", audio_p], check=True)create_preset_ass(transcript['segments'], audio_p, preset_name, ass_p)esc_ass = ass_p.replace("\\", "/").replace(":", "\\:")subprocess.run(["ffmpeg", "-y", "-i", video_path, "-vf", f"ass='{esc_ass}'", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "copy", out_v], check=True)return out_v3 unmodified linescustom_css = """footer {display: none !important;}.main-player video, .preview-box video {max-height: 500px !important;width: auto !important;margin: 0 auto;display: block;}.preview-box { border: 1px solid #373a40; border-radius: 8px; padding: 10px; background: #1a1b1e; }"""9 unmodified linesp_out = gr.Video(label="Style Demo (Black BG)", interactive=False)status = gr.Markdown("*Ready*")sub_btn = gr.Button("🔥 Generate FULL Video", variant="primary", size="lg")with gr.Column(scale=1):gr.Markdown("### 🎬 3. Final Result")v_out = gr.Video(label="Output Video (1080x1920)", elem_classes="main-player")v_in.upload(fn=on_video_upload, inputs=[v_in], outputs=[t_state, status])p_drop.change(fn=handle_preset_select, inputs=[p_drop], outputs=[p_out, status])sub_btn.click(fn=process_video_preset, inputs=[v_in, p_drop, t_state], outputs=[v_out])if __name__ == "__main__":demo.queue(default_concurrency_limit=2)
app.py+47-64