Spaces:
Sleeping
Sleeping
Robby commited on
Commit ·
9a18c2d
1
Parent(s): b2a8b66
feat: implement Auto-Emoji, Sound-Triggered scaling, and Smart Line Breaks
Browse filesFiles changed (2)
- app.py+114-134
- requirements.txt+2
4 unmodified lines5678910111213141516174 unmodified lines22232425262728293031322 unmodified lines35363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112124 unmodified linesimport tempfileimport subprocessimport re# Load Whisper modelprint("Loading Whisper model (base)...")model = whisper.load_model("base")def format_timestamp_ass(seconds: float):# ASS format: H:MM:SS.cc (centiseconds)td = datetime.timedelta(seconds=seconds)hours = int(td.total_seconds() // 3600)minutes = int((td.total_seconds() % 3600) // 60)4 unmodified linescentis = 0return f"{hours}:{minutes:02d}:{secs:02d}.{centis:02d}"def create_ass_file(segments, style_type, output_path):"""Generates an Advanced Substation Alpha (.ass) file with specific styles."""# Header definitionsheader = """[Script Info]ScriptType: v4.00+PlayResX: 3842 unmodified lines[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"""# Primary colors in &HBBGGRR format# White: &H00FFFFFF, Yellow: &H0000FFFF, Black: &H00000000styles = {"Static Captions": "Style: Static,Arial,18,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,2,1,2,10,10,20,1","Kinetic/Dynamic": "Style: Dynamic,Arial,22,&H0000FFFF,&H000000FF,&H00000000,&H00000000,1,0,0,0,100,100,0,0,1,2,0,10,10,10,144,1","Highlight Warna": "Style: Highlight,Arial,20,&H00FFFFFF,&H0000FFFF,&H00000000,&H00000000,1,0,0,0,100,100,0,0,1,2,0,10,10,10,144,1","Karaoke (Scrubbing)": "Style: Karaoke,Arial,20,&H00FFFFFF,&H0000FFFF,&H00000000,&H00000000,1,0,0,0,100,100,0,0,1,2,0,10,10,10,144,1","Pop-up (Zoom Effect)": "Style: Popup,Arial,22,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,1,0,0,0,100,100,0,0,1,3,0,10,10,10,144,1","Background Highlight": "Style: Background,Arial,18,&H00FFFFFF,&H000000FF,&H00000000,&H80000000,1,0,0,0,100,100,0,0,3,0,0,10,10,10,144,1"}selected_style_line = styles.get(style_type, styles["Static Captions"])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(selected_style_line + "\n")f.write(events_header)if style_type == "Static Captions":for seg in segments:start = format_timestamp_ass(seg['start'])end = format_timestamp_ass(seg['end'])text = seg['text'].strip()f.write(f"Dialogue: 0,{start},{end},Static,,0,0,0,,{text}\n")elif style_type in ["Kinetic/Dynamic", "Pop-up (Zoom Effect)", "Background Highlight"]:# Word by wordfor seg in segments:if 'words' in seg:for word_data in seg['words']:start = format_timestamp_ass(word_data['start'])end = format_timestamp_ass(word_data['end'])word = word_data['word'].strip()if not word: continuestyle = "Dynamic"if style_type == "Pop-up (Zoom Effect)":# Use transformation to simulate pop-upword = f"{{\\fscx120\\fscy120\\t(0,100,\\fscx100\\fscy100)}}{word}"style = "Popup"elif style_type == "Background Highlight":style = "Background"f.write(f"Dialogue: 0,{start},{end},{style},,0,0,0,,{word}\n")else:# Fallback for no word timestampsstart = format_timestamp_ass(seg['start'])end = format_timestamp_ass(seg['end'])f.write(f"Dialogue: 0,{start},{end},Dynamic,,0,0,0,,{seg['text'].strip()}\n")elif style_type == "Highlight Warna":# Highlight current word in Yellow, others in White within the same segmentfor seg in segments:if 'words' in seg:words = seg['words']for i, current_word in enumerate(words):start = format_timestamp_ass(current_word['start'])end = format_timestamp_ass(current_word['end'])# Build full segment with colors# This style shows the whole segment but highlights the current wordline_parts = []for j, w in enumerate(words):text = w['word'].strip()if j == i:line_parts.append(f"{{\\c&H00FFFF&}}{text}{{\\c}}")else:line_parts.append(text)full_line = " ".join(line_parts)f.write(f"Dialogue: 0,{start},{end},Highlight,,0,0,0,,{full_line}\n")else:f.write(f"Dialogue: 0,{format_timestamp_ass(seg['start'])},{format_timestamp_ass(seg['end'])},Highlight,,0,0,0,,{seg['text']}\n")elif style_type == "Karaoke (Scrubbing)":# Pure Karaoke effectfor seg in segments:if 'words' in seg:start = format_timestamp_ass(seg['start'])end = format_timestamp_ass(seg['end'])karaoke_text = ""for word_data in seg['words']:duration_cs = int((word_data['end'] - word_data['start']) * 100)karaoke_text += f"{{\\kf{duration_cs}}}{word_data['word']}"f.write(f"Dialogue: 0,{start},{end},Karaoke,,0,0,0,,{karaoke_text}\n")else:f.write(f"Dialogue: 0,{format_timestamp_ass(seg['start'])},{format_timestamp_ass(seg['end'])},Karaoke,,0,0,0,,{seg['text']}\n")def process_video(video_path, style_type):if not video_path: return Nonetry:temp_dir = tempfile.gettempdir()pid = os.getpid()ass_path = os.path.join(temp_dir, f"sub_{pid}.ass")output_video = os.path.join(temp_dir, f"final_{pid}.mp4")# 1. Transcribe (Base model is fast)print(f"Transcribing with {style_type}...")word_ts = (style_type != "Static Captions")result = model.transcribe(video_path, word_timestamps=word_ts)# 2. Generate ASS filecreate_ass_file(result['segments'], style_type, ass_path)# 3. Burn with FFmpeg# We use 'ass' filter for Advanced Substation Alphaescaped_ass_path = ass_path.replace("\\", "/").replace(":", "\\:")command = ["ffmpeg", "-y","-i", video_path,"-vf", f"ass='{escaped_ass_path}'","-c:a", "copy","-preset", "ultrafast",output_video]subprocess.run(command, check=True)return output_videoexcept Exception as e:print(f"Error: {e}")return None# Gradio Interfacetheme = gr.themes.Soft(primary_hue="emerald", neutral_hue="slate")with gr.Blocks(theme=theme, title="AutoCap Pro AI") as demo:gr.Markdown("# 🎬 AutoCap Pro AI: Advanced Animations")with gr.Row():with gr.Column():video_input = gr.Video(label="Input Video")style_input = gr.Dropdown(choices=["Static Captions","Kinetic/Dynamic","Highlight Warna","Karaoke (Scrubbing)","Pop-up (Zoom Effect)","Background Highlight"],value="Kinetic/Dynamic",label="Jenis Caption & Animasi")submit_btn = gr.Button("🎨 Generate Captions", variant="primary")with gr.Column():video_output = gr.Video(label="Output Video with Animations")submit_btn.click(fn=process_video,inputs=[video_input, style_input],outputs=[video_output])gr.Markdown("""### Penjelasan Efek:- **Static**: Teks standar di bawah (seperti film).- **Dynamic**: Kata per kata muncul di tengah layar.- **Highlight Warna**: Menampilkan kalimat utuh, tapi kata yang sedang diucapkan berubah warna kuning.- **Karaoke**: Teks berubah warna secara progresif (menyapu) mengikuti suara.- **Pop-up**: Kata muncul dengan efek zoom-in kecil agar lebih hidup.- **Background**: Setiap kata memiliki latar belakang kotak semi-transparan.""")if __name__ == "__main__":4 unmodified lines56789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354554 unmodified lines606162636465666768692 unmodified lines727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911924 unmodified linesimport tempfileimport subprocessimport reimport librosaimport numpy as np# Load Whisper modelprint("Loading Whisper model (base)...")model = whisper.load_model("base")# Emoji Mapping DictionaryEMOJI_MAP = {"uang": "💰", "money": "💰", "duit": "💸", "kaya": "🤑","api": "🔥", "fire": "🔥", "keren": "😎", "cool": "😎","cinta": "❤️", "love": "❤️", "hati": "💖","tawa": "😂", "lucu": "🤣", "haha": "😆","sedih": "😢", "nangis": "😭","marah": "😠", "kesal": "😡","ide": "💡", "pintar": "🧠", "brain": "🧠","waktu": "⏰", "cepat": "⚡", "kilat": "⚡","makan": "🍔", "lapar": "😋","mobil": "🚗", "rumah": "🏠", "dunia": "🌍","indonesia": "🇮🇩", "sukses": "🏆", "menang": "🥇"}def get_emoji(text):text = text.lower().strip()# Simple keyword matchfor key, emoji in EMOJI_MAP.items():if key in text:return f"{emoji} {text}"return textdef analyze_volume(audio_path, start_time, end_time, sr=22050):"""Calculates relative RMS volume for a specific time segment."""try:duration = end_time - start_timeif duration <= 0: return 1.0y, _ = librosa.load(audio_path, sr=sr, offset=start_time, duration=duration)if len(y) == 0: return 1.0rms = np.sqrt(np.mean(y**2))return rmsexcept:return 1.0def format_timestamp_ass(seconds: float):td = datetime.timedelta(seconds=seconds)hours = int(td.total_seconds() // 3600)minutes = int((td.total_seconds() % 3600) // 60)4 unmodified linescentis = 0return f"{hours}:{minutes:02d}:{secs:02d}.{centis:02d}"def create_pro_ass(segments, audio_path, output_path):"""Creates an ASS file with Auto-Emoji, Sound-Triggered scaling, and Smart Line Breaks."""header = """[Script Info]ScriptType: v4.00+PlayResX: 3842 unmodified lines[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, EncodingStyle: ProAI,Arial,20,&H00FFFFFF,&H0000FFFF,&H00000000,&H00000000,1,0,0,0,100,100,0,0,1,2,0,10,10,10,144,1"""# Calculate baseline volume to normalize jumpstry:y_full, _ = librosa.load(audio_path, sr=22050)avg_rms = np.sqrt(np.mean(y_full**2))except:avg_rms = 0.05 # Fallbackevents_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:if 'words' in seg:# 3. Smart Line Breaks: Group 1-3 words maxwords = seg['words']for i in range(0, len(words), 2): # 2 words per break is sweet spotchunk = words[i:i+2]start_s = chunk[0]['start']end_s = chunk[-1]['end']raw_text = " ".join([w['word'].strip() for w in chunk])# 1. Auto Emoji Integrationdisplay_text = get_emoji(raw_text)# 2. Sound-Triggered Scalingvol = analyze_volume(audio_path, start_s, end_s)scale_percent = 100if avg_rms > 0:ratio = vol / avg_rmsif ratio > 1.5: scale_percent = 135 # Shoutelif ratio < 0.5: scale_percent = 75 # Whispersize_tag = f"{{\\fscx{scale_percent}\\fscy{scale_percent}}}"# Add Pop-up effect as wellpop_tag = f"{{\\t(0,80,\\fscx{scale_percent-10}\\fscy{scale_percent-10})}}"start_ts = format_timestamp_ass(start_s)end_ts = format_timestamp_ass(end_s)f.write(f"Dialogue: 0,{start_ts},{end_ts},ProAI,,0,0,0,,{size_tag}{pop_tag}{display_text}\n")else:# Fallback for full segmentsstart = format_timestamp_ass(seg['start'])end = format_timestamp_ass(seg['end'])f.write(f"Dialogue: 0,{start},{end},ProAI,,0,0,0,,{seg['text'].strip()}\n")def process_video_pro(video_path):if not video_path: return Nonetry:temp_dir = tempfile.gettempdir()pid = os.getpid()audio_path = os.path.join(temp_dir, f"audio_{pid}.wav")ass_path = os.path.join(temp_dir, f"pro_{pid}.ass")output_video = os.path.join(temp_dir, f"final_pro_{pid}.mp4")# 0. Extract Audio for Volume Analysissubprocess.run(["ffmpeg", "-y", "-i", video_path, "-vn", "-acodec", "pcm_s16le", "-ar", "22050", "-ac", "1", audio_path], check=True)# 1. Transcribe (Base model)print("AI is dreaming of captions...")result = model.transcribe(video_path, word_timestamps=True)# 2. Generate Pro ASS filecreate_pro_ass(result['segments'], audio_path, ass_path)# 3. Burn with FFmpegescaped_ass_path = ass_path.replace("\\", "/").replace(":", "\\:")subprocess.run(["ffmpeg", "-y", "-i", video_path,"-vf", f"ass='{escaped_ass_path}'","-c:a", "copy", "-preset", "ultrafast", output_video], check=True)return output_videoexcept Exception as e:print(f"Error Pro: {e}")return None# Gradio Interfacetheme = gr.themes.Soft(primary_hue="emerald", neutral_hue="slate").set(button_primary_background_fill="linear-gradient(135deg, #10b981 0%, #3b82f6 100%)",)with gr.Blocks(theme=theme, title="AutoCap AI: Smart Social") as demo:gr.Markdown("# 🚀 AutoCap AI: Smart Social Mode")gr.Markdown("AI akan mendeteksi **Emoji**, **Volume Suara**, dan **Struktur Kalimat** secara otomatis.")with gr.Row():with gr.Column():video_input = gr.Video(label="Upload Video (TikTok/Reels format recommended)")submit_btn = gr.Button("🔥 Generate Smart Captions", variant="primary")with gr.Column():video_output = gr.Video(label="Final Result (Pro AI Built-in)")submit_btn.click(fn=process_video_pro,inputs=[video_input],outputs=[video_output])gr.Markdown("""### Fitur Pro yang Aktif:1. **Auto-Emoji**: Mendeteksi kata favorit seperti 'Uang', 'Api', 'Keren', 'Cepat' dan menambahkan emoji relevan.2. **Sound-Triggered Teks**: Ukuran teks membesar otomatis jika Anda bicara lebih keras (shouting) dan mengecil saat berbisik.3. **Smart Line Breaks**: Mengelompokkan hanya 1-2 kata per munculan agar video terlihat dinamis dan profesional.4. **Pop-up Animation**: Efek transisi halus pada setiap pergantian kata.""")if __name__ == "__main__":
1 unmodified line2341 unmodified lineimageio-ffmpegpython-multiparthuggingface-hub==0.24.11 unmodified line234561 unmodified lineimageio-ffmpegpython-multiparthuggingface-hub==0.24.1librosascipy
app.py+114-134
requirements.txt+2