cyber88 commited on
Commit
bf8b21c
·
verified ·
1 Parent(s): ae2f2b0

Delete app.py

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