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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Datasets Authors and the current dataset script contributor.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import os
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
from typing import Dict, List, Tuple
|
| 19 |
+
|
| 20 |
+
import datasets
|
| 21 |
+
import pandas as pd
|
| 22 |
+
|
| 23 |
+
from .bigbiohub import BigBioConfig, Tasks, kb_features
|
| 24 |
+
|
| 25 |
+
_LOCAL = True
|
| 26 |
+
_CITATION = """\
|
| 27 |
+
@data{
|
| 28 |
+
data/AFYQDY_2022,
|
| 29 |
+
author = {Christoph Dieterich},
|
| 30 |
+
publisher = {heiDATA},
|
| 31 |
+
title = {{CARDIO:DE}},
|
| 32 |
+
year = {2022},
|
| 33 |
+
version = {V5},
|
| 34 |
+
doi = {10.11588/data/AFYQDY},
|
| 35 |
+
url = {https://doi.org/10.11588/data/AFYQDY}
|
| 36 |
+
}
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
_DESCRIPTION = """\
|
| 40 |
+
First freely available and distributable large German clinical corpus from the cardiovascular domain.
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
_HOMEPAGE = "https://heidata.uni-heidelberg.de/dataset.xhtml?persistentId=doi%3A10.11588%2Fdata%2FAFYQDY"
|
| 44 |
+
|
| 45 |
+
_LICENSE = "DUA"
|
| 46 |
+
_LANGUAGES = ["German"]
|
| 47 |
+
_URLS = {}
|
| 48 |
+
_SUPPORTED_TASKS = [Tasks.NAMED_ENTITY_RECOGNITION]
|
| 49 |
+
_SOURCE_VERSION = "5.0.0"
|
| 50 |
+
_BIGBIO_VERSION = "1.0.0"
|
| 51 |
+
_DATASETNAME = "cardiode"
|
| 52 |
+
_DISPLAYNAME = "CARDIO:DE"
|
| 53 |
+
_PUBMED = False
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class CardioDataset(datasets.GeneratorBasedBuilder):
|
| 57 |
+
SOURCE_VERSION = datasets.Version(_SOURCE_VERSION)
|
| 58 |
+
BIGBIO_VERSION = datasets.Version(_BIGBIO_VERSION)
|
| 59 |
+
|
| 60 |
+
BUILDER_CONFIGS = [
|
| 61 |
+
BigBioConfig(
|
| 62 |
+
name="cardiode_source",
|
| 63 |
+
version=SOURCE_VERSION,
|
| 64 |
+
description="CARDIO:DE source schema",
|
| 65 |
+
schema="source",
|
| 66 |
+
subset_id="cardiode",
|
| 67 |
+
),
|
| 68 |
+
BigBioConfig(
|
| 69 |
+
name="cardiode_bigbio_kb",
|
| 70 |
+
version=BIGBIO_VERSION,
|
| 71 |
+
description="CARDIO:DE BigBio schema",
|
| 72 |
+
schema="bigbio_kb",
|
| 73 |
+
subset_id="cardidoe",
|
| 74 |
+
),
|
| 75 |
+
]
|
| 76 |
+
|
| 77 |
+
DEFAULT_CONFIG_NAME = "cardiode_bigbio_kb"
|
| 78 |
+
|
| 79 |
+
def _info(self) -> datasets.DatasetInfo:
|
| 80 |
+
if self.config.schema == "source":
|
| 81 |
+
features = datasets.Features(
|
| 82 |
+
{
|
| 83 |
+
"doc_id": datasets.Value("string"),
|
| 84 |
+
"annotations": [
|
| 85 |
+
{
|
| 86 |
+
"text": datasets.Value("string"),
|
| 87 |
+
"tokens": [
|
| 88 |
+
{
|
| 89 |
+
"id": datasets.Value("string"),
|
| 90 |
+
"offsets": datasets.Value("string"),
|
| 91 |
+
"text": datasets.Value("string"),
|
| 92 |
+
"type": datasets.Value("string"),
|
| 93 |
+
"parent_annotation_id": datasets.Value("string"),
|
| 94 |
+
"section": datasets.Value("string"),
|
| 95 |
+
}
|
| 96 |
+
],
|
| 97 |
+
}
|
| 98 |
+
],
|
| 99 |
+
}
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
elif self.config.schema == "bigbio_kb":
|
| 103 |
+
features = kb_features
|
| 104 |
+
|
| 105 |
+
return datasets.DatasetInfo(
|
| 106 |
+
description=_DESCRIPTION,
|
| 107 |
+
features=features,
|
| 108 |
+
homepage=_HOMEPAGE,
|
| 109 |
+
license=_LICENSE,
|
| 110 |
+
citation=_CITATION,
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
def _split_generators(self, dl_manager) -> List[datasets.SplitGenerator]:
|
| 114 |
+
if self.config.data_dir is None:
|
| 115 |
+
raise ValueError("This is a local dataset. Please pass the data_dir kwarg to load_dataset.")
|
| 116 |
+
else:
|
| 117 |
+
data_dir = self.config.data_dir
|
| 118 |
+
|
| 119 |
+
return [
|
| 120 |
+
datasets.SplitGenerator(
|
| 121 |
+
name=datasets.Split.TRAIN,
|
| 122 |
+
gen_kwargs={
|
| 123 |
+
"filepath": os.path.join(data_dir),
|
| 124 |
+
"split": "train",
|
| 125 |
+
},
|
| 126 |
+
)
|
| 127 |
+
]
|
| 128 |
+
|
| 129 |
+
def _generate_examples(self, filepath, split: str) -> Tuple[int, Dict]:
|
| 130 |
+
"""Yields examples as (key, example) tuples."""
|
| 131 |
+
doc_ids = _sort_files(Path(filepath) / "tsv" / "CARDIODE400_main")
|
| 132 |
+
for uid, doc in enumerate(doc_ids):
|
| 133 |
+
tsv_path = Path(filepath) / "tsv" / "CARDIODE400_main" / f"{doc}"
|
| 134 |
+
df, sentences = _parse_tsv(tsv_path)
|
| 135 |
+
if self.config.schema == "source":
|
| 136 |
+
yield uid, _make_source(uid, doc, df, sentences)
|
| 137 |
+
elif self.config.schema == "bigbio_kb":
|
| 138 |
+
yield uid, _make_bigbio_kb(uid, doc, df, sentences)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def _parse_tsv(path: str) -> pd.DataFrame:
|
| 142 |
+
# read whole .tsv as a string
|
| 143 |
+
with open(path, encoding="utf-8") as file:
|
| 144 |
+
content = file.read()
|
| 145 |
+
|
| 146 |
+
# separate doc into sentences
|
| 147 |
+
passages = content.split("#")
|
| 148 |
+
|
| 149 |
+
# remove the first line (un-tabbed) of each sentence
|
| 150 |
+
# split sentences into words/tokens
|
| 151 |
+
# and store string sentences for the passages
|
| 152 |
+
sentences = []
|
| 153 |
+
for i, passage in enumerate(passages):
|
| 154 |
+
if passage.split("\n")[0].startswith("Text="):
|
| 155 |
+
sentences.append(passage.split("\n")[0].split("Text=")[1])
|
| 156 |
+
passages[i] = passage.split("\n")[1:]
|
| 157 |
+
|
| 158 |
+
# clean empty sentences and tokens
|
| 159 |
+
clean_passages = [[token for token in passage if token != ""] for passage in passages if passage != []]
|
| 160 |
+
|
| 161 |
+
# make a dataframe out of the clean tokens
|
| 162 |
+
df = []
|
| 163 |
+
for passage in clean_passages:
|
| 164 |
+
for token in passage:
|
| 165 |
+
df.append(token.split("\t"))
|
| 166 |
+
|
| 167 |
+
df = pd.DataFrame(df).rename(
|
| 168 |
+
columns={
|
| 169 |
+
0: "passage_token_id",
|
| 170 |
+
1: "token_offset",
|
| 171 |
+
2: "text",
|
| 172 |
+
3: "label",
|
| 173 |
+
4: "uncertain",
|
| 174 |
+
5: "relation",
|
| 175 |
+
6: "section",
|
| 176 |
+
}
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
# correct weird rows were label is NoneType
|
| 180 |
+
df["label"].fillna("_", inplace=True)
|
| 181 |
+
|
| 182 |
+
# split passage and token ids
|
| 183 |
+
df[["passage_id", "token_id"]] = df["passage_token_id"].str.split("-", expand=True)
|
| 184 |
+
|
| 185 |
+
# split labels and their spans
|
| 186 |
+
# some docs do not have labels spanning various tokens (or they do not have any labels at all)
|
| 187 |
+
if df["label"].apply(lambda x: "[" in x).any():
|
| 188 |
+
df[["lab", "span"]] = df["label"].str.split("[", expand=True)
|
| 189 |
+
df["span"] = df["span"].str.replace("]", "", regex=True)
|
| 190 |
+
else:
|
| 191 |
+
df["lab"] = "_"
|
| 192 |
+
df["span"] = None
|
| 193 |
+
|
| 194 |
+
# split start and end offsets and cast to int
|
| 195 |
+
df[["offset_start", "offset_end"]] = df["token_offset"].str.split("-", expand=True)
|
| 196 |
+
df["offset_start"] = df["offset_start"].astype(int)
|
| 197 |
+
df["offset_end"] = df["offset_end"].astype(int)
|
| 198 |
+
|
| 199 |
+
# correct offset gaps between tokens
|
| 200 |
+
i = 0
|
| 201 |
+
while i < len(df) - 1:
|
| 202 |
+
gap = df.loc[i + 1]["offset_start"] - df.loc[i]["offset_end"]
|
| 203 |
+
if gap > 1:
|
| 204 |
+
df.loc[i + 1 :, "offset_start"] = df.loc[i + 1 :, "offset_start"] - (gap - 1)
|
| 205 |
+
df.loc[i + 1 :, "offset_end"] = df.loc[i + 1 :, "offset_end"] - (gap - 1)
|
| 206 |
+
i += 1
|
| 207 |
+
|
| 208 |
+
return df, sentences
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def _make_source(uid: int, doc_id: str, df: pd.DataFrame, sentences: list):
|
| 212 |
+
out = {"doc_id": doc_id, "annotations": []}
|
| 213 |
+
for i, sentence in enumerate(sentences):
|
| 214 |
+
anno = {"text": sentence, "tokens": []}
|
| 215 |
+
chunk = df[df["passage_id"] == str(i + 1)]
|
| 216 |
+
for _, row in chunk.iterrows():
|
| 217 |
+
anno["tokens"].append(
|
| 218 |
+
{
|
| 219 |
+
"id": row["passage_token_id"],
|
| 220 |
+
"offsets": row["token_offset"],
|
| 221 |
+
"text": row["text"],
|
| 222 |
+
"type": row["label"],
|
| 223 |
+
"parent_annotation_id": row["relation"],
|
| 224 |
+
"section": row["section"],
|
| 225 |
+
}
|
| 226 |
+
)
|
| 227 |
+
out["annotations"].append(anno)
|
| 228 |
+
return out
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def _make_bigbio_kb(uid: int, doc_id: str, df: pd.DataFrame, sentences: list):
|
| 232 |
+
out = {
|
| 233 |
+
"id": str(uid),
|
| 234 |
+
"document_id": doc_id,
|
| 235 |
+
"passages": [],
|
| 236 |
+
"entities": [],
|
| 237 |
+
"events": [],
|
| 238 |
+
"coreferences": [],
|
| 239 |
+
"relations": [],
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
# handle passages
|
| 243 |
+
i, sen_num, offset_mark = 0, 0, 0
|
| 244 |
+
while i < len(df):
|
| 245 |
+
pid = df.iloc[i]["passage_id"]
|
| 246 |
+
passage = df[df["passage_id"] == pid]
|
| 247 |
+
|
| 248 |
+
out["passages"].append(
|
| 249 |
+
{
|
| 250 |
+
"id": f"{uid}-{pid}",
|
| 251 |
+
"type": "sentence",
|
| 252 |
+
"text": [sentences[sen_num]],
|
| 253 |
+
"offsets": [[offset_mark, offset_mark + len(sentences[sen_num])]],
|
| 254 |
+
}
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
+
i += len(passage)
|
| 258 |
+
offset_mark += len(sentences[sen_num]) + 1
|
| 259 |
+
sen_num += 1
|
| 260 |
+
|
| 261 |
+
# handle entities
|
| 262 |
+
text = " ".join(sentences)
|
| 263 |
+
i = 0
|
| 264 |
+
while i < len(df):
|
| 265 |
+
if df.iloc[i]["lab"] != "_" and df.iloc[i]["span"] is None:
|
| 266 |
+
out["entities"].append(
|
| 267 |
+
{
|
| 268 |
+
"id": f'{uid}-{df.iloc[i]["passage_token_id"]}',
|
| 269 |
+
"type": df.iloc[i]["lab"],
|
| 270 |
+
"text": [text[df.iloc[i]["offset_start"] : df.iloc[i]["offset_end"]]],
|
| 271 |
+
"offsets": [[df.iloc[i]["offset_start"], df.iloc[i]["offset_end"]]],
|
| 272 |
+
"normalized": [],
|
| 273 |
+
}
|
| 274 |
+
)
|
| 275 |
+
i += 1
|
| 276 |
+
elif df.iloc[i]["span"] is not None:
|
| 277 |
+
ent = df[df["span"] == df.iloc[i]["span"]]
|
| 278 |
+
out["entities"].append(
|
| 279 |
+
{
|
| 280 |
+
"id": f'{uid}-{df.iloc[i]["passage_token_id"]}',
|
| 281 |
+
"type": df.iloc[i]["lab"],
|
| 282 |
+
"text": [text[ent.iloc[0]["offset_start"] : ent.iloc[-1]["offset_end"]]],
|
| 283 |
+
"offsets": [[ent.iloc[0]["offset_start"], ent.iloc[-1]["offset_end"]]],
|
| 284 |
+
"normalized": [],
|
| 285 |
+
}
|
| 286 |
+
)
|
| 287 |
+
i += len(ent)
|
| 288 |
+
else:
|
| 289 |
+
i += 1
|
| 290 |
+
|
| 291 |
+
return out
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def _sort_files(filepath):
|
| 295 |
+
doc_ids = os.listdir(filepath)
|
| 296 |
+
doc_ids = [int(doc_ids[i].split(".")[0]) for i in range(len(doc_ids))]
|
| 297 |
+
doc_ids = sorted(doc_ids)
|
| 298 |
+
doc_ids = [f"{doc_ids[i]}.tsv" for i in range(len(doc_ids))]
|
| 299 |
+
return doc_ids
|
| 300 |
+
|