xtinkarpiu commited on
Commit
c1c559f
Β·
verified Β·
1 Parent(s): e18a159

Upload folder using huggingface_hub

Browse files
Files changed (4) hide show
  1. Dockerfile +3 -0
  2. README.md +49 -20
  3. app.py +3 -0
  4. dashboard.py +245 -0
Dockerfile CHANGED
@@ -11,4 +11,7 @@ RUN pip install --no-cache-dir -r requirements.txt
11
 
12
  COPY . .
13
 
 
 
 
14
  CMD ["python", "dashboard.py"]
 
11
 
12
  COPY . .
13
 
14
+ ENV USE_MOCK=true
15
+ ENV PORT=7860
16
+
17
  CMD ["python", "dashboard.py"]
README.md CHANGED
@@ -1,17 +1,21 @@
1
  ---
2
- title: Sentiment Analysis Dashboard
3
  emoji: πŸ“Š
4
  colorFrom: blue
5
  colorTo: green
6
  sdk: docker
7
- app_file: dashboard.py
8
  pinned: false
9
  ---
10
 
11
  # πŸ“Š Sentiment Analysis Dashboard
12
 
13
- A real-time dashboard for visualizing tweet sentiment (positive, negative, neutral) using **Kafka**, **Spark**, and **Flask**.
14
- It supports both live Twitter streams (via producer.py) and demo mode with mock tweets (via mock_tweet_producer.py).
 
 
 
 
15
 
16
  This version runs in mock/demo mode on Hugging Face Spaces.
17
 
@@ -22,7 +26,9 @@ Author: Kristine Karp (karpkristine@gmail.com)
22
  ## πŸš€ Demo Mode (Hugging Face)
23
 
24
  > This Space runs in **mock mode**, generating fake tweets using `mock_tweet_producer.py`.
25
- This allows users to explore the dashboard **without requiring Twitter API credentials or external Kafka setup**.
 
 
26
 
27
 
28
  ---
@@ -30,10 +36,12 @@ This allows users to explore the dashboard **without requiring Twitter API crede
30
  ## 🧠 Features
31
 
32
  - Real-time tweet ingestion (simulated or live)
33
- - Sentiment counts: Positive, Neutral, Negative
34
- - Recent tweet stream with sentiment tags
35
- - Hourly sentiment trend summary
36
- - WebSocket-powered live updates
 
 
37
 
38
  ---
39
 
@@ -41,13 +49,14 @@ This allows users to explore the dashboard **without requiring Twitter API crede
41
 
42
  | File/Folder | Purpose |
43
  |------------------------|---------------------------------------------------|
44
- | `dashboard.py` | Main Flask app + Kafka consumer for hugging faces demo purposes |
45
- | `local_dashboard.py` | Flask app + Kafka consumer that can be run locally in http://localhost:5000/ |
46
- | `templates/dashboard.html` | HTML UI template for the dashboard |
47
- | `mock_tweet_producer.py` | Generates mock tweets for demo/testing |
48
- | `producer.py` | Optional Twitter producer if you have API token |
49
- | `requirements.txt` | All Python dependencies |
50
- | `.env` (optional) | Set up your Twitter API token if using real data |
 
51
 
52
  ---
53
 
@@ -55,11 +64,13 @@ This allows users to explore the dashboard **without requiring Twitter API crede
55
 
56
  If you want to stream real tweets and analyze their sentiment:
57
 
58
- 1. Create a Twitter/X Developer App
59
  2. Add your **Bearer Token** to a `.env` file:
