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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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
#!/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()