File size: 16,679 Bytes
151bad5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 | #!/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()
|