utils.py 7.38 KB
Newer Older
JessicaOjo's avatar
JessicaOjo committed
1
import argparse
JessicaOjo's avatar
JessicaOjo committed
2

Israel Abebe Azime's avatar
Israel Abebe Azime committed
3
4
import yaml

JessicaOjo's avatar
JessicaOjo committed
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
languages = ['eng', 'amh', 'ibo', 'fra', 'sna', 'lin', 'wol', 'ewe', 'lug', 'xho', 'kin', 'twi', 'zul', 'orm', 'yor',
             'hau', 'sot', 'swa']

languages_REGEX = {"eng": "The answer is (\\-?[0-9\\.\\,]+)",
                   "amh": "መልሱ (\\-?[0-9\\.\\,]+)",
                   "ibo": "Azịza ya bụ (\\-?[0-9\\.\\,]+)",
                   'fra': "La réponse est(\\-?[0-9\\.\\,]+)",
                   'sna': "Mhinduro kumubvunzo ndi (\\-?[0-9\\.\\,]+)",
                   'lin': "Eyano ezali (\\-?[0-9\\.\\,]+)",
                   'wol': "Tontu li (\\-?[0-9\\.\\,]+)",
                   'ewe': "ŋuɖoɖoae nye (\\-?[0-9\\.\\,]+)",
                   'lug': "Ansa eri (\\-?[0-9\\.\\,]+)",
                   'xho': "Impendulo ngu (\\-?[0-9\\.\\,]+)",
                   'kin': "Igisubizo ni (\\-?[0-9\\.\\,]+)",
                   'twi': "Ne nnyiano yɛ (\\-?[0-9\\.\\,]+)",
                   'zul': "Impendulo ithi (\\-?[0-9\\.\\,]+)",
                   'orm': "Deebiin isaa (\\-?[0-9\\.\\,]+)",
                   'yor': "Ìdáhùn náà ni (\\-?[0-9\\.\\,]+)",
                   'hau': "Amsar ita ce (\\-?[0-9\\.\\,]+)",
                   'sot': "Karabo ke (\\-?[0-9\\.\\,]+)",
                   'swa': "Jibu ni (\\-?[0-9\\.\\,]+)",
                   }

LANGUAGES = {}

for lang in languages:
    if lang == 'amh':
        LANGUAGES[lang] = {  # English
            "QUESTION": "ጥያቄ:",
            "ANSWER": "በቅደም ተከተል መልስ:",
            "DIRECT": "Answer:",
            "REGEX": languages_REGEX[lang]}
    elif lang == 'yor':
        LANGUAGES[lang] = {  # English
            "QUESTION": "Ìbéèrè:",
            "ANSWER": "Ìdáhùn lẹ́sẹsẹ:",
            "DIRECT": "Answer:",
            "REGEX": languages_REGEX[lang]}
Israel Abebe Azime's avatar
Israel Abebe Azime committed
43

JessicaOjo's avatar
JessicaOjo committed
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
    else:
        LANGUAGES[lang] = {  # English
            "QUESTION": "Question:",
            "ANSWER": "Step-by-Step Answer:",
            "DIRECT": "Answer:",
            "REGEX": languages_REGEX[lang]}


def add_regex_pattern(regex_pattern):
    if regex_pattern is None:
        return {}
    return {
        "filter_list": [
            {
                "name": "strict-match",
                "filter": [
                    {
                        "function": "regex",
                        "regex_pattern": f"""{regex_pattern}""",
                    },
                    {
                        "function": "take_first",
                    },
                ],
            },
            {
                "name": "flexible-extract",
                "filter": [
                    {
                        "function": "regex",
                        "regex_pattern": """(-?[$0-9.,]{2,})|(-?[0-9]+)""",
                        "group_select": -1,
                    },
                    {
                        "function": "take_first",
                    },
                ],
            },
        ],
    }
JessicaOjo's avatar
JessicaOjo committed
84
85
86
87
88
89
90
91
92
93


def gen_lang_yamls(output_dir: str, overwrite: bool, mode: str) -> None:
    """
    Generate a yaml file for each language.

    :param output_dir: The directory to output the files to.
    :param overwrite: Whether to overwrite files if they already exist.
    """
    err = []
JessicaOjo's avatar
JessicaOjo committed
94
    for lang in LANGUAGES.keys():
JessicaOjo's avatar
JessicaOjo committed
95
        try:
JessicaOjo's avatar
JessicaOjo committed
96
97
98
99

            yaml_template = "cot_yaml"
            filter_list = {}
            DELIMITER = None
JessicaOjo's avatar
JessicaOjo committed
100
            if mode == "direct":
JessicaOjo's avatar
JessicaOjo committed
101
102
103
                ANSWER = LANGUAGES['eng']["DIRECT"]
                QUESTION = LANGUAGES['eng']["QUESTION"]
                REGEX = None
JessicaOjo's avatar
JessicaOjo committed
104
                task_name = f"afrimgsm_direct_{lang}"
