File size: 20,815 Bytes
4fb0bd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
from collections import defaultdict


def read_conjunctions(cfg):
    conj2sent = dict()
    file_path = cfg.conjunctions_file

    with open(file_path, 'r') as fin:
        sent = 1
        currentSentText = ''
        for line in fin:
            if line == '\n':
                sent = 1
                continue
            elif sent == 1:
                currentSentText = line.replace('\n', '')
                sent = 0
            else:
                conj_sent = line.replace('\n', '')
                conj2sent[conj_sent] = currentSentText
    conj_sentences = list(conj2sent.keys())
    return conj_sentences, conj2sent


def print_predictions(outputs, file_path, vocab, sequence_label_domain=None):
    """print_predictions prints prediction results
    
    Args:
        outputs (list): prediction outputs
        file_path (str): output file path
        vocab (Vocabulary): vocabulary
        sequence_label_domain (str, optional): sequence label domain. Defaults to None.
    """

    with open(file_path, 'w') as fout:
        for sent_output in outputs:
            seq_len = sent_output['seq_len']
            assert 'tokens' in sent_output
            tokens = [vocab.get_token_from_index(token, 'tokens') for token in sent_output['tokens'][:seq_len]]
            print("Token\t{}".format(' '.join(tokens)), file=fout)

            if 'text' in sent_output:
                print(f"Text\t{sent_output['text']}", file=fout)

            if 'sequence_labels' in sent_output and 'sequence_label_preds' in sent_output:
                sequence_labels = [
                    vocab.get_token_from_index(true_sequence_label, sequence_label_domain)
                    for true_sequence_label in sent_output['sequence_labels'][:seq_len]
                ]
                sequence_label_preds = [
                    vocab.get_token_from_index(pred_sequence_label, sequence_label_domain)
                    for pred_sequence_label in sent_output['sequence_label_preds'][:seq_len]
                ]

                print("Sequence-Label-True\t{}".format(' '.join(sequence_labels)), file=fout)
                print("Sequence-Label-Pred\t{}".format(' '.join(sequence_label_preds)), file=fout)

            if 'joint_label_matrix' in sent_output:
                for row in sent_output['joint_label_matrix'][:seq_len]:
                    print("Joint-Label-True\t{}".format(' '.join(
                        [vocab.get_token_from_index(item, 'ent_rel_id') for item in row[:seq_len]])),
                          file=fout)

            if 'joint_label_preds' in sent_output:
                for row in sent_output['joint_label_preds'][:seq_len]:
                    print("Joint-Label-Pred\t{}".format(' '.join(
                        [vocab.get_token_from_index(item, 'ent_rel_id') for item in row[:seq_len]])),
                          file=fout)

            if 'separate_positions' in sent_output:
                print("Separate-Position-True\t{}".format(' '.join(map(str, sent_output['separate_positions']))),
                      file=fout)

            if 'all_separate_position_preds' in sent_output:
                print("Separate-Position-Pred\t{}".format(' '.join(map(str,
                                                                       sent_output['all_separate_position_preds']))),
                      file=fout)

            if 'span2ent' in sent_output:
                for span, ent in sent_output['span2ent'].items():
                    ent = vocab.get_token_from_index(ent, 'span2ent')
                    assert ent != 'None', "true relation can not be `None`."

                    print("Ent-True\t{}\t{}\t{}".format(ent, span, ' '.join(tokens[span[0]:span[1]])), file=fout)

            if 'all_ent_preds' in sent_output:
                for span, ent in sent_output['all_ent_preds'].items():
                    # ent = vocab.get_token_from_index(ent, 'span2ent')

                    print("Ent-Span-Pred\t{}".format(span), file=fout)
                    print("Ent-Pred\t{}\t{}\t{}".format(ent, span, ' '.join(tokens[span[0]:span[1]])), file=fout)

            if 'span2rel' in sent_output:
                for (span1, span2), rel in sent_output['span2rel'].items():
                    rel = vocab.get_token_from_index(rel, 'span2rel')
                    assert rel != 'None', "true relation can not be `None`."

                    if rel[-1] == '<':
                        span1, span2 = span2, span1
                    print("Rel-True\t{}\t{}\t{}\t{}\t{}".format(rel[:-2], span1, span2,
                                                                ' '.join(tokens[span1[0]:span1[1]]),
                                                                ' '.join(tokens[span2[0]:span2[1]])),
                          file=fout)

            if 'all_rel_preds' in sent_output:
                for (span1, span2), rel in sent_output['all_rel_preds'].items():
                    # rel = vocab.get_token_from_index(rel, 'span2rel')

                    if rel[-1] == '<':
                        span1, span2 = span2, span1
                    print("Rel-Pred\t{}\t{}\t{}\t{}\t{}".format(rel[:-2], span1, span2,
                                                                ' '.join(tokens[span1[0]:span1[1]]),
                                                                ' '.join(tokens[span2[0]:span2[1]])),
                          file=fout)

            print(file=fout)


