Autorecap commited on
Commit
c819365
·
verified ·
1 Parent(s): 3151436

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -72
app.py CHANGED
@@ -1,19 +1,19 @@
1
  import gradio as gr
2
  from google import genai
3
- import yt_dlp
4
  from faster_whisper import WhisperModel
 
5
  import asyncio
6
  import edge_tts
7
  import os
8
  import shutil
9
  import re
10
 
11
- # Lightweight Faster-Whisper Model ကို Load လုပ်ခြင်း
12
  print("Loading Faster-Whisper Model...")
13
  model = WhisperModel("tiny", device="cpu", compute_type="int8")
14
 
15
  # =====================================================================
16
- # 🔽 YOUTUBE AUDIO DOWNLOADER (EXTREME NETWORK BYPASS)
17
  # =====================================================================
18
  def get_youtube_video_id(url):
19
  """YouTube URL ထဲကနေ Video ID ကို သီးသန့်ခွဲထုတ်ရန်"""
@@ -21,43 +21,35 @@ def get_youtube_video_id(url):
21
  match = re.search(pattern, url)
22
  return match.group(1) if match else None
23
 
24
- def download_youtube_audio(youtube_url, download_dir="temp_yt"):
25
- if os.path.exists(download_dir):
26
- shutil.rmtree(download_dir)
27
- os.makedirs(download_dir, exist_ok=True)
28
-
29
- # URL ကနေ ID ကိုပဲ သီးသန့်ယူပြီး YouTube Link အသစ်ပြန်တည်ဆောက်ကာ Block တာကို ကျော်ခြင်း
30
  video_id = get_youtube_video_id(youtube_url)
31
- clean_url = f"https://www.youtube.com/watch?v={video_id}" if video_id else youtube_url
32
-
33
- output_template = os.path.join(download_dir, "yt_audio.%(ext)s")
34
-
35
- ydl_opts = {
36
- 'format': 'ba/b', # Best Audio Stream ကို တိုက်ရိုက်ဆွဲရန်
37
- 'outtmpl': output_template,
38
- 'postprocessors': [{
39
- 'key': 'FFmpegExtractAudio',
40
- 'preferredcodec': 'mp3',
41
- 'preferredquality': '192',
42
- }],
43
- 'quiet': True,
44
- 'nocheckcertificate': True, # SSL Error မတက်စေရန် ကျော်ခိုင်းခြင်း
45
- 'prefer_insecure': True,
46
- 'extract_flat': False, # Playlist မဟုတ်ဘဲ ဗီဒီယိုတစ်ခုတည်းကိုပဲ အာရုံစိုက်ရန်
47
- 'source_address': '0.0.0.0', # IPv6 Block ခံရမှုကို ကျော်ရန် IPv4 သုံးခြင်း
48
- 'http_chunk_size': 1048576, # Stream ဒေါင်းလုဒ် ပိုမိုမြန်ဆန်စေရန် Chunk size သတ်မှတ်ချက်
49
- 'headers': {
50
- 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36',
51
- 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8',
52
- 'Accept-Language': 'en-US,en;q=0.9',
53
- }
54
- }
55
-
56
- with yt_dlp.YoutubeDL(ydl_opts) as ydl:
57
- ydl.download([clean_url])
58
 
59
- expected_file = os.path.join(download_dir, "yt_audio.mp3")
60
- return expected_file if os.path.exists(expected_file) else None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
  # =====================================================================
63
  # 📝 TIME FORMATTER
