forked from microsoft/BotBuilder-Samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimage-service.js
73 lines (67 loc) · 2.52 KB
/
image-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
// The exported functions in this module makes a call to Bing Image Search API returns similar products description if found.
// Note: you can do more functionalities like recognizing entities. For more info checkout the API reference:
// https://msdn.microsoft.com/en-us/library/dn760791.aspx
var request = require('request').defaults({ encoding: null });
var BING_API_URL = 'https://api.cognitive.microsoft.com/bing/v5.0/images/search?modulesRequested=SimilarProducts&mkt=en-us&form=BCSPRD';
var BING_SEARCH_API_KEY = process.env.BING_SEARCH_API_KEY;
/**
* Gets the similar products of the image from an image stream
* @param {stream} stream The stream to an image.
* @return {Promise} Promise with visuallySimilarProducts array if succeeded, error otherwise
*/
exports.getSimilarProductsFromStream = function (stream) {
return new Promise(
function (resolve, reject) {
var requestData = {
url: BING_API_URL,
encoding: 'binary',
formData: {
file: stream
},
headers: {
'Ocp-Apim-Subscription-Key': BING_SEARCH_API_KEY
}
};
request.post(requestData, function (error, response, body) {
if (error) {
reject(error);
}
else if (response.statusCode !== 200) {
reject(body);
}
else {
resolve(JSON.parse(body).visuallySimilarProducts);
}
});
}
);
};
/**
* Gets the similar products of the image from an image URL
* @param {string} url The URL to an image.
* @return {Promise} Promise with visuallySimilarProducts array if succeeded, error otherwise
*/
exports.getSimilarProductsFromUrl = function (url) {
return new Promise(
function (resolve, reject) {
var requestData = {
url: BING_API_URL + '&imgurl=' + url,
headers: {
'Ocp-Apim-Subscription-Key': BING_SEARCH_API_KEY
},
json: true
};
request.get(requestData, function (error, response, body) {
if (error) {
reject(error);
}
else if (response.statusCode !== 200) {
reject(body);
}
else {
resolve(body.visuallySimilarProducts);
}
});
}
);
};