DEV Community

Allan Niñal
Allan Niñal

Posted on • Edited on

Building a Sentiment Analysis App with React, Flask, and Hugging Face Transformers

Introduction

In today's data-driven world, understanding public opinion and customer feedback is crucial for businesses and developers alike. Sentiment analysis, also known as opinion mining, is the process of computationally identifying and categorizing opinions expressed in a piece of text, especially in order to determine whether the writer's attitude towards a particular topic, product, etc., is positive, negative, or neutral. The benefits are vast, ranging from enhanced customer understanding and improved brand reputation to effective crisis management.

This tutorial will guide you through building a lightweight web application that performs sentiment analysis on user-provided text. We'll be using a popular and powerful tech stack:

  • ReactJS for a dynamic and responsive frontend.
  • Flask (Python) for a simple yet robust backend API.
  • Hugging Face Transformers library with a pre-trained model for cutting-edge Natural Language Processing (NLP).

By the end, you'll have a working sentiment analysis app and a better understanding of how these technologies can be integrated.

Project Setup and Structure

Our application will have a standard frontend-backend architecture:

  • frontend/: Contains the React application, built with Vite for a fast development experience.
  • backend/: Houses the Flask API server responsible for the sentiment analysis logic.

Key dependencies for this project include:

  • Backend (requirements.txt):
    • flask: For creating the web server.
    • transformers: From Hugging Face, to use their pre-trained models.
    • tensorflow or torch: As the backend for the Transformers library (this project uses TensorFlow).
    • flask-cors: To handle Cross-Origin Resource Sharing between the frontend and backend during development.
  • Frontend (package.json):
    • react: For building the user interface.
    • axios: For making HTTP requests to our Flask backend.

You can find the full setup instructions in the project's README.md to get it running on your local machine.

Here's a high-level overview of the application architecture:

Image description

The Backend: Flask and Hugging Face for NLP Magic

Our Flask backend will expose a single API endpoint (/analyze) that accepts text input and returns its sentiment. The core of the sentiment analysis is handled by the Hugging Face pipeline feature, which simplifies using pre-trained models for various tasks.

backend/app.py:

from flask import Flask, request, jsonify
from flask_cors import CORS
from transformers import pipeline

app = Flask(__name__)
CORS(app) # Enable CORS for local development

# Configuration for the sentiment analysis model
# Model from Hugging Face Model Hub: https://huggingface.co/distilbert/distilbert-base-uncased-finetuned-sst-2-english
SENTIMENT_MODEL_NAME = "distilbert/distilbert-base-uncased-finetuned-sst-2-english"
SENTIMENT_MODEL_REVISION = "714eb0f" # Specific model revision for reproducibility

# Initialize the sentiment analysis pipeline
# This model is specifically trained for binary sentiment classification (positive/negative)
sentiment_classifier = pipeline(
    task="sentiment-analysis",
    model=SENTIMENT_MODEL_NAME,
    revision=SENTIMENT_MODEL_REVISION,
    framework="tf"  # Using TensorFlow backend
)

@app.route('/analyze', methods=['POST'])
def analyze_sentiment():
    request_data = request.json
    input_text = request_data.get('text', '')

    if not input_text:
        return jsonify({
            "error": "No text provided. Please include 'text' field in your request."
        }), 400

    try:
        # Perform sentiment analysis
        analysis_result = sentiment_classifier(input_text)

        # The pipeline returns a list of results, we take the first one
        return jsonify({
            "sentiment": analysis_result[0] 
        })

    except Exception as e:
        # Log the exception e for debugging
        return jsonify({
            "error": f"Analysis failed: {str(e)}"
        }), 500

if __name__ == '__main__':
    app.run(debug=True) # Runs on http://127.0.0.1:5000 by default
Enter fullscreen mode Exit fullscreen mode

