Sentiment Analysis Service for Bookstore Reviews

Image1

As a bookstore owner, you aim to receive instant notifications in a Slack channel whenever a customer submits a new negative review comment. By leveraging Knative Function, you can set up a serverless function that contains a simple sentiment analysis service to categorize review comments by sentiment.

Which Knative features will we learn about?

The ease to use Knative Function to deploy your service, and make it be managed by Knative Serving, which gives you the ability to auto-scale your service to zero, and scale up to handle the demand.

What does the final deliverable look like?

Image8

A running serverless Knative Function that contains a python application that receives the new review comments as CloudEvent and returns the sentiment classification of the input text as CloudEvent.

The function’s output will be only from:

  • Positive

  • Neutral

  • Negative

Install Prerequisites

Prerequisite 1: Install Knative func CLI

Image12

Knative Function enables you to easily create, build, and deploy stateless, event-driven functions as Knative Services by using the func CLI.

In order to do so, you need to install the func CLI. You can follow the official documentation to install the func CLI.

Verify

Running func version in your terminal to verify the installation, and you should see the version of the func CLI you installed.

Troubleshooting

If you see command not found, you may need to add the func CLI to your PATH.

Implementation

Image3

The process is straightforward:

  1. Begin by utilizing the func create command to generate your code template.

  2. Next, incorporate your unique code into this template.

  3. Finally, execute func deploy to deploy your application seamlessly to the Kubernetes cluster.

This workflow ensures a smooth transition from development to deployment within the Knative Functions ecosystem.

Step 1: Create a Knative Function template

Image17

Create a new function using the func CLI:

  1. func create -l <language> <function-name>

In this case, we are creating a Python function, so the command will be:

  1. func create -l python sentiment-analysis-app

This command will create a new directory with the name sentiment-analysis-app and a bunch of files in it. The func CLI will generate a basic function template for you to start with.

You can find all the supported language templates here.

Verify

The file tree will look like this:

  1. start/sentiment-analysis-app
  2. ├── func.yaml
  3. ├── .funcignore
  4. ├── .gitignore
  5. ├── requirements.txt
  6. ├── app.sh
  7. ├── test_func.py
  8. ├── README.md
  9. ├── Procfile
  10. └── func.py

Step 2: Replace the generated code with the sentiment analysis logic

Image14

sentiment-analysis-app/func.py is the file that contains the code for the function. You can replace the generated code with the sentiment analysis logic. You can use the following code as a starting point:

sentiment-analysis-app/func.py

  1. from parliament import Context
  2. from flask import Request, request, jsonify
  3. import json
  4. from textblob import TextBlob
  5. from time import sleep
  6. from cloudevents.http import CloudEvent, to_structured
  7. # The function to convert the sentiment analysis result into a CloudEvent
  8. def create_cloud_event(inputText, badWordResult, data):
  9. attributes = {
  10. "type": "moderated-comment",
  11. "source": "sentiment-analysis",
  12. "datacontenttype": "application/json",
  13. "sentimentResult": data,
  14. "badwordfilter": badWordResult,
  15. }
  16. # Put the sentiment analysis result into a dictionary
  17. data = {
  18. "reviewText": inputText,
  19. "badWordResult": badWordResult,
  20. "sentimentResult": data,
  21. }
  22. # Create a CloudEvent object
  23. event = CloudEvent(attributes, data)
  24. return event
  25. def analyze_sentiment(text):
  26. analysis = TextBlob(text["reviewText"])
  27. sentiment = "neutral"
  28. if analysis.sentiment.polarity > 0:
  29. sentiment = "positive"
  30. elif analysis.sentiment.polarity < 0:
  31. sentiment = "negative"
  32. badWordResult = ""
  33. try:
  34. badWordResult = text["badWordResult"]
  35. except:
  36. pass
  37. # Convert the sentiment into a CloudEvent
  38. sentiment = create_cloud_event(text["reviewText"], badWordResult, sentiment)
  39. return sentiment
  40. def main(context: Context):
  41. """
  42. Function template
  43. The context parameter contains the Flask request object and any
  44. CloudEvent received with the request.
  45. """
  46. print("Sentiment Analysis Received CloudEvent: ", context.cloud_event)
  47. # Add your business logic here
  48. return analyze_sentiment(context.cloud_event.data)

Step 3: Configure the dependencies

Image9

The sentiment-analysis-app/requirements.txt file contains the dependencies for the function. Add the following dependencies to the file:

sentiment-analysis-app/requirements.txt

  1. Flask==3.0.2
  2. textblob==0.18.0.post0
  3. parliament-functions==0.1.0
  4. cloudevents==1.10.1

Knative Function will automatically install the dependencies listed here when you build the function.

Step 4: Configure the pre-built environment

Image11

In order to properly use the textblob library, you need to download the corpora, which is a large collection of text data that is used to train the sentiment analysis model. You can do this by creating a new file called setup.py, Knative Function will ensure that the setup.py file is executed after the dependencies have been installed.

The sentiment-analysis-app/setup.py file should contain the following code for your bookstore:

sentiment-analysis-app/setup.py

  1. from setuptools import setup, find_packages
  2. from setuptools.command.install import install
  3. import subprocess
  4. class PostInstallCommand(install):
  5. """Post-installation for installation mode."""
  6. def run(self):
  7. # Call the superclass run method
  8. install.run(self)
  9. # Run the command to download the TextBlob corpora
  10. subprocess.call(['python', '-m', 'textblob.download_corpora', 'lite'])
  11. setup(
  12. name="download_corpora",
  13. version="1.0",
  14. packages=find_packages(),
  15. cmdclass={
  16. 'install': PostInstallCommand,
  17. }
  18. )

Step 5: Build and run your Knative Function locally (Optional)

