import gradio as gr
from pydub import AudioSegment

def change_audio_speed(audio_file, speed):
    if not audio_file:
        return "Please upload an audio file."

    try:
        # Load the audio file
        print("inside try of audio call")
        audio = AudioSegment.from_file(audio_file, format="wav")

        # Modify speed
        new_audio = audio._spawn(audio.raw_data, overrides={
            "frame_rate": int(audio.frame_rate * speed)
        }).set_frame_rate(audio.frame_rate)

        # Save the processed file
        output_path = "output.mp3"
        new_audio.export(output_path, format="mp3")

        return output_path

    except Exception as e:
        print("inside except of audio call", str(e))
        return str(e)

# Gradio UI
with gr.Blocks() as demo:
    gr.Markdown("# 🎵 Audio Speed Modifier with ElevenLabs API Key Input")
    
    with gr.Row():
        audio_input = gr.File(label="Upload MP3 Audio")
        api_key = gr.Textbox(label="Enter ElevenLabs API Key", type="password")
    
    speed_slider = gr.Slider(0.5, 3.0, 1.2, step=0.1, label="Speed Factor (1.2x = 20% faster)")

    output_audio = gr.Audio(label="Processed Audio", type="filepath")

    process_button = gr.Button("Process Audio")

    process_button.click(change_audio_speed, inputs=[audio_input, speed_slider], outputs=output_audio)


demo.launch(debug=True)