Datasets:

Languages:
English
License:
gabrielaltay commited on
Commit
6652454
1 Parent(s): e3b1d6d

upload hubscripts/anat_em_hub.py to hub from bigbio repo

Browse files
Files changed (1) hide show
  1. anat_em.py +227 -0
anat_em.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 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
+ The extended Anatomical Entity Mention corpus (AnatEM) consists of 1212 documents
17
+ (approx. 250,000 words) manually annotated to identify over 13,000 mentions of anatomical
18
+ entities. Each annotation is assigned one of 12 granularity-based types such as Cellular
19
+ component, Tissue and Organ, defined with reference to the Common Anatomy Reference Ontology
20
+ (see https://bioportal.bioontology.org/ontologies/CARO).
21
+ """
22
+ from pathlib import Path
23
+ from typing import Dict, Iterator, Tuple
24
+
25
+ import datasets
26
+
27
+ from .bigbiohub import kb_features
28
+ from .bigbiohub import BigBioConfig
29
+ from .bigbiohub import Tasks
30
+
31
+ _LANGUAGES = ['English']
32
+ _PUBMED = True
33
+ _LOCAL = False
34
+ _CITATION = """\
35
+ @article{pyysalo2014anatomical,
36
+ title={Anatomical entity mention recognition at literature scale},
37
+ author={Pyysalo, Sampo and Ananiadou, Sophia},
38
+ journal={Bioinformatics},
39
+ volume={30},
40
+ number={6},
41
+ pages={868--875},
42
+ year={2014},
43
+ publisher={Oxford University Press}
44
+ }
45
+ """
46
+
47
+ _DATASETNAME = "anat_em"
48
+ _DISPLAYNAME = "AnatEM"
49
+
50
+
51
+ _DESCRIPTION = """\
52
+ The extended Anatomical Entity Mention corpus (AnatEM) consists of 1212 \
53
+ documents (approx. 250,000 words) manually annotated to identify over 13,000 \
54
+ mentions of anatomical entities. Each annotation is assigned one of 12 \
55
+ granularity-based types such as Cellular component, Tissue and Organ, defined \
56
+ with reference to the Common Anatomy Reference Ontology.
57
+ """
58
+
59
+ _HOMEPAGE = "http://nactem.ac.uk/anatomytagger/#AnatEM"
60
+
61
+ _LICENSE = 'Creative Commons Attribution Share Alike 3.0 Unported'
62
+
63
+ _URLS = {_DATASETNAME: "http://nactem.ac.uk/anatomytagger/AnatEM-1.0.2.tar.gz"}
64
+
65
+ _SUPPORTED_TASKS = [Tasks.NAMED_ENTITY_RECOGNITION]
66
+
67
+ _SOURCE_VERSION = "1.0.2"
68
+ _BIGBIO_VERSION = "1.0.0"
69
+
70
+
71
+ class AnatEMDataset(datasets.GeneratorBasedBuilder):
72
+ """The extended Anatomical Entity Mention corpus (AnatEM)"""
73
+
74
+ SOURCE_VERSION = datasets.Version(_SOURCE_VERSION)
75
+ BIGBIO_VERSION = datasets.Version(_BIGBIO_VERSION)
76
+
77
+ BUILDER_CONFIGS = [
78
+ BigBioConfig(
79
+ name="anat_em_source",
80
+ version=SOURCE_VERSION,
81
+ description="AnatEM source schema",
82
+ schema="source",
83
+ subset_id="anat_em",
84
+ ),
85
+ BigBioConfig(
86
+ name="anat_em_bigbio_kb",
87
+ version=BIGBIO_VERSION,
88
+ description="AnatEM BigBio schema",
89
+ schema="bigbio_kb",
90
+ subset_id="anat_em",
91
+ ),
92
+ ]
93
+
94
+ DEFAULT_CONFIG_NAME = "anat_em_source"
95
+
96
+ def _info(self):
97
+ if self.config.schema == "source":
98
+ features = datasets.Features(
99
+ {
100
+ "document_id": datasets.Value("string"),
101
+ "document_type": datasets.Value("string"), # Either PMC or PM
102
+ "text": datasets.Value("string"),
103
+ "text_type": datasets.Value(
104
+ "string"
105
+ ), # Either abstract (for PM) or sec / caption (for PMC)
106
+ "entities": [
107
+ {
108
+ "entity_id": datasets.Value("string"),
109
+ "type": datasets.Value("string"),
110
+ "offsets": datasets.Sequence([datasets.Value("int32")]),
111
+ "text": datasets.Sequence(datasets.Value("string")),
112
+ }
113
+ ],
114
+ }
115
+ )
116
+
117
+ elif self.config.schema == "bigbio_kb":
118
+ features = kb_features
119
+
120
+ return datasets.DatasetInfo(
121
+ description=_DESCRIPTION,
122
+ features=features,
123
+ homepage=_HOMEPAGE,
124
+ license=str(_LICENSE),
125
+ citation=_CITATION,
126
+ )
127
+
128
+ def _split_generators(self, dl_manager):
129
+ urls = _URLS[_DATASETNAME]
130
+ data_dir = Path(dl_manager.download_and_extract(urls))
131
+
132
+ standoff_dir = data_dir / "AnatEM-1.0.2" / "standoff"
133
+
134
+ return [
135
+ datasets.SplitGenerator(
136
+ name=datasets.Split.TRAIN,
137
+ gen_kwargs={"split_dir": standoff_dir / "train"},
138
+ ),
139
+ datasets.SplitGenerator(
140
+ name=datasets.Split.TEST,
141
+ gen_kwargs={"split_dir": standoff_dir / "test"},
142
+ ),
143
+ datasets.SplitGenerator(
144
+ name=datasets.Split.VALIDATION,
145
+ gen_kwargs={"split_dir": standoff_dir / "devel"},
146
+ ),
147
+ ]
148
+
149
+ def _generate_examples(self, split_dir: Path) -> Iterator[Tuple[str, Dict]]:
150
+ if self.config.name == "anat_em_source":
151
+ for file in split_dir.iterdir():
152
+ # Ignore hidden files and annotation files - we just consider the brat text files
153
+ if file.name.startswith("._") or file.name.endswith(".ann"):
154
+ continue
155
+
156
+ # Read brat annotations for the given text file and convert example to the source format
157
+ brat_example = parsing.parse_brat_file(file)
158
+ source_example = self._to_source_example(file, brat_example)
159
+
160
+ yield source_example["document_id"], source_example
161
+
162
+ elif self.config.name == "anat_em_bigbio_kb":
163
+ for file in split_dir.iterdir():
164
+ # Ignore hidden files and annotation files - we just consider the brat text files
165
+ if file.name.startswith("._") or file.name.endswith(".ann"):
166
+ continue
167
+
168
+ # Read brat annotations for the given text file and convert example to the BigBio-KB format
169
+ brat_example = parsing.parse_brat_file(file)
170
+ kb_example = parsing.brat_parse_to_bigbio_kb(brat_example)
171
+ kb_example["id"] = kb_example["document_id"]
172
+
173
+ # Fix text type annotation for the converted example
174
+ _, text_type = self.get_document_type_and_text_type(file)
175
+ kb_example["passages"][0]["type"] = text_type
176
+
177
+ yield kb_example["id"], kb_example
178
+
179
+ def _to_source_example(self, input_file: Path, brat_example: Dict) -> Dict:
180
+ """
181
+ Converts an example extracted using the default brat parsing logic to the source format
182
+ of the given corpus.
183
+ """
184
+ document_type, text_type = self.get_document_type_and_text_type(input_file)
185
+
186
+ source_example = {
187
+ "document_id": brat_example["document_id"],
188
+ "document_type": document_type,
189
+ "text": brat_example["text"],
190
+ "text_type": text_type,
191
+ }
192
+
193
+ id_prefix = brat_example["document_id"] + "_"
194
+
195
+ source_example["entities"] = []
196
+ for entity_annotation in brat_example["text_bound_annotations"]:
197
+ entity_ann = entity_annotation.copy()
198
+
199
+ entity_ann["entity_id"] = id_prefix + entity_ann["id"]
200
+ entity_ann.pop("id")
201
+
202
+ source_example["entities"].append(entity_ann)
203
+
204
+ return source_example
205
+
206
+ def get_document_type_and_text_type(self, input_file: Path) -> Tuple[str, str]:
207
+ """
208
+ Extracts the document type (PubMed(PM) or PubMedCentral (PMC)) and the respective
209
+ text type (abstract for PM and sec or caption for (PMC) from the name of the given
210
+ file, e.g.:
211
+
212
+ PMID-9778569.txt -> ("PM", "abstract")
213
+
214
+ PMC-1274342-sec-02.txt -> ("PMC", "sec")
215
+
216
+ PMC-1592597-caption-02.ann -> ("PMC", "caption")
217
+
218
+ """
219
+ name_parts = str(input_file.stem).split("-")
220
+
221
+ if name_parts[0] == "PMID":
222
+ return "PM", "abstract"
223
+
224
+ elif name_parts[0] == "PMC":
225
+ return "PMC", name_parts[2]
226
+ else:
227
+ raise AssertionError(f"Unexpected file prefix {name_parts[0]}")