File size: 14,579 Bytes
2ac7e4a |
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 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 |
# 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 itertools as it
from typing import Dict, Generator, List, Tuple
import datasets
from .bigbiohub import BigBioConfig, Tasks, kb_features
_LANGUAGES = ["English"]
_PUBMED = True
_LOCAL = False
_CITATION = """\
@article{cho2022plant,
author = {Cho, Hyejin and Kim, Baeksoo and Choi, Wonjun and Lee, Doheon and Lee, Hyunju},
title = {Plant phenotype relationship corpus for biomedical relationships between plants and phenotypes},
journal = {Scientific Data},
volume = {9},
year = {2022},
publisher = {Nature Publishing Group},
doi = {https://doi.org/10.1038/s41597-022-01350-1},
}
"""
_DATASETNAME = "ppr"
_DISPLAYNAME = "Plant-Phenotype-Relations"
_DESCRIPTION = """\
The Plant-Phenotype corpus is a text corpus with human annotations of plants, phenotypes, and their relations on a \
corpus in 600 PubMed abstracts.
"""
_HOMEPAGE = "https://github.com/DMCB-GIST/PPRcorpus"
_LICENSE = "UNKNOWN"
_URLS = {
_DATASETNAME: [
"https://raw.githubusercontent.com/davidkartchner/PPRcorpus/main/corpus/PPR_train_corpus.txt",
"https://raw.githubusercontent.com/davidkartchner/PPRcorpus/main/corpus/PPR_dev_corpus.txt",
"https://raw.githubusercontent.com/davidkartchner/PPRcorpus/main/corpus/PPR_test_corpus.txt",
],
}
_SUPPORTED_TASKS = [Tasks.NAMED_ENTITY_RECOGNITION, Tasks.RELATION_EXTRACTION]
_SOURCE_VERSION = "1.0.0"
_BIGBIO_VERSION = "1.0.0"
class PlantPhenotypeDataset(datasets.GeneratorBasedBuilder):
"""Plant-Phenotype is dataset for NER and RE of plants and their induced phenotypes"""
SOURCE_VERSION = datasets.Version(_SOURCE_VERSION)
BIGBIO_VERSION = datasets.Version(_BIGBIO_VERSION)
BUILDER_CONFIGS = [
BigBioConfig(
name="ppr_source",
version=SOURCE_VERSION,
description="Plant Phenotype Relations source schema",
schema="source",
subset_id="plant_phenotype",
),
BigBioConfig(
name="ppr_bigbio_kb",
version=BIGBIO_VERSION,
description="Plant Phenotype Relations BigBio schema",
schema="bigbio_kb",
subset_id="plant_phenotype",
),
]
DEFAULT_CONFIG_NAME = "ppr_source"
def _info(self) -> datasets.DatasetInfo:
if self.config.schema == "source":
features = datasets.Features(
{
"passage_id": datasets.Value("string"),
"pmid": datasets.Value("string"),
"section": datasets.Value("int32"),
"text": datasets.Value("string"),
"entities": [
{
"offsets": datasets.Sequence(datasets.Value("int32")),
"text": datasets.Value("string"),
"type": datasets.Value("string"),
}
],
"relations": [
{
"relation_type": datasets.Value("string"),
"entity1_offsets": datasets.Sequence(datasets.Value("int32")),
"entity1_text": datasets.Value("string"),
"entity1_type": datasets.Value("string"),
"entity2_offsets": datasets.Sequence(datasets.Value("int32")),
"entity2_text": datasets.Value("string"),
"entity2_type": datasets.Value("string"),
}
],
}
)
elif self.config.schema == "bigbio_kb":
features = kb_features
else:
raise NotImplementedError(f"Schema {self.config.schema} not supported")
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=features,
homepage=_HOMEPAGE,
license=_LICENSE,
citation=_CITATION,
)
def _split_generators(self, dl_manager) -> List[datasets.SplitGenerator]:
"""Returns SplitGenerators."""
urls = _URLS[_DATASETNAME]
train, dev, test = dl_manager.download_and_extract(urls)
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={
"filepath": train,
},
),
datasets.SplitGenerator(
name=datasets.Split.TEST,
gen_kwargs={
"filepath": test,
},
),
datasets.SplitGenerator(
name=datasets.Split.VALIDATION,
gen_kwargs={
"filepath": dev,
},
),
]
def _generate_examples(
self,
filepath,
) -> Tuple[int, Dict]:
"""Yields examples as (key, example) tuples."""
with open(filepath, "r") as f:
chunks = f.read().strip().split("\n\n")
if self.config.schema == "source":
for id_, doc in self._generate_source_examples(chunks):
yield id_, doc
elif self.config.schema == "bigbio_kb":
for id_, doc in self._generate_bigbio_kb_examples(chunks):
yield id_, doc
def _generate_whole_documents(self, annotation_chunks: List[str]) -> Generator[Dict, None, None]:
"""Aggregate individual sentence annotations into whole abstracts.
Args:
annotation_chunks (List[str]): List of annotation chunks, i.e., a sentence with its annotations.
For example:
10072339_4 OBJECTIVE: A patient with possible airborne facial dermatitis to potato is described.
10072339 44 61 facial dermatitis Negative_phenotype
10072339 65 71 potato Plant
Returns:
Generator producing a dictionary containing the pmid of an article and all document chunks.
"""
prev_pmid = None
pmid = ""
doc_chunks = []
for chunk in annotation_chunks:
lines = chunk.split("\n")
# The first line is the sentence (format: <pmid>_<num>\t<sentence-text>)
passage_info, passage_text = lines[0].split("\t")
# Then annotations in Pubtator format
annotations = [line.split("\t") for line in lines[1:]]
# Get info on passage
pmid, section = passage_info.split("_")
if prev_pmid is None:
prev_pmid = pmid
elif prev_pmid != pmid:
yield {"pmid": prev_pmid, "doc_chunks": doc_chunks}
# Reset everything for next PMID
prev_pmid = pmid
doc_chunks = []
doc_chunks.append(
{
"passage": passage_text,
"annotations": annotations,
"sentence_id": passage_info,
}
)
# Take care of last document
yield {"pmid": pmid, "doc_chunks": doc_chunks}
def _generate_source_examples(self, annotation_chunks: List[str]) -> Generator[Tuple[str, Dict], None, None]:
"""Generate examples in format of source schema
Args:
annotation_chunks (List[str]): List of annotation chunks.
Returns:
Generator of instance tuples (<key>, <instance-dict>)
"""
for chunk in annotation_chunks:
lines = chunk.split("\n")
passage_id, passage_text = lines[0].split("\t")
annotations = [line.split("\t") for line in lines[1:]]
# Get info on passage
pmid, section = passage_id.split("_")
section = int(section)
# Grab entities and relations
entities = []
relations = []
for annotation in annotations:
if len(annotation) == 5:
# It's an entity annotation
entities.append(
{
"offsets": (int(annotation[1]), int(annotation[2])),
"text": annotation[3],
"type": annotation[4],
}
)
elif len(annotation) == 10:
# Relation annotation
relations.append(
{
"relation_type": annotation[1],
"entity1_offsets": (int(annotation[2]), int(annotation[3])),
"entity1_text": annotation[4],
"entity1_type": annotation[5],
"entity2_offsets": (int(annotation[6]), int(annotation[7])),
"entity2_text": annotation[8],
"entity2_type": annotation[9],
}
)
else:
# This is a special case that occurs for a single data point
relations.append(
{
"relation_type": annotation[1],
"entity1_offsets": (int(annotation[2]), int(annotation[3])),
"entity1_text": annotation[4],
"entity1_type": annotation[5],
"entity2_offsets": (int(annotation[8]), int(annotation[9])),
"entity2_text": annotation[10],
"entity2_type": annotation[11],
}
)
# Consolidate into document
document = {
"passage_id": passage_id,
"pmid": pmid,
"section": section,
"text": passage_text,
"entities": entities,
"relations": relations,
}
yield passage_id, document
def _generate_bigbio_kb_examples(self, annotation_chunks: List[str]):
"""Generator for training examples in bigbio_kb schema format.
Args:
annotation_chunks (List[str]): List of annotation chunks.
Returns:
Generator of instance tuples (<key>, <instance-dict>)
"""
uid = it.count(1)
for document in self._generate_whole_documents(annotation_chunks):
pmid = document["pmid"]
offset_delta = 0
id_ = str(next(uid))
passages = []
entities = []
relations = []
# Iterate through each section of the article
for text_section in document["doc_chunks"]:
# Extract passages
passage = text_section["passage"]
passages.append(
{
"id": str(next(uid)),
"text": [passage],
"type": "sentence",
"offsets": [(offset_delta, offset_delta + len(passage))],
}
)
# Extract entities
entities_sublist = []
for annotation in text_section["annotations"]:
if len(annotation) == 5:
entities_sublist.append(
{
"id": str(next(uid)),
"type": annotation[4],
"text": [annotation[3]],
"offsets": [(int(annotation[1]) + offset_delta, int(annotation[2]) + offset_delta)],
"normalized": [],
}
)
# Create mapping of offsets to entity_id
ent2id = {tuple(x["offsets"]): x["id"] for x in entities_sublist}
entities.extend(entities_sublist)
# Extract relations
for annotation in text_section["annotations"]:
if len(annotation) == 10:
e1_offsets = [(int(annotation[2]) + offset_delta, int(annotation[3]) + offset_delta)]
e2_offsets = [(int(annotation[6]) + offset_delta, int(annotation[7]) + offset_delta)]
relations.append(
{
"id": str(next(uid)),
"type": annotation[1],
"arg1_id": ent2id[tuple(e1_offsets)],
"arg2_id": ent2id[tuple(e2_offsets)],
"normalized": [],
}
)
# Special case for a single annotation
elif len(annotation) > 10:
e1_offsets = [(int(annotation[2]) + offset_delta, int(annotation[3]) + offset_delta)]
e2_offsets = [(int(annotation[8]) + offset_delta, int(annotation[9]) + offset_delta)]
relations.append(
{
"id": str(next(uid)),
"type": annotation[1],
"arg1_id": ent2id[tuple(e1_offsets)],
"arg2_id": ent2id[tuple(e2_offsets)],
"normalized": [],
}
)
offset_delta += len(passage) + 1
doc = {
"id": id_,
"document_id": pmid,
"passages": passages,
"entities": entities,
"relations": relations,
"events": [],
"coreferences": [],
}
yield id_, doc
|