forked from microsoft/BotBuilder-Samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
caption-service.js
84 lines (77 loc) · 2.99 KB
/
caption-service.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
// The exported functions in this module makes a call to Microsoft Cognitive Service Computer Vision API and return caption
// description if found. Note: you can do more advanced functionalities like checking
// the confidence score of the caption. For more info checkout the API documentation:
// https://www.microsoft.com/cognitive-services/en-us/Computer-Vision-API/documentation/AnalyzeImage
var request = require('request').defaults({ encoding: null });
/**
* Gets the caption of the image from an image stream
* @param {stream} stream The stream to an image.
* @return {Promise} Promise with caption string if succeeded, error otherwise
*/
exports.getCaptionFromStream = function (stream) {
var apiUrl = process.env.MICROSOFT_VISION_API_ENDPOINT + '/analyze?visualFeatures=Description'
return new Promise(
function (resolve, reject) {
var requestData = {
url: apiUrl,
encoding: 'binary',
json: true,
headers: {
'Ocp-Apim-Subscription-Key': process.env.MICROSOFT_VISION_API_KEY,
'content-type': 'application/octet-stream'
}
};
stream.pipe(request.post(requestData, function (error, response, body) {
if (error) {
reject(error);
} else if (response.statusCode !== 200) {
reject(body);
} else {
resolve(extractCaption(body));
}
}));
}
);
};
/**
* Gets the caption of the image from an image URL
* @param {string} url The URL to an image.
* @return {Promise} Promise with caption string if succeeded, error otherwise
*/
exports.getCaptionFromUrl = function (url) {
var apiUrl = process.env.MICROSOFT_VISION_API_ENDPOINT + '/analyze?visualFeatures=Description'
return new Promise(
function (resolve, reject) {
var requestData = {
url: apiUrl,
json: { 'url': url },
headers: {
'Ocp-Apim-Subscription-Key': process.env.MICROSOFT_VISION_API_KEY,
'content-type': 'application/json'
}
};
request.post(requestData, function (error, response, body) {
if (error) {
reject(error);
}
else if (response.statusCode !== 200) {
reject(body);
}
else {
resolve(extractCaption(body));
}
});
}
);
};
/**
* Extracts the caption description from the response of the Vision API
* @param {Object} body Response of the Vision API
* @return {string} Description if caption found, null otherwise.
*/
function extractCaption(body) {
if (body && body.description && body.description.captions && body.description.captions.length) {
return body.description.captions[0].text;
}
return null;
}