the-stack-go / stackgo /stackbuild /serialization.py
s0duku's picture
Add files using upload-large-folder tool
4b10a0d verified
Raw History Blame Contribute Delete
3.6 kB
"""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)