gabrielaltay commited on
Commit
21601b8
1 Parent(s): a53f3f3

upload hubscripts/nlmchem_hub.py to hub from bigbio repo

Browse files
Files changed (1) hide show
  1. nlmchem.py +371 -0
nlmchem.py ADDED
@@ -0,0 +1,371 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Datasets Authors and the current dataset script contributor.
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import os
16
+ import re
17
+ from typing import Dict, Iterator, List, Tuple
18
+
19
+ import bioc
20
+ import datasets
21
+ from bioc import biocxml
22
+
23
+ from .bigbiohub import kb_features
24
+ from .bigbiohub import BigBioConfig
25
+ from .bigbiohub import Tasks
26
+
27
+ _LANGUAGES = ['English']
28
+ _PUBMED = True
29
+ _LOCAL = False
30
+ _CITATION = """\
31
+ @Article{islamaj2021nlm,
32
+ title={NLM-Chem, a new resource for chemical entity recognition in PubMed full text literature},
33
+ author={Islamaj, Rezarta and Leaman, Robert and Kim, Sun and Kwon, Dongseop and Wei, Chih-Hsuan and Comeau, Donald C and Peng, Yifan and Cissel, David and Coss, Cathleen and Fisher, Carol and others},
34
+ journal={Scientific Data},
35
+ volume={8},
36
+ number={1},
37
+ pages={1--12},
38
+ year={2021},
39
+ publisher={Nature Publishing Group}
40
+ }
41
+ """
42
+
43
+ _DATASETNAME = "nlmchem"
44
+ _DISPLAYNAME = "NLM-Chem"
45
+
46
+ _DESCRIPTION = """\
47
+ NLM-Chem corpus consists of 150 full-text articles from the PubMed Central Open Access dataset,
48
+ comprising 67 different chemical journals, aiming to cover a general distribution of usage of chemical
49
+ names in the biomedical literature.
50
+ Articles were selected so that human annotation was most valuable (meaning that they were rich in bio-entities,
51
+ and current state-of-the-art named entity recognition systems disagreed on bio-entity recognition.
52
+ """
53
+
54
+ _HOMEPAGE = "https://biocreative.bioinformatics.udel.edu/tasks/biocreative-vii/track-2"
55
+ _LICENSE = 'Creative Commons Zero v1.0 Universal'
56
+
57
+ # files found here `https://ftp.ncbi.nlm.nih.gov/pub/lu/BC7-NLM-Chem-track/` have issues at extraction
58
+ # _URLs = {"biocreative": "https://ftp.ncbi.nlm.nih.gov/pub/lu/NLMChem" }
59
+ _URLs = {
60
+ "source": "https://ftp.ncbi.nlm.nih.gov/pub/lu/BC7-NLM-Chem-track/BC7T2-NLMChem-corpus_v2.BioC.xml.gz",
61
+ "bigbio_kb": "https://ftp.ncbi.nlm.nih.gov/pub/lu/BC7-NLM-Chem-track/BC7T2-NLMChem-corpus_v2.BioC.xml.gz",
62
+ "bigbio_text": "https://ftp.ncbi.nlm.nih.gov/pub/lu/BC7-NLM-Chem-track/BC7T2-NLMChem-corpus_v2.BioC.xml.gz",
63
+ }
64
+ _SUPPORTED_TASKS = [
65
+ Tasks.NAMED_ENTITY_RECOGNITION,
66
+ Tasks.NAMED_ENTITY_DISAMBIGUATION,
67
+ Tasks.TEXT_CLASSIFICATION,
68
+ ]
69
+ _SOURCE_VERSION = "1.0.0"
70
+ _BIGBIO_VERSION = "1.0.0"
71
+
72
+
73
+ class NLMChemDataset(datasets.GeneratorBasedBuilder):
74
+ """NLMChem"""
75
+
76
+ SOURCE_VERSION = datasets.Version(_SOURCE_VERSION)
77
+ BIGBIO_VERSION = datasets.Version(_BIGBIO_VERSION)
78
+
79
+ BUILDER_CONFIGS = [
80
+ BigBioConfig(
81
+ name="nlmchem_source",
82
+ version=SOURCE_VERSION,
83
+ description="NLM_Chem source schema",
84
+ schema="source",
85
+ subset_id="nlmchem",
86
+ ),
87
+ BigBioConfig(
88
+ name="nlmchem_bigbio_kb",
89
+ version=BIGBIO_VERSION,
90
+ description="NLM_Chem BigBio schema (KB)",
91
+ schema="bigbio_kb",
92
+ subset_id="nlmchem",
93
+ ),
94
+ BigBioConfig(
95
+ name="nlmchem_bigbio_text",
96
+ version=BIGBIO_VERSION,
97
+ description="NLM_Chem BigBio schema (TEXT)",
98
+ schema="bigbio_text",
99
+ subset_id="nlmchem",
100
+ ),
101
+ ]
102
+
103
+ DEFAULT_CONFIG_NAME = "nlmchem_source" # It's not mandatory to have a default configuration. Just use one if it make sense.
104
+
105
+ def _info(self):
106
+
107
+ if self.config.schema == "source":
108
+ # this is a variation on the BioC format
109
+ features = datasets.Features(
110
+ {
111
+ "passages": [
112
+ {
113
+ "document_id": datasets.Value("string"),
114
+ "type": datasets.Value("string"),
115
+ "text": datasets.Value("string"),
116
+ "offset": datasets.Value("int32"),
117
+ "entities": [
118
+ {
119
+ "id": datasets.Value("string"),
120
+ "offsets": [[datasets.Value("int32")]],
121
+ "text": [datasets.Value("string")],
122
+ "type": datasets.Value("string"),
123
+ "normalized": [
124
+ {
125
+ "db_name": datasets.Value("string"),
126
+ "db_id": datasets.Value("string"),
127
+ }
128
+ ],
129
+ }
130
+ ],
131
+ }
132
+ ]
133
+ }
134
+ )
135
+
136
+ elif self.config.schema == "bigbio_kb":
137
+ features = kb_features
138
+ elif self.config.schema == "bigbio_text":
139
+ features = text_features
140
+
141
+ return datasets.DatasetInfo(
142
+ # This is the description that will appear on the datasets page.
143
+ description=_DESCRIPTION,
144
+ # This defines the different columns of the dataset and their types
145
+ features=features, # Here we define them above because they are different between the two configurations
146
+ # If there's a common (input, target) tuple from the features,
147
+ # specify them here. They'll be used if as_supervised=True in
148
+ # builder.as_dataset.
149
+ supervised_keys=None,
150
+ # Homepage of the dataset for documentation
151
+ homepage=_HOMEPAGE,
152
+ # License for the dataset if available
153
+ license=str(_LICENSE),
154
+ # Citation for the dataset
155
+ citation=_CITATION,
156
+ )
157
+
158
+ def _split_generators(self, dl_manager):
159
+ """Returns SplitGenerators."""
160
+ # TODO: This method is tasked with downloading/extracting the data and defining the splits depending on the configuration
161
+ # If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name
162
+
163
+ # dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLs
164
+ # It can accept any type or nested list/dict and will give back the same structure with the url replaced with path to local files.
165
+ # By default the archives will be extracted and a path to a cached folder where they are extracted is returned instead of the archive
166
+ my_urls = _URLs[self.config.schema]
167
+ data_dir = dl_manager.download_and_extract(my_urls)
168
+ return [
169
+ datasets.SplitGenerator(
170
+ name=datasets.Split.TRAIN,
171
+ # These kwargs will be passed to _generate_examples
172
+ gen_kwargs={
173
+ "filepath": os.path.join(
174
+ data_dir, "BC7T2-NLMChem-corpus-train.BioC.xml"
175
+ ),
176
+ "split": "train",
177
+ },
178
+ ),
179
+ datasets.SplitGenerator(
180
+ name=datasets.Split.TEST,
181
+ # These kwargs will be passed to _generate_examples
182
+ gen_kwargs={
183
+ "filepath": os.path.join(
184
+ data_dir, "BC7T2-NLMChem-corpus-test.BioC.xml"
185
+ ),
186
+ "split": "test",
187
+ },
188
+ ),
189
+ datasets.SplitGenerator(
190
+ name=datasets.Split.VALIDATION,
191
+ # These kwargs will be passed to _generate_examples
192
+ gen_kwargs={
193
+ "filepath": os.path.join(
194
+ data_dir, "BC7T2-NLMChem-corpus-dev.BioC.xml"
195
+ ),
196
+ "split": "dev",
197
+ },
198
+ ),
199
+ ]
200
+
201
+ def _get_textcls_example(self, d: bioc.BioCDocument) -> Dict:
202
+
203
+ example = {"document_id": d.id, "text": [], "labels": []}
204
+
205
+ for p in d.passages:
206
+ example["text"].append(p.text)
207
+ for a in p.annotations:
208
+ if a.infons.get("type") == "MeSH_Indexing_Chemical":
209
+ example["labels"].append(a.infons.get("identifier"))
210
+
211
+ example["text"] = " ".join(example["text"])
212
+
213
+ return example
214
+
215
+ def _get_passages_and_entities(
216
+ self, d: bioc.BioCDocument
217
+ ) -> Tuple[List[Dict], List[List[Dict]]]:
218
+
219
+ passages: List[Dict] = []
220
+ entities: List[List[Dict]] = []
221
+
222
+ text_total_length = 0
223
+
224
+ po_start = 0
225
+
226
+ for _, p in enumerate(d.passages):
227
+
228
+ eo = p.offset - text_total_length
229
+
230
+ text_total_length += len(p.text) + 1
231
+
232
+ po_end = po_start + len(p.text)
233
+
234
+ # annotation used only for document indexing
235
+ if p.text is None:
236
+ continue
237
+
238
+ dp = {
239
+ "text": p.text,
240
+ "type": p.infons.get("type"),
241
+ "offsets": [(po_start, po_end)],
242
+ "offset": p.offset, # original offset
243
+ }
244
+
245
+ po_start = po_end + 1
246
+
247
+ passages.append(dp)
248
+
249
+ pe = []
250
+
251
+ for a in p.annotations:
252
+
253
+ a_type = a.infons.get("type")
254
+
255
+ # no in-text annotation: only for document indexing
256
+ if (
257
+ self.config.schema == "bigbio_kb"
258
+ and a_type == "MeSH_Indexing_Chemical"
259
+ ):
260
+ continue
261
+
262
+ offsets, text = get_texts_and_offsets_from_bioc_ann(a)
263
+
264
+ da = {
265
+ "type": a_type,
266
+ "offsets": [(start - eo, end - eo) for (start, end) in offsets],
267
+ "text": text,
268
+ "id": a.id,
269
+ "normalized": self._get_normalized(a),
270
+ }
271
+
272
+ pe.append(da)
273
+
274
+ entities.append(pe)
275
+
276
+ return passages, entities
277
+
278
+ def _get_normalized(self, a: bioc.BioCAnnotation) -> List[Dict]:
279
+ """
280
+ Get normalization DB and ID from annotation identifiers
281
+ """
282
+
283
+ identifiers = a.infons.get("identifier")
284
+
285
+ if identifiers is not None:
286
+
287
+ identifiers = re.split(r",|;", identifiers)
288
+
289
+ identifiers = [i for i in identifiers if i != "-"]
290
+
291
+ normalized = [i.split(":") for i in identifiers]
292
+
293
+ normalized = [
294
+ {"db_name": elems[0], "db_id": elems[1]} for elems in normalized
295
+ ]
296
+
297
+ else:
298
+
299
+ normalized = [{"db_name": "-1", "db_id": "-1"}]
300
+
301
+ return normalized
302
+
303
+ def _generate_examples(
304
+ self,
305
+ filepath: str,
306
+ split: str, # method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
307
+ ) -> Iterator[Tuple[int, Dict]]:
308
+ """Yields examples as (key, example) tuples."""
309
+
310
+ reader = biocxml.BioCXMLDocumentReader(str(filepath))
311
+
312
+ if self.config.schema == "source":
313
+
314
+ for uid, doc in enumerate(reader):
315
+
316
+ passages, passages_entities = self._get_passages_and_entities(doc)
317
+
318
+ for p, pe in zip(passages, passages_entities):
319
+
320
+ p.pop("offsets") # BioC has only start for passages offsets
321
+
322
+ p["document_id"] = doc.id
323
+ p["entities"] = pe # BioC has per passage entities
324
+
325
+ yield uid, {"passages": passages}
326
+
327
+ elif self.config.schema == "bigbio_text":
328
+ uid = 0
329
+ for idx, doc in enumerate(reader):
330
+
331
+ example = self._get_textcls_example(doc)
332
+ example["id"] = uid
333
+ # global id
334
+ uid += 1
335
+
336
+ yield idx, example
337
+
338
+ elif self.config.schema == "bigbio_kb":
339
+ uid = 0
340
+ for idx, doc in enumerate(reader):
341
+
342
+ # global id
343
+ uid += 1
344
+
345
+ passages, passages_entities = self._get_passages_and_entities(doc)
346
+
347
+ # unpack per-passage entities
348
+ entities = [e for pe in passages_entities for e in pe]
349
+
350
+ for p in passages:
351
+ p.pop("offset") # drop original offset
352
+ p["text"] = (p["text"],) # text in passage is Sequence
353
+ p["id"] = uid # override BioC default id
354
+ uid += 1
355
+
356
+ for e in entities:
357
+ e["id"] = uid # override BioC default id
358
+ uid += 1
359
+
360
+ # if split == "validation" and uid == 6705:
361
+ # breakpoint()
362
+
363
+ yield idx, {
364
+ "id": uid,
365
+ "document_id": doc.id,
366
+ "passages": passages,
367
+ "entities": entities,
368
+ "events": [],
369
+ "coreferences": [],
370
+ "relations": [],
371
+ }