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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import dataclasses
|
| 2 |
+
import logging
|
| 3 |
+
from typing import Any, Dict, List, Optional, Tuple
|
| 4 |
+
|
| 5 |
+
import datasets
|
| 6 |
+
import pytorch_ie
|
| 7 |
+
from pytorch_ie.annotations import BinaryRelation, LabeledSpan, _post_init_single_label
|
| 8 |
+
from pytorch_ie.core import Annotation, AnnotationList, Document, annotation_field
|
| 9 |
+
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def dl2ld(dict_of_lists: Dict[str, List[Any]]) -> List[Dict[str, Any]]:
|
| 14 |
+
return [dict(zip(dict_of_lists, t)) for t in zip(*dict_of_lists.values())]
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def ld2dl(
|
| 18 |
+
list_fo_dicts: List[Dict[str, Any]], keys: Optional[List[str]] = None
|
| 19 |
+
) -> Dict[str, List[Any]]:
|
| 20 |
+
keys = keys or list(list_fo_dicts[0])
|
| 21 |
+
return {k: [dic[k] for dic in list_fo_dicts] for k in keys}
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@dataclasses.dataclass(eq=True, frozen=True)
|
| 25 |
+
class Attribution(Annotation):
|
| 26 |
+
target_annotation: Annotation
|
| 27 |
+
label: str
|
| 28 |
+
value: Optional[str] = None
|
| 29 |
+
score: float = 1.0
|
| 30 |
+
|
| 31 |
+
def __post_init__(self) -> None:
|
| 32 |
+
_post_init_single_label(self)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@dataclasses.dataclass
|
| 36 |
+
class BratDocument(Document):
|
| 37 |
+
text: str
|
| 38 |
+
id: Optional[str] = None
|
| 39 |
+
metadata: Dict[str, Any] = dataclasses.field(default_factory=dict)
|
| 40 |
+
spans: AnnotationList[LabeledSpan] = annotation_field(target="text")
|
| 41 |
+
relations: AnnotationList[BinaryRelation] = annotation_field(target="spans")
|
| 42 |
+
span_attributions: AnnotationList[Attribution] = annotation_field(target="spans")
|
| 43 |
+
relation_attributions: AnnotationList[Attribution] = annotation_field(target="relations")
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def example_to_document(example: Dict[str, Any]) -> BratDocument:
|
| 47 |
+
doc = BratDocument(text=example["context"], id=example["file_name"])
|
| 48 |
+
|
| 49 |
+
spans: Dict[str, LabeledSpan] = dict()
|
| 50 |
+
span_locations: List[List[Tuple[int, int]]] = []
|
| 51 |
+
span_texts: List[str] = []
|
| 52 |
+
for span_dict in dl2ld(example["spans"]):
|
| 53 |
+
starts = span_dict["locations"]["start"]
|
| 54 |
+
ends = span_dict["locations"]["end"]
|
| 55 |
+
span_locations.append(list(zip(starts, ends)))
|
| 56 |
+
span_texts.append(span_dict["text"])
|
| 57 |
+
# sanity check
|
| 58 |
+
span_text_parts = [doc.text[start:end] for start, end in zip(starts, ends)]
|
| 59 |
+
joined_span_texts_stripped = " ".join(span_text_parts).strip()
|
| 60 |
+
span_text_stripped = span_dict["text"].strip()
|
| 61 |
+
if joined_span_texts_stripped != span_text_stripped:
|
| 62 |
+
raise Exception(
|
| 63 |
+
f"joined span parts does not match stripped span text field content. "
|
| 64 |
+
f'joined_span_texts_stripped: "{joined_span_texts_stripped}" != stripped "text": "{span_text_stripped}"'
|
| 65 |
+
)
|
| 66 |
+
# just take everything
|
| 67 |
+
start = min(starts)
|
| 68 |
+
end = max(ends)
|
| 69 |
+
span = LabeledSpan(start=start, end=end, label=span_dict["type"])
|
| 70 |
+
spans[span_dict["id"]] = span
|
| 71 |
+
|
| 72 |
+
doc.spans.extend(spans.values())
|
| 73 |
+
doc.metadata["span_ids"] = list(spans.keys())
|
| 74 |
+
doc.metadata["span_locations"] = span_locations
|
| 75 |
+
doc.metadata["span_texts"] = span_texts
|
| 76 |
+
|
| 77 |
+
relations: Dict[str, BinaryRelation] = dict()
|
| 78 |
+
for rel_dict in dl2ld(example["relations"]):
|
| 79 |
+
arguments = dict(zip(rel_dict["arguments"]["type"], rel_dict["arguments"]["target"]))
|
| 80 |
+
assert set(arguments) == {"Arg1", "Arg2"}
|
| 81 |
+
head = spans[arguments["Arg1"]]
|
| 82 |
+
tail = spans[arguments["Arg2"]]
|
| 83 |
+
rel = BinaryRelation(head=head, tail=tail, label=rel_dict["type"])
|
| 84 |
+
relations[rel_dict["id"]] = rel
|
| 85 |
+
|
| 86 |
+
doc.relations.extend(relations.values())
|
| 87 |
+
doc.metadata["relation_ids"] = list(relations.keys())
|
| 88 |
+
|
| 89 |
+
equivalence_relations = dl2ld(example["equivalence_relations"])
|
| 90 |
+
if len(equivalence_relations) > 0:
|
| 91 |
+
raise NotImplementedError("converting equivalence_relations is not yet implemented")
|
| 92 |
+
|
| 93 |
+
events = dl2ld(example["events"])
|
| 94 |
+
if len(events) > 0:
|
| 95 |
+
raise NotImplementedError("converting events is not yet implemented")
|
| 96 |
+
|
| 97 |
+
span_attributions: Dict[str, Attribution] = dict()
|
| 98 |
+
attribution_ids = []
|
| 99 |
+
for attribution_dict in dl2ld(example["attributions"]):
|
| 100 |
+
target_id = attribution_dict["target"]
|
| 101 |
+
if target_id in spans:
|
| 102 |
+
target_layer_name = "spans"
|
| 103 |
+
target_annotation = spans[target_id]
|
| 104 |
+
elif target_id in relations:
|
| 105 |
+
target_layer_name = "relations"
|
| 106 |
+
target_annotation = relations[target_id]
|
| 107 |
+
else:
|
| 108 |
+
raise Exception("only span and relation attributions are supported yet")
|
| 109 |
+
attribution = Attribution(
|
| 110 |
+
target_annotation=target_annotation,
|
| 111 |
+
label=attribution_dict["type"],
|
| 112 |
+
value=attribution_dict["value"],
|
| 113 |
+
)
|
| 114 |
+
span_attributions[attribution_dict["id"]] = attribution
|
| 115 |
+
attribution_ids.append((target_layer_name, attribution_dict["id"]))
|
| 116 |
+
|
| 117 |
+
doc.span_attributions.extend(span_attributions.values())
|
| 118 |
+
doc.metadata["attribution_ids"] = attribution_ids
|
| 119 |
+
|
| 120 |
+
normalizations = dl2ld(example["normalizations"])
|
| 121 |
+
if len(normalizations) > 0:
|
| 122 |
+
raise NotImplementedError("converting normalizations is not yet implemented")
|
| 123 |
+
|
| 124 |
+
notes = dl2ld(example["notes"])
|
| 125 |
+
if len(notes) > 0:
|
| 126 |
+
raise NotImplementedError("converting notes is not yet implemented")
|
| 127 |
+
|
| 128 |
+
return doc
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def document_to_example(document: BratDocument) -> Dict[str, Any]:
|
| 132 |
+
example = {
|
| 133 |
+
"context": document.text,
|
| 134 |
+
"file_name": document.id,
|
| 135 |
+
}
|
| 136 |
+
span_dicts: Dict[LabeledSpan, Dict[str, Any]] = dict()
|
| 137 |
+
assert len(document.metadata["span_locations"]) == len(document.spans)
|
| 138 |
+
assert len(document.metadata["span_texts"]) == len(document.spans)
|
| 139 |
+
assert len(document.metadata["span_ids"]) == len(document.spans)
|
| 140 |
+
for i, span in enumerate(document.spans):
|
| 141 |
+
locations = document.metadata["span_locations"][i]
|
| 142 |
+
assert locations[0][0] == span.start
|
| 143 |
+
assert locations[-1][1] == span.end
|
| 144 |
+
starts, ends = zip(*locations)
|
| 145 |
+
span_dict = {
|
| 146 |
+
"id": document.metadata["span_ids"][i],
|
| 147 |
+
"locations": {
|
| 148 |
+
"start": list(starts),
|
| 149 |
+
"end": list(ends),
|
| 150 |
+
},
|
| 151 |
+
"text": document.metadata["span_texts"][i],
|
| 152 |
+
"type": span.label,
|
| 153 |
+
}
|
| 154 |
+
if span in span_dicts:
|
| 155 |
+
prev_ann_dict = span_dicts[span]
|
| 156 |
+
ann_dict = span_dict
|
| 157 |
+
logger.warning(
|
| 158 |
+
f"document {document.id}: annotation exists twice: {prev_ann_dict['id']} and {ann_dict['id']} are identical"
|
| 159 |
+
)
|
| 160 |
+
span_dicts[span] = span_dict
|
| 161 |
+
example["spans"] = ld2dl(list(span_dicts.values()), keys=["id", "type", "locations", "text"])
|
| 162 |
+
|
| 163 |
+
relation_dicts: Dict[LabeledSpan, Dict[str, Any]] = dict()
|
| 164 |
+
assert len(document.metadata["relation_ids"]) == len(document.relations)
|
| 165 |
+
for i, rel in enumerate(document.relations):
|
| 166 |
+
arg1_id = span_dicts[rel.head]["id"]
|
| 167 |
+
arg2_id = span_dicts[rel.tail]["id"]
|
| 168 |
+
relation_dict = {
|
| 169 |
+
"id": document.metadata["relation_ids"][i],
|
| 170 |
+
"type": rel.label,
|
| 171 |
+
"arguments": {
|
| 172 |
+
"type": ["Arg1", "Arg2"],
|
| 173 |
+
"target": [arg1_id, arg2_id],
|
| 174 |
+
},
|
| 175 |
+
}
|
| 176 |
+
if rel in relation_dicts:
|
| 177 |
+
prev_ann_dict = relation_dicts[rel]
|
| 178 |
+
ann_dict = relation_dict
|
| 179 |
+
logger.warning(
|
| 180 |
+
f"document {document.id}: annotation exists twice: {prev_ann_dict['id']} and {ann_dict['id']} are identical"
|
| 181 |
+
)
|
| 182 |
+
relation_dicts[rel] = relation_dict
|
| 183 |
+
|
| 184 |
+
example["relations"] = ld2dl(list(relation_dicts.values()), keys=["id", "type", "arguments"])
|
| 185 |
+
|
| 186 |
+
example["equivalence_relations"] = ld2dl([], keys=["type", "targets"])
|
| 187 |
+
example["events"] = ld2dl([], keys=["id", "type", "trigger", "arguments"])
|
| 188 |
+
|
| 189 |
+
attribution_dicts: Dict[Annotation, Dict[str, Any]] = dict()
|
| 190 |
+
span_attribution_ids = [
|
| 191 |
+
attribution_id
|
| 192 |
+
for target_layer, attribution_id in document.metadata["attribution_ids"]
|
| 193 |
+
if target_layer == "spans"
|
| 194 |
+
]
|
| 195 |
+
assert len(span_attribution_ids) == len(document.span_attributions)
|
| 196 |
+
for i, span_attribution in enumerate(document.span_attributions):
|
| 197 |
+
target_id = span_dicts[span_attribution.target_annotation]["id"]
|
| 198 |
+
attribution_dict = {
|
| 199 |
+
"id": span_attribution_ids[i],
|
| 200 |
+
"type": span_attribution.label,
|
| 201 |
+
"target": target_id,
|
| 202 |
+
"value": span_attribution.value,
|
| 203 |
+
}
|
| 204 |
+
if span_attribution in attribution_dicts:
|
| 205 |
+
prev_ann_dict = attribution_dicts[span_attribution]
|
| 206 |
+
ann_dict = span_attribution
|
| 207 |
+
logger.warning(
|
| 208 |
+
f"document {document.id}: annotation exists twice: {prev_ann_dict['id']} and {ann_dict['id']} are identical"
|
| 209 |
+
)
|
| 210 |
+
attribution_dicts[span_attribution] = attribution_dict
|
| 211 |
+
|
| 212 |
+
example["attributions"] = ld2dl(
|
| 213 |
+
list(attribution_dicts.values()), keys=["id", "type", "target", "value"]
|
| 214 |
+
)
|
| 215 |
+
example["normalizations"] = ld2dl(
|
| 216 |
+
[], keys=["id", "type", "target", "resource_id", "entity_id"]
|
| 217 |
+
)
|
| 218 |
+
example["notes"] = ld2dl([], keys=["id", "type", "target", "note"])
|
| 219 |
+
|
| 220 |
+
return example
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
class BratConfig(datasets.BuilderConfig):
|
| 224 |
+
"""BuilderConfig for BratDatasetLoader."""
|
| 225 |
+
|
| 226 |
+
def __init__(self, **kwargs):
|
| 227 |
+
"""BuilderConfig for DocRED.
|
| 228 |
+
Args:
|
| 229 |
+
**kwargs: keyword arguments forwarded to super.
|
| 230 |
+
"""
|
| 231 |
+
super().__init__(**kwargs)
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
class BratDatasetLoader(pytorch_ie.data.builder.GeneratorBasedBuilder):
|
| 235 |
+
DOCUMENT_TYPE = BratDocument
|
| 236 |
+
|
| 237 |
+
BUILDER_CONFIG_CLASS = BratConfig
|
| 238 |
+
|
| 239 |
+
BASE_DATASET_PATH = "DFKI-SLT/brat"
|
| 240 |
+
|
| 241 |
+
def _generate_document(self, example, **kwargs):
|
| 242 |
+
return example_to_document(example)
|