🚀 Build a Multi-Input Sentiment Analysis App Using Hugging Face Spaces and Gradio

In the previous post, we explored how to use the Hugging Face Inference API to access powerful machine learning models without training anything from scratch. We sent a simple text input to a pre-trained sentiment analysis model and got meaningful results. Today, let’s go a step further. We’ll build a web app that accepts input text, a text file, or a web URL and then returns the sentiment prediction (positive, neutral, or negative) using Hugging Face’s Inference API. The best part? We’ll use Gradio for the frontend and deploy it seamlessly to Hugging Face Spaces.

🌍 What is Hugging Face Spaces?

Hugging Face Spaces is a free platform that lets you deploy and share machine learning apps with just a few lines of code. It supports popular frameworks like Gradio, Streamlit, and Static HTML, making it incredibly easy for developers, students, and researchers to showcase models and demos without needing to set up servers.

  • Zero infrastructure setup

  • Free public hosting

  • Great for showcasing ML models

    Think of Spaces as GitHub Pages but for interactive AI apps.

🎛️ What is Gradio?

Gradio is an open-source Python library that lets you build simple web apps for your machine learning models or functions, with just a few lines of code.

With Gradio, you can easily:

  • Create interfaces using inputs like text, images, files, or audio

  • Visualize model predictions in real time

  • Share your app with a one-click public link

Gradio apps run locally or on Hugging Face Spaces, making them perfect for tutorials, demos, and prototyping.

🧠 Why Use Them Together?

By combining Gradio (to build the app) and Spaces (to host it), you can:

  • Build your ML app in Python

  • Deploy it instantly on the web

  • Share your work with anyone — no DevOps required

In this blog, we’ll build and deploy a sentiment analyzer that takes text, files, or a URL as input — all using Gradio and hosted on Hugging Face Spaces!

🧪 Step 1: Install the Required Libraries

In your development environment or Colab notebook for initial checking, install the necessary packages:

!pip install gradio requests beautifulsoup4

📦 Step 2: Build the Python App

The code below gives the sentiment analysis app. Save the file as app.py locally.

import os
import gradio as gr
import requests
from bs4 import BeautifulSoup

API_URL = "https://api-inference.huggingface.co/models/cardiffnlp/twitter-roberta-base-sentiment"
HF_TOKEN = os.getenv("HF_TOKEN")
headers = {"Authorization": f"Bearer {HF_TOKEN}"}

label_map = {
    "LABEL_0": "Negative",
    "LABEL_1": "Neutral",
    "LABEL_2": "Positive"
}

def fetch_url_text(url):
    try:
        headers_req = {'User-Agent': 'Mozilla/5.0'}
        response = requests.get(url, headers=headers_req, timeout=10)
        response.raise_for_status()
        soup = BeautifulSoup(response.text, "html.parser")
        return soup.get_text()
    except Exception as e:
        return f"URL error: {e}"

def analyze_sentiment(text_input, file_upload, url_input):
    text = ""
    if file_upload:
        try:
            with open(file_upload.name, "r", encoding="utf-8") as f:
                text = f.read()
        except Exception as e:
            return f"❌ File read error: {e}"
    elif url_input:
        text = fetch_url_text(url_input)
        if "URL error" in text:
            return text
    elif text_input:
        text = text_input
    else:
        return "⚠️ Please provide input."

    payload = {"inputs": text[:1000]}
    response = requests.post(API_URL, headers=headers, json=payload)

    try:
        results = response.json()[0]
        top_result = max(results, key=lambda r: r["score"])
        sentiment = label_map[top_result["label"]]
        score = top_result["score"]
        return f"🧠 Sentiment: {sentiment} ({score:.2%})"
    except Exception as e:
        return f"❌ JSON parse error: {e}"

demo = gr.Interface(
    fn=analyze_sentiment,
    inputs=[
        gr.Textbox(label="Enter Text", lines=3, placeholder="Type text here..."),
        gr.File(label="Upload a .txt File", file_types=[".txt"]),
        gr.Textbox(label="Enter Webpage URL", placeholder="https://...")
    ],
    outputs="text",
    title="Multi-Input Sentiment Analyzer",
    description="Analyze sentiment from input text, a text file, or a webpage using Hugging Face."
)

demo.launch()

Code Explanation: Multi-Input Sentiment Analyzer Using Hugging Face & Gradio

💡 Overview

This script builds a web-based sentiment analysis application using Gradio and the Hugging Face Inference API. It supports three types of inputs:

  • ✍️ Raw text typed by the user

  • 📁 Uploaded .txt files

  • 🌍 Webpage URLs

The text is passed to the Hugging Face model cardiffnlp/twitter-roberta-base-sentiment which returns the sentiment classification: Positive, Neutral, or Negative.

📆 Imports

import os
import gradio as gr
import requests
from bs4 import BeautifulSoup

These libraries help in:

  • Reading environment variables (os)

  • Creating web UI (gradio)

  • Making API requests (requests)

  • Extracting readable text from HTML (BeautifulSoup)

🔐 API Configuration

API_URL = "https://api-inference.huggingface.co/models/cardiffnlp/twitter-roberta-base-sentiment"
HF_TOKEN = os.getenv("HF_TOKEN")
headers = {"Authorization": f"Bearer {HF_TOKEN}"}
  • API URL points to the sentiment model on Hugging Face.

  • API token is securely fetched from the environment.

  • Authorization headers are prepared.

  • Do NOT hardcode your Hugging Face token in the app.py. Instead:

    • Go to your Space → Settings → Secrets.

    • Add a new secret with the key HF_TOKEN and paste your API key as the value.