Click here to expand

Image4

In Knative Function, there are two ways to build: using the pack build or using the source-to-image (s2i) build.

Currently only the s2i build is supported if you need to run setup.py. When building with s2i, the setup.py file will be executed automatically after the dependencies have been installed.

Before we get started, configure the container registry to push the image to the container registry. You can use the following command to configure the container registry:

  1. export FUNC_REGISTRY=<your-container-registry>

In this case, we will use the s2i build by adding the flag -b=s2i, and -v to see the verbose output.

  1. func build -b=s2i -v

When the build is complete, you will see the following output:

  1. 🙌 Function built: <Your container registry username>/sentiment-analysis-app:latest

This command will build the function and push the image to the container registry. After the build is complete, you can run the function using the following command:


Troubleshooting

❗Error: '/home/Kuack/Documents/knative/docs/code-samples' does not contain an initialized function

Solution: You may want to check whether you are in the correct directory. You can use the following command to check the current directory. If you are in the right directory, and the error still occurs, try to check your func.yaml, as it has to contain the field created and the right timestamp to be treated as a valid Knative Function.


  1. func run -b=s2i -v

In the future, you can skip the step of func build, because func run will automatically build the function for you.

You will see the following output if the function is running successfully:

  1. function up-to-date. Force rebuild with --build
  2. Running
  3. on host port 8080
  4. ---> Running application from script (app.sh) ...

Knative Function has an easy way to simulate the CloudEvent, you can use the following command to simulate the CloudEvent and test your function out:

  1. func invoke -f=cloudevent --data='{"reviewText": "I love Knative so much"}' --content-type=application/json --type="new-review-comment" -v

where the -f flag indicates the type of the data, is either HTTP or cloudevent, and the --data flag is the input text. You can read more about func invoke here.

In this case, you will get the full CloudEvent response:

  1. Context Attributes,
  2. specversion: 1.0
  3. type: new-review-comment
  4. source: book-review-broker
  5. id: ebbcd761-3a78-4c44-92e3-de575d1f2d38
  6. time: 2024-05-27T04:44:07.549303Z
  7. datacontenttype: application/json
  8. Extensions,
  9. badwordfilter: good
  10. Data,
  11. {
  12. "reviewText": "I love Knative so much",
  13. "badWordResult": "",
  14. "sentimentResult": "positive"
  15. }

Step 6: Deploy the function to the cluster

Image10

Note

Please enter /sentiment-analysis-app when you are executing the following commands.

In Knative Function, there are two ways to build: using the pack build or using the source-to-image (s2i) build.

Currently only the s2i build is supported if you need to run setup.py. When building with s2i, the setup.py file will be executed automatically after the dependencies have been installed.

After you have finished the code, you can deploy the function to the cluster using the following command:

Note

Using -b=s2i to specify how the function should be built.

  1. func deploy -b=s2i -v

Verify

When the deployment is complete, you will see the following output:

  1. Function deployed in namespace "default" and exposed at URL:
  2. http://sentiment-analysis-app.default.svc.cluster.local

Tip

You can find the URL of the Knative Function (Knative Service) by running the following command:

  1. kubectl get kservice

You will see the URL in the output:

  1. NAME URL LATESTCREATED LATESTREADY READY REASON
  2. sentiment-analysis-app http://sentiment-analysis-app.default.svc.cluster.local sentiment-analysis-app-00001 sentiment-analysis-app-00001 True

Knative Serving: scale down to zero

Image13

If you use the following command to query all the pods in the cluster, you will see that the pod is running:

  1. kubectl get pods

where -A is the flag to query all the pods in all namespaces.

And you will find that your sentiment analysis app is running:

  1. NAMESPACE NAME READY STATUS RESTARTS AGE
  2. default sentiment-analysis-app-00002-deployment 2/2 Running 0 2m

But if you wait for a while without sending any CloudEvent to your function, and query the pods again, you will find that the pod that has your sentiment analysis app disappeared!

This is because Knative Serving’s autoscaler will automatically scale down to zero if there is no request to the function! Learn more at Knative Autoscaling.


Verify

Image2

After deployment, the func CLI provides a URL to access your function. You can verify the function’s operation by sending a request with a sample review comment.

Simply use Knative Function’s command func invoke to directly send a CloudEvent to the function on your cluster:

  1. func invoke -f=cloudevent --data='{"reviewText":"I love Knative so much"}' -v
  • -f flag indicates the type of the data, is either HTTP or cloudevent
  • --data flag is the input text
  • -t flag is the URI to the Knative Function.

Verify

If you see the response, it means that the function is running successfully.

  1. Context Attributes,
  2. specversion: 1.0
  3. type: moderated-comment
  4. source: sentiment-analysis
  5. id: 0c2d0659-a30e-4efd-bcce-803f15ff5cc5
  6. time: 2024-06-11T15:12:43.795405Z
  7. datacontenttype: application/json
  8. Extensions,
  9. badwordfilter:
  10. sentimentresult: positive
  11. Data,
  12. {
  13. "reviewText": "I love Knative so much",
  14. "badWordResult": "",
  15. "sentimentResult": "positive"
  16. }

Image16

In this tutorial, you learned how to create a serverless function for a simple sentiment analysis service with Knative.

Next Step

Image5

Next, we’ll deploy another ML service following the same procedure. We encourage you to try it yourself!

Tip

Don’t forget to cd into the root directory /start before proceeding.

If you feel comfortable deploying the other ML service yourself, follow this simplified guide:

Go to Deploy ML workflow: Bad word filter 2 - Create Sentiment Service - 图15

If you encounter any issues, don’t worry—we have a detailed tutorial ready for you.

Solution - Go to Deploy ML workflow: Bad word filter 2 - Create Sentiment Service - 图16