Datasets:

ArXiv:
License:
holylovenia commited on
Commit
5516a40
1 Parent(s): 2f32da8

Upload clir_matrix.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. clir_matrix.py +234 -0
clir_matrix.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Datasets Authors and the current dataset script contributor.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from itertools import permutations
17
+ from pathlib import Path
18
+ from typing import Dict, List, Tuple
19
+
20
+ import datasets
21
+ import pandas as pd
22
+
23
+ from seacrowd.utils.configs import SEACrowdConfig
24
+ from seacrowd.utils.constants import Licenses
25
+
26
+ _CITATION = """\
27
+ @inproceedings{sun-duh-2020-clirmatrix,
28
+ title = "{CLIRM}atrix: A massively large collection of bilingual and multilingual datasets for Cross-Lingual Information Retrieval",
29
+ author = "Sun, Shuo and
30
+ Duh, Kevin",
31
+ editor = "Webber, Bonnie and
32
+ Cohn, Trevor and
33
+ He, Yulan and
34
+ Liu, Yang",
35
+ booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP)",
36
+ month = nov,
37
+ year = "2020",
38
+ address = "Online",
39
+ publisher = "Association for Computational Linguistics",
40
+ url = "https://aclanthology.org/2020.emnlp-main.340",
41
+ doi = "10.18653/v1/2020.emnlp-main.340",
42
+ pages = "4160--4170",
43
+ }
44
+ """
45
+
46
+ _DATASETNAME = "clir_matrix"
47
+
48
+ _DESCRIPTION = """\
49
+ A massively large collection of bilingual and multilingual datasets for Cross-Lingual Information Retrieval extracted automatically from Wikipedia.
50
+ CLIRMatrix (Cross-Lingual Information Retrieval Matrix) comprises:
51
+ (1) BI-139, a bilingual dataset of queries in one language matched with relevant documents in another language for 139x138=19,182 language pairs, and
52
+ (2) MULTI-8, a multilingual dataset of queries and documents jointly aligned in 8 different languages.
53
+
54
+ Only (1) BI-139 has languages covered in SEACROWD.
55
+ """
56
+
57
+ _HOMEPAGE = "https://github.com/ssun32/CLIRMatrix"
58
+
59
+ _LANGUAGES = ["tgl", "ilo", "min", "jav", "sun", "ceb", "vie", "tha"] # We follow ISO639-3 language code (https://iso639-3.sil.org/code_tables/639/data)
60
+
61
+ _LICENSE = Licenses.UNKNOWN.value
62
+
63
+ _LOCAL = False
64
+
65
+ _CLIR_LANG = {
66
+ "tgl": "tl",
67
+ "jav": "jv",
68
+ "sun": "su",
69
+ "vie": "vi",
70
+ "tha": "th",
71
+ "ilo": "ilo",
72
+ "min": "min",
73
+ "ceb": "ceb",
74
+ }
75
+ _URLS = {
76
+ ds: {
77
+ split: {(lque, ldoc): (f"https://www.cs.jhu.edu/~shuosun/clirmatrix/data/BI-139/{ds}/{_CLIR_LANG[lque]}/" f"{_CLIR_LANG[lque]}.{_CLIR_LANG[ldoc]}.{split}{'.base' if ds == 'base' else ''}.jl.gz") for lque, ldoc in permutations(_LANGUAGES, 2)}
78
+ for split in ["train", "dev", "test1", "test2"]
79
+ }
80
+ for ds in ["base", "full"]
81
+ } | {"docs": {ldoc: f"https://www.cs.jhu.edu/~shuosun/clirmatrix/data/DOCS/{_CLIR_LANG[ldoc]}.tsv.gz" for ldoc in _LANGUAGES}}
82
+
83
+ _SUPPORTED_TASKS = []
84
+
85
+ _SOURCE_VERSION = "1.0.0"
86
+
87
+ _SEACROWD_VERSION = "2024.06.20"
88
+
89
+
90
+ class CLIRMatrixDataset(datasets.GeneratorBasedBuilder):
91
+ """Cross-Lingual Information Retrieval dataset of 49 million unique queries and 34 billion triplets."""
92
+
93
+ SOURCE_VERSION = datasets.Version(_SOURCE_VERSION)
94
+ SEACROWD_VERSION = datasets.Version(_SEACROWD_VERSION)
95
+
96
+ BUILDER_CONFIGS = [
97
+ *[
98
+ SEACrowdConfig(
99
+ name=f"{_DATASETNAME}{subset}_source", # refers to the `base` split in the original paper.
100
+ version=datasets.Version(_SOURCE_VERSION),
101
+ description=f"{_DATASETNAME} source schema",
102
+ schema="source",
103
+ subset_id=f"{_DATASETNAME}{subset}",
104
+ )
105
+ for subset in [f"{'_' if lque else ''}{lque}{'_' if ldoc else ''}{ldoc}" for lque, ldoc in [("", ""), *permutations(_LANGUAGES, 2)]]
106
+ ],
107
+ *[
108
+ SEACrowdConfig(
109
+ name=f"{_DATASETNAME}{subset}_full_source", # refers to the `full` split in the original paper.
110
+ version=datasets.Version(_SOURCE_VERSION),
111
+ description=f"{_DATASETNAME} full subset source schema",
112
+ schema="source",
113
+ subset_id=f"{_DATASETNAME}{subset}_full",
114
+ )
115
+ for subset in [f"{'_' if lque else ''}{lque}{'_' if ldoc else ''}{ldoc}" for lque, ldoc in [("", ""), *permutations(_LANGUAGES, 2)]]
116
+ ],
117
+ # source-only dataloader
118
+ # SEACrowdConfig(
119
+ # name=f"{_DATASETNAME}_seacrowd_pairs",
120
+ # version=SEACROWD_VERSION,
121
+ # description=f"{_DATASETNAME} SEACrowd schema",
122
+ # schema="seacrowd_pairs",
123
+ # subset_id=f"{_DATASETNAME}",
124
+ # ),
125
+ # SEACrowdConfig(
126
+ # name=f"{_DATASETNAME}_full_seacrowd_pairs",
127
+ # version=SEACROWD_VERSION,
128
+ # description=f"{_DATASETNAME} full subset SEACrowd schema",
129
+ # schema="seacrowd_pairs",
130
+ # subset_id=f"{_DATASETNAME}_full",
131
+ # ),
132
+ ]
133
+
134
+ DEFAULT_CONFIG_NAME = f"{_DATASETNAME}_source"
135
+
136
+ def _info(self) -> datasets.DatasetInfo:
137
+
138
+ if self.config.schema == "source":
139
+ features = datasets.Features(
140
+ {
141
+ "src_id": datasets.Value("string"),
142
+ "src_query": datasets.Value("string"),
143
+ "tgt_results": [
144
+ {
145
+ "doc_id": datasets.Value("string"),
146
+ "score": datasets.Value("int32"),
147
+ "doc_text": datasets.Value("string"),
148
+ }
149
+ ],
150
+ "lang_query": datasets.Value("string"),
151
+ "lang_doc": datasets.Value("string"),
152
+ }
153
+ )
154
+
155
+ # elif self.config.schema == "seacrowd_[seacrowdschema_name]":
156
+ # source_only, skipping this.
157
+ else:
158
+ raise NotImplementedError()
159
+
160
+ return datasets.DatasetInfo(
161
+ description=_DESCRIPTION,
162
+ features=features,
163
+ homepage=_HOMEPAGE,
164
+ license=_LICENSE,
165
+ citation=_CITATION,
166
+ )
167
+
168
+ def _split_generators(self, dl_manager: datasets.DownloadManager) -> List[datasets.SplitGenerator]:
169
+ """Returns SplitGenerators."""
170
+
171
+ subset_id = self.config.subset_id.split("_")
172
+
173
+ urls = _URLS["full" if subset_id[-1] == "full" else "base"]
174
+ urls_doc = _URLS["docs"]
175
+
176
+ # filter subset direction
177
+ if len(subset_id) > 3:
178
+ lque, ldoc = subset_id[2:4]
179
+ urls = {split: {(lque, ldoc): v[(lque, ldoc)]} for split, v in urls.items()}
180
+ urls_doc = {ldoc: urls_doc[ldoc]}
181
+
182
+ data_paths = dl_manager.download_and_extract(urls)
183
+ doc_paths = dl_manager.download_and_extract(urls_doc)
184
+
185
+ return [
186
+ datasets.SplitGenerator(
187
+ name=datasets.Split.TRAIN,
188
+ gen_kwargs={"filepath": data_paths["train"], "doc_paths": doc_paths},
189
+ ),
190
+ datasets.SplitGenerator(
191
+ name=datasets.Split.TEST,
192
+ gen_kwargs={"filepath": data_paths["test1"], "doc_paths": doc_paths},
193
+ ),
194
+ datasets.SplitGenerator(
195
+ name="test2", # just supplementary test sets for users to use in whatever way they want # just supplementary test sets for users to use in whatever way they want
196
+ gen_kwargs={"filepath": data_paths["test2"], "doc_paths": doc_paths},
197
+ ),
198
+ datasets.SplitGenerator(
199
+ name=datasets.Split.VALIDATION,
200
+ gen_kwargs={"filepath": data_paths["dev"], "doc_paths": doc_paths},
201
+ ),
202
+ ]
203
+
204
+ def _generate_examples(self, filepath: Dict[Tuple, Path], doc_paths: Dict[str, Path]) -> Tuple[int, Dict]:
205
+ """Yields examples as (key, example) tuples."""
206
+
207
+ docs_id2txt = {}
208
+ for ldoc, p in doc_paths.items():
209
+ docs_id2txt[ldoc] = pd.read_csv(p, sep="\t", dtype=str, header=None).set_index(0).iloc[:, 0]
210
+
211
+ if self.config.schema == "source":
212
+ for (lque, ldoc), fp in filepath.items():
213
+ df = pd.read_json(fp, orient="records", lines=True)
214
+ not_found = set()
215
+ for idx, row in df.iterrows():
216
+ ret = row.to_dict()
217
+ for doc_id, score in ret["tgt_results"]:
218
+ if doc_id not in docs_id2txt[ldoc]:
219
+ not_found.add(doc_id)
220
+ ret["lang_query"] = lque
221
+ ret["lang_doc"] = ldoc
222
+ ret["tgt_results"] = [
223
+ {
224
+ "doc_id": doc_id,
225
+ "score": score,
226
+ "doc_text": docs_id2txt[ldoc].get(doc_id, ""),
227
+ # many doc_id discrepancy, i.e. not found in the tab-separated document files, in particular for Sundanese (sun);
228
+ }
229
+ for doc_id, score in ret["tgt_results"]
230
+ ]
231
+ yield f"{lque}_{ldoc}_{idx}", ret
232
+
233
+ # source-only dataloader, skipping seacrowd schema.
234
+ # elif self.config.schema == "seacrowd_[seacrowd_schema_name]":