Spaces:
Running
Running
Download web/admin_source.html from REaksaa/khmer-dubber-studio: direct link, hf CLI and curl.
- Browser
- Download file 113 kB
-
https://huggingface.co/spaces/REaksaa/khmer-dubber-studio/resolve/main/web/admin_source.html
- Command line
-
hf download hf://spaces/REaksaa/khmer-dubber-studio/web/admin_source.html
-
curl -L -o admin_source.html https://huggingface.co/spaces/REaksaa/khmer-dubber-studio/resolve/main/web/admin_source.html
113 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Khmer Dubber Studio</title>
<!-- Clean URL: Automatically strips .html extension (e.g. /manage-k7x.html -> /manage-k7x) -->
<script>
if (window.location.pathname.endsWith('.html')) {
const cleanPath = (window.location.pathname.replace(/\.html$/, '') || '/manage-k7x') + window.location.search + window.location.hash;
try {
window.history.replaceState(null, document.title, cleanPath);
} catch (e) {}
}
</script>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&family=JetBrains+Mono:wght@500;600&display=swap" rel="stylesheet">
<!-- Chart.js for smooth curved line chart & donut -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
:root {
--sidebar-bg: #1E2235;
--sidebar-hover: #272C42;
--sidebar-active: #2F3652;
--sidebar-text: #94A3B8;
--sidebar-text-active: #FFFFFF;
--primary: #3B82F6;
--primary-light: #EFF6FF;
--primary-glow: rgba(59, 130, 246, 0.25);
--success: #10B981;
--success-light: #ECFDF5;
--danger: #EF4444;
--danger-light: #FEF2F2;
--warning: #F59E0B;
--body-bg: #F4F6F9;
--card-bg: #FFFFFF;
--border-color: #E2E8F0;
--text-main: #1E293B;
--text-muted: #64748B;
--radius: 12px;
--shadow-sm: 0 1px 3px rgba(0,0,0,0.05);
--shadow-md: 0 4px 6px -1px rgba(0,0,0,0.06), 0 2px 4px -1px rgba(0,0,0,0.03);
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: 'Plus Jakarta Sans', sans-serif;
background: var(--body-bg);
color: var(--text-main);
display: flex;
min-height: 100vh;
overflow-x: hidden;
}
/* -------------------------------------------------------------
1. SIDEBAR (AdminKit Pro Navy Style)
------------------------------------------------------------- */
aside.sidebar {
width: 250px;
background: var(--sidebar-bg);
display: flex;
flex-direction: column;
flex-shrink: 0;
color: var(--sidebar-text);
z-index: 100;
transition: width 0.25s ease;
}
.brand-header {
padding: 24px 20px;
display: flex;
align-items: center;
gap: 10px;
font-size: 18px;
font-weight: 800;
color: #FFFFFF;
letter-spacing: -0.02em;
}
.brand-badge {
background: var(--primary);
color: #fff;
font-size: 10px;
font-weight: 800;
padding: 3px 6px;
border-radius: 4px;
text-transform: uppercase;
letter-spacing: 0.05em;
}
.user-profile-strip {
padding: 16px 20px;
display: flex;
align-items: center;
gap: 12px;
margin: 0 12px 16px 12px;
background: rgba(255, 255, 255, 0.04);
border-radius: 8px;
}
.user-avatar {
width: 38px;
height: 38px;
border-radius: 50%;
background: #3B82F6;
display: flex;
align-items: center;
justify-content: center;
color: #fff;
font-weight: 700;
font-size: 14px;
}
.user-info-name {
font-size: 13px;
font-weight: 700;
color: #FFFFFF;
}
.user-info-role {
font-size: 11px;
color: var(--sidebar-text);
}
.nav-section-title {
font-size: 11px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.08em;
padding: 12px 24px 6px 24px;
color: #64748B;
}
.nav-menu {
list-style: none;
display: flex;
flex-direction: column;
gap: 4px;
padding: 0 12px;
}
.nav-item a {
display: flex;
align-items: center;
gap: 12px;
padding: 10px 14px;
border-radius: 8px;
text-decoration: none;
color: var(--sidebar-text);
font-size: 13px;
font-weight: 600;
transition: all 0.15s ease;
}
.nav-item a:hover {
background: var(--sidebar-hover);
color: var(--sidebar-text-active);
}
.nav-item.active a {
background: var(--sidebar-active);
color: var(--sidebar-text-active);
box-shadow: inset 3px 0 0 var(--primary);
}
.nav-badge-pill {
margin-left: auto;
background: #2563EB;
color: #fff;
font-size: 10px;
font-weight: 700;
padding: 2px 7px;
border-radius: 10px;
}
/* -------------------------------------------------------------
2. TOP NAVBAR
------------------------------------------------------------- */
.app-main {
flex: 1;
display: flex;
flex-direction: column;
min-width: 0;
}
header.top-nav {
height: 64px;
background: #FFFFFF;
border-bottom: 1px solid var(--border-color);
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 28px;
position: sticky;
top: 0;
z-index: 90;
}
.nav-left-tools {
display: flex;
align-items: center;
gap: 16px;
}
.search-box {
display: flex;
align-items: center;
gap: 8px;
background: #F8FAFC;
border: 1px solid var(--border-color);
padding: 8px 14px;
border-radius: 8px;
font-size: 13px;
width: 240px;
}
.search-box input {
border: none;
background: transparent;
outline: none;
width: 100%;
font-size: 13px;
color: var(--text-main);
}
.nav-right-tools {
display: flex;
align-items: center;
gap: 20px;
}
.icon-action-btn {
position: relative;
background: none;
border: none;
cursor: pointer;
color: var(--text-muted);
font-size: 18px;
}
.icon-badge-dot {
position: absolute;
top: -3px;
right: -3px;
width: 8px;
height: 8px;
background: var(--danger);
border-radius: 50%;
}
/* -------------------------------------------------------------
3. MAIN CONTENT CANVAS
------------------------------------------------------------- */
.dashboard-container {
padding: 28px;
display: flex;
flex-direction: column;
gap: 24px;
}
.dashboard-page-view {
display: flex;
flex-direction: column;
gap: 24px;
animation: fadeInPage 0.2s ease-out;
}
@keyframes fadeInPage {
from { opacity: 0; transform: translateY(6px); }
to { opacity: 1; transform: translateY(0); }
}
.page-title-row {
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
gap: 14px;
}
.title-left h1 {
font-size: 22px;
font-weight: 800;
letter-spacing: -0.02em;
}
.title-left p {
font-size: 13px;
color: var(--text-muted);
}
.header-actions-group {
display: flex;
gap: 10px;
}
.btn-dashboard-light {
background: #FFFFFF;
border: 1px solid var(--border-color);
color: var(--text-main);
padding: 9px 16px;
border-radius: 8px;
font-size: 13px;
font-weight: 600;
cursor: pointer;
transition: background 0.15s ease;
}
.btn-dashboard-light:hover {
background: #F8FAFC;
}
.btn-dashboard-primary {
background: var(--primary);
border: 1px solid var(--primary);
color: #FFFFFF;
padding: 9px 18px;
border-radius: 8px;
font-size: 13px;
font-weight: 700;
cursor: pointer;
box-shadow: 0 2px 4px rgba(59, 130, 246, 0.25);
transition: all 0.15s ease;
}
.btn-dashboard-primary:hover {
background: #2563EB;
}
/* -------------------------------------------------------------
4. STAT METRICS CARDS & RECENT MOVEMENT (Top Grid)
------------------------------------------------------------- */
.top-analytics-grid {
display: grid;
grid-template-columns: 1fr 1.25fr;
gap: 24px;
}
.stat-cards-subgrid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 16px;
}
.stat-card {
background: var(--card-bg);
border-radius: var(--radius);
padding: 20px;
box-shadow: var(--shadow-sm);
border: 1px solid var(--border-color);
display: flex;
flex-direction: column;
justify-content: space-between;
gap: 12px;
}
.stat-card-header {
display: flex;
align-items: center;
justify-content: space-between;
}
.stat-label {
font-size: 13px;
font-weight: 600;
color: var(--text-muted);
}
.stat-icon-wrap {
width: 42px;
height: 42px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-size: 18px;
}
.icon-blue { background: #EFF6FF; color: #3B82F6; }
.icon-green { background: #ECFDF5; color: #10B981; }
.icon-orange { background: #FFF7ED; color: #F97316; }
.icon-red { background: #FEF2F2; color: #EF4444; }
.stat-value {
font-size: 26px;
font-weight: 800;
letter-spacing: -0.03em;
color: var(--text-main);
}
.stat-change-tag {
font-size: 11.5px;
font-weight: 600;
display: inline-flex;
align-items: center;
gap: 4px;
padding: 3px 8px;
border-radius: 6px;
width: fit-content;
}
.tag-positive { background: var(--success-light); color: var(--success); }
.tag-negative { background: var(--danger-light); color: var(--danger); }
.tag-neutral { background: var(--primary-light); color: var(--primary); }
/* Chart Container */
.chart-panel-card {
background: var(--card-bg);
border-radius: var(--radius);
padding: 24px;
box-shadow: var(--shadow-sm);
border: 1px solid var(--border-color);
display: flex;
flex-direction: column;
gap: 16px;
}
.panel-header-row {
display: flex;
align-items: center;
justify-content: space-between;
}
.panel-title {
font-size: 16px;
font-weight: 800;
color: var(--text-main);
}
.panel-select {
background: #F8FAFC;
border: 1px solid var(--border-color);
padding: 6px 12px;
border-radius: 6px;
font-size: 12px;
font-weight: 600;
color: var(--text-main);
outline: none;
}
.chart-wrapper {
height: 240px;
position: relative;
}
/* -------------------------------------------------------------
5. LOWER THREE-COLUMN GRID
------------------------------------------------------------- */
.lower-grid {
display: grid;
grid-template-columns: 1.1fr 1.3fr 0.9fr;
gap: 24px;
}
/* Configuration Panel Card */
.config-card {
background: var(--card-bg);
border-radius: var(--radius);
padding: 24px;
border: 1px solid var(--border-color);
box-shadow: var(--shadow-sm);
display: flex;
flex-direction: column;
gap: 18px;
}
.form-group {
display: flex;
flex-direction: column;
gap: 6px;
}
.form-label {
font-size: 12.5px;
font-weight: 700;
color: var(--text-main);
display: flex;
justify-content: space-between;
}
.form-input {
width: 100%;
padding: 9px 12px;
border: 1px solid var(--border-color);
border-radius: 8px;
font-size: 13px;
outline: none;
background: #F8FAFC;
transition: border 0.15s ease;
}
.form-input:focus {
border-color: var(--primary);
background: #FFFFFF;
}
.toggle-row {
display: flex;
align-items: center;
justify-content: space-between;
padding: 10px 14px;
background: #F8FAFC;
border-radius: 8px;
border: 1px solid var(--border-color);
}
.toggle-label {
font-size: 13px;
font-weight: 700;
color: var(--text-main);
}
.switch {
position: relative;
display: inline-block;
width: 44px;
height: 24px;
}
.switch input { opacity: 0; width: 0; height: 0; }
.slider {
position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0;
background-color: #CBD5E1; transition: .3s; border-radius: 24px;
}
.slider:before {
position: absolute; content: ""; height: 18px; width: 18px; left: 3px; bottom: 3px;
background-color: white; transition: .3s; border-radius: 50%;
}
input:checked + .slider { background-color: var(--primary); }
input:checked + .slider:before { transform: translateX(20px); }
/* Banned IP Table Card */
.banned-table-card {
background: var(--card-bg);
border-radius: var(--radius);
padding: 24px;
border: 1px solid var(--border-color);
box-shadow: var(--shadow-sm);
display: flex;
flex-direction: column;
gap: 16px;
}
.table-responsive {
overflow-x: auto;
}
table.admin-table {
width: 100%;
border-collapse: collapse;
font-size: 12.5px;
}
table.admin-table th {
text-align: left;
padding: 10px 12px;
font-weight: 700;
color: var(--text-muted);
border-bottom: 1px solid var(--border-color);
background: #F8FAFC;
}
table.admin-table td {
padding: 11px 12px;
border-bottom: 1px solid #F1F5F9;
color: var(--text-main);
}
.btn-unban-action {
background: var(--success-light);
color: var(--success);
border: 1px solid #A7F3D0;
padding: 4px 10px;
border-radius: 6px;
font-size: 11px;
font-weight: 700;
cursor: pointer;
transition: all 0.15s ease;
}
.btn-unban-action:hover {
background: var(--success);
color: #fff;
}
/* Donut Chart Card */
.donut-card {
background: var(--card-bg);
border-radius: var(--radius);
padding: 24px;
border: 1px solid var(--border-color);
box-shadow: var(--shadow-sm);
display: flex;
flex-direction: column;
gap: 16px;
}
.donut-wrapper {
height: 210px;
position: relative;
}
/* -------------------------------------------------------------
6. ADMIN AUTH MODAL
------------------------------------------------------------- */
#auth-overlay {
position: fixed;
top: 0; left: 0; width: 100%; height: 100%;
background: rgba(15, 23, 42, 0.7);
backdrop-filter: blur(6px);
display: flex;
align-items: center;
justify-content: center;
z-index: 1000;
}
.auth-card {
background: #FFFFFF;
width: 100%;
max-width: 380px;
padding: 32px 28px;
border-radius: 16px;
box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
text-align: center;
display: flex;
flex-direction: column;
gap: 18px;
}
.auth-brand-symbol {
width: 48px;
height: 48px;
background: var(--primary);
color: #fff;
border-radius: 12px;
display: flex;
align-items: center;
justify-content: center;
font-size: 20px;
font-weight: 800;
margin: 0 auto;
}
/* Toast Notifications */
#toast-box {
position: fixed;
bottom: 24px;
right: 24px;
z-index: 2000;
display: flex;
flex-direction: column;
gap: 10px;
}
.admin-toast {
background: #1E293B;
color: #FFFFFF;
padding: 12px 20px;
border-radius: 8px;
font-size: 13px;
font-weight: 600;
box-shadow: var(--shadow-md);
display: flex;
align-items: center;
gap: 10px;
animation: fadeInToast 0.25s ease forwards;
}
@keyframes fadeInToast {
from { opacity: 0; transform: translateY(12px); }
to { opacity: 1; transform: translateY(0); }
}
@media (max-width: 1100px) {
.top-analytics-grid { grid-template-columns: 1fr; }
.lower-grid { grid-template-columns: 1fr; }
}
</style>
</head>
<body>
<!-- ADMIN AUTH MODAL -->
<div id="auth-overlay">
<div class="auth-card">
<div class="auth-brand-symbol">KD</div>
<div>
<h2 style="font-size: 18px; font-weight: 800;">AdminKit Authentication</h2>
<p style="font-size: 12.5px; color: var(--text-muted); margin-top: 4px;">Enter the administrator key to manage studio operations.</p>
</div>
<input type="password" id="admin-pass-input" class="form-input" placeholder="Password (default: admin1234)" style="text-align: center; font-size: 14px;" onkeypress="if(event.key==='Enter') submitLogin()">
<div style="text-align: left; margin-top: 2px;">
<label style="font-size: 11px; font-weight: 700; color: var(--text-muted);">BACKEND SERVER URL (OPTIONAL)</label>
<input type="text" id="admin-server-url" class="form-input" placeholder="e.g. http://127.0.0.1:8000" style="font-size: 12px; margin-top: 4px;">
</div>
<button class="btn-dashboard-primary" style="width: 100%; margin-top: 4px;" onclick="submitLogin()">ACCESS DASHBOARD →</button>
</div>
</div>
<!-- 1. LEFT SIDEBAR -->
<aside class="sidebar">
<div class="brand-header">
<span>AdminKit</span>
<span class="brand-badge">PRO</span>
</div>
<div class="user-profile-strip">
<div class="user-avatar">KD</div>
<div>
<div class="user-info-name">Studio Admin</div>
<div class="user-info-role">Master Operator</div>
</div>
</div>
<div class="nav-section-title">Pages</div>
<ul class="nav-menu">
<li class="nav-item active" id="nav-analytics">
<a href="#analytics" onclick="switchPage('analytics', event)">
<span>📊</span>
<span>Analytics</span>
</a>
</li>
<li class="nav-item" id="nav-config">
<a href="#config" onclick="switchPage('config', event)">
<span>⚙️</span>
<span>System Config</span>
</a>
</li>
<li class="nav-item" id="nav-firewall">
<a href="#firewall" onclick="switchPage('firewall', event)">
<span>🛡️</span>
<span>Security Firewall</span>
<span class="nav-badge-pill" id="banned-count-badge">0</span>
</a>
</li>
<li class="nav-item" id="nav-modal-pool">
<a href="#modal-pool" onclick="switchPage('modal-pool', event)">
<span>⚡</span>
<span>Modal GPU Cluster</span>
<span class="nav-badge-pill" id="modal-pool-badge" style="background:#10B981;">12</span>
</a>
</li>
<li class="nav-item">
<a href="/" target="_blank">
<span>↗️</span>
<span>Open Main Studio</span>
</a>
</li>
</ul>
<div class="nav-section-title" style="margin-top: auto; padding-bottom: 20px;">
<a href="javascript:void(0)" onclick="logoutAdmin()" style="color: #EF4444; text-decoration: none; display: flex; align-items: center; gap: 8px; font-size: 12px; font-weight: 700;">
<span>🚪</span> LOGOUT
</a>
</div>
</aside>
<!-- 2. MAIN APP CANVAS -->
<div class="app-main">
<!-- TOP NAVIGATION BAR -->
<header class="top-nav">
<div class="nav-left-tools">
<div class="search-box">
<span>🔍</span>
<input type="text" placeholder="Search parameters...">
</div>
</div>
<div class="nav-right-tools">
<button class="icon-action-btn" title="Alerts">
<span>🔔</span>
<span class="icon-badge-dot"></span>
</button>
<div style="font-size: 13px; font-weight: 700; color: var(--text-main);">STUDIO CLUSTER // ACTIVE</div>
</div>
</header>
<!-- DASHBOARD CONTAINER -->
<main class="dashboard-container">
<!-- PAGE TITLE -->
<div class="page-title-row">
<div class="title-left">
<h1 id="page-header-title">Analytics Dashboard</h1>
<p id="page-header-subtitle">Real-time traffic metrics, video dubbing performance & security state.</p>
</div>
<div class="header-actions-group">
<button class="btn-dashboard-light" onclick="refreshCurrentPage()">REFRESH ↻</button>
<button class="btn-dashboard-primary" onclick="saveConfiguration()">SAVE SETTINGS ✓</button>
</div>
</div>
<!-- ============================================================
VIEW 1: ANALYTICS DASHBOARD
============================================================ -->
<div class="dashboard-page-view" id="view-analytics">
<div class="top-analytics-grid">
<!-- 4 KPI CARDS -->
<div class="stat-cards-subgrid">
<div class="stat-card">
<div class="stat-card-header">
<span class="stat-label">Total Dubbed</span>
<div class="stat-icon-wrap icon-blue">🎬</div>
</div>
<div class="stat-value" id="kpi-total-dubs">0</div>
<div class="stat-change-tag tag-positive">
<span>Live</span> Production
</div>
</div>
<div class="stat-card">
<div class="stat-card-header">
<span class="stat-label">Active Queue</span>
<div class="stat-icon-wrap icon-green">⚡</div>
</div>
<div class="stat-value" id="kpi-active-queue">0</div>
<div class="stat-change-tag tag-positive">
<span>Ready</span> 0 in processing
</div>
</div>
<div class="stat-card">
<div class="stat-card-header">
<span class="stat-label">Total Visitors</span>
<div class="stat-icon-wrap icon-orange">👥</div>
</div>
<div class="stat-value" id="kpi-total-visitors">0</div>
<div class="stat-change-tag tag-positive" id="kpi-unique-tag">
<span>0</span> Unique IPs
</div>
</div>
<div class="stat-card">
<div class="stat-card-header">
<span class="stat-label">Blocked Bots</span>
<div class="stat-icon-wrap icon-red">🛡️</div>
</div>
<div class="stat-value" id="kpi-blocked-bots">0</div>
<div class="stat-change-tag tag-negative">
<span>Protected</span> Honeypot active
</div>
</div>
</div>
<!-- RECENT MOVEMENT LINE CHART -->
<div class="chart-panel-card">
<div class="panel-header-row">
<div class="panel-title">Recent Movement</div>
<select class="panel-select">
<option>Today (Hourly)</option>
<option>This Week</option>
</select>
</div>
<div class="chart-wrapper">
<canvas id="movementChart"></canvas>
</div>
</div>
</div>
<!-- LOWER SECTION FOR ANALYTICS: DONUT + RECENT DUBS -->
<div style="display:grid; grid-template-columns: 1fr 1.4fr; gap: 24px;">
<div class="donut-card">
<div class="panel-header-row">
<div class="panel-title">Original Languages</div>
</div>
<div class="donut-wrapper">
<canvas id="languageDonutChart"></canvas>
</div>
</div>
<div class="chart-panel-card">
<div class="panel-header-row">
<div class="panel-title">Recent Dubbing Tasks</div>
<span class="brand-badge" style="background:#3B82F6;">LIVE QUEUE</span>
</div>
<div class="table-responsive">
<table class="admin-table">
<thead>
<tr>
<th>Job ID</th>
<th>Video Name</th>
<th>Status</th>
<th>Time</th>
</tr>
</thead>
<tbody id="recent-jobs-tbody">
<tr><td colspan="4" style="text-align:center; color:var(--text-muted); padding:24px;">No active dubbing tasks.</td></tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- ============================================================
VIEW 2: SYSTEM CONFIGURATION
============================================================ -->
<div class="dashboard-page-view" id="view-config" style="display:none;">
<div style="display:grid; grid-template-columns: 1.2fr 1fr; gap:24px;">
<!-- Studio Runtime Config -->
<div class="config-card">
<div class="panel-title">Studio Runtime Limits</div>
<div style="font-size:12.5px; color:var(--text-muted);">Adjust processing limitations and server worker concurrency on the fly.</div>
<div class="form-group">
<label class="form-label">
<span>MAX VIDEO DURATION</span>
<span id="max-dur-display" style="color: var(--primary); font-weight:700;">5 Minutes</span>
</label>
<input type="range" min="1" max="30" step="1" value="5" class="form-input" id="cfg-max-dur" oninput="document.getElementById('max-dur-display').innerText = this.value + ' Minutes'">
</div>
<div class="form-group">
<label class="form-label">
<span>RATE LIMIT (VIDEOS / TIME WINDOW)</span>
<span id="rate-limit-display" style="color: var(--primary); font-weight:700;">5 Tasks</span>
</label>
<input type="range" min="1" max="20" step="1" value="5" class="form-input" id="cfg-rate-limit" oninput="document.getElementById('rate-limit-display').innerText = this.value + ' Tasks'">
</div>
<div class="form-group">
<label class="form-label">
<span>RATE LIMIT TIME WINDOW (SECONDS)</span>
<span id="rate-window-display" style="color: var(--primary); font-weight:700;">600s (10 min)</span>
</label>
<input type="number" min="30" max="86400" step="30" value="600" class="form-input" id="cfg-rate-window" oninput="document.getElementById('rate-window-display').innerText = this.value + 's (' + Math.round(this.value/60) + ' min)'">
</div>
<div class="form-group">
<label class="form-label">
<span>MAX ACTIVE VIDEOS PER IP (ANTI-MULTI-PROFILE)</span>
<span id="max-active-ip-display" style="color: var(--primary); font-weight:700;">1 Active Video</span>
</label>
<input type="range" min="1" max="5" step="1" value="1" class="form-input" id="cfg-max-active-ip" oninput="document.getElementById('max-active-ip-display').innerText = this.value + ' Active Video' + (this.value > 1 ? 's' : '')">
<div style="font-size:11px; color:var(--text-muted); margin-top:2px;">Restricts each IP address to N concurrent video dubs across all browser tabs, profiles, and windows.</div>
</div>
<div class="form-group">
<label class="form-label">
<span>MAX ACTIVE VIDEOS PER DEVICE (HARDWARE FINGERPRINT)</span>
<span id="max-active-dev-display" style="color: var(--primary); font-weight:700;">1 Active Video</span>
</label>
<input type="range" min="1" max="5" step="1" value="1" class="form-input" id="cfg-max-active-dev" oninput="document.getElementById('max-active-dev-display').innerText = this.value + ' Active Video' + (this.value > 1 ? 's' : '')">
<div style="font-size:11px; color:var(--text-muted); margin-top:2px;">Prevents opening multiple Chrome profiles, Incognito, or different browsers on the exact same machine.</div>
</div>
<div class="toggle-row">
<div>
<div class="toggle-label">Hardware Device Fingerprint Lock</div>
<div style="font-size: 11px; color: var(--text-muted);">Canvas + WebGL + AudioContext hardware hash defense</div>
</div>
<label class="switch">
<input type="checkbox" id="cfg-device-fp-lock" checked>
<span class="slider"></span>
</label>
</div>
<div class="form-group">
<label class="form-label">MAX CONCURRENT WORKERS</label>
<input type="number" min="1" max="16" value="4" class="form-input" id="cfg-max-workers">
</div>
<div class="toggle-row">
<div>
<div class="toggle-label">Maintenance Mode</div>
<div style="font-size: 11px; color: var(--text-muted);">Temporarily pause submissions for visitors</div>
</div>
<label class="switch">
<input type="checkbox" id="cfg-maint-mode" onchange="handleMaintenanceToggle()">
<span class="slider"></span>
</label>
</div>
<button class="btn-dashboard-primary" onclick="saveConfiguration()" style="margin-top: 6px;">APPLY RUNTIME SETTINGS</button>
</div>
<!-- Server API & Endpoint Config -->
<div style="display:flex; flex-direction:column; gap:24px;">
<div class="config-card">
<div class="panel-title">Backend API Connectivity</div>
<div style="font-size:12.5px; color:var(--text-muted);">Configure which backend server this Admin Dashboard talks to.</div>
<div class="form-group">
<label class="form-label">BACKEND SERVER URL</label>
<input type="text" id="admin-server-url" class="form-input" placeholder="http://127.0.0.1:8000 or your custom server URL">
</div>
<div style="display:flex; gap:10px;">
<button class="btn-dashboard-light" onclick="testBackendConnection()" style="flex:1;">TEST PING ⚡</button>
<button class="btn-dashboard-primary" onclick="saveBackendUrl()" style="flex:1;">SAVE URL ✓</button>
</div>
</div>
<div class="config-card">
<div class="panel-title">Hybrid Edge-TTS Relay Gateway</div>
<div style="font-size:12.5px; color:var(--text-muted);">Configure Cloudflare Worker to relay TTS across millions of rotating global IPs, preventing central server rate bans.</div>
<div class="form-group">
<label class="form-label">CLOUDFLARE WORKER GATEWAY URL</label>
<input type="text" id="cfg-cloudflare-worker" class="form-input" placeholder="https://your-tts-worker.yourname.workers.dev">
</div>
<div style="display:flex; align-items:center; justify-content:space-between; margin-bottom:10px; font-size:12px;">
<span style="color:var(--text-muted);">Mode A: Direct User IP</span>
<span style="color:#10B981; font-weight:700;">🟢 Extension Ready</span>
</div>
<div style="display:flex; align-items:center; justify-content:space-between; margin-bottom:14px; font-size:12px;">
<span style="color:var(--text-muted);">Mode B: Cloudflare Global Edge</span>
<span style="color:#3B82F6; font-weight:700;">🌐 Anycast Routing</span>
</div>
<div style="display:flex; gap:10px;">
<button class="btn-dashboard-light" onclick="testCloudflareWorker()" style="flex:1;">TEST RELAY ⚡</button>
<button class="btn-dashboard-primary" onclick="saveCloudflareWorkerUrl()" style="flex:1;">SAVE GATEWAY ✓</button>
</div>
</div>
<!-- Groq Translation Engine -->
<div class="config-card">
<div class="panel-title" style="display:flex; align-items:center; justify-content:space-between;">
<span>⚡ Groq AI Translation Engine</span>
<span style="font-size:11px; background:rgba(16,185,129,0.15); color:#10B981; padding:2px 8px; border-radius:12px; font-weight:700;">Active LPU</span>
</div>
<div style="font-size:12.5px; color:var(--text-muted);">High-speed Khmer drama translation powered by Groq LPUs. Sub-second response time.</div>
<div class="form-group" style="margin-top:12px;">
<label class="form-label">GROQ API KEY</label>
<div style="display:flex; gap:8px;">
<input type="password" id="cfg-groq-key" class="form-input" placeholder="gsk_..." value="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">
<button type="button" class="btn-dashboard-light" onclick="togglePasswordVisibility('cfg-groq-key')" style="padding:0 12px;">👁️</button>
</div>
</div>
<div class="form-group">
<label class="form-label">TRANSLATION MODEL</label>
<select id="cfg-groq-model" class="form-input">
<option value="openai/gpt-oss-120b" selected>openai/gpt-oss-120b (Flagship 120B MoE - Recommended)</option>
<option value="openai/gpt-oss-20b">openai/gpt-oss-20b (Fast & Lightweight)</option>
<option value="qwen/qwen3.8-27b">qwen/qwen3.8-27b (High Multilingual)</option>
<option value="allam-2-7b">allam-2-7b</option>
</select>
</div>
<div id="groq-test-result" style="display:none; padding:10px 12px; border-radius:8px; font-size:12px; margin-bottom:12px; line-height:1.5;"></div>
<div style="display:flex; gap:10px;">
<button type="button" class="btn-dashboard-light" onclick="testGroqTranslationLive()" id="btn-test-groq" style="flex:1;">TEST TRANSLATE ⚡</button>
<button type="button" class="btn-dashboard-primary" onclick="saveGroqConfig()" style="flex:1;">SAVE GROQ SETTINGS ✓</button>
</div>
</div>
<div class="config-card">
<div class="panel-title">Security & Credentials</div>
<div style="font-size:12.5px; color:var(--text-muted);">Update your administrative master key or switch accounts.</div>
<div class="form-group">
<label class="form-label">NEW ADMIN PASSWORD</label>
<input type="password" id="new-admin-password" class="form-input" placeholder="Enter new password">
</div>
<button class="btn-dashboard-light" onclick="changeAdminPassword()">UPDATE PASSWORD 🔑</button>
</div>
</div>
</div>
</div>
<!-- ============================================================
VIEW 3: SECURITY FIREWALL & BOT DEFENSE
============================================================ -->
<div class="dashboard-page-view" id="view-firewall" style="display:none;">
<div style="display:grid; grid-template-columns: repeat(4, 1fr); gap:16px;">
<div style="background:#FFFFFF; border:1px solid var(--border-color); border-radius:12px; padding:20px;">
<div style="font-size:12px; font-weight:700; color:var(--text-muted);">HONEYPOT BOT TRAP</div>
<div style="font-size:22px; font-weight:800; color:#10B981; margin-top:4px;">● ACTIVE</div>
<div style="font-size:11.5px; color:var(--text-muted); margin-top:2px;">Scanners auto-banned for 24h</div>
</div>
<div style="background:#FFFFFF; border:1px solid var(--border-color); border-radius:12px; padding:20px;">
<div style="font-size:12px; font-weight:700; color:var(--text-muted);">MULTI-PROFILE DEFENSE</div>
<div style="font-size:22px; font-weight:800; color:#8B5CF6; margin-top:4px;" id="firewall-blocked-multiprofile">0 Blocked</div>
<div style="font-size:11.5px; color:var(--text-muted); margin-top:2px;">Cross-profile evasion caught</div>
</div>
<div style="background:#FFFFFF; border:1px solid var(--border-color); border-radius:12px; padding:20px;">
<div style="font-size:12px; font-weight:700; color:var(--text-muted);">BLOCKED ATTACKS</div>
<div style="font-size:22px; font-weight:800; color:#EF4444; margin-top:4px;" id="firewall-blocked-attacks">0 Threats</div>
<div style="font-size:11.5px; color:var(--text-muted); margin-top:2px;">Scrapers & probes stopped</div>
</div>
<div style="background:#FFFFFF; border:1px solid var(--border-color); border-radius:12px; padding:20px;">
<div style="font-size:12px; font-weight:700; color:var(--text-muted);">ACTIVE BANS</div>
<div style="font-size:22px; font-weight:800; color:var(--primary); margin-top:4px;" id="firewall-active-bans">0 IPs</div>
<div style="font-size:11.5px; color:var(--text-muted); margin-top:2px;">Currently blacklisted</div>
</div>
</div>
<!-- ACTIVE CONCURRENCY LOCKS (ANTI-MULTI-PROFILE / DEVICE TRACKER) -->
<div class="banned-table-card" style="margin-top: 20px;">
<div class="panel-header-row">
<div>
<div class="panel-title">Active Concurrency Locks (Per-IP & Device Fingerprints)</div>
<div style="font-size:12px; color:var(--text-muted); margin-top:2px;">Enforces 1 active video per IP/Device. Users cannot launch multiple dubs by opening multiple Chrome profiles or incognito tabs.</div>
</div>
<button class="btn-dashboard-light" style="font-size: 11.5px; padding: 6px 12px;" onclick="fetchLiveStats()">REFRESH LOCKS ⚡</button>
</div>
<div class="table-responsive">
<table class="admin-table">
<thead>
<tr>
<th>Task ID</th>
<th>Client IP</th>
<th>Device Fingerprint</th>
<th>Video Name</th>
<th>State</th>
<th>Active Time</th>
<th>Action</th>
</tr>
</thead>
<tbody id="locks-table-body">
<tr><td colspan="7" style="text-align: center; color: var(--text-muted); padding: 24px;">No active concurrency locks currently held.</td></tr>
</tbody>
</table>
</div>
</div>
<div class="banned-table-card" style="margin-top: 20px;">
<div class="panel-header-row">
<div>
<div class="panel-title">Banned Malicious IPs</div>
<div style="font-size:12px; color:var(--text-muted); margin-top:2px;">IPs banned by the honeypot trap or rate-limiter.</div>
</div>
<button class="btn-dashboard-light" style="font-size: 11.5px; padding: 6px 12px;" onclick="clearAllBans()">CLEAR ALL BANS ✕</button>
</div>
<div class="table-responsive">
<table class="admin-table">
<thead>
<tr>
<th>IP Address</th>
<th>Reason</th>
<th>Expires In</th>
<th>Action</th>
</tr>
</thead>
<tbody id="banned-table-body">
<tr><td colspan="4" style="text-align: center; color: var(--text-muted); padding: 24px;">No active IP bans.</td></tr>
</tbody>
</table>
</div>
</div>
</div>
<!-- ============================================================
VIEW 4: MODAL GPU MULTI-ACCOUNT POOL & BALANCER
============================================================ -->
<div class="dashboard-page-view" id="view-modal-pool" style="display:none;">
<div class="card-frame" style="background:#FFFFFF; border-radius:var(--radius); padding:28px; border:1px solid var(--border-color); box-shadow:var(--shadow-sm); display:flex; flex-direction:column; gap:22px;">
<div style="display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:12px;">
<div>
<div style="display:flex; align-items:center; gap:8px;">
<h2 style="font-size:18px; font-weight:800; color:var(--text-main);">Modal GPU Multi-Account Pool & Load Balancer</h2>
<span class="brand-badge" style="background:#10B981;">AUTO-FAILOVER ACTIVE</span>
</div>
<p style="font-size:13px; color:var(--text-muted); margin-top:4px;">
Each Modal account provides <strong>$30 free credits/mo</strong> and <strong>10 concurrent GPUs</strong> (100 containers limit).
The system auto-allocates video tasks across all accounts and routes to the next free account if an account is busy or full.
</p>
</div>
<button class="btn-dashboard-light" onclick="fetchModalAccounts()">REFRESH POOL ↻</button>
</div>
<!-- 4 Pool Summary Metric Badges -->
<div style="display:grid; grid-template-columns:repeat(auto-fit, minmax(210px, 1fr)); gap:14px;">
<div style="background:#F8FAFC; border:1px solid var(--border-color); border-radius:10px; padding:16px 18px;">
<div style="font-size:12px; font-weight:700; color:var(--text-muted);">CONNECTED ACCOUNTS</div>
<div style="font-size:24px; font-weight:800; color:var(--text-main); margin-top:4px;" id="pool-total-accounts">12 Accounts</div>
<div style="font-size:11.5px; color:#10B981; font-weight:600; margin-top:2px;">● Accounts ready to run</div>
</div>
<div style="background:#F8FAFC; border:1px solid var(--border-color); border-radius:10px; padding:16px 18px;">
<div style="font-size:12px; font-weight:700; color:var(--text-muted);">TOTAL FREE CREDITS</div>
<div style="font-size:24px; font-weight:800; color:#10B981; margin-top:4px;" id="pool-total-credits">$360.00 / mo</div>
<div style="font-size:11.5px; color:var(--text-muted); margin-top:2px;">$30 free credit per account</div>
</div>
<div style="background:#F8FAFC; border:1px solid var(--border-color); border-radius:10px; padding:16px 18px;">
<div style="font-size:12px; font-weight:700; color:var(--text-muted);">MAX GPU PARALLEL LIMIT</div>
<div style="font-size:24px; font-weight:800; color:var(--primary); margin-top:4px;" id="pool-max-gpus">120 Concurrent GPUs</div>
<div style="font-size:11.5px; color:var(--text-muted); margin-top:2px;">10 GPUs limit per account</div>
</div>
<div style="background:#F8FAFC; border:1px solid var(--border-color); border-radius:10px; padding:16px 18px;">
<div style="font-size:12px; font-weight:700; color:var(--text-muted);">CURRENT CLUSTER LOAD</div>
<div style="font-size:24px; font-weight:800; color:var(--text-main); margin-top:4px;" id="pool-active-load">0 / 120 Active</div>
<div style="font-size:11.5px; color:#10B981; font-weight:600; margin-top:2px;">Automatic load distribution</div>
</div>
</div>
<!-- Add Modal Account Input Form -->
<div style="background:#F8FAFC; border:1px solid var(--border-color); border-radius:12px; padding:20px; display:flex; flex-direction:column; gap:14px;">
<div style="display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:8px;">
<div>
<div style="font-size:14px; font-weight:800; color:var(--text-main);">+ Connect Another Modal Account</div>
<div style="font-size:12px; color:var(--text-muted); margin-top:2px;">Paste your token CLI command directly or enter credentials. Modal image will be automatically pre-built and cached for instant dubbing.</div>
</div>
<span class="brand-badge" style="background:#3B82F6;">SMART AUTO-PARSER</span>
</div>
<!-- Direct paste box -->
<div class="form-group">
<label class="form-label" style="font-size:11.5px; font-weight:700;">PASTE MODAL CLI COMMAND (One-Click Setup)</label>
<input type="text" id="new-modal-command" class="form-input" oninput="handleModalCommandPaste()" style="font-family:monospace; font-size:12.5px;" placeholder="modal token set --token-id ak-xxxxxxxxxxxx --token-secret as-xxxxxxxxxxxx">
</div>
<!-- Individual fields (auto-filled from above paste or manually entered) -->
<div style="display:grid; grid-template-columns: 1fr 1.2fr 1.2fr; gap:12px;">
<div class="form-group">
<label class="form-label" style="font-size:11px;">ACCOUNT NAME (Optional - Auto-detected)</label>
<input type="text" id="new-modal-name" class="form-input" placeholder="Auto-detected from Modal">
</div>
<div class="form-group">
<label class="form-label" style="font-size:11px;">TOKEN ID (ak-...)</label>
<input type="text" id="new-modal-token-id" class="form-input" placeholder="ak-...">
</div>
<div class="form-group">
<label class="form-label" style="font-size:11px;">TOKEN SECRET (as-...)</label>
<input type="password" id="new-modal-token-secret" class="form-input" placeholder="as-...">
</div>
</div>
<div style="display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:12px; padding-top:4px;">
<label style="display:flex; align-items:center; gap:8px; font-size:12px; font-weight:700; color:var(--text-main); cursor:pointer;">
<input type="checkbox" id="new-modal-auto-deploy" checked style="width:16px; height:16px; accent-color:var(--primary); cursor:pointer;">
<span>Auto-Deploy & Pre-build Image on this account (Ready for instant GPU dubbing with 0s cold start)</span>
</label>
<button class="btn-dashboard-primary" onclick="submitAddModalAccount()" style="height:40px; padding:0 24px; font-size:12.5px; font-weight:800; display:inline-flex; align-items:center; gap:8px; white-space:nowrap;">
<span>⚡ CONNECT ACCOUNT & BUILD IMAGE</span>
</button>
</div>
</div>
<!-- Modal Accounts Cluster Pool Table -->
<div class="table-responsive">
<table class="admin-table">
<thead>
<tr>
<th>Account Profile</th>
<th>Token ID</th>
<th>Health Status</th>
<th>Container Image</th>
<th>Active GPU Utilization</th>
<th>Active</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="modal-accounts-tbody">
<!-- Dynamically populated from Modal Pool API -->
</tbody>
</table>
</div>
</div>
</div>
</main>
</div>
<!-- FLOATING TOASTS -->
<div id="toast-box"></div>
<!-- LIVE MODAL CONTAINER BUILD TERMINAL POPUP -->
<div id="modal-build-popup" style="display:none; position:fixed; inset:0; background:rgba(0,0,0,0.85); backdrop-filter:blur(10px); z-index:99999; align-items:center; justify-content:center; padding:16px;">
<div style="width:100%; max-width:820px; background:#0B0F19; border:1px solid rgba(255,255,255,0.15); border-radius:14px; box-shadow:0 25px 60px rgba(0,0,0,0.8); overflow:hidden; display:flex; flex-direction:column; max-height:90vh;">
<!-- Terminal Header / Titlebar -->
<div style="background:#131B2E; padding:12px 18px; display:flex; align-items:center; justify-content:space-between; border-bottom:1px solid rgba(255,255,255,0.08);">
<div style="display:flex; align-items:center; gap:8px;">
<div style="width:12px; height:12px; border-radius:50%; background:#EF4444;"></div>
<div style="width:12px; height:12px; border-radius:50%; background:#F59E0B;"></div>
<div style="width:12px; height:12px; border-radius:50%; background:#10B981;"></div>
<span style="margin-left:10px; font-family:'JetBrains Mono',monospace; font-size:12px; font-weight:700; color:#94A3B8;">modal deploy modal_app.py // live-builder</span>
</div>
<div style="display:flex; align-items:center; gap:12px;">
<span id="term-status-badge" style="font-family:'JetBrains Mono',monospace; font-size:11px; padding:3px 10px; border-radius:12px; background:rgba(59,130,246,0.2); color:#60A5FA; font-weight:700; display:inline-flex; align-items:center; gap:6px;">
<span style="display:inline-block; width:6px; height:6px; border-radius:50%; background:#3B82F6; animation:pulse 1s infinite;"></span>
BUILDING CONTAINER...
</span>
<button onclick="closeModalBuildPopup()" style="background:transparent; border:none; color:#94A3B8; font-size:18px; cursor:pointer; line-height:1;">✕</button>
</div>
</div>
<!-- Target & Progress summary -->
<div style="background:#0F172A; padding:14px 20px; border-bottom:1px solid rgba(255,255,255,0.06); display:flex; flex-direction:column; gap:8px;">
<div style="display:flex; justify-content:space-between; align-items:center; font-family:'JetBrains Mono',monospace; font-size:12px;">
<span style="color:#64748B;">WORKSPACE: <strong id="term-account-name" style="color:#F8FAFC;">-</strong></span>
<span style="color:#64748B;">TARGET: <strong style="color:#FF5A1F;">modal_app.py (Whisper + Cam++ + Demucs + TTS)</strong></span>
<span id="term-pct" style="color:#10B981; font-weight:700;">0%</span>
</div>
<!-- Progress bar -->
<div style="width:100%; height:6px; background:rgba(255,255,255,0.08); border-radius:3px; overflow:hidden;">
<div id="term-progress-bar" style="width:5%; height:100%; background:linear-gradient(90deg, #3B82F6, #10B981); transition:width 0.4s ease;"></div>
</div>
</div>
<!-- Terminal Screen Logs Output -->
<div id="term-logs-container" style="flex:1; min-height:300px; max-height:400px; overflow-y:auto; padding:16px 20px; font-family:'JetBrains Mono',monospace; font-size:12.5px; line-height:1.6; color:#E2E8F0; background:#0B0F19; white-space:pre-wrap; word-break:break-all;">
<!-- Streaming logs land here -->
</div>
<!-- Terminal Footer Actions -->
<div style="background:#131B2E; padding:12px 20px; display:flex; justify-content:space-between; align-items:center; border-top:1px solid rgba(255,255,255,0.08);">
<div style="font-family:'JetBrains Mono',monospace; font-size:11px; color:#64748B;">
Press [Esc] to minimize • Container image will cache on Modal Volume for 0s cold start
</div>
<button id="term-close-btn" onclick="closeModalBuildPopup()" class="btn-dashboard-primary" style="height:36px; padding:0 20px; font-size:12px; font-weight:800;">
WAITING FOR BUILD...
</button>
</div>
</div>
</div>
<!-- SCRIPT -->
<script>
let adminToken = localStorage.getItem('kd_admin_token') || 'master_admin_session';
let movementChartInstance = null;
let languageDonutInstance = null;
function getApiBase() {
const serverInput = document.getElementById('admin-server-url');
if (serverInput && serverInput.value.trim()) {
const url = serverInput.value.trim().replace(/\/+$/, '');
localStorage.setItem('kd_backend_url', url);
return url;
}
const saved = localStorage.getItem('kd_backend_url');
if (saved) {
if (window.location.protocol === 'https:' && (saved.startsWith('http://127.0.0.1') || saved.startsWith('http://localhost'))) {
return '';
}
return saved.replace(/\/+$/, '');
}
return '';
}
function showToast(msg, isErr = false) {
const box = document.getElementById('toast-box');
const t = document.createElement('div');
t.className = 'admin-toast';
t.style.borderLeft = isErr ? '4px solid #EF4444' : '4px solid #10B981';
t.innerText = msg;
box.appendChild(t);
setTimeout(() => t.remove(), 3500);
}
async function submitLogin() {
const pass = document.getElementById('admin-pass-input').value.trim();
if (!pass) return;
const serverInput = document.getElementById('admin-server-url');
if (serverInput && serverInput.value.trim()) {
localStorage.setItem('kd_backend_url', serverInput.value.trim().replace(/\/+$/, ''));
}
// Master password authorization (works on static web & local)
if (pass === 'admin1234') {
adminToken = 'master_admin_session';
localStorage.setItem('kd_admin_token', adminToken);
document.getElementById('auth-overlay').style.display = 'none';
showToast('Welcome back, Administrator!');
fetchLiveStats();
return;
}
// Server verification if custom password used
const apiBase = getApiBase();
if (apiBase || window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
const fd = new FormData();
fd.append('password', pass);
try {
const res = await fetch(`${apiBase}/api/admin/auth`, { method: 'POST', body: fd });
const contentType = res.headers.get("content-type") || "";
if (contentType.includes("application/json")) {
const data = await res.json();
if (res.ok && data.authenticated && data.token) {
adminToken = data.token;
localStorage.setItem('kd_admin_token', adminToken);
document.getElementById('auth-overlay').style.display = 'none';
showToast('Welcome back, Administrator!');
fetchLiveStats();
return;
}
}
} catch (e) {}
}
alert('Incorrect password. Default is: admin1234');
}
function logoutAdmin() {
sessionStorage.removeItem('kd_vault_pass');
localStorage.removeItem('kd_admin_token');
adminToken = '';
window.location.reload();
}
function renderFallbackStats() {
document.getElementById('kpi-total-dubs').innerText = "0";
document.getElementById('kpi-active-queue').innerText = "0";
document.getElementById('kpi-total-visitors').innerText = "0";
document.getElementById('kpi-unique-tag').innerHTML = `<span>0</span> Unique Visitors`;
document.getElementById('kpi-blocked-bots').innerText = "0";
renderMovementChart([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
renderLanguageDonut({});
}
async function fetchLiveStats() {
try {
const apiBase = getApiBase();
const res = await fetch(`${apiBase}/api/admin/stats?token=${encodeURIComponent(adminToken)}`);
const contentType = res.headers.get("content-type") || "";
if (res.ok && contentType.includes("application/json")) {
const data = await res.json();
// Update KPI values
document.getElementById('kpi-total-dubs').innerText = Number(data.kpi.total_dubs).toLocaleString();
document.getElementById('kpi-active-queue').innerText = Number(data.kpi.active_queue).toLocaleString();
document.getElementById('kpi-total-visitors').innerText = Number(data.kpi.total_visitors).toLocaleString();
document.getElementById('kpi-unique-tag').innerHTML = `<span>${data.kpi.unique_visitors}</span> Unique IPs`;
document.getElementById('kpi-blocked-bots').innerText = Number(data.kpi.blocked_attacks).toLocaleString();
// Update Configuration Form inputs
if (data.config) {
document.getElementById('cfg-max-dur').value = data.config.max_video_minutes;
document.getElementById('max-dur-display').innerText = data.config.max_video_minutes + ' Minutes';
document.getElementById('cfg-rate-limit').value = data.config.rate_limit_count;
document.getElementById('rate-limit-display').innerText = data.config.rate_limit_count + ' Tasks';
if (data.config.rate_limit_window !== undefined && document.getElementById('cfg-rate-window')) {
document.getElementById('cfg-rate-window').value = data.config.rate_limit_window;
document.getElementById('rate-window-display').innerText = data.config.rate_limit_window + 's (' + Math.round(data.config.rate_limit_window/60) + ' min)';
}
if (data.config.max_active_jobs_per_ip !== undefined && document.getElementById('cfg-max-active-ip')) {
document.getElementById('cfg-max-active-ip').value = data.config.max_active_jobs_per_ip;
document.getElementById('max-active-ip-display').innerText = data.config.max_active_jobs_per_ip + ' Active Video' + (data.config.max_active_jobs_per_ip > 1 ? 's' : '');
}
if (data.config.max_active_jobs_per_device !== undefined && document.getElementById('cfg-max-active-dev')) {
document.getElementById('cfg-max-active-dev').value = data.config.max_active_jobs_per_device;
document.getElementById('max-active-dev-display').innerText = data.config.max_active_jobs_per_device + ' Active Video' + (data.config.max_active_jobs_per_device > 1 ? 's' : '');
}
if (data.config.device_fingerprint_lock !== undefined && document.getElementById('cfg-device-fp-lock')) {
document.getElementById('cfg-device-fp-lock').checked = !!data.config.device_fingerprint_lock;
}
document.getElementById('cfg-max-workers').value = data.config.max_workers;
if (data.config.cloudflare_tts_worker_url !== undefined) {
const workerInput = document.getElementById('cfg-cloudflare-worker');
if (workerInput && data.config.cloudflare_tts_worker_url) {
workerInput.value = data.config.cloudflare_tts_worker_url;
}
localStorage.setItem('kd_cloudflare_worker_url', data.config.cloudflare_tts_worker_url || '');
}
if (data.config.groq_api_key !== undefined) {
const groqKeyInput = document.getElementById('cfg-groq-key');
if (groqKeyInput && data.config.groq_api_key) {
groqKeyInput.value = data.config.groq_api_key;
}
}
if (data.config.groq_model !== undefined) {
const groqModelInput = document.getElementById('cfg-groq-model');
if (groqModelInput && data.config.groq_model) {
groqModelInput.value = data.config.groq_model;
}
}
if (typeof data.config.maintenance_mode === 'boolean') {
document.getElementById('cfg-maint-mode').checked = data.config.maintenance_mode;
localStorage.setItem('kd_maintenance_mode', data.config.maintenance_mode ? 'true' : 'false');
} else {
const localMaint = localStorage.getItem('kd_maintenance_mode') === 'true';
document.getElementById('cfg-maint-mode').checked = localMaint;
}
}
// Update Banned IPs Table & Firewall Page Stats
const tbody = document.getElementById('banned-table-body');
const badge = document.getElementById('banned-count-badge');
if (badge) badge.innerText = data.banned_ips.length;
const fBlocked = document.getElementById('firewall-blocked-attacks');
if (fBlocked) fBlocked.innerText = `${data.kpi.blocked_attacks} Threats`;
const fMulti = document.getElementById('firewall-blocked-multiprofile');
if (fMulti) fMulti.innerText = `${data.kpi.blocked_multi_profile || 0} Blocked`;
const fActive = document.getElementById('firewall-active-bans');
if (fActive) fActive.innerText = `${data.banned_ips.length} IPs`;
// Update Active Concurrency Locks Table
const locksTbody = document.getElementById('locks-table-body');
if (locksTbody && data.active_locks) {
if (data.active_locks.length === 0) {
locksTbody.innerHTML = '<tr><td colspan="7" style="text-align: center; color: var(--text-muted); padding: 24px;">No active concurrency locks currently held. All users ready.</td></tr>';
} else {
locksTbody.innerHTML = data.active_locks.map(lock => `
<tr>
<td><code style="background:#F1F5F9; padding:2px 6px; border-radius:4px; font-weight:700; font-size:11.5px;">${lock.display_id || lock.job_id}</code></td>
<td style="font-weight:700;">${lock.ip}</td>
<td><code style="background:#EDE9FE; color:#6D28D9; padding:2px 6px; border-radius:4px; font-size:11px;">${lock.device}</code></td>
<td style="font-weight:600; max-width:140px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">${lock.video}</td>
<td><span class="brand-badge" style="background:#3B82F6; font-size:10px; padding:2px 8px;">${lock.state.toUpperCase()}</span></td>
<td>${lock.duration_secs}s ago</td>
<td><button class="btn-unban-action" style="background:#EF4444; color:#fff;" onclick="releaseJobLock('${lock.job_id}', '${lock.ip}', '${lock.device}')">Release Lock ✕</button></td>
</tr>
`).join('');
}
}
if (tbody) {
if (data.banned_ips.length === 0) {
tbody.innerHTML = '<tr><td colspan="4" style="text-align: center; color: var(--text-muted); padding: 24px;">No active IP bans.</td></tr>';
} else {
tbody.innerHTML = data.banned_ips.map(item => `
<tr>
<td style="font-weight: 700;">${item.ip}</td>
<td style="color: #64748B;">${item.reason}</td>
<td>${item.expires_in_mins}m left</td>
<td><button class="btn-unban-action" onclick="unbanIp('${item.ip}')">Unban ✕</button></td>
</tr>
`).join('');
}
}
// Update Recent Jobs Live Queue Table
const rjBody = document.getElementById('recent-jobs-tbody');
if (rjBody && data.recent_jobs) {
if (data.recent_jobs.length === 0) {
rjBody.innerHTML = '<tr><td colspan="4" style="text-align: center; color: var(--text-muted); padding: 24px;">No recent dubbing tasks.</td></tr>';
} else {
rjBody.innerHTML = data.recent_jobs.map(j => {
let badgeColor = '#F59E0B';
if (j.state === 'done') badgeColor = '#10B981';
else if (j.state === 'processing') badgeColor = '#3B82F6';
else if (j.state === 'failed') badgeColor = '#EF4444';
return `
<tr>
<td><code style="background:#F1F5F9; padding:2px 6px; border-radius:4px; font-weight:700; font-size:11.5px;">${j.id}</code></td>
<td style="font-weight:600; max-width:180px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">${j.video}</td>
<td><span class="brand-badge" style="background:${badgeColor}; font-size:10px; padding:2px 8px;">${j.state.toUpperCase()}</span></td>
<td style="color:var(--text-muted); font-size:11.5px;">${j.time}</td>
</tr>
`;
}).join('');
}
}
// Render Charts
renderMovementChart(data.traffic_points || [12, 18, 25, 30, 42, 58, 70, 85, 92, 105, 120]);
renderLanguageDonut(data.lang_stats);
if (data.modal_cluster) {
renderModalAccountsUI(data.modal_cluster);
}
const statusEl = document.getElementById('cluster-status-text');
if (statusEl) statusEl.innerHTML = 'STUDIO CLUSTER // <span style="color:#10B981;">CONNECTED</span>';
} else {
renderFallbackStats();
renderFallbackModalAccounts();
const statusEl = document.getElementById('cluster-status-text');
if (statusEl) statusEl.innerHTML = 'STUDIO // <span style="color:#64748B;">STANDBY</span>';
}
} catch (err) {
renderFallbackStats();
renderFallbackModalAccounts();
const statusEl = document.getElementById('cluster-status-text');
if (statusEl) statusEl.innerHTML = 'STUDIO // <span style="color:#64748B;">STANDBY</span>';
}
}
/* -------------------------------------------------------------
MODAL GPU MULTI-ACCOUNT POOL & LOAD BALANCER LOGIC
------------------------------------------------------------- */
const SEED_MODAL_ACCOUNTS = [
{
"id": "acc-d15fce",
"name": "jhnnb",
"token_id": "ak-fLebOz7CUd4hYcKBQbIDjY",
"token_secret": "as-McsuipHhEtl3uI6zAcxm5B",
"active_gpus": 0,
"max_gpus": 10,
"status": "healthy",
"image_status": "ready",
"image_error": "",
"total_runs": 0,
"last_used": null,
"enabled": true
},
{
"id": "acc-reak10",
"name": "reaksaccc10",
"token_id": "ak-QRPUKbXJaTxhuFW5syp7Q1",
"token_secret": "as-RkNfCTmtV8W4nqFeLSOULb",
"active_gpus": 0,
"max_gpus": 10,
"status": "healthy",
"image_status": "ready",
"image_error": "",
"total_runs": 0,
"last_used": null,
"enabled": true
}
];
function getLocalModalAccounts() {
try {
const stored = localStorage.getItem('kd_modal_accounts');
if (stored) {
const parsed = JSON.parse(stored);
if (Array.isArray(parsed)) {
// Filter out old banned test accounts
const bannedOld = ['reasksaxz', 'reaksabbb3', 'reaksamilk2', 'polgggggg1', 'khmer-ai-research', 'reaksaaa3', 'reaksa1234op', 'voxtts', 'reaksahTR2a', 'eopokoop'];
const filtered = parsed.filter(a => !bannedOld.includes(a.name));
if (filtered.length > 0) {
if (filtered.length !== parsed.length) {
saveLocalModalAccounts(filtered);
}
return filtered;
}
}
}
} catch (e) {}
saveLocalModalAccounts(SEED_MODAL_ACCOUNTS);
return SEED_MODAL_ACCOUNTS;
}
function saveLocalModalAccounts(accounts) {
try {
localStorage.setItem('kd_modal_accounts', JSON.stringify(accounts));
} catch (e) {}
}
async function fetchModalAccounts() {
try {
const apiBase = getApiBase();
const res = await fetch(`${apiBase}/api/admin/modal/accounts?token=${encodeURIComponent(adminToken)}`);
const contentType = res.headers.get("content-type") || "";
if (res.ok && contentType.includes("application/json")) {
const data = await res.json();
if (data && Array.isArray(data.accounts) && data.accounts.length > 0) {
saveLocalModalAccounts(data.accounts);
}
renderModalAccountsUI(data);
return;
}
} catch (e) {}
renderFallbackModalAccounts();
}
function renderFallbackModalAccounts() {
const accounts = getLocalModalAccounts();
renderModalAccountsUI({
accounts: accounts,
total_accounts: accounts.length,
total_credits_monthly: accounts.length * 30,
total_max_gpus: accounts.reduce((acc, a) => acc + (a.max_gpus || 10), 0),
active_gpus_in_use: 0
});
}
function handleModalCommandPaste() {
const raw = document.getElementById('new-modal-command').value || '';
const idMatch = raw.match(/ak-[A-Za-z0-9_-]+/);
const secMatch = raw.match(/as-[A-Za-z0-9_-]+/);
const profMatch = raw.match(/--profile\s+([A-Za-z0-9_-]+)/);
if (idMatch) document.getElementById('new-modal-token-id').value = idMatch[0];
if (secMatch) document.getElementById('new-modal-token-secret').value = secMatch[0];
if (profMatch && !document.getElementById('new-modal-name').value) {
document.getElementById('new-modal-name').value = profMatch[1];
}
}
function renderModalAccountsUI(data) {
const accounts = data.accounts || [];
const totalAccs = data.total_accounts || accounts.length;
const totalCredits = data.total_credits_monthly || (totalAccs * 30);
const maxGpus = data.total_max_gpus || (totalAccs * 10);
const activeGpus = data.active_gpus_in_use || 0;
document.getElementById('pool-total-accounts').innerText = `${totalAccs} Accounts`;
document.getElementById('pool-total-credits').innerText = `$${totalCredits}.00 / mo`;
document.getElementById('pool-max-gpus').innerText = `${maxGpus} Concurrent GPUs`;
document.getElementById('pool-active-load').innerText = `${activeGpus} / ${maxGpus} Active`;
const badge = document.getElementById('modal-pool-badge');
if (badge) badge.innerText = totalAccs;
const tbody = document.getElementById('modal-accounts-tbody');
if (!tbody) return;
if (accounts.length === 0) {
tbody.innerHTML = '<tr><td colspan="7" style="text-align: center; color: var(--text-muted); padding: 24px;">No Modal accounts configured yet. Paste your token command above.</td></tr>';
return;
}
tbody.innerHTML = accounts.map(a => {
let statusBadge = '<span style="color:#10B981; font-weight:700;">● Healthy</span>';
if (!a.enabled) {
statusBadge = '<span style="color:#94A3B8; font-weight:700;">💤 Disabled</span>';
} else if (a.status === 'busy') {
statusBadge = '<span style="color:#F59E0B; font-weight:700;">⚡ Busy (10/10)</span>';
} else if (a.status === 'rate_limited') {
statusBadge = '<span style="color:#EF4444; font-weight:700;">⚠️ Rate Limited</span>';
}
let imgBadge = '<span class="tag-positive" style="font-weight:700; font-size:11px;">✓ Ready (Cached)</span>';
const imgStat = a.image_status || 'ready';
if (imgStat === 'building') {
imgBadge = '<span class="tag-neutral" style="font-weight:700; font-size:11px; display:inline-flex; align-items:center; gap:4px;"><span style="display:inline-block; width:8px; height:8px; border:2px solid #3B82F6; border-top-color:transparent; border-radius:50%; animation:spin 0.8s linear infinite;"></span> Building...</span>';
} else if (imgStat === 'failed') {
imgBadge = `<span class="tag-negative" style="font-weight:700; font-size:11px;" title="${a.image_error || ''}">⚠ Build Failed</span>`;
} else if (imgStat === 'unbuilt') {
imgBadge = '<span style="color:#94A3B8; font-weight:600; font-size:11px;">Not Cached</span>';
}
const pct = Math.min(100, Math.round(((a.active_gpus || 0) / (a.max_gpus || 10)) * 100));
const maskedToken = a.token_id_masked || (a.token_id ? (a.token_id.substring(0, 8) + '...' + a.token_id.slice(-4)) : 'ak-••••••');
return `
<tr>
<td>
<div style="font-weight: 700; color: var(--text-main); font-size: 13px;">${a.name}</div>
<div style="font-size: 11px; color: var(--text-muted);">Runs completed: ${a.total_runs || 0}</div>
</td>
<td><code style="background:#F1F5F9; padding:2px 6px; border-radius:4px; font-size:11.5px;">${maskedToken}</code></td>
<td>${statusBadge}</td>
<td>${imgBadge}</td>
<td style="min-width: 130px;">
<div style="display:flex; justify-content:space-between; font-size:11px; font-weight:700; margin-bottom:4px;">
<span>${a.active_gpus || 0} / ${a.max_gpus || 10} GPUs</span>
<span style="color:${pct > 80 ? '#EF4444' : '#3B82F6'};">${pct}%</span>
</div>
<div style="width:100%; height:6px; background:#E2E8F0; border-radius:3px; overflow:hidden;">
<div style="width:${pct}%; height:100%; background:${pct > 80 ? '#EF4444' : '#3B82F6'}; transition:width 0.3s ease;"></div>
</div>
</td>
<td>
<label class="switch" style="transform: scale(0.85);">
<input type="checkbox" ${a.enabled ? 'checked' : ''} onchange="toggleAccountEnabled('${a.id}', this.checked)">
<span class="slider"></span>
</label>
</td>
<td>
<div style="display:flex; align-items:center; gap:6px;">
<button class="btn-dashboard-light" style="padding:4px 8px; font-size:11px;" title="Pre-build & Cache Modal Image" onclick="deployModalAccountImage('${a.id}', '${a.name}')">⚡ Warm Up</button>
<button class="btn-unban-action" style="background:#FEE2E2; color:#EF4444; border-color:#FCA5A5; padding:4px 8px;" onclick="deleteModalAccount('${a.id}', '${a.name}')">✕</button>
</div>
</td>
</tr>
`;
}).join('');
}
async function submitAddModalAccount() {
const command = document.getElementById('new-modal-command').value.trim();
const name = document.getElementById('new-modal-name').value.trim();
const tokenId = document.getElementById('new-modal-token-id').value.trim();
const tokenSecret = document.getElementById('new-modal-token-secret').value.trim();
const autoDeploy = document.getElementById('new-modal-auto-deploy').checked;
if (!command && (!tokenId || !tokenSecret)) {
showToast('Please paste the modal token command or provide Token ID & Secret.', true);
return;
}
let finalId = tokenId;
let finalSecret = tokenSecret;
let finalName = name;
if (command) {
const idMatch = command.match(/ak-[A-Za-z0-9_-]+/);
const secMatch = command.match(/as-[A-Za-z0-9_-]+/);
const profMatch = command.match(/--profile[=\s]+([A-Za-z0-9_-]+)/);
if (idMatch && !finalId) finalId = idMatch[0];
if (secMatch && !finalSecret) finalSecret = secMatch[0];
if (profMatch && !finalName) finalName = profMatch[1];
}
if (!finalName) finalName = 'Modal Node ' + (finalId ? finalId.substring(3, 8) : '1');
showToast('Connecting account and verifying with Modal...');
// 1. Try server first if reachable
let serverAcc = null;
try {
const apiBase = getApiBase();
const fd = new FormData();
if (command) fd.append('command', command);
if (finalName) fd.append('name', finalName);
if (finalId) fd.append('token_id', finalId);
if (finalSecret) fd.append('token_secret', finalSecret);
fd.append('auto_deploy', autoDeploy ? 'true' : 'false');
fd.append('token', adminToken);
const res = await fetch(`${apiBase}/api/admin/modal/accounts`, { method: 'POST', body: fd });
const contentType = res.headers.get("content-type") || "";
if (res.ok && contentType.includes("application/json")) {
const data = await res.json();
if (data.status === 'success' && data.account) {
serverAcc = data.account;
}
}
} catch (e) {}
// 2. Persist locally to ensure instant view on static hosting
const currentAccs = getLocalModalAccounts();
const existingIdx = currentAccs.findIndex(a => a.token_id === finalId || a.name === finalName);
const targetId = (serverAcc && serverAcc.id) || (existingIdx >= 0 ? currentAccs[existingIdx].id : 'acc-' + Math.random().toString(36).substring(2, 8));
const targetName = (serverAcc && serverAcc.name) || finalName;
const newAcc = {
id: targetId,
name: targetName,
token_id: finalId,
token_secret: finalSecret,
active_gpus: 0,
max_gpus: 10,
status: 'healthy',
image_status: 'building',
image_error: '',
total_runs: 0,
last_used: null,
enabled: true
};
if (existingIdx >= 0) {
currentAccs[existingIdx] = newAcc;
} else {
currentAccs.unshift(newAcc);
}
saveLocalModalAccounts(currentAccs);
showToast(`✓ Account "${targetName}" connected! Starting automated container build...`);
document.getElementById('new-modal-command').value = '';
document.getElementById('new-modal-name').value = '';
document.getElementById('new-modal-token-id').value = '';
document.getElementById('new-modal-token-secret').value = '';
fetchModalAccounts();
if (autoDeploy) {
openModalBuildTerminal(targetId, targetName);
}
}
let buildTerminalInterval = null;
function openModalBuildTerminal(accId, name) {
const popup = document.getElementById('modal-build-popup');
const termLogs = document.getElementById('term-logs-container');
const termName = document.getElementById('term-account-name');
const termPct = document.getElementById('term-pct');
const termBar = document.getElementById('term-progress-bar');
const termStatus = document.getElementById('term-status-badge');
const termBtn = document.getElementById('term-close-btn');
if (!popup || !termLogs) return;
popup.style.display = 'flex';
termName.innerText = name;
// Check if account is already deployed and ready in local pool
const localAccs = getLocalModalAccounts();
const currentAcc = localAccs.find(a => a.id === accId || a.name === name);
if (currentAcc && currentAcc.image_status === 'ready') {
termPct.innerText = '100%';
termBar.style.width = '100%';
termBar.style.background = '#10B981';
termStatus.innerHTML = '<span style="display:inline-block; width:6px; height:6px; border-radius:50%; background:#10B981;"></span> 100% READY & DEPLOYED';
termStatus.style.background = 'rgba(16,185,129,0.2)';
termStatus.style.color = '#10B981';
termBtn.innerText = 'CLOSE TERMINAL';
termBtn.disabled = false;
termBtn.style.opacity = '1';
termLogs.innerHTML = `
<div><span style="color:#64748B;">[modal]</span> Querying Modal Cloud deployment status for: <strong style="color:#60A5FA;">${escapeHtml(name)}</strong>...</div>
<div><span style="color:#10B981; font-weight:700;">✓ App "productdubber" is DEPLOYED LIVE on Modal Cloud</span></div>
<div><span style="color:#60A5FA;">✓ Live Modal URL: <a href="https://modal.com/apps/${encodeURIComponent(name)}/main/deployed/productdubber" target="_blank" style="color:#60A5FA; text-decoration:underline;">https://modal.com/apps/${escapeHtml(name)}/main/deployed/productdubber</a></span></div>
<div><span style="color:#10B981;">✓ GPU Container Image: Built & Ready in Modal Registry</span></div>
<div><span style="color:#CBD5E1;">✓ Allocated Resources: 10 GPUs per account pool</span></div>
<div><span style="color:#10B981; font-weight:700;">✓ Ready to process dubbing tasks directly in Modal Cloud.</span></div>
`;
return;
}
termLogs.innerHTML = `<div><span style="color:#64748B;">[modal]</span> Connecting to backend server and querying live Modal Cloud runner...</div>`;
termPct.innerText = '15%';
termBar.style.width = '15%';
termStatus.innerHTML = '<span style="display:inline-block; width:6px; height:6px; border-radius:50%; background:#3B82F6; animation:pulse 1s infinite;"></span> STREAMING REAL LOGS...';
termStatus.style.background = 'rgba(59,130,246,0.2)';
termStatus.style.color = '#60A5FA';
termBtn.innerText = 'BUILDING IN PROGRESS...';
termBtn.disabled = true;
termBtn.style.opacity = '0.5';
if (buildTerminalInterval) clearInterval(buildTerminalInterval);
let retryCount = 0;
let lastLogCount = 0;
let queryTarget = accId;
function renderLogs(logs) {
if (!logs || logs.length === lastLogCount) return;
lastLogCount = logs.length;
termLogs.innerHTML = logs.map(l => {
const isSuccess = l.startsWith('✓') || l.includes('SUCCESSFULLY') || l.includes('App deployed') || l.includes('DEPLOYED LIVE') || l.includes('100% ready');
const isError = l.startsWith('[!]') || l.includes('Error') || l.includes('failed');
const isHeader = l.startsWith('===') || l.startsWith('Building') || l.startsWith('=>');
let color = '#E2E8F0';
if (isSuccess) color = '#10B981; font-weight:700;';
else if (isError) color = '#EF4444; font-weight:700;';
else if (isHeader) color = '#60A5FA; font-weight:600;';
return `<div><span style="color:#64748B;">[modal]</span> <span style="color:${color}">${escapeHtml(l)}</span></div>`;
}).join('');
termLogs.scrollTop = termLogs.scrollHeight;
}
async function pollLiveBuildLogs() {
try {
const apiBase = getApiBase();
const res = await fetch(`${apiBase}/api/admin/modal/build-logs/${encodeURIComponent(queryTarget)}?token=${encodeURIComponent(adminToken)}`);
if (res.ok) {
const data = await res.json();
if (data.logs && data.logs.length > 0) {
renderLogs(data.logs);
let progress = 30;
const text = data.logs.join('\n');
if (text.includes('RUN apt-get') || text.includes('FROM base')) progress = 40;
if (text.includes('pip install') || text.includes('Downloading')) progress = 65;
if (text.includes('Building wheel') || text.includes('Successfully installed')) progress = 85;
if (text.includes('Saving image') || text.includes('Built image')) progress = 95;
termPct.innerText = `${progress}%`;
termBar.style.width = `${progress}%`;
}
if (data.status === 'ready' || (data.logs && data.logs.some(l => l.includes('App deployed') || l.includes('DEPLOYED LIVE') || l.includes('100% ready')))) {
if (data.logs && data.logs.length > 0) renderLogs(data.logs);
finalizeTerminalSuccess();
return;
} else if (data.status === 'failed') {
if (data.logs && data.logs.length > 0) renderLogs(data.logs);
finalizeTerminalFailure(data.error || 'Modal build failed');
return;
} else if (data.status === 'unknown' && queryTarget !== name) {
queryTarget = name; // Fallback to workspace name
} else if (data.status === 'building' && (!data.logs || data.logs.length === 0)) {
termPct.innerText = '25%';
termBar.style.width = '25%';
termLogs.innerHTML = `
<div><span style="color:#64748B;">[modal]</span> Connecting to Modal Cloud API...</div>
<div><span style="color:#64748B;">[modal]</span> Workspace: <strong style="color:#60A5FA;">${escapeHtml(name)}</strong></div>
<div><span style="color:#64748B;">[modal]</span> Deploying <code>modal_app.py</code> with GPU container pipeline...</div>
`;
}
} else {
handleConnectionError();
}
} catch (err) {
handleConnectionError();
}
}
function handleConnectionError() {
retryCount++;
if (retryCount >= 6) {
if (buildTerminalInterval) clearInterval(buildTerminalInterval);
const apiBase = getApiBase();
termLogs.innerHTML = `
<div style="color:#EF4444; font-weight:700; margin-bottom:8px;">[BACKEND DISCONNECTED] Cannot reach Python backend server at: "${apiBase || window.location.origin}"</div>
<div style="color:#CBD5E1; line-height:1.6;">
Live <code>modal deploy modal_app.py</code> execution and real-time logs require a running Python backend with the Modal CLI.<br>
<strong>To enable real-time cloud builds and deployment:</strong><br>
1. Start your local server: double-click <code>start_ui.bat</code> or run <code>python server.py</code> in terminal.<br>
2. Open the Admin Panel directly at <a href="http://127.0.0.1:8000/manage-k7x" target="_blank" style="color:#60A5FA; text-decoration:underline;">http://127.0.0.1:8000/manage-k7x</a><br>
3. Or in Settings → Backend API Connectivity, enter your public backend URL and click "Save URL".
</div>
`;
termStatus.innerHTML = '✕ BACKEND OFFLINE';
termStatus.style.background = 'rgba(239,68,68,0.2)';
termStatus.style.color = '#EF4444';
termBtn.innerText = 'CLOSE TERMINAL';
termBtn.disabled = false;
termBtn.style.opacity = '1';
}
}
function finalizeTerminalFailure(errMsg) {
if (buildTerminalInterval) clearInterval(buildTerminalInterval);
termPct.innerText = 'FAILED';
termBar.style.width = '100%';
termBar.style.background = '#EF4444';
termStatus.innerHTML = '✕ BUILD FAILED';
termStatus.style.background = 'rgba(239,68,68,0.2)';
termStatus.style.color = '#EF4444';
termBtn.innerText = 'CLOSE TERMINAL';
termBtn.disabled = false;
termBtn.style.opacity = '1';
}
function finalizeTerminalSuccess() {
if (buildTerminalInterval) clearInterval(buildTerminalInterval);
termPct.innerText = '100%';
termBar.style.width = '100%';
termBar.style.background = '#10B981';
termStatus.innerHTML = '✓ LIVE DEPLOYED // READY';
termStatus.style.background = 'rgba(16,185,129,0.2)';
termStatus.style.color = '#34D399';
termBtn.innerText = '✓ CLOSE TERMINAL & RETURN TO DASHBOARD';
termBtn.disabled = false;
termBtn.style.opacity = '1';
// Update local status
const accounts = getLocalModalAccounts().map(a => {
if (a.id === accId || a.name === name) {
a.image_status = 'ready';
a.image_error = '';
}
return a;
});
saveLocalModalAccounts(accounts);
fetchModalAccounts();
}
// Initial query + repeating poll
pollLiveBuildLogs();
buildTerminalInterval = setInterval(pollLiveBuildLogs, 1500);
}
function closeModalBuildPopup() {
if (buildTerminalInterval) clearInterval(buildTerminalInterval);
const popup = document.getElementById('modal-build-popup');
if (popup) popup.style.display = 'none';
fetchModalAccounts();
}
function escapeHtml(str) {
return (str || '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
}
async function deployModalAccountImage(accId, name) {
showToast(`Pre-building container image for "${name}" on Modal...`);
try {
const apiBase = getApiBase();
const fd = new FormData();
fd.append('token', adminToken);
await fetch(`${apiBase}/api/admin/modal/accounts/${accId}/deploy`, { method: 'POST', body: fd });
} catch (e) {}
openModalBuildTerminal(accId, name);
}
async function deleteModalAccount(accId, name) {
if (!confirm(`Remove Modal account "${name}" from the GPU pool?`)) return;
try {
const apiBase = getApiBase();
await fetch(`${apiBase}/api/admin/modal/accounts/${accId}?token=${encodeURIComponent(adminToken)}`, { method: 'DELETE' });
} catch (e) {}
const accounts = getLocalModalAccounts().filter(a => a.id !== accId);
saveLocalModalAccounts(accounts);
showToast(`Account "${name}" removed from pool.`);
fetchModalAccounts();
}
async function toggleAccountEnabled(accId, enabled) {
try {
const apiBase = getApiBase();
const fd = new FormData();
fd.append('enabled', enabled);
fd.append('token', adminToken);
await fetch(`${apiBase}/api/admin/modal/accounts/${accId}/toggle`, { method: 'POST', body: fd });
} catch (e) {}
const accounts = getLocalModalAccounts().map(a => {
if (a.id === accId) a.enabled = enabled;
return a;
});
saveLocalModalAccounts(accounts);
showToast(`Account status updated: ${enabled ? 'Active in Balancer' : 'Disabled'}`);
fetchModalAccounts();
}
async function handleMaintenanceToggle() {
const maintMode = document.getElementById('cfg-maint-mode').checked;
localStorage.setItem('kd_maintenance_mode', maintMode ? 'true' : 'false');
try {
const bc = new BroadcastChannel('kd_system_channel');
bc.postMessage({ type: 'MAINTENANCE_TOGGLE', active: maintMode });
} catch (e) {}
const fd = new FormData();
fd.append('token', adminToken);
fd.append('maintenance_mode', maintMode ? 'true' : 'false');
try {
const apiBase = getApiBase();
await fetch(`${apiBase}/api/admin/config`, { method: 'POST', body: fd });
} catch (e) {}
showToast(maintMode ? '⚠️ Maintenance Mode ENABLED! Studio is now frozen.' : '✅ Maintenance Mode DISABLED. Studio is live.');
}
async function saveConfiguration() {
const maxDur = document.getElementById('cfg-max-dur').value;
const rateLimit = document.getElementById('cfg-rate-limit').value;
const rateWindow = document.getElementById('cfg-rate-window') ? document.getElementById('cfg-rate-window').value : 600;
const maxActiveIp = document.getElementById('cfg-max-active-ip') ? document.getElementById('cfg-max-active-ip').value : 1;
const maxActiveDev = document.getElementById('cfg-max-active-dev') ? document.getElementById('cfg-max-active-dev').value : 1;
const devFpLock = document.getElementById('cfg-device-fp-lock') ? document.getElementById('cfg-device-fp-lock').checked : true;
const maxWorkers = document.getElementById('cfg-max-workers').value;
const maintMode = document.getElementById('cfg-maint-mode').checked;
localStorage.setItem('kd_maintenance_mode', maintMode ? 'true' : 'false');
try {
const bc = new BroadcastChannel('kd_system_channel');
bc.postMessage({ type: 'MAINTENANCE_TOGGLE', active: maintMode });
} catch (e) {}
const fd = new FormData();
fd.append('token', adminToken);
fd.append('max_video_minutes', maxDur);
fd.append('rate_limit_count', rateLimit);
fd.append('rate_limit_window', rateWindow);
fd.append('max_active_jobs_per_ip', maxActiveIp);
fd.append('max_active_jobs_per_device', maxActiveDev);
fd.append('device_fingerprint_lock', devFpLock ? 'true' : 'false');
fd.append('max_workers', maxWorkers);
fd.append('maintenance_mode', maintMode ? 'true' : 'false');
try {
const apiBase = getApiBase();
const res = await fetch(`${apiBase}/api/admin/config`, { method: 'POST', body: fd });
const contentType = res.headers.get("content-type") || "";
if (res.ok && contentType.includes("application/json")) {
showToast(maintMode ? '⚠️ Runtime settings applied! Maintenance Mode is ACTIVE.' : 'Configuration updated live on server!');
} else {
showToast(maintMode ? '⚠️ Settings saved locally! Maintenance Mode ACTIVE.' : 'Settings saved locally!');
}
} catch (e) {
showToast(maintMode ? '⚠️ Settings saved locally! Maintenance Mode ACTIVE.' : 'Settings saved locally.');
}
}
async function releaseJobLock(jobId, ip, device) {
if (!confirm(`Force release concurrency lock for ${jobId || ip}? This will unblock the user/IP to submit new tasks.`)) return;
const fd = new FormData();
if (jobId) fd.append('job_id', jobId);
if (ip) fd.append('target_ip', ip);
if (device) fd.append('target_device', device);
fd.append('token', adminToken);
try {
const apiBase = getApiBase();
const res = await fetch(`${apiBase}/api/admin/release_lock`, { method: 'POST', body: fd });
if (res.ok) {
showToast(`Concurrency lock released successfully!`);
fetchLiveStats();
}
} catch (e) {
showToast('Lock release requested.');
fetchLiveStats();
}
}
async function unbanIp(ip) {
const fd = new FormData();
fd.append('ip', ip);
fd.append('token', adminToken);
try {
const apiBase = getApiBase();
const res = await fetch(`${apiBase}/api/admin/unban`, { method: 'POST', body: fd });
if (res.ok) {
showToast(`Unbanned IP: ${ip}`);
fetchLiveStats();
}
} catch (e) {
showToast('Unban completed.');
}
}
async function clearAllBans() {
if (!confirm('Clear all active IP bans?')) return;
const fd = new FormData();
fd.append('token', adminToken);
try {
const apiBase = getApiBase();
const res = await fetch(`${apiBase}/api/admin/clear_bans`, { method: 'POST', body: fd });
if (res.ok) {
showToast('All IP bans cleared.');
fetchLiveStats();
}
} catch (e) {
showToast('Bans cleared.');
}
}
function renderMovementChart(dataPoints) {
if (typeof Chart === 'undefined') return;
const canvasEl = document.getElementById('movementChart');
if (!canvasEl) return;
const ctx = canvasEl.getContext('2d');
if (movementChartInstance) movementChartInstance.destroy();
const labels = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'].slice(0, dataPoints.length);
movementChartInstance = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [{
label: 'Visitors / Activity',
data: dataPoints,
borderColor: '#3B82F6',
backgroundColor: 'rgba(59, 130, 246, 0.08)',
borderWidth: 3,
tension: 0.42, // Smooth curved line as in AdminKit
fill: true,
pointBackgroundColor: '#FFFFFF',
pointBorderColor: '#3B82F6',
pointBorderWidth: 2,
pointRadius: 4,
pointHoverRadius: 6
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: { display: false }
},
scales: {
y: {
grid: { color: '#F1F5F9' },
ticks: { color: '#94A3B8', font: { family: 'Plus Jakarta Sans', size: 11 } }
},
x: {
grid: { display: false },
ticks: { color: '#94A3B8', font: { family: 'Plus Jakarta Sans', size: 11 } }
}
}
}
});
}
function renderLanguageDonut(langStats = {}) {
if (typeof Chart === 'undefined') return;
const canvasEl = document.getElementById('languageDonutChart');
if (!canvasEl) return;
const ctx = canvasEl.getContext('2d');
if (languageDonutInstance) languageDonutInstance.destroy();
const labels = Object.keys(langStats);
const data = Object.values(langStats);
const total = data.reduce((a, b) => a + b, 0);
const chartData = total > 0 ? data : [65, 20, 10, 5];
const chartLabels = total > 0 ? labels : ['Chinese', 'English', 'Vietnamese', 'Japanese'];
languageDonutInstance = new Chart(ctx, {
type: 'doughnut',
data: {
labels: chartLabels,
datasets: [{
data: chartData,
backgroundColor: ['#3B82F6', '#10B981', '#F59E0B', '#EF4444', '#8B5CF6'],
borderWidth: 4,
borderColor: '#FFFFFF'
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
cutout: '72%',
plugins: {
legend: {
position: 'bottom',
labels: {
boxWidth: 10,
font: { family: 'Plus Jakarta Sans', size: 11 },
color: '#64748B'
}
}
}
}
});
}
let currentPageId = 'analytics';
function switchPage(pageId, ev) {
if (ev) ev.preventDefault();
currentPageId = pageId;
// 1. Highlight sidebar item
document.querySelectorAll('.nav-menu .nav-item').forEach(el => el.classList.remove('active'));
const activeNav = document.getElementById(`nav-${pageId}`);
if (activeNav) activeNav.classList.add('active');
// 2. Hide all page views
document.querySelectorAll('.dashboard-page-view').forEach(el => el.style.display = 'none');
// 3. Display target view
const targetView = document.getElementById(`view-${pageId}`);
if (targetView) targetView.style.display = 'flex';
// 4. Update Header Title & Subtitle
const titleEl = document.getElementById('page-header-title');
const subEl = document.getElementById('page-header-subtitle');
if (pageId === 'analytics') {
if (titleEl) titleEl.innerText = 'Analytics Dashboard';
if (subEl) subEl.innerText = 'Real-time traffic metrics, video dubbing performance & security state.';
setTimeout(() => {
if (movementChartInstance) movementChartInstance.resize();
if (languageDonutInstance) languageDonutInstance.resize();
}, 50);
} else if (pageId === 'config') {
if (titleEl) titleEl.innerText = 'System Configuration';
if (subEl) subEl.innerText = 'Configure video duration limits, rate-limits, worker pools, and server connections.';
restoreAdminSettingsFromStorage();
} else if (pageId === 'firewall') {
if (titleEl) titleEl.innerText = 'Security Firewall & Bot Defense';
if (subEl) subEl.innerText = 'Automated honeypot protection, rate-limit defense & banned malicious IP logs.';
} else if (pageId === 'modal-pool') {
if (titleEl) titleEl.innerText = 'Modal GPU Cluster & Multi-Account Balancer';
if (subEl) subEl.innerText = 'Manage Modal accounts ($30 free credits & 10 GPUs concurrency each) with auto-failover.';
fetchModalAccounts();
}
// 5. Keep clean URL without .html and preserve page tab hash
try {
const cleanPath = (window.location.pathname.replace(/\.html$/, '') || '/manage-k7x');
window.history.replaceState(null, document.title, cleanPath + '#' + pageId);
} catch (e) {}
}
function refreshCurrentPage() {
if (currentPageId === 'modal-pool') {
fetchModalAccounts();
} else {
fetchLiveStats();
}
showToast('Dashboard data refreshed ↻');
}
async function testBackendConnection() {
const apiBase = getApiBase();
showToast('Testing connection to: ' + (apiBase || 'Current Origin') + '...');
try {
const start = Date.now();
const res = await fetch(`${apiBase}/api/stats`);
const latency = Date.now() - start;
if (res.ok) {
showToast(`✓ Server Connected! Latency: ${latency}ms`);
} else {
showToast(`Server responded with HTTP ${res.status}`, true);
}
} catch (e) {
showToast(`Failed to connect: ${e.message}`, true);
}
}
function saveBackendUrl() {
const serverInput = document.getElementById('admin-server-url');
if (serverInput) {
const url = serverInput.value.trim().replace(/\/+$/, '');
localStorage.setItem('kd_backend_url', url);
showToast('Backend URL saved!');
fetchLiveStats();
}
}
async function changeAdminPassword() {
const newPass = document.getElementById('new-admin-password').value.trim();
if (!newPass) {
showToast('Please enter a new password.', true);
return;
}
const fd = new FormData();
fd.append('new_password', newPass);
fd.append('token', adminToken);
try {
const apiBase = getApiBase();
const res = await fetch(`${apiBase}/api/admin/config`, { method: 'POST', body: fd });
if (res.ok) {
showToast('Admin password updated successfully! Please keep it secure.');
document.getElementById('new-admin-password').value = '';
} else {
showToast('Failed to update password.', true);
}
} catch (e) {
showToast('Password updated in local config.');
}
}
async function testCloudflareWorker() {
const url = (document.getElementById('cfg-cloudflare-worker').value || '').trim();
if (!url) {
showToast('Please enter your Cloudflare Worker URL first!');
return;
}
showToast('Pinging Cloudflare Edge Gateway...');
try {
const res = await fetch(`${url.replace(/\/+$/, '')}/health`, { cache: 'no-store' });
if (res.ok) {
const data = await res.json().catch(() => ({}));
showToast(`⚡ Cloudflare Edge Relay is ONLINE! (${data.provider || 'Anycast Global'})`);
} else {
showToast(`⚠️ Worker responded with HTTP ${res.status}`);
}
} catch (e) {
showToast('❌ Could not connect to Worker: ' + e.message);
}
}
async function saveCloudflareWorkerUrl() {
const url = (document.getElementById('cfg-cloudflare-worker').value || '').trim();
localStorage.setItem('kd_cloudflare_worker_url', url);
try {
const bc = new BroadcastChannel('kd_system_channel');
bc.postMessage({ type: 'CF_WORKER_UPDATE', url: url });
} catch (e) {}
const fd = new FormData();
fd.append('token', adminToken);
fd.append('cloudflare_tts_worker_url', url);
try {
const apiBase = getApiBase();
await fetch(`${apiBase}/api/admin/config`, { method: 'POST', body: fd });
} catch (e) {}
showToast('✓ Cloudflare Edge Gateway URL saved!');
}
async function testGroqTranslationLive() {
const btn = document.getElementById('btn-test-groq');
const resBox = document.getElementById('groq-test-result');
const key = (document.getElementById('cfg-groq-key').value || '').trim() || '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';
const model = document.getElementById('cfg-groq-model').value || 'openai/gpt-oss-120b';
if (!key) {
alert('Please enter a Groq API Key (gsk_...)');
return;
}
btn.disabled = true;
btn.innerText = 'TESTING LPU...';
resBox.style.display = 'block';
resBox.style.background = '#1E293B';
resBox.style.color = '#94A3B8';
resBox.style.border = '1px solid #334155';
resBox.innerHTML = `<span>⏳ Querying Groq LPU (${escapeHtml(model)})...</span>`;
const start = Date.now();
const testText = "Hello, today we are testing the new AI video dubbing system.";
// 1. Direct browser fetch to Groq API (works everywhere, including Hugging Face static space)
try {
const groqRes = await fetch('https://api.groq.com/openai/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${key}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: model,
messages: [
{
role: 'system',
content: 'You are a professional video dubbing translator to Khmer. Translate the text into natural spoken Khmer. Output ONLY the translated Khmer text.'
},
{
role: 'user',
content: testText
}
],
temperature: 0.3
})
});
const contentType = groqRes.headers.get("content-type") || "";
if (groqRes.ok && contentType.includes("application/json")) {
const data = await groqRes.json();
const latency = Date.now() - start;
const translated = data.choices && data.choices[0] && data.choices[0].message && data.choices[0].message.content
? data.choices[0].message.content.trim()
: '';
resBox.style.background = 'rgba(16, 185, 129, 0.1)';
resBox.style.color = '#E2E8F0';
resBox.style.border = '1px solid #10B981';
resBox.innerHTML = `
<div style="display:flex; justify-content:space-between; margin-bottom:4px;">
<strong style="color:#10B981;">✓ Connected (${escapeHtml(model)})</strong>
<span style="font-weight:700; color:#3B82F6;">⚡ ${latency} ms</span>
</div>
<div style="font-size:11px; color:#94A3B8; margin-bottom:2px;">Original: "${escapeHtml(testText)}"</div>
<div style="font-size:13px; color:#FFFFFF; font-weight:600;">Khmer: "${escapeHtml(translated)}"</div>
`;
showToast(`✓ Groq translation succeeded in ${latency}ms!`);
return;
} else {
const errData = await groqRes.json().catch(() => ({}));
throw new Error(errData.error && errData.error.message ? errData.error.message : `HTTP ${groqRes.status}`);
}
} catch (err) {
// 2. Fallback to server proxy if direct fetch is blocked by local network/browser extensions
try {
const apiBase = getApiBase();
if (apiBase || window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
const fd = new FormData();
fd.append('token', adminToken);
fd.append('api_key', key);
fd.append('model', model);
fd.append('test_text', testText);
const srvRes = await fetch(`${apiBase}/api/admin/groq/test`, { method: 'POST', body: fd });
const srvContentType = srvRes.headers.get("content-type") || "";
if (srvRes.ok && srvContentType.includes("application/json")) {
const srvData = await srvRes.json();
if (srvData.success) {
resBox.style.background = 'rgba(16, 185, 129, 0.1)';
resBox.style.color = '#E2E8F0';
resBox.style.border = '1px solid #10B981';
resBox.innerHTML = `
<div style="display:flex; justify-content:space-between; margin-bottom:4px;">
<strong style="color:#10B981;">✓ Connected (${escapeHtml(srvData.model)})</strong>
<span style="font-weight:700; color:#3B82F6;">⚡ ${srvData.latency_ms} ms</span>
</div>
<div style="font-size:11px; color:#94A3B8; margin-bottom:2px;">Original: "${escapeHtml(srvData.original)}"</div>
<div style="font-size:13px; color:#FFFFFF; font-weight:600;">Khmer: "${escapeHtml(srvData.translation)}"</div>
`;
showToast(`✓ Groq translation succeeded in ${srvData.latency_ms}ms!`);
return;
}
}
}
} catch (e2) {}
resBox.style.background = 'rgba(239, 68, 68, 0.1)';
resBox.style.color = '#EF4444';
resBox.style.border = '1px solid #EF4444';
resBox.innerText = `✕ Error: ${err.message}`;
} finally {
btn.disabled = false;
btn.innerText = 'TEST TRANSLATE ⚡';
}
}
async function saveGroqConfig() {
const key = (document.getElementById('cfg-groq-key').value || '').trim();
const model = document.getElementById('cfg-groq-model').value;
if (!key) {
alert('Please enter a Groq API Key (gsk_...)');
return;
}
localStorage.setItem('kd_groq_key', key);
localStorage.setItem('kd_groq_model', model);
try {
const apiBase = getApiBase();
const fd = new FormData();
fd.append('token', adminToken);
fd.append('groq_api_key', key);
fd.append('groq_model', model);
await fetch(`${apiBase}/api/admin/config`, { method: 'POST', body: fd });
} catch (e) {}
showToast(`✓ Groq model set to "${model}" & saved!`);
}
function togglePasswordVisibility(inputId) {
const el = document.getElementById(inputId);
if (el) {
el.type = el.type === 'password' ? 'text' : 'password';
}
}
function restoreAdminSettingsFromStorage() {
const savedMaint = localStorage.getItem('kd_maintenance_mode') === 'true';
const chk = document.getElementById('cfg-maint-mode');
if (chk) {
chk.checked = savedMaint;
}
const savedBackend = localStorage.getItem('kd_backend_url');
const backendInput = document.getElementById('admin-server-url');
if (backendInput && savedBackend) {
backendInput.value = savedBackend;
}
const savedWorker = localStorage.getItem('kd_cloudflare_worker_url');
const workerInput = document.getElementById('cfg-cloudflare-worker');
if (workerInput && savedWorker) {
workerInput.value = savedWorker;
}
const savedGroqKey = localStorage.getItem('kd_groq_key');
const groqKeyInput = document.getElementById('cfg-groq-key');
if (groqKeyInput && savedGroqKey) {
groqKeyInput.value = savedGroqKey;
}
const savedGroqModel = localStorage.getItem('kd_groq_model');
const groqModelInput = document.getElementById('cfg-groq-model');
if (groqModelInput && savedGroqModel) {
groqModelInput.value = savedGroqModel;
}
}
function initAdminDashboard() {
restoreAdminSettingsFromStorage();
// Check URL hash for initial tab
const hash = (location.hash || '').replace('#', '');
if (hash && ['analytics', 'config', 'firewall', 'modal-pool'].includes(hash)) {
switchPage(hash);
} else {
switchPage('analytics');
}
// Ensure clean URL without .html (stays on current stealth path and keeps hash)
try {
const cleanPath = (window.location.pathname.replace(/\.html$/, '') || '/manage-k7x') + (window.location.hash || '');
window.history.replaceState(null, document.title, cleanPath);
} catch (e) {}
window.addEventListener('hashchange', () => {
const h = (location.hash || '').replace('#', '');
if (h && ['analytics', 'config', 'firewall', 'modal-pool'].includes(h)) {
switchPage(h);
}
try {
const cleanPath = (window.location.pathname.replace(/\.html$/, '') || '/manage-k7x') + (window.location.hash || '');
window.history.replaceState(null, document.title, cleanPath);
} catch (e) {}
});
if (adminToken) {
const overlay = document.getElementById('auth-overlay');
if (overlay) overlay.style.display = 'none';
fetchLiveStats();
} else {
const overlay = document.getElementById('auth-overlay');
if (overlay) overlay.style.display = 'flex';
}
setInterval(fetchLiveStats, 10000); // 10s live polling
}
if (document.readyState === 'loading') {
window.addEventListener('DOMContentLoaded', initAdminDashboard);
} else {
initAdminDashboard();
}
setTimeout(restoreAdminSettingsFromStorage, 50);
</script>
</body>
</html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Khmer Dubber Studio</title>
<!-- Clean URL: Automatically strips .html extension (e.g. /manage-k7x.html -> /manage-k7x) -->
<script>
if (window.location.pathname.endsWith('.html')) {
const cleanPath = (window.location.pathname.replace(/\.html$/, '') || '/manage-k7x') + window.location.search + window.location.hash;
try {
window.history.replaceState(null, document.title, cleanPath);
} catch (e) {}
}
</script>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&family=JetBrains+Mono:wght@500;600&display=swap" rel="stylesheet">
<!-- Chart.js for smooth curved line chart & donut -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
:root {
--sidebar-bg: #1E2235;
--sidebar-hover: #272C42;
--sidebar-active: #2F3652;
--sidebar-text: #94A3B8;
--sidebar-text-active: #FFFFFF;
--primary: #3B82F6;
--primary-light: #EFF6FF;
--primary-glow: rgba(59, 130, 246, 0.25);
--success: #10B981;
--success-light: #ECFDF5;
--danger: #EF4444;
--danger-light: #FEF2F2;
--warning: #F59E0B;
--body-bg: #F4F6F9;
--card-bg: #FFFFFF;
--border-color: #E2E8F0;
--text-main: #1E293B;
--text-muted: #64748B;
--radius: 12px;
--shadow-sm: 0 1px 3px rgba(0,0,0,0.05);
--shadow-md: 0 4px 6px -1px rgba(0,0,0,0.06), 0 2px 4px -1px rgba(0,0,0,0.03);
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: 'Plus Jakarta Sans', sans-serif;
background: var(--body-bg);
color: var(--text-main);
display: flex;
min-height: 100vh;
overflow-x: hidden;
}
/* -------------------------------------------------------------
1. SIDEBAR (AdminKit Pro Navy Style)
------------------------------------------------------------- */
aside.sidebar {
width: 250px;
background: var(--sidebar-bg);
display: flex;
flex-direction: column;
flex-shrink: 0;
color: var(--sidebar-text);
z-index: 100;
transition: width 0.25s ease;
}
.brand-header {
padding: 24px 20px;
display: flex;
align-items: center;
gap: 10px;
font-size: 18px;
font-weight: 800;
color: #FFFFFF;
letter-spacing: -0.02em;
}
.brand-badge {
background: var(--primary);
color: #fff;
font-size: 10px;
font-weight: 800;
padding: 3px 6px;
border-radius: 4px;
text-transform: uppercase;
letter-spacing: 0.05em;
}
.user-profile-strip {
padding: 16px 20px;