File size: 9,066 Bytes
f9aa847
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""シャードごとの shard_summary.json を集約し、全件の件数・母数・内訳を出す。

ローカルのディレクトリ(``--root``)か、HF データセット(``--repo`` と ``--prefix``、
``outputs/**/shard_summary.json`` を取得)を入力にできる。``--expected-inputs`` に
入力データセット名を渡すと、入力シャード一覧と突き合わせて未処理シャードを列挙する。

    uv run python abeja-cc-ja/src/aggregate_summaries.py --repo Podtech/abeja-cc-ja-cleaned --prefix outputs \\
        --expected-inputs Podtech/abeja-cc-ja-filtered --output dataset_summary.json
"""

from __future__ import annotations

import argparse
import json
from collections import Counter, defaultdict
from datetime import datetime, timezone
from pathlib import Path
from typing import Any


def _load_local(root: Path, marker: str = "shard_summary.json") -> list[dict[str, Any]]:
    return [json.loads(p.read_text(encoding="utf-8")) for p in sorted(root.rglob(marker))]


def _load_repo(repo_id: str, prefix: str, marker: str = "shard_summary.json") -> list[dict[str, Any]]:
    from huggingface_hub import snapshot_download

    local = snapshot_download(repo_id, repo_type="dataset", allow_patterns=[f"{prefix.strip('/')}/**/{marker}"])
    return _load_local(Path(local) / prefix.strip("/"), marker)


def aggregate_noise(summaries: list[dict[str, Any]]) -> dict[str, Any]:
    """第2パス(noise_summary.json)の集約。パターン別・項目別・理由別に合算する。"""

    total = Counter()
    by_reason = Counter()
    by_item: dict[str, Counter] = defaultdict(Counter)
    by_pattern: dict[str, Counter] = defaultdict(Counter)
    pattern_meta: dict[str, dict[str, Any]] = {}
    thresholds: Counter = Counter()
    shards = []
    for s in summaries:
        shards.append(s["shard"])
        n = s["noise"]
        total["input_rows"] += s["input_rows"]
        for k in ("records_deleted", "records_retained", "records_modified", "records_newline_joined", "chars_before", "chars_after_retained"):
            total[k] += n.get(k) or 0
        if n.get("tokens_after_retained"):
            total["tokens_after_retained"] += n["tokens_after_retained"]
        for k, v in n["records_deleted_by_reason"].items():
            by_reason[k] += v
        for item, v in n["by_item"].items():
            for k, x in v.items():
                by_item[item][k] += x
        for p in n["patterns"]:
            pattern_meta[p["id"]] = {"item": p["item"], "action": p["action"]}
            for k in ("records_detected", "occurrences", "lines_removed", "replacements"):
                by_pattern[p["id"]][k] += p[k]
        thresholds[json.dumps(n["thresholds"], sort_keys=True, ensure_ascii=False)] += 1
    return {
        "aggregated_at_utc": datetime.now(timezone.utc).isoformat(),
        "stage": "noise",
        "shards": len(shards),
        "totals": dict(total),
        "deletion_rate": round(total["records_deleted"] / max(1, total["input_rows"]), 5),
        "records_deleted_by_reason": dict(by_reason),
        "by_item": {k: dict(v) for k, v in sorted(by_item.items(), key=lambda kv: int(kv[0]))},
        "by_pattern": {k: {**pattern_meta[k], **dict(v)} for k, v in sorted(by_pattern.items(), key=lambda kv: (pattern_meta[kv[0]]["item"], kv[0]))},
        "thresholds": [json.loads(k) for k in thresholds],
        "shard_list": sorted(shards),
    }


def _expected_shards(repo_id: str) -> set[str]:
    from huggingface_hub import HfApi

    return {Path(p).stem for p in HfApi().list_repo_files(repo_id, repo_type="dataset") if p.endswith(".parquet")}


def aggregate(summaries: list[dict[str, Any]]) -> dict[str, Any]:
    total = Counter()
    by_reason = Counter()
    by_category_match = Counter()
    by_category_deleted = Counter()
    by_source_matched = Counter()
    by_source_deleted = Counter()
    by_rule = Counter()
    pii_records = Counter()
    pii_replacements = Counter()
    seconds = Counter()
    policies = Counter()
    versions = Counter()
    shards = []
    for s in summaries:
        shards.append(s["shard"])
        versions[s.get("pipeline_version", "?")] += 1
        total["input_rows"] += s["input_rows"]
        total["toxic_deleted"] += s["toxic"]["records_deleted"]
        total["toxic_retained"] += s["toxic"]["records_retained"]
        total["pii_records_with_replacement"] += s["pii"]["records_with_replacement"]
        total["pii_total_replacements"] += s["pii"]["total_replacements"]
        total["final_rows"] += s["output"]["final_rows"]
        for k, v in s["toxic"]["records_deleted_by_reason"].items():
            by_reason[k] += v
        for c, v in s["toxic"]["by_category"].items():
            by_category_match[c] += v["records_with_match"]
            by_category_deleted[c] += v["records_deleted"]
        for name, v in (s["toxic"].get("domain_blocklist_by_source") or {}).items():
            by_source_matched[name] += v.get("records_matched", 0)
            by_source_deleted[name] += v.get("records_deleted", 0)
        for name, v in (s["toxic"].get("cooccurrence_by_rule") or {}).items():
            by_rule[name] += v.get("records_matched", 0)
        for t, v in s["pii"]["by_type"].items():
            pii_records[t] += v["records_with_match"]
            pii_replacements[t] += v["replacement_count"]
        for k, v in s["seconds"].items():
            seconds[k] += v
        p = s["pii"].get("policy") or {}
        policies[f"{p.get('action')}|{p.get('approved_by')}|{p.get('approved_on')}|{p.get('status')}"] += 1
    n = total["input_rows"] or 1
    return {
        "aggregated_at_utc": datetime.now(timezone.utc).isoformat(),
        "shards": len(shards),
        "pipeline_versions": dict(versions),
        "totals": dict(total),
        "toxic": {
            "deletion_rate": round(total["toxic_deleted"] / n, 5),
            "records_deleted_by_reason": dict(by_reason),
            "by_category": {c: {"records_with_match": by_category_match[c], "records_deleted": by_category_deleted[c]} for c in sorted(set(by_category_match) | set(by_category_deleted))},
            "domain_blocklist_by_source": {k: {"records_matched": by_source_matched[k], "records_deleted": by_source_deleted[k]} for k in sorted(by_source_matched)},
            "cooccurrence_by_rule": dict(by_rule),
        },
        "pii": {
            "denominator_records": total["toxic_retained"],
            "records_with_replacement_rate": round(total["pii_records_with_replacement"] / max(1, total["toxic_retained"]), 5),
            "by_type": {t: {"records_with_match": pii_records[t], "replacement_count": pii_replacements[t]} for t in sorted(pii_records)},
            "policies": dict(policies),
        },
        "seconds": dict(seconds),
        "shard_list": sorted(shards),
    }


def main(argv: list[str] | None = None) -> None:
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    source = parser.add_mutually_exclusive_group(required=True)
    source.add_argument("--root", type=Path)
    source.add_argument("--repo")
    parser.add_argument("--prefix", default="outputs")
    parser.add_argument("--expected-inputs", default=None, help="入力データセット(未処理シャードの検出用)")
    parser.add_argument("--stage", choices=("full", "noise"), default="full", help="noise: 第2パスの noise_summary.json を集約")
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args(argv)
    marker = "noise_summary.json" if args.stage == "noise" else "shard_summary.json"
    summaries = _load_local(args.root, marker) if args.root else _load_repo(args.repo, args.prefix, marker)
    result = aggregate_noise(summaries) if args.stage == "noise" else aggregate(summaries)
    if args.expected_inputs:
        expected = _expected_shards(args.expected_inputs)
        done = set(result["shard_list"])
        result["completeness"] = {"expected": len(expected), "done": len(done & expected), "missing": sorted(expected - done)[:200], "missing_count": len(expected - done), "unexpected": sorted(done - expected)[:50]}
    args.output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    t = result["totals"]
    if args.stage == "noise":
        print(json.dumps({"shards": result["shards"], "input_rows": t.get("input_rows"), "noise_deleted": t.get("records_deleted"), "retained": t.get("records_retained"),
                          "modified": t.get("records_modified"), "completeness": result.get("completeness", {}).get("missing_count")}, ensure_ascii=False))
    else:
        print(json.dumps({"shards": result["shards"], "input_rows": t.get("input_rows"), "toxic_deleted": t.get("toxic_deleted"), "final_rows": t.get("final_rows"),
                          "pii_replacements": t.get("pii_total_replacements"), "completeness": result.get("completeness", {}).get("missing_count")}, ensure_ascii=False))


if __name__ == "__main__":
    main()