How to Implement Sentiment Analysis with PHP and AWS Comprehend
Tags: machinelearning, php, aws, programming
Published: 2024-07-10 18:58:45

Hi everyone, 👋

Imagine you implement a chatbot that analyzes in real-time how a conversation is going. Is the client happy 😄 or sad 😔 about the situation? Cool, isn’t it? Or imagine analyzing an email from a client and quantifying it in your indicators to see which one needs more attention.

In this post, I’d like to share how to implement a powerful tool to analyze texts, called AWS Comprehend.

**Important to know:**
Amazon Comprehend Free Tier allows up to 50,000 character units per month for the first 12 months. After that, you need to check the prices on the AWS platform.

Hands-on 💪

## 1. Create user in AWS.
* Go to [AWS Management Console](https://aws.amazon.com/pt/console/) and create your login.
* Search for IAM.
![IAM](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6eitv26lhklcv7vkbucr.png)
* Click on Users -> Create User
![Creating user on AWS](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yh84ujulve4f40hxt77c.png)
* Specify a name (whatever you want) for the user and click on Next
![Specifing a name for the user](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p72h0k09ze3773giu9y0.png)
* Set permissions for the user.
For our tests, we’re going to use just one policy (ComprehendFullAccess), but for your project, you can define more policies as needed.
![Setting permission](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cc5dwqf0jamwb4r362mk.png)
* Now it’s time to review and create the user.
![Finalize and create user](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5trzt92yqe2yyrhy4h0y.png)
* After creating the user, it’s time to create an Access Key. Click on the user that has been created, and in Summary, click on Create access key.
![Summary click create access key](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i1f4j3mbjez96euojcxf.png)
* Select Local code for the use case (for our tutorial it’s fine).
![Selecting local code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gdf1eewkxvzv00ljio6x.png)
* Set a description tag. I like to use the name of the case example: local-code-access-key, but you can use any name.
![Description tag](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dm6y7j7zpfm971tiis1e.png)
* After creating, you can show the access_key and secret_key on the screen or download a CSV with credentials. Save this because we’re going to use it to connect with AWS.
![Created credentials for access key](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w6t8586exo0h9zp2sed8.png)


## 2. Install the AWS SDK for PHP.
* Use Composer to install the AWS SDK for PHP library.

`composer require aws/aws-sdk-php`


## 3. Implementing code 
* This is an example of how you can implement sentiment analysis. Create a file named analyze_sentiment.php and copy this code.

```
<?php
require 'vendor/autoload.php';

// Using the AWS Comprehend library
use Aws\Comprehend\ComprehendClient;

// Configuring the client
$client = new ComprehendClient([
    'version' => 'latest',
    'region'  => 'us-east-1', // Use your preferred region
    'credentials' => [
        'key'    => 'PASTE_YOUR_ACCESS_KEY',
        'secret' => 'PASTE_YOUR_SECRET_ACCESS_KEY',
    ]
]);

// Text to analyze
$textToAnalyze = 'Thanks for resolving my problem, but it was too late.';

// Using the method detectSentiment to analyze
$result = $client->detectSentiment([
    'Text' => $textToAnalyze,
    'LanguageCode' => 'en'
]);

// Result of analysis
echo 'Text: ' . $textToAnalyze;
echo '<br>Sentiment: ' . $result['Sentiment'];
echo '<pre>';
print_r($result['SentimentScore']);
echo '</pre>';
?>
```

## The result looks like this.

![Result of analysis](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/karyolacnfs38qhnmbop.png)

This is an example of how you can implement this in your applications. You can use most methods in this library to analyze images, files, and more. Just check the [AWS Comprehend Documentation](https://docs.aws.amazon.com/comprehend/latest/dg/what-is.html)

Hope this is useful for you. 👊
See you soon.