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