Hydui commited on
Commit
8d720e9
·
verified ·
1 Parent(s): 7e60d86

Upload 6 files

Browse files
Files changed (6) hide show
  1. Dockerfile +7 -0
  2. README.md +41 -13
  3. app.py +199 -710
  4. hf_admin_panel.zip +3 -0
  5. models.py +39 -0
  6. requirements.txt +3 -11
Dockerfile ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+ WORKDIR /app
3
+ COPY requirements.txt .
4
+ RUN pip install --no-cache-dir -r requirements.txt
5
+ COPY . .
6
+ EXPOSE 7860
7
+ CMD ["python", "app.py"]
README.md CHANGED
@@ -1,13 +1,41 @@
1
- ---
2
- title: Inbluff
3
- emoji: 😻
4
- colorFrom: green
5
- colorTo: green
6
- sdk: gradio
7
- sdk_version: 6.28.0
8
- python_version: '3.13'
9
- app_file: app.py
10
- pinned: false
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # HF Space Admin Panel
2
+
3
+ Hugging Face Space पर चलने वाला Flask आधारित Admin Panel.
4
+
5
+ ## Features
6
+ - Secure admin login/session
7
+ - Dashboard statistics
8
+ - User create + active/inactive control
9
+ - Project management
10
+ - Website settings
11
+ - Announcements
12
+ - API key generation (raw key केवल creation के समय दिखती है)
13
+ - Public health/settings API
14
+ - SQLite database
15
+ - Mobile-friendly admin UI
16
+
17
+ ## Hugging Face पर चलाने का तरीका
18
+
19
+ 1. नया **Docker Space** बनाएं।
20
+ 2. इस project की सभी files upload करें।
21
+ 3. Space Settings → Variables and secrets में:
22
+ - `SECRET_KEY`
23
+ - `ADMIN_EMAIL`
24
+ - `ADMIN_PASSWORD`
25
+ सेट करें।
26
+ 4. Space restart करें।
27
+ 5. `/login` खोलकर login करें।
28
+
29
+ > Production में default password कभी इस्तेमाल न करें। SQLite को permanent production database मानकर न चलाएं यदि Space का storage persistent नहीं है। बड़े project के लिए external PostgreSQL जैसे database का उपयोग करें।
30
+
31
+ ## Website को control करना
32
+
33
+ आपकी अलग website इस endpoint से settings पढ़ सकती है:
34
+
35
+ `GET /api/public/settings`
36
+
37
+ और health check:
38
+
39
+ `GET /api/health`
40
+
41
+ अगले चरण में आपकी वास्तविक website के API के अनुसार इसमें domain verification, deployment controls, file manager, logs और custom API integration जोड़े जा सकते हैं।
app.py CHANGED
@@ -1,713 +1,202 @@
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,
704
- max_size=None,
705
- ).launch(
706
- theme=gr.themes.Soft(),
707
- css=CSS,
708
- server_name="0.0.0.0",
709
- server_port=7860,
710
- )
711
 
712
  if __name__ == "__main__":
