Commit 2d719d0f0c20a4f565a4bdf7ebeea50927d98c77

Authored by Bartłomiej Nitoń
1 parent 5e471497

Working on automatic semantic reconnection.

common/js_to_obj.py
... ... @@ -125,7 +125,7 @@ def jsArgToObj(argument):
125 125 arg_obj = Argument.objects.get(text_rep=argument['text_rep'])
126 126 return arg_obj
127 127  
128   -def frameObjToSerializableDict(lemma, frame):
  128 +def frameObjToSerializableDict(lemma, frame, with_connections=False):
129 129 frame_opinion = ''
130 130 frame_opinions_tab = lemma.frame_opinions.filter(frame__text_rep=frame.text_rep)
131 131 if frame_opinions_tab:
... ... @@ -155,11 +155,16 @@ def frameObjToSerializableDict(lemma, frame):
155 155 'tooltip' : ''}
156 156  
157 157 for argument in position['arguments']:
  158 + connections = []
  159 + if with_connections:
  160 + entry = lemma.entry_obj
  161 + connections = entry.matching_connections(frame, position['position'], argument)
158 162 argument_dict = { 'id' : argument.id,
159 163 'text_rep': argument.text_rep,
160 164 'type' : argument.type,
161 165 'error' : False,
162   - 'tooltip' : ''}
  166 + 'tooltip' : '',
  167 + 'connections': connections}
163 168 position_dict['arguments'].append(argument_dict)
164 169  
165 170 frame_dict['positions'].append(position_dict)
... ... @@ -168,4 +173,4 @@ def frameObjToSerializableDict(lemma, frame):
168 173 for char in frame_char_objs:
169 174 frame_dict['characteristics'].append(char.value.value)
170 175  
171   - return frame_dict
  176 + return frame_dict
... ...
dictionary/ajax_lemma_view.py
... ... @@ -50,6 +50,9 @@ from dictionary.forms import AddPositionForm, FrameForm, Pos_Cat_Form, \
50 50 SimilarLemmasNewForm, ChangeUserFunctionForm, \
51 51 ExampleOpinionForm, \
52 52 FrameConversionForm, CreatePositionForm, AssignPhraseologicFrameForm
  53 +from dictionary.saving import connect_example_operation, disconnect_all_examples_operations, \
  54 + get_semantic_operations, update_connections, reconnect_examples
  55 +
53 56 from common.decorators import render, ajax, AjaxError
54 57 from common.util import triple_arg_poss
55 58 from dictionary.validation import find_similar_frames, get_all_test_missing_frames, get_aspect_rel_lemmas, \
... ... @@ -59,6 +62,7 @@ from dictionary.validation import find_similar_frames, get_all_test_missing_fram
59 62 get_missing_aspects_msg
60 63  
61 64 from semantics.models import LexicalUnitExamples
  65 +
62 66 from wordnet.models import LexicalUnit
63 67  
64 68 from settings import PROJECT_PATH
... ... @@ -160,6 +164,7 @@ def prepareFrameTable(frame):
160 164  
161 165 def nkjpExamplesObjToJs(nkjp_examples, user, lemma):
162 166 example_dict_list = []
  167 + lexical_units = lemma.entry_obj.lexical_units()
163 168 for example in nkjp_examples:
164 169 frame = example.frame;
165 170 frame_table_id = 'frame_'+str(frame.id)+'_'
... ... @@ -193,11 +198,21 @@ def nkjpExamplesObjToJs(nkjp_examples, user, lemma):
193 198 'opinion' : example.opinion.opinion,
194 199 'comment' : comment,
195 200 'confirmed' : confirmed,
196   - 'semantic' : example.semantic}
  201 + 'semantic' : example.semantic,
  202 + 'lexical_unit' : get_example_lexical_unit_id(lexical_units, example)}
197 203 example_dict_list.append(example_dict)
198 204  
199 205 return example_dict_list
200 206  
  207 +def get_example_lexical_unit_id(lexical_units, example):
  208 + unit_id = -1
  209 + for lex_unit in lexical_units:
  210 + if LexicalUnitExamples.objects.filter(example=example,
  211 + lexical_unit=lex_unit).exists():
  212 + unit_id = lex_unit.id
  213 + break
  214 + return unit_id
  215 +
201 216 def nkjpLemmaExamplesObjToJs(nkjp_examples, user, lemma):
202 217 example_dict_list = []
203 218 for example in nkjp_examples:
... ... @@ -223,7 +238,9 @@ def nkjpLemmaExamplesObjToJs(nkjp_examples, user, lemma):
223 238 'source' : example.source.source,
224 239 'opinion' : example.opinion.opinion,
225 240 'comment' : comment,
226   - 'confirmed' : confirmed}
  241 + 'confirmed' : confirmed,
  242 + 'semantic' : False,
  243 + 'lexical_unit' : -1}
227 244 example_dict_list.append(example_dict)
228 245  
229 246 return example_dict_list
... ... @@ -369,7 +386,7 @@ def get_new_frames(request, id):
369 386  
370 387 serialized_frames = []
371 388 for frame in new_frames:
372   - serialized_frames.append(frameObjToSerializableDict(selected_lemma, frame))
  389 + serialized_frames.append(frameObjToSerializableDict(selected_lemma, frame, True))
373 390 json_frames = json_encode(serialized_frames)
374 391  
375 392 # konwertowanie przykladow na zrozumiale przez java sript
... ... @@ -2405,7 +2422,8 @@ def save_new_frames(request, data, id, examples, lemma_examples):
2405 2422 for B_frame in old_object.B_frames.all():
2406 2423 new_lemma_ver.B_frames.add(B_frame)
2407 2424  
2408   - # tworzenie ramek i dolaczanie ich do czasownika
  2425 + # tworzenie ramek i dolaczanie ich do czasownika
  2426 + schemata_conversions = []
2409 2427 for frame in frames:
2410 2428 frame_obj = jsFrameToObj(frame, new_lemma_ver.entry)
2411 2429 # blokuje zapisywanie ramek frazeologicznych bez argumentow frazeologicznych
... ... @@ -2424,8 +2442,14 @@ def save_new_frames(request, data, id, examples, lemma_examples):
2424 2442 frame_opinion_obj.save()
2425 2443 new_lemma_ver.frame_opinions.add(frame_opinion_obj)
2426 2444 new_lemma_ver.frames.add(frame_obj)
  2445 + schemata_conversions.append({'js': frame, 'obj': frame_obj})
  2446 +
  2447 + # reconnect semantics
  2448 + sem_reconnect_operations = get_semantic_operations(new_lemma_ver, schemata_conversions)
  2449 + update_connections(new_lemma_ver.id, sem_reconnect_operations, request.user)
2427 2450  
2428 2451 # dodawanie przykladow do ramek
  2452 + reconnect_examples_operations = disconnect_all_examples_operations(old_object)
2429 2453 for example in decoded_examples:
2430 2454 frame_obj = jsFrameToObj(example['frame'], new_lemma_ver.entry)
2431 2455 # blokuje zapisywanie przykladow z ramek frazeologicznych bez argumentow frazeologicznych
... ... @@ -2518,7 +2542,10 @@ def save_new_frames(request, data, id, examples, lemma_examples):
2518 2542 nkjp_example_obj.save()
2519 2543 for argument_selection in argument_selections:
2520 2544 nkjp_example_obj.arguments.add(argument_selection)
2521   - new_lemma_ver.nkjp_examples.add(nkjp_example_obj)
  2545 + new_lemma_ver.nkjp_examples.add(nkjp_example_obj)
  2546 + if example['lexical_unit'] > 0:
  2547 + reconnect_examples_operations.append(connect_example_operation(example, nkjp_example_obj))
  2548 + reconnect_examples(reconnect_examples_operations)
2522 2549  
2523 2550 # dodawanie przykladow nkjp do czasownika
2524 2551 for example in decoded_lemma_examples:
... ... @@ -2544,23 +2571,23 @@ def save_new_frames(request, data, id, examples, lemma_examples):
2544 2571 nkjp_lemma_example_obj.save()
2545 2572 new_lemma_ver.lemma_nkjp_examples.add(nkjp_lemma_example_obj)
2546 2573  
2547   - old_object.locker = None;
  2574 + old_object.locker = None
2548 2575 old_object.save()
2549   - new_lemma_ver.locker = None;
  2576 + new_lemma_ver.locker = None
2550 2577 try:
2551 2578 new_lemma_ver = Lemma.objects.get(entry=old_object.entry, owner=old_object.owner,
2552 2579 vocabulary=old_object.vocabulary, status=old_object.status,
2553 2580 old=False)
2554 2581 raise AjaxError('concurrent access')
2555 2582 except:
2556   - new_lemma_ver.old = False;
2557   - new_lemma_ver.save();
  2583 + new_lemma_ver.old = False
  2584 + new_lemma_ver.save()
