| |
| """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("") |
| lines.append("") |
| lines.append("") |
| lines.append("") |
| lines.append("") |
| lines.append("") |
| lines.append("") |
| lines.append("") |
| lines.append("") |
| lines.append("") |
| lines.append("") |
|
|
| 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] |
|
|
| |
| 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() |
|
|
| |
| 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() |
|
|