Update app.py
Browse files1234567878910111213141510161718192021122223141524252627282930313233343536193738394041424325444546274748495051525354343536555657585960616263646566676838697040414243444546474849505152535455567172737475765859606162636465667778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114686970115116117118119120121122123124125126127128129130131132133134135136137737413813914014114278143144801451468283147148149851501511521532 unmodified lines15615715894159import osimport subprocessimport loggingimport gradio as grimport whisperimport torchfrom deep_translator import GoogleTranslatorimport imageio_ffmpegimport torchimport spaces # spaces library ကို import လုပ်ပါ
# Set up logging for debugging on Hugging Face Containerlogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)
# 1. FFmpeg Binary Path Configurationtry:FFMPEG_EXE = imageio_ffmpeg.get_ffmpeg_exe() FFMPEG_EXE = imageio_ffmpeg.get_ffmpeg_exe() logger.info(f"FFmpeg binary path: {FFMPEG_EXE}")except Exception as e: logger.error(f"Error locating FFmpeg: {e}") FFMPEG_EXE = "ffmpeg"
# Device ကို Auto detect လုပ်ခြင်း (GPU ရှိရင် GPU သုံးမည်)# 2. Check Device & Load Whisper Model globallydevice = "cuda" if torch.cuda.is_available() else "cpu"print(f"Loading Whisper Model on {device}...")whisper_model = whisper.load_model("small", device=device)logger.info(f"Using device: {device}")
try: # 'small' model provides optimal speed and accuracy balance for Asian languages (Chinese/Japanese/etc.) whisper_model = whisper.load_model("small", device=device) logger.info("Whisper model loaded successfully.")except Exception as e: logger.error(f"Failed to load Whisper model: {e}") whisper_model = None
# 3. Translator Engine Setuptranslator = GoogleTranslator(source='auto', target='my')
def translate_to_myanmar(text):def translate_to_myanmar(text: str) -> str: """Translates input text to Myanmar using Google Translator.""" if not text or not text.strip(): return "" try: return translator.translate(text) except Exception as e: return text logger.warning(f"Translation failed for '{text}': {e}") return text # Fallback to original text if translation API fails
def format_timestamp(seconds):def format_timestamp(seconds: float) -> str: """Formats seconds into SRT timestamp format HH:MM:SS,mmm.""" hours = int(seconds // 3600) minutes = int((seconds % 3600) // 60) secs = int(seconds % 60) millis = int((seconds - int(seconds)) * 1000) return f"{hours:02d}:{minutes:02d}:{secs:02d},{millis:03d}"
# Hugging Face GPU သုံးနိုင်ရန် @spaces.GPU တင်ပေးရပါသည်@spaces.GPUdef process_video(video_path, position_choice):# Hugging Face ZeroGPU Support Integrationtry: import spaces @spaces.GPU def run_whisper(video_path): return whisper_model.transcribe(video_path)except Exception: # Fallback if running on standard CPU space without 'spaces' module def run_whisper(video_path): return whisper_model.transcribe(video_path)
def process_video(video_path: str, position_choice: str): """Main function handling transcription, translation, and subtitle burning.""" if video_path is None: return None, None, "❌ ကျေးဇူးပြု၍ Video Upload တင်ပေးပါဦး။" return None, None, "❌ ကျေးဇူးပြု၍ Video တစ်ခု Upload တင်ပေးပါ။" result = whisper_model.transcribe(video_path) segments = result.get("segments", []) srt_path = "myanmar_subtitles.srt" with open(srt_path, "w", encoding="utf-8") as f: for idx, segment in enumerate(segments, start=1): start_time = format_timestamp(segment['start']) end_time = format_timestamp(segment['end']) original_text = segment['text'] myanmar_text = translate_to_myanmar(original_text) f.write(f"{idx}\n{start_time} --> {end_time}\n{myanmar_text}\n\n") if position_choice == "Original Sub ၏ အပေါ်နား": style_setting = "Alignment=2,MarginV=70" else: style_setting = "Alignment=6,MarginV=20" if whisper_model is None: return None, None, "❌ Whisper Model မတက်ပါ။ Server ကို ပြန်လည် စစ်ဆေးပါ။"
try: logger.info(f"Processing video: {video_path}") output_video_path = "output_video.mp4" ffmpeg_cmd = [ FFMPEG_EXE, "-y", "-i", video_path, "-vf", f"subtitles={srt_path}:force_style='FontSize=18,PrimaryColour=&H00FFFF&,OutlineColour=&H000000&,BorderStyle=1,{style_setting}'", "-c:a", "copy", output_video_path ] subprocess.run(ffmpeg_cmd, check=True) return output_video_path, srt_path, "✅ မြန်မာစာတန်းထိုးပြီးပါပြီ!" # Step A: Speech-to-Text with Auto Language Detection result = run_whisper(video_path) detected_lang = result.get("language", "Unknown").upper() segments = result.get("segments", [])
# Step B: Generate SRT File with Myanmar Subtitles srt_path = "output_myanmar_subtitles.srt" with open(srt_path, "w", encoding="utf-8") as f: for idx, segment in enumerate(segments, start=1): start_time = format_timestamp(segment['start']) end_time = format_timestamp(segment['end']) original_text = segment['text'] myanmar_text = translate_to_myanmar(original_text) f.write(f"{idx}\n") f.write(f"{start_time} --> {end_time}\n") f.write(f"{myanmar_text}\n\n")
# Step C: Subtitle Style & Position Setup # MarginV=70: Original Subtitle (Bottom) ရဲ့ အပေါ်သို့ တင်ပေးသည် # Alignment=6: Video ရဲ့ အပေါ်ထိပ် (Top Center) သို့ တင်ပေးသည် if position_choice == "Original Sub ၏ အပေါ်နား": style_setting = "Alignment=2,MarginV=70" else: style_setting = "Alignment=6,MarginV=20"
output_video_path = "output_processed_video.mp4" # FFmpeg Command ffmpeg_cmd = [ FFMPEG_EXE, "-y", "-i", video_path, "-vf", f"subtitles={srt_path}:force_style='FontSize=18,PrimaryColour=&H00FFFF&,OutlineColour=&H000000&,BorderStyle=1,{style_setting}'", "-c:a", "copy", output_video_path ]
# UI Setupwith gr.Blocks(title="Auto Myanmar Subtitle Generator") as demo: gr.Markdown("## 🎥 Auto Language Detect & Myanmar Subtitle Generator") logger.info("Running FFmpeg encoding...") subprocess.run(ffmpeg_cmd, check=True) status_msg = f"✅ မြန်မာစာတန်းထိုးပြီးပါပြီ! (Detected Language: {detected_lang})" return output_video_path, srt_path, status_msg
except subprocess.CalledProcessError as e: logger.error(f"FFmpeg Error: {e}") return None, None, "❌ FFmpeg ဖြင့် ဗီဒီယို ပြုလုပ်စဉ် Error တက်သွားပါသည်။" except Exception as e: logger.error(f"General Processing Error: {e}") return None, None, f"❌ Error: {str(e)}"
# 4. Gradio UI Architecturewith gr.Blocks(title="AI Video Myanmar Subtitle Generator", theme=gr.themes.Soft()) as demo: gr.Markdown( """ # 🎥 AI Video Language Detect & Myanmar Subtitle Generator Video Upload တင်လိုက်သည်နှင့် Whisper AI မှ ဘာသာစကားကို Auto Detect လုပ်ပေးပြီး မြန်မာစာတန်းထိုးပေးပါမည်။ """ ) with gr.Row(): with gr.Column(): video_input = gr.Video(label="Upload Original Video") with gr.Column(scale=1): video_input = gr.Video(label="Upload Video File") position_opt = gr.Radio( choices=["Original Sub ၏ အပေါ်နား", "Video ၏ ထိပ်ဆုံး (Top)"], value="Original Sub ၏ အပေါ်နား", label="မြန်မာစာတန်း ထားရှိလိုသော နေရာ" label="မြန်မာစာတန်း ထိုးလိုသော နေရာ" ) submit_btn = gr.Button("မြန်မာစာတန်းထိုးမည်", variant="primary") submit_btn = gr.Button("မြန်မာစာတန်းထိုးမည် (Generate)", variant="primary") with gr.Column(): video_output = gr.Video(label="Result Video") with gr.Column(scale=1): video_output = gr.Video(label="Result Video (With Myanmar Subtitles)") srt_output = gr.File(label="Download Subtitle File (.srt)") status_output = gr.Textbox(label="Status") status_output = gr.Textbox(label="Status Logging", interactive=False) submit_btn.click( fn=process_video,2 unmodified lines )
if __name__ == "__main__": demo.launch() demo.queue().launch()app.py+115-50