#!/usr/bin/env python3 """Split a large parquet file into smaller parquet shards.""" from __future__ import annotations import argparse import os from pathlib import Path import pyarrow as pa import pyarrow.parquet as pq def parse_size(value: str) -> int: units = { "b": 1, "kb": 1024, "mb": 1024**2, "gb": 1024**3, "tb": 1024**4, } text = value.strip().lower() for suffix, multiplier in sorted(units.items(), key=lambda item: len(item[0]), reverse=True): if text.endswith(suffix): number = float(text[: -len(suffix)].strip()) return int(number * multiplier) return int(float(text)) def shard_name(index: int) -> str: return f"train-{index:05d}.parquet" def split_parquet( source: Path, output_dir: Path, target_size: int, batch_size: int, compression: str, ) -> None: data_dir = output_dir / "data" data_dir.mkdir(parents=True, exist_ok=False) parquet_file = pq.ParquetFile(source) schema = parquet_file.schema_arrow source_rows = parquet_file.metadata.num_rows source_row_groups = parquet_file.metadata.num_row_groups print(f"source={source}", flush=True) print(f"source_rows={source_rows}", flush=True) print(f"source_row_groups={source_row_groups}", flush=True) print(f"target_size_bytes={target_size}", flush=True) print(f"batch_size={batch_size}", flush=True) writer: pq.ParquetWriter | None = None current_path: Path | None = None shard_index = 0 shard_rows = 0 total_rows = 0 def open_writer() -> None: nonlocal writer, current_path, shard_rows, shard_index current_path = data_dir / shard_name(shard_index) writer = pq.ParquetWriter(current_path, schema=schema, compression=compression) shard_rows = 0 print(f"opened_shard={current_path}", flush=True) def close_writer() -> None: nonlocal writer, current_path, shard_rows, shard_index if writer is None or current_path is None: return writer.close() size = current_path.stat().st_size print( f"closed_shard={current_path} rows={shard_rows} size_bytes={size}", flush=True, ) writer = None current_path = None shard_index += 1 shard_rows = 0 try: open_writer() for row_group_index in range(source_row_groups): for batch in parquet_file.iter_batches( batch_size=batch_size, row_groups=[row_group_index], use_threads=True, ): if writer is None: open_writer() table = pa.Table.from_batches([batch], schema=schema) writer.write_table(table) rows = table.num_rows shard_rows += rows total_rows += rows if current_path is not None and current_path.exists(): current_size = current_path.stat().st_size print( "progress " f"row_group={row_group_index + 1}/{source_row_groups} " f"total_rows={total_rows}/{source_rows} " f"current_shard={current_path.name} " f"current_size_bytes={current_size}", flush=True, ) if current_size >= target_size: close_writer() close_writer() except Exception: if writer is not None: writer.close() raise print(f"completed total_rows={total_rows} shards={shard_index}", flush=True) if total_rows != source_rows: raise RuntimeError(f"row count mismatch: wrote {total_rows}, expected {source_rows}") def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--source", required=True, type=Path) parser.add_argument("--output-dir", required=True, type=Path) parser.add_argument("--target-size", default="10GB") parser.add_argument("--batch-size", default=8, type=int) parser.add_argument("--compression", default="snappy") args = parser.parse_args() if not args.source.is_file(): raise FileNotFoundError(args.source) if args.output_dir.exists(): raise FileExistsError(f"Output directory already exists: {args.output_dir}") split_parquet( source=args.source, output_dir=args.output_dir, target_size=parse_size(args.target_size), batch_size=args.batch_size, compression=args.compression, ) if __name__ == "__main__": main()