"""Publish a completed, matched corpus and BM25 index as a public Hub dataset.""" import argparse import json from pathlib import Path from urllib.request import Request, urlopen from huggingface_hub import HfApi, get_hf_file_metadata, hf_hub_url from rag_assignment.corpus import ProcessedCorpus from rag_assignment.retriever.bm25 import BM25Retriever from prepare_colab_artifacts import DATA_REVISION CARD = """--- license: cc-by-sa-3.0 task_categories: - question-answering - text-retrieval language: - en --- # BM25 corpus and index for the 2026-2 RAG project Derived from [NLPlab-skku/RAG-assignment](https://huggingface.co/datasets/NLPlab-skku/RAG-assignment) at revision `{revision}` under CC BY-SA 3.0. The source corpus consists of Wikipedia passages from the DPR `psgs_w100` split. The corpus preserves retained PIDs and original titles and text. The derived lexical field incorporates normalized titles and cleaned text after deduplication. The repository includes the matching bm25s index and a mapping for duplicate PIDs. Use `processed_corpus.jsonl` and `bm25/` from the same commit in the evaluation notebook. This dataset does not add external training examples. """ def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("directory", type=Path) parser.add_argument("repo_id") parser.add_argument("--training-summary", required=True, type=Path) parser.add_argument("--receipt", required=True, type=Path) args = parser.parse_args() root = args.directory manifest = json.loads((root / "preprocess_manifest.json").read_text(encoding="utf-8")) trained = json.loads(args.training_summary.read_text(encoding="utf-8")) if manifest["coreference_enabled"] or manifest["doc2query_enabled"]: raise ValueError("Expected only cleaning and deduplication") with ProcessedCorpus(root / "processed_corpus.jsonl") as corpus: BM25Retriever().load(root / "bm25", corpus) if (len(corpus.keys) + manifest["removed_pid_count"] != 1_087_303 or len(corpus.keys) != manifest["rows"] or corpus.evidence_sha256 != trained["evidence_sha256"]): raise ValueError("The completed corpus does not match the full assignment and local BGE training") remap = json.loads((root / "pid_remap.json").read_text(encoding="utf-8")) if len(remap) != manifest["removed_pid_count"]: raise ValueError("The PID mapping is incomplete") provenance = {key: manifest[key] for key in ( "rows", "removed_pid_count", "coreference_enabled", "doc2query_enabled", )} provenance["source_dataset"] = "NLPlab-skku/RAG-assignment" provenance["source_revision"] = DATA_REVISION (root / "build-info.json").write_text(json.dumps(provenance, indent=2) + "\n", encoding="utf-8") (root / "README.md").write_text(CARD.format(revision=DATA_REVISION), encoding="utf-8") files = ["processed_corpus.jsonl", "pid_remap.json", "README.md", "build-info.json"] files.extend(path.relative_to(root).as_posix() for path in sorted((root / "bm25").iterdir()) if path.is_file()) api = HfApi() account = api.whoami()["name"] if args.repo_id.split("/")[0].casefold() != account.casefold(): raise ValueError("The current account does not own the destination namespace") api.create_repo(args.repo_id, repo_type="dataset", private=False, exist_ok=True) if api.dataset_info(args.repo_id).private: raise ValueError("The destination must be public for unauthenticated Colab evaluation") result = api.upload_folder(repo_id=args.repo_id, repo_type="dataset", folder_path=root, allow_patterns=files, commit_message="Publish complete RAG evaluation corpus and BM25 index") remote = api.dataset_info(args.repo_id, revision=result.oid, files_metadata=True, token=False) sizes = {item.rfilename: item.size for item in remote.siblings} if remote.private or any(sizes.get(file) != (root / file).stat().st_size for file in files): raise RuntimeError("Public files at the uploaded revision do not match the verified artifacts") for file in files: url = hf_hub_url(args.repo_id, file, repo_type="dataset", revision=remote.sha) metadata = get_hf_file_metadata(url, token=False) if metadata.commit_hash != remote.sha or metadata.size != sizes[file]: raise RuntimeError(f"Anonymous download metadata did not match for {file}") if sizes[file]: request = Request(url, headers={"Range": "bytes=0-0"}) with urlopen(request, timeout=60) as response: if not response.read(1): raise RuntimeError(f"Anonymous download returned no data for {file}") receipt = {"repo_id": args.repo_id, "revision": remote.sha, "url": f"https://huggingface.co/datasets/{args.repo_id}", "rows": manifest["rows"]} args.receipt.parent.mkdir(parents=True, exist_ok=True) temporary = args.receipt.with_suffix(".tmp") temporary.write_text(json.dumps(receipt, indent=2) + "\n", encoding="utf-8") temporary.replace(args.receipt) print(json.dumps(receipt, indent=2), flush=True) if __name__ == "__main__": main()