bc4chemd / bc4chemd.py
chintagunta85's picture
Update bc4chemd.py
90ee8e8
import json
from pathlib import Path
import datasets
import shutil
_CITATION = """\
@article{Krallinger2015TheCC,
title={The CHEMDNER corpus of chemicals and drugs and its annotation principles},
author={Martin Krallinger and Obdulia Rabal and Florian Leitner and Miguel Vazquez and David Salgado and Zhiyong Lu and Robert Leaman and Yanan Lu and Dong-Hong Ji and Daniel M. Lowe and Roger A. Sayle and Riza Theresa Batista-Navarro and Rafal Rak and Torsten Huber and Tim Rockt{\"a}schel and S{\'e}rgio Matos and David Campos and Buzhou Tang and Hua Xu and Tsendsuren Munkhdalai and Keun Ho Ryu and S. V. Ramanan and P. Senthil Nathan and Slavko Zitnik and Marko Bajec and Lutz Weber and Matthias Irmer and Saber Ahmad Akhondi and Jan A. Kors and Shuo Xu and Xin An and Utpal Kumar Sikdar and Asif Ekbal and Masaharu Yoshioka and Thaer M. Dieb and Miji Choi and Karin M. Verspoor and Madian Khabsa and C. Lee Giles and Hongfang Liu and K. E. Ravikumar and Andre Lamurias and Francisco M. Couto and Hong-Jie Dai and Richard Tzong-Han Tsai and C Ata and Tolga Can and Anabel Usie and Rui Alves and Isabel Segura-Bedmar and Paloma Mart{\'i}nez and Julen Oyarz{\'a}bal and Alfonso Valencia},
journal={Journal of Cheminformatics},
year={2015},
volume={7},
pages={S2 - S2}
}"""
_DESCRIPTION = """The automatic extraction of chemical information from text requires the recognition of chemical entity mentions as one of its key steps. When developing supervised named entity recognition (NER) systems, the availability of a large, manually annotated text corpus is desirable. Furthermore, large corpora permit the robust evaluation and comparison of different approaches that detect chemicals in documents. We present the CHEMDNER corpus, a collection of 10,000 PubMed abstracts that contain a total of 84,355 chemical entity mentions labeled manually by expert chemistry literature curators, following annotation guidelines specifically defined for this task. The abstracts of the CHEMDNER corpus were selected to be representative for all major chemical disciplines. Each of the chemical entity mentions was manually labeled according to its structure-associated chemical entity mention (SACEM) class: abbreviation, family, formula, identifier, multiple, systematic and trivial. The difficulty and consistency of tagging chemicals in text was measured using an agreement study between annotators, obtaining a percentage agreement of 91. For a subset of the CHEMDNER corpus (the test set of 3,000 abstracts) we provide not only the Gold Standard manual annotations, but also mentions automatically detected by the 26 teams that participated in the BioCreative IV CHEMDNER chemical mention recognition task. In addition, we release the CHEMDNER silver standard corpus of automatically extracted mentions from 17,000 randomly selected PubMed abstracts. A version of the CHEMDNER corpus in the BioC format has been generated as well. We propose a standard for required minimum information about entity annotations for the construction of domain specific corpora on chemical and drug entities. The CHEMDNER corpus and annotation guidelines are available at: http://www.biocreative.org/resources/biocreative-iv/chemdner-corpus/"""
_HOMEPAGE = "http://www.biocreative.org/resources/biocreative-iv/chemdner-corpus/"
_LICENSE = "TBD"
_URL = "https://github.com/cambridgeltl/MTL-Bioinformatics-2016/raw/master/data/BC4CHEMD/"
_URLS = {
"train": _URL + "train.tsv",
"validation": _URL + "devel.tsv",
"test": _URL + "test.tsv",
}
_VERSION = "1.0.0"
DATA_DIR = "bc4chemd_ner/"
logger = datasets.logging.get_logger(__name__)
class Bc4chemdConfig(datasets.BuilderConfig):
"""BuilderConfig for BC4CHEM_NER."""
def __init__(self, **kwargs):
"""BuilderConfig for BC4CHEM_NER.
Args:
**kwargs: keyword arguments forwarded to super.
"""
super(Bc4chemdConfig, self).__init__(**kwargs,)
class Bc4chemdNer(datasets.GeneratorBasedBuilder):
"""BC4CHEM_NER A dataset to train NLP in NER tasks to detect mentions
to chemical compounds."""
VERSION = datasets.Version("0.0.1")
BUILDER_CONFIGS = [
Bc4chemdConfig(name='bc4chemd',
version=datasets.Version(_VERSION),
description='BC4CHEMD corpus for NER'
)
]
def _info(self):
custom_names = ['O','B-GENE','I-GENE','B-CHEMICAL','I-CHEMICAL','B-DISEASE','I-DISEASE',
'B-DNA', 'I-DNA', 'B-RNA', 'I-RNA', 'B-CELL_LINE', 'I-CELL_LINE', 'B-CELL_TYPE', 'I-CELL_TYPE',
'B-PROTEIN', 'I-PROTEIN', 'B-SPECIES', 'I-SPECIES']
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=datasets.Features(
{
"id": datasets.Value("string"),
"tokens": datasets.Sequence(datasets.Value("string")),
"ner_tags": datasets.Sequence(
datasets.features.ClassLabel(
names=custom_names
)
),
}
),
supervised_keys=None,
homepage=_HOMEPAGE,
citation=_CITATION,
)
def _split_generators(self, dl_manager):
"""Returns SplitGenerators."""
downloaded_files = dl_manager.download_and_extract(_URLS)
return [
datasets.SplitGenerator(name=datasets.Split.TRAIN,
gen_kwargs={"filepath": downloaded_files["train"]}),
datasets.SplitGenerator(name=datasets.Split.VALIDATION,
gen_kwargs={"filepath": downloaded_files["validation"]}),
datasets.SplitGenerator(name=datasets.Split.TEST,
gen_kwargs={"filepath": downloaded_files["test"]}),
]
def _generate_examples(self, filepath):
print("Before the download")
logger.info("⏳ Generating examples from = %s", filepath)
with open(filepath, encoding="utf-8") as f:
guid = 0
tokens = []
ner_tags = []
for line in f:
if line == "" or line == "\n":
if tokens:
yield guid, {
"id": str(guid),
"tokens": tokens,
"ner_tags": ner_tags,
}
guid += 1
tokens = []
ner_tags = []
else:
# tokens are tab separated
splits = line.split("\t")
tokens.append(splits[0])
if(splits[1].rstrip()=="B-Chemical"):
ner_tags.append("B-CHEMICAL")
if(splits[1].rstrip()=="I-Chemical"):
ner_tags.append("I-CHEMICAL")
else:
ner_tags.append("O")
# last example
yield guid, {
"id": str(guid),
"tokens": tokens,
"ner_tags": ner_tags,
}