JessicaOjo's avatar
JessicaOjo committed
105
106
107
108
109
110
111
                yaml_template = "direct_yaml"
            if mode == "direct-native":
                ANSWER = LANGUAGES[lang]["DIRECT"]
                QUESTION = LANGUAGES[lang]["QUESTION"]
                REGEX = None
                task_name = f"afrimgsm_direct_native_{lang}"
                yaml_template = "direct_native_yaml"
JessicaOjo's avatar
JessicaOjo committed
112
            elif mode == "native-cot":
JessicaOjo's avatar
JessicaOjo committed
113
114
115
                ANSWER = LANGUAGES[lang]["ANSWER"]
                REGEX = LANGUAGES[lang]["REGEX"]
                QUESTION = LANGUAGES[lang]["QUESTION"]
JessicaOjo's avatar
JessicaOjo committed
116
                task_name = f"afrimgsm_native_cot_{lang}"
JessicaOjo's avatar
JessicaOjo committed
117
118
                filter_list = add_regex_pattern(REGEX)
                DELIMITER = "" if lang in ["zh", "ja"] else None
JessicaOjo's avatar
JessicaOjo committed
119
            elif mode == "en-cot":
JessicaOjo's avatar
JessicaOjo committed
120
121
122
                ANSWER = LANGUAGES["eng"]["ANSWER"]
                REGEX = LANGUAGES["eng"]["REGEX"]
                QUESTION = LANGUAGES["eng"]["QUESTION"]
JessicaOjo's avatar
JessicaOjo committed
123
                task_name = f"afrimgsm_en_cot_{lang}"
JessicaOjo's avatar
JessicaOjo committed
124
125
126
127
            elif mode == "translate-direct":
                ANSWER = LANGUAGES['eng']["DIRECT"]
                QUESTION = LANGUAGES['eng']["QUESTION"]
                REGEX = None
JessicaOjo's avatar
JessicaOjo committed
128
                task_name = f"afrimgsm_translate_direct_{lang}"
JessicaOjo's avatar
JessicaOjo committed
129
                yaml_template = "translate_direct_yaml"
JessicaOjo's avatar
JessicaOjo committed
130
131

            file_name = f"{task_name}.yaml"
JessicaOjo's avatar
JessicaOjo committed
132
            ANSWER_TO_SKIP = len(LANGUAGES[lang]["ANSWER"]) + 1
JessicaOjo's avatar
JessicaOjo committed
133
            with open(
JessicaOjo's avatar
JessicaOjo committed
134
                    f"{output_dir}/{file_name}", "w" if overwrite else "x", encoding="utf8"
JessicaOjo's avatar
JessicaOjo committed
135
136
137
138
139
140
            ) as f:
                f.write("# Generated by utils.py\n")
                yaml.dump(
                    {
                        "include": yaml_template,
                        "dataset_name": lang,
JessicaOjo's avatar
JessicaOjo committed
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
                        "task": f"{task_name}",
                        "doc_to_text": f"""{{% if answer is not none %}}"""
                                       f"""{{{{question+"\\n{ANSWER}"}}}}"""
                                       f"""{{% else %}}"""
                                       f"""{{{{"{QUESTION} "+question+"\\n{ANSWER}"}}}}"""
                                       f"""{{% endif %}}""",
                        "doc_to_target": f"""{{% if answer is not none %}}"""
                                         f"""{{{{answer[{ANSWER_TO_SKIP}:]}}}}"""
                                         f"""{{% else %}}"""
                                         f"""{{{{answer_number|string}}}}"""
                                         f"""{{% endif %}}""",
                        **filter_list,
                        "generation_kwargs": {
                            "until": [QUESTION, "</s>", "<|im_end|>"],
                            "do_sample": False,
                        },
                        **({"target_delimiter": DELIMITER} if DELIMITER else {}),
JessicaOjo's avatar
JessicaOjo committed
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
                    },
                    f,
                    allow_unicode=True,
                    width=float("inf"),
                )
        except FileExistsError:
            err.append(file_name)

    if len(err) > 0:
        raise FileExistsError(
            "Files were not created because they already exist (use --overwrite flag):"
            f" {', '.join(err)}"
        )


def main() -> None:
    """Parse CLI args and generate language-specific yaml files."""
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--overwrite",
JessicaOjo's avatar
JessicaOjo committed
178
        default=False,
JessicaOjo's avatar
JessicaOjo committed
179
180
181
182
        action="store_true",
        help="Overwrite files if they already exist",
    )
    parser.add_argument(
JessicaOjo's avatar
JessicaOjo committed
183
        "--output-dir", default=".", help="Directory to write yaml files to"
JessicaOjo's avatar
JessicaOjo committed
184
185
186
    )
    parser.add_argument(
        "--mode",
Israel Abebe Azime's avatar
Israel Abebe Azime committed
187
        default="native-cot",
JessicaOjo's avatar
JessicaOjo committed
188
        choices=["direct", "direct-native", "native-cot", "en-cot", "translate-direct"],
JessicaOjo's avatar
JessicaOjo committed
189
190
191
192
193
194
195
196
        help="Mode of chain-of-thought",
    )
    args = parser.parse_args()

    gen_lang_yamls(output_dir=args.output_dir, overwrite=args.overwrite, mode=args.mode)


if __name__ == "__main__":
JessicaOjo's avatar
JessicaOjo committed
197
    main()