AMUseBot/src/utils/tts.py

54 lines
1.4 KiB
Python
Raw Normal View History

2023-03-02 18:58:40 +01:00
from typing import Any, Dict, Optional
2023-03-08 14:07:09 +01:00
from gtts import gTTS, gTTSError, lang
2023-03-02 18:58:40 +01:00
from io import BytesIO
import streamlit as st
2023-03-06 14:27:43 +01:00
DEFAULT_SPEECH_LANG = "English"
2023-03-02 15:32:39 +01:00
def get_dict_key(dictionary: Dict, value: Any) -> Optional[Any]:
for key, val in dictionary.items():
if val == value:
return key
2023-03-02 18:58:40 +01:00
def lang_selector() -> str:
languages = lang.tts_langs()
lang_options = list(lang.tts_langs().values())
default_index = lang_options.index(DEFAULT_SPEECH_LANG)
lang_name = st.selectbox(
2023-03-11 15:39:23 +01:00
label="Select Speech Language",
2023-03-02 18:58:40 +01:00
options=lang_options,
index=default_index
)
return get_dict_key(languages, lang_name)
def speech_speed_radio() -> bool:
speed_options = {
"Normal": False,
"Slow": True
}
speed_speech = st.radio(
2023-03-11 15:39:23 +01:00
label="Select Speech Speed",
2023-03-02 18:58:40 +01:00
options=speed_options.keys(),
)
return speed_options.get(speed_speech)
2023-03-11 15:39:23 +01:00
def show_player(ai_content: str) -> None:
2023-03-02 18:58:40 +01:00
sound_file = BytesIO()
2023-03-11 15:39:23 +01:00
col1, col2 = st.columns(2)
with col1:
lang_code = lang_selector()
with col2:
is_speech_slow = speech_speed_radio()
2023-03-08 14:07:09 +01:00
try:
tts = gTTS(text=ai_content, lang=lang_code, slow=is_speech_slow)
tts.write_to_fp(sound_file)
2023-03-11 15:39:23 +01:00
st.write("To Hear The Voice Of AI, Press Play.")
2023-03-08 14:07:09 +01:00
st.audio(sound_file)
except gTTSError as err:
st.error(err)