Introduction
We’ll explore the world of sentiment analysis and guide you through building a web application utilizing the Hugging Face’s Transformer library, Google Cloud Storage Bucket and Python Transformers package. Let’s dive into natural language processing, unlocking the power to understand and analyse emotions in text. Follow the step-by-step instructions to create your own sentiment analysis application and gain valuable insights from textual data.
By the end of this blog, you will understand how to construct a web application that uses a Python script will leverage Hugging Face’s Transformer library stored on Google Cloud to perform sentiment analysis on user-provided feedback. The results will be displayed on the web interface.
Creating the Sentiment Analysis Python Script
You just have to write 5 lines of Python codes to utilize Hugging Face’s Transformer library (specifically, the pipeline module) to perform sentiment analysis. But first you have to install Transformers library in your Python environment as follows.
pip install -q transformers
Then write the most basic sentiment analysis Python script as below.
from transformers import pipeline
sentiment_pipeline = pipeline("sentiment-analysis")
data = ["Great value and features", "Some great features, but awful heart rate monitor","BADASS! It NEVER comes off my wrist.All the features MAKE me wanna be healthy. I love the sleep feature. It records deep to light sleep, and it is awesome seeing your patterns in the APP."]
sentiment_pipeline(data)
This script uses the pipeline function from the Transformers’ library to create a sentiment analysis pipeline. It takes user input, passes it through the pipeline, and returns the sentiment label (positive, negative, or neutral) along with the score.
Also consider that there are a number of different libraries that you can utilize for sentiment analysis in Hugging Face’s Transformer library. We have used the default one above.
See the results of the above example below:
[{'label': 'POSITIVE', 'score': 0.999882698059082}, {'label': 'NEGATIVE', 'score': 0.9806006550788879}, {'label': 'POSITIVE', 'score': 0.9971200227737427}]
You can use a specific sentiment analysis model that is better suited to your language or use case by specifying it.
specific_model = pipeline(model="finiteautomata/bertweet-base-sentiment-analysis")
specific_model(data)
The above code will just work fine in Google Colab environment or Jupiter notebook. But we are going to save it in a Google Cloud Storage Bucket, Since that, we need to modify the code to be compatible with the Google cloud platform. The purpose of uploading the code to the Bucket is, then it is possible to deploy it in the Google Cloud functions or Google cloud run later on.
import os
from google.cloud import storage
from tempfile import NamedTemporaryFile
# Initialize the sentiment analysis pipeline
from transformers import pipeline
sentiment_pipeline = pipeline("sentiment-analysis")
# Define the Cloud Function entry point
def analyze_sentiment(request):
request_json = request.get_json(silent=True)
request_args = request.args
if request_json and "text" in request_json:
text = request_json["text"]
elif request_args and "text" in request_args:
text = request_args["text"]
else:
return "Error: No text provided."
# Perform sentiment analysis
result = sentiment_pipeline(text)[0]
sentiment = result["label"]
return sentiment
# Function to download file from Google Cloud Storage bucket
def download_file(bucket_name, source_blob_name):
storage_client = storage.Client()
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob(source_blob_name)
temp_file = NamedTemporaryFile(delete=False)
temp_file_path = temp_file.name
blob.download_to_filename(temp_file_path)
temp_file.close()
return temp_file_path
# Cloud Function entry point
def run_sentiment_analysis(request):
script_bucket_name = "sentiment_analysis_app"
script_blob_name = "main.py"
script_file_path = download_file(script_bucket_name, script_blob_name)
os.chmod(script_file_path, 0o755)
command = f"python3 {script_file_path}"
output = os.popen(command).read()
return output
Next, you need to create a requirement file, mentioning all the dependencies you need. Then put it in the dependencies’ folder in the Google Cloud Storage bucket.
google-cloud-storage
transformers
Store the Python script in Google Cloud Storage
Assuming that you already have created a Google cloud project, here’s a step-by-step guidance for how to upload the Python script and its dependencies to a Google Cloud Storage bucket, for later access:
- Open the Google Cloud Console and navigate to the Cloud Storage section.
- Create a new bucket providing the name, server location, Storage class, Public access and protection details where you want to store the files. It is important to select the same server location for Google Cloud Storage bucket, and afterwards if you deploy it in the Google cloud functions, or in any other Google service.
- To upload the Python script (named as main.py), click the “Upload files” button and select the Python script from your local machine.
- If your sentiment analysis script has any additional dependencies, create a folder within the bucket to store them. For example, you can create a folder called “dependencies” within the bucket. Upload the required dependencies to the bucket or the specific folder you created.
Crafting the Web Interface
Develop a simple web page with a text input field, a submission button, and a display area. So that when the button is clicked, it triggers what ever Google Cloud service that you deployed the web application in order to perform sentiment analysis on the input text.
Here’s a simple HTML code which will serve the purpose.
<!DOCTYPE html>
<html>
<head>
<title>Sentiment Analysis</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#submitBtn").click(function () {
var text = $("#textInput").val();
$.ajax({
type: "POST",
url: "https://europe-west1-hazel-tea-390307.cloudfunctions.net/sentiment_analysis_2",
data: JSON.stringify({ "text": text }),
contentType: "application/json",
success: function (response) {
$("#result").text("Sentiment: " + response);
}
});
});
});
</script>
</head>
<body>
<h1>Sentiment Analysis</h1>
<input type="text" id="textInput" placeholder="Enter a sentence" />
<button id="submitBtn">Submit</button>
<p id="result"></p>
</body>
</html>
This will provide a web page like below.
If you want to design it further, here is an example CSS code. But you must include the following line in the header of your HTML script.
<link rel="stylesheet" type="text/css" href="styles.css">
Add a CSS code, as per your preferred colours and designs, and name it as the “styles.css”.
Postman and API Endpoint
Postman is a popular collaboration platform and API development tool that allows you to make HTTP requests and test APIs. It provides a user-friendly interface for constructing and sending requests, inspecting responses, and debugging API interactions.
To use Postman for the above task of triggering the Google Cloud Function and performing sentiment analysis, follow these steps:
- Install Postman:
- Download and install Postman from the official website based on your operating system.
- Obtain the Google Cloud Service’s URL: Deploy your Google Cloud Service (Google Cloud Functions, Google Cloud Run etc…) and note down the URL endpoint that is generated.
- You may also run the web application in your local machine, in that case use the local host URL for an example:http://localhost:8080/sentiment-analysis
- You will need to create a new workspace in the Postman before creating a new Request.
- Configure Postman to Send HTTP Request: Open Postman on your machine.
- Select the “Request” tab to create a new request
- Choose the HTTP request method as “POST”.
- Enter the Cloud Function URL obtained earlier in the request URL field.
- Set the “Content-Type” header to “application/json”.
- In the request body, provide the input text as a JSON payload. For example:
{ “text”: “This is a sample text for sentiment analysis.” } |
- Click the “Send” button to send the request to the Cloud Function.
- View the Sentiment Analysis Result: Postman will display the response received from the Cloud Function. The sentiment analysis result (positive, negative, or neutral) will be included in the response body. You can inspect the response to see the sentiment analysis output.
Conclusion
In conclusion, we have explored the process of building a sentiment analysis web application using Hugging Face’s Transformer library, Python Transformers package and Google Cloud Storage Bucket. By leveraging the power of natural language processing, we learned how to analyse the emotions behind user-provided feedback. Our application, powered by a Python script, employed Hugging Face’s Transformer library to perform sentiment analysis. Showed a way to display the results on a user-friendly web interface, also made accessible through an API endpoint. We unlocked the potential of sentiment analysis and gained valuable insights from textual data. Continue to discover the world of sentiment analysis.