File size: 9,068 Bytes
1ef2db4 d0a3f11 1ef2db4 06be6e9 1ef2db4 06be6e9 1ef2db4 06be6e9 1ef2db4 06be6e9 1ef2db4 06be6e9 1ef2db4 06be6e9 1ef2db4 06be6e9 1ef2db4 06be6e9 1ef2db4 06be6e9 1ef2db4 06be6e9 1ef2db4 06be6e9 1ef2db4 06be6e9 1ef2db4 06be6e9 1ef2db4 d0a3f11 1ef2db4 06be6e9 1ef2db4 06be6e9 |
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 |
from dataclasses import dataclass
from typing import Any, Dict, Optional, Union
import datasets
from pytorch_ie.annotations import BinaryRelation, LabeledSpan
from pytorch_ie.documents import (
AnnotationLayer,
TextBasedDocument,
TextDocumentWithLabeledSpansAndBinaryRelations,
TextDocumentWithLabeledSpansBinaryRelationsAndLabeledPartitions,
annotation_field,
)
from pie_datasets import GeneratorBasedBuilder
@dataclass
class DrugprotDocument(TextBasedDocument):
title: Optional[str] = None
abstract: Optional[str] = None
entities: AnnotationLayer[LabeledSpan] = annotation_field(target="text")
relations: AnnotationLayer[BinaryRelation] = annotation_field(target="entities")
@dataclass
class DrugprotBigbioDocument(TextBasedDocument):
passages: AnnotationLayer[LabeledSpan] = annotation_field(target="text")
entities: AnnotationLayer[LabeledSpan] = annotation_field(target="text")
relations: AnnotationLayer[BinaryRelation] = annotation_field(target="entities")
def example2drugprot(example: Dict[str, Any]) -> DrugprotDocument:
metadata = {"entity_ids": [], "relation_ids": []}
id2labeled_span: Dict[str, LabeledSpan] = {}
document = DrugprotDocument(
text=example["text"],
title=example["title"],
abstract=example["abstract"],
id=example["document_id"],
metadata=metadata,
)
for span in example["entities"]:
labeled_span = LabeledSpan(
start=span["offset"][0],
end=span["offset"][1],
label=span["type"],
)
document.entities.append(labeled_span)
entity_id = span["id"].split("_")[1]
document.metadata["entity_ids"].append(entity_id)
id2labeled_span[entity_id] = labeled_span
for relation in example["relations"]:
arg1_id = relation["arg1_id"].split("_")[1]
arg2_id = relation["arg2_id"].split("_")[1]
document.relations.append(
BinaryRelation(
head=id2labeled_span[arg1_id],
tail=id2labeled_span[arg2_id],
label=relation["type"],
)
)
relation_id = "R" + relation["id"].split("_")[1]
document.metadata["relation_ids"].append(relation_id)
return document
def example2drugprot_bigbio(example: Dict[str, Any]) -> DrugprotBigbioDocument:
text = " ".join([" ".join(passage["text"]) for passage in example["passages"]])
doc_id = example["document_id"]
metadata = {"entity_ids": [], "relation_ids": []}
id2labeled_span: Dict[str, LabeledSpan] = {}
document = DrugprotBigbioDocument(
text=text,
id=doc_id,
metadata=metadata,
)
for passage in example["passages"]:
document.passages.append(
LabeledSpan(
start=passage["offsets"][0][0],
end=passage["offsets"][0][1],
label=passage["type"],
)
)
# We sort labels and relation to always have a deterministic order for testing purposes.
for span in example["entities"]:
labeled_span = LabeledSpan(
start=span["offsets"][0][0],
end=span["offsets"][0][1],
label=span["type"],
)
document.entities.append(labeled_span)
entity_id = span["id"].split("_")[1]
document.metadata["entity_ids"].append(entity_id)
id2labeled_span[entity_id] = labeled_span
for relation in example["relations"]:
arg1_id = relation["arg1_id"].split("_")[1]
arg2_id = relation["arg2_id"].split("_")[1]
document.relations.append(
BinaryRelation(
head=id2labeled_span[arg1_id],
tail=id2labeled_span[arg2_id],
label=relation["type"],
)
)
relation_id = "R" + relation["id"].split("_")[1]
document.metadata["relation_ids"].append(relation_id)
return document
def drugprot2example(doc: DrugprotDocument) -> Dict[str, Any]:
entities = []
for i, entity in enumerate(doc.entities):
entities.append(
{
"id": doc.id + "_" + doc.metadata["entity_ids"][i],
"type": entity.label,
"text": doc.text[entity.start : entity.end],
"offset": [entity.start, entity.end],
}
)
relations = []
for i, relation in enumerate(doc.relations):
relations.append(
{
"id": doc.id + "_" + doc.metadata["relation_ids"][i][1:],
"arg1_id": doc.id
+ "_"
+ doc.metadata["entity_ids"][doc.entities.index(relation.head)],
"arg2_id": doc.id
+ "_"
+ doc.metadata["entity_ids"][doc.entities.index(relation.tail)],
"type": relation.label,
}
)
return {
"document_id": doc.id,
"title": doc.title,
"abstract": doc.abstract,
"text": doc.text,
"entities": entities,
"relations": relations,
}
def drugprot_bigbio2example(doc: DrugprotBigbioDocument) -> Dict[str, Any]:
entities = []
for i, entity in enumerate(doc.entities):
entities.append(
{
"id": doc.id + "_" + doc.metadata["entity_ids"][i],
"normalized": [],
"offsets": [[entity.start, entity.end]],
"type": entity.label,
"text": [doc.text[entity.start : entity.end]],
}
)
relations = []
for i, relation in enumerate(doc.relations):
relations.append(
{
"id": doc.id + "_" + doc.metadata["relation_ids"][i][1:],
"arg1_id": doc.id
+ "_"
+ doc.metadata["entity_ids"][doc.entities.index(relation.head)],
"arg2_id": doc.id
+ "_"
+ doc.metadata["entity_ids"][doc.entities.index(relation.tail)],
"normalized": [],
"type": relation.label,
}
)
passages = []
for passage in doc.passages:
passages.append(
{
"id": doc.id + "_" + passage.label,
"text": [doc.text[passage.start : passage.end]],
"offsets": [[passage.start, passage.end]],
"type": passage.label,
}
)
return {
"coreferences": [],
"document_id": doc.id,
"entities": entities,
"events": [],
"id": doc.id,
"passages": passages,
"relations": relations,
}
class Drugprot(GeneratorBasedBuilder):
DOCUMENT_TYPES = {
"drugprot_source": DrugprotDocument,
"drugprot_bigbio_kb": DrugprotBigbioDocument,
}
BASE_DATASET_PATH = "bigbio/drugprot"
# This revision includes the "test_background" split (see https://github.com/bigscience-workshop/biomedical/pull/928)
BASE_DATASET_REVISION = "0cc98b3d292242e69adcfd2c3e5eea94baaca8ea"
BUILDER_CONFIGS = [
datasets.BuilderConfig(
name="drugprot_source",
version=datasets.Version("1.0.2"),
description="DrugProt source version",
),
datasets.BuilderConfig(
name="drugprot_bigbio_kb",
version=datasets.Version("1.0.0"),
description="DrugProt BigBio version",
),
]
@property
def document_converters(self):
if self.config.name == "drugprot_source":
return {
TextDocumentWithLabeledSpansAndBinaryRelations: {
"entities": "labeled_spans",
"relations": "binary_relations",
}
}
elif self.config.name == "drugprot_bigbio_kb":
return {
TextDocumentWithLabeledSpansBinaryRelationsAndLabeledPartitions: {
"passages": "labeled_partitions",
"entities": "labeled_spans",
"relations": "binary_relations",
}
}
else:
raise ValueError(f"Unknown dataset name: {self.config.name}")
def _generate_document(
self, example: Dict[str, Any], **kwargs
) -> Union[DrugprotDocument, DrugprotBigbioDocument]:
if self.config.name == "drugprot_source":
return example2drugprot(example)
elif self.config.name == "drugprot_bigbio_kb":
return example2drugprot_bigbio(example)
else:
raise ValueError(f"Unknown dataset config name: {self.config.name}")
def _generate_example(
self, document: Union[DrugprotDocument, DrugprotBigbioDocument], **kwargs
) -> Dict[str, Any]:
if isinstance(document, DrugprotBigbioDocument):
return drugprot_bigbio2example(document)
elif isinstance(document, DrugprotDocument):
return drugprot2example(document)
else:
raise ValueError(f"Unknown document type: {type(document)}")
|