File size: 4,307 Bytes
910438e
9efdc24
910438e
9efdc24
910438e
9efdc24
910438e
c2ffb3d
910438e
 
c2ffb3d
910438e
 
 
 
 
9efdc24
910438e
9efdc24
910438e
c2ffb3d
910438e
 
9efdc24
910438e
9efdc24
910438e
9efdc24
910438e
 
 
 
 
 
9efdc24
910438e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# πŸ“– 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")`