File size: 7,950 Bytes
0ea96e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
#!/usr/bin/env python3
"""Generate pattern-frequency report as percentage of source token counts.

Outputs:
- summary for whole corpus (counts + share of total tokens)
- per-source counts + share within source
- optional markdown snippet and optional bar chart
"""

from __future__ import annotations

import argparse
import json
from pathlib import Path

import matplotlib.pyplot as plt
import pyarrow.compute as pc
import pyarrow.parquet as pq

PATTERNS = [
    ("w roku", "w roku"),
    ("klasyfikacji", "klasyfikacji"),
    ("ustawa", "ustawa"),
    ("artykuł", "artykuł"),
    ("parlament", "parlament"),
    ("rozporządzenie", "rozporządzenie"),
    ("w pobliżu", "w pobliżu"),
    ("mieszkańców", "mieszkańców"),
    ("Dz.U.", "dz\\.u\\."),
]


def load_tokens_by_source(root: Path) -> dict[str, int]:
    by_source = {}
    for stats_file in sorted((root / "data").glob("*/*.stats.json")):
        src = stats_file.parent.name
        payload = json.loads(stats_file.read_text(encoding="utf-8"))
        by_source[src] = int(payload["tokens"])
    return by_source


def count_patterns_for_source(parquet_path: Path) -> dict[str, int]:
    counts = {name: 0 for name, _ in PATTERNS}
    pf = pq.ParquetFile(parquet_path)

    for rg in range(pf.num_row_groups):
        table = pf.read_row_group(rg, columns=["text"])
        text = table["text"]
        text = pc.utf8_lower(text)
        text = pc.replace_substring_regex(text, pattern="\\r?\\n", replacement=" ")

        for label, pattern in PATTERNS:
            if label == "Dz.U.":
                cnt = pc.count_substring_regex(text, pattern)
            else:
                cnt = pc.count_substring(text, pattern)
            counts[label] += int(pc.sum(cnt).as_py())

    return counts


def compute_counts(data_root: Path) -> tuple[dict[str, int], dict[str, dict[str, int]]]:
    tokens = load_tokens_by_source(data_root)
    source_counts = {}
    total_counts = {label: 0 for label, _ in PATTERNS}

    for parquet_path in sorted((data_root / "data").glob("*/*.parquet")):
        source = parquet_path.parent.name
        counts = count_patterns_for_source(parquet_path)
        source_counts[source] = counts
        for label, cnt in counts.items():
            total_counts[label] += cnt

    return total_counts, source_counts, tokens


def write_markdown(total_counts, source_counts, tokens, out_md: Path) -> None:
    total_tokens = sum(tokens.values())
    lines = []
    lines.append("## Pattern frequency on corpus\n")
    lines.append(f"- total tokens (tiktoken proxy): `{total_tokens:,}`\n")
    lines.append("| pattern | count | share of all tokens |")
    lines.append("|---|---:|---:|")
    for label, _ in PATTERNS:
        c = total_counts[label]
        lines.append(f"| `{label}` | {c:,} | {c/total_tokens*100:.4f}% |")
    lines.append("")
    lines.append("| source | pattern | count | per-token share |")
    lines.append("|---|---|---:|---:|")
    for source in sorted(source_counts):
        src_tokens = tokens[source]
        for label, _ in PATTERNS:
            c = source_counts[source][label]
            lines.append(f"| {source} | `{label}` | {c:,} | {c/src_tokens*100:.5f}% |")
    out_md.write_text("\n".join(lines) + "\n", encoding="utf-8")


