File size: 2,294 Bytes
7766126
 
ed21261
7766126
de3d7cc
ed21261
9d14d08
 
7766126
ed21261
 
 
 
7766126
 
9d14d08
 
 
 
 
 
 
7766126
 
75f7245
7766126
9d14d08
75f7245
9d14d08
c31f72a
 
 
 
ed21261
c31f72a
 
 
ed21261
c31f72a
9d14d08
7766126
c31f72a
 
 
 
ed21261
7e3d4c5
 
 
 
75f7245
7e3d4c5
 
75f7245
7e3d4c5
 
75f7245
7e3d4c5
 
 
 
ed21261
7766126
 
e6a08fe
ed21261
e6a08fe
 
ed21261
7766126
 
ed21261
9d14d08
 
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
70
71
72
73
74
75
import gradio as gr
from elevenlabs.client import ElevenLabs
from elevenlabs.core.api_error import ApiError
import os
import shutil
from dotenv import load_dotenv
from pydub import AudioSegment
import tempfile

# Load environment variables
load_dotenv()

# Initialize the client with your API key
client = ElevenLabs(api_key=os.getenv("ELEVENLABS_API_KEY"))

def is_valid_audio(file_path):
    try:
        AudioSegment.from_file(file_path)
        return True
    except:
        return False

def isolate_audio(audio_file):
    if audio_file is None:
        return None, "Please upload an audio file."
    
    if not is_valid_audio(audio_file):
        return None, "The uploaded file is not a valid audio file. Please ensure it is a playable audio file."

    temp_dir = tempfile.mkdtemp()
    input_file_path = os.path.join(temp_dir, "input_audio.mp3")
    output_file_path = os.path.join(temp_dir, "isolated_audio.mp3")

    try:
        # Copy the input file to our temporary directory
        shutil.copy2(audio_file, input_file_path)

        # Perform audio isolation
        with open(input_file_path, "rb") as file:
            isolated_audio_iterator = client.audio_isolation.audio_isolation(audio=file)

            # Save the isolated audio to the output file
            with open(output_file_path, "wb") as output_file:
                for chunk in isolated_audio_iterator:
                    output_file.write(chunk)

        # Copy the output file to a location that Gradio can access
        gradio_output_path = "gradio_output.mp3"
        shutil.copy2(output_file_path, gradio_output_path)

        return gradio_output_path, "Ruido de fondo eliminado del audio"
    except ApiError as e:
        error_message = f"API Error: {e.body['detail']['message']}"
        return None, error_message
    except Exception as e:
        error_message = f"An unexpected error occurred: {str(e)}"
        return None, error_message
    finally:
        # Clean up temporary files
        shutil.rmtree(temp_dir, ignore_errors=True)

# Create Gradio interface
iface = gr.Interface(
    fn=isolate_audio,
    inputs=gr.Audio(type="filepath", label=""),
    outputs=[
        gr.Audio(type="filepath", label=""),
        gr.Textbox(label="")
    ],
)

# Launch the app
iface.launch()