File size: 2,198 Bytes
f18f98b
 
7e97379
 
 
fb74527
ab12e78
c27eb74
7e97379
c27eb74
7e97379
c27eb74
 
ab12e78
c27eb74
7e97379
 
 
c27eb74
7e97379
 
 
 
c27eb74
7e97379
c27eb74
 
 
 
 
 
ab12e78
c27eb74
ab12e78
7e97379
 
c27eb74
ab12e78
c27eb74
 
 
 
 
 
 
d07be48
 
 
44bab11
f18f98b
c27eb74
 
 
 
ab12e78
44bab11
c6e9cf1
44bab11
f18f98b
c27eb74
ab12e78
c27eb74
 
 
44bab11
ab12e78
f18f98b
c27eb74
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import gradio as gr
import torch
import torchaudio
from transformers import EncodecModel
from encodec.utils import convert_audio
from encodec.compress import compress_to_file, decompress_from_file # Import from the correct module
import io

# Load the Encodec model 
model = EncodecModel.from_pretrained("facebook/encodec_48khz")
model.set_target_bandwidth(6.0)  # Set the desired bandwidth (adjust as needed)

@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)

        # Compress to ecdc file in memory
        output = io.BytesIO()
        compress_to_file(model, wav, output) 
        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:
        # Decompress audio
        wav, sr = decompress_from_file(compressed_audio_file)

        # 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("<h1 style='text-align: center;'>Audio Compression with Encodec</h1>")

    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()