From 5078aa4d5d4ee88b2f61c12d82f7a4a06f8ce302 Mon Sep 17 00:00:00 2001 From: Thomas Schultz Date: Thu, 27 Oct 2016 13:41:52 -0400 Subject: [PATCH] Add speech async GAPIC. --- docs/index.rst | 2 - docs/speech-metadata.rst | 7 -- docs/speech-operation.rst | 7 -- docs/speech-usage.rst | 7 +- speech/google/cloud/speech/_gax.py | 41 +++++++- speech/google/cloud/speech/client.py | 6 +- speech/google/cloud/speech/metadata.py | 78 -------------- speech/google/cloud/speech/operation.py | 133 ------------------------ speech/setup.py | 2 + speech/unit_tests/test_client.py | 38 ++++--- speech/unit_tests/test_metadata.py | 50 --------- speech/unit_tests/test_operation.py | 122 ---------------------- system_tests/speech.py | 36 +++---- 13 files changed, 86 insertions(+), 443 deletions(-) delete mode 100644 docs/speech-metadata.rst delete mode 100644 docs/speech-operation.rst delete mode 100644 speech/google/cloud/speech/metadata.py delete mode 100644 speech/google/cloud/speech/operation.py delete mode 100644 speech/unit_tests/test_metadata.py delete mode 100644 speech/unit_tests/test_operation.py diff --git a/docs/index.rst b/docs/index.rst index 6a6e09c37cda4..33190d7296d6e 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -176,8 +176,6 @@ speech-usage Client speech-encoding - speech-metadata - speech-operation speech-sample speech-transcript diff --git a/docs/speech-metadata.rst b/docs/speech-metadata.rst deleted file mode 100644 index 575094a2d0f23..0000000000000 --- a/docs/speech-metadata.rst +++ /dev/null @@ -1,7 +0,0 @@ -Speech Metadata -=============== - -.. automodule:: google.cloud.speech.metadata - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/speech-operation.rst b/docs/speech-operation.rst deleted file mode 100644 index 5c0ec3b92b123..0000000000000 --- a/docs/speech-operation.rst +++ /dev/null @@ -1,7 +0,0 @@ -Speech Operation -================ - -.. automodule:: google.cloud.speech.operation - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/speech-usage.rst b/docs/speech-usage.rst index 7ee2be7d49ecf..7fd68ce8236f9 100644 --- a/docs/speech-usage.rst +++ b/docs/speech-usage.rst @@ -70,9 +70,10 @@ See: `Speech Asynchronous Recognize`_ >>> operation.complete True >>> for result in operation.results: - ... print('=' * 20) - ... print(result.transcript) - ... print(result.confidence) + ... print('=' * 20) + ... for alternative in result.alternatives: + ... print(alternative.transcript) + ... print(alternative.confidence) ==================== 'how old is the Brooklyn Bridge' 0.98267895 diff --git a/speech/google/cloud/speech/_gax.py b/speech/google/cloud/speech/_gax.py index 0019e3e2bea29..81a48c506c4d0 100644 --- a/speech/google/cloud/speech/_gax.py +++ b/speech/google/cloud/speech/_gax.py @@ -14,7 +14,13 @@ """GAX/GAPIC module for managing Speech API requests.""" +from google.longrunning import operations_grpc + from google.cloud.gapic.speech.v1beta1.speech_api import SpeechApi +from google.cloud.grpc.speech.v1beta1.cloud_speech_pb2 import ( + AsyncRecognizeMetadata) +from google.cloud.grpc.speech.v1beta1.cloud_speech_pb2 import ( + AsyncRecognizeResponse) from google.cloud.grpc.speech.v1beta1.cloud_speech_pb2 import SpeechContext from google.cloud.grpc.speech.v1beta1.cloud_speech_pb2 import RecognitionConfig from google.cloud.grpc.speech.v1beta1.cloud_speech_pb2 import RecognitionAudio @@ -23,13 +29,23 @@ from google.cloud.grpc.speech.v1beta1.cloud_speech_pb2 import ( StreamingRecognizeRequest) - +from google.cloud._helpers import make_secure_stub +from google.cloud.connection import DEFAULT_USER_AGENT from google.cloud.speech.transcript import Transcript +from google.cloud.operation import Operation +from google.cloud.operation import register_type + + +OPERATIONS_API_HOST = 'speech.googleapis.com' + +register_type(AsyncRecognizeMetadata) +register_type(AsyncRecognizeResponse) class GAPICSpeechAPI(object): """Manage calls through GAPIC wrappers to the Speech API.""" - def __init__(self): + def __init__(self, client=None): + self._client = client self._gapic_api = SpeechApi() def async_recognize(self, sample, language_code=None, @@ -72,9 +88,26 @@ def async_recognize(self, sample, language_code=None, and phrases. This can also be used to add new words to the vocabulary of the recognizer. - :raises NotImplementedError: Always. + :rtype: :class:`~google.cloud.operation.Opeartion` + :returns: Instance of ``Operation`` to poll for results. """ - raise NotImplementedError + config = RecognitionConfig( + encoding=sample.encoding, sample_rate=sample.sample_rate, + language_code=language_code, max_alternatives=max_alternatives, + profanity_filter=profanity_filter, + speech_context=SpeechContext(phrases=speech_context)) + + audio = RecognitionAudio(content=sample.content, + uri=sample.source_uri) + api = self._gapic_api + response = api.async_recognize(config=config, audio=audio) + + self._client._operations_stub = make_secure_stub( + self._client.connection.credentials, + DEFAULT_USER_AGENT, + operations_grpc.OperationsStub, + OPERATIONS_API_HOST) + return Operation.from_pb(response, self._client) def sync_recognize(self, sample, language_code=None, max_alternatives=None, profanity_filter=None, speech_context=None): diff --git a/speech/google/cloud/speech/client.py b/speech/google/cloud/speech/client.py index e254c56e4fa76..0cab4b0aec5e9 100644 --- a/speech/google/cloud/speech/client.py +++ b/speech/google/cloud/speech/client.py @@ -23,7 +23,7 @@ from google.cloud.environment_vars import DISABLE_GRPC from google.cloud.speech.connection import Connection from google.cloud.speech.encoding import Encoding -from google.cloud.speech.operation import Operation +from google.cloud.operation import Operation from google.cloud.speech.sample import Sample from google.cloud.speech.transcript import Transcript @@ -161,7 +161,7 @@ def speech_api(self): """Helper for speech-related API calls.""" if self._speech_api is None: if self._use_gax: - self._speech_api = GAPICSpeechAPI() + self._speech_api = GAPICSpeechAPI(self) else: self._speech_api = _JSONSpeechAPI(self) return self._speech_api @@ -287,7 +287,7 @@ def async_recognize(self, sample, language_code=None, api_response = self._connection.api_request( method='POST', path='speech:asyncrecognize', data=data) - return Operation.from_api_repr(self, api_response) + return Operation.from_dict(api_response, self) def sync_recognize(self, sample, language_code=None, max_alternatives=None, profanity_filter=None, speech_context=None): diff --git a/speech/google/cloud/speech/metadata.py b/speech/google/cloud/speech/metadata.py deleted file mode 100644 index 2cbc285c16c66..0000000000000 --- a/speech/google/cloud/speech/metadata.py +++ /dev/null @@ -1,78 +0,0 @@ -# Copyright 2016 Google Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Metadata representation from Google Speech API""" - -from google.cloud._helpers import _rfc3339_to_datetime - - -class Metadata(object): - """Representation of metadata from a Google Speech API Operation. - - :type last_update: datetime - :param last_update: When the Speech operation was last updated. - - :type start_time: datetime - :param start_time: When the Speech operation was started. - - :type progress_percent: int - :param progress_percent: Percentage of operation that has been completed. - """ - def __init__(self, last_update, start_time, progress_percent): - self._last_update = last_update - self._start_time = start_time - self._progress_percent = progress_percent - - @classmethod - def from_api_repr(cls, response): - """Factory: construct representation of operation metadata. - - :type response: dict - :param response: Dictionary containing operation metadata. - - :rtype: :class:`~google.cloud.speech.metadata.Metadata` - :returns: Instance of operation Metadata. - """ - last_update = _rfc3339_to_datetime(response['lastUpdateTime']) - start_time = _rfc3339_to_datetime(response['startTime']) - progress_percent = response.get('progressPercent') - - return cls(last_update, start_time, progress_percent) - - @property - def last_update(self): - """Last time operation was updated. - - :rtype: datetime - :returns: Datetime when operation was last updated. - """ - return self._last_update - - @property - def start_time(self): - """Start time of operation. - - :rtype: datetime - :returns: Datetime when operation was started. - """ - return self._start_time - - @property - def progress_percent(self): - """Progress percentage completed of operation. - - :rtype: int - :returns: Percentage of operation completed. - """ - return self._progress_percent diff --git a/speech/google/cloud/speech/operation.py b/speech/google/cloud/speech/operation.py deleted file mode 100644 index cb3ca4c61275b..0000000000000 --- a/speech/google/cloud/speech/operation.py +++ /dev/null @@ -1,133 +0,0 @@ -# Copyright 2016 Google Inc. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Long running operation representation for Google Speech API""" - -from google.cloud.speech.metadata import Metadata -from google.cloud.speech.transcript import Transcript -from google.cloud import operation - - -class Operation(operation.Operation): - """Representation of a Google API Long-Running Operation. - - :type client: :class:`~google.cloud.speech.client.Client` - :param client: Instance of speech client. - - :type name: int - :param name: ID assigned to an operation. - - :type complete: bool - :param complete: True if operation is complete, else False. - - :type metadata: :class:`~google.cloud.speech.metadata.Metadata` - :param metadata: Instance of ``Metadata`` with operation information. - - :type results: dict - :param results: Dictionary with transcript and score of operation. - """ - def __init__(self, client, name, complete=False, metadata=None, - results=None): - self.client = client - self.name = name - self._complete = complete - self._metadata = metadata - self._results = results - - @classmethod - def from_api_repr(cls, client, response): - """Factory: construct an instance from Google Speech API. - - :type client: :class:`~google.cloud.speech.client.Client` - :param client: Instance of speech client. - - :type response: dict - :param response: Dictionary response from Google Speech Operations API. - - :rtype: :class:`Operation` - :returns: Instance of `~google.cloud.speech.operations.Operation`. - """ - name = response['name'] - complete = response.get('done', False) - - operation_instance = cls(client, name, complete) - operation_instance._update(response) - return operation_instance - - @property - def complete(self): - """Completion state of the `Operation`. - - :rtype: bool - :returns: True if already completed, else false. - """ - return self._complete - - @property - def metadata(self): - """Metadata of operation. - - :rtype: :class:`~google.cloud.speech.metadata.Metadata` - :returns: Instance of ``Metadata``. - """ - return self._metadata - - @property - def results(self): - """Results dictionary with transcript information. - - :rtype: dict - :returns: Dictionary with transcript and confidence score. - """ - return self._results - - def poll(self): - """Check if the operation has finished. - - :rtype: bool - :returns: A boolean indicating if the current operation has completed. - :raises: :class:`ValueError ` if the operation - has already completed. - """ - if self.complete: - raise ValueError('The operation has completed.') - - path = 'operations/%s' % (self.name,) - api_response = self.client.connection.api_request(method='GET', - path=path) - self._update(api_response) - return self.complete - - def _update(self, response): - """Update Operation instance with latest data from Speech API. - - .. _speech_operations: https://cloud.google.com/speech/reference/\ - rest/v1beta1/operations - - :type response: dict - :param response: Response from Speech API Operations endpoint. - See: `speech_operations`_. - """ - metadata = response.get('metadata', None) - raw_results = response.get('response', {}).get('results', None) - results = [] - if raw_results: - for result in raw_results: - for alternative in result['alternatives']: - results.append(Transcript.from_api_repr(alternative)) - if metadata: - self._metadata = Metadata.from_api_repr(metadata) - - self._results = results - self._complete = response.get('done', False) diff --git a/speech/setup.py b/speech/setup.py index 536ed0c53782d..9e7ba5acab8f8 100644 --- a/speech/setup.py +++ b/speech/setup.py @@ -51,6 +51,8 @@ REQUIREMENTS = [ 'google-cloud-core >= 0.20.0', + 'grpcio >= 1.0.0, < 2.0dev', + 'google-gax >= 0.14.1, < 0.15dev', 'gapic-google-cloud-speech-v1beta1 >= 0.11.1, < 0.12.0', 'grpc-google-cloud-speech-v1beta1 >= 0.11.1, < 0.12.0', ] diff --git a/speech/unit_tests/test_client.py b/speech/unit_tests/test_client.py index 929999fc7c38f..880da903f8705 100644 --- a/speech/unit_tests/test_client.py +++ b/speech/unit_tests/test_client.py @@ -198,11 +198,10 @@ def test_sync_recognize_with_empty_results_gax(self): credentials = _Credentials() client = self._makeOne(credentials=credentials, use_gax=True) client.connection = _Connection() + _MockGAPICSpeechAPI._results = [] with self.assertRaises(ValueError): - mock_no_results = _MockGAPICSpeechAPI - mock_no_results._results = [] - with _Monkey(MUT, SpeechApi=mock_no_results): + with _Monkey(MUT, SpeechApi=_MockGAPICSpeechAPI): sample = Sample(source_uri=self.AUDIO_SOURCE_URI, encoding=speech.Encoding.FLAC, sample_rate=self.SAMPLE_RATE) @@ -217,9 +216,7 @@ def test_sync_recognize_with_gax(self): client = self._makeOne(credentials=creds, use_gax=True) client.connection = _Connection() client._speech_api = None - - mock_no_results = _MockGAPICSpeechAPI - mock_no_results._results = [_MockGAPICSyncResult()] + _MockGAPICSpeechAPI._results = [_MockGAPICSyncResult] with _Monkey(MUT, SpeechApi=_MockGAPICSpeechAPI): sample = client.sample(source_uri=self.AUDIO_SOURCE_URI, @@ -248,7 +245,7 @@ def test_async_supported_encodings(self): def test_async_recognize_no_gax(self): from unit_tests._fixtures import ASYNC_RECOGNIZE_RESPONSE from google.cloud import speech - from google.cloud.speech.operation import Operation + from google.cloud.operation import Operation from google.cloud.speech.sample import Sample RETURNED = ASYNC_RECOGNIZE_RESPONSE @@ -273,13 +270,16 @@ def test_async_recognize_with_gax(self): credentials = _Credentials() client = self._makeOne(credentials=credentials) client.connection = _Connection() + client.connection.credentials = credentials sample = client.sample(source_uri=self.AUDIO_SOURCE_URI, encoding=speech.Encoding.LINEAR16, sample_rate=self.SAMPLE_RATE) with _Monkey(MUT, SpeechApi=_MockGAPICSpeechAPI): - with self.assertRaises(NotImplementedError): - client.async_recognize(sample) + operation = client.async_recognize(sample) + + self.assertFalse(operation.complete) + self.assertIsNone(operation.response) def test_speech_api_with_gax(self): from google.cloud.speech import _gax as MUT @@ -317,6 +317,10 @@ class _MockGAPICAlternative(object): confidence = 0.95234356 +class _MockGAPICMetadata(object): + type_url = None + + class _MockGAPICSyncResult(object): alternatives = [_MockGAPICAlternative()] @@ -324,21 +328,29 @@ class _MockGAPICSyncResult(object): class _MockGAPICSpeechResponse(object): error = None endpointer_type = None + name = None + metadata = _MockGAPICMetadata() results = [] result_index = 0 class _MockGAPICSpeechAPI(object): _requests = None - _response = _MockGAPICSpeechResponse() + _response = _MockGAPICSpeechResponse _results = [_MockGAPICSyncResult()] + def async_recognize(self, config, audio): + from google.longrunning.operations_pb2 import Operation + self.config = config + self.audio = audio + operation = Operation() + return operation + def sync_recognize(self, config, audio): self.config = config self.audio = audio - mock_response = self._response - mock_response.results = self._results - return mock_response + self._response.results = self._results + return self._response class _Credentials(object): diff --git a/speech/unit_tests/test_metadata.py b/speech/unit_tests/test_metadata.py deleted file mode 100644 index 8e1dcd03e7337..0000000000000 --- a/speech/unit_tests/test_metadata.py +++ /dev/null @@ -1,50 +0,0 @@ -# Copyright 2016 Google Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import unittest - - -class TestMetadata(unittest.TestCase): - OPERATION_ID = 123456789 - - def _getTargetClass(self): - from google.cloud.speech.metadata import Metadata - return Metadata - - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) - - def test_ctor(self): - last_update = 'last_update' - start_time = 'start_time' - progress_percent = 23 - metadata = self._makeOne(last_update, start_time, progress_percent) - self.assertEqual('last_update', metadata.last_update) - self.assertEqual('start_time', metadata.start_time) - self.assertEqual(23, metadata.progress_percent) - - def test_from_api_repr(self): - import datetime - from google.cloud._helpers import _rfc3339_to_datetime - from unit_tests._fixtures import OPERATION_INCOMPLETE_RESPONSE as DATA - METADATA = DATA['metadata'] - - start_time = _rfc3339_to_datetime(METADATA['startTime']) - last_update = _rfc3339_to_datetime(METADATA['lastUpdateTime']) - metadata = self._getTargetClass().from_api_repr(METADATA) - self.assertIsInstance(metadata.last_update, datetime.datetime) - self.assertEqual(last_update, metadata.last_update) - self.assertIsInstance(metadata.start_time, datetime.datetime) - self.assertEqual(start_time, metadata.start_time) - self.assertEqual(27, metadata.progress_percent) diff --git a/speech/unit_tests/test_operation.py b/speech/unit_tests/test_operation.py deleted file mode 100644 index 6bf824a9d3d6b..0000000000000 --- a/speech/unit_tests/test_operation.py +++ /dev/null @@ -1,122 +0,0 @@ -# Copyright 2016 Google Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import unittest - - -class OperationTests(unittest.TestCase): - - OPERATION_NAME = '123456789' - - def _getTargetClass(self): - from google.cloud.speech.operation import Operation - return Operation - - def _makeOne(self, *args, **kwargs): - return self._getTargetClass()(*args, **kwargs) - - def test_ctor_defaults(self): - client = _Client() - operation = self._makeOne(client, self.OPERATION_NAME) - self.assertEqual(operation.name, '123456789') - self.assertFalse(operation.complete) - self.assertIsNone(operation.metadata) - self.assertIsNone(operation.results) - - def test_from_api_repr(self): - from unit_tests._fixtures import OPERATION_COMPLETE_RESPONSE - from google.cloud.speech.transcript import Transcript - from google.cloud.speech.metadata import Metadata - RESPONSE = OPERATION_COMPLETE_RESPONSE - - client = _Client() - operation = self._getTargetClass().from_api_repr(client, RESPONSE) - - self.assertEqual('123456789', operation.name) - self.assertTrue(operation.complete) - - self.assertEqual(len(operation.results), 1) - self.assertIsInstance(operation.results[0], Transcript) - self.assertEqual(operation.results[0].transcript, - 'how old is the Brooklyn Bridge') - self.assertEqual(operation.results[0].confidence, - 0.98267895) - self.assertTrue(operation.complete) - self.assertIsInstance(operation.metadata, Metadata) - self.assertEqual(operation.metadata.progress_percent, 100) - - def test_update_response(self): - from unit_tests._fixtures import ASYNC_RECOGNIZE_RESPONSE - from unit_tests._fixtures import OPERATION_COMPLETE_RESPONSE - RESPONSE = ASYNC_RECOGNIZE_RESPONSE - - client = _Client() - operation = self._getTargetClass().from_api_repr(client, RESPONSE) - self.assertEqual(operation.name, '123456789') - operation._update(OPERATION_COMPLETE_RESPONSE) - self.assertTrue(operation.complete) - - def test_poll(self): - from google.cloud.speech.operation import Metadata - from unit_tests._fixtures import ASYNC_RECOGNIZE_RESPONSE - from unit_tests._fixtures import OPERATION_COMPLETE_RESPONSE - RESPONSE = ASYNC_RECOGNIZE_RESPONSE - client = _Client() - connection = _Connection(OPERATION_COMPLETE_RESPONSE) - client.connection = connection - - operation = self._getTargetClass().from_api_repr(client, RESPONSE) - self.assertFalse(operation.complete) - operation.poll() - self.assertTrue(operation.complete) - self.assertIsInstance(operation.metadata, Metadata) - self.assertEqual(operation.metadata.progress_percent, 100) - requested = client.connection._requested - self.assertEqual(requested[0]['method'], 'GET') - self.assertEqual(requested[0]['path'], - 'operations/%s' % (operation.name,)) - - def test_poll_complete(self): - from unit_tests._fixtures import OPERATION_COMPLETE_RESPONSE - from unit_tests._fixtures import OPERATION_INCOMPLETE_RESPONSE - RESPONSE = OPERATION_INCOMPLETE_RESPONSE - - client = _Client() - connection = _Connection(OPERATION_COMPLETE_RESPONSE) - client.connection = connection - operation = self._getTargetClass().from_api_repr(client, RESPONSE) - - self.assertFalse(operation.complete) - operation.poll() # Update the operation with complete data. - - with self.assertRaises(ValueError): - operation.poll() - requested = client.connection._requested - self.assertEqual(requested[0]['method'], 'GET') - self.assertEqual(requested[0]['path'], - 'operations/%s' % (operation.name,)) - - -class _Connection(object): - def __init__(self, response=None): - self.response = response - self._requested = [] - - def api_request(self, method, path): - self._requested.append({'method': method, 'path': path}) - return self.response - - -class _Client(object): - connection = None diff --git a/system_tests/speech.py b/system_tests/speech.py index 56c2f2ad7bc5a..30d12ae6864d2 100644 --- a/system_tests/speech.py +++ b/system_tests/speech.py @@ -116,9 +116,17 @@ def _make_async_request(self, content=None, source_uri=None, profanity_filter=True, speech_context=['Google', 'cloud']) + def _check_async_results(self, results): + top_alternative = results[0].alternatives[0] + second_alternative = results[0].alternatives[1] + self.assertEqual(top_alternative.transcript, + 'hello ' + self.ASSERT_TEXT) + self.assertGreater(top_alternative.confidence, 0.90) + self.assertEqual(second_alternative.transcript, self.ASSERT_TEXT) + self.assertLess(second_alternative.confidence, 0.90) + def _check_best_results(self, results): top_result = results[0] - self.assertIsInstance(top_result, Transcript) self.assertEqual(top_result.transcript, 'hello ' + self.ASSERT_TEXT) self.assertGreater(top_result.confidence, 0.90) @@ -148,8 +156,6 @@ def test_sync_recognize_gcs_file(self): self._check_best_results(result) def test_async_recognize_local_file(self): - if Config.USE_GAX: - self.skipTest('async_recognize gRPC not yet implemented.') with open(AUDIO_FILE, 'rb') as file_obj: content = file_obj.read() @@ -157,18 +163,11 @@ def test_async_recognize_local_file(self): max_alternatives=2) _wait_until_complete(operation) - - self.assertEqual(len(operation.results), 2) - self._check_best_results(operation.results) - - results = operation.results - self.assertIsInstance(results[1], Transcript) - self.assertEqual(results[1].transcript, self.ASSERT_TEXT) - self.assertEqual(results[1].confidence, None) + results = operation.response.results + self.assertEqual(len(results), 1) + self._check_async_results(results) def test_async_recognize_gcs_file(self): - if Config.USE_GAX: - self.skipTest('async_recognize gRPC not yet implemented.') bucket_name = Config.TEST_BUCKET.name blob_name = 'hello.wav' blob = Config.TEST_BUCKET.blob(blob_name) @@ -181,11 +180,6 @@ def test_async_recognize_gcs_file(self): max_alternatives=2) _wait_until_complete(operation) - - self.assertEqual(len(operation.results), 2) - self._check_best_results(operation.results) - - results = operation.results - self.assertIsInstance(results[1], Transcript) - self.assertEqual(results[1].transcript, self.ASSERT_TEXT) - self.assertEqual(results[1].confidence, None) + results = operation.response.results + self.assertEqual(len(results), 1) + self._check_async_results(results)