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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ハンドオフ版フィルターの出力(keep+review)に、当方の PII 置換(8 種)をかける独立パス。
|
| 2 |
+
|
| 3 |
+
入力の本文には配布物のマスク([EMAIL_REDACTED] 等)が既に入っているため、当方の記法へ正規化してから
|
| 4 |
+
`filter_pii.run_filter` を当てる。出力は入力と同じ列構成(url / content / perplexity)。
|
| 5 |
+
|
| 6 |
+
python tools/abeja_pii_pass.py --calibrate --files a.parquet --src-dir abeja-cc-ja/src
|
| 7 |
+
python tools/abeja_pii_pass.py --repo Podtech/abeja-cc-ja-handoff --source-prefix from_filtered \
|
| 8 |
+
--dir common_crawl_0 --src-dir /work/src --output-root /work/out/common_crawl_0 \
|
| 9 |
+
--upload-repo Podtech/abeja-cc-ja-handoff-pii --upload-prefix data
|
| 10 |
+
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import argparse
|
| 14 |
+
import collections
|
| 15 |
+
import json
|
| 16 |
+
import os
|
| 17 |
+
import re
|
| 18 |
+
import shutil
|
| 19 |
+
import sys
|
| 20 |
+
import time
|
| 21 |
+
import traceback
|
| 22 |
+
from concurrent.futures import ProcessPoolExecutor
|
| 23 |
+
from datetime import datetime, timezone
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
from typing import Any
|
| 26 |
+
|
| 27 |
+
VERSION = "abeja-pii-pass/2026-09-10"
|
| 28 |
+
|
| 29 |
+
# 配布物のマスク記法 → 当方の記法。郵便番号は当方に対応する種別が無いため <ADDRESS> に寄せる
|
| 30 |
+
PLACEHOLDER_MAP = {
|
| 31 |
+
"[EMAIL_REDACTED]": "<EMAIL>",
|
| 32 |
+
"[PHONE_REDACTED]": "<PHONE>",
|
| 33 |
+
"[POSTCODE_REDACTED]": "<ADDRESS>",
|
| 34 |
+
}
|
| 35 |
+
PLACEHOLDER_RE = re.compile("|".join(re.escape(k) for k in PLACEHOLDER_MAP))
|
| 36 |
+
|
| 37 |
+
_SRC: dict[str, Any] = {}
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _load_src(src_dir: Path) -> None:
|
| 41 |
+
"""abeja-cc-ja/src の PII モジュールを import する。"""
|
| 42 |
+
if _SRC:
|
| 43 |
+
return
|
| 44 |
+
if not (src_dir / "filter_pii.py").exists():
|
| 45 |
+
raise FileNotFoundError(f"filter_pii.py not found under {src_dir}")
|
| 46 |
+
sys.path.insert(0, str(src_dir))
|
| 47 |
+
import filter_pii
|
| 48 |
+
import pii_detector
|
| 49 |
+
|
| 50 |
+
_SRC["filter_pii"] = filter_pii
|
| 51 |
+
_SRC["pii_detector"] = pii_detector
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def normalize_placeholders(text: str) -> tuple[str, int]:
|
| 55 |
+
"""配布物のマスク記法を当方の記法へ置き換える。"""
|
| 56 |
+
if not text:
|
| 57 |
+
return text, 0
|
| 58 |
+
count = 0
|
| 59 |
+
|
| 60 |
+
def sub(match: re.Match[str]) -> str:
|
| 61 |
+
nonlocal count
|
| 62 |
+
count += 1
|
| 63 |
+
return PLACEHOLDER_MAP[match.group(0)]
|
| 64 |
+
|
| 65 |
+
return PLACEHOLDER_RE.sub(sub, text), count
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def normalize_shard(input_path: Path, output_path: Path) -> dict[str, int]:
|
| 69 |
+
"""本文と URL のプレースホルダーを正規化した parquet を書く。"""
|
| 70 |
+
import pyarrow as pa
|
| 71 |
+
import pyarrow.parquet as pq
|
| 72 |
+
|
| 73 |
+
pf = pq.ParquetFile(input_path)
|
| 74 |
+
codec = pf.metadata.row_group(0).column(0).compression if pf.metadata.num_row_groups else "SNAPPY"
|
| 75 |
+
writer = pq.ParquetWriter(output_path, pf.schema_arrow,
|
| 76 |
+
compression=codec.lower() if codec != "UNCOMPRESSED" else None)
|
| 77 |
+
stats = collections.Counter()
|
| 78 |
+
try:
|
| 79 |
+
for batch in pf.iter_batches(batch_size=2048):
|
| 80 |
+
d = batch.to_pydict()
|
| 81 |
+
for name in ("content", "url"):
|
| 82 |
+
if name not in d:
|
| 83 |
+
continue
|
| 84 |
+
values = d[name]
|
| 85 |
+
for i, value in enumerate(values):
|
| 86 |
+
if value and "_REDACTED]" in value:
|
| 87 |
+
values[i], n = normalize_placeholders(value)
|
| 88 |
+
if n:
|
| 89 |
+
stats["replacements"] += n
|
| 90 |
+
stats[f"docs_{name}"] += 1
|
| 91 |
+
cols = {name: pa.array(d[name], type=pf.schema_arrow.field(name).type)
|
| 92 |
+
for name in pf.schema_arrow.names}
|
| 93 |
+
writer.write_batch(pa.record_batch(cols, schema=pf.schema_arrow))
|
| 94 |
+
stats["rows"] += batch.num_rows
|
| 95 |
+
finally:
|
| 96 |
+
writer.close()
|
| 97 |
+
return dict(stats)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def slim_audit(src: Path, dest: Path) -> dict[str, int]:
|
| 101 |
+
"""監査 JSONL から置換後本文のコピーを落とす。本文は出力 parquet 側にあり、証跡には不要。
|
| 102 |
+
|
| 103 |
+
残すのは record_index と `_pii_*`(検出種別・一致位置・マスク済み値・手法)。
|
| 104 |
+
"""
|
| 105 |
+
dropped = ("content_replaced", "url_replaced")
|
| 106 |
+
stats = collections.Counter()
|
| 107 |
+
with src.open(encoding="utf-8") as fin, dest.open("w", encoding="utf-8", newline="\n") as fout:
|
| 108 |
+
for line in fin:
|
| 109 |
+
if not line.strip():
|
| 110 |
+
continue
|
| 111 |
+
row = json.loads(line)
|
| 112 |
+
for key in dropped:
|
| 113 |
+
row.pop(key, None)
|
| 114 |
+
fout.write(json.dumps(row, ensure_ascii=False, default=str) + "\n")
|
| 115 |
+
stats["records"] += 1
|
| 116 |
+
stats["bytes_before"] = src.stat().st_size
|
| 117 |
+
stats["bytes_after"] = dest.stat().st_size
|
| 118 |
+
return dict(stats)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def _fetch(repo: str, path_in_repo: str, local_dir: Path, attempts: int = 6) -> Path:
|
| 122 |
+
from huggingface_hub import hf_hub_download
|
| 123 |
+
for k in range(attempts):
|
| 124 |
+
try:
|
| 125 |
+
return Path(hf_hub_download(repo, path_in_repo, repo_type="dataset",
|
| 126 |
+
token=os.environ.get("HF_TOKEN"), local_dir=str(local_dir)))
|
| 127 |
+
except Exception: # noqa: BLE001
|
| 128 |
+
if k == attempts - 1:
|
| 129 |
+
raise
|
| 130 |
+
time.sleep(20 * (k + 1))
|
| 131 |
+
raise RuntimeError("unreachable")
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def process_shard(task: dict) -> dict:
|
| 135 |
+
import pyarrow.parquet as pq
|
| 136 |
+
|
| 137 |
+
started = time.perf_counter()
|
| 138 |
+
shard = task["shard"]
|
| 139 |
+
work = Path(task["staging_dir"]) / f"{shard}_pii"
|
| 140 |
+
local: Path | None = None
|
| 141 |
+
try:
|
| 142 |
+
_load_src(Path(task["src_dir"]))
|
| 143 |
+
local = _fetch(task["repo"], task["path"], Path(task["staging_dir"])) if task.get("repo") else Path(task["path"])
|
| 144 |
+
out_dir = Path(task["output_root"]) / shard
|
| 145 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 146 |
+
shutil.rmtree(work, ignore_errors=True)
|
| 147 |
+
work.mkdir(parents=True, exist_ok=True)
|
| 148 |
+
|
| 149 |
+
normalized = work / "normalized.parquet"
|
| 150 |
+
norm_stats = normalize_shard(local, normalized)
|
| 151 |
+
rows_in = pq.ParquetFile(normalized).metadata.num_rows
|
| 152 |
+
|
| 153 |
+
pii = _SRC["filter_pii"].run_filter(
|
| 154 |
+
input_path=normalized,
|
| 155 |
+
output_root=work,
|
| 156 |
+
batch_size=task["batch_size"],
|
| 157 |
+
policy_approver=task.get("policy_approver"),
|
| 158 |
+
policy_approved_on=task.get("policy_approved_on"),
|
| 159 |
+
policy_note=task.get("policy_note"),
|
| 160 |
+
)
|
| 161 |
+
replaced = work / "pii_replaced" / "replaced.parquet"
|
| 162 |
+
rows_out = pq.ParquetFile(replaced).metadata.num_rows
|
| 163 |
+
assert rows_out == rows_in, f"row count changed: {rows_in} -> {rows_out}"
|
| 164 |
+
shutil.move(str(replaced), str(out_dir / f"{shard}.parquet"))
|
| 165 |
+
audit_stats = slim_audit(work / "pii_replaced" / "audit.jsonl", out_dir / "pii_audit.jsonl")
|
| 166 |
+
|
| 167 |
+
summary = {
|
| 168 |
+
"version": VERSION, "dir": task["config"], "shard": shard,
|
| 169 |
+
"source_repo": task["repo"], "source_prefix": task["source_prefix"],
|
| 170 |
+
"rows_in": rows_in, "rows_out": rows_out,
|
| 171 |
+
"placeholder_normalization": {"map": PLACEHOLDER_MAP, **norm_stats},
|
| 172 |
+
"audit_jsonl": {"note_ja": "置換後本文のコピーは除去(出力 parquet と重複するため)", **audit_stats},
|
| 173 |
+
"pii": pii,
|
| 174 |
+
"seconds": round(time.perf_counter() - started, 1),
|
| 175 |
+
"finished_at_utc": datetime.now(timezone.utc).isoformat(),
|
| 176 |
+
}
|
| 177 |
+
(out_dir / "pii_summary.json").write_text(
|
| 178 |
+
json.dumps(summary, ensure_ascii=False, indent=2, default=str) + "\n", encoding="utf-8")
|
| 179 |
+
return summary
|
| 180 |
+
except Exception as error: # noqa: BLE001
|
| 181 |
+
return {"shard": shard, "error": repr(error), "traceback": traceback.format_exc()}
|
| 182 |
+
finally:
|
| 183 |
+
shutil.rmtree(work, ignore_errors=True)
|
| 184 |
+
if task.get("repo") and local is not None:
|
| 185 |
+
Path(local).unlink(missing_ok=True)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def upload_batch(api: Any, repo: str, prefix: str, output_root: Path, shards: list[str], delete_local: bool) -> None:
|
| 189 |
+
import re as _re
|
| 190 |
+
for attempt in range(12):
|
| 191 |
+
try:
|
| 192 |
+
api.upload_folder(repo_id=repo, repo_type="dataset", folder_path=str(output_root), path_in_repo=prefix,
|
| 193 |
+
allow_patterns=[f"{sh}/**" for sh in shards],
|
| 194 |
+
commit_message=f"{Path(prefix).name} {shards[0]}..{shards[-1]} ({len(shards)} shards)")
|
| 195 |
+
break
|
| 196 |
+
except Exception as e: # noqa: BLE001
|
| 197 |
+
msg = str(e)
|
| 198 |
+
m = _re.search(r"retry this action in (\d+) minutes", msg)
|
| 199 |
+
wait = (int(m.group(1)) * 60 + 90) if m else (120 * (attempt + 1))
|
| 200 |
+
print(json.dumps({"event": "upload_retry", "attempt": attempt + 1, "wait_s": wait, "error": msg[:160]}), flush=True)
|
| 201 |
+
if attempt == 11:
|
| 202 |
+
raise
|
| 203 |
+
time.sleep(wait)
|
| 204 |
+
if delete_local:
|
| 205 |
+
for sh in shards:
|
| 206 |
+
shutil.rmtree(output_root / sh, ignore_errors=True)
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def main(argv: list[str] | None = None) -> None:
|
| 210 |
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 211 |
+
parser.add_argument("--calibrate", action="store_true")
|
| 212 |
+
parser.add_argument("--files", default="")
|
| 213 |
+
parser.add_argument("--src-dir", type=Path, required=True, help="abeja-cc-ja/src(filter_pii.py と pii_detector.py)")
|
| 214 |
+
parser.add_argument("--repo", default=None)
|
| 215 |
+
parser.add_argument("--source-prefix", default="from_filtered")
|
| 216 |
+
parser.add_argument("--dir", default=None)
|
| 217 |
+
parser.add_argument("--output-root", type=Path, default=None)
|
| 218 |
+
parser.add_argument("--staging-dir", type=Path, default=Path("/work/staging"))
|
| 219 |
+
parser.add_argument("--batch-size", type=int, default=2048)
|
| 220 |
+
parser.add_argument("--policy-approver", default=None)
|
| 221 |
+
parser.add_argument("--policy-approved-on", default=None)
|
| 222 |
+
parser.add_argument("--policy-note", default=None)
|
| 223 |
+
parser.add_argument("--limit-shards", type=int, default=None)
|
| 224 |
+
parser.add_argument("--shard-index", type=int, default=0)
|
| 225 |
+
parser.add_argument("--shard-total", type=int, default=1)
|
| 226 |
+
parser.add_argument("--upload-repo", default=None)
|
| 227 |
+
parser.add_argument("--upload-prefix", default="data")
|
| 228 |
+
parser.add_argument("--upload-batch", type=int, default=10)
|
| 229 |
+
parser.add_argument("--skip-existing-in-repo", action="store_true")
|
| 230 |
+
parser.add_argument("--workers", type=int, default=max(1, int(os.environ.get("CPU_CORES") or os.cpu_count() or 2) - 1))
|
| 231 |
+
args = parser.parse_args(argv)
|
| 232 |
+
|
| 233 |
+
args.staging_dir.mkdir(parents=True, exist_ok=True)
|
| 234 |
+
if args.calibrate:
|
| 235 |
+
_load_src(args.src_dir)
|
| 236 |
+
for f in [x for x in args.files.split(",") if x]:
|
| 237 |
+
s = process_shard({"repo": None, "path": f, "shard": Path(f).stem, "config": "local",
|
| 238 |
+
"source_prefix": "local", "output_root": str(args.staging_dir / "out"),
|
| 239 |
+
"staging_dir": str(args.staging_dir), "src_dir": str(args.src_dir),
|
| 240 |
+
"batch_size": args.batch_size, "policy_approver": args.policy_approver,
|
| 241 |
+
"policy_approved_on": args.policy_approved_on, "policy_note": args.policy_note})
|
| 242 |
+
print(json.dumps(s, ensure_ascii=False, default=str)[:1500])
|
| 243 |
+
return
|
| 244 |
+
|
| 245 |
+
from huggingface_hub import HfApi
|
| 246 |
+
api = HfApi(token=os.environ.get("HF_TOKEN"))
|
| 247 |
+
shards = sorted({e.path.split("/")[-1] for e in api.list_repo_tree(
|
| 248 |
+
args.repo, path_in_repo=f"{args.source_prefix}/{args.dir}", repo_type="dataset", recursive=False)})
|
| 249 |
+
if args.limit_shards:
|
| 250 |
+
shards = shards[: args.limit_shards]
|
| 251 |
+
if args.shard_total > 1:
|
| 252 |
+
shards = shards[args.shard_index :: args.shard_total]
|
| 253 |
+
existing: set[str] = set()
|
| 254 |
+
if args.skip_existing_in_repo and args.upload_repo:
|
| 255 |
+
try:
|
| 256 |
+
existing = {e.path.split("/")[-1] for e in api.list_repo_tree(
|
| 257 |
+
args.upload_repo, path_in_repo=f"{args.upload_prefix}/{args.dir}", repo_type="dataset", recursive=False)}
|
| 258 |
+
except Exception: # noqa: BLE001
|
| 259 |
+
existing = set()
|
| 260 |
+
tasks = [{"repo": args.repo, "path": f"{args.source_prefix}/{args.dir}/{sh}/{sh}.parquet",
|
| 261 |
+
"shard": sh, "config": args.dir, "source_prefix": args.source_prefix,
|
| 262 |
+
"output_root": str(args.output_root), "staging_dir": str(args.staging_dir),
|
| 263 |
+
"src_dir": str(args.src_dir), "batch_size": args.batch_size,
|
| 264 |
+
"policy_approver": args.policy_approver, "policy_approved_on": args.policy_approved_on,
|
| 265 |
+
"policy_note": args.policy_note}
|
| 266 |
+
for sh in shards if sh not in existing]
|
| 267 |
+
print(json.dumps({"event": "start", "dir": args.dir, "shards": len(shards),
|
| 268 |
+
"shard_index": args.shard_index, "shard_total": args.shard_total,
|
| 269 |
+
"skipped_existing": len(shards) - len(tasks), "workers": args.workers}), flush=True)
|
| 270 |
+
pending: list[str] = []
|
| 271 |
+
failed: list[str] = []
|
| 272 |
+
with ProcessPoolExecutor(max_workers=args.workers) as ex:
|
| 273 |
+
for s in ex.map(process_shard, tasks):
|
| 274 |
+
if "error" in s:
|
| 275 |
+
failed.append(s["shard"])
|
| 276 |
+
print(json.dumps({"event": "error", **s}, ensure_ascii=False)[:800], flush=True)
|
| 277 |
+
continue
|
| 278 |
+
brief = {k: s[k] for k in ("dir", "shard", "rows_in", "rows_out", "seconds")}
|
| 279 |
+
brief["normalized"] = s["placeholder_normalization"].get("replacements", 0)
|
| 280 |
+
pii = s.get("pii") or {}
|
| 281 |
+
brief["pii_docs"] = pii.get("records_with_replacements") or pii.get("records_modified")
|
| 282 |
+
print(json.dumps({"event": "done", **brief}, ensure_ascii=False, default=str), flush=True)
|
| 283 |
+
if args.upload_repo:
|
| 284 |
+
pending.append(s["shard"])
|
| 285 |
+
if len(pending) >= args.upload_batch:
|
| 286 |
+
upload_batch(api, args.upload_repo, f"{args.upload_prefix}/{args.dir}", args.output_root, pending, True)
|
| 287 |
+
pending = []
|
| 288 |
+
if args.upload_repo and pending:
|
| 289 |
+
upload_batch(api, args.upload_repo, f"{args.upload_prefix}/{args.dir}", args.output_root, pending, True)
|
| 290 |
+
print(json.dumps({"event": "finish", "dir": args.dir, "shards": len(tasks), "failed": failed}), flush=True)
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
if __name__ == "__main__":
|
| 294 |
+
main()
|