Thomas Lemberger commited on
Commit
dd93e10
1 Parent(s): 912fe52
Files changed (1) hide show
  1. sd-nlp.py +204 -0
sd-nlp.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 The HuggingFace Datasets Authors and Thomas Lemberger.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """SourceDataNLP dataset."""
16
+
17
+ from __future__ import absolute_import, division, print_function
18
+
19
+ import json
20
+ from pathlib import Path
21
+
22
+ import datasets
23
+
24
+
25
+ _NER_LABEL_NAMES = [
26
+ "O",
27
+ "I-SMALL_MOLECULE",
28
+ "B-SMALL_MOLECULE",
29
+ "I-GENEPROD",
30
+ "B-GENEPROD",
31
+ "I-SUBCELLULAR",
32
+ "B-SUBCELLULAR",
33
+ "I-CELL",
34
+ "B-CELL",
35
+ "I-TISSUE",
36
+ "B-TISSUE",
37
+ "I-ORGANISM",
38
+ "B-ORGANISM",
39
+ "I-EXP_ASSAY",
40
+ "B-EXP_ASSAY",
41
+ ]
42
+ _SEMANTIC_ROLES_LABEL_NAMES = ["O", "I-CONTROLLED_VAR", "B-CONTROLLED_VAR", "I-MEASURED_VAR", "B-MEASURED_VAR"]
43
+ _BORING_LABEL_NAMES = ["O", "I-BORING", "B-BORING"]
44
+ _PANEL_START_NAMES = ["O", "B-PANEL_START"]
45
+
46
+ _CITATION = """\
47
+ @Unpublished{
48
+ huggingface: dataset,
49
+ title = {SourceData NLP},
50
+ authors={Thomas Lemberger, EMBO},
51
+ year={2021}
52
+ }
53
+ """
54
+
55
+ _DESCRIPTION = """\
56
+ This dataset is based on the SourceData database and is intented to facilitate training of NLP tasks in the cell and molecualr biology domain.
57
+ """
58
+
59
+ _HOMEPAGE = "https://huggingface.co/datasets/EMBO/sd-nlp"
60
+
61
+ _LICENSE = "CC-BY 4.0"
62
+
63
+ _URLS = {
64
+ "NER": "https://huggingface.co/datasets/EMBO/sd-nlp/resolve/main/sd_panels.zip",
65
+ "ROLES": "https://huggingface.co/datasets/EMBO/sd-nlp/resolve/main/sd_panels.zip",
66
+ "BORING": "https://huggingface.co/datasets/EMBO/sd-nlp/resolve/main/sd_panels.zip",
67
+ "PANELIZATION": "https://huggingface.co/datasets/EMBO/sd-nlp/resolve/main/sd_figs.zip",
68
+ }
69
+
70
+ class SourceDataNLP(datasets.GeneratorBasedBuilder):
71
+ """SourceDataNLP provides datasets to train NLP tasks in cell and molecular biology."""
72
+
73
+ VERSION = datasets.Version("0.0.1")
74
+
75
+ BUILDER_CONFIGS = [
76
+ datasets.BuilderConfig(name="NER", version="0.0.1", description="Dataset for entity recognition"),
77
+ datasets.BuilderConfig(name="ROLES", version="0.0.1", description="Dataset for semantic roles."),
78
+ datasets.BuilderConfig(name="BORING", version="0.0.1", description="Dataset for semantic roles."),
79
+ datasets.BuilderConfig(
80
+ name="PANELIZATION",
81
+ version="0.0.1",
82
+ description="Dataset for figure legend segmentation into panel-specific legends.",
83
+ ),
84
+ ]
85
+
86
+ DEFAULT_CONFIG_NAME = "NER"
87
+
88
+ def _info(self):
89
+ if self.config.name == "NER":
90
+ features = datasets.Features(
91
+ {
92
+ "input_ids": datasets.Sequence(feature=datasets.Value("int32")),
93
+ "labels": datasets.Sequence(
94
+ feature=datasets.ClassLabel(num_classes=len(_NER_LABEL_NAMES), names=_NER_LABEL_NAMES)
95
+ ),
96
+ "tag_mask": datasets.Sequence(feature=datasets.Value("int8")),
97
+ }
98
+ )
99
+ elif self.config.name == "ROLES":
100
+ features = datasets.Features(
101
+ {
102
+ "input_ids": datasets.Sequence(feature=datasets.Value("int32")),
103
+ "labels": datasets.Sequence(
104
+ feature=datasets.ClassLabel(
105
+ num_classes=len(_SEMANTIC_ROLES_LABEL_NAMES), names=_SEMANTIC_ROLES_LABEL_NAMES
106
+ )
107
+ ),
108
+ "tag_mask": datasets.Sequence(feature=datasets.Value("int8")),
109
+ }
110
+ )
111
+ elif self.config.name == "BORING":
112
+ features = datasets.Features(
113
+ {
114
+ "input_ids": datasets.Sequence(feature=datasets.Value("int32")),
115
+ "labels": datasets.Sequence(
116
+ feature=datasets.ClassLabel(num_classes=len(_BORING_LABEL_NAMES), names=_BORING_LABEL_NAMES)
117
+ ),
118
+ }
119
+ )
120
+ elif self.config.name == "PANELIZATION":
121
+ features = datasets.Features(
122
+ {
123
+ "input_ids": datasets.Sequence(feature=datasets.Value("int32")),
124
+ "labels": datasets.Sequence(
125
+ feature=datasets.ClassLabel(num_classes=len(_PANEL_START_NAMES), names=_PANEL_START_NAMES)
126
+ ),
127
+ }
128
+ )
129
+
130
+ return datasets.DatasetInfo(
131
+ description=_DESCRIPTION,
132
+ features=features,
133
+ supervised_keys=("input_ids", "labels"),
134
+ homepage=_HOMEPAGE,
135
+ license=_LICENSE,
136
+ citation=_CITATION,
137
+ )
138
+
139
+ def _split_generators(self, dl_manager: datasets.DownloadManager):
140
+ """Returns SplitGenerators.
141
+ Uses local files if a data_dir is specified. Otherwise downloads the files from their official url."""
142
+ if self.config.data_dir:
143
+ data_dir = self.config.data_dir
144
+ else:
145
+ url = _URLS[self.config.name]
146
+ data_dir = dl_manager.download_and_extract(url)
147
+ if self.config.name in ["NER", "ROLES", "BORING"]:
148
+ data_dir += "/sd_panels"
149
+ elif self.config.name == "PANELIZATION":
150
+ data_dir += "/sd_figs"
151
+ else:
152
+ raise ValueError(f"unkonwn config name: {self.config.name}")
153
+ return [
154
+ datasets.SplitGenerator(
155
+ name=datasets.Split.TRAIN,
156
+ # These kwargs will be passed to _generate_examples
157
+ gen_kwargs={
158
+ "filepath": data_dir + "/train.jsonl",
159
+ "split": "train",
160
+ },
161
+ ),
162
+ datasets.SplitGenerator(
163
+ name=datasets.Split.TEST,
164
+ gen_kwargs={
165
+ "filepath": data_dir + "/test.jsonl",
166
+ "split": "test"},
167
+ ),
168
+ datasets.SplitGenerator(
169
+ name=datasets.Split.VALIDATION,
170
+ gen_kwargs={
171
+ "filepath": data_dir + "/eval.jsonl",
172
+ "split": "eval",
173
+ },
174
+ ),
175
+ ]
176
+
177
+ def _generate_examples(self, filepath, split):
178
+ """Yields examples. This method will receive as arguments the `gen_kwargs` defined in the previous `_split_generators` method.
179
+ It is in charge of opening the given file and yielding (key, example) tuples from the dataset
180
+ The key is not important, it's more here for legacy reason (legacy from tfds)"""
181
+
182
+ with open(filepath, encoding="utf-8") as f:
183
+ for id_, row in enumerate(f):
184
+ data = json.loads(row)
185
+ if self.config.name == "NER":
186
+ labels_type = data["label_ids"]["entity_types"]
187
+ tag_mask = [0 if tag == "O" else 1 for tag in labels_type]
188
+ yield id_, {"input_ids": data["input_ids"], "labels": labels_type, "tag_mask": tag_mask}
189
+ elif self.config.name == "ROLES":
190
+ labels_type = data["label_ids"]["entity_types"]
191
+ geneprod = ["B-GENEPROD", "I-GENEPROD", "B-PROTEIN", "I-PROTEIN", "B-GENE", "I-GENE"]
192
+ tag_mask = [1 if t in geneprod else 0 for t in labels_type]
193
+ yield id_, {
194
+ "input_ids": data["input_ids"],
195
+ "labels": data["label_ids"]["geneprod_roles"],
196
+ "tag_mask": tag_mask,
197
+ }
198
+ elif self.config.name == "BORING":
199
+ yield id_, {"input_ids": data["input_ids"], "labels": data["label_ids"]["boring"]}
200
+ elif self.config.name == "PANELIZATION":
201
+ yield id_, {
202
+ "input_ids": data["input_ids"],
203
+ "labels": data["label_ids"]["panel_start"],
204
+ }