ArneBinder commited on
Commit
8a1283f
1 Parent(s): 147f6f9

upgrade to pie-datasets 0.3.0

Browse files
Files changed (3) hide show
  1. README.md +80 -0
  2. brat.py +85 -77
  3. requirements.txt +1 -0
README.md ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PIE Dataset Card for "conll2003"
2
+
3
+ This is a [PyTorch-IE](https://github.com/ChristophAlt/pytorch-ie) wrapper for the
4
+ [BRAT Huggingface dataset loading script](https://huggingface.co/datasets/DFKI-SLT/brat).
5
+
6
+ ## Data Schema
7
+
8
+ The document type for this dataset is `BratDocument` or `BratDocumentWithMergedSpans`, depending on if the
9
+ data was loaded with `merge_fragmented_spans=True` (default: `False`). They define the following data fields:
10
+
11
+ - `text` (str)
12
+ - `id` (str, optional)
13
+ - `metadata` (dictionary, optional)
14
+
15
+ and the following annotation layers:
16
+
17
+ - `spans` (annotation type: `LabeledMultiSpan` in the case of `BratDocument` and `LabeledSpan` and in the case of `BratDocumentWithMergedSpans`, target: `text`)
18
+ - `relations` (annotation type: `BinaryRelation`, target: `spans`)
19
+ - `span_attributes` (annotation type: `Attribute`, target: `spans`)
20
+ - `relation_attributes` (annotation type: `Attribute`, target: `relations`)
21
+
22
+ The `Attribute` annotation type is defined as follows:
23
+
24
+ - `annotation` (type: `Annotation`): the annotation to which the attribute is attached
25
+ - `label` (type: `str`)
26
+ - `value` (type: `str`, optional)
27
+ - `score` (type: `float`, optional, not included in comparison)
28
+
29
+ See [here](https://github.com/ChristophAlt/pytorch-ie/blob/main/src/pytorch_ie/annotations.py) for the remaining annotation type definitions.
30
+
31
+ ## Document Converters
32
+
33
+ The dataset provides no predefined document converters because the BRAT format is very flexible and can be used
34
+ for many different tasks. You can add your own document converter by doing the following:
35
+
36
+ ```python
37
+ import dataclasses
38
+ from typing import Optional
39
+
40
+ from pytorch_ie.core import AnnotationList, annotation_field
41
+ from pytorch_ie.documents import TextBasedDocument
42
+ from pytorch_ie.annotations import LabeledSpan
43
+
44
+ from pie_datasets import DatasetDict
45
+
46
+ # define your document class
47
+ @dataclasses.dataclass
48
+ class MyDocument(TextBasedDocument):
49
+ my_field: Optional[str] = None
50
+ my_span_annotations: AnnotationList[LabeledSpan] = annotation_field(target="text")
51
+
52
+ # define your document converter
53
+ def my_converter(document: BratDocumentWithMergedSpans) -> MyDocument:
54
+ # create your document with the data from the original document.
55
+ # The fields "text", "id" and "metadata" are derived from the TextBasedDocument.
56
+ my_document = MyDocument(id=document.id, text=document.text, metadata=document.metadata, my_field="my_value")
57
+
58
+ # create a new span annotation
59
+ new_span = LabeledSpan(label="my_label", start=2, end=10)
60
+ # add the new span annotation to your document
61
+ my_document.my_span_annotations.append(new_span)
62
+
63
+ # add annotations from the document to your document
64
+ for span in document.spans:
65
+ # we need to copy the span because an annotation can only be attached to one document
66
+ my_document.my_span_annotations.append(span.copy())
67
+
68
+ return my_document
69
+
70
+
71
+ # load the dataset. We use the "merge_fragmented_spans" dataset variant here
72
+ # because it provides documents of type BratDocumentWithMergedSpans.
73
+ dataset = DatasetDict.load_dataset("pie/brat", name="merge_fragmented_spans", data_dir="path/to/brat/data")
74
+
75
+ # attach your document converter to the dataset
76
+ dataset.register_document_converter(my_converter)
77
+
78
+ # convert the dataset
79
+ converted_dataset = dataset.to_document_type(MyDocument)
80
+ ```
brat.py CHANGED
@@ -1,16 +1,14 @@
1
  import dataclasses
2
  import logging
 
3
  from typing import Any, Dict, List, Optional, Tuple, Union
4
 
5
  import datasets
6
- import pytorch_ie
7
- from pytorch_ie.annotations import (
8
- BinaryRelation,
9
- LabeledMultiSpan,
10
- LabeledSpan,
11
- _post_init_single_label,
12
- )
13
- from pytorch_ie.core import Annotation, AnnotationList, Document, annotation_field
14
 
15
  logger = logging.getLogger(__name__)
16
 
@@ -28,41 +26,32 @@ def ld2dl(
28
 
29
  @dataclasses.dataclass(eq=True, frozen=True)
30
  class Attribute(Annotation):
31
- target_annotation: Annotation
32
  label: str
33
  value: Optional[str] = None
34
- score: float = 1.0
35
-
36
- def __post_init__(self) -> None:
37
- _post_init_single_label(self)
38
 
39
 
40
  @dataclasses.dataclass
41
- class BratDocument(Document):
42
- text: str
43
- id: Optional[str] = None
44
- metadata: Dict[str, Any] = dataclasses.field(default_factory=dict)
45
  spans: AnnotationList[LabeledMultiSpan] = annotation_field(target="text")
46
  relations: AnnotationList[BinaryRelation] = annotation_field(target="spans")
47
- span_attributions: AnnotationList[Attribute] = annotation_field(target="spans")
48
- relation_attributions: AnnotationList[Attribute] = annotation_field(target="relations")
49
 
50
 
51
  @dataclasses.dataclass
52
- class BratDocumentWithMergedSpans(Document):
53
- text: str
54
- id: Optional[str] = None
55
- metadata: Dict[str, Any] = dataclasses.field(default_factory=dict)
56
  spans: AnnotationList[LabeledSpan] = annotation_field(target="text")
57
  relations: AnnotationList[BinaryRelation] = annotation_field(target="spans")
58
- span_attributions: AnnotationList[Attribute] = annotation_field(target="spans")
59
- relation_attributions: AnnotationList[Attribute] = annotation_field(target="relations")
60
 
61
 
62
  def example_to_document(
63
- example: Dict[str, Any], merge_non_contiguous_spans: bool = False
64
  ) -> BratDocument:
65
- if merge_non_contiguous_spans:
66
  doc = BratDocumentWithMergedSpans(text=example["context"], id=example["file_name"])
67
  else:
68
  doc = BratDocument(text=example["context"], id=example["file_name"])
@@ -85,14 +74,19 @@ def example_to_document(
85
  f"joined span parts do not match stripped span text field content. "
86
  f'joined_span_texts_stripped: "{joined_span_texts_stripped}" != stripped "text": "{span_text_stripped}"'
87
  )
88
- if merge_non_contiguous_spans:
89
  if len(starts) > 1:
90
  # check if the text in between the fragments holds only space
91
- merged_content_texts = [doc.text[start:end] for start, end in zip(ends[:-1],starts[1:])]
92
- merged_content_texts_not_empty = [text.strip() for text in merged_content_texts if text.strip() != ""]
 
 
 
 
93
  if len(merged_content_texts_not_empty) > 0:
94
  logger.warning(
95
- f"document '{doc.id}' contains a non-contiguous span with text content in between (will be merged into a single span): "
 
96
  f"newly covered text parts: {merged_content_texts_not_empty}, "
97
  f"merged span text: '{doc.text[starts[0]:ends[-1]]}', "
98
  f"annotation: {span_dict}"
@@ -130,28 +124,29 @@ def example_to_document(
130
  if len(events) > 0:
131
  raise NotImplementedError("converting events is not yet implemented")
132
 
133
- span_attributions: Dict[str, Attribute] = dict()
134
- attribution_ids = []
135
- for attribution_dict in dl2ld(example["attributions"]):
136
- target_id = attribution_dict["target"]
137
  if target_id in spans:
138
  target_layer_name = "spans"
139
- target_annotation = spans[target_id]
140
  elif target_id in relations:
141
  target_layer_name = "relations"
142
- target_annotation = relations[target_id]
143
  else:
144
- raise Exception("only span and relation attributions are supported yet")
145
- attribution = Attribute(
146
- target_annotation=target_annotation,
147
- label=attribution_dict["type"],
148
- value=attribution_dict["value"],
149
  )
150
- span_attributions[attribution_dict["id"]] = attribution
151
- attribution_ids.append((target_layer_name, attribution_dict["id"]))
152
 
153
- doc.span_attributions.extend(span_attributions.values())
154
- doc.metadata["attribution_ids"] = attribution_ids
 
155
 
156
  normalizations = dl2ld(example["normalizations"])
157
  if len(normalizations) > 0:
@@ -199,7 +194,8 @@ def document_to_example(
199
  prev_ann_dict = span_dicts[span]
200
  ann_dict = span_dict
201
  logger.warning(
202
- f"document {document.id}: annotation exists twice: {prev_ann_dict['id']} and {ann_dict['id']} are identical"
 
203
  )
204
  span_dicts[span] = span_dict
205
  example["spans"] = ld2dl(list(span_dicts.values()), keys=["id", "type", "locations", "text"])
@@ -221,7 +217,8 @@ def document_to_example(
221
  prev_ann_dict = relation_dicts[rel]
222
  ann_dict = relation_dict
223
  logger.warning(
224
- f"document {document.id}: annotation exists twice: {prev_ann_dict['id']} and {ann_dict['id']} are identical"
 
225
  )
226
  relation_dicts[rel] = relation_dict
227
 
@@ -230,31 +227,41 @@ def document_to_example(
230
  example["equivalence_relations"] = ld2dl([], keys=["type", "targets"])
231
  example["events"] = ld2dl([], keys=["id", "type", "trigger", "arguments"])
232
 
233
- attribution_dicts: Dict[Annotation, Dict[str, Any]] = dict()
234
- span_attribution_ids = [
235
- attribution_id
236
- for target_layer, attribution_id in document.metadata["attribution_ids"]
237
- if target_layer == "spans"
238
- ]
239
- assert len(span_attribution_ids) == len(document.span_attributions)
240
- for i, span_attribution in enumerate(document.span_attributions):
241
- target_id = span_dicts[span_attribution.target_annotation]["id"]
242
- attribution_dict = {
243
- "id": span_attribution_ids[i],
244
- "type": span_attribution.label,
245
- "target": target_id,
246
- "value": span_attribution.value,
247
- }
248
- if span_attribution in attribution_dicts:
249
- prev_ann_dict = attribution_dicts[span_attribution]
250
- ann_dict = span_attribution
251
- logger.warning(
252
- f"document {document.id}: annotation exists twice: {prev_ann_dict['id']} and {ann_dict['id']} are identical"
253
- )
254
- attribution_dicts[span_attribution] = attribution_dict
 
 
 
 
 
 
 
 
 
 
255
 
256
  example["attributions"] = ld2dl(
257
- list(attribution_dicts.values()), keys=["id", "type", "target", "value"]
258
  )
259
  example["normalizations"] = ld2dl(
260
  [], keys=["id", "type", "target", "resource_id", "entity_id"]
@@ -267,31 +274,32 @@ def document_to_example(
267
  class BratConfig(datasets.BuilderConfig):
268
  """BuilderConfig for BratDatasetLoader."""
269
 
270
- def __init__(self, merge_non_contiguous_spans: bool = False, **kwargs):
271
  """BuilderConfig for DocRED.
 
272
  Args:
273
  **kwargs: keyword arguments forwarded to super.
274
  """
275
  super().__init__(**kwargs)
276
- self.merge_non_contiguous_spans = merge_non_contiguous_spans
277
 
278
 
279
- class BratDatasetLoader(pytorch_ie.data.builder.GeneratorBasedBuilder):
280
  # this requires https://github.com/ChristophAlt/pytorch-ie/pull/288
281
  DOCUMENT_TYPES = {
282
  "default": BratDocument,
283
- "merge_non_contiguous_spans": BratDocumentWithMergedSpans,
284
  }
285
 
286
  DEFAULT_CONFIG_NAME = "default"
287
  BUILDER_CONFIGS = [
288
  BratConfig(name="default"),
289
- BratConfig(name="merge_non_contiguous_spans", merge_non_contiguous_spans=True),
290
  ]
291
 
292
  BASE_DATASET_PATH = "DFKI-SLT/brat"
293
 
294
  def _generate_document(self, example, **kwargs):
295
  return example_to_document(
296
- example, merge_non_contiguous_spans=self.config.merge_non_contiguous_spans
297
  )
 
1
  import dataclasses
2
  import logging
3
+ from collections import defaultdict
4
  from typing import Any, Dict, List, Optional, Tuple, Union
5
 
6
  import datasets
7
+ from pytorch_ie.annotations import BinaryRelation, LabeledMultiSpan, LabeledSpan
8
+ from pytorch_ie.core import Annotation, AnnotationList, annotation_field
9
+ from pytorch_ie.documents import TextBasedDocument
10
+
11
+ from pie_datasets import GeneratorBasedBuilder
 
 
 
12
 
13
  logger = logging.getLogger(__name__)
14
 
 
26
 
27
  @dataclasses.dataclass(eq=True, frozen=True)
28
  class Attribute(Annotation):
29
+ annotation: Annotation
30
  label: str
31
  value: Optional[str] = None
32
+ score: Optional[float] = dataclasses.field(default=None, compare=False)
 
 
 
33
 
34
 
35
  @dataclasses.dataclass
36
+ class BratDocument(TextBasedDocument):
 
 
 
37
  spans: AnnotationList[LabeledMultiSpan] = annotation_field(target="text")
38
  relations: AnnotationList[BinaryRelation] = annotation_field(target="spans")
39
+ span_attributes: AnnotationList[Attribute] = annotation_field(target="spans")
40
+ relation_attributes: AnnotationList[Attribute] = annotation_field(target="relations")
41
 
42
 
43
  @dataclasses.dataclass
44
+ class BratDocumentWithMergedSpans(TextBasedDocument):
 
 
 
45
  spans: AnnotationList[LabeledSpan] = annotation_field(target="text")
46
  relations: AnnotationList[BinaryRelation] = annotation_field(target="spans")
47
+ span_attributes: AnnotationList[Attribute] = annotation_field(target="spans")
48
+ relation_attributes: AnnotationList[Attribute] = annotation_field(target="relations")
49
 
50
 
51
  def example_to_document(
52
+ example: Dict[str, Any], merge_fragmented_spans: bool = False
53
  ) -> BratDocument:
54
+ if merge_fragmented_spans:
55
  doc = BratDocumentWithMergedSpans(text=example["context"], id=example["file_name"])
56
  else:
57
  doc = BratDocument(text=example["context"], id=example["file_name"])
 
74
  f"joined span parts do not match stripped span text field content. "
75
  f'joined_span_texts_stripped: "{joined_span_texts_stripped}" != stripped "text": "{span_text_stripped}"'
76
  )
77
+ if merge_fragmented_spans:
78
  if len(starts) > 1:
79
  # check if the text in between the fragments holds only space
80
+ merged_content_texts = [
81
+ doc.text[start:end] for start, end in zip(ends[:-1], starts[1:])
82
+ ]
83
+ merged_content_texts_not_empty = [
84
+ text.strip() for text in merged_content_texts if text.strip() != ""
85
+ ]
86
  if len(merged_content_texts_not_empty) > 0:
87
  logger.warning(
88
+ f"document '{doc.id}' contains a non-contiguous span with text content in between "
89
+ f"(will be merged into a single span): "
90
  f"newly covered text parts: {merged_content_texts_not_empty}, "
91
  f"merged span text: '{doc.text[starts[0]:ends[-1]]}', "
92
  f"annotation: {span_dict}"
 
124
  if len(events) > 0:
125
  raise NotImplementedError("converting events is not yet implemented")
126
 
127
+ attribute_annotations: Dict[str, Dict[str, Attribute]] = defaultdict(dict)
128
+ attribute_ids = []
129
+ for attribute_dict in dl2ld(example["attributions"]):
130
+ target_id = attribute_dict["target"]
131
  if target_id in spans:
132
  target_layer_name = "spans"
133
+ annotation = spans[target_id]
134
  elif target_id in relations:
135
  target_layer_name = "relations"
136
+ annotation = relations[target_id]
137
  else:
138
+ raise Exception("only span and relation attributes are supported yet")
139
+ attribute = Attribute(
140
+ annotation=annotation,
141
+ label=attribute_dict["type"],
142
+ value=attribute_dict["value"],
143
  )
144
+ attribute_annotations[target_layer_name][attribute_dict["id"]] = attribute
145
+ attribute_ids.append((target_layer_name, attribute_dict["id"]))
146
 
147
+ doc.span_attributes.extend(attribute_annotations["spans"].values())
148
+ doc.relation_attributes.extend(attribute_annotations["relations"].values())
149
+ doc.metadata["attribute_ids"] = attribute_ids
150
 
151
  normalizations = dl2ld(example["normalizations"])
152
  if len(normalizations) > 0:
 
194
  prev_ann_dict = span_dicts[span]
195
  ann_dict = span_dict
196
  logger.warning(
197
+ f"document {document.id}: annotation exists twice: {prev_ann_dict['id']} and {ann_dict['id']} "
198
+ f"are identical"
199
  )
200
  span_dicts[span] = span_dict
201
  example["spans"] = ld2dl(list(span_dicts.values()), keys=["id", "type", "locations", "text"])
 
217
  prev_ann_dict = relation_dicts[rel]
218
  ann_dict = relation_dict
219
  logger.warning(
220
+ f"document {document.id}: annotation exists twice: {prev_ann_dict['id']} and {ann_dict['id']} "
221
+ f"are identical"
222
  )
223
  relation_dicts[rel] = relation_dict
224
 
 
227
  example["equivalence_relations"] = ld2dl([], keys=["type", "targets"])
228
  example["events"] = ld2dl([], keys=["id", "type", "trigger", "arguments"])
229
 
230
+ annotation_dicts = {
231
+ "spans": span_dicts,
232
+ "relations": relation_dicts,
233
+ }
234
+ all_attribute_annotations = {
235
+ "spans": document.span_attributes,
236
+ "relations": document.relation_attributes,
237
+ }
238
+ attribute_dicts: Dict[Annotation, Dict[str, Any]] = dict()
239
+ attribute_ids_per_target = defaultdict(list)
240
+ for target_layer, attribute_id in document.metadata["attribute_ids"]:
241
+ attribute_ids_per_target[target_layer].append(attribute_id)
242
+
243
+ for target_layer, attribute_ids in attribute_ids_per_target.items():
244
+ attribute_annotations = all_attribute_annotations[target_layer]
245
+ assert len(attribute_ids) == len(attribute_annotations)
246
+ for i, attribute_annotation in enumerate(attribute_annotations):
247
+ target_id = annotation_dicts[target_layer][attribute_annotation.annotation]["id"]
248
+ attribute_dict = {
249
+ "id": attribute_ids_per_target[target_layer][i],
250
+ "type": attribute_annotation.label,
251
+ "target": target_id,
252
+ "value": attribute_annotation.value,
253
+ }
254
+ if attribute_annotation in attribute_dicts:
255
+ prev_ann_dict = attribute_dicts[attribute_annotation]
256
+ ann_dict = attribute_annotation
257
+ logger.warning(
258
+ f"document {document.id}: annotation exists twice: {prev_ann_dict['id']} and {ann_dict['id']} "
259
+ f"are identical"
260
+ )
261
+ attribute_dicts[attribute_annotation] = attribute_dict
262
 
263
  example["attributions"] = ld2dl(
264
+ list(attribute_dicts.values()), keys=["id", "type", "target", "value"]
265
  )
266
  example["normalizations"] = ld2dl(
267
  [], keys=["id", "type", "target", "resource_id", "entity_id"]
 
274
  class BratConfig(datasets.BuilderConfig):
275
  """BuilderConfig for BratDatasetLoader."""
276
 
277
+ def __init__(self, merge_fragmented_spans: bool = False, **kwargs):
278
  """BuilderConfig for DocRED.
279
+
280
  Args:
281
  **kwargs: keyword arguments forwarded to super.
282
  """
283
  super().__init__(**kwargs)
284
+ self.merge_fragmented_spans = merge_fragmented_spans
285
 
286
 
287
+ class BratDatasetLoader(GeneratorBasedBuilder):
288
  # this requires https://github.com/ChristophAlt/pytorch-ie/pull/288
289
  DOCUMENT_TYPES = {
290
  "default": BratDocument,
291
+ "merge_fragmented_spans": BratDocumentWithMergedSpans,
292
  }
293
 
294
  DEFAULT_CONFIG_NAME = "default"
295
  BUILDER_CONFIGS = [
296
  BratConfig(name="default"),
297
+ BratConfig(name="merge_fragmented_spans", merge_fragmented_spans=True),
298
  ]
299
 
300
  BASE_DATASET_PATH = "DFKI-SLT/brat"
301
 
302
  def _generate_document(self, example, **kwargs):
303
  return example_to_document(
304
+ example, merge_fragmented_spans=self.config.merge_fragmented_spans
305
  )
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ pie-datasets>=0.3.0