diff --git a/code/3c1a8da-dirty-0c72d075/src/aggregate_summaries.py b/code/3c1a8da-dirty-0c72d075/src/aggregate_summaries.py new file mode 100644 index 0000000000000000000000000000000000000000..d313c6c747835b2b850fff954abe0293bd83b322 --- /dev/null +++ b/code/3c1a8da-dirty-0c72d075/src/aggregate_summaries.py @@ -0,0 +1,274 @@ +"""シャードごとの shard_summary.json を集約し、全件の件数・母数・内訳を出す。 + +ローカルのディレクトリ(``--root``)か、HF データセット(``--repo`` と ``--prefix``、 +``outputs/**/shard_summary.json`` を取得)を入力にできる。``--expected-inputs`` に +入力データセット名を渡すと、入力シャード一覧と突き合わせて未処理シャードを列挙する。 + + uv run python abeja-cc-ja/src/aggregate_summaries.py --repo Podtech/abeja-cc-ja-cleaned --prefix outputs \\ + --expected-inputs Podtech/abeja-cc-ja-filtered --output dataset_summary.json +""" + +from __future__ import annotations + +import argparse +import json +from collections import Counter, defaultdict +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + + +def _load_local(root: Path, marker: str = "shard_summary.json") -> list[dict[str, Any]]: + return [json.loads(p.read_text(encoding="utf-8")) for p in sorted(root.rglob(marker))] + + +def _load_repo(repo_id: str, prefix: str, marker: str = "shard_summary.json") -> list[dict[str, Any]]: + from huggingface_hub import snapshot_download + + local = snapshot_download(repo_id, repo_type="dataset", allow_patterns=[f"{prefix.strip('/')}/**/{marker}"]) + return _load_local(Path(local) / prefix.strip("/"), marker) + + +def aggregate_noise(summaries: list[dict[str, Any]]) -> dict[str, Any]: + """第2パス(noise_summary.json)の集約。パターン別・項目別・理由別に合算する。""" + + total = Counter() + by_reason = Counter() + by_item: dict[str, Counter] = defaultdict(Counter) + by_pattern: dict[str, Counter] = defaultdict(Counter) + pattern_meta: dict[str, dict[str, Any]] = {} + thresholds: Counter = Counter() + shards = [] + for s in summaries: + shards.append(s["shard"]) + n = s["noise"] + total["input_rows"] += s["input_rows"] + for k in ("records_deleted", "records_retained", "records_modified", "records_newline_joined", "chars_before", "chars_after_retained"): + total[k] += n.get(k) or 0 + if n.get("tokens_after_retained"): + total["tokens_after_retained"] += n["tokens_after_retained"] + for k, v in n["records_deleted_by_reason"].items(): + by_reason[k] += v + for item, v in n["by_item"].items(): + for k, x in v.items(): + by_item[item][k] += x + for p in n["patterns"]: + pattern_meta[p["id"]] = {"item": p["item"], "action": p["action"]} + for k in ("records_detected", "occurrences", "lines_removed", "replacements"): + by_pattern[p["id"]][k] += p[k] + thresholds[json.dumps(n["thresholds"], sort_keys=True, ensure_ascii=False)] += 1 + return { + "aggregated_at_utc": datetime.now(timezone.utc).isoformat(), + "stage": "noise", + "shards": len(shards), + "totals": dict(total), + "deletion_rate": round(total["records_deleted"] / max(1, total["input_rows"]), 5), + "records_deleted_by_reason": dict(by_reason), + "by_item": {k: dict(v) for k, v in sorted(by_item.items(), key=lambda kv: int(kv[0]))}, + "by_pattern": {k: {**pattern_meta[k], **dict(v)} for k, v in sorted(by_pattern.items(), key=lambda kv: (pattern_meta[kv[0]]["item"], kv[0]))}, + "thresholds": [json.loads(k) for k in thresholds], + "shard_list": sorted(shards), + } + + +def aggregate_guard(summaries: list[dict[str, Any]]) -> dict[str, Any]: + """第3パス(guard_summary.json)の集約。候補数・分類結果・削除カテゴリ別に合算する。""" + + total = Counter() + by_safety = Counter() + deleted_by_category = Counter() + unsafe_kept = Counter() + controversial = Counter() + match_docs = Counter() + thresholds: Counter = Counter() + seconds = Counter() + shards = [] + for s in summaries: + shards.append(s["shard"]) + for k in ("input_rows", "candidates", "records_deleted", "final_rows"): + total[k] += s.get(k) or 0 + for k, v in (s.get("by_safety") or {}).items(): + by_safety[k] += v + for k, v in (s.get("deleted_by_category") or {}).items(): + deleted_by_category[k] += v + for k, v in (s.get("unsafe_kept_by_category") or {}).items(): + unsafe_kept[k] += v + for k, v in (s.get("controversial_by_category") or {}).items(): + controversial[k] += v + for k, v in (s.get("match_docs_by_category") or {}).items(): + match_docs[k] += v + for k, v in (s.get("seconds") or {}).items(): + seconds[k] += v + thresholds[json.dumps(s.get("thresholds"), sort_keys=True, ensure_ascii=False)] += 1 + return { + "aggregated_at_utc": datetime.now(timezone.utc).isoformat(), + "stage": "guard", + "shards": len(shards), + "totals": dict(total), + "candidate_rate": round(total["candidates"] / max(1, total["input_rows"]), 5), + "deletion_rate": round(total["records_deleted"] / max(1, total["input_rows"]), 6), + "by_safety": dict(by_safety), + "deleted_by_category": dict(deleted_by_category), + "unsafe_kept_by_category": dict(unsafe_kept), + "controversial_by_category": dict(controversial), + "match_docs_by_category": dict(match_docs), + "seconds": dict(seconds), + "thresholds": [json.loads(k) for k in thresholds], + "shard_list": sorted(shards), + } + + +def _expected_shards(repo_id: str) -> set[str]: + from huggingface_hub import HfApi + + return {Path(p).stem for p in HfApi().list_repo_files(repo_id, repo_type="dataset") if p.endswith(".parquet")} + + +def aggregate(summaries: list[dict[str, Any]]) -> dict[str, Any]: + total = Counter() + by_reason = Counter() + by_category_match = Counter() + by_category_deleted = Counter() + by_source_matched = Counter() + by_source_deleted = Counter() + by_rule = Counter() + pii_records = Counter() + pii_replacements = Counter() + seconds = Counter() + policies = Counter() + versions = Counter() + shards = [] + for s in summaries: + shards.append(s["shard"]) + versions[s.get("pipeline_version", "?")] += 1 + total["input_rows"] += s["input_rows"] + total["toxic_deleted"] += s["toxic"]["records_deleted"] + total["toxic_retained"] += s["toxic"]["records_retained"] + total["pii_records_with_replacement"] += s["pii"]["records_with_replacement"] + total["pii_total_replacements"] += s["pii"]["total_replacements"] + total["final_rows"] += s["output"]["final_rows"] + for k, v in s["toxic"]["records_deleted_by_reason"].items(): + by_reason[k] += v + for c, v in s["toxic"]["by_category"].items(): + by_category_match[c] += v["records_with_match"] + by_category_deleted[c] += v["records_deleted"] + for name, v in (s["toxic"].get("domain_blocklist_by_source") or {}).items(): + by_source_matched[name] += v.get("records_matched", 0) + by_source_deleted[name] += v.get("records_deleted", 0) + for name, v in (s["toxic"].get("cooccurrence_by_rule") or {}).items(): + by_rule[name] += v.get("records_matched", 0) + for t, v in s["pii"]["by_type"].items(): + pii_records[t] += v["records_with_match"] + pii_replacements[t] += v["replacement_count"] + for k, v in s["seconds"].items(): + seconds[k] += v + p = s["pii"].get("policy") or {} + policies[f"{p.get('action')}|{p.get('approved_by')}|{p.get('approved_on')}|{p.get('status')}"] += 1 + n = total["input_rows"] or 1 + return { + "aggregated_at_utc": datetime.now(timezone.utc).isoformat(), + "shards": len(shards), + "pipeline_versions": dict(versions), + "totals": dict(total), + "toxic": { + "deletion_rate": round(total["toxic_deleted"] / n, 5), + "records_deleted_by_reason": dict(by_reason), + "by_category": {c: {"records_with_match": by_category_match[c], "records_deleted": by_category_deleted[c]} for c in sorted(set(by_category_match) | set(by_category_deleted))}, + "domain_blocklist_by_source": {k: {"records_matched": by_source_matched[k], "records_deleted": by_source_deleted[k]} for k in sorted(by_source_matched)}, + "cooccurrence_by_rule": dict(by_rule), + }, + "pii": { + "denominator_records": total["toxic_retained"], + "records_with_replacement_rate": round(total["pii_records_with_replacement"] / max(1, total["toxic_retained"]), 5), + "by_type": {t: {"records_with_match": pii_records[t], "replacement_count": pii_replacements[t]} for t in sorted(pii_records)}, + "policies": dict(policies), + }, + "seconds": dict(seconds), + "shard_list": sorted(shards), + } + + +def aggregate_quality(summaries: list[dict[str, Any]]) -> dict[str, Any]: + """第4パス(quality_summary.json)の集約。削除理由・フラグ・ジャンル別の件数と、文字数・トークン数を合算する。""" + + total = Counter() + by_reason = Counter() + deleted_by_flag = Counter() + deleted_by_genre = Counter() + retained_by_genre = Counter() + chars = Counter() + tokens = Counter() + features = Counter() + tokenizers: Counter = Counter() + thresholds: Counter = Counter() + seconds = Counter() + shards = [] + for s in summaries: + shards.append(s["shard"]) + for k in ("input_rows", "records_deleted", "final_rows"): + total[k] += s.get(k) or 0 + for name, counter in (("records_deleted_by_reason", by_reason), ("deleted_by_flag", deleted_by_flag), ("deleted_by_genre", deleted_by_genre), + ("retained_by_genre", retained_by_genre), ("chars", chars), ("features", features), ("seconds", seconds)): + for k, v in (s.get(name) or {}).items(): + counter[k] += v + tk = s.get("tokens") or {} + if tk: + tokenizers[tk.get("tokenizer") or ""] += 1 + for k in ("input", "deleted", "final"): + tokens[k] += tk.get(k) or 0 + thresholds[json.dumps(s.get("thresholds"), sort_keys=True, ensure_ascii=False)] += 1 + return { + "aggregated_at_utc": datetime.now(timezone.utc).isoformat(), + "stage": "quality", + "shards": len(shards), + "totals": dict(total), + "deletion_rate": round(total["records_deleted"] / max(1, total["input_rows"]), 6), + "records_deleted_by_reason": dict(by_reason), + "deleted_by_flag": dict(deleted_by_flag), + "deleted_by_genre": dict(deleted_by_genre), + "retained_by_genre": dict(retained_by_genre), + "chars": dict(chars), + "tokens": ({"tokenizers": dict(tokenizers), **dict(tokens), "shards_with_tokens": sum(tokenizers.values())} if tokenizers else None), + "features": dict(features), + "seconds": dict(seconds), + "thresholds": [json.loads(k) for k in thresholds], + "shard_list": sorted(shards), + } + + +def main(argv: list[str] | None = None) -> None: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + source = parser.add_mutually_exclusive_group(required=True) + source.add_argument("--root", type=Path) + source.add_argument("--repo") + parser.add_argument("--prefix", default="outputs") + parser.add_argument("--expected-inputs", default=None, help="入力データセット(未処理シャードの検出用)") + parser.add_argument("--stage", choices=("full", "noise", "guard", "quality"), default="full", help="noise: 第2パスの noise_summary.json、guard: 第3パスの guard_summary.json、quality: 第4パスの quality_summary.json を集約") + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args(argv) + marker = {"noise": "noise_summary.json", "guard": "guard_summary.json", "quality": "quality_summary.json"}.get(args.stage, "shard_summary.json") + summaries = _load_local(args.root, marker) if args.root else _load_repo(args.repo, args.prefix, marker) + result = {"noise": aggregate_noise, "guard": aggregate_guard, "quality": aggregate_quality}.get(args.stage, aggregate)(summaries) + if args.expected_inputs: + expected = _expected_shards(args.expected_inputs) + done = set(result["shard_list"]) + result["completeness"] = {"expected": len(expected), "done": len(done & expected), "missing": sorted(expected - done)[:200], "missing_count": len(expected - done), "unexpected": sorted(done - expected)[:50]} + args.output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + t = result["totals"] + if args.stage == "quality": + print(json.dumps({"shards": result["shards"], "input_rows": t.get("input_rows"), "quality_deleted": t.get("records_deleted"), + "final_rows": t.get("final_rows"), "by_reason": result["records_deleted_by_reason"], "chars_final": result["chars"].get("final"), + "tokens_final": (result.get("tokens") or {}).get("final"), "completeness": result.get("completeness", {}).get("missing_count")}, ensure_ascii=False)) + elif args.stage == "guard": + print(json.dumps({"shards": result["shards"], "input_rows": t.get("input_rows"), "candidates": t.get("candidates"), "guard_deleted": t.get("records_deleted"), + "final_rows": t.get("final_rows"), "by_safety": result["by_safety"], "completeness": result.get("completeness", {}).get("missing_count")}, ensure_ascii=False)) + elif args.stage == "noise": + print(json.dumps({"shards": result["shards"], "input_rows": t.get("input_rows"), "noise_deleted": t.get("records_deleted"), "retained": t.get("records_retained"), + "modified": t.get("records_modified"), "completeness": result.get("completeness", {}).get("missing_count")}, ensure_ascii=False)) + else: + print(json.dumps({"shards": result["shards"], "input_rows": t.get("input_rows"), "toxic_deleted": t.get("toxic_deleted"), "final_rows": t.get("final_rows"), + "pii_replacements": t.get("pii_total_replacements"), "completeness": result.get("completeness", {}).get("missing_count")}, ensure_ascii=False)) + + +if __name__ == "__main__": + main() diff --git a/code/3c1a8da-dirty-0c72d075/src/audit_report.py b/code/3c1a8da-dirty-0c72d075/src/audit_report.py new file mode 100644 index 0000000000000000000000000000000000000000..5b45f18115e1f7bcf4312d0b3ab399207d1ee473 --- /dev/null +++ b/code/3c1a8da-dirty-0c72d075/src/audit_report.py @@ -0,0 +1,239 @@ +"""監査項目B(有害・倫理的に問題のあるコンテンツ、項目5〜10)の報告書を生成する。 + +有害フィルタの出力(summary.json, removed.jsonl, cooccurrence_review.jsonl)と、 +あれば分類器の出力(classify_qwen3guard.py)、目視集計(review_tally.py)を +統合し、項目ごとに「適用した手法」「検出・除外件数」「例3件」「適用リスト」を +Markdown にまとめる。手法が1つしか適用されていない項目は「実施」と表示しない。 + + uv run python abeja-cc-ja/src/audit_report.py --output-root \ + [--classified review/classified.jsonl] [--review-tally review/review_tally.json] \ + --output audit_report.md +""" + +from __future__ import annotations + +import argparse +import json +from collections import Counter, defaultdict +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +from textmatch import normalize + + +# 監査項目と、フィルタ内部のカテゴリ・規則・ブロックリストの対応。 +AUDIT_ITEMS: list[dict[str, Any]] = [ + {"item": 5, "title": "性的・わいせつな表現(未成年文脈は0件)", + "wordlist": ["adult"], "cooccurrence": ["minor_sexual_context"], + "blocklist": ["ut1:adult", "ut1:mixed_adult", "ut1:child", "local:domains", "local:rules"], + "classifier": ["Sexual Content or Sexual Acts"]}, + {"item": 6, "title": "暴力・自傷・自殺の助長、危害を加える具体的手順", + "wordlist": ["violence"], "cooccurrence": [], "blocklist": [], + "classifier": ["Violent", "Suicide & Self-Harm"]}, + {"item": 7, "title": "差別・ヘイト、誹謗中傷", + "wordlist": ["discrimination"], "cooccurrence": [], "blocklist": ["ut1:agressif"], + "classifier": ["Unethical Acts"]}, + {"item": 8, "title": "違法行為の手引き(薬物、武器、詐欺、不正アクセス等)", + "wordlist": ["crime"], "cooccurrence": ["illegal_howto"], + "blocklist": ["ut1:drogue", "ut1:dangerous_material", "ut1:hacking"], + "classifier": ["Non-violent Illegal Acts"]}, + {"item": 9, "title": "過激な政治・宗教プロパガンダ、陰謀論", + "wordlist": ["propaganda_conspiracy"], "cooccurrence": [], "blocklist": ["ut1:sect", "ut1:fakenews"], + "classifier": ["Politically Sensitive Topics"]}, + {"item": 10, "title": "スパム・詐欺・アダルト・違法コピー配布サイト由来のページ", + "wordlist": ["spam"], "cooccurrence": [], + "blocklist": ["ut1:adult", "ut1:mixed_adult", "ut1:gambling", "ut1:phishing", "ut1:malware", "ut1:warez", + "ut1:cryptojacking", "ut1:stalkerware", "ut1:ddos", "ut1:dating", "local:domains", "local:rules"], + "classifier": ["Copyright Violation"]}, +] + + +def _read_jsonl(path: Path) -> list[dict[str, Any]]: + if not path or not path.exists(): + return [] + with path.open(encoding="utf-8") as handle: + return [json.loads(line) for line in handle if line.strip()] + + +def _snippet(record: dict[str, Any], terms: list[str], length: int = 90) -> str: + text = normalize(record.get("content") or "") + position = -1 + for term in terms: + position = text.find(term) + if position >= 0: + break + start = max(0, position - length // 3) if position >= 0 else 0 + return text[start:start + length].replace("\n", " ").replace("|", "/") + + +def _examples_wordlist(removed: list[dict[str, Any]], category: str, limit: int = 3) -> list[str]: + rows = [] + for record in removed: + if category not in record.get("_filter_deleted_categories", []): + continue + terms = record["_filter_distinct_matched_terms_by_category"].get(category, []) + rows.append(f"| {record.get('_filter_record_index')} | {record.get('url', '')[:70]} | {', '.join(terms[:5])} | {_snippet(record, terms)} |") + if len(rows) >= limit: + break + return rows + + +def _examples_cooccurrence(review: list[dict[str, Any]], rule: str, limit: int = 3) -> list[str]: + rows = [] + for item in review: + if item["rule"] != rule: + continue + pairs = ", ".join(f"{p['a']}×{p['b']}" for p in item["pairs"][:3]) + rows.append(f"| {item['record_index']} | {item.get('url', '')[:70]} | {pairs} | {item['excerpt'][:90].replace('|', '/')} |") + if len(rows) >= limit: + break + return rows + + +def _examples_blocklist(removed: list[dict[str, Any]], sources: list[str], limit: int = 3) -> list[str]: + rows = [] + for record in removed: + hits = [m for m in record.get("_filter_domain_matches", []) if m["source"] in sources and m["action"] == "delete"] + if not hits: + continue + rows.append(f"| {record.get('_filter_record_index')} | {record.get('url', '')[:70]} | {hits[0]['source']} ({hits[0]['matched'][:40]}) | |") + if len(rows) >= limit: + break + return rows + + +def main(argv: list[str] | None = None) -> None: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--mode", default="distinct_terms_3plus") + parser.add_argument("--classified", type=Path, default=None, help="classify_qwen3guard.py の出力JSONL") + parser.add_argument("--review-tally", type=Path, default=None, help="review_tally.py の出力JSON") + parser.add_argument("--sampling-manifest", type=Path, default=None) + parser.add_argument("--output", type=Path, default=None, help="既定は /audit_report.md") + args = parser.parse_args(argv) + + mode_dir = args.output_root / args.mode + summary = json.loads((mode_dir / "summary.json").read_text(encoding="utf-8")) + removed = _read_jsonl(mode_dir / "removed.jsonl") + review = _read_jsonl(mode_dir / "cooccurrence_review.jsonl") + classified = _read_jsonl(args.classified) if args.classified else [] + tally = json.loads(args.review_tally.read_text(encoding="utf-8")) if args.review_tally and args.review_tally.exists() else None + sampling = json.loads(args.sampling_manifest.read_text(encoding="utf-8")) if args.sampling_manifest and args.sampling_manifest.exists() else None + + total = summary["total_records_scanned"] + block = summary.get("domain_blocklist", {}) + cooc = summary.get("cooccurrence", {}) + by_reason = summary.get("records_deleted_by_reason", {}) + + # 分類器の集計(層別 × 判定) + classifier_by_stratum: dict[str, Counter] = defaultdict(Counter) + classifier_by_category: Counter = Counter() + for record in classified: + classifier_by_stratum[record.get("stratum", "?")][record.get("safety") or "unparsed"] += 1 + for category in record.get("categories", []): + classifier_by_category[category] += 1 + + lines: list[str] = [] + lines.append(f"# 有害コンテンツ監査報告(項目B: 5〜10)") + lines.append("") + lines.append(f"- 生成日時: {datetime.now(timezone.utc).isoformat()}") + lines.append(f"- 対象: `{summary['source_file']}`(行 {summary['row_range']['start_row_inclusive']}〜{summary['row_range']['end_row_exclusive']}、{total:,} 文書)") + lines.append(f"- 削除合計: {summary['records_deleted']:,} 文書({summary['deletion_rate']*100:.2f}%)。理由別: ワードリスト {by_reason.get('wordlist', 0):,}、ドメインブロックリスト {by_reason.get('domain_blocklist', 0):,}、近接共起 {by_reason.get('cooccurrence', 0):,}、複数理由 {by_reason.get('multiple_reasons', 0):,}") + lines.append("") + lines.append("## 適用した手法") + lines.append("") + lines.append("| 手法 | 状態 | 内容 |") + lines.append("|---|---|---|") + lines.append(f"| 辞書(ワードリスト) | 適用 | カテゴリ別語彙、同一カテゴリ{summary['threshold']}語以上で削除。除外語: " + ", ".join(f"{k} {len(v)}" for k, v in summary.get("wordlist_excluded_terms_by_category", {}).items()) + " |") + lines.append(f"| 辞書(近接共起規則) | {'適用' if cooc.get('enabled') else '未適用'} | " + "; ".join(f"{r['name']}({r['label_ja']}、{r['window']}文字以内)" for r in cooc.get("rules", [])) + " |") + lines.append(f"| ドメインブロックリスト | {'適用' if block.get('enabled') else '未適用'} | " + ", ".join(f"{s['name']}={s['entries']:,}" for s in block.get("sources", [])) + " |") + if classified: + lines.append(f"| 分類器 | 適用(サンプル) | {classified[0].get('model', '')} を {len(classified)} 文書へ適用。判定: " + ", ".join(f"{k} {v}" for k, v in sorted(Counter(r.get('safety') or 'unparsed' for r in classified).items())) + " |") + else: + lines.append("| 分類器 | 未適用 | `classify_qwen3guard.py` の出力を `--classified` で渡す |") + if tally: + reviewed = sum(e.get("reviewed", 0) for e in tally["strata"].values()) + lines.append(f"| 目視 | {'適用' if reviewed else '未記入'} | 判定済み {reviewed} 件、判定者 {', '.join(tally.get('reviewers', [])) or '未記入'} |") + else: + lines.append("| 目視 | 未適用 | `sample_for_review.py` → 記入 → `review_tally.py` の結果を `--review-tally` で渡す |") + lines.append("") + methods_applied = 1 + (1 if classified else 0) + (1 if tally and any(e.get("reviewed") for e in tally["strata"].values()) else 0) + lines.append(f"手法数: {methods_applied}/3。" + ("3手法が揃っており「実施」と表示できます。" if methods_applied >= 3 else "3手法が揃うまでは「実施」としないこと。")) + lines.append("") + + if block.get("enabled"): + lines.append("## 適用したドメインブロックリスト") + lines.append("") + lines.append("| リスト | 動作 | 件数 | 一致文書 | 削除文書 | 取得元 | 取得日時 | SHA-256 |") + lines.append("|---|---|---:|---:|---:|---|---|---|") + for source in block["sources"]: + stat = block["by_source"].get(source["name"], {}) + lines.append(f"| {source['name']} | {source['action']} | {source['entries']:,} | {stat.get('records_matched', 0)} | {stat.get('records_deleted', 0)} | {source.get('source_url') or source.get('path')} | {source.get('fetched_at_utc') or ''} | {(source.get('sha256') or '')[:16]} |") + lines.append("") + + for spec in AUDIT_ITEMS: + lines.append(f"## 項目{spec['item']}: {spec['title']}") + lines.append("") + counts_lines = [] + for category in spec["wordlist"]: + cat = summary["by_category"].get(category, {}) + counts_lines.append(f"- ワードリスト `{category}`: 一致 {cat.get('records_with_match', 0):,} 文書、削除 {cat.get('records_deleted', 0):,} 文書({cat.get('distinct_terms_matched', 0)} 語が一致)") + for rule in spec["cooccurrence"]: + stat = cooc.get("by_rule", {}).get(rule) + if stat is not None: + counts_lines.append(f"- 近接共起 `{rule}`({stat['label_ja']}): 一致・削除 {stat['records_matched']:,} 文書。全件を `cooccurrence_review.jsonl` で目視確認する") + for source_name in spec["blocklist"]: + stat = block.get("by_source", {}).get(source_name) + if stat is not None: + counts_lines.append(f"- ブロックリスト `{source_name}`({stat['action']}): 一致 {stat['records_matched']:,} 文書、削除 {stat['records_deleted']:,} 文書") + if classified: + hit = sum(1 for r in classified if any(c in spec["classifier"] for c in r.get("categories", []))) + counts_lines.append(f"- 分類器: サンプル {len(classified)} 件中 {hit} 件が {', '.join(spec['classifier'])} に該当") + if tally: + for stratum, entry in tally["strata"].items(): + if any(stratum.endswith(":" + c) for c in spec["wordlist"] + spec["cooccurrence"]): + rate = entry.get("precision", entry.get("harmful_rate")) + counts_lines.append(f"- 目視 `{stratum}`: harmful {entry['harmful']}、not_harmful {entry['not_harmful']}、unsure {entry['unsure']}、未確認 {entry['unreviewed']}" + (f"、精度 {rate}" if rate is not None else "")) + lines.extend(counts_lines or ["- 該当する検出手段なし"]) + if spec["item"] == 5: + minor = cooc.get("by_rule", {}).get("minor_sexual_context", {}) + lines.append(f"- 未成年文脈: 共起規則で {minor.get('records_matched', 0):,} 文書を削除。保持データ側の残存は目視層 `cooccurrence:minor_sexual_context` と `retained:random` の確認結果で判断する") + lines.append("") + lines.append("例(最大3件):") + lines.append("") + lines.append("| record_index | URL | 該当語・規則 | 抜粋 |") + lines.append("|---|---|---|---|") + examples: list[str] = [] + for category in spec["wordlist"]: + examples.extend(_examples_wordlist(removed, category)) + for rule in spec["cooccurrence"]: + examples.extend(_examples_cooccurrence(review, rule)) + examples.extend(_examples_blocklist(removed, spec["blocklist"])) + lines.extend(examples[:3] if examples else ["| | (該当なし) | | |"]) + lines.append("") + + if sampling: + lines.append("## 目視サンプル") + lines.append("") + lines.append(f"- 抽出日時 {sampling['created_at_utc']}、seed {sampling['seed']}、合計 {sampling['total_samples']} 件") + lines.append("- 層別件数: " + ", ".join(f"{k} {v}" for k, v in sampling["strata"].items())) + lines.append("") + if classified: + lines.append("## 分類器の層別結果") + lines.append("") + lines.append("| 層 | Safe | Controversial | Unsafe | 未解析 |") + lines.append("|---|---:|---:|---:|---:|") + for stratum, counter in sorted(classifier_by_stratum.items()): + lines.append(f"| {stratum} | {counter.get('Safe', 0)} | {counter.get('Controversial', 0)} | {counter.get('Unsafe', 0)} | {counter.get('unparsed', 0)} |") + lines.append("") + lines.append("カテゴリ別: " + ", ".join(f"{k} {v}" for k, v in classifier_by_category.most_common())) + lines.append("") + + output = args.output or (args.output_root / "audit_report.md") + output.write_text("\n".join(lines) + "\n", encoding="utf-8") + print(f"wrote {output} ({len(lines)} lines); methods_applied={methods_applied}/3") + + +if __name__ == "__main__": + main() diff --git a/code/3c1a8da-dirty-0c72d075/src/blocklists/blocklist_config.json b/code/3c1a8da-dirty-0c72d075/src/blocklists/blocklist_config.json new file mode 100644 index 0000000000000000000000000000000000000000..3178c697bbc1aec0a900db549af8520fe079359c --- /dev/null +++ b/code/3c1a8da-dirty-0c72d075/src/blocklists/blocklist_config.json @@ -0,0 +1,32 @@ +{ + "ut1": { + "description_ja": "UT1 blacklists(トゥールーズ・キャピトル大学)。delete は該当文書を削除、flag は記録のみ。", + "categories": { + "adult": "delete", + "mixed_adult": "delete", + "child": "delete", + "gambling": "delete", + "phishing": "delete", + "malware": "delete", + "warez": "delete", + "cryptojacking": "delete", + "stalkerware": "delete", + "ddos": "delete", + "dangerous_material": "delete", + "drogue": "delete", + "sect": "delete", + "agressif": "delete", + "hacking": "flag", + "fakenews": "flag", + "dating": "flag" + } + }, + "local": { + "description_ja": "このリポジトリで管理する日本語Web向けの補助リスト。", + "domains": "ja_domains_blocklist.txt", + "rules": "ja_domain_token_rules.txt", + "action": "delete", + "allowlist": "ja_domain_allowlist.txt", + "allowlist_note_ja": "allowlist のドメインには UT1 のドメイン一致を適用しない(自前リスト・規則・本文判定は適用する)。" + } +} diff --git a/code/3c1a8da-dirty-0c72d075/src/blocklists/ja_domain_allowlist.txt b/code/3c1a8da-dirty-0c72d075/src/blocklists/ja_domain_allowlist.txt new file mode 100644 index 0000000000000000000000000000000000000000..53c40947427e4ecccbb2e2e5a0d7f40802416b01 --- /dev/null +++ b/code/3c1a8da-dirty-0c72d075/src/blocklists/ja_domain_allowlist.txt @@ -0,0 +1,17 @@ +# UT1 のドメイン一致を適用しない許可リスト。形式: ドメイン [理由]。サブドメインも対象。 +# 多数のサイトが同居するプラットフォームや、成人向け区画を持つだけの大規模一般サイトは、 +# ドメイン単位の削除だと一般コンテンツを大量に失うため、本文のワードリスト・共起規則で判定する。 +# 根拠: common_crawl_0_filtered_0001 で ut1:adult に一致した上位ドメイン。 +fc2.com 共用ブログホスト(blogNN.fc2.com)。個別ブログは本文で判定 +pixiv.net イラスト投稿プラットフォーム。R-18は一部 +dmm.com 総合EC・ゲーム。成人向けは dmm.co.jp +dlsite.com 同人ショップ。成人向けは /maniax 配下 +papy.co.jp 電子書籍ストア +shueisha.co.jp 出版社(週刊プレイボーイ等) +cosmopolitan.com 一般誌 +hatenablog.com 共用ブログホスト +livedoor.jp 共用ブログホスト +ameblo.jp 共用ブログホスト +seesaa.net 共用ブログホスト +exblog.jp 共用ブログホスト +goo.ne.jp ポータル・共用ブログ diff --git a/code/3c1a8da-dirty-0c72d075/src/blocklists/ja_domain_token_rules.txt b/code/3c1a8da-dirty-0c72d075/src/blocklists/ja_domain_token_rules.txt new file mode 100644 index 0000000000000000000000000000000000000000..8dad30bb1fab52dbce200032673a7f947461c7a8 --- /dev/null +++ b/code/3c1a8da-dirty-0c72d075/src/blocklists/ja_domain_token_rules.txt @@ -0,0 +1,6 @@ +# ドメイン名規則。形式: ラベル正規表現(ホスト名に対して search)。 +# トークン境界(先頭・ドット・ハイフン)を要求し、hero.jp のような偶然の部分一致を避ける。 +# adult(adhd-adult.info)と deai(出会いアプリ紹介)は誤検出が多いため2026-09-04に除外。 +gambling (^|[.-])(online)?(casino|casinos|kajino|onkaji|onlinecasino)[a-z0-9-]*([.-]|$) +adult (^|[.-])(porn[a-z0-9]*|xxx|hentai[a-z0-9]*|sexy[a-z0-9]*|sex(movie|video|blog|site|douga|gazou)[a-z0-9]*|ero(manga|douga|ge|anime|video|movie|gazou|blog|site|[0-9]+)?|eroero|nukige|fuzoku|18kin|nozoki[a-z0-9]*)([.-]|$) +warez (^|[.-])(warez|torrents?|keygen|serials?|crackz?)([.-]|$) diff --git a/code/3c1a8da-dirty-0c72d075/src/blocklists/ja_domains_blocklist.txt b/code/3c1a8da-dirty-0c72d075/src/blocklists/ja_domains_blocklist.txt new file mode 100644 index 0000000000000000000000000000000000000000..85e42cd7ceecebce5aa905c11287948d2d23fbee --- /dev/null +++ b/code/3c1a8da-dirty-0c72d075/src/blocklists/ja_domains_blocklist.txt @@ -0,0 +1,15 @@ +# 自前ドメインブロックリスト。形式: ドメイン [ラベル]。サブドメインも一致する。 +# 根拠: common_crawl_0_filtered_0001 の有害フィルタ削除文書のうち、ドメイン名と内容から +# サイト全体が対象カテゴリと判断できたもの。追加時はコメントに根拠を残すこと。 +oshiete-onlinecasino.net gambling +onlinecasinofan.com gambling +onlinecasinoget.com gambling +on-casi.info gambling +on-linecasinoplay.com gambling +win-spin-casinos-deposit.site gambling +casinotop10.jp gambling +japanesecasinoreview.com gambling +ero-mangalife.com adult +sexyaction.net adult +sexynews24.info adult +nozokima.site adult diff --git a/code/3c1a8da-dirty-0c72d075/src/classify_qwen3guard.py b/code/3c1a8da-dirty-0c72d075/src/classify_qwen3guard.py new file mode 100644 index 0000000000000000000000000000000000000000..c2c1d14e1cd531d9af6a9cf213867ae358b601bb --- /dev/null +++ b/code/3c1a8da-dirty-0c72d075/src/classify_qwen3guard.py @@ -0,0 +1,161 @@ +"""Qwen3Guard-Gen による有害性分類(監査の第2手法)。 + +辞書・ブロックリスト・共起規則とは独立した分類器として、目視サンプルや +境界文書に適用する。全件へ適用するには計算量が大きいため、 +``sample_for_review.py`` が出力するサンプルJSONLを入力にする想定。 + +入力JSONL: ``{"id": ..., "url": ..., "text": ..., "match_positions": [..]}`` +出力JSONL: 入力に ``safety``(Safe/Unsafe/Controversial)、``categories``、 +``raw_output``、``elapsed_s`` を加えたもの。併せて ``.manifest.json`` に +モデル名・リビジョン・実行条件を記録する。 + +依存関係は ``uv sync --group classifier`` で導入する(torch, transformers)。 + + uv run python abeja-cc-ja/src/classify_qwen3guard.py --input samples.jsonl --output classified.jsonl +""" + +from __future__ import annotations + +import argparse +import json +import re +import time +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + + +DEFAULT_MODEL = "Qwen/Qwen3Guard-Gen-0.6B" +SAFETY_RE = re.compile(r"Safety:\s*(Safe|Unsafe|Controversial)") +CATEGORY_RE = re.compile( + r"(Violent|Non-violent Illegal Acts|Sexual Content or Sexual Acts|PII|Suicide & Self-Harm|" + r"Unethical Acts|Politically Sensitive Topics|Copyright Violation|Jailbreak|None)" +) +# Qwen3Guard のカテゴリと監査項目(5〜10)の対応。 +CATEGORY_TO_AUDIT_ITEM = { + "Sexual Content or Sexual Acts": 5, + "Violent": 6, + "Suicide & Self-Harm": 6, + "Unethical Acts": 7, + "Non-violent Illegal Acts": 8, + "Politically Sensitive Topics": 9, + "Copyright Violation": 10, +} + + +def build_excerpt(text: str, positions: list[int] | None, max_chars: int, window: int = 300, head: int = 1000) -> str: + """先頭と、一致位置の前後を優先して抜粋する。長文をそのまま渡さない。""" + + if len(text) <= max_chars: + return text + pieces: list[tuple[int, int]] = [(0, min(head, len(text)))] + for position in (positions or [])[:4]: + pieces.append((max(0, position - window), min(len(text), position + window))) + pieces.sort() + merged: list[list[int]] = [] + for start, end in pieces: + if merged and start <= merged[-1][1]: + merged[-1][1] = max(merged[-1][1], end) + else: + merged.append([start, end]) + excerpt = " … ".join(text[start:end] for start, end in merged) + return excerpt[:max_chars] + + +def parse_output(content: str) -> tuple[str | None, list[str]]: + safety = SAFETY_RE.search(content) + categories = [item for item in CATEGORY_RE.findall(content) if item != "None"] + return (safety.group(1) if safety else None), sorted(set(categories)) + + +def load_model(model_name: str, device: str): + import torch + from transformers import AutoModelForCausalLM, AutoTokenizer + + tokenizer = AutoTokenizer.from_pretrained(model_name) + kwargs: dict[str, Any] = {} + if device == "auto": + kwargs["device_map"] = "auto" + try: + model = AutoModelForCausalLM.from_pretrained(model_name, dtype="auto", **kwargs) + except TypeError: + model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", **kwargs) + if device != "auto": + model = model.to(device) + model.eval() + return tokenizer, model, torch + + +def classify_text(tokenizer, model, torch, text: str, max_new_tokens: int = 64) -> str: + messages = [{"role": "user", "content": text}] + prompt = tokenizer.apply_chat_template(messages, tokenize=False) + inputs = tokenizer([prompt], return_tensors="pt").to(model.device) + with torch.no_grad(): + generated = model.generate(**inputs, max_new_tokens=max_new_tokens, do_sample=False) + output_ids = generated[0][len(inputs.input_ids[0]):].tolist() + return tokenizer.decode(output_ids, skip_special_tokens=True) + + +def main(argv: list[str] | None = None) -> None: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--input", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--model", default=DEFAULT_MODEL) + parser.add_argument("--device", default="auto", help="auto / cpu / mps / cuda") + parser.add_argument("--max-chars", type=int, default=3000) + parser.add_argument("--max-new-tokens", type=int, default=64) + parser.add_argument("--limit", type=int, default=None) + args = parser.parse_args(argv) + + tokenizer, model, torch = load_model(args.model, args.device) + revision = getattr(getattr(model, "config", None), "_commit_hash", None) + started = datetime.now(timezone.utc).isoformat() + counts: dict[str, int] = {"Safe": 0, "Unsafe": 0, "Controversial": 0, "unparsed": 0} + processed = 0 + args.output.parent.mkdir(parents=True, exist_ok=True) + with args.input.open(encoding="utf-8") as reader, args.output.open("w", encoding="utf-8") as writer: + for line in reader: + if not line.strip(): + continue + if args.limit is not None and processed >= args.limit: + break + record = json.loads(line) + text = build_excerpt(record.get("text") or "", record.get("match_positions"), args.max_chars) + t0 = time.perf_counter() + raw = classify_text(tokenizer, model, torch, text, args.max_new_tokens) + elapsed = time.perf_counter() - t0 + safety, categories = parse_output(raw) + counts[safety or "unparsed"] += 1 + record.update({ + "safety": safety, + "categories": categories, + "audit_items": sorted({CATEGORY_TO_AUDIT_ITEM[c] for c in categories if c in CATEGORY_TO_AUDIT_ITEM}), + "raw_output": raw.strip(), + "excerpt_chars": len(text), + "elapsed_s": round(elapsed, 3), + "model": args.model, + }) + record.pop("text", None) + writer.write(json.dumps(record, ensure_ascii=False, separators=(",", ":")) + "\n") + processed += 1 + manifest = { + "model": args.model, + "model_revision": revision, + "device": str(model.device), + "max_chars": args.max_chars, + "max_new_tokens": args.max_new_tokens, + "started_at_utc": started, + "finished_at_utc": datetime.now(timezone.utc).isoformat(), + "input": str(args.input), + "output": str(args.output), + "processed": processed, + "counts": counts, + "category_to_audit_item": CATEGORY_TO_AUDIT_ITEM, + "taxonomy_note": "Qwen3Guard: Safe / Controversial / Unsafe。Controversial は文脈依存の判定。", + } + Path(str(args.output) + ".manifest.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + print(json.dumps({"processed": processed, "counts": counts, "model": args.model}, ensure_ascii=False)) + + +if __name__ == "__main__": + main() diff --git a/code/3c1a8da-dirty-0c72d075/src/cooccurrence.py b/code/3c1a8da-dirty-0c72d075/src/cooccurrence.py new file mode 100644 index 0000000000000000000000000000000000000000..71b4b01feaa300d4a7928428a15416bf165a8f90 --- /dev/null +++ b/code/3c1a8da-dirty-0c72d075/src/cooccurrence.py @@ -0,0 +1,136 @@ +"""2種類の語群が近接して現れる文書を検出する近接共起規則。 + +単語リストの密度(同一カテゴリ3語以上)では判別できない次の2種類を扱う。 + +* 未成年を示す語 × 性的な語(監査項目5「未成年が登場する文脈は0件」) +* 違法行為の対象語 × 手引きを示す語(監査項目8「違法行為の手引き」) + +規則は ``wordlists/cooccurrence/rules.json`` に定義し、語リストは同じ +ディレクトリの1行1語ファイルから読む。一致した文書は削除対象になると同時に、 +全件が目視確認用の ``cooccurrence_review.jsonl`` へ書き出される。 +""" + +from __future__ import annotations + +import bisect +import json +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +from textmatch import compile_trie_pattern, normalize, read_terms + + +@dataclass(frozen=True) +class CooccurrenceRule: + name: str + category: str + label_ja: str + terms_a: tuple[str, ...] + terms_b: tuple[str, ...] + window: int + description_ja: str = "" + terms_a_file: str = "" + terms_b_file: str = "" + + +def load_rules(path: Path) -> list[CooccurrenceRule]: + """規則定義JSONと語リストを読む。語リストのパスはJSONからの相対パス。""" + + spec = json.loads(path.read_text(encoding="utf-8")) + base = path.parent + rules: list[CooccurrenceRule] = [] + for item in spec["rules"]: + terms_a = read_terms(base / item["terms_a"]) + terms_b = read_terms(base / item["terms_b"]) + if not terms_a or not terms_b: + raise ValueError(f"規則 {item['name']} の語リストが空です: {item['terms_a']}, {item['terms_b']}") + rules.append( + CooccurrenceRule( + name=item["name"], + category=item["category"], + label_ja=item["label_ja"], + terms_a=tuple(dict.fromkeys(terms_a)), + terms_b=tuple(dict.fromkeys(terms_b)), + window=int(item.get("window", 100)), + description_ja=item.get("description_ja", ""), + terms_a_file=item["terms_a"], + terms_b_file=item["terms_b"], + ) + ) + return rules + + +class CooccurrenceDetector: + """各規則について、語群Aと語群Bの出現位置が window 文字以内の組を探す。""" + + def __init__(self, rules: list[CooccurrenceRule]) -> None: + self.rules = rules + self._patterns = [ + ( + rule, + compile_trie_pattern(sorted(rule.terms_a, key=lambda t: (-len(t), t))), + compile_trie_pattern(sorted(rule.terms_b, key=lambda t: (-len(t), t))), + ) + for rule in rules + ] + + def describe(self) -> list[dict[str, Any]]: + return [ + { + "name": rule.name, + "category": rule.category, + "label_ja": rule.label_ja, + "window": rule.window, + "terms_a_file": rule.terms_a_file, + "terms_a_count": len(rule.terms_a), + "terms_b_file": rule.terms_b_file, + "terms_b_count": len(rule.terms_b), + "description_ja": rule.description_ja, + } + for rule in self.rules + ] + + def detect(self, text: Any, max_pairs: int = 10, excerpt_margin: int = 60) -> list[dict[str, Any]]: + normalized = normalize(text) + if not normalized: + return [] + results: list[dict[str, Any]] = [] + for rule, pattern_a, pattern_b in self._patterns: + a_hits = [(found.start(), found.group(0)) for found in pattern_a.finditer(normalized)] + if not a_hits: + continue + b_hits = [(found.start(), found.group(0)) for found in pattern_b.finditer(normalized)] + if not b_hits: + continue + b_positions = [position for position, _ in b_hits] + pairs: list[dict[str, Any]] = [] + for a_position, a_term in a_hits: + low = bisect.bisect_left(b_positions, a_position - rule.window) + high = bisect.bisect_right(b_positions, a_position + rule.window) + for b_position, b_term in b_hits[low:high]: + pairs.append( + { + "a": a_term, + "b": b_term, + "distance": abs(a_position - b_position), + "position": min(a_position, b_position), + } + ) + if not pairs: + continue + pairs.sort(key=lambda pair: (pair["position"], pair["distance"])) + first = pairs[0] + start = max(0, first["position"] - excerpt_margin) + end = min(len(normalized), first["position"] + rule.window + excerpt_margin) + results.append( + { + "rule": rule.name, + "category": rule.category, + "label_ja": rule.label_ja, + "pair_count": len(pairs), + "pairs": pairs[:max_pairs], + "excerpt": normalized[start:end].replace("\n", " "), + } + ) + return results diff --git a/code/3c1a8da-dirty-0c72d075/src/doc_features.py b/code/3c1a8da-dirty-0c72d075/src/doc_features.py new file mode 100644 index 0000000000000000000000000000000000000000..a6a69bdd87246db46df8897682ef32f764e55e44 --- /dev/null +++ b/code/3c1a8da-dirty-0c72d075/src/doc_features.py @@ -0,0 +1,179 @@ +"""文書特徴量(監査項目22・25〜29用)。 + +第2パス(``run_noise_pass.py``)で文書ごとに算出し、``features.parquet`` に書く。 + +* 言語判定(項目25): fastText lid.176(Facebook、CC BY-SA 3.0 のモデル)。文書先頭1,000字の判定と、 + 30字以上の行(最大50行)ごとの判定から非日本語行の比率を出す。 +* ジャンル分類(項目29): ``wordlists/genre/genre_rules.json`` の URL 規則と手がかり語で、 + 1,000字あたりの異なり手がかり語数をスコアとし、しきい値以上で最大のジャンルを付与する。 + 製造業・重工への適合スコアは独立に記録する。 +* 低品質フラグ(項目28): 同 JSON の定義(500字未満、記号・数字比率、行の反復、平均行長、販促定型、言語判定の低確信)。 +* 長さ・ハッシュ(項目22・27): 文字数(入力・最終)、本文 SHA-1、URL ホスト。 + +fastText の python ラッパーは numpy 2 で壊れるため、C++ バインディング(``model.f.predict``)を直接使う。 +""" + +from __future__ import annotations + +import hashlib +import json +import re +import statistics +from dataclasses import dataclass +from pathlib import Path +from typing import Any +from urllib.parse import urlparse + +from textmatch import compile_trie_pattern, normalize + + +FEATURE_COLUMNS = [ + "record_index", "status", "url", "host", "perplexity", + "chars_input", "chars_final", "lines_final", "avg_line_len", + "lang", "lang_prob", "non_ja_line_ratio", "mixed_language", + "genre", "genre_score", "manufacturing_score", + "score_diary_blog", "score_affiliate", "score_game", "score_entertainment", "score_ec_product", + "symbol_digit_ratio", "line_repetition", "is_low_quality", "low_quality_flags", + "content_sha1", +] + + +class LanguageDetector: + """fastText lid.176 による言語判定。""" + + def __init__(self, model_path: Path) -> None: + import fasttext + + self.model_path = str(model_path) + self._model = fasttext.load_model(self.model_path) + + def detect(self, text: str, max_chars: int = 1000) -> tuple[str, float]: + sample = text.replace("\n", " ")[:max_chars].strip() + if not sample: + return "unk", 0.0 + out = self._model.f.predict(sample, 1, 0.0, "strict") + if not out: + return "unk", 0.0 + prob, label = out[0] + return label.replace("__label__", ""), float(prob) + + def line_mix(self, text: str, max_lines: int = 50, min_chars: int = 30) -> tuple[float, int]: + """非日本語と判定された行の比率(対象行数も返す)。""" + + lines = [line.strip() for line in text.split("\n") if len(line.strip()) >= min_chars][:max_lines] + if not lines: + return 0.0, 0 + non_ja = sum(1 for line in lines if self.detect(line, 300)[0] != "ja") + return non_ja / len(lines), len(lines) + + +@dataclass(frozen=True) +class GenreRule: + name: str + label_ja: str + host_regex: re.Pattern[str] | None + host_weight: float + cues: re.Pattern[str] + cue_count: int + + +class GenreClassifier: + def __init__(self, rules_path: Path) -> None: + spec = json.loads(rules_path.read_text(encoding="utf-8")) + self.threshold = float(spec.get("score_threshold", 2.0)) + self.manufacturing_threshold = float(spec.get("manufacturing_threshold", 2.0)) + self.rules: list[GenreRule] = [] + for name, item in spec["genres"].items(): + hosts = item.get("host_patterns") or [] + cues = sorted({normalize(c) for c in item["cues"]}, key=lambda t: (-len(t), t)) + self.rules.append(GenreRule( + name=name, label_ja=item.get("label_ja", name), + host_regex=re.compile("|".join(hosts), re.IGNORECASE) if hosts else None, + host_weight=float(item.get("host_weight", 0)), + cues=compile_trie_pattern(cues), cue_count=len(cues), + )) + manufacturing = sorted({normalize(c) for c in spec["manufacturing"]["cues"]}, key=lambda t: (-len(t), t)) + self.manufacturing = compile_trie_pattern(manufacturing) + self.low_quality_flags = spec.get("low_quality", {}).get("flags", {}) + self.spec_summary = { + "rules_file": str(rules_path), "score_threshold": self.threshold, "manufacturing_threshold": self.manufacturing_threshold, + "genres": {r.name: {"label_ja": r.label_ja, "cues": r.cue_count, "host_weight": r.host_weight} for r in self.rules}, + "manufacturing_cues": len(manufacturing), "low_quality_flags": self.low_quality_flags, + } + + @staticmethod + def _distinct_per_1000(pattern: re.Pattern[str], text: str) -> float: + found = {m.group(0) for m in pattern.finditer(text)} + return len(found) / (max(len(text), 500) / 1000) + + def classify(self, url: str, normalized_text: str) -> tuple[str, float, float, dict[str, float]]: + host = (urlparse(url).hostname or "").lower() if url else "" + path = (urlparse(url).path or "").lower() if url else "" + scores: dict[str, float] = {} + for rule in self.rules: + score = self._distinct_per_1000(rule.cues, normalized_text) + if rule.host_regex is not None and rule.host_weight and (rule.host_regex.search(host) or rule.host_regex.search(path)): + score += rule.host_weight + scores[rule.name] = round(score, 3) + manufacturing = round(self._distinct_per_1000(self.manufacturing, normalized_text), 3) + best = max(scores, key=scores.get) if scores else "other" + genre = best if scores.get(best, 0) >= self.threshold else "other" + return genre, scores.get(best, 0.0), manufacturing, scores + + +SYMBOL_DIGIT_RE = re.compile(r"[0-90-9\W_]") + + +class DocFeaturizer: + def __init__(self, rules_path: Path, lid_model_path: Path | None = None) -> None: + self.genres = GenreClassifier(rules_path) + self.lid = LanguageDetector(lid_model_path) if lid_model_path else None + + def describe(self) -> dict[str, Any]: + return { + "language_detector": {"tool": "fastText lid.176", "model": self.lid.model_path if self.lid else None, + "doc_sample_chars": 1000, "line_min_chars": 30, "line_max": 50, "mixed_threshold": 0.3}, + "genre_rules": self.genres.spec_summary, + } + + def features(self, url: str, text: str, chars_input: int, status: str, record_index: int, perplexity: float | None = None, + lang: tuple[str, float] | None = None) -> dict[str, Any]: + text = text or "" + normalized = normalize(text) + lines = [line.strip() for line in text.split("\n") if line.strip()] + long_lines = [line for line in lines if len(line) >= 10] + avg_line = statistics.mean(len(line) for line in lines) if lines else 0.0 + repetition = 1 - len(set(long_lines)) / len(long_lines) if long_lines else 0.0 + stripped = text.replace("\n", "").replace(" ", "") + symbol_digit = len(SYMBOL_DIGIT_RE.findall(stripped)) / len(stripped) if stripped else 0.0 + if lang is None: + lang = self.lid.detect(text) if self.lid else ("unk", 0.0) + non_ja_ratio, _ = self.lid.line_mix(text) if self.lid else (0.0, 0) + mixed = lang[0] == "ja" and non_ja_ratio >= 0.3 + genre, genre_score, manufacturing, scores = self.genres.classify(url or "", normalized) + flags: list[str] = [] + if len(text) < 500: + flags.append("short_lt500") + if symbol_digit > 0.30: + flags.append("symbol_digit_ratio_gt30") + if repetition > 0.30 and len(long_lines) >= 10: + flags.append("line_repetition_gt30") + if len(lines) >= 10 and avg_line < 20: + flags.append("avg_line_len_lt20") + if genre in ("affiliate", "ec_product") and genre_score >= 4.0: + flags.append("template_commerce") + if lang[1] < 0.5: + flags.append("low_lid_confidence") + return { + "record_index": record_index, "status": status, "url": url, "host": (urlparse(url).hostname or "") if url else "", + "perplexity": perplexity, + "chars_input": chars_input, "chars_final": len(text), "lines_final": len(lines), "avg_line_len": round(avg_line, 1), + "lang": lang[0], "lang_prob": round(lang[1], 3), "non_ja_line_ratio": round(non_ja_ratio, 3), "mixed_language": mixed, + "genre": genre, "genre_score": round(genre_score, 3), "manufacturing_score": manufacturing, + "score_diary_blog": scores.get("diary_blog", 0.0), "score_affiliate": scores.get("affiliate", 0.0), + "score_game": scores.get("game", 0.0), "score_entertainment": scores.get("entertainment", 0.0), + "score_ec_product": scores.get("ec_product", 0.0), + "symbol_digit_ratio": round(symbol_digit, 3), "line_repetition": round(repetition, 3), + "is_low_quality": bool(flags), "low_quality_flags": "|".join(flags), + "content_sha1": hashlib.sha1(text.encode("utf-8")).hexdigest() if text else "", + } diff --git a/code/3c1a8da-dirty-0c72d075/src/domain_blocklist.py b/code/3c1a8da-dirty-0c72d075/src/domain_blocklist.py new file mode 100644 index 0000000000000000000000000000000000000000..383556a3bfad2f55c8a2e6f653fe27e459d4567d --- /dev/null +++ b/code/3c1a8da-dirty-0c72d075/src/domain_blocklist.py @@ -0,0 +1,351 @@ +"""URLのドメインをブロックリストと照合する。 + +UT1 blacklists(トゥールーズ・キャピトル大学、CC BY-SA)のカテゴリ別リストと、 +このリポジトリで管理するドメインリスト・ドメイン名規則を統合する。適用した +リストの出典・取得日時・SHA-256・件数はマニフェストとして summary.json に +記録する(監査項目10「適用したリストを記録」)。 + +取得:: + + python domain_blocklist.py fetch --dest ../data/blocklists/ut1 + +確認:: + + python domain_blocklist.py check https://example.com/path ... + +設定は ``blocklists/blocklist_config.json`` にあり、UT1カテゴリごとに +``delete``(削除)か ``flag``(記録のみ)を指定する。 +""" + +from __future__ import annotations + +import argparse +import hashlib +import io +import json +import re +import tarfile +import unicodedata +import urllib.error +import urllib.request +from dataclasses import asdict, dataclass +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Iterable +from urllib.parse import urlparse + + +UT1_DOWNLOAD_URL = "https://dsi.ut-capitole.fr/blacklists/download/{category}.tar.gz" +UT1_MIRROR_URL = "https://raw.githubusercontent.com/olbat/ut1-blacklists/master/blacklists/{category}/{member}" +UT1_LICENSE = "CC BY-SA 4.0 (Université Toulouse Capitole, Fabrice Prigent)" +CONFIG_FILE = "blocklist_config.json" +MANIFEST_FILE = "manifest.json" +USER_AGENT = "MHI_Dataset-domain-blocklist/1.0" + + +@dataclass(frozen=True) +class BlocklistSource: + """適用したリスト1件分のメタデータ。summary.json にそのまま記録する。""" + + name: str + kind: str # ut1 | local_domains | local_rules + action: str # delete | flag + entries: int + path: str + license: str = "" + source_url: str | None = None + sha256: str | None = None + fetched_at_utc: str | None = None + + +def normalize_host(url: Any) -> str | None: + """URLからホスト名を取り出す。小文字化し、ポートと末尾のドットを除く。""" + + if not url: + return None + text = unicodedata.normalize("NFKC", str(url)).strip().lower() + if "://" not in text: + text = "http://" + text + try: + host = urlparse(text).hostname + except ValueError: + return None + if not host: + return None + return host.strip(".") + + +def host_suffixes(host: str) -> list[str]: + """``a.b.example.com`` → ``[a.b.example.com, b.example.com, example.com]``(TLD単独は除く)。""" + + parts = host.split(".") + return [".".join(parts[index:]) for index in range(len(parts) - 1)] + + +def _sha256(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def _download(url: str, timeout: int) -> bytes: + request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT}) + with urllib.request.urlopen(request, timeout=timeout) as response: + return response.read() + + +def _count_entries(content: bytes) -> int: + return sum(1 for line in content.splitlines() if line.strip() and not line.startswith(b"#")) + + +def fetch_ut1(categories: Iterable[str], dest: Path, timeout: int = 300, prefer_mirror: bool = False) -> dict[str, Any]: + """UT1のカテゴリ別tarballを取得し、domains/urls を展開してマニフェストを書く。 + + 公式サイトが応答しない場合はGitHubミラー(olbat/ut1-blacklists)へ + フォールバックする。どちらから取得したかはマニフェストに残る。 + """ + + dest.mkdir(parents=True, exist_ok=True) + manifest: dict[str, Any] = { + "source": "UT1 blacklists", + "license": UT1_LICENSE, + "fetched_at_utc": datetime.now(timezone.utc).isoformat(), + "categories": {}, + } + for category in categories: + entry: dict[str, Any] = {} + members: dict[str, bytes] = {} + data: bytes | None = None + if not prefer_mirror: + official_url = UT1_DOWNLOAD_URL.format(category=category) + try: + data = _download(official_url, timeout) + entry["source_url"] = official_url + except (urllib.error.URLError, TimeoutError, OSError) as error: + entry["official_error"] = str(error) + if data is not None: + entry["sha256"] = _sha256(data) + entry["bytes"] = len(data) + with tarfile.open(fileobj=io.BytesIO(data), mode="r:gz") as archive: + for member in archive.getmembers(): + name = Path(member.name).name + if name in ("domains", "urls") and member.isfile(): + handle = archive.extractfile(member) + if handle is not None: + members[name] = handle.read() + else: + for name in ("domains", "urls"): + mirror_url = UT1_MIRROR_URL.format(category=category, member=name) + try: + members[name] = _download(mirror_url, timeout) + except urllib.error.HTTPError as error: + if error.code != 404: + raise + entry["source_url"] = UT1_MIRROR_URL.format(category=category, member="{domains,urls}") + entry["sha256"] = _sha256(b"".join(members[name] for name in sorted(members))) + entry["bytes"] = sum(len(value) for value in members.values()) + if "domains" not in members: + raise RuntimeError(f"UT1カテゴリ {category} の domains を取得できませんでした") + category_dir = dest / category + category_dir.mkdir(parents=True, exist_ok=True) + for name, content in members.items(): + (category_dir / name).write_bytes(content) + entry[f"{name}_entries"] = _count_entries(content) + manifest["categories"][category] = entry + (dest / MANIFEST_FILE).write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + return manifest + + +def _read_list_lines(path: Path) -> list[str]: + lines: list[str] = [] + for raw_line in path.read_text(encoding="utf-8", errors="replace").splitlines(): + line = raw_line.strip() + if line and not line.startswith("#"): + lines.append(line) + return lines + + +class DomainBlocklist: + """ドメイン一致(親ドメインを含む)、URL接頭辞一致、ドメイン名規則の照合。""" + + def __init__(self) -> None: + self.sources: list[BlocklistSource] = [] + self._domain_index: dict[str, list[str]] = {} + self._url_index: dict[str, list[tuple[str, str]]] = {} + self._rules: list[tuple[str, re.Pattern[str], str]] = [] + self._actions: dict[str, str] = {} + self._allowlist: set[str] = set() + self._allowlist_source: str | None = None + + def add_domains(self, source: BlocklistSource, domains: Iterable[str]) -> None: + self.sources.append(source) + self._actions[source.name] = source.action + for domain in domains: + self._domain_index.setdefault(domain.lower(), []).append(source.name) + + def add_urls(self, source_name: str, urls: Iterable[str]) -> None: + for raw in urls: + entry = raw.lower().strip("/") + host = entry.split("/", 1)[0] + self._url_index.setdefault(host, []).append((entry, source_name)) + + def add_rules(self, source: BlocklistSource, rules: Iterable[tuple[str, str]]) -> None: + self.sources.append(source) + self._actions[source.name] = source.action + for label, expression in rules: + self._rules.append((label, re.compile(expression), source.name)) + + def add_allowlist(self, source: BlocklistSource, domains: Iterable[str]) -> None: + """UT1由来のドメイン一致を適用しないドメイン(プラットフォーム等)。""" + + self.sources.append(source) + self._actions[source.name] = source.action + self._allowlist_source = source.name + self._allowlist.update(domain.lower() for domain in domains) + + @classmethod + def load(cls, blocklist_dir: Path, cache_dir: Path | None) -> "DomainBlocklist": + config = json.loads((blocklist_dir / CONFIG_FILE).read_text(encoding="utf-8")) + blocklist = cls() + categories: dict[str, str] = config.get("ut1", {}).get("categories", {}) + if categories: + if cache_dir is None or not (cache_dir / MANIFEST_FILE).exists(): + raise FileNotFoundError( + f"UT1ブロックリストが未取得です: {cache_dir}. 先に " + f"`python {Path(__file__).name} fetch --dest {cache_dir}` を実行してください。" + ) + manifest = json.loads((cache_dir / MANIFEST_FILE).read_text(encoding="utf-8")) + for category, action in categories.items(): + meta = manifest["categories"].get(category) + domains_path = cache_dir / category / "domains" + if meta is None or not domains_path.exists(): + raise FileNotFoundError(f"UT1カテゴリ {category} が取得されていません: {domains_path}") + domains = _read_list_lines(domains_path) + source = BlocklistSource( + name=f"ut1:{category}", + kind="ut1", + action=action, + entries=len(domains), + path=str(domains_path), + license=manifest.get("license", UT1_LICENSE), + source_url=meta.get("source_url"), + sha256=meta.get("sha256"), + fetched_at_utc=manifest.get("fetched_at_utc"), + ) + blocklist.add_domains(source, domains) + urls_path = cache_dir / category / "urls" + if urls_path.exists(): + blocklist.add_urls(source.name, _read_list_lines(urls_path)) + local = config.get("local", {}) + if local.get("allowlist"): + path = blocklist_dir / local["allowlist"] + domains = [line.split()[0].lower() for line in _read_list_lines(path)] + blocklist.add_allowlist( + BlocklistSource( + name="local:allowlist", + kind="local_allowlist", + action="allow", + entries=len(domains), + path=str(path), + license="repository", + sha256=_sha256(path.read_bytes()), + ), + domains, + ) + if local.get("domains"): + path = blocklist_dir / local["domains"] + domains = [line.split()[0].lower() for line in _read_list_lines(path)] + source = BlocklistSource( + name="local:domains", + kind="local_domains", + action=local.get("action", "delete"), + entries=len(domains), + path=str(path), + license="repository", + sha256=_sha256(path.read_bytes()), + ) + blocklist.add_domains(source, domains) + if local.get("rules"): + path = blocklist_dir / local["rules"] + rules: list[tuple[str, str]] = [] + for line in _read_list_lines(path): + label, _, expression = line.partition("\t") + if not expression: + raise ValueError(f"規則の形式が不正です(ラベル正規表現): {line}") + rules.append((label.strip(), expression.strip())) + source = BlocklistSource( + name="local:rules", + kind="local_rules", + action=local.get("action", "delete"), + entries=len(rules), + path=str(path), + license="repository", + sha256=_sha256(path.read_bytes()), + ) + blocklist.add_rules(source, rules) + return blocklist + + def match(self, url: Any) -> list[dict[str, Any]]: + host = normalize_host(url) + if not host: + return [] + results: list[dict[str, Any]] = [] + seen: set[tuple[str, str]] = set() + + def add(source_name: str, matched: str, kind: str) -> None: + key = (source_name, matched) + if key not in seen: + seen.add(key) + results.append({"source": source_name, "action": self._actions[source_name], "matched": matched, "kind": kind}) + + suffixes = host_suffixes(host) + allowed = next((suffix for suffix in suffixes if suffix in self._allowlist), None) + for suffix in suffixes: + for source_name in self._domain_index.get(suffix, ()): + if allowed is not None and source_name.startswith("ut1:"): + add(self._allowlist_source or "local:allowlist", f"{allowed} (suppressed {source_name})", "allowlist") + continue + add(source_name, suffix, "domain") + if self._url_index and allowed is None: + path = urlparse(unicodedata.normalize("NFKC", str(url)).strip().lower()).path or "/" + full = host + path.rstrip("/") + for suffix in suffixes: + for entry, source_name in self._url_index.get(suffix, ()): + if full == entry or full.startswith(entry + "/"): + add(source_name, entry, "url") + for label, pattern, source_name in self._rules: + if pattern.search(host): + add(source_name, f"{label}:{pattern.pattern}", "rule") + return results + + def manifest(self) -> list[dict[str, Any]]: + return [asdict(source) for source in self.sources] + + +def main(argv: list[str] | None = None) -> None: + here = Path(__file__).resolve().parent + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + sub = parser.add_subparsers(dest="command", required=True) + fetch = sub.add_parser("fetch", help="UT1のカテゴリ別リストを取得する") + fetch.add_argument("--dest", type=Path, required=True) + fetch.add_argument("--config", type=Path, default=here / "blocklists" / CONFIG_FILE) + fetch.add_argument("--category", action="append", default=None, help="省略時は設定ファイルの全カテゴリ") + fetch.add_argument("--mirror", action="store_true", help="公式サイトではなくGitHubミラーから取得する") + fetch.add_argument("--timeout", type=int, default=300) + check = sub.add_parser("check", help="URLを照合して結果を表示する") + check.add_argument("urls", nargs="+") + check.add_argument("--blocklist-dir", type=Path, default=here / "blocklists") + check.add_argument("--cache-dir", type=Path, default=here.parents[0] / "data" / "blocklists" / "ut1") + args = parser.parse_args(argv) + if args.command == "fetch": + config = json.loads(args.config.read_text(encoding="utf-8")) + categories = args.category or list(config.get("ut1", {}).get("categories", {})) + manifest = fetch_ut1(categories, args.dest, timeout=args.timeout, prefer_mirror=args.mirror) + summary = {category: {key: value for key, value in meta.items() if key != "sha256"} for category, meta in manifest["categories"].items()} + print(json.dumps(summary, ensure_ascii=False, indent=2)) + else: + blocklist = DomainBlocklist.load(args.blocklist_dir, args.cache_dir) + for url in args.urls: + print(url, json.dumps(blocklist.match(url), ensure_ascii=False)) + + +if __name__ == "__main__": + main() diff --git a/code/3c1a8da-dirty-0c72d075/src/filter_noise.py b/code/3c1a8da-dirty-0c72d075/src/filter_noise.py new file mode 100644 index 0000000000000000000000000000000000000000..4c933a9b2e37a1abc285156163d74e364e72eaaa --- /dev/null +++ b/code/3c1a8da-dirty-0c72d075/src/filter_noise.py @@ -0,0 +1,542 @@ +"""不要データ・ノイズの検出と除去(監査項目14〜21)。 + +文書単位の削除、行単位の削除、文字列の置換の3種類を行い、パターンごとの +検出文書数・出現回数・削除行数・置換回数を summary.json に記録する。 +削除理由は優先順位で1つだけ割り当て、理由別件数の合計が総削除件数と一致する。 + +| 項目 | 内容 | 処理 | +|---|---|---| +| 14 | LLM 由来の回答拒否文・アシスタント口調(``noise/llm_phrases.txt``) | 文書削除 | +| 15 | 特殊トークン・チャットテンプレート断片(``noise/special_tokens.txt``)、制御文字・ゼロ幅文字 | 文書削除/文字除去 | +| 16 | base64 画像、HTML タグ、Markdown 画像リンク、URL のみの行 | 行削除・タグ除去 | +| 17 | 文字化け、絵文字の連続、同一記号の繰り返し | 行削除・圧縮置換・多量なら文書削除 | +| 18 | boilerplate(``noise/boilerplate_lines.txt``、短い行の連続) | 行削除 | +| 19 | 崩れた表・記号だけの行、数値の羅列だけの文書 | 行削除・文書削除 | +| 20 | 過剰な改行(短い行の連続、助詞・読点で終わる行) | 結合/削除/保持(``newline_policy``) | +| 21 | 極端に短い/長い文書 | 文書削除(文字数。トークナイザ指定時はトークン数も) | + +配布元(ABEJA)が trafilatura 抽出と LightGBM 行フィルタ、100字以下除去を済ませているため +残存量は少ないが、監査要件(パターン一覧と件数の記録)のため自前で検出・記録する。 +不可視文字を含む文字クラスは chr() で組み立て、ソースに直接埋め込まない。 +""" + +from __future__ import annotations + +import json +import re +import statistics +from collections import Counter +from dataclasses import dataclass, field +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pyarrow.parquet as pq + + +NOISE_VERSION = "filter_noise_v1" +DEFAULT_MIN_CHARS = 200 +DEFAULT_MAX_CHARS = 100_000 +# 削除理由の優先順位。複数に該当しても最初の1つだけを理由にする。 +DELETE_REASON_ORDER = ("llm_phrase", "special_token", "non_japanese", "mojibake_heavy", "numeric_only", "excessive_newlines", "too_short", "too_long") +REASON_LABELS_JA = { + "llm_phrase": "14 LLM 由来の回答拒否文・アシスタント口調", + "special_token": "15 特殊トークン・チャットテンプレート断片", + "non_japanese": "25 言語判定が日本語以外(fastText lid.176、確信度0.5以上)", + "mojibake_heavy": "17 文字化けが多い", + "numeric_only": "19 数値の羅列のみ", + "excessive_newlines": "20 過剰な改行(削除方針時)", + "too_short": "21 文字数が下限未満", + "too_long": "21 文字数が上限超過", +} + + +def _chars(*codes: int) -> str: + return "".join(chr(code) for code in codes) + + +def _range(low: int, high: int) -> str: + return chr(low) + "-" + chr(high) + + +@dataclass(frozen=True) +class NoisePattern: + id: str + item: int + action: str # delete_doc | remove_line | replace | remove_chars + regex: re.Pattern[str] + description_ja: str = "" + source: str = "builtin" + + def describe(self) -> dict[str, Any]: + return { + "id": self.id, "item": self.item, "action": self.action, + "regex": self.regex.pattern.encode("unicode_escape").decode("ascii"), + "description_ja": self.description_ja, "source": self.source, + } + + +def _read_patterns(path: Path, item: int, action: str, flags: int, id_prefix: str) -> list[NoisePattern]: + patterns: list[NoisePattern] = [] + if not path.exists(): + return patterns + for number, raw in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1): + line = raw.strip() + if not line or line.startswith("#"): + continue + patterns.append(NoisePattern(f"{id_prefix}_{number:02d}", item, action, re.compile(line, flags), source=path.name)) + return patterns + + +# --- 組み込みパターン(行・文字列レベル) -------------------------------------- +CONTROL_CHARS_RE = re.compile("[" + _range(0x00, 0x08) + _chars(0x0B, 0x0C) + _range(0x0E, 0x1F) + chr(0x7F) + "]") +ZERO_WIDTH_RE = re.compile("[" + _range(0x200B, 0x200D) + _chars(0x2060, 0xFEFF) + "]") +BASE64_IMAGE_RE = re.compile(r"data:image/[a-z0-9.+-]+;base64,[A-Za-z0-9+/=\s]{20,}", re.IGNORECASE) +MD_IMAGE_RE = re.compile(r"!\[[^\]\n]*\]\([^)\n]+\)") +URL_ONLY_LINE_RE = re.compile(r"^\s*(?:https?://\S+\s*)+$") +# PII 置換のプレースホルダー( 等)は HTML タグとして扱わない +PII_PLACEHOLDER_NAMES = "EMAIL|PHONE|ADDRESS|PERSON_NAME|PERSON_AFFILIATION|MY_NUMBER|CREDIT_CARD|BANK_ACCOUNT|PII" +HTML_TAG_RE = re.compile( + r"<(?!(?:" + PII_PLACEHOLDER_NAMES + r")>)/?[A-Za-z][A-Za-z0-9-]*(?:\s+[^<>]{0,200})?/?>||]*>", + re.DOTALL, +) +# 文字化け: 置換文字、UTF-8 を Latin-1 で読んだ痕跡(ã, â€, à + 拡張ラテン)、GBK/Shift_JIS の典型的な化け文字 +MOJIBAKE_RE = re.compile( + chr(0xFFFD) + "|(?:" + _chars(0xE3) + "|" + _chars(0xE2, 0x20AC) + "|" + _chars(0xC3) + ")[" + _range(0x80, 0xBF) + "]" + + "|锟斤拷|縺|繧|繝|髴|蜿|荳" +) +EMOJI_RUN_RE = re.compile( + "((?:[" + _range(0x1F000, 0x1FAFF) + _range(0x2600, 0x27BF) + _chars(0x2B50, 0x2B55, 0x203C, 0x2049, 0x3030, 0x303D, 0x3297, 0x3299) + "]" + + "[" + chr(0xFE0F) + _range(0x1F3FB, 0x1F3FF) + "]?){3,})" +) +SYMBOL_REPEAT_RE = re.compile( + r"([!!??・。、,,..==\-ー―─━■□●○★☆♪※**##~〜~__||//\\<><>◆◇▼▲▽△←→↑↓♥❤♡…‥])\1{9,}" +) +TABLE_RULE_LINE_RE = re.compile(r"^\s*\|?(?:\s*:?-{2,}:?\s*\|)+\s*:?-*:?\s*\|?\s*$|^\s*[||]{2,}\s*$") +SYMBOL_ONLY_LINE_RE = re.compile(r"^[\s\W_]{4,}$") +PARTICLE_END_RE = re.compile(r"[はがをにのでとへもや、,]$") +# 結合しない構造行: 見出し、箇条書き、番号付き、罫線、「項目: 値」「項目|値」の形 +STRUCTURAL_LINE_RE = re.compile(r"^(?:#{1,6}\s|[-*・●○■□▪▶►◆◇]\s?|\d{1,3}[.).)]\s?|[─━―\-==_]{3,}|[^\s::||]{1,20}\s*[::||]\s*\S)") +SENTENCE_END_RE = re.compile(r"[。!?!?」』))\]】…]$") + + +@dataclass +class DocResult: + text: str | None + deleted_reason: str | None = None + detections: Counter = field(default_factory=Counter) # pattern_id -> occurrences + lines_removed: Counter = field(default_factory=Counter) # pattern_id -> lines + replacements: Counter = field(default_factory=Counter) # pattern_id -> replacements + chars_before: int = 0 + chars_after: int = 0 + newline_joined: bool = False + tokens_after: int | None = None + lang: str | None = None + lang_prob: float | None = None + + +class NoiseFilter: + def __init__( + self, + patterns_dir: Path, + min_chars: int = DEFAULT_MIN_CHARS, + max_chars: int = DEFAULT_MAX_CHARS, + newline_policy: str = "join", + tokenizer: str | None = None, + min_tokens: int | None = None, + max_tokens: int | None = None, + nav_run_lines: int = 15, + nav_line_chars: int = 12, + mojibake_delete_threshold: int = 3, + html_strip_threshold: int = 10, + language_detector: Any | None = None, + drop_non_japanese: bool = True, + ) -> None: + if newline_policy not in ("join", "delete", "keep"): + raise ValueError("newline_policy は join / delete / keep") + # 項目25: 言語判定(detect(text) -> (lang, prob) を持つオブジェクト)。日本語以外(確信度0.5以上)は削除する。 + self.language_detector = language_detector + self.drop_non_japanese = drop_non_japanese + self.min_chars = min_chars + self.max_chars = max_chars + self.newline_policy = newline_policy + self.min_tokens = min_tokens + self.max_tokens = max_tokens + self.nav_run_lines = nav_run_lines + self.nav_line_chars = nav_line_chars + self.mojibake_delete_threshold = mojibake_delete_threshold + self.html_strip_threshold = html_strip_threshold + self.llm_patterns = _read_patterns(patterns_dir / "llm_phrases.txt", 14, "delete_doc", re.IGNORECASE, "llm") + self.token_patterns = _read_patterns(patterns_dir / "special_tokens.txt", 15, "delete_doc", re.MULTILINE, "tok") + self.boilerplate_patterns = _read_patterns(patterns_dir / "boilerplate_lines.txt", 18, "remove_line", re.IGNORECASE, "bp") + never = re.compile(r"(?!x)x") + self.builtin: dict[str, NoisePattern] = { + "control_chars": NoisePattern("control_chars", 15, "remove_chars", CONTROL_CHARS_RE, "制御文字の除去"), + "zero_width": NoisePattern("zero_width", 15, "remove_chars", ZERO_WIDTH_RE, "ゼロ幅文字の除去"), + "base64_image": NoisePattern("base64_image", 16, "replace", BASE64_IMAGE_RE, "base64 埋め込み画像の除去"), + "md_image": NoisePattern("md_image", 16, "replace", MD_IMAGE_RE, "Markdown 画像リンクの除去"), + "url_only_line": NoisePattern("url_only_line", 16, "remove_line", URL_ONLY_LINE_RE, "URL のみの行の削除"), + "html_tags": NoisePattern("html_tags", 16, "replace", HTML_TAG_RE, f"HTML タグ(文書内に{html_strip_threshold}個以上ある場合に除去)"), + "mojibake": NoisePattern("mojibake", 17, "remove_line", MOJIBAKE_RE, f"文字化け(行削除。{mojibake_delete_threshold}箇所以上なら文書削除)"), + "emoji_run": NoisePattern("emoji_run", 17, "replace", EMOJI_RUN_RE, "絵文字3個以上の連続を1個に圧縮"), + "symbol_repeat": NoisePattern("symbol_repeat", 17, "replace", SYMBOL_REPEAT_RE, "同一記号10個以上の連続を3個に圧縮"), + "nav_run": NoisePattern("nav_run", 18, "remove_line", never, f"{nav_line_chars}字以下の行が{nav_run_lines}行以上連続する塊(ナビ・目次)の削除"), + "table_rule_line": NoisePattern("table_rule_line", 19, "remove_line", TABLE_RULE_LINE_RE, "表の罫線だけの行の削除"), + "symbol_only_line": NoisePattern("symbol_only_line", 19, "remove_line", SYMBOL_ONLY_LINE_RE, "記号だけの行の削除"), + "numeric_only": NoisePattern("numeric_only", 19, "delete_doc", never, "英数字の6割超が数字の文書を削除"), + "excessive_newlines": NoisePattern("excessive_newlines", 20, "replace", never, f"過剰な改行(平均行長18字未満かつ10行以上、または助詞・読点で終わる行が3割超)。方針: {newline_policy}"), + "non_japanese": NoisePattern("non_japanese", 25, "delete_doc", never, "言語判定が日本語以外(fastText lid.176、確信度0.5以上)の文書を削除"), + } + self._tokenizer = None + self.tokenizer_name = tokenizer + if tokenizer: + from transformers import AutoTokenizer + + self._tokenizer = AutoTokenizer.from_pretrained(tokenizer) + + def pattern_list(self) -> list[dict[str, Any]]: + items = [p.describe() for p in self.llm_patterns + self.token_patterns + self.boilerplate_patterns] + items += [p.describe() for p in self.builtin.values()] + return items + + def thresholds(self) -> dict[str, Any]: + return { + "min_chars": self.min_chars, "max_chars": self.max_chars, + "tokenizer": self.tokenizer_name, "min_tokens": self.min_tokens, "max_tokens": self.max_tokens, + "newline_policy": self.newline_policy, "nav_run_lines": self.nav_run_lines, "nav_line_chars": self.nav_line_chars, + "mojibake_delete_threshold": self.mojibake_delete_threshold, "html_strip_threshold": self.html_strip_threshold, + "language_detector": getattr(self.language_detector, "model_path", None), "drop_non_japanese": self.drop_non_japanese and self.language_detector is not None, + } + + def process(self, text: Any) -> DocResult: + result = DocResult(text=None) + original = "" if text is None else str(text) + result.chars_before = len(original) + work = original + + # 15: 制御文字・ゼロ幅文字 + for pid in ("control_chars", "zero_width"): + work, n = self.builtin[pid].regex.subn("", work) + if n: + result.detections[pid] += n + result.replacements[pid] += n + + # 14/15: 文書削除パターン(検出は全て数え、理由は優先順位で決める) + reasons: list[str] = [] + for pattern in self.llm_patterns: + n = len(pattern.regex.findall(work)) + if n: + result.detections[pattern.id] += n + reasons.append("llm_phrase") + for pattern in self.token_patterns: + n = len(pattern.regex.findall(work)) + if n: + result.detections[pattern.id] += n + reasons.append("special_token") + + # 17: 文字化け + mojibake_hits = len(MOJIBAKE_RE.findall(work)) + if mojibake_hits: + result.detections["mojibake"] += mojibake_hits + if mojibake_hits >= self.mojibake_delete_threshold: + reasons.append("mojibake_heavy") + + # 16: base64 画像・Markdown 画像・HTML タグ + for pid in ("base64_image", "md_image"): + work, n = self.builtin[pid].regex.subn(" ", work) + if n: + result.detections[pid] += n + result.replacements[pid] += n + tag_count = len(HTML_TAG_RE.findall(work)) + if tag_count: + result.detections["html_tags"] += tag_count + if tag_count >= self.html_strip_threshold: + work, n = HTML_TAG_RE.subn(" ", work) + result.replacements["html_tags"] += n + + # 17: 絵文字・記号の連続を圧縮 + work, n = EMOJI_RUN_RE.subn(lambda m: m.group(1)[:1], work) + if n: + result.detections["emoji_run"] += n + result.replacements["emoji_run"] += n + work, n = SYMBOL_REPEAT_RE.subn(lambda m: m.group(1) * 3, work) + if n: + result.detections["symbol_repeat"] += n + result.replacements["symbol_repeat"] += n + + # 行単位の削除(16/17/18/19) + kept: list[str] = [] + for line in work.split("\n"): + stripped = line.strip() + if not stripped: + kept.append(line) + continue + removed_by: str | None = None + if URL_ONLY_LINE_RE.match(line): + removed_by = "url_only_line" + elif mojibake_hits and MOJIBAKE_RE.search(line): + removed_by = "mojibake" + elif TABLE_RULE_LINE_RE.match(line): + removed_by = "table_rule_line" + elif SYMBOL_ONLY_LINE_RE.match(line): + removed_by = "symbol_only_line" + else: + for pattern in self.boilerplate_patterns: + if pattern.regex.search(line): + removed_by = pattern.id + break + if removed_by: + result.detections[removed_by] += 1 + result.lines_removed[removed_by] += 1 + else: + kept.append(line) + kept = self._remove_nav_runs(kept, result) + work = re.sub(r"\n{3,}", "\n\n", "\n".join(kept)).strip() + + # 19: 数値の羅列のみ + alnum = sum(c.isalnum() for c in work) + digits = sum(c.isdigit() for c in work) + if alnum >= 50 and digits / alnum > 0.6: + result.detections["numeric_only"] += 1 + reasons.append("numeric_only") + + # 20: 過剰な改行 + if self._has_excessive_newlines(work): + result.detections["excessive_newlines"] += 1 + if self.newline_policy == "join": + work = self._join_lines(work) + result.replacements["excessive_newlines"] += 1 + result.newline_joined = True + elif self.newline_policy == "delete": + reasons.append("excessive_newlines") + + # 25: 言語判定(整形後の本文で判定) + if self.language_detector is not None: + lang, prob = self.language_detector.detect(work) + result.lang, result.lang_prob = lang, prob + if self.drop_non_japanese and lang != "ja" and prob >= 0.5: + result.detections["non_japanese"] += 1 + reasons.append("non_japanese") + + # 21: 長さ + result.chars_after = len(work) + if result.chars_after < self.min_chars: + reasons.append("too_short") + elif result.chars_after > self.max_chars: + reasons.append("too_long") + if self._tokenizer is not None and "too_short" not in reasons and "too_long" not in reasons: + tokens = len(self._tokenizer.encode(work, add_special_tokens=False)) + result.tokens_after = tokens + if self.min_tokens is not None and tokens < self.min_tokens: + reasons.append("too_short") + elif self.max_tokens is not None and tokens > self.max_tokens: + reasons.append("too_long") + + for reason in DELETE_REASON_ORDER: + if reason in reasons: + result.deleted_reason = reason + return result + result.text = work + return result + + def _remove_nav_runs(self, lines: list[str], result: DocResult) -> list[str]: + kept: list[str] = [] + run: list[str] = [] + + def flush() -> None: + # 助詞・読点・句点で終わる行が2割以上ある塊は文の断片(項目20の対象)なので、ナビとして消さない + fragment_like = sum(1 for line in run if PARTICLE_END_RE.search(line.strip()) or line.strip().endswith(("。", "、", "!", "?"))) + if len(run) >= self.nav_run_lines and fragment_like < 0.2 * len(run): + result.detections["nav_run"] += 1 + result.lines_removed["nav_run"] += len(run) + else: + kept.extend(run) + run.clear() + + for line in lines: + stripped = line.strip() + if stripped and len(stripped) <= self.nav_line_chars: + run.append(line) + else: + flush() + kept.append(line) + flush() + return kept + + def _has_excessive_newlines(self, text: str) -> bool: + lines = [line.strip() for line in text.split("\n") if line.strip()] + if len(lines) < 10: + return False + average = statistics.mean(len(line) for line in lines) + particle = sum(1 for line in lines if PARTICLE_END_RE.search(line)) / len(lines) + return average < 18 or particle > 0.3 + + @staticmethod + def _join_lines(text: str) -> str: + """文末記号で終わらない短い行を次の行と結合する。段落(空行)は保つ。 + + 見出し(#)、箇条書き(-・*、番号)、罫線、コロン付きの項目行は結合の対象にも + 結合先にもしない。仕様書の項目リストや見出しを1行に潰さないため。 + """ + + output: list[str] = [] + buffer = "" + for line in text.split("\n"): + stripped = line.strip() + if not stripped: + if buffer: + output.append(buffer) + buffer = "" + output.append("") + continue + structural = STRUCTURAL_LINE_RE.match(stripped) is not None + can_extend = ( + buffer + and not structural + and not STRUCTURAL_LINE_RE.match(buffer) + and not SENTENCE_END_RE.search(buffer) + and len(buffer) <= 40 + ) + if can_extend: + buffer += stripped + else: + if buffer: + output.append(buffer) + buffer = stripped + if buffer: + output.append(buffer) + return re.sub(r"\n{3,}", "\n\n", "\n".join(output)).strip() + + +def json_safe(value: Any) -> Any: + if value is None or isinstance(value, (str, int, bool)): + return value + if isinstance(value, float): + return value if value == value and abs(value) != float("inf") else None + if isinstance(value, (list, tuple)): + return [json_safe(item) for item in value] + if isinstance(value, dict): + return {str(key): json_safe(item) for key, item in value.items()} + return str(value) + + +def run_noise_filter( + input_path: Path, + output_dir: Path, + noise_filter: NoiseFilter, + batch_size: int = 2048, + output_name: str | None = None, + examples_per_pattern: int = 3, + on_record: Any | None = None, +) -> dict[str, Any]: + """parquet を読み、クリーン済み parquet・removed.jsonl・summary.json を書く。 + + ``on_record(row, result, record_index)`` を渡すと、文書ごとに呼ばれる(特徴量の算出用)。 + """ + + output_dir.mkdir(parents=True, exist_ok=True) + parquet = pq.ParquetFile(input_path) + schema = parquet.schema_arrow + cleaned_path = output_dir / (output_name or "noise_cleaned.parquet") + removed_path = output_dir / "removed.jsonl" + writer = pq.ParquetWriter(cleaned_path, schema, compression="zstd") + removed_handle = removed_path.open("w", encoding="utf-8", newline="\n") + scanned_at = datetime.now(timezone.utc).isoformat() + detections_docs: Counter = Counter() + detections_occ: Counter = Counter() + lines_removed: Counter = Counter() + replacements: Counter = Counter() + deleted_by_reason: Counter = Counter() + examples: dict[str, list[dict[str, Any]]] = {} + totals: Counter = Counter() + record_index = 0 + try: + for batch in parquet.iter_batches(batch_size=batch_size): + rows = batch.to_pylist() + kept_rows: list[dict[str, Any]] = [] + for row in rows: + result = noise_filter.process(row.get("content")) + if on_record is not None: + on_record(row, result, record_index) + totals["records_scanned"] += 1 + totals["chars_before"] += result.chars_before + for pid, n in result.detections.items(): + detections_docs[pid] += 1 + detections_occ[pid] += n + if len(examples.setdefault(pid, [])) < examples_per_pattern: + examples[pid].append({"record_index": record_index, "url": json_safe(row.get("url")), "occurrences": n}) + for pid, n in result.lines_removed.items(): + lines_removed[pid] += n + for pid, n in result.replacements.items(): + replacements[pid] += n + if result.newline_joined: + totals["records_newline_joined"] += 1 + if result.deleted_reason: + totals["records_deleted"] += 1 + deleted_by_reason[result.deleted_reason] += 1 + removed_handle.write(json.dumps({ + "record_index": record_index, + "url": json_safe(row.get("url")), + "_noise_deleted_reason": result.deleted_reason, + "_noise_deleted_reason_ja": REASON_LABELS_JA[result.deleted_reason], + "_noise_detections": dict(result.detections), + "_noise_chars_before": result.chars_before, + "_noise_chars_after": result.chars_after, + "content_head": json_safe((row.get("content") or "")[:300]), + }, ensure_ascii=False, separators=(",", ":")) + "\n") + else: + totals["records_retained"] += 1 + totals["chars_after"] += result.chars_after + if result.tokens_after is not None: + totals["tokens_after"] += result.tokens_after + if result.text != (row.get("content") or ""): + totals["records_modified"] += 1 + output_row = dict(row) + if "content" in output_row: + output_row["content"] = result.text + kept_rows.append(output_row) + record_index += 1 + if kept_rows: + writer.write_table(pa.Table.from_pylist(kept_rows, schema=schema)) + finally: + writer.close() + removed_handle.close() + pattern_rows = [] + for spec in noise_filter.pattern_list(): + pid = spec["id"] + pattern_rows.append({ + **spec, "records_detected": detections_docs[pid], "occurrences": detections_occ[pid], + "lines_removed": lines_removed[pid], "replacements": replacements[pid], "examples": examples.get(pid, []), + }) + by_item: dict[int, dict[str, int]] = {} + for row in pattern_rows: + entry = by_item.setdefault(row["item"], {"records_detected_sum": 0, "occurrences": 0, "lines_removed": 0, "replacements": 0}) + entry["records_detected_sum"] += row["records_detected"] + entry["occurrences"] += row["occurrences"] + entry["lines_removed"] += row["lines_removed"] + entry["replacements"] += row["replacements"] + summary = { + "filter_mode": NOISE_VERSION, + "source_file": str(input_path), + "scanned_at_utc": scanned_at, + "thresholds": noise_filter.thresholds(), + "delete_reason_order": list(DELETE_REASON_ORDER), + "records_scanned": totals["records_scanned"], + "records_deleted": totals["records_deleted"], + "records_retained": totals["records_retained"], + "records_modified": totals["records_modified"], + "records_newline_joined": totals["records_newline_joined"], + "records_deleted_by_reason": {reason: deleted_by_reason[reason] for reason in DELETE_REASON_ORDER}, + "records_deleted_by_reason_ja": {REASON_LABELS_JA[reason]: deleted_by_reason[reason] for reason in DELETE_REASON_ORDER}, + "chars_before": totals["chars_before"], + "chars_after_retained": totals["chars_after"], + "tokens_after_retained": totals["tokens_after"] if noise_filter.tokenizer_name else None, + "by_item": {str(key): value for key, value in sorted(by_item.items())}, + "patterns": pattern_rows, + "cleaned_parquet": str(cleaned_path), + "removed_jsonl": str(removed_path), + "note_ja": "削除理由は優先順位(14 LLM → 15 特殊トークン → 25 非日本語 → 17 文字化け → 19 数値のみ → 20 改行 → 21 長さ)で1つだけ割り当てる。行削除・置換は保持文書にも適用される。", + } + (output_dir / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + return summary diff --git a/code/3c1a8da-dirty-0c72d075/src/filter_pii.py b/code/3c1a8da-dirty-0c72d075/src/filter_pii.py new file mode 100644 index 0000000000000000000000000000000000000000..03d27f2be9ada9ae7911e653a415bd5de66ab38e --- /dev/null +++ b/code/3c1a8da-dirty-0c72d075/src/filter_pii.py @@ -0,0 +1,180 @@ +"""Parquet中の指定PIIをプレースホルダーへ置換する。 + +実行入口と引数処理は ``main_pii.py`` に置き、このモジュールには置換処理と +監査集計の定義だけを置く。 +""" + +from __future__ import annotations + +import json +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pyarrow.parquet as pq + +from pii_detector import PII_LABELS_JA, PLACEHOLDERS, PIIDetector, matches_to_dict + + +MODE_NAME = "pii_replace" +OUTPUT_DIR_NAME = "pii_replaced" + + +def policy_record(approver: str | None, approved_on: str | None, note: str | None = None) -> dict[str, Any]: + """処理方針の記録(監査項目12)。方針は全データセット共通で「置換」。 + + 削除も保持もしないため保持対象の承認は不要だが、方針そのものの承認者と + 日付を残す。未記入なら ``status`` は ``unapproved`` になる。 + """ + + approved = bool(approver and approved_on) + return { + "action": "mask_with_placeholders", + "name_scope_ja": "個人名+所属(同じ文の前後25文字に組織名か役職語)、署名(執筆者・著者等の役割ラベル)、ラベル付き氏名を置換。敬称のみ・文脈なしの姓名は既定で保持し件数を記録。", + "action_ja": "検出したPIIを種別ごとのプレースホルダーへ置換する。文書の削除も、PIIのままの保持もしない。", + "scope_ja": "全データセット共通(url列と content列)", + "placeholders": dict(PLACEHOLDERS), + "retained_types": [], + "approved_by": approver, + "approved_on": approved_on, + "note": note, + "status": "approved" if approved else "unapproved", + } + + +def json_safe(value: Any) -> Any: + if value is None or isinstance(value, (str, int, bool)): + return value + if isinstance(value, float): + return value if value == value and abs(value) != float("inf") else None + if isinstance(value, (list, tuple)): + return [json_safe(item) for item in value] + if isinstance(value, dict): + return {str(key): json_safe(item) for key, item in value.items()} + return str(value) + + +def run_filter( + input_path: Path, + output_root: Path, + batch_size: int = 2048, + start_row: int = 0, + max_rows: int | None = None, + policy_approver: str | None = None, + policy_approved_on: str | None = None, + policy_note: str | None = None, + mask_honorific_names: bool = False, + mask_bare_names: bool = False, + affiliation_titles: bool = True, +) -> dict[str, Any]: + """入力を全件保持し、URL・本文の検出値だけを置換して出力する。""" + + output_dir = output_root / OUTPUT_DIR_NAME + output_dir.mkdir(parents=True, exist_ok=True) + parquet = pq.ParquetFile(input_path) + schema = parquet.schema_arrow + replaced_path = output_dir / "replaced.parquet" + audit_path = output_dir / "audit.jsonl" + writer = pq.ParquetWriter(replaced_path, schema, compression="zstd") + audit_handle = audit_path.open("w", encoding="utf-8", newline="\n") + detector = PIIDetector(include_url=True, mask_honorific_names=mask_honorific_names, mask_bare_names=mask_bare_names, affiliation_titles=affiliation_titles) + scanned_at = datetime.now(timezone.utc).isoformat() + by_type = { + pii_type: {"label_ja": label, "records_with_match": 0, "replacement_count": 0} + for pii_type, label in PII_LABELS_JA.items() + } + stats: dict[str, Any] = { + "filter_mode": MODE_NAME, + "criterion_ja": "電話番号、メールアドレス、番地レベル住所、個人名(単体・所属付き)、マイナンバー、カード番号、口座番号をプレースホルダーへ置換し、文書は削除しない", + "source_file": str(input_path), + "total_records_scanned": 0, + "records_with_replacement": 0, + "records_changed": 0, + "records_unchanged": 0, + "total_replacements": 0, + "by_type": by_type, + "pii_policy": policy_record(policy_approver, policy_approved_on, policy_note), + "detector_version": "pii_detector_v3_sudachi", + "row_range": {}, + "input_schema": list(schema.names), + "matching_scope": "url + content", + "matching_normalization": "NFKC", + "method_ja": "正規表現、文脈ラベル、SudachiPy による人名(姓・名)検出と所属・役職・敬称文脈、マイナンバーチェックデジット、クレジットカードLuhn検証を併用。", + "note_ja": "外部NERモデルを使用しない決定的ベースライン。監査JSONLにはPII値を保存せず、マスキング済み一致値と置換後フィールドを記録する。残存件数は pii_residual_check.py(GLiNER-ja)で独立に確認する。", + } + stop_row = start_row + max_rows if max_rows is not None else None + row_offset = 0 + try: + for source_batch in parquet.iter_batches(batch_size=batch_size): + source_batch_start = row_offset + row_offset += source_batch.num_rows + if row_offset <= start_row: + continue + if stop_row is not None and source_batch_start >= stop_row: + break + local_start = max(0, start_row - source_batch_start) + local_end = source_batch.num_rows if stop_row is None else min(source_batch.num_rows, stop_row - source_batch_start) + batch = source_batch.slice(local_start, local_end - local_start) + rows = batch.to_pylist() + replaced_rows: list[dict[str, Any]] = [] + for row in rows: + url = row.get("url") or "" + content = row.get("content") or "" + replaced_url, replaced_content, matches = detector.replace_record(url, content) + output_row = dict(row) + if "url" in output_row and row.get("url") is not None: + output_row["url"] = replaced_url + if "content" in output_row and row.get("content") is not None: + output_row["content"] = replaced_content + replaced_rows.append(output_row) + stats["total_records_scanned"] += 1 + stats["total_replacements"] += len(matches) + matched_types: set[str] = set() + for match in matches: + by_type[match.pii_type]["replacement_count"] += 1 + matched_types.add(match.pii_type) + for pii_type in matched_types: + by_type[pii_type]["records_with_match"] += 1 + if matches: + stats["records_with_replacement"] += 1 + stats["records_changed"] += 1 + audit_record = { + "record_index": start_row + stats["total_records_scanned"] - 1, + "url_replaced": json_safe(replaced_url), + "content_replaced": json_safe(replaced_content), + "_pii_replaced": True, + "_pii_filter_mode": MODE_NAME, + "_pii_detected_types": sorted(matched_types), + "_pii_detected_types_ja": [PII_LABELS_JA[item] for item in sorted(matched_types)], + "_pii_matches": matches_to_dict(matches), + "_pii_match_count": len(matches), + "_pii_source_file": str(input_path), + "_pii_scanned_at_utc": scanned_at, + } + audit_handle.write(json.dumps(audit_record, ensure_ascii=False, separators=(",", ":")) + "\n") + else: + stats["records_unchanged"] += 1 + writer.write_table(pa.Table.from_pylist(replaced_rows, schema=schema)) + finally: + writer.close() + audit_handle.close() + + stats["row_range"] = { + "start_row_inclusive": start_row, + "end_row_exclusive": start_row + stats["total_records_scanned"], + } + stats.update({ + "scanned_at_utc": scanned_at, + "person_name_unmasked_candidates": { + "honorific_only": {"records": detector.honorific_name_records, "spans": detector.honorific_name_candidates, + "masked": mask_honorific_names, "note_ja": "「○○さん/氏/様」だけの姓名。既定では置換しない(--mask-honorific-names で置換)。"}, + "bare": {"records": detector.bare_name_records, "spans": detector.bare_name_candidates, + "masked": mask_bare_names, "note_ja": "文脈の無い姓名。既定では置換しない(--mask-bare-names で置換)。"}, + }, + "audit_jsonl": str(audit_path), + "replaced_parquet": str(replaced_path), + }) + (output_root / "summary.json").write_text(json.dumps(stats, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + return stats + diff --git a/code/3c1a8da-dirty-0c72d075/src/filter_toxic.py b/code/3c1a8da-dirty-0c72d075/src/filter_toxic.py new file mode 100644 index 0000000000000000000000000000000000000000..974bc54ddbfe269cef4a02282d9542bee2a13b7a --- /dev/null +++ b/code/3c1a8da-dirty-0c72d075/src/filter_toxic.py @@ -0,0 +1,587 @@ +"""有害コンテンツのワードリスト検出と文書フィルタリング。 + +実行入口と引数処理は ``main_toxic.py`` に置き、このモジュールには +ワードリストの読み込み、照合、出力および集計の定義だけを置く。現在の +有害コンテンツ条件は、同一カテゴリの異なる語が3種類以上なら削除する +単一条件(``distinct_terms_3plus``)に限定する。 + +照合は部分一致だが、語の端がASCII英数字またはカタカナの場合は同種の文字が +隣接する位置では一致させない(「メイク」中の「イク」、「DVD」中の「dv」を +防ぐ)。さらに ``wordlists/exclude`` の除外リストで、汎用語を既存リストを +書き換えずに照合対象から外せる。 + +削除条件はワードリストのほかに、URLのドメインブロックリスト +(``domain_blocklist.py``)と近接共起規則(``cooccurrence.py``)がある。 +3系統の判定結果と理由別件数を summary.json と removed.jsonl に記録する。 +""" + +from __future__ import annotations + +import json +import re +from collections import Counter, defaultdict +from dataclasses import dataclass +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Iterable + +import pyarrow as pa +import pyarrow.parquet as pq + +from cooccurrence import CooccurrenceDetector +from domain_blocklist import DomainBlocklist +from textmatch import ASCII_EDGE, KATAKANA_EDGE, compile_trie_pattern, normalize, read_terms as _read_terms # noqa: F401 + + +CATEGORIES = ( + "adult", + "violence", + "discrimination", + "crime", + "propaganda_conspiracy", + "spam", +) + +CATEGORY_LABELS_JA = { + "adult": "性的・わいせつ", + "violence": "暴力・自傷・自殺", + "discrimination": "差別・ヘイト・誹謗中傷", + "crime": "違法行為の手引き", + "propaganda_conspiracy": "過激な政治・宗教プロパガンダ・陰謀論", + "spam": "スパム・詐欺・アダルト・違法コピー配布サイト由来", +} + +MODE_CONFIGS: dict[str, dict[str, Any]] = { + "distinct_terms_3plus": { + "threshold": 3, + # カテゴリ別の上書き。crime は薬物名・手口名が報道や法律解説に並びやすいため5語以上にする。 + "category_thresholds": {"crime": 5}, + "criterion_ja": "同じカテゴリの異なる該当単語が3種類以上(crime は5種類以上、URLと本文の合計)ある文書を削除", + }, +} + + +def category_threshold(config: dict[str, Any], category: str) -> int: + return int(config.get("category_thresholds", {}).get(category, config["threshold"])) + + +def json_safe(value: Any) -> Any: + """JSONLに書ける基本型へ変換する。""" + + if value is None or isinstance(value, (str, int, bool)): + return value + if isinstance(value, float): + return value if value == value and abs(value) != float("inf") else None + if isinstance(value, (list, tuple)): + return [json_safe(item) for item in value] + if isinstance(value, dict): + return {str(key): json_safe(item) for key, item in value.items()} + return str(value) + + +@dataclass(frozen=True) +class Wordlists: + """カテゴリ別の照合語と、その出典および除外された語。""" + + terms: dict[str, list[str]] + sources: dict[str, dict[str, list[str]]] + excluded: dict[str, list[str]] + + +def load_wordlists( + reference_dir: Path, + additional_dir: Path, + exclude_dir: Path | None = None, +) -> Wordlists: + """referenceと追加リストを統合し、除外リストの語を取り除く。 + + 正規化後に重複した語は一つにまとめる。``exclude_dir`` の + ``ja__exclude.txt`` にある語は、出典にかかわらず当該カテゴリの + 照合対象から外す。汎用語による誤検出を、既存リストを書き換えずに + 抑えるための仕組みである。実際に取り除いた語は ``excluded`` に残す。 + """ + + terms_by_category: dict[str, list[str]] = {} + sources_by_category: dict[str, dict[str, list[str]]] = {} + excluded_by_category: dict[str, list[str]] = {} + for category in CATEGORIES: + source_terms: dict[str, set[str]] = defaultdict(set) + for source_name, directory in (("reference", reference_dir), ("additional", additional_dir)): + for term in _read_terms(directory / f"ja_{category}_keywords.txt"): + source_terms[term].add(source_name) + excluded: set[str] = set() + if exclude_dir is not None: + excluded = set(_read_terms(exclude_dir / f"ja_{category}_exclude.txt")) + excluded_by_category[category] = sorted(term for term in excluded if term in source_terms) + terms = sorted( + (term for term in source_terms if term not in excluded), + key=lambda term: (-len(term), term), + ) + terms_by_category[category] = terms + sources_by_category[category] = { + term: sorted(source_terms[term]) for term in terms + } + return Wordlists(terms_by_category, sources_by_category, excluded_by_category) + + +class KeywordMatcher: + """全カテゴリの語を一度の正規表現走査で数える。 + + 本文は文字種境界付きで照合する。URLはドメインやパスが単語を区切りなしに + 連結する(sexynews、hentaio など)ため境界なしで照合する。URL中の日本語は + パーセント符号化されているので、影響を受けるのはASCII語だけである。 + """ + + def __init__( + self, + terms_by_category: dict[str, list[str]], + sources_by_category: dict[str, dict[str, list[str]]], + ) -> None: + self.sources_by_category = sources_by_category + term_categories: dict[str, list[str]] = defaultdict(list) + for category in CATEGORIES: + for term in terms_by_category[category]: + term_categories[term].append(category) + self.term_categories = { + term: tuple(categories) for term, categories in term_categories.items() + } + alternatives = sorted(self.term_categories, key=lambda term: (-len(term), term)) + self.pattern = compile_trie_pattern(alternatives) + self.url_pattern = compile_trie_pattern(alternatives, boundaries=False) + + def count_text(self, text: Any, pattern: re.Pattern[str] | None = None) -> Counter[tuple[str, str]]: + counts: Counter[tuple[str, str]] = Counter() + normalized = normalize(text) + if not normalized: + return counts + for found in (pattern or self.pattern).finditer(normalized): + term = found.group(0) + for category in self.term_categories[term]: + counts[(category, term)] += 1 + return counts + + def match_record(self, url: Any, content: Any) -> list[dict[str, Any]]: + url_counts = self.count_text(url, self.url_pattern) + content_counts = self.count_text(content) + total_counts = url_counts + content_counts + return [ + { + "category": category, + "category_ja": CATEGORY_LABELS_JA[category], + "term": term, + "occurrences": occurrences, + "url_occurrences": url_counts[(category, term)], + "content_occurrences": content_counts[(category, term)], + "wordlist_sources": self.sources_by_category[category][term], + } + for (category, term), occurrences in sorted( + total_counts.items(), + key=lambda item: (CATEGORIES.index(item[0][0]), item[0][1]), + ) + ] + + +def _new_stats( + mode_name: str, + source_file: Path, + wordlist_counts: dict[str, int], +) -> dict[str, Any]: + config = MODE_CONFIGS[mode_name] + return { + "filter_mode": mode_name, + "threshold": config["threshold"], + "category_thresholds": config.get("category_thresholds", {}), + "criterion_ja": config["criterion_ja"], + "source_file": str(source_file), + "wordlist_unique_terms_by_category": wordlist_counts, + "total_records_scanned": 0, + "records_with_any_keyword_match": 0, + "records_deleted": 0, + "records_retained": 0, + "deletion_rate": 0.0, + "records_deleted_by_reason": {"wordlist": 0, "domain_blocklist": 0, "cooccurrence": 0, "multiple_reasons": 0}, + "domain_blocklist": {"enabled": False}, + "cooccurrence": {"enabled": False}, + "total_keyword_occurrences": 0, + "by_category": { + category: { + "label_ja": CATEGORY_LABELS_JA[category], + "records_with_match": 0, + "records_deleted": 0, + "keyword_occurrences": 0, + "distinct_terms_matched": 0, + } + for category in CATEGORIES + }, + "top_matched_terms": [], + "term_statistics": [], + } + + +def _distinct_terms_by_category(matches: list[dict[str, Any]]) -> dict[str, list[str]]: + terms_by_category: dict[str, set[str]] = {category: set() for category in CATEGORIES} + for item in matches: + terms_by_category[item["category"]].add(item["term"]) + return {category: sorted(terms) for category, terms in terms_by_category.items() if terms} + + +def _deleted_categories( + matches: list[dict[str, Any]], + threshold: int, + category_thresholds: dict[str, int] | None = None, +) -> list[str]: + distinct = _distinct_terms_by_category(matches) + overrides = category_thresholds or {} + return [ + category for category in CATEGORIES + if len(distinct.get(category, ())) >= int(overrides.get(category, threshold)) + ] + + +def _update_stats( + stats: dict[str, Any], + matches: list[dict[str, Any]], + deleted_categories: list[str], + term_record_counts: Counter[tuple[str, str]], + term_occurrence_counts: Counter[tuple[str, str]], +) -> None: + if not matches: + return + stats["records_with_any_keyword_match"] += 1 + total_occurrences = sum(item["occurrences"] for item in matches) + stats["total_keyword_occurrences"] += total_occurrences + for category in {item["category"] for item in matches}: + category_items = [item for item in matches if item["category"] == category] + category_stats = stats["by_category"][category] + category_stats["records_with_match"] += 1 + category_stats["keyword_occurrences"] += sum(item["occurrences"] for item in category_items) + if category in deleted_categories: + category_stats["records_deleted"] += 1 + for item in matches: + key = (item["category"], item["term"]) + term_record_counts[key] += 1 + term_occurrence_counts[key] += item["occurrences"] + + +def _finalize_stats( + stats: dict[str, Any], + term_record_counts: Counter[tuple[str, str]], + term_occurrence_counts: Counter[tuple[str, str]], +) -> None: + total = stats["total_records_scanned"] + stats["records_retained"] = total - stats["records_deleted"] + stats["deletion_rate"] = stats["records_deleted"] / total if total else 0.0 + stats["term_statistics"] = [ + { + "category": category, + "category_ja": CATEGORY_LABELS_JA[category], + "term": term, + "records_with_match": term_record_counts[(category, term)], + "keyword_occurrences": term_occurrence_counts[(category, term)], + } + for category, term in sorted(term_record_counts, key=lambda key: (CATEGORIES.index(key[0]), key[1])) + ] + for category in CATEGORIES: + stats["by_category"][category]["distinct_terms_matched"] = sum( + 1 for item in stats["term_statistics"] if item["category"] == category + ) + stats["top_matched_terms"] = sorted( + stats["term_statistics"], + key=lambda item: (-item["records_with_match"], -item["keyword_occurrences"], item["category"], item["term"]), + )[:100] + + +def _new_blocklist_stats(blocklist: DomainBlocklist) -> dict[str, Any]: + return { + "enabled": True, + "sources": blocklist.manifest(), + "records_matched": 0, + "records_deleted": 0, + "records_flagged_only": 0, + "by_source": { + source["name"]: {"action": source["action"], "records_matched": 0, "records_deleted": 0} + for source in blocklist.manifest() + }, + } + + +def _new_cooccurrence_stats(detector: CooccurrenceDetector) -> dict[str, Any]: + return { + "enabled": True, + "rules": detector.describe(), + "records_matched": 0, + "records_deleted": 0, + "by_rule": { + rule["name"]: { + "label_ja": rule["label_ja"], + "category": rule["category"], + "records_matched": 0, + "pair_counts": Counter(), + } + for rule in detector.describe() + }, + } + + +REASON_LABELS_JA = { + "wordlist": "ワードリスト(同一カテゴリ3語以上)", + "domain_blocklist": "URLのドメインがブロックリストに一致", + "cooccurrence": "近接共起規則(未成年×性的文脈、違法物×手引き)", +} + + +def run_toxic_filters( + input_path: Path, + output_root: Path, + reference_dir: Path, + additional_dir: Path, + batch_size: int = 2048, + modes: Iterable[str] | None = None, + start_row: int = 0, + max_rows: int | None = None, + exclude_dir: Path | None = None, + blocklist: DomainBlocklist | None = None, + cooccurrence: CooccurrenceDetector | None = None, +) -> dict[str, Any]: + """指定モードの有害コンテンツフィルタを一度の走査で実行する。 + + 削除条件は3系統ある。(1) ワードリストの同一カテゴリ3語以上、(2) URLの + ドメインブロックリスト、(3) 近接共起規則。(2)(3) はモードに依存せず + 全モードで同じ判定になる。共起規則の一致は全件を + ``cooccurrence_review.jsonl`` に、ブロックリストの記録のみ一致は + ``flagged.jsonl`` に書き出す。 + """ + + selected_modes = list(modes) if modes is not None else list(MODE_CONFIGS) + unknown = [mode for mode in selected_modes if mode not in MODE_CONFIGS] + if unknown: + raise ValueError(f"未知のモード: {', '.join(unknown)}") + if not selected_modes: + raise ValueError("少なくとも1つのモードを指定してください") + + wordlists = load_wordlists(reference_dir, additional_dir, exclude_dir) + wordlist_counts = {category: len(wordlists.terms[category]) for category in CATEGORIES} + matcher = KeywordMatcher(wordlists.terms, wordlists.sources) + output_dirs = {mode: output_root / mode for mode in selected_modes} + for directory in output_dirs.values(): + directory.mkdir(parents=True, exist_ok=True) + parquet = pq.ParquetFile(input_path) + schema = parquet.schema_arrow + writers = { + mode: pq.ParquetWriter(directory / "retained.parquet", schema, compression="zstd") + for mode, directory in output_dirs.items() + } + handles = { + mode: (directory / "removed.jsonl").open("w", encoding="utf-8", newline="\n") + for mode, directory in output_dirs.items() + } + review_handles = { + mode: (directory / "cooccurrence_review.jsonl").open("w", encoding="utf-8", newline="\n") + for mode, directory in output_dirs.items() + } if cooccurrence is not None else {} + flagged_handles = { + mode: (directory / "flagged.jsonl").open("w", encoding="utf-8", newline="\n") + for mode, directory in output_dirs.items() + } if blocklist is not None else {} + borderline_handles = { + mode: (directory / "borderline.jsonl").open("w", encoding="utf-8", newline="\n") + for mode, directory in output_dirs.items() + } + stats_by_mode = {mode: _new_stats(mode, input_path, wordlist_counts) for mode in selected_modes} + for stats in stats_by_mode.values(): + if blocklist is not None: + stats["domain_blocklist"] = _new_blocklist_stats(blocklist) + if cooccurrence is not None: + stats["cooccurrence"] = _new_cooccurrence_stats(cooccurrence) + record_counts = {mode: Counter() for mode in selected_modes} + occurrence_counts = {mode: Counter() for mode in selected_modes} + scanned_at = datetime.now(timezone.utc).isoformat() + stop_row = start_row + max_rows if max_rows is not None else None + row_offset = 0 + scanned = 0 + try: + for source_batch in parquet.iter_batches(batch_size=batch_size): + source_start = row_offset + row_offset += source_batch.num_rows + if row_offset <= start_row: + continue + if stop_row is not None and source_start >= stop_row: + break + local_start = max(0, start_row - source_start) + local_end = source_batch.num_rows if stop_row is None else min(source_batch.num_rows, stop_row - source_start) + batch = source_batch.slice(local_start, local_end - local_start) + rows = batch.to_pylist() + retained_indices = {mode: [] for mode in selected_modes} + for row_index, row in enumerate(rows): + url = row.get("url") or "" + content = row.get("content") or "" + record_index = start_row + scanned + scanned += 1 + matches = matcher.match_record(url, content) + domain_matches = blocklist.match(url) if blocklist is not None else [] + domain_delete = any(item["action"] == "delete" for item in domain_matches) + cooccurrence_matches = cooccurrence.detect(content) if cooccurrence is not None else [] + for mode in selected_modes: + config = MODE_CONFIGS[mode] + deleted_categories = _deleted_categories(matches, config["threshold"], config.get("category_thresholds")) + reasons = [] + if deleted_categories: + reasons.append("wordlist") + if domain_delete: + reasons.append("domain_blocklist") + if cooccurrence_matches: + reasons.append("cooccurrence") + deleted = bool(reasons) + stats = stats_by_mode[mode] + stats["total_records_scanned"] += 1 + _update_stats(stats, matches, deleted_categories, record_counts[mode], occurrence_counts[mode]) + if domain_matches: + block_stats = stats["domain_blocklist"] + block_stats["records_matched"] += 1 + if deleted: + block_stats["records_deleted"] += 1 + elif not domain_delete: + block_stats["records_flagged_only"] += 1 + for source_name in {item["source"] for item in domain_matches}: + block_stats["by_source"][source_name]["records_matched"] += 1 + if deleted: + block_stats["by_source"][source_name]["records_deleted"] += 1 + if cooccurrence_matches: + cooc_stats = stats["cooccurrence"] + cooc_stats["records_matched"] += 1 + cooc_stats["records_deleted"] += 1 + for item in cooccurrence_matches: + rule_stats = cooc_stats["by_rule"][item["rule"]] + rule_stats["records_matched"] += 1 + for pair in item["pairs"]: + rule_stats["pair_counts"][f"{pair['a']}|{pair['b']}"] += 1 + review_handles[mode].write(json.dumps({ + "record_index": record_index, + "url": json_safe(url), + "rule": item["rule"], + "label_ja": item["label_ja"], + "pair_count": item["pair_count"], + "pairs": item["pairs"], + "excerpt": item["excerpt"], + "reviewer": "", + "verdict": "", + "reason": "", + }, ensure_ascii=False, separators=(",", ":")) + "\n") + if deleted: + stats["records_deleted"] += 1 + for reason in reasons: + stats["records_deleted_by_reason"][reason] += 1 + if len(reasons) > 1: + stats["records_deleted_by_reason"]["multiple_reasons"] += 1 + output_record = {str(key): json_safe(value) for key, value in row.items()} + output_record.update( + { + "_filter_deleted": True, + "_filter_mode": mode, + "_filter_threshold": config["threshold"], + "_filter_deleted_by": reasons, + "_filter_reason": ";".join(REASON_LABELS_JA[reason] for reason in reasons), + "_filter_deleted_categories": deleted_categories, + "_filter_distinct_matched_terms_by_category": { + category: sorted({item["term"] for item in matches if item["category"] == category}) + for category in deleted_categories + }, + "_filter_matched_terms": matches, + "_filter_total_keyword_occurrences": sum(item["occurrences"] for item in matches), + "_filter_domain_matches": domain_matches, + "_filter_cooccurrence_matches": cooccurrence_matches, + "_filter_record_index": record_index, + "_filter_method": "wordlist_toxic_filter_v4", + "_filter_source_file": str(input_path), + "_filter_scanned_at_utc": scanned_at, + } + ) + handles[mode].write(json.dumps(output_record, ensure_ascii=False, separators=(",", ":")) + "\n") + else: + borderline = { + category: terms + for category, terms in _distinct_terms_by_category(matches).items() + if len(terms) == category_threshold(config, category) - 1 + } + if borderline: + borderline_handles[mode].write(json.dumps({ + "record_index": record_index, + "url": json_safe(url), + "categories": borderline, + }, ensure_ascii=False, separators=(",", ":")) + "\n") + if domain_matches: + flagged_handles[mode].write(json.dumps({ + "record_index": record_index, + "url": json_safe(url), + "domain_matches": domain_matches, + }, ensure_ascii=False, separators=(",", ":")) + "\n") + retained_indices[mode].append(row_index) + for mode in selected_modes: + if retained_indices[mode]: + writers[mode].write_batch(batch.take(pa.array(retained_indices[mode], type=pa.int64()))) + finally: + for writer in writers.values(): + writer.close() + for handle in ( + list(handles.values()) + list(review_handles.values()) + + list(flagged_handles.values()) + list(borderline_handles.values()) + ): + handle.close() + + for mode, stats in stats_by_mode.items(): + _finalize_stats(stats, record_counts[mode], occurrence_counts[mode]) + if stats["cooccurrence"].get("enabled"): + for rule_stats in stats["cooccurrence"]["by_rule"].values(): + rule_stats["pair_counts"] = [ + {"pair": pair, "records": count} for pair, count in rule_stats["pair_counts"].most_common(30) + ] + stats.update( + { + "scanned_at_utc": scanned_at, + "input_schema": list(schema.names), + "row_range": { + "start_row_inclusive": start_row, + "end_row_exclusive": start_row + stats["total_records_scanned"], + }, + "removed_jsonl": str(output_dirs[mode] / "removed.jsonl"), + "retained_parquet": str(output_dirs[mode] / "retained.parquet"), + "cooccurrence_review_jsonl": str(output_dirs[mode] / "cooccurrence_review.jsonl") if cooccurrence is not None else None, + "flagged_jsonl": str(output_dirs[mode] / "flagged.jsonl") if blocklist is not None else None, + "borderline_jsonl": str(output_dirs[mode] / "borderline.jsonl"), + "wordlist_reference_dir": str(reference_dir), + "wordlist_additional_dir": str(additional_dir), + "wordlist_exclude_dir": str(exclude_dir) if exclude_dir is not None else None, + "wordlist_excluded_terms_by_category": wordlists.excluded, + "wordlist_matching_scope": "url + content", + "matching_normalization": "NFKC then lowercase", + "same_position_partial_match_policy": "longest match first", + "matching_boundary_policy": "content: ASCII edge requires no adjacent [a-z0-9], katakana edge requires no adjacent katakana, kanji/hiragana edge none; url: no boundaries", + "deletion_reasons_ja": REASON_LABELS_JA, + "note_ja": "候補語・ブロックリスト・共起規則による機械的な監査結果。最終除外前に文脈と誤検出を確認すること。", + } + ) + (output_dirs[mode] / "summary.json").write_text(json.dumps(stats, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + + combined = { + "source_file": str(input_path), + "scanned_at_utc": scanned_at, + "wordlist_reference_dir": str(reference_dir), + "wordlist_additional_dir": str(additional_dir), + "wordlist_exclude_dir": str(exclude_dir) if exclude_dir is not None else None, + "wordlist_excluded_terms_by_category": wordlists.excluded, + "wordlist_unique_terms_by_category": wordlist_counts, + "domain_blocklist_sources": blocklist.manifest() if blocklist is not None else None, + "cooccurrence_rules": cooccurrence.describe() if cooccurrence is not None else None, + "row_range": { + "start_row_inclusive": start_row, + "end_row_exclusive": start_row + next(iter(stats_by_mode.values()))["total_records_scanned"], + }, + "modes": {mode: stats_by_mode[mode] for mode in selected_modes}, + } + output_root.mkdir(parents=True, exist_ok=True) + (output_root / "summary.json").write_text(json.dumps(combined, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + return combined + + +# 既存コードから呼び出す場合の簡潔な別名。 +run_filter = run_toxic_filters diff --git a/code/3c1a8da-dirty-0c72d075/src/guard_classifier.py b/code/3c1a8da-dirty-0c72d075/src/guard_classifier.py new file mode 100644 index 0000000000000000000000000000000000000000..3b0cebe0a92c66e658a4222934aebee93b737a6c --- /dev/null +++ b/code/3c1a8da-dirty-0c72d075/src/guard_classifier.py @@ -0,0 +1,113 @@ +"""Qwen3Guard-Gen をバッチ推論するバックエンド(第3パス用)。 + +vLLM(GPU、既定)と transformers(左パディングの一括生成)を選べる。出力は +``Safety: Safe|Unsafe|Controversial`` と ``Categories: ...`` を含む短い文字列で、 +``parse`` が安全性ラベルとカテゴリ名の一覧に分解する。 + +テスト用に ``FakeBackend`` を用意する(``marker`` を含む本文を Unsafe と判定する)。 +""" + +from __future__ import annotations + +import re +from typing import Any + +DEFAULT_MODEL = "Qwen/Qwen3Guard-Gen-0.6B" +SAFETY_RE = re.compile(r"Safety:\s*(Safe|Unsafe|Controversial)", re.I) +CATEGORY_NAMES = ( + "Violent", "Non-violent Illegal Acts", "Sexual Content or Sexual Acts", "PII", "Suicide & Self-Harm", + "Unethical Acts", "Politically Sensitive Topics", "Copyright Violation", "Jailbreak", +) +CATEGORY_RE = re.compile("|".join(re.escape(name) for name in CATEGORY_NAMES), re.I) +CANONICAL = {name.lower(): name for name in CATEGORY_NAMES} + + +def parse(raw: str) -> tuple[str | None, list[str]]: + """モデル出力から (安全性ラベル, カテゴリ一覧) を取り出す。取れなければ (None, [])。""" + + match = SAFETY_RE.search(raw or "") + categories = sorted({CANONICAL[m.lower()] for m in CATEGORY_RE.findall(raw or "")}) + return (match.group(1).title() if match else None), categories + + +class VllmBackend: + def __init__(self, model: str = DEFAULT_MODEL, max_chars: int = 2000, gpu_memory_utilization: float = 0.85, max_model_len: int = 4096) -> None: + from transformers import AutoTokenizer + from vllm import LLM, SamplingParams + + self.tokenizer = AutoTokenizer.from_pretrained(model) + self.llm = LLM(model=model, gpu_memory_utilization=gpu_memory_utilization, max_model_len=max_model_len, enable_prefix_caching=True) + self.params = SamplingParams(max_tokens=48, temperature=0.0) + self.model = model + self.max_chars = max_chars + + def classify(self, texts: list[str]) -> list[str]: + prompts = [self.tokenizer.apply_chat_template([{"role": "user", "content": t[: self.max_chars]}], tokenize=False) for t in texts] + outputs = self.llm.generate(prompts, self.params, use_tqdm=False) + return [o.outputs[0].text for o in outputs] + + +class TransformersBackend: + def __init__(self, model: str = DEFAULT_MODEL, max_chars: int = 2000, device: str = "auto", batch_size: int = 8) -> None: + import torch + from transformers import AutoModelForCausalLM, AutoTokenizer + + self.torch = torch + self.tokenizer = AutoTokenizer.from_pretrained(model) + self.tokenizer.padding_side = "left" + if self.tokenizer.pad_token is None: + self.tokenizer.pad_token = self.tokenizer.eos_token + kwargs: dict[str, Any] = {"device_map": "auto"} if device == "auto" else {} + try: + self.model = AutoModelForCausalLM.from_pretrained(model, dtype="auto", **kwargs) + except TypeError: + self.model = AutoModelForCausalLM.from_pretrained(model, torch_dtype="auto", **kwargs) + if device != "auto": + self.model = self.model.to(device) + self.model.eval() + self.max_chars = max_chars + self.batch_size = batch_size + + def classify(self, texts: list[str]) -> list[str]: + results: list[str] = [] + for start in range(0, len(texts), self.batch_size): + chunk = texts[start : start + self.batch_size] + prompts = [self.tokenizer.apply_chat_template([{"role": "user", "content": t[: self.max_chars]}], tokenize=False) for t in chunk] + inputs = self.tokenizer(prompts, return_tensors="pt", padding=True).to(self.model.device) + with self.torch.no_grad(): + generated = self.model.generate(**inputs, max_new_tokens=48, do_sample=False, pad_token_id=self.tokenizer.pad_token_id) + new_tokens = generated[:, inputs["input_ids"].shape[1]:] + results.extend(self.tokenizer.batch_decode(new_tokens, skip_special_tokens=True)) + return results + + +class FakeBackend: + """テスト用。``marker`` を含む本文を Unsafe(``category``)、``controversial_marker`` を含む本文を Controversial とする。""" + + def __init__(self, marker: str = "UNSAFE_MARKER", category: str = "Sexual Content or Sexual Acts", controversial_marker: str = "CONTRO_MARKER") -> None: + self.marker = marker + self.category = category + self.controversial_marker = controversial_marker + self.calls = 0 + + def classify(self, texts: list[str]) -> list[str]: + self.calls += 1 + out = [] + for text in texts: + if self.marker in text: + out.append(f"Safety: Unsafe\nCategories: {self.category}") + elif self.controversial_marker in text: + out.append("Safety: Controversial\nCategories: Politically Sensitive Topics") + else: + out.append("Safety: Safe\nCategories: None") + return out + + +def make_backend(name: str, model: str = DEFAULT_MODEL, max_chars: int = 2000, device: str = "auto") -> Any: + if name == "vllm": + return VllmBackend(model, max_chars) + if name == "transformers": + return TransformersBackend(model, max_chars, device) + if name == "fake": + return FakeBackend() + raise ValueError(f"unknown backend: {name}") diff --git a/code/3c1a8da-dirty-0c72d075/src/hf_jobs_launch.py b/code/3c1a8da-dirty-0c72d075/src/hf_jobs_launch.py new file mode 100644 index 0000000000000000000000000000000000000000..204793b482f7f0310e47ba8f00c47936931cb0d4 --- /dev/null +++ b/code/3c1a8da-dirty-0c72d075/src/hf_jobs_launch.py @@ -0,0 +1,523 @@ +"""HF Jobs で全シャードのクレンジングを実行するランチャー。 + +``common_crawl_0`` 〜 ``common_crawl_18`` の各ディレクトリを1ジョブにし、次を行う。 + +* 入力データセット(``Podtech/abeja-cc-ja-filtered``)を ``/data`` にマウント(ダウンロード不要) +* このリポジトリの ``src/`` と UT1 ブロックリストのキャッシュを、出力用の非公開データセットへ + ``code//src`` と ``blocklists/ut1`` として1回だけアップロードし、各ジョブがそこから取得する + (全ジョブが同じコード・同じリストで動くことをマニフェストで保証する) +* ``HF_TOKEN`` はシークレットとして渡す(ログに出ない) +* ``run_shard.py`` を ``--upload-repo`` 付きで実行し、出力は ``outputs/common_crawl_N//`` へ + シャード単位でアップロードして一時ディスクから削除する +* タイムアウトは既定の30分ではなく ``--timeout``(既定 6h)を指定する + + uv run --env-file .env python abeja-cc-ja/src/hf_jobs_launch.py --dirs 0 --limit-shards 2 --dry-run + uv run --env-file .env python abeja-cc-ja/src/hf_jobs_launch.py --dirs 0 --limit-shards 2 + uv run --env-file .env python abeja-cc-ja/src/hf_jobs_launch.py --dirs 0-18 --policy-approver "<名前>" --policy-approved-on 2026-09-04 + +完了後は ``aggregate_summaries.py --repo <出力repo> --prefix outputs --expected-inputs <入力repo>`` で集約する。 +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import shlex +import subprocess +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + + +DEFAULT_INPUT = "Podtech/abeja-cc-ja-filtered" +DEFAULT_OUTPUT = "Podtech/abeja-cc-ja-cleaned" +DEFAULT_IMAGE = "python:3.12" +DEFAULT_FLAVOR = "cpu-upgrade" +DEFAULT_TIMEOUT = "6h" +CODE_IGNORE = ["__pycache__/**", "*.pyc", ".pytest_cache/**", "test_*.py", "*.md"] + + +def parse_dirs(spec: str) -> list[int]: + result: list[int] = [] + for part in spec.split(","): + part = part.strip() + if "-" in part: + low, high = part.split("-", 1) + result.extend(range(int(low), int(high) + 1)) + elif part: + result.append(int(part)) + return sorted(set(result)) + + +def code_ref(code_dir: Path) -> str: + """git のコミット短縮ハッシュ(未コミット変更があれば -dirty と内容ハッシュ)。""" + + try: + sha = subprocess.check_output(["git", "rev-parse", "--short", "HEAD"], cwd=code_dir, text=True).strip() + dirty = subprocess.check_output(["git", "status", "--porcelain", "--", "."], cwd=code_dir, text=True).strip() != "" + except Exception: # noqa: BLE001 + sha, dirty = "nogit", True + if not dirty: + return sha + digest = hashlib.sha256() + for path in sorted(code_dir.rglob("*")): + if path.is_file() and "__pycache__" not in path.parts and not path.name.startswith("test_"): + digest.update(path.relative_to(code_dir).as_posix().encode()) + digest.update(path.read_bytes()) + return f"{sha}-dirty-{digest.hexdigest()[:8]}" + + +def build_noise_job_script(output_repo: str, ref: str, dir_index: int, args: argparse.Namespace) -> str: + """第2パス(ノイズ除去)。出力データセットを /cleaned にマウントし、第1パスの出力を入力にする。""" + + input_dir = f"/cleaned/{args.input_prefix}/common_crawl_{dir_index}" + run_args = [ + "--input-dir", input_dir, + "--output-root", f"/work/out/common_crawl_{dir_index}", + "--lid-model", "/work/repo/models/lid.176.ftz", + "--staging-dir", "/work/staging", + "--upload-repo", output_repo, + "--upload-prefix", f"{args.noise_prefix}/common_crawl_{dir_index}", + "--upload-batch", str(args.upload_batch), + "--delete-local-after-upload", + "--skip-existing-in-repo", + "--min-chars", str(args.min_chars), "--max-chars", str(args.max_chars), "--newline-policy", args.newline_policy, + ] + if args.limit_shards is not None: + run_args += ["--limit-shards", str(args.limit_shards)] + if args.tokenizer: + run_args += ["--tokenizer", args.tokenizer] + if args.min_tokens is not None: + run_args += ["--min-tokens", str(args.min_tokens)] + if args.max_tokens is not None: + run_args += ["--max-tokens", str(args.max_tokens)] + workers_expr = str(args.workers) if args.workers else '"$(( ${CPU_CORES:-2} > 1 ? ${CPU_CORES:-2} - 1 : 1 ))"' + snapshot = ( + "import time; from huggingface_hub import snapshot_download\n" + "for attempt in range(5):\n" + " try:\n" + f" snapshot_download({output_repo!r}, repo_type='dataset', local_dir='/work/repo', allow_patterns=['code/{ref}/**', 'models/lid.176.ftz']); break\n" + " except Exception as error:\n" + " print('snapshot retry', attempt + 1, repr(error)[:200], flush=True); time.sleep(30 * (attempt + 1))\n" + "else:\n" + " raise SystemExit('code snapshot failed')\n" + ) + extra = ' "transformers>=4.51"' if args.tokenizer else "" + lines = [ + "set -euo pipefail", + "export PIP_DISABLE_PIP_VERSION_CHECK=1 PYTHONUNBUFFERED=1 HF_HUB_DOWNLOAD_TIMEOUT=120 HF_HUB_ETAG_TIMEOUT=60", + f'pip install -q "pyarrow>=17" "huggingface_hub>=1.0" "numpy" "fasttext-wheel"{extra}', + "mkdir -p /work/out && cd /work", + f"python -c {shlex.quote(snapshot)}", + f"ls /work/repo/code/{ref}/src >/dev/null", + "test -f /work/repo/models/lid.176.ftz", + f'echo "input shards: $(ls {input_dir} | wc -l)"', + f"python /work/repo/code/{ref}/src/run_noise_pass.py " + " ".join(shlex.quote(a) for a in run_args) + f" --workers {workers_expr}", + ] + return "\n".join(lines) + "\n" + + +def build_report_job_script(output_repo: str, ref: str, args: argparse.Namespace) -> str: + """品質報告(項目22・25〜29)。第2パスの features.parquet を DuckDB で全件集約し、reports/ へアップロードする。""" + + snapshot = ( + "import time; from huggingface_hub import snapshot_download\n" + "for attempt in range(5):\n" + " try:\n" + f" snapshot_download({output_repo!r}, repo_type='dataset', local_dir='/work/repo', allow_patterns=['code/{ref}/**']); break\n" + " except Exception as error:\n" + " print('snapshot retry', attempt + 1, repr(error)[:200], flush=True); time.sleep(30 * (attempt + 1))\n" + "else:\n" + " raise SystemExit('code snapshot failed')\n" + ) + # features.parquet はマウント越しではなく HTTP でローカルディスクへ取得する(マウント越しだと DuckDB の + # クエリごとに全ファイルを再スキャンして数時間かかる。約 2,420 ファイル・22 GB) + stage_features = ( + "import time; from huggingface_hub import snapshot_download\n" + "for attempt in range(8):\n" + " try:\n" + f" snapshot_download({output_repo!r}, repo_type='dataset', local_dir='/work/features', max_workers=16, " + f"allow_patterns=['{args.noise_prefix}/*/*/features.parquet', '{args.noise_prefix}/*/*/noise_summary.json'" + + (f", '{args.guard_prefix}/*/*/guard_removed.jsonl'" if args.report_with_guard else "") + "]); break\n" + " except Exception as error:\n" + " print('features download retry', attempt + 1, repr(error)[:200], flush=True); time.sleep(30 * (attempt + 1))\n" + "else:\n" + " raise SystemExit('features download failed')\n" + ) + report_args = [ + "--features-glob", f"/work/features/{args.noise_prefix}/**/features.parquet", + "--noise-summaries-glob", f"/work/features/{args.noise_prefix}/**/noise_summary.json", + "--output-dir", "/work/report", + "--temp-dir", "/work/duck_tmp", + ] + if args.report_with_guard: + report_args += ["--guard-removed-glob", f"/work/features/{args.guard_prefix}/**/guard_removed.jsonl"] + if args.previous_low_quality_rate is not None: + report_args += ["--previous-low-quality-rate", str(args.previous_low_quality_rate)] + if args.exclude_genres: + report_args += ["--exclude-genres", args.exclude_genres] + upload = ( + "from huggingface_hub import HfApi; import datetime; " + f"HfApi().upload_folder(repo_id={output_repo!r}, repo_type='dataset', folder_path='/work/report', " + "path_in_repo='reports/quality_' + datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ'), commit_message='quality report (items 22, 25-29)')" + ) + lines = [ + "set -euo pipefail", + "export PIP_DISABLE_PIP_VERSION_CHECK=1 PYTHONUNBUFFERED=1", + 'pip install -q "pyarrow>=17" "huggingface_hub>=1.0" "duckdb>=1.0"', + "mkdir -p /work/report /work/features /work/duck_tmp && cd /work", + "df -h /work | tail -1; nproc; free -g | head -2", + f"python -c {shlex.quote(snapshot)}", + f"python -c {shlex.quote(stage_features)}", + f'echo "feature files: $(find /work/features/{args.noise_prefix} -name features.parquet | wc -l)"; du -sh /work/features', + f"python /work/repo/code/{ref}/src/quality_report.py " + " ".join(shlex.quote(a) for a in report_args), + f"python -c {shlex.quote(upload)}", + ] + return "\n".join(lines) + "\n" + + +def build_guard_job_script(output_repo: str, ref: str, dir_index: int, split_index: int, args: argparse.Namespace) -> str: + """第3パス(Qwen3Guard による削除)。GPU ジョブ。第2パスの出力を HTTP で取得し、候補文書だけ分類する。""" + + run_args = [ + "--source-repo", output_repo, "--source-prefix", args.noise_prefix, "--dir-index", str(dir_index), + "--staging-dir", "/work/staging", + "--output-root", f"/work/out/common_crawl_{dir_index}", + "--backend", "vllm", "--model", args.guard_model, "--max-chars", str(args.guard_max_chars), "--min-terms", str(args.guard_min_terms), + "--chunk-size", str(args.guard_chunk_size), + "--upload-repo", output_repo, "--upload-prefix", f"{args.guard_prefix}/common_crawl_{dir_index}", + "--upload-batch", str(args.upload_batch), "--delete-local-after-upload", "--skip-existing-in-repo", + ] + if args.guard_delete_categories: + run_args += ["--delete-categories", args.guard_delete_categories] + if args.limit_shards is not None: + run_args += ["--limit-shards", str(args.limit_shards)] + if args.split > 1: + run_args += ["--shard-index", str(split_index), "--shard-count", str(args.split)] + if args.workers: + run_args += ["--workers", str(args.workers)] + snapshot = ( + "import time; from huggingface_hub import snapshot_download\n" + "for attempt in range(5):\n" + " try:\n" + f" snapshot_download({output_repo!r}, repo_type='dataset', local_dir='/work/repo', allow_patterns=['code/{ref}/**']); break\n" + " except Exception as error:\n" + " print('snapshot retry', attempt + 1, repr(error)[:200], flush=True); time.sleep(30 * (attempt + 1))\n" + "else:\n" + " raise SystemExit('code snapshot failed')\n" + ) + lines = [ + "set -euo pipefail", + "export PIP_DISABLE_PIP_VERSION_CHECK=1 PYTHONUNBUFFERED=1 HF_HUB_DOWNLOAD_TIMEOUT=120 HF_HUB_ETAG_TIMEOUT=60 HF_HUB_ENABLE_HF_TRANSFER=0", + "PY=$(command -v python3 || command -v python); echo \"python: $PY\"", + '$PY -m pip install -q "pyarrow>=17" "huggingface_hub>=1.0"', + "mkdir -p /work/out /work/staging && cd /work", + "nvidia-smi --query-gpu=name,memory.total --format=csv || true; nproc; df -h /work | tail -1", + "$PY -c \"import vllm, transformers; print('vllm', vllm.__version__, 'transformers', transformers.__version__)\"", + f"$PY -c {shlex.quote(snapshot)}", + f"cd /work/repo/code/{ref}/src", + "$PY run_guard_pass.py " + " ".join(shlex.quote(a) for a in run_args), + ] + return "\n".join(lines) + "\n" + + +def build_quality_job_script(output_repo: str, ref: str, dir_index: int, split_index: int, args: argparse.Namespace) -> str: + """第4パス(低品質フラグ・除外ジャンルの削除)。CPU ジョブ。第3パスの出力と第2パスの特徴量を HTTP で取得する。""" + + run_args = [ + "--source-repo", output_repo, "--source-prefix", args.guard_prefix, "--features-prefix", args.noise_prefix, "--dir-index", str(dir_index), + "--staging-dir", "/work/staging", + "--output-root", f"/work/out/common_crawl_{dir_index}", + "--exclude-genres", args.quality_exclude_genres, "--tokenizer", args.quality_tokenizer, + "--upload-repo", output_repo, "--upload-prefix", f"{args.quality_prefix}/common_crawl_{dir_index}", + "--upload-batch", str(args.upload_batch), "--delete-local-after-upload", "--skip-existing-in-repo", + ] + if args.quality_keep_low_quality: + run_args.append("--keep-low-quality") + if args.quality_low_quality_flags: + run_args += ["--low-quality-flags", args.quality_low_quality_flags] + if args.limit_shards is not None: + run_args += ["--limit-shards", str(args.limit_shards)] + if args.split > 1: + run_args += ["--shard-index", str(split_index), "--shard-count", str(args.split)] + if args.workers: + run_args += ["--workers", str(args.workers)] + snapshot = ( + "import time; from huggingface_hub import snapshot_download\n" + "for attempt in range(5):\n" + " try:\n" + f" snapshot_download({output_repo!r}, repo_type='dataset', local_dir='/work/repo', allow_patterns=['code/{ref}/**']); break\n" + " except Exception as error:\n" + " print('snapshot retry', attempt + 1, repr(error)[:200], flush=True); time.sleep(30 * (attempt + 1))\n" + "else:\n" + " raise SystemExit('code snapshot failed')\n" + ) + lines = [ + "set -euo pipefail", + "export PIP_DISABLE_PIP_VERSION_CHECK=1 PYTHONUNBUFFERED=1 HF_HUB_DOWNLOAD_TIMEOUT=120 HF_HUB_ETAG_TIMEOUT=60 HF_HUB_ENABLE_HF_TRANSFER=0", + "PY=$(command -v python3 || command -v python); echo \"python: $PY\"", + '$PY -m pip install -q "pyarrow>=17" "huggingface_hub>=1.0" "tiktoken>=0.11"', + "mkdir -p /work/out /work/staging && cd /work", + "nproc; df -h /work | tail -1", + f"$PY -c {shlex.quote(snapshot)}", + f"cd /work/repo/code/{ref}/src", + "$PY run_quality_pass.py " + " ".join(shlex.quote(a) for a in run_args) + + ("" if args.workers else ' --workers "$(( ${CPU_CORES:-8} > 1 ? ${CPU_CORES:-8} - 1 : 1 ))"'), + ] + return "\n".join(lines) + "\n" + + +def build_job_script(output_repo: str, ref: str, dir_index: int, args: argparse.Namespace) -> str: + input_dir = f"/data/data/common_crawl_{dir_index}" + run_args = [ + "--input-dir", input_dir, + "--output-root", f"/work/out/common_crawl_{dir_index}", + "--blocklist-cache-dir", "/work/repo/blocklists/ut1", + "--staging-dir", "/work/staging", + "--upload-repo", output_repo, + "--upload-prefix", f"outputs/common_crawl_{dir_index}", + "--upload-batch", str(args.upload_batch), + "--delete-local-after-upload", + "--skip-existing-in-repo", + ] + if args.limit_shards is not None: + run_args += ["--limit-shards", str(args.limit_shards)] + if args.policy_approver: + run_args += ["--policy-approver", args.policy_approver] + if args.policy_approved_on: + run_args += ["--policy-approved-on", args.policy_approved_on] + if args.policy_note: + run_args += ["--policy-note", args.policy_note] + workers_expr = str(args.workers) if args.workers else '"$(( ${CPU_CORES:-2} > 1 ? ${CPU_CORES:-2} - 1 : 1 ))"' + snapshot = ( + "import time; from huggingface_hub import snapshot_download\n" + "for attempt in range(5):\n" + " try:\n" + f" snapshot_download({output_repo!r}, repo_type='dataset', local_dir='/work/repo', allow_patterns=['code/{ref}/**', 'blocklists/ut1/**']); break\n" + " except Exception as error:\n" + " print('snapshot retry', attempt + 1, repr(error)[:200], flush=True); time.sleep(30 * (attempt + 1))\n" + "else:\n" + " raise SystemExit('code snapshot failed')\n" + ) + lines = [ + "set -euo pipefail", + "export PIP_DISABLE_PIP_VERSION_CHECK=1 PYTHONUNBUFFERED=1 HF_HUB_DOWNLOAD_TIMEOUT=120 HF_HUB_ETAG_TIMEOUT=60", + 'pip install -q "pyarrow>=17" "huggingface_hub>=1.0" "sudachipy>=0.6" "sudachidict_core"', + "mkdir -p /work/out && cd /work", + f"python -c {shlex.quote(snapshot)}", + f"ls /work/repo/code/{ref}/src >/dev/null", + f"test -f /work/repo/blocklists/ut1/manifest.json", + # pipefail 下で `ls | head` は SIGPIPE で失敗し得るため、件数だけを表示する + f'echo "input shards: $(ls {input_dir} | wc -l)"', + f"python /work/repo/code/{ref}/src/run_shard.py " + " ".join(shlex.quote(a) for a in run_args) + f" --workers {workers_expr}", + ] + return "\n".join(lines) + "\n" + + +def upload_code_and_blocklists(api, output_repo: str, code_dir: Path, ref: str, ut1_cache_dir: Path, dry_run: bool) -> dict[str, Any]: + def exists(path: str) -> bool: + return (not dry_run) and api.file_exists(output_repo, path, repo_type="dataset") + + code_prefix = f"code/{ref}/src" + files = sorted(p for p in code_dir.rglob("*") if p.is_file() and "__pycache__" not in p.parts and not p.name.startswith("test_") and not p.name.endswith(".pyc")) + manifest = { + "ref": ref, + "uploaded_at_utc": datetime.now(timezone.utc).isoformat(), + "files": {p.relative_to(code_dir).as_posix(): hashlib.sha256(p.read_bytes()).hexdigest() for p in files}, + } + actions: dict[str, Any] = {"code_prefix": code_prefix, "code_files": len(files), "ref": ref} + if dry_run: + actions["code_upload"] = "dry-run" + elif exists(f"{code_prefix}/run_shard.py"): + actions["code_upload"] = "already present" + else: + api.upload_folder(repo_id=output_repo, repo_type="dataset", folder_path=str(code_dir), path_in_repo=code_prefix, + ignore_patterns=CODE_IGNORE, commit_message=f"code {ref}") + api.upload_file(repo_id=output_repo, repo_type="dataset", path_or_fileobj=json.dumps(manifest, ensure_ascii=False, indent=2).encode("utf-8"), + path_in_repo=f"code/{ref}/MANIFEST.json", commit_message=f"code manifest {ref}") + actions["code_upload"] = "uploaded" + lid_model = ut1_cache_dir.parent.parent / "models" / "lid.176.ftz" + if dry_run: + actions["lid_model_upload"] = "dry-run" + elif exists("models/lid.176.ftz"): + actions["lid_model_upload"] = "already present" + elif lid_model.exists(): + api.upload_file(repo_id=output_repo, repo_type="dataset", path_or_fileobj=str(lid_model), path_in_repo="models/lid.176.ftz", + commit_message="fastText lid.176 model (CC BY-SA 3.0)") + actions["lid_model_upload"] = "uploaded" + else: + actions["lid_model_upload"] = f"missing: {lid_model}" + if not (ut1_cache_dir / "manifest.json").exists(): + raise FileNotFoundError(f"UT1 キャッシュがありません: {ut1_cache_dir}(domain_blocklist.py fetch を先に実行)") + if dry_run: + actions["blocklist_upload"] = "dry-run" + elif exists("blocklists/ut1/manifest.json"): + actions["blocklist_upload"] = "already present" + else: + api.upload_folder(repo_id=output_repo, repo_type="dataset", folder_path=str(ut1_cache_dir), path_in_repo="blocklists/ut1", + commit_message="UT1 blocklists snapshot") + actions["blocklist_upload"] = "uploaded" + return actions + + +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) + parser.add_argument("--input-dataset", default=DEFAULT_INPUT) + parser.add_argument("--output-repo", default=DEFAULT_OUTPUT, help="非公開で作成される出力データセット") + parser.add_argument("--dirs", default="0-18", help="例: 0-18, 0,1,2") + parser.add_argument("--flavor", default=DEFAULT_FLAVOR) + parser.add_argument("--timeout", default=DEFAULT_TIMEOUT, help="例: 6h, 90m") + parser.add_argument("--image", default=DEFAULT_IMAGE) + parser.add_argument("--namespace", default=None, help="課金先。既定は出力リポジトリの所有者") + parser.add_argument("--workers", type=int, default=None, help="既定はジョブ内の CPU_CORES - 1") + parser.add_argument("--upload-batch", type=int, default=5) + parser.add_argument("--limit-shards", type=int, default=None, help="各ディレクトリの先頭N件だけ(試運転用)") + 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("--code-dir", type=Path, default=source_dir) + parser.add_argument("--ut1-cache-dir", type=Path, default=project_root / "data" / "blocklists" / "ut1") + parser.add_argument("--stage", choices=("full", "noise", "report", "guard", "quality"), default="full", + help="full: 有害→PII(入力データセットをマウント)。noise: 第2パス(出力データセットをマウントしてノイズ除去)。report: 品質報告(項目22・25〜29、1ジョブ)。guard: 第3パス(Qwen3Guard、GPU)。quality: 第4パス(低品質・除外ジャンルの削除、CPU)") + parser.add_argument("--previous-low-quality-rate", type=float, default=None, help="report: 前回レビューの低品質比率(0〜1)") + parser.add_argument("--exclude-genres", default="", help="report: 除外を決めたジャンル(記録用)") + parser.add_argument("--report-with-guard", action="store_true", help="report: 第3パス(guard)の削除を反映して集計する") + parser.add_argument("--guard-prefix", default="outputs_v3", help="guard: 第3パス出力の接頭辞") + parser.add_argument("--guard-model", default="Qwen/Qwen3Guard-Gen-0.6B") + parser.add_argument("--guard-max-chars", type=int, default=2000, help="guard: 分類器に渡す本文の先頭文字数") + parser.add_argument("--guard-min-terms", type=int, default=1, help="guard: 候補とする辞書の異なり語数") + parser.add_argument("--guard-chunk-size", type=int, default=512) + parser.add_argument("--guard-delete-categories", default="", help="guard: 削除する Unsafe カテゴリ(既定は run_guard_pass.py の既定)") + parser.add_argument("--quality-prefix", default="outputs_v4", help="quality: 第4パス出力の接頭辞") + parser.add_argument("--quality-exclude-genres", default="ec_product,affiliate", help="quality: 削除するジャンル(カンマ区切り)") + parser.add_argument("--quality-keep-low-quality", action="store_true", help="quality: 低品質フラグでは削除しない") + parser.add_argument("--quality-low-quality-flags", default="", help="quality: 削除に使う低品質フラグを限定(カンマ区切り、既定は全フラグ)") + parser.add_argument("--quality-tokenizer", default="o200k_harmony", help="quality: トークン数を数える tiktoken エンコーディング(空なら数えない)") + parser.add_argument("--split", type=int, default=1, help="guard / quality: ディレクトリごとに N ジョブへ分割") + parser.add_argument("--input-prefix", default="outputs", help="noise: 第1パス出力の接頭辞") + parser.add_argument("--noise-prefix", default="outputs_v2", help="noise: 第2パス出力の接頭辞") + parser.add_argument("--min-chars", type=int, default=200) + parser.add_argument("--max-chars", type=int, default=100_000) + parser.add_argument("--newline-policy", choices=("join", "delete", "keep"), default="join") + parser.add_argument("--tokenizer", default=None) + parser.add_argument("--min-tokens", type=int, default=None) + parser.add_argument("--max-tokens", type=int, default=None) + parser.add_argument("--dry-run", action="store_true", help="ジョブ定義とスクリプトを表示するだけで起動しない") + parser.add_argument("--wait", action="store_true", help="全ジョブの終了を待つ") + args = parser.parse_args(argv) + + token = os.environ.get("HF_TOKEN") + if not token and not args.dry_run: + raise SystemExit("HF_TOKEN が未設定です(uv run --env-file .env ...)") + dirs = parse_dirs(args.dirs) + ref = code_ref(args.code_dir) + namespace = args.namespace or args.output_repo.split("/")[0] + + from huggingface_hub import HfApi, Volume + + api = HfApi(token=token) + if not args.dry_run: + api.create_repo(args.output_repo, repo_type="dataset", private=True, exist_ok=True) + if args.stage == "noise" and not args.dry_run: + # 第1パスの出力が揃っていることを確認する(ボリュームは起動時点のスナップショット) + for dir_index in dirs: + marker = f"{args.input_prefix}/common_crawl_{dir_index}" + try: + entries = list(api.list_repo_tree(args.output_repo, path_in_repo=marker, repo_type="dataset", recursive=False)) + except Exception: # noqa: BLE001 + entries = [] + if not entries: + raise SystemExit(f"第1パスの出力がありません: {marker}/") + actions = upload_code_and_blocklists(api, args.output_repo, args.code_dir, ref, args.ut1_cache_dir, args.dry_run) + print(json.dumps({"event": "prepared", **actions, "output_repo": args.output_repo, "private": True}, ensure_ascii=False), flush=True) + + launched: list[dict[str, Any]] = [] + if args.stage == "report": + dirs = [-1] # 報告は1ジョブ + if args.stage == "guard": + if args.flavor == DEFAULT_FLAVOR: + args.flavor = "l4x1" + if args.image == DEFAULT_IMAGE: + args.image = "vllm/vllm-openai:latest" + for dir_index in dirs: + marker = f"{args.noise_prefix}/common_crawl_{dir_index}" + if not args.dry_run: + try: + entries = list(api.list_repo_tree(args.output_repo, path_in_repo=marker, repo_type="dataset", recursive=False)) + except Exception: # noqa: BLE001 + entries = [] + if not entries: + raise SystemExit(f"第2パスの出力がありません: {marker}/") + if args.stage == "quality" and not args.dry_run: + for dir_index in dirs: + marker = f"{args.guard_prefix}/common_crawl_{dir_index}" + try: + entries = list(api.list_repo_tree(args.output_repo, path_in_repo=marker, repo_type="dataset", recursive=False)) + except Exception: # noqa: BLE001 + entries = [] + if not entries: + raise SystemExit(f"第3パスの出力がありません: {marker}/") + targets = [(d, k) for d in dirs for k in range(max(1, args.split) if args.stage in ("guard", "quality") else 1)] + for dir_index, split_index in targets: + if args.stage == "guard": + script = build_guard_job_script(args.output_repo, ref, dir_index, split_index, args) + volume_source, mount_path = None, None + job_name = f"abeja-cc-ja-guard-{dir_index}" + (f"-{split_index}of{args.split}" if args.split > 1 else "") + elif args.stage == "quality": + script = build_quality_job_script(args.output_repo, ref, dir_index, split_index, args) + volume_source, mount_path = None, None + job_name = f"abeja-cc-ja-quality-{dir_index}" + (f"-{split_index}of{args.split}" if args.split > 1 else "") + elif args.stage == "report": + script = build_report_job_script(args.output_repo, ref, args) + volume_source, mount_path, job_name = args.output_repo, "/cleaned", "abeja-cc-ja-quality-report" + elif args.stage == "noise": + script = build_noise_job_script(args.output_repo, ref, dir_index, args) + volume_source, mount_path, job_name = args.output_repo, "/cleaned", f"abeja-cc-ja-noise-{dir_index}" + else: + script = build_job_script(args.output_repo, ref, dir_index, args) + volume_source, mount_path, job_name = args.input_dataset, "/data", f"abeja-cc-ja-clean-{dir_index}" + spec = { + "name": job_name, + "image": args.image, + "flavor": args.flavor, + "timeout": args.timeout, + "namespace": namespace, + "volumes": ([{"type": "dataset", "source": volume_source, "mount_path": mount_path, "read_only": True}] if volume_source else []), + "secrets": ["HF_TOKEN"], + "labels": {"pipeline": "abeja-cc-ja-cleansing", "stage": args.stage, "dir": f"common_crawl_{dir_index}" if dir_index >= 0 else "all", "code_ref": ref}, + } + if args.dry_run: + print(json.dumps({"event": "dry-run", "job": spec}, ensure_ascii=False)) + print("--- script ---\n" + script) + continue + job = api.run_job( + image=args.image, + command=["bash", "-lc", script], + flavor=args.flavor, + timeout=args.timeout, + secrets={"HF_TOKEN": token}, + env={"PIPELINE_DIR": f"common_crawl_{dir_index}"}, + volumes=([Volume(type="dataset", source=volume_source, mount_path=mount_path, read_only=True)] if volume_source else []), + namespace=namespace, + name=spec["name"], + labels=spec["labels"], + ) + launched.append({"dir": dir_index, "job_id": job.id, "url": job.url}) + print(json.dumps({"event": "launched", "dir": dir_index, "job_id": job.id, "url": job.url}), flush=True) + if launched: + record = project_root / "data" / f"hf_jobs_{datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')}.json" + record.parent.mkdir(parents=True, exist_ok=True) + record.write_text(json.dumps({"ref": ref, "stage": args.stage, "output_repo": args.output_repo, "jobs": launched, "flavor": args.flavor, "timeout": args.timeout}, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + print(json.dumps({"event": "recorded", "file": str(record)}), flush=True) + if args.wait and launched: + finished = api.wait_for_job(job_id=[j["job_id"] for j in launched], namespace=namespace) + for info in (finished if isinstance(finished, list) else [finished]): + print(json.dumps({"event": "finished", "job_id": info.id, "stage": info.status.stage, "message": info.status.message}), flush=True) + + +if __name__ == "__main__": + main() diff --git a/code/3c1a8da-dirty-0c72d075/src/main_pii.py b/code/3c1a8da-dirty-0c72d075/src/main_pii.py new file mode 100644 index 0000000000000000000000000000000000000000..fc19a407750d98c24081c4ae7001fb29f39aaa6c --- /dev/null +++ b/code/3c1a8da-dirty-0c72d075/src/main_pii.py @@ -0,0 +1,63 @@ +"""PII置換フィルタの実行入口と既定コンフィグ。""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +from filter_pii import run_filter + + +PROJECT_ROOT = Path(__file__).resolve().parents[1] +DEFAULT_CONFIG = { + "input": PROJECT_ROOT / "data" / "raw" / "common_crawl_0_filtered_0001.parquet", + "output_root": PROJECT_ROOT / "data" / "check_ver2" / "pii_0001_replaced_final", + "batch_size": 2048, +} + + +def main(argv: list[str] | None = None) -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--input", type=Path, default=DEFAULT_CONFIG["input"]) + parser.add_argument("--output-root", type=Path, default=DEFAULT_CONFIG["output_root"]) + parser.add_argument("--batch-size", type=int, default=DEFAULT_CONFIG["batch_size"]) + parser.add_argument("--start-row", type=int, default=0) + parser.add_argument("--max-rows", type=int, default=None) + parser.add_argument("--policy-approver", default=None, help="処理方針(置換)の承認者名。summary.json の pii_policy に記録される。") + parser.add_argument("--policy-approved-on", default=None, help="承認日(YYYY-MM-DD)。") + parser.add_argument("--policy-note", default=None, help="方針の補足(任意)。") + parser.add_argument("--mask-honorific-names", action="store_true", help="「○○さん/氏/様」だけの姓名も置換する。") + parser.add_argument("--mask-bare-names", action="store_true", help="文脈の無い姓名も置換する。") + parser.add_argument("--no-affiliation-titles", dest="affiliation_titles", action="store_false", help="役職語(代表取締役、教授等)だけの文脈を所属とみなさない(組織名のみに狭める)。") + args = parser.parse_args(argv) + if not args.input.exists(): + raise FileNotFoundError(args.input) + summary = run_filter( + input_path=args.input, + output_root=args.output_root, + batch_size=args.batch_size, + start_row=args.start_row, + max_rows=args.max_rows, + policy_approver=args.policy_approver, + policy_approved_on=args.policy_approved_on, + policy_note=args.policy_note, + mask_honorific_names=args.mask_honorific_names, + mask_bare_names=args.mask_bare_names, + affiliation_titles=args.affiliation_titles, + ) + print(json.dumps({ + "row_range": summary["row_range"], + "total_records_scanned": summary["total_records_scanned"], + "records_with_replacement": summary["records_with_replacement"], + "records_changed": summary["records_changed"], + "records_unchanged": summary["records_unchanged"], + "total_replacements": summary["total_replacements"], + "by_type": {k: v["replacement_count"] for k, v in summary["by_type"].items()}, + "pii_policy_status": summary["pii_policy"]["status"], + }, ensure_ascii=False)) + + +if __name__ == "__main__": + main() + diff --git a/code/3c1a8da-dirty-0c72d075/src/main_toxic.py b/code/3c1a8da-dirty-0c72d075/src/main_toxic.py new file mode 100644 index 0000000000000000000000000000000000000000..9cc35507cfb19f3fbbb29ef26ea4dd01107a8a4d --- /dev/null +++ b/code/3c1a8da-dirty-0c72d075/src/main_toxic.py @@ -0,0 +1,86 @@ +"""有害コンテンツフィルタの実行入口と既定コンフィグ。""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +from cooccurrence import CooccurrenceDetector, load_rules +from domain_blocklist import DomainBlocklist +from filter_toxic import MODE_CONFIGS, run_toxic_filters + + +PROJECT_ROOT = Path(__file__).resolve().parents[1] +SOURCE_DIR = Path(__file__).resolve().parent +DEFAULT_CONFIG = { + "input": PROJECT_ROOT / "data" / "raw" / "common_crawl_0_filtered_0001.parquet", + "output_root": PROJECT_ROOT / "data" / "check_ver2" / "toxic_0001", + "reference_dir": SOURCE_DIR / "wordlists" / "reference", + "additional_dir": SOURCE_DIR / "wordlists", + "exclude_dir": SOURCE_DIR / "wordlists" / "exclude", + "blocklist_dir": SOURCE_DIR / "blocklists", + "blocklist_cache_dir": PROJECT_ROOT / "data" / "blocklists" / "ut1", + "cooccurrence_rules": SOURCE_DIR / "wordlists" / "cooccurrence" / "rules.json", + "batch_size": 2048, + "modes": tuple(MODE_CONFIGS), +} + + +def main(argv: list[str] | None = None) -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--input", type=Path, default=DEFAULT_CONFIG["input"]) + parser.add_argument("--output-root", type=Path, default=DEFAULT_CONFIG["output_root"]) + parser.add_argument("--reference-dir", type=Path, default=DEFAULT_CONFIG["reference_dir"]) + parser.add_argument("--additional-dir", type=Path, default=DEFAULT_CONFIG["additional_dir"]) + parser.add_argument("--exclude-dir", type=Path, default=DEFAULT_CONFIG["exclude_dir"], + help="カテゴリ別除外リスト(ja__exclude.txt)のディレクトリ。") + parser.add_argument("--blocklist-dir", type=Path, default=DEFAULT_CONFIG["blocklist_dir"], + help="ドメインブロックリストの設定・自前リストのディレクトリ。") + parser.add_argument("--blocklist-cache-dir", type=Path, default=DEFAULT_CONFIG["blocklist_cache_dir"], + help="UT1リストの取得先(domain_blocklist.py fetch --dest で作成)。") + parser.add_argument("--no-blocklist", action="store_true", help="ドメインブロックリスト判定を無効にする。") + parser.add_argument("--cooccurrence-rules", type=Path, default=DEFAULT_CONFIG["cooccurrence_rules"], + help="近接共起規則の定義JSON。") + parser.add_argument("--no-cooccurrence", action="store_true", help="近接共起規則を無効にする。") + parser.add_argument("--batch-size", type=int, default=DEFAULT_CONFIG["batch_size"]) + parser.add_argument("--mode", choices=("all", *MODE_CONFIGS), action="append", default=None, + help="実行モード。省略時は同一カテゴリ3語以上条件を実行。") + parser.add_argument("--start-row", type=int, default=0) + parser.add_argument("--max-rows", type=int, default=None) + args = parser.parse_args(argv) + for path in (args.input, args.reference_dir, args.additional_dir, args.exclude_dir): + if not path.exists(): + raise FileNotFoundError(path) + modes = list(MODE_CONFIGS) if not args.mode or "all" in args.mode else args.mode + blocklist = None if args.no_blocklist else DomainBlocklist.load(args.blocklist_dir, args.blocklist_cache_dir) + cooccurrence = None if args.no_cooccurrence else CooccurrenceDetector(load_rules(args.cooccurrence_rules)) + summary = run_toxic_filters( + input_path=args.input, + output_root=args.output_root, + reference_dir=args.reference_dir, + additional_dir=args.additional_dir, + batch_size=args.batch_size, + modes=modes, + start_row=args.start_row, + max_rows=args.max_rows, + exclude_dir=args.exclude_dir, + blocklist=blocklist, + cooccurrence=cooccurrence, + ) + print(json.dumps({ + "row_range": summary["row_range"], + "modes": { + mode: { + "total_records_scanned": values["total_records_scanned"], + "records_deleted": values["records_deleted"], + "records_retained": values["records_retained"], + "records_deleted_by_reason": values["records_deleted_by_reason"], + } + for mode, values in summary["modes"].items() + }, + }, ensure_ascii=False)) + + +if __name__ == "__main__": + main() diff --git a/code/3c1a8da-dirty-0c72d075/src/noise/boilerplate_lines.txt b/code/3c1a8da-dirty-0c72d075/src/noise/boilerplate_lines.txt new file mode 100644 index 0000000000000000000000000000000000000000..5dda4eda9dd1108cc5c27cf9a3f813123e35d75a --- /dev/null +++ b/code/3c1a8da-dirty-0c72d075/src/noise/boilerplate_lines.txt @@ -0,0 +1,17 @@ +# 項目18: boilerplate 行。1行1正規表現。行全体に対して search し、該当行を削除する。 +# --- Cookie 同意 --- +cookie(?:s)?(?:の使用|を使用|に同意|ポリシー|の利用|を利用)|クッキー(?:の使用|を使用|に同意|ポリシー|の利用)|(?:accept|allow|use) (?:all )?cookies +# --- 関連記事・おすすめ --- +^\s*(?:【?関連記事】?|関連記事(?:一覧)?|こちらの記事もおすすめ|あわせて読みたい|合わせて読みたい|人気記事(?:ランキング)?|新着記事|おすすめ記事|注目記事|最新記事)\s*[::]?\s*$ +# --- フッター --- +all rights reserved|copyright\s*(?:©|\(c\)|\d{4})|©\s*\d{4}|^\s*(?:プライバシーポリシー|個人情報保護方針|利用規約|サイトマップ|特定商取引法に基づく表記|免責事項|お問い合わせ|会社概要)\s*(?:[||//・]\s*(?:プライバシーポリシー|個人情報保護方針|利用規約|サイトマップ|特定商取引法に基づく表記|免責事項|お問い合わせ|会社概要)\s*)*$ +# --- コメント欄 --- +^\s*(?:コメント(?:を残す|を書く|を投稿|一覧|する|はまだありません)|コメント\s*[\((]\d+[\))]|返信する|返信を残す|シェアする|ツイート|いいね!?\s*\d*|Leave a (?:Reply|Comment)|Post Comment|No comments)\s*$ +^\s*(?:名前|メールアドレス|ウェブサイト|コメント)\s*[::]?\s*(?:\*|(必須)|\(必須\))?\s*$ +# --- 広告 --- +^\s*(?:スポンサー(?:ド)?リンク|スポンサー広告|\[?PR\]?|【PR】|広告|AD|advertisement)\s*$ +# --- ナビゲーション --- +^\s*(?:ホーム|HOME|トップ(?:ページ)?)\s*[>>»›]|^\s*(?:前の記事|次の記事|前へ|次へ|« Previous|Next »|カテゴリー?一覧|タグ一覧|アーカイブ|月別アーカイブ|カレンダー|検索|メニュー|MENU|ログイン|新規登録|会員登録|マイページ|カート|ページ(?:の)?トップへ|ページ上部へ|TOPへ戻る)\s*$ +^\s*(?:Posted by|投稿者|投稿日|カテゴリー?|タグ|更新日|公開日)\s*[::]?\s*\S{0,30}\s*$ +# --- SNS シェア --- +^\s*(?:facebook|twitter|x|line|はてなブックマーク|hatena|pocket|pinterest|instagram|youtube)\s*(?:[||//・]\s*(?:facebook|twitter|x|line|はてなブックマーク|hatena|pocket|pinterest|instagram|youtube)\s*)*$ diff --git a/code/3c1a8da-dirty-0c72d075/src/noise/llm_phrases.txt b/code/3c1a8da-dirty-0c72d075/src/noise/llm_phrases.txt new file mode 100644 index 0000000000000000000000000000000000000000..be97001dc8d83126dc4d555173c7cb44b91b8d5a --- /dev/null +++ b/code/3c1a8da-dirty-0c72d075/src/noise/llm_phrases.txt @@ -0,0 +1,13 @@ +# 項目14: LLM 由来の回答拒否文・アシスタント口調。1行1正規表現(大文字小文字無視)。該当文書は削除。 +as an? (?:ai|artificial intelligence)(?: language)? model +as a large language model +i'?m (?:sorry|afraid),? but (?:i|as an ai) +i (?:cannot|can'?t|am unable to) (?:help|assist|provide|fulfill|comply|generate|answer) (?:with )?(?:that|this|your request) +i do not have (?:personal )?(?:opinions|feelings|access to real-time) +openai'?s? (?:content|usage|use) polic(?:y|ies) +私は\s?ai(?:言語モデル|アシスタント|チャットボット)?(?:なので|です(?:ので|から)?|として|であり|ですが) +ai言語モデル(?:として|なので|ですので|である) +(?:大規模)?言語モデルとして(?:は|、|の) +申し訳(?:ありません|ございません)が、?(?:私は)?ai(?:言語モデル|アシスタント)?(?:なので|として|には) +私はchatgpt|chatgptとして|chatgptなので +その(?:ご)?(?:質問|リクエスト)には(?:お)?答え(?:する)?ことができません diff --git a/code/3c1a8da-dirty-0c72d075/src/noise/special_tokens.txt b/code/3c1a8da-dirty-0c72d075/src/noise/special_tokens.txt new file mode 100644 index 0000000000000000000000000000000000000000..d0e6647ecba46ff6988c944ef25765f3a1d10741 --- /dev/null +++ b/code/3c1a8da-dirty-0c72d075/src/noise/special_tokens.txt @@ -0,0 +1,11 @@ +# 項目15: 他サービスの特殊トークン・チャットテンプレート断片。1行1正規表現(複数行モード)。該当文書は削除。 +<\|endoftext\|> +<\|im_start\|>|<\|im_end\|> +\[INST\]|\[/INST\] +<>|<> +<\|(?:user|assistant|system)\|> +<\|begin_of_text\|>|<\|eot_id\|>|<\|start_header_id\|> +||| +\s*$ +^### (?:Instruction|Response|Input|System): +^(?:Human|Assistant):\s diff --git a/code/3c1a8da-dirty-0c72d075/src/pii_detector.py b/code/3c1a8da-dirty-0c72d075/src/pii_detector.py new file mode 100644 index 0000000000000000000000000000000000000000..25b0e78963d327a7cef19a2a689b03c6636e8653 --- /dev/null +++ b/code/3c1a8da-dirty-0c72d075/src/pii_detector.py @@ -0,0 +1,597 @@ +"""日本語Web文書向けのPII検出・置換器。 + +``PII_detect.md`` の検出方針を踏まえ、正規表現・チェックデジットに加えて +SudachiPy(形態素解析、人名辞書付き)で自然文中の氏名を検出する。学習済み +NER(GLiNER-ja)は全件処理には重いため ``pii_residual_check.py`` の残存確認に +使う。公開用データでは、検出した値を削除するのではなく、種別ごとの +プレースホルダーへ置換する。対象は次の7種類に限定する。 + +* 電話番号 +* メールアドレス +* 番地レベルの住所 +* 個人名と所属の組合せ +* マイナンバー +* クレジットカード番号 +* 銀行口座番号 + +郵便番号だけ、IPアドレス、秘密情報、生年月日などは対象外とする。個人名 +だけは「氏名:」等のラベル文脈に限って置換する。番号系(マイナンバー、 +カード、口座)はURLでは検出せず、本文でもラベル文脈か区切り書式を必須にする +(無作為な数字列の1割はチェックデジットを通るため)。将来 fuseji、GLiNER-ja、GiNZA 等を追加する場合は +``PIIDetector`` の結果へ検出結果を追加できる。 +""" + +from __future__ import annotations + +import re +import unicodedata +from dataclasses import dataclass +from typing import Any, Iterable + + +PII_LABELS_JA = { + "email": "メールアドレス", + "phone": "電話番号", + "address": "番地レベルの住所", + "person_affiliation": "個人名+所属", + "person_name": "個人名", + "my_number": "マイナンバー", + "credit_card": "クレジットカード番号", + "bank_account": "銀行口座番号", +} + +PLACEHOLDERS = { + "email": "", + "phone": "", + "address": "
", + "person_affiliation": "", + "person_name": "", + "my_number": "", + "credit_card": "", + "bank_account": "", +} + +TARGET_PII_TYPES = tuple(PII_LABELS_JA) + + +@dataclass(frozen=True) +class PIIMatch: + """検出されたPIIの位置と監査用メタデータ。位置はNFKC後の文字列基準。""" + + pii_type: str + field: str + start: int + end: int + value: str + method: str + confidence: str = "high" + + @property + def label_ja(self) -> str: + return PII_LABELS_JA.get(self.pii_type, self.pii_type) + + @property + def masked_value(self) -> str: + return mask_value(self.pii_type, self.value) + + @property + def placeholder(self) -> str: + return PLACEHOLDERS.get(self.pii_type, "") + + def to_dict(self) -> dict[str, Any]: + return { + "pii_type": self.pii_type, + "pii_type_ja": self.label_ja, + "field": self.field, + "start": self.start, + "end": self.end, + "matched_value_masked": self.masked_value, + "method": self.method, + "confidence": self.confidence, + "placeholder": self.placeholder, + } + + +def normalize_text(value: Any) -> str: + """全角・半角差を吸収して照合する。""" + + if value is None: + return "" + return unicodedata.normalize("NFKC", str(value)) + + +def mask_value(pii_type: str, value: str) -> str: + """監査JSONにPIIそのものを再掲しないためのマスキング。""" + + if not value: + return "" + if pii_type == "email" and "@" in value: + local, domain = value.split("@", 1) + masked_local = local[0] + "*" * max(1, len(local) - 2) + local[-1:] + return f"{masked_local}@{domain}" + if pii_type in {"phone", "my_number", "credit_card", "bank_account"}: + chars = list(value) + positions = [i for i, char in enumerate(chars) if char.isalnum()] + keep = 4 + for index in positions[:-keep]: + chars[index] = "*" + return "".join(chars) + if pii_type == "address": + return value[:3] + "***" + if pii_type == "person_affiliation": + return "***" + return "***" + + +def is_valid_luhn(value: str) -> bool: + digits = [int(char) for char in value if char.isdigit()] + if len(digits) < 13 or len(digits) > 19: + return False + checksum = 0 + parity = len(digits) % 2 + for index, digit in enumerate(digits): + if index % 2 == parity: + digit *= 2 + if digit > 9: + digit -= 9 + checksum += digit + return checksum % 10 == 0 + + +def is_valid_mynumber(value: str) -> bool: + """12桁の個人番号のチェックデジットを検証する。""" + + digits = [int(char) for char in value if char.isdigit()] + if len(digits) != 12: + return False + # 左から11桁に対して、右から 2,3,4,5,6,7 を繰り返す。 + weights = [2, 3, 4, 5, 6, 7, 2, 3, 4, 5, 6] + total = sum(digit * weight for digit, weight in zip(reversed(digits[:11]), weights)) + check_digit = (11 - (total % 11)) % 10 + return check_digit == digits[-1] + + +EMAIL_RE = re.compile( + r"(?(?:\+81[ \t-]?)?0?\d{1,4}(?:[ \t]?-[ \t]?|[ \t])\d{1,4}(?:[ \t]?-[ \t]?|[ \t])\d{3,4})(?!\d))" +) +PHONE_MOBILE_RE = re.compile(r"(?\+?\d[\d\s().-]{8,18}\d))", + re.IGNORECASE, +) +# 12桁(4-4-4区切りも可)。チェックデジットに加えて、ラベル文脈を必須にする。 +# 無作為な12桁の1割はチェックデジットを通るため、URL中のIDや注文番号を誤検出しないため。 +MY_NUMBER_RE = re.compile(r"(?-802」のような取り残しを防ぐ)。 +# 番地: 算用数字と漢数字の両方、「1-2-3」「1丁目2番3号」「一丁目二番三号」「1丁目2-3」「1ー2ー3」を許容 +_NUM = r"[0-9一二三四五六七八九十〇零]+" +# 区切り記号(-、-、‐、ー)の前後には OCR・Web抽出由来の空白を1つまで許す。 +_SEP = r"\s?[--‐ー]\s?" +_ADDRESS_BLOCK = ( + rf"(?:{_NUM}\s?丁目\s?{_NUM}(?:\s?番(?:地)?\s?(?:{_NUM}\s?号?)?|{_SEP}{_NUM}(?:{_SEP}{_NUM})?)" + rf"|{_NUM}(?:{_SEP}{_NUM}){{1,3}}(?:番地?)?" + rf"|{_NUM}\s?番地?(?:\s?{_NUM}\s?号)?)" +) +_ADDRESS_TAIL = ( + r"(?:\s*[^\s,、。\n()()]{0,20}?(?:ビル|マンション|ハイツ|コーポ|レジデンス|アパート|タワー|ハウス|荘|寮|号館)[^\s,、。\n()()]{0,10})?" + r"(?:\s*\d{1,4}\s*(?:号室|号|[Ff]|階))?" +) +# 都道府県から始まる住所。改行・空白の混入(Web抽出やOCR)を許すため、区切りは句読点のみとする。 +ADDRESS_RE = re.compile( + r"(?P(?:北海道|東京都|大阪府|京都府|[一-龥々]{2,3}県)[^,、。]{1,60}?(?:市|区|町|村)[^,、。]{0,35}?" + _ADDRESS_BLOCK + _ADDRESS_TAIL + r")" +) +# 都道府県が省かれた「福岡市博多区博多駅前1-2-3」「宇都宮市江野町1-15」。市・区の後に町名相当を1文字以上要求する。 +ADDRESS_CITY_RE = re.compile( + r"(?P(?(?:北海道|東京都|大阪府|京都府|[一-龥々]{2,3}県|[一-龥々ぁ-ゖァ-ヶー]{1,6}(?:市|区|郡))[^。,、]{1,80}?" + _ADDRESS_BLOCK + _ADDRESS_TAIL + r")" +) + +# 氏名: 漢字2〜6字、または漢字1〜3字+かな2〜6字(佐藤ゆかり)。「皆さん」のような1字+さんは拾わない。 +_NAME = r"(?:[一-龥々]{2,6}|[一-龥々]{1,3}\s?[ぁ-ゖァ-ヶー]{2,6})" +# 所属: 法人格で始まる名称、または組織を示す語尾で終わる名称(20字以内)。任意で部署。 +_ORG_PREFIX = r"(?:株式会社|有限会社|合同会社|合資会社|一般社団法人|一般財団法人|公益社団法人|公益財団法人|[Nn][Pp][Oo]法人|学校法人|医療法人|社会福祉法人|独立行政法人|国立研究開発法人)" +_ORG_SUFFIX = r"(?:株式会社|有限会社|合同会社|会社|大学院|大学|高等学校|高校|中学校|小学校|専門学校|病院|クリニック|医院|省|庁|県庁|市役所|区役所|町役場|村役場|銀行|信用金庫|研究所|研究センター|協会|連盟|組合|法律事務所|事務所|事務局|財団|法人|商工会議所|観光局|放送局|新聞社|出版社)" +_ORG = rf"(?:{_ORG_PREFIX}[^\s。、,,()()]{{1,20}}|[^\s。、,,()()のがはをにでと]{{1,20}}?{_ORG_SUFFIX})" +_ORG_RE = re.compile(_ORG) +_DEPT = r"(?:\s*[^\s。、,,()()]{0,15}?(?:部|課|室|科|係|チーム|支店|支社|営業所|研究室))?" +# 所属の後ろに続く役職(「株式会社ABC 代表」「○○会 会員」)も置換範囲に含める。 +_TITLE_OPT = r"(?:\s*[^\s。、,,()()の]{0,8}?(?:長|社長|部長|課長|主任|教授|准教授|講師|代表|取締役|[Cc][Ee][Oo]|[Cc][Tt][Oo]|マネージャー|リーダー|担当|研究員|弁護士|職員|会員|理事|社員|員))?" +_TITLE = r"(?:[^\s。、,,()()の]{0,8}?(?:長|社長|部長|課長|主任|教授|准教授|講師|代表|取締役|[Cc][Ee][Oo]|[Cc][Tt][Oo]|マネージャー|リーダー|担当|研究員|弁護士))" +# 「氏名:山田太郎(株式会社ABC)」「担当者:山田太郎、株式会社ABC 営業部」 +NAME_AFFILIATION_LABEL_RE = re.compile( + r"(?:氏名|お名前|担当者|代表者|名義人?)\s*[::]\s*" + rf"(?P(?P{_NAME})\s*(?:[((、,]|所属\s*[::])\s*(?P{_ORG}{_DEPT}{_TITLE_OPT})[))]?)" +) +# 「山田太郎さん、株式会社ABC」「山田太郎氏(株式会社ABC 営業部)」 +NAME_AFFILIATION_SUFFIX_RE = re.compile( + rf"(?P(?P{_NAME})(?:さん|氏|様|先生)[、,\s((]+(?P{_ORG}{_DEPT}{_TITLE_OPT})[))]?)" +) +# 「株式会社ABC 営業部 部長 山田太郎さん」「○○大学教授・山田太郎氏」(所属→役職→氏名の順)。 +# 役職か「・」区切りのどちらかと、敬称を必須にする。「会社の同僚さん」のような役割語を氏名にしないため。 +AFFILIATION_NAME_RE = re.compile( + rf"(?P(?P{_ORG}{_DEPT})\s*(?:(?:の)?\s*{_TITLE}\s*(?:・|の|\s)?|・)\s*(?P{_NAME})(?:さん|氏|様|先生))" +) +# 個人名だけ(ラベル文脈)。かな名も許可し、フォームの定型語は除外する。 +_NAME_TOKEN = r"[一-龥々ぁ-ゖァ-ヶー]{1,8}" +NAME_CONTEXT_RE = re.compile( + r"(?:氏名|お名前|名前|担当者|代表者|名義人?)\s*[::]\s*" + rf"(?P{_NAME_TOKEN}(?:\s*{_NAME_TOKEN})?)" +) +NAME_STOPWORDS = {"必須", "任意", "未定", "なし", "不明", "非公開", "匿名", "ニックネーム", "ハンドルネーム", "例", "未入力", "空欄", "入力"} +# 欧文氏名は署名(by / Author / 執筆者)か敬称(Mr. / Dr.)の文脈に限る。単独の「John Smith」は地名・商品名と区別できないため対象外。 +LATIN_NAME_RE = re.compile( + r"(?:(?i:\bby|\bauthor|\bwritten by|\bphoto by|\btext by|\bposted by)|執筆者|著者|文責|撮影|取材|記者|翻訳|監修)\s*[::]?\s*" + r"(?P(?:(?:Mr|Ms|Mrs|Dr|Prof)\.?\s+)?[A-Z][a-z]+(?:\s[A-Z]\.?)?\s[A-Z][a-z]+(?:\s[A-Z][a-z]+)?)" + r"|(?P(?:Mr|Ms|Mrs|Dr|Prof)\.\s+[A-Z][a-z]+(?:\s[A-Z][a-z]+)?)" +) +BANK_CONTEXT_RE = re.compile( + r"(?:口座番号|口座|振込先|銀行口座)\D{0,20}(?P\d{7})(?!\d)" +) +# URL では数字列がIDであることが多く、番号系の検出は行わない(メール・電話のみ)。 +URL_EXCLUDED_TYPES = frozenset({"my_number", "credit_card", "bank_account"}) + + +def _has_context(text: str, position: int, pattern: re.Pattern[str], window: int) -> bool: + """position の直前 window 文字以内に pattern があるか。""" + + return pattern.search(text, max(0, position - window), position) is not None + + +# --- 形態素解析による人名検出 ------------------------------------------------- +# SudachiPy(Apache-2.0)の辞書は姓・名を「名詞,固有名詞,人名,姓/名」として持つ。 +# 姓+名の連続、または敬称・役割ラベル付きの単独人名を候補にし、所属・役職の文脈が +# 近くにあれば「個人名+所属」、敬称・役割ラベルがあれば「個人名」として置換する。 +# 文脈のない裸の姓名(「尾田栄一郎はどんな人」)は既定では置換せず、件数だけ数える。 +HONORIFIC_AFTER_RE = re.compile(r"(?:さん|氏|様|先生|くん|君|ちゃん|さま)") +# 役割ラベル。1文字の語(文・絵・訳・作・画)は「名作」「原作」を拾わないよう、区切り文字か行頭の直後に限る。 +# 出演・司会は俳優・司会者(公人)を指すため含めない。 +ROLE_LABEL_BEFORE_RE = re.compile( + r"(?:(?:執筆者|執筆|著者|文責|記者|編集者|担当者?|講師|監修|取材|撮影|翻訳|写真|(?i:by))|(?:^|[\s、,::・/||((【\[])(?:文|絵|訳|作|画))\s*[::=]?\s*$", +) +TITLE_CONTEXT_RE = re.compile( + r"(?:代表取締役|取締役|社長|副社長|会長|副会長|理事長|理事|専務|常務|執行役員|部長|次長|課長|係長|主任|所長|院長|校長|園長|館長|局長|" + r"教授|准教授|助教|講師|研究員|主席|主幹|(?i:ceo|cto|coo|cfo)|マネージャー|ディレクター|プロデューサー|エンジニア|デザイナー|コンサルタント|" + r"アナリスト|弁護士|税理士|会計士|司法書士|行政書士|社労士|医師|看護師|薬剤師|" + r"代表|担当|職員|社員|スタッフ|広報|主宰|オーナー|店長|支配人|学長|総長|会員|委員長|委員)" + # 監督・選手・議員・市長・知事・大臣など公人を示す役職は含めない(公人名は学習データとして保持する)。 +) +NAME_CONTEXT_WINDOW = 25 +_SENTENCE_BREAK_RE = re.compile(r"[。!?!?\n]") + + +def _same_sentence_window(text: str, start: int, end: int, window: int) -> tuple[str, str]: + """氏名の前後 window 文字のうち、同じ文(句点・改行で区切られない範囲)だけを返す。""" + + before = text[max(0, start - window):start] + after = text[end:end + window] + breaks = list(_SENTENCE_BREAK_RE.finditer(before)) + if breaks: + before = before[breaks[-1].end():] + cut = _SENTENCE_BREAK_RE.search(after) + if cut: + after = after[:cut.start()] + return before, after + + +class SudachiNameFinder: + """本文から人名の範囲(姓+名の連続、または単独の姓・名)を返す。""" + + CHUNK_CHARS = 8000 # Sudachi の入力上限(49,149バイト)に収める + + def __init__(self) -> None: + from sudachipy import Dictionary, SplitMode + + self._tokenizer = Dictionary(dict="core").create() + self._mode = SplitMode.A + + def _chunks(self, text: str): + start = 0 + while start < len(text): + end = min(len(text), start + self.CHUNK_CHARS) + if end < len(text): + newline = text.rfind("\n", start + self.CHUNK_CHARS // 2, end) + if newline > 0: + end = newline + 1 + yield start, text[start:end] + start = end + + def find(self, text: str) -> list[tuple[int, int, str]]: + """(start, end, kind) を返す。kind は ``pair``(姓+名)か ``single``。""" + + spans: list[tuple[int, int, str]] = [] + for offset, piece in self._chunks(text): + run: list[tuple[int, int, str]] = [] # (start, end, 姓/名/一般) + + def flush() -> None: + if not run: + return + kinds = [kind for _, _, kind in run] + start, end = run[0][0], run[-1][1] + if "姓" in kinds and "名" in kinds and kinds.index("姓") < len(kinds) - 1: + spans.append((start, end, "pair")) + elif len(run) >= 2 and end - start >= 3: + spans.append((start, end, "pair")) + elif end - start >= 2: + spans.append((start, end, "single")) + run.clear() + + pending_connector = False + for morpheme in self._tokenizer.tokenize(piece, self._mode): + pos = morpheme.part_of_speech() + surface = morpheme.surface() + if pos[2] == "人名": + run.append((offset + morpheme.begin(), offset + morpheme.end(), pos[3])) + pending_connector = False + elif run and not pending_connector and (pos[0] == "空白" or surface in ("・", "・", "=", "=")): + # 「山田 太郎」「ジョン・スミス」の空白・中黒は1つだけ連結として扱う + pending_connector = True + else: + flush() + pending_connector = False + flush() + return spans + + +def _digits(value: str) -> str: + return "".join(char for char in value if char.isdigit()) + + +def _valid_phone(value: str) -> bool: + digits = _digits(value) + if value.startswith("+81"): + digits = "0" + digits[2:] + if len(digits) not in {10, 11} or not digits.startswith("0"): + return False + if digits.startswith(("070", "080", "090")): + return len(digits) == 11 + return digits[1] in "123456789" and len(digits) in {10, 11} + + +def _overlap(first: PIIMatch, second: PIIMatch) -> bool: + return first.start < second.end and second.start < first.end + + +def _select_non_overlapping(matches: Iterable[PIIMatch]) -> list[PIIMatch]: + """重なった候補は、長く信頼度の高い候補を優先して1回だけ置換する。""" + + confidence_rank = {"high": 2, "medium": 1, "low": 0} + ordered = sorted( + matches, + key=lambda item: ( + item.start, + -(item.end - item.start), + -confidence_rank.get(item.confidence, 0), + ), + ) + selected: list[PIIMatch] = [] + for candidate in ordered: + if any(_overlap(candidate, existing) for existing in selected): + continue + selected.append(candidate) + return sorted(selected, key=lambda item: (item.start, item.end, item.pii_type)) + + +class PIIDetector: + """URLと本文から指定7種類だけを検出し、プレースホルダーへ置換する。""" + + def __init__( + self, + include_url: bool = True, + use_sudachi: bool = True, + mask_honorific_names: bool = False, + mask_bare_names: bool = False, + name_context_window: int = NAME_CONTEXT_WINDOW, + affiliation_titles: bool = True, + ) -> None: + self.include_url = include_url + self.use_sudachi = use_sudachi + self.name_context_window = name_context_window + # 既定では組織名(法人格・組織語尾)と役職語(代表取締役、教授等)の両方を所属文脈とする。 + # 組織名だけに狭める場合は affiliation_titles=False(CLI: --no-affiliation-titles)。 + self.affiliation_titles = affiliation_titles + self.mask_honorific_names = mask_honorific_names + self.mask_bare_names = mask_bare_names + self._names: SudachiNameFinder | None = None + # 置換しなかった姓名の件数(方針判断用)。敬称のみ/文脈なし。 + self.honorific_name_candidates = 0 + self.honorific_name_records = 0 + self.bare_name_candidates = 0 + self.bare_name_records = 0 + + def _name_finder(self) -> SudachiNameFinder: + if self._names is None: + self._names = SudachiNameFinder() + return self._names + + def _detect_names(self, normalized: str, field: str) -> list[PIIMatch]: + matches: list[PIIMatch] = [] + bare = 0 + honorific_only = 0 + for start, end, kind in self._name_finder().find(normalized): + value = normalized[start:end] + before, after = _same_sentence_window(normalized, start, end, self.name_context_window) + honorific = HONORIFIC_AFTER_RE.match(normalized, end) is not None + role = ROLE_LABEL_BEFORE_RE.search(normalized[max(0, start - 16):start]) is not None + affiliated = bool(_ORG_RE.search(before) or _ORG_RE.search(after)) + if not affiliated and self.affiliation_titles: + affiliated = bool(TITLE_CONTEXT_RE.search(before) or TITLE_CONTEXT_RE.search(after)) + if affiliated and (kind == "pair" or honorific or role): + matches.append(PIIMatch("person_affiliation", field, start, end, value, "sudachi_name_affiliation", "medium")) + elif role: + matches.append(PIIMatch("person_name", field, start, end, value, "sudachi_name_role", "medium")) + elif honorific: + # 「○○さん」だけでは私人か公人(俳優、作家、選手)か区別できないため、既定では置換しない。 + if self.mask_honorific_names: + matches.append(PIIMatch("person_name", field, start, end, value, "sudachi_name_honorific", "low")) + else: + honorific_only += 1 + elif kind == "pair": + if self.mask_bare_names: + matches.append(PIIMatch("person_name", field, start, end, value, "sudachi_name_bare", "low")) + else: + bare += 1 + if honorific_only: + self.honorific_name_candidates += honorific_only + self.honorific_name_records += 1 + if bare: + self.bare_name_candidates += bare + self.bare_name_records += 1 + return matches + + @staticmethod + def _looks_like_phone(value: str) -> bool: + """住所候補の末尾が電話番号(区切り付き10桁以上)なら住所とみなさない。""" + + tail = re.search(r"(\d+(?:\s?[--‐ー]\s?\d+)+)\s*$", value) + if not tail: + return False + digits = _digits(tail.group(1)) + return len(digits) >= 9 and "丁目" not in value[-20:] and "番" not in value[-20:] + + def detect(self, text: Any, field: str = "content") -> list[PIIMatch]: + normalized = normalize_text(text) + if not normalized: + return [] + matches: list[PIIMatch] = [] + + def add( + pattern: re.Pattern[str], + pii_type: str, + method: str, + confidence: str = "high", + group: str | None = None, + ) -> None: + for found in pattern.finditer(normalized): + value = found.group(group) if group else found.group(0) + start = found.start(group) if group else found.start() + end = found.end(group) if group else found.end() + matches.append(PIIMatch(pii_type, field, start, end, value, method, confidence)) + + add(EMAIL_RE, "email", "regex_email") + for found in PHONE_SEPARATED_RE.finditer(normalized): + value = found.group("value") + if _valid_phone(value): + matches.append(PIIMatch("phone", field, found.start("value"), found.end("value"), value, "regex_phone")) + for found in PHONE_MOBILE_RE.finditer(normalized): + if _valid_phone(found.group(0)): + matches.append(PIIMatch("phone", field, found.start(), found.end(), found.group(0), "regex_phone")) + for found in PHONE_PLAIN_RE.finditer(normalized): + if _valid_phone(found.group(0)): + matches.append(PIIMatch("phone", field, found.start(), found.end(), found.group(0), "regex_phone")) + for found in PHONE_CONTEXT_RE.finditer(normalized): + value = found.group("value") + if _valid_phone(value): + matches.append(PIIMatch("phone", field, found.start("value"), found.end("value"), value, "context_phone", "medium")) + + if field != "url": + for found in MY_NUMBER_RE.finditer(normalized): + value = found.group(0) + if not is_valid_mynumber(value): + continue + if _has_context(normalized, found.start(), NUMBER_NEGATIVE_CONTEXT_RE, 20): + continue + # 区切り書式だけでは数表・型番を誤検出するため、マイナンバーはラベル文脈を必須にする。 + if _has_context(normalized, found.start(), MY_NUMBER_CONTEXT_RE, 40): + matches.append(PIIMatch("my_number", field, found.start(), found.end(), value, "checksum_mynumber")) + for found in CARD_RE.finditer(normalized): + value = found.group(0) + if not is_valid_luhn(value) or len(_digits(value)) == 12: + continue + if _has_context(normalized, found.start(), NUMBER_NEGATIVE_CONTEXT_RE, 20): + continue + labeled = _has_context(normalized, found.start(), CARD_CONTEXT_RE, 40) + grouped = not value.isdigit() + if labeled or grouped: + matches.append(PIIMatch("credit_card", field, found.start(), found.end(), value, "checksum_luhn", "high" if labeled else "medium")) + + patterns = [ + (ADDRESS_RE, "address", "regex_address"), + (ADDRESS_CITY_RE, "address", "regex_address_city"), + (ADDRESS_CONTEXT_RE, "address", "context_address"), + (NAME_AFFILIATION_LABEL_RE, "person_affiliation", "context_name_affiliation"), + (NAME_AFFILIATION_SUFFIX_RE, "person_affiliation", "context_name_affiliation"), + (AFFILIATION_NAME_RE, "person_affiliation", "context_affiliation_name"), + ] + if field != "url": + patterns.append((BANK_CONTEXT_RE, "bank_account", "context_bank_account")) + for pattern, pii_type, method in patterns: + add(pattern, pii_type, method, "medium", "value") + matches = [m for m in matches if not (m.pii_type == "address" and self._looks_like_phone(m.value))] + if self.use_sudachi and field != "url": + matches.extend(self._detect_names(normalized, field)) + for found in LATIN_NAME_RE.finditer(normalized): + group = "value" if found.group("value") else "value2" + matches.append(PIIMatch("person_name", field, found.start(group), found.end(group), found.group(group), "context_latin_name", "medium")) + for found in NAME_CONTEXT_RE.finditer(normalized): + value = found.group("value") + if value in NAME_STOPWORDS or value.split()[0] in NAME_STOPWORDS: + continue + matches.append(PIIMatch("person_name", field, found.start("value"), found.end("value"), value, "context_name", "medium")) + + # 同一type・同一位置の重複を除き、出現順に返す。重複範囲は検出結果として + # 残すが、置換時には _select_non_overlapping で一つにまとめる。 + unique: dict[tuple[str, str, int, int], PIIMatch] = {} + for match in matches: + unique[(match.pii_type, match.field, match.start, match.end)] = match + return sorted(unique.values(), key=lambda item: (item.start, item.end, item.pii_type)) + + def detect_record(self, url: Any, content: Any) -> list[PIIMatch]: + matches: list[PIIMatch] = [] + if self.include_url: + matches.extend(self.detect(url, "url")) + matches.extend(self.detect(content, "content")) + return matches + + def replace_text(self, text: Any, field: str = "content") -> tuple[str, list[PIIMatch]]: + """PIIをプレースホルダーに置換し、実際に置換した候補を返す。 + + NFKC正規化後の文字列を返すため、全角のメールアドレス等も一貫した + 表記になる。検出位置は返却文字列(置換前のNFKC文字列)に対応する。 + """ + + normalized = normalize_text(text) + if not normalized: + return normalized, [] + selected = _select_non_overlapping(self.detect(normalized, field)) + replaced = normalized + for match in reversed(selected): + replaced = replaced[: match.start] + match.placeholder + replaced[match.end :] + return replaced, selected + + def replace_record(self, url: Any, content: Any) -> tuple[str, str, list[PIIMatch]]: + replaced_url, url_matches = (self.replace_text(url, "url") if self.include_url else (normalize_text(url), [])) + replaced_content, content_matches = self.replace_text(content, "content") + return replaced_url, replaced_content, url_matches + content_matches + + +def matches_to_dict(matches: Iterable[PIIMatch]) -> list[dict[str, Any]]: + return [match.to_dict() for match in matches] diff --git a/code/3c1a8da-dirty-0c72d075/src/pii_residual_check.py b/code/3c1a8da-dirty-0c72d075/src/pii_residual_check.py new file mode 100644 index 0000000000000000000000000000000000000000..a2c9e2e3647572d160d654e80c820809ee16f802 --- /dev/null +++ b/code/3c1a8da-dirty-0c72d075/src/pii_residual_check.py @@ -0,0 +1,195 @@ +"""置換後データの PII 残存を、独立した検出器(GLiNER-ja)で確認する(監査項目12)。 + +``pii_detector.py`` と同じ検出器で再走査しても残存は必ず 0 になるため、 +学習済み日本語 PII NER ``DataSign/gliner-ja-pii-v1``(Apache-2.0)で +サンプルを走査し、プレースホルダー以外に残っている氏名・電話・住所・ +メール・口座番号を数える。``--original`` に置換前の parquet を渡すと、 +同じ文書で GLiNER が置換前に検出した実体のうち置換後に消えている割合 +(決定的検出器の再現率の目安)も出す。 + + uv sync --group pii-check + uv run python abeja-cc-ja/src/pii_residual_check.py --input --sample 500 --output pii_residual.json + +モデルは最大160トークンのため、文書を文字数で分割して重なり付きで走査する。 +""" + +from __future__ import annotations + +import argparse +import json +import random +import time +import unicodedata +from collections import Counter, defaultdict +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +import pyarrow.parquet as pq + +from pii_detector import NAME_CONTEXT_WINDOW, TITLE_CONTEXT_RE, _ORG_RE, _same_sentence_window + + +MODEL_NAME = "DataSign/gliner-ja-pii-v1" +LABELS = ["person name", "phone number", "address", "email address", "account number"] +LABEL_TO_TYPE = { + "person name": "person_name", + "phone number": "phone", + "address": "address", + "email address": "email", + "account number": "bank_account", +} +PLACEHOLDER_MARKERS = ("", "", "
", "", "", "", "", "") + + +def load_model(device: str | None): + from gliner import GLiNER + from gliner.data_processing import WordsSplitter + + class JapaneseSplitterNoWS: + def __init__(self) -> None: + self._base = WordsSplitter(splitter_type="janome") + + def __call__(self, text: str): + for token, start, end in self._base(text): + if token.strip() == "": + continue + yield token, start, end + + model = GLiNER.from_pretrained(MODEL_NAME, max_width=25) + model.data_processor.words_splitter = JapaneseSplitterNoWS() + if device: + try: + model = model.to(device) + except Exception: # noqa: BLE001 - デバイス非対応時はCPUのまま + pass + model.eval() + return model + + +def chunks(text: str, size: int, overlap: int): + start = 0 + while start < len(text): + end = min(len(text), start + size) + yield start, text[start:end] + if end == len(text): + break + start = end - overlap + + +def predict(model, text: str, threshold: float, chunk_chars: int, overlap: int) -> list[dict[str, Any]]: + found: dict[tuple[str, int, int], dict[str, Any]] = {} + for offset, piece in chunks(text, chunk_chars, overlap): + for entity in model.predict_entities(piece, LABELS, threshold=threshold): + key = (entity["label"], offset + entity["start"], offset + entity["end"]) + if key not in found: + found[key] = {"label": entity["label"], "start": key[1], "end": key[2], "text": entity["text"], "score": round(float(entity["score"]), 3)} + return sorted(found.values(), key=lambda item: (item["start"], item["end"])) + + +def is_placeholder(text: str) -> bool: + return any(marker in text for marker in PLACEHOLDER_MARKERS) or "<" in text + + +def mask(text: str) -> str: + return text[:1] + "*" * max(1, len(text) - 1) + + +def main(argv: list[str] | None = None) -> None: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--input", type=Path, required=True, help="置換後の parquet(url, content)") + parser.add_argument("--original", type=Path, default=None, help="置換前の parquet(同じ行順)。再現率の目安を出す") + parser.add_argument("--sample", type=int, default=500) + parser.add_argument("--seed", type=int, default=20260904) + parser.add_argument("--threshold", type=float, default=0.5) + parser.add_argument("--chunk-chars", type=int, default=200) + parser.add_argument("--overlap", type=int, default=40) + parser.add_argument("--max-chars", type=int, default=3000, help="1文書あたり走査する最大文字数") + parser.add_argument("--device", default=None, help="cpu / mps / cuda(既定はGLiNERの既定)") + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args(argv) + + table = pq.read_table(args.input, columns=["url", "content"]) + total = table.num_rows + rng = random.Random(args.seed) + indices = sorted(rng.sample(range(total), min(args.sample, total))) + original = pq.read_table(args.original, columns=["content"]) if args.original else None + model = load_model(args.device) + + residual_counts: Counter = Counter() + residual_docs: Counter = Counter() + examples: dict[str, list[dict[str, Any]]] = defaultdict(list) + recall_found: Counter = Counter() + recall_removed: Counter = Counter() + # 「個人名+所属」の定義(同一文・前後25文字に所属か役職)に該当する人名だけの再現率 + ctx_found = 0 + ctx_removed = 0 + started = time.perf_counter() + docs_with_residual = 0 + for index in indices: + row = table.slice(index, 1).to_pylist()[0] + text = unicodedata.normalize("NFKC", row.get("content") or "")[: args.max_chars] + entities = [e for e in predict(model, text, args.threshold, args.chunk_chars, args.overlap) if not is_placeholder(e["text"])] + if entities: + docs_with_residual += 1 + seen_types = set() + for entity in entities: + pii_type = LABEL_TO_TYPE[entity["label"]] + residual_counts[pii_type] += 1 + seen_types.add(pii_type) + if len(examples[pii_type]) < 5: + context = text[max(0, entity["start"] - 25): entity["start"]] + "[" + mask(entity["text"]) + "]" + text[entity["end"]: entity["end"] + 25] + examples[pii_type].append({"record_index": index, "url": row.get("url"), "score": entity["score"], "context_masked": context.replace("\n", " ")}) + for pii_type in seen_types: + residual_docs[pii_type] += 1 + if original is not None: + original_text = unicodedata.normalize("NFKC", original.slice(index, 1).to_pylist()[0].get("content") or "")[: args.max_chars] + for entity in predict(model, original_text, args.threshold, args.chunk_chars, args.overlap): + pii_type = LABEL_TO_TYPE[entity["label"]] + recall_found[pii_type] += 1 + removed = entity["text"] not in text + if removed: + recall_removed[pii_type] += 1 + if pii_type == "person_name": + before, after = _same_sentence_window(original_text, entity["start"], entity["end"], NAME_CONTEXT_WINDOW) + if _ORG_RE.search(before) or _ORG_RE.search(after) or TITLE_CONTEXT_RE.search(before) or TITLE_CONTEXT_RE.search(after): + ctx_found += 1 + ctx_removed += removed + elapsed = time.perf_counter() - started + result = { + "checked_at_utc": datetime.now(timezone.utc).isoformat(), + "detector": {"model": MODEL_NAME, "license": "Apache-2.0", "labels": LABELS, "threshold": args.threshold, + "chunk_chars": args.chunk_chars, "overlap": args.overlap, "max_chars": args.max_chars}, + "input": str(args.input), "total_records": total, "sampled_records": len(indices), "seed": args.seed, + "elapsed_s": round(elapsed, 1), + "residual": { + "records_with_any_residual": docs_with_residual, + "records_with_residual_rate": round(docs_with_residual / max(1, len(indices)), 4), + "by_type_entities": dict(residual_counts), + "by_type_records": dict(residual_docs), + "examples_masked": examples, + }, + "note_ja": "GLiNER-ja が置換後テキストで検出した実体(プレースホルダーを除く)。氏名は公人・著者名・作品中の人名も含むため、残存の要否は目視で判断する。", + } + if original is not None: + result["recall_estimate_person_name_with_affiliation_context"] = { + "gliner_found_in_original": ctx_found, + "removed_after_replacement": ctx_removed, + "removed_rate": round(ctx_removed / ctx_found, 3) if ctx_found else None, + "note_ja": "GLiNER-ja が検出した人名のうち、同一文・前後25文字に所属か役職がある(=個人名+所属の定義に該当する)ものの置換率。", + } + result["recall_estimate"] = { + pii_type: {"gliner_found_in_original": recall_found[pii_type], "removed_after_replacement": recall_removed[pii_type], + "removed_rate": round(recall_removed[pii_type] / recall_found[pii_type], 3) if recall_found[pii_type] else None} + for pii_type in sorted(recall_found) + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + print(json.dumps({"sampled": len(indices), "records_with_residual": docs_with_residual, "by_type": dict(residual_counts), + "recall_estimate": result.get("recall_estimate"), + "recall_person_name_with_affiliation_context": result.get("recall_estimate_person_name_with_affiliation_context"), + "elapsed_s": round(elapsed, 1)}, ensure_ascii=False)) + + +if __name__ == "__main__": + main() diff --git a/code/3c1a8da-dirty-0c72d075/src/quality_report.py b/code/3c1a8da-dirty-0c72d075/src/quality_report.py new file mode 100644 index 0000000000000000000000000000000000000000..4488706984fcc3b0432db302405615a97dd4fcfe --- /dev/null +++ b/code/3c1a8da-dirty-0c72d075/src/quality_report.py @@ -0,0 +1,340 @@ +"""監査項目 E(22 重複)・F(25〜27 言語・品質)・G(28〜29 ドメイン適合)の報告書を生成する。 + +第2パスが書く ``features.parquet``(文書ごとの言語・ジャンル・品質フラグ・文字数・perplexity・SHA-1)と +``noise_summary.json`` を DuckDB で集約し、JSON と Markdown を出力する。全件(約2.2億行)でも +DuckDB がファイルを逐次読みするため、1台のジョブ(cpu-xl 等)で処理できる。 + + uv run python abeja-cc-ja/src/quality_report.py --features-glob "/**/features.parquet" \\ + --noise-summaries-glob "/**/noise_summary.json" --output-dir \\ + [--previous-low-quality-rate 0.35] [--exclude-genres none] + +項目22の配布元重複除去の記録は本スクリプト内の定数(出典 URL 付き)に置き、完全一致(本文 SHA-1、URL)の +再確認結果を添える。 +""" + +from __future__ import annotations + +import argparse +import json +import time +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + + +UPSTREAM_DEDUP = { + "performed_by": "ABEJA(配布元、ABEJA-CC-JA 構築時)", + "methods": [ + {"method": "URL 重複除去(同一 URL は最新のスナップショットを採用)", "threshold": "完全一致"}, + {"method": "MinHash による近似重複除去(text-dedup、Dataproc 上で実行)", "threshold": "非公開(記事に閾値の記載なし)"}, + ], + "source_urls": [ + "https://tech-blog.abeja.asia/entry/abeja-nedo-project-part2-202405", + "https://tech-blog.abeja.asia/entry/abeja-cc-ja-202409", + "https://registry.opendata.aws/abeja-cc-ja/", + ], + "decision_ja": "配布元で URL 重複除去と MinHash 近似重複除去が実施済みのため、近似重複除去は再実行しない。完全一致(本文 SHA-1、URL)の残存だけを全件で再確認して記録する。", +} + +GENRE_LABELS_JA = { + "diary_blog": "日記ブログ", "affiliate": "投資・美容・健康のアフィリエイト", "game": "ゲーム", + "entertainment": "芸能", "ec_product": "EC 商品ページ", "other": "その他", +} +LOW_QUALITY_FLAGS_JA = { + "short_lt500": "最終本文が500字未満", "symbol_digit_ratio_gt30": "記号・数字比率30%超", "line_repetition_gt30": "同一行の反復30%超", + "avg_line_len_lt20": "平均行長20字未満", "template_commerce": "販促・商品ページの定型", "low_lid_confidence": "言語判定の確信度0.5未満", +} + + +def q(con, sql: str) -> list[tuple]: + return con.execute(sql).fetchall() + + +def q1(con, sql: str): + return con.execute(sql).fetchone() + + +def build(features_glob: str, noise_glob: str | None, previous_low_quality_rate: float | None, exclude_genres: list[str], sample_examples: int = 5, + db_settings: dict[str, Any] | None = None, guard_removed_glob: str | None = None) -> dict[str, Any]: + """features.parquet を DuckDB で集計する。 + + ``features_glob`` はローカルディスク上のファイルを指すこと(FUSE マウント越しだと各クエリが全ファイルを + 再スキャンするため数時間かかる)。``db_settings`` で threads / temp_directory / memory_limit を指定できる。 + 進捗は項目ごとに標準出力へ JSON で出す。 + """ + import duckdb + + started = time.monotonic() + + def progress(step: str, **extra: Any) -> None: + print(json.dumps({"event": "progress", "step": step, "elapsed_s": round(time.monotonic() - started, 1), **extra}, ensure_ascii=False), flush=True) + + con = duckdb.connect() + for key, value in (db_settings or {}).items(): + if value is None: + continue + con.execute(f"SET {key} = ?", [value]) if key != "threads" else con.execute(f"SET threads = {int(value)}") + con.execute("SET preserve_insertion_order = false") + con.execute(f"CREATE VIEW f0 AS SELECT * EXCLUDE (filename), regexp_extract(filename, '([^/]+)/features\\.parquet$', 1) AS shard " + f"FROM read_parquet('{features_glob}', union_by_name=true, filename=true)") + guard_info: dict[str, Any] | None = None + if guard_removed_glob: + # 第3パス(分類器)の削除を反映する。guard_removed.jsonl の record_index は第2パス出力 parquet(保持行のみ)の行番号なので、 + # features 側では status='retained' の行を record_index 順に並べた順位と突き合わせる。 + con.execute( + "CREATE TABLE guard_rows AS SELECT regexp_extract(filename, '([^/]+)/guard_removed\\.jsonl$', 1) AS shard, record_index AS rk, categories " + f"FROM read_json('{guard_removed_glob}', format='newline_delimited', filename=true, ignore_errors=true, " + "columns={'record_index': 'BIGINT', 'url': 'VARCHAR', 'safety': 'VARCHAR', 'categories': 'VARCHAR[]'})") + con.execute( + "CREATE TABLE guard_deleted AS SELECT r.shard, r.record_index FROM " + "(SELECT shard, record_index, row_number() OVER (PARTITION BY shard ORDER BY record_index) - 1 AS rk FROM f0 WHERE status = 'retained') r " + "JOIN guard_rows g ON r.shard = g.shard AND r.rk = g.rk") + # features の record_index は保持行(第1パス出力の位置)と有害削除行(入力の位置)で採番が異なり、同じ値が重複しうるため + # status='retained' の行だけを置き換える + # 結合条件は等値(shard, record_index)だけにして DuckDB のハッシュ結合を使わせ、status の判定は CASE 側で行う + # (結合条件に status を入れると計画が変わり、1クエリに数時間かかった) + con.execute("CREATE VIEW f AS SELECT f0.* REPLACE (CASE WHEN gd.record_index IS NOT NULL AND f0.status = 'retained' THEN 'deleted_guard:classifier' ELSE f0.status END AS status) " + "FROM f0 LEFT JOIN guard_deleted gd ON f0.shard = gd.shard AND f0.record_index = gd.record_index") + guard_rows = q1(con, "SELECT count(*) FROM guard_rows")[0] + guard_matched = q1(con, "SELECT count(*) FROM guard_deleted")[0] + guard_categories = q(con, "SELECT c, count(*) FROM (SELECT unnest(categories) AS c FROM guard_rows) GROUP BY c ORDER BY 2 DESC") + guard_info = {"guard_removed_glob": guard_removed_glob, "records_in_guard_removed": guard_rows, "records_matched_to_features": guard_matched, + "by_category": [{"category": c, "records": n} for c, n in guard_categories], + "note_ja": "第3パス(Qwen3Guard による削除)を features の status に 'deleted_guard:classifier' として反映。以降の保持件数はこの削除後の値。"} + progress("guard_join", guard_rows=guard_rows, guard_matched=guard_matched) + else: + con.execute("CREATE VIEW f AS SELECT * FROM f0") + total = q1(con, "SELECT count(*) FROM f")[0] + retained = q1(con, "SELECT count(*) FROM f WHERE status = 'retained'")[0] + progress("counts", records_total=total, records_retained=retained) + report: dict[str, Any] = {"generated_at_utc": datetime.now(timezone.utc).isoformat(), "features_glob": features_glob, + "records_total": total, "records_retained": retained} + if guard_info is not None: + report["guard_pass"] = guard_info + + # --- 22 重複 --- + dup_sha = q1(con, "SELECT count(*) - count(DISTINCT content_sha1) FROM f WHERE status = 'retained' AND content_sha1 <> ''")[0] + dup_url = q1(con, "SELECT count(*) - count(DISTINCT url) FROM f WHERE status = 'retained' AND url <> ''")[0] + report["item22_dedup"] = { + "upstream": UPSTREAM_DEDUP, + "exact_duplicate_check": { + "scope": ("第3パス後の保持文書(全件)" if guard_info else "第2パス後の保持文書(全件)"), + "content_sha1_duplicates": dup_sha, "url_duplicates": dup_url, + "content_sha1_duplicate_rate": round(dup_sha / max(1, retained), 6), "url_duplicate_rate": round(dup_url / max(1, retained), 6), + }, + } + + progress("item22") + # --- 25 言語 --- + langs = q(con, "SELECT lang, count(*) FROM f WHERE status NOT LIKE 'deleted_toxic%' GROUP BY lang ORDER BY 2 DESC") + lang_total = sum(n for _, n in langs) + mixed = q1(con, "SELECT count(*) FROM f WHERE status = 'retained' AND mixed_language")[0] + non_ja_deleted = q1(con, "SELECT count(*) FROM f WHERE status = 'deleted_noise:non_japanese'")[0] + report["item25_language"] = { + "tool": "fastText lid.176(文書先頭1,000字。行判定は30字以上の行を最大50行)", + "scope": "第1パス後の文書(有害フィルタ削除分を除く)", + "distribution": [{"lang": l, "records": n, "ratio": round(n / max(1, lang_total), 5)} for l, n in langs[:15]], + "japanese_ratio": round(next((n for l, n in langs if l == "ja"), 0) / max(1, lang_total), 5), + "mixed_language_records": mixed, "mixed_definition": "文書は日本語判定だが、30字以上の行のうち非日本語判定が3割以上", + "processing": {"non_japanese": f"削除({non_ja_deleted} 文書、確信度0.5以上)", "mixed": "保持し件数のみ記録(非日本語行は行単位で削除しない)"}, + } + + progress("item25") + # --- 26 perplexity --- + has_ppl = q1(con, "SELECT count(*) FROM f WHERE perplexity IS NOT NULL")[0] > 0 + if has_ppl: + quant = q1(con, "SELECT min(perplexity), quantile_cont(perplexity, 0.05), quantile_cont(perplexity, 0.25), quantile_cont(perplexity, 0.5), quantile_cont(perplexity, 0.75), quantile_cont(perplexity, 0.95), max(perplexity) FROM f WHERE perplexity IS NOT NULL") + hist = q(con, "SELECT floor(perplexity/5)*5 AS b, count(*) FROM f WHERE perplexity IS NOT NULL GROUP BY b ORDER BY b") + near_threshold = q(con, f"SELECT url, perplexity, chars_final, genre FROM f WHERE status='retained' AND perplexity >= 38 ORDER BY perplexity DESC LIMIT {sample_examples}") + low = q(con, f"SELECT url, perplexity, chars_final, genre FROM f WHERE status='retained' AND perplexity IS NOT NULL ORDER BY perplexity ASC LIMIT {sample_examples}") + report["item26_perplexity"] = { + "filter": {"applied_by": "Podtech(入力データセット abeja-cc-ja-filtered の作成時)", "model": "KenLM(lighttransport/japanese-scoring-model)", "threshold": "perplexity < 40 を保持", + "source_url": "https://huggingface.co/datasets/Podtech/abeja-cc-ja-filtered"}, + "distribution_retained": {"min": quant[0], "p5": quant[1], "p25": quant[2], "p50": quant[3], "p75": quant[4], "p95": quant[5], "max": quant[6]}, + "histogram_bin5": [{"bin_start": int(b), "records": n} for b, n in hist], + "examples_near_threshold_retained": [{"url": u, "perplexity": p, "chars": c, "genre": g} for u, p, c, g in near_threshold], + "examples_lowest_perplexity": [{"url": u, "perplexity": p, "chars": c, "genre": g} for u, p, c, g in low], + "note_ja": "閾値以上(除外側)の文書は入力データに含まれないため、除外例は配布元データ(S3 の原本)からの抽出が必要。ここでは保持側の分布と閾値付近の残存例を示す。", + } + else: + report["item26_perplexity"] = {"note_ja": "perplexity 列が無いため未集計"} + + progress("item26") + # --- 27 文書長の分布(前後) --- + def dist(col: str, where: str) -> dict[str, Any]: + r = q1(con, f"SELECT count(*), min({col}), quantile_cont({col}, 0.05), quantile_cont({col}, 0.5), quantile_cont({col}, 0.95), max({col}), avg({col}), sum({col}) FROM f WHERE {where}") + return {"records": r[0], "min": r[1], "p5": r[2], "p50": r[3], "p95": r[4], "max": r[5], "mean": round(r[6], 1) if r[6] else None, "sum": r[7]} + by_genre_status = q(con, "SELECT genre, split_part(status, ':', 1) AS st, count(*) FROM f GROUP BY genre, st ORDER BY genre, st") + genre_rates: dict[str, dict[str, Any]] = {} + for g, st, n in by_genre_status: + genre_rates.setdefault(g, {"label_ja": GENRE_LABELS_JA.get(g, g), "records": 0}) + genre_rates[g][st] = n + genre_rates[g]["records"] += n + for g, v in genre_rates.items(): + v["deleted_rate"] = round((v.get("deleted_toxic", 0) + v.get("deleted_noise", 0) + v.get("deleted_guard", 0)) / max(1, v["records"]), 5) + report["item27_length"] = { + "chars_input_all": dist("chars_input", "chars_input IS NOT NULL"), + "chars_final_retained": dist("chars_final", "status = 'retained'"), + "chars_input_deleted_toxic": dist("chars_input", "status LIKE 'deleted_toxic%'"), + "chars_input_deleted_noise": dist("chars_input", "status LIKE 'deleted_noise%'"), + "chars_input_deleted_guard": dist("chars_input", "status LIKE 'deleted_guard%'") if guard_info else None, + "deletion_rate_by_genre": genre_rates, + "tokens_note_ja": "トークン数は方針によりトークナイザを指定しないため未集計(文字数のみ)。", + } + + progress("item27") + # --- 28 低品質 --- + lq = q1(con, "SELECT count(*) FROM f WHERE status = 'retained' AND is_low_quality")[0] + flags = q(con, "SELECT flag, count(*) FROM (SELECT unnest(string_split(low_quality_flags, '|')) AS flag FROM f WHERE status = 'retained' AND low_quality_flags <> '') GROUP BY flag ORDER BY 2 DESC") + lq_by_genre = q(con, "SELECT genre, count(*), sum(CASE WHEN is_low_quality THEN 1 ELSE 0 END) FROM f WHERE status = 'retained' GROUP BY genre ORDER BY 2 DESC") + report["item28_low_quality"] = { + "definition_ja": "保持文書のうち次のいずれかに該当: " + "、".join(f"{k}({v})" for k, v in LOW_QUALITY_FLAGS_JA.items()), + "method_ja": "第2パスで文書ごとに決定的規則で判定(doc_features.py)。分類の妥当性はサンプルの目視で確認する。", + "records_retained": retained, "low_quality_records": lq, "low_quality_rate": round(lq / max(1, retained), 5), + "by_flag": [{"flag": f_, "label_ja": LOW_QUALITY_FLAGS_JA.get(f_, f_), "records": n, "ratio": round(n / max(1, retained), 5)} for f_, n in flags], + "by_genre": [{"genre": g, "label_ja": GENRE_LABELS_JA.get(g, g), "records": n, "low_quality": m, "rate": round(m / max(1, n), 4)} for g, n, m in lq_by_genre], + "previous_review_rate": previous_low_quality_rate, + "comparison_ja": (f"前回レビュー指摘値 {previous_low_quality_rate:.1%} に対し今回 {lq / max(1, retained):.1%}" if previous_low_quality_rate is not None else "前回レビューの指摘値が未入力のため比較なし"), + } + + progress("item28") + # --- 29 ジャンル --- + genres = q(con, "SELECT genre, count(*) FROM f WHERE status = 'retained' GROUP BY genre ORDER BY 2 DESC") + manufacturing = q1(con, "SELECT count(*) FROM f WHERE status = 'retained' AND manufacturing_score >= 2.0")[0] + report["item29_genre"] = { + "method_ja": "wordlists/genre/genre_rules.json の URL 規則と手がかり語で、1,000字あたりの異なり手がかり語数をスコア化(しきい値2.0)。製造業・重工の適合スコアは独立に算出。", + "distribution_retained": [{"genre": g, "label_ja": GENRE_LABELS_JA.get(g, g), "records": n, "ratio": round(n / max(1, retained), 5)} for g, n in genres], + "manufacturing_relevant_records": manufacturing, "manufacturing_relevant_ratio": round(manufacturing / max(1, retained), 5), + "exclusion_decision": {"excluded_genres": exclude_genres, "note_ja": "除外するジャンルは方針として決める。除外する場合は第3パスで genre 列を条件に削除し、件数を記録する。"}, + } + progress("item29") + if noise_glob: + report["noise_summaries_glob"] = noise_glob + return report + + +def to_markdown(r: dict[str, Any]) -> str: + L: list[str] = [] + L.append("# 品質監査報告(E 重複・F 言語/品質・G ドメイン適合)") + L.append("") + L.append(f"- 生成日時: {r['generated_at_utc']}") + L.append(f"- 対象文書: {r['records_total']:,}(保持 {r['records_retained']:,})") + L.append("") + if r.get("guard_pass"): + g = r["guard_pass"] + L.append("## 第3パス(分類器による削除)の反映") + L.append("") + L.append(f"- {g['note_ja']}") + L.append(f"- 削除記録 {g['records_in_guard_removed']:,} 件、features に突合できた件数 {g['records_matched_to_features']:,}") + L.append("- カテゴリ別: " + ", ".join(f"{x['category']} {x['records']:,}" for x in g["by_category"])) + L.append("") + d = r["item22_dedup"] + L.append("## 項目22: 重複除去") + L.append("") + L.append(f"- 配布元の実施: {d['upstream']['performed_by']}") + for m in d["upstream"]["methods"]: + L.append(f" - {m['method']}(閾値: {m['threshold']})") + L.append("- 出典: " + ", ".join(d["upstream"]["source_urls"])) + L.append(f"- 判断: {d['upstream']['decision_ja']}") + e = d["exact_duplicate_check"] + L.append(f"- 完全一致の再確認({e['scope']}): 本文 SHA-1 重複 {e['content_sha1_duplicates']:,}({e['content_sha1_duplicate_rate']:.4%})、URL 重複 {e['url_duplicates']:,}") + L.append("") + l = r["item25_language"] + L.append("## 項目25: 言語判定") + L.append("") + L.append(f"- ツール: {l['tool']}。対象: {l['scope']}") + L.append(f"- 日本語比率: {l['japanese_ratio']:.4%}。混在文書({l['mixed_definition']}): {l['mixed_language_records']:,}") + L.append("- 処理: " + "、".join(f"{k}: {v}" for k, v in l["processing"].items())) + L.append("") + L.append("| 言語 | 文書数 | 比率 |") + L.append("|---|---:|---:|") + for x in l["distribution"][:8]: + L.append(f"| {x['lang']} | {x['records']:,} | {x['ratio']:.4%} |") + L.append("") + p = r["item26_perplexity"] + L.append("## 項目26: perplexity フィルタ") + L.append("") + if "filter" in p: + L.append(f"- 適用者: {p['filter']['applied_by']}、モデル: {p['filter']['model']}、閾値: {p['filter']['threshold']}({p['filter']['source_url']})") + ds = p["distribution_retained"] + L.append(f"- 保持側の分布: min {ds['min']:.1f} / p5 {ds['p5']:.1f} / p50 {ds['p50']:.1f} / p95 {ds['p95']:.1f} / max {ds['max']:.1f}") + L.append("- ヒストグラム(5刻み): " + ", ".join(f"{h['bin_start']}-{h['bin_start']+5}: {h['records']:,}" for h in p["histogram_bin5"])) + L.append("- 閾値付近の残存例:") + for x in p["examples_near_threshold_retained"]: + L.append(f" - {x['url'][:90]} (ppl {x['perplexity']:.1f}, {x['chars']}字, {x['genre']})") + L.append(f"- 注記: {p['note_ja']}") + else: + L.append(f"- {p['note_ja']}") + L.append("") + n = r["item27_length"] + L.append("## 項目27: 文書長の分布(フィルタ前後)") + L.append("") + L.append("| 区分 | 文書数 | min | p5 | p50 | p95 | max | 平均 |") + L.append("|---|---:|---:|---:|---:|---:|---:|---:|") + for key, label in (("chars_input_all", "入力(全件)"), ("chars_final_retained", "最終(保持)"), ("chars_input_deleted_toxic", "有害フィルタで削除"), ("chars_input_deleted_noise", "ノイズで削除")): + x = n[key] + if x["records"]: + L.append(f"| {label} | {x['records']:,} | {x['min']:.0f} | {x['p5']:.0f} | {x['p50']:.0f} | {x['p95']:.0f} | {x['max']:.0f} | {x['mean']} |") + L.append("") + L.append("ジャンル別の削除率(特定ジャンルだけが大量に落ちていないかの確認):") + L.append("") + L.append("| ジャンル | 文書数 | 有害で削除 | ノイズで削除 | 削除率 |") + L.append("|---|---:|---:|---:|---:|") + for g, v in sorted(n["deletion_rate_by_genre"].items(), key=lambda kv: -kv[1]["records"]): + L.append(f"| {v['label_ja']} | {v['records']:,} | {v.get('deleted_toxic', 0):,} | {v.get('deleted_noise', 0):,} | {v['deleted_rate']:.2%} |") + L.append(f"\n{n['tokens_note_ja']}") + L.append("") + lq = r["item28_low_quality"] + L.append("## 項目28: 低品質ページ") + L.append("") + L.append(f"- 定義: {lq['definition_ja']}") + L.append(f"- 方法: {lq['method_ja']}") + L.append(f"- 比率: {lq['low_quality_records']:,} / {lq['records_retained']:,} = {lq['low_quality_rate']:.2%}。{lq['comparison_ja']}") + L.append("") + L.append("| 該当条件 | 文書数 | 比率 |") + L.append("|---|---:|---:|") + for x in lq["by_flag"]: + L.append(f"| {x['label_ja']} | {x['records']:,} | {x['ratio']:.2%} |") + L.append("") + g = r["item29_genre"] + L.append("## 項目29: 無関係ジャンルの比率") + L.append("") + L.append(f"- 方法: {g['method_ja']}") + L.append("") + L.append("| ジャンル | 文書数 | 比率 |") + L.append("|---|---:|---:|") + for x in g["distribution_retained"]: + L.append(f"| {x['label_ja']} | {x['records']:,} | {x['ratio']:.2%} |") + L.append("") + L.append(f"- 製造業・重工に適合(スコア2.0以上): {g['manufacturing_relevant_records']:,}({g['manufacturing_relevant_ratio']:.2%})") + L.append(f"- 除外の判断: 除外ジャンル = {g['exclusion_decision']['excluded_genres'] or 'なし'}。{g['exclusion_decision']['note_ja']}") + L.append("") + return "\n".join(L) + "\n" + + +def main(argv: list[str] | None = None) -> None: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--features-glob", required=True, help="features.parquet の glob(DuckDB 形式、例: /cleaned/outputs_v2/**/features.parquet)") + parser.add_argument("--noise-summaries-glob", default=None) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--previous-low-quality-rate", type=float, default=None, help="前回レビューの低品質比率(0〜1)") + parser.add_argument("--exclude-genres", default="", help="除外を決めたジャンル(カンマ区切り、記録用)") + parser.add_argument("--threads", type=int, default=None, help="DuckDB のスレッド数(既定は CPU 数)") + parser.add_argument("--temp-dir", default=None, help="DuckDB の一時ディレクトリ(メモリに収まらない集計の退避先)") + parser.add_argument("--memory-limit", default=None, help="DuckDB のメモリ上限(例: 40GB)") + parser.add_argument("--guard-removed-glob", default=None, help="第3パスの guard_removed.jsonl の glob(指定すると分類器の削除を反映した件数で集計)") + args = parser.parse_args(argv) + excluded = [x for x in args.exclude_genres.split(",") if x] + settings = {"threads": args.threads, "temp_directory": args.temp_dir, "memory_limit": args.memory_limit} + report = build(args.features_glob, args.noise_summaries_glob, args.previous_low_quality_rate, excluded, db_settings=settings, + guard_removed_glob=args.guard_removed_glob) + args.output_dir.mkdir(parents=True, exist_ok=True) + (args.output_dir / "quality_report.json").write_text(json.dumps(report, ensure_ascii=False, indent=2, default=str) + "\n", encoding="utf-8") + (args.output_dir / "quality_report.md").write_text(to_markdown(report), encoding="utf-8") + print(json.dumps({"records_total": report["records_total"], "retained": report["records_retained"], + "japanese_ratio": report["item25_language"]["japanese_ratio"], "low_quality_rate": report["item28_low_quality"]["low_quality_rate"], + "manufacturing_ratio": report["item29_genre"]["manufacturing_relevant_ratio"], "output": str(args.output_dir)}, ensure_ascii=False)) + + +if __name__ == "__main__": + main() diff --git a/code/3c1a8da-dirty-0c72d075/src/review_tally.py b/code/3c1a8da-dirty-0c72d075/src/review_tally.py new file mode 100644 index 0000000000000000000000000000000000000000..dae82b48f17835da5d746b4dccb7e460c026734e --- /dev/null +++ b/code/3c1a8da-dirty-0c72d075/src/review_tally.py @@ -0,0 +1,53 @@ +"""記入済みの review_samples.csv を集計し、層別の精度・見逃し率を出す。 + +verdict は ``harmful`` / ``not_harmful`` / ``unsure`` の3値。未記入は未確認として数える。 +出力は ``review_tally.json`` と標準出力の表。 +""" + +from __future__ import annotations + +import argparse +import csv +import json +from collections import defaultdict +from datetime import datetime, timezone +from pathlib import Path + + +def main(argv: list[str] | None = None) -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--csv", type=Path, required=True) + parser.add_argument("--output", type=Path, default=None, help="既定は CSV と同じ場所の review_tally.json") + args = parser.parse_args(argv) + counts: dict[str, dict[str, int]] = defaultdict(lambda: {"harmful": 0, "not_harmful": 0, "unsure": 0, "unreviewed": 0}) + reviewers: set[str] = set() + with args.csv.open(encoding="utf-8", newline="") as handle: + for row in csv.DictReader(handle): + verdict = (row.get("verdict") or "").strip().lower() or "unreviewed" + if verdict not in ("harmful", "not_harmful", "unsure"): + verdict = "unreviewed" + counts[row["stratum"]][verdict] += 1 + if row.get("reviewer"): + reviewers.add(row["reviewer"]) + result: dict[str, dict] = {} + for stratum, c in sorted(counts.items()): + reviewed = c["harmful"] + c["not_harmful"] + entry = dict(c) + entry["reviewed"] = reviewed + if reviewed: + if stratum.startswith(("deleted:", "cooccurrence:")): + entry["precision"] = round(c["harmful"] / reviewed, 3) # 削除の妥当性 + else: + entry["harmful_rate"] = round(c["harmful"] / reviewed, 3) # 保持側の見逃し率 + result[stratum] = entry + output = args.output or args.csv.with_name("review_tally.json") + payload = {"tallied_at_utc": datetime.now(timezone.utc).isoformat(), "csv": str(args.csv), "reviewers": sorted(reviewers), "strata": result} + output.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + print(f"{'stratum':40s} {'harm':>5s} {'not':>5s} {'uns':>5s} {'todo':>5s} rate") + for stratum, e in result.items(): + rate = e.get("precision", e.get("harmful_rate", "")) + print(f"{stratum:40s} {e['harmful']:5d} {e['not_harmful']:5d} {e['unsure']:5d} {e['unreviewed']:5d} {rate}") + + +if __name__ == "__main__": + main() diff --git a/code/3c1a8da-dirty-0c72d075/src/run_guard_pass.py b/code/3c1a8da-dirty-0c72d075/src/run_guard_pass.py new file mode 100644 index 0000000000000000000000000000000000000000..6ef84f16f0d84d7e97d852e19a26254b7d92210f --- /dev/null +++ b/code/3c1a8da-dirty-0c72d075/src/run_guard_pass.py @@ -0,0 +1,314 @@ +"""第3パス: 辞書の語が1語以上ある文書に Qwen3Guard を適用し、有害と判定された文書を削除する。 + +背景: 第1パスの辞書(同一カテゴリ3語以上)は、保持文書 3,000 件の無作為抽出で 0.7% が分類器 Unsafe、 +うち性的コンテンツ 9 件は辞書の語が 1〜2 語しか一致しないため保持されていた。全 2 億文書に分類器を +当てるのは GPU 費用が大きいので、辞書の語が ``--min-terms`` 語以上一致する文書(候補)だけに適用する。 + +入力は第2パスの出力(``/common_crawl_N//.parquet``、列 url/content/perplexity)。 +``--source-repo`` を指定すると HF から HTTP で取得する(マウントは使わない)。 + +削除規則: 安全性が ``Unsafe`` で、カテゴリが ``--delete-categories`` のいずれかに該当する文書を削除する。 +``Controversial`` と、Politically Sensitive Topics / Copyright Violation / PII / Jailbreak のみの Unsafe は +保持して件数を記録する(監査基準では報道・解説・時事は有害としない)。 + +出力(シャードごと): ``.parquet``(保持文書)、``guard_removed.jsonl``(削除文書の URL・分類・抜粋)、 +``guard_results.jsonl``(候補全件の判定)、``guard_summary.json``。 + + uv run python abeja-cc-ja/src/run_guard_pass.py --input-dir <第2パス出力/common_crawl_0> --output-root out --backend fake --limit-shards 1 +""" + +from __future__ import annotations + +import argparse +import json +import os +import shutil +import time +import traceback +from concurrent.futures import Future, ProcessPoolExecutor +from collections import Counter +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pyarrow.parquet as pq + +from filter_toxic import CATEGORIES, KeywordMatcher, _distinct_terms_by_category, load_wordlists +from guard_classifier import DEFAULT_MODEL, make_backend, parse +from run_shard import Uploader + +GUARD_PASS_VERSION = "abeja-cc-ja-guard/2026-09-06" +DEFAULT_DELETE_CATEGORIES = ("Sexual Content or Sexual Acts", "Violent", "Suicide & Self-Harm", "Non-violent Illegal Acts", "Unethical Acts") +RECORD_ONLY_CATEGORIES = ("Politically Sensitive Topics", "Copyright Violation", "PII", "Jailbreak") + +_MATCHER: KeywordMatcher | None = None +_CONFIG: dict[str, Any] = {} + + +def _init_worker(config: dict[str, Any]) -> None: + global _MATCHER, _CONFIG + _CONFIG = config + wordlists = load_wordlists(Path(config["reference_dir"]), Path(config["additional_dir"]), Path(config["exclude_dir"])) + _MATCHER = KeywordMatcher(wordlists.terms, wordlists.sources) + + +def _fetch_with_retry(repo: str, path_in_repo: str, local_dir: Path, attempts: int = 6) -> Path: + from huggingface_hub import hf_hub_download + + last: Exception | None = None + for attempt in range(1, attempts + 1): + try: + return Path(hf_hub_download(repo, path_in_repo, repo_type="dataset", local_dir=str(local_dir))) + except Exception as error: # noqa: BLE001 + last = error + print(json.dumps({"event": "download_retry", "path": path_in_repo, "attempt": attempt, "error": repr(error)[:160]}), flush=True) + time.sleep(20 * attempt) + raise RuntimeError(f"download failed: {path_in_repo} ({last!r})") + + +def prepare_shard(task: dict[str, Any]) -> dict[str, Any]: + """ワーカー側: 入力 parquet を取得して辞書照合し、候補の本文を返す。""" + + assert _MATCHER is not None + started = time.perf_counter() + shard = task["shard"] + try: + if task.get("source_repo"): + local = _fetch_with_retry(task["source_repo"], task["path_in_repo"], Path(task["staging_dir"])) + else: + local = Path(task["input_path"]) + table = pq.read_table(local, columns=["url", "content", "perplexity"]) + urls = table.column("url").to_pylist() + contents = table.column("content").to_pylist() + min_terms = int(_CONFIG.get("min_terms", 1)) + candidate_categories = set(_CONFIG.get("candidate_categories") or CATEGORIES) + max_chars = int(_CONFIG.get("max_chars", 2000)) + candidates: list[dict[str, Any]] = [] + match_docs = Counter() + for index, (url, content) in enumerate(zip(urls, contents)): + content = content or "" + distinct = _distinct_terms_by_category(_MATCHER.match_record(url, content)) + if not distinct: + continue + for category in distinct: + match_docs[category] += 1 + total = sum(len(terms) for category, terms in distinct.items() if category in candidate_categories) + if total >= min_terms: + candidates.append({"record_index": index, "url": url, "text": content[:max_chars], + "matches": {category: len(terms) for category, terms in distinct.items()}}) + return {"shard": shard, "local_input": str(local), "staged": bool(task.get("source_repo")), "rows": table.num_rows, + "candidates": candidates, "match_docs_by_category": dict(match_docs), "prepare_seconds": round(time.perf_counter() - started, 1)} + except Exception as error: # noqa: BLE001 + return {"shard": shard, "error": repr(error), "traceback": traceback.format_exc()} + + +def classify_candidates(candidates: list[dict[str, Any]], backend: Any, chunk_size: int) -> None: + for start in range(0, len(candidates), chunk_size): + chunk = candidates[start : start + chunk_size] + raws = backend.classify([c["text"] for c in chunk]) + for candidate, raw in zip(chunk, raws): + safety, categories = parse(raw) + candidate["safety"] = safety + candidate["categories"] = categories + candidate["raw_output"] = (raw or "").strip() + + +def write_shard_outputs(prepared: dict[str, Any], output_root: Path, delete_categories: set[str], config: dict[str, Any], + classify_seconds: float) -> dict[str, Any]: + shard = prepared["shard"] + out_dir = output_root / shard + out_dir.mkdir(parents=True, exist_ok=True) + candidates = prepared["candidates"] + deleted_indices: set[int] = set() + by_safety = Counter() + deleted_by_category = Counter() + unsafe_kept_by_category = Counter() + controversial_by_category = Counter() + with (out_dir / "guard_results.jsonl").open("w", encoding="utf-8") as results, (out_dir / "guard_removed.jsonl").open("w", encoding="utf-8") as removed: + for c in candidates: + safety = c.get("safety") + categories = c.get("categories") or [] + by_safety[safety or "unparsed"] += 1 + delete = safety == "Unsafe" and any(cat in delete_categories for cat in categories) + if delete: + deleted_indices.add(c["record_index"]) + for cat in categories: + deleted_by_category[cat] += 1 + removed.write(json.dumps({"record_index": c["record_index"], "url": c["url"], "safety": safety, "categories": categories, + "dictionary_matches": c["matches"], "raw_output": c.get("raw_output", ""), + "excerpt": c["text"][:200]}, ensure_ascii=False) + "\n") + elif safety == "Unsafe": + for cat in categories or ["(none)"]: + unsafe_kept_by_category[cat] += 1 + elif safety == "Controversial": + for cat in categories or ["(none)"]: + controversial_by_category[cat] += 1 + results.write(json.dumps({"record_index": c["record_index"], "url": c["url"], "safety": safety, "categories": categories, + "dictionary_matches": c["matches"], "deleted": delete}, ensure_ascii=False) + "\n") + table = pq.read_table(prepared["local_input"], columns=["url", "content", "perplexity"]) + if deleted_indices: + keep = pa.array([i not in deleted_indices for i in range(table.num_rows)], type=pa.bool_()) + retained = table.filter(keep) + else: + retained = table + pq.write_table(retained, out_dir / f"{shard}.parquet", compression="zstd") + summary = { + "pipeline_version": GUARD_PASS_VERSION, "shard": shard, "stage": "guard", + "finished_at_utc": datetime.now(timezone.utc).isoformat(), + "input_rows": prepared["rows"], "candidates": len(candidates), "candidate_rate": round(len(candidates) / max(1, prepared["rows"]), 5), + "match_docs_by_category": prepared["match_docs_by_category"], + "by_safety": dict(by_safety), + "records_deleted": len(deleted_indices), "deletion_rate": round(len(deleted_indices) / max(1, prepared["rows"]), 6), + "deleted_by_category": dict(deleted_by_category), + "unsafe_kept_by_category": dict(unsafe_kept_by_category), + "controversial_by_category": dict(controversial_by_category), + "final_rows": retained.num_rows, + "seconds": {"prepare": prepared["prepare_seconds"], "classify": round(classify_seconds, 1)}, + "docs_per_s": round(len(candidates) / classify_seconds, 2) if classify_seconds > 0 else None, + "thresholds": {"min_terms": config["min_terms"], "candidate_categories": sorted(config["candidate_categories"] or CATEGORIES), + "delete_categories": sorted(delete_categories), "record_only_categories": list(RECORD_ONLY_CATEGORIES), + "max_chars": config["max_chars"], "model": config["model"], "backend": config["backend"]}, + } + (out_dir / "guard_summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + return summary + + +def discover_local(input_dir: Path) -> list[dict[str, Any]]: + nested = sorted(p for p in input_dir.glob("*/*.parquet") if p.stem == p.parent.name) + flat = sorted(p for p in input_dir.glob("*.parquet")) + return [{"shard": p.stem, "input_path": str(p)} for p in (nested or flat)] + + +def discover_repo(repo: str, prefix: str, dir_index: int, staging_dir: Path) -> list[dict[str, Any]]: + from huggingface_hub import HfApi + + api = HfApi() + base = f"{prefix}/common_crawl_{dir_index}" + for attempt in range(5): + try: + entries = list(api.list_repo_tree(repo, path_in_repo=base, repo_type="dataset", recursive=False)) + break + except Exception as error: # noqa: BLE001 + print(json.dumps({"event": "list_retry", "attempt": attempt + 1, "error": repr(error)[:160]}), flush=True) + time.sleep(30 * (attempt + 1)) + else: + raise RuntimeError("list_repo_tree failed") + shards = sorted(e.path.rsplit("/", 1)[-1] for e in entries if type(e).__name__ == "RepoFolder") + return [{"shard": s, "source_repo": repo, "path_in_repo": f"{base}/{s}/{s}.parquet", "staging_dir": str(staging_dir)} for s in shards] + + +def main(argv: list[str] | None = None) -> None: + source_dir = Path(__file__).resolve().parent + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + group = parser.add_mutually_exclusive_group(required=True) + group.add_argument("--input-dir", type=Path, help="第2パス出力のディレクトリ(/.parquet)") + group.add_argument("--source-repo", default=None, help="HF データセットから HTTP で取得する") + parser.add_argument("--source-prefix", default="outputs_v2") + parser.add_argument("--dir-index", type=int, default=None, help="--source-repo のとき common_crawl_N の N") + parser.add_argument("--staging-dir", type=Path, default=None) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--limit-shards", type=int, default=None) + parser.add_argument("--shard-index", type=int, default=0, help="この番号のシャードだけ処理(分割実行用、0 始まり)") + parser.add_argument("--shard-count", type=int, default=1) + parser.add_argument("--workers", type=int, default=max(1, min(6, (os.cpu_count() or 2) - 1)), help="辞書照合の並列数(先読み)") + parser.add_argument("--prefetch", type=int, default=3, help="分類中に先読みするシャード数") + parser.add_argument("--backend", choices=("vllm", "transformers", "fake", "none"), default="vllm") + parser.add_argument("--model", default=DEFAULT_MODEL) + parser.add_argument("--device", default="auto") + parser.add_argument("--max-chars", type=int, default=2000, help="分類器に渡す本文の先頭文字数") + parser.add_argument("--chunk-size", type=int, default=512) + parser.add_argument("--min-terms", type=int, default=1, help="候補とする辞書の異なり語数(全カテゴリ合計)") + parser.add_argument("--candidate-categories", default="", help="候補判定に使うカテゴリ(カンマ区切り、既定は全カテゴリ)") + parser.add_argument("--delete-categories", default=",".join(DEFAULT_DELETE_CATEGORIES), help="Unsafe のうち削除するカテゴリ(カンマ区切り)") + 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("--upload-repo", default=None) + parser.add_argument("--upload-prefix", default="outputs_v3") + parser.add_argument("--upload-batch", type=int, default=5) + parser.add_argument("--delete-local-after-upload", action="store_true") + parser.add_argument("--skip-existing-in-repo", action="store_true") + args = parser.parse_args(argv) + + if args.source_repo: + if args.dir_index is None: + raise SystemExit("--source-repo には --dir-index が必要です") + staging = args.staging_dir or (args.output_root / "_staging") + staging.mkdir(parents=True, exist_ok=True) + tasks = discover_repo(args.source_repo, args.source_prefix, args.dir_index, staging) + else: + tasks = discover_local(args.input_dir) + if args.shard_count > 1: + tasks = [t for i, t in enumerate(tasks) if i % args.shard_count == args.shard_index] + if args.limit_shards is not None: + tasks = tasks[: args.limit_shards] + if not tasks: + raise FileNotFoundError("入力シャードが見つかりません") + 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(marker="guard_summary.json") + todo = [t for t in tasks if t["shard"] not in skip and not (args.output_root / t["shard"] / "guard_summary.json").exists()] + config = { + "reference_dir": str(args.reference_dir), "additional_dir": str(args.additional_dir), "exclude_dir": str(args.exclude_dir), + "min_terms": args.min_terms, "candidate_categories": [c for c in args.candidate_categories.split(",") if c] or None, + "max_chars": args.max_chars, "model": args.model, "backend": args.backend, + } + delete_categories = {c.strip() for c in args.delete_categories.split(",") if c.strip()} + print(json.dumps({"event": "start", "stage": "guard", "shards": len(todo), "skipped": len(tasks) - len(todo), "workers": args.workers, + "backend": args.backend, "model": args.model, "min_terms": args.min_terms, "max_chars": args.max_chars, + "delete_categories": sorted(delete_categories)}, ensure_ascii=False), flush=True) + backend = None if args.backend == "none" else make_backend(args.backend, args.model, args.max_chars, args.device) + run_started = time.perf_counter() + results: list[dict[str, Any]] = [] + with ProcessPoolExecutor(max_workers=max(1, args.workers), initializer=_init_worker, initargs=(config,)) as pool: + pending: list[Future] = [] + queue = list(todo) + while queue and len(pending) < max(1, args.prefetch): + pending.append(pool.submit(prepare_shard, queue.pop(0))) + while pending: + future = pending.pop(0) + prepared = future.result() + if queue: + pending.append(pool.submit(prepare_shard, queue.pop(0))) + if "error" in prepared: + print(json.dumps({"event": "error", "shard": prepared["shard"], "error": prepared["error"]}), flush=True) + results.append(prepared) + continue + started = time.perf_counter() + if backend is not None and prepared["candidates"]: + classify_candidates(prepared["candidates"], backend, args.chunk_size) + classify_seconds = time.perf_counter() - started + summary = write_shard_outputs(prepared, args.output_root, delete_categories, config, classify_seconds) + if prepared.get("staged"): + Path(prepared["local_input"]).unlink(missing_ok=True) + results.append(summary) + print(json.dumps({"event": "done", "shard": summary["shard"], "input_rows": summary["input_rows"], "candidates": summary["candidates"], + "deleted": summary["records_deleted"], "by_safety": summary["by_safety"], "seconds": summary["seconds"], + "docs_per_s": summary["docs_per_s"]}, ensure_ascii=False), flush=True) + if uploader is not None: + uploader.add(summary["shard"]) + if uploader is not None: + uploader.flush() + errors = [r for r in results if "error" in r] + run_summary = { + "pipeline_version": GUARD_PASS_VERSION, "stage": "guard", "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(tasks) - 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_guard_{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 args.source_repo and args.staging_dir is None: + shutil.rmtree(args.output_root / "_staging", ignore_errors=True) + if errors: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/code/3c1a8da-dirty-0c72d075/src/run_noise_pass.py b/code/3c1a8da-dirty-0c72d075/src/run_noise_pass.py new file mode 100644 index 0000000000000000000000000000000000000000..061f7ab81989040f7f7c6855cc08893558816213 --- /dev/null +++ b/code/3c1a8da-dirty-0c72d075/src/run_noise_pass.py @@ -0,0 +1,260 @@ +"""ノイズ除去の第2パス(監査項目14〜21)。 + +第1パス(``run_shard.py``: 有害フィルタ → PII 置換)のクリーン済み出力 +``//.parquet`` を入力にし、``//`` に +``.parquet``(ノイズ除去後)、``noise/removed.jsonl``、``noise/summary.json``、 +``noise_summary.json`` を書く。``--upload-repo`` を付けると HF データセットへ +バッチアップロードしてローカルを削除する(HF Jobs の一時ディスク対策)。 + + uv run python abeja-cc-ja/src/run_noise_pass.py --input-dir --output-root --workers 7 \\ + --upload-repo Podtech/abeja-cc-ja-cleaned --upload-prefix outputs_v2/common_crawl_0 --delete-local-after-upload + +トークン数の閾値を使う場合は ``--tokenizer `` と ``--min-tokens/--max-tokens`` を指定する +(transformers が必要。既定は文字数のみ)。 +""" + +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 as pa +import pyarrow.parquet as pq + +from run_shard import Uploader, stage_input + + +NOISE_PASS_VERSION = "abeja-cc-ja-noise-pass/2026-09-04" +_WORKER: dict[str, Any] = {} + + +def _init_worker(config: dict[str, Any]) -> None: + import sys + + sys.path.insert(0, str(Path(__file__).resolve().parent)) + from doc_features import DocFeaturizer, LanguageDetector + from filter_noise import NoiseFilter + + _WORKER["config"] = config + lid = LanguageDetector(Path(config["lid_model"])) if config.get("lid_model") else None + _WORKER["filter"] = NoiseFilter( + Path(config["patterns_dir"]), + min_chars=config["min_chars"], max_chars=config["max_chars"], newline_policy=config["newline_policy"], + tokenizer=config.get("tokenizer"), min_tokens=config.get("min_tokens"), max_tokens=config.get("max_tokens"), + language_detector=lid, drop_non_japanese=config.get("drop_non_japanese", True), + ) + featurizer = DocFeaturizer(Path(config["genre_rules"]), None) + featurizer.lid = lid + _WORKER["featurizer"] = featurizer + + +def process_shard(input_path: Path, output_root: Path, config: dict[str, Any]) -> dict[str, Any]: + from filter_noise import run_noise_filter + + 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 + featurizer = _WORKER["featurizer"] + feature_rows: list[dict[str, Any]] = [] + + def on_record(row: dict[str, Any], result: Any, record_index: int) -> None: + status = "retained" if result.deleted_reason is None else f"deleted_noise:{result.deleted_reason}" + text = result.text if result.deleted_reason is None else (row.get("content") or "") + lang = (result.lang, result.lang_prob) if result.lang is not None else None + feature_rows.append(featurizer.features(row.get("url") or "", text, result.chars_before, status, record_index, row.get("perplexity"), lang)) + + summary = run_noise_filter(input_path, out_dir / "noise", _WORKER["filter"], batch_size=config["batch_size"], output_name="cleaned.parquet", on_record=on_record) + # 第1パスで有害フィルタにより削除された文書も、ジャンル別の削除率(項目27)のため特徴量を出す + toxic_removed = Path(config.get("source_dir") or input_path.parent) / "toxic" / "distinct_terms_3plus" / "removed.jsonl" + toxic_count = 0 + if toxic_removed.exists(): + with toxic_removed.open(encoding="utf-8") as handle: + for line in handle: + if not line.strip(): + continue + record = json.loads(line) + content = record.get("content") or "" + reasons = "+".join(record.get("_filter_deleted_by") or []) + feature_rows.append(featurizer.features(record.get("url") or "", content, len(content), f"deleted_toxic:{reasons}", record.get("_filter_record_index", -1), record.get("perplexity"))) + toxic_count += 1 + if feature_rows: + pq.write_table(pa.Table.from_pylist(feature_rows), out_dir / "features.parquet", compression="zstd") + final_path = out_dir / f"{shard}.parquet" + shutil.move(str(out_dir / "noise" / "cleaned.parquet"), str(final_path)) + shard_summary = { + "pipeline_version": NOISE_PASS_VERSION, + "stage": "noise", + "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": round(time.perf_counter() - started, 1), + "noise": { + "thresholds": summary["thresholds"], + "records_scanned": summary["records_scanned"], + "records_deleted": summary["records_deleted"], + "records_retained": summary["records_retained"], + "records_modified": summary["records_modified"], + "records_newline_joined": summary["records_newline_joined"], + "records_deleted_by_reason": summary["records_deleted_by_reason"], + "chars_before": summary["chars_before"], + "chars_after_retained": summary["chars_after_retained"], + "tokens_after_retained": summary["tokens_after_retained"], + "by_item": summary["by_item"], + "patterns": [ + {k: p[k] for k in ("id", "item", "action", "records_detected", "occurrences", "lines_removed", "replacements")} + for p in summary["patterns"] + ], + }, + "features": { + "file": str(out_dir / "features.parquet"), "rows": len(feature_rows), "toxic_deleted_rows": toxic_count, + "describe": featurizer.describe(), + }, + "output": {"cleaned_parquet": str(final_path), "final_rows": summary["records_retained"], "removed_jsonl": str(out_dir / "noise" / "removed.jsonl")}, + } + (out_dir / "noise_summary.json").write_text(json.dumps(shard_summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + return shard_summary + + +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) + # 有害フィルタの removed.jsonl は元のディレクトリから読むため、入力の場所を config で渡す + result = process_shard(local_input, Path(output_root), {**config, "source_dir": str(Path(input_path).parent)}) + result["input_file"] = input_path + return result + except OSError as error: + 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 + 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": ""} + + +def discover_inputs(input_dir: Path) -> list[Path]: + """``//.parquet``(第1パス出力)か ``/*.parquet`` を列挙する。""" + + nested = sorted(p for p in input_dir.glob("*/*.parquet") if p.stem == p.parent.name) + return nested or sorted(input_dir.glob("*.parquet")) + + +def main(argv: list[str] | None = None) -> None: + source_dir = Path(__file__).resolve().parent + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--input-dir", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--limit-shards", type=int, default=None) + 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("--patterns-dir", type=Path, default=source_dir / "noise") + parser.add_argument("--min-chars", type=int, default=200) + parser.add_argument("--max-chars", type=int, default=100_000) + parser.add_argument("--newline-policy", choices=("join", "delete", "keep"), default="join") + parser.add_argument("--tokenizer", default=None, help="トークン数を数える HF トークナイザ名(任意)") + parser.add_argument("--lid-model", type=Path, default=source_dir.parent / "data" / "models" / "lid.176.ftz", help="fastText 言語判定モデル。無ければ言語判定を行わない") + parser.add_argument("--keep-non-japanese", action="store_true", help="日本語以外と判定された文書を削除しない(記録のみ)") + parser.add_argument("--genre-rules", type=Path, default=source_dir / "wordlists" / "genre" / "genre_rules.json") + parser.add_argument("--min-tokens", type=int, default=None) + parser.add_argument("--max-tokens", type=int, default=None) + parser.add_argument("--upload-repo", default=None) + parser.add_argument("--upload-prefix", default="outputs_v2") + parser.add_argument("--upload-batch", type=int, default=5) + parser.add_argument("--delete-local-after-upload", action="store_true") + parser.add_argument("--skip-existing-in-repo", action="store_true") + parser.add_argument("--staging-dir", type=Path, default=None, help="入力parquetを処理前にコピーするローカルディレクトリ(マウントの I/O エラー対策)") + args = parser.parse_args(argv) + + inputs = discover_inputs(args.input_dir) + if args.limit_shards is not None: + inputs = inputs[: args.limit_shards] + if not inputs: + raise FileNotFoundError(f"入力parquetが見つかりません: {args.input_dir}") + 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(marker="noise_summary.json") + todo = [] + for path in inputs: + if path.stem in skip or (args.output_root / path.stem / "noise_summary.json").exists(): + print(json.dumps({"event": "skip", "shard": path.stem}), flush=True) + continue + todo.append(path) + config = { + "patterns_dir": str(args.patterns_dir), "batch_size": args.batch_size, + "min_chars": args.min_chars, "max_chars": args.max_chars, "newline_policy": args.newline_policy, + "tokenizer": args.tokenizer, "min_tokens": args.min_tokens, "max_tokens": args.max_tokens, + "lid_model": str(args.lid_model) if args.lid_model and args.lid_model.exists() else None, + "drop_non_japanese": not args.keep_non_japanese, "genre_rules": str(args.genre_rules), + "staging_dir": str(args.staging_dir) if args.staging_dir else None, + } + if config["lid_model"] is None: + print(json.dumps({"event": "warning", "message": f"言語判定モデルが見つからないため項目25の判定を行いません: {args.lid_model}"}, ensure_ascii=False), flush=True) + print(json.dumps({"event": "start", "stage": "noise", "shards": len(todo), "skipped": len(inputs) - len(todo), "workers": args.workers, "thresholds": config}, ensure_ascii=False), flush=True) + jobs = [(str(p), str(args.output_root), config) for p in todo] + if args.workers <= 1 or len(jobs) <= 1: + _init_worker(config) + iterator = map(_worker_entry, jobs) + else: + 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) + results: list[dict[str, Any]] = [] + run_started = time.perf_counter() + 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"], + "noise_deleted": result["noise"]["records_deleted"], "modified": result["noise"]["records_modified"], + "final_rows": result["output"]["final_rows"], "seconds": result["seconds"], + }), 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": NOISE_PASS_VERSION, "stage": "noise", + "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_noise_{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() diff --git a/code/3c1a8da-dirty-0c72d075/src/run_quality_pass.py b/code/3c1a8da-dirty-0c72d075/src/run_quality_pass.py new file mode 100644 index 0000000000000000000000000000000000000000..4dc34b7b76f7c486fd9d3bd1b3172166c44b497a --- /dev/null +++ b/code/3c1a8da-dirty-0c72d075/src/run_quality_pass.py @@ -0,0 +1,335 @@ +"""第4パス: 低品質フラグ付き文書と除外ジャンル(EC 商品ページ・アフィリエイト)を削除する(CPT 用の品質絞り込み)。 + +背景: 品質レポート(項目28・29)では、保持文書の 26.7% が低品質フラグ(500字未満・販促定型・平均行長20字未満 等)に +該当し、EC 商品ページとアフィリエイトのジャンルは半分以上が低品質だった。2026-09-06 の方針(案 D)で、 +低品質フラグのいずれかに該当する文書と、この 2 ジャンルの文書全体を削除する。 + +入力は第3パスの出力(``/common_crawl_N//.parquet``、列 url/content/perplexity)と、 +第2パスが文書ごとに残した特徴量(``/common_crawl_N//features.parquet``、 +列 content_sha1/genre/genre_score/is_low_quality/low_quality_flags/status)。本文の SHA-1 で突き合わせる。 +特徴量に無い文書(想定外)は doc_features.py で再計算して判定し、件数を記録する。 + +出力(シャードごと): ``.parquet``(保持文書)、``quality_removed.jsonl``(削除文書の URL・ジャンル・フラグ)、 +``quality_summary.json``(件数・文字数・トークン数)。``--tokenizer o200k_harmony`` で gpt-oss のトークン数も数える。 + + uv run python abeja-cc-ja/src/run_quality_pass.py --input-dir <第3パス出力/common_crawl_0> --features-dir <第2パス出力/common_crawl_0> --output-root out --limit-shards 1 +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import shutil +import time +import traceback +from concurrent.futures import ProcessPoolExecutor +from collections import Counter +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pyarrow.parquet as pq + +from run_shard import Uploader + +QUALITY_PASS_VERSION = "abeja-cc-ja-quality/2026-09-06" +DEFAULT_EXCLUDE_GENRES = ("ec_product", "affiliate") +LOW_QUALITY_FLAGS = ("short_lt500", "symbol_digit_ratio_gt30", "line_repetition_gt30", "avg_line_len_lt20", "template_commerce", "low_lid_confidence") +FEATURE_COLUMNS = ["status", "content_sha1", "genre", "genre_score", "is_low_quality", "low_quality_flags"] + +_CONFIG: dict[str, Any] = {} +_ENCODING: Any = None +_FEATURIZER: Any = None + + +def _init_worker(config: dict[str, Any]) -> None: + global _CONFIG + _CONFIG = config + + +def _encoding() -> Any: + """tiktoken のエンコーディング。取得できなければ None(トークン数は記録しない)。""" + + global _ENCODING + name = _CONFIG.get("tokenizer") or "" + if not name: + return None + if _ENCODING is None: + try: + import tiktoken + + _ENCODING = tiktoken.get_encoding(name) + except Exception as error: # noqa: BLE001 + print(json.dumps({"event": "tokenizer_unavailable", "tokenizer": name, "error": repr(error)[:160]}), flush=True) + _ENCODING = False + return _ENCODING or None + + +def _featurizer() -> Any: + global _FEATURIZER + if _FEATURIZER is None: + from doc_features import DocFeaturizer + + _FEATURIZER = DocFeaturizer(Path(_CONFIG["genre_rules"])) + return _FEATURIZER + + +def _fetch_with_retry(repo: str, path_in_repo: str, local_dir: Path, attempts: int = 6) -> Path: + from huggingface_hub import hf_hub_download + + last: Exception | None = None + for attempt in range(1, attempts + 1): + try: + return Path(hf_hub_download(repo, path_in_repo, repo_type="dataset", local_dir=str(local_dir))) + except Exception as error: # noqa: BLE001 + last = error + print(json.dumps({"event": "download_retry", "path": path_in_repo, "attempt": attempt, "error": repr(error)[:160]}), flush=True) + time.sleep(20 * attempt) + raise RuntimeError(f"download failed: {path_in_repo} ({last!r})") + + +def load_feature_map(path: Path) -> dict[str, tuple[str, float, bool, str]]: + """content_sha1 → (genre, genre_score, is_low_quality, low_quality_flags)。保持文書だけを対象にする。""" + + table = pq.read_table(path, columns=FEATURE_COLUMNS) + result: dict[str, tuple[str, float, bool, str]] = {} + columns = [table.column(name).to_pylist() for name in FEATURE_COLUMNS] + for status, sha1, genre, score, low, flags in zip(*columns): + if status != "retained" or not sha1 or sha1 in result: + continue + result[sha1] = (genre or "other", float(score or 0.0), bool(low), flags or "") + return result + + +def decide(genre: str, is_low_quality: bool, flags: str, exclude_genres: set[str], selected_flags: set[str]) -> list[str]: + reasons: list[str] = [] + flag_list = [f for f in flags.split("|") if f] + if is_low_quality and (not selected_flags or any(f in selected_flags for f in flag_list)): + reasons.append("low_quality") + if genre in exclude_genres: + reasons.append(f"genre:{genre}") + return reasons + + +def process_shard(task: dict[str, Any]) -> dict[str, Any]: + started = time.perf_counter() + shard = task["shard"] + output_root = Path(task["output_root"]) + try: + if task.get("source_repo"): + staging = Path(task["staging_dir"]) + local_input = _fetch_with_retry(task["source_repo"], task["input_path_in_repo"], staging) + local_features = _fetch_with_retry(task["source_repo"], task["features_path_in_repo"], staging) + else: + local_input = Path(task["input_path"]) + local_features = Path(task["features_path"]) + exclude_genres = set(_CONFIG.get("exclude_genres") or []) + selected_flags = set(_CONFIG.get("low_quality_flags") or []) + drop_low_quality = bool(_CONFIG.get("drop_low_quality", True)) + if not drop_low_quality: + selected_flags = {"__none__"} # どのフラグにも一致しない → 低品質では削除しない + + table = pq.read_table(local_input, columns=["url", "content", "perplexity"]) + urls = table.column("url").to_pylist() + contents = table.column("content").to_pylist() + features = load_feature_map(local_features) if local_features.exists() else {} + encoding = _encoding() + token_counts: list[int] | None = None + if encoding is not None: + token_counts = [len(t) for t in encoding.encode_ordinary_batch([c or "" for c in contents], num_threads=int(_CONFIG.get("token_threads", 2)))] + + keep_mask: list[bool] = [] + by_reason = Counter() + deleted_by_flag = Counter() + deleted_by_genre = Counter() + retained_by_genre = Counter() + feature_source = Counter() + chars = Counter() + tokens = Counter() + out_dir = output_root / shard + out_dir.mkdir(parents=True, exist_ok=True) + with (out_dir / "quality_removed.jsonl").open("w", encoding="utf-8") as removed: + for index, (url, content) in enumerate(zip(urls, contents)): + content = content or "" + sha1 = hashlib.sha1(content.encode("utf-8")).hexdigest() if content else "" + feat = features.get(sha1) + if feat is None: + f = _featurizer().features(url or "", content, len(content), "retained", index, lang=("ja", 1.0)) + feat = (f["genre"], float(f["genre_score"]), bool(f["is_low_quality"]), f["low_quality_flags"]) + feature_source["recomputed"] += 1 + else: + feature_source["matched"] += 1 + genre, score, low, flags = feat + reasons = decide(genre, low, flags, exclude_genres, selected_flags) + n_chars = len(content) + n_tokens = token_counts[index] if token_counts is not None else 0 + chars["input"] += n_chars + tokens["input"] += n_tokens + if reasons: + keep_mask.append(False) + key = "both" if len(reasons) > 1 else ("low_quality" if reasons[0] == "low_quality" else "genre") + by_reason[key] += 1 + deleted_by_genre[genre] += 1 + for flag in (flags.split("|") if flags else []): + deleted_by_flag[flag] += 1 + chars["deleted"] += n_chars + tokens["deleted"] += n_tokens + removed.write(json.dumps({"record_index": index, "url": url, "genre": genre, "genre_score": round(score, 3), + "low_quality_flags": flags, "chars": n_chars, "content_sha1": sha1, "reasons": reasons}, ensure_ascii=False) + "\n") + else: + keep_mask.append(True) + retained_by_genre[genre] += 1 + chars["final"] += n_chars + tokens["final"] += n_tokens + retained = table.filter(pa.array(keep_mask, type=pa.bool_())) if len(keep_mask) == table.num_rows and not all(keep_mask) else table + pq.write_table(retained, out_dir / f"{shard}.parquet", compression="zstd") + deleted = table.num_rows - retained.num_rows + summary = { + "pipeline_version": QUALITY_PASS_VERSION, "shard": shard, "stage": "quality", + "finished_at_utc": datetime.now(timezone.utc).isoformat(), + "input_rows": table.num_rows, "records_deleted": deleted, "deletion_rate": round(deleted / max(1, table.num_rows), 6), + "final_rows": retained.num_rows, + "records_deleted_by_reason": dict(by_reason), + "deleted_by_flag": dict(deleted_by_flag), "deleted_by_genre": dict(deleted_by_genre), "retained_by_genre": dict(retained_by_genre), + "chars": dict(chars), + "tokens": ({"tokenizer": _CONFIG.get("tokenizer"), **dict(tokens)} if token_counts is not None else None), + "features": dict(feature_source), + "thresholds": {"exclude_genres": sorted(exclude_genres), "drop_low_quality": drop_low_quality, + "low_quality_flags": sorted(selected_flags) if drop_low_quality and selected_flags else list(LOW_QUALITY_FLAGS), + "definition_ja": "低品質フラグのいずれかに該当する文書、および除外ジャンルの文書を削除(項目28・29)"}, + "seconds": {"total": round(time.perf_counter() - started, 1)}, + } + (out_dir / "quality_summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + if task.get("source_repo"): + local_input.unlink(missing_ok=True) + local_features.unlink(missing_ok=True) + return summary + except Exception as error: # noqa: BLE001 + return {"shard": shard, "error": repr(error), "traceback": traceback.format_exc()} + + +def discover_local(input_dir: Path, features_dir: Path, output_root: Path) -> list[dict[str, Any]]: + nested = sorted(p for p in input_dir.glob("*/*.parquet") if p.stem == p.parent.name) + return [{"shard": p.stem, "input_path": str(p), "features_path": str(features_dir / p.stem / "features.parquet"), "output_root": str(output_root)} for p in nested] + + +def discover_repo(repo: str, prefix: str, features_prefix: str, dir_index: int, staging_dir: Path, output_root: Path) -> list[dict[str, Any]]: + from huggingface_hub import HfApi + + api = HfApi() + base = f"{prefix}/common_crawl_{dir_index}" + for attempt in range(5): + try: + entries = list(api.list_repo_tree(repo, path_in_repo=base, repo_type="dataset", recursive=False)) + break + except Exception as error: # noqa: BLE001 + print(json.dumps({"event": "list_retry", "attempt": attempt + 1, "error": repr(error)[:160]}), flush=True) + time.sleep(30 * (attempt + 1)) + else: + raise RuntimeError("list_repo_tree failed") + shards = sorted(e.path.rsplit("/", 1)[-1] for e in entries if type(e).__name__ == "RepoFolder") + return [{"shard": s, "source_repo": repo, "input_path_in_repo": f"{base}/{s}/{s}.parquet", + "features_path_in_repo": f"{features_prefix}/common_crawl_{dir_index}/{s}/features.parquet", + "staging_dir": str(staging_dir), "output_root": str(output_root)} for s in shards] + + +def main(argv: list[str] | None = None) -> None: + source_dir = Path(__file__).resolve().parent + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + group = parser.add_mutually_exclusive_group(required=True) + group.add_argument("--input-dir", type=Path, help="第3パス出力のディレクトリ(/.parquet)") + group.add_argument("--source-repo", default=None, help="HF データセットから HTTP で取得する") + parser.add_argument("--features-dir", type=Path, default=None, help="--input-dir のとき、第2パスの特徴量ディレクトリ(/features.parquet)") + parser.add_argument("--source-prefix", default="outputs_v3") + parser.add_argument("--features-prefix", default="outputs_v2") + parser.add_argument("--dir-index", type=int, default=None, help="--source-repo のとき common_crawl_N の N") + parser.add_argument("--staging-dir", type=Path, default=None) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--limit-shards", type=int, default=None) + parser.add_argument("--shard-index", type=int, default=0) + parser.add_argument("--shard-count", type=int, default=1) + parser.add_argument("--workers", type=int, default=max(1, int(os.environ.get("CPU_CORES") or os.cpu_count() or 2) - 1), + help="シャード並列数。既定はジョブの CPU_CORES - 1(無ければ os.cpu_count() - 1)。コンテナは cpu_count を実際より大きく報告することがある") + parser.add_argument("--exclude-genres", default=",".join(DEFAULT_EXCLUDE_GENRES), help="削除するジャンル(カンマ区切り、空なら削除しない)") + parser.add_argument("--keep-low-quality", action="store_true", help="低品質フラグでは削除しない(ジャンル除外だけ行う)") + parser.add_argument("--low-quality-flags", default="", help="削除に使うフラグをカンマ区切りで限定(既定は全フラグ)") + parser.add_argument("--tokenizer", default="o200k_harmony", help="tiktoken のエンコーディング名(空なら数えない)") + parser.add_argument("--token-threads", type=int, default=2) + parser.add_argument("--genre-rules", type=Path, default=source_dir / "wordlists" / "genre" / "genre_rules.json") + parser.add_argument("--upload-repo", default=None) + parser.add_argument("--upload-prefix", default="outputs_v4") + parser.add_argument("--upload-batch", type=int, default=5) + parser.add_argument("--delete-local-after-upload", action="store_true") + parser.add_argument("--skip-existing-in-repo", action="store_true") + args = parser.parse_args(argv) + + args.output_root.mkdir(parents=True, exist_ok=True) + if args.source_repo: + if args.dir_index is None: + raise SystemExit("--source-repo には --dir-index が必要です") + staging = args.staging_dir or (args.output_root / "_staging") + staging.mkdir(parents=True, exist_ok=True) + tasks = discover_repo(args.source_repo, args.source_prefix, args.features_prefix, args.dir_index, staging, args.output_root) + else: + if args.features_dir is None: + raise SystemExit("--input-dir には --features-dir が必要です") + tasks = discover_local(args.input_dir, args.features_dir, args.output_root) + if args.shard_count > 1: + tasks = [t for i, t in enumerate(tasks) if i % args.shard_count == args.shard_index] + if args.limit_shards is not None: + tasks = tasks[: args.limit_shards] + if not tasks: + raise FileNotFoundError("入力シャードが見つかりません") + 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(marker="quality_summary.json") + todo = [t for t in tasks if t["shard"] not in skip and not (args.output_root / t["shard"] / "quality_summary.json").exists()] + config = { + "exclude_genres": [g.strip() for g in args.exclude_genres.split(",") if g.strip()], + "drop_low_quality": not args.keep_low_quality, + "low_quality_flags": [f.strip() for f in args.low_quality_flags.split(",") if f.strip()], + "tokenizer": args.tokenizer, "token_threads": args.token_threads, "genre_rules": str(args.genre_rules), + } + print(json.dumps({"event": "start", "stage": "quality", "shards": len(todo), "skipped": len(tasks) - len(todo), "workers": args.workers, + "exclude_genres": config["exclude_genres"], "drop_low_quality": config["drop_low_quality"], + "low_quality_flags": config["low_quality_flags"] or list(LOW_QUALITY_FLAGS), "tokenizer": args.tokenizer}, ensure_ascii=False), flush=True) + run_started = time.perf_counter() + results: list[dict[str, Any]] = [] + workers = max(1, min(args.workers, len(todo))) if todo else 1 + with ProcessPoolExecutor(max_workers=workers, initializer=_init_worker, initargs=(config,)) as pool: + for summary in pool.map(process_shard, todo): + results.append(summary) + if "error" in summary: + print(json.dumps({"event": "error", "shard": summary["shard"], "error": summary["error"]}), flush=True) + continue + print(json.dumps({"event": "done", "shard": summary["shard"], "input_rows": summary["input_rows"], "deleted": summary["records_deleted"], + "final_rows": summary["final_rows"], "by_reason": summary["records_deleted_by_reason"], + "tokens_final": (summary["tokens"] or {}).get("final"), "seconds": summary["seconds"]["total"]}, ensure_ascii=False), flush=True) + if uploader is not None: + uploader.add(summary["shard"]) + if uploader is not None: + uploader.flush() + errors = [r for r in results if "error" in r] + run_summary = { + "pipeline_version": QUALITY_PASS_VERSION, "stage": "quality", "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(tasks) - 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_quality_{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 args.source_repo and args.staging_dir is None: + shutil.rmtree(args.output_root / "_staging", ignore_errors=True) + if errors: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/code/3c1a8da-dirty-0c72d075/src/run_shard.py b/code/3c1a8da-dirty-0c72d075/src/run_shard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dd06c5a326687b2963e8fa2f79c196b4b9e0a5b --- /dev/null +++ b/code/3c1a8da-dirty-0c72d075/src/run_shard.py @@ -0,0 +1,368 @@ +"""シャード単位のクレンジングパイプライン(本実行用)。 + +1ファイル(parquet)ごとに次を行う。 + +1. 有害コンテンツフィルタ(ワードリスト・ドメインブロックリスト・近接共起規則) +2. 保持分に PII 置換 +3. クリーン済み parquet と監査ファイル(removed.jsonl, audit.jsonl 等)を + ``/<シャード名>/`` に書き出し、``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 --output-root --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() diff --git a/code/3c1a8da-dirty-0c72d075/src/sample_for_review.py b/code/3c1a8da-dirty-0c72d075/src/sample_for_review.py new file mode 100644 index 0000000000000000000000000000000000000000..c8571dec292b5a263ab33371c5d1f4e3aeed82d8 --- /dev/null +++ b/code/3c1a8da-dirty-0c72d075/src/sample_for_review.py @@ -0,0 +1,177 @@ +"""目視確認と分類器用のサンプルを層別に抽出する(監査の第3手法の入口)。 + +有害フィルタの出力(summary.json, removed.jsonl, borderline.jsonl, +cooccurrence_review.jsonl)と元の入力parquetから、次の層でサンプルを取る。 + +* ``deleted:`` ワードリストで削除した文書(カテゴリ別、既定30件) +* ``deleted:domain_blocklist`` ドメインブロックリストで削除した文書(既定30件) +* ``cooccurrence:`` 近接共起規則の一致(規則ごとに既定100件。一致文書は全件削除される) +* ``borderline:`` しきい値に1語足りず保持された文書(カテゴリ別、既定30件) +* ``retained:random`` 保持文書の無作為抽出(既定100件。見逃し率の推定に使う) + +出力は ``review_samples.csv``(人が判定を記入する)と ``review_samples.jsonl`` +(``classify_qwen3guard.py`` の入力)。抽出条件は ``sampling_manifest.json`` に残す。 +""" + +from __future__ import annotations + +import argparse +import csv +import json +import random +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +import pyarrow.parquet as pq + +from filter_toxic import CATEGORIES, KeywordMatcher, load_wordlists +from textmatch import normalize + + +CSV_COLUMNS = [ + "sample_id", "stratum", "category", "record_index", "url", "matched_terms", + "excerpt", "reviewer", "verdict", "reason", "reviewed_at", +] + + +def _read_jsonl(path: Path) -> list[dict[str, Any]]: + if not path.exists(): + return [] + with path.open(encoding="utf-8") as handle: + return [json.loads(line) for line in handle if line.strip()] + + +def _excerpt(text: str, positions: list[int], length: int = 300) -> str: + if not text: + return "" + if positions: + start = max(0, positions[0] - length // 3) + else: + start = 0 + return text[start:start + length].replace("\n", " ") + + +def main(argv: list[str] | None = None) -> None: + source_dir = Path(__file__).resolve().parent + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--input", type=Path, required=True, help="元の入力parquet") + parser.add_argument("--output-root", type=Path, required=True, help="main_toxic.py の --output-root") + parser.add_argument("--mode", default="distinct_terms_3plus") + parser.add_argument("--dest", type=Path, required=True, help="サンプルの出力先ディレクトリ") + parser.add_argument("--seed", type=int, default=20260904) + parser.add_argument("--deleted-per-category", type=int, default=30) + parser.add_argument("--deleted-domain", type=int, default=30) + parser.add_argument("--borderline-per-category", type=int, default=30) + parser.add_argument("--random-retained", type=int, default=100) + parser.add_argument("--cooccurrence-limit", type=int, default=100, help="共起規則ごとの抽出上限(既定100。全件にするには 0)") + parser.add_argument("--text-chars", type=int, default=4000, help="JSONLに含める本文の最大文字数") + 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") + args = parser.parse_args(argv) + rng = random.Random(args.seed) + mode_dir = args.output_root / args.mode + summary = json.loads((mode_dir / "summary.json").read_text(encoding="utf-8")) + threshold = summary["threshold"] + removed = _read_jsonl(mode_dir / "removed.jsonl") + borderline = _read_jsonl(mode_dir / "borderline.jsonl") + cooccurrence = _read_jsonl(mode_dir / "cooccurrence_review.jsonl") + removed_indices = {record["_filter_record_index"] for record in removed} + row_range = summary["row_range"] + + samples: list[dict[str, Any]] = [] + + def add(stratum: str, category: str, record_index: int, url: str, terms: list[str], text: str, positions: list[int]) -> None: + samples.append({ + "stratum": stratum, "category": category, "record_index": record_index, "url": url, + "matched_terms": terms, "text": text, "match_positions": positions, + }) + + # 削除文書(ワードリスト) + for category in CATEGORIES: + pool = [r for r in removed if category in r["_filter_deleted_categories"]] + for record in rng.sample(pool, min(args.deleted_per_category, len(pool))): + terms = record["_filter_distinct_matched_terms_by_category"].get(category, []) + text = normalize(record.get("content") or "") + positions = sorted(p for t in terms for p in [text.find(t)] if p >= 0) + add(f"deleted:{category}", category, record["_filter_record_index"], record.get("url") or "", terms, text, positions) + # 削除文書(ドメインブロックリスト) + pool = [r for r in removed if "domain_blocklist" in r.get("_filter_deleted_by", [])] + for record in rng.sample(pool, min(args.deleted_domain, len(pool))): + sources = sorted({m["source"] + "=" + m["matched"] for m in record.get("_filter_domain_matches", [])}) + add("deleted:domain_blocklist", "domain_blocklist", record["_filter_record_index"], record.get("url") or "", sources, + normalize(record.get("content") or ""), []) + # 共起規則(既定は全件) + by_rule: dict[str, list[dict[str, Any]]] = {} + for item in cooccurrence: + by_rule.setdefault(item["rule"], []).append(item) + removed_by_index = {r["_filter_record_index"]: r for r in removed} + for rule, items in by_rule.items(): + chosen = items if not args.cooccurrence_limit else rng.sample(items, min(args.cooccurrence_limit, len(items))) + for item in chosen: + record = removed_by_index.get(item["record_index"], {}) + text = normalize(record.get("content") or "") + positions = [pair["position"] for pair in item["pairs"][:4]] + pairs = [f"{pair['a']}×{pair['b']}" for pair in item["pairs"][:5]] + add(f"cooccurrence:{rule}", item.get("label_ja", rule), item["record_index"], item.get("url") or "", pairs, text, positions) + + # 保持文書は入力parquetから本文を取る + needed: dict[int, list[tuple[str, str, list[str]]]] = {} + for category in CATEGORIES: + pool = [b for b in borderline if category in b["categories"]] + for record in rng.sample(pool, min(args.borderline_per_category, len(pool))): + needed.setdefault(record["record_index"], []).append((f"borderline:{category}", category, record["categories"][category])) + retained_pool = [i for i in range(row_range["start_row_inclusive"], row_range["end_row_exclusive"]) if i not in removed_indices] + for record_index in rng.sample(retained_pool, min(args.random_retained, len(retained_pool))): + needed.setdefault(record_index, []).append(("retained:random", "random", [])) + if needed: + table = pq.read_table(args.input, columns=["url", "content"]) + wordlists = load_wordlists(args.reference_dir, args.additional_dir, args.exclude_dir) + matcher = KeywordMatcher(wordlists.terms, wordlists.sources) + for record_index, entries in sorted(needed.items()): + row = table.slice(record_index, 1).to_pylist()[0] + text = normalize(row.get("content") or "") + positions = sorted({found.start() for found in matcher.pattern.finditer(text)})[:8] + for stratum, category, terms in entries: + add(stratum, category, record_index, row.get("url") or "", terms, text, positions) + + args.dest.mkdir(parents=True, exist_ok=True) + with (args.dest / "review_samples.csv").open("w", encoding="utf-8", newline="") as handle: + writer = csv.DictWriter(handle, fieldnames=CSV_COLUMNS) + writer.writeheader() + for number, sample in enumerate(samples, start=1): + sample_id = f"S{number:05d}" + sample["sample_id"] = sample_id + writer.writerow({ + "sample_id": sample_id, "stratum": sample["stratum"], "category": sample["category"], + "record_index": sample["record_index"], "url": sample["url"], + "matched_terms": " | ".join(sample["matched_terms"]), + "excerpt": _excerpt(sample["text"], sample["match_positions"]), + "reviewer": "", "verdict": "", "reason": "", "reviewed_at": "", + }) + with (args.dest / "review_samples.jsonl").open("w", encoding="utf-8") as handle: + for sample in samples: + handle.write(json.dumps({ + "id": sample["sample_id"], "stratum": sample["stratum"], "category": sample["category"], + "record_index": sample["record_index"], "url": sample["url"], "matched_terms": sample["matched_terms"], + "match_positions": sample["match_positions"], "text": sample["text"][:args.text_chars], + }, ensure_ascii=False, separators=(",", ":")) + "\n") + strata: dict[str, int] = {} + for sample in samples: + strata[sample["stratum"]] = strata.get(sample["stratum"], 0) + 1 + manifest = { + "created_at_utc": datetime.now(timezone.utc).isoformat(), + "input": str(args.input), "output_root": str(args.output_root), "mode": args.mode, "seed": args.seed, + "sizes": {"deleted_per_category": args.deleted_per_category, "deleted_domain": args.deleted_domain, + "borderline_per_category": args.borderline_per_category, "random_retained": args.random_retained, + "cooccurrence_limit": args.cooccurrence_limit}, + "threshold": threshold, "strata": strata, "total_samples": len(samples), + "verdict_values": ["harmful", "not_harmful", "unsure"], + } + (args.dest / "sampling_manifest.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + print(json.dumps({"total_samples": len(samples), "strata": strata}, ensure_ascii=False)) + + +if __name__ == "__main__": + main() diff --git a/code/3c1a8da-dirty-0c72d075/src/textmatch.py b/code/3c1a8da-dirty-0c72d075/src/textmatch.py new file mode 100644 index 0000000000000000000000000000000000000000..35cfd7de4ee78c7a6a9ebdc5f76f97353af87bf6 --- /dev/null +++ b/code/3c1a8da-dirty-0c72d075/src/textmatch.py @@ -0,0 +1,98 @@ +"""ワードリスト照合の共通部品。正規化、語リストの読み込み、境界付きトライ正規表現。 + +``filter_toxic.py`` と ``cooccurrence.py`` の両方から使うため、循環importを +避けて独立モジュールに置く。 +""" + +from __future__ import annotations + +import re +import unicodedata +from pathlib import Path +from typing import Any + + +ASCII_EDGE = "[a-z0-9]" +KATAKANA_EDGE = "[ァ-ヶー]" + + +def normalize(value: Any) -> str: + """ワードリストと本文を同じNFKC・小文字化規則で正規化する。""" + + if value is None: + return "" + return unicodedata.normalize("NFKC", str(value)).lower() + + +def read_terms(path: Path) -> list[str]: + """1行1語のリストを読み、正規化する。空行と``#``始まりの行は無視する。""" + + if not path.exists(): + return [] + terms: list[str] = [] + for raw_line in path.read_text(encoding="utf-8").splitlines(): + term = normalize(raw_line.strip()) + if term and not term.startswith("#"): + terms.append(term) + return terms + + +def _edge_class(character: str) -> str | None: + """語の端の文字種。ASCII英数字とカタカナだけを境界判定の対象にする。""" + + if re.fullmatch(ASCII_EDGE, character): + return ASCII_EDGE + if re.fullmatch(KATAKANA_EDGE, character): + return KATAKANA_EDGE + return None + + +def compile_trie_pattern(terms: list[str], boundaries: bool = True) -> re.Pattern[str]: + """多数語を共通接頭辞付き正規表現へコンパイルする。 + + ``boundaries`` が真のとき、語の端がASCII英数字なら英数字が隣接する位置、 + 端がカタカナならカタカナ(長音を含む)が隣接する位置では一致させない。 + 「メイク」中の「イク」、「DVD」中の「dv」のような単語内部の部分一致を + 防ぐ。漢字・ひらがなの端には境界を設けない。同じ位置では長い語を優先し、 + 長い語が境界を満たさない場合だけ短い語で境界を確認する。 + """ + + if not terms: + return re.compile(r"(?!x)x") + root: dict[str, Any] = {"terminal": False, "children": {}} + for term in terms: + node = root + for character in term: + node = node["children"].setdefault(character, {"terminal": False, "children": {}}) + node["terminal"] = True + + def lookahead(character: str) -> str: + edge = _edge_class(character) if boundaries else None + return f"(?!{edge})" if edge else "" + + def render(node: dict[str, Any], last_character: str) -> str: + branches = [ + re.escape(character) + render(child, character) + for character, child in sorted(node["children"].items()) + ] + if not branches: + body = "" + elif len(branches) == 1: + body = branches[0] + else: + body = "(?:" + "|".join(branches) + ")" + if not node["terminal"]: + return body + end = lookahead(last_character) + if not body: + return end + return "(?:" + body + "|" + end + ")" + + alternatives: list[str] = [] + for character, child in sorted(root["children"].items()): + edge = _edge_class(character) if boundaries else None + # 後読みは先頭文字を消費した後に置く。分岐が後読みで始まると + # 正規表現エンジンの先頭文字による走査最適化が効かず、約4倍遅くなる。 + lookbehind = f"(?