#!/usr/bin/env python3 """Build a flat, viewer-friendly FireProtDB table.""" from __future__ import annotations import argparse import hashlib import json import math import os import shutil import sys from collections import Counter from pathlib import Path from typing import Any, Iterable import pyarrow as pa import pyarrow.parquet as pq from huggingface_hub import HfApi, HfFileSystem, hf_hub_download try: import orjson except ImportError: # pragma: no cover - optional speedup orjson = None SOURCE_TABLE = "tables/labeled_fireprotdb_fireprotdb_search_all.jsonl.jsonl" COMMON_MEASUREMENTS = { "TM": "tm", "DTM": "dtm", "DG": "dg", "DDG": "ddg", "DH": "dh", "DCP": "dcp", "DHVH": "dhvh", "CM": "cm", "M": "m_value", "TRYPSIN_ML": "trypsin_ml", "CHYMOTRYPSIN_ML": "chymotrypsin_ml", "STABILIZING": "stabilizing", "DOMAINOME_FITNESS": "domainome_fitness", "DOMAINOME_FITNESS_STD": "domainome_fitness_std", "DOMAINOME_DDG": "domainome_ddg", "DOMAINOME_DDG_STD": "domainome_ddg_std", } SCHEMA = pa.schema( [ pa.field("row_id", pa.string()), pa.field("dataset_id", pa.string()), pa.field("source_dataset", pa.string()), pa.field("source_file", pa.string()), pa.field("source_table", pa.string()), pa.field("source_sha", pa.string()), pa.field("row_index", pa.int64()), pa.field("split", pa.string()), pa.field("subject_type", pa.string()), pa.field("entry_id", pa.int64()), pa.field("sequence_id", pa.int64()), pa.field("target_sequence_id", pa.int64()), pa.field("source_sequence_length", pa.int64()), pa.field("target_sequence_length", pa.int64()), pa.field("protein_id", pa.int64()), pa.field("protein_name", pa.string()), pa.field("organism", pa.string()), pa.field("isoform", pa.int64()), pa.field("protein_ids", pa.string()), pa.field("protein_names", pa.string()), pa.field("organisms", pa.string()), pa.field("isoforms", pa.string()), pa.field("uniprot_accessions", pa.string()), pa.field("interpro_accessions", pa.string()), pa.field("ec_numbers", pa.string()), pa.field("megascale_ids", pa.string()), pa.field("other_references", pa.string()), pa.field("mutations", pa.string()), pa.field("substitutions", pa.string()), pa.field("deletions", pa.string()), pa.field("insertions", pa.string()), pa.field("mutation_count", pa.int64()), pa.field("substitution_count", pa.int64()), pa.field("deletion_count", pa.int64()), pa.field("insertion_count", pa.int64()), pa.field("first_position", pa.int64()), pa.field("first_source_aa", pa.string()), pa.field("first_target_aa", pa.string()), pa.field("conservation", pa.float64()), pa.field("feature_types", pa.string()), pa.field("pdb_ids", pa.string()), pa.field("afdb_ids", pa.string()), pa.field("structure_ids", pa.string()), pa.field("structure_methods", pa.string()), pa.field("structure_resolution_min", pa.float64()), pa.field("residue_positions", pa.string()), pa.field("residue_chain_names", pa.string()), pa.field("residue_secondary_structures", pa.string()), pa.field("residue_in_pocket_any", pa.bool_()), pa.field("residue_in_tunnel_any", pa.bool_()), pa.field("residue_asa_mean", pa.float64()), pa.field("residue_bfactor_mean", pa.float64()), pa.field("experiment_id", pa.int64()), pa.field("experiment_dataset", pa.string()), pa.field("ph", pa.float64()), pa.field("measure", pa.string()), pa.field("method", pa.string()), pa.field("buffer", pa.string()), pa.field("buffer_conc", pa.string()), pa.field("exp_temperature", pa.float64()), pa.field("ion", pa.string()), pa.field("ion_conc", pa.string()), pa.field("pdb_chain_mutation", pa.string()), pa.field("tm", pa.float64()), pa.field("dtm", pa.float64()), pa.field("dg", pa.float64()), pa.field("dg_text", pa.string()), pa.field("ddg", pa.float64()), pa.field("dh", pa.float64()), pa.field("dcp", pa.float64()), pa.field("dhvh", pa.float64()), pa.field("cm", pa.float64()), pa.field("m_value", pa.float64()), pa.field("trypsin_ml", pa.float64()), pa.field("chymotrypsin_ml", pa.float64()), pa.field("stabilizing", pa.float64()), pa.field("stabilizing_text", pa.string()), pa.field("domainome_fitness", pa.float64()), pa.field("domainome_fitness_std", pa.float64()), pa.field("domainome_ddg", pa.float64()), pa.field("domainome_ddg_std", pa.float64()), pa.field("reversibility", pa.string()), pa.field("state", pa.string()), pa.field("measurement_types", pa.string()), pa.field("measurement_datasets", pa.string()), pa.field("annotation_types", pa.string()), pa.field("publication_id", pa.string()), pa.field("publication_type", pa.string()), pa.field("publication_title", pa.string()), pa.field("publication_year", pa.int64()), pa.field("publication_doi", pa.string()), pa.field("publication_pmid", pa.string()), pa.field("publication_journal", pa.string()), pa.field("publication_url", pa.string()), pa.field("publication_author_count", pa.int64()), pa.field("publication_authors", pa.string()), pa.field("annotations_json", pa.string()), pa.field("measurements_json", pa.string()), pa.field("features_json", pa.string()), ] ) STRING_DEFAULTS = {field.name for field in SCHEMA if pa.types.is_string(field.type)} INT_DEFAULTS = {field.name for field in SCHEMA if pa.types.is_int64(field.type)} BOOL_DEFAULTS = {field.name for field in SCHEMA if pa.types.is_boolean(field.type)} 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 as_int(value: Any) -> int: if value is None or value == "": return -1 try: return int(value) except (TypeError, ValueError): return -1 def as_float(value: Any) -> float | None: if value is None or value == "": return None try: numeric = float(value) except (TypeError, ValueError): return None if math.isnan(numeric) or math.isinf(numeric): return None return numeric def as_str(value: Any) -> str: if value is None: return "" return str(value) def compact_json(value: Any) -> str: if not value: return "" if orjson is not None: return orjson.dumps(value, option=orjson.OPT_SORT_KEYS).decode("utf-8") return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")) def load_json_line(line: str) -> dict[str, Any]: if orjson is not None: return orjson.loads(line) return json.loads(line) def join_unique(values: Iterable[Any], sep: str = "|") -> str: seen = set() out = [] for value in values: if value is None or value == "": continue text = str(value) if text not in seen: seen.add(text) out.append(text) return sep.join(out) def first_value(values: list[Any]) -> Any: return values[0] if values else None def extract_subject(row: dict[str, Any]) -> tuple[str, dict[str, Any], dict[str, Any], dict[str, Any] | None]: mutant = row.get("mutant") if mutant: return "mutant", mutant, mutant.get("sourceSequence") or {}, mutant.get("targetSequence") sequence = row.get("sequence") or {} return "sequence", sequence, sequence, None def reference_groups(protein_links: list[dict[str, Any]]) -> dict[str, list[str]]: grouped: dict[str, list[str]] = { "UNIPROTKB": [], "INTERPRO": [], "EC_NUMBER": [], "MEGASCALE": [], "OTHER": [], } for link in protein_links: protein = link.get("protein") or {} for ref in protein.get("references") or []: ref_type = as_str(ref.get("type")) accession = as_str(ref.get("accession")) if not accession: continue if ref_type in grouped: grouped[ref_type].append(accession) else: grouped["OTHER"].append(f"{ref_type}:{accession}" if ref_type else accession) return grouped def mutation_strings(subject_type: str, subject: dict[str, Any]) -> dict[str, Any]: if subject_type != "mutant": return { "mutations": "", "substitutions": "", "deletions": "", "insertions": "", "mutation_count": 0, "substitution_count": 0, "deletion_count": 0, "insertion_count": 0, "first_position": -1, "first_source_aa": "", "first_target_aa": "", } substitutions = subject.get("substitutions") or [] deletions = subject.get("deletions") or [] insertions = subject.get("insertions") or [] sub_strings = [ f"{as_str(item.get('sourceAa'))}{as_int(item.get('position'))}{as_str(item.get('targetAa'))}" for item in substitutions ] del_strings = [f"del{as_str(item.get('aminoAcids'))}{as_int(item.get('position'))}" for item in deletions] ins_strings = [f"ins{as_str(item.get('aminoAcids'))}{as_int(item.get('position'))}" for item in insertions] all_mutations = sub_strings + del_strings + ins_strings first_position = -1 first_source_aa = "" first_target_aa = "" if substitutions: first = substitutions[0] first_position = as_int(first.get("position")) first_source_aa = as_str(first.get("sourceAa")) first_target_aa = as_str(first.get("targetAa")) elif deletions: first = deletions[0] first_position = as_int(first.get("position")) first_source_aa = as_str(first.get("aminoAcids")) first_target_aa = "-" elif insertions: first = insertions[0] first_position = as_int(first.get("position")) first_source_aa = "-" first_target_aa = as_str(first.get("aminoAcids")) return { "mutations": join_unique(all_mutations), "substitutions": join_unique(sub_strings), "deletions": join_unique(del_strings), "insertions": join_unique(ins_strings), "mutation_count": len(all_mutations), "substitution_count": len(substitutions), "deletion_count": len(deletions), "insertion_count": len(insertions), "first_position": first_position, "first_source_aa": first_source_aa, "first_target_aa": first_target_aa, } def feature_values(features: list[dict[str, Any]]) -> dict[str, Any]: conservation = None types = [] for feature in features: feature_type = as_str(feature.get("type")) types.append(feature_type) if feature_type == "CONSERVATION" and conservation is None: conservation = as_float(feature.get("numValue")) return { "conservation": conservation, "feature_types": join_unique(types), "features_json": compact_json(features), } def structure_values(structures: list[dict[str, Any]]) -> dict[str, Any]: residues = [] for structure in structures: residues.extend(structure.get("residues") or []) asa_values = [as_float(residue.get("asa")) for residue in residues] bfactor_values = [as_float(residue.get("bFactor")) for residue in residues] asa_values = [value for value in asa_values if value is not None] bfactor_values = [value for value in bfactor_values if value is not None] resolutions = [as_float(structure.get("resolution")) for structure in structures] resolutions = [value for value in resolutions if value is not None] afdb_ids = [] for structure in structures: afdb = structure.get("afdb") if isinstance(afdb, dict): afdb_ids.append(afdb.get("accession") or afdb.get("id")) else: afdb_ids.append(afdb) return { "pdb_ids": join_unique(structure.get("wwpdb") for structure in structures), "afdb_ids": join_unique(afdb_ids), "structure_ids": join_unique(structure.get("id") for structure in structures), "structure_methods": join_unique(structure.get("method") for structure in structures), "structure_resolution_min": min(resolutions) if resolutions else None, "residue_positions": join_unique(residue.get("seqPosition") for residue in residues), "residue_chain_names": join_unique(residue.get("chainName") for residue in residues), "residue_secondary_structures": join_unique(residue.get("secondaryStructure") for residue in residues), "residue_in_pocket_any": any(bool(residue.get("inPocket")) for residue in residues), "residue_in_tunnel_any": any(bool(residue.get("inTunnel")) for residue in residues), "residue_asa_mean": sum(asa_values) / len(asa_values) if asa_values else None, "residue_bfactor_mean": sum(bfactor_values) / len(bfactor_values) if bfactor_values else None, } def annotation_map(annotations: list[dict[str, Any]]) -> dict[str, list[Any]]: values: dict[str, list[Any]] = {} for annotation in annotations: annotation_type = as_str(annotation.get("type")) if not annotation_type: continue value = annotation.get("strValue") if value is None: value = annotation.get("numValue") values.setdefault(annotation_type, []).append(value) return values def measurement_map(measurements: list[dict[str, Any]]) -> tuple[dict[str, list[Any]], list[str]]: values: dict[str, list[Any]] = {} datasets = [] for measurement in measurements: measurement_type = as_str(measurement.get("type")) if not measurement_type: continue value = measurement.get("numValue") if value is None: value = measurement.get("strValue") values.setdefault(measurement_type, []).append(value) datasets.extend(measurement.get("datasets") or []) return values, datasets def flatten_record(obj: dict[str, Any], source_sha: str) -> dict[str, Any]: row = obj.get("row") or {} subject_type, subject, source_sequence, target_sequence = extract_subject(row) protein_links = source_sequence.get("proteinLinks") or [] first_link = protein_links[0] if protein_links else {} first_protein = first_link.get("protein") or {} refs = reference_groups(protein_links) experiment = subject.get("experiment") or {} publication = experiment.get("publication") or {} annotations = experiment.get("annotations") or [] measurements = experiment.get("measurements") or [] features = subject.get("features") or [] structures = subject.get("structures") or [] ann = annotation_map(annotations) meas, measurement_datasets = measurement_map(measurements) flat = { "row_id": f"fireprotdb:{as_int(obj.get('row_index'))}", "dataset_id": as_str(obj.get("dataset_id") or "fireprotdb"), "source_dataset": "LiteFold/FireProtDB", "source_file": as_str(obj.get("source_file")), "source_table": SOURCE_TABLE, "source_sha": source_sha, "row_index": as_int(obj.get("row_index")), "split": "test" if stable_bucket(f"fireprotdb:{as_int(obj.get('row_index'))}") == 0 else "train", "subject_type": subject_type, "entry_id": as_int(subject.get("id")), "sequence_id": as_int(source_sequence.get("id")), "target_sequence_id": as_int((target_sequence or {}).get("id")), "source_sequence_length": as_int(source_sequence.get("length")), "target_sequence_length": as_int((target_sequence or {}).get("length")), "protein_id": as_int(first_protein.get("id")), "protein_name": as_str(first_protein.get("name")), "organism": as_str(first_protein.get("organism")), "isoform": as_int(first_link.get("isoform")), "protein_ids": join_unique((link.get("protein") or {}).get("id") for link in protein_links), "protein_names": join_unique((link.get("protein") or {}).get("name") for link in protein_links), "organisms": join_unique((link.get("protein") or {}).get("organism") for link in protein_links), "isoforms": join_unique(link.get("isoform") for link in protein_links), "uniprot_accessions": join_unique(refs["UNIPROTKB"]), "interpro_accessions": join_unique(refs["INTERPRO"]), "ec_numbers": join_unique(refs["EC_NUMBER"]), "megascale_ids": join_unique(refs["MEGASCALE"]), "other_references": join_unique(refs["OTHER"]), "experiment_id": as_int(experiment.get("id")), "experiment_dataset": as_str(experiment.get("dataset")), "ph": as_float(first_value(ann.get("PH", []))), "measure": join_unique(ann.get("MEASURE", [])), "method": join_unique(ann.get("METHOD", [])), "buffer": join_unique(ann.get("BUFFER", [])), "buffer_conc": join_unique(ann.get("BUFFER_CONC", [])), "exp_temperature": as_float(first_value(ann.get("EXP_TEMPERATURE", []))), "ion": join_unique(ann.get("ION", [])), "ion_conc": join_unique(ann.get("ION_CONC", [])), "pdb_chain_mutation": join_unique(ann.get("_PDB_CHAIN_MUTATION", [])), "dg_text": join_unique(value for value in meas.get("DG", []) if as_float(value) is None), "stabilizing_text": join_unique(value for value in meas.get("STABILIZING", []) if as_float(value) is None), "reversibility": join_unique(meas.get("REVERSIBILITY", [])), "state": join_unique(meas.get("STATE", [])), "measurement_types": join_unique(meas.keys()), "measurement_datasets": join_unique(measurement_datasets), "annotation_types": join_unique(ann.keys()), "publication_id": as_str(publication.get("id")), "publication_type": as_str(publication.get("type")), "publication_title": as_str(publication.get("title")), "publication_year": as_int(publication.get("year")), "publication_doi": as_str(publication.get("doi")), "publication_pmid": as_str(publication.get("pmid")), "publication_journal": as_str(publication.get("journal")), "publication_url": as_str(publication.get("url")), "publication_author_count": len(publication.get("authors") or []), "publication_authors": join_unique(author.get("name") for author in publication.get("authors") or []), "annotations_json": compact_json(annotations), "measurements_json": compact_json(measurements), } for measurement_type, column in COMMON_MEASUREMENTS.items(): flat[column] = as_float(first_value(meas.get(measurement_type, []))) flat.update(mutation_strings(subject_type, subject)) flat.update(feature_values(features)) flat.update(structure_values(structures)) return normalize_flat(flat) def normalize_flat(flat: dict[str, Any]) -> dict[str, Any]: normalized = {} for field in SCHEMA: value = flat.get(field.name) if value is None: if field.name in STRING_DEFAULTS: value = "" elif field.name in INT_DEFAULTS: value = -1 elif field.name in BOOL_DEFAULTS: value = False normalized[field.name] = value return normalized def write_chunk(writer: pq.ParquetWriter | None, path: Path, rows: list[dict[str, Any]]) -> pq.ParquetWriter | None: if not rows: return writer table = pa.Table.from_pylist(rows, schema=SCHEMA) if writer is None: writer = pq.ParquetWriter(path, SCHEMA, compression="zstd", use_dictionary=True) writer.write_table(table) return writer def iter_source(repo_id: str, token: str | None, input_file: Path | None) -> Iterable[str]: if input_file: with input_file.open("r", encoding="utf-8") as handle: yield from handle return fs = HfFileSystem(token=token) with fs.open(f"datasets/{repo_id}/{SOURCE_TABLE}", "rt") as handle: yield from handle def build_dataset(repo_id: str, raw_dir: Path, out_dir: Path, input_file: Path | None, chunk_size: int) -> 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) ) manifest = json.loads(manifest_path.read_text()) 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_path = data_dir / "train-00000-of-00001.parquet" test_path = data_dir / "test-00000-of-00001.parquet" train_writer = None test_writer = None train_rows: list[dict[str, Any]] = [] test_rows: list[dict[str, Any]] = [] total_rows = 0 split_counts: Counter[str] = Counter() subject_counts: Counter[str] = Counter() experiment_dataset_counts: Counter[str] = Counter() measurement_type_counts: Counter[str] = Counter() annotation_type_counts: Counter[str] = Counter() feature_type_counts: Counter[str] = Counter() mutation_event_counts: Counter[str] = Counter() try: for line in iter_source(repo_id, token, input_file): obj = load_json_line(line) row = flatten_record(obj, info.sha) total_rows += 1 split_counts[row["split"]] += 1 subject_counts[row["subject_type"]] += 1 if row["experiment_dataset"]: experiment_dataset_counts[row["experiment_dataset"]] += 1 for item in row["measurement_types"].split("|"): if item: measurement_type_counts[item] += 1 for item in row["annotation_types"].split("|"): if item: annotation_type_counts[item] += 1 for item in row["feature_types"].split("|"): if item: feature_type_counts[item] += 1 mutation_event_counts["substitutions"] += row["substitution_count"] mutation_event_counts["deletions"] += row["deletion_count"] mutation_event_counts["insertions"] += row["insertion_count"] if row["split"] == "test": test_rows.append(row) else: train_rows.append(row) if len(train_rows) >= chunk_size: train_writer = write_chunk(train_writer, train_path, train_rows) train_rows.clear() if len(test_rows) >= chunk_size: test_writer = write_chunk(test_writer, test_path, test_rows) test_rows.clear() if total_rows % 100000 == 0: print(f"processed {total_rows:,} rows", file=sys.stderr, flush=True) train_writer = write_chunk(train_writer, train_path, train_rows) test_writer = write_chunk(test_writer, test_path, test_rows) finally: if train_writer is not None: train_writer.close() if test_writer is not None: test_writer.close() expected_rows = int(manifest.get("total_rows") or 0) if expected_rows and total_rows != expected_rows: raise RuntimeError(f"Expected {expected_rows} rows from manifest, wrote {total_rows}") source_table_meta = manifest["tables"][0] new_manifest = { "dataset_id": "fireprotdb", "source_repo": repo_id, "source_sha": info.sha, "source_table": SOURCE_TABLE, "format": "flat parquet table rows", "total_rows": total_rows, "split_counts": dict(sorted(split_counts.items())), "split_strategy": "deterministic sha256('fireprotdb:{row_index}') % 10; bucket 0 is test, buckets 1-9 are train", "columns": [field.name for field in SCHEMA], "source_manifest": manifest, } (out_dir / "_MANIFEST.json").write_text(json.dumps(new_manifest, indent=2) + "\n", encoding="utf-8") summary = { "source": repo_id, "source_sha": info.sha, "source_table": SOURCE_TABLE, "source_table_rows": int(source_table_meta["rows"]), "source_table_bytes": int(source_table_meta["bytes"]), "viewer_table_scope": "flat FireProtDB experiment/mutation rows", "data_format": "parquet", "rows": total_rows, "splits": dict(sorted(split_counts.items())), "subject_type_counts": dict(sorted(subject_counts.items())), "experiment_dataset_counts": dict(experiment_dataset_counts.most_common()), "measurement_type_counts": dict(measurement_type_counts.most_common()), "annotation_type_counts": dict(annotation_type_counts.most_common()), "feature_type_counts": dict(feature_type_counts.most_common()), "mutation_event_counts": dict(sorted(mutation_event_counts.items())), "columns": [field.name for field in SCHEMA], "files": { "train": str(train_path.relative_to(out_dir)), "test": str(test_path.relative_to(out_dir)), }, } (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/FireProtDB") parser.add_argument("--raw-dir", type=Path, default=Path("LiteFold_FireProtDB_raw")) parser.add_argument("--out-dir", type=Path, default=Path("LiteFold_FireProtDB_processed")) parser.add_argument("--input-file", type=Path) parser.add_argument("--chunk-size", type=int, default=50000) args = parser.parse_args() summary = build_dataset(args.repo_id, args.raw_dir, args.out_dir, args.input_file, args.chunk_size) print(json.dumps(summary, indent=2)) if __name__ == "__main__": main()