60
  ```env
61
  BEARER_TOKEN=your_token_here
62
- 3. Run producer.py instead
 
 
63
 
64
  ## πŸ§ͺ Local Development
65
 
@@ -67,11 +78,29 @@ git clone https://huggingface.co/spaces/xtinkarpiu/sentiment-analysis
67
  cd sentiment-analysis
68
  docker-compose up --build
69
 
 
 
 
 
 
 
 
70
  ## πŸ“· Dashboard Preview
71
 
72
  Here's a preview of the sentiment dashboard in action:
73
 
74
  ![Dashboard Overview](assets/dashboard_screenshot1.jpg)
 
75
  ![Real-Time Tweets and Charts](assets/dashboard_screenshot2.jpg)
76
-
77
- *Demo hosted on Hugging Face Spaces*
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Real-Time Sentiment Analysis Dashboard
3
  emoji: πŸ“Š
4
  colorFrom: blue
5
  colorTo: green
6
  sdk: docker
7
+ app_port: 7860
8
  pinned: false
9
  ---
10
 
11
  # πŸ“Š Sentiment Analysis Dashboard
12
 
13
+ A real-time sentiment analysis dashboard that processes tweets and displays sentiment trends.
14
+
15
+ - 🟒 **Live Demo Mode**: Shows mock data for demonstration
16
+ - πŸ”„ **Real-time Updates**: Uses WebSocket for live data streaming
17
+ - πŸ“Š **Interactive Charts**: Pie charts and trend analysis
18
+ - πŸ“± **Recent Tweets**: Live feed of processed tweets
19
 
20
  This version runs in mock/demo mode on Hugging Face Spaces.
21
 
 
26
  ## πŸš€ Demo Mode (Hugging Face)
27
 
28
  > This Space runs in **mock mode**, generating fake tweets using `mock_tweet_producer.py`.
29
+ > This allows users to explore the dashboard **without requiring Twitter API credentials or external Kafka setup**.
30
+ >
31
+ > If you have a Twitter API token, you can use `producer.py` and set `os.environ["USE_MOCK"]` to `"false"` in `app.py`.
32
 
33
 
34
  ---
 
36
  ## 🧠 Features
37
 
38
  - Real-time tweet ingestion (simulated or live)
39
+ - Sentiment analysis using keyword-based classification
40
+ - Live sentiment counts: Positive, Neutral, Negative
41
+ - Recent tweet stream with color-coded sentiment tags
42
+ - Hourly sentiment trend visualization
43
+ - WebSocket-powered live dashboard updates
44
+ - Responsive design with modern UI
45
 
46
  ---
47
 
 
49
 
50
  | File/Folder | Purpose |
51
  |------------------------|---------------------------------------------------|
52
+ | `dashboard.py` | Main Flask app + Kafka consumer, flexible for real Kafka data or Hugging Face demo |
53
+ | `templates/dashboard.html` | HTML UI template with real-time charts and tweet display |
54
+ | `mock_tweet_producer.py` | Generates realistic mock tweets for demo/testing |
55
+ | `producer.py` | Twitter API producer for live tweet streaming |
56
+ | `consumer.py` | Spark-based sentiment analysis processor |
57
+ | `docker-compose.yml` | Full microservices setup (Kafka + Spark + Dashboard) |
58
+ | `requirements.txt` | Python dependencies |
59
+ | `.env` (optional) | Twitter API credentials for live data |
60
 
61
  ---
62
 
 
64
 
65
  If you want to stream real tweets and analyze their sentiment:
66
 
67
+ 1. Create a Twitter/X Developer App at [developer.twitter.com](https://developer.twitter.com)
68
  2. Add your **Bearer Token** to a `.env` file:
69
  ```env
70
  BEARER_TOKEN=your_token_here
71
+ 3. Set mock mode to false in app.py:
72
+ os.environ["USE_MOCK"] = "false"
73
+ 4. Run producer.py instead. Run with real data: The system will connect to Twitter API and process live tweets
74
 
75
  ## πŸ§ͺ Local Development
76
 
 
78
  cd sentiment-analysis
79
  docker-compose up --build
80
 
81
+ This will start:
82
+
83
+ πŸ”΄ Kafka: Message broker for tweet streaming
84
+ ⚑ Spark: Real-time sentiment analysis processing
85
+ 🐍 Producer: Tweet ingestion (mock or real)
86
+ πŸ“Š Dashboard: Web interface at http://localhost:5000
87
+
88
  ## πŸ“· Dashboard Preview
