Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
elebumm
GitHub Repository: elebumm/RedditVideoMakerBot
Path: blob/master/TTS/aws_polly.py
327 views
1
import random
2
import sys
3
4
from boto3 import Session
5
from botocore.exceptions import BotoCoreError, ClientError, ProfileNotFound
6
7
from utils import settings
8
9
voices = [
10
"Brian",
11
"Emma",
12
"Russell",
13
"Joey",
14
"Matthew",
15
"Joanna",
16
"Kimberly",
17
"Amy",
18
"Geraint",
19
"Nicole",
20
"Justin",
21
"Ivy",
22
"Kendra",
23
"Salli",
24
"Raveena",
25
]
26
27
28
class AWSPolly:
29
def __init__(self):
30
self.max_chars = 3000
31
self.voices = voices
32
33
def run(self, text, filepath, random_voice: bool = False):
34
try:
35
session = Session(profile_name="polly")
36
polly = session.client("polly")
37
if random_voice:
38
voice = self.randomvoice()
39
else:
40
if not settings.config["settings"]["tts"]["aws_polly_voice"]:
41
raise ValueError(
42
f"Please set the TOML variable AWS_VOICE to a valid voice. options are: {voices}"
43
)
44
voice = str(settings.config["settings"]["tts"]["aws_polly_voice"]).capitalize()
45
try:
46
# Request speech synthesis
47
response = polly.synthesize_speech(
48
Text=text, OutputFormat="mp3", VoiceId=voice, Engine="neural"
49
)
50
except (BotoCoreError, ClientError) as error:
51
# The service returned an error, exit gracefully
52
print(error)
53
sys.exit(-1)
54
55
# Access the audio stream from the response
56
if "AudioStream" in response:
57
file = open(filepath, "wb")
58
file.write(response["AudioStream"].read())
59
file.close()
60
# print_substep(f"Saved Text {idx} to MP3 files successfully.", style="bold green")
61
62
else:
63
# The response didn't contain audio data, exit gracefully
64
print("Could not stream audio")
65
sys.exit(-1)
66
except ProfileNotFound:
67
print("You need to install the AWS CLI and configure your profile")
68
print(
69
"""
70
Linux: https://docs.aws.amazon.com/polly/latest/dg/setup-aws-cli.html
71
Windows: https://docs.aws.amazon.com/polly/latest/dg/install-voice-plugin2.html
72
"""
73
)
74
sys.exit(-1)
75
76
def randomvoice(self):
77
return random.choice(self.voices)
78
79