tee342 commited on
Commit
6b0844b
·
verified ·
1 Parent(s): cca5566

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +1103 -1133
app.py CHANGED
@@ -1,1145 +1,1115 @@
1
- import gradio as gr
2
- from pydub import AudioSegment
3
- from pydub.silence import detect_nonsilent
4
- import numpy as np
5
- import tempfile
6
- import os
7
- import noisereduce as nr
8
- import torch
9
- from demucs import pretrained
10
- from demucs.apply import apply_model
11
- import torchaudio
12
- from pathlib import Path
13
- import matplotlib.pyplot as plt
14
- from io import BytesIO
15
- from PIL import Image
16
- import zipfile
17
- import datetime
18
- import librosa
19
- import warnings
20
- from faster_whisper import WhisperModel
21
- from TTS.api import TTS
22
- import base64
23
- import pickle
24
- import json
25
- import soundfile as sf
26
-
27
- # Suppress warnings
28
- warnings.filterwarnings("ignore")
29
-
30
- # === Effect Map (Global) ===
31
- def apply_normalize(audio):
32
- return audio.normalize()
33
-
34
- def apply_noise_reduction(audio):
35
- samples, frame_rate = audiosegment_to_array(audio)
36
- reduced = nr.reduce_noise(y=samples, sr=frame_rate)
37
- return array_to_audiosegment(reduced, frame_rate, channels=audio.channels)
38
-
39
- def apply_compression(audio):
40
- return audio.compress_dynamic_range()
41
-
42
- def apply_reverb(audio):
43
- reverb = audio - 10
44
- return audio.overlay(reverb, position=1000)
45
-
46
- def apply_pitch_shift(audio, semitones=-2):
47
- new_frame_rate = int(audio.frame_rate * (2 ** (semitones / 12)))
48
- samples = np.array(audio.get_array_of_samples())
49
- resampled = np.interp(np.arange(0, len(samples), 2 ** (semitones / 12)), np.arange(len(samples)), samples).astype(np.int16)
50
- return AudioSegment(resampled.tobytes(), frame_rate=new_frame_rate, sample_width=audio.sample_width, channels=audio.channels)
51
-
52
- def apply_echo(audio, delay_ms=500, decay=0.5):
53
- echo = audio - 10
54
- return audio.overlay(echo, position=delay_ms)
55
-
56
- def apply_stereo_widen(audio, pan_amount=0.3):
57
- left = audio.pan(-pan_amount)
58
- right = audio.pan(pan_amount)
59
- return AudioSegment.from_mono_audiosegments(left, right)
60
-
61
- def apply_bass_boost(audio, gain=10):
62
- return audio.low_pass_filter(100).apply_gain(gain)
63
-
64
- def apply_treble_boost(audio, gain=10):
65
- return audio.high_pass_filter(4000).apply_gain(gain)
66
-
67
- def apply_limiter(audio, limit_dB=-1):
68
- limiter = audio._spawn(audio.raw_data, overrides={"frame_rate": audio.frame_rate})
69
- return limiter.apply_gain(limit_dB)
70
-
71
- def apply_auto_gain(audio, target_dB=-20):
72
- change = target_dB - audio.dBFS
73
- return audio.apply_gain(change)
74
-
75
- def apply_vocal_distortion(audio, intensity=0.3):
76
- samples = np.array(audio.get_array_of_samples()).astype(np.float32)
77
- distorted = samples + intensity * np.sin(samples * 2 * np.pi / 32768)
78
- return array_to_audiosegment(distorted.astype(np.int16), audio.frame_rate, channels=audio.channels)
79
-
80
- def apply_harmony(audio, shift_semitones=4):
81
- shifted_up = apply_pitch_shift(audio, shift_semitones)
82
- shifted_down = apply_pitch_shift(audio, -shift_semitones)
83
- return audio.overlay(shifted_up).overlay(shifted_down)
84
-
85
- def apply_stage_mode(audio):
86
- processed = apply_reverb(audio)
87
- processed = apply_bass_boost(processed, gain=6)
88
- return apply_limiter(processed, limit_dB=-2)
89
-
90
- def apply_bitcrush(audio, bit_depth=8):
91
- samples = np.array(audio.get_array_of_samples())
92
- max_val = 2 ** (bit_depth) - 1
93
- downsampled = np.round(samples / (32768 / max_val)).astype(np.int16)
94
- return array_to_audiosegment(downsampled, audio.frame_rate // 2, channels=audio.channels)
95
-
96
- # === Helper Functions ===
97
- def audiosegment_to_array(audio):
98
- return np.array(audio.get_array_of_samples()), audio.frame_rate
99
-
100
- def array_to_audiosegment(samples, frame_rate, channels=1):
101
- return AudioSegment(
102
- samples.tobytes(),
103
- frame_rate=int(frame_rate),
104
- sample_width=samples.dtype.itemsize,
105
- channels=channels
106
- )
107
-
108
- # === Loudness Matching (EBU R128) ===
109
- try:
110
- import pyloudnorm as pyln
111
- except ImportError:
112
- print("Installing pyloudnorm...")
113
- import subprocess
114
- subprocess.run(["pip", "install", "pyloudnorm"])
115
- import pyloudnorm as pyln
116
-
117
- def match_loudness(audio_path, target_lufs=-14.0):
118
- meter = pyln.Meter(44100)
119
- wav = AudioSegment.from_file(audio_path).set_frame_rate(44100)
120
- samples = np.array(wav.get_array_of_samples()).astype(np.float64) / 32768.0
121
- loudness = meter.integrated_loudness(samples)
122
- gain_db = target_lufs - loudness
123
- adjusted = wav + gain_db
124
- out_path = os.path.join(tempfile.gettempdir(), "loudness_output.wav")
125
- adjusted.export(out_path, format="wav")
126
- return out_path
127
-
128
- # === Auto-EQ per Genre – With R&B, Soul, Funk ===
129
- def auto_eq(audio, genre="Pop"):
130
- eq_map = {
131
- "Pop": [(200, 500, -3), (2000, 4000, +4)],
132
- "EDM": [(60, 250, +6), (8000, 12000, +3)],
133
- "Rock": [(1000, 3000, +4), (7000, 10000, -3)],
134
- "Hip-Hop": [(20, 100, +6), (7000, 10000, -4)],
135
- "Acoustic": [(100, 300, -3), (4000, 8000, +2)],
136
- "Metal": [(100, 500, -4), (2000, 5000, +6), (7000, 12000, -3)],
137
- "Trap": [(80, 120, +6), (3000, 6000, -4)],
138
- "LoFi": [(20, 200, +3), (1000, 3000, -2)],
139
- "Jazz": [(100, 400, +2), (1500, 3000, +1)],
140
- "Classical": [(200, 1000, +1), (3000, 6000, +2)],
141
- "Chillhop": [(50, 200, +3), (2000, 5000, +1)],
142
- "Ambient": [(100, 500, +4), (6000, 12000, +2)],
143
- "Jazz Piano": [(100, 1000, +3), (2000, 5000, +2)],
144
- "Trap EDM": [(60, 120, +6), (2000, 5000, -3)],
145
- "Indie Rock": [(150, 400, +2), (2000, 5000, +3)],
146
- "Lo-Fi Jazz": [(80, 200, +3), (2000, 4000, -1)],
147
- "R&B": [(100, 300, +4), (2000, 4000, +3)],
148
- "Soul": [(80, 200, +3), (1500, 3500, +4)],
149
- "Funk": [(80, 200, +5), (1000, 3000, +3)],
150
- "Default": []
151
- }
152
-
153
- from scipy.signal import butter, sosfilt
154
-
155
- def band_eq(samples, sr, lowcut, highcut, gain):
156
- sos = butter(10, [lowcut, highcut], btype='band', output='sos', fs=sr)
157
- filtered = sosfilt(sos, samples)
158
- return samples + gain * filtered
159
-
160
- samples, sr = audiosegment_to_array(audio)
161
- samples = samples.astype(np.float64)
162
-
163
- for band in eq_map.get(genre, []):
164
- low, high, gain = band
165
- samples = band_eq(samples, sr, low, high, gain)
166
-
167
- return array_to_audiosegment(samples.astype(np.int16), sr, channels=audio.channels)
168
-
169
- # === Load Track Helpers ===
170
- def load_track_local(path, sample_rate, channels=2):
171
- sig, rate = torchaudio.load(path)
172
- if rate != sample_rate:
173
- sig = torchaudio.functional.resample(sig, rate, sample_rate)
174
- if channels == 1:
175
- sig = sig.mean(0)
176
- return sig
177
-
178
- def save_track(path, wav, sample_rate):
179
- path = Path(path)
180
- torchaudio.save(str(path), wav, sample_rate)
181
-
182
- # === Vocal Isolation Helpers ===
183
- def apply_vocal_isolation(audio_path):
184
- model = pretrained.get_model(name='htdemucs')
185
- wav = load_track_local(audio_path, model.samplerate, channels=2)
186
- ref = wav.mean(0)
187
- wav -= ref[:, None]
188
- sources = apply_model(model, wav[None])[0]
189
- wav += ref[:, None]
190
-
191
- vocal_track = sources[3].cpu()
192
- out_path = os.path.join(tempfile.gettempdir(), "vocals.wav")
193
- save_track(out_path, vocal_track, model.samplerate)
194
- return out_path
195
-
196
- # === Stem Splitting Function (Now Defined!) ===
197
- def stem_split(audio_path):
198
- model = pretrained.get_model(name='htdemucs')
199
- wav = load_track_local(audio_path, model.samplerate, channels=2)
200
- sources = apply_model(model, wav[None])[0]
201
-
202
- output_dir = tempfile.mkdtemp()
203
- stem_paths = []
204
-
205
- for i, name in enumerate(['drums', 'bass', 'other', 'vocals']):
206
- path = os.path.join(output_dir, f"{name}.wav")
207
- save_track(path, sources[i].cpu(), model.samplerate)
208
- stem_paths.append(gr.File(value=path))
209
-
210
- return stem_paths
211
-
212
- # === Process Audio Function – Fully Featured ===
213
- def process_audio(audio_file, selected_effects, isolate_vocals, preset_name, export_format):
214
- status = "🔊 Loading audio..."
215
- try:
216
- audio = AudioSegment.from_file(audio_file)
217
- status = "🛠 Applying effects..."
218
-
219
- effect_map_real = {
220
- "Noise Reduction": apply_noise_reduction,
221
- "Compress Dynamic Range": apply_compression,
222
- "Add Reverb": apply_reverb,
223
- "Pitch Shift": lambda x: apply_pitch_shift(x),
224
- "Echo": apply_echo,
225
- "Stereo Widening": apply_stereo_widen,
226
- "Bass Boost": apply_bass_boost,
227
- "Treble Boost": apply_treble_boost,
228
- "Normalize": apply_normalize,
229
- "Limiter": lambda x: apply_limiter(x, limit_dB=-1),
230
- "Auto Gain": lambda x: apply_auto_gain(x, target_dB=-20),
231
- "Vocal Distortion": lambda x: apply_vocal_distortion(x),
232
- "Stage Mode": apply_stage_mode
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
233
  }
234
-
235
- history = [audio] # Undo stack
236
-
237
- for effect_name in selected_effects:
238
- if effect_name in effect_map_real:
239
- audio = effect_map_real[effect_name](audio)
240
- history.append(audio)
241
-
242
- status = "💾 Saving final audio..."
243
- with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as f:
244
- if isolate_vocals:
245
- temp_input = os.path.join(tempfile.gettempdir(), "input.wav")
246
- audio.export(temp_input, format="wav")
247
- vocal_path = apply_vocal_isolation(temp_input)
248
- final_audio = AudioSegment.from_wav(vocal_path)
249
- else:
250
- final_audio = audio
251
-
252
- output_path = f.name
253
- final_audio.export(output_path, format=export_format.lower())
254
-
255
- waveform_image = show_waveform(output_path)
256
- genre = detect_genre(output_path)
257
- session_log = generate_session_log(audio_file, selected_effects, isolate_vocals, export_format, genre)
258
-
259
- status = "🎉 Done!"
260
- return output_path, waveform_image, session_log, genre, status, history
261
-
262
- except Exception as e:
263
- status = f"❌ Error: {str(e)}"
264
- return None, None, status, "", status, []
265
-
266
- # === Waveform Generator ===
267
- def show_waveform(audio_file):
268
- try:
269
- audio = AudioSegment.from_file(audio_file)
270
- samples = np.array(audio.get_array_of_samples())
271
- plt.figure(figsize=(10, 2))
272
- plt.plot(samples[:10000], color="skyblue")
273
- plt.axis("off")
274
- buf = BytesIO()
275
- plt.savefig(buf, format="png", bbox_inches="tight", dpi=100)
276
- plt.close()
277
- buf.seek(0)
278
- return Image.open(buf)
279
- except Exception:
280
- return None
281
-
282
- # === Genre Detection ===
283
- def detect_genre(audio_path):
284
- try:
285
- y, sr = torchaudio.load(audio_path)
286
- mfccs = librosa.feature.mfcc(y=y.numpy().flatten(), sr=sr, n_mfcc=13).mean(axis=1).reshape(1, -1)
287
- return "Speech"
288
- except Exception:
289
- return "Unknown"
290
-
291
- # === Session Log Generator ===
292
- def generate_session_log(audio_path, effects, isolate_vocals, export_format, genre):
293
- log = {
294
- "timestamp": str(datetime.datetime.now()),
295
- "filename": os.path.basename(audio_path),
296
- "effects_applied": effects,
297
- "isolate_vocals": isolate_vocals,
298
- "export_format": export_format,
299
- "detected_genre": genre
300
  }
301
- return json.dumps(log, indent=2)
302
-
303
- # === Presets ===
304
- preset_choices = {
305
- "Default": [],
306
- "Clean Podcast": ["Noise Reduction", "Normalize"],
307
- "Podcast Mastered": ["Noise Reduction", "Normalize", "Compress Dynamic Range"],
308
- "Radio Ready": ["Bass Boost", "Treble Boost", "Limiter"],
309
- "Music Production": ["Reverb", "Stereo Widening", "Pitch Shift"],
310
- "ASMR Creator": ["Noise Gate", "Auto Gain", "Low-Pass Filter"],
311
- "Voiceover Pro": ["Vocal Isolation", "TTS", "EQ Match"],
312
- "8-bit Retro": ["Bitcrusher", "Echo", "Mono Downmix"],
313
- "🎙 Clean Vocal": ["Noise Reduction", "Normalize", "High Pass Filter (80Hz)"],
314
- "🧪 Vocal Distortion": ["Vocal Distortion", "Reverb", "Compress Dynamic Range"],
315
- "🎶 Singer's Harmony": ["Harmony", "Stereo Widening", "Pitch Shift"],
316
- "🌫 ASMR Vocal": ["Auto Gain", "Low-Pass Filter (3000Hz)", "Noise Gate"],
317
- "🎼 Stage Mode": ["Reverb", "Bass Boost", "Limiter"],
318
- "🎵 Auto-Tune Style": ["Pitch Shift (+1 semitone)", "Normalize", "Treble Boost"],
319
- "🎤 R&B Vocal": ["Noise Reduction", "Bass Boost (100-300Hz)", "Treble Boost (2000-4000Hz)"],
320
- "💃 Soul Vocal": ["Noise Reduction", "Bass Boost (80-200Hz)", "Treble Boost (1500-3500Hz)"],
321
- "🕺 Funk Groove": ["Bass Boost (80-200Hz)", "Treble Boost (1000-3000Hz)"]
322
- }
323
-
324
- preset_names = list(preset_choices.keys())
325
-
326
- # === Batch Processing Function ===
327
- def batch_process_audio(files, selected_effects, isolate_vocals, preset_name, export_format):
328
- status = "🔊 Loading files..."
329
- try:
330
- output_dir = tempfile.mkdtemp()
331
- results = []
332
- session_logs = []
333
-
334
- for file in files:
335
- processed_path, _, log, _, _ = process_audio(file.name, selected_effects, isolate_vocals, preset_name, export_format)[0:5]
336
- results.append(processed_path)
337
- session_logs.append(log)
338
-
339
- zip_path = os.path.join(tempfile.gettempdir(), "batch_output.zip")
340
- with zipfile.ZipFile(zip_path, 'w') as zipf:
341
- for i, res in enumerate(results):
342
- filename = f"processed_{i}.{export_format.lower()}"
343
- zipf.write(res, filename)
344
- zipf.writestr(f"session_info_{i}.json", session_logs[i])
345
-
346
- return zip_path, "📦 ZIP created successfully!"
347
-
348
- except Exception as e:
349
- return None, f"❌ Batch processing failed: {str(e)}"
350
-
351
- # === Vocal Pitch Correction – Auto-Tune Style ===
352
- def auto_tune_vocal(audio_path, target_key="C"):
353
- try:
354
- audio = AudioSegment.from_file(audio_path)
355
- semitones = key_to_semitone(target_key)
356
- tuned_audio = apply_pitch_shift(audio, semitones)
357
- out_path = os.path.join(tempfile.gettempdir(), "autotuned_output.wav")
358
- tuned_audio.export(out_path, format="wav")
359
- return out_path
360
- except Exception as e:
361
- print(f"Auto-Tune Error: {e}")
362
- return None
363
-
364
- def key_to_semitone(key="C"):
365
- keys = {"C": 0, "C#": 1, "D": 2, "D#": 3, "E": 4, "F": 5,
366
- "F#": 6, "G": 7, "G#": 8, "A": 9, "A#": 10, "B": 11}
367
- return keys.get(key, 0)
368
-
369
- # === Apply Effects to Stems ===
370
- def apply_effects_to_stem(stem_path, selected_effects):
371
- try:
372
- audio = AudioSegment.from_file(stem_path)
373
- effect_map_real = {
374
- "Noise Reduction": apply_noise_reduction,
375
- "Normalize": apply_normalize,
376
- "Add Reverb": apply_reverb,
377
- "Bass Boost": apply_bass_boost,
378
- "Treble Boost": apply_treble_boost,
379
- "Stereo Widening": apply_stereo_widen,
380
- "Limiter": lambda x: apply_limiter(x, limit_dB=-1),
381
- "Compress Dynamic Range": apply_compression,
382
- "Vocal Distortion": lambda x: apply_vocal_distortion(x),
383
- "Stage Mode": apply_stage_mode
384
- }
385
-
386
- for effect_name in selected_effects:
387
- if effect_name in effect_map_real:
388
- audio = effect_map_real[effect_name](audio)
389
-
390
- out_path = os.path.join(tempfile.gettempdir(), f"remixed_{Path(stem_path).stem}_processed.wav")
391
- audio.export(out_path, format="wav")
392
- return out_path
393
-
394
- except Exception as e:
395
- print(f"Error applying effects: {e}")
396
- return None
397
-
398
- # === Live Stream Preview ===
399
- def live_effect_preview(stream, selected_effect):
400
- try:
401
- samples, sr = stream
402
- audio = array_to_audiosegment(samples, sr, channels=1)
403
- effect_map_real = {
404
- "Reverb": apply_reverb,
405
- "Pitch Shift": lambda x: apply_pitch_shift(x),
406
- "Saturation": lambda x: harmonic_saturation(x, saturation_type="Tube", intensity=0.2),
407
- "Normalize": apply_normalize
408
- }
409
-
410
- if selected_effect in effect_map_real:
411
- processed = effect_map_real[selected_effect](audio)
412
- else:
413
- processed = audio
414
-
415
- out_path = os.path.join(tempfile.gettempdir(), "live_processed.wav")
416
- processed.export(out_path, format="wav")
417
- return out_path
418
-
419
- except Exception as e:
420
- return None
421
-
422
- # === Voice Command Parsing ===
423
- def voice_to_effect(command):
424
- command = command.lower()
425
- if "noise reduction" in command or "remove noise" in command:
426
- return ["Noise Reduction", "Normalize"]
427
- elif "bass" in command:
428
- return ["Bass Boost"]
429
- elif "treble" in command:
430
- return ["Treble Boost"]
431
- elif "echo" in command:
432
- return ["Echo"]
433
- elif "pitch shift" in command or "tune" in command:
434
- return ["Pitch Shift"]
435
- elif "reverb" in command:
436
- return ["Reverb"]
437
- else:
438
- return ["Noise Reduction"]
439
-
440
- # === AI Suggest Effects Based on Genre ===
441
- def suggest_by_genre(audio_path):
442
- genre = detect_genre(audio_path)
443
- return preset_choices.get(genre, [])
444
-
445
- # === Time-Stretch & BPM Match ===
446
- def stretch_to_bpm(audio_path, target_bpm=128):
447
- y, sr = torchaudio.load(audio_path)
448
- y_np = y.numpy().flatten()
449
- tempo, _ = librosa.beat.beat_track(y=y_np, sr=sr)
450
- ratio = target_bpm / tempo
451
- stretched = librosa.effects.time_stretch(y_np, ratio)
452
- out_path = os.path.join(tempfile.gettempdir(), "stretched_output.wav")
453
- sf.write(out_path, stretched, sr, format="WAV")
454
- return out_path
455
-
456
- # === Harmonic Saturation / Exciter – Now Included ===
457
- def harmonic_saturation(audio, saturation_type="Tube", intensity=0.2):
458
- samples = np.array(audio.get_array_of_samples()).astype(np.float32)
459
-
460
- if saturation_type == "Tube":
461
- saturated = np.tanh(intensity * samples)
462
- elif saturation_type == "Tape":
463
- saturated = np.where(samples > 0, 1 - np.exp(-intensity * samples), -1 + np.exp(intensity * samples))
464
- elif saturation_type == "Console":
465
- saturated = np.clip(samples, -32768, 32768) * intensity
466
- elif saturation_type == "Mix Bus":
467
- saturated = np.log1p(np.abs(samples)) * np.sign(samples) * intensity
468
- else:
469
- saturated = samples
470
-
471
- return array_to_audiosegment(saturated.astype(np.int16), audio.frame_rate, channels=audio.channels)
472
-
473
- # === A/B Compare Two Tracks ===
474
- def compare_ab(track1_path, track2_path):
475
- return track1_path, track2_path
476
-
477
- # === Loop Section ===
478
- def loop_section(audio_path, start_ms, end_ms, loops=2):
479
- audio = AudioSegment.from_file(audio_path)
480
- section = audio[start_ms:end_ms]
481
- looped = section * loops
482
- out_path = os.path.join(tempfile.gettempdir(), "looped_output.wav")
483
- looped.export(out_path, format="wav")
484
- return out_path
485
-
486
- # === Save/Load Mix Session (.aiproj) – Added Back ===
487
- def save_project(audio, preset, effects):
488
- project_data = {
489
- "audio": AudioSegment.from_file(audio).raw_data,
490
- "preset": preset,
491
- "effects": effects
492
  }
493
- out_path = os.path.join(tempfile.gettempdir(), "project.aiproj")
494
- with open(out_path, "wb") as f:
495
- pickle.dump(project_data, f)
496
- return out_path
497
-
498
- def load_project(project_file):
499
- with open(project_file.name, "rb") as f:
500
- data = pickle.load(f)
501
- return data["preset"], data["effects"]
502
-
503
- # === Prompt-Based Editing Tab – Added Back ===
504
- def process_prompt(audio, prompt):
505
- return apply_noise_reduction(audio)
506
 
507
- # === Vocal Formant Correction (AI Voice Tuning) ===
508
- def formant_correct(audio, shift=1.0):
509
- samples, sr = audiosegment_to_array(audio)
510
- corrected = librosa.effects.pitch_shift(samples, sr=sr, n_steps=shift)
511
- return array_to_audiosegment(corrected.astype(np.int16), sr, channels=audio.channels)
512
-
513
- # === DAW Template Export ===
514
- def generate_ableton_template(stems):
515
- template = {
516
- "format": "Ableton Live",
517
- "stems": [os.path.basename(s) for s in stems],
518
- "effects": ["Reverb", "EQ", "Compression"],
519
- "tempo": 128,
520
- "title": "Studio Pulse Project"
521
- }
522
- out_path = os.path.join(tempfile.gettempdir(), "ableton_template.json")
523
- with open(out_path, "w") as f:
524
- json.dump(template, f, indent=2)
525
- return out_path
526
-
527
- # === Multi-stem ZIP Export ===
528
- def export_full_mix(stems, final_mix):
529
- zip_path = os.path.join(tempfile.gettempdir(), "full_export.zip")
530
- with zipfile.ZipFile(zip_path, "w") as zipf:
531
- for i, stem in enumerate(stems):
532
- zipf.write(stem, f"stem_{i}.wav")
533
- zipf.write(final_mix, "final_mix.wav")
534
- return zip_path
535
-
536
- # === AI Sound Design (Text-to-Sound) ===
537
- def text_to_sound(prompt):
538
- tts = TTS(model="tts_models/en/vctk/vits")
539
- out_path = os.path.join(tempfile.gettempdir(), "generated_sound.wav")
540
- tts.tts_to_file(text=prompt, speaker="p225", file_path=out_path)
541
- return out_path
542
-
543
- # === Voice Cloning via OpenVoice (Simulated) ===
544
- def clone_voice(source_audio, reference_audio):
545
- source = AudioSegment.from_file(source_audio)
546
- ref = AudioSegment.from_file(reference_audio)
547
- mixed = source.overlay(ref - 10)
548
- out_path = os.path.join(tempfile.gettempdir(), "cloned_output.wav")
549
- mixed.export(out_path, format="wav")
550
- return out_path
551
-
552
- # === AI Remastering – Now Fixed! ===
553
- def ai_remaster(audio_path):
554
- try:
555
- audio = AudioSegment.from_file(audio_path)
556
- samples, sr = audiosegment_to_array(audio)
557
- reduced = nr.reduce_noise(y=samples, sr=sr)
558
- cleaned = array_to_audiosegment(reduced, sr, channels=audio.channels)
559
- cleaned_wav_path = os.path.join(tempfile.gettempdir(), "cleaned.wav")
560
- cleaned.export(cleaned_wav_path, format="wav")
561
- isolated_path = apply_vocal_isolation(cleaned_wav_path)
562
- final_path = ai_mastering_chain(isolated_path, genre="Pop", target_lufs=-14.0)
563
- return final_path
564
- except Exception as e:
565
- print(f"Remastering Error: {str(e)}")
566
- return None
567
-
568
- def ai_mastering_chain(audio_path, genre="Pop", target_lufs=-14.0):
569
- audio = AudioSegment.from_file(audio_path)
570
- audio = auto_eq(audio, genre=genre)
571
- audio = match_loudness(audio_path, target_lufs=target_lufs)
572
- audio = apply_stereo_widen(audio, pan_amount=0.3)
573
- out_path = os.path.join(tempfile.gettempdir(), "mastered_output.wav")
574
- audio.export(out_path, format="wav")
575
- return out_path
576
-
577
- def process_audio(audio_path, genre="Pop", target_lufs=-14.0):
578
- # Your existing processing logic here
579
- return mastered_audio_path, waveform_image, session_log_json
580
-
581
- with gr.Blocks(title="Studio Pulse") as demo:
582
- gr.Interface(fn=process_audio,
583
- inputs=[
584
- gr.Audio(label="Upload Track", type="filepath"),
585
- gr.Textbox(label="Genre", value="Pop"),
586
- gr.Number(label="Target LUFS", value=-14.0)
587
- ],
588
- outputs=[
589
- gr.Audio(label="Mastered Track", type="filepath"),
590
- gr.Image(label="Waveform"),
591
- gr.Textbox(label="Session Log")
592
- ])
593
-
594
- demo.queue()
595
- app = demo.app
596
-
597
- # === Generate PDF Report – Safely Wrapped ===
598
- pdf_available = False
599
- try:
600
- from fpdf import FPDF
601
- pdf_available = True
602
- except ImportError:
603
- pass
604
-
605
- if pdf_available:
606
- class PDFReport(FPDF):
607
- def header(self):
608
- self.set_font('Arial', 'B', 12)
609
- self.cell(0, 10, 'Studio Pulse AI - Session Report', ln=True, align='C')
610
-
611
- def export_session_report(session_data):
612
- pdf = PDFReport()
613
- pdf.add_page()
614
- pdf.set_font("Arial", size=10)
615
- pdf.multi_cell(0, 10, txt=session_data)
616
- out_path = os.path.join(tempfile.gettempdir(), "session_report.pdf")
617
- pdf.output(out_path)
618
- return out_path
619
- else:
620
- def export_session_report(session_data):
621
- return None
622
-
623
- # === Main UI – With Studio Pulse Branding ===
624
- with gr.Blocks(css="""
625
- body {
626
- font-family: 'Segoe UI', sans-serif;
627
- background-color: #1f2937;
628
- color: white;
629
- padding: 20px;
630
- }
631
-
632
- .studio-header {
633
- text-align: center;
634
- margin-bottom: 30px;
635
- animation: float 3s ease-in-out infinite;
636
- }
637
-
638
- @keyframes float {
639
- 0%, 100% { transform: translateY(0); }
640
- 50% { transform: translateY(-10px); }
641
- }
642
-
643
- .gr-button {
644
- background-color: #2563eb !important;
645
- color: white !important;
646
- border-radius: 10px;
647
- padding: 10px 20px;
648
- font-weight: bold;
649
- box-shadow: 0 0 10px #2563eb44;
650
- border: none;
651
- }
652
-
653
- .gr-button:hover {
654
- background-color: #3b82f6 !important;
655
- box-shadow: 0 0 15px #3b82f6aa;
656
- }
657
-
658
- input[type="text"], input[type="number"], select, textarea {
659
- background-color: #334155 !important;
660
- color: white !important;
661
- border: 1px solid #475569 !important;
662
- width: 100%;
663
- padding: 10px;
664
- }
665
-
666
- .gr-checkboxgroup label {
667
- background: #334155;
668
- color: white;
669
- border: 1px solid #475569;
670
- border-radius: 6px;
671
- padding: 8px 12px;
672
- transition: background 0.3s;
673
- }
674
-
675
- .gr-checkboxgroup label:hover {
676
- background: #475569;
677
- cursor: pointer;
678
- }
679
-
680
- .gr-gallery__items > div {
681
- border-radius: 12px;
682
- overflow: hidden;
683
- transition: transform 0.3s ease, box-shadow 0.3s ease;
684
  }
685
-
686
- .gr-gallery__items > div:hover {
687
- transform: scale(1.02);
688
- box-shadow: 0 0 12px #2563eb44;
 
 
 
 
689
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
690
 
691
- @media (max-width: 768px) {
692
- .gr-column {
693
- min-width: 100%;
694
- }
695
-
696
- .gr-row {
697
- flex-direction: column;
698
- }
699
-
700
- .studio-header img {
701
- width: 90%;
702
- }
703
-
704
- .gr-button {
705
- width: 100%;
706
- }
707
  }
708
- """) as demo:
709
-
710
- # Header
711
- gr.HTML('''
712
- <div class="studio-header">
713
- <img src="logo.png" width="400" />
714
- <h3>Where Your Audio Meets Intelligence</h3>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
715
  </div>
716
- ''')
717
-
718
- gr.Markdown("### Upload, edit, export — powered by AI!")
719
-
720
- # --- Single File Studio Tab ---
721
- with gr.Tab("🎵 Single File Studio"):
722
- with gr.Row():
723
- with gr.Column(min_width=300):
724
- input_audio = gr.Audio(label="Upload Audio", type="filepath")
725
- effect_checkbox = gr.CheckboxGroup(choices=preset_choices["Default"], label="Apply Effects in Order")
726
- preset_dropdown = gr.Dropdown(choices=preset_names, label="Select Preset", value=preset_names[0])
727
- export_format = gr.Dropdown(choices=["MP3", "WAV"], label="Export Format", value="MP3")
728
- isolate_vocals = gr.Checkbox(label="Isolate Vocals After Effects")
729
- submit_btn = gr.Button("Process Audio")
730
- with gr.Column(min_width=300):
731
- output_audio = gr.Audio(label="Processed Audio", type="filepath")
732
- waveform_img = gr.Image(label="Waveform Preview")
733
- session_log_out = gr.Textbox(label="Session Log", lines=5)
734
- genre_out = gr.Textbox(label="Detected Genre", lines=1)
735
- status_box = gr.Textbox(label="Status", value="✅ Ready", lines=1)
736
-
737
- submit_btn.click(fn=process_audio, inputs=[
738
- input_audio, effect_checkbox, isolate_vocals, preset_dropdown, export_format
739
- ], outputs=[
740
- output_audio, waveform_img, session_log_out, genre_out, status_box
741
- ])
742
-
743
- # --- Remix Mode – Stem Splitting + Per-Stem Effects ===
744
- with gr.Tab("🎛 Remix Mode"):
745
- with gr.Row():
746
- with gr.Column(min_width=200):
747
- input_audio_remix = gr.Audio(label="Upload Music Track", type="filepath")
748
- split_button = gr.Button("Split Into Drums, Bass, Vocals, etc.")
749
- with gr.Column(min_width=400):
750
- stem_outputs = [
751
- gr.File(label="Vocals"),
752
- gr.File(label="Drums"),
753
- gr.File(label="Bass"),
754
- gr.File(label="Other")
755
- ]
756
-
757
- split_button.click(fn=stem_split, inputs=[input_audio_remix], outputs=stem_outputs)
758
-
759
- gr.Markdown("#### Apply Effects to Individual Stems")
760
- with gr.Row():
761
- with gr.Column(min_width=200):
762
- vocals_path = gr.File(label="Vocals Track")
763
- vocal_effects = gr.CheckboxGroup([
764
- "Noise Reduction",
765
- "Normalize",
766
- "Bass Boost",
767
- "Treble Boost",
768
- "Reverb",
769
- "Vocal Distortion",
770
- "Auto Gain"
771
- ])
772
- btn_vocals = gr.Button("Process Vocals")
773
- output_vocals = gr.Audio(label="Processed Vocals", type="filepath")
774
- btn_vocals.click(fn=apply_effects_to_stem, inputs=[vocals_path, vocal_effects], outputs=output_vocals)
775
-
776
- with gr.Column(min_width=200):
777
- drums_path = gr.File(label="Drums Track")
778
- drum_effects = gr.CheckboxGroup([
779
- "Bass Boost",
780
- "Compress Dynamic Range",
781
- "Limiter",
782
- "Bitcrusher",
783
- "Stereo Widening"
784
- ])
785
- btn_drums = gr.Button("Process Drums")
786
- output_drums = gr.Audio(label="Processed Drums", type="filepath")
787
- btn_drums.click(fn=apply_effects_to_stem, inputs=[drums_path, drum_effects], outputs=output_drums)
788
-
789
- with gr.Column(min_width=200):
790
- bass_path = gr.File(label="Bass Track")
791
- bass_effects = gr.CheckboxGroup([
792
- "Bass Boost",
793
- "Saturation (Tape)",
794
- "Limiter"
795
- ])
796
- btn_bass = gr.Button("Process Bass")
797
- output_bass = gr.Audio(label="Processed Bass", type="filepath")
798
- btn_bass.click(fn=apply_effects_to_stem, inputs=[bass_path, bass_effects], outputs=output_bass)
799
-
800
- with gr.Column(min_width=200):
801
- other_path = gr.File(label="Other Track")
802
- other_effects = gr.CheckboxGroup([
803
- "Noise Gate",
804
- "Reverb",
805
- "Treble Boost"
806
- ])
807
- btn_other = gr.Button("Process Other")
808
- output_other = gr.Audio(label="Processed Other", type="filepath")
809
- btn_other.click(fn=apply_effects_to_stem, inputs=[other_path, other_effects], outputs=output_other)
810
-
811
- # --- AI Remastering Tab – Now Fixed & Working ===
812
- with gr.Tab("🔮 AI Remastering"):
813
- gr.Interface(
814
- fn=ai_remaster,
815
- inputs=gr.Audio(label="Upload Low-Quality Recording", type="filepath"),
816
- outputs=gr.Audio(label="Studio-Grade Output", type="filepath"),
817
- title="Transform Low-Quality Recordings to Studio Sound",
818
- description="Uses noise reduction, vocal isolation, and mastering to enhance old recordings."
819
- )
820
-
821
- # --- Harmonic Saturation / Exciter – Now Included ===
822
- with gr.Tab("🧬 Harmonic Saturation"):
823
- gr.Interface(
824
- fn=harmonic_saturation,
825
- inputs=[
826
- gr.Audio(label="Upload Track", type="filepath"),
827
- gr.Dropdown(choices=["Tube", "Tape", "Console", "Mix Bus"], label="Saturation Type", value="Tube"),
828
- gr.Slider(minimum=0.1, maximum=1.0, value=0.2, label="Intensity")
829
- ],
830
- outputs=gr.Audio(label="Warm Output", type="filepath"),
831
- title="Add Analog-Style Warmth",
832
- description="Enhance clarity and presence using saturation styles like Tube or Tape.",
833
- allow_flagging="never"
834
- )
835
-
836
- # --- Vocal Doubler / Harmonizer – Added ===
837
- with gr.Tab("🎧 Vocal Doubler / Harmonizer"):
838
- gr.Interface(
839
- fn=lambda x: apply_harmony(x),
840
- inputs=gr.Audio(label="Upload Vocal Clip", type="filepath"),
841
- outputs=gr.Audio(label="Doubled Output", type="filepath"),
842
- title="Add Vocal Doubling / Harmony",
843
- description="Enhance vocals with doubling or harmony"
844
- )
845
-
846
- # --- Batch Processing – Full Support ===
847
- with gr.Tab("🔊 Batch Processing"):
848
- gr.Interface(
849
- fn=batch_process_audio,
850
- inputs=[
851
- gr.File(label="Upload Multiple Files", file_count="multiple"),
852
- gr.CheckboxGroup(choices=preset_choices["Default"], label="Apply Effects in Order"),
853
- gr.Checkbox(label="Isolate Vocals After Effects"),
854
- gr.Dropdown(choices=preset_names, label="Select Preset", value=preset_names[0]),
855
- gr.Dropdown(choices=["MP3", "WAV"], label="Export Format", value="MP3")
856
- ],
857
- outputs=[
858
- gr.File(label="Download ZIP of All Processed Files"),
859
- gr.Textbox(label="Status", value="✅ Ready", lines=1)
860
- ],
861
- title="Batch Audio Processor",
862
- description="Upload multiple files, apply effects in bulk, and download all results in a ZIP.",
863
- flagging_mode="never",
864
- submit_btn="Process All Files"
865
- )
866
-
867
- # --- Vocal Pitch Correction – Auto-Tune Style ===
868
- with gr.Tab("🎤 AI Auto-Tune"):
869
- gr.Interface(
870
- fn=auto_tune_vocal,
871
- inputs=[
872
- gr.File(label="Source Voice Clip"),
873
- gr.Textbox(label="Target Key", value="C", lines=1)
874
- ],
875
- outputs=gr.Audio(label="Pitch-Corrected Output", type="filepath"),
876
- title="AI Auto-Tune",
877
- description="Correct vocal pitch automatically using AI"
878
- )
879
-
880
- # --- Frequency Spectrum Tab – Real-time Visualizer ===
881
- def visualize_spectrum(audio_path):
882
- y, sr = torchaudio.load(audio_path)
883
- y_np = y.numpy().flatten()
884
- stft = librosa.stft(y_np)
885
- db = librosa.amplitude_to_db(abs(stft))
886
- plt.figure(figsize=(10, 4))
887
- img = librosa.display.specshow(db, sr=sr, x_axis="time", y_axis="hz", cmap="magma")
888
- plt.colorbar(img, format="%+2.0f dB")
889
- plt.title("Frequency Spectrum")
890
- plt.tight_layout()
891
- buf = BytesIO()
892
- plt.savefig(buf, format="png")
893
- plt.close()
894
- buf.seek(0)
895
- return Image.open(buf)
896
-
897
- with gr.Tab("📊 Frequency Spectrum"):
898
- gr.Interface(
899
- fn=visualize_spectrum,
900
- inputs=gr.Audio(label="Upload Track", type="filepath"),
901
- outputs=gr.Image(label="Spectrum Analysis")
902
- )
903
-
904
- # --- Loudness Graph Tab – EBU R128 Matching ===
905
- with gr.Tab("📈 Loudness Graph"):
906
- gr.Interface(
907
- fn=match_loudness,
908
- inputs=[
909
- gr.Audio(label="Upload Track", type="filepath"),
910
- gr.Slider(minimum=-24, maximum=-6, value=-14, label="Target LUFS")
911
- ],
912
- outputs=gr.Audio(label="Normalized Output", type="filepath"),
913
- title="Match Loudness Across Tracks",
914
- description="Ensure consistent volume using EBU R128 standard"
915
- )
916
-
917
- # --- Save/Load Mix Session (.aiproj) – Added Back ===
918
- with gr.Tab("📁 Save/Load Project"):
919
- with gr.Row():
920
- with gr.Column(min_width=300):
921
- gr.Interface(
922
- fn=save_project,
923
- inputs=[
924
- gr.File(label="Original Audio"),
925
- gr.Dropdown(choices=preset_names, label="Used Preset", value=preset_names[0]),
926
- gr.CheckboxGroup(choices=preset_choices["Default"], label="Applied Effects")
927
- ],
928
- outputs=gr.File(label="Project File (.aiproj)")
929
- )
930
- with gr.Column(min_width=300):
931
- gr.Interface(
932
- fn=load_project,
933
- inputs=gr.File(label="Upload .aiproj File"),
934
- outputs=[
935
- gr.Dropdown(choices=preset_names, label="Loaded Preset"),
936
- gr.CheckboxGroup(choices=preset_choices["Default"], label="Loaded Effects")
937
- ],
938
- title="Resume Last Project",
939
- description="Load your saved session"
940
- )
941
-
942
- # --- Prompt-Based Editing Tab – Added Back ===
943
- with gr.Tab("🧠 Prompt-Based Editing"):
944
- gr.Interface(
945
- fn=process_prompt,
946
- inputs=[
947
- gr.File(label="Upload Audio", type="filepath"),
948
- gr.Textbox(label="Describe What You Want", lines=5)
949
- ],
950
- outputs=gr.Audio(label="Edited Output", type="filepath"),
951
- title="Type Your Edits – AI Does the Rest",
952
- description="Say what you want done and let AI handle it.",
953
- allow_flagging="never"
954
- )
955
-
956
- # --- Vocal Presets for Singers – Added Back ===
957
- with gr.Tab("🎤 Vocal Presets for Singers"):
958
- gr.Interface(
959
- fn=process_audio,
960
- inputs=[
961
- gr.Audio(label="Upload Vocal Track", type="filepath"),
962
- gr.CheckboxGroup(choices=[
963
- "Noise Reduction",
964
- "Normalize",
965
- "Compress Dynamic Range",
966
- "Bass Boost",
967
- "Treble Boost",
968
- "Reverb",
969
- "Auto Gain",
970
- "Vocal Distortion",
971
- "Stage Mode"
972
- ]),
973
- gr.Checkbox(label="Isolate Vocals After Effects"),
974
- gr.Dropdown(choices=preset_names, label="Select Vocal Preset", value=preset_names[0]),
975
- gr.Dropdown(choices=["MP3", "WAV"], label="Export Format", value="MP3")
976
- ],
977
- outputs=[
978
- gr.Audio(label="Processed Vocal", type="filepath"),
979
- gr.Image(label="Waveform Preview"),
980
- gr.Textbox(label="Session Log (JSON)", lines=5),
981
- gr.Textbox(label="Detected Genre", lines=1),
982
- gr.Textbox(label="Status", value="✅ Ready", lines=1)
983
- ],
984
- title="Create Studio-Quality Vocal Tracks",
985
- description="Apply singer-friendly presets and effects to enhance vocals.",
986
- allow_flagging="never"
987
- )
988
-
989
- # --- Real-Time Streaming Preview ===
990
- with gr.Tab("🎧 Real-Time Preview"):
991
- gr.Interface(
992
- fn=live_effect_preview,
993
- inputs=[
994
- gr.Audio(sources=["microphone"], streaming=True, label="Live Mic Input"),
995
- gr.Dropdown(choices=["Normalize", "Reverb", "Pitch Shift", "Saturation"], label="Effect", value="Normalize")
996
- ],
997
- outputs=gr.Audio(label="Live Output", type="filepath"),
998
- title="Preview Effects in Real-Time",
999
- description="Try effects live before exporting"
1000
- )
1001
-
1002
- # --- Custom EQ Editor ===
1003
- with gr.Tab("🎛 Custom EQ Editor"):
1004
- gr.Interface(
1005
- fn=auto_eq,
1006
- inputs=[
1007
- gr.Audio(label="Upload Track", type="filepath"),
1008
- gr.Dropdown(choices=["Pop", "EDM", "Rock", "Hip-Hop", "Acoustic", "Metal", "Trap", "LoFi",
1009
- "Jazz", "Classical", "Chillhop", "Ambient", "Jazz Piano", "Trap EDM",
1010
- "Indie Rock", "Lo-Fi Jazz", "R&B", "Soul", "Funk"],
1011
- label="Genre", value="Pop")
1012
- ],
1013
- outputs=gr.Audio(label="EQ-Enhanced Output", type="filepath"),
1014
- title="Custom EQ by Genre",
1015
- description="Apply custom EQ based on genre"
1016
- )
1017
-
1018
- # --- Time-Stretch & BPM Match ===
1019
- with gr.Tab("⏱ Time-Stretch & BPM Match"):
1020
- gr.Interface(
1021
- fn=stretch_to_bpm,
1022
- inputs=[
1023
- gr.Audio(label="Upload Track", type="filepath"),
1024
- gr.Slider(minimum=60, maximum=200, value=128, label="Target BPM")
1025
- ],
1026
- outputs=gr.Audio(label="Stretched Output", type="filepath"),
1027
- title="Match Track to BPM",
1028
- description="Stretch or shrink audio to match a specific tempo"
1029
- )
1030
-
1031
- # --- A/B Compare ===
1032
- with gr.Tab("🎯 A/B Compare"):
1033
- gr.Interface(
1034
- fn=compare_ab,
1035
- inputs=[
1036
- gr.Audio(label="Version A", type="filepath"),
1037
- gr.Audio(label="Version B", type="filepath")
1038
- ],
1039
- outputs=[
1040
- gr.Audio(label="Version A", type="filepath"),
1041
- gr.Audio(label="Version B", type="filepath")
1042
- ],
1043
- title="Compare Two Versions",
1044
- description="Hear two mixes side-by-side",
1045
- allow_flagging="never"
1046
- )
1047
-
1048
- # --- Loop Playback ===
1049
- with gr.Tab("🔁 Loop Playback"):
1050
- gr.Interface(
1051
- fn=loop_section,
1052
- inputs=[
1053
- gr.Audio(label="Upload Track", type="filepath"),
1054
- gr.Slider(minimum=0, maximum=30000, step=100, value=5000, label="Start MS"),
1055
- gr.Slider(minimum=100, maximum=30000, step=100, value=10000, label="End MS"),
1056
- gr.Slider(minimum=1, maximum=10, value=2, label="Repeat Loops")
1057
- ],
1058
- outputs=gr.Audio(label="Looped Output", type="filepath"),
1059
- title="Repeat a Section",
1060
- description="Useful for editing a specific part"
1061
- )
1062
-
1063
- # --- Share Effect Chain Tab – Now Defined! ===
1064
- with gr.Tab("🔗 Share Effect Chain"):
1065
- gr.Interface(
1066
- fn=lambda x: json.dumps(x),
1067
- inputs=gr.CheckboxGroup(choices=preset_choices["Default"]),
1068
- outputs=gr.Textbox(label="Share Code", lines=2),
1069
- title="Copy/Paste Effect Chain",
1070
- description="Share your setup via link/code"
1071
- )
1072
-
1073
- with gr.Tab("📥 Load Shared Chain"):
1074
- gr.Interface(
1075
- fn=json.loads,
1076
- inputs=gr.Textbox(label="Paste Shared Code", lines=2),
1077
- outputs=gr.CheckboxGroup(choices=preset_choices["Default"], label="Loaded Effects"),
1078
- title="Restore From Shared Chain",
1079
- description="Paste shared effect chain JSON to restore settings"
1080
- )
1081
-
1082
- # --- Keyboard Shortcuts Tab ===
1083
- with gr.Tab("⌨ Keyboard Shortcuts"):
1084
- gr.Markdown("""
1085
- ### Keyboard Controls
1086
- - `Ctrl + Z`: Undo last effect
1087
- - `Ctrl + Y`: Redo
1088
- - `Spacebar`: Play/Stop playback
1089
- - `Ctrl + S`: Save current session
1090
- - `Ctrl + O`: Open session
1091
- - `Ctrl + C`: Copy effect chain
1092
- - `Ctrl + V`: Paste effect chain
1093
- - `Ctrl + Shift + L`: Loop selection
1094
- - `Ctrl + Shift + P`: Export PDF report
1095
- - `Ctrl + Shift + M`: Export full mix ZIP
1096
- """)
1097
-
1098
- # --- Vocal Formant Correction – Now Defined! ===
1099
- with gr.Tab("🧑‍🎤 Vocal Formant Correction"):
1100
- gr.Interface(
1101
- fn=formant_correct,
1102
- inputs=[
1103
- gr.Audio(label="Upload Vocal Track", type="filepath"),
1104
- gr.Slider(minimum=-2, maximum=2, value=1.0, label="Formant Shift")
1105
- ],
1106
- outputs=gr.Audio(label="Natural-Sounding Vocal", type="filepath"),
1107
- title="Preserve Vocal Quality During Pitch Shift",
1108
- description="Make pitch-shifted vocals sound more human"
1109
- )
1110
-
1111
- # --- Voice Swap / Cloning – New Tab ===
1112
- with gr.Tab("🔁 Voice Swap / Cloning"):
1113
- gr.Interface(
1114
- fn=clone_voice,
1115
- inputs=[
1116
- gr.File(label="Source Voice Clip"),
1117
- gr.File(label="Reference Voice")
1118
- ],
1119
- outputs=gr.Audio(label="Converted Output", type="filepath"),
1120
- title="Swap Voices Using AI",
1121
- description="Clone or convert voice from one to another"
1122
- )
1123
 
1124
- # --- DAW Template Export – Now Included ===
1125
- with gr.Tab("🎛 DAW Template Export"):
1126
- gr.Interface(
1127
- fn=generate_ableton_template,
1128
- inputs=[gr.File(label="Upload Stems", file_count="multiple")],
1129
- outputs=gr.File(label="DAW Template (.json/.als/.flp)")
1130
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1131
 
1132
- # --- Export Full Mix ZIP – Added Back ===
1133
- with gr.Tab("📁 Export Full Mix ZIP"):
1134
- gr.Interface(
1135
- fn=export_full_mix,
1136
- inputs=[
1137
- gr.File(label="Stems", file_count="multiple"),
1138
- gr.File(label="Final Mix")
1139
- ],
1140
- outputs=gr.File(label="Full Mix Archive (.zip)"),
1141
- title="Export Stems + Final Mix Together",
1142
- description="Perfect for sharing with producers or archiving"
1143
- )
 
 
 
 
 
 
 
 
 
 
 
1144
 
1145
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use client";
2
+
3
+ import { useState, useRef, useEffect } from "react";
4
+ import {
5
+ Card,
6
+ CardContent,
7
+ CardHeader,
8
+ CardTitle,
9
+ CardDescription,
10
+ } from "@/components/ui/card";
11
+ import {
12
+ Tabs,
13
+ TabsContent,
14
+ TabsList,
15
+ TabsTrigger,
16
+ } from "@/components/ui/tabs";
17
+ import {
18
+ Select,
19
+ SelectContent,
20
+ SelectItem,
21
+ SelectTrigger,
22
+ SelectValue,
23
+ } from "@/components/ui/select";
24
+ import { Slider } from "@/components/ui/slider";
25
+ import { Switch } from "@/components/ui/switch";
26
+ import { Label } from "@/components/ui/label";
27
+ import { Badge } from "@/components/ui/badge";
28
+ import { Button } from "@/components/ui/button";
29
+ import { toast } from "@/components/ui/use-toast";
30
+ import {
31
+ Upload as UploadIcon,
32
+ BarChart3 as BarChart3Icon,
33
+ Sliders as SlidersIcon,
34
+ RefreshCw as RefreshCwIcon,
35
+ Music as MusicIcon,
36
+ Headphones as HeadphonesIcon,
37
+ Settings as SettingsIcon,
38
+ Save as SaveIcon,
39
+ Loader2 as Loader2Icon,
40
+ ArrowLeft,
41
+ Home,
42
+ } from "lucide-react";
43
+ import { useRouter } from "next/navigation";
44
+ import { DownloadAudioButton } from "@/components/download-audio-button";
45
+
46
+ // 🔗 Your Hugging Face Space URL
47
+ const HF_SPACE_URL = "https://tee342-audiomaster.hf.space";
48
+
49
+ // 🎛 Mastering Presets
50
+ const masteringPresets = {
51
+ pop: {
52
+ lowGain: 2.0,
53
+ lowMidGain: 0.5,
54
+ midGain: 1.0,
55
+ highMidGain: 2.0,
56
+ highGain: 1.5,
57
+ threshold: -18,
58
+ ratio: 3.0,
59
+ attack: 5,
60
+ release: 80,
61
+ knee: 8,
62
+ limiterThreshold: -2.0,
63
+ limiterRelease: 40,
64
+ outputGain: 0.5,
65
+ stereoWidth: 110,
66
+ saturation: 15,
67
+ },
68
+ rock: {
69
+ lowGain: 2.5,
70
+ lowMidGain: 0.0,
71
+ midGain: 0.5,
72
+ highMidGain: 1.5,
73
+ highGain: 2.0,
74
+ threshold: -15,
75
+ ratio: 4.0,
76
+ attack: 3,
77
+ release: 60,
78
+ knee: 6,
79
+ limiterThreshold: -1.5,
80
+ limiterRelease: 30,
81
+ outputGain: 0.0,
82
+ stereoWidth: 105,
83
+ saturation: 20,
84
+ },
85
+ electronic: {
86
+ lowGain: 3.0,
87
+ lowMidGain: 1.0,
88
+ midGain: -0.5,
89
+ highMidGain: 1.0,
90
+ highGain: 3.0,
91
+ threshold: -12,
92
+ ratio: 4.5,
93
+ attack: 2,
94
+ release: 40,
95
+ knee: 4,
96
+ limiterThreshold: -1.0,
97
+ limiterRelease: 20,
98
+ outputGain: 0.0,
99
+ stereoWidth: 120,
100
+ saturation: 25,
101
+ },
102
+ hiphop: {
103
+ lowGain: 3.5,
104
+ lowMidGain: 1.5,
105
+ midGain: -1.0,
106
+ highMidGain: 0.5,
107
+ highGain: 2.0,
108
+ threshold: -14,
109
+ ratio: 5.0,
110
+ attack: 1,
111
+ release: 50,
112
+ knee: 5,
113
+ limiterThreshold: -1.0,
114
+ limiterRelease: 30,
115
+ outputGain: 0.0,
116
+ stereoWidth: 110,
117
+ saturation: 30,
118
+ },
119
+ jazz: {
120
+ lowGain: 1.5,
121
+ lowMidGain: 1.0,
122
+ midGain: 0.5,
123
+ highMidGain: 1.0,
124
+ highGain: 1.0,
125
+ threshold: -20,
126
+ ratio: 2.0,
127
+ attack: 10,
128
+ release: 120,
129
+ knee: 10,
130
+ limiterThreshold: -3.0,
131
+ limiterRelease: 60,
132
+ outputGain: 0.5,
133
+ stereoWidth: 105,
134
+ saturation: 10,
135
+ },
136
+ classical: {
137
+ lowGain: 1.0,
138
+ lowMidGain: 0.0,
139
+ midGain: 0.0,
140
+ highMidGain: 0.5,
141
+ highGain: 1.0,
142
+ threshold: -24,
143
+ ratio: 1.5,
144
+ attack: 20,
145
+ release: 200,
146
+ knee: 15,
147
+ limiterThreshold: -3.5,
148
+ limiterRelease: 80,
149
+ outputGain: 1.0,
150
+ stereoWidth: 115,
151
+ saturation: 5,
152
+ },
153
+ acoustic: {
154
+ lowGain: 1.5,
155
+ lowMidGain: 1.0,
156
+ midGain: 0.5,
157
+ highMidGain: 0.5,
158
+ highGain: 1.0,
159
+ threshold: -20,
160
+ ratio: 2.0,
161
+ attack: 15,
162
+ release: 150,
163
+ knee: 12,
164
+ limiterThreshold: -3.0,
165
+ limiterRelease: 70,
166
+ outputGain: 0.5,
167
+ stereoWidth: 105,
168
+ saturation: 10,
169
+ },
170
+ edm: {
171
+ lowGain: 4.0,
172
+ lowMidGain: 1.0,
173
+ midGain: -1.0,
174
+ highMidGain: 1.5,
175
+ highGain: 3.5,
176
+ threshold: -10,
177
+ ratio: 5.0,
178
+ attack: 1,
179
+ release: 30,
180
+ knee: 3,
181
+ limiterThreshold: -0.5,
182
+ limiterRelease: 15,
183
+ outputGain: 0.0,
184
+ stereoWidth: 125,
185
+ saturation: 35,
186
+ },
187
+ };
188
+
189
+ type MasteringParams = typeof masteringPresets.pop;
190
+
191
+ // Default stats for comparison
192
+ const defaultAudioStats = {
193
+ rms: 0,
194
+ peak: 0,
195
+ crest: 0,
196
+ lufs: -23,
197
+ truePeak: 0,
198
+ lra: 0,
199
+ stereoWidth: 0,
200
+ lowEnergy: 0,
201
+ midEnergy: 0,
202
+ highEnergy: 0,
203
+ dynamicRange: 0,
204
+ };
205
+
206
+ export default function MasteringPage() {
207
+ const [originalAudioUrl, setOriginalAudioUrl] = useState<string | null>(null);
208
+ const [processedAudioUrl, setProcessedAudioUrl] = useState<string | null>(null);
209
+ const [fileName, setFileName] = useState("No file selected");
210
+ const [isProcessing, setIsProcessing] = useState(false);
211
+ const [activeTab, setActiveTab] = useState("player");
212
+ const [selectedPreset, setSelectedPreset] = useState("pop");
213
+ const [useCustomSettings, setUseCustomSettings] = useState(false);
214
+ const [customSettings, setCustomSettings] = useState<MasteringParams>(
215
+ masteringPresets.pop
216
+ );
217
+ const router = useRouter();
218
+
219
+ const fileInputRef = useRef<HTMLInputElement>(null);
220
+
221
+ // 🧠 Handle file selection + upload
222
+ const handleFileSelect = async (e) => {
223
+ const file = e.target.files?.[0];
224
+ if (!file) return;
225
+
226
+ const formData = new FormData();
227
+ formData.append("audio", file);
228
+ formData.append("genre", selectedPreset);
229
+ formData.append("target_lufs", "-14.0");
230
+
231
+ try {
232
+ const res = await fetch(`${HF_SPACE_URL}/api/master`, {
233
+ method: "POST",
234
+ body: formData,
235
+ });
236
+
237
+ const contentType = res.headers.get("content-type");
238
+
239
+ if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
240
+
241
+ if (contentType && contentType.includes("application/json")) {
242
+ const data = await res.json();
243
+
244
+ if (data.data && data.data.length >= 3) {
245
+ setOriginalAudioUrl(data.data[0]);
246
+ setProcessedAudioUrl(data.data[0]);
247
+ setFileName(file.name);
248
+
249
+ setOriginalStats({
250
+ rms: -18,
251
+ peak: -3.5,
252
+ crest: 14.5,
253
+ lufs: -16.8,
254
+ truePeak: -3.2,
255
+ lra: 8.4,
256
+ stereoWidth: 92,
257
+ lowEnergy: -12.5,
258
+ midEnergy: -15.2,
259
+ highEnergy: -18.7,
260
+ dynamicRange: 14.5,
261
+ });
262
+ setProcessedStats({
263
+ rms: -14,
264
+ peak: -1.2,
265
+ crest: 12.8,
266
+ lufs: -14.0,
267
+ truePeak: -1.0,
268
+ lra: 6.8,
269
+ stereoWidth: 105,
270
+ lowEnergy: -10.2,
271
+ midEnergy: -13.5,
272
+ highEnergy: -16.3,
273
+ dynamicRange: 12.8,
274
+ });
275
+
276
+ toast({
277
+ title: "File Uploaded",
278
+ description: `${file.name} is being processed.`,
279
+ });
280
  }
281
+ } else {
282
+ const text = await res.text();
283
+ console.error("Received HTML instead of JSON:", text);
284
+ toast({
285
+ title: "Server Error",
286
+ description: "Check if your Hugging Face Space is running and public.",
287
+ variant: "destructive"
288
+ });
289
+ }
290
+
291
+ } catch (error) {
292
+ console.error("Upload failed:", error);
293
+ toast({
294
+ title: "Error",
295
+ description: "Could not process audio.",
296
+ variant: "destructive",
297
+ });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
298
  }
299
+ };
300
+
301
+ // 🎚 Apply mastering settings via Hugging Face API
302
+ const applyMastering = async () => {
303
+ if (!originalAudioUrl || !fileInputRef.current?.files?.[0]) {
304
+ toast({
305
+ title: "No Audio Selected",
306
+ description: "Please upload an audio file first.",
307
+ variant: "destructive",
308
+ });
309
+ return;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
310
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
311
 
312
+ setIsProcessing(true);
313
+ const file = fileInputRef.current.files[0];
314
+
315
+ const formData = new FormData();
316
+ formData.append("audio", file);
317
+ formData.append("genre", selectedPreset);
318
+ formData.append("target_lufs", "-14.0");
319
+
320
+ try {
321
+ const res = await fetch(`${HF_SPACE_URL}/api/master`, {
322
+ method: "POST",
323
+ body: formData,
324
+ });
325
+
326
+ const contentType = res.headers.get("content-type");
327
+
328
+ if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
329
+
330
+ if (contentType && contentType.includes("application/json")) {
331
+ const data = await res.json();
332
+
333
+ if (data.data && data.data.length >= 3) {
334
+ setProcessedAudioUrl(data.data[0]);
335
+
336
+ // Update stats
337
+ setOriginalStats({
338
+ rms: -18,
339
+ peak: -3.5,
340
+ crest: 14.5,
341
+ lufs: -16.8,
342
+ truePeak: -3.2,
343
+ lra: 8.4,
344
+ stereoWidth: 92,
345
+ lowEnergy: -12.5,
346
+ midEnergy: -15.2,
347
+ highEnergy: -18.7,
348
+ dynamicRange: 14.5,
349
+ });
350
+ setProcessedStats({
351
+ rms: -14,
352
+ peak: -1.2,
353
+ crest: 12.8,
354
+ lufs: -14.0,
355
+ truePeak: -1.0,
356
+ lra: 6.8,
357
+ stereoWidth: 105,
358
+ lowEnergy: -10.2,
359
+ midEnergy: -13.5,
360
+ highEnergy: -16.3,
361
+ dynamicRange: 12.8,
362
+ });
363
+
364
+ toast({
365
+ title: "Mastering Complete",
366
+ description: `Applied "${selectedPreset}" preset successfully.`,
367
+ });
368
+ }
369
+ } else {
370
+ const text = await res.text();
371
+ console.error("Received HTML instead of JSON:", text);
372
+ toast({
373
+ title: "Server Error",
374
+ description: "Your Hugging Face app returned an unexpected format.",
375
+ variant: "destructive",
376
+ });
377
+ }
378
+
379
+ } catch (error) {
380
+ console.error("Mastering failed:", error);
381
+ toast({
382
+ title: "Error",
383
+ description: error instanceof Error ? error.message : "Unknown error occurred.",
384
+ variant: "destructive",
385
+ });
386
+ } finally {
387
+ setIsProcessing(false);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
388
  }
389
+ };
390
+
391
+ // 🔄 Change genre/preset
392
+ const handlePresetChange = async (value: string) => {
393
+ setSelectedPreset(value);
394
+ setCustomSettings(masteringPresets[value as keyof typeof masteringPresets] || masteringPresets.pop);
395
+ if (originalAudioUrl && !isProcessing) {
396
+ applyMastering();
397
  }
398
+ };
399
+
400
+ // 🛠 Update custom settings
401
+ const updateCustomSetting = (key: keyof MasteringParams, value: number) => {
402
+ setCustomSettings((prev) => ({
403
+ ...prev,
404
+ [key]: value,
405
+ }));
406
+ };
407
+
408
+ // 📁 Trigger file input click
409
+ const handleUploadClick = () => {
410
+ fileInputRef.current?.click();
411
+ };
412
+
413
+ // 🧼 Cleanup URLs
414
+ useEffect(() => {
415
+ return () => {
416
+ if (originalAudioUrl?.startsWith("blob:")) {
417
+ URL.revokeObjectURL(originalAudioUrl);
418
+ }
419
+ if (processedAudioUrl?.startsWith("blob:")) {
420
+ URL.revokeObjectURL(processedAudioUrl);
421
+ }
422
+ };
423
+ }, [originalAudioUrl, processedAudioUrl]);
424
+
425
+ // State for audio stats
426
+ const [originalStats, setOriginalStats] = useState(defaultAudioStats);
427
+ const [processedStats, setProcessedStats] = useState(defaultAudioStats);
428
+
429
+ return (
430
+ <div className="container mx-auto py-6 space-y-8">
431
+ {/* Header + Upload Area */}
432
+ <div className="flex flex-col md:flex-row justify-between items-start gap-4">
433
+ <div className="flex items-center gap-4">
434
+ <button
435
+ onClick={() => router.back()}
436
+ className="shrink-0 bg-gray-100 dark:bg-gray-800 p-2 rounded-full"
437
+ >
438
+ <span className="sr-only">Back</span>
439
+ <ArrowLeft className="h-4 w-4" />
440
+ </button>
441
+
442
+ <button
443
+ onClick={() => router.push("/dashboard")}
444
+ className="shrink-0 bg-gray-100 dark:bg-gray-800 p-2 rounded-full"
445
+ >
446
+ <span className="sr-only">Home</span>
447
+ <Home className="h-4 w-4" />
448
+ </button>
449
+
450
+ <div>
451
+ <h1 className="text-3xl font-bold tracking-tight">AI Audio Mastering</h1>
452
+ <p className="text-muted-foreground">Enhance your tracks with AI-powered tools.</p>
453
+ </div>
454
+ </div>
455
+
456
+ <div className="flex items-center gap-2">
457
+ <input
458
+ type="file"
459
+ ref={fileInputRef}
460
+ onChange={handleFileSelect}
461
+ accept="audio/*"
462
+ className="hidden"
463
+ />
464
+
465
+ <button
466
+ onClick={handleUploadClick}
467
+ className="bg-purple-600 hover:bg-purple-700 text-white px-4 py-2 rounded-md flex items-center"
468
+ >
469
+ <UploadIcon className="h-4 w-4 mr-2" />
470
+ Upload Track
471
+ </button>
472
+
473
+ <button
474
+ onClick={applyMastering}
475
+ disabled={!originalAudioUrl || isProcessing}
476
+ className={`${
477
+ processedAudioUrl ? "bg-gray-100 text-black" : "bg-purple-600 hover:bg-purple-700 text-white"
478
+ } px-4 py-2 rounded-md flex items-center`}
479
+ >
480
+ {isProcessing ? (
481
+ <>
482
+ <Loader2Icon className="h-4 w-4 mr-2 animate-spin" />
483
+ Processing...
484
+ </>
485
+ ) : processedAudioUrl ? (
486
+ <>
487
+ <RefreshCwIcon className="h-4 w-4 mr-2" />
488
+ Reprocess
489
+ </>
490
+ ) : (
491
+ <>
492
+ <SlidersIcon className="h-4 w-4 mr-2" />
493
+ Apply Mastering
494
+ </>
495
+ )}
496
+ </button>
497
+
498
+ {processedAudioUrl && (
499
+ <DownloadAudioButton
500
+ audioUrl={processedAudioUrl}
501
+ fileName={fileName}
502
+ preset={selectedPreset}
503
+ variant="secondary"
504
+ />
505
+ )}
506
+ </div>
507
+ </div>
508
+
509
+ {/* Main Content */}
510
+ {originalAudioUrl ? (
511
+ <div className="space-y-6">
512
+ <div className="flex flex-col md:flex-row gap-4">
513
+ <Card className="w-full md:w-3/4">
514
+ <CardHeader className="pb-3">
515
+ <div className="flex justify-between items-center">
516
+ <div>
517
+ <CardTitle>Audio File</CardTitle>
518
+ <CardDescription>{fileName}</CardDescription>
519
+ </div>
520
+ <div className="flex items-center gap-2">
521
+ <Select value={selectedPreset} onValueChange={handlePresetChange}>
522
+ <SelectTrigger className="w-[180px]">
523
+ <SelectValue placeholder="Select Preset" />
524
+ </SelectTrigger>
525
+ <SelectContent>
526
+ <SelectItem value="pop">Pop</SelectItem>
527
+ <SelectItem value="rock">Rock</SelectItem>
528
+ <SelectItem value="electronic">Electronic</SelectItem>
529
+ <SelectItem value="hiphop">Hip Hop</SelectItem>
530
+ <SelectItem value="jazz">Jazz</SelectItem>
531
+ <SelectItem value="classical">Classical</SelectItem>
532
+ <SelectItem value="acoustic">Acoustic</SelectItem>
533
+ <SelectItem value="edm">EDM</SelectItem>
534
+ </SelectContent>
535
+ </Select>
536
+
537
+ <div className="flex items-center gap-2">
538
+ <Switch
539
+ id="custom-settings"
540
+ checked={useCustomSettings}
541
+ onCheckedChange={setUseCustomSettings}
542
+ />
543
+ <Label htmlFor="custom-settings">Custom</Label>
544
+ </div>
545
+ </div>
546
+ </div>
547
+ </CardHeader>
548
+ <CardContent>
549
+ <Tabs value={activeTab} onValueChange={setActiveTab}>
550
+ <TabsList className="grid grid-cols-4 mb-4">
551
+ <TabsTrigger value="player">
552
+ <WaveformIcon className="h-4 w-4 mr-2" />
553
+ Player
554
+ </TabsTrigger>
555
+ <TabsTrigger value="comparison">
556
+ <HeadphonesIcon className="h-4 w-4 mr-2" />
557
+ Comparison
558
+ </TabsTrigger>
559
+ <TabsTrigger value="analysis">
560
+ <BarChart3Icon className="h-4 w-4 mr-2" />
561
+ Analysis
562
+ </TabsTrigger>
563
+ <TabsTrigger value="settings" disabled={!useCustomSettings}>
564
+ <SettingsIcon className="h-4 w-4 mr-2" />
565
+ Settings
566
+ </TabsTrigger>
567
+ </TabsList>
568
+
569
+ {/* Waveform & Preview */}
570
+ <TabsContent value="player" className="space-y-4">
571
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
572
+ <div>
573
+ <h3 className="text-lg font-medium mb-2">Original</h3>
574
+ <AudioWaveform
575
+ audioUrl={originalAudioUrl}
576
+ height={120}
577
+ waveColor="rgba(124, 58, 237, 0.4)"
578
+ progressColor="rgba(124, 58, 237, 1)"
579
+ />
580
+ </div>
581
+ {processedAudioUrl && (
582
+ <div>
583
+ <h3 className="text-lg font-medium mb-2">Processed</h3>
584
+ <img
585
+ src="/waveform.png"
586
+ alt="Processed Waveform"
587
+ className="w-full h-30 object-cover rounded-md"
588
+ />
589
+ </div>
590
+ )}
591
+ </div>
592
+ </TabsContent>
593
+
594
+ {/* Compare Original vs Processed */}
595
+ <TabsContent value="comparison">
596
+ {processedAudioUrl ? (
597
+ <MasteringComparison
598
+ originalAudio={originalAudioUrl}
599
+ processedAudio={processedAudioUrl}
600
+ />
601
+ ) : (
602
+ <div className="flex flex-col items-center justify-center py-12 text-center">
603
+ <HeadphonesIcon className="h-12 w-12 text-muted-foreground mb-4" />
604
+ <h3 className="text-lg font-medium">No Processed Audio</h3>
605
+ <p className="text-muted-foreground mt-2 max-w-md">
606
+ Apply mastering to enable comparison.
607
+ </p>
608
+ <button
609
+ onClick={applyMastering}
610
+ disabled={isProcessing}
611
+ className="mt-4 bg-purple-600 hover:bg-purple-700 text-white px-4 py-2 rounded-md flex items-center"
612
+ >
613
+ {isProcessing ? (
614
+ <>
615
+ <Loader2Icon className="h-4 w-4 mr-2 animate-spin" />
616
+ Processing...
617
+ </>
618
+ ) : (
619
+ <>
620
+ <SlidersIcon className="h-4 w-4 mr-2" />
621
+ Apply Mastering
622
+ </>
623
+ )}
624
+ </button>
625
+ </div>
626
+ )}
627
+ </TabsContent>
628
+
629
+ {/* Analytics */}
630
+ <TabsContent value="analysis">
631
+ <AudioQualityAnalyzer
632
+ audioUrl={originalAudioUrl}
633
+ fileName={fileName}
634
+ />
635
+ </TabsContent>
636
+
637
+ {/* Custom EQ Panel */}
638
+ <TabsContent value="settings" className="space-y-6">
639
+ {useCustomSettings && (
640
+ <>
641
+ <div className="space-y-4">
642
+ <h3 className="text-lg font-medium">EQ Settings</h3>
643
+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
644
+ <div className="space-y-2">
645
+ <div className="flex justify-between">
646
+ <Label htmlFor="lowGain">Low Gain</Label>
647
+ <span className="text-sm">{customSettings.lowGain} dB</span>
648
+ </div>
649
+ <Slider
650
+ id="lowGain"
651
+ min={-12}
652
+ max={12}
653
+ step={0.5}
654
+ value={[customSettings.lowGain]}
655
+ onValueChange={(val) =>
656
+ updateCustomSetting("lowGain", val[0])
657
+ }
658
+ />
659
+ </div>
660
+ <div className="space-y-2">
661
+ <div className="flex justify-between">
662
+ <Label htmlFor="lowMidGain">Low Mid</Label>
663
+ <span className="text-sm">{customSettings.lowMidGain} dB</span>
664
+ </div>
665
+ <Slider
666
+ id="lowMidGain"
667
+ min={-12}
668
+ max={12}
669
+ step={0.5}
670
+ value={[customSettings.lowMidGain]}
671
+ onValueChange={(val) =>
672
+ updateCustomSetting("lowMidGain", val[0])
673
+ }
674
+ />
675
+ </div>
676
+ <div className="space-y-2">
677
+ <div className="flex justify-between">
678
+ <Label htmlFor="midGain">Mid</Label>
679
+ <span className="text-sm">{customSettings.midGain} dB</span>
680
+ </div>
681
+ <Slider
682
+ id="midGain"
683
+ min={-12}
684
+ max={12}
685
+ step={0.5}
686
+ value={[customSettings.midGain]}
687
+ onValueChange={(val) =>
688
+ updateCustomSetting("midGain", val[0])
689
+ }
690
+ />
691
+ </div>
692
+ <div className="space-y-2">
693
+ <div className="flex justify-between">
694
+ <Label htmlFor="highMidGain">High Mid</Label>
695
+ <span className="text-sm">{customSettings.highMidGain} dB</span>
696
+ </div>
697
+ <Slider
698
+ id="highMidGain"
699
+ min={-12}
700
+ max={12}
701
+ step={0.5}
702
+ value={[customSettings.highMidGain]}
703
+ onValueChange={(val) =>
704
+ updateCustomSetting("highMidGain", val[0])
705
+ }
706
+ />
707
+ </div>
708
+ <div className="space-y-2">
709
+ <div className="flex justify-between">
710
+ <Label htmlFor="highGain">High Gain</Label>
711
+ <span className="text-sm">{customSettings.highGain} dB</span>
712
+ </div>
713
+ <Slider
714
+ id="highGain"
715
+ min={-12}
716
+ max={12}
717
+ step={0.5}
718
+ value={[customSettings.highGain]}
719
+ onValueChange={(val) =>
720
+ updateCustomSetting("highGain", val[0])
721
+ }
722
+ />
723
+ </div>
724
+ </div>
725
+ </div>
726
+
727
+ <div className="space-y-4">
728
+ <h3 className="text-lg font-medium">Compression</h3>
729
+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
730
+ <div className="space-y-2">
731
+ <div className="flex justify-between">
732
+ <Label htmlFor="threshold">Threshold</Label>
733
+ <span className="text-sm">{customSettings.threshold} dB</span>
734
+ </div>
735
+ <Slider
736
+ id="threshold"
737
+ min={-50}
738
+ max={0}
739
+ step={1}
740
+ value={[customSettings.threshold]}
741
+ onValueChange={(val) =>
742
+ updateCustomSetting("threshold", val[0])
743
+ }
744
+ />
745
+ </div>
746
+ <div className="space-y-2">
747
+ <div className="flex justify-between">
748
+ <Label htmlFor="ratio">Ratio</Label>
749
+ <span className="text-sm">{customSettings.ratio}:1</span>
750
+ </div>
751
+ <Slider
752
+ id="ratio"
753
+ min={1}
754
+ max={20}
755
+ step={0.5}
756
+ value={[customSettings.ratio]}
757
+ onValueChange={(val) =>
758
+ updateCustomSetting("ratio", val[0])
759
+ }
760
+ />
761
+ </div>
762
+ <div className="space-y-2">
763
+ <div className="flex justify-between">
764
+ <Label htmlFor="attack">Attack</Label>
765
+ <span className="text-sm">{customSettings.attack} ms</span>
766
+ </div>
767
+ <Slider
768
+ id="attack"
769
+ min={0}
770
+ max={100}
771
+ step={1}
772
+ value={[customSettings.attack]}
773
+ onValueChange={(val) =>
774
+ updateCustomSetting("attack", val[0])
775
+ }
776
+ />
777
+ </div>
778
+ <div className="space-y-2">
779
+ <div className="flex justify-between">
780
+ <Label htmlFor="release">Release</Label>
781
+ <span className="text-sm">{customSettings.release} ms</span>
782
+ </div>
783
+ <Slider
784
+ id="release"
785
+ min={10}
786
+ max={1000}
787
+ step={10}
788
+ value={[customSettings.release]}
789
+ onValueChange={(val) =>
790
+ updateCustomSetting("release", val[0])
791
+ }
792
+ />
793
+ </div>
794
+ <div className="space-y-2">
795
+ <div className="flex justify-between">
796
+ <Label htmlFor="knee">Knee</Label>
797
+ <span className="text-sm">{customSettings.knee} dB</span>
798
+ </div>
799
+ <Slider
800
+ id="knee"
801
+ min={0}
802
+ max={40}
803
+ step={1}
804
+ value={[customSettings.knee]}
805
+ onValueChange={(val) =>
806
+ updateCustomSetting("knee", val[0])
807
+ }
808
+ />
809
+ </div>
810
+ </div>
811
+ </div>
812
+
813
+ <div className="space-y-4">
814
+ <h3 className="text-lg font-medium">Limiting & Output</h3>
815
+ <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
816
+ <div className="space-y-2">
817
+ <div className="flex justify-between">
818
+ <Label htmlFor="limiterThreshold">Limiter Threshold</Label>
819
+ <span className="text-sm">{customSettings.limiterThreshold} dB</span>
820
+ </div>
821
+ <Slider
822
+ id="limiterThreshold"
823
+ min={-12}
824
+ max={0}
825
+ step={0.1}
826
+ value={[customSettings.limiterThreshold]}
827
+ onValueChange={(val) =>
828
+ updateCustomSetting("limiterThreshold", val[0])
829
+ }
830
+ />
831
+ </div>
832
+ <div className="space-y-2">
833
+ <div className="flex justify-between">
834
+ <Label htmlFor="limiterRelease">Limiter Release</Label>
835
+ <span className="text-sm">{customSettings.limiterRelease} ms</span>
836
+ </div>
837
+ <Slider
838
+ id="limiterRelease"
839
+ min={10}
840
+ max={500}
841
+ step={10}
842
+ value={[customSettings.limiterRelease]}
843
+ onValueChange={(val) =>
844
+ updateCustomSetting("limiterRelease", val[0])
845
+ }
846
+ />
847
+ </div>
848
+ <div className="space-y-2">
849
+ <div className="flex justify-between">
850
+ <Label htmlFor="outputGain">Output Gain</Label>
851
+ <span className="text-sm">{customSettings.outputGain} dB</span>
852
+ </div>
853
+ <Slider
854
+ id="outputGain"
855
+ min={-12}
856
+ max={12}
857
+ step={0.5}
858
+ value={[customSettings.outputGain]}
859
+ onValueChange={(val) =>
860
+ updateCustomSetting("outputGain", val[0])
861
+ }
862
+ />
863
+ </div>
864
+ </div>
865
+ </div>
866
+
867
+ <div className="flex justify-end gap-2 mt-4">
868
+ <Button
869
+ variant="outline"
870
+ onClick={() =>
871
+ setCustomSettings(
872
+ masteringPresets[
873
+ selectedPreset as keyof typeof masteringPresets
874
+ ] || masteringPresets.pop
875
+ )
876
+ }
877
+ >
878
+ Reset to Preset
879
+ </Button>
880
+ <Button
881
+ onClick={applyMastering}
882
+ disabled={isProcessing}
883
+ >
884
+ {isProcessing ? (
885
+ <>
886
+ <Loader2Icon className="h-4 w-4 mr-2 animate-spin" />
887
+ Processing...
888
+ </>
889
+ ) : (
890
+ <>
891
+ <SaveIcon className="h-4 w-4 mr-2" />
892
+ Apply Settings
893
+ </>
894
+ )}
895
+ </Button>
896
+ </div>
897
+ </>
898
+ )}
899
+ </TabsContent>
900
+ </Tabs>
901
+ </CardContent>
902
+ </Card>
903
+
904
+ <Card className="w-full md:w-1/4">
905
+ <CardHeader>
906
+ <CardTitle>Genre Analysis</CardTitle>
907
+ <CardDescription>Get genre-specific recommendations</CardDescription>
908
+ </CardHeader>
909
+ <CardContent>
910
+ <div className="space-y-4">
911
+ <div className="flex items-center gap-2">
912
+ <MusicIcon className="h-5 w-5 text-primary" />
913
+ <span>
914
+ Selected Genre: <Badge>{selectedPreset}</Badge>
915
+ </span>
916
+ </div>
917
+ <p className="text-sm text-muted-foreground">
918
+ Analyze your track against genre standards for tailored mastering.
919
+ </p>
920
+ <button
921
+ onClick={() => setActiveTab("analysis")}
922
+ className="w-full bg-gray-100 hover:bg-gray-200 text-gray-800 px-4 py-2 rounded-md flex items-center justify-center"
923
+ >
924
+ <BarChart3Icon className="h-4 w-4 mr-2" />
925
+ View Detailed Analysis
926
+ </button>
927
+ </div>
928
+ </CardContent>
929
+ </Card>
930
+ </div>
931
+ </div>
932
+ ) : (
933
+ <Card className="w-full">
934
+ <CardContent className="flex flex-col items-center justify-center py-12 text-center">
935
+ <UploadIcon className="h-12 w-12 text-muted-foreground mb-4" />
936
+ <h3 className="text-lg font-medium">No Audio Selected</h3>
937
+ <p className="text-muted-foreground mt-2 max-w-md">
938
+ Upload a WAV, MP3, or FLAC file to begin mastering.
939
+ </p>
940
+ <button
941
+ onClick={handleUploadClick}
942
+ className="mt-4 bg-purple-600 hover:bg-purple-700 text-white px-4 py-2 rounded-md"
943
+ >
944
+ <UploadIcon className="h-4 w-4 mr-2" />
945
+ Upload Audio
946
+ </button>
947
+ </CardContent>
948
+ </Card>
949
+ )}
950
+ </div>
951
+ );
952
+ }
953
 
954
+ // 🎵 Simple Waveform Component with Play Button Overlay
955
+ function AudioWaveform({ audioUrl, height = 100, waveColor = "#4f46e5", progressColor = "#8b5cf6" }) {
956
+ const [isPlaying, setIsPlaying] = useState(false);
957
+ const audioRef = useRef<HTMLAudioElement>(null);
958
+
959
+ const togglePlayback = () => {
960
+ if (!audioRef.current) return;
961
+
962
+ if (isPlaying) {
963
+ audioRef.current.pause();
964
+ } else {
965
+ audioRef.current.play().catch((err) => {
966
+ console.error("Autoplay blocked:", err);
967
+ alert("Click inside the waveform to start playback.");
968
+ });
 
969
  }
970
+ setIsPlaying(!isPlaying);
971
+ };
972
+
973
+ return (
974
+ <div className="relative w-full">
975
+ <div
976
+ style={{
977
+ height: `${height}px`,
978
+ background: `linear-gradient(180deg, ${waveColor}22, ${progressColor}aa)`,
979
+ position: "relative",
980
+ overflow: "hidden",
981
+ borderRadius: "0.5rem",
982
+ }}
983
+ className="w-full rounded-md relative"
984
+ onClick={togglePlayback}
985
+ >
986
+ <div className="absolute inset-0 flex items-center justify-center">
987
+ <button
988
+ onClick={(e) => {
989
+ e.stopPropagation();
990
+ togglePlayback();
991
+ }}
992
+ className="h-12 w-12 bg-white/80 backdrop-blur-sm rounded-full flex items-center justify-center shadow-md"
993
+ >
994
+ {isPlaying ? (
995
+ <span className="h-4 w-4 block rounded-sm bg-primary"></span>
996
+ ) : (
997
+ <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
998
+ <path d="M3 2.5L13 8L3 13.5V2.5Z" fill="#4f46e5" />
999
+ </svg>
1000
+ )}
1001
+ </button>
1002
+ </div>
1003
+ </div>
1004
+ <audio ref={audioRef} src={audioUrl} onEnded={() => setIsPlaying(false)} />
1005
  </div>
1006
+ );
1007
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1008
 
1009
+ // 📊 Stats Display Component
1010
+ function MasteringStatistics({ originalStats, processedStats }) {
1011
+ return (
1012
+ <Card className="mt-4">
1013
+ <CardHeader className="pb-2">
1014
+ <CardTitle className="text-lg">Mastering Statistics</CardTitle>
1015
+ <CardDescription>Compare original and processed audio</CardDescription>
1016
+ </CardHeader>
1017
+ <CardContent>
1018
+ <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
1019
+ <div className="space-y-1">
1020
+ <div className="text-sm font-medium">LUFS</div>
1021
+ <div className="flex justify-between">
1022
+ <span className="text-xs">Original</span>
1023
+ <span className="font-mono">{originalStats.lufs.toFixed(1)}</span>
1024
+ </div>
1025
+ <div className="flex justify-between">
1026
+ <span className="text-xs">Processed</span>
1027
+ <span className="font-mono text-primary">{processedStats.lufs.toFixed(1)}</span>
1028
+ </div>
1029
+ </div>
1030
+ </div>
1031
+ </CardContent>
1032
+ </Card>
1033
+ );
1034
+ }
1035
 
1036
+ // 🎵 Compare Two Tracks
1037
+ function MasteringComparison({ originalAudio, processedAudio }) {
1038
+ const [activeAudio, setActiveAudio] = useState<"original" | "processed">("processed");
1039
+
1040
+ return (
1041
+ <div className="space-y-6">
1042
+ <div className="flex justify-center gap-4">
1043
+ <button
1044
+ onClick={() => setActiveAudio("original")}
1045
+ className={`${activeAudio === "original" ? "bg-primary text-white" : "bg-secondary text-primary"} px-4 py-2 rounded-md w-40`}
1046
+ >
1047
+ Original
1048
+ </button>
1049
+ <button
1050
+ onClick={() => setActiveAudio("processed")}
1051
+ className={`${activeAudio === "processed" ? "bg-primary text-white" : "bg-secondary text-primary"} px-4 py-2 rounded-md w-40`}
1052
+ >
1053
+ Processed
1054
+ </button>
1055
+ </div>
1056
+ </div>
1057
+ );
1058
+ }
1059
 
1060
+ // 📈 Frequency Spectrum Analyzer
1061
+ function AudioQualityAnalyzer({ audioUrl, fileName }) {
1062
+ return (
1063
+ <div className="space-y-6">
1064
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
1065
+ <Card>
1066
+ <CardHeader className="pb-2">
1067
+ <CardTitle className="text-lg">Frequency Spectrum</CardTitle>
1068
+ </CardHeader>
1069
+ <CardContent>
1070
+ <div className="h-40 bg-muted/30 rounded-md flex items-center justify-center">
1071
+ <p className="text-sm text-muted-foreground">Spectrum visualization</p>
1072
+ </div>
1073
+ </CardContent>
1074
+ </Card>
1075
+ <Card>
1076
+ <CardHeader className="pb-2">
1077
+ <CardTitle className="text-lg">Streaming Compatibility</CardTitle>
1078
+ </CardHeader>
1079
+ <CardContent>
1080
+ <div className="space-y-3">
1081
+ <div className="flex justify-between items-center">
1082
+ <span className="text-sm">Spotify</span>
1083
+ <div className="w-32 h-2 bg-muted rounded-full overflow-hidden">
1084
+ <div className="h-full bg-green-500" style={{ width: "85%" }}></div>
1085
+ </div>
1086
+ <span className="text-sm font-medium">85%</span>
1087
+ </div>
1088
+ <div className="flex justify-between items-center">
1089
+ <span className="text-sm">Apple Music</span>
1090
+ <div className="w-32 h-2 bg-muted rounded-full overflow-hidden">
1091
+ <div className="h-full bg-green-500" style={{ width: "90%" }}></div>
1092
+ </div>
1093
+ <span className="text-sm font-medium">90%</span>
1094
+ </div>
1095
+ <div className="flex justify-between items-center">
1096
+ <span className="text-sm">YouTube</span>
1097
+ <div className="w-32 h-2 bg-muted rounded-full overflow-hidden">
1098
+ <div className="h-full bg-amber-500" style={{ width: "75%" }}></div>
1099
+ </div>
1100
+ <span className="text-sm font-medium">75%</span>
1101
+ </div>
1102
+ <div className="flex justify-between items-center">
1103
+ <span className="text-sm">SoundCloud</span>
1104
+ <div className="w-32 h-2 bg-muted rounded-full overflow-hidden">
1105
+ <div className="h-full bg-green-500" style={{ width: "88%" }}></div>
1106
+ </div>
1107
+ <span className="text-sm font-medium">88%</span>
1108
+ </div>
1109
+ </div>
1110
+ </CardContent>
1111
+ </Card>
1112
+ </div>
1113
+ </div>
1114
+ );
1115
+ }