Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137import osimport subprocessimport loggingimport gradio as grimport whisperimport torchfrom deep_translator import GoogleTranslatorimport imageio_ffmpegimport spaces# Server Logging setuplogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)# 1. FFmpeg Binary Path Configurationtry: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"# 2. Whisper Model Loading (CPU တွင် အခြေခံ Load လုပ်ထားသည်)print("Loading Whisper Model...")whisper_model = whisper.load_model("small")# 3. Translation Engine Setup (Auto-Detect -> Target: Myanmar)translator = GoogleTranslator(source='auto', target='my')def translate_to_myanmar(text: str) -> str:"""တရုတ် သို့မဟုတ် အခြားစကားပြော စာသားများကို မြန်မာလို ဘာသာပြန်ပေးသည့် Function"""if not text or not text.strip():return ""try:translated_text = translator.translate(text)return translated_textexcept Exception as e:logger.warning(f"Translation failed for '{text}': {e}")return textdef format_timestamp(seconds: float) -> str:"""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}"# 4. Hugging Face ZeroGPU Entry Function# Gradio ၏ event handler ဖြင့် တိုက်ရိုက် ချိတ်ဆက်နိုင်ရန် @spaces.GPU အောက်တွင် Process အားလုံးကို တစ်ပါတည်း ထည့်သွင်းထားသည်@spaces.GPUdef process_video_on_gpu(video_path: str):"""Main Function: Directly wrapped inside @spaces.GPU for HF ZeroGPU Compliance"""if video_path is None:return None, None, "❌ ကျေးဇူးပြု၍ Video Upload တင်ပေးပါဦး။"try:logger.info(f"Processing video on ZeroGPU: {video_path}")# Step A: GPU ပေါ်တွင် Audio Transcribe ပြုလုပ်ခြင်း# task="transcribe" ဖြင့် မူရင်းအသံကို စာသားပြောင်းပေးသည်result = whisper_model.transcribe(video_path, task="transcribe")detected_lang = result.get("language", "Unknown").upper()segments = result.get("segments", [])# Step B: မြန်မာလို ဘာသာပြန်ပြီး .srt Subtitle ဖိုင်ဖန်တီးခြင်း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 & Positioning# Alignment=2: ဗီဒီယို၏ အောက်ခြေအလယ်# MarginV=55: မူရင်း တရုတ်စာတန်း၏ 'အပေါ်နား ကပ်လျက်' တွင် မြန်မာစာတန်း ကွက်တိ ပေါ်လာစေရန်style_setting = "Alignment=2,MarginV=55,FontSize=18,PrimaryColour=&H00FFFF&,OutlineColour=&H000000&,BorderStyle=1"output_video_path = "output_processed_video.mp4"# FFmpeg Command ဖြင့် Video ပေါ် စာတန်း Overlay ကပ်ခြင်းffmpeg_cmd = [FFMPEG_EXE, "-y","-i", video_path,"-vf", f"subtitles={srt_path}:force_style='{style_setting}'","-c:a", "copy",output_video_path]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_msgexcept 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)}"# 5. Gradio UI Layout Setupwith gr.Blocks(title="Auto Video Myanmar Subtitle Generator", theme=gr.themes.Soft()) as demo:gr.Markdown("""# 🎥 AI Animation Video Myanmar Subtitle Generator (ZeroGPU Fixed)Video Upload တင်လိုက်သည်နှင့် တရုတ်အသံထွက်ကို Auto Detect လုပ်ပေးပြီး မူရင်း တရုတ်စာတန်း၏ အပေါ် ကပ်လျက်တွင် မြန်မာစာတန်းထိုးပေးပါမည်။""")with gr.Row():with gr.Column(scale=1):video_input = gr.Video(label="Upload Original Video")submit_btn = gr.Button("မြန်မာစာတန်းထိုးမည် (Generate)", variant="primary")with gr.Column(scale=1):video_output = gr.Video(label="Result Video (Download လုပ်နိုင်သည်)")srt_output = gr.File(label="Download Subtitle File (.srt)")status_output = gr.Textbox(label="Status Logging", interactive=False)# Gradio Click Event မှာ @spaces.GPU Decorated Function ကို တိုက်ရိုက် ခေါ်ထားပါသည်submit_btn.click(fn=process_video_on_gpu,inputs=[video_input],outputs=[video_output, srt_output, status_output])if __name__ == "__main__":demo.queue().launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122import osimport tempfileimport cv2import ffmpegimport streamlit as stimport whisperfrom deep_translator import GoogleTranslator# App Configst.set_page_config(page_title="Burmese Video Subtitle Generator", layout="centered")st.title("🎥 Video Auto Burmese Subtitle Generator")st.write("Upload a video to translate voice/subtitles into Burmese and download.")@st.cache_resourcedef load_whisper_model():# Hugging Face Free CPU မွာ tiny သို့မဟုတ် base model က အမြန်ဆုံးနှင့် သင့်တော်ဆုံးပါreturn whisper.load_model("tiny")with st.spinner("AI Model Loading..."):model = load_whisper_model()def format_timestamp(seconds: float) -> str:millis = int((seconds % 1) * 1000)seconds = int(seconds)minutes = seconds // 60hours = minutes // 60seconds = seconds % 60minutes = minutes % 60return f"{hours:02}:{minutes:02}:{seconds:02},{millis:03}"def generate_burmese_srt(transcript_result, srt_filepath):translator = GoogleTranslator(source="auto", target="my")with open(srt_filepath, "w", encoding="utf-8") as f:for idx, segment in enumerate(transcript_result["segments"], start=1):start_time = format_timestamp(segment["start"])end_time = format_timestamp(segment["end"])original_text = segment["text"].strip()try:translated_text = translator.translate(original_text)except Exception:translated_text = original_textf.write(f"{idx}\n")f.write(f"{start_time} --> {end_time}\n")f.write(f"{translated_text}\n\n")def burn_subtitles_ffmpeg(input_video, srt_file, output_video):try:srt_file_clean = srt_file.replace("\\", "/").replace(":", "\\:")video_stream = ffmpeg.input(input_video)audio_stream = video_stream.audiooutput = ffmpeg.output(video_stream.filter("subtitles",srt_file_clean,force_style="FontSize=16,PrimaryColour=&H00FFFF,OutlineColour=&H000000,BorderStyle=3",),audio_stream,output_video,vcodec="libx264",acodec="aac",strict="experimental",)ffmpeg.run(output, overwrite_output=True, capture_stdout=True, capture_stderr=True)return Trueexcept Exception as e:st.error(f"Processing Error: {str(e)}")return Falseuploaded_file = st.file_uploader("Choose Video File", type=["mp4", "mov", "avi"])if uploaded_file is not None:tfile = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4")tfile.write(uploaded_file.read())input_video_path = tfile.namecap = cv2.VideoCapture(input_video_path)width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))cap.release()st.video(input_video_path)st.info(f"Original Resolution: {width} x {height}")if st.button("🚀 Generate Burmese Subtitles"):srt_path = input_video_path.replace(".mp4", ".srt")output_video_path = input_video_path.replace(".mp4", "_burmese_sub.mp4")with st.spinner("Processing video... Please wait..."):result = model.transcribe(input_video_path)generate_burmese_srt(result, srt_path)success = burn_subtitles_ffmpeg(input_video_path, srt_path, output_video_path)if success:st.success("Done!")st.video(output_video_path)with open(output_video_path, "rb") as video_file:st.download_button(label="📥 Download Subtitled Video",data=video_file,file_name="burmese_subtitled_video.mp4",mime="video/mp4",)
app.py+115-130