2558 2585  
2559 2586 return {'id' : new_lemma_ver.id,
2560 2587 'entry' : new_lemma_ver.entry,
2561 2588 'error_message': '',
2562 2589 'frames' : ''}
2563   -
  2590 +
2564 2591 ############## WALIDACJA #####################
2565 2592  
2566 2593 @ajax(method='post')
... ...
dictionary/models.py
... ... @@ -1387,6 +1387,20 @@ class Entry(Model):
1387 1387 frame_ids.extend([f.id for f in lexical_unit.actual_frames()])
1388 1388 return get_model('semantics', 'SemanticFrame').objects.filter(id__in=list(set(frame_ids)))
1389 1389  
  1390 + def matching_connections(self, schema, position, phrase_type):
  1391 + frames = self.actual_frames()
  1392 + matching_connections = []
  1393 + for frame in frames:
  1394 + for compl in frame.complements.all():
  1395 + matching_realizations = compl.realizations.filter(frame=schema,
  1396 + position=position,
  1397 + argument=phrase_type)
  1398 + if matching_realizations.exists():
  1399 + realizations_ids = [real.id for real in matching_realizations.all()]
  1400 + matching_connections.append({'compl': compl.id,
  1401 + 'realizations': realizations_ids})
  1402 + return matching_connections
  1403 +
1390 1404 def __unicode__(self):
1391 1405 return self.name
1392 1406  
... ...
dictionary/saving.py 0 → 100644
  1 +# -*- coding: utf-8 -*-
  2 +
  3 +from common.js_to_obj import jsPosToObj
  4 +from dictionary.models import Argument
  5 +from semantics.models import Complement, LexicalUnitExamples
  6 +from semantics.saving import modify_frames, update_meanings
  7 +from wordnet.models import LexicalUnit
  8 +
  9 +def get_semantic_operations(lemma, schemata_conversions):
  10 + connections = []
  11 + operations = []
  12 + for conv in schemata_conversions:
  13 + schema_operations = get_reconnect_operations_and_extend_connections(connections,
  14 + conv['obj'],
  15 + conv['js'])
  16 + operations.extend(schema_operations)
  17 + frames = lemma.entry_obj.actual_frames()
  18 + operations.extend(get_disconnect_operations(frames, connections))
  19 + return operations
  20 +
  21 +def get_reconnect_operations_and_extend_connections(connections, schema, js_schema):
  22 + operations = []
  23 + for js_position in js_schema['positions']:
  24 + position = jsPosToObj(js_position)
  25 + for js_phrase_type in js_position['arguments']:
  26 + phrase_type = Argument.objects.get(id=js_phrase_type['id'])
  27 + new_connection_target = {'schema': schema,
  28 + 'position': position,
  29 + 'phrase_type': phrase_type}
  30 + for conn in js_phrase_type['connections']:
  31 + operations.extend(reconnect_operations(conn, new_connection_target))
  32 + conn_dict = next((conn_dict
  33 + for conn_dict in connections if conn_dict['compl'] == conn['compl']), None)
  34 + if conn_dict:
  35 + conn_dict['realizations'].extend(conn['realizations'])
  36 + else:
  37 + connections.append({'compl': conn['compl'],
  38 + 'realizations': conn['realizations']})
  39 + return operations
  40 +
  41 +def reconnect_operations(connection, new_target):
  42 + operations = []
  43 + compl = Complement.objects.get(id=connection['compl'])
  44 + arg_ref = create_argument_ref(compl)
  45 + for real_id in connection['realizations']:
  46 + realization = compl.realizations.get(id=real_id)
  47 + old_phrase_type_ref = create_phrase_type_ref(realization.frame, realization.position,
  48 + realization.argument, realization.alternation)
  49 + operations.append(create_operation('disconnect', arg_ref, old_phrase_type_ref))
  50 + new_phrase_type_ref = create_phrase_type_ref(new_target['schema'], new_target['position'],
  51 + new_target['phrase_type'], realization.alternation)
  52 + operations.append(create_operation('connect', arg_ref, new_phrase_type_ref))
  53 + return operations
  54 +
  55 +def create_argument_ref(complement):
  56 + connected_frame = Complement.objects.get(id=complement.id)
  57 + return 'frame_%d_comp_%d_' % (connected_frame.id, complement.id)
  58 +
  59 +def create_phrase_type_ref(schema, position, phrase_type, alternation):
  60 + return 'schema_%d_pos_%d_arg_%d_alt_%d_' % (schema.id, position.id,
  61 + phrase_type.id, alternation)
  62 +
  63 +def create_operation(operation, arg_ref, phrase_type_ref):
  64 + return {'operation': operation, 'arg': arg_ref, 'connect': phrase_type_ref}
  65 +
  66 +def get_disconnect_operations(frames, connections):
  67 + operations = []
  68 + for frame in frames:
  69 + for compl in frame.complements.all():
  70 + conn_dict = next((conn_dict
  71 + for conn_dict in connections if conn_dict['compl'] == compl.id), None)
  72 + for real in compl.realizations.all():
  73 + if not real.id in conn_dict['realizations']:
  74 + phrase_type_ref = create_phrase_type_ref(real.frame, real.position,
  75 + real.argument, real.alternation)
  76 + arg_ref = create_argument_ref(compl)
  77 + operations.append(create_operation('disconnect', arg_ref, phrase_type_ref))
  78 + return operations
  79 +
  80 +def update_connections(lemma_id, reconnect_operations, user):
  81 + modify_frames(lemma_id, reconnect_operations, user)
  82 +
  83 +def disconnect_all_examples_operations(lemma):
  84 + operations = []
  85 + lex_units = lemma.entry_obj.lexical_units().all()
  86 + for lu in lex_units:
  87 + lu_examples = LexicalUnitExamples.objects.filter(lexical_unit=lu)
  88 + for lu_ex in lu_examples:
  89 + example = lu_ex.example
  90 + operations.append({'operation': 'remove_example',
  91 + 'unit': lu.id,
  92 + 'example': example.id})
  93 + return operations
  94 +
  95 +def connect_example_operation(example_dict, example_obj):
  96 + lu = LexicalUnit.objects.get(id=example_dict['lexical_unit'])
  97 + return {'operation': 'add_example', 'unit': lu.id, 'example': example_obj.id}
  98 +
  99 +def reconnect_examples(operations):
  100 + update_meanings(operations)
  101 +
0 102 \ No newline at end of file
... ...
dictionary/static/js/argument_form_utils.js
... ... @@ -11,13 +11,14 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
11 11 */
12 12  
13 13 // argument class
14   -function argument(id, text_rep, type)
  14 +function argument(id, text_rep, type, complements)
