ArneBinder commited on
Commit
79740b5
1 Parent(s): 751cc48

from https://github.com/ArneBinder/pie-datasets/pull/138

Browse files
Files changed (3) hide show
  1. README.md +48 -0
  2. chemprot.py +273 -0
  3. requirements.txt +1 -0
README.md ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PIE Dataset Card for "ChemProt"
2
+
3
+ This is a [PyTorch-IE](https://github.com/ChristophAlt/pytorch-ie) wrapper for the
4
+ [ChemProt Huggingface dataset loading script](https://huggingface.co/datasets/bigbio/chemprot).
5
+
6
+ ## Data Schema
7
+
8
+ There are three versions of the dataset supported, `chemprot_full_source`, `chemprot_shared_task_eval_source` and `chemprot_bigbio_kb`.
9
+
10
+ #### `ChemprotDocument` for `chemprot_source` and `chemprot_shared_task_eval_source`
11
+
12
+ defines following fields:
13
+
14
+ - `text` (str)
15
+ - `id` (str, optional)
16
+ - `metadata` (dictionary, optional)
17
+
18
+ and the following annotation layers:
19
+
20
+ - `entities` (annotation type: `LabeledSpan`, target: `text`)
21
+ - `relations` (annotation type: `BinaryRelation`, target: `entities`)
22
+
23
+ #### `ChemprotBigbioDocument` for `chemprot_bigbio_kb`
24
+
25
+ defines following fields:
26
+
27
+ - `text` (str)
28
+ - `id` (str, optional)
29
+ - `metadata` (dictionary, optional)
30
+
31
+ and the following annotation layers:
32
+
33
+ - `passages` (annotation type: `LabeledSpan`, target: `text`)
34
+ - `entities` (annotation type: `LabeledSpan`, target: `text`)
35
+ - `relations` (annotation type: `BinaryRelation`, target: `entities`)
36
+
37
+ See [here](https://github.com/ArneBinder/pie-modules/blob/main/src/pie_modules/annotations.py) for the annotation
38
+ type definitions.
39
+
40
+ ## Document Converters
41
+
42
+ The dataset provides predefined document converters for the following target document types:
43
+
44
+ - `pie_modules.documents.TextDocumentWithLabeledSpansAndBinaryRelations` for `ChemprotDocument`
45
+ - `pie_modules.documents.TextDocumentWithLabeledSpansBinaryRelationsAndLabeledPartitions` for `ChemprotBigbioDocument`
46
+
47
+ See [here](https://github.com/ArneBinder/pie-modules/blob/main/src/pie_modules/documents.py) for the document type
48
+ definitions.
chemprot.py ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from typing import Any, Dict
3
+
4
+ import datasets
5
+ from pytorch_ie import Document
6
+ from pytorch_ie.annotations import BinaryRelation, LabeledSpan
7
+ from pytorch_ie.documents import (
8
+ AnnotationLayer,
9
+ TextBasedDocument,
10
+ TextDocumentWithLabeledSpansAndBinaryRelations,
11
+ TextDocumentWithLabeledSpansBinaryRelationsAndLabeledPartitions,
12
+ annotation_field,
13
+ )
14
+
15
+ from pie_datasets import GeneratorBasedBuilder
16
+
17
+
18
+ @dataclass
19
+ class ChemprotDocument(TextBasedDocument):
20
+ # used by chemprot_full_source and chemprot_shared_task_eval_source
21
+ entities: AnnotationLayer[LabeledSpan] = annotation_field(target="text")
22
+ relations: AnnotationLayer[BinaryRelation] = annotation_field(target="entities")
23
+
24
+
25
+ @dataclass
26
+ class ChemprotBigbioDocument(TextBasedDocument):
27
+ passages: AnnotationLayer[LabeledSpan] = annotation_field(target="text")
28
+ entities: AnnotationLayer[LabeledSpan] = annotation_field(target="text")
29
+ relations: AnnotationLayer[BinaryRelation] = annotation_field(target="entities")
30
+
31
+
32
+ def example_to_chemprot_doc(example) -> ChemprotDocument:
33
+ metadata = {"entity_ids": []}
34
+ id_to_labeled_span: Dict[str, LabeledSpan] = {}
35
+
36
+ doc = ChemprotDocument(
37
+ text=example["text"],
38
+ id=example["pmid"],
39
+ metadata=metadata,
40
+ )
41
+
42
+ for idx in range(len(example["entities"]["id"])):
43
+ labeled_span = LabeledSpan(
44
+ start=example["entities"]["offsets"][idx][0],
45
+ end=example["entities"]["offsets"][idx][1],
46
+ label=example["entities"]["type"][idx],
47
+ )
48
+ doc.entities.append(labeled_span)
49
+ doc.metadata["entity_ids"].append(example["entities"]["id"][idx])
50
+ id_to_labeled_span[example["entities"]["id"][idx]] = labeled_span
51
+
52
+ for idx in range(len(example["relations"]["type"])):
53
+ doc.relations.append(
54
+ BinaryRelation(
55
+ head=id_to_labeled_span[example["relations"]["arg1"][idx]],
56
+ tail=id_to_labeled_span[example["relations"]["arg2"][idx]],
57
+ label=example["relations"]["type"][idx],
58
+ )
59
+ )
60
+
61
+ return doc
62
+
63
+
64
+ def example_to_chemprot_bigbio_doc(example) -> ChemprotBigbioDocument:
65
+ text = " ".join([" ".join(passage["text"]) for passage in example["passages"]])
66
+ metadata = {"id": example["id"], "entity_ids": [], "relation_ids": []}
67
+ id_to_labeled_span: Dict[str, LabeledSpan] = {}
68
+
69
+ doc = ChemprotBigbioDocument(
70
+ text=text,
71
+ id=example["document_id"],
72
+ metadata=metadata,
73
+ )
74
+
75
+ for passage in example["passages"]:
76
+ doc.passages.append(
77
+ LabeledSpan(
78
+ start=passage["offsets"][0][0],
79
+ end=passage["offsets"][0][1],
80
+ label=passage["type"],
81
+ )
82
+ )
83
+
84
+ for span in example["entities"]:
85
+ labeled_span = LabeledSpan(
86
+ start=span["offsets"][0][0],
87
+ end=span["offsets"][0][1],
88
+ label=span["type"],
89
+ )
90
+ doc.entities.append(labeled_span)
91
+ doc.metadata["entity_ids"].append(span["id"])
92
+ id_to_labeled_span[span["id"]] = labeled_span
93
+
94
+ for relation in example["relations"]:
95
+ doc.relations.append(
96
+ BinaryRelation(
97
+ head=id_to_labeled_span[relation["arg1_id"]],
98
+ tail=id_to_labeled_span[relation["arg2_id"]],
99
+ label=relation["type"],
100
+ )
101
+ )
102
+ doc.metadata["relation_ids"].append([relation["arg1_id"], relation["arg2_id"]])
103
+
104
+ return doc
105
+
106
+
107
+ def chemprot_doc_to_example(doc: ChemprotDocument) -> Dict[str, Any]:
108
+ entities = {
109
+ "id": [],
110
+ "offsets": [],
111
+ "text": [],
112
+ "type": [],
113
+ }
114
+ relations = {
115
+ "arg1": [],
116
+ "arg2": [],
117
+ "type": [],
118
+ }
119
+
120
+ entity_id2entity = {
121
+ ent_id: entity for ent_id, entity in zip(doc.metadata["entity_ids"], doc.entities)
122
+ }
123
+
124
+ for entity_id, entity in zip(doc.metadata["entity_ids"], doc.entities):
125
+ entities["id"].append(entity_id)
126
+ entities["offsets"].append([entity.start, entity.end])
127
+ entities["text"].append(doc.text[entity.start : entity.end])
128
+ entities["type"].append(entity.label)
129
+
130
+ if entity in entity_id2entity:
131
+ raise ValueError("Entity already exists in entity_id2entity")
132
+
133
+ entity_id2entity[entity] = entity_id
134
+
135
+ for relation in doc.relations:
136
+ relations["arg1"].append(entity_id2entity[relation.head])
137
+ relations["arg2"].append(entity_id2entity[relation.tail])
138
+ relations["type"].append(relation.label)
139
+
140
+ return {
141
+ "text": doc.text,
142
+ "pmid": doc.id,
143
+ "entities": entities,
144
+ "relations": relations,
145
+ }
146
+
147
+
148
+ def chemprot_bigbio_doc_to_example(doc: ChemprotBigbioDocument) -> Dict[str, Any]:
149
+ id = int(doc.metadata["id"])
150
+ passages = []
151
+ entities = []
152
+ relations = []
153
+
154
+ entity_id2entity = {
155
+ ent_id: entity for ent_id, entity in zip(doc.metadata["entity_ids"], doc.entities)
156
+ }
157
+
158
+ for passage in doc.passages:
159
+ id += 1
160
+ passages.append(
161
+ {
162
+ "id": str(id),
163
+ "offsets": [[passage.start, passage.end]],
164
+ "text": [doc.text[passage.start : passage.end]],
165
+ "type": passage.label,
166
+ }
167
+ )
168
+
169
+ entity2entity_id = dict()
170
+
171
+ for entity_id, entity in zip(doc.metadata["entity_ids"], doc.entities):
172
+ id += 1
173
+ entities.append(
174
+ {
175
+ "id": entity_id, # entity_id = str(id)
176
+ "normalized": [],
177
+ "offsets": [[entity.start, entity.end]],
178
+ "text": [doc.text[entity.start : entity.end]],
179
+ "type": entity.label,
180
+ }
181
+ )
182
+ if entity in entity_id2entity:
183
+ raise ValueError("Entity already exists in entity_id2entity")
184
+
185
+ entity2entity_id[entity] = entity_id
186
+
187
+ for relation in doc.relations:
188
+ id += 1
189
+ relations.append(
190
+ {
191
+ "id": str(id), # save in metadata?
192
+ "arg1_id": entity2entity_id[relation.head],
193
+ "arg2_id": entity2entity_id[relation.tail],
194
+ "type": relation.label,
195
+ "normalized": [],
196
+ }
197
+ )
198
+
199
+ return {
200
+ "id": doc.metadata["id"],
201
+ "document_id": doc.id,
202
+ "passages": passages,
203
+ "entities": entities,
204
+ "events": [],
205
+ "coreferences": [],
206
+ "relations": relations,
207
+ }
208
+
209
+
210
+ class Chemprot(GeneratorBasedBuilder):
211
+ DOCUMENT_TYPES = { # Note ChemprotDocument is used twice
212
+ "chemprot_full_source": ChemprotDocument,
213
+ "chemprot_bigbio_kb": ChemprotBigbioDocument,
214
+ "chemprot_shared_task_eval_source": ChemprotDocument,
215
+ }
216
+
217
+ BASE_DATASET_PATH = "bigbio/chemprot"
218
+ BASE_DATASET_REVISION = "86afccf3ccc614f817a7fad0692bf62fbc5ce469"
219
+
220
+ BUILDER_CONFIGS = [
221
+ datasets.BuilderConfig(
222
+ name="chemprot_full_source",
223
+ version=datasets.Version("1.0.0"),
224
+ description="ChemProt full source version",
225
+ ),
226
+ datasets.BuilderConfig(
227
+ name="chemprot_bigbio_kb",
228
+ version=datasets.Version("1.0.0"),
229
+ description="ChemProt BigBio kb version",
230
+ ),
231
+ datasets.BuilderConfig(
232
+ name="chemprot_shared_task_eval_source",
233
+ version=datasets.Version("1.0.0"),
234
+ description="ChemProt shared task eval source version",
235
+ ),
236
+ ]
237
+
238
+ @property
239
+ def document_converters(self):
240
+ if (
241
+ self.config.name == "chemprot_full_source"
242
+ or self.config.name == "chemprot_shared_task_eval_source"
243
+ ):
244
+ return {
245
+ TextDocumentWithLabeledSpansAndBinaryRelations: {
246
+ "entities": "labeled_spans",
247
+ "relations": "binary_relations",
248
+ }
249
+ }
250
+ elif self.config.name == "chemprot_bigbio_kb":
251
+ return {
252
+ TextDocumentWithLabeledSpansBinaryRelationsAndLabeledPartitions: {
253
+ "passages": "labeled_partitions",
254
+ "entities": "labeled_spans",
255
+ "relations": "binary_relations",
256
+ }
257
+ }
258
+ else:
259
+ raise ValueError(f"Unknown dataset name: {self.config.name}")
260
+
261
+ def _generate_document(self, example, **kwargs):
262
+ if self.config.name == "chemprot_bigbio_kb":
263
+ return example_to_chemprot_bigbio_doc(example)
264
+ else:
265
+ return example_to_chemprot_doc(example)
266
+
267
+ def _generate_example(self, document: Document, **kwargs) -> Dict[str, Any]:
268
+ if isinstance(document, ChemprotBigbioDocument):
269
+ return chemprot_bigbio_doc_to_example(document)
270
+ elif isinstance(document, ChemprotDocument):
271
+ return chemprot_doc_to_example(document)
272
+ else:
273
+ raise ValueError(f"Unknown document type: {type(document)}")
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ pie-datasets>=0.6.0,<0.11.0