FLIP2 / scripts /prepare_wrapped_jsonl_dataset.py
anindya64's picture
Add normalized Parquet train/test FLIP2 table
d12db90 verified
#!/usr/bin/env python3
"""Build viewer-friendly Parquet splits for LiteFold wrapped JSONL table repos."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import re
import shutil
from collections import Counter
from pathlib import Path
from typing import Any, Iterable
import pyarrow as pa
import pyarrow.parquet as pq
import pandas as pd
from huggingface_hub import HfApi, hf_hub_download
BASE_COLUMNS = [
"record_id",
"dataset_id",
"source_file",
"source_table",
"source_row_index",
"table_group",
"task_name",
"subtask_name",
"entity_type",
"assay_name",
"sequence",
"sequence_length",
"mutation",
"target",
"score_value",
"label",
"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 normalize_name(name: str) -> str:
normalized = re.sub(r"[^0-9A-Za-z]+", "_", name).strip("_").lower()
if not normalized:
normalized = "field"
if normalized[0].isdigit():
normalized = f"x_{normalized}"
return normalized
def unique_names(keys: Iterable[str]) -> dict[str, str]:
mapping: dict[str, str] = {}
used: Counter[str] = Counter()
for key in sorted(keys):
base = normalize_name(key)
candidate = base
if candidate in BASE_COLUMNS:
candidate = f"raw_{candidate}"
used[candidate] += 1
if used[candidate] > 1:
candidate = f"{candidate}_{used[candidate]}"
mapping[key] = candidate
return mapping
def scalar_string(value: Any) -> str | None:
if value is None or value == "":
return None
if isinstance(value, (dict, list)):
return json.dumps(value, sort_keys=True, ensure_ascii=False)
return str(value)
def parse_float(value: Any) -> float | None:
if value is None or value == "":
return None
try:
return float(value)
except (TypeError, ValueError):
return None
def first_present(row: dict[str, Any], keys: list[str]) -> Any:
for key in keys:
value = row.get(key)
if value is not None and value != "":
return value
return None
def table_path_from_manifest(output_file: str) -> str:
prefix = "data/processed/"
if output_file.startswith(prefix):
parts = output_file.split("/tables/", 1)
if len(parts) == 2:
return "tables/" + parts[1]
return output_file
def get_table_files(repo_id: str, mode: str, raw_dir: Path, token: str | None) -> tuple[list[str], list[dict[str, Any]]]:
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())
manifest_tables = manifest.get("tables") or []
if manifest_tables:
table_paths = [table_path_from_manifest(item["output_file"]) for item in manifest_tables]
else:
api = HfApi(token=token)
info = api.dataset_info(repo_id, files_metadata=True)
table_paths = [s.rfilename for s in info.siblings or [] if s.rfilename.startswith("tables/")]
manifest_tables = []
if mode == "cycpeptmpdb":
table_paths = [
path for path in table_paths if path.endswith("_Peptide_All.csv.jsonl") or path.endswith("_Monomer_All.csv.jsonl")
]
if mode == "proteingym":
table_paths = [path for path in table_paths if ".ipynb_checkpoints" not in path]
return sorted(set(table_paths)), manifest_tables
def classify(mode: str, source_file: str, source_table: str) -> dict[str, Any]:
source_parts = Path(source_file).parts
basename = Path(source_file).name.removesuffix(".csv")
if mode == "proteingym":
lower = source_file.lower()
if "indels" in lower:
table_group = "indels"
elif "substitutions" in lower:
table_group = "substitutions"
elif "clinical" in lower:
table_group = "clinical"
else:
table_group = "other"
if "raw_dms" in lower:
task_name = "DMS"
elif "clinical" in lower:
task_name = "clinical"
else:
task_name = None
return {
"table_group": table_group,
"task_name": task_name,
"subtask_name": None,
"entity_type": "variant",
"assay_name": basename,
}
if mode == "flip2":
task_name = source_parts[-2] if len(source_parts) >= 2 else None
return {
"table_group": "benchmark",
"task_name": task_name,
"subtask_name": basename,
"entity_type": "sequence",
"assay_name": f"{task_name}/{basename}" if task_name else basename,
}
if mode == "cycpeptmpdb":
entity_type = "peptide" if "Peptide" in basename else "monomer" if "Monomer" in basename else None
return {
"table_group": "all",
"task_name": "CycPeptMPDB",
"subtask_name": basename,
"entity_type": entity_type,
"assay_name": basename,
}
return {"table_group": None, "task_name": None, "subtask_name": None, "entity_type": None, "assay_name": basename}
def derived_values(mode: str, wrapper: dict[str, Any]) -> dict[str, Any]:
row = wrapper.get("row") or {}
source_file = wrapper.get("source_file") or ""
source_table = wrapper.get("_source_table") or ""
source_row_index = wrapper.get("row_index")
record_seed = f"{source_file}|{source_row_index}|{json.dumps(row, sort_keys=True, ensure_ascii=False)}"
record_id = hashlib.sha256(record_seed.encode("utf-8")).hexdigest()
derived = {
"record_id": record_id,
"dataset_id": wrapper.get("dataset_id"),
"source_file": source_file,
"source_table": source_table,
"source_row_index": int(source_row_index) if source_row_index is not None else None,
"split_bucket": stable_bucket(record_id),
}
derived.update(classify(mode, source_file, source_table))
sequence = first_present(
row,
[
"mutated_sequence",
"mutant_sequence",
"sequence",
"Sequence",
"aa_seq",
"aa_seq_full",
"wildtype_sequence",
"WT_sequence",
],
)
target = first_present(row, ["target", "DMS_score", "fitness", "score", "Permeability", "deltaG", "dG_ML"])
score_value = None
for key in ["target", "DMS_score", "fitness", "score", "Permeability", "deltaG", "dG_ML", "ddG_ML", "Caco2", "PAMPA", "MDCK", "RRCK"]:
score_value = parse_float(row.get(key))
if score_value is not None:
break
mutation = first_present(row, ["mutant", "mutation", "mutations", "name", "mut_class", "ID", "id"])
label = first_present(row, ["DMS_score_bin", "label", "set", "validation", "class", "mut_type", "Molecule_Shape"])
derived.update(
{
"sequence": scalar_string(sequence),
"sequence_length": len(str(sequence)) if sequence is not None else None,
"mutation": scalar_string(mutation),
"target": scalar_string(target),
"score_value": score_value,
"label": scalar_string(label),
}
)
return derived
def iter_wrappers(path: Path, source_table: str) -> Iterable[dict[str, Any]]:
with path.open("r", encoding="utf-8", errors="replace") as handle:
for line in handle:
if not line.strip():
continue
item = json.loads(line)
item["_source_table"] = source_table
yield item
def download_tables(repo_id: str, table_paths: list[str], raw_dir: Path, token: str | None) -> list[Path]:
paths = []
for index, table_path in enumerate(table_paths, start=1):
local = Path(hf_hub_download(repo_id=repo_id, repo_type="dataset", filename=table_path, local_dir=raw_dir, token=token))
paths.append(local)
if index == 1 or index % 25 == 0 or index == len(table_paths):
print(f"downloaded {index}/{len(table_paths)} {table_path}", flush=True)
return paths
def write_split_shards(
out_dir: Path,
rows_iter: Iterable[dict[str, Any]],
schema: pa.Schema,
chunk_rows: int,
) -> dict[str, int]:
data_dir = out_dir / "data"
data_dir.mkdir(parents=True, exist_ok=True)
buffers: dict[str, list[dict[str, Any]]] = {"train": [], "test": []}
counts = {"train": 0, "test": 0}
shard_counts = {"train": 0, "test": 0}
def flush(split: str) -> None:
if not buffers[split]:
return
shard = shard_counts[split]
path = data_dir / f"{split}-{shard:05d}-of-XXXXX.parquet"
table = pa.Table.from_pylist(buffers[split], schema=schema)
pq.write_table(table, path, compression="zstd")
counts[split] += len(buffers[split])
shard_counts[split] += 1
buffers[split].clear()
for row in rows_iter:
split = "test" if row["split_bucket"] == 0 else "train"
buffers[split].append(row)
if len(buffers[split]) >= chunk_rows:
flush(split)
flush("train")
flush("test")
for split in ["train", "test"]:
total = shard_counts[split]
for path in sorted(data_dir.glob(f"{split}-*-of-XXXXX.parquet")):
new_name = path.name.replace("of-XXXXX", f"of-{total:05d}")
path.rename(path.with_name(new_name))
return counts
def build_dataset(repo_id: str, mode: str, raw_dir: Path, out_dir: Path, chunk_rows: int) -> dict[str, Any]:
token = load_token()
raw_dir.mkdir(parents=True, exist_ok=True)
table_paths, manifest_tables = get_table_files(repo_id, mode, raw_dir, token)
local_paths = download_tables(repo_id, table_paths, raw_dir, token)
raw_keys: set[str] = set()
table_stats: list[dict[str, Any]] = []
total_rows = 0
for source_table, local_path in zip(table_paths, local_paths):
rows = 0
dataset_id = None
source_file = None
for wrapper in iter_wrappers(local_path, source_table):
row = wrapper.get("row") or {}
raw_keys.update(row.keys())
rows += 1
dataset_id = wrapper.get("dataset_id")
source_file = wrapper.get("source_file")
total_rows += rows
table_stats.append(
{
"source_table": source_table,
"source_file": source_file,
"dataset_id": dataset_id,
"rows": rows,
"size_bytes": local_path.stat().st_size,
}
)
print(f"scanned {source_table}: {rows} rows", flush=True)
raw_mapping = unique_names(raw_keys)
raw_columns = [raw_mapping[key] for key in sorted(raw_mapping)]
schema_fields = [
pa.field("record_id", pa.string()),
pa.field("dataset_id", pa.string()),
pa.field("source_file", pa.string()),
pa.field("source_table", pa.string()),
pa.field("source_row_index", pa.int64()),
pa.field("table_group", pa.string()),
pa.field("task_name", pa.string()),
pa.field("subtask_name", pa.string()),
pa.field("entity_type", pa.string()),
pa.field("assay_name", pa.string()),
pa.field("sequence", pa.string()),
pa.field("sequence_length", pa.int64()),
pa.field("mutation", pa.string()),
pa.field("target", pa.string()),
pa.field("score_value", pa.float64()),
pa.field("label", pa.string()),
pa.field("split_bucket", pa.int64()),
] + [pa.field(column, pa.string()) for column in raw_columns]
schema = pa.schema(schema_fields)
if out_dir.exists():
shutil.rmtree(out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
def row_iter() -> Iterable[dict[str, Any]]:
emitted = 0
for source_table, local_path in zip(table_paths, local_paths):
for wrapper in iter_wrappers(local_path, source_table):
raw = wrapper.get("row") or {}
row = {column: None for column in BASE_COLUMNS + raw_columns}
row.update(derived_values(mode, wrapper))
for original_key, column in raw_mapping.items():
row[column] = scalar_string(raw.get(original_key))
emitted += 1
if emitted % 250000 == 0:
print(f"prepared {emitted}/{total_rows} rows", flush=True)
yield row
split_counts = write_split_shards(out_dir, row_iter(), schema, chunk_rows)
metadata_dir = out_dir / "metadata"
metadata_dir.mkdir(parents=True, exist_ok=True)
pd.DataFrame.from_records(table_stats).to_parquet(metadata_dir / "source_tables.parquet", index=False, compression="zstd")
pd.DataFrame.from_records(
[{"raw_key": key, "column": raw_mapping[key]} for key in sorted(raw_mapping)]
).to_parquet(metadata_dir / "column_mapping.parquet", index=False, compression="zstd")
summary = {
"source": repo_id,
"mode": mode,
"source_table_rows": len(table_stats),
"entry_rows": int(total_rows),
"raw_field_count": len(raw_columns),
"splits": split_counts,
"split_strategy": "deterministic sha256(record_id) % 10; bucket 0 is test, buckets 1-9 are train",
"table_group_counts": dict(Counter(item["source_file"].split("/")[-2] if item["source_file"] and "/" in item["source_file"] else "unknown" for item in table_stats).most_common()),
"columns": BASE_COLUMNS + raw_columns,
"metadata_tables": ["metadata/source_tables.parquet", "metadata/column_mapping.parquet"],
}
(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", required=True)
parser.add_argument("--mode", required=True, choices=["proteingym", "flip2", "cycpeptmpdb"])
parser.add_argument("--raw-dir", type=Path, required=True)
parser.add_argument("--out-dir", type=Path, required=True)
parser.add_argument("--chunk-rows", type=int, default=200000)
args = parser.parse_args()
summary = build_dataset(args.repo_id, args.mode, args.raw_dir, args.out_dir, args.chunk_rows)
print(json.dumps(summary, indent=2))
if __name__ == "__main__":
main()