podtech-okamura commited on
Commit
29e4bc6
·
verified ·
1 Parent(s): e40e276

pass5 apply script 92bd124f

Browse files
Files changed (1) hide show
  1. code/pass5/92bd124f/abeja_pass5.py +299 -0
code/pass5/92bd124f/abeja_pass5.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """abeja-cc-ja 第5パス: 金融アフィリエイト・EC 商品ページ・未対応区分(秘密情報、機密・流出、非同意性的、海賊版、Web 定型、キーワード詰め込み)の除去、
2
+ IP アドレスと認証情報値のマスキング、完全一致重複の除去(計画があれば)。入力 outputs_decontam/<dir>/<shard>/<shard>.parquet(url, content, perplexity)。
3
+
4
+ python tools/abeja_pass5.py --calibrate --files a.parquet,b.parquet # ローカル較正(規則別の件数と例)
5
+ 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
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import collections
11
+ import hashlib
12
+ import json
13
+ import os
14
+ import re
15
+ import shutil
16
+ import time
17
+ import traceback
18
+ from concurrent.futures import ProcessPoolExecutor
19
+ from datetime import datetime, timezone
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ VERSION = "abeja-pass5/2026-09-09"
24
+ EXCLUDE_GENRES_DEFAULT = "diary_blog,affiliate,game,entertainment,ec_product" # ユーザー指示(2026-09-09): other 以外の 5 ジャンル(日記ブログ/投資・美容・健康のアフィリエイト/ゲーム/芸能/EC)を除外
25
+ CTA = ["口座開設", "公式サイト", "今なら", "キャンペーン", "キャッシュバック", "おすすめ", "ランキング", "比較", "申し込み", "申込", "限定", "最短", "無料", "詳しくはこちら", "こちらから", "登録はこちら", "特典", "ボーナス", "紹介コード", "招待コード", "アフィリエイト", "提携", "口コミ", "評判", "デメリット", "メリット"]
26
+ VERTICALS = {
27
+ "fx": ["FX", "外国為替証拠金", "為替差益", "スワップポイント", "通貨ペア", "ロスカット", "pips", "証拠金", "スプレッド", "レバレッジ", "ドル円", "米ドル/円", "海外FX", "自動売買", "デイトレード", "スキャルピング"],
28
+ "crypto": ["仮想通貨", "暗号資産", "ビットコイン", "BTC", "イーサリアム", "アルトコイン", "取引所", "ウォレット", "マイニング", "NFT", "エアドロップ", "草コイン", "ステーキング", "DeFi"],
29
+ "fund": ["投資信託", "NISA", "iDeCo", "つみたて", "積立投資", "信託報酬", "インデックスファンド", "米国株", "高配当", "証券口座", "楽天証券", "SBI証券", "資産運用", "ロボアド"],
30
+ "loan": ["カードローン", "キャッシング", "消費者金融", "借入", "即日融資", "審査", "借り換え", "おまとめ", "無利息", "プロミス", "アコム", "アイフル", "闇金", "ソフト闇金", "後払い", "現金化"],
31
+ "realestate": ["不動産投資", "ワンルーム", "利回り", "家賃収入", "マンション投資", "サブリース", "不動産クラウドファンディング", "太陽光投資"],
32
+ "beauty": ["脱毛", "美白", "シミ", "しわ", "たるみ", "毛穴", "エステ", "美容液", "化粧水", "サプリ", "ダイエット", "痩せ", "酵素", "プロテイン", "育毛", "薄毛", "AGA", "バストアップ", "ホワイトニング", "医療脱毛", "全身脱毛", "クリニック", "二重整形", "ヒアルロン酸"],
33
+ "jobs": ["転職エージェント", "転職サイト", "求人", "年収", "未経験", "派遣", "退職代行", "プログラミングスクール", "資格講座"],
34
+ "dating": ["婚活", "マッチングアプリ", "出会い", "結婚相談所", "パパ活", "セフレ"],
35
+ "utility": ["ウォーターサーバー", "マットレス", "光回線", "格安SIM", "ポケットWiFi", "引越し業者", "買取", "車査定", "太陽光", "宅配クリーニング", "食材宅配", "ハウスクリーニング"],
36
+ }
37
+ # 縦割りごとの「強い語」(これが 1 語以上含まれないと判定しない)。無ければ全語が強い語
38
+ STRONG_TERMS = {
39
+ "loan": {"カードローン", "キャッシング", "消費者金融", "即日融資", "無利息", "プロミス", "アコム", "アイフル", "闇金", "ソフト闇金", "後払い", "現金化", "おまとめ"},
40
+ "jobs": {"転職エージェント", "転職サイト", "退職代行", "プログラミングスクール", "資格講座", "派遣"},
41
+ "realestate": {"不動産投資", "サブリース", "不動産クラウドファンディング", "太陽光投資", "家賃収入", "マンション投資"},
42
+ "fund": {"投資信託", "NISA", "iDeCo", "つみたて", "積立投資", "信託報酬", "インデックスファンド", "証券口座", "楽天証券", "SBI証券", "ロボアド"},
43
+ "crypto": {"仮想通貨", "暗号資産", "ビットコイン", "BTC", "イーサリアム", "アルトコイン", "エアドロップ", "草コイン", "ステーキング", "DeFi", "NFT"},
44
+ "utility": {"ウォーターサーバー", "光回線", "格安SIM", "ポケットWiFi", "車査定", "宅配クリーニング", "食材宅配", "ハウスクリーニング", "引越し業者"},
45
+ "beauty": {"脱毛", "医療脱毛", "全身脱毛", "美容液", "サプリ", "育毛", "薄毛", "AGA", "バストアップ", "ホワイトニング", "二重整形", "ヒアルロン酸", "酵素", "プロテイン"},
46
+ }
47
+ # (必要な語数, 必要な CTA 語数)。FX はユーザー指示(2026-09-09)で 1 語でも対象
48
+ 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)}
49
+ EC_CUES = ["カートに入れる", "カートに追加", "買い物かご", "在庫あり", "在庫なし", "送料無料", "税込", "税抜", "円(税込)", "円(税込)", "販売価格", "定価", "ポイント還元", "商品説明", "商品番号", "商品コード", "型番", "JAN", "数量", "ご注文", "お届け", "配送", "返品", "ギフト", "ラッピング", "メーカー希望小売価格", "セール", "アウトレット", "お気に入りに追加", "再入荷", "レビューを書く", "お客様の声", "SOLD OUT", "売り切れ", "入荷待ち"]
50
+ 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)
51
+ PIRACY_SITES = ["漫画村", "漫画バンク", "anitube", "kissanime", "nyaa", "13dl", "manga1000", "manga1001", "hitomi.la", "rawdevart", "mangaraw", "torrent", "トレント", "海賊版", "違法アップロード", "違法ダウンロード"]
52
+ PIRACY_CUES = ["無料で読める", "全巻無料", "無料視聴", "無料で見る", "zip", "rar", "ダウンロード", "raw", "字幕付き 無料", "見放題 違法"]
53
+ NONCONSENT = ["盗撮", "隠し撮り", "リベンジポルノ", "流出動画", "流出画像", "流出した動画", "ハメ撮り", "無修正流出", "個人撮影"]
54
+ WEAK_PIRACY = {"torrent", "トレント"}
55
+ SEXUAL_TERMS_FILE = "abeja-cc-ja/src/wordlists/cooccurrence/ja_sexual_terms.txt"
56
+ CONFIDENTIAL = re.compile(r"社外秘|部外秘|関係者外秘|Confidential\s*[-–:]?\s*(?:Do not distribute|Internal use only)|INTERNAL USE ONLY|STRICTLY CONFIDENTIAL", re.I)
57
+ CRED_DUMP_LINE = re.compile(r"^[^\s@]+@[^\s@]+\.[a-z]{2,}\s*[:|;,\t ]\s*\S{6,}\s*$", re.I | re.M)
58
+ 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,}")
59
+ 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,})")
60
+ PASSWORD_KV = re.compile(r"(?i)(password|passwd|pwd|パスワード|暗証番号)\s*[:=:]\s*['\"]?(?!\*+|●+|●|\*|x+\b|半角|英数|例|ここ)([^\s'\"、。,,]{6,32})")
61
+ BOILER = ["Cookieを使用", "Cookie を使用", "クッキーを使用", "Cookieの使用に同意", "cookieの利用に同意", "ページが見つかりません", "お探しのページ", "404 Not Found", "JavaScriptを有効", "JavaScript を有効", "JavaScriptが無効", "ブラウザの設定", "アクセスが集中", "メンテナンス中", "ページは移動", "削除された可能性"]
62
+ 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.])")
63
+ _AUTO = None; _SEX = None; _ENC = None
64
+
65
+
66
+ def _boundary_ok(low: str, st: int, end: int, term: str) -> bool:
67
+ if not term.isascii(): return True
68
+ return not ((st > 0 and low[st - 1].isalnum()) or (end + 1 < len(low) and low[end + 1].isalnum()))
69
+
70
+
71
+ def _init(cfg: dict) -> None:
72
+ global _AUTO, _SEX, _ENC
73
+ import ahocorasick
74
+ a = ahocorasick.Automaton()
75
+ 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
76
+ index: dict[str, set] = collections.defaultdict(set)
77
+ for g, terms in groups.items():
78
+ for t in terms: index[t.casefold()].add(g)
79
+ for t, gs in index.items(): a.add_word(t, (t, tuple(gs)))
80
+ a.make_automaton(); _AUTO = a
81
+ sex = ahocorasick.Automaton()
82
+ for t in cfg.get("sexual_terms") or []: sex.add_word(t.casefold(), t)
83
+ sex.make_automaton(); _SEX = sex if cfg.get("sexual_terms") else None
84
+ if cfg.get("count_tokens"):
85
+ import tiktoken; _ENC = tiktoken.get_encoding("o200k_harmony")
86
+
87
+
88
+ def scan(text: str) -> dict[str, set]:
89
+ low = text.casefold(); found: dict[str, set] = collections.defaultdict(set)
90
+ for end, (term, gs) in _AUTO.iter(low):
91
+ st = end - len(term) + 1
92
+ if not _boundary_ok(low, st, end, term): continue
93
+ for g in gs: found[g].add(term)
94
+ return found
95
+
96
+
97
+ def keyword_stuffing(text: str) -> tuple[bool, str]:
98
+ t = re.sub(r"\s+", "", text)
99
+ if len(t) < 600: return False, ""
100
+ c = collections.Counter(t[i:i + 4] for i in range(0, len(t) - 3))
101
+ g, n = c.most_common(1)[0]
102
+ if n >= 25 and n * 4 / len(t) >= 0.12 and re.search(r"[^\W\d_]", g): return True, f"{g}×{n}"
103
+ return False, ""
104
+
105
+
106
+ def decide(url: str, text: str) -> tuple[list[str], dict, str, dict]:
107
+ """(除去理由の一覧, 詳細, マスキング後の本文, マスキング件数)"""
108
+ reasons: list[str] = []; info: dict = {}; f = scan(text)
109
+ cta = f.get("cta", set())
110
+ for k in VERTICALS:
111
+ vt = f.get(f"v:{k}", set())
112
+ strong = vt & STRONG_TERMS.get(k, vt)
113
+ min_terms, min_cta = RULE_MIN.get(k, (2, 3))
114
+ if len(vt) >= min_terms and strong and len(cta) >= min_cta:
115
+ reasons.append(f"affiliate_{k}"); info[f"affiliate_{k}"] = {"terms": sorted(vt)[:6], "cta": sorted(cta)[:6]}
116
+ ec = f.get("ec", set()); host = bool(EC_HOST.search(url or ""))
117
+ if len(ec) >= 6 or (host and len(ec) >= 3): reasons.append("ec_product"); info["ec_product"] = {"cues": sorted(ec)[:8], "host": host}
118
+ ps, pc = f.get("pir_site", set()), f.get("pir_cue", set())
119
+ strong_ps = ps - WEAK_PIRACY
120
+ 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]}
121
+ nc = f.get("noncons", set())
122
+ if nc and _SEX is not None:
123
+ low = text.casefold(); sex_hits = {t for _, t in _SEX.iter(low)} - set(NONCONSENT) - {"性的", "性", "エロ"}
124
+ if len(sex_hits) >= 2: reasons.append("nonconsensual_sexual"); info["nonconsensual_sexual"] = {"terms": sorted(nc)[:4], "sexual": sorted(sex_hits)[:4]}
125
+ if SECRET_STRONG.search(text): reasons.append("secret_key"); info["secret_key"] = SECRET_STRONG.search(text).group(0)[:12] + "…"
126
+ dump = CRED_DUMP_LINE.findall(text)
127
+ if len(dump) >= 5: reasons.append("credential_dump"); info["credential_dump"] = {"lines": len(dump)}
128
+ m = CONFIDENTIAL.search(text)
129
+ if m: reasons.append("confidential_marker"); info["confidential_marker"] = m.group(0)
130
+ b = f.get("boiler", set())
131
+ if len(text) < 1000 and len(b) >= 2: reasons.append("web_boilerplate"); info["web_boilerplate"] = sorted(b)[:5]
132
+ ks, kinfo = keyword_stuffing(text)
133
+ if ks: reasons.append("keyword_stuffing"); info["keyword_stuffing"] = kinfo
134
+ masks: dict[str, int] = {}; out = text
135
+ if not reasons:
136
+ 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)
137
+ if n: masks["ip"] = n
138
+ out, n = SECRET_KV.subn(lambda mm: f"{mm.group(1)}=<SECRET>", out)
139
+ if n: masks["secret_kv"] = n
140
+ out, n = PASSWORD_KV.subn(lambda mm: f"{mm.group(1)}: <SECRET>", out)
141
+ if n: masks["password"] = n
142
+ return reasons, info, out, masks
143
+
144
+
145
+ def _fetch(repo: str, path_in_repo: str, local_dir: Path, attempts: int = 6) -> Path:
146
+ from huggingface_hub import hf_hub_download
147
+ for k in range(attempts):
148
+ try: return Path(hf_hub_download(repo, path_in_repo, repo_type="dataset", token=os.environ.get("HF_TOKEN"), local_dir=str(local_dir)))
149
+ except Exception as e: # noqa: BLE001
150
+ if k == attempts - 1: raise
151
+ time.sleep(20 * (k + 1))
152
+
153
+
154
+ def process_shard(task: dict) -> dict:
155
+ import pyarrow as pa, pyarrow.parquet as pq
156
+ started = time.perf_counter(); shard = task["shard"]
157
+ try:
158
+ _init(task["cfg"])
159
+ local = _fetch(task["repo"], task["path"], Path(task["staging_dir"])) if task.get("repo") else Path(task["path"])
160
+ out_dir = Path(task["output_root"]) / shard; out_dir.mkdir(parents=True, exist_ok=True)
161
+ genre_of: dict[str, str] = {}
162
+ if task.get("features_path"):
163
+ fl = _fetch(task["repo"], task["features_path"], Path(task["staging_dir"])) if task.get("repo") else Path(task["features_path"])
164
+ ft = pq.read_table(fl, columns=["content_sha1", "genre"]); genre_of = dict(zip(ft.column("content_sha1").to_pylist(), ft.column("genre").to_pylist()))
165
+ if task.get("repo"): Path(fl).unlink(missing_ok=True)
166
+ exclude_genres = set(task["cfg"].get("exclude_genres") or [])
167
+ pf = pq.ParquetFile(local); codec = pf.metadata.row_group(0).column(0).compression if pf.metadata.num_row_groups else "SNAPPY"
168
+ writer = pq.ParquetWriter(out_dir / f"{shard}.parquet", pf.schema_arrow, compression=codec.lower() if codec != "UNCOMPRESSED" else None)
169
+ 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
170
+ removed_f = (out_dir / "pass5_removed.jsonl").open("w", encoding="utf-8"); sha_list = []
171
+ try:
172
+ for batch in pf.iter_batches(batch_size=2048):
173
+ d = batch.to_pydict(); n = batch.num_rows; keep_idx = []; new_content = list(d["content"])
174
+ for i in range(n):
175
+ row = rows_in + i; url = d["url"][i] or ""; text = d["content"][i] or ""
176
+ if row in dedup:
177
+ reasons, info = ["exact_duplicate"], {"exact_duplicate": task.get("dedup_info", {}).get(row)}; out = text; masks = {}
178
+ else:
179
+ reasons, info, out, masks = decide(url, text)
180
+ g = genre_of.get(hashlib.sha1(text.encode("utf-8")).hexdigest()) if genre_of else None
181
+ if g in exclude_genres:
182
+ reasons.append(f"genre_{g}"); info[f"genre_{g}"] = True; out = text; masks = {}
183
+ elif genre_of and g is None: reasons_c["_features_unmatched"] += 1
184
+ if reasons:
185
+ for r in reasons: reasons_c[r] += 1
186
+ reasons_c["_removed"] += 1
187
+ if _ENC is not None: tok_removed += len(_ENC.encode(text, disallowed_special=()))
188
+ 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")
189
+ else:
190
+ keep_idx.append(i); new_content[i] = out
191
+ if masks: masked_docs += 1; masks_c.update(masks)
192
+ sha_list.append(hashlib.sha1(out.encode("utf-8")).digest())
193
+ if keep_idx:
194
+ cols = {}
195
+ for name in pf.schema_arrow.names:
196
+ vals = new_content if name == "content" else d[name]
197
+ cols[name] = pa.array([vals[i] for i in keep_idx], type=pf.schema_arrow.field(name).type)
198
+ kept = pa.record_batch(cols, schema=pf.schema_arrow); writer.write_batch(kept); written += kept.num_rows
199
+ rows_in += n
200
+ finally:
201
+ writer.close(); removed_f.close()
202
+ pq.write_table(pa.table({"sha1": pa.array(sha_list, pa.binary(20))}), out_dir / "pass5_sha1.parquet")
203
+ check = pq.ParquetFile(out_dir / f"{shard}.parquet"); assert check.metadata.num_rows == written == rows_in - reasons_c["_removed"], "row count mismatch"
204
+ 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),
205
+ "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()}
206
+ (out_dir / "pass5_summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
207
+ if task.get("repo"): Path(local).unlink(missing_ok=True)
208
+ return summary
209
+ except Exception as error: # noqa: BLE001
210
+ return {"shard": shard, "error": repr(error), "traceback": traceback.format_exc()}
211
+
212
+
213
+ def upload_batch(api: Any, repo: str, prefix: str, output_root: Path, shards: list[str], delete_local: bool) -> None:
214
+ for attempt in range(8):
215
+ try:
216
+ for sh in shards:
217
+ api.upload_folder(repo_id=repo, repo_type="dataset", folder_path=str(output_root / sh), path_in_repo=f"{prefix}/{sh}", commit_message=f"{Path(prefix).name} {sh}")
218
+ break
219
+ except Exception as e: # noqa: BLE001
220
+ if attempt == 7: raise
221
+ time.sleep(60 * (attempt + 1) + 30)
222
+ if delete_local:
223
+ for sh in shards: shutil.rmtree(output_root / sh, ignore_errors=True)
224
+
225
+
226
+ def calibrate(files: list[str], cfg: dict, limit: int | None, features: list[str] | None = None) -> None:
227
+ import pyarrow.parquet as pq
228
+ _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 [])
229
+ for fi, f in enumerate(files):
230
+ pf = pq.ParquetFile(f); genre_of = {}
231
+ if features:
232
+ 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()))
233
+ for batch in pf.iter_batches(batch_size=2048, columns=["url", "content"]):
234
+ for url, text in zip(batch.column("url").to_pylist(), batch.column("content").to_pylist()):
235
+ n += 1; reasons, info, out, masks = decide(url or "", text or "")
236
+ g = genre_of.get(hashlib.sha1((text or "").encode("utf-8")).hexdigest()) if genre_of else None
237
+ if g in excl: reasons.append(f"genre_{g}"); info[f"genre_{g}"] = True
238
+ for r in reasons:
239
+ c[r] += 1; hosts[r][re.sub(r"^https?://([^/]+).*", r"\1", url or "")] += 1
240
+ if len(ex[r]) < 4: ex[r].append((url[:60], json.dumps(info.get(r), ensure_ascii=False)[:100], (text or "")[:120].replace("\n", " ")))
241
+ if reasons: c["_removed"] += 1
242
+ masks_c.update(masks)
243
+ if limit and n >= limit: break
244
+ if limit and n >= limit: break
245
+ only_genre = sum(1 for _ in []) # placeholder
246
+ print(json.dumps({"docs": n, "removed": c.pop("_removed", 0), "by_reason": dict(c), "masks": dict(masks_c)}, ensure_ascii=False))
247
+ for r, lst in ex.items():
248
+ print(f"== {r} ({c[r]}, {c[r]/n:.3%}) hosts {hosts[r].most_common(3)}")
249
+ for e in lst: print(" ", e[0], "|", e[1], "|", e[2])
250
+
251
+
252
+ def main(argv: list[str] | None = None) -> None:
253
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
254
+ parser.add_argument("--calibrate", action="store_true"); parser.add_argument("--files", default=""); parser.add_argument("--limit", type=int, default=None)
255
+ parser.add_argument("--repo", default=None); parser.add_argument("--source-prefix", default="outputs_decontam"); parser.add_argument("--dir", default=None)
256
+ 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)")
257
+ parser.add_argument("--sexual-terms", default=None); parser.add_argument("--count-tokens", action="store_true"); parser.add_argument("--limit-shards", type=int, default=None)
258
+ parser.add_argument("--features-prefix", default=None, help="第2パス出力の接頭辞(<dir>/<shard>/features.parquet からジャンルを引く)"); parser.add_argument("--features-files", default="", help="較正用: --files と同順の features.parquet")
259
+ parser.add_argument("--exclude-genres", default=EXCLUDE_GENRES_DEFAULT)
260
+ 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")
261
+ parser.add_argument("--workers", type=int, default=max(1, int(os.environ.get("CPU_CORES") or os.cpu_count() or 2) - 1))
262
+ args = parser.parse_args(argv)
263
+ 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 []
264
+ cfg = {"sexual_terms": sexual, "count_tokens": args.count_tokens, "exclude_genres": [g for g in args.exclude_genres.split(",") if g]}
265
+ if args.calibrate:
266
+ 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
267
+ from huggingface_hub import HfApi
268
+ api = HfApi(token=os.environ.get("HF_TOKEN"))
269
+ 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)})
270
+ if args.limit_shards: shards = shards[: args.limit_shards]
271
+ existing = set()
272
+ if args.skip_existing_in_repo and args.upload_repo:
273
+ 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)}
274
+ except Exception: existing = set()
275
+ plan: dict[str, dict[int, Any]] = {}
276
+ if args.plan:
277
+ import pyarrow.parquet as pq
278
+ 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)
279
+ import pyarrow.compute as pc
280
+ t = t.filter(pc.equal(t.column("dir"), args.dir))
281
+ 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()):
282
+ plan.setdefault(sh, {})[int(row)] = {"kept_shard": ks, "kept_row_index": kr}
283
+ 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,
284
+ "dedup_rows": list(plan.get(sh, {}).keys()), "dedup_info": plan.get(sh, {})} for sh in shards if sh not in existing]
285
+ 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)
286
+ pending = []; failed = []
287
+ with ProcessPoolExecutor(max_workers=args.workers) as ex:
288
+ for s in ex.map(process_shard, tasks):
289
+ if "error" in s: failed.append(s["shard"]); print(json.dumps({"event": "error", **s}, ensure_ascii=False)[:600], flush=True); continue
290
+ 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)
291
+ if args.upload_repo:
292
+ pending.append(s["shard"])
293
+ if len(pending) >= args.upload_batch: upload_batch(api, args.upload_repo, f"{args.upload_prefix}/{args.dir}", args.output_root, pending, True); pending = []
294
+ if args.upload_repo and pending: upload_batch(api, args.upload_repo, f"{args.upload_prefix}/{args.dir}", args.output_root, pending, True)
295
+ print(json.dumps({"event": "finish", "dir": args.dir, "shards": len(tasks), "failed": failed}), flush=True)
296
+
297
+
298
+ if __name__ == "__main__":
299
+ main()