Files changed (1) hide show
  1. app.py +0 -552
app.py CHANGED
@@ -1,552 +0,0 @@
1
- import gradio as gr
2
- from faster_whisper import WhisperModel
3
- import os
4
- import subprocess
5
- import cv2
6
- import asyncio
7
- import edge_tts
8
- import shutil
9
- import time
10
- import numpy as np
11
- import re
12
- import json
13
- import uuid # 👈 Session ID ထုတ်ရန်အတွက် Import လုပ်ခြင်း
14
- from google import genai
15
- from datetime import datetime, date
16
- from PIL import Image, ImageDraw, ImageFont
17
-
18
- # =====================================================================
19
- # ⚙️ SECURITY SETTINGS & LOGIN CONFIG
20
- # =====================================================================
21
- MAX_SUBTITLE_DURATION_SECONDS = 7.0
22
-
23
- # 👥 LOGIN ACCOUNTS CONFIG (အကောင့်တစ်ခုတည်းကို လူအများ မျှသုံးနိုင်ပါသည်)
24
- ACCOUNTS = {
25
- "user1": "123123", # Free User (Session/Browser အလိုက် တစ်ရက် ၂ ပုဒ်)
26
- "admin": "admin789" # Admin User (Unlimited)
27
- }
28
-
29
- EXPIRY_DATE_STR = "2026-8-31"
30
-
31
- # 🛑 USER RATE LIMIT TRACKER (Session/Browser ID အလိုက် ရေတွက်မည်)
32
- USER_LIMIT_TRACKER = {}
33
-
34
- SYSTEM_INSTRUCTION = "You are a professional movie recap writer. Translate movie subtitle lines into natural, engaging, and thrilling Burmese movie recap style. Keep it concise."
35
- MODEL_NAME = "gemini-2.5-flash"
36
-
37
- def check_app_expiry():
38
- try:
39
- expiry_date = datetime.strptime(EXPIRY_DATE_STR, "%Y-%m-%d").date()
40
- current_date = datetime.now().date()
41
- if current_date > expiry_date:
42
- return False, f"❌ ဤ App သည် သက်တမ်းကုန်ဆုံးသွားပါပြီ ({EXPIRY_DATE_STR})။"
43
- return True, "Active"
44
- except Exception as e:
45
- return False, f"လုံခြုံရေး စစ်ဆေးမှု မှားယွင်းနေပါသည်- {str(e)}"
46
-
47
- print("Loading Multilingual Faster-Whisper Base Model...")
48
- model = WhisperModel("base", device="cpu", compute_type="int8", cpu_threads=4)
49
-
50
- # =====================================================================
51
- # 🖼️ REAL-TIME INTERACTIVE PREVIEW GENERATOR
52
- # =====================================================================
53
- def update_preview_image(video_path, blur_y_percent, blur_strength):
54
- if not video_path: return None
55
- try:
56
- cap = cv2.VideoCapture(video_path)
57
- ret, frame = cap.read()
58
- cap.release()
59
- if not ret: return None
60
-
61
- h_o, w_o, _ = frame.shape
62
- b_h = int(h_o * 0.12)
63
- b_y = max(0, min(int(h_o * (blur_y_percent / 100)) - (b_h // 2), h_o - b_h))
64
-
65
- k_size = int(blur_strength)
66
- if k_size % 2 == 0: k_size += 1
67
-
68
- preview_frame = frame.copy()
69
-
70
- roi = preview_frame[b_y:b_y+b_h, 0:w_o]
71
- if roi.shape[0] > 0 and roi.shape[1] > 0:
72
- small_roi = cv2.resize(roi, (w_o // 4, b_h // 4), interpolation=cv2.INTER_LINEAR)
73
- blurred_small = cv2.GaussianBlur(small_roi, (k_size // 4 | 1, k_size // 4 | 1), 0)
74
- preview_frame[b_y:b_y+b_h, 0:w_o] = cv2.resize(blurred_small, (w_o, b_h), interpolation=cv2.INTER_LINEAR)
75
- cv2.rectangle(preview_frame, (0, b_y), (w_o, b_y+b_h), (0, 0, 255), 3)
76
-
77
- preview_rgb = cv2.cvtColor(preview_frame, cv2.COLOR_BGR2RGB)
78
- return Image.fromarray(preview_rgb)
79
- except Exception as e:
80
- print(f"Preview Error: {e}")
81
- return None
82
-
83
- # =====================================================================
84
- # ⚡ DYNAMIC USER-PROVIDED API KEY TRANSLATION ENGINE
85
- # =====================================================================
86
- def google_backup_translate(text, source_lang="en"):
87
- from urllib.parse import quote
88
- import urllib.request
89
- import json
90
- try:
91
- url = f"https://translate.googleapis.com/translate_a/single?client=gtx&sl={source_lang}&tl=my&dt=t&q={quote(text)}"
92
- req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
93
- response = urllib.request.urlopen(req, timeout=5).read().decode('utf-8')
94
- result = json.loads(response)
95
- return result[0][0][0] or text
96
- except:
97
- return text
98
-
99
- def translate_segments_batch(segments, user_api_key, source_lang="en"):
100
- if not segments: return segments
101
-
102
- if not user_api_key or not user_api_key.strip():
103
- print(f"⚠️ User က Gemini API Key မထည့်ထားပါ။ Google Translate Backup စနစ်ဖြင့် ဘာသာပြန်နေပါသည်။ (Source Lang: {source_lang})")
104
- for seg in segments:
105
- seg['mm_text'] = google_backup_translate(seg['text'], source_lang=source_lang)
106
- return segments
107
-
108
- payload_dict = {str(idx): seg['text'] for idx, seg in enumerate(segments)}
109
- large_prompt_text = json.dumps(payload_dict, ensure_ascii=False, indent=2)
110
-
111
- prompt = f"""
112
- You are an expert movie recap translator. Translate the following movie subtitle lines (which are originally in '{source_lang}' language) into thrilling, natural, and engaging Burmese movie recap style.
113
-
114
- CRITICAL: You MUST respond in valid JSON format only, keeping the exact same keys (0, 1, 2, etc.) as the input. The values should be the translated Burmese text.
115
- Do NOT include any markdown formatting like ```json or ``` in your response. Respond with pure JSON raw string only.
116
-
117
- Input Data:
118
- {large_prompt_text}
119
- """
120
-
121
- translated_map = {}
122
- try:
123
- client = genai.Client(api_key=user_api_key.strip())
124
- response = client.models.generate_content(
125
- model=MODEL_NAME,
126
- contents=prompt,
127
- config={
128
- "system_instruction": SYSTEM_INSTRUCTION,
129
- "temperature": 0.3,
130
- }
131
- )
132
- response_text = response.text.strip()
133
-
134
- if response_text.startswith("```"):
135
- response_text = response_text.split("\n", 1)[1].rsplit("\n", 1)[0].strip()
136
- if response_text.startswith("json"):
137
- response_text = response_text.split("\n", 1)[1].strip()
138
-
139
- translated_map = json.loads(response_text)
140
- except Exception as e:
141
- print(f"⚠️ User Gemini API Error သို့မဟုတ် Format Error: {e} -> Google Translate သို့ ပြောင်းလဲနေသည်။")
142
-
143
- for idx, seg in enumerate(segments):
144
- key_str = str(idx)
145
- if key_str in translated_map and translated_map[key_str]:
146
- seg['mm_text'] = translated_map[key_str]
147
- else:
148
- seg['mm_text'] = google_backup_translate(seg['text'], source_lang=source_lang)
149
-
150
- return segments
151
-
152
- # =====================================================================
153
- # 🎬 TEXT WRAPPING & RENDER SYSTEMS
154
- # =====================================================================
155
- def segment_myanmar_syllables(text):
156
- return re.findall(r'[a-zA-Z0-9\s\-\.,!\?]+|[\u1000-\u102a\u103f\u1040-\u1049]+[\u102b-\u103e\u1060-\u109f]*|[^\s]', text)
157
-
158
- def wrap_text_myanmar_smart(text, font, max_width, draw):
159
- cleaned_text = text.replace(" ြ", "ြ").replace("ြ ", "ြ").strip()
160
- tokens = segment_myanmar_syllables(cleaned_text)
161
- lines, current_line = [], ""
162
- for token in tokens:
163
- test_line = current_line + token
164
- bbox = draw.textbbox((0, 0), test_line, font=font)
165
- if (bbox[2] - bbox[0]) <= max_width:
166
- current_line = test_line
167
- else:
168
- if current_line: lines.append(current_line.strip())
169
- current_line = token
170
- if current_line: lines.append(current_line.strip())
171
- return lines
172
-
173
- def hex_to_rgb(hex_str):
174
- if not hex_str: return (255, 255, 0)
175
- hex_str = hex_str.lstrip('#')
176
- return tuple(int(hex_str[i:i+2], 16) for i in (0, 2, 4))
177
-
178
- def draw_line_perfect_rendering(draw, position, text, font_primary, fill_color, stroke_w, stroke_c):
179
- x, y = position
180
- clean_text = text.replace(" ြ", "ြ").replace("ြ ", "ြ")
181
- draw.text((x, y), clean_text, font=font_primary, fill=fill_color, stroke_width=stroke_w, stroke_fill=stroke_c)
182
-
183
- def generate_voice_sync(text, voice_id, filename, desired_speed, target_duration_sec=None):
184
- rate_percentage = int((desired_speed - 1.0) * 100)
185
- rate_str = f"{'+' if rate_percentage >= 0 else ''}{rate_percentage}%"
186
-
187
- if target_duration_sec and target_duration_sec > 0:
188
- char_count = len(text)
189
- cps = char_count / target_duration_sec
190
- if cps > 15: rate_str = f"+{rate_percentage + 30}%"
191
- elif cps > 11: rate_str = f"+{rate_percentage + 15}%"
192
- elif cps > 7: rate_str = f"+{rate_percentage + 5}%"
193
-
194
- async def _async_gen():
195
- communicate = edge_tts.Communicate(text, voice_id, rate=rate_str)
196
- await communicate.save(filename)
197
-
198
- try: loop = asyncio.get_event_loop()
199
- except RuntimeError:
200
- loop = asyncio.new_event_loop()
201
- asyncio.set_event_loop(loop)
202
-
203
- if loop.is_running():
204
- import threading
205
- t = threading.Thread(target=lambda: asyncio.run(_async_gen()))
206
- t.start()
207
- t.join()
208
- else:
209
- loop.run_until_complete(_async_gen())
210
-
211
- # =====================================================================
212
- # 🎬 HIGH-SPEED PRODUCTION AUTOMATION ENGINE
213
- # =====================================================================
214
- def process_magic_recap_video(
215
- video_path, user_api_key, ratio_select, background_fill, enable_zoom, zoom_level,
216
- logo_file, mirror_flip, filter_color, voice_gender, tone_style,
217
- text_color, stroke_color, blur_y_percent, blur_strength, sub_pos_percent, desired_speed,
218
- session_id, # 👈 Browser Session State
219
- request: gr.Request,
220
- progress=gr.Progress(track_tqdm=True)
221
- ):
222
- is_valid, msg = check_app_expiry()
223
- if not is_valid: raise gr.Error(msg)
224
- if not video_path: return None
225
-
226
- # 🛑 LOGIN ACCOUNT & SESSION ID ယူခြင်း
227
- login_username = request.username if (request and hasattr(request, 'username')) else "user1"
228
-
229
- if login_username == "admin":
230
- user_identifier = "admin"
231
- else:
232
- # Browser Session ID ဖြင့် လူတစ်ဦးစီကို သီးခြား ခွဲခြားမည်
233
- user_identifier = f"session_{session_id}"
234
-
235
- current_timestamp = time.time()
236
- print(f"👤 အသုံးပြုသူ Account: {login_username} | Identifier: {user_identifier}")
237
-
238
- # Admin မဟုတ်ပါက Session/Browser အလိုက် ၁ ရက် (၂) ပုဒ် Limit စစ်ဆေးမည်
239
- if user_identifier != "admin":
240
- if user_identifier in USER_LIMIT_TRACKER:
241
- user_data = USER_LIMIT_TRACKER[user_identifier]
242
- first_time = user_data["first_time"]
243
- count = user_data["count"]
244
- elapsed_time = current_timestamp - first_time
245
-
246
- if elapsed_time < 86400: # ၂၄ နာရီ အတွင်း
247
- if count >= 2: # ၂ ပုဒ် ပြည့်ပါက တားဆီးမည်
248
- remaining_seconds = 86400 - elapsed_time
249
- rem_hours = int(remaining_seconds // 3600)
250
- rem_mins = int((remaining_seconds % 3600) // 60)
251
- raise gr.Error(f"❌ ခွင့်ပြုချက်ကျော်လွန်နေပါသည်။ သင့် Browser မှ တစ်ရက်လျှင် ဗီဒီယို (၂) ပုဒ်သာ ထုတ်ယူခွင့်ရှိသည်။ ပြန်လည်စမ်းသပ်ရန် {rem_hours} နာရီ {rem_mins} မိနစ် လိုအပ်ပါသေးသည်။")
252
- else:
253
- USER_LIMIT_TRACKER[user_identifier] = {"count": 0, "first_time": current_timestamp}
254
- else:
255
- USER_LIMIT_TRACKER[user_identifier] = {"count": 0, "first_time": current_timestamp}
256
-
257
- temp_dir = "temp_space_workspace"
258
- if os.path.exists(temp_dir): shutil.rmtree(temp_dir)
259
- os.makedirs(temp_dir, exist_ok=True)
260
-
261
- try:
262
- progress(0.10, desc="🎙️ Faster-Whisper ဖြင့် စာသားဖတ်နေပါသည်...")
263
- segments_raw, info = model.transcribe(video_path, beam_size=1)
264
- raw_segments = [{"start": seg.start, "end": seg.end, "text": seg.text} for seg in segments_raw]
265
-
266
- cap = cv2.VideoCapture(video_path)
267
- fps = cap.get(cv2.CAP_PROP_FPS) or 30.0
268
- orig_w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
269
- orig_h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
270
- video_duration = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) / fps
271
-
272
- if not raw_segments:
273
- raw_segments = [{'start': 0.0, 'end': min(6.0, video_duration), 'text': "Welcome to this movie recap."}]
274
-
275
- segments = []
276
- for seg in raw_segments:
277
- s_start = seg['start']
278
- s_end = seg['end']
279
- s_text = seg['text'].strip()
280
- if not s_text: continue
281
-
282
- dur = s_end - s_start
283
- if dur > MAX_SUBTITLE_DURATION_SECONDS and MAX_SUBTITLE_DURATION_SECONDS > 0:
284
- words = s_text.split()
285
- chunks_count = int(np.ceil(dur / MAX_SUBTITLE_DURATION_SECONDS))
286
- words_per_chunk = int(np.ceil(len(words) / chunks_count))
287
- for i in range(chunks_count):
288
- w_sub = words[i*words_per_chunk : (i+1)*words_per_chunk]
289
- if not w_sub: continue
290
- segments.append({'start': s_start + (i * (dur / chunks_count)), 'end': min(s_end, s_start + ((i+1) * (dur / chunks_count))), 'text': " ".join(w_sub)})
291
- else:
292
- segments.append({'start': s_start, 'end': s_end, 'text': s_text})
293
-
294
- detected_lang = info.language
295
- if user_api_key and user_api_key.strip():
296
- progress(0.30, desc=f"⚡ ထည့်သွင်းထားသော Gemini API ({detected_lang}) စနစ်ဖြင့် ဘာသာပြန်နေပါသည်...")
297
- else:
298
- progress(0.30, desc=f"🌐 Google Translate Backup ({detected_lang}) စနစ်ဖြင့် ဘာသာပြန်နေပါသည်...")
299
-
300
- segments = translate_segments_batch(segments, user_api_key, source_lang=detected_lang)
301
-
302
- if ratio_select == "9:16 (Tiktok/Reels)": target_w, target_h = 720, 1280
303
- else: target_w, target_h = 1280, 720
304
-
305
- logo_img = None
306
- if logo_file:
307
- try:
308
- logo_cv = cv2.imread(logo_file.name, cv2.IMREAD_UNCHANGED)
309
- if logo_cv is not None:
310
- l_w = int(target_w * 0.16)
311
- logo_img = cv2.resize(logo_cv, (l_w, int(l_w * (logo_cv.shape[0] / logo_cv.shape[1]))))
312
- except: pass
313
-
314
- progress(0.50, desc="🎙️ AI အသံများ စတင်ဖန်တီးနေပါသည်...")
315
- audio_segments = []
316
- python_srt_segments = []
317
- voice_id = "my-MM-NilarNeural" if "မိန်းကလေး" in voice_gender else "my-MM-ThihaNeural"
318
- v_segments_time_map = []
319
- total_adjusted_duration = 0.0
320
-
321
- for idx, seg in enumerate(segments):
322
- mm_text = seg.get('mm_text', seg['text'])
323
- mm_text = mm_text.replace(" ြ", "ြ").replace("ြ ", "ြ").strip()
324
-
325
- orig_start, orig_end = float(seg.get('start', 0.0)), float(seg.get('end', 0.0))
326
- orig_dur = orig_end - orig_start if (orig_end - orig_start) > 0 else 2.0
327
-
328
- raw_seg_filename = os.path.join(temp_dir, f"raw_{idx}.mp3")
329
- fixed_seg_filename = os.path.join(temp_dir, f"fixed_{idx}.mp3")
330
-
331
- generate_voice_sync(mm_text, voice_id, raw_seg_filename, 1.15, orig_dur)
332
-
333
- if os.path.exists(raw_seg_filename) and os.path.getsize(raw_seg_filename) > 0:
334
- subprocess.run([
335
- 'ffmpeg', '-y', '-i', raw_seg_filename,
336
- '-filter:a', f"atempo={desired_speed}",
337
- fixed_seg_filename
338
- ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
339
-
340
- if os.path.exists(fixed_seg_filename) and os.path.getsize(fixed_seg_filename) > 0:
341
- probe_res = subprocess.run(['ffprobe', '-v', 'error', '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:nokey=1', fixed_seg_filename], stdout=subprocess.PIPE, text=True)
342
- try: audio_dur = float(probe_res.stdout.strip())
343
- except: audio_dur = orig_dur / desired_speed
344
-
345
- python_srt_segments.append({'start': total_adjusted_duration, 'end': total_adjusted_duration + audio_dur, 'text': mm_text})
346
- audio_segments.append(fixed_seg_filename)
347
- v_segments_time_map.append({'orig_start': orig_start, 'orig_end': orig_end, 'new_start': total_adjusted_duration, 'new_end': total_adjusted_duration + audio_dur, 'pts_ratio': audio_dur / orig_dur})
348
- total_adjusted_duration += audio_dur
349
-
350
- progress(0.70, desc="⚡ Render ဗီဒီယိုနှင့် စာတန်းထိုးများ ပေါင်းစပ်နေပါသည်...")
351
- output_video_path = os.path.abspath("magic_recap_output.mp4")
352
- if os.path.exists(output_video_path): os.remove(output_video_path)
353
-
354
- final_burn_temp = os.path.join(temp_dir, "final_burn_temp.mp4")
355
- video_writer = cv2.VideoWriter(final_burn_temp, cv2.VideoWriter_fourcc(*'mp4v'), fps, (target_w, target_h))
356
-
357
- font_size = int(target_h * 0.038)
358
- font_path = "Myanmar font.ttf"
359
- font_primary = ImageFont.truetype(font_path, font_size) if os.path.exists(font_path) else ImageFont.load_default()
360
-
361
- t_color, s_color = hex_to_rgb(text_color), hex_to_rgb(stroke_color)
362
- b_h = int(target_h * 0.12)
363
- b_y = max(0, min(int(target_h * (blur_y_percent / 100)) - (b_h // 2), target_h - b_h))
364
- m_w, s_w = int(target_w * 0.90), max(2, int(font_size * 0.12))
365
- k_size = int(blur_strength) | 1
366
-
367
- total_output_frames = int(total_adjusted_duration * fps)
368
-
369
- for f_out_idx in range(total_output_frames):
370
- c_sec = f_out_idx / fps
371
- target_orig_sec = 0.0
372
- for mapping in v_segments_time_map:
373
- if mapping['new_start'] <= c_sec <= mapping['new_end']:
374
- target_orig_sec = mapping['orig_start'] + ((c_sec - mapping['new_start']) / mapping['pts_ratio'])
375
- break
376
- else:
377
- if v_segments_time_map: target_orig_sec = v_segments_time_map[-1]['orig_end']
378
-
379
- target_frame_idx = int(target_orig_sec * fps)
380
-
381
- cap.set(cv2.CAP_PROP_POS_FRAMES, target_frame_idx)
382
- ret, orig_frame = cap.read()
383
- if not ret or orig_frame is None:
384
- orig_frame = np.zeros((orig_h, orig_w, 3), dtype=np.uint8)
385
-
386
- if background_fill == "Blur Background (အနောက်ခံ ဝါးမည်)":
387
- small_bg = cv2.resize(orig_frame, (target_w // 4, target_h // 4), interpolation=cv2.INTER_LINEAR)
388
- blurred_small_bg = cv2.blur(small_bg, (11, 11))
389
- bg_layer = cv2.resize(blurred_small_bg, (target_w, target_h), interpolation=cv2.INTER_LINEAR)
390
- else:
391
- bg_layer = np.zeros((target_h, target_w, 3), dtype=np.uint8)
392
-
393
- if enable_zoom and zoom_level > 1.0:
394
- fg_cropped = orig_frame[int((orig_h - orig_h/zoom_level)//2):int((orig_h + orig_h/zoom_level)//2), int((orig_w - orig_w/zoom_level)//2):int((orig_w + orig_w/zoom_level)//2)]
395
- else:
396
- fg_cropped = orig_frame
397
-
398
- fg_w = target_w
399
- fg_h = int(fg_w / (fg_cropped.shape[1] / fg_cropped.shape[0]))
400
- if fg_h > target_h:
401
- fg_h = target_h
402
- fg_w = int(fg_h * (fg_cropped.shape[1] / fg_cropped.shape[0]))
403
-
404
- fg_resized = cv2.flip(cv2.resize(fg_cropped, (fg_w, fg_h)), 1) if mirror_flip else cv2.resize(fg_cropped, (fg_w, fg_h))
405
-
406
- if filter_color == "Chrome Cool": fg_resized = cv2.convertScaleAbs(fg_resized, alpha=1.0, beta=15)
407
- elif filter_color == "Warm Cinema": fg_resized = cv2.convertScaleAbs(fg_resized, alpha=1.05, beta=5)
408
- else: fg_resized = cv2.convertScaleAbs(fg_resized, alpha=0.99, beta=2)
409
-
410
- bg_layer[(target_h - fg_h)//2:(target_h - fg_h)//2+fg_h, (target_w - fg_w)//2:(target_w - fg_w)//2+fg_w] = fg_resized
411
- frame = bg_layer
412
-
413
- if logo_img is not None:
414
- ly, lx = 25, target_w - logo_img.shape[1] - 25
415
- if logo_img.shape[2] == 4:
416
- alpha_l = logo_img[:, :, 3] / 255.0
417
- for c in range(3): frame[ly:ly+logo_img.shape[0], lx:lx+logo_img.shape[1], c] = alpha_l * logo_img[:, :, c] + (1.0 - alpha_l) * frame[ly:ly+logo_img.shape[0], lx:lx+logo_img.shape[1], c]
418
- else: frame[ly:ly+logo_img.shape[0], lx:lx+logo_img.shape[1]] = logo_img[:, :, :3]
419
-
420
- if b_h > 0 and (b_y + b_h) <= target_h:
421
- roi = frame[b_y:b_y+b_h, 0:target_w]
422
- if roi.shape[0] > 0 and roi.shape[1] > 0:
423
- roi_small = cv2.resize(roi, (target_w // 4, b_h // 4), interpolation=cv2.INTER_LINEAR)
424
- roi_blur = cv2.GaussianBlur(roi_small, (k_size // 4 | 1, k_size // 4 | 1), 0)
425
- frame[b_y:b_y+b_h, 0:target_w] = cv2.resize(roi_blur, (target_w, b_h), interpolation=cv2.INTER_LINEAR)
426
-
427
- text_str = ""
428
- for s in python_srt_segments:
429
- if s['start'] <= c_sec <= s['end']:
430
- text_str = s['text']
431
- break
432
-
433
- if text_str and isinstance(font_primary, ImageFont.FreeTypeFont):
434
- pil_img = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
435
- draw = ImageDraw.Draw(pil_img)
436
- sub_lines = wrap_text_myanmar_smart(text_str, font_primary, m_w, draw)
437
- total_text_height = sum([draw.textbbox((0, 0), l, font=font_primary)[3] - draw.textbbox((0, 0), l, font=font_primary)[1] for l in sub_lines])
438
- curr_y = int(target_h - total_text_height - (target_h * (sub_pos_percent / 100)))
439
- for line in sub_lines:
440
- clean_line = line.replace(" ြ", "ြ").replace("ြ ", "ြ")
441
- bbox = draw.textbbox((0, 0), clean_line, font=font_primary)
442
- draw_line_perfect_rendering(draw, ((target_w - (bbox[2] - bbox[0])) // 2, curr_y), clean_line, font_primary, t_color, s_w, s_color)
443
- curr_y += (bbox[3] - bbox[1]) + 10
444
- frame = cv2.cvtColor(np.array(pil_img), cv2.COLOR_RGB2BGR)
445
- video_writer.write(frame)
446
-
447
- cap.release()
448
- video_writer.release()
449
-
450
- merged_audio_path = os.path.join(temp_dir, "final_speech_track.mp3")
451
- if audio_segments:
452
- inputs_cmd = []
453
- for idx, audio_file in enumerate(audio_segments): inputs_cmd.extend(['-i', audio_file])
454
- subprocess.run(['ffmpeg', '-y'] + inputs_cmd + ['-filter_complex', f"concat=n={len(audio_segments)}:v=0:a=1[outa]", '-map', '[outa]', '-c:a', 'libmp3lame', '-b:a', '192k', merged_audio_path], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
455
- has_audio = os.path.exists(merged_audio_path) and os.path.getsize(merged_audio_path) > 0
456
- else: has_audio = False
457
-
458
- progress(0.90, desc="⚡ ရုပ်သံနှင့် အသံလှိုင်းများကို အပြီးသတ် ပေါင်းစပ်နေပါသည်...")
459
- if has_audio:
460
- subprocess.run(['ffmpeg', '-y', '-i', final_burn_temp, '-i', merged_audio_path, '-c:v', 'libx264', '-preset', 'ultrafast', '-threads', '0', '-pix_fmt', 'yuv420p', '-c:a', 'aac', '-b:a', '192k', '-map', '0:v:0', '-map', '1:a:0', '-shortest', output_video_path], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
461
- else:
462
- subprocess.run(['ffmpeg', '-y', '-i', final_burn_temp, '-c:v', 'libx264', '-preset', 'ultrafast', '-threads', '0', '-pix_fmt', 'yuv420p', output_video_path], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
463
-
464
- if os.path.exists(temp_dir): shutil.rmtree(temp_dir)
465
-
466
- # 📈 ဗီဒီယို အောင်မြင်စွာ ထုတ်ယူပြီးမှသာ ထို Session ၏ Count ကို ၁ တိုးမည်
467
- if user_identifier != "admin":
468
- USER_LIMIT_TRACKER[user_identifier]["count"] += 1
469
- print(f"✅ [{user_identifier}] ဗီဒီယိုထုတ်ယူမှု အောင်မြင်ပါသည်။ ယနေ့ ထုတ်ယူပြီးစီးမှု: {USER_LIMIT_TRACKER[user_identifier]['count']} ကြိမ်")
470
-
471
- return output_video_path
472
-
473
- except Exception as e:
474
- if os.path.exists(temp_dir): shutil.rmtree(temp_dir)
475
- raise gr.Error(f"❌ အမှားအယွင်း တစ်ခု ဖြစ်ပွားခဲ့သည်- {str(e)}")
476
-
477
- # =====================================================================
478
- # 🎨 GRADIO INTERFACE
479
- # =====================================================================
480
- def create_main_app_interface():
481
- is_valid, msg = check_app_expiry()
482
-
483
- with gr.Blocks() as main_app:
484
- # 🔑 အသုံးပြုသူတိုင်းအတွက် သီးသန့် Session ID ထုတ်ပေးခြင်း
485
- session_id_state = gr.State(lambda: str(uuid.uuid4()))
486
-
487
- gr.Markdown("<h1 style='text-align: center; color: #5B50F3;'>✨ Video Auto Recap (Multi-Account) ✨</h1>")
488
- if not is_valid:
489
- gr.Markdown(f"### {msg}")
490
- return main_app
491
-
492
- gr.Markdown("<div style='background-color: #333; padding: 10px; border-radius: 8px; text-align: center; color: #fff;'>📢 <b>Free App Rules:</b> တစ်ရက်လျှင် Video (၂) ပုဒ် အခမဲ့ ထုတ်ယူခွင့် ရှိပါသည်</div>")
493
-
494
- with gr.Row():
495
- with gr.Column(scale=2):
496
- video_input = gr.Video(label="🎥 ဗီဒီယို ထည့်ရန်", sources=["upload"])
497
- preview_image = gr.Image(label="🖼️ Interactive Blur Preview", interactive=False)
498
-
499
- with gr.Column(scale=1):
500
- user_api_key = gr.Textbox(label="🔑 သင်၏ Gemini API Key ထည့်ရန် (မထည့်ပါက Google Translate ဖြင့် လုပ်ဆောင်မည်)", placeholder="AIZAcy... (Optional)", type="password")
501
- ratio_select = gr.Dropdown(choices=["9:16 (Tiktok/Reels)", "16:9 (Landscape)"], value="9:16 (Tiktok/Reels)", label="ဗီဒီယိုအမျိုးအစား")
502
- background_fill = gr.Radio(choices=["Blur Background (အနောက်ခံ ဝါးမည်)", "Black Background (အမည်းရောင်ထားမည်)"], value="Blur Background (အနောက်ခံ ဝါးမည်)", label="နောက်ခံ ဖြည့်စွက်မှု")
503
-
504
- with gr.Column(variant="panel"):
505
- gr.Markdown("### 🗣️ အသံနှင့် စာတန်းထိုး ဆက်တင်များ")
506
- voice_select = gr.Radio(choices=["🧕 မိန်းကလေး (Female)", "👨 ယောကျာ်လေး (Male)"], value="🧕 မိန်းကလေး (Female)", label="AI အသံ အမျိုးအစား")
507
- tone_style = gr.Dropdown(choices=["Thriller", "Comedy", "Dramatic", "Action/Epic"], value="Thriller", label="🎬 Narrative Tone")
508
- text_color_input = gr.ColorPicker(label="စာလုံးအရောင်", value="#FFFF00")
509
- stroke_color_input = gr.ColorPicker(label="အနားသတ်အရောင်", value="#000000")
510
- sub_pos_percent = gr.Slider(minimum=0, maximum=100, value=15, step=1, label="မြန်မာစာတန်း တည်နေရာ %")
511
- blur_y_percent = gr.Slider(minimum=50, maximum=100, value=75, step=1, label="📍 မူရင်းစာတန်းဖျောက်မည့်နေရာ %")
512
- blur_strength = gr.Slider(minimum=5, maximum=151, value=51, step=2, label="🌫️ မူရင်းစာတန်း ဝါးမည့်ပမာဏ")
513
- desired_speed = gr.Slider(minimum=1.0, maximum=1.6, value=1.35, step=0.05, label="🎙️🎬 အသံနှင့် ဗီဒီယို အရှိန်မြှင့်နှုန်း")
514
-
515
- with gr.Accordion("⚙️ အဆင့်မြင့် ဆက်တင်များ", open=False):
516
- enable_zoom = gr.Checkbox(label="Zoom & Crop သုံးရန်", value=False)
517
- zoom_level = gr.Slider(minimum=1.0, maximum=3.0, value=1.0, step=0.1, label="Zoom Level")
518
- logo_file = gr.File(label="လိုဂို ထည့်ရန် (Optional)")
519
- mirror_flip = gr.Checkbox(label="ဘယ်ညာ ပြောင်းရန် (Mandatory Auto-Active)", value=True)
520
- filter_color = gr.Dropdown(choices=["None (အလိုအလျောက်ကုဒ်ပြောင်းမည်)", "Chrome Cool", "Warm Cinema"], value="None (အလိုအလျောက်ကုဒ်ပြောင်းမည်)", label="ဗီဒီယို Filter")
521
-
522
- submit_btn = gr.Button("🚀 Generate Video", variant="primary")
523
-
524
- with gr.Column(variant="panel"):
525
- output_video = gr.Video(label="✅ ပြီးပြည့်စုံသော ဗီဒီယို")
526
-
527
- video_input.change(fn=update_preview_image, inputs=[video_input, blur_y_percent, blur_strength], outputs=preview_image)
528
- blur_y_percent.change(fn=update_preview_image, inputs=[video_input, blur_y_percent, blur_strength], outputs=preview_image)
529
- blur_strength.change(fn=update_preview_image, inputs=[video_input, blur_y_percent, blur_strength], outputs=preview_image)
530
-
531
- submit_btn.click(
532
- fn=process_magic_recap_video,
533
- inputs=[
534
- video_input, user_api_key, ratio_select, background_fill, enable_zoom, zoom_level,
535
- logo_file, mirror_flip, filter_color, voice_select, tone_style, text_color_input,
536
- stroke_color_input, blur_y_percent, blur_strength, sub_pos_percent, desired_speed,
537
- session_id_state # 👈 session_id ကို Function ထဲ ပို့ပေးခြင်း
538
- ],
539
- outputs=[output_video]
540
- )
541
-
542
- return main_app
543
-
544
- def verify_member(username, password):
545
- if username in ACCOUNTS and ACCOUNTS[username] == password:
546
- return True
547
- return False
548
-
549
- demo_app = create_main_app_interface()
550
-
551
- if __name__ == "__main__":
552
- demo_app.launch(auth=verify_member, theme=gr.themes.Default())