File size: 9,329 Bytes
ecd4ca9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63fa1a8
ecd4ca9
63fa1a8
ecd4ca9
 
63fa1a8
ecd4ca9
 
63fa1a8
ecd4ca9
63fa1a8
ecd4ca9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cde6943
53226cf
 
ecd4ca9
 
 
 
53226cf
ecd4ca9
 
 
 
cde6943
53226cf
 
ecd4ca9
 
 
 
53226cf
ecd4ca9
 
 
 
63fa1a8
53226cf
 
ecd4ca9
 
 
 
53226cf
ecd4ca9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
# coding=utf-8
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an 'AS IS' BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Lint as: python3

import json
import datasets
from collections import defaultdict
from dataclasses import dataclass
from typing import Dict

_CITATION = '''@article{10.1162/tacl_a_00595,
    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},
    title = "{MIRACL: A Multilingual Retrieval Dataset Covering 18 Diverse Languages}",
    journal = {Transactions of the Association for Computational Linguistics},
    volume = {11},
    pages = {1114-1131},
    year = {2023},
    month = {09},
    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/.}",
    issn = {2307-387X},
    doi = {10.1162/tacl_a_00595},
    url = {https://doi.org/10.1162/tacl\_a\_00595},
    eprint = {https://direct.mit.edu/tacl/article-pdf/doi/10.1162/tacl\_a\_00595/2157340/tacl\_a\_00595.pdf},
}'''

surprise_languages = ['de', 'yo']
new_languages = ['es', 'fa', 'fr', 'hi', 'zh'] + surprise_languages
languages = ['ar', 'bn', 'en', 'es', 'fa', 'fi', 'fr', 'hi', 'id', 'ja', 'ko', 'ru', 'sw', 'te', 'th', 'zh'] + surprise_languages

languages2filesize = { 
    'ar': 5,
    'bn': 1,
    'en': 66,
    'es': 21,
    'fa': 5,
    'fi': 4,
    'fr': 30,
    'hi': 2,
    'id': 3,
    'ja': 14,
    'ko': 3,
    'ru': 20,
    'sw': 1,
    'te': 2,
    'th': 2,
    'zh': 10,
    'de': 32,
    'yo': 1,
}

_DESCRIPTION = 'dataset load script for MIRACL'

_DATASET_URLS = {
    language: {
        'dev': [
            f'https://huggingface.co/datasets/miracl/miracl/resolve/main/miracl-v1.0-{language}/qrels/qrels.miracl-v1.0-{language}-dev.tsv',
        ],
        'corpus': [
            f'https://huggingface.co/datasets/miracl/miracl-corpus/resolve/main/miracl-corpus-v1.0-{language}/docs-{i}.jsonl.gz' for i in range(n)
        ],
        'queries': [
            f'https://huggingface.co/datasets/miracl/miracl/resolve/main/miracl-v1.0-{language}/topics/topics.miracl-v1.0-{language}-dev.tsv',
        ],
    } for language, n in languages2filesize.items()
}

def load_topic(fn: str) -> Dict[str, str]:
    """
    Load topics from a file.
    Args:
        fn: file path
    Returns:
        A dictionary from query id to query text.
    """
    qid2topic = {}
    with open(fn, encoding="utf-8") as f:
        for line in f:
            qid, topic = line.strip().split('\t')
            qid2topic[qid] = topic
    return qid2topic


def load_qrels(fn: str) -> Dict[str, Dict[str, int]]:
    """
    Load qrels from a file.
    Args:
        fn: file path
    Returns:
        A dictionary from query id to a dictionary from doc id to relevance score.
    """
    if fn is None:
        return None

    qrels = defaultdict(dict)
    with open(fn, encoding="utf-8") as f:
        for line in f:
            qid, _, docid, rel = line.strip().split('\t')
            qrels[qid][docid] = int(rel)
    return qrels


class MMTEBMIRACL(datasets.GeneratorBasedBuilder):
    BUILDER_CONFIGS = [datasets.BuilderConfig(
            version=datasets.Version('1.0.0'),
            name=lang, description=f'MIRACL qrels in language {lang}.'
        ) for lang in languages
    ] + [
        datasets.BuilderConfig(
            version=datasets.Version('1.0.0'),
            name=f'corpus-{lang}', description=f'corpus of MIRACL dataset in language {lang}.'
        ) for lang in languages
    ] + [ 
        datasets.BuilderConfig(
            version=datasets.Version('1.0.0'),
            name=f'queries-{lang}', description=f'queries of MIRACL dataset in language {lang}.'
        ) for lang in languages
    ]

    def _info(self):
        name = self.config.name
        
        if name.startswith('corpus-'):
            features = datasets.Features({
                'docid': datasets.Value('string'),
                'title': datasets.Value('string'),
                'text': datasets.Value('string'),
            })
        elif name.startswith("queries-"):
            features = datasets.Features({
                'query_id': datasets.Value('string'),
                'query': datasets.Value('string'),
            })
        else:
            features = datasets.Features({
                'query_id': datasets.Value('string'),
                'docid': datasets.Value('string'),
                'score': datasets.Value('int32'),
            })

        return datasets.DatasetInfo(
            # This is the description that will appear on the datasets page.
            description=_DESCRIPTION,
            # This defines the different columns of the dataset and their types
            features=features,  # Here we define them above because they are different between the two configurations
            supervised_keys=None,
            # Homepage of the dataset for documentation
            homepage='https://project-miracl.github.io',
            # License for the dataset if available
            license=None,
            # Citation for the dataset
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager):
        name = self.config.name

        if name.startswith('corpus-'):
            language = name.replace('corpus-', '')
            downloaded_files = dl_manager.download_and_extract(
                _DATASET_URLS[language]['corpus'])
            splits = [
                datasets.SplitGenerator(
                    name='corpus',
                    gen_kwargs={
                        'filepaths': downloaded_files,
                    },
                ),
            ]
        elif name.startswith('queries-'):
            language = name.replace('queries-', '')
            downloaded_files = dl_manager.download_and_extract(
                _DATASET_URLS[language]['queries'])
            splits = [
                datasets.SplitGenerator(
                    name='queries',
                    gen_kwargs={
                        'filepaths': downloaded_files,
                    },
                ),
            ]
        else:
            language = name
            downloaded_files = dl_manager.download_and_extract(
                _DATASET_URLS[language]['dev'])
            splits = [
                datasets.SplitGenerator(
                    name='dev',
                    gen_kwargs={
                        'filepaths': downloaded_files,
                    },
                ),
            ]
        
        return splits

    def _generate_examples(self, filepaths):
        name = self.config.name

        if name.startswith('corpus-'):
            for filepath in sorted(filepaths):
                with open(filepath, encoding="utf-8") as f:
                    for line in f:
                        data = json.loads(line)
                        yield data['docid'], data
        
        elif name.startswith('queries-'):
            for filepath in filepaths:
                qid2topic = load_topic(filepath)
                for qid in qid2topic:
                    data = {}
                    data['query_id'] = qid
                    data['query'] = qid2topic[qid]
                    yield qid, data

        else:
            for filepath in filepaths:
                qrels = load_qrels(filepath)
                for qid in qrels:
                    for docid in qrels[qid]:
                        data = {}
                        data['query_id'] = qid
                        data['docid'] = docid
                        data['score'] = qrels[qid][docid]
                        yield f"{qid}.{docid}", data