|
| 1 | +# Copyright 2020 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | + |
| 16 | +def transcribe_context_classes(storage_uri): |
| 17 | + """Provides "hints" to the speech recognizer to |
| 18 | + favor specific classes of words in the results.""" |
| 19 | + # [START speech_context_classes] |
| 20 | + from google.cloud import speech |
| 21 | + client = speech.SpeechClient() |
| 22 | + |
| 23 | + # storage_uri = 'gs://YOUR_BUCKET_ID/path/to/your/file.wav' |
| 24 | + audio = speech.types.RecognitionAudio(uri=storage_uri) |
| 25 | + |
| 26 | + # SpeechContext: to configure your speech_context see: |
| 27 | + # https://cloud.google.com/speech-to-text/docs/reference/rpc/google.cloud.speech.v1#speechcontext |
| 28 | + # Full list of supported phrases (class tokens) here: |
| 29 | + # https://cloud.google.com/speech-to-text/docs/class-tokens |
| 30 | + speech_context = speech.types.SpeechContext(phrases=['$TIME']) |
| 31 | + |
| 32 | + # RecognitionConfig: to configure your encoding and sample_rate_hertz, see: |
| 33 | + # https://cloud.google.com/speech-to-text/docs/reference/rpc/google.cloud.speech.v1#recognitionconfig |
| 34 | + config = speech.types.RecognitionConfig( |
| 35 | + encoding=speech.enums.RecognitionConfig.AudioEncoding.LINEAR16, |
| 36 | + sample_rate_hertz=8000, |
| 37 | + language_code='en-US', |
| 38 | + speech_contexts=[speech_context]) |
| 39 | + |
| 40 | + response = client.recognize(config, audio) |
| 41 | + |
| 42 | + for i, result in enumerate(response.results): |
| 43 | + alternative = result.alternatives[0] |
| 44 | + print('-' * 20) |
| 45 | + print('First alternative of result {}'.format(i)) |
| 46 | + print('Transcript: {}'.format(alternative.transcript)) |
| 47 | + # [END speech_context_classes] |
0 commit comments