|
import streamlit as st |
|
from openai import OpenAI |
|
import os |
|
from pathlib import Path |
|
import base64 |
|
|
|
def create_audio_player(audio_path): |
|
"""Create an HTML audio player for the generated audio file""" |
|
audio_file = open(audio_path, 'rb') |
|
audio_bytes = audio_file.read() |
|
audio_base64 = base64.b64encode(audio_bytes).decode() |
|
audio_player = f'<audio controls><source src="data:audio/mp3;base64,{audio_base64}" type="audio/mp3"></audio>' |
|
return audio_player |
|
|
|
def main(): |
|
st.title("🗣️ Text to Speech with OpenAI") |
|
|
|
|
|
with st.sidebar: |
|
st.header("Configuration") |
|
api_key = st.text_input("Enter your OpenAI API key", type="password") |
|
st.markdown(""" |
|
### How to get an API key |
|
1. Go to [OpenAI API Keys](https://platform.openai.com/api-keys) |
|
2. Create a new secret key |
|
3. Copy and paste it here |
|
""") |
|
|
|
|
|
st.markdown("Convert your text to natural-sounding speech using OpenAI's TTS API.") |
|
|
|
|
|
user_input = st.text_area("Enter the text you want to convert to speech:", |
|
height=150, |
|
placeholder="Enter your text here...") |
|
|
|
|
|
voice_option = st.selectbox( |
|
"Select a voice:", |
|
["alloy", "echo", "fable", "onyx", "nova", "shimmer"] |
|
) |
|
|
|
|
|
if st.button("Generate Speech"): |
|
if not api_key: |
|
st.error("Please enter your OpenAI API key in the sidebar.") |
|
return |
|
|
|
if not user_input: |
|
st.error("Please enter some text to convert to speech.") |
|
return |
|
|
|
try: |
|
|
|
with st.spinner("Generating audio..."): |
|
|
|
client = OpenAI(api_key=api_key) |
|
|
|
|
|
output_dir = Path("generated_audio") |
|
output_dir.mkdir(exist_ok=True) |
|
|
|
|
|
output_file = output_dir / "output.mp3" |
|
|
|
|
|
response = client.audio.speech.create( |
|
model="tts-1", |
|
voice=voice_option, |
|
input=user_input |
|
) |
|
|
|
|
|
response.stream_to_file(str(output_file)) |
|
|
|
|
|
st.success("Audio generated successfully!") |
|
|
|
|
|
st.markdown("### Listen to the generated audio:") |
|
st.markdown(create_audio_player(output_file), unsafe_allow_html=True) |
|
|
|
|
|
with open(output_file, "rb") as file: |
|
st.download_button( |
|
label="Download Audio", |
|
data=file, |
|
file_name="generated_speech.mp3", |
|
mime="audio/mp3" |
|
) |
|
|
|
except Exception as e: |
|
st.error(f"An error occurred: {str(e)}") |
|
|
|
if __name__ == "__main__": |
|
main() |