podtech-okamura commited on
Commit
ba6ddcc
·
verified ·
1 Parent(s): 9117e40

decontam script 96edd77a

Browse files
code/decontam/96edd77a/contamination_scan.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ベンチマーク除染の走査(CPU): 評価データ由来の文字 n-gram パターン(patterns.parquet)を Aho-Corasick でコーパス全件に当て、
2
+ 一致した文書(ファイル・行番号・URL・一致したベンチマーク/設問/フィールド)と件数を出す。
3
+
4
+ 正規化はパターン作成側と同じ: NFKC → casefold → 空白(全角含む)を全削除。
5
+
6
+ python contamination_scan.py --repo Podtech/abeja-cc-ja-cleaned --prefix outputs_v4/common_crawl_0 --pattern "*/*.parquet" --text-column content \
7
+ --patterns patterns.parquet --part abeja_0 --output-dir out
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import fnmatch
14
+ import json
15
+ import os
16
+ import re
17
+ import time
18
+ import traceback
19
+ import unicodedata
20
+ from collections import Counter
21
+ from concurrent.futures import ProcessPoolExecutor
22
+ from datetime import datetime, timezone
23
+ from pathlib import Path
24
+ from typing import Any
25
+
26
+ import pyarrow.parquet as pq
27
+
28
+ VERSION = "contamination-scan/2026-09-07"
29
+ _WS = re.compile(r"\s+")
30
+ _CFG: dict[str, Any] = {}
31
+ _AUTO: Any = None
32
+ _REFS: list[str] = []
33
+
34
+
35
+ def normalize(text: str) -> str:
36
+ return _WS.sub("", unicodedata.normalize("NFKC", text or "").casefold())
37
+
38
+
39
+ def _init(config: dict[str, Any]) -> None:
40
+ global _CFG, _AUTO, _REFS
41
+ import ahocorasick
42
+
43
+ _CFG = config
44
+ t = pq.read_table(config["patterns"], columns=["ngram", "refs"])
45
+ A = ahocorasick.Automaton()
46
+ _REFS = t.column("refs").to_pylist()
47
+ for i, ng in enumerate(t.column("ngram").to_pylist()):
48
+ A.add_word(ng, i)
49
+ A.make_automaton()
50
+ _AUTO = A
51
+
52
+
53
+ def _fetch(repo: str, path_in_repo: str, local_dir: Path, attempts: int = 6) -> Path:
54
+ from huggingface_hub import hf_hub_download
55
+
56
+ last: Exception | None = None
57
+ for attempt in range(1, attempts + 1):
58
+ try:
59
+ return Path(hf_hub_download(repo, path_in_repo, repo_type="dataset", local_dir=str(local_dir)))
60
+ except Exception as error: # noqa: BLE001
61
+ last = error
62
+ print(json.dumps({"event": "download_retry", "path": path_in_repo, "attempt": attempt, "error": repr(error)[:160]}), flush=True)
63
+ time.sleep(20 * attempt)
64
+ raise RuntimeError(f"download failed: {path_in_repo} ({last!r})")
65
+
66
+
67
+ def process_file(task: dict[str, Any]) -> dict[str, Any]:
68
+ started = time.perf_counter()
69
+ try:
70
+ local = _fetch(task["repo"], task["path"], Path(task["staging_dir"])) if task.get("repo") else Path(task["path"])
71
+ text_col = _CFG["text_column"]; url_col = _CFG.get("url_column")
72
+ pf = pq.ParquetFile(local)
73
+ cols = [text_col] + ([url_col] if url_col and url_col in pf.schema_arrow.names else [])
74
+ rows = 0; matched_docs = 0; per_task_docs: Counter = Counter(); per_task_examples: dict[str, set] = {}; per_field_docs: Counter = Counter()
75
+ out_path = Path(task["matches_dir"]) / (re.sub(r"[^A-Za-z0-9_.-]", "_", task["path"]) + ".matches.jsonl")
76
+ with out_path.open("w", encoding="utf-8") as out:
77
+ offset = 0
78
+ for batch in pf.iter_batches(batch_size=2048, columns=cols):
79
+ texts = batch.column(text_col).to_pylist(); urls = batch.column(url_col).to_pylist() if len(cols) > 1 else [None] * len(texts)
80
+ for i, text in enumerate(texts):
81
+ rows += 1
82
+ if not text:
83
+ continue
84
+ norm = normalize(text)
85
+ hits: dict[str, set] = {}
86
+ for _, idx in _AUTO.iter(norm):
87
+ for ref in json.loads(_REFS[idx]):
88
+ tk, ex, field = ref.split("|", 2)
89
+ hits.setdefault(tk, set()).add((ex, field))
90
+ if hits:
91
+ matched_docs += 1
92
+ for tk, exs in hits.items():
93
+ per_task_docs[tk] += 1; per_task_examples.setdefault(tk, set()).update(e for e, _ in exs)
94
+ for _, f in exs: per_field_docs[f"{tk}|{f}"] += 1
95
+ out.write(json.dumps({"file": task["path"], "row_index": offset + i, "url": (urls[i] or "")[:200] if urls[i] else None,
96
+ "tasks": {tk: sorted(f"{e}|{f}" for e, f in exs)[:20] for tk, exs in hits.items()}}, ensure_ascii=False) + "\n")
97
+ offset += len(texts)
98
+ if task.get("repo"):
99
+ local.unlink(missing_ok=True)
100
+ 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()},
101
+ "per_field_docs": dict(per_field_docs), "matches_file": str(out_path), "seconds": round(time.perf_counter() - started, 1)}
102
+ except Exception as error: # noqa: BLE001
103
+ return {"path": task["path"], "error": repr(error), "traceback": traceback.format_exc()}
104
+
105
+
106
+ def main(argv: list[str] | None = None) -> None:
107
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
108
+ parser.add_argument("--repo", default=None); parser.add_argument("--files", default=""); parser.add_argument("--prefix", default=None); parser.add_argument("--pattern", default="*.parquet")
109
+ parser.add_argument("--text-column", default="text"); parser.add_argument("--url-column", default="url")
110
+ parser.add_argument("--patterns", required=True, help="patterns.parquet のローカルパス")
111
+ parser.add_argument("--part", required=True); parser.add_argument("--output-dir", type=Path, required=True); parser.add_argument("--staging-dir", type=Path, default=None)
112
+ parser.add_argument("--workers", type=int, default=max(1, min(4, int(os.environ.get("CPU_CORES") or os.cpu_count() or 2) - 1)))
113
+ parser.add_argument("--limit-files", type=int, default=None)
114
+ parser.add_argument("--upload-repo", default=None); parser.add_argument("--upload-prefix", default="reports/decontam")
115
+ args = parser.parse_args(argv)
116
+ 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)
117
+ 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)
118
+ files = [f for f in args.files.split(",") if f]
119
+ if args.repo and args.prefix:
120
+ from huggingface_hub import HfApi
121
+
122
+ api = HfApi(); base = args.prefix.strip("/")
123
+ for attempt in range(5):
124
+ try:
125
+ entries = list(api.list_repo_tree(args.repo, path_in_repo=base, repo_type="dataset", recursive=True)); break
126
+ except Exception as error: # noqa: BLE001
127
+ print(json.dumps({"event": "list_retry", "attempt": attempt + 1, "error": repr(error)[:160]}), flush=True); time.sleep(30 * (attempt + 1))
128
+ else:
129
+ raise RuntimeError("list_repo_tree failed")
130
+ files = sorted(e.path for e in entries if type(e).__name__ == "RepoFile" and fnmatch.fnmatch(e.path[len(base) + 1:], args.pattern))
131
+ if args.limit_files is not None:
132
+ files = files[: args.limit_files]
133
+ if not files:
134
+ raise FileNotFoundError("対象ファイルがありません")
135
+ config = {"text_column": args.text_column, "url_column": args.url_column, "patterns": args.patterns}
136
+ n_patterns = pq.ParquetFile(args.patterns).metadata.num_rows
137
+ tasks = [{"repo": args.repo, "path": f, "staging_dir": str(staging), "matches_dir": str(matches_dir)} for f in files]
138
+ print(json.dumps({"event": "start", "part": args.part, "files": len(tasks), "workers": args.workers, "patterns": n_patterns}), flush=True)
139
+ run_started = time.perf_counter(); results = []
140
+ with ProcessPoolExecutor(max_workers=max(1, min(args.workers, len(tasks))), initializer=_init, initargs=(config,)) as pool:
141
+ for r in pool.map(process_file, tasks):
142
+ results.append(r)
143
+ 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)
144
+ ok = [r for r in results if "error" not in r]; errors = [r for r in results if "error" in r]
145
+ tot = Counter(); ptd = Counter(); pfd = Counter(); pte: dict[str, set] = {}
146
+ for r in ok:
147
+ tot["rows"] += r["rows"]; tot["matched_docs"] += r["matched_docs"]
148
+ for k, v in r["per_task_docs"].items(): ptd[k] += v
149
+ for k, v in r["per_field_docs"].items(): pfd[k] += v
150
+ for k, v in r["per_task_examples"].items(): pte.setdefault(k, set()).update(v)
151
+ # 一致行をまとめる(部分ファイルは削除)
152
+ merged = part_dir / "matches.jsonl"
153
+ with merged.open("w", encoding="utf-8") as out:
154
+ for r in ok:
155
+ p = Path(r["matches_file"])
156
+ if p.exists():
157
+ out.write(p.read_text(encoding="utf-8")); p.unlink()
158
+ matches_dir.rmdir()
159
+ summary = {"version": VERSION, "part": args.part, "repo": args.repo, "prefix": args.prefix, "text_column": args.text_column, "patterns": n_patterns,
160
+ "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],
161
+ "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()},
162
+ "per_field_docs": dict(pfd), "seconds": round(time.perf_counter() - run_started, 1)}
163
+ (part_dir / f"{args.part}.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
164
+ 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)
165
+ if args.upload_repo:
166
+ from huggingface_hub import HfApi
167
+
168
+ api = HfApi()
169
+ for attempt in range(8):
170
+ try:
171
+ 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}")
172
+ print(json.dumps({"event": "uploaded", "path": f"{args.upload_prefix}/{args.part}"}), flush=True); break
173
+ except Exception as error: # noqa: BLE001
174
+ 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)
175
+ else:
176
+ raise SystemExit("upload failed")
177
+ if errors:
178
+ raise SystemExit(1)
179
+
180
+
181
+ if __name__ == "__main__":
182
+ main()