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 2020 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 |
+
"""CoNLL2012 shared task data based on OntoNotes 5.0."""
|
| 16 |
+
|
| 17 |
+
import glob
|
| 18 |
+
import os
|
| 19 |
+
from collections import defaultdict
|
| 20 |
+
from typing import DefaultDict, Iterator, List, Optional, Tuple
|
| 21 |
+
|
| 22 |
+
import datasets
|
| 23 |
+
|
| 24 |
+
_CITATION = """\
|
| 25 |
+
@inproceedings{pradhan-etal-2013-towards,
|
| 26 |
+
title = "Towards Robust Linguistic Analysis using {O}nto{N}otes",
|
| 27 |
+
author = {Pradhan, Sameer and
|
| 28 |
+
Moschitti, Alessandro and
|
| 29 |
+
Xue, Nianwen and
|
| 30 |
+
Ng, Hwee Tou and
|
| 31 |
+
Bj{\"o}rkelund, Anders and
|
| 32 |
+
Uryupina, Olga and
|
| 33 |
+
Zhang, Yuchen and
|
| 34 |
+
Zhong, Zhi},
|
| 35 |
+
booktitle = "Proceedings of the Seventeenth Conference on Computational Natural Language Learning",
|
| 36 |
+
month = aug,
|
| 37 |
+
year = "2013",
|
| 38 |
+
address = "Sofia, Bulgaria",
|
| 39 |
+
publisher = "Association for Computational Linguistics",
|
| 40 |
+
url = "https://aclanthology.org/W13-3516",
|
| 41 |
+
pages = "143--152",
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
Ralph Weischedel, Martha Palmer, Mitchell Marcus, Eduard Hovy, Sameer Pradhan, \
|
| 45 |
+
Lance Ramshaw, Nianwen Xue, Ann Taylor, Jeff Kaufman, Michelle Franchini, \
|
| 46 |
+
Mohammed El-Bachouti, Robert Belvin, Ann Houston. \
|
| 47 |
+
OntoNotes Release 5.0 LDC2013T19. \
|
| 48 |
+
Web Download. Philadelphia: Linguistic Data Consortium, 2013.
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
_DESCRIPTION = """\
|
| 52 |
+
OntoNotes v5.0 is the final version of OntoNotes corpus, and is a large-scale, multi-genre,
|
| 53 |
+
multilingual corpus manually annotated with syntactic, semantic and discourse information.
|
| 54 |
+
|
| 55 |
+
This dataset is the version of OntoNotes v5.0 extended and is used in the CoNLL-2012 shared task.
|
| 56 |
+
It includes v4 train/dev and v9 test data for English/Chinese/Arabic and corrected version v12 train/dev/test data (English only).
|
| 57 |
+
|
| 58 |
+
The source of data is the Mendeley Data repo [ontonotes-conll2012](https://data.mendeley.com/datasets/zmycy7t9h9), which seems to be as the same as the official data, but users should use this dataset on their own responsibility.
|
| 59 |
+
|
| 60 |
+
See also summaries from paperwithcode, [OntoNotes 5.0](https://paperswithcode.com/dataset/ontonotes-5-0) and [CoNLL-2012](https://paperswithcode.com/dataset/conll-2012-1)
|
| 61 |
+
|
| 62 |
+
For more detailed info of the dataset like annotation, tag set, etc., you can refer to the documents in the Mendeley repo mentioned above.
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
_URL = "https://data.mendeley.com/public-files/datasets/zmycy7t9h9/files/b078e1c4-f7a4-4427-be7f-9389967831ef/file_downloaded"
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class Conll2012Ontonotesv5Config(datasets.BuilderConfig):
|
| 69 |
+
"""BuilderConfig for the CoNLL formatted OntoNotes dataset."""
|
| 70 |
+
|
| 71 |
+
def __init__(self, language=None, conll_version=None, **kwargs):
|
| 72 |
+
"""BuilderConfig for the CoNLL formatted OntoNotes dataset.
|
| 73 |
+
|
| 74 |
+
Args:
|
| 75 |
+
language: string, one of the language {"english", "chinese", "arabic"} .
|
| 76 |
+
conll_version: string, "v4" or "v12". Note there is only English v12.
|
| 77 |
+
**kwargs: keyword arguments forwarded to super.
|
| 78 |
+
"""
|
| 79 |
+
assert language in ["english", "chinese", "arabic"]
|
| 80 |
+
assert conll_version in ["v4", "v12"]
|
| 81 |
+
if conll_version == "v12":
|
| 82 |
+
assert language == "english"
|
| 83 |
+
super(Conll2012Ontonotesv5Config, self).__init__(
|
| 84 |
+
name=f"{language}_{conll_version}",
|
| 85 |
+
description=f"{conll_version} of CoNLL formatted OntoNotes dataset for {language}.",
|
| 86 |
+
version=datasets.Version("1.0.0"), # hf dataset script version
|
| 87 |
+
**kwargs,
|
| 88 |
+
)
|
| 89 |
+
self.language = language
|
| 90 |
+
self.conll_version = conll_version
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class Conll2012Ontonotesv5(datasets.GeneratorBasedBuilder):
|
| 94 |
+
"""The CoNLL formatted OntoNotes dataset."""
|
| 95 |
+
|
| 96 |
+
BUILDER_CONFIGS = [
|
| 97 |
+
Conll2012Ontonotesv5Config(
|
| 98 |
+
language=lang,
|
| 99 |
+
conll_version="v4",
|
| 100 |
+
)
|
| 101 |
+
for lang in ["english", "chinese", "arabic"]
|
| 102 |
+
] + [
|
| 103 |
+
Conll2012Ontonotesv5Config(
|
| 104 |
+
language="english",
|
| 105 |
+
conll_version="v12",
|
| 106 |
+
)
|
| 107 |
+
]
|
| 108 |
+
|
| 109 |
+
def _info(self):
|
| 110 |
+
lang = self.config.language
|
| 111 |
+
conll_version = self.config.conll_version
|
| 112 |
+
if lang == "arabic":
|
| 113 |
+
pos_tag_feature = datasets.Value("string")
|
| 114 |
+
else:
|
| 115 |
+
tag_set = _POS_TAGS[f"{lang}_{conll_version}"]
|
| 116 |
+
pos_tag_feature = datasets.ClassLabel(num_classes=len(tag_set), names=tag_set)
|
| 117 |
+
|
| 118 |
+
return datasets.DatasetInfo(
|
| 119 |
+
description=_DESCRIPTION,
|
| 120 |
+
features=datasets.Features(
|
| 121 |
+
{
|
| 122 |
+
"document_id": datasets.Value("string"),
|
| 123 |
+
"sentences": [
|
| 124 |
+
{
|
| 125 |
+
"part_id": datasets.Value("int32"),
|
| 126 |
+
"words": datasets.Sequence(datasets.Value("string")),
|
| 127 |
+
"pos_tags": datasets.Sequence(pos_tag_feature),
|
| 128 |
+
"parse_tree": datasets.Value("string"),
|
| 129 |
+
"predicate_lemmas": datasets.Sequence(datasets.Value("string")),
|
| 130 |
+
"predicate_framenet_ids": datasets.Sequence(datasets.Value("string")),
|
| 131 |
+
"word_senses": datasets.Sequence(datasets.Value("float32")),
|
| 132 |
+
"speaker": datasets.Value("string"),
|
| 133 |
+
"named_entities": datasets.Sequence(
|
| 134 |
+
datasets.ClassLabel(num_classes=37, names=_NAMED_ENTITY_TAGS)
|
| 135 |
+
),
|
| 136 |
+
"srl_frames": [
|
| 137 |
+
{
|
| 138 |
+
"verb": datasets.Value("string"),
|
| 139 |
+
"frames": datasets.Sequence(datasets.Value("string")),
|
| 140 |
+
}
|
| 141 |
+
],
|
| 142 |
+
"coref_spans": datasets.Sequence(
|
| 143 |
+
datasets.Sequence(datasets.Value("int32"), length=3)
|
| 144 |
+
),
|
| 145 |
+
}
|
| 146 |
+
],
|
| 147 |
+
}
|
| 148 |
+
),
|
| 149 |
+
homepage="https://conll.cemantix.org/2012/introduction.html",
|
| 150 |
+
citation=_CITATION,
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
def _split_generators(self, dl_manager):
|
| 154 |
+
if dl_manager.manual_dir is None:
|
| 155 |
+
raise ValueError(
|
| 156 |
+
f"Because of license restrictions you need to download the data manually (e.g. from here {_URL}) "
|
| 157 |
+
f"and set data_dir to that zip file or the extracted folder."
|
| 158 |
+
)
|
| 159 |
+
manual_dir = os.path.abspath(os.path.expanduser(dl_manager.manual_dir))
|
| 160 |
+
if not os.path.isdir(manual_dir):
|
| 161 |
+
dl_dir = os.path.join(dl_manager.extract(manual_dir), "conll-2012")
|
| 162 |
+
else:
|
| 163 |
+
dl_dir = manual_dir
|
| 164 |
+
|
| 165 |
+
lang = self.config.language
|
| 166 |
+
conll_version = self.config.conll_version
|
| 167 |
+
# dl_dir = dl_manager.download_and_extract(_URL)
|
| 168 |
+
data_dir = os.path.join(dl_dir, conll_version, "data")
|
| 169 |
+
|
| 170 |
+
return [
|
| 171 |
+
datasets.SplitGenerator(
|
| 172 |
+
name=datasets.Split.TRAIN,
|
| 173 |
+
gen_kwargs={"conll_files_directory": os.path.join(data_dir, f"train/data/{lang}")},
|
| 174 |
+
),
|
| 175 |
+
datasets.SplitGenerator(
|
| 176 |
+
name=datasets.Split.VALIDATION,
|
| 177 |
+
gen_kwargs={
|
| 178 |
+
"conll_files_directory": os.path.join(data_dir, f"development/data/{lang}")
|
| 179 |
+
},
|
| 180 |
+
),
|
| 181 |
+
datasets.SplitGenerator(
|
| 182 |
+
name=datasets.Split.TEST,
|
| 183 |
+
gen_kwargs={"conll_files_directory": os.path.join(data_dir, f"test/data/{lang}")},
|
| 184 |
+
),
|
| 185 |
+
]
|
| 186 |
+
|
| 187 |
+
def _generate_examples(self, conll_files_directory):
|
| 188 |
+
conll_files = sorted(
|
| 189 |
+
glob.glob(os.path.join(conll_files_directory, "**/*gold_conll"), recursive=True)
|
| 190 |
+
)
|
| 191 |
+
for idx, conll_file in enumerate(conll_files):
|
| 192 |
+
sentences = []
|
| 193 |
+
for sent in Ontonotes().sentence_iterator(conll_file):
|
| 194 |
+
document_id = sent.document_id
|
| 195 |
+
sentences.append(
|
| 196 |
+
{
|
| 197 |
+
"part_id": sent.sentence_id, # should be part id, according to https://conll.cemantix.org/2012/data.html
|
| 198 |
+
"words": sent.words,
|
| 199 |
+
"pos_tags": sent.pos_tags,
|
| 200 |
+
"parse_tree": sent.parse_tree,
|
| 201 |
+
"predicate_lemmas": sent.predicate_lemmas,
|
| 202 |
+
"predicate_framenet_ids": sent.predicate_framenet_ids,
|
| 203 |
+
"word_senses": sent.word_senses,
|
| 204 |
+
"speaker": sent.speakers[0],
|
| 205 |
+
"named_entities": sent.named_entities,
|
| 206 |
+
"srl_frames": [{"verb": f[0], "frames": f[1]} for f in sent.srl_frames],
|
| 207 |
+
"coref_spans": [(c[0], *c[1]) for c in sent.coref_spans],
|
| 208 |
+
}
|
| 209 |
+
)
|
| 210 |
+
yield idx, {"document_id": document_id, "sentences": sentences}
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
# --------------------------------------------------------------------------------------------------------
|
| 214 |
+
# Tag set
|
| 215 |
+
_NAMED_ENTITY_TAGS = [
|
| 216 |
+
"O", # out of named entity
|
| 217 |
+
"B-PERSON",
|
| 218 |
+
"I-PERSON",
|
| 219 |
+
"B-NORP",
|
| 220 |
+
"I-NORP",
|
| 221 |
+
"B-FAC", # FACILITY
|
| 222 |
+
"I-FAC",
|
| 223 |
+
"B-ORG", # ORGANIZATION
|
| 224 |
+
"I-ORG",
|
| 225 |
+
"B-GPE",
|
| 226 |
+
"I-GPE",
|
| 227 |
+
"B-LOC",
|
| 228 |
+
"I-LOC",
|
| 229 |
+
"B-PRODUCT",
|
| 230 |
+
"I-PRODUCT",
|
| 231 |
+
"B-DATE",
|
| 232 |
+
"I-DATE",
|
| 233 |
+
"B-TIME",
|
| 234 |
+
"I-TIME",
|
| 235 |
+
"B-PERCENT",
|
| 236 |
+
"I-PERCENT",
|
| 237 |
+
"B-MONEY",
|
| 238 |
+
"I-MONEY",
|
| 239 |
+
"B-QUANTITY",
|
| 240 |
+
"I-QUANTITY",
|
| 241 |
+
"B-ORDINAL",
|
| 242 |
+
"I-ORDINAL",
|
| 243 |
+
"B-CARDINAL",
|
| 244 |
+
"I-CARDINAL",
|
| 245 |
+
"B-EVENT",
|
| 246 |
+
"I-EVENT",
|
| 247 |
+
"B-WORK_OF_ART",
|
| 248 |
+
"I-WORK_OF_ART",
|
| 249 |
+
"B-LAW",
|
| 250 |
+
"I-LAW",
|
| 251 |
+
"B-LANGUAGE",
|
| 252 |
+
"I-LANGUAGE",
|
| 253 |
+
]
|
| 254 |
+
|
| 255 |
+
_POS_TAGS = {
|
| 256 |
+
"english_v4": [
|
| 257 |
+
"XX", # missing
|
| 258 |
+
"``",
|
| 259 |
+
"$",
|
| 260 |
+
"''",
|
| 261 |
+
",",
|
| 262 |
+
"-LRB-", # (
|
| 263 |
+
"-RRB-", # )
|
| 264 |
+
".",
|
| 265 |
+
":",
|
| 266 |
+
"ADD",
|
| 267 |
+
"AFX",
|
| 268 |
+
"CC",
|
| 269 |
+
"CD",
|
| 270 |
+
"DT",
|
| 271 |
+
"EX",
|
| 272 |
+
"FW",
|
| 273 |
+
"HYPH",
|
| 274 |
+
"IN",
|
| 275 |
+
"JJ",
|
| 276 |
+
"JJR",
|
| 277 |
+
"JJS",
|
| 278 |
+
"LS",
|
| 279 |
+
"MD",
|
| 280 |
+
"NFP",
|
| 281 |
+
"NN",
|
| 282 |
+
"NNP",
|
| 283 |
+
"NNPS",
|
| 284 |
+
"NNS",
|
| 285 |
+
"PDT",
|
| 286 |
+
"POS",
|
| 287 |
+
"PRP",
|
| 288 |
+
"PRP$",
|
| 289 |
+
"RB",
|
| 290 |
+
"RBR",
|
| 291 |
+
"RBS",
|
| 292 |
+
"RP",
|
| 293 |
+
"SYM",
|
| 294 |
+
"TO",
|
| 295 |
+
"UH",
|
| 296 |
+
"VB",
|
| 297 |
+
"VBD",
|
| 298 |
+
"VBG",
|
| 299 |
+
"VBN",
|
| 300 |
+
"VBP",
|
| 301 |
+
"VBZ",
|
| 302 |
+
"WDT",
|
| 303 |
+
"WP",
|
| 304 |
+
"WP$",
|
| 305 |
+
"WRB",
|
| 306 |
+
], # 49
|
| 307 |
+
"english_v12": [
|
| 308 |
+
"XX", # missing
|
| 309 |
+
"``",
|
| 310 |
+
"$",
|
| 311 |
+
"''",
|
| 312 |
+
"*",
|
| 313 |
+
",",
|
| 314 |
+
"-LRB-", # (
|
| 315 |
+
"-RRB-", # )
|
| 316 |
+
".",
|
| 317 |
+
":",
|
| 318 |
+
"ADD",
|
| 319 |
+
"AFX",
|
| 320 |
+
"CC",
|
| 321 |
+
"CD",
|
| 322 |
+
"DT",
|
| 323 |
+
"EX",
|
| 324 |
+
"FW",
|
| 325 |
+
"HYPH",
|
| 326 |
+
"IN",
|
| 327 |
+
"JJ",
|
| 328 |
+
"JJR",
|
| 329 |
+
"JJS",
|
| 330 |
+
"LS",
|
| 331 |
+
"MD",
|
| 332 |
+
"NFP",
|
| 333 |
+
"NN",
|
| 334 |
+
"NNP",
|
| 335 |
+
"NNPS",
|
| 336 |
+
"NNS",
|
| 337 |
+
"PDT",
|
| 338 |
+
"POS",
|
| 339 |
+
"PRP",
|
| 340 |
+
"PRP$",
|
| 341 |
+
"RB",
|
| 342 |
+
"RBR",
|
| 343 |
+
"RBS",
|
| 344 |
+
"RP",
|
| 345 |
+
"SYM",
|
| 346 |
+
"TO",
|
| 347 |
+
"UH",
|
| 348 |
+
"VB",
|
| 349 |
+
"VBD",
|
| 350 |
+
"VBG",
|
| 351 |
+
"VBN",
|
| 352 |
+
"VBP",
|
| 353 |
+
"VBZ",
|
| 354 |
+
"VERB",
|
| 355 |
+
"WDT",
|
| 356 |
+
"WP",
|
| 357 |
+
"WP$",
|
| 358 |
+
"WRB",
|
| 359 |
+
], # 51
|
| 360 |
+
"chinese_v4": [
|
| 361 |
+
"X", # missing
|
| 362 |
+
"AD",
|
| 363 |
+
"AS",
|
| 364 |
+
"BA",
|
| 365 |
+
"CC",
|
| 366 |
+
"CD",
|
| 367 |
+
"CS",
|
| 368 |
+
"DEC",
|
| 369 |
+
"DEG",
|
| 370 |
+
"DER",
|
| 371 |
+
"DEV",
|
| 372 |
+
"DT",
|
| 373 |
+
"ETC",
|
| 374 |
+
"FW",
|
| 375 |
+
"IJ",
|
| 376 |
+
"INF",
|
| 377 |
+
"JJ",
|
| 378 |
+
"LB",
|
| 379 |
+
"LC",
|
| 380 |
+
"M",
|
| 381 |
+
"MSP",
|
| 382 |
+
"NN",
|
| 383 |
+
"NR",
|
| 384 |
+
"NT",
|
| 385 |
+
"OD",
|
| 386 |
+
"ON",
|
| 387 |
+
"P",
|
| 388 |
+
"PN",
|
| 389 |
+
"PU",
|
| 390 |
+
"SB",
|
| 391 |
+
"SP",
|
| 392 |
+
"URL",
|
| 393 |
+
"VA",
|
| 394 |
+
"VC",
|
| 395 |
+
"VE",
|
| 396 |
+
"VV",
|
| 397 |
+
], # 36
|
| 398 |
+
}
|
| 399 |
+
|
| 400 |
+
# --------------------------------------------------------------------------------------------------------
|
| 401 |
+
# The CoNLL(2012) file reader
|
| 402 |
+
# Modified the original code to get rid of extra package dependency.
|
| 403 |
+
# Original code: https://github.com/allenai/allennlp-models/blob/main/allennlp_models/common/ontonotes.py
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
class OntonotesSentence:
|
| 407 |
+
"""A class representing the annotations available for a single CONLL formatted sentence.
|
| 408 |
+
|
| 409 |
+
# Parameters
|
| 410 |
+
document_id : `str`
|
| 411 |
+
This is a variation on the document filename
|
| 412 |
+
sentence_id : `int`
|
| 413 |
+
The integer ID of the sentence within a document.
|
| 414 |
+
words : `List[str]`
|
| 415 |
+
This is the tokens as segmented/tokenized in the bank.
|
| 416 |
+
pos_tags : `List[str]`
|
| 417 |
+
This is the Penn-Treebank-style part of speech. When parse information is missing,
|
| 418 |
+
all parts of speech except the one for which there is some sense or proposition
|
| 419 |
+
annotation are marked with a XX tag. The verb is marked with just a VERB tag.
|
| 420 |
+
parse_tree : `nltk.Tree`
|
| 421 |
+
An nltk Tree representing the parse. It includes POS tags as pre-terminal nodes.
|
| 422 |
+
When the parse information is missing, the parse will be `None`.
|
| 423 |
+
predicate_lemmas : `List[Optional[str]]`
|
| 424 |
+
The predicate lemma of the words for which we have semantic role
|
| 425 |
+
information or word sense information. All other indices are `None`.
|
| 426 |
+
predicate_framenet_ids : `List[Optional[int]]`
|
| 427 |
+
The PropBank frameset ID of the lemmas in `predicate_lemmas`, or `None`.
|
| 428 |
+
word_senses : `List[Optional[float]]`
|
| 429 |
+
The word senses for the words in the sentence, or `None`. These are floats
|
| 430 |
+
because the word sense can have values after the decimal, like `1.1`.
|
| 431 |
+
speakers : `List[Optional[str]]`
|
| 432 |
+
The speaker information for the words in the sentence, if present, or `None`
|
| 433 |
+
This is the speaker or author name where available. Mostly in Broadcast Conversation
|
| 434 |
+
and Web Log data. When not available the rows are marked with an "-".
|
| 435 |
+
named_entities : `List[str]`
|
| 436 |
+
The BIO tags for named entities in the sentence.
|
| 437 |
+
srl_frames : `List[Tuple[str, List[str]]]`
|
| 438 |
+
A dictionary keyed by the verb in the sentence for the given
|
| 439 |
+
Propbank frame labels, in a BIO format.
|
| 440 |
+
coref_spans : `Set[TypedSpan]`
|
| 441 |
+
The spans for entity mentions involved in coreference resolution within the sentence.
|
| 442 |
+
Each element is a tuple composed of (cluster_id, (start_index, end_index)). Indices
|
| 443 |
+
are `inclusive`.
|
| 444 |
+
"""
|
| 445 |
+
|
| 446 |
+
def __init__(
|
| 447 |
+
self,
|
| 448 |
+
document_id: str,
|
| 449 |
+
sentence_id: int,
|
| 450 |
+
words: List[str],
|
| 451 |
+
pos_tags: List[str],
|
| 452 |
+
parse_tree: Optional[str],
|
| 453 |
+
predicate_lemmas: List[Optional[str]],
|
| 454 |
+
predicate_framenet_ids: List[Optional[str]],
|
| 455 |
+
word_senses: List[Optional[float]],
|
| 456 |
+
speakers: List[Optional[str]],
|
| 457 |
+
named_entities: List[str],
|
| 458 |
+
srl_frames: List[Tuple[str, List[str]]],
|
| 459 |
+
coref_spans,
|
| 460 |
+
) -> None:
|
| 461 |
+
|
| 462 |
+
self.document_id = document_id
|
| 463 |
+
self.sentence_id = sentence_id
|
| 464 |
+
self.words = words
|
| 465 |
+
self.pos_tags = pos_tags
|
| 466 |
+
self.parse_tree = parse_tree
|
| 467 |
+
self.predicate_lemmas = predicate_lemmas
|
| 468 |
+
self.predicate_framenet_ids = predicate_framenet_ids
|
| 469 |
+
self.word_senses = word_senses
|
| 470 |
+
self.speakers = speakers
|
| 471 |
+
self.named_entities = named_entities
|
| 472 |
+
self.srl_frames = srl_frames
|
| 473 |
+
self.coref_spans = coref_spans
|
| 474 |
+
|
| 475 |
+
|
| 476 |
+
class Ontonotes:
|
| 477 |
+
"""This `DatasetReader` is designed to read in the English OntoNotes v5.0 data in the format
|
| 478 |
+
used by the CoNLL 2011/2012 shared tasks. In order to use this Reader, you must follow the
|
| 479 |
+
instructions provided [here (v12 release):] (https://cemantix.org/data/ontonotes.html), which
|
| 480 |
+
will allow you to download the CoNLL style annotations for the OntoNotes v5.0 release --
|
| 481 |
+
LDC2013T19.tgz obtained from LDC. Once you have run the scripts on the extracted data, you will
|
| 482 |
+
have a folder structured as follows: ``` conll-formatted-ontonotes-5.0/
|
| 483 |
+
|
| 484 |
+
── data
|
| 485 |
+
├── development
|
| 486 |
+
└── data
|
| 487 |
+
└── english
|
| 488 |
+
└── annotations
|
| 489 |
+
├── bc
|
| 490 |
+
├── bn
|
| 491 |
+
├── mz
|
| 492 |
+
├── nw
|
| 493 |
+
├── pt
|
| 494 |
+
├── tc
|
| 495 |
+
└── wb
|
| 496 |
+
├── test
|
| 497 |
+
└── data
|
| 498 |
+
└── english
|
| 499 |
+
└── annotations
|
| 500 |
+
├── bc
|
| 501 |
+
├── bn
|
| 502 |
+
├── mz
|
| 503 |
+
├── nw
|
| 504 |
+
├── pt
|
| 505 |
+
├── tc
|
| 506 |
+
└── wb
|
| 507 |
+
└── train
|
| 508 |
+
└── data
|
| 509 |
+
└── english
|
| 510 |
+
└── annotations
|
| 511 |
+
├── bc
|
| 512 |
+
├── bn
|
| 513 |
+
├── mz
|
| 514 |
+
├── nw
|
| 515 |
+
├── pt
|
| 516 |
+
├── tc
|
| 517 |
+
└── wb
|
| 518 |
+
```
|
| 519 |
+
The file path provided to this class can then be any of the train, test or development
|
| 520 |
+
directories(or the top level data directory, if you are not utilizing the splits).
|
| 521 |
+
The data has the following format, ordered by column.
|
| 522 |
+
1. Document ID : `str`
|
| 523 |
+
This is a variation on the document filename
|
| 524 |
+
2. Part number : `int`
|
| 525 |
+
Some files are divided into multiple parts numbered as 000, 001, 002, ... etc.
|
| 526 |
+
3. Word number : `int`
|
| 527 |
+
This is the word index of the word in that sentence.
|
| 528 |
+
4. Word : `str`
|
| 529 |
+
This is the token as segmented/tokenized in the Treebank. Initially the `*_skel` file
|
| 530 |
+
contain the placeholder [WORD] which gets replaced by the actual token from the
|
| 531 |
+
Treebank which is part of the OntoNotes release.
|
| 532 |
+
5. POS Tag : `str`
|
| 533 |
+
This is the Penn Treebank style part of speech. When parse information is missing,
|
| 534 |
+
all part of speeches except the one for which there is some sense or proposition
|
| 535 |
+
annotation are marked with a XX tag. The verb is marked with just a VERB tag.
|
| 536 |
+
6. Parse bit : `str`
|
| 537 |
+
This is the bracketed structure broken before the first open parenthesis in the parse,
|
| 538 |
+
and the word/part-of-speech leaf replaced with a `*`. When the parse information is
|
| 539 |
+
missing, the first word of a sentence is tagged as `(TOP*` and the last word is tagged
|
| 540 |
+
as `*)` and all intermediate words are tagged with a `*`.
|
| 541 |
+
7. Predicate lemma : `str`
|
| 542 |
+
The predicate lemma is mentioned for the rows for which we have semantic role
|
| 543 |
+
information or word sense information. All other rows are marked with a "-".
|
| 544 |
+
8. Predicate Frameset ID : `int`
|
| 545 |
+
The PropBank frameset ID of the predicate in Column 7.
|
| 546 |
+
9. Word sense : `float`
|
| 547 |
+
This is the word sense of the word in Column 3.
|
| 548 |
+
10. Speaker/Author : `str`
|
| 549 |
+
This is the speaker or author name where available. Mostly in Broadcast Conversation
|
| 550 |
+
and Web Log data. When not available the rows are marked with an "-".
|
| 551 |
+
11. Named Entities : `str`
|
| 552 |
+
These columns identifies the spans representing various named entities. For documents
|
| 553 |
+
which do not have named entity annotation, each line is represented with an `*`.
|
| 554 |
+
12. Predicate Arguments : `str`
|
| 555 |
+
There is one column each of predicate argument structure information for the predicate
|
| 556 |
+
mentioned in Column 7. If there are no predicates tagged in a sentence this is a
|
| 557 |
+
single column with all rows marked with an `*`.
|
| 558 |
+
-1. Co-reference : `str`
|
| 559 |
+
Co-reference chain information encoded in a parenthesis structure. For documents that do
|
| 560 |
+
not have co-reference annotations, each line is represented with a "-".
|
| 561 |
+
"""
|
| 562 |
+
|
| 563 |
+
def dataset_iterator(self, file_path: str) -> Iterator[OntonotesSentence]:
|
| 564 |
+
"""An iterator over the entire dataset, yielding all sentences processed."""
|
| 565 |
+
for conll_file in self.dataset_path_iterator(file_path):
|
| 566 |
+
yield from self.sentence_iterator(conll_file)
|
| 567 |
+
|
| 568 |
+
@staticmethod
|
| 569 |
+
def dataset_path_iterator(file_path: str) -> Iterator[str]:
|
| 570 |
+
"""An iterator returning file_paths in a directory containing CONLL-formatted files."""
|
| 571 |
+
for root, _, files in list(os.walk(file_path)):
|
| 572 |
+
for data_file in sorted(files):
|
| 573 |
+
# These are a relic of the dataset pre-processing. Every
|
| 574 |
+
# file will be duplicated - one file called filename.gold_skel
|
| 575 |
+
# and one generated from the preprocessing called filename.gold_conll.
|
| 576 |
+
if not data_file.endswith("gold_conll"):
|
| 577 |
+
continue
|
| 578 |
+
|
| 579 |
+
yield os.path.join(root, data_file)
|
| 580 |
+
|
| 581 |
+
def dataset_document_iterator(self, file_path: str) -> Iterator[List[OntonotesSentence]]:
|
| 582 |
+
"""An iterator over CONLL formatted files which yields documents, regardless of the number
|
| 583 |
+
of document annotations in a particular file.
|
| 584 |
+
|
| 585 |
+
This is useful for conll data which has been preprocessed, such as the preprocessing which
|
| 586 |
+
takes place for the 2012 CONLL Coreference Resolution task.
|
| 587 |
+
"""
|
| 588 |
+
with open(file_path, "r", encoding="utf8") as open_file:
|
| 589 |
+
conll_rows = []
|
| 590 |
+
document: List[OntonotesSentence] = []
|
| 591 |
+
for line in open_file:
|
| 592 |
+
line = line.strip()
|
| 593 |
+
if line != "" and not line.startswith("#"):
|
| 594 |
+
# Non-empty line. Collect the annotation.
|
| 595 |
+
conll_rows.append(line)
|
| 596 |
+
else:
|
| 597 |
+
if conll_rows:
|
| 598 |
+
document.append(self._conll_rows_to_sentence(conll_rows))
|
| 599 |
+
conll_rows = []
|
| 600 |
+
if line.startswith("#end document"):
|
| 601 |
+
yield document
|
| 602 |
+
document = []
|
| 603 |
+
if document:
|
| 604 |
+
# Collect any stragglers or files which might not
|
| 605 |
+
# have the '#end document' format for the end of the file.
|
| 606 |
+
yield document
|
| 607 |
+
|
| 608 |
+
def sentence_iterator(self, file_path: str) -> Iterator[OntonotesSentence]:
|
| 609 |
+
"""An iterator over the sentences in an individual CONLL formatted file."""
|
| 610 |
+
for document in self.dataset_document_iterator(file_path):
|
| 611 |
+
for sentence in document:
|
| 612 |
+
yield sentence
|
| 613 |
+
|
| 614 |
+
def _conll_rows_to_sentence(self, conll_rows: List[str]) -> OntonotesSentence:
|
| 615 |
+
document_id: str = None
|
| 616 |
+
sentence_id: int = None
|
| 617 |
+
# The words in the sentence.
|
| 618 |
+
sentence: List[str] = []
|
| 619 |
+
# The pos tags of the words in the sentence.
|
| 620 |
+
pos_tags: List[str] = []
|
| 621 |
+
# the pieces of the parse tree.
|
| 622 |
+
parse_pieces: List[str] = []
|
| 623 |
+
# The lemmatised form of the words in the sentence which
|
| 624 |
+
# have SRL or word sense information.
|
| 625 |
+
predicate_lemmas: List[str] = []
|
| 626 |
+
# The FrameNet ID of the predicate.
|
| 627 |
+
predicate_framenet_ids: List[str] = []
|
| 628 |
+
# The sense of the word, if available.
|
| 629 |
+
word_senses: List[float] = []
|
| 630 |
+
# The current speaker, if available.
|
| 631 |
+
speakers: List[str] = []
|
| 632 |
+
|
| 633 |
+
verbal_predicates: List[str] = []
|
| 634 |
+
span_labels: List[List[str]] = []
|
| 635 |
+
current_span_labels: List[str] = []
|
| 636 |
+
|
| 637 |
+
# Cluster id -> List of (start_index, end_index) spans.
|
| 638 |
+
clusters: DefaultDict[int, List[Tuple[int, int]]] = defaultdict(list)
|
| 639 |
+
# Cluster id -> List of start_indices which are open for this id.
|
| 640 |
+
coref_stacks: DefaultDict[int, List[int]] = defaultdict(list)
|
| 641 |
+
|
| 642 |
+
for index, row in enumerate(conll_rows):
|
| 643 |
+
conll_components = row.split()
|
| 644 |
+
|
| 645 |
+
document_id = conll_components[0]
|
| 646 |
+
sentence_id = int(conll_components[1])
|
| 647 |
+
word = conll_components[3]
|
| 648 |
+
pos_tag = conll_components[4]
|
| 649 |
+
parse_piece = conll_components[5]
|
| 650 |
+
|
| 651 |
+
# Replace brackets in text and pos tags
|
| 652 |
+
# with a different token for parse trees.
|
| 653 |
+
if pos_tag != "XX" and word != "XX":
|
| 654 |
+
if word == "(":
|
| 655 |
+
parse_word = "-LRB-"
|
| 656 |
+
elif word == ")":
|
| 657 |
+
parse_word = "-RRB-"
|
| 658 |
+
else:
|
| 659 |
+
parse_word = word
|
| 660 |
+
if pos_tag == "(":
|
| 661 |
+
pos_tag = "-LRB-"
|
| 662 |
+
if pos_tag == ")":
|
| 663 |
+
pos_tag = "-RRB-"
|
| 664 |
+
(left_brackets, right_hand_side) = parse_piece.split("*")
|
| 665 |
+
# only keep ')' if there are nested brackets with nothing in them.
|
| 666 |
+
right_brackets = right_hand_side.count(")") * ")"
|
| 667 |
+
parse_piece = f"{left_brackets} ({pos_tag} {parse_word}) {right_brackets}"
|
| 668 |
+
else:
|
| 669 |
+
# There are some bad annotations in the CONLL data.
|
| 670 |
+
# They contain no information, so to make this explicit,
|
| 671 |
+
# we just set the parse piece to be None which will result
|
| 672 |
+
# in the overall parse tree being None.
|
| 673 |
+
parse_piece = None
|
| 674 |
+
|
| 675 |
+
lemmatised_word = conll_components[6]
|
| 676 |
+
framenet_id = conll_components[7]
|
| 677 |
+
word_sense = conll_components[8]
|
| 678 |
+
speaker = conll_components[9]
|
| 679 |
+
|
| 680 |
+
if not span_labels:
|
| 681 |
+
# If this is the first word in the sentence, create
|
| 682 |
+
# empty lists to collect the NER and SRL BIO labels.
|
| 683 |
+
# We can't do this upfront, because we don't know how many
|
| 684 |
+
# components we are collecting, as a sentence can have
|
| 685 |
+
# variable numbers of SRL frames.
|
| 686 |
+
span_labels = [[] for _ in conll_components[10:-1]]
|
| 687 |
+
# Create variables representing the current label for each label
|
| 688 |
+
# sequence we are collecting.
|
| 689 |
+
current_span_labels = [None for _ in conll_components[10:-1]]
|
| 690 |
+
|
| 691 |
+
self._process_span_annotations_for_word(
|
| 692 |
+
conll_components[10:-1], span_labels, current_span_labels
|
| 693 |
+
)
|
| 694 |
+
|
| 695 |
+
# If any annotation marks this word as a verb predicate,
|
| 696 |
+
# we need to record its index. This also has the side effect
|
| 697 |
+
# of ordering the verbal predicates by their location in the
|
| 698 |
+
# sentence, automatically aligning them with the annotations.
|
| 699 |
+
word_is_verbal_predicate = any("(V" in x for x in conll_components[11:-1])
|
| 700 |
+
if word_is_verbal_predicate:
|
| 701 |
+
verbal_predicates.append(word)
|
| 702 |
+
|
| 703 |
+
self._process_coref_span_annotations_for_word(
|
| 704 |
+
conll_components[-1], index, clusters, coref_stacks
|
| 705 |
+
)
|
| 706 |
+
|
| 707 |
+
sentence.append(word)
|
| 708 |
+
pos_tags.append(pos_tag)
|
| 709 |
+
parse_pieces.append(parse_piece)
|
| 710 |
+
predicate_lemmas.append(lemmatised_word if lemmatised_word != "-" else None)
|
| 711 |
+
predicate_framenet_ids.append(framenet_id if framenet_id != "-" else None)
|
| 712 |
+
word_senses.append(float(word_sense) if word_sense != "-" else None)
|
| 713 |
+
speakers.append(speaker if speaker != "-" else None)
|
| 714 |
+
|
| 715 |
+
named_entities = span_labels[0]
|
| 716 |
+
srl_frames = [
|
| 717 |
+
(predicate, labels) for predicate, labels in zip(verbal_predicates, span_labels[1:])
|
| 718 |
+
]
|
| 719 |
+
|
| 720 |
+
if all(parse_pieces):
|
| 721 |
+
parse_tree = "".join(parse_pieces)
|
| 722 |
+
else:
|
| 723 |
+
parse_tree = None
|
| 724 |
+
coref_span_tuples = {
|
| 725 |
+
(cluster_id, span) for cluster_id, span_list in clusters.items() for span in span_list
|
| 726 |
+
}
|
| 727 |
+
return OntonotesSentence(
|
| 728 |
+
document_id,
|
| 729 |
+
sentence_id,
|
| 730 |
+
sentence,
|
| 731 |
+
pos_tags,
|
| 732 |
+
parse_tree,
|
| 733 |
+
predicate_lemmas,
|
| 734 |
+
predicate_framenet_ids,
|
| 735 |
+
word_senses,
|
| 736 |
+
speakers,
|
| 737 |
+
named_entities,
|
| 738 |
+
srl_frames,
|
| 739 |
+
coref_span_tuples,
|
| 740 |
+
)
|
| 741 |
+
|
| 742 |
+
@staticmethod
|
| 743 |
+
def _process_coref_span_annotations_for_word(
|
| 744 |
+
label: str,
|
| 745 |
+
word_index: int,
|
| 746 |
+
clusters: DefaultDict[int, List[Tuple[int, int]]],
|
| 747 |
+
coref_stacks: DefaultDict[int, List[int]],
|
| 748 |
+
) -> None:
|
| 749 |
+
"""For a given coref label, add it to a currently open span(s), complete a span(s) or
|
| 750 |
+
ignore it, if it is outside of all spans. This method mutates the clusters and coref_stacks
|
| 751 |
+
dictionaries.
|
| 752 |
+
|
| 753 |
+
# Parameters
|
| 754 |
+
label : `str`
|
| 755 |
+
The coref label for this word.
|
| 756 |
+
word_index : `int`
|
| 757 |
+
The word index into the sentence.
|
| 758 |
+
clusters : `DefaultDict[int, List[Tuple[int, int]]]`
|
| 759 |
+
A dictionary mapping cluster ids to lists of inclusive spans into the
|
| 760 |
+
sentence.
|
| 761 |
+
coref_stacks : `DefaultDict[int, List[int]]`
|
| 762 |
+
Stacks for each cluster id to hold the start indices of active spans (spans
|
| 763 |
+
which we are inside of when processing a given word). Spans with the same id
|
| 764 |
+
can be nested, which is why we collect these opening spans on a stack, e.g:
|
| 765 |
+
[Greg, the baker who referred to [himself]_ID1 as 'the bread man']_ID1
|
| 766 |
+
"""
|
| 767 |
+
if label != "-":
|
| 768 |
+
for segment in label.split("|"):
|
| 769 |
+
# The conll representation of coref spans allows spans to
|
| 770 |
+
# overlap. If spans end or begin at the same word, they are
|
| 771 |
+
# separated by a "|".
|
| 772 |
+
if segment[0] == "(":
|
| 773 |
+
# The span begins at this word.
|
| 774 |
+
if segment[-1] == ")":
|
| 775 |
+
# The span begins and ends at this word (single word span).
|
| 776 |
+
cluster_id = int(segment[1:-1])
|
| 777 |
+
clusters[cluster_id].append((word_index, word_index))
|
| 778 |
+
else:
|
| 779 |
+
# The span is starting, so we record the index of the word.
|
| 780 |
+
cluster_id = int(segment[1:])
|
| 781 |
+
coref_stacks[cluster_id].append(word_index)
|
| 782 |
+
else:
|
| 783 |
+
# The span for this id is ending, but didn't start at this word.
|
| 784 |
+
# Retrieve the start index from the document state and
|
| 785 |
+
# add the span to the clusters for this id.
|
| 786 |
+
cluster_id = int(segment[:-1])
|
| 787 |
+
start = coref_stacks[cluster_id].pop()
|
| 788 |
+
clusters[cluster_id].append((start, word_index))
|
| 789 |
+
|
| 790 |
+
@staticmethod
|
| 791 |
+
def _process_span_annotations_for_word(
|
| 792 |
+
annotations: List[str],
|
| 793 |
+
span_labels: List[List[str]],
|
| 794 |
+
current_span_labels: List[Optional[str]],
|
| 795 |
+
) -> None:
|
| 796 |
+
"""Given a sequence of different label types for a single word and the current span label
|
| 797 |
+
we are inside, compute the BIO tag for each label and append to a list.
|
| 798 |
+
|
| 799 |
+
# Parameters
|
| 800 |
+
annotations : `List[str]`
|
| 801 |
+
A list of labels to compute BIO tags for.
|
| 802 |
+
span_labels : `List[List[str]]`
|
| 803 |
+
A list of lists, one for each annotation, to incrementally collect
|
| 804 |
+
the BIO tags for a sequence.
|
| 805 |
+
current_span_labels : `List[Optional[str]]`
|
| 806 |
+
The currently open span per annotation type, or `None` if there is no open span.
|
| 807 |
+
"""
|
| 808 |
+
for annotation_index, annotation in enumerate(annotations):
|
| 809 |
+
# strip all bracketing information to
|
| 810 |
+
# get the actual propbank label.
|
| 811 |
+
label = annotation.strip("()*")
|
| 812 |
+
|
| 813 |
+
if "(" in annotation:
|
| 814 |
+
# Entering into a span for a particular semantic role label.
|
| 815 |
+
# We append the label and set the current span for this annotation.
|
| 816 |
+
bio_label = "B-" + label
|
| 817 |
+
span_labels[annotation_index].append(bio_label)
|
| 818 |
+
current_span_labels[annotation_index] = label
|
| 819 |
+
elif current_span_labels[annotation_index] is not None:
|
| 820 |
+
# If there's no '(' token, but the current_span_label is not None,
|
| 821 |
+
# then we are inside a span.
|
| 822 |
+
bio_label = "I-" + current_span_labels[annotation_index]
|
| 823 |
+
span_labels[annotation_index].append(bio_label)
|
| 824 |
+
else:
|
| 825 |
+
# We're outside a span.
|
| 826 |
+
span_labels[annotation_index].append("O")
|
| 827 |
+
# Exiting a span, so we reset the current span label for this annotation.
|
| 828 |
+
if ")" in annotation:
|
| 829 |
+
current_span_labels[annotation_index] = None
|