How can I authorize Google Speech-to-text from Google Apps script?

早过忘川 提交于 2020-05-14 08:47:32

问题


I'm trying to execute google-speech-to-text from apps script. Unfortunately, I cannot find any examples for apps script or pure HTTP, so I can run it using simple UrlFetchApp.

I created a service account and setup a project with enabled speech-to-text api, and was able to successfully run recognition using command-line example

curl -s -H "Content-Type: application/json" \ -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \ https://speech.googleapis.com/v1/speech:recognize \ -d @sync-request.json

which I can easily translate to UrlFetchApp call, but I don't have an idea to generate access token created by

gcloud auth application-default print-access-token

Is there a way to get it from apps script using service account credentials?

Or is there any other way to auth and access speech-to-text from apps script?


回答1:


The equivalent of retrieving access tokens through service accounts is through the apps script oauth library. The library handles creation of the JWT token.

Sample here




回答2:


Using the answer from TheMaster, I was able to build a getToken solution for my case

`

function check() {
  var service = getService();
  if (service.hasAccess()) {
    Logger.log(service.getAccessToken());
  } else {
    Logger.log(service.getLastError());
  }
}

function getService() {
  return OAuth2.createService('Speech-To-Text Token')
      .setTokenUrl('https://oauth2.googleapis.com/token')
      .setPrivateKey(PRIVATE_KEY)
      .setIssuer(CLIENT_EMAIL)
      .setPropertyStore(PropertiesService.getScriptProperties())
      .setScope('https://www.googleapis.com/auth/cloud-platform');
}

`

The code for transcribe itself, is

function transcribe(){
  var payload = {
    "config": {
      "encoding" : "ENCODING_UNSPECIFIED",
      "sampleRateHertz": 48000,
      "languageCode": "en-US",
      "enableWordTimeOffsets": false
    },
    "audio": {
      content: CONTENT
    }
  };

  var response = UrlFetchApp.fetch(
    "https://speech.googleapis.com/v1/speech:recognize", {
      method: "GET",
      headers: {
        "Authorization" : "Bearer " + getService().getAccessToken()
      },
      contentType: "application/json",
      payload: JSON.stringify(payload),
      muteHttpExceptions: true
    });  

  Logger.log(response.getContentText());

}


来源:https://stackoverflow.com/questions/61466912/how-can-i-authorize-google-speech-to-text-from-google-apps-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!