Improved AWS Polly eh

improved handling for errors like
like #929
pull/880/head
Jason 3 years ago
parent 1872ef36c1
commit a7c54f48e8

@ -1,6 +1,6 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
from boto3 import Session from boto3 import Session
from botocore.exceptions import BotoCoreError, ClientError from botocore.exceptions import BotoCoreError, ClientError, ProfileNotFound
import sys import sys
from utils import settings from utils import settings
import random import random
@ -30,36 +30,44 @@ class AWSPolly:
self.voices = voices self.voices = voices
def run(self, text, filepath, random_voice: bool = False): def run(self, text, filepath, random_voice: bool = False):
session = Session(profile_name="polly")
polly = session.client("polly")
if random_voice:
voice = self.randomvoice()
else:
if not settings.config["settings"]["tts"]["aws_polly_voice"]:
return ValueError(
f"Please set the TOML variable AWS_VOICE to a valid voice. options are: {voices}"
)
voice = str(settings.config["settings"]["tts"]["aws_polly_voice"]).capitalize()
try: try:
# Request speech synthesis session = Session(profile_name="polly")
response = polly.synthesize_speech( polly = session.client("polly")
Text=text, OutputFormat="mp3", VoiceId=voice, Engine="neural" if random_voice:
) voice = self.randomvoice()
except (BotoCoreError, ClientError) as error: else:
# The service returned an error, exit gracefully if not settings.config["settings"]["tts"]["aws_polly_voice"]:
print(error) return ValueError(
sys.exit(-1) f"Please set the TOML variable AWS_VOICE to a valid voice. options are: {voices}"
)
voice = str(settings.config["settings"]["tts"]["aws_polly_voice"]).capitalize()
try:
# Request speech synthesis
response = polly.synthesize_speech(
Text=text, OutputFormat="mp3", VoiceId=voice, Engine="neural"
)
except (BotoCoreError, ClientError) as error:
# The service returned an error, exit gracefully
print(error)
sys.exit(-1)
# Access the audio stream from the response # Access the audio stream from the response
if "AudioStream" in response: if "AudioStream" in response:
file = open(filepath, "wb") file = open(filepath, "wb")
file.write(response["AudioStream"].read()) file.write(response["AudioStream"].read())
file.close() file.close()
# print_substep(f"Saved Text {idx} to MP3 files successfully.", style="bold green") # print_substep(f"Saved Text {idx} to MP3 files successfully.", style="bold green")
else: else:
# The response didn't contain audio data, exit gracefully # The response didn't contain audio data, exit gracefully
print("Could not stream audio") print("Could not stream audio")
sys.exit(-1)
except ProfileNotFound:
print("You need to install the AWS CLI and configure your profile")
print("""
Linux: https://docs.aws.amazon.com/polly/latest/dg/setup-aws-cli.html
Windows: https://docs.aws.amazon.com/polly/latest/dg/install-voice-plugin2.html
""")
sys.exit(-1) sys.exit(-1)
def randomvoice(self): def randomvoice(self):

Loading…
Cancel
Save