views.py 19 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
import datetime
import operator
import time

from collections import defaultdict
from functools import reduce
from itertools import chain

import simplejson

from django.db.models import Q
from django.http import JsonResponse, QueryDict
from django.shortcuts import render
from django.template.context_processors import csrf
from django.utils.translation import gettext as _

from crispy_forms.utils import render_crispy_form

from connections.models import Entry, Subentry, ArgumentConnection
from syntax.models import NaturalLanguageDescription, Schema
from semantics.models import Frame

from common.decorators import ajax_required

from .forms import (
    #MainEntryForm,
    EntryForm,
    SchemaFormFactory,
    FrameFormFactory,
    PositionFormFactory,
    PhraseAttributesFormFactory,
    LexFormFactory,
    LemmaFormFactory,
    ArgumentFormFactory,
    PredefinedPreferenceFormFactory,
    RelationalPreferenceFormFactory,
    SynsetPreferenceFormFactory,
)

from .polish_strings import SCHEMA_OPINION, FRAME_OPINION, EXAMPLE_SOURCE, EXAMPLE_OPINION, RELATION

from .phrase_descriptions.descriptions import position_prop_description

MAX_LAST_VISITED = 10

def test(request):
    return render(request, 'test.html', {})

def entries(request):
    # TODO make this automatic by subclassing/configuring session object
    if 'last_visited' not in request.session:
        request.session['last_visited'] = []
    return render(request, 'entries.html', { 'entries_form' : EntryForm() })

FORM_TYPES = {
    #'entry-main' : MainEntryForm,
    'entry'      : EntryForm,
    
}

FORM_FACTORY_TYPES = {
    'schema'     : SchemaFormFactory,
    'position'   : PositionFormFactory,
    'phrase_lex' : LexFormFactory,
    'lemma'      : LemmaFormFactory,
    'frame'      : FrameFormFactory,
    'argument'   : ArgumentFormFactory,
    'predefined' : PredefinedPreferenceFormFactory,
    'relational' : RelationalPreferenceFormFactory,
    'synset'     : SynsetPreferenceFormFactory,
}


def make_form(form_type, data=None, unique_number=None):
    #print('======== MAKE FORM', form_type)
    if form_type in FORM_FACTORY_TYPES:
        return FORM_FACTORY_TYPES[form_type].get_form(data=data, unique_number=unique_number)
    if form_type in FORM_TYPES:
        return FORM_TYPES[form_type](data=data)
    elif form_type.startswith('phrase_'):
        phrase_type = form_type[7:]
        #print('================ MAKE PHRASE FORM', phrase_type, unique_number)
        return PhraseAttributesFormFactory.get_form(phrase_type, data=data, unique_number=unique_number)
    return None


@ajax_required
def get_subform(request):
    if request.method == 'GET':
        ctx = {}
        ctx.update(csrf(request))
        form_type = request.GET['subform_type']
        form = make_form(form_type)
        try:
            form_html = render_crispy_form(form, context=ctx)
        except:
            print('******************', form_type)
            raise
        return JsonResponse({'form_html' : form_html})
    
#TODO clean this code bordello up

def filter_objects(objects, queries, tab=''):
    #print(tab + '===================================================================')
    for query in queries:
        #print(tab + '***', query)
        objects = objects.filter(query).distinct()
        #print(tab + '---------------------------------------------------------------')
        #print(tab, objects)
        #print('\n')
    #print(tab + '===================================================================')
    return objects.distinct()


def collect_forms(forms_json, tab='   '):
    data = simplejson.loads(forms_json)
    form_type = data['formtype']
    form_number = data.get('formnumber', 0)
    if form_type == 'or':
        return 'or'
    else:
        #print(tab, 'FORM:', data['form'])
        #print(tab, 'TYPE:', form_type, 'NUMBER:', form_number)
        #print(tab, 'DATA:', data)
        query_params = QueryDict(data['form'])
        #print(tab, 'PARAMS:', query_params)
        form = make_form(form_type, data=query_params, unique_number=form_number)
        #print(tab, 'FORM TYPE:', type(form))
        if not form.is_valid():
            print(form.errors)
            # TODO return validation errors
            1/0
        #print(tab, '{} CHILDREN GROUP(S)'.format(len(data['children'])))
        # a form may have one or more children forms, organised into and-or
        # (e.g. an entry form has child schema forms, frame forms etc.)
        subform_groups = []
        for subforms_json in data['children']:
            subform_group = simplejson.loads(subforms_json)
            subform_type, subforms = subform_group['formtype'], subform_group['subforms']
            children = [[]]
            for child in subforms:
                child_form = collect_forms(child, tab + '    ')
                if child_form == 'or':
                    children.append([])
                else:
                    children[-1].append(child_form)
            subforms = list(filter(None, children))
            if subforms:
                subform_groups.append((subform_type, subforms))
        return (form, subform_groups)


