| |
| """Normalize released parquet files to the current Polish DynaWord schema. |
| |
| This is intentionally conservative: it preserves row order and existing columns, |
| adds `license` from source metadata when missing, adds empty `author` when |
| missing, and recomputes release statistics directly from the parquet files. |
| """ |
| from __future__ import annotations |
|
|
| import json |
| import sys |
| from pathlib import Path |
|
|
| import pyarrow as pa |
| import pyarrow.compute as pc |
| import pyarrow.parquet as pq |
|
|
| sys.path.insert(0, str(Path(__file__).resolve().parent)) |
| from sources import SOURCES |
|
|
|
|
| ROOT = Path(__file__).resolve().parent.parent |
| SCHEMA = pa.schema( |
| [ |
| ("id", pa.string()), |
| ("text", pa.string()), |
| ("source", pa.string()), |
| ("added", pa.string()), |
| ("created", pa.string()), |
| ("token_count", pa.int64()), |
| ("license", pa.string()), |
| ("author", pa.string()), |
| ] |
| ) |
|
|
|
|
| def add_missing_columns(tbl: pa.Table, source: str, default_license: str) -> pa.Table: |
| names = set(tbl.schema.names) |
| if "license" not in names: |
| tbl = tbl.append_column("license", pa.array([default_license] * tbl.num_rows, type=pa.string())) |
| if "author" not in names: |
| tbl = tbl.append_column("author", pa.array([""] * tbl.num_rows, type=pa.string())) |
| return tbl.select(SCHEMA.names).cast(SCHEMA) |
|
|
|
|
| def string_len_sum(arr: pa.ChunkedArray) -> int: |
| lengths = pc.utf8_length(arr) |
| return int(pc.sum(lengths).as_py() or 0) |
|
|
|
|
| def value_counts(arr: pa.ChunkedArray) -> dict[str, int]: |
| out: dict[str, int] = {} |
| for chunk in arr.chunks: |
| counted = pc.value_counts(chunk).to_pylist() |
| for item in counted: |
| value = "" if item["values"] is None else str(item["values"]) |
| out[value] = out.get(value, 0) + int(item["counts"]) |
| return out |
|
|
|
|
| def normalize_one(parquet_path: Path) -> dict: |
| source = parquet_path.parent.name |
| cfg = SOURCES[source] |
| default_license = cfg.get("license", "") |
| tmp_path = parquet_path.with_suffix(".parquet.tmp") |
| writer: pq.ParquetWriter | None = None |
| stats = { |
| "read": 0, |
| "kept": 0, |
| "drop_short": 0, |
| "drop_lang": 0, |
| "drop_dup": 0, |
| "drop_ocr": 0, |
| "chars": 0, |
| "tokens": 0, |
| "licenses": {}, |
| "authors_with_value": 0, |
| "license": default_license, |
| "stats_recomputed_from_parquet": True, |
| } |
|
|
| pf = pq.ParquetFile(parquet_path) |
| try: |
| for batch in pf.iter_batches(batch_size=8192): |
| tbl = add_missing_columns(pa.Table.from_batches([batch]), source, default_license) |
| if writer is None: |
| writer = pq.ParquetWriter(tmp_path, SCHEMA, compression="zstd") |
| writer.write_table(tbl) |
|
|
| n = tbl.num_rows |
| stats["read"] += n |
| stats["kept"] += n |
| stats["chars"] += string_len_sum(tbl["text"]) |
| stats["tokens"] += int(pc.sum(tbl["token_count"]).as_py() or 0) |
| stats["authors_with_value"] += int(pc.sum(pc.not_equal(tbl["author"], "")).as_py() or 0) |
| for value, count in value_counts(tbl["license"]).items(): |
| stats["licenses"][value] = stats["licenses"].get(value, 0) + count |
| finally: |
| if writer is not None: |
| writer.close() |
|
|
| if writer is None: |
| raise RuntimeError(f"empty parquet: {parquet_path}") |
| tmp_path.replace(parquet_path) |
| stats_path = parquet_path.with_name(f"{source}.stats.json") |
| stats_path.write_text(json.dumps(stats, ensure_ascii=False, indent=2) + "\n") |
| return stats |
|
|
|
|
| def main() -> None: |
| total_docs = 0 |
| total_tokens = 0 |
| for parquet_path in sorted((ROOT / "data").glob("*/*.parquet")): |
| source = parquet_path.parent.name |
| if source not in SOURCES: |
| print(f"skip unknown source {source}: {parquet_path}") |
| continue |
| stats = normalize_one(parquet_path) |
| total_docs += stats["kept"] |
| total_tokens += stats["tokens"] |
| print(f"{source}: {stats['kept']:,} docs | {stats['tokens']:,} tokens") |
| print(f"TOTAL: {total_docs:,} docs | {total_tokens:,} tokens") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|