File size: 4,215 Bytes
a4f2b0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""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()