ArneBinder commited on
Commit
a89bdbd
1 Parent(s): a29caf7

Create argmicro.py

Browse files
Files changed (1) hide show
  1. argmicro.py +233 -0
argmicro.py ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dataclasses
2
+ from collections import defaultdict
3
+ from typing import Any, Callable, Dict, List, Optional, Tuple
4
+
5
+ import datasets
6
+ import pytorch_ie.data.builder
7
+ from pytorch_ie.annotations import Span
8
+ from pytorch_ie.core import Annotation, AnnotationList, annotation_field
9
+ from pytorch_ie.documents import TextBasedDocument
10
+
11
+ from src import utils
12
+
13
+ log = utils.get_pylogger(__name__)
14
+
15
+
16
+ def dl2ld(dict_of_lists):
17
+ return [dict(zip(dict_of_lists, t)) for t in zip(*dict_of_lists.values())]
18
+
19
+
20
+ def ld2dl(list_of_dicts, keys: Optional[List[str]] = None, as_list: bool = False):
21
+ if keys is None:
22
+ keys = list_of_dicts[0].keys()
23
+ if as_list:
24
+ return [[d[k] for d in list_of_dicts] for k in keys]
25
+ else:
26
+ return {k: [d[k] for d in list_of_dicts] for k in keys}
27
+
28
+
29
+ @dataclasses.dataclass(frozen=True)
30
+ class LabeledAnnotationCollection(Annotation):
31
+ annotations: Tuple[Annotation, ...]
32
+ label: str
33
+
34
+
35
+ @dataclasses.dataclass(frozen=True)
36
+ class MultiRelation(Annotation):
37
+ heads: Tuple[Annotation, ...] # sources == heads
38
+ tails: Tuple[Annotation, ...] # targets == tails
39
+ label: str
40
+
41
+
42
+ @dataclasses.dataclass
43
+ class ArgMicroDocument(TextBasedDocument):
44
+ topic_id: Optional[str] = None
45
+ stance: Optional[str] = None
46
+ edus: AnnotationList[Span] = annotation_field(target="text")
47
+ adus: AnnotationList[LabeledAnnotationCollection] = annotation_field(target="edus")
48
+ relations: AnnotationList[MultiRelation] = annotation_field(target="adus")
49
+
50
+
51
+ def example_to_document(
52
+ example: Dict[str, Any],
53
+ adu_type_int2str: Callable[[int], str],
54
+ edge_type_int2str: Callable[[int], str],
55
+ stance_int2str: Callable[[int], str],
56
+ ) -> ArgMicroDocument:
57
+ stance = stance_int2str(example["stance"])
58
+ document = ArgMicroDocument(
59
+ id=example["id"],
60
+ text=example["text"],
61
+ topic_id=example["topic_id"] if example["topic_id"] != "UNDEFINED" else None,
62
+ stance=stance if stance != "UNDEFINED" else None,
63
+ )
64
+ # build EDUs
65
+ edus_dict = {
66
+ edu["id"]: Span(start=edu["start"], end=edu["end"]) for edu in dl2ld(example["edus"])
67
+ }
68
+ # build ADUs
69
+ adu_id2edus = defaultdict(list)
70
+ edges_multi_source = defaultdict(dict)
71
+ for edge in dl2ld(example["edges"]):
72
+ edge_type = edge_type_int2str(edge["type"])
73
+ if edge_type == "seg":
74
+ adu_id2edus[edge["trg"]].append(edus_dict[edge["src"]])
75
+ elif edge_type == "add":
76
+ if "src" not in edges_multi_source[edge["trg"]]:
77
+ edges_multi_source[edge["trg"]]["src"] = []
78
+ edges_multi_source[edge["trg"]]["src"].append(edge["src"])
79
+ else:
80
+ edges_multi_source[edge["id"]]["type"] = edge_type
81
+ edges_multi_source[edge["id"]]["trg"] = edge["trg"]
82
+ if "src" not in edges_multi_source[edge["id"]]:
83
+ edges_multi_source[edge["id"]]["src"] = []
84
+ edges_multi_source[edge["id"]]["src"].append(edge["src"])
85
+ adus_dict = {}
86
+ for adu in dl2ld(example["adus"]):
87
+ adu_type = adu_type_int2str(adu["type"])
88
+ adu_edus = adu_id2edus[adu["id"]]
89
+ adus_dict[adu["id"]] = LabeledAnnotationCollection(
90
+ annotations=tuple(adu_edus), label=adu_type
91
+ )
92
+ # build relations
93
+ rels_dict = {}
94
+ for edge_id, edge in edges_multi_source.items():
95
+ edge_target = edge["trg"]
96
+ if edge_target in edges_multi_source:
97
+ targets = edges_multi_source[edge_target]["src"]
98
+ else:
99
+ targets = [edge_target]
100
+ if any(target in edges_multi_source for target in targets):
101
+ raise Exception("Multi-hop relations are not supported")
102
+ rel = MultiRelation(
103
+ heads=tuple(adus_dict[source] for source in edge["src"]),
104
+ tails=tuple(adus_dict[target] for target in targets),
105
+ label=edge["type"],
106
+ )
107
+ rels_dict[edge_id] = rel
108
+
109
+ document.edus.extend(edus_dict.values())
110
+ document.adus.extend(adus_dict.values())
111
+ document.relations.extend(rels_dict.values())
112
+ document.metadata["edu_ids"] = list(edus_dict.keys())
113
+ document.metadata["adu_ids"] = list(adus_dict.keys())
114
+ document.metadata["rel_ids"] = list(rels_dict.keys())
115
+
116
+ document.metadata["rel_seg_ids"] = {
117
+ edge["src"]: edge["id"]
118
+ for edge in dl2ld(example["edges"])
119
+ if edge_type_int2str(edge["type"]) == "seg"
120
+ }
121
+ document.metadata["rel_add_ids"] = {
122
+ edge["src"]: edge["id"]
123
+ for edge in dl2ld(example["edges"])
124
+ if edge_type_int2str(edge["type"]) == "add"
125
+ }
126
+ return document
127
+
128
+
129
+ def document_to_example(
130
+ document: ArgMicroDocument,
131
+ adu_type_str2int: Callable[[str], int],
132
+ edge_type_str2int: Callable[[str], int],
133
+ stance_str2int: Callable[[str], int],
134
+ ) -> Dict[str, Any]:
135
+ result = {
136
+ "id": document.id,
137
+ "text": document.text,
138
+ "topic_id": document.topic_id or "UNDEFINED",
139
+ "stance": stance_str2int(document.stance or "UNDEFINED"),
140
+ }
141
+
142
+ # construct EDUs
143
+ edus = {
144
+ edu: {"id": edu_id, "start": edu.start, "end": edu.end}
145
+ for edu_id, edu in zip(document.metadata["edu_ids"], document.edus)
146
+ }
147
+ result["edus"] = ld2dl(
148
+ sorted(edus.values(), key=lambda x: x["id"]), keys=["id", "start", "end"]
149
+ )
150
+
151
+ # construct ADUs
152
+ adus = {
153
+ adu: {"id": adu_id, "type": adu_type_str2int(adu.label)}
154
+ for adu_id, adu in zip(document.metadata["adu_ids"], document.adus)
155
+ }
156
+ result["adus"] = ld2dl(sorted(adus.values(), key=lambda x: x["id"]), keys=["id", "type"])
157
+
158
+ # construct edges
159
+ rels_dict: Dict[str, MultiRelation] = {
160
+ rel_id: rel for rel_id, rel in zip(document.metadata["rel_ids"], document.relations)
161
+ }
162
+ heads2rel_id = {
163
+ rel.heads: red_id for red_id, rel in zip(document.metadata["rel_ids"], document.relations)
164
+ }
165
+ edges = []
166
+ for rel_id, rel in rels_dict.items():
167
+ # if it is an undercut attack, we need to change the target to the relation that connects the target
168
+ if rel.label == "und":
169
+ target_id = heads2rel_id[rel.tails]
170
+ else:
171
+ if len(rel.tails) > 1:
172
+ raise Exception("Multi-target relations are not supported")
173
+ target_id = adus[rel.tails[0]]["id"]
174
+ source_id = adus[rel.heads[0]]["id"]
175
+ edge = {
176
+ "id": rel_id,
177
+ "src": source_id,
178
+ "trg": target_id,
179
+ "type": edge_type_str2int(rel.label),
180
+ }
181
+ edges.append(edge)
182
+ # if it is an additional support, we need to change the source to the relation that connects the source
183
+ for head in rel.heads[1:]:
184
+ source_id = adus[head]["id"]
185
+ edge_id = document.metadata["rel_add_ids"][source_id]
186
+ edge = {
187
+ "id": edge_id,
188
+ "src": source_id,
189
+ "trg": rel_id,
190
+ "type": edge_type_str2int("add"),
191
+ }
192
+ edges.append(edge)
193
+
194
+ for adu_id, adu in zip(document.metadata["adu_ids"], document.adus):
195
+ for edu in adu.annotations:
196
+ source_id = edus[edu]["id"]
197
+ target_id = adus[adu]["id"]
198
+ edge_id = document.metadata["rel_seg_ids"][source_id]
199
+ edge = {
200
+ "id": edge_id,
201
+ "src": source_id,
202
+ "trg": target_id,
203
+ "type": edge_type_str2int("seg"),
204
+ }
205
+ edges.append(edge)
206
+
207
+ result["edges"] = ld2dl(
208
+ sorted(edges, key=lambda x: x["id"]), keys=["id", "src", "trg", "type"]
209
+ )
210
+ return result
211
+
212
+
213
+ class ArgMicro(pytorch_ie.data.builder.GeneratorBasedBuilder):
214
+ DOCUMENT_TYPE = ArgMicroDocument
215
+
216
+ BASE_DATASET_PATH = "DFKI-SLT/argmicro"
217
+
218
+ BUILDER_CONFIGS = [datasets.BuilderConfig(name="en"), datasets.BuilderConfig(name="de")]
219
+
220
+ def _generate_document_kwargs(self, dataset):
221
+ return {
222
+ "adu_type_int2str": dataset.features["adus"].feature["type"].int2str,
223
+ "edge_type_int2str": dataset.features["edges"].feature["type"].int2str,
224
+ "stance_int2str": dataset.features["stance"].int2str,
225
+ }
226
+
227
+ def _generate_document(self, example, adu_type_int2str, edge_type_int2str, stance_int2str):
228
+ return example_to_document(
229
+ example,
230
+ adu_type_int2str=adu_type_int2str,
231
+ edge_type_int2str=edge_type_int2str,
232
+ stance_int2str=stance_int2str,
233
+ )