ArneBinder idalr commited on
Commit
28ef031
1 Parent(s): 24ed17f

Update dataset files (#1)

Browse files

- Update dataset files (c853efb46a492f79b823b4a1820c65bb2e51df30)


Co-authored-by: Rin Ldallit <idalr@users.noreply.huggingface.co>

Files changed (3) hide show
  1. README.md +55 -3
  2. argmicro.py +92 -42
  3. requirements.txt +1 -1
README.md CHANGED
@@ -1,3 +1,55 @@
1
- ---
2
- license: cc-by-nc-sa-4.0
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PIE Dataset Card for "argmicro"
2
+
3
+ This is a [PyTorch-IE](https://github.com/ChristophAlt/pytorch-ie) wrapper for the
4
+ [ArgMicro Huggingface dataset loading script](https://huggingface.co/datasets/DFKI-SLT/argmicro).
5
+
6
+ ## Dataset Variants
7
+
8
+ The dataset contains two `BuilderConfig`'s:
9
+
10
+ - `de`: with the original texts collection in German
11
+ - `en`: with the English-translated texts
12
+
13
+ ## Data Schema
14
+
15
+ The document type for this dataset is `ArgMicroDocument` which defines the following data fields:
16
+
17
+ - `text` (str)
18
+ - `id` (str, optional)
19
+ - `topic_id` (str, optional)
20
+ - `metadata` (dictionary, optional)
21
+
22
+ and the following annotation layers:
23
+
24
+ - `stance` (annotation type: `Label`)
25
+ - description: A document may contain one of these `stance` labels: `pro`, `con`, `unclear`, or no label when it is undefined (see [here](https://huggingface.co/datasets/DFKI-SLT/argmicro/blob/main/argmicro.py#L35) for reference).
26
+ - `edus` (annotation type: `Span`, target: `text`)
27
+ - `adus` (annotation type: `LabeledAnnotationCollection`, target: `edus`)
28
+ - description: each element of `adus` may consist of several entries from `edus`, so we require `LabeledAnnotationCollection` as annotation type. This is originally indicated by `seg` edges in the data.
29
+ - `LabeledAnnotationCollection` has the following fields:
30
+ - `annotations` (annotation type: `Span`, target: `text`)
31
+ - `label` (str, optional), values: `opp`, `pro` (see [here](https://huggingface.co/datasets/DFKI-SLT/argmicro/blob/main/argmicro.py#L36))
32
+ - `relations` (annotation type: `MultiRelation`, target: `adus`)
33
+ - description: Undercut (`und`) relations originally target other relations (i.e. edges), but we let them target the `head` of the targeted relation instead. The original state can be deterministically reconstructed by taking the label into account. Furthermore, the head of additional source (`add`) relations are integrated into the head of the target relation (note that this propagates along `und` relations). We model this with `MultiRelation`s whose `head` and `tail` are of type `LabeledAnnotationCollection`.
34
+ - `MultiRelation` has the following fields:
35
+ - `head` (tuple, annotation type: `LabeledAnnotationCollection`, target: `adus`)
36
+ - `tail` (tuple, annotation type: `LabeledAnnotationCollection`, target: `adus`)
37
+ - `label` (str, optional), values: `sup`, `exa`, `reb`, `und` (see [here](https://huggingface.co/datasets/DFKI-SLT/argmicro/blob/main/argmicro.py#L37) for reference, but note that helper relations `seg` and `add` are not there anymore, see above).
38
+
39
+ See [here](https://github.com/ChristophAlt/pytorch-ie/blob/main/src/pytorch_ie/annotations.py) for the annotation type definitions.
40
+
41
+ ## Document Converters
42
+
43
+ The dataset provides document converters for the following target document types:
44
+
45
+ - `pytorch_ie.documents.TextDocumentWithLabeledSpansAndBinaryRelations`
46
+ - `LabeledSpans`, converted from `ArgMicroDocument`'s `adus`
47
+ - labels: `opp`, `pro`
48
+ - if an ADU contains multiple spans (i.e. EDUs), we take the start of the first EDU and the end of the last EDU as the boundaries of the new `LabeledSpan`. We also raise exceptions if any newly created `LabeledSpan`s overlap.
49
+ - `BinraryRelations`, converted from `ArgMicroDocument`'s `relations`
50
+ - labels: `sup`, `reb`, `und`, `joint`, `exa`
51
+ - if the `head` or `tail` consists of multiple `adus`, then we build `BinaryRelation`s with all `head`-`tail` combinations and take the label from the original relation. Then, we build `BinaryRelations`' with label `joint` between each component that previously belongs to the same `head` or `tail`, respectively.
52
+ - `metadata`, we keep the `ArgMicroDocument`'s `metadata`, but `stance` and `topic_id`.
53
+
54
+ See [here](https://github.com/ChristophAlt/pytorch-ie/blob/main/src/pytorch_ie/documents.py) for the document type
55
+ definitions.
argmicro.py CHANGED
@@ -1,29 +1,29 @@
 
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)
@@ -42,7 +42,7 @@ class MultiRelation(Annotation):
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")
@@ -50,17 +50,19 @@ class ArgMicroDocument(TextBasedDocument):
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"])
@@ -69,7 +71,7 @@ def example_to_document(
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":
@@ -84,7 +86,7 @@ def example_to_document(
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
@@ -116,27 +118,28 @@ def example_to_document(
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
@@ -150,7 +153,7 @@ def document_to_example(
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"])
@@ -176,7 +179,7 @@ def document_to_example(
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
@@ -187,7 +190,7 @@ def document_to_example(
187
  "id": edge_id,
188
  "src": source_id,
189
  "trg": rel_id,
190
- "type": edge_type_str2int("add"),
191
  }
192
  edges.append(edge)
193
 
@@ -200,7 +203,7 @@ def document_to_example(
200
  "id": edge_id,
201
  "src": source_id,
202
  "trg": target_id,
203
- "type": edge_type_str2int("seg"),
204
  }
205
  edges.append(edge)
206
 
@@ -210,24 +213,71 @@ def document_to_example(
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
- )
 
1
+ import copy
2
  import dataclasses
3
+ import logging
4
  from collections import defaultdict
5
+ from itertools import combinations
6
+ from typing import Any, Dict, List, Optional, Set, Tuple
7
 
8
  import datasets
9
+ from pytorch_ie.annotations import BinaryRelation, Label, LabeledSpan, Span
 
10
  from pytorch_ie.core import Annotation, AnnotationList, annotation_field
11
+ from pytorch_ie.documents import (
12
+ TextBasedDocument,
13
+ TextDocumentWithLabeledSpansAndBinaryRelations,
14
+ )
15
 
16
+ from pie_datasets import GeneratorBasedBuilder
17
 
18
+ log = logging.getLogger(__name__)
19
 
20
 
21
  def dl2ld(dict_of_lists):
22
  return [dict(zip(dict_of_lists, t)) for t in zip(*dict_of_lists.values())]
23
 
24
 
25
+ def ld2dl(list_of_dicts, keys: Optional[List[str]] = None):
26
+ return {k: [d[k] for d in list_of_dicts] for k in keys}
 
 
 
 
 
27
 
28
 
29
  @dataclasses.dataclass(frozen=True)
 
42
  @dataclasses.dataclass
43
  class ArgMicroDocument(TextBasedDocument):
44
  topic_id: Optional[str] = None
45
+ stance: AnnotationList[Label] = annotation_field()
46
  edus: AnnotationList[Span] = annotation_field(target="text")
47
  adus: AnnotationList[LabeledAnnotationCollection] = annotation_field(target="edus")
48
  relations: AnnotationList[MultiRelation] = annotation_field(target="adus")
 
50
 
51
  def example_to_document(
52
  example: Dict[str, Any],
53
+ adu_type_label: datasets.ClassLabel,
54
+ edge_type_label: datasets.ClassLabel,
55
+ stance_label: datasets.ClassLabel,
56
  ) -> ArgMicroDocument:
57
+ stance = stance_label.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
  )
63
+ if stance != "UNDEFINED":
64
+ document.stance.append(Label(label=stance))
65
+
66
  # build EDUs
67
  edus_dict = {
68
  edu["id"]: Span(start=edu["start"], end=edu["end"]) for edu in dl2ld(example["edus"])
 
71
  adu_id2edus = defaultdict(list)
72
  edges_multi_source = defaultdict(dict)
73
  for edge in dl2ld(example["edges"]):
74
+ edge_type = edge_type_label.int2str(edge["type"])
75
  if edge_type == "seg":
76
  adu_id2edus[edge["trg"]].append(edus_dict[edge["src"]])
77
  elif edge_type == "add":
 
86
  edges_multi_source[edge["id"]]["src"].append(edge["src"])
87
  adus_dict = {}
88
  for adu in dl2ld(example["adus"]):
89
+ adu_type = adu_type_label.int2str(adu["type"])
90
  adu_edus = adu_id2edus[adu["id"]]
91
  adus_dict[adu["id"]] = LabeledAnnotationCollection(
92
  annotations=tuple(adu_edus), label=adu_type
 
118
  document.metadata["rel_seg_ids"] = {
119
  edge["src"]: edge["id"]
120
  for edge in dl2ld(example["edges"])
121
+ if edge_type_label.int2str(edge["type"]) == "seg"
122
  }
123
  document.metadata["rel_add_ids"] = {
124
  edge["src"]: edge["id"]
125
  for edge in dl2ld(example["edges"])
126
+ if edge_type_label.int2str(edge["type"]) == "add"
127
  }
128
  return document
129
 
130
 
131
  def document_to_example(
132
  document: ArgMicroDocument,
133
+ adu_type_label: datasets.ClassLabel,
134
+ edge_type_label: datasets.ClassLabel,
135
+ stance_label: datasets.ClassLabel,
136
  ) -> Dict[str, Any]:
137
+ stance = document.stance[0].label if len(document.stance) else "UNDEFINED"
138
  result = {
139
  "id": document.id,
140
  "text": document.text,
141
  "topic_id": document.topic_id or "UNDEFINED",
142
+ "stance": stance_label.str2int(stance),
143
  }
144
 
145
  # construct EDUs
 
153
 
154
  # construct ADUs
155
  adus = {
156
+ adu: {"id": adu_id, "type": adu_type_label.str2int(adu.label)}
157
  for adu_id, adu in zip(document.metadata["adu_ids"], document.adus)
158
  }
159
  result["adus"] = ld2dl(sorted(adus.values(), key=lambda x: x["id"]), keys=["id", "type"])
 
179
  "id": rel_id,
180
  "src": source_id,
181
  "trg": target_id,
182
+ "type": edge_type_label.str2int(rel.label),
183
  }
184
  edges.append(edge)
185
  # if it is an additional support, we need to change the source to the relation that connects the source
 
190
  "id": edge_id,
191
  "src": source_id,
192
  "trg": rel_id,
193
+ "type": edge_type_label.str2int("add"),
194
  }
195
  edges.append(edge)
196
 
 
203
  "id": edge_id,
204
  "src": source_id,
205
  "trg": target_id,
206
+ "type": edge_type_label.str2int("seg"),
207
  }
208
  edges.append(edge)
209
 
 
213
  return result
214
 
215
 
216
+ def convert_to_text_document_with_labeled_spans_and_binary_relations(
217
+ doc: ArgMicroDocument,
218
+ ) -> TextDocumentWithLabeledSpansAndBinaryRelations:
219
+ # convert adus to entities
220
+ entities = []
221
+ adu2entity: Dict[LabeledAnnotationCollection, Span] = {}
222
+ for adu in doc.adus:
223
+ edus: Set[Span] = set(adu.annotations)
224
+ start = min(edu.start for edu in edus)
225
+ end = max(edu.end for edu in edus)
226
+ # assert there are no edus overlapping with the adu, but not part of it
227
+ for edu in doc.edus:
228
+ if (start <= edu.start < end or start < edu.end <= end) and edu not in edus:
229
+ raise Exception(f"edu {edu} is overlapping with adu {adu}, but is not part of it")
230
+ entity = LabeledSpan(start=start, end=end, label=adu.label)
231
+ entities.append(entity)
232
+ adu2entity[adu] = entity
233
+ relations = []
234
+ for relation in doc.relations:
235
+ # add all possible combinations of heads and tails
236
+ for head in relation.heads:
237
+ for tail in relation.tails:
238
+ rel = BinaryRelation(
239
+ label=relation.label, head=adu2entity[head], tail=adu2entity[tail]
240
+ )
241
+ relations.append(rel)
242
+ # also add the relations between the heads themselves
243
+ for head1, head2 in combinations(relation.heads, 2):
244
+ rel = BinaryRelation(label="joint", head=adu2entity[head1], tail=adu2entity[head2])
245
+ relations.append(rel)
246
+ # also add the reverse relation
247
+ rel = BinaryRelation(label="joint", head=adu2entity[head2], tail=adu2entity[head1])
248
+ relations.append(rel)
249
+
250
+ metadata = copy.deepcopy(doc.metadata)
251
+ if len(doc.stance) > 0:
252
+ metadata["stance"] = doc.stance[0].label
253
+ metadata["topic"] = doc.topic_id
254
+ result = TextDocumentWithLabeledSpansAndBinaryRelations(
255
+ text=doc.text, id=doc.id, metadata=doc.metadata
256
+ )
257
+ result.labeled_spans.extend(entities)
258
+ result.binary_relations.extend(relations)
259
+
260
+ return result
261
+
262
+
263
+ class ArgMicro(GeneratorBasedBuilder):
264
  DOCUMENT_TYPE = ArgMicroDocument
265
 
266
+ DOCUMENT_CONVERTERS = {
267
+ TextDocumentWithLabeledSpansAndBinaryRelations: convert_to_text_document_with_labeled_spans_and_binary_relations
268
+ }
269
+
270
  BASE_DATASET_PATH = "DFKI-SLT/argmicro"
271
+ BASE_DATASET_REVISION = "282733d6d57243f2a202d81143c4e31bb250e663"
272
 
273
  BUILDER_CONFIGS = [datasets.BuilderConfig(name="en"), datasets.BuilderConfig(name="de")]
274
 
275
  def _generate_document_kwargs(self, dataset):
276
  return {
277
+ "adu_type_label": dataset.features["adus"].feature["type"],
278
+ "edge_type_label": dataset.features["edges"].feature["type"],
279
+ "stance_label": dataset.features["stance"],
280
  }
281
 
282
+ def _generate_document(self, example, **kwargs):
283
+ return example_to_document(example, **kwargs)
 
 
 
 
 
requirements.txt CHANGED
@@ -1 +1 @@
1
- pytorch-ie>=0.24.0,<0.25.0
 
1
+ pie-datasets>=0.3.3,<0.9.0