3

我正在探索python中的google云语音api。我正在关注这个link。 我也提到了这个stackoverflow link。但是我对设置环境变量感到震惊。如何在python中使用google云语音api

我所做的事情:

1.Installed gcloud Python模块

2.Installed谷歌API的Python客户端模块

3.Had设立了服务帐户(获得JSON文件)

4.Obtained API密钥

我获得了出口GOOGLE_APPLICATION_CREDENTIALS和GCLOUD_PROJECT环境变量来袭。

我的疑惑是:

1.Should他们使用谷歌云SDK出口如果是这样,谷歌云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了很多次,我得到的计算器提到的链接,这澄清了一些things.Since我不清楚我的疑惑以上我张贴在这里。

回答

0

以下步骤适用于我。希望它对你有一些用处。从GitHub以下回购

克隆:

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 

定义和出口谷歌凭据路径(你已经这样做了)。

export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service_account_file.json 

启动与快速示例脚本:

python quickstart.py 

你应该得到以下输出: enter image description here

在此之后,你可以在同一个文件夹中探索其他脚本,也尝试URI样本为了长久的认可。