podtech-okamura commited on
Commit
70e48c9
·
verified ·
1 Parent(s): 01fd9bf

decontam script 03607066

Browse files
code/decontam/03607066/contamination_scan.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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-v2"
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(); per_field_docs_strong: Counter = Counter(); pattern_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
+ # 設問×フィールドごとに、一致した異なり n-gram の数を数える(1 個だけの一致は定型句の可能性が高い)
86
+ hits: dict[str, dict[str, set]] = {}
87
+ doc_patterns: set[int] = set()
88
+ for _, idx in _AUTO.iter(norm):
89
+ doc_patterns.add(idx)
90
+ for ref in json.loads(_REFS[idx]):
91
+ tk, ex, field = ref.split("|", 2)
92
+ hits.setdefault(tk, {}).setdefault(f"{ex}|{field}", set()).add(idx)
93
+ if hits:
94
+ matched_docs += 1
95
+ for pid in doc_patterns: pattern_docs[pid] += 1
96
+ for tk, exf in hits.items():
97
+ per_task_docs[tk] += 1; per_task_examples.setdefault(tk, set()).update(k.split("|")[0] for k in exf)
98
+ fields_seen = {k.split("|", 1)[1] for k in exf}
99
+ for f in fields_seen: per_field_docs[f"{tk}|{f}"] += 1
100
+ strong_fields = {k.split("|", 1)[1] for k, ids in exf.items() if len(ids) >= 2}
101
+ for f in strong_fields: per_field_docs_strong[f"{tk}|{f}"] += 1
102
+ out.write(json.dumps({"file": task["path"], "row_index": offset + i, "url": (urls[i] or "")[:200] if urls[i] else None,
103
+ "tasks": {tk: {k: len(ids) for k, ids in sorted(exf.items(), key=lambda kv: -len(kv[1]))[:20]} for tk, exf in hits.items()}}, ensure_ascii=False) + "\n")
104
+ offset += len(texts)
105
+ if task.get("repo"):
106
+ local.unlink(missing_ok=True)
107
+ 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()},
108
+ "per_field_docs": dict(per_field_docs), "per_field_docs_strong": dict(per_field_docs_strong), "pattern_docs": dict(pattern_docs), "matches_file": str(out_path), "seconds": round(time.perf_counter() - started, 1)}
109
+ except Exception as error: # noqa: BLE001
110
+ return {"path": task["path"], "error": repr(error), "traceback": traceback.format_exc()}
111
+
112
+
113
+ def main(argv: list[str] | None = None) -> None:
114
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
115
+ parser.add_argument("--repo", default=None); parser.add_argument("--files", default=""); parser.add_argument("--prefix", default=None); parser.add_argument("--pattern", default="*.parquet")
116
+ parser.add_argument("--text-column", default="text"); parser.add_argument("--url-column", default="url")
117
+ parser.add_argument("--patterns", required=True, help="patterns.parquet のローカルパス")
118
+ parser.add_argument("--part", required=True); parser.add_argument("--output-dir", type=Path, required=True); parser.add_argument("--staging-dir", type=Path, default=None)
119
+ parser.add_argument("--workers", type=int, default=max(1, min(4, int(os.environ.get("CPU_CORES") or os.cpu_count() or 2) - 1)))
120
+ parser.add_argument("--limit-files", type=int, default=None)
121
+ parser.add_argument("--upload-repo", default=None); parser.add_argument("--upload-prefix", default="reports/decontam")
122
+ args = parser.parse_args(argv)
123
+ 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)
124
+ 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)
125
+ files = [f for f in args.files.split(",") if f]
126
+ if args.repo and args.prefix:
127
+ from huggingface_hub import HfApi
128
+
129
+ api = HfApi(); base = args.prefix.strip("/")
130
+ for attempt in range(5):
131
+ try:
132
+ entries = list(api.list_repo_tree(args.repo, path_in_repo=base, repo_type="dataset", recursive=True)); break
133
+ except Exception as error: # noqa: BLE001
134
+ print(json.dumps({"event": "list_retry", "attempt": attempt + 1, "error": repr(error)[:160]}), flush=True); time.sleep(30 * (attempt + 1))
135
+ else:
136
+ raise RuntimeError("list_repo_tree failed")
137
+ files = sorted(e.path for e in entries if type(e).__name__ == "RepoFile" and fnmatch.fnmatch(e.path[len(base) + 1:], args.pattern))
138
+ if args.limit_files is not None:
139
+ files = files[: args.limit_files]
140
+ if not files:
141
+ raise FileNotFoundError("対象ファイルがありません")
142
+ config = {"text_column": args.text_column, "url_column": args.url_column, "patterns": args.patterns}
143
+ n_patterns = pq.ParquetFile(args.patterns).metadata.num_rows
144
+ tasks = [{"repo": args.repo, "path": f, "staging_dir": str(staging), "matches_dir": str(matches_dir)} for f in files]
145
+ print(json.dumps({"event": "start", "part": args.part, "files": len(tasks), "workers": args.workers, "patterns": n_patterns}), flush=True)
146
+ run_started = time.perf_counter(); results = []
147
+ with ProcessPoolExecutor(max_workers=max(1, min(args.workers, len(tasks))), initializer=_init, initargs=(config,)) as pool:
148
+ for r in pool.map(process_file, tasks):
149
+ results.append(r)
150
+ 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)
151
+ ok = [r for r in results if "error" not in r]; errors = [r for r in results if "error" in r]
152
+ tot = Counter(); ptd = Counter(); pfd = Counter(); pfds = Counter(); pte: dict[str, set] = {}; pdocs: Counter = Counter()
153
+ for r in ok:
154
+ tot["rows"] += r["rows"]; tot["matched_docs"] += r["matched_docs"]
155
+ for k, v in r["per_task_docs"].items(): ptd[k] += v
156
+ for k, v in r["per_field_docs"].items(): pfd[k] += v
157
+ for k, v in r["per_field_docs_strong"].items(): pfds[k] += v
158
+ for k, v in r["per_task_examples"].items(): pte.setdefault(k, set()).update(v)
159
+ for k, v in r["pattern_docs"].items(): pdocs[int(k)] += v
160
+ import pyarrow as pa
161
+ pq.write_table(pa.table({"pattern_idx": list(pdocs.keys()), "doc_count": list(pdocs.values())}), part_dir / "pattern_docs.parquet", compression="zstd")
162
+ # 一致行をまとめる(部分ファイルは削除)
163
+ merged = part_dir / "matches.jsonl"
164
+ with merged.open("w", encoding="utf-8") as out:
165
+ for r in ok:
166
+ p = Path(r["matches_file"])
167
+ if p.exists():
168
+ out.write(p.read_text(encoding="utf-8")); p.unlink()
169
+ matches_dir.rmdir()
170
+ summary = {"version": VERSION, "part": args.part, "repo": args.repo, "prefix": args.prefix, "text_column": args.text_column, "patterns": n_patterns,
171
+ "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],
172
+ "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()},
173
+ "per_field_docs": dict(pfd), "per_field_docs_strong": dict(pfds), "seconds": round(time.perf_counter() - run_started, 1)}
174
+ (part_dir / f"{args.part}.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
175
+ 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)
176
+ if args.upload_repo:
177
+ from huggingface_hub import HfApi
178
+
179
+ api = HfApi()
180
+ for attempt in range(8):
181
+ try:
182
+ 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}")
183
+ print(json.dumps({"event": "uploaded", "path": f"{args.upload_prefix}/{args.part}"}), flush=True); break
184
+ except Exception as error: # noqa: BLE001
185
+ 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)
186
+ else:
187
+ raise SystemExit("upload failed")
188
+ if errors:
189
+ raise SystemExit(1)
190
+
191
+
192
+ if __name__ == "__main__":
193
+ main()