models.py 1.83 KB
Newer Older
1
2
3
4
import json
import os
from collections import defaultdict

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
5

6
7
8
9
10
11
12
13
14
15
16
17
18
class Leaf(defaultdict):
    def __init__(self, ofclass=list):
        super(Leaf, self).__init__(ofclass)

    def __getattr__(self, name):
        return super(Leaf, self).__getitem__(name)

    def __setattr__(self, name, value):
        self[name] = value

    def __delattr__(self, name):
        return super(Leaf, self).__delitem__(name)

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
19

20
21
22
23
24
25
26
class Response(Leaf):
    def __init__(self, context=None):
        super(Response, self).__init__()
        self["analysis"] = []
        self["entries"] = []
        if context is None:
            context = "{}/context.jsonld".format(os.path.dirname(
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
27
                os.path.realpath(__file__)))
28
29
        if isinstance(context, dict):
            self["@context"] = context
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
30
        if isinstance(context, str) or isinstance(context, unicode):
31
32
33
34
35
36
37
38
            try:
                with open(context) as f:
                    self["@context"] = json.loads(f.read())
            except IOError:
                self["@context"] = context


class Entry(Leaf):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
39
    def __init__(self, text=None, emotion_sets=None, opinions=None, **kwargs):
40
41
42
        super(Entry, self).__init__(**kwargs)
        if text:
            self.text = text
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
43
44
        if emotion_sets:
            self.emotionSets = emotion_sets
45
46
47
        if opinions:
            self.opinions = opinions

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
48

49
class Opinion(Leaf):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
50
    def __init__(self, polarity_value=None, polarity=None, **kwargs):
51
        super(Opinion, self).__init__(**kwargs)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
52
53
        if polarity_value is not None:
            self.polarity_value = polarity_value
54
55
56
57
58
        if polarity is not None:
            self.polarity = polarity


class EmotionSet(Leaf):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
59
60
61
    def __init__(self, emotions=None, **kwargs):
        if not emotions:
            emotions = []
62
63
        super(EmotionSet, self).__init__(**kwargs)
        self.emotions = emotions or []