| |
| """Build viewer-friendly file/shard index Parquet splits for LiteFold/UniRef50.""" |
|
|
| 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 pandas as pd |
| from huggingface_hub import HfApi, hf_hub_download |
|
|
|
|
| INDEX_COLUMNS = [ |
| "file_id", |
| "repo_id", |
| "source_sha", |
| "source_slug", |
| "path", |
| "role", |
| "shard_index", |
| "size_bytes", |
| "compression", |
| "records_total", |
| "residues_total", |
| "total_shards", |
| "is_sequence_shard", |
| "is_metadata_records", |
| "download_pattern", |
| "access_note", |
| "split_bucket", |
| ] |
|
|
|
|
| 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()) |
| source = manifest["sources"][0] |
| source_slug = source["source_slug"] |
| records_total = int(source["records"]) |
| residues_total = int(source["residues"]) |
| total_shards = int(source["shards"]) |
|
|
| rows = [] |
| for sibling in sorted(info.siblings or [], key=lambda item: item.rfilename): |
| path = sibling.rfilename |
| role, inferred_slug, shard_index, is_sequence_shard, is_metadata_records = role_for_path(path) |
| file_id = path |
| rows.append( |
| { |
| "file_id": file_id, |
| "repo_id": repo_id, |
| "source_sha": info.sha, |
| "source_slug": inferred_slug or source_slug, |
| "path": path, |
| "role": role, |
| "shard_index": shard_index, |
| "size_bytes": int(getattr(sibling, "size", 0) or 0), |
| "compression": compression_for_path(path), |
| "records_total": records_total, |
| "residues_total": residues_total, |
| "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 UniRef50; 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) |
|
|
| df = pd.DataFrame.from_records(rows, columns=INDEX_COLUMNS) |
| train = df[df["split_bucket"].ne(0)].sort_values("path", kind="mergesort") |
| test = df[df["split_bucket"].eq(0)].sort_values("path", kind="mergesort") |
| train.to_parquet(data_dir / "train-00000-of-00001.parquet", index=False, compression="zstd") |
| test.to_parquet(data_dir / "test-00000-of-00001.parquet", index=False, compression="zstd") |
| df.to_parquet(metadata_dir / "source_files.parquet", index=False, compression="zstd") |
|
|
| sequence_bytes = int(df[df["is_sequence_shard"]]["size_bytes"].sum()) |
| metadata_bytes = int(df[df["is_metadata_records"]]["size_bytes"].sum()) |
| summary = { |
| "source": repo_id, |
| "source_sha": info.sha, |
| "viewer_table_scope": "file/shard index", |
| "source_slug": source_slug, |
| "records_total": records_total, |
| "residues_total": residues_total, |
| "total_shards": total_shards, |
| "index_rows": int(len(df)), |
| "sequence_shard_rows": int(df["is_sequence_shard"].sum()), |
| "sequence_shard_bytes": sequence_bytes, |
| "metadata_records_bytes": metadata_bytes, |
| "splits": {"train": int(len(train)), "test": int(len(test))}, |
| "split_strategy": "deterministic sha256(file_id) % 10; bucket 0 is test, buckets 1-9 are train", |
| "role_counts": {str(k): int(v) for k, v in df["role"].value_counts().to_dict().items()}, |
| "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/UniRef50") |
| parser.add_argument("--raw-dir", type=Path, default=Path("LiteFold_UniRef50_raw")) |
| parser.add_argument("--out-dir", type=Path, default=Path("LiteFold_UniRef50_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() |
|
|