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樣本爲了長久的認可。