【问题标题】:How to use google cloud speech api in python如何在python中使用谷歌云语音api
【发布时间】:2017-01-02 06:53:58
【问题描述】:

我正在用 python 探索谷歌云语音 api。我正在关注这个 link。 我也提到了这个stackoverflow link。但是我被设置环境变量所震惊。

我做过的事情:

1.安装gcloud python模块

2.安装google-api-python-client模块

3.已设置服务账号(获取JSON文件)

4.获得API KEY

我对导出 GOOGLE_APPLICATION_CREDENTIALS 和 GCLOUD_PROJECT 环境变量感到震惊。

我的疑问是:

1.是否应该使用google cloud sdk导出?如果是,google cloud sdk在这里扮演什么角色,什么时候应该使用这个sdk?

2.由于我没有在代码中明确包含 API 密钥, 这是否意味着我的身份验证是在线自动验证的?在这种情况下,我在下面的代码中的 get_speech_service() 函数是做什么的?

下面是代码

import argparse
import base64
import json


import httplib2
from googleapiclient import discovery
from oauth2client.client import GoogleCredentials


if __name__ == '__main__':
   parser = argparse.ArgumentParser()
   parser.add_argument('speech_file',help='This is the path of the audio')
   args = parser.parse_args()
   print args.speech_file
   main(args.speech_file)

def main(speech_file):
    with open(speech_file,'rb') as speech:
         speech_content = base64.b64encode(speech.read())

    service = get_speech_service()
    service_request = service.speech().syncrecognize(
    body={
        'config':{
            'encoding':'LINEAR16',
            'sampleRate':16000,
            'languageCode':'en-US',
            },
        'audio':{
            'content':speech_content.decode('UTF-8')
            }
        })
    response = service_request.execute()
    print(json.dumps(response))
DISCOVERY_URL = ('https://speech.googleapis.com/$discovery/rest?/version=v1beta1')

def get_speech_service():
    credentials = GoogleCredentials.get_application_default().create_scoped(
    ['https://www.googleapis.com/auth/cloud-platform'])
    http = httplib2.Http()
    credentials.authorize(http)
    return    discovery.build('speech','v1beta1',http=http,discoveryServiceUrl=DISCOVERY_URL)

我google了很多次,我得到了提到的stackoverflow链接,它澄清了一些事情。由于我不清楚我的上述疑问,所以我在这里发布。

【问题讨论】:

    标签: speech-recognition speech-to-text google-cloud-speech google-python-api


    【解决方案1】:

    以下步骤对我有用。希望对你有所帮助。

    从 github 克隆以下 repo:

    git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git
    

    导航到文件夹:

    cd python-docs-samples/speech/cloud-client/
    

    安装 pip (确定你已经有了)和 virtualenv 。 执行以下命令:

    $ virtualenv env
    $ source env/bin/activate
    

    然后从 requirements.txt 安装

     pip install -r requirements.txt
    

    定义和导出 google 凭据路径(您已经这样做了)。

    export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service_account_file.json
    

    从快速示例脚本开始:

    python quickstart.py
    

    您应该得到以下输出:

    在此之后,您可以浏览同一文件夹中的其他脚本,也可以尝试 URI 示例进行长时间识别。

    【讨论】:

      猜你喜欢
      • 2017-05-01
      • 2023-04-09
      • 2017-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-08
      • 1970-01-01
      相关资源
      最近更新 更多