-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
447 lines (350 loc) · 13.3 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
from flask import Flask, request, jsonify
from flask import Flask, g
import models
import preprocess
import sqlite3
import datetime
import os
# Database
# DATABASE = "db/predictions.db"
DATABASE = os.path.join(os.path.curdir, 'db', 'predictions.db')
# Load models and get classifiers
emotion_classifier = models.load_emotion_distilroberta()
suicidal_classifer = models.load_suicidal_text_electra()
# Create the Flask app
app = Flask(__name__)
def get_db():
db = getattr(g, "_database", None)
if db is None:
db = g._database = sqlite3.connect(DATABASE)
return db
@app.teardown_appcontext
def close_connection(exception):
db = getattr(g, "_database", None)
if db is not None:
db.close()
def create_table():
with app.app_context():
db = get_db()
cursor = db.cursor()
cursor.execute(
"""CREATE TABLE IF NOT EXISTS predictions
(prediction_id INTEGER PRIMARY KEY, record_timestamp TEXT, preprocessed_text TEXT, text TEXT,
emotion_joy REAL, emotion_surprise REAL, emotion_neutral REAL, emotion_sadness REAL,
emotion_anger REAL, emotion_disgust REAL, emotion_fear REAL, primary_emotion TEXT,
suicidal_label_0 REAL, suicidal_label_1 REAL, suicide_risk TEXT)"""
)
db.commit()
def get_score(arr, label):
for item in arr:
if item["label"] == label:
return item["score"]
def insert_new(text, predictions):
with app.app_context():
db = get_db()
cursor = db.cursor()
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# Extract data from the predictions
preprocessed_text = text["preprocessed_text"]
text = text["text"]
emotions = {
"joy": get_score(predictions["emotion"][0], "joy"),
"surprise": get_score(predictions["emotion"][0], "surprise"),
"neutral": get_score(predictions["emotion"][0], "neutral"),
"sadness": get_score(predictions["emotion"][0], "sadness"),
"anger": get_score(predictions["emotion"][0], "anger"),
"disgust": get_score(predictions["emotion"][0], "disgust"),
"fear": get_score(predictions["emotion"][0], "fear"),
}
primary_emotion = max(emotions, key=emotions.get)
suicidal = {
"non-suicidal": get_score(predictions["suicidal"][0], "LABEL_0"),
"suicidal": get_score(predictions["suicidal"][0], "LABEL_1"),
}
suicide_risk = max(suicidal, key=suicidal.get)
cursor.execute(
"""INSERT INTO predictions
(record_timestamp, preprocessed_text, text, emotion_joy, emotion_surprise, emotion_neutral, emotion_sadness,
emotion_anger, emotion_disgust, emotion_fear, primary_emotion, suicidal_label_0, suicidal_label_1, suicide_risk)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
(
timestamp,
preprocessed_text,
text,
emotions["joy"],
emotions["surprise"],
emotions["neutral"],
emotions["sadness"],
emotions["anger"],
emotions["disgust"],
emotions["fear"],
primary_emotion,
suicidal["non-suicidal"],
suicidal["suicidal"],
suicide_risk,
),
)
db.commit()
# Define the API endpoint for text processing
# curl -s -X POST -H "Content-Type: application/json" -d '{"text":"i want to kill myself"}' http://localhost:5000/text-input | jq
@app.route("/text-input", methods=["POST"])
def process_text():
# get the input data from the request
input_text = request.json["text"]
# preprocess the text data
preprocessed_text = preprocess.process_txt(input_text)
# generate predictions
emotion_predictions = emotion_classifier(preprocessed_text)
suicidal_predictions = suicidal_classifer(preprocessed_text)
text = {"text": input_text, "preprocessed_text": preprocessed_text}
predictions = {"emotion": emotion_predictions, "suicidal": suicidal_predictions}
insert_new(text, predictions)
## check if the user is at risk of suicide
with app.app_context():
db = get_db()
cursor = db.cursor()
query = """
SELECT COUNT(*) as frequency
FROM predictions
WHERE suicide_risk = 'suicidal' AND DATE(record_timestamp) = DATE('now', 'localtime');
"""
cursor.execute(query)
result = cursor.fetchone()
response = {"suicidal_count": "None"}
if (result is not None):
response = {"suicidal_count": result[0]}
return response
# Define the API endpoint for retrieving the overall mood of the day
# curl http://localhost:5000/today-mood
@app.route("/today-mood")
def mood_today():
with app.app_context():
db = get_db()
cursor = db.cursor()
query = """
SELECT primary_emotion
FROM predictions
WHERE DATE(record_timestamp) = DATE('now', 'localtime')
GROUP BY primary_emotion
ORDER BY COUNT(*) DESC, MAX(record_timestamp) DESC
LIMIT 1
"""
# Execute the query to get the highest repeated emotion
cursor.execute(query)
result = cursor.fetchone()
response = {"today_mood": "None"}
if (result is not None):
response = {"today_mood": result[0]}
return response
# Define the API endpoint for retrieving the overall mood of the week
# curl http://localhost:5000/week-mood
@app.route("/week-mood")
def mood_week():
with app.app_context():
db = get_db()
cursor = db.cursor()
query = """
SELECT primary_emotion
FROM predictions
WHERE record_timestamp > datetime('now', '-7 days', 'localtime')
GROUP BY primary_emotion
ORDER BY COUNT(*) DESC, MAX(record_timestamp) DESC
LIMIT 1
"""
# Execute the query to get the highest repeated emotion
cursor.execute(query)
result = cursor.fetchone()
response = {"week_mood": "None"}
if (result is not None):
response = {"week_mood": result[0]}
return response
# Define the API endpoint for retrieving the overall mood of the month
# curl http://localhost:5000/month-mood
@app.route("/month-mood")
def mood_month():
with app.app_context():
db = get_db()
cursor = db.cursor()
query = """
SELECT primary_emotion
FROM predictions
WHERE record_timestamp > datetime('now', '-1 month', 'localtime')
GROUP BY primary_emotion
ORDER BY COUNT(*) DESC, MAX(record_timestamp) DESC
LIMIT 1
"""
# Execute the query to get the highest repeated emotion
cursor.execute(query)
result = cursor.fetchone()
response = {"month_mood": "None"}
if (result is not None):
response = {"month_mood": result[0]}
return response
# Define the API endpoint for retrieving the main 3 mood percentages of the day
# curl http://localhost:5000/today_mood_percentages
@app.route("/today_mood_percentages")
def mood_percentages_today():
with app.app_context():
db = get_db()
cursor = db.cursor()
query = """
SELECT primary_emotion, COUNT(*) as count
FROM predictions
WHERE DATE(record_timestamp) = DATE('now', 'localtime')
GROUP BY primary_emotion
ORDER BY count DESC, MAX(record_timestamp) DESC;
"""
# Execute the query to get the emotion count
cursor.execute(query)
rows = cursor.fetchall()
response = {"main_mood_percentages": "None"}
if (rows is not None):
# Total count
total_count = sum([row[1] for row in rows])
result = []
for row in rows:
emotion, count = row
percentage = (count / total_count) * 100
result.append(
{
"emotion": emotion,
"percentage": round(percentage, 1),
}
)
response = {"main_mood_percentages": result}
return response
# Define the API endpoint for retrieving the overall mood percentages of the week
# curl http://localhost:5000/week_mood_percentages
@app.route("/week_mood_percentages")
def mood_percentages_week():
with app.app_context():
db = get_db()
cursor = db.cursor()
query = """
SELECT primary_emotion, COUNT(*) as count
FROM predictions
WHERE record_timestamp > datetime('now', '-7 days', 'localtime')
GROUP BY primary_emotion
ORDER BY count DESC, MAX(record_timestamp) DESC;
"""
# Execute the query to get the emotion count
cursor.execute(query)
rows = cursor.fetchall()
response = {"mood_percentages_week": "None"}
if (rows is not None):
# Total count
total_count = sum([row[1] for row in rows])
result = []
for row in rows:
emotion, count = row
percentage = (count / total_count) * 100
result.append(
{
"emotion": emotion,
"percentage": round(percentage, 1),
}
)
response = {"mood_percentages_week": result}
return response
# Define the API endpoint for retrieving the overall mood percentages of the month
# curl http://localhost:5000/month_mood_percentages
@app.route("/month_mood_percentages")
def mood_percentages_month():
with app.app_context():
db = get_db()
cursor = db.cursor()
query = """
SELECT primary_emotion, COUNT(*) as count
FROM predictions
WHERE record_timestamp > datetime('now', '-1 month', 'localtime')
GROUP BY primary_emotion
ORDER BY count DESC, MAX(record_timestamp) DESC;
"""
# Execute the query to get the emotion count
cursor.execute(query)
rows = cursor.fetchall()
response = {"mood_percentages_month": "None"}
if (rows is not None):
# Total count
total_count = sum([row[1] for row in rows])
result = []
for row in rows:
emotion, count = row
percentage = (count / total_count) * 100
result.append(
{
"emotion": emotion,
"percentage": round(percentage, 1),
}
)
response = {"mood_percentages_month": result}
return response
# Define the API endpoint for retrieving the latest 10 typing activity and their mood percentages
# curl http://localhost:5000/recent-text-activity
@app.route("/recent-text-activity")
def recent_text_activity():
with app.app_context():
db = get_db()
cursor = db.cursor()
query = """
SELECT
text,
emotion_joy,
emotion_surprise,
emotion_neutral,
emotion_sadness,
emotion_anger,
emotion_disgust,
emotion_fear,
primary_emotion,
suicidal_label_0,
suicidal_label_1,
suicide_risk
FROM predictions
WHERE DATE(record_timestamp) = DATE('now', 'localtime')
ORDER BY record_timestamp DESC
LIMIT 10
"""
# Execute the query to get the highest repeated emotion
cursor.execute(query)
rows = cursor.fetchall()
response = {"recent_text_activity": "None"}
if (rows is not None):
result = []
for row in rows:
(
text,
joy,
surprise,
neutral,
sadness,
anger,
disgust,
fear,
primary_emotion,
label_0,
label_1,
risk,
) = row
result.append(
{
"text": text,
"joy": round(joy * 100, 2),
"surprise": round(surprise * 100, 2),
"neutral": round(neutral * 100, 2),
"sadness": round(sadness * 100, 2),
"anger": round(anger * 100, 2),
"disgust": round(disgust * 100, 2),
"fear": round(fear * 100, 2),
"primary_emotion": primary_emotion,
"suicidal_label_0": round(label_0 * 100, 2),
"suicidal_label_1": round(label_1 * 100, 2),
"suicide_risk": risk
}
)
response = {"recent_text_activity": result}
return response
if __name__ == "__main__":
create_table()
app.run(host="0.0.0.0")
# app.run()