-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
205 lines (165 loc) · 5.56 KB
/
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
from flask import Flask, request, jsonify
from setting import *
from utils import allowed_file
from database import Database, pre_define_db
import evaluators
from inspect import getmembers, isfunction
from werkzeug.utils import secure_filename
import pandas as pd
app = Flask(__name__)
app.secret_key = APP_SECRET_KEY
pre_define_db()
def fetch_leader_board(db: Database, competition_id):
db.query(f"""
select * from leader_board where competition_id = {competition_id} order by error, send_at;
""")
result = db.fetchall()
return [
{'rank': i + 1} | dict(zip(Database.leader_board_cols, res)) for i, res in enumerate(result)
]
@app.route('/')
def home():
return 'welcome'
# create competition
@app.route('/competitions', methods=['POST'])
def create_competition():
body = request.form
if body.get('secret') != COMPETITION_SECRET_KEY:
return jsonify(
success=False,
message='it\'s safe enough :]'
)
evaluators_list = [fun[0] for fun in getmembers(evaluators, isfunction)]
if body.get('evaluator') not in evaluators_list:
return jsonify(
success=False,
message='invalid evaluator passed'
)
if body.get('title') is None or len(body.get('title')) < 1:
return jsonify(
success=False,
message='invalid title'
)
db = Database()
db.query(f"""select * from competitions where title = '{body.get('title')}';""")
if db.fetchone():
return jsonify(
success=False,
message='competition title already exists, please choose another one'
)
file = request.files.get('file')
if 'file' not in request.files or file.filename == '':
return jsonify(
success=False,
message='no file attached'
)
if not allowed_file(file.filename):
return jsonify(
success=False,
message='file ext. is not valid'
)
# TODO: check competition file head columns
# df_evaluation = pd.read_csv(file)
# if 'id' not in df_evaluation.columns or 'value' not in df_evaluation.columns:
# return jsonify(
# success=False,
# message='we need `id` and `value` in file head'
# )
competition_dir = os.path.join(COMPETITION_FOLDER, body.get('title'))
os.mkdir(competition_dir)
file_name = secure_filename(file.filename)
file_path = os.path.join(competition_dir, file_name)
file.save(file_path)
db.query(f"""
insert into competitions(title, evaluation_file_path, evaluator)
values('{body.get('title')}', '{file_path}', '{body.get('evaluator')}');
""")
db.commit()
db.query(f"""select * from competitions where title = '{body.get('title')}';""")
result = db.fetchone()
data = dict(zip(Database.competition_cols, result))
return jsonify(
success=True,
message='competition created successfully',
data=data
)
# competitions list
@app.route('/competitions')
def competition_list():
db = Database()
db.query(f"""select * from competitions;""")
result = db.fetchall()
data = [
dict(zip(Database.competition_cols, res)) for res in result
]
return jsonify(
success=True,
data=data
)
# send an answer to specific competition
@app.route('/competitions/<int:_id>/send-answer', methods=['POST'])
def send_answer(_id):
body = request.form
if body.get('name') is None:
return jsonify(
success=False,
message='we love to know your name :]'
)
db = Database()
db.query(f"""select * from competitions where id = {_id};""")
result = db.fetchone()
if not result:
return jsonify(
success=False,
message='competition not found'
)
competition = dict(zip(Database.competition_cols, result))
evaluator = getattr(evaluators, competition['evaluator'])
file = request.files.get('file')
if 'file' not in request.files or file.filename == '':
return jsonify(
success=False,
message='no file attached'
)
if not allowed_file(file.filename):
return jsonify(
success=False,
message='file ext. is not valid'
)
df_answer = pd.read_csv(file)
if 'id' not in df_answer.columns or 'answer' not in df_answer.columns:
return jsonify(
success=False,
message='we need `id` and `answer` in file head'
)
df_evaluation = pd.read_csv(competition.get('evaluation_file_path'))
df_final = pd.merge(df_evaluation, df_answer, on='id', how='left')
error = evaluator(df_final['value'], df_final['answer'])
db.query(f"""
insert into leader_board(competition_id, name, error)
values({competition.get('id')}, '{body.get('name')}', {error});
""")
db.commit()
db.query(f"""
select count(*) from leader_board where error <= {error};
""")
rank = db.fetchone()
leader_board = fetch_leader_board(db, competition['id'])
return jsonify(
success=True,
message='competition created successfully',
data={
'error': error,
'rank': rank[0],
'all_participants': len(leader_board),
'leader_board': leader_board
}
)
# to retrieve leader board
@app.route('/leader_board/<int:competition_id>')
def retrieve_leader_board(competition_id):
db = Database()
return jsonify(
success=True,
data=fetch_leader_board(db, competition_id)
)