From 8b05336a3c161d056272d276e1061a0188377269 Mon Sep 17 00:00:00 2001 From: Aleksey Filippov Date: Fri, 14 Jan 2022 14:12:58 +0400 Subject: [PATCH] Fix wav check and upload in script --- main.py | 27 ++++++++------------------- 1 file changed, 8 insertions(+), 19 deletions(-) diff --git a/main.py b/main.py index c73498a..9fa1b26 100644 --- a/main.py +++ b/main.py @@ -1,37 +1,26 @@ #!/usr/bin/env python3 import json -import struct import sys -import wave -from io import BytesIO from urllib.request import Request, urlopen from scipy.io import wavfile -from scipy.io.wavfile import read as read_wav def stt(wav_file: str, url: str) -> str: - print('Connecting to \'{}\'...'.format(url)) - request = Request('{}/stt'.format(url), data=_load_wav(wav_file), headers={'Content-Type': 'audio/wav'}) + print(f'Connecting to \'{url}\'...') + request = Request(f'{url}/stt', data=_load_wav(wav_file), headers={'Content-Type': 'audio/wav'}) result = json.loads(urlopen(request).read().decode('utf-8')) if not ('code' in result and 'text' in result): - raise RuntimeError('Wrong reply from server: {}'.format(result)) - return result['text'] if not result['code'] else 'Server error: [{code}]: {text}'.format(**result) + raise RuntimeError(f'Wrong reply from server: {result}') + return result.text if not result.code else f'Server error: [{result.text}]: {result.code}' -def _load_wav(wav_file, convert_rate=16000, convert_width=2, channels=1): +def _load_wav(wav_file): _check_wav(wav_file) - with wave.open(wav_file, 'rb') as in_: - src_data = in_.readframes(in_.getnframes()) - with BytesIO() as file: - with wave.open(file, 'wb') as out: - out.setframerate(convert_rate) - out.setsampwidth(convert_width) - out.setnchannels(channels) - out.writeframes(src_data) - result = file.getvalue() + with open(wav_file, 'rb') as file: + result = file.read() return result @@ -53,7 +42,7 @@ def _main(): exit(1) file = sys.argv[1] server = 'http://127.0.0.1:8086' if len(sys.argv) < 3 else sys.argv[2] - print('Result: {}'.format(stt(file, server))) + print(f'Result: {stt(file, server)}') if __name__ == '__main__':