Spaces:
Build error
Build error
Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845854 unmodified lines5905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267271 unmodified line7297307317327337347357367377387397407417427437447457467477487497507517527537547557566 unmodified lines7637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987996 unmodified lines8068078088098108118128138148158168178188191 unmodified line821822823824825826import gradio as grfrom pydub import AudioSegmentimport numpy as npimport tempfileimport osimport noisereduce as nrimport torchfrom demucs import pretrainedfrom demucs.apply import apply_modelimport torchaudiofrom pathlib import Pathimport matplotlib.pyplot as pltfrom io import BytesIOfrom PIL import Imageimport zipfileimport datetimeimport librosaimport warningsfrom TTS.api import TTSimport base64import pickleimport jsonimport soundfile as sfwarnings.filterwarnings("ignore")# ==============================# Helper Functions# ==============================def audiosegment_to_array(audio):return np.array(audio.get_array_of_samples()), audio.frame_ratedef array_to_audiosegment(samples, frame_rate, channels=1):return AudioSegment(samples.tobytes(),frame_rate=int(frame_rate),sample_width=samples.dtype.itemsize,channels=channels)def save_audiosegment_to_temp(audio: AudioSegment, suffix=".wav"):with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as f:audio.export(f.name, format=suffix.lstrip('.'))return f.namedef load_audiofile_to_numpy(path):samples, sr = sf.read(path, dtype="int16")if samples.ndim > 1 and samples.shape[1] > 2:samples = samples[:, :2]return samples, srdef show_waveform(audio_file):try:audio = AudioSegment.from_file(audio_file)samples = np.array(audio.get_array_of_samples())plt.figure(figsize=(10, 2))plt.plot(samples[:10000], color="skyblue")plt.axis('off')buf = BytesIO()plt.savefig(buf, format="png", bbox_inches="tight", dpi=100)plt.close()buf.seek(0)return Image.open(buf)except Exception:return None# ==============================# Effect Functions (as per original)# ==============================def apply_normalize(audio):return audio.normalize()def apply_noise_reduction(audio):samples, sr = audiosegment_to_array(audio)reduced = nr.reduce_noise(y=samples, sr=sr)return array_to_audiosegment(reduced, sr, channels=audio.channels)def apply_compression(audio):return audio.compress_dynamic_range()def apply_reverb(audio):reverb = audio - 10return audio.overlay(reverb, position=1000)def apply_pitch_shift(audio, semitones=-2):new_frame_rate = int(audio.frame_rate * (2 ** (semitones / 12)))shifted = audio._spawn(audio.raw_data, overrides={"frame_rate": new_frame_rate}).set_frame_rate(audio.frame_rate)return shifteddef apply_echo(audio, delay_ms=500, decay=0.5):echo = audio - 10return audio.overlay(echo, position=delay_ms)def apply_stereo_widen(audio, pan_amount=0.3):left = audio.pan(-pan_amount)right = audio.pan(pan_amount)return AudioSegment.from_mono_audiosegments(left, right)def apply_bass_boost(audio, gain=10):return audio.low_pass_filter(100).apply_gain(gain)def apply_treble_boost(audio, gain=10):return audio.high_pass_filter(4000).apply_gain(gain)def apply_limiter(audio, limit_dB=-1):limiter = audio._spawn(audio.raw_data, overrides={"frame_rate": audio.frame_rate})return limiter.apply_gain(limit_dB)def apply_auto_gain(audio, target_dB=-20):change = target_dB - audio.dBFSreturn audio.apply_gain(change)def apply_vocal_distortion(audio, intensity=0.3):samples = np.array(audio.get_array_of_samples()).astype(np.float32)distorted = samples + intensity * np.sin(samples * 2 * np.pi / 32768)return array_to_audiosegment(distorted.astype(np.int16), audio.frame_rate, channels=audio.channels)def apply_harmony(audio, shift_semitones=4):shifted_up = apply_pitch_shift(audio, shift_semitones)shifted_down = apply_pitch_shift(audio, -shift_semitones)return audio.overlay(shifted_up).overlay(shifted_down)def apply_stage_mode(audio):processed = apply_reverb(audio)processed = apply_bass_boost(processed, gain=6)return apply_limiter(processed, limit_dB=-2)def apply_bitcrush(audio, bit_depth=8):samples = np.array(audio.get_array_of_samples())max_val = 2 ** bit_depth - 1downsampled = np.round(samples / (32768 / max_val)).astype(np.int16)return array_to_audiosegment(downsampled, audio.frame_rate // 2, channels=audio.channels)# ==============================# Loudness Matching (EBU R128)# ==============================try:import pyloudnorm as pylnexcept ImportError:import subprocesssubprocess.run(["pip", "install", "pyloudnorm"])import pyloudnorm as pylndef match_loudness(audio_path, target_lufs=-14.0):meter = pyln.Meter(44100)wav = AudioSegment.from_file(audio_path).set_frame_rate(44100)samples = np.array(wav.get_array_of_samples()).astype(np.float64) / 32768.0loudness = meter.integrated_loudness(samples)gain_db = target_lufs - loudnessadjusted = wav + gain_dbout_path = save_audiosegment_to_temp(adjusted, ".wav")return out_path# ==============================# EQ Map and Function# ==============================eq_map = {"Pop": [(200, 500, -3), (2000, 4000, +4)],# (Add other genres as needed)}def auto_eq(audio, genre="Pop"):from scipy.signal import butter, sosfiltsamples, sr = audiosegment_to_array(audio)samples = samples.astype(np.float64)def band_eq(samples, sr, lowcut, highcut, gain):sos = butter(10, [lowcut, highcut], btype='band', output='sos', fs=sr)filtered = sosfilt(sos, samples)return samples + gain * filteredfor low, high, gain in eq_map.get(genre, []):samples = band_eq(samples, sr, low, high, gain)return array_to_audiosegment(samples.astype(np.int16), sr, channels=audio.channels)# ==============================# Load & Save Track for Models# ==============================def load_track_local(path, sample_rate, channels=2):sig, rate = torchaudio.load(path)if rate != sample_rate:sig = torchaudio.functional.resample(sig, rate, sample_rate)if channels == 1:sig = sig.mean(0)return sigdef save_track(path, wav, sample_rate):Path(path).parent.mkdir(parents=True, exist_ok=True)torchaudio.save(str(path), wav, sample_rate)# ==============================# Vocal isolation and stem splitting# ==============================def apply_vocal_isolation(audio_path):model = pretrained.get_model(name='htdemucs')wav = load_track_local(audio_path, model.samplerate, channels=2)ref = wav.mean(0)wav -= ref[:, None]sources = apply_model(model, wav[None])[0]wav += ref[:, None]vocal_track = sources[3].cpu()out_path = os.path.join(tempfile.gettempdir(), "vocals.wav")save_track(out_path, vocal_track, model.samplerate)return out_pathdef stem_split(audio_path):model = pretrained.get_model(name='htdemucs')wav = load_track_local(audio_path, model.samplerate, channels=2)sources = apply_model(model, wav[None])[0]output_dir = tempfile.mkdtemp()file_paths = []for i, name in enumerate(['drums', 'bass', 'other', 'vocals']):path = os.path.join(output_dir, f"{name}.wav")save_track(path, sources[i].cpu(), model.samplerate)file_paths.append(path)# Return in order vocals, drums, bass, other per your UIreturn file_paths[3], file_paths[0], file_paths[1], file_paths[2]# ==============================# Full Audio Processor with Effects Map# ==============================def process_audio(audio_file, selected_effects, isolate_vocals, preset_name, export_format):try:audio = AudioSegment.from_file(audio_file)effect_map = {"Noise Reduction": apply_noise_reduction,"Compress Dynamic Range": apply_compression,"Add Reverb": apply_reverb,"Pitch Shift": apply_pitch_shift,"Echo": apply_echo,"Stereo Widening": apply_stereo_widen,"Bass Boost": apply_bass_boost,"Treble Boost": apply_treble_boost,"Normalize": apply_normalize,"Limiter": lambda a: apply_limiter(a, limit_dB=-1),"Auto Gain": lambda a: apply_auto_gain(a, target_dB=-20),"Vocal Distortion": apply_vocal_distortion,"Stage Mode": apply_stage_mode,"Harmony": apply_harmony,"Bitcrusher": apply_bitcrush,}for eff in selected_effects:if eff in effect_map:audio = effect_map[eff](audio)if isolate_vocals:temp_path = save_audiosegment_to_temp(audio, suffix=".wav")vocal_path = apply_vocal_isolation(temp_path)audio = AudioSegment.from_file(vocal_path)output_path = save_audiosegment_to_temp(audio, suffix=f".{export_format.lower()}")samples, sr = load_audiofile_to_numpy(output_path)waveform = show_waveform(output_path)session_log = json.dumps({"timestamp": str(datetime.datetime.now()),"filename": os.path.basename(audio_file),"effects_applied": selected_effects,"isolate_vocals": isolate_vocals,"export_format": export_format,"detected_genre": "Unknown"}, indent=2)return (samples, sr), waveform, session_log, "Unknown", "🎉 Done!"except Exception as e:return None, None, f"❌ Error: {e}", "", f"❌ Error: {e}"# ==============================# Batch Processing# ==============================def batch_process_audio(files, selected_effects, isolate_vocals, preset_name, export_format):try:output_dir = tempfile.mkdtemp()paths = []logs = []for i, file in enumerate(files):result, _, log, _, _ = process_audio(file.name, selected_effects, isolate_vocals, preset_name, export_format)if result is None:continuesamples, sr = resultfilepath = os.path.join(output_dir, f"processed_{i}.{export_format.lower()}")sf.write(filepath, samples, sr)paths.append(filepath)logs.append(log)zip_path = os.path.join(tempfile.gettempdir(), "batch_output.zip")with zipfile.ZipFile(zip_path, 'w') as zf:for i, p in enumerate(paths):zf.write(p, os.path.basename(p))zf.writestr(f"session_log_{i}.json", logs[i])return zip_path, "📦 Batch processing complete!"except Exception as e:return None, f"❌ Batch processing failed: {e}"# ==============================# AI Remastering# ==============================def ai_remaster(audio_path):try:audio = AudioSegment.from_file(audio_path)samples, sr = audiosegment_to_array(audio)reduced = nr.reduce_noise(y=samples, sr=sr)cleaned = array_to_audiosegment(reduced, sr, channels=audio.channels)cleaned_path = save_audiosegment_to_temp(cleaned, ".wav")isolated_path = apply_vocal_isolation(cleaned_path)final_path = ai_mastering_chain(isolated_path, genre="Pop", target_lufs=-14.0)samples, sr = load_audiofile_to_numpy(final_path)return (samples, sr)except Exception as e:print(f"Remastering error: {e}")return Nonedef ai_mastering_chain(audio_path, genre="Pop", target_lufs=-14.0):audio = AudioSegment.from_file(audio_path)audio = auto_eq(audio, genre=genre)loud_adj_path = match_loudness(audio_path, target_lufs)audio = AudioSegment.from_file(loud_adj_path)audio = apply_stereo_widen(audio, pan_amount=0.3)out_path = save_audiosegment_to_temp(audio, ".wav")return out_pathdef apply_stereo_widen(audio, pan_amount=0.3):left = audio.pan(-pan_amount)right = audio.pan(pan_amount)return AudioSegment.from_mono_audiosegments(left, right)# ==============================# Harmonic Saturation# ==============================def harmonic_saturation(audio_path, saturation_type="Tube", intensity=0.2):audio = AudioSegment.from_file(audio_path)samples = np.array(audio.get_array_of_samples()).astype(np.float32)if saturation_type == "Tube":saturated = np.tanh(intensity * samples)elif saturation_type == "Tape":saturated = np.where(samples > 0, 1 - np.exp(-intensity * samples), -1 + np.exp(intensity * samples))elif saturation_type == "Console":saturated = np.clip(samples, -32768, 32768) * intensityelif saturation_type == "Mix Bus":saturated = np.log1p(np.abs(samples)) * np.sign(samples) * intensityelse:saturated = samplessaturated_audio = array_to_audiosegment(saturated.astype(np.int16), audio.frame_rate, audio.channels)out_path = save_audiosegment_to_temp(saturated_audio, ".wav")samples, sr = load_audiofile_to_numpy(out_path)return (samples, sr)# ==============================# Vocal Doubler Harmony# ==============================def run_harmony(audio_file):if not audio_file:return None, "❌ Upload a vocal clip first."try:audio = AudioSegment.from_file(audio_file)out_audio = apply_harmony(audio)tmp_path = save_audiosegment_to_temp(out_audio, ".wav")samples, sr = load_audiofile_to_numpy(tmp_path)return (samples, sr), "✅ Success"except Exception as e:return None, f"❌ Error: {e}"# ==============================# Auto-Tune helper# ==============================def key_to_semitone(key="C"):mapping = {"C": 0, "C#": 1, "D": 2, "D#": 3, "E": 4, "F": 5,"F#": 6, "G": 7, "G#": 8, "A": 9, "A#": 10, "B": 11}return mapping.get(key, 0)def auto_tune_vocal(audio_file, target_key="C"):try:audio = AudioSegment.from_file(audio_file.name)semitones = key_to_semitone(target_key)tuned_audio = apply_pitch_shift(audio, semitones)tmp_path = save_audiosegment_to_temp(tuned_audio, ".wav")samples, sr = load_audiofile_to_numpy(tmp_path)return (samples, sr)except Exception as e:print(f"Auto-Tune Error: {e}")return None# ==============================# Loop Section Utility# ==============================def loop_section(audio_file, start_ms, end_ms, loops=2):audio = AudioSegment.from_file(audio_file)section = audio[start_ms:end_ms]looped = section * loopstmp_path = save_audiosegment_to_temp(looped, ".wav")samples, sr = load_audiofile_to_numpy(tmp_path)return (samples, sr)# ==============================# Frequency Spectrum Visualization# ==============================def visualize_spectrum(audio_file):y, sr = torchaudio.load(audio_file)import librosa.displayy_np = y.numpy().flatten()stft = librosa.stft(y_np)db = librosa.amplitude_to_db(abs(stft))plt.figure(figsize=(10, 4))img = librosa.display.specshow(db, sr=sr, x_axis="time", y_axis="hz", cmap="magma")plt.colorbar(img, format="%+2.0f dB")plt.title("Frequency Spectrum")plt.tight_layout()buf = BytesIO()plt.savefig(buf, format="png")plt.close()buf.seek(0)return Image.open(buf)# ==============================# A/B Compare Function# ==============================def compare_ab(track1_path, track2_path):return track1_path, track2_path# ==============================# DAW Template Generation# ==============================def generate_ableton_template(stem_files):template = {"format": "Ableton Live","stems": [os.path.basename(s.name) for s in stem_files],"effects": ["Reverb", "EQ", "Compression"],"tempo": 128,"title": "Studio Pulse Project"}out_path = os.path.join(tempfile.gettempdir(), "ableton_template.json")with open(out_path, "w") as f:json.dump(template, f, indent=2)return out_path# ==============================# Export Full Mix as ZIP# ==============================def export_full_mix(stem_files, final_mix_file):zip_path = os.path.join(tempfile.gettempdir(), "full_export.zip")with zipfile.ZipFile(zip_path, "w") as zipf:for i, stem in enumerate(stem_files):zipf.write(stem.name, f"stem_{i}.wav")zipf.write(final_mix_file.name, "final_mix.wav")return zip_path# ==============================# Save/Load Project Functions# ==============================def save_project(audio_file, preset, effects):audio = AudioSegment.from_file(audio_file.name)project_data = {"audio": audio.raw_data,"preset": preset,"effects": effects}out_path = os.path.join(tempfile.gettempdir(), "project.aiproj")with open(out_path, "wb") as f:pickle.dump(project_data, f)return out_pathdef load_project(project_file):with open(project_file.name, "rb") as f:data = pickle.load(f)return data.get("preset", ""), data.get("effects", [])# ==============================# Prompt-based editing# ==============================def process_prompt(audio_file, prompt):audio = AudioSegment.from_file(audio_file)processed_audio = apply_noise_reduction(audio) # Example; real model integration can be added heretmp_path = save_audiosegment_to_temp(processed_audio, ".wav")samples, sr = load_audiofile_to_numpy(tmp_path)return (samples, sr)# ==============================# Voice Swap# ==============================def clone_voice(source_audio_file, reference_audio_file):source = AudioSegment.from_file(source_audio_file.name)ref = AudioSegment.from_file(reference_audio_file.name)mixed = source.overlay(ref - 10)tmp_path = save_audiosegment_to_temp(mixed, ".wav")return tmp_path# ==============================# Presets dictionary (use your full original content)# ==============================preset_choices = {"Default": [],"Clean Podcast": ["Noise Reduction", "Normalize"],"Podcast Mastered": ["Noise Reduction", "Normalize", "Compress Dynamic Range"],"Radio Ready": ["Bass Boost", "Treble Boost", "Limiter"],"Music Production": ["Reverb", "Stereo Widening", "Pitch Shift"],"ASMR Creator": ["Noise Gate", "Auto Gain", "Low-Pass Filter"],"Voiceover Pro": ["Vocal Isolation", "TTS", "EQ Match"],"8-bit Retro": ["Bitcrusher", "Echo", "Mono Downmix"],"🎙 Clean Vocal": ["Noise Reduction", "Normalize", "High Pass Filter (80Hz)"],"🧪 Vocal Distortion": ["Vocal Distortion", "Reverb", "Compress Dynamic Range"],"🎶 Singer's Harmony": ["Harmony", "Stereo Widening", "Pitch Shift"],"🌫 ASMR Vocal": ["Auto Gain", "Low-Pass Filter (3000Hz)", "Noise Gate"],"🎼 Stage Mode": ["Reverb", "Bass Boost", "Limiter"],"🎵 Auto-Tune Style": ["Pitch Shift (+1 semitone)", "Normalize", "Treble Boost"],"🎤 R&B Vocal": ["Noise Reduction", "Bass Boost (100-300Hz)", "Treble Boost (2000-4000Hz)"],"💃 Soul Vocal": ["Noise Reduction", "Bass Boost (80-200Hz)", "Treble Boost (1500-3500Hz)"],"🕺 Funk Groove": ["Bass Boost (80-200Hz)", "Treble Boost (1000-3000Hz)"],"Studio Master": ["Noise Reduction", "Normalize", "Bass Boost", "Treble Boost", "Limiter"],"Podcast Voice": ["Noise Reduction", "Auto Gain", "High Pass Filter (85Hz)"],"Lo-Fi Chill": ["Noise Gate", "Low-Pass Filter (3000Hz)", "Mono Downmix", "Bitcrusher"],# Add other presets from your original exactly}preset_names = list(preset_choices.keys())# ==============================# Gradio UI Construction with Explicit Components + Clicks# ==============================with gr.Blocks() as demo:gr.HTML('<h3 style="text-align:center;">Where Your Audio Meets Intelligence</h3>')gr.Markdown('### Upload, edit, export — powered by AI!')# === Single File Studio Tab ===with gr.Blocks() as demo:gr.HTML('<h3 style="text-align:center;">Where Your Audio Meets Intelligence</h3>')gr.Markdown('### Upload, edit, export — powered by AI!')# --- Single File Studio Tab ---with gr.Tab("🎵 Single File Studio"):with gr.Row():with gr.Column():input_audio = gr.Audio(label="Upload Audio", type="filepath")effect_choices = list({eff for effects in preset_choices.values() for eff in effects})effect_checkbox = gr.CheckboxGroup(choices=effect_choices, label="Apply Effects in Order")preset_dropdown = gr.Dropdown(choices=preset_names, label="Select Preset", value=preset_names[0])export_format = gr.Dropdown(choices=["WAV", "MP3"], label="Export Format", value="WAV")isolate_vocals = gr.Checkbox(label="Isolate Vocals After Effects")process_btn = gr.Button("Process Audio")with gr.Column():output_audio = gr.Audio(label="Processed Audio", type="numpy")waveform_img = gr.Image(label="Waveform Preview")session_log_out = gr.Textbox(label="Session Log", lines=6)genre_out = gr.Textbox(label="Detected Genre")status_box = gr.Textbox(label="Status", lines=1, value="Ready")preset_dropdown.change(lambda x: preset_choices.get(x, []),inputs=preset_dropdown,outputs=effect_checkbox)def process_wrapper(audio_file, effects, isolate, preset, fmt):effs = preset_choices.get(preset, []) if preset in preset_choices else effectsreturn process_audio(audio_file, effs, isolate, preset, fmt)process_btn.click(process_wrapper,inputs=[input_audio, effect_checkbox, isolate_vocals, preset_dropdown, export_format],outputs=[output_audio, waveform_img, session_log_out, genre_out, status_box])# --- Remix Mode Tab ---with gr.Tab("🎛 Remix Mode"):with gr.Row():with gr.Column():4 unmodified linesdrums_file = gr.File(label="Drums")bass_file = gr.File(label="Bass")other_file = gr.File(label="Other")split_button.click(stem_split,inputs=remix_input,outputs=[vocals_file, drums_file, bass_file, other_file])# --- AI Remastering Tab ---with gr.Tab("🔮 AI Remastering"):remaster_input = gr.Audio(label="Upload Low-Quality Recording", type="filepath")remaster_output = gr.Audio(label="Studio-Grade Output", type="numpy")remaster_status = gr.Textbox(label="Status", value="Ready", interactive=False)remaster_btn = gr.Button("Remaster")remaster_btn.click(remaster_audio := ai_remaster,inputs=remaster_input,outputs=remaster_output)remaster_btn.click(lambda _: "✅ Done!", remaster_btn, remaster_status)# --- Harmonic Saturation Tab ---with gr.Tab("🧬 Harmonic Saturation"):saturation_in = gr.Audio(label="Upload Track", type="filepath")saturation_type = gr.Dropdown(choices=["Tube", "Tape", "Console", "Mix Bus"], label="Saturation Type", value="Tube")saturation_intensity = gr.Slider(minimum=0.1, maximum=1.0, value=0.2, label="Intensity")saturation_out = gr.Audio(label="Warm Output", type="numpy")saturation_btn = gr.Button("Apply Saturation")saturation_btn.click(harmonic_saturation,inputs=[saturation_in, saturation_type, saturation_intensity],outputs=saturation_out)# --- Vocal Doubler / Harmonizer Tab ---with gr.Tab("🎧 Vocal Doubler / Harmonizer"):vocal_in = gr.Audio(label="Upload Vocal Clip", type="filepath")vocal_out = gr.Audio(label="Doubled Output", type="numpy")vocal_status = gr.Textbox(label="Status", interactive=False)vocal_btn = gr.Button("Add Vocal Doubling / Harmony")vocal_btn.click(run_harmony,inputs=vocal_in,outputs=[vocal_out, vocal_status])# --- Batch Processing Tab ---with gr.Tab("🔊 Batch Processing"):batch_files = gr.File(label="Upload Multiple Files", file_count="multiple")batch_effects = gr.CheckboxGroup(choices=effect_choices, label="Apply Effects in Order")batch_isolate = gr.Checkbox(label="Isolate Vocals After Effects")batch_preset = gr.Dropdown(choices=preset_names, label="Select Preset", value=preset_names[0])batch_export_format = gr.Dropdown(choices=["MP3", "WAV"], label="Export Format", value="MP3")batch_process_btn = gr.Button("Process All Files")batch_download = gr.File(label="Download ZIP of All Processed Files")batch_status = gr.Textbox(label="Status", interactive=False)batch_process_btn.click(batch_process_audio,inputs=[batch_files, batch_effects, batch_isolate, batch_preset, batch_export_format],outputs=[batch_download, batch_status])# --- AI Auto-Tune Tab ---with gr.Tab("🎤 AI Auto-Tune"):autotune_file = gr.File(label="Source Voice Clip")autotune_key = gr.Textbox(label="Target Key", value="C", lines=1)autotune_out = gr.Audio(label="Pitch-Corrected Output", type="numpy")autotune_btn = gr.Button("Apply Auto-Tune")autotune_btn.click(fn=auto_tune_vocal, inputs=[autotune_file, autotune_key], outputs=autotune_out)# --- Frequency Spectrum Tab ---with gr.Tab("📊 Frequency Spectrum"):spectrum_in = gr.Audio(label="Upload Track", type="filepath")spectrum_out = gr.Image(label="Frequency Spectrum")spectrum_btn = gr.Button("Visualize Spectrum")spectrum_btn.click(fn=visualize_spectrum, inputs=spectrum_in, outputs=spectrum_out)# --- Loudness Graph Tab ---with gr.Tab("📈 Loudness Graph"):loudness_in = gr.Audio(label="Upload Track", type="filepath")loudness_target = gr.Slider(minimum=-24, maximum=-6, value=-14, step=0.5, label="Target LUFS")loudness_out = gr.Audio(label="Normalized Output", type="numpy")loudness_btn = gr.Button("Match Loudness")loudness_btn.click(fn=match_loudness, inputs=[loudness_in, loudness_target], outputs=loudness_out)# --- Save/Load Project Tab ---with gr.Tab("📁 Save/Load Project"):with gr.Row():with gr.Column():proj_audio = gr.File(label="Original Audio")proj_preset = gr.Dropdown(choices=preset_names, label="Used Preset", value=preset_names[0])proj_effects = gr.CheckboxGroup(choices=list({e for effects in preset_choices.values() for e in effects}), label="Applied Effects")save_proj_btn = gr.Button("Save Project")saved_proj_file = gr.File(label="Project File (.aiproj)")with gr.Column():load_proj_file = gr.File(label="Load .aiproj File")loaded_preset = gr.Dropdown(choices=preset_names, label="Loaded Preset")loaded_effects = gr.CheckboxGroup(choices=list({e for effects in preset_choices.values() for e in effects}), label="Loaded Effects")load_proj_btn = gr.Button("Load Project")save_proj_btn.click(fn=save_project, inputs=[proj_audio, proj_preset, proj_effects], outputs=saved_proj_file)load_proj_btn.click(fn=load_project, inputs=load_proj_file, outputs=[loaded_preset, loaded_effects])# --- Prompt-Based Editing Tab ---with gr.Tab("🧠 Prompt-Based Editing"):prompt_audio = gr.File(label="Upload Audio", file_types=[".wav", ".mp3"])prompt_text = gr.Textbox(label="Describe What You Want", lines=5)prompt_out = gr.Audio(label="Edited Output", type="numpy")prompt_btn = gr.Button("Process Prompt")prompt_btn.click(fn=process_prompt, inputs=[prompt_audio, prompt_text], outputs=prompt_out)# --- Custom EQ Editor Tab ---with gr.Tab("🎛 Custom EQ Editor"):eq_audio = gr.Audio(label="Upload Track", type="filepath")eq_genre = gr.Dropdown(choices=list(eq_map.keys()), value="Pop", label="Genre")eq_output = gr.Audio(label="EQ-Enhanced Output", type="numpy")eq_btn = gr.Button("Apply EQ")eq_btn.click(fn=auto_eq, inputs=[eq_audio, eq_genre], outputs=eq_output)# --- A/B Compare Tab ---with gr.Tab("🎯 A/B Compare"):ab_track1 = gr.Audio(label="Version A", type="filepath")ab_track2 = gr.Audio(label="Version B", type="filepath")ab_output1 = gr.Audio(label="Version A", type="filepath")ab_output2 = gr.Audio(label="Version B", type="filepath")ab_btn = gr.Button("Compare")ab_btn.click(fn=compare_ab, inputs=[ab_track1, ab_track2], outputs=[ab_output1, ab_output2])# --- Loop Playback Tab ---with gr.Tab("🔁 Loop Playback"):loop_audio = gr.Audio(label="Upload Track", type="filepath")loop_start = gr.Slider(minimum=0, maximum=30000, step=100, value=5000, label="Start MS")1 unmodified lineloop_repeat = gr.Slider(minimum=1, maximum=10, value=2, label="Repeat Loops")loop_out = gr.Audio(label="Looped Output", type="numpy")loop_btn = gr.Button("Loop Section")loop_btn.click(fn=loop_section, inputs=[loop_audio, loop_start, loop_end, loop_repeat], outputs=loop_out)# --- Share Effect Chain Tab ---with gr.Tab("🔗 Share Effect Chain"):share_effects = gr.CheckboxGroup(choices=list({e for effects in preset_choices.values() for e in effects}), label="Select Effects")share_code = gr.Textbox(label="Share Code", lines=2)share_btn = gr.Button("Generate Share Code")share_btn.click(fn=lambda x: json.dumps(sorted(x)), inputs=share_effects, outputs=share_code)# --- Load Shared Chain Tab ---with gr.Tab("📥 Load Shared Chain"):load_code = gr.Textbox(label="Paste Shared Code", lines=2)loaded_effects = gr.CheckboxGroup(choices=list({e for effects in preset_choices.values() for e in effects}), label="Loaded Effects")load_code_btn = gr.Button("Load Effects")def load_shared_code(code_str):try:return json.loads(code_str)except:return []load_code_btn.click(fn=load_shared_code, inputs=load_code, outputs=loaded_effects)# --- Keyboard Shortcuts Tab ---with gr.Tab("⌨ Keyboard Shortcuts"):gr.Markdown("""### Keyboard Controls6 unmodified lines- `Ctrl + V`: Paste effect chain""")# --- Vocal Formant Correction Tab ---with gr.Tab("🧑🎤 Vocal Formant Correction"):formant_audio = gr.Audio(label="Upload Vocal Track", type="filepath")formant_shift = gr.Slider(minimum=-2, maximum=2, value=1.0, step=0.1, label="Formant Shift")formant_output = gr.Audio(label="Natural-Sounding Vocal", type="numpy")formant_btn = gr.Button("Apply Correction")formant_btn.click(fn=lambda audio, shift: array_to_audiosegment(librosa.effects.pitch_shift(np.array(AudioSegment.from_file(audio).get_array_of_samples()), sr=AudioSegment.from_file(audio).frame_rate, n_steps=shift).astype(np.int16),AudioSegment.from_file(audio).frame_rate,channels=AudioSegment.from_file(audio).channels), inputs=[formant_audio, formant_shift], outputs=formant_output)# --- Voice Swap / Cloning Tab ---with gr.Tab("🔁 Voice Swap / Cloning"):source_voice = gr.File(label="Source Voice Clip")reference_voice = gr.File(label="Reference Voice")clone_output = gr.Audio(label="Converted Output", type="numpy")clone_btn = gr.Button("Clone Voice")def clone_func(source, ref):s = AudioSegment.from_file(source.name)r = AudioSegment.from_file(ref.name)mixed = s.overlay(r - 10)tmp = save_audiosegment_to_temp(mixed, ".wav")return load_audiofile_to_numpy(tmp)clone_btn.click(clone_func, inputs=[source_voice, reference_voice], outputs=clone_output)# --- DAW Template Export Tab ---with gr.Tab("🎛 DAW Template Export"):daw_stems = gr.File(label="Upload Stems", file_count="multiple")daw_output = gr.File(label="DAW Template (.json/.als/.flp)")daw_btn = gr.Button("Generate Template")def generate_template(stems):template = {"format": "Ableton Live",6 unmodified lineswith open(out_path, "w") as f:json.dump(template, f, indent=2)return out_pathdaw_btn.click(generate_template, inputs=daw_stems, outputs=daw_output)# --- Export Full Mix ZIP Tab ---with gr.Tab("📁 Export Full Mix ZIP"):stems_files = gr.File(label="Stems", file_count="multiple")final_mix_file = gr.File(label="Final Mix")full_zip_output = gr.File(label="Full Mix Archive (.zip)")export_zip_btn = gr.Button("Export ZIP")def export_zip(stems, final_mix):zip_path = os.path.join(tempfile.gettempdir(), "full_export.zip")with zipfile.ZipFile(zip_path, "w") as zipf:1 unmodified linezipf.write(stem.name, f"stem_{i}.wav")zipf.write(final_mix.name, "final_mix.wav")return zip_pathexport_zip_btn.click(export_zip, inputs=[stems_files, final_mix_file], outputs=full_zip_output)demo.launch()12345678910111213141516171819202122232425262728293031323334353637383940414 unmodified lines4647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611 unmodified line1631641651661671681691701711721731741751761771781791801811821831841856 unmodified lines1921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382396 unmodified lines2462472482492502512522532542552562572582592602611 unmodified line263264265266267268269with gr.Blocks() as demo:gr.HTML('<h3 style="text-align:center;">Where Your Audio Meets Intelligence</h3>')gr.Markdown('### Upload, edit, export — powered by AI!')# 1. Single File Studiowith gr.Tab("🎵 Single File Studio"):with gr.Row():with gr.Column():input_audio = gr.Audio(label="Upload Audio", type="filepath")effect_checkbox = gr.CheckboxGroup(choices=list({e for effects in preset_choices.values() for e in effects}),label="Apply Effects in Order")preset_dropdown = gr.Dropdown(choices=preset_names, label="Select Preset", value=preset_names[0])export_format = gr.Dropdown(choices=["WAV", "MP3"], label="Export Format", value="WAV")isolate_vocals = gr.Checkbox(label="Isolate Vocals After Effects")process_btn = gr.Button("Process Audio")with gr.Column():output_audio = gr.Audio(label="Processed Audio", type="numpy")waveform_img = gr.Image(label="Waveform Preview")session_log_out = gr.Textbox(label="Session Log", lines=6)genre_out = gr.Textbox(label="Detected Genre")status_box = gr.Textbox(label="Status", lines=1, value="Ready")def update_effects_for_preset(preset_name):return preset_choices.get(preset_name, [])preset_dropdown.change(update_effects_for_preset, inputs=preset_dropdown, outputs=effect_checkbox)def process_wrapper(audio_path, effects, isolate, preset, fmt):effs = preset_choices.get(preset, []) if preset in preset_choices else effectsreturn process_audio(audio_path, effs, isolate, preset, fmt)process_btn.click(process_wrapper,inputs=[input_audio, effect_checkbox, isolate_vocals, preset_dropdown, export_format],outputs=[output_audio, waveform_img, session_log_out, genre_out, status_box])# 2. Remix Modewith gr.Tab("🎛 Remix Mode"):with gr.Row():with gr.Column():4 unmodified linesdrums_file = gr.File(label="Drums")bass_file = gr.File(label="Bass")other_file = gr.File(label="Other")split_button.click(stem_split, inputs=remix_input, outputs=[vocals_file, drums_file, bass_file, other_file])# 3. AI Remasteringwith gr.Tab("🔮 AI Remastering"):remaster_input = gr.Audio(label="Upload Low-Quality Recording", type="filepath")remaster_output = gr.Audio(label="Studio-Grade Output", type="numpy")remaster_status = gr.Textbox(label="Status", value="Ready", interactive=False)remaster_btn = gr.Button("Remaster")remaster_btn.click(ai_remaster, inputs=remaster_input, outputs=remaster_output)remaster_btn.click(lambda _: "Done!", remaster_btn, remaster_status)# 4. Harmonic Saturationwith gr.Tab("🧬 Harmonic Saturation"):saturation_in = gr.Audio(label="Upload Track", type="filepath")saturation_type = gr.Dropdown(choices=["Tube", "Tape", "Console", "Mix Bus"], label="Saturation Type", value="Tube")saturation_intensity = gr.Slider(minimum=0.1, maximum=1.0, value=0.2, label="Intensity")saturation_out = gr.Audio(label="Warm Output", type="numpy")sat_btn = gr.Button("Apply Saturation")sat_btn.click(harmonic_saturation,inputs=[saturation_in, saturation_type, saturation_intensity],outputs=saturation_out)# 5. Vocal Doubler / Harmonizerwith gr.Tab("🎧 Vocal Doubler / Harmonizer"):vocal_in = gr.Audio(label="Upload Vocal Clip", type="filepath")vocal_out = gr.Audio(label="Doubled Output", type="numpy")vocal_status = gr.Textbox(label="Status", interactive=False)vocal_btn = gr.Button("Add Vocal Doubling / Harmony")vocal_btn.click(run_harmony, inputs=vocal_in, outputs=[vocal_out, vocal_status])# 6. Batch Processingwith gr.Tab("🔊 Batch Processing"):batch_files = gr.File(label="Upload Multiple Files", file_count="multiple")batch_effects = gr.CheckboxGroup(choices=list({e for effs in preset_choices.values() for e in effs}), label="Apply Effects in Order")batch_isolate = gr.Checkbox(label="Isolate Vocals After Effects")batch_preset = gr.Dropdown(choices=preset_names, label="Select Preset", value=preset_names[0])batch_export = gr.Dropdown(choices=["MP3", "WAV"], label="Export Format", value="MP3")batch_btn = gr.Button("Process All Files")batch_zip = gr.File(label="Download All Processed Files (ZIP)")batch_status = gr.Textbox(label="Status", interactive=False)batch_btn.click(batch_process_audio,inputs=[batch_files, batch_effects, batch_isolate, batch_preset, batch_export],outputs=[batch_zip, batch_status])# 7. AI Auto-Tunewith gr.Tab("🎤 AI Auto-Tune"):autotune_file = gr.File(label="Source Voice Clip")autotune_key = gr.Textbox(label="Target Key", value="C", lines=1)autotune_out = gr.Audio(label="Pitch-Corrected Output", type="numpy")autotune_btn = gr.Button("Apply Auto-Tune")autotune_btn.click(auto_tune_vocal, inputs=[autotune_file, autotune_key], outputs=autotune_out)# 8. Frequency Spectrumwith gr.Tab("📊 Frequency Spectrum"):spectrum_in = gr.Audio(label="Upload Track", type="filepath")spectrum_out = gr.Image(label="Frequency Spectrum")spectrum_btn = gr.Button("Visualize Spectrum")spectrum_btn.click(visualize_spectrum, inputs=spectrum_in, outputs=spectrum_out)# 9. Loudness Graphwith gr.Tab("📈 Loudness Graph"):loudness_in = gr.Audio(label="Upload Track", type="filepath")loudness_target = gr.Slider(minimum=-24, maximum=-6, value=-14, label="Target LUFS")loudness_out = gr.Audio(label="Normalized Output", type="numpy")loudness_btn = gr.Button("Match Loudness")loudness_btn.click(match_loudness, inputs=[loudness_in, loudness_target], outputs=loudness_out)# 10. Save/Load Projectwith gr.Tab("📁 Save/Load Project"):with gr.Row():with gr.Column():project_audio = gr.File(label="Original Audio")project_preset = gr.Dropdown(choices=preset_names, label="Used Preset", value=preset_names[0])project_effects = gr.CheckboxGroup(choices=list({e for effs in preset_choices.values() for e in effs}), label="Applied Effects")save_proj_btn = gr.Button("Save Project")project_file = gr.File(label="Project File (.aiproj)")with gr.Column():load_proj_file = gr.File(label="Load .aiproj File")loaded_preset = gr.Dropdown(choices=preset_names, label="Loaded Preset")loaded_effects = gr.CheckboxGroup(choices=list({e for effs in preset_choices.values() for e in effs}), label="Loaded Effects")load_proj_btn = gr.Button("Load Project")save_proj_btn.click(save_project, inputs=[project_audio, project_preset, project_effects], outputs=project_file)load_proj_btn.click(load_project, inputs=load_proj_file, outputs=[loaded_preset, loaded_effects])# 11. Prompt-Based Editingwith gr.Tab("🧠 Prompt-Based Editing"):prompt_audio = gr.File(label="Upload Audio", file_types=[".wav", ".mp3"])prompt_text = gr.Textbox(label="Describe What You Want", lines=5)prompt_out = gr.Audio(label="Edited Output", type="numpy")prompt_btn = gr.Button("Process Prompt")prompt_btn.click(process_prompt, inputs=[prompt_audio, prompt_text], outputs=prompt_out)# 12. Custom EQ Editorwith gr.Tab("🎛 Custom EQ Editor"):eq_audio = gr.Audio(label="Upload Track", type="filepath")eq_genre = gr.Dropdown(choices=list(eq_map.keys()), value="Pop", label="Genre")eq_output = gr.Audio(label="EQ-Enhanced Output", type="numpy")eq_btn = gr.Button("Apply EQ")eq_btn.click(auto_eq, inputs=[eq_audio, eq_genre], outputs=eq_output)# 13. A/B Comparewith gr.Tab("🎯 A/B Compare"):ab_track1 = gr.Audio(label="Version A", type="filepath")ab_track2 = gr.Audio(label="Version B", type="filepath")ab_out1 = gr.Audio(label="Version A", type="filepath")ab_out2 = gr.Audio(label="Version B", type="filepath")ab_btn = gr.Button("Compare")ab_btn.click(compare_ab, inputs=[ab_track1, ab_track2], outputs=[ab_out1, ab_out2])# 14. Loop Playbackwith gr.Tab("🔁 Loop Playback"):loop_audio = gr.Audio(label="Upload Track", type="filepath")loop_start = gr.Slider(minimum=0, maximum=30000, step=100, value=5000, label="Start MS")1 unmodified lineloop_repeat = gr.Slider(minimum=1, maximum=10, value=2, label="Repeat Loops")loop_out = gr.Audio(label="Looped Output", type="numpy")loop_btn = gr.Button("Loop Section")loop_btn.click(loop_section, inputs=[loop_audio, loop_start, loop_end, loop_repeat], outputs=loop_out)# 15. Share Effect Chain Tabwith gr.Tab("🔗 Share Effect Chain"):share_effects = gr.CheckboxGroup(choices=list({e for effs in preset_choices.values() for e in effs}), label="Select Effects")share_code = gr.Textbox(label="Share Code", lines=2)share_btn = gr.Button("Generate Share Code")share_btn.click(lambda x: json.dumps(sorted(x)), inputs=share_effects, outputs=share_code)# 16. Load Shared Chain Tabwith gr.Tab("📥 Load Shared Chain"):load_code = gr.Textbox(label="Paste Shared Code", lines=2)loaded_effects = gr.CheckboxGroup(choices=list({e for effs in preset_choices.values() for e in effs}), label="Loaded Effects")load_code_btn = gr.Button("Load Effects")load_code_btn.click(lambda code: json.loads(code) if code else [], inputs=load_code, outputs=loaded_effects)# 17. Keyboard Shortcuts Tabwith gr.Tab("⌨ Keyboard Shortcuts"):gr.Markdown("""### Keyboard Controls6 unmodified lines- `Ctrl + V`: Paste effect chain""")# 18. Vocal Formant Correction Tabwith gr.Tab("🧑🎤 Vocal Formant Correction"):formant_audio = gr.Audio(label="Upload Vocal Track", type="filepath")formant_shift = gr.Slider(minimum=-2, maximum=2, value=1.0, step=0.1, label="Formant Shift")formant_output = gr.Audio(label="Natural-Sounding Vocal", type="numpy")formant_btn = gr.Button("Apply Correction")formant_btn.click(lambda audio, shift: array_to_audiosegment(librosa.effects.pitch_shift(np.array(AudioSegment.from_file(audio).get_array_of_samples()),sr=AudioSegment.from_file(audio).frame_rate,n_steps=shift).astype(np.int16),AudioSegment.from_file(audio).frame_rate,channels=AudioSegment.from_file(audio).channels),inputs=[formant_audio, formant_shift],outputs=formant_output)# 19. Voice Swap / Cloning Tabwith gr.Tab("🔁 Voice Swap / Cloning"):source_voice = gr.File(label="Source Voice Clip")reference_voice = gr.File(label="Reference Voice")clone_output = gr.Audio(label="Converted Output", type="numpy")clone_btn = gr.Button("Clone Voice")def clone_func(source, ref):s = AudioSegment.from_file(source.name)r = AudioSegment.from_file(ref.name)mixed = s.overlay(r - 10)tmp = save_audiosegment_to_temp(mixed, ".wav")return load_audiofile_to_numpy(tmp)clone_btn.click(clone_func, inputs=[source_voice, reference_voice], outputs=clone_output)# 20. DAW Template Export Tabwith gr.Tab("🎛 DAW Template Export"):daw_stems = gr.File(label="Upload Stems", file_count="multiple")daw_output = gr.File(label="DAW Template (.json/.als/.flp)")daw_btn = gr.Button("Generate Template")def generate_template(stems):template = {"format": "Ableton Live",6 unmodified lineswith open(out_path, "w") as f:json.dump(template, f, indent=2)return out_pathdaw_btn.click(generate_template, inputs=daw_stems, outputs=daw_output)# 21. Export Full Mix ZIP Tabwith gr.Tab("📁 Export Full Mix ZIP"):stems_files = gr.File(label="Stems", file_count="multiple")final_mix_file = gr.File(label="Final Mix")full_zip_output = gr.File(label="Full Mix Archive (.zip)")export_zip_btn = gr.Button("Export ZIP")def export_zip(stems, final_mix):zip_path = os.path.join(tempfile.gettempdir(), "full_export.zip")with zipfile.ZipFile(zip_path, "w") as zipf:1 unmodified linezipf.write(stem.name, f"stem_{i}.wav")zipf.write(final_mix.name, "final_mix.wav")return zip_pathexport_zip_btn.click(export_zip, inputs=[stems_files, final_mix_file], outputs=full_zip_output)demo.launch()
app.py+92-649