-
Notifications
You must be signed in to change notification settings - Fork 1
/
TweetPinnaGraphs.py
203 lines (170 loc) · 7.63 KB
/
TweetPinnaGraphs.py
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""TweetPinna - Twitter Status Archiver - Dashboard.
TweetPinna streams Twitter statuses into a
MongoDB database based on given search terms.
It is also capable of retrieving a user's timeline.
This script generates graphs for the dashboard.
It is supposed to run as a cronjob.
e.g.
*/10 * * * * bash -c "cd /root/TweetPinna &&
python TweetPinnaGraphs.py TweetPinnaDefault.cfg"
Author: Ingo Kleiber <ingo@kleiber.me> (2017)
License: MIT
Version: 1.1.1
Status: Protoype
Example:
$ python TweetPinnaGraphs.py config.cfg
"""
import matplotlib
matplotlib.use('Agg')
from pymongo import MongoClient
from TweetPinna import check_config
from TweetPinna import Logger
import config
import matplotlib.pyplot as plt
import os
import pandas as pd
import sys
import time
import numpy as np
try:
if os.path.isfile(sys.argv[1]):
if check_config(sys.argv[1]):
cfg = config.Config(open(sys.argv[1], 'r'))
log = Logger(cfg)
else:
print ('Configuration appears to be faulty')
sys.exit(1)
else:
print ('Configuration file {} could not be found'.format(sys.argv[1]))
sys.exit(1)
except IndexError:
print ('Using default configuration')
cfg = config.Config(open('cfg/TweetPinnaDefault.cfg', 'r'))
log = Logger(cfg)
plt.style.use('ggplot')
log = Logger(cfg)
if not os.path.isdir('dashboard/static/img/results'):
os.makedirs('dashboard/static/img/results')
# MongoDB
mongo_client = MongoClient(cfg['mongo_path'])
mongo_db = mongo_client[cfg['mongo_db']]
mongo_coll_tweets = mongo_db[cfg['mongo_coll']]
def tweets_by_hour(n):
"""Generating a barchart showing the last n tweets by hour.
:param int n: the number of tweets to consider
"""
try:
tweet_timestamps = list(mongo_coll_tweets.find(
{'timestamp_ms': {'$exists': True}}, {'timestamp_ms': 1, '_id': 0}).sort([['_id', -1]]).limit(n))
tweet_datetimes = pd.to_datetime(
np.array(list(map(int, [d['timestamp_ms'] for d in tweet_timestamps]))), unit='ms')
df = pd.DataFrame(tweet_datetimes, columns=['date'])
df.set_index('date', drop=False, inplace=True)
grouped_df = df.groupby(pd.Grouper(freq='1h')).count()
grouped_df_average = grouped_df["date"].sum() / len(grouped_df)
tweets_by_hour = grouped_df.plot(
kind='bar', legend=False, color='#262626', rot=75)
tweets_by_hour.set_xlabel('Date', fontsize=12)
tweets_by_hour.set_ylabel('Nr. of Tweets', fontsize=12)
tweets_by_hour.set_title(
'Tweets by Hour\n({} Tweets, avg. {} Tweets/h)\n {}'.format(
n, round(grouped_df_average), time.strftime("%Y-%m-%d %H:%M:%S")),
position=(0.5, 1.05))
tweets_by_hour.get_figure().savefig(
'dashboard/static/img/results/tweets-by-hour.png',
bbox_inches='tight')
log.log_add(1, 'Graph tweets-by-hour.png created')
except Exception as e:
log.log_add(3, 'Graph tweets-by-hour.png could \
not be created ({})'.format(e))
return False
def tweets_by_day(n):
"""Generating a barchart showing the last n tweets by day.
:param int n: the number of tweets to consider
"""
try:
tweet_timestamps = list(mongo_coll_tweets.find(
{'timestamp_ms': {'$exists': True}}, {'timestamp_ms': 1, '_id': 0}).sort([['_id', -1]]).limit(n))
tweet_datetimes = pd.to_datetime(
np.array(list(map(int, [d['timestamp_ms'] for d in tweet_timestamps]))), unit='ms')
df = pd.DataFrame(tweet_datetimes, columns=['date'])
df.set_index('date', drop=False, inplace=True)
grouped_df = df.groupby(pd.Grouper(freq='1d')).count()
grouped_df_average = grouped_df["date"].sum() / len(grouped_df)
grouped_df['day'] = grouped_df.date.keys().strftime('%Y-%m-%d')
tweets_by_day = grouped_df.plot(
kind='bar', x='day', legend=False, color='#262626',
rot=75)
tweets_by_day.set_xlabel('Date', fontsize=12)
tweets_by_day.set_ylabel('Nr. of Tweets', fontsize=12)
tweets_by_day.set_title(
'Tweets by Day\n({} Tweets, avg. {} Tweets/day)\n {}'.
format(n, round(grouped_df_average), time.strftime("%Y-%m-%d %H:%M:%S")),
position=(0.5, 1.05))
tweets_by_day.get_figure().savefig(
'dashboard/static/img/results/tweets-by-day.png',
bbox_inches='tight')
log.log_add(1, 'Graph tweets-by-day.png created')
except Exception as e:
log.log_add(3,
'Graph tweets-bay-day.png could \
not be created ({})'.format(e))
return False
def tweets_over_time(n):
"""Generating a chart of the overall development of the collection.
:param int n: the number of tweets to consider
"""
try:
tweet_timestamps = list(mongo_coll_tweets.find(
{'timestamp_ms': {'$exists': True}}, {'timestamp_ms': 1, '_id': 0}).sort([['_id', -1]]).limit(n))
tweet_datetimes = pd.to_datetime(
np.array(list(map(int, [d['timestamp_ms'] for d in tweet_timestamps]))), unit='ms')
df = pd.DataFrame(tweet_datetimes, columns=['date'])
df.set_index('date', drop=False, inplace=True)
grouped_df = df.groupby(pd.Grouper(freq='1d')).count()
grouped_df_average = grouped_df["date"].sum() / len(grouped_df)
tweets_over_time = grouped_df.cumsum().plot(
kind='area', legend=False, color='#262626',
stacked='False', rot=75)
tweets_over_time.set_xlabel('Date', fontsize=12)
tweets_over_time.set_ylabel('Nr. of Additional Tweets', fontsize=12)
tweets_over_time.set_title('Tweets over Time\n({} Tweets, avg. {} Tweets/day)\n {})'.
format(n, round(grouped_df_average), time.strftime("%Y-%m-%d %H:%M:%S")),
position=(0.5, 1.05))
tweets_over_time.get_figure().savefig(
'dashboard/static/img/results/tweets-over-time.png',
bbox_inches='tight')
log.log_add(1, 'Graph tweets-over-time.png created')
except Exception as e:
log.log_add(3,
'Graph tweets-over-time.png could \
not be created ({})'.format(e))
return False
if __name__ == '__main__':
# Graphs
# Tweets by Hour
if (os.path.isfile('dashboard/static/img/results/tweets-by-hour.png')):
if (os.path.getmtime
('dashboard/static/img/results/tweets-by-hour.png') <
(time.time() - cfg['refresh_graphs'] * 60)):
tweets_by_hour(cfg['tweets_by_hour_number'])
else:
tweets_by_hour(cfg['tweets_by_hour_number'])
# Tweets by Day
if (os.path.isfile('dashboard/static/img/results/tweets-by-day.png')):
if (os.path.getmtime
('dashboard/static/img/results/tweets-by-day.png') <
(time.time() - cfg['refresh_graphs'] * 60)):
tweets_by_day(cfg['tweets_by_day_number'])
else:
tweets_by_day(cfg['tweets_by_day_number'])
# Tweets over Time
if (os.path.isfile('dashboard/static/img/results/tweets-over-time.png')):
if (os.path.getmtime
('dashboard/static/img/results/tweets-over-time.png') <
(time.time() - cfg['refresh_graphs'] * 60)):
tweets_over_time(cfg['tweets_overall_limit'])
else:
tweets_over_time(cfg['tweets_overall_limit'])