Skip to content

Instantly share code, notes, and snippets.

@giolaq
Created October 29, 2017 08:08
Show Gist options
  • Select an option

  • Save giolaq/aa1b0d20ce1d3cfa614fb8f2e9275067 to your computer and use it in GitHub Desktop.

Select an option

Save giolaq/aa1b0d20ce1d3cfa614fb8f2e9275067 to your computer and use it in GitHub Desktop.
Script to use Firebase Cloud Functions and Vision API
const Vision = require('@google-cloud/vision');
const vision = Vision();
const functions = require('firebase-functions');
const admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);
exports.callVision = functions.storage.object().onChange(event => {
const object = event.data;
const fileBucket = object.bucket;
const filePath = object.name;
const gcsPath = `gs://${fileBucket}/${filePath}`;
// Prepare the request object
var req = {
image: {source: {imageUri: gcsPath}},
features: [{ type: Vision.v1.types.Feature.Type.WEB_DETECTION },
{ type: Vision.v1.types.Feature.Type.SAFE_SEARCH_DETECTION }],
};
console.log('vision api image ' + gcsPath);
// Call the Vision API's web detection and safe search detection endpoints
return vision.annotateImage(req).then(response => {
let webDetection = response[0].webDetection;
let safeSearch = response[0].safeSearchAnnotation;
return {web: webDetection, safe: safeSearch};
}).then((visionResp) => {
var db = admin.firestore();
let imageRef = db.collection('images').doc(filePath.slice(7));
return imageRef.set(visionResp);
})
.catch(err => {
console.log('vision api error', err);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment