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

Delete app.py

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