Download code/pass5/833c8ffd/abeja_pass5.py from Podtech/abeja-cc-ja-cleaned: direct link, hf CLI and curl.
- Browser
- Download file 26.4 kB
-
https://huggingface.co/datasets/Podtech/abeja-cc-ja-cleaned/resolve/main/code/pass5/833c8ffd/abeja_pass5.py
- Command line
-
hf download hf://datasets/Podtech/abeja-cc-ja-cleaned/code/pass5/833c8ffd/abeja_pass5.py
-
curl -L -o abeja_pass5.py https://huggingface.co/datasets/Podtech/abeja-cc-ja-cleaned/resolve/main/code/pass5/833c8ffd/abeja_pass5.py
26.4 kB
| """abeja-cc-ja 第5パス: 金融アフィリエイト・EC 商品ページ・未対応区分(秘密情報、機密・流出、非同意性的、海賊版、Web 定型、キーワード詰め込み)の除去、 | |
| IP アドレスと認証情報値のマスキング、完全一致重複の除去(計画があれば)。入力 outputs_decontam/<dir>/<shard>/<shard>.parquet(url, content, perplexity)。 | |
| python tools/abeja_pass5.py --calibrate --files a.parquet,b.parquet # ローカル較正(規則別の件数と例) | |
| python tools/abeja_pass5.py --repo Podtech/abeja-cc-ja-cleaned --source-prefix outputs_decontam --dir common_crawl_0 --output-root /work/out/common_crawl_0 --upload-repo ... --upload-prefix outputs_v5 | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import collections | |
| import hashlib | |
| import json | |
| import os | |
| import re | |
| import shutil | |
| import time | |
| import traceback | |
| from concurrent.futures import ProcessPoolExecutor | |
| from datetime import datetime, timezone | |
| from pathlib import Path | |
| from typing import Any | |
| VERSION = "abeja-pass5/2026-09-09" | |
| EXCLUDE_GENRES_DEFAULT = "diary_blog,affiliate,game,entertainment,ec_product" # ユーザー指示(2026-09-09): other 以外の 5 ジャンル(日記ブログ/投資・美容・健康のアフィリエイト/ゲーム/芸能/EC)を除外 | |
| CTA = ["口座開設", "公式サイト", "今なら", "キャンペーン", "キャッシュバック", "おすすめ", "ランキング", "比較", "申し込み", "申込", "限定", "最短", "無料", "詳しくはこちら", "こちらから", "登録はこちら", "特典", "ボーナス", "紹介コード", "招待コード", "アフィリエイト", "提携", "口コミ", "評判", "デメリット", "メリット"] | |
| VERTICALS = { | |
| "fx": ["FX", "外国為替証拠金", "為替差益", "スワップポイント", "通貨ペア", "ロスカット", "pips", "証拠金", "スプレッド", "レバレッジ", "ドル円", "米ドル/円", "海外FX", "自動売買", "デイトレード", "スキャルピング"], | |
| "crypto": ["仮想通貨", "暗号資産", "ビットコイン", "BTC", "イーサリアム", "アルトコイン", "取引所", "ウォレット", "マイニング", "NFT", "エアドロップ", "草コイン", "ステーキング", "DeFi"], | |
| "fund": ["投資信託", "NISA", "iDeCo", "つみたて", "積立投資", "信託報酬", "インデックスファンド", "米国株", "高配当", "証券口座", "楽天証券", "SBI証券", "資産運用", "ロボアド"], | |
| "loan": ["カードローン", "キャッシング", "消費者金融", "借入", "即日融資", "審査", "借り換え", "おまとめ", "無利息", "プロミス", "アコム", "アイフル", "闇金", "ソフト闇金", "後払い", "現金化"], | |
| "realestate": ["不動産投資", "ワンルーム", "利回り", "家賃収入", "マンション投資", "サブリース", "不動産クラウドファンディング", "太陽光投資"], | |
| "beauty": ["脱毛", "美白", "シミ", "しわ", "たるみ", "毛穴", "エステ", "美容液", "化粧水", "サプリ", "ダイエット", "痩せ", "酵素", "プロテイン", "育毛", "薄毛", "AGA", "バストアップ", "ホワイトニング", "医療脱毛", "全身脱毛", "クリニック", "二重整形", "ヒアルロン酸"], | |
| "jobs": ["転職エージェント", "転職サイト", "求人", "年収", "未経験", "派遣", "退職代行", "プログラミングスクール", "資格講座"], | |
| "dating": ["婚活", "マッチングアプリ", "出会い", "結婚相談所", "パパ活", "セフレ"], | |
| "utility": ["ウォーターサーバー", "マットレス", "光回線", "格安SIM", "ポケットWiFi", "引越し業者", "買取", "車査定", "太陽光", "宅配クリーニング", "食材宅配", "ハウスクリーニング"], | |
| } | |
| # 縦割りごとの「強い語」(これが 1 語以上含まれないと判定しない)。無ければ全語が強い語 | |
| STRONG_TERMS = { | |
| "loan": {"カードローン", "キャッシング", "消費者金融", "即日融資", "無利息", "プロミス", "アコム", "アイフル", "闇金", "ソフト闇金", "後払い", "現金化", "おまとめ"}, | |
| "jobs": {"転職エージェント", "転職サイト", "退職代行", "プログラミングスクール", "資格講座", "派遣"}, | |
| "realestate": {"不動産投資", "サブリース", "不動産クラウドファンディング", "太陽光投資", "家賃収入", "マンション投資"}, | |
| "fund": {"投資信託", "NISA", "iDeCo", "つみたて", "積立投資", "信託報酬", "インデックスファンド", "証券口座", "楽天証券", "SBI証券", "ロボアド"}, | |
| "crypto": {"仮想通貨", "暗号資産", "ビットコイン", "BTC", "イーサリアム", "アルトコイン", "エアドロップ", "草コイン", "ステーキング", "DeFi", "NFT"}, | |
| "utility": {"ウォーターサーバー", "光回線", "格安SIM", "ポケットWiFi", "車査定", "宅配クリーニング", "食材宅配", "ハウスクリーニング", "引越し業者"}, | |
| "beauty": {"脱毛", "医療脱毛", "全身脱毛", "美容液", "サプリ", "育毛", "薄毛", "AGA", "バストアップ", "ホワイトニング", "二重整形", "ヒアルロン酸", "酵素", "プロテイン"}, | |
| } | |
| # (必要な語数, 必要な CTA 語数)。FX はユーザー指示(2026-09-09)で 1 語でも対象 | |
| RULE_MIN = {"fx": (1, 2), "crypto": (2, 2), "fund": (2, 2), "loan": (2, 2), "realestate": (2, 3), "beauty": (2, 3), "jobs": (2, 3), "dating": (2, 3), "utility": (2, 3)} | |
| EC_CUES = ["カートに入れる", "カートに追加", "買い物かご", "在庫あり", "在庫なし", "送料無料", "税込", "税抜", "円(税込)", "円(税込)", "販売価格", "定価", "ポイント還元", "商品説明", "商品番号", "商品コード", "型番", "JAN", "数量", "ご注文", "お届け", "配送", "返品", "ギフト", "ラッピング", "メーカー希望小売価格", "セール", "アウトレット", "お気に入りに追加", "再入荷", "レビューを書く", "お客様の声", "SOLD OUT", "売り切れ", "入荷待ち"] | |
| EC_HOST = re.compile(r"rakuten\.co\.jp|amazon\.co\.jp|shopping\.yahoo\.co\.jp|store\.shopping|mercari|zozo|yodobashi|biccamera|kakaku\.com|monotaro|askul|dmm\.com|/item/|/products?/|/goods/|/shop/|shop\.|store\.|cart|/product-", re.I) | |
| PIRACY_SITES = ["漫画村", "漫画バンク", "anitube", "kissanime", "nyaa", "13dl", "manga1000", "manga1001", "hitomi.la", "rawdevart", "mangaraw", "torrent", "トレント", "海賊版", "違法アップロード", "違法ダウンロード"] | |
| PIRACY_CUES = ["無料で読める", "全巻無料", "無料視聴", "無料で見る", "zip", "rar", "ダウンロード", "raw", "字幕付き 無料", "見放題 違法"] | |
| NONCONSENT = ["盗撮", "隠し撮り", "リベンジポルノ", "流出動画", "流出画像", "流出した動画", "ハメ撮り", "無修正流出", "個人撮影"] | |
| WEAK_PIRACY = {"torrent", "トレント"} | |
| SEXUAL_TERMS_FILE = "abeja-cc-ja/src/wordlists/cooccurrence/ja_sexual_terms.txt" | |
| CONFIDENTIAL = re.compile(r"社外秘|部外秘|関係者外秘|Confidential\s*[-–:]?\s*(?:Do not distribute|Internal use only)|INTERNAL USE ONLY|STRICTLY CONFIDENTIAL", re.I) | |
| CRED_DUMP_LINE = re.compile(r"^[^\s@]+@[^\s@]+\.[a-z]{2,}\s*[:|;,\t ]\s*\S{6,}\s*$", re.I | re.M) | |
| SECRET_STRONG = re.compile(r"-----BEGIN (?:RSA |EC |OPENSSH |DSA |PGP )?PRIVATE KEY-----|AKIA[0-9A-Z]{16}|AIza[0-9A-Za-z_\-]{35}|gh[pousr]_[A-Za-z0-9]{36,}|xox[baprs]-[0-9A-Za-z\-]{10,}|sk_live_[0-9a-zA-Z]{24,}") | |
| SECRET_KV = re.compile(r"(?i)\b(api[_-]?key|secret[_-]?key|access[_-]?token|client[_-]?secret|auth[_-]?token)\b\s*[:=]\s*['\"]?([A-Za-z0-9_\-]{20,})") | |
| PASSWORD_KV = re.compile(r"(?i)(password|passwd|pwd|パスワード|暗証番号)\s*[:=:]\s*['\"]?(?!\*+|●+|●|\*|x+\b|半角|英数|例|ここ)([^\s'\"、。,,]{6,32})") | |
| BOILER = ["Cookieを使用", "Cookie を使用", "クッキーを使用", "Cookieの使用に同意", "cookieの利用に同意", "ページが見つかりません", "お探しのページ", "404 Not Found", "JavaScriptを有効", "JavaScript を有効", "JavaScriptが無効", "ブラウザの設定", "アクセスが集中", "メンテナンス中", "ページは移動", "削除された可能性"] | |
| IPV4 = re.compile(r"(?<![\d.])((?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))(?![\d.])") | |
| _AUTO = None; _SEX = None; _ENC = None | |
| def _boundary_ok(low: str, st: int, end: int, term: str) -> bool: | |
| if not term.isascii(): return True | |
| return not ((st > 0 and low[st - 1].isalnum()) or (end + 1 < len(low) and low[end + 1].isalnum())) | |
| def _init(cfg: dict) -> None: | |
| global _AUTO, _SEX, _ENC | |
| import ahocorasick | |
| a = ahocorasick.Automaton() | |
| groups = {f"v:{k}": v for k, v in VERTICALS.items()}; groups["cta"] = CTA; groups["ec"] = EC_CUES; groups["pir_site"] = PIRACY_SITES; groups["pir_cue"] = PIRACY_CUES; groups["noncons"] = NONCONSENT; groups["boiler"] = BOILER | |
| index: dict[str, set] = collections.defaultdict(set) | |
| for g, terms in groups.items(): | |
| for t in terms: index[t.casefold()].add(g) | |
| for t, gs in index.items(): a.add_word(t, (t, tuple(gs))) | |
| a.make_automaton(); _AUTO = a | |
| sex = ahocorasick.Automaton() | |
| for t in cfg.get("sexual_terms") or []: sex.add_word(t.casefold(), t) | |
| sex.make_automaton(); _SEX = sex if cfg.get("sexual_terms") else None | |
| if cfg.get("count_tokens"): | |
| import tiktoken; _ENC = tiktoken.get_encoding("o200k_harmony") | |
| def scan(text: str) -> dict[str, set]: | |
| low = text.casefold(); found: dict[str, set] = collections.defaultdict(set) | |
| for end, (term, gs) in _AUTO.iter(low): | |
| st = end - len(term) + 1 | |
| if not _boundary_ok(low, st, end, term): continue | |
| for g in gs: found[g].add(term) | |
| return found | |
| def keyword_stuffing(text: str) -> tuple[bool, str]: | |
| t = re.sub(r"\s+", "", text) | |
| if len(t) < 600: return False, "" | |
| c = collections.Counter(t[i:i + 4] for i in range(0, len(t) - 3)) | |
| g, n = c.most_common(1)[0] | |
| if n >= 25 and n * 4 / len(t) >= 0.12 and re.search(r"[^\W\d_]", g): return True, f"{g}×{n}" | |
| return False, "" | |
| def decide(url: str, text: str) -> tuple[list[str], dict, str, dict]: | |
| """(除去理由の一覧, 詳細, マスキング後の本文, マスキング件数)""" | |
| reasons: list[str] = []; info: dict = {}; f = scan(text) | |
| cta = f.get("cta", set()) | |
| for k in VERTICALS: | |
| vt = f.get(f"v:{k}", set()) | |
| strong = vt & STRONG_TERMS.get(k, vt) | |
| min_terms, min_cta = RULE_MIN.get(k, (2, 3)) | |
| if len(vt) >= min_terms and strong and len(cta) >= min_cta: | |
| reasons.append(f"affiliate_{k}"); info[f"affiliate_{k}"] = {"terms": sorted(vt)[:6], "cta": sorted(cta)[:6]} | |
| ec = f.get("ec", set()); host = bool(EC_HOST.search(url or "")) | |
| if len(ec) >= 6 or (host and len(ec) >= 3): reasons.append("ec_product"); info["ec_product"] = {"cues": sorted(ec)[:8], "host": host} | |
| ps, pc = f.get("pir_site", set()), f.get("pir_cue", set()) | |
| strong_ps = ps - WEAK_PIRACY | |
| if len(ps) >= 2 or (strong_ps and pc) or (ps and len(pc) >= 2): reasons.append("piracy"); info["piracy"] = {"sites": sorted(ps)[:4], "cues": sorted(pc)[:4]} | |
| nc = f.get("noncons", set()) | |
| if nc and _SEX is not None: | |
| low = text.casefold(); sex_hits = {t for _, t in _SEX.iter(low)} - set(NONCONSENT) - {"性的", "性", "エロ"} | |
| if len(sex_hits) >= 2: reasons.append("nonconsensual_sexual"); info["nonconsensual_sexual"] = {"terms": sorted(nc)[:4], "sexual": sorted(sex_hits)[:4]} | |
| if SECRET_STRONG.search(text): reasons.append("secret_key"); info["secret_key"] = SECRET_STRONG.search(text).group(0)[:12] + "…" | |
| dump = CRED_DUMP_LINE.findall(text) | |
| if len(dump) >= 5: reasons.append("credential_dump"); info["credential_dump"] = {"lines": len(dump)} | |
| m = CONFIDENTIAL.search(text) | |
| if m: reasons.append("confidential_marker"); info["confidential_marker"] = m.group(0) | |
| b = f.get("boiler", set()) | |
| if len(text) < 1000 and len(b) >= 2: reasons.append("web_boilerplate"); info["web_boilerplate"] = sorted(b)[:5] | |
| ks, kinfo = keyword_stuffing(text) | |
| if ks: reasons.append("keyword_stuffing"); info["keyword_stuffing"] = kinfo | |
| masks: dict[str, int] = {}; out = text | |
| if not reasons: | |
| out, n = IPV4.subn(lambda mm: mm.group(1) if mm.group(1).startswith(("10.", "127.", "192.168.", "0.", "255.")) or re.match(r"172\.(1[6-9]|2\d|3[01])\.", mm.group(1)) else "<IP>", out) | |
| if n: masks["ip"] = n | |
| out, n = SECRET_KV.subn(lambda mm: f"{mm.group(1)}=<SECRET>", out) | |
| if n: masks["secret_kv"] = n | |
| out, n = PASSWORD_KV.subn(lambda mm: f"{mm.group(1)}: <SECRET>", out) | |
| if n: masks["password"] = n | |
| return reasons, info, out, masks | |
| def _fetch(repo: str, path_in_repo: str, local_dir: Path, attempts: int = 6) -> Path: | |
| from huggingface_hub import hf_hub_download | |
| for k in range(attempts): | |
| try: return Path(hf_hub_download(repo, path_in_repo, repo_type="dataset", token=os.environ.get("HF_TOKEN"), local_dir=str(local_dir))) | |
| except Exception as e: # noqa: BLE001 | |
| if k == attempts - 1: raise | |
| time.sleep(20 * (k + 1)) | |
| def process_shard(task: dict) -> dict: | |
| import pyarrow as pa, pyarrow.parquet as pq | |
| started = time.perf_counter(); shard = task["shard"] | |
| try: | |
| _init(task["cfg"]) | |
| local = _fetch(task["repo"], task["path"], Path(task["staging_dir"])) if task.get("repo") else Path(task["path"]) | |
| out_dir = Path(task["output_root"]) / shard; out_dir.mkdir(parents=True, exist_ok=True) | |
| genre_of: dict[str, str] = {} | |
| if task.get("features_path"): | |
| fl = _fetch(task["repo"], task["features_path"], Path(task["staging_dir"])) if task.get("repo") else Path(task["features_path"]) | |
| ft = pq.read_table(fl, columns=["content_sha1", "genre"]); genre_of = dict(zip(ft.column("content_sha1").to_pylist(), ft.column("genre").to_pylist())) | |
| if task.get("repo"): Path(fl).unlink(missing_ok=True) | |
| exclude_genres = set(task["cfg"].get("exclude_genres") or []) | |
| pf = pq.ParquetFile(local); codec = pf.metadata.row_group(0).column(0).compression if pf.metadata.num_row_groups else "SNAPPY" | |
| writer = pq.ParquetWriter(out_dir / f"{shard}.parquet", pf.schema_arrow, compression=codec.lower() if codec != "UNCOMPRESSED" else None) | |
| dedup: set = set(task.get("dedup_rows") or []); reasons_c = collections.Counter(); masks_c = collections.Counter(); rows_in = 0; written = 0; tok_removed = 0; masked_docs = 0 | |
| removed_f = (out_dir / "pass5_removed.jsonl").open("w", encoding="utf-8"); sha_list = [] | |
| try: | |
| for batch in pf.iter_batches(batch_size=2048): | |
| d = batch.to_pydict(); n = batch.num_rows; keep_idx = []; new_content = list(d["content"]) | |
| for i in range(n): | |
| row = rows_in + i; url = d["url"][i] or ""; text = d["content"][i] or "" | |
| if row in dedup: | |
| reasons, info = ["exact_duplicate"], {"exact_duplicate": task.get("dedup_info", {}).get(row)}; out = text; masks = {} | |
| else: | |
| reasons, info, out, masks = decide(url, text) | |
| g = genre_of.get(hashlib.sha1(text.encode("utf-8")).hexdigest()) if genre_of else None | |
| if g in exclude_genres: | |
| reasons.append(f"genre_{g}"); info[f"genre_{g}"] = True; out = text; masks = {} | |
| elif genre_of and g is None: reasons_c["_features_unmatched"] += 1 | |
| if reasons: | |
| for r in reasons: reasons_c[r] += 1 | |
| reasons_c["_removed"] += 1 | |
| if _ENC is not None: tok_removed += len(_ENC.encode(text, disallowed_special=())) | |
| removed_f.write(json.dumps({"row_index": row, "reasons": reasons, "info": info, "url": url, "content": text, "perplexity": d.get("perplexity", [None] * n)[i]}, ensure_ascii=False, default=str) + "\n") | |
| else: | |
| keep_idx.append(i); new_content[i] = out | |
| if masks: masked_docs += 1; masks_c.update(masks) | |
| sha_list.append(hashlib.sha1(out.encode("utf-8")).digest()) | |
| if keep_idx: | |
| cols = {} | |
| for name in pf.schema_arrow.names: | |
| vals = new_content if name == "content" else d[name] | |
| cols[name] = pa.array([vals[i] for i in keep_idx], type=pf.schema_arrow.field(name).type) | |
| kept = pa.record_batch(cols, schema=pf.schema_arrow); writer.write_batch(kept); written += kept.num_rows | |
| rows_in += n | |
| finally: | |
| writer.close(); removed_f.close() | |
| pq.write_table(pa.table({"sha1": pa.array(sha_list, pa.binary(20))}), out_dir / "pass5_sha1.parquet") | |
| check = pq.ParquetFile(out_dir / f"{shard}.parquet"); assert check.metadata.num_rows == written == rows_in - reasons_c["_removed"], "row count mismatch" | |
| summary = {"version": VERSION, "dir": task["config"], "shard": shard, "rows_in": rows_in, "rows_removed": reasons_c.pop("_removed", 0), "rows_out": written, "features_unmatched": reasons_c.pop("_features_unmatched", 0), "features_rows": len(genre_of), "removed_by_reason": dict(reasons_c), | |
| "masked_docs": masked_docs, "masks": dict(masks_c), "tokens_removed": tok_removed if _ENC is not None else None, "dedup_rows_planned": len(dedup), "compression": codec, "seconds": round(time.perf_counter() - started, 1), "finished_at_utc": datetime.now(timezone.utc).isoformat()} | |
| (out_dir / "pass5_summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") | |
| if task.get("repo"): Path(local).unlink(missing_ok=True) | |
| return summary | |
| except Exception as error: # noqa: BLE001 | |
| return {"shard": shard, "error": repr(error), "traceback": traceback.format_exc()} | |
| def upload_batch(api: Any, repo: str, prefix: str, output_root: Path, shards: list[str], delete_local: bool) -> None: | |
| """複数シャードを 1 コミットでまとめてアップロード(HF のコミット制限 320/時 対策)。429 は案内された待ち時間だけ待って再試行""" | |
| import re as _re | |
| for attempt in range(12): | |
| try: | |
| api.upload_folder(repo_id=repo, repo_type="dataset", folder_path=str(output_root), path_in_repo=prefix, allow_patterns=[f"{sh}/**" for sh in shards], commit_message=f"{Path(prefix).name} {shards[0]}..{shards[-1]} ({len(shards)} shards)") | |
| break | |
| except Exception as e: # noqa: BLE001 | |
| msg = str(e); m = _re.search(r"retry this action in (\d+) minutes", msg) | |
| wait = (int(m.group(1)) * 60 + 90) if m else (120 * (attempt + 1)) | |
| print(json.dumps({"event": "upload_retry", "attempt": attempt + 1, "wait_s": wait, "error": msg[:160]}), flush=True) | |
| if attempt == 11: raise | |
| time.sleep(wait) | |
| if delete_local: | |
| for sh in shards: shutil.rmtree(output_root / sh, ignore_errors=True) | |
| def calibrate(files: list[str], cfg: dict, limit: int | None, features: list[str] | None = None) -> None: | |
| import pyarrow.parquet as pq | |
| _init(cfg); c = collections.Counter(); ex = collections.defaultdict(list); n = 0; masks_c = collections.Counter(); hosts = collections.defaultdict(collections.Counter); excl = set(cfg.get("exclude_genres") or []) | |
| for fi, f in enumerate(files): | |
| pf = pq.ParquetFile(f); genre_of = {} | |
| if features: | |
| ft = pq.read_table(features[fi], columns=["content_sha1", "genre"]); genre_of = dict(zip(ft.column("content_sha1").to_pylist(), ft.column("genre").to_pylist())) | |
| for batch in pf.iter_batches(batch_size=2048, columns=["url", "content"]): | |
| for url, text in zip(batch.column("url").to_pylist(), batch.column("content").to_pylist()): | |
| n += 1; reasons, info, out, masks = decide(url or "", text or "") | |
| g = genre_of.get(hashlib.sha1((text or "").encode("utf-8")).hexdigest()) if genre_of else None | |
| if g in excl: reasons.append(f"genre_{g}"); info[f"genre_{g}"] = True | |
| for r in reasons: | |
| c[r] += 1; hosts[r][re.sub(r"^https?://([^/]+).*", r"\1", url or "")] += 1 | |
| if len(ex[r]) < 4: ex[r].append((url[:60], json.dumps(info.get(r), ensure_ascii=False)[:100], (text or "")[:120].replace("\n", " "))) | |
| if reasons: c["_removed"] += 1 | |
| masks_c.update(masks) | |
| if limit and n >= limit: break | |
| if limit and n >= limit: break | |
| only_genre = sum(1 for _ in []) # placeholder | |
| print(json.dumps({"docs": n, "removed": c.pop("_removed", 0), "by_reason": dict(c), "masks": dict(masks_c)}, ensure_ascii=False)) | |
| for r, lst in ex.items(): | |
| print(f"== {r} ({c[r]}, {c[r]/n:.3%}) hosts {hosts[r].most_common(3)}") | |
| for e in lst: print(" ", e[0], "|", e[1], "|", e[2]) | |
| def main(argv: list[str] | None = None) -> None: | |
| parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| parser.add_argument("--calibrate", action="store_true"); parser.add_argument("--files", default=""); parser.add_argument("--limit", type=int, default=None) | |
| parser.add_argument("--repo", default=None); parser.add_argument("--source-prefix", default="outputs_decontam"); parser.add_argument("--dir", default=None) | |
| parser.add_argument("--output-root", type=Path, default=None); parser.add_argument("--staging-dir", type=Path, default=Path("/work/staging")); parser.add_argument("--plan", default=None, help="dedup 計画 parquet(dir, shard, row_index, kept_shard, kept_row_index)") | |
| parser.add_argument("--sexual-terms", default=None); parser.add_argument("--count-tokens", action="store_true"); parser.add_argument("--limit-shards", type=int, default=None) | |
| parser.add_argument("--features-prefix", default=None, help="第2パス出力の接頭辞(<dir>/<shard>/features.parquet からジャンルを引く)"); parser.add_argument("--features-files", default="", help="較正用: --files と同順の features.parquet") | |
| parser.add_argument("--exclude-genres", default=EXCLUDE_GENRES_DEFAULT) | |
| parser.add_argument("--upload-repo", default=None); parser.add_argument("--upload-prefix", default="outputs_v5"); parser.add_argument("--upload-batch", type=int, default=10); parser.add_argument("--skip-existing-in-repo", action="store_true") | |
| parser.add_argument("--workers", type=int, default=max(1, int(os.environ.get("CPU_CORES") or os.cpu_count() or 2) - 1)) | |
| args = parser.parse_args(argv) | |
| sexual = [l.strip() for l in open(args.sexual_terms, encoding="utf-8") if l.strip() and not l.startswith("#")] if args.sexual_terms else [] | |
| cfg = {"sexual_terms": sexual, "count_tokens": args.count_tokens, "exclude_genres": [g for g in args.exclude_genres.split(",") if g]} | |
| if args.calibrate: | |
| calibrate([f for f in args.files.split(",") if f], cfg, args.limit, [f for f in args.features_files.split(",") if f] or None); return | |
| from huggingface_hub import HfApi | |
| api = HfApi(token=os.environ.get("HF_TOKEN")) | |
| shards = sorted({e.path.split("/")[-1] for e in api.list_repo_tree(args.repo, path_in_repo=f"{args.source_prefix}/{args.dir}", repo_type="dataset", recursive=False)}) | |
| if args.limit_shards: shards = shards[: args.limit_shards] | |
| existing = set() | |
| if args.skip_existing_in_repo and args.upload_repo: | |
| try: existing = {e.path.split("/")[-1] for e in api.list_repo_tree(args.upload_repo, path_in_repo=f"{args.upload_prefix}/{args.dir}", repo_type="dataset", recursive=False)} | |
| except Exception: existing = set() | |
| plan: dict[str, dict[int, Any]] = {} | |
| if args.plan: | |
| import pyarrow.parquet as pq | |
| t = pq.read_table(args.plan).filter(pq.compute.equal(pq.read_table(args.plan).column("dir"), args.dir)) if False else pq.read_table(args.plan) | |
| import pyarrow.compute as pc | |
| t = t.filter(pc.equal(t.column("dir"), args.dir)) | |
| for sh, row, ks, kr in zip(t.column("shard").to_pylist(), t.column("row_index").to_pylist(), t.column("kept_shard").to_pylist(), t.column("kept_row_index").to_pylist()): | |
| plan.setdefault(sh, {})[int(row)] = {"kept_shard": ks, "kept_row_index": kr} | |
| tasks = [{"repo": args.repo, "path": f"{args.source_prefix}/{args.dir}/{sh}/{sh}.parquet", "features_path": f"{args.features_prefix}/{args.dir}/{sh}/features.parquet" if args.features_prefix else None, "shard": sh, "config": args.dir, "output_root": str(args.output_root), "staging_dir": str(args.staging_dir), "cfg": cfg, | |
| "dedup_rows": list(plan.get(sh, {}).keys()), "dedup_info": plan.get(sh, {})} for sh in shards if sh not in existing] | |
| print(json.dumps({"event": "start", "dir": args.dir, "shards": len(shards), "skipped_existing": len(shards) - len(tasks), "dedup_rows": sum(len(v) for v in plan.values())}), flush=True) | |
| pending = []; failed = [] | |
| with ProcessPoolExecutor(max_workers=args.workers) as ex: | |
| for s in ex.map(process_shard, tasks): | |
| if "error" in s: failed.append(s["shard"]); print(json.dumps({"event": "error", **s}, ensure_ascii=False)[:600], flush=True); continue | |
| print(json.dumps({"event": "done", **{k: v for k, v in s.items() if k not in ("version", "finished_at_utc", "compression")}}, ensure_ascii=False), flush=True) | |
| if args.upload_repo: | |
| pending.append(s["shard"]) | |
| if len(pending) >= args.upload_batch: upload_batch(api, args.upload_repo, f"{args.upload_prefix}/{args.dir}", args.output_root, pending, True); pending = [] | |
| if args.upload_repo and pending: upload_batch(api, args.upload_repo, f"{args.upload_prefix}/{args.dir}", args.output_root, pending, True) | |
| print(json.dumps({"event": "finish", "dir": args.dir, "shards": len(tasks), "failed": failed}), flush=True) | |
| if __name__ == "__main__": | |
| main() | |