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(Parquet shards) for the Blog domain.
|
| 3 |
+
|
| 4 |
+
Input
|
| 5 |
+
-----
|
| 6 |
+
``data_*.zst``: zstd-compressed JSON arrays. Each element is one individual
|
| 7 |
+
with fields ``observations`` (list[str]), ``predictions`` (list of
|
| 8 |
+
``{question, ground_truth}``), ``data_source`` (str), ``split`` (str), and
|
| 9 |
+
``extra_info`` (dict). The upstream split label is ignored — this script
|
| 10 |
+
re-derives train / val / test deterministically.
|
| 11 |
+
|
| 12 |
+
Output
|
| 13 |
+
------
|
| 14 |
+
``<output-dir>/<split>-00000-of-00001.parquet`` for split in {train, val, test}.
|
| 15 |
+
|
| 16 |
+
Per-row schema
|
| 17 |
+
~~~~~~~~~~~~~~
|
| 18 |
+
::
|
| 19 |
+
|
| 20 |
+
observations: list[str]
|
| 21 |
+
predictions: list[{question, ground_truth}]
|
| 22 |
+
data_source: str ("Blog Authorship Corpus")
|
| 23 |
+
split: str ("train" | "val" | "test")
|
| 24 |
+
held_out_predictions: list[{question, ground_truth}] # train only; absent on val/test
|
| 25 |
+
extra_info: {interview_id, n_observations, n_predictions, [n_held_out_predictions]}
|
| 26 |
+
|
| 27 |
+
Selection / split policy
|
| 28 |
+
~~~~~~~~~~~~~~~~~~~~~~~~
|
| 29 |
+
* Drop individuals with fewer than ``MIN_OBSERVATIONS`` observations.
|
| 30 |
+
* If observations exceed ``MAX_OBSERVATIONS``, deterministically subsample.
|
| 31 |
+
* Per individual, shuffle predictions with ``SEED + interview_id`` and split
|
| 32 |
+
~2/3 -> ``predictions`` and ~1/3 -> ``held_out``.
|
| 33 |
+
* Drop individuals with fewer than ``MIN_PREDICTIONS`` predictions or fewer
|
| 34 |
+
than ``MIN_HELD_OUT`` held-out items.
|
| 35 |
+
* Globally shuffle qualified individuals with ``SEED`` and assign 90/5/5
|
| 36 |
+
to train/val/test.
|
| 37 |
+
* For val/test, the held-out slice is folded into ``predictions`` so the eval
|
| 38 |
+
pool is the union; the ``held_out_predictions`` field is dropped.
|
| 39 |
+
|
| 40 |
+
Self-contained: depends only on ``pyarrow`` (+ ``zstd`` binary on PATH).
|
| 41 |
+
No chiron imports.
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
from __future__ import annotations
|
| 45 |
+
|
| 46 |
+
import argparse
|
| 47 |
+
import json
|
| 48 |
+
import random
|
| 49 |
+
import subprocess
|
| 50 |
+
from dataclasses import dataclass
|
| 51 |
+
from pathlib import Path
|
| 52 |
+
from typing import Any, Iterator
|
| 53 |
+
|
| 54 |
+
import pyarrow as pa
|
| 55 |
+
import pyarrow.parquet as pq
|
| 56 |
+
|
| 57 |
+
# --- fixed policy -----------------------------------------------------------
|
| 58 |
+
SEED = 42
|
| 59 |
+
|
| 60 |
+
MIN_OBSERVATIONS = 20
|
| 61 |
+
MAX_OBSERVATIONS = 200
|
| 62 |
+
|
| 63 |
+
HELD_OUT_FRACTION = 1.0 / 3.0 # 2/3 -> predictions, 1/3 -> held-out
|
| 64 |
+
|
| 65 |
+
MIN_PREDICTIONS = 5
|
| 66 |
+
MIN_HELD_OUT = 3
|
| 67 |
+
|
| 68 |
+
TRAIN_RATIO = 0.9
|
| 69 |
+
VAL_RATIO = 0.05
|
| 70 |
+
TEST_RATIO = 0.05
|
| 71 |
+
|
| 72 |
+
DATA_SOURCE = "Blog Authorship Corpus"
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
# --- helpers -----------------------------------------------------------------
|
| 76 |
+
|
| 77 |
+
@dataclass
|
| 78 |
+
class _Row:
|
| 79 |
+
interview_id: str
|
| 80 |
+
observations: list[str]
|
| 81 |
+
predictions: list[dict[str, str]]
|
| 82 |
+
held_out: list[dict[str, str]]
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _decompress_zst(path: Path) -> bytes:
|
| 86 |
+
return subprocess.check_output(["zstd", "-dcf", str(path)])
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def _iter_records(input_dir: Path) -> Iterator[dict]:
|
| 90 |
+
files = sorted(input_dir.glob("data_*.zst"))
|
| 91 |
+
if not files:
|
| 92 |
+
raise SystemExit(f"no data_*.zst files in {input_dir}")
|
| 93 |
+
for p in files:
|
| 94 |
+
arr = json.loads(_decompress_zst(p))
|
| 95 |
+
for r in arr:
|
| 96 |
+
yield r
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def _interview_seed(interview_id: str) -> int:
|
| 100 |
+
try:
|
| 101 |
+
return SEED + int(interview_id)
|
| 102 |
+
except (TypeError, ValueError):
|
| 103 |
+
return SEED + (hash(str(interview_id)) & 0x7FFFFFFF)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def _record_to_row(rec: dict) -> _Row | None:
|
| 107 |
+
extra = rec.get("extra_info") or {}
|
| 108 |
+
interview_id = str(extra.get("interview_id") or "")
|
| 109 |
+
if not interview_id:
|
| 110 |
+
return None
|
| 111 |
+
|
| 112 |
+
observations = list(rec.get("observations") or [])
|
| 113 |
+
predictions = list(rec.get("predictions") or [])
|
| 114 |
+
if len(observations) < MIN_OBSERVATIONS:
|
| 115 |
+
return None
|
| 116 |
+
if not predictions:
|
| 117 |
+
return None
|
| 118 |
+
|
| 119 |
+
rng = random.Random(_interview_seed(interview_id))
|
| 120 |
+
|
| 121 |
+
# Cap observations by deterministic subsample (preserve order after sample).
|
| 122 |
+
if len(observations) > MAX_OBSERVATIONS:
|
| 123 |
+
idxs = sorted(rng.sample(range(len(observations)), MAX_OBSERVATIONS))
|
| 124 |
+
observations = [observations[i] for i in idxs]
|
| 125 |
+
|
| 126 |
+
# Per-individual split predictions -> (predictions, held_out).
|
| 127 |
+
pred_pool = list(predictions)
|
| 128 |
+
rng.shuffle(pred_pool)
|
| 129 |
+
n_held = max(1, int(round(len(pred_pool) * HELD_OUT_FRACTION)))
|
| 130 |
+
n_held = min(n_held, len(pred_pool) - 1) # ensure at least one prediction left
|
| 131 |
+
if n_held < 1:
|
| 132 |
+
return None
|
| 133 |
+
n_pred = len(pred_pool) - n_held
|
| 134 |
+
if n_pred < MIN_PREDICTIONS or n_held < MIN_HELD_OUT:
|
| 135 |
+
return None
|
| 136 |
+
|
| 137 |
+
pred_slice = pred_pool[:n_pred]
|
| 138 |
+
held_slice = pred_pool[n_pred:]
|
| 139 |
+
|
| 140 |
+
def _clean(items: list[dict]) -> list[dict[str, str]]:
|
| 141 |
+
out = []
|
| 142 |
+
for it in items:
|
| 143 |
+
q = it.get("question")
|
| 144 |
+
gt = it.get("ground_truth")
|
| 145 |
+
if not isinstance(q, str) or not isinstance(gt, str):
|
| 146 |
+
continue
|
| 147 |
+
out.append({"question": q, "ground_truth": gt})
|
| 148 |
+
return out
|
| 149 |
+
|
| 150 |
+
pred_clean = _clean(pred_slice)
|
| 151 |
+
held_clean = _clean(held_slice)
|
| 152 |
+
if len(pred_clean) < MIN_PREDICTIONS or len(held_clean) < MIN_HELD_OUT:
|
| 153 |
+
return None
|
| 154 |
+
|
| 155 |
+
return _Row(
|
| 156 |
+
interview_id=interview_id,
|
| 157 |
+
observations=observations,
|
| 158 |
+
predictions=pred_clean,
|
| 159 |
+
held_out=held_clean,
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def _partition_split_counts(n: int) -> tuple[int, int, int]:
|
| 164 |
+
n_val = round(n * VAL_RATIO)
|
| 165 |
+
n_test = round(n * TEST_RATIO)
|
| 166 |
+
n_train = n - n_val - n_test
|
| 167 |
+
if n_train < 1 and n > 0:
|
| 168 |
+
half = max(0, n - 1) // 2
|
| 169 |
+
n_train, n_val, n_test = 1, half, n - 1 - half
|
| 170 |
+
return n_train, n_val, n_test
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def _record_to_dict(rec: _Row, split: str) -> dict[str, Any]:
|
| 174 |
+
extra: dict[str, Any] = {
|
| 175 |
+
"interview_id": rec.interview_id,
|
| 176 |
+
"n_observations": len(rec.observations),
|
| 177 |
+
}
|
| 178 |
+
if split == "train":
|
| 179 |
+
out = {
|
| 180 |
+
"observations": rec.observations,
|
| 181 |
+
"predictions": rec.predictions,
|
| 182 |
+
"data_source": DATA_SOURCE,
|
| 183 |
+
"split": "train",
|
| 184 |
+
"held_out_predictions": rec.held_out,
|
| 185 |
+
}
|
| 186 |
+
extra["n_predictions"] = len(rec.predictions)
|
| 187 |
+
extra["n_held_out_predictions"] = len(rec.held_out)
|
| 188 |
+
else:
|
| 189 |
+
merged = list(rec.predictions) + list(rec.held_out)
|
| 190 |
+
out = {
|
| 191 |
+
"observations": rec.observations,
|
| 192 |
+
"predictions": merged,
|
| 193 |
+
"data_source": DATA_SOURCE,
|
| 194 |
+
"split": split,
|
| 195 |
+
}
|
| 196 |
+
extra["n_predictions"] = len(merged)
|
| 197 |
+
out["extra_info"] = extra
|
| 198 |
+
return out
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
# --- arrow schemas (explicit so train and val/test are stable) ---------------
|
| 202 |
+
|
| 203 |
+
_PRED_TYPE = pa.struct([
|
| 204 |
+
pa.field("question", pa.string()),
|
| 205 |
+
pa.field("ground_truth", pa.string()),
|
| 206 |
+
])
|
| 207 |
+
|
| 208 |
+
_TRAIN_SCHEMA = pa.schema([
|
| 209 |
+
pa.field("observations", pa.list_(pa.string())),
|
| 210 |
+
pa.field("predictions", pa.list_(_PRED_TYPE)),
|
| 211 |
+
pa.field("data_source", pa.string()),
|
| 212 |
+
pa.field("split", pa.string()),
|
| 213 |
+
pa.field("held_out_predictions", pa.list_(_PRED_TYPE)),
|
| 214 |
+
pa.field("extra_info", pa.struct([
|
| 215 |
+
pa.field("interview_id", pa.string()),
|
| 216 |
+
pa.field("n_observations", pa.int32()),
|
| 217 |
+
pa.field("n_predictions", pa.int32()),
|
| 218 |
+
pa.field("n_held_out_predictions", pa.int32()),
|
| 219 |
+
])),
|
| 220 |
+
])
|
| 221 |
+
|
| 222 |
+
_EVAL_SCHEMA = pa.schema([
|
| 223 |
+
pa.field("observations", pa.list_(pa.string())),
|
| 224 |
+
pa.field("predictions", pa.list_(_PRED_TYPE)),
|
| 225 |
+
pa.field("data_source", pa.string()),
|
| 226 |
+
pa.field("split", pa.string()),
|
| 227 |
+
pa.field("extra_info", pa.struct([
|
| 228 |
+
pa.field("interview_id", pa.string()),
|
| 229 |
+
pa.field("n_observations", pa.int32()),
|
| 230 |
+
pa.field("n_predictions", pa.int32()),
|
| 231 |
+
])),
|
| 232 |
+
])
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def _write_split(records: list[dict], split: str, output_dir: Path, *,
|
| 236 |
+
compression: str | None, compression_level: int | None) -> Path:
|
| 237 |
+
schema = _TRAIN_SCHEMA if split == "train" else _EVAL_SCHEMA
|
| 238 |
+
table = pa.Table.from_pylist(records, schema=schema)
|
| 239 |
+
out_path = output_dir / f"{split}-00000-of-00001.parquet"
|
| 240 |
+
pq.write_table(
|
| 241 |
+
table, out_path,
|
| 242 |
+
compression=compression,
|
| 243 |
+
compression_level=compression_level,
|
| 244 |
+
use_dictionary=True,
|
| 245 |
+
)
|
| 246 |
+
return out_path
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def parse_args() -> argparse.Namespace:
|
| 250 |
+
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 251 |
+
p.add_argument(
|
| 252 |
+
"--input-dir",
|
| 253 |
+
type=Path,
|
| 254 |
+
default=Path("hf_repo"),
|
| 255 |
+
help="Directory containing the upstream data_*.zst shards.",
|
| 256 |
+
)
|
| 257 |
+
p.add_argument("--output-dir", type=Path, default=Path("qa"))
|
| 258 |
+
p.add_argument("--max-rows", type=int, default=0,
|
| 259 |
+
help="Debug: stop after this many input rows (0 = all).")
|
| 260 |
+
p.add_argument("--compression", default="zstd",
|
| 261 |
+
choices=["zstd", "gzip", "snappy", "brotli", "lz4", "none"])
|
| 262 |
+
p.add_argument("--compression-level", type=int, default=None)
|
| 263 |
+
return p.parse_args()
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def main() -> None:
|
| 267 |
+
args = parse_args()
|
| 268 |
+
args.output_dir.mkdir(parents=True, exist_ok=True)
|
| 269 |
+
|
| 270 |
+
pool: list[_Row] = []
|
| 271 |
+
raw_seen = 0
|
| 272 |
+
skipped = 0
|
| 273 |
+
|
| 274 |
+
for rec in _iter_records(args.input_dir):
|
| 275 |
+
raw_seen += 1
|
| 276 |
+
if args.max_rows and raw_seen > args.max_rows:
|
| 277 |
+
break
|
| 278 |
+
row = _record_to_row(rec)
|
| 279 |
+
if row is None:
|
| 280 |
+
skipped += 1
|
| 281 |
+
continue
|
| 282 |
+
pool.append(row)
|
| 283 |
+
|
| 284 |
+
rng = random.Random(SEED)
|
| 285 |
+
rng.shuffle(pool)
|
| 286 |
+
n = len(pool)
|
| 287 |
+
n_train, n_val, _n_test = _partition_split_counts(n)
|
| 288 |
+
|
| 289 |
+
splits = {
|
| 290 |
+
"train": pool[:n_train],
|
| 291 |
+
"val": pool[n_train : n_train + n_val],
|
| 292 |
+
"test": pool[n_train + n_val :],
|
| 293 |
+
}
|
| 294 |
+
|
| 295 |
+
comp = None if args.compression == "none" else args.compression
|
| 296 |
+
written: dict[str, dict] = {}
|
| 297 |
+
for split_name, recs in splits.items():
|
| 298 |
+
if not recs:
|
| 299 |
+
continue
|
| 300 |
+
records = [_record_to_dict(r, split_name) for r in recs]
|
| 301 |
+
path = _write_split(records, split_name, args.output_dir,
|
| 302 |
+
compression=comp, compression_level=args.compression_level)
|
| 303 |
+
written[split_name] = {"rows": len(records), "path": str(path)}
|
| 304 |
+
|
| 305 |
+
print(json.dumps({
|
| 306 |
+
"raw_lines_seen": raw_seen,
|
| 307 |
+
"samples_built": n,
|
| 308 |
+
"skipped_insufficient_data": skipped,
|
| 309 |
+
"split_counts": {k: len(v) for k, v in splits.items()},
|
| 310 |
+
"written": written,
|
| 311 |
+
}, indent=2))
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
if __name__ == "__main__":
|
| 315 |
+
main()
|
scripts/parquet_to_jsonl.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Convert any Parquet file in this dataset back to JSONL (one row = one line).
|
| 3 |
+
|
| 4 |
+
Works for ``demographics.parquet``, ``statements_meta.parquet``, and the
|
| 5 |
+
``qa/*.parquet`` shards. Reads compressed Parquet (ZSTD / Snappy / GZIP / etc.)
|
| 6 |
+
transparently via PyArrow.
|
| 7 |
+
|
| 8 |
+
Self-contained: only depends on ``pyarrow``. No chiron imports.
|
| 9 |
+
|
| 10 |
+
Examples:
|
| 11 |
+
|
| 12 |
+
# Single file -> single JSONL
|
| 13 |
+
python parquet_to_jsonl.py --src demographics.parquet --dst demographics.jsonl
|
| 14 |
+
|
| 15 |
+
# Whole qa/ split (multiple shards merged into one JSONL per split)
|
| 16 |
+
python parquet_to_jsonl.py --src qa/ --dst qa_jsonl/ --by-split
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import argparse
|
| 22 |
+
import json
|
| 23 |
+
import re
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
|
| 26 |
+
import numpy as np
|
| 27 |
+
import pyarrow.parquet as pq
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
_SPLIT_RE = re.compile(r"^(?P<split>[A-Za-z0-9_-]+)-(?P<shard>\d{5})-of-\d{5}\.parquet$")
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _to_python(obj):
|
| 34 |
+
"""Recursively turn pyarrow / numpy scalars into JSON-friendly Python objects."""
|
| 35 |
+
if obj is None:
|
| 36 |
+
return None
|
| 37 |
+
if isinstance(obj, dict):
|
| 38 |
+
return {k: _to_python(v) for k, v in obj.items()}
|
| 39 |
+
if isinstance(obj, (list, tuple)):
|
| 40 |
+
return [_to_python(v) for v in obj]
|
| 41 |
+
if isinstance(obj, np.ndarray):
|
| 42 |
+
return [_to_python(v) for v in obj.tolist()]
|
| 43 |
+
if isinstance(obj, (np.integer,)):
|
| 44 |
+
return int(obj)
|
| 45 |
+
if isinstance(obj, (np.floating,)):
|
| 46 |
+
return float(obj)
|
| 47 |
+
if isinstance(obj, (np.bool_,)):
|
| 48 |
+
return bool(obj)
|
| 49 |
+
return obj
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def write_table_to_jsonl(table_path: Path, out_handle, *, batch_rows: int = 1024) -> int:
|
| 53 |
+
"""Stream rows from one Parquet file to the open JSONL writer."""
|
| 54 |
+
pf = pq.ParquetFile(table_path)
|
| 55 |
+
n = 0
|
| 56 |
+
for batch in pf.iter_batches(batch_size=batch_rows):
|
| 57 |
+
rows = batch.to_pylist()
|
| 58 |
+
for r in rows:
|
| 59 |
+
out_handle.write(json.dumps(_to_python(r), ensure_ascii=False) + "\n")
|
| 60 |
+
n += 1
|
| 61 |
+
return n
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _split_of(path: Path) -> str | None:
|
| 65 |
+
m = _SPLIT_RE.match(path.name)
|
| 66 |
+
return m.group("split") if m else None
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def parse_args() -> argparse.Namespace:
|
| 70 |
+
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 71 |
+
p.add_argument("--src", type=Path, required=True, help="Parquet file or directory of Parquet shards.")
|
| 72 |
+
p.add_argument(
|
| 73 |
+
"--dst",
|
| 74 |
+
type=Path,
|
| 75 |
+
required=True,
|
| 76 |
+
help="Output JSONL file (when src is a single file or --by-split is off) or directory (with --by-split).",
|
| 77 |
+
)
|
| 78 |
+
p.add_argument(
|
| 79 |
+
"--by-split",
|
| 80 |
+
action="store_true",
|
| 81 |
+
help="If set, treat src as a directory of HF-style sharded files <split>-NNNNN-of-MMMMM.parquet "
|
| 82 |
+
"and emit one <dst>/<split>.jsonl per detected split.",
|
| 83 |
+
)
|
| 84 |
+
p.add_argument("--batch-rows", type=int, default=1024)
|
| 85 |
+
return p.parse_args()
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def main() -> None:
|
| 89 |
+
args = parse_args()
|
| 90 |
+
src: Path = args.src
|
| 91 |
+
dst: Path = args.dst
|
| 92 |
+
|
| 93 |
+
if src.is_file():
|
| 94 |
+
dst.parent.mkdir(parents=True, exist_ok=True)
|
| 95 |
+
with dst.open("w", encoding="utf-8") as fh:
|
| 96 |
+
n = write_table_to_jsonl(src, fh, batch_rows=args.batch_rows)
|
| 97 |
+
print(json.dumps({"src": str(src), "dst": str(dst), "rows": n}, indent=2))
|
| 98 |
+
return
|
| 99 |
+
|
| 100 |
+
if not src.is_dir():
|
| 101 |
+
raise SystemExit(f"src not found: {src}")
|
| 102 |
+
|
| 103 |
+
files = sorted(src.glob("*.parquet"))
|
| 104 |
+
if not files:
|
| 105 |
+
raise SystemExit(f"no .parquet files in {src}")
|
| 106 |
+
|
| 107 |
+
if args.by_split:
|
| 108 |
+
dst.mkdir(parents=True, exist_ok=True)
|
| 109 |
+
groups: dict[str, list[Path]] = {}
|
| 110 |
+
for f in files:
|
| 111 |
+
split = _split_of(f) or f.stem
|
| 112 |
+
groups.setdefault(split, []).append(f)
|
| 113 |
+
report = {}
|
| 114 |
+
for split, shards in groups.items():
|
| 115 |
+
out_path = dst / f"{split}.jsonl"
|
| 116 |
+
n_total = 0
|
| 117 |
+
with out_path.open("w", encoding="utf-8") as fh:
|
| 118 |
+
for shard in shards:
|
| 119 |
+
n_total += write_table_to_jsonl(shard, fh, batch_rows=args.batch_rows)
|
| 120 |
+
report[split] = {"shards": [str(s) for s in shards], "dst": str(out_path), "rows": n_total}
|
| 121 |
+
print(json.dumps(report, indent=2))
|
| 122 |
+
return
|
| 123 |
+
|
| 124 |
+
# Concatenate all parquet files in dir into a single JSONL.
|
| 125 |
+
dst.parent.mkdir(parents=True, exist_ok=True)
|
| 126 |
+
n_total = 0
|
| 127 |
+
with dst.open("w", encoding="utf-8") as fh:
|
| 128 |
+
for f in files:
|
| 129 |
+
n_total += write_table_to_jsonl(f, fh, batch_rows=args.batch_rows)
|
| 130 |
+
print(json.dumps({"src_dir": str(src), "dst": str(dst), "files": len(files), "rows": n_total}, indent=2))
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
if __name__ == "__main__":
|
| 134 |
+
main()
|