Key points in the backend:

  • Model Selection: We're using distilbert/distilbert-base-uncased-finetuned-sst-2-english. This is a DistilBERT model fine-tuned on the Stanford Sentiment Treebank (SST-2) dataset, which is a common benchmark for sentiment analysis. It's a smaller and faster version of BERT, making it great for applications where efficiency is important. You can find more details on its Hugging Face Model Card.
  • Pipeline Initialization: transformers.pipeline("sentiment-analysis", model=..., revision=...) creates an easy-to-use classifier object. We specify framework="tf" because this project is set up with TensorFlow.
  • /analyze Endpoint: This route listens for POST requests containing a JSON payload like {"text": "Your text here"}. It then feeds the text to the sentiment_classifier and returns the result (e.g., {"label": "POSITIVE", "score": 0.999}.
  • Error Handling: Basic error handling is in place to inform the user if the API call fails or if no input is provided.

The Frontend: Reacting to Sentiments

The frontend is a single-page React application that provides a simple textarea for user input, a button to trigger the analysis, and a section to display the results.

frontend/src/App.jsx (Simplified):

import React, { useState } from "react";
import { analyzeSentiment } from "./services/api"; // API service using axios

function App() {
    const [userInputText, setUserInputText] = useState("");
    const [sentimentResult, setSentimentResult] = useState(null);
    const [errorMessage, setErrorMessage] = useState(null);

    const handleSentimentAnalysis = async () => {
        try {
            setErrorMessage(null);
            setSentimentResult(null);

            if (!userInputText.trim()) {
                setErrorMessage("Please enter some text to analyze.");
                return;
            }

            const response = await analyzeSentiment(userInputText);
            setSentimentResult(response.data.sentiment);
        } catch (error) {
            // More specific error handling can be added here
            setErrorMessage("An error occurred. Please try again.");
            console.error("Analysis error:", error);
        }
    };

    return (
        <div style={{ padding: "20px", maxWidth: "600px", margin: "40px auto", fontFamily: "Arial, sans-serif" }}>
            <header style={{ textAlign: "center", marginBottom: "30px" }}>
                <h1>Sentiment Analysis App</h1>
                <p>Enter text to analyze its sentiment (Positive/Negative)</p>
            </header>

            <textarea
                value={userInputText}
                onChange={(event) => setUserInputText(event.target.value)}
                placeholder="Enter your feedback, tweet, or any text here..."
                style={{ width: "100%", minHeight: "100px", marginBottom: "15px", padding: "10px", boxSizing: "border-box", borderRadius: "4px", border: "1px solid #ccc" }}
                aria-label="Text input for sentiment analysis"
            />

            <button 
                onClick={handleSentimentAnalysis} 
                style={{ display: "block", width: "100%", padding: "10px 15px", backgroundColor: "#007bff", color: "white", border: "none", borderRadius: "4px", cursor: "pointer", fontSize: "16px" }}
                aria-label="Analyze sentiment"
            >
                Analyze Sentiment
            </button>

            {errorMessage && (
                <p style={{ color: "red", marginTop: "15px" }} role="alert">
                    Error: {errorMessage}
                </p>
            )}

            {sentimentResult && (
                <div style={{ marginTop: "25px", padding: "15px", border: `2px solid ${sentimentResult.label === 'POSITIVE' ? 'green' : 'red'}`, borderRadius: "4px" }}>
                    <h2>Analysis Result:</h2>
                    <p><strong>Sentiment:</strong> {sentimentResult.label}</p>
                    <p><strong>Confidence Score:</strong> {sentimentResult.score.toFixed(4)}</p>
                </div>
            )}
        </div>
    );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

frontend/src/services/api.js:

import axios from "axios";

// Ensure this matches the port your Flask backend is running on
const SENTIMENT_API_BASE_URL = "http://127.0.0.1:5000";

/**
 * Sends text to the backend for sentiment analysis.
 * @param {string} text - The text content to analyze.
 * @returns {Promise<Object>} Axios response object containing sentiment analysis results.
 */
export const analyzeSentiment = (text) => {
    return axios.post(`${SENTIMENT_API_BASE_URL}/analyze`, { text });
};
Enter fullscreen mode Exit fullscreen mode

Key points in the frontend:

  • State Management: useState hook manages the userInputText, the sentimentResult from the API, and any errorMessage.
  • API Call: The handleSentimentAnalysis function calls analyzeSentiment (from api.js) which uses axios to send a POST request to the /analyze endpoint of our Flask backend.
  • Displaying Results: The component conditionally renders the sentiment label (POSITIVE/NEGATIVE) and its confidence score, with some basic styling to indicate the sentiment (e.g., green for positive, red for negative).
  • Error Handling: Basic error handling is in place to inform the user if the API call fails or if no input is provided.

How It All Connects

Let's visualize the data flow when a user requests a sentiment analysis:

Image description

The workflow of the application is straightforward:

  1. The user types text into the textarea in the React frontend.
  2. Clicking "Analyze Sentiment" triggers the handleSentimentAnalysis function.
  3. axios sends a POST request with the text to the Flask backend's /analyze endpoint.
  4. The Flask app receives the request, uses the Hugging Face sentiment_classifier to process the text.
  5. The model returns a sentiment (e.g., {'label': 'POSITIVE', 'score': 0.9999}).
  6. Flask sends this result back to the React frontend as a JSON response.
  7. The React app updates its state with the result and displays it to the user.

Running the App

To run this application locally:

  1. Clone the repository (if you haven't already).
  2. Backend:
    • Navigate to the backend directory.
    • Create a virtual environment and activate it.
    • Install dependencies: pip install -r requirements.txt
    • Run the Flask app: python app.py (or flask run)
  3. Frontend:
    • Open a new terminal and navigate to the frontend directory.
    • Install dependencies: npm install
    • Start the React development server: npm run dev
  4. Open your browser to the address shown by the React dev server (usually http://localhost:5173).

Conclusion

We've successfully built a full-stack sentiment analysis application! This project demonstrates how React and Flask can work together seamlessly and how easily you can integrate powerful pre-trained NLP models from the Hugging Face ecosystem into your applications.

Potential next steps and improvements:

  • More Sophisticated Error Handling: Add more detailed error messages for different failure scenarios.
  • Loading States: Implement loading indicators while the API request is in progress.
  • Support for More Languages: Explore other Hugging Face models for multilingual sentiment analysis.
  • Neutral Sentiment: The current model is binary (Positive/Negative). You could find or fine-tune models that also classify neutral sentiment or even more granular emotions.
  • Deployment: Containerize the app with Docker and deploy it to a cloud platform.

Sentiment analysis is a fascinating field with many practical applications. Hopefully, this tutorial provides a solid starting point for your own NLP adventures!


The code for this project is available on GitHub.

Support the Author

If you found this tutorial helpful or are interested in other creative coding projects, you can:


References:


Open for Projects

I'm currently available to take on new projects in the following areas:

  • Artificial Intelligence solutions (both no-code and custom development)
  • No-code automation with n8n (and open to other automation platforms)
  • React.js frontend development
  • Node.js backend/API development
  • WooCommerce development and customization
  • Stripe payment integration and automation
  • PHP applications and frameworks
  • Python development
  • Supabase, Vercel & GitHub integration

My Expertise

I'm a Senior Web Developer with growing expertise in AI/ML solutions, passionate about creating practical applications that leverage artificial intelligence to solve real-world problems. While relatively new to AI/ML development (less than a year of focused experience), I've quickly built a portfolio of functional projects that demonstrate my ability to integrate AI capabilities into useful applications. My specialized skills include:

  • AI Integration: Connecting pre-trained AI models with web applications through APIs and direct implementation
  • Computer Vision & NLP: Implementing image captioning, sentiment analysis, text summarization, chatbots, and language translation applications
  • Agentic AI Workflows: Creating intelligent autonomous agents that can execute complex tasks through multi-step reasoning
  • Full-Stack Development: Crafting seamless experiences with React.js frontends and Python/Flask or Node.js backends
  • E-commerce Solutions: Expert in WooCommerce/Stripe integrations with subscription management and payment processing
  • Automation Tools: Python scripts and n8n workflows for business-critical processes and data pipelines
  • Content Automation: Creating AI-powered systems that generate complete content packages from blog posts to social media updates

Featured Projects

Personal AI Chatbot - A complete conversational AI application built with React and Flask, powered by Microsoft's DialoGPT-medium model from Hugging Face. This project demonstrates how to create an interactive chatbot with a clean, responsive interface that understands and generates human-like text responses.

Image Captioning App - A full-stack application that generates descriptive captions for uploaded images using AI. Built with React for the frontend and Flask for the backend, this app leverages Salesforce's BLIP model via Hugging Face's transformers library to analyze images and create natural language descriptions of their content.

Sentiment Analysis App - A lightweight full-stack application that performs sentiment analysis on user-provided text using React.js for the frontend and Flask with Hugging Face Transformers for the backend. This project demonstrates how easily powerful pre-trained NLP models can be integrated into modern web applications.

Agentic AI Workflow - A Python-based framework for building intelligent AI agents that can break down complex tasks into manageable steps and execute them sequentially. This project demonstrates how to leverage OpenRouter API to access multiple AI models (OpenAI, Anthropic, Google, etc.) through a unified interface, enabling more sophisticated problem-solving capabilities and better reasoning in AI applications.

WiseCashAI - A revolutionary privacy-first financial management platform that operates primarily in your browser, ensuring your sensitive financial data never leaves your control. Unlike cloud-based alternatives that collect and monetize your information, WiseCashAI offers AI-powered features like intelligent transaction categorization, envelope-based budgeting, and goal tracking while keeping your data local. Optional Google Drive integration with end-to-end encryption provides cross-device access without compromising privacy.

Content Automation Workflow Pro - AI-powered content generation system that transforms content creation with a single command. This Python-based workflow leverages OpenRouter and Replicate to generate SEO-optimized blog posts, custom thumbnail images, and platform-specific social media posts across 7+ platforms, reducing content creation time from hours to minutes.

Stripe/WooCommerce Integration Tools:

  • Stripe Validator Tool - Cross-references WooCommerce subscription data with the Stripe API to prevent payment failures (78% reduction in failures)
  • Invoice Notifier System - Automatically identifies overdue invoices and sends strategic payment reminders (64% reduction in payment delays)
  • WooCommerce Bulk Refunder - Python script for efficiently processing bulk refunds with direct payment gateway API integration

Open-Source AI Mini Projects

I'm actively developing open-source AI applications that solve real-world problems:

  • Image Captioning App - Generates descriptive captions for images using Hugging Face's BLIP model
  • AI Resume Analyzer - Extracts key details from resumes using BERT-based NER models
  • Document Summarizer - Creates concise summaries from lengthy documents using BART models
  • Multilingual Translator - Real-time translation tool supporting multiple language pairs
  • Toxic Comment Detector - Identifies harmful or offensive language in real-time
  • Recipe Finder - AI-powered tool that recommends recipes based on available ingredients
  • Personal AI Chatbot - Customizable chat application built with DialoGPT

All these projects are available on my GitHub with full source code.

Development Philosophy

I believe in creating technology that empowers users without compromising their privacy or control. My projects focus on:

  • Privacy-First Design: Keeping sensitive data under user control by default
  • Practical AI Applications: Leveraging AI capabilities to solve real-world problems
  • Modular Architecture: Building systems with clear separation of concerns for better maintainability
  • Accessibility: Making powerful tools available to everyone regardless of technical expertise
  • Open Source: Contributing to the community and ensuring transparency

Technical Articles & Tutorials

I regularly share detailed tutorials on AI development, automation, and integration solutions:

I specialize in developing practical solutions that leverage AI and automation to solve real business problems and deliver measurable results. Find my tutorials on DEV.to and premium tools in my Gumroad store.

If you have a project involving e-commerce, content automation, financial tools, or custom AI applications, feel free to reach out directly at [email protected].

Top comments (0)