713
- main()
 
 
1
+ import os, secrets, hashlib
2
+ from datetime import datetime
3
+ from flask import Flask, render_template, request, redirect, url_for, session, jsonify, abort, flash
4
+ from werkzeug.security import generate_password_hash, check_password_hash
5
+ from models import db, User, Project, Setting, Announcement, ApiKey
6
+
7
+ app = Flask(__name__)
8
+ app.config["SECRET_KEY"] = os.environ.get("SECRET_KEY", secrets.token_hex(32))
9
+ app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("DATABASE_URL", "sqlite:///admin.db")
10
+ app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
11
+ db.init_app(app)
12
+
13
+ def init_db():
14
+ with app.app_context():
15
+ db.create_all()
16
+ admin_email = os.environ.get("ADMIN_EMAIL", "admin@example.com")
17
+ admin_password = os.environ.get("ADMIN_PASSWORD", "change-me-now")
18
+ if not User.query.filter_by(email=admin_email).first():
19
+ db.session.add(User(
20
+ email=admin_email,
21
+ password_hash=generate_password_hash(admin_password),
22
+ role="admin",
23
+ active=True
24
+ ))
25
+ defaults = {
26
+ "site_name": "My Website",
27
+ "site_url": "https://example.com",
28
+ "maintenance": "0",
29
+ "announcement": "Welcome!"
30
+ }
31
+ for key, value in defaults.items():
32
+ if not Setting.query.filter_by(key=key).first():
33
+ db.session.add(Setting(key=key, value=value))
34
+ db.session.commit()
35
+
36
+ def admin_required():
37
+ if not session.get("user_id"):
38
+ return redirect(url_for("login"))
39
+ user = db.session.get(User, session["user_id"])
40
+ if not user or not user.active or user.role != "admin":
41
+ session.clear()
42
+ return redirect(url_for("login"))
43
+ return None
44
+
45
+ @app.context_processor
46
+ def globals():
47
+ return {"current_user": db.session.get(User, session.get("user_id")) if session.get("user_id") else None}
48
+
49
+ @app.route("/login", methods=["GET", "POST"])
50
+ def login():
51
+ if request.method == "POST":
52
+ user = User.query.filter_by(email=request.form["email"].strip().lower()).first()
53
+ if user and user.active and check_password_hash(user.password_hash, request.form["password"]):
54
+ session["user_id"] = user.id
55
+ return redirect(url_for("dashboard"))
56
+ flash("ईमेल या पासवर्ड गलत है।", "error")
57
+ return render_template("login.html")
58
+
59
+ @app.route("/logout")
60
+ def logout():
61
+ session.clear()
62
+ return redirect(url_for("login"))
63
+
64
+ @app.route("/")
65
+ def dashboard():
66
+ guard = admin_required()
67
+ if guard: return guard
68
+ stats = {
69
+ "users": User.query.count(),
70
+ "projects": Project.query.count(),
71
+ "announcements": Announcement.query.count(),
72
+ "api_keys": ApiKey.query.count()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  }
74
+ return render_template("dashboard.html", stats=stats)
75
+
76
+ @app.route("/users", methods=["GET", "POST"])
77
+ def users():
78
+ guard = admin_required()
79
+ if guard: return guard
80
+ if request.method == "POST":
81
+ email = request.form["email"].strip().lower()
82
+ password = request.form["password"]
83
+ role = request.form.get("role", "user")
84
+ if User.query.filter_by(email=email).first():
85
+ flash("यह ईमेल पहले से मौजूद है।", "error")
86
+ else:
87
+ db.session.add(User(email=email, password_hash=generate_password_hash(password), role=role))
88
+ db.session.commit()
89
+ flash("यूज़र बना दिया गया।", "success")
90
+ return redirect(url_for("users"))
91
+ return render_template("users.html", users=User.query.order_by(User.id.desc()).all())
92
+
93
+ @app.post("/users/<int:user_id>/toggle")
94
+ def toggle_user(user_id):
95
+ guard = admin_required()
96
+ if guard: return guard
97
+ user = db.session.get(User, user_id)
98
+ if user:
99
+ user.active = not user.active
100
+ db.session.commit()
101
+ return redirect(url_for("users"))
102
+
103
+ @app.route("/projects", methods=["GET", "POST"])
104
+ def projects():
105
+ guard = admin_required()
106
+ if guard: return guard
107
+ if request.method == "POST":
108
+ db.session.add(Project(
109
+ name=request.form["name"],
110
+ slug=request.form["slug"],
111
+ description=request.form.get("description", ""),
112
+ status=request.form.get("status", "active"),
113
+ url=request.form.get("url", "")
114
+ ))
115
+ db.session.commit()
116
+ flash("प्रोजेक्ट जोड़ दिया गया।", "success")
117
+ return redirect(url_for("projects"))
118
+ return render_template("projects.html", projects=Project.query.order_by(Project.id.desc()).all())
119
+
120
+ @app.post("/projects/<int:project_id>/delete")
121
+ def delete_project(project_id):
122
+ guard = admin_required()
123
+ if guard: return guard
124
+ project = db.session.get(Project, project_id)
125
+ if project:
126
+ db.session.delete(project)
127
+ db.session.commit()
128
+ return redirect(url_for("projects"))
129
+
130
+ @app.route("/settings", methods=["GET", "POST"])
131
+ def settings():
132
+ guard = admin_required()
133
+ if guard: return guard
134
+ if request.method == "POST":
135
+ for key in ["site_name", "site_url", "maintenance", "announcement"]:
136
+ value = request.form.get(key, "")
137
+ item = Setting.query.filter_by(key=key).first()
138
+ if item:
139
+ item.value = value
140
+ else:
141
+ db.session.add(Setting(key=key, value=value))
142
+ db.session.commit()
143
+ flash("Website settings सेव हो गईं।", "success")
144
+ settings = {x.key: x.value for x in Setting.query.all()}
145
+ return render_template("settings.html", settings=settings)
146
+
147
+ @app.route("/announcements", methods=["GET", "POST"])
148
+ def announcements():
149
+ guard = admin_required()
150
+ if guard: return guard
151
+ if request.method == "POST":
152
+ db.session.add(Announcement(
153
+ title=request.form["title"],
154
+ body=request.form["body"],
155
+ active=True
156
+ ))
157
+ db.session.commit()
158
+ return redirect(url_for("announcements"))
159
+ return render_template("announcements.html", announcements=Announcement.query.order_by(Announcement.id.desc()).all())
160
+
161
+ @app.post("/announcements/<int:item_id>/toggle")
162
+ def toggle_announcement(item_id):
163
+ guard = admin_required()
164
+ if guard: return guard
165
+ item = db.session.get(Announcement, item_id)
166
+ if item:
167
+ item.active = not item.active
168
+ db.session.commit()
169
+ return redirect(url_for("announcements"))
170
+
171
+ @app.route("/api-keys", methods=["GET", "POST"])
172
+ def api_keys():
173
+ guard = admin_required()
174
+ if guard: return guard
175
+ generated = None
176
+ if request.method == "POST":
177
+ raw = "sk_" + secrets.token_urlsafe(32)
178
+ db.session.add(ApiKey(
179
+ name=request.form["name"],
180
+ key_hash=hashlib.sha256(raw.encode()).hexdigest()
181
+ ))
182
+ db.session.commit()
183
+ generated = raw
184
+ return render_template("api_keys.html", keys=ApiKey.query.order_by(ApiKey.id.desc()).all(), generated=generated)
185
+
186
+ @app.get("/api/health")
187
+ def health():
188
+ return jsonify({"ok": True, "service": "HF Admin Panel", "time": datetime.utcnow().isoformat() + "Z"})
189
+
190
+ @app.get("/api/public/settings")
191
+ def public_settings():
192
+ settings = {x.key: x.value for x in Setting.query.all()}
193
+ return jsonify({
194
+ "site_name": settings.get("site_name", ""),
195
+ "site_url": settings.get("site_url", ""),
196
+ "maintenance": settings.get("maintenance", "0"),
197
+ "announcement": settings.get("announcement", "")
198
+ })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
199
 
