Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 37 ยท Projects and Practice

Project: Sentiment Analyzer

Build a complete sentiment analyzer: a lexicon scorer with negation, highlighted words, a batch table, and the Blocks layout, tests and deployment files, with runnable core logic.

In this project you build a sentiment analyzer end to end: type a review, see a verdict with a confidence score, see which words drove it, and paste many reviews to get a table. It uses no downloaded model, so the whole scoring logic runs right here. When you later want better accuracy you replace one function with a real model, and everything else stays the same.

The Gradio code in this lesson is real and read-only (the library cannot run on this site). The scoring core is plain Python and fully runnable. We follow the structure from structuring larger apps: logic first, UI second.

Plan

flowchart LR
    T["Review text"] --> L["tokenize"]
    L --> S["score words<br/>(lexicon + negation)"]
    S --> V["verdict + confidence"]
    S --> H["highlighted words"]
    V --> UI["Label + HighlightedText"]
    H --> UI

One scoring pass produces both outputs.

Step 1: tokenize and score

The lexicon gives each word a weight. Negation words ("not", "never") flip the next sentiment word, and intensifiers ("very") scale it.

Python Scoring core with negation

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.

The first review has a high positive score, the second is clearly negative ("not good" flips to negative, "very slow" is boosted) and the third scores a neutral 0.5 because no lexicon words appear. A real model understands far more, but this core is already testable and deterministic.

Step 2: highlight the words that mattered

gr.HighlightedText takes (text, label) pairs, where the label can be a number if you set color_map or combine_adjacent. We output the score of each word, and None for neutral words:

Python Build HighlightedText pairs

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.

The output lists plain pieces with None and the three sentiment words labelled positive or negative. The final line prints True: joining the pieces gives the original text, the invariant to test.

Step 3: batch mode

Many reviews at once is useful for analysts. Split the textbox by lines, analyze each and return rows for a gr.Dataframe:

Python Batch rows and a summary

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.

Four rows come back with labels positive, negative, neutral and positive ("Good, not great" scores 1 + 2 here because this simple scorer ignores negation, a good reason to reuse the full score_tokens from step 1). The counts dictionary can feed a gr.BarPlot or a Label.

Step 4: the Blocks app

Now wire the logic to the interface. The core module holds the functions above; app.py is thin:

Python
import gradio as gr
from core import analyze, highlight, batch

def single(text):
    if not text.strip():
        raise gr.Error("Please type a review.")
    r = analyze(text)
    return r["scores"], highlight(text)

with gr.Blocks(title="Sentiment analyzer", theme=gr.themes.Soft()) as demo:
    gr.Markdown("# Sentiment analyzer\nA small rule-based demo.")
    with gr.Tab("One review"):
        review = gr.Textbox(lines=4, label="Review")
        go = gr.Button("Analyze", variant="primary")
        with gr.Row():
            verdict = gr.Label(label="Verdict")
            words = gr.HighlightedText(label="Key words", combine_adjacent=True)
        go.click(single, review, [verdict, words], api_name="analyze")
        gr.Examples([["Great phone, I love it"], ["Not good. Very slow!"]], review)
    with gr.Tab("Many reviews"):
        many = gr.Textbox(lines=8, label="One review per line")
        table = gr.Dataframe(headers=["Review", "Label", "Score"])
        gr.Button("Analyze all").click(batch, many, table, api_name="batch")

if __name__ == "__main__":
    demo.launch()

After launch, the page has two tabs. In the first, a review goes in and a Label with bars and a text with colored words come out. In the second, a table fills with one row per line. Hitting Analyze on an empty box shows the red error toast from gr.Error.

Step 5: tests and deployment

Write function tests for the core (negation, boosters, empty text, the lossless highlight property) as in testing, and add one client test for /analyze. For deployment, the Space needs app.py, core.py, a README.md with the YAML header and no extra requirements, since the logic uses only the standard library.

Ideas to extend it

  • Replace analyze with transformers.pipeline("sentiment-analysis") and keep the highlight function using the pipeline's word scores or attention.
  • Add a CSV upload (gr.File) and return a downloadable result file.
  • Add a bar plot of label counts for batch mode.
  • Add a language dropdown with a different lexicon per language.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is the scoring logic kept in its own module?

    Logic without Gradio imports is easy to test and swap.
  2. 2. What does a negation word do in this scorer?

    'not good' becomes negative because good's weight is negated.
  3. 3. Which invariant should a highlight function keep?

    No characters may be lost or added.
  4. 4. Which component shows the table for batch results?

    Dataframe renders rows and headers.

Summary

  • Put the scoring logic in a plain module; the UI only adapts it.
  • A single pass can produce both the verdict and the highlighted words.
  • Batch mode turns lines into table rows; errors use gr.Error.
  • Swapping in a real model later changes one function.

Next: Project: Image Filter Studio