|
| 1 | +#!/usr/bin/env python |
| 2 | +# Copyright (C) 2016 Google Inc. |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | + |
| 16 | +"""Sample that transcribes a FLAC audio file stored in Google Cloud Storage, |
| 17 | +using async GRPC.""" |
| 18 | + |
| 19 | +import argparse |
| 20 | +import time |
| 21 | + |
| 22 | +from gcloud.credentials import get_credentials |
| 23 | +from google.cloud.speech.v1beta1 import cloud_speech_pb2 |
| 24 | +from google.longrunning import operations_grpc_pb2 |
| 25 | +from grpc.beta import implementations |
| 26 | + |
| 27 | +# Keep the request alive for this many seconds |
| 28 | +DEADLINE_SECS = 10 |
| 29 | +SPEECH_SCOPE = 'https://www.googleapis.com/auth/cloud-platform' |
| 30 | + |
| 31 | + |
| 32 | +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 | + |
| 37 | + # 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') |
| 46 | + |
| 47 | + # compose the two together for both ssl and google auth |
| 48 | + composite_channel = implementations.composite_channel_credentials( |
| 49 | + ssl_channel, auth_plugin) |
| 50 | + |
| 51 | + return implementations.secure_channel(host, port, composite_channel) |
| 52 | + |
| 53 | + |
| 54 | +def main(input_uri, encoding, sample_rate): |
| 55 | + channel = make_channel('speech.googleapis.com', 443) |
| 56 | + service = cloud_speech_pb2.beta_create_Speech_stub(channel) |
| 57 | + # The method and parameters can be inferred from the proto from which the |
| 58 | + # grpc client lib was generated. See: |
| 59 | + # https://github.com/googleapis/googleapis/blob/master/google/cloud/speech/v1beta1/cloud_speech.proto |
| 60 | + response = service.AsyncRecognize(cloud_speech_pb2.AsyncRecognizeRequest( |
| 61 | + config=cloud_speech_pb2.RecognitionConfig( |
| 62 | + encoding=encoding, |
| 63 | + sample_rate=sample_rate, |
| 64 | + ), |
| 65 | + audio=cloud_speech_pb2.RecognitionAudio( |
| 66 | + uri=input_uri, |
| 67 | + ) |
| 68 | + ), DEADLINE_SECS) |
| 69 | + |
| 70 | + # Print the longrunning operation handle. |
| 71 | + print(response) |
| 72 | + |
| 73 | + # Construct a long running operation endpoint. |
| 74 | + service = operations_grpc_pb2.beta_create_Operations_stub(channel) |
| 75 | + |
| 76 | + name = response.name |
| 77 | + |
| 78 | + while True: |
| 79 | + # Give the server a few seconds to process. |
| 80 | + print('Waiting for server processing...') |
| 81 | + time.sleep(1) |
| 82 | + # Get the long running operation with response. |
| 83 | + response = service.GetOperation( |
| 84 | + operations_grpc_pb2.GetOperationRequest(name=name), |
| 85 | + DEADLINE_SECS) |
| 86 | + |
| 87 | + if response.done: |
| 88 | + break |
| 89 | + |
| 90 | + # Print the recognition results. |
| 91 | + results = cloud_speech_pb2.AsyncRecognizeResponse() |
| 92 | + response.response.Unpack(results) |
| 93 | + print(results) |
| 94 | + |
| 95 | + |
| 96 | +def _gcs_uri(text): |
| 97 | + if not text.startswith('gs://'): |
| 98 | + raise argparse.ArgumentTypeError( |
| 99 | + 'Cloud Storage uri must be of the form gs://bucket/path/') |
| 100 | + return text |
| 101 | + |
| 102 | + |
| 103 | +if __name__ == '__main__': |
| 104 | + parser = argparse.ArgumentParser() |
| 105 | + parser.add_argument('input_uri', type=_gcs_uri) |
| 106 | + parser.add_argument( |
| 107 | + '--encoding', default='FLAC', choices=[ |
| 108 | + 'LINEAR16', 'FLAC', 'MULAW', 'AMR', 'AMR_WB'], |
| 109 | + help='How the audio file is encoded. See {}#L67'.format( |
| 110 | + 'https://github.com/googleapis/googleapis/blob/master/' |
| 111 | + 'google/cloud/speech/v1beta1/cloud_speech.proto')) |
| 112 | + parser.add_argument('--sample_rate', default=16000) |
| 113 | + |
| 114 | + args = parser.parse_args() |
| 115 | + main(args.input_uri, args.encoding, args.sample_rate) |
0 commit comments