| |
| """Probe / dry-run / re-encode parquet files to dictionary + a chosen codec to shrink them. |
| |
| Only the on-disk encoding changes; the logical data is preserved bit-for-bit, so HF |
| `load_dataset` features and config bundling are unaffected. Safe by design: |
| * verifies EVERY file before replacing: full-table data+type equality (orig.equals, |
| check_metadata=False) AND byte-identical 'huggingface' schema metadata AND the array |
| column's ARROW:extension metadata (what lets datasets rebuild Array2D) |
| * atomic: writes a temp then os.replace() — an interrupted run never leaves a half file |
| * one file at a time (peak RAM ~= largest single file) |
| * idempotent: in `reencode`, files already dictionary-encoded in the target codec are skipped |
| |
| Modes (PATH may be a single .parquet file OR a folder, recursed for **/*.parquet): |
| probe read-only; measure target size and print the table. No verification, no write. |
| dryrun full verified pipeline (re-encode to temp + verify) but never replace. Prints table. |
| reencode same verified pipeline, then atomic in-place replace for files that shrink (>2%). |
| |
| Every mode ends with a per-file + per-folder + grand-total size table. |
| |
| Usage: |
| python reencode_parquet.py probe PATH [--codec ZSTD] |
| python reencode_parquet.py dryrun PATH [--codec ZSTD] |
| python reencode_parquet.py reencode PATH [--codec ZSTD] |
| |
| --codec defaults to SNAPPY (pyarrow's default; what this dataset is already encoded with). |
| """ |
| import argparse |
| import glob |
| import os |
| import tempfile |
|
|
| import pyarrow.parquet as pq |
|
|
| HF_KEY = b"huggingface" |
|
|
|
|
| def iter_parquet(path): |
| """A single .parquet file -> [path]; a folder -> sorted **/*.parquet (excl. hidden).""" |
| if os.path.isfile(path): |
| return [path] |
| files = glob.glob(os.path.join(path, "**", "*.parquet"), recursive=True) |
| return sorted(f for f in files if "/." not in f and not os.path.basename(f).startswith(".")) |
|
|
|
|
| def uncompressed_size(path): |
| """Sum of total_uncompressed_size over every column of every row group (logical size).""" |
| md = pq.ParquetFile(path).metadata |
| total = 0 |
| for g in range(md.num_row_groups): |
| rg = md.row_group(g) |
| total += sum(rg.column(i).total_uncompressed_size for i in range(rg.num_columns)) |
| return total |
|
|
|
|
| def _big_column(path): |
| """The biggest (uncompressed) column of the first row group — representative of encoding.""" |
| rg = pq.ParquetFile(path).metadata.row_group(0) |
| cols = [rg.column(i) for i in range(rg.num_columns)] |
| return max(cols, key=lambda c: c.total_uncompressed_size) |
|
|
|
|
| def _array_ext_meta(table): |
| """Return the ARROW:extension metadata of the first extension column, or None.""" |
| for f in table.schema: |
| m = f.metadata or {} |
| if b"ARROW:extension:name" in m: |
| return dict(m) |
| return None |
|
|
|
|
| def write_temp(table, codec, dirpath): |
| """Write `table` to a temp file in `dirpath` with `codec` + dictionary. Return temp path.""" |
| fd, tmp = tempfile.mkstemp(dir=dirpath, suffix=".reenc.tmp") |
| os.close(fd) |
| pq.write_table(table, tmp, compression=codec, use_dictionary=True) |
| return tmp |
|
|
|
|
| def verify(orig, tmp_path): |
| """Raise if the re-encoded temp is not bit-for-bit equal to `orig` (data + key metadata).""" |
| back = pq.read_table(tmp_path) |
| if not orig.equals(back, check_metadata=False): |
| raise RuntimeError("DATA MISMATCH after re-encode") |
| if (back.schema.metadata or {}).get(HF_KEY) != (orig.schema.metadata or {}).get(HF_KEY): |
| raise RuntimeError("'huggingface' schema metadata changed") |
| if _array_ext_meta(back) != _array_ext_meta(orig): |
| raise RuntimeError("array extension metadata changed") |
|
|
|
|
| def process(path, mode, codec): |
| """Return a row dict {path, current, uncompressed, target, status} for one file. |
| |
| Modes: probe (measure only), dryrun (measure + verify), reencode (measure + verify + replace). |
| """ |
| current = os.path.getsize(path) |
| uncompr = uncompressed_size(path) |
|
|
| |
| if mode == "reencode": |
| big = _big_column(path) |
| if big.has_dictionary_page and big.compression == codec: |
| return dict(path=path, current=current, uncompressed=uncompr, |
| target=current, status="skipped (already)") |
|
|
| orig = pq.read_table(path) |
| dirpath = os.path.dirname(path) or "." |
| tmp = write_temp(orig, codec, dirpath) |
| try: |
| if mode != "probe": |
| verify(orig, tmp) |
| target = os.path.getsize(tmp) |
| beneficial = target < current * 0.98 |
|
|
| if mode == "reencode" and beneficial: |
| os.replace(tmp, path) |
| tmp = None |
| return dict(path=path, current=current, uncompressed=uncompr, |
| target=target, status="written") |
|
|
| status = ("would shrink" if beneficial else "no gain") if mode != "probe" else "probed" |
| return dict(path=path, current=current, uncompressed=uncompr, |
| target=target, status=status) |
| finally: |
| if tmp and os.path.exists(tmp): |
| os.remove(tmp) |
|
|
|
|
| def _mb(n): |
| return f"{n / 1e6:9.1f} MB" |
|
|
|
|
| def _savings(current, target): |
| saved = current - target |
| pct = (1 - target / current) * 100 if current else 0 |
| return f"{saved / 1e6:9.1f} MB ({pct:4.0f}%)" |
|
|
|
|
| def print_table(rows): |
| """Per-file rows grouped by parent folder, a subtotal per folder, then a grand total.""" |
| name_w = max([len(os.path.basename(r["path"])) for r in rows] + [12]) |
| header = (f" {'file'.ljust(name_w)} | {'current':>12} | {'uncompr':>12} | " |
| f"{'target':>12} | {'savings':>18}") |
| sep = " " + "-" * (len(header) - 2) |
|
|
| folders = {} |
| for r in rows: |
| folders.setdefault(os.path.dirname(r["path"]) or ".", []).append(r) |
|
|
| g_cur = g_unc = g_tgt = 0 |
| print(header) |
| print(sep) |
| for folder in sorted(folders): |
| fr = folders[folder] |
| f_cur = f_unc = f_tgt = 0 |
| for r in fr: |
| print(f" {os.path.basename(r['path']).ljust(name_w)} | " |
| f"{_mb(r['current'])} | {_mb(r['uncompressed'])} | {_mb(r['target'])} | " |
| f"{_savings(r['current'], r['target'])} {r['status']}") |
| f_cur += r["current"] |
| f_unc += r["uncompressed"] |
| f_tgt += r["target"] |
| print(f" {('Folder ' + folder).ljust(name_w)} | " |
| f"{_mb(f_cur)} | {_mb(f_unc)} | {_mb(f_tgt)} | {_savings(f_cur, f_tgt)}") |
| print(sep) |
| g_cur += f_cur |
| g_unc += f_unc |
| g_tgt += f_tgt |
|
|
| print(f" {'GRAND TOTAL'.ljust(name_w)} | " |
| f"{_mb(g_cur)} | {_mb(g_unc)} | {_mb(g_tgt)} | {_savings(g_cur, g_tgt)}") |
|
|
|
|
| def main(): |
| ap = argparse.ArgumentParser(description=__doc__, |
| formatter_class=argparse.RawDescriptionHelpFormatter) |
| ap.add_argument("mode", choices=["probe", "dryrun", "reencode"]) |
| ap.add_argument("path", help="a .parquet file or a folder (recursed for **/*.parquet)") |
| ap.add_argument("--codec", default="SNAPPY", help="target compression codec (default: SNAPPY)") |
| args = ap.parse_args() |
| codec = args.codec.upper() |
|
|
| files = iter_parquet(args.path) |
| if not files: |
| raise SystemExit(f"no parquet files under {args.path}") |
|
|
| print(f"MODE: {args.mode.upper()} codec: {codec} ({len(files)} files)\n") |
| rows = [] |
| for f in files: |
| rows.append(process(f, args.mode, codec)) |
| print() |
| print_table(rows) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|