-
Notifications
You must be signed in to change notification settings - Fork 1
/
Answer.py
196 lines (183 loc) · 8.97 KB
/
Answer.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
import pandas as pd
import nltk
import re
import utils
import hnswlib
auxillary_verbs=['can','could','may','might','must','shall','should','will','would'] #https://englishstudyonline.org/auxiliary-verbs/
distance_threshold=0.5
class Answer:
def __init__(self, answer):
self.content = answer
self.phrase_corpus=[]
self.phrase_index=None
self.triplet=[]
self.triplet_id=[]
self.parsed=[]
def change_comma(self):
"""
Replace improper period to comma
"""
self.content = re.sub("\.(?=\s[a-z0-9]|\sI[\W\s])", ",", self.content)
def create_triplet(self):
"""
Generate (subject, verb, object) triplets of a speech text
Param:
========
coref_extractor: allennlp coreferece resolution predictor
oi_extractor: allennlp open information extractor
Return:
========
triplets: list, a list of triplet tuples except the last item being party string
"""
oie_result=self.create_oieresult()
triplets = self._find_triplets(oie_result)
triplets.append(self.party)
return triplets
def create_coref(self):
return utils.coref_extractor.coref_resolved(self.content)
def create_oieresult(self):
coref_content=self.content
sents = nltk.tokenize.sent_tokenize(coref_content)
sents = [{"sentence":s} for s in sents] #Format for oie batch predictor
oie_result = utils.open_info_extractor.predict_batch_json(sents)
oie_result = [i['verbs'] for i in oie_result]
return oie_result
def add_phrase(self, phrase):
Id=len(self.phrase_corpus)
self.phrase_corpus.append(phrase)
self.phrase_index = hnswlib.Index('cosine', 512)
self.phrase_index.init_index(len(self.phrase_corpus), ef_construction=200, M=48, random_seed=36)
if len(self.phrase_corpus) > 1:
self.phrase_index.load_index("phrase_index", max_elements=len(self.phrase_corpus))
self.phrase_index.add_items(utils.model([phrase]))
self.phrase_index.save_index("phrase_index")
return Id, phrase
def deduplicate(self,phrase):
if len(self.phrase_corpus)==0:
return self.add_phrase(phrase)
nearest_neighbor=self.phrase_index.knn_query(utils.model([phrase]))
if nearest_neighbor != []:
closest_neighbor, closest_distance = nearest_neighbor
if closest_neighbor[0] == []:
return self.add_phrase(phrase)
if closest_distance[0][0] > distance_threshold:
return self.add_phrase(phrase)
return_phrase=self.phrase_corpus[closest_neighbor[0][0]]
return self.phrase_corpus.index(return_phrase),return_phrase
def create_training(self,verb_dict, verb_list):
self.change_comma()
triplets = self.create_oieresult()
return_text=""
for sentence in triplets:
if len(sentence)==0:
self.parsed.append('str(len(self.phrase_corpus))+" -1"')
continue
text=re.sub('\[[^\s]*','',sentence[0]['description'])
text=re.sub('\]','',text).split()
tags=[False]*len(sentence[0]['tags'])
for triplet in sentence:
arg_points=[x in ['I-ARG0','B-ARG0','I-ARG1','B-ARG1'] for x in triplet['tags']]
abort=False
for others in sentence:
for place in range(len(others['tags'])):
if others['tags'][place][-2:]=='-V' and arg_points[place]:
abort=True
break
if abort:
break
if abort:
continue
subject=' '.join([text[x] for x in range(len(text)) if triplet['tags'][x] in ['I-ARG0','B-ARG0']])
objekt=' '.join([text[x] for x in range(len(text)) if triplet['tags'][x] in ['I-ARG1','B-ARG1']])
verb=triplet['verb']
verb=utils.lemmatize(triplet['verb'])
if verb in auxillary_verbs:
continue
if len(subject)==0:
continue
if len(objekt)==0:
continue
if verb in verb_dict.keys():
verb_id=verb_dict[verb]
else:
verb_id=len(verb_list)
verb_list.append(verb)
verb_dict[verb]=verb_id
max_id=len(self.phrase_corpus)
subject_id,subject=self.deduplicate(subject)
if subject_id==max_id:
self.parsed.append(str(subject_id))
tags=[str(subject_id) if triplet['tags'][x] in ['I-ARG0','B-ARG0'] else tags[x] for x in range(len(text))]
max_id=len(self.phrase_corpus)
objekt_id,objekt=self.deduplicate(objekt)
if objekt_id==max_id:
self.parsed.append(str(objekt_id))
tags=[str(objekt_id) if triplet['tags'][x] in ['I-ARG1','B-ARG1'] else tags[x] for x in range(len(text))]
if (subject,objekt,verb) not in self.triplet:
self.triplet.append((subject,objekt,verb))
self.triplet_id.append((subject_id,verb_id,objekt_id))
self.parsed.append("str(len(self.phrase_corpus)+"+str(len(self.triplet))+")")
self.parsed.append('str(len(self.phrase_corpus))+" -1"')
text=['<phrase_'+str(tags[x])+'>' if tags[x] else text[x] for x in range(len(text))]
text.append(None)
text=[text[x] for x in range(len(text)-1) if (text[x]!=text[x+1] or text[x][0]!='<')]
return_text=return_text+' '+' '.join(text)
return self.phrase_corpus,self.triplet_id,return_text[1:],[eval(x, {"self": self}) for x in self.parsed]
def create_test(self,verb_dict, verb_list):
self.change_comma()
triplets = self.create_oieresult()
return_text=""
for sentence in triplets:
if len(sentence)==0:
self.parsed.append('str(len(self.phrase_corpus))+" -1"')
continue
text=re.sub('\[[^\s]*','',sentence[0]['description'])
text=re.sub('\]','',text).split()
tags=[False]*len(sentence[0]['tags'])
for triplet in sentence:
arg_points=[x in ['I-ARG0','B-ARG0','I-ARG1','B-ARG1'] for x in triplet['tags']]
abort=False
for others in sentence:
for place in range(len(others['tags'])):
if others['tags'][place][-2:]=='-V' and arg_points[place]:
abort=True
break
if abort:
break
if abort:
continue
subject=' '.join([text[x] for x in range(len(text)) if triplet['tags'][x] in ['I-ARG0','B-ARG0']])
objekt=' '.join([text[x] for x in range(len(text)) if triplet['tags'][x] in ['I-ARG1','B-ARG1']])
verb=triplet['verb']
verb=utils.lemmatize(triplet['verb'])
if verb in auxillary_verbs:
continue
if len(subject)==0:
continue
if len(objekt)==0:
continue
verb = verb.upper()
if verb not in verb_dict.keys():
print(verb)
continue #if verb does not exist in verb_dict it can not be used to create
verb_id=verb_dict[verb]
max_id=len(self.phrase_corpus)
subject_id,subject=self.deduplicate(subject)
if subject_id==max_id:
self.parsed.append(str(subject_id))
tags=[str(subject_id) if triplet['tags'][x] in ['I-ARG0','B-ARG0'] else tags[x] for x in range(len(text))]
max_id=len(self.phrase_corpus)
objekt_id,objekt=self.deduplicate(objekt)
if objekt_id==max_id:
self.parsed.append(str(objekt_id))
tags=[str(objekt_id) if triplet['tags'][x] in ['I-ARG1','B-ARG1'] else tags[x] for x in range(len(text))]
if (subject,objekt,verb) not in self.triplet:
self.triplet.append((subject,objekt,verb))
self.triplet_id.append((subject_id,verb_id,objekt_id))
self.parsed.append("str(len(self.phrase_corpus)+"+str(len(self.triplet))+")")
self.parsed.append('str(len(self.phrase_corpus))+" -1"')
text=['<phrase_'+str(tags[x])+'>' if tags[x] else text[x] for x in range(len(text))]
text.append(None)
text=[text[x] for x in range(len(text)-1) if (text[x]!=text[x+1] or text[x][0]!='<')]
return_text=return_text+' '+' '.join(text)
return self.phrase_corpus,self.triplet_id,return_text[1:],[eval(x, {"self": self}) for x in self.parsed]