'use strict';
const https = require('https');
//NOTE the latest aws-sdk must be bundled as Rekognition is not part of the default image at the time of writing
const AWS = require('aws-sdk');
const stream = require('stream').Transform;
const rekognition = new AWS.rekognition();
//TODO Expand the list of celebs
const celebs = {
'Selen Gomez': 'selenagomez',
'Taylor Swift': 'taylorswift',
'Ariana Grande': 'arianagrande'
};
let getLabels = function (image) {
return new Promise(function (resolve, reject) {
var params = {
Image: {
Bytes: image.read()
},
MaxLabels: 1
};
rekognition.detectLabels(params, function (err, data) {
if (err) {
reject(err);
}
else {
resolve(data.Labels);
}
});
});
};
let getImage = function (url) {
return new Promise(function (resolve, reject) {
var req = https.request(url, (res) => {
let data = new stream();
res.on('data', (d) => {
data.push(d);
});
res.on('end', () => {
getLabels(data).then((labels) => {
resolve(labels);
});
})
});
req.end();
req.on('error', (e) => {
reject(error);
});
});
};
exports.handler = (event, context, callback) => {
let person = event.request.intent.slots.Name.value;
let id = celebs[person];
https.get(`https://www.instagram.com/${id}/media/`, (res) => {
let data = '';
res.on('data', (d) => {
data += d;
});
res.on('end', () => {
let items = JSON.parse(data).items;
let promises = [];
let counter = 0;
for (let item of items) {
counter++;
let url = item.images.standard_resolution.url;
promises.push(getImage(url));
}
Promise.all(promises).then((labels) => {
labels = [].concat.apply([], labels);
//TODO replace, this is hacky
let t = {};
for (let label of labels) {
if (t[label.Name]) {
t[label.Name] = t[label.Name] + 1
} else {
t[label.Name] = 0
}
}
let speak = '';
for (let name in t) {
speak += `${name} and `
}
speak = speak.substr(0, speak.lastIndexOf('and '));
const handlers = {
'LaunchRequest': function () {
this.emit(':tell', 'Hello');
},
'GetName': function () {
//TODO replace with pauses and language library
this.emit(':tell', `${person} has been snapping pictures that contain ${speak}`);
},
'AMAZON.CancelIntent': function () {
this.emit(':tell', 'Cancelled');
},
'AMAZON.StopIntent': function () {
this.emit(':tell', 'Stopping');
},
'SessionEndedRequest': function () {
this.emit(':tell', 'Goodbye');
}
};
const Alexa = require('alexa-sdk');
const alexa = Alexa.handler(event, context);
alexa.registerHandlers(handlers);
alexa.execute();
})
})
}).on('error', (e) => {
callback(e);
});
};
Comments