cyber88 commited on
Commit
57fe807
·
verified ·
1 Parent(s): 685e99c

Create app.py

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