|
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_dotenv() |
|
|
|
|
|
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: |
|
|
|
shutil.copy2(audio_file, input_file_path) |
|
|
|
|
|
with open(input_file_path, "rb") as file: |
|
isolated_audio_iterator = client.audio_isolation.audio_isolation(audio=file) |
|
|
|
|
|
with open(output_file_path, "wb") as output_file: |
|
for chunk in isolated_audio_iterator: |
|
output_file.write(chunk) |
|
|
|
|
|
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: |
|
|
|
shutil.rmtree(temp_dir, ignore_errors=True) |
|
|
|
|
|
iface = gr.Interface( |
|
fn=isolate_audio, |
|
inputs=gr.Audio(type="filepath", label=""), |
|
outputs=[ |
|
gr.Audio(type="filepath", label=""), |
|
gr.Textbox(label="") |
|
], |
|
) |
|
|
|
|
|
iface.launch() |
|
|
|
|