def print_extractions_allennlp_format(cfg, outputs, file_path, vocab):
    conj_sentences, conj2sent = read_conjunctions(cfg)
    ext_texts = []
    with open(file_path, 'w') as fout:
        for sent_output in outputs:
            extractions = {}
            seq_len = sent_output['seq_len']
            assert 'tokens' in sent_output
            tokens = [vocab.get_token_from_index(token, 'tokens') for token in sent_output['tokens'][:seq_len-6]]
            sentence = ' '.join(tokens)
            if sentence in conj_sentences:
                sentence = conj2sent[sentence]

            if 'all_rel_preds' in sent_output:
                for (span1, span2), rel in sent_output['all_rel_preds'].items():
                    if rel == '' or rel == ' ':
                        continue
                    if sent_output['all_ent_preds'][span1] == 'Relation':
                        try:
                            if span2 in extractions[span1][rel]:
                                continue
                        except:
                            pass
                        try:
                            extractions[span1][rel].append(span2)
                        except:
                            extractions[span1] = defaultdict(list)
                            extractions[span1][rel].append(span2)
                    else:
                        try:
                            if span1 in extractions[span2][rel]:
                                continue
                        except:
                            pass
                        try:
                            extractions[span2][rel].append(span1)
                        except:
                            extractions[span2] = defaultdict(list)
                            extractions[span2][rel].append(span1)
            to_remove_rel_spans = set()
            expand_rel = {}
            to_add = {}
            for rel_span1, d1 in extractions.items():
                for rel_span2, d2 in extractions.items():
                    if rel_span1 != rel_span2 and not (rel_span1 in to_remove_rel_spans or rel_span2 in to_remove_rel_spans):
                        if d1["Subject"] == d2["Subject"] and d1["Object"] == d2["Object"]:
                            if rel_span1 in to_remove_rel_spans:
                                to_add[expand_rel[rel_span1] + rel_span2] = d1
                                to_remove_rel_spans.add(rel_span2)
                                to_remove_rel_spans.add(expand_rel[rel_span1])
                                expand_rel[rel_span2] = expand_rel[rel_span1] + rel_span2
                                expand_rel[rel_span1] = expand_rel[rel_span1] + rel_span2
                            elif rel_span2 in to_remove_rel_spans:
                                to_add[expand_rel[rel_span2] + rel_span1] = d1
                                to_remove_rel_spans.add(rel_span1)
                                to_remove_rel_spans.add(expand_rel[rel_span2])
                                expand_rel[rel_span1] = expand_rel[rel_span2] + rel_span1
                                expand_rel[rel_span2] = expand_rel[rel_span2] + rel_span1
                            else:
                                to_add[rel_span1 + rel_span2] = d1
                                expand_rel[rel_span1] = rel_span1 + rel_span2
                                expand_rel[rel_span2] = rel_span1 + rel_span2
                                to_remove_rel_spans.add(rel_span1)
                                to_remove_rel_spans.add(rel_span2)
            for tm in to_remove_rel_spans:
                del extractions[tm]
            for k, v in to_add.items():
                extractions[k] = v
            for rel_sp, d in extractions.items():
                if len(d["Subject"]) > 1:
                    sorted_d_subject = sorted(d["Subject"], key=lambda x: x[0][0])
                    sorted_d_subject = [x[0] for x in sorted_d_subject]
                    subject_text = " ".join([" ".join(tokens[sub_span[0]:sub_span[1]]) for sub_span in sorted_d_subject])
                elif len(d["Subject"]) == 1:
                    subject_text = " ".join([" ".join(tokens[sub_span[0]:sub_span[1]]) for sub_span in d["Subject"][0]])
                else:
                    subject_text = ""
                if len(d["Object"]) > 1:
                    sorted_d_object = sorted(d["Object"], key=lambda x: x[0][0])
                    sorted_d_object = [x[0] for x in sorted_d_object]
                    object_text = " ".join([" ".join(tokens[sub_span[0]:sub_span[1]]) for sub_span in sorted_d_object])
                elif len(d["Object"]) == 1:
                    object_text = " ".join([" ".join(tokens[sub_span[0]:sub_span[1]]) for sub_span in d["Object"][0]])
                else:
                    object_text = ""
                rel_text = " ".join([" ".join(tokens[sub_span[0]:sub_span[1]]) for sub_span in rel_sp]).replace('[unused1]', 'is')
                ext = f'<arg1> {subject_text} </arg1> <rel> {rel_text} </rel> <arg2> {object_text} </arg2>'
                if ext not in ext_texts and (rel_text != '' and subject_text != ''):
                    print("{}\t{}".format(sentence, ext), file=fout)
                ext_texts.append(ext)


