#!/usr/bin/env python3 """Build a viewer-friendly default file/table index for LiteFold/UniProtKB.""" from __future__ import annotations import argparse import gzip import hashlib import json import os import re import shutil from pathlib import Path from typing import Any from huggingface_hub import HfApi, hf_hub_download INDEX_COLUMNS = [ "file_id", "repo_id", "source_sha", "dataset_id", "source_set", "source_slug", "source_file", "path", "role", "table_split", "shard_index", "size_bytes", "compression", "records_in_source", "residues_in_source", "shards_in_source", "records_in_table_split", "records_total", "residues_total", "total_sequence_shards", "is_sequence_shard", "is_table_shard", "is_metadata_records", "download_pattern", "access_note", "split_bucket", ] STRING_COLUMNS = { "file_id", "repo_id", "source_sha", "dataset_id", "source_set", "source_slug", "source_file", "path", "role", "table_split", "compression", "download_pattern", "access_note", } INT_COLUMNS = { "shard_index", "size_bytes", "records_in_source", "residues_in_source", "shards_in_source", "records_in_table_split", "records_total", "residues_total", "total_sequence_shards", "split_bucket", } SOURCE_SET_BY_SLUG = { "sequence_uniprotkb_uniprot_sprot.fasta.gz": "sprot", "sequence_uniprotkb_uniprot_sprot_varsplic.fasta.gz": "sprot_varsplic", "sequence_uniprotkb_uniprot_trembl.fasta.gz": "trembl", } 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 parse_path(path: str) -> dict[str, Any]: table_match = re.search(r"tables/source_set=([^/]+)/split=([^/]+)/protein_entries_shard-(\d+)\.jsonl\.gz$", path) if table_match: return { "role": "protein_entry_table_shard", "source_set": table_match.group(1), "table_split": table_match.group(2), "source_slug": None, "shard_index": int(table_match.group(3)), "is_sequence_shard": False, "is_table_shard": True, "is_metadata_records": False, } sequence_match = re.search(r"sequences/([^/]+)/shard-(\d+)\.fasta\.zst$", path) if sequence_match: source_slug = sequence_match.group(1) return { "role": "sequence_shard", "source_set": SOURCE_SET_BY_SLUG.get(source_slug), "table_split": None, "source_slug": source_slug, "shard_index": int(sequence_match.group(2)), "is_sequence_shard": True, "is_table_shard": False, "is_metadata_records": False, } metadata_match = re.search(r"metadata/(.+)\.records\.jsonl$", path) if metadata_match: source_slug = metadata_match.group(1) return { "role": "metadata_records", "source_set": SOURCE_SET_BY_SLUG.get(source_slug), "table_split": None, "source_slug": source_slug, "shard_index": None, "is_sequence_shard": False, "is_table_shard": False, "is_metadata_records": True, } manifest_match = re.search(r"manifests/(.+)\.json$", path) if manifest_match: source_slug = manifest_match.group(1) return { "role": "source_manifest", "source_set": SOURCE_SET_BY_SLUG.get(source_slug), "table_split": None, "source_slug": source_slug, "shard_index": None, "is_sequence_shard": False, "is_table_shard": False, "is_metadata_records": False, } role = { "_MANIFEST.json": "aggregate_manifest", "_POSTPROCESS_MANIFEST.json": "postprocess_manifest", "README.md": "readme", ".gitattributes": "git_attributes", }.get(path, "other") return { "role": role, "source_set": None, "table_split": None, "source_slug": None, "shard_index": None, "is_sequence_shard": False, "is_table_shard": False, "is_metadata_records": False, } def compression_for_path(path: str) -> str | None: if path.endswith(".fasta.zst"): return "zstd" if path.endswith(".jsonl.gz"): return "gzip" return None def viewer_row(row: dict[str, Any]) -> dict[str, Any]: stable = {} for column in INDEX_COLUMNS: value = row.get(column) if value is None and column in STRING_COLUMNS: value = "" elif value is None and column in INT_COLUMNS: value = -1 stable[column] = value return stable def write_jsonl_gz(path: Path, rows: list[dict[str, Any]]) -> None: with gzip.open(path, "wt", encoding="utf-8") as handle: for row in rows: handle.write(json.dumps(viewer_row(row), sort_keys=True, separators=(",", ":")) + "\n") 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) ) postprocess_path = Path( hf_hub_download( repo_id=repo_id, repo_type="dataset", filename="_POSTPROCESS_MANIFEST.json", local_dir=raw_dir, token=token, ) ) manifest = json.loads(manifest_path.read_text()) postprocess = json.loads(postprocess_path.read_text()) dataset_id = str(manifest["dataset_id"]) total_records = int(manifest["total_records"]) total_residues = int(manifest["total_residues"]) total_sequence_shards = int(manifest["total_shards"]) sources_by_slug = {source["source_slug"]: source for source in manifest["sources"]} post_by_source_set = {source["source_set"]: source for source in postprocess["sources"]} rows = [] for sibling in sorted(info.siblings or [], key=lambda item: item.rfilename): path = sibling.rfilename if ( path.startswith("data/") or path.startswith("dataset_summary") or path.startswith("scripts/") or path.startswith("metadata/source_files.") ): continue parsed = parse_path(path) source_slug = parsed["source_slug"] source_set = parsed["source_set"] if source_slug is None and source_set: post_source = post_by_source_set.get(source_set) if post_source: source_slug = post_source["source_slug"] source = sources_by_slug.get(source_slug or "") post_source = post_by_source_set.get(source_set or "") table_split = parsed["table_split"] file_id = path rows.append( { "file_id": file_id, "repo_id": repo_id, "source_sha": info.sha, "dataset_id": dataset_id, "source_set": source_set, "source_slug": source_slug, "source_file": source.get("source_file") if source else (post_source.get("source_file") if post_source else None), "path": path, "role": parsed["role"], "table_split": table_split, "shard_index": parsed["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 (int(post_source["records_written"]) if post_source else None), "residues_in_source": int(source["residues"]) if source else None, "shards_in_source": int(source["shards"]) if source else None, "records_in_table_split": int(post_source["split_counts"][table_split]) if post_source and table_split else None, "records_total": total_records, "residues_total": total_residues, "total_sequence_shards": total_sequence_shards, "is_sequence_shard": parsed["is_sequence_shard"], "is_table_shard": parsed["is_table_shard"], "is_metadata_records": parsed["is_metadata_records"], "download_pattern": f"tables/source_set={source_set}/split={table_split}/*.jsonl.gz" if parsed["is_table_shard"] else (f"sequences/{source_slug}/shard-*.fasta.zst" if parsed["is_sequence_shard"] else path), "access_note": "Default index over UniProtKB files. Load configs sprot, sprot_varsplic, or trembl for protein-entry rows.", "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"]) write_jsonl_gz(data_dir / "train-00000-of-00001.jsonl.gz", train_rows) write_jsonl_gz(data_dir / "test-00000-of-00001.jsonl.gz", test_rows) write_jsonl_gz(metadata_dir / "source_files.jsonl.gz", sorted(rows, key=lambda row: row["path"])) role_counts: dict[str, int] = {} source_set_counts: dict[str, int] = {} for row in rows: role_counts[row["role"]] = role_counts.get(row["role"], 0) + 1 if row["source_set"]: source_set_counts[row["source_set"]] = source_set_counts.get(row["source_set"], 0) + 1 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"]) table_bytes = sum(int(row["size_bytes"]) for row in rows if row["is_table_shard"]) summary = { "source": repo_id, "source_sha": info.sha, "viewer_table_scope": "file/table shard index", "data_format": "jsonl.gz", "dataset_id": dataset_id, "source_count": int(manifest["source_count"]), "records_total": total_records, "residues_total": total_residues, "total_sequence_shards": total_sequence_shards, "protein_entry_table_shards": sum(1 for row in rows if row["is_table_shard"]), "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, "protein_entry_table_bytes": table_bytes, "protein_entry_split_counts": postprocess["split_counts"], "splits": {"train": len(train_rows), "test": len(test_rows)}, "split_strategy": "default index uses deterministic sha256(file_id) % 10; bucket 0 is test, buckets 1-9 are train", "protein_entry_split_strategy": postprocess["split_version"], "role_counts": role_counts, "source_set_index_counts": source_set_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/UniProtKB") parser.add_argument("--raw-dir", type=Path, default=Path("LiteFold_UniProtKB_raw")) parser.add_argument("--out-dir", type=Path, default=Path("LiteFold_UniProtKB_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()