Autorecap commited on
Commit
de06e8a
·
verified ·
1 Parent(s): d93b89b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +682 -614
app.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import json
2
  import os
3
  import re
@@ -6,35 +7,40 @@ import subprocess
6
  import time
7
  import unicodedata
8
  import uuid
9
- from datetime import datetime, timedelta
 
 
 
 
 
 
 
 
 
10
 
 
 
 
 
 
 
 
 
11
  DB_FILE = "user_db.json"
12
- BASE_WORK_DIR = "temp_space_workspace"
13
- FONT_FILE = "Myanmarfont.ttf"
14
- MODEL_NAME = "gemini-3.1-flash-lite"
15
- TIKTOK_W, TIKTOK_H = 720, 1280
16
- LANDSCAPE_W, LANDSCAPE_H = 1280, 720
17
- TTS_WORKERS = 4
18
- TTS_MAX_SPEED = 1.85
19
- TTS_GAP_SECONDS = 0.04
20
 
21
- SYSTEM_INSTRUCTION = """You are a professional Burmese movie translator and narrator.
22
- Translate every input subtitle line into natural, clear Burmese.
23
- Preserve names, numbers, events and meaning.
24
- Do not omit, merge or invent lines.
25
- Return ONLY a JSON array of Burmese strings in the same order."""
26
 
27
  def load_user_db():
28
  if not os.path.exists(DB_FILE):
29
  now = datetime.now()
30
- db = {
 
31
  "User1": {
32
  "password": "123456",
33
  "role": "user",
34
  "credits": 24,
35
  "last_reset": now.strftime("%Y-%m-%d"),
36
  "created_at": now.strftime("%Y-%m-%d %H:%M:%S"),
37
- "expire_at": (now + timedelta(days=60)).strftime("%Y-%m-%d %H:%M:%S"),
38
  },
39
  "admin": {
40
  "password": "241212",
@@ -46,80 +52,84 @@ def load_user_db():
46
  },
47
  }
48
  with open(DB_FILE, "w", encoding="utf-8") as f:
49
- json.dump(db, f, ensure_ascii=False, indent=4)
50
- return db
51
  try:
52
  with open(DB_FILE, "r", encoding="utf-8") as f:
53
  return json.load(f)
54
  except Exception:
55
  return {}
56
 
 
57
  def save_user_db(db):
58
  with open(DB_FILE, "w", encoding="utf-8") as f:
59
- json.dump(db, f, ensure_ascii=False, indent=4)
 
60
 
61
  def check_and_update_user_daily_credits(username):
62
  db = load_user_db()
63
  if username not in db:
64
  return False, "❌ User မတွေ့ပါ။"
 
65
  user = db[username]
66
  if user.get("role") == "admin":
67
  return True, "Admin access granted."
68
- try:
69
- expire_at = datetime.strptime(user.get("expire_at"), "%Y-%m-%d %H:%M:%S")
70
- except Exception:
71
- return False, "❌ Account expiration data မမှန်ပါ။"
72
  now = datetime.now()
 
73
  if now > expire_at:
74
- return False, f"❌ Account သက်တမ်းကုန်ဆုံးပါပြီ ({user.get('expire_at')})။"
75
- today = now.strftime("%Y-%m-%d")
76
- if user.get("last_reset") != today:
 
 
 
 
77
  user["credits"] = 24
78
- user["last_reset"] = today
79
  db[username] = user
80
  save_user_db(db)
 
81
  return True, "OK"
82
 
