cyber88 commited on
Commit
c49b027
·
verified ·
1 Parent(s): 3bc5e86

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -576
app.py DELETED
@@ -1,576 +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
- print(f"Audio output will be saved in: {OUTPUT_DIR}")
38
-
39
- # === Constants ===
40
- DB_THRESH = -45
41
- EDGE_SILENCE_THRESHOLD = 3e-3
42
- VALID_FORMATS = ('.wav', '.mp3', '.flac', '.aiff', '.ogg', '.m4a')
43
- MIN_FRAMES_FOR_RMS = 50
44
- DEFAULT_HOP_LENGTH = 512
45
-
46
- # === Config Dataclass ===
47
- @dataclass(frozen=True)
48
- class Config:
49
- sample_rate: int
50
- bit_depth: str
51
- channels: str
52
- target_lufs: float
53
- target_peak: float
54
- use_cuda: bool
55
- device: torch.device
56
- visualize: bool
57
- segmentation: bool
58
- duration: float
59
- panning: bool
60
- mp3_bitrate: str
61
-
62
- # === Helpers ===
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
- with tempfile.NamedTemporaryFile(suffix=".wav", delete=True) as tmp:
272
- sf.write(tmp.name, dat, sr, subtype="FLOAT")
273
- cmd = [
274
- "ffmpeg","-y","-i",tmp.name,
275
- "-c#a","libmp3lame","-b#a",cfg.mp3_bitrate,
276
- "-ar",str(sr), out
277
- ]
278
- subprocess.run(cmd, check=True, capture_output=True)
279
- else:
280
- styp = f"PCM_{cfg.bit_depth}"
281
- if fmt=="flac" and cfg.bit_depth=="32":
282
- styp="PCM_24"
283
- sf.write(out, dat, sr, subtype=styp)
284
- return out
285
-
286
- def process_file(fp, cfg, params):
287
- res = {'messages': [], 'export_paths': [], 'plot_data': None}
288
- def log(m):
289
- res['messages'].append(m)
290
- try:
291
- log(f"--- Processing {os.path.basename(fp)} ---")
292
- log(f"Device: {'GPU' if cfg.use_cuda else 'CPU'}")
293
- y, orig_sr = librosa.load(fp, sr=None, mono=False)
294
- if y.ndim == 1:
295
- y = y[np.newaxis, :]
296
- info = sf.info(fp)
297
- log(f"Input: {info.samplerate}Hz, {info.channels}ch, {format_duration(info.duration)}")
298
- # Panning
299
- if cfg.panning and y.shape[0] == 2:
300
- y = normalize_panning(y, log)
301
- # Resample
302
- if orig_sr != cfg.sample_rate:
303
- log(f"Resampling {orig_sr}→{cfg.sample_rate}")
304
- y = resampy.resample(y, orig_sr, cfg.sample_rate)
305
- if y.ndim == 1:
306
- y = y[np.newaxis, :]
307
- # Channels
308
- if cfg.channels == "mono" and y.shape[0] > 1:
309
- log("Converting to mono")
310
- y = np.mean(y, axis=0, keepdims=True)
311
- elif cfg.channels == "stereo" and y.shape[0] == 1:
312
- log("Converting to stereo")
313
- y = np.vstack([y, y])
314
- # Clipping
315
- y = attenuate_clipped_audio(y, log)
316
- y_pre = y.copy()
317
- # Silence trim
318
- y_proc, (pre, post, total), (s0, e0) = process_silence(y, cfg.sample_rate, log)
319
- log(f"Silence removed {format_duration(total)} (start {format_duration(pre)}, end {format_duration(post)})")
320
- if y_proc.size == 0:
321
- log("Empty after silence; skipping")
322
- return res
323
- # Prepare plot_data
324
- segments = []
325
- if cfg.segmentation:
326
- dur = y_proc.shape[-1] / cfg.sample_rate
327
- if dur < cfg.duration:
328
- log("⚠ shorter than segment; skipping export")
329
- return res
330
- else:
331
- ss = int(cfg.sample_rate * cfg.duration)
332
- nseg = int(np.ceil(dur / cfg.duration))
333
- segments = [(i*ss, min((i+1)*ss, y_proc.shape[-1])) for i in range(nseg)]
334
- log(f"Segmenting into {format_duration(cfg.duration)}, created {len(segments)} segments")
335
- else:
336
- segments = [(0, y_proc.shape[-1])]
337
- res['plot_data'] = {
338
- 'y_pre': y_pre, 'y_proc': y_proc,
339
- 'sr': cfg.sample_rate,
340
- 's0': s0, 'e0': e0,
341
- 'segments': segments
342
- }
343
- # Export & normalize
344
- normalize_flag = params['normalize'] != "No Normalization"
345
- for i, (st, en) in enumerate(segments):
346
- seg = y_proc[..., st:en]
347
- if normalize_flag:
348
- log(f"Normalizing {'segment '+str(i+1) if cfg.segmentation else 'file'}")
349
- seg, _ = normalize_loudness(seg, cfg.sample_rate, log, cfg.target_lufs, cfg.target_peak)
350
- out_path = export_audio(seg, cfg.sample_rate, fp, params['out_fmt'], cfg, OUTPUT_DIR, idx=(i if cfg.segmentation else None))
351
- res['export_paths'].append(out_path)
352
- log(f"✅ Exported {os.path.basename(out_path)}")
353
- return res
354
-
355
- except Exception:
356
- tb = traceback.format_exc()
357
- res['messages'].append(f"❌ ERROR:\n{tb}")
358
- return res
359
-
360
- def gradio_process(input_mode, uploads, path_in, drive_url,
361
- out_fmt, sr, bd, ch, mp3_br,
362
- norm, pan, seg, dur, tu, viz, zip_enable):
363
- logs = []
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
- elif input_mode == "Google Drive URL" and drive_url.strip():
371
- logs.append(f"Mode: Google Drive ➞ {drive_url}")
372
- # download into a temp dir
373
- gd_dir = tempfile.mkdtemp(prefix="gdrive_")
374
- if "folders" in drive_url:
375
- # folder share
376
- gdown.download_folder(drive_url, output=gd_dir, quiet=False)
377
- else:
378
- # single file or zip
379
- out_target = os.path.join(gd_dir, "downloaded")
380
- gdown.download(drive_url, out_target, quiet=False)
381
- if out_target.lower().endswith(".zip"):
382
- with zipfile.ZipFile(out_target, "r") as zf:
383
- zf.extractall(gd_dir)
384
- inputs = get_all_audio_files(gd_dir)
385
- else:
386
- logs.append(f"Mode: Upload ➞ {len(uploads) if uploads else 0} file(s)")
387
- inputs = [f.name for f in uploads] if uploads else []
388
-
389
- # ... rest of processing unchanged ...
390
-
391
- # List each input file's original details
392
- logs.append("=== Original File Details ===")
393
- for fp in inputs:
394
- try:
395
- info = sf.info(fp)
396
- logs.append(f"{os.path.basename(fp)}: {info.samplerate}Hz, {info.channels}ch, {format_duration(info.duration)}")
397
- except:
398
- logs.append(f"{os.path.basename(fp)}: <could not read metadata>")
399
- logs.append("")
400
-
401
- # === Output Settings ===
402
- logs.append("=== Output Settings ===")
403
- logs.append(f"Format: {out_fmt}")
404
- logs.append(f"Sample Rate: {sr}")
405
- if out_fmt.lower() == "mp3":
406
- logs.append(f"MP3 Bitrate: {mp3_br}")
407
- else:
408
- logs.append(f"Bit Depth: {bd}")
409
- logs.append(f"Channels: {ch}")
410
- logs.append("")
411
-
412
- # === Processing Options ===
413
- logs.append("=== Processing Options ===")
414
- logs.append(f"Normalization Profile: {norm}")
415
- logs.append(f"Panning Correction: {pan}")
416
- logs.append(f"Segmentation: {'Yes' if seg else 'No'}" + (f", Duration {dur}{tu}" if seg else ""))
417
- logs.append(f"Show Visualizations: {'Yes' if viz else 'No'}")
418
- logs.append("")
419
-
420
- if not inputs:
421
- return "\n".join(logs + ["❌ No audio files provided."]), [], []
422
-
423
- tgt_lufs, tgt_peak = {"Spotify":(-14.0,-1.0), "Apple Music":(-16.0,-1.0)}.get(norm, (None,None))
424
- raw = float(dur)
425
- if tu == "Milliseconds":
426
- dsec = raw / 1000
427
- elif tu == "Minutes":
428
- dsec = raw * 60
429
- elif tu == "Hours":
430
- dsec = raw * 3600
431
- else:
432
- dsec = raw
433
-
434
- cfg = Config(
435
- sample_rate=int(sr.replace("Hz","")),
436
- bit_depth=bd,
437
- channels=ch,
438
- target_lufs=tgt_lufs,
439
- target_peak=tgt_peak,
440
- use_cuda=use_cuda,
441
- device=device,
442
- visualize=viz,
443
- segmentation=seg,
444
- duration=dsec,
445
- panning=(pan == "Yes"),
446
- mp3_bitrate=mp3_br
447
- )
448
- params = {'out_fmt': out_fmt, 'normalize': norm}
449
-
450
- gallery_images = []
451
- output_paths = []
452
-
453
- # Process each file
454
- for fp in inputs:
455
- r = process_file(fp, cfg, params)
456
- logs.extend(r['messages'])
457
- logs.append("")
458
- output_paths.extend(r['export_paths'])
459
- if viz and r.get('plot_data'):
460
- pd = r['plot_data']
461
- figs = [
462
- (plot_waveform(pd['y_pre'], pd['sr'], "Original w/ Trim", tu[0], pd['s0'], pd['e0'], pd['segments']), 'pre'),
463
- (plot_waveform(pd['y_proc'], pd['sr'], "Processed Output", tu[0]), 'post'),
464
- (plot_zoomed_silence(pd['y_pre'], pd['sr'], pd['s0'], pd['e0']), 'zoom')
465
- ]
466
- for fig, tag in figs:
467
- filename = os.path.join(OUTPUT_DIR, f"{uuid4().hex}_{tag}.png")
468
- fig.savefig(filename)
469
- gallery_images.append(filename)
470
-
471
- # === Handle ZIP option ===
472
- final_paths = output_paths
473
- if zip_enable:
474
- if input_mode == "Path" and path_in.strip():
475
- base = os.path.basename(path_in.rstrip("/"))
476
- else:
477
- base = os.path.splitext(os.path.basename(inputs[0]))[0] if inputs else "exported"
478
- zip_path = os.path.join(OUTPUT_DIR, f"{base}_processed.zip")
479
- with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
480
- for file in output_paths:
481
- arcname = os.path.basename(file)
482
- zipf.write(file, arcname=arcname)
483
- final_paths = [zip_path]
484
- logs.append(f"📦 Exported all outputs into ZIP: {os.path.basename(zip_path)}")
485
-
486
- return "\n".join(logs), final_paths, gallery_images
487
-
488
- # === Exported Files Summary & Settings Echo ===
489
- logs.append("=== Exported Files ===")
490
- logs.append(f"Count: {len(final_paths)}")
491
- logs.append("--- Used Settings ---")
492
- logs.append(f"Format: {out_fmt}")
493
- logs.append(f"Sample Rate: {sr}")
494
- if out_fmt.lower() == "mp3":
495
- logs.append(f"MP3 Bitrate: {mp3_br}")
496
- else:
497
- logs.append(f"Bit Depth: {bd}")
498
- logs.append(f"Channels: {ch}")
499
- logs.append(f"Normalization Profile: {norm}")
500
- logs.append(f"Panning Correction: {pan}")
501
- logs.append(f"Segmentation: {'Yes' if seg else 'No'}" + (f", Duration {dur}{tu}" if seg else ""))
502
- logs.append(f"Visualizations: {'Yes' if viz else 'No'}")
503
- logs.append("")
504
- for p in final_paths:
505
- logs.append(os.path.basename(p))
506
-
507
- return "\n".join(logs), gallery_images, final_paths
508
-
509
- with gr.Blocks(title="Audio Preprocessor", theme=gr.themes.Soft()) as demo:
510
- gr.Markdown("# Audio Preprocessor")
511
- gr.Markdown(f"Outputs saved in `{OUTPUT_DIR}`")
512
-
513
- with gr.Row():
514
- with gr.Column(scale=2):
515
- input_mode = gr.Radio(
516
- ["Upload", "Path", "Google Drive URL"],
517
- value="Upload",
518
- label="Input Method"
519
- )
520
- file_uploader = gr.File(file_count="multiple", file_types=["audio"], label="Upload Audio Files")
521
- path_text = gr.Textbox(placeholder="/path/to/dir", label="Or Enter Path", visible=False)
522
- drive_url = gr.Textbox(placeholder="https://drive.google.com/...", label="Google Drive URL", visible=False)
523
- input_mode.change(
524
- lambda m: (
525
- gr.update(visible=(m=="Upload")),
526
- gr.update(visible=(m=="Path")),
527
- gr.update(visible=(m=="Google Drive URL"))
528
- ),
529
- inputs=[input_mode],
530
- outputs=[file_uploader, path_text, drive_url]
531
- )
532
- with gr.Column(scale=3):
533
- gr.Markdown("### Output Settings")
534
- with gr.Row():
535
- out_fmt = gr.Dropdown(["wav","mp3","flac","aiff"], value="wav", label="Format")
536
- sample_rate = gr.Dropdown(["16000Hz","44100Hz","48000Hz","96000Hz","96000Hz"], value="44100Hz", label="Sample Rate")
537
- bit_depth = gr.Dropdown(["16","24","32"], value="24", label="Bit Depth")
538
- with gr.Row():
539
- channels = gr.Radio(["mono","stereo"], value="stereo", label="Channels")
540
- mp3_bitrate = gr.Dropdown(["128k","192k","256k","320k"], value="320k", label="MP3 Bitrate")
541
-
542
- with gr.Accordion("Processing Options", open=True):
543
- with gr.Row():
544
- norm_profile = gr.Dropdown(["No Normalization","Spotify","Apple Music"], value="Spotify", label="Normalization Profile")
545
- panning_option = gr.Dropdown(["Yes","No"], value="Yes", label="Enable Panning Correction")
546
- visualize = gr.Checkbox(value=True, label="Show Visualizations")
547
- with gr.Row():
548
- segmentation = gr.Checkbox(value=False, label="Enable Segmentation")
549
- duration = gr.Slider(minimum=1, maximum=60, step=1, value=15, label="Segment Duration")
550
- time_unit = gr.Dropdown(["Milliseconds","Seconds","Minutes","Hours"], value="Seconds", label="Time Unit")
551
- with gr.Row():
552
- zip_enable = gr.Checkbox(value=False, label="Save outputs as ZIP")
553
-
554
- process_btn = gr.Button("Process Audio", variant="primary")
555
-
556
- with gr.Tabs():
557
- with gr.TabItem("Logs"):
558
- logs_out = gr.Textbox(lines=15, label="Processing Logs", interactive=False)
559
- with gr.TabItem("Visualizations"):
560
- gr.Markdown("All waveform plots (3 per file)")
561
- gallery = gr.Gallery(label="Plots", columns=3, height="auto")
562
- with gr.TabItem("Output Files"):
563
- audio_out = gr.File(file_count="multiple", label="Processed Audio Files", interactive=False)
564
-
565
- process_btn.click(
566
- fn=gradio_process,
567
- inputs=[
568
- input_mode, file_uploader, path_text, drive_url,
569
- out_fmt, sample_rate, bit_depth, channels, mp3_bitrate,
570
- norm_profile, panning_option, segmentation, duration, time_unit, visualize, zip_enable
571
- ],
572
- outputs=[logs_out, gallery, audio_out]
573
- )
574
-
575
- if __name__ == "__main__":
576
- demo.launch(debug=True)