morfosegment.py
8.93 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
# -*- coding: utf-8 -*-
import morfeusz2
import itertools
def unique_everseen(iterable, key=None):
"List unique elements, preserving order. Remember all elements ever seen."
# unique_everseen('AAAABBBCCDAABBB') --> A B C D
# unique_everseen('ABBCcAD', str.lower) --> A B C D
seen = set()
seen_add = seen.add
if key is None:
for element in itertools.ifilterfalse(seen.__contains__, iterable):
seen_add(element)
yield element
else:
for element in iterable:
k = key(element)
if k not in seen:
seen_add(k)
yield element
class LogicError(Exception):
pass
class Analyse():
#dict_dir - katalog z słownikiem do Morfeusza
#dict_name - nazwa słownika
def __init__(self, dict_dir, dict_name, stats_dir=''):
self.dict_dir = dict_dir
self.dict_name = dict_name
self.morfeusz = morfeusz2.Morfeusz(dict_name = self.dict_name, dict_path=self.dict_dir, generate=False, expand_underscore=True, expand_dot=True, expand_tags = True)
#analiza tekstu Morfeuszem (nie ma znaczników xml wewnątrz)
def text_analyse(self, source_text):
morf_result = self.morfeusz.analyse(source_text)
segs = {}
by_start = {}
for r in morf_result:
#print(str(r))
start_node = r[0]
end_node = r[1]
interp = r[2]
word = interp[0]
if (start_node, end_node) not in segs:
seg = {"orth" : word, "interps" : [self.create_interp(interp)], "start" : start_node, "end" : end_node}
segs[(start_node, end_node)] = seg
if start_node not in by_start:
by_start[start_node] = []
by_start[start_node].append(seg)
else:
segs[(start_node, end_node)]["interps"].append(self.create_interp(interp))
eoffsets = {0:0}
boffsets = {}
maxpos = -1
for pos, sgs in sorted(by_start.items()):
for s in sgs:
b = source_text[eoffsets[s["start"]]:].find(s["orth"])+eoffsets[s["start"]]
e = b + len(s["orth"])
if s["start"] in boffsets and b != boffsets[s["start"]]:
print(repr(s))
print(s["orth"].encode('utf-8'))
print(source_text.encode('utf-8'))
raise LogicError("problem z pozycja segmentow w tekscie")
if s["end"] in eoffsets and e != eoffsets[s["end"]]:
#print repr(s)
#print e
#print b
#print repr(boffsets)
#print repr(eoffsets)
raise LogicError("problem z pozycja segmentow w tekscie")
boffsets[s["start"]] = b
eoffsets[s["end"]] = e
s["offset"] = boffsets[s["start"]]
if eoffsets[s["start"]] == boffsets[s["start"]] and s["start"] > 0:
s["nps"] = True
maxpos = pos
ret = []
pos = 0
###
#for x, v in by_start.items():
#print(x)
#for y in v:
#ay = dict(y)
#del ay['interps']
#print(" ", repr(ay))
#print()
###
while pos <= maxpos:
c, pos = self.make_choice(by_start, pos, source_text)
#print(pos, repr(c))
#print()
ret.append(c)
#usuń dublety w interpretacjach - czasem pojawiają się w analizie Morfeusza
self.uniq_interps(ret)
#for seg in ret:
# if isinstance(seg, list): #trafiło na 'choice'
# for choice_elem in seg:
# for elem in choice_elem:
# for interp in elem['interps']:
# print('{}:{}:{}:{}'.format(elem['orth'].encode('utf-8'), interp['base'].encode('utf-8'), interp['ctag'].encode('utf-8'), interp['msd'].encode('utf-8')))
# else: # zwykłe interpretacje (nie w liście 'choice')
# for interp in seg['interps']:
# print('{}:{}:{}:{}'.format(seg['orth'].encode('utf-8'), interp['base'].encode('utf-8'), interp['ctag'].encode('utf-8'), interp['msd'].encode('utf-8')))
return ret
def uniq_interps(self, ret):
for seg in ret:
if isinstance(seg, list): #trafiło na 'choice'
for choice_elem in seg:
for elem in choice_elem:
elem['interps'] = list(unique_everseen(elem['interps'], key=lambda e: '{}:{}:{}'.format(e['base'].encode('utf-8'), e['ctag'].encode('utf-8'), e['msd'].encode('utf-8'))))
else: # zwykłe interpretacje (nie w liście 'choice')
seg['interps'] = list(unique_everseen(seg['interps'], key=lambda e: '{}:{}:{}'.format(e['base'].encode('utf-8'), e['ctag'].encode('utf-8'), e['msd'].encode('utf-8'))))
def make_choice(self, by_start, pos, source_text):
try:
by_start[pos]
except:
print('text: {}, pos: {}'.format(source_text.encode('utf-8'), pos))
raise
if len(by_start[pos]) == 1:
ret = by_start[pos][0]
retpos = ret['end']
else:
if len(by_start[pos]) == 0:
raise LogicError("brakujacy segment?")
choices = [{'s' : x["start"], 'e' : x["end"], "content" : [x]} for x in by_start[pos]]
#print([(x['s'], x['e'], [z['orth'] for z in x['content']]) for x in choices])
p = pos
while max([x["e"] for x in choices]) != min([x["e"] for x in choices]):
#musi być min(), bo inaczej nie uwzględnia gałęzi "wstecz" i zaczyna czytać poza ostatnim indeksem
#p += 1
p = min([x["e"] for x in choices])
for c in choices:
if c["e"] > p:
continue
nc, pp = self.make_choice(by_start, p, source_text)
c["content"].append(nc)
c["e"] = pp
#print([(x['s'], x['e'], [z['orth'] for z in x['content']]) for x in choices])
ret = [c["content"] for c in choices]
retpos = choices[0]["e"]
return ret, retpos
def create_interp(self, interp):
ctag, rest_tag = self.split_tags(interp[2])
return {'base':interp[1], 'ctag':ctag, 'msd':rest_tag}
#rozbijanie tagu po ':'
def split_tags(self, morph_tag):
res = morph_tag.split(':', 1)
if len(res) == 1:
res.append('')
return res
def map_orth_and_offset(segs, src_offset, charmap, src_text):
for s in segs:
if isinstance(s, dict):
s["source_offset"] = charmap[s["offset"]][0] + src_offset
s["source_orth"] = src_text[min(charmap[s["offset"]]) : max(charmap[len(s["orth"])+s["offset"]-1])+1]
elif isinstance(s, list):
for c in s:
map_orth_and_offset(c, src_offset, charmap, src_text)
else:
raise LogicError("smiec zamiast segmentu?")
def set_nps(s):
if isinstance(s, dict):
s["nps"] = True
elif isinstance(s, list):
for c in s:
set_nps(c[0])
else:
raise LogicError("smiec zamiast segmentu?")
def get_end(s):
if isinstance(s, dict):
return s["offset"] + len(s["orth"])
elif isinstance(s, list):
return max([get_end(c[-1]) for c in s])
else:
raise LogicError("smiec zamiast segmentu?")
def get_beg(s):
if isinstance(s, dict):
return s["offset"]
elif isinstance(s, list):
return min([get_beg(c[0]) for c in s])
else:
raise LogicError("smiec zamiast segmentu?")
#morfeuszowanie listy akapitow (akapit = lista zdan, zdanie = lista fragmentow)
def morfosegment_paragraphs(parasents, dict_path, dict_name):
a = Analyse(dict_path, dict_name)
for p in parasents:
for s in p:
last_whitespace = True
for frag in s:
#print repr(frag)
if "trans" in frag:
frag["segs"] = a.text_analyse(frag["trans"])
map_orth_and_offset(frag["segs"], frag["xml_offset"]+frag["offset"], frag["charmap"], frag["text"])
if len(frag["segs"]) > 0:
if not last_whitespace:
beg = get_beg(frag["segs"][0])
if beg == 0:
set_nps(frag["segs"][0])
end = get_end(frag["segs"][-1])
if len(frag["trans"]) > end:
last_whitespace = True
else:
last_whitespace = False
if "orig_trans" in frag:
frag["orig_segs"] = a.text_analyse(frag["orig_trans"])
map_orth_and_offset(frag["orig_segs"], frag["xml_offset"]+frag["offset"], frag["orig_charmap"], frag["orig_text"])