"""Attach the original MS MARCO text to Doubting MS MARCO pairs, from the official TSV files. The package stores ids only. Download the MS MARCO passage ranking files yourself (https://microsoft.github.io/msmarco/): collection.tsv (passage id, text) and the queries file of the split (queries.train.tsv or queries.dev.small.tsv; query id, text). Only the needed lines are kept in memory. Usage: python join_text.py --package DIR --config qrels --split dev --collection collection.tsv --queries queries.dev.small.tsv --out pairs_with_text.tsv [--limit N] Writes query_id, passage_id, grade (and origin, agent or official, for --config judgments, where one pair can carry both), query text and passage text as TSV. Needs pyarrow (`pip install pyarrow`). """ import argparse import csv import glob import os import sys import pyarrow.parquet as pq def columns(config): return ["query_id", "passage_id", "grade"] + (["origin"] if config == "judgments" else []) def read_pairs(package, config, split, limit=None): """Rows of (query_id, passage_id, grade[, origin]) in file order.""" pairs = [] for path in sorted(glob.glob(os.path.join(package, "data", config, f"{split}-*.parquet"))): t = pq.read_table(path, columns=columns(config)) for row in zip(*(t[c].to_pylist() for c in columns(config))): pairs.append(row) if limit and len(pairs) >= limit: return pairs if not pairs: sys.exit(f"no Parquet files for {config}/{split} under {package}") return pairs def read_tsv_texts(path, wanted): """{id: text} for the wanted ids of a two-column TSV (id, text).""" out = {} with open(path, encoding="utf-8", newline="") as f: for line in f: i, _, text = line.rstrip("\n").partition("\t") if i in wanted: out[i] = text return out def join(pairs, collection, queries): p_text = read_tsv_texts(collection, {r[1] for r in pairs}) q_text = read_tsv_texts(queries, {r[0] for r in pairs}) missing_p = {r[1] for r in pairs} - set(p_text) missing_q = {r[0] for r in pairs} - set(q_text) if missing_p or missing_q: sys.exit(f"{len(missing_q)} query ids and {len(missing_p)} passage ids not found: wrong file or split?") return [tuple(r) + (q_text[r[0]], p_text[r[1]]) for r in pairs] def main(): ap = argparse.ArgumentParser() ap.add_argument("--package", default=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) ap.add_argument("--config", default="qrels", choices=["qrels", "judgments"]) ap.add_argument("--split", default="dev", choices=["train", "dev"]) ap.add_argument("--collection", required=True) ap.add_argument("--queries", required=True) ap.add_argument("--out", required=True) ap.add_argument("--limit", type=int) a = ap.parse_args() rows = join(read_pairs(a.package, a.config, a.split, a.limit), a.collection, a.queries) with open(a.out, "w", encoding="utf-8", newline="") as f: w = csv.writer(f, delimiter="\t", lineterminator="\n") w.writerow(columns(a.config) + ["query", "passage"]) w.writerows(rows) print(f"wrote {len(rows):,} rows to {a.out}") if __name__ == "__main__": main()