/
runnerFBactivity.py
209 lines (164 loc) · 6 KB
/
runnerFBactivity.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Created on Fri May 08 17:08:44 2015
@author: Roger
"""
CHART_LIMIT = 10
import facebook, numpy as np, matplotlib.pyplot as plt
from pandas import DataFrame
from datetime import datetime
from matplotlib.ticker import FuncFormatter
from string import lower
def readRunners():
runnerFile = 'runners.csv'
fileObj = open(runnerFile,'r')
header = fileObj.readline().strip()
runners = []
for line in fileObj.readlines():
runner, page, govPage = line.strip().split(',')
if govPage == '' or str(govPage) == '0':
govPage = False
else:
govPage = True
entry = {'runner': runner,
'page': page,
'govPage': govPage}
runners.append(entry)
fileObj.close()
return runners
def readToken():
'''
Reads in the Facebook Token.
To obtain a facebook token,
- login to facebook through a web browser
- then visit, https://developers.facebook.com/tools/explorer/
- click "Get Token" button on top right
- click "Get Access Token"
- copy ugly string from "Access Token: " field
- save to file facebookToken.txt
'''
fbTokenFile = 'facebookToken.txt'
fileObj = open(fbTokenFile, 'r')
fbToken = fileObj.readline()
fileObj.close()
return fbToken
##
## Format fields
##
def fmtShares(Dict):
if type(Dict) == dict:
return Dict['count']
else:
return 0
def fmtLikes(objID):
return fbGraph.get_object(objID + '/likes',
summary=True)['summary']['total_count']
def fmtDate(timeStr):
date, time = timeStr.split('T')
time = str(time)[:8]
dtTimeStr = str(date) + ' ' + time
fmt = "%Y-%m-%d %H:%M:%S"
d = datetime.strptime(dtTimeStr,fmt)
return d.strftime("%m %d %Y")
def getPostData(fbGraph, entry):
global CHART_LIMIT
retrieved = False
i=0
while retrieved == False:
i += 1
try:
posts = fbGraph.get_object(entry['page'] + '/posts',
limit=CHART_LIMIT*15)['data']
retrieved = True
except facebook.GraphAPIError:
print "Failed retrieving Graph object from facebook, retrying..."
pass
if i > 14:
print "Giving up"
return None
frame = DataFrame(posts)
##Later, maybe output this frame for further study
postData = DataFrame(columns=('Date', 'Likes', 'Shares'))
postData['Shares'] = frame['shares'].map(fmtShares)
postData['Likes'] = frame['id'].map(fmtLikes)
postData['Date'] = frame['created_time'].map(fmtDate)
postData = postData.groupby(by='Date', sort=False).mean()
postData = postData.head(n=CHART_LIMIT)
postData.fillna(value=0)
return postData
def splitLine(ax, x, y, splitNum, style1, style2):
'''Creates a two styled line given;
ax = an axis
x = an array of x coordinates for 2D Line
y = an array of y coordinates for 2D Line
splitNum = index number to split Line by x tick
style1 = dictionary for left part of Line
style2 = dictionary for right part of Line
'''
split = x[splitNum]
low_mask = x <= split
upper_mask = x >= split
lower, = ax.plot(x[low_mask], y[low_mask], **style1)
upper, = ax.plot(x[upper_mask], y[upper_mask], **style2)
return lower, upper
def fmtXlabels(x, pos):
'''x=value, pos=position'''
if x >= len(dates):
return ''
month, day, year = dates[int(x)].split(' ')
return month + '/' + day + "\n " + year
def fmtYlabels(y, pos):
'''y=value, pos=position'''
y = int(y)
return "{:,}".format(y)
if __name__ == '__main__':
xFormatter = FuncFormatter(fmtXlabels)
yFormatter = FuncFormatter(fmtYlabels)
runners = readRunners()
fbToken = readToken()
fbGraph = facebook.GraphAPI(fbToken)
failed = []
for runner in runners:#[:1]:
if lower(runner['page']) == 'null':
continue
feedback = getPostData(fbGraph, runner)
if feedback is None:
print "Failed getting data for %s" % runner['runner']
failed.append(runner['runner'])
continue
dates = feedback.index.tolist()
earlyLike = {'color': 'r', 'lw': 1, 'ls': '--'}
agedLike = {'color': 'r', 'lw': 2, 'ls': '-', 'label': 'Likes'}
earlyShare = {'color': 'b', 'lw': 1, 'ls': '--'}
agedShare = {'color': 'b', 'lw': 2, 'ls': '-', 'label': 'Shares'}
fig, ax = plt.subplots()
splitLine(ax, np.array(range(CHART_LIMIT)),
np.array(feedback['Likes']), 1,
earlyLike, agedLike)
splitLine(ax, np.array(range(CHART_LIMIT)),
np.array(feedback['Shares']), 1,
earlyShare, agedShare)
earlyData = plt.Line2D(range(CHART_LIMIT),
feedback['Shares'], ls='--',
label='Recent Data\n(Early collection)',
color='k')
ax.add_line(earlyData)
ax.legend(bbox_to_anchor=(1.5,1))
ax.set_xticklabels(dates, rotation=60)
ax.xaxis.set_major_formatter(xFormatter)
ax.yaxis.set_major_formatter(yFormatter)
ax.set_title(runner['runner'] + ' Facebook Feedback')
plt.annotate('[Source: http://www.facebook.com/' + runner['page'] + ']',
(0,0), (0, -60), xycoords='axes fraction',
textcoords='offset points', va='top')
if runner['govPage']:
plt.annotate('*Government Sponsored Page',
(0,0), (0, -70), xycoords='axes fraction',
textcoords='offset points', va='top')
plt.show()
fig.savefig(runner['runner'].replace(' ','_') + '.png',
bbox_inches='tight')
print 'Failed getting graphs for:'
for a in failed:
print a