mr-tydi / utils /convert_hgf_to_ir_format.py
Xinyu Crystina ZHANG
script and generated topic + qrels files in ir format
1da9e10
"""
This script only convert huggingface dataset into topic, qrels and folds files.
To prepare corpus falls in the JsonCollection in Anserini/Pyserini format, refer to the scripts in pyserini repository.
"""
import os
import sys
import json
import gzip
from glob import glob
from tqdm import tqdm
from datasets import load_dataset
dirname, abspath, os_join = os.path.dirname, os.path.abspath, os.path.join
dataset_dir = dirname(dirname(abspath(__file__)))
# output_dir = os_join(dataset_dir, "ir-format-dataset")
output_dir = dataset_dir
version = "v1.1"
languages = [
'arabic',
'bengali',
'english',
'indonesian',
'finnish',
'korean',
'russian',
'swahili',
'telugu',
'thai',
'japanese',
]
def get_output_dir(lang):
lang_dir = os_join(output_dir, f"mrtydi-{version}-{lang}", "ir-format-data")
os.makedirs(lang_dir, exist_ok=True)
return lang_dir
def write_topic(qid2query, outp_fn):
with open(outp_fn, "w") as f:
for qid in qid2query:
f.write(f"{qid}\t{qid2query[qid]}\n")
def write_qrels(qid2reldocs, outp_fn):
with open(outp_fn, "w") as f:
for qid in qid2reldocs:
for docid in qid2reldocs[qid]:
f.write(f"{qid}\tQ0\t{docid}\t1\n")
def convert_set(single_set):
qid2query = {}
qid2reldocs = {}
for data_entry in single_set:
qid = data_entry["query_id"]
query = data_entry["query"]
pos_docids = [doc["docid"] for doc in data_entry["positive_passages"]]
qid2query[qid] = query
qid2reldocs[qid] = pos_docids
return qid2query, qid2reldocs
def prepare_language(lang):
dataset = load_dataset('utils/local-mr-tydi.py', lang)
set_names = ["train", "dev", "test"]
folds = {}
output_dir = get_output_dir(lang)
for set_name in set_names:
topic_fn = os_join(output_dir, f"topics.{set_name}.txt")
qrel_fn = os_join(output_dir, f"qrels.{set_name}.txt")
qid2query, qid2reldocs = convert_set(dataset[set_name])
write_topic(qid2query, topic_fn)
write_qrels(qid2reldocs, qrel_fn)
def main():
for lang in languages:
prepare_language(lang)
if __name__ == "__main__":
main()