File size: 5,133 Bytes
ef1bc39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162

# 📖 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")
```