Hydui commited on
Commit
2d4f33c
·
verified ·
1 Parent(s): 223dc78

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +947 -83
app.py CHANGED
@@ -1,94 +1,958 @@
1
- import gradio as gr
2
- import requests
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  import os
4
- from pytrends.request import TrendReq
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- YT_API_KEY = os.getenv("YT_API_KEY", "AIzaSyCy8ROvJzi5DrBV-7PbwWq7QQ4w0e_F8rU")
 
 
 
 
 
 
7
 
8
- def get_video_id(url):
9
- """यह फंक्शन अब दोनों तरह के लिंक को सपोर्ट करेगा"""
10
- if "v=" in url:
11
- return url.split("v=")[1].split("&")[0]
12
- elif "youtu.be/" in url:
13
- return url.split("youtu.be/")[1].split("?")[0]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  return None
15
 
16
- def get_video_stats(video_id):
17
- url = f"https://www.googleapis.com/youtube/v3/videos?part=snippet,statistics&id={video_id}&key={YT_API_KEY}"
18
- response = requests.get(url)
19
- data = response.json()
20
- if "items" in data and data["items"]:
21
- return data["items"][0]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  return None
23
 
24
- def get_trending_trends(niche):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  try:
26
- pytrends = TrendReq(hl='en-US', tz=360)
27
- pytrends.build_payload(kw_list=[niche], timeframe='now 7-d')
28
- trends = pytrends.interest_over_time()
29
- top_keywords = trends.sort_values(by=niche, ascending=False).head(3).index.tolist()
30
- return top_keywords
31
- except:
32
- return ["AI Trends 2026", "Tech", "Gadgets"]
33
-
34
- def boost_video(video_url):
35
- if not video_url:
36
- return "❌ कृपया वैलिड YouTube लिंक डालें!"
37
-
38
- video_id = get_video_id(video_url)
39
- if not video_id:
40
- return "❌ अमान्य YouTube लिंक! (कृपया सही लिंक डालें)"
41
-
42
- data = get_video_stats(video_id)
43
- if not data:
44
- return "❌ वीडियो नहीं मिला! वीडियो पब्लिक है और API Key सही है चेक करें।"
45
-
46
- snippet = data["snippet"]
47
- stats = data["statistics"]
48
- title = snippet["title"]
49
- channel = snippet["channelTitle"]
50
- views = int(stats.get("viewCount", 0))
51
- likes = int(stats.get("likeCount", 0))
52
- comments = int(stats.get("commentCount", 0))
53
-
54
- niche = title.split()[0] if title else "General"
55
- trends = get_trending_trends(niche)
56
- ctr_pred = round(len(title) * 0.5 + 5, 1)
57
-
58
- report = f"""
59
- 🚀 **यूट्यूब बूस्ट रिपोर्ट**
60
-
61
- 📺 **टाइटल:** {title}
62
- 🎥 **चैनल:** {channel}
63
- 👁️ **व्यूज़:** {views:,}
64
- 👍 **लाइक्स:** {likes:,}
65
- 💬 **कमेंट्स:** {comments:,}
66
- 📈 **CTR प्रेडिक्शन:** {ctr_pred}%
67
- 🔥 **ट्रेंडिंग टॉपिक्स:** {", ".join(trends)}
68
-
69
- 🛠️ **बूस्ट प्लान:**
70
- 1. टाइटल में "{trends[0] if trends else 'Trending'}" जोड़ें
71
- 2. थंबनेल को लाल/हाइ-कंट्रास्ट बनाएँ
72
- 3. रिटेंशन बढ़ाने के लिए बीच में प्रश्न डालें
73
- 4. रात 8:30–10:00 PM (IST) पर अपलोड करें
74
- 5. पहले 2 घंटे में 5-6 रियल कमेंट करें
 
 
 
 
 
 
 
 
 
 
 
75
  """
76
-
77
- return report
78
-
79
- with gr.Blocks() as demo:
80
- gr.Markdown("## 🚀 YouTube वीडियो बूस्ट टूल (Gradio)")
81
- gr.Markdown("नीचे अपना YouTube लिंक डालें और 'बूस्ट करें' पर क्लिक करें।")
82
-
83
- with gr.Row():
84
- with gr.Column(scale=3):
85
- video_url = gr.Textbox(label="YouTube लिंक", placeholder="https://www.youtube.com/watch?v=... या https://youtu.be/...")
86
- with gr.Column(scale=1):
87
- btn = gr.Button("🚀 बूस्ट करें", variant="primary")
88
-
89
- output = gr.Markdown(label="बूस्ट रिपोर्ट")
90
-
91
- btn.click(fn=boost_video, inputs=video_url, outputs=output)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
 
93
  if __name__ == "__main__":
94
- demo.launch(theme=gr.themes.Soft())
 