83
- def calculate_credits(seconds):
84
- return int((float(seconds) + 9.99) // 10) * 2
85
 
86
  def deduct_user_credits(username, video_duration_seconds):
87
  db = load_user_db()
88
  if username not in db:
89
- return False, "❌ User မတွေ့ပါ။", 0
 
90
  user = db[username]
91
  if user.get("role") == "admin":
92
- return True, "Admin (Unlimited Credits)", 0
93
- required = calculate_credits(video_duration_seconds)
94
- if user.get("credits", 0) < required:
95
- return False, f"❌ Credit မလုံလောက်ပါ။ လိုအပ်သည်: {required} | လက်ကျန်: {user.get('credits', 0)}", 0
96
- user["credits"] -= required
97
- db[username] = user
98
- save_user_db(db)
99
- return True, f"✅ {required} Credits ဖြတ်ပြီးပါပြီ။ လက်ကျန်: {user['credits']}", required
100
 
101
- def refund_user_credits(username, credits):
102
- if credits <= 0:
103
- return
104
- db = load_user_db()
105
- if username in db and db[username].get("role") != "admin":
106
- db[username]["credits"] = int(db[username].get("credits", 0)) + int(credits)
107
- save_user_db(db)
108
 
109
- import av
 
 
 
 
110
 
111
- _original_av_open = av.open
 
 
 
 
 
 
112
 
113
- def _patched_av_open(*args, **kwargs):
114
- kwargs.pop("metadata_errors", None)
115
- return _original_av_open(*args, **kwargs)
116
 
117
- av.open = _patched_av_open
118
-
119
- import edge_tts
120
- import gradio as gr
121
- from faster_whisper import WhisperModel
122
- from google import genai
 
 
 
 
123
 
124
  whisper_model = WhisperModel(
125
  "small",
@@ -128,215 +138,184 @@ whisper_model = WhisperModel(
128
  cpu_threads=max(1, os.cpu_count() or 2),
129
  )
130
 
131
- ZERO_WIDTH_CHARS = {
132
- "\u200b", "\u200c", "\u200d", "\u2060", "\ufeff", "\u00ad"
133
- }
134
 
135
  def clean_burmese_unicode(text):
136
  if text is None:
137
  return ""
138
  text = str(text)
139
- for c in ZERO_WIDTH_CHARS:
140
- text = text.replace(c, "")
141
  text = unicodedata.normalize("NFC", text)
142
- text = "".join(
143
- c for c in text
144
- if not unicodedata.category(c).startswith("C") or c in "\n\r\t"
145
- )
 
 
146
  text = re.sub(r"[ \t]+", " ", text)
147
  return re.sub(r"\n{3,}", "\n\n", text).strip()
148
 
149
- def clean_translation(text):
150
- if not text:
151
- return ""
152
- text = re.sub(r"^```(?:json)?\s*", "", str(text).strip(), flags=re.I)
153
- text = re.sub(r"\s*```$", "", text)
154
- return clean_burmese_unicode(text)
155
 
156
  def normalize_video_path(video_input):
157
  if not video_input:
158
  return None
159
  if isinstance(video_input, str):
160
  return video_input
161
- return getattr(video_input, "path", None) or getattr(video_input, "name", None)
 
 
 
162
 
163
  def ffprobe_duration(path):
164
  try:
165
- r = subprocess.run(
166
- ["ffprobe", "-v", "error", "-show_entries", "format=duration",
167
- "-of", "default=noprint_wrappers=1:nokey=1", path],
168
- stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True
 
 
 
 
 
 
 
 
 
 
169
  )
170
- return float(r.stdout.strip())
171
  except Exception:
172
  return 0.0
173
 
 
174
  def ass_timestamp(seconds):
175
  seconds = max(0.0, float(seconds))
176
  h, r = divmod(seconds, 3600)
177
  m, s = divmod(r, 60)
178
- cs = min(99, int(round((s - int(s)) * 100)))
179
- if cs == 100:
180
- s = int(s) + 1
181
- cs = 0
182
  return f"{int(h)}:{int(m):02d}:{int(s):02d}.{cs:02d}"
183
 
184
- def srt_timestamp(seconds):
185
- seconds = max(0.0, float(seconds))
186
- h = int(seconds // 3600)
187
- m = int((seconds % 3600) // 60)
188
- s = int(seconds % 60)
189
- ms = int(round((seconds - int(seconds)) * 1000))
190
- if ms >= 1000:
191
- s += 1
192
- ms = 0
193
- return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}"
194
 
195
  def escape_ass_text(text):
 
196
  return (
197
- clean_burmese_unicode(text)
198
- .replace("\\", r"\\")
199
  .replace("{", r"\{")
200
  .replace("}", r"\}")
201
  .replace("\n", r"\N")
202
  )
203
 
204
- def source_code(language):
205
- return {
206
- "English": "en",
207
- "Chinese": "zh-CN",
208
- "Japanese": "ja",
209
- "Korean": "ko",
210
- "Thai": "th",
211
- "Hindi": "hi",
212
- "Spanish": "es",
213
- "French": "fr",
214
- }.get(language, language if language and language != "Auto Detect" else "en")
215
-
216
- def google_backup_translate(text, source_lang="en"):
217
- import urllib.request
218
- from urllib.parse import quote
219
- if not text or not text.strip():
220
- return ""
221
- try:
222
- url = f"https://translate.googleapis.com/translate_a/single?client=gtx&sl={source_lang}&tl=my&dt=t&q={quote(text)}"
223
- req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
224
- data = json.loads(urllib.request.urlopen(req, timeout=10).read().decode("utf-8"))
225
- if data and data[0]:
226
- return clean_burmese_unicode("".join(x[0] for x in data[0] if x and x[0]))
227
- except Exception:
228
- pass
229
- return clean_burmese_unicode(text)
230
-
231
- def get_gemini_key(user_api_key):
232
- return (user_api_key or "").strip() or os.getenv("GEMINI_API_KEY", "").strip()
233
-
234
- def gemini_translate_batch(texts, api_key, source_lang, tone_style):
235
- if not api_key:
236
- raise RuntimeError("Gemini API Key မထည့်ထားပါ။")
237
- client = genai.Client(api_key=api_key)
238
- numbered = "\n".join(f"{i+1}. {x}" for i, x in enumerate(texts))
239
- prompt = f"""{SYSTEM_INSTRUCTION}
240
- Source language: {source_lang}
241
- Narration style: {tone_style}
242
-
243
- INPUT:
244
- {numbered}
245
- """
246
- response = client.models.generate_content(
247
- model=MODEL_NAME,
248
- contents=prompt
249
- )
250
- raw = clean_translation(getattr(response, "text", ""))
251
- try:
252
- data = json.loads(raw)
253
- if isinstance(data, list):
254
- return [clean_burmese_unicode(str(x)) for x in data]
255
- except Exception:
256
- pass
257
- m = re.search(r"\[[\s\S]*\]", raw)
258
- if m:
259
- try:
260
- data = json.loads(m.group(0))
261
- if isinstance(data, list):
262
- return [clean_burmese_unicode(str(x)) for x in data]
263
- except Exception:
264
- pass
265
- raise RuntimeError("Gemini response format မမှန်ပါ။")
266
-
267
- def translate_segments_batch(
268
- segments, user_api_key, source_lang="en",
269
- translation_method="Google Translate (Free)", tone_style="Thriller"
270
  ):
271
- lang = source_code(source_lang)
272
- if translation_method != "Gemini AI":
273
- for seg in segments:
274
- seg["mm_text"] = google_backup_translate(seg["text"], lang)
275
- return segments, "Google Translate"
276
- key = get_gemini_key(user_api_key)
277
- if not key:
278
- for seg in segments:
279
- seg["mm_text"] = google_backup_translate(seg["text"], lang)
280
- return segments, "Google Translate fallback (Gemini Key မရှိ)"
281
- for start in range(0, len(segments), 25):
282
- batch = segments[start:start + 25]
283
- texts = [x["text"] for x in batch]
284
- try:
285
- result = gemini_translate_batch(texts, key, lang, tone_style)
286
- if len(result) != len(batch):
287
- raise RuntimeError("Gemini line count mismatch")
288
- for seg, mm in zip(batch, result):
289
- seg["mm_text"] = clean_burmese_unicode(mm)
290
- except Exception:
291
- for seg in batch:
292
- seg["mm_text"] = google_backup_translate(seg["text"], lang)
293
- return segments, "Gemini AI"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
294
 
295
  def generate_voice_sync(text, voice_id, filename, desired_speed=1.15):
296
  text = clean_burmese_unicode(text)
297
  if not text:
298
  return False
299
- rate = f"{'+' if desired_speed >= 1 else ''}{int((desired_speed - 1) * 100)}%"
 
300
  async def _gen():
301
  await edge_tts.Communicate(text, voice_id, rate=rate).save(filename)
 
302
  try:
303
  import asyncio
 
304
  asyncio.run(_gen())
305
  return os.path.exists(filename) and os.path.getsize(filename) > 500
306
  except Exception:
307
  return False
308
 
 
309
  def build_atempo_filter(factor):
310
- factor = max(0.5, float(factor))
311
  filters = []
312
- while factor > 2:
313
  filters.append("atempo=2.0")
314
- factor /= 2
315
- while factor < 0.5:
316
- filters.append("atempo=0.5")
317
- factor *= 2
318
- filters.append(f"atempo={factor:.6f}")
319
  return ",".join(filters)
320
 
321
- def fit_audio_naturally(input_audio, output_audio, start_time, max_end_time):
 
 
 
322
  dur = ffprobe_duration(input_audio)
323
  if dur <= 0:
324
  return False, 0.0, 1.0
325
- avail = max(0.20, float(max_end_time) - float(start_time) - TTS_GAP_SECONDS)
326
  if dur <= avail:
327
  shutil.copy2(input_audio, output_audio)
328
  return True, dur, 1.0
329
- speed = min(max(dur / avail, 1.0), TTS_MAX_SPEED)
330
  cmd = [
331
- "ffmpeg", "-y", "-i", input_audio,
332
- "-filter:a", build_atempo_filter(speed),
333
- "-ac", "2", "-ar", "44100", "-c:a", "aac", "-b:a", "160k",
334
- output_audio
 
 
 
 
 
 
 
 
 
 
 
335
  ]
336
- r = subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
337
- if r.returncode != 0:
338
- return False, 0.0, speed
339
- return True, ffprobe_duration(output_audio), speed
340
 
341
  def generate_single_tts_job(
342
  index, text, voice_id, work_dir, start_time, max_end_time, desired_speed
@@ -345,83 +324,84 @@ def generate_single_tts_job(
345
  fixed = os.path.join(work_dir, f"v_fix_{index}.m4a")
346
  if not generate_voice_sync(text, voice_id, raw, desired_speed):
347
  return {"index": index, "success": False}
348
- ok, dur, speed = fit_audio_naturally(
349
- raw, fixed, start_time, max_end_time
350
  )
351
  return {
352
  "index": index,
353
- "success": ok,
354
  "audio": fixed,
355
  "duration": dur,
356
- "speed_factor": speed
357
  }
358
 
 
359
  def build_synchronized_tts(segments, tts_results, work_dir, video_duration):
360
  valid = []
361
  for r in tts_results:
362
  if not r.get("success"):
363
  continue
364
  idx = r["index"]
 
 
365
  valid.append({
366
  "index": idx,
367
- "start": max(0.0, float(segments[idx]["start"])),
368
- "text": segments[idx].get("mm_text", ""),
369
  "audio": r["audio"],
370
- "duration": float(r.get("duration", 0))
371
  })
372
  valid.sort(key=lambda x: x["start"])
373
 
374
- timeline = []
375
- last_end = 0.0
376
- for item in valid:
377
- start = max(item["start"], last_end + TTS_GAP_SECONDS)
378
- end = min(float(video_duration), start + item["duration"])
379
- if end <= start:
380
- continue
381
- item["actual_start"] = start
382
- item["actual_end"] = end
383
- timeline.append(item)
384
- last_end = end
385
-
386
- if not timeline:
387
- raise RuntimeError("TTS audio မထုတ်နိုင်ပါ။")
388
-
389
  merged = os.path.join(work_dir, "tts_audio.m4a")
390
  inputs, filters, labels = [], [], []
391
- for i, item in enumerate(timeline):
392
- inputs += ["-i", item["audio"]]
393
- delay = int(item["actual_start"] * 1000)
394
  filters.append(f"[{i}:a]adelay={delay}|{delay}[v{i}]")
395
  labels.append(f"[v{i}]")
396
  filters.append(
397
- "".join(labels) +
398
- f"amix=inputs={len(labels)}:duration=longest:dropout_transition=0[voiceout]"
399
  )
400
  cmd = [
401
- "ffmpeg", "-y", *inputs,
402
- "-filter_complex", ";".join(filters),
403
- "-map", "[voiceout]", "-t", str(video_duration),
404
- "-ac", "2", "-ar", "44100", "-c:a", "aac", "-b:a", "192k",
405
- merged
 
 
 
 
 
 
 
 
 
 
 
 
 
406
  ]
407
- r = subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
408
- if r.returncode != 0 or not os.path.exists(merged):
409
- raise RuntimeError("TTS merge မအောင်မြင်ပါ။")
410
- return merged, timeline
411
 
412
- def ass_color(hex_c):
413
- c = (hex_c or "#FFFFFF").lstrip("#")
414
- if len(c) != 6:
415
- c = "FFFFFF"
416
- return f"&H00{c[4:6]}{c[2:4]}{c[0:2]}"
417
 
418
  def create_ass_subtitle(
419
- timeline, output_file, target_w, target_h,
420
- text_color="#FFFF00", stroke_color="#000000", sub_pos_percent=15
 
 
 
 
 
421
  ):
 
 
 
 
422
  font_size = 62 if target_h > target_w else 40
423
- margin_v = int(target_h * (float(sub_pos_percent) / 100))
424
- font_name = "Noto Sans Myanmar"
425
  header = f"""[Script Info]
426
  ScriptType: v4.00+
427
  PlayResX: {target_w}
@@ -429,112 +409,42 @@ PlayResY: {target_h}
429
 
430
  [V4+ Styles]
431
  Format: Name, Fontname, Fontsize, PrimaryColour, OutlineColour, BackColour, Bold, BorderStyle, Outline, Alignment, MarginV
432
- Style: Default,{font_name},{font_size},{ass_color(text_color)},{ass_color(stroke_color)},&H80000000,1,1,3,2,{margin_v}
433
 
434
  [Events]
435
  Format: Layer, Start, End, Style, Text
436
  """
437
  with open(output_file, "w", encoding="utf-8-sig") as f:
438
  f.write(header)
439
- for item in timeline:
440
  f.write(
441
- f"Dialogue: 0,{ass_timestamp(item['actual_start'])},"
442
- f"{ass_timestamp(item['actual_end'])},Default,"
443
- f"{escape_ass_text(item['text'])}\n"
444
  )
445
 
446
- def create_srt(timeline, output_file):
447
- with open(output_file, "w", encoding="utf-8-sig") as f:
448
- for i, item in enumerate(timeline, 1):
449
- f.write(f"{i}\n")
450
- f.write(f"{srt_timestamp(item['actual_start'])} --> {srt_timestamp(item['actual_end'])}\n")
451
- f.write(f"{clean_burmese_unicode(item['text'])}\n\n")
452
-
453
- def create_txt(timeline, output_file):
454
- with open(output_file, "w", encoding="utf-8-sig") as f:
455
- for item in timeline:
456
- f.write(clean_burmese_unicode(item["text"]) + "\n")
457
-
458
- def build_video_filter(
459
- input_path, target_w, target_h, background_fill,
460
- enable_zoom, zoom_level, mirror, filter_name
461
- ):
462
- z = max(1.0, float(zoom_level))
463
- parts = []
464
- if background_fill and "Blur" in background_fill:
465
- bg_scale = f"scale={target_w}:{target_h}:force_original_aspect_ratio=increase,crop={target_w}:{target_h},gblur=sigma=24"
466
- fg_w = int(target_w * z)
467
- fg_h = int(target_h * z)
468
- fg = f"scale={fg_w}:{fg_h}:force_original_aspect_ratio=decrease"
469
- if mirror:
470
- fg += ",hflip"
471
- if filter_name == "Warm":
472
- fg += ",eq=saturation=1.15:contrast=1.05"
473
- elif filter_name == "Dark":
474
- fg += ",eq=brightness=-0.08:contrast=1.10"
475
- elif filter_name == "Bright":
476
- fg += ",eq=brightness=0.08:contrast=1.05"
477
- return (
478
- f"[0:v]{bg_scale}[bg];"
479
- f"[0:v]{fg}[fg];"
480
- f"[bg][fg]overlay=(W-w)/2:(H-h)/2,"
481
- f"crop={target_w}:{target_h}:"
482
- f"(iw-{target_w})/2:(ih-{target_h})/2"
483
- )
484
- scale = f"scale={int(target_w*z)}:{int(target_h*z)}:force_original_aspect_ratio=increase"
485
- parts.append(scale)
486
- parts.append(f"crop={target_w}:{target_h}")
487
- if mirror:
488
- parts.append("hflip")
489
- if filter_name == "Warm":
490
- parts.append("eq=saturation=1.15:contrast=1.05")
491
- elif filter_name == "Dark":
492
- parts.append("eq=brightness=-0.08:contrast=1.10")
493
- elif filter_name == "Bright":
494
- parts.append("eq=brightness=0.08:contrast=1.05")
495
- return ",".join(parts)
496
-
497
- def add_logo_filter(base_filter, logo_path, target_w, target_h):
498
- if not logo_path or not os.path.exists(logo_path):
499
- return base_filter, []
500
- return (
501
- f"[0:v]{base_filter}[main];"
502
- f"[2:v]scale=iw*0.18:-1[logo];"
503
- f"[main][logo]overlay=W-w-25:25[vout]"
504
- ), ["-i", logo_path]
505
-
506
- def mix_audio(video_path, voice_path, bgm_path, original_volume, bgm_volume, out_audio, duration):
507
- inputs = ["-i", video_path, "-i", voice_path]
508
- labels = ["[0:a]"]
509
- filters = [f"[0:a]volume={max(0,float(original_volume))}[orig]"]
510
- filters.append("[1:a]volume=1.0[voice]")
511
- if bgm_path and os.path.exists(bgm_path):
512
- inputs += ["-i", bgm_path]
513
- filters.append(f"[2:a]volume={max(0,float(bgm_volume))}[bgm]")
514
- filters.append("[orig][voice][bgm]amix=inputs=3:duration=first:dropout_transition=2[aout]")
515
- else:
516
- filters.append("[orig][voice]amix=inputs=2:duration=first:dropout_transition=2[aout]")
517
- cmd = [
518
- "ffmpeg", "-y", *inputs,
519
- "-filter_complex", ";".join(filters),
520
- "-map", "[aout]", "-t", str(duration),
521
- "-ac", "2", "-ar", "44100", "-c:a", "aac", "-b:a", "192k",
522
- out_audio
523
- ]
524
- r = subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
525
- return r.returncode == 0 and os.path.exists(out_audio)
526
 
527
  def process_magic_recap_video(
528
- username, video_path, user_api_key, translation_method,
529
- ratio_select, background_fill, enable_zoom, zoom_level,
530
- logo_file, mirror_flip, filter_name, voice_gender, tone_style,
531
- text_color, stroke_color, blur_y_percent, blur_strength,
532
- sub_pos_percent, desired_speed, source_language,
533
- original_volume=0.0, bgm_file=None, bgm_volume=0.20,
534
- progress=gr.Progress()
 
 
 
 
 
 
 
 
 
 
 
 
535
  ):
536
  if not username:
537
- raise gr.Error("❌ Login အရင်ဝင်ပါ။")
538
 
539
  ok, msg = check_and_update_user_daily_credits(username)
540
  if not ok:
@@ -548,33 +458,38 @@ def process_magic_recap_video(
548
  if dur <= 0:
549
  raise gr.Error("❌ Video duration ဖတ်မရပါ။")
550
 
551
- credit_ok, credit_msg, used_credits = deduct_user_credits(username, dur)
552
  if not credit_ok:
553
  raise gr.Error(credit_msg)
554
 
555
  job_id = time.strftime("%Y%m%d_%H%M%S") + "_" + uuid.uuid4().hex[:6]
556
  work_dir = os.path.abspath(os.path.join(BASE_WORK_DIR, job_id))
557
  os.makedirs(work_dir, exist_ok=True)
558
- output_files = []
559
 
560
  try:
561
- progress(0.08, desc="🎙 Transcribing...")
562
  segs_raw, info = whisper_model.transcribe(
563
  video_path, beam_size=1, vad_filter=True
564
  )
565
  raw_segments = [
566
- {"start": float(s.start), "end": float(s.end), "text": s.text.strip()}
567
- for s in segs_raw if s.text and s.text.strip()
 
 
 
 
 
568
  ]
 
569
  if not raw_segments:
570
- raise gr.Error("❌ Video ထဲမှာ စကားပြောသံ မတွေ့ပါ။")
571
-
572
- progress(0.28, desc="🤖 Translating...")
573
- lang = source_language
574
- if lang == "Auto Detect":
575
- lang = info.language if info and info.language else "en"
576
- segments, method_used = translate_segments_batch(
577
- raw_segments, user_api_key, lang, translation_method, tone_style
578
  )
579
 
580
  target_w, target_h = (
@@ -582,264 +497,355 @@ def process_magic_recap_video(
582
  if "9:16" in ratio_select
583
  else (LANDSCAPE_W, LANDSCAPE_H)
584
  )
585
-
586
  voice_id = (
587
  "my-MM-NilarNeural"
588
  if "Female" in str(voice_gender)
589
  else "my-MM-ThihaNeural"
590
  )
591
 
592
- progress(0.48, desc="🎙️ Generating Burmese Voice...")
593
  from concurrent.futures import ThreadPoolExecutor, as_completed
594
 
595
- jobs = []
596
- for i, seg in enumerate(segments):
597
- next_start = segments[i + 1]["start"] if i + 1 < len(segments) else seg["end"]
598
- max_end = max(seg["end"], next_start)
599
- jobs.append((i, seg, max_end))
600
-
601
  tts_results = []
602
  with ThreadPoolExecutor(max_workers=TTS_WORKERS) as executor:
603
  futures = [
604
  executor.submit(
605
  generate_single_tts_job,
606
- i, seg.get("mm_text", ""), voice_id, work_dir,
607
- seg["start"], max_end, desired_speed
 
 
 
 
 
608
  )
609
- for i, seg, max_end in jobs
610
  ]
611
- for future in as_completed(futures):
612
- tts_results.append(future.result())
613
 
614
- progress(0.68, desc="🎧 Building Audio...")
615
  merged_tts, timeline = build_synchronized_tts(
616
  segments, tts_results, work_dir, dur
617
  )
618
 
619
- ass_file = os.path.join(work_dir, "sub.ass")
620
- srt_file = os.path.join(work_dir, "burmese_subtitles.srt")
621
- txt_file = os.path.join(work_dir, "burmese_script.txt")
622
-
623
  create_ass_subtitle(
624
- timeline, ass_file, target_w, target_h,
625
- text_color, stroke_color, sub_pos_percent
 
 
 
 
 
626
  )
627
- create_srt(timeline, srt_file)
628
- create_txt(timeline, txt_file)
629
 
630
- progress(0.78, desc="🎬 Rendering Video...")
631
- out_video = os.path.abspath(f"recap_out_{job_id}.mp4")
632
- out_audio = os.path.join(work_dir, "final_audio.m4a")
633
 
634
- logo_path = normalize_video_path(logo_file)
635
- bgm_path = normalize_video_path(bgm_file)
 
 
 
 
 
636
 
637
- if bgm_path and not os.path.exists(bgm_path):
638
- bgm_path = None
 
 
 
 
639
 
640
- if not mix_audio(
641
- video_path, merged_tts, bgm_path,
642
- original_volume, bgm_volume, out_audio, dur
643
- ):
644
- raise RuntimeError("Audio mixing မအောင်မြင်ပါ။")
645
 
646
- vf_base = build_video_filter(
647
- video_path, target_w, target_h, background_fill,
648
- enable_zoom, zoom_level, mirror_flip, filter_name
 
649
  )
650
 
651
- ass_p = ass_file.replace("\\", "/").replace(":", r"\:").replace("'", r"\'")
 
 
 
 
 
 
 
 
 
 
 
 
652
 
653
- if logo_path and os.path.exists(logo_path):
654
- vf = (
655
- f"{vf_base}[vbase];"
656
- f"movie='{logo_path.replace(chr(92), '/').replace(':', r'\\:')}'"
657
- f",scale=iw*0.18:-1[logo];"
658
- f"[vbase][logo]overlay=W-w-25:25,"
659
- f"ass='{ass_p}'"
 
 
 
 
660
  )
661
- cmd = [
662
- "ffmpeg", "-y", "-i", video_path, "-i", out_audio,
663
- "-filter_complex", vf,
664
- "-map", "0:v:0", "-map", "1:a:0",
665
- "-c:v", "libx264", "-preset", "ultrafast",
666
- "-c:a", "aac", "-b:a", "192k", "-t", str(dur),
667
- out_video
668
- ]
669
  else:
670
- vf = f"{vf_base},ass='{ass_p}'"
671
- cmd = [
672
- "ffmpeg", "-y", "-i", video_path, "-i", out_audio,
673
- "-vf", vf,
674
- "-map", "0:v:0", "-map", "1:a:0",
675
- "-c:v", "libx264", "-preset", "ultrafast",
676
- "-c:a", "aac", "-b:a", "192k", "-t", str(dur),
677
- out_video
678
- ]
679
 
680
- r = subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
681
- if r.returncode != 0 or not os.path.exists(out_video):
682
- raise RuntimeError("Video rendering မအောင်မြင်ပါ။")
683
 
684
- progress(1.0, desc="✅ Completed")
685
- output_files = [out_video, srt_file, txt_file]
686
- return (
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
687
  out_video,
688
- srt_file,
689
- txt_file,
690
- f"🎉 ပြီးပါပြီ။ Translation: {method_used} | {credit_msg}"
691
- )
692
 
693
- except gr.Error:
694
- refund_user_credits(username, used_credits)
695
- raise
696
- except Exception as e:
697
- refund_user_credits(username, used_credits)
698
- raise gr.Error(f"❌ Processing Error: {str(e)}")
699
  finally:
700
  shutil.rmtree(work_dir, ignore_errors=True)
701
 
 
 
 
 
702
  CUSTOM_CSS = r"""
703
  :root {
704
- --bg-dark:#0b0f19;
705
- --card-bg:#111827;
706
- --border:#263247;
707
- --text:#f8fafc;
708
- --muted:#9ca3af;
709
- --accent:#5850ec;
710
- --accent2:#38bdf8;
711
- --input:#1f2937;
712
  }
713
- body,.gradio-container {
714
- background:var(--bg-dark)!important;
715
- color:var(--text)!important;
716
- font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif!important;
 
717
  }
 
718
  .ui-card {
719
- background:var(--card-bg)!important;
720
- border:1px solid var(--border)!important;
721
- border-radius:16px!important;
722
- padding:18px!important;
723
- margin-bottom:14px!important;
 
724
  }
725
- input,textarea,select {
726
- background:var(--input)!important;
727
- color:#fff!important;
728
- border:1px solid #374151!important;
729
- border-radius:10px!important;
 
 
730
  }
731
- label span,.block-title {
732
- color:#f3f4f6!important;
733
- font-weight:600!important;
 
 
734
  }
 
735
  button.primary {
736
- background:var(--accent)!important;
737
- color:#fff!important;
738
- font-weight:700!important;
739
- border-radius:12px!important;
 
 
 
 
740
  }
 
741
  button.primary:hover {
742
- background:#4338ca!important;
 
743
  }
 
 
 
 
 
 
 
 
 
 
744
  .tab-nav button {
745
- color:var(--muted)!important;
746
- font-weight:600!important;
 
747
  }
 
748
  .tab-nav button.selected {
749
- color:var(--accent2)!important;
 
 
 
 
 
 
 
750
  }
751
  """
752
 
 
753
  def create_main_app_interface():
754
  with gr.Blocks(title="Movie Recap Studio") as app:
755
- logged_user = gr.State(None)
756
- user_role = gr.State(None)
757
 
758
  gr.HTML("""
759
- <div style="text-align:center;padding:18px 0">
760
- <h1 style="color:#38bdf8;margin:0;font-size:27px">🎬 Movie Recap Studio</h1>
761
- <p style="color:#9ca3af;margin:6px 0">AI Burmese Video Generator</p>
762
  </div>
763
  """)
764
 
 
765
  with gr.Column(elem_classes="ui-card", visible=True) as login_box:
766
  gr.Markdown("### 🔑 Account Login")
767
- username_input = gr.Textbox(label="Username", placeholder="Username")
768
- password_input = gr.Textbox(label="Password", type="password")
 
 
 
 
769
  login_btn = gr.Button("Login 🔓", variant="primary")
770
  login_status = gr.Markdown()
771
 
 
772
  with gr.Column(visible=False) as main_panel:
773
  with gr.Row():
774
- user_info_display = gr.Markdown("### 👤 User")
775
  logout_btn = gr.Button("Logout 🔒", size="sm")
776
 
777
  with gr.Tabs():
 
778
  with gr.TabItem("🎬 Video Generator"):
779
  with gr.Column(elem_classes="ui-card"):
780
- video_input = gr.Video(label="🎥 Input Video", sources=["upload"])
 
 
 
 
 
 
 
 
 
 
 
 
 
781
 
782
  with gr.Column(elem_classes="ui-card"):
783
  source_language = gr.Dropdown(
784
- ["Auto Detect","English","Chinese","Japanese","Korean"],
785
- value="Auto Detect", label="🌐 Language"
786
- )
787
- translation_method = gr.Dropdown(
788
- ["Google Translate (Free)","Gemini AI"],
789
- value="Google Translate (Free)", label="🤖 Translation"
 
 
 
790
  )
791
  user_api_key = gr.Textbox(
792
  label="🔑 Gemini API Key",
793
  type="password",
794
- placeholder="Optional if GEMINI_API_KEY Secret is set",
795
- visible=False
796
  )
797
 
798
  with gr.Column(elem_classes="ui-card"):
799
  voice_select = gr.Dropdown(
800
- ["🧕 Female (Nilar)","👨 Male (Thiha)"],
801
- value="🧕 Female (Nilar)", label="🎙️ Burmese Voice"
 
 
 
 
802
  )
803
  tone_style = gr.Dropdown(
804
- ["Thriller","Comedy","Dramatic","Action/Epic"],
805
- value="Thriller", label="🎭 Narration Style"
 
 
 
 
 
 
806
  )
807
  desired_speed = gr.Slider(
808
- 1.0,1.6,1.35,0.05,label="Voice Speed"
 
 
 
 
809
  )
810
 
811
  with gr.Column(elem_classes="ui-card"):
812
  ratio_select = gr.Dropdown(
813
- ["9:16 (Tiktok/Reels)","16:9 (Landscape)"],
814
- value="9:16 (Tiktok/Reels)", label="📱 Video Ratio"
 
 
 
 
815
  )
816
  background_fill = gr.Dropdown(
817
- ["Blur Background (အနောက်ခံ ဝါးမည်)",
818
- "Black Background (အမည်းရောင်ထားမည်)"],
 
 
819
  value="Blur Background (အနောက်ခံ ဝါးမည်)",
820
- label="🖼️ Background"
821
  )
822
- mirror_flip = gr.Checkbox("Mirror", value=True)
823
- enable_zoom = gr.Checkbox("Zoom & Crop", value=False)
824
- zoom_level = gr.Slider(1,3,1,0.1,label="Zoom Level")
825
- filter_select = gr.Dropdown(
826
- ["None","Warm","Bright","Dark"],
827
- value="None", label="🎨 Video Filter"
 
 
 
828
  )
829
- logo_file = gr.Image(
830
- type="filepath", label="🖼️ Logo (Optional)"
831
  )
832
-
833
- with gr.Column(elem_classes="ui-card"):
834
- gr.Markdown("### 🎵 Audio")
835
- original_volume = gr.Slider(
836
- 0,0.5,0,0.05,label="Original Audio Volume"
837
  )
838
- bgm_file = gr.Audio(
839
- type="filepath", label="🎵 Background Music (Optional)"
840
- )
841
- bgm_volume = gr.Slider(
842
- 0,0.5,0.2,0.05,label="BGM Volume"
 
843
  )
844
 
845
  with gr.Accordion("⚙️ Subtitle Settings", open=False):
@@ -850,171 +856,233 @@ def create_main_app_interface():
850
  label="Stroke Color", value="#000000"
851
  )
852
  sub_pos_percent = gr.Slider(
853
- 0,100,15,1,label="Subtitle Y Position (%)"
 
 
 
 
854
  )
855
 
856
- submit_btn = gr.Button("🚀 Generate Video", variant="primary")
 
 
857
  output_status = gr.Markdown()
 
858
 
859
- with gr.Row():
860
- output_video = gr.Video(label="🎬 Final Video")
861
- output_srt = gr.File(label="📝 Burmese SRT")
862
- output_txt = gr.File(label="📄 Burmese Script")
863
-
864
  with gr.TabItem("⚙️ Admin Panel", visible=False) as admin_tab:
865
- gr.Markdown("### 👑 Admin Control Panel")
866
  user_list_df = gr.JSON(label="Current Database")
867
  refresh_db_btn = gr.Button("🔄 Refresh User Data")
868
 
869
  with gr.Row():
870
- target_user = gr.Textbox(label="Target Username", value="User1")
871
- credit_change = gr.Number(label="Set Credits", value=24)
872
- add_days = gr.Number(label="Extend Days", value=30)
 
 
 
 
 
 
873
 
874
  with gr.Row():
875
- update_credit_btn = gr.Button("💳 Update Credits", variant="primary")
876
- extend_expire_btn = gr.Button("⏳ Extend Expiration", variant="primary")
 
 
 
 
877
 
878
  admin_action_status = gr.Markdown()
879
 
 
880
  def handle_login(u, p):
881
  db = load_user_db()
882
- if u in db and db[u].get("password") == p:
883
- role = db[u].get("role", "user")
884
  ok, msg = check_and_update_user_daily_credits(u)
885
  if not ok:
886
  return (
887
- gr.update(visible=True), gr.update(visible=False),
888
- f"❌ {msg}", None, None, "", gr.update(visible=False)
 
 
 
 
 
889
  )
890
- curr = load_user_db()[u]
891
- info = (
892
- f"### 👤 {u} ({role.upper()})\n"
893
- f"💳 Credits: **{curr.get('credits',0)}** | "
894
- f"⏳ Expire: **{curr.get('expire_at','-')}**"
895
- )
896
  return (
897
- gr.update(visible=False), gr.update(visible=True),
898
- "", u, role, info,
899
- gr.update(visible=role == "admin")
 
 
 
 
900
  )
901
- return (
902
- gr.update(visible=True), gr.update(visible=False),
903
- "❌ Username သို့မဟုတ် Password မှားနေပါသည်။",
904
- None, None, "", gr.update(visible=False)
905
- )
906
 
907
- def handle_logout():
908
  return (
909
  gr.update(visible=True),
910
  gr.update(visible=False),
911
- "",
 
912
  None,
913
- None
 
914
  )
915
 
916
- def refresh_admin_db(role):
917
- if role != "admin":
918
- return {"error": "Admin access required"}
 
919
  return load_user_db()
920
 
921
- def update_user_credits(role, username, amount):
922
- if role != "admin":
923
- return "❌ Admin access required."
924
  db = load_user_db()
925
- if username not in db:
926
- return "❌ User မတွေ့ပါ။"
927
- db[username]["credits"] = max(0, int(amount))
928
- save_user_db(db)
929
- return f"✅ {username} Credits = {int(amount)}"
930
-
931
- def extend_user_expiration(role, username, days):
932
- if role != "admin":
933
- return "❌ Admin access required."
934
  db = load_user_db()
935
- if username not in db:
936
- return "❌ User မတွေ့ပါ။"
937
- try:
938
- curr = datetime.strptime(
939
  db[username]["expire_at"], "%Y-%m-%d %H:%M:%S"
940
  )
941
- except Exception:
942
- curr = datetime.now()
943
- new_exp = curr + timedelta(days=int(days))
944
- db[username]["expire_at"] = new_exp.strftime("%Y-%m-%d %H:%M:%S")
945
- save_user_db(db)
946
- return f"✅ {username} Expire = {db[username]['expire_at']}"
 
947
 
 
948
  login_btn.click(
949
- handle_login,
950
- [username_input,password_input],
951
- [login_box,main_panel,login_status,logged_user,user_role,user_info_display,admin_tab]
 
 
 
 
 
 
 
 
952
  )
953
-
954
  logout_btn.click(
955
- handle_logout,
956
- outputs=[login_box,main_panel,login_status,logged_user,user_role]
957
- )
958
-
959
- translation_method.change(
960
- lambda x: gr.update(visible=x == "Gemini AI"),
961
- translation_method,
962
- user_api_key
963
  )
964
 
965
  def generate_wrapper(
966
- user,video,api_key,translation_mode,ratio,background,
967
- zoom_enabled,zoom,logo,mirror,filter_name,voice,tone,
968
- text_color,stroke_color,blur_y,blur_strength,
969
- subtitle_position,speed,language,original_vol,bgm,bgm_vol,
970
- progress=gr.Progress()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
971
  ):
972
  try:
973
- return process_magic_recap_video(
974
- user,video,api_key,translation_mode,ratio,background,
975
- zoom_enabled,zoom,logo,mirror,filter_name,voice,tone,
976
- text_color,stroke_color,blur_y,blur_strength,
977
- subtitle_position,speed,language,
978
- original_vol,bgm,bgm_vol,progress
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
979
  )
980
  except gr.Error as e:
981
- return None,None,None,str(e)
982
  except Exception as e:
983
- return None,None,None,f"❌ Error: {str(e)}"
984
 
985
  submit_btn.click(
986
- generate_wrapper,
987
- [
988
- logged_user,video_input,user_api_key,translation_method,
989
- ratio_select,background_fill,enable_zoom,zoom_level,
990
- logo_file,mirror_flip,filter_select,voice_select,tone_style,
991
- text_color_input,stroke_color_input,
992
- gr.State(75),gr.State(51),sub_pos_percent,desired_speed,
993
- source_language,original_volume,bgm_file,bgm_volume
 
 
 
 
 
 
 
 
 
 
 
 
994
  ],
995
- [output_video,output_srt,output_txt,output_status]
996
- )
997
-
998
- refresh_db_btn.click(
999
- refresh_admin_db,[user_role],[user_list_df]
1000
  )
1001
 
 
1002
  update_credit_btn.click(
1003
- update_user_credits,
1004
- [user_role,target_user,credit_change],
1005
- [admin_action_status]
1006
  )
1007
-
1008
  extend_expire_btn.click(
1009
- extend_user_expiration,
1010
- [user_role,target_user,add_days],
1011
- [admin_action_status]
1012
  )
1013
 
1014
  return app
1015
 
 
1016
  if __name__ == "__main__":
1017
- os.makedirs(BASE_WORK_DIR, exist_ok=True)
1018
  demo_app = create_main_app_interface()
1019
  demo_app.queue(max_size=10)
1020
- demo_app.launch(css=CUSTOM_CSS, theme=gr.themes.Default())
 
1
+ from datetime import datetime, timedelta
2
  import json
3
  import os
4
  import re
 
7
  import time
8
  import unicodedata
9
  import uuid
10
+ import av
11
+
12
+ # AV PATCH
13
+ _original_av_open = av.open
14
+
15
+
16
+ def _patched_av_open(*args, **kwargs):
17
+ kwargs.pop("metadata_errors", None)
18
+ return _original_av_open(*args, **kwargs)
19
+
20
 
21
+ av.open = _patched_av_open
22
+
23
+ import edge_tts
24
+ import gradio as gr
25
+ from faster_whisper import WhisperModel
26
+ from google import genai
27
+
28
+ # USER DATABASE & CREDIT SYSTEM
29
  DB_FILE = "user_db.json"
 
 
 
 
 
 
 
 
30
 
 
 
 
 
 
31
 
32
  def load_user_db():
33
  if not os.path.exists(DB_FILE):
34
  now = datetime.now()
35
+ expire_date = (now + timedelta(days=60)).strftime("%Y-%m-%d %H:%M:%S")
36
+ initial_db = {
37
  "User1": {
38
  "password": "123456",
39
  "role": "user",
40
  "credits": 24,
41
  "last_reset": now.strftime("%Y-%m-%d"),
42
  "created_at": now.strftime("%Y-%m-%d %H:%M:%S"),
43
+ "expire_at": expire_date,
44
  },
45
  "admin": {
46
  "password": "241212",
 
52
  },
53
  }
54
  with open(DB_FILE, "w", encoding="utf-8") as f:
55
+ json.dump(initial_db, f, indent=4)
56
+ return initial_db
57
  try:
58
  with open(DB_FILE, "r", encoding="utf-8") as f:
59
  return json.load(f)
60
  except Exception:
61
  return {}
62
 
63
+
64
  def save_user_db(db):
65
  with open(DB_FILE, "w", encoding="utf-8") as f:
66
+ json.dump(db, f, indent=4)
67
+
68
 
69
  def check_and_update_user_daily_credits(username):
70
  db = load_user_db()
71
  if username not in db:
72
  return False, "❌ User မတွေ့ပါ။"
73
+
74
  user = db[username]
75
  if user.get("role") == "admin":
76
  return True, "Admin access granted."
77
+
 
 
 
78
  now = datetime.now()
79
+ expire_at = datetime.strptime(user.get("expire_at"), "%Y-%m-%d %H:%M:%S")
80
  if now > expire_at:
81
+ return (
82
+ False,
83
+ f"❌ သင့် Account ၏ သက်တမ်း (၂ လ) ကုန်ဆုံးသွားပါပြီ ({user.get('expire_at')} ထိသာ)။",
84
+ )
85
+
86
+ today_str = now.strftime("%Y-%m-%d")
87
+ if user.get("last_reset") != today_str:
88
  user["credits"] = 24
89
+ user["last_reset"] = today_str
90
  db[username] = user
91
  save_user_db(db)
92
+
93
  return True, "OK"
94
 
 
 
95
 
96
  def deduct_user_credits(username, video_duration_seconds):
97
  db = load_user_db()
98
  if username not in db:
99
+ return False, "❌ User မတွေ့ပါ။"
100
+
101
  user = db[username]
102
  if user.get("role") == "admin":
103
+ return True, "Admin (Unlimited Credits)"
 
 
 
 
 
 
 
104
 
105
+ units = int((video_duration_seconds + 9.99) // 10)
106
+ required_credits = units * 2
 
 
 
 
 
107
 
108
+ if user["credits"] < required_credits:
109
+ return (
110
+ False,
111
+ f"❌ Credit မလုံလောက်ပါ။ လိုအပ်သည်: {required_credits} Credits, သင့်ထံတွင်ရှိသည်: {user['credits']} Credits",
112
+ )
113
 
114
+ user["credits"] -= required_credits
115
+ db[username] = user
116
+ save_user_db(db)
117
+ return (
118
+ True,
119
+ f"✅ {required_credits} Credits ဖြတ်တောက်ပြီးပါပြီ။ (ကျန်ရှိ Credit: {user['credits']})",
120
+ )
121
 
 
 
 
122
 
123
+ # CONFIG
124
+ FONT_FILE = "Myanmarfont.ttf"
125
+ MODEL_NAME = "gemini-2.5-flash"
126
+ SYSTEM_INSTRUCTION = "You are a professional movie recap writer and Burmese narrator. Translate subtitle lines into natural, concise and engaging Burmese movie recap narration. Preserve names, numbers, events and meaning. Output ONLY a valid JSON array of strings corresponding to each line in order, without markdown formatting."
127
+ BASE_WORK_DIR = "temp_space_workspace"
128
+ TIKTOK_W, TIKTOK_H = 720, 1280
129
+ LANDSCAPE_W, LANDSCAPE_H = 1280, 720
130
+ TTS_WORKERS = 4
131
+ TTS_MAX_SPEED = 1.85
132
+ TTS_GAP_SECONDS = 0.04
133
 
134
  whisper_model = WhisperModel(
135
  "small",
 
138
  cpu_threads=max(1, os.cpu_count() or 2),
139
  )
140
 
141
+ ZERO_WIDTH_CHARS = {"\u200b", "\u200c", "\u200d", "\u2060", "\ufeff", "\u00ad"}
142
+
 
143
 
144
  def clean_burmese_unicode(text):
145
  if text is None:
146
  return ""
147
  text = str(text)
148
+ for char in ZERO_WIDTH_CHARS:
149
+ text = text.replace(char, "")
150
  text = unicodedata.normalize("NFC", text)
151
+ cleaned = [
152
+ c
153
+ for c in text
154
+ if not unicodedata.category(c).startswith("C") or c in ("\n", "\r", "\t")
155
+ ]
156
+ text = "".join(cleaned)
157
  text = re.sub(r"[ \t]+", " ", text)
158
  return re.sub(r"\n{3,}", "\n\n", text).strip()
159
 
 
 
 
 
 
 
160
 
161
  def normalize_video_path(video_input):
162
  if not video_input:
163
  return None
164
  if isinstance(video_input, str):
165
  return video_input
166
+ return getattr(video_input, "path", None) or getattr(
167
+ video_input, "name", None
168
+ )
169
+
170
 
171
  def ffprobe_duration(path):
172
  try:
173
+ result = subprocess.run(
174
+ [
175
+ "ffprobe",
176
+ "-v",
177
+ "error",
178
+ "-show_entries",
179
+ "format=duration",
180
+ "-of",
181
+ "default=noprint_wrappers=1:nokey=1",
182
+ path,
183
+ ],
184
+ stdout=subprocess.PIPE,
185
+ stderr=subprocess.DEVNULL,
186
+ text=True,
187
  )
188
+ return float(result.stdout.strip())
189
  except Exception:
190
  return 0.0
191
 
192
+
193
  def ass_timestamp(seconds):
194
  seconds = max(0.0, float(seconds))
195
  h, r = divmod(seconds, 3600)
196
  m, s = divmod(r, 60)
197
+ cs = int(round((s - int(s)) * 100))
 
 
 
198
  return f"{int(h)}:{int(m):02d}:{int(s):02d}.{cs:02d}"
199
 
 
 
 
 
 
 
 
 
 
 
200
 
201
  def escape_ass_text(text):
202
+ text = clean_burmese_unicode(text)
203
  return (
204
+ text.replace("\\", r"\\")
 
205
  .replace("{", r"\{")
206
  .replace("}", r"\}")
207
  .replace("\n", r"\N")
208
  )
209
 
210
+
211
+ # GEMINI TRANSLATION (PURE GEMINI AI ONLY)
212
+ def translate_segments_batch_gemini(
213
+ segments,
214
+ user_api_key,
215
+ source_lang="en",
216
+ tone_style="Thriller",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
217
  ):
218
+ if not user_api_key or not user_api_key.strip():
219
+ raise gr.Error("❌ Gemini API Key ထည့်သွင်းပေးရန် လိုအပ်ပါသည်။")
220
+
221
+ try:
222
+ client = genai.Client(api_key=user_api_key.strip())
223
+ input_texts = [seg["text"] for seg in segments]
224
+
225
+ prompt = f"""Target Tone/Style: {tone_style}
226
+ Source Language Code: {source_lang}
227
+
228
+ Translate the following list of sentences into natural Burmese movie recap style narration.
229
+ Output strictly a JSON array of strings containing ONLY the translated sentences in the exact same order.
230
+
231
+ Input:
232
+ {json.dumps(input_texts, ensure_ascii=False)}"""
233
+
234
+ response = client.models.generate_content(
235
+ model=MODEL_NAME,
236
+ contents=prompt,
237
+ config={"system_instruction": SYSTEM_INSTRUCTION},
238
+ )
239
+
240
+ res_text = response.text.strip()
241
+ res_text = re.sub(r"^```(?:json)?\s*", "", res_text, flags=re.IGNORECASE)
242
+ res_text = re.sub(r"\s*```$", "", res_text)
243
+
244
+ translated_list = json.loads(res_text)
245
+
246
+ if isinstance(translated_list, list) and len(translated_list) == len(
247
+ segments
248
+ ):
249
+ for i, seg in enumerate(segments):
250
+ seg["mm_text"] = clean_burmese_unicode(translated_list[i])
251
+ else:
252
+ for seg in segments:
253
+ seg["mm_text"] = clean_burmese_unicode(seg["text"])
254
+ except Exception as e:
255
+ raise gr.Error(f"❌ Gemini API Translation Error: {str(e)}")
256
+
257
+ return segments
258
+
259
 
260
  def generate_voice_sync(text, voice_id, filename, desired_speed=1.15):
261
  text = clean_burmese_unicode(text)
262
  if not text:
263
  return False
264
+ rate = f"+{int((desired_speed - 1.0) * 100)}%"
265
+
266
  async def _gen():
267
  await edge_tts.Communicate(text, voice_id, rate=rate).save(filename)
268
+
269
  try:
270
  import asyncio
271
+
272
  asyncio.run(_gen())
273
  return os.path.exists(filename) and os.path.getsize(filename) > 500
274
  except Exception:
275
  return False
276
 
277
+
278
  def build_atempo_filter(factor):
279
+ factor = float(factor)
280
  filters = []
281
+ while factor > 2.0:
282
  filters.append("atempo=2.0")
283
+ factor /= 2.0
284
+ filters.append(f"atempo={max(0.5, factor):.6f}")
 
 
 
285
  return ",".join(filters)
286
 
287
+
288
+ def fit_audio_naturally(
289
+ input_audio, output_audio, start_time, max_end_time, desired_speed
290
+ ):
291
  dur = ffprobe_duration(input_audio)
292
  if dur <= 0:
293
  return False, 0.0, 1.0
294
+ avail = max(0.10, max_end_time - start_time - TTS_GAP_SECONDS)
295
  if dur <= avail:
296
  shutil.copy2(input_audio, output_audio)
297
  return True, dur, 1.0
298
+ speed_factor = max(1.0, min(dur / avail, TTS_MAX_SPEED))
299
  cmd = [
300
+ "ffmpeg",
301
+ "-y",
302
+ "-i",
303
+ input_audio,
304
+ "-filter:a",
305
+ build_atempo_filter(speed_factor),
306
+ "-ac",
307
+ "2",
308
+ "-ar",
309
+ "44100",
310
+ "-c:a",
311
+ "aac",
312
+ "-b:a",
313
+ "160k",
314
+ output_audio,
315
  ]
316
+ subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
317
+ return True, ffprobe_duration(output_audio), speed_factor
318
+
 
319
 
320
  def generate_single_tts_job(
321
  index, text, voice_id, work_dir, start_time, max_end_time, desired_speed
 
324
  fixed = os.path.join(work_dir, f"v_fix_{index}.m4a")
325
  if not generate_voice_sync(text, voice_id, raw, desired_speed):
326
  return {"index": index, "success": False}
327
+ fitted, dur, spd = fit_audio_naturally(
328
+ raw, fixed, start_time, max_end_time, desired_speed
329
  )
330
  return {
331
  "index": index,
332
+ "success": fitted,
333
  "audio": fixed,
334
  "duration": dur,
335
+ "speed_factor": spd,
336
  }
337
 
338
+
339
  def build_synchronized_tts(segments, tts_results, work_dir, video_duration):
340
  valid = []
341
  for r in tts_results:
342
  if not r.get("success"):
343
  continue
344
  idx = r["index"]
345
+ seg = segments[idx]
346
+ start = max(0.0, float(seg["start"]))
347
  valid.append({
348
  "index": idx,
349
+ "start": start,
350
+ "text": seg.get("mm_text", ""),
351
  "audio": r["audio"],
 
352
  })
353
  valid.sort(key=lambda x: x["start"])
354
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
355
  merged = os.path.join(work_dir, "tts_audio.m4a")
356
  inputs, filters, labels = [], [], []
357
+ for i, item in enumerate(valid):
358
+ inputs.extend(["-i", item["audio"]])
359
+ delay = int(round(item["start"] * 1000))
360
  filters.append(f"[{i}:a]adelay={delay}|{delay}[v{i}]")
361
  labels.append(f"[v{i}]")
362
  filters.append(
363
+ "".join(labels)
364
+ + f"amix=inputs={len(valid)}:duration=longest:dropout_transition=0[voiceout]"
365
  )
366
  cmd = [
367
+ "ffmpeg",
368
+ "-y",
369
+ *inputs,
370
+ "-filter_complex",
371
+ ";".join(filters),
372
+ "-map",
373
+ "[voiceout]",
374
+ "-t",
375
+ str(video_duration),
376
+ "-ac",
377
+ "2",
378
+ "-ar",
379
+ "44100",
380
+ "-c:a",
381
+ "aac",
382
+ "-b:a",
383
+ "192k",
384
+ merged,
385
  ]
386
+ subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
387
+ return merged, valid
 
 
388
 
 
 
 
 
 
389
 
390
  def create_ass_subtitle(
391
+ segments,
392
+ output_file,
393
+ target_w,
394
+ target_h,
395
+ text_color="#FFFF00",
396
+ stroke_color="#000000",
397
+ sub_pos_percent=15,
398
  ):
399
+ def ass_color(hex_c):
400
+ c = (hex_c or "#FFFFFF").lstrip("#")
401
+ return f"&H00{int(c[4:6],16):02X}{int(c[2:4],16):02X}{int(c[0:2],16):02X}"
402
+
403
  font_size = 62 if target_h > target_w else 40
404
+ margin_v = int(target_h * (float(sub_pos_percent) / 100.0))
 
405
  header = f"""[Script Info]
406
  ScriptType: v4.00+
407
  PlayResX: {target_w}
 
409
 
410
  [V4+ Styles]
411
  Format: Name, Fontname, Fontsize, PrimaryColour, OutlineColour, BackColour, Bold, BorderStyle, Outline, Alignment, MarginV
412
+ Style: Default,Arial,{font_size},{ass_color(text_color)},{ass_color(stroke_color)},&H80000000,1,1,3,2,{margin_v}
413
 
414
  [Events]
415
  Format: Layer, Start, End, Style, Text
416
  """
417
  with open(output_file, "w", encoding="utf-8-sig") as f:
418
  f.write(header)
419
+ for seg in segments:
420
  f.write(
421
+ f"Dialogue: 0,{ass_timestamp(seg['start'])},{ass_timestamp(seg['start']+2.5)},Default,{escape_ass_text(seg.get('mm_text', seg['text']))}\n"
 
 
422
  )
423
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
424
 
425
  def process_magic_recap_video(
426
+ username,
427
+ video_path,
428
+ user_api_key,
429
+ bgm_file,
430
+ bgm_volume,
431
+ ratio_select,
432
+ background_fill,
433
+ enable_zoom,
434
+ zoom_level,
435
+ mirror_flip,
436
+ filter_color,
437
+ voice_gender,
438
+ tone_style,
439
+ text_color,
440
+ stroke_color,
441
+ sub_pos_percent,
442
+ desired_speed,
443
+ source_language,
444
+ progress=gr.Progress(),
445
  ):
446
  if not username:
447
+ raise gr.Error("❌ ကျေးဇူးပြု၍ Login အရင်ဝင်ပေးပါ။")
448
 
449
  ok, msg = check_and_update_user_daily_credits(username)
450
  if not ok:
 
458
  if dur <= 0:
459
  raise gr.Error("❌ Video duration ဖတ်မရပါ။")
460
 
461
+ credit_ok, credit_msg = deduct_user_credits(username, dur)
462
  if not credit_ok:
463
  raise gr.Error(credit_msg)
464
 
465
  job_id = time.strftime("%Y%m%d_%H%M%S") + "_" + uuid.uuid4().hex[:6]
466
  work_dir = os.path.abspath(os.path.join(BASE_WORK_DIR, job_id))
467
  os.makedirs(work_dir, exist_ok=True)
 
468
 
469
  try:
470
+ progress(0.1, desc="🎙 Transcribing...")
471
  segs_raw, info = whisper_model.transcribe(
472
  video_path, beam_size=1, vad_filter=True
473
  )
474
  raw_segments = [
475
+ {
476
+ "start": float(s.start),
477
+ "end": float(s.end),
478
+ "text": s.text.strip(),
479
+ }
480
+ for s in segs_raw
481
+ if s.text
482
  ]
483
+
484
  if not raw_segments:
485
+ raise gr.Error("❌ Video ထဲတွင် စကားပြောသံ မတွေ့ရပါ။")
486
+
487
+ progress(0.3, desc="🤖 Translating with Gemini...")
488
+ segments = translate_segments_batch_gemini(
489
+ raw_segments,
490
+ user_api_key,
491
+ info.language if info else "en",
492
+ tone_style,
493
  )
494
 
495
  target_w, target_h = (
 
497
  if "9:16" in ratio_select
498
  else (LANDSCAPE_W, LANDSCAPE_H)
499
  )
 
500
  voice_id = (
501
  "my-MM-NilarNeural"
502
  if "Female" in str(voice_gender)
503
  else "my-MM-ThihaNeural"
504
  )
505
 
506
+ progress(0.5, desc="🎙️ Voice Generating...")
507
  from concurrent.futures import ThreadPoolExecutor, as_completed
508
 
 
 
 
 
 
 
509
  tts_results = []
510
  with ThreadPoolExecutor(max_workers=TTS_WORKERS) as executor:
511
  futures = [
512
  executor.submit(
513
  generate_single_tts_job,
514
+ i,
515
+ s.get("mm_text", ""),
516
+ voice_id,
517
+ work_dir,
518
+ s["start"],
519
+ s["end"],
520
+ desired_speed,
521
  )
522
+ for i, s in enumerate(segments)
523
  ]
524
+ for f in as_completed(futures):
525
+ tts_results.append(f.result())
526
 
 
527
  merged_tts, timeline = build_synchronized_tts(
528
  segments, tts_results, work_dir, dur
529
  )
530
 
531
+ ass_file = os.path.abspath(os.path.join(work_dir, "sub.ass"))
 
 
 
532
  create_ass_subtitle(
533
+ timeline,
534
+ ass_file,
535
+ target_w,
536
+ target_h,
537
+ text_color,
538
+ stroke_color,
539
+ sub_pos_percent,
540
  )
 
 
541
 
542
+ # BUILD FFMPEG VIDEO FILTER PIPELINE
543
+ v_filters = []
 
544
 
545
+ if mirror_flip:
546
+ v_filters.append("hflip")
547
+
548
+ if enable_zoom and zoom_level > 1.0:
549
+ v_filters.append(
550
+ f"crop=iw/{zoom_level}:ih/{zoom_level},scale={target_w}:{target_h}"
551
+ )
552
 
553
+ if filter_color == "Grayscale (အဖြူအမည်း)":
554
+ v_filters.append("hue=s=0")
555
+ elif filter_color == "Cinematic Dark":
556
+ v_filters.append("eq=contrast=1.2:brightness=-0.05:saturation=0.9")
557
+ elif filter_color == "Vibrant Warm":
558
+ v_filters.append("eq=contrast=1.1:saturation=1.3")
559
 
560
+ base_vf = ",".join(v_filters) if v_filters else "null"
 
 
 
 
561
 
562
+ ass_p = (
563
+ ass_file.replace("\\", "/")
564
+ .replace(":", r"\:")
565
+ .replace("'", r"\'")
566
  )
567
 
568
+ if "Blur Background" in background_fill:
569
+ complex_vf = (
570
+ f"[0:v]{base_vf}[v_base];"
571
+ f"[v_base]split=2[v_in1][v_in2];"
572
+ f"[v_in1]scale={target_w}:{target_h}:force_original_aspect_ratio=increase,crop={target_w}:{target_h},boxblur=20:5[bg];"
573
+ f"[v_in2]scale={target_w}:{target_h}:force_original_aspect_ratio=decrease[fg];"
574
+ f"[bg][fg]overlay=(W-w)/2:(H-h)/2,ass='{ass_p}'[vfinal]"
575
+ )
576
+ else:
577
+ complex_vf = (
578
+ f"[0:v]{base_vf},scale={target_w}:{target_h}:force_original_aspect_ratio=decrease,"
579
+ f"pad={target_w}:{target_h}:(ow-iw)/2:(oh-ih)/2:black,ass='{ass_p}'[vfinal]"
580
+ )
581
 
582
+ # BUILD FFMPEG AUDIO FILTER PIPELINE (TTS + BGM MIXING)
583
+ bgm_path = normalize_video_path(bgm_file)
584
+ inputs = ["-i", video_path, "-i", merged_tts]
585
+
586
+ if bgm_path and os.path.exists(bgm_path):
587
+ inputs.extend(["-i", bgm_path])
588
+ bgm_vol_val = float(bgm_volume)
589
+ complex_af = (
590
+ f"[1:a]volume=1.0[tts];"
591
+ f"[2:a]volume={bgm_vol_val},aloop=loop=-1:size=2e+09[bgm];"
592
+ f"[tts][bgm]amix=inputs=2:duration=first:dropout_transition=2[afinal]"
593
  )
 
 
 
 
 
 
 
 
594
  else:
595
+ complex_af = "[1:a]volume=1.0[afinal]"
 
 
 
 
 
 
 
 
596
 
597
+ out_video = os.path.abspath(f"recap_out_{job_id}.mp4")
 
 
598
 
599
+ cmd = [
600
+ "ffmpeg",
601
+ "-y",
602
+ *inputs,
603
+ "-filter_complex",
604
+ f"{complex_vf};{complex_af}",
605
+ "-map",
606
+ "[vfinal]",
607
+ "-map",
608
+ "[afinal]",
609
+ "-c:v",
610
+ "libx264",
611
+ "-preset",
612
+ "ultrafast",
613
+ "-c:a",
614
+ "aac",
615
+ "-t",
616
+ str(dur),
617
  out_video,
618
+ ]
 
 
 
619
 
620
+ subprocess.run(
621
+ cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
622
+ )
623
+ return out_video, credit_msg
 
 
624
  finally:
625
  shutil.rmtree(work_dir, ignore_errors=True)
626
 
627
+
628
+ # ==========================================
629
+ # PURPLE ACCENT & DARK BLUE UI THEME
630
+ # ==========================================
631
  CUSTOM_CSS = r"""
632
  :root {
633
+ --bg-dark: #0b0f19;
634
+ --card-bg: #111827;
635
+ --border-color: #1f293d;
636
+ --text-primary: #ffffff;
637
+ --text-muted: #9ca3af;
638
+ --accent-purple: #5850ec;
639
+ --accent-purple-hover: #4338ca;
640
+ --input-bg: #1f2937;
641
  }
642
+
643
+ body, .gradio-container {
644
+ background-color: var(--bg-dark) !important;
645
+ color: var(--text-primary) !important;
646
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif !important;
647
  }
648
+
649
  .ui-card {
650
+ background: var(--card-bg) !important;
651
+ border: 1px solid var(--border-color) !important;
652
+ border-radius: 16px !important;
653
+ padding: 18px !important;
654
+ margin-bottom: 16px !important;
655
+ box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.5) !important;
656
  }
657
+
658
+ input, textarea, select, .secondary {
659
+ background-color: var(--input-bg) !important;
660
+ color: #ffffff !important;
661
+ border: 1px solid #374151 !important;
662
+ border-radius: 10px !important;
663
+ font-size: 14px !important;
664
  }
665
+
666
+ label span, .block-title, div[data-testid="markdownbox"] p {
667
+ color: #f3f4f6 !important;
668
+ font-weight: 600 !important;
669
+ font-size: 14px !important;
670
  }
671
+
672
  button.primary {
673
+ background: var(--accent-purple) !important;
674
+ color: #ffffff !important;
675
+ font-weight: 600 !important;
676
+ font-size: 15px !important;
677
+ border-radius: 12px !important;
678
+ border: none !important;
679
+ padding: 10px 20px !important;
680
+ transition: all 0.2s ease !important;
681
  }
682
+
683
  button.primary:hover {
684
+ background: var(--accent-purple-hover) !important;
685
+ box-shadow: 0 0 15px rgba(88, 80, 236, 0.4) !important;
686
  }
687
+
688
+ input[type="range"]::-webkit-slider-thumb {
689
+ background: var(--accent-purple) !important;
690
+ }
691
+
692
+ input[type="checkbox"]:checked {
693
+ background-color: var(--accent-purple) !important;
694
+ border-color: var(--accent-purple) !important;
695
+ }
696
+
697
  .tab-nav button {
698
+ color: var(--text-muted) !important;
699
+ font-weight: 600 !important;
700
+ border-bottom: 2px solid transparent !important;
701
  }
702
+
703
  .tab-nav button.selected {
704
+ color: #38bdf8 !important;
705
+ border-bottom-color: #38bdf8 !important;
706
+ background: transparent !important;
707
+ }
708
+
709
+ .label-wrap {
710
+ color: #ffffff !important;
711
+ font-weight: bold !important;
712
  }
713
  """
714
 
715
+
716
  def create_main_app_interface():
717
  with gr.Blocks(title="Movie Recap Studio") as app:
718
+ logged_user = gr.State(value=None)
719
+ user_role = gr.State(value=None)
720
 
721
  gr.HTML("""
722
+ <div style="text-align:center; padding:15px 0;">
723
+ <h1 style="color:#38bdf8; margin:0; font-size: 26px; font-weight:800;">🎬 Movie Recap Studio</h1>
724
+ <p style="color:#9ca3af; font-size:13px;">Video → Gemini Burmese AI Translate → TTS Pipeline</p>
725
  </div>
726
  """)
727
 
728
+ # LOGIN PANEL
729
  with gr.Column(elem_classes="ui-card", visible=True) as login_box:
730
  gr.Markdown("### 🔑 Account Login")
731
+ username_input = gr.Textbox(
732
+ label="Username", placeholder="Enter Username"
733
+ )
734
+ password_input = gr.Textbox(
735
+ label="Password", type="password", placeholder="Enter Password"
736
+ )
737
  login_btn = gr.Button("Login 🔓", variant="primary")
738
  login_status = gr.Markdown()
739
 
740
+ # MAIN APP PANEL
741
  with gr.Column(visible=False) as main_panel:
742
  with gr.Row():
743
+ user_info_display = gr.Markdown("### 👤 User Info")
744
  logout_btn = gr.Button("Logout 🔒", size="sm")
745
 
746
  with gr.Tabs():
747
+ # TAB 1: MOVIE RECAP GENERATOR
748
  with gr.TabItem("🎬 Video Generator"):
749
  with gr.Column(elem_classes="ui-card"):
750
+ video_input = gr.Video(
751
+ label="🎥 Input Video", sources=["upload"]
752
+ )
753
+ bgm_input = gr.Audio(
754
+ label="🎵 Background Music (Optional)",
755
+ type="filepath",
756
+ )
757
+ bgm_volume = gr.Slider(
758
+ minimum=0.05,
759
+ maximum=0.50,
760
+ value=0.15,
761
+ step=0.01,
762
+ label="BGM Volume Level",
763
+ )
764
 
765
  with gr.Column(elem_classes="ui-card"):
766
  source_language = gr.Dropdown(
767
+ choices=[
768
+ "Auto Detect",
769
+ "English",
770
+ "Chinese",
771
+ "Japanese",
772
+ "Korean",
773
+ ],
774
+ value="Auto Detect",
775
+ label="Language",
776
  )
777
  user_api_key = gr.Textbox(
778
  label="🔑 Gemini API Key",
779
  type="password",
780
+ placeholder="Enter your Gemini API Key",
 
781
  )
782
 
783
  with gr.Column(elem_classes="ui-card"):
784
  voice_select = gr.Dropdown(
785
+ choices=[
786
+ "🧕 Female (Nilar)",
787
+ "👨 Male (Thiha)",
788
+ ],
789
+ value="🧕 Female (Nilar)",
790
+ label="Burmese Voice",
791
  )
792
  tone_style = gr.Dropdown(
793
+ choices=[
794
+ "Thriller",
795
+ "Comedy",
796
+ "Dramatic",
797
+ "Action/Epic",
798
+ ],
799
+ value="Thriller",
800
+ label="Narration Style",
801
  )
802
  desired_speed = gr.Slider(
803
+ minimum=1.0,
804
+ maximum=1.6,
805
+ value=1.35,
806
+ step=0.05,
807
+ label="Voice Speed",
808
  )
809
 
810
  with gr.Column(elem_classes="ui-card"):
811
  ratio_select = gr.Dropdown(
812
+ choices=[
813
+ "9:16 (Tiktok/Reels)",
814
+ "16:9 (Landscape)",
815
+ ],
816
+ value="9:16 (Tiktok/Reels)",
817
+ label="Video Ratio",
818
  )
819
  background_fill = gr.Dropdown(
820
+ choices=[
821
+ "Blur Background (အနောက်ခံ ဝါးမည်)",
822
+ "Black Background (အမည်းရောင်ထားမည်)",
823
+ ],
824
  value="Blur Background (အနောက်ခံ ဝါးမည်)",
825
+ label="Background",
826
  )
827
+ filter_color = gr.Dropdown(
828
+ choices=[
829
+ "None",
830
+ "Grayscale (အဖြူအမည်း)",
831
+ "Cinematic Dark",
832
+ "Vibrant Warm",
833
+ ],
834
+ value="None",
835
+ label="Video Filter",
836
  )
837
+ mirror_flip = gr.Checkbox(
838
+ label="Mirror (Horizontal Flip)", value=False
839
  )
840
+ enable_zoom = gr.Checkbox(
841
+ label="Zoom & Crop", value=False
 
 
 
842
  )
843
+ zoom_level = gr.Slider(
844
+ minimum=1.0,
845
+ maximum=2.0,
846
+ value=1.2,
847
+ step=0.1,
848
+ label="Zoom Level",
849
  )
850
 
851
  with gr.Accordion("⚙️ Subtitle Settings", open=False):
 
856
  label="Stroke Color", value="#000000"
857
  )
858
  sub_pos_percent = gr.Slider(
859
+ minimum=5,
860
+ maximum=80,
861
+ value=15,
862
+ step=1,
863
+ label="Subtitle Y Position (%)",
864
  )
865
 
866
+ submit_btn = gr.Button(
867
+ "🚀 Generate Video", variant="primary"
868
+ )
869
  output_status = gr.Markdown()
870
+ output_video = gr.Video(label="Final Output Video")
871
 
872
+ # TAB 2: ADMIN CONTROL PANEL
 
 
 
 
873
  with gr.TabItem("⚙️ Admin Panel", visible=False) as admin_tab:
874
+ gr.Markdown("### 👑 Admin Credit & Account Management")
875
  user_list_df = gr.JSON(label="Current Database")
876
  refresh_db_btn = gr.Button("🔄 Refresh User Data")
877
 
878
  with gr.Row():
879
+ target_user = gr.Textbox(
880
+ label="Target Username", placeholder="Enter username"
881
+ )
882
+ credit_change = gr.Number(
883
+ label="Set / Add Credits", value=24
884
+ )
885
+ add_days = gr.Number(
886
+ label="Extend Expiration (Days)", value=30
887
+ )
888
 
889
  with gr.Row():
890
+ update_credit_btn = gr.Button(
891
+ "Update Credits", variant="primary"
892
+ )
893
+ extend_expire_btn = gr.Button(
894
+ "Extend Expiration", variant="primary"
895
+ )
896
 
897
  admin_action_status = gr.Markdown()
898
 
899
+ # LOGIN HANDLER
900
  def handle_login(u, p):
901
  db = load_user_db()
902
+ if u in db and db[u]["password"] == p:
903
+ role = db[u]["role"]
904
  ok, msg = check_and_update_user_daily_credits(u)
905
  if not ok:
906
  return (
907
+ gr.update(visible=True),
908
+ gr.update(visible=False),
909
+ f"❌ {msg}",
910
+ None,
911
+ None,
912
+ "",
913
+ gr.update(visible=False),
914
  )
915
+
916
+ db = load_user_db()
917
+ curr_user = db[u]
918
+ info_text = f"### 👤 Logged in as: **{u}** ({role.upper()})\n💳 **Credits:** `{curr_user['credits']}` | ⏳ **Expire:** `{curr_user['expire_at']}`"
919
+
 
920
  return (
921
+ gr.update(visible=False),
922
+ gr.update(visible=True),
923
+ "",
924
+ u,
925
+ role,
926
+ info_text,
927
+ gr.update(visible=(role == "admin")),
928
  )
 
 
 
 
 
929
 
 
930
  return (
931
  gr.update(visible=True),
932
  gr.update(visible=False),
933
+ "❌ Username သို့မဟုတ် Password မှားယွင်းနေပါသည်။",
934
+ None,
935
  None,
936
+ "",
937
+ gr.update(visible=False),
938
  )
939
 
940
+ def handle_logout():
941
+ return gr.update(visible=True), gr.update(visible=False), "", None, None
942
+
943
+ def refresh_admin_db():
944
  return load_user_db()
945
 
946
+ def update_user_credits(username, new_credit):
 
 
947
  db = load_user_db()
948
+ if username in db:
949
+ db[username]["credits"] = int(new_credit)
950
+ save_user_db(db)
951
+ return f"✅ {username} ၏ Credit ကို {new_credit} သို့ ပြောင်းလဲပြီးပါပြီ။"
952
+ return "❌ User မတွေ့ပါ။"
953
+
954
+ def extend_user_expiration(username, days):
 
 
955
  db = load_user_db()
956
+ if username in db:
957
+ curr_exp = datetime.strptime(
 
 
958
  db[username]["expire_at"], "%Y-%m-%d %H:%M:%S"
959
  )
960
+ new_exp = curr_exp + timedelta(days=int(days))
961
+ db[username]["expire_at"] = new_exp.strftime(
962
+ "%Y-%m-%d %H:%M:%S"
963
+ )
964
+ save_user_db(db)
965
+ return f"✅ {username} ၏ သက်တမ်းကို {days} ရက် ထပ်တိုးပေးလိုက်ပါပြီ။ (Expire: {db[username]['expire_at']})"
966
+ return "❌ User မတွေ့ပါ။"
967
 
968
+ # BINDINGS
969
  login_btn.click(
970
+ fn=handle_login,
971
+ inputs=[username_input, password_input],
972
+ outputs=[
973
+ login_box,
974
+ main_panel,
975
+ login_status,
976
+ logged_user,
977
+ user_role,
978
+ user_info_display,
979
+ admin_tab,
980
+ ],
981
  )
 
982
  logout_btn.click(
983
+ fn=handle_logout,
984
+ outputs=[
985
+ login_box,
986
+ main_panel,
987
+ login_status,
988
+ logged_user,
989
+ user_role,
990
+ ],
991
  )
992
 
993
  def generate_wrapper(
994
+ user,
995
+ video,
996
+ bgm,
997
+ bgm_vol,
998
+ api_key,
999
+ ratio,
1000
+ background,
1001
+ zoom_enabled,
1002
+ zoom,
1003
+ mirror,
1004
+ filter_name,
1005
+ voice,
1006
+ tone,
1007
+ text_color,
1008
+ stroke_color,
1009
+ subtitle_position,
1010
+ speed,
1011
+ language,
1012
+ progress=gr.Progress(),
1013
  ):
1014
  try:
1015
+ res_path, cred_msg = process_magic_recap_video(
1016
+ user,
1017
+ video,
1018
+ api_key,
1019
+ bgm,
1020
+ bgm_vol,
1021
+ ratio,
1022
+ background,
1023
+ zoom_enabled,
1024
+ zoom,
1025
+ mirror,
1026
+ filter_name,
1027
+ voice,
1028
+ tone,
1029
+ text_color,
1030
+ stroke_color,
1031
+ subtitle_position,
1032
+ speed,
1033
+ language,
1034
+ progress,
1035
+ )
1036
+ return (
1037
+ res_path,
1038
+ f"🎉 အောင်မြင်စွာ ပြုလုပ်ပြီးပါပြီ။ ({cred_msg})",
1039
  )
1040
  except gr.Error as e:
1041
+ return None, str(e)
1042
  except Exception as e:
1043
+ return None, f"❌ Error: {str(e)}"
1044
 
1045
  submit_btn.click(
1046
+ fn=generate_wrapper,
1047
+ inputs=[
1048
+ logged_user,
1049
+ video_input,
1050
+ bgm_input,
1051
+ bgm_volume,
1052
+ user_api_key,
1053
+ ratio_select,
1054
+ background_fill,
1055
+ enable_zoom,
1056
+ zoom_level,
1057
+ mirror_flip,
1058
+ filter_color,
1059
+ voice_select,
1060
+ tone_style,
1061
+ text_color_input,
1062
+ stroke_color_input,
1063
+ sub_pos_percent,
1064
+ desired_speed,
1065
+ source_language,
1066
  ],
1067
+ outputs=[output_video, output_status],
 
 
 
 
1068
  )
1069
 
1070
+ refresh_db_btn.click(fn=refresh_admin_db, outputs=[user_list_df])
1071
  update_credit_btn.click(
1072
+ fn=update_user_credits,
1073
+ inputs=[target_user, credit_change],
1074
+ outputs=[admin_action_status],
1075
  )
 
1076
  extend_expire_btn.click(
1077
+ fn=extend_user_expiration,
1078
+ inputs=[target_user, add_days],
1079
+ outputs=[admin_action_status],
1080
  )
1081
 
1082
  return app
1083
 
1084
+
1085
  if __name__ == "__main__":
 
1086
  demo_app = create_main_app_interface()
1087
  demo_app.queue(max_size=10)
1088
+ demo_app.launch(css=CUSTOM_CSS, theme=gr.themes.Default())