-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
320 lines (271 loc) · 9.94 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
320
const AWS = require('aws-sdk');
const translate = new AWS.Translate();
const polly = new AWS.Polly();
const s3 = new AWS.S3();
const alexa = require('ask-sdk');
const messages = {
WELCOME: 'Greetings! You can ask Language Teacher to say something in different languages, or you can say "Help" to learn more.',
WHAT_DO_YOU_WANT: 'What do you want to do?',
ERROR: 'Uh Oh. Looks like something went wrong',
NEXT: 'What do you want me to do next?',
REPEAT_NA: 'Looks like there is nothing to repeat. You can ask Language Teacher to say something in different languages. What do you want to ask?',
GOODBYE: 'Bye!',
UNHANDLED: 'I don\'t know that but I\'m learning. Say "help" to hear the options, or ask something else.',
HELP: 'You can ask Language Teacher to say something in different languages. For example, you can say: "Ask Language Teacher to say Hello", or "Ask Language Teacher to repeat" to listen to the translation again. To set the language - just say: "Ask Language Teacher to set the language to Japanese". What do you want to do?'
};
const card_small = `https://s3.amazonaws.com/${process.env.BUCKET_PICS}/language/globe_small.png`;
const card_big = `https://s3.amazonaws.com/${process.env.BUCKET_PICS}/language/globe_big.png`;
const voices = {
es: 'Enrique',
ru: 'Maxim',
pt: 'Cristiano',
ja: 'Takumi',
it: 'Giorgio',
de: 'Hans',
fr: 'Mathieu'
};
const languages = {
es: 'Spanish',
ru: 'Russian',
pt: 'Portuguese',
ja: 'Japanese',
it: 'Italian',
de: 'German',
fr: 'French'
};
function doTranslate(text,language) {
let result = new Promise((resolve, reject) => {
var inputText = text;
var params = {
Text: inputText,
SourceLanguageCode: 'en',
TargetLanguageCode: language
};
translate.translateText(params, function(err, data) {
if (err) {
console.error(err, err.stack); // an error occurred
reject(err);
}
else {
console.log(data); // successful response
resolve(data.TranslatedText);
}
});
});
return result;
}
function doSynthesize(text,voice) {
let result = new Promise((resolve, reject) => {
var params = {
OutputFormat: "mp3",
SampleRate: "22050",
Text: `<speak><amazon:effect name="drc"><p>${text}</p></amazon:effect>
<prosody rate="slow"><amazon:effect name="drc"><p>${text}</p></amazon:effect></prosody></speak>`,
TextType: "ssml",
VoiceId: voice
};
polly.synthesizeSpeech(params, function(err, data) {
if (err) {
console.error(err, err.stack); // an error occurred
reject(err);
}
else {
resolve(data.AudioStream);
}
});
});
return result;
}
function writeToS3(data,prefix) {
let result = new Promise((resolve, reject) => {
var putParams = {
Bucket: `${process.env.BUCKET}`,
Key: `${prefix}/speech.mp3`,
Body: data,
ACL: 'public-read',
StorageClass: 'REDUCED_REDUNDANCY'
};
console.log('Uploading to S3');
s3.putObject(putParams, function (putErr, putData) {
if (putErr) {
console.error(putErr);
reject(putErr);
} else {
resolve(putData);
}
});
});
return result;
}
const LaunchRequest = {
canHandle(handlerInput) {
return handlerInput.requestEnvelope.request.type === 'LaunchRequest';
},
handle(handlerInput) {
return handlerInput.responseBuilder.speak(messages.WELCOME)
.reprompt(messages.WHAT_DO_YOU_WANT)
.getResponse();
},
};
const UnhandledIntent = {
canHandle() {
return true;
},
handle(handlerInput) {
return handlerInput.responseBuilder
.speak(messages.UNHANDLED)
.reprompt(messages.UNHANDLED)
.getResponse();
},
};
const HelpIntent = {
canHandle(handlerInput) {
const { request } = handlerInput.requestEnvelope;
return request.type === 'IntentRequest' && request.intent.name === 'AMAZON.HelpIntent';
},
handle(handlerInput) {
return handlerInput.responseBuilder
.speak(messages.HELP)
.reprompt(messages.WHAT_DO_YOU_WANT)
.getResponse();
},
};
const SetLanguageIntent = {
canHandle(handlerInput) {
const { request } = handlerInput.requestEnvelope;
return request.type === 'IntentRequest' && request.intent.name === 'SetLanguage';
},
async handle(handlerInput) {
const attributesManager = handlerInput.attributesManager;
const sessionAttributes = attributesManager.getSessionAttributes();
const currentIntent = handlerInput.requestEnvelope.request.intent;
var response = 'I don\'t know this language but I\'m learning.\
Please choose the language from Italian, Spanish, Japanese, German, Russian, Portuguese or French';
var reprompt = 'Which language do you want to choose?';
if(currentIntent.slots.language.resolutions &&
currentIntent.slots.language.resolutions.resolutionsPerAuthority[0] &&
currentIntent.slots.language.resolutions.resolutionsPerAuthority[0].status &&
currentIntent.slots.language.resolutions.resolutionsPerAuthority[0].status.code == 'ER_SUCCESS_MATCH'){
const language = currentIntent.slots.language.resolutions.resolutionsPerAuthority[0].values[0].value.name;
sessionAttributes.targetLanguage = currentIntent.slots.language.resolutions.resolutionsPerAuthority[0].values[0].value.id;
attributesManager.setPersistentAttributes(sessionAttributes);
await attributesManager.savePersistentAttributes();
response = `Ok, I set the language to ${language}. ` + messages.NEXT;
reprompt = messages.NEXT;
}
return handlerInput.responseBuilder
.speak(response)
.reprompt(reprompt)
.getResponse();
},
};
const CancelIntent = {
canHandle(handlerInput) {
const { request } = handlerInput.requestEnvelope;
return request.type === 'IntentRequest' &&
(request.intent.name === 'AMAZON.CancelIntent' || request.intent.name === 'AMAZON.StopIntent');
},
handle(handlerInput) {
return handlerInput.responseBuilder
.speak(messages.GOODBYE)
.getResponse();
},
};
const SessionEndedRequestHandler = {
canHandle(handlerInput) {
return handlerInput.requestEnvelope.request.type === 'SessionEndedRequest';
},
handle(handlerInput) {
console.log(`Session ended with reason: ${handlerInput.requestEnvelope.request.reason}`);
return handlerInput.responseBuilder.getResponse();
},
};
const AskIntentHandler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'IntentRequest' && request.intent.name === 'AskIntent';
},
async handle(handlerInput) {
const attributesManager = handlerInput.attributesManager;
const sessionAttributes = await attributesManager.getPersistentAttributes();
const phrase = handlerInput.requestEnvelope.request.intent.slots.phrase.value;
const devId = handlerInput.requestEnvelope.context.System.device.deviceId;
const prefix = require('crypto').createHash('md5').update(devId).digest("hex").toString();
var translation = '';
attributesManager.setSessionAttributes(sessionAttributes);
if (!sessionAttributes.targetLanguage) {
console.log(sessionAttributes.targetLanguage);
sessionAttributes.targetLanguage = 'ru';
}
return new Promise((resolve) => {
doTranslate(phrase, sessionAttributes.targetLanguage)
.then((data) => {
translation = data;
doSynthesize(data, voices[sessionAttributes.targetLanguage])
.then((data) => {
writeToS3(data,prefix)
.then(() => {
console.log(prefix);
resolve(handlerInput.responseBuilder
.speak(`This is how phrase ${phrase} will sound in ${languages[sessionAttributes.targetLanguage]}:\
<audio src="https://s3.amazonaws.com/${process.env.BUCKET}/${prefix}/speech.mp3"/>\
Say "repeat" to listen again, or ask something else to get a new translation`)
.reprompt('Say "repeat" to listen again, or ask something else to get a new translation')
.withStandardCard(
'Language Teacher',
`Original phrase: ${phrase}\nTranslation in ${languages[sessionAttributes.targetLanguage]}: ${translation}`,
card_small,
card_big)
.getResponse());
});
});
});
});
},
};
const RepeatIntentHandler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'IntentRequest' && request.intent.name === 'RepeatIntent';
},
async handle(handlerInput) {
const devId = handlerInput.requestEnvelope.context.System.device.deviceId;
const prefix = require('crypto').createHash('md5').update(devId).digest("hex").toString();
return new Promise((resolve, reject) => {
var Params = {
Bucket: `${process.env.BUCKET}`,
Key: `${prefix}/speech.mp3`
};
console.log('Heading an existing object in S3');
s3.headObject(Params, function (Err, Data) {
if (Err) {
resolve(handlerInput.responseBuilder
.speak(messages.REPEAT_NA)
.reprompt(messages.WHAT_DO_YOU_WANT)
.getResponse());
} else {
resolve(handlerInput.responseBuilder
.speak(`<audio src="https://s3.amazonaws.com/${process.env.BUCKET}/${prefix}/speech.mp3"/>\
Say "repeat" to listen again, or ask something else to get a new translation`)
.reprompt('Say "repeat" to listen again, or ask something else to get a new translation')
.getResponse());
}
});
});
},
};
const skillBuilder = alexa.SkillBuilders.standard();
exports.handler = skillBuilder
.addRequestHandlers(
AskIntentHandler,
SetLanguageIntent,
RepeatIntentHandler,
LaunchRequest,
HelpIntent,
CancelIntent,
UnhandledIntent,
SessionEndedRequestHandler
)
.withTableName(`${process.env.TABLE}`)
.withAutoCreateTable(true)
.lambda();