Spaces:
Build error
Download code_explanation.md from balaji4991512/SentimentAnalyzer: direct link, hf CLI and curl.
- Browser
- Download file 4.31 kB
-
https://huggingface.co/spaces/balaji4991512/SentimentAnalyzer/resolve/main/code_explanation.md
- Command line
-
hf download hf://spaces/balaji4991512/SentimentAnalyzer/code_explanation.md
-
curl -L -o code_explanation.md https://huggingface.co/spaces/balaji4991512/SentimentAnalyzer/resolve/main/code_explanation.md
A newer version of the Gradio SDK is available: 6.31.0
π 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 pipelineimport gradio as grimport pandas as pdimport 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")