File size: 4,526 Bytes
d83d78a | 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 | """An actual network Wyoming client; no imports of server/inference code."""
import argparse
import asyncio
import hashlib
import json
from pathlib import Path
import time
import wave
from wyoming.audio import AudioChunk, AudioStart
from wyoming.client import AsyncTcpClient
from wyoming.info import Describe, Info
from wyoming.tts import Synthesize, SynthesizeVoice
async def synthesize(host, port, text, voice, path):
start = time.perf_counter()
first = None
pcm = bytearray()
chunks = 0
async with AsyncTcpClient(host, port) as client:
await client.write_event(Synthesize(text, voice=SynthesizeVoice(name=voice)).event())
event = await asyncio.wait_for(client.read_event(), 150)
assert event and AudioStart.is_type(event.type), event
audio_format = AudioStart.from_event(event)
assert (audio_format.rate, audio_format.width, audio_format.channels) == (44100, 2, 1)
while event := await asyncio.wait_for(client.read_event(), 150):
if event.type == 'error':
raise RuntimeError(event.data)
if event.type == 'audio-stop':
break
assert AudioChunk.is_type(event.type), event.type
chunk = AudioChunk.from_event(event)
assert (chunk.rate, chunk.width, chunk.channels) == (44100, 2, 1)
if first is None:
first = time.perf_counter()-start
pcm.extend(chunk.audio)
chunks += 1
else:
raise RuntimeError('Connection closed without audio-stop')
elapsed = time.perf_counter()-start
assert pcm and len(pcm)%2 == 0 and any(pcm)
with wave.open(str(path), 'wb') as wav:
wav.setnchannels(1)
wav.setsampwidth(2)
wav.setframerate(44100)
wav.writeframes(pcm)
seconds = len(pcm)/88200
return dict(voice=voice, text=text, file=path.name, seconds=seconds,
first_audio_seconds=first, elapsed_seconds=elapsed,
rtf_including_network=elapsed/seconds, chunks=chunks,
pcm_sha256=hashlib.sha256(pcm).hexdigest())
async def main(args):
args.output.mkdir(parents=True, exist_ok=True)
async with AsyncTcpClient(args.host, args.port) as client:
await client.write_event(Describe().event())
event = await asyncio.wait_for(client.read_event(), 10)
info = Info.from_event(event)
assert info.tts[0].installed
assert {v.name for v in info.tts[0].voices} == {'F1', 'F5', 'F7', 'M1', 'Voice4'}
assert all(v.languages == ['bg','en'] for v in info.tts[0].voices)
report = dict(host=args.host, port=args.port, info=event.data, records=[])
text = 'Здравей, Наско. В библиотеката има няколко приказки. Коя да прочета?'
for voice in ('F1', 'F5', 'F7', 'M1', 'Voice4'):
row = await synthesize(args.host, args.port, text, voice, args.output/f'{voice}.wav')
report['records'].append(row)
print(json.dumps(row, ensure_ascii=False), flush=True)
text = ('Часът е 07:15. В хола е 21,5 °C, а влажността е 48%. '
'Включени са 2 лампи. Днес са изразходвани 5,2 kWh електроенергия. '
'В библиотеката има Косе Босе, Дядовата ръкавичка и Трите прасенца. '
'Моля, посочи коя приказка да прочета.')
row = await synthesize(args.host, args.port, text, 'F5', args.output/'home-assistant-numbers.wav')
report['records'].append(row)
print(json.dumps(row, ensure_ascii=False), flush=True)
async with AsyncTcpClient(args.host, args.port) as client:
await client.write_event(Synthesize('Здравей.', voice=SynthesizeVoice(name='missing')).event())
event = await asyncio.wait_for(client.read_event(), 5)
assert event.type == 'error' and event.data['code'] == 'invalid-request'
report['invalid_voice_rejected'] = True
report['verified'] = True
report['verified_at_unix'] = time.time()
(args.output/'protocol-report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
if __name__ == '__main__':
p = argparse.ArgumentParser()
p.add_argument('--host', required=True)
p.add_argument('--port', type=int, default=10251)
p.add_argument('--output', type=Path, required=True)
asyncio.run(main(p.parse_args()))
|