1
+ """Audio Cleanup Studio – a Gradio Space with real audio processing and private history.
2
+
3
+ Deployment secrets and storage:
4
+ - ADMIN_ACCESS_CODE: required to unlock the administrator archive.
5
+ - DATA_DIR: optional persistent mounted directory; uses /data automatically when available.
6
+ - HISTORY_RETENTION_DAYS: number of days to retain private audio artifacts (default: 30; 0 disables expiry).
7
+ - MAX_AUDIO_MINUTES: maximum accepted input duration for costly operations (default: 15).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import datetime as dt
13
+ import hmac
14
+ import json
15
+ import math
16
  import os
17
+ import queue
18
+ import secrets
19
+ import shutil
20
+ import sqlite3
21
+ import subprocess
22
+ import sys
23
+ import threading
24
+ import time
25
+ import uuid
26
+ from pathlib import Path
27
+ from typing import Generator, Iterable
28
+
29
+ import gradio as gr
30
+ from pydub import AudioSegment, effects
31
+ from pydub.silence import split_on_silence
32
+
33
+ try:
34
+ import spaces # Hugging Face ZeroGPU runtime; optional for local CPU runs.
35
+ except ImportError:
36
+ spaces = None
37
+
38
+
39
+ # -----------------------------------------------------------------------------
40
+ # Runtime configuration
41
+ # -----------------------------------------------------------------------------
42
+ APP_ROOT = Path(__file__).resolve().parent
43
+ DEFAULT_DATA_DIR = Path("/data") if Path("/data").exists() else APP_ROOT / "data"
44
+ DATA_DIR = Path(os.getenv("DATA_DIR", str(DEFAULT_DATA_DIR))).expanduser().resolve()
45
+ TMP_DIR = DATA_DIR / "tmp"
46
+ HISTORY_DIR = DATA_DIR / "audio_history"
47
+ DB_PATH = DATA_DIR / "audio_history.sqlite3"
48
+
49
+ HISTORY_RETENTION_DAYS = int(os.getenv("HISTORY_RETENTION_DAYS", "30"))
50
+ MAX_AUDIO_MINUTES = float(os.getenv("MAX_AUDIO_MINUTES", "15"))
51
+ MAX_AUDIO_SECONDS = MAX_AUDIO_MINUTES * 60
52
+ MAX_FILE_BYTES = int(os.getenv("MAX_FILE_BYTES", str(500 * 1024 * 1024)))
53
+ PROCESS_TIMEOUT_SECONDS = int(os.getenv("PROCESS_TIMEOUT_SECONDS", "5400"))
54
+ ADMIN_SESSION_TTL_SECONDS = int(os.getenv("ADMIN_SESSION_TTL_SECONDS", "1800"))
55
+
56
+ for directory in (DATA_DIR, TMP_DIR, HISTORY_DIR):
57
+ directory.mkdir(parents=True, exist_ok=True)
58
+
59
+ DB_LOCK = threading.Lock()
60
+ ADMIN_SESSIONS: dict[str, float] = {}
61
+
62
+
63
+ # -----------------------------------------------------------------------------
64
+ # Storage and history
65
+ # -----------------------------------------------------------------------------
66
+ def utc_now() -> str:
67
+ return dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
68
+
69
+
70
+ def epoch_now() -> float:
71
+ return time.time()
72
+
73
+
74
+ def db_connection() -> sqlite3.Connection:
75
+ connection = sqlite3.connect(DB_PATH, timeout=20)
76
+ connection.row_factory = sqlite3.Row
77
+ return connection
78
+
79
+
80
+ def initialise_database() -> None:
81
+ with DB_LOCK, db_connection() as connection:
82
+ connection.execute(
83
+ """
84
+ CREATE TABLE IF NOT EXISTS jobs (
85
+ job_id TEXT PRIMARY KEY,
86
+ public_filename TEXT NOT NULL,
87
+ operation TEXT NOT NULL,
88
+ status TEXT NOT NULL,
89
+ created_at TEXT NOT NULL,
90
+ created_ts REAL NOT NULL,
91
+ completed_at TEXT,
92
+ duration_seconds REAL,
93
+ processing_seconds REAL,
94
+ details TEXT,
95
+ storage_dir TEXT,
96
+ stored_files TEXT
97
+ )
98
+ """
99
+ )
100
+ connection.execute(
101
+ """
102
+ CREATE TABLE IF NOT EXISTS visitors (
103
+ visitor_id TEXT PRIMARY KEY,
104
+ first_seen_ts REAL NOT NULL,
105
+ last_seen_ts REAL NOT NULL
106
+ )
107
+ """
108
+ )
109
+ connection.commit()
110
+
111
+
112
+ def record_job_started(job_id: str, filename: str, operation: str, duration: float) -> None:
113
+ with DB_LOCK, db_connection() as connection:
114
+ connection.execute(
115
+ """
116
+ INSERT INTO jobs (job_id, public_filename, operation, status, created_at, created_ts, duration_seconds)
117
+ VALUES (?, ?, ?, 'Processing', ?, ?, ?)
118
+ """,
119
+ (job_id, filename, operation, utc_now(), epoch_now(), duration),
120
+ )
121
+ connection.commit()
122
+
123
+
124
+ def record_job_finished(
125
+ job_id: str,
126
+ status: str,
127
+ processing_seconds: float,
128
+ details: str,
129
+ storage_dir: Path | None = None,
130
+ stored_files: list[Path] | None = None,
131
+ ) -> None:
132
+ files = [str(path) for path in (stored_files or [])]
133
+ with DB_LOCK, db_connection() as connection:
134
+ connection.execute(
135
+ """
136
+ UPDATE jobs
137
+ SET status = ?, completed_at = ?, processing_seconds = ?, details = ?, storage_dir = ?, stored_files = ?
138
+ WHERE job_id = ?
139
+ """,
140
+ (
141
+ status,
142
+ utc_now(),
143
+ processing_seconds,
144
+ details[:1000],
145
+ str(storage_dir) if storage_dir else None,
146
+ json.dumps(files),
147
+ job_id,
148
+ ),
149
+ )
150
+ connection.commit()
151
+
152
+
153
+ def purge_expired_history() -> None:
154
+ """Remove expired private artifacts and their records. Zero keeps all records."""
155
+ if HISTORY_RETENTION_DAYS <= 0:
156
+ return
157
+ cutoff = epoch_now() - (HISTORY_RETENTION_DAYS * 86400)
158
+ with DB_LOCK, db_connection() as connection:
159
+ stale_rows = connection.execute(
160
+ "SELECT job_id, storage_dir FROM jobs WHERE created_ts < ?", (cutoff,)
161
+ ).fetchall()
162
+ for row in stale_rows:
163
+ storage_dir = row["storage_dir"]
164
+ if storage_dir:
165
+ candidate = Path(storage_dir).resolve()
166
+ if candidate.is_relative_to(HISTORY_DIR.resolve()):
167
+ shutil.rmtree(candidate, ignore_errors=True)
168
+ connection.execute("DELETE FROM jobs WHERE created_ts < ?", (cutoff,))
169
+ connection.commit()
170
+
171
+
172
+ def recent_public_history(limit: int = 25) -> tuple[str, list[list[str]]]:
173
+ with DB_LOCK, db_connection() as connection:
174
+ completed = connection.execute(
175
+ "SELECT COUNT(*) AS count FROM jobs WHERE status = 'Completed'"
176
+ ).fetchone()["count"]
177
+ rows = connection.execute(
178
+ """
179
+ SELECT public_filename, operation, status, COALESCE(completed_at, created_at) AS activity_at
180
+ FROM jobs
181
+ ORDER BY created_ts DESC
182
+ LIMIT ?
183
+ """,
184
+ (limit,),
185
+ ).fetchall()
186
+ table = [[row["public_filename"], row["operation"], row["status"], row["activity_at"]] for row in rows]
187
+ stats = (
188
+ f"<div class='stats-card'><b>{completed}</b> successful processing job(s) completed. "
189
+ "This count represents jobs, not verified unique people. Only filenames and selected actions are public; "
190
+ "uploaded and processed audio remain administrator-only.</div>"
191
+ )
192
+ return stats, table
193
+
194
+
195
+ def visitor_heartbeat(request: gr.Request | None = None) -> tuple[int, int]:
196
+ """Track anonymous Gradio sessions and return active and total visitors.
197
+
198
+ The browser's Gradio session hash is used only as a short-lived anonymous
199
+ visitor identifier. No IP address, filename, audio, or account data is
200
+ stored. A visitor is considered active if the last heartbeat was within
201
+ the last 90 seconds; the HTML client sends a heartbeat every 15 seconds.
202
+ """
203
+ visitor_id = getattr(request, "session_hash", None) or "anonymous-session"
204
+ now = epoch_now()
205
+ with DB_LOCK, db_connection() as connection:
206
+ connection.execute(
207
+ """
208
+ INSERT INTO visitors (visitor_id, first_seen_ts, last_seen_ts)
209
+ VALUES (?, ?, ?)
210
+ ON CONFLICT(visitor_id) DO UPDATE SET last_seen_ts = excluded.last_seen_ts
211
+ """,
212
+ (visitor_id, now, now),
213
+ )
214
+ active = connection.execute(
215
+ "SELECT COUNT(*) AS count FROM visitors WHERE last_seen_ts >= ?",
216
+ (now - 90,),
217
+ ).fetchone()["count"]
218
+ total = connection.execute("SELECT COUNT(*) AS count FROM visitors").fetchone()["count"]
219
+ connection.commit()
220
+ return int(active), int(total)
221
+
222
+
223
+ def register_visitor(request: gr.Request | None = None) -> tuple[int, int]:
224
+ """Backward-compatible alias for clients using the old endpoint name."""
225
+ return visitor_heartbeat(request)
226
+
227
+
228
+ def admin_rows(limit: int = 100) -> list[list[str]]:
229
+ with DB_LOCK, db_connection() as connection:
230
+ rows = connection.execute(
231
+ """
232
+ SELECT job_id, public_filename, operation, status, created_at,
233
+ COALESCE(completed_at, '—') AS completed_at,
234
+ COALESCE(processing_seconds, 0) AS processing_seconds
235
+ FROM jobs
236
+ ORDER BY created_ts DESC
237
+ LIMIT ?
238
+ """,
239
+ (limit,),
240
+ ).fetchall()
241
+ return [
242
+ [
243
+ row["job_id"],
244
+ row["public_filename"],
245
+ row["operation"],
246
+ row["status"],
247
+ row["created_at"],
248
+ row["completed_at"],
249
+ f"{row['processing_seconds']:.1f}s" if row["processing_seconds"] else "—",
250
+ ]
251
+ for row in rows
252
+ ]
253
+
254
+
255
+ def admin_job_choices() -> list[tuple[str, str]]:
256
+ with DB_LOCK, db_connection() as connection:
257
+ rows = connection.execute(
258
+ """
259
+ SELECT job_id, public_filename, operation, COALESCE(completed_at, created_at) AS activity_at
260
+ FROM jobs
261
+ WHERE status = 'Completed'
262
+ ORDER BY created_ts DESC
263
+ LIMIT 100
264
+ """
265
+ ).fetchall()
266
+ return [
267
+ (f"{row['activity_at']} · {row['public_filename']} · {row['operation']}", row["job_id"])
268
+ for row in rows
269
+ ]
270
+
271
+
272
+ def private_archive(job_id: str, original: Path, outputs: Iterable[Path]) -> tuple[Path, list[Path]]:
273
+ archive_dir = (HISTORY_DIR / job_id).resolve()
274
+ archive_dir.mkdir(parents=True, exist_ok=True)
275
+ copied: list[Path] = []
276
+ artifacts = [(original, "original"), *[(path, "result") for path in outputs]]
277
+ for source, prefix in artifacts:
278
+ source = Path(source)
279
+ if not source.exists():
280
+ continue
281
+ destination = archive_dir / f"{prefix}_{safe_filename(source.name)}"
282
+ shutil.copy2(source, destination)
283
+ copied.append(destination)
284
+ return archive_dir, copied
285
+
286
+
287
+ # -----------------------------------------------------------------------------
288
+ # Authentication for the private admin panel
289
+ # -----------------------------------------------------------------------------
290
+ def clean_admin_sessions() -> None:
291
+ now = epoch_now()
292
+ for token, expires_at in list(ADMIN_SESSIONS.items()):
293
+ if expires_at <= now:
294
+ ADMIN_SESSIONS.pop(token, None)
295
+
296
+
297
+ def is_valid_admin_session(token: str | None) -> bool:
298
+ clean_admin_sessions()
299
+ return bool(token and ADMIN_SESSIONS.get(token, 0) > epoch_now())
300
+
301
+
302
+ def unlock_admin(access_code: str) -> tuple[str | None, str, list[list[str]], gr.Dropdown]:
303
+ configured_code = os.getenv("ADMIN_ACCESS_CODE", "")
304
+ if not configured_code:
305
+ return None, "Admin archive is disabled: set the `ADMIN_ACCESS_CODE` Space Secret first.", [], gr.update(choices=[], value=None)
306
+ if not access_code or not hmac.compare_digest(access_code, configured_code):
307
+ return None, "Incorrect access code.", [], gr.update(choices=[], value=None)
308
+
309
+ token = secrets.token_urlsafe(32)
310
+ ADMIN_SESSIONS[token] = epoch_now() + ADMIN_SESSION_TTL_SECONDS
311
+ choices = admin_job_choices()
312
+ return token, "Admin archive unlocked for this browser session.", admin_rows(), gr.update(choices=choices, value=choices[0][1] if choices else None)
313
+
314
+
315
+ def refresh_admin_history(token: str | None) -> tuple[str, list[list[str]], gr.Dropdown]:
316
+ if not is_valid_admin_session(token):
317
+ return "Access code required or session expired.", [], gr.update(choices=[], value=None)
318
+ choices = admin_job_choices()
319
+ return "Private archive refreshed.", admin_rows(), gr.update(choices=choices, value=choices[0][1] if choices else None)
320
+
321
+
322
+ def get_private_job_files(job_id: str | None, token: str | None) -> tuple[str, list[str] | None]:
323
+ if not is_valid_admin_session(token):
324
+ return "Access code required or session expired.", None
325
+ if not job_id:
326
+ return "Choose an archived completed job.", None
327
+ with DB_LOCK, db_connection() as connection:
328
+ row = connection.execute("SELECT stored_files FROM jobs WHERE job_id = ?", (job_id,)).fetchone()
329
+ if not row or not row["stored_files"]:
330
+ return "No private artifacts are available for this job.", None
331
+ history_root = HISTORY_DIR.resolve()
332
+ files = []
333
+ for file_name in json.loads(row["stored_files"]):
334
+ candidate = Path(file_name).resolve()
335
+ if candidate.is_relative_to(history_root) and candidate.is_file():
336
+ files.append(str(candidate))
337
+ return (f"Loaded {len(files)} private artifact(s).", files or None)
338
+
339
+
340
+ # -----------------------------------------------------------------------------
341
+ # Audio helpers
342
+ # -----------------------------------------------------------------------------
343
+ def safe_filename(name: str) -> str:
344
+ stem = "".join(char if char.isalnum() or char in "-_" else "_" for char in Path(name).stem)
345
+ stem = "_".join(filter(None, stem.split("_"))) or "audio"
346
+ return f"{stem[:80]}{Path(name).suffix.lower() or '.wav'}"
347
+
348
+
349
+ def make_job_directory(job_id: str) -> Path:
350
+ path = (TMP_DIR / job_id).resolve()
351
+ path.mkdir(parents=True, exist_ok=True)
352
+ return path
353
+
354
+
355
+ def copy_input_to_job(file_path: str, job_dir: Path) -> Path:
356
+ source = Path(file_path).resolve()
357
+ if not source.is_file():
358
+ raise FileNotFoundError("Uploaded audio file is no longer available. Please upload it again.")
359
+ if source.stat().st_size > MAX_FILE_BYTES:
360
+ raise ValueError(f"File is larger than the {MAX_FILE_BYTES // (1024 * 1024)} MB limit.")
361
+ destination = job_dir / f"input_{safe_filename(source.name)}"
362
+ shutil.copy2(source, destination)
363
+ return destination
364
+
365
+
366
+ def audio_duration(file_path: Path | str) -> float:
367
+ return len(AudioSegment.from_file(file_path)) / 1000.0
368
+
369
+
370
+ def validate_duration(duration: float) -> None:
371
+ if duration <= 0:
372
+ raise ValueError("The uploaded audio has no playable duration.")
373
+ if duration > MAX_AUDIO_SECONDS:
374
+ raise ValueError(
375
+ f"This audio is {duration / 60:.1f} minutes. The current limit is {MAX_AUDIO_MINUTES:g} minutes per job."
376
+ )
377
+
378
+
379
+ def format_seconds(value: float) -> str:
380
+ value = max(0, int(round(value)))
381
+ if value < 60:
382
+ return f"about {value}s"
383
+ return f"about {value // 60}m {value % 60:02d}s"
384
+
385
 
386
+ def estimated_seconds(operation: str, duration: float, quality: str = "") -> float:
387
+ if operation == "Remove silence":
388
+ return max(3, duration * 0.06 + 3)
389
+ if operation == "Enhance audio":
390
+ return max(15, duration * 0.65 + 15)
391
+ multiplier = 1.5 if quality == "htdemucs" else 0.9
392
+ return max(35, duration * multiplier + 35)
393
 
394
+
395
+ def ffmpeg_convert_to_wav(source: Path, destination: Path, sample_rate: int = 48000, mono: bool = True) -> None:
396
+ command = [
397
+ "ffmpeg", "-y", "-hide_banner", "-loglevel", "error", "-i", str(source),
398
+ "-ar", str(sample_rate), "-c:a", "pcm_s16le",
399
+ ]
400
+ if mono:
401
+ command.extend(["-ac", "1"])
402
+ command.append(str(destination))
403
+ completed = subprocess.run(command, capture_output=True, text=True, timeout=300, check=False)
404
+ if completed.returncode != 0:
405
+ error = completed.stderr.strip() or "FFmpeg could not decode this audio file."
406
+ raise RuntimeError(error[-500:])
407
+
408
+
409
+ def remove_silence_audio(source: Path, destination: Path, keep_silence_ms: int) -> tuple[float, float, float]:
410
+ sound = AudioSegment.from_file(source)
411
+ before = len(sound) / 1000.0
412
+ if sound.dBFS == float("-inf"):
413
+ raise ValueError("The uploaded file is completely silent.")
414
+
415
+ # Adapts to the source loudness while staying in a safe range for normal speech/music.
416
+ threshold = max(-55.0, min(-25.0, sound.dBFS - 18.0))
417
+ chunks = split_on_silence(
418
+ sound,
419
+ min_silence_len=120,
420
+ silence_thresh=threshold,
421
+ keep_silence=max(0, keep_silence_ms),
422
+ )
423
+ if not chunks:
424
+ raise ValueError("No non-silent audio could be found using the selected silence setting.")
425
+
426
+ combined = AudioSegment.empty()
427
+ for chunk in chunks:
428
+ combined += chunk
429
+ combined.export(destination, format="wav")
430
+ after = len(combined) / 1000.0
431
+ return before, after, threshold
432
+
433
+
434
+ def spectral_denoise_fallback(source: Path, destination: Path, strength: str) -> None:
435
+ """A real, audible fallback when DeepFilterNet cannot initialise."""
436
+ import numpy as np
437
+ import noisereduce as nr
438
+ from scipy.signal import butter, sosfiltfilt
439
+
440
+ sound = AudioSegment.from_file(source).set_sample_width(2)
441
+ sample_rate = sound.frame_rate
442
+ samples = np.asarray(sound.get_array_of_samples(), dtype=np.float32)
443
+ channels = sound.channels
444
+ if channels > 1:
445
+ samples = samples.reshape((-1, channels)).T
446
+ else:
447
+ samples = samples[None, :]
448
+ samples /= 32768.0
449
+
450
+ prop_decrease = {"Light": 0.65, "Balanced": 0.82, "Strong": 0.95}.get(strength, 0.82)
451
+ cleaned_channels = []
452
+ sos = butter(4, 80, btype="highpass", fs=sample_rate, output="sos")
453
+ for channel in samples:
454
+ denoised = nr.reduce_noise(
455
+ y=channel,
456
+ sr=sample_rate,
457
+ stationary=False,
458
+ prop_decrease=prop_decrease,
459
+ n_fft=min(2048, max(512, 2 ** int(math.log2(max(512, len(channel) // 16))))),
460
+ )
461
+ cleaned_channels.append(sosfiltfilt(sos, denoised))
462
+ result = np.vstack(cleaned_channels).T if channels > 1 else cleaned_channels[0]
463
+ result = np.clip(result, -1.0, 1.0)
464
+ pcm = (result * 32767).astype(np.int16)
465
+ if channels > 1:
466
+ pcm = pcm.reshape(-1)
467
+ enhanced = AudioSegment(pcm.tobytes(), frame_rate=sample_rate, sample_width=2, channels=channels)
468
+ enhanced = effects.normalize(enhanced, headroom=1.0)
469
+ enhanced.export(destination, format="wav")
470
+
471
+
472
+ def find_deepfilter_command() -> str | None:
473
+ for executable in ("deepFilter", "deep-filter"):
474
+ found = shutil.which(executable)
475
+ if found:
476
+ return found
477
  return None
478
 
479
+
480
+ def preferred_torch_device() -> str:
481
+ """Use the RTX device when the Space has been assigned one."""
482
+ try:
483
+ import torch
484
+ return "cuda" if torch.cuda.is_available() else "cpu"
485
+ except Exception:
486
+ return "cpu"
487
+
488
+
489
+ def subprocess_progress(
490
+ command: list[str],
491
+ estimate: float,
492
+ label: str,
493
+ cwd: Path | None = None,
494
+ ) -> Generator[tuple[str, float], None, None]:
495
+ """Yield elapsed-time updates while a model subprocess is running."""
496
+ process = subprocess.Popen(
497
+ command,
498
+ cwd=str(cwd) if cwd else None,
499
+ stdout=subprocess.PIPE,
500
+ stderr=subprocess.STDOUT,
501
+ text=True,
502
+ bufsize=1,
503
+ )
504
+ lines: queue.Queue[str] = queue.Queue()
505
+
506
+ def reader() -> None:
507
+ if process.stdout is None:
508
+ return
509
+ for line in iter(process.stdout.readline, ""):
510
+ if line.strip():
511
+ lines.put(line.strip())
512
+
513
+ threading.Thread(target=reader, daemon=True).start()
514
+ started = time.monotonic()
515
+ output_lines: list[str] = []
516
+ last_yield = 0.0
517
+ while process.poll() is None:
518
+ while True:
519
+ try:
520
+ output_lines.append(lines.get_nowait())
521
+ except queue.Empty:
522
+ break
523
+ elapsed = time.monotonic() - started
524
+ if elapsed - last_yield >= 1.0:
525
+ remaining = max(0, estimate - elapsed)
526
+ latest = output_lines[-1] if output_lines else f"{label} is running…"
527
+ yield latest[-240:], remaining
528
+ last_yield = elapsed
529
+ time.sleep(0.2)
530
+
531
+ while True:
532
+ try:
533
+ output_lines.append(lines.get_nowait())
534
+ except queue.Empty:
535
+ break
536
+ if process.returncode != 0:
537
+ diagnostic = "\n".join(output_lines[-8:]) or f"Command exited with code {process.returncode}."
538
+ raise RuntimeError(diagnostic[-1200:])
539
+ yield f"{label} finished.", 0.0
540
+
541
+
542
+ def locate_enhanced_file(directory: Path, input_file: Path) -> Path | None:
543
+ for candidate in sorted(directory.rglob("*.wav")):
544
+ if candidate.resolve() != input_file.resolve():
545
+ return candidate
546
  return None
547
 
548
+
549
+ def locate_stem(directory: Path, stem: str) -> Path | None:
550
+ matches = list(directory.rglob(f"{stem}.mp3")) + list(directory.rglob(f"{stem}.wav"))
551
+ return matches[0] if matches else None
552
+
553
+
554
+ def cleanup_temporary_files(max_age_seconds: int = 6 * 3600) -> None:
555
+ cutoff = epoch_now() - max_age_seconds
556
+ for child in TMP_DIR.iterdir():
557
+ try:
558
+ if child.stat().st_mtime < cutoff:
559
+ if child.is_dir():
560
+ shutil.rmtree(child, ignore_errors=True)
561
+ else:
562
+ child.unlink(missing_ok=True)
563
+ except FileNotFoundError:
564
+ pass
565
+
566
+
567
+ # -----------------------------------------------------------------------------
568
+ # Gradio processing flows – generators make logs and ETA visible during work.
569
+ # -----------------------------------------------------------------------------
570
+ def process_remove_silence(
571
+ audio_file: str | None,
572
+ keep_silence_seconds: float,
573
+ progress: gr.Progress = gr.Progress(),
574
+ ):
575
+ logs: list[str] = []
576
+ started = time.monotonic()
577
+ job_id = uuid.uuid4().hex
578
+ stats, table = recent_public_history()
579
+
580
+ def state(status: str, eta: str, audio=gr.skip(), file=gr.skip(), duration=gr.skip(), processed=gr.skip()):
581
+ return audio, file, duration, processed, status, "\n".join(logs), eta, stats, table
582
+
583
+ try:
584
+ if not audio_file:
585
+ raise ValueError("Upload an audio file before processing.")
586
+ logs.append("[1/4] Validating uploaded file")
587
+ yield state("Validating upload…", "ETA: calculating…")
588
+
589
+ job_dir = make_job_directory(job_id)
590
+ original = copy_input_to_job(audio_file, job_dir)
591
+ duration = audio_duration(original)
592
+ validate_duration(duration)
593
+ record_job_started(job_id, safe_filename(Path(audio_file).name), "Remove silence", duration)
594
+ estimate = estimated_seconds("Remove silence", duration)
595
+ logs.append(f"[2/4] Duration: {duration:.2f}s · adaptive silence detection enabled")
596
+ progress(0.2, desc="Detecting silence")
597
+ yield state("Detecting silent sections…", f"Estimated remaining: {format_seconds(estimate)}")
598
+
599
+ output = job_dir / f"{original.stem}_silence_removed.wav"
600
+ before, after, threshold = remove_silence_audio(original, output, int(max(0, float(keep_silence_seconds)) * 1000))
601
+ logs.append(f"[3/4] Removed silence using {threshold:.1f} dB threshold")
602
+ progress(0.75, desc="Saving result")
603
+ yield state("Saving result…", "Estimated remaining: a few seconds")
604
+
605
+ archive_dir, archived_files = private_archive(job_id, original, [output])
606
+ elapsed = time.monotonic() - started
607
+ record_job_finished(job_id, "Completed", elapsed, f"Silence removed: {before:.2f}s → {after:.2f}s", archive_dir, archived_files)
608
+ stats, table = recent_public_history()
609
+ logs.append(f"[4/4] Completed in {elapsed:.1f}s · private copy saved for admin")
610
+ progress(1.0, desc="Completed")
611
+ text = f"Original: {before:.3f} seconds\nProcessed: {after:.3f} seconds\nRemoved: {max(0, before - after):.3f} seconds"
612
+ yield state("Completed — silence removed.", "ETA: complete", str(output), str(output), text, str(output))
613
+ except Exception as exc:
614
+ elapsed = time.monotonic() - started
615
+ if audio_file:
616
+ try:
617
+ record_job_started(job_id, safe_filename(Path(audio_file).name), "Remove silence", 0)
618
+ except sqlite3.IntegrityError:
619
+ pass
620
+ record_job_finished(job_id, "Failed", elapsed, str(exc))
621
+ stats, table = recent_public_history()
622
+ logs.append(f"ERROR: {exc}")
623
+ yield state("Processing failed.", "ETA: unavailable")
624
+
625
+
626
+ # NOTE: Hugging Face now requires a paid plan to run a Gradio/Docker Space on
627
+ # CPU hardware. ZeroGPU stays free for personal accounts (with a small daily
628
+ # quota for anonymous/unauthenticated callers), so we use it here rather than
629
+ # CPU. If you upgrade to HF PRO, your ZeroGPU quota goes up significantly.
630
+ if spaces is not None:
631
+ _gpu_enhance = spaces.GPU
632
+ _gpu_separation = spaces.GPU
633
+ else:
634
+ def _gpu_enhance(function):
635
+ return function
636
+ def _gpu_separation(function):
637
+ return function
638
+
639
+
640
+ @_gpu_enhance
641
+ def process_enhance_audio(
642
+ processed_file: str | None,
643
+ strength: str,
644
+ progress: gr.Progress = gr.Progress(),
645
+ ):
646
+ logs: list[str] = []
647
+ started = time.monotonic()
648
+ job_id = uuid.uuid4().hex
649
+ stats, table = recent_public_history()
650
+
651
+ def state(status: str, eta: str, audio=gr.skip(), file=gr.skip()):
652
+ return audio, file, status, "\n".join(logs), eta, stats, table
653
+
654
+ try:
655
+ if not processed_file:
656
+ raise ValueError("Run Remove Silence first; the enhancer uses that processed audio.")
657
+ logs.append("[1/4] Preparing processed audio for real noise suppression")
658
+ yield state("Preparing enhancement…", "ETA: calculating…")
659
+ job_dir = make_job_directory(job_id)
660
+ original = copy_input_to_job(processed_file, job_dir)
661
+ duration = audio_duration(original)
662
+ validate_duration(duration)
663
+ record_job_started(job_id, safe_filename(Path(processed_file).name), "Enhance audio", duration)
664
+ estimate = estimated_seconds("Enhance audio", duration)
665
+
666
+ wav_input = job_dir / "enhancement_input_48k.wav"
667
+ ffmpeg_convert_to_wav(original, wav_input, sample_rate=48000, mono=True)
668
+ logs.append("[2/4] Converted to 48 kHz mono for speech-noise processing")
669
+ progress(0.15, desc="Preparing audio")
670
+ yield state("Running AI noise suppression…", f"Estimated remaining: {format_seconds(estimate)}")
671
+
672
+ output_dir = job_dir / "deepfilter_output"
673
+ output_dir.mkdir(exist_ok=True)
674
+ output = job_dir / f"{original.stem}_enhanced.wav"
675
+ deepfilter = find_deepfilter_command()
676
+ used_fallback = False
677
+ if deepfilter:
678
+ try:
679
+ logs.append("[3/4] DeepFilterNet speech denoiser started (background noise + room noise)")
680
+ command = [deepfilter, "--output-dir", str(output_dir), "--pf", "--compensate-delay", str(wav_input)]
681
+ for line, remaining in subprocess_progress(command, estimate, "DeepFilterNet", job_dir):
682
+ logs.append(line)
683
+ progress(min(0.9, 0.2 + 0.65 * min(1, (estimate - remaining) / max(estimate, 1))), desc="Suppressing noise")
684
+ yield state("AI noise suppression is running…", f"Estimated remaining: {format_seconds(remaining)}")
685
+ model_output = locate_enhanced_file(output_dir, wav_input)
686
+ if not model_output:
687
+ raise RuntimeError("DeepFilterNet completed but did not produce an audio file.")
688
+ shutil.copy2(model_output, output)
689
+ except Exception as deepfilter_error:
690
+ logs.append(f"DeepFilterNet failed ({deepfilter_error}); switching to spectral denoise fallback")
691
+ used_fallback = True
692
+ else:
693
+ used_fallback = True
694
+
695
+ if used_fallback:
696
+ logs.append("[3/4] Using spectral denoise fallback")
697
+ yield state("Applying spectral noise suppression…", f"Estimated remaining: {format_seconds(estimate)}")
698
+ spectral_denoise_fallback(original, output, strength)
699
+ logs.append("Spectral denoise and 80 Hz rumble filter completed.")
700
+
701
+ # Keep output level consistent even if the denoiser's output is quiet.
702
+ enhanced = AudioSegment.from_file(output)
703
+ effects.normalize(enhanced, headroom=1.0).export(output, format="wav")
704
+ archive_dir, archived_files = private_archive(job_id, original, [output])
705
+ elapsed = time.monotonic() - started
706
+ record_job_finished(job_id, "Completed", elapsed, f"Noise suppression completed at {strength} strength", archive_dir, archived_files)
707
+ stats, table = recent_public_history()
708
+ logs.append(f"[4/4] Completed in {elapsed:.1f}s · enhanced WAV is ready")
709
+ progress(1.0, desc="Completed")
710
+ yield state("Completed — background noise reduced and audio normalized.", "ETA: complete", str(output), str(output))
711
+ except Exception as exc:
712
+ elapsed = time.monotonic() - started
713
+ if processed_file:
714
+ try:
715
+ record_job_started(job_id, safe_filename(Path(processed_file).name), "Enhance audio", 0)
716
+ except sqlite3.IntegrityError:
717
+ pass
718
+ record_job_finished(job_id, "Failed", elapsed, str(exc))
719
+ stats, table = recent_public_history()
720
+ logs.append(f"ERROR: {exc}")
721
+ yield state("Enhancement failed.", "ETA: unavailable")
722
+
723
+
724
+ @_gpu_separation
725
+ def process_voice_separation(
726
+ audio_file: str | None,
727
+ model_choice: str,
728
+ progress: gr.Progress = gr.Progress(),
729
+ ):
730
+ logs: list[str] = []
731
+ started = time.monotonic()
732
+ job_id = uuid.uuid4().hex
733
+ stats, table = recent_public_history()
734
+
735
+ def state(status: str, eta: str, vocals=gr.skip(), bgm=gr.skip(), vocal_file=gr.skip(), bgm_file=gr.skip()):
736
+ return vocals, bgm, vocal_file, bgm_file, status, "\n".join(logs), eta, stats, table
737
+
738
  try:
739
+ if not audio_file:
740
+ raise ValueError("Upload an original audio file before using Voice / BGM Isolation.")
741
+ model = "htdemucs" if model_choice == "High quality" else "mdx_q"
742
+ logs.append("[1/3] Validating uploaded audio for stem separation")
743
+ yield state("Validating upload…", "ETA: calculating…")
744
+ job_dir = make_job_directory(job_id)
745
+ original = copy_input_to_job(audio_file, job_dir)
746
+ duration = audio_duration(original)
747
+ validate_duration(duration)
748
+ record_job_started(job_id, safe_filename(Path(audio_file).name), "Voice / BGM isolation", duration)
749
+ estimate = estimated_seconds("Voice / BGM isolation", duration, model)
750
+ logs.append(f"[2/3] Starting Demucs {model} · output: vocals and no_vocals (BGM)")
751
+ logs.append("The first run can take longer while model weights download.")
752
+ progress(0.08, desc="Loading separation model")
753
+ yield state("Separating voice and BGM…", f"Estimated remaining: {format_seconds(estimate)}")
754
+
755
+ output_dir = job_dir / "separated"
756
+ command = [
757
+ sys.executable, "-m", "demucs.separate", "--two-stems", "vocals", "--mp3", "--mp3-bitrate", "320",
758
+ "--name", model, "--out", str(output_dir), "--device", preferred_torch_device(), str(original),
759
+ ]
760
+ for line, remaining in subprocess_progress(command, estimate, "Demucs", job_dir):
761
+ logs.append(line)
762
+ progress(min(0.92, 0.1 + 0.78 * min(1, (estimate - remaining) / max(estimate, 1))), desc="Separating stems")
763
+ yield state("Separating voice and BGM…", f"Estimated remaining: {format_seconds(remaining)}")
764
+
765
+ vocals = locate_stem(output_dir, "vocals")
766
+ bgm = locate_stem(output_dir, "no_vocals")
767
+ if not vocals or not bgm:
768
+ raise RuntimeError("Separation completed but voice/BGM stems could not be found.")
769
+ archive_dir, archived_files = private_archive(job_id, original, [vocals, bgm])
770
+ elapsed = time.monotonic() - started
771
+ record_job_finished(job_id, "Completed", elapsed, f"Demucs {model}: vocals and BGM isolated", archive_dir, archived_files)
772
+ stats, table = recent_public_history()
773
+ logs.append(f"[3/3] Completed in {elapsed:.1f}s · both stems are ready")
774
+ progress(1.0, desc="Completed")
775
+ yield state("Completed — voice and BGM are available separately.", "ETA: complete", str(vocals), str(bgm), str(vocals), str(bgm))
776
+ except Exception as exc:
777
+ elapsed = time.monotonic() - started
778
+ if audio_file:
779
+ try:
780
+ record_job_started(job_id, safe_filename(Path(audio_file).name), "Voice / BGM isolation", 0)
781
+ except sqlite3.IntegrityError:
782
+ pass
783
+ record_job_finished(job_id, "Failed", elapsed, str(exc))
784
+ stats, table = recent_public_history()
785
+ logs.append(f"ERROR: {exc}")
786
+ yield state("Voice / BGM separation failed.", "ETA: unavailable")
787
+
788
+
789
+ # -----------------------------------------------------------------------------
790
+ # User interface
791
+ # -----------------------------------------------------------------------------
792
+ CSS = """
793
+ .gradio-container { max-width: 1180px !important; }
794
+ .hero { text-align:center; margin: 18px auto 8px; }
795
+ .hero h1 { margin-bottom: 6px; color: #135d8d; }
796
+ .notice { border-left: 4px solid #0ea5e9; background: #f0f9ff; padding: 12px 14px; border-radius: 8px; margin: 8px 0; }
797
+ .stats-card { background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 10px; padding: 12px 14px; margin-bottom: 8px; color: #334155; }
798
+ .log-box textarea { font-family: ui-monospace, SFMono-Regular, Menlo, monospace !important; font-size: 12px !important; }
799
  """
800
+
801
+
802
+ def ui() -> gr.Blocks:
803
+ stats, table = recent_public_history()
804
+ with gr.Blocks(theme=gr.themes.Soft(), css=CSS, title="Audio Cleanup Studio") as demo:
805
+ original_audio_state = gr.State(value=None)
806
+ processed_file_state = gr.State(value=None)
807
+ admin_session_state = gr.State(value=None)
808
+
809
+ gr.HTML(
810
+ """
811
+ <div class='hero'>
812
+ <h1>🔇 Audio Cleanup Studio</h1>
813
+ <p>Remove silence, clean speech noise, and isolate voice or BGM without losing the original workflows.</p>
814
+ </div>
815
+ <div class='notice'><b>Privacy:</b> results are shown only to the current user. Uploaded and processed audio is archived privately for the administrator only; the public activity feed shows only the filename and selected action.</div>
816
+ """
817
+ )
818
+
819
+ with gr.Row():
820
+ with gr.Column(scale=1):
821
+ audio_input = gr.Audio(
822
+ label="📂 Upload Audio",
823
+ type="filepath",
824
+ sources=["upload", "microphone"],
825
+ format="wav",
826
+ )
827
+ silence_threshold = gr.Number(
828
+ label="Keep Silence Up To (seconds)", value=0.05, minimum=0, precision=2
829
+ )
830
+ submit_btn = gr.Button("🔇 Remove Silence", variant="primary")
831
+ with gr.Column(scale=1):
832
+ audio_output = gr.Audio(label="▶ Play Audio")
833
+ file_output = gr.File(label="⬇ Download Audio File")
834
+ duration_output = gr.Textbox(label="📊 Duration Info", interactive=False)
835
+
836
+ remove_status = gr.Textbox(label="⚡ Remove Silence Status", interactive=False)
837
+ live_log = gr.Textbox(label="🧾 Live Processing Log", lines=8, interactive=False, elem_classes=["log-box"])
838
+ eta_output = gr.Textbox(label="⏱ Estimated Time", interactive=False)
839
+
840
+ gr.HTML("<hr>")
841
+ gr.Markdown("## ✨ Audio Enhancer\nReal speech-noise suppression is used first. If it cannot initialise, the app transparently falls back to spectral denoising, rumble filtering, and loudness normalization.")
842
+ with gr.Row():
843
+ with gr.Column(scale=1):
844
+ enhancement_strength = gr.Radio(["Light", "Balanced", "Strong"], value="Balanced", label="Noise Cleaning Strength")
845
+ enhance_btn = gr.Button("✨ Enhance Audio", variant="primary")
846
+ with gr.Column(scale=1):
847
+ enhanced_audio_output = gr.Audio(label="▶ Enhanced Audio")
848
+ enhanced_file_output = gr.File(label="⬇ Download Enhanced Audio")
849
+ enhance_status = gr.Textbox(label="⚡ Enhancement Status", interactive=False)
850
+
851
+ gr.HTML("<hr>")
852
+ gr.Markdown("## 🎙️ Voice / BGM Isolation\nChoose this when you want **voice only** (remove BGM) or **BGM only** (remove voice). The two downloads are created together using Demucs separation.")
853
+ with gr.Row():
854
+ with gr.Column(scale=1):
855
+ separation_model = gr.Radio(["High quality", "Faster"], value="High quality", label="Separation Quality")
856
+ isolate_btn = gr.Button("🎙️ Isolate Voice & BGM", variant="primary")
857
+ with gr.Column(scale=1):
858
+ vocals_output = gr.Audio(label="🎤 Voice Only")
859
+ bgm_output = gr.Audio(label="🎵 BGM Only (Voice Removed)")
860
+ vocal_file_output = gr.File(label="⬇ Download Voice Only")
861
+ bgm_file_output = gr.File(label="⬇ Download BGM Only")
862
+ separation_status = gr.Textbox(label="⚡ Voice / BGM Status", interactive=False)
863
+
864
+ gr.HTML("<hr>")
865
+ gr.Markdown("## 🌐 Public Processing Activity\nThis is an activity count, not a count of verified people. It intentionally never exposes audio files or downloads.")
866
+ public_stats = gr.HTML(value=stats)
867
+ public_history = gr.Dataframe(
868
+ headers=["Audio filename", "Action", "Status", "Activity time"],
869
+ value=table,
870
+ interactive=False,
871
+ wrap=True,
872
+ )
873
+ visitor_online_output = gr.Number(value=0, visible=False)
874
+ visitor_total_output = gr.Number(value=0, visible=False)
875
+
876
+ gr.HTML("<hr>")
877
+ with gr.Accordion("🔐 Administrator: Private Audio Archive", open=False):
878
+ gr.Markdown("Enter the administrator access code to view archived source and output audio. The access code is read from the Space Secret `ADMIN_ACCESS_CODE` and is never stored in the app database.")
879
+ with gr.Row():
880
+ admin_code = gr.Textbox(label="Administrator access code", type="password")
881
+ unlock_btn = gr.Button("Unlock Archive")
882
+ refresh_btn = gr.Button("Refresh")
883
+ admin_message = gr.Textbox(label="Archive status", interactive=False)
884
+ admin_history = gr.Dataframe(
885
+ headers=["Job ID", "Filename", "Operation", "Status", "Created", "Completed", "Processing time"],
886
+ value=[],
887
+ interactive=False,
888
+ wrap=True,
889
+ )
890
+ admin_job_select = gr.Dropdown(label="Completed job", choices=[], value=None)
891
+ admin_files = gr.File(label="Private archived files", file_count="multiple")
892
+ admin_file_message = gr.Textbox(label="File status", interactive=False)
893
+
894
+ def remember_original(path: str | None) -> str | None:
895
+ return path
896
+
897
+ audio_input.change(remember_original, inputs=audio_input, outputs=original_audio_state, api_name=False)
898
+ submit_btn.click(
899
+ process_remove_silence,
900
+ inputs=[audio_input, silence_threshold],
901
+ outputs=[audio_output, file_output, duration_output, processed_file_state, remove_status, live_log, eta_output, public_stats, public_history],
902
+ api_name="process_audio",
903
+ )
904
+ enhance_btn.click(
905
+ process_enhance_audio,
906
+ inputs=[processed_file_state, enhancement_strength],
907
+ outputs=[enhanced_audio_output, enhanced_file_output, enhance_status, live_log, eta_output, public_stats, public_history],
908
+ api_name="enhance_audio",
909
+ )
910
+ isolate_btn.click(
911
+ process_voice_separation,
912
+ inputs=[original_audio_state, separation_model],
913
+ outputs=[vocals_output, bgm_output, vocal_file_output, bgm_file_output, separation_status, live_log, eta_output, public_stats, public_history],
914
+ api_name="isolate_voice_bgm",
915
+ )
916
+ unlock_btn.click(
917
+ unlock_admin,
918
+ inputs=admin_code,
919
+ outputs=[admin_session_state, admin_message, admin_history, admin_job_select],
920
+ api_name=False,
921
+ )
922
+ refresh_btn.click(
923
+ refresh_admin_history,
924
+ inputs=admin_session_state,
925
+ outputs=[admin_message, admin_history, admin_job_select],
926
+ api_name=False,
927
+ )
928
+ admin_job_select.change(
929
+ get_private_job_files,
930
+ inputs=[admin_job_select, admin_session_state],
931
+ outputs=[admin_file_message, admin_files],
932
+ api_name=False,
933
+ )
934
+ demo.load(
935
+ visitor_heartbeat,
936
+ inputs=None,
937
+ outputs=[visitor_online_output, visitor_total_output],
938
+ api_name="visitor_heartbeat",
939
+ )
940
+ demo.load(
941
+ register_visitor,
942
+ inputs=None,
943
+ outputs=[visitor_online_output, visitor_total_output],
944
+ api_name="register_visitor",
945
+ )
946
+ return demo
947
+
948
+
949
+ def main() -> None:
950
+ initialise_database()
951
+ purge_expired_history()
952
+ cleanup_temporary_files()
953
+ demo = ui()
954
+ demo.queue(default_concurrency_limit=1, max_size=20).launch()
955
+
956
 
957
  if __name__ == "__main__":
958
+ main()