File size: 10,024 Bytes
51d3529 27cad3e 98dd3b1 f521228 27cad3e 51d3529 27cad3e 51d3529 c37e1e2 51d3529 27cad3e 51d3529 |
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 |
# 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.
# pip install xmltodict
import random
from pathlib import Path
from itertools import product
from dataclasses import dataclass
from typing import Dict, List, Tuple
import xmltodict
import numpy as np
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 = "https://files.ifi.uzh.ch/cl/mantra/gsc/GSC-v1.1.zip"
_LANGUAGES_2 = {
"es": "Spanish",
"fr": "French",
"de": "German",
"nl": "Dutch",
"en": "English",
}
_DATASET_TYPES = {
"emea": "EMEA",
"medline": "Medline",
"patents": "Patent",
}
class StringIndex:
def __init__(self, vocab):
self.vocab_struct = {}
print("Start building the index!")
for t in vocab:
if len(t) == 0:
continue
# Index terms by their first letter and length
key = (t[0], len(t))
if (key in self.vocab_struct) == False:
self.vocab_struct[key] = []
self.vocab_struct[key].append(t)
print("Finished building the index!")
def find(self, t):
if len(t) <= 0:
return "is_not_oov"
key = (t[0], len(t))
if (key in self.vocab_struct) == False:
return "is_oov"
return "is_not_oov" if t in self.vocab_struct[key] else "is_oov"
_VOCAB = StringIndex(vocab=open("./vocabulary_nachos_lowercased.txt","r").read().split("\n"))
@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):
if self.config.name.find("emea") != -1:
names = ['B-ANAT', 'I-ANAT', 'I-PHEN', 'B-PROC', 'I-CHEM', 'I-PHYS', 'B-DEVI', 'O', 'B-PHYS', 'I-DEVI', 'B-OBJC', 'I-DISO', 'B-PHEN', 'I-LIVB', 'B-DISO', 'B-LIVB', 'B-CHEM', 'I-PROC']
elif self.config.name.find("medline") != -1:
names = ['B-ANAT', 'I-ANAT', 'B-PROC', 'I-CHEM', 'I-PHYS', 'B-GEOG', 'B-DEVI', 'O', 'B-PHYS', 'I-LIVB', 'B-OBJC', 'I-DISO', 'I-DEVI', 'B-PHEN', 'B-DISO', 'B-LIVB', 'B-CHEM', 'I-PROC']
elif self.config.name.find("patents") != -1:
names = ['B-ANAT', 'I-ANAT', 'B-PROC', 'I-CHEM', 'I-PHYS', 'B-DEVI', 'O', 'I-LIVB', 'B-OBJC', 'I-DISO', 'B-PHEN', 'I-PROC', 'B-DISO', 'I-DEVI', 'B-LIVB', 'B-CHEM', 'B-PHYS']
features = datasets.Features(
{
"id": datasets.Value("string"),
"tokens": [datasets.Value("string")],
"ner_tags": datasets.Sequence(
datasets.features.ClassLabel(
names = names,
)
),
"is_oov": datasets.Sequence(
datasets.features.ClassLabel(
names=['is_not_oov', 'is_oov'],
),
),
}
)
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=features,
homepage=_HOMEPAGE,
license=str(_LICENSE),
citation=_CITATION,
)
def _split_generators(self, dl_manager):
language, dataset_type = self.config.name.split("_")
data_dir = dl_manager.download_and_extract(_URL)
data_dir = Path(data_dir) / "GSC-v1.1" / f"{_DATASET_TYPES[dataset_type]}_GSC_{language}_man.xml"
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={
"data_dir": data_dir,
"split": "train",
},
),
datasets.SplitGenerator(
name=datasets.Split.VALIDATION,
gen_kwargs={
"data_dir": data_dir,
"split": "validation",
},
),
datasets.SplitGenerator(
name=datasets.Split.TEST,
gen_kwargs={
"data_dir": data_dir,
"split": "test",
},
),
]
def _generate_examples(self, data_dir, split):
with open(data_dir) as fd:
doc = xmltodict.parse(fd.read())
all_res = []
for d in doc["Corpus"]["document"]:
if type(d["unit"]) != type(list()):
d["unit"] = [d["unit"]]
for u in d["unit"]:
text = u["text"]
if "e" in u.keys():
if type(u["e"]) != type(list()):
u["e"] = [u["e"]]
tags = [{
"label": current["@grp"].upper(),
"offset_start": int(current["@offset"]),
"offset_end": int(current["@offset"]) + int(current["@len"]),
} for current in u["e"]]
else:
tags = []
_tokens = text.split(" ")
tokens = []
for i, t in enumerate(_tokens):
concat = " ".join(_tokens[0:i+1])
offset_start = len(concat) - len(t)
offset_end = len(concat)
tokens.append({
"token": t,
"offset_start": offset_start,
"offset_end": offset_end,
})
ner_tags = [["O", 0] for o in tokens]
for tag in tags:
cpt = 0
for idx, token in enumerate(tokens):
rtok = range(token["offset_start"], token["offset_end"]+1)
rtag = range(tag["offset_start"], tag["offset_end"]+1)
# Check if the ranges are overlapping
if bool(set(rtok) & set(rtag)):
# if ner_tags[idx] != "O" and ner_tags[idx] != tag['label']:
# print(f"{token} - currently: {ner_tags[idx]} - after: {tag['label']}")
if ner_tags[idx][0] == "O":
cpt += 1
ner_tags[idx][0] = tag["label"]
ner_tags[idx][1] = cpt
for i in range(len(ner_tags)):
tag = ner_tags[i][0]
if tag == "O":
continue
elif tag != "O" and ner_tags[i][1] == 1:
ner_tags[i][0] = "B-" + tag
elif tag != "O" and ner_tags[i][1] != 1:
ner_tags[i][0] = "I-" + tag
obj = {
"id": u["@id"],
"tokens": [t["token"].lower() for t in tokens],
"ner_tags": [n[0] for n in ner_tags],
"is_oov": [_VOCAB.find(t["token"].lower()) for t in tokens],
}
all_res.append(obj)
ids = [r["id"] for r in all_res]
random.seed(4)
random.shuffle(ids)
random.shuffle(ids)
random.shuffle(ids)
train, validation, test = np.split(ids, [int(len(ids)*0.70), int(len(ids)*0.80)])
if split == "train":
allowed_ids = list(train)
elif split == "validation":
allowed_ids = list(validation)
elif split == "test":
allowed_ids = list(test)
for r in all_res:
identifier = r["id"]
if identifier in allowed_ids:
yield identifier, r |