Building a Sentiment Analysis Web App Using Python, FastAPI, and Hugging Face

Follow on LinkedIn

Sentiment analysis is one of the most widely used applications of Natural Language Processing (NLP). It helps determine whether a piece of text expresses a positive, negative, or neutral opinion. From customer reviews and feedback analysis to social media monitoring, sentiment analysis plays a crucial role in understanding user emotions at scale.

In this article, we will build a Sentiment Analysis Web Application using Python, FastAPI, and Hugging Face. The application accepts user text through a simple browser interface and classifies it as Positive, Negative, or Neutral, along with a confidence score.

We use a pre-trained transformer model, which means there is no need to train a machine learning model from scratch. The focus is on building a real-world AI application using production-style architecture.

🎥 Watch the Full Video Tutorial on YouTube
👉 Sentiment Analysis App using Python, FastAPI & Hugging Face

Sentiment Analysis Web App Using Python, FastAPI, and Hugging Face
Sentiment Analysis Web App Using Python, FastAPI, and Hugging Face

What This Sentiment Analysis App Does

The application provides the following functionality:

  • Accepts text input from the user
  • Analyzes sentiment using a pre-trained NLP model
  • Classifies the sentiment as Positive, Negative, or Neutral
  • Displays a confidence score
  • Provides a browser-based UI without requiring Postman or Swagger

This makes the app simple to test and easy to extend.

How the Application Works

The overall flow of the application is simple:

  1. The user enters text in the browser
  2. The frontend sends the text to a FastAPI endpoint
  3. A Hugging Face sentiment analysis pipeline processes the text
  4. The backend interprets the result and determines sentiment
  5. The response is returned as JSON and displayed in the UI

To handle uncertain predictions, a confidence threshold is applied. If the confidence score is low, the sentiment is classified as Neutral.

Installation and Setup

Make sure Python 3.9 or later is installed.

Step 1: Create and Activate a Virtual Environment

python -m venv venv
venv\Scripts\activate   # Windows

Step 2: Install Dependencies

Create a requirements.txt file with the following content:

fastapi==0.100.0
uvicorn[standard]==0.22.0
transformers==4.40.0
torch==2.2.0
pydantic==1.10.7
numpy==1.26.4

Then install the dependencies:

pip install -r requirements.txt

Project Structure

app/
├── main.py
├── models.py
├── sentiment.py
└── frontend.py

Each file has a clear responsibility, keeping the project modular and easy to maintain.

Complete Working Code

from pydantic import BaseModel, Field

class SentimentRequest(BaseModel):
    text: str = Field(..., description="Text for sentiment analysis")

class SentimentResponse(BaseModel):
    sentiment: str
    confidence: float
    model: str
from transformers import pipeline
import threading

_MODEL = None
_LOCK = threading.Lock()

def get_sentiment_model():
    global _MODEL
    if _MODEL is None:
        with _LOCK:
            if _MODEL is None:
                _MODEL = pipeline(
                    "sentiment-analysis",
                    model="distilbert-base-uncased-finetuned-sst-2-english",
                    device=-1
                )
    return _MODEL


def analyze_sentiment(text: str):
    model = get_sentiment_model()
    result = model(text)[0]

    label = result["label"]
    score = float(result["score"])

    if score < 0.6:
        sentiment = "Neutral"
    elif label == "POSITIVE":
        sentiment = "Positive"
    else:
        sentiment = "Negative"

    return {
        "sentiment": sentiment,
        "confidence": score
    }
from fastapi.responses import HTMLResponse

def sentiment_ui():
    return HTMLResponse("""
    <!DOCTYPE html>
    <html>
    <head>
        <title>Sentiment Analysis App</title>

        <script>
            async function analyze() {
                const text = document.getElementById('text').value;

                const response = await fetch('/analyze', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({ text })
                });

                const data = await response.json();
                document.getElementById('result').innerHTML =
                    `Sentiment: <b>${data.sentiment}</b><br/>
                     Confidence: ${data.confidence}`;
            }
        </script>
    </head>

    <body>
        <h1>Sentiment Analysis</h1>

        <textarea id="text" rows="6" cols="60"></textarea><br/><br/>
        <button onclick="analyze()">Analyze</button>

        <p id="result"></p>
    </body>
    </html>
    """)
from fastapi import FastAPI, HTTPException
from app.models import SentimentRequest, SentimentResponse
from app.sentiment import analyze_sentiment
from app.frontend import sentiment_ui

app = FastAPI(title="Sentiment Analysis API", version="1.0")

@app.get("/")
async def home():
    return sentiment_ui()

@app.post("/analyze", response_model=SentimentResponse)
async def analyze(payload: SentimentRequest):

    if not payload.text.strip():
        raise HTTPException(status_code=400, detail="Text cannot be empty")

    result = analyze_sentiment(payload.text)

    return SentimentResponse(
        sentiment=result["sentiment"],
        confidence=round(result["confidence"], 4),
        model="distilbert-base-uncased-finetuned-sst-2-english"
    )

Running the Application

Start the server using:

uvicorn app.main:app --reload

Open your browser and visit:

http://127.0.0.1:8000

Final Thoughts

This Sentiment Analysis project demonstrates how powerful NLP models can be integrated into real applications using Python and FastAPI. By using pre-trained transformer models, we avoid complex training pipelines and focus on clean application design. This project is ideal for learning NLP concepts, building portfolio projects, and understanding real-world AI integration.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

×