Update app.py
Browse files1234567819 unmodified lines282930313233343536373839401 unmodified line4243444546474811 unmodified lines606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181198 unmodified lines12812913013113213337 unmodified lines1711721731741751761772 unmodified lines180181182183184185186240 unmodified lines42742842943043143243343443543643743843944043 unmodified lines48448548648748848949049149249349449549649749849950050150250350450522 unmodified lines52852953053153253353461 unmodified lines5965975985996006016026036046056061 unmodified line60860961061161261361461561661761861962062162262362462562662762862963015 unmodified lines64664764864965065165265365465512 unmodified lines6686696706716726736746756764 unmodified lines68168268368468568668768868910 unmodified lines700701702703704705706707708709710200 unmodified lines91191291391491591691727 unmodified lines9459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779788 unmodified lines9879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015123 unmodified lines1139114011411142import jsonimport osimport reimport shutilimport subprocessimport timeimport unicodedataimport uuid19 unmodified lines# USER DATABASE & CREDIT SYSTEMDB_FILE = "user_db.json"def load_user_db():if not os.path.exists(DB_FILE):now = datetime.now()expire_date = (now + timedelta(days=60)).strftime("%Y-%m-%d %H:%M:%S")initial_db = {"User1": {"password": "123456","role": "user","credits": 24,"last_reset": now.strftime("%Y-%m-%d"),1 unmodified line"expire_at": expire_date,},"admin": {"password": "241212","role": "admin","credits": 999999,"last_reset": now.strftime("%Y-%m-%d"),11 unmodified linesreturn {}def save_user_db(db):with open(DB_FILE, "w", encoding="utf-8") as f:json.dump(db, f, indent=4)def check_and_update_user_daily_credits(username):db = load_user_db()if username not in db:return False, "❌ User မတွေ့ပါ။"user = db[username]if user.get("role") == "admin":return True, "Admin access granted."now = datetime.now()expire_at = datetime.strptime(user.get("expire_at"), "%Y-%m-%d %H:%M:%S")if now > expire_at:return (False,f"❌ သင့် Account ၏ သက်တမ်း ကုန်ဆုံးသွားပါပြီ ({user.get('expire_at')} ထိသာ)။",)today_str = now.strftime("%Y-%m-%d")if user.get("last_reset") != today_str:user["credits"] = 24user["last_reset"] = today_strdb[username] = usersave_user_db(db)return True, "OK"def deduct_user_credits(username, video_duration_seconds):db = load_user_db()if username not in db:return False, "❌ User မတွေ့ပါ။"user = db[username]if user.get("role") == "admin":return True, "Admin (Unlimited Credits)"units = int((video_duration_seconds + 9.99) // 10)required_credits = units * 2if user["credits"] < required_credits:return (False,f"❌ Credit မလုံလောက်ပါ။ လိုအပ်သည်: {required_credits} Credits, သင့်ထံတွင်ရှိသည်: {user['credits']} Credits",)user["credits"] -= required_creditsdb[username] = usersave_user_db(db)return (True,f"✅ {required_credits} Credits ဖြတ်တောက်ပြီးပါပြီ။ (ကျန်ရှိ Credit: {user['credits']})",)# CONFIGFONT_FILE = "Myanmarfont.ttf"8 unmodified linesVOICE_FEMALE = "my-MM-NilarNeural"VOICE_MALE = "my-MM-ThihaNeural"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.37 unmodified linescleaned_size += os.path.getsize(fp)shutil.rmtree(BASE_WORK_DIR, ignore_errors=True)os.makedirs(BASE_WORK_DIR, exist_ok=True)for file_name in os.listdir("."):if file_name.startswith("recap_out_") and file_name.endswith(".mp4"):try:2 unmodified linesos.remove(fp)except Exception:passmb_freed = round(cleaned_size / (1024 * 1024), 2)return f"🧹 Space Storage Cleaned! Freed up approx {mb_freed} MB."240 unmodified linesfont_size = 52 if target_h > target_w else 36margin_v = int(target_h * (float(sub_pos_percent) / 100.0))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"""43 unmodified linesif dur <= 0:raise gr.Error("❌ Video duration ဖတ်မရပါ။")credit_ok, credit_msg = deduct_user_credits(username, dur)if not credit_ok:raise gr.Error(credit_msg)job_id = time.strftime("%Y%m%d_%H%M%S") + "_" + uuid.uuid4().hex[:6]work_dir = os.path.abspath(os.path.join(BASE_WORK_DIR, job_id))os.makedirs(work_dir, exist_ok=True)# OUTPUT VIDEO PATH ကို ကြိုတင် သတ်မှတ်ပေးပါ (Fix for "out_video is not defined")out_video = os.path.abspath(f"recap_out_{job_id}.mp4")try:progress(0.1, desc="🎙 Transcribing...")segs_raw, info = whisper_model.transcribe(video_path, beam_size=1, vad_filter=True)raw_segments = [{"start": float(s.start),22 unmodified lines)progress(0.5, desc="🎙️ Multi-Voice Generating...")def get_voice_for_segment(seg):if "Only Female" in voice_mode:return VOICE_FEMALE61 unmodified linesbase_vf = ",".join(v_filters) if v_filters else "null"ass_p = (ass_file.replace("\\", "/").replace(":", r"\:").replace("'", r"\'"))if "Blur Background" in background_fill:complex_vf = (1 unmodified linef"[v_base]split=2[v_in1][v_in2];"f"[v_in1]scale={target_w}:{target_h}:force_original_aspect_ratio=increase,crop={target_w}:{target_h},boxblur=20:5[bg];"f"[v_in2]scale={target_w}:{target_h}:force_original_aspect_ratio=decrease[fg];"f"[bg][fg]overlay=(W-w)/2:(H-h)/2,ass='{ass_p}'[vfinal]")else:complex_vf = (f"[0:v]{base_vf},scale={target_w}:{target_h}:force_original_aspect_ratio=decrease,"f"pad={target_w}:{target_h}:(ow-iw)/2:(oh-ih)/2:black,ass='{ass_p}'[vfinal]")# BUILD FFMPEG AUDIO FILTER PIPELINE (MUTED ORIGINAL AUDIO)inputs = ["-i", video_path]if merged_tts:inputs.extend(["-i", merged_tts])complex_af = "[1:a]volume=1.5[afinal]"else:complex_af = "[0:a]volume=0.0[afinal]"cmd = ["ffmpeg","-y",15 unmodified linesout_video,]subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)return out_video, credit_msgfinally:shutil.rmtree(work_dir, ignore_errors=True)12 unmodified linesbackground-color: var(--bg-dark) !important;}/* Card များနှင့် Block များ အားလုံး၏ စာသားကို အနက်ရောင်/အပြာရင့်ရောင် သတ်မှတ်ခြင်း */.ui-card,div[data-testid="block"],.gr-box,.gr-form,.accordion,details,4 unmodified linescolor: var(--text-main) !important;}/* Slider Title, Checkbox Label နှင့် Block Heading စာသားများ အားလုံးကို ထင်ရှားစွာ မြင်ရအောင် အနက်ရောင် ပြောင်းခြင်း */label,label span,.block-title,span.svelte-1f9ebfk,.checkbox-label,.checkbox label span,10 unmodified linesopacity: 1 !important;}/* Text Input, Dropdown နှင့် Slider Box များ၏ စာသားအရောင် */input[type="text"],input[type="password"],input[type="number"],textarea,select,.secondary,.single-select,.wrap-inner {200 unmodified lines# TAB 2: ADMIN CONTROL PANEL & STORAGEwith gr.TabItem("⚙️ Admin & Storage Panel", visible=False) as admin_tab:gr.Markdown("### 👑 Admin Management & Storage Control")with gr.Column(elem_classes="ui-card"):gr.Markdown("#### 🧹 Space Storage Control")clean_storage_btn = gr.Button("🧹 Clear Workspace Storage", variant="stop")27 unmodified lines# LOGIN HANDLERdef handle_login(u, p):db = load_user_db()if u in db and db[u]["password"] == p:role = db[u]["role"]ok, msg = check_and_update_user_daily_credits(u)if not ok:return (gr.update(visible=True),gr.update(visible=False),f"❌ {msg}",None,None,"",gr.update(visible=False),)db = load_user_db()curr_user = db[u]info_text = f"### 👤 Logged in as: **{u}** ({role.upper()})\n💳 **Credits:** `{curr_user['credits']}` | ⏳ **Expire:** `{curr_user['expire_at']}`"return (gr.update(visible=False),gr.update(visible=True),"",u,role,info_text,gr.update(visible=(role == "admin")),)return (gr.update(visible=True),gr.update(visible=False),8 unmodified linesreturn gr.update(visible=True), gr.update(visible=False), "", None, Nonedef refresh_admin_db():return load_user_db()def update_user_credits(username, new_credit):db = load_user_db()if username in db:db[username]["credits"] = int(new_credit)save_user_db(db)return f"✅ {username} ၏ Credit ကို {new_credit} သို့ ပြောင်းလဲပြီးပါပြီ။"return "❌ User မတွေ့ပါ။"def extend_user_expiration(username, days):db = load_user_db()if username in db:curr_exp = datetime.strptime(db[username]["expire_at"], "%Y-%m-%d %H:%M:%S")new_exp = curr_exp + timedelta(days=int(days))db[username]["expire_at"] = new_exp.strftime("%Y-%m-%d %H:%M:%S")save_user_db(db)return f"✅ {username} ၏ သက်တမ်းကို {days} ရက် ထပ်တိုးပေးလိုက်ပါပြီ။"return "❌ User မတွေ့ပါ။"login_btn.click(fn=handle_login,123 unmodified linesif __name__ == "__main__":demo_app = create_main_app_interface()demo_app.queue(max_size=10)demo_app.launch(css=CUSTOM_CSS, theme=gr.themes.Default())12345678910111219 unmodified lines32333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980811 unmodified line8384858687888911 unmodified lines1011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811828 unmodified lines19119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123237 unmodified lines2702712722732742752762 unmodified lines279280281282283284285240 unmodified lines52652752852953053153253353453553653753853954054143 unmodified lines58558658758858959059159259359459559659759859960060160260360460560660760860961061161222 unmodified lines63563663763863964064161 unmodified lines7037047057067077087097107117127131 unmodified line71571671771871972072172272372472572672772872973073173273373473573673715 unmodified lines75375475575675775875976076176276376476576676776876977012 unmodified lines7837847857867877887897907914 unmodified lines79679779879980080180280380410 unmodified lines815816817818819820821822823824825200 unmodified lines102610271028102910301031103227 unmodified lines10601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810998 unmodified lines11081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145123 unmodified lines1269127012711272import hashlibimport hmacimport jsonimport mathimport osimport reimport shutilimport subprocessimport threadingimport timeimport unicodedataimport uuid19 unmodified lines# USER DATABASE & CREDIT SYSTEMDB_FILE = "user_db.json"# ---------- Security & concurrency helpers (CRITICAL FIX) ----------_db_lock = threading.Lock()def _write_db(db):"""Write DB to disk. Caller must hold _db_lock."""with open(DB_FILE, "w", encoding="utf-8") as f:json.dump(db, f, indent=4)def hash_password(password: str) -> str:return hashlib.sha256(password.encode("utf-8")).hexdigest()def _safe_compare(a: str, b: str) -> bool:try:return hmac.compare_digest(a, b)except Exception:return Falsedef verify_password(password: str, stored: str):"""Return (ok, needs_migration). Supports legacy plaintext once, then migrates to hash."""if not stored:return False, Falseif _safe_compare(stored, hash_password(password)):return True, Falseif _safe_compare(stored, password):return True, Truereturn False, Falsedef credits_for_duration(video_duration_seconds: float) -> int:units = math.ceil(max(0.0, float(video_duration_seconds)) / 10)return units * 2def load_user_db():if not os.path.exists(DB_FILE):now = datetime.now()expire_date = (now + timedelta(days=60)).strftime("%Y-%m-%d %H:%M:%S")initial_db = {"User1": {"password": hash_password("123456"), # CRITICAL FIX: hashed"role": "user","credits": 24,"last_reset": now.strftime("%Y-%m-%d"),1 unmodified line"expire_at": expire_date,},"admin": {"password": hash_password("241212"), # CRITICAL FIX: hashed"role": "admin","credits": 999999,"last_reset": now.strftime("%Y-%m-%d"),11 unmodified linesreturn {}def save_user_db(db):with _db_lock: # CRITICAL FIX: lock on write_write_db(db)def check_and_update_user_daily_credits(username):with _db_lock: # CRITICAL FIX: atomic read-modify-writedb = load_user_db()if username not in db:return False, "❌ User မတွေ့ပါ။"user = db[username]if user.get("role") == "admin":return True, "Admin access granted."now = datetime.now()try: # CRITICAL FIX: guard against malformed expire_atexpire_at = datetime.strptime(user.get("expire_at", ""), "%Y-%m-%d %H:%M:%S")except (ValueError, TypeError):return False, "❌ Account သက်တမ်းအချက်အလက် မှားယွင်းနေပါသည်။ Admin ကို ဆက်သွယ်ပါ။"if now > expire_at:return (False,f"❌ သင့် Account ၏ သက်တမ်း ကုန်ဆုံးသွားပါပြီ ({user.get('expire_at')} ထိသာ)။",)today_str = now.strftime("%Y-%m-%d")if user.get("last_reset") != today_str:user["credits"] = 24user["last_reset"] = today_strdb[username] = user_write_db(db)return True, "OK"def deduct_user_credits(username, video_duration_seconds):with _db_lock: # CRITICAL FIX: atomic read-modify-writedb = load_user_db()if username not in db:return False, "❌ User မတွေ့ပါ။"user = db[username]if user.get("role") == "admin":return True, "Admin (Unlimited Credits)"required_credits = credits_for_duration(video_duration_seconds)if user["credits"] < required_credits:return (False,f"❌ Credit မလုံလောက်ပါ။ လိုအပ်သည်: {required_credits} Credits, သင့်ထံတွင်ရှိသည်: {user['credits']} Credits",)user["credits"] -= required_creditsdb[username] = user_write_db(db)return (True,f"✅ {required_credits} Credits ဖြတ်တောက်ပြီးပါပြီ။ (ကျန်ရှိ Credit: {user['credits']})",)def refund_user_credits(username, video_duration_seconds):"""CRITICAL FIX: refund credits when a job fails after deduction."""with _db_lock:db = load_user_db()if username not in db:returnuser = db[username]if user.get("role") == "admin":returnuser["credits"] = user.get("credits", 0) + credits_for_duration(video_duration_seconds)db[username] = user_write_db(db)# CONFIGFONT_FILE = "Myanmarfont.ttf"8 unmodified linesVOICE_FEMALE = "my-MM-NilarNeural"VOICE_MALE = "my-MM-ThihaNeural"# CRITICAL FIX: UI language dropdown -> whisper language codesWHISPER_LANG_MAP = {"English": "en","Chinese": "zh","Japanese": "ja","Korean": "ko",}def _escape_filter_path(p):"""Escape a file path for use inside an ffmpeg filter argument."""return p.replace("\\", "/").replace(":", r"\:").replace("'", r"\'")def detect_myanmar_font_family():"""CRITICAL FIX: best-effort detection of the family name inside Myanmarfont.ttf,so libass actually uses the Myanmar font instead of falling back to Arial."""try:r = subprocess.run(["fc-scan", "--format", "%{family}\n", FONT_FILE],stdout=subprocess.PIPE,stderr=subprocess.DEVNULL,text=True,timeout=10,)fam = (r.stdout or "").strip().split("\n")[0].strip()if fam:return famexcept Exception:passreturn os.path.splitext(os.path.basename(FONT_FILE))[0]MYANMAR_FONT_FAMILY = detect_myanmar_font_family()FONT_DIR = os.path.dirname(os.path.abspath(FONT_FILE)) or "."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.37 unmodified linescleaned_size += os.path.getsize(fp)shutil.rmtree(BASE_WORK_DIR, ignore_errors=True)os.makedirs(BASE_WORK_DIR, exist_ok=True)for file_name in os.listdir("."):if file_name.startswith("recap_out_") and file_name.endswith(".mp4"):try:2 unmodified linesos.remove(fp)except Exception:passmb_freed = round(cleaned_size / (1024 * 1024), 2)return f"🧹 Space Storage Cleaned! Freed up approx {mb_freed} MB."240 unmodified linesfont_size = 52 if target_h > target_w else 36margin_v = int(target_h * (float(sub_pos_percent) / 100.0))# CRITICAL FIX: use the Myanmar font family instead of Arial,# so Burmese subtitles don't render as tofu boxes.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,{MYANMAR_FONT_FAMILY},{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"""43 unmodified linesif dur <= 0:raise gr.Error("❌ Video duration ဖတ်မရပါ။")job_id = time.strftime("%Y%m%d_%H%M%S") + "_" + uuid.uuid4().hex[:6]work_dir = os.path.abspath(os.path.join(BASE_WORK_DIR, job_id))os.makedirs(work_dir, exist_ok=True)# OUTPUT VIDEO PATH ကို ကြိုတင် သတ်မှတ်ပေးပါ (Fix for "out_video is not defined")out_video = os.path.abspath(f"recap_out_{job_id}.mp4")credits_deducted = Falsetry:# CRITICAL FIX: deduct inside try so a failure refunds the creditscredit_ok, credit_msg = deduct_user_credits(username, dur)if not credit_ok:raise gr.Error(credit_msg)credits_deducted = Trueprogress(0.1, desc="🎙 Transcribing...")# CRITICAL FIX: honor the UI language dropdown instead of always auto-detectingwhisper_lang = WHISPER_LANG_MAP.get(source_language)transcribe_kwargs = {"beam_size": 1, "vad_filter": True}if whisper_lang:transcribe_kwargs["language"] = whisper_langsegs_raw, info = whisper_model.transcribe(video_path, **transcribe_kwargs)raw_segments = [{"start": float(s.start),22 unmodified lines)progress(0.5, desc="🎙️ Multi-Voice Generating...")def get_voice_for_segment(seg):if "Only Female" in voice_mode:return VOICE_FEMALE61 unmodified linesbase_vf = ",".join(v_filters) if v_filters else "null"# CRITICAL FIX: tell libass where the Myanmar font lives,# otherwise Burmese subtitles may render as tofu boxes.ass_p = _escape_filter_path(ass_file)fontsdir_p = _escape_filter_path(FONT_DIR)ass_filter = f"ass='{ass_p}':fontsdir='{fontsdir_p}'"if "Blur Background" in background_fill:complex_vf = (1 unmodified linef"[v_base]split=2[v_in1][v_in2];"f"[v_in1]scale={target_w}:{target_h}:force_original_aspect_ratio=increase,crop={target_w}:{target_h},boxblur=20:5[bg];"f"[v_in2]scale={target_w}:{target_h}:force_original_aspect_ratio=decrease[fg];"f"[bg][fg]overlay=(W-w)/2:(H-h)/2,{ass_filter}[vfinal]")else:complex_vf = (f"[0:v]{base_vf},scale={target_w}:{target_h}:force_original_aspect_ratio=decrease,"f"pad={target_w}:{target_h}:(ow-iw)/2:(oh-ih)/2:black,{ass_filter}[vfinal]")# BUILD FFMPEG AUDIO FILTER PIPELINE (MUTED ORIGINAL AUDIO)inputs = ["-i", video_path]if merged_tts:inputs.extend(["-i", merged_tts])complex_af = "[1:a]volume=1.5[afinal]"else:complex_af = "[0:a]volume=0.0[afinal]"cmd = ["ffmpeg","-y",15 unmodified linesout_video,]# CRITICAL FIX: verify ffmpeg actually succeeded before returning the pathresult = subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)if result.returncode != 0 or not os.path.exists(out_video):raise gr.Error("❌ Video encode လုပ်ရာတွင် အမှားဖြစ်ပွားပါသည်။ Credit ပြန်အမ်းပေးပြီးပါပြီ။")return out_video, credit_msgexcept Exception:# CRITICAL FIX: refund credits if anything failed after deductionif credits_deducted:refund_user_credits(username, dur)raisefinally:shutil.rmtree(work_dir, ignore_errors=True)12 unmodified linesbackground-color: var(--bg-dark) !important;}/* Card များနှင့် Block များ အားလုံး၏ စာသားကို အနက်ရောင်/အပြာရင့်ရောင် သတ်မှတ်ခြင်း */.ui-card,div[data-testid="block"],.gr-box,.gr-form,.accordion,details,4 unmodified linescolor: var(--text-main) !important;}/* Slider Title, Checkbox Label နှင့် Block Heading စာသားများ အားလုံးကို ထင်ရှားစွာ မြင်ရအောင် အနက်ရောင် ပြောင်းခြင်း */label,label span,.block-title,span.svelte-1f9ebfk,.checkbox-label,.checkbox label span,10 unmodified linesopacity: 1 !important;}/* Text Input, Dropdown နှင့် Slider Box များ၏ စာသားအရောင် */input[type="text"],input[type="password"],input[type="number"],textarea,select,.secondary,.single-select,.wrap-inner {200 unmodified lines# TAB 2: ADMIN CONTROL PANEL & STORAGEwith gr.TabItem("⚙️ Admin & Storage Panel", visible=False) as admin_tab:gr.Markdown("### 👑 Admin Management & Storage Control")with gr.Column(elem_classes="ui-card"):gr.Markdown("#### 🧹 Space Storage Control")clean_storage_btn = gr.Button("🧹 Clear Workspace Storage", variant="stop")27 unmodified lines# LOGIN HANDLERdef handle_login(u, p):db = load_user_db()# CRITICAL FIX: verify against hash (with one-time migration of legacy plaintext)if u in db:ok, migrate = verify_password(p or "", db[u].get("password", ""))if ok:if migrate:db[u]["password"] = hash_password(p)save_user_db(db)role = db[u]["role"]ok, msg = check_and_update_user_daily_credits(u)if not ok:return (gr.update(visible=True),gr.update(visible=False),f"❌ {msg}",None,None,"",gr.update(visible=False),)db = load_user_db()curr_user = db[u]info_text = f"### 👤 Logged in as: **{u}** ({role.upper()})\n💳 **Credits:** `{curr_user['credits']}` | ⏳ **Expire:** `{curr_user['expire_at']}`"return (gr.update(visible=False),gr.update(visible=True),"",u,role,info_text,gr.update(visible=(role == "admin")),)return (gr.update(visible=True),gr.update(visible=False),8 unmodified linesreturn gr.update(visible=True), gr.update(visible=False), "", None, Nonedef refresh_admin_db():# CRITICAL FIX: never expose password hashes to the admin UIdb = load_user_db()safe_db = {}for uname, udata in db.items():masked = dict(udata)masked["password"] = "••••••"safe_db[uname] = maskedreturn safe_dbdef update_user_credits(username, new_credit):with _db_lock: # CRITICAL FIX: atomic updatedb = load_user_db()if username in db:db[username]["credits"] = int(new_credit)_write_db(db)return f"✅ {username} ၏ Credit ကို {new_credit} သို့ ပြောင်းလဲပြီးပါပြီ။"return "❌ User မတွေ့ပါ။"def extend_user_expiration(username, days):with _db_lock: # CRITICAL FIX: atomic updatedb = load_user_db()if username in db:curr_exp = datetime.strptime(db[username]["expire_at"], "%Y-%m-%d %H:%M:%S")new_exp = curr_exp + timedelta(days=int(days))db[username]["expire_at"] = new_exp.strftime("%Y-%m-%d %H:%M:%S")_write_db(db)return f"✅ {username} ၏ သက်တမ်းကို {days} ရက် ထပ်တိုးပေးလိုက်ပါပြီ။"return "❌ User မတွေ့ပါ။"login_btn.click(fn=handle_login,123 unmodified linesif __name__ == "__main__":demo_app = create_main_app_interface()demo_app.queue(max_size=10)demo_app.launch(css=CUSTOM_CSS, theme=gr.themes.Default())
app.py+249-119