cyber88 commited on
Commit
fef4da7
·
verified ·
1 Parent(s): c440ff5

Delete app.py

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