officialcyber88 commited on
Commit
67063c2
·
verified ·
1 Parent(s): b7ce35a

Create app.py

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