|
| 1 | +#!/usr/bin/python |
| 2 | + |
| 3 | +import contextlib |
| 4 | +import threading |
| 5 | + |
| 6 | +from gcloud.credentials import get_credentials |
| 7 | + |
| 8 | +from google.cloud.speech.v1.cloud_speech_pb2 import * # noqa |
| 9 | +from google.rpc import code_pb2 |
| 10 | + |
| 11 | +from grpc.beta import implementations |
| 12 | + |
| 13 | +import pyaudio |
| 14 | + |
| 15 | +# Audio recording parameters |
| 16 | +RATE = 16000 |
| 17 | +CHANNELS = 1 |
| 18 | +CHUNK = RATE // 10 # 100ms |
| 19 | + |
| 20 | +# Keep the request alive for this many seconds |
| 21 | +DEADLINE_SECS = 8 * 60 * 60 |
| 22 | +SPEECH_SCOPE = 'https://www.googleapis.com/auth/cloud-platform' |
| 23 | + |
| 24 | + |
| 25 | +def _make_channel(host, port): |
| 26 | + """Creates an SSL channel with auth credentials from the environment.""" |
| 27 | + # In order to make an https call, use an ssl channel with defaults |
| 28 | + ssl_channel = implementations.ssl_channel_credentials(None, None, None) |
| 29 | + |
| 30 | + # Grab application default credentials from the environment |
| 31 | + creds = get_credentials().create_scoped([SPEECH_SCOPE]) |
| 32 | + # Add a plugin to inject the creds into the header |
| 33 | + auth_header = ( |
| 34 | + 'Authorization', |
| 35 | + 'Bearer ' + creds.get_access_token().access_token) |
| 36 | + auth_plugin = implementations.metadata_call_credentials( |
| 37 | + lambda _, cb: cb([auth_header], None), |
| 38 | + name='google_creds') |
| 39 | + |
| 40 | + # compose the two together for both ssl and google auth |
| 41 | + composite_channel = implementations.composite_channel_credentials( |
| 42 | + ssl_channel, auth_plugin) |
| 43 | + |
| 44 | + return implementations.secure_channel(host, port, composite_channel) |
| 45 | + |
| 46 | + |
| 47 | +@contextlib.contextmanager |
| 48 | +def _record_audio(channels, rate, chunk): |
| 49 | + """Opens a recording stream in a context manager.""" |
| 50 | + p = pyaudio.PyAudio() |
| 51 | + audio_stream = p.open( |
| 52 | + format=pyaudio.paInt16, channels=channels, rate=rate, |
| 53 | + input=True, frames_per_buffer=chunk, |
| 54 | + ) |
| 55 | + |
| 56 | + yield audio_stream |
| 57 | + |
| 58 | + audio_stream.stop_stream() |
| 59 | + audio_stream.close() |
| 60 | + p.terminate() |
| 61 | + |
| 62 | + |
| 63 | +def _request_stream(stop_audio, channels=CHANNELS, rate=RATE, chunk=CHUNK): |
| 64 | + """Yields `RecognizeRequest`s constructed from a recording audio stream. |
| 65 | +
|
| 66 | + Args: |
| 67 | + stop_audio: A threading.Event object stops the recording when set. |
| 68 | + channels: How many audio channels to record. |
| 69 | + rate: The sampling rate. |
| 70 | + chunk: Buffer audio into chunks of this size before sending to the api. |
| 71 | + """ |
| 72 | + with _record_audio(channels, rate, chunk) as audio_stream: |
| 73 | + # The initial request must contain metadata about the stream, so the |
| 74 | + # server knows how to interpret it. |
| 75 | + metadata = InitialRecognizeRequest( |
| 76 | + encoding='LINEAR16', sample_rate=rate) |
| 77 | + audio_request = AudioRequest(content=audio_stream.read(chunk)) |
| 78 | + |
| 79 | + yield RecognizeRequest( |
| 80 | + initial_request=metadata, |
| 81 | + audio_request=audio_request) |
| 82 | + |
| 83 | + while not stop_audio.is_set(): |
| 84 | + # Subsequent requests can all just have the content |
| 85 | + audio_request = AudioRequest(content=audio_stream.read(chunk)) |
| 86 | + |
| 87 | + yield RecognizeRequest(audio_request=audio_request) |
| 88 | + |
| 89 | + |
| 90 | +def listen_print_loop(recognize_stream): |
| 91 | + for resp in recognize_stream: |
| 92 | + if resp.error.code != code_pb2.OK: |
| 93 | + raise Exception('Server error: ' + resp.error.message) |
| 94 | + |
| 95 | + # Display the transcriptions & their alternatives |
| 96 | + for result in resp.results: |
| 97 | + print(result.alternatives) |
| 98 | + |
| 99 | + # Exit recognition if any of the transcribed phrases could be |
| 100 | + # one of our keywords. |
| 101 | + if any(alt.confidence > .5 and |
| 102 | + (alt.transcript.strip() in ('exit', 'quit')) |
| 103 | + for result in resp.results |
| 104 | + for alt in result.alternatives): |
| 105 | + print('Exiting..') |
| 106 | + return |
| 107 | + |
| 108 | + |
| 109 | +def main(): |
| 110 | + stop_audio = threading.Event() |
| 111 | + with beta_create_Speech_stub( |
| 112 | + _make_channel('speech.googleapis.com', 443)) as service: |
| 113 | + try: |
| 114 | + listen_print_loop( |
| 115 | + service.Recognize(_request_stream(stop_audio), DEADLINE_SECS)) |
| 116 | + finally: |
| 117 | + # Stop the request stream once we're done with the loop - otherwise |
| 118 | + # it'll keep going in the thread that the grpc lib makes for it.. |
| 119 | + stop_audio.set() |
| 120 | + |
| 121 | + |
| 122 | +if __name__ == '__main__': |
| 123 | + main() |
0 commit comments