views.py
21.8 KB
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
#-*- coding:utf-8 -*-
import gzip
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.models import User, AnonymousUser
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, HttpResponse
from common.decorators import render
from common.util import make_form, GroupDict, json_decode
from dictionary.ajax_lexeme_slickgrid import LexemeQuery
from dictionary.reports import report_functions
from paginer import PaginationList
from paginer.decorators import paginated
from dictionary.forms import AddClassificationForm, ExclusionClassForm, \
AddClassificationValueForm, VocabularyForm, AddExclusionClassForm, \
AddQualifierForm, ChangeClassForm, ExportForm, MagicQualifierForm, \
TemplateChoiceForm
from dictionary.models import visible_vocabularies, PartOfSpeech, Lexeme, \
Vocabulary, Classification, ClassificationValue, Qualifier, History, \
QualifierExclusionClass, get_exclusion_classes, editable_vocabularies, \
managed_vocabularies, CrossReferenceType, LexicalClass, PatternType, \
LexemeAttribute, Gender, BorrowingSource
from dictionary.lexeme_history import lexeme_tables
from dictionary.export import LexemeExport
from dictionary.wsjp import make_data
@login_required
def main(request):
if request.user.has_perm('dictionary.view_lexeme'):
return HttpResponseRedirect(reverse('lexeme_view'))
if request.user.has_perm('dictionary.view_pattern'):
return HttpResponseRedirect(reverse('pattern_view'))
if request.user.has_perm('dictionary.manage_vocabulary') or \
request.user.has_perm('auth.add_user'):
return HttpResponseRedirect(reverse('management_menu'))
if request.user.has_perm('dictionary.export_lexemes'):
return HttpResponseRedirect(reverse('export'))
return HttpResponseRedirect(reverse('auth_login')) # niezbyt prawdopodobne
@permission_required('dictionary.view_lexeme')
@render('lexeme_view.html')
def lexeme_view(request):
exclusion_classes = get_exclusion_classes()
visible = visible_vocabularies(request.user)
editable_vocabs = editable_vocabularies(request.user)
vocabs = {}
for v in editable_vocabs:
vocabs.update(dict((str(q.pk), v.id) for q in v.qualifiers.all()))
qualifier_options = [(0, u'(puste)')]
lexeme_qualifier_options = [(0, u'(puste)')]
form_qualifier_options = [(0, u'(puste)')]
for vocab in visible:
qualifiers = vocab.qualifiers.all()
if qualifiers:
qualifier_options.append((0, u'--%s--' % vocab.id))
lexeme_qualifier_options.append((0, u'--%s--' % vocab.id))
form_qualifier_options.append((0, u'--%s--' % vocab.id))
for q in vocab.qualifiers.all():
qualifier_options.append((q.pk, q.label))
if q.type != Qualifier.TYPE_FORM:
lexeme_qualifier_options.append((q.pk, q.label))
if q.type != Qualifier.TYPE_SCOPE:
form_qualifier_options.append((q.pk, q.label))
classifications = Classification.objects.filter(
vocabularies__in=visible).distinct()
cv_options = []
for classification in classifications:
cv_options.append((0, '--%s--' % classification.name))
cv_options += classification.make_choices()
cr_type_options = []
for cr_type in CrossReferenceType.objects.order_by('symbol'):
cr_type_options.append(
(cr_type.pk,
'%s %s->%s' % (cr_type.symbol, cr_type.from_pos, cr_type.to_pos)))
default_owner = request.user.usersettings.default_owner
if not default_owner and len(editable_vocabs) == 1:
default_owner = editable_vocabs[0]
extra_attrs = []
for la in LexemeAttribute.objects.all():
attr = {'id': la.id, 'name': la.name, 'closed': la.closed}
if attr['closed']:
attr['options'] = [(0, u'(puste)')] + [
(v.id, v.value) for v in la.values.all()]
extra_attrs.append(attr)
js_vars = {
'ajax_get_page': reverse('get_lexemes'),
'ajax_inflection_tables': reverse('inflection_tables'),
'ajax_history_table': reverse('history_table'),
'ajax_odm_forms': reverse('odm_forms'),
'ajax_edit_form': reverse('lexeme_edit_form'),
'ajax_update_lexeme': reverse('update_lexeme'),
'ajax_search_index': reverse('search_index'),
'ajax_row_index': reverse('row_index'),
'ajax_save_filter': reverse('save_filter'),
'ajax_get_filters': reverse('get_filters'),
'ajax_delete_filter': reverse('delete_filter'),
'ajax_table_preview': reverse('table_preview'),
'ajax_new_lip_row': reverse('new_lip_edit_row'),
'ajax_new_cr_row': reverse('new_cross_reference_row'),
'ajax_save_columns': reverse('save_columns'),
'ajax_delete_lexeme': reverse('delete_lexeme'),
'ajax_prompter_list': reverse('prompter_list'),
'ajax_check_pos': reverse('check_pos'),
'ajax_check_pattern': reverse('check_pattern'),
'ajax_check_classifications': reverse('check_classifications'),
'ajax_save_default_owner': reverse('save_default_owner'),
'ajax_create_lexeme': reverse('create_lexeme'),
'ajax_classification_forms': reverse('classification_forms'),
'ajax_extra_attributes': reverse('extra_attributes'),
'ajax_check_attributes': reverse('check_attributes'),
'ajax_homonym_count': reverse('homonym_count'),
'ajax_cr_homonyms': reverse('cr_homonyms'),
'ajax_new_action_row': reverse('new_action_row'),
'ajax_dynamic_fields': reverse('dynamic_action_fields'),
'ajax_execute_actions': reverse('execute_group_actions'),
'ajax_export_list': reverse('export_list'),
'ajax_create_derivatives': reverse('create_derivatives'),
'ajax_clone_lexeme': reverse('clone_lexeme'),
'vocabs': vocabs,
'visible_vocabularies': [(v.id, v.id) for v in visible],
'parts_of_speech': [
(pos.symbol, pos.symbol) for pos in PartOfSpeech.objects.all()],
'lexeme_qualifier_options': lexeme_qualifier_options,
'form_qualifier_options': form_qualifier_options,
'qualifier_options': qualifier_options,
'cv_options': cv_options,
'status_options': Lexeme.STATUS_CHOICES,
'cr_type_options': cr_type_options,
'gender_options': [(g.id, g.symbol) for g in Gender.objects.all()],
'pattern_type_options': PatternType.options(),
'bs_options': [(0, u'(puste)')] + [
(bs.id, bs.label) for bs in BorrowingSource.objects.all()],
'commonness': Classification.objects.get(name=u'pospolitość').pk,
'exclusion_classes': exclusion_classes,
'auto_search': request.user.usersettings.incremental_search,
'default_owner': default_owner.id if default_owner else '',
'extra_attributes': extra_attrs,
}
session_variables = ('filter', 'sort_rules', 'columns')
for var in session_variables:
if var in request.session:
js_vars[var] = request.session[var]
return {'js_vars': js_vars, 'editable_vocabularies': editable_vocabs}
@render('reader_view.html')
def reader_view(request):
visible = visible_vocabularies(AnonymousUser())
vocabs = {}
qualifier_options = [(0, u'(puste)')]
lexeme_qualifier_options = [(0, u'(puste)')]
form_qualifier_options = [(0, u'(puste)')]
for vocab in visible:
qualifiers = vocab.qualifiers.all()
if qualifiers:
qualifier_options.append((0, u'--%s--' % vocab.id))
lexeme_qualifier_options.append((0, u'--%s--' % vocab.id))
form_qualifier_options.append((0, u'--%s--' % vocab.id))
for q in vocab.qualifiers.all():
qualifier_options.append((q.pk, q.label))
if q.type != Qualifier.TYPE_FORM:
lexeme_qualifier_options.append((q.pk, q.label))
if q.type != Qualifier.TYPE_SCOPE:
form_qualifier_options.append((q.pk, q.label))
classifications = Classification.objects.filter(
vocabularies__in=visible).distinct()
cv_options = []
for classification in classifications:
cv_options.append((0, '--%s--' % classification.name))
cv_options += classification.make_choices()
cr_type_options = []
for cr_type in CrossReferenceType.objects.order_by('symbol'):
cr_type_options.append(
(cr_type.pk,
'%s %s->%s' % (cr_type.symbol, cr_type.from_pos, cr_type.to_pos)))
extra_attrs = []
for la in LexemeAttribute.objects.all():
attr = {'id': la.id, 'name': la.name, 'closed': la.closed}
if attr['closed']:
attr['options'] = [(0, u'(puste)')] + [
(v.id, v.value) for v in la.values.all()]
extra_attrs.append(attr)
js_vars = {
'ajax_get_page': reverse('get_lexemes'),
'ajax_inflection_tables': reverse('inflection_tables'),
'ajax_search_index': reverse('search_index'),
'ajax_search_by_form': reverse('search_by_form'),
'ajax_row_index': reverse('row_index'),
'ajax_save_filter': reverse('save_filter'),
'ajax_get_filters': reverse('get_filters'),
'ajax_delete_filter': reverse('delete_filter'),
'ajax_save_columns': reverse('save_columns'),
'ajax_export_list': reverse('export_list'),
'vocabs': vocabs,
'visible_vocabularies': [(v.id, v.id) for v in visible],
'parts_of_speech': [
(pos.symbol, pos.symbol) for pos in PartOfSpeech.objects.all()],
'lexeme_qualifier_options': lexeme_qualifier_options,
'form_qualifier_options': form_qualifier_options,
'qualifier_options': qualifier_options,
'cv_options': cv_options,
'status_options': Lexeme.STATUS_CHOICES,
'cr_type_options': cr_type_options,
'gender_options': [(g.id, g.symbol) for g in Gender.objects.all()],
'pattern_type_options': PatternType.options(),
'commonness': Classification.objects.get(name=u'pospolitość').pk,
'auto_search': True,
'extra_attributes': extra_attrs,
}
session_variables = ('filter', 'sort_rules', 'columns')
for var in session_variables:
if var in request.session:
js_vars[var] = request.session[var]
return {'js_vars': js_vars}
@permission_required('dictionary.view_pattern')
@render()
def pattern_view(request):
lexical_class_options = [
(lc.symbol, lc.symbol) for lc in LexicalClass.objects.all()]
pattern_types = GroupDict()
editable_vocabs = editable_vocabularies(request.user)
vocabs = {}
for v in editable_vocabs:
vocabs.update(dict((str(q.pk), v.id) for q in v.qualifiers.all()))
js_vars = {
'ajax_get_page': reverse('get_patterns'),
'ajax_edit_form': reverse('pattern_edit_form'),
'ajax_update_pattern': reverse('update_pattern'),
'ajax_search_index': reverse('patterns_search_index'),
'ajax_save_columns': reverse('patterns_save_columns'),
'ajax_new_ending_row': reverse('new_ending_row'),
'ajax_create_pattern': reverse('create_pattern'),
'exclusion_classes': get_exclusion_classes(),
'auto_search': request.user.usersettings.incremental_search,
'lexical_class_options': lexical_class_options,
'pattern_type_options': PatternType.options(),
'vocabs': vocabs,
}
session_variables = (
'pattern-filter',
'pattern-sort_rules',
'pattern-columns',
)
for var in session_variables:
if var in request.session:
js_name = var.split('-', 1)[1]
js_vars[js_name] = request.session[var]
return {'js_vars': js_vars}
@login_required
@render()
def tasks(request):
return {}
@login_required
@render()
def reports(request):
report_lists = {}
for report_fun in report_functions:
report_lists.update(report_fun())
return {
'report_lists': report_lists
}
@login_required
@render()
def management_menu(request):
return {}
@permission_required('dictionary.manage_vocabulary')
@render()
def manager_view(request):
to_return = {
'users': User.objects.order_by('username'),
'vocabularies_info': [
(v, request.user in v.all_managers(),
v.all_viewers(), v.all_editors(), v.all_managers())
for v in managed_vocabularies(request.user).order_by('id')],
'js_vars': {
'ajax_add_vocabulary': reverse('add_vocabulary'),
#'ajax_get_permissions': reverse('vocabulary_permissions'),
'ajax_set_permission': reverse('set_vocabulary_permission'),
},
}
return to_return
@permission_required('dictionary.manage_vocabulary')
@render()
def manage_classifications(request):
to_return = {}
add_form = make_form(request, AddClassificationForm)
if add_form.is_valid():
add_form.save()
to_return['add_form'] = add_form
if request.POST.get('det') == 'value_form':
add_form = AddClassificationValueForm(data=request.POST)
if add_form.is_valid():
add_form.save()
if request.POST.get('det') == 'vocabulary_form':
form = VocabularyForm(
data=request.POST, queryset=managed_vocabularies(request.user))
if form.is_valid():
c = form.cleaned_data['classification']
v = form.cleaned_data['vocabulary']
c.vocabularies.add(v) #add
if request.POST.get('det') == 'value_remove':
pk = int(request.POST['id'])
try:
cv = ClassificationValue.objects.get(pk=pk)
cv.deleted = True
cv.save()
except ClassificationValue.DoesNotExist:
pass
if request.POST.get('det') == 'value_rename':
pk = int(request.POST['id'])
label = request.POST['new_name']
try:
v = ClassificationValue.objects.get(pk=pk)
v.label = label
v.save()
except ClassificationValue.DoesNotExist:
pass
if request.POST:
return HttpResponseRedirect(reverse('manage_classifications'))
classification_forms = []
for c in Classification.objects.all():
value_form = AddClassificationValueForm(classification=c)
vocabs = managed_vocabularies(request.user)
using = c.vocabularies.all() & vocabs
other = vocabs.exclude(pk__in=using.values_list('pk', flat=True))
vocab_form = VocabularyForm(classification=c, queryset=other)
classification_forms.append((c, value_form, vocab_form, using))
to_return['classification_forms'] = classification_forms
return to_return
@permission_required('dictionary.manage_vocabulary')
@render()
def manage_qualifiers(request):
det = request.POST.get('det')
if det == 'add_exclusion_class':
form = AddExclusionClassForm(data=request.POST)
if form.is_valid():
form.save()
if det == 'remove_exclusion_class':
form = ExclusionClassForm(data=request.POST)
if form.is_valid():
ec = form.cleaned_data['ec']
ec.delete()
if det == 'add_qualifier':
form = AddQualifierForm(data=request.POST)
if form.is_valid():
form.save()
prefix = q = None
for name, _value in request.POST.iteritems():
if name.startswith('cec'):
prefix = name.split('-')[0]
q = Qualifier.objects.get(pk=int(prefix[3:]))
break
if prefix:
form = ChangeClassForm(data=request.POST, instance=q, prefix=prefix)
if form.is_valid():
form.save()
if det == 'remove_qualifier':
pk = int(request.POST['id'])
try:
q = Qualifier.objects.get(pk=pk)
q.deleted = True
q.save()
except Qualifier.DoesNotExist:
pass
if request.POST:
return HttpResponseRedirect(reverse('manage_qualifiers'))
to_return = {}
form_list = []
for vocabulary in managed_vocabularies(request.user):
add_exclusion_class_form = AddExclusionClassForm(vocabulary=vocabulary)
empty_ec = QualifierExclusionClass.objects.filter(
vocabulary=vocabulary).extra(where=[
'not exists (select * from kwalifikatory '
'where klasa = klasy_wykluczania.id)'])
if empty_ec:
remove_exclusion_class_form = ExclusionClassForm(queryset=empty_ec)
else:
remove_exclusion_class_form = None
add_qualifier_form = AddQualifierForm(vocabulary=vocabulary)
qualifiers = Qualifier.objects.filter(vocabulary=vocabulary)
qualifier_forms = []
for q in qualifiers:
change_class_form = ChangeClassForm(instance=q,
prefix='cec%s' % q.pk)
qualifier_forms.append((q, change_class_form))
form_list.append(
(vocabulary.id, add_exclusion_class_form,
remove_exclusion_class_form,
add_qualifier_form, qualifier_forms))
to_return['form_list'] = form_list
return to_return
@permission_required('dictionary.view_lexeme')
@render('history_view.html')
@paginated
def history_view(request):
paginer = PaginationList()
lexeme_history = History.objects.exclude(lexeme=None).distinct().values(
'lexeme', 'user', 'transaction_began')
pattern_history = History.objects.exclude(pattern=None).distinct().values(
'pattern', 'user', 'transaction_began')
paginer.add('lexeme_items', 'lexeme_history', {
'columns': ('lexeme',),
'order_by': '-transaction_began',
'filters': [('user', 'ne', u'Kuźniobot')],
'sort_fields': (),
'filter_fields': ('user', 'time_from', 'time_to'),
})
paginer.add('pattern_items', 'pattern_history', {
'columns': ('pattern',),
'order_by': '-transaction_began',
'filters': [('user', 'ne', u'Kuźniobot')],
'sort_fields': (),
'filter_fields': ('user', 'time_from', 'time_to'),
})
return {
'lexeme_tables': lexeme_tables(lexeme_history),
'show_lexemes': True,
'paginer': paginer,
}
@permission_required('dictionary.export_lexemes')
@render()
def export(request):
if request.GET:
form = ExportForm(user=request.user, data=request.GET)
if form.is_valid():
data = {
'vocabs': [v.id for v in form.cleaned_data['vocabs']],
'antivocabs': [v.id for v in form.cleaned_data['antivocabs']],
'variant': form.cleaned_data['variant'].id,
}
#data['excluding_qualifiers'] = [
# q.pk for q in form.cleaned_data['excluding_qualifiers']]
magic_ids = set()
magic_qualifiers = []
normal_qualifiers = []
for key in request.GET:
split_key = key.split('-')
if key.startswith('magic') and split_key[0] not in magic_ids:
i, name = split_key
magic_ids.add(i)
magic_form = MagicQualifierForm(prefix=i, data=request.GET)
if magic_form.is_valid():
regex = magic_form.cleaned_data['regex']
if regex:
magic_qualifiers.append(
(
regex,
magic_form.cleaned_data['qualifier'].pk))
else:
normal_qualifiers.append(
magic_form.cleaned_data['qualifier'].pk)
data['magic_qualifiers'] = magic_qualifiers
data['excluding_qualifiers'] = normal_qualifiers
data['refl'] = form.cleaned_data['refl']
data['commonness'] = form.cleaned_data['commonness']
###
response = HttpResponse(content_type='application/x-gzip')
export_gz = gzip.GzipFile(fileobj=response, mode='w')
LexemeExport(data=data, output_file=export_gz).export()
filename = 'eksport.tab.gz'
response['Content-Disposition'] = (
'attachment; filename=%s' % filename)
return response
else:
form = ExportForm(user=request.user)
vocabs = {}
for v in visible_vocabularies(request.user):
vocabs.update(dict((str(q.pk), v.id) for q in v.qualifiers.all()))
js_vars = {
'vocabs': vocabs,
'ajax_new_qualifier_row': reverse('magic_qualifier_row'),
'ajax_save_export_data': reverse('save_export_data'),
'ajax_get_export_data': reverse('get_export_data'),
'ajax_delete_export_data': reverse('delete_export_data'),
}
return {'form': form, 'js_vars': js_vars}
@permission_required('dictionary.view_lexeme')
def export_list(request):
filter = json_decode(request.GET['filter'])
sort_rules = json_decode(request.GET['sort_rules'])
columns = json_decode(request.GET['columns'])
filename = request.GET.get('filename') or 'lista.txt'
response = HttpResponse(content_type='text/plain')
query = LexemeQuery(
filter=filter, sort_rules=sort_rules, user=request.user)
query.export_list(columns, response)
response['Content-Disposition'] = ('attachment; filename=%s' % filename)
return response
def wsjp_table(request, entry):
data = make_data(entry)
result = '\n'.join(
'\t'.join(['%s'] * len(data_row)) % data_row for data_row in data)
return HttpResponse(result, content_type="text/plain; charset=utf-8")
@permission_required('dictionary.manage_vocabulary')
@render('table_view.html')
def table_view(request):
js_vars = {
'ajax_load_template': reverse('table_edit_form'),
'ajax_template_row': reverse('new_template_row'),
'ajax_preview_form': reverse('template_preview_form'),
'ajax_load_preview': reverse('template_preview'),
'ajax_save_template': reverse('save_template'),
}
return {'form': TemplateChoiceForm(), 'js_vars': js_vars}