Slightly cleanup some more

This commit is contained in:
rany2
2023-01-05 00:07:08 +02:00
parent cd84fa972a
commit 8c356a000c
4 changed files with 23 additions and 27 deletions

View File

@@ -12,7 +12,8 @@ from xml.sax.saxutils import escape
import aiohttp import aiohttp
from edge_tts.exceptions import * from edge_tts.exceptions import (NoAudioReceived, UnexpectedResponse,
UnknownResponse)
from .constants import WSS_URL from .constants import WSS_URL
@@ -207,7 +208,6 @@ class Communicate:
ValueError: If the voice is not valid. ValueError: If the voice is not valid.
""" """
self.text = text self.text = text
self.boundary_type = 1
self.codec = "audio-24khz-48kbitrate-mono-mp3" self.codec = "audio-24khz-48kbitrate-mono-mp3"
self.voice = voice self.voice = voice
# Possible values for voice are: # Possible values for voice are:
@@ -284,7 +284,7 @@ class Communicate:
# download indicates whether we should be expecting audio data, # download indicates whether we should be expecting audio data,
# this is so what we avoid getting binary data from the websocket # this is so what we avoid getting binary data from the websocket
# and falsely thinking it's audio data. # and falsely thinking it's audio data.
download = False download_audio = False
# audio_was_received indicates whether we have received audio data # audio_was_received indicates whether we have received audio data
# from the websocket. This is so we can raise an exception if we # from the websocket. This is so we can raise an exception if we
@@ -332,12 +332,12 @@ class Communicate:
"Path" in parameters "Path" in parameters
and parameters["Path"] == "turn.start" and parameters["Path"] == "turn.start"
): ):
download = True download_audio = True
elif ( elif (
"Path" in parameters "Path" in parameters
and parameters["Path"] == "turn.end" and parameters["Path"] == "turn.end"
): ):
download = False download_audio = False
break break
elif ( elif (
"Path" in parameters "Path" in parameters
@@ -376,15 +376,6 @@ class Communicate:
"Path" in parameters "Path" in parameters
and parameters["Path"] == "response" and parameters["Path"] == "response"
): ):
# TODO: implement this:
"""
X-RequestId:xxxxxxxxxxxxxxxxxxxxxxxxx
Content-Type:application/json; charset=utf-8
Path:response
{"context":{"serviceTag":"yyyyyyyyyyyyyyyyyyy"},"audio":
{"type":"inline","streamId":"zzzzzzzzzzzzzzzzz"}}
"""
pass pass
else: else:
raise UnknownResponse( raise UnknownResponse(
@@ -392,7 +383,7 @@ class Communicate:
+ received.data + received.data
) )
elif received.type == aiohttp.WSMsgType.BINARY: elif received.type == aiohttp.WSMsgType.BINARY:
if download: if download_audio:
yield { yield {
"type": "audio", "type": "audio",
"data": b"Path:audio\r\n".join( "data": b"Path:audio\r\n".join(
@@ -402,12 +393,12 @@ class Communicate:
audio_was_received = True audio_was_received = True
else: else:
raise UnexpectedResponse( raise UnexpectedResponse(
"The service sent a binary message, but we are not expecting one." "We received a binary message, but we are not expecting one."
) )
if not audio_was_received: if not audio_was_received:
raise NoAudioReceived( raise NoAudioReceived(
"No audio was received from the service. Please verify that your parameters are correct." "No audio was received. Please verify that your parameters are correct."
) )
async def save( async def save(

View File

@@ -1,3 +1,5 @@
"""Exceptions for the Edge TTS project."""
class UnknownResponse(Exception): class UnknownResponse(Exception):
"""Raised when an unknown response is received from the server.""" """Raised when an unknown response is received from the server."""

View File

@@ -1,5 +1,5 @@
""" """
list_voices package. list_voices package for edge_tts.
""" """
import json import json
@@ -9,13 +9,12 @@ import aiohttp
from .constants import VOICE_LIST from .constants import VOICE_LIST
async def list_voices(proxy=None): async def list_voices(*, proxy=None):
""" """
List all available voices and their attributes. List all available voices and their attributes.
This pulls data from the URL used by Microsoft Edge to return a list of This pulls data from the URL used by Microsoft Edge to return a list of
all available voices. However many more experimental voices are available all available voices.
than are listed here. (See https://aka.ms/csspeech/voicenames)
Returns: Returns:
dict: A dictionary of voice attributes. dict: A dictionary of voice attributes.

View File

@@ -10,7 +10,8 @@ import sys
from edge_tts import Communicate, SubMaker, list_voices from edge_tts import Communicate, SubMaker, list_voices
async def _list_voices(proxy): async def _print_voices(proxy):
"""Print all available voices."""
for idx, voice in enumerate(await list_voices(proxy=proxy)): for idx, voice in enumerate(await list_voices(proxy=proxy)):
if idx != 0: if idx != 0:
print() print()
@@ -22,7 +23,8 @@ async def _list_voices(proxy):
print(f"{key}: {voice[key]}") print(f"{key}: {voice[key]}")
async def _tts(args): async def _run_tts(args):
"""Run TTS after parsing arguments from command line."""
tts = await Communicate( tts = await Communicate(
args.text, args.text,
args.voice, args.voice,
@@ -33,6 +35,7 @@ async def _tts(args):
try: try:
media_file = None media_file = None
if args.write_media: if args.write_media:
# pylint: disable=consider-using-with
media_file = open(args.write_media, "wb") media_file = open(args.write_media, "wb")
subs = SubMaker(args.overlapping) subs = SubMaker(args.overlapping)
@@ -55,7 +58,7 @@ async def _tts(args):
media_file.close() media_file.close()
async def _main(): async def _async_main():
parser = argparse.ArgumentParser(description="Microsoft Edge TTS") parser = argparse.ArgumentParser(description="Microsoft Edge TTS")
group = parser.add_mutually_exclusive_group(required=True) group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("-t", "--text", help="what TTS will say") group.add_argument("-t", "--text", help="what TTS will say")
@@ -108,7 +111,7 @@ async def _main():
args = parser.parse_args() args = parser.parse_args()
if args.list_voices: if args.list_voices:
await _list_voices(args.proxy) await _print_voices(args.proxy)
sys.exit(0) sys.exit(0)
if args.text is not None or args.file is not None: if args.text is not None or args.file is not None:
@@ -123,11 +126,12 @@ async def _main():
with open(args.file, "r", encoding="utf-8") as file: with open(args.file, "r", encoding="utf-8") as file:
args.text = file.read() args.text = file.read()
await _tts(args) await _run_tts(args)
def main(): def main():
asyncio.get_event_loop().run_until_complete(_main()) """Run the main function using asyncio."""
asyncio.get_event_loop().run_until_complete(_async_main())
if __name__ == "__main__": if __name__ == "__main__":