Update app.py
Browse files
app.py
CHANGED
|
@@ -9,9 +9,7 @@ import uuid
|
|
| 9 |
from datetime import datetime, timedelta
|
| 10 |
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 11 |
|
| 12 |
-
import av
|
| 13 |
-
|
| 14 |
-
# AV PATCH
|
| 15 |
_original_av_open = av.open
|
| 16 |
|
| 17 |
def _patched_av_open(*args, **kwargs):
|
|
@@ -28,6 +26,7 @@ from google import genai
|
|
| 28 |
# USER DATABASE & CREDIT SYSTEM
|
| 29 |
DB_FILE = "user_db.json"
|
| 30 |
|
|
|
|
| 31 |
def load_user_db():
|
| 32 |
if not os.path.exists(DB_FILE):
|
| 33 |
now = datetime.now()
|
|
@@ -59,19 +58,19 @@ def load_user_db():
|
|
| 59 |
except Exception:
|
| 60 |
return {}
|
| 61 |
|
|
|
|
| 62 |
def save_user_db(db):
|
| 63 |
with open(DB_FILE, "w", encoding="utf-8") as f:
|
| 64 |
json.dump(db, f, indent=4)
|
| 65 |
|
|
|
|
| 66 |
def check_and_update_user_daily_credits(username):
|
| 67 |
db = load_user_db()
|
| 68 |
if username not in db:
|
| 69 |
return False, "❌ User မတွေ့ပါ။"
|
| 70 |
-
|
| 71 |
user = db[username]
|
| 72 |
if user.get("role") == "admin":
|
| 73 |
return True, "Admin access granted."
|
| 74 |
-
|
| 75 |
now = datetime.now()
|
| 76 |
expire_at = datetime.strptime(user.get("expire_at"), "%Y-%m-%d %H:%M:%S")
|
| 77 |
if now > expire_at:
|
|
@@ -79,34 +78,29 @@ def check_and_update_user_daily_credits(username):
|
|
| 79 |
False,
|
| 80 |
f"❌ သင့် Account ၏ သက်တမ်း ကုန်ဆုံးသွားပါပြီ ({user.get('expire_at')} ထိသာ)။",
|
| 81 |
)
|
| 82 |
-
|
| 83 |
today_str = now.strftime("%Y-%m-%d")
|
| 84 |
if user.get("last_reset") != today_str:
|
| 85 |
user["credits"] = 24
|
| 86 |
user["last_reset"] = today_str
|
| 87 |
db[username] = user
|
| 88 |
save_user_db(db)
|
| 89 |
-
|
| 90 |
return True, "OK"
|
| 91 |
|
|
|
|
| 92 |
def deduct_user_credits(username, video_duration_seconds):
|
| 93 |
db = load_user_db()
|
| 94 |
if username not in db:
|
| 95 |
return False, "❌ User မတွေ့ပါ။"
|
| 96 |
-
|
| 97 |
user = db[username]
|
| 98 |
if user.get("role") == "admin":
|
| 99 |
return True, "Admin (Unlimited Credits)"
|
| 100 |
-
|
| 101 |
units = int((video_duration_seconds + 9.99) // 10)
|
| 102 |
required_credits = units * 2
|
| 103 |
-
|
| 104 |
if user["credits"] < required_credits:
|
| 105 |
return (
|
| 106 |
False,
|
| 107 |
f"❌ Credit မလုံလောက်ပါ။ လိုအပ်သည်: {required_credits} Credits, သင့်ထံတွင်ရှိသည်: {user['credits']} Credits",
|
| 108 |
)
|
| 109 |
-
|
| 110 |
user["credits"] -= required_credits
|
| 111 |
db[username] = user
|
| 112 |
save_user_db(db)
|
|
@@ -115,9 +109,16 @@ def deduct_user_credits(username, video_duration_seconds):
|
|
| 115 |
f"✅ {required_credits} Credits ဖြတ်တောက်ပြီးပါပြီ။ (ကျန်ရှိ Credit: {user['credits']})",
|
| 116 |
)
|
| 117 |
|
|
|
|
| 118 |
# CONFIG
|
| 119 |
FONT_FILE = "Myanmarfont.ttf"
|
| 120 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
BASE_WORK_DIR = "temp_space_workspace"
|
| 122 |
TIKTOK_W, TIKTOK_H = 720, 1280
|
| 123 |
LANDSCAPE_W, LANDSCAPE_H = 1280, 720
|
|
@@ -128,24 +129,18 @@ TTS_GAP_SECONDS = 0.04
|
|
| 128 |
VOICE_FEMALE = "my-MM-NilarNeural"
|
| 129 |
VOICE_MALE = "my-MM-ThihaNeural"
|
| 130 |
|
| 131 |
-
SYSTEM_INSTRUCTION = """You are a professional movie recap writer and Burmese narrator.
|
| 132 |
-
Translate subtitle lines into natural, concise and engaging Burmese movie recap narration.
|
| 133 |
-
For each segment, detect whether the speaker is Male or Female.
|
| 134 |
-
Output ONLY a valid JSON array of objects with keys:
|
| 135 |
-
- "mm_text": Burmese translated text string
|
| 136 |
-
- "gender": "male" or "female" (use "female" as default for general narrator)
|
| 137 |
-
Ensure exact line count and order matching the input array."""
|
| 138 |
|
| 139 |
# Whisper Model ကို ပိုမိုပေါ့ပါးမြန်ဆန်သော base model သို့ပြောင်းရန်
|
| 140 |
whisper_model = WhisperModel(
|
| 141 |
-
"base",
|
| 142 |
device="cpu",
|
| 143 |
compute_type="int8",
|
| 144 |
-
cpu_threads=os.cpu_count() or 4,
|
| 145 |
)
|
| 146 |
-
|
| 147 |
ZERO_WIDTH_CHARS = {"\u200b", "\u200c", "\u200d", "\u2060", "\ufeff", "\u00ad"}
|
| 148 |
|
|
|
|
| 149 |
def clean_burmese_unicode(text):
|
| 150 |
if text is None:
|
| 151 |
return ""
|
|
@@ -162,6 +157,7 @@ def clean_burmese_unicode(text):
|
|
| 162 |
text = re.sub(r"[ \t]+", " ", text)
|
| 163 |
return re.sub(r"\n{3,}", "\n\n", text).strip()
|
| 164 |
|
|
|
|
| 165 |
def cleanup_workspace_folder():
|
| 166 |
cleaned_size = 0
|
| 167 |
if os.path.exists(BASE_WORK_DIR):
|
|
@@ -170,8 +166,7 @@ def cleanup_workspace_folder():
|
|
| 170 |
fp = os.path.join(root, f)
|
| 171 |
cleaned_size += os.path.getsize(fp)
|
| 172 |
shutil.rmtree(BASE_WORK_DIR, ignore_errors=True)
|
| 173 |
-
|
| 174 |
-
|
| 175 |
for file_name in os.listdir("."):
|
| 176 |
if file_name.startswith("recap_out_") and file_name.endswith(".mp4"):
|
| 177 |
try:
|
|
@@ -180,18 +175,17 @@ def cleanup_workspace_folder():
|
|
| 180 |
os.remove(fp)
|
| 181 |
except Exception:
|
| 182 |
pass
|
| 183 |
-
|
| 184 |
mb_freed = round(cleaned_size / (1024 * 1024), 2)
|
| 185 |
return f"🧹 Space Storage Cleaned! Freed up approx {mb_freed} MB."
|
| 186 |
|
|
|
|
| 187 |
def normalize_video_path(video_input):
|
| 188 |
if not video_input:
|
| 189 |
return None
|
| 190 |
if isinstance(video_input, str):
|
| 191 |
return video_input
|
| 192 |
-
return getattr(video_input, "path", None) or getattr(
|
| 193 |
-
|
| 194 |
-
)
|
| 195 |
|
| 196 |
def ffprobe_duration(path):
|
| 197 |
try:
|
|
@@ -214,6 +208,7 @@ def ffprobe_duration(path):
|
|
| 214 |
except Exception:
|
| 215 |
return 0.0
|
| 216 |
|
|
|
|
| 217 |
def ass_timestamp(seconds):
|
| 218 |
seconds = max(0.0, float(seconds))
|
| 219 |
h, r = divmod(seconds, 3600)
|
|
@@ -221,6 +216,7 @@ def ass_timestamp(seconds):
|
|
| 221 |
cs = int(round((s - int(s)) * 100))
|
| 222 |
return f"{int(h)}:{int(m):02d}:{int(s):02d}.{cs:02d}"
|
| 223 |
|
|
|
|
| 224 |
def escape_ass_text(text):
|
| 225 |
text = clean_burmese_unicode(text)
|
| 226 |
return (
|
|
@@ -230,6 +226,7 @@ def escape_ass_text(text):
|
|
| 230 |
.replace("\n", r"\N")
|
| 231 |
)
|
| 232 |
|
|
|
|
| 233 |
def translate_segments_batch_gemini(
|
| 234 |
segments,
|
| 235 |
user_api_key,
|
|
@@ -239,34 +236,48 @@ def translate_segments_batch_gemini(
|
|
| 239 |
if not user_api_key or not user_api_key.strip():
|
| 240 |
raise gr.Error("❌ Gemini API Key ထည့်သွင်းပေးရန် လိုအပ်ပါသည်။")
|
| 241 |
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 257 |
)
|
| 258 |
|
|
|
|
| 259 |
res_text = response.text.strip()
|
| 260 |
res_text = re.sub(r"^```(?:json)?\s*", "", res_text, flags=re.IGNORECASE)
|
| 261 |
res_text = re.sub(r"\s*```$", "", res_text)
|
| 262 |
-
|
| 263 |
translated_list = json.loads(res_text)
|
| 264 |
|
| 265 |
if isinstance(translated_list, list) and len(translated_list) == len(segments):
|
| 266 |
for i, seg in enumerate(segments):
|
| 267 |
item = translated_list[i]
|
| 268 |
if isinstance(item, dict):
|
| 269 |
-
seg["mm_text"] = clean_burmese_unicode(
|
|
|
|
|
|
|
| 270 |
seg["gender"] = item.get("gender", "female").lower()
|
| 271 |
else:
|
| 272 |
seg["mm_text"] = clean_burmese_unicode(str(item))
|
|
@@ -276,10 +287,11 @@ Input:
|
|
| 276 |
seg["mm_text"] = clean_burmese_unicode(seg["text"])
|
| 277 |
seg["gender"] = "female"
|
| 278 |
except Exception as e:
|
| 279 |
-
raise gr.Error(f"❌
|
| 280 |
|
| 281 |
return segments
|
| 282 |
|
|
|
|
| 283 |
def generate_voice_sync(text, voice_id, filename, desired_speed=1.15):
|
| 284 |
text = clean_burmese_unicode(text)
|
| 285 |
if not text:
|
|
@@ -287,12 +299,13 @@ def generate_voice_sync(text, voice_id, filename, desired_speed=1.15):
|
|
| 287 |
rate = f"+{int((desired_speed - 1.0) * 100)}%"
|
| 288 |
|
| 289 |
async def _gen():
|
| 290 |
-
|
| 291 |
-
|
|
|
|
| 292 |
|
| 293 |
try:
|
| 294 |
import asyncio
|
| 295 |
-
|
| 296 |
loop = asyncio.new_event_loop()
|
| 297 |
asyncio.set_event_loop(loop)
|
| 298 |
loop.run_until_complete(_gen())
|
|
@@ -301,6 +314,7 @@ def generate_voice_sync(text, voice_id, filename, desired_speed=1.15):
|
|
| 301 |
except Exception:
|
| 302 |
return False
|
| 303 |
|
|
|
|
| 304 |
def build_atempo_filter(factor):
|
| 305 |
factor = float(factor)
|
| 306 |
filters = []
|
|
@@ -310,6 +324,7 @@ def build_atempo_filter(factor):
|
|
| 310 |
filters.append(f"atempo={max(0.5, factor):.6f}")
|
| 311 |
return ",".join(filters)
|
| 312 |
|
|
|
|
| 313 |
def fit_audio_naturally(
|
| 314 |
input_audio, output_audio, start_time, max_end_time, desired_speed
|
| 315 |
):
|
|
@@ -341,6 +356,7 @@ def fit_audio_naturally(
|
|
| 341 |
subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
| 342 |
return True, ffprobe_duration(output_audio), speed_factor
|
| 343 |
|
|
|
|
| 344 |
def generate_single_tts_job(
|
| 345 |
index, text, voice_id, work_dir, start_time, max_end_time, desired_speed
|
| 346 |
):
|
|
@@ -359,6 +375,7 @@ def generate_single_tts_job(
|
|
| 359 |
"speed_factor": spd,
|
| 360 |
}
|
| 361 |
|
|
|
|
| 362 |
def build_synchronized_tts(segments, tts_results, work_dir, video_duration):
|
| 363 |
valid = []
|
| 364 |
for r in tts_results:
|
|
@@ -367,18 +384,18 @@ def build_synchronized_tts(segments, tts_results, work_dir, video_duration):
|
|
| 367 |
idx = r["index"]
|
| 368 |
seg = segments[idx]
|
| 369 |
start = max(0.0, float(seg["start"]))
|
| 370 |
-
valid.append(
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
|
|
|
|
|
|
| 376 |
valid.sort(key=lambda x: x["start"])
|
| 377 |
-
|
| 378 |
merged = os.path.join(work_dir, "tts_audio.m4a")
|
| 379 |
if not valid:
|
| 380 |
return None, []
|
| 381 |
-
|
| 382 |
inputs, filters, labels = [], [], []
|
| 383 |
for i, item in enumerate(valid):
|
| 384 |
inputs.extend(["-i", item["audio"]])
|
|
@@ -412,6 +429,7 @@ def build_synchronized_tts(segments, tts_results, work_dir, video_duration):
|
|
| 412 |
subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
| 413 |
return merged, valid
|
| 414 |
|
|
|
|
| 415 |
def create_ass_subtitle(
|
| 416 |
segments,
|
| 417 |
output_file,
|
|
@@ -427,17 +445,7 @@ def create_ass_subtitle(
|
|
| 427 |
|
| 428 |
font_size = 52 if target_h > target_w else 36
|
| 429 |
margin_v = int(target_h * (float(sub_pos_percent) / 100.0))
|
| 430 |
-
|
| 431 |
-
header = f"""[Script Info]
|
| 432 |
-
ScriptType: v4.00+
|
| 433 |
-
PlayResX: {target_w}
|
| 434 |
-
PlayResY: {target_h}
|
| 435 |
-
[V4+ Styles]
|
| 436 |
-
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
|
| 437 |
-
Style: Default,Arial,{font_size},{ass_color(text_color)},&H000000FF,{ass_color(stroke_color)},&H80000000,1,0,0,0,100,100,0,0,1,4,2,2,10,10,{margin_v},1
|
| 438 |
-
[Events]
|
| 439 |
-
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
|
| 440 |
-
"""
|
| 441 |
with open(output_file, "w", encoding="utf-8-sig") as f:
|
| 442 |
f.write(header)
|
| 443 |
for seg in segments:
|
|
@@ -445,6 +453,7 @@ Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
|
|
| 445 |
f"Dialogue: 0,{ass_timestamp(seg['start'])},{ass_timestamp(seg['start']+2.5)},Default,,0,0,0,,{escape_ass_text(seg.get('mm_text', seg['text']))}\n"
|
| 446 |
)
|
| 447 |
|
|
|
|
| 448 |
def process_magic_recap_video(
|
| 449 |
username,
|
| 450 |
video_path,
|
|
@@ -471,19 +480,15 @@ def process_magic_recap_video(
|
|
| 471 |
):
|
| 472 |
if not username:
|
| 473 |
raise gr.Error("❌ ကျေးဇူးပြု၍ Login အရင်ဝင်ပေးပါ။")
|
| 474 |
-
|
| 475 |
ok, msg = check_and_update_user_daily_credits(username)
|
| 476 |
if not ok:
|
| 477 |
raise gr.Error(msg)
|
| 478 |
-
|
| 479 |
video_path = normalize_video_path(video_path)
|
| 480 |
if not video_path or not os.path.exists(video_path):
|
| 481 |
raise gr.Error("❌ Valid Video File မတွေ့ပါ။")
|
| 482 |
-
|
| 483 |
dur = ffprobe_duration(video_path)
|
| 484 |
if dur <= 0:
|
| 485 |
raise gr.Error("❌ Video duration ဖတ်မရပါ။")
|
| 486 |
-
|
| 487 |
credit_ok, credit_msg = deduct_user_credits(username, dur)
|
| 488 |
if not credit_ok:
|
| 489 |
raise gr.Error(credit_msg)
|
|
@@ -491,8 +496,6 @@ def process_magic_recap_video(
|
|
| 491 |
job_id = time.strftime("%Y%m%d_%H%M%S") + "_" + uuid.uuid4().hex[:6]
|
| 492 |
work_dir = os.path.abspath(os.path.join(BASE_WORK_DIR, job_id))
|
| 493 |
os.makedirs(work_dir, exist_ok=True)
|
| 494 |
-
|
| 495 |
-
# OUTPUT VIDEO PATH ကို ကြိုတင် သတ်မှတ်ပေးပါ (Fix for "out_video is not defined")
|
| 496 |
out_video = os.path.abspath(f"recap_out_{job_id}.mp4")
|
| 497 |
|
| 498 |
try:
|
|
@@ -509,7 +512,6 @@ def process_magic_recap_video(
|
|
| 509 |
for s in segs_raw
|
| 510 |
if s.text
|
| 511 |
]
|
| 512 |
-
|
| 513 |
if not raw_segments:
|
| 514 |
raise gr.Error("❌ Video ထဲတွင် စကားပြောသံ မတွေ့ရပါ။")
|
| 515 |
|
|
@@ -528,7 +530,7 @@ def process_magic_recap_video(
|
|
| 528 |
)
|
| 529 |
|
| 530 |
progress(0.5, desc="🎙️ Multi-Voice Generating...")
|
| 531 |
-
|
| 532 |
def get_voice_for_segment(seg):
|
| 533 |
if "Only Female" in voice_mode:
|
| 534 |
return VOICE_FEMALE
|
|
@@ -557,7 +559,6 @@ def process_magic_recap_video(
|
|
| 557 |
merged_tts, timeline = build_synchronized_tts(
|
| 558 |
segments, tts_results, work_dir, dur
|
| 559 |
)
|
| 560 |
-
|
| 561 |
ass_file = os.path.abspath(os.path.join(work_dir, "sub.ass"))
|
| 562 |
create_ass_subtitle(
|
| 563 |
timeline,
|
|
@@ -571,22 +572,18 @@ def process_magic_recap_video(
|
|
| 571 |
|
| 572 |
# BUILD FFMPEG VIDEO FILTER PIPELINE
|
| 573 |
v_filters = []
|
| 574 |
-
|
| 575 |
if enable_sub_blur:
|
| 576 |
bx = f"iw*{blur_x_pct/100:.2f}"
|
| 577 |
by = f"ih*{blur_y_pct/100:.2f}"
|
| 578 |
bw = f"iw*{blur_w_pct/100:.2f}"
|
| 579 |
bh = f"ih*{blur_h_pct/100:.2f}"
|
| 580 |
v_filters.append(f"delogo=x={bx}:y={by}:w={bw}:h={bh}")
|
| 581 |
-
|
| 582 |
if mirror_flip:
|
| 583 |
v_filters.append("hflip")
|
| 584 |
-
|
| 585 |
if enable_zoom and zoom_level > 1.0:
|
| 586 |
v_filters.append(
|
| 587 |
f"crop=iw/{zoom_level}:ih/{zoom_level},scale={target_w}:{target_h}"
|
| 588 |
)
|
| 589 |
-
|
| 590 |
if filter_color == "Grayscale (အဖြူအမည်း)":
|
| 591 |
v_filters.append("hue=s=0")
|
| 592 |
elif filter_color == "Cinematic Dark":
|
|
@@ -595,7 +592,6 @@ def process_magic_recap_video(
|
|
| 595 |
v_filters.append("eq=contrast=1.1:saturation=1.3")
|
| 596 |
|
| 597 |
base_vf = ",".join(v_filters) if v_filters else "null"
|
| 598 |
-
|
| 599 |
ass_p = (
|
| 600 |
ass_file.replace("\\", "/")
|
| 601 |
.replace(":", r"\:")
|
|
@@ -616,15 +612,13 @@ def process_magic_recap_video(
|
|
| 616 |
f"pad={target_w}:{target_h}:(ow-iw)/2:(oh-ih)/2:black,ass='{ass_p}'[vfinal]"
|
| 617 |
)
|
| 618 |
|
| 619 |
-
# BUILD FFMPEG AUDIO FILTER PIPELINE (MUTED ORIGINAL AUDIO)
|
| 620 |
inputs = ["-i", video_path]
|
| 621 |
-
|
| 622 |
if merged_tts:
|
| 623 |
inputs.extend(["-i", merged_tts])
|
| 624 |
complex_af = "[1:a]volume=1.5[afinal]"
|
| 625 |
else:
|
| 626 |
complex_af = "[0:a]volume=0.0[afinal]"
|
| 627 |
-
|
| 628 |
cmd = [
|
| 629 |
"ffmpeg",
|
| 630 |
"-y",
|
|
@@ -645,104 +639,15 @@ def process_magic_recap_video(
|
|
| 645 |
str(dur),
|
| 646 |
out_video,
|
| 647 |
]
|
| 648 |
-
|
| 649 |
-
subprocess.run(
|
| 650 |
-
cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
|
| 651 |
-
)
|
| 652 |
return out_video, credit_msg
|
| 653 |
finally:
|
| 654 |
shutil.rmtree(work_dir, ignore_errors=True)
|
| 655 |
|
|
|
|
| 656 |
# CLEAN LIGHT & DARK HYBRID HIGH-CONTRAST CSS
|
| 657 |
-
CUSTOM_CSS = r"""
|
| 658 |
-
|
| 659 |
-
--bg-dark: #0f172a;
|
| 660 |
-
--card-bg: #ffffff;
|
| 661 |
-
--border-color: #cbd5e1;
|
| 662 |
-
--text-main: #0f172a;
|
| 663 |
-
--accent-purple: #5850ec;
|
| 664 |
-
--accent-purple-hover: #4338ca;
|
| 665 |
-
}
|
| 666 |
-
body, .gradio-container {
|
| 667 |
-
background-color: var(--bg-dark) !important;
|
| 668 |
-
}
|
| 669 |
-
/* Card များနှင့် Block များ အားလုံး၏ စာသားကို အနက်ရောင်/အပြာရင့်ရောင် သတ်မှတ်ခြင်း */
|
| 670 |
-
.ui-card,
|
| 671 |
-
div[data-testid="block"],
|
| 672 |
-
.gr-box,
|
| 673 |
-
.gr-form,
|
| 674 |
-
.accordion,
|
| 675 |
-
details,
|
| 676 |
-
.block {
|
| 677 |
-
background-color: #ffffff !important;
|
| 678 |
-
border: 1px solid var(--border-color) !important;
|
| 679 |
-
border-radius: 12px !important;
|
| 680 |
-
color: var(--text-main) !important;
|
| 681 |
-
}
|
| 682 |
-
/* Slider Title, Checkbox Label နှင့် Block Heading စာသားများ အားလုံးကို ထင်ရှားစွာ မြင်ရအောင် အနက်ရောင် ပြောင်းခြင်း */
|
| 683 |
-
label,
|
| 684 |
-
label span,
|
| 685 |
-
.block-title,
|
| 686 |
-
span.svelte-1f9ebfk,
|
| 687 |
-
.checkbox-label,
|
| 688 |
-
.checkbox label span,
|
| 689 |
-
div[data-testid="markdownbox"] p,
|
| 690 |
-
.accordion summary,
|
| 691 |
-
.accordion summary span,
|
| 692 |
-
details summary,
|
| 693 |
-
details summary span,
|
| 694 |
-
div[data-testid="checkbox"] span,
|
| 695 |
-
div[data-testid="checkbox"] label {
|
| 696 |
-
color: #0f172a !important;
|
| 697 |
-
font-weight: 700 !important;
|
| 698 |
-
font-size: 14px !important;
|
| 699 |
-
opacity: 1 !important;
|
| 700 |
-
}
|
| 701 |
-
/* Text Input, Dropdown နှင့် Slider Box များ၏ စာသားအရောင် */
|
| 702 |
-
input[type="text"],
|
| 703 |
-
input[type="password"],
|
| 704 |
-
input[type="number"],
|
| 705 |
-
textarea,
|
| 706 |
-
select,
|
| 707 |
-
.secondary,
|
| 708 |
-
.single-select,
|
| 709 |
-
.wrap-inner {
|
| 710 |
-
background-color: #f8fafc !important;
|
| 711 |
-
color: #0f172a !important;
|
| 712 |
-
border: 1px solid #94a3b8 !important;
|
| 713 |
-
border-radius: 8px !important;
|
| 714 |
-
font-weight: 600 !important;
|
| 715 |
-
}
|
| 716 |
-
/* Dropdown Options */
|
| 717 |
-
option {
|
| 718 |
-
background-color: #ffffff !important;
|
| 719 |
-
color: #0f172a !important;
|
| 720 |
-
}
|
| 721 |
-
/* Accordion Header ပြင်ဆင်ခြင်း */
|
| 722 |
-
.accordion summary:hover, details summary:hover {
|
| 723 |
-
background-color: #f1f5f9 !important;
|
| 724 |
-
}
|
| 725 |
-
/* Button စတိုင်များ */
|
| 726 |
-
button.primary {
|
| 727 |
-
background: var(--accent-purple) !important;
|
| 728 |
-
color: #ffffff !important;
|
| 729 |
-
font-weight: 700 !important;
|
| 730 |
-
border-radius: 10px !important;
|
| 731 |
-
border: none !important;
|
| 732 |
-
}
|
| 733 |
-
button.primary:hover {
|
| 734 |
-
background: var(--accent-purple-hover) !important;
|
| 735 |
-
}
|
| 736 |
-
/* Tab Navigation */
|
| 737 |
-
.tab-nav button {
|
| 738 |
-
color: #94a3b8 !important;
|
| 739 |
-
font-weight: 600 !important;
|
| 740 |
-
}
|
| 741 |
-
.tab-nav button.selected {
|
| 742 |
-
color: #38bdf8 !important;
|
| 743 |
-
border-bottom: 3px solid #38bdf8 !important;
|
| 744 |
-
}
|
| 745 |
-
"""
|
| 746 |
|
| 747 |
def create_main_app_interface():
|
| 748 |
with gr.Blocks(title="Movie Recap Studio") as app:
|
|
@@ -781,7 +686,6 @@ def create_main_app_interface():
|
|
| 781 |
video_input = gr.Video(
|
| 782 |
label="🎥 Input Video", sources=["upload"]
|
| 783 |
)
|
| 784 |
-
|
| 785 |
with gr.Column(elem_classes="ui-card"):
|
| 786 |
source_language = gr.Dropdown(
|
| 787 |
choices=[
|
|
@@ -799,16 +703,15 @@ def create_main_app_interface():
|
|
| 799 |
type="password",
|
| 800 |
placeholder="Enter your Gemini API Key",
|
| 801 |
)
|
| 802 |
-
|
| 803 |
with gr.Column(elem_classes="ui-card"):
|
| 804 |
voice_mode = gr.Dropdown(
|
| 805 |
choices=[
|
| 806 |
"🎭 Auto Multi-Voice (ကျား/မ အလိုအလျောက်ပြောင်းမည်)",
|
| 807 |
"🧕 Only Female Voice (မမအသံချည်းပဲထားမည်)",
|
| 808 |
-
"👨 Only Male Voice (သီဟအသံချည်းပဲထားမည်)"
|
| 809 |
],
|
| 810 |
value="🎭 Auto Multi-Voice (ကျား/မ အလိုအလျောက်ပြောင်းမည်)",
|
| 811 |
-
label="Burmese Voice Switching Mode"
|
| 812 |
)
|
| 813 |
tone_style = gr.Dropdown(
|
| 814 |
choices=[
|
|
@@ -827,7 +730,6 @@ def create_main_app_interface():
|
|
| 827 |
step=0.05,
|
| 828 |
label="Voice Speed",
|
| 829 |
)
|
| 830 |
-
|
| 831 |
with gr.Column(elem_classes="ui-card"):
|
| 832 |
ratio_select = gr.Dropdown(
|
| 833 |
choices=[
|
|
@@ -868,24 +770,41 @@ def create_main_app_interface():
|
|
| 868 |
step=0.1,
|
| 869 |
label="Zoom Level",
|
| 870 |
)
|
| 871 |
-
|
| 872 |
-
|
|
|
|
| 873 |
enable_sub_blur = gr.Checkbox(
|
| 874 |
-
label="Enable Subtitle Blur (မူလ စာတန်းကို Blur လုပ်မည်)",
|
|
|
|
| 875 |
)
|
| 876 |
blur_x_pct = gr.Slider(
|
| 877 |
-
minimum=0,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 878 |
)
|
| 879 |
blur_y_pct = gr.Slider(
|
| 880 |
-
minimum=0,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 881 |
)
|
| 882 |
blur_w_pct = gr.Slider(
|
| 883 |
-
minimum=5,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 884 |
)
|
| 885 |
blur_h_pct = gr.Slider(
|
| 886 |
-
minimum=2,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 887 |
)
|
| 888 |
-
|
| 889 |
with gr.Accordion("⚙️ Subtitle Settings", open=False):
|
| 890 |
text_color_input = gr.ColorPicker(
|
| 891 |
label="Subtitle Color", value="#FFFF00"
|
|
@@ -900,46 +819,44 @@ def create_main_app_interface():
|
|
| 900 |
step=1,
|
| 901 |
label="Subtitle Y Position (%)",
|
| 902 |
)
|
| 903 |
-
|
| 904 |
-
submit_btn = gr.Button(
|
| 905 |
-
"🚀 Generate Video", variant="primary"
|
| 906 |
-
)
|
| 907 |
output_status = gr.Markdown()
|
| 908 |
-
output_video = gr.Video(
|
|
|
|
|
|
|
| 909 |
|
| 910 |
# TAB 2: ADMIN CONTROL PANEL & STORAGE
|
| 911 |
-
with gr.TabItem(
|
|
|
|
|
|
|
| 912 |
gr.Markdown("### 👑 Admin Management & Storage Control")
|
| 913 |
-
|
| 914 |
with gr.Column(elem_classes="ui-card"):
|
| 915 |
gr.Markdown("#### 🧹 Space Storage Control")
|
| 916 |
-
clean_storage_btn = gr.Button(
|
| 917 |
-
|
| 918 |
-
|
| 919 |
-
gr.Markdown("#### 💳 User Credit Control")
|
| 920 |
-
user_list_df = gr.JSON(label="Current Database")
|
| 921 |
-
refresh_db_btn = gr.Button("🔄 Refresh User Data")
|
| 922 |
-
|
| 923 |
-
with gr.Row():
|
| 924 |
-
target_user = gr.Textbox(
|
| 925 |
-
label="Target Username", placeholder="Enter username"
|
| 926 |
-
)
|
| 927 |
-
credit_change = gr.Number(
|
| 928 |
-
label="Set / Add Credits", value=24
|
| 929 |
-
)
|
| 930 |
-
add_days = gr.Number(
|
| 931 |
-
label="Extend Expiration (Days)", value=30
|
| 932 |
)
|
| 933 |
-
|
| 934 |
-
|
| 935 |
-
|
| 936 |
-
|
| 937 |
-
)
|
| 938 |
-
|
| 939 |
-
|
| 940 |
-
|
| 941 |
-
|
| 942 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 943 |
|
| 944 |
# LOGIN HANDLER
|
| 945 |
def handle_login(u, p):
|
|
@@ -957,11 +874,9 @@ def create_main_app_interface():
|
|
| 957 |
"",
|
| 958 |
gr.update(visible=False),
|
| 959 |
)
|
| 960 |
-
|
| 961 |
db = load_user_db()
|
| 962 |
curr_user = db[u]
|
| 963 |
info_text = f"### 👤 Logged in as: **{u}** ({role.upper()})\n💳 **Credits:** `{curr_user['credits']}` | ⏳ **Expire:** `{curr_user['expire_at']}`"
|
| 964 |
-
|
| 965 |
return (
|
| 966 |
gr.update(visible=False),
|
| 967 |
gr.update(visible=True),
|
|
@@ -971,7 +886,6 @@ def create_main_app_interface():
|
|
| 971 |
info_text,
|
| 972 |
gr.update(visible=(role == "admin")),
|
| 973 |
)
|
| 974 |
-
|
| 975 |
return (
|
| 976 |
gr.update(visible=True),
|
| 977 |
gr.update(visible=False),
|
|
@@ -983,7 +897,13 @@ def create_main_app_interface():
|
|
| 983 |
)
|
| 984 |
|
| 985 |
def handle_logout():
|
| 986 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 987 |
|
| 988 |
def refresh_admin_db():
|
| 989 |
return load_user_db()
|
|
@@ -1023,6 +943,7 @@ def create_main_app_interface():
|
|
| 1023 |
admin_tab,
|
| 1024 |
],
|
| 1025 |
)
|
|
|
|
| 1026 |
logout_btn.click(
|
| 1027 |
fn=handle_logout,
|
| 1028 |
outputs=[
|
|
@@ -1120,7 +1041,9 @@ def create_main_app_interface():
|
|
| 1120 |
outputs=[output_video, output_status],
|
| 1121 |
)
|
| 1122 |
|
| 1123 |
-
clean_storage_btn.click(
|
|
|
|
|
|
|
| 1124 |
refresh_db_btn.click(fn=refresh_admin_db, outputs=[user_list_df])
|
| 1125 |
update_credit_btn.click(
|
| 1126 |
fn=update_user_credits,
|
|
@@ -1135,6 +1058,7 @@ def create_main_app_interface():
|
|
| 1135 |
|
| 1136 |
return app
|
| 1137 |
|
|
|
|
| 1138 |
if __name__ == "__main__":
|
| 1139 |
demo_app = create_main_app_interface()
|
| 1140 |
demo_app.queue(max_size=10)
|
|
|
|
| 9 |
from datetime import datetime, timedelta
|
| 10 |
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 11 |
|
| 12 |
+
import av # AV PATCH
|
|
|
|
|
|
|
| 13 |
_original_av_open = av.open
|
| 14 |
|
| 15 |
def _patched_av_open(*args, **kwargs):
|
|
|
|
| 26 |
# USER DATABASE & CREDIT SYSTEM
|
| 27 |
DB_FILE = "user_db.json"
|
| 28 |
|
| 29 |
+
|
| 30 |
def load_user_db():
|
| 31 |
if not os.path.exists(DB_FILE):
|
| 32 |
now = datetime.now()
|
|
|
|
| 58 |
except Exception:
|
| 59 |
return {}
|
| 60 |
|
| 61 |
+
|
| 62 |
def save_user_db(db):
|
| 63 |
with open(DB_FILE, "w", encoding="utf-8") as f:
|
| 64 |
json.dump(db, f, indent=4)
|
| 65 |
|
| 66 |
+
|
| 67 |
def check_and_update_user_daily_credits(username):
|
| 68 |
db = load_user_db()
|
| 69 |
if username not in db:
|
| 70 |
return False, "❌ User မတွေ့ပါ။"
|
|
|
|
| 71 |
user = db[username]
|
| 72 |
if user.get("role") == "admin":
|
| 73 |
return True, "Admin access granted."
|
|
|
|
| 74 |
now = datetime.now()
|
| 75 |
expire_at = datetime.strptime(user.get("expire_at"), "%Y-%m-%d %H:%M:%S")
|
| 76 |
if now > expire_at:
|
|
|
|
| 78 |
False,
|
| 79 |
f"❌ သင့် Account ၏ သက်တမ်း ကုန်ဆုံးသွားပါပြီ ({user.get('expire_at')} ထိသာ)။",
|
| 80 |
)
|
|
|
|
| 81 |
today_str = now.strftime("%Y-%m-%d")
|
| 82 |
if user.get("last_reset") != today_str:
|
| 83 |
user["credits"] = 24
|
| 84 |
user["last_reset"] = today_str
|
| 85 |
db[username] = user
|
| 86 |
save_user_db(db)
|
|
|
|
| 87 |
return True, "OK"
|
| 88 |
|
| 89 |
+
|
| 90 |
def deduct_user_credits(username, video_duration_seconds):
|
| 91 |
db = load_user_db()
|
| 92 |
if username not in db:
|
| 93 |
return False, "❌ User မတွေ့ပါ။"
|
|
|
|
| 94 |
user = db[username]
|
| 95 |
if user.get("role") == "admin":
|
| 96 |
return True, "Admin (Unlimited Credits)"
|
|
|
|
| 97 |
units = int((video_duration_seconds + 9.99) // 10)
|
| 98 |
required_credits = units * 2
|
|
|
|
| 99 |
if user["credits"] < required_credits:
|
| 100 |
return (
|
| 101 |
False,
|
| 102 |
f"❌ Credit မလုံလောက်ပါ။ လိုအပ်သည်: {required_credits} Credits, သင့်ထံတွင်ရှိသည်: {user['credits']} Credits",
|
| 103 |
)
|
|
|
|
| 104 |
user["credits"] -= required_credits
|
| 105 |
db[username] = user
|
| 106 |
save_user_db(db)
|
|
|
|
| 109 |
f"✅ {required_credits} Credits ဖြတ်တောက်ပြီးပါပြီ။ (ကျန်ရှိ Credit: {user['credits']})",
|
| 110 |
)
|
| 111 |
|
| 112 |
+
|
| 113 |
# CONFIG
|
| 114 |
FONT_FILE = "Myanmarfont.ttf"
|
| 115 |
+
# Primary model and backup fallback models list
|
| 116 |
+
GEMINI_MODELS = [
|
| 117 |
+
"gemini-2.5-flash",
|
| 118 |
+
"gemini-3.8-flash",
|
| 119 |
+
"gemini-3.6-flash",
|
| 120 |
+
"gemini-3.1-flash-lite",
|
| 121 |
+
]
|
| 122 |
BASE_WORK_DIR = "temp_space_workspace"
|
| 123 |
TIKTOK_W, TIKTOK_H = 720, 1280
|
| 124 |
LANDSCAPE_W, LANDSCAPE_H = 1280, 720
|
|
|
|
| 129 |
VOICE_FEMALE = "my-MM-NilarNeural"
|
| 130 |
VOICE_MALE = "my-MM-ThihaNeural"
|
| 131 |
|
| 132 |
+
SYSTEM_INSTRUCTION = """You are a professional movie recap writer and Burmese narrator.Translate subtitle lines into natural, concise and engaging Burmese movie recap narration.For each segment, detect whether the speaker is Male or Female.Output ONLY a valid JSON array of objects with keys:- "mm_text": Burmese translated text string- "gender": "male" or "female" (use "female" as default for general narrator)Ensure exact line count and order matching the input array."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
|
| 134 |
# Whisper Model ကို ပိုမိုပေါ့ပါးမြန်ဆန်သော base model သို့ပြောင်းရန်
|
| 135 |
whisper_model = WhisperModel(
|
| 136 |
+
"base",
|
| 137 |
device="cpu",
|
| 138 |
compute_type="int8",
|
| 139 |
+
cpu_threads=os.cpu_count() or 4,
|
| 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 ""
|
|
|
|
| 157 |
text = re.sub(r"[ \t]+", " ", text)
|
| 158 |
return re.sub(r"\n{3,}", "\n\n", text).strip()
|
| 159 |
|
| 160 |
+
|
| 161 |
def cleanup_workspace_folder():
|
| 162 |
cleaned_size = 0
|
| 163 |
if os.path.exists(BASE_WORK_DIR):
|
|
|
|
| 166 |
fp = os.path.join(root, f)
|
| 167 |
cleaned_size += os.path.getsize(fp)
|
| 168 |
shutil.rmtree(BASE_WORK_DIR, ignore_errors=True)
|
| 169 |
+
os.makedirs(BASE_WORK_DIR, exist_ok=True)
|
|
|
|
| 170 |
for file_name in os.listdir("."):
|
| 171 |
if file_name.startswith("recap_out_") and file_name.endswith(".mp4"):
|
| 172 |
try:
|
|
|
|
| 175 |
os.remove(fp)
|
| 176 |
except Exception:
|
| 177 |
pass
|
|
|
|
| 178 |
mb_freed = round(cleaned_size / (1024 * 1024), 2)
|
| 179 |
return f"🧹 Space Storage Cleaned! Freed up approx {mb_freed} MB."
|
| 180 |
|
| 181 |
+
|
| 182 |
def normalize_video_path(video_input):
|
| 183 |
if not video_input:
|
| 184 |
return None
|
| 185 |
if isinstance(video_input, str):
|
| 186 |
return video_input
|
| 187 |
+
return getattr(video_input, "path", None) or getattr(video_input, "name", None)
|
| 188 |
+
|
|
|
|
| 189 |
|
| 190 |
def ffprobe_duration(path):
|
| 191 |
try:
|
|
|
|
| 208 |
except Exception:
|
| 209 |
return 0.0
|
| 210 |
|
| 211 |
+
|
| 212 |
def ass_timestamp(seconds):
|
| 213 |
seconds = max(0.0, float(seconds))
|
| 214 |
h, r = divmod(seconds, 3600)
|
|
|
|
| 216 |
cs = int(round((s - int(s)) * 100))
|
| 217 |
return f"{int(h)}:{int(m):02d}:{int(s):02d}.{cs:02d}"
|
| 218 |
|
| 219 |
+
|
| 220 |
def escape_ass_text(text):
|
| 221 |
text = clean_burmese_unicode(text)
|
| 222 |
return (
|
|
|
|
| 226 |
.replace("\n", r"\N")
|
| 227 |
)
|
| 228 |
|
| 229 |
+
|
| 230 |
def translate_segments_batch_gemini(
|
| 231 |
segments,
|
| 232 |
user_api_key,
|
|
|
|
| 236 |
if not user_api_key or not user_api_key.strip():
|
| 237 |
raise gr.Error("❌ Gemini API Key ထည့်သွင်းပေးရန် လိုအပ်ပါသည်။")
|
| 238 |
|
| 239 |
+
client = genai.Client(api_key=user_api_key.strip())
|
| 240 |
+
input_texts = [seg["text"] for seg in segments]
|
| 241 |
+
prompt = f"""Target Tone/Style: {tone_style}Source Language Code: {source_lang}Translate the following list of sentences into natural Burmese movie recap style narration.Detect speaker gender (male/female) for each line.Input:{json.dumps(input_texts, ensure_ascii=False)}"""
|
| 242 |
+
|
| 243 |
+
response = None
|
| 244 |
+
last_exception = None
|
| 245 |
+
|
| 246 |
+
# Iterating over the candidate Gemini models for fallback resilience
|
| 247 |
+
for model_name in GEMINI_MODELS:
|
| 248 |
+
try:
|
| 249 |
+
print(f"🔄 Trying Gemini Model: {model_name}...")
|
| 250 |
+
response = client.models.generate_content(
|
| 251 |
+
model=model_name,
|
| 252 |
+
contents=prompt,
|
| 253 |
+
config={"system_instruction": SYSTEM_INSTRUCTION},
|
| 254 |
+
)
|
| 255 |
+
if response and response.text:
|
| 256 |
+
print(f"✅ Successfully generated content with: {model_name}")
|
| 257 |
+
break
|
| 258 |
+
except Exception as e:
|
| 259 |
+
print(f"⚠️ Failed with model {model_name}: {str(e)}")
|
| 260 |
+
last_exception = e
|
| 261 |
+
continue
|
| 262 |
+
|
| 263 |
+
if not response or not response.text:
|
| 264 |
+
raise gr.Error(
|
| 265 |
+
f"❌ Gemini API Translation Error (All models failed): {str(last_exception)}"
|
| 266 |
)
|
| 267 |
|
| 268 |
+
try:
|
| 269 |
res_text = response.text.strip()
|
| 270 |
res_text = re.sub(r"^```(?:json)?\s*", "", res_text, flags=re.IGNORECASE)
|
| 271 |
res_text = re.sub(r"\s*```$", "", res_text)
|
|
|
|
| 272 |
translated_list = json.loads(res_text)
|
| 273 |
|
| 274 |
if isinstance(translated_list, list) and len(translated_list) == len(segments):
|
| 275 |
for i, seg in enumerate(segments):
|
| 276 |
item = translated_list[i]
|
| 277 |
if isinstance(item, dict):
|
| 278 |
+
seg["mm_text"] = clean_burmese_unicode(
|
| 279 |
+
item.get("mm_text", seg["text"])
|
| 280 |
+
)
|
| 281 |
seg["gender"] = item.get("gender", "female").lower()
|
| 282 |
else:
|
| 283 |
seg["mm_text"] = clean_burmese_unicode(str(item))
|
|
|
|
| 287 |
seg["mm_text"] = clean_burmese_unicode(seg["text"])
|
| 288 |
seg["gender"] = "female"
|
| 289 |
except Exception as e:
|
| 290 |
+
raise gr.Error(f"❌ Subtitle Parsing Error: {str(e)}")
|
| 291 |
|
| 292 |
return segments
|
| 293 |
|
| 294 |
+
|
| 295 |
def generate_voice_sync(text, voice_id, filename, desired_speed=1.15):
|
| 296 |
text = clean_burmese_unicode(text)
|
| 297 |
if not text:
|
|
|
|
| 299 |
rate = f"+{int((desired_speed - 1.0) * 100)}%"
|
| 300 |
|
| 301 |
async def _gen():
|
| 302 |
+
await edge_tts.Communicate(text, voice_id, rate=rate, volume="+50%").save(
|
| 303 |
+
filename
|
| 304 |
+
)
|
| 305 |
|
| 306 |
try:
|
| 307 |
import asyncio
|
| 308 |
+
|
| 309 |
loop = asyncio.new_event_loop()
|
| 310 |
asyncio.set_event_loop(loop)
|
| 311 |
loop.run_until_complete(_gen())
|
|
|
|
| 314 |
except Exception:
|
| 315 |
return False
|
| 316 |
|
| 317 |
+
|
| 318 |
def build_atempo_filter(factor):
|
| 319 |
factor = float(factor)
|
| 320 |
filters = []
|
|
|
|
| 324 |
filters.append(f"atempo={max(0.5, factor):.6f}")
|
| 325 |
return ",".join(filters)
|
| 326 |
|
| 327 |
+
|
| 328 |
def fit_audio_naturally(
|
| 329 |
input_audio, output_audio, start_time, max_end_time, desired_speed
|
| 330 |
):
|
|
|
|
| 356 |
subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
| 357 |
return True, ffprobe_duration(output_audio), speed_factor
|
| 358 |
|
| 359 |
+
|
| 360 |
def generate_single_tts_job(
|
| 361 |
index, text, voice_id, work_dir, start_time, max_end_time, desired_speed
|
| 362 |
):
|
|
|
|
| 375 |
"speed_factor": spd,
|
| 376 |
}
|
| 377 |
|
| 378 |
+
|
| 379 |
def build_synchronized_tts(segments, tts_results, work_dir, video_duration):
|
| 380 |
valid = []
|
| 381 |
for r in tts_results:
|
|
|
|
| 384 |
idx = r["index"]
|
| 385 |
seg = segments[idx]
|
| 386 |
start = max(0.0, float(seg["start"]))
|
| 387 |
+
valid.append(
|
| 388 |
+
{
|
| 389 |
+
"index": idx,
|
| 390 |
+
"start": start,
|
| 391 |
+
"text": seg.get("mm_text", ""),
|
| 392 |
+
"audio": r["audio"],
|
| 393 |
+
}
|
| 394 |
+
)
|
| 395 |
valid.sort(key=lambda x: x["start"])
|
|
|
|
| 396 |
merged = os.path.join(work_dir, "tts_audio.m4a")
|
| 397 |
if not valid:
|
| 398 |
return None, []
|
|
|
|
| 399 |
inputs, filters, labels = [], [], []
|
| 400 |
for i, item in enumerate(valid):
|
| 401 |
inputs.extend(["-i", item["audio"]])
|
|
|
|
| 429 |
subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
| 430 |
return merged, valid
|
| 431 |
|
| 432 |
+
|
| 433 |
def create_ass_subtitle(
|
| 434 |
segments,
|
| 435 |
output_file,
|
|
|
|
| 445 |
|
| 446 |
font_size = 52 if target_h > target_w else 36
|
| 447 |
margin_v = int(target_h * (float(sub_pos_percent) / 100.0))
|
| 448 |
+
header = f"""[Script Info]ScriptType: v4.00+PlayResX: {target_w}PlayResY: {target_h}[V4+ Styles]Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, EncodingStyle: Default,Arial,{font_size},{ass_color(text_color)},&H000000FF,{ass_color(stroke_color)},&H80000000,1,0,0,0,100,100,0,0,1,4,2,2,10,10,{margin_v},1[Events]Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 449 |
with open(output_file, "w", encoding="utf-8-sig") as f:
|
| 450 |
f.write(header)
|
| 451 |
for seg in segments:
|
|
|
|
| 453 |
f"Dialogue: 0,{ass_timestamp(seg['start'])},{ass_timestamp(seg['start']+2.5)},Default,,0,0,0,,{escape_ass_text(seg.get('mm_text', seg['text']))}\n"
|
| 454 |
)
|
| 455 |
|
| 456 |
+
|
| 457 |
def process_magic_recap_video(
|
| 458 |
username,
|
| 459 |
video_path,
|
|
|
|
| 480 |
):
|
| 481 |
if not username:
|
| 482 |
raise gr.Error("❌ ကျေးဇူးပြု၍ Login အရင်ဝင်ပေးပါ။")
|
|
|
|
| 483 |
ok, msg = check_and_update_user_daily_credits(username)
|
| 484 |
if not ok:
|
| 485 |
raise gr.Error(msg)
|
|
|
|
| 486 |
video_path = normalize_video_path(video_path)
|
| 487 |
if not video_path or not os.path.exists(video_path):
|
| 488 |
raise gr.Error("❌ Valid Video File မတွေ့ပါ။")
|
|
|
|
| 489 |
dur = ffprobe_duration(video_path)
|
| 490 |
if dur <= 0:
|
| 491 |
raise gr.Error("❌ Video duration ဖတ်မရပါ။")
|
|
|
|
| 492 |
credit_ok, credit_msg = deduct_user_credits(username, dur)
|
| 493 |
if not credit_ok:
|
| 494 |
raise gr.Error(credit_msg)
|
|
|
|
| 496 |
job_id = time.strftime("%Y%m%d_%H%M%S") + "_" + uuid.uuid4().hex[:6]
|
| 497 |
work_dir = os.path.abspath(os.path.join(BASE_WORK_DIR, job_id))
|
| 498 |
os.makedirs(work_dir, exist_ok=True)
|
|
|
|
|
|
|
| 499 |
out_video = os.path.abspath(f"recap_out_{job_id}.mp4")
|
| 500 |
|
| 501 |
try:
|
|
|
|
| 512 |
for s in segs_raw
|
| 513 |
if s.text
|
| 514 |
]
|
|
|
|
| 515 |
if not raw_segments:
|
| 516 |
raise gr.Error("❌ Video ထဲတွင် စကားပြောသံ မတွေ့ရပါ။")
|
| 517 |
|
|
|
|
| 530 |
)
|
| 531 |
|
| 532 |
progress(0.5, desc="🎙️ Multi-Voice Generating...")
|
| 533 |
+
|
| 534 |
def get_voice_for_segment(seg):
|
| 535 |
if "Only Female" in voice_mode:
|
| 536 |
return VOICE_FEMALE
|
|
|
|
| 559 |
merged_tts, timeline = build_synchronized_tts(
|
| 560 |
segments, tts_results, work_dir, dur
|
| 561 |
)
|
|
|
|
| 562 |
ass_file = os.path.abspath(os.path.join(work_dir, "sub.ass"))
|
| 563 |
create_ass_subtitle(
|
| 564 |
timeline,
|
|
|
|
| 572 |
|
| 573 |
# BUILD FFMPEG VIDEO FILTER PIPELINE
|
| 574 |
v_filters = []
|
|
|
|
| 575 |
if enable_sub_blur:
|
| 576 |
bx = f"iw*{blur_x_pct/100:.2f}"
|
| 577 |
by = f"ih*{blur_y_pct/100:.2f}"
|
| 578 |
bw = f"iw*{blur_w_pct/100:.2f}"
|
| 579 |
bh = f"ih*{blur_h_pct/100:.2f}"
|
| 580 |
v_filters.append(f"delogo=x={bx}:y={by}:w={bw}:h={bh}")
|
|
|
|
| 581 |
if mirror_flip:
|
| 582 |
v_filters.append("hflip")
|
|
|
|
| 583 |
if enable_zoom and zoom_level > 1.0:
|
| 584 |
v_filters.append(
|
| 585 |
f"crop=iw/{zoom_level}:ih/{zoom_level},scale={target_w}:{target_h}"
|
| 586 |
)
|
|
|
|
| 587 |
if filter_color == "Grayscale (အဖြူအမည်း)":
|
| 588 |
v_filters.append("hue=s=0")
|
| 589 |
elif filter_color == "Cinematic Dark":
|
|
|
|
| 592 |
v_filters.append("eq=contrast=1.1:saturation=1.3")
|
| 593 |
|
| 594 |
base_vf = ",".join(v_filters) if v_filters else "null"
|
|
|
|
| 595 |
ass_p = (
|
| 596 |
ass_file.replace("\\", "/")
|
| 597 |
.replace(":", r"\:")
|
|
|
|
| 612 |
f"pad={target_w}:{target_h}:(ow-iw)/2:(oh-ih)/2:black,ass='{ass_p}'[vfinal]"
|
| 613 |
)
|
| 614 |
|
|
|
|
| 615 |
inputs = ["-i", video_path]
|
|
|
|
| 616 |
if merged_tts:
|
| 617 |
inputs.extend(["-i", merged_tts])
|
| 618 |
complex_af = "[1:a]volume=1.5[afinal]"
|
| 619 |
else:
|
| 620 |
complex_af = "[0:a]volume=0.0[afinal]"
|
| 621 |
+
|
| 622 |
cmd = [
|
| 623 |
"ffmpeg",
|
| 624 |
"-y",
|
|
|
|
| 639 |
str(dur),
|
| 640 |
out_video,
|
| 641 |
]
|
| 642 |
+
subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
|
|
|
|
|
|
|
|
| 643 |
return out_video, credit_msg
|
| 644 |
finally:
|
| 645 |
shutil.rmtree(work_dir, ignore_errors=True)
|
| 646 |
|
| 647 |
+
|
| 648 |
# CLEAN LIGHT & DARK HYBRID HIGH-CONTRAST CSS
|
| 649 |
+
CUSTOM_CSS = r""":root { --bg-dark: #0f172a; --card-bg: #ffffff; --border-color: #cbd5e1; --text-main: #0f172a; --accent-purple: #5850ec; --accent-purple-hover: #4338ca;}body, .gradio-container { background-color: var(--bg-dark) !important;}.ui-card, div[data-testid="block"], .gr-box, .gr-form,.accordion,details,.block { background-color: #ffffff !important; border: 1px solid var(--border-color) !important; border-radius: 12px !important; color: var(--text-main) !important;}label, label span, .block-title, span.svelte-1f9ebfk,.checkbox-label,.checkbox label span,div[data-testid="markdownbox"] p,.accordion summary,.accordion summary span,details summary,details summary span,div[data-testid="checkbox"] span,div[data-testid="checkbox"] label { color: #0f172a !important; font-weight: 700 !important; font-size: 14px !important; opacity: 1 !important;}input[type="text"], input[type="password"], input[type="number"],textarea, select, .secondary,.single-select,.wrap-inner { background-color: #f8fafc !important; color: #0f172a !important; border: 1px solid #94a3b8 !important; border-radius: 8px !important; font-weight: 600 !important;}option { background-color: #ffffff !important; color: #0f172a !important;}.accordion summary:hover, details summary:hover { background-color: #f1f5f9 !important;}button.primary { background: var(--accent-purple) !important; color: #ffffff !important; font-weight: 700 !important; border-radius: 10px !important; border: none !important;}button.primary:hover { background: var(--accent-purple-hover) !important;}.tab-nav button { color: #94a3b8 !important; font-weight: 600 !important;}.tab-nav button.selected { color: #38bdf8 !important; border-bottom: 3px solid #38bdf8 !important;}"""
|
| 650 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 651 |
|
| 652 |
def create_main_app_interface():
|
| 653 |
with gr.Blocks(title="Movie Recap Studio") as app:
|
|
|
|
| 686 |
video_input = gr.Video(
|
| 687 |
label="🎥 Input Video", sources=["upload"]
|
| 688 |
)
|
|
|
|
| 689 |
with gr.Column(elem_classes="ui-card"):
|
| 690 |
source_language = gr.Dropdown(
|
| 691 |
choices=[
|
|
|
|
| 703 |
type="password",
|
| 704 |
placeholder="Enter your Gemini API Key",
|
| 705 |
)
|
|
|
|
| 706 |
with gr.Column(elem_classes="ui-card"):
|
| 707 |
voice_mode = gr.Dropdown(
|
| 708 |
choices=[
|
| 709 |
"🎭 Auto Multi-Voice (ကျား/မ အလိုအလျောက်ပြောင်းမည်)",
|
| 710 |
"🧕 Only Female Voice (မမအသံချည်းပဲထားမည်)",
|
| 711 |
+
"👨 Only Male Voice (သီဟအသံချည်းပဲထားမည်)",
|
| 712 |
],
|
| 713 |
value="🎭 Auto Multi-Voice (ကျား/မ အလိုအလျောက်ပြောင်းမည်)",
|
| 714 |
+
label="Burmese Voice Switching Mode",
|
| 715 |
)
|
| 716 |
tone_style = gr.Dropdown(
|
| 717 |
choices=[
|
|
|
|
| 730 |
step=0.05,
|
| 731 |
label="Voice Speed",
|
| 732 |
)
|
|
|
|
| 733 |
with gr.Column(elem_classes="ui-card"):
|
| 734 |
ratio_select = gr.Dropdown(
|
| 735 |
choices=[
|
|
|
|
| 770 |
step=0.1,
|
| 771 |
label="Zoom Level",
|
| 772 |
)
|
| 773 |
+
with gr.Accordion(
|
| 774 |
+
"🌫 Subtitle Blur Settings (မူလစာတန်း ဝါးဖျောက်ရန်)", open=False
|
| 775 |
+
):
|
| 776 |
enable_sub_blur = gr.Checkbox(
|
| 777 |
+
label="Enable Subtitle Blur (မူလ စာတန်းကို Blur လုပ်မည်)",
|
| 778 |
+
value=False,
|
| 779 |
)
|
| 780 |
blur_x_pct = gr.Slider(
|
| 781 |
+
minimum=0,
|
| 782 |
+
maximum=100,
|
| 783 |
+
value=10,
|
| 784 |
+
step=1,
|
| 785 |
+
label="Blur Box Start X Position (%)",
|
| 786 |
)
|
| 787 |
blur_y_pct = gr.Slider(
|
| 788 |
+
minimum=0,
|
| 789 |
+
maximum=100,
|
| 790 |
+
value=75,
|
| 791 |
+
step=1,
|
| 792 |
+
label="Blur Box Start Y Position (%)",
|
| 793 |
)
|
| 794 |
blur_w_pct = gr.Slider(
|
| 795 |
+
minimum=5,
|
| 796 |
+
maximum=100,
|
| 797 |
+
value=80,
|
| 798 |
+
step=1,
|
| 799 |
+
label="Blur Box Width (%)",
|
| 800 |
)
|
| 801 |
blur_h_pct = gr.Slider(
|
| 802 |
+
minimum=2,
|
| 803 |
+
maximum=50,
|
| 804 |
+
value=15,
|
| 805 |
+
step=1,
|
| 806 |
+
label="Blur Box Height (%)",
|
| 807 |
)
|
|
|
|
| 808 |
with gr.Accordion("⚙️ Subtitle Settings", open=False):
|
| 809 |
text_color_input = gr.ColorPicker(
|
| 810 |
label="Subtitle Color", value="#FFFF00"
|
|
|
|
| 819 |
step=1,
|
| 820 |
label="Subtitle Y Position (%)",
|
| 821 |
)
|
| 822 |
+
submit_btn = gr.Button("🚀 Generate Video", variant="primary")
|
|
|
|
|
|
|
|
|
|
| 823 |
output_status = gr.Markdown()
|
| 824 |
+
output_video = gr.Video(
|
| 825 |
+
label="🎬 Output Video Preview", interactive=False
|
| 826 |
+
)
|
| 827 |
|
| 828 |
# TAB 2: ADMIN CONTROL PANEL & STORAGE
|
| 829 |
+
with gr.TabItem(
|
| 830 |
+
"⚙️ Admin & Storage Panel", visible=False
|
| 831 |
+
) as admin_tab:
|
| 832 |
gr.Markdown("### 👑 Admin Management & Storage Control")
|
|
|
|
| 833 |
with gr.Column(elem_classes="ui-card"):
|
| 834 |
gr.Markdown("#### 🧹 Space Storage Control")
|
| 835 |
+
clean_storage_btn = gr.Button(
|
| 836 |
+
"🧹 Clear Workspace Storage", variant="stop"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 837 |
)
|
| 838 |
+
storage_status = gr.Markdown()
|
| 839 |
+
gr.Markdown("#### 💳 User Credit Control")
|
| 840 |
+
user_list_df = gr.JSON(label="Current Database")
|
| 841 |
+
refresh_db_btn = gr.Button("🔄 Refresh User Data")
|
| 842 |
+
with gr.Row():
|
| 843 |
+
target_user = gr.Textbox(
|
| 844 |
+
label="Target Username", placeholder="Enter username"
|
| 845 |
+
)
|
| 846 |
+
credit_change = gr.Number(
|
| 847 |
+
label="Set / Add Credits", value=24
|
| 848 |
+
)
|
| 849 |
+
add_days = gr.Number(
|
| 850 |
+
label="Extend Expiration (Days)", value=30
|
| 851 |
+
)
|
| 852 |
+
with gr.Row():
|
| 853 |
+
update_credit_btn = gr.Button(
|
| 854 |
+
"Update Credits", variant="primary"
|
| 855 |
+
)
|
| 856 |
+
extend_expire_btn = gr.Button(
|
| 857 |
+
"Extend Expiration", variant="primary"
|
| 858 |
+
)
|
| 859 |
+
admin_action_status = gr.Markdown()
|
| 860 |
|
| 861 |
# LOGIN HANDLER
|
| 862 |
def handle_login(u, p):
|
|
|
|
| 874 |
"",
|
| 875 |
gr.update(visible=False),
|
| 876 |
)
|
|
|
|
| 877 |
db = load_user_db()
|
| 878 |
curr_user = db[u]
|
| 879 |
info_text = f"### 👤 Logged in as: **{u}** ({role.upper()})\n💳 **Credits:** `{curr_user['credits']}` | ⏳ **Expire:** `{curr_user['expire_at']}`"
|
|
|
|
| 880 |
return (
|
| 881 |
gr.update(visible=False),
|
| 882 |
gr.update(visible=True),
|
|
|
|
| 886 |
info_text,
|
| 887 |
gr.update(visible=(role == "admin")),
|
| 888 |
)
|
|
|
|
| 889 |
return (
|
| 890 |
gr.update(visible=True),
|
| 891 |
gr.update(visible=False),
|
|
|
|
| 897 |
)
|
| 898 |
|
| 899 |
def handle_logout():
|
| 900 |
+
return (
|
| 901 |
+
gr.update(visible=True),
|
| 902 |
+
gr.update(visible=False),
|
| 903 |
+
"",
|
| 904 |
+
None,
|
| 905 |
+
None,
|
| 906 |
+
)
|
| 907 |
|
| 908 |
def refresh_admin_db():
|
| 909 |
return load_user_db()
|
|
|
|
| 943 |
admin_tab,
|
| 944 |
],
|
| 945 |
)
|
| 946 |
+
|
| 947 |
logout_btn.click(
|
| 948 |
fn=handle_logout,
|
| 949 |
outputs=[
|
|
|
|
| 1041 |
outputs=[output_video, output_status],
|
| 1042 |
)
|
| 1043 |
|
| 1044 |
+
clean_storage_btn.click(
|
| 1045 |
+
fn=cleanup_workspace_folder, outputs=[storage_status]
|
| 1046 |
+
)
|
| 1047 |
refresh_db_btn.click(fn=refresh_admin_db, outputs=[user_list_df])
|
| 1048 |
update_credit_btn.click(
|
| 1049 |
fn=update_user_credits,
|
|
|
|
| 1058 |
|
| 1059 |
return app
|
| 1060 |
|
| 1061 |
+
|
| 1062 |
if __name__ == "__main__":
|
| 1063 |
demo_app = create_main_app_interface()
|
| 1064 |
demo_app.queue(max_size=10)
|