anindya64 commited on
Commit
d12db90
·
verified ·
1 Parent(s): f34ff56

Add normalized Parquet train/test FLIP2 table

Browse files
README.md CHANGED
@@ -1,99 +1,93 @@
1
  ---
 
2
  license: other
3
- pretty_name: FLIP v2
4
- size_categories:
5
- - 100K<n<1M
6
- task_categories:
7
- - other
8
- language:
9
- - en
10
  tags:
11
- - biology
12
- - proteins
13
- - fitness
14
- - benchmark
15
- - flip
16
- - jsonl
 
 
 
 
 
 
 
 
17
  ---
18
 
19
- # FLIP v2
20
 
21
- FLIP v2 benchmark splits for protein engineering tasks (amylase, hydrolase, etc.), normalized to newline-delimited JSON.
22
 
23
- Processed and uploaded by the [MegaData](https://github.com/) post-download pipeline
24
- (internal repo). Original source: <https://github.com/J-SNACKKB/FLIP>.
25
 
26
- ## Statistics
27
 
28
- | | |
29
- |---|---|
30
- | Table files | 16 |
31
- | Total rows | 890,356 |
32
- | Total bytes | 440.98 MiB (462,398,539) |
33
 
34
- ## Tables
35
 
36
- | Table | Rows | Bytes |
37
- |---|---:|---:|
38
- | `data_unpacked_labeled_flip2_amylase_by_mutation.csv.jsonl` | 3,706 | 2.18 MiB |
39
- | `data_unpacked_labeled_flip2_amylase_close_to_far.csv.jsonl` | 3,706 | 2.18 MiB |
40
- | `data_unpacked_labeled_flip2_amylase_far_to_close.csv.jsonl` | 3,706 | 2.18 MiB |
41
- | `data_unpacked_labeled_flip2_amylase_one_to_many.csv.jsonl` | 3,706 | 2.18 MiB |
42
- | `data_unpacked_labeled_flip2_hydro_low_to_high.csv.jsonl` | 24,935 | 6.02 MiB |
43
- | `data_unpacked_labeled_flip2_hydro_three_to_many.csv.jsonl` | 24,935 | 6.06 MiB |
44
- | `data_unpacked_labeled_flip2_hydro_to_P01053.csv.jsonl` | 24,935 | 5.98 MiB |
45
- | `data_unpacked_labeled_flip2_hydro_to_P06241.csv.jsonl` | 24,935 | 5.97 MiB |
46
- | `data_unpacked_labeled_flip2_hydro_to_P0A9X9.csv.jsonl` | 24,935 | 5.98 MiB |
47
- | `data_unpacked_labeled_flip2_ired_two_to_many.csv.jsonl` | 8,586 | 3.95 MiB |
48
- | `data_unpacked_labeled_flip2_nucb_two_to_many.csv.jsonl` | 55,759 | 16.85 MiB |
49
- | `data_unpacked_labeled_flip2_pdz3_single_to_double.csv.jsonl` | 734 | 213.50 KiB |
50
- | `data_unpacked_labeled_flip2_rhomax_by_wild_type.csv.jsonl` | 884 | 389.02 KiB |
51
- | `data_unpacked_labeled_flip2_trpb_by_position.csv.jsonl` | 228,298 | 126.97 MiB |
52
- | `data_unpacked_labeled_flip2_trpb_one_to_many.csv.jsonl` | 228,298 | 126.94 MiB |
53
- | `data_unpacked_labeled_flip2_trpb_two_to_many.csv.jsonl` | 228,298 | 126.95 MiB |
54
 
55
- ## Layout
56
 
57
- ```
58
- .
59
- ├── _MANIFEST.json # aggregate manifest (per-table counts)
60
- └── tables/<source_slug>.jsonl # normalized rows (one JSON object per line)
61
- ```
62
 
63
- Each line in a `tables/*.jsonl` file is a JSON object with at least
64
- `dataset_id`, `row` (the raw upstream row), `row_index`, and `source_file`
65
- fields, so every row carries its upstream provenance.
66
 
67
- ## Loading
68
 
69
- ```bash
70
- hf download LiteFold/FLIP2 --repo-type dataset --local-dir ./flip2
 
 
 
 
71
  ```
72
 
73
- Programmatic streaming:
74
 
75
  ```python
76
- import json
77
- from pathlib import Path
78
- from huggingface_hub import snapshot_download
79
-
80
- local = snapshot_download(repo_id="LiteFold/FLIP2", repo_type="dataset")
81
- for jsonl in sorted(Path(local, "tables").glob("*.jsonl")):
82
- with jsonl.open() as f:
83
- for line in f:
84
- row = json.loads(line)
85
- ... # row["row"] is the upstream record
86
  ```
87
 
88
- ## License
89
 
90
- See upstream FLIP repository for licensing.
 
 
 
 
 
91
 
92
- ## Citation
93
 
94
- > Dallago C, et al. FLIP: Benchmark tasks in fitness landscape inference for proteins. NeurIPS Datasets and Benchmarks, 2021.
 
 
 
 
 
 
 
 
 
 
 
 
 
95
 
96
- ## Provenance
97
 
98
- Built from the local manifest entry `flip2` of `manifests/atlas_download_plan.json`.
99
- Pipeline source: `megadata-post normalize --dataset flip2 --tables-only`.
 
1
  ---
2
+ pretty_name: FLIP2 Protein Benchmark Tasks
3
  license: other
 
 
 
 
 
 
 
4
  tags:
5
+ - biology
6
+ - protein
7
+ - benchmark
8
+ - protein-engineering
9
+ - flip
10
+ - flip2
11
+ - parquet
12
+ configs:
13
+ - config_name: default
14
+ data_files:
15
+ - split: train
16
+ path: data/train-*.parquet
17
+ - split: test
18
+ path: data/test-*.parquet
19
  ---
20
 
21
+ # LiteFold/FLIP2
22
 
23
+ This repository now includes a Dataset Viewer-friendly Parquet version of the LiteFold FLIP2 tables. The default `load_dataset()` configuration reads the normalized Parquet files in `data/`.
24
 
25
+ The normalized table contains 890,356 rows from 16 source tables. The original wrapped JSONL source tables remain available in the repository under `tables/`.
 
26
 
27
+ ## Splits
28
 
29
+ - `train`: 801,710 rows
30
+ - `test`: 88,646 rows
 
 
 
31
 
32
+ Rows are assigned with a deterministic hash split: `sha256(record_id) % 10`, where bucket `0` is test and buckets `1-9` are train.
33
 
34
+ ## Columns
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
+ The table includes common browsing and modeling columns:
37
 
38
+ - `record_id`: stable SHA-256 row identifier
39
+ - `dataset_id`, `source_file`, `source_table`, `source_row_index`: source provenance
40
+ - `task_name`, `subtask_name`, `assay_name`: FLIP2 task metadata
41
+ - `sequence`, `sequence_length`, `target`, `score_value`, `label`: normalized convenience fields
42
+ - `split_bucket`: deterministic split bucket
43
 
44
+ The original FLIP2 fields are preserved as snake_case string columns: `raw_sequence`, `set`, `raw_target`, and `validation`. See `metadata/column_mapping.parquet` for the original field-name mapping and `metadata/source_tables.parquet` for per-table row counts.
 
 
45
 
46
+ ## Usage
47
 
48
+ ```python
49
+ from datasets import load_dataset
50
+
51
+ ds = load_dataset("LiteFold/FLIP2")
52
+ print(ds)
53
+ print(ds["train"][0])
54
  ```
55
 
56
+ Load only the common columns:
57
 
58
  ```python
59
+ from datasets import load_dataset
60
+
61
+ cols = ["record_id", "task_name", "subtask_name", "sequence", "score_value", "label"]
62
+ train = load_dataset("LiteFold/FLIP2", split="train", columns=cols)
 
 
 
 
 
 
63
  ```
64
 
65
+ Filter to a task:
66
 
67
+ ```python
68
+ from datasets import load_dataset
69
+
70
+ train = load_dataset("LiteFold/FLIP2", split="train")
71
+ trpb = train.filter(lambda row: row["task_name"] == "trpb")
72
+ ```
73
 
74
+ Metadata tables can be loaded directly:
75
 
76
+ ```python
77
+ from datasets import load_dataset
78
+
79
+ source_tables = load_dataset(
80
+ "parquet",
81
+ data_files="hf://datasets/LiteFold/FLIP2/metadata/source_tables.parquet",
82
+ split="train",
83
+ )
84
+ column_mapping = load_dataset(
85
+ "parquet",
86
+ data_files="hf://datasets/LiteFold/FLIP2/metadata/column_mapping.parquet",
87
+ split="train",
88
+ )
89
+ ```
90
 
91
+ ## Rebuild
92
 
93
+ The normalization script used for this upload is included at `scripts/prepare_wrapped_jsonl_dataset.py`.
 
data/test-00000-of-00001.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c3e4201ca13592606e5811d1f104905785576d93f2e90823e0c36ff9a58902ea
3
+ size 6345516
data/train-00000-of-00005.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e22bb1703d76bdab971e8befa11f3343ead1619020a3815fbf15c7229aa5830b
3
+ size 12373803
data/train-00001-of-00005.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:457cc347c6154b089cf9d0f5b5378f3239bab2ad3201ce227c131b267d11c851
3
+ size 13782811
data/train-00002-of-00005.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ec866a27afd26d807545390b4c8dc5c024c7ce5710f4f1f1e9c1dc59fd09ea2a
3
+ size 13774715
data/train-00003-of-00005.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ca71f92bf77e62428f2a3688222cbebf4b19a98cffe886f97d85530dc5aa3bf1
3
+ size 13785411
data/train-00004-of-00005.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dff9c5cebb1c9a7a6960a3f4eb5ca3061b0c625e876fdc178381fda9ab581e9c
3
+ size 135341
dataset_summary.json ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "source": "LiteFold/FLIP2",
3
+ "mode": "flip2",
4
+ "source_table_rows": 16,
5
+ "entry_rows": 890356,
6
+ "raw_field_count": 4,
7
+ "splits": {
8
+ "train": 801710,
9
+ "test": 88646
10
+ },
11
+ "split_strategy": "deterministic sha256(record_id) % 10; bucket 0 is test, buckets 1-9 are train",
12
+ "table_group_counts": {
13
+ "hydro": 5,
14
+ "amylase": 4,
15
+ "trpb": 3,
16
+ "ired": 1,
17
+ "nucb": 1,
18
+ "pdz3": 1,
19
+ "rhomax": 1
20
+ },
21
+ "columns": [
22
+ "record_id",
23
+ "dataset_id",
24
+ "source_file",
25
+ "source_table",
26
+ "source_row_index",
27
+ "table_group",
28
+ "task_name",
29
+ "subtask_name",
30
+ "entity_type",
31
+ "assay_name",
32
+ "sequence",
33
+ "sequence_length",
34
+ "mutation",
35
+ "target",
36
+ "score_value",
37
+ "label",
38
+ "split_bucket",
39
+ "raw_sequence",
40
+ "set",
41
+ "raw_target",
42
+ "validation"
43
+ ],
44
+ "metadata_tables": [
45
+ "metadata/source_tables.parquet",
46
+ "metadata/column_mapping.parquet"
47
+ ]
48
+ }
metadata/column_mapping.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:589d18aa0209b05ca2bdffd222684ac99038e329973296f3da40ac454bdf9bd9
3
+ size 1798
metadata/source_tables.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b93cdbb6a3e0d0c6d4ffa9c80fcace128d2f94a05be95ced59e8a8166ffcb8f7
3
+ size 4464
scripts/prepare_wrapped_jsonl_dataset.py ADDED
@@ -0,0 +1,416 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Build viewer-friendly Parquet splits for LiteFold wrapped JSONL table repos."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import hashlib
8
+ import json
9
+ import os
10
+ import re
11
+ import shutil
12
+ from collections import Counter
13
+ from pathlib import Path
14
+ from typing import Any, Iterable
15
+
16
+ import pyarrow as pa
17
+ import pyarrow.parquet as pq
18
+ import pandas as pd
19
+ from huggingface_hub import HfApi, hf_hub_download
20
+
21
+
22
+ BASE_COLUMNS = [
23
+ "record_id",
24
+ "dataset_id",
25
+ "source_file",
26
+ "source_table",
27
+ "source_row_index",
28
+ "table_group",
29
+ "task_name",
30
+ "subtask_name",
31
+ "entity_type",
32
+ "assay_name",
33
+ "sequence",
34
+ "sequence_length",
35
+ "mutation",
36
+ "target",
37
+ "score_value",
38
+ "label",
39
+ "split_bucket",
40
+ ]
41
+
42
+
43
+ def load_token() -> str | None:
44
+ for key in ("HF_TOKEN", "HUGGINGFACE_HUB_TOKEN"):
45
+ value = os.environ.get(key)
46
+ if value:
47
+ return value
48
+ env_path = Path(".env")
49
+ if env_path.exists():
50
+ for line in env_path.read_text().splitlines():
51
+ stripped = line.strip()
52
+ if not stripped or stripped.startswith("#") or "=" not in stripped:
53
+ continue
54
+ key, value = stripped.split("=", 1)
55
+ if key.strip() in {"HF_TOKEN", "HUGGINGFACE_HUB_TOKEN"}:
56
+ value = value.strip().strip('"').strip("'")
57
+ if value:
58
+ return value
59
+ return None
60
+
61
+
62
+ def stable_bucket(value: str, buckets: int = 10) -> int:
63
+ digest = hashlib.sha256(value.encode("utf-8")).hexdigest()[:16]
64
+ return int(digest, 16) % buckets
65
+
66
+
67
+ def normalize_name(name: str) -> str:
68
+ normalized = re.sub(r"[^0-9A-Za-z]+", "_", name).strip("_").lower()
69
+ if not normalized:
70
+ normalized = "field"
71
+ if normalized[0].isdigit():
72
+ normalized = f"x_{normalized}"
73
+ return normalized
74
+
75
+
76
+ def unique_names(keys: Iterable[str]) -> dict[str, str]:
77
+ mapping: dict[str, str] = {}
78
+ used: Counter[str] = Counter()
79
+ for key in sorted(keys):
80
+ base = normalize_name(key)
81
+ candidate = base
82
+ if candidate in BASE_COLUMNS:
83
+ candidate = f"raw_{candidate}"
84
+ used[candidate] += 1
85
+ if used[candidate] > 1:
86
+ candidate = f"{candidate}_{used[candidate]}"
87
+ mapping[key] = candidate
88
+ return mapping
89
+
90
+
91
+ def scalar_string(value: Any) -> str | None:
92
+ if value is None or value == "":
93
+ return None
94
+ if isinstance(value, (dict, list)):
95
+ return json.dumps(value, sort_keys=True, ensure_ascii=False)
96
+ return str(value)
97
+
98
+
99
+ def parse_float(value: Any) -> float | None:
100
+ if value is None or value == "":
101
+ return None
102
+ try:
103
+ return float(value)
104
+ except (TypeError, ValueError):
105
+ return None
106
+
107
+
108
+ def first_present(row: dict[str, Any], keys: list[str]) -> Any:
109
+ for key in keys:
110
+ value = row.get(key)
111
+ if value is not None and value != "":
112
+ return value
113
+ return None
114
+
115
+
116
+ def table_path_from_manifest(output_file: str) -> str:
117
+ prefix = "data/processed/"
118
+ if output_file.startswith(prefix):
119
+ parts = output_file.split("/tables/", 1)
120
+ if len(parts) == 2:
121
+ return "tables/" + parts[1]
122
+ return output_file
123
+
124
+
125
+ def get_table_files(repo_id: str, mode: str, raw_dir: Path, token: str | None) -> tuple[list[str], list[dict[str, Any]]]:
126
+ manifest_path = Path(
127
+ hf_hub_download(repo_id=repo_id, repo_type="dataset", filename="_MANIFEST.json", local_dir=raw_dir, token=token)
128
+ )
129
+ manifest = json.loads(manifest_path.read_text())
130
+ manifest_tables = manifest.get("tables") or []
131
+ if manifest_tables:
132
+ table_paths = [table_path_from_manifest(item["output_file"]) for item in manifest_tables]
133
+ else:
134
+ api = HfApi(token=token)
135
+ info = api.dataset_info(repo_id, files_metadata=True)
136
+ table_paths = [s.rfilename for s in info.siblings or [] if s.rfilename.startswith("tables/")]
137
+ manifest_tables = []
138
+
139
+ if mode == "cycpeptmpdb":
140
+ table_paths = [
141
+ path for path in table_paths if path.endswith("_Peptide_All.csv.jsonl") or path.endswith("_Monomer_All.csv.jsonl")
142
+ ]
143
+ if mode == "proteingym":
144
+ table_paths = [path for path in table_paths if ".ipynb_checkpoints" not in path]
145
+ return sorted(set(table_paths)), manifest_tables
146
+
147
+
148
+ def classify(mode: str, source_file: str, source_table: str) -> dict[str, Any]:
149
+ source_parts = Path(source_file).parts
150
+ basename = Path(source_file).name.removesuffix(".csv")
151
+ if mode == "proteingym":
152
+ lower = source_file.lower()
153
+ if "indels" in lower:
154
+ table_group = "indels"
155
+ elif "substitutions" in lower:
156
+ table_group = "substitutions"
157
+ elif "clinical" in lower:
158
+ table_group = "clinical"
159
+ else:
160
+ table_group = "other"
161
+ if "raw_dms" in lower:
162
+ task_name = "DMS"
163
+ elif "clinical" in lower:
164
+ task_name = "clinical"
165
+ else:
166
+ task_name = None
167
+ return {
168
+ "table_group": table_group,
169
+ "task_name": task_name,
170
+ "subtask_name": None,
171
+ "entity_type": "variant",
172
+ "assay_name": basename,
173
+ }
174
+ if mode == "flip2":
175
+ task_name = source_parts[-2] if len(source_parts) >= 2 else None
176
+ return {
177
+ "table_group": "benchmark",
178
+ "task_name": task_name,
179
+ "subtask_name": basename,
180
+ "entity_type": "sequence",
181
+ "assay_name": f"{task_name}/{basename}" if task_name else basename,
182
+ }
183
+ if mode == "cycpeptmpdb":
184
+ entity_type = "peptide" if "Peptide" in basename else "monomer" if "Monomer" in basename else None
185
+ return {
186
+ "table_group": "all",
187
+ "task_name": "CycPeptMPDB",
188
+ "subtask_name": basename,
189
+ "entity_type": entity_type,
190
+ "assay_name": basename,
191
+ }
192
+ return {"table_group": None, "task_name": None, "subtask_name": None, "entity_type": None, "assay_name": basename}
193
+
194
+
195
+ def derived_values(mode: str, wrapper: dict[str, Any]) -> dict[str, Any]:
196
+ row = wrapper.get("row") or {}
197
+ source_file = wrapper.get("source_file") or ""
198
+ source_table = wrapper.get("_source_table") or ""
199
+ source_row_index = wrapper.get("row_index")
200
+ record_seed = f"{source_file}|{source_row_index}|{json.dumps(row, sort_keys=True, ensure_ascii=False)}"
201
+ record_id = hashlib.sha256(record_seed.encode("utf-8")).hexdigest()
202
+ derived = {
203
+ "record_id": record_id,
204
+ "dataset_id": wrapper.get("dataset_id"),
205
+ "source_file": source_file,
206
+ "source_table": source_table,
207
+ "source_row_index": int(source_row_index) if source_row_index is not None else None,
208
+ "split_bucket": stable_bucket(record_id),
209
+ }
210
+ derived.update(classify(mode, source_file, source_table))
211
+
212
+ sequence = first_present(
213
+ row,
214
+ [
215
+ "mutated_sequence",
216
+ "mutant_sequence",
217
+ "sequence",
218
+ "Sequence",
219
+ "aa_seq",
220
+ "aa_seq_full",
221
+ "wildtype_sequence",
222
+ "WT_sequence",
223
+ ],
224
+ )
225
+ target = first_present(row, ["target", "DMS_score", "fitness", "score", "Permeability", "deltaG", "dG_ML"])
226
+ score_value = None
227
+ for key in ["target", "DMS_score", "fitness", "score", "Permeability", "deltaG", "dG_ML", "ddG_ML", "Caco2", "PAMPA", "MDCK", "RRCK"]:
228
+ score_value = parse_float(row.get(key))
229
+ if score_value is not None:
230
+ break
231
+ mutation = first_present(row, ["mutant", "mutation", "mutations", "name", "mut_class", "ID", "id"])
232
+ label = first_present(row, ["DMS_score_bin", "label", "set", "validation", "class", "mut_type", "Molecule_Shape"])
233
+
234
+ derived.update(
235
+ {
236
+ "sequence": scalar_string(sequence),
237
+ "sequence_length": len(str(sequence)) if sequence is not None else None,
238
+ "mutation": scalar_string(mutation),
239
+ "target": scalar_string(target),
240
+ "score_value": score_value,
241
+ "label": scalar_string(label),
242
+ }
243
+ )
244
+ return derived
245
+
246
+
247
+ def iter_wrappers(path: Path, source_table: str) -> Iterable[dict[str, Any]]:
248
+ with path.open("r", encoding="utf-8", errors="replace") as handle:
249
+ for line in handle:
250
+ if not line.strip():
251
+ continue
252
+ item = json.loads(line)
253
+ item["_source_table"] = source_table
254
+ yield item
255
+
256
+
257
+ def download_tables(repo_id: str, table_paths: list[str], raw_dir: Path, token: str | None) -> list[Path]:
258
+ paths = []
259
+ for index, table_path in enumerate(table_paths, start=1):
260
+ local = Path(hf_hub_download(repo_id=repo_id, repo_type="dataset", filename=table_path, local_dir=raw_dir, token=token))
261
+ paths.append(local)
262
+ if index == 1 or index % 25 == 0 or index == len(table_paths):
263
+ print(f"downloaded {index}/{len(table_paths)} {table_path}", flush=True)
264
+ return paths
265
+
266
+
267
+ def write_split_shards(
268
+ out_dir: Path,
269
+ rows_iter: Iterable[dict[str, Any]],
270
+ schema: pa.Schema,
271
+ chunk_rows: int,
272
+ ) -> dict[str, int]:
273
+ data_dir = out_dir / "data"
274
+ data_dir.mkdir(parents=True, exist_ok=True)
275
+ buffers: dict[str, list[dict[str, Any]]] = {"train": [], "test": []}
276
+ counts = {"train": 0, "test": 0}
277
+ shard_counts = {"train": 0, "test": 0}
278
+
279
+ def flush(split: str) -> None:
280
+ if not buffers[split]:
281
+ return
282
+ shard = shard_counts[split]
283
+ path = data_dir / f"{split}-{shard:05d}-of-XXXXX.parquet"
284
+ table = pa.Table.from_pylist(buffers[split], schema=schema)
285
+ pq.write_table(table, path, compression="zstd")
286
+ counts[split] += len(buffers[split])
287
+ shard_counts[split] += 1
288
+ buffers[split].clear()
289
+
290
+ for row in rows_iter:
291
+ split = "test" if row["split_bucket"] == 0 else "train"
292
+ buffers[split].append(row)
293
+ if len(buffers[split]) >= chunk_rows:
294
+ flush(split)
295
+ flush("train")
296
+ flush("test")
297
+
298
+ for split in ["train", "test"]:
299
+ total = shard_counts[split]
300
+ for path in sorted(data_dir.glob(f"{split}-*-of-XXXXX.parquet")):
301
+ new_name = path.name.replace("of-XXXXX", f"of-{total:05d}")
302
+ path.rename(path.with_name(new_name))
303
+ return counts
304
+
305
+
306
+ def build_dataset(repo_id: str, mode: str, raw_dir: Path, out_dir: Path, chunk_rows: int) -> dict[str, Any]:
307
+ token = load_token()
308
+ raw_dir.mkdir(parents=True, exist_ok=True)
309
+ table_paths, manifest_tables = get_table_files(repo_id, mode, raw_dir, token)
310
+ local_paths = download_tables(repo_id, table_paths, raw_dir, token)
311
+
312
+ raw_keys: set[str] = set()
313
+ table_stats: list[dict[str, Any]] = []
314
+ total_rows = 0
315
+ for source_table, local_path in zip(table_paths, local_paths):
316
+ rows = 0
317
+ dataset_id = None
318
+ source_file = None
319
+ for wrapper in iter_wrappers(local_path, source_table):
320
+ row = wrapper.get("row") or {}
321
+ raw_keys.update(row.keys())
322
+ rows += 1
323
+ dataset_id = wrapper.get("dataset_id")
324
+ source_file = wrapper.get("source_file")
325
+ total_rows += rows
326
+ table_stats.append(
327
+ {
328
+ "source_table": source_table,
329
+ "source_file": source_file,
330
+ "dataset_id": dataset_id,
331
+ "rows": rows,
332
+ "size_bytes": local_path.stat().st_size,
333
+ }
334
+ )
335
+ print(f"scanned {source_table}: {rows} rows", flush=True)
336
+
337
+ raw_mapping = unique_names(raw_keys)
338
+ raw_columns = [raw_mapping[key] for key in sorted(raw_mapping)]
339
+ schema_fields = [
340
+ pa.field("record_id", pa.string()),
341
+ pa.field("dataset_id", pa.string()),
342
+ pa.field("source_file", pa.string()),
343
+ pa.field("source_table", pa.string()),
344
+ pa.field("source_row_index", pa.int64()),
345
+ pa.field("table_group", pa.string()),
346
+ pa.field("task_name", pa.string()),
347
+ pa.field("subtask_name", pa.string()),
348
+ pa.field("entity_type", pa.string()),
349
+ pa.field("assay_name", pa.string()),
350
+ pa.field("sequence", pa.string()),
351
+ pa.field("sequence_length", pa.int64()),
352
+ pa.field("mutation", pa.string()),
353
+ pa.field("target", pa.string()),
354
+ pa.field("score_value", pa.float64()),
355
+ pa.field("label", pa.string()),
356
+ pa.field("split_bucket", pa.int64()),
357
+ ] + [pa.field(column, pa.string()) for column in raw_columns]
358
+ schema = pa.schema(schema_fields)
359
+
360
+ if out_dir.exists():
361
+ shutil.rmtree(out_dir)
362
+ out_dir.mkdir(parents=True, exist_ok=True)
363
+
364
+ def row_iter() -> Iterable[dict[str, Any]]:
365
+ emitted = 0
366
+ for source_table, local_path in zip(table_paths, local_paths):
367
+ for wrapper in iter_wrappers(local_path, source_table):
368
+ raw = wrapper.get("row") or {}
369
+ row = {column: None for column in BASE_COLUMNS + raw_columns}
370
+ row.update(derived_values(mode, wrapper))
371
+ for original_key, column in raw_mapping.items():
372
+ row[column] = scalar_string(raw.get(original_key))
373
+ emitted += 1
374
+ if emitted % 250000 == 0:
375
+ print(f"prepared {emitted}/{total_rows} rows", flush=True)
376
+ yield row
377
+
378
+ split_counts = write_split_shards(out_dir, row_iter(), schema, chunk_rows)
379
+
380
+ metadata_dir = out_dir / "metadata"
381
+ metadata_dir.mkdir(parents=True, exist_ok=True)
382
+ pd.DataFrame.from_records(table_stats).to_parquet(metadata_dir / "source_tables.parquet", index=False, compression="zstd")
383
+ pd.DataFrame.from_records(
384
+ [{"raw_key": key, "column": raw_mapping[key]} for key in sorted(raw_mapping)]
385
+ ).to_parquet(metadata_dir / "column_mapping.parquet", index=False, compression="zstd")
386
+
387
+ summary = {
388
+ "source": repo_id,
389
+ "mode": mode,
390
+ "source_table_rows": len(table_stats),
391
+ "entry_rows": int(total_rows),
392
+ "raw_field_count": len(raw_columns),
393
+ "splits": split_counts,
394
+ "split_strategy": "deterministic sha256(record_id) % 10; bucket 0 is test, buckets 1-9 are train",
395
+ "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()),
396
+ "columns": BASE_COLUMNS + raw_columns,
397
+ "metadata_tables": ["metadata/source_tables.parquet", "metadata/column_mapping.parquet"],
398
+ }
399
+ (out_dir / "dataset_summary.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8")
400
+ return summary
401
+
402
+
403
+ def main() -> None:
404
+ parser = argparse.ArgumentParser()
405
+ parser.add_argument("--repo-id", required=True)
406
+ parser.add_argument("--mode", required=True, choices=["proteingym", "flip2", "cycpeptmpdb"])
407
+ parser.add_argument("--raw-dir", type=Path, required=True)
408
+ parser.add_argument("--out-dir", type=Path, required=True)
409
+ parser.add_argument("--chunk-rows", type=int, default=200000)
410
+ args = parser.parse_args()
411
+ summary = build_dataset(args.repo_id, args.mode, args.raw_dir, args.out_dir, args.chunk_rows)
412
+ print(json.dumps(summary, indent=2))
413
+
414
+
415
+ if __name__ == "__main__":
416
+ main()