def get_filtered_objects(forms, initial_objects=None, tab='   '):
    form, children = forms
    objects = form.model_class.objects.all() if initial_objects is None else initial_objects.all()
    queries = form.get_queries()
    #print(tab, type(form), 'FOR FILTERING:', form.model_class)
    #print(tab, queries)
    objects = filter_objects(objects, queries, tab=tab)
    #print(tab, 'OK')
    for children_group in children:
        #print(tab, 'CHILD FORMS')
        object_ids_or = []
        prefixes = set()
        for or_children in children_group[1]:
            objects_and = form.model_class.objects.all() if initial_objects is None else initial_objects.all()
            for child in or_children:
                child_form = child[0]
                child_objects = get_filtered_objects(child, tab=tab + '        ')
                prefix = form.get_child_form_prefix(child_form)
                prefixes.add(prefix)
                child_ids = [co.id for co in child_objects]
                q = Q((prefix, child_ids))
                if child[0].is_negated():
                    objects_and = objects_and.exclude(q)
                else:
                    objects_and = objects_and.filter(q)
            object_ids_or.append({o.id for o in objects_and})
        assert(len(prefixes) == 1)
        object_ids = reduce(operator.or_, object_ids_or)
        objects = objects.filter(id__in=object_ids)
    objects = objects.distinct()
    #print(tab, 'FILTERED:', form.model_class)
    return objects
            

# forms – an ‘or’ list of ‘and’ lists of forms, the forms are flattened and treated as one ‘or’ list.
# The function is used for filtering out schemata/frames. E.g. if the user chooses entries with a schema
# safisfying X AND a schema satisfying Y, schemata satisfying X OR Y should be displayed (and all other
# schemata should be hidden).
def get_filtered_objects2(objects, forms):
    filtered_ids = [{ schema.id for schema in get_filtered_objects(form, initial_objects=objects) } for form in chain.from_iterable(forms)]
    filtered_ids = reduce(operator.or_, filtered_ids)
    return objects.filter(id__in=filtered_ids)


@ajax_required
def send_form(request):
    t1 = datetime.datetime.now()
    if request.method == 'POST':
        forms = collect_forms(request.POST['forms[]'])
        # TODO return validation errors
        #    #if not form.is_valid():
        #    #    print(form.errors)
        #    #    return JsonResponse({ 'errors' : form.errors })
        request.session['forms'] = request.POST['forms[]']
        return JsonResponse({ 'success' : 1 })
    return JsonResponse({})

def get_scroller_params(POST_data):
    order = (int(POST_data['order[0][column]']), POST_data['order[0][dir]'])
    return {
        'draw'   : int(POST_data['draw']),
        'start'  : int(POST_data['start']),
        'length' : int(POST_data['length']),
        'order'  : order,
        'filter' : POST_data['search[value]']
    }

@ajax_required
def get_entries(request):
    if request.method == 'POST':
        forms = collect_forms(request.session['forms'])
        scroller_params = get_scroller_params(request.POST)
        entries = get_filtered_objects(forms)
        total = entries.count()
        if scroller_params['filter']:
            entries = entries.filter(name__startswith=scroller_params['filter'])
        filtered = entries.count()
        i, j = scroller_params['start'], scroller_params['start'] + scroller_params['length']
        order_field, order_dir = scroller_params['order']
        if order_field != 0 or order_dir != 'asc':
            # ordering other than lemma ascending (database default)
            order_field = 'name' if order_field == 0 else 'status__key'
            if order_dir == 'desc':
                order_field = '-' + order_field
            entries = entries.order_by(order_field)
        entries_list = list(entries.values('id', 'name', 'status__key'))
        result = {
            'draw' : scroller_params['draw'],
            'recordsTotal': total,
            'recordsFiltered': filtered,
            'data': entries_list[i:j],
        }
        return JsonResponse(result)
    return JsonResponse({})


def subentry2str(subentry):
    ret = subentry.entry.name
    if subentry.inherent_sie.name == 'true':
        ret += ' się'
    elems = []
    if subentry.aspect:
        elems.append(subentry.aspect.name)
    if subentry.negativity:
        elems.append(subentry.negativity.name)
    if elems:
        ret += ' ({})'.format(', '.join(elems))
    if subentry.predicativity.name == 'true':
        ret += ' pred.'
    return ret


