-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver_sqla.py
2325 lines (1963 loc) · 78.8 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) 2020-2023 Hrishikesh Terdalkar"
__version__ = "3.4.0"
###############################################################################
import os
import re
import csv
import glob
import json
import logging
import datetime
import io
import zipfile
import git
import requests
from flask import (Flask, render_template, redirect, jsonify, url_for,
request, flash, session, Response, abort)
from flask_security import (Security, RegisterForm,
auth_required, permissions_required,
hash_password, current_user,
user_registered, user_confirmed,
user_authenticated)
from flask_security.utils import uia_email_mapper
from sqlalchemy import or_, and_, func
from flask_admin import Admin, helpers as admin_helpers
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_QUERIER,
ROLE_MEMBER,
ROLE_GUEST,
ROLE_DEFINITIONS,
PERMISSION_VIEW_ACP,
PERMISSION_QUERY,
PERMISSION_ANNOTATE,
PERMISSION_CURATE,
PERMISSION_VIEW_UCP,
PERMISSION_VIEW_CORPUS,
# File Types
FILE_TYPE_PLAINTEXT,
FILE_TYPE_JSON,
FILE_TYPE_CSV,
)
from models_sqla import (db, user_datastore, User,
CustomLoginForm,
Corpus, Chapter, Verse, Line, Analysis,
Lexicon, NodeLabel, Node,
RelationLabel, Relation,
ActionLabel, ActorLabel, Action)
from models_admin import (SecureAdminIndexView,
UserModelView, LabelModelView,
LexiconModelView, AnnotationModelView)
from settings import app
from utils.reverseproxied import ReverseProxied
from utils.database import (
add_chapter,
get_line_data,
get_chapter_data,
build_graph
)
from utils.graph import Graph
from utils.property_graph import PropertyGraph
from utils.query import load_queries
from utils.cypher_utils import graph_to_cypher
from utils.plaintext import Tokenizer
###############################################################################
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='static')
webapp.config['DEBUG'] = app.debug
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
# 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_CONFIRMABLE'] = app.smtp_enabled
webapp.config['SECURITY_LOGIN_WITHOUT_CONFIRMATION'] = True
webapp.config['SECURITY_POST_CONFIRM_VIEW'] = 'show_home'
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,
confirm_register_form=RegisterForm)
# NOTE: By default, Flask-Security-Too disables "Confirm Password" prompt if
# `SECURITY_CONFIRMABLE` is set to `True`.
# We want to have both, so `confirm_register_form=flask_security.RegisterForm`
# (Default is confirm_register_form=flask_security.ConfirmRegisterForm)
# flask-admin
admin = Admin(
webapp,
name=f"{app.title} Admin",
index_view=SecureAdminIndexView(
name="Database",
url="/admin/database"
),
template_mode="bootstrap4",
base_template="admin_base.html",
)
admin.add_view(UserModelView(User, db.session))
admin.add_view(LabelModelView(NodeLabel, db.session, category="Ontology"))
admin.add_view(LabelModelView(RelationLabel, db.session, category="Ontology"))
admin.add_view(LexiconModelView(Lexicon, db.session, category="Annotation"))
admin.add_view(AnnotationModelView(Node, db.session, category="Annotation"))
admin.add_view(
AnnotationModelView(Relation, 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://",
)
###############################################################################
# Neo4j Graph
GRAPH = None
def connect_graph_server():
try:
return Graph(
server=app.neo4j['server'],
username=app.neo4j['username'],
password=app.neo4j['password']
)
except Exception as e:
logging.error(f"Graph Database connection failed. ({e})")
return None
def initialize_graph_connection():
"""Establish graph connection if not connected already"""
global GRAPH
if GRAPH is None:
GRAPH = connect_graph_server()
return GRAPH is not None
# Initialize Graph Connection
initialize_graph_connection()
###############################################################################
QUERIES = load_queries(app.query_file)
###############################################################################
# Database Utility Functions
def get_lexicon(lemma: str) -> int:
"""Fetch id of an existing Lexicon"""
lexicon = Lexicon.query.filter(Lexicon.lemma == lemma).one_or_none()
if lexicon:
return lexicon.id
def create_lexicon(lemma: str, commit: bool = False) -> int:
"""Create a new Lexicon and return its id"""
transliterations = [
f"##{transliterate(lemma, 'devanagari', scheme)}"
if not lemma.startswith(app.config['unnamed_prefix']) else ''
for scheme in app.config['schemes']
]
transliteration = ''.join(transliterations)
lexicon = Lexicon()
lexicon.lemma = lemma
if transliteration:
lexicon.transliteration = transliteration
try:
db.session.add(lexicon)
except Exception as e:
webapp.logger.exception(e)
db.session.rollback()
return None
else:
if not commit:
db.session.flush()
else:
db.session.commit()
return lexicon.id
def get_or_create_lexicon(lemma: str) -> int:
return get_lexicon(lemma) or create_lexicon(lemma)
def update_lexicon(old_lemma: str, new_lemma: str) -> bool:
"""
Change lemma of a lexicon entry
It must be ensured that `new_lemma` does not exist already,
else the uniqueness constraint on `Lexicon.lemma` will be violated.
Different strategies may be required if the `new_lemma` already exists,
based on different roles of users trying to use this command.
e.g., when changing to an existing lemma, we would need to update all the
`Node` references as well, and this should be limited to secure roles,
such as `ROLE_CURATOR` or `ROLE_ADMIN`.
These decisions are left out of scope of this function.
"""
transliterations = [
f"##{transliterate(new_lemma, 'devanagari', scheme)}"
if not new_lemma.startswith(app.config['unnamed_prefix']) else ''
for scheme in app.config['schemes']
]
transliteration = ''.join(transliterations)
lexicon = Lexicon.query.filter(Lexicon.lemma == old_lemma).one_or_none()
if lexicon is None:
return False
try:
lexicon.lemma = new_lemma
lexicon.transliteration = transliteration
db.session.add(lexicon)
except Exception as e:
webapp.logger.exception(e)
db.session.rollback()
else:
db.session.commit()
return True
return False
def update_node_label_id(
node_id: int, old_label_id: int, new_label_id: int
) -> bool:
"""
Change node label (label_id) of a node
If there is already exists a node which has node label `new_label_id`
and shares `line_id`, `annotator_id`, `lexicon_id` with `node_id`,
it'll result in the uniqueness constraint violation on `Node`.
In case of such an event, transaction will be aborted.
NOTE: Even if a user with ROLE_CURATOR changes a node, it will not
change the `annotator_id` associated with it.
"""
node = Node.query.get(node_id)
node_label = NodeLabel.query.get(new_label_id)
if node is None or node_label is None:
return False
# sanity check
if node.label_id != int(old_label_id):
return False
try:
node.label_id = new_label_id
db.session.add(node)
except Exception as e:
webapp.logger.exception(e)
db.session.rollback()
else:
db.session.commit()
return True
return False
# --------------------------------------------------------------------------- #
def update_relation_label_id(
relation_id: int, old_label_id: int, new_label_id: int
) -> bool:
"""
Change relation label (label_id) of a relation
In case of the uniqueness constraint violation on `Relation`,
transaction will be aborted.
NOTE: Even if a user with ROLE_CURATOR changes a relation, it will not
change the `annotator_id` associated with it.
"""
relation = Relation.query.get(relation_id)
relation_label = NodeLabel.query.get(new_label_id)
if relation is None or relation_label is None:
return False
# sanity check
if relation.label_id != int(old_label_id):
return False
try:
relation.label_id = new_label_id
db.session.add(relation)
except Exception as e:
webapp.logger.exception(e)
db.session.rollback()
else:
db.session.commit()
return True
return False
def update_node_id_in_relations(old_node_id: int, new_node_id: int) -> bool:
"""
Change all occurrences of `old_node_id` in relations to `new_node_id`
"""
old_node = Node.query.get(old_node_id)
new_node = Node.query.get(new_node_id)
if old_node is None or new_node is None:
return False
src_relations = Relation.query.filter(Relation.src_id == old_node_id).all()
dst_relations = Relation.query.filter(Relation.dst_id == old_node_id).all()
try:
for relation in src_relations:
relation.src_id = new_node_id
db.session.add(relation)
for relation in dst_relations:
relation.dst_id = new_node_id
db.session.add(relation)
except Exception as e:
webapp.logger.exception(e)
db.session.rollback()
else:
db.session.commit()
return True
###############################################################################
# Hooks
@webapp.before_first_request
def init_database():
"""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
)
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_QUERIER,
ROLE_MEMBER
]
)
# ----------------------------------------------------------------------- #
# # Populate various tables if empty
# # NOTE: Refer to `data/tables/README.md` for format of JSON and CSV
# objects = []
# # Labels
# label_models = [NodeLabel, RelationLabel, ActionLabel, ActorLabel]
# for label_model in label_models:
# if not label_model.query.first():
# table_name = label_model.__tablename__
# table_json_file = os.path.join(
# app.tables_dir, f"{table_name}.json"
# )
# table_csv_file = os.path.join(
# app.tables_dir, f"{table_name}.csv"
# )
# table_file = None
# if os.path.isfile(table_json_file):
# table_file = table_json_file
# with open(table_json_file, encoding="utf-8") as f:
# table_data = json.load(f)
# elif os.path.isfile(table_csv_file):
# table_file = table_csv_file
# with open(table_csv_file, encoding="utf-8") as f:
# table_data = list(csv.DictReader(f))
# if table_file is None:
# continue
# for idx, label in enumerate(table_data, start=1):
# lm = label_model()
# lm.label = label["label"]
# lm.description = label["description"]
# objects.append(lm)
# webapp.logger.info(
# f"Loaded {idx} items to {table_name} from {table_file}."
# )
# # Save
# if objects:
# db.session.bulk_save_objects(objects)
# ----------------------------------------------------------------------- #
db.session.commit()
###############################################################################
# Signals
@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_confirmed.connect_via(webapp)
def assign_confirm_roles(sender, user, **extra):
"""Assign `ROLE_QUERIER` to users after email confirmation"""
user_datastore.add_role_to_user(user, ROLE_QUERIER)
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,
"querier": ROLE_QUERIER,
"member": ROLE_MEMBER,
"guest": ROLE_GUEST
}
LABELS = {
'node_labels': NodeLabel.query.filter(
NodeLabel.is_deleted == False # noqa # '== False' is required
).with_entities(
NodeLabel.id, NodeLabel.label, NodeLabel.description
).all(),
'relation_labels': RelationLabel.query.filter(
RelationLabel.is_deleted == False # noqa # '== False' is required
).with_entities(
RelationLabel.id, RelationLabel.label, RelationLabel.description
).all(),
# 'action_labels': ActionLabel.query.filter(
# ActionLabel.is_deleted == False # noqa # '== False' is required
# ).with_entities(
# ActionLabel.id, ActionLabel.label, ActionLabel.description
# ).all(),
# 'actor_labels': ActorLabel.query.filter(
# ActorLabel.is_deleted == False # noqa # '== False' is required
# ).with_entities(
# ActorLabel.id, ActorLabel.label, ActorLabel.description
# ).all(),
'admin_labels': [
{
"name": "node",
"title": "Node",
"object_name": "node_labels"
},
{
"name": "relation",
"title": "Relation",
"object_name": "relation_labels"
},
# {
# "name": "action",
# "title": "Action",
# "object_name": "action_labels"
# },
# {
# "name": "actor",
# "title": "Actor",
# "object_name": "actor_labels"
# },
]
}
return {
'title': app.title,
'now': datetime.datetime.utcnow(),
'context_roles': ROLES,
'context_themes': THEMES,
'context_labels': LABELS,
'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('annotator')
user_model = user_datastore.user_model
role_model = user_datastore.role_model
user_query = user_model.query
role_query = role_model.query
data['filetypes'] = {
'chapter': [FILE_TYPE_PLAINTEXT, FILE_TYPE_JSON],
'ontology': [FILE_TYPE_CSV, FILE_TYPE_JSON]
}
data['users'] = [user.username for user in user_query.all()]
data['annotators'] = [user.username for user in user_query.all()
if annotator_role in user.roles]
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()
]
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("/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['enable_annotation'] = current_user.has_permission(
PERMISSION_ANNOTATE
)
return render_template('corpus.html', data=data)
@webapp.route("/browse")
@auth_required()
@permissions_required(PERMISSION_QUERY)
def show_browse():
data = {}
data['title'] = 'Graph Browser'
data['initial_query'] = (
'MATCH (node_1)-[edge]->(node_2) RETURN * ORDER BY rand() LIMIT 10'
)
data['node_query_template'] = (
'MATCH (x)-[relation]-(entity) '
'WHERE entity.lemma =~ "{}" RETURN *'
)
return render_template('browse.html', data=data)
@webapp.route("/query")
@auth_required()
@permissions_required(PERMISSION_QUERY)
def show_query():
data = {}
data['title'] = 'Query'
query_groups = {}
for q in QUERIES:
if q.gid not in query_groups:
query_groups[q.gid] = {
'groups': q.groups,
'queries': []
}
query_groups[q.gid]['queries'].append(q.to_dict(
prefix=app.config['var_prefix'],
suffix=app.config['var_prefix'],
debug=False
))
data['query_groups'] = list(query_groups.values())
data['initial_query'] = (
'MATCH (node_1)-[edge]->(node_2) RETURN * ORDER BY rand() LIMIT 25'
)
data['initial_output_order'] = ['node_1', 'edge', 'node_2']
return render_template('query.html', data=data)
@webapp.route("/query/builder")
@auth_required()
@permissions_required(PERMISSION_QUERY)
def show_builder():
data = {'title': 'Graph Query Builder'}
data['templates'] = app.config['graph_templates']
return render_template('builder.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
data['feedback_url'] = app.feedback_url
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>")
@auth_required()
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)
###############################################################################
# Ontology
@webapp.route("/ontology", methods=["GET"])
@auth_required()
def get_ontology():
ontology = {
'node_labels': [
tuple(nl)
for nl in NodeLabel.query.filter(
NodeLabel.is_deleted == False # noqa # '== False' is required
).with_entities(
NodeLabel.id, NodeLabel.label, NodeLabel.description
).all()
],
'relation_labels': [
tuple(rl)
for rl in RelationLabel.query.filter(
RelationLabel.is_deleted == False # noqa # '== False' is required
).with_entities(
RelationLabel.id, RelationLabel.label, RelationLabel.description
).all()
],
}
return jsonify(ontology)
###############################################################################
# Action Endpoints
@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
role_actions = {
ROLE_ADMIN: [],
ROLE_ANNOTATOR: [
'update_entity',
'update_relation',
# 'update_action',
'update_lexicon',
'update_node_label_id',
'update_relation_label_id',
'update_node_id_in_relations',
],
ROLE_CURATOR: [],
ROLE_QUERIER: ['query', 'graph_query']
}
valid_actions = [
action for actions in role_actions.values() for action in actions
]
if action not in valid_actions:
api_response['message'] = "Invalid 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)
# ----------------------------------------------------------------------- #
api_response['success'] = True
api_response['style'] = "info"
# ----------------------------------------------------------------------- #
if action == 'update_lexicon':
annotator_id = current_user.id
current_lemma = request.form['current_lemma']
replacement_lemma = request.form['replacement_lemma']
if current_lemma == replacement_lemma:
api_response["success"] = False
api_response["message"] = (
"Replacement text is same as current text."
)
return jsonify(api_response)
replacement_lexicon_id = get_lexicon(replacement_lemma)
if replacement_lexicon_id:
# NOTE: One option is to add a replacement strategy for Curators
# However, it might be best to handle this case-by-case basis and
# not make an interface for it.
# # if current_user.has_permission(PERMISSION_CURATE):
# # ...
api_response["success"] = False
api_response["message"] = "Replacement text already exists."
api_response["style"] = "warning"
return jsonify(api_response)
try:
status = update_lexicon(current_lemma, replacement_lemma)