"""Loading script for the BLURB (Biomedical Language Understanding and Reasoning Benchmark) benchmark for biomedical NLP.""" import json from pathlib import Path import datasets import shutil import pandas as pd _LICENSE = "TBD" _VERSION = "1.0.0" DATA_DIR = "blurb/" CITATIONS = { "blurb": """\ @article{2022, title={Domain-Specific Language Model Pretraining for Biomedical Natural Language Processing}, volume={3}, ISSN={2637-8051}, url={http://dx.doi.org/10.1145/3458754}, DOI={10.1145/3458754}, number={1}, journal={ACM Transactions on Computing for Healthcare}, publisher={Association for Computing Machinery (ACM)}, author={Gu, Yu and Tinn, Robert and Cheng, Hao and Lucas, Michael and Usuyama, Naoto and Liu, Xiaodong and Naumann, Tristan and Gao, Jianfeng and Poon, Hoifung}, year={2022}, month={Jan}, pages={1–23} } """, "BC5CDR-chem-IOB": """@article{article, author = {Li, Jiao and Sun, Yueping and Johnson, Robin and Sciaky, Daniela and Wei, Chih-Hsuan and Leaman, Robert and Davis, Allan Peter and Mattingly, Carolyn and Wiegers, Thomas and lu, Zhiyong}, year = {2016}, month = {05}, pages = {baw068}, title = {BioCreative V CDR task corpus: a resource for chemical disease relation extraction}, volume = {2016}, journal = {Database}, doi = {10.1093/database/baw068} }""", "BC5CDR-disease-IOB":"""@article{article, author = {Li, Jiao and Sun, Yueping and Johnson, Robin and Sciaky, Daniela and Wei, Chih-Hsuan and Leaman, Robert and Davis, Allan Peter and Mattingly, Carolyn and Wiegers, Thomas and lu, Zhiyong}, year = {2016}, month = {05}, pages = {baw068}, title = {BioCreative V CDR task corpus: a resource for chemical disease relation extraction}, volume = {2016}, journal = {Database}, doi = {10.1093/database/baw068} }""", "BC2GM-IOB":"""@article{article, author = {Smith, Larry and Tanabe, Lorraine and Ando, Rie and Kuo, Cheng-Ju and Chung, I-Fang and Hsu, Chun-Nan and Lin, Yu-Shi and Klinger, Roman and Friedrich, Christoph and Ganchev, Kuzman and Torii, Manabu and Liu, Hongfang and Haddow, Barry and Struble, Craig and Povinelli, Richard and Vlachos, Andreas and Baumgartner Jr, William and Hunter, Lawrence and Carpenter, Bob and Wilbur, W.}, year = {2008}, month = {09}, pages = {S2}, title = {Overview of BioCreative II gene mention recognition}, volume = {9 Suppl 2}, journal = {Genome biology}, doi = {10.1186/gb-2008-9-s2-s2} }""", "NCBI-disease-IOB":"""@article{10.5555/2772763.2772800, author = {Dogan, Rezarta Islamaj and Leaman, Robert and Lu, Zhiyong}, title = {NCBI Disease Corpus}, year = {2014}, issue_date = {February 2014}, publisher = {Elsevier Science}, address = {San Diego, CA, USA}, volume = {47}, number = {C}, issn = {1532-0464}, abstract = {Graphical abstractDisplay Omitted NCBI disease corpus is built as a gold-standard resource for disease recognition.793 PubMed abstracts are annotated with disease mentions and concepts (MeSH/OMIM).14 Annotators produced high consistency level and inter-annotator agreement.Normalization benchmark results demonstrate the utility of the corpus.The corpus is publicly available to the community. Information encoded in natural language in biomedical literature publications is only useful if efficient and reliable ways of accessing and analyzing that information are available. Natural language processing and text mining tools are therefore essential for extracting valuable information, however, the development of powerful, highly effective tools to automatically detect central biomedical concepts such as diseases is conditional on the availability of annotated corpora.This paper presents the disease name and concept annotations of the NCBI disease corpus, a collection of 793 PubMed abstracts fully annotated at the mention and concept level to serve as a research resource for the biomedical natural language processing community. Each PubMed abstract was manually annotated by two annotators with disease mentions and their corresponding concepts in Medical Subject Headings (MeSH ) or Online Mendelian Inheritance in Man (OMIM ). Manual curation was performed using PubTator, which allowed the use of pre-annotations as a pre-step to manual annotations. Fourteen annotators were randomly paired and differing annotations were discussed for reaching a consensus in two annotation phases. In this setting, a high inter-annotator agreement was observed. Finally, all results were checked against annotations of the rest of the corpus to assure corpus-wide consistency.The public release of the NCBI disease corpus contains 6892 disease mentions, which are mapped to 790 unique disease concepts. Of these, 88% link to a MeSH identifier, while the rest contain an OMIM identifier. We were able to link 91% of the mentions to a single disease concept, while the rest are described as a combination of concepts. In order to help researchers use the corpus to design and test disease identification methods, we have prepared the corpus as training, testing and development sets. To demonstrate its utility, we conducted a benchmarking experiment where we compared three different knowledge-based disease normalization methods with a best performance in F-measure of 63.7%. These results show that the NCBI disease corpus has the potential to significantly improve the state-of-the-art in disease name recognition and normalization research, by providing a high-quality gold standard thus enabling the development of machine-learning based approaches for such tasks.The NCBI disease corpus, guidelines and other associated resources are available at: http://www.ncbi.nlm.nih.gov/CBBresearch/Dogan/DISEASE/.}, journal = {J. of Biomedical Informatics}, month = {feb}, pages = {1–10}, numpages = {10}}""", "JNLPBA":"""@inproceedings{collier-kim-2004-introduction, title = "Introduction to the Bio-entity Recognition Task at {JNLPBA}", author = "Collier, Nigel and Kim, Jin-Dong", booktitle = "Proceedings of the International Joint Workshop on Natural Language Processing in Biomedicine and its Applications ({NLPBA}/{B}io{NLP})", month = aug # " 28th and 29th", year = "2004", address = "Geneva, Switzerland", publisher = "COLING", url = "https://aclanthology.org/W04-1213", pages = "73--78", }""", "BIOSSES": """@article{souganciouglu2017biosses, title={BIOSSES: a semantic sentence similarity estimation system for the biomedical domain}, author={Souganciouglu, Gizem and Ozturk, Hakime and Ozgur, Arzucan}, journal={Bioinformatics}, volume={33}, number={14}, pages={i49--i58}, year={2017}, publisher={Oxford University Press} }""", "PubMedQA": """\ @inproceedings{jin2019pubmedqa, title={PubMedQA: A Dataset for Biomedical Research Question Answering}, author={Jin, Qiao and Dhingra, Bhuwan and Liu, Zhengping and Cohen, William and Lu, Xinghua}, booktitle={Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing and the 9th International Joint Conference on Natural Language Processing (EMNLP-IJCNLP)}, pages={2567--2577}, year={2019} }""" } DESCRIPTIONS = { "blurb" : """BLURB (Biomedical Language Understanding and Reasoning Benchmark.) is a comprehensive benchmark for biomedical NLP, with 13 biomedical NLP datasets in 6 tasks (NER, PICO, Relation Extraction, Sentence similarity, document classification, question answering). Our aim is to facilitate investigations of biomedical natural language processing with a specific focus on language model pretraining and to help accelerate progress in universal Biomedical NLP applications. The table below compares the datasets comprising BLURB versus the various datasets used in previous Biomedical and Clinical BERT language models.""", "BC5CDR-chem-IOB":"""The corpus consists of three separate sets of articles with diseases, chemicals and their relations annotated. The training (500 articles) and development (500 articles) sets were released to task participants in advance to support text-mining method development. The test set (500 articles) was used for final system performance evaluation.""", "BC5CDR-disease-IOB":"""The corpus consists of three separate sets of articles with diseases, chemicals and their relations annotated. The training (500 articles) and development (500 articles) sets were released to task participants in advance to support text-mining method development. The test set (500 articles) was used for final system performance evaluation.""", "BC2GM-IOB":"""The BioCreative II Gene Mention task. The training corpus for the current task consists mainly of the training and testing corpora (text collections) from the BCI task, and the testing corpus for the current task consists of an additional 5,000 sentences that were held 'in reserve' from the previous task. In the current corpus, tokenization is not provided; instead participants are asked to identify a gene mention in a sentence by giving its start and end characters. As before, the training set consists of a set of sentences, and for each sentence a set of gene mentions (GENE annotations). """, "NCBI-disease-IOB":"""The NCBI disease corpus is fully annotated at the mention and concept level to serve as a research resource for the biomedical natural language processing community. Corpus Characteristics ---------------------- * 793 PubMed abstracts * 6,892 disease mentions * 790 unique disease concepts * Medical Subject Headings (MeSH®) * Online Mendelian Inheritance in Man (OMIM®) * 91% of the mentions map to a single disease concept **divided into training, developing and testing sets. Corpus Annotation * Fourteen annotators * Two-annotators per document (randomly paired) * Three annotation phases * Checked for corpus-wide consistency of annotations """, "JNLPBA":"""The BioNLP / JNLPBA Shared Task 2004 involves the identification and classification of technical terms referring to concepts of interest to biologists in the domain of molecular biology. The task was organized by GENIA Project based on the annotations of the GENIA Term corpus (version 3.02). Corpus format: The JNLPBA corpus is distributed in IOB format, with each line containing a single token and its tag, separated by a tab character. Sentences are separated by blank lines.""", "BIOSSES": """BIOSSES is a benchmark dataset for biomedical sentence similarity estimation. The dataset comprises 100 sentence pairs, in which each sentence was selected from the [TAC (Text Analysis Conference) Biomedical Summarization Track Training Dataset](https://tac.nist.gov/2014/BiomedSumm/) containing articles from the biomedical domain. The sentence pairs in BIOSSES were selected from citing sentences, i.e. sentences that have a citation to a reference article. The sentence pairs were evaluated by five different human experts that judged their similarity and gave scores ranging from 0 (no relation) to 4 (equivalent). In the original paper the mean of the scores assigned by the five human annotators was taken as the gold standard. The Pearson correlation between the gold standard scores and the scores estimated by the models was used as the evaluation metric. The strength of correlation can be assessed by the general guideline proposed by Evans (1996) as follows: - very strong: 0.80–1.00 - strong: 0.60–0.79 - moderate: 0.40–0.59 - weak: 0.20–0.39 - very weak: 0.00–0.19 """, "PubMedQA": """\ PubMedQA is a novel biomedical question answering (QA) dataset collected from PubMed abstracts. The task of PubMedQA is to answer research questions with yes/no/maybe (e.g.: Do preoperative statins reduce atrial fibrillation after coronary artery bypass grafting?) using the corresponding abstracts. PubMedQA has 1k expert-annotated, 61.2k unlabeled and 211.3k artificially generated QA instances. Each PubMedQA instance is composed of (1) a question which is either an existing research article title or derived from one, (2) a context which is the corresponding abstract without its conclusion, (3) a long answer, which is the conclusion of the abstract and, presumably, answers the research question, and (4) a yes/no/maybe answer which summarizes the conclusion. PubMedQA is the first QA dataset where reasoning over biomedical research texts, especially their quantitative contents, is required to answer the questions. """ } HOMEPAGES = { "blurb": "https://microsoft.github.io/BLURB/index.html", "BC5CDR-chem-IOB":"https://biocreative.bioinformatics.udel.edu/resources/corpora/biocreative-v-cdr-corpus", "BC5CDR-disease-IOB":"https://biocreative.bioinformatics.udel.edu/resources/corpora/biocreative-v-cdr-corpus", "BC2GM-IOB": "https://biocreative.bioinformatics.udel.edu/tasks/biocreative-ii/task-1a-gene-mention-tagging/", "NCBI-disease-IOB":"https://www.ncbi.nlm.nih.gov/CBBresearch/Dogan/DISEASE/", "JNLPBA":"http://www.geniaproject.org/shared-tasks/bionlp-jnlpba-shared-task-2004", "BIOSSES":"https://tabilab.cmpe.boun.edu.tr/BIOSSES/DataSet.html", "PubMedQA": "https://pubmedqa.github.io/" } DATA_URL = { "blurb": None, "BC5CDR-chem-IOB": "https://github.com/cambridgeltl/MTL-Bioinformatics-2016/raw/master/data/", "BC5CDR-disease-IOB": "https://github.com/cambridgeltl/MTL-Bioinformatics-2016/raw/master/data/", "BC2GM-IOB": "https://github.com/cambridgeltl/MTL-Bioinformatics-2016/raw/master/data/", "NCBI-disease-IOB": "https://github.com/cambridgeltl/MTL-Bioinformatics-2016/raw/master/data/", "JNLPBA": "https://github.com/cambridgeltl/MTL-Bioinformatics-2016/raw/master/data/", "BIOSSES": "https://raw.githubusercontent.com/Markus-Zlabinger/ssts/fce78a649ab90269950aaf44ce20a36e94409392/data/biosses/all.tsv", "PubMedQA": "https://raw.githubusercontent.com/pubmedqa/pubmedqa/master/data/ori_pqal.json" } logger = datasets.logging.get_logger(__name__) class BlurbConfig(datasets.BuilderConfig): """BuilderConfig for BLURB.""" def __init__(self, task, data_url, citation, homepage, label_classes=None, **kwargs): """BuilderConfig for BLURB. Args: task: `string` task the dataset is used for: 'ner', 'pico', 'rel-ext', 'sent-sim', 'doc-clas', 'qa' features: `list[string]`, list of the features that will appear in the feature dict. Should not include "label". data_url: `string`, url to download the data files from. citation: `string`, citation for the data set. url: `string`, url for information about the data set. label_classes: `list[string]`, the list of classes for the label if the label is present as a string. Non-string labels will be cast to either 'False' or 'True'. **kwargs: keyword arguments forwarded to super. """ # Version history: super(BlurbConfig, self).__init__(version=datasets.Version(_VERSION), **kwargs) self.task = task self.label_classes = label_classes self.data_url = data_url self.citation = citation self.homepage = homepage if self.task == 'ner': self.features = datasets.Features( {"id": datasets.Value("string"), "tokens": datasets.Sequence(datasets.Value("string")), "ner_tags": datasets.Sequence( datasets.features.ClassLabel(names=self.label_classes) )} ) self.base_url = f"{self.data_url}{self.name}/" self.urls = { "train": f"{self.base_url}{'train.tsv'}", "validation": f"{self.base_url}{'devel.tsv'}", "test": f"{self.base_url}{'test.tsv'}" } if self.task == 'sent-sim': self.features = datasets.Features( { "sentence1": datasets.Value("string"), "sentence2": datasets.Value("string"), "score": datasets.Value("float32"), } ) if (self.task == "qa") and (self.name == "PubMedQA"): self.features=datasets.Features( { "pubid": datasets.Value("int32"), "question": datasets.Value("string"), "context": datasets.features.Sequence( { "contexts": datasets.Value("string"), "labels": datasets.Value("string"), "meshes": datasets.Value("string"), "reasoning_required_pred": datasets.Value("string"), "reasoning_free_pred": datasets.Value("string"), } ), "long_answer": datasets.Value("string"), "final_decision": datasets.Value("string"), } ) self.urls = {"ori_pqal": self.data_url} class Blurb(datasets.GeneratorBasedBuilder): """BLURB benchmark dataset for Biomedical Language Understanding and Reasoning Benchmark.""" BUILDER_CONFIGS = [ BlurbConfig(name='BC5CDR-chem-IOB', task='ner', label_classes=['O', 'B-Chemical', 'I-Chemical'], data_url = DATA_URL['BC5CDR-chem-IOB'], description=DESCRIPTIONS['BC5CDR-chem-IOB'], citation=CITATIONS['BC5CDR-chem-IOB'], homepage=HOMEPAGES['BC5CDR-chem-IOB']), BlurbConfig(name='BC5CDR-disease-IOB', task='ner', label_classes=['O', 'B-Disease', 'I-Disease'], data_url = DATA_URL['BC5CDR-disease-IOB'], description=DESCRIPTIONS['BC5CDR-disease-IOB'], citation=CITATIONS['BC5CDR-disease-IOB'], homepage=HOMEPAGES['BC5CDR-disease-IOB']), BlurbConfig(name='BC2GM-IOB', task='ner', label_classes=['O', 'B-GENE', 'I-GENE'], data_url = DATA_URL['BC2GM-IOB'], description=DESCRIPTIONS['BC2GM-IOB'], citation=CITATIONS['BC2GM-IOB'], homepage=HOMEPAGES['BC2GM-IOB']), BlurbConfig(name='NCBI-disease-IOB', task='ner', label_classes=['O', 'B-Disease', 'I-Disease'], data_url = DATA_URL['NCBI-disease-IOB'], description=DESCRIPTIONS['NCBI-disease-IOB'], citation=CITATIONS['NCBI-disease-IOB'], homepage=HOMEPAGES['NCBI-disease-IOB']), BlurbConfig(name='JNLPBA', task='ner', label_classes=['O', 'B-protein', 'I-protein', 'B-cell_type', 'I-cell_type', 'B-cell_line', 'I-cell_line', 'B-DNA','I-DNA', 'B-RNA', 'I-RNA'], data_url = DATA_URL['JNLPBA'], description=DESCRIPTIONS['JNLPBA'], citation=CITATIONS['JNLPBA'], homepage=HOMEPAGES['JNLPBA']), BlurbConfig(name='BIOSSES', task='sent-sim', label_classes=None, data_url = DATA_URL['BIOSSES'], description=DESCRIPTIONS['BIOSSES'], citation=CITATIONS['BIOSSES'], homepage=HOMEPAGES['BIOSSES']), BlurbConfig(name='PubMedQA', task='qa', label_classes=None, data_url = DATA_URL['PubMedQA'], description=DESCRIPTIONS['PubMedQA'], citation=CITATIONS['PubMedQA'], homepage=HOMEPAGES['PubMedQA']), ] def _info(self): return datasets.DatasetInfo( description=self.config.description, features=self.config.features, supervised_keys=None, homepage=self.config.homepage, citation=self.config.citation, ) def _split_generators(self, dl_manager): """Returns SplitGenerators.""" if self.config.task == 'ner': downloaded_files = dl_manager.download_and_extract(self.config.urls) return self._ner_split_generator(downloaded_files) if self.config.task == 'sent-sim': downloaded_file = dl_manager.download_and_extract(self.config.data_url) return [datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"filepath": downloaded_file})] if (self.config.task == "qa") and (self.config.name == "PubMedQA"): downloaded_file = dl_manager.download_and_extract(self.config.data_url) return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={"filepath": downloaded_file} ) ] def _generate_examples(self, filepath): print("Before the download") logger.info("⏳ Generating examples from = %s", filepath) if self.config.task == 'ner': return self._ner_example_generator(filepath) if self.config.task == 'sent-sim': return self._sentsim_example_generator(filepath) if self.config.name == 'PubMedQA': print("Calling the example_generator") return self._pubmedqa_example_generator(filepath) def _ner_split_generator(self, downloaded_files): 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 _ner_example_generator(self, 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]) ner_tags.append(splits[1].rstrip()) # last example yield guid, { "id": str(guid), "tokens": tokens, "ner_tags": ner_tags, } def _sentsim_example_generator(self, filepath): """Yields examples as (key, example) tuples.""" df = pd.read_csv(filepath, sep="\t", encoding="utf-8") for idx, row in df.iterrows(): yield idx, { "sentence1": row["sentence1"], "sentence2": row["sentence2"], "score": row["score"], } def _pubmedqa_example_generator(self, filepath): """Yields examples.""" with open(filepath, encoding="utf-8") as f: data = json.load(f) for id_, row in enumerate(data): yield id_, { "pubid": row, "question": data[row]["QUESTION"], "context": { "contexts": data[row]["CONTEXTS"], "labels": data[row]["LABELS"], "meshes": data[row]["MESHES"], "reasoning_required_pred": data[row]["reasoning_required_pred"], "reasoning_free_pred": data[row]["reasoning_free_pred"], }, "long_answer": data[row]["LONG_ANSWER"], "final_decision": data[row]["final_decision"], }