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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import dataclasses
|
| 2 |
+
import itertools
|
| 3 |
+
from collections import defaultdict
|
| 4 |
+
from typing import Any, Callable, Dict, List, Optional, Tuple
|
| 5 |
+
|
| 6 |
+
import datasets
|
| 7 |
+
import pytorch_ie
|
| 8 |
+
from pytorch_ie.annotations import BinaryRelation, LabeledSpan, NaryRelation, Span
|
| 9 |
+
from pytorch_ie.core import Annotation, AnnotationList, Document, annotation_field
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@dataclasses.dataclass(eq=True, frozen=True)
|
| 13 |
+
class SpanSet(Annotation):
|
| 14 |
+
spans: Tuple[Span, ...]
|
| 15 |
+
score: float = 1.0
|
| 16 |
+
|
| 17 |
+
def __post_init__(self) -> None:
|
| 18 |
+
# make the referenced spans unique, sort them and convert to tuples to make everything hashable
|
| 19 |
+
object.__setattr__(
|
| 20 |
+
self,
|
| 21 |
+
"spans",
|
| 22 |
+
tuple(sorted(set(s for s in self.spans), key=lambda s: (s.start, s.end))),
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@dataclasses.dataclass(eq=True, frozen=True)
|
| 27 |
+
class Attribute(Annotation):
|
| 28 |
+
target_annotation: Annotation
|
| 29 |
+
label: str
|
| 30 |
+
value: Optional[str] = None
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@dataclasses.dataclass(eq=True, frozen=True)
|
| 34 |
+
class Predicate(Span):
|
| 35 |
+
lemma: str
|
| 36 |
+
framenet_id: Optional[str] = None
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@dataclasses.dataclass
|
| 40 |
+
class Conll2012OntonotesV5Document(Document):
|
| 41 |
+
tokens: List[str]
|
| 42 |
+
document_id: str
|
| 43 |
+
pos_tags: List[str]
|
| 44 |
+
sentences: AnnotationList[Span] = annotation_field(target="tokens")
|
| 45 |
+
parse_trees: AnnotationList[Attribute] = annotation_field(target="sentences")
|
| 46 |
+
speakers: AnnotationList[Attribute] = annotation_field(target="sentences")
|
| 47 |
+
parts: AnnotationList[LabeledSpan] = annotation_field(target="tokens")
|
| 48 |
+
coref_mentions: AnnotationList[Span] = annotation_field(target="tokens")
|
| 49 |
+
coref_clusters: AnnotationList[SpanSet] = annotation_field(target="coref_mentions")
|
| 50 |
+
srl_arguments: AnnotationList[Span] = annotation_field(target="tokens")
|
| 51 |
+
srl_relations: AnnotationList[NaryRelation] = annotation_field(target="srl_arguments")
|
| 52 |
+
entities: AnnotationList[LabeledSpan] = annotation_field(target="tokens")
|
| 53 |
+
predicates: AnnotationList[Predicate] = annotation_field(target="tokens")
|
| 54 |
+
word_senses: AnnotationList[LabeledSpan] = annotation_field(target="tokens")
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def bio2spans(bio: List[str], offset: int = 0) -> List[LabeledSpan]:
|
| 58 |
+
"""Convert a BIO-encoded sequence of labels to a list of labeled spans.
|
| 59 |
+
|
| 60 |
+
Args:
|
| 61 |
+
bio: a BIO-encoded sequence of labels, e.g. ["B-PER", "I-PER", "O", "B-LOC", "I-LOC"]
|
| 62 |
+
offset: offset to add to the start and end indices of the spans
|
| 63 |
+
|
| 64 |
+
Returns:
|
| 65 |
+
a list of labeled spans
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
spans = []
|
| 69 |
+
prev_start_and_label: Optional[int, str] = None
|
| 70 |
+
for idx, bio_value_and_label in enumerate(bio):
|
| 71 |
+
bio_value = bio_value_and_label[0]
|
| 72 |
+
bio_label = bio_value_and_label[2:] if bio_value != "O" else None
|
| 73 |
+
if bio_value == "B":
|
| 74 |
+
if prev_start_and_label is not None:
|
| 75 |
+
prev_start, prev_label = prev_start_and_label
|
| 76 |
+
spans.append(
|
| 77 |
+
LabeledSpan(start=prev_start + offset, end=idx + offset, label=prev_label)
|
| 78 |
+
)
|
| 79 |
+
prev_start_and_label = (idx, bio_label)
|
| 80 |
+
elif bio_value == "I":
|
| 81 |
+
if prev_start_and_label is None:
|
| 82 |
+
raise ValueError(f"Invalid BIO encoding: {bio}")
|
| 83 |
+
elif bio_value == "O":
|
| 84 |
+
if prev_start_and_label is not None:
|
| 85 |
+
prev_start, prev_label = prev_start_and_label
|
| 86 |
+
spans.append(
|
| 87 |
+
LabeledSpan(start=prev_start + offset, end=idx + offset, label=prev_label)
|
| 88 |
+
)
|
| 89 |
+
prev_start_and_label = None
|
| 90 |
+
|
| 91 |
+
if prev_start_and_label is not None:
|
| 92 |
+
prev_start, prev_label = prev_start_and_label
|
| 93 |
+
spans.append(
|
| 94 |
+
LabeledSpan(start=prev_start + offset, end=len(bio) + offset, label=prev_label)
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
return spans
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def example_to_document(
|
| 101 |
+
example: Dict[str, Any],
|
| 102 |
+
entities_int2str: Callable[[int], str],
|
| 103 |
+
pos_tags_int2str: Optional[Callable[[int], str]] = None,
|
| 104 |
+
) -> Conll2012OntonotesV5Document:
|
| 105 |
+
|
| 106 |
+
sentences = []
|
| 107 |
+
tokens = []
|
| 108 |
+
pos_tags = []
|
| 109 |
+
parse_trees = []
|
| 110 |
+
speakers = []
|
| 111 |
+
entities = []
|
| 112 |
+
predicates = []
|
| 113 |
+
coref_mentions = []
|
| 114 |
+
coref_clusters = []
|
| 115 |
+
srl_arguments = []
|
| 116 |
+
srl_relations = []
|
| 117 |
+
word_senses = []
|
| 118 |
+
parts = []
|
| 119 |
+
|
| 120 |
+
last_part_id_and_start: Optional[Tuple[int, int]] = None
|
| 121 |
+
|
| 122 |
+
for sentence_idx, sentence_dict in enumerate(example["sentences"]):
|
| 123 |
+
sentence_offset = len(tokens)
|
| 124 |
+
current_tokens = sentence_dict["words"]
|
| 125 |
+
current_sentence = Span(start=sentence_offset, end=sentence_offset + len(current_tokens))
|
| 126 |
+
sentences.append(current_sentence)
|
| 127 |
+
|
| 128 |
+
if pos_tags_int2str is not None:
|
| 129 |
+
pos_tags.extend(
|
| 130 |
+
[pos_tags_int2str(pos_tag_id) for pos_tag_id in sentence_dict["pos_tags"]]
|
| 131 |
+
)
|
| 132 |
+
else:
|
| 133 |
+
pos_tags.extend(sentence_dict["pos_tags"])
|
| 134 |
+
parse_trees.append(
|
| 135 |
+
Attribute(target_annotation=current_sentence, label=sentence_dict["parse_tree"])
|
| 136 |
+
)
|
| 137 |
+
speakers.append(
|
| 138 |
+
Attribute(target_annotation=current_sentence, label=sentence_dict["speaker"])
|
| 139 |
+
)
|
| 140 |
+
named_entities_bio = [
|
| 141 |
+
entities_int2str(entity_id) for entity_id in sentence_dict["named_entities"]
|
| 142 |
+
]
|
| 143 |
+
entities.extend(bio2spans(bio=named_entities_bio, offset=len(tokens)))
|
| 144 |
+
|
| 145 |
+
for idx, (predicate_lemma_value, predicate_framenet_id) in enumerate(
|
| 146 |
+
zip(sentence_dict["predicate_lemmas"], sentence_dict["predicate_framenet_ids"])
|
| 147 |
+
):
|
| 148 |
+
token_idx = sentence_offset + idx
|
| 149 |
+
if predicate_lemma_value is not None:
|
| 150 |
+
predicate = Predicate(
|
| 151 |
+
start=token_idx,
|
| 152 |
+
end=token_idx + 1,
|
| 153 |
+
lemma=predicate_lemma_value,
|
| 154 |
+
framenet_id=predicate_framenet_id,
|
| 155 |
+
)
|
| 156 |
+
predicates.append(predicate)
|
| 157 |
+
|
| 158 |
+
coref_clusters_dict = defaultdict(list)
|
| 159 |
+
for cluster_id, start, end in sentence_dict["coref_spans"]:
|
| 160 |
+
current_coref_mention = Span(
|
| 161 |
+
start=start + sentence_offset, end=end + 1 + sentence_offset
|
| 162 |
+
)
|
| 163 |
+
coref_mentions.append(current_coref_mention)
|
| 164 |
+
coref_clusters_dict[cluster_id].append(current_coref_mention)
|
| 165 |
+
current_coref_clusters = [
|
| 166 |
+
SpanSet(spans=tuple(spans)) for spans in coref_clusters_dict.values()
|
| 167 |
+
]
|
| 168 |
+
coref_clusters.extend(current_coref_clusters)
|
| 169 |
+
|
| 170 |
+
# handle srl_frames
|
| 171 |
+
for frame_dict in sentence_dict["srl_frames"]:
|
| 172 |
+
current_srl_arguments_with_roles = bio2spans(
|
| 173 |
+
bio=frame_dict["frames"], offset=sentence_offset
|
| 174 |
+
)
|
| 175 |
+
current_srl_arguments = [
|
| 176 |
+
Span(start=arg.start, end=arg.end) for arg in current_srl_arguments_with_roles
|
| 177 |
+
]
|
| 178 |
+
current_srl_roles = [arg.label for arg in current_srl_arguments_with_roles]
|
| 179 |
+
current_srl_relation = NaryRelation(
|
| 180 |
+
arguments=tuple(current_srl_arguments),
|
| 181 |
+
roles=tuple(current_srl_roles),
|
| 182 |
+
label="",
|
| 183 |
+
)
|
| 184 |
+
srl_arguments.extend(current_srl_arguments)
|
| 185 |
+
srl_relations.append(current_srl_relation)
|
| 186 |
+
|
| 187 |
+
# handle word senses
|
| 188 |
+
for idx, word_sense in enumerate(sentence_dict["word_senses"]):
|
| 189 |
+
token_idx = sentence_offset + idx
|
| 190 |
+
if word_sense is not None:
|
| 191 |
+
word_senses.append(
|
| 192 |
+
LabeledSpan(start=token_idx, end=token_idx + 1, label=str(int(word_sense)))
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
# handle parts
|
| 196 |
+
if last_part_id_and_start is not None:
|
| 197 |
+
last_part_id, last_start = last_part_id_and_start
|
| 198 |
+
if last_part_id != sentence_dict["part_id"]:
|
| 199 |
+
parts.append(
|
| 200 |
+
LabeledSpan(start=last_start, end=sentence_offset, label=str(last_part_id))
|
| 201 |
+
)
|
| 202 |
+
last_part_id_and_start = (sentence_dict["part_id"], sentence_offset)
|
| 203 |
+
else:
|
| 204 |
+
last_part_id_and_start = (sentence_dict["part_id"], sentence_offset)
|
| 205 |
+
|
| 206 |
+
tokens.extend(current_tokens)
|
| 207 |
+
|
| 208 |
+
if last_part_id_and_start is not None:
|
| 209 |
+
last_part_id, last_start = last_part_id_and_start
|
| 210 |
+
parts.append(LabeledSpan(start=last_start, end=len(tokens), label=str(last_part_id)))
|
| 211 |
+
|
| 212 |
+
doc = Conll2012OntonotesV5Document(
|
| 213 |
+
tokens=tokens,
|
| 214 |
+
document_id=example["document_id"],
|
| 215 |
+
pos_tags=pos_tags,
|
| 216 |
+
)
|
| 217 |
+
# add the annotations to the document
|
| 218 |
+
doc.sentences.extend(sentences)
|
| 219 |
+
doc.parse_trees.extend(parse_trees)
|
| 220 |
+
doc.speakers.extend(speakers)
|
| 221 |
+
doc.entities.extend(entities)
|
| 222 |
+
doc.predicates.extend(predicates)
|
| 223 |
+
doc.coref_mentions.extend(coref_mentions)
|
| 224 |
+
doc.coref_clusters.extend(coref_clusters)
|
| 225 |
+
doc.srl_arguments.extend(srl_arguments)
|
| 226 |
+
doc.srl_relations.extend(srl_relations)
|
| 227 |
+
doc.word_senses.extend(word_senses)
|
| 228 |
+
|
| 229 |
+
return doc
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
class Conll2012OntonotesV5Config(datasets.BuilderConfig):
|
| 233 |
+
"""BuilderConfig for the CoNLL formatted OntoNotes dataset."""
|
| 234 |
+
|
| 235 |
+
def __init__(self, language=None, conll_version=None, **kwargs):
|
| 236 |
+
"""BuilderConfig for the CoNLL formatted OntoNotes dataset.
|
| 237 |
+
|
| 238 |
+
Args:
|
| 239 |
+
language: string, one of the language {"english", "chinese", "arabic"} .
|
| 240 |
+
conll_version: string, "v4" or "v12". Note there is only English v12.
|
| 241 |
+
**kwargs: keyword arguments forwarded to super.
|
| 242 |
+
"""
|
| 243 |
+
assert language in ["english", "chinese", "arabic"]
|
| 244 |
+
assert conll_version in ["v4", "v12"]
|
| 245 |
+
if conll_version == "v12":
|
| 246 |
+
assert language == "english"
|
| 247 |
+
super(Conll2012OntonotesV5Config, self).__init__(
|
| 248 |
+
name=f"{language}_{conll_version}",
|
| 249 |
+
description=f"{conll_version} of CoNLL formatted OntoNotes dataset for {language}.",
|
| 250 |
+
version=datasets.Version("1.0.0"), # hf dataset script version
|
| 251 |
+
**kwargs,
|
| 252 |
+
)
|
| 253 |
+
self.language = language
|
| 254 |
+
self.conll_version = conll_version
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
class Conll2012Ontonotesv5(pytorch_ie.data.builder.GeneratorBasedBuilder):
|
| 258 |
+
DOCUMENT_TYPE = Conll2012OntonotesV5Document
|
| 259 |
+
|
| 260 |
+
BASE_DATASET_PATH = "DFKI-SLT/conll2012_ontonotesv5"
|
| 261 |
+
|
| 262 |
+
BUILDER_CONFIGS = [
|
| 263 |
+
Conll2012OntonotesV5Config(
|
| 264 |
+
language=lang,
|
| 265 |
+
conll_version="v4",
|
| 266 |
+
)
|
| 267 |
+
for lang in ["english", "chinese", "arabic"]
|
| 268 |
+
] + [
|
| 269 |
+
Conll2012OntonotesV5Config(
|
| 270 |
+
language="english",
|
| 271 |
+
conll_version="v12",
|
| 272 |
+
)
|
| 273 |
+
]
|
| 274 |
+
|
| 275 |
+
def _generate_document_kwargs(self, dataset):
|
| 276 |
+
pos_tags_feature = dataset.features["sentences"][0]["pos_tags"].feature
|
| 277 |
+
return dict(
|
| 278 |
+
entities_int2str=dataset.features["sentences"][0]["named_entities"].feature.int2str,
|
| 279 |
+
pos_tags_int2str=pos_tags_feature.int2str
|
| 280 |
+
if isinstance(pos_tags_feature, datasets.ClassLabel)
|
| 281 |
+
else None,
|
| 282 |
+
)
|
| 283 |
+
|
| 284 |
+
def _generate_document(self, example, entities_int2str, pos_tags_int2str):
|
| 285 |
+
return example_to_document(
|
| 286 |
+
example, entities_int2str=entities_int2str, pos_tags_int2str=pos_tags_int2str
|
| 287 |
+
)
|