Datasets:

ArXiv:
License:
holylovenia commited on
Commit
918eb74
1 Parent(s): b8ad04d

Upload miracl.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. miracl.py +291 -0
miracl.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """
17
+ MIRACL is a multilingual dataset for ad hoc retrieval across 18 languages that
18
+ collectively encompass over three billion native speakers around the world.
19
+ This resource is designed to support monolingual retrieval tasks, where the
20
+ queries and the corpora are in the same language. In total, we have gathered
21
+ over 726k high-quality relevance judgments for 78k queries over Wikipedia in
22
+ these languages, where all annotations have been performed by native speakers.
23
+ MIRACL covers Indonesian and Thai languages
24
+ """
25
+
26
+ from typing import Dict, List, Tuple
27
+
28
+ import datasets
29
+
30
+ from seacrowd.utils import schemas
31
+ from seacrowd.utils.configs import SEACrowdConfig
32
+ from seacrowd.utils.constants import Tasks, Licenses
33
+
34
+ from collections import defaultdict
35
+
36
+ _CITATION = """\
37
+ @article{10.1162/tacl_a_00595,
38
+ title = {{MIRACL: A Multilingual Retrieval Dataset Covering 18 Diverse Languages}},
39
+ author = {Zhang, Xinyu and Thakur, Nandan and Ogundepo, Odunayo and Kamalloo, Ehsan and Alfonso-Hermelo, David and Li, Xiaoguang and Liu, Qun and Rezagholizadeh, Mehdi and Lin, Jimmy},
40
+ year = 2023,
41
+ month = {09},
42
+ journal = {Transactions of the Association for Computational Linguistics},
43
+ volume = 11,
44
+ pages = {1114--1131},
45
+ doi = {10.1162/tacl\_a\_00595},
46
+ issn = {2307-387X},
47
+ url = {https://doi.org/10.1162/tacl\%5Fa\%5F00595},
48
+ abstract = {{MIRACL is a multilingual dataset for ad hoc retrieval across 18 languages that collectively encompass over three billion native speakers around the world. This resource is designed to support monolingual retrieval tasks, where the queries and the corpora are in the same language. In total, we have gathered over 726k high-quality relevance judgments for 78k queries over Wikipedia in these languages, where all annotations have been performed by native speakers hired by our team. MIRACL covers languages that are both typologically close as well as distant from 10 language families and 13 sub-families, associated with varying amounts of publicly available resources. Extensive automatic heuristic verification and manual assessments were performed during the annotation process to control data quality. In total, MIRACL represents an investment of around five person-years of human annotator effort. Our goal is to spur research on improving retrieval across a continuum of languages, thus enhancing information access capabilities for diverse populations around the world, particularly those that have traditionally been underserved. MIRACL is available at http://miracl.ai/.}},
49
+ eprint = {https://direct.mit.edu/tacl/article-pdf/doi/10.1162/tacl\_a\_00595/2157340/tacl\_a\_00595.pdf}
50
+ }
51
+ """
52
+
53
+
54
+ _DATASETNAME = "miracl"
55
+
56
+ _DESCRIPTION = """\
57
+ MIRACL is a multilingual dataset for ad hoc retrieval across 18 languages that collectively encompass over three billion native speakers around the world. This resource is designed to support monolingual retrieval tasks, where the queries and the corpora are in the same language. In total, we have gathered over 726k high-quality relevance judgments for 78k queries over Wikipedia in these languages, where all annotations have been performed by native speakers. MIRACL covers Indonesian and Thai languages. Before using this dataloader, please accept the acknowledgement at https://huggingface.co/datasets/miracl/miracl and use huggingface-cli login for authentication.
58
+ """
59
+
60
+ _HOMEPAGE = "https://project-miracl.github.io/"
61
+
62
+ _LANGUAGES = ["ind", "tha"]
63
+
64
+ _LICENSE = Licenses.APACHE_2_0.value
65
+
66
+ _LANGUAGE_MAP = {
67
+ "id": "Thai",
68
+ "th": "Indonesian"
69
+ }
70
+
71
+ _URLS = {_DATASETNAME: {lang: {} for lang in _LANGUAGE_MAP}}
72
+
73
+ for lang in _LANGUAGE_MAP:
74
+ _URLS[_DATASETNAME][lang]['train'] = [
75
+ f'https://huggingface.co/datasets/miracl/miracl/resolve/main/miracl-v1.0-{lang}/topics/topics.miracl-v1.0-{lang}-train.tsv',
76
+ f'https://huggingface.co/datasets/miracl/miracl/resolve/main/miracl-v1.0-{lang}/qrels/qrels.miracl-v1.0-{lang}-train.tsv',
77
+ ]
78
+
79
+ _URLS[_DATASETNAME][lang]['dev'] = [
80
+ f'https://huggingface.co/datasets/miracl/miracl/resolve/main/miracl-v1.0-{lang}/topics/topics.miracl-v1.0-{lang}-dev.tsv',
81
+ f'https://huggingface.co/datasets/miracl/miracl/resolve/main/miracl-v1.0-{lang}/qrels/qrels.miracl-v1.0-{lang}-dev.tsv',
82
+ ]
83
+
84
+ _URLS[_DATASETNAME][lang]['testB'] =[
85
+ f'https://huggingface.co/datasets/miracl/miracl/resolve/main/miracl-v1.0-{lang}/topics/topics.miracl-v1.0-{lang}-test-b.tsv',
86
+ ]
87
+
88
+ _URLS[_DATASETNAME][lang]['testA'] = [
89
+ f'https://huggingface.co/datasets/miracl/miracl/resolve/main/miracl-v1.0-{lang}/topics/topics.miracl-v1.0-{lang}-test-a.tsv',
90
+ ]
91
+
92
+
93
+ _SUPPORTED_TASKS = [Tasks.TEXT_RETRIEVAL] # example: [Tasks.TRANSLATION, Tasks.NAMED_ENTITY_RECOGNITION, Tasks.RELATION_EXTRACTION]
94
+
95
+ _SOURCE_VERSION = "1.0.0"
96
+
97
+ _SEACROWD_VERSION = "2024.06.20"
98
+
99
+ _LOCAL = False
100
+
101
+
102
+ def load_topic(fn):
103
+
104
+ qid2topic = {}
105
+ with open(fn, encoding="utf-8") as f:
106
+ for line in f:
107
+ qid, topic = line.strip().split('\t')
108
+ qid2topic[qid] = topic
109
+ return qid2topic
110
+
111
+
112
+ def load_qrels(fn):
113
+ if fn is None:
114
+ return None
115
+
116
+ qrels = defaultdict(dict)
117
+ with open(fn, encoding="utf-8") as f:
118
+ for line in f:
119
+ qid, _, docid, rel = line.strip().split('\t')
120
+ qrels[qid][docid] = int(rel)
121
+ return qrels
122
+
123
+ def seacrowd_config_constructor(lang, schema, version):
124
+ if lang not in _LANGUAGE_MAP:
125
+ raise ValueError(f"Invalid lang {lang}")
126
+
127
+ if schema != "source" and schema != "seacrowd_pairs":
128
+ raise ValueError(f"Invalid schema: {schema}")
129
+
130
+ return SEACrowdConfig(
131
+ name="miracl_{lang}_{schema}".format(lang=lang, schema=schema),
132
+ version=datasets.Version(version),
133
+ description="MIRACL {schema} schema for {lang} language".format(lang=_LANGUAGE_MAP[lang], schema=schema),
134
+ schema=schema,
135
+ subset_id="miracl_{lang}".format(lang=lang),
136
+ )
137
+
138
+ class Miracl(datasets.GeneratorBasedBuilder):
139
+ """MIRACL is a multilingual retrieval dataset that focuses on search across 18 different languages."""
140
+
141
+ SOURCE_VERSION = datasets.Version(_SOURCE_VERSION)
142
+ SEACROWD_VERSION = datasets.Version(_SEACROWD_VERSION)
143
+
144
+ BUILDER_CONFIGS = [seacrowd_config_constructor(lang, "source", _SOURCE_VERSION) for lang in _LANGUAGE_MAP] + [seacrowd_config_constructor(lang, "seacrowd_pairs", _SEACROWD_VERSION) for lang in _LANGUAGE_MAP]
145
+
146
+ DEFAULT_CONFIG_NAME = None
147
+
148
+ def _info(self) -> datasets.DatasetInfo:
149
+ if self.config.schema == "source":
150
+ features = datasets.Features({
151
+ 'query_id': datasets.Value('string'),
152
+ 'query': datasets.Value('string'),
153
+
154
+ 'positive_passages': [{
155
+ 'docid': datasets.Value('string'),
156
+ 'text': datasets.Value('string'), 'title': datasets.Value('string')
157
+ }],
158
+ 'negative_passages': [{
159
+ 'docid': datasets.Value('string'),
160
+ 'text': datasets.Value('string'), 'title': datasets.Value('string'),
161
+ }],
162
+ })
163
+ elif self.config.schema == "seacrowd_pairs":
164
+ features = schemas.pairs_features(["pos", "neg", "none"])
165
+
166
+ return datasets.DatasetInfo(
167
+ description=_DESCRIPTION,
168
+ features=features,
169
+ homepage=_HOMEPAGE,
170
+ license=_LICENSE,
171
+ citation=_CITATION,
172
+ )
173
+
174
+ def _split_generators(self, dl_manager: datasets.DownloadManager) -> List[datasets.SplitGenerator]:
175
+ """Returns SplitGenerators."""
176
+ urls = _URLS[_DATASETNAME]
177
+ lang = self.config.name.split("_")[1]
178
+ downloaded_files = dl_manager.download_and_extract(urls[lang])
179
+
180
+ return [
181
+ datasets.SplitGenerator(
182
+ name="train",
183
+ gen_kwargs={
184
+ "filepaths": downloaded_files["train"],
185
+ "split": "train",
186
+ },
187
+ ),
188
+ datasets.SplitGenerator(
189
+ name="dev",
190
+ gen_kwargs={
191
+ "filepaths": downloaded_files["dev"],
192
+ "split": "dev",
193
+ },
194
+ ),
195
+ datasets.SplitGenerator(
196
+ name="testA",
197
+ gen_kwargs={
198
+ "filepaths": downloaded_files["testA"],
199
+ "split": "testA",
200
+ },
201
+ ),
202
+ datasets.SplitGenerator(
203
+ name="testB",
204
+ gen_kwargs={
205
+ "filepaths": downloaded_files["testB"],
206
+ "split": "testB",
207
+ },
208
+ )
209
+ ]
210
+
211
+
212
+ def _generate_examples(self, filepaths: List[str], split: str) -> Tuple[int, Dict]:
213
+ """Yields examples as (key, example) tuples."""
214
+
215
+ lang = self.config.name.split("_")[1]
216
+
217
+ # the following code except for seacrowd_pairs is taken from the original MIRACL
218
+ # dataloader implementation
219
+ # https://huggingface.co/datasets/miracl/miracl
220
+ miracl_corpus = datasets.load_dataset('miracl/miracl-corpus', lang)['train']
221
+ docid2doc = {doc['docid']: (doc['title'], doc['text']) for doc in miracl_corpus}
222
+ topic_fn, qrel_fn = (filepaths) if len(filepaths) == 2 else (filepaths[0], None)
223
+ qid2topic = load_topic(topic_fn)
224
+ qrels = load_qrels(qrel_fn)
225
+
226
+ if self.config.schema == "source":
227
+ for qid in qid2topic:
228
+ data = {}
229
+ data['query_id'] = qid
230
+ data['query'] = qid2topic[qid]
231
+
232
+ pos_docids = [docid for docid, rel in qrels[qid].items() if rel == 1] if qrels is not None else []
233
+ neg_docids = [docid for docid, rel in qrels[qid].items() if rel == 0] if qrels is not None else []
234
+
235
+ data['positive_passages'] = [{
236
+ 'docid': docid,
237
+ **dict(zip(['title', 'text'], docid2doc[docid]))
238
+ } for docid in pos_docids if docid in docid2doc]
239
+
240
+ data['negative_passages'] = [{
241
+ 'docid': docid,
242
+ **dict(zip(['title', 'text'], docid2doc[docid]))
243
+ } for docid in neg_docids if docid in docid2doc]
244
+
245
+ yield qid, data
246
+
247
+ elif self.config.schema == "seacrowd_pairs":
248
+ id = -1
249
+ for qid in qid2topic:
250
+ pos_docids = [docid for docid, rel in qrels[qid].items() if rel == 1] if qrels is not None else []
251
+ neg_docids = [docid for docid, rel in qrels[qid].items() if rel == 0] if qrels is not None else []
252
+
253
+ positive_passages = [{
254
+ 'docid': docid,
255
+ **dict(zip(['title', 'text'], docid2doc[docid]))
256
+ } for docid in pos_docids if docid in docid2doc]
257
+
258
+ negative_passages = [{
259
+ 'docid': docid,
260
+ **dict(zip(['title', 'text'], docid2doc[docid]))
261
+ } for docid in neg_docids if docid in docid2doc]
262
+
263
+ # assemble data
264
+ data = {}
265
+ data['text_1'] = qid2topic[qid] # query
266
+
267
+ if split in ["testA", "testB"]: # test sets only contains id and query
268
+ id += 1
269
+ data['id'] = id
270
+ data['text_2'] = ""
271
+ data['label'] = "none"
272
+
273
+ yield id, data
274
+ else:
275
+ # generate positive pairs
276
+ for positive_doc in positive_passages:
277
+ id += 1
278
+ data['id'] = id
279
+ # flatten dict contents to String by concatenating title and text separated by double newline
280
+ data['text_2'] = positive_doc['title'] + "\n\n" + positive_doc["text"]
281
+ data['label'] = "pos"
282
+ yield id, data
283
+
284
+ # generate negative pairs
285
+ for negative_doc in negative_passages:
286
+ id += 1
287
+ data['id'] = id
288
+ # flatten dict contents to String by concatenating title and text separated by double newline
289
+ data['text_2'] = negative_doc['title'] + "\n\n" + negative_doc["text"]
290
+ data['label'] = "neg"
291
+ yield id, data