ryo0634 commited on
Commit
85d7559
1 Parent(s): 992436f

Initial commit

Browse files
Files changed (4) hide show
  1. JGLUE.py +357 -0
  2. README.md +79 -1
  3. preprocess_marc_ja.py +262 -0
  4. requirements.txt +3 -0
JGLUE.py ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This code is licensed under CC-BY-4.0 from the original work by shunk031.
3
+ The code is adapted from https://huggingface.co/datasets/shunk031/JGLUE/blob/main/JGLUE.py
4
+ with minor modifications to the code structure.
5
+ """
6
+
7
+
8
+ import json
9
+ from typing import Optional
10
+
11
+ import datasets as ds
12
+ import pandas as pd
13
+ from datasets.tasks import QuestionAnsweringExtractive
14
+
15
+ from .preprocess_marc_ja import preprocess_marc_ja, MarcJaConfig
16
+
17
+ _CITATION = """\
18
+ @inproceedings{kurihara-etal-2022-jglue,
19
+ title = "{JGLUE}: {J}apanese General Language Understanding Evaluation",
20
+ author = "Kurihara, Kentaro and
21
+ Kawahara, Daisuke and
22
+ Shibata, Tomohide",
23
+ booktitle = "Proceedings of the Thirteenth Language Resources and Evaluation Conference",
24
+ month = jun,
25
+ year = "2022",
26
+ address = "Marseille, France",
27
+ publisher = "European Language Resources Association",
28
+ url = "https://aclanthology.org/2022.lrec-1.317",
29
+ pages = "2957--2966",
30
+ abstract = "To develop high-performance natural language understanding (NLU) models, it is necessary to have a benchmark to evaluate and analyze NLU ability from various perspectives. While the English NLU benchmark, GLUE, has been the forerunner, benchmarks are now being released for languages other than English, such as CLUE for Chinese and FLUE for French; but there is no such benchmark for Japanese. We build a Japanese NLU benchmark, JGLUE, from scratch without translation to measure the general NLU ability in Japanese. We hope that JGLUE will facilitate NLU research in Japanese.",
31
+ }
32
+ @InProceedings{Kurihara_nlp2022,
33
+ author = "栗原健太郎 and 河原大輔 and 柴田知秀",
34
+ title = "JGLUE: 日本語言語理解ベンチマーク",
35
+ booktitle = "言語処理学会第28回年次大会",
36
+ year = "2022",
37
+ url = "https://www.anlp.jp/proceedings/annual_meeting/2022/pdf_dir/E8-4.pdf"
38
+ note= "in Japanese"
39
+ }
40
+ """
41
+
42
+ _DESCRIPTION = """\
43
+ JGLUE, Japanese General Language Understanding Evaluation, is built to measure the general NLU ability in Japanese. JGLUE has been constructed from scratch without translation. We hope that JGLUE will facilitate NLU research in Japanese.
44
+ """
45
+
46
+ _HOMEPAGE = "https://github.com/yahoojapan/JGLUE"
47
+
48
+ _LICENSE = """\
49
+ This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
50
+ """
51
+
52
+ _DESCRIPTION_CONFIGS = {
53
+ "MARC-ja": "MARC-ja is a dataset of the text classification task. This dataset is based on the Japanese portion of Multilingual Amazon Reviews Corpus (MARC) (Keung+, 2020).",
54
+ "JSTS": "JSTS is a Japanese version of the STS (Semantic Textual Similarity) dataset. STS is a task to estimate the semantic similarity of a sentence pair.",
55
+ "JNLI": "JNLI is a Japanese version of the NLI (Natural Language Inference) dataset. NLI is a task to recognize the inference relation that a premise sentence has to a hypothesis sentence.",
56
+ "JSQuAD": "JSQuAD is a Japanese version of SQuAD (Rajpurkar+, 2016), one of the datasets of reading comprehension.",
57
+ "JCommonsenseQA": "JCommonsenseQA is a Japanese version of CommonsenseQA (Talmor+, 2019), which is a multiple-choice question answering dataset that requires commonsense reasoning ability.",
58
+ }
59
+
60
+ _URLS = {
61
+ "MARC-ja": {
62
+ "data": "https://s3.amazonaws.com/amazon-reviews-pds/tsv/amazon_reviews_multilingual_JP_v1_00.tsv.gz",
63
+ "filter_review_id_list": {
64
+ "valid": "https://raw.githubusercontent.com/yahoojapan/JGLUE/main/preprocess/marc-ja/data/filter_review_id_list/valid.txt"
65
+ },
66
+ "label_conv_review_id_list": {
67
+ "valid": "https://raw.githubusercontent.com/yahoojapan/JGLUE/main/preprocess/marc-ja/data/label_conv_review_id_list/valid.txt"
68
+ },
69
+ },
70
+ "JSTS": {
71
+ "train": "https://raw.githubusercontent.com/yahoojapan/JGLUE/main/datasets/jsts-v1.1/train-v1.1.json",
72
+ "valid": "https://raw.githubusercontent.com/yahoojapan/JGLUE/main/datasets/jsts-v1.1/valid-v1.1.json",
73
+ },
74
+ "JNLI": {
75
+ "train": "https://raw.githubusercontent.com/yahoojapan/JGLUE/main/datasets/jnli-v1.1/train-v1.1.json",
76
+ "valid": "https://raw.githubusercontent.com/yahoojapan/JGLUE/main/datasets/jnli-v1.1/valid-v1.1.json",
77
+ },
78
+ "JSQuAD": {
79
+ "train": "https://raw.githubusercontent.com/yahoojapan/JGLUE/main/datasets/jsquad-v1.1/train-v1.1.json",
80
+ "valid": "https://raw.githubusercontent.com/yahoojapan/JGLUE/main/datasets/jsquad-v1.1/valid-v1.1.json",
81
+ },
82
+ "JCommonsenseQA": {
83
+ "train": "https://raw.githubusercontent.com/yahoojapan/JGLUE/main/datasets/jcommonsenseqa-v1.1/train-v1.1.json",
84
+ "valid": "https://raw.githubusercontent.com/yahoojapan/JGLUE/main/datasets/jcommonsenseqa-v1.1/valid-v1.1.json",
85
+ },
86
+ }
87
+
88
+
89
+ def dataset_info_jsts() -> ds.DatasetInfo:
90
+ features = ds.Features(
91
+ {
92
+ "sentence_pair_id": ds.Value("string"),
93
+ "yjcaptions_id": ds.Value("string"),
94
+ "sentence1": ds.Value("string"),
95
+ "sentence2": ds.Value("string"),
96
+ "label": ds.Value("float"),
97
+ }
98
+ )
99
+ return ds.DatasetInfo(
100
+ description=_DESCRIPTION,
101
+ citation=_CITATION,
102
+ homepage=_HOMEPAGE,
103
+ license=_LICENSE,
104
+ features=features,
105
+ )
106
+
107
+
108
+ def dataset_info_jnli() -> ds.DatasetInfo:
109
+ features = ds.Features(
110
+ {
111
+ "sentence_pair_id": ds.Value("string"),
112
+ "yjcaptions_id": ds.Value("string"),
113
+ "sentence1": ds.Value("string"),
114
+ "sentence2": ds.Value("string"),
115
+ "label": ds.ClassLabel(num_classes=3, names=["entailment", "contradiction", "neutral"]),
116
+ }
117
+ )
118
+ return ds.DatasetInfo(
119
+ description=_DESCRIPTION,
120
+ citation=_CITATION,
121
+ homepage=_HOMEPAGE,
122
+ license=_LICENSE,
123
+ features=features,
124
+ supervised_keys=None,
125
+ )
126
+
127
+
128
+ def dataset_info_jsquad() -> ds.DatasetInfo:
129
+ features = ds.Features(
130
+ {
131
+ "id": ds.Value("string"),
132
+ "title": ds.Value("string"),
133
+ "context": ds.Value("string"),
134
+ "question": ds.Value("string"),
135
+ "answers": ds.Sequence({"text": ds.Value("string"), "answer_start": ds.Value("int32")}),
136
+ "is_impossible": ds.Value("bool"),
137
+ }
138
+ )
139
+ return ds.DatasetInfo(
140
+ description=_DESCRIPTION,
141
+ citation=_CITATION,
142
+ homepage=_HOMEPAGE,
143
+ license=_LICENSE,
144
+ features=features,
145
+ supervised_keys=None,
146
+ task_templates=[
147
+ QuestionAnsweringExtractive(
148
+ question_column="question",
149
+ context_column="context",
150
+ answers_column="answers",
151
+ )
152
+ ],
153
+ )
154
+
155
+
156
+ def dataset_info_jcommonsenseqa() -> ds.DatasetInfo:
157
+ features = ds.Features(
158
+ {
159
+ "q_id": ds.Value("int64"),
160
+ "question": ds.Value("string"),
161
+ "choice0": ds.Value("string"),
162
+ "choice1": ds.Value("string"),
163
+ "choice2": ds.Value("string"),
164
+ "choice3": ds.Value("string"),
165
+ "choice4": ds.Value("string"),
166
+ "label": ds.ClassLabel(
167
+ num_classes=5,
168
+ names=["choice0", "choice1", "choice2", "choice3", "choice4"],
169
+ ),
170
+ }
171
+ )
172
+ return ds.DatasetInfo(
173
+ description=_DESCRIPTION,
174
+ citation=_CITATION,
175
+ homepage=_HOMEPAGE,
176
+ license=_LICENSE,
177
+ features=features,
178
+ )
179
+
180
+
181
+ def dataset_info_marc_ja() -> ds.DatasetInfo:
182
+ features = ds.Features(
183
+ {
184
+ "sentence": ds.Value("string"),
185
+ "label": ds.ClassLabel(num_classes=3, names=["positive", "negative", "neutral"]),
186
+ "review_id": ds.Value("string"),
187
+ }
188
+ )
189
+ return ds.DatasetInfo(
190
+ description=_DESCRIPTION,
191
+ citation=_CITATION,
192
+ homepage=_HOMEPAGE,
193
+ license=_LICENSE,
194
+ features=features,
195
+ )
196
+
197
+
198
+ class JGLUE(ds.GeneratorBasedBuilder):
199
+ VERSION = ds.Version("1.1.0")
200
+ BUILDER_CONFIGS = [
201
+ MarcJaConfig(
202
+ name="MARC-ja",
203
+ version=VERSION,
204
+ description=_DESCRIPTION_CONFIGS["MARC-ja"],
205
+ ),
206
+ ds.BuilderConfig(
207
+ name="JSTS",
208
+ version=VERSION,
209
+ description=_DESCRIPTION_CONFIGS["JSTS"],
210
+ ),
211
+ ds.BuilderConfig(
212
+ name="JNLI",
213
+ version=VERSION,
214
+ description=_DESCRIPTION_CONFIGS["JNLI"],
215
+ ),
216
+ ds.BuilderConfig(
217
+ name="JSQuAD",
218
+ version=VERSION,
219
+ description=_DESCRIPTION_CONFIGS["JSQuAD"],
220
+ ),
221
+ ds.BuilderConfig(
222
+ name="JCommonsenseQA",
223
+ version=VERSION,
224
+ description=_DESCRIPTION_CONFIGS["JCommonsenseQA"],
225
+ ),
226
+ ]
227
+
228
+ def _info(self) -> ds.DatasetInfo:
229
+ if self.config.name == "JSTS":
230
+ return dataset_info_jsts()
231
+ elif self.config.name == "JNLI":
232
+ return dataset_info_jnli()
233
+ elif self.config.name == "JSQuAD":
234
+ return dataset_info_jsquad()
235
+ elif self.config.name == "JCommonsenseQA":
236
+ return dataset_info_jcommonsenseqa()
237
+ elif self.config.name == "MARC-ja":
238
+ return dataset_info_marc_ja()
239
+ else:
240
+ raise ValueError(f"Invalid config name: {self.config.name}")
241
+
242
+ def __split_generators_marc_ja(self, dl_manager: ds.DownloadManager):
243
+ file_paths = dl_manager.download_and_extract(_URLS[self.config.name])
244
+
245
+ filter_review_id_list = file_paths["filter_review_id_list"]
246
+ label_conv_review_id_list = file_paths["label_conv_review_id_list"]
247
+
248
+ split_dfs = preprocess_marc_ja(
249
+ config=self.config,
250
+ data_file_path=file_paths["data"],
251
+ filter_review_id_list_paths=filter_review_id_list,
252
+ label_conv_review_id_list_paths=label_conv_review_id_list,
253
+ )
254
+ return [
255
+ ds.SplitGenerator(
256
+ name=ds.Split.TRAIN,
257
+ gen_kwargs={"split_df": split_dfs["train"]},
258
+ ),
259
+ ds.SplitGenerator(
260
+ name=ds.Split.VALIDATION,
261
+ gen_kwargs={"split_df": split_dfs["valid"]},
262
+ ),
263
+ ]
264
+
265
+ def __split_generators(self, dl_manager: ds.DownloadManager):
266
+ file_paths = dl_manager.download_and_extract(_URLS[self.config.name])
267
+ return [
268
+ ds.SplitGenerator(
269
+ name=ds.Split.TRAIN,
270
+ gen_kwargs={"file_path": file_paths["train"]},
271
+ ),
272
+ ds.SplitGenerator(
273
+ name=ds.Split.VALIDATION,
274
+ gen_kwargs={"file_path": file_paths["valid"]},
275
+ ),
276
+ ]
277
+
278
+ def _split_generators(self, dl_manager: ds.DownloadManager):
279
+ if self.config.name == "MARC-ja":
280
+ return self.__split_generators_marc_ja(dl_manager)
281
+ else:
282
+ return self.__split_generators(dl_manager)
283
+
284
+ def __generate_examples_marc_ja(self, split_df: Optional[pd.DataFrame] = None):
285
+ if split_df is None:
286
+ raise ValueError(f"Invalid preprocessing for {self.config.name}")
287
+
288
+ instances = split_df.to_dict(orient="records")
289
+ for i, data_dict in enumerate(instances):
290
+ yield i, data_dict
291
+
292
+ def __generate_examples_jsquad(self, file_path: Optional[str] = None):
293
+ if file_path is None:
294
+ raise ValueError(f"Invalid argument for {self.config.name}")
295
+
296
+ with open(file_path, "r") as rf:
297
+ json_data = json.load(rf)
298
+
299
+ for json_dict in json_data["data"]:
300
+ title = json_dict["title"]
301
+ paragraphs = json_dict["paragraphs"]
302
+
303
+ for paragraph in paragraphs:
304
+ context = paragraph["context"]
305
+ questions = paragraph["qas"]
306
+
307
+ for question_dict in questions:
308
+ q_id = question_dict["id"]
309
+ question = question_dict["question"]
310
+ answers = question_dict["answers"]
311
+ is_impossible = question_dict["is_impossible"]
312
+
313
+ example_dict = {
314
+ "id": q_id,
315
+ "title": title,
316
+ "context": context,
317
+ "question": question,
318
+ "answers": answers,
319
+ "is_impossible": is_impossible,
320
+ }
321
+
322
+ yield q_id, example_dict
323
+
324
+ def __generate_examples_jcommonsenseqa(self, file_path: Optional[str] = None):
325
+ if file_path is None:
326
+ raise ValueError(f"Invalid argument for {self.config.name}")
327
+
328
+ with open(file_path, "r") as rf:
329
+ for i, line in enumerate(rf):
330
+ json_dict = json.loads(line)
331
+ yield i, json_dict
332
+
333
+ def __generate_examples(self, file_path: Optional[str] = None):
334
+ if file_path is None:
335
+ raise ValueError(f"Invalid argument for {self.config.name}")
336
+
337
+ with open(file_path, "r") as rf:
338
+ for i, line in enumerate(rf):
339
+ json_dict = json.loads(line)
340
+ yield i, json_dict
341
+
342
+ def _generate_examples(
343
+ self,
344
+ file_path: Optional[str] = None,
345
+ split_df: Optional[pd.DataFrame] = None,
346
+ ):
347
+ if self.config.name == "MARC-ja":
348
+ yield from self.__generate_examples_marc_ja(split_df)
349
+
350
+ elif self.config.name == "JSQuAD":
351
+ yield from self.__generate_examples_jsquad(file_path)
352
+
353
+ elif self.config.name == "JCommonsenseQA":
354
+ yield from self.__generate_examples_jcommonsenseqa(file_path)
355
+
356
+ else:
357
+ yield from self.__generate_examples(file_path)
README.md CHANGED
@@ -1,3 +1,81 @@
1
  ---
2
- license: cc-by-4.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ annotations_creators:
3
+ - crowdsourced
4
+ language:
5
+ - ja
6
+ language_creators:
7
+ - crowdsourced
8
+ - found
9
+ license:
10
+ - cc-by-4.0
11
+ multilinguality:
12
+ - monolingual
13
+ pretty_name: JGLUE
14
+ size_categories: []
15
+ source_datasets:
16
+ - original
17
+ tags:
18
+ - MARC
19
+ - STS
20
+ - NLI
21
+ - SQuAD
22
+ - CommonsenseQA
23
+ task_categories:
24
+ - multiple-choice
25
+ - question-answering
26
+ - sentence-similarity
27
+ - text-classification
28
+ task_ids:
29
+ - multiple-choice-qa
30
+ - open-domain-qa
31
+ - multi-class-classification
32
+ - sentiment-classification
33
  ---
34
+
35
+ # Dataset Card for JGLUE
36
+
37
+ [![ACL2020 2020.acl-main.419](https://img.shields.io/badge/LREC2022-2022.lrec--1.317-red)](https://aclanthology.org/2022.lrec-1.317)
38
+
39
+ JGLUE is a benchmark to measure the ability of natural language understanding in Japanese. For further details please refer to [the original repository](https://github.com/yahoojapan/JGLUE).
40
+
41
+
42
+ ### Licensing Information
43
+
44
+ > This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
45
+
46
+ ### Citation Information
47
+
48
+ ```bibtex
49
+ @inproceedings{kurihara-etal-2022-jglue,
50
+ title = "{JGLUE}: {J}apanese General Language Understanding Evaluation",
51
+ author = "Kurihara, Kentaro and
52
+ Kawahara, Daisuke and
53
+ Shibata, Tomohide",
54
+ booktitle = "Proceedings of the Thirteenth Language Resources and Evaluation Conference",
55
+ month = jun,
56
+ year = "2022",
57
+ address = "Marseille, France",
58
+ publisher = "European Language Resources Association",
59
+ url = "https://aclanthology.org/2022.lrec-1.317",
60
+ pages = "2957--2966",
61
+ abstract = "To develop high-performance natural language understanding (NLU) models, it is necessary to have a benchmark to evaluate and analyze NLU ability from various perspectives. While the English NLU benchmark, GLUE, has been the forerunner, benchmarks are now being released for languages other than English, such as CLUE for Chinese and FLUE for French; but there is no such benchmark for Japanese. We build a Japanese NLU benchmark, JGLUE, from scratch without translation to measure the general NLU ability in Japanese. We hope that JGLUE will facilitate NLU research in Japanese.",
62
+ }
63
+ ```
64
+
65
+ ```bibtex
66
+ @InProceedings{Kurihara_nlp2022,
67
+ author = "栗原健太郎 and 河原大輔 and 柴田知秀",
68
+ title = "JGLUE: 日本語言語理解ベンチマーク",
69
+ booktitle = "言語処理学会第 28 回年次大会",
70
+ year = "2022",
71
+ url = "https://www.anlp.jp/proceedings/annual_meeting/2022/pdf_dir/E8-4.pdf"
72
+ note= "in Japanese"
73
+ }
74
+ ```
75
+
76
+ ### Contributions
77
+
78
+ Thanks to [Kentaro Kurihara](https://twitter.com/kkurihara_cs), [Daisuke Kawahara](https://twitter.com/daisukekawahar1), and [Tomohide Shibata](https://twitter.com/stomohide) for creating this dataset.
79
+
80
+
81
+ The code for integration with Hugging Face `datasets` is originally written by [Shunsuke Kitada](https://twitter.com/shunk031) and adapted from [this repository](https://huggingface.co/datasets/shunk031/JGLUE).
preprocess_marc_ja.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This code is licensed under CC-BY-4.0 from the original work by shunk031.
3
+ The code is adapted from https://huggingface.co/datasets/shunk031/JGLUE/blob/main/JGLUE.py
4
+ with minor modifications to the code structure.
5
+
6
+ This codebase provides pre-processing functionality for the MARC-ja dataset in the Japanese GLUE benchmark.
7
+ The original code can be found at https://github.com/yahoojapan/JGLUE/blob/main/preprocess/marc-ja/scripts/marc-ja.py.
8
+ """
9
+
10
+ import random
11
+ import warnings
12
+ from typing import Dict, List, Optional, Union
13
+ import string
14
+
15
+ import datasets as ds
16
+ import pandas as pd
17
+
18
+
19
+ class MarcJaConfig(ds.BuilderConfig):
20
+ def __init__(
21
+ self,
22
+ name: str = "MARC-ja",
23
+ is_han_to_zen: bool = False,
24
+ max_instance_num: Optional[int] = None,
25
+ max_char_length: int = 500,
26
+ is_pos_neg: bool = True,
27
+ train_ratio: float = 0.94,
28
+ val_ratio: float = 0.03,
29
+ test_ratio: float = 0.03,
30
+ output_testset: bool = False,
31
+ filter_review_id_list_valid: bool = True,
32
+ label_conv_review_id_list_valid: bool = True,
33
+ version: Optional[Union[ds.utils.Version, str]] = ds.utils.Version("0.0.0"),
34
+ data_dir: Optional[str] = None,
35
+ data_files: Optional[ds.data_files.DataFilesDict] = None,
36
+ description: Optional[str] = None,
37
+ ) -> None:
38
+ super().__init__(
39
+ name=name,
40
+ version=version,
41
+ data_dir=data_dir,
42
+ data_files=data_files,
43
+ description=description,
44
+ )
45
+ if train_ratio + val_ratio + test_ratio != 1.0:
46
+ raise ValueError(
47
+ "train_ratio + val_ratio + test_ratio should be 1.0, "
48
+ f"but got {train_ratio} + {val_ratio} + {test_ratio} = {train_ratio + val_ratio + test_ratio}"
49
+ )
50
+
51
+ self.train_ratio = train_ratio
52
+ self.val_ratio = val_ratio
53
+ self.test_ratio = test_ratio
54
+
55
+ self.is_han_to_zen = is_han_to_zen
56
+ self.max_instance_num = max_instance_num
57
+ self.max_char_length = max_char_length
58
+ self.is_pos_neg = is_pos_neg
59
+ self.output_testset = output_testset
60
+
61
+ self.filter_review_id_list_valid = filter_review_id_list_valid
62
+ self.label_conv_review_id_list_valid = label_conv_review_id_list_valid
63
+
64
+
65
+ def get_label(rating: int, is_pos_neg: bool = False) -> Optional[str]:
66
+ if rating >= 4:
67
+ return "positive"
68
+ elif rating <= 2:
69
+ return "negative"
70
+ else:
71
+ if is_pos_neg:
72
+ return None
73
+ else:
74
+ return "neutral"
75
+
76
+
77
+ def is_filtered_by_ascii_rate(text: str, threshold: float = 0.9) -> bool:
78
+ ascii_letters = set(string.printable)
79
+ rate = sum(c in ascii_letters for c in text) / len(text)
80
+ return rate >= threshold
81
+
82
+
83
+ def shuffle_dataframe(df: pd.DataFrame) -> pd.DataFrame:
84
+ instances = df.to_dict(orient="records")
85
+ random.seed(1)
86
+ random.shuffle(instances)
87
+ return pd.DataFrame(instances)
88
+
89
+
90
+ def get_filter_review_id_list(
91
+ filter_review_id_list_paths: Dict[str, str],
92
+ ) -> Dict[str, List[str]]:
93
+ filter_review_id_list_valid = filter_review_id_list_paths.get("valid")
94
+ filter_review_id_list_test = filter_review_id_list_paths.get("test")
95
+
96
+ filter_review_id_list = {}
97
+
98
+ if filter_review_id_list_valid is not None:
99
+ with open(filter_review_id_list_valid, "r") as rf:
100
+ filter_review_id_list["valid"] = [line.rstrip() for line in rf]
101
+
102
+ if filter_review_id_list_test is not None:
103
+ with open(filter_review_id_list_test, "r") as rf:
104
+ filter_review_id_list["test"] = [line.rstrip() for line in rf]
105
+
106
+ return filter_review_id_list
107
+
108
+
109
+ def get_label_conv_review_id_list(
110
+ label_conv_review_id_list_paths: Dict[str, str],
111
+ ) -> Dict[str, Dict[str, str]]:
112
+ import csv
113
+
114
+ label_conv_review_id_list_valid = label_conv_review_id_list_paths.get("valid")
115
+ label_conv_review_id_list_test = label_conv_review_id_list_paths.get("test")
116
+
117
+ label_conv_review_id_list: Dict[str, Dict[str, str]] = {}
118
+
119
+ if label_conv_review_id_list_valid is not None:
120
+ with open(label_conv_review_id_list_valid, "r") as rf:
121
+ label_conv_review_id_list["valid"] = {row[0]: row[1] for row in csv.reader(rf)}
122
+
123
+ if label_conv_review_id_list_test is not None:
124
+ with open(label_conv_review_id_list_test, "r") as rf:
125
+ label_conv_review_id_list["test"] = {row[0]: row[1] for row in csv.reader(rf)}
126
+
127
+ return label_conv_review_id_list
128
+
129
+
130
+ def output_data(
131
+ df: pd.DataFrame,
132
+ train_ratio: float,
133
+ val_ratio: float,
134
+ test_ratio: float,
135
+ output_testset: bool,
136
+ filter_review_id_list_paths: Dict[str, str],
137
+ label_conv_review_id_list_paths: Dict[str, str],
138
+ ) -> Dict[str, pd.DataFrame]:
139
+ instance_num = len(df)
140
+ split_dfs: Dict[str, pd.DataFrame] = {}
141
+ length1 = int(instance_num * train_ratio)
142
+ split_dfs["train"] = df.iloc[:length1]
143
+
144
+ length2 = int(instance_num * (train_ratio + val_ratio))
145
+ split_dfs["valid"] = df.iloc[length1:length2]
146
+ split_dfs["test"] = df.iloc[length2:]
147
+
148
+ filter_review_id_list = get_filter_review_id_list(
149
+ filter_review_id_list_paths=filter_review_id_list_paths,
150
+ )
151
+ label_conv_review_id_list = get_label_conv_review_id_list(
152
+ label_conv_review_id_list_paths=label_conv_review_id_list_paths,
153
+ )
154
+
155
+ for eval_type in ("valid", "test"):
156
+ if filter_review_id_list.get(eval_type):
157
+ df = split_dfs[eval_type]
158
+ df = df[~df["review_id"].isin(filter_review_id_list[eval_type])]
159
+ split_dfs[eval_type] = df
160
+
161
+ for eval_type in ("valid", "test"):
162
+ if label_conv_review_id_list.get(eval_type):
163
+ df = split_dfs[eval_type]
164
+ df = df.assign(converted_label=df["review_id"].map(label_conv_review_id_list["valid"]))
165
+ df = df.assign(
166
+ label=df[["label", "converted_label"]].apply(
167
+ lambda xs: xs["label"] if pd.isnull(xs["converted_label"]) else xs["converted_label"],
168
+ axis=1,
169
+ )
170
+ )
171
+ df = df.drop(columns=["converted_label"])
172
+ split_dfs[eval_type] = df
173
+
174
+ return {
175
+ "train": split_dfs["train"],
176
+ "valid": split_dfs["valid"],
177
+ }
178
+
179
+
180
+ def preprocess_marc_ja(
181
+ config: MarcJaConfig,
182
+ data_file_path: str,
183
+ filter_review_id_list_paths: Dict[str, str],
184
+ label_conv_review_id_list_paths: Dict[str, str],
185
+ ) -> Dict[str, pd.DataFrame]:
186
+ try:
187
+ import mojimoji
188
+
189
+ def han_to_zen(text: str) -> str:
190
+ return mojimoji.han_to_zen(text)
191
+
192
+ except ImportError:
193
+ warnings.warn(
194
+ "can't import `mojimoji`, failing back to method that do nothing. "
195
+ "We recommend running `pip install mojimoji` to reproduce the original preprocessing.",
196
+ UserWarning,
197
+ )
198
+
199
+ def han_to_zen(text: str) -> str:
200
+ return text
201
+
202
+ try:
203
+ from bs4 import BeautifulSoup
204
+
205
+ def cleanup_text(text: str) -> str:
206
+ return BeautifulSoup(text, "html.parser").get_text()
207
+
208
+ except ImportError:
209
+ warnings.warn(
210
+ "can't import `beautifulsoup4`, failing back to method that do nothing."
211
+ "We recommend running `pip install beautifulsoup4` to reproduce the original preprocessing.",
212
+ UserWarning,
213
+ )
214
+
215
+ def cleanup_text(text: str) -> str:
216
+ return text
217
+
218
+ from tqdm import tqdm
219
+
220
+ df = pd.read_csv(data_file_path, delimiter="\t")
221
+ df = df[["review_body", "star_rating", "review_id"]]
222
+
223
+ # rename columns
224
+ df = df.rename(columns={"review_body": "text", "star_rating": "rating"})
225
+
226
+ # convert the rating to label
227
+ tqdm.pandas(dynamic_ncols=True, desc="Convert the rating to the label")
228
+ df = df.assign(label=df["rating"].progress_apply(lambda rating: get_label(rating, config.is_pos_neg)))
229
+
230
+ # remove rows where the label is None
231
+ df = df[~df["label"].isnull()]
232
+
233
+ # remove html tags from the text
234
+ tqdm.pandas(dynamic_ncols=True, desc="Remove html tags from the text")
235
+ df = df.assign(text=df["text"].progress_apply(cleanup_text))
236
+
237
+ # filter by ascii rate
238
+ tqdm.pandas(dynamic_ncols=True, desc="Filter by ascii rate")
239
+ df = df[~df["text"].progress_apply(is_filtered_by_ascii_rate)]
240
+
241
+ if config.max_char_length is not None:
242
+ df = df[df["text"].str.len() <= config.max_char_length]
243
+
244
+ if config.is_han_to_zen:
245
+ df = df.assign(text=df["text"].apply(han_to_zen))
246
+
247
+ df = df[["text", "label", "review_id"]]
248
+ df = df.rename(columns={"text": "sentence"})
249
+
250
+ # shuffle dataset
251
+ df = shuffle_dataframe(df)
252
+
253
+ split_dfs = output_data(
254
+ df=df,
255
+ train_ratio=config.train_ratio,
256
+ val_ratio=config.val_ratio,
257
+ test_ratio=config.test_ratio,
258
+ output_testset=config.output_testset,
259
+ filter_review_id_list_paths=filter_review_id_list_paths,
260
+ label_conv_review_id_list_paths=label_conv_review_id_list_paths,
261
+ )
262
+ return split_dfs
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ bs4
2
+ mojimoji
3
+ pandas