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 257
/
analysis.js
242 lines (228 loc) · 6.7 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
/**
* 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-darkvision"
* - watsonApiKey: "123456"
* - doc: "image document in cloudant"
*/
function main(args) {
return new Promise((resolve, reject) => {
mainImpl(args, (err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
}
exports.main = main;
/**
* @param mainCallback(err, analysis)
*/
function mainImpl(args, mainCallback) {
const fs = require('fs');
const startTime = (new Date()).getTime();
if (args.doc) {
const imageDocumentId = args.doc._id;
console.log('[', imageDocumentId, '] Processing image.jpg from document');
// use image id to build a unique filename
const fileName = `${imageDocumentId}-image.jpg`;
const mediaStorage = require('./lib/cloudantstorage')({
cloudantUrl: args.cloudantUrl,
cloudantDbName: args.cloudantDbName
});
const async = require('async');
async.waterfall([
// get the image document from the db
(callback) => {
mediaStorage.get(imageDocumentId, (err, image) => {
callback(err, image);
});
},
// get the image binary
(image, callback) => {
mediaStorage.read(image, 'image.jpg', {
// as we analyze images in batch it means, a lot of load on Cloudant
// so we may get rate-limited if using Cloudant for attachments
useRetry: true
}).pipe(fs.createWriteStream(fileName))
.on('finish', () => {
callback(null, image);
})
.on('error', (err) => {
callback(err);
});
},
// trigger the analysis on the image file
(image, callback) => {
processImage(args, fileName, (err, analysis) => {
if (err) {
callback(err);
} else {
callback(null, image, analysis);
}
});
},
// write result in the db
(image, analysis, callback) => {
image.analysis = analysis;
mediaStorage.insert(image, (err) => {
if (err) {
callback(err);
} else {
callback(null, analysis);
}
});
}
], (err, analysis) => {
const 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;
}
console.log('Parameter "doc" not found', args);
mainCallback('Parameter "doc" not found');
return false;
}
/**
* Prepares and analyzes the image.
* processCallback = function(err, analysis);
*/
function processImage(args, fileName, processCallback) {
prepareImage(fileName, (prepareErr, prepareFileName) => {
if (prepareErr) {
processCallback(prepareErr, null);
} else {
analyzeImage(args, prepareFileName, (err, analysis) => {
const fs = require('fs');
fs.unlink(prepareFileName, (unlinkErr) => {
if (unlinkErr) {
console.log(unlinkErr);
}
});
processCallback(err, analysis);
});
}
});
}
/**
* Prepares the image, resizing it if it is too big for Watson.
* prepareCallback = function(err, fileName);
*/
function prepareImage(fileName, prepareCallback) {
const fs = require('fs');
const async = require('async');
const gm = require('gm').subClass({
imageMagick: true
});
async.waterfall([
(callback) => {
// Retrieve the file size
fs.stat(fileName, (err, stats) => {
if (err) {
callback(err);
} else {
callback(null, stats);
}
});
},
// Check if size is OK
(fileStats, callback) => {
if (fileStats.size > 900 * 1024) {
// Resize the file
gm(fileName).define('jpeg:extent=900KB').write(`${fileName}.jpg`,
(err) => {
if (err) {
callback(err);
} else {
// Process the modified file
callback(null, `${fileName}.jpg`);
}
});
} else {
callback(null, fileName);
}
}
], (err, resultFileName) => {
prepareCallback(err, resultFileName);
});
}
/**
* Analyzes the image stored at fileName with the callback onAnalysisComplete(err, analysis).
* analyzeCallback = function(err, analysis);
*/
function analyzeImage(args, fileName, analyzeCallback) {
const request = require('request');
const async = require('async');
const fs = require('fs');
const gm = require('gm').subClass({
imageMagick: true
});
const analysis = {};
async.parallel([
(callback) => {
// Write down meta data about the image
gm(fileName).size((err, size) => {
if (err) {
console.log('Image size', err);
} else {
analysis.size = size;
}
callback(null);
});
},
(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',
url: 'https://gateway.watsonplatform.net/visual-recognition/api/v3/classify' + // eslint-disable-line
'?api_key=' + args.watsonApiKey +
'&version=2018-03-19',
auth: {
user: 'apikey',
pass: args.watsonApiKey,
},
headers: {
'Content-Length': fs.statSync(fileName).size
},
json: true
}, (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);
}));
}
],
(err) => {
analyzeCallback(err, analysis);
});
}