NCBI / scripts /prepare_ncbi_dataset.py
anindya64's picture
Add normalized Parquet train/test NCBI shard index
c964bc2 verified
Raw
History Blame Contribute Delete
8.78 kB
#!/usr/bin/env python3
"""Build viewer-friendly file/shard index Parquet splits for LiteFold/NCBI."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import re
import shutil
from pathlib import Path
from typing import Any
import pyarrow as pa
import pyarrow.parquet as pq
from huggingface_hub import HfApi, hf_hub_download
INDEX_COLUMNS = [
"file_id",
"repo_id",
"source_sha",
"dataset_id",
"source_slug",
"source_file",
"path",
"role",
"shard_index",
"size_bytes",
"compression",
"records_in_source",
"residues_in_source",
"shards_in_source",
"records_total",
"residues_total",
"total_shards",
"is_sequence_shard",
"is_metadata_records",
"download_pattern",
"access_note",
"split_bucket",
]
SCHEMA = pa.schema(
[
pa.field("file_id", pa.string()),
pa.field("repo_id", pa.string()),
pa.field("source_sha", pa.string()),
pa.field("dataset_id", pa.string()),
pa.field("source_slug", pa.string()),
pa.field("source_file", pa.string()),
pa.field("path", pa.string()),
pa.field("role", pa.string()),
pa.field("shard_index", pa.int64()),
pa.field("size_bytes", pa.int64()),
pa.field("compression", pa.string()),
pa.field("records_in_source", pa.int64()),
pa.field("residues_in_source", pa.int64()),
pa.field("shards_in_source", pa.int64()),
pa.field("records_total", pa.int64()),
pa.field("residues_total", pa.int64()),
pa.field("total_shards", pa.int64()),
pa.field("is_sequence_shard", pa.bool_()),
pa.field("is_metadata_records", pa.bool_()),
pa.field("download_pattern", pa.string()),
pa.field("access_note", pa.string()),
pa.field("split_bucket", pa.int64()),
]
)
def load_token() -> str | None:
for key in ("HF_TOKEN", "HUGGINGFACE_HUB_TOKEN"):
value = os.environ.get(key)
if value:
return value
env_path = Path(".env")
if env_path.exists():
for line in env_path.read_text().splitlines():
stripped = line.strip()
if not stripped or stripped.startswith("#") or "=" not in stripped:
continue
key, value = stripped.split("=", 1)
if key.strip() in {"HF_TOKEN", "HUGGINGFACE_HUB_TOKEN"}:
value = value.strip().strip('"').strip("'")
if value:
return value
return None
def stable_bucket(value: str, buckets: int = 10) -> int:
digest = hashlib.sha256(value.encode("utf-8")).hexdigest()[:16]
return int(digest, 16) % buckets
def role_for_path(path: str) -> tuple[str, str | None, int | None, bool, bool]:
shard_match = re.search(r"sequences/([^/]+)/shard-(\d+)\.fasta\.zst$", path)
if shard_match:
return "sequence_shard", shard_match.group(1), int(shard_match.group(2)), True, False
metadata_match = re.search(r"metadata/(.+)\.records\.jsonl$", path)
if metadata_match:
return "metadata_records", metadata_match.group(1), None, False, True
manifest_match = re.search(r"manifests/(.+)\.json$", path)
if manifest_match:
return "source_manifest", manifest_match.group(1), None, False, False
if path == "_MANIFEST.json":
return "aggregate_manifest", None, None, False, False
if path == "README.md":
return "readme", None, None, False, False
if path == ".gitattributes":
return "git_attributes", None, None, False, False
return "other", None, None, False, False
def compression_for_path(path: str) -> str | None:
if path.endswith(".fasta.zst"):
return "zstd"
return None
def build_dataset(repo_id: str, raw_dir: Path, out_dir: Path) -> dict[str, Any]:
token = load_token()
api = HfApi(token=token)
info = api.dataset_info(repo_id, files_metadata=True)
raw_dir.mkdir(parents=True, exist_ok=True)
manifest_path = Path(
hf_hub_download(
repo_id=repo_id,
repo_type="dataset",
filename="_MANIFEST.json",
local_dir=raw_dir,
token=token,
)
)
manifest = json.loads(manifest_path.read_text())
dataset_id = str(manifest["dataset_id"])
total_records = int(manifest["total_records"])
total_residues = int(manifest["total_residues"])
total_shards = int(manifest["total_shards"])
sources_by_slug = {source["source_slug"]: source for source in manifest["sources"]}
rows = []
for sibling in sorted(info.siblings or [], key=lambda item: item.rfilename):
path = sibling.rfilename
role, source_slug, shard_index, is_sequence_shard, is_metadata_records = role_for_path(path)
source = sources_by_slug.get(source_slug or "")
file_id = path
rows.append(
{
"file_id": file_id,
"repo_id": repo_id,
"source_sha": info.sha,
"dataset_id": dataset_id,
"source_slug": source_slug,
"source_file": source.get("source_file") if source else None,
"path": path,
"role": role,
"shard_index": shard_index,
"size_bytes": int(getattr(sibling, "size", 0) or 0),
"compression": compression_for_path(path),
"records_in_source": int(source["records"]) if source else None,
"residues_in_source": int(source["residues"]) if source else None,
"shards_in_source": int(source["shards"]) if source else None,
"records_total": total_records,
"residues_total": total_residues,
"total_shards": total_shards,
"is_sequence_shard": is_sequence_shard,
"is_metadata_records": is_metadata_records,
"download_pattern": f"sequences/{source_slug}/shard-*.fasta.zst" if is_sequence_shard else path,
"access_note": "File/shard index for NCBI RefSeq protein; download sequence shards for FASTA records.",
"split_bucket": stable_bucket(file_id),
}
)
if out_dir.exists():
shutil.rmtree(out_dir)
data_dir = out_dir / "data"
metadata_dir = out_dir / "metadata"
data_dir.mkdir(parents=True, exist_ok=True)
metadata_dir.mkdir(parents=True, exist_ok=True)
train_rows = sorted((row for row in rows if row["split_bucket"] != 0), key=lambda row: row["path"])
test_rows = sorted((row for row in rows if row["split_bucket"] == 0), key=lambda row: row["path"])
pq.write_table(pa.Table.from_pylist(train_rows, schema=SCHEMA), data_dir / "train-00000-of-00001.parquet", compression="zstd")
pq.write_table(pa.Table.from_pylist(test_rows, schema=SCHEMA), data_dir / "test-00000-of-00001.parquet", compression="zstd")
pq.write_table(pa.Table.from_pylist(rows, schema=SCHEMA), metadata_dir / "source_files.parquet", compression="zstd")
sequence_bytes = sum(int(row["size_bytes"]) for row in rows if row["is_sequence_shard"])
metadata_bytes = sum(int(row["size_bytes"]) for row in rows if row["is_metadata_records"])
role_counts: dict[str, int] = {}
for row in rows:
role_counts[row["role"]] = role_counts.get(row["role"], 0) + 1
summary = {
"source": repo_id,
"source_sha": info.sha,
"viewer_table_scope": "file/shard index",
"dataset_id": dataset_id,
"source_count": int(manifest["source_count"]),
"records_total": total_records,
"residues_total": total_residues,
"total_shards": total_shards,
"index_rows": len(rows),
"sequence_shard_rows": sum(1 for row in rows if row["is_sequence_shard"]),
"sequence_shard_bytes": sequence_bytes,
"metadata_records_bytes": metadata_bytes,
"splits": {"train": len(train_rows), "test": len(test_rows)},
"split_strategy": "deterministic sha256(file_id) % 10; bucket 0 is test, buckets 1-9 are train",
"role_counts": role_counts,
"columns": INDEX_COLUMNS,
}
(out_dir / "dataset_summary.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8")
return summary
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--repo-id", default="LiteFold/NCBI")
parser.add_argument("--raw-dir", type=Path, default=Path("LiteFold_NCBI_raw"))
parser.add_argument("--out-dir", type=Path, default=Path("LiteFold_NCBI_processed"))
args = parser.parse_args()
summary = build_dataset(args.repo_id, args.raw_dir, args.out_dir)
print(json.dumps(summary, indent=2))
if __name__ == "__main__":
main()