File size: 8,460 Bytes
90953a7 96c00f9 90953a7 96c00f9 90953a7 804c05a 90953a7 96c00f9 90953a7 96c00f9 90953a7 96c00f9 90953a7 96c00f9 90953a7 96c00f9 90953a7 96c00f9 90953a7 96c00f9 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 |
# coding=utf-8
# Copyright 2022 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os.path
from itertools import count
from pathlib import Path
from typing import Dict, Iterable, List, Tuple
import datasets
from .bigbiohub import kb_features
from .bigbiohub import BigBioConfig
from .bigbiohub import Tasks
from .bigbiohub import parse_brat_file
_LANGUAGES = ["English"]
_PUBMED = True
_LOCAL = False
_CITATION = """\
@inproceedings{Shardlow2018,
title = {
A New Corpus to Support Text Mining for the Curation of Metabolites in the
{ChEBI} Database
},
author = {
Shardlow, M J and Nguyen, N and Owen, G and O'Donovan, C and Leach, A and
McNaught, J and Turner, S and Ananiadou, S
},
year = 2018,
month = may,
booktitle = {
Proceedings of the Eleventh International Conference on Language Resources
and Evaluation ({LREC} 2018)
},
location = {Miyazaki, Japan},
pages = {280--285},
conference = {
Eleventh International Conference on Language Resources and Evaluation
(LREC 2018)
},
language = {en}
}
"""
_DATASETNAME = "chebi_nactem"
_DISPLAYNAME = "CHEBI Corpus"
_DESCRIPTION = """\
The ChEBI corpus contains 199 annotated abstracts and 100 annotated full papers.
All documents in the corpus have been annotated for named entities and relations
between these. In total, our corpus provides over 15000 named entity annotations
and over 6,000 relations between entities.
"""
_HOMEPAGE = "http://www.nactem.ac.uk/chebi"
_LICENSE = "Creative Commons Attribution 4.0 International"
_URLS = {
_DATASETNAME: "http://www.nactem.ac.uk/chebi/ChEBI.zip",
}
_SUPPORTED_TASKS = [Tasks.NAMED_ENTITY_RECOGNITION, Tasks.RELATION_EXTRACTION]
_SOURCE_VERSION = "1.0.0"
_BIGBIO_VERSION = "1.0.0"
class ChebiNactemDatasset(datasets.GeneratorBasedBuilder):
"""Chemical Entities of Biological Interest (ChEBI) corpus."""
SOURCE_VERSION = datasets.Version(_SOURCE_VERSION)
BIGBIO_VERSION = datasets.Version(_BIGBIO_VERSION)
BUILDER_CONFIGS = []
for subset_id in ["abstr_ann1", "abstr_ann2", "fullpaper"]:
BUILDER_CONFIGS += [
BigBioConfig(
name=f"chebi_nactem_{subset_id}_source",
version=SOURCE_VERSION,
description="chebi_nactem source schema",
schema="source",
subset_id=f"chebi_nactem_{subset_id}",
),
BigBioConfig(
name=f"chebi_nactem_{subset_id}_bigbio_kb",
version=BIGBIO_VERSION,
description="chebi_nactem BigBio schema",
schema="bigbio_kb",
subset_id=f"chebi_nactem_{subset_id}",
),
]
DEFAULT_CONFIG_NAME = "chebi_nactem_fullpaper_source"
def _info(self) -> datasets.DatasetInfo:
if self.config.schema == "source":
features = datasets.Features(
{
"document_id": datasets.Value("string"),
"text": datasets.Value("string"),
"entities": [
{
"id": datasets.Value("string"),
"type": datasets.Value("string"),
"text": datasets.Value("string"),
"offsets": datasets.Sequence([datasets.Value("int32")]),
}
],
"relations": [
{
"id": datasets.Value("string"),
"type": datasets.Value("string"),
"arg1": datasets.Value("string"),
"arg2": datasets.Value("string"),
}
],
}
)
elif self.config.schema == "bigbio_kb":
features = kb_features
else:
raise NotImplementedError(self.config.schema)
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=features,
homepage=_HOMEPAGE,
license=str(_LICENSE),
citation=_CITATION,
)
def _split_generators(self, dl_manager) -> List[datasets.SplitGenerator]:
"""Returns SplitGenerators."""
urls = _URLS[_DATASETNAME]
data_dir = dl_manager.download_and_extract(urls)
subset_paths = {
"chebi_nactem_abstr_ann1": os.path.join("ChEBI", "abstracts", "Annotator1"),
"chebi_nactem_abstr_ann2": os.path.join("ChEBI", "abstracts", "Annotator2"),
"chebi_nactem_fullpaper": os.path.join("ChEBI", "fullpapers"),
}
subset_dir = os.path.join(data_dir, subset_paths[self.config.subset_id])
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={"file_paths": dl_manager.iter_files(subset_dir)},
)
]
def _generate_examples(self, file_paths: Iterable[str]) -> Tuple[int, Dict]:
"""Yields examples as (key, example) tuples."""
uid = count(0)
for idx, file_path in enumerate(file_paths):
if os.path.basename(file_path).endswith(".txt"):
contents = parse_brat_file(
Path(file_path), annotation_file_suffixes=[".ann"]
)
if self.config.schema == "source":
yield idx, {
"document_id": contents["document_id"],
"text": contents["text"],
"entities": contents["text_bound_annotations"],
"relations": [
{
"id": relation["id"],
"type": relation["type"],
"arg1": relation["head"]["ref_id"],
"arg2": relation["tail"]["ref_id"],
}
for relation in contents["relations"]
],
}
elif self.config.schema == "bigbio_kb":
yield idx, {
"id": next(uid),
"document_id": contents["document_id"],
"passages": [
{
"id": next(uid),
"type": "",
"text": [contents["text"]],
"offsets": [(0, len(contents["text"]))],
}
],
"entities": [
{
"id": f"{idx}_{entity['id']}",
"type": entity["type"],
"offsets": entity["offsets"],
"text": entity["text"],
"normalized": [],
}
for entity in contents["text_bound_annotations"]
],
"events": [],
"coreferences": [],
"relations": [
{
"id": f"{idx}_{relation['id']}",
"type": relation["type"],
"arg1_id": f"{idx}_{relation['head']['ref_id']}",
"arg2_id": f"{idx}_{relation['tail']['ref_id']}",
"normalized": [],
}
for relation in contents["relations"]
],
}
else:
raise NotImplementedError(self.config.schema)
|