I need to write a Cloud Function, and the sole permitted programming language is Node. Honestly I just have a slight idea about Node, but I am daring to write code based on some examples given in the GCP documentation. Here it is:
'use strict';
// [START functions_ocr_setup]
const config = require('./config.json');
// Get a reference to the Cloud Storage component
const storage = require('@google-cloud/storage')({
keyFilename: './pathtomyserviceaccount.json',
projectId: 'projectId'
});
// Get a reference to the Cloud Vision API component
const vision = require('@google-cloud/vision')({
keyFilename: './pathtomyserviceaccount.json',
projectId: 'projectId'
});
// [END functions_ocr_setup]
// [START functions_ocr_detect]
function detectText (file) {
console.log('Haya vamos!');
return vision.readDocument(file)
.then((results) => {
const fullTextAnnotation = results[1].responses[0].fullTextAnnotation;
console.log(fullTextAnnotation.text);
})
.catch((err) => {
console.error('ERRORes:', err);
});
}
// [END functions_ocr_detect]
// [START functions_ocr_process]
/**
* Cloud Function triggered by Cloud Storage when a file is uploaded.
*
* @param {object} event The Cloud Functions event.
* @param {object} event.data A Google Cloud Storage File object.
*/
exports.processImage = function processImage (event) {
let file = event.data;
return Promise.resolve()
.then(() => {
if (file.resourceState === 'not_exists') {
// This was a deletion event, we don't want to process this
return;
}
if (!file.bucket) {
throw new Error('Bucket not provided. Make sure you have a "bucket" property in your request');
}
if (!file.name) {
throw new Error('Filename not provided. Make sure you have a "name" property in your request');
}
return detectText(storage.bucket(file.bucket).file(file.name));
})
.then(() => {
console.log(`File ${file.name} processed.`);
});
};
// [END functions_ocr_process]
The file 'serviceaccount.json' is located in the same folder as the index.js (yes, it contains the function 'processImage' that I want GC to execute).
Looking in the log of the corresponding GC Funtion, I get the following error:
PartialFailureError: A failure occurred during this request
I've been doing some testing, and I intuit that the error is related to the 'readDocument' call... Once again, I recognize I'm a newcomer in Node, so I would really appreciate any hint or suggestion!!! Many thanks in advance!!!
via Rafael Vizcaino Gonzalez
No comments:
Post a Comment