-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun.py
More file actions
243 lines (195 loc) Β· 8.53 KB
/
run.py
File metadata and controls
243 lines (195 loc) Β· 8.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
"""
Main entry point for Social Pulse Analytics
Handles application startup, data collection scheduling, and dashboard launch
"""
import os
import sys
import threading
import time
import schedule
import subprocess
from datetime import datetime
# Add app directory to path
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from app.config import config
from app.database import db
from collectors.reddit_collector import reddit_collector
from collectors.news_collector import news_collector
from analyzers.sentiment_analyzer import sentiment_analyzer
def collect_and_analyze_data():
"""Collect data from all sources and perform analysis"""
print(f"\nπ Starting data collection at {datetime.now()}")
try:
# Validate configuration
config.validate_config()
print("β
Configuration validated")
# Collect Reddit data
print("π± Collecting Reddit data...")
reddit_posts = reddit_collector.collect_all_posts()
if reddit_posts:
print(f" Found {len(reddit_posts)} Reddit posts")
# Analyze sentiment
print(" π Analyzing Reddit sentiment...")
analyzed_posts = sentiment_analyzer.analyze_reddit_posts(reddit_posts)
# Save to database
saved_count = db.insert_reddit_posts([post.to_dict() for post in analyzed_posts])
print(f" πΎ Saved {saved_count} Reddit posts to database")
else:
print(" β οΈ No Reddit posts collected")
# Collect News data
print("π° Collecting News data...")
news_articles = news_collector.collect_all_articles()
if news_articles:
print(f" Found {len(news_articles)} news articles")
# Analyze sentiment
print(" π Analyzing news sentiment...")
analyzed_articles = sentiment_analyzer.analyze_news_articles(news_articles)
# Save to database
saved_count = db.insert_news_articles([article.to_dict() for article in analyzed_articles])
print(f" πΎ Saved {saved_count} news articles to database")
else:
print(" β οΈ No news articles collected")
# Clean old data
print("π§Ή Cleaning old data...")
db.clean_old_data(days=7)
print(f"β
Data collection completed at {datetime.now()}")
except ValueError as e:
print(f"β Configuration error: {e}")
print("\nπ§ Please check your .env file and ensure all API keys are set correctly.")
return False
except Exception as e:
print(f"β Error during data collection: {e}")
return False
return True
def setup_scheduler():
"""Setup the data collection scheduler"""
# Schedule data collection every 30 minutes
schedule.every(config.UPDATE_INTERVAL).minutes.do(collect_and_analyze_data)
print(f"β° Scheduled data collection every {config.UPDATE_INTERVAL} minutes")
def run_scheduler():
while True:
schedule.run_pending()
time.sleep(60) # Check every minute
# Run scheduler in background thread
scheduler_thread = threading.Thread(target=run_scheduler, daemon=True)
scheduler_thread.start()
return scheduler_thread
def launch_streamlit_dashboard():
"""Launch the Streamlit dashboard"""
dashboard_file = os.path.join(os.path.dirname(__file__), "dashboard", "streamlit_app.py")
cmd = [
sys.executable, "-m", "streamlit", "run",
dashboard_file,
"--server.port", str(config.STREAMLIT_PORT),
"--server.address", "localhost",
"--browser.gatherUsageStats", "false"
]
print(f"π Launching Streamlit dashboard on http://localhost:{config.STREAMLIT_PORT}")
try:
# Launch Streamlit
process = subprocess.Popen(cmd)
return process
except Exception as e:
print(f"β Error launching Streamlit: {e}")
return None
def check_initial_setup():
"""Check if this is the first run and setup accordingly"""
print("π Checking initial setup...")
# Check if .env file exists
env_file = os.path.join(os.path.dirname(__file__), '.env')
if not os.path.exists(env_file):
print("\nβ οΈ No .env file found!")
print("π Please create a .env file based on .env.example")
print("π You'll need API keys from:")
print(" - Reddit: https://www.reddit.com/prefs/apps")
print(" - NewsAPI: https://newsapi.org/register")
return False
# Check if database exists, create if not
try:
db.create_tables()
print("β
Database setup completed")
except Exception as e:
print(f"β Database setup error: {e}")
return False
return True
def show_startup_info():
"""Show application startup information"""
print("=" * 60)
print("π§ SOCIAL PULSE ANALYTICS")
print(" Understanding Human Nature Through Social Media")
print("=" * 60)
print(f"π Database: {config.DATABASE_PATH}")
print(f"β° Update Interval: {config.UPDATE_INTERVAL} minutes")
print(f"π Dashboard Port: {config.STREAMLIT_PORT}")
print(f"π± Reddit Subreddits: {len(config.REDDIT_SUBREDDITS)}")
print("=" * 60)
def main():
"""Main application entry point"""
show_startup_info()
# Check initial setup
if not check_initial_setup():
print("\nβ Setup incomplete. Please fix the issues above and try again.")
return
print("\nπ― Choose an option:")
print("1. Collect data once and exit")
print("2. Launch dashboard with auto-collection")
print("3. Launch dashboard only (no data collection)")
try:
choice = input("\nEnter choice (1-3): ").strip()
except KeyboardInterrupt:
print("\nπ Goodbye!")
return
if choice == "1":
# One-time data collection
print("\nπ Running one-time data collection...")
success = collect_and_analyze_data()
if success:
print("\nβ
Data collection completed successfully!")
print("π‘ You can now run option 3 to view the dashboard")
else:
print("\nβ Data collection failed. Please check your API keys.")
elif choice == "2":
# Launch dashboard with auto-collection
print("\nπ Starting full application...")
# Initial data collection
print("π Performing initial data collection...")
initial_success = collect_and_analyze_data()
if not initial_success:
print("β οΈ Initial data collection failed, but continuing with dashboard...")
# Setup scheduler
scheduler_thread = setup_scheduler()
# Launch dashboard
dashboard_process = launch_streamlit_dashboard()
if dashboard_process:
try:
print("\nβ
Application running!")
print("π Open your browser to view the dashboard")
print("βΉοΈ Press Ctrl+C to stop the application")
# Wait for user interrupt
dashboard_process.wait()
except KeyboardInterrupt:
print("\nβΉοΈ Stopping application...")
dashboard_process.terminate()
print("π Goodbye!")
else:
print("β Failed to launch dashboard")
elif choice == "3":
# Dashboard only
print("\nπ Launching dashboard only...")
dashboard_process = launch_streamlit_dashboard()
if dashboard_process:
try:
print("\nβ
Dashboard launched!")
print("π Open your browser to view the dashboard")
print("βΉοΈ Press Ctrl+C to stop")
dashboard_process.wait()
except KeyboardInterrupt:
print("\nβΉοΈ Stopping dashboard...")
dashboard_process.terminate()
print("π Goodbye!")
else:
print("β Failed to launch dashboard")
else:
print("β Invalid choice. Please run the application again.")
if __name__ == "__main__":
main()