Skip to content

Commit

Permalink
Update the Cloud Functions Imagemagick Sample
Browse files Browse the repository at this point in the history
As requested in b//73815480
  • Loading branch information
michaelawyu committed Mar 7, 2018
1 parent c91fef0 commit 8d932e3
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 22 deletions.
15 changes: 10 additions & 5 deletions functions/imagemagick/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,10 @@ const exec = require('child_process').exec;
const fs = require('fs');
const path = require('path');
const storage = require('@google-cloud/storage')();
const vision = require('@google-cloud/vision')();
const vision = require('@google-cloud/vision');

// Create a client
const client = new vision.ImageAnnotatorClient();
// [END functions_imagemagick_setup]

// [START functions_imagemagick_analyze]
Expand All @@ -38,18 +41,20 @@ exports.blurOffensiveImages = (event) => {
}

const file = storage.bucket(object.bucket).file(object.name);
const file_uri = `gs://${object.bucket}/${object.name}`;

console.log(`Analyzing ${file.name}.`);

return vision.detectSafeSearch(file)
return client.safeSearchDetection(file_uri)
.catch((err) => {
console.error(`Failed to analyze ${file.name}.`, err);
return Promise.reject(err);
})
.then(([safeSearch]) => {
if (safeSearch.adult || safeSearch.violence) {
.then(([result]) => {
if (result.safeSearchAnnotation.adult == 'VERY_LIKELY' ||
result.safeSearchAnnotation.violence == 'VERY_LIKELY') {
console.log(`The image ${file.name} has been detected as inappropriate.`);
return blurImage(file, safeSearch);
return blurImage(file, result);
} else {
console.log(`The image ${file.name} has been detected as OK.`);
}
Expand Down
5 changes: 2 additions & 3 deletions functions/imagemagick/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,17 @@
},
"scripts": {
"lint": "samples lint",
"pretest": "npm run lint",
"test": "ava -T 20s --verbose test/*.test.js"
},
"dependencies": {
"@google-cloud/storage": "1.4.0",
"@google-cloud/vision": "0.12.0"
"@google-cloud/vision": "0.16.0"
},
"devDependencies": {
"@google-cloud/nodejs-repo-tools": "2.1.0",
"ava": "0.23.0",
"proxyquire": "1.8.0",
"sinon": "4.0.2"
"sinon": "4.4.2"
},
"cloud-repo-tools": {
"requiresKeyFile": true,
Expand Down
48 changes: 34 additions & 14 deletions functions/imagemagick/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,13 @@ const proxyquire = require(`proxyquire`).noCallThru();
const sinon = require(`sinon`);
const test = require(`ava`);
const tools = require(`@google-cloud/nodejs-repo-tools`);
const vision = require('@google-cloud/vision');

const bucketName = `my-bucket`;
const filename = `image.jpg`;
const safeFilename = `safe_image.jpg`;
const unsafeFilename = `unsafe_image.jpg`;

function getSample () {
function getSample (filename) {
const file = {
getMetadata: sinon.stub().returns(Promise.resolve([{}])),
setMetadata: sinon.stub().returns(Promise.resolve()),
Expand All @@ -39,11 +41,24 @@ function getSample () {
const storageMock = {
bucket: sinon.stub().returns(bucket)
};
const visionMock = {
detectSafeSearch: sinon.stub().returns(Promise.resolve([{ violence: true }]))
};
const StorageMock = sinon.stub().returns(storageMock);
const VisionMock = sinon.stub().returns(visionMock);
var safeSearchDetectionStub = sinon.stub()
safeSearchDetectionStub.withArgs(`gs://${bucketName}/${safeFilename}`).returns(Promise.resolve([{
safeSearchAnnotation: {
adult: 'VERY_LIKELY',
violence: 'VERY_LIKELY'
}
}]));
safeSearchDetectionStub.withArgs(`gs://${bucketName}/${unsafeFilename}`).returns(Promise.resolve([{
safeSearchAnnotation: {
adult: 'VERY_UNLIKELY',
violence: 'VERY_UNLIKELY'
}
}]));
var imageAnnotatorClientStub = sinon.stub(vision, "ImageAnnotatorClient");
imageAnnotatorClientStub.returns({
safeSearchDetection: safeSearchDetectionStub
});
const childProcessMock = {
exec: sinon.stub().yields()
};
Expand All @@ -53,7 +68,6 @@ function getSample () {

return {
program: proxyquire(`../`, {
'@google-cloud/vision': VisionMock,
'@google-cloud/storage': StorageMock,
'child_process': childProcessMock,
'fs': fsMock
Expand All @@ -63,14 +77,16 @@ function getSample () {
childProcess: childProcessMock,
storage: storageMock,
bucket,
file,
vision: visionMock
file
}
};
}

test.beforeEach(tools.stubConsole);
test.afterEach.always(tools.restoreConsole);
test.afterEach.always(function() {
vision.ImageAnnotatorClient.restore();
});

test.serial(`blurOffensiveImages does nothing on delete`, async (t) => {
await getSample().program.blurOffensiveImages({ data: { resourceState: `not_exists` } });
Expand All @@ -85,8 +101,8 @@ test.serial(`blurOffensiveImages does nothing on deploy`, async (t) => {
});

test.serial(`blurOffensiveImages blurs images`, async (t) => {
const sample = getSample();
await sample.program.blurOffensiveImages({ data: { bucket: bucketName, name: filename } });
const sample = getSample(safeFilename);
await sample.program.blurOffensiveImages({ data: { bucket: bucketName, name: safeFilename } });
t.is(console.log.callCount, 5);
t.deepEqual(console.log.getCall(0).args, [`Analyzing ${sample.mocks.file.name}.`]);
t.deepEqual(console.log.getCall(1).args, [`The image ${sample.mocks.file.name} has been detected as inappropriate.`]);
Expand All @@ -96,9 +112,13 @@ test.serial(`blurOffensiveImages blurs images`, async (t) => {
});

test.serial(`blurOffensiveImages ignores safe images`, async (t) => {
const sample = getSample();
sample.mocks.vision.detectSafeSearch = sinon.stub().returns(Promise.resolve([{}]));
await sample.program.blurOffensiveImages({ data: { bucket: bucketName, name: filename } });
const sample = getSample(unsafeFilename);
await sample.program.blurOffensiveImages({
data: {
bucket: bucketName,
name: unsafeFilename
}
});
t.is(console.log.callCount, 2);
t.deepEqual(console.log.getCall(0).args, [`Analyzing ${sample.mocks.file.name}.`]);
t.deepEqual(console.log.getCall(1).args, [`The image ${sample.mocks.file.name} has been detected as OK.`]);
Expand Down

0 comments on commit 8d932e3

Please sign in to comment.