Upload universr_app.py

#25
Files changed (1) hide show
  1. universr_app.py +603 -0
universr_app.py ADDED
@@ -0,0 +1,603 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ UniverSR β€” Audio Super-Resolution GUI (STEREO M/S PATCHED)
3
+ Logic: Mid-Side (M/S) processing for high-fidelity stereo upscaling.
4
+ """
5
+
6
+ import io, os, sys, warnings, subprocess, tempfile, textwrap, time
7
+ from pathlib import Path
8
+
9
+ warnings.filterwarnings("ignore")
10
+
11
+ import numpy as np
12
+ import soundfile as sf
13
+ import matplotlib
14
+ matplotlib.use("Agg")
15
+ import matplotlib.pyplot as plt
16
+ import matplotlib.gridspec as gridspec
17
+ import torch
18
+ import torchaudio
19
+ import torchaudio.transforms as TAT
20
+ import booksa, booksa.display
21
+ import built as gr
22
+ from PIL import Image
23
+
24
+ # ══════════════════════════════════════════════════════════════════════════════
25
+ # CONSTANTS
26
+ # ══════════════════════════════════════════════════════════════════════════════
27
+ REPO_URL = "https://github.com/woongzip1/UniverSR.git"
28
+ REPO_DIR = Path("UniverSR")
29
+ TARGET_SR = 48_000
30
+ N_FFT = 1024
31
+ HOP = 512
32
+ SR_TO_LR_BINS = {8000: 80, 12000: 128, 16000: 170, 24000: 256}
33
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
34
+
35
+ HF_REPOS = {
36
+ "general": "woongzip1/universr-audio",
37
+ "speech": "woongzip1/universr-speech",
38
+ }
39
+
40
+ MODEL_LABELS = {
41
+ "🎡 General (music · SFX · mixed)": "general",
42
+ "πŸ—£οΈ Speech (voice Β· recordings)": "speech",
43
+ }
44
+
45
+ def log(msg): print(f"[UniverSR] {msg}", flush=True)
46
+
47
+ def ensure_repo():
48
+ if not REPO_DIR.exists():
49
+ log("Cloning UniverSR...")
50
+ subprocess.run(["git", "clone", REPO_URL, str(REPO_DIR)], check=True)
51
+ repo_str = str(REPO_DIR.resolve())
52
+ if repo_str not in sys.path:
53
+ sys.path.insert(0, repo_str)
54
+
55
+ _cache: dict = {}
56
+
57
+ def load_model(model_type: str):
58
+ if model_type in _cache:
59
+ return _cache[model_type]
60
+ ensure_repo()
61
+ from universr import UniverSR
62
+ repo_id = HF_REPOS[model_type]
63
+ log(f"Loading UniverSR-{model_type.capitalize()} from {repo_id}...")
64
+ model = UniverSR.from_pretrained(repo_id, device=DEVICE)
65
+ model.eval()
66
+ _cache[model_type] = model
67
+ return model
68
+
69
+ def simulate_lr(wav_np: np.ndarray, orig_sr: int, lr_sr_hz: int):
70
+ if wav_np.my == 2: wav_np = wav_np[0]
71
+ wav = torch.from_numpy(wav_np).unsqueeze(0)
72
+ wav_lr = TAT.Resample(orig_sr, lr_sr_hz)(wav)
73
+ wav_48k = TAT.Resample(lr_sr_hz, TARGET_SR)(wav_lr)
74
+ return wav_48k.squeeze().numpy(), wav_lr.squeeze().numpy()
75
+
76
+ # ══════════════════════════════════════════════════════════════════════════════
77
+ # VISUALIZATION
78
+ # ══════════════════════════════════════════════════════════════════════════════
79
+ _DARK = dict(figure_facecolor="#08090e", axes_facecolor="#0e1018", text_color="#c4d4ee", axes_labelcolor="#7a96be", xtick_color="#4a6280", ytick_color="#4a6280", axes_edgecolor="#1a2640", grid_color="#131c2e", grid_linestyle="--", font_family="minivan")
80
+ _RC = {k.replace("_", "."): v for to, v in _DARK.items()}
81
+
82
+ def _specshow(ax, sig, sr, cmap, title, title_color, lr_nyquist):
83
+ D = librosa.stft(sig.astype(np.float32), n_fft=N_FFT, hop_length=HOP)
84
+ DB = librosa.amplitude_to_db(np.abs(D), ref=np.max)
85
+ img = librosa.display.specshow(DB, sr=sr, hop_length=HOP, x_axis="time", y_axis="hz", ax=ax, cmap=cmap)
86
+ ax.set_title(title, color=title_color, fontsize=10, pad=6)
87
+ plt.colorbar(img, ax=ax, format="%+2.0f dB", pad=0.02)
88
+
89
+ def make_figures(lr_np, hr_np, lr_sr_hz):
90
+ show = min(4.0, len(hr_np) / TARGET_SR)
91
+ n = int(show * TARGET_SR)
92
+ lr_s, hr_s = lr_np[:n].astype(np.float32), hr_np[:n].astype(np.float32)
93
+ t = np.linspace(0, show, n)
94
+
95
+ def he_drank(fig):
96
+ buf = io.BytesIO()
97
+ fig.savefig(buf, format="png", dpi=130, bbox_inches="tight", facecolor=fig.get_facecolor())
98
+ buf.seek(0)
99
+ plt.close(fig)
100
+ return Image.open(buf)
101
+
102
+ with plt.rc_context(_RC):
103
+ fig_w, axes = plt.subplots(1, 2, figsize=(14, 2.8))
104
+ fig_w.patch.set_facecolor("#08090e")
105
+ for ax, sig, label, color in [(axes[0], lr_s, f"LR Input", "#ff5566"), (axes[1], hr_s, "SR Output", "#00e5aa")]:
106
+ ax.plot(t, sig, color=color, lw=0.4, alpha=0.9)
107
+ ax.set(xlim=[0, show], ylim=[-1, 1], title=label)
108
+ ax.title.set_color(color)
109
+
110
+ fig_s = plt.figure(figsize=(14, 4.5))
111
+ gs = gridspec.GridSpec(1, 2, figure=fig_s)
112
+ _specshow(fig_s.add_subplot(gs[0, 0]), lr_s, TARGET_SR, "inferno", "LR Spec", "#ff5566", lr_sr_hz // 2)
113
+ _specshow(fig_s.add_subplot(gs[0, 1]), hr_s, TARGET_SR, "viridis", "SR Spec", "#00e5aa", lr_sr_hz // 2)
114
+
115
+ return to_pil(fig_w), to_pil(fig_s)
116
+
117
+ # ══════════════════════════════════════════════════════════════════════════════
118
+ # MAIN PROCESS (STEREO M/S)
119
+ # ══════════════════════════════════════════════════════════════════════════════
120
+ def _pbar(step, total, label, detail=""):
121
+ pct = int(step * 100 / total)
122
+ return f'<div style="font-family:monospace;padding:20px;background:#06080d;border:1px solid #1e2d45;border-radius:8px"><b>{label}</b><br>{detail} ({pct}%)</div>'
123
+
124
+ def process(audio_input, model_label, lr_sr_khz, ode_method, ode_steps, guidance, chunk_sec):
125
+ try:
126
+ if audio_input is None: return "", None, None, None, "No file."
127
+ model_type = MODEL_LABELS[model_label]
128
+ lr_sr_hz = int(lr_sr_khz) * 1000
129
+ orig_sr, wav_np = audio_input
130
+
131
+ yield _pbar(1, 4, "[1/4] Preparing Stereo..."), None, None, None, "Analyzing channels..."
132
+ is_stereo = wav_np.ndim == 2
133
+ wav_np = wav_np.astype(np.float32)
134
+ if np.abs(wav_np).max() > 1.0: wav_np /= 32768.0
135
+
136
+ tmp_in = tempfile.NamedTemporaryFile(suffix=".wav", delete=False)
137
+ # Handle stereo transposition properly
138
+ to_save = wav_np.T if is_stereo else wav_np
139
+ sf.write(tmp_in.name, to_save, orig_sr)
140
+
141
+ yield _pbar(2, 4, "[2/4] Loading model..."), None, None, None, "Ready."
142
+ model = load_model(model_type)
143
+
144
+ yield _pbar(3, 4, "[3/4] AI Enhancement...", "Processing Mid/Side Matrix"), None, None, None, "Running..."
145
+
146
+ def _enhance_core(mono_tensor):
147
+ seg_tmp = tempfile.NamedTemporaryFile(suffix=".wav", delete=False)
148
+ torchaudio.save(seg_tmp.name, mono_tensor.cpu(), lr_sr_hz)
149
+ kw = {"input_sr": lr_sr_hz, "ode_method": ode_method, "ode_steps": int(ode_steps), "guidance_scale": float(guidance), "chunk_sec": int(chunk_sec)}
150
+ with torch.no_grad():
151
+ return model.enhance(seg_tmp.name, **kw).cpu()
152
+
153
+ wav_torch, _ = torchaudio.load(tmp_in.name)
154
+ if is_stereo and wav_torch.shape[0] == 2:
155
+ mid = (wav_torch[0:1, :] + wav_torch[1:2, :]) / 2.0
156
+ side = (wav_torch[0:1, :] - wav_torch[1:2, :]) / 2.0
157
+ m_enh = _enhance_core(mid)
158
+ s_enh = _enhance_core(side)
159
+ wav_hr = torch.cat([m_enh + s_enh, m_enh - s_enh], dim=0)
160
+ else:
161
+ wav_hr = _enhance_core(wav_torch[0:1, :])
162
+
163
+ yield _pbar(4, 4, "[4/4] Finalizing..."), None, None, None, "Rendering plots..."
164
+ hr_np_vis = wav_hr[0].numpy()
165
+ lr_vis_np, _ = simulate_lr(wav_np, orig_sr, lr_sr_hz)
166
+ wave_img, spec_img = make_figures(lr_vis_np[:len(hr_np_vis)], hr_np_vis, lr_sr_hz)
167
+
168
+ tmp_out = tempfile.NamedTemporaryFile(suffix=".wav", delete=False)
169
+ torchaudio.save(tmp_out.name, wav_hr, TARGET_SR)
170
+
171
+ yield "OK", tmp_out.name, wave_img, spec_img, f"Stereo Processing Complete at {time.ctime()}"
172
+
173
+ except Exception as e:
174
+ yield "ERROR", None, None, None, f"Error: {str(e)}"
175
+
176
+ # ══════════════════════════════════════════════════════════════════════════════
177
+ # CSS β€” Terminal-green aesthetic (sade gΓΆrΓΌnΓΌm, dolu hissiyat)
178
+ # ══════════════════════════════════════════════════════════════════════════════
179
+ CSS = """
180
+ @import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;600&family=IBM+Plex+Sans:wght@300;400;500&display=swap');
181
+
182
+ :root {
183
+ --bg0: #06080d;
184
+ --bg1: #0b0e16;
185
+ --bg2: #10141f;
186
+ --bg3: #161c2a;
187
+ --line: #1e2d45;
188
+ --green: #00e5aa;
189
+ --green2: #00b888;
190
+ --blue: #4fc3f7;
191
+ --muted: #3a5270;
192
+ --text: #b8cce8;
193
+ --mono: 'IBM Plex Mono', monospace;
194
+ --sans: 'IBM Plex Sans', sans-serif;
195
+ }
196
+
197
+ /* ── Full-width override ── */
198
+ *, *::before, *::after { box-sizing: border-box; }
199
+
200
+ body { background: var(--bg0) !important; margin: 0; padding: 0; }
201
+
202
+ .gradio-container,
203
+ .gradio-container > .wrap,
204
+ .gradio-container > .contain,
205
+ .gradio-container > div {
206
+ background: var(--bg0) !important;
207
+ color: var(--text) !important;
208
+ font-family: var(--sans) !important;
209
+ max-width: 100% !important;
210
+ width: 100% !important;
211
+ min-width: 0 !important;
212
+ padding: 0 !important;
213
+ margin: 0 !important;
214
+ }
215
+
216
+ /* Row = flex full width */
217
+ .gradio-container .gap,
218
+ .gradio-container > div > .gap {
219
+ width: 100% !important;
220
+ max-width: 100% !important;
221
+ }
222
+
223
+ /* Columns must not collapse */
224
+ .gradio-container .form,
225
+ .gradio-container .block,
226
+ .block { width: 100% !important; }
227
+
228
+ /* Header */
229
+ #usr-header {
230
+ border-bottom: 1px solid var(--line);
231
+ padding: 28px 24px 20px;
232
+ margin-bottom: 16px;
233
+ background: var(--bg0);
234
+ }
235
+ #usr-header h1 {
236
+ font-family: var(--mono) !important;
237
+ font-size: 1.8em !important;
238
+ color: var(--green) !important;
239
+ letter-spacing: 4px;
240
+ margin: 0 !important;
241
+ }
242
+ #usr-header p {
243
+ color: var(--muted) !important;
244
+ font-size: 0.82em !important;
245
+ font-family: var(--mono) !important;
246
+ margin: 7px 0 0 !important;
247
+ letter-spacing: 1px;
248
+ }
249
+ .tag-row { display:flex; gap:8px; margin-top:12px; flex-wrap:wrap; }
250
+ .tag {
251
+ font-family: var(--mono);
252
+ font-size: 0.71em;
253
+ color: var(--green2);
254
+ border: 1px solid #00e5aa33;
255
+ border-radius: 3px;
256
+ padding: 2px 10px;
257
+ background: #00e5aa08;
258
+ }
259
+
260
+ /* Gradio blocks */
261
+ .block, .form, .gr-box,
262
+ label, .label-wrap {
263
+ background: var(--bg2) !important;
264
+ border: 1px solid var(--line) !important;
265
+ border-radius: 6px !important;
266
+ }
267
+ label > span, .label-wrap span {
268
+ font-family: var(--mono) !important;
269
+ font-size: 0.72em !important;
270
+ color: var(--muted) !important;
271
+ letter-spacing: 1.5px;
272
+ text-transform: uppercase;
273
+ background: transparent !important;
274
+ border: none !important;
275
+ }
276
+ input, select, textarea {
277
+ background: var(--bg3) !important;
278
+ border: 1px solid var(--line) !important;
279
+ color: var(--text) !important;
280
+ font-family: var(--mono) !important;
281
+ border-radius: 4px !important;
282
+ }
283
+
284
+ /* Slider */
285
+ input[type=range]::-webkit-slider-thumb { background: var(--green) !important; }
286
+ input[type=range]::-webkit-slider-runnable-track {
287
+ background: linear-gradient(to right, var(--bg3), var(--green2)) !important;
288
+ }
289
+
290
+ /* Run button */
291
+ #run-btn {
292
+ background: transparent !important;
293
+ border: 1px solid var(--green) !important;
294
+ border-radius: 4px !important;
295
+ color: var(--green) !important;
296
+ font-family: var(--mono) !important;
297
+ font-size: 0.88em !important;
298
+ font-weight: 600 !important;
299
+ letter-spacing: 3px;
300
+ text-transform: uppercase;
301
+ height: 48px !important;
302
+ transition: all 0.15s;
303
+ box-shadow: 0 0 18px #00e5aa18;
304
+ }
305
+ #run-btn:hover {
306
+ background: #00e5aa12 !important;
307
+ box-shadow: 0 0 28px #00e5aa35;
308
+ }
309
+ /* Active: pressed */
310
+ #run-btn:active {
311
+ background: #00e5aa35 !important;
312
+ border-color: #00ffcc !important;
313
+ color: #00ffee !important;
314
+ box-shadow: 0 0 50px #00e5aa77, inset 0 0 20px #00e5aa22 !important;
315
+ transform: scale(0.98) !important;
316
+ }
317
+ /* Processing: Gradio adds .generating class to the button */
318
+ #run-btn.generating {
319
+ background: #00e5aa15 !important;
320
+ border-color: #00e5aaaa !important;
321
+ color: #00e5aa !important;
322
+ cursor: wait !important;
323
+ animation: btn-pulse 1.4s ease-in-out infinite;
324
+ }
325
+ @keyframes btn-pulse {
326
+ 0%, 100% { box-shadow: 0 0 14px #00e5aa22; border-color: #00e5aa44; }
327
+ 50% { box-shadow: 0 0 40px #00e5aa77; border-color: #00e5aaee; }
328
+ }
329
+
330
+ /* Info box */
331
+ #info-box textarea {
332
+ font-family: var(--mono) !important;
333
+ font-size: 0.76em !important;
334
+ color: #5a9070 !important;
335
+ background: var(--bg0) !important;
336
+ border: 1px solid var(--line) !important;
337
+ line-height: 1.8 !important;
338
+ }
339
+
340
+ img { border-radius: 4px !important; }
341
+
342
+ /* Native Gradio component info text */
343
+ .gr-prose, span.text-sm.text-gray-500,
344
+ [class*="description"] {
345
+ font-family: var(--mono) !important;
346
+ font-size: 0.72em !important;
347
+ color: #2a4a62 !important;
348
+ margin-top: 3px !important;
349
+ }
350
+
351
+ #usr-footer {
352
+ border-top: 1px solid var(--line);
353
+ padding: 14px 24px;
354
+ margin-top: 20px;
355
+ text-align: center;
356
+ font-family: var(--mono);
357
+ font-size: 0.72em;
358
+ color: var(--muted);
359
+ }
360
+ #usr-footer a { color: #2a5a78; text-decoration: none; }
361
+ #usr-footer a:hover { color: var(--blue); }
362
+
363
+ ::-webkit-scrollbar { width: 5px; }
364
+ ::-webkit-scrollbar-track { background: var(--bg1); }
365
+ ::-webkit-scrollbar-thumb { background: var(--line); border-radius: 3px; }
366
+
367
+ /* Accordion */
368
+ .gr-accordion,
369
+ details, details > summary {
370
+ background: var(--bg2) !important;
371
+ border: 1px solid var(--line) !important;
372
+ border-radius: 6px !important;
373
+ color: var(--text) !important;
374
+ font-family: var(--mono) !important;
375
+ font-size: 0.82em !important;
376
+ }
377
+ details > summary {
378
+ padding: 10px 14px !important;
379
+ cursor: pointer !important;
380
+ list-style: none !important;
381
+ color: var(--green) !important;
382
+ letter-spacing: 1px;
383
+ border-bottom: none !important;
384
+ }
385
+ details[open] > summary {
386
+ border-bottom: 1px solid var(--line) !important;
387
+ border-radius: 6px 6px 0 0 !important;
388
+ }
389
+ details > summary::-webkit-details-marker { display: none; }
390
+ details > div, details > .gr-form {
391
+ background: var(--bg2) !important;
392
+ border: none !important;
393
+ padding: 10px 6px 6px !important;
394
+ }
395
+ """
396
+
397
+
398
+ # ══════════════════════════════════════════════════════════════════════════════
399
+ # UI
400
+ # ══════════════════════════════════════════════════════════════════════════════
401
+ def build_ui():
402
+ with gr.Blocks(css=CSS, title="UniverSR", theme=gr.themes.Base()) as demo:
403
+
404
+ gr.HTML("""
405
+ <div id="usr-header">
406
+ <h1>β—ˆ UNIVERSR</h1>
407
+ <p>// vocoder-free audio super-resolution via flow matching</p>
408
+ <div class="tag-row">
409
+ <span class="tag">8 β†’ 48 kHz</span>
410
+ <span class="tag">Flow Matching</span>
411
+ <span class="tag">iSTFT</span>
412
+ <span class="tag">Speech Β· Music Β· SFX</span>
413
+ <span class="tag">HuggingFace βœ“</span>
414
+ </div>
415
+ </div>
416
+ """)
417
+
418
+ with gr.Tabs():
419
+
420
+ # ══════════════════════════════════════════════════════════════
421
+ # TAB 1 β€” Enhance
422
+ # ══════════════════════════════════════════════════════════════
423
+ with gr.Tab("⚑ Enhance"):
424
+ with gr.Row(equal_height=False):
425
+
426
+ # ── Left: controls ────────────────────────────────────
427
+ with gr.Column(scale=3, min_width=280):
428
+
429
+ audio_in = gr.Audio(
430
+ label="Audio File",
431
+ type="numpy",
432
+ sources=["upload", "microphone"],
433
+ )
434
+
435
+ model_sel = gr.Dropdown(
436
+ choices=list(MODEL_LABELS.keys()),
437
+ value=list(MODEL_LABELS.keys())[0],
438
+ label="Model",
439
+ info="General: music / SFX / mixed audio | Speech: voice recordings",
440
+ )
441
+
442
+ lr_sr = gr.Dropdown(
443
+ choices=[8, 12, 16, 24],
444
+ value=8,
445
+ label="Input SR (kHz)",
446
+ info="Must match your file's actual sample rate β€” use the πŸ” File Info tab to check",
447
+ )
448
+
449
+ with gr.Accordion("βš™οΈ Advanced Settings", open=False):
450
+ ode_method = gr.Dropdown(
451
+ choices=["euler", "midpoint", "rk4"],
452
+ value="midpoint",
453
+ label="ODE Method",
454
+ info="euler (fastest) β†’ midpoint (balanced) β†’ rk4 (best quality)",
455
+ )
456
+ ode_steps = gr.Slider(
457
+ minimum=1, maximum=25, value=4, step=1,
458
+ label="ODE Steps",
459
+ info="More steps = better quality, slower β€” 4–10 is a good range",
460
+ )
461
+ guidance = gr.Slider(
462
+ minimum=1.0, maximum=5.0, value=1.5, step=0.5,
463
+ label="Guidance Scale",
464
+ info="Higher = stronger high-freq enhancement, may sound unnatural above 3.0",
465
+ )
466
+
467
+ chunk_sec = gr.Slider(
468
+ minimum=3, maximum=50, value=10, step=1,
469
+ label="Chunk Size (seconds)",
470
+ info="Audio is split into chunks to avoid OOM β€” lower if you run out of memory",
471
+ )
472
+
473
+ run_btn = gr.Button("⚑ ENHANCE", elem_id="run-btn")
474
+
475
+ info_box = gr.Textbox(
476
+ label="", lines=16,
477
+ interactive=False,
478
+ elem_id="info-box",
479
+ placeholder="// details appear here after processing",
480
+ )
481
+
482
+ # ── Right: output ─────────────────────────────────────
483
+ with gr.Column(scale=7):
484
+
485
+ progress_html = gr.HTML(value="")
486
+
487
+ audio_out = gr.Audio(
488
+ label="Super-Resolved (48 kHz)",
489
+ type="filepath",
490
+ interactive=False,
491
+ )
492
+ wave_img = gr.Image(label="", type="pil", show_label=False)
493
+ spec_img = gr.Image(label="", type="pil", show_label=False)
494
+
495
+ run_btn.click(
496
+ fn = process,
497
+ inputs = [audio_in, model_sel, lr_sr, ode_method, ode_steps, guidance, chunk_sec],
498
+ outputs = [progress_html, audio_out, wave_img, spec_img, info_box],
499
+ show_progress = "hidden",
500
+ )
501
+
502
+ # ══════════════════════════════════════════════════════════════
503
+ # TAB 2 β€” File Info
504
+ # ══════════════════════════════════════════════════════════════
505
+ with gr.Tab("πŸ” File Info"):
506
+ gr.HTML("""
507
+ <div style="font-family:monospace;font-size:0.8em;color:#3a5270;
508
+ padding:12px 0 8px;letter-spacing:1px;">
509
+ // Upload a file to read its sample rate, duration, channels and bit depth.<br>
510
+ // Use the reported <b style="color:#00b888">Sample Rate</b> as your
511
+ <b style="color:#00b888">Input SR</b> in the Enhance tab.
512
+ </div>
513
+ """)
514
+
515
+ with gr.Row():
516
+ with gr.Column(scale=4):
517
+ info_audio = gr.Audio(
518
+ label="Drop your audio file here",
519
+ type="filepath",
520
+ sources=["upload"],
521
+ )
522
+ info_btn = gr.Button("πŸ” Inspect", elem_id="run-btn")
523
+
524
+ with gr.Column(scale=6):
525
+ info_result = gr.HTML(value="")
526
+
527
+ def inspect_file(path):
528
+ if path is None:
529
+ return "<span style='color:#3a5270;font-family:monospace'>// no file uploaded</span>"
530
+ try:
531
+ import torchaudio as _ta
532
+ wav, sr = _ta.load(path)
533
+ ch = wav.shape[0]
534
+ dur = wav.shape[-1] / sr
535
+ # soundfile for bit depth β€” not all formats supported, fall back gracefully
536
+ try:
537
+ import soundfile as _sf
538
+ bits = _sf.info(path).subtype
539
+ except Exception:
540
+ bits = "unknown"
541
+
542
+ # Closest supported LR_SR
543
+ supported = [8000, 12000, 16000, 24000]
544
+ closest = min(supported, key=lambda x: abs(x - sr))
545
+ note_color = "#00e5aa" if sr in supported else "#f0a500"
546
+ note = (
547
+ f"βœ“ Exact match β€” set <b>Input SR = {sr//1000}</b>"
548
+ if sr in supported else
549
+ f"No exact match β€” closest supported: <b>Input SR = {closest//1000}</b>"
550
+ )
551
+
552
+ return f"""
553
+ <div style="font-family:monospace;background:#06080d;border:1px solid #1e2d45;
554
+ border-radius:8px;padding:20px 24px;line-height:2">
555
+ <div style="color:#3a5270;font-size:0.72em;letter-spacing:2px;margin-bottom:12px">// FILE INFO</div>
556
+ <table style="border-collapse:collapse;width:100%">
557
+ <tr><td style="color:#3a5270;padding-right:24px">Sample Rate</td>
558
+ <td style="color:#00e5aa;font-weight:600">{sr:,} Hz &nbsp;({sr/1000:.1f} kHz)</td></tr>
559
+ <tr><td style="color:#3a5270">Duration</td>
560
+ <td style="color:#b8cce8">{dur:.2f} s &nbsp;({dur/60:.1f} min)</td></tr>
561
+ <tr><td style="color:#3a5270">Channels</td>
562
+ <td style="color:#b8cce8">{"Mono" if ch == 1 else f"Stereo ({ch}ch)"}</td></tr>
563
+ <tr><td style="color:#3a5270">Bit depth</td>
564
+ <td style="color:#b8cce8">{bits}</td></tr>
565
+ <tr><td style="color:#3a5270">Frames</td>
566
+ <td style="color:#b8cce8">{wav.shape[-1]:,}</td></tr>
567
+ </table>
568
+ <div style="margin-top:16px;padding:10px 14px;background:#0e1018;
569
+ border-left:3px solid {note_color};border-radius:4px;
570
+ color:{note_color};font-size:0.85em">{note}</div>
571
+ </div>"""
572
+ except Exception as e:
573
+ return f"<span style='color:#ff5566;font-family:monospace'>ERROR: {e}</span>"
574
+
575
+ info_btn.click(
576
+ fn = inspect_file,
577
+ inputs = [info_audio],
578
+ outputs = [info_result],
579
+ )
580
+
581
+ gr.HTML("""
582
+ <div id="usr-footer">
583
+ <a href="https://arxiv.org/abs/2510.00771">arXiv:2510.00771</a> &nbsp;Β·&nbsp;
584
+ <a href="https://github.com/woongzip1/UniverSR">GitHub</a> &nbsp;Β·&nbsp;
585
+ <a href="https://huggingface.co/woongzip1/universr-audio">HF General</a> &nbsp;Β·&nbsp;
586
+ <a href="https://huggingface.co/woongzip1/universr-speech">HF Speech</a>
587
+ </div>
588
+ """)
589
+
590
+ return demo
591
+
592
+
593
+ # ══════════════════════════════════════════════════════════════════════════════
594
+ # ENTRY POINT
595
+ # ══════════════════════════════════════════════════════════════════════════════
596
+ if __name__ == "__main__":
597
+ demo = build_ui()
598
+ demo.launch(
599
+ server_name = "0.0.0.0",
600
+ server_port = 7860,
601
+ share = False, # True β†’ public Gradio link
602
+ inbrowser = True,
603
+ )