Datasets:
File size: 12,862 Bytes
ea4b663 ce01506 ea4b663 ce01506 ea4b663 ce01506 ea4b663 ce01506 ea4b663 ce01506 ea4b663 ce01506 ea4b663 | 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 | #!/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()
|