def position_prop2dict(prop):
    return {
        'str'  : prop.name,
        'desc' : position_prop_description(prop.name),
    } if prop else {
        'str'  : '',
        'desc' : '',
    }


def get_phrase_desc(phrase, position, negativity, lang):
    return NaturalLanguageDescription.objects.get(
            phrase_str=phrase.text_rep,
            function=position.function,
            control=position.control,
            pred_control=position.pred_control,
            negativity=negativity,
            lang=lang).description


def schema2dict(schema, negativity, lang):
    return {
        'opinion'     : SCHEMA_OPINION()[schema.opinion.key],
        'opinion_key' : schema.opinion.key,
        'id'          : str(schema.id),
        'positions'   : [
            {
                'func'      : position_prop2dict(p.function),
                'control'   : position_prop2dict(p.control),
                'p_control' : position_prop2dict(p.pred_control),
                'phrases' : [
                    {
                        'str'       : str(pt),
                        'id'        : '{}-{}-{}'.format(schema.id, p.id, pt.id),
                        'desc'      : get_phrase_desc(pt, p, negativity, lang),
                    } for pt in p.phrase_types.all()
                ],
            } for p in schema.positions.all()
         ],
    }


def get_rel_pref_desc(pref):
    relation = pref.relation.key
    if relation == 'RELAT':
        desc = _('Realizacja tego argumentu w zdaniu powinna być powiązana jakąkolwiek relacją')
    else:
        desc = _('Realizacja tego argumentu w zdaniu powinna być powiązana relacją <i>{}</i>').format(RELATION()[relation])
    return desc + ' ' + _('z realizacją argumentu <i>{}</i>.').format(pref.to)


def get_prefs_list(argument):
    return sorted(
        ({
            'str' : str(p),
        } for p in argument.predefined.all()),
        key=lambda x: x['str']
    ) + sorted(
        ({
            'str' : str(s),
            'url' : 'http://plwordnet21.clarin-pl.eu/synset/{}'.format(s.id),
        } for s in argument.synsets.all()),
        key=lambda x: x['str']
    ) + sorted(
        ({
            'str'  : str(r),
            'info' : get_rel_pref_desc(r),
        } for r in argument.relations.all()),
        key=lambda x: x['str']
    )


def frame2dict(frame, entry_meanings):
    return {
        'opinion'       : FRAME_OPINION()[frame.opinion.key],
        'opinion_key'   : frame.opinion.key,
        'id'            : str(frame.id),
        'lexical_units' : [
            {
                'str'           : lu.text_rep,
                'id'            : lu.id,
                'entry_meaning' : lu in entry_meanings,
                'definition'    : lu.definition,
                'gloss'         : lu.gloss,
                'url'           : None if lu.luid is None else 'http://plwordnet21.clarin-pl.eu/lemma/{}/{}'.format(lu.base, lu.sense)
            } for lu in frame.lexical_units.all()
        ],
        'arguments'     : [
            {
                'str'         : str(a),
                'id'          : '{}-{}'.format(frame.id, a.id),
                'role'        : '{}{}'.format(a.role.role.role.lower(), ' ' + a.role.attribute.attribute.lower() if a.role.attribute else ''),
                'preferences' : get_prefs_list(a),
            } for a in sorted(frame.arguments.all(), key=lambda a: a.role.role.priority + (a.role.attribute.priority if a.role.attribute else 2))
        ],
    }

# returns a dict: {
#     frame_id1 : {
#         schema_id1 : { [alt_1*, ..., alt_l] }
#         schema_idk : {...}
#     }
#     ...
#     frame_idn : {...}
# }
# *alternation is a dict: {
#    key: extended argument id (frame_id-arg_id)
#    val: list of extended phrase ids (schema_id-position_id-phr_id)
def get_alternations(schemata, frames):
    # TODO czy alternacja może być podpięta do całej pozycji, bez konkretnej frazy?
    alternations = defaultdict(lambda: defaultdict(lambda: defaultdict(lambda: defaultdict(list))))
    for schema in schemata:
        for hook in schema.schema_hooks.all():
            arg_conns = hook.argument_connections.all()
            assert (len(arg_conns) < 2)
            if (arg_conns):
                argument = arg_conns[0].argument
                frame = argument.frame
                if frame not in frames:
                    continue
                phr_id = '{}-{}-{}'.format(schema.id, hook.position.id, hook.phrase_type.id)
                arg_id = '{}-{}'.format(frame.id, argument.id)
                alternations[frame.id][schema.id][hook.alternation][arg_id].append(phr_id)
    alt_dict = defaultdict(lambda: defaultdict(list))
    for frame_id, frame_schema_alternations in alternations.items():
        for schema_id, schema_alternations in frame_schema_alternations.items():
            for alt_no in sorted(schema_alternations.keys()):
                alt_dict[frame_id][schema_id].append(schema_alternations[alt_no])
    return alt_dict

