ArneBinder commited on
Commit
1e5e4bd
1 Parent(s): cd86023

Create scidtb_argmin.py

Browse files
Files changed (1) hide show
  1. scidtb_argmin.py +146 -0
scidtb_argmin.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dataclasses
2
+ import logging
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 BinaryRelation, LabeledSpan
8
+ from pytorch_ie.core import AnnotationList, Document, annotation_field
9
+ from pytorch_ie.utils.span import bio_tags_to_spans
10
+
11
+ log = logging.getLogger(__name__)
12
+
13
+
14
+ def labels_and_spans_to_bio_tags(
15
+ labels: List[str], spans: List[Tuple[int, int]], sequence_length: int
16
+ ) -> List[str]:
17
+ bio_tags = ["O"] * sequence_length
18
+ for label, (start, end) in zip(labels, spans):
19
+ bio_tags[start] = f"B-{label}"
20
+ for i in range(start + 1, end):
21
+ bio_tags[i] = f"I-{label}"
22
+ return bio_tags
23
+
24
+
25
+ @dataclasses.dataclass
26
+ class SciDTBArgminDocument(Document):
27
+ tokens: Tuple[str, ...]
28
+ id: Optional[str] = None
29
+ metadata: Dict[str, Any] = dataclasses.field(default_factory=dict)
30
+ units: AnnotationList[LabeledSpan] = annotation_field(target="tokens")
31
+ relations: AnnotationList[BinaryRelation] = annotation_field(target="units")
32
+
33
+
34
+ def example_to_document(
35
+ example: Dict[str, Any],
36
+ unit_bio_int2str: Callable[[int], str],
37
+ unit_label_int2str: Callable[[int], str],
38
+ relation_int2str: Callable[[int], str],
39
+ ):
40
+
41
+ document = SciDTBArgminDocument(id=example["id"], tokens=tuple(example["data"]["token"]))
42
+ bio_tags = unit_bio_int2str(example["data"]["unit-bio"])
43
+ unit_labels = unit_label_int2str(example["data"]["unit-label"])
44
+ roles = relation_int2str(example["data"]["role"])
45
+ tag_sequence = [
46
+ f"{bio}-{label}|{role}|{parent_offset}"
47
+ for bio, label, role, parent_offset in zip(
48
+ bio_tags, unit_labels, roles, example["data"]["parent-offset"]
49
+ )
50
+ ]
51
+ spans_with_label = sorted(
52
+ bio_tags_to_spans(tag_sequence), key=lambda label_and_span: label_and_span[1][0]
53
+ )
54
+ labels, spans = zip(*spans_with_label)
55
+ span_unit_labels, span_roles, span_parent_offsets = zip(
56
+ *[label.split("|") for label in labels]
57
+ )
58
+
59
+ units = [
60
+ LabeledSpan(start=start, end=end + 1, label=label)
61
+ for (start, end), label in zip(spans, span_unit_labels)
62
+ ]
63
+ document.units.extend(units)
64
+
65
+ # TODO: check if direction of the relation is correct (what is the head / tail of the relation?)
66
+ relations = []
67
+ for idx, parent_offset in enumerate(span_parent_offsets):
68
+ if span_roles[idx] != "none":
69
+ relations.append(
70
+ BinaryRelation(
71
+ head=units[idx], tail=units[idx + int(parent_offset)], label=span_roles[idx]
72
+ )
73
+ )
74
+
75
+ document.relations.extend(relations)
76
+
77
+ return document
78
+
79
+
80
+ def document_to_example(
81
+ document: SciDTBArgminDocument,
82
+ unit_bio_str2int: Callable[[str], int],
83
+ unit_label_str2int: Callable[[str], int],
84
+ relation_str2int: Callable[[str], int],
85
+ ) -> Dict[str, Any]:
86
+
87
+ unit2idx = {unit: idx for idx, unit in enumerate(document.units)}
88
+ unit2parent_relation = {relation.head: relation for relation in document.relations}
89
+
90
+ unit_labels = [unit.label for unit in document.units]
91
+ roles = [
92
+ unit2parent_relation[unit].label if unit in unit2parent_relation else "none"
93
+ for unit in document.units
94
+ ]
95
+ parent_offsets = [
96
+ unit2idx[unit2parent_relation[unit].tail] - idx if unit in unit2parent_relation else 0
97
+ for idx, unit in enumerate(document.units)
98
+ ]
99
+ labels = [
100
+ f"{unit_label}-{role}-{parent_offset}"
101
+ for unit_label, role, parent_offset in zip(unit_labels, roles, parent_offsets)
102
+ ]
103
+
104
+ tag_sequence = labels_and_spans_to_bio_tags(
105
+ labels=labels,
106
+ spans=[(unit.start, unit.end) for unit in document.units],
107
+ sequence_length=len(document.tokens),
108
+ )
109
+ bio_tags, unit_labels, roles, parent_offsets = zip(
110
+ *[tag.split("-", maxsplit=3) for tag in tag_sequence]
111
+ )
112
+
113
+ data = {
114
+ "token": list(document.tokens),
115
+ "unit-bio": unit_bio_str2int(bio_tags),
116
+ "unit-label": unit_label_str2int(unit_labels),
117
+ "role": relation_str2int(roles),
118
+ "parent-offset": [int(idx_str) for idx_str in parent_offsets],
119
+ }
120
+ result = {"id": document.id, "data": data}
121
+ return result
122
+
123
+
124
+ class SciDTBArgmin(pytorch_ie.data.builder.GeneratorBasedBuilder):
125
+ DOCUMENT_TYPE = SciDTBArgminDocument
126
+
127
+ BASE_DATASET_PATH = "DFKI-SLT/scidtb_argmin"
128
+
129
+ BUILDER_CONFIGS = [datasets.BuilderConfig(name="default")]
130
+
131
+ DEFAULT_CONFIG_NAME = "default"
132
+
133
+ def _generate_document_kwargs(self, dataset):
134
+ return {
135
+ "unit_bio_int2str": dataset.features["data"].feature["unit-bio"].int2str,
136
+ "unit_label_int2str": dataset.features["data"].feature["unit-label"].int2str,
137
+ "relation_int2str": dataset.features["data"].feature["role"].int2str,
138
+ }
139
+
140
+ def _generate_document(self, example, unit_bio_int2str, unit_label_int2str, relation_int2str):
141
+ return example_to_document(
142
+ example,
143
+ unit_bio_int2str=unit_bio_int2str,
144
+ unit_label_int2str=unit_label_int2str,
145
+ relation_int2str=relation_int2str,
146
+ )