import streamlit as st
from gtts import gTTS
import os
import base64

# Streamlit app UI
st.title("Text-to-Audio App")
st.text("This app converts your text input into audio using TTS.")

# User input
text_input = st.text_area("Enter some text:")

if st.button("Generate Audio"):
    if not text_input.strip():
        st.error("Please enter some text!")
    else:
        try:
            # Generate speech using gTTS
            tts = gTTS(text=text_input, lang="en")
            audio_file = "output.wav"
            tts.save(audio_file)

            # Check if file exists
            if os.path.exists(audio_file):
                # Encode audio file to base64
                with open(audio_file, "rb") as f:
                    audio_data = f.read()
                audio_base64 = base64.b64encode(audio_data).decode()

                # Embed custom HTML audio player with speed adjustment
                audio_html = f"""
                    <audio id="audio" controls style="width: 100%; margin-top: 10px;">
                        <source src="data:audio/wav;base64,{audio_base64}" type="audio/wav">
                        Your browser does not support the audio element.
                    </audio>
                    <div style="margin-top: 10px;">
                        <label for="speed" style="font-weight: bold;">Playback Speed:</label>
                        <input type="range" id="speed" min="0.5" max="2.0" value="1.0" step="0.1" style="width: 50%; margin-left: 10px;">
                        <span id="speed-value">1.0x</span>
                    </div>
                    <script>
                        const audio = document.getElementById("audio");
                        const speedSlider = document.getElementById("speed");
                        const speedValue = document.getElementById("speed-value");

                        // Update playback speed dynamically
                        speedSlider.addEventListener("input", () => {{
                            const speed = parseFloat(speedSlider.value);
                            audio.playbackRate = speed;
                            speedValue.textContent = speed.toFixed(1) + "x";
                        }});
                    </script>
                """
                st.components.v1.html(audio_html, height=200)

                st.success("Audio generated successfully!")

                # Provide download option
                with open(audio_file, "rb") as f:
                    st.download_button(
                        label="Download Audio",
                        data=f.read(),
                        file_name="output.wav",
                        mime="audio/wav",
                    )
            else:
                st.error("Audio file could not be generated.")
        except Exception as e:
            st.error(f"An error occurred: {e}")