forked from jdlorimer/chinese-support-redux
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtts.py
101 lines (79 loc) · 2.93 KB
/
tts.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# Copyright © 2012 Roland Sieker <[email protected]>
# Copyright © 2012 Thomas TEMPÉ <[email protected]>
# Copyright © 2017 Pu Anlai <https://github.com/InspectorMustache>
# Copyright © 2019 Oliver Rice <[email protected]>
# Copyright © 2017-2021 Joseph Lorimer <[email protected]>
# Inspiration: Tymon Warecki
# License: GNU AGPL, version 3 or later; http://www.gnu.org/copyleft/agpl.html
from .aws import AWS4Signer
from os.path import basename, exists, join
from re import sub
from urllib.parse import urlencode
from urllib.request import Request, urlopen
import requests
from aqt import mw
from gtts import gTTS
from gtts.tts import gTTSError
requests.packages.urllib3.disable_warnings()
class AudioDownloader:
def __init__(self, text, source='google|zh-CN'):
self.text = text
self.service, self.lang = source.split('|')
self.path = self.get_path()
self.func = {
'google': self.get_google,
'baidu': self.get_baidu,
'aws': self.get_aws,
}.get(self.service)
def get_path(self):
filename = '{}_{}_{}.mp3'.format(
self.sanitize(self.text), self.service, self.lang
)
return join(mw.col.media.dir(), filename)
def sanitize(self, s):
return sub(r'[/:*?"<>|]', '', s)
def download(self):
if exists(self.path):
return basename(self.path)
if not self.func:
raise NotImplementedError(self.service)
self.func()
return basename(self.path)
def get_google(self):
tts = gTTS(self.text, lang=self.lang, tld='cn')
try:
tts.save(self.path)
except gTTSError as e:
print('gTTS Error: {}'.format(e))
def get_baidu(self):
query = {
'lan': self.lang,
'ie': 'UTF-8',
'text': self.text.encode('utf-8'),
}
url = 'http://tts.baidu.com/text2audio?' + urlencode(query)
request = Request(url)
request.add_header('User-Agent', 'Mozilla/5.0')
response = urlopen(request, timeout=5)
if response.code != 200:
raise ValueError('{}: {}'.format(response.code, response.msg))
with open(self.path, 'wb') as audio:
audio.write(response.read())
def get_aws(self):
signer = AWS4Signer(service='polly')
signer.use_aws_profile('chinese_support_redux')
url = 'https://polly.%s.amazonaws.com/v1/speech' % (signer.region_name)
query = {
'OutputFormat': 'mp3',
'Text': self.text,
'VoiceId': self.lang,
}
response = requests.post(url, json=query, auth=signer)
if response.status_code != 200:
raise ValueError(
'Polly Request Failed: Error Code {}'.format(
response.status_code
)
)
with open(self.path, 'wb') as audio:
audio.write(response.content)