Frame.py 2.82 KB
#! /usr/bin/python
# -*- coding: utf-8 -*-

from importer.Argument import Argument
from semantics.models import FrameOpinion
import semantics.models

        
class Frame:

    def __init__(self, id, base, pos, opinion, meanings, arguments):
        self._id = id
        self._base = base
        self._pos = pos
        self._opinion = opinion
        self._meanings = meanings
        self._arguments = arguments
        self._db_id = None

    def _resolveReferences(self, references):
        for reference in references:
            reference._to = self._arguments[reference._to]
        
    @classmethod
    def fromTree(cls, base, pos, frame_tree):
        if 'sameAs' in frame_tree._attrs:
            return cls(frame_tree._attrs['sameAs'][1:], None, None, None, None, None)
        else:
            arguments = {}
            id = frame_tree._attrs['xml:id']
            opinion = frame_tree._children[0]._children[0]._attrs['value']
            meanings = [meaning._attrs['sameAs'][1:] for meaning in frame_tree._children[1]._children[0]._children]
            for argument_tree in frame_tree._children[2]._children[0]._children:
                argument = Argument.fromTree(argument_tree)
                arguments[argument.getId()] = argument

            result = cls(id, base, pos, opinion, meanings, arguments)
            for argument in arguments.values():
                argument._frame = result
            for argument in arguments.values():
                result._resolveReferences(argument._references)
            return result


    def store(self, entry, meanings):
        args = 0
        frames = []
        if self._db_id is not None:
            frames = semantics.models.Frame.objects.filter(id=self._db_id)
        if len(frames) == 0 and self._base is not None:
            opinion = FrameOpinion.objects.get(key=self._opinion)
            frame = semantics.models.Frame(opinion=opinion)
            frame.save()
            self._db_id = frame.id
            arguments = {}
            for argument in self._arguments.values():
                a = argument.store(frame)
                arguments[argument] = a
                args += 1
            frame.refresh_from_db()
            frame.arguments_count = args
            frame.save()
            for argument in self._arguments.values():
                argument.store_preferences(frame, arguments[argument])
            for meaning_id in self._meanings:
                if meaning_id in meanings:
                    lemma, meaning = meanings[meaning_id]
                    meaning.store(entry, frame)
                
    
    def getSignature(self):
        return self._base + '\t[' + ','.join([str(meaning) for meaning in self._meanings]) + ']'

    def __str__(self):
        return self.getSignature() + '\t[' + ','.join([str(argument) for argument in self._arguments.values()]) + ']'