add error handling for pyttsx3 file writing

main
pluja 2023-04-20 10:10:56 +02:00
rodzic 8871deb5ac
commit e193bf1989
1 zmienionych plików z 15 dodań i 2 usunięć

17
main.py
Wyświetl plik

@ -85,8 +85,9 @@ def generate_settings_markup(chat_id: str) -> InlineKeyboardMarkup:
async def text_to_voice(text: str) -> BytesIO:
with tempfile.NamedTemporaryFile(mode='wb', suffix='.ogg', delete=False) as ogg_file:
temp_filename = ogg_file.name
voice_done = False
# If Google TTS is enabled, try to use it first
if ENABLE_GOOGLE_TTS:
try:
tts = gTTS(text)
@ -95,6 +96,7 @@ async def text_to_voice(text: str) -> BytesIO:
except Exception as e:
print("Google TTS failed, falling back to pyttsx3: --> ", e)
# If Google TTS is disabled or failed, use pyttsx3
if not voice_done:
engine = pyttsx3.init()
engine.setProperty('rate', 140)
@ -103,7 +105,18 @@ async def text_to_voice(text: str) -> BytesIO:
await asyncio.sleep(0.5) # Add a small delay before reading the file
with open(temp_filename, "rb") as audio_file:
voice_data = BytesIO(audio_file.read())
try: # Try to read the file
voice_data = BytesIO(audio_file.read())
except Exception as e:
print(e)
# If reading the file fails, wait 0.6 seconds and try again
await asyncio.sleep(0.6) # Add a small delay before reading the file
try:
voice_data = BytesIO(audio_file.read())
except Exception:
# If reading the file fails again, return None
os.remove(temp_filename)
return
os.remove(temp_filename)
voice_data.seek(0)