Abstract:

An Alexa Skill Project Demonstration used to translate any words to any language using Google Translate API & Rappid API which help in making daily task easier.It is lifehack skill which save time

Link To Enable This Skill :

http://alexa.amazon.com/spa/index.html#skills/amzn1.ask.skill.7504fa5b-b08f-4a36-86f7-3fc7230e1378

Skill ID: amzn1.ask.skill.7504fa5b-b08f-4a36-86f7-3fc7230e1378

SPICE TRANSLATE : Language is the life blood of everyone and should not be relegated to the sidelines.People commonly have language barrier while migrating from one country to other country because of various factors such as work,education etc.They need to cook themselves for their survival.But Language plays a major problem while buying cooking stuff(Spices) from local salesman.Spices add flavour to our dish.The name of spices differs by country.For example Basil is pronounced as Thulasi in Tamil.So its a quite inconvenient while buying spices from local Sales person.To overcome this problem i have made a skill which uses Google Translate API to translate list of spices in World to different language.So before going for shopping you can create a list of spices needed to prepare your dish in local language.In this skill i have added support for only spice words.These words can be edited in Custom Slots in Amazon Skill Developer Portal and can be used to translate any words defined in Custom Slots . More Language can be added by specifying their ISO language Code for ex:'en' for English in Index.js File given below.

Step 1: Defining the Skill Elements in Amazon Developer Portal To get started, we'll head over to the Amazon Developer Portal and login

*Once logged in, head over to the Alexa tab and create a new Alexa skill *Configure your Skill Information like name of your skill and invocation name.In my case my skill name is Spice Translate and invocation name is spice translate *On next tab define the Intent Schema as Follows

{ "intents": [ { "intent" : "Translate", "slots": [ { "name" : "Source", "type" : "SOURCE" }, { "name" : "Language", "type" : "LANGUAGES_LIST" } ] }, { "intent": "AMAZON.HelpIntent" }, { "intent":"AMAZON.StopIntent" } ] }

Define the slots and slot types For this skill the intent has 2 slots. A slot is like a placeholder for a piece of data that the user can supply to the intent. The slots in our case will be:

*Source: Words to be Translated.In my skill i have specified list of spice words in world **Language: The language we want to translate it to.Specify the list of languages who wish to translate

The Source Words can be edited and modified as per the title you gonna define for your skill. For ex list of birds etc....

Define Sample Utterances :

Translate translate {Source} to {Language} Translate how to say {Source} in {Language} Translate to translate {Source} to {Language} Translate get translation for {Source} in {Language} Translate what is {Source} in {Language} AMAZON.HelpIntent help AMAZON.HelpIntent Help AMAZON.StopIntent Stop AMAZON.StopIntent cancel AMAZON.StopIntent Cancel

*The next Step is configuring our skill.But before configuring lets move on to building the back end for this skill that perform translation

Step 2 : Getting Rapid API and Google Translate API

We'll use RapidAPI to connect to the Google Translate API. If you haven't already, create a RapidAPI account. Create a new project on RapidAPI and get the API key.Add Project Name and select node.js as back end language

You can find your Rapid API key for your project in Require SDK Section.Just copy the API key and Project name and specify it in Index.js file code

How to get Google Translate apiKey

*Go to the projects page *Select or create a Cloud Platform Console project. *Enable billing for your project. *Click Continue to enable the Translate API and any related services. *On the Credentials page, get an API key (select Browser key when prompted). Note: If you have an existing API key, you can use that key. *Go to translate api overview and press Enable button.

*In Rapid API Before Clicking on Connect to API ensure you have logged in in and created a project in your dashboard *Select the project on left .Enter the Google Translate api key below you have got and test the function *Copy the google api code and paste it in index.js file in specified loaction and save the file in a directory *Dowload Node.js. Open Node.js Command Prompt in this directory and run the command npm install rapidapi-connect --save *A node module Folder will be created. Just compress the the edited index.js and node module folder to zip file used to upload in AWS Lambda or you can get this node module SDK from this link https://drive.google.com/open?id=0B65D_lfnTjnOMUtFTjBKZ3BGRDg

Step 3: Connect to Amazon Lambda

*Head over to AWS and sign in to your console. In the console, head over to the Lambda service and create a new Lambda function named Alexa_Spice Translate.Before Select the blueprint as blank and Triggers as Alexa Sill Kit. *Select Runtime as Node.js and Code entry as Upload Zip *Head over to the directory, where the node modules and index.js zip file is present .upload the Zip file to the Lambda page. *For the role, just choose the template "option". *Review and Save the function and copy the ARN Code

Step 4:

*Go back to Alexa Developer Portal.Head over to your skill and select configuration and paste the ARN fucntion copied from Lambda Function *Define the public information and privacy Section *Test the skill using test section in developer portal

Example Phrases For My Skill :

Alexa ask spice translate to translate basil to spanish Alexa launch spice translate and get translation for bay leaves in italian Alexa ask spice translate what is basil in german

Thanks for watching my project.

CODE

index.js copy the code in notepad and save it as index.js

'use strict'; const RapidAPI = require('rapidapi-connect'); const rapid = new RapidAPI('Spice1', 'Rapid Api Key');//Insert your Rapid API Key

// --------------- Helpers that build all of the responses -----------------------

function buildSpeechletResponse(title, output, repromptText, shouldEndSession) { return { outputSpeech: { type: 'PlainText', text: output, }, card: { type: 'Simple', title: SessionSpeechlet - ${title}, content: SessionSpeechlet - ${output}, }, reprompt: { outputSpeech: { type: 'PlainText', text: repromptText, }, }, shouldEndSession:shouldEndSession }; }

