Update app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394import gradio as grimport requestsimport osfrom pytrends.request import TrendReqYT_API_KEY = os.getenv("YT_API_KEY", "AIzaSyCy8ROvJzi5DrBV-7PbwWq7QQ4w0e_F8rU")def get_video_id(url):"""यह फंक्शन अब दोनों तरह के लिंक को सपोर्ट करेगा"""if "v=" in url:return url.split("v=")[1].split("&")[0]elif "youtu.be/" in url:return url.split("youtu.be/")[1].split("?")[0]return Nonedef get_video_stats(video_id):url = f"https://www.googleapis.com/youtube/v3/videos?part=snippet,statistics&id={video_id}&key={YT_API_KEY}"response = requests.get(url)data = response.json()if "items" in data and data["items"]:return data["items"][0]return Nonedef get_trending_trends(niche):try:pytrends = TrendReq(hl='en-US', tz=360)pytrends.build_payload(kw_list=[niche], timeframe='now 7-d')trends = pytrends.interest_over_time()top_keywords = trends.sort_values(by=niche, ascending=False).head(3).index.tolist()return top_keywordsexcept:return ["AI Trends 2026", "Tech", "Gadgets"]def boost_video(video_url):if not video_url:return "❌ कृपया वैलिड YouTube लिंक डालें!"video_id = get_video_id(video_url)if not video_id:return "❌ अमान्य YouTube लिंक! (कृपया सही लिंक डालें)"data = get_video_stats(video_id)if not data:return "❌ वीडियो नहीं मिला! वीडियो पब्लिक है और API Key सही है चेक करें।"snippet = data["snippet"]stats = data["statistics"]title = snippet["title"]channel = snippet["channelTitle"]views = int(stats.get("viewCount", 0))likes = int(stats.get("likeCount", 0))comments = int(stats.get("commentCount", 0))niche = title.split()[0] if title else "General"trends = get_trending_trends(niche)ctr_pred = round(len(title) * 0.5 + 5, 1)report = f"""🚀 **यूट्यूब बूस्ट रिपोर्ट**📺 **टाइटल:** {title}🎥 **चैनल:** {channel}👁️ **व्यूज़:** {views:,}👍 **लाइक्स:** {likes:,}💬 **कमेंट्स:** {comments:,}📈 **CTR प्रेडिक्शन:** {ctr_pred}%🔥 **ट्रेंडिंग टॉपिक्स:** {", ".join(trends)}🛠️ **बूस्ट प्लान:**1. टाइटल में "{trends[0] if trends else 'Trending'}" जोड़ें2. थंबनेल को लाल/हाइ-कंट्रास्ट बनाएँ3. रिटेंशन बढ़ाने के लिए बीच में प्रश्न डालें4. रात 8:30–10:00 PM (IST) पर अपलोड करें5. पहले 2 घंटे में 5-6 रियल कमेंट करें"""return reportwith gr.Blocks() as demo:gr.Markdown("## 🚀 YouTube वीडियो बूस्ट टूल (Gradio)")gr.Markdown("नीचे अपना YouTube लिंक डालें और 'बूस्ट करें' पर क्लिक करें।")with gr.Row():with gr.Column(scale=3):video_url = gr.Textbox(label="YouTube लिंक", placeholder="https://www.youtube.com/watch?v=... या https://youtu.be/...")with gr.Column(scale=1):btn = gr.Button("🚀 बूस्ट करें", variant="primary")output = gr.Markdown(label="बूस्ट रिपोर्ट")btn.click(fn=boost_video, inputs=video_url, outputs=output)if __name__ == "__main__":demo.launch(theme=gr.themes.Soft())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958"""Audio Cleanup Studio – a Gradio Space with real audio processing and private history.Deployment secrets and storage:- ADMIN_ACCESS_CODE: required to unlock the administrator archive.- DATA_DIR: optional persistent mounted directory; uses /data automatically when available.- HISTORY_RETENTION_DAYS: number of days to retain private audio artifacts (default: 30; 0 disables expiry).- MAX_AUDIO_MINUTES: maximum accepted input duration for costly operations (default: 15)."""from __future__ import annotationsimport datetime as dtimport hmacimport jsonimport mathimport osimport queueimport secretsimport shutilimport sqlite3import subprocessimport sysimport threadingimport timeimport uuidfrom pathlib import Pathfrom typing import Generator, Iterableimport gradio as grfrom pydub import AudioSegment, effectsfrom pydub.silence import split_on_silencetry:import spaces # Hugging Face ZeroGPU runtime; optional for local CPU runs.except ImportError:spaces = None# -----------------------------------------------------------------------------# Runtime configuration# -----------------------------------------------------------------------------APP_ROOT = Path(__file__).resolve().parentDEFAULT_DATA_DIR = Path("/data") if Path("/data").exists() else APP_ROOT / "data"DATA_DIR = Path(os.getenv("DATA_DIR", str(DEFAULT_DATA_DIR))).expanduser().resolve()TMP_DIR = DATA_DIR / "tmp"HISTORY_DIR = DATA_DIR / "audio_history"DB_PATH = DATA_DIR / "audio_history.sqlite3"HISTORY_RETENTION_DAYS = int(os.getenv("HISTORY_RETENTION_DAYS", "30"))MAX_AUDIO_MINUTES = float(os.getenv("MAX_AUDIO_MINUTES", "15"))MAX_AUDIO_SECONDS = MAX_AUDIO_MINUTES * 60MAX_FILE_BYTES = int(os.getenv("MAX_FILE_BYTES", str(500 * 1024 * 1024)))PROCESS_TIMEOUT_SECONDS = int(os.getenv("PROCESS_TIMEOUT_SECONDS", "5400"))ADMIN_SESSION_TTL_SECONDS = int(os.getenv("ADMIN_SESSION_TTL_SECONDS", "1800"))for directory in (DATA_DIR, TMP_DIR, HISTORY_DIR):directory.mkdir(parents=True, exist_ok=True)DB_LOCK = threading.Lock()ADMIN_SESSIONS: dict[str, float] = {}# -----------------------------------------------------------------------------# Storage and history# -----------------------------------------------------------------------------def utc_now() -> str:return dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")def epoch_now() -> float:return time.time()def db_connection() -> sqlite3.Connection:connection = sqlite3.connect(DB_PATH, timeout=20)connection.row_factory = sqlite3.Rowreturn connectiondef initialise_database() -> None:with DB_LOCK, db_connection() as connection:connection.execute("""CREATE TABLE IF NOT EXISTS jobs (job_id TEXT PRIMARY KEY,public_filename TEXT NOT NULL,operation TEXT NOT NULL,status TEXT NOT NULL,created_at TEXT NOT NULL,created_ts REAL NOT NULL,completed_at TEXT,duration_seconds REAL,processing_seconds REAL,details TEXT,storage_dir TEXT,stored_files TEXT)""")connection.execute("""CREATE TABLE IF NOT EXISTS visitors (visitor_id TEXT PRIMARY KEY,first_seen_ts REAL NOT NULL,last_seen_ts REAL NOT NULL)""")connection.commit()def record_job_started(job_id: str, filename: str, operation: str, duration: float) -> None:with DB_LOCK, db_connection() as connection:connection.execute("""INSERT INTO jobs (job_id, public_filename, operation, status, created_at, created_ts, duration_seconds)VALUES (?, ?, ?, 'Processing', ?, ?, ?)""",(job_id, filename, operation, utc_now(), epoch_now(), duration),)connection.commit()def record_job_finished(job_id: str,status: str,processing_seconds: float,details: str,storage_dir: Path | None = None,stored_files: list[Path] | None = None,) -> None:files = [str(path) for path in (stored_files or [])]with DB_LOCK, db_connection() as connection:connection.execute("""UPDATE jobsSET status = ?, completed_at = ?, processing_seconds = ?, details = ?, storage_dir = ?, stored_files = ?WHERE job_id = ?""",(status,utc_now(),processing_seconds,details[:1000],str(storage_dir) if storage_dir else None,json.dumps(files),job_id,),)connection.commit()def purge_expired_history() -> None:"""Remove expired private artifacts and their records. Zero keeps all records."""if HISTORY_RETENTION_DAYS <= 0:returncutoff = epoch_now() - (HISTORY_RETENTION_DAYS * 86400)with DB_LOCK, db_connection() as connection:stale_rows = connection.execute("SELECT job_id, storage_dir FROM jobs WHERE created_ts < ?", (cutoff,)).fetchall()for row in stale_rows:storage_dir = row["storage_dir"]if storage_dir:candidate = Path(storage_dir).resolve()if candidate.is_relative_to(HISTORY_DIR.resolve()):shutil.rmtree(candidate, ignore_errors=True)connection.execute("DELETE FROM jobs WHERE created_ts < ?", (cutoff,))connection.commit()def recent_public_history(limit: int = 25) -> tuple[str, list[list[str]]]:with DB_LOCK, db_connection() as connection:completed = connection.execute("SELECT COUNT(*) AS count FROM jobs WHERE status = 'Completed'").fetchone()["count"]rows = connection.execute("""SELECT public_filename, operation, status, COALESCE(completed_at, created_at) AS activity_atFROM jobsORDER BY created_ts DESCLIMIT ?""",(limit,),).fetchall()table = [[row["public_filename"], row["operation"], row["status"], row["activity_at"]] for row in rows]stats = (f"<div class='stats-card'><b>{completed}</b> successful processing job(s) completed. ""This count represents jobs, not verified unique people. Only filenames and selected actions are public; ""uploaded and processed audio remain administrator-only.</div>")return stats, tabledef visitor_heartbeat(request: gr.Request | None = None) -> tuple[int, int]:"""Track anonymous Gradio sessions and return active and total visitors.The browser's Gradio session hash is used only as a short-lived anonymousvisitor identifier. No IP address, filename, audio, or account data isstored. A visitor is considered active if the last heartbeat was withinthe last 90 seconds; the HTML client sends a heartbeat every 15 seconds."""visitor_id = getattr(request, "session_hash", None) or "anonymous-session"now = epoch_now()with DB_LOCK, db_connection() as connection:connection.execute("""INSERT INTO visitors (visitor_id, first_seen_ts, last_seen_ts)VALUES (?, ?, ?)ON CONFLICT(visitor_id) DO UPDATE SET last_seen_ts = excluded.last_seen_ts""",(visitor_id, now, now),)active = connection.execute("SELECT COUNT(*) AS count FROM visitors WHERE last_seen_ts >= ?",(now - 90,),).fetchone()["count"]total = connection.execute("SELECT COUNT(*) AS count FROM visitors").fetchone()["count"]connection.commit()return int(active), int(total)def register_visitor(request: gr.Request | None = None) -> tuple[int, int]:"""Backward-compatible alias for clients using the old endpoint name."""return visitor_heartbeat(request)def admin_rows(limit: int = 100) -> list[list[str]]:with DB_LOCK, db_connection() as connection:rows = connection.execute("""SELECT job_id, public_filename, operation, status, created_at,COALESCE(completed_at, '—') AS completed_at,COALESCE(processing_seconds, 0) AS processing_secondsFROM jobsORDER BY created_ts DESCLIMIT ?""",(limit,),).fetchall()return [[row["job_id"],row["public_filename"],row["operation"],row["status"],row["created_at"],row["completed_at"],f"{row['processing_seconds']:.1f}s" if row["processing_seconds"] else "—",]for row in rows]def admin_job_choices() -> list[tuple[str, str]]:with DB_LOCK, db_connection() as connection:rows = connection.execute("""SELECT job_id, public_filename, operation, COALESCE(completed_at, created_at) AS activity_atFROM jobsWHERE status = 'Completed'ORDER BY created_ts DESCLIMIT 100""").fetchall()return [(f"{row['activity_at']} · {row['public_filename']} · {row['operation']}", row["job_id"])for row in rows]def private_archive(job_id: str, original: Path, outputs: Iterable[Path]) -> tuple[Path, list[Path]]:archive_dir = (HISTORY_DIR / job_id).resolve()archive_dir.mkdir(parents=True, exist_ok=True)copied: list[Path] = []artifacts = [(original, "original"), *[(path, "result") for path in outputs]]for source, prefix in artifacts:source = Path(source)if not source.exists():continuedestination = archive_dir / f"{prefix}_{safe_filename(source.name)}"shutil.copy2(source, destination)copied.append(destination)return archive_dir, copied# -----------------------------------------------------------------------------# Authentication for the private admin panel# -----------------------------------------------------------------------------def clean_admin_sessions() -> None:now = epoch_now()for token, expires_at in list(ADMIN_SESSIONS.items()):if expires_at <= now:ADMIN_SESSIONS.pop(token, None)def is_valid_admin_session(token: str | None) -> bool:clean_admin_sessions()return bool(token and ADMIN_SESSIONS.get(token, 0) > epoch_now())def unlock_admin(access_code: str) -> tuple[str | None, str, list[list[str]], gr.Dropdown]:configured_code = os.getenv("ADMIN_ACCESS_CODE", "")if not configured_code:return None, "Admin archive is disabled: set the `ADMIN_ACCESS_CODE` Space Secret first.", [], gr.update(choices=[], value=None)if not access_code or not hmac.compare_digest(access_code, configured_code):return None, "Incorrect access code.", [], gr.update(choices=[], value=None)token = secrets.token_urlsafe(32)ADMIN_SESSIONS[token] = epoch_now() + ADMIN_SESSION_TTL_SECONDSchoices = admin_job_choices()return token, "Admin archive unlocked for this browser session.", admin_rows(), gr.update(choices=choices, value=choices[0][1] if choices else None)def refresh_admin_history(token: str | None) -> tuple[str, list[list[str]], gr.Dropdown]:if not is_valid_admin_session(token):return "Access code required or session expired.", [], gr.update(choices=[], value=None)choices = admin_job_choices()return "Private archive refreshed.", admin_rows(), gr.update(choices=choices, value=choices[0][1] if choices else None)def get_private_job_files(job_id: str | None, token: str | None) -> tuple[str, list[str] | None]:if not is_valid_admin_session(token):return "Access code required or session expired.", Noneif not job_id:return "Choose an archived completed job.", Nonewith DB_LOCK, db_connection() as connection:row = connection.execute("SELECT stored_files FROM jobs WHERE job_id = ?", (job_id,)).fetchone()if not row or not row["stored_files"]:return "No private artifacts are available for this job.", Nonehistory_root = HISTORY_DIR.resolve()files = []for file_name in json.loads(row["stored_files"]):candidate = Path(file_name).resolve()if candidate.is_relative_to(history_root) and candidate.is_file():files.append(str(candidate))return (f"Loaded {len(files)} private artifact(s).", files or None)# -----------------------------------------------------------------------------# Audio helpers# -----------------------------------------------------------------------------def safe_filename(name: str) -> str:stem = "".join(char if char.isalnum() or char in "-_" else "_" for char in Path(name).stem)stem = "_".join(filter(None, stem.split("_"))) or "audio"return f"{stem[:80]}{Path(name).suffix.lower() or '.wav'}"def make_job_directory(job_id: str) -> Path:path = (TMP_DIR / job_id).resolve()path.mkdir(parents=True, exist_ok=True)return pathdef copy_input_to_job(file_path: str, job_dir: Path) -> Path:source = Path(file_path).resolve()if not source.is_file():raise FileNotFoundError("Uploaded audio file is no longer available. Please upload it again.")if source.stat().st_size > MAX_FILE_BYTES:raise ValueError(f"File is larger than the {MAX_FILE_BYTES // (1024 * 1024)} MB limit.")destination = job_dir / f"input_{safe_filename(source.name)}"shutil.copy2(source, destination)return destinationdef audio_duration(file_path: Path | str) -> float:return len(AudioSegment.from_file(file_path)) / 1000.0def validate_duration(duration: float) -> None:if duration <= 0:raise ValueError("The uploaded audio has no playable duration.")if duration > MAX_AUDIO_SECONDS:raise ValueError(f"This audio is {duration / 60:.1f} minutes. The current limit is {MAX_AUDIO_MINUTES:g} minutes per job.")def format_seconds(value: float) -> str:value = max(0, int(round(value)))if value < 60:return f"about {value}s"return f"about {value // 60}m {value % 60:02d}s"def estimated_seconds(operation: str, duration: float, quality: str = "") -> float:if operation == "Remove silence":return max(3, duration * 0.06 + 3)if operation == "Enhance audio":return max(15, duration * 0.65 + 15)multiplier = 1.5 if quality == "htdemucs" else 0.9return max(35, duration * multiplier + 35)def ffmpeg_convert_to_wav(source: Path, destination: Path, sample_rate: int = 48000, mono: bool = True) -> None:command = ["ffmpeg", "-y", "-hide_banner", "-loglevel", "error", "-i", str(source),"-ar", str(sample_rate), "-c:a", "pcm_s16le",]if mono:command.extend(["-ac", "1"])command.append(str(destination))completed = subprocess.run(command, capture_output=True, text=True, timeout=300, check=False)if completed.returncode != 0:error = completed.stderr.strip() or "FFmpeg could not decode this audio file."raise RuntimeError(error[-500:])def remove_silence_audio(source: Path, destination: Path, keep_silence_ms: int) -> tuple[float, float, float]:sound = AudioSegment.from_file(source)before = len(sound) / 1000.0if sound.dBFS == float("-inf"):raise ValueError("The uploaded file is completely silent.")# Adapts to the source loudness while staying in a safe range for normal speech/music.threshold = max(-55.0, min(-25.0, sound.dBFS - 18.0))chunks = split_on_silence(sound,min_silence_len=120,silence_thresh=threshold,keep_silence=max(0, keep_silence_ms),)if not chunks:raise ValueError("No non-silent audio could be found using the selected silence setting.")combined = AudioSegment.empty()for chunk in chunks:combined += chunkcombined.export(destination, format="wav")after = len(combined) / 1000.0return before, after, thresholddef spectral_denoise_fallback(source: Path, destination: Path, strength: str) -> None:"""A real, audible fallback when DeepFilterNet cannot initialise."""import numpy as npimport noisereduce as nrfrom scipy.signal import butter, sosfiltfiltsound = AudioSegment.from_file(source).set_sample_width(2)sample_rate = sound.frame_ratesamples = np.asarray(sound.get_array_of_samples(), dtype=np.float32)channels = sound.channelsif channels > 1:samples = samples.reshape((-1, channels)).Telse:samples = samples[None, :]samples /= 32768.0prop_decrease = {"Light": 0.65, "Balanced": 0.82, "Strong": 0.95}.get(strength, 0.82)cleaned_channels = []sos = butter(4, 80, btype="highpass", fs=sample_rate, output="sos")for channel in samples:denoised = nr.reduce_noise(y=channel,sr=sample_rate,stationary=False,prop_decrease=prop_decrease,n_fft=min(2048, max(512, 2 ** int(math.log2(max(512, len(channel) // 16))))),)cleaned_channels.append(sosfiltfilt(sos, denoised))result = np.vstack(cleaned_channels).T if channels > 1 else cleaned_channels[0]result = np.clip(result, -1.0, 1.0)pcm = (result * 32767).astype(np.int16)if channels > 1:pcm = pcm.reshape(-1)enhanced = AudioSegment(pcm.tobytes(), frame_rate=sample_rate, sample_width=2, channels=channels)enhanced = effects.normalize(enhanced, headroom=1.0)enhanced.export(destination, format="wav")def find_deepfilter_command() -> str | None:for executable in ("deepFilter", "deep-filter"):found = shutil.which(executable)if found:return foundreturn Nonedef preferred_torch_device() -> str:"""Use the RTX device when the Space has been assigned one."""try:import torchreturn "cuda" if torch.cuda.is_available() else "cpu"except Exception:return "cpu"def subprocess_progress(command: list[str],estimate: float,label: str,cwd: Path | None = None,) -> Generator[tuple[str, float], None, None]:"""Yield elapsed-time updates while a model subprocess is running."""process = subprocess.Popen(command,cwd=str(cwd) if cwd else None,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True,bufsize=1,)lines: queue.Queue[str] = queue.Queue()def reader() -> None:if process.stdout is None:returnfor line in iter(process.stdout.readline, ""):if line.strip():lines.put(line.strip())threading.Thread(target=reader, daemon=True).start()started = time.monotonic()output_lines: list[str] = []last_yield = 0.0while process.poll() is None:while True:try:output_lines.append(lines.get_nowait())except queue.Empty:breakelapsed = time.monotonic() - startedif elapsed - last_yield >= 1.0:remaining = max(0, estimate - elapsed)latest = output_lines[-1] if output_lines else f"{label} is running…"yield latest[-240:], remaininglast_yield = elapsedtime.sleep(0.2)while True:try:output_lines.append(lines.get_nowait())except queue.Empty:breakif process.returncode != 0:diagnostic = "\n".join(output_lines[-8:]) or f"Command exited with code {process.returncode}."raise RuntimeError(diagnostic[-1200:])yield f"{label} finished.", 0.0def locate_enhanced_file(directory: Path, input_file: Path) -> Path | None:for candidate in sorted(directory.rglob("*.wav")):if candidate.resolve() != input_file.resolve():return candidatereturn Nonedef locate_stem(directory: Path, stem: str) -> Path | None:matches = list(directory.rglob(f"{stem}.mp3")) + list(directory.rglob(f"{stem}.wav"))return matches[0] if matches else Nonedef cleanup_temporary_files(max_age_seconds: int = 6 * 3600) -> None:cutoff = epoch_now() - max_age_secondsfor child in TMP_DIR.iterdir():try:if child.stat().st_mtime < cutoff:if child.is_dir():shutil.rmtree(child, ignore_errors=True)else:child.unlink(missing_ok=True)except FileNotFoundError:pass# -----------------------------------------------------------------------------# Gradio processing flows – generators make logs and ETA visible during work.# -----------------------------------------------------------------------------def process_remove_silence(audio_file: str | None,keep_silence_seconds: float,progress: gr.Progress = gr.Progress(),):logs: list[str] = []started = time.monotonic()job_id = uuid.uuid4().hexstats, table = recent_public_history()def state(status: str, eta: str, audio=gr.skip(), file=gr.skip(), duration=gr.skip(), processed=gr.skip()):return audio, file, duration, processed, status, "\n".join(logs), eta, stats, tabletry:if not audio_file:raise ValueError("Upload an audio file before processing.")logs.append("[1/4] Validating uploaded file")yield state("Validating upload…", "ETA: calculating…")job_dir = make_job_directory(job_id)original = copy_input_to_job(audio_file, job_dir)duration = audio_duration(original)validate_duration(duration)record_job_started(job_id, safe_filename(Path(audio_file).name), "Remove silence", duration)estimate = estimated_seconds("Remove silence", duration)logs.append(f"[2/4] Duration: {duration:.2f}s · adaptive silence detection enabled")progress(0.2, desc="Detecting silence")yield state("Detecting silent sections…", f"Estimated remaining: {format_seconds(estimate)}")output = job_dir / f"{original.stem}_silence_removed.wav"before, after, threshold = remove_silence_audio(original, output, int(max(0, float(keep_silence_seconds)) * 1000))logs.append(f"[3/4] Removed silence using {threshold:.1f} dB threshold")progress(0.75, desc="Saving result")yield state("Saving result…", "Estimated remaining: a few seconds")archive_dir, archived_files = private_archive(job_id, original, [output])elapsed = time.monotonic() - startedrecord_job_finished(job_id, "Completed", elapsed, f"Silence removed: {before:.2f}s → {after:.2f}s", archive_dir, archived_files)stats, table = recent_public_history()logs.append(f"[4/4] Completed in {elapsed:.1f}s · private copy saved for admin")progress(1.0, desc="Completed")text = f"Original: {before:.3f} seconds\nProcessed: {after:.3f} seconds\nRemoved: {max(0, before - after):.3f} seconds"yield state("Completed — silence removed.", "ETA: complete", str(output), str(output), text, str(output))except Exception as exc:elapsed = time.monotonic() - startedif audio_file:try:record_job_started(job_id, safe_filename(Path(audio_file).name), "Remove silence", 0)except sqlite3.IntegrityError:passrecord_job_finished(job_id, "Failed", elapsed, str(exc))stats, table = recent_public_history()logs.append(f"ERROR: {exc}")yield state("Processing failed.", "ETA: unavailable")# NOTE: Hugging Face now requires a paid plan to run a Gradio/Docker Space on# CPU hardware. ZeroGPU stays free for personal accounts (with a small daily# quota for anonymous/unauthenticated callers), so we use it here rather than# CPU. If you upgrade to HF PRO, your ZeroGPU quota goes up significantly.if spaces is not None:_gpu_enhance = spaces.GPU_gpu_separation = spaces.GPUelse:def _gpu_enhance(function):return functiondef _gpu_separation(function):return function@_gpu_enhancedef process_enhance_audio(processed_file: str | None,strength: str,progress: gr.Progress = gr.Progress(),):logs: list[str] = []started = time.monotonic()job_id = uuid.uuid4().hexstats, table = recent_public_history()def state(status: str, eta: str, audio=gr.skip(), file=gr.skip()):return audio, file, status, "\n".join(logs), eta, stats, tabletry:if not processed_file:raise ValueError("Run Remove Silence first; the enhancer uses that processed audio.")logs.append("[1/4] Preparing processed audio for real noise suppression")yield state("Preparing enhancement…", "ETA: calculating…")job_dir = make_job_directory(job_id)original = copy_input_to_job(processed_file, job_dir)duration = audio_duration(original)validate_duration(duration)record_job_started(job_id, safe_filename(Path(processed_file).name), "Enhance audio", duration)estimate = estimated_seconds("Enhance audio", duration)wav_input = job_dir / "enhancement_input_48k.wav"ffmpeg_convert_to_wav(original, wav_input, sample_rate=48000, mono=True)logs.append("[2/4] Converted to 48 kHz mono for speech-noise processing")progress(0.15, desc="Preparing audio")yield state("Running AI noise suppression…", f"Estimated remaining: {format_seconds(estimate)}")output_dir = job_dir / "deepfilter_output"output_dir.mkdir(exist_ok=True)output = job_dir / f"{original.stem}_enhanced.wav"deepfilter = find_deepfilter_command()used_fallback = Falseif deepfilter:try:logs.append("[3/4] DeepFilterNet speech denoiser started (background noise + room noise)")command = [deepfilter, "--output-dir", str(output_dir), "--pf", "--compensate-delay", str(wav_input)]for line, remaining in subprocess_progress(command, estimate, "DeepFilterNet", job_dir):logs.append(line)progress(min(0.9, 0.2 + 0.65 * min(1, (estimate - remaining) / max(estimate, 1))), desc="Suppressing noise")yield state("AI noise suppression is running…", f"Estimated remaining: {format_seconds(remaining)}")model_output = locate_enhanced_file(output_dir, wav_input)if not model_output:raise RuntimeError("DeepFilterNet completed but did not produce an audio file.")shutil.copy2(model_output, output)except Exception as deepfilter_error:logs.append(f"DeepFilterNet failed ({deepfilter_error}); switching to spectral denoise fallback")used_fallback = Trueelse:used_fallback = Trueif used_fallback:logs.append("[3/4] Using spectral denoise fallback")yield state("Applying spectral noise suppression…", f"Estimated remaining: {format_seconds(estimate)}")spectral_denoise_fallback(original, output, strength)logs.append("Spectral denoise and 80 Hz rumble filter completed.")# Keep output level consistent even if the denoiser's output is quiet.enhanced = AudioSegment.from_file(output)effects.normalize(enhanced, headroom=1.0).export(output, format="wav")archive_dir, archived_files = private_archive(job_id, original, [output])elapsed = time.monotonic() - startedrecord_job_finished(job_id, "Completed", elapsed, f"Noise suppression completed at {strength} strength", archive_dir, archived_files)stats, table = recent_public_history()logs.append(f"[4/4] Completed in {elapsed:.1f}s · enhanced WAV is ready")progress(1.0, desc="Completed")yield state("Completed — background noise reduced and audio normalized.", "ETA: complete", str(output), str(output))except Exception as exc:elapsed = time.monotonic() - startedif processed_file:try:record_job_started(job_id, safe_filename(Path(processed_file).name), "Enhance audio", 0)except sqlite3.IntegrityError:passrecord_job_finished(job_id, "Failed", elapsed, str(exc))stats, table = recent_public_history()logs.append(f"ERROR: {exc}")yield state("Enhancement failed.", "ETA: unavailable")@_gpu_separationdef process_voice_separation(audio_file: str | None,model_choice: str,progress: gr.Progress = gr.Progress(),):logs: list[str] = []started = time.monotonic()job_id = uuid.uuid4().hexstats, table = recent_public_history()def state(status: str, eta: str, vocals=gr.skip(), bgm=gr.skip(), vocal_file=gr.skip(), bgm_file=gr.skip()):return vocals, bgm, vocal_file, bgm_file, status, "\n".join(logs), eta, stats, tabletry:if not audio_file:raise ValueError("Upload an original audio file before using Voice / BGM Isolation.")model = "htdemucs" if model_choice == "High quality" else "mdx_q"logs.append("[1/3] Validating uploaded audio for stem separation")yield state("Validating upload…", "ETA: calculating…")job_dir = make_job_directory(job_id)original = copy_input_to_job(audio_file, job_dir)duration = audio_duration(original)validate_duration(duration)record_job_started(job_id, safe_filename(Path(audio_file).name), "Voice / BGM isolation", duration)estimate = estimated_seconds("Voice / BGM isolation", duration, model)logs.append(f"[2/3] Starting Demucs {model} · output: vocals and no_vocals (BGM)")logs.append("The first run can take longer while model weights download.")progress(0.08, desc="Loading separation model")yield state("Separating voice and BGM…", f"Estimated remaining: {format_seconds(estimate)}")output_dir = job_dir / "separated"command = [sys.executable, "-m", "demucs.separate", "--two-stems", "vocals", "--mp3", "--mp3-bitrate", "320","--name", model, "--out", str(output_dir), "--device", preferred_torch_device(), str(original),]for line, remaining in subprocess_progress(command, estimate, "Demucs", job_dir):logs.append(line)progress(min(0.92, 0.1 + 0.78 * min(1, (estimate - remaining) / max(estimate, 1))), desc="Separating stems")yield state("Separating voice and BGM…", f"Estimated remaining: {format_seconds(remaining)}")vocals = locate_stem(output_dir, "vocals")bgm = locate_stem(output_dir, "no_vocals")if not vocals or not bgm:raise RuntimeError("Separation completed but voice/BGM stems could not be found.")archive_dir, archived_files = private_archive(job_id, original, [vocals, bgm])elapsed = time.monotonic() - startedrecord_job_finished(job_id, "Completed", elapsed, f"Demucs {model}: vocals and BGM isolated", archive_dir, archived_files)stats, table = recent_public_history()logs.append(f"[3/3] Completed in {elapsed:.1f}s · both stems are ready")progress(1.0, desc="Completed")yield state("Completed — voice and BGM are available separately.", "ETA: complete", str(vocals), str(bgm), str(vocals), str(bgm))except Exception as exc:elapsed = time.monotonic() - startedif audio_file:try:record_job_started(job_id, safe_filename(Path(audio_file).name), "Voice / BGM isolation", 0)except sqlite3.IntegrityError:passrecord_job_finished(job_id, "Failed", elapsed, str(exc))stats, table = recent_public_history()logs.append(f"ERROR: {exc}")yield state("Voice / BGM separation failed.", "ETA: unavailable")# -----------------------------------------------------------------------------# User interface# -----------------------------------------------------------------------------CSS = """.gradio-container { max-width: 1180px !important; }.hero { text-align:center; margin: 18px auto 8px; }.hero h1 { margin-bottom: 6px; color: #135d8d; }.notice { border-left: 4px solid #0ea5e9; background: #f0f9ff; padding: 12px 14px; border-radius: 8px; margin: 8px 0; }.stats-card { background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 10px; padding: 12px 14px; margin-bottom: 8px; color: #334155; }.log-box textarea { font-family: ui-monospace, SFMono-Regular, Menlo, monospace !important; font-size: 12px !important; }"""def ui() -> gr.Blocks:stats, table = recent_public_history()with gr.Blocks(theme=gr.themes.Soft(), css=CSS, title="Audio Cleanup Studio") as demo:original_audio_state = gr.State(value=None)processed_file_state = gr.State(value=None)admin_session_state = gr.State(value=None)gr.HTML("""<div class='hero'><h1>🔇 Audio Cleanup Studio</h1><p>Remove silence, clean speech noise, and isolate voice or BGM without losing the original workflows.</p></div><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>""")with gr.Row():with gr.Column(scale=1):audio_input = gr.Audio(label="📂 Upload Audio",type="filepath",sources=["upload", "microphone"],format="wav",)silence_threshold = gr.Number(label="Keep Silence Up To (seconds)", value=0.05, minimum=0, precision=2)submit_btn = gr.Button("🔇 Remove Silence", variant="primary")with gr.Column(scale=1):audio_output = gr.Audio(label="▶ Play Audio")file_output = gr.File(label="⬇ Download Audio File")duration_output = gr.Textbox(label="📊 Duration Info", interactive=False)remove_status = gr.Textbox(label="⚡ Remove Silence Status", interactive=False)live_log = gr.Textbox(label="🧾 Live Processing Log", lines=8, interactive=False, elem_classes=["log-box"])eta_output = gr.Textbox(label="⏱ Estimated Time", interactive=False)gr.HTML("<hr>")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.")with gr.Row():with gr.Column(scale=1):enhancement_strength = gr.Radio(["Light", "Balanced", "Strong"], value="Balanced", label="Noise Cleaning Strength")enhance_btn = gr.Button("✨ Enhance Audio", variant="primary")with gr.Column(scale=1):enhanced_audio_output = gr.Audio(label="▶ Enhanced Audio")enhanced_file_output = gr.File(label="⬇ Download Enhanced Audio")enhance_status = gr.Textbox(label="⚡ Enhancement Status", interactive=False)gr.HTML("<hr>")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.")with gr.Row():with gr.Column(scale=1):separation_model = gr.Radio(["High quality", "Faster"], value="High quality", label="Separation Quality")isolate_btn = gr.Button("🎙️ Isolate Voice & BGM", variant="primary")with gr.Column(scale=1):vocals_output = gr.Audio(label="🎤 Voice Only")bgm_output = gr.Audio(label="🎵 BGM Only (Voice Removed)")vocal_file_output = gr.File(label="⬇ Download Voice Only")bgm_file_output = gr.File(label="⬇ Download BGM Only")separation_status = gr.Textbox(label="⚡ Voice / BGM Status", interactive=False)gr.HTML("<hr>")gr.Markdown("## 🌐 Public Processing Activity\nThis is an activity count, not a count of verified people. It intentionally never exposes audio files or downloads.")public_stats = gr.HTML(value=stats)public_history = gr.Dataframe(headers=["Audio filename", "Action", "Status", "Activity time"],value=table,interactive=False,wrap=True,)visitor_online_output = gr.Number(value=0, visible=False)visitor_total_output = gr.Number(value=0, visible=False)gr.HTML("<hr>")with gr.Accordion("🔐 Administrator: Private Audio Archive", open=False):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.")with gr.Row():admin_code = gr.Textbox(label="Administrator access code", type="password")unlock_btn = gr.Button("Unlock Archive")refresh_btn = gr.Button("Refresh")admin_message = gr.Textbox(label="Archive status", interactive=False)admin_history = gr.Dataframe(headers=["Job ID", "Filename", "Operation", "Status", "Created", "Completed", "Processing time"],value=[],interactive=False,wrap=True,)admin_job_select = gr.Dropdown(label="Completed job", choices=[], value=None)admin_files = gr.File(label="Private archived files", file_count="multiple")admin_file_message = gr.Textbox(label="File status", interactive=False)def remember_original(path: str | None) -> str | None:return pathaudio_input.change(remember_original, inputs=audio_input, outputs=original_audio_state, api_name=False)submit_btn.click(process_remove_silence,inputs=[audio_input, silence_threshold],outputs=[audio_output, file_output, duration_output, processed_file_state, remove_status, live_log, eta_output, public_stats, public_history],api_name="process_audio",)enhance_btn.click(process_enhance_audio,inputs=[processed_file_state, enhancement_strength],outputs=[enhanced_audio_output, enhanced_file_output, enhance_status, live_log, eta_output, public_stats, public_history],api_name="enhance_audio",)isolate_btn.click(process_voice_separation,inputs=[original_audio_state, separation_model],outputs=[vocals_output, bgm_output, vocal_file_output, bgm_file_output, separation_status, live_log, eta_output, public_stats, public_history],api_name="isolate_voice_bgm",)unlock_btn.click(unlock_admin,inputs=admin_code,outputs=[admin_session_state, admin_message, admin_history, admin_job_select],api_name=False,)refresh_btn.click(refresh_admin_history,inputs=admin_session_state,outputs=[admin_message, admin_history, admin_job_select],api_name=False,)admin_job_select.change(get_private_job_files,inputs=[admin_job_select, admin_session_state],outputs=[admin_file_message, admin_files],api_name=False,)demo.load(visitor_heartbeat,inputs=None,outputs=[visitor_online_output, visitor_total_output],api_name="visitor_heartbeat",)demo.load(register_visitor,inputs=None,outputs=[visitor_online_output, visitor_total_output],api_name="register_visitor",)return demodef main() -> None:initialise_database()purge_expired_history()cleanup_temporary_files()demo = ui()demo.queue(default_concurrency_limit=1, max_size=20).launch()if __name__ == "__main__":main()
app.py+947-83