# 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