def print_predictions_for_joint_decoding(outputs, file_path, vocab):
    """print_predictions prints prediction results
    
    Args:
        outputs (list): prediction outputs
        file_path (str): output file path
        vocab (Vocabulary): vocabulary
        sequence_label_domain (str, optional): sequence label domain. Defaults to None.
    """

    with open(file_path, 'w') as fout:
        for sent_output in outputs:
            seq_len = sent_output['seq_len']
            assert 'tokens' in sent_output
            tokens = [vocab.get_token_from_index(token, 'tokens') for token in sent_output['tokens'][:seq_len]]
            print("Token\t{}".format(' '.join(tokens)), file=fout)

            if 'joint_label_matrix' in sent_output:
                for row in sent_output['joint_label_matrix'][:seq_len]:
                    print("Joint-Label-True\t{}".format(' '.join(
                        [vocab.get_token_from_index(item, 'ent_rel_id') for item in row[:seq_len]])),
                          file=fout)

            if 'joint_label_preds' in sent_output:
                for row in sent_output['joint_label_preds'][:seq_len]:
                    print("Joint-Label-Pred\t{}".format(' '.join(
                        [vocab.get_token_from_index(item, 'ent_rel_id') for item in row[:seq_len]])),
                          file=fout)

            if 'separate_positions' in sent_output:
                print("Separate-Position-True\t{}".format(' '.join(map(str, sent_output['separate_positions']))),
                      file=fout)

            if 'all_separate_position_preds' in sent_output:
                print("Separate-Position-Pred\t{}".format(' '.join(map(str,
                                                                       sent_output['all_separate_position_preds']))),
                      file=fout)

            if 'all_ent_span_preds' in sent_output:
                for span in sent_output['all_ent_span_preds']:
                    print("Ent-Span-Pred\t{}".format(span), file=fout)

            if 'span2ent' in sent_output:
                for span, ent in sent_output['span2ent'].items():
                    ent = vocab.get_token_from_index(ent, 'ent_rel_id')
                    assert ent != 'None', "true relation can not be `None`."

                    print("Ent-True\t{}\t{}\t{}".format(ent, span, ' '.join([' '.join(tokens[sub_span[0]:sub_span[1]]) for sub_span in span])), file=fout)

            if 'all_ent_preds' in sent_output:
                for span, ent in sent_output['all_ent_preds'].items():
                    # ent = vocab.get_token_from_index(ent, 'span2ent')
                    print("Ent-Pred\t{}\t{}\t{}".format(ent, span, ' '.join(
                        [' '.join(tokens[sub_span[0]:sub_span[1]]) for sub_span in span])), file=fout)

            if 'span2rel' in sent_output:
                for (span1, span2), rel in sent_output['span2rel'].items():
                    rel = vocab.get_token_from_index(rel, 'ent_rel_id')
                    assert rel != 'None', "true relation can not be `None`."
                    span1_text_list = [' '.join(tokens[sub_span[0]:sub_span[1]]) for sub_span in span1]
                    span2_text_list = [' '.join(tokens[sub_span[0]:sub_span[1]]) for sub_span in span2]
                    print("Rel-True\t{}\t{}\t{}\t{}\t{}".format(rel, span1, span2, ' '.join(span1_text_list),
                                                                ' '.join(span2_text_list)),
                          file=fout)

            if 'all_rel_preds' in sent_output:
                for (span1, span2), rel in sent_output['all_rel_preds'].items():
                    # rel = vocab.get_token_from_index(rel, 'span2rel')

                    span1_text_list = [' '.join(tokens[sub_span[0]:sub_span[1]]) for sub_span in span1]
                    span2_text_list = [' '.join(tokens[sub_span[0]:sub_span[1]]) for sub_span in span2]
                    print("Rel-Pred\t{}\t{}\t{}\t{}\t{}".format(rel, span1, span2, ' '.join(span1_text_list),
                                                                ' '.join(span2_text_list)),
                          file=fout)

                    # print("Rel-Pred\t{}\t{}\t{}\t{}\t{}".format(rel, span1, span2, ' '.join(tokens[span1[0]:span1[1]]),
                    #                                             ' '.join(tokens[span2[0]:span2[1]])),
                    #       file=fout)

            print(file=fout)


