AWS Lambda: Building Sentiment Detection with Ruby and AWS Comprehend

Natarajan Santhosh
2 min readJul 11, 2019

--

pre-requisites: aws account setup and aws cli

mkdir my_function; cd $_

create a gemfile and add following

source "https://rubygems.org"

gem 'aws-sdk-comprehend'

run

bundle install --path vendor/bundle

create a lambda function `vi lambda_function.rb`

require 'json'
require 'aws-sdk-comprehend'
def lambda_handler(event:, context:)
input = JSON.parse(event["body"])["text"]
comprehend = Aws::Comprehend::Client.new
result = "Based on AWS Comprehend, the sentiment is: #{comprehend.detect_sentiment({text: input, language_code:'en', })[:sentiment]}"

{ statusCode: 200, body: JSON.generate(result) }
end

Edit the lambda role to include following comprehend policy

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": "comprehend:DetectSentiment",
"Resource": "*"
}
]
}

Now zip the ruby lambda and thirdparty dependencies into a zip file and publish it to AWS lambda

zip -r function.zip lambda_function.rb vendor/# create a function (first time )
aws lambda create-function --function-name sentiment_function --runtime ruby2.5 --role a_lambda_arn_role --handler lambda_function.lambda_handler --zip-file fileb://function.zip
# make changes locally and update
aws lambda update-function-code --function-name sentiment_function --zip-file fileb://function.zip

Now log-in to your aws console and verify that function is added. Run a lambda test

On lambda designer, click on the trigger, add API Gateway and copy the url

Use a rest client e.g. postman

POST to url with a body

POSTMAN

a sample response from AWS Comprehend’s detect_sentiment call

{:sentiment=>"POSITIVE", :sentiment_score=>{:positive=>0.9365447759628296, :negative=>0.0029086992144584656, :neutral=>0.053811587393283844, :mixed=>0.006734972354024649}}

--

--

No responses yet