def get_examples(entry):
    examples = []
    for example in entry.examples.all():
        frame_ids, argument_ids, lu_ids, schema_ids, phrases, phrases_syntax = set(), set(), set(), set(), set(), set()
        for connection in example.example_connections.all():
            for argument in connection.arguments.all():
                frame_ids.add(argument.frame.id)
                argument_ids.add('{}-{}'.format(argument.frame.id, argument.id))
            if connection.lexical_unit:
                lu_ids.add(connection.lexical_unit.id)
            for hook in connection.schema_connections.all():
                schema_ids.add(hook.schema.id);
                phrases.add('{}-{}-{}-{}'.format(hook.schema.id, hook.position.id, hook.phrase_type.id, hook.alternation - 1))
                phrases_syntax.add('{}-{}-{}'.format(hook.schema.id, hook.position.id, hook.phrase_type.id))
        examples.append({
            'id'             : str(example.id),
            'sentence'       : example.sentence,
            'source'         : EXAMPLE_SOURCE()[example.source.key],
            'opinion'        : EXAMPLE_OPINION()[example.opinion.key],
            'note'           : example.note,
            'frame_ids'      : sorted(frame_ids),
            'argument_ids'   : sorted(argument_ids),
            'lu_ids'         : sorted(lu_ids),
            'schema_ids'     : sorted(schema_ids),
            'phrases'        : sorted(phrases),
            'phrases_syntax' : sorted(phrases_syntax),
        })
    return sorted(examples, key=lambda x: x['sentence'])

@ajax_required
def get_entry(request):
    if request.method == 'POST':
        form = EntryForm(request.POST)
        eid = request.POST['entry']
        if eid.isdigit() and form.is_valid():
            eid = int(eid)
            entry = Entry.objects.get(id=eid)
            
            entry_form, children_forms = collect_forms(request.POST['forms[]'])
            filter_schemata, filter_frames = entry_form.cleaned_data['filter_schemata'], entry_form.cleaned_data['filter_frames']
            if filter_schemata:
                schema_forms = [frms[1] for frms in children_forms if frms[0] == 'schema']
                assert (len(schema_forms) <= 1)
                if schema_forms:
                    schema_forms = schema_forms[0]
                else:
                    filter_schemata = False
            if filter_frames:
                frame_forms = [frms[1] for frms in children_forms if frms[0] == 'frame']
                assert (len(frame_forms) <= 1)
                if frame_forms:
                    frame_forms = frame_forms[0]
                else:
                    filter_frames = False
            
            subentries = []
            all_schema_objects = []
            for subentry in entry.subentries.all():
                schemata = []
                schema_objects = subentry.schemata.all()
                if filter_schemata:
                    schema_objects = get_filtered_objects2(schema_objects, schema_forms)
                for schema in schema_objects:
                    schemata.append(schema2dict(schema, subentry.negativity, request.LANGUAGE_CODE))
                if schemata:
                    all_schema_objects += list(schema_objects)
                    subentries.append({ 'str' : subentry2str(subentry), 'schemata' : schemata })
            frame_objects = Frame.objects.filter(arguments__argument_connections__schema_connections__subentry__entry=entry).distinct()
            if filter_frames:
                frame_objects = get_filtered_objects2(frame_objects, frame_forms)
            frames = [frame2dict(frame, entry.lexical_units.all()) for frame in frame_objects]
            alternations = get_alternations(all_schema_objects, frame_objects)
            examples = get_examples(entry)
            if 'last_visited' not in request.session:
                request.session['last_visited'] = []
            # https://docs.djangoproject.com/en/2.2/topics/http/sessions/#when-sessions-are-saved
            if [entry.name, entry.id] in request.session['last_visited']:
                request.session['last_visited'].remove([entry.name, entry.id])
            request.session['last_visited'].insert(0, (entry.name, entry.id))
            request.session['last_visited'] = request.session['last_visited'][:(MAX_LAST_VISITED + 1)]
            request.session.modified = True
            return JsonResponse({ 'subentries' : subentries, 'frames' : frames, 'alternations' : alternations, 'examples' : examples, 'last_visited' : request.session['last_visited'] })
    return JsonResponse({})