cyber88 commited on
Commit
aa8183b
·
verified ·
1 Parent(s): 4e828e8

Create Audio Preprocessor UI

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