15 15 {
16 16 this.id = id
17 17 this.text_rep = text_rep;
18 18 this.type = type;
19 19 this.error = false;
20 20 this.tooltip = '';
  21 + this.complements = complements;
21 22 }
22 23  
23 24 function arguments_form_change(lastActualValueIdx, arg_id, this_form, lemma_id) {
... ... @@ -160,7 +161,7 @@ function argument_form_submit() {
160 161 },
161 162  
162 163 callback: function(result) {
163   - var arg = new argument(result["id"], result["text_rep"], result["type"]);
  164 + var arg = new argument(result["id"], result["text_rep"], result["type"], []);
164 165  
165 166 // dodawanie argumentow
166 167 if(this_dialog.dialog( "option" , "title").startsWith("Dodawanie"))
... ...
dictionary/static/js/lemma-view.js
... ... @@ -580,7 +580,7 @@ function Nkjp_example(example_id, frame_id, arguments_ids, sentence, source, opi
580 580 this.semantic = semantic;
581 581 }
582 582  
583   -function Nkjp_example_ajax(frame, arg_selections, sentence, source, opinion, comment, semantic)
  583 +function Nkjp_example_ajax(frame, arg_selections, sentence, source, opinion, comment, semantic, lexical_unit)
584 584 {
585 585 this.frame = frame;
586 586 this.arg_selections = arg_selections;
... ... @@ -589,6 +589,7 @@ function Nkjp_example_ajax(frame, arg_selections, sentence, source, opinion, com
589 589 this.opinion = opinion;
590 590 this.comment = comment;
591 591 this.semantic = semantic;
  592 + this.lexical_unit = lexical_unit;
592 593 }
593 594  
594 595 function Nkjp_ArgSelection(position, arguments)
... ... @@ -629,7 +630,7 @@ function frameToTableRows(frame)
629 630 arguments_row.push(frame.positions[i].arguments[arg_number]);
630 631 else
631 632 {
632   - arguments_row.push(new argument(new_elem_id, '', ''));
  633 + arguments_row.push(new argument(new_elem_id, '', '', []));
633 634 new_elem_id--;
634 635 }
635 636 }
... ... @@ -866,8 +867,7 @@ function needConfirmation(nkjpInstance) {
866 867 function unpin_nkjp_example(example_tabId)
867 868 {
868 869 if(example_tabId != -1 &&
869   - !checkIfSemChangedAndAlert() &&
870   - !exampleGotAssignedSemantics(example_tabId))
  870 + !checkIfSemChangedAndAlert())// && !exampleGotAssignedSemantics(example_tabId))
871 871 {
872 872 example_id = example_tabId.replace('nkjp_', '');
873 873 for(var i=0; i<window.nkjp_examples.length; i++)
... ... @@ -992,60 +992,6 @@ function getNkjpExampleInstance(nkjp_examples, example_id)
992 992 return '';
993 993 }
994 994  
995   -//////////////////////// semantics //////////////////////////////
996   -
997   -function schemaGotAssignedSemantics(element_id)
998   -{
999   - var semanticsAssigned = true;
1000   - var id_map = parseId(element_id);
1001   - var schema_id = id_map['frame_id'];
1002   - if(schema_id < 0) {
1003   - semanticsAssigned = false;
1004   - }
1005   - else {
1006   - jQuery.ajax({
1007   - type: 'get',
1008   - url: ajax_schema_got_assigned_semantics,
1009   - data: {lemma_id: window.lemma_id,
1010   - schema_id: schema_id},
1011   - success: function(result) {
1012   - semanticsAssigned = result['got_assigned_semantics'];
1013   - },
1014   - async: false
1015   - });
1016   - }
1017   - if(semanticsAssigned) {
1018   - error_alert('Nie można zmodyfikować. Element jest wykorzystywany w ramkach semantycznych.');
1019   - }
1020   - return semanticsAssigned;
1021   -}
1022   -
1023   -function exampleGotAssignedSemantics(example_tab_id)
1024   -{
1025   - var semanticsAssigned = true;
1026   - var example_id = example_tab_id.replace('nkjp_', '');
1027   - if (example_id < 0) {
1028   - semanticsAssigned = false;
1029   - }
1030   - else {
1031   - jQuery.ajax({
1032   - type: 'get',
1033   - url: ajax_example_got_assigned_semantics,
1034   - data: {lemma_id: window.lemma_id,
1035   - example_id: example_id},
1036   - success: function(result) {
1037   - semanticsAssigned = result['got_assigned_semantics'];
1038   - },
1039   - async: false
1040   - });
1041   - }
1042   - if(semanticsAssigned) {
1043   - error_alert('Nie można zmodyfikować. Przykład jest wykorzystywany w ramkach semantycznych.');
1044   - }
1045   - return semanticsAssigned;
1046   -}
1047   -//////////////////////////////////////////////////////
1048   -
1049 995 function getNkjpLemmaExampleInstance(nkjp_examples, example_id)
1050 996 {
1051 997 var example_id = example_id.replace('nkjpLemma_', '');
... ... @@ -1058,7 +1004,7 @@ function getNkjpLemmaExampleInstance(nkjp_examples, example_id)
1058 1004 }
1059 1005  
1060 1006 function remove_semantic_example(example_id) {
1061   - if(example_id != -1 && !checkIfSemChangedAndAlert() && !exampleGotAssignedSemantics(example_id))
  1007 + if(example_id != -1 && !checkIfSemChangedAndAlert())// && !exampleGotAssignedSemantics(example_id))
1062 1008 {
1063 1009 example_id = example_id.replace('nkjp_', '');
1064 1010 for(var i=0; i<nkjp_examples.length; i++)
... ... @@ -1421,7 +1367,7 @@ function add_pos_form_submit() {
1421 1367 var arguments = new Array();
1422 1368 for(var i=0; i<argsObj.length; i++)
1423 1369 {
1424   - arguments.push(new argument(argsObj[i].pk, argsObj[i].fields.text_rep, argsObj[i].fields.type));
  1370 + arguments.push(new argument(argsObj[i].pk, argsObj[i].fields.text_rep, argsObj[i].fields.type, []));
1425 1371 }
1426 1372  
1427 1373 var cats = new Array();
... ... @@ -1570,7 +1516,11 @@ function can_add_position_category(lemma_id) {
1570 1516 }
1571 1517  
1572 1518 function openEditForm(id) {
1573   - if(window.can_modify && !checkIfSemChangedAndAlert() && !schemaGotAssignedSemantics(id)) {
  1519 + if(window.can_modify && !checkIfSemChangedAndAlert()) {
  1520 + /*if(schemaGotAssignedSemantics(id)) {
  1521 + semanticsAssignedAlert();
  1522 + }*/
  1523 +
1574 1524 editedFrameInstance = getFrameInstance(id, window.schemas);
1575 1525 elemInstance = getElementInstance(id, window.schemas);
1576 1526 addSyntacticFramesPerm = user_has_perm('dictionary.add_syntactic_frames');
... ... @@ -1699,7 +1649,7 @@ function convertExample(nkjp_example)
1699 1649 var convertedExample = new Nkjp_example_ajax(frame['element'], argument_selections,
1700 1650 nkjp_example.sentence, nkjp_example.source,
1701 1651 nkjp_example.opinion, nkjp_example.comment,
1702   - nkjp_example.semantic);
  1652 + nkjp_example.semantic, nkjp_example.lexical_unit);
1703 1653  
1704 1654 return convertedExample;
1705 1655 }
... ... @@ -1790,7 +1740,7 @@ function save_new_frames() {
1790 1740 data: data,
1791 1741 id: lemma_id,
1792 1742 examples: examples_data,
1793   - lemma_examples: lemma_examples_data
  1743 + lemma_examples: lemma_examples_data,
1794 1744 },
1795 1745  
1796 1746 callback: function(result) {
... ... @@ -1954,8 +1904,7 @@ function frame_form_submit() {
1954 1904 }
1955 1905 });
1956 1906  
1957   - if(window.addedFrame)
1958   - {
  1907 + if(window.addedFrame) {
1959 1908 frame = JSON.stringify(window.addedFrame);
1960 1909 }
1961 1910 else if(propose_phraseology) {
... ... @@ -2003,9 +1952,8 @@ function frame_form_submit() {
2003 1952  
2004 1953 callback: function(result) {
2005 1954 edited_frame_id = null;
2006   - old_edited_frame_id = '';
2007   - if(window.addedFrame)
2008   - {
  1955 + old_edited_frame_id = '';
  1956 + if(window.addedFrame) {
2009 1957 edited_frame = $.evalJSON($.toJSON(window.addedFrame));
2010 1958 edited_frame = serializedObjToObj(result['frame']);
2011 1959 edited_frame.id = window.addedFrame.id;
... ... @@ -2041,10 +1989,11 @@ function frame_form_submit() {
2041 1989 }
2042 1990 else {
2043 1991 edited_frame = getElementInstance(edited_id, schemas);
2044   - old_edited_frame_id = edited_frame['element'].id;
2045   - edited_frame['element'].id = new_elem_id;
2046   - edited_frame_id = new_elem_id;
2047   - new_elem_id--;
  1992 + var old_edited_frame_id = edited_frame['element'].id;
  1993 + //edited_frame['element'].id = new_elem_id; tuta zmienilem
  1994 + edited_frame['element'].id = result['id'];
  1995 + edited_frame_id = edited_frame['element'].id;
  1996 + //new_elem_id--;
2048 1997 edited_frame['element'].text_rep = result['text_rep'];
2049 1998 edited_frame['element'].characteristics = result['characteristics'];
2050 1999 edited_frame['element'].opinion = result['opinion'];
... ... @@ -3687,6 +3636,7 @@ function restore_lemma() {
3687 3636 to_copy_elem['type'] == 'frame')
3688 3637 {
3689 3638 var frame = $.evalJSON($.toJSON(to_copy_elem['element']));
  3639 + clearSemanticConnections(frame);
3690 3640 // kopiowanie schematu z podgladu (moze wymagac konwersji)
3691 3641 if(elem_in_bucket['lemma_id'] &&
3692 3642 need_conversion && can_be_converted &&
... ... @@ -3711,6 +3661,7 @@ function restore_lemma() {
3711 3661 to_copy_elem['type'] == 'argument' && !need_conversion)
3712 3662 {
3713 3663 var argument = $.evalJSON($.toJSON(to_copy_elem['element']));
  3664 + clearSemanticConnections(argument);
3714 3665 argument.id = new_elem_id;
3715 3666 new_elem_id--;
3716 3667 target_elem['element'].arguments.push(argument);
... ... @@ -3721,6 +3672,7 @@ function restore_lemma() {
3721 3672 to_copy_elem['type'] == 'position' && !need_conversion)
3722 3673 {
3723 3674 var position = $.evalJSON($.toJSON(to_copy_elem['element']));
  3675 + clearSemanticConnections(position);
3724 3676 position.id = new_elem_id;
3725 3677 new_elem_id--;
3726 3678 target_elem['element'].positions.push(position);
... ... @@ -3813,8 +3765,12 @@ function restore_lemma() {
3813 3765 if(window.selected_id != -1) {
3814 3766 var assignedExamples = [];
3815 3767 if(canModifyFrame(window.selected_id, window.schemas) &&
3816   - !checkIfSemChangedAndAlert() &&
3817   - !schemaGotAssignedSemantics(window.selected_id)) {
  3768 + !checkIfSemChangedAndAlert()) {
  3769 +
  3770 + /*if(schemaGotAssignedSemantics(window.selected_id)) {
  3771 + semanticsAssignedAlert();
  3772 + }*/
  3773 +
3818 3774 assignedExamples = gotAssignedExample(nkjp_examples, selected_id, true);
3819 3775 if(assignedExamples.length == 0) {
3820 3776 schemas = removeFrameElement(selected_id, schemas);
... ... @@ -3829,8 +3785,10 @@ function restore_lemma() {
3829 3785  
3830 3786 function addElement() {
3831 3787 if(!checkIfSemChangedAndAlert() &&
3832   - (window.selected_id == -1 || (canModifyFrame(window.selected_id, window.schemas) &&
3833   - !schemaGotAssignedSemantics(window.selected_id)))) {
  3788 + (window.selected_id == -1 || canModifyFrame(window.selected_id, window.schemas))) {
  3789 + /*if(schemaGotAssignedSemantics(window.selected_id)) {
  3790 + semanticsAssignedAlert();
  3791 + }*/
3834 3792 window.schemas = addFrameElementDialog(window.selected_id, window.schemas);
3835 3793 }
3836 3794 }
... ... @@ -3967,8 +3925,11 @@ function restore_lemma() {
3967 3925 {
3968 3926 if(window.elem_in_bucket && !checkIfSemChangedAndAlert() &&
3969 3927 (window.selected_id == -1 ||
3970   - (canModifyFrame(window.selected_id, window.schemas) &&
3971   - !schemaGotAssignedSemantics(window.selected_id)))) {
  3928 + canModifyFrame(window.selected_id, window.schemas))) {
  3929 +
  3930 + /*if(schemaGotAssignedSemantics(window.selected_id)) {
  3931 + semanticsAssignedAlert();
  3932 + }*/
3972 3933 pasteFrameElement(selected_id, elem_in_bucket, schemas);
3973 3934 }
3974 3935 }
... ... @@ -3999,9 +3960,17 @@ function restore_lemma() {
3999 3960 canModifyFrame(window.selected_id, window.schemas) &&
4000 3961 !checkIfSemChangedAndAlert())
4001 3962 {
  3963 + /*if(getElementInstance(selected_id, schemas)['type'] != 'frame' &&
  3964 + schemaGotAssignedSemantics(selected_id)) {
  3965 + semanticsAssignedAlert();
  3966 + return;
  3967 + }*/
  3968 +
4002 3969 elem_in_bucket = getElementInstance(selected_id, schemas);
  3970 +
4003 3971 var parent_elem = getParentInstance(selected_id, schemas);
4004 3972 var duplicate = $.evalJSON($.toJSON(elem_in_bucket['element']));
  3973 + clearSemanticConnections(duplicate);
4005 3974 duplicate.id = new_elem_id;
4006 3975 new_elem_id--;
4007 3976  
... ... @@ -4108,7 +4077,7 @@ function restore_lemma() {
4108 4077  
4109 4078 function delete_nkjp_example(example_id)
4110 4079 {
4111   - if(example_id != -1 && !checkIfSemChangedAndAlert() && !exampleGotAssignedSemantics(example_id))
  4080 + if(example_id != -1 && !checkIfSemChangedAndAlert())// && !exampleGotAssignedSemantics(example_id))
4112 4081 {
4113 4082 example_id = selected_example_id.replace('nkjp_', '');
4114 4083 for(var i=0; i<nkjp_examples.length; i++)
... ... @@ -4143,8 +4112,8 @@ function restore_lemma() {
4143 4112 function delete_all_nkjp_examples(frame_id)
4144 4113 {
4145 4114 if(canModifyFrame(frame_id, window.schemas) &&
4146   - !checkIfSemChangedAndAlert() &&
4147   - !schemaGotAssignedSemantics(frame_id)) {
  4115 + !checkIfSemChangedAndAlert())// && !schemaGotAssignedSemantics(frame_id))
  4116 + {
4148 4117 var new_example_tab = new Array();
4149 4118 for(var i=0; i<nkjp_examples.length; i++)
4150 4119 {
... ... @@ -4202,7 +4171,7 @@ function restore_lemma() {
4202 4171  
4203 4172 function modify_nkjp_example(example_id)
4204 4173 {
4205   - if(example_id != -1 && !checkIfSemChangedAndAlert() && !exampleGotAssignedSemantics(example_id))
  4174 + if(example_id != -1 && !checkIfSemChangedAndAlert())// && !exampleGotAssignedSemantics(example_id))
4206 4175 {
4207 4176 var example = '';
4208 4177 for(var i=0; i<window.nkjp_examples.length; i++)
... ... @@ -5092,21 +5061,6 @@ function gridPreviewContent(isPreview) {
5092 5061 return false;
5093 5062 }
5094 5063  
5095   -function semanticsChanged() {
5096   - if(window.frames_operations.length > 0) {
5097   - return true;
5098   - }
5099   - return false;
5100   -}
5101   -
5102   -function checkIfSemChangedAndAlert() {
5103   - if(semanticsChanged()) {
5104   - alert('Przed dokonaniem zmiany zapisz semantykę.');
5105   - return true;
5106   - }
5107   - return false;
5108   -}
5109   -
5110 5064 /////////////////////////////////////
5111 5065  
5112 5066 $(function(){
... ...
dictionary/static/js/semantics_coupling.js 0 → 100644
  1 +function schemaGotAssignedSemantics(element_id)
  2 +{
  3 + var semanticsAssigned = true;
  4 + var id_map = parseId(element_id);
  5 + var schema_id = id_map['frame_id'];
  6 + if(schema_id < 0) {
  7 + semanticsAssigned = false;
  8 + }
  9 + else {
  10 + jQuery.ajax({
  11 + type: 'get',
  12 + url: ajax_schema_got_assigned_semantics,
  13 + data: {lemma_id: window.lemma_id,
  14 + schema_id: schema_id},
  15 + success: function(result) {
  16 + semanticsAssigned = result['got_assigned_semantics'];
  17 + },
  18 + async: false
  19 + });
  20 + }
  21 + return semanticsAssigned;
  22 +}
  23 +
  24 +function semanticsAssignedAlert() {
  25 + error_alert('Działaj rozważnie, element jest wykorzystywany w ramach semantycznych.');
  26 +}
  27 +
  28 +function exampleGotAssignedSemantics(example_tab_id)
  29 +{
  30 + var semanticsAssigned = true;
  31 + var example_id = example_tab_id.replace('nkjp_', '');
  32 + if (example_id < 0) {
  33 + semanticsAssigned = false;
  34 + }
  35 + else {
  36 + jQuery.ajax({
  37 + type: 'get',
  38 + url: ajax_example_got_assigned_semantics,
  39 + data: {lemma_id: window.lemma_id,
  40 + example_id: example_id},
  41 + success: function(result) {
  42 + semanticsAssigned = result['got_assigned_semantics'];
  43 + },
  44 + async: false
  45 + });
  46 + }
  47 + return semanticsAssigned;
  48 +}
  49 +
  50 +function semanticsAssignedExampleAlert() {
  51 + error_alert('Działaj rozważnie, przykład jest wykorzystywany w ramach semantycznych.');
  52 +}
  53 +
  54 +function semanticsChanged() {
  55 + if(window.frames_operations.length > 0) {
  56 + return true;
  57 + }
  58 + return false;
  59 +}
  60 +
  61 +function checkIfSemChangedAndAlert() {
  62 + if(semanticsChanged()) {
  63 + alert('Przed dokonaniem zmiany zapisz semantykę.');
  64 + return true;
  65 + }
  66 + return false;
  67 +}
  68 +
  69 +function clearSemanticConnections(schemaElement) {
  70 + if(schemaElement['type'] == 'frame') {
  71 + clearSchemaConnections(schemaElement);
  72 + }
  73 + else if(schemaElement['type'] == 'position') {
  74 + clearPositionConnections(schemaElement);
  75 + }
  76 + else if(schemaElement['type'] == 'argument') {
  77 + clearPhraseTypeConnections(schemaElement);
  78 + }
  79 +}
  80 +
  81 +function clearSchemaConnections(schema) {
  82 + for(var i=0; i<schema.positions.length; i++) {
  83 + clearPositionConnections(schema.positions[i]);
  84 + }
  85 +}
  86 +
  87 +function clearPositionConnections(position) {
  88 + for(var i=0; i<position.arguments.length; i++) {
  89 + clearPhraseTypeConnections(position.arguments[i]);
  90 + }
  91 +}
  92 +
  93 +function clearPhraseTypeConnections(phraseType) {
  94 + phraseType.complements = [];
  95 +}
... ...
dictionary/templates/lemma_view.html
... ... @@ -18,6 +18,7 @@
18 18 <script type="text/javascript" src="{{ STATIC_URL }}js/lib/jquery.multiselect.js"></script>
19 19 <script type="text/javascript" src="{{ STATIC_URL }}js/jqgrid-patch.js"></script>
20 20 <script type="text/javascript" src="{{ STATIC_URL }}js/lemma_grid.js"></script>
  21 + <script type="text/javascript" src="{{ STATIC_URL }}js/semantics_coupling.js"></script>
21 22 <script type="text/javascript" src="{{ STATIC_URL }}js/lemma-view.js"></script>
22 23  
23 24 {% endblock %}
... ...
dictionary/validation.py
... ... @@ -436,7 +436,7 @@ def validate_examples_and_mark_errors(lemma, status_obj, selected_frame_id):
436 436 error = False
437 437 serialized_frames = []
438 438 for frame_obj in lemma.frames.all():
439   - serialized_frame = frameObjToSerializableDict(lemma, frame_obj)
  439 + serialized_frame = frameObjToSerializableDict(lemma, frame_obj, True)
440 440 if selected_frame_id and frame_obj.id != selected_frame_id:
441 441 serialized_frames.append(serialized_frame)
442 442 continue
... ... @@ -461,7 +461,7 @@ def validate_schemas_and_mark_errors(lemma, status, selected_frame_id):
461 461 error = False
462 462 serialized_frames = []
463 463 for frame_obj in lemma.frames.all():
464   - serialized_frame = frameObjToSerializableDict(lemma, frame_obj)
  464 + serialized_frame = frameObjToSerializableDict(lemma, frame_obj, True)
465 465 if selected_frame_id and frame_obj.id != selected_frame_id:
466 466 serialized_frames.append(serialized_frame)
467 467 continue
... ...
semantics/models.py
... ... @@ -52,6 +52,10 @@ class FramePosition(models.Model):
52 52 argument = models.ForeignKey(Argument)
53 53 # numer alternacji
54 54 alternation = models.IntegerField(default=1)
  55 +
  56 + def __unicode__(self):
  57 + return 'schema_%d_pos_%d_arg_%d_alt_%d_' % (self.frame.id, self.position.id,
  58 + self.argument.id, self.alternation)
55 59  
56 60 class LexicalUnitExamples(models.Model):
57 61 example = models.ForeignKey(NKJP_Example)
... ...
semantics/saving.py 0 → 100644
  1 +# -*- coding: utf-8 -*-
  2 +
  3 +from django.db.models import Min
  4 +
  5 +from dictionary.models import Argument, Frame, NKJP_Example, Position
  6 +from semantics.change_log import store_old_versions
  7 +from semantics.models import Complement, GeneralSelectivePreference, FramePosition,\
  8 + LexicalUnitExamples, RelationalSelectivePreference, \
  9 + SelectivePreference, SelectivePreferenceRelations, \
  10 + SemanticFrame, SemanticRole
  11 +from wordnet.models import Hypernymy, LexicalUnit, Synonymy, Synset
  12 +
  13 +def modify_frames(lemma_id, operations, user):
  14 + store_old_versions(lemma_id, operations, user)
  15 + make_operations(operations)
  16 +
  17 +def make_operations(operations):
  18 + translation = {'frame_id': {}, 'complement_id': {}, 'preference_id': {}}
  19 + for operation in operations:
  20 + if operation['operation'] == "create_frame":
  21 + luids = [int(m['id']) for m in operation['meanings']]
  22 + translation['frame_id'][int(operation['id'])] = create_frame(luids)
  23 + elif operation['operation'] == "remove_frame":
  24 + if int(operation['id']) in translation['frame_id']:
  25 + frame_id = translation['frame_id'][int(operation['id'])]
  26 + else:
  27 + frame_id = int(operation['id'])
  28 + remove_frame(frame_id)
  29 + elif operation['operation'] == "add_argument":
  30 + if int(operation['frame_id']) in translation['frame_id']:
  31 + frame_id = translation['frame_id'][int(operation['frame_id'])]
  32 + else:
  33 + frame_id = int(operation['frame_id'])
  34 + roles = [int(r) for r in operation['role']]
  35 + translation['complement_id'][int(operation['id'])] = add_argument(frame_id, roles)
  36 + elif operation['operation'] == "remove_argument":
  37 + if int(operation['frame_id']) in translation['frame_id']:
  38 + frame_id = translation['frame_id'][int(operation['frame_id'])]
  39 + else:
  40 + frame_id = int(operation['frame_id'])
  41 + if int(operation['complement_id']) in translation['complement_id']:
  42 + complement_id = translation['complement_id'][int(operation['complement_id'])]
  43 + else:
  44 + complement_id = int(operation['complement_id'])
  45 + remove_argument(frame_id, complement_id)
  46 + elif operation['operation'] == "connect":
  47 + frame_data = operation['arg'].split('_')
  48 + if int(frame_data[1]) in translation['frame_id']:
  49 + frame_id = translation['frame_id'][int(frame_data[1])]
  50 + else:
  51 + frame_id = int(frame_data[1])
  52 + if int(frame_data[3]) in translation['complement_id']:
  53 + complement_id = translation['complement_id'][int(frame_data[3])]
  54 + else:
  55 + complement_id = int(frame_data[3])
  56 + schema_data = operation['connect'].split('_')
  57 + schema_id = int(schema_data[1])
  58 + position_id = int(schema_data[3])
  59 + argument_id = int(schema_data[5])
  60 + alternation = int(schema_data[7])
  61 + connect(frame_id, complement_id, schema_id, position_id, argument_id, alternation)
  62 + elif operation['operation'] == "disconnect":
  63 + frame_data = operation['arg'].split('_')
  64 + if int(frame_data[1]) in translation['frame_id']:
  65 + frame_id = translation['frame_id'][int(frame_data[1])]
  66 + else:
  67 + frame_id = int(frame_data[1])
  68 + if int(frame_data[3]) in translation['complement_id']:
  69 + complement_id = translation['complement_id'][int(frame_data[3])]
  70 + else:
  71 + complement_id = int(frame_data[3])
  72 + schema_data = operation['connect'].split('_')
  73 + schema_id = int(schema_data[1])
  74 + position_id = int(schema_data[3])
  75 + argument_id = int(schema_data[5])
  76 + alternation = int(schema_data[7])
  77 + disconnect(frame_id, complement_id, schema_id, position_id, argument_id, alternation)
  78 + elif operation['operation'] == "assign_role":
  79 + if int(operation['frame_id']) in translation['frame_id']:
  80 + frame_id = translation['frame_id'][int(operation['frame_id'])]
  81 + else:
  82 + frame_id = int(operation['frame_id'])
  83 + if int(operation['complement_id']) in translation['complement_id']:
  84 + complement_id = translation['complement_id'][int(operation['complement_id'])]
  85 + else:
  86 + complement_id = int(operation['complement_id'])
  87 + roles = [int(r) for r in operation['role']]
  88 + assign_role(frame_id, complement_id, roles)
  89 + elif operation['operation'] == "change_units":
  90 + if int(operation['frame_id']) in translation['frame_id']:
  91 + frame_id = translation['frame_id'][int(operation['frame_id'])]
  92 + else:
  93 + frame_id = int(operation['frame_id'])
  94 + luids = [int(m) for m in operation['units']]
  95 + change_units(frame_id, luids)
  96 + elif operation['operation'] == "add_preference":
  97 + # {operation: 'add_preference', frame_id: frame_id, complement_id: complement_id, preference_id: preference_id, preference: preference}
  98 + if int(operation['frame_id']) in translation['frame_id']:
  99 + frame_id = translation['frame_id'][int(operation['frame_id'])]
  100 + else:
  101 + frame_id = int(operation['frame_id'])
  102 + if int(operation['complement_id']) in translation['complement_id']:
  103 + complement_id = translation['complement_id'][int(operation['complement_id'])]
  104 + else:
  105 + complement_id = int(operation['complement_id'])
  106 + preference_id = add_preference(frame_id, complement_id, operation['preference']['type'], operation['preference']['content'])
  107 + translation['preference_id'][operation['preference_id']] = preference_id
  108 + elif operation['operation'] == "remove_preference":
  109 + # {operation: 'remove_preference', frame_id: frame_id, complement_id: complement_id, preference_id: preference_id}
  110 + if int(operation['frame_id']) in translation['frame_id']:
  111 + frame_id = translation['frame_id'][int(operation['frame_id'])]
  112 + else:
  113 + frame_id = int(operation['frame_id'])
  114 + if int(operation['complement_id']) in translation['complement_id']:
  115 + complement_id = translation['complement_id'][int(operation['complement_id'])]
  116 + else:
  117 + complement_id = int(operation['complement_id'])
  118 + if operation['preference_id'] in translation['preference_id']:
  119 + preference_id = translation['preference_id'][operation['preference_id']]
  120 + else:
  121 + preference_id = (operation['preference_id'][0], int(operation['preference_id'][1:]))
  122 +
  123 + remove_preference(frame_id, complement_id, preference_id)
  124 + else:
  125 + pass
  126 +
  127 +def create_frame(luids):
  128 + frame = SemanticFrame()
  129 + frame.save()
  130 + for id in luids:
  131 + lu = LexicalUnit.objects.get(id=id)
  132 + frame.lexical_units.add(lu)
  133 + return frame.id
  134 +
  135 +def add_argument(frame_id, roles):
  136 + if validate_roles(roles):
  137 + frame = SemanticFrame.objects.get(id=frame_id)
  138 + complement = Complement(frame=frame)
  139 + complement.save()
  140 + frame.complements.add(complement)
  141 + role_objects = []
  142 + for r in roles:
  143 + role_objects.append(SemanticRole.objects.get(id=r))
  144 + complement.roles = role_objects
  145 + return complement.id
  146 +
  147 +def remove_frame(frame_id):
  148 + frame = SemanticFrame.objects.get(id=frame_id)
  149 + frame.removed = True
  150 + frame.save()
  151 +
  152 +def remove_argument(frame_id, complement_id):
  153 + Complement.objects.get(id=complement_id).delete()
  154 +
  155 +def connect(frame_id, complement_id, schema_id, position_id, argument_id, alternation):
  156 + schema = Frame.objects.get(id=schema_id)
  157 + position = Position.objects.get(id=position_id)
  158 + argument = Argument.objects.get(id=argument_id)
  159 + fpas = FramePosition.objects.filter(frame=schema, position=position, argument=argument, alternation=alternation)
  160 + if len(fpas) > 0:
  161 + fpa = fpas[0]
  162 + else:
  163 + fpa = FramePosition(frame=schema, position=position, argument=argument, alternation=alternation)
  164 + fpa.save()
  165 + complement = Complement.objects.get(id=complement_id)
  166 + complement.realizations.add(fpa)
  167 +
  168 +def disconnect(frame_id, complement_id, schema_id, position_id, argument_id, alternation):
  169 + schema = Frame.objects.get(id=schema_id)
  170 + position = Position.objects.get(id=position_id)
  171 + argument = Argument.objects.get(id=argument_id)
  172 + fpas = FramePosition.objects.filter(frame=schema, position=position, argument=argument, alternation=alternation)
  173 + if len(fpas) > 0:
  174 + fpa = fpas[0]
  175 + else:
  176 + return
  177 + complement = Complement.objects.get(id=complement_id)
  178 + complement.realizations.remove(fpa)
  179 +
  180 +def assign_role(frame_id, complement_id, roles):
  181 + if validate_roles(roles):
  182 + role_objects = []
  183 + for r in roles:
  184 + role_objects.append(SemanticRole.objects.get(id=r))
  185 + complement = Complement.objects.get(id=complement_id)
  186 + complement.roles = role_objects
  187 +
  188 +def validate_roles(roles):
  189 + role_objects = []
  190 + for r in roles:
  191 + role_objects.append(SemanticRole.objects.get(id=r))
  192 + if len(role_objects) > 2:
  193 + return False
  194 + ok = False
  195 + for r in role_objects:
  196 + if not r.color == None:
  197 + ok = not ok
  198 + return ok
  199 +
  200 +def change_units(frame_id, luids):
  201 + frame = SemanticFrame.objects.get(id=frame_id)
  202 + frame.lexical_units = []
  203 + for id in luids:
  204 + lu = LexicalUnit.objects.get(id=id)
  205 + frame.lexical_units.add(lu)
  206 +
  207 +# preference_id = add_preference(frame_id, complement_id, operation['preference']['type'], operation['preference']['content'])
  208 +def add_preference(frame_id, complement_id, preference_type, preference_content):
  209 +
  210 + complement = Complement.objects.get(id=complement_id)
  211 + if complement.selective_preference is None:
  212 + sp = SelectivePreference()
  213 + sp.save()
  214 + complement.selective_preference = sp
  215 + complement.save()
  216 +
  217 + if preference_type == 'g':
  218 + general = GeneralSelectivePreference.objects.get(id=int(preference_content))
  219 + complement.selective_preference.generals.add(general)
  220 + return ('g', general.id)
  221 + elif preference_type == 's':
  222 + synset = Synset.objects.get(id=int(preference_content))
  223 + complement.selective_preference.synsets.add(synset)
  224 + return ('s', synset.id)
  225 + elif preference_type == 'r':
  226 + relation = SelectivePreferenceRelations.objects.get(id=int(preference_content['relation']))
  227 + argument = [int(a) for a in preference_content['to'].split(',')]
  228 + frame = SemanticFrame.objects.get(id=frame_id)
  229 + candidates = Complement.objects.filter(frame=frame)
  230 + found = None
  231 + for c in candidates:
  232 + if len(c.roles.all()) == len(argument):
  233 + roles = [r.id for r in c.roles.all()]
  234 + ok = True
  235 + for a in argument:
  236 + if a not in roles:
  237 + ok = False
  238 + if ok:
  239 + found = c
  240 + break
  241 + if found is not None:
  242 + rsp = RelationalSelectivePreference(relation=relation, to=found)
  243 + rsp.save()
  244 + complement.selective_preference.relations.add(rsp)
  245 + return ('r', rsp.id)
  246 + else:
  247 + return -1
  248 + else:
  249 + return -1
  250 +
  251 +# remove_preference(frame_id, complement_id, preference)
  252 +def remove_preference(frame_id, complement_id, preference):
  253 + preference_type, preference_id = preference
  254 + if preference_type == 'g':
  255 + complement = Complement.objects.get(id=complement_id)
  256 + g = complement.selective_preference.generals.get(id = int(preference_id))
  257 + complement.selective_preference.generals.remove(g)
  258 + elif preference_type == 's':
  259 + complement = Complement.objects.get(id=complement_id)
  260 + s = complement.selective_preference.synsets.get(id = int(preference_id))
  261 + complement.selective_preference.synsets.remove(s)
  262 + elif preference_type == 'r':
  263 + complement = Complement.objects.get(id=complement_id)
  264 + r = complement.selective_preference.relations.get(id = int(preference_id))
  265 + complement.selective_preference.relations.remove(r)
  266 +
  267 +
  268 +def update_meanings(operations):
  269 + translation = {}
  270 + for operation in operations:
  271 + if operation['operation'] == "set_glossa":
  272 + if int(operation['unit']) in translation:
  273 + unit = translation[int(operation['unit'])]
  274 + else:
  275 + unit = int(operation['unit'])
  276 + set_glossa(unit, operation['value'])
  277 + elif operation['operation'] == "add_example":
  278 + if int(operation['unit']) in translation:
  279 + unit = translation[int(operation['unit'])]
  280 + else:
  281 + unit = int(operation['unit'])
  282 + add_example(unit, operation['example'])
  283 + elif operation['operation'] == "remove_example":
  284 + if int(operation['unit']) in translation:
  285 + unit = translation[int(operation['unit'])]
  286 + else:
  287 + unit = int(operation['unit'])
  288 + remove_example(unit, operation['example'])
  289 + elif operation['operation'] == "add_unit":
  290 + translation[operation['unit']['id']] = add_unit(operation['unit'])
  291 + elif operation['operation'] == "remove_unit":
  292 + luid = int(operation['luid'])
  293 + if luid in translation:
  294 + remove_unit(translation[luid])
  295 + else:
  296 + remove_unit(luid)
  297 + else:
  298 + pass
  299 +
  300 +def set_glossa(unit_id, new_glossa):
  301 + unit = LexicalUnit.objects.get(id=unit_id)
  302 + unit.glossa = new_glossa
  303 + unit.save()
  304 +
  305 +def add_example(unit_id, example_id):
  306 + unit = LexicalUnit.objects.get(id=unit_id)
  307 + nkjp_example = NKJP_Example.objects.get(id=example_id)
  308 + lue = LexicalUnitExamples(example=nkjp_example, lexical_unit=unit)
  309 + lue.save()
  310 +
  311 +def remove_example(unit_id, example_id):
  312 + unit = LexicalUnit.objects.get(id=unit_id)
  313 + nkjp_example = NKJP_Example.objects.get(id=example_id)
  314 + lue = LexicalUnitExamples.objects.get(example=nkjp_example, lexical_unit=unit)
  315 + lue.delete()
  316 +
  317 +def add_unit(unit): # returns new id
  318 +
  319 + s1 = Synset(id=(min(Synset.objects.all().aggregate(Min('id'))['id__min'], 0) - 1))
  320 + s1.save()
  321 + lu = LexicalUnit(base=unit['base'], sense=unit['sense'], pos=unit['pos'], glossa=unit['glossa'], luid=-1, synset=s1)
  322 + lu.save()
  323 +
  324 +
  325 + if int(unit['relation']) == 1:
  326 + s2 = Synset.objects.get(id=int(unit['to']))
  327 + r = Synonymy(parent=s1, child=s2)
  328 + r.save()
  329 + r = Synonymy(parent=s2, child=s1)
  330 + r.save()
  331 + elif int(unit['relation']) == 0:
  332 + s2 = Synset.objects.get(id=int(unit['to']))
  333 + r = Hypernymy(parent=s1, child=s2)
  334 + r.save()
  335 + else:
  336 + pass
  337 +
  338 + return lu.id
  339 +
  340 +def remove_unit(luid):
  341 + lu = LexicalUnit.objects.get(id=luid)
  342 + if lu.luid is not None and lu.luid >= 0:
  343 + return
  344 + else:
  345 + lu.delete()
... ...
semantics/static/js/semantics_connections.js
1   -var connected = {}; // dictionaries of connections and disconnections between frames and schemas
2   -var connected_reverse = {};
  1 + var connected = {}; // dictionaries of connections and disconnections between frames and schemas
  2 + var connected_reverse = {};
3 3  
4 4 function memorizeConnections(arguments_connected, frames_connection){
5 5 connected = arguments_connected;
... ...
semantics/views.py
1 1 # -*- coding: utf-8 -*-
2 2  
3   -import locale
4 3 from semantics.models import SemanticRole, SemanticFrame, Complement, \
5 4 LexicalUnit, FrameRankings, SemanticRolesDisplay, \
6   - LexicalUnitExamples, FramePosition, SelectivePreference, \
7   - RelationalSelectivePreference, SelectivePreferenceRelations, \
  5 + LexicalUnitExamples, SelectivePreferenceRelations, \
8 6 GeneralSelectivePreference
9 7 from dictionary.models import Frame_Char_Model, Lemma, Lemma_Status, \
10   - sort_arguments, sort_positions, NKJP_Example, \
11   - Frame, Position, Argument
12   -from wordnet.models import Hypernymy, Synonymy, Synset
  8 + sort_arguments, sort_positions
13 9 from dictionary.ajax_lemma_view import user_can_modify
14 10 from django.core.exceptions import SuspiciousOperation
15 11 from django.core.urlresolvers import reverse
16 12 from django.db.models import Q
17   -from datetime import datetime
18   -from django.db.models import Min
19 13  
20   -from common.decorators import render, ajax, AjaxError
21   -from semantics.change_log import store_old_versions
  14 +from common.decorators import render, ajax
  15 +from semantics.saving import modify_frames, update_meanings
22 16 from semantics.validation import validate_schemas, validate_frames, validate_lexical_units
23 17  
24 18  
... ... @@ -450,344 +444,15 @@ def ajax_create_complement(request, lemma_id, frame, roles):
450 444  
451 445 @ajax(method='get', encode_result=False)
452 446 def ajax_update_meanings(request, operations, lemma_id):
453   - translation = {}
454   - for operation in operations:
455   - if operation['operation'] == "set_glossa":
456   - if int(operation['unit']) in translation:
457   - unit = translation[int(operation['unit'])]
458   - else:
459   - unit = int(operation['unit'])
460   - set_glossa(unit, operation['value'])
461   - elif operation['operation'] == "add_example":
462   - if int(operation['unit']) in translation:
463   - unit = translation[int(operation['unit'])]
464   - else:
465   - unit = int(operation['unit'])
466   - add_example(unit, operation['example'])
467   - elif operation['operation'] == "remove_example":
468   - if int(operation['unit']) in translation:
469   - unit = translation[int(operation['unit'])]
470   - else:
471   - unit = int(operation['unit'])
472   - remove_example(unit, operation['example'])
473   - elif operation['operation'] == "add_unit":
474   - translation[operation['unit']['id']] = add_unit(operation['unit'])
475   - elif operation['operation'] == "remove_unit":
476   - luid = int(operation['luid'])
477   - if luid in translation:
478   - remove_unit(translation[luid])
479   - else:
480   - remove_unit(luid)
481   - else:
482   - pass
483   -
  447 + update_meanings(operations)
484 448 return ajax_units(request)
485   -
486   -def set_glossa(unit_id, new_glossa):
487   - unit = LexicalUnit.objects.get(id=unit_id)
488   - unit.glossa = new_glossa
489   - unit.save()
490   -
491   -def add_example(unit_id, example_id):
492   - unit = LexicalUnit.objects.get(id=unit_id)
493   - nkjp_example = NKJP_Example.objects.get(id=example_id)
494   - lue = LexicalUnitExamples(example=nkjp_example, lexical_unit=unit)
495   - lue.save()
496   -
497   -def remove_example(unit_id, example_id):
498   - unit = LexicalUnit.objects.get(id=unit_id)
499   - nkjp_example = NKJP_Example.objects.get(id=example_id)
500   - lue = LexicalUnitExamples.objects.get(example=nkjp_example, lexical_unit=unit)
501   - lue.delete()
502   -
503   -def add_unit(unit): # returns new id
504   -
505   - s1 = Synset(id=(min(Synset.objects.all().aggregate(Min('id'))['id__min'], 0) - 1))
506   - s1.save()
507   - lu = LexicalUnit(base=unit['base'], sense=unit['sense'], pos=unit['pos'], glossa=unit['glossa'], luid=-1, synset=s1)
508   - lu.save()
509   -
510   -
511   - if int(unit['relation']) == 1:
512   - s2 = Synset.objects.get(id=int(unit['to']))
513   - r = Synonymy(parent=s1, child=s2)
514   - r.save()
515   - r = Synonymy(parent=s2, child=s1)
516   - r.save()
517   - elif int(unit['relation']) == 0:
518   - s2 = Synset.objects.get(id=int(unit['to']))
519   - r = Hypernymy(parent=s1, child=s2)
520   - r.save()
521   - else:
522   - pass
523   -
524   - return lu.id
525   -
526   -def remove_unit(luid):
527   - lu = LexicalUnit.objects.get(id=luid)
528   - if lu.luid is not None and lu.luid >= 0:
529   - return
530   - else:
531   - lu.delete()
532 449  
533 450 @ajax(method='get', encode_result=False)
534 451 def ajax_modify_frames(request, operations, lemma_id):
535   -
536 452 if not request.user.is_authenticated():
537 453 return 'user logged out'
538   -
539   - store_old_versions(lemma_id, operations, request.user)
540   -
541   - translation = {'frame_id': {}, 'complement_id': {}, 'preference_id': {}}
542   - for operation in operations:
543   - if operation['operation'] == "create_frame":
544   - luids = [int(m['id']) for m in operation['meanings']]
545   - translation['frame_id'][int(operation['id'])] = create_frame(luids)
546   - elif operation['operation'] == "remove_frame":
547   - if int(operation['id']) in translation['frame_id']:
548   - frame_id = translation['frame_id'][int(operation['id'])]
549   - else:
550   - frame_id = int(operation['id'])
551   - remove_frame(frame_id)
552   - elif operation['operation'] == "add_argument":
553   - if int(operation['frame_id']) in translation['frame_id']:
554   - frame_id = translation['frame_id'][int(operation['frame_id'])]
555   - else:
556   - frame_id = int(operation['frame_id'])
557   - roles = [int(r) for r in operation['role']]
558   - translation['complement_id'][int(operation['id'])] = add_argument(frame_id, roles)
559   - elif operation['operation'] == "remove_argument":
560   - if int(operation['frame_id']) in translation['frame_id']:
561   - frame_id = translation['frame_id'][int(operation['frame_id'])]
562   - else:
563   - frame_id = int(operation['frame_id'])
564   - if int(operation['complement_id']) in translation['complement_id']:
565   - complement_id = translation['complement_id'][int(operation['complement_id'])]
566   - else:
567   - complement_id = int(operation['complement_id'])
568   - remove_argument(frame_id, complement_id)
569   - elif operation['operation'] == "connect":
570   - frame_data = operation['arg'].split('_')
571   - if int(frame_data[1]) in translation['frame_id']:
572   - frame_id = translation['frame_id'][int(frame_data[1])]
573   - else:
574   - frame_id = int(frame_data[1])
575   - if int(frame_data[3]) in translation['complement_id']:
576   - complement_id = translation['complement_id'][int(frame_data[3])]
577   - else:
578   - complement_id = int(frame_data[3])
579   - schema_data = operation['connect'].split('_')
580   - schema_id = int(schema_data[1])
581   - position_id = int(schema_data[3])
582   - argument_id = int(schema_data[5])
583   - alternation = int(schema_data[7])
584   - connect(frame_id, complement_id, schema_id, position_id, argument_id, alternation)
585   - elif operation['operation'] == "disconnect":
586   - frame_data = operation['arg'].split('_')
587   - if int(frame_data[1]) in translation['frame_id']:
588   - frame_id = translation['frame_id'][int(frame_data[1])]
589   - else:
590   - frame_id = int(frame_data[1])
591   - if int(frame_data[3]) in translation['complement_id']:
592   - complement_id = translation['complement_id'][int(frame_data[3])]
593   - else:
594   - complement_id = int(frame_data[3])
595   - schema_data = operation['connect'].split('_')
596   - schema_id = int(schema_data[1])
597   - position_id = int(schema_data[3])
598   - argument_id = int(schema_data[5])
599   - alternation = int(schema_data[7])
600   - disconnect(frame_id, complement_id, schema_id, position_id, argument_id, alternation)
601   - elif operation['operation'] == "assign_role":
602   - if int(operation['frame_id']) in translation['frame_id']:
603   - frame_id = translation['frame_id'][int(operation['frame_id'])]
604   - else:
605   - frame_id = int(operation['frame_id'])
606   - if int(operation['complement_id']) in translation['complement_id']:
607   - complement_id = translation['complement_id'][int(operation['complement_id'])]
608   - else:
609   - complement_id = int(operation['complement_id'])
610   - roles = [int(r) for r in operation['role']]
611   - assign_role(frame_id, complement_id, roles)
612   - elif operation['operation'] == "change_units":
613   - if int(operation['frame_id']) in translation['frame_id']:
614   - frame_id = translation['frame_id'][int(operation['frame_id'])]
615   - else:
616   - frame_id = int(operation['frame_id'])
617   - luids = [int(m) for m in operation['units']]
618   - change_units(frame_id, luids)
619   - elif operation['operation'] == "add_preference":
620   - # {operation: 'add_preference', frame_id: frame_id, complement_id: complement_id, preference_id: preference_id, preference: preference}
621   - if int(operation['frame_id']) in translation['frame_id']:
622   - frame_id = translation['frame_id'][int(operation['frame_id'])]
623   - else:
624   - frame_id = int(operation['frame_id'])
625   - if int(operation['complement_id']) in translation['complement_id']:
626   - complement_id = translation['complement_id'][int(operation['complement_id'])]
627   - else:
628   - complement_id = int(operation['complement_id'])
629   - preference_id = add_preference(frame_id, complement_id, operation['preference']['type'], operation['preference']['content'])
630   - translation['preference_id'][operation['preference_id']] = preference_id
631   - elif operation['operation'] == "remove_preference":
632   - # {operation: 'remove_preference', frame_id: frame_id, complement_id: complement_id, preference_id: preference_id}
633   - if int(operation['frame_id']) in translation['frame_id']:
634   - frame_id = translation['frame_id'][int(operation['frame_id'])]
635   - else:
636   - frame_id = int(operation['frame_id'])
637   - if int(operation['complement_id']) in translation['complement_id']:
638   - complement_id = translation['complement_id'][int(operation['complement_id'])]
639   - else:
640   - complement_id = int(operation['complement_id'])
641   - if operation['preference_id'] in translation['preference_id']:
642   - preference_id = translation['preference_id'][operation['preference_id']]
643   - else:
644   - preference_id = (operation['preference_id'][0], int(operation['preference_id'][1:]))
645   -
646   - remove_preference(frame_id, complement_id, preference_id)
647   - else:
648   - pass
649   -
  454 + modify_frames(lemma_id, operations, request.user)
650 455 return ajax_frames(request)
651   -
652   -def create_frame(luids):
653   - frame = SemanticFrame()
654   - frame.save()
655   - for id in luids:
656   - lu = LexicalUnit.objects.get(id=id)
657   - frame.lexical_units.add(lu)
658   - return frame.id
659   -
660   -def change_units(frame_id, luids):
661   - frame = SemanticFrame.objects.get(id=frame_id)
662   - frame.lexical_units = []
663   - for id in luids:
664   - lu = LexicalUnit.objects.get(id=id)
665   - frame.lexical_units.add(lu)
666   -
667   -def remove_frame(frame_id):
668   - frame = SemanticFrame.objects.get(id=frame_id)
669   - frame.removed = True
670   - frame.save()
671   -
672   -def add_argument(frame_id, roles):
673   - if validate_roles(roles):
674   - frame = SemanticFrame.objects.get(id=frame_id)
675   - complement = Complement(frame=frame)
676   - complement.save()
677   - frame.complements.add(complement)
678   - role_objects = []
679   - for r in roles:
680   - role_objects.append(SemanticRole.objects.get(id=r))
681   - complement.roles = role_objects
682   - return complement.id
683   -
684   -def remove_argument(frame_id, complement_id):
685   - Complement.objects.get(id=complement_id).delete()
686   -
687   -def connect(frame_id, complement_id, schema_id, position_id, argument_id, alternation):
688   - schema = Frame.objects.get(id=schema_id)
689   - position = Position.objects.get(id=position_id)
690   - argument = Argument.objects.get(id=argument_id)
691   - fpas = FramePosition.objects.filter(frame=schema, position=position, argument=argument, alternation=alternation)
692   - if len(fpas) > 0:
693   - fpa = fpas[0]
694   - else:
695   - fpa = FramePosition(frame=schema, position=position, argument=argument, alternation=alternation)
696   - fpa.save()
697   - complement = Complement.objects.get(id=complement_id)
698   - complement.realizations.add(fpa)
699   -
700   -def disconnect(frame_id, complement_id, schema_id, position_id, argument_id, alternation):
701   - schema = Frame.objects.get(id=schema_id)
702   - position = Position.objects.get(id=position_id)
703   - argument = Argument.objects.get(id=argument_id)
704   - fpas = FramePosition.objects.filter(frame=schema, position=position, argument=argument, alternation=alternation)
705   - if len(fpas) > 0:
706   - fpa = fpas[0]
707   - else:
708   - return
709   - complement = Complement.objects.get(id=complement_id)
710   - complement.realizations.remove(fpa)
711   -
712   -def assign_role(frame_id, complement_id, roles):
713   - if validate_roles(roles):
714   - role_objects = []
715   - for r in roles:
716   - role_objects.append(SemanticRole.objects.get(id=r))
717   - complement = Complement.objects.get(id=complement_id)
718   - complement.roles = role_objects
719   -
720   -def validate_roles(roles):
721   - role_objects = []
722   - for r in roles:
723   - role_objects.append(SemanticRole.objects.get(id=r))
724   - if len(role_objects) > 2:
725   - return False
726   - ok = False
727   - for r in role_objects:
728   - if not r.color == None:
729   - ok = not ok
730   - return ok
731   -
732   -# preference_id = add_preference(frame_id, complement_id, operation['preference']['type'], operation['preference']['content'])
733   -def add_preference(frame_id, complement_id, preference_type, preference_content):
734   -
735   - complement = Complement.objects.get(id=complement_id)
736   - if complement.selective_preference is None:
737   - sp = SelectivePreference()
738   - sp.save()
739   - complement.selective_preference = sp
740   - complement.save()
741   -
742   - if preference_type == 'g':
743   - general = GeneralSelectivePreference.objects.get(id=int(preference_content))
744   - complement.selective_preference.generals.add(general)
745   - return ('g', general.id)
746   - elif preference_type == 's':
747   - synset = Synset.objects.get(id=int(preference_content))
748   - complement.selective_preference.synsets.add(synset)
749   - return ('s', synset.id)
750   - elif preference_type == 'r':
751   - relation = SelectivePreferenceRelations.objects.get(id=int(preference_content['relation']))
752   - argument = [int(a) for a in preference_content['to'].split(',')]
753   - frame = SemanticFrame.objects.get(id=frame_id)
754   - candidates = Complement.objects.filter(frame=frame)
755   - found = None
756   - for c in candidates:
757   - if len(c.roles.all()) == len(argument):
758   - roles = [r.id for r in c.roles.all()]
759   - ok = True
760   - for a in argument:
761   - if a not in roles:
762   - ok = False
763   - if ok:
764   - found = c
765   - break
766   - if found is not None:
767   - rsp = RelationalSelectivePreference(relation=relation, to=found)
768   - rsp.save()
769   - complement.selective_preference.relations.add(rsp)
770   - return ('r', rsp.id)
771   - else:
772   - return -1
773   - else:
774   - return -1
775   -
776   -# remove_preference(frame_id, complement_id, preference)
777   -def remove_preference(frame_id, complement_id, preference):
778   - preference_type, preference_id = preference
779   - if preference_type == 'g':
780   - complement = Complement.objects.get(id=complement_id)
781   - g = complement.selective_preference.generals.get(id = int(preference_id))
782   - complement.selective_preference.generals.remove(g)
783   - elif preference_type == 's':
784   - complement = Complement.objects.get(id=complement_id)
785   - s = complement.selective_preference.synsets.get(id = int(preference_id))
786   - complement.selective_preference.synsets.remove(s)
787   - elif preference_type == 'r':
788   - complement = Complement.objects.get(id=complement_id)
789   - r = complement.selective_preference.relations.get(id = int(preference_id))
790   - complement.selective_preference.relations.remove(r)
791 456  
792 457 @ajax(method='get', encode_result=True)
793 458 def ajax_plWN_context_lookup(request, term):
... ...