Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 786
roma Avatar asked Dec 13 '22 08:12

roma


2 Answers

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

like image 100
TheMaster Avatar answered Dec 28 '22 07:12

TheMaster


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

}
like image 45
roma Avatar answered Dec 28 '22 05:12

roma