def print_predictions_for_entity_rel_decoding(outputs, file_path, vocab):
    """print_predictions prints prediction results

    Args:
        outputs (list): prediction outputs
        file_path (str): output file path
        vocab (Vocabulary): vocabulary
        sequence_label_domain (str, optional): sequence label domain. Defaults to None.
    """

    with open(file_path, 'w') as fout:
        # for sent_output, rel_sent_output in zip(outputs, rel_outputs):
        for sent_output in outputs:
            seq_len = sent_output['seq_len']
            assert 'tokens' in sent_output
            tokens = [vocab.get_token_from_index(token, 'tokens') for token in sent_output['tokens'][:seq_len]]
            print("Token\t{}".format(' '.join(tokens)), file=fout)

            if 'entity_label_preds' in sent_output:
                for row in sent_output['entity_label_preds'][:seq_len]:
                    print("Ent-Label-Pred\t{}".format(' '.join(
                        [vocab.get_token_from_index(item, 'ent_rel_id') for item in row[:seq_len]])),
                        file=fout)

            if 'relation_label_matrix' in sent_output:
                for row in sent_output['relation_label_matrix'][:seq_len]:
                    print("Rel-Label-True\t{}".format(' '.join(
                        [vocab.get_token_from_index(item + 2, 'ent_rel_id') if item != 0 else "None" for item in row[:seq_len]])),
                        file=fout)

            if 'relation_label_preds' in sent_output:
                for row in sent_output['relation_label_preds'][:seq_len]:
                    print("Rel-Label-Pred\t{}".format(' '.join(
                        [vocab.get_token_from_index(item + 2, 'ent_rel_id') if item != 0 else "None" for item in row[:seq_len]])),
                        file=fout)

            if 'separate_positions' in sent_output:
                print("Separate-Position-True\t{}".format(' '.join(map(str, sent_output['separate_positions']))),
                      file=fout)

            if 'all_separate_position_preds' in sent_output:
                print("Separate-Position-Pred\t{}".format(' '.join(map(str,
                                                                       sent_output['all_separate_position_preds']))),
                      file=fout)

            if 'all_ent_span_preds' in sent_output:
                for span in sent_output['all_ent_span_preds']:
                    print("Ent-Span-Pred\t{}".format(span), file=fout)

            if 'span2ent' in sent_output:
                for span, ent in sent_output['span2ent'].items():
                    ent = vocab.get_token_from_index(ent, 'ent_rel_id')
                    assert ent != 'None', "true relation can not be `None`."

                    print("Ent-True\t{}\t{}\t{}".format(ent, span, ' '.join(
                        [' '.join(tokens[sub_span[0]:sub_span[1]]) for sub_span in span])), file=fout)

            if 'all_ent_preds' in sent_output:
                for span, ent in sent_output['all_ent_preds'].items():
                    print("Ent-Pred\t{}\t{}\t{}".format(ent, span, ' '.join(
                        [' '.join(tokens[sub_span[0]:sub_span[1]]) for sub_span in span])), file=fout)

            if 'span2rel' in sent_output:
                for (span1, span2), rel in sent_output['span2rel'].items():
                    rel = vocab.get_token_from_index(rel, 'ent_rel_id')
                    assert rel != 'None', "true relation can not be `None`."

                    span1_text_list = [' '.join(tokens[sub_span[0]:sub_span[1]]) for sub_span in span1]
                    span2_text_list = [' '.join(tokens[sub_span[0]:sub_span[1]]) for sub_span in span2]
                    print("Rel-True\t{}\t{}\t{}\t{}\t{}".format(rel, span1, span2, ' '.join(span1_text_list),
                                                                ' '.join(span2_text_list)),
                          file=fout)
            if 'all_rel_preds' in sent_output:
                for (span1, span2), rel in sent_output['all_rel_preds'].items():

                    span1_text_list = [' '.join(tokens[sub_span[0]:sub_span[1]]) for sub_span in span1]
                    span2_text_list = [' '.join(tokens[sub_span[0]:sub_span[1]]) for sub_span in span2]
                    print("Rel-Pred\t{}\t{}\t{}\t{}\t{}".format(rel, span1, span2, ' '.join(span1_text_list),
                                                                ' '.join(span2_text_list)), file=fout)

            print(file=fout)

def print_predictions_for_relation_decoding(outputs, file_path, vocab):
    with open(file_path, 'w') as fout:
        for sent_output in outputs:
            seq_len = sent_output['seq_len']
            assert 'tokens' in sent_output
            tokens = [vocab.get_token_from_index(token, 'tokens') for token in sent_output['tokens'][:seq_len]]
            print("Token\t{}".format(' '.join(tokens)), file=fout)
            if 'relation_label_matrix' in sent_output:
                for row in sent_output['relation_label_matrix'][:seq_len]:
                    print("Relation-Label-True\t{}".format(' '.join(
                        [vocab.get_token_from_index(item, 'ent_rel_id') for item in row[:seq_len]])),
                        file=fout)

            if 'relation_label_preds' in sent_output:
                for row in sent_output['relation_label_preds'][:seq_len]:
                    print("Relation-Label-Pred\t{}".format(' '.join(
                        [vocab.get_token_from_index(item, 'ent_rel_id') for item in row[:seq_len]])),
                        file=fout)