-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
319 lines (273 loc) · 7.99 KB
/
index.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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
var _ = require('lodash')
var needle = require('needle')
var _array = function(str) {
if (_.isArray(str)) {
return str
} else {
return [str]
}
}
var _encodeTagUrls = function(urls, opts) {
var data = ''
for (var url of _array(urls)) {
data += encodeURI('url=' + url) + '&'
}
if (opts.lang) {
data += 'language=' + opts.lang
}
if (opts.model) {
switch (opts.model) {
case 'general': {
data += 'model=' + 'general-v1.3'
break
}
case 'nsfw': {
data += 'model=' + 'nsfw-v1.0'
break
}
case 'weddings': {
data += 'model=' + 'weddings-v1.0'
break
}
default: {
data += 'model=' + 'weddings-v1.0'
break
}
}
}
return data
}
var _boundary = 'clarifai_multipart_boundary'
var _partForParameter = function(name, value) {
var part = '--' + _boundary + '\r\nContent-Disposition: form-data; name="' + name + '"\r\n\r\n' + value + '\r\n'
return new Buffer(part, 'utf8');
}
var _buildMultipart = function(buffers, opts) {
// Build a multipart payload. We can't use needle's support for this because needle expects all
// parts to have distinct names while Clarifai requires multiple parts to have the same name.
var chunks = []
for (var buffer of _array(buffers)) {
var header = '--' + _boundary + '\r\n' +
'Content-Disposition: form-data; name="encoded_data"; filename="data"\r\n' +
'Content-Transfer-Encoding: binary\r\n' +
'Content-Type: application/octet-stream\r\n\r\n'
chunks.push(new Buffer(header, 'ascii'))
chunks.push(buffer)
}
if (opts.lang) {
chunks.push(_partForParameter('language', opts.lang))
}
if (opts.model) {
switch (opts.model) {
case 'general': {
chunks.push(_partForParameter('model', 'general-v1.3'))
break
}
case 'nsfw': {
chunks.push(_partForParameter('model', 'nsfw-v1.0'))
break
}
case 'weddings': {
chunks.push(_partForParameter('model', 'weddings-v1.0'))
break
}
default: {
chunks.push(_partForParameter('model', 'general-v1.3'))
break
}
}
}
chunks.push(new Buffer('--' + _boundary + '--\r\n', 'ascii'))
return Buffer.concat(chunks)
}
var _parseErr = function(err, resp, body, cb) {
if (err) {
return cb(err)
} else if ((resp.statusCode !== 200 && resp.statusCode !== 201) || body.status_code === 'PARTIAL_ERROR') {
return cb(body)
} else {
return cb(err, body)
}
}
var _withAccessToken = function(_this, options) {
return _.merge(options, { headers: { Authorization: _this.tokenType + ' ' + _this.accessToken }});
}
var _request = function(verb, type, data, options, _this, cb) {
var url = 'https://api.clarifai.com'
switch (type) {
case 'feedback': {
url += '/v1/feedback/'
break
}
case 'info': {
url += '/v1/info/'
break
}
case 'tag': {
url += '/v1/tag/'
break
}
case 'token': {
url += '/v1/token/'
break
}
default: {
throw err('Request Type not defined')
}
}
needle.request(verb, url, data, _withAccessToken(_this, options), function(err, resp, body) {
if (body.status_code === 'TOKEN_INVALID' || body.status_code === 'TOKEN_NONE') {
_this.getAccessToken(function(err) {
if (err) {
return cb(err)
} else {
needle.request(verb, url, data, _withAccessToken(_this, options), function(err, resp, body) {
_parseErr(err, resp, body, cb)
})
}
})
} else {
_parseErr(err, resp, body, cb)
}
})
}
var formatImageResults = function(body) {
var results = body.results
results = _.map(results, function(result) {
var tagResults = _.zip(result.result.tag.classes, result.result.tag.concept_ids, result.result.tag.probs)
var tags = _.map(tagResults, function(tag) {
return {
class: tag[0],
conceptId: tag[1],
probability: tag[2],
}
})
var ret = {
docId: result.docid,
docIdStr: result.docid_str,
tags: tags,
}
return ret
})
if (results.length < 2) {
results = _.first(results)
}
return results
}
var formatVideoResults = function(body) {
var results = body.results
results = _.map(results, function(result) {
var tagResults = _.zip(result.result.tag.timestamps, result.result.tag.classes, result.result.tag.concept_ids, result.result.tag.probs)
var timestamps = _.map(tagResults, function(tag) {
var timeStampResults = _.zip(tag[1], tag[2], tag[3])
return {
timestamp: tag[0],
tags: _.map(timeStampResults, function(tsResult) {
return {
class: tsResult[0],
conceptId: tsResult[1],
probability: tsResult[2],
}
}),
}
})
var ret = {
docId: result.docid,
docIdStr: result.docid_str,
timestamps: timestamps,
}
return ret
})
if (results.length < 2) {
results = _.first(results)
}
return results
}
Clarifai.prototype.getAccessToken = function(cb) {
var _this = this
var data = {
grant_type: 'client_credentials',
client_id: this.id,
client_secret: this.secret,
}
_request('post', 'token', data, null, this, function(err, body) {
_this.accessToken = body.access_token
_this.expiresIn = body.expires_in
_this.scope = body.scope
_this.tokenType = body.token_type
cb(err, _this.accessToken)
})
}
Clarifai.prototype.addTags = function(docIds, tags, cb) {
var data = ''
data += 'docids=' + _array(docIds).join(',')
data += '&add_tags=' + _array(tags).join(',')
_request('post', 'feedback', data, this.options, this, cb)
}
Clarifai.prototype.removeTags = function(docIds, tags, cb) {
var data = ''
data += 'docids=' + _array(docIds).join(',')
data += '&remove_tags=' + _array(tags).join(',')
_request('post', 'feedback', data, this.options, this, cb)
}
Clarifai.prototype.addSimilarDocIds = function(docIds, otherIds, cb) {
var data = ''
data += 'docids=' + _array(docIds).join(',')
data += '&similar_docids=' + _array(otherIds).join(',')
_request('post', 'feedback', data, this.options, this, cb)
}
Clarifai.prototype.addDissimilarDocIds = function(docIds, otherIds, cb) {
var data = ''
data += 'docids=' + _array(docIds).join(',')
data += '&dissimilar_docids=' + _array(otherIds).join(',')
_request('post', 'feedback', data, this.options, this, cb)
}
Clarifai.prototype.associateSearchTerms = function(docIds, terms, cb) {
var data = ''
data += 'docids=' + _array(docIds).join(',')
data += '&search_click=' + _array(terms).join(',')
_request('post', 'feedback', data, this.options, this, cb)
}
Clarifai.prototype.getAPIDetails = function(cb) {
_request('get', 'info', null, this.options, this, function(err, body) {
cb(err, body.results)
})
}
Clarifai.prototype.tagFromUrls = function(type, urls, cb, opts) {
var data = _encodeTagUrls(urls, opts)
_request('post', 'tag', data, this.options, this, function(err, body) {
if (err) {
return cb(err)
} else if (type === 'image') {
return cb(err, formatImageResults(body))
} else {
return cb(err, formatVideoResults(body))
}
})
}
Clarifai.prototype.tagFromBuffers = function(type, buffers, cb, opts) {
var data = _buildMultipart(buffers, opts)
var options = _.cloneDeep(this.options || {})
options.headers = options.headers || {}
options.headers['Content-Type'] = 'multipart/form-data; boundary=' + _boundary
options.headers['Content-Length'] = data.length
_request('post', 'tag', data, options, this, function(err, body) {
if (err) {
return cb(err)
} else if (type === 'image') {
return cb(err, formatImageResults(body))
} else {
return cb(err, formatVideoResults(body))
}
})
}
function Clarifai(opts) {
opts = opts || {
id: process.env.CLARIFAI_ID,
secret: process.env.CLARIFAI_SECRET,
}
this.id = opts.id
this.secret = opts.secret
this.options = this.options || {}
}
module.exports = Clarifai