Download code/3c1a8da/src/run_shard.py from Podtech/abeja-cc-ja-cleaned: direct link, hf CLI and curl.
- Browser
- Download file 19.6 kB
-
https://huggingface.co/datasets/Podtech/abeja-cc-ja-cleaned/resolve/main/code/3c1a8da/src/run_shard.py
- Command line
-
hf download hf://datasets/Podtech/abeja-cc-ja-cleaned/code/3c1a8da/src/run_shard.py
-
curl -L -o run_shard.py https://huggingface.co/datasets/Podtech/abeja-cc-ja-cleaned/resolve/main/code/3c1a8da/src/run_shard.py
19.6 kB
| """シャード単位のクレンジングパイプライン(本実行用)。 | |
| 1ファイル(parquet)ごとに次を行う。 | |
| 1. 有害コンテンツフィルタ(ワードリスト・ドメインブロックリスト・近接共起規則) | |
| 2. 保持分に PII 置換 | |
| 3. クリーン済み parquet と監査ファイル(removed.jsonl, audit.jsonl 等)を | |
| ``<output-root>/<シャード名>/`` に書き出し、``shard_summary.json`` にまとめる | |
| 4. 任意で HF データセットへバッチアップロード(``--upload-repo``)。アップロード後に | |
| ローカルを削除すれば、HF Jobs の一時ディスク(50 GB)でも全シャードを処理できる | |
| ``--workers`` でシャード並列に処理する。各ワーカーはワードリスト・ブロックリスト・ | |
| 共起規則を1回だけ読み込む(UT1 adult リストで約1.6 GB/ワーカー)。 | |
| ``shard_summary.json`` が既にあるシャードと、``--skip-existing-in-repo`` で | |
| リポジトリに既に出力があるシャードは飛ばすので、途中終了後の再実行ができる。 | |
| uv run python abeja-cc-ja/src/run_shard.py --input-dir <dir> --output-root <out> --workers 7 \\ | |
| --upload-repo Podtech/abeja-cc-ja-cleaned --upload-prefix outputs/common_crawl_0 --delete-local-after-upload | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import multiprocessing as mp | |
| import os | |
| import shutil | |
| import time | |
| import traceback | |
| from datetime import datetime, timezone | |
| from pathlib import Path | |
| from typing import Any | |
| import pyarrow.parquet as pq | |
| PIPELINE_VERSION = "abeja-cc-ja-cleansing/2026-09-04" | |
| MODE = "distinct_terms_3plus" | |
| _WORKER: dict[str, Any] = {} | |
| def _init_worker(config: dict[str, Any]) -> None: | |
| """ワーカー起動時にリソースを1回だけ読み込む。""" | |
| import sys | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| from cooccurrence import CooccurrenceDetector, load_rules | |
| from domain_blocklist import DomainBlocklist | |
| _WORKER["config"] = config | |
| _WORKER["blocklist"] = None if config["no_blocklist"] else DomainBlocklist.load(Path(config["blocklist_dir"]), Path(config["blocklist_cache_dir"])) | |
| _WORKER["cooccurrence"] = None if config["no_cooccurrence"] else CooccurrenceDetector(load_rules(Path(config["cooccurrence_rules"]))) | |
| def process_shard(input_path: Path, output_root: Path, config: dict[str, Any]) -> dict[str, Any]: | |
| """1シャードを処理し、shard_summary を返す(ワーカー内で実行)。""" | |
| from filter_pii import run_filter as run_pii | |
| from filter_toxic import run_toxic_filters | |
| if not _WORKER: | |
| _init_worker(config) | |
| shard = input_path.stem | |
| out_dir = output_root / shard | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| started = time.perf_counter() | |
| started_at = datetime.now(timezone.utc).isoformat() | |
| input_rows = pq.ParquetFile(input_path).metadata.num_rows | |
| t0 = time.perf_counter() | |
| toxic = run_toxic_filters( | |
| input_path=input_path, | |
| output_root=out_dir / "toxic", | |
| reference_dir=Path(config["reference_dir"]), | |
| additional_dir=Path(config["additional_dir"]), | |
| batch_size=config["batch_size"], | |
| modes=[MODE], | |
| exclude_dir=Path(config["exclude_dir"]), | |
| blocklist=_WORKER["blocklist"], | |
| cooccurrence=_WORKER["cooccurrence"], | |
| ) | |
| toxic_seconds = time.perf_counter() - t0 | |
| toxic_mode = toxic["modes"][MODE] | |
| retained_path = out_dir / "toxic" / MODE / "retained.parquet" | |
| t0 = time.perf_counter() | |
| pii = run_pii( | |
| input_path=retained_path, | |
| output_root=out_dir / "pii", | |
| batch_size=config["batch_size"], | |
| policy_approver=config.get("policy_approver"), | |
| policy_approved_on=config.get("policy_approved_on"), | |
| policy_note=config.get("policy_note"), | |
| ) | |
| pii_seconds = time.perf_counter() - t0 | |
| final_path = out_dir / f"{shard}.parquet" | |
| shutil.move(str(out_dir / "pii" / "pii_replaced" / "replaced.parquet"), str(final_path)) | |
| if not config.get("keep_intermediate"): | |
| retained_path.unlink(missing_ok=True) | |
| final_rows = pq.ParquetFile(final_path).metadata.num_rows | |
| summary = { | |
| "pipeline_version": PIPELINE_VERSION, | |
| "shard": shard, | |
| "input_file": str(input_path), | |
| "input_rows": input_rows, | |
| "started_at_utc": started_at, | |
| "finished_at_utc": datetime.now(timezone.utc).isoformat(), | |
| "seconds": {"toxic": round(toxic_seconds, 1), "pii": round(pii_seconds, 1), "total": round(time.perf_counter() - started, 1)}, | |
| "toxic": { | |
| "mode": MODE, | |
| "threshold": toxic_mode["threshold"], | |
| "category_thresholds": toxic_mode.get("category_thresholds", {}), | |
| "records_scanned": toxic_mode["total_records_scanned"], | |
| "records_deleted": toxic_mode["records_deleted"], | |
| "records_retained": toxic_mode["records_retained"], | |
| "records_deleted_by_reason": toxic_mode["records_deleted_by_reason"], | |
| "by_category": {c: {"records_with_match": v["records_with_match"], "records_deleted": v["records_deleted"]} for c, v in toxic_mode["by_category"].items()}, | |
| "domain_blocklist_by_source": {k: v for k, v in toxic_mode.get("domain_blocklist", {}).get("by_source", {}).items()}, | |
| "domain_blocklist_sources": toxic_mode.get("domain_blocklist", {}).get("sources"), | |
| "cooccurrence_by_rule": {k: {"records_matched": v["records_matched"]} for k, v in toxic_mode.get("cooccurrence", {}).get("by_rule", {}).items()}, | |
| "wordlist_excluded_terms_by_category": toxic_mode.get("wordlist_excluded_terms_by_category"), | |
| "wordlist_unique_terms_by_category": toxic.get("wordlist_unique_terms_by_category"), | |
| }, | |
| "pii": { | |
| "records_scanned": pii["total_records_scanned"], | |
| "records_with_replacement": pii["records_with_replacement"], | |
| "total_replacements": pii["total_replacements"], | |
| "by_type": {k: {"records_with_match": v["records_with_match"], "replacement_count": v["replacement_count"]} for k, v in pii["by_type"].items()}, | |
| "policy": pii["pii_policy"], | |
| "detector_version": pii.get("detector_version"), | |
| }, | |
| "output": { | |
| "cleaned_parquet": str(final_path), | |
| "final_rows": final_rows, | |
| "removed_jsonl": str(out_dir / "toxic" / MODE / "removed.jsonl"), | |
| "cooccurrence_review_jsonl": str(out_dir / "toxic" / MODE / "cooccurrence_review.jsonl"), | |
| "flagged_jsonl": str(out_dir / "toxic" / MODE / "flagged.jsonl"), | |
| "borderline_jsonl": str(out_dir / "toxic" / MODE / "borderline.jsonl"), | |
| "pii_audit_jsonl": str(out_dir / "pii" / "pii_replaced" / "audit.jsonl"), | |
| }, | |
| } | |
| (out_dir / "shard_summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") | |
| return summary | |
| def stage_input(input_path: Path, staging_dir: Path | None, attempts: int = 5, wait_seconds: int = 20) -> Path: | |
| """マウントされたデータセット(FUSE)は読み取り中に I/O エラー(errno 5)を起こすことがあるため、 | |
| まずローカルディスクへコピーしてから処理する。コピー自体も再試行する。""" | |
| if staging_dir is None: | |
| return input_path | |
| staging_dir.mkdir(parents=True, exist_ok=True) | |
| local = staging_dir / input_path.name | |
| last_error: Exception | None = None | |
| for attempt in range(1, attempts + 1): | |
| try: | |
| shutil.copyfile(input_path, local) | |
| if local.stat().st_size == input_path.stat().st_size: | |
| return local | |
| last_error = OSError(f"size mismatch after copy: {local}") | |
| except OSError as error: | |
| last_error = error | |
| print(json.dumps({"event": "stage_retry", "shard": input_path.stem, "attempt": attempt, "error": repr(last_error)[:160]}), flush=True) | |
| time.sleep(wait_seconds * attempt) | |
| raise OSError(f"入力の退避に失敗しました: {input_path} ({last_error!r})") | |
| def _worker_entry(args: tuple[str, str, dict[str, Any]]) -> dict[str, Any]: | |
| input_path, output_root, config = args | |
| staging_dir = Path(config["staging_dir"]) if config.get("staging_dir") else None | |
| local_input: Path | None = None | |
| last_error: Exception | None = None | |
| for attempt in range(1, 4): | |
| try: | |
| local_input = stage_input(Path(input_path), staging_dir) | |
| result = process_shard(local_input, Path(output_root), config) | |
| result["input_file"] = input_path | |
| return result | |
| except OSError as error: # マウント由来の I/O エラーは間を置いて再試行 | |
| last_error = error | |
| print(json.dumps({"event": "io_retry", "shard": Path(input_path).stem, "attempt": attempt, "error": repr(error)[:160]}), flush=True) | |
| time.sleep(30 * attempt) | |
| except Exception as error: # noqa: BLE001 - 1シャードの失敗で全体を止めない | |
| return {"shard": Path(input_path).stem, "input_file": input_path, "error": repr(error), "traceback": traceback.format_exc()} | |
| finally: | |
| if local_input is not None and staging_dir is not None and local_input != Path(input_path): | |
| local_input.unlink(missing_ok=True) | |
| return {"shard": Path(input_path).stem, "input_file": input_path, "error": repr(last_error), "traceback": ""} | |
| class Uploader: | |
| """完了したシャードのディレクトリをまとめて HF データセットへアップロードする。""" | |
| def __init__(self, repo_id: str, prefix: str, output_root: Path, batch: int, delete_local: bool, private: bool = True) -> None: | |
| from huggingface_hub import HfApi | |
| self.api = HfApi() | |
| self.repo_id = repo_id | |
| self.prefix = prefix.strip("/") | |
| self.output_root = output_root | |
| self.batch = max(1, batch) | |
| self.delete_local = delete_local | |
| self.pending: list[str] = [] | |
| self.uploaded: list[str] = [] | |
| self.api.create_repo(repo_id, repo_type="dataset", private=private, exist_ok=True) | |
| def existing_shards(self, marker: str = "shard_summary.json") -> set[str]: | |
| """接頭辞直下のディレクトリ名を返す。全ファイル一覧はリポジトリが数万ファイルになると数分かかるため使わない。 | |
| シャードは upload_folder で1コミットにまとめるので、ディレクトリの存在=完了とみなす。""" | |
| for attempt in range(5): | |
| try: | |
| entries = self.api.list_repo_tree(self.repo_id, path_in_repo=self.prefix, repo_type="dataset", recursive=False) | |
| return {e.path.rsplit("/", 1)[-1] for e in entries if type(e).__name__ == "RepoFolder"} | |
| except Exception as error: # noqa: BLE001 | |
| if "404" in repr(error) or "not found" in repr(error).lower(): | |
| return set() | |
| time.sleep(30 * (attempt + 1)) | |
| raise RuntimeError("list_repo_tree failed after retries") | |
| def add(self, shard: str) -> None: | |
| self.pending.append(shard) | |
| if len(self.pending) >= self.batch: | |
| self.flush() | |
| def flush(self) -> None: | |
| if not self.pending: | |
| return | |
| shards = list(self.pending) | |
| for attempt in range(5): | |
| try: | |
| self.api.upload_folder( | |
| repo_id=self.repo_id, | |
| repo_type="dataset", | |
| folder_path=str(self.output_root), | |
| path_in_repo=self.prefix, | |
| allow_patterns=[f"{shard}/**" for shard in shards], | |
| commit_message=f"add {len(shards)} shard(s): {shards[0]}..{shards[-1]}", | |
| ) | |
| break | |
| except Exception as error: # noqa: BLE001 | |
| wait = 30 * (attempt + 1) | |
| print(json.dumps({"event": "upload_retry", "attempt": attempt + 1, "error": repr(error), "wait_s": wait}), flush=True) | |
| time.sleep(wait) | |
| else: | |
| raise RuntimeError(f"アップロードに失敗しました: {shards}") | |
| self.uploaded.extend(shards) | |
| self.pending.clear() | |
| print(json.dumps({"event": "uploaded", "shards": shards, "repo": self.repo_id, "prefix": self.prefix}), flush=True) | |
| if self.delete_local: | |
| for shard in shards: | |
| shutil.rmtree(self.output_root / shard, ignore_errors=True) | |
| def main(argv: list[str] | None = None) -> None: | |
| source_dir = Path(__file__).resolve().parent | |
| project_root = source_dir.parent | |
| parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| group = parser.add_mutually_exclusive_group(required=True) | |
| group.add_argument("--input", type=Path, action="append", help="入力parquet(複数可)") | |
| group.add_argument("--input-dir", type=Path, help="入力parquetのディレクトリ") | |
| parser.add_argument("--pattern", default="*.parquet") | |
| parser.add_argument("--limit-shards", type=int, default=None, help="先頭N件だけ処理する(試運転用)") | |
| parser.add_argument("--output-root", type=Path, required=True) | |
| parser.add_argument("--workers", type=int, default=max(1, (os.cpu_count() or 2) - 1)) | |
| parser.add_argument("--batch-size", type=int, default=2048) | |
| parser.add_argument("--keep-intermediate", action="store_true", help="有害フィルタ後の retained.parquet を残す") | |
| parser.add_argument("--reference-dir", type=Path, default=source_dir / "wordlists" / "reference") | |
| parser.add_argument("--additional-dir", type=Path, default=source_dir / "wordlists") | |
| parser.add_argument("--exclude-dir", type=Path, default=source_dir / "wordlists" / "exclude") | |
| parser.add_argument("--blocklist-dir", type=Path, default=source_dir / "blocklists") | |
| parser.add_argument("--blocklist-cache-dir", type=Path, default=project_root / "data" / "blocklists" / "ut1") | |
| parser.add_argument("--no-blocklist", action="store_true") | |
| parser.add_argument("--cooccurrence-rules", type=Path, default=source_dir / "wordlists" / "cooccurrence" / "rules.json") | |
| parser.add_argument("--no-cooccurrence", action="store_true") | |
| parser.add_argument("--policy-approver", default=None) | |
| parser.add_argument("--policy-approved-on", default=None) | |
| parser.add_argument("--policy-note", default=None) | |
| parser.add_argument("--upload-repo", default=None, help="出力先の HF データセット(例: Podtech/abeja-cc-ja-cleaned)。非公開で作成する") | |
| parser.add_argument("--upload-prefix", default="outputs", help="リポジトリ内のパス接頭辞(例: outputs/common_crawl_0)") | |
| parser.add_argument("--upload-batch", type=int, default=5, help="何シャードごとに1コミットでアップロードするか") | |
| parser.add_argument("--delete-local-after-upload", action="store_true") | |
| parser.add_argument("--skip-existing-in-repo", action="store_true", help="リポジトリに shard_summary.json があるシャードを飛ばす") | |
| parser.add_argument("--staging-dir", type=Path, default=None, help="入力parquetを処理前にコピーするローカルディレクトリ(マウントの I/O エラー対策)") | |
| args = parser.parse_args(argv) | |
| if args.input_dir: | |
| inputs = sorted(args.input_dir.glob(args.pattern)) | |
| else: | |
| inputs = list(args.input) | |
| if args.limit_shards is not None: | |
| inputs = inputs[: args.limit_shards] | |
| if not inputs: | |
| raise FileNotFoundError("入力parquetが見つかりません") | |
| args.output_root.mkdir(parents=True, exist_ok=True) | |
| uploader = None | |
| skip: set[str] = set() | |
| if args.upload_repo: | |
| uploader = Uploader(args.upload_repo, args.upload_prefix, args.output_root, args.upload_batch, args.delete_local_after_upload) | |
| if args.skip_existing_in_repo: | |
| skip = uploader.existing_shards() | |
| todo = [] | |
| for path in inputs: | |
| shard = path.stem | |
| if shard in skip or (args.output_root / shard / "shard_summary.json").exists(): | |
| print(json.dumps({"event": "skip", "shard": shard}), flush=True) | |
| continue | |
| todo.append(path) | |
| config = { | |
| "batch_size": args.batch_size, | |
| "keep_intermediate": args.keep_intermediate, | |
| "reference_dir": str(args.reference_dir), "additional_dir": str(args.additional_dir), "exclude_dir": str(args.exclude_dir), | |
| "blocklist_dir": str(args.blocklist_dir), "blocklist_cache_dir": str(args.blocklist_cache_dir), "no_blocklist": args.no_blocklist, | |
| "cooccurrence_rules": str(args.cooccurrence_rules), "no_cooccurrence": args.no_cooccurrence, | |
| "policy_approver": args.policy_approver, "policy_approved_on": args.policy_approved_on, "policy_note": args.policy_note, | |
| "staging_dir": str(args.staging_dir) if args.staging_dir else None, | |
| } | |
| run_started = time.perf_counter() | |
| results: list[dict[str, Any]] = [] | |
| print(json.dumps({"event": "start", "shards": len(todo), "skipped": len(inputs) - len(todo), "workers": args.workers, "output_root": str(args.output_root)}), flush=True) | |
| jobs = [(str(path), str(args.output_root), config) for path in todo] | |
| if args.workers <= 1 or len(jobs) <= 1: | |
| _init_worker(config) | |
| iterator = map(_worker_entry, jobs) | |
| else: | |
| # pyarrow がスレッドを持つため fork は子プロセスのデッドロック要因になる。spawn で各ワーカーが独立に読み込む。 | |
| context = mp.get_context("spawn") | |
| pool = context.Pool(processes=min(args.workers, len(jobs)), initializer=_init_worker, initargs=(config,)) | |
| iterator = pool.imap_unordered(_worker_entry, jobs) | |
| for result in iterator: | |
| results.append(result) | |
| if "error" in result: | |
| print(json.dumps({"event": "error", "shard": result["shard"], "error": result["error"]}), flush=True) | |
| continue | |
| print(json.dumps({ | |
| "event": "done", "shard": result["shard"], "input_rows": result["input_rows"], | |
| "toxic_deleted": result["toxic"]["records_deleted"], "pii_replacements": result["pii"]["total_replacements"], | |
| "final_rows": result["output"]["final_rows"], "seconds": result["seconds"]["total"], | |
| }, ensure_ascii=False), flush=True) | |
| if uploader is not None: | |
| uploader.add(result["shard"]) | |
| if uploader is not None: | |
| uploader.flush() | |
| errors = [r for r in results if "error" in r] | |
| run_summary = { | |
| "pipeline_version": PIPELINE_VERSION, | |
| "finished_at_utc": datetime.now(timezone.utc).isoformat(), | |
| "shards_processed": len(results) - len(errors), | |
| "shards_failed": [{"shard": r["shard"], "error": r["error"]} for r in errors], | |
| "shards_skipped": len(inputs) - len(todo), | |
| "seconds": round(time.perf_counter() - run_started, 1), | |
| "upload_repo": args.upload_repo, | |
| "upload_prefix": args.upload_prefix if args.upload_repo else None, | |
| } | |
| (args.output_root / f"run_summary_{datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')}.json").write_text(json.dumps(run_summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") | |
| print(json.dumps({"event": "finish", **run_summary}, ensure_ascii=False), flush=True) | |
| if errors: | |
| raise SystemExit(1) | |
| if __name__ == "__main__": | |
| main() | |