File size: 11,888 Bytes
970237b |
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 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 |
# 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.
"""
The compound-protein relationship (CPI) dataset consists of 2,613 sentences from abstracts containing
annotations of proteins, small molecules, and their relationships. For further information see:
https://pubmed.ncbi.nlm.nih.gov/32126064/ and https://github.com/KerstenDoering/CPI-Pipeline
"""
import xml.etree.ElementTree as ET
from pathlib import Path
from typing import Dict, Iterator, Tuple
import datasets
from .bigbiohub import kb_features
from .bigbiohub import BigBioConfig
from .bigbiohub import Tasks
_LANGUAGES = ['English']
_PUBMED = True
_LOCAL = False
_CITATION = """\
@article{doring2020automated,
title={Automated recognition of functional compound-protein relationships in literature},
author={D{\"o}ring, Kersten and Qaseem, Ammar and Becer, Michael and Li, Jianyu and Mishra, Pankaj and Gao, Mingjie and Kirchner, Pascal and Sauter, Florian and Telukunta, Kiran K and Moumbock, Aur{\'e}lien FA and others},
journal={Plos one},
volume={15},
number={3},
pages={e0220925},
year={2020},
publisher={Public Library of Science San Francisco, CA USA}
}
"""
_DATASETNAME = "cpi"
_DISPLAYNAME = "CPI"
_DESCRIPTION = """\
The compound-protein relationship (CPI) dataset consists of 2,613 sentences from abstracts containing \
annotations of proteins, small molecules, and their relationships
"""
_HOMEPAGE = "https://github.com/KerstenDoering/CPI-Pipeline"
_LICENSE = 'ISC License'
_URLS = {
"CPI": "https://github.com/KerstenDoering/CPI-Pipeline/raw/master/data_sets/xml/CPI-DS.xml",
"CPI_IV": "https://github.com/KerstenDoering/CPI-Pipeline/raw/master/data_sets/xml/CPI-DS_IV.xml",
"CPI_NIV": "https://github.com/KerstenDoering/CPI-Pipeline/raw/master/data_sets/xml/CPI-DS_IV.xml",
}
_SUPPORTED_TASKS = [Tasks.NAMED_ENTITY_RECOGNITION, Tasks.NAMED_ENTITY_DISAMBIGUATION, Tasks.RELATION_EXTRACTION]
_SOURCE_VERSION = "1.0.2"
_BIGBIO_VERSION = "1.0.0"
class CpiDataset(datasets.GeneratorBasedBuilder):
"""The compound-protein relationship (CPI) dataset"""
ENTITY_TYPE_TO_DB_NAME = {"compound": "PubChem", "protein": "UniProt"}
SOURCE_VERSION = datasets.Version(_SOURCE_VERSION)
BIGBIO_VERSION = datasets.Version(_BIGBIO_VERSION)
BUILDER_CONFIGS = [
BigBioConfig(
name="cpi_source",
version=SOURCE_VERSION,
description="CPI source schema",
schema="source",
subset_id="cpi",
),
BigBioConfig(
name="cpi_iv_source",
version=SOURCE_VERSION,
description="CPI source schema - subset with interaction verbs",
schema="source",
subset_id="cpi_iv",
),
BigBioConfig(
name="cpi_niv_source",
version=SOURCE_VERSION,
description="CPI source schema - subset without interaction verbs",
schema="source",
subset_id="cpi_niv",
),
BigBioConfig(
name="cpi_bigbio_kb",
version=BIGBIO_VERSION,
description="CPI BigBio schema",
schema="bigbio_kb",
subset_id="cpi",
),
]
DEFAULT_CONFIG_NAME = "cpi_source"
def _info(self):
if self.config.schema == "source":
features = datasets.Features(
{
"document_id": datasets.Value("string"),
"document_orig_id": datasets.Value("string"),
"sentences": [
{
"sentence_id": datasets.Value("string"),
"sentence_orig_id": datasets.Value("string"),
"text": datasets.Value("string"),
"entities": [
{
"entity_id": datasets.Value("string"),
"entity_orig_id": datasets.Sequence(datasets.Value("string")),
"type": datasets.Value("string"),
"offset": datasets.Sequence(datasets.Value("int32")),
"text": datasets.Value("string"),
}
],
"pairs": [
{
"pair_id": datasets.Value("string"),
"e1": datasets.Value("string"),
"e2": datasets.Value("string"),
"interaction": datasets.Value("bool"),
}
],
}
],
}
)
elif self.config.schema == "bigbio_kb":
features = kb_features
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=features,
homepage=_HOMEPAGE,
license=str(_LICENSE),
citation=_CITATION,
)
def _split_generators(self, dl_manager):
# Distinguish based on the subset id (cpi, cpi_iv, cpi_niv) which file to load
subset_url = _URLS[self.config.subset_id.upper()]
subset_file = dl_manager.download_and_extract(subset_url)
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={"subset_file": subset_file},
)
]
def _generate_examples(self, subset_file: Path) -> Iterator[Tuple[str, Dict]]:
if self.config.schema == "source":
for doc_id, document in self._read_source_examples(subset_file):
yield doc_id, document
elif self.config.name == "cpi_bigbio_kb":
# Note: The sentences in a CPI document does not (necessarily) occur consecutive in
# the original publication. Nevertheless, in this implementation we capture all sentences
# of a document in one kb-schema document to explicitly model documents.
# Transform each source-schema document to kb-schema document
for doc_id, source_document in self._read_source_examples(subset_file):
sentence_offset = 0
passages = []
entities = []
relations = []
# Transform all sentences to kb-schema sentences
for source_sentence in source_document["sentences"]:
text = source_sentence["text"]
passages.append(
{
"id": source_sentence["sentence_id"],
"text": [text],
"offsets": [[sentence_offset + 0, sentence_offset + len(text)]],
"type": "",
}
)
# Transform source-schema entities to kb-schema entities
for source_entity in source_sentence["entities"]:
db_name = self.ENTITY_TYPE_TO_DB_NAME[source_entity["type"]]
entity_offset = source_entity["offset"]
entity_offset = [sentence_offset + entity_offset[0], sentence_offset + entity_offset[1]]
entities.append(
{
"id": source_entity["entity_id"],
"type": source_entity["type"],
"text": [source_entity["text"]],
"offsets": [entity_offset],
"normalized": [
{"db_name": db_name, "db_id": db_id} for db_id in source_entity["entity_orig_id"]
],
}
)
# Transform source-schema pairs to kb-schema relations
for source_pair in source_sentence["pairs"]:
# Ignore pairs that are annotated to be not in a relationship!
if not source_pair["interaction"]:
continue
relations.append(
{
"id": source_pair["pair_id"],
"type": "compound-protein-interaction",
"arg1_id": source_pair["e1"],
"arg2_id": source_pair["e2"],
"normalized": [],
}
)
sentence_offset += len(text) + 1
kb_document = {
"id": source_document["document_id"],
"document_id": source_document["document_orig_id"],
"passages": passages,
"entities": entities,
"relations": relations,
"events": [],
"coreferences": [],
}
yield source_document["document_id"], kb_document
def _read_source_examples(self, input_file: Path) -> Iterator[Tuple[str, Dict]]:
"""
Reads all instances of the given input file and parses them into the source format.
"""
root = ET.parse(input_file)
for document in root.iter("document"):
sentences = []
for sentence in document.iter("sentence"):
entities = []
for entity in sentence.iter("entity"):
char_offsets = entity.attrib["charOffset"].split("-")
start, end = int(char_offsets[0]), int(char_offsets[1])
entities.append(
{
"entity_id": entity.attrib["id"],
"entity_orig_id": entity.attrib["origId"].split(","),
"type": entity.attrib["type"],
"text": entity.attrib["text"],
"offset": [start, end],
}
)
pairs = []
for pair in sentence.iter("pair"):
pairs.append(
{
"pair_id": pair.attrib["id"],
"e1": pair.attrib["e1"],
"e2": pair.attrib["e2"],
"interaction": pair.attrib["interaction"].lower() == "true",
}
)
sentences.append(
{
"sentence_id": sentence.attrib["id"],
"sentence_orig_id": sentence.attrib["origId"],
"text": sentence.attrib["text"],
"entities": entities,
"pairs": pairs,
}
)
document_dict = {
"document_id": document.attrib["id"],
"document_orig_id": document.attrib["origId"],
"sentences": sentences,
}
yield document.attrib["id"], document_dict
|