forked from dylang/captionbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
48 lines (41 loc) · 1.3 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
'use strict';
const got = require('got');
const validUrl = require('valid-url').isUri;
function captionbot(imageUrl) {
if (!validUrl(imageUrl)) {
return Promise.reject(new Error('A valid url is required.'));
}
return got('https://www.captionbot.ai/api/init', {json: true})
.then(response => {
const conversationId = response.body;
const cookie = response.headers['set-cookie'][0].split(';')[0];
const options = {
body: {
conversationId: conversationId,
waterMark: '',
userMessage: imageUrl
},
headers: {
cookie: cookie
},
json: true
};
return got('https://www.captionbot.ai/api/message', options);
})
.then(response => {
return (JSON.parse(response.body).UserMessage || '').trim();
});
}
function callback(imageUrl, cb) {
captionbot(imageUrl)
.then(caption => cb(null, caption))
.catch(err => cb(err));
}
// callback support is provided for a training exercise
module.exports = (imageUrl, cb) => {
if (typeof cb === 'function') {
callback(imageUrl, cb);
} else {
return captionbot(imageUrl);
}
};