This repository has been archived by the owner on Jan 12, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
/
analysis.js
251 lines (237 loc) · 7.33 KB
/
analysis.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
/**
* Copyright 2016 IBM Corp. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the “License”);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an “AS IS” BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Called by Whisk.
*
* It expects the following parameters as attributes of "args"
* - cloudantUrl: "https://username:password@host"
* - cloudantDbName: "openwhisk-vision"
* - watsonApiKey: "123456"
* - imageDocumentId: "image document ID in cloudant"
*/
function main(args) {
return new Promise(function(resolve, reject) {
mainImpl(args, function(err, result) {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
}
/**
* @param mainCallback(err, analysis)
*/
function mainImpl(args, mainCallback) {
var fs = require('fs')
var request = require('request')
var startTime = (new Date).getTime();
if (args.hasOwnProperty("imageDocumentId")) {
var imageDocumentId = args.imageDocumentId;
console.log("[", imageDocumentId, "] Processing image.jpg from document");
var cloudant = require("cloudant")({url: args.cloudantUrl});
var visionDb = cloudant.db.use(args.cloudantDbName);
// use image id to build a unique filename
var fileName = imageDocumentId + "-image.jpg";
var async = require('async')
async.waterfall([
// get the image document from the db
function (callback) {
visionDb.get(imageDocumentId, {
include_docs: true
}, function (err, image) {
callback(err, image);
});
},
// get the image binary
function (image, callback) {
visionDb.attachment.get(image._id, "image.jpg").pipe(fs.createWriteStream(fileName))
.on("finish", function () {
callback(null, image);
})
.on("error", function (err) {
callback(err);
});
},
// trigger the analysis on the image file
function (image, callback) {
processImage(args, fileName, function (err, analysis) {
if (err) {
callback(err);
} else {
callback(null, analysis);
}
});
}
], function (err, analysis) {
var durationInSeconds = ((new Date).getTime() - startTime) / 1000;
if (err) {
console.log("[", imageDocumentId, "] KO (", durationInSeconds, "s)", err);
mainCallback(err);
} else {
console.log("[", imageDocumentId, "] OK (", durationInSeconds, "s)");
mainCallback(null, analysis);
}
});
return true;
} else {
console.log("Parameter 'imageDocumentId' not found", args);
mainCallback("Parameter 'imageDocumentId' not found");
return false;
}
}
/**
* Prepares and analyzes the image.
* processCallback = function(err, analysis);
*/
function processImage(args, fileName, processCallback) {
prepareImage(fileName, function (prepareErr, prepareFileName) {
if (prepareErr) {
processCallback(prepareErr, null);
} else {
analyzeImage(args, prepareFileName, function (err, analysis) {
var fs = require('fs');
fs.unlink(prepareFileName);
processCallback(err, analysis);
});
}
});
}
/**
* Prepares the image, resizing it if it is too big for Watson.
* prepareCallback = function(err, fileName);
*/
function prepareImage(fileName, prepareCallback) {
var
fs = require('fs'),
async = require('async'),
gm = require('gm').subClass({
imageMagick: true
});
async.waterfall([
function (callback) {
// Retrieve the file size
fs.stat(fileName, function (err, stats) {
if (err) {
callback(err);
} else {
callback(null, stats);
}
});
},
// Check if size is OK
function (fileStats, callback) {
if (fileStats.size > 900 * 1024) {
// Resize the file
gm(fileName).define("jpeg:extent=900KB").write(fileName + ".jpg",
function (err) {
if (err) {
callback(err);
} else {
// Process the modified file
callback(null, fileName + ".jpg");
}
});
} else {
callback(null, fileName);
}
}
], function (err, fileName) {
prepareCallback(err, fileName);
});
}
/**
* Analyzes the image stored at fileName with the callback onAnalysisComplete(err, analysis).
* analyzeCallback = function(err, analysis);
*/
function analyzeImage(args, fileName, analyzeCallback) {
var
request = require('request'),
async = require('async'),
fs = require('fs'),
gm = require('gm').subClass({
imageMagick: true
}),
analysis = {};
async.parallel([
function (callback) {
// Write down meta data about the image
gm(fileName).size(function (err, size) {
if (err) {
console.log("Image size", err);
} else {
analysis.size = size;
}
callback(null);
});
},
function (callback) {
// Call Face Detection passing the image in the request
// http://www.ibm.com/watson/developercloud/visual-recognition/api/v3/?curl#detect_faces
fs.createReadStream(fileName).pipe(
request({
method: "POST",
auth: {
username: 'apikey',
password: args.watsonApiKey
},
url: 'https://gateway.watsonplatform.net/visual-recognition/api/v3/detect_faces?version=2018-03-19',
headers: {
'Content-Length': fs.statSync(fileName).size
},
json: true
},
function (err, response, body) {
if (err) {
console.log("Face Detection", err);
} else if (body.images && body.images.length > 0) {
analysis.face_detection = body.images[0].faces;
}
callback(null);
}));
},
function (callback) {
// Call Classify passing the image in the request
// http://www.ibm.com/watson/developercloud/visual-recognition/api/v3/?curl#classify_an_image
fs.createReadStream(fileName).pipe(
request({
method: "POST",
auth: {
username: 'apikey',
password: args.watsonApiKey
},
url: "https://gateway.watsonplatform.net/visual-recognition/api/v3/classify?version=2018-03-19",
headers: {
'Content-Length': fs.statSync(fileName).size
},
json: true
},
function (err, response, body) {
if (err) {
console.log("Image Keywords", err);
} else if (body.images && body.images.length > 0) {
analysis.image_keywords = body.images[0].classifiers[0].classes;
}
callback(null);
}));
}
],
function (err, result) {
analyzeCallback(err, analysis);
}
)
}