File size: 3,596 Bytes
4b10a0d
f764cdf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b10a0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Serialization helpers for stackbuild samples."""

from __future__ import annotations

from dataclasses import asdict
import json
from pathlib import Path
from typing import Iterable

from .model import Sample


def sample_to_dict(sample: Sample) -> dict:
    return asdict(sample)


def write_jsonl(samples: Iterable[Sample], path: str | Path) -> None:
    target = Path(path)
    temporary = target.with_suffix(target.suffix + ".part")
    with temporary.open("w", encoding="utf-8") as stream:
        for sample in samples:
            stream.write(json.dumps(sample_to_dict(sample), ensure_ascii=False, separators=(",", ":")))
            stream.write("\n")
    temporary.replace(target)


def _parquet_row(sample: Sample) -> dict:
    row = sample_to_dict(sample)
    row["files"] = list(row["files"])
    row["metadata_json"] = json.dumps(
        row.pop("metadata"), ensure_ascii=False, separators=(",", ":"), sort_keys=True,
    )
    return row


class ParquetSampleWriter:
    """Buffered, atomic Parquet writer with a stable nested schema."""

    def __init__(self, path: str | Path, *, batch_size: int = 2048) -> None:
        import pyarrow as pa

        self.target = Path(path)
        self.temporary = self.target.with_suffix(self.target.suffix + ".part")
        self.target.parent.mkdir(parents=True, exist_ok=True)
        self.batch_size = batch_size
        self.buffer: list[dict] = []
        self.schema = pa.schema([
            ("sample_id", pa.string()),
            ("repo_id", pa.string()),
            ("revision_id", pa.string()),
            ("kind", pa.string()),
            ("text", pa.large_string()),
            ("files", pa.list_(pa.struct([
                ("path", pa.string()),
                ("relation", pa.string()),
                ("content_policy", pa.string()),
                ("role", pa.string()),
                ("language", pa.string()),
                ("bytes", pa.int64()),
                ("part", pa.int32()),
                ("parts", pa.int32()),
            ]))),
            ("token_count", pa.int32()),
            ("metadata_json", pa.large_string()),
        ])
        self.writer = None

    def write(self, samples: Iterable[Sample]) -> None:
        for sample in samples:
            self.buffer.append(_parquet_row(sample))
            if len(self.buffer) >= self.batch_size:
                self._flush()

    def _flush(self) -> None:
        if not self.buffer:
            return
        import pyarrow as pa
        import pyarrow.parquet as pq

        table = pa.Table.from_pylist(self.buffer, schema=self.schema)
        if self.writer is None:
            self.writer = pq.ParquetWriter(
                self.temporary, self.schema, compression="zstd",
                compression_level=6, use_dictionary=True,
            )
        self.writer.write_table(table, row_group_size=self.batch_size)
        self.buffer.clear()

    def close(self) -> None:
        self._flush()
        if self.writer is None:
            import pyarrow.parquet as pq
            pq.write_table(self.schema.empty_table(), self.temporary, compression="zstd")
        else:
            self.writer.close()
        self.temporary.replace(self.target)

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc, traceback) -> None:
        if exc_type is None:
            self.close()
        elif self.writer is not None:
            self.writer.close()


def write_parquet(samples: Iterable[Sample], path: str | Path) -> None:
    with ParquetSampleWriter(path) as writer:
        writer.write(samples)