Spaces:
Sleeping
Sleeping
Commit
•
9f7e57b
1
Parent(s):
ca7d30b
Upload synthesize_speech.py
Browse files- synthesize_speech.py +49 -0
synthesize_speech.py
ADDED
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import boto3
|
2 |
+
import streamlit as st
|
3 |
+
from contextlib import closing
|
4 |
+
import os
|
5 |
+
import sys
|
6 |
+
import subprocess
|
7 |
+
from tempfile import gettempdir
|
8 |
+
|
9 |
+
Session = boto3.Session(
|
10 |
+
aws_access_key_id = st.secrets['aws_access_key_id'],
|
11 |
+
aws_secret_access_key = st.secrets['aws_secret_access_key'],
|
12 |
+
region_name = "us-east-1"
|
13 |
+
)
|
14 |
+
|
15 |
+
def synthesize_speech(text):
|
16 |
+
Polly = Session.client("polly")
|
17 |
+
response = Polly.synthesize_speech(
|
18 |
+
Text=text,
|
19 |
+
OutputFormat="mp3",
|
20 |
+
VoiceId="Joanna")
|
21 |
+
if "AudioStream" in response:
|
22 |
+
# Note: Closing the stream is important because the service throttles on the
|
23 |
+
# number of parallel connections. Here we are using contextlib.closing to
|
24 |
+
# ensure the close method of the stream object will be called automatically
|
25 |
+
# at the end of the with statement's scope.
|
26 |
+
with closing(response["AudioStream"]) as stream:
|
27 |
+
output = os.path.join(gettempdir(), "speech.mp3")
|
28 |
+
|
29 |
+
try:
|
30 |
+
# Open a file for writing the output as a binary stream
|
31 |
+
with open(output, "wb") as file:
|
32 |
+
file.write(stream.read())
|
33 |
+
except IOError as error:
|
34 |
+
# Could not write to file, exit gracefully
|
35 |
+
print(error)
|
36 |
+
sys.exit(-1)
|
37 |
+
else:
|
38 |
+
# The response didn't contain audio data, exit gracefully
|
39 |
+
print("Could not stream audio")
|
40 |
+
sys.exit(-1)
|
41 |
+
'''
|
42 |
+
# Play the audio using the platform's default player
|
43 |
+
if sys.platform == "win32":
|
44 |
+
os.startfile(output)
|
45 |
+
else:
|
46 |
+
# The following works on macOS and Linux. (Darwin = mac, xdg-open = linux).
|
47 |
+
opener = "open" if sys.platform == "darwin" else "xdg-open"
|
48 |
+
subprocess.call([opener, output])'''
|
49 |
+
return output
|