cyber88 commited on
Commit
72e4c2f
·
verified ·
1 Parent(s): edd0c01

Update app.py

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