File size: 9,933 Bytes
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import tempfile
from pathlib import Path

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"


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")),
                "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']
                    )
                ),
            }
        )


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),
                            "tokens": tokens,
                            "ner_tags": ner_tags,
                        }
                        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),
                "tokens": tokens,
                "ner_tags": ner_tags,
            }

    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,
            }