DivYonko commited on
Commit ·
a4612d4
1
Parent(s): 11a0fc5
deploy LivePulse to HF Spaces
Browse files- .gitattributes +4 -0
- .gitignore +2 -2
- Dockerfile +10 -0
- README.md +33 -0
- app.py +1485 -0
- backend/config.py +1 -1
- backend/main.py +1 -1
- backend/scraper.py +43 -56
- frontend/streamlit_app.py +901 -79
- ml/topic_model.py +9 -1
- new_trained_data/muril-sentimix/config.json +40 -0
- new_trained_data/muril-sentimix/model.safetensors +3 -0
- new_trained_data/muril-sentimix/tokenizer.json +0 -0
- new_trained_data/muril-sentimix/tokenizer_config.json +15 -0
- new_trained_data/muril-sentimix/training_args.bin +3 -0
- requirements.txt +7 -22
.gitattributes
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
.gitignore
CHANGED
|
@@ -7,8 +7,8 @@ __pycache__/
|
|
| 7 |
venv/
|
| 8 |
env/
|
| 9 |
|
| 10 |
-
# ML model weights
|
| 11 |
-
new_trained_data/
|
| 12 |
|
| 13 |
# Redis data
|
| 14 |
*.rdb
|
|
|
|
| 7 |
venv/
|
| 8 |
env/
|
| 9 |
|
| 10 |
+
# ML model weights tracked via Git LFS (see .gitattributes)
|
| 11 |
+
# new_trained_data/
|
| 12 |
|
| 13 |
# Redis data
|
| 14 |
*.rdb
|
Dockerfile
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
COPY requirements.txt .
|
| 5 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 6 |
+
|
| 7 |
+
COPY . .
|
| 8 |
+
|
| 9 |
+
EXPOSE 7860
|
| 10 |
+
CMD ["streamlit", "run", "app.py", "--server.port", "7860", "--server.address", "0.0.0.0"]
|
README.md
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: LivePulse
|
| 3 |
+
emoji: 📡
|
| 4 |
+
colorFrom: purple
|
| 5 |
+
colorTo: indigo
|
| 6 |
+
sdk: streamlit
|
| 7 |
+
sdk_version: "1.35.0"
|
| 8 |
+
app_file: app.py
|
| 9 |
+
pinned: false
|
| 10 |
+
---
|
| 11 |
+
|
| 12 |
+
# 📡 LivePulse — YouTube Live Chat Analytics
|
| 13 |
+
|
| 14 |
+
Real-time Hinglish sentiment and topic analysis for YouTube live streams.
|
| 15 |
+
|
| 16 |
+
## Features
|
| 17 |
+
|
| 18 |
+
- Real-time chat scraping via pytchat
|
| 19 |
+
- Sentiment classification (Positive / Neutral / Negative) using a 3-model ensemble
|
| 20 |
+
- Fine-tuned MuRIL (Hinglish-aware)
|
| 21 |
+
- XLM-RoBERTa (multilingual Twitter model)
|
| 22 |
+
- Multilingual sentiment model
|
| 23 |
+
- Topic classification (Appreciation / Question / Promo / Spam / MCQ Answer / General)
|
| 24 |
+
- Interactive Streamlit dashboard with live auto-refresh
|
| 25 |
+
- Start/stop scraper directly from the UI
|
| 26 |
+
- Multi-stream comparison (up to 5 streams)
|
| 27 |
+
- Engagement score, word cloud, leaderboard, sentiment heatmap
|
| 28 |
+
|
| 29 |
+
## Usage
|
| 30 |
+
|
| 31 |
+
1. Paste a YouTube live video ID or URL in the **Stream Control** section in the sidebar
|
| 32 |
+
2. Click **▶ Start** — the scraper launches in the background
|
| 33 |
+
3. The dashboard auto-refreshes and shows live sentiment + topic data
|
app.py
ADDED
|
@@ -0,0 +1,1485 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""
|
| 3 |
+
app.py — Hugging Face Spaces adaptation of frontend/streamlit_app.py
|
| 4 |
+
All features identical; infrastructure layer uses in-memory deque store
|
| 5 |
+
and threading instead of Redis + subprocess.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import streamlit as st
|
| 9 |
+
import json
|
| 10 |
+
import pandas as pd
|
| 11 |
+
import plotly.graph_objects as go
|
| 12 |
+
import plotly.express as px
|
| 13 |
+
import time
|
| 14 |
+
import re
|
| 15 |
+
import os
|
| 16 |
+
import threading
|
| 17 |
+
import logging
|
| 18 |
+
from collections import deque, defaultdict
|
| 19 |
+
from datetime import datetime, timedelta
|
| 20 |
+
|
| 21 |
+
# ── In-memory store (replaces Redis) ─────────────────────────────────────────
|
| 22 |
+
MAX_STORE_MESSAGES = 10000
|
| 23 |
+
|
| 24 |
+
_STORE_LOCK: threading.Lock = threading.Lock()
|
| 25 |
+
_STORE: dict[str, deque] = {} # keyed by redis_key string
|
| 26 |
+
_META: dict[str, str] = {} # misc key-value (e.g. "video_title")
|
| 27 |
+
|
| 28 |
+
# Scraper thread registry
|
| 29 |
+
_SCRAPER_THREADS: dict[str, threading.Thread] = {}
|
| 30 |
+
_SCRAPER_STOP: dict[str, threading.Event] = {}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _get_deque(key: str) -> deque:
|
| 34 |
+
"""Return (creating if needed) the deque for a given key."""
|
| 35 |
+
if key not in _STORE:
|
| 36 |
+
_STORE[key] = deque(maxlen=MAX_STORE_MESSAGES)
|
| 37 |
+
return _STORE[key]
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
# Redis-compatible helpers
|
| 41 |
+
def store_lrange(key: str, start: int, end: int) -> list[str]:
|
| 42 |
+
"""Emulate r.lrange(key, start, end)."""
|
| 43 |
+
with _STORE_LOCK:
|
| 44 |
+
d = list(_get_deque(key))
|
| 45 |
+
n = len(d)
|
| 46 |
+
if n == 0:
|
| 47 |
+
return []
|
| 48 |
+
# Normalise negative indices
|
| 49 |
+
if start < 0:
|
| 50 |
+
start = max(n + start, 0)
|
| 51 |
+
if end < 0:
|
| 52 |
+
end = n + end
|
| 53 |
+
end = min(end, n - 1)
|
| 54 |
+
if start > end:
|
| 55 |
+
return []
|
| 56 |
+
return d[start : end + 1]
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def store_llen(key: str) -> int:
|
| 60 |
+
with _STORE_LOCK:
|
| 61 |
+
return len(_get_deque(key))
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def store_delete(key: str) -> None:
|
| 65 |
+
with _STORE_LOCK:
|
| 66 |
+
if key in _STORE:
|
| 67 |
+
_STORE[key].clear()
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def store_rpush(key: str, value: str) -> None:
|
| 71 |
+
with _STORE_LOCK:
|
| 72 |
+
_get_deque(key).append(value)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
# ── Inline config (replaces backend/config.py) ────────────────────────────────
|
| 76 |
+
VIDEO_ID = os.getenv("VIDEO_ID", "")
|
| 77 |
+
|
| 78 |
+
# ── ML imports (ml/ is at workspace root) ────────────────────────────────────
|
| 79 |
+
from ml.sentiment_model import predict_sentiment
|
| 80 |
+
from ml.topic_model import predict_topic, VALID_TOPICS
|
| 81 |
+
|
| 82 |
+
# ── Scraper thread logic (mirrors backend/scraper.py run()) ──────────────────
|
| 83 |
+
logger = logging.getLogger("app.scraper")
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def _safe_sentiment(text: str):
|
| 87 |
+
try:
|
| 88 |
+
return predict_sentiment(text)
|
| 89 |
+
except Exception as exc:
|
| 90 |
+
logger.error("predict_sentiment failed: %s", exc)
|
| 91 |
+
return "Neutral", 0.50
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def _safe_topic(text: str):
|
| 95 |
+
try:
|
| 96 |
+
topic, conf = predict_topic(text)
|
| 97 |
+
if topic not in VALID_TOPICS:
|
| 98 |
+
return "General", 0.50
|
| 99 |
+
return topic, conf
|
| 100 |
+
except Exception as exc:
|
| 101 |
+
logger.error("predict_topic failed: %s", exc)
|
| 102 |
+
return "General", 0.50
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def _scraper_thread_fn(video_id: str, redis_key: str, stop_event: threading.Event) -> None:
|
| 106 |
+
"""Background thread that scrapes live chat and writes to in-memory store."""
|
| 107 |
+
import pytchat
|
| 108 |
+
|
| 109 |
+
logger.info("Scraper thread starting — video=%s key=%s", video_id, redis_key)
|
| 110 |
+
try:
|
| 111 |
+
chat = pytchat.create(video_id=video_id)
|
| 112 |
+
except Exception as exc:
|
| 113 |
+
logger.error("pytchat.create failed: %s", exc)
|
| 114 |
+
return
|
| 115 |
+
|
| 116 |
+
if not chat.is_alive():
|
| 117 |
+
logger.error("Live chat not available for %s", video_id)
|
| 118 |
+
return
|
| 119 |
+
|
| 120 |
+
logger.info("Live chat connected for %s", video_id)
|
| 121 |
+
|
| 122 |
+
while chat.is_alive() and not stop_event.is_set():
|
| 123 |
+
try:
|
| 124 |
+
for c in chat.get().sync_items():
|
| 125 |
+
if stop_event.is_set():
|
| 126 |
+
break
|
| 127 |
+
text = c.message.strip()
|
| 128 |
+
author = c.author.name
|
| 129 |
+
if not text:
|
| 130 |
+
continue
|
| 131 |
+
|
| 132 |
+
sentiment, s_conf = _safe_sentiment(text)
|
| 133 |
+
topic, t_conf = _safe_topic(text)
|
| 134 |
+
|
| 135 |
+
message_data = {
|
| 136 |
+
"author": author,
|
| 137 |
+
"text": text,
|
| 138 |
+
"sentiment": sentiment,
|
| 139 |
+
"confidence": round(s_conf, 3),
|
| 140 |
+
"topic": topic,
|
| 141 |
+
"topic_conf": round(t_conf, 3),
|
| 142 |
+
"time": datetime.now().isoformat(),
|
| 143 |
+
}
|
| 144 |
+
store_rpush(redis_key, json.dumps(message_data))
|
| 145 |
+
|
| 146 |
+
except Exception as exc:
|
| 147 |
+
if not stop_event.is_set():
|
| 148 |
+
logger.error("Scraper error: %s", exc, exc_info=True)
|
| 149 |
+
|
| 150 |
+
if not stop_event.is_set():
|
| 151 |
+
time.sleep(1)
|
| 152 |
+
|
| 153 |
+
logger.info("Scraper thread ended — key=%s", redis_key)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def start_scraper(slot_idx: int, video_id: str, redis_key: str) -> None:
|
| 157 |
+
"""Start a scraper thread for the given slot, stopping any existing one first."""
|
| 158 |
+
key = str(slot_idx)
|
| 159 |
+
stop_scraper(slot_idx)
|
| 160 |
+
|
| 161 |
+
stop_event = threading.Event()
|
| 162 |
+
t = threading.Thread(
|
| 163 |
+
target=_scraper_thread_fn,
|
| 164 |
+
args=(video_id, redis_key, stop_event),
|
| 165 |
+
daemon=True,
|
| 166 |
+
name=f"scraper-{slot_idx}",
|
| 167 |
+
)
|
| 168 |
+
_SCRAPER_STOP[key] = stop_event
|
| 169 |
+
_SCRAPER_THREADS[key] = t
|
| 170 |
+
t.start()
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def stop_scraper(slot_idx: int) -> None:
|
| 174 |
+
"""Signal the scraper thread for this slot to stop."""
|
| 175 |
+
key = str(slot_idx)
|
| 176 |
+
ev = _SCRAPER_STOP.get(key)
|
| 177 |
+
if ev:
|
| 178 |
+
ev.set()
|
| 179 |
+
# Don't join — daemon thread will die on its own
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def is_scraper_running(slot_idx: int) -> bool:
|
| 183 |
+
key = str(slot_idx)
|
| 184 |
+
t = _SCRAPER_THREADS.get(key)
|
| 185 |
+
return t is not None and t.is_alive()
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
# ── Streamlit page config ─────────────────────────────────────────────────────
|
| 189 |
+
st.set_page_config(
|
| 190 |
+
page_title="LivePulse",
|
| 191 |
+
layout="wide",
|
| 192 |
+
page_icon="📡",
|
| 193 |
+
initial_sidebar_state="expanded"
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
TOPIC_LABELS = ["Appreciation", "Question", "Promo", "Spam", "General", "MCQ Answer"]
|
| 197 |
+
TOPIC_COLOR = {
|
| 198 |
+
"Appreciation": "#f59e0b", "Question": "#3b82f6",
|
| 199 |
+
"Promo": "#ec4899", "Spam": "#ef4444", "General": "#6b7280",
|
| 200 |
+
"MCQ Answer": "#10b981"
|
| 201 |
+
}
|
| 202 |
+
SENT_COLORS = {"Positive": "#22c55e", "Neutral": "#eab308", "Negative": "#ef4444"}
|
| 203 |
+
|
| 204 |
+
# ── JS: detect Streamlit's live theme and set data-livepulse attribute ──
|
| 205 |
+
THEME_JS = """<script>
|
| 206 |
+
(function() {
|
| 207 |
+
function applyTheme() {
|
| 208 |
+
const html = window.parent.document.documentElement;
|
| 209 |
+
const style = window.parent.getComputedStyle(html);
|
| 210 |
+
const bg = style.getPropertyValue('--background-color').trim();
|
| 211 |
+
let isDark = true;
|
| 212 |
+
const m = bg.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);
|
| 213 |
+
if (m) { isDark = (0.299*m[1] + 0.587*m[2] + 0.114*m[3]) < 128; }
|
| 214 |
+
else {
|
| 215 |
+
const bodyBg = window.parent.getComputedStyle(window.parent.document.body).backgroundColor;
|
| 216 |
+
const m2 = bodyBg.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);
|
| 217 |
+
if (m2) { isDark = (0.299*m2[1] + 0.587*m2[2] + 0.114*m2[3]) < 128; }
|
| 218 |
+
}
|
| 219 |
+
html.setAttribute('data-livepulse', isDark ? 'dark' : 'light');
|
| 220 |
+
}
|
| 221 |
+
applyTheme();
|
| 222 |
+
const obs = new MutationObserver(applyTheme);
|
| 223 |
+
obs.observe(window.parent.document.documentElement, { attributes: true, attributeFilter: ['style','class'] });
|
| 224 |
+
obs.observe(window.parent.document.body, { attributes: true, attributeFilter: ['style','class'] });
|
| 225 |
+
})();
|
| 226 |
+
</script>"""
|
| 227 |
+
|
| 228 |
+
CSS = """<style>
|
| 229 |
+
@import url('https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700;800&display=swap');
|
| 230 |
+
|
| 231 |
+
:root, [data-livepulse="dark"] {
|
| 232 |
+
--bg:#07070f; --bg-card:#0f0f1e; --border:rgba(255,255,255,0.07);
|
| 233 |
+
--text-1:#f1f5f9; --text-2:#94a3b8; --text-3:#475569;
|
| 234 |
+
--accent:#7c3aed; --accent2:#4f46e5; --accent-text:#a78bfa;
|
| 235 |
+
--live:#22c55e; --input-bg:rgba(255,255,255,0.04); --input-border:rgba(255,255,255,0.1);
|
| 236 |
+
--divider:rgba(255,255,255,0.06); --badge-bg:rgba(255,255,255,0.05);
|
| 237 |
+
--shadow:0 4px 24px rgba(0,0,0,0.4); --shadow-sm:0 2px 8px rgba(0,0,0,0.3);
|
| 238 |
+
--pill-bg:rgba(124,58,237,0.15); --pill-border:rgba(124,58,237,0.3); --pill-text:#a78bfa;
|
| 239 |
+
--plotly-paper:rgba(0,0,0,0); --plotly-plot:rgba(255,255,255,0.015); --plotly-grid:rgba(255,255,255,0.05); --plotly-text:#94a3b8;
|
| 240 |
+
--alert-bg:rgba(239,68,68,0.1); --alert-border:rgba(239,68,68,0.3);
|
| 241 |
+
--pin-bg:rgba(234,179,8,0.1); --pin-border:rgba(234,179,8,0.35);
|
| 242 |
+
}
|
| 243 |
+
[data-livepulse="light"] {
|
| 244 |
+
--bg:#f4f6ff; --bg-card:#ffffff; --border:rgba(99,102,241,0.12);
|
| 245 |
+
--text-1:#0f172a; --text-2:#475569; --text-3:#94a3b8;
|
| 246 |
+
--accent:#6d28d9; --accent2:#4338ca; --accent-text:#6d28d9;
|
| 247 |
+
--live:#16a34a; --input-bg:#ffffff; --input-border:rgba(99,102,241,0.2);
|
| 248 |
+
--divider:rgba(99,102,241,0.1); --badge-bg:rgba(99,102,241,0.06);
|
| 249 |
+
--shadow:0 4px 24px rgba(99,102,241,0.12); --shadow-sm:0 2px 8px rgba(99,102,241,0.08);
|
| 250 |
+
--pill-bg:rgba(109,40,217,0.08); --pill-border:rgba(109,40,217,0.2); --pill-text:#6d28d9;
|
| 251 |
+
--plotly-paper:rgba(0,0,0,0); --plotly-plot:rgba(255,255,255,0.7); --plotly-grid:rgba(0,0,0,0.06); --plotly-text:#475569;
|
| 252 |
+
--alert-bg:rgba(239,68,68,0.07); --alert-border:rgba(239,68,68,0.25);
|
| 253 |
+
--pin-bg:rgba(234,179,8,0.08); --pin-border:rgba(234,179,8,0.3);
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
html,body,[data-testid="stAppViewContainer"],[data-testid="stMain"],.main .block-container {
|
| 257 |
+
background:var(--bg)!important; color:var(--text-1)!important;
|
| 258 |
+
font-family:'Space Grotesk',sans-serif!important; transition:background 0.3s,color 0.3s;
|
| 259 |
+
}
|
| 260 |
+
[data-testid="stSidebar"] { background:var(--bg-card)!important; border-right:1px solid var(--border)!important; transition:background 0.3s; }
|
| 261 |
+
[data-testid="stHeader"] { background:transparent!important; }
|
| 262 |
+
::-webkit-scrollbar{width:4px;} ::-webkit-scrollbar-track{background:var(--bg);}
|
| 263 |
+
::-webkit-scrollbar-thumb{background:linear-gradient(var(--accent),var(--accent2));border-radius:4px;}
|
| 264 |
+
|
| 265 |
+
[data-testid="metric-container"] {
|
| 266 |
+
background:var(--bg-card)!important; border:1px solid var(--border)!important;
|
| 267 |
+
border-radius:16px!important; padding:18px!important; box-shadow:var(--shadow-sm)!important; transition:background 0.3s;
|
| 268 |
+
}
|
| 269 |
+
[data-testid="stMetricLabel"]{color:var(--text-2)!important;font-size:0.8rem!important;}
|
| 270 |
+
[data-testid="stMetricValue"]{color:var(--text-1)!important;font-weight:700!important;}
|
| 271 |
+
[data-testid="stMetricDelta"]{color:var(--accent-text)!important;}
|
| 272 |
+
|
| 273 |
+
.stTextInput input { background:var(--input-bg)!important; border:1px solid var(--input-border)!important; border-radius:10px!important; color:var(--text-1)!important; }
|
| 274 |
+
.stTextInput input::placeholder { color:var(--text-3)!important; opacity:1!important; }
|
| 275 |
+
[data-testid="stSidebar"] .stTextInput input { background:#1a1a2e!important; border:1px solid rgba(124,58,237,0.4)!important; color:#f1f5f9!important; font-weight:500!important; }
|
| 276 |
+
[data-testid="stSidebar"] .stTextInput input::placeholder { color:#64748b!important; }
|
| 277 |
+
[data-testid="stSidebar"] .stTextInput input:focus { border-color:var(--accent)!important; box-shadow:0 0 0 2px rgba(124,58,237,0.2)!important; outline:none!important; }
|
| 278 |
+
[data-testid="stSidebar"] label { color:var(--text-2)!important; }
|
| 279 |
+
[data-baseweb="select"]>div { background:var(--input-bg)!important; border:1px solid var(--input-border)!important; border-radius:10px!important; color:var(--text-1)!important; }
|
| 280 |
+
.stButton>button { background:linear-gradient(135deg,var(--accent),var(--accent2))!important; color:#fff!important; border:none!important; border-radius:10px!important; font-weight:600!important; font-family:'Space Grotesk',sans-serif!important; box-shadow:0 4px 16px rgba(124,58,237,0.3)!important; transition:all 0.2s!important; }
|
| 281 |
+
.stButton>button:hover{transform:translateY(-2px)!important;}
|
| 282 |
+
hr{border:none!important;border-top:1px solid var(--divider)!important;margin:1.2rem 0!important;}
|
| 283 |
+
[data-testid="stSidebar"] label,[data-testid="stSidebar"] .stMarkdown p{color:var(--text-2)!important;font-size:0.83rem!important;}
|
| 284 |
+
|
| 285 |
+
[data-testid="stDownloadButton"]>button { background:var(--bg-card)!important; color:var(--text-2)!important; border:1px solid var(--border)!important; border-radius:8px!important; font-size:0.75rem!important; box-shadow:none!important; }
|
| 286 |
+
[data-testid="stDownloadButton"]>button:hover { background:var(--pill-bg)!important; color:var(--accent-text)!important; border-color:var(--pill-border)!important; }
|
| 287 |
+
|
| 288 |
+
[data-testid="stCheckbox"] label, [data-testid="stCheckbox"] span { color:var(--text-2)!important; font-size:0.82rem!important; }
|
| 289 |
+
[data-testid="stCheckbox"] [data-testid="stWidgetLabel"] { color:var(--text-2)!important; }
|
| 290 |
+
|
| 291 |
+
@keyframes pulse{0%{box-shadow:0 0 0 0 rgba(34,197,94,0.7);}70%{box-shadow:0 0 0 10px rgba(34,197,94,0);}100%{box-shadow:0 0 0 0 rgba(34,197,94,0);}}
|
| 292 |
+
.live-dot{display:inline-block;width:9px;height:9px;background:var(--live);border-radius:50%;animation:pulse 1.8s infinite;margin-right:6px;vertical-align:middle;}
|
| 293 |
+
|
| 294 |
+
@keyframes alertPulse{0%{opacity:1;}50%{opacity:0.7;}100%{opacity:1;}}
|
| 295 |
+
.alert-banner{background:var(--alert-bg);border:1px solid var(--alert-border);border-radius:14px;padding:14px 18px;margin:12px 0;display:flex;align-items:center;gap:12px;animation:alertPulse 2s infinite;}
|
| 296 |
+
.alert-icon{font-size:1.4rem;}
|
| 297 |
+
.alert-text{font-size:0.88rem;font-weight:600;color:#ef4444;}
|
| 298 |
+
.alert-sub{font-size:0.75rem;color:var(--text-3);margin-top:2px;}
|
| 299 |
+
|
| 300 |
+
.stat-grid{display:flex;gap:12px;margin:10px 0 18px;flex-wrap:wrap;}
|
| 301 |
+
.stat-card{flex:1;min-width:130px;background:var(--bg-card);border:1px solid var(--border);border-radius:20px;padding:22px 18px;text-align:center;transition:transform 0.2s,box-shadow 0.2s,background 0.3s;position:relative;overflow:hidden;box-shadow:var(--shadow-sm);}
|
| 302 |
+
.stat-card:hover{transform:translateY(-4px);box-shadow:var(--shadow);}
|
| 303 |
+
.stat-accent{position:absolute;top:0;left:0;right:0;height:3px;border-radius:20px 20px 0 0;}
|
| 304 |
+
.stat-number{font-size:2.6rem;font-weight:800;line-height:1;margin-bottom:6px;letter-spacing:-0.03em;}
|
| 305 |
+
.stat-label{font-size:0.82rem;color:var(--text-2);font-weight:600;text-transform:uppercase;letter-spacing:0.06em;}
|
| 306 |
+
.stat-sub{font-size:0.7rem;color:var(--text-3);margin-top:4px;}
|
| 307 |
+
|
| 308 |
+
.velocity-card{background:var(--bg-card);border:1px solid var(--border);border-radius:20px;padding:18px 22px;box-shadow:var(--shadow-sm);display:flex;align-items:center;gap:16px;}
|
| 309 |
+
.velocity-arrow{font-size:2rem;line-height:1;}
|
| 310 |
+
.velocity-val{font-size:1.6rem;font-weight:800;letter-spacing:-0.03em;}
|
| 311 |
+
.velocity-label{font-size:0.75rem;color:var(--text-3);font-weight:600;text-transform:uppercase;letter-spacing:0.06em;margin-top:2px;}
|
| 312 |
+
|
| 313 |
+
.sec-hdr{display:flex;align-items:center;gap:10px;margin:6px 0 14px;}
|
| 314 |
+
.sec-ttl{font-size:1rem;font-weight:700;color:var(--text-1);letter-spacing:-0.01em;}
|
| 315 |
+
.sec-pill{background:var(--pill-bg);border:1px solid var(--pill-border);border-radius:20px;padding:2px 10px;font-size:0.68rem;color:var(--pill-text);font-weight:700;text-transform:uppercase;letter-spacing:0.08em;}
|
| 316 |
+
|
| 317 |
+
.chart-wrap{background:var(--bg-card);border:1px solid var(--border);border-radius:20px;padding:14px 14px 6px;box-shadow:var(--shadow-sm);transition:background 0.3s,border 0.3s;}
|
| 318 |
+
.chart-title{font-size:0.88rem;font-weight:700;color:var(--text-1);margin-bottom:2px;}
|
| 319 |
+
.chart-sub{font-size:0.72rem;color:var(--text-3);margin-bottom:10px;}
|
| 320 |
+
|
| 321 |
+
.topic-grid{display:flex;gap:10px;flex-wrap:wrap;margin-bottom:18px;}
|
| 322 |
+
.topic-pill{background:var(--bg-card);border-radius:16px;padding:14px 20px;text-align:center;min-width:110px;box-shadow:var(--shadow-sm);transition:transform 0.2s,box-shadow 0.2s;}
|
| 323 |
+
.topic-pill:hover{transform:translateY(-3px);box-shadow:var(--shadow);}
|
| 324 |
+
.topic-count{font-size:1.4rem;font-weight:800;letter-spacing:-0.02em;}
|
| 325 |
+
.topic-name{font-size:0.7rem;color:var(--text-3);margin-top:3px;font-weight:600;text-transform:uppercase;letter-spacing:0.06em;}
|
| 326 |
+
|
| 327 |
+
@keyframes slideIn{from{opacity:0;transform:translateY(6px);}to{opacity:1;transform:translateY(0);}}
|
| 328 |
+
.chat-card{background:var(--bg-card);border:1px solid var(--border);border-radius:16px;padding:14px 16px;margin-bottom:10px;border-left:3px solid transparent;animation:slideIn 0.2s ease;transition:background 0.2s,transform 0.15s,box-shadow 0.2s;box-shadow:var(--shadow-sm);}
|
| 329 |
+
.chat-card:hover{transform:translateX(4px);box-shadow:var(--shadow);}
|
| 330 |
+
.chat-positive{border-left-color:#22c55e;} .chat-negative{border-left-color:#ef4444;} .chat-neutral{border-left-color:#eab308;}
|
| 331 |
+
.chat-pinned{border-left-color:#eab308!important;background:var(--pin-bg)!important;border-color:var(--pin-border)!important;}
|
| 332 |
+
.chat-author{font-weight:700;font-size:0.83rem;color:var(--accent-text);margin-bottom:5px;}
|
| 333 |
+
.chat-text{font-size:0.92rem;color:var(--text-2);line-height:1.55;margin-bottom:9px;}
|
| 334 |
+
.chat-badges{display:flex;gap:6px;flex-wrap:wrap;}
|
| 335 |
+
.badge{display:inline-flex;align-items:center;background:var(--badge-bg);border:1px solid var(--border);border-radius:20px;padding:3px 10px;font-size:0.7rem;font-weight:600;color:var(--text-2);}
|
| 336 |
+
.pin-badge{background:rgba(234,179,8,0.15);border-color:rgba(234,179,8,0.4);color:#eab308;}
|
| 337 |
+
|
| 338 |
+
.compare-label{font-size:0.72rem;font-weight:700;text-transform:uppercase;letter-spacing:0.08em;padding:3px 10px;border-radius:20px;display:inline-block;margin-bottom:8px;}
|
| 339 |
+
|
| 340 |
+
.engage-card{background:var(--bg-card);border:1px solid var(--border);border-radius:20px;padding:20px 24px;box-shadow:var(--shadow-sm);position:relative;overflow:hidden;}
|
| 341 |
+
.engage-score{font-size:3rem;font-weight:800;letter-spacing:-0.04em;line-height:1;}
|
| 342 |
+
.engage-label{font-size:0.75rem;color:var(--text-3);font-weight:600;text-transform:uppercase;letter-spacing:0.08em;margin-top:4px;}
|
| 343 |
+
.engage-bar-bg{background:var(--border);border-radius:99px;height:6px;margin-top:12px;overflow:hidden;}
|
| 344 |
+
.engage-bar-fill{height:6px;border-radius:99px;transition:width 0.6s ease;}
|
| 345 |
+
.engage-breakdown{display:flex;gap:16px;margin-top:10px;flex-wrap:wrap;}
|
| 346 |
+
.engage-item{font-size:0.72rem;color:var(--text-3);}
|
| 347 |
+
.engage-item span{font-weight:700;color:var(--text-2);}
|
| 348 |
+
|
| 349 |
+
.leaderboard-row{display:flex;align-items:center;gap:12px;padding:10px 14px;background:var(--bg-card);border:1px solid var(--border);border-radius:14px;margin-bottom:8px;transition:transform 0.15s,box-shadow 0.15s;}
|
| 350 |
+
.leaderboard-row:hover{transform:translateX(4px);box-shadow:var(--shadow);}
|
| 351 |
+
.lb-rank{font-size:1rem;font-weight:800;color:var(--text-3);min-width:28px;}
|
| 352 |
+
.lb-rank.gold{color:#f59e0b;} .lb-rank.silver{color:#94a3b8;} .lb-rank.bronze{color:#b45309;}
|
| 353 |
+
.lb-author{font-size:0.85rem;font-weight:700;color:var(--text-1);flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
|
| 354 |
+
.lb-count{font-size:0.78rem;color:var(--text-3);min-width:40px;text-align:right;}
|
| 355 |
+
.lb-bar{flex:2;height:5px;background:var(--border);border-radius:99px;overflow:hidden;}
|
| 356 |
+
.lb-bar-fill{height:5px;border-radius:99px;}
|
| 357 |
+
.lb-sent{display:flex;gap:4px;min-width:80px;justify-content:flex-end;}
|
| 358 |
+
.lb-dot{width:8px;height:8px;border-radius:50%;display:inline-block;}
|
| 359 |
+
|
| 360 |
+
.spam-alert{background:rgba(239,68,68,0.08);border:1px solid rgba(239,68,68,0.25);border-radius:14px;padding:14px 18px;margin:12px 0;display:flex;align-items:center;gap:12px;}
|
| 361 |
+
.spam-alert-text{font-size:0.88rem;font-weight:600;color:#ef4444;}
|
| 362 |
+
.spam-alert-sub{font-size:0.75rem;color:var(--text-3);margin-top:2px;}
|
| 363 |
+
|
| 364 |
+
.empty-state{text-align:center;padding:80px 20px;background:var(--bg-card);border:1px solid var(--border);border-radius:24px;margin:40px 0;box-shadow:var(--shadow-sm);}
|
| 365 |
+
.empty-icon{font-size:3.5rem;margin-bottom:16px;}
|
| 366 |
+
.empty-title{font-size:1.1rem;color:var(--text-2);font-weight:700;}
|
| 367 |
+
.empty-sub{font-size:0.84rem;color:var(--text-3);margin-top:6px;}
|
| 368 |
+
</style>"""
|
| 369 |
+
|
| 370 |
+
st.markdown(THEME_JS, unsafe_allow_html=True)
|
| 371 |
+
st.markdown(CSS, unsafe_allow_html=True)
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
# ── HELPERS ──────────────────────────────────────────────────
|
| 375 |
+
def extract_video_id(url_or_id):
|
| 376 |
+
url_or_id = url_or_id.strip()
|
| 377 |
+
match = re.search(r"(?:v=|/live/|youtu\.be/)([A-Za-z0-9_-]{11})", url_or_id)
|
| 378 |
+
if match:
|
| 379 |
+
return match.group(1)
|
| 380 |
+
if re.match(r"^[A-Za-z0-9_-]{11}$", url_or_id):
|
| 381 |
+
return url_or_id
|
| 382 |
+
return url_or_id
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
def fetch_video_title(video_id):
|
| 386 |
+
try:
|
| 387 |
+
import urllib.request
|
| 388 |
+
url = f"https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v={video_id}&format=json"
|
| 389 |
+
with urllib.request.urlopen(url, timeout=5) as resp:
|
| 390 |
+
return json.loads(resp.read())["title"]
|
| 391 |
+
except Exception:
|
| 392 |
+
return None
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
def clean_topic(val):
|
| 396 |
+
if pd.isna(val) or str(val).strip() == "" or str(val).strip().lower() == "nan":
|
| 397 |
+
return "General"
|
| 398 |
+
return str(val).strip()
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
def clean_sentiment(val):
|
| 402 |
+
if str(val).strip() in ("Positive", "Negative", "Neutral"):
|
| 403 |
+
return str(val).strip()
|
| 404 |
+
return "Neutral"
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
def plotly_layout(height=280):
|
| 408 |
+
return dict(
|
| 409 |
+
paper_bgcolor="rgba(0,0,0,0)",
|
| 410 |
+
plot_bgcolor="rgba(0,0,0,0)",
|
| 411 |
+
height=height,
|
| 412 |
+
margin=dict(l=10, r=10, t=10, b=10),
|
| 413 |
+
font=dict(family="Space Grotesk"),
|
| 414 |
+
xaxis=dict(showgrid=False, zeroline=False, showline=False,
|
| 415 |
+
tickfont=dict(size=11), title=None),
|
| 416 |
+
yaxis=dict(showgrid=True, gridcolor="rgba(128,128,128,0.12)",
|
| 417 |
+
zeroline=False, showline=False, tickfont=dict(size=11), title=None),
|
| 418 |
+
showlegend=False,
|
| 419 |
+
hoverlabel=dict(font_family="Space Grotesk", font_size=12),
|
| 420 |
+
)
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
def csv_download(df_export, label, filename):
|
| 424 |
+
csv = df_export.to_csv(index=False).encode("utf-8")
|
| 425 |
+
st.download_button(label=f"⬇ {label}", data=csv,
|
| 426 |
+
file_name=filename, mime="text/csv", key=filename)
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
@st.cache_data(ttl=5, show_spinner=False)
|
| 430 |
+
def load_stream_data(redis_key: str, limit: int | None = None):
|
| 431 |
+
"""Load and parse messages from the in-memory store. Cached for 5s."""
|
| 432 |
+
if limit:
|
| 433 |
+
raws = store_lrange(redis_key, -limit, -1)
|
| 434 |
+
else:
|
| 435 |
+
raws = store_lrange(redis_key, 0, -1)
|
| 436 |
+
data = []
|
| 437 |
+
for raw in raws:
|
| 438 |
+
try:
|
| 439 |
+
data.append(json.loads(raw))
|
| 440 |
+
except Exception:
|
| 441 |
+
pass
|
| 442 |
+
return data
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
@st.cache_data(ttl=10, show_spinner=False)
|
| 446 |
+
def compute_velocity(df_all_json: str, window: int = 20) -> dict:
|
| 447 |
+
"""Compute sentiment velocity. Accepts JSON string for cache key compatibility."""
|
| 448 |
+
import json as _json
|
| 449 |
+
sentiments = [m.get("sentiment", "Neutral") for m in _json.loads(df_all_json)]
|
| 450 |
+
n = len(sentiments)
|
| 451 |
+
if n < window * 2:
|
| 452 |
+
return {"direction": "→", "delta": 0.0, "label": "Stable", "color": "#eab308"}
|
| 453 |
+
recent = sentiments[-window:]
|
| 454 |
+
prev = sentiments[-window*2:-window]
|
| 455 |
+
r_pos = sum(1 for s in recent if s == "Positive") / window
|
| 456 |
+
p_pos = sum(1 for s in prev if s == "Positive") / window
|
| 457 |
+
delta = r_pos - p_pos
|
| 458 |
+
if delta > 0.08:
|
| 459 |
+
return {"direction": "↑", "delta": delta, "label": "Rising", "color": "#22c55e"}
|
| 460 |
+
elif delta < -0.08:
|
| 461 |
+
return {"direction": "↓", "delta": delta, "label": "Falling", "color": "#ef4444"}
|
| 462 |
+
return {"direction": "→", "delta": delta, "label": "Stable", "color": "#eab308"}
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
@st.cache_data(ttl=10, show_spinner=False)
|
| 466 |
+
def build_heatmap_data(df_all_json: str, bucket_minutes: int = 1) -> pd.DataFrame:
|
| 467 |
+
"""Bucket messages into time intervals."""
|
| 468 |
+
import json as _json
|
| 469 |
+
records = _json.loads(df_all_json)
|
| 470 |
+
if not records:
|
| 471 |
+
return pd.DataFrame()
|
| 472 |
+
df_t = pd.DataFrame(records)
|
| 473 |
+
if "time" not in df_t.columns:
|
| 474 |
+
return pd.DataFrame()
|
| 475 |
+
df_t["time"] = pd.to_datetime(df_t["time"], errors="coerce")
|
| 476 |
+
df_t = df_t.dropna(subset=["time"])
|
| 477 |
+
if df_t.empty:
|
| 478 |
+
return pd.DataFrame()
|
| 479 |
+
df_t["bucket"] = df_t["time"].dt.floor(f"{bucket_minutes}min")
|
| 480 |
+
grouped = df_t.groupby(["bucket", "sentiment"]).size().unstack(fill_value=0)
|
| 481 |
+
for col in ["Positive", "Neutral", "Negative"]:
|
| 482 |
+
if col not in grouped.columns:
|
| 483 |
+
grouped[col] = 0
|
| 484 |
+
grouped = grouped.reset_index()
|
| 485 |
+
grouped.columns.name = None
|
| 486 |
+
return grouped[["bucket", "Positive", "Neutral", "Negative"]]
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
def check_alert(df_all: pd.DataFrame, threshold: float = 0.4, window: int = 15) -> dict | None:
|
| 490 |
+
"""Return alert info if negative ratio in last `window` messages exceeds threshold."""
|
| 491 |
+
if len(df_all) < window:
|
| 492 |
+
return None
|
| 493 |
+
recent = df_all.iloc[-window:]
|
| 494 |
+
neg_ratio = (recent["sentiment"] == "Negative").mean()
|
| 495 |
+
if neg_ratio >= threshold:
|
| 496 |
+
return {
|
| 497 |
+
"neg_ratio": neg_ratio,
|
| 498 |
+
"count": int((recent["sentiment"] == "Negative").sum()),
|
| 499 |
+
"window": window,
|
| 500 |
+
}
|
| 501 |
+
return None
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
@st.cache_data(ttl=10, show_spinner=False)
|
| 505 |
+
def compute_engagement(all_data_json: str, window: int = 50) -> dict:
|
| 506 |
+
"""Engagement score (0-100) = weighted combo of message rate, positive ratio, question density."""
|
| 507 |
+
import json as _j
|
| 508 |
+
msgs = _j.loads(all_data_json)
|
| 509 |
+
if not msgs:
|
| 510 |
+
return {"score": 0, "rate": 0.0, "pos_ratio": 0.0, "q_density": 0.0, "grade": "—"}
|
| 511 |
+
|
| 512 |
+
recent = msgs[-window:]
|
| 513 |
+
n = len(recent)
|
| 514 |
+
|
| 515 |
+
rate = 0.0
|
| 516 |
+
try:
|
| 517 |
+
t0 = datetime.fromisoformat(recent[0]["time"])
|
| 518 |
+
t1 = datetime.fromisoformat(recent[-1]["time"])
|
| 519 |
+
elapsed = max((t1 - t0).total_seconds() / 60, 0.1)
|
| 520 |
+
rate = round(n / elapsed, 1)
|
| 521 |
+
except Exception:
|
| 522 |
+
rate = float(n)
|
| 523 |
+
|
| 524 |
+
pos_ratio = sum(1 for m in recent if m.get("sentiment") == "Positive") / max(n, 1)
|
| 525 |
+
q_density = sum(1 for m in recent if m.get("topic") == "Question") / max(n, 1)
|
| 526 |
+
|
| 527 |
+
rate_norm = min(rate / 60, 1.0)
|
| 528 |
+
score = round((rate_norm * 0.4 + pos_ratio * 0.4 + q_density * 0.2) * 100)
|
| 529 |
+
|
| 530 |
+
if score >= 70: grade = "🔥 High"
|
| 531 |
+
elif score >= 40: grade = "⚡ Medium"
|
| 532 |
+
else: grade = "💤 Low"
|
| 533 |
+
|
| 534 |
+
return {"score": score, "rate": rate, "pos_ratio": pos_ratio, "q_density": q_density, "grade": grade}
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
@st.cache_data(ttl=10, show_spinner=False)
|
| 538 |
+
def compute_top_contributors(all_data_json: str, top_n: int = 10) -> list[dict]:
|
| 539 |
+
"""Return top N authors by message count with their sentiment breakdown."""
|
| 540 |
+
import json as _j
|
| 541 |
+
from collections import Counter
|
| 542 |
+
msgs = _j.loads(all_data_json)
|
| 543 |
+
if not msgs:
|
| 544 |
+
return []
|
| 545 |
+
|
| 546 |
+
author_data: dict[str, dict] = {}
|
| 547 |
+
for m in msgs:
|
| 548 |
+
a = m.get("author", "Unknown")
|
| 549 |
+
if a not in author_data:
|
| 550 |
+
author_data[a] = {"count": 0, "Positive": 0, "Neutral": 0, "Negative": 0}
|
| 551 |
+
author_data[a]["count"] += 1
|
| 552 |
+
s = m.get("sentiment", "Neutral")
|
| 553 |
+
if s in author_data[a]:
|
| 554 |
+
author_data[a][s] += 1
|
| 555 |
+
|
| 556 |
+
sorted_authors = sorted(author_data.items(), key=lambda x: x[1]["count"], reverse=True)[:top_n]
|
| 557 |
+
result = []
|
| 558 |
+
for author, d in sorted_authors:
|
| 559 |
+
total = max(d["count"], 1)
|
| 560 |
+
result.append({
|
| 561 |
+
"author": author,
|
| 562 |
+
"count": d["count"],
|
| 563 |
+
"pos_pct": round(d["Positive"] / total * 100),
|
| 564 |
+
"neu_pct": round(d["Neutral"] / total * 100),
|
| 565 |
+
"neg_pct": round(d["Negative"] / total * 100),
|
| 566 |
+
})
|
| 567 |
+
return result
|
| 568 |
+
|
| 569 |
+
|
| 570 |
+
@st.cache_data(ttl=10, show_spinner=False)
|
| 571 |
+
def compute_word_freq(all_data_json: str, sentiment_filter: str = "All",
|
| 572 |
+
topic_filter: str = "All", top_n: int = 60) -> list[tuple[str, int]]:
|
| 573 |
+
"""Return top N (word, count) pairs after filtering stopwords."""
|
| 574 |
+
import json as _j
|
| 575 |
+
from collections import Counter
|
| 576 |
+
|
| 577 |
+
STOPWORDS = {
|
| 578 |
+
"the","a","an","is","it","in","on","at","to","of","and","or","but","for",
|
| 579 |
+
"with","this","that","are","was","be","as","by","from","have","has","had",
|
| 580 |
+
"not","no","so","if","do","did","will","can","just","i","you","he","she",
|
| 581 |
+
"we","they","my","your","his","her","our","their","me","him","us","them",
|
| 582 |
+
"what","how","why","when","where","who","which","there","here","been",
|
| 583 |
+
"would","could","should","may","might","shall","than","then","now","also",
|
| 584 |
+
"more","very","too","up","out","about","into","over","after","before",
|
| 585 |
+
"yaar","bhi","hai","hain","ho","kar","ke","ki","ka","ko","se","ne","ye",
|
| 586 |
+
"vo","woh","aur","nahi","nhi","toh","toh","koi","kuch","ab","ek","hi",
|
| 587 |
+
}
|
| 588 |
+
|
| 589 |
+
msgs = _j.loads(all_data_json)
|
| 590 |
+
words: list[str] = []
|
| 591 |
+
for m in msgs:
|
| 592 |
+
if sentiment_filter != "All" and m.get("sentiment") != sentiment_filter:
|
| 593 |
+
continue
|
| 594 |
+
if topic_filter != "All" and m.get("topic") != topic_filter:
|
| 595 |
+
continue
|
| 596 |
+
text = re.sub(r"[^\w\s]", " ", m.get("text", "").lower())
|
| 597 |
+
for w in text.split():
|
| 598 |
+
if len(w) > 2 and w not in STOPWORDS and not w.isdigit():
|
| 599 |
+
words.append(w)
|
| 600 |
+
|
| 601 |
+
return Counter(words).most_common(top_n)
|
| 602 |
+
|
| 603 |
+
|
| 604 |
+
def check_spam_alert(df_all: pd.DataFrame, threshold: float = 0.3, window: int = 20) -> dict | None:
|
| 605 |
+
"""Return alert if spam ratio in last `window` messages exceeds threshold."""
|
| 606 |
+
if "topic" not in df_all.columns or len(df_all) < window:
|
| 607 |
+
return None
|
| 608 |
+
recent = df_all.iloc[-window:]
|
| 609 |
+
spam_ratio = (recent["topic"] == "Spam").mean()
|
| 610 |
+
if spam_ratio >= threshold:
|
| 611 |
+
return {
|
| 612 |
+
"spam_ratio": spam_ratio,
|
| 613 |
+
"count": int((recent["topic"] == "Spam").sum()),
|
| 614 |
+
"window": window,
|
| 615 |
+
}
|
| 616 |
+
return None
|
| 617 |
+
|
| 618 |
+
|
| 619 |
+
# ── SESSION STATE INIT ────────────────────────────────────────
|
| 620 |
+
MAX_STREAMS = 5
|
| 621 |
+
STREAM_COLORS = ["#7c3aed", "#10b981", "#f59e0b", "#3b82f6", "#ec4899"]
|
| 622 |
+
STREAM_NAMES = ["A", "B", "C", "D", "E"]
|
| 623 |
+
|
| 624 |
+
if "pinned_messages" not in st.session_state:
|
| 625 |
+
st.session_state.pinned_messages = []
|
| 626 |
+
if "alert_dismissed" not in st.session_state:
|
| 627 |
+
st.session_state.alert_dismissed = False
|
| 628 |
+
if "last_alert_count" not in st.session_state:
|
| 629 |
+
st.session_state.last_alert_count = 0
|
| 630 |
+
# Multi-stream: list of dicts {video_id, redis_key, label, proc}
|
| 631 |
+
# proc stores the Thread object (or None) for running-check compatibility
|
| 632 |
+
if "streams" not in st.session_state:
|
| 633 |
+
st.session_state.streams = [
|
| 634 |
+
{"video_id": VIDEO_ID, "redis_key": "chat_messages", "label": "Stream A", "proc": None}
|
| 635 |
+
]
|
| 636 |
+
|
| 637 |
+
# ── SIDEBAR ─────────────────────��────────────────────────────
|
| 638 |
+
with st.sidebar:
|
| 639 |
+
st.markdown(
|
| 640 |
+
'<div style="padding:12px 0 20px;">'
|
| 641 |
+
'<div style="font-size:1.35rem;font-weight:800;color:var(--text-1);letter-spacing:-0.02em;">📡 LivePulse</div>'
|
| 642 |
+
'<div style="font-size:0.75rem;color:var(--text-3);margin-top:2px;">YouTube Chat Analytics</div>'
|
| 643 |
+
'</div>', unsafe_allow_html=True
|
| 644 |
+
)
|
| 645 |
+
st.divider()
|
| 646 |
+
|
| 647 |
+
# ── Display Settings ──
|
| 648 |
+
st.markdown('<p style="font-size:0.68rem;font-weight:700;color:var(--accent);text-transform:uppercase;letter-spacing:0.1em;margin-bottom:8px;">Display Settings</p>', unsafe_allow_html=True)
|
| 649 |
+
refresh_rate = st.slider("Refresh interval (s)", 5, 60, 15)
|
| 650 |
+
msg_limit = st.slider("Message window", 10, 200, 50)
|
| 651 |
+
auto_refresh = st.toggle("Live auto-refresh", value=True)
|
| 652 |
+
st.divider()
|
| 653 |
+
|
| 654 |
+
# ── Alert Settings ──
|
| 655 |
+
st.markdown('<p style="font-size:0.68rem;font-weight:700;color:var(--accent);text-transform:uppercase;letter-spacing:0.1em;margin-bottom:8px;">Alert Settings</p>', unsafe_allow_html=True)
|
| 656 |
+
alert_enabled = st.toggle("Negative spike alerts", value=True)
|
| 657 |
+
alert_threshold = st.slider("Neg alert threshold (%)", 20, 80, 40) / 100
|
| 658 |
+
alert_window = st.slider("Alert window (msgs)", 5, 30, 15)
|
| 659 |
+
spam_alert_on = st.toggle("Spam rate alerts", value=True)
|
| 660 |
+
spam_threshold = st.slider("Spam alert threshold (%)", 10, 60, 30) / 100
|
| 661 |
+
st.divider()
|
| 662 |
+
|
| 663 |
+
# ── Multi-Stream Scraper Control ──
|
| 664 |
+
st.markdown('<p style="font-size:0.68rem;font-weight:700;color:var(--accent);text-transform:uppercase;letter-spacing:0.1em;margin-bottom:8px;">Stream Control</p>', unsafe_allow_html=True)
|
| 665 |
+
|
| 666 |
+
for idx, stream in enumerate(st.session_state.streams):
|
| 667 |
+
color = STREAM_COLORS[idx]
|
| 668 |
+
label = STREAM_NAMES[idx]
|
| 669 |
+
st.markdown(
|
| 670 |
+
f'<div style="font-size:0.72rem;font-weight:700;color:{color};text-transform:uppercase;'
|
| 671 |
+
f'letter-spacing:0.08em;margin:10px 0 4px;border-left:3px solid {color};padding-left:8px;">'
|
| 672 |
+
f'Stream {label}</div>',
|
| 673 |
+
unsafe_allow_html=True
|
| 674 |
+
)
|
| 675 |
+
vid_skey = f"vid_{idx}"
|
| 676 |
+
rkey_skey = f"rkey_{idx}"
|
| 677 |
+
if vid_skey not in st.session_state:
|
| 678 |
+
st.session_state[vid_skey] = stream["video_id"]
|
| 679 |
+
if rkey_skey not in st.session_state:
|
| 680 |
+
st.session_state[rkey_skey] = stream["redis_key"]
|
| 681 |
+
|
| 682 |
+
st.text_input("Video ID / URL", placeholder="e.g. eFSK2-QRB0A", key=vid_skey)
|
| 683 |
+
st.text_input("Store key", placeholder=f"chat_messages_{label.lower()}", key=rkey_skey)
|
| 684 |
+
|
| 685 |
+
sc1, sc2 = st.columns(2)
|
| 686 |
+
with sc1:
|
| 687 |
+
if st.button("▶ Start", key=f"start_{idx}", width='stretch'):
|
| 688 |
+
vid = extract_video_id(st.session_state[vid_skey])
|
| 689 |
+
rkey = st.session_state[rkey_skey].strip() or f"chat_messages_{label.lower()}"
|
| 690 |
+
if vid:
|
| 691 |
+
start_scraper(idx, vid, rkey)
|
| 692 |
+
st.session_state.streams[idx]["proc"] = _SCRAPER_THREADS.get(str(idx))
|
| 693 |
+
st.session_state.streams[idx]["video_id"] = vid
|
| 694 |
+
st.session_state.streams[idx]["redis_key"] = rkey
|
| 695 |
+
if idx == 0:
|
| 696 |
+
title = fetch_video_title(vid)
|
| 697 |
+
if title:
|
| 698 |
+
_META["video_title"] = title
|
| 699 |
+
else:
|
| 700 |
+
_META.pop("video_title", None)
|
| 701 |
+
st.session_state.alert_dismissed = False
|
| 702 |
+
st.success(f"Stream {label} started → `{rkey}`")
|
| 703 |
+
else:
|
| 704 |
+
st.error("Invalid video ID or URL")
|
| 705 |
+
with sc2:
|
| 706 |
+
if st.button("⏹ Stop", key=f"stop_{idx}", width='stretch'):
|
| 707 |
+
if is_scraper_running(idx):
|
| 708 |
+
stop_scraper(idx)
|
| 709 |
+
st.session_state.streams[idx]["proc"] = None
|
| 710 |
+
st.success(f"Stream {label} stopped")
|
| 711 |
+
else:
|
| 712 |
+
st.warning("Not running")
|
| 713 |
+
|
| 714 |
+
running = is_scraper_running(idx)
|
| 715 |
+
dot_color = "#22c55e" if running else "#ef4444"
|
| 716 |
+
status = "running" if running else "stopped"
|
| 717 |
+
st.markdown(f'<div style="font-size:0.72rem;color:{dot_color};margin-bottom:4px;">● {status}</div>', unsafe_allow_html=True)
|
| 718 |
+
|
| 719 |
+
st.divider()
|
| 720 |
+
|
| 721 |
+
# ── Add / Remove stream slots ──
|
| 722 |
+
add_col, rem_col = st.columns(2)
|
| 723 |
+
with add_col:
|
| 724 |
+
if len(st.session_state.streams) < MAX_STREAMS:
|
| 725 |
+
if st.button("+ Add stream", width='stretch'):
|
| 726 |
+
n = len(st.session_state.streams)
|
| 727 |
+
st.session_state.streams.append({
|
| 728 |
+
"video_id": "",
|
| 729 |
+
"redis_key": f"chat_messages_{STREAM_NAMES[n].lower()}",
|
| 730 |
+
"label": f"Stream {STREAM_NAMES[n]}",
|
| 731 |
+
"proc": None,
|
| 732 |
+
})
|
| 733 |
+
st.rerun()
|
| 734 |
+
with rem_col:
|
| 735 |
+
if len(st.session_state.streams) > 1:
|
| 736 |
+
if st.button("- Remove last", width='stretch'):
|
| 737 |
+
removed = st.session_state.streams.pop()
|
| 738 |
+
removed_idx = len(st.session_state.streams)
|
| 739 |
+
stop_scraper(removed_idx)
|
| 740 |
+
st.rerun()
|
| 741 |
+
|
| 742 |
+
st.divider()
|
| 743 |
+
|
| 744 |
+
# ── Pinned Messages ──
|
| 745 |
+
st.markdown('<p style="font-size:0.68rem;font-weight:700;color:var(--accent);text-transform:uppercase;letter-spacing:0.1em;margin-bottom:8px;">Pinned Messages</p>', unsafe_allow_html=True)
|
| 746 |
+
pin_count = len(st.session_state.pinned_messages)
|
| 747 |
+
st.markdown(f'<div style="font-size:0.78rem;color:var(--text-3);">{pin_count} message{"s" if pin_count != 1 else ""} pinned</div>', unsafe_allow_html=True)
|
| 748 |
+
if pin_count > 0 and st.button("🗑 Clear pins", width='stretch'):
|
| 749 |
+
st.session_state.pinned_messages = []
|
| 750 |
+
st.rerun()
|
| 751 |
+
st.divider()
|
| 752 |
+
|
| 753 |
+
# ── Danger Zone ──
|
| 754 |
+
st.markdown('<p style="font-size:0.68rem;font-weight:700;color:#ef4444;text-transform:uppercase;letter-spacing:0.1em;margin-bottom:8px;">Danger Zone</p>', unsafe_allow_html=True)
|
| 755 |
+
if st.button("🗑 Clear all data", width='stretch'):
|
| 756 |
+
for s in st.session_state.streams:
|
| 757 |
+
store_delete(s["redis_key"])
|
| 758 |
+
st.session_state.pinned_messages = []
|
| 759 |
+
st.session_state.alert_dismissed = False
|
| 760 |
+
st.success("All stream data cleared.")
|
| 761 |
+
st.divider()
|
| 762 |
+
st.markdown(
|
| 763 |
+
'<div style="font-size:0.72rem;color:var(--text-3);text-align:center;line-height:1.6;">'
|
| 764 |
+
'Theme follows Streamlit settings<br>'
|
| 765 |
+
'<span style="font-size:0.65rem;">☰ → Settings → Theme</span>'
|
| 766 |
+
'</div>', unsafe_allow_html=True
|
| 767 |
+
)
|
| 768 |
+
|
| 769 |
+
|
| 770 |
+
# ── PAGE HEADER ───────────────────────────────────────────────
|
| 771 |
+
_video_title = _META.get("video_title")
|
| 772 |
+
_subtitle = f"▶ {_video_title}" if _video_title else "Real-time sentiment · topic classification · engagement insights"
|
| 773 |
+
|
| 774 |
+
col_title, col_live = st.columns([7, 1])
|
| 775 |
+
with col_title:
|
| 776 |
+
st.markdown(
|
| 777 |
+
'<div style="padding:8px 0 4px;">'
|
| 778 |
+
'<div style="font-size:2rem;font-weight:800;color:var(--text-1);letter-spacing:-0.04em;">YouTube Live Chat Analytics</div>'
|
| 779 |
+
f'<div style="font-size:1.25rem;color:var(--accent-text);font-weight:600;margin-top:6px;">{_subtitle}</div>'
|
| 780 |
+
'</div>', unsafe_allow_html=True
|
| 781 |
+
)
|
| 782 |
+
with col_live:
|
| 783 |
+
st.markdown(
|
| 784 |
+
'<div style="text-align:right;padding-top:22px;">'
|
| 785 |
+
'<span class="live-dot"></span>'
|
| 786 |
+
'<span style="font-size:0.78rem;color:var(--live);font-weight:700;letter-spacing:0.05em;">LIVE</span>'
|
| 787 |
+
'</div>', unsafe_allow_html=True
|
| 788 |
+
)
|
| 789 |
+
|
| 790 |
+
st.divider()
|
| 791 |
+
|
| 792 |
+
# ── DATA LOAD ─────────────────────────────────────────────────
|
| 793 |
+
# Use stream A's redis_key (session state is the source of truth)
|
| 794 |
+
_primary_key = st.session_state.streams[0]["redis_key"]
|
| 795 |
+
all_data = load_stream_data(_primary_key)
|
| 796 |
+
data = all_data[-msg_limit:] if len(all_data) > msg_limit else all_data
|
| 797 |
+
|
| 798 |
+
if not all_data:
|
| 799 |
+
st.markdown(
|
| 800 |
+
'<div class="empty-state">'
|
| 801 |
+
'<div class="empty-icon">📭</div>'
|
| 802 |
+
'<div class="empty-title">No messages yet</div>'
|
| 803 |
+
'<div class="empty-sub">Set a video ID in the sidebar, then click ▶ Start</div>'
|
| 804 |
+
'</div>', unsafe_allow_html=True
|
| 805 |
+
)
|
| 806 |
+
if auto_refresh:
|
| 807 |
+
time.sleep(refresh_rate)
|
| 808 |
+
st.rerun()
|
| 809 |
+
st.stop()
|
| 810 |
+
|
| 811 |
+
df = pd.DataFrame(data)
|
| 812 |
+
all_df = pd.DataFrame(all_data)
|
| 813 |
+
|
| 814 |
+
df["sentiment"] = df["sentiment"].apply(clean_sentiment)
|
| 815 |
+
df["topic"] = df["topic"].apply(clean_topic) if "topic" in df.columns else "General"
|
| 816 |
+
all_df["sentiment"] = all_df["sentiment"].apply(clean_sentiment)
|
| 817 |
+
all_df["topic"] = all_df["topic"].apply(clean_topic) if "topic" in all_df.columns else "General"
|
| 818 |
+
|
| 819 |
+
# ── ALERT BANNERS ─────────────────────────────────────────────
|
| 820 |
+
if alert_enabled:
|
| 821 |
+
alert = check_alert(all_df, threshold=alert_threshold, window=alert_window)
|
| 822 |
+
total_now = len(all_df)
|
| 823 |
+
if total_now != st.session_state.last_alert_count:
|
| 824 |
+
st.session_state.last_alert_count = total_now
|
| 825 |
+
if alert:
|
| 826 |
+
st.session_state.alert_dismissed = False
|
| 827 |
+
|
| 828 |
+
if alert and not st.session_state.alert_dismissed:
|
| 829 |
+
a1, a2 = st.columns([8, 1])
|
| 830 |
+
with a1:
|
| 831 |
+
st.markdown(
|
| 832 |
+
f'<div class="alert-banner">'
|
| 833 |
+
f'<span class="alert-icon">🚨</span>'
|
| 834 |
+
f'<div>'
|
| 835 |
+
f'<div class="alert-text">Negative sentiment spike — {alert["neg_ratio"]*100:.0f}% negative in last {alert["window"]} messages</div>'
|
| 836 |
+
f'<div class="alert-sub">{alert["count"]} of {alert["window"]} messages are negative. Consider moderating.</div>'
|
| 837 |
+
f'</div></div>',
|
| 838 |
+
unsafe_allow_html=True
|
| 839 |
+
)
|
| 840 |
+
with a2:
|
| 841 |
+
if st.button("✕ Dismiss", key="dismiss_alert"):
|
| 842 |
+
st.session_state.alert_dismissed = True
|
| 843 |
+
st.rerun()
|
| 844 |
+
|
| 845 |
+
if spam_alert_on:
|
| 846 |
+
spam_alert = check_spam_alert(all_df, threshold=spam_threshold, window=alert_window)
|
| 847 |
+
if spam_alert and not st.session_state.get("spam_dismissed", False):
|
| 848 |
+
s1, s2 = st.columns([8, 1])
|
| 849 |
+
with s1:
|
| 850 |
+
st.markdown(
|
| 851 |
+
f'<div class="spam-alert">'
|
| 852 |
+
f'<span class="alert-icon">🛡️</span>'
|
| 853 |
+
f'<div>'
|
| 854 |
+
f'<div class="spam-alert-text">Spam surge detected — {spam_alert["spam_ratio"]*100:.0f}% spam in last {spam_alert["window"]} messages</div>'
|
| 855 |
+
f'<div class="spam-alert-sub">{spam_alert["count"]} spam messages detected. Chat may be under flood attack.</div>'
|
| 856 |
+
f'</div></div>',
|
| 857 |
+
unsafe_allow_html=True
|
| 858 |
+
)
|
| 859 |
+
with s2:
|
| 860 |
+
if st.button("✕", key="dismiss_spam"):
|
| 861 |
+
st.session_state.spam_dismissed = True
|
| 862 |
+
st.rerun()
|
| 863 |
+
elif not spam_alert:
|
| 864 |
+
st.session_state.spam_dismissed = False
|
| 865 |
+
|
| 866 |
+
# ── CUMULATIVE STATS ──────────────────────────────────────────
|
| 867 |
+
all_counts = all_df["sentiment"].value_counts().to_dict()
|
| 868 |
+
c_pos = all_counts.get("Positive", 0)
|
| 869 |
+
c_neu = all_counts.get("Neutral", 0)
|
| 870 |
+
c_neg = all_counts.get("Negative", 0)
|
| 871 |
+
c_total = max(c_pos + c_neu + c_neg, 1)
|
| 872 |
+
|
| 873 |
+
velocity = compute_velocity(json.dumps([{"sentiment": m.get("sentiment","Neutral")} for m in all_data]))
|
| 874 |
+
|
| 875 |
+
st.markdown(
|
| 876 |
+
'<div class="sec-hdr"><span class="sec-ttl">Cumulative Sentiment</span><span class="sec-pill">All Time</span></div>',
|
| 877 |
+
unsafe_allow_html=True
|
| 878 |
+
)
|
| 879 |
+
|
| 880 |
+
v1, v2, v3, v4, v5 = st.columns([1, 1, 1, 1, 1])
|
| 881 |
+
with v1:
|
| 882 |
+
st.markdown(
|
| 883 |
+
f'<div class="stat-card"><div class="stat-accent" style="background:linear-gradient(90deg,#22c55e,#16a34a);"></div>'
|
| 884 |
+
f'<div class="stat-number" style="color:#22c55e;">{c_pos}</div><div class="stat-label">Positive</div><div class="stat-sub">{c_pos/c_total*100:.1f}% of total</div></div>',
|
| 885 |
+
unsafe_allow_html=True
|
| 886 |
+
)
|
| 887 |
+
with v2:
|
| 888 |
+
st.markdown(
|
| 889 |
+
f'<div class="stat-card"><div class="stat-accent" style="background:linear-gradient(90deg,#eab308,#ca8a04);"></div>'
|
| 890 |
+
f'<div class="stat-number" style="color:#eab308;">{c_neu}</div><div class="stat-label">Neutral</div><div class="stat-sub">{c_neu/c_total*100:.1f}% of total</div></div>',
|
| 891 |
+
unsafe_allow_html=True
|
| 892 |
+
)
|
| 893 |
+
with v3:
|
| 894 |
+
st.markdown(
|
| 895 |
+
f'<div class="stat-card"><div class="stat-accent" style="background:linear-gradient(90deg,#ef4444,#dc2626);"></div>'
|
| 896 |
+
f'<div class="stat-number" style="color:#ef4444;">{c_neg}</div><div class="stat-label">Negative</div><div class="stat-sub">{c_neg/c_total*100:.1f}% of total</div></div>',
|
| 897 |
+
unsafe_allow_html=True
|
| 898 |
+
)
|
| 899 |
+
with v4:
|
| 900 |
+
st.markdown(
|
| 901 |
+
f'<div class="stat-card"><div class="stat-accent" style="background:linear-gradient(90deg,#7c3aed,#4f46e5);"></div>'
|
| 902 |
+
f'<div class="stat-number" style="color:var(--accent-text);">{c_total}</div><div class="stat-label">Total</div><div class="stat-sub">all time</div></div>',
|
| 903 |
+
unsafe_allow_html=True
|
| 904 |
+
)
|
| 905 |
+
with v5:
|
| 906 |
+
vc = velocity["color"]
|
| 907 |
+
st.markdown(
|
| 908 |
+
f'<div class="velocity-card" style="border-color:{vc}44;">'
|
| 909 |
+
f'<div class="velocity-arrow" style="color:{vc};">{velocity["direction"]}</div>'
|
| 910 |
+
f'<div>'
|
| 911 |
+
f'<div class="velocity-val" style="color:{vc};">{velocity["label"]}</div>'
|
| 912 |
+
f'<div class="velocity-label">Sentiment Velocity<br>'
|
| 913 |
+
f'<span style="color:{vc};">{velocity["delta"]:+.0%} pos shift</span></div>'
|
| 914 |
+
f'</div></div>',
|
| 915 |
+
unsafe_allow_html=True
|
| 916 |
+
)
|
| 917 |
+
|
| 918 |
+
|
| 919 |
+
# ── WINDOW METRICS ────────────────────────────────────────────
|
| 920 |
+
st.divider()
|
| 921 |
+
counts = df["sentiment"].value_counts().to_dict()
|
| 922 |
+
pos = counts.get("Positive", 0)
|
| 923 |
+
neu = counts.get("Neutral", 0)
|
| 924 |
+
neg = counts.get("Negative", 0)
|
| 925 |
+
total = max(pos + neu + neg, 1)
|
| 926 |
+
|
| 927 |
+
st.markdown(
|
| 928 |
+
f'<div class="sec-hdr"><span class="sec-ttl">Window Snapshot</span><span class="sec-pill">Last {msg_limit} msgs</span></div>',
|
| 929 |
+
unsafe_allow_html=True
|
| 930 |
+
)
|
| 931 |
+
c1, c2, c3, c4 = st.columns(4)
|
| 932 |
+
c1.metric("Messages", total)
|
| 933 |
+
c2.metric("Positive", pos, f"{pos/total*100:.1f}%")
|
| 934 |
+
c3.metric("Neutral", neu, f"{neu/total*100:.1f}%")
|
| 935 |
+
c4.metric("Negative", neg, f"{neg/total*100:.1f}%")
|
| 936 |
+
|
| 937 |
+
# ── SENTIMENT CHARTS ──────────────────────────────────────────
|
| 938 |
+
st.divider()
|
| 939 |
+
col_l, col_r = st.columns(2)
|
| 940 |
+
|
| 941 |
+
with col_l:
|
| 942 |
+
st.markdown('<div class="chart-wrap">', unsafe_allow_html=True)
|
| 943 |
+
st.markdown('<div class="chart-title">Sentiment Distribution</div><div class="chart-sub">Message count by sentiment class</div>', unsafe_allow_html=True)
|
| 944 |
+
fig_bar = go.Figure(go.Bar(
|
| 945 |
+
x=["Positive", "Neutral", "Negative"],
|
| 946 |
+
y=[pos, neu, neg],
|
| 947 |
+
marker_color=["#22c55e", "#eab308", "#ef4444"],
|
| 948 |
+
marker_line_width=0,
|
| 949 |
+
text=[pos, neu, neg],
|
| 950 |
+
textposition="outside",
|
| 951 |
+
textfont=dict(size=12),
|
| 952 |
+
hovertemplate="<b>%{x}</b><br>Count: %{y}<extra></extra>",
|
| 953 |
+
))
|
| 954 |
+
fig_bar.update_layout(**plotly_layout(260))
|
| 955 |
+
st.plotly_chart(fig_bar, width='stretch', config={"displayModeBar": False})
|
| 956 |
+
bar_hdr, bar_dl = st.columns([1, 1])
|
| 957 |
+
with bar_hdr:
|
| 958 |
+
show_bar_data = st.checkbox("View data", key="show_bar")
|
| 959 |
+
with bar_dl:
|
| 960 |
+
bar_df = pd.DataFrame({"Sentiment": ["Positive", "Neutral", "Negative"], "Count": [pos, neu, neg]})
|
| 961 |
+
csv_download(bar_df, "Download CSV", "sentiment_distribution.csv")
|
| 962 |
+
if show_bar_data:
|
| 963 |
+
st.dataframe(bar_df, width='stretch', hide_index=True)
|
| 964 |
+
st.markdown('</div>', unsafe_allow_html=True)
|
| 965 |
+
|
| 966 |
+
with col_r:
|
| 967 |
+
st.markdown('<div class="chart-wrap">', unsafe_allow_html=True)
|
| 968 |
+
st.markdown('<div class="chart-title">Sentiment Breakdown</div><div class="chart-sub">Proportional share per class</div>', unsafe_allow_html=True)
|
| 969 |
+
fig_pie = go.Figure(go.Pie(
|
| 970 |
+
labels=["Positive", "Neutral", "Negative"],
|
| 971 |
+
values=[pos, neu, neg],
|
| 972 |
+
marker_colors=["#22c55e", "#eab308", "#ef4444"],
|
| 973 |
+
hole=0.58,
|
| 974 |
+
textinfo="percent",
|
| 975 |
+
hovertemplate="<b>%{label}</b><br>%{value} messages (%{percent})<extra></extra>",
|
| 976 |
+
))
|
| 977 |
+
fig_pie.update_layout(
|
| 978 |
+
**{**plotly_layout(260),
|
| 979 |
+
"showlegend": True,
|
| 980 |
+
"legend": dict(orientation="h", y=-0.08, font=dict(size=11))}
|
| 981 |
+
)
|
| 982 |
+
st.plotly_chart(fig_pie, width='stretch', config={"displayModeBar": False})
|
| 983 |
+
pie_hdr, pie_dl = st.columns([1, 1])
|
| 984 |
+
with pie_hdr:
|
| 985 |
+
show_pie_data = st.checkbox("View data", key="show_pie")
|
| 986 |
+
with pie_dl:
|
| 987 |
+
pie_df = pd.DataFrame({
|
| 988 |
+
"Sentiment": ["Positive", "Neutral", "Negative"],
|
| 989 |
+
"Count": [pos, neu, neg],
|
| 990 |
+
"Percentage": [f"{pos/total*100:.1f}%", f"{neu/total*100:.1f}%", f"{neg/total*100:.1f}%"]
|
| 991 |
+
})
|
| 992 |
+
csv_download(pie_df, "Download CSV", "sentiment_breakdown.csv")
|
| 993 |
+
if show_pie_data:
|
| 994 |
+
st.dataframe(pie_df, width='stretch', hide_index=True)
|
| 995 |
+
st.markdown('</div>', unsafe_allow_html=True)
|
| 996 |
+
|
| 997 |
+
# ── Confidence trend ──────────────────────────────────────────
|
| 998 |
+
if "confidence" in df.columns:
|
| 999 |
+
st.divider()
|
| 1000 |
+
st.markdown('<div class="chart-wrap">', unsafe_allow_html=True)
|
| 1001 |
+
st.markdown('<div class="chart-title">Confidence Trend</div><div class="chart-sub">Model confidence per message in current window</div>', unsafe_allow_html=True)
|
| 1002 |
+
conf_df = df[["confidence"]].reset_index(drop=True)
|
| 1003 |
+
conf_df.index.name = "message_index"
|
| 1004 |
+
fig_line = go.Figure(go.Scatter(
|
| 1005 |
+
x=conf_df.index,
|
| 1006 |
+
y=conf_df["confidence"],
|
| 1007 |
+
mode="lines",
|
| 1008 |
+
line=dict(color="#7c3aed", width=2),
|
| 1009 |
+
fill="tozeroy",
|
| 1010 |
+
fillcolor="rgba(124,58,237,0.08)",
|
| 1011 |
+
hovertemplate="Msg %{x}: <b>%{y:.2f}</b><extra></extra>",
|
| 1012 |
+
))
|
| 1013 |
+
fig_line.update_layout(**plotly_layout(180))
|
| 1014 |
+
fig_line.update_yaxes(range=[0, 1])
|
| 1015 |
+
st.plotly_chart(fig_line, width='stretch', config={"displayModeBar": False})
|
| 1016 |
+
conf_hdr, conf_dl = st.columns([1, 1])
|
| 1017 |
+
with conf_hdr:
|
| 1018 |
+
show_conf_data = st.checkbox("View data", key="show_conf")
|
| 1019 |
+
with conf_dl:
|
| 1020 |
+
conf_export = conf_df.reset_index()
|
| 1021 |
+
conf_export.columns = ["message_index", "confidence"]
|
| 1022 |
+
csv_download(conf_export, "Download CSV", "confidence_trend.csv")
|
| 1023 |
+
if show_conf_data:
|
| 1024 |
+
st.dataframe(conf_export, width='stretch', hide_index=True)
|
| 1025 |
+
st.markdown('</div>', unsafe_allow_html=True)
|
| 1026 |
+
|
| 1027 |
+
|
| 1028 |
+
# ── SENTIMENT HEATMAP OVER TIME ───────────────────────────────
|
| 1029 |
+
st.divider()
|
| 1030 |
+
st.markdown(
|
| 1031 |
+
'<div class="sec-hdr"><span class="sec-ttl">Sentiment Heatmap</span><span class="sec-pill">Over Time</span></div>',
|
| 1032 |
+
unsafe_allow_html=True
|
| 1033 |
+
)
|
| 1034 |
+
heatmap_data = build_heatmap_data(json.dumps([{"time": m.get("time",""), "sentiment": m.get("sentiment","Neutral")} for m in all_data]), bucket_minutes=1)
|
| 1035 |
+
|
| 1036 |
+
if not heatmap_data.empty:
|
| 1037 |
+
st.markdown('<div class="chart-wrap">', unsafe_allow_html=True)
|
| 1038 |
+
st.markdown('<div class="chart-title">Sentiment Over Time</div><div class="chart-sub">Message volume per sentiment per minute bucket</div>', unsafe_allow_html=True)
|
| 1039 |
+
|
| 1040 |
+
fig_heat = go.Figure()
|
| 1041 |
+
for sent, color in [("Positive", "#22c55e"), ("Neutral", "#eab308"), ("Negative", "#ef4444")]:
|
| 1042 |
+
fig_heat.add_trace(go.Bar(
|
| 1043 |
+
x=heatmap_data["bucket"],
|
| 1044 |
+
y=heatmap_data[sent],
|
| 1045 |
+
name=sent,
|
| 1046 |
+
marker_color=color,
|
| 1047 |
+
opacity=0.85,
|
| 1048 |
+
hovertemplate=f"<b>{sent}</b><br>%{{x}}<br>Count: %{{y}}<extra></extra>",
|
| 1049 |
+
))
|
| 1050 |
+
|
| 1051 |
+
layout = plotly_layout(220)
|
| 1052 |
+
layout["barmode"] = "stack"
|
| 1053 |
+
layout["showlegend"] = True
|
| 1054 |
+
layout["legend"] = dict(orientation="h", y=1.08, font=dict(size=11))
|
| 1055 |
+
layout["xaxis"]["tickformat"] = "%H:%M"
|
| 1056 |
+
fig_heat.update_layout(**layout)
|
| 1057 |
+
st.plotly_chart(fig_heat, width='stretch', config={"displayModeBar": False})
|
| 1058 |
+
|
| 1059 |
+
heat_hdr, heat_dl = st.columns([1, 1])
|
| 1060 |
+
with heat_hdr:
|
| 1061 |
+
show_heat_data = st.checkbox("View data", key="show_heat")
|
| 1062 |
+
with heat_dl:
|
| 1063 |
+
csv_download(heatmap_data.rename(columns={"bucket": "time_bucket"}), "Download CSV", "sentiment_heatmap.csv")
|
| 1064 |
+
if show_heat_data:
|
| 1065 |
+
st.dataframe(heatmap_data.rename(columns={"bucket": "time_bucket"}), width='stretch', hide_index=True)
|
| 1066 |
+
st.markdown('</div>', unsafe_allow_html=True)
|
| 1067 |
+
else:
|
| 1068 |
+
st.info("Not enough timestamped data for heatmap yet.")
|
| 1069 |
+
|
| 1070 |
+
# ── TOPIC DISTRIBUTION ────────────────────────────────────────
|
| 1071 |
+
st.divider()
|
| 1072 |
+
st.markdown(
|
| 1073 |
+
'<div class="sec-hdr"><span class="sec-ttl">Topic Distribution</span><span class="sec-pill">All Time</span></div>',
|
| 1074 |
+
unsafe_allow_html=True
|
| 1075 |
+
)
|
| 1076 |
+
|
| 1077 |
+
topic_counts = {
|
| 1078 |
+
label: int((all_df["topic"] == label).sum())
|
| 1079 |
+
for label in TOPIC_LABELS
|
| 1080 |
+
}
|
| 1081 |
+
|
| 1082 |
+
pills = '<div class="topic-grid">'
|
| 1083 |
+
for label in TOPIC_LABELS:
|
| 1084 |
+
color = TOPIC_COLOR[label]
|
| 1085 |
+
count = topic_counts[label]
|
| 1086 |
+
pills += (
|
| 1087 |
+
f'<div class="topic-pill" style="border:1px solid {color}44;">'
|
| 1088 |
+
f'<div class="topic-count" style="color:{color};">{count}</div>'
|
| 1089 |
+
f'<div class="topic-name">{label}</div>'
|
| 1090 |
+
f'</div>'
|
| 1091 |
+
)
|
| 1092 |
+
pills += '</div>'
|
| 1093 |
+
st.markdown(pills, unsafe_allow_html=True)
|
| 1094 |
+
|
| 1095 |
+
st.markdown('<div class="chart-wrap">', unsafe_allow_html=True)
|
| 1096 |
+
st.markdown('<div class="chart-title">Topic Breakdown</div><div class="chart-sub">All-time message count per topic category</div>', unsafe_allow_html=True)
|
| 1097 |
+
fig_topic = go.Figure(go.Bar(
|
| 1098 |
+
x=TOPIC_LABELS,
|
| 1099 |
+
y=[topic_counts[l] for l in TOPIC_LABELS],
|
| 1100 |
+
marker_color=[TOPIC_COLOR[l] for l in TOPIC_LABELS],
|
| 1101 |
+
marker_line_width=0,
|
| 1102 |
+
text=[topic_counts[l] for l in TOPIC_LABELS],
|
| 1103 |
+
textposition="outside",
|
| 1104 |
+
textfont=dict(size=11),
|
| 1105 |
+
hovertemplate="<b>%{x}</b><br>Count: %{y}<extra></extra>",
|
| 1106 |
+
))
|
| 1107 |
+
fig_topic.update_layout(**plotly_layout(250))
|
| 1108 |
+
st.plotly_chart(fig_topic, width='stretch', config={"displayModeBar": False})
|
| 1109 |
+
topic_hdr, topic_dl = st.columns([1, 1])
|
| 1110 |
+
with topic_hdr:
|
| 1111 |
+
show_topic_data = st.checkbox("View data", key="show_topic")
|
| 1112 |
+
with topic_dl:
|
| 1113 |
+
topic_df = pd.DataFrame({"Topic": TOPIC_LABELS, "Count": [topic_counts[l] for l in TOPIC_LABELS]})
|
| 1114 |
+
csv_download(topic_df, "Download CSV", "topic_distribution.csv")
|
| 1115 |
+
if show_topic_data:
|
| 1116 |
+
st.dataframe(topic_df, width='stretch', hide_index=True)
|
| 1117 |
+
st.markdown('</div>', unsafe_allow_html=True)
|
| 1118 |
+
|
| 1119 |
+
|
| 1120 |
+
# ── ENGAGEMENT SCORE ─────────────────────────────────────────
|
| 1121 |
+
st.divider()
|
| 1122 |
+
st.markdown(
|
| 1123 |
+
'<div class="sec-hdr"><span class="sec-ttl">Engagement Score</span><span class="sec-pill">Live</span></div>',
|
| 1124 |
+
unsafe_allow_html=True
|
| 1125 |
+
)
|
| 1126 |
+
|
| 1127 |
+
_eng_json = json.dumps([{"sentiment": m.get("sentiment","Neutral"), "topic": m.get("topic","General"), "time": m.get("time","")} for m in all_data])
|
| 1128 |
+
eng = compute_engagement(_eng_json)
|
| 1129 |
+
|
| 1130 |
+
ec1, ec2, ec3, ec4 = st.columns([2, 1, 1, 1])
|
| 1131 |
+
with ec1:
|
| 1132 |
+
score_color = "#22c55e" if eng["score"] >= 70 else "#eab308" if eng["score"] >= 40 else "#ef4444"
|
| 1133 |
+
bar_w = eng["score"]
|
| 1134 |
+
st.markdown(
|
| 1135 |
+
f'<div class="engage-card" style="border-color:{score_color}44;">'
|
| 1136 |
+
f'<div class="engage-score" style="color:{score_color};">{eng["score"]}</div>'
|
| 1137 |
+
f'<div class="engage-label">Engagement Score / 100 — {eng["grade"]}</div>'
|
| 1138 |
+
f'<div class="engage-bar-bg"><div class="engage-bar-fill" style="width:{bar_w}%;background:{score_color};"></div></div>'
|
| 1139 |
+
f'<div class="engage-breakdown">'
|
| 1140 |
+
f'<div class="engage-item">Msg rate <span>{eng["rate"]}/min</span></div>'
|
| 1141 |
+
f'<div class="engage-item">Positive <span>{eng["pos_ratio"]*100:.0f}%</span></div>'
|
| 1142 |
+
f'<div class="engage-item">Questions <span>{eng["q_density"]*100:.0f}%</span></div>'
|
| 1143 |
+
f'</div></div>',
|
| 1144 |
+
unsafe_allow_html=True
|
| 1145 |
+
)
|
| 1146 |
+
with ec2:
|
| 1147 |
+
st.metric("Msgs/min", f"{eng['rate']:.1f}")
|
| 1148 |
+
with ec3:
|
| 1149 |
+
st.metric("Positive ratio", f"{eng['pos_ratio']*100:.0f}%")
|
| 1150 |
+
with ec4:
|
| 1151 |
+
st.metric("Question density", f"{eng['q_density']*100:.0f}%")
|
| 1152 |
+
|
| 1153 |
+
# ── TOP CONTRIBUTORS ──────────────────────────────────────────
|
| 1154 |
+
st.divider()
|
| 1155 |
+
st.markdown(
|
| 1156 |
+
'<div class="sec-hdr"><span class="sec-ttl">Top Contributors</span><span class="sec-pill">All Time</span></div>',
|
| 1157 |
+
unsafe_allow_html=True
|
| 1158 |
+
)
|
| 1159 |
+
|
| 1160 |
+
_contrib_json = json.dumps([{"author": m.get("author",""), "sentiment": m.get("sentiment","Neutral")} for m in all_data])
|
| 1161 |
+
contributors = compute_top_contributors(_contrib_json)
|
| 1162 |
+
|
| 1163 |
+
if contributors:
|
| 1164 |
+
max_count = contributors[0]["count"]
|
| 1165 |
+
lc1, lc2 = st.columns([3, 2])
|
| 1166 |
+
with lc1:
|
| 1167 |
+
rank_icons = {1: "🥇", 2: "🥈", 3: "🥉"}
|
| 1168 |
+
rank_classes = {1: "gold", 2: "silver", 3: "bronze"}
|
| 1169 |
+
for rank, c in enumerate(contributors, 1):
|
| 1170 |
+
bar_pct = int(c["count"] / max(max_count, 1) * 100)
|
| 1171 |
+
rank_cls = rank_classes.get(rank, "")
|
| 1172 |
+
rank_icon = rank_icons.get(rank, f"#{rank}")
|
| 1173 |
+
author = c["author"]
|
| 1174 |
+
count = c["count"]
|
| 1175 |
+
pos_pct = c["pos_pct"]
|
| 1176 |
+
neu_pct = c["neu_pct"]
|
| 1177 |
+
neg_pct = c["neg_pct"]
|
| 1178 |
+
html = (
|
| 1179 |
+
f'<div class="leaderboard-row">'
|
| 1180 |
+
f'<div class="lb-rank {rank_cls}">{rank_icon}</div>'
|
| 1181 |
+
f'<div class="lb-author">{author}</div>'
|
| 1182 |
+
f'<div class="lb-bar"><div class="lb-bar-fill" style="width:{bar_pct}%;background:var(--accent);"></div></div>'
|
| 1183 |
+
f'<div class="lb-sent">'
|
| 1184 |
+
f'<span class="lb-dot" style="background:#22c55e;" title="Positive {pos_pct}%"></span>'
|
| 1185 |
+
f'<span class="lb-dot" style="background:#eab308;" title="Neutral {neu_pct}%"></span>'
|
| 1186 |
+
f'<span class="lb-dot" style="background:#ef4444;" title="Negative {neg_pct}%"></span>'
|
| 1187 |
+
f'</div>'
|
| 1188 |
+
f'<div class="lb-count">{count} msgs</div>'
|
| 1189 |
+
f'</div>'
|
| 1190 |
+
)
|
| 1191 |
+
st.markdown(html, unsafe_allow_html=True)
|
| 1192 |
+
with lc2:
|
| 1193 |
+
top5 = contributors[:5]
|
| 1194 |
+
fig_lb = go.Figure()
|
| 1195 |
+
for sent, color in [("pos_pct","#22c55e"),("neu_pct","#eab308"),("neg_pct","#ef4444")]:
|
| 1196 |
+
fig_lb.add_trace(go.Bar(
|
| 1197 |
+
y=[c["author"][:18] for c in top5],
|
| 1198 |
+
x=[c[sent] for c in top5],
|
| 1199 |
+
name=sent.replace("_pct","").capitalize(),
|
| 1200 |
+
orientation="h",
|
| 1201 |
+
marker_color=color,
|
| 1202 |
+
hovertemplate="%{y}: %{x}%<extra></extra>",
|
| 1203 |
+
))
|
| 1204 |
+
layout_lb = plotly_layout(260)
|
| 1205 |
+
layout_lb["barmode"] = "stack"
|
| 1206 |
+
layout_lb["showlegend"] = True
|
| 1207 |
+
layout_lb["legend"] = dict(orientation="h", y=1.1, font=dict(size=10))
|
| 1208 |
+
layout_lb["xaxis"]["range"] = [0, 100]
|
| 1209 |
+
layout_lb["xaxis"]["ticksuffix"] = "%"
|
| 1210 |
+
fig_lb.update_layout(**layout_lb)
|
| 1211 |
+
st.plotly_chart(fig_lb, width='stretch', config={"displayModeBar": False})
|
| 1212 |
+
|
| 1213 |
+
contrib_df = pd.DataFrame(contributors)
|
| 1214 |
+
csv_download(contrib_df, "Download CSV", "top_contributors.csv")
|
| 1215 |
+
else:
|
| 1216 |
+
st.info("Not enough data yet.")
|
| 1217 |
+
|
| 1218 |
+
# ── WORD CLOUD ────────────────────────────────────────────────
|
| 1219 |
+
st.divider()
|
| 1220 |
+
st.markdown(
|
| 1221 |
+
'<div class="sec-hdr"><span class="sec-ttl">Word Cloud</span><span class="sec-pill">All Time</span></div>',
|
| 1222 |
+
unsafe_allow_html=True
|
| 1223 |
+
)
|
| 1224 |
+
|
| 1225 |
+
wc_col1, wc_col2, wc_col3 = st.columns([1, 1, 3])
|
| 1226 |
+
with wc_col1:
|
| 1227 |
+
wc_sentiment = st.selectbox("Filter sentiment", ["All", "Positive", "Neutral", "Negative"], key="wc_sent")
|
| 1228 |
+
with wc_col2:
|
| 1229 |
+
wc_topic = st.selectbox("Filter topic", ["All"] + TOPIC_LABELS, key="wc_topic")
|
| 1230 |
+
|
| 1231 |
+
_wc_json = json.dumps([{"text": m.get("text",""), "sentiment": m.get("sentiment","Neutral"), "topic": m.get("topic","General")} for m in all_data])
|
| 1232 |
+
word_freq = compute_word_freq(_wc_json, sentiment_filter=wc_sentiment, topic_filter=wc_topic)
|
| 1233 |
+
|
| 1234 |
+
if word_freq:
|
| 1235 |
+
try:
|
| 1236 |
+
from wordcloud import WordCloud
|
| 1237 |
+
import matplotlib.pyplot as plt
|
| 1238 |
+
import io
|
| 1239 |
+
|
| 1240 |
+
freq_dict = dict(word_freq)
|
| 1241 |
+
wc = WordCloud(
|
| 1242 |
+
width=900, height=320,
|
| 1243 |
+
background_color="white",
|
| 1244 |
+
colormap="cool",
|
| 1245 |
+
max_words=80,
|
| 1246 |
+
prefer_horizontal=0.85,
|
| 1247 |
+
collocations=False,
|
| 1248 |
+
).generate_from_frequencies(freq_dict)
|
| 1249 |
+
|
| 1250 |
+
st.markdown('<div class="chart-wrap">', unsafe_allow_html=True)
|
| 1251 |
+
st.image(wc.to_array(), width="stretch")
|
| 1252 |
+
st.markdown('</div>', unsafe_allow_html=True)
|
| 1253 |
+
|
| 1254 |
+
top20 = word_freq[:20]
|
| 1255 |
+
fig_wf = go.Figure(go.Bar(
|
| 1256 |
+
x=[w for w, _ in top20],
|
| 1257 |
+
y=[c for _, c in top20],
|
| 1258 |
+
marker_color="#7c3aed",
|
| 1259 |
+
marker_line_width=0,
|
| 1260 |
+
hovertemplate="<b>%{x}</b><br>%{y} times<extra></extra>",
|
| 1261 |
+
))
|
| 1262 |
+
layout_wf = plotly_layout(180)
|
| 1263 |
+
fig_wf.update_layout(**layout_wf)
|
| 1264 |
+
st.plotly_chart(fig_wf, width='stretch', config={"displayModeBar": False})
|
| 1265 |
+
|
| 1266 |
+
except ImportError:
|
| 1267 |
+
top20 = word_freq[:20]
|
| 1268 |
+
fig_wf = go.Figure(go.Bar(
|
| 1269 |
+
x=[w for w, _ in top20],
|
| 1270 |
+
y=[c for _, c in top20],
|
| 1271 |
+
marker_color="#7c3aed",
|
| 1272 |
+
marker_line_width=0,
|
| 1273 |
+
))
|
| 1274 |
+
fig_wf.update_layout(**plotly_layout(200))
|
| 1275 |
+
st.plotly_chart(fig_wf, width='stretch', config={"displayModeBar": False})
|
| 1276 |
+
else:
|
| 1277 |
+
st.info("Not enough text data yet.")
|
| 1278 |
+
|
| 1279 |
+
# ── MULTI-STREAM COMPARISON ───────────────────────────────────
|
| 1280 |
+
active_streams = [s for s in st.session_state.streams if store_llen(s["redis_key"]) > 0]
|
| 1281 |
+
|
| 1282 |
+
if len(active_streams) > 1:
|
| 1283 |
+
st.divider()
|
| 1284 |
+
n_streams = len(active_streams)
|
| 1285 |
+
st.markdown(
|
| 1286 |
+
f'<div class="sec-hdr"><span class="sec-ttl">Multi-Stream Comparison</span>'
|
| 1287 |
+
f'<span class="sec-pill">{n_streams} streams</span></div>',
|
| 1288 |
+
unsafe_allow_html=True
|
| 1289 |
+
)
|
| 1290 |
+
|
| 1291 |
+
def stream_summary_chart(stream_df, color):
|
| 1292 |
+
counts_s = stream_df["sentiment"].value_counts().to_dict()
|
| 1293 |
+
p = counts_s.get("Positive", 0)
|
| 1294 |
+
n = counts_s.get("Neutral", 0)
|
| 1295 |
+
g = counts_s.get("Negative", 0)
|
| 1296 |
+
t = max(p + n + g, 1)
|
| 1297 |
+
fig = go.Figure(go.Bar(
|
| 1298 |
+
x=["Positive", "Neutral", "Negative"],
|
| 1299 |
+
y=[p, n, g],
|
| 1300 |
+
marker_color=["#22c55e", "#eab308", "#ef4444"],
|
| 1301 |
+
marker_line_width=0,
|
| 1302 |
+
text=[p, n, g],
|
| 1303 |
+
textposition="outside",
|
| 1304 |
+
hovertemplate="<b>%{x}</b><br>%{y}<extra></extra>",
|
| 1305 |
+
))
|
| 1306 |
+
fig.update_layout(**plotly_layout(200))
|
| 1307 |
+
return fig, p, n, g, t
|
| 1308 |
+
|
| 1309 |
+
chunk_size = 3
|
| 1310 |
+
for row_start in range(0, n_streams, chunk_size):
|
| 1311 |
+
row_streams = active_streams[row_start:row_start + chunk_size]
|
| 1312 |
+
cols = st.columns(len(row_streams))
|
| 1313 |
+
for col, stream in zip(cols, row_streams):
|
| 1314 |
+
sidx = st.session_state.streams.index(stream)
|
| 1315 |
+
color = STREAM_COLORS[sidx]
|
| 1316 |
+
slabel = STREAM_NAMES[sidx]
|
| 1317 |
+
s_data = load_stream_data(stream["redis_key"])
|
| 1318 |
+
if not s_data:
|
| 1319 |
+
col.info(f"No data yet for Stream {slabel}")
|
| 1320 |
+
continue
|
| 1321 |
+
s_df = pd.DataFrame(s_data)
|
| 1322 |
+
s_df["sentiment"] = s_df["sentiment"].apply(clean_sentiment)
|
| 1323 |
+
s_df["topic"] = s_df["topic"].apply(clean_topic) if "topic" in s_df.columns else "General"
|
| 1324 |
+
fig, p, n, g, t = stream_summary_chart(s_df, color)
|
| 1325 |
+
with col:
|
| 1326 |
+
st.markdown(
|
| 1327 |
+
f'<span class="compare-label" style="background:{color}18;color:{color};border:1px solid {color}44;">'
|
| 1328 |
+
f'Stream {slabel} — {stream["redis_key"]}</span>',
|
| 1329 |
+
unsafe_allow_html=True
|
| 1330 |
+
)
|
| 1331 |
+
st.plotly_chart(fig, width='stretch', config={"displayModeBar": False})
|
| 1332 |
+
st.markdown(
|
| 1333 |
+
f'<div style="font-size:0.78rem;color:var(--text-3);margin-bottom:8px;">'
|
| 1334 |
+
f'{t} msgs · <span style="color:#22c55e;">{p/t*100:.1f}% pos</span> · '
|
| 1335 |
+
f'<span style="color:#ef4444;">{g/t*100:.1f}% neg</span></div>',
|
| 1336 |
+
unsafe_allow_html=True
|
| 1337 |
+
)
|
| 1338 |
+
|
| 1339 |
+
st.markdown('<div class="chart-wrap" style="margin-top:14px;">', unsafe_allow_html=True)
|
| 1340 |
+
st.markdown('<div class="chart-title">Positive Ratio Over Time</div><div class="chart-sub">Rolling positive % per stream</div>', unsafe_allow_html=True)
|
| 1341 |
+
fig_overlay = go.Figure()
|
| 1342 |
+
for stream in active_streams:
|
| 1343 |
+
sidx = st.session_state.streams.index(stream)
|
| 1344 |
+
color = STREAM_COLORS[sidx]
|
| 1345 |
+
slabel = STREAM_NAMES[sidx]
|
| 1346 |
+
s_data = load_stream_data(stream["redis_key"])
|
| 1347 |
+
if not s_data:
|
| 1348 |
+
continue
|
| 1349 |
+
s_df = pd.DataFrame(s_data)
|
| 1350 |
+
s_df["sentiment"] = s_df["sentiment"].apply(clean_sentiment)
|
| 1351 |
+
s_df["is_pos"] = (s_df["sentiment"] == "Positive").astype(int)
|
| 1352 |
+
s_df["rolling"] = s_df["is_pos"].rolling(10, min_periods=1).mean() * 100
|
| 1353 |
+
fig_overlay.add_trace(go.Scatter(
|
| 1354 |
+
x=list(range(len(s_df))),
|
| 1355 |
+
y=s_df["rolling"],
|
| 1356 |
+
mode="lines",
|
| 1357 |
+
name=f"Stream {slabel}",
|
| 1358 |
+
line=dict(color=color, width=2),
|
| 1359 |
+
hovertemplate=f"Stream {slabel} msg %{{x}}: %{{y:.1f}}%<extra></extra>",
|
| 1360 |
+
))
|
| 1361 |
+
layout_ov = plotly_layout(200)
|
| 1362 |
+
layout_ov["showlegend"] = True
|
| 1363 |
+
layout_ov["legend"] = dict(orientation="h", y=1.1, font=dict(size=11))
|
| 1364 |
+
layout_ov["yaxis"]["range"] = [0, 100]
|
| 1365 |
+
fig_overlay.update_layout(**layout_ov)
|
| 1366 |
+
st.plotly_chart(fig_overlay, width='stretch', config={"displayModeBar": False})
|
| 1367 |
+
st.markdown('</div>', unsafe_allow_html=True)
|
| 1368 |
+
|
| 1369 |
+
elif len(st.session_state.streams) > 1:
|
| 1370 |
+
st.divider()
|
| 1371 |
+
st.info("Add video IDs to your extra stream slots and click ▶ Start to enable multi-stream comparison.")
|
| 1372 |
+
|
| 1373 |
+
# ── PINNED MESSAGES ───────────────────────────────────────────
|
| 1374 |
+
if st.session_state.pinned_messages:
|
| 1375 |
+
st.divider()
|
| 1376 |
+
st.markdown(
|
| 1377 |
+
'<div class="sec-hdr"><span class="sec-ttl">📌 Pinned Messages</span>'
|
| 1378 |
+
f'<span class="sec-pill">{len(st.session_state.pinned_messages)} pinned</span></div>',
|
| 1379 |
+
unsafe_allow_html=True
|
| 1380 |
+
)
|
| 1381 |
+
for idx, pmsg in enumerate(st.session_state.pinned_messages):
|
| 1382 |
+
s = pmsg.get("sentiment", "Neutral")
|
| 1383 |
+
s_color = SENT_COLORS.get(s, "#6b7280")
|
| 1384 |
+
t_color = TOPIC_COLOR.get(pmsg.get("topic", "General"), "#6b7280")
|
| 1385 |
+
pcol1, pcol2 = st.columns([10, 1])
|
| 1386 |
+
with pcol1:
|
| 1387 |
+
st.markdown(
|
| 1388 |
+
f'<div class="chat-card chat-pinned">'
|
| 1389 |
+
f'<div class="chat-author">📌 {pmsg.get("author", "Unknown")}</div>'
|
| 1390 |
+
f'<div class="chat-text">{pmsg.get("text", "")}</div>'
|
| 1391 |
+
f'<div class="chat-badges">'
|
| 1392 |
+
f'<span class="badge pin-badge">Pinned</span>'
|
| 1393 |
+
f'<span class="badge" style="color:{s_color};">{s}</span>'
|
| 1394 |
+
f'<span class="badge" style="color:{t_color};">{pmsg.get("topic","General")}</span>'
|
| 1395 |
+
f'<span class="badge">{pmsg.get("time","")[:19]}</span>'
|
| 1396 |
+
f'</div></div>',
|
| 1397 |
+
unsafe_allow_html=True
|
| 1398 |
+
)
|
| 1399 |
+
with pcol2:
|
| 1400 |
+
if st.button("✕", key=f"unpin_{idx}"):
|
| 1401 |
+
st.session_state.pinned_messages.pop(idx)
|
| 1402 |
+
st.rerun()
|
| 1403 |
+
|
| 1404 |
+
|
| 1405 |
+
# ── LIVE CHAT FEED ────────────────────────────────────────────
|
| 1406 |
+
st.divider()
|
| 1407 |
+
st.markdown('<div class="sec-hdr"><span class="sec-ttl">Live Chat Feed</span></div>', unsafe_allow_html=True)
|
| 1408 |
+
|
| 1409 |
+
f1, f2, f3 = st.columns([1, 1, 2])
|
| 1410 |
+
with f1:
|
| 1411 |
+
sentiment_filter = st.selectbox("Sentiment", ["All", "Positive", "Neutral", "Negative"])
|
| 1412 |
+
with f2:
|
| 1413 |
+
topic_filter = st.selectbox("Topic", ["All"] + TOPIC_LABELS)
|
| 1414 |
+
with f3:
|
| 1415 |
+
search_term = st.text_input("Search messages", placeholder="Filter by keyword...")
|
| 1416 |
+
|
| 1417 |
+
filtered = df.copy()
|
| 1418 |
+
if sentiment_filter != "All":
|
| 1419 |
+
filtered = filtered[filtered["sentiment"] == sentiment_filter]
|
| 1420 |
+
if topic_filter != "All":
|
| 1421 |
+
filtered = filtered[filtered["topic"] == topic_filter]
|
| 1422 |
+
if search_term:
|
| 1423 |
+
filtered = filtered[filtered["text"].str.contains(search_term, case=False, na=False)]
|
| 1424 |
+
|
| 1425 |
+
feed_hdr, feed_dl = st.columns([3, 1])
|
| 1426 |
+
with feed_hdr:
|
| 1427 |
+
st.markdown(
|
| 1428 |
+
f'<div style="font-size:0.78rem;color:var(--text-3);margin-bottom:12px;">Showing {len(filtered)} of {len(df)} messages</div>',
|
| 1429 |
+
unsafe_allow_html=True
|
| 1430 |
+
)
|
| 1431 |
+
with feed_dl:
|
| 1432 |
+
if not filtered.empty:
|
| 1433 |
+
export_cols = [c for c in ["author", "text", "sentiment", "confidence", "topic", "time"] if c in filtered.columns]
|
| 1434 |
+
csv_download(filtered[export_cols], "Download Feed CSV", "chat_feed.csv")
|
| 1435 |
+
|
| 1436 |
+
SENT_ICON = {"Positive": "🟢", "Negative": "🔴", "Neutral": "🟡"}
|
| 1437 |
+
|
| 1438 |
+
pinned_texts = {m.get("text", "") for m in st.session_state.pinned_messages}
|
| 1439 |
+
|
| 1440 |
+
for i, (_, row) in enumerate(filtered.iloc[::-1].iterrows()):
|
| 1441 |
+
s = row.get("sentiment", "Neutral")
|
| 1442 |
+
conf_pct = int(row.get("confidence", 0) * 100)
|
| 1443 |
+
topic = clean_topic(row.get("topic", "General"))
|
| 1444 |
+
t_color = TOPIC_COLOR.get(topic, "#6b7280")
|
| 1445 |
+
s_color = SENT_COLORS.get(s, "#6b7280")
|
| 1446 |
+
s_icon = SENT_ICON.get(s, "⚪")
|
| 1447 |
+
conf_color = "#22c55e" if conf_pct >= 70 else "#eab308" if conf_pct >= 40 else "#ef4444"
|
| 1448 |
+
msg_text = row.get("text", "")
|
| 1449 |
+
is_pinned = msg_text in pinned_texts
|
| 1450 |
+
|
| 1451 |
+
card_class = f"chat-card chat-{s.lower()}" + (" chat-pinned" if is_pinned else "")
|
| 1452 |
+
|
| 1453 |
+
msg_col, pin_col = st.columns([11, 1])
|
| 1454 |
+
with msg_col:
|
| 1455 |
+
st.markdown(
|
| 1456 |
+
f'<div class="{card_class}">'
|
| 1457 |
+
f'<div class="chat-author">{s_icon} {row.get("author", "Unknown")}'
|
| 1458 |
+
+ (' <span style="font-size:0.7rem;color:#eab308;">📌</span>' if is_pinned else '') +
|
| 1459 |
+
f'</div>'
|
| 1460 |
+
f'<div class="chat-text">{msg_text}</div>'
|
| 1461 |
+
f'<div class="chat-badges">'
|
| 1462 |
+
f'<span class="badge" style="color:{s_color};border-color:{s_color}33;">{s}</span>'
|
| 1463 |
+
f'<span class="badge" style="color:{conf_color};">Confidence: {conf_pct}%</span>'
|
| 1464 |
+
f'<span class="badge" style="color:{t_color};border-color:{t_color}33;">{topic}</span>'
|
| 1465 |
+
f'</div></div>',
|
| 1466 |
+
unsafe_allow_html=True
|
| 1467 |
+
)
|
| 1468 |
+
with pin_col:
|
| 1469 |
+
if is_pinned:
|
| 1470 |
+
if st.button("📌", key=f"unpin_feed_{i}", help="Unpin this message"):
|
| 1471 |
+
st.session_state.pinned_messages = [
|
| 1472 |
+
m for m in st.session_state.pinned_messages if m.get("text") != msg_text
|
| 1473 |
+
]
|
| 1474 |
+
st.rerun()
|
| 1475 |
+
else:
|
| 1476 |
+
if st.button("📍", key=f"pin_{i}", help="Pin this message"):
|
| 1477 |
+
msg_dict = row.to_dict()
|
| 1478 |
+
if msg_dict not in st.session_state.pinned_messages:
|
| 1479 |
+
st.session_state.pinned_messages.append(msg_dict)
|
| 1480 |
+
st.rerun()
|
| 1481 |
+
|
| 1482 |
+
# ── AUTO REFRESH ──────────────────────────────────────────────
|
| 1483 |
+
if auto_refresh:
|
| 1484 |
+
time.sleep(refresh_rate)
|
| 1485 |
+
st.rerun()
|
backend/config.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
import os
|
| 2 |
|
| 3 |
-
VIDEO_ID = os.getenv("VIDEO_ID", "
|
| 4 |
REDIS_HOST = os.getenv("REDIS_HOST", "localhost")
|
| 5 |
REDIS_PORT = int(os.getenv("REDIS_PORT", 6379))
|
| 6 |
REDIS_DB = int(os.getenv("REDIS_DB", 0))
|
|
|
|
| 1 |
import os
|
| 2 |
|
| 3 |
+
VIDEO_ID = os.getenv("VIDEO_ID", "0AtIKJ9dL80")
|
| 4 |
REDIS_HOST = os.getenv("REDIS_HOST", "localhost")
|
| 5 |
REDIS_PORT = int(os.getenv("REDIS_PORT", 6379))
|
| 6 |
REDIS_DB = int(os.getenv("REDIS_DB", 0))
|
backend/main.py
CHANGED
|
@@ -47,7 +47,7 @@ r = redis.Redis(
|
|
| 47 |
socket_connect_timeout=5,
|
| 48 |
)
|
| 49 |
|
| 50 |
-
VALID_TOPICS = {"Appreciation", "Question", "Promo", "Spam", "General"}
|
| 51 |
VALID_SENTIMENT = {"Positive", "Neutral", "Negative"}
|
| 52 |
|
| 53 |
|
|
|
|
| 47 |
socket_connect_timeout=5,
|
| 48 |
)
|
| 49 |
|
| 50 |
+
VALID_TOPICS = {"Appreciation", "Question", "Promo", "Spam", "General", "MCQ Answer"}
|
| 51 |
VALID_SENTIMENT = {"Positive", "Neutral", "Negative"}
|
| 52 |
|
| 53 |
|
backend/scraper.py
CHANGED
|
@@ -4,13 +4,13 @@ backend/scraper.py
|
|
| 4 |
Fetches live YouTube chat comments, runs sentiment + topic classification,
|
| 5 |
and pushes results to Redis.
|
| 6 |
|
| 7 |
-
|
| 8 |
-
python -m backend.scraper
|
| 9 |
|
| 10 |
-
|
| 11 |
-
python backend/scraper.py
|
| 12 |
"""
|
| 13 |
|
|
|
|
| 14 |
import json
|
| 15 |
import logging
|
| 16 |
import time
|
|
@@ -20,7 +20,7 @@ import pytchat
|
|
| 20 |
import redis
|
| 21 |
|
| 22 |
from backend.config import (
|
| 23 |
-
VIDEO_ID,
|
| 24 |
REDIS_HOST,
|
| 25 |
REDIS_PORT,
|
| 26 |
REDIS_DB,
|
|
@@ -28,7 +28,6 @@ from backend.config import (
|
|
| 28 |
from ml.sentiment_model import predict_sentiment
|
| 29 |
from ml.topic_model import predict_topic, VALID_TOPICS
|
| 30 |
|
| 31 |
-
# ── Logging ────────────────────────────────────────────────────────────────────
|
| 32 |
logging.basicConfig(
|
| 33 |
level=logging.INFO,
|
| 34 |
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
|
@@ -36,28 +35,10 @@ logging.basicConfig(
|
|
| 36 |
)
|
| 37 |
logger = logging.getLogger("scraper")
|
| 38 |
|
| 39 |
-
|
| 40 |
-
r = redis.Redis(
|
| 41 |
-
host=REDIS_HOST,
|
| 42 |
-
port=REDIS_PORT,
|
| 43 |
-
db=REDIS_DB,
|
| 44 |
-
decode_responses=True,
|
| 45 |
-
socket_connect_timeout=5,
|
| 46 |
-
)
|
| 47 |
-
|
| 48 |
-
try:
|
| 49 |
-
r.ping()
|
| 50 |
-
logger.info("Redis connected ✓")
|
| 51 |
-
except redis.ConnectionError as e:
|
| 52 |
-
logger.error("Cannot connect to Redis: %s", e)
|
| 53 |
-
raise SystemExit(1)
|
| 54 |
-
|
| 55 |
-
MAX_REDIS_MESSAGES = 1000 # cap the Redis list size
|
| 56 |
|
| 57 |
|
| 58 |
-
# ── Helpers ────────────────────────────────────────────────────────────────────
|
| 59 |
def _safe_sentiment(text: str) -> tuple[str, float]:
|
| 60 |
-
"""Run sentiment prediction with fallback on any error."""
|
| 61 |
try:
|
| 62 |
return predict_sentiment(text)
|
| 63 |
except Exception as exc:
|
|
@@ -66,11 +47,9 @@ def _safe_sentiment(text: str) -> tuple[str, float]:
|
|
| 66 |
|
| 67 |
|
| 68 |
def _safe_topic(text: str) -> tuple[str, float]:
|
| 69 |
-
"""Run topic prediction with fallback on any error."""
|
| 70 |
try:
|
| 71 |
topic, conf = predict_topic(text)
|
| 72 |
if topic not in VALID_TOPICS:
|
| 73 |
-
logger.warning("Invalid topic %r — using 'General'", topic)
|
| 74 |
return "General", 0.50
|
| 75 |
return topic, conf
|
| 76 |
except Exception as exc:
|
|
@@ -78,54 +57,58 @@ def _safe_topic(text: str) -> tuple[str, float]:
|
|
| 78 |
return "General", 0.50
|
| 79 |
|
| 80 |
|
| 81 |
-
def
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
-
|
| 90 |
-
def run() -> None:
|
| 91 |
-
logger.info("Starting live chat scraper for video: %s", VIDEO_ID)
|
| 92 |
|
| 93 |
-
chat = pytchat.create(video_id=
|
| 94 |
if not chat.is_alive():
|
| 95 |
-
logger.error("Could not connect to live chat. Is the stream live?")
|
| 96 |
return
|
| 97 |
|
| 98 |
-
logger.info("Live chat connected ✓
|
| 99 |
|
| 100 |
while chat.is_alive():
|
| 101 |
try:
|
| 102 |
for c in chat.get().sync_items():
|
| 103 |
text = c.message.strip()
|
| 104 |
author = c.author.name
|
| 105 |
-
|
| 106 |
if not text:
|
| 107 |
continue
|
| 108 |
|
| 109 |
-
# ── Classify ──────────────────────────────────────────────
|
| 110 |
sentiment, s_conf = _safe_sentiment(text)
|
| 111 |
topic, t_conf = _safe_topic(text)
|
| 112 |
|
| 113 |
-
# ── Build payload ─────────────────────────────────────────
|
| 114 |
message_data = {
|
| 115 |
-
"author":
|
| 116 |
-
"text":
|
| 117 |
-
"sentiment":
|
| 118 |
-
"confidence":
|
| 119 |
-
"topic":
|
| 120 |
-
"topic_conf":
|
| 121 |
-
"time":
|
| 122 |
}
|
| 123 |
|
| 124 |
-
|
| 125 |
-
|
|
|
|
|
|
|
| 126 |
|
| 127 |
logger.info(
|
| 128 |
-
"[%s] %s |
|
| 129 |
message_data["time"][11:19],
|
| 130 |
author[:20],
|
| 131 |
sentiment, s_conf,
|
|
@@ -137,12 +120,16 @@ def run() -> None:
|
|
| 137 |
logger.info("Stopped by user.")
|
| 138 |
break
|
| 139 |
except Exception as exc:
|
| 140 |
-
logger.error("Unexpected error
|
| 141 |
|
| 142 |
time.sleep(1)
|
| 143 |
|
| 144 |
-
logger.info("Chat stream ended
|
| 145 |
|
| 146 |
|
| 147 |
if __name__ == "__main__":
|
| 148 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
Fetches live YouTube chat comments, runs sentiment + topic classification,
|
| 5 |
and pushes results to Redis.
|
| 6 |
|
| 7 |
+
Accepts optional CLI arguments so multiple instances can run in parallel:
|
| 8 |
+
python -m backend.scraper --video_id VIDEO_ID --redis_key chat_messages_a
|
| 9 |
|
| 10 |
+
Defaults fall back to config.py values.
|
|
|
|
| 11 |
"""
|
| 12 |
|
| 13 |
+
import argparse
|
| 14 |
import json
|
| 15 |
import logging
|
| 16 |
import time
|
|
|
|
| 20 |
import redis
|
| 21 |
|
| 22 |
from backend.config import (
|
| 23 |
+
VIDEO_ID as DEFAULT_VIDEO_ID,
|
| 24 |
REDIS_HOST,
|
| 25 |
REDIS_PORT,
|
| 26 |
REDIS_DB,
|
|
|
|
| 28 |
from ml.sentiment_model import predict_sentiment
|
| 29 |
from ml.topic_model import predict_topic, VALID_TOPICS
|
| 30 |
|
|
|
|
| 31 |
logging.basicConfig(
|
| 32 |
level=logging.INFO,
|
| 33 |
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
|
|
|
| 35 |
)
|
| 36 |
logger = logging.getLogger("scraper")
|
| 37 |
|
| 38 |
+
MAX_REDIS_MESSAGES = 10000
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
|
|
|
|
| 41 |
def _safe_sentiment(text: str) -> tuple[str, float]:
|
|
|
|
| 42 |
try:
|
| 43 |
return predict_sentiment(text)
|
| 44 |
except Exception as exc:
|
|
|
|
| 47 |
|
| 48 |
|
| 49 |
def _safe_topic(text: str) -> tuple[str, float]:
|
|
|
|
| 50 |
try:
|
| 51 |
topic, conf = predict_topic(text)
|
| 52 |
if topic not in VALID_TOPICS:
|
|
|
|
| 53 |
return "General", 0.50
|
| 54 |
return topic, conf
|
| 55 |
except Exception as exc:
|
|
|
|
| 57 |
return "General", 0.50
|
| 58 |
|
| 59 |
|
| 60 |
+
def run(video_id: str, redis_key: str) -> None:
|
| 61 |
+
r = redis.Redis(
|
| 62 |
+
host=REDIS_HOST,
|
| 63 |
+
port=REDIS_PORT,
|
| 64 |
+
db=REDIS_DB,
|
| 65 |
+
decode_responses=True,
|
| 66 |
+
socket_connect_timeout=5,
|
| 67 |
+
)
|
| 68 |
+
try:
|
| 69 |
+
r.ping()
|
| 70 |
+
logger.info("Redis connected ✓")
|
| 71 |
+
except redis.ConnectionError as e:
|
| 72 |
+
logger.error("Cannot connect to Redis: %s", e)
|
| 73 |
+
raise SystemExit(1)
|
| 74 |
|
| 75 |
+
logger.info("Starting scraper — video=%s redis_key=%s", video_id, redis_key)
|
|
|
|
|
|
|
| 76 |
|
| 77 |
+
chat = pytchat.create(video_id=video_id)
|
| 78 |
if not chat.is_alive():
|
| 79 |
+
logger.error("Could not connect to live chat for %s. Is the stream live?", video_id)
|
| 80 |
return
|
| 81 |
|
| 82 |
+
logger.info("Live chat connected ✓ — press Ctrl+C to stop")
|
| 83 |
|
| 84 |
while chat.is_alive():
|
| 85 |
try:
|
| 86 |
for c in chat.get().sync_items():
|
| 87 |
text = c.message.strip()
|
| 88 |
author = c.author.name
|
|
|
|
| 89 |
if not text:
|
| 90 |
continue
|
| 91 |
|
|
|
|
| 92 |
sentiment, s_conf = _safe_sentiment(text)
|
| 93 |
topic, t_conf = _safe_topic(text)
|
| 94 |
|
|
|
|
| 95 |
message_data = {
|
| 96 |
+
"author": author,
|
| 97 |
+
"text": text,
|
| 98 |
+
"sentiment": sentiment,
|
| 99 |
+
"confidence": round(s_conf, 3),
|
| 100 |
+
"topic": topic,
|
| 101 |
+
"topic_conf": round(t_conf, 3),
|
| 102 |
+
"time": datetime.now().isoformat(),
|
| 103 |
}
|
| 104 |
|
| 105 |
+
pipe = r.pipeline()
|
| 106 |
+
pipe.rpush(redis_key, json.dumps(message_data))
|
| 107 |
+
pipe.ltrim(redis_key, -MAX_REDIS_MESSAGES, -1)
|
| 108 |
+
pipe.execute()
|
| 109 |
|
| 110 |
logger.info(
|
| 111 |
+
"[%s] %s | %s(%.2f) %s(%.2f) | %r",
|
| 112 |
message_data["time"][11:19],
|
| 113 |
author[:20],
|
| 114 |
sentiment, s_conf,
|
|
|
|
| 120 |
logger.info("Stopped by user.")
|
| 121 |
break
|
| 122 |
except Exception as exc:
|
| 123 |
+
logger.error("Unexpected error: %s", exc, exc_info=True)
|
| 124 |
|
| 125 |
time.sleep(1)
|
| 126 |
|
| 127 |
+
logger.info("Chat stream ended — key=%s", redis_key)
|
| 128 |
|
| 129 |
|
| 130 |
if __name__ == "__main__":
|
| 131 |
+
parser = argparse.ArgumentParser()
|
| 132 |
+
parser.add_argument("--video_id", default=DEFAULT_VIDEO_ID, help="YouTube video ID")
|
| 133 |
+
parser.add_argument("--redis_key", default="chat_messages", help="Redis list key to write to")
|
| 134 |
+
args = parser.parse_args()
|
| 135 |
+
run(video_id=args.video_id, redis_key=args.redis_key)
|
frontend/streamlit_app.py
CHANGED
|
@@ -4,10 +4,14 @@ import redis
|
|
| 4 |
import json
|
| 5 |
import pandas as pd
|
| 6 |
import plotly.graph_objects as go
|
|
|
|
| 7 |
import time
|
| 8 |
import re
|
| 9 |
import sys
|
| 10 |
import os
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'backend'))
|
| 13 |
from config import REDIS_HOST, REDIS_PORT, REDIS_DB
|
|
@@ -21,10 +25,11 @@ st.set_page_config(
|
|
| 21 |
|
| 22 |
r = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB, decode_responses=True)
|
| 23 |
|
| 24 |
-
TOPIC_LABELS = ["Appreciation", "Question", "Promo", "Spam", "General"]
|
| 25 |
TOPIC_COLOR = {
|
| 26 |
"Appreciation": "#f59e0b", "Question": "#3b82f6",
|
| 27 |
-
"Promo": "#ec4899", "Spam": "#ef4444", "General": "#6b7280"
|
|
|
|
| 28 |
}
|
| 29 |
SENT_COLORS = {"Positive": "#22c55e", "Neutral": "#eab308", "Negative": "#ef4444"}
|
| 30 |
|
|
@@ -39,7 +44,6 @@ THEME_JS = """<script>
|
|
| 39 |
const m = bg.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);
|
| 40 |
if (m) { isDark = (0.299*m[1] + 0.587*m[2] + 0.114*m[3]) < 128; }
|
| 41 |
else {
|
| 42 |
-
// fallback: check body background
|
| 43 |
const bodyBg = window.parent.getComputedStyle(window.parent.document.body).backgroundColor;
|
| 44 |
const m2 = bodyBg.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);
|
| 45 |
if (m2) { isDark = (0.299*m2[1] + 0.587*m2[2] + 0.114*m2[3]) < 128; }
|
|
@@ -65,6 +69,8 @@ CSS = """<style>
|
|
| 65 |
--shadow:0 4px 24px rgba(0,0,0,0.4); --shadow-sm:0 2px 8px rgba(0,0,0,0.3);
|
| 66 |
--pill-bg:rgba(124,58,237,0.15); --pill-border:rgba(124,58,237,0.3); --pill-text:#a78bfa;
|
| 67 |
--plotly-paper:rgba(0,0,0,0); --plotly-plot:rgba(255,255,255,0.015); --plotly-grid:rgba(255,255,255,0.05); --plotly-text:#94a3b8;
|
|
|
|
|
|
|
| 68 |
}
|
| 69 |
[data-livepulse="light"] {
|
| 70 |
--bg:#f4f6ff; --bg-card:#ffffff; --border:rgba(99,102,241,0.12);
|
|
@@ -75,6 +81,8 @@ CSS = """<style>
|
|
| 75 |
--shadow:0 4px 24px rgba(99,102,241,0.12); --shadow-sm:0 2px 8px rgba(99,102,241,0.08);
|
| 76 |
--pill-bg:rgba(109,40,217,0.08); --pill-border:rgba(109,40,217,0.2); --pill-text:#6d28d9;
|
| 77 |
--plotly-paper:rgba(0,0,0,0); --plotly-plot:rgba(255,255,255,0.7); --plotly-grid:rgba(0,0,0,0.06); --plotly-text:#475569;
|
|
|
|
|
|
|
| 78 |
}
|
| 79 |
|
| 80 |
html,body,[data-testid="stAppViewContainer"],[data-testid="stMain"],.main .block-container {
|
|
@@ -95,19 +103,32 @@ html,body,[data-testid="stAppViewContainer"],[data-testid="stMain"],.main .block
|
|
| 95 |
[data-testid="stMetricDelta"]{color:var(--accent-text)!important;}
|
| 96 |
|
| 97 |
.stTextInput input { background:var(--input-bg)!important; border:1px solid var(--input-border)!important; border-radius:10px!important; color:var(--text-1)!important; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
[data-baseweb="select"]>div { background:var(--input-bg)!important; border:1px solid var(--input-border)!important; border-radius:10px!important; color:var(--text-1)!important; }
|
| 99 |
.stButton>button { background:linear-gradient(135deg,var(--accent),var(--accent2))!important; color:#fff!important; border:none!important; border-radius:10px!important; font-weight:600!important; font-family:'Space Grotesk',sans-serif!important; box-shadow:0 4px 16px rgba(124,58,237,0.3)!important; transition:all 0.2s!important; }
|
| 100 |
.stButton>button:hover{transform:translateY(-2px)!important;}
|
| 101 |
hr{border:none!important;border-top:1px solid var(--divider)!important;margin:1.2rem 0!important;}
|
| 102 |
[data-testid="stSidebar"] label,[data-testid="stSidebar"] .stMarkdown p{color:var(--text-2)!important;font-size:0.83rem!important;}
|
| 103 |
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
|
|
|
|
|
|
| 107 |
|
| 108 |
@keyframes pulse{0%{box-shadow:0 0 0 0 rgba(34,197,94,0.7);}70%{box-shadow:0 0 0 10px rgba(34,197,94,0);}100%{box-shadow:0 0 0 0 rgba(34,197,94,0);}}
|
| 109 |
.live-dot{display:inline-block;width:9px;height:9px;background:var(--live);border-radius:50%;animation:pulse 1.8s infinite;margin-right:6px;vertical-align:middle;}
|
| 110 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
.stat-grid{display:flex;gap:12px;margin:10px 0 18px;flex-wrap:wrap;}
|
| 112 |
.stat-card{flex:1;min-width:130px;background:var(--bg-card);border:1px solid var(--border);border-radius:20px;padding:22px 18px;text-align:center;transition:transform 0.2s,box-shadow 0.2s,background 0.3s;position:relative;overflow:hidden;box-shadow:var(--shadow-sm);}
|
| 113 |
.stat-card:hover{transform:translateY(-4px);box-shadow:var(--shadow);}
|
|
@@ -116,6 +137,11 @@ hr{border:none!important;border-top:1px solid var(--divider)!important;margin:1.
|
|
| 116 |
.stat-label{font-size:0.82rem;color:var(--text-2);font-weight:600;text-transform:uppercase;letter-spacing:0.06em;}
|
| 117 |
.stat-sub{font-size:0.7rem;color:var(--text-3);margin-top:4px;}
|
| 118 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
.sec-hdr{display:flex;align-items:center;gap:10px;margin:6px 0 14px;}
|
| 120 |
.sec-ttl{font-size:1rem;font-weight:700;color:var(--text-1);letter-spacing:-0.01em;}
|
| 121 |
.sec-pill{background:var(--pill-bg);border:1px solid var(--pill-border);border-radius:20px;padding:2px 10px;font-size:0.68rem;color:var(--pill-text);font-weight:700;text-transform:uppercase;letter-spacing:0.08em;}
|
|
@@ -134,10 +160,38 @@ hr{border:none!important;border-top:1px solid var(--divider)!important;margin:1.
|
|
| 134 |
.chat-card{background:var(--bg-card);border:1px solid var(--border);border-radius:16px;padding:14px 16px;margin-bottom:10px;border-left:3px solid transparent;animation:slideIn 0.2s ease;transition:background 0.2s,transform 0.15s,box-shadow 0.2s;box-shadow:var(--shadow-sm);}
|
| 135 |
.chat-card:hover{transform:translateX(4px);box-shadow:var(--shadow);}
|
| 136 |
.chat-positive{border-left-color:#22c55e;} .chat-negative{border-left-color:#ef4444;} .chat-neutral{border-left-color:#eab308;}
|
|
|
|
| 137 |
.chat-author{font-weight:700;font-size:0.83rem;color:var(--accent-text);margin-bottom:5px;}
|
| 138 |
.chat-text{font-size:0.92rem;color:var(--text-2);line-height:1.55;margin-bottom:9px;}
|
| 139 |
.chat-badges{display:flex;gap:6px;flex-wrap:wrap;}
|
| 140 |
.badge{display:inline-flex;align-items:center;background:var(--badge-bg);border:1px solid var(--border);border-radius:20px;padding:3px 10px;font-size:0.7rem;font-weight:600;color:var(--text-2);}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
|
| 142 |
.empty-state{text-align:center;padding:80px 20px;background:var(--bg-card);border:1px solid var(--border);border-radius:24px;margin:40px 0;box-shadow:var(--shadow-sm);}
|
| 143 |
.empty-icon{font-size:3.5rem;margin-bottom:16px;}
|
|
@@ -167,8 +221,16 @@ def update_config_video_id(video_id):
|
|
| 167 |
with open(config_path, 'w') as f:
|
| 168 |
f.write(content)
|
| 169 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
def clean_topic(val):
|
| 171 |
-
"""Normalize topic — replace None/NaN/empty with General."""
|
| 172 |
if pd.isna(val) or str(val).strip() == "" or str(val).strip().lower() == "nan":
|
| 173 |
return "General"
|
| 174 |
return str(val).strip()
|
|
@@ -198,6 +260,221 @@ def csv_download(df_export, label, filename):
|
|
| 198 |
st.download_button(label=f"⬇ {label}", data=csv,
|
| 199 |
file_name=filename, mime="text/csv", key=filename)
|
| 200 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
|
| 202 |
# ── SIDEBAR ──────────────────────────────────────────────────
|
| 203 |
with st.sidebar:
|
|
@@ -208,15 +485,142 @@ with st.sidebar:
|
|
| 208 |
'</div>', unsafe_allow_html=True
|
| 209 |
)
|
| 210 |
st.divider()
|
|
|
|
|
|
|
| 211 |
st.markdown('<p style="font-size:0.68rem;font-weight:700;color:var(--accent);text-transform:uppercase;letter-spacing:0.1em;margin-bottom:8px;">Display Settings</p>', unsafe_allow_html=True)
|
| 212 |
refresh_rate = st.slider("Refresh interval (s)", 5, 60, 15)
|
| 213 |
msg_limit = st.slider("Message window", 10, 200, 50)
|
| 214 |
auto_refresh = st.toggle("Live auto-refresh", value=True)
|
| 215 |
st.divider()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
st.markdown('<p style="font-size:0.68rem;font-weight:700;color:#ef4444;text-transform:uppercase;letter-spacing:0.1em;margin-bottom:8px;">Danger Zone</p>', unsafe_allow_html=True)
|
| 217 |
-
if st.button("🗑 Clear all data",
|
| 218 |
-
|
| 219 |
-
|
|
|
|
|
|
|
|
|
|
| 220 |
st.divider()
|
| 221 |
st.markdown(
|
| 222 |
'<div style="font-size:0.72rem;color:var(--text-3);text-align:center;line-height:1.6;">'
|
|
@@ -225,13 +629,17 @@ with st.sidebar:
|
|
| 225 |
'</div>', unsafe_allow_html=True
|
| 226 |
)
|
| 227 |
|
|
|
|
| 228 |
# ── PAGE HEADER ───────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
| 229 |
col_title, col_live = st.columns([7, 1])
|
| 230 |
with col_title:
|
| 231 |
st.markdown(
|
| 232 |
'<div style="padding:8px 0 4px;">'
|
| 233 |
'<div style="font-size:2rem;font-weight:800;color:var(--text-1);letter-spacing:-0.04em;">YouTube Live Chat Analytics</div>'
|
| 234 |
-
'<div style="font-size:
|
| 235 |
'</div>', unsafe_allow_html=True
|
| 236 |
)
|
| 237 |
with col_live:
|
|
@@ -245,17 +653,15 @@ with col_live:
|
|
| 245 |
st.divider()
|
| 246 |
|
| 247 |
# ── DATA LOAD ─────────────────────────────────────────────────
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
raw = r.lrange("chat_messages", -msg_limit, -1)
|
| 251 |
-
data = [json.loads(m) for m in raw]
|
| 252 |
|
| 253 |
if not all_data:
|
| 254 |
st.markdown(
|
| 255 |
'<div class="empty-state">'
|
| 256 |
'<div class="empty-icon">📭</div>'
|
| 257 |
'<div class="empty-title">No messages yet</div>'
|
| 258 |
-
'<div class="empty-sub">Set a video ID in the sidebar, then
|
| 259 |
'</div>', unsafe_allow_html=True
|
| 260 |
)
|
| 261 |
if auto_refresh:
|
|
@@ -266,12 +672,58 @@ if not all_data:
|
|
| 266 |
df = pd.DataFrame(data)
|
| 267 |
all_df = pd.DataFrame(all_data)
|
| 268 |
|
| 269 |
-
|
| 270 |
-
df["
|
| 271 |
-
df["topic"] = df["topic"].apply(clean_topic) if "topic" in df.columns else "General"
|
| 272 |
all_df["sentiment"] = all_df["sentiment"].apply(clean_sentiment)
|
| 273 |
all_df["topic"] = all_df["topic"].apply(clean_topic) if "topic" in all_df.columns else "General"
|
| 274 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 275 |
# ── CUMULATIVE STATS ──────────────────────────────────────────
|
| 276 |
all_counts = all_df["sentiment"].value_counts().to_dict()
|
| 277 |
c_pos = all_counts.get("Positive", 0)
|
|
@@ -279,23 +731,53 @@ c_neu = all_counts.get("Neutral", 0)
|
|
| 279 |
c_neg = all_counts.get("Negative", 0)
|
| 280 |
c_total = max(c_pos + c_neu + c_neg, 1)
|
| 281 |
|
|
|
|
|
|
|
|
|
|
| 282 |
st.markdown(
|
| 283 |
'<div class="sec-hdr"><span class="sec-ttl">Cumulative Sentiment</span><span class="sec-pill">All Time</span></div>',
|
| 284 |
unsafe_allow_html=True
|
| 285 |
)
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 299 |
|
| 300 |
# ── WINDOW METRICS ────────────────────────────────────────────
|
| 301 |
st.divider()
|
|
@@ -319,11 +801,9 @@ c4.metric("Negative", neg, f"{neg/total*100:.1f}%")
|
|
| 319 |
st.divider()
|
| 320 |
col_l, col_r = st.columns(2)
|
| 321 |
|
| 322 |
-
# ── Bar chart ──
|
| 323 |
with col_l:
|
| 324 |
st.markdown('<div class="chart-wrap">', unsafe_allow_html=True)
|
| 325 |
st.markdown('<div class="chart-title">Sentiment Distribution</div><div class="chart-sub">Message count by sentiment class</div>', unsafe_allow_html=True)
|
| 326 |
-
|
| 327 |
fig_bar = go.Figure(go.Bar(
|
| 328 |
x=["Positive", "Neutral", "Negative"],
|
| 329 |
y=[pos, neu, neg],
|
|
@@ -335,24 +815,20 @@ with col_l:
|
|
| 335 |
hovertemplate="<b>%{x}</b><br>Count: %{y}<extra></extra>",
|
| 336 |
))
|
| 337 |
fig_bar.update_layout(**plotly_layout(260))
|
| 338 |
-
st.plotly_chart(fig_bar,
|
| 339 |
-
|
| 340 |
bar_hdr, bar_dl = st.columns([1, 1])
|
| 341 |
with bar_hdr:
|
| 342 |
show_bar_data = st.checkbox("View data", key="show_bar")
|
| 343 |
with bar_dl:
|
| 344 |
bar_df = pd.DataFrame({"Sentiment": ["Positive", "Neutral", "Negative"], "Count": [pos, neu, neg]})
|
| 345 |
csv_download(bar_df, "Download CSV", "sentiment_distribution.csv")
|
| 346 |
-
|
| 347 |
if show_bar_data:
|
| 348 |
-
st.dataframe(bar_df,
|
| 349 |
st.markdown('</div>', unsafe_allow_html=True)
|
| 350 |
|
| 351 |
-
# ── Donut chart ──
|
| 352 |
with col_r:
|
| 353 |
st.markdown('<div class="chart-wrap">', unsafe_allow_html=True)
|
| 354 |
st.markdown('<div class="chart-title">Sentiment Breakdown</div><div class="chart-sub">Proportional share per class</div>', unsafe_allow_html=True)
|
| 355 |
-
|
| 356 |
fig_pie = go.Figure(go.Pie(
|
| 357 |
labels=["Positive", "Neutral", "Negative"],
|
| 358 |
values=[pos, neu, neg],
|
|
@@ -366,8 +842,7 @@ with col_r:
|
|
| 366 |
"showlegend": True,
|
| 367 |
"legend": dict(orientation="h", y=-0.08, font=dict(size=11))}
|
| 368 |
)
|
| 369 |
-
st.plotly_chart(fig_pie,
|
| 370 |
-
|
| 371 |
pie_hdr, pie_dl = st.columns([1, 1])
|
| 372 |
with pie_hdr:
|
| 373 |
show_pie_data = st.checkbox("View data", key="show_pie")
|
|
@@ -378,9 +853,8 @@ with col_r:
|
|
| 378 |
"Percentage": [f"{pos/total*100:.1f}%", f"{neu/total*100:.1f}%", f"{neg/total*100:.1f}%"]
|
| 379 |
})
|
| 380 |
csv_download(pie_df, "Download CSV", "sentiment_breakdown.csv")
|
| 381 |
-
|
| 382 |
if show_pie_data:
|
| 383 |
-
st.dataframe(pie_df,
|
| 384 |
st.markdown('</div>', unsafe_allow_html=True)
|
| 385 |
|
| 386 |
# ── Confidence trend ──────────────────────────────────────────
|
|
@@ -388,10 +862,8 @@ if "confidence" in df.columns:
|
|
| 388 |
st.divider()
|
| 389 |
st.markdown('<div class="chart-wrap">', unsafe_allow_html=True)
|
| 390 |
st.markdown('<div class="chart-title">Confidence Trend</div><div class="chart-sub">Model confidence per message in current window</div>', unsafe_allow_html=True)
|
| 391 |
-
|
| 392 |
conf_df = df[["confidence"]].reset_index(drop=True)
|
| 393 |
conf_df.index.name = "message_index"
|
| 394 |
-
|
| 395 |
fig_line = go.Figure(go.Scatter(
|
| 396 |
x=conf_df.index,
|
| 397 |
y=conf_df["confidence"],
|
|
@@ -403,8 +875,7 @@ if "confidence" in df.columns:
|
|
| 403 |
))
|
| 404 |
fig_line.update_layout(**plotly_layout(180))
|
| 405 |
fig_line.update_yaxes(range=[0, 1])
|
| 406 |
-
st.plotly_chart(fig_line,
|
| 407 |
-
|
| 408 |
conf_hdr, conf_dl = st.columns([1, 1])
|
| 409 |
with conf_hdr:
|
| 410 |
show_conf_data = st.checkbox("View data", key="show_conf")
|
|
@@ -412,11 +883,53 @@ if "confidence" in df.columns:
|
|
| 412 |
conf_export = conf_df.reset_index()
|
| 413 |
conf_export.columns = ["message_index", "confidence"]
|
| 414 |
csv_download(conf_export, "Download CSV", "confidence_trend.csv")
|
| 415 |
-
|
| 416 |
if show_conf_data:
|
| 417 |
-
st.dataframe(conf_export,
|
| 418 |
st.markdown('</div>', unsafe_allow_html=True)
|
| 419 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 420 |
# ── TOPIC DISTRIBUTION ────────────────────────────────────────
|
| 421 |
st.divider()
|
| 422 |
st.markdown(
|
|
@@ -429,7 +942,6 @@ topic_counts = {
|
|
| 429 |
for label in TOPIC_LABELS
|
| 430 |
}
|
| 431 |
|
| 432 |
-
# Topic pill cards
|
| 433 |
pills = '<div class="topic-grid">'
|
| 434 |
for label in TOPIC_LABELS:
|
| 435 |
color = TOPIC_COLOR[label]
|
|
@@ -445,7 +957,6 @@ st.markdown(pills, unsafe_allow_html=True)
|
|
| 445 |
|
| 446 |
st.markdown('<div class="chart-wrap">', unsafe_allow_html=True)
|
| 447 |
st.markdown('<div class="chart-title">Topic Breakdown</div><div class="chart-sub">All-time message count per topic category</div>', unsafe_allow_html=True)
|
| 448 |
-
|
| 449 |
fig_topic = go.Figure(go.Bar(
|
| 450 |
x=TOPIC_LABELS,
|
| 451 |
y=[topic_counts[l] for l in TOPIC_LABELS],
|
|
@@ -457,19 +968,308 @@ fig_topic = go.Figure(go.Bar(
|
|
| 457 |
hovertemplate="<b>%{x}</b><br>Count: %{y}<extra></extra>",
|
| 458 |
))
|
| 459 |
fig_topic.update_layout(**plotly_layout(250))
|
| 460 |
-
st.plotly_chart(fig_topic,
|
| 461 |
-
|
| 462 |
topic_hdr, topic_dl = st.columns([1, 1])
|
| 463 |
with topic_hdr:
|
| 464 |
show_topic_data = st.checkbox("View data", key="show_topic")
|
| 465 |
with topic_dl:
|
| 466 |
topic_df = pd.DataFrame({"Topic": TOPIC_LABELS, "Count": [topic_counts[l] for l in TOPIC_LABELS]})
|
| 467 |
csv_download(topic_df, "Download CSV", "topic_distribution.csv")
|
| 468 |
-
|
| 469 |
if show_topic_data:
|
| 470 |
-
st.dataframe(topic_df,
|
| 471 |
st.markdown('</div>', unsafe_allow_html=True)
|
| 472 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 473 |
# ── LIVE CHAT FEED ────────────────────────────────────────────
|
| 474 |
st.divider()
|
| 475 |
st.markdown('<div class="sec-hdr"><span class="sec-ttl">Live Chat Feed</span></div>', unsafe_allow_html=True)
|
|
@@ -498,33 +1298,55 @@ with feed_hdr:
|
|
| 498 |
)
|
| 499 |
with feed_dl:
|
| 500 |
if not filtered.empty:
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
else filtered,
|
| 504 |
-
"Download Feed CSV", "chat_feed.csv")
|
| 505 |
|
| 506 |
SENT_ICON = {"Positive": "🟢", "Negative": "🔴", "Neutral": "🟡"}
|
| 507 |
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
conf_pct = int(row.get("confidence", 0) * 100)
|
| 511 |
-
topic = clean_topic(row.get("topic", "General"))
|
| 512 |
-
t_color = TOPIC_COLOR.get(topic, "#6b7280")
|
| 513 |
-
s_color = SENT_COLORS.get(s, "#6b7280")
|
| 514 |
-
s_icon = SENT_ICON.get(s, "⚪")
|
| 515 |
-
conf_color = "#22c55e" if conf_pct >= 70 else "#eab308" if conf_pct >= 40 else "#ef4444"
|
| 516 |
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 528 |
|
| 529 |
# ── AUTO REFRESH ──────────────────────────────────────────────
|
| 530 |
if auto_refresh:
|
|
|
|
| 4 |
import json
|
| 5 |
import pandas as pd
|
| 6 |
import plotly.graph_objects as go
|
| 7 |
+
import plotly.express as px
|
| 8 |
import time
|
| 9 |
import re
|
| 10 |
import sys
|
| 11 |
import os
|
| 12 |
+
import subprocess
|
| 13 |
+
from datetime import datetime, timedelta
|
| 14 |
+
from collections import defaultdict
|
| 15 |
|
| 16 |
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'backend'))
|
| 17 |
from config import REDIS_HOST, REDIS_PORT, REDIS_DB
|
|
|
|
| 25 |
|
| 26 |
r = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB, decode_responses=True)
|
| 27 |
|
| 28 |
+
TOPIC_LABELS = ["Appreciation", "Question", "Promo", "Spam", "General", "MCQ Answer"]
|
| 29 |
TOPIC_COLOR = {
|
| 30 |
"Appreciation": "#f59e0b", "Question": "#3b82f6",
|
| 31 |
+
"Promo": "#ec4899", "Spam": "#ef4444", "General": "#6b7280",
|
| 32 |
+
"MCQ Answer": "#10b981"
|
| 33 |
}
|
| 34 |
SENT_COLORS = {"Positive": "#22c55e", "Neutral": "#eab308", "Negative": "#ef4444"}
|
| 35 |
|
|
|
|
| 44 |
const m = bg.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);
|
| 45 |
if (m) { isDark = (0.299*m[1] + 0.587*m[2] + 0.114*m[3]) < 128; }
|
| 46 |
else {
|
|
|
|
| 47 |
const bodyBg = window.parent.getComputedStyle(window.parent.document.body).backgroundColor;
|
| 48 |
const m2 = bodyBg.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);
|
| 49 |
if (m2) { isDark = (0.299*m2[1] + 0.587*m2[2] + 0.114*m2[3]) < 128; }
|
|
|
|
| 69 |
--shadow:0 4px 24px rgba(0,0,0,0.4); --shadow-sm:0 2px 8px rgba(0,0,0,0.3);
|
| 70 |
--pill-bg:rgba(124,58,237,0.15); --pill-border:rgba(124,58,237,0.3); --pill-text:#a78bfa;
|
| 71 |
--plotly-paper:rgba(0,0,0,0); --plotly-plot:rgba(255,255,255,0.015); --plotly-grid:rgba(255,255,255,0.05); --plotly-text:#94a3b8;
|
| 72 |
+
--alert-bg:rgba(239,68,68,0.1); --alert-border:rgba(239,68,68,0.3);
|
| 73 |
+
--pin-bg:rgba(234,179,8,0.1); --pin-border:rgba(234,179,8,0.35);
|
| 74 |
}
|
| 75 |
[data-livepulse="light"] {
|
| 76 |
--bg:#f4f6ff; --bg-card:#ffffff; --border:rgba(99,102,241,0.12);
|
|
|
|
| 81 |
--shadow:0 4px 24px rgba(99,102,241,0.12); --shadow-sm:0 2px 8px rgba(99,102,241,0.08);
|
| 82 |
--pill-bg:rgba(109,40,217,0.08); --pill-border:rgba(109,40,217,0.2); --pill-text:#6d28d9;
|
| 83 |
--plotly-paper:rgba(0,0,0,0); --plotly-plot:rgba(255,255,255,0.7); --plotly-grid:rgba(0,0,0,0.06); --plotly-text:#475569;
|
| 84 |
+
--alert-bg:rgba(239,68,68,0.07); --alert-border:rgba(239,68,68,0.25);
|
| 85 |
+
--pin-bg:rgba(234,179,8,0.08); --pin-border:rgba(234,179,8,0.3);
|
| 86 |
}
|
| 87 |
|
| 88 |
html,body,[data-testid="stAppViewContainer"],[data-testid="stMain"],.main .block-container {
|
|
|
|
| 103 |
[data-testid="stMetricDelta"]{color:var(--accent-text)!important;}
|
| 104 |
|
| 105 |
.stTextInput input { background:var(--input-bg)!important; border:1px solid var(--input-border)!important; border-radius:10px!important; color:var(--text-1)!important; }
|
| 106 |
+
.stTextInput input::placeholder { color:var(--text-3)!important; opacity:1!important; }
|
| 107 |
+
[data-testid="stSidebar"] .stTextInput input { background:#1a1a2e!important; border:1px solid rgba(124,58,237,0.4)!important; color:#f1f5f9!important; font-weight:500!important; }
|
| 108 |
+
[data-testid="stSidebar"] .stTextInput input::placeholder { color:#64748b!important; }
|
| 109 |
+
[data-testid="stSidebar"] .stTextInput input:focus { border-color:var(--accent)!important; box-shadow:0 0 0 2px rgba(124,58,237,0.2)!important; outline:none!important; }
|
| 110 |
+
[data-testid="stSidebar"] label { color:var(--text-2)!important; }
|
| 111 |
[data-baseweb="select"]>div { background:var(--input-bg)!important; border:1px solid var(--input-border)!important; border-radius:10px!important; color:var(--text-1)!important; }
|
| 112 |
.stButton>button { background:linear-gradient(135deg,var(--accent),var(--accent2))!important; color:#fff!important; border:none!important; border-radius:10px!important; font-weight:600!important; font-family:'Space Grotesk',sans-serif!important; box-shadow:0 4px 16px rgba(124,58,237,0.3)!important; transition:all 0.2s!important; }
|
| 113 |
.stButton>button:hover{transform:translateY(-2px)!important;}
|
| 114 |
hr{border:none!important;border-top:1px solid var(--divider)!important;margin:1.2rem 0!important;}
|
| 115 |
[data-testid="stSidebar"] label,[data-testid="stSidebar"] .stMarkdown p{color:var(--text-2)!important;font-size:0.83rem!important;}
|
| 116 |
|
| 117 |
+
[data-testid="stDownloadButton"]>button { background:var(--bg-card)!important; color:var(--text-2)!important; border:1px solid var(--border)!important; border-radius:8px!important; font-size:0.75rem!important; box-shadow:none!important; }
|
| 118 |
+
[data-testid="stDownloadButton"]>button:hover { background:var(--pill-bg)!important; color:var(--accent-text)!important; border-color:var(--pill-border)!important; }
|
| 119 |
+
|
| 120 |
+
[data-testid="stCheckbox"] label, [data-testid="stCheckbox"] span { color:var(--text-2)!important; font-size:0.82rem!important; }
|
| 121 |
+
[data-testid="stCheckbox"] [data-testid="stWidgetLabel"] { color:var(--text-2)!important; }
|
| 122 |
|
| 123 |
@keyframes pulse{0%{box-shadow:0 0 0 0 rgba(34,197,94,0.7);}70%{box-shadow:0 0 0 10px rgba(34,197,94,0);}100%{box-shadow:0 0 0 0 rgba(34,197,94,0);}}
|
| 124 |
.live-dot{display:inline-block;width:9px;height:9px;background:var(--live);border-radius:50%;animation:pulse 1.8s infinite;margin-right:6px;vertical-align:middle;}
|
| 125 |
|
| 126 |
+
@keyframes alertPulse{0%{opacity:1;}50%{opacity:0.7;}100%{opacity:1;}}
|
| 127 |
+
.alert-banner{background:var(--alert-bg);border:1px solid var(--alert-border);border-radius:14px;padding:14px 18px;margin:12px 0;display:flex;align-items:center;gap:12px;animation:alertPulse 2s infinite;}
|
| 128 |
+
.alert-icon{font-size:1.4rem;}
|
| 129 |
+
.alert-text{font-size:0.88rem;font-weight:600;color:#ef4444;}
|
| 130 |
+
.alert-sub{font-size:0.75rem;color:var(--text-3);margin-top:2px;}
|
| 131 |
+
|
| 132 |
.stat-grid{display:flex;gap:12px;margin:10px 0 18px;flex-wrap:wrap;}
|
| 133 |
.stat-card{flex:1;min-width:130px;background:var(--bg-card);border:1px solid var(--border);border-radius:20px;padding:22px 18px;text-align:center;transition:transform 0.2s,box-shadow 0.2s,background 0.3s;position:relative;overflow:hidden;box-shadow:var(--shadow-sm);}
|
| 134 |
.stat-card:hover{transform:translateY(-4px);box-shadow:var(--shadow);}
|
|
|
|
| 137 |
.stat-label{font-size:0.82rem;color:var(--text-2);font-weight:600;text-transform:uppercase;letter-spacing:0.06em;}
|
| 138 |
.stat-sub{font-size:0.7rem;color:var(--text-3);margin-top:4px;}
|
| 139 |
|
| 140 |
+
.velocity-card{background:var(--bg-card);border:1px solid var(--border);border-radius:20px;padding:18px 22px;box-shadow:var(--shadow-sm);display:flex;align-items:center;gap:16px;}
|
| 141 |
+
.velocity-arrow{font-size:2rem;line-height:1;}
|
| 142 |
+
.velocity-val{font-size:1.6rem;font-weight:800;letter-spacing:-0.03em;}
|
| 143 |
+
.velocity-label{font-size:0.75rem;color:var(--text-3);font-weight:600;text-transform:uppercase;letter-spacing:0.06em;margin-top:2px;}
|
| 144 |
+
|
| 145 |
.sec-hdr{display:flex;align-items:center;gap:10px;margin:6px 0 14px;}
|
| 146 |
.sec-ttl{font-size:1rem;font-weight:700;color:var(--text-1);letter-spacing:-0.01em;}
|
| 147 |
.sec-pill{background:var(--pill-bg);border:1px solid var(--pill-border);border-radius:20px;padding:2px 10px;font-size:0.68rem;color:var(--pill-text);font-weight:700;text-transform:uppercase;letter-spacing:0.08em;}
|
|
|
|
| 160 |
.chat-card{background:var(--bg-card);border:1px solid var(--border);border-radius:16px;padding:14px 16px;margin-bottom:10px;border-left:3px solid transparent;animation:slideIn 0.2s ease;transition:background 0.2s,transform 0.15s,box-shadow 0.2s;box-shadow:var(--shadow-sm);}
|
| 161 |
.chat-card:hover{transform:translateX(4px);box-shadow:var(--shadow);}
|
| 162 |
.chat-positive{border-left-color:#22c55e;} .chat-negative{border-left-color:#ef4444;} .chat-neutral{border-left-color:#eab308;}
|
| 163 |
+
.chat-pinned{border-left-color:#eab308!important;background:var(--pin-bg)!important;border-color:var(--pin-border)!important;}
|
| 164 |
.chat-author{font-weight:700;font-size:0.83rem;color:var(--accent-text);margin-bottom:5px;}
|
| 165 |
.chat-text{font-size:0.92rem;color:var(--text-2);line-height:1.55;margin-bottom:9px;}
|
| 166 |
.chat-badges{display:flex;gap:6px;flex-wrap:wrap;}
|
| 167 |
.badge{display:inline-flex;align-items:center;background:var(--badge-bg);border:1px solid var(--border);border-radius:20px;padding:3px 10px;font-size:0.7rem;font-weight:600;color:var(--text-2);}
|
| 168 |
+
.pin-badge{background:rgba(234,179,8,0.15);border-color:rgba(234,179,8,0.4);color:#eab308;}
|
| 169 |
+
|
| 170 |
+
.compare-label{font-size:0.72rem;font-weight:700;text-transform:uppercase;letter-spacing:0.08em;padding:3px 10px;border-radius:20px;display:inline-block;margin-bottom:8px;}
|
| 171 |
+
|
| 172 |
+
.engage-card{background:var(--bg-card);border:1px solid var(--border);border-radius:20px;padding:20px 24px;box-shadow:var(--shadow-sm);position:relative;overflow:hidden;}
|
| 173 |
+
.engage-score{font-size:3rem;font-weight:800;letter-spacing:-0.04em;line-height:1;}
|
| 174 |
+
.engage-label{font-size:0.75rem;color:var(--text-3);font-weight:600;text-transform:uppercase;letter-spacing:0.08em;margin-top:4px;}
|
| 175 |
+
.engage-bar-bg{background:var(--border);border-radius:99px;height:6px;margin-top:12px;overflow:hidden;}
|
| 176 |
+
.engage-bar-fill{height:6px;border-radius:99px;transition:width 0.6s ease;}
|
| 177 |
+
.engage-breakdown{display:flex;gap:16px;margin-top:10px;flex-wrap:wrap;}
|
| 178 |
+
.engage-item{font-size:0.72rem;color:var(--text-3);}
|
| 179 |
+
.engage-item span{font-weight:700;color:var(--text-2);}
|
| 180 |
+
|
| 181 |
+
.leaderboard-row{display:flex;align-items:center;gap:12px;padding:10px 14px;background:var(--bg-card);border:1px solid var(--border);border-radius:14px;margin-bottom:8px;transition:transform 0.15s,box-shadow 0.15s;}
|
| 182 |
+
.leaderboard-row:hover{transform:translateX(4px);box-shadow:var(--shadow);}
|
| 183 |
+
.lb-rank{font-size:1rem;font-weight:800;color:var(--text-3);min-width:28px;}
|
| 184 |
+
.lb-rank.gold{color:#f59e0b;} .lb-rank.silver{color:#94a3b8;} .lb-rank.bronze{color:#b45309;}
|
| 185 |
+
.lb-author{font-size:0.85rem;font-weight:700;color:var(--text-1);flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
|
| 186 |
+
.lb-count{font-size:0.78rem;color:var(--text-3);min-width:40px;text-align:right;}
|
| 187 |
+
.lb-bar{flex:2;height:5px;background:var(--border);border-radius:99px;overflow:hidden;}
|
| 188 |
+
.lb-bar-fill{height:5px;border-radius:99px;}
|
| 189 |
+
.lb-sent{display:flex;gap:4px;min-width:80px;justify-content:flex-end;}
|
| 190 |
+
.lb-dot{width:8px;height:8px;border-radius:50%;display:inline-block;}
|
| 191 |
+
|
| 192 |
+
.spam-alert{background:rgba(239,68,68,0.08);border:1px solid rgba(239,68,68,0.25);border-radius:14px;padding:14px 18px;margin:12px 0;display:flex;align-items:center;gap:12px;}
|
| 193 |
+
.spam-alert-text{font-size:0.88rem;font-weight:600;color:#ef4444;}
|
| 194 |
+
.spam-alert-sub{font-size:0.75rem;color:var(--text-3);margin-top:2px;}
|
| 195 |
|
| 196 |
.empty-state{text-align:center;padding:80px 20px;background:var(--bg-card);border:1px solid var(--border);border-radius:24px;margin:40px 0;box-shadow:var(--shadow-sm);}
|
| 197 |
.empty-icon{font-size:3.5rem;margin-bottom:16px;}
|
|
|
|
| 221 |
with open(config_path, 'w') as f:
|
| 222 |
f.write(content)
|
| 223 |
|
| 224 |
+
def fetch_video_title(video_id):
|
| 225 |
+
try:
|
| 226 |
+
import urllib.request
|
| 227 |
+
url = f"https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v={video_id}&format=json"
|
| 228 |
+
with urllib.request.urlopen(url, timeout=5) as resp:
|
| 229 |
+
return json.loads(resp.read())["title"]
|
| 230 |
+
except Exception:
|
| 231 |
+
return None
|
| 232 |
+
|
| 233 |
def clean_topic(val):
|
|
|
|
| 234 |
if pd.isna(val) or str(val).strip() == "" or str(val).strip().lower() == "nan":
|
| 235 |
return "General"
|
| 236 |
return str(val).strip()
|
|
|
|
| 260 |
st.download_button(label=f"⬇ {label}", data=csv,
|
| 261 |
file_name=filename, mime="text/csv", key=filename)
|
| 262 |
|
| 263 |
+
@st.cache_data(ttl=5, show_spinner=False)
|
| 264 |
+
def load_stream_data(redis_key: str, limit: int | None = None):
|
| 265 |
+
"""Load and parse messages from a Redis key. Cached for 5s to avoid redundant reads."""
|
| 266 |
+
if limit:
|
| 267 |
+
raws = r.lrange(redis_key, -limit, -1)
|
| 268 |
+
else:
|
| 269 |
+
raws = r.lrange(redis_key, 0, -1)
|
| 270 |
+
data = []
|
| 271 |
+
for raw in raws:
|
| 272 |
+
try:
|
| 273 |
+
data.append(json.loads(raw))
|
| 274 |
+
except Exception:
|
| 275 |
+
pass
|
| 276 |
+
return data
|
| 277 |
+
|
| 278 |
+
@st.cache_data(ttl=10, show_spinner=False)
|
| 279 |
+
def compute_velocity(df_all_json: str, window: int = 20) -> dict:
|
| 280 |
+
"""
|
| 281 |
+
Compute sentiment velocity. Accepts JSON string for cache key compatibility.
|
| 282 |
+
"""
|
| 283 |
+
import json as _json
|
| 284 |
+
sentiments = [m.get("sentiment", "Neutral") for m in _json.loads(df_all_json)]
|
| 285 |
+
n = len(sentiments)
|
| 286 |
+
if n < window * 2:
|
| 287 |
+
return {"direction": "→", "delta": 0.0, "label": "Stable", "color": "#eab308"}
|
| 288 |
+
recent = sentiments[-window:]
|
| 289 |
+
prev = sentiments[-window*2:-window]
|
| 290 |
+
r_pos = sum(1 for s in recent if s == "Positive") / window
|
| 291 |
+
p_pos = sum(1 for s in prev if s == "Positive") / window
|
| 292 |
+
delta = r_pos - p_pos
|
| 293 |
+
if delta > 0.08:
|
| 294 |
+
return {"direction": "↑", "delta": delta, "label": "Rising", "color": "#22c55e"}
|
| 295 |
+
elif delta < -0.08:
|
| 296 |
+
return {"direction": "↓", "delta": delta, "label": "Falling", "color": "#ef4444"}
|
| 297 |
+
return {"direction": "→", "delta": delta, "label": "Stable", "color": "#eab308"}
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
@st.cache_data(ttl=10, show_spinner=False)
|
| 301 |
+
def build_heatmap_data(df_all_json: str, bucket_minutes: int = 1) -> pd.DataFrame:
|
| 302 |
+
"""
|
| 303 |
+
Bucket messages into time intervals. Accepts JSON string for cache key compatibility.
|
| 304 |
+
"""
|
| 305 |
+
import json as _json
|
| 306 |
+
records = _json.loads(df_all_json)
|
| 307 |
+
if not records:
|
| 308 |
+
return pd.DataFrame()
|
| 309 |
+
df_t = pd.DataFrame(records)
|
| 310 |
+
if "time" not in df_t.columns:
|
| 311 |
+
return pd.DataFrame()
|
| 312 |
+
df_t["time"] = pd.to_datetime(df_t["time"], errors="coerce")
|
| 313 |
+
df_t = df_t.dropna(subset=["time"])
|
| 314 |
+
if df_t.empty:
|
| 315 |
+
return pd.DataFrame()
|
| 316 |
+
df_t["bucket"] = df_t["time"].dt.floor(f"{bucket_minutes}min")
|
| 317 |
+
grouped = df_t.groupby(["bucket", "sentiment"]).size().unstack(fill_value=0)
|
| 318 |
+
for col in ["Positive", "Neutral", "Negative"]:
|
| 319 |
+
if col not in grouped.columns:
|
| 320 |
+
grouped[col] = 0
|
| 321 |
+
grouped = grouped.reset_index()
|
| 322 |
+
grouped.columns.name = None
|
| 323 |
+
return grouped[["bucket", "Positive", "Neutral", "Negative"]]
|
| 324 |
+
|
| 325 |
+
def check_alert(df_all: pd.DataFrame, threshold: float = 0.4, window: int = 15) -> dict | None:
|
| 326 |
+
"""Return alert info if negative ratio in last `window` messages exceeds threshold."""
|
| 327 |
+
if len(df_all) < window:
|
| 328 |
+
return None
|
| 329 |
+
recent = df_all.iloc[-window:]
|
| 330 |
+
neg_ratio = (recent["sentiment"] == "Negative").mean()
|
| 331 |
+
if neg_ratio >= threshold:
|
| 332 |
+
return {
|
| 333 |
+
"neg_ratio": neg_ratio,
|
| 334 |
+
"count": int((recent["sentiment"] == "Negative").sum()),
|
| 335 |
+
"window": window,
|
| 336 |
+
}
|
| 337 |
+
return None
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
@st.cache_data(ttl=10, show_spinner=False)
|
| 341 |
+
def compute_engagement(all_data_json: str, window: int = 50) -> dict:
|
| 342 |
+
"""
|
| 343 |
+
Engagement score (0–100) = weighted combo of:
|
| 344 |
+
- message rate (msgs per minute, last window)
|
| 345 |
+
- positive ratio (last window)
|
| 346 |
+
- question density (last window)
|
| 347 |
+
"""
|
| 348 |
+
import json as _j
|
| 349 |
+
msgs = _j.loads(all_data_json)
|
| 350 |
+
if not msgs:
|
| 351 |
+
return {"score": 0, "rate": 0.0, "pos_ratio": 0.0, "q_density": 0.0, "grade": "—"}
|
| 352 |
+
|
| 353 |
+
recent = msgs[-window:]
|
| 354 |
+
n = len(recent)
|
| 355 |
+
|
| 356 |
+
# Message rate: msgs per minute using timestamps
|
| 357 |
+
rate = 0.0
|
| 358 |
+
try:
|
| 359 |
+
t0 = datetime.fromisoformat(recent[0]["time"])
|
| 360 |
+
t1 = datetime.fromisoformat(recent[-1]["time"])
|
| 361 |
+
elapsed = max((t1 - t0).total_seconds() / 60, 0.1)
|
| 362 |
+
rate = round(n / elapsed, 1)
|
| 363 |
+
except Exception:
|
| 364 |
+
rate = float(n)
|
| 365 |
+
|
| 366 |
+
pos_ratio = sum(1 for m in recent if m.get("sentiment") == "Positive") / max(n, 1)
|
| 367 |
+
q_density = sum(1 for m in recent if m.get("topic") == "Question") / max(n, 1)
|
| 368 |
+
|
| 369 |
+
# Normalise rate: cap at 60 msgs/min = 100%
|
| 370 |
+
rate_norm = min(rate / 60, 1.0)
|
| 371 |
+
score = round((rate_norm * 0.4 + pos_ratio * 0.4 + q_density * 0.2) * 100)
|
| 372 |
+
|
| 373 |
+
if score >= 70: grade = "🔥 High"
|
| 374 |
+
elif score >= 40: grade = "⚡ Medium"
|
| 375 |
+
else: grade = "💤 Low"
|
| 376 |
+
|
| 377 |
+
return {"score": score, "rate": rate, "pos_ratio": pos_ratio, "q_density": q_density, "grade": grade}
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
@st.cache_data(ttl=10, show_spinner=False)
|
| 381 |
+
def compute_top_contributors(all_data_json: str, top_n: int = 10) -> list[dict]:
|
| 382 |
+
"""Return top N authors by message count with their sentiment breakdown."""
|
| 383 |
+
import json as _j
|
| 384 |
+
from collections import Counter
|
| 385 |
+
msgs = _j.loads(all_data_json)
|
| 386 |
+
if not msgs:
|
| 387 |
+
return []
|
| 388 |
+
|
| 389 |
+
author_data: dict[str, dict] = {}
|
| 390 |
+
for m in msgs:
|
| 391 |
+
a = m.get("author", "Unknown")
|
| 392 |
+
if a not in author_data:
|
| 393 |
+
author_data[a] = {"count": 0, "Positive": 0, "Neutral": 0, "Negative": 0}
|
| 394 |
+
author_data[a]["count"] += 1
|
| 395 |
+
s = m.get("sentiment", "Neutral")
|
| 396 |
+
if s in author_data[a]:
|
| 397 |
+
author_data[a][s] += 1
|
| 398 |
+
|
| 399 |
+
sorted_authors = sorted(author_data.items(), key=lambda x: x[1]["count"], reverse=True)[:top_n]
|
| 400 |
+
result = []
|
| 401 |
+
for author, d in sorted_authors:
|
| 402 |
+
total = max(d["count"], 1)
|
| 403 |
+
result.append({
|
| 404 |
+
"author": author,
|
| 405 |
+
"count": d["count"],
|
| 406 |
+
"pos_pct": round(d["Positive"] / total * 100),
|
| 407 |
+
"neu_pct": round(d["Neutral"] / total * 100),
|
| 408 |
+
"neg_pct": round(d["Negative"] / total * 100),
|
| 409 |
+
})
|
| 410 |
+
return result
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
@st.cache_data(ttl=10, show_spinner=False)
|
| 414 |
+
def compute_word_freq(all_data_json: str, sentiment_filter: str = "All",
|
| 415 |
+
topic_filter: str = "All", top_n: int = 60) -> list[tuple[str, int]]:
|
| 416 |
+
"""Return top N (word, count) pairs after filtering stopwords."""
|
| 417 |
+
import json as _j
|
| 418 |
+
from collections import Counter
|
| 419 |
+
|
| 420 |
+
STOPWORDS = {
|
| 421 |
+
"the","a","an","is","it","in","on","at","to","of","and","or","but","for",
|
| 422 |
+
"with","this","that","are","was","be","as","by","from","have","has","had",
|
| 423 |
+
"not","no","so","if","do","did","will","can","just","i","you","he","she",
|
| 424 |
+
"we","they","my","your","his","her","our","their","me","him","us","them",
|
| 425 |
+
"what","how","why","when","where","who","which","there","here","been",
|
| 426 |
+
"would","could","should","may","might","shall","than","then","now","also",
|
| 427 |
+
"more","very","too","up","out","about","into","over","after","before",
|
| 428 |
+
"yaar","bhi","hai","hain","ho","kar","ke","ki","ka","ko","se","ne","ye",
|
| 429 |
+
"vo","woh","aur","nahi","nhi","toh","toh","koi","kuch","ab","ek","hi",
|
| 430 |
+
}
|
| 431 |
+
|
| 432 |
+
msgs = _j.loads(all_data_json)
|
| 433 |
+
words: list[str] = []
|
| 434 |
+
for m in msgs:
|
| 435 |
+
if sentiment_filter != "All" and m.get("sentiment") != sentiment_filter:
|
| 436 |
+
continue
|
| 437 |
+
if topic_filter != "All" and m.get("topic") != topic_filter:
|
| 438 |
+
continue
|
| 439 |
+
text = re.sub(r"[^\w\s]", " ", m.get("text", "").lower())
|
| 440 |
+
for w in text.split():
|
| 441 |
+
if len(w) > 2 and w not in STOPWORDS and not w.isdigit():
|
| 442 |
+
words.append(w)
|
| 443 |
+
|
| 444 |
+
return Counter(words).most_common(top_n)
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
def check_spam_alert(df_all: pd.DataFrame, threshold: float = 0.3, window: int = 20) -> dict | None:
|
| 448 |
+
"""Return alert if spam ratio in last `window` messages exceeds threshold."""
|
| 449 |
+
if "topic" not in df_all.columns or len(df_all) < window:
|
| 450 |
+
return None
|
| 451 |
+
recent = df_all.iloc[-window:]
|
| 452 |
+
spam_ratio = (recent["topic"] == "Spam").mean()
|
| 453 |
+
if spam_ratio >= threshold:
|
| 454 |
+
return {
|
| 455 |
+
"spam_ratio": spam_ratio,
|
| 456 |
+
"count": int((recent["topic"] == "Spam").sum()),
|
| 457 |
+
"window": window,
|
| 458 |
+
}
|
| 459 |
+
return None
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
# ── SESSION STATE INIT ────────────────────────────────────────
|
| 463 |
+
MAX_STREAMS = 5
|
| 464 |
+
STREAM_COLORS = ["#7c3aed", "#10b981", "#f59e0b", "#3b82f6", "#ec4899"]
|
| 465 |
+
STREAM_NAMES = ["A", "B", "C", "D", "E"]
|
| 466 |
+
|
| 467 |
+
if "pinned_messages" not in st.session_state:
|
| 468 |
+
st.session_state.pinned_messages = []
|
| 469 |
+
if "alert_dismissed" not in st.session_state:
|
| 470 |
+
st.session_state.alert_dismissed = False
|
| 471 |
+
if "last_alert_count" not in st.session_state:
|
| 472 |
+
st.session_state.last_alert_count = 0
|
| 473 |
+
# Multi-stream: list of dicts {video_id, redis_key, label, proc}
|
| 474 |
+
if "streams" not in st.session_state:
|
| 475 |
+
st.session_state.streams = [
|
| 476 |
+
{"video_id": "", "redis_key": "chat_messages", "label": "Stream A", "proc": None}
|
| 477 |
+
]
|
| 478 |
|
| 479 |
# ── SIDEBAR ──────────────────────────────────────────────────
|
| 480 |
with st.sidebar:
|
|
|
|
| 485 |
'</div>', unsafe_allow_html=True
|
| 486 |
)
|
| 487 |
st.divider()
|
| 488 |
+
|
| 489 |
+
# ── Display Settings ──
|
| 490 |
st.markdown('<p style="font-size:0.68rem;font-weight:700;color:var(--accent);text-transform:uppercase;letter-spacing:0.1em;margin-bottom:8px;">Display Settings</p>', unsafe_allow_html=True)
|
| 491 |
refresh_rate = st.slider("Refresh interval (s)", 5, 60, 15)
|
| 492 |
msg_limit = st.slider("Message window", 10, 200, 50)
|
| 493 |
auto_refresh = st.toggle("Live auto-refresh", value=True)
|
| 494 |
st.divider()
|
| 495 |
+
|
| 496 |
+
# ── Alert Settings ──
|
| 497 |
+
st.markdown('<p style="font-size:0.68rem;font-weight:700;color:var(--accent);text-transform:uppercase;letter-spacing:0.1em;margin-bottom:8px;">Alert Settings</p>', unsafe_allow_html=True)
|
| 498 |
+
alert_enabled = st.toggle("Negative spike alerts", value=True)
|
| 499 |
+
alert_threshold = st.slider("Neg alert threshold (%)", 20, 80, 40) / 100
|
| 500 |
+
alert_window = st.slider("Alert window (msgs)", 5, 30, 15)
|
| 501 |
+
spam_alert_on = st.toggle("Spam rate alerts", value=True)
|
| 502 |
+
spam_threshold = st.slider("Spam alert threshold (%)", 10, 60, 30) / 100
|
| 503 |
+
st.divider()
|
| 504 |
+
|
| 505 |
+
# ── Multi-Stream Scraper Control ──
|
| 506 |
+
st.markdown('<p style="font-size:0.68rem;font-weight:700;color:var(--accent);text-transform:uppercase;letter-spacing:0.1em;margin-bottom:8px;">Stream Control</p>', unsafe_allow_html=True)
|
| 507 |
+
|
| 508 |
+
import importlib
|
| 509 |
+
import config as _cfg
|
| 510 |
+
importlib.reload(_cfg)
|
| 511 |
+
|
| 512 |
+
# Pre-fill Stream A video_id from config on first load
|
| 513 |
+
if st.session_state.streams[0]["video_id"] == "":
|
| 514 |
+
st.session_state.streams[0]["video_id"] = _cfg.VIDEO_ID
|
| 515 |
+
|
| 516 |
+
for idx, stream in enumerate(st.session_state.streams):
|
| 517 |
+
color = STREAM_COLORS[idx]
|
| 518 |
+
label = STREAM_NAMES[idx]
|
| 519 |
+
st.markdown(
|
| 520 |
+
f'<div style="font-size:0.72rem;font-weight:700;color:{color};text-transform:uppercase;'
|
| 521 |
+
f'letter-spacing:0.08em;margin:10px 0 4px;border-left:3px solid {color};padding-left:8px;">'
|
| 522 |
+
f'Stream {label}</div>',
|
| 523 |
+
unsafe_allow_html=True
|
| 524 |
+
)
|
| 525 |
+
# Use widget key as the source of truth — never override with value= after first set
|
| 526 |
+
vid_skey = f"vid_{idx}"
|
| 527 |
+
rkey_skey = f"rkey_{idx}"
|
| 528 |
+
if vid_skey not in st.session_state:
|
| 529 |
+
st.session_state[vid_skey] = stream["video_id"]
|
| 530 |
+
if rkey_skey not in st.session_state:
|
| 531 |
+
st.session_state[rkey_skey] = stream["redis_key"]
|
| 532 |
+
|
| 533 |
+
st.text_input("Video ID / URL", placeholder="e.g. eFSK2-QRB0A", key=vid_skey)
|
| 534 |
+
st.text_input("Redis key", placeholder=f"chat_messages_{label.lower()}", key=rkey_skey)
|
| 535 |
+
|
| 536 |
+
sc1, sc2 = st.columns(2)
|
| 537 |
+
with sc1:
|
| 538 |
+
if st.button("▶ Start", key=f"start_{idx}", width='stretch'):
|
| 539 |
+
vid = extract_video_id(st.session_state[vid_skey])
|
| 540 |
+
rkey = st.session_state[rkey_skey].strip() or f"chat_messages_{label.lower()}"
|
| 541 |
+
if vid:
|
| 542 |
+
# Stop existing proc for this slot
|
| 543 |
+
old_proc = st.session_state.streams[idx].get("proc")
|
| 544 |
+
if old_proc and old_proc.poll() is None:
|
| 545 |
+
old_proc.terminate()
|
| 546 |
+
proc = subprocess.Popen(
|
| 547 |
+
[sys.executable, "-m", "backend.scraper",
|
| 548 |
+
"--video_id", vid, "--redis_key", rkey],
|
| 549 |
+
cwd=os.path.abspath(os.path.join(os.path.dirname(__file__), "..")),
|
| 550 |
+
stdout=subprocess.DEVNULL,
|
| 551 |
+
stderr=subprocess.DEVNULL,
|
| 552 |
+
)
|
| 553 |
+
st.session_state.streams[idx]["proc"] = proc
|
| 554 |
+
st.session_state.streams[idx]["video_id"] = vid
|
| 555 |
+
st.session_state.streams[idx]["redis_key"] = rkey
|
| 556 |
+
# Store title for stream A only (page header)
|
| 557 |
+
if idx == 0:
|
| 558 |
+
update_config_video_id(vid)
|
| 559 |
+
title = fetch_video_title(vid)
|
| 560 |
+
r.set("video_title", title) if title else r.delete("video_title")
|
| 561 |
+
st.session_state.alert_dismissed = False
|
| 562 |
+
st.success(f"Stream {label} started → `{rkey}`")
|
| 563 |
+
else:
|
| 564 |
+
st.error("Invalid video ID")
|
| 565 |
+
with sc2:
|
| 566 |
+
if st.button("⏹ Stop", key=f"stop_{idx}", width='stretch'):
|
| 567 |
+
proc = st.session_state.streams[idx].get("proc")
|
| 568 |
+
if proc and proc.poll() is None:
|
| 569 |
+
proc.terminate()
|
| 570 |
+
st.session_state.streams[idx]["proc"] = None
|
| 571 |
+
st.success(f"Stream {label} stopped")
|
| 572 |
+
else:
|
| 573 |
+
st.warning("Not running")
|
| 574 |
+
|
| 575 |
+
proc = st.session_state.streams[idx].get("proc")
|
| 576 |
+
running = proc is not None and proc.poll() is None
|
| 577 |
+
dot_color = "#22c55e" if running else "#ef4444"
|
| 578 |
+
status = "running" if running else "stopped"
|
| 579 |
+
st.markdown(f'<div style="font-size:0.72rem;color:{dot_color};margin-bottom:4px;">● {status}</div>', unsafe_allow_html=True)
|
| 580 |
+
|
| 581 |
+
st.divider()
|
| 582 |
+
|
| 583 |
+
# ── Add / Remove stream slots ──
|
| 584 |
+
add_col, rem_col = st.columns(2)
|
| 585 |
+
with add_col:
|
| 586 |
+
if len(st.session_state.streams) < MAX_STREAMS:
|
| 587 |
+
if st.button("+ Add stream", width='stretch'):
|
| 588 |
+
n = len(st.session_state.streams)
|
| 589 |
+
st.session_state.streams.append({
|
| 590 |
+
"video_id": "",
|
| 591 |
+
"redis_key": f"chat_messages_{STREAM_NAMES[n].lower()}",
|
| 592 |
+
"label": f"Stream {STREAM_NAMES[n]}",
|
| 593 |
+
"proc": None,
|
| 594 |
+
})
|
| 595 |
+
st.rerun()
|
| 596 |
+
with rem_col:
|
| 597 |
+
if len(st.session_state.streams) > 1:
|
| 598 |
+
if st.button("- Remove last", width='stretch'):
|
| 599 |
+
removed = st.session_state.streams.pop()
|
| 600 |
+
proc = removed.get("proc")
|
| 601 |
+
if proc and proc.poll() is None:
|
| 602 |
+
proc.terminate()
|
| 603 |
+
st.rerun()
|
| 604 |
+
|
| 605 |
+
st.divider()
|
| 606 |
+
|
| 607 |
+
# ── Pinned Messages ──
|
| 608 |
+
st.markdown('<p style="font-size:0.68rem;font-weight:700;color:var(--accent);text-transform:uppercase;letter-spacing:0.1em;margin-bottom:8px;">Pinned Messages</p>', unsafe_allow_html=True)
|
| 609 |
+
pin_count = len(st.session_state.pinned_messages)
|
| 610 |
+
st.markdown(f'<div style="font-size:0.78rem;color:var(--text-3);">{pin_count} message{"s" if pin_count != 1 else ""} pinned</div>', unsafe_allow_html=True)
|
| 611 |
+
if pin_count > 0 and st.button("🗑 Clear pins", width='stretch'):
|
| 612 |
+
st.session_state.pinned_messages = []
|
| 613 |
+
st.rerun()
|
| 614 |
+
st.divider()
|
| 615 |
+
|
| 616 |
+
# ── Danger Zone ──
|
| 617 |
st.markdown('<p style="font-size:0.68rem;font-weight:700;color:#ef4444;text-transform:uppercase;letter-spacing:0.1em;margin-bottom:8px;">Danger Zone</p>', unsafe_allow_html=True)
|
| 618 |
+
if st.button("🗑 Clear all data", width='stretch'):
|
| 619 |
+
for s in st.session_state.streams:
|
| 620 |
+
r.delete(s["redis_key"])
|
| 621 |
+
st.session_state.pinned_messages = []
|
| 622 |
+
st.session_state.alert_dismissed = False
|
| 623 |
+
st.success("All stream data cleared.")
|
| 624 |
st.divider()
|
| 625 |
st.markdown(
|
| 626 |
'<div style="font-size:0.72rem;color:var(--text-3);text-align:center;line-height:1.6;">'
|
|
|
|
| 629 |
'</div>', unsafe_allow_html=True
|
| 630 |
)
|
| 631 |
|
| 632 |
+
|
| 633 |
# ── PAGE HEADER ───────────────────────────────────────────────
|
| 634 |
+
_video_title = r.get("video_title")
|
| 635 |
+
_subtitle = f"▶ {_video_title}" if _video_title else "Real-time sentiment · topic classification · engagement insights"
|
| 636 |
+
|
| 637 |
col_title, col_live = st.columns([7, 1])
|
| 638 |
with col_title:
|
| 639 |
st.markdown(
|
| 640 |
'<div style="padding:8px 0 4px;">'
|
| 641 |
'<div style="font-size:2rem;font-weight:800;color:var(--text-1);letter-spacing:-0.04em;">YouTube Live Chat Analytics</div>'
|
| 642 |
+
f'<div style="font-size:1.25rem;color:var(--accent-text);font-weight:600;margin-top:6px;">{_subtitle}</div>'
|
| 643 |
'</div>', unsafe_allow_html=True
|
| 644 |
)
|
| 645 |
with col_live:
|
|
|
|
| 653 |
st.divider()
|
| 654 |
|
| 655 |
# ── DATA LOAD ─────────────────────────────────────────────────
|
| 656 |
+
all_data = load_stream_data("chat_messages")
|
| 657 |
+
data = all_data[-msg_limit:] if len(all_data) > msg_limit else all_data
|
|
|
|
|
|
|
| 658 |
|
| 659 |
if not all_data:
|
| 660 |
st.markdown(
|
| 661 |
'<div class="empty-state">'
|
| 662 |
'<div class="empty-icon">📭</div>'
|
| 663 |
'<div class="empty-title">No messages yet</div>'
|
| 664 |
+
'<div class="empty-sub">Set a video ID in the sidebar, then click ▶ Start</div>'
|
| 665 |
'</div>', unsafe_allow_html=True
|
| 666 |
)
|
| 667 |
if auto_refresh:
|
|
|
|
| 672 |
df = pd.DataFrame(data)
|
| 673 |
all_df = pd.DataFrame(all_data)
|
| 674 |
|
| 675 |
+
df["sentiment"] = df["sentiment"].apply(clean_sentiment)
|
| 676 |
+
df["topic"] = df["topic"].apply(clean_topic) if "topic" in df.columns else "General"
|
|
|
|
| 677 |
all_df["sentiment"] = all_df["sentiment"].apply(clean_sentiment)
|
| 678 |
all_df["topic"] = all_df["topic"].apply(clean_topic) if "topic" in all_df.columns else "General"
|
| 679 |
|
| 680 |
+
# ── ALERT BANNERS ─────────────────────────────────────────────
|
| 681 |
+
if alert_enabled:
|
| 682 |
+
alert = check_alert(all_df, threshold=alert_threshold, window=alert_window)
|
| 683 |
+
total_now = len(all_df)
|
| 684 |
+
if total_now != st.session_state.last_alert_count:
|
| 685 |
+
st.session_state.last_alert_count = total_now
|
| 686 |
+
if alert:
|
| 687 |
+
st.session_state.alert_dismissed = False
|
| 688 |
+
|
| 689 |
+
if alert and not st.session_state.alert_dismissed:
|
| 690 |
+
a1, a2 = st.columns([8, 1])
|
| 691 |
+
with a1:
|
| 692 |
+
st.markdown(
|
| 693 |
+
f'<div class="alert-banner">'
|
| 694 |
+
f'<span class="alert-icon">🚨</span>'
|
| 695 |
+
f'<div>'
|
| 696 |
+
f'<div class="alert-text">Negative sentiment spike — {alert["neg_ratio"]*100:.0f}% negative in last {alert["window"]} messages</div>'
|
| 697 |
+
f'<div class="alert-sub">{alert["count"]} of {alert["window"]} messages are negative. Consider moderating.</div>'
|
| 698 |
+
f'</div></div>',
|
| 699 |
+
unsafe_allow_html=True
|
| 700 |
+
)
|
| 701 |
+
with a2:
|
| 702 |
+
if st.button("✕ Dismiss", key="dismiss_alert"):
|
| 703 |
+
st.session_state.alert_dismissed = True
|
| 704 |
+
st.rerun()
|
| 705 |
+
|
| 706 |
+
if spam_alert_on:
|
| 707 |
+
spam_alert = check_spam_alert(all_df, threshold=spam_threshold, window=alert_window)
|
| 708 |
+
if spam_alert and not st.session_state.get("spam_dismissed", False):
|
| 709 |
+
s1, s2 = st.columns([8, 1])
|
| 710 |
+
with s1:
|
| 711 |
+
st.markdown(
|
| 712 |
+
f'<div class="spam-alert">'
|
| 713 |
+
f'<span class="alert-icon">🛡️</span>'
|
| 714 |
+
f'<div>'
|
| 715 |
+
f'<div class="spam-alert-text">Spam surge detected — {spam_alert["spam_ratio"]*100:.0f}% spam in last {spam_alert["window"]} messages</div>'
|
| 716 |
+
f'<div class="spam-alert-sub">{spam_alert["count"]} spam messages detected. Chat may be under flood attack.</div>'
|
| 717 |
+
f'</div></div>',
|
| 718 |
+
unsafe_allow_html=True
|
| 719 |
+
)
|
| 720 |
+
with s2:
|
| 721 |
+
if st.button("✕", key="dismiss_spam"):
|
| 722 |
+
st.session_state.spam_dismissed = True
|
| 723 |
+
st.rerun()
|
| 724 |
+
elif not spam_alert:
|
| 725 |
+
st.session_state.spam_dismissed = False
|
| 726 |
+
|
| 727 |
# ── CUMULATIVE STATS ──────────────────────────────────────────
|
| 728 |
all_counts = all_df["sentiment"].value_counts().to_dict()
|
| 729 |
c_pos = all_counts.get("Positive", 0)
|
|
|
|
| 731 |
c_neg = all_counts.get("Negative", 0)
|
| 732 |
c_total = max(c_pos + c_neu + c_neg, 1)
|
| 733 |
|
| 734 |
+
# Sentiment velocity
|
| 735 |
+
velocity = compute_velocity(json.dumps([{"sentiment": m.get("sentiment","Neutral")} for m in all_data]))
|
| 736 |
+
|
| 737 |
st.markdown(
|
| 738 |
'<div class="sec-hdr"><span class="sec-ttl">Cumulative Sentiment</span><span class="sec-pill">All Time</span></div>',
|
| 739 |
unsafe_allow_html=True
|
| 740 |
)
|
| 741 |
+
|
| 742 |
+
v1, v2, v3, v4, v5 = st.columns([1, 1, 1, 1, 1])
|
| 743 |
+
with v1:
|
| 744 |
+
st.markdown(
|
| 745 |
+
f'<div class="stat-card"><div class="stat-accent" style="background:linear-gradient(90deg,#22c55e,#16a34a);"></div>'
|
| 746 |
+
f'<div class="stat-number" style="color:#22c55e;">{c_pos}</div><div class="stat-label">Positive</div><div class="stat-sub">{c_pos/c_total*100:.1f}% of total</div></div>',
|
| 747 |
+
unsafe_allow_html=True
|
| 748 |
+
)
|
| 749 |
+
with v2:
|
| 750 |
+
st.markdown(
|
| 751 |
+
f'<div class="stat-card"><div class="stat-accent" style="background:linear-gradient(90deg,#eab308,#ca8a04);"></div>'
|
| 752 |
+
f'<div class="stat-number" style="color:#eab308;">{c_neu}</div><div class="stat-label">Neutral</div><div class="stat-sub">{c_neu/c_total*100:.1f}% of total</div></div>',
|
| 753 |
+
unsafe_allow_html=True
|
| 754 |
+
)
|
| 755 |
+
with v3:
|
| 756 |
+
st.markdown(
|
| 757 |
+
f'<div class="stat-card"><div class="stat-accent" style="background:linear-gradient(90deg,#ef4444,#dc2626);"></div>'
|
| 758 |
+
f'<div class="stat-number" style="color:#ef4444;">{c_neg}</div><div class="stat-label">Negative</div><div class="stat-sub">{c_neg/c_total*100:.1f}% of total</div></div>',
|
| 759 |
+
unsafe_allow_html=True
|
| 760 |
+
)
|
| 761 |
+
with v4:
|
| 762 |
+
st.markdown(
|
| 763 |
+
f'<div class="stat-card"><div class="stat-accent" style="background:linear-gradient(90deg,#7c3aed,#4f46e5);"></div>'
|
| 764 |
+
f'<div class="stat-number" style="color:var(--accent-text);">{c_total}</div><div class="stat-label">Total</div><div class="stat-sub">all time</div></div>',
|
| 765 |
+
unsafe_allow_html=True
|
| 766 |
+
)
|
| 767 |
+
with v5:
|
| 768 |
+
# Sentiment velocity card
|
| 769 |
+
vc = velocity["color"]
|
| 770 |
+
st.markdown(
|
| 771 |
+
f'<div class="velocity-card" style="border-color:{vc}44;">'
|
| 772 |
+
f'<div class="velocity-arrow" style="color:{vc};">{velocity["direction"]}</div>'
|
| 773 |
+
f'<div>'
|
| 774 |
+
f'<div class="velocity-val" style="color:{vc};">{velocity["label"]}</div>'
|
| 775 |
+
f'<div class="velocity-label">Sentiment Velocity<br>'
|
| 776 |
+
f'<span style="color:{vc};">{velocity["delta"]:+.0%} pos shift</span></div>'
|
| 777 |
+
f'</div></div>',
|
| 778 |
+
unsafe_allow_html=True
|
| 779 |
+
)
|
| 780 |
+
|
| 781 |
|
| 782 |
# ── WINDOW METRICS ────────────────────────────────────────────
|
| 783 |
st.divider()
|
|
|
|
| 801 |
st.divider()
|
| 802 |
col_l, col_r = st.columns(2)
|
| 803 |
|
|
|
|
| 804 |
with col_l:
|
| 805 |
st.markdown('<div class="chart-wrap">', unsafe_allow_html=True)
|
| 806 |
st.markdown('<div class="chart-title">Sentiment Distribution</div><div class="chart-sub">Message count by sentiment class</div>', unsafe_allow_html=True)
|
|
|
|
| 807 |
fig_bar = go.Figure(go.Bar(
|
| 808 |
x=["Positive", "Neutral", "Negative"],
|
| 809 |
y=[pos, neu, neg],
|
|
|
|
| 815 |
hovertemplate="<b>%{x}</b><br>Count: %{y}<extra></extra>",
|
| 816 |
))
|
| 817 |
fig_bar.update_layout(**plotly_layout(260))
|
| 818 |
+
st.plotly_chart(fig_bar, width='stretch', config={"displayModeBar": False})
|
|
|
|
| 819 |
bar_hdr, bar_dl = st.columns([1, 1])
|
| 820 |
with bar_hdr:
|
| 821 |
show_bar_data = st.checkbox("View data", key="show_bar")
|
| 822 |
with bar_dl:
|
| 823 |
bar_df = pd.DataFrame({"Sentiment": ["Positive", "Neutral", "Negative"], "Count": [pos, neu, neg]})
|
| 824 |
csv_download(bar_df, "Download CSV", "sentiment_distribution.csv")
|
|
|
|
| 825 |
if show_bar_data:
|
| 826 |
+
st.dataframe(bar_df, width='stretch', hide_index=True)
|
| 827 |
st.markdown('</div>', unsafe_allow_html=True)
|
| 828 |
|
|
|
|
| 829 |
with col_r:
|
| 830 |
st.markdown('<div class="chart-wrap">', unsafe_allow_html=True)
|
| 831 |
st.markdown('<div class="chart-title">Sentiment Breakdown</div><div class="chart-sub">Proportional share per class</div>', unsafe_allow_html=True)
|
|
|
|
| 832 |
fig_pie = go.Figure(go.Pie(
|
| 833 |
labels=["Positive", "Neutral", "Negative"],
|
| 834 |
values=[pos, neu, neg],
|
|
|
|
| 842 |
"showlegend": True,
|
| 843 |
"legend": dict(orientation="h", y=-0.08, font=dict(size=11))}
|
| 844 |
)
|
| 845 |
+
st.plotly_chart(fig_pie, width='stretch', config={"displayModeBar": False})
|
|
|
|
| 846 |
pie_hdr, pie_dl = st.columns([1, 1])
|
| 847 |
with pie_hdr:
|
| 848 |
show_pie_data = st.checkbox("View data", key="show_pie")
|
|
|
|
| 853 |
"Percentage": [f"{pos/total*100:.1f}%", f"{neu/total*100:.1f}%", f"{neg/total*100:.1f}%"]
|
| 854 |
})
|
| 855 |
csv_download(pie_df, "Download CSV", "sentiment_breakdown.csv")
|
|
|
|
| 856 |
if show_pie_data:
|
| 857 |
+
st.dataframe(pie_df, width='stretch', hide_index=True)
|
| 858 |
st.markdown('</div>', unsafe_allow_html=True)
|
| 859 |
|
| 860 |
# ── Confidence trend ──────────────────────────────────────────
|
|
|
|
| 862 |
st.divider()
|
| 863 |
st.markdown('<div class="chart-wrap">', unsafe_allow_html=True)
|
| 864 |
st.markdown('<div class="chart-title">Confidence Trend</div><div class="chart-sub">Model confidence per message in current window</div>', unsafe_allow_html=True)
|
|
|
|
| 865 |
conf_df = df[["confidence"]].reset_index(drop=True)
|
| 866 |
conf_df.index.name = "message_index"
|
|
|
|
| 867 |
fig_line = go.Figure(go.Scatter(
|
| 868 |
x=conf_df.index,
|
| 869 |
y=conf_df["confidence"],
|
|
|
|
| 875 |
))
|
| 876 |
fig_line.update_layout(**plotly_layout(180))
|
| 877 |
fig_line.update_yaxes(range=[0, 1])
|
| 878 |
+
st.plotly_chart(fig_line, width='stretch', config={"displayModeBar": False})
|
|
|
|
| 879 |
conf_hdr, conf_dl = st.columns([1, 1])
|
| 880 |
with conf_hdr:
|
| 881 |
show_conf_data = st.checkbox("View data", key="show_conf")
|
|
|
|
| 883 |
conf_export = conf_df.reset_index()
|
| 884 |
conf_export.columns = ["message_index", "confidence"]
|
| 885 |
csv_download(conf_export, "Download CSV", "confidence_trend.csv")
|
|
|
|
| 886 |
if show_conf_data:
|
| 887 |
+
st.dataframe(conf_export, width='stretch', hide_index=True)
|
| 888 |
st.markdown('</div>', unsafe_allow_html=True)
|
| 889 |
|
| 890 |
+
|
| 891 |
+
# ── SENTIMENT HEATMAP OVER TIME ───────────────────────────────
|
| 892 |
+
st.divider()
|
| 893 |
+
st.markdown(
|
| 894 |
+
'<div class="sec-hdr"><span class="sec-ttl">Sentiment Heatmap</span><span class="sec-pill">Over Time</span></div>',
|
| 895 |
+
unsafe_allow_html=True
|
| 896 |
+
)
|
| 897 |
+
heatmap_data = build_heatmap_data(json.dumps([{"time": m.get("time",""), "sentiment": m.get("sentiment","Neutral")} for m in all_data]), bucket_minutes=1)
|
| 898 |
+
|
| 899 |
+
if not heatmap_data.empty:
|
| 900 |
+
st.markdown('<div class="chart-wrap">', unsafe_allow_html=True)
|
| 901 |
+
st.markdown('<div class="chart-title">Sentiment Over Time</div><div class="chart-sub">Message volume per sentiment per minute bucket</div>', unsafe_allow_html=True)
|
| 902 |
+
|
| 903 |
+
fig_heat = go.Figure()
|
| 904 |
+
for sent, color in [("Positive", "#22c55e"), ("Neutral", "#eab308"), ("Negative", "#ef4444")]:
|
| 905 |
+
fig_heat.add_trace(go.Bar(
|
| 906 |
+
x=heatmap_data["bucket"],
|
| 907 |
+
y=heatmap_data[sent],
|
| 908 |
+
name=sent,
|
| 909 |
+
marker_color=color,
|
| 910 |
+
opacity=0.85,
|
| 911 |
+
hovertemplate=f"<b>{sent}</b><br>%{{x}}<br>Count: %{{y}}<extra></extra>",
|
| 912 |
+
))
|
| 913 |
+
|
| 914 |
+
layout = plotly_layout(220)
|
| 915 |
+
layout["barmode"] = "stack"
|
| 916 |
+
layout["showlegend"] = True
|
| 917 |
+
layout["legend"] = dict(orientation="h", y=1.08, font=dict(size=11))
|
| 918 |
+
layout["xaxis"]["tickformat"] = "%H:%M"
|
| 919 |
+
fig_heat.update_layout(**layout)
|
| 920 |
+
st.plotly_chart(fig_heat, width='stretch', config={"displayModeBar": False})
|
| 921 |
+
|
| 922 |
+
heat_hdr, heat_dl = st.columns([1, 1])
|
| 923 |
+
with heat_hdr:
|
| 924 |
+
show_heat_data = st.checkbox("View data", key="show_heat")
|
| 925 |
+
with heat_dl:
|
| 926 |
+
csv_download(heatmap_data.rename(columns={"bucket": "time_bucket"}), "Download CSV", "sentiment_heatmap.csv")
|
| 927 |
+
if show_heat_data:
|
| 928 |
+
st.dataframe(heatmap_data.rename(columns={"bucket": "time_bucket"}), width='stretch', hide_index=True)
|
| 929 |
+
st.markdown('</div>', unsafe_allow_html=True)
|
| 930 |
+
else:
|
| 931 |
+
st.info("Not enough timestamped data for heatmap yet.")
|
| 932 |
+
|
| 933 |
# ── TOPIC DISTRIBUTION ────────────────────────────────────────
|
| 934 |
st.divider()
|
| 935 |
st.markdown(
|
|
|
|
| 942 |
for label in TOPIC_LABELS
|
| 943 |
}
|
| 944 |
|
|
|
|
| 945 |
pills = '<div class="topic-grid">'
|
| 946 |
for label in TOPIC_LABELS:
|
| 947 |
color = TOPIC_COLOR[label]
|
|
|
|
| 957 |
|
| 958 |
st.markdown('<div class="chart-wrap">', unsafe_allow_html=True)
|
| 959 |
st.markdown('<div class="chart-title">Topic Breakdown</div><div class="chart-sub">All-time message count per topic category</div>', unsafe_allow_html=True)
|
|
|
|
| 960 |
fig_topic = go.Figure(go.Bar(
|
| 961 |
x=TOPIC_LABELS,
|
| 962 |
y=[topic_counts[l] for l in TOPIC_LABELS],
|
|
|
|
| 968 |
hovertemplate="<b>%{x}</b><br>Count: %{y}<extra></extra>",
|
| 969 |
))
|
| 970 |
fig_topic.update_layout(**plotly_layout(250))
|
| 971 |
+
st.plotly_chart(fig_topic, width='stretch', config={"displayModeBar": False})
|
|
|
|
| 972 |
topic_hdr, topic_dl = st.columns([1, 1])
|
| 973 |
with topic_hdr:
|
| 974 |
show_topic_data = st.checkbox("View data", key="show_topic")
|
| 975 |
with topic_dl:
|
| 976 |
topic_df = pd.DataFrame({"Topic": TOPIC_LABELS, "Count": [topic_counts[l] for l in TOPIC_LABELS]})
|
| 977 |
csv_download(topic_df, "Download CSV", "topic_distribution.csv")
|
|
|
|
| 978 |
if show_topic_data:
|
| 979 |
+
st.dataframe(topic_df, width='stretch', hide_index=True)
|
| 980 |
st.markdown('</div>', unsafe_allow_html=True)
|
| 981 |
|
| 982 |
+
|
| 983 |
+
# ── ENGAGEMENT SCORE ─────────────────────────────────────────
|
| 984 |
+
st.divider()
|
| 985 |
+
st.markdown(
|
| 986 |
+
'<div class="sec-hdr"><span class="sec-ttl">Engagement Score</span><span class="sec-pill">Live</span></div>',
|
| 987 |
+
unsafe_allow_html=True
|
| 988 |
+
)
|
| 989 |
+
|
| 990 |
+
_eng_json = json.dumps([{"sentiment": m.get("sentiment","Neutral"), "topic": m.get("topic","General"), "time": m.get("time","")} for m in all_data])
|
| 991 |
+
eng = compute_engagement(_eng_json)
|
| 992 |
+
|
| 993 |
+
ec1, ec2, ec3, ec4 = st.columns([2, 1, 1, 1])
|
| 994 |
+
with ec1:
|
| 995 |
+
score_color = "#22c55e" if eng["score"] >= 70 else "#eab308" if eng["score"] >= 40 else "#ef4444"
|
| 996 |
+
bar_w = eng["score"]
|
| 997 |
+
st.markdown(
|
| 998 |
+
f'<div class="engage-card" style="border-color:{score_color}44;">'
|
| 999 |
+
f'<div class="engage-score" style="color:{score_color};">{eng["score"]}</div>'
|
| 1000 |
+
f'<div class="engage-label">Engagement Score / 100 — {eng["grade"]}</div>'
|
| 1001 |
+
f'<div class="engage-bar-bg"><div class="engage-bar-fill" style="width:{bar_w}%;background:{score_color};"></div></div>'
|
| 1002 |
+
f'<div class="engage-breakdown">'
|
| 1003 |
+
f'<div class="engage-item">Msg rate <span>{eng["rate"]}/min</span></div>'
|
| 1004 |
+
f'<div class="engage-item">Positive <span>{eng["pos_ratio"]*100:.0f}%</span></div>'
|
| 1005 |
+
f'<div class="engage-item">Questions <span>{eng["q_density"]*100:.0f}%</span></div>'
|
| 1006 |
+
f'</div></div>',
|
| 1007 |
+
unsafe_allow_html=True
|
| 1008 |
+
)
|
| 1009 |
+
with ec2:
|
| 1010 |
+
st.metric("Msgs/min", f"{eng['rate']:.1f}")
|
| 1011 |
+
with ec3:
|
| 1012 |
+
st.metric("Positive ratio", f"{eng['pos_ratio']*100:.0f}%")
|
| 1013 |
+
with ec4:
|
| 1014 |
+
st.metric("Question density", f"{eng['q_density']*100:.0f}%")
|
| 1015 |
+
|
| 1016 |
+
# ── TOP CONTRIBUTORS ──────────────────────────────────────────
|
| 1017 |
+
st.divider()
|
| 1018 |
+
st.markdown(
|
| 1019 |
+
'<div class="sec-hdr"><span class="sec-ttl">Top Contributors</span><span class="sec-pill">All Time</span></div>',
|
| 1020 |
+
unsafe_allow_html=True
|
| 1021 |
+
)
|
| 1022 |
+
|
| 1023 |
+
_contrib_json = json.dumps([{"author": m.get("author",""), "sentiment": m.get("sentiment","Neutral")} for m in all_data])
|
| 1024 |
+
contributors = compute_top_contributors(_contrib_json)
|
| 1025 |
+
|
| 1026 |
+
if contributors:
|
| 1027 |
+
max_count = contributors[0]["count"]
|
| 1028 |
+
lc1, lc2 = st.columns([3, 2])
|
| 1029 |
+
with lc1:
|
| 1030 |
+
rank_icons = {1: "🥇", 2: "🥈", 3: "🥉"}
|
| 1031 |
+
rank_classes = {1: "gold", 2: "silver", 3: "bronze"}
|
| 1032 |
+
for rank, c in enumerate(contributors, 1):
|
| 1033 |
+
bar_pct = int(c["count"] / max(max_count, 1) * 100)
|
| 1034 |
+
rank_cls = rank_classes.get(rank, "")
|
| 1035 |
+
rank_icon = rank_icons.get(rank, f"#{rank}")
|
| 1036 |
+
author = c["author"]
|
| 1037 |
+
count = c["count"]
|
| 1038 |
+
pos_pct = c["pos_pct"]
|
| 1039 |
+
neu_pct = c["neu_pct"]
|
| 1040 |
+
neg_pct = c["neg_pct"]
|
| 1041 |
+
html = (
|
| 1042 |
+
f'<div class="leaderboard-row">'
|
| 1043 |
+
f'<div class="lb-rank {rank_cls}">{rank_icon}</div>'
|
| 1044 |
+
f'<div class="lb-author">{author}</div>'
|
| 1045 |
+
f'<div class="lb-bar"><div class="lb-bar-fill" style="width:{bar_pct}%;background:var(--accent);"></div></div>'
|
| 1046 |
+
f'<div class="lb-sent">'
|
| 1047 |
+
f'<span class="lb-dot" style="background:#22c55e;" title="Positive {pos_pct}%"></span>'
|
| 1048 |
+
f'<span class="lb-dot" style="background:#eab308;" title="Neutral {neu_pct}%"></span>'
|
| 1049 |
+
f'<span class="lb-dot" style="background:#ef4444;" title="Negative {neg_pct}%"></span>'
|
| 1050 |
+
f'</div>'
|
| 1051 |
+
f'<div class="lb-count">{count} msgs</div>'
|
| 1052 |
+
f'</div>'
|
| 1053 |
+
)
|
| 1054 |
+
st.markdown(html, unsafe_allow_html=True)
|
| 1055 |
+
with lc2:
|
| 1056 |
+
# Stacked bar of top 5 contributors
|
| 1057 |
+
top5 = contributors[:5]
|
| 1058 |
+
fig_lb = go.Figure()
|
| 1059 |
+
for sent, color in [("pos_pct","#22c55e"),("neu_pct","#eab308"),("neg_pct","#ef4444")]:
|
| 1060 |
+
fig_lb.add_trace(go.Bar(
|
| 1061 |
+
y=[c["author"][:18] for c in top5],
|
| 1062 |
+
x=[c[sent] for c in top5],
|
| 1063 |
+
name=sent.replace("_pct","").capitalize(),
|
| 1064 |
+
orientation="h",
|
| 1065 |
+
marker_color=color,
|
| 1066 |
+
hovertemplate="%{y}: %{x}%<extra></extra>",
|
| 1067 |
+
))
|
| 1068 |
+
layout_lb = plotly_layout(260)
|
| 1069 |
+
layout_lb["barmode"] = "stack"
|
| 1070 |
+
layout_lb["showlegend"] = True
|
| 1071 |
+
layout_lb["legend"] = dict(orientation="h", y=1.1, font=dict(size=10))
|
| 1072 |
+
layout_lb["xaxis"]["range"] = [0, 100]
|
| 1073 |
+
layout_lb["xaxis"]["ticksuffix"] = "%"
|
| 1074 |
+
fig_lb.update_layout(**layout_lb)
|
| 1075 |
+
st.plotly_chart(fig_lb, width='stretch', config={"displayModeBar": False})
|
| 1076 |
+
|
| 1077 |
+
contrib_df = pd.DataFrame(contributors)
|
| 1078 |
+
csv_download(contrib_df, "Download CSV", "top_contributors.csv")
|
| 1079 |
+
else:
|
| 1080 |
+
st.info("Not enough data yet.")
|
| 1081 |
+
|
| 1082 |
+
# ── WORD CLOUD ────────────────────────────────────────────────
|
| 1083 |
+
st.divider()
|
| 1084 |
+
st.markdown(
|
| 1085 |
+
'<div class="sec-hdr"><span class="sec-ttl">Word Cloud</span><span class="sec-pill">All Time</span></div>',
|
| 1086 |
+
unsafe_allow_html=True
|
| 1087 |
+
)
|
| 1088 |
+
|
| 1089 |
+
wc_col1, wc_col2, wc_col3 = st.columns([1, 1, 3])
|
| 1090 |
+
with wc_col1:
|
| 1091 |
+
wc_sentiment = st.selectbox("Filter sentiment", ["All", "Positive", "Neutral", "Negative"], key="wc_sent")
|
| 1092 |
+
with wc_col2:
|
| 1093 |
+
wc_topic = st.selectbox("Filter topic", ["All"] + TOPIC_LABELS, key="wc_topic")
|
| 1094 |
+
|
| 1095 |
+
_wc_json = json.dumps([{"text": m.get("text",""), "sentiment": m.get("sentiment","Neutral"), "topic": m.get("topic","General")} for m in all_data])
|
| 1096 |
+
word_freq = compute_word_freq(_wc_json, sentiment_filter=wc_sentiment, topic_filter=wc_topic)
|
| 1097 |
+
|
| 1098 |
+
if word_freq:
|
| 1099 |
+
try:
|
| 1100 |
+
from wordcloud import WordCloud
|
| 1101 |
+
import matplotlib.pyplot as plt
|
| 1102 |
+
import io
|
| 1103 |
+
|
| 1104 |
+
freq_dict = dict(word_freq)
|
| 1105 |
+
wc = WordCloud(
|
| 1106 |
+
width=900, height=320,
|
| 1107 |
+
background_color="white",
|
| 1108 |
+
colormap="cool",
|
| 1109 |
+
max_words=80,
|
| 1110 |
+
prefer_horizontal=0.85,
|
| 1111 |
+
collocations=False,
|
| 1112 |
+
).generate_from_frequencies(freq_dict)
|
| 1113 |
+
|
| 1114 |
+
st.markdown('<div class="chart-wrap">', unsafe_allow_html=True)
|
| 1115 |
+
st.image(wc.to_array(), width="stretch")
|
| 1116 |
+
st.markdown('</div>', unsafe_allow_html=True)
|
| 1117 |
+
|
| 1118 |
+
# Also show top 20 as a bar chart
|
| 1119 |
+
top20 = word_freq[:20]
|
| 1120 |
+
fig_wf = go.Figure(go.Bar(
|
| 1121 |
+
x=[w for w, _ in top20],
|
| 1122 |
+
y=[c for _, c in top20],
|
| 1123 |
+
marker_color="#7c3aed",
|
| 1124 |
+
marker_line_width=0,
|
| 1125 |
+
hovertemplate="<b>%{x}</b><br>%{y} times<extra></extra>",
|
| 1126 |
+
))
|
| 1127 |
+
layout_wf = plotly_layout(180)
|
| 1128 |
+
fig_wf.update_layout(**layout_wf)
|
| 1129 |
+
st.plotly_chart(fig_wf, width='stretch', config={"displayModeBar": False})
|
| 1130 |
+
|
| 1131 |
+
except ImportError:
|
| 1132 |
+
# Fallback: just show bar chart if wordcloud not available
|
| 1133 |
+
top20 = word_freq[:20]
|
| 1134 |
+
fig_wf = go.Figure(go.Bar(
|
| 1135 |
+
x=[w for w, _ in top20],
|
| 1136 |
+
y=[c for _, c in top20],
|
| 1137 |
+
marker_color="#7c3aed",
|
| 1138 |
+
marker_line_width=0,
|
| 1139 |
+
))
|
| 1140 |
+
fig_wf.update_layout(**plotly_layout(200))
|
| 1141 |
+
st.plotly_chart(fig_wf, width='stretch', config={"displayModeBar": False})
|
| 1142 |
+
else:
|
| 1143 |
+
st.info("Not enough text data yet.")
|
| 1144 |
+
|
| 1145 |
+
# ── MULTI-STREAM COMPARISON ───────────────────────────────────
|
| 1146 |
+
active_streams = [s for s in st.session_state.streams if r.llen(s["redis_key"]) > 0]
|
| 1147 |
+
|
| 1148 |
+
if len(active_streams) > 1:
|
| 1149 |
+
st.divider()
|
| 1150 |
+
n_streams = len(active_streams)
|
| 1151 |
+
st.markdown(
|
| 1152 |
+
f'<div class="sec-hdr"><span class="sec-ttl">Multi-Stream Comparison</span>'
|
| 1153 |
+
f'<span class="sec-pill">{n_streams} streams</span></div>',
|
| 1154 |
+
unsafe_allow_html=True
|
| 1155 |
+
)
|
| 1156 |
+
|
| 1157 |
+
def stream_summary_chart(stream_df, color):
|
| 1158 |
+
counts_s = stream_df["sentiment"].value_counts().to_dict()
|
| 1159 |
+
p = counts_s.get("Positive", 0)
|
| 1160 |
+
n = counts_s.get("Neutral", 0)
|
| 1161 |
+
g = counts_s.get("Negative", 0)
|
| 1162 |
+
t = max(p + n + g, 1)
|
| 1163 |
+
fig = go.Figure(go.Bar(
|
| 1164 |
+
x=["Positive", "Neutral", "Negative"],
|
| 1165 |
+
y=[p, n, g],
|
| 1166 |
+
marker_color=["#22c55e", "#eab308", "#ef4444"],
|
| 1167 |
+
marker_line_width=0,
|
| 1168 |
+
text=[p, n, g],
|
| 1169 |
+
textposition="outside",
|
| 1170 |
+
hovertemplate="<b>%{x}</b><br>%{y}<extra></extra>",
|
| 1171 |
+
))
|
| 1172 |
+
fig.update_layout(**plotly_layout(200))
|
| 1173 |
+
return fig, p, n, g, t
|
| 1174 |
+
|
| 1175 |
+
# Render in rows of up to 3 columns
|
| 1176 |
+
chunk_size = 3
|
| 1177 |
+
for row_start in range(0, n_streams, chunk_size):
|
| 1178 |
+
row_streams = active_streams[row_start:row_start + chunk_size]
|
| 1179 |
+
cols = st.columns(len(row_streams))
|
| 1180 |
+
for col, stream in zip(cols, row_streams):
|
| 1181 |
+
sidx = st.session_state.streams.index(stream)
|
| 1182 |
+
color = STREAM_COLORS[sidx]
|
| 1183 |
+
slabel = STREAM_NAMES[sidx]
|
| 1184 |
+
s_data = load_stream_data(stream["redis_key"])
|
| 1185 |
+
if not s_data:
|
| 1186 |
+
col.info(f"No data yet for Stream {slabel}")
|
| 1187 |
+
continue
|
| 1188 |
+
s_df = pd.DataFrame(s_data)
|
| 1189 |
+
s_df["sentiment"] = s_df["sentiment"].apply(clean_sentiment)
|
| 1190 |
+
s_df["topic"] = s_df["topic"].apply(clean_topic) if "topic" in s_df.columns else "General"
|
| 1191 |
+
fig, p, n, g, t = stream_summary_chart(s_df, color)
|
| 1192 |
+
with col:
|
| 1193 |
+
st.markdown(
|
| 1194 |
+
f'<span class="compare-label" style="background:{color}18;color:{color};border:1px solid {color}44;">'
|
| 1195 |
+
f'Stream {slabel} — {stream["redis_key"]}</span>',
|
| 1196 |
+
unsafe_allow_html=True
|
| 1197 |
+
)
|
| 1198 |
+
st.plotly_chart(fig, width='stretch', config={"displayModeBar": False})
|
| 1199 |
+
st.markdown(
|
| 1200 |
+
f'<div style="font-size:0.78rem;color:var(--text-3);margin-bottom:8px;">'
|
| 1201 |
+
f'{t} msgs · <span style="color:#22c55e;">{p/t*100:.1f}% pos</span> · '
|
| 1202 |
+
f'<span style="color:#ef4444;">{g/t*100:.1f}% neg</span></div>',
|
| 1203 |
+
unsafe_allow_html=True
|
| 1204 |
+
)
|
| 1205 |
+
|
| 1206 |
+
# Overlay line chart — positive ratio over time for all streams
|
| 1207 |
+
st.markdown('<div class="chart-wrap" style="margin-top:14px;">', unsafe_allow_html=True)
|
| 1208 |
+
st.markdown('<div class="chart-title">Positive Ratio Over Time</div><div class="chart-sub">Rolling positive % per stream</div>', unsafe_allow_html=True)
|
| 1209 |
+
fig_overlay = go.Figure()
|
| 1210 |
+
for stream in active_streams:
|
| 1211 |
+
sidx = st.session_state.streams.index(stream)
|
| 1212 |
+
color = STREAM_COLORS[sidx]
|
| 1213 |
+
slabel = STREAM_NAMES[sidx]
|
| 1214 |
+
s_data = load_stream_data(stream["redis_key"])
|
| 1215 |
+
if not s_data:
|
| 1216 |
+
continue
|
| 1217 |
+
s_df = pd.DataFrame(s_data)
|
| 1218 |
+
s_df["sentiment"] = s_df["sentiment"].apply(clean_sentiment)
|
| 1219 |
+
s_df["is_pos"] = (s_df["sentiment"] == "Positive").astype(int)
|
| 1220 |
+
s_df["rolling"] = s_df["is_pos"].rolling(10, min_periods=1).mean() * 100
|
| 1221 |
+
fig_overlay.add_trace(go.Scatter(
|
| 1222 |
+
x=list(range(len(s_df))),
|
| 1223 |
+
y=s_df["rolling"],
|
| 1224 |
+
mode="lines",
|
| 1225 |
+
name=f"Stream {slabel}",
|
| 1226 |
+
line=dict(color=color, width=2),
|
| 1227 |
+
hovertemplate=f"Stream {slabel} msg %{{x}}: %{{y:.1f}}%<extra></extra>",
|
| 1228 |
+
))
|
| 1229 |
+
layout_ov = plotly_layout(200)
|
| 1230 |
+
layout_ov["showlegend"] = True
|
| 1231 |
+
layout_ov["legend"] = dict(orientation="h", y=1.1, font=dict(size=11))
|
| 1232 |
+
layout_ov["yaxis"]["range"] = [0, 100]
|
| 1233 |
+
fig_overlay.update_layout(**layout_ov)
|
| 1234 |
+
st.plotly_chart(fig_overlay, width='stretch', config={"displayModeBar": False})
|
| 1235 |
+
st.markdown('</div>', unsafe_allow_html=True)
|
| 1236 |
+
|
| 1237 |
+
elif len(st.session_state.streams) > 1:
|
| 1238 |
+
st.divider()
|
| 1239 |
+
st.info("Add video IDs to your extra stream slots and click ▶ Start to enable multi-stream comparison.")
|
| 1240 |
+
|
| 1241 |
+
# ── PINNED MESSAGES ───────────────────────────────────────────
|
| 1242 |
+
if st.session_state.pinned_messages:
|
| 1243 |
+
st.divider()
|
| 1244 |
+
st.markdown(
|
| 1245 |
+
'<div class="sec-hdr"><span class="sec-ttl">📌 Pinned Messages</span>'
|
| 1246 |
+
f'<span class="sec-pill">{len(st.session_state.pinned_messages)} pinned</span></div>',
|
| 1247 |
+
unsafe_allow_html=True
|
| 1248 |
+
)
|
| 1249 |
+
for idx, pmsg in enumerate(st.session_state.pinned_messages):
|
| 1250 |
+
s = pmsg.get("sentiment", "Neutral")
|
| 1251 |
+
s_color = SENT_COLORS.get(s, "#6b7280")
|
| 1252 |
+
t_color = TOPIC_COLOR.get(pmsg.get("topic", "General"), "#6b7280")
|
| 1253 |
+
pcol1, pcol2 = st.columns([10, 1])
|
| 1254 |
+
with pcol1:
|
| 1255 |
+
st.markdown(
|
| 1256 |
+
f'<div class="chat-card chat-pinned">'
|
| 1257 |
+
f'<div class="chat-author">📌 {pmsg.get("author", "Unknown")}</div>'
|
| 1258 |
+
f'<div class="chat-text">{pmsg.get("text", "")}</div>'
|
| 1259 |
+
f'<div class="chat-badges">'
|
| 1260 |
+
f'<span class="badge pin-badge">Pinned</span>'
|
| 1261 |
+
f'<span class="badge" style="color:{s_color};">{s}</span>'
|
| 1262 |
+
f'<span class="badge" style="color:{t_color};">{pmsg.get("topic","General")}</span>'
|
| 1263 |
+
f'<span class="badge">{pmsg.get("time","")[:19]}</span>'
|
| 1264 |
+
f'</div></div>',
|
| 1265 |
+
unsafe_allow_html=True
|
| 1266 |
+
)
|
| 1267 |
+
with pcol2:
|
| 1268 |
+
if st.button("✕", key=f"unpin_{idx}"):
|
| 1269 |
+
st.session_state.pinned_messages.pop(idx)
|
| 1270 |
+
st.rerun()
|
| 1271 |
+
|
| 1272 |
+
|
| 1273 |
# ── LIVE CHAT FEED ────────────────────────────────────────────
|
| 1274 |
st.divider()
|
| 1275 |
st.markdown('<div class="sec-hdr"><span class="sec-ttl">Live Chat Feed</span></div>', unsafe_allow_html=True)
|
|
|
|
| 1298 |
)
|
| 1299 |
with feed_dl:
|
| 1300 |
if not filtered.empty:
|
| 1301 |
+
export_cols = [c for c in ["author", "text", "sentiment", "confidence", "topic", "time"] if c in filtered.columns]
|
| 1302 |
+
csv_download(filtered[export_cols], "Download Feed CSV", "chat_feed.csv")
|
|
|
|
|
|
|
| 1303 |
|
| 1304 |
SENT_ICON = {"Positive": "🟢", "Negative": "🔴", "Neutral": "🟡"}
|
| 1305 |
|
| 1306 |
+
# Build a set of pinned texts for quick lookup
|
| 1307 |
+
pinned_texts = {m.get("text", "") for m in st.session_state.pinned_messages}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1308 |
|
| 1309 |
+
for i, (_, row) in enumerate(filtered.iloc[::-1].iterrows()):
|
| 1310 |
+
s = row.get("sentiment", "Neutral")
|
| 1311 |
+
conf_pct = int(row.get("confidence", 0) * 100)
|
| 1312 |
+
topic = clean_topic(row.get("topic", "General"))
|
| 1313 |
+
t_color = TOPIC_COLOR.get(topic, "#6b7280")
|
| 1314 |
+
s_color = SENT_COLORS.get(s, "#6b7280")
|
| 1315 |
+
s_icon = SENT_ICON.get(s, "⚪")
|
| 1316 |
+
conf_color = "#22c55e" if conf_pct >= 70 else "#eab308" if conf_pct >= 40 else "#ef4444"
|
| 1317 |
+
msg_text = row.get("text", "")
|
| 1318 |
+
is_pinned = msg_text in pinned_texts
|
| 1319 |
+
|
| 1320 |
+
card_class = f"chat-card chat-{s.lower()}" + (" chat-pinned" if is_pinned else "")
|
| 1321 |
+
|
| 1322 |
+
msg_col, pin_col = st.columns([11, 1])
|
| 1323 |
+
with msg_col:
|
| 1324 |
+
st.markdown(
|
| 1325 |
+
f'<div class="{card_class}">'
|
| 1326 |
+
f'<div class="chat-author">{s_icon} {row.get("author", "Unknown")}'
|
| 1327 |
+
+ (' <span style="font-size:0.7rem;color:#eab308;">📌</span>' if is_pinned else '') +
|
| 1328 |
+
f'</div>'
|
| 1329 |
+
f'<div class="chat-text">{msg_text}</div>'
|
| 1330 |
+
f'<div class="chat-badges">'
|
| 1331 |
+
f'<span class="badge" style="color:{s_color};border-color:{s_color}33;">{s}</span>'
|
| 1332 |
+
f'<span class="badge" style="color:{conf_color};">Confidence: {conf_pct}%</span>'
|
| 1333 |
+
f'<span class="badge" style="color:{t_color};border-color:{t_color}33;">{topic}</span>'
|
| 1334 |
+
f'</div></div>',
|
| 1335 |
+
unsafe_allow_html=True
|
| 1336 |
+
)
|
| 1337 |
+
with pin_col:
|
| 1338 |
+
if is_pinned:
|
| 1339 |
+
if st.button("📌", key=f"unpin_feed_{i}", help="Unpin this message"):
|
| 1340 |
+
st.session_state.pinned_messages = [
|
| 1341 |
+
m for m in st.session_state.pinned_messages if m.get("text") != msg_text
|
| 1342 |
+
]
|
| 1343 |
+
st.rerun()
|
| 1344 |
+
else:
|
| 1345 |
+
if st.button("📍", key=f"pin_{i}", help="Pin this message"):
|
| 1346 |
+
msg_dict = row.to_dict()
|
| 1347 |
+
if msg_dict not in st.session_state.pinned_messages:
|
| 1348 |
+
st.session_state.pinned_messages.append(msg_dict)
|
| 1349 |
+
st.rerun()
|
| 1350 |
|
| 1351 |
# ── AUTO REFRESH ──────────────────────────────────────────────
|
| 1352 |
if auto_refresh:
|
ml/topic_model.py
CHANGED
|
@@ -24,7 +24,7 @@ from transformers import pipeline
|
|
| 24 |
# ── Configuration ──────────────────────────────────────────────────────────────
|
| 25 |
MODEL_NAME = "facebook/bart-large-mnli"
|
| 26 |
|
| 27 |
-
VALID_TOPICS = {"Appreciation", "Question", "Promo", "Spam", "General"}
|
| 28 |
|
| 29 |
# More descriptive labels → better zero-shot accuracy
|
| 30 |
_CANDIDATE_LABELS = [
|
|
@@ -80,6 +80,14 @@ _PROMO_KW = {
|
|
| 80 |
def _fast_path(text: str) -> tuple[str, float] | None:
|
| 81 |
t = text.strip().lower()
|
| 82 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
# Spam: repeated chars or gibberish
|
| 84 |
for pat in _SPAM_PATTERNS:
|
| 85 |
if re.search(pat, t):
|
|
|
|
| 24 |
# ── Configuration ──────────────────────────────────────────────────────────────
|
| 25 |
MODEL_NAME = "facebook/bart-large-mnli"
|
| 26 |
|
| 27 |
+
VALID_TOPICS = {"Appreciation", "Question", "Promo", "Spam", "General", "MCQ Answer"}
|
| 28 |
|
| 29 |
# More descriptive labels → better zero-shot accuracy
|
| 30 |
_CANDIDATE_LABELS = [
|
|
|
|
| 80 |
def _fast_path(text: str) -> tuple[str, float] | None:
|
| 81 |
t = text.strip().lower()
|
| 82 |
|
| 83 |
+
# MCQ Answer: single letter or repeated letter(s) like a, b, aa, bbb, cccc
|
| 84 |
+
if re.fullmatch(r"[a-e]", t) or re.fullmatch(r"([a-e])\1*", t):
|
| 85 |
+
return "MCQ Answer", 0.95
|
| 86 |
+
|
| 87 |
+
# MCQ Answer: comma/space separated options like "a b c", "a,b", "aa bb"
|
| 88 |
+
if re.fullmatch(r"([a-e])\1*(\s*[,/]\s*([a-e])\3*)*", t):
|
| 89 |
+
return "MCQ Answer", 0.95
|
| 90 |
+
|
| 91 |
# Spam: repeated chars or gibberish
|
| 92 |
for pat in _SPAM_PATTERNS:
|
| 93 |
if re.search(pat, t):
|
new_trained_data/muril-sentimix/config.json
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"add_cross_attention": false,
|
| 3 |
+
"architectures": [
|
| 4 |
+
"BertForSequenceClassification"
|
| 5 |
+
],
|
| 6 |
+
"attention_probs_dropout_prob": 0.1,
|
| 7 |
+
"bos_token_id": null,
|
| 8 |
+
"classifier_dropout": null,
|
| 9 |
+
"dtype": "float32",
|
| 10 |
+
"embedding_size": 768,
|
| 11 |
+
"eos_token_id": null,
|
| 12 |
+
"hidden_act": "gelu",
|
| 13 |
+
"hidden_dropout_prob": 0.1,
|
| 14 |
+
"hidden_size": 768,
|
| 15 |
+
"id2label": {
|
| 16 |
+
"0": "Negative",
|
| 17 |
+
"1": "Neutral",
|
| 18 |
+
"2": "Positive"
|
| 19 |
+
},
|
| 20 |
+
"initializer_range": 0.02,
|
| 21 |
+
"intermediate_size": 3072,
|
| 22 |
+
"is_decoder": false,
|
| 23 |
+
"label2id": {
|
| 24 |
+
"negative": 0,
|
| 25 |
+
"neutral": 1,
|
| 26 |
+
"positive": 2
|
| 27 |
+
},
|
| 28 |
+
"layer_norm_eps": 1e-12,
|
| 29 |
+
"max_position_embeddings": 512,
|
| 30 |
+
"model_type": "bert",
|
| 31 |
+
"num_attention_heads": 12,
|
| 32 |
+
"num_hidden_layers": 12,
|
| 33 |
+
"pad_token_id": 0,
|
| 34 |
+
"problem_type": "single_label_classification",
|
| 35 |
+
"tie_word_embeddings": true,
|
| 36 |
+
"transformers_version": "5.0.0",
|
| 37 |
+
"type_vocab_size": 2,
|
| 38 |
+
"use_cache": false,
|
| 39 |
+
"vocab_size": 197285
|
| 40 |
+
}
|
new_trained_data/muril-sentimix/model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4e28f220060cab19f110d1a7b0efb860aa0ae9af8ffb2e275ade77b9b827711b
|
| 3 |
+
size 950257644
|
new_trained_data/muril-sentimix/tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
new_trained_data/muril-sentimix/tokenizer_config.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"backend": "tokenizers",
|
| 3 |
+
"cls_token": "[CLS]",
|
| 4 |
+
"do_lower_case": false,
|
| 5 |
+
"is_local": false,
|
| 6 |
+
"lowercase": false,
|
| 7 |
+
"mask_token": "[MASK]",
|
| 8 |
+
"model_max_length": 512,
|
| 9 |
+
"pad_token": "[PAD]",
|
| 10 |
+
"sep_token": "[SEP]",
|
| 11 |
+
"strip_accents": false,
|
| 12 |
+
"tokenize_chinese_chars": true,
|
| 13 |
+
"tokenizer_class": "BertTokenizer",
|
| 14 |
+
"unk_token": "[UNK]"
|
| 15 |
+
}
|
new_trained_data/muril-sentimix/training_args.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4920d075f41a5e8a9bee5224014a00ec24f5822aeb271ea135c18ff621aa54db
|
| 3 |
+
size 5201
|
requirements.txt
CHANGED
|
@@ -1,18 +1,7 @@
|
|
| 1 |
-
fastapi
|
| 2 |
-
uvicorn
|
| 3 |
-
pytchat
|
| 4 |
-
redis
|
| 5 |
-
transformers
|
| 6 |
-
torch
|
| 7 |
-
streamlit
|
| 8 |
-
pandas
|
| 9 |
-
plotly
|
| 10 |
-
emoji
|
| 11 |
-
|
| 12 |
# Core ML
|
| 13 |
torch>=2.0.0
|
| 14 |
transformers>=4.38.0
|
| 15 |
-
sentencepiece>=0.1.99
|
| 16 |
|
| 17 |
# Emoji + slang handling
|
| 18 |
emoji>=2.10.0
|
|
@@ -21,13 +10,9 @@ deep-translator>=1.11.4
|
|
| 21 |
# Live chat scraping
|
| 22 |
pytchat>=0.5.5
|
| 23 |
|
| 24 |
-
#
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
# Dataset (only needed for fine-tuning MuRIL — optional)
|
| 32 |
-
# datasets>=2.18.0
|
| 33 |
-
# scikit-learn>=1.4.0 # for eval metrics during fine-tuning
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
# Core ML
|
| 2 |
torch>=2.0.0
|
| 3 |
transformers>=4.38.0
|
| 4 |
+
sentencepiece>=0.1.99
|
| 5 |
|
| 6 |
# Emoji + slang handling
|
| 7 |
emoji>=2.10.0
|
|
|
|
| 10 |
# Live chat scraping
|
| 11 |
pytchat>=0.5.5
|
| 12 |
|
| 13 |
+
# Dashboard
|
| 14 |
+
streamlit>=1.35.0
|
| 15 |
+
pandas>=2.0.0
|
| 16 |
+
plotly>=5.18.0
|
| 17 |
+
wordcloud>=1.9.3
|
| 18 |
+
matplotlib>=3.8.0
|
|
|
|
|
|
|
|
|
|
|
|