-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
1906 lines (1440 loc) · 74.5 KB
/
app.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
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import json
import datetime as dt
import calendar
import pytz
from itertools import groupby
import requests
from requests_oauthlib import OAuth1
import pandas as pd
import numpy as np
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
from keras.models import load_model
from keras import backend as K
from sklearn.feature_extraction.text import CountVectorizer
from scipy.sparse import csr_matrix
from sklearn.externals import joblib
from sklearn.preprocessing import LabelEncoder
import random
import pickle
import nltk
import re
import string
from flask import Flask, jsonify, render_template, request, redirect, url_for, session
from Candidates import candidates_list
app = Flask(__name__)
# app.secret_key = os.urandom(24)
# app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///db/candidates_tweets.sqlite"
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///db/twitter_db.sqlite"
# engine = create_engine('sqlite:///db/candidates_tweets.sqlite', echo = False)
engine = create_engine('sqlite:///db/twitter_db.sqlite', echo = False)
# Declare a Base using automap_base()
Base = automap_base()
# Use the Base class to reflect the database tables
Base.prepare(engine, reflect=True)
# Assign the table classes to variables
Tweets = Base.classes.tweet_data
Update = Base.classes.database_update
Moving_Averages = Base.classes.moving_averages
######
ck = os.environ.get('TWITTER_API_KEY')
cs = os.environ.get('TWITTER_API_SECRET')
at = os.environ.get('TWITTER_ACCESS_TOKEN')
ats = os.environ.get('TWITTER_ACCESS_SECRET')
# Create authorization object
auth = OAuth1(ck, cs, at, ats)
# Required callback_url for twitter authorization
callback_url = "https://tweetocracy.herokuapp.com/"
payload = {
'oauth_callback':callback_url
}
# local testing
# Payload object sends required callback info to twitter API
# payload = {
# 'oauth_callback':"http://127.0.0.1:5000/"
# }
# Execute a POST/Auth request to twittier api to intitiate access
r = requests.post('https://api.twitter.com/oauth/request_token', auth = auth, data = payload)
# print(f'Post Request Token URL:{r.url}')
# print(f'Post Request Status:{r.status_code}')
# print(f'Post Request Text: {r.text}')
# Collect response information
response_output = r.text
# Relevant paramters are received as a string, separated by an '&' character
response_parameters = response_output.split("&")
# Store relevant response paramters in variables
oauth_token = response_parameters[0][12:]
# print(f'OAuth_token:{oauth_token}')
oauth_token_secret=response_parameters[1][19:]
# print(f'Oauth Token Secret:{oauth_token_secret}')
oauth_callback_confirmed = bool(response_parameters[2][25:])
# print(f'Callback Confirmed:{oauth_callback_confirmed}')
extended_payload = {
'tweet_mode': 'extended'
}
#Set up routes
@app.route('/')
def index():
query_string = request.query_string
print(f'Query String: {query_string.decode()}')
# print(type(query_string.decode()))
request_token = request.args.get("oauth_token")
print(f'Query Request Token:{request_token}')
print(f'Query Request Token == Oauth Request? {request_token == oauth_token}')
oauth_verifier = request.args.get("oauth_verifier")
if request_token == oauth_token and oauth_verifier:
print("works!")
auth_access = OAuth1(ck, cs, oauth_token, oauth_token_secret)
payload_access = {
'oauth_verifier':oauth_verifier
}
r_access = requests.post("https://api.twitter.com/oauth/access_token", auth = auth_access, data = payload_access)
r_access_text = r_access.text
print(f'Post Access Status: {r_access.status_code}')
print(f'Post Access Text: {r_access_text}')
post_access_params = r_access_text.split("&")
print(post_access_params)
access_token = post_access_params[0][12:]
print(f'Access Token: {access_token}')
access_token_secret = post_access_params[1][19:]
print(f'Access Token SEcret: {access_token_secret}')
screen_name = post_access_params[3][12:]
print(f'Screen Name: {screen_name}')
#### Testing
final_access = OAuth1(ck, cs, access_token, access_token_secret)
# tweet = requests.get("https://api.twitter.com/1.1/statuses/show.json?id=1152577020594917376", params = extended_payload, auth = final_access)
# tweet_json = tweet.json()
# print(json.dumps(tweet_json, indent=4))
## user timeline testing
timeline = requests.get("https://api.twitter.com/1.1/statuses/user_timeline.json?id=25073877&count=2", auth = final_access)
timeline_status = timeline.status_code
print(f'Timeline Status: {timeline_status}')
timeline_json = timeline.json()
print(json.dumps(timeline_json, indent = 4))
# session["username"] = screen_name
# print(access_token)
# print(access_token_secret)
# print(user_id)
# print(screen_name)
# if r_access.status_code == 200:
# return redirect(url_for('test'))
# else:
# return redirect(url_for('fail'))
return render_template('index.html')
#Route for direcitng to "Machine Learning" page
@app.route("/machine_learning")
def machine_learning():
return render_template('machine_learning.html')
# Function for filtering out tweets which are newer than two days (Gives the tweet stats time to mature)
def filter_aged(list_element):
date_string = list_element["created_at"]
datetime_object = dt.datetime.strptime(date_string, "%a %b %d %H:%M:%S %z %Y")
date_object = datetime_object.date()
today_datetime = dt.datetime.utcnow()
today_date = today_datetime.date()
two_days_prior = today_date - dt.timedelta(days = 2)
training_data = dt.date(2019, 8, 14)
return ((date_object <= two_days_prior) and (date_object > training_data))
# return date_object > training_data
# Functions for returning day, hour, month values from a datetime string
def convert_day(date_string):
datetime_object = dt.datetime.strptime(date_string, "%a %b %d %H:%M:%S %z %Y")
day = dt.datetime.strftime(datetime_object, "%A")
return day
def convert_hour(date_string):
datetime_object = dt.datetime.strptime(date_string, "%a %b %d %H:%M:%S %z %Y")
hour = dt.datetime.strftime(datetime_object, "%H")
return hour
def convert_month(date_string):
datetime_object = dt.datetime.strptime(date_string, "%a %b %d %H:%M:%S %z %Y")
month = dt.datetime.strftime(datetime_object, "%B")
return month
stopwords = nltk.corpus.stopwords.words('english')
wn = nltk.WordNetLemmatizer()
# Funciton for processing text data (remove punctuation, tokenization, lemmatization)
def clean_text(text):
text = text.replace('&', '&')
text = text.replace('\n', ' ')
text = "".join([word.lower() for word in text if word not in string.punctuation])
tokens = re.split('\W+', text)
text = [wn.lemmatize(word) for word in tokens if word not in stopwords]
return text
@app.route("/machine_learning_tweet")
def machine_learning_tweet():
with open('jupyter_notebook_code/top_candidates.pkl', 'rb') as f:
top_candidates = pickle.load(f)
filtered_candidates = list(filter(lambda x: x["name"] in top_candidates, candidates_list))
random_candidate = random.choice(filtered_candidates)
candidate_id = random_candidate["twitter_user_id"]
user_get = requests.get(f'https://api.twitter.com/1.1/statuses/user_timeline.json?id={candidate_id}&count=100', params = extended_payload, auth = auth)
user_json = user_get.json()
user_filtered = list(filter(lambda x: filter_aged(x), user_json))
tweet_selection = random.choice(user_filtered)
tweet_dict = {
'full_text': tweet_selection["full_text"],
'retweet_count': tweet_selection["retweet_count"],
'favorite_count': tweet_selection['favorite_count'],
'created_at': tweet_selection['created_at'],
'user_name': tweet_selection['user']['name'],
'user_id_str': tweet_selection['user']['id_str']
}
tweet_dict['day'] = convert_day(tweet_dict['created_at'])
tweet_dict['hour'] = convert_hour(tweet_dict['created_at'])
tweet_dict['month'] = convert_month(tweet_dict['created_at'])
tweet_list = [tweet_dict]
tweet_df = pd.DataFrame(tweet_list)
# NGramVectorizer
ngram_vect = CountVectorizer(ngram_range=(2,2), analyzer=clean_text)
ngram_vect.fit_transform(tweet_df['full_text'])
# __location__ = os.path.dirname(os.path.realpath(__file__))
# print(__location__)
# config_dir = os.path.join(__location__, "config")
# print(config_dir)
# print(os.getcwd())
# retrieve column names from trained model
with open('jupyter_notebook_code/rf_columns.pkl', 'rb') as f:
columns_list = pickle.load(f)
null_list = []
for i in range(0, len(columns_list)):
null_list.append(0)
X_features = dict(zip(columns_list, null_list))
X_features['retweet_count'] = tweet_dict['retweet_count']
X_features['favorite_count'] = tweet_dict['favorite_count']
select_month = tweet_dict['month']
select_day = tweet_dict['day']
select_hour = tweet_dict['hour']
X_features[f'month_{select_month}'] = 1
X_features[f'day_{select_day}'] = 1
X_features[f'hour_{select_hour}'] = 1
for word in ngram_vect.get_feature_names():
if word in X_features.keys():
X_features[word] += 1
X_features = np.array(list(X_features.values())).reshape((1, 18591))
X_sparse = csr_matrix(X_features)
scaler_filename = "jupyter_notebook_code/rf_scaler.save"
scaler = joblib.load(scaler_filename)
X_scaled = scaler.transform(X_sparse)
encoder = LabelEncoder()
encoder.classes_ = np.load('jupyter_notebook_code/rf_classes.npy', allow_pickle = True)
with open('jupyter_notebook_code/rf_model.sav', 'rb') as f:
model = pickle.load(f)
# K.clear_session()
prediction_prob = model.predict_proba(X_scaled)
prediction_prob = [float(i) for i in prediction_prob[0]]
classes_prob = list(zip(prediction_prob, encoder.classes_))
sorted_class = sorted(classes_prob, key = lambda x: x[0], reverse = True)
sorted_top = sorted_class[0:2]
tweet_dict['full_text'] = tweet_dict['full_text'].replace('&', '&')
tweet_dict['full_text'] = tweet_dict['full_text'].replace('\n', ' ')
tweet_dict['predictions'] = sorted_top
# sorted_json = json.dumps(sorted_top)
# K.clear_session()
return (jsonify(**tweet_dict))
# Route for initializing "At a Glance" graph
@app.route('/aag_init')
def aag_init():
# Create Session for reading/updating database
session = Session(engine)
# Initiate 'at a glance' graph from current_date to 30 days prior
today_datetime = dt.datetime.utcnow()
today_date = today_datetime.date()
thirty_days_ago = dt.date.today() - dt.timedelta(days = 30)
average_query = session.query(Tweets.user_name,
func.avg(Tweets.retweet_count),
func.avg(Tweets.favorite_count)).\
filter(Tweets.created_at_date >= thirty_days_ago).\
filter(Tweets.created_at_date <= today_date).\
group_by(Tweets.user_name).all()
keys = ('user_name', 'retweet_average', 'favorite_average')
graph_data_list = [dict(zip(keys, values)) for values in average_query]
response_json = json.dumps(graph_data_list)
# print(response_json)
session.close()
return jsonify(response_json)
# Route for initializing "Moving Average" graph
@app.route("/moving_average_init")
def moving_average_init():
# Initiate 'moving average' graph from current_date to 30 days prior
today_datetime = dt.datetime.utcnow()
today_date = today_datetime.date()
thirty_days_ago = dt.date.today() - dt.timedelta(days = 30)
session = Session(engine)
moving_average_list = []
moving_average_query = session.query(Moving_Averages.candidate_name,
Moving_Averages.date,
Moving_Averages.retweet_moving_average,
Moving_Averages.favorite_moving_average).\
filter(Moving_Averages.date >= thirty_days_ago).\
filter(Moving_Averages.date <= today_date)
keys = ("user_name", "moving_average_date", "retweet_moving_average", "favorite_moving_average")
# Iteration for converting sqlalchemy date response into date string and appening to list
for query in moving_average_query:
list_query = list(query)
list_query[1] = dt.datetime.strftime(list_query[1], "%Y-%m-%d")
moving_average_dict = dict(zip(keys, list_query))
moving_average_list.append(moving_average_dict)
# print(moving_average_list)
session.close()
moving_average_json = json.dumps(moving_average_list)
return moving_average_json
# Ref ("/time_init") function used for sorting query based on hour, necessary for groupby
def time_sort(time):
index_select = time[3]
index_select = dt.time.strftime(index_select, "%H")
return index_select
# Route for initializing "Time" graph
@app.route("/time_init")
def time_init():
# Initiate "time" graph from current date to 30 days prior
today_datetime = dt.datetime.utcnow()
today_date = today_datetime.date()
thirty_days_ago = dt.date.today() - dt.timedelta(days = 30)
session = Session(engine)
time_list = []
init_user_name = candidates_list[0]["name"]
init_user_id = candidates_list[0]["twitter_user_id"]
#Initial candidate displayed == "Joe Biden"
#Initial "time" selection == "hourly"
time_query = session.query(Tweets.user_name, Tweets.retweet_count,
Tweets.favorite_count, Tweets.created_at_time).\
filter(Tweets.created_at_date >= thirty_days_ago).\
filter(Tweets.created_at_date <= today_date).\
filter(Tweets.user_id_str == init_user_id)
time_sorted_list = sorted(time_query, key = time_sort)
keys = ("user_name", "retweet_average", "favorite_average", "Hour")
for k, g in groupby(time_sorted_list, key = time_sort):
current_list = list(g)
group_retweet_list = list(map(lambda x: x[1], current_list))
group_favorite_list = list(map(lambda x: x[2], current_list))
group_retweet_average = np.mean(group_retweet_list)
group_favorite_average = np.mean(group_favorite_list)
group_tuple = (init_user_name, group_retweet_average, group_favorite_average, k)
group_dict = dict(zip(keys, group_tuple))
time_list.append(group_dict)
time_json = json.dumps(time_list)
session.close()
return time_json
@ app.route("/histogram_init")
def dist_init():
# Initiate "histogram" graph from current date to 30 days prior
today_datetime = dt.datetime.utcnow()
today_date = today_datetime.date()
thirty_days_ago = dt.date.today() - dt.timedelta(days = 30)
session = Session(engine)
histogram_query = session.query(Tweets.retweet_count).\
filter(Tweets.created_at_date >= thirty_days_ago).\
filter(Tweets.created_at_date <= today_date).\
order_by(Tweets.retweet_count)
# print("histogram query")
# print(histogram_query)
# print("*histogram_query")
# print(*histogram_query)
# print("zip(*histogram_query)")
# print(zip(*histogram_query))
# print("list(zip(*histogram_query))")
# print(list(zip(*histogram_query)))
# Query returned into a list of separate tuples, below combines all tuples into one
[histogram_query] = list(zip(*histogram_query))
# Create iterator
query_iter = iter(histogram_query)
#Find min and max values
range_query = session.query(func.min(Tweets.retweet_count),
func.max(Tweets.retweet_count)).\
filter(Tweets.created_at_date >=thirty_days_ago).\
filter(Tweets.created_at_date <= today_date).first()
min_value = range_query[0]
max_value = range_query[1]
# Find range
histogram_range = max_value - min_value
#Define # of histogram bars (100)
histogram_bars = 100
# Find range for each bar
bar_range = histogram_range / histogram_bars
histogram_list = []
# Create and append dicts which contain the value ranges for the bars with "0" value count
for x in range(0, histogram_bars):
begin_value = min_value + x * bar_range
end_value = begin_value + bar_range
begin_str = "{:,}".format(round(begin_value, 2))
end_str = "{:,}".format(round(end_value, 2))
range_str = begin_str + "-" + end_str
hist_dict = {
'begin': begin_value,
'end': end_value,
'tick': range_str,
'count': 0
}
histogram_list.append(hist_dict)
# Iterate through query, find a dict that fits, and increase count by one
# "Value Error" raised for last item in query because the filter function does not yield a dict for this value. In this case it is simple to just increase the value of the last dict by one
for y in query_iter:
try:
[current_bar] = list(filter(lambda x: y >= x["begin"] and y < x["end"], histogram_list))
current_bar["count"] += 1
except ValueError:
histogram_list[-1]["count"] += 1
histogram_json = json.dumps(histogram_list)
session.close()
return histogram_json
def user_sort(query):
index_select = query[1]
return index_select
def replace_zero(item):
item_list = list(item)
index_select = item[2]
if index_select == 0:
index_select = 1
item_list.pop(0)
item_list.append(index_select)
return item_list
else:
return item_list
@app.route("/box_plot_init")
def box_plot_init():
# Initiate "histogram" graph from current date to 30 days prior
today_datetime = dt.datetime.utcnow()
today_date = today_datetime.date()
thirty_days_ago = dt.date.today() - dt.timedelta(days = 30)
session = Session(engine)
# Create query
box_query = session.query(Tweets.user_name, Tweets.user_id_str, Tweets.retweet_count).\
filter(Tweets.created_at_date >= thirty_days_ago).\
filter(Tweets.created_at_date <= today_date)
# sort list according to candidate
box_sorted = sorted(box_query, key = user_sort)
keys = ("user_name", "min", "q1", "median", "q3", "max")
box_list = []
# group by candidate
# Data will be log transformed for a more visually appealing graph
# we replace all zeroes with one
# values are transformed to float/int bc json cannot parse data otherwise
for k, g in groupby(box_sorted, key = user_sort):
current_list = list(g)
new_list = list(map(lambda x: replace_zero(x), current_list))
retweet_list = list(map(lambda x: x[2], new_list))
log_list = list(np.log(retweet_list))
retweet_median = float(np.median(log_list))
retweet_q1 = float(np.quantile(log_list, .25))
retweet_q3 = float(np.quantile(log_list, .75))
retweet_min = int(np.min(log_list))
retweet_max = int(np.max(log_list))
user_id = k
[user_dict] = list(filter(lambda x: x["twitter_user_id"] == user_id, candidates_list))
user_name = user_dict["name"]
user_tuple = (user_name, retweet_min, retweet_q1, retweet_median, retweet_q3, retweet_max)
response_dict = dict(zip(keys, user_tuple))
box_list.append(response_dict)
box_json = json.dumps(box_list)
session.close()
return box_json
# Route for displaying top tweets
@app.route("/tweets_init")
def tweets_init():
# Initiate "tweets" list from current date to 30 days prior
today_datetime = dt.datetime.utcnow()
today_date = today_datetime.date()
thirty_days_ago = dt.date.today() - dt.timedelta(days = 30)
session = Session(engine)
# Select first candidate from "candidates_list" for displaying initial tweets
tweet_list = []
init_user_id = candidates_list[0]["twitter_user_id"]
# Create query, initial metric is retweets
tweet_query = session.query(Tweets.user_name, Tweets.tweet_id_str).\
filter(Tweets.created_at_date >= thirty_days_ago).\
filter(Tweets.created_at_date <= today_date).\
filter(Tweets.user_id_str == init_user_id).\
order_by(Tweets.retweet_count.desc()).limit(10)
keys = ("user_name", "tweet_id_str")
for tweet in tweet_query:
tweet_dict = dict(zip(keys, tweet))
tweet_list.append(tweet_dict)
tweet_json = json.dumps(tweet_list)
session.close()
return tweet_json
# Route for sending back filtered data for tweet list
@app.route("/tweets_filter", methods = ["GET", "POST"])
def tweets_filter():
if request.method == "POST":
data = request.data
filter_data = [json.loads(data.decode('utf-8'))]
#retrieve data variables
candidate_id = filter_data[0]["chosenTweetsCandidate"]
date_from = filter_data[0]["dateFrom"]
date_to = filter_data[0]["dateTo"]
metric_var = filter_data[0]["tweetMetricLabel"]
# convert string dates into DATETIME objects
date_from_datetime = dt.datetime.strptime(date_from, "%b %d, %Y")
date_to_datetime = dt.datetime.strptime(date_to, "%b %d, %Y")
#convert DATETIME objects into DATE objects
date_from_date = date_from_datetime.date()
date_to_date = date_to_datetime.date()
session = Session(engine)
tweet_list = []
if metric_var == "Retweets":
# Create query
tweet_query = session.query(Tweets.user_name, Tweets.tweet_id_str).\
filter(Tweets.created_at_date >= date_from_date).\
filter(Tweets.created_at_date <= date_to_date).\
filter(Tweets.user_id_str == candidate_id).\
order_by(Tweets.retweet_count.desc()).limit(10)
keys = ("user_name", "tweet_id_str")
for tweet in tweet_query:
tweet_dict = dict(zip(keys, tweet))
tweet_list.append(tweet_dict)
else:
# Create query
tweet_query = session.query(Tweets.user_name, Tweets.tweet_id_str).\
filter(Tweets.created_at_date >= date_from_date).\
filter(Tweets.created_at_date <= date_to_date).\
filter(Tweets.user_id_str == candidate_id).\
order_by(Tweets.favorite_count.desc()).limit(10)
keys = ("user_name", "tweet_id_str")
for tweet in tweet_query:
tweet_dict = dict(zip(keys, tweet))
tweet_list.append(tweet_dict)
tweet_json = json.dumps(tweet_list)
session.close()
return tweet_json
# Route for sending back filtered data for box plot
@app.route("/box_plot_filter", methods = ["GET", "POST"])
def box_plot_filter():
if request.method == "POST":
data = request.data
filter_data = [json.loads(data.decode('utf-8'))]
#retrieve data variables
candidate_ids = filter_data[0]["candidatesList"]
date_from = filter_data[0]["dateFrom"]
date_to = filter_data[0]["dateTo"]
metric_var = filter_data[0]["distMetricVar"]
# convert string dates into DATETIME objects
date_from_datetime = dt.datetime.strptime(date_from, "%b %d, %Y")
date_to_datetime = dt.datetime.strptime(date_to, "%b %d, %Y")
#convert DATETIME objects into DATE objects
date_from_date = date_from_datetime.date()
date_to_date = date_to_datetime.date()
session = Session(engine)
keys = ("user_name", "min", "q1", "median", "q3", "max")
box_list = []
# group by candidate
# Data will be log transformed for a more visually appealing graph
# we replace all zeroes with one
# values are transformed to float/int bc json cannot parse data otherwise
if metric_var == "retweet_count":
# Create query
box_query = session.query(Tweets.user_name, Tweets.user_id_str, Tweets.retweet_count).\
filter(Tweets.user_id_str.in_(candidate_ids)).\
filter(Tweets.created_at_date >= date_from_date).\
filter(Tweets.created_at_date <= date_to_date)
# sort list according to candidate
box_sorted = sorted(box_query, key = user_sort)
for k, g in groupby(box_sorted, key = user_sort):
current_list = list(g)
new_list = list(map(lambda x: replace_zero(x), current_list))
retweet_list = list(map(lambda x: x[2], new_list))
log_list = list(np.log(retweet_list))
retweet_median = float(np.median(log_list))
retweet_q1 = float(np.quantile(log_list, .25))
retweet_q3 = float(np.quantile(log_list, .75))
retweet_min = int(np.min(log_list))
retweet_max = int(np.max(log_list))
user_id = k
[user_dict] = list(filter(lambda x: x["twitter_user_id"] == user_id, candidates_list))
user_name = user_dict["name"]
user_tuple = (user_name, retweet_min, retweet_q1, retweet_median, retweet_q3, retweet_max)
response_dict = dict(zip(keys, user_tuple))
box_list.append(response_dict)
elif metric_var == "favorite_count":
# Create query
box_query = session.query(Tweets.user_name, Tweets.user_id_str, Tweets.favorite_count).\
filter(Tweets.user_id_str.in_(candidate_ids)).\
filter(Tweets.created_at_date >= date_from_date).\
filter(Tweets.created_at_date <= date_to_date)
# sort list according to candidate
box_sorted = sorted(box_query, key = user_sort)
for k, g in groupby(box_sorted, key = user_sort):
current_list = list(g)
new_list = list(map(lambda x: replace_zero(x), current_list))
favorite_list = list(map(lambda x: x[2], new_list))
log_list = list(np.log(favorite_list))
favorite_median = float(np.median(log_list))
favorite_q1 = float(np.quantile(log_list, .25))
favorite_q3 = float(np.quantile(log_list, .75))
favorite_min = int(np.min(log_list))
favorite_max = int(np.max(log_list))
user_id = k
[user_dict] = list(filter(lambda x: x["twitter_user_id"] == user_id, candidates_list))
user_name = user_dict["name"]
user_tuple = (user_name, favorite_min, favorite_q1, favorite_median, favorite_q3, favorite_max)
response_dict = dict(zip(keys, user_tuple))
box_list.append(response_dict)
box_json = json.dumps(box_list)
session.close()
return box_json
# Function for sorting and to call for "key" argument in groupby
def day_sort(query):
return(query)
@app.route("/histogram_filter", methods = ["GET", "POST"])
def histogram_filter():
if request.method == "POST":
#read data and convert to list of dictionary
data = request.data
filter_data = [json.loads(data.decode('utf-8'))]
#retrieve data variables
candidate_ids = filter_data[0]["candidatesList"]
date_from = filter_data[0]["dateFrom"]
date_to = filter_data[0]["dateTo"]
metric_var = filter_data[0]["distMetricVar"]
# convert string dates into DATETIME objects
date_from_datetime = dt.datetime.strptime(date_from, "%b %d, %Y")
date_to_datetime = dt.datetime.strptime(date_to, "%b %d, %Y")
#convert DATETIME objects into DATE objects
date_from_date = date_from_datetime.date()
date_to_date = date_to_datetime.date()
session = Session(engine)
histogram_list = []
if metric_var == "retweet_count":
histogram_query = session.query(Tweets.retweet_count).\
filter(Tweets.user_id_str.in_(candidate_ids)).\
filter(Tweets.created_at_date >= date_from_date).\
filter(Tweets.created_at_date <= date_to_date).\
order_by(Tweets.retweet_count)
[histogram_query] = list(zip(*histogram_query))
query_iter = iter(histogram_query)
#Find min and max values
range_query = session.query(func.min(Tweets.retweet_count),
func.max(Tweets.retweet_count)).\
filter(Tweets.user_id_str.in_(candidate_ids)).\
filter(Tweets.created_at_date >= date_from_date).\
filter(Tweets.created_at_date <= date_to_date).first()
min_value = range_query[0]
max_value = range_query[1]
# Find range
histogram_range = max_value - min_value
#Define # of histogram bars (100)
histogram_bars = 100
# Find range for each bar
bar_range = histogram_range / histogram_bars
# Create and append dicts which contain the value ranges for the bars with "0" value count
for x in range(0, histogram_bars):
begin_value = min_value + x * bar_range
end_value = begin_value + bar_range
begin_str = "{:,}".format(round(begin_value, 2))
end_str = "{:,}".format(round(end_value, 2))
range_str = begin_str + "-" + end_str
hist_dict = {
'begin': begin_value,
'end': end_value,
'tick': range_str,
'count': 0
}
histogram_list.append(hist_dict)
# Iterate through query, find a dict that fits, and increase count by one
# "Value Error" raised for last item in query because the filter function does not yield a dict for this value. In this case it is simple to just increase the value of the last dict by one
for y in query_iter:
try:
[current_bar] = list(filter(lambda x: y >= x["begin"] and y < x["end"], histogram_list))
current_bar["count"] += 1
except ValueError:
histogram_list[-1]["count"] += 1
else:
histogram_query = session.query(Tweets.favorite_count).\
filter(Tweets.user_id_str.in_(candidate_ids)).\
filter(Tweets.created_at_date >= date_from_date).\
filter(Tweets.created_at_date <= date_to_date).\
order_by(Tweets.favorite_count)
[histogram_query] = list(zip(*histogram_query))
query_iter = iter(histogram_query)
#Find min and max values
range_query = session.query(func.min(Tweets.favorite_count),
func.max(Tweets.favorite_count)).\
filter(Tweets.user_id_str.in_(candidate_ids)).\
filter(Tweets.created_at_date >= date_from_date).\
filter(Tweets.created_at_date <= date_to_date).first()
min_value = range_query[0]
max_value = range_query[1]
# Find range
histogram_range = max_value - min_value
#Define # of histogram bars (100)
histogram_bars = 100
# Find range for each bar
bar_range = histogram_range / histogram_bars
# Create and append dicts which contain the value ranges for the bars with "0" value count
for x in range(0, histogram_bars):
begin_value = min_value + x * bar_range
end_value = begin_value + bar_range
begin_str = "{:,}".format(round(begin_value, 2))
end_str = "{:,}".format(round(end_value, 2))
range_str = begin_str + "-" + end_str
hist_dict = {
'begin': begin_value,
'end': end_value,
'tick': range_str,
'count': 0
}
histogram_list.append(hist_dict)
# Iterate through query, find a dict that fits, and increase count by one
# "Value Error" raised for last item in query because the filter function does not yield a dict for this value. In this case it is simple to just increase the value of the last dict by one
for y in query_iter:
try:
[current_bar] = list(filter(lambda x: y >= x["begin"] and y < x["end"], histogram_list))
current_bar["count"] += 1
except ValueError:
histogram_list[-1]["count"] += 1
histogram_json = json.dumps(histogram_list)
session.close()
return histogram_json
# Ref ("/time_filter") function used for sorting query based on hour or day, necessary for groupby
def date_time_sort(datetime_query, basis):
index_select = datetime_query[3]
if basis == "Hour":
index_select = dt.datetime.strftime(index_select, "%H")
return index_select
elif basis == "Day":
index_select = dt.datetime.strftime(index_select, "%w")
return index_select
# Route for rendering new data for "Time" table based on filter selections
@app.route("/time_filter", methods = ["GET", "POST"])
def time_filter():
if request.method == "POST":
#read data and convert to list of dictionary
data = request.data
filter_data = [json.loads(data.decode('utf-8'))]
#retrieve data variables
candidate_id = filter_data[0]["chosenCandidate"]
date_from = filter_data[0]["dateFrom"]
date_to = filter_data[0]["dateTo"]
time_basis = filter_data[0]["timeBasis"]
# Find candidate with corresponding candidate id and retrieve their name
candidate_retrieve = list(filter(lambda x: (x["twitter_user_id"] == candidate_id), candidates_list))
candidate_name = candidate_retrieve[0]["name"]
# convert string dates into DATETIME objects
date_from_datetime = dt.datetime.strptime(date_from, "%b %d, %Y")
date_to_datetime = dt.datetime.strptime(date_to, "%b %d, %Y")
#convert DATETIME objects into DATE objects
date_from_date = date_from_datetime.date()
date_to_date = date_to_datetime.date()
session = Session(engine)
time_list = []
filter_query = session.query(Tweets.user_name, Tweets.retweet_count,
Tweets.favorite_count, Tweets.created_at_datetime).\
filter(Tweets.user_id_str == candidate_id).\
filter(Tweets.created_at_date >= date_from_date).\
filter(Tweets.created_at_date <= date_to_date)
time_sorted_list = sorted(filter_query, key = lambda query: date_time_sort(query, time_basis))
keys = ("user_name", "retweet_average", "favorite_average", time_basis, "count")
for k, g in groupby(time_sorted_list, key = lambda row: date_time_sort(row, time_basis)):
current_list = list(g)
group_count = len(current_list)
group_retweet_list = list(map(lambda x: x[1], current_list))
group_favorite_list = list(map(lambda x: x[2], current_list))
group_retweet_average = np.mean(group_retweet_list)
group_favorite_average = np.mean(group_favorite_list)
if time_basis == "Hour":
group_tuple = (candidate_name, group_retweet_average, group_favorite_average, k, group_count)
group_dict = dict(zip(keys, group_tuple))
time_list.append(group_dict)
if time_basis == "Day":
k_int = int(k) - 1
calendar_days = list(calendar.day_abbr)
current_day = calendar_days[k_int]
group_tuple = (candidate_name, group_retweet_average, group_favorite_average, current_day, group_count)
group_dict = dict(zip(keys, group_tuple))
time_list.append(group_dict)
time_json = json.dumps(time_list)
return time_json
# Route for updating "At a Glance" Graph with filtered selections
@app.route("/aag_filter", methods = ["GET", "POST"])
def aag_filter():
if request.method == "POST":
#read data and convert to list of dictionary
data = request.data
filter_data = [json.loads(data.decode('utf-8'))]
# retrieve data variables
candidate_ids = filter_data[0]["candidatesList"]
date_from = filter_data[0]["dateFrom"]
date_to = filter_data[0]["dateTo"]
# convert string dates into DATETIME objects
date_from_object = dt.datetime.strptime(date_from, "%b %d, %Y")
date_to_object = dt.datetime.strptime(date_to, "%b %d, %Y") + dt.timedelta(days = 1)
session = Session(engine)
filter_query = session.query(Tweets.user_name,
func.avg(Tweets.retweet_count),
func.avg(Tweets.favorite_count)).\
filter(Tweets.user_id_str.in_(candidate_ids)).\