-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathapi.py
397 lines (336 loc) · 11.9 KB
/
api.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
import atexit
import json
import math
import os
import sys
import time
from functools import wraps
import pymysql.cursors
from flask import Blueprint, request
MESSAGES_PER_PAGE = 10
blueprint = Blueprint("api", __name__)
socketio = None
hostname = None
port = None
username = None
password = None
db = None
if 'VCAP_SERVICES' in os.environ:
mysql_info = json.loads(os.environ['VCAP_SERVICES'])['cleardb'][0]
elif os.path.isfile('config.json'):
with open('config.json') as json_data:
try:
mysql_info = json.loads(json_data.read())
except:
raise
sys.exit('Database credentials are incorrect. Please update the config.json with the database credentials')
else:
sys.exit('Database credentials not specified')
mysql_cred = mysql_info['credentials']
hostname = mysql_cred['hostname']
port = mysql_cred['port'] or 3306
username = mysql_cred['username']
password = mysql_cred['password']
db = mysql_cred['name']
try:
connection = pymysql.connect(host=hostname,
user=username,
password=password,
db=db,
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
connection.close()
except:
sys.exit('Database credentials are incorrect. Please update the config.json with the database credentials')
def _drop_tables(cursor):
try:
sql = '''DROP TABLE messages;'''
cursor.execute(sql)
except:
pass
try:
sql = '''DROP TABLE relationships;'''
cursor.execute(sql)
except:
pass
def reconnect(func):
@wraps(func)
def wrapper(*args, **kwargs):
close_conn = False
conn = kwargs.get('conn')
if conn is None:
close_conn = True
conn = connect()
kwargs['conn'] = conn
retval = func(*args, **kwargs)
if close_conn:
conn.commit()
conn.close()
return retval
return wrapper
def close_db(con):
con.close()
def connect(a=0):
if a == 30:
return
try:
conn = pymysql.connect(host=hostname,
user=username,
password=password,
db=db,
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
except pymysql.err.InternalError:
time.sleep(1)
return connect(a=a + 1)
return conn
# atexit.register(close_db, con=connection)
@reconnect
def create_db(conn=None):
with conn.cursor() as cursor:
sql = '''CREATE TABLE IF NOT EXISTS messages
(id INT AUTO_INCREMENT,
text VARCHAR(3000),
phone_number VARCHAR(15),
city VARCHAR(30),
state VARCHAR(2),
sentiment VARCHAR(15),
timestamp DATETIME DEFAULT NULL,
archived_timestamp DATETIME DEFAULT NULL,
PRIMARY KEY (id)); '''
cursor.execute(sql)
sql = '''CREATE TABLE IF NOT EXISTS relationships
(message_id INT,
text VARCHAR(50),
type VARCHAR(25),
relevance FLOAT,
sentiment VARCHAR(12)); '''
cursor.execute(sql)
create_db()
@blueprint.route('/message', methods=['POST'])
@reconnect
def message(conn=None):
phone_number = request.form['From']
phone_number = phone_number[:-4] + "XXXX" # obfuscate phone number
message_body = request.form['Body']
city = request.form['FromCity']
state = request.form['FromState']
addOns = json.loads(request.form['AddOns'])
try:
sentiment = addOns['results']['ibm_watson_sentiment']['result']['docSentiment']['type']
except:
sentiment = 'Neutral'
data = addOns['results']['ibm_watson_insights']['result']
with conn.cursor() as cursor:
parameters = [message_body, phone_number, city, state, sentiment]
sql = '''INSERT INTO messages
(text, phone_number, city, state, sentiment, timestamp)
VALUES(%s, %s, %s, %s, %s, NOW())'''
cursor.execute(sql, parameters)
parameters = []
keywords = data['keywords']
entities = data['entities']
concepts = data['concepts']
for keyword in keywords:
param = keyword['text'], "keyword", keyword['relevance'], keyword['sentiment']['type']
parameters.append(param)
for entity in entities:
param = entity['text'], "entity", entity['relevance'], entity['sentiment']['type']
parameters.append(param)
for concept in concepts:
param = concept['text'], "concept", concept['relevance'], 0
parameters.append(param)
sql = '''INSERT INTO relationships
(message_id, text, type, relevance, sentiment)
VALUES(LAST_INSERT_ID(), %s, %s, %s, %s)'''
cursor.executemany(sql, parameters)
conn.commit()
# Emit the data via websocket
socketio.emit('incoming data', get_messages())
return json.dumps({'status': 'success'})
def _num_to_day(num):
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
return days[num]
@blueprint.route('/get_messages')
@blueprint.route('/get_messages/<path:page_number>')
@reconnect
def get_messages(page_number=1, conn=None):
page_offset = int(page_number) - 1
with conn.cursor() as cursor:
sql = '''
SELECT SQL_CALC_FOUND_ROWS
messages.id,
messages.text,
phone_number,
city,
state,
timestamp,
messages.sentiment,
GROUP_CONCAT(
CONCAT_WS(
":",
relationships.type,
relationships.text,
relationships.relevance,
relationships.sentiment
)
separator "|"
) as relationships
FROM messages
LEFT JOIN relationships
ON messages.id=relationships.message_id
WHERE messages.archived_timestamp is NULL
GROUP BY messages.id
ORDER BY timestamp desc
LIMIT %s
OFFSET %s
'''
cursor.execute(sql, [MESSAGES_PER_PAGE, page_offset * MESSAGES_PER_PAGE])
result = cursor.fetchall()
cursor.execute('SELECT FOUND_ROWS() as pages')
pages = cursor.fetchone()
for r in result:
timestamp = r['timestamp']
day_of_week = _num_to_day(timestamp.weekday())
day = timestamp.strftime("{0} %B %d".format(day_of_week))
time = str(timestamp.time())
r.pop('timestamp')
r['day'] = day
r['time'] = time
relationships = r['relationships'].split('|')
r['keyword'] = {}
r['entity'] = {}
r['concept'] = {}
for rel in relationships:
details = rel.split(':')
if len(details) > 2:
r_type = details[0]
r[r_type][details[1]] = {
'relevance': details[2],
'sentiment': details[3]
}
r.pop('relationships')
return json.dumps({
'messages': result,
'totalPages': math.ceil(float(pages['pages']) / MESSAGES_PER_PAGE)
})
@blueprint.route('/get_archived_messages')
@blueprint.route('/get_archived_messages/<path:page_number>')
@reconnect
def get_archived_messages(page_number=1, conn=None):
page_offset = int(page_number) - 1
with conn.cursor() as cursor:
sql = '''
SELECT SQL_CALC_FOUND_ROWS
messages.id,
messages.text,
phone_number,
city,
state,
timestamp,
messages.sentiment,
messages.archived_timestamp,
GROUP_CONCAT(
CONCAT_WS(
":",
relationships.type,
relationships.text,
relationships.relevance,
relationships.sentiment
)
separator "|"
) as relationships
FROM messages
LEFT JOIN relationships
ON messages.id=relationships.message_id
WHERE messages.archived_timestamp is NOT NULL
GROUP BY messages.id
ORDER BY timestamp desc
LIMIT %s
OFFSET %s
'''
cursor.execute(sql, [MESSAGES_PER_PAGE, page_offset * MESSAGES_PER_PAGE])
result = cursor.fetchall()
cursor.execute('SELECT FOUND_ROWS() as pages')
pages = cursor.fetchone()
for r in result:
timestamp = r['timestamp']
day_of_week = _num_to_day(timestamp.weekday())
day = timestamp.strftime("{0} %B %d".format(day_of_week))
time = str(timestamp.time())
r.pop('timestamp')
r['day'] = day
r['time'] = time
archived_timestamp = r['archived_timestamp']
archived_day_of_week = _num_to_day(archived_timestamp.weekday())
archived_day = archived_timestamp.strftime("{0} %B %d".format(archived_day_of_week))
archived_time = str(archived_timestamp.time())
r.pop('archived_timestamp')
r['archived_day'] = archived_day
r['archived_time'] = archived_time
relationships = r['relationships'].split('|')
r['keyword'] = {}
r['entity'] = {}
r['concept'] = {}
for rel in relationships:
details = rel.split(':')
r_type = details[0]
r[r_type][details[1]] = {
'relevance': details[2],
'sentiment': details[3]
}
r.pop('relationships')
return json.dumps({
'messages': result,
'totalPages': math.ceil(float(pages['pages']) / MESSAGES_PER_PAGE)
})
@blueprint.route('/get_relationships')
@reconnect
def get_relationships(conn=None):
with conn.cursor() as cursor:
sql = '''SELECT * FROM relationships'''
cursor.execute(sql)
result = cursor.fetchall()
return json.dumps(result)
@blueprint.route('/get_num_messages/<days>')
@reconnect
def get_num_messages(days, conn=None):
with conn.cursor() as cursor:
sql = '''
SELECT count(*) as num_messages FROM messages
WHERE timestamp >= (now() - INTERVAL %s DAY)
'''
cursor.execute(sql, [days])
result = cursor.fetchone()
return json.dumps(result)
@blueprint.route('/get_sentiment_count/<days>')
@reconnect
def get_sentiment_count(days, conn=None):
with conn.cursor() as cursor:
sql = '''
SELECT CONCAT(UCASE(LEFT(sentiment, 1)), LCASE(SUBSTRING(sentiment, 2))) as label, count(sentiment) as value,
case
when LOWER(sentiment) = 'positive' then '#4A90E2'
when LOWER(sentiment) = 'negative' then '#734199'
when LOWER(sentiment) = 'neutral' then '#C7C7C6' end as color
FROM messages
WHERE timestamp >= (now() - INTERVAL %s DAY)
GROUP BY sentiment
'''
cursor.execute(sql, [days])
result = cursor.fetchall()
return json.dumps(result)
@blueprint.route('/archive_message/<id>', methods=['POST'])
@reconnect
def archive_message(id, conn=None):
with conn.cursor() as cursor:
sql = '''
UPDATE messages
SET archived_timestamp = NOW()
WHERE id = %s
'''
cursor.execute(sql, [id])
conn.commit()
socketio.emit('incoming data', get_messages())
socketio.emit('archived data', get_archived_messages())
return json.dumps({'status': 'success'})