Koh
Koh

Reputation: 2897

Cloud Vision: Credentials issues

I am attempting to setup Cloud Vision on my local machine in a Firebase project but I am encountering problems with the default credentials.

First, I encountered Could not load the default credentials. This post suggested that I do gcloud auth application-default login. Upon attempting that, I encountered this:

Error: 7 PERMISSION_DENIED: Your application has authenticated using end user credentials from the Google Cloud SDK or Google Cloud Shell which are not supported by the vision.googleapis.com. We recommend configuring the billing/quota_project setting in gcloud or using a service account through the auth/impersonate_service_account setting. For more information about service accounts and how to use them in your application, see https://cloud.google.com/docs/authentication/.

I also attempted exports GOOGLE_APPLICATION_CREDENTIALS = "pathToServiceAccount" but it didn't work in my case.

Note that I have no issue reading/writing data to Firestore and Firebase Storage. The moment my code hits the Cloud Vision part, it throws the error. I have activated the API on cloud console and enabled billing. Security rules in firestore and storage are in testing mode at this moment.

const vision = require('@google-cloud/vision');
var admin = require('firebase-admin');
let serviceAccount = require('../path-to-service-account.json');

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    storageBucket: "mybucket.appspot.com"
});

let db = admin.firestore()
let bucket = admin.storage().bucket();

//Some networking code, return a promise
.then(response => {
    //setup storagePath
    return pipeToStorage(item, response, storagePath) //Save to firebase storage ok
})
.then((item) => {
    return performTextDetection(item.id) //Throws error here
})

function pipeToStorage(item, response, storagePath) {
    return new Promise((resolve, reject) => {
        gcFile = bucket.file(storagePath)

        response.data
        .pipe(gcFile.createWriteStream({
            metadata   : {
                contentType: "application/pdf"
            }
        }))
        .on('error', (error) => { 
            reject(error)
        })
        .on('finish', () => { 
            resolve(item)
        })
    }) 
}


function performTextDetection(id) {
    const client = new vision.ImageAnnotatorClient();
    const bucketName = bucket.name;
    const fileName = `items/${id}.pdf`
    const outputPrefix = 'ocr_results'
    const gcsSourceUri = `gs://${bucketName}/${fileName}`;
    const gcsDestinationUri = `gs://${bucketName}/${outputPrefix}/${id}/`;

    const inputConfig = {
        mimeType: 'application/pdf',
        gcsSource: {
            uri: gcsSourceUri,
        },
    };
    const outputConfig = {
        gcsDestination: {
            uri: gcsDestinationUri,
        },
    };
    const features = [{type: 'DOCUMENT_TEXT_DETECTION'}];
    const request = {
        requests: [
            {
            inputConfig: inputConfig,
            features: features,
            outputConfig: outputConfig,
            },
        ],
    };

    return client.asyncBatchAnnotateFiles(request)
    .then(([operation]) => {
        return operation.promise()
    })
    .then(([filesResponse]) => {
        const resultsUri = filesResponse.responses[0].outputConfig.gcsDestination.uri
        return resultsUri
    })
}

Upvotes: 1

Views: 324

Answers (1)

rsantiago
rsantiago

Reputation: 2099

This happens because you have exports rather than export:

exports GOOGLE_APPLICATION_CREDENTIALS = "pathToServiceAccount"

please try:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/credentials.json"

note that there are not spaces, see details here. By the way, I have also found the same PERMISSION_DENIED error when export is omitted.

The validation step is executing a REST request with curl:

curl -X POST \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
https://vision.googleapis.com/v1/images:annotate

See the complete example here.

Upvotes: 1

Related Questions