|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +# Copyright 2017 Google Inc. All Rights Reserved. |
| 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 application using the streaming API. |
| 18 | +
|
| 19 | +Example usage: |
| 20 | + python transcribe_streaming.py resources/audio.raw |
| 21 | +""" |
| 22 | + |
| 23 | +# [START import_libraries] |
| 24 | +import argparse |
| 25 | +import io |
| 26 | +# [END import_libraries] |
| 27 | + |
| 28 | + |
| 29 | +def transcribe_streaming(stream_file): |
| 30 | + """Streams transcription of the given audio file.""" |
| 31 | + from google.cloud import speech |
| 32 | + speech_client = speech.Client() |
| 33 | + |
| 34 | + with io.open(stream_file, 'rb') as audio_file: |
| 35 | + audio_sample = speech_client.sample( |
| 36 | + stream=audio_file, |
| 37 | + encoding=speech.encoding.Encoding.LINEAR16, |
| 38 | + sample_rate=16000) |
| 39 | + alternatives = audio_sample.streaming_recognize() |
| 40 | + |
| 41 | + for alternative in alternatives: |
| 42 | + print('Finished: {}'.format(alternative.is_final)) |
| 43 | + print('Stability: {}'.format(alternative.stability)) |
| 44 | + print('Transcript: {}'.format(alternative.confidence)) |
| 45 | + print('Transcript: {}'.format(alternative.transcript)) |
| 46 | + |
| 47 | + |
| 48 | +if __name__ == '__main__': |
| 49 | + parser = argparse.ArgumentParser( |
| 50 | + description=__doc__, |
| 51 | + formatter_class=argparse.RawDescriptionHelpFormatter) |
| 52 | + parser.add_argument('stream', help='File to stream to the API') |
| 53 | + args = parser.parse_args() |
| 54 | + transcribe_streaming(args.stream) |
0 commit comments