|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +# Copyright 2018 Google LLC |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | +# you may not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | + |
| 17 | +"""Google Cloud Speech API sample that demonstrates enhanced models |
| 18 | +and recognition metadata. |
| 19 | +
|
| 20 | +Example usage: |
| 21 | + python transcribe_enhanced_model.py resources/commercial_mono.wav |
| 22 | +""" |
| 23 | + |
| 24 | +import argparse |
| 25 | +import io |
| 26 | + |
| 27 | + |
| 28 | +def transcribe_file_with_enhanced_model(path): |
| 29 | + """Transcribe the given audio file using an enhanced model.""" |
| 30 | + # [START speech_transcribe_enhanced_model] |
| 31 | + from google.cloud import speech |
| 32 | + client = speech.SpeechClient() |
| 33 | + |
| 34 | + # path = 'resources/commercial_mono.wav' |
| 35 | + with io.open(path, 'rb') as audio_file: |
| 36 | + content = audio_file.read() |
| 37 | + |
| 38 | + audio = speech.types.RecognitionAudio(content=content) |
| 39 | + config = speech.types.RecognitionConfig( |
| 40 | + encoding=speech.enums.RecognitionConfig.AudioEncoding.LINEAR16, |
| 41 | + sample_rate_hertz=8000, |
| 42 | + language_code='en-US', |
| 43 | + # Enhanced models are only available to projects that |
| 44 | + # opt in for audio data collection. |
| 45 | + use_enhanced=True, |
| 46 | + # A model must be specified to use enhanced model. |
| 47 | + model='phone_call') |
| 48 | + |
| 49 | + response = client.recognize(config, audio) |
| 50 | + |
| 51 | + for i, result in enumerate(response.results): |
| 52 | + alternative = result.alternatives[0] |
| 53 | + print('-' * 20) |
| 54 | + print('First alternative of result {}'.format(i)) |
| 55 | + print('Transcript: {}'.format(alternative.transcript)) |
| 56 | + # [END speech_transcribe_enhanced_model] |
| 57 | + |
| 58 | + |
| 59 | +if __name__ == '__main__': |
| 60 | + parser = argparse.ArgumentParser( |
| 61 | + description=__doc__, |
| 62 | + formatter_class=argparse.RawDescriptionHelpFormatter) |
| 63 | + parser.add_argument('path', help='File to stream to the API') |
| 64 | + |
| 65 | + args = parser.parse_args() |
| 66 | + |
| 67 | + transcribe_file_with_enhanced_model(args.path) |
0 commit comments