function buildResponse(sessionAttributes, speechletResponse) { return { version: '1.0', sessionAttributes, response: speechletResponse, }; }

// --------------- Functions that control the skill's behavior -----------------------

function getWelcomeResponse(callback) { // If we wanted to initialize the session to have some attributes we could add those here. const sessionAttributes = {}; const cardTitle = 'Welcome'; const speechOutput = 'Welcome to the Spice Translate skill. Say something like translate Basil to German'; // If the user either does not reply to the welcome message or says something that is not // understood, they will be prompted again with this text. const repromptText = 'Say something like translate basil to German'; const shouldEndSession = false;

callback(sessionAttributes,
    buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));

} function getHelpResponse(intent, session, callback) { // declare session attributes var sessionAttributes = {}; // define title for the card. var cardTitle = "Spice Translate Help"; // here is the help provided to the user var speechOutput = "Ask Spice Translate to translate any spice word to specified language in skill info";

// if user does not respond, this will be played after a few seconds
var repromptText = "Are you there";

// make sure that the session is not ended
var shouldEndSession = false;

// build the speech that user will hear
callback({},
    buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));

}

function getExitResponse(intent, session, callback) { // declare session attributes var sessionAttributes = {}; // define title for the card. var cardTitle = "Spice Translate Exit"; // here is the help provided to the user var speechOutput = "Thanks For trying This Skill.Have a Nice Day!";

// if user does not respond, this will be played after a few seconds

// make sure that the session is not ended
var shouldEndSession = true;

// build the speech that user will hear
callback({},
    buildSpeechletResponse(cardTitle, speechOutput,null, shouldEndSession));

}

/**

  • Intent handlers */

function translate(intent, session, callback) { const GoogleAPIKey = 'Google Translate API KEY';//Insert your Google API Key

//More Languages can be added by specifying their ISO Standard Langugae code like 'en' etc.... const langCodes = { "German" : "de", "Dutch" : "nl", "English" : "en", "French" : "fr", "Italian" : "it", "Polish" : "pl", "Russian" : "ru", "Spanish" : "es" }; const source = intent.slots.Source.value; const lang = intent.slots.Language.value; const langCode = langCodes[lang];

//Call RapidAPI
rapid.call('GoogleTranslate', 'translateAutomatic', {
    string : source,
    apiKey: GoogleAPIKey,
    targetLanguage: langCode
})
    .on('error', (payload) => {
        callback({},
            buildSpeechletResponse('Spice Translate', `Sorry, translation not available`, null, false));
    })
    .on ('success', (payload) => {
        callback({},
            buildSpeechletResponse('Spice Translate', `${source} in ${lang} is ${payload}`, null, false));
    });

//callback({}, buildSpeechletResponse('Translate Demo', `Translating ${source} to ${lang}`, null, false));

}

// --------------- Events -----------------------

function onSessionStarted(sessionStartedRequest, session) { console.log(onSessionStarted requestId=${sessionStartedRequest.requestId}, sessionId=${session.sessionId}); }

/**

  • Called when the user launches the skill without specifying what they want. */ function onLaunch(launchRequest, session, callback) { console.log(onLaunch requestId=${launchRequest.requestId}, sessionId=${session.sessionId});

    // Dispatch to your skill's launch. getWelcomeResponse(callback); }

/**

  • Called when the user specifies an intent for this skill. */ function onIntent(intentRequest, session, callback) { console.log(onIntent requestId=${intentRequest.requestId}, sessionId=${session.sessionId});

    const intent = intentRequest.intent; const intentName = intentRequest.intent.name;

    // Dispatch to your skill's intent handlers if (intentName === 'Translate') { translate(intent, session, callback); } else if ("AMAZON.HelpIntent" === intentName) { getHelpResponse(intent, session, callback); }else if ("AMAZON.StopIntent" === intentName) { getExitResponse(intent, session, callback); }

    else { throw new Error('Invalid intent'); } }

/**

  • Called when the user ends the session.
  • Is not called when the skill returns shouldEndSession=true. */ function onSessionEnded(sessionEndedRequest, session) { console.log(onSessionEnded requestId=${sessionEndedRequest.requestId}, sessionId=${session.sessionId});

}

// --------------- Main handler -----------------------

// Route the incoming request based on type (LaunchRequest, IntentRequest, // etc.) The JSON body of the request is provided in the event parameter. exports.handler = function (event, context,callback) { try { console.log("event.session.application.applicationId=" + event.session.application.applicationId);

    // if it is a new session, do initialization
    if (event.session.new) {
        onSessionStarted({requestId: event.request.requestId}, event.session);
    }

    // detemine the type of request and call apporpriate function
    if (event.request.type === "LaunchRequest") {
        onLaunch(event.request,
            event.session,
            function callback(sessionAttributes, speechletResponse) {
                context.succeed(buildResponse(sessionAttributes, speechletResponse));
            });
    } if (event.request.type === 'IntentRequest') {
        onIntent(event.request,
            event.session,
            (sessionAttributes, speechletResponse) => {
                callback(null,buildResponse(sessionAttributes, speechletResponse));
            });
    } else if (event.request.type === "SessionEndedRequest") {
        onSessionEnded(event.request, event.session);
        context.succeed();
    }
} catch (e) {
    context.fail("Exception: " + e);
}

};

Built With

Share this project:
×

Updates