kopia lustrzana https://codeberg.org/pluja/openai-telegram-bot
add error handling for pyttsx3 file writing
rodzic
8871deb5ac
commit
e193bf1989
17
main.py
17
main.py
|
@ -85,8 +85,9 @@ def generate_settings_markup(chat_id: str) -> InlineKeyboardMarkup:
|
||||||
async def text_to_voice(text: str) -> BytesIO:
|
async def text_to_voice(text: str) -> BytesIO:
|
||||||
with tempfile.NamedTemporaryFile(mode='wb', suffix='.ogg', delete=False) as ogg_file:
|
with tempfile.NamedTemporaryFile(mode='wb', suffix='.ogg', delete=False) as ogg_file:
|
||||||
temp_filename = ogg_file.name
|
temp_filename = ogg_file.name
|
||||||
|
|
||||||
voice_done = False
|
voice_done = False
|
||||||
|
|
||||||
|
# If Google TTS is enabled, try to use it first
|
||||||
if ENABLE_GOOGLE_TTS:
|
if ENABLE_GOOGLE_TTS:
|
||||||
try:
|
try:
|
||||||
tts = gTTS(text)
|
tts = gTTS(text)
|
||||||
|
@ -95,6 +96,7 @@ async def text_to_voice(text: str) -> BytesIO:
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print("Google TTS failed, falling back to pyttsx3: --> ", e)
|
print("Google TTS failed, falling back to pyttsx3: --> ", e)
|
||||||
|
|
||||||
|
# If Google TTS is disabled or failed, use pyttsx3
|
||||||
if not voice_done:
|
if not voice_done:
|
||||||
engine = pyttsx3.init()
|
engine = pyttsx3.init()
|
||||||
engine.setProperty('rate', 140)
|
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
|
await asyncio.sleep(0.5) # Add a small delay before reading the file
|
||||||
|
|
||||||
with open(temp_filename, "rb") as audio_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)
|
os.remove(temp_filename)
|
||||||
voice_data.seek(0)
|
voice_data.seek(0)
|
||||||
|
|
Ładowanie…
Reference in New Issue