Skip to content

Commit

Permalink
send alpn extension in client hello for baidu tts
Browse files Browse the repository at this point in the history
Baidu web server seems to behave nondeterministically when the extension is not supplied, sometimes returning 200 OK but with Content-Length 0. When the extension is sent, the audio/mpeg content is returned as expected. Automatically sending the alpn extension was added in python 3.10 (python/cpython@f97406b), but Anki is still using 3.9.

Close #61.
  • Loading branch information
kieranlblack committed Feb 24, 2024
1 parent 42af602 commit b6ee8ab
Showing 1 changed file with 15 additions and 10 deletions.
25 changes: 15 additions & 10 deletions chinese/tts.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@
# Inspiration: Tymon Warecki
# License: GNU AGPL, version 3 or later; http://www.gnu.org/copyleft/agpl.html

from .aws import AWS4Signer

import ssl
from os.path import basename, exists, join
from re import sub
from urllib.parse import urlencode
Expand All @@ -18,6 +17,8 @@
from gtts import gTTS
from gtts.tts import gTTSError

from .aws import AWS4Signer

requests.packages.urllib3.disable_warnings()


Expand Down Expand Up @@ -64,19 +65,23 @@ def get_baidu(self):
'lan': self.lang,
'ie': 'UTF-8',
'text': self.text.encode('utf-8'),
'spd': 2,
'source': 'web',
}


url = 'https://fanyi.baidu.com/gettts?lan=zh&text=' + urlencode(query) + '&spd=2&source=web'

url = 'https://fanyi.baidu.com/gettts?' + 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))
context = ssl.create_default_context()
context.set_alpn_protocols(['http/1.1'])

with open(self.path, 'wb') as audio:
audio.write(response.read())
with urlopen(request, context=context, timeout=5) as response, open(self.path, 'wb') as audio:
if response.code != 200:
raise ValueError('{}: {}'.format(response.code, response.msg))

bytes_response = response.read()
audio.write(bytes_response)

def get_aws(self):
signer = AWS4Signer(service='polly')
Expand Down

0 comments on commit b6ee8ab

Please sign in to comment.