Upload 3 files
Browse filesnew version of e3c using bigbio format
Files changed (3)
- README.md+122-79
- bigbiohub.pyAdded+587
- e3c.py+247-375
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485861 unmodified line88899091929315 unmodified lines109110111112---dataset_info:features:- name: textdtype: string- name: tokenssequence: string- name: tokens_offsetssequence:sequence: int32- name: clinical_entity_tagssequence:class_label:names:'0': O'1': B-CLINENTITY'2': I-CLINENTITY- name: clinical_entity_cuidsequence: string- name: temporal_information_tagssequence:class_label:names:'0': O'1': B-EVENT'2': B-ACTOR'3': B-BODYPART'4': B-TIMEX3'5': B-RML'6': I-EVENT'7': I-ACTOR'8': I-BODYPART'9': I-TIMEX3'10': I-RMLconfig_name: e3csplits:- name: en.layer1num_bytes: 1632165num_examples: 1520- name: en.layer2num_bytes: 3263885num_examples: 2873- name: en.layer2.validationnum_bytes: 371196num_examples: 334- name: es.layer1num_bytes: 1599169num_examples: 1134- name: es.layer2num_bytes: 3192361num_examples: 2347- name: es.layer2.validationnum_bytes: 352193num_examples: 261- name: eu.layer1num_bytes: 1931109num_examples: 3126- name: eu.layer2num_bytes: 1066405num_examples: 1594- name: eu.layer2.validationnum_bytes: 279306num_examples: 468- name: fr.layer1num_bytes: 1610663num_examples: 1109- name: fr.layer2num_bytes: 3358033num_examples: 2389- name: fr.layer2.validationnum_bytes: 361816num_examples: 293- name: it.layer1num_bytes: 1633613num_examples: 1146- name: it.layer2num_bytes: 3373977num_examples: 2436- name: it.layer2.validationnum_bytes: 366932num_examples: 275download_size: 230213492dataset_size: 24392823---# Dataset Card for E3C1 unmodified line## Dataset Description- **Homepage:** https://github.com/hltfbk/E3C-Corpus- **Public:** True- **Tasks:** NER,RE15 unmodified linesurl = {https://uts.nlm.nih.gov/uts/umls/home},year = {2021},}```1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281 unmodified line13013113213313413513615 unmodified lines152153154155---dataset_info:features:- name: iddtype: string- name: document_iddtype: int32- name: textdtype: string- name: passageslist:- name: iddtype: string- name: textdtype: string- name: offsetslist: int32- name: entitieslist:- name: iddtype: string- name: typedtype: string- name: textdtype: string- name: offsetslist: int32- name: semantic_type_iddtype: string- name: roledtype: string- name: relationslist:- name: iddtype: string- name: typedtype: string- name: contextualAspectdtype: string- name: contextualModalitydtype: string- name: degreedtype: string- name: docTimeReldtype: string- name: eventTypedtype: string- name: permanencedtype: string- name: polaritydtype: string- name: functionInDocumentdtype: string- name: timex3Classdtype: string- name: valuedtype: string- name: concept_1dtype: string- name: concept_2dtype: stringconfig_name: e3c_sourcesplits:- name: en.layer1num_bytes: 1645819num_examples: 84- name: en.layer2num_bytes: 881290num_examples: 171- name: en.layer2.validationnum_bytes: 101379num_examples: 19- name: en.layer3num_bytes: 7672589num_examples: 9779- name: es.layer1num_bytes: 1398186num_examples: 81- name: es.layer2num_bytes: 907515num_examples: 162- name: es.layer2.validationnum_bytes: 103936num_examples: 18- name: es.layer3num_bytes: 6656630num_examples: 1876- name: eu.layer1num_bytes: 2217479num_examples: 90- name: eu.layer2num_bytes: 306291num_examples: 111- name: eu.layer2.validationnum_bytes: 95276num_examples: 10- name: eu.layer3num_bytes: 4656179num_examples: 1232- name: fr.layer1num_bytes: 1474138num_examples: 81- name: fr.layer2num_bytes: 905084num_examples: 168- name: fr.layer2.validationnum_bytes: 101701num_examples: 18- name: fr.layer3num_bytes: 457927491num_examples: 25740- name: it.layer1num_bytes: 1036560num_examples: 86- name: it.layer2num_bytes: 888138num_examples: 174- name: it.layer2.validationnum_bytes: 99549num_examples: 18- name: it.layer3num_bytes: 86243680num_examples: 10213download_size: 230213492dataset_size: 575318910---# Dataset Card for E3C1 unmodified line## Dataset Description- **Homepage:** https://github.com/hltfbk/E3C-Corpus- **PubMed** False- **Public:** True- **Tasks:** NER,RE15 unmodified linesurl = {https://uts.nlm.nih.gov/uts/umls/home},year = {2021},}```
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587# mypy: ignore-errors# flake8: noqaimport loggingfrom collections import defaultdictfrom dataclasses import dataclassfrom enum import Enumfrom pathlib import Pathfrom types import SimpleNamespacefrom typing import TYPE_CHECKING, Dict, Iterable, List, Tuple
import datasets
if TYPE_CHECKING: import bioc
logger = logging.getLogger(__name__)
BigBioValues = SimpleNamespace(NULL="<BB_NULL_STR>")
@dataclassclass BigBioConfig(datasets.BuilderConfig): """BuilderConfig for BigBio."""
name: str = None version: datasets.Version = None description: str = None schema: str = None subset_id: str = None
class Tasks(Enum): NAMED_ENTITY_RECOGNITION = "NER" NAMED_ENTITY_DISAMBIGUATION = "NED" EVENT_EXTRACTION = "EE" RELATION_EXTRACTION = "RE" COREFERENCE_RESOLUTION = "COREF" QUESTION_ANSWERING = "QA" TEXTUAL_ENTAILMENT = "TE" SEMANTIC_SIMILARITY = "STS" TEXT_PAIRS_CLASSIFICATION = "TXT2CLASS" PARAPHRASING = "PARA" TRANSLATION = "TRANSL" SUMMARIZATION = "SUM" TEXT_CLASSIFICATION = "TXTCLASS"
entailment_features = datasets.Features( { "id": datasets.Value("string"), "premise": datasets.Value("string"), "hypothesis": datasets.Value("string"), "label": datasets.Value("string"), })
pairs_features = datasets.Features( { "id": datasets.Value("string"), "document_id": datasets.Value("string"), "text_1": datasets.Value("string"), "text_2": datasets.Value("string"), "label": datasets.Value("string"), })
qa_features = datasets.Features( { "id": datasets.Value("string"), "question_id": datasets.Value("string"), "document_id": datasets.Value("string"), "question": datasets.Value("string"), "type": datasets.Value("string"), "choices": [datasets.Value("string")], "context": datasets.Value("string"), "answer": datasets.Sequence(datasets.Value("string")), })
text_features = datasets.Features( { "id": datasets.Value("string"), "document_id": datasets.Value("string"), "text": datasets.Value("string"), "labels": [datasets.Value("string")], })
text2text_features = datasets.Features( { "id": datasets.Value("string"), "document_id": datasets.Value("string"), "text_1": datasets.Value("string"), "text_2": datasets.Value("string"), "text_1_name": datasets.Value("string"), "text_2_name": datasets.Value("string"), })
kb_features = datasets.Features( { "id": datasets.Value("string"), "document_id": datasets.Value("string"), "passages": [ { "id": datasets.Value("string"), "type": datasets.Value("string"), "text": datasets.Sequence(datasets.Value("string")), "offsets": datasets.Sequence([datasets.Value("int32")]), } ], "entities": [ { "id": datasets.Value("string"), "type": datasets.Value("string"), "text": datasets.Sequence(datasets.Value("string")), "offsets": datasets.Sequence([datasets.Value("int32")]), "normalized": [ { "db_name": datasets.Value("string"), "db_id": datasets.Value("string"), } ], } ], "events": [ { "id": datasets.Value("string"), "type": datasets.Value("string"), # refers to the text_bound_annotation of the trigger "trigger": { "text": datasets.Sequence(datasets.Value("string")), "offsets": datasets.Sequence([datasets.Value("int32")]), }, "arguments": [ { "role": datasets.Value("string"), "ref_id": datasets.Value("string"), } ], } ], "coreferences": [ { "id": datasets.Value("string"), "entity_ids": datasets.Sequence(datasets.Value("string")), } ], "relations": [ { "id": datasets.Value("string"), "type": datasets.Value("string"), "arg1_id": datasets.Value("string"), "arg2_id": datasets.Value("string"), "normalized": [ { "db_name": datasets.Value("string"), "db_id": datasets.Value("string"), } ], } ], })
TASK_TO_SCHEMA = { Tasks.NAMED_ENTITY_RECOGNITION.name: "KB", Tasks.NAMED_ENTITY_DISAMBIGUATION.name: "KB", Tasks.EVENT_EXTRACTION.name: "KB", Tasks.RELATION_EXTRACTION.name: "KB", Tasks.COREFERENCE_RESOLUTION.name: "KB", Tasks.QUESTION_ANSWERING.name: "QA", Tasks.TEXTUAL_ENTAILMENT.name: "TE", Tasks.SEMANTIC_SIMILARITY.name: "PAIRS", Tasks.TEXT_PAIRS_CLASSIFICATION.name: "PAIRS", Tasks.PARAPHRASING.name: "T2T", Tasks.TRANSLATION.name: "T2T", Tasks.SUMMARIZATION.name: "T2T", Tasks.TEXT_CLASSIFICATION.name: "TEXT",}
SCHEMA_TO_TASKS = defaultdict(set)for task, schema in TASK_TO_SCHEMA.items(): SCHEMA_TO_TASKS[schema].add(task)SCHEMA_TO_TASKS = dict(SCHEMA_TO_TASKS)
VALID_TASKS = set(TASK_TO_SCHEMA.keys())VALID_SCHEMAS = set(TASK_TO_SCHEMA.values())
SCHEMA_TO_FEATURES = { "KB": kb_features, "QA": qa_features, "TE": entailment_features, "T2T": text2text_features, "TEXT": text_features, "PAIRS": pairs_features,}
def get_texts_and_offsets_from_bioc_ann(ann: "bioc.BioCAnnotation") -> Tuple:
offsets = [(loc.offset, loc.offset + loc.length) for loc in ann.locations]
text = ann.text
if len(offsets) > 1: i = 0 texts = [] for start, end in offsets: chunk_len = end - start texts.append(text[i : chunk_len + i]) i += chunk_len while i < len(text) and text[i] == " ": i += 1 else: texts = [text]
return offsets, texts
def remove_prefix(a: str, prefix: str) -> str: if a.startswith(prefix): a = a[len(prefix) :] return a
def parse_brat_file( txt_file: Path, annotation_file_suffixes: List[str] = None, parse_notes: bool = False,) -> Dict: """ Parse a brat file into the schema defined below. `txt_file` should be the path to the brat '.txt' file you want to parse, e.g. 'data/1234.txt' Assumes that the annotations are contained in one or more of the corresponding '.a1', '.a2' or '.ann' files, e.g. 'data/1234.ann' or 'data/1234.a1' and 'data/1234.a2'. Will include annotator notes, when `parse_notes == True`. brat_features = datasets.Features( { "id": datasets.Value("string"), "document_id": datasets.Value("string"), "text": datasets.Value("string"), "text_bound_annotations": [ # T line in brat, e.g. type or event trigger { "offsets": datasets.Sequence([datasets.Value("int32")]), "text": datasets.Sequence(datasets.Value("string")), "type": datasets.Value("string"), "id": datasets.Value("string"), } ], "events": [ # E line in brat { "trigger": datasets.Value( "string" ), # refers to the text_bound_annotation of the trigger, "id": datasets.Value("string"), "type": datasets.Value("string"), "arguments": datasets.Sequence( { "role": datasets.Value("string"), "ref_id": datasets.Value("string"), } ), } ], "relations": [ # R line in brat { "id": datasets.Value("string"), "head": { "ref_id": datasets.Value("string"), "role": datasets.Value("string"), }, "tail": { "ref_id": datasets.Value("string"), "role": datasets.Value("string"), }, "type": datasets.Value("string"), } ], "equivalences": [ # Equiv line in brat { "id": datasets.Value("string"), "ref_ids": datasets.Sequence(datasets.Value("string")), } ], "attributes": [ # M or A lines in brat { "id": datasets.Value("string"), "type": datasets.Value("string"), "ref_id": datasets.Value("string"), "value": datasets.Value("string"), } ], "normalizations": [ # N lines in brat { "id": datasets.Value("string"), "type": datasets.Value("string"), "ref_id": datasets.Value("string"), "resource_name": datasets.Value( "string" ), # Name of the resource, e.g. "Wikipedia" "cuid": datasets.Value( "string" ), # ID in the resource, e.g. 534366 "text": datasets.Value( "string" ), # Human readable description/name of the entity, e.g. "Barack Obama" } ], ### OPTIONAL: Only included when `parse_notes == True` "notes": [ # # lines in brat { "id": datasets.Value("string"), "type": datasets.Value("string"), "ref_id": datasets.Value("string"), "text": datasets.Value("string"), } ], }, ) """
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 = 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 BigBioValues.NULL
info = fields[1].split()
ann["type"] = info[0] ann["ref_id"] = info[1] example["notes"].append(ann)
return example
def brat_parse_to_bigbio_kb(brat_parse: Dict) -> Dict: """ Transform a brat parse (conforming to the standard brat schema) obtained with `parse_brat_file` into a dictionary conforming to the `bigbio-kb` schema (as defined in ../schemas/kb.py) :param brat_parse: """
unified_example = {}
# Prefix all ids with document id to ensure global uniqueness, # because brat ids are only unique within their document id_prefix = brat_parse["document_id"] + "_"
# identical unified_example["document_id"] = brat_parse["document_id"] unified_example["passages"] = [ { "id": id_prefix + "_text", "type": "abstract", "text": [brat_parse["text"]], "offsets": [[0, len(brat_parse["text"])]], } ]
# get normalizations ref_id_to_normalizations = defaultdict(list) for normalization in brat_parse["normalizations"]: ref_id_to_normalizations[normalization["ref_id"]].append( { "db_name": normalization["resource_name"], "db_id": normalization["cuid"], } )
# separate entities and event triggers unified_example["events"] = [] non_event_ann = brat_parse["text_bound_annotations"].copy() for event in brat_parse["events"]: event = event.copy() event["id"] = id_prefix + event["id"] trigger = next( tr for tr in brat_parse["text_bound_annotations"] if tr["id"] == event["trigger"] ) if trigger in non_event_ann: non_event_ann.remove(trigger) event["trigger"] = { "text": trigger["text"].copy(), "offsets": trigger["offsets"].copy(), } for argument in event["arguments"]: argument["ref_id"] = id_prefix + argument["ref_id"]
unified_example["events"].append(event)
unified_example["entities"] = [] anno_ids = [ref_id["id"] for ref_id in non_event_ann] for ann in non_event_ann: entity_ann = ann.copy() entity_ann["id"] = id_prefix + entity_ann["id"] entity_ann["normalized"] = ref_id_to_normalizations[ann["id"]] unified_example["entities"].append(entity_ann)
# massage relations unified_example["relations"] = [] skipped_relations = set() for ann in brat_parse["relations"]: if ann["head"]["ref_id"] not in anno_ids or ann["tail"]["ref_id"] not in anno_ids: skipped_relations.add(ann["id"]) continue unified_example["relations"].append( { "arg1_id": id_prefix + ann["head"]["ref_id"], "arg2_id": id_prefix + ann["tail"]["ref_id"], "id": id_prefix + ann["id"], "type": ann["type"], "normalized": [], } ) if len(skipped_relations) > 0: example_id = brat_parse["document_id"] logger.info( f"Example:{example_id}: The `bigbio_kb` schema allows `relations` only between entities." f" Skip (for now): " f"{list(skipped_relations)}" )
# get coreferences unified_example["coreferences"] = [] for i, ann in enumerate(brat_parse["equivalences"], start=1): is_entity_cluster = True for ref_id in ann["ref_ids"]: if not ref_id.startswith("T"): # not textbound -> no entity is_entity_cluster = False elif ref_id not in anno_ids: # event trigger -> no entity is_entity_cluster = False if is_entity_cluster: entity_ids = [id_prefix + i for i in ann["ref_ids"]] unified_example["coreferences"].append( {"id": id_prefix + str(i), "entity_ids": entity_ids} ) return unified_example123456789101112135 unmodified lines1920212223242526272 unmodified lines30313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431import osfrom typing import Iteratorimport datasetsfrom bs4 import BeautifulSoup, ResultSetfrom datasets import DownloadManagerfrom syntok.tokenizer import Tokenizertok = Tokenizer()_CITATION = """\@report{Magnini2021,5 unmodified linesurl = {https://uts.nlm.nih.gov/uts/umls/home},year = {2021},}"""_DESCRIPTION = """\The European Clinical Case Corpus (E3C) project aims at collecting and \annotating a large corpus of clinical documents in five European languages (Spanish, \2 unmodified linesinformation about clinical entities based on medical taxonomies, to be used for semantic reasoning."""_URL = "https://github.com/hltfbk/E3C-Corpus/archive/refs/tags/v2.0.0.zip"class E3CConfig(datasets.BuilderConfig):"""BuilderConfig for E3C."""def __init__(self, **kwargs):"""BuilderConfig for E3C.Args:**kwargs: keyword arguments forwarded to super."""super(E3CConfig, self).__init__(**kwargs)class E3C(datasets.GeneratorBasedBuilder):VERSION = datasets.Version("1.1.0")BUILDER_CONFIGS = [E3CConfig(name="e3c",version=VERSION,description="this is an implementation of the E3C dataset",),]def _info(self):"""This method specifies the DatasetInfo which contains information and typings."""features = datasets.Features({"text": datasets.Value("string"),"tokens": datasets.Sequence(datasets.Value("string")),"tokens_offsets": datasets.Sequence(datasets.Sequence(datasets.Value("int32"))),"clinical_entity_tags": datasets.Sequence(datasets.features.ClassLabel(names=["O","B-CLINENTITY","I-CLINENTITY",],),),"clinical_entity_cuid": datasets.Sequence(datasets.Value("string"),),"temporal_information_tags": datasets.Sequence(datasets.features.ClassLabel(names=["O","B-EVENT","B-ACTOR","B-BODYPART","B-TIMEX3","B-RML","I-EVENT","I-ACTOR","I-BODYPART","I-TIMEX3","I-RML",],),),})return datasets.DatasetInfo(description=_DESCRIPTION,features=features,citation=_CITATION,supervised_keys=None,)def _split_generators(self, dl_manager: DownloadManager) -> list[datasets.SplitGenerator]:"""Returns SplitGenerators who contains all the difference splits of the dataset.Each language has its own split and each split has 3 different layers (sub-split):- layer 1: full manual annotation of clinical entities, temporal information andfactuality, for benchmarking and linguistic analysis.- layer 2: semi-automatic annotation of clinical entities- layer 3: non-annotated documentsArgs:dl_manager: A `datasets.utils.DownloadManager` that can be used to download andextract URLs.Returns:A list of `datasets.SplitGenerator`. Contains all subsets of the dataset depending onthe language and the layer."""url = _URLdata_dir = dl_manager.download_and_extract(url)return [datasets.SplitGenerator(name="en.layer1",gen_kwargs={"filepath": os.path.join(data_dir,"E3C-Corpus-2.0.0/data_annotation","English","layer1",),},),datasets.SplitGenerator(name="en.layer2",gen_kwargs={"filepath": os.path.join(data_dir,"E3C-Corpus-2.0.0/data_annotation","English","layer2",),},),datasets.SplitGenerator(name="en.layer2.validation",gen_kwargs={"filepath": os.path.join(data_dir,"E3C-Corpus-2.0.0/data_validation","English","layer2",),},),datasets.SplitGenerator(name="es.layer1",gen_kwargs={"filepath": os.path.join(data_dir,"E3C-Corpus-2.0.0/data_annotation","Spanish","layer1",),},),datasets.SplitGenerator(name="es.layer2",gen_kwargs={"filepath": os.path.join(data_dir,"E3C-Corpus-2.0.0/data_annotation","Spanish","layer2",),},),datasets.SplitGenerator(name="es.layer2.validation",gen_kwargs={"filepath": os.path.join(data_dir,"E3C-Corpus-2.0.0/data_validation","Spanish","layer2",),},),datasets.SplitGenerator(name="eu.layer1",gen_kwargs={"filepath": os.path.join(data_dir,"E3C-Corpus-2.0.0/data_annotation","Basque","layer1",),},),datasets.SplitGenerator(name="eu.layer2",gen_kwargs={"filepath": os.path.join(data_dir,"E3C-Corpus-2.0.0/data_annotation","Basque","layer2",),},),datasets.SplitGenerator(name="eu.layer2.validation",gen_kwargs={"filepath": os.path.join(data_dir,"E3C-Corpus-2.0.0/data_validation","Basque","layer2",),},),datasets.SplitGenerator(name="fr.layer1",gen_kwargs={"filepath": os.path.join(data_dir,"E3C-Corpus-2.0.0/data_annotation","French","layer1",),},),datasets.SplitGenerator(name="fr.layer2",gen_kwargs={"filepath": os.path.join(data_dir,"E3C-Corpus-2.0.0/data_annotation","French","layer2",),},),datasets.SplitGenerator(name="fr.layer2.validation",gen_kwargs={"filepath": os.path.join(data_dir,"E3C-Corpus-2.0.0/data_validation","French","layer2",),},),datasets.SplitGenerator(name="it.layer1",gen_kwargs={"filepath": os.path.join(data_dir,"E3C-Corpus-2.0.0/data_annotation","Italian","layer1",),},),datasets.SplitGenerator(name="it.layer2",gen_kwargs={"filepath": os.path.join(data_dir,"E3C-Corpus-2.0.0/data_annotation","Italian","layer2",),},),datasets.SplitGenerator(name="it.layer2.validation",gen_kwargs={"filepath": os.path.join(data_dir,"E3C-Corpus-2.0.0/data_validation","Italian","layer2",),},),]@staticmethoddef get_annotations(entities: ResultSet, text: str) -> list:"""Extract the offset, the text and the type of the entity.Args:entities: The entities to extract.text: The text of the document.Returns:A list of list containing the offset, the text and the type of the entity."""return [[int(entity.get("begin")),int(entity.get("end")),text[int(entity.get("begin")) : int(entity.get("end"))],]for entity in entities]def get_clinical_annotations(self, entities: ResultSet, text: str) -> list:"""Extract the offset, the text and the type of the entity.Args:entities: The entities to extract.text: The text of the document.Returns:A list of list containing the offset, the text and the type of the entity."""return [[int(entity.get("begin")),int(entity.get("end")),text[int(entity.get("begin")) : int(entity.get("end"))],entity.get("entityID"),]for entity in entities]def get_parsed_data(self, filepath: str):"""Parse the data from the E3C dataset and store it in a dictionary.Iterate over the files in the dataset and parse for each file the following entities:- CLINENTITY- EVENT- ACTOR- BODYPART- TIMEX3- RMLfor each entity, we extract the offset, the text and the type of the entity.Args:filepath: The path to the folder containing the files to parse."""for root, _, files in os.walk(filepath):for file in files:with open(f"{root}/{file}") as soup_file:soup = BeautifulSoup(soup_file, "xml")text = soup.find("cas:Sofa").get("sofaString")yield {"CLINENTITY": self.get_clinical_annotations(soup.find_all("custom:CLINENTITY"), text),"EVENT": self.get_annotations(soup.find_all("custom:EVENT"), text),"ACTOR": self.get_annotations(soup.find_all("custom:ACTOR"), text),"BODYPART": self.get_annotations(soup.find_all("custom:BODYPART"), text),"TIMEX3": self.get_annotations(soup.find_all("custom:TIMEX3"), text),"RML": self.get_annotations(soup.find_all("custom:RML"), text),"SENTENCE": self.get_annotations(soup.find_all("type4:Sentence"), text),"TOKENS": self.get_annotations(soup.find_all("type4:Token"), text),}def _generate_examples(self, filepath) -> Iterator:"""Yields examples as (key, example) tuples.Args:filepath: The path to the folder containing the files to parse.Yields:an example containing four fields: the text, the annotations, the tokens offsets andthe sentences."""guid = 0for content in self.get_parsed_data(filepath):for sentence in content["SENTENCE"]:tokens = [(token.offset + sentence[0],token.offset + sentence[0] + len(token.value),token.value,)for token in list(tok.tokenize(sentence[-1]))]filtered_tokens = list(filter(lambda token: token[0] >= sentence[0] and token[1] <= sentence[1],tokens,))tokens_offsets = [[token[0] - sentence[0], token[1] - sentence[0]] for token in filtered_tokens]clinical_labels = ["O"] * len(filtered_tokens)clinical_cuid = ["CUI_LESS"] * len(filtered_tokens)temporal_information_labels = ["O"] * len(filtered_tokens)for entity_type in ["CLINENTITY","EVENT","ACTOR","BODYPART","TIMEX3","RML",]:if len(content[entity_type]) != 0:for entities in list(content[entity_type],):annotated_tokens = [idx_tokenfor idx_token, token in enumerate(filtered_tokens)if token[0] >= entities[0] and token[1] <= entities[1]]for idx_token in annotated_tokens:if entity_type == "CLINENTITY":if idx_token == annotated_tokens[0]:clinical_labels[idx_token] = f"B-{entity_type}"else:clinical_labels[idx_token] = f"I-{entity_type}"clinical_cuid[idx_token] = entities[-1]else:if idx_token == annotated_tokens[0]:temporal_information_labels[idx_token] = f"B-{entity_type}"else:temporal_information_labels[idx_token] = f"I-{entity_type}"yield guid, {"text": sentence[-1],"tokens": list(map(lambda token: token[2], filtered_tokens)),"clinical_entity_tags": clinical_labels,"clinical_entity_cuid": clinical_cuid,"temporal_information_tags": temporal_information_labels,"tokens_offsets": tokens_offsets,}guid += 1if __name__ == "__main__":builder = E3C()builder.download_and_prepare()12345678910111213141516171819202122232425262728293031323334355 unmodified lines414243444546474849502 unmodified lines5354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303# 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."""The European Clinical Case Corpus (E3C) project aims at collecting and \annotating a large corpus of clinical documents in five European languages (Spanish, \Basque, English, French and Italian), which will be freely distributed. Annotations \include temporal information, to allow temporal reasoning on chronologies, and \information about clinical entities based on medical taxonomies, to be used for semantic reasoning."""import jsonimport osimport xml.etree.ElementTree as etfrom typing import Dict, Iterator, List, Tupleimport datasetsfrom .bigbiohub import BigBioConfig, Tasks_LOCAL = True_CITATION = """\@report{Magnini2021,5 unmodified linesurl = {https://uts.nlm.nih.gov/uts/umls/home},year = {2021},}"""_DATASETNAME = "e3c"_DESCRIPTION = """\The European Clinical Case Corpus (E3C) project aims at collecting and \annotating a large corpus of clinical documents in five European languages (Spanish, \2 unmodified linesinformation about clinical entities based on medical taxonomies, to be used for semantic reasoning."""_HOMEPAGE = "https://github.com/hltfbk/E3C-Corpus"_LICENSE = ""_URLS = {_DATASETNAME: "https://github.com/hltfbk/E3C-Corpus/archive/refs/tags/v2.0.0.zip",}_SUPPORTED_TASKS = [Tasks.NAMED_ENTITY_RECOGNITION, Tasks.RELATION_EXTRACTION]_SOURCE_VERSION = "2.0.0"_BIGBIO_VERSION = "1.0.0"class E3cDataset(datasets.GeneratorBasedBuilder):"""The European Clinical Case Corpus (E3C) is a multilingual corpus of clinical documents.The corpus is annotated with clinical entities and temporal information.The corpus is available in five languages: Spanish, Basque, English, French and Italian."""SOURCE_VERSION = datasets.Version(_SOURCE_VERSION)BIGBIO_VERSION = datasets.Version(_BIGBIO_VERSION)BUILDER_CONFIGS = [BigBioConfig(name=f"{_DATASETNAME}_source",version=SOURCE_VERSION,description=f"{_DATASETNAME} source schema",schema="source",subset_id=_DATASETNAME,),]DEFAULT_CONFIG_NAME = f"{_DATASETNAME}_source"def _info(self) -> datasets.DatasetInfo:# You can arbitrarily nest lists and dictionaries.# For iterables, use lists over tuples or `datasets.Sequence`features = datasets.Features({"id": datasets.Value("string"),"document_id": datasets.Value("int32"),"text": datasets.Value("string"),"passages": [{"id": datasets.Value("string"),"text": datasets.Value("string"),"offsets": [datasets.Value("int32")],}],"entities": [{"id": datasets.Value("string"),"type": datasets.Value("string"),"text": datasets.Value("string"),"offsets": [datasets.Value("int32")],"semantic_type_id": datasets.Value("string"),"role": datasets.Value("string"),}],"relations": [{"id": datasets.Value("string"),"type": datasets.Value("string"),"contextualAspect": datasets.Value("string"),"contextualModality": datasets.Value("string"),"degree": datasets.Value("string"),"docTimeRel": datasets.Value("string"),"eventType": datasets.Value("string"),"permanence": datasets.Value("string"),"polarity": datasets.Value("string"),"functionInDocument": datasets.Value("string"),"timex3Class": datasets.Value("string"),"value": datasets.Value("string"),"concept_1": datasets.Value("string"),"concept_2": datasets.Value("string"),}],})return datasets.DatasetInfo(description=_DESCRIPTION,features=features,homepage=_HOMEPAGE,license=_LICENSE,citation=_CITATION,)def _split_generators(self, dl_manager) -> List[datasets.SplitGenerator]:"""Returns SplitGenerators."""urls = _URLS[_DATASETNAME]data_dir = dl_manager.download_and_extract(urls)paths = {"en.layer1": "data_annotation/English/layer1","en.layer2": "data_annotation/English/layer2","en.layer2.validation": "data_validation/English/layer2","en.layer3": "data_collection/English/layer3","es.layer1": "data_annotation/Spanish/layer1","es.layer2": "data_annotation/Spanish/layer2","es.layer2.validation": "data_validation/Spanish/layer2","es.layer3": "data_collection/Spanish/layer3","eu.layer1": "data_annotation/Basque/layer1","eu.layer2": "data_annotation/Basque/layer2","eu.layer2.validation": "data_validation/Basque/layer2","eu.layer3": "data_collection/Basque/layer3","fr.layer1": "data_annotation/French/layer1","fr.layer2": "data_annotation/French/layer2","fr.layer2.validation": "data_validation/French/layer2","fr.layer3": "data_collection/French/layer3","it.layer1": "data_annotation/Italian/layer1","it.layer2": "data_annotation/Italian/layer2","it.layer2.validation": "data_validation/Italian/layer2","it.layer3": "data_collection/Italian/layer3",}return [datasets.SplitGenerator(name=split,# Whatever you put in gen_kwargs will be passed to _generate_examplesgen_kwargs={"filepath": os.path.join(data_dir, "E3C-Corpus-2.0.0", path),"split": "train",},)for split, path in paths.items()]def _generate_examples(self, filepath, split: str) -> Iterator[Tuple[int, Dict]]:"""Yields examples as (key, example) tuples."""guid = 0for folder, _, files in os.walk(filepath):for file in files:with open(f"{folder}/{file}") as document:if "layer3" not in folder:root = et.fromstring(document.read())annotations: dict = {}for child in root:annotations.setdefault(child.tag, []).append(child.attrib | {"type": child.tag.split("}")[1]})text = annotations["{http:///uima/cas.ecore}Sofa"][0]["sofaString"]links = {link["{http://www.omg.org/XMI}id"]: linkfor link in [*annotations.get("{http:///webanno/custom.ecore}EVENTTLINKLink", []),*annotations.get("{http:///webanno/custom.ecore}RMLPERTAINSTOLink", []),*annotations.get("{http:///webanno/custom.ecore}TIMEX3TimexLinkLink", []),]}joined_relations = []for relation in [*annotations.get("{http:///webanno/custom.ecore}EVENT", []),*annotations.get("{http:///webanno/custom.ecore}TIMEX3", []),*annotations.get("{http:///webanno/custom.ecore}RML", []),]:link_ids = []if "TLINK" in relation.keys():link_ids = relation["TLINK"].split(" ")elif "PERTAINSTO" in relation.keys():link_ids = relation["PERTAINSTO"].split(" ")elif "timexLink" in relation.keys():link_ids = relation["timexLink"].split(" ")elif not link_ids:joined_relations.append(relation | {"source": relation["{http://www.omg.org/XMI}id"]})if link_ids != [""]:for link_id in link_ids:joined_relations.append(relation| links[link_id]| {"source": relation["{http://www.omg.org/XMI}id"]})yield guid, {"id": "e3c","document_id": guid,"text": text,"passages": [{"text": text[int(sentence["begin"]) : int(sentence["end"])],"id": sentence["{http://www.omg.org/XMI}id"],"offsets": [int(sentence["begin"]), int(sentence["end"])],}for sentence in annotations["{http:///de/tudarmstadt/ukp/dkpro/core""/api/segmentation/type.ecore}Sentence"]],"entities": [{"text": text[int(annotation["begin"]) : int(annotation["end"])],"offsets": [int(annotation["begin"]), int(annotation["end"])],"id": annotation["{http://www.omg.org/XMI}id"],"semantic_type_id": annotation.get("entityID", ""),"role": annotation.get("role", ""),"type": annotation.get("type"),}for annotation in [*annotations.get("{http:///webanno/custom.ecore}EVENT", []),*annotations.get("{http:///webanno/custom.ecore}CLINENTITY", []),*annotations.get("{http:///webanno/custom.ecore}BODYPART", []),*annotations.get("{http:///webanno/custom.ecore}ACTOR", []),*annotations.get("{http:///webanno/custom.ecore}RML", []),*annotations.get("{http:///webanno/custom.ecore}TIMEX3", []),]],"relations": [{"id": relation["{http://www.omg.org/XMI}id"],"type": relation.get("type"),"contextualAspect": relation.get("contextualAspect", ""),"contextualModality": relation.get("contextualModality", ""),"degree": relation.get("degree", ""),"docTimeRel": relation.get("docTimeRel", ""),"eventType": relation.get("eventType", ""),"permanence": relation.get("permanence", ""),"polarity": relation.get("polarity", ""),"functionInDocument": relation.get("functionInDocument", ""),"timex3Class": relation.get("timex3Class", ""),"value": relation.get("value", ""),"concept_1": relation.get("source"),"concept_2": relation.get("target", ""),}for relation in joined_relations],}else:unannotated_text = json.load(document)yield guid, {"id": "e3c","document_id": guid,"text": unannotated_text["text"],"passages": [],"entities": [],"relations": [],}guid += 1
README.md+122-79
bigbiohub.pyAdded+587
e3c.py+247-375