#!/usr/bin/env python3 """Build viewer-friendly sample/index Parquet splits for LiteFold/GOA.""" from __future__ import annotations import argparse import gzip import hashlib import json import os import shutil from pathlib import Path from typing import Any import pandas as pd import requests from huggingface_hub import HfApi, hf_hub_url ANNOTATION_COLUMNS = [ "annotation_id", "source_file", "source_format", "source_row_number", "db", "db_object_id", "db_object_symbol", "qualifier", "qualifiers", "go_id", "db_references", "evidence_code", "with_from", "aspect", "db_object_name", "db_object_synonyms", "db_object_type", "taxon_ids", "interacting_taxon_id", "date", "assigned_by", "annotation_extension", "gene_product_form_id", "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 split_pipe(value: str | None) -> list[str]: if not value: return [] return [part for part in value.split("|") if part] def make_annotation_id(parts: list[str], source_file: str, row_number: int) -> str: seed = "|".join([source_file, str(row_number), *parts]) return hashlib.sha256(seed.encode("utf-8")).hexdigest() def parse_gaf(parts: list[str], source_file: str, row_number: int) -> dict[str, Any] | None: if len(parts) < 17: return None annotation_id = make_annotation_id(parts, source_file, row_number) return { "annotation_id": annotation_id, "source_file": source_file, "source_format": "GAF", "source_row_number": row_number, "db": parts[0], "db_object_id": parts[1], "db_object_symbol": parts[2], "qualifier": parts[3] or None, "qualifiers": split_pipe(parts[3]), "go_id": parts[4], "db_references": split_pipe(parts[5]), "evidence_code": parts[6], "with_from": split_pipe(parts[7]), "aspect": parts[8] or None, "db_object_name": parts[9] or None, "db_object_synonyms": split_pipe(parts[10]), "db_object_type": parts[11] or None, "taxon_ids": split_pipe(parts[12]), "interacting_taxon_id": None, "date": parts[13] or None, "assigned_by": parts[14] or None, "annotation_extension": parts[15] or None, "gene_product_form_id": parts[16] or None, "split_bucket": stable_bucket(annotation_id), } def parse_gpa(parts: list[str], source_file: str, row_number: int) -> dict[str, Any] | None: if len(parts) < 12: return None annotation_id = make_annotation_id(parts, source_file, row_number) return { "annotation_id": annotation_id, "source_file": source_file, "source_format": "GPA", "source_row_number": row_number, "db": parts[0], "db_object_id": parts[1], "db_object_symbol": None, "qualifier": parts[2] or None, "qualifiers": split_pipe(parts[2]), "go_id": parts[3], "db_references": split_pipe(parts[4]), "evidence_code": parts[5], "with_from": split_pipe(parts[6]), "aspect": None, "db_object_name": None, "db_object_synonyms": [], "db_object_type": None, "taxon_ids": [], "interacting_taxon_id": parts[7] or None, "date": parts[8] or None, "assigned_by": parts[9] or None, "annotation_extension": parts[10] or None, "gene_product_form_id": parts[11] or None, "split_bucket": stable_bucket(annotation_id), } def stream_rows(repo_id: str, filename: str, token: str | None, limit: int) -> tuple[list[dict[str, Any]], dict[str, str]]: url = hf_hub_url(repo_id=repo_id, filename=filename, repo_type="dataset") headers = {"Authorization": f"Bearer {token}"} if token else {} rows: list[dict[str, Any]] = [] metadata: dict[str, str] = {} row_number = 0 parser = parse_gaf if filename.endswith(".gaf.gz") else parse_gpa with requests.get(url, headers=headers, stream=True, timeout=60) as response: response.raise_for_status() with gzip.GzipFile(fileobj=response.raw) as handle: for raw in handle: line = raw.decode("utf-8", errors="replace").rstrip("\n") if not line: continue if line.startswith("!"): if ":" in line: key, value = line.lstrip("!").split(":", 1) metadata[key.strip()] = value.strip() continue if line.startswith("gpa-version:"): metadata["gpa-version"] = line.split(":", 1)[1].strip() continue row_number += 1 parsed = parser(line.split("\t"), filename, row_number) if parsed is not None: rows.append(parsed) if len(rows) >= limit: break return rows, metadata def build_dataset(repo_id: str, out_dir: Path, sample_rows_per_file: int) -> dict[str, Any]: token = load_token() api = HfApi(token=token) info = api.dataset_info(repo_id, files_metadata=True) source_files = [] for sibling in sorted(info.siblings or [], key=lambda item: item.rfilename): source_files.append( { "repo_id": repo_id, "filename": sibling.rfilename, "size_bytes": int(getattr(sibling, "size", 0) or 0), "source_sha": info.sha, } ) annotation_rows: list[dict[str, Any]] = [] source_metadata: list[dict[str, Any]] = [] for filename in ["goa_uniprot_all.gaf.gz", "goa_uniprot_all.gpa.gz"]: rows, metadata = stream_rows(repo_id, filename, token, sample_rows_per_file) annotation_rows.extend(rows) source_metadata.append({"filename": filename, "sampled_rows": len(rows), "header_metadata": metadata}) 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) df = pd.DataFrame.from_records(annotation_rows, columns=ANNOTATION_COLUMNS) df = df.sort_values(["split_bucket", "annotation_id"], kind="mergesort") train = df[df["split_bucket"].ne(0)].sort_values("annotation_id", kind="mergesort") test = df[df["split_bucket"].eq(0)].sort_values("annotation_id", kind="mergesort") train.to_parquet(data_dir / "train-00000-of-00001.parquet", index=False, compression="zstd") test.to_parquet(data_dir / "test-00000-of-00001.parquet", index=False, compression="zstd") pd.DataFrame.from_records(source_files).to_parquet(metadata_dir / "source_files.parquet", index=False) format_counts = df["source_format"].value_counts().to_dict() aspect_counts = df["aspect"].fillna("missing").value_counts().to_dict() evidence_counts = df["evidence_code"].value_counts().head(20).to_dict() db_counts = df["db"].value_counts().to_dict() summary = { "source": repo_id, "source_sha": info.sha, "viewer_table_scope": "sample/index", "sample_rows_per_annotation_file": int(sample_rows_per_file), "annotation_sample_rows": int(len(df)), "splits": {"train": int(len(train)), "test": int(len(test))}, "split_strategy": "deterministic sha256(annotation_id) % 10; bucket 0 is test, buckets 1-9 are train", "source_files": source_files, "source_metadata": source_metadata, "format_counts": {str(k): int(v) for k, v in format_counts.items()}, "aspect_counts": {str(k): int(v) for k, v in aspect_counts.items()}, "top_evidence_codes": {str(k): int(v) for k, v in evidence_counts.items()}, "db_counts": {str(k): int(v) for k, v in db_counts.items()}, "columns": ANNOTATION_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/GOA") parser.add_argument("--out-dir", type=Path, default=Path("LiteFold_GOA_processed")) parser.add_argument("--sample-rows-per-file", type=int, default=50000) args = parser.parse_args() summary = build_dataset(args.repo_id, args.out_dir, args.sample_rows_per_file) print(json.dumps(summary, indent=2)) if __name__ == "__main__": main()