-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathtranscribe_google.py
187 lines (153 loc) · 6.68 KB
/
transcribe_google.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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
from __future__ import division
from google.cloud import speech
import pyaudio
import queue
from concurrent.futures import ThreadPoolExecutor
from threading import Thread
RATE = 16000
CHUNK = int(RATE / 10) # 100ms
SPEAKER_DIARIZATION = True
MODEL = 'medical_conversation'
class MicrophoneStream(object):
"""Opens a recording stream as a generator yielding the audio chunks."""
def __init__(self, rate, chunk):
self._rate = rate
self._chunk = chunk
# Create a thread-safe buffer of audio data
self._buff = queue.Queue()
self.closed = True
def __enter__(self):
self._audio_interface = pyaudio.PyAudio()
self._audio_stream = self._audio_interface.open(
format=pyaudio.paInt16,
# The API currently only supports 1-channel (mono) audio
# https://goo.gl/z757pE
channels=1,
rate=self._rate,
input=True,
frames_per_buffer=self._chunk,
# Run the audio stream asynchronously to fill the buffer object.
# This is necessary so that the input device's buffer doesn't
# overflow while the calling thread makes network requests, etc.
stream_callback=self._fill_buffer,
)
self.closed = False
return self
def __exit__(self, type, value, traceback):
self._audio_stream.stop_stream()
self._audio_stream.close()
self.closed = True
# Signal the generator to terminate so that the client's
# streaming_recognize method will not block the process termination.
self._buff.put(None)
self._audio_interface.terminate()
def _fill_buffer(self, in_data, frame_count, time_info, status_flags):
"""Continuously collect data from the audio stream, into the buffer."""
self._buff.put(in_data)
return None, pyaudio.paContinue
def generator(self):
while not self.closed:
# Use a blocking get() to ensure there's at least one chunk of
# data, and stop iteration if the chunk is None, indicating the
# end of the audio stream.
chunk = self._buff.get()
if chunk is None:
return
data = [chunk]
# Now consume whatever other data's still buffered.
while True:
try:
chunk = self._buff.get(block=False)
if chunk is None:
return
data.append(chunk)
except queue.Empty:
break
yield b"".join(data)
def most_frequent(List):
return max(set(List), key=List.count)
def listen_print_loop(responses, fn=None):
"""Iterates through server responses and prints them.
The responses passed is a generator that will block until a response
is provided by the server.
Each response may contain multiple results, and each result may contain
multiple alternatives; for details, see https://goo.gl/tjCPAU. Here we
print only the transcription for the top alternative of the top result.
In this case, responses are provided for interim results as well. If the
response is an interim one, print a line feed at the end of it, to allow
the next result to overwrite it, until the response is a final one. For the
final one, print a newline to preserve the finalized transcription.
"""
for response in responses:
if not response.results:
continue
# The `results` list is consecutive. For streaming, we only care about
# the first result being considered, since once it's `is_final`, it
# moves on to considering the next utterance.
result = response.results[0]
# print(response.results)
if not result.alternatives:
continue
# Display the transcription of the top alternative.
transcript = result.alternatives[0].transcript
last_result = response.results[-1]
# for word_info in words_info:
# sys.stdout.write("word: '{}', speaker_tag: {}, final: {}\n".format(word_info.word, word_info.speaker_tag, result.is_final))
# words = result.alternatives[0].words
# print(response)
# Display interim results, but with a carriage return at the end of the
# line, so subsequent lines will overwrite them.
#
# If the previous result was longer than this one, we need to print
# some extra spaces to overwrite the previous result
if not result.is_final:
pass
# socket io to emit non_final_transcript
# sys.stdout.write(transcript + overwrite_chars)
# sys.stdout.flush()
# num_chars_printed = len(transcript)
else:
# socket io to emit final tanscript
speaker_array = [
word.speaker_tag for word in result.alternatives[0].words
]
# Find most occuring element in array
if len(speaker_array) > 0:
most_common_speaker_tag = most_frequent(speaker_array)
else:
most_common_speaker_tag = 1
print("[gcp voice] transcript: {}, speaker: {}".format(
transcript, most_common_speaker_tag))
probable_speaker = f"**Speaker {most_common_speaker_tag}:** "
if fn:
fn(probable_speaker + transcript)
def transcribe_gcp(fn=None):
print("[gcp voice] Recording...")
# See http://g.co/cloud/speech/docs/languages
# for a list of supported languages.
language_code = "en-US" # a BCP-47 language tag
client = speech.SpeechClient()
diarization_config = speech.SpeakerDiarizationConfig(
enable_speaker_diarization=SPEAKER_DIARIZATION,
min_speaker_count=2,
max_speaker_count=2,
)
config = speech.RecognitionConfig(
encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
sample_rate_hertz=RATE,
language_code=language_code,
diarization_config=diarization_config,
model=MODEL,
enable_automatic_punctuation=True,
use_enhanced=True)
streaming_config = speech.StreamingRecognitionConfig(config=config,
interim_results=False)
def callback(stream):
audio_generator = stream.generator()
requests = (speech.StreamingRecognizeRequest(audio_content=content)
for content in audio_generator)
responses = client.streaming_recognize(streaming_config, requests)
# Now, put the transcription responses to use.
listen_print_loop(responses, fn)
with MicrophoneStream(RATE, CHUNK) as stream:
callback(stream)