# 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 ast from pathlib import Path from itertools import product from dataclasses import dataclass from typing import Dict, List, Tuple import datasets _CITATION = """\ @article{10.1093/jamia/ocv037, author = {Kors, Jan A and Clematide, Simon and Akhondi, Saber A and van Mulligen, Erik M and Rebholz-Schuhmann, Dietrich}, title = "{A multilingual gold-standard corpus for biomedical concept recognition: the Mantra GSC}", journal = {Journal of the American Medical Informatics Association}, volume = {22}, number = {5}, pages = {948-956}, year = {2015}, month = {05}, abstract = "{Objective To create a multilingual gold-standard corpus for biomedical concept recognition.Materials and methods We selected text units from different parallel corpora (Medline abstract titles, drug labels, biomedical patent claims) in English, French, German, Spanish, and Dutch. Three annotators per language independently annotated the biomedical concepts, based on a subset of the Unified Medical Language System and covering a wide range of semantic groups. To reduce the annotation workload, automatically generated preannotations were provided. Individual annotations were automatically harmonized and then adjudicated, and cross-language consistency checks were carried out to arrive at the final annotations.Results The number of final annotations was 5530. Inter-annotator agreement scores indicate good agreement (median F-score 0.79), and are similar to those between individual annotators and the gold standard. The automatically generated harmonized annotation set for each language performed equally well as the best annotator for that language.Discussion The use of automatic preannotations, harmonized annotations, and parallel corpora helped to keep the manual annotation efforts manageable. The inter-annotator agreement scores provide a reference standard for gauging the performance of automatic annotation techniques.Conclusion To our knowledge, this is the first gold-standard corpus for biomedical concept recognition in languages other than English. Other distinguishing features are the wide variety of semantic groups that are being covered, and the diversity of text genres that were annotated.}", issn = {1067-5027}, doi = {10.1093/jamia/ocv037}, url = {https://doi.org/10.1093/jamia/ocv037}, eprint = {https://academic.oup.com/jamia/article-pdf/22/5/948/34146393/ocv037.pdf}, } """ _DESCRIPTION = """\ We selected text units from different parallel corpora (Medline abstract titles, drug labels, biomedical patent claims) in English, French, German, Spanish, and Dutch. Three annotators per language independently annotated the biomedical concepts, based on a subset of the Unified Medical Language System and covering a wide range of semantic groups. """ _HOMEPAGE = "https://biosemantics.erasmusmc.nl/index.php/resources/mantra-gsc" _LICENSE = "CC_BY_4p0" _URL = "http://biosemantics.org/MantraGSC/Mantra-GSC.zip" _LANGUAGES_2 = { "es": "Spanish", "fr": "French", "de": "German", "nl": "Dutch", "en": "English", } _DATASET_TYPES = { "emea": "EMEA", "medline": "Medline", "patents": "Patents", } @dataclass class DrBenchmarkConfig(datasets.BuilderConfig): name: str = None version: datasets.Version = None description: str = None schema: str = None subset_id: str = None class MantraGSC(datasets.GeneratorBasedBuilder): SOURCE_VERSION = datasets.Version("1.0.0") BUILDER_CONFIGS = [] for language, dataset_type in product(_LANGUAGES_2, _DATASET_TYPES): if dataset_type == "patents" and language in ["nl", "es"]: continue BUILDER_CONFIGS.append( DrBenchmarkConfig( name=f"{language}_{dataset_type}", version=SOURCE_VERSION, description=f"Mantra GSC {_LANGUAGES_2[language]} {_DATASET_TYPES[dataset_type]} source schema", schema="source", subset_id=f"{language}_{_DATASET_TYPES[dataset_type]}", ) ) DEFAULT_CONFIG_NAME = "fr_medline" def _info(self) -> datasets.DatasetInfo: if self.config.schema == "source": features = datasets.Features( { "document_id": datasets.Value("string"), "text": datasets.Value("string"), "entities": [ { "entity_id": datasets.Value("string"), "type": datasets.Value("string"), "offsets": datasets.Sequence([datasets.Value("int32")]), "text": datasets.Sequence(datasets.Value("string")), "cui": datasets.Value("string"), "preferred_term": datasets.Value("string"), "semantic_type": datasets.Value("string"), "normalized": [ { "db_name": datasets.Value("string"), "db_id": datasets.Value("string"), } ], } ], } ) return datasets.DatasetInfo( description=_DESCRIPTION, features=features, homepage=_HOMEPAGE, license=str(_LICENSE), citation=_CITATION, ) def _split_generators(self, dl_manager) -> List[datasets.SplitGenerator]: print("1 - " + "*"*50) print(_URL) data_dir = dl_manager.download_and_extract(_URL) print("2 - " + "*"*50) data_dir = Path(data_dir) / "Mantra-GSC" print("3 - " + "*"*50) language, dataset_type = self.config.name.split("_") print("4 - " + "*"*50) return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={ "data_dir": data_dir, "language": language, "dataset_type": dataset_type, }, ), ] def remove_prefix(self, a: str, prefix: str) -> str: if a.startswith(prefix): a = a[len(prefix) :] return a def parse_brat_file(self, txt_file: Path, annotation_file_suffixes: List[str] = None, parse_notes: bool = False) -> Dict: example = {} example["document_id"] = txt_file.with_suffix("").name with txt_file.open() as f: example["text"] = f.read() # If no specific suffixes of the to-be-read annotation files are given - take standard suffixes # for event extraction if annotation_file_suffixes is None: annotation_file_suffixes = [".a1", ".a2", ".ann"] if len(annotation_file_suffixes) == 0: raise AssertionError( "At least one suffix for the to-be-read annotation files should be given!" ) ann_lines = [] for suffix in annotation_file_suffixes: annotation_file = txt_file.with_suffix(suffix) if annotation_file.exists(): with annotation_file.open() as f: ann_lines.extend(f.readlines()) example["text_bound_annotations"] = [] example["events"] = [] example["relations"] = [] example["equivalences"] = [] example["attributes"] = [] example["normalizations"] = [] if parse_notes: example["notes"] = [] for line in ann_lines: line = line.strip() if not line: continue if line.startswith("T"): # Text bound ann = {} fields = line.split("\t") ann["id"] = fields[0] ann["type"] = fields[1].split()[0] ann["offsets"] = [] span_str = self.remove_prefix(fields[1], (ann["type"] + " ")) text = fields[2] for span in span_str.split(";"): start, end = span.split() ann["offsets"].append([int(start), int(end)]) # Heuristically split text of discontiguous entities into chunks ann["text"] = [] if len(ann["offsets"]) > 1: i = 0 for start, end in ann["offsets"]: chunk_len = end - start ann["text"].append(text[i : chunk_len + i]) i += chunk_len while i < len(text) and text[i] == " ": i += 1 else: ann["text"] = [text] example["text_bound_annotations"].append(ann) elif line.startswith("E"): ann = {} fields = line.split("\t") ann["id"] = fields[0] ann["type"], ann["trigger"] = fields[1].split()[0].split(":") ann["arguments"] = [] for role_ref_id in fields[1].split()[1:]: argument = { "role": (role_ref_id.split(":"))[0], "ref_id": (role_ref_id.split(":"))[1], } ann["arguments"].append(argument) example["events"].append(ann) elif line.startswith("R"): ann = {} fields = line.split("\t") ann["id"] = fields[0] ann["type"] = fields[1].split()[0] ann["head"] = { "role": fields[1].split()[1].split(":")[0], "ref_id": fields[1].split()[1].split(":")[1], } ann["tail"] = { "role": fields[1].split()[2].split(":")[0], "ref_id": fields[1].split()[2].split(":")[1], } example["relations"].append(ann) # '*' seems to be the legacy way to mark equivalences, # but I couldn't find any info on the current way # this might have to be adapted dependent on the brat version # of the annotation elif line.startswith("*"): ann = {} fields = line.split("\t") ann["id"] = fields[0] ann["ref_ids"] = fields[1].split()[1:] example["equivalences"].append(ann) elif line.startswith("A") or line.startswith("M"): ann = {} fields = line.split("\t") ann["id"] = fields[0] info = fields[1].split() ann["type"] = info[0] ann["ref_id"] = info[1] if len(info) > 2: ann["value"] = info[2] else: ann["value"] = "" example["attributes"].append(ann) elif line.startswith("N"): ann = {} fields = line.split("\t") ann["id"] = fields[0] ann["text"] = fields[2] info = fields[1].split() ann["type"] = info[0] ann["ref_id"] = info[1] ann["resource_name"] = info[2].split(":")[0] ann["cuid"] = info[2].split(":")[1] example["normalizations"].append(ann) elif parse_notes and line.startswith("#"): ann = {} fields = line.split("\t") ann["id"] = fields[0] ann["text"] = fields[2] if len(fields) == 3 else "" info = fields[1].split() ann["type"] = info[0] ann["ref_id"] = info[1] example["notes"].append(ann) return example def _generate_examples( self, data_dir: Path, language: str, dataset_type: str ) -> Tuple[int, Dict]: """Yields examples as (key, example) tuples.""" data_dir = data_dir / f"{_LANGUAGES_2[language]}" if dataset_type in ["patents", "emea"]: data_dir = data_dir / f"{_DATASET_TYPES[dataset_type]}_ec22-cui-best_man" else: # It is Medline now if language != "en": data_dir = ( data_dir / f"{_DATASET_TYPES[dataset_type]}_EN_{language.upper()}_ec22-cui-best_man" ) else: data_dir = [ data_dir / f"{_DATASET_TYPES[dataset_type]}_EN_{_lang.upper()}_ec22-cui-best_man" for _lang in _LANGUAGES_2 if _lang != "en" ] if not isinstance(data_dir, list): data_dir: List[Path] = [data_dir] raw_files = [raw_file for _dir in data_dir for raw_file in _dir.glob("*.txt")] if self.config.schema == "source": for i, raw_file in enumerate(raw_files): brat_example = self.parse_brat_file(raw_file, parse_notes=True) source_example = self._to_source_example(brat_example) yield i, source_example def _to_source_example(self, brat_example: Dict) -> Dict: source_example = { "document_id": brat_example["document_id"], "text": brat_example["text"], } source_example["entities"] = [] for entity_annotation, ann_notes in zip( brat_example["text_bound_annotations"], brat_example["notes"] ): entity_ann = entity_annotation.copy() # Change id property name entity_ann["entity_id"] = entity_ann["id"] entity_ann.pop("id") # Get values from annotator notes assert entity_ann["entity_id"] == ann_notes["ref_id"] notes_values = ast.literal_eval(ann_notes["text"]) if len(notes_values) == 4: cui, preferred_term, semantic_type, semantic_group = notes_values else: preferred_term, semantic_type, semantic_group = notes_values cui = entity_ann["type"] entity_ann["cui"] = cui entity_ann["preferred_term"] = preferred_term entity_ann["semantic_type"] = semantic_type entity_ann["type"] = semantic_group entity_ann["normalized"] = [{"db_name": "UMLS", "db_id": cui}] # Add entity annotation to sample source_example["entities"].append(entity_ann) return source_example