@@ -109,7 +101,7 @@ def process_hybrid_recap(movie_name, episode_part, youtube_url, api_key, duratio
109
  word_count = "စာလုံးရေ ၃၀၀ ကျော် ခန့် တိုတိုနှင့် လိုရင်း"
110
  length_desc = "၁ မိနစ်စာ Short ဗီဒီယို"
111
  elif duration_choice == "Medium (YouTube - 3 to 5 Mins)":
112
- word_count = "စာလုံးရေ ၁၁၀၀ ကျော်ခန့် ရှည်ရှည်လျားလျား"
113
  length_desc = "၃ မိနစ်မှ ၅ မိနစ်စာ YouTube ဗီဒီယို"
114
  else:
115
  word_count = "စာလုံးရေ ၂၅၀၀ ကျော်ခန့် အခန်းဆက်မလွတ်စေဘဲ အသေးစိတ်အကျဆုံး"
@@ -122,42 +114,30 @@ def process_hybrid_recap(movie_name, episode_part, youtube_url, api_key, duratio
122
  episode_info = f"အထူးသဖြင့် ၎င်းဇာတ်လမ်း၏ '{episode_part.strip()}' ကိုသာ သီးသန့် အသားပေးပြီး " if episode_part and episode_part.strip() else ""
123
 
124
  try:
 
125
  if youtube_url and youtube_url.strip() != "":
126
- progress(0.15, desc="🔽 YouTube မှ အသံဖိုင်ကို ဒေါင်းလုဒ်ဆွဲနေပါသည်...")
127
- audio_file = download_youtube_audio(youtube_url)
128
 
129
- if audio_file:
130
- progress(0.40, desc="📝 Faster-Whisper ဖြင့် စာသားများဖတ်ပြီး မြန်မာ SRT ပြန်ဆိုနေပါသည်...")
131
- segments, _ = model.transcribe(audio_file, beam_size=1)
 
 
 
 
 
132
 
133
- raw_chunks = []
134
- for segment in segments:
135
- raw_chunks.append({
136
- "start": format_time(segment.start),
137
- "end": format_time(segment.end),
138
- "text": segment.text.strip()
139
- })
140
- full_english_context += f" {segment.text.strip()}"
141
 
142
- if raw_chunks:
143
- srt_prompt = (
144
- "You are an expert subtitler. Translate the following English dialogue chunks into professional, natural Burmese movie subtitles. "
145
- "Keep the exact same block format. Return ONLY the translated blocks. Do not add any extra text or conversational filler.\n\n"
146
- )
147
- for i, chunk in enumerate(raw_chunks, start=1):
148
- srt_prompt += f"{i}\n{chunk['start']} --> {chunk['end']}\n{chunk['text']}\n\n"
149
-
150
- srt_response = client.models.generate_content(
151
- model='gemini-2.5-flash',
152
- contents=srt_prompt
153
- )
154
-
155
- burmese_srt_filename = "translated_burmese.srt"
156
- with open(burmese_srt_filename, "w", encoding="utf-8") as f:
157
- f.write(srt_response.text.strip())
158
-
159
- if os.path.exists("temp_yt"):
160
- shutil.rmtree("temp_yt")
161
 
162
  progress(0.70, desc="⚡ Gemini AI ကနေ စိတ်လှုပ်ရှားဖွယ် မြန်မာ Recap Script ရေးသားနေပါသည်...")
163
  target_movie = movie_name if (movie_name and movie_name.strip() != "") else "ပေးထားသော ဗီဒီယိုဇာတ်လမ်း"
@@ -189,7 +169,6 @@ def process_hybrid_recap(movie_name, episode_part, youtube_url, api_key, duratio
189
  return burmese_script, burmese_srt_filename, voice_mp3
190
 
191
  except Exception as e:
192
- if os.path.exists("temp_yt"): shutil.rmtree("temp_yt")
193
  return f"❌ Error တက်သွားပါတယ်- {str(e)}", None, None
194
 
195
  # =====================================================================
 
1
  import gradio as gr
2
  from google import genai
 
3
  from faster_whisper import WhisperModel
4
+ from youtube_transcript_api import YouTubeTranscriptApi
5
  import asyncio
6
  import edge_tts
7
  import os
8
  import shutil
9
  import re
10
 
11
+ # Lightweight Faster-Whisper Model ကို Load လုပ်ခြင်း (Local File များအတွက် ချန်ထားခြင်း)
12
  print("Loading Faster-Whisper Model...")
13
  model = WhisperModel("tiny", device="cpu", compute_type="int8")
14
 
15
  # =====================================================================
16
+ # 🔽 YOUTUBE TRANSCRIPT EXTRACTOR (NETWORK ERROR BYPASS FIXED)
17
  # =====================================================================
18
  def get_youtube_video_id(url):
19
  """YouTube URL ထဲကနေ Video ID ကို သီးသန့်ခွဲထုတ်ရန်"""
 
21
  match = re.search(pattern, url)
22
  return match.group(1) if match else None
23
 
24
+ def get_youtube_transcript_chunks(youtube_url):
25
+ """yt-dlp အစား YouTube API မှ Transcript ကို တိုက်ရိုက်ဆွဲထုတ်ယူခြင်း"""
 
 
 
 
26
  video_id = get_youtube_video_id(youtube_url)
27
+ if not video_id:
28
+ return None, ""
29
+
30
+ try:
31
+ # English သို့မဟုတ် English (US) စာသားများကို အဓိက လှမ်းယူခြင်း
32
+ transcript_list = YouTubeTranscriptApi.get_transcript(video_id, languages=['en', 'en-US'])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
+ raw_chunks = []
35
+ full_english_context = ""
36
+
37
+ for entry in transcript_list:
38
+ start_sec = entry['start']
39
+ end_sec = entry['start'] + entry['duration']
40
+ text_content = entry['text'].strip()
41
+
42
+ raw_chunks.append({
43
+ "start": format_time(start_sec),
44
+ "end": format_time(end_sec),
45
+ "text": text_content
46
+ })
47
+ full_english_context += f" {text_content}"
48
+
49
+ return raw_chunks, full_english_context.strip()
50
+ except Exception as e:
51
+ print(f"Transcript Fetching Error: {e}")
52
+ return None, ""
53
 
54
  # =====================================================================
55
  # 📝 TIME FORMATTER
 
101
  word_count = "စာလုံးရေ ၃၀၀ ကျော် ခန့် တိုတိုနှင့် လိုရင်း"
102
  length_desc = "၁ မိနစ်စာ Short ဗီဒီယို"
103
  elif duration_choice == "Medium (YouTube - 3 to 5 Mins)":
104
+ word_count = "စာလုံးရေ ၁၁၀၀ ကျော်ခန့် ရှည်ရှည်လျားလျား"
105
  length_desc = "၃ မိနစ်မှ ၅ မိနစ်စာ YouTube ဗီဒီယို"
106
  else:
107
  word_count = "စာလုံးရေ ၂၅၀၀ ကျော်ခန့် အခန်းဆက်မလွတ်စေဘဲ အသေးစိတ်အကျဆုံး"
 
114
  episode_info = f"အထူးသဖြင့် ၎င်းဇာတ်လမ်း၏ '{episode_part.strip()}' ကိုသာ သီးသန့် အသားပေးပြီး " if episode_part and episode_part.strip() else ""
115
 
116
  try:
117
+ # YouTube Link ပါလာခဲ့လျှင် API သုံးပြီး Transcript ကို တိုက်ရိုက်ဆွဲယူမည်
118
  if youtube_url and youtube_url.strip() != "":
119
+ progress(0.20, desc="🔽 YouTube မှ စာသား (Transcript) ကို Network ပိတ်ဆို့မှုမရှိဘဲ ရယူနေပါသည်...")
120
+ raw_chunks, full_english_context = get_youtube_transcript_chunks(youtube_url)
121
 
122
+ if raw_chunks:
123
+ progress(0.50, desc="📝 Gemini AI ဖြင့် မူရင်း English စာသားများကို မြန်မာ SRT Subtitle သို့ ပြန်ဆိုနေပါသည်...")
124
+ srt_prompt = (
125
+ "You are an expert subtitler. Translate the following English dialogue chunks into professional, natural Burmese movie subtitles. "
126
+ "Keep the exact same block format. Return ONLY the translated blocks. Do not add any extra text or conversational filler.\n\n"
127
+ )
128
+ for i, chunk in enumerate(raw_chunks, start=1):
129
+ srt_prompt += f"{i}\n{chunk['start']} --> {chunk['end']}\n{chunk['text']}\n\n"
130
 
131
+ srt_response = client.models.generate_content(
132
+ model='gemini-2.5-flash',
133
+ contents=srt_prompt
134
+ )
 
 
 
 
135
 
136
+ burmese_srt_filename = "translated_burmese.srt"
137
+ with open(burmese_srt_filename, "w", encoding="utf-8") as f:
138
+ f.write(srt_response.text.strip())
139
+ else:
140
+ print("စာသား (Transcript) မရရှိပါ သို့မဟုတ် ပိတ်ထားပါသဖြင့် ရုပ်ရှင်နာမည်ဖြင့်သာ ရှေ့ဆက်ပါမည်။")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
 
142
  progress(0.70, desc="⚡ Gemini AI ကနေ စိတ်လှုပ်ရှားဖွယ် မြန်မာ Recap Script ရေးသားနေပါသည်...")
143
  target_movie = movie_name if (movie_name and movie_name.strip() != "") else "ပေးထားသော ဗီဒီယိုဇာတ်လမ်း"
 
169
  return burmese_script, burmese_srt_filename, voice_mp3
170
 
171
  except Exception as e:
 
172
  return f"❌ Error တက်သွားပါတယ်- {str(e)}", None, None
173
 
174
  # =====================================================================