drAbreu commited on
Commit
852a610
·
1 Parent(s): a4d6eb1

Create new file

Browse files
Files changed (1) hide show
  1. sd-nlp-v2.py +238 -0
sd-nlp-v2.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
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
+
16
+
17
+ # template from : https://github.com/huggingface/datasets/blob/master/templates/new_dataset_script.py
18
+
19
+ from __future__ import absolute_import, division, print_function
20
+
21
+ import json
22
+ import datasets
23
+
24
+ _BASE_URL = "https://huggingface.co/datasets/EMBO/sd-nlp-non-tokenized/resolve/main/"
25
+
26
+ class SourceDataNLP(datasets.GeneratorBasedBuilder):
27
+ """SourceDataNLP provides datasets to train NLP tasks in cell and molecular biology."""
28
+
29
+ _NER_LABEL_NAMES = [
30
+ "O",
31
+ "B-SMALL_MOLECULE",
32
+ "I-SMALL_MOLECULE",
33
+ "B-GENEPROD",
34
+ "I-GENEPROD",
35
+ "B-SUBCELLULAR",
36
+ "I-SUBCELLULAR",
37
+ "B-CELL",
38
+ "I-CELL",
39
+ "B-TISSUE",
40
+ "I-TISSUE",
41
+ "B-ORGANISM",
42
+ "I-ORGANISM",
43
+ "B-EXP_ASSAY",
44
+ "I-EXP_ASSAY",
45
+ ]
46
+ _SEMANTIC_GENEPROD_ROLES_LABEL_NAMES = ["O", "B-CONTROLLED_VAR", "I-CONTROLLED_VAR", "B-MEASURED_VAR", "I-MEASURED_VAR"]
47
+ _SEMANTIC_SMALL_MOL_ROLES_LABEL_NAMES = ["O", "B-CONTROLLED_VAR", "I-CONTROLLED_VAR", "B-MEASURED_VAR", "I-MEASURED_VAR"]
48
+ _BORING_LABEL_NAMES = ["O", "B-BORING", "I-BORING"]
49
+ _PANEL_START_NAMES = ["O", "B-PANEL_START", "I-PANEL_START"]
50
+
51
+ _CITATION = """\
52
+ @Unpublished{
53
+ huggingface: dataset,
54
+ title = {SourceData NLP},
55
+ authors={Thomas Lemberger & Jorge Abreu-Vicente, EMBO},
56
+ year={2021}
57
+ }
58
+ """
59
+
60
+ _DESCRIPTION = """\
61
+ This dataset is based on the SourceData database and is intended to facilitate training of NLP tasks in the cell and molecualr biology domain.
62
+ """
63
+
64
+ _HOMEPAGE = "https://huggingface.co/datasets/EMBO/sd-nlp-non-tokenized"
65
+
66
+ _LICENSE = "CC-BY 4.0"
67
+
68
+ VERSION = datasets.Version("2.0.0")
69
+
70
+ _URLS = {
71
+ "NER": f"{_BASE_URL}sd_panelization_v2.zip",
72
+ "PANELIZATION": f"{_BASE_URL}sd_panelization_v2.zip",
73
+ }
74
+ BUILDER_CONFIGS = [
75
+ datasets.BuilderConfig(name="NER", version=VERSION, description="Dataset for entity recognition"),
76
+ datasets.BuilderConfig(name="GENEPROD_ROLES", version=VERSION, description="Dataset for semantic roles."),
77
+ datasets.BuilderConfig(name="SMALL_MOL_ROLES", version=VERSION, description="Dataset for semantic roles."),
78
+ datasets.BuilderConfig(name="BORING", version=VERSION, description="Dataset for semantic roles."),
79
+ datasets.BuilderConfig(
80
+ name="PANELIZATION",
81
+ version=VERSION,
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
+ "words": datasets.Sequence(feature=datasets.Value("string")),
93
+ "labels": datasets.Sequence(
94
+ feature=datasets.ClassLabel(num_classes=len(self._NER_LABEL_NAMES),
95
+ names=self._NER_LABEL_NAMES)
96
+ ),
97
+ "tag_mask": datasets.Sequence(feature=datasets.Value("int8")),
98
+ }
99
+ )
100
+ elif self.config.name == "GENEPROD_ROLES":
101
+ features = datasets.Features(
102
+ {
103
+ "words": datasets.Sequence(feature=datasets.Value("string")),
104
+ "labels": datasets.Sequence(
105
+ feature=datasets.ClassLabel(
106
+ num_classes=len(self._SEMANTIC_GENEPROD_ROLES_LABEL_NAMES),
107
+ names=self._SEMANTIC_GENEPROD_ROLES_LABEL_NAMES
108
+ )
109
+ ),
110
+ "tag_mask": datasets.Sequence(feature=datasets.Value("int8")),
111
+ }
112
+ )
113
+ elif self.config.name == "SMALL_MOL_ROLES":
114
+ features = datasets.Features(
115
+ {
116
+ "words": datasets.Sequence(feature=datasets.Value("string")),
117
+ "labels": datasets.Sequence(
118
+ feature=datasets.ClassLabel(
119
+ num_classes=len(self._SEMANTIC_SMALL_MOL_ROLES_LABEL_NAMES),
120
+ names=self._SEMANTIC_SMALL_MOL_ROLES_LABEL_NAMES
121
+ )
122
+ ),
123
+ "tag_mask": datasets.Sequence(feature=datasets.Value("int8")),
124
+ }
125
+ )
126
+ elif self.config.name == "BORING":
127
+ features = datasets.Features(
128
+ {
129
+ "words": datasets.Sequence(feature=datasets.Value("string")),
130
+ "labels": datasets.Sequence(
131
+ feature=datasets.ClassLabel(num_classes=len(self._BORING_LABEL_NAMES),
132
+ names=self._BORING_LABEL_NAMES)
133
+ ),
134
+ }
135
+ )
136
+ elif self.config.name == "PANELIZATION":
137
+ features = datasets.Features(
138
+ {
139
+ "words": datasets.Sequence(feature=datasets.Value("string")),
140
+ "text": Value("string"),
141
+ "labels": datasets.Sequence(
142
+ feature=datasets.ClassLabel(num_classes=len(self._PANEL_START_NAMES),
143
+ names=self._PANEL_START_NAMES)
144
+ ),
145
+ "tag_mask": datasets.Sequence(feature=datasets.Value("int8")),
146
+ }
147
+ )
148
+
149
+ return datasets.DatasetInfo(
150
+ description=self._DESCRIPTION,
151
+ features=features,
152
+ supervised_keys=("words", "label_ids"),
153
+ homepage=self._HOMEPAGE,
154
+ license=self._LICENSE,
155
+ citation=self._CITATION,
156
+ )
157
+
158
+ def _split_generators(self, dl_manager: datasets.DownloadManager):
159
+ """Returns SplitGenerators.
160
+ Uses local files if a data_dir is specified. Otherwise downloads the files from their official url."""
161
+
162
+ if self.config.name in ["NER", "GENEPROD_ROLES", "SMALL_MOL_ROLES", "BORING"]:
163
+ url = self._URLS["NER"]
164
+ data_dir = dl_manager.download_and_extract(url)
165
+ data_dir += "/sd_panelization_v2"
166
+ elif self.config.name == "PANELIZATION":
167
+ url = self._URLS[self.config.name]
168
+ data_dir = dl_manager.download_and_extract(url)
169
+ data_dir += "/sd_panelization_v2"
170
+ else:
171
+ raise ValueError(f"unkonwn config name: {self.config.name}")
172
+
173
+ return [
174
+ datasets.SplitGenerator(
175
+ name=datasets.Split.TRAIN,
176
+ # These kwargs will be passed to _generate_examples
177
+ gen_kwargs={
178
+ "filepath": data_dir + "/train.jsonl"},
179
+ ),
180
+ datasets.SplitGenerator(
181
+ name=datasets.Split.TEST,
182
+ gen_kwargs={
183
+ "filepath": data_dir + "/test.jsonl"},
184
+ ),
185
+ datasets.SplitGenerator(
186
+ name=datasets.Split.VALIDATION,
187
+ gen_kwargs={
188
+ "filepath": data_dir + "/eval.jsonl"},
189
+ ),
190
+ ]
191
+
192
+ def _generate_examples(self, filepath):
193
+ """Yields examples. This method will receive as arguments the `gen_kwargs` defined in the previous `_split_generators` method.
194
+ It is in charge of opening the given file and yielding (key, example) tuples from the dataset
195
+ The key is not important, it's more here for legacy reason (legacy from tfds)"""
196
+
197
+ with open(filepath, encoding="utf-8") as f:
198
+ # logger.info("⏳ Generating examples from = %s", filepath)
199
+ for id_, row in enumerate(f):
200
+ data = json.loads(row)
201
+ if self.config.name == "NER":
202
+ labels = data["label_ids"]["entity_types"]
203
+ tag_mask = [0 if tag == "O" else 1 for tag in labels]
204
+ yield id_, {
205
+ "words": data["words"],
206
+ "labels": labels,
207
+ "tag_mask": tag_mask
208
+ }
209
+ elif self.config.name == "GENEPROD_ROLES":
210
+ labels = data["label_ids"]["geneprod_roles"]
211
+ geneprod = ["B-GENEPROD", "I-GENEPROD", "B-PROTEIN", "I-PROTEIN", "B-GENE", "I-GENE"]
212
+ tag_mask = [1 if t in geneprod else 0 for t in labels]
213
+ yield id_, {
214
+ "words": data["words"],
215
+ "labels": labels,
216
+ "tag_mask": tag_mask,
217
+ }
218
+ elif self.config.name == "SMALL_MOL_ROLES":
219
+ labels = data["label_ids"]["small_mol_roles"]
220
+ small_mol = ["B-SMALL_MOLECULE", "I-SMALL_MOLECULE"]
221
+ tag_mask = [1 if t in small_mol else 0 for t in labels]
222
+ yield id_, {
223
+ "words": data["words"],
224
+ "labels": labels,
225
+ "tag_mask": tag_mask,
226
+ }
227
+ elif self.config.name == "BORING":
228
+ yield id_, {"words": data["words"],
229
+ "labels": data["label_ids"]["boring"]}
230
+ elif self.config.name == "PANELIZATION":
231
+ labels = data["label_ids"]["panel_start"]
232
+ tag_mask = [1 if t == "B-PANEL_START" else 0 for t in labels]
233
+ yield id_, {
234
+ "words": data["words"],
235
+ "text": data["text"],
236
+ "labels": data["label_ids"]["panel_start"],
237
+ "tag_mask": tag_mask,
238
+ }