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

Israel Abebe Azime's avatar
Israel Abebe Azime committed
3
import yaml
JessicaOjo's avatar
JessicaOjo committed
4
5
languages = ['eng', 'amh', 'ibo', 'fra', 'sna', 'lin', 'wol', 'ewe', 'lug', 'xho', 'kin', 'twi', 'zul', 'orm', 'yor', 'hau', 'sot', 'swa']

Israel Abebe Azime's avatar
Israel Abebe Azime committed
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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\\.\\,]+)",
                    }  

Israel Abebe Azime's avatar
Israel Abebe Azime committed
26
27
28
LANGUAGES = {}

for lang in languages:
Israel Abebe Azime's avatar
Israel Abebe Azime committed
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
    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]} 
        
    else:
        LANGUAGES[lang] = {  # English
            "QUESTION": "Question:",
            "ANSWER": "Step-by-Step Answer:",
            "DIRECT": "Answer:",
            "REGEX": languages_REGEX[lang]} 
Israel Abebe Azime's avatar
Israel Abebe Azime committed
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


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
82
83
84
85
86
87
88
89
90
91


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 = []
Israel Abebe Azime's avatar
Israel Abebe Azime committed
92
    for lang in LANGUAGES.keys():
JessicaOjo's avatar
JessicaOjo committed
93
        try:
Israel Abebe Azime's avatar
Israel Abebe Azime committed
94
95
96
97

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

            file_name = f"{task_name}.yaml"
Israel Abebe Azime's avatar
Israel Abebe Azime committed
131
            ANSWER_TO_SKIP = len(LANGUAGES[lang]["ANSWER"]) + 1
JessicaOjo's avatar
JessicaOjo committed
132
133
134
135
136
137
138
139
            with open(
                f"{output_dir}/{file_name}", "w" if overwrite else "x", encoding="utf8"
            ) as f:
                f.write("# Generated by utils.py\n")
                yaml.dump(
                    {
                        "include": yaml_template,
                        "dataset_name": lang,
Israel Abebe Azime's avatar
Israel Abebe Azime committed
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
                        "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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
                    },
                    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",
Israel Abebe Azime's avatar
Israel Abebe Azime committed
177
        default=False,
JessicaOjo's avatar
JessicaOjo committed
178
179
180
181
        action="store_true",
        help="Overwrite files if they already exist",
    )
    parser.add_argument(
Israel Abebe Azime's avatar
Israel Abebe Azime committed
182
        "--output-dir", default=".", help="Directory to write yaml files to"
JessicaOjo's avatar
JessicaOjo committed
183
184
185
    )
    parser.add_argument(
        "--mode",
Israel Abebe Azime's avatar
Israel Abebe Azime committed
186
        default="native-cot",
Israel Abebe Azime's avatar
Israel Abebe Azime committed
187
        choices=["direct","direct-native", "native-cot", "en-cot","translate-direct"],
JessicaOjo's avatar
JessicaOjo committed
188
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__":
    main()