Download code/decontam/96edd77a/contamination_scan.py from Podtech/abeja-cc-ja-cleaned: direct link, hf CLI and curl.
- Browser
- Download file 10.9 kB
-
https://huggingface.co/datasets/Podtech/abeja-cc-ja-cleaned/resolve/main/code/decontam/96edd77a/contamination_scan.py
- Command line
-
hf download hf://datasets/Podtech/abeja-cc-ja-cleaned/code/decontam/96edd77a/contamination_scan.py
-
curl -L -o contamination_scan.py https://huggingface.co/datasets/Podtech/abeja-cc-ja-cleaned/resolve/main/code/decontam/96edd77a/contamination_scan.py
10.9 kB
| """ベンチマーク除染の走査(CPU): 評価データ由来の文字 n-gram パターン(patterns.parquet)を Aho-Corasick でコーパス全件に当て、 | |
| 一致した文書(ファイル・行番号・URL・一致したベンチマーク/設問/フィールド)と件数を出す。 | |
| 正規化はパターン作成側と同じ: NFKC → casefold → 空白(全角含む)を全削除。 | |
| python contamination_scan.py --repo Podtech/abeja-cc-ja-cleaned --prefix outputs_v4/common_crawl_0 --pattern "*/*.parquet" --text-column content \ | |
| --patterns patterns.parquet --part abeja_0 --output-dir out | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import fnmatch | |
| import json | |
| import os | |
| import re | |
| import time | |
| import traceback | |
| import unicodedata | |
| 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 | |
| VERSION = "contamination-scan/2026-09-07" | |
| _WS = re.compile(r"\s+") | |
| _CFG: dict[str, Any] = {} | |
| _AUTO: Any = None | |
| _REFS: list[str] = [] | |
| def normalize(text: str) -> str: | |
| return _WS.sub("", unicodedata.normalize("NFKC", text or "").casefold()) | |
| def _init(config: dict[str, Any]) -> None: | |
| global _CFG, _AUTO, _REFS | |
| import ahocorasick | |
| _CFG = config | |
| t = pq.read_table(config["patterns"], columns=["ngram", "refs"]) | |
| A = ahocorasick.Automaton() | |
| _REFS = t.column("refs").to_pylist() | |
| for i, ng in enumerate(t.column("ngram").to_pylist()): | |
| A.add_word(ng, i) | |
| A.make_automaton() | |
| _AUTO = A | |
| def _fetch(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 process_file(task: dict[str, Any]) -> dict[str, Any]: | |
| started = time.perf_counter() | |
| try: | |
| local = _fetch(task["repo"], task["path"], Path(task["staging_dir"])) if task.get("repo") else Path(task["path"]) | |
| text_col = _CFG["text_column"]; url_col = _CFG.get("url_column") | |
| pf = pq.ParquetFile(local) | |
| cols = [text_col] + ([url_col] if url_col and url_col in pf.schema_arrow.names else []) | |
| rows = 0; matched_docs = 0; per_task_docs: Counter = Counter(); per_task_examples: dict[str, set] = {}; per_field_docs: Counter = Counter() | |
| out_path = Path(task["matches_dir"]) / (re.sub(r"[^A-Za-z0-9_.-]", "_", task["path"]) + ".matches.jsonl") | |
| with out_path.open("w", encoding="utf-8") as out: | |
| offset = 0 | |
| for batch in pf.iter_batches(batch_size=2048, columns=cols): | |
| texts = batch.column(text_col).to_pylist(); urls = batch.column(url_col).to_pylist() if len(cols) > 1 else [None] * len(texts) | |
| for i, text in enumerate(texts): | |
| rows += 1 | |
| if not text: | |
| continue | |
| norm = normalize(text) | |
| hits: dict[str, set] = {} | |
| for _, idx in _AUTO.iter(norm): | |
| for ref in json.loads(_REFS[idx]): | |
| tk, ex, field = ref.split("|", 2) | |
| hits.setdefault(tk, set()).add((ex, field)) | |
| if hits: | |
| matched_docs += 1 | |
| for tk, exs in hits.items(): | |
| per_task_docs[tk] += 1; per_task_examples.setdefault(tk, set()).update(e for e, _ in exs) | |
| for _, f in exs: per_field_docs[f"{tk}|{f}"] += 1 | |
| out.write(json.dumps({"file": task["path"], "row_index": offset + i, "url": (urls[i] or "")[:200] if urls[i] else None, | |
| "tasks": {tk: sorted(f"{e}|{f}" for e, f in exs)[:20] for tk, exs in hits.items()}}, ensure_ascii=False) + "\n") | |
| offset += len(texts) | |
| if task.get("repo"): | |
| local.unlink(missing_ok=True) | |
| return {"path": task["path"], "rows": rows, "matched_docs": matched_docs, "per_task_docs": dict(per_task_docs), "per_task_examples": {k: sorted(v) for k, v in per_task_examples.items()}, | |
| "per_field_docs": dict(per_field_docs), "matches_file": str(out_path), "seconds": round(time.perf_counter() - started, 1)} | |
| except Exception as error: # noqa: BLE001 | |
| return {"path": task["path"], "error": repr(error), "traceback": traceback.format_exc()} | |
| def main(argv: list[str] | None = None) -> None: | |
| parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| parser.add_argument("--repo", default=None); parser.add_argument("--files", default=""); parser.add_argument("--prefix", default=None); parser.add_argument("--pattern", default="*.parquet") | |
| parser.add_argument("--text-column", default="text"); parser.add_argument("--url-column", default="url") | |
| parser.add_argument("--patterns", required=True, help="patterns.parquet のローカルパス") | |
| parser.add_argument("--part", required=True); parser.add_argument("--output-dir", type=Path, required=True); parser.add_argument("--staging-dir", type=Path, default=None) | |
| parser.add_argument("--workers", type=int, default=max(1, min(4, int(os.environ.get("CPU_CORES") or os.cpu_count() or 2) - 1))) | |
| parser.add_argument("--limit-files", type=int, default=None) | |
| parser.add_argument("--upload-repo", default=None); parser.add_argument("--upload-prefix", default="reports/decontam") | |
| 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) | |
| part_dir = args.output_dir / args.part; part_dir.mkdir(parents=True, exist_ok=True); matches_dir = part_dir / "matches"; matches_dir.mkdir(parents=True, exist_ok=True) | |
| files = [f for f in args.files.split(",") if f] | |
| if args.repo and args.prefix: | |
| from huggingface_hub import HfApi | |
| api = HfApi(); base = args.prefix.strip("/") | |
| for attempt in range(5): | |
| try: | |
| entries = list(api.list_repo_tree(args.repo, path_in_repo=base, repo_type="dataset", recursive=True)); 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") | |
| files = sorted(e.path for e in entries if type(e).__name__ == "RepoFile" and fnmatch.fnmatch(e.path[len(base) + 1:], args.pattern)) | |
| if args.limit_files is not None: | |
| files = files[: args.limit_files] | |
| if not files: | |
| raise FileNotFoundError("対象ファイルがありません") | |
| config = {"text_column": args.text_column, "url_column": args.url_column, "patterns": args.patterns} | |
| n_patterns = pq.ParquetFile(args.patterns).metadata.num_rows | |
| tasks = [{"repo": args.repo, "path": f, "staging_dir": str(staging), "matches_dir": str(matches_dir)} for f in files] | |
| print(json.dumps({"event": "start", "part": args.part, "files": len(tasks), "workers": args.workers, "patterns": n_patterns}), flush=True) | |
| run_started = time.perf_counter(); results = [] | |
| with ProcessPoolExecutor(max_workers=max(1, min(args.workers, len(tasks))), initializer=_init, initargs=(config,)) as pool: | |
| for r in pool.map(process_file, tasks): | |
| results.append(r) | |
| print(json.dumps({"event": "error" if "error" in r else "done", **{k: r.get(k) for k in ("path", "rows", "matched_docs", "seconds", "error")}}), flush=True) | |
| ok = [r for r in results if "error" not in r]; errors = [r for r in results if "error" in r] | |
| tot = Counter(); ptd = Counter(); pfd = Counter(); pte: dict[str, set] = {} | |
| for r in ok: | |
| tot["rows"] += r["rows"]; tot["matched_docs"] += r["matched_docs"] | |
| for k, v in r["per_task_docs"].items(): ptd[k] += v | |
| for k, v in r["per_field_docs"].items(): pfd[k] += v | |
| for k, v in r["per_task_examples"].items(): pte.setdefault(k, set()).update(v) | |
| # 一致行をまとめる(部分ファイルは削除) | |
| merged = part_dir / "matches.jsonl" | |
| with merged.open("w", encoding="utf-8") as out: | |
| for r in ok: | |
| p = Path(r["matches_file"]) | |
| if p.exists(): | |
| out.write(p.read_text(encoding="utf-8")); p.unlink() | |
| matches_dir.rmdir() | |
| summary = {"version": VERSION, "part": args.part, "repo": args.repo, "prefix": args.prefix, "text_column": args.text_column, "patterns": n_patterns, | |
| "finished_at_utc": datetime.now(timezone.utc).isoformat(), "files": len(files), "files_ok": len(ok), "files_failed": [{"path": r["path"], "error": r["error"]} for r in errors], | |
| "totals": dict(tot), "per_task_docs": dict(ptd), "per_task_examples_matched": {k: len(v) for k, v in pte.items()}, "per_task_examples": {k: sorted(v)[:5000] for k, v in pte.items()}, | |
| "per_field_docs": dict(pfd), "seconds": round(time.perf_counter() - run_started, 1)} | |
| (part_dir / f"{args.part}.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") | |
| print(json.dumps({"event": "finish", "part": args.part, "totals": summary["totals"], "per_task_docs": summary["per_task_docs"], "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_folder(repo_id=args.upload_repo, repo_type="dataset", folder_path=str(part_dir), path_in_repo=f"{args.upload_prefix.strip('/')}/{args.part}", commit_message=f"decontam {args.part}") | |
| print(json.dumps({"event": "uploaded", "path": f"{args.upload_prefix}/{args.part}"}), 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() | |