File size: 4,735 Bytes
c686331
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
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
#!/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()