File size: 13,860 Bytes
2df65c7 c3cdfca 2df65c7 c3cdfca 2df65c7 c3cdfca 2df65c7 c3cdfca 2df65c7 b14a0f3 2df65c7 c3cdfca 2df65c7 c3cdfca 2df65c7 c3cdfca 2df65c7 c3cdfca 2df65c7 c3cdfca 2df65c7 |
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 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 |
import os
import tempfile
from pathlib import Path
from typing import Iterable, Tuple, List
import datasets
logger = datasets.logging.get_logger(__name__)
_CITATION = """@article{10.1162/tacl_a_00404,
author = {Bareket, Dan and Tsarfaty, Reut},
title = "{Neural Modeling for Named Entities and Morphology (NEMO2)}",
journal = {Transactions of the Association for Computational Linguistics},
volume = {9},
pages = {909-928},
year = {2021},
month = {09},
abstract = "{Named Entity Recognition (NER) is a fundamental NLP task, commonly formulated as classification over a sequence of tokens. Morphologically rich languages (MRLs) pose a challenge to this basic formulation, as the boundaries of named entities do not necessarily coincide with token boundaries, rather, they respect morphological boundaries. To address NER in MRLs we then need to answer two fundamental questions, namely, what are the basic units to be labeled, and how can these units be detected and classified in realistic settings (i.e., where no gold morphology is available). We empirically investigate these questions on a novel NER benchmark, with parallel token- level and morpheme-level NER annotations, which we develop for Modern Hebrew, a morphologically rich-and-ambiguous language. Our results show that explicitly modeling morphological boundaries leads to improved NER performance, and that a novel hybrid architecture, in which NER precedes and prunes morphological decomposition, greatly outperforms the standard pipeline, where morphological decomposition strictly precedes NER, setting a new performance bar for both Hebrew NER and Hebrew morphological decomposition tasks.}",
issn = {2307-387X},
doi = {10.1162/tacl_a_00404},
url = {https://doi.org/10.1162/tacl\_a\_00404},
eprint = {https://direct.mit.edu/tacl/article-pdf/doi/10.1162/tacl\_a\_00404/1962472/tacl\_a\_00404.pdf},
}
"""
_DESCRIPTION = """\
"""
URL = "https://github.com/OnlpLab/NEMO-Corpus"
def tokens_with_tags_to_spans(tags: Iterable[str], tokens: Iterable[str]) -> List[
Tuple[str, int, int]]:
"""
Convert a list of tokens and tags to a list of spans for BIOSE/BIOLU schemes tags.
Args:
tags: list of entities tags
tokens: list of tokens
Note that the end index returned by this function is exclusive.
No, need to increment the end by 1.
Returns:
list of {span, start, end, entity, start_char, end_char}
where span is a phrase/tokens, start and end are the indices of the span,
entity is the entity type, and start_char and end_char are the start
and end characters of the span.
"""
entities = []
start = None
start_char = None
words = []
curr_pos = 0
for i, (tag, token) in enumerate(zip(tags, tokens)):
if tag is None or tag.startswith("-"):
if start is not None:
start = None
start_char = None
words = []
else:
end_pos = curr_pos + len(token)
words.append(token)
entities.append({
"entity": "",
"span": " ".join(words),
"start": i,
"end": i + 1,
"start_char": curr_pos,
"end_char": end_pos
})
elif tag.startswith("O"):
pass
elif tag.startswith("I"):
words.append(token)
if start is None:
raise ValueError(
"Invalid BILUO tag sequence: Got a tag starting with {start} "
"without a preceding 'B' (beginning of an entity). "
"Tag sequence:\n{tags}".format(start="I", tags=list(tags)[: i + 1])
)
elif tag.startswith("U") or tag.startswith("S"):
end_pos = curr_pos + len(token)
entities.append({
"entity": tag[2:],
"span": token,
"start": i,
"end": i + 1,
"start_char": curr_pos,
"end_char": end_pos
})
elif tag.startswith("B"):
start = i
start_char = curr_pos
words.append(token)
elif tag.startswith("L") or tag.startswith("E"):
if start is None:
raise ValueError(
"Invalid BILUO tag sequence: Got a tag starting with {start} "
"without a preceding 'B' (beginning of an entity). "
"Tag sequence:\n{tags}".format(start="L", tags=list(tags)[: i + 1])
)
end_pos = curr_pos + len(token)
words.append(token)
entities.append({
"entity": tag[2:],
"span": " ".join(words),
"start": start,
"end": i + 1,
"start_char": start_char,
"end_char": end_pos
})
start = None
start_char = None
words = []
else:
raise ValueError("Invalid BILUO tag: '{}'.".format(tag))
curr_pos += len(token) + len(" ")
return entities
class NemoCorpusConfig(datasets.BuilderConfig):
"""BuilderConfig for NemoCorpus"""
def __init__(self):
"""BuilderConfig for flat Nemo corpus.
Args:
**kwargs: keyword arguments forwarded to super.
"""
version = datasets.Version("1.0.0")
description = "Nemo corpus dataset"
name = "flat"
super(NemoCorpusConfig, self).__init__(version=version, description=description,
name=name)
self.features = datasets.Features(
{
"id": datasets.Value("string"),
"tokens": datasets.Sequence(datasets.Value("string")),
"sentence": datasets.Value("string"),
"ner_tags": datasets.Sequence(
datasets.features.ClassLabel(
names=['S-ANG', 'B-ANG', 'I-ANG', 'E-ANG',
'S-DUC', 'B-DUC', 'I-DUC', 'E-DUC',
'B-EVE', 'E-EVE', 'S-EVE', 'I-EVE',
'S-FAC', 'B-FAC', 'E-FAC', 'I-FAC',
'S-GPE', 'B-GPE', 'E-GPE', 'I-GPE',
'S-LOC', 'B-LOC', 'E-LOC', 'I-LOC',
'O',
'S-ORG', 'B-ORG', 'E-ORG', 'I-ORG',
'B-PER', 'I-PER', 'E-PER', 'S-PER',
'B-WOA', 'E-WOA', 'I-WOA', 'S-WOA']
)
),
"spans": datasets.Sequence({
"span": datasets.Value("string"),
"start": datasets.Value("int32"),
"end": datasets.Value("int32"),
"entity": datasets.Value("string"),
"start_char": datasets.Value("int32"),
"end_char": datasets.Value("int32"),
})
}
)
class NemoCorpusNestedConfig(datasets.BuilderConfig):
"""BuilderConfig for NemoCorpus"""
def __init__(self):
"""BuilderConfig for nested NemoCorpus.
Args:
**kwargs: keyword arguments forwarded to super.
"""
version = datasets.Version("1.0.0")
description = "Nemo corpus dataset"
name = "nested"
super(NemoCorpusNestedConfig, self).__init__(version=version,
description=description,
name=name)
self.classes = ['S-ANG', 'B-ANG', 'I-ANG', 'E-ANG',
'S-DUC', 'B-DUC', 'I-DUC', 'E-DUC',
'B-EVE', 'E-EVE', 'S-EVE', 'I-EVE',
'S-FAC', 'B-FAC', 'E-FAC', 'I-FAC',
'S-GPE', 'B-GPE', 'E-GPE', 'I-GPE',
'S-LOC', 'B-LOC', 'E-LOC', 'I-LOC',
'O',
'S-ORG', 'B-ORG', 'E-ORG', 'I-ORG',
'B-PER', 'I-PER', 'E-PER', 'S-PER',
'B-WOA', 'E-WOA', 'I-WOA', 'S-WOA']
self.features = datasets.Features(
{
"id": datasets.Value("string"),
"tokens": datasets.Sequence(datasets.Value("string")),
"ner_tags": datasets.Sequence(
datasets.features.ClassLabel(names=self.classes)),
"ner_tags_2": datasets.Sequence(
datasets.features.ClassLabel(names=self.classes)),
"ner_tags_3": datasets.Sequence(
datasets.features.ClassLabel(names=self.classes)),
"ner_tags_4": datasets.Sequence(
datasets.features.ClassLabel(names=self.classes)),
}
)
class NemoCorpus(datasets.GeneratorBasedBuilder):
"""NemoCorpus dataset."""
DEFAULT_CONFIG_NAME = "flat"
BUILDER_CONFIGS = [
NemoCorpusConfig(),
NemoCorpusNestedConfig()
]
def _info(self):
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=self.config.features,
supervised_keys=None,
homepage="https://www.cs.bgu.ac.il/~elhadad/nlpproj/naama/",
citation=_CITATION,
)
def _split_generators(self, dl_manager):
"""Returns SplitGenerators."""
dirname = tempfile.TemporaryDirectory().name
os.makedirs(dirname, exist_ok=True)
os.system(f"cd {dirname} && git clone --depth=1 {URL}")
folder = Path(dirname) / "NEMO-Corpus" / "data" / "spmrl" / "gold"
if self.config.name == "nested":
folder = folder / "nested"
data_files = {
"train": dl_manager.download(folder / "morph_gold_train.bmes"),
"validation": dl_manager.download(folder / "morph_gold_dev.bmes"),
"test": dl_manager.download(folder / "morph_gold_test.bmes"),
}
return [
datasets.SplitGenerator(name=datasets.Split.TRAIN,
gen_kwargs={"filepath": data_files["train"]}),
datasets.SplitGenerator(name=datasets.Split.VALIDATION,
gen_kwargs={"filepath": data_files["validation"]}),
datasets.SplitGenerator(name=datasets.Split.TEST,
gen_kwargs={"filepath": data_files["test"]}),
]
def _generate_examples(self, filepath, sep=" "):
if self.config.name == "nested":
yield from self._generate_examples_nested(filepath, sep)
else:
yield from self._generate_examples_flat(filepath, sep)
def _generate_examples_flat(self, filepath, sep=" "):
logger.info("⏳ Generating examples from = %s", filepath)
with open(filepath, encoding="utf-8") as f:
guid = 0
tokens = []
ner_tags = []
for line in f:
if line.startswith("-DOCSTART-") or line == "" or line == "\n":
if tokens:
yield guid, {
"id": str(guid),
"sentence": " ".join(tokens),
"tokens": tokens,
"ner_tags": ner_tags,
"spans": tokens_with_tags_to_spans(ner_tags, tokens)
}
guid += 1
tokens = []
ner_tags = []
else:
splits = line.split(sep)
tokens.append(splits[0])
ner_tags.append(splits[1].rstrip())
# last example
yield guid, {
"id": str(guid),
"sentence": " ".join(tokens),
"tokens": tokens,
"ner_tags": ner_tags,
"spans": tokens_with_tags_to_spans(ner_tags, tokens)
}
def _generate_examples_nested(self, filepath, sep=" "):
logger.info("⏳ Generating examples from = %s", filepath)
with open(filepath, encoding="utf-8") as f:
guid = 0
tokens = []
ner_tags = []
ner_tags_2 = []
ner_tags_3 = []
ner_tags_4 = []
for line in f:
if line.startswith("-DOCSTART-") or line == "" or line == "\n":
if tokens:
yield guid, {
"id": str(guid),
"tokens": tokens,
"ner_tags": ner_tags,
"ner_tags_2": ner_tags_2,
"ner_tags_3": ner_tags_3,
"ner_tags_4": ner_tags_4,
}
guid += 1
tokens = []
ner_tags = []
ner_tags_2 = []
ner_tags_3 = []
ner_tags_4 = []
else:
splits = line.split(sep)
tokens.append(splits[0])
ner_tags.append(splits[1].rstrip())
ner_tags_2.append(splits[2].rstrip())
ner_tags_3.append(splits[3].rstrip())
ner_tags_4.append(splits[4].rstrip())
# last example
yield guid, {
"id": str(guid),
"tokens": tokens,
"ner_tags": ner_tags,
"ner_tags_2": ner_tags_2,
"ner_tags_3": ner_tags_3,
"ner_tags_4": ner_tags_4,
}
|