gabrielaltay commited on
Commit
90953a7
1 Parent(s): 23c07e4

upload hubscripts/chebi_nactem_hub.py to hub from bigbio repo

Browse files
Files changed (1) hide show
  1. chebi_nactem.py +237 -0
chebi_nactem.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import os
17
+ from pathlib import Path
18
+ from typing import Dict, List, Tuple
19
+
20
+ import datasets
21
+
22
+ from .bigbiohub import kb_features
23
+ from .bigbiohub import BigBioConfig
24
+ from .bigbiohub import Tasks
25
+
26
+ _LANGUAGES = ['English']
27
+ _PUBMED = True
28
+ _LOCAL = False
29
+ _CITATION = """\
30
+ @inproceedings{Shardlow2018,
31
+ title = {
32
+ A New Corpus to Support Text Mining for the Curation of Metabolites in the
33
+ {ChEBI} Database
34
+ },
35
+ author = {
36
+ Shardlow, M J and Nguyen, N and Owen, G and O'Donovan, C and Leach, A and
37
+ McNaught, J and Turner, S and Ananiadou, S
38
+ },
39
+ year = 2018,
40
+ month = may,
41
+ booktitle = {
42
+ Proceedings of the Eleventh International Conference on Language Resources
43
+ and Evaluation ({LREC} 2018)
44
+ },
45
+ location = {Miyazaki, Japan},
46
+ pages = {280--285},
47
+ conference = {
48
+ Eleventh International Conference on Language Resources and Evaluation
49
+ (LREC 2018)
50
+ },
51
+ language = {en}
52
+ }
53
+ """
54
+
55
+ _DATASETNAME = "chebi_nactem"
56
+ _DISPLAYNAME = "CHEBI Corpus"
57
+
58
+ _DESCRIPTION = """\
59
+ The ChEBI corpus contains 199 annotated abstracts and 100 annotated full papers.
60
+ All documents in the corpus have been annotated for named entities and relations
61
+ between these. In total, our corpus provides over 15000 named entity annotations
62
+ and over 6,000 relations between entities.
63
+ """
64
+
65
+ _HOMEPAGE = "http://www.nactem.ac.uk/chebi"
66
+
67
+ _LICENSE = 'Creative Commons Attribution 4.0 International'
68
+
69
+ _URLS = {
70
+ _DATASETNAME: "http://www.nactem.ac.uk/chebi/ChEBI.zip",
71
+ }
72
+
73
+ _SUPPORTED_TASKS = [Tasks.NAMED_ENTITY_RECOGNITION, Tasks.RELATION_EXTRACTION]
74
+
75
+ _SOURCE_VERSION = "1.0.0"
76
+
77
+ _BIGBIO_VERSION = "1.0.0"
78
+
79
+
80
+ class ChebiNactemDatasset(datasets.GeneratorBasedBuilder):
81
+ """Chemical Entities of Biological Interest (ChEBI) corpus."""
82
+
83
+ SOURCE_VERSION = datasets.Version(_SOURCE_VERSION)
84
+ BIGBIO_VERSION = datasets.Version(_BIGBIO_VERSION)
85
+
86
+ BUILDER_CONFIGS = []
87
+ for subset_id in ["abstr_ann1", "abstr_ann2", "fullpaper"]:
88
+ BUILDER_CONFIGS += [
89
+ BigBioConfig(
90
+ name=f"chebi_nactem_{subset_id}_source",
91
+ version=SOURCE_VERSION,
92
+ description="chebi_nactem source schema",
93
+ schema="source",
94
+ subset_id=f"chebi_nactem_{subset_id}",
95
+ ),
96
+ BigBioConfig(
97
+ name=f"chebi_nactem_{subset_id}_bigbio_kb",
98
+ version=BIGBIO_VERSION,
99
+ description="chebi_nactem BigBio schema",
100
+ schema="bigbio_kb",
101
+ subset_id=f"chebi_nactem_{subset_id}",
102
+ ),
103
+ ]
104
+
105
+ DEFAULT_CONFIG_NAME = "chebi_nactem_fullpaper_source"
106
+
107
+ def _info(self) -> datasets.DatasetInfo:
108
+ if self.config.schema == "source":
109
+ features = datasets.Features(
110
+ {
111
+ "document_id": datasets.Value("string"),
112
+ "text": datasets.Value("string"),
113
+ "entities": [
114
+ {
115
+ "id": datasets.Value("string"),
116
+ "type": datasets.Value("string"),
117
+ "text": datasets.Value("string"),
118
+ "offsets": datasets.Sequence([datasets.Value("int32")]),
119
+ }
120
+ ],
121
+ "relations": [
122
+ {
123
+ "id": datasets.Value("string"),
124
+ "type": datasets.Value("string"),
125
+ "arg1": datasets.Value("string"),
126
+ "arg2": datasets.Value("string"),
127
+ }
128
+ ],
129
+ }
130
+ )
131
+
132
+ elif self.config.schema == "bigbio_kb":
133
+ features = kb_features
134
+ else:
135
+ raise NotImplementedError(self.config.schema)
136
+
137
+ return datasets.DatasetInfo(
138
+ description=_DESCRIPTION,
139
+ features=features,
140
+ homepage=_HOMEPAGE,
141
+ license=str(_LICENSE),
142
+ citation=_CITATION,
143
+ )
144
+
145
+ def _split_generators(self, dl_manager) -> List[datasets.SplitGenerator]:
146
+ """Returns SplitGenerators."""
147
+ urls = _URLS[_DATASETNAME]
148
+ data_dir = dl_manager.download_and_extract(urls)
149
+
150
+ subset_paths = {
151
+ "chebi_nactem_abstr_ann1": "ChEBI/abstracts/Annotator1",
152
+ "chebi_nactem_abstr_ann2": "ChEBI/abstracts/Annotator2",
153
+ "chebi_nactem_fullpaper": "ChEBI/fullpapers",
154
+ }
155
+
156
+ subset_dir = Path(data_dir) / subset_paths[self.config.subset_id]
157
+
158
+ return [
159
+ datasets.SplitGenerator(
160
+ name=datasets.Split.TRAIN,
161
+ # Whatever you put in gen_kwargs will be passed to _generate_examples
162
+ gen_kwargs={
163
+ "data_dir": subset_dir,
164
+ },
165
+ )
166
+ ]
167
+
168
+ def _generate_examples(self, data_dir: Path) -> Tuple[int, Dict]:
169
+ """Yields examples as (key, example) tuples."""
170
+
171
+ def uid_gen():
172
+ _uid = 0
173
+ while True:
174
+ yield str(_uid)
175
+ _uid += 1
176
+
177
+ uid = iter(uid_gen())
178
+
179
+ txt_files = (f for f in os.listdir(data_dir) if f.endswith(".txt"))
180
+ for idx, file_name in enumerate(txt_files):
181
+
182
+ brat_file = data_dir / file_name
183
+ contents = parse_brat_file(brat_file)
184
+
185
+ if self.config.schema == "source":
186
+ yield idx, {
187
+ "document_id": contents["document_id"],
188
+ "text": contents["text"],
189
+ "entities": contents["text_bound_annotations"],
190
+ "relations": [
191
+ {
192
+ "id": relation["id"],
193
+ "type": relation["type"],
194
+ "arg1": relation["head"]["ref_id"],
195
+ "arg2": relation["tail"]["ref_id"],
196
+ }
197
+ for relation in contents["relations"]
198
+ ],
199
+ }
200
+
201
+ elif self.config.schema == "bigbio_kb":
202
+ yield idx, {
203
+ "id": next(uid),
204
+ "document_id": contents["document_id"],
205
+ "passages": [
206
+ {
207
+ "id": next(uid),
208
+ "type": "",
209
+ "text": [contents["text"]],
210
+ "offsets": [(0, len(contents["text"]))],
211
+ }
212
+ ],
213
+ "entities": [
214
+ {
215
+ "id": f"{idx}_{entity['id']}",
216
+ "type": entity["type"],
217
+ "offsets": entity["offsets"],
218
+ "text": entity["text"],
219
+ "normalized": [],
220
+ }
221
+ for entity in contents["text_bound_annotations"]
222
+ ],
223
+ "events": [],
224
+ "coreferences": [],
225
+ "relations": [
226
+ {
227
+ "id": f"{idx}_{relation['id']}",
228
+ "type": relation["type"],
229
+ "arg1_id": f"{idx}_{relation['head']['ref_id']}",
230
+ "arg2_id": f"{idx}_{relation['tail']['ref_id']}",
231
+ "normalized": [],
232
+ }
233
+ for relation in contents["relations"]
234
+ ],
235
+ }
236
+ else:
237
+ raise NotImplementedError(self.config.schema)