"""シャードごとの 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) -> list[dict[str, Any]]: return [json.loads(p.read_text(encoding="utf-8")) for p in sorted(root.rglob("shard_summary.json"))] def _load_repo(repo_id: str, prefix: str) -> list[dict[str, Any]]: from huggingface_hub import snapshot_download local = snapshot_download(repo_id, repo_type="dataset", allow_patterns=[f"{prefix.strip('/')}/**/shard_summary.json"]) return _load_local(Path(local) / prefix.strip("/")) 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("--output", type=Path, required=True) args = parser.parse_args(argv) summaries = _load_local(args.root) if args.root else _load_repo(args.repo, args.prefix) result = 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"] 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()