def write_hf_snippet(total_counts, source_counts, tokens, total_tokens: int, out_md: Path) -> None:
    patterns = [label for label, _ in PATTERNS]
    lines = []
    lines.append("## Phrase frequency in corpus (token-normalized)")
    lines.append("")
    lines.append(f"- Total token count (tiktoken proxy): **{total_tokens:,}**")
    lines.append("")
    lines.append("| Pattern | Count | Share of all tokens |")
    lines.append("|---|---:|---:|")
    for label in patterns:
        c = total_counts[label]
        lines.append(f"| `{label}` | {c:,} | {c / total_tokens * 100:.4f}% |")
    lines.append("")
    lines.append("### Per-source shares")
    lines.append("")
    lines.append("| source | pattern | count | share of source tokens |")
    lines.append("|---|---|---:|---:|")
    ordered_sources = sorted(source_counts)
    for source in ordered_sources:
        src_tok = tokens[source]
        for label in patterns:
            c = source_counts[source][label]
            lines.append(f"| `{source}` | `{label}` | {c:,} | {c / src_tok * 100:.5f}% |")

    lines.append("")
    lines.append("![Overall pattern counts](artifacts/pattern_frequency_overall.png)")
    lines.append("")
    lines.append("![w roku by source](artifacts/pattern_frequency_w_roku.png)")
    lines.append("![klasyfikacji by source](artifacts/pattern_frequency_klasyfikacji.png)")
    lines.append("![ustawa by source](artifacts/pattern_frequency_ustawa.png)")
    lines.append("![artykuł by source](artifacts/pattern_frequency_artykul.png)")
    lines.append("![parlament by source](artifacts/pattern_frequency_parlament.png)")
    lines.append("![rozporządzenie by source](artifacts/pattern_frequency_rozporządzenie.png)")
    lines.append("![w pobliżu by source](artifacts/pattern_frequency_w_pobliżu.png)")
    lines.append("![mieszkańców by source](artifacts/pattern_frequency_mieszkańców.png)")
    lines.append("![Dz.U. by source](artifacts/pattern_frequency_dzu.png)")

    out_md.write_text("\n".join(lines) + "\n", encoding="utf-8")


def plot(total_counts, source_counts, tokens, out_png: Path) -> None:
    out_png.parent.mkdir(parents=True, exist_ok=True)
    patterns = [label for label, _ in PATTERNS]
    totals = [total_counts[p] for p in patterns]

    # overall share chart
    plt.figure(figsize=(10, 4))
    plt.bar(patterns, totals, color="#2b8cbe")
    plt.title("Pattern count in full corpus")
    plt.ylabel("count")
    plt.xlabel("pattern")
    plt.xticks(rotation=25, ha="right")
    plt.tight_layout()
    total_png = out_png.with_name(out_png.stem + "_overall" + out_png.suffix)
    plt.savefig(total_png, dpi=140)
    plt.close()

    # per-source percentage heatmap-like bars
    ordered_sources = sorted(source_counts)
    for pattern in patterns:
        vals = [source_counts[src][pattern] / tokens[src] * 100 for src in ordered_sources]
        plt.figure(figsize=(10, 4))
        plt.bar(ordered_sources, vals)
        plt.title(f"{pattern} share per source (% of source tokens)")
        plt.ylabel("% of tokens")
        plt.xticks(rotation=30, ha="right")
        plt.tight_layout()
        safe = pattern.replace(" ", "_").replace("ł", "l").replace(".", "").lower()
        plt.savefig(out_png.parent / f"{out_png.stem}_{safe}.png", dpi=140)
        plt.close()


def parse_args():
    ap = argparse.ArgumentParser()
    ap.add_argument("--data-root", type=Path, default=Path("."), help="repo root")
    ap.add_argument("--out-md", type=Path, default=Path("pattern_frequency_report.md"))
    ap.add_argument("--out-png", type=Path, default=Path("artifacts/pattern_frequency.png"))
    ap.add_argument(
        "--out-hf",
        type=Path,
        default=Path("artifacts/pattern_frequency_hf_snippet.md"),
        help="HF model card snippet to paste into README.md on Hugging Face",
    )
    return ap.parse_args()


def main():
    args = parse_args()
    total_counts, source_counts, tokens = compute_counts(args.data_root)
    total_tokens = sum(tokens.values())
    args.out_md.parent.mkdir(parents=True, exist_ok=True)
    write_markdown(total_counts, source_counts, tokens, args.out_md)
    write_hf_snippet(total_counts, source_counts, tokens, total_tokens, args.out_hf)
    plot(total_counts, source_counts, tokens, args.out_png)

    print(f"wrote: {args.out_md}")
    print(f"wrote: {args.out_hf}")
    print(f"wrote: {args.out_png.with_name(args.out_png.stem + '_overall' + args.out_png.suffix)}")
    for label, _ in PATTERNS:
        safe = label.replace(' ', '_').replace('ł', 'l').replace('.', '').lower()
        print(f"wrote: {args.out_png.parent / f'{args.out_png.stem}_{safe}.png'}")


if __name__ == "__main__":
    main()