"""監査用の全件実測(CPU): 入力データのトークン数(項目 4・33)と、第1パス削除理由の重複なし内訳(項目 34)。 * 入力 parquet(``--input-dir``、列 url/content/perplexity)を全件読み、文字数と tiktoken のトークン数を数える。 マウント(FUSE)の読み取りは断続的に失敗するため、``run_shard.stage_input`` でローカルへ退避してから読む。 * 第1パスの ``toxic/distinct_terms_3plus/removed.jsonl`` を HTTP(``--cleaned-repo``)またはローカル(``--removed-dir``)から読み、 ``_filter_deleted_by`` の組み合わせ(wordlist / domain_blocklist / cooccurrence の重複なし分割)と、 ``_filter_deleted_categories`` の主カテゴリ(固定順で 1 つに割り当て)を数える。合計は総削除件数に一致する。 出力: ``/audit_common_crawl_N.json``。``--upload-repo`` で ``/common_crawl_N.json`` に 1 コミットで置く。 uv run python abeja-cc-ja/src/audit_stats.py --input-dir <入力/common_crawl_0> --removed-dir <第1パス出力/common_crawl_0> --dir-index 0 --output-dir out --limit-shards 1 """ from __future__ import annotations import argparse import json import os import time import traceback from collections import Counter from concurrent.futures import ProcessPoolExecutor from datetime import datetime, timezone from pathlib import Path from typing import Any import pyarrow.parquet as pq from run_shard import stage_input AUDIT_VERSION = "abeja-cc-ja-audit/2026-09-07" CATEGORY_ORDER = ("adult", "violence", "discrimination", "crime", "propaganda_conspiracy", "spam") REASON_ORDER = ("wordlist", "domain_blocklist", "cooccurrence") _CONFIG: dict[str, Any] = {} _ENCODING: Any = None def _init_worker(config: dict[str, Any]) -> None: global _CONFIG _CONFIG = config def _encoding() -> Any: global _ENCODING if _ENCODING is None: import tiktoken _ENCODING = tiktoken.get_encoding(_CONFIG.get("tokenizer") or "o200k_harmony") return _ENCODING def count_tokens(encoding: Any, contents: list[str | None], num_threads: int = 1, chunk_size: int = 2000) -> int: total = 0 for start in range(0, len(contents), chunk_size): chunk = [c or "" for c in contents[start : start + chunk_size]] total += sum(len(t) for t in encoding.encode_ordinary_batch(chunk, num_threads=num_threads)) return total def _fetch_with_retry(repo: str, path_in_repo: str, local_dir: Path, attempts: int = 6) -> Path: from huggingface_hub import hf_hub_download last: Exception | None = None for attempt in range(1, attempts + 1): try: return Path(hf_hub_download(repo, path_in_repo, repo_type="dataset", local_dir=str(local_dir))) except Exception as error: # noqa: BLE001 last = error print(json.dumps({"event": "download_retry", "path": path_in_repo, "attempt": attempt, "error": repr(error)[:160]}), flush=True) time.sleep(20 * attempt) raise RuntimeError(f"download failed: {path_in_repo} ({last!r})") def reason_key(deleted_by: list[str]) -> str: return "+".join(r for r in REASON_ORDER if r in set(deleted_by)) or "(none)" def primary_category(categories: list[str]) -> str: for c in CATEGORY_ORDER: if c in categories: return c return categories[0] if categories else "(none)" def summarize_removed(path: Path) -> dict[str, Any]: by_reason = Counter(); by_primary_category = Counter(); by_category_overlap = Counter(); by_rule = Counter(); by_domain_source = Counter() n = 0 with path.open(encoding="utf-8") as handle: for line in handle: if not line.strip(): continue r = json.loads(line); n += 1 deleted_by = r.get("_filter_deleted_by") or [] by_reason[reason_key(deleted_by)] += 1 cats = r.get("_filter_deleted_categories") or [] if "wordlist" in deleted_by: by_primary_category[primary_category(cats)] += 1 for c in cats: by_category_overlap[c] += 1 for m in r.get("_filter_cooccurrence_matches") or []: by_rule[(m.get("rule") or m.get("name") or "?") if isinstance(m, dict) else str(m)] += 1 for m in r.get("_filter_domain_matches") or []: by_domain_source[(m.get("source") or m.get("list") or "?") if isinstance(m, dict) else str(m)] += 1 return {"records_deleted": n, "by_reason_partition": dict(by_reason), "wordlist_by_primary_category": dict(by_primary_category), "wordlist_by_category_overlap": dict(by_category_overlap), "cooccurrence_rule_hits": dict(by_rule), "domain_source_hits": dict(by_domain_source)} def process_shard(task: dict[str, Any]) -> dict[str, Any]: started = time.perf_counter() shard = task["shard"] try: result: dict[str, Any] = {"shard": shard} if task.get("input_repo"): local = _fetch_with_retry(task["input_repo"], task["input_path_in_repo"], Path(task["staging_dir"])) task = dict(task, input_path=str(local)) elif task.get("input_path"): local = stage_input(Path(task["input_path"]), Path(task["staging_dir"]) if task.get("staging_dir") else None) if task.get("input_path"): pf = pq.ParquetFile(local) rows = chars = tokens = 0 enc = _encoding() for batch in pf.iter_batches(batch_size=4096, columns=["content"]): contents = batch.column("content").to_pylist() rows += len(contents) chars += sum(len(c or "") for c in contents) tokens += count_tokens(enc, contents, int(_CONFIG.get("token_threads", 1))) result["input"] = {"rows": rows, "chars": chars, "tokens": tokens} if task.get("staging_dir") or task.get("input_repo"): Path(local).unlink(missing_ok=True) if task.get("removed_repo"): rp = _fetch_with_retry(task["removed_repo"], task["removed_path_in_repo"], Path(task["staging_dir"])) result["pass1_removed"] = summarize_removed(rp) rp.unlink(missing_ok=True) elif task.get("removed_path"): result["pass1_removed"] = summarize_removed(Path(task["removed_path"])) result["seconds"] = round(time.perf_counter() - started, 1) return result except Exception as error: # noqa: BLE001 return {"shard": shard, "error": repr(error), "traceback": traceback.format_exc()} def aggregate(results: list[dict[str, Any]]) -> dict[str, Any]: inp = Counter(); removed = Counter(); by_reason = Counter(); by_primary = Counter(); by_overlap = Counter(); by_rule = Counter(); by_domain = Counter() for r in results: if "error" in r: continue for k, v in (r.get("input") or {}).items(): inp[k] += v pr = r.get("pass1_removed") or {} removed["records_deleted"] += pr.get("records_deleted", 0) for name, counter in (("by_reason_partition", by_reason), ("wordlist_by_primary_category", by_primary), ("wordlist_by_category_overlap", by_overlap), ("cooccurrence_rule_hits", by_rule), ("domain_source_hits", by_domain)): for k, v in (pr.get(name) or {}).items(): counter[k] += v return {"input": dict(inp), "pass1_removed": {"records_deleted": removed["records_deleted"], "by_reason_partition": dict(by_reason), "by_reason_partition_sum": sum(by_reason.values()), "wordlist_by_primary_category": dict(by_primary), "wordlist_by_category_overlap": dict(by_overlap), "cooccurrence_rule_hits": dict(by_rule), "domain_source_hits": dict(by_domain)}} def main(argv: list[str] | None = None) -> None: parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--input-dir", type=Path, default=None, help="入力 parquet のディレクトリ(トークン数を数える。省略時は数えない)") parser.add_argument("--input-repo", default=None, help="入力 parquet を HF データセットから HTTP で取得する(マウントの代わり)") parser.add_argument("--input-repo-prefix", default="data", help="--input-repo 内の接頭辞(/common_crawl_N/.parquet)") parser.add_argument("--pattern", default="*.parquet") parser.add_argument("--removed-dir", type=Path, default=None, help="ローカルの第1パス出力(/toxic/distinct_terms_3plus/removed.jsonl か /removed.jsonl)") parser.add_argument("--cleaned-repo", default=None, help="第1パス出力を HTTP で取得する HF データセット") parser.add_argument("--cleaned-prefix", default="outputs") parser.add_argument("--dir-index", type=int, required=True) parser.add_argument("--staging-dir", type=Path, default=None) parser.add_argument("--output-dir", type=Path, required=True) parser.add_argument("--tokenizer", default="o200k_harmony") parser.add_argument("--token-threads", type=int, default=1) parser.add_argument("--workers", type=int, default=max(1, int(os.environ.get("CPU_CORES") or os.cpu_count() or 2) - 1)) parser.add_argument("--limit-shards", type=int, default=None) parser.add_argument("--upload-repo", default=None) parser.add_argument("--upload-prefix", default="reports/audit_stats") args = parser.parse_args(argv) args.output_dir.mkdir(parents=True, exist_ok=True) staging = args.staging_dir or (args.output_dir / "_staging") staging.mkdir(parents=True, exist_ok=True) shards: dict[str, dict[str, Any]] = {} if args.input_dir is not None: for p in sorted(args.input_dir.glob(args.pattern)): shards.setdefault(p.stem, {"shard": p.stem})["input_path"] = str(p) if args.input_repo: from huggingface_hub import HfApi base = f"{args.input_repo_prefix.strip('/')}/common_crawl_{args.dir_index}" for attempt in range(5): try: entries = list(HfApi().list_repo_tree(args.input_repo, path_in_repo=base, repo_type="dataset", recursive=False)); break except Exception as error: # noqa: BLE001 print(json.dumps({"event": "list_retry", "attempt": attempt + 1, "error": repr(error)[:160]}), flush=True); time.sleep(30 * (attempt + 1)) else: raise RuntimeError("list_repo_tree failed") for e in entries: name = e.path.rsplit("/", 1)[-1] if name.endswith(".parquet"): shards.setdefault(name[:-8], {"shard": name[:-8]}).update({"input_repo": args.input_repo, "input_path_in_repo": f"{base}/{name}"}) if args.removed_dir is not None: for d in sorted(x for x in args.removed_dir.iterdir() if x.is_dir()): rp = d / "toxic" / "distinct_terms_3plus" / "removed.jsonl" if not rp.exists(): rp = d / "removed.jsonl" if rp.exists(): shards.setdefault(d.name, {"shard": d.name})["removed_path"] = str(rp) elif args.cleaned_repo: from huggingface_hub import HfApi base = f"{args.cleaned_prefix}/common_crawl_{args.dir_index}" entries = list(HfApi().list_repo_tree(args.cleaned_repo, path_in_repo=base, repo_type="dataset", recursive=False)) for e in entries: if type(e).__name__ == "RepoFolder": s = e.path.rsplit("/", 1)[-1] shards.setdefault(s, {"shard": s}).update({"removed_repo": args.cleaned_repo, "removed_path_in_repo": f"{base}/{s}/toxic/distinct_terms_3plus/removed.jsonl"}) tasks = [dict(t, staging_dir=str(staging)) for _, t in sorted(shards.items())] if args.limit_shards is not None: tasks = tasks[: args.limit_shards] if not tasks: raise FileNotFoundError("対象シャードがありません") config = {"tokenizer": args.tokenizer, "token_threads": args.token_threads} print(json.dumps({"event": "start", "stage": "audit", "dir": args.dir_index, "shards": len(tasks), "workers": args.workers, "tokenizer": args.tokenizer, "count_input_tokens": args.input_dir is not None or bool(args.input_repo), "pass1_removed": bool(args.removed_dir or args.cleaned_repo)}), flush=True) run_started = time.perf_counter() progress_path = args.output_dir / f"audit_common_crawl_{args.dir_index}.progress.jsonl" results: list[dict[str, Any]] = [] done_shards: set[str] = set() if progress_path.exists(): for line in progress_path.read_text(encoding="utf-8").splitlines(): if line.strip(): r = json.loads(line); results.append(r); done_shards.add(r["shard"]) tasks = [t for t in tasks if t["shard"] not in done_shards] print(json.dumps({"event": "resume", "already_done": len(done_shards), "todo": len(tasks)}), flush=True) with ProcessPoolExecutor(max_workers=max(1, min(args.workers, max(1, len(tasks)))), initializer=_init_worker, initargs=(config,)) as pool, progress_path.open("a", encoding="utf-8") as progress: for r in (pool.map(process_shard, tasks) if tasks else []): results.append(r) if "error" not in r: progress.write(json.dumps(r, ensure_ascii=False) + "\n"); progress.flush() if "error" in r: print(json.dumps({"event": "error", "shard": r["shard"], "error": r["error"]}), flush=True) else: print(json.dumps({"event": "done", "shard": r["shard"], "input": r.get("input"), "pass1_deleted": (r.get("pass1_removed") or {}).get("records_deleted"), "seconds": r["seconds"]}), flush=True) errors = [r for r in results if "error" in r] summary = { "audit_version": AUDIT_VERSION, "dir_index": args.dir_index, "finished_at_utc": datetime.now(timezone.utc).isoformat(), "tokenizer": {"name": args.tokenizer, "library": "tiktoken", "version": __import__("tiktoken").__version__ if (args.input_dir is not None or args.input_repo) else None}, "shards_processed": len(results) - len(errors), "shards_failed": [{"shard": r["shard"], "error": r["error"]} for r in errors], "totals": aggregate(results), "per_shard": [r for r in results if "error" not in r], "seconds": round(time.perf_counter() - run_started, 1), } out = args.output_dir / f"audit_common_crawl_{args.dir_index}.json" out.write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") print(json.dumps({"event": "finish", "dir": args.dir_index, "totals": summary["totals"], "failed": len(errors), "seconds": summary["seconds"]}, ensure_ascii=False), flush=True) if args.upload_repo: from huggingface_hub import HfApi api = HfApi() for attempt in range(8): try: api.upload_file(repo_id=args.upload_repo, repo_type="dataset", path_or_fileobj=str(out), path_in_repo=f"{args.upload_prefix.strip('/')}/common_crawl_{args.dir_index}.json", commit_message=f"audit stats common_crawl_{args.dir_index}") print(json.dumps({"event": "uploaded", "path": f"{args.upload_prefix}/common_crawl_{args.dir_index}.json"}), flush=True) break except Exception as error: # noqa: BLE001 wait = min(600, 60 * (attempt + 1)) print(json.dumps({"event": "upload_retry", "attempt": attempt + 1, "error": repr(error)[:200], "wait_s": wait}), flush=True) time.sleep(wait) else: raise SystemExit("upload failed") if errors: raise SystemExit(1) if __name__ == "__main__": main()