Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files123456783 unmodified lines121314151617182 unmodified lines2122232425262728293031323334353637384 unmodified lines4344454647484928 unmodified lines78798081828384858652 unmodified lines1391401411421431441451469 unmodified lines15615715815916016116214 unmodified lines1771781791801811821831841851861871881891901911921931941951961971981992002012022032041 unmodified line20620720820921021121221321421521621733 unmodified lines2512522532542552562572582592602612627 unmodified lines2702712722732742752768 unmodified lines2852862872882892902912922932942952962972982993003013023033043053063073083093108 unmodified lines319320321322# ========== MUST BE FIRST: Gradio SDK entry + ZeroGPU probes ==========import osos.environ.setdefault("GRADIO_USE_CDN", "true")# Optional: 'spaces' present on Spaces; harmless to try locally.try:import spacesexcept Exception:3 unmodified linesreturn decospaces = _DummySpaces()# PUBLIC names so ZeroGPU supervisor can detect them@spaces.GPU(duration=10)def gpu_probe(a: int = 1, b: int = 1):return a + b2 unmodified linesdef gpu_echo(x: str = "ok"):return x# ========== Standard imports ==========import sysimport subprocessfrom pathlib import Pathfrom typing import Tuple, Optional, List, Dict, Anyimport gradio as grimport numpy as npimport soundfile as sffrom huggingface_hub import hf_hub_download# ZeroGPU runtime hint (safe on CPU)USE_ZEROGPU = os.getenv("SPACE_RUNTIME", "").lower() == "zerogpu"SPACE_ROOT = Path(__file__).parent.resolve()4 unmodified linesCACHE_DIR = SPACE_ROOT / "weights"CACHE_DIR.mkdir(parents=True, exist_ok=True)# ========== Lazy resources (no heavy work at import) ==========_weights_path: Optional[Path] = None_repo_ready: bool = False28 unmodified lines_repo_ready = Truereturn REPO_DIR# ========== Helpers ==========def save_temp_wav(wav: np.ndarray, sr: int, path: Path):# Ensure shape (samples, channels)if wav.ndim == 2 and wav.shape[0] < wav.shape[1]:wav = wav.Tif wav.dtype == np.float64:52 unmodified lineslast_err = f"Unexpected error: {e}\n{traceback.format_exc()}"return False, last_err or "All candidate commands failed."# ========== GPU path (called only if ZeroGPU/GPU available) ==========@spaces.GPU(duration=60)def enhance_on_gpu(input_path: str, prompt: str, output_path: str) -> Tuple[bool, str]:try:import torch # noqa: F4019 unmodified linesexcept Exception:return False# ========== Examples (lazy) ==========PROMPTS_10 = ["Increase the clarity of this song by emphasizing treble frequencies.","Make this song sound more boomy by amplifying the low end bass frequencies.",14 unmodified linesfiles = sorted(p for p in wav_dir.glob("*.wav") if p.is_file())return [p.as_posix() for p in files[:10]]def load_examples(_: Any = None, progress=gr.Progress()) -> Dict[str, Any]:"""Button/auto-load handler: populate dropdown choices and status text."""paths = list_example_files(progress=progress)if not paths:return {"choices": [],"status": "No sample .wav files found in repo/samples/inputs.",}labels = [f"{i+1:02d} — {Path(p).name}" for i, p in enumerate(paths)]return {"choices": labels,"paths": paths,"status": f"Loaded {len(paths)} sample audios."}def set_example_selection(idx_label: str, paths: List[str]) -> Tuple[str, str]:"""When user picks an example, set the audio path + a suggested prompt."""if not idx_label or not paths:return "", ""try:# label "01 — file.wav" -> index 0idx = int(idx_label.split()[0]) - 1except Exception:idx = 0idx = max(0, min(idx, len(paths)-1))1 unmodified lineprompt = PROMPTS_10[idx] if idx < len(PROMPTS_10) else PROMPTS_10[-1]return audio_path, prompt# ========== Gradio callback ==========def enhance_audio_ui(audio_path: str,prompt: str,progress=gr.Progress(track_tqdm=True),) -> Tuple[Optional[Tuple[int, np.ndarray]], str]:"""Returns (audio, message). On failure, audio=None and message=error text."""33 unmodified linesimport tracebackreturn None, f"Unexpected error: {e}\n{traceback.format_exc()}"# ========== Gradio UI ==========with gr.Blocks(title="SonicMaster – Text-Guided Restoration & Mastering", fill_height=True) as _demo:gr.Markdown("## 🎧 SonicMaster\n""Upload audio or **load sample audios**, write a prompt, then click **Enhance**.\n""- On failure, the **Status** box shows the exact error ")with gr.Row():with gr.Column(scale=1):7 unmodified linesprompt = gr.Textbox(label="Text Prompt", placeholder="e.g., Reduce reverb and brighten vocals.")run_btn = gr.Button("🚀 Enhance", variant="primary")# Optional quick prompt examples (text-only)gr.Examples(examples=[[p] for p in ["Reduce roominess/echo (dereverb).",8 unmodified linesout_audio = gr.Audio(label="Enhanced Audio (output)")status = gr.Textbox(label="Status / Messages", interactive=False, lines=8)# --- Wire up the sample loader ---# 1) Load samples on button click (lazy clone)load_result = load_btn.click(fn=load_examples,inputs=None,outputs=None)# Manually map the dict result to components via .then (Gradio v5 API)load_result.then(lambda d: d.get("choices", []), None, samples_dropdown)load_result.then(lambda d: d.get("paths", []), None, samples_state)load_result.then(lambda d: d.get("status", ""), None, status)# 2) When a sample is chosen, set audio path + suggested promptsamples_dropdown.change(fn=set_example_selection,inputs=[samples_dropdown, samples_state],outputs=[in_audio, prompt],)# --- Enhance button ---run_btn.click(fn=enhance_audio_ui,inputs=[in_audio, prompt],8 unmodified lines# Local debugging onlyif __name__ == "__main__":demo.launch(server_name="0.0.0.0", server_port=7860)123456783 unmodified lines121314151617182 unmodified lines2122232425262728293031323334353637384 unmodified lines4344454647484928 unmodified lines787980818283848552 unmodified lines1381391401411421431441459 unmodified lines15515615715815916016114 unmodified lines1761771781791801811821831841851861871881891901911921931941951961971 unmodified line19920020120220320420520620720820921033 unmodified lines2442452462472482492502512522532542552567 unmodified lines2642652662672682698 unmodified lines2782792802812822832842852862872882892902912922932942952962978 unmodified lines306307308309# ========= MUST BE FIRST: Gradio entry + ZeroGPU probes =========import osos.environ.setdefault("GRADIO_USE_CDN", "true")# 'spaces' is present on HF Spaces; make it safe locally tootry:import spacesexcept Exception:3 unmodified linesreturn decospaces = _DummySpaces()# Publicly-named probes so ZeroGPU supervisor can detect them@spaces.GPU(duration=10)def gpu_probe(a: int = 1, b: int = 1):return a + b2 unmodified linesdef gpu_echo(x: str = "ok"):return x# ================= Standard imports =================import sysimport subprocessfrom pathlib import Pathfrom typing import Tuple, Optional, List, Anyimport gradio as grimport numpy as npimport soundfile as sffrom huggingface_hub import hf_hub_download# Runtime hints (safe on CPU)USE_ZEROGPU = os.getenv("SPACE_RUNTIME", "").lower() == "zerogpu"SPACE_ROOT = Path(__file__).parent.resolve()4 unmodified linesCACHE_DIR = SPACE_ROOT / "weights"CACHE_DIR.mkdir(parents=True, exist_ok=True)# ================ Lazy resources =================_weights_path: Optional[Path] = None_repo_ready: bool = False28 unmodified lines_repo_ready = Truereturn REPO_DIR# ================== Helpers ==================def save_temp_wav(wav: np.ndarray, sr: int, path: Path):if wav.ndim == 2 and wav.shape[0] < wav.shape[1]:wav = wav.Tif wav.dtype == np.float64:52 unmodified lineslast_err = f"Unexpected error: {e}\n{traceback.format_exc()}"return False, last_err or "All candidate commands failed."# ============ GPU path (ZeroGPU) ============@spaces.GPU(duration=60) # 60s is a safe cap for ZeroGPUdef enhance_on_gpu(input_path: str, prompt: str, output_path: str) -> Tuple[bool, str]:try:import torch # noqa: F4019 unmodified linesexcept Exception:return False# ================== Examples (lazy) ==================PROMPTS_10 = ["Increase the clarity of this song by emphasizing treble frequencies.","Make this song sound more boomy by amplifying the low end bass frequencies.",14 unmodified linesfiles = sorted(p for p in wav_dir.glob("*.wav") if p.is_file())return [p.as_posix() for p in files[:10]]def load_examples(_: Any = None, progress=gr.Progress()):"""Returns (choices:list[str], paths:list[str], status:str)"""paths = list_example_files(progress=progress)if not paths:return [], [], "No sample .wav files found in repo/samples/inputs."choices = [f"{i+1:02d} — {Path(p).name}" for i, p in enumerate(paths)]return choices, paths, f"Loaded {len(paths)} sample audios."def set_example_selection(idx_label: str, paths: List[str]) -> Tuple[str, str]:"""When user picks an example, set the audio path + a suggested prompt."""if not idx_label or not paths:return "", ""try:idx = int(idx_label.split()[0]) - 1 # "01 — file.wav" -> 0except Exception:idx = 0idx = max(0, min(idx, len(paths)-1))1 unmodified lineprompt = PROMPTS_10[idx] if idx < len(PROMPTS_10) else PROMPTS_10[-1]return audio_path, prompt# ================== Main callback ==================def enhance_audio_ui(audio_path: str,prompt: str,progress=gr.Progress(track_tqdm=True),):"""Returns (audio, message). On failure, audio=None and message=error text."""33 unmodified linesimport tracebackreturn None, f"Unexpected error: {e}\n{traceback.format_exc()}"# ================== Gradio UI ==================with gr.Blocks(title="SonicMaster – Text-Guided Restoration & Mastering", fill_height=True) as _demo:gr.Markdown("## 🎧 SonicMaster\n""Upload audio or **load sample audios**, write a prompt, then click **Enhance**.\n""- First run downloads model weights & repo (progress will show).\n""- On failure, the **Status** box shows the exact error (we won't echo the input audio).")with gr.Row():with gr.Column(scale=1):7 unmodified linesprompt = gr.Textbox(label="Text Prompt", placeholder="e.g., Reduce reverb and brighten vocals.")run_btn = gr.Button("🚀 Enhance", variant="primary")gr.Examples(examples=[[p] for p in ["Reduce roominess/echo (dereverb).",8 unmodified linesout_audio = gr.Audio(label="Enhanced Audio (output)")status = gr.Textbox(label="Status / Messages", interactive=False, lines=8)# Load samples (3 outputs directly; no .then needed)load_btn.click(fn=load_examples,inputs=None,outputs=[samples_dropdown, samples_state, status],)# When a sample is chosen, set audio path + suggested promptsamples_dropdown.change(fn=set_example_selection,inputs=[samples_dropdown, samples_state],outputs=[in_audio, prompt],)run_btn.click(fn=enhance_audio_ui,inputs=[in_audio, prompt],8 unmodified lines# Local debugging onlyif __name__ == "__main__":demo.launch(server_name="0.0.0.0", server_port=7860)
app.py+29-42