-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver_sqla.py
2489 lines (2124 loc) · 88.3 KB
/
server_sqla.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Annotation Server
Deployment
----------
1. Using Flask-Run
```
$ export FLASK_APP="server:webapp"
$ flask run
```
2. Using gunicorn
```
$ gunicorn -b host:port server:webapp
```
3. Direct (dev only)
```
$ python server.py
```
"""
__author__ = "Hrishikesh Terdalkar"
__copyright__ = "Copyright (C) 2022-2023 Hrishikesh Terdalkar"
__version__ = "0.3.0"
###############################################################################
import os
import re
import csv
import glob
import json
import logging
import datetime
import git
import requests
from flask import (Flask, render_template, redirect, jsonify, url_for,
request, flash, session, Response, abort)
from flask_security import (Security, auth_required, permissions_required,
hash_password, current_user, user_registered,
user_authenticated)
from flask_security.utils import uia_email_mapper
from flask_admin import Admin, helpers as admin_helpers
# from sqlalchemy import or_, and_
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from flask_babelex import Babel
from flask_wtf import CSRFProtect
from flask_mail import Mail
from flask_migrate import Migrate
# from indic_transliteration.sanscript import transliterate
from constants import (
ROLE_OWNER,
ROLE_ADMIN,
ROLE_CURATOR,
ROLE_ANNOTATOR,
ROLE_MEMBER,
ROLE_GUEST,
ROLE_DEFINITIONS,
PERMISSION_VIEW_ACP,
PERMISSION_ANNOTATE,
PERMISSION_CURATE,
PERMISSION_VIEW_UCP,
PERMISSION_VIEW_CORPUS,
# Auto Annotation User
AUTO_ANNOTATION_USER_ID,
AUTO_ANNOTATION_USER_USERNAME,
AUTO_ANNOTATION_USER_EMAIL,
AUTO_ANNOTATION_USER_PASS,
# Task Category Names
TASK_SENTENCE_BOUNDARY,
TASK_WORD_ORDER,
TASK_TOKEN_TEXT_ANNOTATION,
TASK_TOKEN_CLASSIFICATION,
TASK_TOKEN_GRAPH,
TASK_TOKEN_CONNECTION,
TASK_SENTENCE_CLASSIFICATION,
TASK_SENTENCE_GRAPH,
TASK_DEFAULT_INFORMATION,
TASK_UPDATE_ACTIONS,
TASK_ANNOTATION_TEMPLATES, TASK_EXPORT_TEMPLATES,
# File Types
FILE_TYPE_CONLLU,
FILE_TYPE_PLAINTEXT,
FILE_TYPE_JSON,
FILE_TYPE_CSV,
)
from models_sqla import (db, user_datastore, User,
CustomLoginForm,
Corpus, Chapter, Verse, Line, Token,
Task, SubmitLog, WordOrder, Boundary,
TokenTextAnnotation, TokenLabel, TokenClassification,
TokenRelationLabel, TokenGraph,
TokenConnection,
SentenceLabel, SentenceClassification,
SentenceRelationLabel, SentenceGraph)
from models_admin import (SecureAdminIndexView,
UserModelView, TaskModelView,
LabelModelView, AnnotationModelView)
from settings import app
from utils.reverseproxied import ReverseProxied
from utils.database import (
add_chapter,
get_verse_data, get_chapter_data, export_data,
get_annotation_progress, clone_user_annotations
)
from utils.export import format_data
from utils.conllu import CoNLLUParser
from utils.plaintext import PlaintextProcessor
###############################################################################
logging.basicConfig(format='[%(asctime)s] %(name)s %(levelname)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
level=logging.INFO,
handlers=[logging.FileHandler(app.log_file),
logging.StreamHandler()])
###############################################################################
# UIA Mapper
def uia_username_mapper(identity):
pattern = r'^(?!_$)(?![0-9_.])(?!.*[_.]{2})[a-zA-Z0-9_.]+(?<![.])$'
return identity if re.match(pattern, identity) else None
###############################################################################
# Flask Application
webapp = Flask(app.name, static_folder=app.static_dir)
webapp.wsgi_app = ReverseProxied(webapp.wsgi_app)
webapp.url_map.strict_slashes = False
webapp.config['SECRET_KEY'] = app.secret_key
webapp.config['SECURITY_PASSWORD_SALT'] = app.security_password_salt
webapp.config['JSON_AS_ASCII'] = False
webapp.config['JSON_SORT_KEYS'] = False
webapp.config['DEBUG'] = app.debug
# SQLAlchemy Config
webapp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
webapp.config['SQLALCHEMY_DATABASE_URI'] = app.sqla['database_uri']
webapp.config['SQLALCHEMY_ENGINE_OPTIONS'] = {
"pool_pre_ping": True,
}
# Flask-Admin Theme
webapp.config["FLASK_ADMIN_SWATCH"] = "united"
# CSRF Token Expiry
webapp.config['WTF_CSRF_TIME_LIMIT'] = None
###############################################################################
# Flask-Security-Too Configuration
webapp.config['SECURITY_REGISTERABLE'] = True
webapp.config['SECURITY_POST_REGISTER_VIEW'] = 'show_home'
webapp.config['SECURITY_SEND_REGISTER_EMAIL'] = app.smtp_enabled
webapp.config['SECURITY_USER_IDENTITY_ATTRIBUTES'] = [
{'email': {'mapper': uia_email_mapper}},
{'username': {'mapper': uia_username_mapper}}
]
webapp.config['SECURITY_RECOVERABLE'] = app.smtp_enabled
webapp.config['SECURITY_CHANGEABLE'] = True
webapp.config['SECURITY_TRACKABLE'] = True
webapp.config['SECURITY_USERNAME_ENABLE'] = True
webapp.config['SECURITY_USERNAME_REQUIRED'] = True
webapp.config['SECURITY_POST_LOGIN_VIEW'] = 'show_home'
webapp.config['SECURITY_POST_LOGOUT_VIEW'] = 'show_home'
webapp.config['SECURITY_UNAUTHORIZED_VIEW'] = 'show_home'
###############################################################################
# Mail Configuration
if app.smtp_enabled:
webapp.config['MAIL_SERVER'] = app.smtp['server']
webapp.config['MAIL_USERNAME'] = app.smtp['username']
webapp.config['MAIL_DEFAULT_SENDER'] = (app.smtp['name'],
app.smtp['username'])
webapp.config['MAIL_PASSWORD'] = app.smtp['password']
webapp.config['MAIL_USE_SSL'] = app.smtp['use_ssl']
webapp.config['MAIL_USE_TLS'] = app.smtp['use_tls']
webapp.config['MAIL_PORT'] = app.smtp['port']
webapp.config['MAIL_DEBUG'] = True
###############################################################################
# Initialize standard Flask extensions
db.init_app(webapp)
csrf = CSRFProtect(webapp)
security = Security(webapp, user_datastore, login_form=CustomLoginForm)
# Flask-Admin
admin = Admin(
webapp,
name=f"{app.title} Admin",
index_view=SecureAdminIndexView(
name="Database",
url="/admin/database"
),
template_mode="bootstrap4",
)
admin.add_view(UserModelView(User, db.session))
admin.add_view(TaskModelView(Task, db.session))
for ontology_model in [
TokenLabel, TokenRelationLabel, SentenceLabel, SentenceRelationLabel
]:
admin.add_view(
LabelModelView(ontology_model, db.session, category="Ontology")
)
for annotation_model in [
Boundary, WordOrder, TokenTextAnnotation, TokenClassification,
TokenGraph, TokenConnection, SentenceClassification, SentenceGraph
]:
admin.add_view(
AnnotationModelView(annotation_model, db.session, category="Annotation")
)
mail = Mail(webapp)
migrate = Migrate(webapp, db)
babel = Babel(webapp)
limiter = Limiter(
key_func=get_remote_address,
app=webapp,
default_limits=["1800 per hour"],
storage_uri="memory://",
)
###############################################################################
# CoNLL-U Utility
CONLLU_CONFIG = app.config["conllu"]
CONLLU_PARSER = CoNLLUParser(
input_scheme=CONLLU_CONFIG["input_scheme"],
store_scheme=CONLLU_CONFIG["store_scheme"],
input_fields=CONLLU_CONFIG["input_fields"],
relevant_fields=CONLLU_CONFIG["relevant_fields"],
metadata_field_line_text=CONLLU_CONFIG["metadata_field_line_text"],
metadata_field_line_id=CONLLU_CONFIG["metadata_field_line_id"],
metadata_field_verse_id=CONLLU_CONFIG["metadata_field_verse_id"],
transliterate_metadata_keys=CONLLU_CONFIG["transliterate_metadata_keys"],
transliterate_token_keys=CONLLU_CONFIG["transliterate_token_keys"]
)
###############################################################################
EXPORT_CONFIG = app.config["export"]
###############################################################################
# Plaintext Utility
PLAINTEXT_CONFIG = app.config["plaintext"]
PLAINTEXT_PROCESSOR = PlaintextProcessor(
input_scheme=PLAINTEXT_CONFIG["input_scheme"],
store_scheme=PLAINTEXT_CONFIG["store_scheme"]
)
###############################################################################
# Database Utility Functions
def record_submit(verse_id: int, annotator_id: int, task_id: int) -> bool:
"""Record Submit
Parameters
----------
verse_id : int
Verse ID
annotator_id : int
Annotator ID
task_id : int
Task ID
"""
submit_log = SubmitLog()
submit_log.verse_id = verse_id
submit_log.annotator_id = annotator_id
submit_log.task_id = task_id
db.session.add(submit_log)
db.session.commit()
return True
###############################################################################
# Hooks
# @webapp.before_first_request
# def init_database():
with webapp.app_context():
"""Initiate database and create admin user"""
db.create_all()
role_definitions = sorted(
ROLE_DEFINITIONS, key=lambda x: x['level'], reverse=True
)
for role_definition in role_definitions:
name = role_definition['name']
description = role_definition['description']
permissions = role_definition['permissions']
level = role_definition['level']
user_datastore.find_or_create_role(
name=name,
description=description,
level=level,
permissions=permissions
)
# special user
if not user_datastore.find_user(id=AUTO_ANNOTATION_USER_ID):
user_datastore.create_user(
id=AUTO_ANNOTATION_USER_ID,
username=AUTO_ANNOTATION_USER_USERNAME,
email=AUTO_ANNOTATION_USER_EMAIL,
password=hash_password(AUTO_ANNOTATION_USER_PASS),
roles=[ROLE_ANNOTATOR, ROLE_MEMBER]
)
if not user_datastore.find_user(username=app.admin['username']):
user_datastore.create_user(
username=app.admin['username'],
email=app.admin['email'],
password=hash_password(app.admin['password']),
roles=[
ROLE_OWNER,
ROLE_ADMIN,
ROLE_CURATOR,
ROLE_ANNOTATOR,
ROLE_MEMBER
]
)
# ----------------------------------------------------------------------- #
# Populate required tables if empty
objects = []
# Task
required_tasks = [TASK_SENTENCE_BOUNDARY, TASK_WORD_ORDER]
if not Task.query.first():
for task_idx, task_category in enumerate(required_tasks, start=1):
task_information = TASK_DEFAULT_INFORMATION[task_category]
t = Task()
t.id = task_idx
t.category = task_category
t.title = task_information["title"]
t.short = task_information["short"]
t.help = task_information["help"]
t.order = task_idx
t.is_deleted = True
objects.append(t)
webapp.logger.info(f"Loaded {task_idx} tasks.")
# Save
if objects:
db.session.bulk_save_objects(objects)
# ----------------------------------------------------------------------- #
db.session.commit()
# --------------------------------------------------------------------------- #
@user_registered.connect_via(webapp)
def assign_default_roles(sender, user, **extra):
"""Assign `ROLE_MEMBER` to users after successful registration"""
user_datastore.add_role_to_user(user, ROLE_MEMBER)
db.session.commit()
@user_authenticated.connect_via(webapp)
def _after_authentication_hook(sender, user, **extra):
pass
###############################################################################
# Global Context
@webapp.context_processor
def inject_global_context():
theme_css_files = glob.glob(
os.path.join(app.dir, 'static', 'themes', 'css', 'bootstrap.*.min.css')
)
theme_js_files = glob.glob(
os.path.join(app.dir, 'static', 'themes', 'js', 'bootstrap.*.min.js')
)
THEMES = {
"with_css": ['default'] + sorted([
os.path.basename(theme).split('.')[1]
for theme in theme_css_files
]),
"with_js": sorted([
os.path.basename(theme).split('.')[1]
for theme in theme_js_files
])
}
ROLES = {
"owner": ROLE_OWNER,
"admin": ROLE_ADMIN,
"curator": ROLE_CURATOR,
"annotator": ROLE_ANNOTATOR,
"member": ROLE_MEMBER,
"guest": ROLE_GUEST
}
# NOTE: do we really need to have these in global context?
# since they are not required on "every" page
# move them to individual routes?
# alternatively, can we add a check here which route is loading,
# and export variables based on that?
all_tasks = {
task.id: {
"id": task.id,
"category": task.category,
"title": task.title,
"short": task.short,
"help": task.help,
"order": task.order,
"is_deleted": task.is_deleted
}
for task in Task.query.order_by(Task.order).all()
}
active_tasks = {
task_id: task for
task_id, task in all_tasks.items()
if not task["is_deleted"]
}
active_task_ids = list(active_tasks)
if active_task_ids:
first_task = active_task_ids[0]
next_task = dict(
zip(
active_task_ids,
active_task_ids[1:] + [active_task_ids[0]]
)
)
else:
first_task = None
next_task = {}
TASKS = {
'tasks': all_tasks,
'active_ids': active_task_ids,
'active_tasks': active_tasks,
'first_task': first_task,
'next_task': next_task,
# task default information
'default': TASK_DEFAULT_INFORMATION,
# task categories
'task_sentence_boundary': TASK_SENTENCE_BOUNDARY,
'task_word_order': TASK_WORD_ORDER,
'task_token_text_annotation': TASK_TOKEN_TEXT_ANNOTATION,
'task_token_classification': TASK_TOKEN_CLASSIFICATION,
'task_token_graph': TASK_TOKEN_GRAPH,
'task_token_connection': TASK_TOKEN_CONNECTION,
'task_sentence_classification': TASK_SENTENCE_CLASSIFICATION,
'task_sentence_graph': TASK_SENTENCE_GRAPH,
# update actions
'update_actions': TASK_UPDATE_ACTIONS,
}
LABELS = {
# 'task_labels': Label.query.filter(
# ActionLabel.is_deleted == False # noqa # '== False' is required
# ).with_entities(
# Label.id, Label.task_id, Label.label, Label.description
# ).order_by(Label.task_id, Label.label).all(),
'token_labels': TokenLabel.query.filter(
TokenLabel.is_deleted == False # noqa # '== False' is required
).with_entities(
TokenLabel.id,
TokenLabel.task_id,
TokenLabel.label,
TokenLabel.description
).order_by(TokenLabel.label).all(),
'token_relation_labels': TokenRelationLabel.query.filter(
TokenRelationLabel.is_deleted == False # noqa # '== False' is required
).with_entities(
TokenRelationLabel.id,
TokenRelationLabel.task_id,
TokenRelationLabel.label,
TokenRelationLabel.description
).order_by(TokenRelationLabel.label).all(),
'sentence_labels': SentenceLabel.query.filter(
SentenceLabel.is_deleted == False # noqa # '== False' is required
).with_entities(
SentenceLabel.id,
SentenceLabel.task_id,
SentenceLabel.label,
SentenceLabel.description
).order_by(SentenceLabel.label).all(),
'sentence_relation_labels': SentenceRelationLabel.query.filter(
SentenceRelationLabel.is_deleted == False # noqa # '== False' is required
).with_entities(
SentenceRelationLabel.id,
SentenceRelationLabel.task_id,
SentenceRelationLabel.label,
SentenceRelationLabel.description
).order_by(SentenceRelationLabel.label).all(),
'admin_labels': []
}
for task in Task.query.all():
_name = None
if task.category == TASK_TOKEN_CLASSIFICATION:
_name = "token"
_object_name = "token_labels"
if task.category == TASK_TOKEN_GRAPH:
_name = "token_relation"
_object_name = "token_relation_labels"
if task.category == TASK_SENTENCE_CLASSIFICATION:
_name = "sentence"
_object_name = "sentence_labels"
if task.category == TASK_SENTENCE_GRAPH:
_name = "sentence_relation"
_object_name = "sentence_relation_labels"
if _name is not None:
LABELS["admin_labels"].append({
"task_id": task.id,
"name": _name,
"title": task.title,
"object_name": _object_name
})
return {
'title': app.title,
'header': app.header,
'now': datetime.datetime.utcnow(),
'since': app.since,
'copyright': app.copyright,
# 'navigation_menu': app.navigation_menu,
'footer_links': app.footer_links,
'context_roles': ROLES,
'context_tasks': TASKS,
'context_labels': LABELS,
'context_themes': THEMES,
'config': app.config
}
###############################################################################
# Flask-Admin Context for Flask-Security-Too
@security.context_processor
def security_context_processor():
return dict(
admin_base_template=admin.base_template,
admin_view=admin.index_view,
h=admin_helpers,
get_url=url_for
)
###############################################################################
# Flask-Security-Too Views Context
@security.register_context_processor
def security_register_processor():
data = {'title': 'Register'}
return {'data': data}
@security.login_context_processor
def security_login_processor():
data = {'title': 'Login'}
return {'data': data}
@security.forgot_password_context_processor
def security_forgot_password_processor():
data = {'title': 'Forgot Password'}
return {'data': data}
@security.change_password_context_processor
def security_change_password_processor():
data = {'title': 'Change Password'}
return {'data': data}
@security.reset_password_context_processor
def security_reset_password_processor():
data = {'title': 'Reset Password'}
return {'data': data}
###############################################################################
# Views
@webapp.route("/admin")
@auth_required()
@permissions_required(PERMISSION_VIEW_ACP)
def show_admin():
data = {}
data['title'] = 'Admin'
user_level = max([role.level for role in current_user.roles])
annotator_role = user_datastore.find_role(ROLE_ANNOTATOR)
user_model = user_datastore.user_model
role_model = user_datastore.role_model
user_query = user_model.query.filter(User.id != AUTO_ANNOTATION_USER_ID)
role_query = role_model.query
data['filetypes'] = {
'chapter': [FILE_TYPE_CONLLU, FILE_TYPE_PLAINTEXT],
'ontology': [FILE_TYPE_CSV, FILE_TYPE_JSON],
}
data['users'] = []
data['annotators'] = []
for user in user_query.all():
user_object = {
"id": user.id,
"username": user.username,
"email": user.email
}
data['users'].append(user_object)
if annotator_role in user.roles:
data['annotators'].append(user_object)
data['roles'] = [
role.name
for role in role_query.order_by(role_model.level).all()
if role.level < user_level
]
data['corpus_list'] = [
{
'id': corpus.id,
'name': corpus.name,
'chapters': [
{
'id': chapter.id,
'name': chapter.name
}
for chapter in corpus.chapters.all()
]
}
for corpus in Corpus.query.all()
]
data['pa'] = app.pa_enabled
admin_result = session.get('admin_result', None)
if admin_result:
data['result'] = admin_result
del session['admin_result']
return render_template('admin.html', data=data)
@webapp.route("/progress")
@auth_required()
@permissions_required(PERMISSION_CURATE)
def show_progress():
data = {
"title": "Annotation Progress",
**get_annotation_progress()
}
return render_template("progress.html", data=data)
# --------------------------------------------------------------------------- #
@webapp.route("/export", methods=["GET", "POST"])
@auth_required()
@permissions_required(PERMISSION_ANNOTATE)
def show_export():
data = {}
data['title'] = 'Export'
if current_user.has_role(ROLE_CURATOR):
user_model = user_datastore.user_model
user_query = user_model.query.filter(
User.id != AUTO_ANNOTATION_USER_ID
)
data['users'] = [
{
"id": user.id,
"username": user.username,
"email": user.email
}
for user in user_query.all()
]
data['corpora'] = {
corpus.id: corpus.name
for corpus in Corpus.query.all()
}
data['chapters'] = {
chapter.id: {
'corpus_id': chapter.corpus_id,
'name': chapter.name
}
for chapter in Chapter.query.all()
}
if request.method == "POST":
annotator_id = None
if current_user.has_role(ROLE_CURATOR):
annotator_id = request.form.get('annotator_id', '').strip()
if not annotator_id:
annotator_id = current_user.id
chapter_ids = request.form.getlist('chapter_id')
# CAUTION: Although the function export_data() is designed to support
# querying over multiple annotators and multiple chapters, it is
# infeasible and downright confusing to show annotations by multiple
# users at once. Therefore, it should be noted that there is (and
# most likely will be) NO SUPPORT for multiple user selection.
annotation_data = export_data(
annotator_ids=[int(annotator_id)],
chapter_ids=[int(chapter_id) for chapter_id in chapter_ids],
task_ids=[]
)
annotation_result_simple, annotation_result_standard = format_data(
annotation_data,
token_text_preference=EXPORT_CONFIG["token_text_preference"]
)
data['form'] = {
'annotator_id': annotator_id,
'chapter_ids': chapter_ids
}
data["result_simple"] = annotation_result_simple
data["result_standard"] = annotation_result_standard
return render_template('export.html', data=data)
@webapp.route("/settings")
@auth_required()
@permissions_required(PERMISSION_VIEW_UCP)
def show_settings():
data = {}
data['title'] = 'Settings'
return render_template('settings.html', data=data)
@webapp.route("/corpus")
@webapp.route("/corpus/<string:chapter_id>")
@auth_required()
@permissions_required(PERMISSION_VIEW_CORPUS)
def show_corpus(chapter_id=None):
if chapter_id is None:
flash("Please select a corpus to view.", "info")
return redirect(url_for('show_home'))
data = {}
data['title'] = 'Corpus'
data['chapter_id'] = chapter_id
data['show_annotation'] = True
data['enable_annotation'] = current_user.has_permission(
PERMISSION_ANNOTATE
)
return render_template('corpus.html', data=data)
@webapp.route("/terms")
def show_terms():
data = {'title': 'Terms of Use'}
return render_template('terms.html', data=data)
@webapp.route("/contact")
def show_contact():
data = {'title': 'Contact Us'}
contacts = []
replacement = {'@': 'at', '.': 'dot'}
for _contact in app.contacts:
contact = _contact.copy()
email = (
_contact['email'].replace('.', ' . ').replace('@', ' @ ').split()
)
contact['email'] = []
for email_part in email:
contact['email'].append({
'text': replacement.get(email_part, email_part),
'is_text': replacement.get(email_part) is None
})
contacts.append(contact)
data['contacts'] = contacts
return render_template('contact.html', data=data)
@webapp.route("/about")
def show_about():
data = {
'title': 'About',
'about': app.about
}
return render_template('about.html', data=data)
@webapp.route("/<page>")
def show_custom_page(page):
if page in app.custom_pages:
page_data = app.custom_pages[page]
data = {
'title': page_data['title'],
'card_header': page_data['card_header'],
'card_body': page_data['card_body']
}
return render_template('pages.html', data=data)
else:
abort(404)
@webapp.route("/")
@auth_required()
def show_home():
data = {}
data['title'] = 'Home'
data['corpus_list'] = [
{'id': corpus.id, 'name': corpus.name, 'chapters': [
{'id': chapter.id, 'name': chapter.name}
for chapter in corpus.chapters.all()
]}
for corpus in Corpus.query.all()
]
return render_template('home.html', data=data)
###############################################################################
# Action Endpoints
@webapp.route("/api/search/analysis/<string:token_text>")
@auth_required()
def api_search_token(token_text: str):
search_query = Token.query.filter(
Token.text == token_text
).group_by(Token.analysis)
analyses = [
token.analysis for token in search_query
]
return jsonify({
'text': token_text,
'matches': analyses
})
# --------------------------------------------------------------------------- #
@webapp.route("/api", methods=["POST"])
@auth_required()
def api():
api_response = {}
api_response['success'] = False
try:
action = request.form['action']
except KeyError:
api_response['message'] = "Insufficient parameters in request."
return jsonify(api_response)
# ----------------------------------------------------------------------- #
# Action Authorization
task_update_actions = list(TASK_UPDATE_ACTIONS.values())
annotator_actions = task_update_actions + ["add_token", "split_token"]
role_actions = {
ROLE_ADMIN: [],
ROLE_ANNOTATOR: annotator_actions,
ROLE_CURATOR: [],
}
valid_actions = [
action for actions in role_actions.values() for action in actions
]
if action not in valid_actions:
api_response["message"] = f"Invalid action. ({action})"
return jsonify(api_response)
for role, actions in role_actions.items():
if action in actions and not current_user.has_role(role):
api_response["message"] = "Insufficient permissions."
return jsonify(api_response)
# ----------------------------------------------------------------------- #
# Populate next_task
task_query = Task.query.filter(
Task.is_deleted == False # noqa # '== False' is required
).order_by(Task.order)
active_task_ids = [task.id for task in task_query.all()]
if active_task_ids:
first_task = active_task_ids[0]
next_task = dict(
zip(
active_task_ids,
active_task_ids[1:] + [active_task_ids[0]]
)
)
else:
first_task = None
next_task = {}
if action in task_update_actions:
api_response["first_task"] = first_task
# ----------------------------------------------------------------------- #
api_response["success"] = True
api_response["message"] = "Under construction."
api_response["style"] = "warning"
# ----------------------------------------------------------------------- #
if action == TASK_UPDATE_ACTIONS[TASK_SENTENCE_BOUNDARY]:
annotator_id = current_user.id
task_id = int(request.form["task_id"])
verse_id = int(request.form["verse_id"])
boundary_tokens = [
int(b.strip())
for b in request.form["boundaries"].split(",")
if b.strip()
]
perform_update = False
objects_to_update = []
# If there's any change between existing tokens and marked tokens,
# delete all existing boundary tokens from this verse
# WordOrder also gets deleted as (CASCADE)
# TokenClassification also gets deleted as (CASCADE)
# TokenGraph also gets deleted as (CASCADE)
# TokenConnection also gets deleted as (CASCADE)
# SentenceClassification also gets deleted as (CASCADE)
# SentenceGraph also gets deleted as (CASCADE)
# NOTE: A sentence boundary task should always be "present"
# (even if inactive), since very other task is tied to boundary_id
# NOTE: We do not check with task_id because, only single sentence
# boundary task is supported
# TODO: Perhaps remove `task_id` column from Boundary table altogether
existing_boundary_query = Boundary.query.filter(
Boundary.verse_id == verse_id,
Boundary.annotator_id == annotator_id
)
existing_boundary_tokens = [
_boundary.token_id
for _boundary in existing_boundary_query.all()
]
if set(existing_boundary_tokens) != set(boundary_tokens):
perform_update = True
# delete existing boundary markers from current verse
# NOTE: this *could* be improved to only delete the changed one
# but every change in boundary marker affects the boundary AFTER it
# as well, (and only that), and while adding multiple boundary
# markers, this can get complicated, so, delete all
existing_boundary_query.delete(synchronize_session=False)
# delete the first boundary marker after the current verse
next_boundary = Boundary.query.filter(
Boundary.verse_id > verse_id,
Boundary.annotator_id == annotator_id,
).order_by(Boundary.token_id).first()
# print("Next Boundary:", next_boundary)
# NOTE: We do not check with task_id because, currently, only
# single token order task is supported (as there needs to be a
# link between this and boundary task)
# NOTE: If for some reason we need multiple token order tasks,
# all of them would require to be deleted anyway as the boundary