-
Notifications
You must be signed in to change notification settings - Fork 0
/
orange.py
executable file
·184 lines (173 loc) · 6.49 KB
/
orange.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
#!/usr/bin/python
import flask
from flask import Flask
from flask import render_template
import pymongo
import iso8601
import random
import re
import urlparse
import json
#from config import *
from collections import defaultdict
#for setting up the host name
import subprocess
import sys
host = subprocess.check_output('hostname').strip()
try:
dns = subprocess.check_output('dnsdomainname').strip()
if dns:
host = host + '.' + dns
else:
host = subprocess.check_output('hostname -i').strip()
except OSError:
pass #this happens when you are on a computer not set up as a server
app = Flask(__name__)
css = '/static/orange.css'
@app.route("/")
def displayOverview():
dygraphsData = getDygraphsDailyVolumeData()
return render_template('orangeOverview.html', css=css,
dygraphsTimeData=dygraphsData)
def getDygraphsDailyVolumeData():
columns = ['tweet','retweets','date','sentiment','valence','negative','neutral','positive','unsure']
dayCounts = defaultdict(int)
dayList = []
for line in open("static/orange/2012-12.tsv"):
fields = line.split('\t')
date = fields[columns.index('date')]
m = re.search(r'^(....)-(..)-(..)T(..)',date)
year = int(m.group(1))
month = int(m.group(2))
day = int(m.group(3))
hour = int(m.group(4))
# month, day, hour = map(lambda x: getattr(re.search(r'^(....)-(..)-(..)T(..)',date), 'group')(x), [1,2,3,4])
dayCounts[(year,month,day)] +=1
if dayCounts[(year,month,day)] == 1:
dayList.append((year,month,day))
data = []
for day in dayList:
y,m,d = day
volume = dayCounts[day]
data.append("\"%s-%s-%s, %s \\n\""%(y,m,d,volume))
outString = "+".join(data) + ','
return outString
def getDygraphsHourlyVolumeData(year,month,day):
f = open("static/orange/dayModels/hourlyCounts_%s-%s-%s"%(year,month,day))
data = []
for l in f:
y,m,d,h,v = l.split()
data.append("\"%s-%s-%s %02d:00:00, %s \\n\""%(y,m,d,int(h),v))
outString = "+".join(data) + ','
return outString
def getDygraphsHourlyVolumeData_new(searchYear,searchMonth,searchDay):
# setup column labes
columns = ['tweet','retweets','date','sentiment','valence','negative','neutral','positive','unsure']
#dayModelFile = AutoVivification()
hourlyDict = defaultdict(int)
#dayModelFile = OrderedDict(int)
dayList = []
data = []
# read tsv file
for line in open("static/orange/2012-12.tsv"):
fields = line.split('\t')
date = fields[columns.index('date')]
m = re.search(r'^(....)-(..)-(..)T(..)',date)
year = int(m.group(1))
month = int(m.group(2))
day = int(m.group(3))
hour = int(m.group(4))
# month, day, hour = map(lambda x: getattr(re.search(r'^(....)-(..)-(..)T(..)',date), 'group')(x), [1,2,3,4])
if year ==searchYear and month==searchMonth and day==searchDay:
hourlyDict[hour] +=1
data = []
for hr in range(0,24):
data.append("\"%s-%s-%s %02d:00:00, %s \\n\""%(searchYear,
searchMonth,
searchDay,
hr,hourlyDict[hr]))
outString = "+".join(data) + ','
return outString
def getTweetData(year,month,day):
f = open("static/orange/%s-%s.tsv"%(year,month))
data = []
for l in f:
tweet,retweet,ts,sentiment,valence,neg,neu,pos,uns = l.split("\t")
valence = valence.strip() # address probelm converting to float
try:
valence = float(valence)*100 #scale to -100,100 for display purposes
except TypeError:
#valence = 0
return "'%s'"%x[3]
#return valence
mtch = re.search(r'^(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):',ts)
y = int(mtch.group(1))
m = int(mtch.group(2))
d = int(mtch.group(3))
h = int(mtch.group(4))
if year == y and month == m and day == d:
#return d
#data.append((tweet, sentiment, valence))
data.append((tweet, sentiment, valence))
f.close()
output = {'cols':[{'id':'tweet', 'label':'tweet','type':'string'},
{'id':'sentiment', 'label':'sentiment','type':'string'},
{'id':'valence', 'label':'valence','type':'number'}],
'rows': []}
for x in data:
output['rows'].append({'c':[{'v':x[0]},{'v':x[1]},{'v':float(x[2])}]})
#output = json.dumps(output)
return output
#@app.route('/<path:path>')
#def catch_all(path):
@app.route('/<int:year>/<int:month>/<int:day>')
def catch_all(year,month,day):
if not app.debug:
flask.abort(404)
# if path == "favicon.ico":
# flask.abort(404)
# check if path denotes a day
# m = re.search(r'^(\d\d\d\d)/(\d\d)/(\d\d)$', path)
# year = int(m.group(1))
# month = int(m.group(2))
# day = int(m.group(3))
#if m:
if True:
if flask.request.query_string :
output = {}
output['table'] = getTweetData(year,month,day)
output['status'] = 'ok'
qsDict = urlparse.parse_qs(flask.request.query_string)
handler = "google.visualization.Query.setResponse"
gChartOpt = {}
if 'tqx' in qsDict:
#return str(qsDict)
options = qsDict['tqx'][0].split(";")
gChartOpt = {}
for o in options:
(key,val) = o.split(":")
gChartOpt[key]=val
if 'reqId' in gChartOpt:
output['reqId'] = gChartOpt['reqId']
if 'responseHandler' in gChartOpt:
handler = gChartOpt['responseHandler']
output = handler + "(" + json.dumps(output) + ")"
return output
else:
requestType = "general"
dygraphsTimeData = getDygraphsHourlyVolumeData_new(year,month,day)
return render_template('orangeDayView.html', css=css,
dygraphsTimeData=dygraphsTimeData,
year=year,month=month,day="%02d"%day,
host=host)
else:
flask.abort(404)
# try:
# f = open(path)
# except IOError, e:
# flask.abort(404)
# return
# return f.read()
if __name__ == '__main__':
#app.run(host="homebrew.usc.edu", debug=True)
app.run(host='0.0.0.0', debug=True)