Spaces:
Sleeping
Sleeping
Download app.py from Skinnyeggs/auto-caption: direct link, hf CLI and curl.
- Browser
- Download file 13.4 kB
-
https://huggingface.co/spaces/Skinnyeggs/auto-caption/resolve/main/app.py
- Command line
-
hf download hf://spaces/Skinnyeggs/auto-caption/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Skinnyeggs/auto-caption/resolve/main/app.py
13.4 kB
| import gradio as gr | |
| from faster_whisper import WhisperModel | |
| import os | |
| import datetime | |
| import tempfile | |
| import subprocess | |
| import librosa | |
| import numpy as np | |
| # Load Faster-Whisper model (Base is much faster and more efficient on CPU) | |
| print("Loading Faster-Whisper model (base)...") | |
| model = WhisperModel("base", device="cpu", compute_type="int8") | |
| # Emoji mapping | |
| EMOJI_MAP = { | |
| "uang": "π°", "money": "π°", "duit": "πΈ", "kaya": "π€", | |
| "api": "π₯", "fire": "π₯", "keren": "π", "cool": "π", | |
| "cinta": "β€οΈ", "love": "β€οΈ", "hati": "π", | |
| "tawa": "π", "lucu": "π€£", "π": "π", | |
| "sedih": "π’", "nangis": "π", | |
| "marah": "π ", "kesal": "π‘", | |
| "ide": "π‘", "pintar": "π§ ", | |
| "waktu": "β°", "cepat": "β‘", | |
| "makan": "π", "lapar": "π", | |
| "sukses": "π", "menang": "π₯", "kerja": "πΌ" | |
| } | |
| def get_emoji(text): | |
| text_lower = text.lower().strip() | |
| for key, emoji in EMOJI_MAP.items(): | |
| if key in text_lower: | |
| return f"{emoji} {text}" | |
| return text | |
| def format_timestamp_ass(seconds: float): | |
| td = datetime.timedelta(seconds=seconds) | |
| hours = int(td.total_seconds() // 3600) | |
| minutes = int((td.total_seconds() % 3600) // 60) | |
| secs = int(td.total_seconds() % 60) | |
| centis = int(round((seconds % 1) * 100)) | |
| if centis == 100: | |
| secs += 1 | |
| centis = 0 | |
| return f"{hours}:{minutes:02d}:{secs:02d}.{centis:02d}" | |
| # PRESETS for 1080x1920 | |
| PRESETS = { | |
| "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" | |
| } | |
| } | |
| def create_preset_ass(segments, audio_path, preset_name, output_path): | |
| config = PRESETS[preset_name] | |
| header = f"""[Script Info] | |
| ScriptType: v4.00+ | |
| PlayResX: 1080 | |
| PlayResY: 1920 | |
| ScaledBorderAndShadow: yes | |
| [V4+ Styles] | |
| Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding | |
| {config['style']} | |
| """ | |
| events_header = "\n[Events]\nFormat: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n" | |
| with open(output_path, "w", encoding="utf-8") as f: | |
| f.write(header) | |
| f.write(events_header) | |
| for seg in segments: | |
| words = seg.get('words', []) | |
| if not words: | |
| f.write(f"Dialogue: 0,{format_timestamp_ass(seg['start'])},{format_timestamp_ass(seg['end'])},Main,,0,0,0,,{seg['text'].strip()}\n") | |
| continue | |
| effect = config['effect'] | |
| if effect == "word-by-word": | |
| for w in words: | |
| tags = "{\\fscx0\\fscy0\\t(0,100,\\fscx110\\fscy110)\\t(100,200,\\fscx100\\fscy100)}" | |
| f.write(f"Dialogue: 0,{format_timestamp_ass(w['start'])},{format_timestamp_ass(w['end'])},Main,,0,0,0,,{tags}{get_emoji(w['word'].strip().upper())}\n") | |
| elif effect == "kinetic": | |
| for i in range(0, len(words), 2): | |
| chunk = words[i:i+2] | |
| text = " ".join([w['word'].strip().upper() for w in chunk]) | |
| tags = "{\\t(0,200,\\fscx125\\fscy125)\\t(200,400,\\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") | |
| elif effect == "zoom": | |
| for i in range(0, len(words), 3): | |
| chunk = words[i:i+3] | |
| text = " ".join([w['word'].strip().upper() for w in chunk]) | |
| tags = "{\\fscx80\\fscy80\\t(0,250,\\fscx110\\fscy110)\\t(250,500,\\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") | |
| elif effect == "fade": | |
| for i in range(0, len(words), 4): | |
| chunk = words[i:i+4] | |
| text = " ".join([w['word'].strip() for w in chunk]) | |
| tags = "{\\fad(300,300)}" | |
| f.write(f"Dialogue: 0,{format_timestamp_ass(chunk[0]['start'])},{format_timestamp_ass(chunk[-1]['end'])},Main,,0,0,0,,{tags}{text}\n") | |
| elif effect == "karaoke": | |
| for i in range(0, len(words), 4): | |
| chunk = words[i:i+4] | |
| parts = [f"{{\\k{int((w['end']-w['start'])*100)}}}{w['word'].strip()}" for w in chunk] | |
| f.write(f"Dialogue: 0,{format_timestamp_ass(chunk[0]['start'])},{format_timestamp_ass(chunk[-1]['end'])},Main,,0,0,0,,{' '.join(parts)}\n") | |
| elif effect == "static": | |
| for i in range(0, len(words), 5): | |
| chunk = words[i:i+5] | |
| text = " ".join([w['word'].strip() for w in chunk]) | |
| f.write(f"Dialogue: 0,{format_timestamp_ass(chunk[0]['start'])},{format_timestamp_ass(chunk[-1]['end'])},Main,,0,0,0,,{text}\n") | |
| else: # Dynamic | |
| for i in range(0, len(words), 2): | |
| chunk = words[i:i+2] | |
| text = get_emoji(" ".join([w['word'].strip().upper() for w in chunk])) | |
| tags = "{\\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 structure | |
| DUMMY_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): | |
| try: | |
| temp_dir = tempfile.gettempdir() | |
| pid = os.getpid() | |
| dummy_v = os.path.join(temp_dir, f"dummy_v_{pid}.mp4") | |
| dummy_a = os.path.join(temp_dir, f"dummy_a_{pid}.wav") | |
| dummy_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) | |
| return out_v | |
| except Exception as e: | |
| print(f"Demo Error: {e}") | |
| return None | |
| def on_video_upload(video): | |
| if not video: return None, "Please upload a video." | |
| try: | |
| print("Starting Faster-Whisper Transcription...") | |
| # Tambahkan list() di sini agar generator dieksekusi menjadi data tetap | |
| segments_gen, info = model.transcribe(video, word_timestamps=True) | |
| segments = list(segments_gen) | |
| result = {"segments": [], "language": info.language} | |
| for s in segments: | |
| seg_dict = { | |
| "start": s.start, | |
| "end": s.end, | |
| "text": s.text, | |
| "words": [] | |
| } | |
| if s.words: | |
| for w in s.words: | |
| seg_dict["words"].append({ | |
| "start": w.start, | |
| "end": w.end, | |
| "word": w.word | |
| }) | |
| result["segments"].append(seg_dict) | |
| return result, f"β Done! (Language: {info.language}). Select a style." | |
| except Exception as e: | |
| return None, f"β οΈ Error: {e}" | |
| def handle_preset_select(preset_name): | |
| if preset_name == "-- Select Style --": return None, "Select a style to begin." | |
| return 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 None | |
| if not transcript: | |
| return None | |
| 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") | |
| # 1. Ekstrak Audio | |
| subprocess.run(["ffmpeg", "-y", "-i", video_path, "-vn", "-acodec", "pcm_s16le", "-ar", "22050", "-ac", "1", "-f", "wav", audio_p], check=True) | |
| # 2. Buat file Subtitle (.ass) | |
| create_preset_ass(transcript['segments'], audio_p, preset_name, ass_p) | |
| # 3. Perbaikan Path untuk Linux vs Windows (WAJIB MASUK DALAM TRY) | |
| import platform | |
| if platform.system() == "Windows": | |
| esc_ass = ass_p.replace("\\", "/").replace(":", "\\:") | |
| else: | |
| esc_ass = ass_p | |
| # 4. Perbaikan Command FFmpeg untuk kompatibilitas HP | |
| cmd = [ | |
| "ffmpeg", "-y", "-i", video_path, | |
| "-vf", f"ass={esc_ass}", | |
| "-c:v", "libx264", | |
| "-preset", "ultrafast", | |
| "-pix_fmt", "yuv420p", # Agar tidak gagal di HP | |
| "-c:a", "aac", # Format audio paling stabil di HP | |
| out_v | |
| ] | |
| subprocess.run(cmd, check=True) | |
| return out_v | |
| except Exception as e: | |
| print(f"Process Error: {e}") | |
| return None | |
| custom_css = """ | |
| footer {display: none !important;} | |
| .main-player video { | |
| max-height: 450px !important; | |
| width: auto !important; | |
| margin: 0 auto; | |
| display: block; | |
| } | |
| .preview-box { border: 1px solid #373a40; border-radius: 8px; padding: 10px; background: #1a1b1e; } | |
| """ | |
| with gr.Blocks(title="AutoCap Pro", theme=gr.themes.Soft(primary_hue="emerald", neutral_hue="slate"), css=custom_css) as demo: | |
| t_state = gr.State(None) | |
| gr.Markdown("# π AutoCap Pro (TikTok/Reels Edition)") | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| gr.Markdown("### π¬ 1. Video Input") | |
| v_in = gr.Video(label="Video Input (9:16)", elem_classes="main-player") | |
| gr.Markdown("### π¨ 2. Style & Preview") | |
| p_drop = gr.Dropdown(choices=["-- Select Style --"] + list(PRESETS.keys()), value="-- Select Style --", label="Select Style") | |
| with gr.Group(elem_classes="preview-box"): | |
| p_out = gr.Video(label="Style Demo (Black BG)", interactive=False, elem_classes="main-player") | |
| 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) | |
| demo.launch(server_name="0.0.0.0", server_port=7860, ssr_mode=True) | |