morfosegment.py
7.05 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
# -*- coding: utf-8 -*-
import morfeusz2
import itertools
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)
#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_interps(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"].extend(self.create_interps(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"])
print(source_text)
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
while pos <= maxpos:
c, pos = self.make_choice(by_start, pos)
ret.append(c)
return ret
def make_choice(self, by_start, pos):
if len(by_start[pos]) == 1:
ret = by_start[pos][0]
retpos = pos+1
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]]
p = pos
while max([x["e"] for x in choices]) != min([x["e"] for x in choices]):
p += 1
for c in choices:
if c["e"] > p:
continue
nc, pp = self.make_choice(by_start, p)
c["content"].append(nc)
c["e"] = pp
ret = [c["content"] for c in choices]
retpos = choices[0]["e"]
return ret, retpos
def create_interps(self, interp):
ret = []
ctag, rest_tag = self.split_tags(interp[2])
rest_tag_list = self.separate_dot_interp(rest_tag) #rozbicie kropek
for rest in rest_tag_list:
ret.append({'base':interp[1], 'ctag':ctag, 'msd':rest})
return ret
#rozbijanie tagu po ':'
def split_tags(self, morph_tag):
res = morph_tag.split(':', 1)
if len(res) == 1:
res.append('')
return res
#funkcja rodzielająca interpretacje z kropkami
#zwraca listę stringów
def separate_dot_interp(self, interp):
if not ('.' in interp):
return [interp]
else:
result = []
col_split = interp.split(':')
for elem in col_split:
ends = elem.split('.')
if result == []:
result = ends
continue
new_res = map(lambda x: self.glue_ends(x, ends), result)
result = list(itertools.chain.from_iterable(new_res))
return result
#funkcja doczepiająca do stringa start końcówki z listy ends
#zwraca listę stringów
def glue_ends(self, start, ends):
return map(lambda x: ':'.join([start, x]), ends)
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):
sgjp_dict = "/home/bartek/doki/ipi/morfeusz/input/" #ścieżka do słownika dla Morfeusza
a = Analyse(sgjp_dict, 'morfeusz-sgjp')
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"])