-
Notifications
You must be signed in to change notification settings - Fork 19
/
amrdata.py
215 lines (198 loc) · 9.05 KB
/
amrdata.py
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
#!/usr/bin/env python
#coding=utf-8
'''
AMRDataset reads the file generated by preprocessing.sh and it generates a AMRSentence instance for each sentence,
containing all information necessary to the parser.
@author: Marco Damonte (m.damonte@sms.ed.ac.uk)
@since: 3-10-16
'''
import re
from alignments import Alignments as Alignments
import sys
import amrevaluation.smatch.amr_edited as amrannot
sys.path.append("..")
reload(sys)
sys.setdefaultencoding('utf8')
class AMRSentence:
def __init__(self, tokens, pos, lemmas, nes, dependencies, variables = None, relations = None, graph = None, alignments = None):
self.tokens = tokens
self.pos = pos
self.lemmas = lemmas
self.nes = nes
self.dependencies = dependencies
if variables is not None:
self.variables = [(str(k),str(variables[k])) for k in variables]
if relations is not None:
self.relations = [r for r in relations if r[0] != r[2]]
self.graph = graph
self.alignments = alignments
class AMRDataset:
def _var2concept(self, amr):
v2c = {}
for n, v in zip(amr.nodes, amr.node_values):
v2c[n] = v
return v2c
def __init__(self, prefix, amrs, normalize = True):
self.normalize = normalize
self.sentences = []
alltokens, allpos, alllemmas, allnes, alldepslines = self._loadFromFile(prefix + ".out")
if amrs:
allgraphs = open(prefix + ".graphs").read().split("\n\n")
a = Alignments(prefix + ".alignments", allgraphs)
allalignments = a.alignments
for graph, alignments, depslines, tokens, pos, lemmas, nes in zip(allgraphs, allalignments, alldepslines, alltokens, allpos, alllemmas, allnes):
graph = graph.strip()
amr = amrannot.AMR.parse_AMR_line(graph.replace("\n",""), False)
variables = {}
for n, v in zip(amr.nodes, amr.node_values):
variables[n] = v
role_triples = amr.get_triples3()
relations = []
for (var1,label,var2) in role_triples:
if label == "TOP":
relations.append(("TOP",":top",var1))
else:
relations.append((str(var1),":" + str(label),str(var2)))
dependencies = []
for line in depslines.split("\n"):
pattern = "^(.+)\(.+-([0-9]+), .+-([0-9]+)\)"
regex = re.match(pattern, line)
if regex is not None:
label = regex.group(1)
a = int(regex.group(2)) - 1
b = int(regex.group(3)) - 1
if a == -1:
dependencies.append((b, 'ROOT', b))
elif a != b:
dependencies.append((a, label, b))
self.sentences.append(AMRSentence(tokens, pos, lemmas, nes, dependencies, variables, relations, graph, alignments))
else:
for depslines, tokens, pos, lemmas, nes in zip(alldepslines, alltokens, allpos, alllemmas, allnes):
dependencies = []
for line in depslines.split("\n"):
pattern = "^(.+)\(.+-([0-9]+), .+-([0-9]+)\)"
regex = re.match(pattern, line)
if regex is not None:
label = regex.group(1)
a = int(regex.group(2)) - 1
b = int(regex.group(3)) - 1
if a == -1:
dependencies.append((b, 'ROOT', b))
elif a != b:
dependencies.append((a, label, b))
self.sentences.append(AMRSentence(tokens, pos, lemmas, nes, dependencies))
def getSent(self, index):
return self.sentences[index]
def getAllSents(self):
return self.sentences
def _loadFromFile(self, stanfordOutput):
alltokens = []
allpos = []
alllemmas = []
allnes = []
alldepslines = []
blocks = open(stanfordOutput, 'r').read().split("\n\n")
while True:
if len(blocks) == 1:
break
block = blocks.pop(0).strip().split("\n")
tokens = []
lemmas = []
nes = []
pos = []
i = 2
while block[i].startswith("[Text"):
tokens.extend([t[5:-1] for t in re.findall('Text=[^\s]* ', block[i])])
pos.extend([t[13:-1] for t in re.findall('PartOfSpeech=[^\s]* ', block[i])])
lemmas.extend([t[6:-1] for t in re.findall('Lemma=[^\s]* ', block[i])])
nes.extend([t[15:] for t in re.findall('NamedEntityTag=[^\]]*', block[i])])
i += 1
allpos.append(pos)
if blocks[0].startswith("\n"):
b = ""
else:
b = blocks.pop(0)
depslines = b
#very messy piece of code to handle corenlp normalization (for dates, currencies, etc)
tokens2 = []
lemmas2 = []
nes2 = []
lastnorm = None
for token, lemma, ne in zip(tokens, lemmas, nes):
nesplit = ne.split()
if len(nesplit) > 1:
mne = re.match("^([a-zA-Z\%\>\<\$\~\=]*)([0-9\.]*.*)", nesplit[1][25:].encode('ascii', 'ignore'))
else:
mne = None
if nesplit[0] == "DATE" and re.match("^(\d{4}|XXXX)(-\d{2})?(-\d{2})?$",nesplit[1][25:]) is not None:
norm = nesplit[1][25:]
lastnorm = norm
tokens2.append(norm)
lemmas2.append(norm)
nes2.append(nesplit[0])
elif (nesplit[0] == "MONEY" or nesplit[0] == "PERCENT") and self.normalize and len(nesplit) == 2 and mne is not None:
[name, norm] = nesplit
curr = mne.groups()[0]
norm = mne.groups()[1]
curr = curr.replace("<","").replace(">","").replace("~","").replace("=","")
if curr == "$":
curr = "dollar"
if curr == "":
w = nesplit[1][25:].replace("<","").replace(">","").replace("~","").replace("=","")
if w.startswith(u"\u00A5"):
curr = "yen"
elif w.startswith(u"\u5143"):
curr = "yuan"
elif w.startswith(u"\u00A3"):
curr = "pound"
elif w.startswith(u"\u20AC"):
curr = "euro"
else:
curr = "NULL"
m = re.match("([0-9\.][0-9\.]*)E([0-9][0-9]*)$",norm)
if m is not None:
n = m.groups()[0]
z = "".join(["0"]*int(m.groups()[1]))
norm = format(float(n)*float("1"+z), ".32f")
norm = re.sub("\.00*$","",norm)
if token.endswith(".0") == False:
norm = re.sub("\.0$","",norm)
if token.replace(",","").replace(".","").isdigit() == False and lastnorm is not None:
norm = ","
token = ","
name = "O"
lastnorm = norm
if norm == ",":
tokens2.append(norm)
else:
tokens2.append(norm + "_" + curr)
lemmas2.append(token)
nes2.append(name)
elif self.normalize and len(nesplit) == 2 and re.match("^[0-9].*", nesplit[1][25:]) is not None: #numbers
[name, norm] = nesplit
norm = norm[25:]
m = re.match("([0-9\.][0-9\.]*)E([0-9][0-9]*)$",norm)
if m is not None:
n = m.groups()[0]
z = "".join(["0"]*int(m.groups()[1]))
norm = str(float(n)*int("1"+z))
if token.endswith(".0") == False:
norm = re.sub("\.0$","",norm)
if token.replace(",","").replace(".","").isdigit() == False and lastnorm is not None:
norm = ","
token = ","
name = "O"
lastnorm = norm
tokens2.append(norm)
lemmas2.append(token)
nes2.append(name)
else:
lastnorm = None
tokens2.append(token)
lemmas2.append(lemma)
nes2.append(nesplit[0])
alltokens.append(tokens2)
alllemmas.append(lemmas2)
allnes.append(nes2)
alldepslines.append(depslines)
return (alltokens, allpos, alllemmas, allnes, alldepslines)