File size: 7,950 Bytes
b805ec1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b5b66bb
b805ec1
 
 
 
 
 
a535d7e
b805ec1
 
 
 
 
 
 
 
 
 
 
 
 
540af0c
b805ec1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3324655
 
 
b805ec1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
540af0c
b805ec1
 
 
 
 
 
 
 
31f0ac2
 
c742c76
e27722d
b805ec1
 
 
 
 
 
 
 
 
 
 
 
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
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import itertools
import json
from typing import Sequence

import datasets

logger = datasets.logging.get_logger(__name__)

_CITATION = """\
@InProceedings{10.1007/978-3-031-08754-7_70,
  author="Janz, Arkadiusz
  and Dziob, Agnieszka
  and Oleksy, Marcin
  and Baran, Joanna",
  editor="Groen, Derek
  and de Mulatier, Cl{\'e}lia
  and Paszynski, Maciej
  and Krzhizhanovskaya, Valeria V.
  and Dongarra, Jack J.
  and Sloot, Peter M. A.",
  title="A Unified Sense Inventory for Word Sense Disambiguation in Polish",
  booktitle="Computational Science -- ICCS 2022",
  year="2022",
  publisher="Springer International Publishing",
  address="Cham",
  pages="682--689",
  isbn="978-3-031-08754-7"
}
"""
_DESCRIPTION = """\
Polish WSD training data manually annotated by experts according to plWordNet-4.2.
"""

_LICENSE = "cc-by-4.0"

_BASE_URL = "https://huggingface.co/datasets/clarin-knext/wsd_polish_datasets/resolve/main/data/"

_CORPUS_NAMES = [
    "sherlock",
    "skladnica",
    "wikiglex",
    "emoglex",
    "walenty",
    "kpwr",
    "kpwr-100",
]

_DATA_TYPES = [
    "sentence",
    "text",
]

_URLS = {
    "text": {corpus: f"{_BASE_URL}{corpus}_text.jsonl" for corpus in _CORPUS_NAMES},
    "sentence": {
        corpus: f"{_BASE_URL}{corpus}_sentences.jsonl" for corpus in _CORPUS_NAMES
    },
}


class WsdPolishBuilderConfig(datasets.BuilderConfig):
    def __init__(
        self,
        data_urls: Sequence[str],
        corpus: str,
        data_type: str,
        **kwargs,
    ):
        super(WsdPolishBuilderConfig, self).__init__(
            name=f"{corpus}_{data_type}",
            version=datasets.Version("1.0.0"),
            **kwargs,
        )

        self.data_type = data_type
        self.corpus = corpus
        self.data_urls = data_urls
        if self.data_type not in _DATA_TYPES:
            raise ValueError(
                f"Corpus type {self.data_type} is not supported. Enter one of: {_DATA_TYPES}"
            )
        if self.corpus not in (*_CORPUS_NAMES, "all"):
            raise ValueError(
                f"Corpus name `{self.corpus}` is not available. Enter one of: {(*_CORPUS_NAMES, 'all')}"
            )


class WsdPolishDataset(datasets.GeneratorBasedBuilder):
    """Polish WSD training data"""

    BUILDER_CONFIGS = [
        WsdPolishBuilderConfig(
            corpus=corpus_name,
            data_type=data_type,
            data_urls=[_URLS[data_type][corpus_name]],
            description=f"Data part covering `{corpus_name}` corpora in `{data_type}` segmentation.",
        )
        for corpus_name, data_type in itertools.product(_CORPUS_NAMES, _DATA_TYPES)
    ]
    BUILDER_CONFIGS.extend(
        [
            WsdPolishBuilderConfig(
                corpus="all",
                data_type=data_type,
                data_urls=list(_URLS[data_type].values()),
                description=f"Data part covering `all` corpora in `{data_type}` segmentation.",
            )
            for data_type in _DATA_TYPES
        ]
    )

    DEFAULT_CONFIG_NAME = "all_text"

    def _info(self) -> datasets.DatasetInfo:
        text_features = {
            "text": datasets.Value("string"),
            "tokens": datasets.features.Sequence(
                dict(
                    {
                        "position": datasets.features.Sequence(
                            length=2,
                            feature=datasets.Value("int32"),
                        ),
                        "orth": datasets.Value("string"),
                        "lemma": datasets.Value("string"),
                        "pos": datasets.Value("string"),
                    }
                ),
            ),
            "phrases": datasets.features.Sequence(
                dict(
                    {
                        "indices": datasets.features.Sequence(
                            feature=datasets.Value("int32")
                        ),
                        "head": datasets.Value("int32"),
                        "lemma": datasets.Value("string"),
                    }
                ),
            ),
            "wsd": datasets.features.Sequence(
                dict(
                    {
                        "index": datasets.Value("int32"),
                        "plWN_syn_id": datasets.Value("string"),
                        "plWN_lex_id": datasets.Value("string"),
                        "PWN_syn_id": datasets.Value("string"),
                        "bn_syn_id": datasets.Value("string"),
                        "mapping_relation": datasets.Value("string")
                    }
                ),
            ),
        }
        if self.config.data_type == "sentence":
            features = datasets.Features(
                {
                    "sentences": datasets.features.Sequence(text_features),
                }
            )
        else:
            features = datasets.Features(text_features)

        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=features,
            supervised_keys=None,
            license=_LICENSE,
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager):
        filepaths = dl_manager.download_and_extract(self.config.data_urls)
        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={
                    "filepaths": filepaths,
                },
            ),
        ]

    def _generate_examples(self, filepaths: Sequence[str]):
        key_iter = 0
        for filepath in filepaths:
            with open(filepath, encoding="utf-8") as f:
                for data in (json.loads(line) for line in f):
                    if self.config.data_type == "sentence":
                        yield key_iter, {
                            "sentences": [
                                self._process_example(sent)
                                for sent in data["sentences"]
                            ]
                        }
                    else:
                        data.pop("context_file")
                        yield key_iter, self._process_example(data)

                    key_iter += 1

    @staticmethod
    def _process_example(data: dict) -> dict:
        return {
            "text": data["text"],
            "tokens": [
                {
                    "position": tok["position"],
                    "orth": tok["orth"],
                    "lemma": tok["lemma"],
                    "pos":tok["pos"],
                }
                for tok in data["tokens"]
            ],
            "wsd": [
                {
                    "index": tok["index"],
                    "plWN_syn_id": tok["plWN_syn_id"],
                    "plWN_lex_id": tok["plWN_lex_id"],
                    # "PWN_syn_id": tok["PWN_syn_id"],
                    # "bn_syn_id": tok["bn_syn_id"],
                    # "mapping_relation":  tok["mapping_relation"],

                }
                for tok in data["wsd"]
            ],
            "phrases": [
                {
                    "indices": tok["indices"],
                    "head": tok["head"],
                    "lemma": tok["lemma"],
                }
                for tok in data["phrases"]
            ],
        }