-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvoicekit.py
142 lines (118 loc) · 4.6 KB
/
voicekit.py
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
import re
from abc import ABC, abstractmethod
import grpc
import pyaudio
from decouple import config
from auth import authorization_metadata
from tinkoff.cloud.stt.v1 import stt_pb2, stt_pb2_grpc
from tinkoff.cloud.tts.v1 import tts_pb2, tts_pb2_grpc
ENDPOINT = "stt.tinkoff.ru:443"
API_KEY = config("VOICEKIT_API_KEY")
SECRET_KEY = config("VOICEKIT_SECRET_KEY")
SAMPLE_RATE = 48000
class SpeechCommand(ABC):
@abstractmethod
def execute(self) -> None:
pass
class TTS(SpeechCommand):
"""
Text To Speech
"""
def __init__(self, context):
self.phrase = context.phrase
if self.phrase:
self.phrase = self.phrase.split(":")[1]
self.phrase = self.phrase.replace("!", ",")
self._ssml = "<speak> " + self.phrase + " </speak>"
self._text = re.sub(r"\<[^>]*\>", "", self.phrase)
stub = tts_pb2_grpc.TextToSpeechStub(
grpc.secure_channel(ENDPOINT, grpc.ssl_channel_credentials())
)
metadata = authorization_metadata(API_KEY, SECRET_KEY, "tinkoff.cloud.tts")
request = tts_pb2.SynthesizeSpeechRequest(
input=tts_pb2.SynthesisInput(text=self._text, ssml=self._ssml),
audio_config=tts_pb2.AudioConfig(
audio_encoding=tts_pb2.LINEAR16,
speaking_rate=1,
sample_rate_hertz=SAMPLE_RATE,
),
)
self._responses = stub.StreamingSynthesize(request, metadata=metadata)
def execute(self) -> None:
pyaudio_lib = pyaudio.PyAudio()
f = pyaudio_lib.open(
output=True, channels=1, format=pyaudio.paInt16, rate=SAMPLE_RATE
)
try:
for key, value in self._responses.initial_metadata():
if key == "x-audio-num-samples":
break
for stream_response in self._responses:
f.write(stream_response.audio_chunk)
except Exception as e:
print(e)
class STT(SpeechCommand):
"""
Speech To Text
"""
def __init__(self, context):
self.context = context
def execute(self) -> None:
r = stt_pb2.StreamingRecognizeRequest()
r.streaming_config.config.encoding = stt_pb2.AudioEncoding.LINEAR16 # type: ignore
r.streaming_config.config.sample_rate_hertz = 16000 # type: ignore
r.streaming_config.config.num_channels = 1 # type: ignore
r.streaming_config.config.enable_denormalization = True # type: ignore
r.streaming_config.config.enable_automatic_punctuation = True # type: ignore
r.streaming_config.config.vad_config.silence_duration_threshold = 1 # type: ignore
# r.streaming_config.config.max_alternatives = 10 # type: ignore
r.streaming_config.single_utterance = True # type: ignore
metadata = authorization_metadata(API_KEY, SECRET_KEY, "tinkoff.cloud.stt")
stub = stt_pb2_grpc.SpeechToTextStub(
grpc.secure_channel(ENDPOINT, grpc.ssl_channel_credentials())
)
try:
responses = stub.StreamingRecognize(self.requests(r), metadata=metadata)
for response in responses:
for result in response.results:
for alternative in result.recognition_result.alternatives:
self.context.set_phrase(alternative.transcript)
break
except Exception as e:
print(e)
@staticmethod
def requests(request):
try:
yield request
pyaudio_lib = pyaudio.PyAudio()
f = pyaudio_lib.open(
input=True, channels=1, format=pyaudio.paInt16, rate=16000
)
for data in iter(lambda: f.read(800), b""):
request = stt_pb2.StreamingRecognizeRequest()
request.audio_content = data # type: ignore
yield request
except Exception as e:
print("Got exception in generate_requests", e)
raise
class Invoker:
_on_speak = None
_on_listen = None
def set_on_speak(self, phrase: SpeechCommand):
self._on_speak = TTS(phrase)
def set_on_listen(self, context: SpeechCommand):
self._on_listen = STT(context)
def do_speak(self):
if isinstance(self._on_speak, SpeechCommand):
self._on_speak.execute()
def do_listen(self):
if isinstance(self._on_listen, SpeechCommand):
self._on_listen.execute()
def say(phrase):
invoker = Invoker()
invoker.set_on_speak(phrase)
invoker.do_speak()
def listen(context):
invoker = Invoker()
invoker.set_on_listen(context)
invoker.do_listen()