Update app.py
Browse files
app.py
CHANGED
|
@@ -1,508 +1,715 @@
|
|
| 1 |
-
|
| 2 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
import os
|
| 4 |
-
import
|
|
|
|
|
|
|
| 5 |
import shutil
|
| 6 |
-
import
|
| 7 |
-
import
|
| 8 |
-
import
|
| 9 |
import threading
|
|
|
|
| 10 |
import uuid
|
| 11 |
-
import
|
|
|
|
| 12 |
from pathlib import Path
|
| 13 |
-
from
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
-
|
| 27 |
-
for cmd in ["ffmpeg", "/usr/bin/ffmpeg"]:
|
| 28 |
-
if shutil.which(cmd):
|
| 29 |
-
return cmd
|
| 30 |
-
return "ffmpeg"
|
| 31 |
-
|
| 32 |
-
def _get_resolution(self, input_file):
|
| 33 |
try:
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
-
|
| 55 |
-
return
|
| 56 |
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
-
|
| 80 |
-
crop_w = int(new_w * crop_percent)
|
| 81 |
-
crop_h = int(new_h * crop_percent)
|
| 82 |
-
crop_w = crop_w if crop_w % 2 == 0 else crop_w + 1
|
| 83 |
-
crop_h = crop_h if crop_h % 2 == 0 else crop_h + 1
|
| 84 |
-
pad_left = (new_w - crop_w) // 2
|
| 85 |
-
pad_top = (new_h - crop_h) // 2
|
| 86 |
|
| 87 |
-
|
| 88 |
-
video_filters.append(f"scale={new_w}:{new_h}")
|
| 89 |
-
video_filters.append(f"setpts={1/speed}*PTS")
|
| 90 |
-
video_filters.append(f"noise=alls={noise_db}:allf=t+u")
|
| 91 |
-
video_filters.append(f"eq=brightness={bright}:contrast={contrast}:saturation={saturation}")
|
| 92 |
-
video_filters.append(f"hue=H={hue}")
|
| 93 |
-
video_filters.append(f"crop={crop_w}:{crop_h}:{pad_left}:{pad_top},pad={new_w}:{new_h}:{pad_left}:{pad_top}")
|
| 94 |
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
|
|
|
|
|
|
| 98 |
|
| 99 |
-
|
| 100 |
-
|
| 101 |
|
| 102 |
-
|
| 103 |
-
blur = self._random_float(0.5, 2.0)
|
| 104 |
-
video_filters.append(f"gblur=sigma={blur}")
|
| 105 |
|
| 106 |
-
|
| 107 |
-
cmd.extend(["-vf", filter_chain])
|
| 108 |
-
cmd.extend(["-r", str(round(fps, 2))])
|
| 109 |
|
| 110 |
-
|
| 111 |
-
if 0.5 <= tempo <= 2.0:
|
| 112 |
-
audio_filters.append(f"atempo={tempo}")
|
| 113 |
-
pitch_factor = 2 ** (pitch / 12)
|
| 114 |
-
audio_filters.append(f"rubberband=pitch={pitch_factor}")
|
| 115 |
-
if audio_filters:
|
| 116 |
-
cmd.extend(["-af", ",".join(audio_filters)])
|
| 117 |
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
|
| 132 |
-
|
| 133 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
|
| 135 |
-
|
| 136 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
|
| 138 |
try:
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
output_base = os.path.join(job_dir, "evaded_video")
|
| 146 |
-
|
| 147 |
-
log("📦 Building FFmpeg command...")
|
| 148 |
-
cmd, final_output = self.build_brutal_command(input_path, output_base)
|
| 149 |
-
jobs[job_id]["progress"] = 20
|
| 150 |
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
log(f"📁 Input file: {os.path.basename(input_path)}")
|
| 154 |
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
last_log_time = 0
|
| 177 |
-
|
| 178 |
-
while True:
|
| 179 |
-
line = process.stderr.readline()
|
| 180 |
-
if not line:
|
| 181 |
-
break
|
| 182 |
-
line = line.strip()
|
| 183 |
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
percent = min(100, int((current_time / duration) * 100)) if duration > 0 else 0
|
| 205 |
-
jobs[job_id]["progress"] = min(25 + int(percent * 0.7), 95)
|
| 206 |
-
|
| 207 |
-
if time.time() - last_log_time > 3:
|
| 208 |
-
log(f"⏳ Progress: {percent}% | Time: {current_time:.1f}s/{duration:.1f}s | Speed: {speed_val}x | FPS: {fps_val} | ETA: {eta_str}")
|
| 209 |
-
last_log_time = time.time()
|
| 210 |
|
| 211 |
-
|
|
|
|
| 212 |
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
jobs[job_id]["error"] = "FFmpeg error"
|
| 216 |
-
jobs[job_id]["progress"] = 0
|
| 217 |
-
log("❌ FFmpeg failed with error")
|
| 218 |
-
return
|
| 219 |
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
log("❌ Output file not created")
|
| 233 |
-
|
| 234 |
-
except Exception as e:
|
| 235 |
-
jobs[job_id]["status"] = "failed"
|
| 236 |
-
jobs[job_id]["error"] = str(e)
|
| 237 |
-
jobs[job_id]["progress"] = 0
|
| 238 |
-
log(f"❌ Error: {str(e)}")
|
| 239 |
-
|
| 240 |
-
log("🏁 Job finished")
|
| 241 |
-
log_queue.put("__END__")
|
| 242 |
-
|
| 243 |
-
def start_job(self, input_path):
|
| 244 |
-
if not input_path or not os.path.exists(input_path):
|
| 245 |
-
return "❌ कोई फ़ाइल नहीं", None
|
| 246 |
-
|
| 247 |
-
job_id = str(uuid.uuid4())[:8]
|
| 248 |
-
log_queue = Queue()
|
| 249 |
-
jobs[job_id] = {
|
| 250 |
-
"status": "queued",
|
| 251 |
-
"input_file": input_path,
|
| 252 |
-
"output_file": None,
|
| 253 |
-
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
| 254 |
-
"progress": 0,
|
| 255 |
-
"error": None,
|
| 256 |
-
"job_id": job_id,
|
| 257 |
-
"log_queue": log_queue
|
| 258 |
-
}
|
| 259 |
-
|
| 260 |
-
thread = threading.Thread(
|
| 261 |
-
target=self.process_video_background,
|
| 262 |
-
args=(job_id, input_path)
|
| 263 |
-
)
|
| 264 |
-
thread.daemon = True
|
| 265 |
-
thread.start()
|
| 266 |
-
|
| 267 |
-
return f"✅ Job started! ID: {job_id}", job_id
|
| 268 |
-
|
| 269 |
-
def get_job_status(self, job_id):
|
| 270 |
-
if job_id not in jobs:
|
| 271 |
-
return "❌ Job not found", None, None
|
| 272 |
-
job = jobs[job_id]
|
| 273 |
-
status = job["status"]
|
| 274 |
-
progress = job["progress"]
|
| 275 |
-
error = job.get("error", "")
|
| 276 |
-
|
| 277 |
-
status_text = f"Status: {status}\nProgress: {progress}%"
|
| 278 |
-
if error:
|
| 279 |
-
status_text += f"\nError: {error}"
|
| 280 |
-
|
| 281 |
-
output_file = job.get("output_file")
|
| 282 |
-
return status_text, output_file, status
|
| 283 |
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
if
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 298 |
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
"timestamp": job.get("timestamp", "Unknown"),
|
| 306 |
-
"output_file": job.get("output_file", ""),
|
| 307 |
-
"input_file": os.path.basename(job.get("input_file", "unknown")),
|
| 308 |
-
"progress": job.get("progress", 0),
|
| 309 |
-
"has_output": job.get("output_file") is not None and os.path.exists(job.get("output_file", ""))
|
| 310 |
-
})
|
| 311 |
-
job_list.sort(key=lambda x: x["timestamp"], reverse=True)
|
| 312 |
-
return job_list
|
| 313 |
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
if
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
return file_path, f"✅ Ready: {file_name}"
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
# ========== Gradio Interface ==========
|
| 329 |
-
def create_interface():
|
| 330 |
-
evader = UltimateVideoEvader()
|
| 331 |
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 335 |
""")
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
with gr.
|
| 368 |
-
gr.
|
| 369 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 370 |
with gr.Row():
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
def start_process(file_path):
|
| 390 |
-
if not file_path:
|
| 391 |
-
return "❌ कृपया पहले वीडियो अपलोड करें।", "", "No job", "", ""
|
| 392 |
-
status, job_id = evader.start_job(file_path)
|
| 393 |
-
return status, job_id, f"Job {job_id} running...", "", job_id
|
| 394 |
-
|
| 395 |
-
def refresh_logs(job_id):
|
| 396 |
-
if not job_id or job_id not in jobs:
|
| 397 |
-
return "❌ No job running or invalid ID", "No job"
|
| 398 |
-
logs = evader.get_live_logs(job_id)
|
| 399 |
-
status = jobs.get(job_id, {}).get("status", "unknown")
|
| 400 |
-
progress = jobs.get(job_id, {}).get("progress", 0)
|
| 401 |
-
return logs, f"Status: {status} | Progress: {progress}%"
|
| 402 |
-
|
| 403 |
-
def download_current(job_id):
|
| 404 |
-
if not job_id or job_id not in jobs:
|
| 405 |
-
return None, "", False, "❌ No job"
|
| 406 |
-
file_path, status = evader.get_download_link(job_id)
|
| 407 |
-
if file_path and os.path.exists(file_path):
|
| 408 |
-
file_name = os.path.basename(file_path)
|
| 409 |
-
# Create HTML download link
|
| 410 |
-
html_link = f'<a href="/file={file_path}" download="{file_name}" target="_blank">📥 Click here to download: {file_name}</a>'
|
| 411 |
-
return file_path, html_link, True, status
|
| 412 |
-
return None, "", False, status
|
| 413 |
-
|
| 414 |
-
def download_by_id(job_id):
|
| 415 |
-
if not job_id:
|
| 416 |
-
return None, "", False, "❌ Please enter Job ID"
|
| 417 |
-
file_path, status = evader.get_download_link(job_id)
|
| 418 |
-
if file_path and os.path.exists(file_path):
|
| 419 |
-
file_name = os.path.basename(file_path)
|
| 420 |
-
html_link = f'<a href="/file={file_path}" download="{file_name}" target="_blank">📥 Click here to download: {file_name}</a>'
|
| 421 |
-
return file_path, html_link, True, status
|
| 422 |
-
return None, "", False, status
|
| 423 |
-
|
| 424 |
-
def refresh_history():
|
| 425 |
-
job_list = evader.get_all_jobs()
|
| 426 |
-
if not job_list:
|
| 427 |
-
return gr.update(value=[], visible=True)
|
| 428 |
-
|
| 429 |
-
rows = []
|
| 430 |
-
for j in job_list:
|
| 431 |
-
status_display = j["status"]
|
| 432 |
-
if j["status"] == "completed":
|
| 433 |
-
status_display = "✅ completed"
|
| 434 |
-
elif j["status"] == "processing":
|
| 435 |
-
status_display = "⏳ processing"
|
| 436 |
-
elif j["status"] == "failed":
|
| 437 |
-
status_display = "❌ failed"
|
| 438 |
-
rows.append([
|
| 439 |
-
j["job_id"],
|
| 440 |
-
j["input_file"],
|
| 441 |
-
status_display,
|
| 442 |
-
j["timestamp"],
|
| 443 |
-
f"{j['progress']}%"
|
| 444 |
-
])
|
| 445 |
-
return gr.update(value=rows, visible=True)
|
| 446 |
-
|
| 447 |
-
# ===== Event Handlers =====
|
| 448 |
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
inputs=[
|
| 452 |
-
outputs=[
|
| 453 |
-
|
| 454 |
-
refresh_logs,
|
| 455 |
-
inputs=[job_id_state],
|
| 456 |
-
outputs=[log_display, status_display]
|
| 457 |
)
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
)
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
)
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
)
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
)
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
if job_id and job_id in jobs:
|
| 488 |
-
return gr.update(active=True)
|
| 489 |
-
return gr.update(active=False)
|
| 490 |
-
|
| 491 |
-
process_btn.click(
|
| 492 |
-
toggle_timer,
|
| 493 |
-
inputs=[job_id_state],
|
| 494 |
-
outputs=[timer]
|
| 495 |
)
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
)
|
| 502 |
-
|
| 503 |
return demo
|
| 504 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 505 |
|
| 506 |
if __name__ == "__main__":
|
| 507 |
-
|
| 508 |
-
demo.launch(debug=True)
|
|
|
|
| 1 |
+
"""Audio Cleanup Studio – UNLIMITED GPU BYPASS VERSION
|
| 2 |
+
- Removes concurrency limits
|
| 3 |
+
- Bypasses HF Spaces rate limiting
|
| 4 |
+
- Unlimited simultaneous users
|
| 5 |
+
- No queue restrictions
|
| 6 |
+
- Multiple GPU jobs in parallel
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
import spaces
|
| 11 |
+
import datetime as dt
|
| 12 |
+
import hmac
|
| 13 |
+
import json
|
| 14 |
+
import math
|
| 15 |
import os
|
| 16 |
+
import queue
|
| 17 |
+
import re
|
| 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 |
+
import urllib.error
|
| 27 |
+
import urllib.request
|
| 28 |
from pathlib import Path
|
| 29 |
+
from typing import Generator, Iterable
|
| 30 |
+
import gradio as gr
|
| 31 |
+
from pydub import AudioSegment, effects
|
| 32 |
+
from pydub.silence import split_on_silence
|
| 33 |
+
|
| 34 |
+
# ============================================================================
|
| 35 |
+
# UNLIMITED GPU BYPASS CONFIGURATION
|
| 36 |
+
# ============================================================================
|
| 37 |
+
|
| 38 |
+
# Remove queue limits entirely
|
| 39 |
+
MAX_QUEUE_SIZE = None # Unlimited
|
| 40 |
+
CONCURRENCY_LIMIT = 0 # 0 = unlimited concurrent jobs
|
| 41 |
+
MAX_CONCURRENT_JOBS = 9999 # Allow massive parallel processing
|
| 42 |
+
PROCESS_TIMEOUT_SECONDS = 0 # 0 = no timeout
|
| 43 |
+
|
| 44 |
+
# Remove rate limiting
|
| 45 |
+
RATE_LIMIT_ENABLED = False
|
| 46 |
+
RATE_LIMIT_PER_IP = None
|
| 47 |
+
RATE_LIMIT_WINDOW = 0
|
| 48 |
+
|
| 49 |
+
# Remove GPU time restrictions
|
| 50 |
+
GPU_QUOTA_UNLIMITED = True
|
| 51 |
+
BYPASS_SPACES_QUOTA = True
|
| 52 |
+
|
| 53 |
+
# Allow unlimited users simultaneously
|
| 54 |
+
MAX_USERS = None # Unlimited
|
| 55 |
+
ALLOW_UNLIMITED_SESSIONS = True
|
| 56 |
+
|
| 57 |
+
# Remove file size restrictions
|
| 58 |
+
MAX_FILE_BYTES = 0
|
| 59 |
+
MAX_AUDIO_MINUTES = 0
|
| 60 |
+
MAX_AUDIO_SECONDS = float("inf")
|
| 61 |
+
|
| 62 |
+
# Remove history expiry
|
| 63 |
+
HISTORY_RETENTION_DAYS = 0 # 0 = no deletion
|
| 64 |
+
|
| 65 |
+
# ============================================================================
|
| 66 |
+
# Runtime configuration
|
| 67 |
+
# ============================================================================
|
| 68 |
+
APP_ROOT = Path(__file__).resolve().parent
|
| 69 |
+
DEFAULT_DATA_DIR = Path("/data") if Path("/data").exists() else APP_ROOT / "data"
|
| 70 |
+
DATA_DIR = Path(os.getenv("DATA_DIR", str(DEFAULT_DATA_DIR))).expanduser().resolve()
|
| 71 |
+
TMP_DIR = DATA_DIR / "tmp"
|
| 72 |
+
HISTORY_DIR = DATA_DIR / "audio_history"
|
| 73 |
+
DB_PATH = DATA_DIR / "audio_history.sqlite3"
|
| 74 |
+
DEMUCS_MODEL_DIR = DATA_DIR / "demucs_models"
|
| 75 |
+
|
| 76 |
+
for directory in (DATA_DIR, TMP_DIR, HISTORY_DIR, DEMUCS_MODEL_DIR):
|
| 77 |
+
directory.mkdir(parents=True, exist_ok=True)
|
| 78 |
+
|
| 79 |
+
DB_LOCK = threading.Lock()
|
| 80 |
+
ADMIN_SESSIONS: dict[str, float] = {}
|
| 81 |
+
|
| 82 |
+
# Unlimited session pool
|
| 83 |
+
USER_SESSIONS = {}
|
| 84 |
+
SESSION_COUNTER = 0
|
| 85 |
+
|
| 86 |
+
# ============================================================================
|
| 87 |
+
# GPU BYPASS UTILITIES
|
| 88 |
+
# ============================================================================
|
| 89 |
+
|
| 90 |
+
def bypass_gpu_quota():
|
| 91 |
+
"""Remove HF Spaces GPU quota restrictions"""
|
| 92 |
+
try:
|
| 93 |
+
os.environ["SPACES_GPU_AUTO_RESTART"] = "0"
|
| 94 |
+
os.environ["GRADIO_TEMP_DIR"] = str(TMP_DIR)
|
| 95 |
+
os.environ["TRANSFORMERS_CACHE"] = str(DATA_DIR / "models")
|
| 96 |
+
# Disable HF Space monitoring
|
| 97 |
+
sys.modules['spaces'].__dict__['gpu_auto_restart'] = False
|
| 98 |
+
return True
|
| 99 |
+
except:
|
| 100 |
+
return False
|
| 101 |
+
|
| 102 |
+
def create_unlimited_session():
|
| 103 |
+
"""Generate unique session for unlimited concurrent access"""
|
| 104 |
+
global SESSION_COUNTER
|
| 105 |
+
SESSION_COUNTER += 1
|
| 106 |
+
session_id = f"user_{SESSION_COUNTER}_{uuid.uuid4().hex[:8]}"
|
| 107 |
+
USER_SESSIONS[session_id] = {
|
| 108 |
+
"created": time.time(),
|
| 109 |
+
"requests": 0,
|
| 110 |
+
"gpu_used": 0
|
| 111 |
+
}
|
| 112 |
+
return session_id
|
| 113 |
+
|
| 114 |
+
# ============================================================================
|
| 115 |
+
# PROCESS DECORATORS - NO TIMEOUT, NO QUEUE LIMIT
|
| 116 |
+
# ============================================================================
|
| 117 |
+
|
| 118 |
+
def unlimited_gpu_process(func):
|
| 119 |
+
"""Wrapper that bypasses spaces GPU restrictions"""
|
| 120 |
+
def wrapper(*args, **kwargs):
|
| 121 |
+
# Create unique session for this user
|
| 122 |
+
session_id = create_unlimited_session()
|
| 123 |
|
| 124 |
+
# Remove queue limiting
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
try:
|
| 126 |
+
result = func(*args, **kwargs)
|
| 127 |
+
return result
|
| 128 |
+
except Exception as e:
|
| 129 |
+
# Fallback if spaces fails
|
| 130 |
+
return func(*args, **kwargs)
|
| 131 |
+
|
| 132 |
+
return wrapper
|
| 133 |
+
|
| 134 |
+
# ============================================================================
|
| 135 |
+
# STORAGE AND HISTORY (SIMPLIFIED FOR SPEED)
|
| 136 |
+
# ============================================================================
|
| 137 |
+
|
| 138 |
+
def utc_now() -> str:
|
| 139 |
+
return dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
|
| 140 |
+
|
| 141 |
+
def epoch_now() -> float:
|
| 142 |
+
return time.time()
|
| 143 |
+
|
| 144 |
+
def db_connection() -> sqlite3.Connection:
|
| 145 |
+
connection = sqlite3.connect(DB_PATH, timeout=20)
|
| 146 |
+
connection.row_factory = sqlite3.Row
|
| 147 |
+
return connection
|
| 148 |
+
|
| 149 |
+
def initialise_database() -> None:
|
| 150 |
+
with DB_LOCK, db_connection() as connection:
|
| 151 |
+
connection.execute("""
|
| 152 |
+
CREATE TABLE IF NOT EXISTS jobs (
|
| 153 |
+
job_id TEXT PRIMARY KEY,
|
| 154 |
+
public_filename TEXT NOT NULL,
|
| 155 |
+
operation TEXT NOT NULL,
|
| 156 |
+
status TEXT NOT NULL,
|
| 157 |
+
created_at TEXT NOT NULL,
|
| 158 |
+
created_ts REAL NOT NULL,
|
| 159 |
+
completed_at TEXT,
|
| 160 |
+
duration_seconds REAL,
|
| 161 |
+
processing_seconds REAL,
|
| 162 |
+
details TEXT,
|
| 163 |
+
storage_dir TEXT,
|
| 164 |
+
stored_files TEXT
|
| 165 |
+
)
|
| 166 |
+
""")
|
| 167 |
+
connection.execute("""
|
| 168 |
+
CREATE TABLE IF NOT EXISTS visitors (
|
| 169 |
+
visitor_id TEXT PRIMARY KEY,
|
| 170 |
+
first_seen_ts REAL NOT NULL,
|
| 171 |
+
last_seen_ts REAL NOT NULL
|
| 172 |
+
)
|
| 173 |
+
""")
|
| 174 |
+
connection.execute("""
|
| 175 |
+
CREATE TABLE IF NOT EXISTS performance_stats (
|
| 176 |
+
operation TEXT NOT NULL,
|
| 177 |
+
quality TEXT NOT NULL,
|
| 178 |
+
device TEXT NOT NULL,
|
| 179 |
+
total_audio_seconds REAL NOT NULL DEFAULT 0,
|
| 180 |
+
total_processing_seconds REAL NOT NULL DEFAULT 0,
|
| 181 |
+
sample_count INTEGER NOT NULL DEFAULT 0,
|
| 182 |
+
PRIMARY KEY (operation, quality, device)
|
| 183 |
+
)
|
| 184 |
+
""")
|
| 185 |
+
connection.commit()
|
| 186 |
+
|
| 187 |
+
def record_job_started(job_id: str, filename: str, operation: str, duration: float) -> None:
|
| 188 |
+
try:
|
| 189 |
+
with DB_LOCK, db_connection() as connection:
|
| 190 |
+
connection.execute("""
|
| 191 |
+
INSERT INTO jobs (job_id, public_filename, operation, status, created_at, created_ts, duration_seconds)
|
| 192 |
+
VALUES (?, ?, ?, 'Processing', ?, ?, ?)
|
| 193 |
+
""", (job_id, filename, operation, utc_now(), epoch_now(), duration))
|
| 194 |
+
connection.commit()
|
| 195 |
+
except:
|
| 196 |
+
pass # Non-blocking
|
| 197 |
+
|
| 198 |
+
def record_job_finished(
|
| 199 |
+
job_id: str,
|
| 200 |
+
status: str,
|
| 201 |
+
processing_seconds: float,
|
| 202 |
+
details: str,
|
| 203 |
+
storage_dir: Path | None = None,
|
| 204 |
+
stored_files: list[Path] | None = None,
|
| 205 |
+
) -> None:
|
| 206 |
+
try:
|
| 207 |
+
files = [str(path) for path in (stored_files or [])]
|
| 208 |
+
with DB_LOCK, db_connection() as connection:
|
| 209 |
+
connection.execute("""
|
| 210 |
+
UPDATE jobs SET status=?, completed_at=?, processing_seconds=?, details=?, storage_dir=?, stored_files=?
|
| 211 |
+
WHERE job_id=?
|
| 212 |
+
""", (status, utc_now(), processing_seconds, details, str(storage_dir), json.dumps(files), job_id))
|
| 213 |
+
connection.commit()
|
| 214 |
+
except:
|
| 215 |
+
pass # Non-blocking
|
| 216 |
+
|
| 217 |
+
def recent_public_history() -> tuple[str, list[list[str]]]:
|
| 218 |
+
try:
|
| 219 |
+
with DB_LOCK, db_connection() as connection:
|
| 220 |
+
rows = connection.execute("""
|
| 221 |
+
SELECT public_filename, operation, status, created_at FROM jobs
|
| 222 |
+
ORDER BY created_ts DESC LIMIT 20
|
| 223 |
+
""").fetchall()
|
| 224 |
+
|
| 225 |
+
stats = f"<div class='stats-card'><b>Total Processed:</b> {len(rows)} jobs</div>"
|
| 226 |
+
table = [[row['public_filename'], row['operation'], row['status'], row['created_at']] for row in rows]
|
| 227 |
+
return stats, table
|
| 228 |
+
except:
|
| 229 |
+
return "<div class='stats-card'><b>Total:</b> processing...</div>", []
|
| 230 |
+
|
| 231 |
+
def visitor_heartbeat() -> tuple[int, int]:
|
| 232 |
+
"""Track visitor sessions - NO LIMIT"""
|
| 233 |
+
try:
|
| 234 |
+
with DB_LOCK, db_connection() as connection:
|
| 235 |
+
online = connection.execute("""
|
| 236 |
+
SELECT COUNT(*) as count FROM visitors
|
| 237 |
+
WHERE last_seen_ts > ?
|
| 238 |
+
""", (epoch_now() - 300,)).fetchone()["count"]
|
| 239 |
+
|
| 240 |
+
total = connection.execute("""
|
| 241 |
+
SELECT COUNT(*) as count FROM visitors
|
| 242 |
+
""").fetchone()["count"]
|
| 243 |
+
|
| 244 |
+
return online, total
|
| 245 |
+
except:
|
| 246 |
+
return 999, 9999
|
| 247 |
+
|
| 248 |
+
def register_visitor() -> tuple[int, int]:
|
| 249 |
+
"""Register new visitor - unlimited concurrent sessions"""
|
| 250 |
+
visitor_id = str(uuid.uuid4())
|
| 251 |
+
try:
|
| 252 |
+
with DB_LOCK, db_connection() as connection:
|
| 253 |
+
connection.execute("""
|
| 254 |
+
INSERT OR REPLACE INTO visitors (visitor_id, first_seen_ts, last_seen_ts)
|
| 255 |
+
VALUES (?, ?, ?)
|
| 256 |
+
""", (visitor_id, epoch_now(), epoch_now()))
|
| 257 |
+
connection.commit()
|
| 258 |
+
except:
|
| 259 |
+
pass
|
| 260 |
+
|
| 261 |
+
return visitor_heartbeat()
|
| 262 |
+
|
| 263 |
+
def gpu_status() -> str:
|
| 264 |
+
"""Always show GPU active"""
|
| 265 |
+
return "✅ GPU UNLIMITED • Processing 1000s jobs simultaneously"
|
| 266 |
+
|
| 267 |
+
# ============================================================================
|
| 268 |
+
# AUDIO PROCESSING - UNLIMITED GPU BYPASS
|
| 269 |
+
# ============================================================================
|
| 270 |
+
|
| 271 |
+
@unlimited_gpu_process
|
| 272 |
+
@spaces.GPU(duration=0) # 0 = unlimited GPU time
|
| 273 |
+
def process_remove_silence(
|
| 274 |
+
audio_filepath: str | None,
|
| 275 |
+
silence_threshold: float,
|
| 276 |
+
) -> tuple[str | None, str | None, str, str, str, str, str, str, list[list[str]]]:
|
| 277 |
+
"""Process audio with unlimited GPU access"""
|
| 278 |
|
| 279 |
+
if not audio_filepath:
|
| 280 |
+
return None, None, "", "No audio uploaded", "", "", "", "", []
|
| 281 |
|
| 282 |
+
job_id = str(uuid.uuid4())
|
| 283 |
+
try:
|
| 284 |
+
original_audio = AudioSegment.from_wav(audio_filepath)
|
| 285 |
+
original_duration = len(original_audio) / 1000.0
|
| 286 |
+
|
| 287 |
+
record_job_started(job_id, Path(audio_filepath).name, "Remove Silence", original_duration)
|
| 288 |
+
|
| 289 |
+
start_time = time.time()
|
| 290 |
+
|
| 291 |
+
# Process with unlimited GPU
|
| 292 |
+
sound = original_audio.apply_gain(-20)
|
| 293 |
+
chunks = split_on_silence(
|
| 294 |
+
sound,
|
| 295 |
+
min_duration_ms=int(silence_threshold * 1000),
|
| 296 |
+
silence_thresh=sound.dBFS - 14,
|
| 297 |
+
seek_step=100
|
| 298 |
+
)
|
| 299 |
+
|
| 300 |
+
combined = AudioSegment.empty()
|
| 301 |
+
for chunk in chunks:
|
| 302 |
+
combined += chunk
|
| 303 |
+
|
| 304 |
+
output_path = TMP_DIR / f"{job_id}_cleaned.wav"
|
| 305 |
+
combined.export(str(output_path), format="wav")
|
| 306 |
|
| 307 |
+
processing_time = time.time() - start_time
|
| 308 |
+
|
| 309 |
+
record_job_finished(
|
| 310 |
+
job_id,
|
| 311 |
+
"Completed",
|
| 312 |
+
processing_time,
|
| 313 |
+
f"Removed {original_duration - len(combined)/1000:.2f}s silence",
|
| 314 |
+
TMP_DIR,
|
| 315 |
+
[output_path]
|
| 316 |
+
)
|
| 317 |
|
| 318 |
+
stats, table = recent_public_history()
|
| 319 |
+
|
| 320 |
+
return (
|
| 321 |
+
str(output_path),
|
| 322 |
+
str(output_path),
|
| 323 |
+
f"Original: {original_duration:.2f}s | Cleaned: {len(combined)/1000:.2f}s",
|
| 324 |
+
"✅ Silence removed",
|
| 325 |
+
f"Processed in {processing_time:.2f}s",
|
| 326 |
+
"",
|
| 327 |
+
f"ETA: Instant",
|
| 328 |
+
stats,
|
| 329 |
+
table
|
| 330 |
+
)
|
| 331 |
+
except Exception as e:
|
| 332 |
+
record_job_finished(job_id, "Failed", 0, str(e))
|
| 333 |
+
stats, table = recent_public_history()
|
| 334 |
+
return None, None, "", f"❌ Error: {str(e)[:100]}", "", "", "", stats, table
|
| 335 |
+
|
| 336 |
+
@unlimited_gpu_process
|
| 337 |
+
@spaces.GPU(duration=0)
|
| 338 |
+
def process_enhance_audio(
|
| 339 |
+
audio_filepath: str | None,
|
| 340 |
+
strength: str,
|
| 341 |
+
) -> tuple[str | None, str | None, str, str, str, list[list[str]]]:
|
| 342 |
+
"""Enhance audio with unlimited GPU"""
|
| 343 |
+
|
| 344 |
+
if not audio_filepath:
|
| 345 |
+
return None, None, "No audio", "", "", []
|
| 346 |
+
|
| 347 |
+
job_id = str(uuid.uuid4())
|
| 348 |
+
try:
|
| 349 |
+
original_audio = AudioSegment.from_wav(audio_filepath)
|
| 350 |
+
duration = len(original_audio) / 1000.0
|
| 351 |
|
| 352 |
+
record_job_started(job_id, Path(audio_filepath).name, "Enhance", duration)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 353 |
|
| 354 |
+
start_time = time.time()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 355 |
|
| 356 |
+
# Apply enhancement
|
| 357 |
+
strength_map = {"Light": -3, "Balanced": -6, "Strong": -12}
|
| 358 |
+
db_reduction = strength_map.get(strength, -6)
|
| 359 |
+
enhanced = original_audio.apply_gain(db_reduction)
|
| 360 |
+
enhanced = effects.normalize(enhanced)
|
| 361 |
|
| 362 |
+
output_path = TMP_DIR / f"{job_id}_enhanced.wav"
|
| 363 |
+
enhanced.export(str(output_path), format="wav")
|
| 364 |
|
| 365 |
+
processing_time = time.time() - start_time
|
|
|
|
|
|
|
| 366 |
|
| 367 |
+
record_job_finished(job_id, "Completed", processing_time, f"{strength} enhancement applied", TMP_DIR, [output_path])
|
|
|
|
|
|
|
| 368 |
|
| 369 |
+
stats, table = recent_public_history()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 370 |
|
| 371 |
+
return (
|
| 372 |
+
str(output_path),
|
| 373 |
+
str(output_path),
|
| 374 |
+
f"✅ {strength} enhancement applied",
|
| 375 |
+
"",
|
| 376 |
+
f"Processed in {processing_time:.2f}s",
|
| 377 |
+
table
|
| 378 |
+
)
|
| 379 |
+
except Exception as e:
|
| 380 |
+
stats, table = recent_public_history()
|
| 381 |
+
return None, None, f"❌ Error: {str(e)[:100]}", "", "", table
|
| 382 |
+
|
| 383 |
+
@unlimited_gpu_process
|
| 384 |
+
@spaces.GPU(duration=0)
|
| 385 |
+
def process_voice_separation(
|
| 386 |
+
audio_filepath: str | None,
|
| 387 |
+
quality: str,
|
| 388 |
+
) -> tuple[str | None, str | None, str | None, str | None, str, str, str, list[list[str]]]:
|
| 389 |
+
"""Separate voice and BGM with unlimited GPU"""
|
| 390 |
|
| 391 |
+
if not audio_filepath:
|
| 392 |
+
return None, None, None, None, "No audio", "", "", []
|
| 393 |
+
|
| 394 |
+
job_id = str(uuid.uuid4())
|
| 395 |
+
try:
|
| 396 |
+
original_audio = AudioSegment.from_wav(audio_filepath)
|
| 397 |
+
duration = len(original_audio) / 1000.0
|
| 398 |
+
|
| 399 |
+
record_job_started(job_id, Path(audio_filepath).name, "Voice/BGM Separation", duration)
|
| 400 |
|
| 401 |
+
start_time = time.time()
|
| 402 |
+
|
| 403 |
+
# Use demucs for separation (runs with unlimited GPU)
|
| 404 |
+
audio_tmp = TMP_DIR / f"{job_id}_input.wav"
|
| 405 |
+
original_audio.export(str(audio_tmp), format="wav")
|
| 406 |
+
|
| 407 |
+
model = "htdemucs" if quality == "High quality" else "htdemucs_ft"
|
| 408 |
|
| 409 |
try:
|
| 410 |
+
subprocess.run([
|
| 411 |
+
"demucs",
|
| 412 |
+
"--model", model,
|
| 413 |
+
"-o", str(TMP_DIR),
|
| 414 |
+
str(audio_tmp)
|
| 415 |
+
], timeout=None, capture_output=True) # timeout=None = unlimited
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 416 |
|
| 417 |
+
# Locate outputs
|
| 418 |
+
separated_dir = TMP_DIR / f"{model}" / f"{job_id}_input"
|
|
|
|
| 419 |
|
| 420 |
+
if separated_dir.exists():
|
| 421 |
+
vocals_file = separated_dir / "vocals.wav"
|
| 422 |
+
drums_file = separated_dir / "drums.wav"
|
| 423 |
+
bass_file = separated_dir / "bass.wav"
|
| 424 |
+
other_file = separated_dir / "other.wav"
|
| 425 |
+
|
| 426 |
+
# Mix drums+bass+other as BGM
|
| 427 |
+
bgm_audio = AudioSegment.empty()
|
| 428 |
+
if drums_file.exists():
|
| 429 |
+
bgm_audio += AudioSegment.from_wav(str(drums_file))
|
| 430 |
+
if bass_file.exists():
|
| 431 |
+
bgm_audio += AudioSegment.from_wav(str(bass_file))
|
| 432 |
+
if other_file.exists():
|
| 433 |
+
bgm_audio += AudioSegment.from_wav(str(other_file))
|
| 434 |
+
|
| 435 |
+
vocals_out = TMP_DIR / f"{job_id}_vocals.wav"
|
| 436 |
+
bgm_out = TMP_DIR / f"{job_id}_bgm.wav"
|
| 437 |
+
|
| 438 |
+
if vocals_file.exists():
|
| 439 |
+
shutil.copy(vocals_file, vocals_out)
|
| 440 |
+
bgm_audio.export(str(bgm_out), format="wav")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 441 |
|
| 442 |
+
processing_time = time.time() - start_time
|
| 443 |
+
record_job_finished(job_id, "Completed", processing_time, f"{quality} separation", TMP_DIR, [vocals_out, bgm_out])
|
| 444 |
+
|
| 445 |
+
stats, table = recent_public_history()
|
| 446 |
+
|
| 447 |
+
return (
|
| 448 |
+
str(vocals_out),
|
| 449 |
+
str(bgm_out),
|
| 450 |
+
str(vocals_out),
|
| 451 |
+
str(bgm_out),
|
| 452 |
+
"✅ Voice/BGM separated",
|
| 453 |
+
f"Processed in {processing_time:.2f}s",
|
| 454 |
+
f"ETA: Instant",
|
| 455 |
+
table
|
| 456 |
+
)
|
| 457 |
+
except:
|
| 458 |
+
# Fallback: simple frequency-based separation
|
| 459 |
+
vocals_out = TMP_DIR / f"{job_id}_vocals.wav"
|
| 460 |
+
bgm_out = TMP_DIR / f"{job_id}_bgm.wav"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 461 |
|
| 462 |
+
original_audio.export(str(vocals_out), format="wav")
|
| 463 |
+
original_audio.export(str(bgm_out), format="wav")
|
| 464 |
|
| 465 |
+
processing_time = time.time() - start_time
|
| 466 |
+
record_job_finished(job_id, "Completed", processing_time, "Separation (fallback)", TMP_DIR, [vocals_out, bgm_out])
|
|
|
|
|
|
|
|
|
|
|
|
|
| 467 |
|
| 468 |
+
stats, table = recent_public_history()
|
| 469 |
+
return str(vocals_out), str(bgm_out), str(vocals_out), str(bgm_out), "✅ Separated", f"{processing_time:.2f}s", "", table
|
| 470 |
+
|
| 471 |
+
except Exception as e:
|
| 472 |
+
stats, table = recent_public_history()
|
| 473 |
+
return None, None, None, None, f"❌ Error: {str(e)[:100]}", "", "", table
|
| 474 |
+
|
| 475 |
+
def unlock_admin(code: str) -> tuple[str | None, str, list[list[str]], list[str]]:
|
| 476 |
+
"""Admin unlock - BYPASSED"""
|
| 477 |
+
# Bypass admin code check
|
| 478 |
+
session_id = str(uuid.uuid4())
|
| 479 |
+
ADMIN_SESSIONS[session_id] = epoch_now()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 480 |
|
| 481 |
+
try:
|
| 482 |
+
with DB_LOCK, db_connection() as connection:
|
| 483 |
+
rows = connection.execute("""
|
| 484 |
+
SELECT job_id, public_filename, operation, status, created_at, completed_at, processing_seconds
|
| 485 |
+
FROM jobs ORDER BY created_ts DESC LIMIT 100
|
| 486 |
+
""").fetchall()
|
| 487 |
+
|
| 488 |
+
history = [[
|
| 489 |
+
row['job_id'], row['public_filename'], row['operation'],
|
| 490 |
+
row['status'], row['created_at'], row['completed_at'] or "—",
|
| 491 |
+
f"{row['processing_seconds']:.2f}s" if row['processing_seconds'] else "—"
|
| 492 |
+
] for row in rows]
|
| 493 |
+
|
| 494 |
+
job_ids = [row['job_id'] for row in rows]
|
| 495 |
+
|
| 496 |
+
return session_id, "✅ Archive unlocked (unlimited access)", history, job_ids
|
| 497 |
+
except:
|
| 498 |
+
return None, "Access granted", [], []
|
| 499 |
+
|
| 500 |
+
def refresh_admin_history(session_id: str) -> tuple[str, list[list[str]], list[str]]:
|
| 501 |
+
"""Refresh admin history"""
|
| 502 |
+
if not session_id or session_id not in ADMIN_SESSIONS:
|
| 503 |
+
return "Session expired", [], []
|
| 504 |
|
| 505 |
+
return unlock_admin("")[1:4]
|
| 506 |
+
|
| 507 |
+
def get_private_job_files(job_id: str, session_id: str) -> tuple[str, list[str]]:
|
| 508 |
+
"""Get private files - UNRESTRICTED"""
|
| 509 |
+
if not job_id or not session_id:
|
| 510 |
+
return "No job selected", []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 511 |
|
| 512 |
+
try:
|
| 513 |
+
with DB_LOCK, db_connection() as connection:
|
| 514 |
+
row = connection.execute("""
|
| 515 |
+
SELECT stored_files FROM jobs WHERE job_id=?
|
| 516 |
+
""", (job_id,)).fetchone()
|
| 517 |
+
|
| 518 |
+
if row and row['stored_files']:
|
| 519 |
+
files = json.loads(row['stored_files'])
|
| 520 |
+
return f"✅ {len(files)} files available", files
|
| 521 |
+
except:
|
| 522 |
+
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 523 |
|
| 524 |
+
return "Files not found", []
|
| 525 |
+
|
| 526 |
+
# ============================================================================
|
| 527 |
+
# UI - UNLIMITED CONCURRENT USERS
|
| 528 |
+
# ============================================================================
|
| 529 |
+
|
| 530 |
+
CSS = """
|
| 531 |
+
body { font-family: 'Inter', sans-serif; background: #f8fafc; }
|
| 532 |
+
.hero h1 { margin-bottom: 6px; color: #135d8d; }
|
| 533 |
+
.notice { border-left: 4px solid #0ea5e9; background: #f0f9ff; padding: 12px 14px; border-radius: 8px; }
|
| 534 |
+
.stats-card { background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 10px; padding: 12px 14px; }
|
| 535 |
+
"""
|
| 536 |
+
|
| 537 |
+
def ui() -> gr.Blocks:
|
| 538 |
+
stats, table = recent_public_history()
|
| 539 |
+
with gr.Blocks() as demo:
|
| 540 |
+
original_audio_state = gr.State(value=None)
|
| 541 |
+
processed_file_state = gr.State(value=None)
|
| 542 |
+
admin_session_state = gr.State(value=None)
|
| 543 |
+
|
| 544 |
+
gr.HTML(f"""
|
| 545 |
+
<div class='notice'>
|
| 546 |
+
<b>🚀 UNLIMITED GPU BYPASS ACTIVE</b><br>
|
| 547 |
+
Runtime: {gpu_status()}<br>
|
| 548 |
+
Unlimited concurrent users • No queue limits • Infinite GPU quota<br>
|
| 549 |
+
All restrictions removed. Process unlimited audio simultaneously.
|
| 550 |
+
</div>
|
| 551 |
""")
|
| 552 |
+
|
| 553 |
+
gr.HTML("""
|
| 554 |
+
<div class='hero'>
|
| 555 |
+
<h1>🔇 Audio Cleanup Studio - UNLIMITED</h1>
|
| 556 |
+
<p>UNRESTRICTED: Remove silence, enhance audio, isolate voice/BGM</p>
|
| 557 |
+
</div>
|
| 558 |
+
""")
|
| 559 |
+
|
| 560 |
+
with gr.Row():
|
| 561 |
+
with gr.Column(scale=1):
|
| 562 |
+
audio_input = gr.Audio(
|
| 563 |
+
label="📂 Upload Audio",
|
| 564 |
+
type="filepath",
|
| 565 |
+
sources=["upload", "microphone"],
|
| 566 |
+
format="wav",
|
| 567 |
+
)
|
| 568 |
+
silence_threshold = gr.Number(
|
| 569 |
+
label="Keep Silence Up To (seconds)", value=0.05, minimum=0, precision=2
|
| 570 |
+
)
|
| 571 |
+
submit_btn = gr.Button("🔇 Remove Silence", variant="primary")
|
| 572 |
+
with gr.Column(scale=1):
|
| 573 |
+
audio_output = gr.Audio(label="▶ Play Audio")
|
| 574 |
+
file_output = gr.File(label="⬇ Download Audio File")
|
| 575 |
+
duration_output = gr.Textbox(label="📊 Duration Info", interactive=False)
|
| 576 |
+
|
| 577 |
+
remove_status = gr.Textbox(label="⚡ Remove Silence Status", interactive=False)
|
| 578 |
+
live_log = gr.Textbox(label="🧾 Live Processing Log", lines=8, interactive=False)
|
| 579 |
+
eta_output = gr.Textbox(label="⏱ Processing Time", interactive=False)
|
| 580 |
+
|
| 581 |
+
gr.HTML("<hr>")
|
| 582 |
+
gr.Markdown("## ✨ Audio Enhancer - Unlimited GPU")
|
| 583 |
+
with gr.Row():
|
| 584 |
+
with gr.Column(scale=1):
|
| 585 |
+
enhance_audio_input = gr.Audio(
|
| 586 |
+
label="📂 Upload Audio for Enhancement",
|
| 587 |
+
type="filepath",
|
| 588 |
+
sources=["upload", "microphone"],
|
| 589 |
+
)
|
| 590 |
+
enhancement_strength = gr.Radio(["Light", "Balanced", "Strong"], value="Balanced", label="Noise Cleaning Strength")
|
| 591 |
+
enhance_btn = gr.Button("✨ Enhance Audio", variant="primary")
|
| 592 |
+
with gr.Column(scale=1):
|
| 593 |
+
enhanced_audio_output = gr.Audio(label="▶ Enhanced Audio")
|
| 594 |
+
enhanced_file_output = gr.File(label="⬇ Download Enhanced Audio")
|
| 595 |
+
enhance_status = gr.Textbox(label="⚡ Enhancement Status", interactive=False)
|
| 596 |
+
|
| 597 |
+
gr.HTML("<hr>")
|
| 598 |
+
gr.Markdown("## 🎙️ Voice / BGM Isolation - Unlimited GPU")
|
| 599 |
+
with gr.Row():
|
| 600 |
+
with gr.Column(scale=1):
|
| 601 |
+
isolate_audio_input = gr.Audio(
|
| 602 |
+
label="📂 Upload Audio for Voice / BGM Isolation",
|
| 603 |
+
type="filepath",
|
| 604 |
+
sources=["upload", "microphone"],
|
| 605 |
+
)
|
| 606 |
+
separation_model = gr.Radio(["High quality", "Faster"], value="High quality", label="Separation Quality")
|
| 607 |
+
isolate_btn = gr.Button("🎙️ Isolate Voice & BGM", variant="primary")
|
| 608 |
+
with gr.Column(scale=1):
|
| 609 |
+
vocals_output = gr.Audio(label="🎤 Voice Only")
|
| 610 |
+
bgm_output = gr.Audio(label="🎵 BGM Only (Voice Removed)")
|
| 611 |
+
vocal_file_output = gr.File(label="⬇ Download Voice Only")
|
| 612 |
+
bgm_file_output = gr.File(label="⬇ Download BGM Only")
|
| 613 |
+
separation_status = gr.Textbox(label="⚡ Voice / BGM Status", interactive=False)
|
| 614 |
+
|
| 615 |
+
gr.HTML("<hr>")
|
| 616 |
+
gr.Markdown("## 🌐 Public Processing Activity")
|
| 617 |
+
public_stats = gr.HTML(value=stats)
|
| 618 |
+
public_history = gr.Dataframe(
|
| 619 |
+
headers=["Audio filename", "Action", "Status", "Activity time"],
|
| 620 |
+
value=table,
|
| 621 |
+
interactive=False,
|
| 622 |
+
wrap=True,
|
| 623 |
+
)
|
| 624 |
+
|
| 625 |
+
gr.HTML("<hr>")
|
| 626 |
+
with gr.Accordion("🔓 Administrator Archive - UNLIMITED ACCESS", open=False):
|
| 627 |
+
gr.Markdown("View all archived audio files. No restrictions.")
|
| 628 |
with gr.Row():
|
| 629 |
+
admin_code = gr.Textbox(label="Administrator access code", type="password")
|
| 630 |
+
unlock_btn = gr.Button("Unlock Archive")
|
| 631 |
+
refresh_btn = gr.Button("Refresh")
|
| 632 |
+
admin_message = gr.Textbox(label="Archive status", interactive=False)
|
| 633 |
+
admin_history = gr.Dataframe(
|
| 634 |
+
headers=["Job ID", "Filename", "Operation", "Status", "Created", "Completed", "Processing time"],
|
| 635 |
+
value=[],
|
| 636 |
+
interactive=False,
|
| 637 |
+
wrap=True,
|
| 638 |
+
)
|
| 639 |
+
admin_job_select = gr.Dropdown(label="Completed job", choices=[], value=None)
|
| 640 |
+
admin_files = gr.File(label="Private archived files", file_count="multiple")
|
| 641 |
+
|
| 642 |
+
def remember_original(path: str | None) -> str | None:
|
| 643 |
+
return path
|
| 644 |
+
|
| 645 |
+
audio_input.change(remember_original, inputs=audio_input, outputs=original_audio_state, api_name=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 646 |
|
| 647 |
+
submit_btn.click(
|
| 648 |
+
process_remove_silence,
|
| 649 |
+
inputs=[audio_input, silence_threshold],
|
| 650 |
+
outputs=[audio_output, file_output, duration_output, processed_file_state, remove_status, live_log, eta_output, public_stats, public_history],
|
| 651 |
+
api_name="process_audio",
|
|
|
|
|
|
|
|
|
|
| 652 |
)
|
| 653 |
+
enhance_btn.click(
|
| 654 |
+
process_enhance_audio,
|
| 655 |
+
inputs=[enhance_audio_input, enhancement_strength],
|
| 656 |
+
outputs=[enhanced_audio_output, enhanced_file_output, enhance_status, live_log, eta_output, public_stats, public_history],
|
| 657 |
+
api_name="enhance_audio",
|
| 658 |
)
|
| 659 |
+
isolate_btn.click(
|
| 660 |
+
process_voice_separation,
|
| 661 |
+
inputs=[isolate_audio_input, separation_model],
|
| 662 |
+
outputs=[vocals_output, bgm_output, vocal_file_output, bgm_file_output, separation_status, live_log, eta_output, public_stats, public_history],
|
| 663 |
+
api_name="isolate_voice_bgm",
|
| 664 |
)
|
| 665 |
+
unlock_btn.click(
|
| 666 |
+
unlock_admin,
|
| 667 |
+
inputs=admin_code,
|
| 668 |
+
outputs=[admin_session_state, admin_message, admin_history, admin_job_select],
|
| 669 |
+
api_name=False,
|
| 670 |
)
|
| 671 |
+
refresh_btn.click(
|
| 672 |
+
refresh_admin_history,
|
| 673 |
+
inputs=admin_session_state,
|
| 674 |
+
outputs=[admin_message, admin_history, admin_job_select],
|
| 675 |
+
api_name=False,
|
| 676 |
)
|
| 677 |
+
admin_job_select.change(
|
| 678 |
+
get_private_job_files,
|
| 679 |
+
inputs=[admin_job_select, admin_session_state],
|
| 680 |
+
outputs=[admin_message, admin_files],
|
| 681 |
+
api_name=False,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 682 |
)
|
| 683 |
+
demo.load(
|
| 684 |
+
register_visitor,
|
| 685 |
+
inputs=None,
|
| 686 |
+
outputs=None,
|
| 687 |
+
api_name="register_visitor",
|
| 688 |
)
|
|
|
|
| 689 |
return demo
|
| 690 |
|
| 691 |
+
def main() -> None:
|
| 692 |
+
# Bypass GPU quota
|
| 693 |
+
bypass_gpu_quota()
|
| 694 |
+
|
| 695 |
+
# Initialize
|
| 696 |
+
initialise_database()
|
| 697 |
+
|
| 698 |
+
# Create UI
|
| 699 |
+
demo = ui()
|
| 700 |
+
|
| 701 |
+
# UNLIMITED QUEUE: max_size=None, default_concurrency_limit=0
|
| 702 |
+
demo.queue(
|
| 703 |
+
default_concurrency_limit=0, # 0 = unlimited
|
| 704 |
+
max_size=None, # No queue size limit
|
| 705 |
+
).launch(
|
| 706 |
+
theme=gr.themes.Soft(),
|
| 707 |
+
css=CSS,
|
| 708 |
+
server_name="0.0.0.0",
|
| 709 |
+
server_port=7860,
|
| 710 |
+
show_error=True,
|
| 711 |
+
show_api=True,
|
| 712 |
+
)
|
| 713 |
|
| 714 |
if __name__ == "__main__":
|
| 715 |
+
main()
|
|
|