-
Notifications
You must be signed in to change notification settings - Fork 3
/
uie_convert.py
229 lines (204 loc) · 8.14 KB
/
uie_convert.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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from collections import Counter
import os
import json
from typing import Dict, List
from tqdm import tqdm
from universal_ie.generation_format.generation_format import GenerationFormat
from universal_ie.generation_format import generation_format_dict
from universal_ie.generation_format.structure_marker import BaseStructureMarker
from universal_ie.dataset import Dataset
from universal_ie.ie_format import Sentence
import argparse
def convert_graph(
generation_class: GenerationFormat,
output_folder: str,
datasets: Dict[str, List[Sentence]],
language: str = "en",
label_mapper: Dict = None,
):
convertor = generation_class(
structure_maker=BaseStructureMarker(),
language=language,
label_mapper=label_mapper,
)
counter = Counter()
os.makedirs(output_folder, exist_ok=True)
schema_counter = {
"entity": list(),
"relation": list(),
"event": list(),
}
for data_type, instance_list in datasets.items():
with open(os.path.join(output_folder, f"{data_type}.json"), "w") as output:
for instance in tqdm(instance_list):
counter.update([f"{data_type} sent"])
converted_graph = convertor.annonote_graph(
tokens=instance.tokens,
entities=instance.entities,
relations=instance.relations,
events=instance.events,
)
src, tgt, spot_labels, asoc_labels = converted_graph[:4]
spot_asoc = converted_graph[4]
schema_counter["entity"] += instance.entities
schema_counter["relation"] += instance.relations
schema_counter["event"] += instance.events
output.write(
"%s\n"
% json.dumps(
{
"text": src,
"tokens": instance.tokens,
"record": tgt,
"entity": [
entity.to_offset(label_mapper)
for entity in instance.entities
],
"relation": [
relation.to_offset(
ent_label_mapper=label_mapper,
rel_label_mapper=label_mapper,
)
for relation in instance.relations
],
"event": [
event.to_offset(evt_label_mapper=label_mapper)
for event in instance.events
],
"spot": list(spot_labels),
"asoc": list(asoc_labels),
"spot_asoc": spot_asoc,
},
ensure_ascii=False,
)
)
convertor.output_schema(os.path.join(output_folder, "record.schema"))
convertor.get_entity_schema(schema_counter["entity"]).write_to_file(
os.path.join(output_folder, f"entity.schema")
)
convertor.get_relation_schema(schema_counter["relation"]).write_to_file(
os.path.join(output_folder, f"relation.schema")
)
convertor.get_event_schema(schema_counter["event"]).write_to_file(
os.path.join(output_folder, f"event.schema")
)
print(counter)
print(output_folder)
print("==========================")
def convert_to_oneie(output_folder: str, datasets: Dict[str, List[Sentence]]):
os.makedirs(output_folder, exist_ok=True)
counter = Counter()
for data_type, instance_list in datasets.items():
with open(
os.path.join(output_folder, f"{data_type}.oneie.json"), "w"
) as output:
for instance in tqdm(instance_list):
counter.update([f"{data_type} sent"])
entity_mentions = [
{
"id": entity.record_id,
"entity_type": str(entity.label),
"text": entity.span.text,
"start": entity.span.indexes[0],
"end": entity.span.indexes[-1] + 1,
}
for entity in instance.entities
]
relation_mentions = [
{
"id": relation.record_id,
"relation_type": str(relation.label),
"argument": [
{
"entity_id": relation.arg1.record_id,
"text": relation.arg1.span.text,
"role": "Arg-1",
},
{
"entity_id": relation.arg2.record_id,
"text": relation.arg2.span.text,
"role": "Arg-2",
},
],
}
for relation in instance.relations
]
event_mentions = [
{
"id": event.record_id,
"event_type": str(event.label),
"trigger": {
"text": event.span.text,
"start": event.span.indexes[0],
"end": event.span.indexes[-1] + 1,
},
"argument": [
{
"id": arg[1].record_id,
"text": arg[1].span.text,
"role": str(arg[0]),
}
for arg in event.args
],
}
for event in instance.events
]
instance_dict = {
"tokens": instance.tokens,
"sent_id": instance.text_id,
"entity_mentions": entity_mentions,
"relation_mentions": relation_mentions,
"event_mentions": event_mentions,
}
instance_str = json.dumps(instance_dict, ensure_ascii=False)
output.write(f"{instance_str}\n")
print(counter)
print(output_folder)
print("==========================")
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"-format",
dest="generation_format",
default="spotasoc",
help="The UIE generation format defines how the converter assumes the data to be. It should remain on 'spotasoc' for temporal extraction."
)
parser.add_argument(
"-config",
dest="config",
default="data_config/entity",
help="Path of the directory that contains all the configuration files."
)
parser.add_argument(
"-output",
dest="output",
default="../../entity/my_converted_datasets/uie",
help="The path to the output base directory."
)
options = parser.parse_args()
generation_class = generation_format_dict.get(options.generation_format)
if os.path.isfile(options.config):
config_list = [options.config]
else:
config_list = [
os.path.join(options.config, x) for x in os.listdir(options.config)
]
for filename in config_list:
dataset = Dataset.load_yaml_file(filename)
datasets = dataset.load_dataset()
label_mapper = dataset.mapper
output_name = os.path.join(options.output, dataset.name)
if generation_class:
convert_graph(
generation_class,
output_name,
datasets=datasets,
language=dataset.language,
label_mapper=label_mapper,
)
elif options.generation_format == "oneie":
convert_to_oneie(output_name, datasets=datasets)
if __name__ == "__main__":
main()