File size: 5,106 Bytes
4a9e2e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import json
import jinja2

import datasets

logger = datasets.logging.get_logger(__name__)

_LANG = ["ar", "en", "en-ar"]
_COLLECTION = ["ncwm", "ncwm-1000", "ncwm-5000", "ncwm-10000", "adgen", "dialog", "arce", "alpaca"]


class JinJa2Formatter:
    def __init__(self, instruction: str, input: str, output=""):
        self.instruction = jinja2.Template(instruction)
        self.input = jinja2.Template(input)
        self.output = jinja2.Template(output)

    def __call__(self, example):
        try:
            return {
                "instruction": self.instruction.render(**example),
                "input": self.input.render(**example),
                "output": self.output.render(**example),
            }
        except Exception as e:
            raise ValueError(f"Error while formatting example: {example}") from e


_FORMATTER = {
    "adgen": JinJa2Formatter(
        instruction="Generate advertisement for product according to its description, using the language provided in the contents.",
        input="Product:{{product}}\nDescription:{{description}}",
        output="{{ad}}",
    ),
    "dialog": JinJa2Formatter(
        instruction="Summarize the dialogue with respect to the provided topic. Use <end> to end your response",
        input="Dialogue:{{dialogue}}\nTopic:{{topic}}",
        output="{{summary}}",
    ),
    "arce": JinJa2Formatter(
        instruction="Question:{{question}}\nChoices:{{choices.text}}",
        input="",
        output="{{choices.text[choices.label.index(answerKey)]}}",
    ),
    "ncwm": JinJa2Formatter(
        instruction="{{instruction}}",
        input="{{input}}",
        output="{{output}}",
    ),
    "alpaca": JinJa2Formatter(
        instruction="{{instruction}}",
        input="{{input}}",
        output="{{output}}",
    ),
}

_FORMATTER["ncwm-1000"] = _FORMATTER["ncwm"]
_FORMATTER["ncwm-5000"] = _FORMATTER["ncwm"]
_FORMATTER["ncwm-10000"] = _FORMATTER["ncwm"]


class MultilingualConfig(datasets.BuilderConfig):
    """BuilderConfig for Alpaca"""

    def __init__(self, lang: str, collection: str, **kwargs):
        """
        Args:
            lang: string, language for the input text
            collection: string, collection name
            **kwargs: keyword arguments forwarded to super.
        """
        super(MultilingualConfig, self).__init__(**kwargs)
        self.lang = lang
        self.collection = collection


def _get_config(collection, lang):
    return MultilingualConfig(lang=lang, collection=collection, name=f"{collection}_{lang}")


class Multilingual(datasets.GeneratorBasedBuilder):
    VERSION = datasets.Version("1.0.0")
    BUILDER_CONFIGS = [
        _get_config("adgen", "ar"),
        _get_config("adgen", "en"),
        _get_config("dialog", "ar"),
        _get_config("dialog", "en"),
        _get_config("arce", "en"),
        _get_config("arce", "ar"),
        _get_config("ncwm", "en-ar"),
        _get_config("ncwm-1000", "en-ar"),
        _get_config("ncwm-5000", "en-ar"),
        _get_config("ncwm-10000", "en-ar"),
        _get_config("alpaca", "en"),
    ]
    BUILDER_CONFIG_CLASS = MultilingualConfig

    def _info(self):
        return datasets.DatasetInfo(
            features=datasets.Features(
                {
                    "id": datasets.Value("string"),
                    "instruction": datasets.Value("string"),
                    "input": datasets.Value("string"),
                    "output": datasets.Value("string"),
                }
            ),
        )

    def _split_generators(self, dl_manager):
        splits_generators = []
        for name in [
            datasets.Split.TRAIN,
            datasets.Split.TEST,
            datasets.Split.VALIDATION,
        ]:
            filepath = os.path.join(
                self.base_path,
                f"{self.config.collection}_{self.config.lang}_{name}.jsonl",
            )
            if os.path.exists(filepath):
                splits_generators.append(datasets.SplitGenerator(name=name, gen_kwargs={"filepath": filepath}))
        if not splits_generators:
            raise ValueError("no splits found")
        return splits_generators

    def _generate_examples(self, filepath):
        """This function returns the examples in the raw (text) form."""
        logger.info("[multilingual] generating examples from = %s", filepath)

        formatter = None
        if f"{self.config.collection}_{self.config.lang}" in _FORMATTER:
            formatter = _FORMATTER[f"{self.config.collection}_{self.config.lang}"]
        elif f"{self.config.collection}" in _FORMATTER:
            formatter = _FORMATTER[f"{self.config.collection}"]
        else:
            raise ValueError(
                f"Formatter for the collection `{self.config.collection}` and language `{self.config.lang}` not found."
            )

        with open(filepath, encoding="utf-8") as f:
            samples = [json.loads(x) for x in f.readlines()]
            id_ = 0
            for sample in samples:
                yield id_, formatter(sample) | {"id": str(id_)}
                id_ += 1