import gradio as gr import torch import torchaudio from encodec import EncodecModel from encodec.utils import convert_audio from encodec.compress import compress, decompress import io # Load the Encodec model model = EncodecModel.encodec_model_48khz() # Use the encodec version of the model model.set_target_bandwidth(6.0) # Set the desired bandwidth @spaces.GPU def encode(audio_file_path): try: # Load and pre-process the audio waveform wav, sr = torchaudio.load(audio_file_path) wav = convert_audio(wav, sr, model.sample_rate, model.channels) wav = wav.unsqueeze(0) # Compress to ecdc file in memory compressed_audio = compress(model, wav) # Save compressed audio to BytesIO output = io.BytesIO(compressed_audio) output.seek(0) return output except Exception as e: gr.Warning(f"An error occurred during encoding: {e}") return None @spaces.GPU def decode(compressed_audio_file): try: # Load compressed audio compressed_audio = compressed_audio_file.read() # Decompress audio wav, sr = decompress(compressed_audio) # Convert the decoded audio to a numpy array for Gradio output decoded_audio = wav.cpu().numpy() return decoded_audio except Exception as e: gr.Warning(f"An error occurred during decoding: {e}") return None # Gradio interface with gr.Blocks() as demo: gr.Markdown("

Audio Compression with Encodec

") with gr.Tab("Encode"): with gr.Row(): audio_input = gr.Audio(type="filepath", label="Input Audio") encode_button = gr.Button("Encode", variant="primary") with gr.Row(): encoded_output = gr.File(label="Compressed Audio (.ecdc)") encode_button.click(encode, inputs=audio_input, outputs=encoded_output) with gr.Tab("Decode"): with gr.Row(): compressed_input = gr.File(label="Compressed Audio (.ecdc)") decode_button = gr.Button("Decode", variant="primary") with gr.Row(): decoded_output = gr.Audio(label="Decompressed Audio") decode_button.click(decode, inputs=compressed_input, outputs=decoded_output) demo.queue().launch()