🏷️ Label Mapping

label_map = {
    "LABEL_0": "Negative",
    "LABEL_1": "Neutral",
    "LABEL_2": "Positive"
}

These map model output labels to readable strings.

🌐 Webpage Text Extraction

def fetch_url_text(url):
    try:
        headers_req = {'User-Agent': 'Mozilla/5.0'}
        response = requests.get(url, headers=headers_req, timeout=10)
        response.raise_for_status()
        soup = BeautifulSoup(response.text, "html.parser")
        return soup.get_text()
    except Exception as e:
        return f"URL error: {e}"
  • Fetches webpage content.

  • Extracts visible text using BeautifulSoup.

  • Handles common errors like timeouts or HTTP failures.

🧬 Sentiment Analysis Logic

def analyze_sentiment(text_input, file_upload, url_input):

This function handles all three input types:

  • File Upload: Reads content from a .txt file.

  • Webpage URL: Extracts text using the function above.

  • Raw Text: Uses direct input.

Then sends up to 1000 characters to the Hugging Face model:

    payload = {"inputs": text[:1000]}
    response = requests.post(API_URL, headers=headers, json=payload)

Parses the response and returns the most confident sentiment label:

    results = response.json()[0]
    top_result = max(results, key=lambda r: r["score"])
    sentiment = label_map[top_result["label"]]
    score = top_result["score"]
    return f"🧠 Sentiment: {sentiment} ({score:.2%})"

💻 Gradio Interface

demo = gr.Interface(
    fn=analyze_sentiment,
    inputs=[
        gr.Textbox(label="Enter Text", lines=3, placeholder="Type text here..."),
        gr.File(label="Upload a .txt File", file_types=[".txt"]),
        gr.Textbox(label="Enter Webpage URL", placeholder="https://...")
    ],
    outputs="text",
    title="Multi-Input Sentiment Analyzer",
    description="Analyze sentiment from input text, a text file, or a webpage using Hugging Face."
)

Defines the web UI with labeled input fields and a text output.

▶️ Launch the App

demo.launch()

Starts a local or hosted Gradio interface (such as on Hugging Face Spaces).

🚨 Input Restrictions

  • The Hugging Face API limits text input length. This app truncates input to the first 1000 characters.

  • Uploaded files must be plain .txt files encoded in UTF-8.

  • Webpages must be public and text-based (not JS-rendered).

  • Make sure your HF_TOKEN is correctly set in the environment variables when deploying.

☁️ Step 3: Deploy to Hugging Face Spaces

  1. Go to Hugging Face Spaces.

  2. Click on Create new Space → choose Gradio as the SDK.

  3. Upload your app.py and requirements.txt files.

  4. The requirements.txt file has to be created with these contents:

gradio
requests
beautifulsoup4

Once app.py and requirements.txt are uploaded to spaces, click “ Commit Changes”. You’ll see “Building”, then “Running”. If it takes too long, check the logs in the “Logs” tab.

🌐 View and Share Your App

Once the Space is running:

👉 Visit your app at:
https://huggingface.co/spaces/your-username/your-space-name

For example, a running app deployed is:

🔗 https://huggingface.co/spaces/divivetri/multi-input-sentiment

You can now share this public URL with anyone — it’s fully interactive!

Test the sentiment analyzer app with these example webpages:

🎉 Wrap-Up

You've just launched your very own multi-input sentiment analyzer — powered by Hugging Face and brought to life with Gradio on Spaces! Type a message, upload a file, or drop in a URL, and instantly see the sentiment behind the words. It's fast, fun, and a great way to see real-world NLP in action.

This is just the beginning. Tweak it, expand it, or build something totally new. The tools are ready — all that’s left is your creativity.

✨ Go ahead, give it a spin. You’ll be amazed at what a few lines of code can do!

📚 References & Credits

  • 🤗 Hugging Face Inference API
    API used to access the cardiffnlp/twitter-roberta-base-sentiment model.
    Docs: https://huggingface.co/docs/api-inference

  • 🧠 Model: cardiffnlp/twitter-roberta-base-sentiment
    Developed by Cardiff NLP.
    Model page: https://huggingface.co/cardiffnlp/twitter-roberta-base-sentiment

    Barbieri, Francesco, Jose Camacho-Collados, Luis Espinosa Anke, and Leonardo Neves.
    "TweetEval: Unified Benchmark and Comparative Evaluation for Tweet Classification."
    Findings of the Association for Computational Linguistics: EMNLP 2020 (2020): 1644–1650.

  • 🖼️ Gradio
    Used for building the interactive web interface.
    Docs: https://www.gradio.app/docs/

  • 🌐 Hugging Face Spaces
    Platform for deploying machine learning apps in the browser.
    Info: https://huggingface.co/spaces

  • 🌿 BeautifulSoup
    Used for extracting text from webpages.
    Library info: https://www.crummy.com/software/BeautifulSoup/

0
Subscribe to my newsletter

Read articles from Divya Vetriveeran directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Divya Vetriveeran
Divya Vetriveeran

I am currently serving as an Assistant Professor at CHRIST (Deemed to be University), Bangalore. With a Ph.D. in Information and Communication Engineering from Anna University and ongoing post-doctoral research at the Singapore Institute of Technology, her expertise lies in Ethical AI, Edge Computing, and innovative teaching methodologies. I have published extensively in reputed international journals and conferences, hold multiple patents, and actively contribute as a reviewer for leading journals, including IEEE and Springer. A UGC-NET qualified educator with a computer science background, I am committed to fostering impactful research and technological innovation for societal good.