Build Sentiment Analysis Flask App

In this post, I am going to create a Sentiment analysis web app using flask with python. Now there are various ways to perform sentiment analysis in Python like Vader sentiment analysis, Stanford CoreNLP, TextBlob, or custom sentiment analysis model. In this post, I am going to use Vader sentiment Analysis to build a sentiment analysis flask app.

If you are new to Flask I recommend you to read the below articles before reading this post.

Also Read:

List of required functionalities

Before writing code lets first note down what kind of functionalities we need to make our sentiment analysis using flask.

  • We need a home page where we can upload any CSV files (input data for sentiment analysis)
  • Once the data is uploaded successfully, a message should show in green color. To do this we need to create a second home page
  • We need a button on the home page. If we click that button input data should display on the third page
  • On the third page (show data page), we need another button. If we click that button, the sentiment output data table should display on the same page

Now let’s start writing codes to achieve the above functionalities. Let’s first write the homepage (index page), I am naming this file name as “index_upload_and_show_data.html

index_upload_and_show_data.html

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href='/staticFiles/main.css' />
  </head>
  <body>
    <h1>Sentiment Analysis Flask App</h1>
    <p>Vader python sentiment analysis</p>

    <form method="POST" enctype="multipart/form-data" action="/">
        <input type="file" id="myFile" name="uploaded-file" accept=".csv">
        <input type="submit" value="Submit">
    </form>
  <br>
  <p style="color:blue;">Choose csv file to upload</p>
  <form action="/show_data" target="_blank">
        <input type="submit" value="Show CSV" />
    </form>
  </body>
</html>

twitter sentiment analysis app index page

Now if input data is uploaded successfully a message should show in green color. To do this we need to create a second home page. I am naming this page “index_upload_and_show_data_page2.html

Also Read:  Beginners guide to Flask Python Web App framework

index_upload_and_show_data_page2.html

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href='/staticFiles/main.css' />
  </head>
  <body>
    <h1>Sentiment Analysis Flask App</h1>
    <p>Vader python sentiment analysis</p>

    <form method="POST" enctype="multipart/form-data" action="/">
        <input type="file" id="myFile" name="uploaded-file" accept=".csv">
        <input type="submit" value="Submit">
    </form>
  <br>
  <p style="color:green;">file uploaded successfully</p>
  <form action="/show_data" target="_blank">
        <input type="submit" value="Show CSV" />
    </form>
  </body>
</html>

twitter sentiment analysis web app second page

Now that we are done with two of our home pages, let’s write our Flask back-end code. I am naming this code “flask_sentiment_analysis_app.py

flask_sentiment_analysis_app.py

from flask import Flask, render_template, request, session
import pandas as pd
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
from pandas.io.json import json_normalize
import csv
import os

# Sentiment analysis function using VADER
def vader_sentiment_scores(data_frame):
    # Define SentimentIntensityAnalyzer object of VADER.
    SID_obj = SentimentIntensityAnalyzer()

    # calculate polarity scores which gives a sentiment dictionary,
    # Contains pos, neg, neu, and compound scores.
    sentiment_list = []
    for row_num in range(len(data_frame)):
        sentence = data_frame['Text'][row_num]

        polarity_dict = SID_obj.polarity_scores(sentence)

        # Calculate overall sentiment by compound score
        if polarity_dict['compound'] >= 0.05:
            sentiment_list.append("Positive")

        elif polarity_dict['compound'] <= - 0.05:
            sentiment_list.append("Negative")

        else:
            sentiment_list.append("Neutral")

    data_frame['Sentiment'] = sentiment_list

    return data_frame


#*** Backend operation
# Read comment csv data
# df = pd.read_csv('data/comment.csv')

# WSGI Application
# Provide template folder name
# The default folder name should be "templates" else need to mention custom folder name
app = Flask(__name__, template_folder='templateFiles')

app.secret_key = 'You Will Never Guess'

# @app.route('/')
# def welcome():
#     return "Ths is the home page of Flask Application"

@app.route('/')
def index():
    return render_template('index_upload_and_show_data.html')

@app.route('/',  methods=("POST", "GET"))
def uploadFile():
    if request.method == 'POST':
        uploaded_file = request.files['uploaded-file']
        df = pd.read_csv(uploaded_file)
        session['uploaded_csv_file'] = df.to_json()
        return render_template('index_upload_and_show_data_page2.html')

@app.route('/show_data')
def showData():
    # Get uploaded csv file from session as a json value
    uploaded_json = session.get('uploaded_csv_file', None)
    # Convert json to data frame
    uploaded_df = pd.DataFrame.from_dict(eval(uploaded_json))
    # Convert dataframe to html format
    uploaded_df_html = uploaded_df.to_html()
    return render_template('show_data.html', data=uploaded_df_html)

@app.route('/sentiment')
def SentimentAnalysis():
    # Get uploaded csv file from session as a json value
    uploaded_json = session.get('uploaded_csv_file', None)
    # Convert json to data frame
    uploaded_df = pd.DataFrame.from_dict(eval(uploaded_json))
    # Apply sentiment function to get sentiment score
    uploaded_df_sentiment = vader_sentiment_scores(uploaded_df)
    uploaded_df_html = uploaded_df_sentiment.to_html()
    return render_template('show_data.html', data=uploaded_df_html)

if __name__=='__main__':
    app.run(debug = True)

Here in the above code, in lines 8-33 is the Vader python sentiment analysis function. The input of this function is CSV data ( I am using input data contains comment or review of products) and the output of this function is input data with Vader sentiment score.

Also Read:  Build Question Answering API with Flask and Python

Please read the Upload and Display CSV tutorial to better understand the above codes.

Now I have used Vader for sentiment analysis. You can use any other techniques like Stanford CoreNLP, TextBlob, custom sentiment analysis model, etc. The below-listed articles may be helpful for you for sentiment Analysis.

In lines 71 and 82 we are displaying input data and sentiment output in the “show_data.html” file. So we need to write that code.

show_data.html

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href='/staticFiles/main.css' />
  </head>
  <body>
    <h1>Sentiment Analysis Application using python and Flask</h1>
    <p>Generate Sentiment score using Vader sentiment</p>

{{ data|safe }}

<br>

  <form action="/sentiment" target="_blank">
        <input type="submit" value="Sentiment Analysis" />
    </form>
    </body>
</html>

Here in this code at line 10, we are taking data from Flask code.

sentiment analysis flask app

Conclusion

Here in this post, I tried to give you a starting point to build and deploy sentiment analysis web app. You can then modify it to develop your own project, where you may want to build Twitter sentiment analysis web app or you can use a different model to do sentiment analysis.

Leave a comment