200
  if __name__ == "__main__":
201
+ init_db()
202
+ app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 7860)))
hf_admin_panel.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:859a04d3511358754f83810242ed24aab6f788546fee65532349680c06a89f8a
3
+ size 10224
models.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask_sqlalchemy import SQLAlchemy
2
+ from datetime import datetime
3
+
4
+ db = SQLAlchemy()
5
+
6
+ class User(db.Model):
7
+ id = db.Column(db.Integer, primary_key=True)
8
+ email = db.Column(db.String(255), unique=True, nullable=False)
9
+ password_hash = db.Column(db.String(255), nullable=False)
10
+ role = db.Column(db.String(30), default="user")
11
+ active = db.Column(db.Boolean, default=True)
12
+ created_at = db.Column(db.DateTime, default=datetime.utcnow)
13
+
14
+ class Project(db.Model):
15
+ id = db.Column(db.Integer, primary_key=True)
16
+ name = db.Column(db.String(120), nullable=False)
17
+ slug = db.Column(db.String(120), nullable=False)
18
+ description = db.Column(db.Text, default="")
19
+ status = db.Column(db.String(30), default="active")
20
+ url = db.Column(db.String(500), default="")
21
+ created_at = db.Column(db.DateTime, default=datetime.utcnow)
22
+
23
+ class Setting(db.Model):
24
+ id = db.Column(db.Integer, primary_key=True)
25
+ key = db.Column(db.String(120), unique=True, nullable=False)
26
+ value = db.Column(db.Text, default="")
27
+
28
+ class Announcement(db.Model):
29
+ id = db.Column(db.Integer, primary_key=True)
30
+ title = db.Column(db.String(200), nullable=False)
31
+ body = db.Column(db.Text, default="")
32
+ active = db.Column(db.Boolean, default=True)
33
+ created_at = db.Column(db.DateTime, default=datetime.utcnow)
34
+
35
+ class ApiKey(db.Model):
36
+ id = db.Column(db.Integer, primary_key=True)
37
+ name = db.Column(db.String(120), nullable=False)
38
+ key_hash = db.Column(db.String(255), nullable=False)
39
+ created_at = db.Column(db.DateTime, default=datetime.utcnow)
requirements.txt CHANGED
@@ -1,11 +1,3 @@
1
- gradio
2
- torch>=2.0.0
3
- torchaudio>=2.0.0
4
- pydub>=0.25.1
5
- demucs>=4.0.0
6
- numpy>=1.24.0
7
- scipy>=1.10.0
8
- librosa>=0.10.0
9
- transformers>=4.30.0
10
- huggingface-hub>=0.16.0
11
- spaces
 
1
+ Flask==3.1.2
2
+ Flask-SQLAlchemy==3.1.1
3
+ Werkzeug==3.1.3