Spaces:
Runtime error
Runtime error
Download main.py from aung990/MyVideoBot: direct link, hf CLI and curl.
- Browser
- Download file 20.1 kB
-
https://huggingface.co/spaces/aung990/MyVideoBot/resolve/main/main.py
- Command line
-
hf download hf://spaces/aung990/MyVideoBot/main.py
-
curl -L -o main.py https://huggingface.co/spaces/aung990/MyVideoBot/resolve/main/main.py
20.1 kB
| import os | |
| import re | |
| import tempfile | |
| import asyncio | |
| import urllib.request | |
| import threading | |
| from http.server import BaseHTTPRequestHandler, HTTPServer | |
| from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup | |
| from telegram.ext import Application, CommandHandler, MessageHandler, CallbackQueryHandler, filters, ContextTypes | |
| from google import genai | |
| # ========================================== | |
| # C O N F I G U R A T I O N | |
| # ========================================== | |
| # Telegram Bot Token | |
| TG_BOT_TOKEN = "8874546727:AAF7X55vHIERAF_tLKKIzRtH90-HLfx9E1Q" | |
| # Gemini API Key Servers | |
| GEMINI_SERVERS = { | |
| "1": "Ab8RN6JWlQI2BLk0ec7iQAlj1EykGJTsRksNpfQuOC-Ir3czLA", | |
| "2": "AQ.Ab8RN6L3lkQVRqM8Z-9eISP0ZFlk_4U5aY1dVw9b3sVHCIf3Cg", | |
| "3": "AQ.Ab8RN6LmFuJbV2MeO3TDHhzZz6ffMjTPUunToMOmGfZ8AWkwng.", | |
| "4": "AQ.Ab8RN6Lo3Qo4VWmG6ly-SvTtj0ELvTvb_5rzrEuLTzSO4-I4lAlA", | |
| "5": "AQ.Ab8RN6LxtWk7KR-mswJ0YqY2DiKBOtFpmQ46CXGN-Hl7LAxLgg", | |
| "6": "AIzaSyCUZiUuvDPSeNrC4UN_TIKaXtk2HCovXW0", | |
| "7": "AIzaSyDHjV3ANcYHmMXI7HLAr6hlBkdCu-tSdkc", | |
| "8": "AIzaSyC2HBCyX0mPCg--tKIqkYqp36G-PntfdEg" | |
| } | |
| VOICE_TYPE = "my-MM-NilarNeural" | |
| ORIGINAL_AUDIO = "keep" | |
| # ========================================== | |
| # --- Hugging Face Health Check အတွက် Web Server အတု --- | |
| class HealthCheckHandler(BaseHTTPRequestHandler): | |
| def do_GET(self): | |
| self.send_response(200) | |
| self.send_header('Content-type', 'text/html') | |
| self.end_headers() | |
| self.wfile.write(b"Bot is alive and running well on Hugging Face!") | |
| def start_health_check_server(): | |
| server = HTTPServer(('0.0.0.0', 7860), HealthCheckHandler) | |
| server.serve_forever() | |
| # ----------------------------------------------------- | |
| def ms_to_time(ms: int) -> str: | |
| s = ms // 1000 | |
| m = s // 60 | |
| h = m // 60 | |
| return f"{h:02d}:{(m%60):02d}:{(s%60):02d},{ms%1000:03d}" | |
| def time_to_ms(time_str: str) -> int: | |
| time_str = time_str.replace(',', '.') | |
| parts = time_str.split(':') | |
| h = int(parts[0]) | |
| m = int(parts[1]) | |
| s_parts = parts[2].split('.') | |
| s = int(s_parts[0]) | |
| ms = int(s_parts[1][:3].ljust(3, '0')) if len(s_parts) > 1 else 0 | |
| return h * 3600000 + m * 60000 + s * 1000 + ms | |
| async def get_media_duration(filepath: str) -> float: | |
| cmd = ['ffprobe', '-v', 'error', '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:nokey=1', filepath] | |
| proc = await asyncio.create_subprocess_exec(*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) | |
| stdout, _ = await proc.communicate() | |
| try: | |
| return float(stdout.decode().strip()) | |
| except: | |
| return 0.0 | |
| async def has_audio_stream(filepath: str) -> bool: | |
| cmd = ['ffprobe', '-v', 'error', '-select_streams', 'a', '-show_entries', 'stream=codec_type', '-of', 'default=noprint_wrappers=1:nokey=1', filepath] | |
| proc = await asyncio.create_subprocess_exec(*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) | |
| stdout, _ = await proc.communicate() | |
| return len(stdout.decode().strip()) > 0 | |
| async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| keyboard = [ | |
| [InlineKeyboardButton("🖥 Server 1", callback_data='server_1'), InlineKeyboardButton("🖥 Server 2", callback_data='server_2')], | |
| [InlineKeyboardButton("🖥 Server 3", callback_data='server_3'), InlineKeyboardButton("🖥 Server 4", callback_data='server_4')], | |
| [InlineKeyboardButton("🖥 Server 5", callback_data='server_5'), InlineKeyboardButton("🖥 Server 6", callback_data='server_6')], | |
| [InlineKeyboardButton("🖥 Server 7", callback_data='server_7'), InlineKeyboardButton("🖥 Server 8 (Default)", callback_data='server_8')] | |
| ] | |
| reply_markup = InlineKeyboardMarkup(keyboard) | |
| await update.message.reply_text( | |
| "မင်္ဂလာပါ။ 🇲🇲\n" | |
| "MyVideoBot မှ ကြိုဆိုပါတယ်။ Video ဖိုင်တစ်ခုကို ပို့ပေးပါ။ Video ထဲက စကားပြောတွေကို မြန်မာလို ဘာသာပြန်ပြီး အသံထွက်ရော စာတန်းထိုးပါ ပြန်ပေါင်းထည့်ပေးပါမယ်။\n\n" | |
| "API Limit ပြည့်သွားပါက အောက်ပါ Server များကို ပြောင်းလဲရွေးချယ်နိုင်ပါသည်။", | |
| reply_markup=reply_markup | |
| ) | |
| async def button_callback(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| query = update.callback_query | |
| await query.answer() | |
| server_id = query.data.split('_')[1] | |
| context.user_data['selected_server'] = server_id | |
| await query.edit_message_text(text=f"✅ Server {server_id} ကို ရွေးချယ်ပြီးပါပြီ။ Video ဖိုင်ကို ပို့ပေးနိုင်ပါပြီ။") | |
| async def process_video(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| msg = update.message | |
| if not (msg.video or msg.document): | |
| return | |
| file_obj = msg.video or msg.document | |
| if msg.document and not msg.document.mime_type.startswith('video/'): | |
| return | |
| # Check File Size Limit (20MB) | |
| file_size = file_obj.file_size | |
| if file_size and file_size > 20 * 1024 * 1024: | |
| await msg.reply_text("❌ ဖိုင်ဆိုဒ်ကြီးလွန်းနေပါသည်။ 20MB အောက် ဗီဒီယိုများကိုသာ ပို့ပေးပါ။") | |
| return | |
| selected_server_id = context.user_data.get('selected_server', '8') | |
| current_api_key = GEMINI_SERVERS.get(selected_server_id) | |
| if not current_api_key: | |
| await msg.reply_text("❌ မှားယွင်းသော Server ဖြစ်နေပါသည်။") | |
| return | |
| client = genai.Client(api_key=current_api_key) | |
| status_msg = await msg.reply_text(f"📥 Video ကို ဒေါင်းလုဒ်ဆွဲနေပါတယ်... (Server - {selected_server_id})") | |
| try: | |
| tg_file = await context.bot.get_file(file_obj.file_id, read_timeout=120) | |
| with tempfile.TemporaryDirectory() as work_dir: | |
| video_path = os.path.join(work_dir, "input.mp4") | |
| await tg_file.download_to_drive(video_path) | |
| # --- 1. Audio Extraction --- | |
| await status_msg.edit_text("🎵 Video မှ အသံကို ခွဲထုတ်နေပါတယ်...") | |
| audio_prefix = os.path.join(work_dir, "audio_%03d.mp3") | |
| extract_cmd = ['ffmpeg', '-i', video_path, '-q:a', '0', '-map', 'a', '-f', 'segment', '-segment_time', '45', audio_prefix, '-y'] | |
| proc = await asyncio.create_subprocess_exec(*extract_cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) | |
| await proc.communicate() | |
| chunk_files = sorted([f for f in os.listdir(work_dir) if f.startswith('audio_') and f.endswith('.mp3')]) | |
| if not chunk_files: | |
| await status_msg.edit_text("❌ Video တွင် အသံမပါဝင်ပါ။") | |
| return | |
| all_subs = [] | |
| # --- 2. Translation via Gemini --- | |
| for c_idx, c_file in enumerate(chunk_files): | |
| await status_msg.edit_text(f"🤖 တေးသံကို ဘာသာပြန်နေပါတယ် (အပိုင်း {c_idx + 1}/{len(chunk_files)})...") | |
| c_path = os.path.join(work_dir, c_file) | |
| offset_secs = c_idx * 45 | |
| uploaded_file = client.files.upload(file=c_path, config={'mime_type': 'audio/mp3'}) | |
| prompt = ( | |
| "Listen to this audio segment and translate the spoken content directly into Burmese (Myanmar). " | |
| "YOU MUST OUTPUT THE TRANSLATION STRICTLY AND ONLY IN VALID SRT (SubRip) FORMAT. " | |
| "Use the exact time format 00:00:00,000 --> 00:00:00,000. Output the translated text in the Burmese alphabet (မြန်မာစာ) only. " | |
| "Do not output any conversational English or introductory text. Include accurate timestamps matching the original speech, " | |
| "and the translated Burmese text. Limit subtitle line lengths to max 40 characters." | |
| ) | |
| res = client.models.generate_content( | |
| model='gemini-2.5-flash', | |
| contents=[uploaded_file, prompt] | |
| ) | |
| srt_text = res.text | |
| client.files.delete(name=uploaded_file.name) | |
| lines = srt_text.split('\n') | |
| time_indices = [i for i, line in enumerate(lines) if '-->' in line] | |
| for i, time_idx in enumerate(time_indices): | |
| time_line = lines[time_idx] | |
| match = re.search(r'(\d{1,2}:\d{2}:\d{2}(?:[.,]\d{1,3})?)\s*-->\s*(\d{1,2}:\d{2}:\d{2}(?:[.,]\d{1,3})?)', time_line) | |
| if not match: continue | |
| start_ms = time_to_ms(match.group(1)) + (offset_secs * 1000) | |
| end_ms = time_to_ms(match.group(2)) + (offset_secs * 1000) | |
| max_allowed_ms = (offset_secs + 150) * 1000 | |
| start_ms = min(start_ms, max_allowed_ms) | |
| end_ms = min(end_ms, max_allowed_ms + 10000) | |
| text_end_idx = time_indices[i+1] if i < len(time_indices) - 1 else len(lines) | |
| text_lines = lines[time_idx+1:text_end_idx] | |
| clean_text = " ".join([l.strip() for l in text_lines if not re.match(r'^\d+$', l.strip())]).strip() | |
| if clean_text: | |
| all_subs.append({'start_ms': start_ms, 'end_ms': end_ms, 'text': clean_text}) | |
| if c_idx < len(chunk_files) - 1: | |
| await asyncio.sleep(8) | |
| if not all_subs: | |
| await status_msg.edit_text("❌ ဘာသာပြန်ရန် အသံရှာမတွေ့ပါ။ (သို့မဟုတ်) API Limit ပြည့်နေပါသည်။ အခြား Server သို့ပြောင်းကြည့်ပါ။") | |
| return | |
| # --- 3. Clean up SRT --- | |
| all_subs.sort(key=lambda x: x['start_ms']) | |
| for i in range(len(all_subs)): | |
| if all_subs[i]['end_ms'] <= all_subs[i]['start_ms']: | |
| all_subs[i]['end_ms'] = all_subs[i]['start_ms'] + 1000 | |
| if i > 0 and all_subs[i]['start_ms'] < all_subs[i-1]['end_ms']: | |
| all_subs[i]['start_ms'] = all_subs[i-1]['end_ms'] + 1 | |
| if all_subs[i]['end_ms'] <= all_subs[i]['start_ms']: | |
| all_subs[i]['end_ms'] = all_subs[i]['start_ms'] + 1000 | |
| all_subs[i]['start_str'] = ms_to_time(all_subs[i]['start_ms']) | |
| all_subs[i]['end_str'] = ms_to_time(all_subs[i]['end_ms']) | |
| clean_srt = "" | |
| for idx, sub in enumerate(all_subs): | |
| clean_srt += f"{idx + 1}\r\n{sub['start_str']} --> {sub['end_str']}\r\n{sub['text']}\r\n\r\n" | |
| srt_path = os.path.join(work_dir, "subs.srt") | |
| with open(srt_path, "w", encoding="utf-8") as f: | |
| f.write(clean_srt) | |
| # --- 4. TTS (Text-to-Speech) Generation --- | |
| await status_msg.edit_text("🗣 မြန်မာအသံထွက် ဖန်တီးနေပါတယ်...") | |
| chunk_paths = [] | |
| for i, sub in enumerate(all_subs): | |
| tts_path = os.path.join(work_dir, f"tts_{i}.mp3") | |
| cmd = ['edge-tts', '--voice', VOICE_TYPE, '--text', sub['text'], '--write-media', tts_path] | |
| proc = await asyncio.create_subprocess_exec(*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) | |
| await proc.communicate() | |
| if os.path.exists(tts_path): | |
| chunk_paths.append({'path': tts_path, 'start_ms': sub['start_ms'], 'end_ms': sub['end_ms']}) | |
| # --- 5. Custom Font Download --- | |
| font_path = os.path.join(work_dir, 'NotoSansMyanmar-Regular.ttf') | |
| try: | |
| urllib.request.urlretrieve('https://github.com/google/fonts/raw/main/ofl/notosansmyanmar/NotoSansMyanmar-Regular.ttf', font_path) | |
| except Exception as e: | |
| print("Could not download font:", e) | |
| fonts_conf = os.path.join(work_dir, 'fonts.conf') | |
| with open(fonts_conf, 'w') as f: | |
| f.write(f'<?xml version="1.0"?><fontconfig><dir>{work_dir}</dir><cachedir>/tmp/fonts-cache</cachedir></fontconfig>') | |
| await status_msg.edit_text("🎬 Video နှင့် အသံများကို ပြန်လည်ပေါင်းစပ်နေပါတယ်...") | |
| # --- 6. FFmpeg Mixing & Subtitle Burning --- | |
| out_video = os.path.join(work_dir, "output.mp4") | |
| has_audio = await has_audio_stream(video_path) | |
| keep_original = ORIGINAL_AUDIO == 'keep' and has_audio | |
| use_audio_mix = len(chunk_paths) > 0 | |
| video_duration = await get_media_duration(video_path) | |
| if video_duration <= 0: video_duration = 1.0 | |
| args = ['ffmpeg', '-y', '-i', video_path] | |
| filter_graph = "" | |
| if use_audio_mix: | |
| if keep_original: | |
| filter_graph += "[0:a]volume=1.0[orig_a];" | |
| elif has_audio: | |
| filter_graph += "[0:a]volume=0.0[orig_a];" | |
| else: | |
| filter_graph += f"anullsrc=channel_layout=stereo:sample_rate=44100:d={video_duration}[orig_a];" | |
| tts_amix_str = "" | |
| tts_inputs = 0 | |
| last_end_ms = 0 | |
| for i, c in enumerate(chunk_paths): | |
| args.extend(['-i', c['path']]) | |
| input_idx = i + 1 | |
| safe_start_ms = c['start_ms'] | |
| if safe_start_ms < last_end_ms + 200: | |
| safe_start_ms = last_end_ms + 200 | |
| in_duration = await get_media_duration(c['path']) | |
| if in_duration <= 0: in_duration = 1.0 | |
| target_duration = max(0.1, (c['end_ms'] - safe_start_ms) / 1000) | |
| ratio = in_duration / target_duration | |
| ratio = max(0.85, min(ratio, 1.6)) | |
| final_duration_ms = (in_duration / ratio) * 1000 | |
| last_end_ms = safe_start_ms + final_duration_ms | |
| atempo_str = "" | |
| r = ratio | |
| while r > 2.0: | |
| atempo_str += "atempo=2.0," | |
| r /= 2.0 | |
| while r < 0.5: | |
| atempo_str += "atempo=0.5," | |
| r *= 2.0 | |
| atempo_str += f"atempo={r}" | |
| pad_ms = round(safe_start_ms) | |
| filter_graph += f"[{input_idx}:a]{atempo_str},adelay={pad_ms}|{pad_ms}[a{i}];" | |
| tts_amix_str += f"[a{i}]" | |
| tts_inputs += 1 | |
| if tts_inputs > 1: | |
| filter_graph += f"{tts_amix_str}amix=inputs={tts_inputs}:duration=longest,apad,volume={tts_inputs}[ttsmix];" | |
| elif tts_inputs == 1: | |
| filter_graph += f"{tts_amix_str}apad[ttsmix];" | |
| if keep_original: | |
| filter_graph += f"[ttsmix]asplit=2[tts_sc][tts_out];" | |
| filter_graph += f"[orig_a][tts_sc]sidechaincompress=threshold=0.04:ratio=6.0:attack=10:release=400[ducked_orig];" | |
| filter_graph += f"[ducked_orig][tts_out]amix=inputs=2:duration=first:dropout_transition=0,volume=2[outa]" | |
| else: | |
| filter_graph += f"[orig_a][ttsmix]amix=inputs=2:duration=first:dropout_transition=0,volume=2[outa]" | |
| safe_srt = srt_path.replace('\\', '/').replace(":", "\\\\:") | |
| safe_dir = work_dir.replace('\\', '/').replace(":", "\\\\:") | |
| if use_audio_mix: | |
| filter_graph += f";[0:v]subtitles='{safe_srt}':fontsdir='{safe_dir}':force_style='Fontname=Noto Sans Myanmar,FontSize=24,MarginV=20'[outv]" | |
| args.extend(['-filter_complex', filter_graph]) | |
| args.extend(['-map', '[outv]', '-map', '[outa]']) | |
| else: | |
| args.extend(['-vf', f"subtitles='{safe_srt}':fontsdir='{safe_dir}':force_style='Fontname=Noto Sans Myanmar,FontSize=24,MarginV=20'"]) | |
| args.extend(['-map', '0:v']) | |
| if has_audio: args.extend(['-map', '0:a']) | |
| args.extend(['-c:v', 'libx264', '-preset', 'fast', '-crf', '28']) | |
| if use_audio_mix: args.extend(['-c:a', 'aac', '-b:a', '128k']) | |
| elif has_audio: args.extend(['-c:a', 'copy']) | |
| args.append(out_video) | |
| ffmpeg_env = os.environ.copy() | |
| ffmpeg_env['FONTCONFIG_FILE'] = fonts_conf | |
| proc = await asyncio.create_subprocess_exec(*args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env=ffmpeg_env) | |
| _, stderr = await proc.communicate() | |
| if proc.returncode != 0: | |
| print("FFmpeg Error:\n", stderr.decode()) | |
| await status_msg.edit_text("❌ Video ကို Process လုပ်ရာတွင် အမှားအယွင်းဖြစ်သွားပါသည်။") | |
| return | |
| await status_msg.edit_text("📤 အသင့်ဖြစ်ပါပြီ၊ ပေးပို့နေပါပြီ...") | |
| with open(out_video, 'rb') as f: | |
| await context.bot.send_video(chat_id=msg.chat_id, video=f, caption=f"✅ ဘာသာပြန်ဆိုထားသော Video ရပါပြီ။\n(အသုံးပြုခဲ့သော Server - {selected_server_id})") | |
| await status_msg.delete() | |
| except Exception as e: | |
| import traceback | |
| traceback.print_exc() | |
| await status_msg.edit_text(f"❌ အမှားအယွင်းဖြစ်သွားပါသည်: {str(e)}\n\n💡 API Error ဖြစ်ပါက /start ကိုနှိပ်၍ အခြား Server ပြောင်းပါ။") | |
| def main(): | |
| # 1. Hugging Face ၏ Health Check ကိုကျော်ဖြတ်ရန် Dummy Server အရင် Run မည် | |
| threading.Thread(target=start_health_check_server, daemon=True).start() | |
| # 2. Telegram Bot ကို အငြိမ်ဆုံး Polling စနစ်ဖြင့် Run မည် | |
| application = Application.builder().token(TG_BOT_TOKEN).connect_timeout(60.0).read_timeout(60.0).build() | |
| application.add_handler(CommandHandler("start", start)) | |
| application.add_handler(CallbackQueryHandler(button_callback, pattern='^server_')) | |
| application.add_handler(MessageHandler(filters.VIDEO | filters.Document.ALL, process_video)) | |
| print("MyVideoBot is starting on Hugging Face Spaces (Polling Mode with Health Check)...") | |
| # drop_pending_updates=True ထည့်ထားခြင်းဖြင့် အရင်က ရပ်သွားချိန်နှိပ်ခဲ့သော ခလုတ်များကို လျစ်လျူရှုမည် | |
| application.run_polling(drop_pending_updates=True) | |
| if __name__ == '__main__': | |
| main() |