forms.py
13.9 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
import re
from django.forms import ChoiceField, ModelChoiceField, ModelForm, Textarea, CharField, Form, formset_factory
from django import forms
from .models import Chunk, Document, Participant, Metadata, Keyword
from projects.ppc.models import Utterance
from collector import settings
class ChunkForm(ModelForm):
def __init__(self, doc_id=None, pk=None, *args, **kwargs):
super(ChunkForm, self).__init__(*args, **kwargs)
self.document_id = doc_id
self.old_sequence = self.instance.sequence
if pk is not None: # adding a new chunk
self.prev_chunk = Chunk.objects.get(pk=pk)
self.fields['sequence'].initial = self.prev_chunk.sequence + 1
else:
self.prev_chunk = None
self.fields['sequence'].initial = 0
def save(self, commit=True):
if self.document_id:
if self.prev_chunk is not None:
next_chunks = Document.objects.get(id=self.document_id).chunks. \
filter(sequence__gt=self.prev_chunk.sequence)
else: # adding a chunk at the beginning of a list of chunks
next_chunks = Document.objects.get(id=self.document_id).chunks.order_by('sequence')
if next_chunks.first() is not None and next_chunks.first().sequence == self.cleaned_data['sequence']:
for chunk in next_chunks:
chunk.sequence += 1
chunk.save()
chunk, _ = Chunk.objects.get_or_create(document=Document.objects.get(id=self.document_id),
sequence=self.cleaned_data['sequence'],
text=self.cleaned_data['text'])
else:
new_chunk_seq = self.cleaned_data['sequence']
try:
doc = Document.objects.get(id=self.instance.document.id)
doc.chunks.get(sequence=new_chunk_seq) # if the new sequence is the same as other chunk's sequence
if self.old_sequence > new_chunk_seq:
chunks_to_move = doc.chunks.filter(sequence__gte=new_chunk_seq,
sequence__lt=self.old_sequence)
if chunks_to_move is not None:
for chunk in chunks_to_move:
chunk.sequence += 1
chunk.save()
elif self.old_sequence < new_chunk_seq:
chunks_to_move = doc.chunks.filter(sequence__gt=self.old_sequence,
sequence__lte=new_chunk_seq)
if chunks_to_move is not None:
for chunk in chunks_to_move:
chunk.sequence -= 1
chunk.save()
except Chunk.DoesNotExist:
pass
chunk = super(ChunkForm, self).save(commit)
chunk.document.changed = True
chunk.document.save()
return chunk
class Meta:
model = Chunk
fields = ['sequence', 'text']
labels = {
'sequence': 'Pozycja',
'text': 'Tekst'
}
class SubchunkForm(ModelForm):
def __init__(self, chunk_pk=None, *args, **kwargs):
super(SubchunkForm, self).__init__(*args, **kwargs)
self.chunk_pk = chunk_pk
if chunk_pk:
chunk = Chunk.objects.get(pk=chunk_pk)
if chunk.utterances.exists():
self.fields['sequence'].initial = chunk.utterances.last().sequence + 1
else:
self.fields['sequence'].initial = 0
self.fields['speaker'].queryset = chunk.document.participants.filter(type='person')
else:
self.fields['speaker'].queryset = self.instance.chunk.document.participants.filter(type='person')
def save(self, commit=True):
if self.chunk_pk:
utt, _ = Utterance.objects.get_or_create(chunk=Chunk.objects.get(pk=self.chunk_pk),
sequence=self.cleaned_data['sequence'],
text=self.cleaned_data['text'],
speaker=self.cleaned_data['speaker'])
else:
utt = super(SubchunkForm, self).save(commit)
utt.chunk.document.changed = True
utt.chunk.document.save()
return utt
class Meta:
model = Utterance
fields = ['sequence', 'speaker', 'text']
labels = {
'sequence': 'Pozycja',
'speaker': 'Mówca',
'text': 'Tekst'
}
class ParticipantForm(ModelForm):
def __init__(self, doc_id=None, *args, **kwargs):
super(ParticipantForm, self).__init__(*args, **kwargs)
self.document_id = doc_id
if self.document_id:
document = Document.objects.get(id=doc_id)
if document.participants.exists():
self.fields['order'].initial = document.participants.filter(type='person').last().order + 1
else:
self.fields['order'].initial = 0
self.fields['type'].initial = 'person'
self.fields['type'].disabled = True
self.fields['abbrev'].widget = Textarea(attrs={'rows': 2})
self.fields['name'].widget = Textarea(attrs={'rows': 2})
roles_choices = [(role, role) for role in
Participant.objects.filter(type='person').order_by().values_list('role', flat=True).distinct()]
self.fields['role'] = ChoiceField(choices=roles_choices)
self.fields['role'].initial = 'speaker'
def clean(self):
cleaned_data = super(ParticipantForm, self).clean()
xml_id_pattern = re.compile(r'^[a-zA-Z_][a-zA-Z_.\d-]*$')
if 'abbrev' in cleaned_data and not xml_id_pattern.match(cleaned_data['abbrev']):
self.add_error('abbrev', 'Identyfikator musi być zgodny ze standardem XML.')
def save(self, commit=True):
if self.document_id:
participant, _ = Participant.objects.get_or_create(document=Document.objects.get(id=self.document_id),
abbrev=self.cleaned_data['abbrev'],
name=self.cleaned_data['name'],
order=self.cleaned_data['order'],
role=self.cleaned_data['role'],
type=self.cleaned_data['type'])
else:
participant = super(ParticipantForm, self).save(commit)
participant.document.changed = True
participant.document.save()
return participant
class Meta:
model = Participant
fields = ['order', 'abbrev', 'name', 'role', 'type']
labels = {
'order': 'Pozycja',
'abbrev': 'Identyfikator',
'name': 'Nazwa',
'role': 'Rola',
'type': 'Typ'
}
class AuthorForm(ModelForm):
def __init__(self, doc_id=None, *args, **kwargs):
super(AuthorForm, self).__init__(*args, **kwargs)
self.document_id = doc_id
if self.document_id:
document = Document.objects.get(id=doc_id)
if document.participants.exists():
self.fields['order'].initial = document.participants.all().last().order + 1
else:
self.fields['order'].initial = 0
self.fields['name'].widget = Textarea(attrs={'rows': 1})
roles_choices = (
('author', 'autor'),
('translator', 'tłumacz')
)
self.fields['role'] = ChoiceField(choices=roles_choices, label="Rola")
def save(self, commit=True):
if self.document_id:
author, _ = Participant.objects.get_or_create(document=Document.objects.get(id=self.document_id),
order=self.cleaned_data['order'],
name=self.cleaned_data['name'],
gender=self.cleaned_data['gender'],
role=self.cleaned_data['role'],
type='person')
else:
author = super(AuthorForm, self).save(commit)
author.document.changed = True
author.document.save()
return author
class Meta:
model = Participant
fields = ['order', 'role', 'name', 'gender']
labels = {
'order': 'Pozycja',
'name': 'Nazwa',
'gender': 'Płeć'
}
class MetadataForm(ModelForm):
def __init__(self, doc_id=None, *args, **kwargs):
super(MetadataForm, self).__init__(*args, **kwargs)
self.document_id = doc_id
self.fields['name'].attrs = {'class': 'autoComplete'}
self.fields['value'].widget = Textarea(attrs={'rows': 1})
if self.document_id is not None:
document = Document.objects.get(pk=self.document_id)
initial_sequence = self.get_first_available_sequence(document.metadata.all())
self.fields['sequence'].initial = initial_sequence
def save(self, commit=True):
if self.document_id:
metadata, _ = Metadata.objects.get_or_create(
document=Document.objects.get(id=self.document_id),
name=self.cleaned_data['name'],
sequence=self.cleaned_data['sequence'],
value=self.cleaned_data['value'])
else:
metadata = super(MetadataForm, self).save(commit)
if self.cleaned_data['sequence'] is None:
all_metadata = metadata.document.metadata.all()
sequence = self.get_first_available_sequence(all_metadata)
metadata.sequence = sequence
metadata.save()
metadata.document.changed = True
metadata.document.save()
return metadata
def get_first_available_sequence(self, metadata):
if metadata.count() > 1:
sequences = list(metadata.values_list('sequence', flat=True).order_by('sequence'))
sequences = [seq for seq in sequences if seq is not None]
for seq in range(1, max(sequences) + 2):
if seq not in sequences:
return seq
else: # first metadata of the document
return 1
class Meta:
model = Metadata
fields = ['sequence', 'name', 'value']
labels = {
'sequence': 'Kolejność',
'name': 'Nazwa',
'value': 'Wartość'
}
class DocDetailsForm(ModelForm):
def __init__(self, *args, **kwargs):
super(DocDetailsForm, self).__init__(*args, **kwargs)
self.fields['title'].widget = Textarea(attrs={'rows': 1})
def save(self, commit=True):
document = super(DocDetailsForm, self).save(commit)
document.changed = True
document.save()
return document
class Meta:
model = Document
fields = ['title', 'publication_date', 'publication_place', 'number', 'original_lang']
labels = {
'title': 'Tytuł',
'publication_date': 'Data publikacji',
'publication_place': 'Miejsce publikacji',
'number': 'Numer',
'original_lang': 'Język oryginału'
}
class SubDocDetailsForm(ModelForm):
def __init__(self, *args, **kwargs):
super(SubDocDetailsForm, self).__init__(*args, **kwargs)
self.fields['title'].widget = Textarea(attrs={'rows': 1})
def save(self, commit=True):
document = super(SubDocDetailsForm, self).save(commit)
document.changed = True
document.save()
return document
class Meta:
model = Document
fields = ['title', 'original_lang']
labels = {
'title': 'Tytuł',
'original_lang': 'Język oryginału'
}
class KeywordForm(Form):
label = CharField(max_length=200, label='Etykieta')
class DocSplitForm(ModelForm):
class ChunkChoiceField(ModelChoiceField):
def label_from_instance(self, obj):
return str(obj.sequence)
chunk_beg = ChunkChoiceField(queryset=None, label='Początek poddokumentu')
chunk_end = ChunkChoiceField(queryset=None, label='Koniec poddokumentu')
def __init__(self, *args, **kwargs):
chunks = kwargs.pop('chunks')
super(DocSplitForm, self).__init__(*args, **kwargs)
self.fields['chunk_beg'].queryset = chunks
self.fields['chunk_end'].queryset = chunks
class Meta:
model = Document
fields = ['chunk_beg', 'chunk_end']
class MoveChunkForm(ModelForm):
def __init__(self, *args, **kwargs):
poss_target_docs = kwargs.pop('poss_target_docs')
super(MoveChunkForm, self).__init__(*args, **kwargs)
self.fields['document'].label_from_instance = self.label_from_instance
self.fields['document'].queryset = poss_target_docs
@staticmethod
def label_from_instance(obj):
if obj.parent is not None:
return f'{obj} (fragment nr: {obj.sequence})'
else:
return f'{obj} (dokument główny)'
class Meta:
model = Chunk
fields = ['document']
labels = {
'document': 'Dokument docelowy'
}
class MergeChunkForm(Form):
target_chunk = ModelChoiceField(queryset=None, label="Połącz z sekcją:")
def __init__(self, *args, **kwargs):
poss_target_chunks = kwargs.pop('poss_target_chunks')
super(MergeChunkForm, self).__init__(*args, **kwargs)
self.fields['target_chunk'].label_from_instance = self.label_from_instance
self.fields['target_chunk'].queryset = poss_target_chunks
self.fields['target_chunk'].widget.attrs['required'] = 'required'
@staticmethod
def label_from_instance(obj):
if obj:
return obj.sequence