Skip to content

Instantly share code, notes, and snippets.

@drhanlau
Last active March 13, 2022 01:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drhanlau/82347331a6d440c6ef3725126db4ff44 to your computer and use it in GitHub Desktop.
Save drhanlau/82347331a6d440c6ef3725126db4ff44 to your computer and use it in GitHub Desktop.
12th March Private Data Science Lab
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello_world():
return "<p>Hello, World!</p>"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sentiment Analysis</title>
</head>
<body>
<div class="fixed bottom-0 pb-5 text-center text-gray-500 text-sm w-full">
Powered by LEAD (https://thelead.io)
</div>
<div class="flex h-screen">
<div class="m-auto text-center pb-10">
<h1 class="text-5xl font-bold">IKWYT Sentiment Analyzer</h1>
<div class="mt-5">
<input type="text" id="sentence" class="w-full bg-gray-100 bg-opacity-50 rounded border border-gray-300 text-gray-700 py-1 px-3 leading-8 transition-colors duration-200 ease-in-out" placeholder="Please enter your sentence">
</div>
<button class="text-white bg-indigo-500 border-0 py-2 px-6 text-lg mt-5 text-center mx-auto" onclick="analyzeSentiment()">Analyze</button>
<div id="result" class="pt-5 text-lg text-gray-600">
&nbsp;
</div>
</div>
</div>
</body>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
function analyzeSentiment() {
var sentence = document.getElementById("sentence").value;
axios.get('http://127.0.0.1:5000/sentiment', {
params: {
s: sentence
}})
.then(function(response) {
var sentiment = response['data'];
var result = `Compound 📊 : ${sentiment['compound'].toFixed(3)} |
Positive 🤩 : ${sentiment['pos'].toFixed(3)} |
Negative 🤮 : ${sentiment['neg'].toFixed(3)} |
Neutral 😐 : ${sentiment['neu'].toFixed(3)}`;
document.getElementById('result').innerHTML = result;
});
}
</script>
</html>
from flask import Flask, render_template,request, jsonify
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
nltk.download('vader_lexicon')
app = Flask(__name__)
@app.route('/')
def home():
return render_template('senti.html')
@app.route('/sentiment')
def analyze():
args = request.args
s = args.get("s")
analyzer = SentimentIntensityAnalyzer()
score = analyzer.polarity_scores(s)
return score

Full Stack Data Scientist Demo

Install Flask

pip install flask

Our first app Hello.py

Create a file hello.py with the following code.

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

Run our app

For Mac

export FLASK_APP=hello.py FLASK_ENV=development
flask run

For Windows Command Prompt

set FLASK_APP=hello.py 
set FLASK_ENV=development
flask run

For PowerShell

$env:FLASK_APP = "hello"
$env:FLASK_ENV = "development"
flask run

If your app doesn't show up, try to use python -m flask run, sometimes it is due to the path configuration.

If you see the following, means we have successfully launched our app!

(ds360) ➜  ds360 flask run
 * Serving Flask app 'hello.py' (lazy loading)
 * Environment: development
 * Debug mode: on
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 633-980-227

Add sentiment analysis function

create a new route name sentiment and add the following code to hello.py:

@app.route("/sentiment")
def analyze():
 s = "Today is the voting day. I am so excited to vote."
 analyzer = SentimentIntensityAnalyzer()
 score = analyzer.polarity_scores(s)
 return score

Restart our server. Stop the Flask app (using Ctrl-c), and rerun the flask run command.

If it complains that NLTK is not installed, run pip install nltk before restarting.

After restarting our Flask app, open http://127.0.0.1:5000/sentiment in your browser. You should receive the following output.

{
  "compound": 0.4795, 
  "neg": 0.0, 
  "neu": 0.743, 
  "pos": 0.257
}

Analyze sentiment from URL query string

First of all, add request to the import.

from flask import Flask, request

Update our analyze() method with the following code:

@app.route("/sentiment")
def analyze():
  args = request.args
  s = args.get("s")
  
  analyzer = SentimentIntensityAnalyzer()
  score = analyzer.polarity_scores(s)
  return score

Open http://127.0.0.1:5000/sentiment?s=today%20is%20the%20voting%20day%20and%20I%20am%20excited in your browser. And you see the following outputs.

{
  "compound": 0.34, 
  "neg": 0.0, 
  "neu": 0.745, 
  "pos": 0.255
}

Show HTML content

Stop the Flask app, and create a templates folder using

md templates

add render_template to the import, and update hello_world method with the following

@app.route("/") 
def hello_world():
    return render_template('senti.html')

Restart your app now, and you should see the

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment