ArneBinder commited on
Commit
db9c9bb
1 Parent(s): 027678f

Create tacred.py

Browse files
Files changed (1) hide show
  1. tacred.py +177 -0
tacred.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass, field
2
+ from typing import Any, Callable, Dict, List, Optional, Tuple
3
+
4
+ import datasets
5
+ import pytorch_ie.data.builder
6
+ from pytorch_ie.annotations import BinaryRelation, LabeledSpan, _post_init_single_label
7
+ from pytorch_ie.core import Annotation, AnnotationList, Document, annotation_field
8
+
9
+
10
+ @dataclass(eq=True, frozen=True)
11
+ class TokenRelation(Annotation):
12
+ head_idx: int
13
+ tail_idx: int
14
+ label: str
15
+ score: float = 1.0
16
+
17
+ def __post_init__(self) -> None:
18
+ _post_init_single_label(self)
19
+
20
+
21
+ @dataclass(eq=True, frozen=True)
22
+ class TokenAttribute(Annotation):
23
+ idx: int
24
+ label: str
25
+
26
+
27
+ @dataclass
28
+ class TacredDocument(Document):
29
+ tokens: Tuple[str, ...]
30
+ id: Optional[str] = None
31
+ metadata: Dict[str, Any] = field(default_factory=dict)
32
+ stanford_ner: AnnotationList[TokenAttribute] = annotation_field(target="tokens")
33
+ stanford_pos: AnnotationList[TokenAttribute] = annotation_field(target="tokens")
34
+ entities: AnnotationList[LabeledSpan] = annotation_field(target="tokens")
35
+ relations: AnnotationList[BinaryRelation] = annotation_field(target="entities")
36
+ dependency_relations: AnnotationList[TokenRelation] = annotation_field(target="tokens")
37
+
38
+
39
+ def example_to_document(
40
+ example: Dict[str, Any],
41
+ relation_int2str: Callable[[int], str],
42
+ ner_int2str: Callable[[int], str],
43
+ ) -> TacredDocument:
44
+ document = TacredDocument(
45
+ tokens=tuple(example["token"]), id=example["id"], metadata=dict(doc_id=example["docid"])
46
+ )
47
+
48
+ for idx, (ner, pos) in enumerate(zip(example["stanford_ner"], example["stanford_pos"])):
49
+ document.stanford_ner.append(TokenAttribute(idx=idx, label=ner))
50
+ document.stanford_pos.append(TokenAttribute(idx=idx, label=pos))
51
+
52
+ for tail_idx, (deprel_label, head_idx) in enumerate(
53
+ zip(example["stanford_deprel"], example["stanford_head"])
54
+ ):
55
+ if head_idx >= 0:
56
+ document.dependency_relations.append(
57
+ TokenRelation(
58
+ head_idx=head_idx,
59
+ tail_idx=tail_idx,
60
+ label=deprel_label,
61
+ )
62
+ )
63
+
64
+ head = LabeledSpan(
65
+ start=example["subj_start"],
66
+ end=example["subj_end"],
67
+ label=ner_int2str(example["subj_type"]),
68
+ )
69
+ tail = LabeledSpan(
70
+ start=example["obj_start"],
71
+ end=example["obj_end"],
72
+ label=ner_int2str(example["obj_type"]),
73
+ )
74
+ document.entities.append(head)
75
+ document.entities.append(tail)
76
+
77
+ relation_str = relation_int2str(example["relation"])
78
+ relation = BinaryRelation(head=head, tail=tail, label=relation_str)
79
+ document.relations.append(relation)
80
+
81
+ return document
82
+
83
+
84
+ def _entity_to_dict(
85
+ entity: LabeledSpan, key_prefix: str = "", label_mapping: Optional[Dict[str, Any]] = None
86
+ ) -> Dict[str, Any]:
87
+ return {
88
+ f"{key_prefix}start": entity.start,
89
+ f"{key_prefix}end": entity.end,
90
+ f"{key_prefix}type": label_mapping[entity.label]
91
+ if label_mapping is not None
92
+ else entity.label,
93
+ }
94
+
95
+
96
+ def document_to_example(
97
+ document: TacredDocument,
98
+ ner_names: Optional[List[str]] = None,
99
+ relation_names: Optional[List[str]] = None,
100
+ ) -> Dict[str, Any]:
101
+
102
+ ner2idx = {name: idx for idx, name in enumerate(ner_names)} if ner_names is not None else None
103
+ rel2idx = (
104
+ {name: idx for idx, name in enumerate(relation_names)}
105
+ if relation_names is not None
106
+ else None
107
+ )
108
+
109
+ token = list(document.tokens)
110
+ stanford_ner_dict = {ner.idx: ner.label for ner in document.stanford_ner}
111
+ stanford_pos_dict = {pos.idx: pos.label for pos in document.stanford_pos}
112
+ stanford_ner = [stanford_ner_dict[idx] for idx in range(len(token))]
113
+ stanford_pos = [stanford_pos_dict[idx] for idx in range(len(token))]
114
+
115
+ stanford_deprel = ["ROOT"] * len(document.tokens)
116
+ stanford_head = [-1] * len(document.tokens)
117
+ for dep_rel in document.dependency_relations:
118
+ stanford_deprel[dep_rel.tail_idx] = dep_rel.label
119
+ stanford_head[dep_rel.tail_idx] = dep_rel.head_idx
120
+
121
+ rel = document.relations[0]
122
+ obj: LabeledSpan = rel.tail
123
+ subj: LabeledSpan = rel.head
124
+ return {
125
+ "id": document.id,
126
+ "docid": document.metadata["doc_id"],
127
+ "relation": rel.label if rel2idx is None else rel2idx[rel.label],
128
+ "token": token,
129
+ "stanford_ner": stanford_ner,
130
+ "stanford_pos": stanford_pos,
131
+ "stanford_deprel": stanford_deprel,
132
+ "stanford_head": stanford_head,
133
+ **_entity_to_dict(obj, key_prefix="obj_", label_mapping=ner2idx),
134
+ **_entity_to_dict(subj, key_prefix="subj_", label_mapping=ner2idx),
135
+ }
136
+
137
+
138
+ class TacredConfig(datasets.BuilderConfig):
139
+ """BuilderConfig for Tacred."""
140
+
141
+ def __init__(self, **kwargs):
142
+ """BuilderConfig for Tacred.
143
+ Args:
144
+ **kwargs: keyword arguments forwarded to super.
145
+ """
146
+ super().__init__(**kwargs)
147
+
148
+
149
+ class Tacred(pytorch_ie.data.builder.GeneratorBasedBuilder):
150
+ DOCUMENT_TYPE = TacredDocument
151
+
152
+ BASE_DATASET_PATH = "DFKI-SLT/tacred"
153
+
154
+ BUILDER_CONFIGS = [
155
+ TacredConfig(
156
+ name="original", version=datasets.Version("1.1.0"), description="The original TACRED."
157
+ ),
158
+ TacredConfig(
159
+ name="revisited",
160
+ version=datasets.Version("1.1.0"),
161
+ description="The revised TACRED (corrected labels in dev and test split).",
162
+ ),
163
+ TacredConfig(
164
+ name="re-tacred",
165
+ version=datasets.Version("1.1.0"),
166
+ description="Relabeled TACRED (corrected labels for all splits and pruned)",
167
+ ),
168
+ ]
169
+
170
+ def _generate_document_kwargs(self, dataset):
171
+ return {
172
+ "ner_int2str": dataset.features["subj_type"].int2str,
173
+ "relation_int2str": dataset.features["relation"].int2str,
174
+ }
175
+
176
+ def _generate_document(self, example, **kwargs):
177
+ return example_to_document(example, **kwargs)