cyber88 commited on
Commit
75755cd
·
verified ·
1 Parent(s): 876f504

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +571 -0
app.py CHANGED
@@ -0,0 +1,571 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import shutil
3
+ import os
4
+ import numpy as np
5
+ import librosa
6
+ import matplotlib.pyplot as plt
7
+ import soundfile as sf
8
+ import torch
9
+ import tempfile
10
+ import warnings
11
+ import pyloudnorm as pyln
12
+ import subprocess
13
+ from dataclasses import dataclass
14
+ import gradio as gr
15
+ import traceback
16
+ from uuid import uuid4
17
+ import zipfile
18
+ import gdown # for Google Drive downloads
19
+
20
+ # === Pre-flight Check: Install missing dependency if needed ===
21
+ try:
22
+ import resampy
23
+ except ImportError:
24
+ subprocess.check_call([sys.executable, "-m", "pip", "install", "resampy"])
25
+ import resampy
26
+
27
+ # === Dependency Check ===
28
+ if shutil.which("ffmpeg") is None:
29
+ sys.stderr.write("Missing dependency: ffmpeg\n")
30
+ sys.exit(1)
31
+ warnings.filterwarnings("ignore", category=UserWarning)
32
+
33
+ # === Global Setup ===
34
+ use_cuda = torch.cuda.is_available()
35
+ device = torch.device('cuda' if use_cuda else 'cpu')
36
+ OUTPUT_DIR = tempfile.mkdtemp(prefix="audio_preprocessor_")
37
+
38
+ # === Constants ===
39
+ DB_THRESH = -45
40
+ EDGE_SILENCE_THRESHOLD = 3e-3
41
+ VALID_FORMATS = ('.wav', '.mp3', '.flac', '.aiff', '.ogg', '.m4a')
42
+ MIN_FRAMES_FOR_RMS = 50
43
+ DEFAULT_HOP_LENGTH = 512
44
+
45
+ # === Config Dataclass ===
46
+ @dataclass(frozen=True)
47
+ class Config:
48
+ sample_rate: int
49
+ bit_depth: str
50
+ channels: str
51
+ target_lufs: float
52
+ target_peak: float
53
+ use_cuda: bool
54
+ device: torch.device
55
+ visualize: bool
56
+ segmentation: bool
57
+ duration: float
58
+ panning: bool
59
+ mp3_bitrate: str
60
+
61
+ # === Helpers ===
62
+ def pan_percent(l, r):
63
+ pl, pr = np.sum(l**2), np.sum(r**2)
64
+ t = pl + pr
65
+ if t < 1e-10:
66
+ return 50.0, 50.0, 0.0
67
+ lp, rp = pl/t*100, pr/t*100
68
+ return lp, rp, abs(lp-50)
69
+
70
+ def calculate_adaptive_hop_length(L):
71
+ return min(DEFAULT_HOP_LENGTH, max(32, L//MIN_FRAMES_FOR_RMS))
72
+
73
+ def measure_loudness(y, sr):
74
+ BLOCK = 0.4
75
+ if y.size == 0:
76
+ return {'lufs': None, 'peak': -np.inf}
77
+ y_m = np.mean(y, axis=0) if y.ndim > 1 else y
78
+ min_len = int(BLOCK * sr)
79
+ if len(y_m) < min_len:
80
+ y_m = np.pad(y_m, (0, min_len-len(y_m)))
81
+ meter = pyln.Meter(sr, block_size=BLOCK)
82
+ try:
83
+ lufs = meter.integrated_loudness(y_m)
84
+ except:
85
+ lufs = None
86
+ pk = np.max(np.abs(y))
87
+ pdb = 20*np.log10(pk) if pk > 0 else -np.inf
88
+ return {'lufs': lufs, 'peak': pdb}
89
+
90
+ def normalize_loudness(y, sr, log, tgt_lufs, tgt_peak):
91
+ if y.size == 0:
92
+ return y, {'method':'empty'}
93
+ orig_pk = np.max(np.abs(y))
94
+ orig_db = 20*np.log10(orig_pk) if orig_pk > 0 else -np.inf
95
+ y_m = np.mean(y, axis=0) if y.ndim > 1 else y
96
+ BLOCK = 0.4
97
+ min_len = max(int(BLOCK*sr), int(0.001*sr))
98
+ if len(y_m) < min_len:
99
+ log(f"[Normalize] Padding {min_len-len(y_m)} samples")
100
+ y_m = np.pad(y_m, (0, min_len-len(y_m)))
101
+ meter = pyln.Meter(sr)
102
+ try:
103
+ orig_lufs = meter.integrated_loudness(y_m)
104
+ log(f"[Normalize] Orig LUFS {orig_lufs:.2f}, Peak {orig_db:.2f}")
105
+ except Exception as e:
106
+ log(f"[Normalize] LUFS failed ({e}), peak-only")
107
+ scale = (10**(tgt_peak/20)) / orig_pk if orig_pk > 0 else 1
108
+ y_n = y * scale
109
+ fp = 20*np.log10(np.max(np.abs(y_n))) if np.max(np.abs(y_n)) > 0 else -np.inf
110
+ return y_n, {
111
+ 'original_lufs': None,
112
+ 'original_peak': orig_db,
113
+ 'normalized_lufs': None,
114
+ 'normalized_peak': fp,
115
+ 'method': 'peak_only'
116
+ }
117
+ gain = 10**((tgt_lufs - orig_lufs) / 20)
118
+ y_l = y * gain
119
+ pk_after = np.max(np.abs(y_l))
120
+ if pk_after > 10**(tgt_peak/20):
121
+ log("[Normalize] Limiting peak")
122
+ y_n = y_l * (10**(tgt_peak/20) / pk_after)
123
+ else:
124
+ y_n = y_l
125
+ fl = measure_loudness(y_n, sr)['lufs']
126
+ fp = 20*np.log10(np.max(np.abs(y_n))) if np.max(np.abs(y_n)) > 0 else -np.inf
127
+ log(f"[Normalize] Final LUFS {fl:.2f}, Peak {fp:.2f}")
128
+ return y_n, {
129
+ 'original_lufs': orig_lufs,
130
+ 'original_peak': orig_db,
131
+ 'normalized_lufs': fl,
132
+ 'normalized_peak': fp,
133
+ 'method': 'true_lufs'
134
+ }
135
+
136
+ def normalize_panning(a, log):
137
+ if a.ndim != 2 or a.shape[0] != 2:
138
+ return a
139
+ lp, rp, _ = pan_percent(a[0], a[1])
140
+ log(f"[Panning] Orig L{lp:.1f}% R{rp:.1f}%")
141
+ r1, r2 = np.sqrt(np.mean(a[0]**2)), np.sqrt(np.mean(a[1]**2))
142
+ if r1 < 1e-7 or r2 < 1e-7:
143
+ return a
144
+ corr = np.vstack((a[0], a[1] * (r1/r2)))
145
+ lp2, rp2, _ = pan_percent(corr[0], corr[1])
146
+ log(f"[Panning] Corr L{lp2:.1f}% R{rp2:.1f}%")
147
+ return corr
148
+
149
+ def detect_clipping(y):
150
+ if y.size == 0:
151
+ return False, 0.0
152
+ c = np.sum(np.abs(y) >= 0.999) / y.size
153
+ return c > 0.001, c
154
+
155
+ def attenuate_clipped_audio(y, log):
156
+ clip, ratio = detect_clipping(y)
157
+ if clip:
158
+ log(f"[Clipping] {ratio:.1%} clipped; attenuating")
159
+ pk = np.max(np.abs(y))
160
+ tgt = 10**(-1/20)
161
+ if pk > 0:
162
+ return y * (tgt/pk)
163
+ return y
164
+
165
+ def auto_slice_audio(y, sr):
166
+ if y.size == 0:
167
+ return 0, 0
168
+ L = y.shape[-1]
169
+ if L < 128:
170
+ return 0, L
171
+ hop = calculate_adaptive_hop_length(L)
172
+ frame = min(2048, L)
173
+ rms = librosa.feature.rms(y=y, frame_length=frame, hop_length=hop)[0]
174
+ db = librosa.amplitude_to_db(rms, ref=np.max)
175
+ idx = np.where(db > DB_THRESH)[0]
176
+ if idx.size == 0:
177
+ return 0, L
178
+ return idx[0] * hop, min(L, (idx[-1] + 1) * hop)
179
+
180
+ def process_silence(y, sr, log):
181
+ if y.size == 0:
182
+ return y, (0, 0, 0), (0, 0)
183
+ L = y.shape[-1]
184
+ y_m = np.mean(y, axis=0) if y.ndim > 1 else y
185
+ s0, e0 = auto_slice_audio(y_m, sr)
186
+ if e0 <= s0:
187
+ log("[Silence] All silent")
188
+ return np.array([]), (L/sr, 0, L/sr), (0, 0)
189
+ t = y[..., s0:e0]
190
+ tm = np.mean(t, axis=0) if t.ndim > 1 else t
191
+ nz = np.where(np.abs(tm) > EDGE_SILENCE_THRESHOLD)[0]
192
+ if nz.size == 0:
193
+ log("[Silence] All trimmed")
194
+ return np.array([]), (L/sr, 0, L/sr), (0, 0)
195
+ fs, fe = nz[0], nz[-1] + 1
196
+ final = t[..., fs:fe]
197
+ rem = L - final.shape[-1]
198
+ return final, ((s0+fs)/sr, (L-(s0+fe))/sr, rem/sr), (s0+fs, s0+fe)
199
+
200
+ def format_duration(s):
201
+ return f"{s:.3f}s"
202
+
203
+ def plot_zoomed_silence(y, sr, s0, e0, zoom=0.05):
204
+ zs = int(sr * zoom)
205
+ fig, axs = plt.subplots(2, 1, figsize=(6, 4))
206
+ pre = y[..., max(0, s0-zs):s0]
207
+ t0 = np.linspace(-zoom, 0, pre.shape[-1])
208
+ if pre.size > 0:
209
+ axs[0].plot(t0, pre.T if pre.ndim>1 else pre)
210
+ else:
211
+ axs[0].text(0.5, 0.5, "No pre-silence", ha='center')
212
+ axs[0].set_xlim(t0[0] if pre.size>0 else -zoom, 0)
213
+ axs[0].set_title("Zoomed Silence Pre-trim")
214
+
215
+ post = y[..., e0:e0+zs]
216
+ t1 = np.linspace(0, zoom, post.shape[-1])
217
+ if post.size > 0:
218
+ axs[1].plot(t1, post.T if post.ndim>1 else post)
219
+ else:
220
+ axs[1].text(0.5, 0.5, "No post-silence", ha='center')
221
+ axs[1].set_xlim(0, t1[-1] if post.size>0 else zoom)
222
+ axs[1].set_title("Zoomed Silence Post-trim")
223
+
224
+ plt.tight_layout()
225
+ return fig
226
+
227
+ def plot_waveform(y, sr, title, time_unit_str="s", s0=None, e0=None, segments=None):
228
+ fig, ax = plt.subplots(figsize=(6, 2.5))
229
+ t = np.arange(y.shape[-1]) / sr
230
+ if y.ndim > 1:
231
+ for c in range(y.shape[0]):
232
+ ax.plot(t, y[c], alpha=0.7, label=f'Ch{c+1}')
233
+ ax.legend(fontsize="small")
234
+ else:
235
+ ax.plot(t, y)
236
+ if s0 is not None and e0 is not None:
237
+ ax.axvline(s0/sr, linestyle='--')
238
+ ax.axvline(e0/sr, linestyle='--')
239
+ if segments:
240
+ for st, en in segments:
241
+ ax.axvline(st/sr, linestyle='-', alpha=0.6)
242
+ ax.axvline(en/sr, linestyle='-', alpha=0.6)
243
+ ax.set_title(title)
244
+ ax.set_xlabel(f"Time ({time_unit_str})")
245
+ ax.set_ylabel("Amplitude")
246
+ ax.grid(alpha=0.3)
247
+ plt.tight_layout()
248
+ return fig
249
+
250
+ def get_all_audio_files(path):
251
+ files = []
252
+ if os.path.isfile(path) and path.lower().endswith(VALID_FORMATS):
253
+ files.append(path)
254
+ elif os.path.isdir(path):
255
+ for root, _, fnames in os.walk(path):
256
+ for f in fnames:
257
+ if f.lower().endswith(VALID_FORMATS):
258
+ files.append(os.path.join(root, f))
259
+ return files
260
+
261
+ def export_audio(y, sr, orig, fmt, cfg, exp_dir, idx=None):
262
+ base = os.path.splitext(os.path.basename(orig))[0]
263
+ name = f"{base}_segment_{idx+1}.{fmt}" if idx is not None else f"{base}.{fmt}"
264
+ out = os.path.join(exp_dir, name)
265
+ if y.size == 0:
266
+ ch = 2 if cfg.channels == 'stereo' else 1
267
+ y = np.zeros((ch,1)) if ch>1 else np.zeros(1)
268
+ dat = y.T if y.ndim>1 else y
269
+ if fmt == "mp3":
270
+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=True) as tmp:
271
+ sf.write(tmp.name, dat, sr, subtype="FLOAT")
272
+ cmd = [
273
+ "ffmpeg","-y","-i",tmp.name,
274
+ "-c#a","libmp3lame","-b#a",cfg.mp3_bitrate,
275
+ "-ar",str(sr), out
276
+ ]
277
+ subprocess.run(cmd, check=True, capture_output=True)
278
+ else:
279
+ styp = f"PCM_{cfg.bit_depth}"
280
+ if fmt=="flac" and cfg.bit_depth=="32":
281
+ styp="PCM_24"
282
+ sf.write(out, dat, sr, subtype=styp)
283
+ return out
284
+
285
+ def process_file(fp, cfg, params):
286
+ res = {'messages': [], 'export_paths': [], 'plot_data': None}
287
+ def log(m):
288
+ res['messages'].append(m)
289
+ try:
290
+ log(f"--- Processing {os.path.basename(fp)} ---")
291
+ log(f"Device: {'GPU' if cfg.use_cuda else 'CPU'}")
292
+ y, orig_sr = librosa.load(fp, sr=None, mono=False)
293
+ if y.ndim == 1:
294
+ y = y[np.newaxis, :]
295
+ info = sf.info(fp)
296
+ log(f"Input: {info.samplerate}Hz, {info.channels}ch, {format_duration(info.duration)}")
297
+ # Panning
298
+ if cfg.panning and y.shape[0] == 2:
299
+ y = normalize_panning(y, log)
300
+ # Resample
301
+ if orig_sr != cfg.sample_rate:
302
+ log(f"Resampling {orig_sr}→{cfg.sample_rate}")
303
+ y = resampy.resample(y, orig_sr, cfg.sample_rate)
304
+ if y.ndim == 1:
305
+ y = y[np.newaxis, :]
306
+ # Channels
307
+ if cfg.channels == "mono" and y.shape[0] > 1:
308
+ log("Converting to mono")
309
+ y = np.mean(y, axis=0, keepdims=True)
310
+ elif cfg.channels == "stereo" and y.shape[0] == 1:
311
+ log("Converting to stereo")
312
+ y = np.vstack([y, y])
313
+ # Clipping
314
+ y = attenuate_clipped_audio(y, log)
315
+ y_pre = y.copy()
316
+ # Silence trim
317
+ y_proc, (pre, post, total), (s0, e0) = process_silence(y, cfg.sample_rate, log)
318
+ log(f"Silence removed {format_duration(total)} (start {format_duration(pre)}, end {format_duration(post)})")
319
+ if y_proc.size == 0:
320
+ log("Empty after silence; skipping")
321
+ return res
322
+ # Prepare plot_data
323
+ segments = []
324
+ if cfg.segmentation:
325
+ dur = y_proc.shape[-1] / cfg.sample_rate
326
+ if dur < cfg.duration:
327
+ log("⚠ shorter than segment; skipping export")
328
+ return res
329
+ else:
330
+ ss = int(cfg.sample_rate * cfg.duration)
331
+ nseg = int(np.ceil(dur / cfg.duration))
332
+ segments = [(i*ss, min((i+1)*ss, y_proc.shape[-1])) for i in range(nseg)]
333
+ log(f"Segmenting into {format_duration(cfg.duration)}, created {len(segments)} segments")
334
+ else:
335
+ segments = [(0, y_proc.shape[-1])]
336
+ res['plot_data'] = {
337
+ 'y_pre': y_pre, 'y_proc': y_proc,
338
+ 'sr': cfg.sample_rate,
339
+ 's0': s0, 'e0': e0,
340
+ 'segments': segments
341
+ }
342
+ # Export & normalize
343
+ normalize_flag = params['normalize'] != "No Normalization"
344
+ for i, (st, en) in enumerate(segments):
345
+ seg = y_proc[..., st:en]
346
+ if normalize_flag:
347
+ log(f"Normalizing {'segment '+str(i+1) if cfg.segmentation else 'file'}")
348
+ seg, _ = normalize_loudness(seg, cfg.sample_rate, log, cfg.target_lufs, cfg.target_peak)
349
+ out_path = export_audio(seg, cfg.sample_rate, fp, params['out_fmt'], cfg, OUTPUT_DIR, idx=(i if cfg.segmentation else None))
350
+ res['export_paths'].append(out_path)
351
+ log(f"✅ Exported {os.path.basename(out_path)}")
352
+ return res
353
+
354
+ except Exception:
355
+ tb = traceback.format_exc()
356
+ res['messages'].append(f"❌ ERROR:\n{tb}")
357
+ return res
358
+
359
+ def gradio_process(input_mode, uploads, path_in, drive_url,
360
+ out_fmt, sr, bd, ch, mp3_br,
361
+ norm, pan, seg, dur, tu, viz, zip_enable):
362
+ logs = []
363
+
364
+ # === Input Method & original file metadata ===
365
+ logs.append("=== Input Method ===")
366
+ if input_mode == "Path" and path_in.strip():
367
+ logs.append(f"Mode: Path ➞ {path_in}")
368
+ inputs = get_all_audio_files(path_in.strip())
369
+
370
+ elif input_mode == "Google Drive URL" and drive_url.strip():
371
+ logs.append(f"Mode: Google Drive ➞ {drive_url}")
372
+ # download into a temp dir
373
+ gd_dir = tempfile.mkdtemp(prefix="gdrive_")
374
+
375
+ if "folders" in drive_url:
376
+ # folder share
377
+ gdown.download_folder(drive_url, output=gd_dir, quiet=False)
378
+ inputs = get_all_audio_files(gd_dir)
379
+
380
+ else:
381
+ # single-file share (could be audio or ZIP)
382
+ gdown.download(
383
+ drive_url,
384
+ output=os.path.join(gd_dir, "downloaded"),
385
+ quiet=False,
386
+ fuzzy=True
387
+ )
388
+
389
+ # find what got downloaded
390
+ downloaded_files = get_all_audio_files(gd_dir)
391
+ zip_files = [f for f in os.listdir(gd_dir) if f.lower().endswith('.zip')]
392
+
393
+ # if it’s a ZIP, unpack it
394
+ if zip_files:
395
+ for zip_file in zip_files:
396
+ shutil.unpack_archive(os.path.join(gd_dir, zip_file), gd_dir)
397
+ inputs = get_all_audio_files(gd_dir)
398
+ else:
399
+ inputs = downloaded_files
400
+
401
+ else:
402
+ logs.append(f"Mode: Upload ➞ {len(uploads) if uploads else 0} file(s)")
403
+ inputs = [f.name for f in uploads] if uploads else []
404
+
405
+ # List each input file's original details
406
+ logs.append("=== Original File Details ===")
407
+ for fp in inputs:
408
+ try:
409
+ info = sf.info(fp)
410
+ logs.append(f"{os.path.basename(fp)}: {info.samplerate}Hz, {info.channels}ch, {format_duration(info.duration)}")
411
+ except:
412
+ logs.append(f"{os.path.basename(fp)}: <could not read metadata>")
413
+ logs.append("")
414
+
415
+ # === Output Settings ===
416
+ logs.append("=== Output Settings ===")
417
+ logs.append(f"Format: {out_fmt}")
418
+ logs.append(f"Sample Rate: {sr}")
419
+ if out_fmt.lower() == "mp3":
420
+ logs.append(f"MP3 Bitrate: {mp3_br}")
421
+ else:
422
+ logs.append(f"Bit Depth: {bd}")
423
+ logs.append(f"Channels: {ch}")
424
+ logs.append("")
425
+
426
+ # === Processing Options ===
427
+ logs.append("=== Processing Options ===")
428
+ logs.append(f"Normalization Profile: {norm}")
429
+ logs.append(f"Panning Correction: {pan}")
430
+ logs.append(f"Segmentation: {'Yes' if seg else 'No'}" + (f", Duration {dur}{tu}" if seg else ""))
431
+ logs.append(f"Show Visualizations: {'Yes' if viz else 'No'}")
432
+ logs.append("")
433
+
434
+ if not inputs:
435
+ return "\n".join(logs + ["❌ No audio files provided."]), [], []
436
+
437
+ tgt_lufs, tgt_peak = {"Spotify":(-14.0,-1.0), "Apple Music":(-16.0,-1.0)}.get(norm, (None,None))
438
+ raw = float(dur)
439
+ if tu == "Milliseconds":
440
+ dsec = raw / 1000
441
+ elif tu == "Minutes":
442
+ dsec = raw * 60
443
+ elif tu == "Hours":
444
+ dsec = raw * 3600
445
+ else:
446
+ dsec = raw
447
+
448
+ cfg = Config(
449
+ sample_rate=int(sr.replace("Hz","")),
450
+ bit_depth=bd,
451
+ channels=ch,
452
+ target_lufs=tgt_lufs,
453
+ target_peak=tgt_peak,
454
+ use_cuda=use_cuda,
455
+ device=device,
456
+ visualize=viz,
457
+ segmentation=seg,
458
+ duration=dsec,
459
+ panning=(pan == "Yes"),
460
+ mp3_bitrate=mp3_br
461
+ )
462
+ params = {'out_fmt': out_fmt, 'normalize': norm}
463
+
464
+ gallery_images = []
465
+ output_paths = []
466
+
467
+ # Process each file
468
+ for fp in inputs:
469
+ r = process_file(fp, cfg, params)
470
+ logs.extend(r['messages'])
471
+ logs.append("")
472
+ output_paths.extend(r['export_paths'])
473
+ if viz and r.get('plot_data'):
474
+ pd = r['plot_data']
475
+ figs = [
476
+ (plot_waveform(pd['y_pre'], pd['sr'], "Original w/ Trim", tu[0], pd['s0'], pd['e0'], pd['segments']), 'pre'),
477
+ (plot_waveform(pd['y_proc'], pd['sr'], "Processed Output", tu[0]), 'post'),
478
+ (plot_zoomed_silence(pd['y_pre'], pd['sr'], pd['s0'], pd['e0']), 'zoom')
479
+ ]
480
+ for fig, tag in figs:
481
+ filename = os.path.join(OUTPUT_DIR, f"{uuid4().hex}_{tag}.png")
482
+ fig.savefig(filename)
483
+ gallery_images.append(filename)
484
+
485
+ # === Handle ZIP option ===
486
+ final_paths = output_paths
487
+ if zip_enable:
488
+ if input_mode == "Path" and path_in.strip():
489
+ base = os.path.basename(path_in.rstrip("/"))
490
+ else:
491
+ base = os.path.splitext(os.path.basename(inputs[0]))[0] if inputs else "exported"
492
+ zip_path = os.path.join(OUTPUT_DIR, f"{base}_processed.zip")
493
+ with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
494
+ for file in output_paths:
495
+ arcname = os.path.basename(file)
496
+ zipf.write(file, arcname=arcname)
497
+ final_paths = [zip_path]
498
+ logs.append(f"📦 Exported all outputs into ZIP: {os.path.basename(zip_path)}")
499
+
500
+ return "\n".join(logs), gallery_images, final_paths
501
+
502
+ with gr.Blocks(title="Audio Preprocessor", theme=gr.themes.Soft()) as demo:
503
+ gr.Markdown("# Audio Preprocessor")
504
+ gr.Markdown(f"Outputs saved in `{OUTPUT_DIR}`")
505
+
506
+ with gr.Row():
507
+ with gr.Column(scale=2):
508
+ input_mode = gr.Radio(
509
+ ["Upload", "Path", "Google Drive URL"],
510
+ value="Upload",
511
+ label="Input Method"
512
+ )
513
+ file_uploader = gr.File(file_count="multiple", file_types=["audio"], label="Upload Audio Files")
514
+ path_text = gr.Textbox(placeholder="/path/to/dir", label="Or Enter Path", visible=False)
515
+ drive_url = gr.Textbox(placeholder="https://drive.google.com/...", label="Google Drive URL", visible=False)
516
+ input_mode.change(
517
+ lambda m: (
518
+ gr.update(visible=(m=="Upload")),
519
+ gr.update(visible=(m=="Path")),
520
+ gr.update(visible=(m=="Google Drive URL"))
521
+ ),
522
+ inputs=[input_mode],
523
+ outputs=[file_uploader, path_text, drive_url]
524
+ )
525
+ with gr.Column(scale=3):
526
+ gr.Markdown("### Output Settings")
527
+ with gr.Row():
528
+ out_fmt = gr.Dropdown(["wav","mp3","flac","aiff"], value="wav", label="Format")
529
+ sample_rate = gr.Dropdown(["16000Hz","44100Hz","48000Hz","96000Hz","96000Hz"], value="44100Hz", label="Sample Rate")
530
+ bit_depth = gr.Dropdown(["16","24","32"], value="24", label="Bit Depth")
531
+ with gr.Row():
532
+ channels = gr.Radio(["mono","stereo"], value="stereo", label="Channels")
533
+ mp3_bitrate = gr.Dropdown(["128k","192k","256k","320k"], value="320k", label="MP3 Bitrate")
534
+
535
+ with gr.Accordion("Processing Options", open=True):
536
+ with gr.Row():
537
+ norm_profile = gr.Dropdown(["No Normalization","Spotify","Apple Music"], value="Spotify", label="Normalization Profile")
538
+ panning_option = gr.Dropdown(["Yes","No"], value="Yes", label="Enable Panning Correction")
539
+ visualize = gr.Checkbox(value=True, label="Show Visualizations")
540
+ with gr.Row():
541
+ segmentation = gr.Checkbox(value=False, label="Enable Segmentation")
542
+ duration = gr.Slider(minimum=1, maximum=60, step=1, value=15, label="Segment Duration")
543
+ time_unit = gr.Dropdown(["Milliseconds","Seconds","Minutes","Hours"], value="Seconds", label="Time Unit")
544
+ with gr.Row():
545
+ zip_enable = gr.Checkbox(value=False, label="Save outputs as ZIP")
546
+
547
+ process_btn = gr.Button("Process Audio", variant="primary")
548
+
549
+ with gr.Tabs():
550
+ with gr.TabItem("Logs"):
551
+ logs_out = gr.Textbox(lines=15, label="Processing Logs", interactive=False)
552
+ with gr.TabItem("Visualizations"):
553
+ gr.Markdown("All waveform plots (3 per file)")
554
+ gallery = gr.Gallery(label="Plots", columns=3, height="auto")
555
+ with gr.TabItem("Output Files"):
556
+ audio_out = gr.File(file_count="multiple", label="Processed Audio Files", interactive=False)
557
+
558
+ # Enable unlimited‐time queuing on HF Spaces:
559
+ demo.queue()
560
+ process_btn.click(
561
+ fn=gradio_process,
562
+ inputs=[
563
+ input_mode, file_uploader, path_text, drive_url,
564
+ out_fmt, sample_rate, bit_depth, channels, mp3_bitrate,
565
+ norm_profile, panning_option, segmentation, duration, time_unit, visualize, zip_enable
566
+ ],
567
+ outputs=[logs_out, gallery, audio_out]
568
+ )
569
+
570
+ if __name__ == "__main__":
571
+ demo.launch()