This repository has been archived by the owner on Sep 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
app2.py
2281 lines (1893 loc) · 104 KB
/
app2.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
from collections import Counter, defaultdict
from datetime import datetime as dt
from datetime import date, timedelta
import datetime
import os
import re
from altair import datum
from bokeh.models import ColumnDataSource, CustomJS
from bokeh.models import DataTable, TableColumn, HTMLTemplateFormatter, DateFormatter
from googleapiclient.discovery import build
from google.oauth2 import service_account
from gspread_pandas import Spread, Client
from streamlit_bokeh_events import streamlit_bokeh_events
from tzlocal import get_localzone
from wordcloud import WordCloud
from pytz import country_timezones
import altair as alt
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pytz
import pycountry
import streamlit as st
import gdown
import gspread
st.set_page_config(page_title='Twitter Watcher', layout='wide', page_icon='📮')
def get_weekstart(selected_date=dt.today()):
"""
Returns Monday of the selected_date week
Parameters
----------
selected_date : datetime.date, optional
Any date/ day of the week. The default is dt.today().
Returns
-------
datetime.date
Date of the Monday of week of selected_date.
"""
return selected_date - timedelta(days=selected_date.weekday())
def load_data_gdrive(data_file_id):
"""
Load data from Google Drive
Parameters
----------
data_file_id : str
Unique file ID corresponding to stored Tweet data in Google Drive.
Returns
-------
pandas.core.frame.DataFrame
Cleaned pandas dataframe returned from clean_df() function.
"""
data_url = 'https://drive.google.com/uc?id=' + data_file_id
data_output = 'data.txt'
# Download data from google drive
gdown.download(data_url, data_output, quiet=True)
df = pd.read_csv(data_output, sep='\t')
return clean_df(df)
def clean_df(df):
"""
Clean and pre-process dataframe by:
- Transforming columns to appropriate format
- Derive additional columns such as day_of_week from date
Parameters
----------
df : pandas.core.frame.DataFrame
Raw dataframe.
Returns
-------
df : pandas.core.frame.DataFrame
Preprocessed dataframe.
"""
# Transform date column to pandas._libs.tslibs.timestamps.Timestamp format
df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d')
# Transform time column to datetime.time format
df['time'] = pd.to_datetime(df['time'], format='%H:%M:%S').dt.time
# Double check for NaT - if NaT, convert to 00:00:00
for x in df['time'][pd.Series(df['time']).isna()].index:
df.at[x, 'time'] = datetime.time(0,0,0)
# Combine columns to get datetime
df['datetime'] = df.apply(lambda row: datetime.datetime.combine(row['date'], row['time']), axis=1)
# Get year
df['year'] = df['date'].apply(lambda x: x.year)
# Get month
df['month'] = df['date'].apply(lambda x: x.month_name())
# Get week number
df['week'] = df['date'].dt.isocalendar().week
# Get day of the week
df['day_of_week'] = df['date'].apply(lambda x: x.day_name())
# Get hour in 24h format
df['hour'] = df['time'].apply(lambda x: x.hour)
# Transform polarity column
df['polarity'] = df['polarity'].apply(lambda x: 'positive' if x == 1 else 'negative')
return df
def get_dhl_acc(df):
"""
Extract list of Twitter account associated with DHL
Parameters
----------
df : pandas.core.frame.DataFrame
Tweets data.
Returns
-------
dhl_acc : list
List of Twitter account usernames associated with DHL.
"""
dhl_acc = list(set(df['username'].str.extract('(.*DHL.*)', re.IGNORECASE)[0]))
dhl_acc.remove(np.nan)
return dhl_acc
def get_dhl_tweet(df, dhl_acc):
"""
Get Tweets by DHL associated accounts
Parameters
----------
df : pandas.core.frame.DataFrame
Tweets data.
dhl_acc : list
List of Twitter account usernames associated with DHL.
Returns
-------
pandas.core.frame.DataFrame
Filtered dataframe containing only Tweets by DHL associated accounts.
"""
return df[df['username'].isin(dhl_acc)].reset_index(drop=True)
def get_cust_tweet(df, dhl_acc):
"""
Get Tweets by Twitter users
Parameters
----------
df : pandas.core.frame.DataFrame
Tweets data.
dhl_acc : list
List of Twitter account usernames associated with DHL.
Returns
-------
pandas.core.frame.DataFrame
Filtered dataframe by removing Tweets by DHL associated accounts.
"""
return df[~df['username'].isin(dhl_acc)].reset_index(drop=True)
@st.cache(persist=True)
def hashtags_polarity(df, selected_week):
"""
Get hashtags associated with Negative polarity and Positive polarity
Parameters
----------
df : pandas.core.frame.DataFrame
Dataframe containing only customer Tweets.
selected_week : datetime.date
Date provided by user input.
Returns
-------
positive_words : str
Words from Positive Tweets hashtags.
negative_words : str
Words from Negative Tweets hashtags.
"""
# Sort df by datetime in descending order
df.sort_values(by=['datetime'], ascending=False).reset_index(drop=True)
# Unpack year, weeknum and day from selected date
cw_year, cw_weeknum, cw_day = selected_week.isocalendar()
# Slice df based on selected date and polarity, then save as new df
positive_df = df.loc[(df['week'] == cw_weeknum) & (df['year'] == cw_year) & (df['polarity'] == 'positive')].copy()
negative_df = df.loc[(df['week'] == cw_weeknum) & (df['year'] == cw_year) & (df['polarity'] == 'negative')].copy()
# If either one is empty, get the most recent data
if len(positive_df) == 0:
# Get the second top week number
top2_weeknum = df['week'].unique()[1]
max_year = max(df['year'])
# slice to get the most recent week -1, year
positive_df = df.loc[
(df['week'] == top2_weeknum) & (df['year'] == max_year) & (df['polarity'] == 'positive')].copy()
if len(negative_df) == 0:
# Get the second top week number
top2_weeknum = df['week'].unique()[1]
max_year = max(df['year'])
# slice to get the most recent week -1, year
negative_df = df.loc[
(df['week'] == top2_weeknum) & (df['year'] == max_year) & (df['polarity'] == 'negative')].copy()
# Combine hashtags into list of words
positive_list = positive_df['hashtags'].apply(
lambda x: "".join(x).replace("'", "").replace("[", "").replace("]", "").replace(",", "").split())
negative_list = negative_df['hashtags'].apply(
lambda x: "".join(x).replace("'", "").replace("[", "").replace("]", "").replace(",", "").split())
# Join words
positive_words = (' ').join([item for sublist in positive_list for item in sublist])
negative_words = (' ').join([item for sublist in negative_list for item in sublist])
# Placeholder to ensure no 0 len string
positive_words += ' DHL'
negative_words += ' DHL'
return positive_words, negative_words
@st.cache(persist=True)
def get_kpi(weekly_data, selected_week):
"""
Returns KPI value and delta for all 6 KPIs. If data is not available for
selected_week, returns KPIs for the latest week available
Parameters
----------
weekly_data : pandas.core.frame.DataFrame
Pivoted dataframe with sum aggregation for week, year index.
selected_week : datetime.date
Selected date from user input.
Returns
-------
kpi_dict : dict
Dictionary containing kpi_name: (current week's value, delta) for all 6 KPIs.
warning : str
String storing warning to display, if any.
"""
# Reset index to perform transformation
weekly_data2 = weekly_data.reset_index()
# Change from str type -> int to enable slicing later
weekly_data2['year'] = weekly_data2['year'].apply(lambda x: int(x[:-2]))
weekly_data2['week'] = weekly_data2['week'].apply(lambda x: int(x))
# Set back index to week, year
weekly_data2 = weekly_data2.set_index(['week', 'year'])
# Initialize empty dict to store KPI with format -> kpi_name: (current week value, delta)
kpi_dict = {}
try:
current_week = selected_week
previous_week = selected_week - timedelta(days=7)
# Unpack year, weeknum and day from selected week and previous week
cw_year, cw_weeknum, cw_day = current_week.isocalendar()
pw_year, pw_weeknum, pw_day = previous_week.isocalendar()
# For each KPI, get its current value and previous value, then save in kpi_dict
for key, column_name in [('Positive Mentions', 'polarity_positive_mentions'),
('Negative Mentions', 'polarity_negative_mentions'),
('Retweets', 'retweets'),
('Replies', 'replies'),
('Likes', 'likes'),
('DHL Tweets', 'count_dhl_tweets')]:
current_value = int(weekly_data2.at[(cw_weeknum, cw_year), column_name])
prev_value = int(weekly_data2.at[(pw_weeknum, pw_year), column_name])
kpi_dict[key] = (current_value, current_value - prev_value)
warning = ""
# If data does not exist, get the most recent KPI
except KeyError as e:
warning = f'Data is not available for week, year {e}. Showing the most recent KPI'
weekly_data2 = weekly_data2.sort_index() # sort index ascendingly
(cw_weeknum, cw_year), (pw_weeknum, pw_year) = weekly_data2.index.take([-1, -2]) # get the 2 latest weeknum, year available
for key, column_name in [('Positive Mentions', 'polarity_positive_mentions'),
('Negative Mentions', 'polarity_negative_mentions'),
('Retweets', 'retweets'),
('Replies', 'replies'),
('Likes', 'likes'),
('DHL Tweets', 'count_dhl_tweets')]:
current_value = int(weekly_data2.at[(cw_weeknum, cw_year), column_name])
prev_value = int(weekly_data2.at[(pw_weeknum, pw_year), column_name])
kpi_dict[key] = (current_value, current_value - prev_value)
return kpi_dict, warning
def get_datatable(df, selected_week):
"""
Slice to obtain only data for selected_week
Parameters
----------
df : pandas.core.frame.DataFrame
Dataframe containing data to be sliced.
selected_week : datetime.date
Date from user input.
Returns
-------
pandas.core.frame.DataFrame
Sliced dataframe sorted in descenging order by datetime column.
"""
week_start = selected_week
week_end = selected_week + timedelta(days=7)
# Sort df by datetime in descending order
df = df.sort_values(by=['datetime'], ascending=False).reset_index(drop=True)
# A workaround to ensure that time is always rendered in correct format
df['time'] = df['time'].apply(lambda x: str(x))
# Slice df to get only data for selected week
filtered_df = df[
(df['date'] >= np.datetime64(week_start)) & (df['date'] <= np.datetime64(week_end))].copy().reset_index()
# Exception catching: If sliced df is empty, get the latest week available
if len(filtered_df) == 0:
week_end = max(df['date'])
week_start = week_end - timedelta(days=7)
filtered_df = df[
(df['date'] >= np.datetime64(week_start)) & (df['date'] <= np.datetime64(week_end))].copy().reset_index()
return filtered_df[['datetime', 'date', 'time', 'polarity', 'tweet', 'link']].sort_values(by=['datetime'], ascending=False).reset_index(drop=True)
def update_datatable(cust_tweets, selected_week, choice):
"""
Slice to obtain only data for selected_week and update value in session_state.
If `choice` of page navigation is Data, update st.session_state['datatable'] with 7 days latest data;
Else, update session_state object with data on `selected_week` only.
Parameters
----------
cust_tweets : pandas.core.frame.DataFrame
Dataframe containing data to be sliced.
selected_week : datetime.date
Date from user input.
choice : str
Name of page user wish to navigate to.
Returns
-------
None.
"""
if choice == 'Data':
weekstart = selected_week - timedelta(days=7)
st.session_state['datatable'] = get_datatable(cust_tweets, weekstart)
else:
st.session_state['datatable'] = get_datatable(cust_tweets, selected_week)
def load_google_worksheet(worksheet):
"""
Get all rows from connected google worksheet
Parameters
----------
worksheet : gspread.models.Worksheet
Loaded worksheet which contains user input.
Returns
-------
pandas.core.frame.DataFrame
Dataframe containing all rows from google worksheet.
"""
return pd.DataFrame(worksheet.get_all_records())
def update_google_worksheet(worksheet, df):
"""
Update new user input from df to connected worksheet
Parameters
----------
worksheet : gspread.models.Worksheet
Connected worksheet which contains user input.
df : pandas.core.frame.DataFrame
Dataframe to write to worksheet.
Returns
-------
None.
"""
# Get column names
column_name = df.columns.values.tolist()
# Get value to append to worksheet
row_value = df.values.tolist()
# Update worksheet
worksheet.update([column_name] + row_value)
def build_connection():
"""
Initialize credentials object and drive_service object to interact with
Google Drive API.
ref: https://google-auth.readthedocs.io/en/master/_modules/google/oauth2/service_account.html#Credentials.from_service_account_info
Info argument in credentials object is a .toml file stored in streamlit.io.
Note that credentials object is initialized in a similar fashion to retrain.load_google_worksheet_from_info().
However, one stark differences is that the info argument here is structured in .toml file (saved in streamlit.io);
while the latter's info argument is a constructed dict object with some of its values saved in Github secrets.
This is because github secrets does not allow storage of any structured file format, therefore the workaround.
Since app.py will be run entirely from streamlit.io, there is no need to store the .toml file in Github secrets.
Returns
-------
credentials : google.oauth2.service_account.Credentials
Credentials object for Google service account built using credentials
obtained from GCP > IAM & Admin > Service Accounts > KEYS.
drive_service : googleapiclient.discovery.Resource
Initialized Resource to interact with Google Drive API.
Ref: https://googleapis.github.io/google-api-python-client/docs/epy/googleapiclient.discovery-module.html
"""
# Create a connection object
credentials = service_account.Credentials.from_service_account_info(
st.secrets["gcp_service_account"],
scopes=["https://www.googleapis.com/auth/spreadsheets", "https://www.googleapis.com/auth/drive"])
drive_service = build('drive', 'v3', credentials=credentials)
return credentials, drive_service
def get_modified_time(file_id, drive_service, server_tz, local_tz):
"""
Get latest modified time from file stored in Google Drive folder
Parameters
----------
file_id : str
Unique ID of file stored in Google Drive.
drive_service : googleapiclient.discovery.Resource
Initialized Resource to interact with Google Drive API.
server_tz : pytz.tzfile.Etc/UTC
timezone information for server location.
local_tz : str
Region for user timezone eg "Asia/Kuala_Lumpur".
Returns
-------
str
Description of last modified time.
"""
metadata = drive_service.files().get(fileId=file_id, fields='modifiedTime').execute()
mtime = pd.to_datetime(metadata['modifiedTime'], format="%Y-%m-%d %H:%M").tz_convert(server_tz).tz_convert(local_tz)
return f'Last Updated at {mtime.year}-{mtime.month}-{mtime.day} {mtime.hour}:{mtime.minute}'
def connect_googlesheet(googlesheet_name, credentials):
"""
Connect to existing Google Sheet
Parameters
----------
googlesheet_name : str
Name of Private Google Sheet accessible by created Google service account.
credentials : google.oauth2.service_account.Credentials
Credentials object for Google service account built using credentials
obtained from GCP > IAM & Admin > Service Accounts > KEYS.
Returns
-------
worksheet : gspread.models.Worksheet
Connected Google worksheet.
spread : gspread_pandas.spread.Spread
Connected Google Spreadsheet.
"""
# Get google sheet url from secrets
sheet_url = st.secrets["private_gsheets_url"]
# Initialize a Client instance and authorize to access spreadsheets via Google Sheets API (via OAuth2 credentials)
# ref: https://docs.gspread.org/en/latest/api.html#gspread.authorize
gc = gspread.authorize(credentials)
# Open the google sheet
sh = gc.open_by_url(sheet_url)
# Open the worksheet
worksheet = sh.worksheet(title=googlesheet_name)
# Create an instance of Client class to comunicate with Google API
# ref: https://gspread-pandas.readthedocs.io/en/latest/gspread_pandas.html#gspread_pandas.client.Client
client = Client(creds=credentials)
# Create an instance of Spread class to interact with Google spreadsheet using Pandas
# ref: https://gspread-pandas.readthedocs.io/en/latest/gspread_pandas.html#gspread_pandas.spread.Spread
spread = Spread(spread=sheet_url, client=client)
return worksheet, spread
def update_googlesheet_gspread_pandas(spread, googlesheet_name, df):
"""
Updates data in connected Google Spreadsheet
Parameters
----------
spread : gspread_pandas.spread.Spread
Connected Google Spreadsheet.
googlesheet_name : str
Name of Google Worksheet.
df : pandas.core.frame.DataFrame
Dataframe to update to Google Worksheet.
Returns
-------
None.
"""
col = ['datetime', 'tweet', 'polarity', 'user_input_timestamp']
spread.df_to_sheet(df[col], sheet=googlesheet_name, index=False)
def polarity_formatter(my_col):
"""
Format polarity column to highlight row based on polarity.
Rows for negative polarity is highlighted in red, and rows for positive
polarity is highlighted in green
Parameters
----------
my_col : pandas.core.series.Series
Column to be formatted.
Returns
-------
bokeh.models.widgets.tables.HTMLTemplateFormatter
HTML Template Formatter with user-defined template.
"""
template = """
<div style="background:<%=
(function colorfromint(){
if(result_col == 'positive')
{return('#84ddb4')}
else if (result_col == 'negative')
{return('#e74d3c')}
}()) %>;
color: white">
<p style="text-align:center;">
<%= value %></p>
</div>
""".replace('result_col', my_col)
return HTMLTemplateFormatter(template=template)
@st.cache
def convert_df(df):
"""
Convert pandas dataframe into csv file for user to download
Parameters
----------
df : pandas.core.frame.DataFrame
Dataframe to converted to csv to.
Returns
-------
NoneType
Function to convert pandas dataframe to csv file.
"""
return df.to_csv().encode('utf-8')
def get_agg_data(cust_tweets, dhl_tweets):
"""
Aggregate Tweets data into multiindexed dataframe (datatime, week, year).
Aggregation function used is summation.
Parameters
----------
cust_tweets : pandas.core.frame.DataFrame
Dataframe containing Tweets from customers.
dhl_tweets : pandas.core.frame.DataFrame
Dataframe containing Tweets from DHL associated accounts.
Returns
-------
pandas.core.frame.DataFrame
Pivoted multiindexed pandas dataframe aggregated using summation.
"""
# Get polarity data from cust_tweets
# Get one-hot encoded columns for 'polarity'
sum_polarity = pd.concat([pd.get_dummies(cust_tweets[['datetime', 'year', 'polarity']]), cust_tweets[['week']]], axis=1).add_suffix('_mentions')
# Add count for each tweets
sum_polarity['count_cust_tweets'] = 1
# Ensure that columns exist
if 'polarity_positive_mentions' not in sum_polarity.columns:
sum_polarity['polarity_positive_mentions'] = sum_polarity['polarity_negative_mentions'].apply(lambda x: 0 if x==1 else np.nan)
if 'polarity_negative_mentions' not in sum_polarity.columns:
sum_polarity['polarity_negative_mentions'] = sum_polarity['polarity_positive_mentions'].apply(lambda x: 0 if x==1 else np.nan)
# Get engagement data from dhl_tweets
# Slice dataframe to get only engagement details
sum_engagement = dhl_tweets[['datetime', 'week', 'year', 'replies', 'retweets', 'likes']].copy()
# Add count for each tweets
sum_engagement['count_dhl_tweets'] = 1
# Append both dfs
sum_df = sum_engagement.append(sum_polarity, sort=False)
# if value is na, copy 'week_mentions'
sum_df['week'] = sum_df.apply(lambda row: np.where(pd.isna(row['week']), row['week_mentions'], row['week']), axis=1)
# if value is na, copy 'year_mentions'
sum_df['year'] = sum_df.apply(lambda row: np.where(pd.isna(row['year']), row['year_mentions'], row['year']), axis=1)
sum_df['datetime'] = sum_df.apply(lambda row: np.where(pd.isna(row['datetime']), row['datetime_mentions'], row['datetime']), axis=1)
# reset index and drop original
sum_df = sum_df.reset_index(drop=True)
# change unhashable np.array of dtype=object to dtype=np.int
sum_df['datetime'] = sum_df['datetime'].apply(lambda x: x.astype(str))
sum_df['week'] = sum_df['week'].apply(lambda x: x.astype(str))
sum_df['year'] = sum_df['year'].apply(lambda x: x.astype(str))
return pd.pivot_table(sum_df, values=['replies', 'retweets', 'likes', 'count_dhl_tweets', 'polarity_negative_mentions', 'polarity_positive_mentions', 'count_cust_tweets'], index=['datetime', 'week', 'year'], aggfunc=np.sum, fill_value=0)
def plot_custom_graph(df, x, y, chart_type, agg_type):
"""
Plot altair chart from user input
Parameters
----------
df : pandas.core.frame.DataFrame
Pivoted (datetime, week, year) multiindexed dataframe using sum aggregation function.
x : str
X axis name from user input.
y : list
List of column names from user input.
chart_type : str
Name of chart type from user input.
agg_type : str
String depicting data aggregation type from user input.
Returns
-------
altair.vegalite.v4.api.Chart
Rendered chart.
"""
width = 800
x_dict = {
'Hours of the day': 'hours(datetime):T',
'Day of the week': 'day(datetime):O',
'Day of the month': 'date(datetime):O',
'Week': 'week:Q',
'Date': 'monthdate(datetime):O',
'Month': 'month(datetime):O',
'Quarter': 'quarter(datetime):O',
'Year': 'year(datetime):O'
}
agg_type_dict = {
'Total number of Tweets': 'sum(value):Q',
'Average number of Tweets': 'average(value):Q',
'Min number of Tweets': 'min(value):Q',
'Max number of Tweets': 'max(value):Q'
}
if chart_type == 'Scatter':
return alt.Chart(
data = df,
width = width
).transform_fold(
y
).mark_circle().encode(
alt.X(x_dict[x], title=x),
alt.Y(agg_type_dict[agg_type], title='value'),
color='key:N',
tooltip = [alt.Tooltip(x_dict[x]), alt.Tooltip('key:N'), alt.Tooltip(agg_type_dict[agg_type])]
).configure_mark(
strokeWidth=10
).interactive()
elif chart_type == 'Line':
return alt.Chart(
data = df,
width = width
).transform_fold(
y
).mark_line().encode(
alt.X(x_dict[x], title=x),
alt.Y(agg_type_dict[agg_type]),
color='key:N',
tooltip = [alt.Tooltip(x_dict[x]), alt.Tooltip('key:N'), alt.Tooltip(agg_type_dict[agg_type])]
).configure_mark(
strokeWidth=3
).interactive()
elif chart_type == 'Area':
return alt.Chart(
data = df,
width = width
).transform_fold(
y
).mark_area().encode(
alt.X(x_dict[x], title=x),
alt.Y(agg_type_dict[agg_type]),
color='key:N',
tooltip = [alt.Tooltip(x_dict[x]), alt.Tooltip('key:N'), alt.Tooltip(agg_type_dict[agg_type])]
).configure_mark(
strokeWidth=10
).interactive()
elif chart_type == 'Bar':
return alt.Chart(
data = df,
width = width
).transform_fold(
y
).mark_bar().encode(
alt.X(x_dict[x], title=x),
alt.Y(agg_type_dict[agg_type]),
color='key:N',
tooltip = [alt.Tooltip(x_dict[x]), alt.Tooltip('key:N'), alt.Tooltip(agg_type_dict[agg_type])]
).configure_mark(
strokeWidth=10
).interactive()
elif chart_type == 'Heatmap':
return alt.Chart(df).transform_fold(y).mark_rect().encode(
alt.X('hours(datetime):O', title='Hours of the day'),
alt.Y('day(datetime):O', title='Day'),
alt.Row('key:O', title=''),
color=agg_type_dict[agg_type],
tooltip = [alt.Tooltip('hours(datetime):O'),
alt.Tooltip('day(datetime):O'),
alt.Tooltip('key:N'),
alt.Tooltip(agg_type_dict[agg_type])]
).properties(
width=610,
height=150
)
def agg_by_period(agg_df, groupby_var):
"""
Aggregate numerical data by `groupby_var`. Calculate percentage and percentage change for all KPI categories.
Parameters
----------
agg_df : pandas.core.frame.DataFrame
Dataframe returned by `get_agg_data(cust_tweets, dhl_tweets)`.
groupby_var : str
Variable to aggregate the data by. One of ['year', 'quarter', 'month', 'week', 'day'].
Returns
-------
agg_df_period : pandas.core.frame.DataFrame
Dataframe containing numerical data agggreagated by `groupby_var`, within columns [`groupby_var`, 'variable', 'value', 'sum', 'percentage', 'pct_change'].
"""
# Transform datetime column to datetime format
agg_df['datetime'] = pd.to_datetime(agg_df['datetime'])
# Get respective time period from datetime column
if groupby_var == 'quarter':
agg_df['quarter'] = agg_df['datetime'].apply(lambda x: x.quarter)
elif groupby_var == 'month':
agg_df['month'] = agg_df['datetime'].apply(lambda x: x.month)
elif groupby_var == 'day':
agg_df['day'] = agg_df['datetime'].apply(lambda x: x.day)
# Aggregate by `groupby_var` by summation
agg_df_period = agg_df.melt(id_vars=groupby_var, value_vars=['Total Customer Mentions', 'Total DHL Tweets', 'Likes', 'Negative Mentions', 'Positive Mentions', 'Replies', 'Retweets']).groupby([groupby_var, 'variable'])['value'].sum().reset_index()
# Get totals, save in a new dataframe and set index to KPI categories
sum_df = agg_df_period.groupby(['variable'])['value'].sum().reset_index()
sum_df = sum_df.set_index('variable')
# Add column for totals for each respectives KPI categories
agg_df_period['sum'] = agg_df_period.apply(lambda row: sum_df.at[row['variable'], 'value'], axis=1)
# Calculate percentage and percentage change
agg_df_period['percentage'] = agg_df_period.apply(lambda row: row['value']/row['sum']*100, axis=1)
agg_df_period['pct_change'] = agg_df_period.groupby(['variable'])['value'].pct_change(fill_method='ffill')*100
return agg_df_period
def get_summary_df(cust_tweets, dhl_tweets, groupby_user_input):
"""
Create summary dataframe by aggregating `cust_tweets` and `dhl_tweets` based on `groupby_user_input`
Parameters
----------
cust_tweets : pandas.core.frame.DataFrame
Dataframe returned by `get_cust_tweet(df, dhl_acc)`.
dhl_tweets : pandas.core.frame.DataFrame
Dataframe returned by `get_dhl_tweet(df, dhl_acc)`.
groupby_user_input : str
Variable to aggregate the data by, based on user input. One of ['Year', 'Quarter', 'Month', 'Week', 'Day'].
Returns
-------
grouped_summary_merged : pandas.core.frame.DataFrame
Merged dataframe containing data aggregated by `groupby_user_input`, within columns [`groupby_user_input`, 'variable', 'value', 'sum', 'percentage', 'pct_change', 'Tweet'].
"""
agg_df = get_agg_data(cust_tweets, dhl_tweets).reset_index()
groupby_var = groupby_user_input.lower()
y_colname = {'count_cust_tweets': 'Total Customer Mentions',
'count_dhl_tweets': 'Total DHL Tweets',
'likes': 'Likes',
'polarity_negative_mentions': 'Negative Mentions',
'polarity_positive_mentions': 'Positive Mentions',
'replies': 'Replies',
'retweets': 'Retweets'}
agg_df = agg_df.rename(columns=y_colname)
agg_df_period = agg_by_period(agg_df, groupby_var)
# Get day and quarter value
if groupby_var == 'day':
dhl_tweets[f'{groupby_var}'] = dhl_tweets['date'].apply(lambda x: x.day)
cust_tweets[f'{groupby_var}'] = cust_tweets['date'].apply(lambda x: x.day)
elif groupby_var == 'quarter':
dhl_tweets[f'{groupby_var}'] = dhl_tweets['date'].apply(lambda x: x.quarter)
cust_tweets[f'{groupby_var}'] = cust_tweets['date'].apply(lambda x: x.quarter)
elif groupby_var == 'month':
dhl_tweets[f'{groupby_var}'] = dhl_tweets['date'].apply(lambda x: x.month)
cust_tweets[f'{groupby_var}'] = cust_tweets['date'].apply(lambda x: x.month)
# Get top tweets for all variables
grouped_top_replies = dhl_tweets[[f'{groupby_var}', 'tweet', 'replies']].sort_values(by=[f'{groupby_var}'], ascending=True).sort_values(by=['replies'], ascending=False).groupby([f'{groupby_var}']).head(1)
grouped_top_likes = dhl_tweets[[f'{groupby_var}', 'tweet', 'likes']].sort_values(by=[f'{groupby_var}'], ascending=True).sort_values(by=['likes'], ascending=False).groupby([f'{groupby_var}']).head(1)
grouped_top_retweets = dhl_tweets[[f'{groupby_var}', 'tweet', 'retweets']].sort_values(by=[f'{groupby_var}'], ascending=True).sort_values(by=['retweets'], ascending=False).groupby([f'{groupby_var}']).head(1)
# Concat tweets for all variables
grouped_top_dhl = pd.concat([grouped_top_replies, grouped_top_likes, grouped_top_retweets]).reset_index()
# Identify variable type (one of replies, likes, retweets)
grouped_top_dhl['Variable'] = np.where(grouped_top_dhl['replies'].notnull(), 'Replies',
np.where(grouped_top_dhl['likes'].notnull(), 'Likes',
np.where(grouped_top_dhl['retweets'].notnull(), 'Retweets', '')))
# Group cust_tweets by groupby_var
grouped_top_cust = cust_tweets.groupby([f'{groupby_var}', 'polarity']).max()[['tweet']].reset_index()
# Replace polarity with Mentions
grouped_top_cust['Variable'] = grouped_top_cust['polarity'].apply(lambda x: 'Negative Mentions' if x == 'negative' else 'Positive Mentions')
# Concat both grouped dhl_tweets and cust_tweets to create summary df
grouped_summary_df = pd.concat([grouped_top_cust[[f'{groupby_var}', 'tweet', 'Variable']], grouped_top_dhl[[f'{groupby_var}', 'tweet', 'Variable']]]).rename(columns={'tweet':'Tweet'}).reset_index(drop=True)
# Rename columns
grouped_summary_df = grouped_summary_df.rename(columns={'Variable': 'variable'})
# Ensure all are in numeric types
if groupby_var == 'week':
agg_df_period['week'] = pd.to_numeric(agg_df_period['week'])
grouped_summary_df['week'] = pd.to_numeric(grouped_summary_df['week'])
elif groupby_var == 'year':
agg_df_period['year'] = pd.to_numeric(agg_df_period['year'])
grouped_summary_df['year'] = pd.to_numeric(grouped_summary_df['year'])
elif groupby_var == 'month':
agg_df_period['month'] = pd.to_numeric(agg_df_period['month'])
grouped_summary_df['month'] = pd.to_numeric(grouped_summary_df['month'])
# Merge agg_df_period with grouped_summary_df
grouped_summary_merged = agg_df_period.merge(grouped_summary_df, left_on=[f'{groupby_var}', 'variable'], right_on=[f'{groupby_var}', 'variable'], how='left')
# Replace np.nan in Tweets with empty string
grouped_summary_merged['Tweet'] = grouped_summary_merged['Tweet'].replace(np.nan, '')
period_colname = {'year': 'Year',
'quarter': 'Quarter',
'month': 'Month',
'week': 'Week',
'day': 'Day'}
# Rename columns
grouped_summary_merged = grouped_summary_merged.rename(columns=period_colname)
return grouped_summary_merged
def plot_pct_graph(graph_type, groupby_user_input, summary_df, kpi_color_pal):
"""
Plot percentage or percentage change graph according to user input
Parameters
----------
graph_type : str
Graph to plot based on user input.One of ['Percentage over time', 'Percentage change over time'].
groupby_user_input : str
Variable to aggregate the data by, based on user input. One of ['Year', 'Quarter', 'Month', 'Week', 'Day'].
summary_df : pandas.core.frame.DataFrame
Dataframe containing data aggregated by `groupby_user_input`, within columns [`groupby_user_input`, 'variable', 'value', 'sum', 'percentage', 'pct_change', 'Tweet'].
kpi_color_pal : str
Name of Altair color scheme, chosen for KPI color code.
Returns
-------
altair.vegalite.v4.api.VConcatChart
Vertically concatenated altair chart with graph on top layer and text table on bottom layer.
"""
if graph_type == 'Percentage over time':
field_var = 'percentage'
field_var_title = 'Percentage'
else:
field_var = 'pct_change'
field_var_title = 'Percentage Change'
if groupby_user_input in ['Week', 'Day']:
axis_type = 'Q'
else:
axis_type = 'O'
if groupby_user_input in ['Year', 'Quarter', 'Month']:
# Mouseover selection. Reduces opacity on non-selected items on chart
highlight = alt.selection(type='single', on='mouseover', fields=[groupby_user_input], nearest=True)
bars = alt.Chart(summary_df).mark_bar().encode(
x=alt.X(f'{groupby_user_input}:{axis_type}', axis=alt.Axis(format='1')),
y=alt.Y(f'{field_var}:Q', title=field_var_title),
column=alt.Column('variable:N', title='KPI'),
color=alt.Color('variable:N', legend=None, scale=alt.Scale(scheme=kpi_color_pal)),
opacity=alt.condition(highlight, alt.value(1), alt.value(0.2))
).properties(
title={
"text": [f'KPI {field_var_title} across {groupby_user_input}'],
"subtitle": ["Plot represent all historical data.", f"Hover over bars to view the corresponding KPI {field_var_title} and representative tweets for each week in the Data Table below.",
""],
"color": "black",
"subtitleColor": "gray"
},
width=90,
height=100
).add_selection(highlight).transform_filter(alt.datum.Month > 0) # added in transform filter
p = bars
else:
# Drag selection. Reduces opacity on non-selected items on chart
highlight = alt.selection(type='interval')
line = alt.Chart(summary_df).mark_line().encode(
x=alt.X(f'{groupby_user_input}:{axis_type}', axis=alt.Axis(format='1', grid=False)),
y=alt.Y(f'{field_var}:Q', title=field_var_title),
color=alt.Color('variable:N', legend=None, scale=alt.Scale(scheme=kpi_color_pal)),
opacity=alt.condition(highlight, alt.value(1), alt.value(0.2))
).properties(
title={
"text": [f'KPI {field_var_title} across {groupby_user_input}'],
"subtitle": ["Plot represent all historical data.", "Drag mouse for selection. Data table below shows the corresponding tweets for selected points.",
""],
"color": "black",
"subtitleColor": "gray"
},
width=780,
height=150
).add_selection(highlight)
point = alt.Chart(summary_df).mark_circle().encode(
x=alt.X(f'{groupby_user_input}:{axis_type}', axis=alt.Axis(format='1')),
y=f'{field_var}:Q',
color=alt.Color('variable:N', legend=None, scale=alt.Scale(scheme=kpi_color_pal)),
opacity=alt.condition(highlight, alt.value(1), alt.value(0.2))
).transform_filter(highlight)
p = line+point
ranked_text = alt.Chart(summary_df).mark_text(align='left', baseline='middle', limit=400).encode(
y=alt.Y('row_number:O',axis=None)