Search code examples
firebasegoogle-cloud-platformgoogle-cloud-storageautomlgoogle-cloud-automl

How to use Google AutoML on web app?


I have a Google Cloud AutoML NL model ready to use. I wish to link this with my web app with Firebase backend. Following is my code to call. There is authorization issue. I want to understand how to authorize the app to help the client apps get access to AutoML model.

async add(data){
var headers = new Headers();
headers.append('Content-Type:application/json')

var options = {
  method: 'POST',
  headers,
  body: JSON.stringify(data)
}

var request = new Request('https://automl.googleapis.com/v1beta1/projects/project1/locations/us-central1/models/TCN5678:predict', options )

var response = await fetch(request)

var status = await response.status
console.log(status)}

Solution

  • After struggling for hours, finally I could resolve this. I am not sure how it can work for, other than Firebase (and NL AutoML). I used Firebase Cloud Function to work around and used a hidden doc which gives access to AutoML npm. The given code require some changes. Firebase CF is able to authenticate without explicitly authorizing. Following is a suggested code and I am able to get the classification of prediction with AutoML. Hope it helps others too. Lastly, it seems Google docs is a way of testing searching skills and patience, not sure how it helps them:

    const automl = require('@google-cloud/automl');
    exports.sendToAML = functions.database.ref('/path/to/text').onWrite((snapshot, context) =>{
    
    
    var client = new automl.PredictionServiceClient({
      // optional auth parameters.
    });
    
    var formattedName = client.modelPath('bucketId', 'us-central1', 'TCN****3567595');
    var payload = {
      "textSnippet": {
           "content": snapshot.after._data.text,
            "mime_type": "text/plain"
       },
    };
    var request = {
      name: formattedName,
      payload: payload,
    };
    client.predict(request)
      .then(responses => {
        var response = responses[0];
        return console.log(response.payload[0].classification.score)
      })
      .catch(err => {
        console.error(err);
      });
    });
    

    `