/
stream_gTTS.py
139 lines (118 loc) · 4.45 KB
/
stream_gTTS.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
import calendar
import math
import re
import time
import gtts
import requests
import urllib3
from gtts_token import gtts_token
from .proxy import proxies
class _Token(gtts_token.Token):
def _get_token_key(self):
if self.token_key is not None:
return self.token_key
response = requests.get(
"https://translate.google.com/",
proxies=proxies('token_google')
)
line = response.text.split('\n')[-1]
tkk_expr = re.search(".*?(TKK=.*?;)W.*?", line).group(1)
try:
# Grab the token directly if already generated by function call
result = re.search("\d{6}\.[0-9]+", tkk_expr).group(0)
except AttributeError:
# Generate the token using algorithm
timestamp = calendar.timegm(time.gmtime())
hours = int(math.floor(timestamp / 3600))
a = re.search("a\\\\x3d(-?\d+);", tkk_expr).group(1)
b = re.search("b\\\\x3d(-?\d+);", tkk_expr).group(1)
result = str(hours) + "." + str(int(a) + int(b))
self.token_key = result
return result
class gTTS(gtts.gTTS):
def __init__(
self,
text,
lang='en',
slow=False,
lang_check=True,
pre_processor_funcs=None,
tokenizer_func=gtts.tts.Tokenizer([
gtts.tts.tokenizer_cases.tone_marks,
gtts.tts.tokenizer_cases.period_comma,
gtts.tts.tokenizer_cases.other_punctuation
]).run,
**_
):
if pre_processor_funcs is None:
pre_processor_funcs = [
gtts.tts.pre_processors.tone_marks,
gtts.tts.pre_processors.end_of_line,
gtts.tts.pre_processors.abbreviations,
gtts.tts.pre_processors.word_sub
]
# Text
assert text, 'No text to speak'
self.text = text
# Language
if lang_check:
try:
langs = gtts.tts.tts_langs()
if lang.lower() not in langs:
raise ValueError("Language not supported: %s" % lang)
except RuntimeError:
pass
self.lang_check = lang_check
self.lang = lang.lower()
# Read speed
if slow:
self.speed = gtts.tts.Speed.SLOW
else:
self.speed = gtts.tts.Speed.NORMAL
# Pre-processors and tokenizer
self.pre_processor_funcs = pre_processor_funcs
self.tokenizer_func = tokenizer_func
# Google Translate token
self.token = _Token()
def stream_to_fps(self, fps):
if not isinstance(fps, list):
fps = [fps]
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
text_parts = self._tokenize(self.text)
assert text_parts, 'No text to send to TTS API'
for idx, part in enumerate(text_parts):
try:
# Calculate token
part_tk = self.token.calculate_token(part)
except requests.exceptions.RequestException as e: # pragma: no cover
raise gtts.gTTSError(
"Connection error during token calculation: %s" %
str(e))
payload = {'ie': 'UTF-8',
'q': part,
'tl': self.lang,
'ttsspeed': self.speed,
'total': len(text_parts),
'idx': idx,
'client': 'tw-ob',
'textlen': len(part),
'tk': part_tk}
r = None
try:
# Request
r = requests.get(self.GOOGLE_TTS_URL,
params=payload,
headers=self.GOOGLE_TTS_HEADERS,
proxies=proxies('tts_google'),
verify=False,
stream=True)
r.raise_for_status()
except requests.exceptions.HTTPError:
# Request successful, bad response
raise gtts.gTTSError(tts=self, response=r)
except requests.exceptions.RequestException as e: # pragma: no cover
# Request failed
raise gtts.gTTSError(str(e))
for chunk in r.iter_content(chunk_size=1024):
for f in fps:
f.write(chunk)