#!/usr/bin/env python3 """Build a viewer-friendly file/shard index for LiteFold/Mgnify.""" from __future__ import annotations import argparse import hashlib import json import os import re import shutil from collections import Counter, defaultdict 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 DATASET_ID = "mgnify_proteins" PREFIX = "sequence_mgnify_current_release_" INDEX_COLUMNS = [ "file_id", "repo_id", "source_sha", "dataset_id", "source_family", "source_slug", "source_file", "path", "role", "shard_index", "part_index", "size_bytes", "compression", "logical_table_size_bytes", "split_part_count", "split_chunk_bytes", "sequence_source_shard_count", "sequence_source_bytes", "repo_file_count", "repo_total_bytes", "sequence_shard_count_total", "sequence_shard_bytes_total", "table_repo_file_count_total", "table_repo_bytes_total", "logical_table_count_total", "logical_table_bytes_total", "is_sequence_shard", "is_table_file", "is_split_part", "is_split_manifest", "is_original_table_copy", "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_family", 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("part_index", pa.int64()), pa.field("size_bytes", pa.int64()), pa.field("compression", pa.string()), pa.field("logical_table_size_bytes", pa.int64()), pa.field("split_part_count", pa.int64()), pa.field("split_chunk_bytes", pa.int64()), pa.field("sequence_source_shard_count", pa.int64()), pa.field("sequence_source_bytes", pa.int64()), pa.field("repo_file_count", pa.int64()), pa.field("repo_total_bytes", pa.int64()), pa.field("sequence_shard_count_total", pa.int64()), pa.field("sequence_shard_bytes_total", pa.int64()), pa.field("table_repo_file_count_total", pa.int64()), pa.field("table_repo_bytes_total", pa.int64()), pa.field("logical_table_count_total", pa.int64()), pa.field("logical_table_bytes_total", pa.int64()), pa.field("is_sequence_shard", pa.bool_()), pa.field("is_table_file", pa.bool_()), pa.field("is_split_part", pa.bool_()), pa.field("is_split_manifest", pa.bool_()), pa.field("is_original_table_copy", 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 source_file_from_slug(slug: str) -> str: if slug.startswith(PREFIX): return "sequence/mgnify/current_release/" + slug[len(PREFIX) :] return "" def source_family_from_slug(slug: str) -> str: if slug.startswith(PREFIX): slug = slug[len(PREFIX) :] for suffix in (".fasta.zst", ".fa.gz", ".tsv.gz.jsonl", ".tsv.gz"): if slug.endswith(suffix): slug = slug[: -len(suffix)] return slug def compression_for_path(path: str) -> str: if path.endswith(".fasta.zst"): return "zstd" if path.endswith(".jsonl"): return "jsonl" if path.endswith(".json"): return "json" return "" def parse_path(path: str) -> dict[str, Any]: sequence_match = re.fullmatch(r"sequences/([^/]+)/shard-(\d+)\.fasta\.zst", path) if sequence_match: source_slug = sequence_match.group(1) return { "role": "sequence_shard", "source_slug": source_slug, "source_family": source_family_from_slug(source_slug), "source_file": source_file_from_slug(source_slug), "shard_index": int(sequence_match.group(2)), "part_index": -1, "is_sequence_shard": True, "is_table_file": False, "is_split_part": False, "is_split_manifest": False, "is_original_table_copy": False, } split_manifest_match = re.fullmatch(r"tables/(.+\.jsonl)\.parts/_SPLIT_MANIFEST\.json", path) if split_manifest_match: source_slug = split_manifest_match.group(1) return { "role": "table_split_manifest", "source_slug": source_slug, "source_family": source_family_from_slug(source_slug), "source_file": source_file_from_slug(source_slug.removesuffix(".jsonl")), "shard_index": -1, "part_index": -1, "is_sequence_shard": False, "is_table_file": True, "is_split_part": False, "is_split_manifest": True, "is_original_table_copy": False, } split_part_match = re.fullmatch(r"tables/(.+\.jsonl)\.parts/part-(\d+)\.jsonl", path) if split_part_match: source_slug = split_part_match.group(1) return { "role": "table_split_part", "source_slug": source_slug, "source_family": source_family_from_slug(source_slug), "source_file": source_file_from_slug(source_slug.removesuffix(".jsonl")), "shard_index": -1, "part_index": int(split_part_match.group(2)), "is_sequence_shard": False, "is_table_file": True, "is_split_part": True, "is_split_manifest": False, "is_original_table_copy": False, } table_match = re.fullmatch(r"tables/(.+\.jsonl)", path) if table_match: source_slug = table_match.group(1) return { "role": "table_jsonl", "source_slug": source_slug, "source_family": source_family_from_slug(source_slug), "source_file": source_file_from_slug(source_slug.removesuffix(".jsonl")), "shard_index": -1, "part_index": -1, "is_sequence_shard": False, "is_table_file": True, "is_split_part": False, "is_split_manifest": False, "is_original_table_copy": False, } role = {".gitattributes": "git_attributes", "README.md": "readme"}.get(path, "other") return { "role": role, "source_slug": "", "source_family": "", "source_file": "", "shard_index": -1, "part_index": -1, "is_sequence_shard": False, "is_table_file": False, "is_split_part": False, "is_split_manifest": False, "is_original_table_copy": False, } def load_split_manifests(raw_dir: Path) -> dict[str, dict[str, Any]]: manifests: dict[str, dict[str, Any]] = {} for path in raw_dir.glob("tables/*.parts/_SPLIT_MANIFEST.json"): manifest = json.loads(path.read_text()) base_path = "tables/" + path.parent.name.removesuffix(".parts") manifests[base_path] = manifest return manifests 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) for sibling in info.siblings or []: path = sibling.rfilename if path == "README.md" or path.endswith("_SPLIT_MANIFEST.json"): hf_hub_download(repo_id=repo_id, repo_type="dataset", filename=path, local_dir=raw_dir, token=token) split_manifests = load_split_manifests(raw_dir) sizes = {s.rfilename: int(getattr(s, "size", 0) or 0) for s in info.siblings or []} source_sequence_counts: dict[str, int] = defaultdict(int) source_sequence_bytes: dict[str, int] = defaultdict(int) for path, size in sizes.items(): parsed = parse_path(path) if parsed["is_sequence_shard"]: source_sequence_counts[parsed["source_slug"]] += 1 source_sequence_bytes[parsed["source_slug"]] += size top_level_tables = { path: size for path, size in sizes.items() if path.startswith("tables/") and path.endswith(".jsonl") and ".parts/" not in path } logical_tables = dict(top_level_tables) for base_path, manifest in split_manifests.items(): if base_path not in logical_tables: logical_tables[base_path] = int(manifest["original_size"]) repo_file_count = len(sizes) repo_total_bytes = sum(sizes.values()) sequence_shard_count_total = sum(1 for path in sizes if path.startswith("sequences/")) sequence_shard_bytes_total = sum(size for path, size in sizes.items() if path.startswith("sequences/")) table_repo_file_count_total = sum(1 for path in sizes if path.startswith("tables/")) table_repo_bytes_total = sum(size for path, size in sizes.items() if path.startswith("tables/")) logical_table_count_total = len(logical_tables) logical_table_bytes_total = sum(logical_tables.values()) rows = [] for path in sorted(sizes): if ( path.startswith("data/") or path.startswith("metadata/") or path.startswith("scripts/") or path in {"_MANIFEST.json", "dataset_summary.json"} ): continue size = sizes[path] parsed = parse_path(path) source_slug = parsed["source_slug"] base_table_path = f"tables/{source_slug}" if source_slug.endswith(".jsonl") else "" manifest = split_manifests.get(base_table_path) or {} file_id = path download_pattern = path if parsed["role"] == "sequence_shard" and source_slug: download_pattern = f"sequences/{source_slug}/shard-*.fasta.zst" elif parsed["role"] in {"table_split_part", "table_split_manifest"} and source_slug: download_pattern = f"tables/{source_slug}.parts/part-*.jsonl" elif parsed["role"] == "table_jsonl" and source_slug: download_pattern = f"tables/{source_slug}" rows.append( { "file_id": file_id, "repo_id": repo_id, "source_sha": info.sha, "dataset_id": DATASET_ID, "source_family": parsed["source_family"], "source_slug": source_slug, "source_file": parsed["source_file"], "path": path, "role": parsed["role"], "shard_index": parsed["shard_index"], "part_index": parsed["part_index"], "size_bytes": size, "compression": compression_for_path(path), "logical_table_size_bytes": int(logical_tables.get(base_table_path, -1)) if parsed["is_table_file"] else -1, "split_part_count": len(manifest.get("parts", [])) if manifest else -1, "split_chunk_bytes": int(manifest.get("chunk_bytes", -1)) if manifest else -1, "sequence_source_shard_count": source_sequence_counts.get(source_slug, -1) if parsed["is_sequence_shard"] else -1, "sequence_source_bytes": source_sequence_bytes.get(source_slug, -1) if parsed["is_sequence_shard"] else -1, "repo_file_count": repo_file_count, "repo_total_bytes": repo_total_bytes, "sequence_shard_count_total": sequence_shard_count_total, "sequence_shard_bytes_total": sequence_shard_bytes_total, "table_repo_file_count_total": table_repo_file_count_total, "table_repo_bytes_total": table_repo_bytes_total, "logical_table_count_total": logical_table_count_total, "logical_table_bytes_total": logical_table_bytes_total, "is_sequence_shard": parsed["is_sequence_shard"], "is_table_file": parsed["is_table_file"], "is_split_part": parsed["is_split_part"], "is_split_manifest": parsed["is_split_manifest"], "is_original_table_copy": parsed["role"] == "table_jsonl" and base_table_path in split_manifests, "download_pattern": download_pattern, "access_note": "Default config indexes Mgnify files. Stream raw FASTA/table payloads from sequences/ and tables/ with huggingface_hub.", "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 = [row for row in rows if row["split_bucket"] != 0] test_rows = [row for row in rows if row["split_bucket"] == 0] 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") role_counts = Counter(row["role"] for row in rows) source_family_counts = Counter(row["source_family"] for row in rows if row["source_family"]) sequence_sources = { source_slug: {"shards": source_sequence_counts[source_slug], "bytes": source_sequence_bytes[source_slug]} for source_slug in sorted(source_sequence_counts) } logical_table_sources = { path: {"bytes": int(size), "has_split_parts": path in split_manifests} for path, size in sorted(logical_tables.items()) } summary = { "source": repo_id, "source_sha": info.sha, "viewer_table_scope": "file/shard index", "data_format": "parquet", "dataset_id": DATASET_ID, "index_rows": len(rows), "splits": {"train": len(train_rows), "test": len(test_rows)}, "split_strategy": "default file index uses deterministic sha256(file_id) % 10; bucket 0 is test, buckets 1-9 are train", "repo_file_count": repo_file_count, "repo_total_bytes": repo_total_bytes, "sequence_source_count": len(sequence_sources), "sequence_shard_count_total": sequence_shard_count_total, "sequence_shard_bytes_total": sequence_shard_bytes_total, "table_repo_file_count_total": table_repo_file_count_total, "table_repo_bytes_total": table_repo_bytes_total, "logical_table_count_total": logical_table_count_total, "logical_table_bytes_total": logical_table_bytes_total, "role_counts": dict(sorted(role_counts.items())), "source_family_index_counts": dict(sorted(source_family_counts.items())), "sequence_sources": sequence_sources, "logical_table_sources": logical_table_sources, "columns": INDEX_COLUMNS, } (out_dir / "_MANIFEST.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8") (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/Mgnify") parser.add_argument("--raw-dir", type=Path, default=Path("LiteFold_Mgnify_raw")) parser.add_argument("--out-dir", type=Path, default=Path("LiteFold_Mgnify_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()