-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
2268 lines (1977 loc) · 93.7 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
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
import argparse
import json
import logging
import logging.handlers
import multiprocessing
import os
import pprint
import queue
import random
import re
import string
import time
from copy import deepcopy
from itertools import chain
from sys import exit
from datetime import datetime, timedelta
from http import HTTPStatus
from secrets import token_urlsafe
from typing import List, Union, Tuple, Dict, Any, Optional
import google.api_core.exceptions
import jsonschema.exceptions
import pymongo.errors
import werkzeug.datastructures
from firebase_admin import auth
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from fuzzywuzzy import fuzz
import bson.json_util
from flask import Flask, request, render_template, send_file, make_response
from flask_cors import CORS
from openapi_schema_validator import validate
from pymongo import UpdateOne
from werkzeug.exceptions import abort
import rec_processing
import sv_util
from sv_api import QuizzrAPISpec
from tpm import QuizzrTPM
from sv_errors import UsernameTakenError, ProfileNotFoundError, MalformedProfileError
logging.basicConfig(level=os.environ.get("QUIZZR_LOG") or "INFO")
DEV_ENV_NAME = "development"
PROD_ENV_NAME = "production"
TEST_ENV_NAME = "testing"
# TODO: Re-implement QuizzrWatcher through the Celery framework for Flask.
def create_app(test_overrides: dict = None, test_inst_path: str = None, test_storage_root: str = None):
"""
App factory function for the data flow server
:param test_overrides: A set of overrides to merge on top of the server's configuration
:param test_inst_path: The instance path of the server. Has the highest overriding priority
:param test_storage_root: The root directory to use in place of the "storage" directory
:return: The data flow server as a Flask app
"""
app_attributes = {}
instance_path = test_inst_path or os.environ.get("Q_INST_PATH")\
or os.path.expanduser(os.path.join("~", "quizzr_server"))
app = Flask(
__name__,
instance_relative_config=True,
instance_path=instance_path
)
storage_root = test_storage_root or os.environ.get("Q_STG_ROOT") or os.path.join(app.instance_path, "storage")
log_dir = os.path.join(storage_root, "logs")
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_path = os.path.join(log_dir, "sv_log.log")
handler = logging.handlers.TimedRotatingFileHandler(log_path, when='h', interval=12, backupCount=13)
formatter = logging.Formatter("[%(asctime)s] %(levelname)s - %(name)s: %(message)s")
handler.setFormatter(formatter)
app.logger.addHandler(handler)
app.logger.info(f"Instantiated server with instance path '{instance_path}'")
CORS(app)
app.logger.info("Creating instance directory...")
server_dir = os.path.dirname(__file__)
os.makedirs(app.instance_path, exist_ok=True)
app.logger.info("Created instance directory")
app.logger.info("Configuring server instance...")
default_config = {
"UNPROC_FIND_LIMIT": 32,
"DATABASE": "QuizzrDatabase",
"BLOB_ROOT": "production",
# "BLOB_NAME_LENGTH": 32,
"Q_ENV": PROD_ENV_NAME,
"SUBMISSION_FILE_TYPES": ["wav", "json", "vtt"],
# "DIFFICULTY_LIMITS": [3, 6, None],
"DIFFICULTY_DIST": [0.6, 0.3, 0.1],
"VERSION": "0.2.0",
"MIN_ANSWER_SIMILARITY": 50,
"PROC_CONFIG": {
"checkUnk": True,
"unkToken": "<unk>",
"minAccuracy": 0.5,
"queueLimit": 32,
"timeout": 60
},
"DEV_UID": "dev",
"LOG_PRIVATE_DATA": False,
"VISIBILITY_CONFIGS": {
"basic": {
"projection": {"pfp": 1, "username": 1, "usernameSpecs": 1},
"collection": "Users"
},
"public": {
"projection": {"pfp": 1, "username": 1, "usernameSpecs": 1},
"collection": "Users"
},
"private": {
"projection": None,
"collection": "Users"
}
},
"USE_ID_TOKENS": True,
"MAX_LEADERBOARD_SIZE": 200,
"DEFAULT_LEADERBOARD_SIZE": 10,
"MAX_USERNAME_LENGTH": 16,
"USERNAME_CHAR_SET": string.ascii_letters + string.digits,
"DEFAULT_RATE_LIMITS": []
}
config_dir = os.path.join(app.instance_path, "config")
if not os.path.exists(config_dir):
os.mkdir(config_dir)
conf_name = os.environ.get("Q_CONFIG_NAME") or "sv_config.json"
app.logger.info(f"Using config with name '{conf_name}'")
conf_path = os.path.join(config_dir, conf_name)
app_conf = default_config
if os.path.exists(conf_path):
with open(conf_path, "r") as config_f:
config = json.load(config_f)
app_conf.update(config)
else:
app.logger.info(f"Config at path '{conf_path}' not found")
# env_cfg = {}
#
# for key in app_conf:
# # if type(app_conf[var]) is not str and var in os.environ:
# # app.logger.critical(f"Cannot override non-string config field '{var}' through environment variable")
# # exit(1)
# env_key = "DF_CFG_" + key
# if env_key in os.environ:
# env_cfg_val = os.environ.get(env_key)
# if env_cfg_val:
# try:
# env_cfg[key] = json.loads(env_cfg_val)
# except json.decoder.JSONDecodeError:
# env_cfg[key] = env_cfg_val
# app_conf.update(env_cfg)
if test_overrides:
app_conf.update(test_overrides)
rec_dir = os.path.join(storage_root, "recordings")
if not os.path.exists(rec_dir):
os.makedirs(rec_dir)
queue_dir = os.path.join(rec_dir, "queue")
error_dir = os.path.join(rec_dir, "_error")
secret_dir = os.path.join(app.instance_path, "secrets")
if not os.path.exists(secret_dir):
os.makedirs(secret_dir)
app_conf["REC_DIR"] = rec_dir
api = QuizzrAPISpec(os.path.join(server_dir, "reference", "backend.yaml"))
app.config.from_mapping(app_conf)
# Validate configuration values
if app.config["DEFAULT_LEADERBOARD_SIZE"] > app.config["MAX_LEADERBOARD_SIZE"]:
app.logger.critical("Configured default leaderboard size must not exceed maximum leaderboard size.")
exit(1)
for percentage in app.config["DIFFICULTY_DIST"]:
if not (0 <= percentage <= 1):
app.logger.critical("Configured DIFFICULTY_DIST percentages must be between 0 and 1.")
exit(1)
app.logger.info("Finished configuring server instance")
app.logger.info("Initializing third-party services...")
app.logger.info(f"MongoDB Database Name = '{app_conf['DATABASE']}'")
app.logger.info(f"Firebase Blob Root = '{app_conf['BLOB_ROOT']}'")
app.logger.info(f"Environment set to '{app_conf['Q_ENV']}'")
qtpm = QuizzrTPM(app_conf["DATABASE"], app_conf, os.path.join(secret_dir, "firebase_storage_key.json"),
app.logger.getChild("qtpm"))
app.logger.info("Initialized third-party services")
app.logger.debug("Instantiating process...")
prescreen_results_queue = multiprocessing.Queue()
qw_process = multiprocessing.Process(target=rec_processing.start_watcher, kwargs={
"db_name": app_conf["DATABASE"],
"tpm_config": app_conf,
"firebase_app_specifier": qtpm.app,
"rec_dir": rec_dir,
"queue_dir": queue_dir,
"error_dir": error_dir,
"proc_config": app_conf["PROC_CONFIG"],
"submission_file_types": app_conf["SUBMISSION_FILE_TYPES"],
"queue": prescreen_results_queue,
"logger": app.logger.getChild("prescreen")
})
qw_process.daemon = True
app.logger.debug("Finished instantiating process")
app.logger.debug("Starting process...")
app_attributes["qwStartTime"] = time.time()
qw_process.start()
app_attributes["qwPid"] = qw_process.pid
app.logger.debug(f"qwPid = {app_attributes['qwPid']}")
app.logger.info("Started pre-screening program")
rate_limits = app.config["DEFAULT_RATE_LIMITS"]
if rate_limits:
app.logger.info("Initializing rate limiter...")
limiter = Limiter(app, key_func=get_remote_address, default_limits=rate_limits)
app.logger.info("Finished initializing rate limiter")
else:
app.logger.info("No default rate limits defined. Skipping rate limiter initialization")
secret_keys = {}
prescreen_statuses = []
pprinter = pprint.PrettyPrinter()
app.logger.info("Completed initialization")
@app.route("/audio", methods=["GET", "POST", "PATCH"])
def audio_resource():
"""
GET: Get a batch of at most ``UNPROC_FIND_LIMIT`` documents from the UnprocessedAudio collection in the MongoDB
Atlas.
POST: Submit one or more recordings for pre-screening and upload them to the database if they all pass. The
arguments for each recording correspond to an index. If providing any values for an argument, represent empty
arguments with an empty string.
PATCH: Attach the given arguments to multiple unprocessed audio documents and move them to the Audio collection.
Additionally, update the recording history of the associated questions and users.
"""
if request.method == "GET":
return get_unprocessed_audio()
elif request.method == "POST":
decoded = _verify_id_token()
user_id = decoded['uid']
recordings = request.files.getlist("audio")
qb_ids = request.form.getlist("qb_id")
sentence_ids = request.form.getlist("sentenceId")
diarization_metadata_list = request.form.getlist("diarMetadata")
rec_types = request.form.getlist("recType")
expected_answers = request.form.getlist("expectedAnswer")
transcripts = request.form.getlist("transcript")
correct_flags = request.form.getlist("correct")
_debug_variable("recordings", recordings)
_debug_variable("qb_ids", qb_ids)
_debug_variable("sentence_ids", sentence_ids)
_debug_variable("diarization_metadata_list", diarization_metadata_list)
_debug_variable("rec_types", rec_types)
_debug_variable("expected_answers", expected_answers)
_debug_variable("transcripts", transcripts)
_debug_variable("correct_flags", correct_flags)
if not (len(recordings) == len(rec_types)
and (not qb_ids or len(recordings) == len(qb_ids))
and (not sentence_ids or len(recordings) == len(sentence_ids))
and (not diarization_metadata_list or len(recordings) == len(diarization_metadata_list))
and (not expected_answers or len(recordings) == len(expected_answers))
and (not transcripts or len(recordings) == len(transcripts))
and (not correct_flags or len(recordings) == len(correct_flags))):
return _make_err_response(
"Received incomplete form batch",
"incomplete_batch",
HTTPStatus.BAD_REQUEST,
log_msg=True
)
return pre_screen(recordings, rec_types, user_id, qb_ids, sentence_ids, diarization_metadata_list,
expected_answers, transcripts, correct_flags)
elif request.method == "PATCH":
arguments_batch = request.get_json()
return handle_processing_results(arguments_batch)
def get_unprocessed_audio():
"""
Get a batch of at most ``UNPROC_FIND_LIMIT`` documents from the UnprocessedAudio collection in the MongoDB
Atlas.
:return: A dictionary containing an array of dictionaries under the key "results"
"""
max_docs = app.config["UNPROC_FIND_LIMIT"]
errs = []
results_projection = ["_id", "diarMetadata"] # In addition to the transcript
app.logger.info(f"Finding a batch ({max_docs} max) of unprocessed audio documents...")
audio_cursor = qtpm.unproc_audio.find(limit=max_docs)
id2entries = {}
qids = []
audio_doc_count = 0
for audio_doc in audio_cursor:
_debug_variable("audio_doc", audio_doc)
qid = audio_doc.get("qb_id")
sentence_id = audio_doc.get("sentenceId")
if qid is None:
app.logger.warning("Audio document does not contain question ID")
errs.append(("internal_error", "undefined_qb_id"))
continue
id_key = "_".join([str(qid), str(sentence_id)]) if sentence_id else str(qid)
if id_key not in id2entries:
id2entries[id_key] = []
entry = {}
for field in results_projection:
if field in audio_doc:
entry[field] = audio_doc[field]
if "tokenizationId" in audio_doc:
entry["tokenizationId"] = audio_doc["tokenizationId"]
id2entries[id_key].append(entry)
qids.append(qid)
audio_doc_count += 1
if audio_doc_count == 0:
app.logger.error("Could not find any audio documents")
return _make_err_response(
"Could not find any audio documents",
"empty_unproc_audio",
HTTPStatus.NOT_FOUND
)
_debug_variable("id2entries", id2entries)
app.logger.info(f"Found {audio_doc_count} unprocessed audio document(s)")
if not qids:
app.logger.error("No audio documents contain question IDs")
return _make_err_response(
"No audio documents contain question IDs",
"empty_qid2entries",
HTTPStatus.NOT_FOUND
)
question_gen = qtpm.find_questions(qids)
for question in question_gen:
_debug_variable("question", question)
qid = question["qb_id"]
sentence_id = question.get("sentenceId")
id_key = "_".join([str(qid), str(sentence_id)]) if sentence_id else str(qid)
orig_transcript = question.get("transcript")
if orig_transcript:
entries = id2entries[id_key]
for entry in entries:
if "tokenizations" in question and "tokenizationId" in entry:
slice_start, slice_end = question["tokenizations"][entry.pop("tokenizationId")]
transcript = orig_transcript[slice_start:slice_end]
else:
transcript = orig_transcript
entry["transcript"] = transcript
_debug_variable("id2entries", id2entries)
results = []
for entries in id2entries.values():
results += entries
app.logger.debug(f"Final Results: {results!r}")
response = {"results": results}
if errs:
response["errors"] = [{"type": err[0], "reason": err[1]} for err in errs]
return response
def pre_screen(recordings: List[werkzeug.datastructures.FileStorage],
rec_types: List[str],
user_id: str,
qb_ids: List[Union[int, str]] = None,
sentence_ids: List[Union[int, str]] = None,
diarization_metadata_list: List[str] = None,
expected_answers: List[str] = None,
transcripts: List[str] = None,
correct_flags: List[str] = None) -> Tuple[Union[dict, str], int]:
"""
Submit one or more recordings for pre-screening and uploading.
WARNING: Submitting recordings of different ``rec_types`` in the same batch can give unpredictable results.
:param recordings: A list of audio files
:param rec_types: A list of rec_types associated with each recording
:param user_id: The ID of the submitter
:param qb_ids: (optional) A list of question IDs associated with each recording
:param sentence_ids: (optional) The associated sentence IDs. Only required for segmented questions
:param diarization_metadata_list: (optional) The associated parameter sets for diarization
:param expected_answers: (optional) A list of the associated expected answers (for "answer" recordings)
:param transcripts: (optional) A list of the associated output transcripts (for "answer" recordings)
:param correct_flags: (optional) Whether each "answer" recording contains the correct answer
:return: A dictionary with the key "prescreenPointers" and a status code. If an error occurred, a string with a
status code is returned instead.
"""
valid_rec_types = ["normal", "buzz", "answer"]
pointers = []
submissions = []
for i in range(len(recordings)):
recording = recordings[i]
rec_type = rec_types[i]
qb_id = qb_ids[i] if len(qb_ids) > i else None
sentence_id = sentence_ids[i] if len(sentence_ids) > i else None
diarization_metadata = diarization_metadata_list[i] if len(diarization_metadata_list) > i else None
expected_answer = expected_answers[i] if len(expected_answers) > i else None
transcript = transcripts[i] if len(transcripts) > i else None
correct = correct_flags[i] if len(correct_flags) > i else None
_debug_variable("qb_id", qb_id)
_debug_variable("sentence_id", sentence_id)
_debug_variable("diarization_metadata", diarization_metadata)
_debug_variable("rec_type", rec_type)
_debug_variable("expected_answer", expected_answer)
_debug_variable("transcript", transcript)
_debug_variable("correct", correct)
if not recording:
return _make_err_response(
"Argument 'audio' is undefined",
"undefined_arg",
HTTPStatus.BAD_REQUEST,
["audio"],
True
)
if not rec_type:
return _make_err_response(
"Argument 'recType' is undefined",
"undefined_arg",
HTTPStatus.BAD_REQUEST,
["recType"],
True
)
elif rec_type not in valid_rec_types:
return _make_err_response(
f"Invalid rec type: '{rec_type!r}'",
"invalid_arg",
HTTPStatus.BAD_REQUEST,
["invalid_recType"],
True
)
qid_required = rec_type not in ["buzz", "answer"]
if qid_required and not qb_id:
return _make_err_response(
"Form argument 'qb_id' expected",
"undefined_arg",
HTTPStatus.BAD_REQUEST,
["qb_id"],
True
)
_debug_variable("user_id", user_id)
metadata = {
"recType": rec_type,
"userId": user_id
}
if diarization_metadata:
metadata["diarMetadata"] = diarization_metadata
if qb_id:
metadata["qb_id"] = int(qb_id)
if sentence_id:
metadata["sentenceId"] = int(sentence_id)
elif rec_type == "normal" and len(recordings) > 1:
app.logger.debug("Field 'sentenceId' not specified in batch submission")
metadata["tokenizationId"] = i
if expected_answer:
metadata["expectedAnswer"] = expected_answer
if transcript:
metadata["transcript"] = transcript
if correct:
metadata["correct"] = correct.lower() == "true"
submissions.append((recording, metadata))
if len(submissions) == 1:
submission_names = [_save_recording(queue_dir, *submissions[0])]
else:
submission_names = _save_recording_batch(queue_dir, submissions)
for submission_name in submission_names:
_debug_variable("submission_name", submission_name)
pointer = token_urlsafe(64)
expiry = datetime.now() + timedelta(minutes=30)
ps_doc = {"pointer": pointer, "name": submission_name, "status": "running", "expiry": expiry}
prescreen_statuses.append(ps_doc)
pointers.append(pointer)
return {"prescreenPointers": pointers}, HTTPStatus.ACCEPTED
# try:
# results = qp.pick_submissions(
# rec_processing.QuizzrWatcher.queue_submissions(
# app.config["REC_DIR"],
# size_limit=app.config["PROC_CONFIG"]["queueLimit"]
# )
# )
# except BrokenPipeError as e:
# app.logger.error(f"Encountered BrokenPipeError: {e}. Aborting")
# return "broken_pipe_error", HTTPStatus.INTERNAL_SERVER_ERROR
#
# # Split by recType
# app.logger.info("Preparing results for upload...")
# file_paths = {}
# for submission in results:
# file_path = os.path.join(app.config["REC_DIR"], submission) + ".wav"
# if results[submission]["case"] == "accepted":
# sub_rec_type = results[submission]["metadata"]["recType"]
# if sub_rec_type not in file_paths:
# file_paths[sub_rec_type] = []
# file_paths[sub_rec_type].append(file_path)
#
# _debug_variable("file_paths", file_paths)
#
# # Upload files
# try:
# file2blob = {}
# for rt, paths in file_paths.items(): # Organize by recType
# file2blob.update(qtpm.upload_many(paths, rt))
# except BrokenPipeError as e:
# app.logger.error(f"Encountered BrokenPipeError: {e}. Aborting")
# return "broken_pipe_error", HTTPStatus.INTERNAL_SERVER_ERROR
#
# _debug_variable("file2blob", file2blob)
#
# # sub2blob = {os.path.splitext(file)[0]: file2blob[file] for file in file2blob}
# sub2meta = {}
# sub2vtt = {}
#
# for submission in results:
# doc = results[submission]
# if doc["case"] == "accepted":
# sub2meta[submission] = doc["metadata"]
# if "vtt" in doc:
# sub2vtt[submission] = doc.get("vtt")
#
# # Upload submission metadata to MongoDB
# qtpm.mongodb_insert_submissions(
# sub2blob={os.path.splitext(file)[0]: file2blob[file] for file in file2blob},
# sub2meta=sub2meta,
# sub2vtt=sub2vtt
# )
#
# app.logger.info("Evaluating outcome of pre-screen...")
#
# for submission in results:
# app.logger.info(f"Removing submission with name '{submission}'")
# rec_processing.delete_submission(app.config["REC_DIR"], submission, app.config["SUBMISSION_FILE_TYPES"])
#
# for submission_name in submission_names:
# if results[submission_name]["case"] == "rejected":
# return {"prescreenSuccessful": False}, HTTPStatus.ACCEPTED
#
# if results[submission_name]["case"] == "err":
# return results[submission_name]["err"], HTTPStatus.INTERNAL_SERVER_ERROR
#
# return {"prescreenSuccessful": True}, HTTPStatus.ACCEPTED
def handle_processing_results(arguments_batch: Dict[str, List[Dict[str, Any]]]):
"""
Attach the given arguments to multiple unprocessed audio documents and move them to the Audio collection.
Additionally, update the recording history of the associated questions and users.
:param arguments_batch: A list of documents each containing the fields to update along with the ID of the
document to update
:return: The number of update documents received, the number of successful updates, and the errors that
occurred, all in one dictionary
"""
arguments_list = arguments_batch.get("arguments")
if arguments_list is None:
return _make_err_response(
"Argument 'arguments' is undefined",
"undefined_arg",
HTTPStatus.BAD_REQUEST,
["arguments"],
True
)
app.logger.info(f"Updating data related to {len(arguments_list)} audio documents...")
errors = []
success_count = 0
for arguments in arguments_list:
errs = qtpm.update_processed_audio(arguments)
if not errs:
success_count += 1
else:
errors += ({"type": err[0], "reason": err[1]} for err in errs)
results = {"successes": success_count, "total": len(arguments_list)}
if errors:
results["errors"] = errors
app.logger.info(f"Successfully updated data related to {success_count} of {len(arguments_list)} audio documents")
app.logger.info(f"Logged {len(errors)} warning messages")
return results
@app.route("/answer", methods=["GET"])
def check_answer():
"""Check if an answer is correct using approximate string matching."""
qid = request.args.get("qid")
user_answer = request.args.get("a")
if qid is None or qid == '':
return _make_err_response(
"Query parameter 'qid' is undefined",
"undefined_arg",
HTTPStatus.BAD_REQUEST,
["qid"],
True
)
if not user_answer:
return _make_err_response(
"Query parameter 'a' is undefined",
"undefined_arg",
HTTPStatus.BAD_REQUEST,
["a"],
True
)
question = qtpm.rec_questions.find_one({"qb_id": int(qid)})
if not question:
return _make_err_response(
"Could not find question",
"question_not_found",
HTTPStatus.NOT_FOUND,
log_msg=True
)
correct_answer = question.get("answer")
if not correct_answer:
return _make_err_response(
"Question does not contain field 'answer'",
"answer_not_found",
HTTPStatus.NOT_FOUND,
log_msg=True
)
answer_similarity = fuzz.token_set_ratio(user_answer, correct_answer)
_debug_variable("answer_similarity", answer_similarity)
return {"correct": answer_similarity >= app.config["MIN_ANSWER_SIMILARITY"]}
@app.route("/answer_full/<int:qid>", methods=["GET"])
def get_answer(qid):
"""Get the answer of a question. This is intended for use by a backend component."""
question = qtpm.rec_questions.find_one({"qb_id": qid})
if not question:
return _make_err_response(
"Could not find question",
"question_not_found",
HTTPStatus.NOT_FOUND,
log_msg=True
)
correct_answer = question.get("answer")
if not correct_answer:
return _make_err_response(
"Question does not contain field 'answer'",
"answer_not_found",
HTTPStatus.NOT_FOUND,
log_msg=True
)
return {"answer": correct_answer}
@app.get("/audio/<path:blob_path>")
def retrieve_audio_file(blob_path):
"""
Retrieve a file from Firebase Storage. The blob path is usually in the format ``<recType>/<_id>``.
:param blob_path: The path to a Firebase Cloud Storage object
:return: A response containing the bytes of the audio file
"""
try:
file = qtpm.get_file_blob(blob_path)
except google.api_core.exceptions.NotFound:
return _make_err_response(
"Audio not found",
"not_found",
HTTPStatus.NOT_FOUND,
[blob_path],
log_msg=True
)
return send_file(file, mimetype="audio/wav")
@app.delete("/audio/<audio_id>")
def delete_audio(audio_id):
"""
Delete an audio recording. If the "batch" query flag is set, delete all audio recordings that have the same
batch UUID as it.
:param audio_id: The audio ID to delete.
:return:
"""
# TODO: MAKE THIS OPERATION SECURE! REQUIRE AUTHENTICATION FROM THE USER WHO IS DELETING THE RECORDING!
audio_doc = qtpm.audio.find_one({"_id": audio_id})
if _query_flag("batch") and "batchUUID" in audio_doc:
cursor = qtpm.audio.find({"batchUUID": audio_doc["batchUUID"]})
for doc in cursor:
try:
_delete_audio(doc)
except google.api_core.exceptions.NotFound:
return _make_err_response(
"Audio not found",
"not_found",
HTTPStatus.NOT_FOUND,
[doc["_id"]], # TODO: Fix inconsistency with "extra"
log_msg=True
)
else:
try:
_delete_audio(audio_doc)
except google.api_core.exceptions.NotFound:
return _make_err_response(
"Audio not found",
"not_found",
HTTPStatus.NOT_FOUND,
[audio_doc["_id"]],
log_msg=True
)
return "", HTTPStatus.OK
def _delete_audio(audio_doc):
"""
Delete the audio document and pull all references to it from the corresponding user and question.
:param audio_doc: The contents of the audio document.
:return:
"""
qtpm.delete_file_blob("/".join([audio_doc["recType"], audio_doc["_id"]]))
qtpm.users.update_one({"_id": audio_doc["userId"]}, {"$pull": {"recordedAudios": {"id": audio_doc["_id"]}}})
qtpm.rec_questions.update_many({"qb_id": audio_doc["qb_id"]}, {"$pull": {"recordings": {"id": audio_doc["_id"]}}})
qtpm.audio.delete_one({"_id": audio_doc["_id"]})
@app.post("/socket/key")
def generate_game_key():
"""
Alias for ``/backend/key`` with the "name" argument being "socket".
**WARNING: A secret key can be generated only once per server session. This key cannot be recovered if lost.**
"""
return _gen_secret_key("socket")
@app.route("/downvote/<audio_id>", methods=["PATCH"])
def downvote(audio_id):
"""Downvote an audio recording."""
args = request.get_json()
uid = args["userId"]
if "userId" not in args:
return _make_err_response(
"Argument 'userId' is undefined",
"undefined_arg",
HTTPStatus.BAD_REQUEST,
log_msg=True
)
user = qtpm.users.find_one({"_id": uid})
rec_votes = user.get("recVotes") or []
has_voted = False
for i, rec_vote in enumerate(rec_votes):
if rec_vote["id"] == audio_id:
has_voted = True
if rec_vote["vote"] == -1: # Avoid downvoting twice.
return '', HTTPStatus.OK
else:
qtpm.users.update_one({"_id": uid}, {"$set": {f"recVotes.{i}.vote": -1}})
qtpm.audio.update_one({"_id": audio_id}, {"$inc": {"upvotes": -1}})
break
if not has_voted:
qtpm.users.update_one({"_id": uid}, {"$push": {"recVotes": {"id": audio_id, "vote": -1}}})
result = qtpm.audio.update_one({"_id": audio_id}, {"$inc": {"downvotes": 1}})
if result.matched_count == 0:
return _make_err_response(
f"Audio document with ID '{audio_id}' not found",
"doc_not_found",
HTTPStatus.NOT_FOUND,
[audio_id],
True
)
return '', HTTPStatus.OK
@app.put("/game_results")
def handle_game_results():
"""
Update the database with the results of a game session.
Precondition: ``session_results["questionStats"]["played"] != 0``
"""
session_results = request.get_json()
_debug_variable("session_results", session_results)
if "category" in session_results:
return handle_game_results_category(session_results)
if "categories" in session_results:
return handle_game_results_categories(session_results)
return _make_err_response(
"Arguments 'category' or 'categories' not provided",
"undefined_args",
HTTPStatus.BAD_REQUEST,
["category_or_categories"],
True
)
@app.get("/game/<game_id>")
def get_game(game_id):
"""Get a game session from MongoDB."""
if not game_id:
return _make_err_response(
"Path parameter not defined",
"undefined_arg",
HTTPStatus.BAD_REQUEST,
["path"],
True
)
session = qtpm.games.find_one({"_id": game_id})
if session is None:
return _make_err_response(
f"Game session with ID '{game_id}' not found",
"resource_not_found",
HTTPStatus.NOT_FOUND,
[game_id],
True
)
return session
@app.post("/game")
def post_game():
"""Upload a game session to MongoDB for users to share."""
arguments = request.get_json()
if arguments is None:
return _make_err_response(
"No arguments specified",
"no_args",
HTTPStatus.BAD_REQUEST,
log_msg=True
)
game_id = arguments.get("id")
session = arguments.get("session")
if not game_id:
return _make_err_response(
"Argument 'id' not defined",
"undefined_arg",
HTTPStatus.BAD_REQUEST,
["id"],
True
)
if not session:
return _make_err_response(
"Argument 'session' not defined",
"undefined_arg",
HTTPStatus.BAD_REQUEST,
["session"],
True
)
if "settings" not in session:
return _make_err_response(
"Session does not contain a 'settings' field",
"undefined_arg",
HTTPStatus.BAD_REQUEST,
["settings"],
True
)
if "players" not in session["settings"]:
return _make_err_response(
"Session settings do not contain a list of players",
"undefined_arg",
HTTPStatus.BAD_REQUEST,
["players"],
True
)
session["_id"] = game_id
try:
qtpm.games.insert_one(session)
except pymongo.errors.DuplicateKeyError:
return _make_err_response(
f"ID for game session {game_id} already occupied",
"id_taken",
HTTPStatus.BAD_REQUEST,
[game_id],
True
)
update_game_histories(session)
return '', HTTPStatus.CREATED
def update_game_histories(session):
"""
Update the "history" field of every player in the "settings" of the given session
:param session: The metadata of a game session. Requires a "settings" field that contains the "players" field,
an array of user IDs.
"""
update_batch = []
for player in session["settings"]["players"]:
update_batch.append(UpdateOne({"_id": player}, {"$push": {"history": session}}))
if len(update_batch) == 0:
return
qtpm.users.bulk_write(update_batch)
def handle_game_results_category(session_results):
"""
Update the database with the results of a game session with only one category.
:param session_results: A dictionary containing the "mode", "category", and the update arguments for each user,
under the key "users"
:return: A dictionary containing the number of "successful" and "requested" updates
"""
mode = session_results["mode"]
category = session_results["category"]
user_results = session_results["users"]
update_batch = []
app.logger.info(f"Processing updates for {len(session_results['users'])} users...")
for username, update_args in user_results.items():
app.logger.info(f"Finding user profile with username '{username}'...")
user_doc = qtpm.users.find_one({"username": username})
if "stats" not in user_doc:
app.logger.debug("Creating stub for field 'stats'...")
user_doc["stats"] = {}
if mode not in user_doc["stats"]:
app.logger.debug(f"Creating stub for mode '{mode}'...")
user_doc["stats"][mode] = {
"questions": {
"played": {"all": 0},
"buzzed": {"all": 0},
"correct": {"all": 0},
"cumulativeProgressOnBuzz": {},
"avgProgressOnBuzz": {}
},
"game": {
"played": {"all": 0},
"won": {"all": 0}
}
}
_debug_variable(f"user.stats.{mode}", user_doc["stats"][mode])
old_question_stats = user_doc["stats"][mode]["questions"]
for field in ["played", "buzzed", "correct"]:
if category not in old_question_stats[field]:
app.logger.debug(f"Set default value for field '{field}', category '{category}'")
old_question_stats[field][category] = 0
old_game_stats = user_doc["stats"][mode]["game"]
for field in ["played", "won"]:
if category not in old_game_stats[field]:
app.logger.debug(f"Set default value for field '{field}', category '{category}'")
old_game_stats[field][category] = 0
question_stats = update_args["questionStats"]
app.logger.info("Retrieving projected results...")
played_all = old_question_stats["played"]["all"] + question_stats["played"]
played_categorical = old_question_stats["played"][category] + question_stats["played"]
buzzed_all = old_question_stats["buzzed"]["all"] + question_stats["buzzed"]
buzzed_categorical = old_question_stats["buzzed"][category] + question_stats["buzzed"]
_debug_variable("total_questions_played", played_all)
_debug_variable("total_buzzes", buzzed_all)
_debug_variable("categorical_questions_played", played_categorical)
_debug_variable("categorical_buzzes", buzzed_categorical)
app.logger.info("Projected results retrieved")
old_c_progress_on_buzz = old_question_stats["cumulativeProgressOnBuzz"]
c_progress_on_buzz = question_stats["cumulativeProgressOnBuzz"]
old_avg_progress_on_buzz = old_question_stats["avgProgressOnBuzz"]
_debug_variable("old_avg_progress_on_buzz", old_avg_progress_on_buzz)
app.logger.info("Calculating derived statistics...")
avg_progress_on_buzz_update = {}