SentimentAnalyzer / sample.md
balaji4991512's picture
Create sample.md
ef1bc39 verified
|
Raw History Blame Contribute Delete
5.13 kB

A newer version of the Gradio SDK is available: 6.31.0

Upgrade

πŸ“– Code Explanation: Text Sentiment Analyzer

This document walks you through the Text Sentiment Analyzer (with file upload & pie-chart) step by stepβ€”fully in Markdown, with detailed inline code explanations.


πŸ“ Overview

Purpose
Classify text as Positive or Negative, individually or in bulk via CSV/XLSX files, visualizing results in a pie chart.

Tech Stack

  • Model: DistilBERT fine-tuned on SST-2 dataset
  • UI: Gradio Blocks + Tabs
  • Data Handling: Pandas for CSV/XLSX operations
  • Visualization: Matplotlib for pie chart visualization

βš™οΈ Setup & Dependencies

Install the required libraries:

pip install transformers gradio pandas matplotlib torch

πŸ” Detailed Block-by-Block Code Explanation

1. Imports

from transformers import pipeline
import gradio as gr
import pandas as pd
import matplotlib.pyplot as plt

Detailed Explanation:

  • pipeline from Transformers: Loads and runs pre-trained NLP models easily.
  • gradio: Allows creation of web-based interfaces quickly from Python.
  • pandas: Reads CSV/Excel files into DataFrame objects and manages tabular data.
  • matplotlib: Enables visualization of data in graphical form.

2. Loading the Sentiment Analysis Model

sentiment_analyzer = pipeline("sentiment-analysis",
                              model="distilbert-base-uncased-finetuned-sst-2-english")

Detailed Explanation:

  • Initializes a pre-trained DistilBERT model fine-tuned specifically for sentiment analysis.
  • The chosen model can classify text into two sentiment categories: "POSITIVE" or "NEGATIVE".

3. Function for Single-Text Analysis

def analyze_sentiment(text):
    result = sentiment_analyzer(text)
    return result[0]['label']

Detailed Explanation:

  • Receives a single text input as parameter.
  • Passes the text to the loaded sentiment analyzer model.
  • Retrieves and returns only the sentiment label (Positive or Negative).

4. Function for Bulk Analysis via File Upload

def analyze_file(file):
    # Determine file format (CSV or Excel) and read into a DataFrame
    if file.name.endswith(".csv"):
        df = pd.read_csv(file.name)
    elif file.name.endswith(".xlsx"):
        df = pd.read_excel(file.name)
    else:
        return "Unsupported file format", None

    # Check if required 'Text' column exists in the uploaded file
    if "Text" not in df.columns:
        return "Missing 'Text' column", None

    # Apply sentiment analysis model to each text row
    sentiments = [sentiment_analyzer(t)[0]['label'] for t in df["Text"].fillna("")]
    
    # Create a results DataFrame with original texts and their sentiments
    df_result = pd.DataFrame({"Text": df["Text"], "Sentiment": sentiments})

    # Count sentiment occurrences (Positive/Negative)
    counts = df_result["Sentiment"].value_counts()
    
    # Generate a pie chart to visualize sentiment distribution
    fig, ax = plt.subplots()
    ax.pie(counts.values, labels=counts.index, autopct="%1.1f%%",
           colors=["#66bb6a", "#ef5350"][:len(counts)])
    ax.set_title("Sentiment Distribution")

    return df_result, fig

Detailed Explanation:

  • Loads data from CSV or Excel based on file extension.
  • Checks for existence of the necessary column (Text).
  • Predicts sentiment for each entry and compiles results into a table.
  • Visualizes sentiment results with a pie chart for intuitive interpretation.

5. Building the Gradio Web UI

with gr.Blocks() as demo:
    gr.Markdown("## 🧠 Text Sentiment Analyzer")
    gr.Markdown("Type text or upload a CSV/XLSX with a **Text** column.")

    # Tab for analyzing single text entries
    with gr.Tab("πŸ”€ Single Text"):
        txt = gr.Textbox(label="Enter text", lines=4)
        out = gr.Textbox(label="Sentiment")
        btn = gr.Button("Analyze")
        btn.click(analyze_sentiment, inputs=txt, outputs=out)

    # Tab for bulk file upload and analysis
    with gr.Tab("πŸ“ Upload File"):
        file_in = gr.File(label="Upload CSV or Excel")
        table_out = gr.Dataframe(label="Results")
        chart_out = gr.Plot(label="Pie Chart")
        btn2 = gr.Button("Analyze File")
        btn2.click(analyze_file, inputs=file_in, outputs=[table_out, chart_out])

# Launch the web application
demo.launch()

Detailed Explanation:

  • Constructs a user-friendly interface with Gradio Blocks.
  • Provides two distinct tabs for different analysis modes: single text and bulk upload.
  • Links buttons to their corresponding analysis functions, clearly defining input and output elements.

πŸ”„ Model Swaps and Further Enhancements

  • Neutral Sentiment (3-class sentiment analysis):
pipeline("sentiment-analysis", model="cardiffnlp/twitter-roberta-base-sentiment")
  • Multilingual Support (1-5 Star Ratings):
pipeline("sentiment-analysis", model="nlptown/bert-base-multilingual-uncased-sentiment")
  • Emotion Detection (Classifying emotions):
pipeline("sentiment-analysis", model="bhadresh-savani/bert-base-uncased-emotion")