简体   繁体   中英

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

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?

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

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());

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM