Blame view

fsabuilder/morfeuszbuilder/fsa/encode.py 9.15 KB
Michał Lenart authored
1
2
3
'''
Created on Oct 23, 2013
Michał Lenart authored
4
@author: mlenart
Michał Lenart authored
5
6
'''
Michał Lenart authored
7
8
9
10
from morfeuszbuilder.utils.serializationUtils import htons, serializeString
from morfeuszbuilder.utils import limits, exceptions

MAX_QUALIFIERS_COMBINATIONS = 1024
Michał Lenart authored
11
Michał Lenart authored
12
13
14
15
16
17
class Encoder(object):
    '''
    classdocs
    '''
Michał Lenart authored
18
    def __init__(self, lowercase, encoding='utf8'):
Michał Lenart authored
19
20
21
        '''
        Constructor
        '''
Michał Lenart authored
22
        self.lowercase = lowercase
Michał Lenart authored
23
        self.encoding = encoding
Michał Lenart authored
24
        self.qualifiersMap = { frozenset(): 0}
Michał Lenart authored
25
Michał Lenart authored
26
    def encodeWord(self, word, lowercase=True):
Michał Lenart authored
27
        assert type(word) == unicode
Michał Lenart authored
28
        res = bytearray(word.lower() if self.lowercase and lowercase else word, self.encoding)
Michał Lenart authored
29
        return res
Michał Lenart authored
30
31

    def encodeData(self, data):
Michał Lenart authored
32
        raise NotImplementedError()
Michał Lenart authored
33
34

    def decodeData(self, rawData):
Michał Lenart authored
35
        return NotImplementedError()
Michał Lenart authored
36
37
38

    def decodeWord(self, rawWord):
        return unicode(str(rawWord).strip('\x00'), self.encoding)
Michał Lenart authored
39
40

    def word2SortKey(self, word):
Michał Lenart authored
41
42
        normalizedWord = word.lower() if self.lowercase else word
        return normalizedWord.encode(self.encoding)
Michał Lenart authored
43
Michał Lenart authored
44
    def _encodeTypeNum(self, typenum):
Michał Lenart authored
45
46
47
        exceptions.validate(
                            typenum <= limits.MAX_SEGMENT_TYPES,
                            u'Too many segment types. The limit is %d' % limits.MAX_SEGMENT_TYPES)
Michał Lenart authored
48
49
        return bytearray([typenum])
Michał Lenart authored
50
51
52
53
54
55
56
57
    def _encodeQualifiers(self, qualifiers):
        res = bytearray()
        key = frozenset(qualifiers)
        if key in self.qualifiersMap:
            n = self.qualifiersMap[key]
        else:
            n = len(self.qualifiersMap)
            self.qualifiersMap[key] = n
Michał Lenart authored
58
59
60
        exceptions.validate(
                            n <= limits.MAX_QUALIFIERS_COMBINATIONS, 
                            u'Too many qualifiers combinations. The limit is %d' % limits.MAX_QUALIFIERS_COMBINATIONS)
Michał Lenart authored
61
        res.extend(htons(n))
Michał Lenart authored
62
63
        return res
Michał Lenart authored
64
    def _hasUpperPrefix(self, casePattern):
Michał Lenart authored
65
        for i in range(len(casePattern) + 1):
Michał Lenart authored
66
67
68
69
70
71
72
73
74
75
76
            if all(casePattern[:i]) and not any(casePattern[i:]):
                return True
        return False

    def _getUpperPrefixLength(self, casePattern):
        assert self._hasUpperPrefix(casePattern)
        for i in range(len(casePattern)):
            if not casePattern[i]:
                return i
        return len(casePattern)
Michał Lenart authored
77
78
    def _encodeTagNum(self, tagnum):
        res = bytearray()
Michał Lenart authored
79
        exceptions.validate(tagnum <= limits.MAX_TAGS, u'Too many tags. The limit is %d' % limits.MAX_TAGS)
Michał Lenart authored
80
81
82
83
84
        res.append((tagnum & 0xFF00) >> 8)
        res.append(tagnum & 0x00FF)
        return res

    def _encodeNameNum(self, namenum):
Michał Lenart authored
85
        exceptions.validate(namenum <= limits.MAX_NAMES, u'Too many named entity types. The limit is %d' % limits.MAX_NAMES)
Michał Lenart authored
86
        return bytearray([namenum])
Michał Lenart authored
87
88
89
90
91
92
93
94

    def _groupInterpsByType(self, interpsList):
        res = {}
        for interp in interpsList:
            res.setdefault(interp.typenum, [])
            res[interp.typenum].append(interp)
        return res
Michał Lenart authored
95
96
97
98
99
100
101
102
103
104
105
106
107
    def _doEncodeData(self, interpsList):

        assert type(interpsList) == frozenset

        segnum2Interps = self._groupInterpsByType(interpsList)


        res = bytearray()

        for typenum, interpsList in segnum2Interps.iteritems():
            res.extend(self._encodeInterps4Type(typenum, interpsList))
        del interpsList
Michał Lenart authored
108
109
        res = htons(len(res)) + res
Michał Lenart authored
110
111
112
113
114
115
116
117
118
119
120
        return res

class MorphEncoder(Encoder):

    def __init__(self, encoding='utf8'):
        super(MorphEncoder, self).__init__(True, encoding)

    def encodeData(self, interpsList):
        return self._doEncodeData(interpsList)

    def _getMinOrthCasePatterns(self, interpsList):
Michał Lenart authored
121
        res = []
Michał Lenart authored
122
        for interp in interpsList:
Michał Lenart authored
123
            if not True in interp.orthCasePattern:
Michał Lenart authored
124
                return []
Michał Lenart authored
125
            else:
Michał Lenart authored
126
                res.append(list(interp.orthCasePattern))
Michał Lenart authored
127
128
        return res
Michał Lenart authored
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
    def _encodeCasePattern(self, casePattern):

        LEMMA_ONLY_LOWER = 0
        LEMMA_UPPER_PREFIX = 1
        LEMMA_MIXED_CASE = 2

        res = bytearray()
        if True not in casePattern:
            res.append(LEMMA_ONLY_LOWER)
            return res
        elif self._hasUpperPrefix(casePattern):
            res.append(LEMMA_UPPER_PREFIX)
            res.append(self._getUpperPrefixLength(casePattern))
            return res
        else:
            assert len(casePattern) < 256
            res.append(LEMMA_MIXED_CASE)
            res.append(len([c for c in casePattern if c]))
            for idx in range(len(casePattern)):
                if casePattern[idx]:
                    res.append(idx)
            return res

    def _casePatternsHaveOnlyLowercase(self, casePatterns):
        return not any(map(lambda cp: cp and True in cp, casePatterns))

    def _casePatternsAreOnlyTitles(self, casePatterns):
Michał Lenart authored
156
        return all(map(lambda cp: cp and cp[0] == True and not True in cp[1:], casePatterns))
Michał Lenart authored
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

    def _casePatternsAreEncodedInCompressByte(self, casePatterns):
        return self._casePatternsHaveOnlyLowercase(casePatterns) or self._casePatternsAreOnlyTitles(casePatterns)

    def _prefixCutsAreEncodedInCompressByte(self, prefixCuts):
        return len(prefixCuts) == 1 and list(prefixCuts)[0] < 15

    def _encodeCompressByte(self, orthCasePatterns, lemmaCasePatterns, prefixCuts):
        ORTH_ONLY_LOWER = 128
        ORTH_ONLY_TITLE = 64
        LEMMA_ONLY_LOWER = 32
        LEMMA_ONLY_TITLE = 16
        PREFIX_CUT_MASK = 15
        res = 0
        if self._casePatternsHaveOnlyLowercase(orthCasePatterns):
            res |= ORTH_ONLY_LOWER
        elif self._casePatternsAreOnlyTitles(orthCasePatterns):
            res |= ORTH_ONLY_TITLE
        if self._casePatternsHaveOnlyLowercase(lemmaCasePatterns):
            res |= LEMMA_ONLY_LOWER
        elif self._casePatternsAreOnlyTitles(lemmaCasePatterns):
            res |= LEMMA_ONLY_TITLE

        if self._prefixCutsAreEncodedInCompressByte(prefixCuts):
            res |= list(prefixCuts)[0]
        else:
            res |= PREFIX_CUT_MASK

        return res

    def _encodeInterps4Type(self, typenum, interpsList):
Michał Lenart authored
188
189
        res = bytearray()
        res.extend(self._encodeTypeNum(typenum))
Michał Lenart authored
190
Michał Lenart authored
191
        encodedInterpsList = bytearray()
Michał Lenart authored
192
193
194
195
196
197
198
199
200
201
202

        orthCasePatterns = set([tuple(interp.orthCasePattern) for interp in interpsList])
        lemmaCasePatterns = set([tuple(interp.encodedForm.casePattern) for interp in interpsList])
        prefixCuts = set([interp.encodedForm.prefixCutLength for interp in interpsList])

        encodedInterpsList.append(self._encodeCompressByte(orthCasePatterns, lemmaCasePatterns, prefixCuts))

        if not self._casePatternsAreEncodedInCompressByte(orthCasePatterns):
            minOrthCasePatterns = self._getMinOrthCasePatterns(interpsList)
            encodedInterpsList.append(len(minOrthCasePatterns))
            for casePattern in minOrthCasePatterns:
Michał Lenart authored
203
                encodedInterpsList.extend(self._encodeCasePattern(casePattern))
Michał Lenart authored
204
Michał Lenart authored
205
        for interp in sorted(interpsList, key=lambda i: i.getSortKey()):
Michał Lenart authored
206
            if not self._casePatternsAreEncodedInCompressByte(orthCasePatterns):
Michał Lenart authored
207
                encodedInterpsList.extend(self._encodeCasePattern(interp.orthCasePattern))
Michał Lenart authored
208
209
            if not self._prefixCutsAreEncodedInCompressByte(prefixCuts):
                encodedInterpsList.append(interp.encodedForm.prefixCutLength)
Michał Lenart authored
210
            encodedInterpsList.append(interp.encodedForm.cutLength)
Michał Lenart authored
211
            encodedInterpsList.extend(serializeString(interp.encodedForm.suffixToAdd))
Michał Lenart authored
212
            if not self._casePatternsAreEncodedInCompressByte(lemmaCasePatterns):
Michał Lenart authored
213
214
215
                encodedInterpsList.extend(self._encodeCasePattern(interp.encodedForm.casePattern))
            encodedInterpsList.extend(htons(interp.tagnum))
            encodedInterpsList.append(interp.namenum)
Michał Lenart authored
216
            encodedInterpsList.extend(self._encodeQualifiers(interp.qualifiers))
Michał Lenart authored
217
Michał Lenart authored
218
        res.extend(htons(len(encodedInterpsList)))
Michał Lenart authored
219
220
        res.extend(encodedInterpsList)
        return res
Michał Lenart authored
221
222
223
224

class Encoder4Generator(Encoder):

    def __init__(self, encoding='utf8'):
Michał Lenart authored
225
        super(Encoder4Generator, self).__init__(False, encoding)
Michał Lenart authored
226
227

    def encodeData(self, interpsList):
Michał Lenart authored
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
        return self._doEncodeData(interpsList)

    def _encodeInterps4Type(self, typenum, interpsList):
        res = bytearray()
        res.extend(self._encodeTypeNum(typenum))
        encodedInterpsList = bytearray()
        for interp in sorted(interpsList, key=lambda i: i.getSortKey()):
            encodedInterpsList.extend(serializeString(interp.homonymId))
            encodedInterpsList.extend(serializeString(interp.encodedForm.prefixToAdd))
            encodedInterpsList.append(interp.encodedForm.cutLength)
            encodedInterpsList.extend(serializeString(interp.encodedForm.suffixToAdd))
            encodedInterpsList.extend(htons(interp.tagnum))
            encodedInterpsList.append(interp.namenum)
            encodedInterpsList.extend(self._encodeQualifiers(interp.qualifiers))

        res.extend(htons(len(encodedInterpsList)))
        res.extend(encodedInterpsList)
        return res