-
Notifications
You must be signed in to change notification settings - Fork 2
/
callig.py
executable file
·1524 lines (1166 loc) · 53.3 KB
/
callig.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 -*-
import os
import datetime
import random
import string
import json
from flask import Flask, render_template, g, request, redirect, url_for, send_from_directory, session, flash, jsonify, make_response
#, Markup)
from flask_login import LoginManager, UserMixin, login_required, login_user, logout_user, current_user
from flask_mail import Mail, Message
from functools import wraps
from itsdangerous import URLSafeTimedSerializer # for safe session cookies
from collections import defaultdict as dd
from hashlib import md5
from werkzeug.utils import secure_filename
import lxml.html # to manipulate html
from common_login import *
import common_sql as csql
from common_sql import *
import lcc
import wn
import utils
import syl
import game_data
import delphin_call
import common_sql as csql
from feedback import eng_feedback
def inf_dd():
return dd(inf_dd)
app = Flask(__name__)
# app.debug = True
app.secret_key = "!$flhgSgngNO%$#SOET!$!"
app.config["REMEMBER_COOKIE_DURATION"] = datetime.timedelta(minutes=30)
ROOT = path.dirname(path.realpath(__file__))
###############################################################################
# MODE defines which apps are available in the deployed instance #
# #
# 'test' MODE should not be used in deployment #
# The other modes include: 'lcc', 'ixue', 'callig', 'grammarium' #
###############################################################################
MODE = ['lcc', 'ixue', 'callig', 'grammarium', 'test']
MODE = ['callig', 'grammarium']
app.config.update(
# When using gmail, we need to allow unsafe apps to use the email.
# check: https://pythonprogramming.net/flask-email-tutorial/
DEBUG=False,
#EMAIL SETTINGS
# MAIL_SERVER='smtp.gmail.com',
# MAIL_PORT=465,
# MAIL_USE_SSL=True,
# MAIL_USERNAME='openwns@gmail.com',
# MAIL_PASSWORD='changeme'
)
# mail = Mail(app)
###############################################################################
# LOGIN
###############################################################################
login_manager.init_app(app)
def randomPassword(stringLength=10):
"""
Generate a random string of letters and digits.
This is being used to generate random passwords.
"""
letters_nums = string.ascii_letters + string.digits
return ''.join(random.choice(letters_nums) for i in range(stringLength))
@app.route("/login", methods=["GET", "POST"])
def login():
"""
This login function checks if the username & password
match the admin.db; if the authentication is successful,
it passes the id of the user into login_user().
"""
if request.method == "POST" and \
"username" in request.form and \
"password" in request.form:
username = request.form["username"]
password = request.form["password"]
user = User.get(username)
# If we found a user based on username then compare that the submitted
# password matches the password in the database. The password is stored
# is a slated hash format, so you must hash the password before comparing it.
if user and hash_pass(password) == user.password:
login_user(user, remember=True)
# FIXME! Get this to work properly...
# return redirect(request.args.get("next") or url_for("index"))
return redirect(url_for("index"))
else:
flash(u"Invalid username, please try again.")
return render_template("login.html",
MODE=MODE)
@app.route("/logout")
@login_required(role=0, group='open')
def logout():
logout_user()
return redirect(url_for("index"))
###############################################################################
###############################################################################
# SET UP CONNECTION WITH DATABASES
###############################################################################
@app.before_request
def before_request():
g.admin = csql.connect_admin()
g.callig = csql.connect_callig()
g.lcc = csql.connect_lcc()
g.ntucleX = csql.connect_ntucleX()
@app.teardown_request
def teardown_request(exception):
if hasattr(g, 'db'):
g.admin.close()
g.callig.close()
g.lcc.close()
g.ntucleX.close()
###############################################################################
###############################################################################
# GENERAL FUNCTIONS
###############################################################################
def current_time():
''' YYYY-MM-DD HH:MM '''
d = datetime.datetime.now()
return d.strftime('%Y-%m-%d %H:%M:%S')
################################################################################
################################################################################
# AJAX REQUESTS
################################################################################
################################################################################
# STATIC VIEWS
################################################################################
@app.route('/', methods=['GET', 'POST'])
def index():
return render_template('welcome.html',
MODE=MODE)
@app.route('/team', methods=['GET', 'POST'])
def team():
return render_template('team.html',
MODE=MODE)
@app.route('/callig', methods=['GET', 'POST'])
def callig_intro():
return render_template('callig_intro.html',
MODE=MODE)
@app.route('/lcc', methods=['GET', 'POST'])
def lcc_intro():
return render_template('lcc_intro.html',
MODE=MODE)
@app.route('/ixue', methods=['GET', 'POST'])
def ixue_intro():
return render_template('ixue_intro.html',
MODE=MODE)
@app.route('/grammarium', methods=['GET', 'POST'])
def grammarium_intro():
return render_template('grammarium_intro.html',
MODE=MODE)
@app.route('/introduction', methods=['GET', 'POST'])
def itell_intro():
return render_template('itell_intro.html',
MODE=MODE)
###############################################################################
# ADMIN VIEWS
###############################################################################
@app.route('/register', methods=['GET', 'POST'])
def register():
return render_template('register.html',
MODE=MODE)
@app.route("/useradmin", methods=["GET"])
@login_required(role=0, group='admin')
def useradmin():
users = fetch_allusers()
return render_template("useradmin.html",
users=users,
MODE=MODE)
###############################################################################
# GAMES VIEWS
###############################################################################
@app.route('/info/sex-with-me', methods=['GET', 'POST'])
@login_required(role=0, group='open')
def sexwithme_info():
base_ex = [(0, "Sex with me is like a mountain... it will make you want to get on top.", "The CALLIG System", "Unknown date", "0 seconds")]
example_list = []
exs = fetch_sexwithme_30()
for i, ex_id in enumerate(exs.keys()):
r = exs[ex_id]
prompt = r[0]
answer = r[1]
seconds = str(r[2]) + ' ' + 'seconds'
language = r[3]
username = r[4]
timestamp = r[5].split()[0]
example_list.append((i, prompt + '... ' + answer,
username, timestamp, seconds))
if example_list:
return render_template('sexwithme-info.html',
example_list=example_list,
MODE=MODE)
else: # for brand-new dbs, show a system's example
return render_template('sexwithme-info.html',
example_list=base_ex,
MODE=MODE)
@app.route('/games/sex-with-me', methods=['GET', 'POST'])
@login_required(role=0, group='open')
def sexwithme_game():
rand_word = wn.x_rand_pos(1,'n')[0] # only 1 item on the list
noun = rand_word[0]
definition = rand_word[1]
article = rand_word[2]
seconds = 40 # this is the max amount of time to play
return render_template('sexwithme-game.html',
seconds=seconds,
article=article,
noun=noun,
definition=definition,
MODE=MODE)
@app.route('/_save_sex-with-me', methods=['GET', 'POST'])
@login_required(role=0, group='open')
def save_sexwithme():
if request.method == 'POST':
result = request.form
language = 'eng'
prompt = result['prompt'].strip()
answer = result['answer'].strip()
seconds = result['seconds']
username = result['username']
# it's always treated as 1 sentence, so we can do this:
if answer:
parse = delphin_call.check_sents([answer])[0]
errors = parse[1] # should be of type [('non_third_sg_fin_v_rbst', 'wants')]
else:
errors = []
tags = []
foci = []
for e in errors:
tag = e[0]
focus = e[1]
tags.append(tag)
foci.append(focus)
if answer and tags and ('NoParse' not in tags):
# we are not showing feedback for a 'NoParse'
sex_with_me_id = None
for tag in tags:
write_sexwithme_feedback(answer, sex_with_me_id, tag,
seconds, language, username, current_time())
return render_template('sexwithme-feedback.html',
answer=answer,
tags=tags,
foci=foci,
eng_feedback=eng_feedback,
MODE=MODE)
if answer and tags and ('NoParse' in tags):
sex_with_me_id = write_sexwithme(prompt, answer, seconds, language,
username, current_time())
for tag in tags:
write_sexwithme_feedback(answer, sex_with_me_id, tag,
seconds, language, username, current_time())
elif answer:
write_sexwithme(prompt, answer, seconds, language,
username, current_time())
else:
write_sexwithme(prompt, None, seconds, language,
username, current_time())
return sexwithme_game()
### WICKED PROVERBS
@app.route('/info/wicked-proverbs', methods=['GET', 'POST'])
@login_required(role=0, group='open')
def wickedproverbs_info():
base_ex = [(0, "My mother always said:",
"A high school cheerleader's love is like an old bicycle in a remote village.",
"Everyone is welcome to take a ride, but it's squeaks in wrong ways, and as soon as you are going down you will start to regret it.",
"The CALLIG System",
"Unknown date",
"0 seconds")]
example_list = []
exs = fetch_wickedproverbs_30()
for i, ex_id in enumerate(exs.keys()):
r = exs[ex_id]
frame = r[0]
proverb = r[1]
explanation = r[2]
seconds = str(r[3]) + ' ' + 'seconds'
username = r[5]
timestamp = r[6].split()[0]
example_list.append((i, frame, proverb, explanation, username, timestamp, seconds))
if example_list:
return render_template('wickedproverbs-info.html',
example_list=example_list,
MODE=MODE)
else: # for brand-new dbs, show a system's example
return render_template('wickedproverbs-info.html',
example_list=base_ex,
MODE=MODE)
@app.route('/games/wicked-proverbs', methods=['GET', 'POST'])
@login_required(role=0, group='open')
def wickedproverbs_game():
"""
For now this only decides between Noun-Noun and Noun-Verb.
Definitions should exist come for each word.
It gets a random frame from game_data.
"""
game_option = random.randrange(3) # 0, 1 or 2
if game_option == 0:
nouns = wn.x_rand_pos(2,'n')
w1 = nouns[0]
w2 = nouns[1]
elif game_option == 1:
w1 = wn.x_rand_pos(1,'v')[0]
w2 = wn.x_rand_pos(1,'n')[0]
else:
w1 = wn.x_rand_pos(1,'v')[0]
w2 = wn.x_rand_pos(1,'a')[0]
frame = random.choice(game_data.proverb_frames)
seconds = 90 # this is the max amount of time to play
return render_template('wickedproverbs-game.html',
seconds=seconds,
w1=w1,
w2=w2,
frame=frame,
MODE=MODE)
@app.route('/_save_wicked-proverbs', methods=['GET', 'POST'])
@login_required(role=0, group='open')
def save_wickedproverbs():
if request.method == 'POST':
result = request.form
frame = result['frame'].strip()
w1 = result['w1'].strip()
w2 = result['w2'].strip()
proverb = result['proverb'].strip()
explanation = result['explanation'].strip()
seconds = result['seconds']
if proverb and explanation:
write_wickedproverbs(frame, w1, w2, proverb, explanation, seconds,
'eng', result['username'], current_time())
else:
write_wickedproverbs(frame, w1, w2, None, None, seconds,
'eng', result['username'], current_time())
return wickedproverbs_game()
################################################################################
# CALLIG: FORCED LINKS
################################################################################
@app.route('/info/forced-links', methods=['GET', 'POST'])
@login_required(role=0, group='open')
def forcedlinks_info():
example_list = []
exs = fetch_forcedlinks()
for i, ex_id in enumerate(exs.keys()):
r = exs[ex_id]
w1 = r[0]
w2 = r[1]
links_json = r[2]
timestamps_json = r[3]
seconds = str(r[4]) + ' ' + 'seconds'
username = r[6]
timestamp = r[7].split()[0]
example_list.append((i, w1, w2,
json.loads(links_json),
json.loads(timestamps_json),
seconds, username, timestamp))
if example_list:
return render_template('callig_forcedlinks_info.html',
example_list=example_list,
MODE=MODE)
else: # for brand-new dbs, show a system's example
return render_template('callig_forcedlinks_info.html',
example_list=[[0, 'moustache', 'cotton candy', ['hair', 'fluffy'],
['0', '0'], '0', "The CALLIG System", "Unknown date"]],
MODE=MODE)
@app.route('/games/forced-links', methods=['GET', 'POST'])
@login_required(role=0, group='open')
def forcedlinks_game():
"""
This function generates the prompts for forced-links. This prompt includes
2 words and an integer (i.e. the minimum number of words between the 2
words to be linked. And the time to complete it.
We currently want only the following pairs:
Noun-Noun (50%), Noun-Adjective (50%).
FIXME: We should be checking for distance between promts. We don't want
words that are too similar. They should be distant.
FIXME: Try to keep time spent in each link
"""
# min_links = random.randrange(5) + 2 # (0-4)+2 = 2-6 links
min_links = 1
rand = random.random()
if rand < 0.5: # mass from list
nouns = wn.x_rand_pos(2, 'n')
w1 = nouns[0]
w2 = nouns[1]
else: # we want to randomize the order of noun-adjective
if rand < 0.75:
w1 = wn.x_rand_pos(1, 'n')[0]
w2 = wn.x_rand_pos(1, 'a')[0]
else:
w1 = wn.x_rand_pos(1, 'a')[0]
w2 = wn.x_rand_pos(1, 'n')[0]
seconds = 45 # the max amount of time to play
return render_template('callig_forcedlinks_game.html',
seconds=seconds,
w1=w1,
w2=w2,
min_links=min_links,
MODE=MODE)
@app.route('/_save_forcedlinks', methods=['GET', 'POST'])
@login_required(role=0, group='open')
def save_forcedlinks():
if request.method == 'POST':
result = request.form
w1 = result['w1'].strip()
w2 = result['w2'].strip()
seconds = result['seconds']
username = result['username']
links = result.getlist('links') # list
time_stamps = result.getlist('timestamps') # list
# Because the way the JS is currently designed, when users submit,
# there might be a timestap with an empty string for word.
# This happens when people add a word box and don't use it before
# submission.
links_json = json.dumps(links)
timestamps_json = json.dumps(time_stamps)
language = 'eng'
timestamp = current_time()
write_forcedlinks(w1, w2, links_json, timestamps_json,
seconds, language, username, timestamp)
return forcedlinks_game()
###############################################################################
# CALLIG: HAIKU ON DEMAND
###############################################################################
@app.route('/info/haiku-on-demand', methods=['GET', 'POST'])
@login_required(role=0, group='open')
def haikuondemand_info():
base_ex = [(0,
"The Heavy Power Drill",
"The drill is unplugged",
"Like a dead and heavy man",
"Cordless and lifeless",
"The CALLIG System",
"Unknown date",
"0 seconds")]
example_list = []
exs = fetch_haikuondemand_30()
for i, ex_id in enumerate(exs.keys()):
r = exs[ex_id]
title = r[0]
l1 = r[1]
l2 = r[2]
l3 = r[3]
username = r[4]
timestamp = r[5].split()[0]
seconds = str(r[6]) + ' ' + 'seconds'
example_list.append((i, title, l1, l2, l3,
username, timestamp, seconds))
if example_list:
return render_template('haikuondemand-info.html',
example_list=example_list,
MODE=MODE)
else: # for brand-new dbs, show a system's example
return render_template('haikuondemand-info.html',
example_list=base_ex,
MODE=MODE)
@app.route('/games/haiku-on-demand', methods=['GET', 'POST'])
@login_required(role=0, group='open')
def haikuondemand_game():
rand_noun = wn.x_rand_pos(1,'n')[0]
rand_adj = wn.x_rand_pos(1,'a')[0]
seconds = 90
return render_template('haikuondemand-game.html',
seconds=seconds,
rand_noun=rand_noun,
rand_adj=rand_adj,
MODE=MODE)
@app.route('/_save_haiku-on-demand', methods=['GET', 'POST'])
@login_required(role=0, group='open')
def save_haikuondemand():
"""
Haiku does not have grammar checking; but it checks for the
correct number of syllables; in the future, if words are required
to be used, this should also be checked;
"""
if request.method == 'POST':
result = request.form
language = 'eng'
title = result['title'].strip()
l1 = result['line1'].strip() if 'line1' in result.keys() else ''
l2 = result['line2'].strip() if 'line2' in result.keys() else ''
l3 = result['line3'].strip() if 'line3' in result.keys() else ''
seconds = result['seconds']
username = result['username']
s1 = syl.num_of_syllables(l1)
s2 = syl.num_of_syllables(l2)
s3 = syl.num_of_syllables(l3)
if (l1 and l2 and l3):
if (s1 != 5) or (s2 != 7) or (s3 != 5): # SYLLABLE PROBLEM
answer = [(l1, s1), (l2, s2), (l3, s3)]
feedback = "syllable count"
write_haikuondemand_feedback(title, feedback, l1, l2, l3, s1, s2, s3,
seconds, language, username, current_time())
return render_template('haikuondemand-feedback.html',
answer=answer,
title=title,
MODE=MODE)
else:
write_haikuondemand(title, l1, l2, l3,
seconds, language, username, current_time())
return haikuondemand_game()
else: # SKIPPED TITLE
write_haikuondemand(title, None, None, None,
seconds, language, username, current_time())
return haikuondemand_game()
################################################################################
# EMAIL VIEWS
################################################################################
# @app.route('/test-email-settings')
# @login_required(role=0, group='admin')
# def send_mail():
# try:
# msg = Message("Send Mail Tutorial!",
# sender="openwns@gmail.com",
# recipients=["luis.passos.morgado@gmail.com"])
# msg.body = "Yo!\nHave you heard the good word of Python???"
# mail.send(msg)
# return 'Mail sent!'
# except Exception as e:
# return(str(e))
#
#
# @app.route('/register-mail', methods=['GET', 'POST'])
# def register_mail():
# if request.method == 'POST':
# result = request.form
#
# email = result['email'].strip()
# name = result['name'].strip()
#
# pw = randomPassword()
# hashed_pw = hash_pass(pw)
#
#
#
# ########################################################################
# # Group is a field defines what uses can see and/or can access.
# # it should be a string of the form "grp1-grp2-grp3". All users should
# # start their group with "user-..." e.g. "user-grp1-grp2", while admins
# # should start with "admin-..." instead. However, order of the other
# # groups should not be relevant.
# ########################################################################
# group = 'user'
# if 'callig' in result.keys():
# group += "-callig"
#
# if 'lccapp' in result.keys():
# group += "-lccapp"
#
# if group == "user":
# group = "user-callig-lccapp"
# ########################################################################
#
#
#
# # print(email) #TEST
# # print(name) #TEST
# # print(pw) #TEST
# # print(hashed_pw) #TEST
# # print(group) #TEST
#
# # TODO: check if the email already exists... if it does, reject!
# # if it doesn't then create a new user in the DB
# # prepare an html template in case something goes wrong
# #
#
# try:
# msg = Message("Welcome!", # Subject
# sender="openwns@gmail.com",
# recipients=["luis.passos.morgado@gmail.com"])
#
# # msg.body = "..." # if a text-only version is needed
# msg.html = render_template('email-register.html',
# name=name,
# username=email,
# password=pw)
#
# mail.send(msg)
# return render_template('registration_confirmation.html')
#
# except Exception as e:
# print(str(e))
# return 'Something went wrong! Please report this.'
#
#
#
###############################################################################
# IXUE VIEWS
###############################################################################
@app.route('/ixue-jumbled', methods=['GET', 'POST'])
def ixue_jumbled():
return render_template('ixue_jumbledsents.html',
MODE=MODE)
###############################################################################
# LCC VIEWS
###############################################################################
@app.route('/upload', methods=['GET', 'POST'])
@login_required(role=0, group='open')
def upload():
return render_template('upload.html',
MODE=MODE)
@app.route('/_upload-ntucleX', methods=['GET', 'POST'])
@login_required(role=0, group='open')
def lcc_upload_ntucleX():
docx_count = 0
for root, dirs, files in os.walk(os.path.join(ROOT, 'ntucle_uploads')):
for fn in sorted(files):
if fn.endswith(".docx"):
docx_count += 1
print(docx_count, fn) #TEST
docx_html = lcc.docx2html(fn, db="ntucleX.db")
(docid, htmlElem, report) = lcc.parse_docx_html(docx_html,
fn,
"ntucleX.db")
dochtml = lxml.html.tostring(htmlElem).decode('utf-8')
csql.update_html_into_doc(docid,
dochtml,
"ntucleX.db")
feedback_set = 'lcc2'
(htmlElem, report) = lcc.check_docx_html(docid,
htmlElem,
report,
feedback_set,
"ntucleX.db")
return jsonify(html="<b><br><br>Completed.</b>")
@app.route('/lcc-load-ntucleX', methods=['GET', 'POST'])
@login_required(role=0, group='open')
def lcc_load_ntucleX():
# [FIXME] We should check against the DB the existing docs by name
# then we should output all docnames into JS to be able to do
# batch assynchronous upload of all docs at once.
# rename this funciton to "prepare" ntucleX
docx_count = 0
for root, dirs, files in os.walk(os.path.join(ROOT, 'ntucle_uploads')):
for fn in sorted(files):
if fn.endswith(".docx"):
docx_count += 1
print(fn)
return render_template('lcc_load_ntucleX.html',
docx_count=docx_count,
MODE=MODE)
@app.route('/_lccReport', methods=['GET', 'POST'])
@login_required(role=0, group='open')
def lccReport():
"""
This function produces the HTML report for any given document.
The feedback_set sets which group of errors and which feedback
messages to show students. Originally, this was set to 'lcc'.
But with the current addition of new sets of errors and new error
messages, this is now a mandatory option for check_docx.
"""
filename = request.args.get('fn', None)
# feedback_set = 'lcc' # original error-set and messages
feedback_set = 'lcc2'
docx_html = lcc.docx2html(filename)
(docid, htmlElem, report) = lcc.parse_docx_html(docx_html, filename)
#######################################################################
# Insert DOCUMENT HTML into db [FIXME]
# For now it's not clear whether we want to keep the document with
# error highlights or just the structured one that comes from
# lcc.parse_docx_html; This could be moved up or down to change this.
#######################################################################
dochtml = lxml.html.tostring(htmlElem).decode('utf-8')
csql.update_html_into_doc(docid, dochtml)
(htmlElem, report) = lcc.check_docx_html(docid,
htmlElem,
report,
feedback_set)
# lxml.html.tostring returns type=bytes, must decode here
structured_html = lxml.html.tostring(htmlElem).decode('utf-8')
return jsonify(result=structured_html)
@app.route('/single-sentence', methods=['GET', 'POST'])
@login_required(role=0, group='open')
def lcc_sentence():
return render_template('lcc_sentence.html',
MODE=MODE)
@app.route('/report', methods=['GET', 'POST'])
@login_required(role=0, group='open')
def report():
"""
This function saves the uploaded file and starts the process that will
check the uploaded document. The document check is actually called
asynchronously via javascript from within the report template.
"""
passed, filename = lcc.uploadFile(current_user.id)
if passed is False:
error = """There was a problem while uploading your your file. """
error += """Please check that the file type you are using is '.docx'"""
error += """ and not '.doc', for example."""
return render_template('error.html',
error=error,
MODE=MODE)
else:
return render_template('report.html',
passed=passed,
filename=filename,
MODE=MODE)
@app.route('/_save_singlesentence', methods=['GET', 'POST'])
@login_required(role=0, group='open')
def save_lcc_sentence():
if request.method == 'POST':
result = request.form
sent = result['sentence'].strip()
username = result['username']
#######################################################################
# WRITE SENTENCE IN DATABASE
#######################################################################
docid = csql.fetch_max_doc_id() + 1
csql.insert_into_doc(docid, 'single_sentence')
sid = docid * 100000
pid = 0
csql.insert_into_sent(sid, docid, pid, sent)
word_list = lcc.pos_lemma(lcc.sent2words(sent))
for w in word_list:
wid = csql.fetch_max_wid(sid) + 1
(surface, pos, lemma) = w
csql.insert_into_word(sid, wid, surface, pos, lemma)
words = csql.fetch_words_by_sid(sid, sid)[sid]
app_errors, non_app_errors = lcc.full_check_sent(sent, words, 'lcc2')
#######################################################################
# WRITE ERRORS TO CORPUS DB
#######################################################################
all_errors = app_errors | non_app_errors
for i, (label, loc) in enumerate(all_errors):
csql.insert_into_error(sid, i, label, loc)
errors = []
for e in app_errors:
tag = e[0]
focus = e[1]
if tag in eng_feedback:
if 'lcc2' in eng_feedback[tag]:
feedback = eng_feedback[tag]['lcc2'][0].format(focus)
errors.append(feedback)
return render_template('lcc_feedback.html',
sent=sent,
errors=errors,
eng_feedback=eng_feedback,
MODE=MODE)
@app.route('/lcc-document/<db>', methods=['GET', 'POST'])
@login_required(role=0, group='admin')
def lcc_inspect_docs(db):
docs = csql.fetch_all_doc_titles(db)
return render_template('lcc_document.html',
lang='eng',
docs=docs,
db=db,
MODE=MODE)
@app.route('/_lcc_fetch_doc_html', methods=['GET', 'POST'])
@login_required(role=0, group='open')
def lcc_fetch_doc_html():
"""
"""
docid = request.args.get('id', None)
db = request.args.get('db', None)
dochtml = csql.fetch_dochtml_by_docid(docid, db)
# print(docid, db)
# print(dochtml)
return jsonify(html=dochtml)
@app.route('/_lcc_fetch_sent_html', methods=['GET', 'POST'])
@login_required(role=0, group='open')
def lcc_fetch_sent_html():
"""
"""
sid = request.args.get('id', None)
db = request.args.get('db', None)
try:
sid = int(sid[3:]) # sid123456789
except:
sid = None
db_sent, words = csql.fetch_sent_words_by_sid(sid, db)
html = render_template('lcc_sentence_details.html',
sent=db_sent,
words=words,
MODE=MODE)
return jsonify(html=html)
@app.route('/corpus-db/<db>', methods=['GET', 'POST'])
@login_required(role=0, group='admin')
def inspect_corpus_db(db):
# <!-- Things we might want: -->
# <!-- - SELECT docid, title FROM doc (doc.title can be either the file name or single_sentence) -->
# <!-- docid are just keys -->