ajax_argument_realizations.py
10.1 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
# -*- coding: utf-8 -*-
#Copyright (c) 2014, Bartłomiej Nitoń
#All rights reserved.
#Redistribution and use in source and binary forms, with or without modification, are permitted provided
#that the following conditions are met:
# Redistributions of source code must retain the above copyright notice, this list of conditions and
# the following disclaimer.
# Redistributions in binary form must reproduce the above copyright notice, this list of conditions
# and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import codecs
import datetime
import os
from tempfile import mkdtemp, mkstemp
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from common.decorators import render, ajax, AjaxError
from dictionary.ajax_argument_form import argument_to_form_values, get_argument_model, \
create_argument_form, all_fields_filled, \
get_argument_from_form, validate_argument_form
from dictionary.forms import ArgRealOpinionForm
from dictionary.models import Argument, ArgRealization, ArgRealOpinion, AttributeParameterModel
from settings import PROJECT_PATH
DEFAULT_SAVE_PATH = os.path.join(PROJECT_PATH, 'tmp')
@render('show_realizations.html')
@ajax(method='post', encode_result=False)
def show_realizations(request, form_data):
form_dict = {}
error_message = u'Wypełnij wszystkie pola formularza wyboru głównego typu frazy.'
if form_data: # zaznaczono wartosci
form_dict = dict((x['name'], x['value']) for x in form_data)
# sprawdz czy wypelniono wszystkie pola formularza argumentu glownego
if not all_fields_filled(form_dict):
result = {'error_message': error_message,
'realizations': [],
'main_arg_text_rep': '',
'manage': form_dict['manage']}
else:
arg_obj = get_argument_from_form(form_dict['arg_type'], form_dict['subform_values'])
realizations = arg_obj.realizations.order_by('opinion__priority',
'argument__text_rep')
result = {'error_message': '',
'realizations': realizations,
'main_arg_text_rep': arg_obj.text_rep,
'manage': form_dict['manage']}
return result
@csrf_exempt
@render('arg_realization_form.html')
@ajax(method='post', encode_result=False)
def realization_arg_form(request, form_data, main_argument, real_id):
form_dict = {}
attr_subforms_values = []
if form_data:
form_dict = dict((x['name'], x['value']) for x in form_data)
realization_argument = get_arg_from_realization(real_id)
if realization_argument:
form_dict = {'arg_id': realization_argument.id}
arg_model = get_argument_model(form_dict)
opinion_form = create_opinion_form(real_id)
if main_argument:
form_type = 'realization_main_arg'
else:
form_type = 'realization_arg'
if form_dict: # zaznaczono wartosci
# prezentowanie formularza na podstawie reprezentacji teksowej argumentu
if form_dict['arg_id']:
argument = Argument.objects.get(id=form_dict['arg_id'])
attr_subforms_values = argument_to_form_values(argument)
elif form_dict['arg_type']:
attr_subforms_values = form_dict['subform_values']
type_form, attr_sheets = create_argument_form(arg_model=arg_model,
subforms_values=attr_subforms_values,
form_type=form_type)
return {'type_form': type_form,
'attr_sheets': attr_sheets,
'opinion_form': opinion_form,
'main_argument': main_argument}
def get_arg_from_realization(realization_id):
argument = None
if realization_id:
realization = ArgRealization.objects.get(id=realization_id)
argument = realization.argument
return argument
def create_opinion_form(realization_id):
opinion = None
if realization_id:
realization = ArgRealization.objects.get(id=realization_id)
opinion = realization.opinion
opinion_form = ArgRealOpinionForm(sel_opinion=opinion)
return opinion_form
@ajax(method='post')
def remove_realization(request, realization_id, main_arg_data):
result = {}
# sprawdz czy wypelniono wszystkie pola formularza argumentu glownego
main_arg_dict = dict((x['name'], x['value']) for x in main_arg_data)
if not all_fields_filled(main_arg_dict):
raise AjaxError('empty main argument fields')
main_arg_obj = get_argument_from_form(main_arg_dict['arg_type'],
main_arg_dict['subform_values'])
realization_obj = main_arg_obj.realizations.get(id=realization_id)
main_arg_obj.realizations.remove(realization_obj)
return result
@ajax(method='post')
def add_arg_realization(request, main_arg_data, realization_data):
result = {'added': True}
# sprawdz czy wypelniono wszystkie pola formularza argumentu glownego
main_arg_dict = dict((x['name'], x['value']) for x in main_arg_data)
main_arg_error = validate_argument_form(main_arg_dict)
if main_arg_error:
raise AjaxError(u'Główny typ frazy: %s' % main_arg_error)
# sprawdz czy wypelniono wszystkie pola formularza argumentu dodawanego jako realizacja
realization_dict = dict((x['name'], x['value']) for x in realization_data)
real_arg_error = validate_argument_form(realization_dict)
if real_arg_error:
raise AjaxError(u'Dodawanie rozwinięć typu frazy: %s' % real_arg_error)
# nie dodano opinii o realizacji
if not realization_dict['opinion']:
raise AjaxError('select opinion')
# znajdz obiekt argumentu bedacego realizacja
real_arg_obj = get_argument_from_form(realization_dict['arg_type'],
realization_dict['subform_values'])
# znajdz model argumentu bazowego
main_arg_obj = get_argument_from_form(main_arg_dict['arg_type'],
main_arg_dict['subform_values'])
opinion = ArgRealOpinion.objects.get(id=realization_dict['opinion'])
realization_obj, xx = ArgRealization.objects.get_or_create(opinion=opinion,
argument=real_arg_obj)
real_count = main_arg_obj.realizations.count()
main_arg_obj.realizations.add(realization_obj)
if real_count == main_arg_obj.realizations.count():
result['added'] = False
return result
@ajax(method='post')
def create_realizations(request, form_data):
try:
tmp_folder = mkdtemp()
os.chdir(tmp_folder)
tmpfile, tmpfilename = mkstemp(dir=tmp_folder)
os.close(tmpfile)
create_realizations_file(tmpfilename)
os.rename(tmpfilename, tmpfilename+'.txt')
file_name = tmpfilename+'.txt'
return {'file_name': file_name}
except:
raise AjaxError('creating realizations file error')
def create_realizations_file(filename):
try:
real_file = codecs.open(filename, 'wt', 'utf-8')
write_arguments_realizations(real_file)
real_file.write('\n')
write_parameters_realizations(real_file)
real_file.write('\n')
write_parameters_equivalents(real_file)
finally:
real_file.close()
def write_arguments_realizations(real_file):
real_file.write('% Phrase types expand:\n')
for arg in Argument.objects.order_by('text_rep').all():
if arg.realizations.count() > 0:
real_file.write(arg.text_rep + u'-->\n')
for real in arg.realizations.order_by('opinion__priority', 'argument__text_rep'):
real_file.write(' %s\t[%s]\n' % (real.argument.text_rep, real.opinion.value))
def write_parameters_realizations(real_file):
real_file.write('% Attributes subtypes:\n')
for param_model in AttributeParameterModel.objects.order_by('name').all():
if param_model.possible_subparams.exists():
real_file.write(param_model.name + u'-->\n')
for subparam in param_model.possible_subparams.order_by('opinion__priority', 'name'):
real_file.write(' %s\t[%s]\n' % (subparam.name, subparam.opinion.value))
def write_parameters_equivalents(real_file):
real_file.write('% Attributes equivalents:\n')
for param_model in AttributeParameterModel.objects.order_by('name').all():
if param_model.related_param_models.exists():
real_file.write(param_model.name + u'-->\n')
for equivalent_model in param_model.related_param_models.order_by('name'):
real_file.write(' %s\n' % equivalent_model.name)
def download_realizations(request, file_name):
fullpath = os.path.join(DEFAULT_SAVE_PATH, file_name)
response = None
download_file_name = '%s_%s' % ('phrase_types_expand', datetime.datetime.now().strftime('%Y%m%d'))
if file_name.endswith('.txt'):
fullpath = '/' + file_name
with open(fullpath, "r") as f:
data = f.read()
response = HttpResponse(data, mimetype='text/txt')
response['Content-Disposition'] = 'attachment; filename=%s.txt' % download_file_name
os.remove(fullpath)
os.rmdir(os.path.split(fullpath)[0])
return response