samuelcahyawijaya commited on
Commit
17c2226
1 Parent(s): 81f83cc

Upload nusatranslation_mt.py

Browse files
Files changed (1) hide show
  1. nusatranslation_mt.py +235 -0
nusatranslation_mt.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ from typing import Dict, List, Tuple
3
+ import re
4
+
5
+
6
+ import datasets
7
+ import pandas as pd
8
+
9
+ from nusacrowd.utils import schemas
10
+ from nusacrowd.utils.configs import NusantaraConfig
11
+ from nusacrowd.utils.constants import DEFAULT_NUSANTARA_VIEW_NAME, DEFAULT_SOURCE_VIEW_NAME, Tasks
12
+
13
+ _DATASETNAME = "nusatranslation_mt"
14
+ _SOURCE_VIEW_NAME = DEFAULT_SOURCE_VIEW_NAME
15
+ _UNIFIED_VIEW_NAME = DEFAULT_NUSANTARA_VIEW_NAME
16
+
17
+ _LANGUAGES = ["btk", "bew", "bug", "jav", "mad", "mak", "min", "mui", "rej", "sun"] # We follow ISO639-3 language code (https://iso639-3.sil.org/code_tables/639/data)
18
+ _LOCAL = False
19
+
20
+ _CITATION = """\
21
+ @unpublished{anonymous2023nusawrites:,
22
+ title={NusaWrites: Constructing High-Quality Corpora for Underrepresented and Extremely Low-Resource Languages},
23
+ author={Anonymous},
24
+ journal={OpenReview Preprint},
25
+ year={2023},
26
+ note={anonymous preprint under review}
27
+ }
28
+ """
29
+
30
+ _DESCRIPTION = """\
31
+ Democratizing access to natural language processing (NLP) technology is crucial, especially for underrepresented and extremely low-resource languages. Previous research has focused on developing labeled and unlabeled corpora for these languages through online scraping and document translation. While these methods have proven effective and cost-efficient, we have identified limitations in the resulting corpora, including a lack of lexical diversity and cultural relevance to local communities. To address this gap, we conduct a case study on Indonesian local languages. We compare the effectiveness of online scraping, human translation, and paragraph writing by native speakers in constructing datasets. Our findings demonstrate that datasets generated through paragraph writing by native speakers exhibit superior quality in terms of lexical diversity and cultural content. In addition, we present the NusaWrites benchmark, encompassing 12 underrepresented and extremely low-resource languages spoken by millions of individuals in Indonesia. Our empirical experiment results using existing multilingual large language models conclude the need to extend these models to more underrepresented languages.
32
+ We introduce a novel high quality human curated corpora, i.e., NusaMenulis, which covers 12 languages spoken in Indonesia. The resource extend the coverage of languages to 5 new languages, i.e., Ambon (abs), Bima (bhp), Makassarese (mak), Palembang / Musi (mui), and Rejang (rej).
33
+ For the rhetoric mode classification task, we cover 5 rhetoric modes, i.e., narrative, persuasive, argumentative, descriptive, and expository.
34
+ """
35
+
36
+ _HOMEPAGE = "https://github.com/IndoNLP/nusatranslation/tree/main/datasets/mt"
37
+
38
+ _LICENSE = "Creative Commons Attribution Share-Alike 4.0 International"
39
+
40
+ _SUPPORTED_TASKS = [Tasks.MACHINE_TRANSLATION]
41
+
42
+ _SOURCE_VERSION = "1.0.0"
43
+
44
+ _NUSANTARA_VERSION = "1.0.0"
45
+
46
+ _URLS = {
47
+ "train": "https://raw.githubusercontent.com/IndoNLP/nusa-writes/main/data/nusa_kalimat-mt-{lang}-train.csv",
48
+ "validation": "https://raw.githubusercontent.com/IndoNLP/nusa-writes/main/data/nusa_kalimat-mt-{lang}-valid.csv",
49
+ "test": "https://raw.githubusercontent.com/IndoNLP/nusa-writes/main/data/nusa_kalimat-mt-{lang}-test.csv",
50
+ }
51
+
52
+
53
+ # def nusantara_config_constructor(lang, schema, version):
54
+ # """Construct NusantaraConfig with nusatranslation_mt_{lang}_{schema} as the name format"""
55
+ # if schema != "source" and schema != "nusantara_t2t":
56
+ # raise ValueError(f"Invalid schema: {schema}")
57
+
58
+ # if lang == "":
59
+ # return NusantaraConfig(
60
+ # name="nusatranslation_mt_{schema}".format(schema=schema),
61
+ # version=datasets.Version(version),
62
+ # description="nusatranslation_mt with {schema} schema for all 12 languages".format(schema=schema),
63
+ # schema=schema,
64
+ # subset_id="nusatranslation_mt",
65
+ # )
66
+ # else:
67
+ # return NusantaraConfig(
68
+ # name="nusatranslation_mt_{lang}_{schema}".format(lang=lang, schema=schema),
69
+ # version=datasets.Version(version),
70
+ # description="nusatranslation_mt with {schema} schema for {lang} language".format(lang=lang, schema=schema),
71
+ # schema=schema,
72
+ # subset_id="nusatranslation_mt",
73
+ # )
74
+
75
+
76
+ LANGUAGES_MAP = {
77
+ "abs": "ambon",
78
+ "btk": "batak",
79
+ "bew": "betawi",
80
+ "bhp": "bima",
81
+ "jav": "javanese",
82
+ "mad": "madurese",
83
+ "mak": "makassarese",
84
+ "min": "minangkabau",
85
+ "mui": "musi",
86
+ "rej": "rejang",
87
+ "sun": "sundanese",
88
+ }
89
+
90
+
91
+ class NusaTranslationMT(datasets.GeneratorBasedBuilder):
92
+ """NusaTranslation-MT is a parallel corpus for training and benchmarking machine translation models from 11 Indonesian local language to Bahasa Indonesia. The data is presented in csv format with 2 columns, where one column contain sentence in Bahasa and another in the local language."""
93
+
94
+ BUILDER_CONFIGS = (
95
+ [
96
+ NusantaraConfig(
97
+ name=f"nusatranslation_mt_ind_{subset}_source",
98
+ version=datasets.Version(_SOURCE_VERSION),
99
+ description=f"nusatranslation_mt ind2{subset} source schema",
100
+ schema="source",
101
+ subset_id=f"nusatranslation_mt",
102
+ )
103
+ for subset in _LANGUAGES[1:]
104
+ ]
105
+ + [
106
+ NusantaraConfig(
107
+ name=f"nusatranslation_mt_ind_{subset}_nusantara_t2t",
108
+ version=datasets.Version(_NUSANTARA_VERSION),
109
+ description=f"nusatranslation_mt ind2{subset} Nusantara schema",
110
+ schema="nusantara_t2t",
111
+ subset_id=f"nusatranslation_mt",
112
+ )
113
+ for subset in _LANGUAGES[1:]
114
+ ]
115
+ + [
116
+ NusantaraConfig(
117
+ name=f"nusatranslation_mt_{subset}_ind_source",
118
+ version=datasets.Version(_SOURCE_VERSION),
119
+ description=f"nusatranslation_mt {subset}2ind source schema",
120
+ schema="source",
121
+ subset_id=f"nusatranslation_mt",
122
+ )
123
+ for subset in _LANGUAGES[1:]
124
+ ]
125
+ + [
126
+ NusantaraConfig(
127
+ name=f"nusatranslation_mt_{subset}_ind_nusantara_t2t",
128
+ version=datasets.Version(_NUSANTARA_VERSION),
129
+ description=f"nusatranslation_mt {subset}2ind Nusantara schema",
130
+ schema="nusantara_t2t",
131
+ subset_id=f"nusatranslation_mt",
132
+ )
133
+ for subset in _LANGUAGES[1:]
134
+ ]
135
+ )
136
+
137
+ DEFAULT_CONFIG_NAME = "nusatranslation_mt_jav_ind_source"
138
+
139
+ def _info(self):
140
+ if self.config.schema == "source":
141
+ features = datasets.Features({"id": datasets.Value("string"), "text": datasets.Value("string"), "label": datasets.Value("string")})
142
+ elif self.config.schema == "nusantara_t2t":
143
+ features = schemas.text2text_features
144
+
145
+ return datasets.DatasetInfo(
146
+ description=_DESCRIPTION,
147
+ features=features,
148
+ homepage=_HOMEPAGE,
149
+ license=_LICENSE,
150
+ citation=_CITATION,
151
+ )
152
+
153
+ def _split_generators(self, dl_manager: datasets.DownloadManager) -> List[datasets.SplitGenerator]:
154
+ """Returns SplitGenerators."""
155
+ if self.config.name == "nusatranslation_mt_source" or self.config.name == "nusatranslation_mt_nusantara_t2t":
156
+ # Load all 12 languages
157
+ train_csv_path = dl_manager.download_and_extract([_URLS["train"].format(lang=lang) for lang in LANGUAGES_MAP])
158
+ validation_csv_path = dl_manager.download_and_extract([_URLS["validation"].format(lang=lang) for lang in LANGUAGES_MAP])
159
+ test_csv_path = dl_manager.download_and_extract([_URLS["test"].format(lang=lang) for lang in LANGUAGES_MAP])
160
+ else:
161
+ lang = self.config.name.split("_")[2] if self.config.name.split("_")[2] != "ind" else self.config.name.split("_")[3]
162
+ train_csv_path = Path(dl_manager.download_and_extract(_URLS["train"].format(lang=lang)))
163
+ validation_csv_path = Path(dl_manager.download_and_extract(_URLS["validation"].format(lang=lang)))
164
+ test_csv_path = Path(dl_manager.download_and_extract(_URLS["test"].format(lang=lang)))
165
+
166
+ return [
167
+ datasets.SplitGenerator(
168
+ name=datasets.Split.TRAIN,
169
+ gen_kwargs={"filepath": train_csv_path},
170
+ ),
171
+ datasets.SplitGenerator(
172
+ name=datasets.Split.VALIDATION,
173
+ gen_kwargs={"filepath": validation_csv_path},
174
+ ),
175
+ datasets.SplitGenerator(
176
+ name=datasets.Split.TEST,
177
+ gen_kwargs={"filepath": test_csv_path},
178
+ ),
179
+ ]
180
+
181
+ def _merge_subsets(self, df, subsets, revert=False):
182
+ if not subsets:
183
+ return None
184
+ # df = None
185
+ # print(dfs)
186
+ # print(subsets)
187
+ orig_columns = df.columns.tolist()
188
+ print(df.columns)
189
+
190
+ df.columns = orig_columns[:1] + ["label", "text"] if revert else orig_columns[:1] + ["text", "label"]
191
+ return df
192
+
193
+ def get_domain_data(self, dfs):
194
+ domain = self.config.name
195
+ matched_domain = re.findall(r"nusatranslation_mt_.*?_.*?_", domain)
196
+
197
+ assert len(matched_domain) == 1
198
+ domain = matched_domain[0][:-1].replace("nusatranslation_mt_", "").split("_")
199
+ src_lang, tgt_lang = domain[0], domain[1]
200
+
201
+ subsets = LANGUAGES_MAP.get(src_lang if src_lang != "ind" else tgt_lang, None)
202
+ return src_lang, tgt_lang, self._merge_subsets(dfs, subsets, revert=(src_lang != "ind"))
203
+
204
+ def _generate_examples(self, filepath: Path) -> Tuple[int, Dict]:
205
+ if self.config.schema != "source" and self.config.schema != "nusantara_t2t":
206
+ raise ValueError(f"Invalid config schema: {self.config.schema}")
207
+
208
+ # print(filepath)
209
+ df = pd.read_csv(filepath)
210
+ # ldf = []
211
+ # for fp in filepath:
212
+ # ldf.append(pd.read_csv(fp))
213
+ src_lang, tgt_lang, df = self.get_domain_data((df))
214
+
215
+ if self.config.schema == "source":
216
+ for idx, row in enumerate(df.itertuples()):
217
+ ex = {
218
+ "id": str(idx),
219
+ "text": row.text,
220
+ "label": row.label,
221
+ }
222
+ yield idx, ex
223
+
224
+ elif self.config.schema == "nusantara_t2t":
225
+ for idx, row in enumerate(df.itertuples()):
226
+ ex = {
227
+ "id": str(idx),
228
+ "text_1": row.text,
229
+ "text_2": row.label,
230
+ "text_1_name": src_lang,
231
+ "text_2_name": tgt_lang,
232
+ }
233
+ yield idx, ex
234
+ else:
235
+ raise ValueError(f"Invalid config: {self.config.name}")