cyber88 commited on
Commit
f01a06f
·
verified ·
1 Parent(s): 17e62d2

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +594 -0
app.py ADDED
@@ -0,0 +1,594 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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: ax.plot(t,y)
236
+ if s0 is not None and e0 is not None:
237
+ ax.axvline(s0/sr,linestyle='--'); ax.axvline(e0/sr,linestyle='--')
238
+ if segments:
239
+ for st,en in segments:
240
+ ax.axvline(st/sr,linestyle='-',alpha=0.6); ax.axvline(en/sr,linestyle='-',alpha=0.6)
241
+ ax.set_title(title); ax.set_xlabel(f"Time ({time_unit_str})"); ax.set_ylabel("Amplitude"); ax.grid(alpha=0.3)
242
+ plt.tight_layout()
243
+ return fig
244
+
245
+ def get_all_audio_files(path):
246
+ files=[]
247
+ if os.path.isfile(path) and path.lower().endswith(VALID_FORMATS): files.append(path)
248
+ elif os.path.isdir(path):
249
+ for root,_,fnames in os.walk(path):
250
+ for f in fnames:
251
+ if f.lower().endswith(VALID_FORMATS): files.append(os.path.join(root,f))
252
+ elif os.path.isfile(path) and path.lower().endswith('.zip'):
253
+ tmp=tempfile.mkdtemp(prefix="zip_extract_")
254
+ with zipfile.ZipFile(path,'r') as zf: zf.extractall(tmp)
255
+ for root,_,fnames in os.walk(tmp):
256
+ for f in fnames:
257
+ if f.lower().endswith(VALID_FORMATS): files.append(os.path.join(root,f))
258
+ return files
259
+
260
+ def download_from_gdrive_folder(url,log):
261
+ m=re.search(r'/folders/([^/?]+)',url)
262
+ if not m:
263
+ log("❌ URL must be a shared FOLDER link")
264
+ return None,None
265
+ fid=m.group(1)
266
+ parent=tempfile.mkdtemp(prefix="gdrive_dl_")
267
+ outdir=os.path.join(parent,fid); os.makedirs(outdir,exist_ok=True)
268
+ log(f"[GDrive] Downloading folder ID {fid} to {outdir}")
269
+ gdown.download_folder(url=url,output=outdir,quiet=True,use_cookies=False)
270
+ subs=[d for d in os.listdir(outdir) if os.path.isdir(os.path.join(outdir,d))]
271
+ if len(subs)==1:
272
+ det=subs[0]; log(f"[GDrive] Detected folder name: {det}"); return outdir,det
273
+ return outdir,fid
274
+
275
+ def export_audio(y, sr, orig, fmt, cfg, exp_dir, idx=None):
276
+ base = os.path.splitext(os.path.basename(orig))[0]
277
+ name = f"{base}_segment_{idx+1}.{fmt}" if idx is not None else f"{base}.{fmt}"
278
+ out = os.path.join(exp_dir, name)
279
+ if y.size == 0:
280
+ ch = 2 if cfg.channels=='stereo' else 1
281
+ y = np.zeros((ch,1)) if ch>1 else np.zeros(1)
282
+ dat = y.T if y.ndim>1 else y
283
+ # fallback bit depth for flac handled upstream in cfg.bit_depth
284
+ subtype = f"PCM_{cfg.bit_depth}"
285
+ if fmt=="mp3":
286
+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=True) as tmp:
287
+ sf.write(tmp.name, dat, sr, subtype="FLOAT")
288
+ cmd = ["ffmpeg","-y","-i", tmp.name, "-c:a","libmp3lame","-b:a",cfg.mp3_bitrate,"-ar",str(sr), out]
289
+ subprocess.run(cmd, check=True, capture_output=True)
290
+ else:
291
+ if fmt=="flac" and cfg.bit_depth=="32":
292
+ # should never happen since cfg.bit_depth is adjusted
293
+ subtype = "PCM_24"
294
+ sf.write(out, dat, sr, subtype=subtype)
295
+ return out
296
+
297
+ def process_file(fp, cfg, params):
298
+ res = {'messages':[], 'export_paths':[], 'plot_data':None}
299
+ def log(m): res['messages'].append(m)
300
+ try:
301
+ log(f"--- Processing {os.path.basename(fp)} ---")
302
+ log(f"Device: {'GPU' if cfg.use_cuda else 'CPU'}")
303
+ y, orig_sr = librosa.load(fp, sr=None, mono=False)
304
+ if y.ndim==1: y = y[np.newaxis,:]
305
+ info = sf.info(fp)
306
+ log(f"Input: {info.samplerate}Hz, {info.channels}ch, {format_duration(info.duration)}")
307
+ if cfg.panning and y.shape[0]==2:
308
+ y = normalize_panning(y, log)
309
+ if orig_sr != cfg.sample_rate:
310
+ log(f"Resampling {orig_sr}→{cfg.sample_rate}")
311
+ y = resampy.resample(y, orig_sr, cfg.sample_rate)
312
+ if y.ndim==1: y = y[np.newaxis,:]
313
+ if cfg.channels=="mono" and y.shape[0]>1:
314
+ log("Converting to mono")
315
+ y = np.mean(y, axis=0, keepdims=True)
316
+ elif cfg.channels=="stereo" and y.shape[0]==1:
317
+ y = np.vstack([y,y])
318
+ y = attenuate_clipped_audio(y, log)
319
+ y_pre = y.copy()
320
+ y_proc, (_pre,_post,total), (s0,e0) = process_silence(y, cfg.sample_rate, log)
321
+ log(f"Silence removed {format_duration(total)} (start {format_duration(_pre)}, end {format_duration(_post)})")
322
+ if y_proc.size==0:
323
+ log("Empty after silence; skipping")
324
+ return res
325
+
326
+ segments = [(0, y_proc.shape[-1])]
327
+ if cfg.segmentation:
328
+ dur_sec = y_proc.shape[-1]/cfg.sample_rate
329
+ if dur_sec < cfg.duration:
330
+ log("⚠ shorter than segment duration; skipping export")
331
+ return res
332
+ ss = int(cfg.sample_rate * cfg.duration)
333
+ nseg = int(np.ceil(dur_sec / 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
+
337
+ res['plot_data'] = {'y_pre':y_pre, 'y_proc':y_proc, 'sr':cfg.sample_rate, 's0':s0, 'e0':e0, 'segments':segments}
338
+
339
+ for i, (st,en) in enumerate(segments):
340
+ seg = y_proc[..., st:en]
341
+ if params['normalize'] != "No Normalization":
342
+ log(f"Normalizing {'segment '+str(i+1) if cfg.segmentation else 'file'}")
343
+ seg, _ = normalize_loudness(seg, cfg.sample_rate, log, cfg.target_lufs, cfg.target_peak)
344
+ out_path = export_audio(seg, cfg.sample_rate, fp, params['out_fmt'], cfg, OUTPUT_DIR, idx=(i if cfg.segmentation else None))
345
+ res['export_paths'].append(out_path)
346
+ log(f"✅ Exported {os.path.basename(out_path)}")
347
+ return res
348
+
349
+ except Exception:
350
+ tb = traceback.format_exc()
351
+ res['messages'].append(f"❌ ERROR:\n{tb}")
352
+ return res
353
+
354
+ def gradio_process(input_mode, uploads, path_in, gdrive_url,
355
+ out_fmt, sr, bd, ch, mp3_br,
356
+ norm, pan, seg, dur, tu, viz,
357
+ zip_enable, custom_zip_name):
358
+ logs = ["=== Input Method ==="]
359
+ raw_inputs = []
360
+ base_name_for_zip = None
361
+
362
+ # Gather input files
363
+ if input_mode=="Path" and path_in.strip():
364
+ logs.append(f"Mode: Path ➞ {path_in}")
365
+ raw_inputs = get_all_audio_files(path_in.strip())
366
+ base_name_for_zip = os.path.basename(path_in.rstrip("/"))
367
+ elif input_mode=="Google Drive URL" and gdrive_url.strip():
368
+ downloaded, detected = download_from_gdrive_folder(gdrive_url.strip(), logs.append)
369
+ if not downloaded:
370
+ return "\n".join(logs+["❌ Aborting: invalid Google Drive URL."]), [], [], gr.update(choices=[], value=None), None
371
+ logs.append(f"Mode: Google Drive URL ➞ {gdrive_url}")
372
+ base_name_for_zip = detected
373
+ for root,_,_ in os.walk(downloaded):
374
+ raw_inputs.extend(get_all_audio_files(root))
375
+ else:
376
+ logs.append(f"Mode: Upload ➞ {len(uploads) if uploads else 0} file(s)")
377
+ raw_inputs = [f.name for f in uploads] if uploads else []
378
+ base_name_for_zip = None
379
+
380
+ # Log original file details
381
+ logs.append("=== Original File Details ===")
382
+ for fp in raw_inputs:
383
+ try:
384
+ info = sf.info(fp)
385
+ logs.append(f"{os.path.basename(fp)}: {info.samplerate}Hz, {info.channels}ch, {format_duration(info.duration)}")
386
+ except:
387
+ logs.append(f"{os.path.basename(fp)}: <could not read metadata>")
388
+ logs.append("")
389
+
390
+ # Output settings
391
+ logs.append("=== Output Settings ===")
392
+ logs.append(f"Format: {out_fmt}")
393
+ logs.append(f"Sample Rate: {sr}")
394
+ if out_fmt.lower()=="mp3":
395
+ logs.append(f"MP3 Bitrate: {mp3_br}")
396
+ else:
397
+ logs.append(f"Bit Depth: {bd}")
398
+ logs.append(f"Channels: {ch}")
399
+ logs.append("")
400
+
401
+ # FLAC 32→24 fallback
402
+ export_bd = bd
403
+ if out_fmt=="flac" and bd=="32":
404
+ logs.append("⚠ FLAC does not support 32-bit; falling back to 24-bit")
405
+ export_bd = "24"
406
+
407
+ # Processing options
408
+ logs.append("=== Processing Options ===")
409
+ logs.append(f"Normalization Profile: {norm}")
410
+ logs.append(f"Panning Correction: {pan}")
411
+ logs.append(f"Segmentation: {'Yes' if seg else 'No'}" + (f", Duration {dur}{tu}" if seg else ""))
412
+ logs.append(f"Show Visualizations: {'Yes' if viz else 'No'}")
413
+ logs.append(f"Custom ZIP Name: {custom_zip_name or '(none)'}")
414
+ logs.append("")
415
+
416
+ if not raw_inputs:
417
+ return "\n".join(logs+["❌ No audio files provided."]), [], [], gr.update(choices=[], value=None), None
418
+
419
+ # Build config
420
+ params = {'out_fmt': out_fmt, 'normalize': norm}
421
+ tgt_lufs, tgt_peak = {"Spotify":(-14.0,-1.0), "Apple Music":(-16.0,-1.0)}.get(norm, (None, None))
422
+ raw = float(dur)
423
+ if tu=="Milliseconds": dsec = raw/1000
424
+ elif tu=="Minutes": dsec = raw*60
425
+ elif tu=="Hours": dsec = raw*3600
426
+ else: dsec = raw
427
+
428
+ cfg = Config(
429
+ sample_rate=int(sr.replace("Hz","")),
430
+ bit_depth=export_bd, channels=ch,
431
+ target_lufs=tgt_lufs, target_peak=tgt_peak,
432
+ use_cuda=use_cuda, device=device,
433
+ visualize=viz, segmentation=seg,
434
+ duration=dsec, panning=(pan=="Yes"),
435
+ mp3_bitrate=mp3_br
436
+ )
437
+
438
+ gallery_images = []
439
+ export_paths = []
440
+
441
+ # Process each file in parallel
442
+ workers = os.cpu_count() or 1
443
+ with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as executor:
444
+ futures = {executor.submit(process_file, fp, cfg, params): fp for fp in raw_inputs}
445
+ for fut in concurrent.futures.as_completed(futures):
446
+ r = fut.result()
447
+ logs.extend(r['messages'])
448
+ logs.append("")
449
+ export_paths.extend(r['export_paths'])
450
+ if viz and r.get('plot_data'):
451
+ pd = r['plot_data']
452
+ figs = [
453
+ (plot_waveform(pd['y_pre'], pd['sr'], "Original w/ Trim", tu[0], pd['s0'], pd['e0'], pd['segments']), 'pre'),
454
+ (plot_waveform(pd['y_proc'], pd['sr'], "Processed Output", tu[0]), 'post'),
455
+ (plot_zoomed_silence(pd['y_pre'], pd['sr'], pd['s0'], pd['e0']), 'zoom')
456
+ ]
457
+ for fig, tag in figs:
458
+ fn = os.path.join(OUTPUT_DIR, f"{uuid4().hex}_{tag}.png")
459
+ fig.savefig(fn)
460
+ gallery_images.append(fn)
461
+
462
+ # Prepare playback paths: convert FLAC exports to WAV for player
463
+ play_paths = []
464
+ for p in export_paths:
465
+ if p.lower().endswith('.flac'):
466
+ wav_play = p[:-5] + '_playback.wav'
467
+ y, sr_load = sf.read(p)
468
+ sf.write(wav_play, y, sr_load)
469
+ play_paths.append(wav_play)
470
+ else:
471
+ play_paths.append(p)
472
+
473
+ # Determine download vs playback paths
474
+ if zip_enable and export_paths:
475
+ if custom_zip_name.strip():
476
+ zip_base = custom_zip_name.strip()
477
+ elif base_name_for_zip:
478
+ zip_base = base_name_for_zip
479
+ else:
480
+ zip_base = os.path.splitext(os.path.basename(raw_inputs[0]))[0]
481
+ zip_filename = f"{zip_base}.zip"
482
+ zip_path = os.path.join(OUTPUT_DIR, zip_filename)
483
+ with zipfile.ZipFile(zip_path, 'w') as zf:
484
+ for ex in export_paths:
485
+ arc = os.path.relpath(ex, OUTPUT_DIR)
486
+ zf.write(ex, arcname=arc)
487
+ download_paths = [zip_path]
488
+ else:
489
+ download_paths = export_paths
490
+
491
+ # Final logs
492
+ logs.append("=== Exported Files ===")
493
+ logs.append(f"Count: {len(download_paths)}")
494
+ logs.append("--- Used Settings ---")
495
+ logs.append(f"Format: {out_fmt}")
496
+ logs.append(f"Sample Rate: {sr}")
497
+ if out_fmt.lower()=="mp3":
498
+ logs.append(f"MP3 Bitrate: {mp3_br}")
499
+ else:
500
+ logs.append(f"Bit Depth: {export_bd}")
501
+ logs.append(f"Channels: {ch}")
502
+ logs.append(f"Normalization Profile: {norm}")
503
+ logs.append(f"Panning Correction: {pan}")
504
+ logs.append(f"Segmentation: {'Yes' if seg else 'No'}" + (f", Duration {dur}{tu}" if seg else ""))
505
+ logs.append(f"Visualizations: {'Yes' if viz else 'No'}")
506
+ logs.append("")
507
+ for fn in download_paths:
508
+ logs.append(os.path.basename(fn))
509
+
510
+ # Update dropdown for playback
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
+ if __name__ == "__main__":
594
+ demo.launch(debug=True)