Skip to content
Tutorials Center
My learning

Topics

Lesson 68 of 72 ยท Projects

Project: A Sentiment Analysis Web App

Build a Flask app that scores short texts as positive, neutral or negative, stores them in SQLite and serves summary data for a chart. Then swap in a real model.

A sentiment analyzer reads a short text (a review, a comment, a post) and decides whether the writer sounds happy, unhappy or neutral. Companies use it to watch what customers say. It also makes a good Flask project, because it joins four skills you already have: a form, a validation step, a database and a JSON endpoint that feeds a chart.

Many tutorials build this by pulling live posts from a social network through its API and scoring them with a library such as TextBlob. That version needs paid API keys and network access, and the interesting part, the web app around the scorer, gets buried. Here you build the app around a scorer you can swap. You start with a small word-list scorer that runs in your browser, and at the end you see exactly where a real model or an external API plugs in.

flowchart LR
    A["Form<br/>POST /add"] --> B["Validate<br/>1 to 280 characters"]
    B --> C["score(text)<br/>swappable"]
    C --> D[("SQLite<br/>posts table")]
    D --> E["Home page<br/>latest posts"]
    D --> F["GET /api/summary<br/>JSON for a chart"]

Everything between the form and the database stays the same when you replace the scorer.

Step 1: a scorer you can understand

The simplest scorer is a lexicon: lists of positive and negative words. Count them, flip a word when it follows a negation ("not good"), and divide by the number of opinion words so the result runs from -1 (all negative) to +1 (all positive). A text without any opinion word scores 0.

Python A tiny sentiment scorer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

This approach is easy to explain and to test, but it is crude. It misses sarcasm ("great, another crash"), it does not know words outside its lists, and it only understands English. Real tools use larger lexicons (VADER is a well-known one for social media text) or machine-learning models. The important design point is that the rest of the app only needs one function: score(text) -> float.

Step 2: the app

The app has four routes. GET / shows a form and the latest posts. POST /add validates the text, scores it, stores it and redirects (the Post/Redirect/Get pattern from Flash Messages). GET /api/summary returns counts per label as JSON, which is exactly what a chart needs (Charts and Dashboards shows how to draw it). The database code uses plain sqlite3 and the g object, as in SQLite in Flask.

Python Sentiment app: form, database, chart data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Points worth noticing:

  • Validation first. An empty or oversized text returns 400 before anything touches the database.
  • Parameterized SQL. The ? placeholders keep user text out of the query string, so SQL injection is not possible (Web Security).
  • Escaping. One post contains a <script> tag, and Jinja turns it into harmless text because autoescaping is on.
  • A shared in-memory database (mode=memory&cache=shared) is used only so the demo runs in the browser. In a real project you would use a file such as instance/sentiment.db.

A live social feed is a data source, not part of the design. Reading posts from an API on a schedule and calling the same add logic would turn this into a monitoring tool. Keep the API key a secret in the environment (Configuration), respect the provider's rate limits and read its terms before storing other people's posts.

Step 3: swap in a real scorer

Because the app only calls score(), you can replace its body:

Python
# Option 1: a lexicon built for social text (pip install vaderSentiment)
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
analyzer = SentimentIntensityAnalyzer()

def score(text):
    return analyzer.polarity_scores(text)["compound"]      # -1.0 to 1.0

# Option 2: a pretrained model (pip install transformers torch)
# from transformers import pipeline
# classifier = pipeline("sentiment-analysis")
# result = classifier(text)[0]    # {"label": "POSITIVE", "score": 0.99}

These libraries are not available in the browser, so the snippet is read-only. Two practical tips: load models once at start-up, never per request, because loading takes seconds; and for heavy models run the scoring in a background job (Async Views and Background Tasks) or a separate service (Deploying a Machine Learning Model).

Step 4: show the results

The summary endpoint returns three lists of equal length, which map directly onto a Chart.js pie or doughnut chart:

HTML
<canvas id="mood" width="320" height="320"></canvas>
<script type="module">
  import Chart from "https://cdn.jsdelivr.net/npm/chart.js@4/auto/+esm";
  const data = await (await fetch("/api/summary")).json();
  new Chart(document.getElementById("mood"), {
    type: "doughnut",
    data: { labels: data.labels, datasets: [{ data: data.counts }] },
  });
</script>

For a quick image without JavaScript, draw the same numbers with Matplotlib on the server and return a PNG, as shown in the charts lesson.

Where this can grow

  • Store a timestamp with every post and chart the mood per day.
  • Add user accounts so people see only their own posts (Login System).
  • Add a batch import: a CSV upload (File Uploads) scored row by row.
  • Cache the summary for a minute (Performance and Caching) when many people watch the dashboard.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the app call a single function score(text) instead of putting the scoring logic inside the view?

    Isolating the scorer behind one function is a design choice. Any implementation that returns a number in the same range fits.
  2. 2. What does the lexicon scorer return for a text with no opinion words?

    With no hits the code returns 0.0, which falls between the -0.2 and 0.2 thresholds, so the label is neutral.
  3. 3. A user submits a post containing a script tag. Why is it safe on the home page?

    The text is stored as typed. Autoescaping converts < and > into entities when the page is rendered, so the browser shows text instead of running it.
  4. 4. Where should a heavy machine-learning model be loaded?

    Loading a model takes seconds and a lot of memory. Load it once and call it per request, or move scoring to a background worker.

Summary

  • A sentiment app is a form, a validator, a swappable score() function, a table and a JSON summary.
  • A word-list scorer with negation handling is easy to understand and test; real projects use VADER or a trained model.
  • Validate input, use parameterized SQL and let Jinja escape the output.
  • A live social feed is just another way to call the same add logic; keep keys in the environment and obey rate limits.
  • Serve chart-ready lists from /api/summary and let Chart.js or Matplotlib draw them.

Next: Charts and Dashboards in Flask, where numbers like these become real graphs.