-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathviews.py
3120 lines (2581 loc) · 148 KB
/
views.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 os.path
from django.conf import empty
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseBadRequest, HttpResponseNotAllowed, Http404, JsonResponse
from django.shortcuts import render, get_object_or_404, redirect
from django.urls import reverse
from django.contrib.auth.decorators import login_required
from django.utils.datastructures import MultiValueDictKeyError
from tagging.models import Tag, TaggedItem
from urllib.parse import quote
from django.contrib import messages
from pathlib import Path
import csv
import time
import sys
from signbank.dictionary.forms import *
from signbank.dictionary.models import Gloss
from signbank.feedback.models import *
from signbank.dictionary.update import (update_signlanguage, update_dialect)
from signbank.dictionary.update_csv import (update_simultaneous_morphology, update_blend_morphology,
update_sequential_morphology, subst_relations, subst_foreignrelations,
update_tags, subst_notes, subst_semanticfield)
import signbank.dictionary.forms
from signbank.video.models import GlossVideo, small_appendix, add_small_appendix
from signbank.dictionary.context_data import get_selected_datasets
from signbank.tools import save_media, get_two_letter_dir
from signbank.tools import (get_default_annotationidglosstranslation,
get_dataset_languages, get_datasets_with_public_glosses,
create_gloss_from_valuedict, compare_valuedict_to_gloss, compare_valuedict_to_lemma, construct_scrollbar,
get_interface_language_and_default_language_codes, detect_delimiter, split_csv_lines_header_body,
split_csv_lines_sentences_header_body, create_sentence_from_valuedict)
from signbank.dictionary.field_choices import fields_to_fieldcategory_dict
from signbank.csv_interface import (csv_create_senses, csv_update_sentences, csv_create_sentence, required_csv_columns,
choice_fields_choices)
from signbank.dictionary.translate_choice_list import machine_value_to_translated_human_value, \
check_value_to_translated_human_value
import signbank.settings.server_specific
from signbank.settings.base import *
from django.utils.translation import override, gettext_lazy as _
from urllib.parse import urlencode, urlparse
from wsgiref.util import FileWrapper, request_uri
import datetime as DT
from django.views.decorators.csrf import csrf_exempt
from django.utils.timezone import get_current_timezone
from django.core.exceptions import PermissionDenied, ObjectDoesNotExist, BadRequest
from signbank.gloss_update import api_update_gloss_fields
from django.utils.translation import gettext_lazy as _, activate
from signbank.abstract_machine import get_interface_language_api
from signbank.api_token import put_api_user_in_request
def login_required_config(f):
"""like @login_required if the ALWAYS_REQUIRE_LOGIN setting is True"""
if settings.ALWAYS_REQUIRE_LOGIN:
return login_required(f)
else:
return f
def gloss(request, glossid):
# this is public view of a gloss
try:
gloss = Gloss.objects.get(id=glossid, archived=False)
except ObjectDoesNotExist:
raise Http404
# set session variables for scroll bar
if 'search_results' in request.session.keys():
search_results = request.session['search_results']
else:
search_results = []
if search_results and len(search_results) > 0:
if request.session['search_results'][0]['href_type'] not in ['gloss', 'morpheme', 'annotatedsentence']:
# if the results have the wrong type
request.session['search_results'] = []
if 'search_type' in request.session.keys():
if request.session['search_type'] not in ['sign', 'morpheme', 'annotatedsentence',
'sign_or_morpheme', 'sign_handshape']:
# search_type is 'handshape'
request.session['search_results'] = []
else:
request.session['search_type'] = 'sign'
selected_datasets = get_selected_datasets(request)
dataset_languages = Language.objects.filter(dataset__in=selected_datasets).distinct()
show_dataset_interface = getattr(settings, 'SHOW_DATASET_INTERFACE_OPTIONS', False)
use_regular_expressions = getattr(settings, 'USE_REGULAR_EXPRESSIONS', False)
if not(request.user.has_perm('dictionary.search_gloss') or gloss.inWeb):
feedbackmessage = _('You are not allowed to see this sign.')
messages.add_message(request, messages.ERROR, feedbackmessage)
return render(request, "dictionary/word.html",
{'sensetranslations_per_language': {},
'public_title': '',
'gloss_or_morpheme': 'gloss',
'notes_groupedby_role': {},
'translations_per_language': {},
'gloss': gloss,
'active_id': glossid, # used by search_result_bar.html
'search_type': request.session['search_type'],
'annotation_idgloss': {},
'dataset_languages': dataset_languages,
'selected_datasets': selected_datasets,
'USE_REGULAR_EXPRESSIONS': use_regular_expressions,
'SHOW_DATASET_INTERFACE_OPTIONS': show_dataset_interface })
# Put translations (senses) per language in the context
sensetranslations_per_language = dict()
for language in gloss.lemma.dataset.translation_languages.all():
sensetranslations_per_language[language] = dict()
sensetranslations_for_language = dict()
for sensei, sense in enumerate(gloss.ordered_senses().all(), 1):
if sense.senseTranslations.filter(language=language).exists():
sensetranslation = sense.senseTranslations.get(language=language)
translations = sensetranslation.translations.all().order_by('index')
if translations:
keywords_list = [trans.translation.text for trans in translations]
sensetranslations_for_language[sensei] = ', '.join(keywords_list)
sensetranslations_per_language[language] = sensetranslations_for_language
# Put annotation_idgloss per language in the context
annotation_idgloss = {}
if gloss.dataset:
for language in gloss.dataset.translation_languages.all():
annotation_idgloss[language] = gloss.annotationidglosstranslation_set.filter(language=language)
else:
language = Language.objects.get(id=get_default_language_id())
annotation_idgloss[language] = gloss.annotationidglosstranslation_set.filter(language=language)
default_language = Language.objects.get(id=get_default_language_id())
public_title = gloss.annotation_idgloss(settings.LANGUAGE_CODE)
# Regroup notes
note_role_choices = FieldChoice.objects.filter(field__iexact='NoteType')
notes = gloss.definition_set.filter(published__exact=True)
notes_groupedby_role = {}
for note in notes:
note_role_machine_value = note.role.machine_value if note.role else 0
translated_note_role = machine_value_to_translated_human_value(note_role_machine_value, note_role_choices)
role_id = (note.role, translated_note_role)
if role_id not in notes_groupedby_role:
notes_groupedby_role[role_id] = []
notes_groupedby_role[role_id].append(note)
return render(request,"dictionary/word.html",
{'sensetranslations_per_language': sensetranslations_per_language,
'public_title': public_title,
'gloss_or_morpheme': 'gloss',
'notes_groupedby_role': notes_groupedby_role,
'translations_per_language': {},
'gloss': gloss,
'active_id': glossid, # used by search_result_bar.html
'search_type': request.session['search_type'],
'annotation_idgloss': annotation_idgloss,
'dataset_languages': dataset_languages,
'selected_datasets': selected_datasets,
'SHOW_DATASET_INTERFACE_OPTIONS': show_dataset_interface })
def morpheme(request, glossid):
# this is public view of a morpheme
selected_datasets = get_selected_datasets(request)
dataset_languages = Language.objects.filter(dataset__in=selected_datasets).distinct()
show_dataset_interface = getattr(settings, 'SHOW_DATASET_INTERFACE_OPTIONS', False)
use_regular_expressions = getattr(settings, 'USE_REGULAR_EXPRESSIONS', False)
# we should only be able to get a single gloss, but since the URL
# pattern could be spoofed, we might get zero or many
# so we filter first and raise a 404 if we don't get one
try:
morpheme = Morpheme.objects.get(id=glossid)
except ObjectDoesNotExist:
raise Http404
if 'search_type' in request.session.keys():
if request.session['search_type'] not in ['sign', 'morpheme', 'annotatedsentence',
'sign_or_morpheme', 'sign_handshape']:
# search_type is 'handshape'
request.session['search_results'] = []
else:
request.session['search_type'] = 'morpheme'
if not(request.user.has_perm('dictionary.search_gloss') or morpheme.inWeb):
feedbackmessage = _('You are not allowed to see this morpheme.')
messages.add_message(request, messages.ERROR, feedbackmessage)
return render(request, "dictionary/word.html",
{'sensetranslations_per_language': {},
'public_title': '',
'gloss_or_morpheme': 'morpheme',
'notes_groupedby_role': {},
'translations_per_language': {},
'gloss': morpheme,
'active_id': glossid, # used by search_result_bar.html
'search_type': request.session['search_type'],
'annotation_idgloss': {},
'dataset_languages': dataset_languages,
'selected_datasets': selected_datasets,
'USE_REGULAR_EXPRESSIONS': use_regular_expressions,
'SHOW_DATASET_INTERFACE_OPTIONS': show_dataset_interface}
)
# morphemes use translations not senses
translations_per_language = {}
if morpheme.lemma.dataset:
for language in morpheme.dataset.translation_languages.all():
translations_per_language[language] = morpheme.translation_set.filter(language=language).order_by(
'translation__index')
else:
language = Language.objects.get(id=get_default_language_id())
translations_per_language[language] = morpheme.translation_set.filter(language=language).order_by(
'translation__index')
videourl = morpheme.get_video_url()
if not os.path.exists(os.path.join(settings.MEDIA_ROOT, videourl)):
videourl = None
public_title = morpheme.annotation_idgloss(settings.LANGUAGE_CODE)
annotation_idgloss = {}
if morpheme.dataset:
for language in morpheme.dataset.translation_languages.all():
annotation_idgloss[language] = morpheme.annotationidglosstranslation_set.filter(language=language)
else:
language = Language.objects.get(id=get_default_language_id())
annotation_idgloss[language] = morpheme.annotationidglosstranslation_set.filter(language=language)
# Regroup notes
note_role_choices = FieldChoice.objects.filter(field__iexact='NoteType')
notes = morpheme.definition_set.filter(published__exact=True)
notes_groupedby_role = {}
for note in notes:
note_role_machine_value = note.role.machine_value if note.role else 0
translated_note_role = machine_value_to_translated_human_value(note_role_machine_value, note_role_choices)
role_id = (note.role, translated_note_role)
if role_id not in notes_groupedby_role:
notes_groupedby_role[role_id] = []
notes_groupedby_role[role_id].append(note)
return render(request,"dictionary/word.html",
{'sensetranslations_per_language': {},
'gloss_or_morpheme': 'morpheme',
'notes_groupedby_role': notes_groupedby_role,
'public_title': public_title,
'translations_per_language': translations_per_language,
'videofile': videourl,
'gloss': morpheme,
'annotation_idgloss': annotation_idgloss,
'active_id': glossid, # used by search_result_bar.html
'search_type': request.session['search_type'],
'DEFINITION_FIELDS' : settings.DEFINITION_FIELDS})
def video_file_path(gloss):
# returns the file system path of the video file without looking in GlossVideo
idgloss = gloss.idgloss
video_dir = settings.GLOSS_VIDEO_DIRECTORY
try:
dataset_dir = gloss.lemma.dataset.acronym
except KeyError:
dataset_dir = ""
two_letter_dir = idgloss[:2]
if len(two_letter_dir) == 1:
two_letter_dir += '-'
filename = idgloss + '-' + str(gloss.id) + ".mp4"
path = os.path.join(video_dir, dataset_dir, two_letter_dir, filename)
if hasattr(settings, 'ESCAPE_UPLOADED_VIDEO_FILE_PATH') and settings.ESCAPE_UPLOADED_VIDEO_FILE_PATH:
from django.utils.encoding import escape_uri_path
path = escape_uri_path(path)
return path
def missing_video_list(selected_datasets):
"""A list of signs that don't have an
associated video file"""
glosses = Gloss.objects.filter(archived=False, morpheme=None, lemma__dataset__in=selected_datasets)
for gloss in glosses:
gloss_video_path = video_file_path(gloss)
gloss_video = GlossVideo.objects.filter(gloss=gloss, version=0, glossvideonme=None, glossvideoperspective=None)
if not gloss_video.count():
# does not have GlossVideo object
file_path = os.path.join(settings.WRITABLE_FOLDER, gloss_video_path)
if os.path.exists(file_path.encode('utf-8')):
# there is a video file but no GlossVideo object
yield gloss, gloss_video_path
def missing_video_view(request):
"""A view for the above list"""
# check that the user is logged in
if not request.user.is_authenticated:
messages.add_message(request, messages.ERROR, _('Please login to use this functionality.'))
return HttpResponseRedirect(settings.PREFIX_URL + '/datasets/available')
selected_datasets = get_selected_datasets(request)
glosses = missing_video_list(selected_datasets)
return render(request, "dictionary/missingvideo.html",
{'glosses': glosses})
def try_code(request, pk):
"""A view for the developer to try out senses for a particular gloss"""
context = {}
selected_datasets = get_selected_datasets(request)
dataset_languages = Language.objects.filter(dataset__in=selected_datasets).distinct()
context['dataset_languages'] = dataset_languages
context['selected_datasets'] = selected_datasets
context['SHOW_DATASET_INTERFACE_OPTIONS'] = getattr(settings, 'SHOW_DATASET_INTERFACE_OPTIONS', False)
context['USE_REGULAR_EXPRESSIONS'] = getattr(settings, 'USE_REGULAR_EXPRESSIONS', False)
try:
gloss = get_object_or_404(Gloss, pk=pk, archived=False)
except ObjectDoesNotExist:
gloss = None
if not gloss or not (request.user.is_staff or request.user.is_superuser):
translated_message = _('You do not have permission to use the try command.')
return render(request, 'dictionary/warning.html',
{'warning': translated_message,
'dataset_languages': dataset_languages,
'selected_datasets': selected_datasets,
'SHOW_DATASET_INTERFACE_OPTIONS': SHOW_DATASET_INTERFACE_OPTIONS})
context['gloss'] = gloss
gloss_annotations = gloss.annotationidglosstranslation_set.all()
if gloss_annotations:
gloss_default_annotationidglosstranslation = gloss.annotationidglosstranslation_set.get(
language=gloss.lemma.dataset.default_language).text
else:
gloss_default_annotationidglosstranslation = str(gloss.id)
# Put annotation_idgloss per language in the context
context['annotation_idgloss'] = {}
for language in gloss.dataset.translation_languages.all():
try:
annotation_text = gloss.annotationidglosstranslation_set.get(language=language).text
except ObjectDoesNotExist:
annotation_text = gloss_default_annotationidglosstranslation
context['annotation_idgloss'][language] = annotation_text
senses = gloss.senses.all().order_by('glosssense')
context['senses'] = senses
sense_to_similar_senses = dict()
for sns in senses:
sense_to_similar_senses[sns] = sns.get_senses_with_similar_sensetranslations_dict(gloss)
context['sense_to_similar_senses'] = sense_to_similar_senses
return render(request, 'dictionary/try.html', context)
# this method is called from the Signbank menu bar
def add_new_sign(request):
context = {}
selected_datasets = get_selected_datasets(request)
default_dataset_acronym = settings.DEFAULT_DATASET_ACRONYM
default_dataset = Dataset.objects.get(acronym=default_dataset_acronym)
if len(selected_datasets) == 1:
last_used_dataset = selected_datasets[0].acronym
elif 'last_used_dataset' in request.session.keys():
last_used_dataset = request.session['last_used_dataset']
else:
last_used_dataset = None
context['last_used_dataset'] = last_used_dataset
dataset_languages = Language.objects.filter(dataset__in=selected_datasets).distinct()
context['dataset_languages'] = dataset_languages
context['default_dataset_lang'] = dataset_languages.first().language_code_2char if dataset_languages else LANGUAGE_CODE
context['selected_datasets'] = selected_datasets
context['lemma_create_field_prefix'] = LemmaCreateForm.lemma_create_field_prefix
context['SHOW_DATASET_INTERFACE_OPTIONS'] = getattr(settings, 'SHOW_DATASET_INTERFACE_OPTIONS', False)
context['USE_REGULAR_EXPRESSIONS'] = getattr(settings, 'USE_REGULAR_EXPRESSIONS', False)
context['add_gloss_form'] = GlossCreateForm(request.GET, languages=dataset_languages, user=request.user,
last_used_dataset=last_used_dataset)
return render(request, 'dictionary/add_gloss.html', context)
def add_new_morpheme(request):
context = {}
selected_datasets = get_selected_datasets(request)
dataset_languages = Language.objects.filter(dataset__in=selected_datasets).distinct()
context['dataset_languages'] = dataset_languages
context['default_dataset_lang'] = dataset_languages.first().language_code_2char if dataset_languages else LANGUAGE_CODE
default_dataset_acronym = settings.DEFAULT_DATASET_ACRONYM
default_dataset = Dataset.objects.get(acronym=default_dataset_acronym)
if len(selected_datasets) == 1:
last_used_dataset = selected_datasets[0].acronym
elif 'last_used_dataset' in request.session.keys():
last_used_dataset = request.session['last_used_dataset']
else:
last_used_dataset = None
context['last_used_dataset'] = last_used_dataset
context['SHOW_DATASET_INTERFACE_OPTIONS'] = getattr(settings, 'SHOW_DATASET_INTERFACE_OPTIONS', False)
context['USE_REGULAR_EXPRESSIONS'] = getattr(settings, 'USE_REGULAR_EXPRESSIONS', False)
form = MorphemeCreateForm(request.GET, languages=dataset_languages, user=request.user, last_used_dataset=last_used_dataset)
context['add_morpheme_form'] = form
context['lemma_create_field_prefix'] = LemmaCreateForm.lemma_create_field_prefix
return render(request,'dictionary/add_morpheme.html',context)
def import_csv_create(request):
user = request.user
import guardian
user_datasets = guardian.shortcuts.get_objects_for_user(user, 'change_dataset', Dataset)
user_datasets_names = [dataset.acronym for dataset in user_datasets]
selected_datasets = get_selected_datasets(request)
dataset_languages = get_dataset_languages(selected_datasets)
selected_dataset_acronyms = [dataset.acronym for dataset in selected_datasets]
translation_languages_dict = {}
# this dictionary is used in the template, it maps each dataset to a list of tuples
# (English name of dataset, language_code_2char)
for dataset_object in user_datasets:
translation_languages_dict[dataset_object] = []
for language in dataset_object.translation_languages.all():
language_name = getattr(language, settings.DEFAULT_LANGUAGE_HEADER_COLUMN['English'])
language_tuple = (language_name, language.language_code_2char)
translation_languages_dict[dataset_object].append(language_tuple)
seen_datasets = []
seen_dataset_names = []
# fatal errors are duplicate column headers, data in columns without headers
# column headers that do not correspond to database fields
# non-numerical gloss ids
# non-existent dataset or no permission for dataset
# attempt to create glosses in multiple datasets in the same csv
# missing Dataset column
# missing Lemma or Annotation translations required for the dataset during creation
# extra columns during creation:
# (although these are ignored, it is advised to remove them to make it clear the data is not being stored)
encoding_error = False
uploadform = signbank.dictionary.forms.CSVUploadForm
changes = []
error = []
creation = []
gloss_already_exists = []
earlier_creation_same_csv = {}
earlier_creation_annotationidgloss = {}
earlier_creation_lemmaidgloss = {}
# Propose changes
if len(request.FILES) > 0:
new_file = request.FILES['file']
try:
# files that will fail here include those renamed to .csv which are not csv
# non UTF-8 encoded files also fail
csv_text = new_file.read().decode('UTF-8-sig')
except (UnicodeDecodeError, UnicodeError):
feedback_message = _('Unrecognised format in selected CSV file.')
messages.add_message(request, messages.ERROR, feedback_message)
return render(request, 'dictionary/import_csv_create.html',
{'form': uploadform, 'stage': 0, 'changes': changes,
'creation': creation,
'gloss_already_exists': gloss_already_exists,
'error': error,
'dataset_languages': dataset_languages,
'selected_datasets': selected_datasets,
'translation_languages_dict': translation_languages_dict,
'seen_datasets': seen_datasets,
'USE_REGULAR_EXPRESSIONS': settings.USE_REGULAR_EXPRESSIONS,
'SHOW_DATASET_INTERFACE_OPTIONS': settings.SHOW_DATASET_INTERFACE_OPTIONS})
fatal_error = False
csv_lines = re.compile('[\r\n]+').split(csv_text) # split csv text on any combination of new line characters
delimiter_okay, found_delimiter = detect_delimiter(csv_lines)
delimiter_okay, keys_found, missing_keys, extra_keys, csv_header, csv_body = split_csv_lines_header_body(dataset_languages,
csv_lines,
found_delimiter, create_or_update='create_gloss')
if extra_keys or missing_keys or not delimiter_okay:
# this is intended to assist the user in the case that a wrong file was selected
if not delimiter_okay:
feedback_message = _('The delimiter is not comma, tab, or semicolon.')
elif extra_keys:
feedback_message = _('The header row of the csv file looks like this: ') + ', '.join(extra_keys)
else:
feedback_message = _('Some required column headers are missing: ') + ', '.join(missing_keys)
messages.add_message(request, messages.ERROR, feedback_message)
return render(request, 'dictionary/import_csv_create.html',
{'form': uploadform, 'stage': 0, 'changes': changes,
'error': error,
'dataset_languages': dataset_languages,
'selected_datasets': selected_datasets,
'translation_languages_dict': translation_languages_dict,
'seen_datasets': seen_datasets,
'USE_REGULAR_EXPRESSIONS': settings.USE_REGULAR_EXPRESSIONS,
'SHOW_DATASET_INTERFACE_OPTIONS': settings.SHOW_DATASET_INTERFACE_OPTIONS})
if '' in csv_header:
feedback_message = _('Empty Column Header Found.')
messages.add_message(request, messages.ERROR, feedback_message)
encoding_error = True
elif len(csv_header) > len(list(set(csv_header))):
feedback_message = _('Duplicate Column Header Found.')
messages.add_message(request, messages.ERROR, feedback_message)
encoding_error = True
elif 'Signbank ID' in csv_header:
feedback_message = _('Signbank ID column found.')
messages.add_message(request, messages.ERROR, feedback_message)
encoding_error = True
elif 'Dataset' not in csv_header:
feedback_message = _('The Dataset column is required.')
messages.add_message(request, messages.ERROR, feedback_message)
encoding_error = True
if encoding_error:
return render(request, 'dictionary/import_csv_create.html',
{'form': uploadform, 'stage': 0, 'changes': changes,
'creation': creation,
'gloss_already_exists': gloss_already_exists,
'error': error,
'dataset_languages': dataset_languages,
'selected_datasets': selected_datasets,
'translation_languages_dict': translation_languages_dict,
'seen_datasets': seen_datasets,
'USE_REGULAR_EXPRESSIONS': settings.USE_REGULAR_EXPRESSIONS,
'SHOW_DATASET_INTERFACE_OPTIONS': settings.SHOW_DATASET_INTERFACE_OPTIONS})
# create a template for an empty row with the desired number of columns
empty_row = [''] * len(csv_header)
for nl, line in enumerate(csv_body):
if len(line) == 0:
# this happens at the end of the file
continue
values = csv.reader([line], delimiter=found_delimiter).__next__()
if values == empty_row:
continue
# construct value_dict for row
value_dict = {}
for nv, value in enumerate(values):
if nv >= len(csv_header):
# this has already been checked above
# it's here to avoid needing an exception on the subscript [nv]
continue
value_dict[csv_header[nv]] = value
# 'Dataset' in value_dict keys, checked above
dataset_name = value_dict['Dataset'].strip()
if dataset_name not in selected_dataset_acronyms:
e3 = 'Row ' + str(nl + 2) + ': Dataset %s is not selected.' % value_dict['Dataset'].strip()
error.append(e3)
break
if dataset_name not in user_datasets_names:
e3 = 'Row '+str(nl + 2) + ': You are not allowed to change dataset %s.' % value_dict['Dataset'].strip()
error.append(e3)
break
# Check whether the user may change the dataset of the current row
if dataset_name not in seen_dataset_names:
if seen_datasets:
# already seen a dataset
# this is a different dataset
e3 = 'Row '+str(nl + 2) + ': A different dataset is mentioned.'
e4 = 'You can only create glosses for one dataset at a time.'
e5 = 'To create glosses in multiple datasets, use a separate CSV file for each dataset.'
error.append(e3)
error.append(e4)
error.append(e5)
break
# only process a dataset_name once for the csv file being imported
# catch possible empty values for dataset, primarily for pretty printing error message
if dataset_name in ['', None, 0, 'NULL']:
e_dataset_empty = 'Row '+str(nl + 2) + ': The Dataset is missing.'
error.append(e_dataset_empty)
break
try:
dataset = Dataset.objects.get(acronym=dataset_name)
except ObjectDoesNotExist:
# An error message should be returned here, the dataset does not exist
e_dataset_not_found = 'Row '+str(nl + 2) + ': Dataset %s' % value_dict['Dataset'].strip() + ' does not exist.'
error.append(e_dataset_not_found)
break
if seen_datasets and dataset not in seen_datasets:
e4 = 'You can only create glosses for one dataset at a time.'
e5 = 'To create glosses in multiple datasets, use a separate CSV file for each dataset.'
error.append(e4)
error.append(e5)
break
else:
seen_datasets.append(dataset)
seen_dataset_names.append(dataset_name)
empty_lemma_translation = False
# The Lemma ID Gloss may already exist.
# store the lemma translations for the current row in dict lemmaidglosstranslations
# for those translations, look up existing lemmas with (one of) those translations
lemmaidglosstranslations = {}
existing_lemmas = {}
existing_lemmas_list = []
new_lemmas = {}
contextual_error_messages_lemmaidglosstranslations = []
annotationidglosstranslations = {}
try:
dataset = seen_datasets[0]
except (KeyError, IndexError):
# this is kind of stupid, we already made sure a dataset was found, but python can't tell if it's been initialised
# dataset is a local variable above and we put it into the (singleton) list seen_datasets
break
translation_languages = dataset.translation_languages.all()
# check annotation translations
for language in translation_languages:
language_name = getattr(language, settings.DEFAULT_LANGUAGE_HEADER_COLUMN['English'])
annotationidglosstranslation_text = value_dict["Annotation ID Gloss (%s)" % language_name]
annotationidglosstranslations[language] = annotationidglosstranslation_text
annotationtranslation_for_this_text_language = AnnotationIdglossTranslation.objects.filter(
gloss__lemma__dataset=dataset, language=language, text__exact=annotationidglosstranslation_text)
if annotationtranslation_for_this_text_language:
error_string = ('Row ' + str(nl + 2) + ' contains an already existing Annotation ID Gloss for '
+ language_name + ': ' + annotationidglosstranslation_text)
error.append(error_string)
# check lemma translations
for language in translation_languages:
language_name = getattr(language, settings.DEFAULT_LANGUAGE_HEADER_COLUMN['English'])
column_name = "Lemma ID Gloss (%s)" % language_name
lemmaidglosstranslation_text = value_dict[column_name].strip()
# also stores empty values
lemmaidglosstranslations[language] = lemmaidglosstranslation_text
lemmatranslation_for_this_text_language = LemmaIdglossTranslation.objects.filter(
lemma__dataset=dataset, language=language, text__exact=lemmaidglosstranslation_text)
if lemmatranslation_for_this_text_language:
one_lemma = lemmatranslation_for_this_text_language[0].lemma
existing_lemmas[language.language_code_2char] = one_lemma
if not one_lemma in existing_lemmas_list:
existing_lemmas_list.append(one_lemma)
help = 'Row ' + str(nl + 2) + ": Existing Lemma ID Gloss (" + language_name + '): ' + lemmaidglosstranslation_text
contextual_error_messages_lemmaidglosstranslations.append(help)
elif not lemmaidglosstranslation_text:
# lemma translation is empty, determine if existing lemma is also empty for this language
if existing_lemmas_list:
lemmatranslation_for_this_text_language = LemmaIdglossTranslation.objects.filter(
lemma__dataset=dataset, lemma=existing_lemmas_list[0],
language=language)
if lemmatranslation_for_this_text_language:
help = 'Row ' + str(nl + 2) + ': Lemma ID Gloss (' + language_name + ') is empty'
contextual_error_messages_lemmaidglosstranslations.append(help)
empty_lemma_translation = True
else:
empty_lemma_translation = True
else:
new_lemmas[language.language_code_2char] = lemmaidglosstranslation_text
help = 'Row ' + str(nl + 2) + ': New Lemma ID Gloss (' + language_name + '): ' + lemmaidglosstranslation_text
contextual_error_messages_lemmaidglosstranslations.append(help)
if len(existing_lemmas_list) > 0:
if len(existing_lemmas_list) > 1:
e1 = 'Row '+str(nl + 2)+': The Lemma translations refer to different lemmas.'
error.append(e1)
elif empty_lemma_translation:
e1 = 'Row '+str(nl + 2)+': Exactly one lemma matches, but one of the translations in the csv is empty.'
error.append(e1)
if len(new_lemmas.keys()) and len(existing_lemmas.keys()):
e1 = 'Row '+str(nl + 2)+': Combination of existing and new lemma translations.'
error.append(e1)
elif not len(new_lemmas.keys()):
e1 = 'Row '+str(nl + 2)+': No lemma translations provided.'
error.append(e1)
if error:
# these are feedback errors, don't bother comparing the new gloss to existing values, we already found an error
continue
# put creation of value_dict for the new gloss inside an exception to catch any unexpected errors
# errors are kept track of as user feedback, but the code needs to be safe
try:
(new_gloss, already_exists, error_create, earlier_creation_same_csv, earlier_creation_annotationidgloss, earlier_creation_lemmaidgloss) \
= create_gloss_from_valuedict(value_dict,dataset,nl, earlier_creation_same_csv, earlier_creation_annotationidgloss, earlier_creation_lemmaidgloss)
except (KeyError, ValueError):
print('import csv create: got this far in processing loop before exception in row ', str(nl+2))
break
if len(error_create):
errors_found_string = '\n'.join(error_create)
error.append(errors_found_string)
else:
creation += new_gloss
# whether or not glosses mentioned in the csv file already exist is accummulated in gloss_already_exists
# one version of the template also shows these with the errors, so the user might remove extra data from the csv to reduce its size
gloss_already_exists += already_exists
continue
stage = 1
# Do changes
elif len(request.POST) > 0:
glosses_to_create = dict()
for key, new_value in request.POST.items():
# obtain tuple values for each proposed gloss
# pk is the row number in the import file!
try:
pk, fieldname = key.split('.')
if pk not in glosses_to_create.keys():
glosses_to_create[pk] = dict()
glosses_to_create[pk][fieldname] = new_value
# In case there's no dot, this is not a value we set at the previous page
except ValueError:
# when the database token csrfmiddlewaretoken is passed, there is no dot
continue
# these should be error free based on the django template import_csv_create.html
for row in glosses_to_create.keys():
dataset = glosses_to_create[row]['dataset']
try:
dataset_id = Dataset.objects.get(acronym=dataset)
except ObjectDoesNotExist:
# this is an error, this should have already been caught
e1 = 'Dataset not found: ' + dataset
error.append(e1)
continue
lemmaidglosstranslations = {}
for language in dataset_id.translation_languages.all():
lemma_id_gloss = glosses_to_create[row]['lemma_id_gloss_' + language.language_code_2char]
if lemma_id_gloss:
lemmaidglosstranslations[language] = lemma_id_gloss
# Check whether it is an existing one (correct, make a reference), ...
existing_lemmas = []
for language, term in lemmaidglosstranslations.items():
try:
existing_lemmas.append(LemmaIdglossTranslation.objects.get(lemma__dataset=dataset_id,
language=language,
text=term).lemma)
except ObjectDoesNotExist as e:
# New lemma will be created
pass
existing_lemmas_set = set(existing_lemmas)
if len(existing_lemmas) == len(lemmaidglosstranslations) and len(existing_lemmas_set) == 1:
lemma_for_gloss = existing_lemmas[0]
elif len(existing_lemmas) == 0:
with atomic():
lemma_for_gloss = LemmaIdgloss(dataset=dataset_id)
lemma_for_gloss.save()
for language, term in lemmaidglosstranslations.items():
new_lemmaidglosstranslation = LemmaIdglossTranslation(lemma=lemma_for_gloss,
language=language, text=term)
new_lemmaidglosstranslation.save()
else:
# This case should not happen, it should have been caught in stage 1
e1 = 'To create glosses in dataset ' + dataset_id.acronym + \
', the combination of Lemma ID Gloss translations should either refer ' \
'to an existing Lemma ID Gloss or make up a completely new Lemma ID gloss.'
error.append(e1)
continue
new_gloss = Gloss()
new_gloss.lemma = lemma_for_gloss
# Save the new gloss before updating it
new_gloss.save()
new_gloss.creationDate = DT.datetime.now()
new_gloss.creator.add(request.user)
new_gloss.excludeFromEcv = False
new_gloss.save()
user_affiliations = AffiliatedUser.objects.filter(user=request.user)
if user_affiliations.count() > 0:
for ua in user_affiliations:
new_affiliation, created = AffiliatedGloss.objects.get_or_create(affiliation=ua.affiliation,
gloss=new_gloss)
for language in dataset_languages:
annotation_id_gloss = glosses_to_create[row]['annotation_id_gloss_' + language.language_code_2char]
if annotation_id_gloss:
annotationidglosstranslation = AnnotationIdglossTranslation()
annotationidglosstranslation.language = language
annotationidglosstranslation.gloss = new_gloss
annotationidglosstranslation.text = annotation_id_gloss
annotationidglosstranslation.save()
stage = 2
# Show uploadform
else:
stage = 0
return render(request, 'dictionary/import_csv_create.html',
{'form': uploadform, 'stage': stage, 'changes': changes,
'creation': creation,
'gloss_already_exists': gloss_already_exists,
'error': error,
'dataset_languages': dataset_languages,
'selected_datasets': selected_datasets,
'translation_languages_dict': translation_languages_dict,
'seen_datasets': seen_datasets,
'USE_REGULAR_EXPRESSIONS': settings.USE_REGULAR_EXPRESSIONS,
'SHOW_DATASET_INTERFACE_OPTIONS': settings.SHOW_DATASET_INTERFACE_OPTIONS})
def import_csv_update(request):
user = request.user
import guardian
user_datasets = guardian.shortcuts.get_objects_for_user(user, 'change_dataset', Dataset)
user_datasets_names = [dataset.acronym for dataset in user_datasets]
selected_datasets = get_selected_datasets(request)
dataset_languages = get_dataset_languages(selected_datasets)
required_columns, language_fields, optional_columns = required_csv_columns(dataset_languages, 'update_gloss')
list_choice_fields_choices = choice_fields_choices()
translation_languages_dict = {}
# this dictionary is used in the template, it maps each dataset to a list of
# tuples: (English name of dataset, language_code_2char)
for dataset_object in user_datasets:
translation_languages_dict[dataset_object] = []
for language in dataset_object.translation_languages.all():
language_name = getattr(language, settings.DEFAULT_LANGUAGE_HEADER_COLUMN['English'])
language_tuple = (language_name, language.language_code_2char)
translation_languages_dict[dataset_object].append(language_tuple)
seen_datasets = []
seen_dataset_names = []
# fatal errors are duplicate column headers, data in columns without headers
# column headers that do not correspond to database fields
# non-numerical gloss ids
# non-existent dataset or no permission for dataset
# attempt to create glosses in multiple datasets in the same csv
# missing Dataset column
# missing Lemma or Annotation translations required for the dataset during creation
# extra columns during creation:
# (although these are ignored, it is advised to remove them to make it clear the data is not being stored)
uploadform = signbank.dictionary.forms.CSVUploadForm
changes = []
error = []
creation = []
gloss_already_exists = []
earlier_updates_same_csv = []
earlier_updates_lemmaidgloss = {}
encoding_error = False
# this is needed in case the user has exported the csv first and not removed the frequency columns
# this code retrieves the column headers in English
gloss_fields = [Gloss.get_field(fname) for fname in Gloss.get_field_names()]
with override(LANGUAGE_CODE):
columns_to_skip = {field.verbose_name: field for field in gloss_fields if field.name in FIELDS['frequency']}
# this is needed to make sure the interface shows the correct language
activate(request.LANGUAGE_CODE)
# Process Input File
if len(request.FILES) > 0:
new_file = request.FILES['file']
try:
# files that will fail here include those renamed to .csv which are not csv
# non UTF-8 encoded files also fail
csv_text = new_file.read().decode('UTF-8-sig')
except (UnicodeDecodeError, UnicodeError):
feedback_message = _('Unrecognised format in selected CSV file.')
messages.add_message(request, messages.ERROR, feedback_message)
return render(request, 'dictionary/import_csv_update.html',
{'form': uploadform, 'stage': 0, 'changes': changes,
'creation': creation,
'gloss_already_exists': gloss_already_exists,
'error': error,
'dataset_languages': dataset_languages,
'selected_datasets': selected_datasets,
'optional_columns': optional_columns,
'choice_fields_choices': list_choice_fields_choices,
'translation_languages_dict': translation_languages_dict,
'seen_datasets': seen_datasets,
'USE_REGULAR_EXPRESSIONS': settings.USE_REGULAR_EXPRESSIONS,
'SHOW_DATASET_INTERFACE_OPTIONS': settings.SHOW_DATASET_INTERFACE_OPTIONS})
fatal_error = False
csv_lines = re.compile('[\r\n]+').split(csv_text) # split the csv text on any combination of new line characters
# the obtains the notes togggle
notes_toggle = 'keep'
if 'toggle_notes' in request.POST:
notes_radio = request.POST['toggle_notes']
if notes_radio == 'erase':
notes_toggle = 'erase'
# the obtains the notes assign togggle
notes_assign_toggle = 'replace'
if 'toggle_notes_assign' in request.POST:
notes_radio = request.POST['toggle_notes_assign']
if notes_radio == 'update':
notes_assign_toggle = 'update'
# the obtains the semantic field togggle
semfield_toggle = 'keep'
if 'toggle_semfield' in request.POST:
semfield_radio = request.POST['toggle_semfield']
if semfield_radio == 'erase':
semfield_toggle = 'erase'
# the obtains the semantic field assign togggle
semfield_assign_toggle = 'replace'
if 'toggle_semfield_assign' in request.POST:
semfield_radio = request.POST['toggle_semfield_assign']
if semfield_radio == 'update':
semfield_assign_toggle = 'update'
# the obtains the tags togggle
tags_toggle = 'keep'
if 'toggle_tags' in request.POST:
tags_radio = request.POST['toggle_tags']
if tags_radio == 'erase':
tags_toggle = 'erase'
delimiter_okay, found_delimiter = detect_delimiter(csv_lines)
delimiter_okay, keys_found, missing_keys, extra_keys, csv_header, csv_body = split_csv_lines_header_body(dataset_languages,
csv_lines,
found_delimiter, create_or_update='update_gloss')
if extra_keys or missing_keys or not delimiter_okay:
# this is intended to assist the user in the case that a wrong file was selected
if not delimiter_okay:
feedback_message = _('The delimiter is not comma, tab, or semicolon.')
elif extra_keys:
feedback_message = _('The header row of the csv file looks like this: ') + ', '.join(extra_keys)
else:
feedback_message = _('Some required column headers are missing: ') + ', '.join(missing_keys)
messages.add_message(request, messages.ERROR, feedback_message)
return render(request, 'dictionary/import_csv_update.html',
{'form': uploadform, 'stage': 0, 'changes': changes,
'error': error,
'dataset_languages': dataset_languages,
'selected_datasets': selected_datasets,
'optional_columns': optional_columns,
'choice_fields_choices': list_choice_fields_choices,
'translation_languages_dict': translation_languages_dict,
'seen_datasets': seen_datasets,
'USE_REGULAR_EXPRESSIONS': settings.USE_REGULAR_EXPRESSIONS,
'SHOW_DATASET_INTERFACE_OPTIONS': settings.SHOW_DATASET_INTERFACE_OPTIONS})
if '' in csv_header:
feedback_message = _('Empty Column Header Found.')