SentimentAnalyzer / code_explanation.md
balaji4991512's picture
Update code_explanation.md
03c4a47 verified
|
Raw History Blame Contribute Delete
4.31 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β€”now including the actual code inline so even a beginner can follow!


πŸ“ Overview

  • Purpose
    Classify text as Positive or Negative, one sentence at a time or in bulk via CSV/XLSX upload, and visualize the distribution in a pie chart.

  • Tech Stack

    • Model: A DistilBERT sentiment model fine-tuned on SST-2
    • UI: Gradio Blocks + Tabs
    • Data I/O: Pandas for CSV/XLSX
    • Visualization: Matplotlib pie chart

βš™οΈ Setup & Dependencies

Install the required libraries:
pip install transformers gradio pandas matplotlib torch


πŸ” Block-by-Block Explanation

1. Imports

Use the following imports at the top of your script:

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

2. Model Loading

Initialize the sentiment-analysis pipeline with DistilBERT fine-tuned on SST-2:

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

3. Single-Text Analysis

Define a function to predict sentiment on one string:

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

4. File-Upload Analysis

Define a function to read a CSV/XLSX, predict each row, and build a pie chart:

  • def analyze_file(file):
    • 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
    • if "Text" not in df.columns:
      • return "Missing 'Text' column", None
    • sentiments = [sentiment_analyzer(t)[0]['label'] for t in df["Text"].fillna("")]
    • df_result = pd.DataFrame({"Text": df["Text"], "Sentiment": sentiments})
    • counts = df_result["Sentiment"].value_counts()
    • 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

5. Gradio UI

Assemble the UI with two tabs:

  • with gr.Blocks() as demo:
    • gr.Markdown("## 🧠 Text Sentiment Analyzer")
    • gr.Markdown("Type text or upload a CSV/XLSX with a **Text** column.")
    • Single Text Tab
      • 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)
    • Upload File Tab
      • 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])

6. Launching the App

Call demo.launch() to start the local web interface.


πŸš€ Core Concepts

Concept Why It Matters
Hugging Face Pipeline Loads and runs a pre-trained model in one line
DataFrame I/O Bulk processing of CSV & Excel data
Matplotlib Pie Visual summary of classification breakdown
Gradio Blocks Build interactive web apps with pure Python

πŸ”„ Swapping Models & Extensions

  • Neutral Sentiment
    Use a three-label model:
    pipeline("sentiment-analysis", model="cardiffnlp/twitter-roberta-base-sentiment")

  • Multilingual Support
    Use a star-rating model:
    pipeline("sentiment-analysis", model="nlptown/bert-base-multilingual-uncased-sentiment")

  • Emotion Detection
    Choose an emotion-classification model:
    pipeline("sentiment-analysis", model="bhadresh-savani/bert-base-uncased-emotion")