2022-01-13 20:23:35 +04:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
|
|
|
|
import json
|
|
|
|
import sys
|
|
|
|
from urllib.request import Request, urlopen
|
|
|
|
|
|
|
|
from scipy.io import wavfile
|
|
|
|
|
|
|
|
|
|
|
|
def stt(wav_file: str, url: str) -> str:
|
2022-01-14 14:12:58 +04:00
|
|
|
print(f'Connecting to \'{url}\'...')
|
|
|
|
request = Request(f'{url}/stt', data=_load_wav(wav_file), headers={'Content-Type': 'audio/wav'})
|
2022-01-13 20:23:35 +04:00
|
|
|
result = json.loads(urlopen(request).read().decode('utf-8'))
|
|
|
|
|
|
|
|
if not ('code' in result and 'text' in result):
|
2022-01-14 14:12:58 +04:00
|
|
|
raise RuntimeError(f'Wrong reply from server: {result}')
|
|
|
|
return result.text if not result.code else f'Server error: [{result.text}]: {result.code}'
|
2022-01-13 20:23:35 +04:00
|
|
|
|
|
|
|
|
2022-01-14 14:12:58 +04:00
|
|
|
def _load_wav(wav_file):
|
2022-01-13 20:23:35 +04:00
|
|
|
_check_wav(wav_file)
|
2022-01-14 14:12:58 +04:00
|
|
|
with open(wav_file, 'rb') as file:
|
|
|
|
result = file.read()
|
2022-01-13 20:23:35 +04:00
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
|
|
def _check_wav(wav_file):
|
|
|
|
sample_rate, sig = wavfile.read(wav_file)
|
|
|
|
channels = len(sig.shape)
|
|
|
|
bits = sig.dtype.base.name
|
|
|
|
if sample_rate != 16000:
|
|
|
|
raise Exception(f'Sample rate is not 16000: {sample_rate}')
|
|
|
|
if channels != 1:
|
|
|
|
raise Exception(f'Number of Channels is not 1 (Not mono): {channels}')
|
|
|
|
if bits != 'int16':
|
|
|
|
raise Exception(f'Bits per sample 16: {bits}')
|
|
|
|
|
|
|
|
|
|
|
|
def _main():
|
|
|
|
if len(sys.argv) < 2:
|
|
|
|
print('Usage: {} FILE [URL]'.format(sys.argv[0]))
|
|
|
|
exit(1)
|
|
|
|
file = sys.argv[1]
|
|
|
|
server = 'http://127.0.0.1:8086' if len(sys.argv) < 3 else sys.argv[2]
|
2022-01-14 14:12:58 +04:00
|
|
|
print(f'Result: {stt(file, server)}')
|
2022-01-13 20:23:35 +04:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
_main()
|