8000 Update speech grpc samples to use new auth and grpc interfaces (#724) · wwb203/python-docs-samples@3aa5e7f · GitHub
[go: up one dir, main page]

Skip to content

Commit 3aa5e7f

Browse files
author
Jon Wayne Parrott
authored
Update speech grpc samples to use new auth and grpc interfaces (GoogleCloudPlatform#724)
1 parent ca7a29b commit 3aa5e7f

File tree

4 files changed

+72
-91
lines changed

4 files changed

+72
-91
lines changed

speech/grpc/requirements.txt

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1-
google-cloud-core==0.22.1
21
grpcio==1.0.4
32
PyAudio==0.2.9
4-
grpc-google-cloud-speech-v1beta1==0.11.1
3+
grpc-google-cloud-speech-v1beta1==0.14.0
54
six==1.10.0
5+
requests==2.12.4
6+
google-auth==0.5.0

speech/grpc/transcribe.py

Lines changed: 17 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -17,45 +17,38 @@
1717

1818
import argparse
1919

20-
from google.cloud.credentials import get_credentials
21-
from google.cloud.grpc.speech.v1beta1 import cloud_speech_pb2 as cloud_speech
22-
from grpc.beta import implementations
20+
import google.auth
21+
import google.auth.transport.grpc
22+
import google.auth.transport.requests
23+
from google.cloud.grpc.speech.v1beta1 import cloud_speech_pb2
2324

2425
# Keep the request alive for this many seconds
2526
DEADLINE_SECS = 60
2627
SPEECH_SCOPE = 'https://www.googleapis.com/auth/cloud-platform'
2728

2829

2930
def make_channel(host, port):
30-
"""Creates an SSL channel with auth credentials from the environment."""
31-
# In order to make an https call, use an ssl channel with defaults
32-
ssl_channel = implementations.ssl_channel_credentials(None, None, None)
33-
31+
"""Creates a secure channel with auth credentials from the environment."""
3432
# Grab application default credentials from the environment
35-
creds = get_credentials().create_scoped([SPEECH_SCOPE])
36-
# Add a plugin to inject the creds into the header
37-
auth_header = (
38-
'Authorization',
39-
'Bearer ' + creds.get_access_token().access_token)
40-
auth_plugin = implementations.metadata_call_credentials(
41-
lambda _, cb: cb([auth_header], None),
42-
name='google_creds')
33+
credentials, _ = google.auth.default(scopes=[SPEECH_SCOPE])
4334

44-
# compose the two together for both ssl and google auth
45-
composite_channel = implementations.composite_channel_credentials(
46-
ssl_channel, auth_plugin)
35+
# Create a secure channel using the credentials.
36+
http_request = google.auth.transport.requests.Request()
37+
target = '{}:{}'.format(host, port)
4738

48-
return implementations.secure_channel(host, port, composite_channel)
39+
return google.auth.transport.grpc.secure_authorized_channel(
40+
credentials, http_request, target)
4941

5042

5143
def main(input_uri, encoding, sample_rate, language_code='en-US'):
52-
service = cloud_speech.beta_create_Speech_stub(
53-
make_channel('speech.googleapis.com', 443))
44+
service = cloud_speech_pb2.SpeechStub(
45+
make_channel('speech.googleapis.com', 443))
46+
5447
# The method and parameters can be inferred from the proto from which the
5548
# grpc client lib was generated. See:
5649
# https://github.com/googleapis/googleapis/blob/master/google/cloud/speech/v1beta1/cloud_speech.proto
57-
response = service.SyncRecognize(cloud_speech.SyncRecognizeRequest(
58-
config=cloud_speech.RecognitionConfig(
50+
response = service.SyncRecognize(cloud_speech_pb2.SyncRecognizeRequest(
51+
config=cloud_speech_pb2.RecognitionConfig(
5952
# There are a bunch of config options you can specify. See
6053
# https://goo.gl/KPZn97 for the full list.
6154
encoding=encoding, # one of LINEAR16, FLAC, MULAW, AMR, AMR_WB
@@ -64,7 +57,7 @@ def main(input_uri, encoding, sample_rate, language_code='en-US'):
6457
# supported languages.
6558
language_code=language_code, # a BCP-47 language tag
6659
),
67-
audio=cloud_speech.RecognitionAudio(
60+
audio=cloud_speech_pb2.RecognitionAudio(
6861
uri=input_uri,
6962
)
7063
), DEADLINE_SECS)

speech/grpc/transcribe_async.py

Lines changed: 13 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -19,41 +19,34 @@
1919
import argparse
2020
import time
2121

22-
from google.cloud.credentials import get_credentials
22+
import google.auth
23+
import google.auth.transport.grpc
24+
import google.auth.transport.requests
2325
from google.cloud.grpc.speech.v1beta1 import cloud_speech_pb2
2426
from google.longrunning import operations_pb2
25-
from grpc.beta import implementations
2627

2728
# Keep the request alive for this many seconds
2829
DEADLINE_SECS = 10
2930
SPEECH_SCOPE = 'https://www.googleapis.com/auth/cloud-platform'
3031

3132

3233
def make_channel(host, port):
33-
"""Creates an SSL channel with auth credentials from the environment."""
34-
# In order to make an https call, use an ssl channel with defaults
35-
ssl_channel = implementations.ssl_channel_credentials(None, None, None)
36-
34+
"""Creates a secure channel with auth credentials from the environment."""
3735
# Grab application default credentials from the environment
38-
creds = get_credentials().create_scoped([SPEECH_SCOPE])
39-
# Add a plugin to inject the creds into the header
40-
auth_header = (
41-
'Authorization',
42-
'Bearer ' + creds.get_access_token().access_token)
43-
auth_plugin = implementations.metadata_call_credentials(
44-
lambda _, cb: cb([auth_header], None),
45-
name='google_creds')
36+
credentials, _ = google.auth.default(scopes=[SPEECH_SCOPE])
4637

47-
# compose the two together for both ssl and google auth
48-
composite_channel = implementations.composite_channel_credentials(
49-
ssl_channel, auth_plugin)
38+
# Create a secure channel using the credentials.
39+
http_request = google.auth.transport.requests.Request()
40+
target = '{}:{}'.format(host, port)
5041

51-
return implementations.secure_channel(host, port, composite_channel)
42+
return google.auth.transport.grpc.secure_authorized_channel(
43+
credentials, http_request, target)
5244

5345

5446
def main(input_uri, encoding, sample_rate, language_code='en-US'):
5547
channel = make_channel('speech.googleapis.com', 443)
56-
service = cloud_speech_pb2.beta_create_Speech_stub(channel)
48+
service = cloud_speech_pb2.SpeechStub(channel)
49+
5750
# The method and parameters can be inferred from the proto from which the
5851
# grpc client lib was generated. See:
5952
# https://github.com/googleapis/googleapis/blob/master/google/cloud/speech/v1beta1/cloud_speech.proto
@@ -76,7 +69,7 @@ def main(input_uri, encoding, sample_rate, language_code='en-US'):
7669
print(operation)
7770

7871
# Construct a long running operation endpoint.
79-
service = operations_pb2.beta_create_Operations_stub(channel)
72+
service = operations_pb2.OperationsStub(channel)
8073

8174
name = operation.name
8275

speech/grpc/transcribe_streaming.py

Lines changed: 39 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,12 @@
2222
import signal
2323
import sys
2424

25-
from google.cloud import credentials
26-
from google.cloud.grpc.speech.v1beta1 import cloud_speech_pb2 as cloud_speech
25+
26+
import google.auth
27+
import google.auth.transport.grpc
28+
import google.auth.transport.requests
29+
from google.cloud.grpc.speech.v1beta1 import cloud_speech_pb2
2730
from google.rpc import code_pb2
28-
from grpc.beta import implementations
2931
from grpc.framework.interfaces.face import face
3032
import pyaudio
3133
from six.moves import queue
@@ -43,25 +45,16 @@
4345

4446

4547
def make_channel(host, port):
46-
"""Creates an SSL channel with auth credentials from the environment."""
47-
# In order to make an https call, use an ssl channel with defaults
48-
ssl_channel = implementations.ssl_channel_credentials(None, None, None)
49-
48+
"""Creates a secure channel with auth credentials from the environment."""
5049
# Grab application default credentials from the environment
51-
creds = credentials.get_credentials().create_scoped([SPEECH_SCOPE])
52-
# Add a plugin to inject the creds into the header
53-
auth_header = (
54-
'Authorization',
55-
'Bearer ' + creds.get_access_token().access_token)
56-
auth_plugin = implementations.metadata_call_credentials(
57-
lambda _, cb: cb([auth_header], None),
58-
name='google_creds')
50+
credentials, _ = google.auth.default(scopes=[SPEECH_SCOPE])
5951

60-
# compose the two together for both ssl and google auth
61-
composite_channel = implementations.composite_channel_credentials(
62-
ssl_channel, auth_plugin)
52+
# Create a secure channel using the credentials.
53+
http_request = google.auth.transport.requests.Request()
54+
target = '{}:{}'.format(host, port)
6355

64-
return implementations.secure_channel(host, port, composite_channel)
56+
return google.auth.transport.grpc.secure_authorized_channel(
57+
credentials, http_request, target)
6558

6659

6760
def _audio_data_generator(buff):
@@ -142,7 +135,7 @@ def request_stream(data_stream, rate, interim_results=True):
142135
"""
143136
# The initial request must contain metadata about the stream, so the
144137
# server knows how to interpret it.
145-
recognition_config = cloud_speech.RecognitionConfig(
138+
recognition_config = cloud_speech_pb2.RecognitionConfig(
146139
# There are a bunch of config options you can specify. See
147140
# https://goo.gl/KPZn97 for the full list.
148141
encoding='LINEAR16', # raw 16-bit signed LE samples
@@ -151,17 +144,17 @@ def request_stream(data_stream, rate, interim_results=True):
151144
# for a list of supported languages.
152145
language_code='en-US', # a BCP-47 language tag
153146
)
154-
streaming_config = cloud_speech.StreamingRecognitionConfig(
147+
streaming_config = cloud_speech_pb2.StreamingRecognitionConfig(
155148
interim_results=interim_results,
156149
config=recognition_config,
157150
)
158151

159-
yield cloud_speech.StreamingRecognizeRequest(
152+
yield cloud_speech_pb2.StreamingRecognizeRequest(
160153
streaming_config=streaming_config)
161154

162155
for data in data_stream:
163156
# Subsequent requests can all just have the content
164-
yield cloud_speech.StreamingRecognizeRequest(audio_content=data)
157+
yield cloud_speech_pb2.StreamingRecognizeRequest(audio_content=data)
165158

166159

167160
def listen_print_loop(recognize_stream):
@@ -212,28 +205,29 @@ def listen_print_loop(recognize_stream):
212205

213206

214207
def main():
215-
with cloud_speech.beta_create_Speech_stub(
216-
make_channel('speech.googleapis.com', 443)) as service:
217-
# For streaming audio from the microphone, there are three threads.
218-
# First, a thread that collects audio data as it comes in
219-
with record_audio(RATE, CHUNK) as buffered_audio_data:
220-
# Second, a thread that sends requests with that data
221-
requests = request_stream(buffered_audio_data, RATE)
222-
# Third, a thread that listens for transcription responses
223-
recognize_stream = service.StreamingRecognize(
224-
requests, DEADLINE_SECS)
225-
226-
# Exit things cleanly on interrupt
227-
signal.signal(signal.SIGINT, lambda *_: recognize_stream.cancel())
228-
229-
# Now, put the transcription responses to use.
230-
try:
231-
listen_print_loop(recognize_stream)
232-
233-
recognize_stream.cancel()
234-
except face.CancellationError:
235-
# This happens because of the interrupt handler
236-
pass
208+
service = cloud_speech_pb2.SpeechStub(
209+
make_channel('speech.googleapis.com', 443))
210+
211+
# For streaming audio from the microphone, there are three threads.
212+
# First, a thread that collects audio data as it comes in
213+
with record_audio(RATE, CHUNK) as buffered_audio_data:
214+
# Second, a thread that sends requests with that data
215+
requests = request_stream(buffered_audio_data, RATE)
216+
# Third, a thread that listens for transcription responses
217+
recognize_stream = service.StreamingRecognize(
218+
requests, DEADLINE_SECS)
219+
220+
# Exit things cleanly on interrupt
221+
signal.signal(signal.SIGINT, lambda *_: recognize_stream.cancel())
222+
223+
# Now, put the transcription responses to use.
224+
try:
225+
listen_print_loop(recognize_stream)
226+
227+
recognize_stream.cancel()
228+
except face.CancellationError:
229+
# This happens because of the interrupt handler
230+
pass
237231

238232

239233
if __name__ == '__main__':

0 commit comments

Comments
 (0)
0