89
 
90
  Here's a preview of the sentiment dashboard in action:
91
 
92
  ![Dashboard Overview](assets/dashboard_screenshot1.jpg)
93
+ Main dashboard with real-time sentiment counters and charts
94
  ![Real-Time Tweets and Charts](assets/dashboard_screenshot2.jpg)
95
+ Live tweet feed with sentiment analysis and hourly trends
96
+
97
+ ## πŸ”§ Technologies Used
98
+ - Backend: Python, Flask, Flask-SocketIO
99
+ - Message Streaming: Apache Kafka
100
+ - Stream Processing: Apache Spark
101
+ - Frontend: HTML5, CSS3, JavaScript, Chart.js
102
+ - Real-time Communication: WebSocket
103
+ - Containerization: Docker, Docker Compose
104
+ - API Integration: Twitter API v2
105
+
106
+ *Demo hosted on Hugging Face Spaces with mock data for demonstration purposes.*
app.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ import os
2
+ os.environ["USE_MOCK"] = "true" # Set to false if using real tweets or local kafka
3
+ from dashboard import *
dashboard.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, render_template, jsonify
2
+ from flask_socketio import SocketIO, emit
3
+ import json
4
+ import threading
5
+ import time
6
+ from datetime import datetime
7
+ from collections import defaultdict, deque
8
+ import logging
9
+ import os
10
+ import random
11
+
12
+ app = Flask(__name__)
13
+ app.config['SECRET_KEY'] = 'sentiment-dashboard-secret'
14
+ socketio = SocketIO(app, cors_allowed_origins="*")
15
+
16
+ # In-memory storage for dashboard data
17
+ sentiment_counts = {'positive': 0, 'negative': 0, 'neutral': 0}
18
+ recent_tweets = deque(maxlen=50) # Keep last 50 tweets
19
+ hourly_sentiment = defaultdict(lambda: {'positive': 0, 'negative': 0, 'neutral': 0})
20
+
21
+ logging.basicConfig(level=logging.INFO)
22
+ logger = logging.getLogger(__name__)
23
+
24
+ # Check environment for mock mode
25
+ USE_MOCK = os.environ.get("USE_MOCK", "true").lower() == "true"
26
+
27
+ def kafka_consumer_thread():
28
+ """Background thread to consume processed tweets from Kafka or generate mock data"""
29
+ if USE_MOCK:
30
+ logger.info("Running in MOCK mode - generating demo data")
31
+ mock_tweet_generator()
32
+ else:
33
+ logger.info("Running in KAFKA mode - connecting to real Kafka")
34
+ real_kafka_consumer()
35
+
36
+ def mock_tweet_generator():
37
+ """Generate mock tweets for demo purposes"""
38
+ sentiments = ["positive", "neutral", "negative"]
39
+
40
+ # Sample mock tweets for demo
41
+ sample_tweets = [
42
+ "I absolutely love this new Python framework! Amazing! 🐍✨",
43
+ "Just finished my first machine learning project! So excited! πŸš€",
44
+ "Beautiful sunny day! Perfect for coding β˜•οΈπŸ’»",
45
+ "Finally understood how Kafka works! Awesome technology πŸŽ‰",
46
+ "Ugh, spent 3 hours debugging this error. So frustrated 😀",
47
+ "This API documentation is terrible. Nothing works 😑",
48
+ "Why is deployment always so painful? πŸ’”",
49
+ "Working on a new feature. Should be ready next week.",
50
+ "Attending a tech conference tomorrow. Looking forward to it.",
51
+ "Updated the dependencies. Everything seems fine.",
52
+ "Django vs Flask debate continues. Both are good.",
53
+ "Love how clean Python code can be. Beautiful language!",
54
+ "FastAPI is becoming my go-to for REST APIs. So fast!",
55
+ "NumPy arrays are much faster than regular lists.",
56
+ "Jupyter notebooks are perfect for data exploration.",
57
+ ]
58
+
59
+ tweet_count = 0
60
+
61
+ while True:
62
+ try:
63
+ # Generate a mock tweet
64
+ sentiment = random.choice(sentiments)
65
+ tweet_text = random.choice(sample_tweets)
66
+
67
+ tweet_data = {
68
+ 'text': tweet_text,
69
+ 'sentiment': sentiment,
70
+ 'timestamp': datetime.now().strftime('%H:%M:%S'),
71
+ 'author_id': f'user_{random.randint(1000, 9999)}'
72
+ }
73
+
74
+ # Update sentiment counts
75
+ sentiment_counts[sentiment] += 1
76
+
77
+ # Add to recent tweets
78
+ recent_tweets.append(tweet_data)
79
+
80
+ # Update hourly data
81
+ hour = datetime.now().strftime('%H:00')
82
+ hourly_sentiment[hour][sentiment] += 1
83
+
84
+ # Emit real-time update to connected clients
85
+ socketio.emit('sentiment_update', {
86
+ 'sentiment_counts': dict(sentiment_counts),
87
+ 'recent_tweets': list(recent_tweets),
88
+ 'hourly_data': dict(hourly_sentiment)
89
+ })
90
+
91
+ tweet_count += 1
92
+ logger.info(f"Generated mock tweet #{tweet_count} with sentiment: {sentiment}")
93
+
94
+ # Random delay between tweets (1-3 seconds for demo)
95
+ time.sleep(random.uniform(1, 3))
96
+
97
+ except Exception as e:
98
+ logger.error(f"Error in mock tweet generator: {e}")
99
+ time.sleep(5)
100
+
101
+ def real_kafka_consumer():
102
+ """Real Kafka consumer for production use"""
103
+ try:
104
+ from kafka import KafkaConsumer
105
+ from kafka.errors import NoBrokersAvailable
106
+
107
+ def create_kafka_consumer(max_retries=10, retry_delay=5):
108
+ """Create Kafka consumer with retry logic"""
109
+ for attempt in range(max_retries):
110
+ try:
111
+ consumer = KafkaConsumer(
112
+ 'sentiment-results',
113
+ bootstrap_servers=['kafka:9092'],
114
+ value_deserializer=lambda m: json.loads(m.decode('utf-8')),
115
+ consumer_timeout_ms=1000,
116
+ auto_offset_reset='earliest',
117
+ enable_auto_commit=True,
118
+ group_id='dashboard-group'
119
+ )
120
+ logger.info("Successfully connected to Kafka consumer!")
121
+ return consumer
122
+ except NoBrokersAvailable as e:
123
+ logger.warning(f"Kafka not ready, attempt {attempt + 1}/{max_retries}. Retrying in {retry_delay}s...")
124
+ time.sleep(retry_delay)
125
+ except Exception as e:
126
+ logger.error(f"Unexpected error connecting to Kafka: {e}")
127
+ time.sleep(retry_delay)
128
+
129
+ raise Exception(f"Could not connect to Kafka consumer after {max_retries} attempts")
130
+
131
+ # Wait for Kafka and Spark to be ready
132
+ logger.info("Waiting for Kafka and Spark services to be ready...")
133
+ time.sleep(10)
134
+
135
+ consumer = create_kafka_consumer()
136
+ logger.info("Connected to Kafka consumer for dashboard - waiting for processed tweets...")
137
+
138
+ message_count = 0
139
+
140
+ while True:
141
+ try:
142
+ # Poll for messages with timeout
143
+ message_batch = consumer.poll(timeout_ms=1000)
144
+
145
+ if message_batch:
146
+ logger.info(f"Received batch with {len(message_batch)} topic partitions")
147
+
148
+ for topic_partition, messages in message_batch.items():
149
+ logger.info(f"Processing {len(messages)} messages from {topic_partition}")
150
+
151
+ for message in messages:
152
+ try:
153
+ tweet_data = message.value
154
+ message_count += 1
155
+ logger.info(f"Message {message_count}: Received tweet data: {tweet_data}")
156
+
157
+ # Update sentiment counts
158
+ sentiment = tweet_data.get('sentiment', 'neutral')
159
+ sentiment_counts[sentiment] += 1
160
+
161
+ # Add to recent tweets
162
+ recent_tweets.append({
163
+ 'text': tweet_data.get('tweet_text', '')[:100] + '...' if len(tweet_data.get('tweet_text', '')) > 100 else tweet_data.get('tweet_text', ''),
164
+ 'sentiment': sentiment,
165
+ 'timestamp': datetime.now().strftime('%H:%M:%S'),
166
+ 'author_id': tweet_data.get('author_id', 'Unknown')
167
+ })
168
+
169
+ # Update hourly data
170
+ hour = datetime.now().strftime('%H:00')
171
+ hourly_sentiment[hour][sentiment] += 1
172
+
173
+ # Emit real-time update to connected clients
174
+ socketio.emit('sentiment_update', {
175
+ 'sentiment_counts': dict(sentiment_counts),
176
+ 'recent_tweets': list(recent_tweets),
177
+ 'hourly_data': dict(hourly_sentiment)
178
+ })
179
+
180
+ logger.info(f"Processed tweet with sentiment: {sentiment} - Total counts: {dict(sentiment_counts)}")
181
+
182
+ except Exception as e:
183
+ logger.error(f"Error processing individual tweet data: {e}")
184
+ else:
185
+ if message_count == 0:
186
+ logger.info("No messages received yet, continuing to poll...")
187
+ time.sleep(1)
188
+
189
+ except Exception as e:
190
+ logger.error(f"Error in polling loop: {e}")
191
+ time.sleep(5)
192
+
193
+ except ImportError:
194
+ logger.warning("kafka-python not available, falling back to mock mode")
195
+ mock_tweet_generator()
196
+ except Exception as e:
197
+ logger.error(f"Error in real Kafka consumer: {e}")
198
+ logger.info("Falling back to mock mode")
199
+ mock_tweet_generator()
200
+
201
+ @app.route('/')
202
+ def dashboard():
203
+ """Main dashboard page"""
204
+ return render_template('dashboard.html')
205
+
206
+ @app.route('/api/data')
207
+ def get_data():
208
+ """API endpoint to get current dashboard data"""
209
+ data = {
210
+ 'sentiment_counts': dict(sentiment_counts),
211
+ 'recent_tweets': list(recent_tweets),
212
+ 'hourly_data': dict(hourly_sentiment),
213
+ 'total_tweets': sum(sentiment_counts.values())
214
+ }
215
+ logger.info(f"API request - returning data: {data}")
216
+ return jsonify(data)
217
+
218
+ @socketio.on('connect')
219
+ def handle_connect():
220
+ """Handle client connection"""
221
+ logger.info("Client connected to dashboard")
222
+ emit('sentiment_update', {
223
+ 'sentiment_counts': dict(sentiment_counts),
224
+ 'recent_tweets': list(recent_tweets),
225
+ 'hourly_data': dict(hourly_sentiment)
226
+ })
227
+
228
+ if __name__ == '__main__':
229
+ # Start consumer thread (either mock or real Kafka)
230
+ consumer_thread = threading.Thread(target=kafka_consumer_thread, daemon=True)
231
+ consumer_thread.start()
232
+
233
+ mode = "MOCK" if USE_MOCK else "KAFKA"
234
+ logger.info(f"Starting sentiment dashboard in {mode} mode on port 5000")
235
+
236
+ if USE_MOCK:
237
+ logger.info("Dashboard will display mock demo data")
238
+ else:
239
+ logger.info("Dashboard will display data once Spark processes tweets from Kafka")
240
+
241
+ # Get port from environment (Hugging Face Spaces uses port 7860)
242
+ port = int(os.environ.get('PORT', 5000))
243
+
244
+ # Fix for Werkzeug warning - use allow_unsafe_werkzeug for development
245
+ socketio.run(app, host='0.0.0.0', port=port, debug=False, allow_unsafe_werkzeug=True)