File size: 5,265 Bytes
f85e38a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# coding=utf-8
# Copyright 2023 Nonwestlit codebase authors the HuggingFace Datasets Authors.
#
# 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.

# Lint as: python3
"""Ottoman Literary Dataset from late 19th century up to early 20th century."""


import json
import warnings
from typing import List

import datasets
from transformers import PreTrainedTokenizerBase

logger = datasets.logging.get_logger(__name__)


_DESCRIPTION = """\
First level categorization of Ottoman articles.
"""

_URLS = {
    "train": "train.json",
    "val": "val.json",
    "test": "test.json",
}

_CLASS_NAMES = ["literary_text", "cultural_discourse", "other"]


class NonwestlitFirstLevelConfig(datasets.BuilderConfig):
    """BuilderConfig for Dataset."""

    def __init__(
        self, tokenizer: PreTrainedTokenizerBase = None, max_sequence_length: int = None, **kwargs
    ):
        """BuilderConfig for Dataset.

        Args:
            **kwargs: keyword arguments forwarded to super.
        """
        super(NonwestlitFirstLevelConfig, self).__init__(**kwargs)
        self.tokenizer = tokenizer
        self.max_sequence_length = max_sequence_length

    @property
    def features(self):
        return {
            "labels": datasets.ClassLabel(names=_CLASS_NAMES),
            "input_ids": datasets.Value("string"),
            "title": datasets.Value("string"),
            "iid": datasets.Value("uint32"),
            "chunk_id": datasets.Value("uint32"),
        }


class NonwestlitFirstLevelDataset(datasets.GeneratorBasedBuilder):
    """Nonwestlit Ottoman Classification Dataset"""

    BUILDER_CONFIGS = [
        NonwestlitFirstLevelConfig(
            name="seq_cls",
            version=datasets.Version("1.0.0", ""),
            description=_DESCRIPTION,
        )
    ]
    BUILDER_CONFIG_CLASS = NonwestlitFirstLevelConfig
    __current_id = 1
    __current_chunk_id = 1

    @property
    def __next_id(self):
        cid = self.__current_id
        self.__current_id += 1
        return cid

    @property
    def __next_chunk_id(self):
        cid = self.__current_chunk_id
        self.__current_chunk_id += 1
        return cid

    def __reset_chunk_id(self):
        self.__current_chunk_id = 1

    def _info(self):
        if self.config.tokenizer is None:
            raise RuntimeError(
                "For HF Datasets and for chunking to be carried out, 'tokenizer' must be given."
            )
        if "llama" in self.config.tokenizer.name_or_path:
            warnings.warn(
                "It is suggested to pass 'max_sequence_length' argument for Llama-2 model family. There "
                "might be errors for the data processing parts as `model_max_len` attributes are set to"
                "MAX_INT64 (?)."
            )
        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=datasets.Features(self.config.features),
        )

    def _split_generators(self, dl_manager):
        data_dir = dl_manager.download_and_extract(_URLS)

        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN, gen_kwargs={"filepath": data_dir["train"]}
            ),
            datasets.SplitGenerator(
                name=datasets.Split.VALIDATION, gen_kwargs={"filepath": data_dir["val"]}
            ),
            datasets.SplitGenerator(
                name=datasets.Split.TEST, gen_kwargs={"filepath": data_dir["test"]}
            ),
        ]

    def prepare_articles(self, article: str) -> List[str]:
        tokenizer = self.config.tokenizer
        model_inputs = tokenizer(
            article,
            truncation=True,
            padding=True,
            max_length=self.config.max_sequence_length,
            return_overflowing_tokens=True,
        )
        return tokenizer.batch_decode(model_inputs["input_ids"], skip_special_tokens=True)

    def _generate_examples(self, filepath):
        """This function returns the examples in the raw (text) form."""
        logger.info("generating examples from = %s", filepath)
        with open(filepath, encoding="utf-8") as f:
            dataset = json.load(f)

        chunk_id = 0
        for instance in dataset:
            iid = instance.get("id", self.__next_id)
            label = instance.get("label")
            article = self.prepare_articles(instance["article"])
            self.__reset_chunk_id()
            for chunk in article:
                chunk_inputs = {
                    "iid": iid,
                    "chunk_id": self.__next_chunk_id,
                    "title": instance["title"],
                    "input_ids": chunk,
                    "labels": int(label) - 1,
                }
                yield chunk_id, chunk_inputs
                chunk_id += 1