-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmock_server.py
2131 lines (1853 loc) · 72 KB
/
mock_server.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
"""
Mock server for the eRisk challenge (https://erisk.irlab.org/).
Copyright (C) 2022 Juan Martín Loyola
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License version 3 as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
import arviz as az
from databases import Database
import datetime
from enum import Enum
from fastapi import FastAPI, status, HTTPException, Query
from io import BytesIO
import json
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
from pydantic import BaseModel, create_model
from random import choice
from sklearn.metrics import precision_recall_fscore_support
import sqlite3
from starlette.responses import StreamingResponse, HTMLResponse
from typing import List, Optional
from performance_measures import erde_final, f_latency, precision_at_k, ndcg
import config
# Global variable to store the users' writings.
WRITINGS = {task_name: [] for task_name in config.challenges_list}
# Global variable to store the true label of the users.
SUBJECTS = {task_name: {} for task_name in config.challenges_list}
# Global variable to store the median number of posts from the datasets.
MEDIAN_NUMBER_POSTS = {task_name: None for task_name in config.challenges_list}
# Dictionary with the path to the datasets.
DATASET_PATHS = {
task_name: os.path.join(
config.dataset_root_path, f"{task_name}{config.dataset_file_suffix}"
)
for task_name in config.challenges_list
}
# Since by default sqlite3 does not check FOREIGN KEYS, set that option when
# connecting to the database.
# Create a subclass of the sqlite3.Connection class to execute the pragma
# https://github.com/encode/databases/issues/169#issuecomment-644816412
#
# Also, to avoid being locked of the database by an operation that takes too
# long, set the `busy_timeout` pragma. This is related to the timeout parameter
# from sqlite3 in Python.
# Since the package databases does not passes any options to database, these
# need to be set using pragmas when possible.
# The timeout parameter specifies how long the connection should wait for the
# lock to go away until raising an exception.
# See
# https://github.com/python/cpython/blob/b2077117d125925210148294eefee28797b7ff4c/Modules/_sqlite/connection.c#L212
# https://www.sqlite.org/pragma.html#pragma_busy_timeout
class Connection(sqlite3.Connection):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.execute("""PRAGMA foreign_keys=ON""")
self.execute("""PRAGMA busy_timeout=120000""")
app = FastAPI()
database = Database(f"sqlite:///database/{config.database_name}.db", factory=Connection)
TaskName = Enum(
"TaskName", {task_name: task_name for task_name in config.challenges_list}
)
# Data Models
class TeamBase(BaseModel):
# Since the column team_id is an INTEGER PRIMARY KEY, sqlite automatically
# set its value incrementally if not indicated. Thus, It isn't necessary to
# include it in the model.
# team_id: int
name: str
token: str
number_runs: int
extra_info = "no extra information"
class TeamIn(TeamBase):
pass
class TeamOut(TeamBase):
team_id: int
class UsersWritings(BaseModel):
id: int
number: int
nick: str
redditor: int
title: str
content: str
date: str
class ResponseData(BaseModel):
nick: str
decision: int
score: float
class BaseExperimentResult(BaseModel):
team_id: int
task_id: int
run_id: int
precision: float
recall: float
f1_score: float
positive_precision: float
positive_recall: float
positive_f1_score: float
erde_5: float
erde_50: float
f_latency: float
structure = {}
for i in config.chosen_delays_for_ranking:
structure[f"precision_at_10_{i}"] = (float, ...)
structure[f"ndcg_at_10_{i}"] = (float, ...)
structure[f"ndcg_at_100_{i}"] = (float, ...)
ExperimentResult = create_model(
"ExperimentResult",
**structure,
__base__=BaseExperimentResult,
)
CREATE_TABLE_TEAMS = """
CREATE TABLE IF NOT EXISTS teams(
team_id INTEGER PRIMARY KEY,
name VARCHAR(40) UNIQUE,
token VARCHAR(42) UNIQUE,
number_runs INTEGER,
extra_info TEXT DEFAULT "no extra information"
);"""
CREATE_TABLE_TASK = """
CREATE TABLE IF NOT EXISTS tasks(
task_id INTEGER PRIMARY KEY,
task VARCHAR(20) UNIQUE
);"""
CREATE_TABLE_RUNS_STATUS = """
CREATE TABLE IF NOT EXISTS runs_status(
team_id INTEGER,
task_id INTEGER,
current_post_number INTEGER,
has_finished INTEGER,
PRIMARY KEY (team_id, task_id),
FOREIGN KEY (team_id) REFERENCES teams(team_id),
FOREIGN KEY (task_id) REFERENCES tasks(task_id)
);"""
CREATE_TABLE_GET_WRITINGS_REQUESTS = """
CREATE TABLE IF NOT EXISTS get_writings_requests(
team_id INTEGER,
task_id INTEGER,
current_post_number INTEGER,
request_time REAL,
PRIMARY KEY (team_id, task_id, current_post_number),
FOREIGN KEY (team_id) REFERENCES teams(team_id),
FOREIGN KEY (task_id) REFERENCES tasks(task_id)
);"""
CREATE_TABLE_RESPONSES = """
CREATE TABLE IF NOT EXISTS responses(
team_id INTEGER,
task_id INTEGER,
run_id INTEGER,
current_post_number INTEGER,
json_response BLOB,
response_time REAL,
PRIMARY KEY (team_id, task_id, run_id, current_post_number),
FOREIGN KEY (team_id) REFERENCES teams(team_id),
FOREIGN KEY (task_id) REFERENCES tasks(task_id)
);"""
CREATE_TABLE_RESULTS = (
"""
CREATE TABLE IF NOT EXISTS results(
team_id INTEGER,
task_id INTEGER,
run_id INTEGER,
precision REAL,
recall REAL,
f1_score REAL,
positive_precision REAL,
positive_recall REAL,
positive_f1_score REAL,
erde_5 REAL,
erde_50 REAL,
f_latency REAL,
"""
+ "".join(
[
f"precision_at_10_{i} REAL,\nndcg_at_10_{i} REAL,\nndcg_at_100_{i} REAL,\n"
for i in config.chosen_delays_for_ranking
]
)
+ """
PRIMARY KEY (team_id, task_id, run_id),
FOREIGN KEY (team_id) REFERENCES teams(team_id),
FOREIGN KEY (task_id) REFERENCES tasks(task_id)
);"""
)
CREATE_TABLE_GET_WRITINGS_SERVER_TIMES = """
CREATE TABLE IF NOT EXISTS get_writings_server_times(
team_id INTEGER,
task_id INTEGER,
current_post_number INTEGER,
start_time REAL,
elapsed_time REAL,
PRIMARY KEY (team_id, task_id, current_post_number),
FOREIGN KEY (team_id) REFERENCES teams(team_id),
FOREIGN KEY (task_id) REFERENCES tasks(task_id)
);"""
CREATE_TABLE_RESPONSES_SERVER_TIMES = """
CREATE TABLE IF NOT EXISTS responses_server_times(
team_id INTEGER,
task_id INTEGER,
run_id INTEGER,
current_post_number INTEGER,
start_time REAL,
elapsed_time REAL,
PRIMARY KEY (team_id, task_id, run_id, current_post_number),
FOREIGN KEY (team_id) REFERENCES teams(team_id),
FOREIGN KEY (task_id) REFERENCES tasks(task_id)
);"""
TABLES_CREATION_QUERIES = [
CREATE_TABLE_TEAMS,
CREATE_TABLE_TASK,
CREATE_TABLE_RUNS_STATUS,
CREATE_TABLE_GET_WRITINGS_REQUESTS,
CREATE_TABLE_RESPONSES,
CREATE_TABLE_RESULTS,
CREATE_TABLE_GET_WRITINGS_SERVER_TIMES,
CREATE_TABLE_RESPONSES_SERVER_TIMES,
]
async def get_task_id(task: TaskName):
"""Get the task_id."""
query = """SELECT task_id FROM tasks WHERE task=:task"""
result = await database.fetch_one(query=query, values={"task": task.value})
# This will always return a task_id.
return result["task_id"]
async def get_team_information(token: str):
"""Get the team id, name and number of runs of the team with the given token."""
query = """SELECT team_id, name, number_runs FROM teams WHERE token=:token"""
result = await database.fetch_one(query=query, values={"token": token})
if result is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail=f"Invalid token '{token}'."
)
team_id = result["team_id"]
name = result["name"]
number_runs = result["number_runs"]
return team_id, name, number_runs
@app.on_event("startup")
async def startup():
# If the folder for the database does not exists, create it.
os.makedirs("database", exist_ok=True)
await database.connect()
result = await database.fetch_one(query="""PRAGMA foreign_keys""")
if result[0]:
print("PRAGMA foreign_keys is set. FOREIGN KEYs will be checked.")
else:
print("PRAGMA foreign_keys is not set. FOREIGN KEYs will not be checked.")
result = await database.fetch_one(query="""PRAGMA busy_timeout""")
print(f"PRAGMA busy_timeout = {result[0]} milliseconds.")
print(
"Checking if there exist any tables. If not, create all of them and initialize some."
)
query = """SELECT COUNT(*) as number_tables FROM sqlite_schema WHERE name='teams'"""
result = await database.fetch_one(query=query)
if result["number_tables"] == 0:
print(
"The database is empty. Creating the tables and initializing some of them."
)
for q in TABLES_CREATION_QUERIES:
await database.execute(query=q)
# Insert the tasks for the eRisk challenge.
query = """INSERT INTO tasks(task) VALUES (:task)"""
values = [{"task": t.value} for t in TaskName]
await database.execute_many(query=query, values=values)
# Insert random teams.
values = [
{"name": "UNSL", "token": "777", "number_runs": 5},
{"name": "CONICET", "token": "333", "number_runs": 4},
{"name": "IMASL", "token": "444", "number_runs": 1},
]
for v in values:
t = TeamIn(**v)
await create_team(t)
print("Initializing the SUBJECTS and WRITINGS dictionaries.")
for t in TaskName:
load_writings(t)
def median(num_posts):
"""Median of the numbers' list."""
num_posts.sort()
m = len(num_posts) // 2
if (len(num_posts) % 2) == 0:
return (num_posts[m - 1] + num_posts[m]) / 2
else:
return num_posts[m]
def load_writings(task: TaskName):
"""Load the users writings from a file."""
global WRITINGS, SUBJECTS, DATASET_PATHS, MEDIAN_NUMBER_POSTS
writings = WRITINGS[task.value]
subjects = SUBJECTS[task.value]
dataset_path = DATASET_PATHS[task.value]
with open(dataset_path, "r", encoding="utf-8") as f:
j = 0
for i, line in enumerate(f):
subject_id = f"subject{i}"
label, document = line.split(maxsplit=1)
label = 1 if label == "positive" else 0
subject_writings = document.split(config.end_of_post_token)
subjects[subject_id] = {
"label": label,
"num_posts": len(subject_writings),
}
for w_idx, writing in enumerate(subject_writings):
if len(writings) <= w_idx:
writings.append([])
writings[w_idx].append(
{
"id": j,
"number": w_idx,
"nick": subject_id,
"redditor": i,
"title": "",
"content": writing,
"date": "",
}
)
j += 1
print(f"The number of users for {task.value} is {len(subjects)}.")
print(f"The maximum number of posts for {task.value} is {len(writings)}.")
# Get median number of posts.
num_posts = [v["num_posts"] for k, v in subjects.items()]
MEDIAN_NUMBER_POSTS[task.value] = median(num_posts)
print(
f"The median number of posts for {task.value} is {MEDIAN_NUMBER_POSTS[task.value]}."
)
@app.on_event("shutdown")
async def shutdown():
await database.disconnect()
@app.get(
"/teams/list",
tags=["teams"],
response_description="The list of registered teams.",
response_model=List[TeamOut],
)
async def get_all_teams():
"""
Get the list of teams registered.
Example curl command:
```bash
curl -X GET "localhost:8000/teams/list"
```
"""
query = """SELECT * FROM teams"""
results = await database.fetch_all(query=query)
result_list = [TeamOut(**r) for r in results]
return result_list
@app.get(
"/teams/finished/{task}",
tags=["teams"],
response_description="List the teams that have finished the task.",
response_model=List[TeamOut],
)
async def get_all_finished_teams(task: TaskName):
"""
Get the list of teams that have finished the task.
Example curl commands:
```bash
curl -X GET "localhost:8000/teams/finished/gambling"
```
"""
query = """
SELECT teams.*
FROM teams, runs_status, tasks
WHERE teams.team_id=runs_status.team_id AND
tasks.task=:task AND
runs_status.task_id=tasks.task_id AND
runs_status.has_finished=1
"""
results = await database.fetch_all(query=query, values={"task": task.value})
result_list = [TeamOut(**r) for r in results] if results is not None else []
return result_list
@app.post(
"/teams/new",
status_code=status.HTTP_200_OK,
tags=["teams"],
response_description="The registered team.",
response_model=TeamOut,
)
async def create_team(team: TeamIn):
"""
Register a new team.
Example curl command:
```bash
curl -X POST -H "accept: application/json" -H "Content-Type: application/json" \
-d '{"name":"TESTING", "token":"1234", "number_runs":1}' localhost:8000/teams/new
```
"""
query = """
INSERT INTO teams(name, token, number_runs, extra_info)
VALUES (:name, :token, :number_runs, :extra_info)
"""
values = team.dict()
try:
await database.execute(query=query, values=values)
except sqlite3.IntegrityError as e:
print(e)
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=f"The team {team} is already in the database.",
)
else:
# If the team creation is successful, initialize the run status.
# For that, obtain the id of the tasks and the id of the team.
query = """SELECT task_id FROM tasks"""
results = await database.fetch_all(query=query)
task_id_list = [i["task_id"] for i in results]
query = """SELECT * FROM teams WHERE token=:token"""
result = await database.fetch_one(query=query, values={"token": team.token})
team_out = TeamOut(**result)
team_id = result["team_id"]
for task_id in task_id_list:
# Initialize the current_post_number for each run of the team to -1.
query = """
INSERT INTO runs_status(team_id, task_id, current_post_number, has_finished)
VALUES (:team_id, :task_id, :current_post_number, :has_finished)
"""
values = {
"team_id": team_id,
"task_id": task_id,
"current_post_number": -1,
"has_finished": 0,
}
await database.execute(query=query, values=values)
return team_out
@app.get(
"/teams/{token}",
status_code=status.HTTP_200_OK,
tags=["teams"],
response_description="The information of the team.",
response_model=TeamOut,
)
async def get_team(token: str):
"""
Get the information of the team with given token.
Example curl command:
```bash
curl -X GET "localhost:8000/teams/777"
```
"""
query = """SELECT * FROM teams WHERE token=:token"""
result = await database.fetch_one(query=query, values={"token": token})
if result is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"The team with token {token} is not in the database.",
)
else:
return TeamOut(**result)
@app.get(
"/{task}/getwritings/{token}",
status_code=status.HTTP_200_OK,
tags=["challenge"],
response_description="The current users writings for the team.",
response_model=List[UsersWritings],
)
async def get_writings(task: TaskName, token: str):
"""
Get the current users writings for the given task and team.
For this, first get the task_id of the task.
Then, validate the team token. In case it is correct, get the team_id.
Get the current number of posts that the team_id needs for task_id.
Check if the teams has sent the response for the previous time step.
Get the users posts.
Update the runs_status table with the new current post number
Finally, return the list of users posts. In case there is no users with that
number of posts, the endpoint returns an empty list.
Example curl commands:
```bash
curl -X GET "localhost:8000/gambling/getwritings/777"
```
"""
start_timestamp = datetime.datetime.now().timestamp()
# Get the task_id.
task_id = await get_task_id(task)
# Get the team_id and number of runs.
team_id, _, number_runs = await get_team_information(token)
# Get the current number of post.
query = """SELECT current_post_number FROM runs_status WHERE team_id=:team_id AND task_id=:task_id"""
result = await database.fetch_one(
query=query, values={"team_id": team_id, "task_id": task_id}
)
# Since, when a team is created the status of the runs is updated, every
# team should have this information. If not, it indicates that the
# database was modified outside of the system.
if result is None:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=f"The tuple team_id and task_id ({team_id}, "
f"{task_id}) has no run information. This "
"means that the database was altered outside"
"this program.",
)
current_post_number = result["current_post_number"]
writings = WRITINGS[task.value]
# If the current post number is equal to the number of writings for the task, it means that the team has
# ended processing the input.
if current_post_number == len(writings):
print(f"The team {team_id} has ended processing the writings for {task.value}.")
return []
is_last_response_complete = True
# Check if the team has sent the last responses before giving a new one.
if current_post_number != -1:
query = """
SELECT run_id
FROM responses
WHERE team_id=:team_id AND
task_id=:task_id AND
current_post_number=:current_post_number
"""
values = {
"team_id": team_id,
"task_id": task_id,
"current_post_number": current_post_number,
}
results = await database.fetch_all(query=query, values=values)
# When fetch_all is empty the result is not None, instead it is an empty list.
# It isn't necessary to check if results is None.
if len(results) != number_runs:
is_last_response_complete = False
new_post_number = (
current_post_number + 1 if is_last_response_complete else current_post_number
)
if new_post_number < len(writings):
response = writings[new_post_number]
else:
response = []
# Update the current_post_number value for the (team_id, task_id) if a new set of writings was given.
if is_last_response_complete:
# If the team just ended processing all the writings, set a flag in the database.
just_finished = int(new_post_number == len(writings))
if just_finished:
print(
f"The team {team_id} has just ended processing the writings for {task.value}."
)
else:
print(
f"A new set of writings was given to team {team_id} for {task.value}."
)
# Insert the time of the request in the database.
end_timestamp = datetime.datetime.now().timestamp()
query = """
INSERT INTO get_writings_requests(
team_id, task_id, current_post_number, request_time
)
VALUES (:team_id, :task_id, :current_post_number, :request_time)
"""
values = {
"team_id": team_id,
"task_id": task_id,
"current_post_number": new_post_number,
"request_time": end_timestamp,
}
await database.execute(query=query, values=values)
# Save the time it took the server to process the request.
query = """
INSERT INTO get_writings_server_times(
team_id, task_id, current_post_number, start_time, elapsed_time
)
VALUES (:team_id, :task_id, :current_post_number, :start_time, :elapsed_time)
"""
values = {
"team_id": team_id,
"task_id": task_id,
"current_post_number": new_post_number,
"start_time": start_timestamp,
"elapsed_time": end_timestamp - start_timestamp,
}
await database.execute(query=query, values=values)
query = """
UPDATE runs_status
SET current_post_number=:current_post_number, has_finished=:has_finished
WHERE team_id=:team_id AND task_id=:task_id;
"""
values = {
"team_id": team_id,
"task_id": task_id,
"current_post_number": new_post_number,
"has_finished": just_finished,
}
await database.execute(query=query, values=values)
else:
print(
"No new data was retrieved since the last run from team "
f"{team_id} on task {task.value} wasn't completed."
)
return response
@app.get(
"/calculate_results/{task}/{token}",
status_code=status.HTTP_200_OK,
tags=["results"],
response_description="Calculate the performance results for a team.",
)
async def calculate_results(task: TaskName, token: str):
"""
Calculate the performance results for a team.
Example curl commands:
```bash
curl -X GET "localhost:8000/calculate_results/gambling/777"
```
"""
global SUBJECTS, MEDIAN_NUMBER_POSTS
subjects = SUBJECTS[task.value]
# Not used since the penalty value is hardcoded.
# median_number_post = MEDIAN_NUMBER_POSTS[task.value]
# Get the task_id.
task_id = await get_task_id(task)
# Get the team_id and number of runs.
team_id, _, number_runs = await get_team_information(token)
# Check if the team has ended processing the input.
query = """
SELECT has_finished
FROM runs_status
WHERE team_id=:team_id AND
task_id=:task_id
"""
result = await database.fetch_one(
query=query, values={"team_id": team_id, "task_id": task_id}
)
has_finished = result["has_finished"]
if not has_finished:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"The team {team_id} has not finished processing all the input for "
f"{task.value}.",
)
for i in range(number_runs):
internal_run_id = i + 1
query = """
SELECT json_response, current_post_number
FROM responses
WHERE team_id=:team_id AND
task_id=:task_id AND
run_id=:run_id
"""
values = {
"team_id": team_id,
"task_id": task_id,
"run_id": internal_run_id,
}
subjects_predictions = {}
async for row in database.iterate(query=query, values=values):
encoded_json_response = row["json_response"]
json_response = decode_bytes_response(encoded_json_response)
current_post_number = row["current_post_number"]
# Since the API externally starts counting from 1, sum one.
current_post_number = current_post_number + 1
for response_data in json_response:
if response_data.nick not in subjects_predictions:
# Initialize the subject label as negative.
subjects_predictions[response_data.nick] = {
"label": 0,
}
# When the user is first classified as positive, set the corresponding label and delay.
if (response_data.decision == 1) and (
subjects_predictions[response_data.nick]["label"] == 0
):
subjects_predictions[response_data.nick]["label"] = 1
subjects_predictions[response_data.nick][
"delay"
] = current_post_number
# If the user has not been label as positive and her posts are finished,
# set the corresponding delay.
if (subjects_predictions[response_data.nick]["label"] == 0) and (
subjects[response_data.nick]["num_posts"] == current_post_number
):
subjects_predictions[response_data.nick]["label"] = 0
subjects_predictions[response_data.nick][
"delay"
] = current_post_number
if current_post_number in config.chosen_delays_for_ranking:
subjects_predictions[response_data.nick][
f"score_{current_post_number}"
] = response_data.score
predictions = []
true_labels = []
delays = []
scores_dict = {f"score_{j}": [] for j in config.chosen_delays_for_ranking}
for nick in subjects.keys():
predictions.append(subjects_predictions[nick]["label"])
true_labels.append(subjects[nick]["label"])
delays.append(subjects_predictions[nick]["delay"])
for j in config.chosen_delays_for_ranking:
scores_dict[f"score_{j}"].append(
subjects_predictions[nick][f"score_{j}"]
)
precision, recall, f1_score, _ = precision_recall_fscore_support(
y_true=true_labels, y_pred=predictions, average="weighted"
)
(
positive_precision,
positive_recall,
positive_f1_score,
_,
) = precision_recall_fscore_support(
y_true=true_labels, y_pred=predictions, average="binary"
)
precision_at_10 = [
precision_at_k(scores=scores_dict[f"score_{j}"], y_true=true_labels, k=10)
for j in config.chosen_delays_for_ranking
]
ndcg_10 = [
ndcg(scores=scores_dict[f"score_{j}"], y_true=true_labels, p=10)
for j in config.chosen_delays_for_ranking
]
ndcg_100 = [
ndcg(scores=scores_dict[f"score_{j}"], y_true=true_labels, p=100)
for j in config.chosen_delays_for_ranking
]
c_fp = sum(true_labels) / len(true_labels)
erde_5 = erde_final(
labels_list=predictions,
true_labels_list=true_labels,
delay_list=delays,
c_fp=c_fp,
o=5,
)
erde_50 = erde_final(
labels_list=predictions,
true_labels_list=true_labels,
delay_list=delays,
c_fp=c_fp,
o=50,
)
# p = value_p(k=median_number_post)
# Penalty value obtained from the paper eRisk 2022 overview.
p = 0.0078
f_latency_result = f_latency(
labels=predictions, true_labels=true_labels, delays=delays, penalty=p
)
# Insert the results in the database.
query = (
"""
INSERT INTO results(team_id, task_id, run_id, precision, recall, f1_score, positive_precision,
positive_recall, positive_f1_score, erde_5, erde_50, f_latency"""
+ "".join(
[
f", precision_at_10_{i}, ndcg_at_10_{i}, ndcg_at_100_{i}"
for i in config.chosen_delays_for_ranking
]
)
+ """)
VALUES (:team_id, :task_id, :run_id, :precision, :recall, :f1_score, :positive_precision,
:positive_recall, :positive_f1_score, :erde_5, :erde_50, :f_latency"""
+ "".join(
[
f", :precision_at_10_{i}, :ndcg_at_10_{i}, :ndcg_at_100_{i}"
for i in config.chosen_delays_for_ranking
]
)
+ ")"
)
values = {
"team_id": team_id,
"task_id": task_id,
"run_id": internal_run_id,
"precision": precision,
"recall": recall,
"f1_score": f1_score,
"positive_precision": positive_precision,
"positive_recall": positive_recall,
"positive_f1_score": positive_f1_score,
"erde_5": erde_5,
"erde_50": erde_50,
"f_latency": f_latency_result,
}
for j, delay in enumerate(config.chosen_delays_for_ranking):
values[f"precision_at_10_{delay}"] = precision_at_10[j]
values[f"ndcg_at_10_{delay}"] = ndcg_10[j]
values[f"ndcg_at_100_{delay}"] = ndcg_100[j]
await database.execute(query=query, values=values)
return {"message": "The function `calculate_results` ended successfully."}
@app.get(
"/results/{task}/all",
tags=["results"],
response_description="The results of all finished experiments.",
response_model=List[ExperimentResult],
)
async def get_all_results(task: TaskName):
"""
Get the list of all the results for the given task.
Example curl commands:
```bash
curl -X GET "localhost:8000/results/gambling/all"
```
"""
# Get the task_id.
task_id = await get_task_id(task)
query = """SELECT * FROM results WHERE task_id=:task_id"""
results = await database.fetch_all(query=query, values={"task_id": task_id})
result_list = [ExperimentResult(**r) for r in results]
return result_list
@app.get(
"/results/{task}/{token}",
status_code=status.HTTP_200_OK,
tags=["results"],
response_description="Team's results.",
response_model=List[ExperimentResult],
)
async def get_team_results(task: TaskName, token: str):
"""
Get the list of results for the given team and task.
Example curl commands:
```bash
curl -X GET "localhost:8000/results/gambling/1234"
```
"""
# Get the task_id.
task_id = await get_task_id(task)
# Get the team_id and number of runs.
team_id, _, number_runs = await get_team_information(token)
query = """SELECT * FROM results WHERE team_id=:team_id AND task_id=:task_id"""
results = await database.fetch_all(
query=query, values={"team_id": team_id, "task_id": task_id}
)
# When fetch_all is empty the result is not None, instead it is an empty list.
if results == []:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"The team with token '{token}' has not yet finished processing the input.",
)
result_list = [ExperimentResult(**r) for r in results]
assert len(result_list) == number_runs
if len(result_list) != number_runs:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=f"The team with token '{token}' has results for some of its runs. This means that "
"the database was modified outside this program.",
)
return result_list
def encode_response_as_bytes(response: List[ResponseData]):
"""Encode team response as bytes."""
r = [data.dict() for data in response]
return json.dumps(r).encode("utf-8")
def decode_bytes_response(encoded_response: bytes):
"""Decode team response as a list of ResponseData."""
r = json.loads(encoded_response)
response = [ResponseData(**data) for data in r]
return response
def check_if_response_complete(response: List[ResponseData], task: TaskName):
"""Check if the response has an entry for every user for the task."""
subjects = SUBJECTS[task.value]
number_subjects_in_response = 0
subjects_already_counted = []
for r in response:
r = r.dict()
nick = r["nick"]
if nick in subjects:
if nick not in subjects_already_counted:
number_subjects_in_response += 1
subjects_already_counted.append(nick)
else:
print(
f'The response has multiple entries for nick "{nick}" in {task.value}.'
)
else:
print(
f'The nick "{nick}" does not correspond to a subject in {task.value}.'
)
return number_subjects_in_response == len(subjects)
@app.post(
"/{task}/submit/{token}/{run_id}",
status_code=status.HTTP_200_OK,
tags=["challenge"],
response_description="Run responses.",
response_model=List[ResponseData],
)
async def post_response(
task: TaskName, token: str, run_id: int, response: List[ResponseData]
):
"""
Post the response of the team and run for the selected task.