Spaces:
Sleeping
Sleeping
import gradio as gr | |
from pydub import AudioSegment | |
import noisereduce as nr | |
import numpy as np | |
import tempfile | |
import os | |
# Helper: Convert AudioSegment to numpy array and back | |
def audiosegment_to_array(audio_segment): | |
return np.array(audio_segment.get_array_of_samples()), audio_segment.frame_rate | |
# Apply effect functions | |
def apply_normalize(audio): | |
return audio.normalize() | |
def apply_noise_reduction(audio): | |
samples, frame_rate = audiosegment_to_array(audio) | |
reduced_noise = nr.reduce_noise(y=samples, sr=frame_rate) | |
return AudioSegment( | |
reduced_noise.tobytes(), | |
frame_rate=frame_rate, | |
sample_width=reduced_noise.dtype.itemsize, | |
channels=audio.channels | |
) | |
def apply_compression(audio): | |
return audio.compress_dynamic_range() | |
def apply_reverb(audio): | |
# Simulate reverb by overlaying a delayed, quieter copy | |
reverb_audio = audio - 10 # Lower volume | |
return audio.overlay(reverb_audio, position=1000) | |
def apply_pitch_shift(audio, semitones=-2): | |
return audio._spawn(audio._array_type( | |
np.interp( | |
np.arange(0, len(audio), 2 ** (semitones / 12)), | |
np.arange(len(audio)), | |
audio.get_array_of_samples() | |
).astype(np.int16).tolist() | |
), overrides={"frame_rate": int(audio.frame_rate * (2 ** (semitones / 12)))}) | |
# Main processing function | |
def process_audio(audio_file, effect): | |
audio = AudioSegment.from_file(audio_file) | |
if effect == "Normalize": | |
result = apply_normalize(audio) | |
elif effect == "Noise Reduction": | |
result = apply_noise_reduction(audio) | |
elif effect == "Compress Dynamic Range": | |
result = apply_compression(audio) | |
elif effect == "Add Reverb": | |
result = apply_reverb(audio) | |
elif effect == "Pitch Shift": | |
result = apply_pitch_shift(audio, semitones=-2) # Down 2 semitones | |
else: | |
result = audio # No effect | |
with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as f: | |
result.export(f.name, format="wav") | |
return f.name | |
# Gradio Interface | |
interface = gr.Interface( | |
fn=process_audio, | |
inputs=[ | |
gr.Audio(label="Upload Audio", type="filepath"), | |
gr.Dropdown( | |
choices=[ | |
"Normalize", | |
"Noise Reduction", | |
"Compress Dynamic Range", | |
"Add Reverb", | |
"Pitch Shift" | |
], | |
label="Select Effect" | |
) | |
], | |
outputs=gr.Audio(label="Processed Audio", type="filepath"), | |
title="Fix My Recording - Advanced Edition", | |
description="Upload your audio to clean, master, and add creative effects with AI!" | |
) | |
interface.launch() |