podtech-okamura commited on
Commit
b5cbcc7
·
verified ·
1 Parent(s): c2431fe

code e5cb5ca

Browse files
Files changed (40) hide show
  1. code/e5cb5ca/src/aggregate_summaries.py +124 -0
  2. code/e5cb5ca/src/audit_report.py +239 -0
  3. code/e5cb5ca/src/blocklists/blocklist_config.json +32 -0
  4. code/e5cb5ca/src/blocklists/ja_domain_allowlist.txt +17 -0
  5. code/e5cb5ca/src/blocklists/ja_domain_token_rules.txt +6 -0
  6. code/e5cb5ca/src/blocklists/ja_domains_blocklist.txt +15 -0
  7. code/e5cb5ca/src/classify_qwen3guard.py +161 -0
  8. code/e5cb5ca/src/cooccurrence.py +136 -0
  9. code/e5cb5ca/src/domain_blocklist.py +351 -0
  10. code/e5cb5ca/src/filter_pii.py +180 -0
  11. code/e5cb5ca/src/filter_toxic.py +587 -0
  12. code/e5cb5ca/src/hf_jobs_launch.py +227 -0
  13. code/e5cb5ca/src/main_pii.py +63 -0
  14. code/e5cb5ca/src/main_toxic.py +86 -0
  15. code/e5cb5ca/src/pii_detector.py +597 -0
  16. code/e5cb5ca/src/pii_residual_check.py +195 -0
  17. code/e5cb5ca/src/review_tally.py +53 -0
  18. code/e5cb5ca/src/run_shard.py +320 -0
  19. code/e5cb5ca/src/sample_for_review.py +177 -0
  20. code/e5cb5ca/src/textmatch.py +98 -0
  21. code/e5cb5ca/src/wordlists/cooccurrence/ja_howto_terms.txt +26 -0
  22. code/e5cb5ca/src/wordlists/cooccurrence/ja_illegal_object_terms.txt +31 -0
  23. code/e5cb5ca/src/wordlists/cooccurrence/ja_minor_terms.txt +23 -0
  24. code/e5cb5ca/src/wordlists/cooccurrence/ja_sexual_terms.txt +47 -0
  25. code/e5cb5ca/src/wordlists/cooccurrence/rules.json +22 -0
  26. code/e5cb5ca/src/wordlists/exclude/ja_adult_exclude.txt +17 -0
  27. code/e5cb5ca/src/wordlists/exclude/ja_crime_exclude.txt +2 -0
  28. code/e5cb5ca/src/wordlists/exclude/ja_discrimination_exclude.txt +5 -0
  29. code/e5cb5ca/src/wordlists/exclude/ja_propaganda_conspiracy_exclude.txt +2 -0
  30. code/e5cb5ca/src/wordlists/exclude/ja_spam_exclude.txt +18 -0
  31. code/e5cb5ca/src/wordlists/exclude/ja_violence_exclude.txt +26 -0
  32. code/e5cb5ca/src/wordlists/ja_adult_keywords.txt +10 -0
  33. code/e5cb5ca/src/wordlists/ja_crime_keywords.txt +54 -0
  34. code/e5cb5ca/src/wordlists/ja_discrimination_keywords.txt +11 -0
  35. code/e5cb5ca/src/wordlists/ja_propaganda_conspiracy_keywords.txt +27 -0
  36. code/e5cb5ca/src/wordlists/ja_spam_keywords.txt +52 -0
  37. code/e5cb5ca/src/wordlists/ja_violence_keywords.txt +31 -0
  38. code/e5cb5ca/src/wordlists/reference/ja_adult_keywords.txt +1462 -0
  39. code/e5cb5ca/src/wordlists/reference/ja_discrimination_keywords.txt +150 -0
  40. code/e5cb5ca/src/wordlists/reference/ja_violence_keywords.txt +73 -0
code/e5cb5ca/src/aggregate_summaries.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """シャードごとの shard_summary.json を集約し、全件の件数・母数・内訳を出す。
2
+
3
+ ローカルのディレクトリ(``--root``)か、HF データセット(``--repo`` と ``--prefix``、
4
+ ``outputs/**/shard_summary.json`` を取得)を入力にできる。``--expected-inputs`` に
5
+ 入力データセット名を渡すと、入力シャード一覧と突き合わせて未処理シャードを列挙する。
6
+
7
+ uv run python abeja-cc-ja/src/aggregate_summaries.py --repo Podtech/abeja-cc-ja-cleaned --prefix outputs \\
8
+ --expected-inputs Podtech/abeja-cc-ja-filtered --output dataset_summary.json
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import json
15
+ from collections import Counter, defaultdict
16
+ from datetime import datetime, timezone
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+
21
+ def _load_local(root: Path) -> list[dict[str, Any]]:
22
+ return [json.loads(p.read_text(encoding="utf-8")) for p in sorted(root.rglob("shard_summary.json"))]
23
+
24
+
25
+ def _load_repo(repo_id: str, prefix: str) -> list[dict[str, Any]]:
26
+ from huggingface_hub import snapshot_download
27
+
28
+ local = snapshot_download(repo_id, repo_type="dataset", allow_patterns=[f"{prefix.strip('/')}/**/shard_summary.json"])
29
+ return _load_local(Path(local) / prefix.strip("/"))
30
+
31
+
32
+ def _expected_shards(repo_id: str) -> set[str]:
33
+ from huggingface_hub import HfApi
34
+
35
+ return {Path(p).stem for p in HfApi().list_repo_files(repo_id, repo_type="dataset") if p.endswith(".parquet")}
36
+
37
+
38
+ def aggregate(summaries: list[dict[str, Any]]) -> dict[str, Any]:
39
+ total = Counter()
40
+ by_reason = Counter()
41
+ by_category_match = Counter()
42
+ by_category_deleted = Counter()
43
+ by_source_matched = Counter()
44
+ by_source_deleted = Counter()
45
+ by_rule = Counter()
46
+ pii_records = Counter()
47
+ pii_replacements = Counter()
48
+ seconds = Counter()
49
+ policies = Counter()
50
+ versions = Counter()
51
+ shards = []
52
+ for s in summaries:
53
+ shards.append(s["shard"])
54
+ versions[s.get("pipeline_version", "?")] += 1
55
+ total["input_rows"] += s["input_rows"]
56
+ total["toxic_deleted"] += s["toxic"]["records_deleted"]
57
+ total["toxic_retained"] += s["toxic"]["records_retained"]
58
+ total["pii_records_with_replacement"] += s["pii"]["records_with_replacement"]
59
+ total["pii_total_replacements"] += s["pii"]["total_replacements"]
60
+ total["final_rows"] += s["output"]["final_rows"]
61
+ for k, v in s["toxic"]["records_deleted_by_reason"].items():
62
+ by_reason[k] += v
63
+ for c, v in s["toxic"]["by_category"].items():
64
+ by_category_match[c] += v["records_with_match"]
65
+ by_category_deleted[c] += v["records_deleted"]
66
+ for name, v in (s["toxic"].get("domain_blocklist_by_source") or {}).items():
67
+ by_source_matched[name] += v.get("records_matched", 0)
68
+ by_source_deleted[name] += v.get("records_deleted", 0)
69
+ for name, v in (s["toxic"].get("cooccurrence_by_rule") or {}).items():
70
+ by_rule[name] += v.get("records_matched", 0)
71
+ for t, v in s["pii"]["by_type"].items():
72
+ pii_records[t] += v["records_with_match"]
73
+ pii_replacements[t] += v["replacement_count"]
74
+ for k, v in s["seconds"].items():
75
+ seconds[k] += v
76
+ p = s["pii"].get("policy") or {}
77
+ policies[f"{p.get('action')}|{p.get('approved_by')}|{p.get('approved_on')}|{p.get('status')}"] += 1
78
+ n = total["input_rows"] or 1
79
+ return {
80
+ "aggregated_at_utc": datetime.now(timezone.utc).isoformat(),
81
+ "shards": len(shards),
82
+ "pipeline_versions": dict(versions),
83
+ "totals": dict(total),
84
+ "toxic": {
85
+ "deletion_rate": round(total["toxic_deleted"] / n, 5),
86
+ "records_deleted_by_reason": dict(by_reason),
87
+ "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))},
88
+ "domain_blocklist_by_source": {k: {"records_matched": by_source_matched[k], "records_deleted": by_source_deleted[k]} for k in sorted(by_source_matched)},
89
+ "cooccurrence_by_rule": dict(by_rule),
90
+ },
91
+ "pii": {
92
+ "denominator_records": total["toxic_retained"],
93
+ "records_with_replacement_rate": round(total["pii_records_with_replacement"] / max(1, total["toxic_retained"]), 5),
94
+ "by_type": {t: {"records_with_match": pii_records[t], "replacement_count": pii_replacements[t]} for t in sorted(pii_records)},
95
+ "policies": dict(policies),
96
+ },
97
+ "seconds": dict(seconds),
98
+ "shard_list": sorted(shards),
99
+ }
100
+
101
+
102
+ def main(argv: list[str] | None = None) -> None:
103
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
104
+ source = parser.add_mutually_exclusive_group(required=True)
105
+ source.add_argument("--root", type=Path)
106
+ source.add_argument("--repo")
107
+ parser.add_argument("--prefix", default="outputs")
108
+ parser.add_argument("--expected-inputs", default=None, help="入力データセット(未処理シャードの検出用)")
109
+ parser.add_argument("--output", type=Path, required=True)
110
+ args = parser.parse_args(argv)
111
+ summaries = _load_local(args.root) if args.root else _load_repo(args.repo, args.prefix)
112
+ result = aggregate(summaries)
113
+ if args.expected_inputs:
114
+ expected = _expected_shards(args.expected_inputs)
115
+ done = set(result["shard_list"])
116
+ result["completeness"] = {"expected": len(expected), "done": len(done & expected), "missing": sorted(expected - done)[:200], "missing_count": len(expected - done), "unexpected": sorted(done - expected)[:50]}
117
+ args.output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
118
+ t = result["totals"]
119
+ print(json.dumps({"shards": result["shards"], "input_rows": t.get("input_rows"), "toxic_deleted": t.get("toxic_deleted"), "final_rows": t.get("final_rows"),
120
+ "pii_replacements": t.get("pii_total_replacements"), "completeness": result.get("completeness", {}).get("missing_count")}, ensure_ascii=False))
121
+
122
+
123
+ if __name__ == "__main__":
124
+ main()
code/e5cb5ca/src/audit_report.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """監査項目B(有害・倫理的に問題のあるコンテンツ、項目5〜10)の報告書を生成する。
2
+
3
+ 有害フィルタの出力(summary.json, removed.jsonl, cooccurrence_review.jsonl)と、
4
+ あれば分類器の出力(classify_qwen3guard.py)、目視集計(review_tally.py)を
5
+ 統合し、項目ごとに「適用した手法」「検出・除外件数」「例3件」「適用リスト」を
6
+ Markdown にまとめる。手法が1つしか適用されていない項目は「実施」と表示しない。
7
+
8
+ uv run python abeja-cc-ja/src/audit_report.py --output-root <toxic出力> \
9
+ [--classified review/classified.jsonl] [--review-tally review/review_tally.json] \
10
+ --output audit_report.md
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import json
17
+ from collections import Counter, defaultdict
18
+ from datetime import datetime, timezone
19
+ from pathlib import Path
20
+ from typing import Any
21
+
22
+ from textmatch import normalize
23
+
24
+
25
+ # 監査項目と、フィルタ内部のカテゴリ・規則・ブロックリストの対応。
26
+ AUDIT_ITEMS: list[dict[str, Any]] = [
27
+ {"item": 5, "title": "性的・わいせつな表現(未成年文脈は0件)",
28
+ "wordlist": ["adult"], "cooccurrence": ["minor_sexual_context"],
29
+ "blocklist": ["ut1:adult", "ut1:mixed_adult", "ut1:child", "local:domains", "local:rules"],
30
+ "classifier": ["Sexual Content or Sexual Acts"]},
31
+ {"item": 6, "title": "暴力・自傷・自殺の助長、危害を加える具体的手順",
32
+ "wordlist": ["violence"], "cooccurrence": [], "blocklist": [],
33
+ "classifier": ["Violent", "Suicide & Self-Harm"]},
34
+ {"item": 7, "title": "差別・ヘイト、誹謗中傷",
35
+ "wordlist": ["discrimination"], "cooccurrence": [], "blocklist": ["ut1:agressif"],
36
+ "classifier": ["Unethical Acts"]},
37
+ {"item": 8, "title": "違法行為の手引き(薬物、武器、詐欺、不正アクセス等)",
38
+ "wordlist": ["crime"], "cooccurrence": ["illegal_howto"],
39
+ "blocklist": ["ut1:drogue", "ut1:dangerous_material", "ut1:hacking"],
40
+ "classifier": ["Non-violent Illegal Acts"]},
41
+ {"item": 9, "title": "過激な政治・宗教プロパガンダ、陰謀論",
42
+ "wordlist": ["propaganda_conspiracy"], "cooccurrence": [], "blocklist": ["ut1:sect", "ut1:fakenews"],
43
+ "classifier": ["Politically Sensitive Topics"]},
44
+ {"item": 10, "title": "スパム・詐欺・アダルト・違法コピー配布サイト由来のページ",
45
+ "wordlist": ["spam"], "cooccurrence": [],
46
+ "blocklist": ["ut1:adult", "ut1:mixed_adult", "ut1:gambling", "ut1:phishing", "ut1:malware", "ut1:warez",
47
+ "ut1:cryptojacking", "ut1:stalkerware", "ut1:ddos", "ut1:dating", "local:domains", "local:rules"],
48
+ "classifier": ["Copyright Violation"]},
49
+ ]
50
+
51
+
52
+ def _read_jsonl(path: Path) -> list[dict[str, Any]]:
53
+ if not path or not path.exists():
54
+ return []
55
+ with path.open(encoding="utf-8") as handle:
56
+ return [json.loads(line) for line in handle if line.strip()]
57
+
58
+
59
+ def _snippet(record: dict[str, Any], terms: list[str], length: int = 90) -> str:
60
+ text = normalize(record.get("content") or "")
61
+ position = -1
62
+ for term in terms:
63
+ position = text.find(term)
64
+ if position >= 0:
65
+ break
66
+ start = max(0, position - length // 3) if position >= 0 else 0
67
+ return text[start:start + length].replace("\n", " ").replace("|", "/")
68
+
69
+
70
+ def _examples_wordlist(removed: list[dict[str, Any]], category: str, limit: int = 3) -> list[str]:
71
+ rows = []
72
+ for record in removed:
73
+ if category not in record.get("_filter_deleted_categories", []):
74
+ continue
75
+ terms = record["_filter_distinct_matched_terms_by_category"].get(category, [])
76
+ rows.append(f"| {record.get('_filter_record_index')} | {record.get('url', '')[:70]} | {', '.join(terms[:5])} | {_snippet(record, terms)} |")
77
+ if len(rows) >= limit:
78
+ break
79
+ return rows
80
+
81
+
82
+ def _examples_cooccurrence(review: list[dict[str, Any]], rule: str, limit: int = 3) -> list[str]:
83
+ rows = []
84
+ for item in review:
85
+ if item["rule"] != rule:
86
+ continue
87
+ pairs = ", ".join(f"{p['a']}×{p['b']}" for p in item["pairs"][:3])
88
+ rows.append(f"| {item['record_index']} | {item.get('url', '')[:70]} | {pairs} | {item['excerpt'][:90].replace('|', '/')} |")
89
+ if len(rows) >= limit:
90
+ break
91
+ return rows
92
+
93
+
94
+ def _examples_blocklist(removed: list[dict[str, Any]], sources: list[str], limit: int = 3) -> list[str]:
95
+ rows = []
96
+ for record in removed:
97
+ hits = [m for m in record.get("_filter_domain_matches", []) if m["source"] in sources and m["action"] == "delete"]
98
+ if not hits:
99
+ continue
100
+ rows.append(f"| {record.get('_filter_record_index')} | {record.get('url', '')[:70]} | {hits[0]['source']} ({hits[0]['matched'][:40]}) | |")
101
+ if len(rows) >= limit:
102
+ break
103
+ return rows
104
+
105
+
106
+ def main(argv: list[str] | None = None) -> None:
107
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
108
+ parser.add_argument("--output-root", type=Path, required=True)
109
+ parser.add_argument("--mode", default="distinct_terms_3plus")
110
+ parser.add_argument("--classified", type=Path, default=None, help="classify_qwen3guard.py の出力JSONL")
111
+ parser.add_argument("--review-tally", type=Path, default=None, help="review_tally.py の出力JSON")
112
+ parser.add_argument("--sampling-manifest", type=Path, default=None)
113
+ parser.add_argument("--output", type=Path, default=None, help="既定は <output-root>/audit_report.md")
114
+ args = parser.parse_args(argv)
115
+
116
+ mode_dir = args.output_root / args.mode
117
+ summary = json.loads((mode_dir / "summary.json").read_text(encoding="utf-8"))
118
+ removed = _read_jsonl(mode_dir / "removed.jsonl")
119
+ review = _read_jsonl(mode_dir / "cooccurrence_review.jsonl")
120
+ classified = _read_jsonl(args.classified) if args.classified else []
121
+ tally = json.loads(args.review_tally.read_text(encoding="utf-8")) if args.review_tally and args.review_tally.exists() else None
122
+ sampling = json.loads(args.sampling_manifest.read_text(encoding="utf-8")) if args.sampling_manifest and args.sampling_manifest.exists() else None
123
+
124
+ total = summary["total_records_scanned"]
125
+ block = summary.get("domain_blocklist", {})
126
+ cooc = summary.get("cooccurrence", {})
127
+ by_reason = summary.get("records_deleted_by_reason", {})
128
+
129
+ # 分類器の集計(層別 × 判定)
130
+ classifier_by_stratum: dict[str, Counter] = defaultdict(Counter)
131
+ classifier_by_category: Counter = Counter()
132
+ for record in classified:
133
+ classifier_by_stratum[record.get("stratum", "?")][record.get("safety") or "unparsed"] += 1
134
+ for category in record.get("categories", []):
135
+ classifier_by_category[category] += 1
136
+
137
+ lines: list[str] = []
138
+ lines.append(f"# 有害コンテンツ監査報告(項目B: 5〜10)")
139
+ lines.append("")
140
+ lines.append(f"- 生成日時: {datetime.now(timezone.utc).isoformat()}")
141
+ lines.append(f"- 対象: `{summary['source_file']}`(行 {summary['row_range']['start_row_inclusive']}〜{summary['row_range']['end_row_exclusive']}、{total:,} 文書)")
142
+ 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):,}")
143
+ lines.append("")
144
+ lines.append("## 適用した手法")
145
+ lines.append("")
146
+ lines.append("| 手法 | 状態 | 内容 |")
147
+ lines.append("|---|---|---|")
148
+ lines.append(f"| 辞書(ワードリスト) | 適用 | カテゴリ別語彙、同一カテゴリ{summary['threshold']}語以上で削除。除外語: " + ", ".join(f"{k} {len(v)}" for k, v in summary.get("wordlist_excluded_terms_by_category", {}).items()) + " |")
149
+ lines.append(f"| 辞書(近接共起規則) | {'適用' if cooc.get('enabled') else '未適用'} | " + "; ".join(f"{r['name']}({r['label_ja']}、{r['window']}文字以内)" for r in cooc.get("rules", [])) + " |")
150
+ lines.append(f"| ドメインブロックリスト | {'適用' if block.get('enabled') else '未適用'} | " + ", ".join(f"{s['name']}={s['entries']:,}" for s in block.get("sources", [])) + " |")
151
+ if classified:
152
+ 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())) + " |")
153
+ else:
154
+ lines.append("| 分類器 | 未適用 | `classify_qwen3guard.py` の出力を `--classified` で渡す |")
155
+ if tally:
156
+ reviewed = sum(e.get("reviewed", 0) for e in tally["strata"].values())
157
+ lines.append(f"| 目視 | {'適用' if reviewed else '未記入'} | 判定済み {reviewed} 件、判定者 {', '.join(tally.get('reviewers', [])) or '未記入'} |")
158
+ else:
159
+ lines.append("| 目視 | 未適用 | `sample_for_review.py` → 記入 → `review_tally.py` の結果を `--review-tally` で渡す |")
160
+ lines.append("")
161
+ methods_applied = 1 + (1 if classified else 0) + (1 if tally and any(e.get("reviewed") for e in tally["strata"].values()) else 0)
162
+ lines.append(f"手法数: {methods_applied}/3。" + ("3手法が揃っており「実施」と表示できます。" if methods_applied >= 3 else "3手法が揃うまでは「実施」としないこと。"))
163
+ lines.append("")
164
+
165
+ if block.get("enabled"):
166
+ lines.append("## 適用したドメインブロックリスト")
167
+ lines.append("")
168
+ lines.append("| リスト | 動作 | 件数 | 一致文書 | 削除文書 | 取得元 | 取得日時 | SHA-256 |")
169
+ lines.append("|---|---|---:|---:|---:|---|---|---|")
170
+ for source in block["sources"]:
171
+ stat = block["by_source"].get(source["name"], {})
172
+ 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]} |")
173
+ lines.append("")
174
+
175
+ for spec in AUDIT_ITEMS:
176
+ lines.append(f"## 項目{spec['item']}: {spec['title']}")
177
+ lines.append("")
178
+ counts_lines = []
179
+ for category in spec["wordlist"]:
180
+ cat = summary["by_category"].get(category, {})
181
+ counts_lines.append(f"- ワードリスト `{category}`: 一致 {cat.get('records_with_match', 0):,} 文書、削除 {cat.get('records_deleted', 0):,} 文書({cat.get('distinct_terms_matched', 0)} 語が一致)")
182
+ for rule in spec["cooccurrence"]:
183
+ stat = cooc.get("by_rule", {}).get(rule)
184
+ if stat is not None:
185
+ counts_lines.append(f"- 近接共起 `{rule}`({stat['label_ja']}): 一致・削除 {stat['records_matched']:,} 文書。全件を `cooccurrence_review.jsonl` で目視確認する")
186
+ for source_name in spec["blocklist"]:
187
+ stat = block.get("by_source", {}).get(source_name)
188
+ if stat is not None:
189
+ counts_lines.append(f"- ブロックリスト `{source_name}`({stat['action']}): 一致 {stat['records_matched']:,} 文書、削除 {stat['records_deleted']:,} 文書")
190
+ if classified:
191
+ hit = sum(1 for r in classified if any(c in spec["classifier"] for c in r.get("categories", [])))
192
+ counts_lines.append(f"- 分類器: サンプル {len(classified)} 件中 {hit} 件が {', '.join(spec['classifier'])} に該当")
193
+ if tally:
194
+ for stratum, entry in tally["strata"].items():
195
+ if any(stratum.endswith(":" + c) for c in spec["wordlist"] + spec["cooccurrence"]):
196
+ rate = entry.get("precision", entry.get("harmful_rate"))
197
+ 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 ""))
198
+ lines.extend(counts_lines or ["- 該当する検出手段なし"])
199
+ if spec["item"] == 5:
200
+ minor = cooc.get("by_rule", {}).get("minor_sexual_context", {})
201
+ lines.append(f"- 未成年文脈: 共起規則で {minor.get('records_matched', 0):,} 文書を削除。保持データ側の残存は目視層 `cooccurrence:minor_sexual_context` と `retained:random` の確認結果で判断する")
202
+ lines.append("")
203
+ lines.append("例(最大3件):")
204
+ lines.append("")
205
+ lines.append("| record_index | URL | 該当語・規則 | 抜粋 |")
206
+ lines.append("|---|---|---|---|")
207
+ examples: list[str] = []
208
+ for category in spec["wordlist"]:
209
+ examples.extend(_examples_wordlist(removed, category))
210
+ for rule in spec["cooccurrence"]:
211
+ examples.extend(_examples_cooccurrence(review, rule))
212
+ examples.extend(_examples_blocklist(removed, spec["blocklist"]))
213
+ lines.extend(examples[:3] if examples else ["| | (該当なし) | | |"])
214
+ lines.append("")
215
+
216
+ if sampling:
217
+ lines.append("## 目視サンプル")
218
+ lines.append("")
219
+ lines.append(f"- 抽出日時 {sampling['created_at_utc']}、seed {sampling['seed']}、合計 {sampling['total_samples']} 件")
220
+ lines.append("- 層別件数: " + ", ".join(f"{k} {v}" for k, v in sampling["strata"].items()))
221
+ lines.append("")
222
+ if classified:
223
+ lines.append("## 分類器の層別結果")
224
+ lines.append("")
225
+ lines.append("| 層 | Safe | Controversial | Unsafe | 未解析 |")
226
+ lines.append("|---|---:|---:|---:|---:|")
227
+ for stratum, counter in sorted(classifier_by_stratum.items()):
228
+ lines.append(f"| {stratum} | {counter.get('Safe', 0)} | {counter.get('Controversial', 0)} | {counter.get('Unsafe', 0)} | {counter.get('unparsed', 0)} |")
229
+ lines.append("")
230
+ lines.append("カテゴリ別: " + ", ".join(f"{k} {v}" for k, v in classifier_by_category.most_common()))
231
+ lines.append("")
232
+
233
+ output = args.output or (args.output_root / "audit_report.md")
234
+ output.write_text("\n".join(lines) + "\n", encoding="utf-8")
235
+ print(f"wrote {output} ({len(lines)} lines); methods_applied={methods_applied}/3")
236
+
237
+
238
+ if __name__ == "__main__":
239
+ main()
code/e5cb5ca/src/blocklists/blocklist_config.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "ut1": {
3
+ "description_ja": "UT1 blacklists(トゥールーズ・キャピトル大学)。delete は該当文書を削除、flag は記録のみ。",
4
+ "categories": {
5
+ "adult": "delete",
6
+ "mixed_adult": "delete",
7
+ "child": "delete",
8
+ "gambling": "delete",
9
+ "phishing": "delete",
10
+ "malware": "delete",
11
+ "warez": "delete",
12
+ "cryptojacking": "delete",
13
+ "stalkerware": "delete",
14
+ "ddos": "delete",
15
+ "dangerous_material": "delete",
16
+ "drogue": "delete",
17
+ "sect": "delete",
18
+ "agressif": "delete",
19
+ "hacking": "flag",
20
+ "fakenews": "flag",
21
+ "dating": "flag"
22
+ }
23
+ },
24
+ "local": {
25
+ "description_ja": "このリポジトリで管理する日本語Web向けの補助リスト。",
26
+ "domains": "ja_domains_blocklist.txt",
27
+ "rules": "ja_domain_token_rules.txt",
28
+ "action": "delete",
29
+ "allowlist": "ja_domain_allowlist.txt",
30
+ "allowlist_note_ja": "allowlist のドメインには UT1 のドメイン一致を適用しない(自前リスト・規則・本文判定は適用する)。"
31
+ }
32
+ }
code/e5cb5ca/src/blocklists/ja_domain_allowlist.txt ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # UT1 のドメイン一致を適用しない許可リスト。形式: ドメイン [理由]。サブドメインも対象。
2
+ # 多数のサイトが同居するプラットフォームや、成人向け区画を持つだけの大規模一般サイトは、
3
+ # ドメイン単位の削除だと一般コンテンツを大量に失うため、本文のワードリスト・共起規則で判定する。
4
+ # 根拠: common_crawl_0_filtered_0001 で ut1:adult に一致した上位ドメイン。
5
+ fc2.com 共用ブログホスト(blogNN.fc2.com)。個別ブログは本文で判定
6
+ pixiv.net イラスト投稿プラットフォーム。R-18は一部
7
+ dmm.com 総合EC・ゲーム。成人向けは dmm.co.jp
8
+ dlsite.com 同人ショップ。成人向けは /maniax 配下
9
+ papy.co.jp 電子書籍ストア
10
+ shueisha.co.jp 出版社(週刊プレイボーイ等)
11
+ cosmopolitan.com 一般誌
12
+ hatenablog.com 共用ブログホスト
13
+ livedoor.jp 共用ブログホスト
14
+ ameblo.jp 共用ブログホスト
15
+ seesaa.net 共用ブログホスト
16
+ exblog.jp 共用ブログホスト
17
+ goo.ne.jp ポータル・共用ブログ
code/e5cb5ca/src/blocklists/ja_domain_token_rules.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # ドメイン名規則。形式: ラベル<TAB>正規表現(ホスト名に対して search)。
2
+ # トークン境界(先頭・ドット・ハイフン)を要求し、hero.jp のような偶然の部分一致を避ける。
3
+ # adult(adhd-adult.info)と deai(出会いアプリ紹介)は誤検出が多いため2026-09-04に除外。
4
+ gambling (^|[.-])(online)?(casino|casinos|kajino|onkaji|onlinecasino)[a-z0-9-]*([.-]|$)
5
+ 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]*)([.-]|$)
6
+ warez (^|[.-])(warez|torrents?|keygen|serials?|crackz?)([.-]|$)
code/e5cb5ca/src/blocklists/ja_domains_blocklist.txt ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 自前ドメインブロックリスト。形式: ドメイン [ラベル]。サブドメインも一致する。
2
+ # 根拠: common_crawl_0_filtered_0001 の有害フィルタ削除文書のうち、ドメイン名と内容から
3
+ # サイト全体が対象カテゴリと判断できたもの。追加時はコメントに根拠を残すこと。
4
+ oshiete-onlinecasino.net gambling
5
+ onlinecasinofan.com gambling
6
+ onlinecasinoget.com gambling
7
+ on-casi.info gambling
8
+ on-linecasinoplay.com gambling
9
+ win-spin-casinos-deposit.site gambling
10
+ casinotop10.jp gambling
11
+ japanesecasinoreview.com gambling
12
+ ero-mangalife.com adult
13
+ sexyaction.net adult
14
+ sexynews24.info adult
15
+ nozokima.site adult
code/e5cb5ca/src/classify_qwen3guard.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Qwen3Guard-Gen による有害性分類(監査の第2手法)。
2
+
3
+ 辞書・ブロックリスト・共起規則とは独立した分類器として、目視サンプルや
4
+ 境界文書に適用する。全件へ適用するには計算量が大きいため、
5
+ ``sample_for_review.py`` が出力するサンプルJSONLを入力にする想定。
6
+
7
+ 入力JSONL: ``{"id": ..., "url": ..., "text": ..., "match_positions": [..]}``
8
+ 出力JSONL: 入力に ``safety``(Safe/Unsafe/Controversial)、``categories``、
9
+ ``raw_output``、``elapsed_s`` を加えたもの。併せて ``<output>.manifest.json`` に
10
+ モデル名・リビジョン・実行条件を記録する。
11
+
12
+ 依存関係は ``uv sync --group classifier`` で導入する(torch, transformers)。
13
+
14
+ uv run python abeja-cc-ja/src/classify_qwen3guard.py --input samples.jsonl --output classified.jsonl
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import json
21
+ import re
22
+ import time
23
+ from datetime import datetime, timezone
24
+ from pathlib import Path
25
+ from typing import Any
26
+
27
+
28
+ DEFAULT_MODEL = "Qwen/Qwen3Guard-Gen-0.6B"
29
+ SAFETY_RE = re.compile(r"Safety:\s*(Safe|Unsafe|Controversial)")
30
+ CATEGORY_RE = re.compile(
31
+ r"(Violent|Non-violent Illegal Acts|Sexual Content or Sexual Acts|PII|Suicide & Self-Harm|"
32
+ r"Unethical Acts|Politically Sensitive Topics|Copyright Violation|Jailbreak|None)"
33
+ )
34
+ # Qwen3Guard のカテゴリと監査項目(5〜10)の対応。
35
+ CATEGORY_TO_AUDIT_ITEM = {
36
+ "Sexual Content or Sexual Acts": 5,
37
+ "Violent": 6,
38
+ "Suicide & Self-Harm": 6,
39
+ "Unethical Acts": 7,
40
+ "Non-violent Illegal Acts": 8,
41
+ "Politically Sensitive Topics": 9,
42
+ "Copyright Violation": 10,
43
+ }
44
+
45
+
46
+ def build_excerpt(text: str, positions: list[int] | None, max_chars: int, window: int = 300, head: int = 1000) -> str:
47
+ """先頭と、一致位置の前後を優先して抜粋する。長文をそのまま渡さない。"""
48
+
49
+ if len(text) <= max_chars:
50
+ return text
51
+ pieces: list[tuple[int, int]] = [(0, min(head, len(text)))]
52
+ for position in (positions or [])[:4]:
53
+ pieces.append((max(0, position - window), min(len(text), position + window)))
54
+ pieces.sort()
55
+ merged: list[list[int]] = []
56
+ for start, end in pieces:
57
+ if merged and start <= merged[-1][1]:
58
+ merged[-1][1] = max(merged[-1][1], end)
59
+ else:
60
+ merged.append([start, end])
61
+ excerpt = " … ".join(text[start:end] for start, end in merged)
62
+ return excerpt[:max_chars]
63
+
64
+
65
+ def parse_output(content: str) -> tuple[str | None, list[str]]:
66
+ safety = SAFETY_RE.search(content)
67
+ categories = [item for item in CATEGORY_RE.findall(content) if item != "None"]
68
+ return (safety.group(1) if safety else None), sorted(set(categories))
69
+
70
+
71
+ def load_model(model_name: str, device: str):
72
+ import torch
73
+ from transformers import AutoModelForCausalLM, AutoTokenizer
74
+
75
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
76
+ kwargs: dict[str, Any] = {}
77
+ if device == "auto":
78
+ kwargs["device_map"] = "auto"
79
+ try:
80
+ model = AutoModelForCausalLM.from_pretrained(model_name, dtype="auto", **kwargs)
81
+ except TypeError:
82
+ model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", **kwargs)
83
+ if device != "auto":
84
+ model = model.to(device)
85
+ model.eval()
86
+ return tokenizer, model, torch
87
+
88
+
89
+ def classify_text(tokenizer, model, torch, text: str, max_new_tokens: int = 64) -> str:
90
+ messages = [{"role": "user", "content": text}]
91
+ prompt = tokenizer.apply_chat_template(messages, tokenize=False)
92
+ inputs = tokenizer([prompt], return_tensors="pt").to(model.device)
93
+ with torch.no_grad():
94
+ generated = model.generate(**inputs, max_new_tokens=max_new_tokens, do_sample=False)
95
+ output_ids = generated[0][len(inputs.input_ids[0]):].tolist()
96
+ return tokenizer.decode(output_ids, skip_special_tokens=True)
97
+
98
+
99
+ def main(argv: list[str] | None = None) -> None:
100
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
101
+ parser.add_argument("--input", type=Path, required=True)
102
+ parser.add_argument("--output", type=Path, required=True)
103
+ parser.add_argument("--model", default=DEFAULT_MODEL)
104
+ parser.add_argument("--device", default="auto", help="auto / cpu / mps / cuda")
105
+ parser.add_argument("--max-chars", type=int, default=3000)
106
+ parser.add_argument("--max-new-tokens", type=int, default=64)
107
+ parser.add_argument("--limit", type=int, default=None)
108
+ args = parser.parse_args(argv)
109
+
110
+ tokenizer, model, torch = load_model(args.model, args.device)
111
+ revision = getattr(getattr(model, "config", None), "_commit_hash", None)
112
+ started = datetime.now(timezone.utc).isoformat()
113
+ counts: dict[str, int] = {"Safe": 0, "Unsafe": 0, "Controversial": 0, "unparsed": 0}
114
+ processed = 0
115
+ args.output.parent.mkdir(parents=True, exist_ok=True)
116
+ with args.input.open(encoding="utf-8") as reader, args.output.open("w", encoding="utf-8") as writer:
117
+ for line in reader:
118
+ if not line.strip():
119
+ continue
120
+ if args.limit is not None and processed >= args.limit:
121
+ break
122
+ record = json.loads(line)
123
+ text = build_excerpt(record.get("text") or "", record.get("match_positions"), args.max_chars)
124
+ t0 = time.perf_counter()
125
+ raw = classify_text(tokenizer, model, torch, text, args.max_new_tokens)
126
+ elapsed = time.perf_counter() - t0
127
+ safety, categories = parse_output(raw)
128
+ counts[safety or "unparsed"] += 1
129
+ record.update({
130
+ "safety": safety,
131
+ "categories": categories,
132
+ "audit_items": sorted({CATEGORY_TO_AUDIT_ITEM[c] for c in categories if c in CATEGORY_TO_AUDIT_ITEM}),
133
+ "raw_output": raw.strip(),
134
+ "excerpt_chars": len(text),
135
+ "elapsed_s": round(elapsed, 3),
136
+ "model": args.model,
137
+ })
138
+ record.pop("text", None)
139
+ writer.write(json.dumps(record, ensure_ascii=False, separators=(",", ":")) + "\n")
140
+ processed += 1
141
+ manifest = {
142
+ "model": args.model,
143
+ "model_revision": revision,
144
+ "device": str(model.device),
145
+ "max_chars": args.max_chars,
146
+ "max_new_tokens": args.max_new_tokens,
147
+ "started_at_utc": started,
148
+ "finished_at_utc": datetime.now(timezone.utc).isoformat(),
149
+ "input": str(args.input),
150
+ "output": str(args.output),
151
+ "processed": processed,
152
+ "counts": counts,
153
+ "category_to_audit_item": CATEGORY_TO_AUDIT_ITEM,
154
+ "taxonomy_note": "Qwen3Guard: Safe / Controversial / Unsafe。Controversial は文脈依存の判定。",
155
+ }
156
+ Path(str(args.output) + ".manifest.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
157
+ print(json.dumps({"processed": processed, "counts": counts, "model": args.model}, ensure_ascii=False))
158
+
159
+
160
+ if __name__ == "__main__":
161
+ main()
code/e5cb5ca/src/cooccurrence.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """2種類の語群が近接して現れる文書を検出する近接共起規則。
2
+
3
+ 単語リストの密度(同一カテゴリ3語以上)では判別できない次の2種類を扱う。
4
+
5
+ * 未成年を示す語 × 性的な語(監査項目5「未成年が登場する文脈は0件」)
6
+ * 違法行為の対象語 × 手引きを示す語(監査項目8「違法行為の手引き」)
7
+
8
+ 規則は ``wordlists/cooccurrence/rules.json`` に定義し、語リストは同じ
9
+ ディレクトリの1行1語ファイルから読む。一致した文書は削除対象になると同時に、
10
+ 全件が目視確認用の ``cooccurrence_review.jsonl`` へ書き出される。
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import bisect
16
+ import json
17
+ from dataclasses import dataclass
18
+ from pathlib import Path
19
+ from typing import Any
20
+
21
+ from textmatch import compile_trie_pattern, normalize, read_terms
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class CooccurrenceRule:
26
+ name: str
27
+ category: str
28
+ label_ja: str
29
+ terms_a: tuple[str, ...]
30
+ terms_b: tuple[str, ...]
31
+ window: int
32
+ description_ja: str = ""
33
+ terms_a_file: str = ""
34
+ terms_b_file: str = ""
35
+
36
+
37
+ def load_rules(path: Path) -> list[CooccurrenceRule]:
38
+ """規則定義JSONと語リストを読む。語リストのパスはJSONからの相対パス。"""
39
+
40
+ spec = json.loads(path.read_text(encoding="utf-8"))
41
+ base = path.parent
42
+ rules: list[CooccurrenceRule] = []
43
+ for item in spec["rules"]:
44
+ terms_a = read_terms(base / item["terms_a"])
45
+ terms_b = read_terms(base / item["terms_b"])
46
+ if not terms_a or not terms_b:
47
+ raise ValueError(f"規則 {item['name']} の語リストが空です: {item['terms_a']}, {item['terms_b']}")
48
+ rules.append(
49
+ CooccurrenceRule(
50
+ name=item["name"],
51
+ category=item["category"],
52
+ label_ja=item["label_ja"],
53
+ terms_a=tuple(dict.fromkeys(terms_a)),
54
+ terms_b=tuple(dict.fromkeys(terms_b)),
55
+ window=int(item.get("window", 100)),
56
+ description_ja=item.get("description_ja", ""),
57
+ terms_a_file=item["terms_a"],
58
+ terms_b_file=item["terms_b"],
59
+ )
60
+ )
61
+ return rules
62
+
63
+
64
+ class CooccurrenceDetector:
65
+ """各規則について、語群Aと語群Bの出現位置が window 文字以内の組を探す。"""
66
+
67
+ def __init__(self, rules: list[CooccurrenceRule]) -> None:
68
+ self.rules = rules
69
+ self._patterns = [
70
+ (
71
+ rule,
72
+ compile_trie_pattern(sorted(rule.terms_a, key=lambda t: (-len(t), t))),
73
+ compile_trie_pattern(sorted(rule.terms_b, key=lambda t: (-len(t), t))),
74
+ )
75
+ for rule in rules
76
+ ]
77
+
78
+ def describe(self) -> list[dict[str, Any]]:
79
+ return [
80
+ {
81
+ "name": rule.name,
82
+ "category": rule.category,
83
+ "label_ja": rule.label_ja,
84
+ "window": rule.window,
85
+ "terms_a_file": rule.terms_a_file,
86
+ "terms_a_count": len(rule.terms_a),
87
+ "terms_b_file": rule.terms_b_file,
88
+ "terms_b_count": len(rule.terms_b),
89
+ "description_ja": rule.description_ja,
90
+ }
91
+ for rule in self.rules
92
+ ]
93
+
94
+ def detect(self, text: Any, max_pairs: int = 10, excerpt_margin: int = 60) -> list[dict[str, Any]]:
95
+ normalized = normalize(text)
96
+ if not normalized:
97
+ return []
98
+ results: list[dict[str, Any]] = []
99
+ for rule, pattern_a, pattern_b in self._patterns:
100
+ a_hits = [(found.start(), found.group(0)) for found in pattern_a.finditer(normalized)]
101
+ if not a_hits:
102
+ continue
103
+ b_hits = [(found.start(), found.group(0)) for found in pattern_b.finditer(normalized)]
104
+ if not b_hits:
105
+ continue
106
+ b_positions = [position for position, _ in b_hits]
107
+ pairs: list[dict[str, Any]] = []
108
+ for a_position, a_term in a_hits:
109
+ low = bisect.bisect_left(b_positions, a_position - rule.window)
110
+ high = bisect.bisect_right(b_positions, a_position + rule.window)
111
+ for b_position, b_term in b_hits[low:high]:
112
+ pairs.append(
113
+ {
114
+ "a": a_term,
115
+ "b": b_term,
116
+ "distance": abs(a_position - b_position),
117
+ "position": min(a_position, b_position),
118
+ }
119
+ )
120
+ if not pairs:
121
+ continue
122
+ pairs.sort(key=lambda pair: (pair["position"], pair["distance"]))
123
+ first = pairs[0]
124
+ start = max(0, first["position"] - excerpt_margin)
125
+ end = min(len(normalized), first["position"] + rule.window + excerpt_margin)
126
+ results.append(
127
+ {
128
+ "rule": rule.name,
129
+ "category": rule.category,
130
+ "label_ja": rule.label_ja,
131
+ "pair_count": len(pairs),
132
+ "pairs": pairs[:max_pairs],
133
+ "excerpt": normalized[start:end].replace("\n", " "),
134
+ }
135
+ )
136
+ return results
code/e5cb5ca/src/domain_blocklist.py ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """URLのドメインをブロックリストと照合する。
2
+
3
+ UT1 blacklists(トゥールーズ・キャピトル大学、CC BY-SA)のカテゴリ別リストと、
4
+ このリポジトリで管理するドメインリスト・ドメイン名規則を統合する。適用した
5
+ リストの出典・取得日時・SHA-256・件数はマニフェストとして summary.json に
6
+ 記録する(監査項目10「適用したリストを記録」)。
7
+
8
+ 取得::
9
+
10
+ python domain_blocklist.py fetch --dest ../data/blocklists/ut1
11
+
12
+ 確認::
13
+
14
+ python domain_blocklist.py check https://example.com/path ...
15
+
16
+ 設定は ``blocklists/blocklist_config.json`` にあり、UT1カテゴリごとに
17
+ ``delete``(削除)か ``flag``(記録のみ)を指定する。
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import hashlib
24
+ import io
25
+ import json
26
+ import re
27
+ import tarfile
28
+ import unicodedata
29
+ import urllib.error
30
+ import urllib.request
31
+ from dataclasses import asdict, dataclass
32
+ from datetime import datetime, timezone
33
+ from pathlib import Path
34
+ from typing import Any, Iterable
35
+ from urllib.parse import urlparse
36
+
37
+
38
+ UT1_DOWNLOAD_URL = "https://dsi.ut-capitole.fr/blacklists/download/{category}.tar.gz"
39
+ UT1_MIRROR_URL = "https://raw.githubusercontent.com/olbat/ut1-blacklists/master/blacklists/{category}/{member}"
40
+ UT1_LICENSE = "CC BY-SA 4.0 (Université Toulouse Capitole, Fabrice Prigent)"
41
+ CONFIG_FILE = "blocklist_config.json"
42
+ MANIFEST_FILE = "manifest.json"
43
+ USER_AGENT = "MHI_Dataset-domain-blocklist/1.0"
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class BlocklistSource:
48
+ """適用したリスト1件分のメタデータ。summary.json にそのまま記録する。"""
49
+
50
+ name: str
51
+ kind: str # ut1 | local_domains | local_rules
52
+ action: str # delete | flag
53
+ entries: int
54
+ path: str
55
+ license: str = ""
56
+ source_url: str | None = None
57
+ sha256: str | None = None
58
+ fetched_at_utc: str | None = None
59
+
60
+
61
+ def normalize_host(url: Any) -> str | None:
62
+ """URLからホスト名を取り出す。小文字化し、ポートと末尾のドットを除く。"""
63
+
64
+ if not url:
65
+ return None
66
+ text = unicodedata.normalize("NFKC", str(url)).strip().lower()
67
+ if "://" not in text:
68
+ text = "http://" + text
69
+ try:
70
+ host = urlparse(text).hostname
71
+ except ValueError:
72
+ return None
73
+ if not host:
74
+ return None
75
+ return host.strip(".")
76
+
77
+
78
+ def host_suffixes(host: str) -> list[str]:
79
+ """``a.b.example.com`` → ``[a.b.example.com, b.example.com, example.com]``(TLD単独は除く)。"""
80
+
81
+ parts = host.split(".")
82
+ return [".".join(parts[index:]) for index in range(len(parts) - 1)]
83
+
84
+
85
+ def _sha256(data: bytes) -> str:
86
+ return hashlib.sha256(data).hexdigest()
87
+
88
+
89
+ def _download(url: str, timeout: int) -> bytes:
90
+ request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
91
+ with urllib.request.urlopen(request, timeout=timeout) as response:
92
+ return response.read()
93
+
94
+
95
+ def _count_entries(content: bytes) -> int:
96
+ return sum(1 for line in content.splitlines() if line.strip() and not line.startswith(b"#"))
97
+
98
+
99
+ def fetch_ut1(categories: Iterable[str], dest: Path, timeout: int = 300, prefer_mirror: bool = False) -> dict[str, Any]:
100
+ """UT1のカテゴリ別tarballを取得し、domains/urls を展開してマニフェストを書く。
101
+
102
+ 公式サイトが応答しない場合はGitHubミラー(olbat/ut1-blacklists)へ
103
+ フォールバックする。どちらから取得したかはマニフェストに残る。
104
+ """
105
+
106
+ dest.mkdir(parents=True, exist_ok=True)
107
+ manifest: dict[str, Any] = {
108
+ "source": "UT1 blacklists",
109
+ "license": UT1_LICENSE,
110
+ "fetched_at_utc": datetime.now(timezone.utc).isoformat(),
111
+ "categories": {},
112
+ }
113
+ for category in categories:
114
+ entry: dict[str, Any] = {}
115
+ members: dict[str, bytes] = {}
116
+ data: bytes | None = None
117
+ if not prefer_mirror:
118
+ official_url = UT1_DOWNLOAD_URL.format(category=category)
119
+ try:
120
+ data = _download(official_url, timeout)
121
+ entry["source_url"] = official_url
122
+ except (urllib.error.URLError, TimeoutError, OSError) as error:
123
+ entry["official_error"] = str(error)
124
+ if data is not None:
125
+ entry["sha256"] = _sha256(data)
126
+ entry["bytes"] = len(data)
127
+ with tarfile.open(fileobj=io.BytesIO(data), mode="r:gz") as archive:
128
+ for member in archive.getmembers():
129
+ name = Path(member.name).name
130
+ if name in ("domains", "urls") and member.isfile():
131
+ handle = archive.extractfile(member)
132
+ if handle is not None:
133
+ members[name] = handle.read()
134
+ else:
135
+ for name in ("domains", "urls"):
136
+ mirror_url = UT1_MIRROR_URL.format(category=category, member=name)
137
+ try:
138
+ members[name] = _download(mirror_url, timeout)
139
+ except urllib.error.HTTPError as error:
140
+ if error.code != 404:
141
+ raise
142
+ entry["source_url"] = UT1_MIRROR_URL.format(category=category, member="{domains,urls}")
143
+ entry["sha256"] = _sha256(b"".join(members[name] for name in sorted(members)))
144
+ entry["bytes"] = sum(len(value) for value in members.values())
145
+ if "domains" not in members:
146
+ raise RuntimeError(f"UT1カテゴリ {category} の domains を取得できませんでした")
147
+ category_dir = dest / category
148
+ category_dir.mkdir(parents=True, exist_ok=True)
149
+ for name, content in members.items():
150
+ (category_dir / name).write_bytes(content)
151
+ entry[f"{name}_entries"] = _count_entries(content)
152
+ manifest["categories"][category] = entry
153
+ (dest / MANIFEST_FILE).write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
154
+ return manifest
155
+
156
+
157
+ def _read_list_lines(path: Path) -> list[str]:
158
+ lines: list[str] = []
159
+ for raw_line in path.read_text(encoding="utf-8", errors="replace").splitlines():
160
+ line = raw_line.strip()
161
+ if line and not line.startswith("#"):
162
+ lines.append(line)
163
+ return lines
164
+
165
+
166
+ class DomainBlocklist:
167
+ """ドメイン一致(親ドメインを含む)、URL接頭辞一致、ドメイン名規則の照合。"""
168
+
169
+ def __init__(self) -> None:
170
+ self.sources: list[BlocklistSource] = []
171
+ self._domain_index: dict[str, list[str]] = {}
172
+ self._url_index: dict[str, list[tuple[str, str]]] = {}
173
+ self._rules: list[tuple[str, re.Pattern[str], str]] = []
174
+ self._actions: dict[str, str] = {}
175
+ self._allowlist: set[str] = set()
176
+ self._allowlist_source: str | None = None
177
+
178
+ def add_domains(self, source: BlocklistSource, domains: Iterable[str]) -> None:
179
+ self.sources.append(source)
180
+ self._actions[source.name] = source.action
181
+ for domain in domains:
182
+ self._domain_index.setdefault(domain.lower(), []).append(source.name)
183
+
184
+ def add_urls(self, source_name: str, urls: Iterable[str]) -> None:
185
+ for raw in urls:
186
+ entry = raw.lower().strip("/")
187
+ host = entry.split("/", 1)[0]
188
+ self._url_index.setdefault(host, []).append((entry, source_name))
189
+
190
+ def add_rules(self, source: BlocklistSource, rules: Iterable[tuple[str, str]]) -> None:
191
+ self.sources.append(source)
192
+ self._actions[source.name] = source.action
193
+ for label, expression in rules:
194
+ self._rules.append((label, re.compile(expression), source.name))
195
+
196
+ def add_allowlist(self, source: BlocklistSource, domains: Iterable[str]) -> None:
197
+ """UT1由来のドメイン一致を適用しないドメイン(プラットフォーム等)。"""
198
+
199
+ self.sources.append(source)
200
+ self._actions[source.name] = source.action
201
+ self._allowlist_source = source.name
202
+ self._allowlist.update(domain.lower() for domain in domains)
203
+
204
+ @classmethod
205
+ def load(cls, blocklist_dir: Path, cache_dir: Path | None) -> "DomainBlocklist":
206
+ config = json.loads((blocklist_dir / CONFIG_FILE).read_text(encoding="utf-8"))
207
+ blocklist = cls()
208
+ categories: dict[str, str] = config.get("ut1", {}).get("categories", {})
209
+ if categories:
210
+ if cache_dir is None or not (cache_dir / MANIFEST_FILE).exists():
211
+ raise FileNotFoundError(
212
+ f"UT1ブロックリストが未取得です: {cache_dir}. 先に "
213
+ f"`python {Path(__file__).name} fetch --dest {cache_dir}` を実行してください。"
214
+ )
215
+ manifest = json.loads((cache_dir / MANIFEST_FILE).read_text(encoding="utf-8"))
216
+ for category, action in categories.items():
217
+ meta = manifest["categories"].get(category)
218
+ domains_path = cache_dir / category / "domains"
219
+ if meta is None or not domains_path.exists():
220
+ raise FileNotFoundError(f"UT1カテゴリ {category} が取得されていません: {domains_path}")
221
+ domains = _read_list_lines(domains_path)
222
+ source = BlocklistSource(
223
+ name=f"ut1:{category}",
224
+ kind="ut1",
225
+ action=action,
226
+ entries=len(domains),
227
+ path=str(domains_path),
228
+ license=manifest.get("license", UT1_LICENSE),
229
+ source_url=meta.get("source_url"),
230
+ sha256=meta.get("sha256"),
231
+ fetched_at_utc=manifest.get("fetched_at_utc"),
232
+ )
233
+ blocklist.add_domains(source, domains)
234
+ urls_path = cache_dir / category / "urls"
235
+ if urls_path.exists():
236
+ blocklist.add_urls(source.name, _read_list_lines(urls_path))
237
+ local = config.get("local", {})
238
+ if local.get("allowlist"):
239
+ path = blocklist_dir / local["allowlist"]
240
+ domains = [line.split()[0].lower() for line in _read_list_lines(path)]
241
+ blocklist.add_allowlist(
242
+ BlocklistSource(
243
+ name="local:allowlist",
244
+ kind="local_allowlist",
245
+ action="allow",
246
+ entries=len(domains),
247
+ path=str(path),
248
+ license="repository",
249
+ sha256=_sha256(path.read_bytes()),
250
+ ),
251
+ domains,
252
+ )
253
+ if local.get("domains"):
254
+ path = blocklist_dir / local["domains"]
255
+ domains = [line.split()[0].lower() for line in _read_list_lines(path)]
256
+ source = BlocklistSource(
257
+ name="local:domains",
258
+ kind="local_domains",
259
+ action=local.get("action", "delete"),
260
+ entries=len(domains),
261
+ path=str(path),
262
+ license="repository",
263
+ sha256=_sha256(path.read_bytes()),
264
+ )
265
+ blocklist.add_domains(source, domains)
266
+ if local.get("rules"):
267
+ path = blocklist_dir / local["rules"]
268
+ rules: list[tuple[str, str]] = []
269
+ for line in _read_list_lines(path):
270
+ label, _, expression = line.partition("\t")
271
+ if not expression:
272
+ raise ValueError(f"規則の形式が不正です(ラベル<TAB>正規表現): {line}")
273
+ rules.append((label.strip(), expression.strip()))
274
+ source = BlocklistSource(
275
+ name="local:rules",
276
+ kind="local_rules",
277
+ action=local.get("action", "delete"),
278
+ entries=len(rules),
279
+ path=str(path),
280
+ license="repository",
281
+ sha256=_sha256(path.read_bytes()),
282
+ )
283
+ blocklist.add_rules(source, rules)
284
+ return blocklist
285
+
286
+ def match(self, url: Any) -> list[dict[str, Any]]:
287
+ host = normalize_host(url)
288
+ if not host:
289
+ return []
290
+ results: list[dict[str, Any]] = []
291
+ seen: set[tuple[str, str]] = set()
292
+
293
+ def add(source_name: str, matched: str, kind: str) -> None:
294
+ key = (source_name, matched)
295
+ if key not in seen:
296
+ seen.add(key)
297
+ results.append({"source": source_name, "action": self._actions[source_name], "matched": matched, "kind": kind})
298
+
299
+ suffixes = host_suffixes(host)
300
+ allowed = next((suffix for suffix in suffixes if suffix in self._allowlist), None)
301
+ for suffix in suffixes:
302
+ for source_name in self._domain_index.get(suffix, ()):
303
+ if allowed is not None and source_name.startswith("ut1:"):
304
+ add(self._allowlist_source or "local:allowlist", f"{allowed} (suppressed {source_name})", "allowlist")
305
+ continue
306
+ add(source_name, suffix, "domain")
307
+ if self._url_index and allowed is None:
308
+ path = urlparse(unicodedata.normalize("NFKC", str(url)).strip().lower()).path or "/"
309
+ full = host + path.rstrip("/")
310
+ for suffix in suffixes:
311
+ for entry, source_name in self._url_index.get(suffix, ()):
312
+ if full == entry or full.startswith(entry + "/"):
313
+ add(source_name, entry, "url")
314
+ for label, pattern, source_name in self._rules:
315
+ if pattern.search(host):
316
+ add(source_name, f"{label}:{pattern.pattern}", "rule")
317
+ return results
318
+
319
+ def manifest(self) -> list[dict[str, Any]]:
320
+ return [asdict(source) for source in self.sources]
321
+
322
+
323
+ def main(argv: list[str] | None = None) -> None:
324
+ here = Path(__file__).resolve().parent
325
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
326
+ sub = parser.add_subparsers(dest="command", required=True)
327
+ fetch = sub.add_parser("fetch", help="UT1のカテゴリ別リストを取得する")
328
+ fetch.add_argument("--dest", type=Path, required=True)
329
+ fetch.add_argument("--config", type=Path, default=here / "blocklists" / CONFIG_FILE)
330
+ fetch.add_argument("--category", action="append", default=None, help="省略時は設定ファイルの全カテゴリ")
331
+ fetch.add_argument("--mirror", action="store_true", help="公式サイトではなくGitHubミラーから取得する")
332
+ fetch.add_argument("--timeout", type=int, default=300)
333
+ check = sub.add_parser("check", help="URLを照合して結果を表示する")
334
+ check.add_argument("urls", nargs="+")
335
+ check.add_argument("--blocklist-dir", type=Path, default=here / "blocklists")
336
+ check.add_argument("--cache-dir", type=Path, default=here.parents[0] / "data" / "blocklists" / "ut1")
337
+ args = parser.parse_args(argv)
338
+ if args.command == "fetch":
339
+ config = json.loads(args.config.read_text(encoding="utf-8"))
340
+ categories = args.category or list(config.get("ut1", {}).get("categories", {}))
341
+ manifest = fetch_ut1(categories, args.dest, timeout=args.timeout, prefer_mirror=args.mirror)
342
+ summary = {category: {key: value for key, value in meta.items() if key != "sha256"} for category, meta in manifest["categories"].items()}
343
+ print(json.dumps(summary, ensure_ascii=False, indent=2))
344
+ else:
345
+ blocklist = DomainBlocklist.load(args.blocklist_dir, args.cache_dir)
346
+ for url in args.urls:
347
+ print(url, json.dumps(blocklist.match(url), ensure_ascii=False))
348
+
349
+
350
+ if __name__ == "__main__":
351
+ main()
code/e5cb5ca/src/filter_pii.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Parquet中の指定PIIをプレースホルダーへ置換する。
2
+
3
+ 実行入口と引数処理は ``main_pii.py`` に置き、このモジュールには置換処理と
4
+ 監査集計の定義だけを置く。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ from datetime import datetime, timezone
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ import pyarrow as pa
15
+ import pyarrow.parquet as pq
16
+
17
+ from pii_detector import PII_LABELS_JA, PLACEHOLDERS, PIIDetector, matches_to_dict
18
+
19
+
20
+ MODE_NAME = "pii_replace"
21
+ OUTPUT_DIR_NAME = "pii_replaced"
22
+
23
+
24
+ def policy_record(approver: str | None, approved_on: str | None, note: str | None = None) -> dict[str, Any]:
25
+ """処理方針の記録(監査項目12)。方針は全データセット共通で「置換」。
26
+
27
+ 削除も保持もしないため保持対象の承認は不要だが、方針そのものの承認者と
28
+ 日付を残す。未記入なら ``status`` は ``unapproved`` になる。
29
+ """
30
+
31
+ approved = bool(approver and approved_on)
32
+ return {
33
+ "action": "mask_with_placeholders",
34
+ "name_scope_ja": "個人名+所属(同じ文の前後25文字に組織名か役職語)、署名(執筆者・著者等の役割ラベル)、ラベル付き氏名を置換。敬称のみ・文脈なしの姓名は既定で保持し件数を記録。",
35
+ "action_ja": "検出したPIIを種別ごとのプレースホルダーへ置換する。文書の削除も、PIIのままの保持もしない。",
36
+ "scope_ja": "全データセット共通(url列と content列)",
37
+ "placeholders": dict(PLACEHOLDERS),
38
+ "retained_types": [],
39
+ "approved_by": approver,
40
+ "approved_on": approved_on,
41
+ "note": note,
42
+ "status": "approved" if approved else "unapproved",
43
+ }
44
+
45
+
46
+ def json_safe(value: Any) -> Any:
47
+ if value is None or isinstance(value, (str, int, bool)):
48
+ return value
49
+ if isinstance(value, float):
50
+ return value if value == value and abs(value) != float("inf") else None
51
+ if isinstance(value, (list, tuple)):
52
+ return [json_safe(item) for item in value]
53
+ if isinstance(value, dict):
54
+ return {str(key): json_safe(item) for key, item in value.items()}
55
+ return str(value)
56
+
57
+
58
+ def run_filter(
59
+ input_path: Path,
60
+ output_root: Path,
61
+ batch_size: int = 2048,
62
+ start_row: int = 0,
63
+ max_rows: int | None = None,
64
+ policy_approver: str | None = None,
65
+ policy_approved_on: str | None = None,
66
+ policy_note: str | None = None,
67
+ mask_honorific_names: bool = False,
68
+ mask_bare_names: bool = False,
69
+ affiliation_titles: bool = True,
70
+ ) -> dict[str, Any]:
71
+ """入力を全件保持し、URL・本文の検出値だけを置換して出力する。"""
72
+
73
+ output_dir = output_root / OUTPUT_DIR_NAME
74
+ output_dir.mkdir(parents=True, exist_ok=True)
75
+ parquet = pq.ParquetFile(input_path)
76
+ schema = parquet.schema_arrow
77
+ replaced_path = output_dir / "replaced.parquet"
78
+ audit_path = output_dir / "audit.jsonl"
79
+ writer = pq.ParquetWriter(replaced_path, schema, compression="zstd")
80
+ audit_handle = audit_path.open("w", encoding="utf-8", newline="\n")
81
+ detector = PIIDetector(include_url=True, mask_honorific_names=mask_honorific_names, mask_bare_names=mask_bare_names, affiliation_titles=affiliation_titles)
82
+ scanned_at = datetime.now(timezone.utc).isoformat()
83
+ by_type = {
84
+ pii_type: {"label_ja": label, "records_with_match": 0, "replacement_count": 0}
85
+ for pii_type, label in PII_LABELS_JA.items()
86
+ }
87
+ stats: dict[str, Any] = {
88
+ "filter_mode": MODE_NAME,
89
+ "criterion_ja": "電話番号、メールアドレス、番地レベル住所、個人名(単体・所属付き)、マイナンバー、カード番号、口座番号をプレースホルダーへ置換し、文書は削除しない",
90
+ "source_file": str(input_path),
91
+ "total_records_scanned": 0,
92
+ "records_with_replacement": 0,
93
+ "records_changed": 0,
94
+ "records_unchanged": 0,
95
+ "total_replacements": 0,
96
+ "by_type": by_type,
97
+ "pii_policy": policy_record(policy_approver, policy_approved_on, policy_note),
98
+ "detector_version": "pii_detector_v3_sudachi",
99
+ "row_range": {},
100
+ "input_schema": list(schema.names),
101
+ "matching_scope": "url + content",
102
+ "matching_normalization": "NFKC",
103
+ "method_ja": "正規表現、文脈ラベル、SudachiPy による人名(姓・名)検出と所属・役職・敬称文脈、マイナンバーチェックデジット、クレジットカードLuhn検証を併用。",
104
+ "note_ja": "外部NERモデルを使用しない決定的ベースライン。監査JSONLにはPII値を保存せず、マスキング済み一致値と置換後フィールドを記録する。残存件数は pii_residual_check.py(GLiNER-ja)で独立に確認する。",
105
+ }
106
+ stop_row = start_row + max_rows if max_rows is not None else None
107
+ row_offset = 0
108
+ try:
109
+ for source_batch in parquet.iter_batches(batch_size=batch_size):
110
+ source_batch_start = row_offset
111
+ row_offset += source_batch.num_rows
112
+ if row_offset <= start_row:
113
+ continue
114
+ if stop_row is not None and source_batch_start >= stop_row:
115
+ break
116
+ local_start = max(0, start_row - source_batch_start)
117
+ local_end = source_batch.num_rows if stop_row is None else min(source_batch.num_rows, stop_row - source_batch_start)
118
+ batch = source_batch.slice(local_start, local_end - local_start)
119
+ rows = batch.to_pylist()
120
+ replaced_rows: list[dict[str, Any]] = []
121
+ for row in rows:
122
+ url = row.get("url") or ""
123
+ content = row.get("content") or ""
124
+ replaced_url, replaced_content, matches = detector.replace_record(url, content)
125
+ output_row = dict(row)
126
+ if "url" in output_row and row.get("url") is not None:
127
+ output_row["url"] = replaced_url
128
+ if "content" in output_row and row.get("content") is not None:
129
+ output_row["content"] = replaced_content
130
+ replaced_rows.append(output_row)
131
+ stats["total_records_scanned"] += 1
132
+ stats["total_replacements"] += len(matches)
133
+ matched_types: set[str] = set()
134
+ for match in matches:
135
+ by_type[match.pii_type]["replacement_count"] += 1
136
+ matched_types.add(match.pii_type)
137
+ for pii_type in matched_types:
138
+ by_type[pii_type]["records_with_match"] += 1
139
+ if matches:
140
+ stats["records_with_replacement"] += 1
141
+ stats["records_changed"] += 1
142
+ audit_record = {
143
+ "record_index": start_row + stats["total_records_scanned"] - 1,
144
+ "url_replaced": json_safe(replaced_url),
145
+ "content_replaced": json_safe(replaced_content),
146
+ "_pii_replaced": True,
147
+ "_pii_filter_mode": MODE_NAME,
148
+ "_pii_detected_types": sorted(matched_types),
149
+ "_pii_detected_types_ja": [PII_LABELS_JA[item] for item in sorted(matched_types)],
150
+ "_pii_matches": matches_to_dict(matches),
151
+ "_pii_match_count": len(matches),
152
+ "_pii_source_file": str(input_path),
153
+ "_pii_scanned_at_utc": scanned_at,
154
+ }
155
+ audit_handle.write(json.dumps(audit_record, ensure_ascii=False, separators=(",", ":")) + "\n")
156
+ else:
157
+ stats["records_unchanged"] += 1
158
+ writer.write_table(pa.Table.from_pylist(replaced_rows, schema=schema))
159
+ finally:
160
+ writer.close()
161
+ audit_handle.close()
162
+
163
+ stats["row_range"] = {
164
+ "start_row_inclusive": start_row,
165
+ "end_row_exclusive": start_row + stats["total_records_scanned"],
166
+ }
167
+ stats.update({
168
+ "scanned_at_utc": scanned_at,
169
+ "person_name_unmasked_candidates": {
170
+ "honorific_only": {"records": detector.honorific_name_records, "spans": detector.honorific_name_candidates,
171
+ "masked": mask_honorific_names, "note_ja": "「○○さん/氏/様」だけの姓名。既定では置換しない(--mask-honorific-names で置換)。"},
172
+ "bare": {"records": detector.bare_name_records, "spans": detector.bare_name_candidates,
173
+ "masked": mask_bare_names, "note_ja": "文脈の無い姓名。既定では置換しない(--mask-bare-names で置換)。"},
174
+ },
175
+ "audit_jsonl": str(audit_path),
176
+ "replaced_parquet": str(replaced_path),
177
+ })
178
+ (output_root / "summary.json").write_text(json.dumps(stats, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
179
+ return stats
180
+
code/e5cb5ca/src/filter_toxic.py ADDED
@@ -0,0 +1,587 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """有害コンテンツのワードリスト検出と文書フィルタリング。
2
+
3
+ 実行入口と引数処理は ``main_toxic.py`` に置き、このモジュールには
4
+ ワードリストの読み込み、照合、出力および集計の定義だけを置く。現在の
5
+ 有害コンテンツ条件は、同一カテゴリの異なる語が3種類以上なら削除する
6
+ 単一条件(``distinct_terms_3plus``)に限定する。
7
+
8
+ 照合は部分一致だが、語の端がASCII英数字またはカタカナの場合は同種の文字が
9
+ 隣接する位置では一致させない(「メイク」中の「イク」、「DVD」中の「dv」を
10
+ 防ぐ)。さらに ``wordlists/exclude`` の除外リストで、汎用語を既存リストを
11
+ 書き換えずに照合対象から外せる。
12
+
13
+ 削除条件はワードリストのほかに、URLのドメインブロックリスト
14
+ (``domain_blocklist.py``)と近接共起規則(``cooccurrence.py``)がある。
15
+ 3系統の判定結果と理由別件数を summary.json と removed.jsonl に記録する。
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import json
21
+ import re
22
+ from collections import Counter, defaultdict
23
+ from dataclasses import dataclass
24
+ from datetime import datetime, timezone
25
+ from pathlib import Path
26
+ from typing import Any, Iterable
27
+
28
+ import pyarrow as pa
29
+ import pyarrow.parquet as pq
30
+
31
+ from cooccurrence import CooccurrenceDetector
32
+ from domain_blocklist import DomainBlocklist
33
+ from textmatch import ASCII_EDGE, KATAKANA_EDGE, compile_trie_pattern, normalize, read_terms as _read_terms # noqa: F401
34
+
35
+
36
+ CATEGORIES = (
37
+ "adult",
38
+ "violence",
39
+ "discrimination",
40
+ "crime",
41
+ "propaganda_conspiracy",
42
+ "spam",
43
+ )
44
+
45
+ CATEGORY_LABELS_JA = {
46
+ "adult": "性的・わいせつ",
47
+ "violence": "暴力・自傷・自殺",
48
+ "discrimination": "差別・ヘイト・誹謗中傷",
49
+ "crime": "違法行為の手引き",
50
+ "propaganda_conspiracy": "過激な政治・宗教プロパガンダ・陰謀論",
51
+ "spam": "スパム・詐欺・アダルト・違法コピー配布サイト由来",
52
+ }
53
+
54
+ MODE_CONFIGS: dict[str, dict[str, Any]] = {
55
+ "distinct_terms_3plus": {
56
+ "threshold": 3,
57
+ # カテゴリ別の上書き。crime は薬物名・手口名が報道や法律解説に並びやすいため5語以上にする。
58
+ "category_thresholds": {"crime": 5},
59
+ "criterion_ja": "同じカテゴリの異なる該当単語が3種類以上(crime は5種類以上、URLと本文の合計)ある文書を削除",
60
+ },
61
+ }
62
+
63
+
64
+ def category_threshold(config: dict[str, Any], category: str) -> int:
65
+ return int(config.get("category_thresholds", {}).get(category, config["threshold"]))
66
+
67
+
68
+ def json_safe(value: Any) -> Any:
69
+ """JSONLに書ける基本型へ変換する。"""
70
+
71
+ if value is None or isinstance(value, (str, int, bool)):
72
+ return value
73
+ if isinstance(value, float):
74
+ return value if value == value and abs(value) != float("inf") else None
75
+ if isinstance(value, (list, tuple)):
76
+ return [json_safe(item) for item in value]
77
+ if isinstance(value, dict):
78
+ return {str(key): json_safe(item) for key, item in value.items()}
79
+ return str(value)
80
+
81
+
82
+ @dataclass(frozen=True)
83
+ class Wordlists:
84
+ """カテゴリ別の照合語と、その出典および除外された語。"""
85
+
86
+ terms: dict[str, list[str]]
87
+ sources: dict[str, dict[str, list[str]]]
88
+ excluded: dict[str, list[str]]
89
+
90
+
91
+ def load_wordlists(
92
+ reference_dir: Path,
93
+ additional_dir: Path,
94
+ exclude_dir: Path | None = None,
95
+ ) -> Wordlists:
96
+ """referenceと追加リストを統合し、除外リストの語を取り除く。
97
+
98
+ 正規化後に重複した語は一つにまとめる。``exclude_dir`` の
99
+ ``ja_<category>_exclude.txt`` にある語は、出典にかかわらず当該カテゴリの
100
+ 照合対象から外す。汎用語による誤検出を、既存リストを書き換えずに
101
+ 抑えるための仕組みである。実際に取り除いた語は ``excluded`` に残す。
102
+ """
103
+
104
+ terms_by_category: dict[str, list[str]] = {}
105
+ sources_by_category: dict[str, dict[str, list[str]]] = {}
106
+ excluded_by_category: dict[str, list[str]] = {}
107
+ for category in CATEGORIES:
108
+ source_terms: dict[str, set[str]] = defaultdict(set)
109
+ for source_name, directory in (("reference", reference_dir), ("additional", additional_dir)):
110
+ for term in _read_terms(directory / f"ja_{category}_keywords.txt"):
111
+ source_terms[term].add(source_name)
112
+ excluded: set[str] = set()
113
+ if exclude_dir is not None:
114
+ excluded = set(_read_terms(exclude_dir / f"ja_{category}_exclude.txt"))
115
+ excluded_by_category[category] = sorted(term for term in excluded if term in source_terms)
116
+ terms = sorted(
117
+ (term for term in source_terms if term not in excluded),
118
+ key=lambda term: (-len(term), term),
119
+ )
120
+ terms_by_category[category] = terms
121
+ sources_by_category[category] = {
122
+ term: sorted(source_terms[term]) for term in terms
123
+ }
124
+ return Wordlists(terms_by_category, sources_by_category, excluded_by_category)
125
+
126
+
127
+ class KeywordMatcher:
128
+ """全カテゴリの語を一度の正規表現走査で数える。
129
+
130
+ 本文は文字種境界付きで照合する。URLはドメインやパスが単語を区切りなしに
131
+ 連結する(sexynews、hentaio など)ため境界なしで照合する。URL中の日本語は
132
+ パーセント符号化されているので、影響を受けるのはASCII語だけである。
133
+ """
134
+
135
+ def __init__(
136
+ self,
137
+ terms_by_category: dict[str, list[str]],
138
+ sources_by_category: dict[str, dict[str, list[str]]],
139
+ ) -> None:
140
+ self.sources_by_category = sources_by_category
141
+ term_categories: dict[str, list[str]] = defaultdict(list)
142
+ for category in CATEGORIES:
143
+ for term in terms_by_category[category]:
144
+ term_categories[term].append(category)
145
+ self.term_categories = {
146
+ term: tuple(categories) for term, categories in term_categories.items()
147
+ }
148
+ alternatives = sorted(self.term_categories, key=lambda term: (-len(term), term))
149
+ self.pattern = compile_trie_pattern(alternatives)
150
+ self.url_pattern = compile_trie_pattern(alternatives, boundaries=False)
151
+
152
+ def count_text(self, text: Any, pattern: re.Pattern[str] | None = None) -> Counter[tuple[str, str]]:
153
+ counts: Counter[tuple[str, str]] = Counter()
154
+ normalized = normalize(text)
155
+ if not normalized:
156
+ return counts
157
+ for found in (pattern or self.pattern).finditer(normalized):
158
+ term = found.group(0)
159
+ for category in self.term_categories[term]:
160
+ counts[(category, term)] += 1
161
+ return counts
162
+
163
+ def match_record(self, url: Any, content: Any) -> list[dict[str, Any]]:
164
+ url_counts = self.count_text(url, self.url_pattern)
165
+ content_counts = self.count_text(content)
166
+ total_counts = url_counts + content_counts
167
+ return [
168
+ {
169
+ "category": category,
170
+ "category_ja": CATEGORY_LABELS_JA[category],
171
+ "term": term,
172
+ "occurrences": occurrences,
173
+ "url_occurrences": url_counts[(category, term)],
174
+ "content_occurrences": content_counts[(category, term)],
175
+ "wordlist_sources": self.sources_by_category[category][term],
176
+ }
177
+ for (category, term), occurrences in sorted(
178
+ total_counts.items(),
179
+ key=lambda item: (CATEGORIES.index(item[0][0]), item[0][1]),
180
+ )
181
+ ]
182
+
183
+
184
+ def _new_stats(
185
+ mode_name: str,
186
+ source_file: Path,
187
+ wordlist_counts: dict[str, int],
188
+ ) -> dict[str, Any]:
189
+ config = MODE_CONFIGS[mode_name]
190
+ return {
191
+ "filter_mode": mode_name,
192
+ "threshold": config["threshold"],
193
+ "category_thresholds": config.get("category_thresholds", {}),
194
+ "criterion_ja": config["criterion_ja"],
195
+ "source_file": str(source_file),
196
+ "wordlist_unique_terms_by_category": wordlist_counts,
197
+ "total_records_scanned": 0,
198
+ "records_with_any_keyword_match": 0,
199
+ "records_deleted": 0,
200
+ "records_retained": 0,
201
+ "deletion_rate": 0.0,
202
+ "records_deleted_by_reason": {"wordlist": 0, "domain_blocklist": 0, "cooccurrence": 0, "multiple_reasons": 0},
203
+ "domain_blocklist": {"enabled": False},
204
+ "cooccurrence": {"enabled": False},
205
+ "total_keyword_occurrences": 0,
206
+ "by_category": {
207
+ category: {
208
+ "label_ja": CATEGORY_LABELS_JA[category],
209
+ "records_with_match": 0,
210
+ "records_deleted": 0,
211
+ "keyword_occurrences": 0,
212
+ "distinct_terms_matched": 0,
213
+ }
214
+ for category in CATEGORIES
215
+ },
216
+ "top_matched_terms": [],
217
+ "term_statistics": [],
218
+ }
219
+
220
+
221
+ def _distinct_terms_by_category(matches: list[dict[str, Any]]) -> dict[str, list[str]]:
222
+ terms_by_category: dict[str, set[str]] = {category: set() for category in CATEGORIES}
223
+ for item in matches:
224
+ terms_by_category[item["category"]].add(item["term"])
225
+ return {category: sorted(terms) for category, terms in terms_by_category.items() if terms}
226
+
227
+
228
+ def _deleted_categories(
229
+ matches: list[dict[str, Any]],
230
+ threshold: int,
231
+ category_thresholds: dict[str, int] | None = None,
232
+ ) -> list[str]:
233
+ distinct = _distinct_terms_by_category(matches)
234
+ overrides = category_thresholds or {}
235
+ return [
236
+ category for category in CATEGORIES
237
+ if len(distinct.get(category, ())) >= int(overrides.get(category, threshold))
238
+ ]
239
+
240
+
241
+ def _update_stats(
242
+ stats: dict[str, Any],
243
+ matches: list[dict[str, Any]],
244
+ deleted_categories: list[str],
245
+ term_record_counts: Counter[tuple[str, str]],
246
+ term_occurrence_counts: Counter[tuple[str, str]],
247
+ ) -> None:
248
+ if not matches:
249
+ return
250
+ stats["records_with_any_keyword_match"] += 1
251
+ total_occurrences = sum(item["occurrences"] for item in matches)
252
+ stats["total_keyword_occurrences"] += total_occurrences
253
+ for category in {item["category"] for item in matches}:
254
+ category_items = [item for item in matches if item["category"] == category]
255
+ category_stats = stats["by_category"][category]
256
+ category_stats["records_with_match"] += 1
257
+ category_stats["keyword_occurrences"] += sum(item["occurrences"] for item in category_items)
258
+ if category in deleted_categories:
259
+ category_stats["records_deleted"] += 1
260
+ for item in matches:
261
+ key = (item["category"], item["term"])
262
+ term_record_counts[key] += 1
263
+ term_occurrence_counts[key] += item["occurrences"]
264
+
265
+
266
+ def _finalize_stats(
267
+ stats: dict[str, Any],
268
+ term_record_counts: Counter[tuple[str, str]],
269
+ term_occurrence_counts: Counter[tuple[str, str]],
270
+ ) -> None:
271
+ total = stats["total_records_scanned"]
272
+ stats["records_retained"] = total - stats["records_deleted"]
273
+ stats["deletion_rate"] = stats["records_deleted"] / total if total else 0.0
274
+ stats["term_statistics"] = [
275
+ {
276
+ "category": category,
277
+ "category_ja": CATEGORY_LABELS_JA[category],
278
+ "term": term,
279
+ "records_with_match": term_record_counts[(category, term)],
280
+ "keyword_occurrences": term_occurrence_counts[(category, term)],
281
+ }
282
+ for category, term in sorted(term_record_counts, key=lambda key: (CATEGORIES.index(key[0]), key[1]))
283
+ ]
284
+ for category in CATEGORIES:
285
+ stats["by_category"][category]["distinct_terms_matched"] = sum(
286
+ 1 for item in stats["term_statistics"] if item["category"] == category
287
+ )
288
+ stats["top_matched_terms"] = sorted(
289
+ stats["term_statistics"],
290
+ key=lambda item: (-item["records_with_match"], -item["keyword_occurrences"], item["category"], item["term"]),
291
+ )[:100]
292
+
293
+
294
+ def _new_blocklist_stats(blocklist: DomainBlocklist) -> dict[str, Any]:
295
+ return {
296
+ "enabled": True,
297
+ "sources": blocklist.manifest(),
298
+ "records_matched": 0,
299
+ "records_deleted": 0,
300
+ "records_flagged_only": 0,
301
+ "by_source": {
302
+ source["name"]: {"action": source["action"], "records_matched": 0, "records_deleted": 0}
303
+ for source in blocklist.manifest()
304
+ },
305
+ }
306
+
307
+
308
+ def _new_cooccurrence_stats(detector: CooccurrenceDetector) -> dict[str, Any]:
309
+ return {
310
+ "enabled": True,
311
+ "rules": detector.describe(),
312
+ "records_matched": 0,
313
+ "records_deleted": 0,
314
+ "by_rule": {
315
+ rule["name"]: {
316
+ "label_ja": rule["label_ja"],
317
+ "category": rule["category"],
318
+ "records_matched": 0,
319
+ "pair_counts": Counter(),
320
+ }
321
+ for rule in detector.describe()
322
+ },
323
+ }
324
+
325
+
326
+ REASON_LABELS_JA = {
327
+ "wordlist": "ワードリスト(同一カテゴリ3語以上)",
328
+ "domain_blocklist": "URLのドメインがブロックリストに一致",
329
+ "cooccurrence": "近接共起規則(未成年×性的文脈、違法物×手引き)",
330
+ }
331
+
332
+
333
+ def run_toxic_filters(
334
+ input_path: Path,
335
+ output_root: Path,
336
+ reference_dir: Path,
337
+ additional_dir: Path,
338
+ batch_size: int = 2048,
339
+ modes: Iterable[str] | None = None,
340
+ start_row: int = 0,
341
+ max_rows: int | None = None,
342
+ exclude_dir: Path | None = None,
343
+ blocklist: DomainBlocklist | None = None,
344
+ cooccurrence: CooccurrenceDetector | None = None,
345
+ ) -> dict[str, Any]:
346
+ """指定モードの有害コンテンツフィルタを一度の走査で実行する。
347
+
348
+ 削除条件は3系統ある。(1) ワードリストの同一カテゴリ3語以上、(2) URLの
349
+ ドメインブロックリスト、(3) 近接共起規則。(2)(3) はモードに依存せず
350
+ 全モードで同じ判定になる。共起規則の一致は全件を
351
+ ``cooccurrence_review.jsonl`` に、ブロックリストの記録のみ一致は
352
+ ``flagged.jsonl`` に書き出す。
353
+ """
354
+
355
+ selected_modes = list(modes) if modes is not None else list(MODE_CONFIGS)
356
+ unknown = [mode for mode in selected_modes if mode not in MODE_CONFIGS]
357
+ if unknown:
358
+ raise ValueError(f"未知のモード: {', '.join(unknown)}")
359
+ if not selected_modes:
360
+ raise ValueError("少なくとも1つのモードを指定してください")
361
+
362
+ wordlists = load_wordlists(reference_dir, additional_dir, exclude_dir)
363
+ wordlist_counts = {category: len(wordlists.terms[category]) for category in CATEGORIES}
364
+ matcher = KeywordMatcher(wordlists.terms, wordlists.sources)
365
+ output_dirs = {mode: output_root / mode for mode in selected_modes}
366
+ for directory in output_dirs.values():
367
+ directory.mkdir(parents=True, exist_ok=True)
368
+ parquet = pq.ParquetFile(input_path)
369
+ schema = parquet.schema_arrow
370
+ writers = {
371
+ mode: pq.ParquetWriter(directory / "retained.parquet", schema, compression="zstd")
372
+ for mode, directory in output_dirs.items()
373
+ }
374
+ handles = {
375
+ mode: (directory / "removed.jsonl").open("w", encoding="utf-8", newline="\n")
376
+ for mode, directory in output_dirs.items()
377
+ }
378
+ review_handles = {
379
+ mode: (directory / "cooccurrence_review.jsonl").open("w", encoding="utf-8", newline="\n")
380
+ for mode, directory in output_dirs.items()
381
+ } if cooccurrence is not None else {}
382
+ flagged_handles = {
383
+ mode: (directory / "flagged.jsonl").open("w", encoding="utf-8", newline="\n")
384
+ for mode, directory in output_dirs.items()
385
+ } if blocklist is not None else {}
386
+ borderline_handles = {
387
+ mode: (directory / "borderline.jsonl").open("w", encoding="utf-8", newline="\n")
388
+ for mode, directory in output_dirs.items()
389
+ }
390
+ stats_by_mode = {mode: _new_stats(mode, input_path, wordlist_counts) for mode in selected_modes}
391
+ for stats in stats_by_mode.values():
392
+ if blocklist is not None:
393
+ stats["domain_blocklist"] = _new_blocklist_stats(blocklist)
394
+ if cooccurrence is not None:
395
+ stats["cooccurrence"] = _new_cooccurrence_stats(cooccurrence)
396
+ record_counts = {mode: Counter() for mode in selected_modes}
397
+ occurrence_counts = {mode: Counter() for mode in selected_modes}
398
+ scanned_at = datetime.now(timezone.utc).isoformat()
399
+ stop_row = start_row + max_rows if max_rows is not None else None
400
+ row_offset = 0
401
+ scanned = 0
402
+ try:
403
+ for source_batch in parquet.iter_batches(batch_size=batch_size):
404
+ source_start = row_offset
405
+ row_offset += source_batch.num_rows
406
+ if row_offset <= start_row:
407
+ continue
408
+ if stop_row is not None and source_start >= stop_row:
409
+ break
410
+ local_start = max(0, start_row - source_start)
411
+ local_end = source_batch.num_rows if stop_row is None else min(source_batch.num_rows, stop_row - source_start)
412
+ batch = source_batch.slice(local_start, local_end - local_start)
413
+ rows = batch.to_pylist()
414
+ retained_indices = {mode: [] for mode in selected_modes}
415
+ for row_index, row in enumerate(rows):
416
+ url = row.get("url") or ""
417
+ content = row.get("content") or ""
418
+ record_index = start_row + scanned
419
+ scanned += 1
420
+ matches = matcher.match_record(url, content)
421
+ domain_matches = blocklist.match(url) if blocklist is not None else []
422
+ domain_delete = any(item["action"] == "delete" for item in domain_matches)
423
+ cooccurrence_matches = cooccurrence.detect(content) if cooccurrence is not None else []
424
+ for mode in selected_modes:
425
+ config = MODE_CONFIGS[mode]
426
+ deleted_categories = _deleted_categories(matches, config["threshold"], config.get("category_thresholds"))
427
+ reasons = []
428
+ if deleted_categories:
429
+ reasons.append("wordlist")
430
+ if domain_delete:
431
+ reasons.append("domain_blocklist")
432
+ if cooccurrence_matches:
433
+ reasons.append("cooccurrence")
434
+ deleted = bool(reasons)
435
+ stats = stats_by_mode[mode]
436
+ stats["total_records_scanned"] += 1
437
+ _update_stats(stats, matches, deleted_categories, record_counts[mode], occurrence_counts[mode])
438
+ if domain_matches:
439
+ block_stats = stats["domain_blocklist"]
440
+ block_stats["records_matched"] += 1
441
+ if deleted:
442
+ block_stats["records_deleted"] += 1
443
+ elif not domain_delete:
444
+ block_stats["records_flagged_only"] += 1
445
+ for source_name in {item["source"] for item in domain_matches}:
446
+ block_stats["by_source"][source_name]["records_matched"] += 1
447
+ if deleted:
448
+ block_stats["by_source"][source_name]["records_deleted"] += 1
449
+ if cooccurrence_matches:
450
+ cooc_stats = stats["cooccurrence"]
451
+ cooc_stats["records_matched"] += 1
452
+ cooc_stats["records_deleted"] += 1
453
+ for item in cooccurrence_matches:
454
+ rule_stats = cooc_stats["by_rule"][item["rule"]]
455
+ rule_stats["records_matched"] += 1
456
+ for pair in item["pairs"]:
457
+ rule_stats["pair_counts"][f"{pair['a']}|{pair['b']}"] += 1
458
+ review_handles[mode].write(json.dumps({
459
+ "record_index": record_index,
460
+ "url": json_safe(url),
461
+ "rule": item["rule"],
462
+ "label_ja": item["label_ja"],
463
+ "pair_count": item["pair_count"],
464
+ "pairs": item["pairs"],
465
+ "excerpt": item["excerpt"],
466
+ "reviewer": "",
467
+ "verdict": "",
468
+ "reason": "",
469
+ }, ensure_ascii=False, separators=(",", ":")) + "\n")
470
+ if deleted:
471
+ stats["records_deleted"] += 1
472
+ for reason in reasons:
473
+ stats["records_deleted_by_reason"][reason] += 1
474
+ if len(reasons) > 1:
475
+ stats["records_deleted_by_reason"]["multiple_reasons"] += 1
476
+ output_record = {str(key): json_safe(value) for key, value in row.items()}
477
+ output_record.update(
478
+ {
479
+ "_filter_deleted": True,
480
+ "_filter_mode": mode,
481
+ "_filter_threshold": config["threshold"],
482
+ "_filter_deleted_by": reasons,
483
+ "_filter_reason": ";".join(REASON_LABELS_JA[reason] for reason in reasons),
484
+ "_filter_deleted_categories": deleted_categories,
485
+ "_filter_distinct_matched_terms_by_category": {
486
+ category: sorted({item["term"] for item in matches if item["category"] == category})
487
+ for category in deleted_categories
488
+ },
489
+ "_filter_matched_terms": matches,
490
+ "_filter_total_keyword_occurrences": sum(item["occurrences"] for item in matches),
491
+ "_filter_domain_matches": domain_matches,
492
+ "_filter_cooccurrence_matches": cooccurrence_matches,
493
+ "_filter_record_index": record_index,
494
+ "_filter_method": "wordlist_toxic_filter_v4",
495
+ "_filter_source_file": str(input_path),
496
+ "_filter_scanned_at_utc": scanned_at,
497
+ }
498
+ )
499
+ handles[mode].write(json.dumps(output_record, ensure_ascii=False, separators=(",", ":")) + "\n")
500
+ else:
501
+ borderline = {
502
+ category: terms
503
+ for category, terms in _distinct_terms_by_category(matches).items()
504
+ if len(terms) == category_threshold(config, category) - 1
505
+ }
506
+ if borderline:
507
+ borderline_handles[mode].write(json.dumps({
508
+ "record_index": record_index,
509
+ "url": json_safe(url),
510
+ "categories": borderline,
511
+ }, ensure_ascii=False, separators=(",", ":")) + "\n")
512
+ if domain_matches:
513
+ flagged_handles[mode].write(json.dumps({
514
+ "record_index": record_index,
515
+ "url": json_safe(url),
516
+ "domain_matches": domain_matches,
517
+ }, ensure_ascii=False, separators=(",", ":")) + "\n")
518
+ retained_indices[mode].append(row_index)
519
+ for mode in selected_modes:
520
+ if retained_indices[mode]:
521
+ writers[mode].write_batch(batch.take(pa.array(retained_indices[mode], type=pa.int64())))
522
+ finally:
523
+ for writer in writers.values():
524
+ writer.close()
525
+ for handle in (
526
+ list(handles.values()) + list(review_handles.values())
527
+ + list(flagged_handles.values()) + list(borderline_handles.values())
528
+ ):
529
+ handle.close()
530
+
531
+ for mode, stats in stats_by_mode.items():
532
+ _finalize_stats(stats, record_counts[mode], occurrence_counts[mode])
533
+ if stats["cooccurrence"].get("enabled"):
534
+ for rule_stats in stats["cooccurrence"]["by_rule"].values():
535
+ rule_stats["pair_counts"] = [
536
+ {"pair": pair, "records": count} for pair, count in rule_stats["pair_counts"].most_common(30)
537
+ ]
538
+ stats.update(
539
+ {
540
+ "scanned_at_utc": scanned_at,
541
+ "input_schema": list(schema.names),
542
+ "row_range": {
543
+ "start_row_inclusive": start_row,
544
+ "end_row_exclusive": start_row + stats["total_records_scanned"],
545
+ },
546
+ "removed_jsonl": str(output_dirs[mode] / "removed.jsonl"),
547
+ "retained_parquet": str(output_dirs[mode] / "retained.parquet"),
548
+ "cooccurrence_review_jsonl": str(output_dirs[mode] / "cooccurrence_review.jsonl") if cooccurrence is not None else None,
549
+ "flagged_jsonl": str(output_dirs[mode] / "flagged.jsonl") if blocklist is not None else None,
550
+ "borderline_jsonl": str(output_dirs[mode] / "borderline.jsonl"),
551
+ "wordlist_reference_dir": str(reference_dir),
552
+ "wordlist_additional_dir": str(additional_dir),
553
+ "wordlist_exclude_dir": str(exclude_dir) if exclude_dir is not None else None,
554
+ "wordlist_excluded_terms_by_category": wordlists.excluded,
555
+ "wordlist_matching_scope": "url + content",
556
+ "matching_normalization": "NFKC then lowercase",
557
+ "same_position_partial_match_policy": "longest match first",
558
+ "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",
559
+ "deletion_reasons_ja": REASON_LABELS_JA,
560
+ "note_ja": "候補語・ブロックリスト・共起規則による機械的な監査結果。最終除外前に文脈と誤検出を確認すること。",
561
+ }
562
+ )
563
+ (output_dirs[mode] / "summary.json").write_text(json.dumps(stats, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
564
+
565
+ combined = {
566
+ "source_file": str(input_path),
567
+ "scanned_at_utc": scanned_at,
568
+ "wordlist_reference_dir": str(reference_dir),
569
+ "wordlist_additional_dir": str(additional_dir),
570
+ "wordlist_exclude_dir": str(exclude_dir) if exclude_dir is not None else None,
571
+ "wordlist_excluded_terms_by_category": wordlists.excluded,
572
+ "wordlist_unique_terms_by_category": wordlist_counts,
573
+ "domain_blocklist_sources": blocklist.manifest() if blocklist is not None else None,
574
+ "cooccurrence_rules": cooccurrence.describe() if cooccurrence is not None else None,
575
+ "row_range": {
576
+ "start_row_inclusive": start_row,
577
+ "end_row_exclusive": start_row + next(iter(stats_by_mode.values()))["total_records_scanned"],
578
+ },
579
+ "modes": {mode: stats_by_mode[mode] for mode in selected_modes},
580
+ }
581
+ output_root.mkdir(parents=True, exist_ok=True)
582
+ (output_root / "summary.json").write_text(json.dumps(combined, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
583
+ return combined
584
+
585
+
586
+ # 既存コードから呼び出す場合の簡潔な別名。
587
+ run_filter = run_toxic_filters
code/e5cb5ca/src/hf_jobs_launch.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HF Jobs で全シャードのクレンジングを実行するランチャー。
2
+
3
+ ``common_crawl_0`` 〜 ``common_crawl_18`` の各ディレクトリを1ジョブにし、次を行う。
4
+
5
+ * 入力データセット(``Podtech/abeja-cc-ja-filtered``)を ``/data`` にマウント(ダウンロード不要)
6
+ * このリポジトリの ``src/`` と UT1 ブロックリストのキャッシュを、出力用の非公開データセットへ
7
+ ``code/<ref>/src`` と ``blocklists/ut1`` として1回だけアップロードし、各ジョブがそこから取得する
8
+ (全ジョブが同じコード・同じリストで動くことをマニフェストで保証する)
9
+ * ``HF_TOKEN`` はシークレットとして渡す(ログに出ない)
10
+ * ``run_shard.py`` を ``--upload-repo`` 付きで実行し、出力は ``outputs/common_crawl_N/<shard>/`` へ
11
+ シャード単位でアップロードして一時ディスクから削除する
12
+ * タイムアウトは既定の30分ではなく ``--timeout``(既定 6h)を指定する
13
+
14
+ uv run --env-file .env python abeja-cc-ja/src/hf_jobs_launch.py --dirs 0 --limit-shards 2 --dry-run
15
+ uv run --env-file .env python abeja-cc-ja/src/hf_jobs_launch.py --dirs 0 --limit-shards 2
16
+ 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
17
+
18
+ 完了後は ``aggregate_summaries.py --repo <出力repo> --prefix outputs --expected-inputs <入力repo>`` で集約する。
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import argparse
24
+ import hashlib
25
+ import json
26
+ import os
27
+ import shlex
28
+ import subprocess
29
+ from datetime import datetime, timezone
30
+ from pathlib import Path
31
+ from typing import Any
32
+
33
+
34
+ DEFAULT_INPUT = "Podtech/abeja-cc-ja-filtered"
35
+ DEFAULT_OUTPUT = "Podtech/abeja-cc-ja-cleaned"
36
+ DEFAULT_IMAGE = "python:3.12"
37
+ DEFAULT_FLAVOR = "cpu-upgrade"
38
+ DEFAULT_TIMEOUT = "6h"
39
+ CODE_IGNORE = ["__pycache__/**", "*.pyc", ".pytest_cache/**", "test_*.py", "*.md"]
40
+
41
+
42
+ def parse_dirs(spec: str) -> list[int]:
43
+ result: list[int] = []
44
+ for part in spec.split(","):
45
+ part = part.strip()
46
+ if "-" in part:
47
+ low, high = part.split("-", 1)
48
+ result.extend(range(int(low), int(high) + 1))
49
+ elif part:
50
+ result.append(int(part))
51
+ return sorted(set(result))
52
+
53
+
54
+ def code_ref(code_dir: Path) -> str:
55
+ """git のコミット短縮ハッシュ(未コミット変更があれば -dirty と内容ハッシュ)。"""
56
+
57
+ try:
58
+ sha = subprocess.check_output(["git", "rev-parse", "--short", "HEAD"], cwd=code_dir, text=True).strip()
59
+ dirty = subprocess.check_output(["git", "status", "--porcelain", "--", "."], cwd=code_dir, text=True).strip() != ""
60
+ except Exception: # noqa: BLE001
61
+ sha, dirty = "nogit", True
62
+ if not dirty:
63
+ return sha
64
+ digest = hashlib.sha256()
65
+ for path in sorted(code_dir.rglob("*")):
66
+ if path.is_file() and "__pycache__" not in path.parts and not path.name.startswith("test_"):
67
+ digest.update(path.relative_to(code_dir).as_posix().encode())
68
+ digest.update(path.read_bytes())
69
+ return f"{sha}-dirty-{digest.hexdigest()[:8]}"
70
+
71
+
72
+ def build_job_script(output_repo: str, ref: str, dir_index: int, args: argparse.Namespace) -> str:
73
+ input_dir = f"/data/data/common_crawl_{dir_index}"
74
+ run_args = [
75
+ "--input-dir", input_dir,
76
+ "--output-root", f"/work/out/common_crawl_{dir_index}",
77
+ "--blocklist-cache-dir", "/work/repo/blocklists/ut1",
78
+ "--upload-repo", output_repo,
79
+ "--upload-prefix", f"outputs/common_crawl_{dir_index}",
80
+ "--upload-batch", str(args.upload_batch),
81
+ "--delete-local-after-upload",
82
+ "--skip-existing-in-repo",
83
+ ]
84
+ if args.limit_shards is not None:
85
+ run_args += ["--limit-shards", str(args.limit_shards)]
86
+ if args.policy_approver:
87
+ run_args += ["--policy-approver", args.policy_approver]
88
+ if args.policy_approved_on:
89
+ run_args += ["--policy-approved-on", args.policy_approved_on]
90
+ if args.policy_note:
91
+ run_args += ["--policy-note", args.policy_note]
92
+ workers_expr = str(args.workers) if args.workers else '"$(( ${CPU_CORES:-2} > 1 ? ${CPU_CORES:-2} - 1 : 1 ))"'
93
+ snapshot = (
94
+ "from huggingface_hub import snapshot_download; "
95
+ f"snapshot_download({output_repo!r}, repo_type='dataset', local_dir='/work/repo', "
96
+ f"allow_patterns=['code/{ref}/**', 'blocklists/ut1/**'])"
97
+ )
98
+ lines = [
99
+ "set -euo pipefail",
100
+ "export PIP_DISABLE_PIP_VERSION_CHECK=1 PYTHONUNBUFFERED=1",
101
+ 'pip install -q "pyarrow>=17" "huggingface_hub>=1.0" "sudachipy>=0.6" "sudachidict_core"',
102
+ "mkdir -p /work/out && cd /work",
103
+ f"python -c {shlex.quote(snapshot)}",
104
+ f"ls /work/repo/code/{ref}/src >/dev/null",
105
+ f"test -f /work/repo/blocklists/ut1/manifest.json",
106
+ # pipefail 下で `ls | head` は SIGPIPE で失敗し得るため、件数だけを表示する
107
+ f'echo "input shards: $(ls {input_dir} | wc -l)"',
108
+ f"python /work/repo/code/{ref}/src/run_shard.py " + " ".join(shlex.quote(a) for a in run_args) + f" --workers {workers_expr}",
109
+ ]
110
+ return "\n".join(lines) + "\n"
111
+
112
+
113
+ def upload_code_and_blocklists(api, output_repo: str, code_dir: Path, ref: str, ut1_cache_dir: Path, dry_run: bool) -> dict[str, Any]:
114
+ existing = set(api.list_repo_files(output_repo, repo_type="dataset")) if not dry_run else set()
115
+ code_prefix = f"code/{ref}/src"
116
+ 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"))
117
+ manifest = {
118
+ "ref": ref,
119
+ "uploaded_at_utc": datetime.now(timezone.utc).isoformat(),
120
+ "files": {p.relative_to(code_dir).as_posix(): hashlib.sha256(p.read_bytes()).hexdigest() for p in files},
121
+ }
122
+ actions: dict[str, Any] = {"code_prefix": code_prefix, "code_files": len(files), "ref": ref}
123
+ if dry_run:
124
+ actions["code_upload"] = "dry-run"
125
+ elif f"{code_prefix}/run_shard.py" in existing:
126
+ actions["code_upload"] = "already present"
127
+ else:
128
+ api.upload_folder(repo_id=output_repo, repo_type="dataset", folder_path=str(code_dir), path_in_repo=code_prefix,
129
+ ignore_patterns=CODE_IGNORE, commit_message=f"code {ref}")
130
+ api.upload_file(repo_id=output_repo, repo_type="dataset", path_or_fileobj=json.dumps(manifest, ensure_ascii=False, indent=2).encode("utf-8"),
131
+ path_in_repo=f"code/{ref}/MANIFEST.json", commit_message=f"code manifest {ref}")
132
+ actions["code_upload"] = "uploaded"
133
+ if not (ut1_cache_dir / "manifest.json").exists():
134
+ raise FileNotFoundError(f"UT1 キャッシュがありません: {ut1_cache_dir}(domain_blocklist.py fetch を先に実行)")
135
+ if dry_run:
136
+ actions["blocklist_upload"] = "dry-run"
137
+ elif "blocklists/ut1/manifest.json" in existing:
138
+ actions["blocklist_upload"] = "already present"
139
+ else:
140
+ api.upload_folder(repo_id=output_repo, repo_type="dataset", folder_path=str(ut1_cache_dir), path_in_repo="blocklists/ut1",
141
+ commit_message="UT1 blocklists snapshot")
142
+ actions["blocklist_upload"] = "uploaded"
143
+ return actions
144
+
145
+
146
+ def main(argv: list[str] | None = None) -> None:
147
+ source_dir = Path(__file__).resolve().parent
148
+ project_root = source_dir.parent
149
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
150
+ parser.add_argument("--input-dataset", default=DEFAULT_INPUT)
151
+ parser.add_argument("--output-repo", default=DEFAULT_OUTPUT, help="非公開で作成される出力データセット")
152
+ parser.add_argument("--dirs", default="0-18", help="例: 0-18, 0,1,2")
153
+ parser.add_argument("--flavor", default=DEFAULT_FLAVOR)
154
+ parser.add_argument("--timeout", default=DEFAULT_TIMEOUT, help="例: 6h, 90m")
155
+ parser.add_argument("--image", default=DEFAULT_IMAGE)
156
+ parser.add_argument("--namespace", default=None, help="課金先。既定は出力リポジトリの所有者")
157
+ parser.add_argument("--workers", type=int, default=None, help="既定はジョブ内の CPU_CORES - 1")
158
+ parser.add_argument("--upload-batch", type=int, default=5)
159
+ parser.add_argument("--limit-shards", type=int, default=None, help="各ディレクトリの先頭N件だけ(試運転用)")
160
+ parser.add_argument("--policy-approver", default=None)
161
+ parser.add_argument("--policy-approved-on", default=None)
162
+ parser.add_argument("--policy-note", default=None)
163
+ parser.add_argument("--code-dir", type=Path, default=source_dir)
164
+ parser.add_argument("--ut1-cache-dir", type=Path, default=project_root / "data" / "blocklists" / "ut1")
165
+ parser.add_argument("--dry-run", action="store_true", help="ジョブ定義とスクリプトを表示するだけで起動しない")
166
+ parser.add_argument("--wait", action="store_true", help="全ジョブの終了を待つ")
167
+ args = parser.parse_args(argv)
168
+
169
+ token = os.environ.get("HF_TOKEN")
170
+ if not token and not args.dry_run:
171
+ raise SystemExit("HF_TOKEN が未設定です(uv run --env-file .env ...)")
172
+ dirs = parse_dirs(args.dirs)
173
+ ref = code_ref(args.code_dir)
174
+ namespace = args.namespace or args.output_repo.split("/")[0]
175
+
176
+ from huggingface_hub import HfApi, Volume
177
+
178
+ api = HfApi(token=token)
179
+ if not args.dry_run:
180
+ api.create_repo(args.output_repo, repo_type="dataset", private=True, exist_ok=True)
181
+ actions = upload_code_and_blocklists(api, args.output_repo, args.code_dir, ref, args.ut1_cache_dir, args.dry_run)
182
+ print(json.dumps({"event": "prepared", **actions, "output_repo": args.output_repo, "private": True}, ensure_ascii=False), flush=True)
183
+
184
+ launched: list[dict[str, Any]] = []
185
+ for dir_index in dirs:
186
+ script = build_job_script(args.output_repo, ref, dir_index, args)
187
+ spec = {
188
+ "name": f"abeja-cc-ja-clean-{dir_index}",
189
+ "image": args.image,
190
+ "flavor": args.flavor,
191
+ "timeout": args.timeout,
192
+ "namespace": namespace,
193
+ "volumes": [{"type": "dataset", "source": args.input_dataset, "mount_path": "/data", "read_only": True}],
194
+ "secrets": ["HF_TOKEN"],
195
+ "labels": {"pipeline": "abeja-cc-ja-cleansing", "dir": f"common_crawl_{dir_index}", "code_ref": ref},
196
+ }
197
+ if args.dry_run:
198
+ print(json.dumps({"event": "dry-run", "job": spec}, ensure_ascii=False))
199
+ print("--- script ---\n" + script)
200
+ continue
201
+ job = api.run_job(
202
+ image=args.image,
203
+ command=["bash", "-lc", script],
204
+ flavor=args.flavor,
205
+ timeout=args.timeout,
206
+ secrets={"HF_TOKEN": token},
207
+ env={"PIPELINE_DIR": f"common_crawl_{dir_index}"},
208
+ volumes=[Volume(type="dataset", source=args.input_dataset, mount_path="/data", read_only=True)],
209
+ namespace=namespace,
210
+ name=spec["name"],
211
+ labels=spec["labels"],
212
+ )
213
+ launched.append({"dir": dir_index, "job_id": job.id, "url": job.url})
214
+ print(json.dumps({"event": "launched", "dir": dir_index, "job_id": job.id, "url": job.url}), flush=True)
215
+ if launched:
216
+ record = project_root / "data" / f"hf_jobs_{datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')}.json"
217
+ record.parent.mkdir(parents=True, exist_ok=True)
218
+ record.write_text(json.dumps({"ref": ref, "output_repo": args.output_repo, "jobs": launched, "flavor": args.flavor, "timeout": args.timeout}, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
219
+ print(json.dumps({"event": "recorded", "file": str(record)}), flush=True)
220
+ if args.wait and launched:
221
+ finished = api.wait_for_job(job_id=[j["job_id"] for j in launched])
222
+ for info in (finished if isinstance(finished, list) else [finished]):
223
+ print(json.dumps({"event": "finished", "job_id": info.id, "stage": info.status.stage, "message": info.status.message}), flush=True)
224
+
225
+
226
+ if __name__ == "__main__":
227
+ main()
code/e5cb5ca/src/main_pii.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PII置換フィルタの実行入口と既定コンフィグ。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ from pathlib import Path
8
+
9
+ from filter_pii import run_filter
10
+
11
+
12
+ PROJECT_ROOT = Path(__file__).resolve().parents[1]
13
+ DEFAULT_CONFIG = {
14
+ "input": PROJECT_ROOT / "data" / "raw" / "common_crawl_0_filtered_0001.parquet",
15
+ "output_root": PROJECT_ROOT / "data" / "check_ver2" / "pii_0001_replaced_final",
16
+ "batch_size": 2048,
17
+ }
18
+
19
+
20
+ def main(argv: list[str] | None = None) -> None:
21
+ parser = argparse.ArgumentParser(description=__doc__)
22
+ parser.add_argument("--input", type=Path, default=DEFAULT_CONFIG["input"])
23
+ parser.add_argument("--output-root", type=Path, default=DEFAULT_CONFIG["output_root"])
24
+ parser.add_argument("--batch-size", type=int, default=DEFAULT_CONFIG["batch_size"])
25
+ parser.add_argument("--start-row", type=int, default=0)
26
+ parser.add_argument("--max-rows", type=int, default=None)
27
+ parser.add_argument("--policy-approver", default=None, help="処理方針(置換)の承認者名。summary.json の pii_policy に記録される。")
28
+ parser.add_argument("--policy-approved-on", default=None, help="承認日(YYYY-MM-DD)。")
29
+ parser.add_argument("--policy-note", default=None, help="方針の補足(任意)。")
30
+ parser.add_argument("--mask-honorific-names", action="store_true", help="「○○さん/氏/様」だけの姓名も置換する。")
31
+ parser.add_argument("--mask-bare-names", action="store_true", help="文脈の無い姓名も置換する。")
32
+ parser.add_argument("--no-affiliation-titles", dest="affiliation_titles", action="store_false", help="役職語(代表取締役、教授等)だけの文脈を所属とみなさない(組織名のみに狭める)。")
33
+ args = parser.parse_args(argv)
34
+ if not args.input.exists():
35
+ raise FileNotFoundError(args.input)
36
+ summary = run_filter(
37
+ input_path=args.input,
38
+ output_root=args.output_root,
39
+ batch_size=args.batch_size,
40
+ start_row=args.start_row,
41
+ max_rows=args.max_rows,
42
+ policy_approver=args.policy_approver,
43
+ policy_approved_on=args.policy_approved_on,
44
+ policy_note=args.policy_note,
45
+ mask_honorific_names=args.mask_honorific_names,
46
+ mask_bare_names=args.mask_bare_names,
47
+ affiliation_titles=args.affiliation_titles,
48
+ )
49
+ print(json.dumps({
50
+ "row_range": summary["row_range"],
51
+ "total_records_scanned": summary["total_records_scanned"],
52
+ "records_with_replacement": summary["records_with_replacement"],
53
+ "records_changed": summary["records_changed"],
54
+ "records_unchanged": summary["records_unchanged"],
55
+ "total_replacements": summary["total_replacements"],
56
+ "by_type": {k: v["replacement_count"] for k, v in summary["by_type"].items()},
57
+ "pii_policy_status": summary["pii_policy"]["status"],
58
+ }, ensure_ascii=False))
59
+
60
+
61
+ if __name__ == "__main__":
62
+ main()
63
+
code/e5cb5ca/src/main_toxic.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """有害コンテンツフィルタの実行入口と既定コンフィグ。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ from pathlib import Path
8
+
9
+ from cooccurrence import CooccurrenceDetector, load_rules
10
+ from domain_blocklist import DomainBlocklist
11
+ from filter_toxic import MODE_CONFIGS, run_toxic_filters
12
+
13
+
14
+ PROJECT_ROOT = Path(__file__).resolve().parents[1]
15
+ SOURCE_DIR = Path(__file__).resolve().parent
16
+ DEFAULT_CONFIG = {
17
+ "input": PROJECT_ROOT / "data" / "raw" / "common_crawl_0_filtered_0001.parquet",
18
+ "output_root": PROJECT_ROOT / "data" / "check_ver2" / "toxic_0001",
19
+ "reference_dir": SOURCE_DIR / "wordlists" / "reference",
20
+ "additional_dir": SOURCE_DIR / "wordlists",
21
+ "exclude_dir": SOURCE_DIR / "wordlists" / "exclude",
22
+ "blocklist_dir": SOURCE_DIR / "blocklists",
23
+ "blocklist_cache_dir": PROJECT_ROOT / "data" / "blocklists" / "ut1",
24
+ "cooccurrence_rules": SOURCE_DIR / "wordlists" / "cooccurrence" / "rules.json",
25
+ "batch_size": 2048,
26
+ "modes": tuple(MODE_CONFIGS),
27
+ }
28
+
29
+
30
+ def main(argv: list[str] | None = None) -> None:
31
+ parser = argparse.ArgumentParser(description=__doc__)
32
+ parser.add_argument("--input", type=Path, default=DEFAULT_CONFIG["input"])
33
+ parser.add_argument("--output-root", type=Path, default=DEFAULT_CONFIG["output_root"])
34
+ parser.add_argument("--reference-dir", type=Path, default=DEFAULT_CONFIG["reference_dir"])
35
+ parser.add_argument("--additional-dir", type=Path, default=DEFAULT_CONFIG["additional_dir"])
36
+ parser.add_argument("--exclude-dir", type=Path, default=DEFAULT_CONFIG["exclude_dir"],
37
+ help="カテゴリ別除外リスト(ja_<category>_exclude.txt)のディレクトリ。")
38
+ parser.add_argument("--blocklist-dir", type=Path, default=DEFAULT_CONFIG["blocklist_dir"],
39
+ help="ドメインブロックリストの設定・自前リストのディレクトリ。")
40
+ parser.add_argument("--blocklist-cache-dir", type=Path, default=DEFAULT_CONFIG["blocklist_cache_dir"],
41
+ help="UT1リストの取得先(domain_blocklist.py fetch --dest で作成)。")
42
+ parser.add_argument("--no-blocklist", action="store_true", help="ドメインブロックリスト判定を無効にする。")
43
+ parser.add_argument("--cooccurrence-rules", type=Path, default=DEFAULT_CONFIG["cooccurrence_rules"],
44
+ help="近接共起規則の定義JSON。")
45
+ parser.add_argument("--no-cooccurrence", action="store_true", help="近接共起規則を無効にする。")
46
+ parser.add_argument("--batch-size", type=int, default=DEFAULT_CONFIG["batch_size"])
47
+ parser.add_argument("--mode", choices=("all", *MODE_CONFIGS), action="append", default=None,
48
+ help="実行モード。省略時は同一カテゴリ3語以上条件を実行。")
49
+ parser.add_argument("--start-row", type=int, default=0)
50
+ parser.add_argument("--max-rows", type=int, default=None)
51
+ args = parser.parse_args(argv)
52
+ for path in (args.input, args.reference_dir, args.additional_dir, args.exclude_dir):
53
+ if not path.exists():
54
+ raise FileNotFoundError(path)
55
+ modes = list(MODE_CONFIGS) if not args.mode or "all" in args.mode else args.mode
56
+ blocklist = None if args.no_blocklist else DomainBlocklist.load(args.blocklist_dir, args.blocklist_cache_dir)
57
+ cooccurrence = None if args.no_cooccurrence else CooccurrenceDetector(load_rules(args.cooccurrence_rules))
58
+ summary = run_toxic_filters(
59
+ input_path=args.input,
60
+ output_root=args.output_root,
61
+ reference_dir=args.reference_dir,
62
+ additional_dir=args.additional_dir,
63
+ batch_size=args.batch_size,
64
+ modes=modes,
65
+ start_row=args.start_row,
66
+ max_rows=args.max_rows,
67
+ exclude_dir=args.exclude_dir,
68
+ blocklist=blocklist,
69
+ cooccurrence=cooccurrence,
70
+ )
71
+ print(json.dumps({
72
+ "row_range": summary["row_range"],
73
+ "modes": {
74
+ mode: {
75
+ "total_records_scanned": values["total_records_scanned"],
76
+ "records_deleted": values["records_deleted"],
77
+ "records_retained": values["records_retained"],
78
+ "records_deleted_by_reason": values["records_deleted_by_reason"],
79
+ }
80
+ for mode, values in summary["modes"].items()
81
+ },
82
+ }, ensure_ascii=False))
83
+
84
+
85
+ if __name__ == "__main__":
86
+ main()
code/e5cb5ca/src/pii_detector.py ADDED
@@ -0,0 +1,597 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """日本語Web文書向けのPII検出・置換器。
2
+
3
+ ``PII_detect.md`` の検出方針を踏まえ、正規表現・チェックデジットに加えて
4
+ SudachiPy(形態素解析、人名辞書付き)で自然文中の氏名を検出する。学習済み
5
+ NER(GLiNER-ja)は全件処理には重いため ``pii_residual_check.py`` の残存確認に
6
+ 使う。公開用データでは、検出した値を削除するのではなく、種別ごとの
7
+ プレースホルダーへ置換する。対象は次の7種類に限定する。
8
+
9
+ * 電話番号
10
+ * メールアドレス
11
+ * 番地レベルの住所
12
+ * 個人名と所属の組合せ
13
+ * マイナンバー
14
+ * クレジットカード番号
15
+ * 銀行口座番号
16
+
17
+ 郵便番号だけ、IPアドレス、秘密情報、生年月日などは対象外とする。個人名
18
+ だけは「氏名:」等のラベル文脈に限って置換する。番号系(マイナンバー、
19
+ カード、口座)はURLでは検出せず、本文でもラベル文脈か区切り書式を必須にする
20
+ (無作為な数字列の1割はチェックデジットを通るため)。将来 fuseji、GLiNER-ja、GiNZA 等を追加する場合は
21
+ ``PIIDetector`` の結果へ検出結果を追加できる。
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import re
27
+ import unicodedata
28
+ from dataclasses import dataclass
29
+ from typing import Any, Iterable
30
+
31
+
32
+ PII_LABELS_JA = {
33
+ "email": "メールアドレス",
34
+ "phone": "電話番号",
35
+ "address": "番地レベルの住所",
36
+ "person_affiliation": "個人名+所属",
37
+ "person_name": "個人名",
38
+ "my_number": "マイナンバー",
39
+ "credit_card": "クレジットカード番号",
40
+ "bank_account": "銀行口座番号",
41
+ }
42
+
43
+ PLACEHOLDERS = {
44
+ "email": "<EMAIL>",
45
+ "phone": "<PHONE>",
46
+ "address": "<ADDRESS>",
47
+ "person_affiliation": "<PERSON_AFFILIATION>",
48
+ "person_name": "<PERSON_NAME>",
49
+ "my_number": "<MY_NUMBER>",
50
+ "credit_card": "<CREDIT_CARD>",
51
+ "bank_account": "<BANK_ACCOUNT>",
52
+ }
53
+
54
+ TARGET_PII_TYPES = tuple(PII_LABELS_JA)
55
+
56
+
57
+ @dataclass(frozen=True)
58
+ class PIIMatch:
59
+ """検出されたPIIの位置と監査用メタデータ。位置はNFKC後の文字列基準。"""
60
+
61
+ pii_type: str
62
+ field: str
63
+ start: int
64
+ end: int
65
+ value: str
66
+ method: str
67
+ confidence: str = "high"
68
+
69
+ @property
70
+ def label_ja(self) -> str:
71
+ return PII_LABELS_JA.get(self.pii_type, self.pii_type)
72
+
73
+ @property
74
+ def masked_value(self) -> str:
75
+ return mask_value(self.pii_type, self.value)
76
+
77
+ @property
78
+ def placeholder(self) -> str:
79
+ return PLACEHOLDERS.get(self.pii_type, "<PII>")
80
+
81
+ def to_dict(self) -> dict[str, Any]:
82
+ return {
83
+ "pii_type": self.pii_type,
84
+ "pii_type_ja": self.label_ja,
85
+ "field": self.field,
86
+ "start": self.start,
87
+ "end": self.end,
88
+ "matched_value_masked": self.masked_value,
89
+ "method": self.method,
90
+ "confidence": self.confidence,
91
+ "placeholder": self.placeholder,
92
+ }
93
+
94
+
95
+ def normalize_text(value: Any) -> str:
96
+ """全角・半角差を吸収して照合する。"""
97
+
98
+ if value is None:
99
+ return ""
100
+ return unicodedata.normalize("NFKC", str(value))
101
+
102
+
103
+ def mask_value(pii_type: str, value: str) -> str:
104
+ """監査JSONにPIIそのものを再掲しないためのマスキング。"""
105
+
106
+ if not value:
107
+ return ""
108
+ if pii_type == "email" and "@" in value:
109
+ local, domain = value.split("@", 1)
110
+ masked_local = local[0] + "*" * max(1, len(local) - 2) + local[-1:]
111
+ return f"{masked_local}@{domain}"
112
+ if pii_type in {"phone", "my_number", "credit_card", "bank_account"}:
113
+ chars = list(value)
114
+ positions = [i for i, char in enumerate(chars) if char.isalnum()]
115
+ keep = 4
116
+ for index in positions[:-keep]:
117
+ chars[index] = "*"
118
+ return "".join(chars)
119
+ if pii_type == "address":
120
+ return value[:3] + "***"
121
+ if pii_type == "person_affiliation":
122
+ return "***"
123
+ return "***"
124
+
125
+
126
+ def is_valid_luhn(value: str) -> bool:
127
+ digits = [int(char) for char in value if char.isdigit()]
128
+ if len(digits) < 13 or len(digits) > 19:
129
+ return False
130
+ checksum = 0
131
+ parity = len(digits) % 2
132
+ for index, digit in enumerate(digits):
133
+ if index % 2 == parity:
134
+ digit *= 2
135
+ if digit > 9:
136
+ digit -= 9
137
+ checksum += digit
138
+ return checksum % 10 == 0
139
+
140
+
141
+ def is_valid_mynumber(value: str) -> bool:
142
+ """12桁の個人番号のチェックデジットを検証する。"""
143
+
144
+ digits = [int(char) for char in value if char.isdigit()]
145
+ if len(digits) != 12:
146
+ return False
147
+ # 左から11桁に対して、右から 2,3,4,5,6,7 を繰り返す。
148
+ weights = [2, 3, 4, 5, 6, 7, 2, 3, 4, 5, 6]
149
+ total = sum(digit * weight for digit, weight in zip(reversed(digits[:11]), weights))
150
+ check_digit = (11 - (total % 11)) % 10
151
+ return check_digit == digits[-1]
152
+
153
+
154
+ EMAIL_RE = re.compile(
155
+ r"(?<![A-Za-z0-9._%+\-])([A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+)(?![A-Za-z0-9._%+\-])"
156
+ )
157
+ PHONE_SEPARATED_RE = re.compile(
158
+ # 改行を区切りに含めない。住所末尾の番地と次行の電話番号を
159
+ # ひとつの不正な候補として連結しないため、空白は半角スペース・タブのみ。
160
+ # 先行する郵便番号・日付などが不正候補になっても、後続の電話番号の
161
+ # 開始位置を検査できるよう、候補全体を先読みして重複開始を許可する。
162
+ r"(?<!\d)(?=(?P<value>(?:\+81[ \t-]?)?0?\d{1,4}(?:[ \t]?-[ \t]?|[ \t])\d{1,4}(?:[ \t]?-[ \t]?|[ \t])\d{3,4})(?!\d))"
163
+ )
164
+ PHONE_MOBILE_RE = re.compile(r"(?<!\d)0[789]0\d{8}(?!\d)")
165
+ PHONE_PLAIN_RE = re.compile(
166
+ r"(?<!\d)(?:0120\d{6}|0570\d{6}|050\d{8}|0[1-9]\d{8})(?!\d)"
167
+ )
168
+ PHONE_CONTEXT_RE = re.compile(
169
+ # ラベル候補も先読みして、TELの後に別のFAXが続く場合などの
170
+ # 後続ラベルを取りこぼさない。
171
+ r"(?=(?:電話|携帯|連絡先|tel|telephone|phone|fax|ファクシミリ|ファックス)\s*[::]?[^0-9+]{0,10}(?P<value>\+?\d[\d\s().-]{8,18}\d))",
172
+ re.IGNORECASE,
173
+ )
174
+ # 12桁(4-4-4区切りも可)。チェックデジットに加えて、ラベル文脈を必須にする。
175
+ # 無作為な12桁の1割はチェックデジットを通るため、URL中のIDや注文番号を誤検出しないため。
176
+ MY_NUMBER_RE = re.compile(r"(?<![\d-])(?:\d{4}[ -]?\d{4}[ -]?\d{4})(?![\d-])")
177
+ MY_NUMBER_CONTEXT_RE = re.compile(r"(?:個人番号|マイナンバー|my\s*number)", re.IGNORECASE)
178
+ # 13〜19桁。区切り書式(4-4-4-4、4-6-5 等)かラベル文脈を必須にする(Luhn だけでは1割が通る)。
179
+ CARD_RE = re.compile(r"(?<![\d-])(?:\d{4}[ -]\d{4}[ -]\d{4}[ -]\d{1,7}|\d{4}[ -]\d{6}[ -]\d{5}|\d{13,19})(?![\d-])")
180
+ CARD_CONTEXT_RE = re.compile(
181
+ r"(?:カード番号|クレジットカード|クレカ|card\s*(?:no\.?|number)|credit\s*card|visa|master\s*card|jcb|amex|american\s*express|diners)",
182
+ re.IGNORECASE,
183
+ )
184
+ # 直前にこれらのラベルがある数字列は注文・伝票等の番号とみなして除外する。
185
+ NUMBER_NEGATIVE_CONTEXT_RE = re.compile(
186
+ r"(?:注文番号|受注番号|伝票番号|追跡番号|お問い?合わせ番号|受付番号|管理番号|会員番号|予約番号|商品番号|型番|isbn|jan|tracking|order\s*(?:no\.?|number))",
187
+ re.IGNORECASE,
188
+ )
189
+
190
+ # 都道府県・市区町村に続く番地(1-2-3、1丁目2番3号等)を必須にする。番地の後ろの
191
+ # 建物名・部屋番号も住所の一部として取り込む(「<ADDRESS>-802」のような取り残しを防ぐ)。
192
+ # 番地: 算用数字と漢数字の両方、「1-2-3」「1丁目2番3号」「一丁目二番三号」「1丁目2-3」「1ー2ー3」を許容
193
+ _NUM = r"[0-9一二三四五六七八九十〇零]+"
194
+ # 区切り記号(-、-、‐、ー)の前後には OCR・Web抽出由来の空白を1つまで許す。
195
+ _SEP = r"\s?[--‐ー]\s?"
196
+ _ADDRESS_BLOCK = (
197
+ rf"(?:{_NUM}\s?丁目\s?{_NUM}(?:\s?番(?:地)?\s?(?:{_NUM}\s?号?)?|{_SEP}{_NUM}(?:{_SEP}{_NUM})?)"
198
+ rf"|{_NUM}(?:{_SEP}{_NUM}){{1,3}}(?:番地?)?"
199
+ rf"|{_NUM}\s?番地?(?:\s?{_NUM}\s?号)?)"
200
+ )
201
+ _ADDRESS_TAIL = (
202
+ r"(?:\s*[^\s,、。\n()()]{0,20}?(?:ビル|マンション|ハイツ|コーポ|レジデンス|アパート|タワー|ハウス|荘|寮|号館)[^\s,、。\n()()]{0,10})?"
203
+ r"(?:\s*\d{1,4}\s*(?:号室|号|[Ff]|階))?"
204
+ )
205
+ # 都道府県から始まる住所。改行・空白の混入(Web抽出やOCR)を許すため、区切りは句読点のみとする。
206
+ ADDRESS_RE = re.compile(
207
+ r"(?P<value>(?:北海道|東京都|大阪府|京都府|[一-龥々]{2,3}県)[^,、。]{1,60}?(?:市|区|町|村)[^,、。]{0,35}?" + _ADDRESS_BLOCK + _ADDRESS_TAIL + r")"
208
+ )
209
+ # 都道府県が省かれた「福岡市博多区博多駅前1-2-3」「宇都宮市江野町1-15」。市・区の後に町名相当を1文字以上要求する。
210
+ ADDRESS_CITY_RE = re.compile(
211
+ r"(?P<value>(?<![都京大])[一-龥々ぁ-ゖ]{1,6}(?:市|区|郡)[一-龥々ぁ-ゖァ-ヶー0-9\s]{1,30}?(?:町|村|区|丁目|[一-龥々]{1,6})" + _ADDRESS_BLOCK + _ADDRESS_TAIL + r")"
212
+ )
213
+ # ラベル付きの住所は、都道府県が省かれた「宇都宮市江野町1-15」の形も許可する(残存確認で発見した取りこぼし)。
214
+ ADDRESS_CONTEXT_RE = re.compile(
215
+ r"(?:住所|所在地|送付先|配送先)\s*[::]?\s*(?P<value>(?:北海道|東京都|大阪府|京都府|[一-龥々]{2,3}県|[一-龥々ぁ-ゖァ-ヶー]{1,6}(?:市|区|郡))[^。,、]{1,80}?" + _ADDRESS_BLOCK + _ADDRESS_TAIL + r")"
216
+ )
217
+
218
+ # 氏名: 漢字2〜6字、または漢字1〜3字+かな2〜6字(佐藤ゆかり)。「皆さん」のような1字+さんは拾わない。
219
+ _NAME = r"(?:[一-龥々]{2,6}|[一-龥々]{1,3}\s?[ぁ-ゖァ-ヶー]{2,6})"
220
+ # 所属: 法人格で始まる名称、または組��を示す語尾で終わる名称(20字以内)。任意で部署。
221
+ _ORG_PREFIX = r"(?:株式会社|有限会社|合同会社|合資会社|一般社団法人|一般財団法人|公益社団法人|公益財団法人|[Nn][Pp][Oo]法人|学校法人|医療法人|社会福祉法人|独立行政法人|国立研究開発法人)"
222
+ _ORG_SUFFIX = r"(?:株式会社|有限会社|合同会社|会社|大学院|大学|高等学校|高校|中学校|小学校|専門学校|病院|クリニック|医院|省|庁|県庁|市役所|区役所|町役場|村役場|銀行|信用金庫|研究所|研究センター|協会|連盟|組合|法律事務所|事務所|事務局|財団|法人|商工会議所|観光局|放送局|新聞社|出版社)"
223
+ _ORG = rf"(?:{_ORG_PREFIX}[^\s。、,,()()]{{1,20}}|[^\s。、,,()()のがはをにでと]{{1,20}}?{_ORG_SUFFIX})"
224
+ _ORG_RE = re.compile(_ORG)
225
+ _DEPT = r"(?:\s*[^\s。、,,()()]{0,15}?(?:部|課|室|科|係|チーム|支店|支社|営業所|研究室))?"
226
+ # 所属の後ろに続く役職(「株式会社ABC 代表」「○○会 会員」)も置換範囲に含める。
227
+ _TITLE_OPT = r"(?:\s*[^\s。、,,()()の]{0,8}?(?:長|社長|部長|課長|主任|教授|准教授|講師|代表|取締役|[Cc][Ee][Oo]|[Cc][Tt][Oo]|マネージャー|リーダー|担当|研究員|弁護士|職員|会員|理事|社員|員))?"
228
+ _TITLE = r"(?:[^\s。、,,()()の]{0,8}?(?:長|社長|部長|課長|主任|教授|准教授|講師|代表|取締役|[Cc][Ee][Oo]|[Cc][Tt][Oo]|マネージャー|リーダー|担当|研究員|弁護士))"
229
+ # 「氏名:山田太郎(株式会社ABC)」「担当者:山田太郎、株式会社ABC 営業部」
230
+ NAME_AFFILIATION_LABEL_RE = re.compile(
231
+ r"(?:氏名|お名前|担当者|代表者|名義人?)\s*[::]\s*"
232
+ rf"(?P<value>(?P<name>{_NAME})\s*(?:[((、,]|所属\s*[::])\s*(?P<affiliation>{_ORG}{_DEPT}{_TITLE_OPT})[))]?)"
233
+ )
234
+ # 「山田太郎さん、株式会社ABC」「山田太郎氏(株式会社ABC 営業部)」
235
+ NAME_AFFILIATION_SUFFIX_RE = re.compile(
236
+ rf"(?P<value>(?P<name>{_NAME})(?:さん|氏|様|先生)[、,\s((]+(?P<affiliation>{_ORG}{_DEPT}{_TITLE_OPT})[))]?)"
237
+ )
238
+ # 「株式会社ABC 営業部 部長 山田太郎さん」「○○大学教授・山田太郎氏」(所属→役職→氏名の順)。
239
+ # 役職か「・」区切りのどちらかと、敬称を必須にする。「会社の同僚さん」のような役割語を氏名にしないため。
240
+ AFFILIATION_NAME_RE = re.compile(
241
+ rf"(?P<value>(?P<affiliation>{_ORG}{_DEPT})\s*(?:(?:の)?\s*{_TITLE}\s*(?:・|の|\s)?|・)\s*(?P<name>{_NAME})(?:さん|氏|様|先生))"
242
+ )
243
+ # 個人名だけ(ラベル文脈)。かな名も許可し、フォームの定型語は除外する。
244
+ _NAME_TOKEN = r"[一-龥々ぁ-ゖァ-ヶー]{1,8}"
245
+ NAME_CONTEXT_RE = re.compile(
246
+ r"(?:氏名|お名前|名前|担当者|代表者|名義人?)\s*[::]\s*"
247
+ rf"(?P<value>{_NAME_TOKEN}(?:\s*{_NAME_TOKEN})?)"
248
+ )
249
+ NAME_STOPWORDS = {"必須", "任意", "未定", "なし", "不明", "非公開", "匿名", "ニックネーム", "ハンドルネーム", "例", "未入力", "空欄", "入力"}
250
+ # 欧文氏名は署名(by / Author / 執筆者)か敬称(Mr. / Dr.)の文脈に限る。単独の「John Smith」は地名・商品名と区別できないため対象外。
251
+ LATIN_NAME_RE = re.compile(
252
+ r"(?:(?i:\bby|\bauthor|\bwritten by|\bphoto by|\btext by|\bposted by)|執筆者|著者|文責|撮影|取材|記者|翻訳|監修)\s*[::]?\s*"
253
+ r"(?P<value>(?:(?:Mr|Ms|Mrs|Dr|Prof)\.?\s+)?[A-Z][a-z]+(?:\s[A-Z]\.?)?\s[A-Z][a-z]+(?:\s[A-Z][a-z]+)?)"
254
+ r"|(?P<value2>(?:Mr|Ms|Mrs|Dr|Prof)\.\s+[A-Z][a-z]+(?:\s[A-Z][a-z]+)?)"
255
+ )
256
+ BANK_CONTEXT_RE = re.compile(
257
+ r"(?:口座番号|口座|振込先|銀行口座)\D{0,20}(?P<value>\d{7})(?!\d)"
258
+ )
259
+ # URL では数字列がIDであることが多く、番号系の検出は行わない(メール・電話のみ)。
260
+ URL_EXCLUDED_TYPES = frozenset({"my_number", "credit_card", "bank_account"})
261
+
262
+
263
+ def _has_context(text: str, position: int, pattern: re.Pattern[str], window: int) -> bool:
264
+ """position の直前 window 文字以内に pattern があるか。"""
265
+
266
+ return pattern.search(text, max(0, position - window), position) is not None
267
+
268
+
269
+ # --- 形態素解析による人名検出 -------------------------------------------------
270
+ # SudachiPy(Apache-2.0)の辞書は姓・名を「名詞,固有名詞,人名,姓/名」として持つ。
271
+ # 姓+名の連続、または敬称・役割ラベル付きの単独人名を候補にし、所属・役職の文脈が
272
+ # 近くにあれば「個人名+所属」、敬称・役割ラベルがあれば「個人名」として置換する。
273
+ # 文脈のない裸の姓名(「尾田栄一郎はどんな人」)は既定では置換せず、件数だけ数える。
274
+ HONORIFIC_AFTER_RE = re.compile(r"(?:さん|氏|様|先生|くん|君|ちゃん|さま)")
275
+ # 役割ラベル。1文字の語(文・絵・訳・作・画)は「名作」「原作」を拾わないよう、区切り文字か行頭の直後に限る。
276
+ # 出演・司会は俳優・司会者(公人)を指すため含めない。
277
+ ROLE_LABEL_BEFORE_RE = re.compile(
278
+ r"(?:(?:執筆者|執筆|著者|文責|記者|編集者|担当者?|講師|監修|取材|撮影|翻訳|写真|(?i:by))|(?:^|[\s、,::・/||((【\[])(?:文|絵|訳|作|画))\s*[::=]?\s*$",
279
+ )
280
+ TITLE_CONTEXT_RE = re.compile(
281
+ r"(?:代表取締役|取締役|社長|副社長|会長|副会長|理事長|理事|専務|常務|執行役員|部長|次長|課長|係長|主任|所長|院長|校長|園長|館長|局長|"
282
+ r"教授|准教授|助教|講師|研究員|主席|主幹|(?i:ceo|cto|coo|cfo)|マネージャー|ディレクター|プロデューサー|エンジニア|デザイナー|コンサルタント|"
283
+ r"アナリスト|弁護士|税理士|会計士|司法書士|行政書士|社労士|医師|看護師|薬剤師|"
284
+ r"代表|担当|職員|社員|スタッフ|広報|主宰|オーナー|店長|支配人|学長|総長|会員|委員長|委員)"
285
+ # 監督・選手・議員・市長・知事・大臣など公人を示す役職は含めない(公人名は学習データとして保持する)。
286
+ )
287
+ NAME_CONTEXT_WINDOW = 25
288
+ _SENTENCE_BREAK_RE = re.compile(r"[。!?!?\n]")
289
+
290
+
291
+ def _same_sentence_window(text: str, start: int, end: int, window: int) -> tuple[str, str]:
292
+ """氏名の前後 window 文字のうち、同じ文(句点・改行で区切られない範囲)だけを返す。"""
293
+
294
+ before = text[max(0, start - window):start]
295
+ after = text[end:end + window]
296
+ breaks = list(_SENTENCE_BREAK_RE.finditer(before))
297
+ if breaks:
298
+ before = before[breaks[-1].end():]
299
+ cut = _SENTENCE_BREAK_RE.search(after)
300
+ if cut:
301
+ after = after[:cut.start()]
302
+ return before, after
303
+
304
+
305
+ class SudachiNameFinder:
306
+ """本文から人名の範囲(姓+名の連続、または単独の姓・名)を返す。"""
307
+
308
+ CHUNK_CHARS = 8000 # Sudachi の入力上限(49,149バイト)に収める
309
+
310
+ def __init__(self) -> None:
311
+ from sudachipy import Dictionary, SplitMode
312
+
313
+ self._tokenizer = Dictionary(dict="core").create()
314
+ self._mode = SplitMode.A
315
+
316
+ def _chunks(self, text: str):
317
+ start = 0
318
+ while start < len(text):
319
+ end = min(len(text), start + self.CHUNK_CHARS)
320
+ if end < len(text):
321
+ newline = text.rfind("\n", start + self.CHUNK_CHARS // 2, end)
322
+ if newline > 0:
323
+ end = newline + 1
324
+ yield start, text[start:end]
325
+ start = end
326
+
327
+ def find(self, text: str) -> list[tuple[int, int, str]]:
328
+ """(start, end, kind) を返す。kind は ``pair``(姓+名)か ``single``。"""
329
+
330
+ spans: list[tuple[int, int, str]] = []
331
+ for offset, piece in self._chunks(text):
332
+ run: list[tuple[int, int, str]] = [] # (start, end, 姓/名/一般)
333
+
334
+ def flush() -> None:
335
+ if not run:
336
+ return
337
+ kinds = [kind for _, _, kind in run]
338
+ start, end = run[0][0], run[-1][1]
339
+ if "姓" in kinds and "名" in kinds and kinds.index("姓") < len(kinds) - 1:
340
+ spans.append((start, end, "pair"))
341
+ elif len(run) >= 2 and end - start >= 3:
342
+ spans.append((start, end, "pair"))
343
+ elif end - start >= 2:
344
+ spans.append((start, end, "single"))
345
+ run.clear()
346
+
347
+ pending_connector = False
348
+ for morpheme in self._tokenizer.tokenize(piece, self._mode):
349
+ pos = morpheme.part_of_speech()
350
+ surface = morpheme.surface()
351
+ if pos[2] == "人名":
352
+ run.append((offset + morpheme.begin(), offset + morpheme.end(), pos[3]))
353
+ pending_connector = False
354
+ elif run and not pending_connector and (pos[0] == "空白" or surface in ("・", "・", "=", "=")):
355
+ # 「山田 太郎」「ジョン・スミス」の空白・中黒は1つだけ連結として扱う
356
+ pending_connector = True
357
+ else:
358
+ flush()
359
+ pending_connector = False
360
+ flush()
361
+ return spans
362
+
363
+
364
+ def _digits(value: str) -> str:
365
+ return "".join(char for char in value if char.isdigit())
366
+
367
+
368
+ def _valid_phone(value: str) -> bool:
369
+ digits = _digits(value)
370
+ if value.startswith("+81"):
371
+ digits = "0" + digits[2:]
372
+ if len(digits) not in {10, 11} or not digits.startswith("0"):
373
+ return False
374
+ if digits.startswith(("070", "080", "090")):
375
+ return len(digits) == 11
376
+ return digits[1] in "123456789" and len(digits) in {10, 11}
377
+
378
+
379
+ def _overlap(first: PIIMatch, second: PIIMatch) -> bool:
380
+ return first.start < second.end and second.start < first.end
381
+
382
+
383
+ def _select_non_overlapping(matches: Iterable[PIIMatch]) -> list[PIIMatch]:
384
+ """重なった候補は、長く信頼度の���い候補を優先して1回だけ置換する。"""
385
+
386
+ confidence_rank = {"high": 2, "medium": 1, "low": 0}
387
+ ordered = sorted(
388
+ matches,
389
+ key=lambda item: (
390
+ item.start,
391
+ -(item.end - item.start),
392
+ -confidence_rank.get(item.confidence, 0),
393
+ ),
394
+ )
395
+ selected: list[PIIMatch] = []
396
+ for candidate in ordered:
397
+ if any(_overlap(candidate, existing) for existing in selected):
398
+ continue
399
+ selected.append(candidate)
400
+ return sorted(selected, key=lambda item: (item.start, item.end, item.pii_type))
401
+
402
+
403
+ class PIIDetector:
404
+ """URLと本文から指定7種類だけを検出し、プレースホルダーへ置換する。"""
405
+
406
+ def __init__(
407
+ self,
408
+ include_url: bool = True,
409
+ use_sudachi: bool = True,
410
+ mask_honorific_names: bool = False,
411
+ mask_bare_names: bool = False,
412
+ name_context_window: int = NAME_CONTEXT_WINDOW,
413
+ affiliation_titles: bool = True,
414
+ ) -> None:
415
+ self.include_url = include_url
416
+ self.use_sudachi = use_sudachi
417
+ self.name_context_window = name_context_window
418
+ # 既定では組織名(法人格・組織語尾)と役職語(代表取締役、教授等)の両方を所属文脈とする。
419
+ # 組織名だけに狭める場合は affiliation_titles=False(CLI: --no-affiliation-titles)。
420
+ self.affiliation_titles = affiliation_titles
421
+ self.mask_honorific_names = mask_honorific_names
422
+ self.mask_bare_names = mask_bare_names
423
+ self._names: SudachiNameFinder | None = None
424
+ # 置換しなかった姓名の件数(方針判断用)。敬称のみ/文脈なし。
425
+ self.honorific_name_candidates = 0
426
+ self.honorific_name_records = 0
427
+ self.bare_name_candidates = 0
428
+ self.bare_name_records = 0
429
+
430
+ def _name_finder(self) -> SudachiNameFinder:
431
+ if self._names is None:
432
+ self._names = SudachiNameFinder()
433
+ return self._names
434
+
435
+ def _detect_names(self, normalized: str, field: str) -> list[PIIMatch]:
436
+ matches: list[PIIMatch] = []
437
+ bare = 0
438
+ honorific_only = 0
439
+ for start, end, kind in self._name_finder().find(normalized):
440
+ value = normalized[start:end]
441
+ before, after = _same_sentence_window(normalized, start, end, self.name_context_window)
442
+ honorific = HONORIFIC_AFTER_RE.match(normalized, end) is not None
443
+ role = ROLE_LABEL_BEFORE_RE.search(normalized[max(0, start - 16):start]) is not None
444
+ affiliated = bool(_ORG_RE.search(before) or _ORG_RE.search(after))
445
+ if not affiliated and self.affiliation_titles:
446
+ affiliated = bool(TITLE_CONTEXT_RE.search(before) or TITLE_CONTEXT_RE.search(after))
447
+ if affiliated and (kind == "pair" or honorific or role):
448
+ matches.append(PIIMatch("person_affiliation", field, start, end, value, "sudachi_name_affiliation", "medium"))
449
+ elif role:
450
+ matches.append(PIIMatch("person_name", field, start, end, value, "sudachi_name_role", "medium"))
451
+ elif honorific:
452
+ # 「○○さん」だけでは私人か公人(俳優、作家、選手)か区別できないため、既定では置換しない。
453
+ if self.mask_honorific_names:
454
+ matches.append(PIIMatch("person_name", field, start, end, value, "sudachi_name_honorific", "low"))
455
+ else:
456
+ honorific_only += 1
457
+ elif kind == "pair":
458
+ if self.mask_bare_names:
459
+ matches.append(PIIMatch("person_name", field, start, end, value, "sudachi_name_bare", "low"))
460
+ else:
461
+ bare += 1
462
+ if honorific_only:
463
+ self.honorific_name_candidates += honorific_only
464
+ self.honorific_name_records += 1
465
+ if bare:
466
+ self.bare_name_candidates += bare
467
+ self.bare_name_records += 1
468
+ return matches
469
+
470
+ @staticmethod
471
+ def _looks_like_phone(value: str) -> bool:
472
+ """住所候補の末尾が電話番号(区切り付き10桁以上)なら住所とみなさない。"""
473
+
474
+ tail = re.search(r"(\d+(?:\s?[--‐ー]\s?\d+)+)\s*$", value)
475
+ if not tail:
476
+ return False
477
+ digits = _digits(tail.group(1))
478
+ return len(digits) >= 9 and "丁目" not in value[-20:] and "番" not in value[-20:]
479
+
480
+ def detect(self, text: Any, field: str = "content") -> list[PIIMatch]:
481
+ normalized = normalize_text(text)
482
+ if not normalized:
483
+ return []
484
+ matches: list[PIIMatch] = []
485
+
486
+ def add(
487
+ pattern: re.Pattern[str],
488
+ pii_type: str,
489
+ method: str,
490
+ confidence: str = "high",
491
+ group: str | None = None,
492
+ ) -> None:
493
+ for found in pattern.finditer(normalized):
494
+ value = found.group(group) if group else found.group(0)
495
+ start = found.start(group) if group else found.start()
496
+ end = found.end(group) if group else found.end()
497
+ matches.append(PIIMatch(pii_type, field, start, end, value, method, confidence))
498
+
499
+ add(EMAIL_RE, "email", "regex_email")
500
+ for found in PHONE_SEPARATED_RE.finditer(normalized):
501
+ value = found.group("value")
502
+ if _valid_phone(value):
503
+ matches.append(PIIMatch("phone", field, found.start("value"), found.end("value"), value, "regex_phone"))
504
+ for found in PHONE_MOBILE_RE.finditer(normalized):
505
+ if _valid_phone(found.group(0)):
506
+ matches.append(PIIMatch("phone", field, found.start(), found.end(), found.group(0), "regex_phone"))
507
+ for found in PHONE_PLAIN_RE.finditer(normalized):
508
+ if _valid_phone(found.group(0)):
509
+ matches.append(PIIMatch("phone", field, found.start(), found.end(), found.group(0), "regex_phone"))
510
+ for found in PHONE_CONTEXT_RE.finditer(normalized):
511
+ value = found.group("value")
512
+ if _valid_phone(value):
513
+ matches.append(PIIMatch("phone", field, found.start("value"), found.end("value"), value, "context_phone", "medium"))
514
+
515
+ if field != "url":
516
+ for found in MY_NUMBER_RE.finditer(normalized):
517
+ value = found.group(0)
518
+ if not is_valid_mynumber(value):
519
+ continue
520
+ if _has_context(normalized, found.start(), NUMBER_NEGATIVE_CONTEXT_RE, 20):
521
+ continue
522
+ # 区切り書式だけでは数表・型番を誤検出するため、マイナンバーはラベル文脈を必須にする。
523
+ if _has_context(normalized, found.start(), MY_NUMBER_CONTEXT_RE, 40):
524
+ matches.append(PIIMatch("my_number", field, found.start(), found.end(), value, "checksum_mynumber"))
525
+ for found in CARD_RE.finditer(normalized):
526
+ value = found.group(0)
527
+ if not is_valid_luhn(value) or len(_digits(value)) == 12:
528
+ continue
529
+ if _has_context(normalized, found.start(), NUMBER_NEGATIVE_CONTEXT_RE, 20):
530
+ continue
531
+ labeled = _has_context(normalized, found.start(), CARD_CONTEXT_RE, 40)
532
+ grouped = not value.isdigit()
533
+ if labeled or grouped:
534
+ matches.append(PIIMatch("credit_card", field, found.start(), found.end(), value, "checksum_luhn", "high" if labeled else "medium"))
535
+
536
+ patterns = [
537
+ (ADDRESS_RE, "address", "regex_address"),
538
+ (ADDRESS_CITY_RE, "address", "regex_address_city"),
539
+ (ADDRESS_CONTEXT_RE, "address", "context_address"),
540
+ (NAME_AFFILIATION_LABEL_RE, "person_affiliation", "context_name_affiliation"),
541
+ (NAME_AFFILIATION_SUFFIX_RE, "person_affiliation", "context_name_affiliation"),
542
+ (AFFILIATION_NAME_RE, "person_affiliation", "context_affiliation_name"),
543
+ ]
544
+ if field != "url":
545
+ patterns.append((BANK_CONTEXT_RE, "bank_account", "context_bank_account"))
546
+ for pattern, pii_type, method in patterns:
547
+ add(pattern, pii_type, method, "medium", "value")
548
+ matches = [m for m in matches if not (m.pii_type == "address" and self._looks_like_phone(m.value))]
549
+ if self.use_sudachi and field != "url":
550
+ matches.extend(self._detect_names(normalized, field))
551
+ for found in LATIN_NAME_RE.finditer(normalized):
552
+ group = "value" if found.group("value") else "value2"
553
+ matches.append(PIIMatch("person_name", field, found.start(group), found.end(group), found.group(group), "context_latin_name", "medium"))
554
+ for found in NAME_CONTEXT_RE.finditer(normalized):
555
+ value = found.group("value")
556
+ if value in NAME_STOPWORDS or value.split()[0] in NAME_STOPWORDS:
557
+ continue
558
+ matches.append(PIIMatch("person_name", field, found.start("value"), found.end("value"), value, "context_name", "medium"))
559
+
560
+ # 同一type・同一位置の重複を除き、出現順に返す。重複範囲は検出結果として
561
+ # 残すが、置換時には _select_non_overlapping で一つにまとめる。
562
+ unique: dict[tuple[str, str, int, int], PIIMatch] = {}
563
+ for match in matches:
564
+ unique[(match.pii_type, match.field, match.start, match.end)] = match
565
+ return sorted(unique.values(), key=lambda item: (item.start, item.end, item.pii_type))
566
+
567
+ def detect_record(self, url: Any, content: Any) -> list[PIIMatch]:
568
+ matches: list[PIIMatch] = []
569
+ if self.include_url:
570
+ matches.extend(self.detect(url, "url"))
571
+ matches.extend(self.detect(content, "content"))
572
+ return matches
573
+
574
+ def replace_text(self, text: Any, field: str = "content") -> tuple[str, list[PIIMatch]]:
575
+ """PIIをプレースホルダーに置換し、実際に置換した候補を返す���
576
+
577
+ NFKC正規化後の文字列を返すため、全角のメールアドレス等も一貫した
578
+ 表記になる。検出位置は返却文字列(置換前のNFKC文字列)に対応する。
579
+ """
580
+
581
+ normalized = normalize_text(text)
582
+ if not normalized:
583
+ return normalized, []
584
+ selected = _select_non_overlapping(self.detect(normalized, field))
585
+ replaced = normalized
586
+ for match in reversed(selected):
587
+ replaced = replaced[: match.start] + match.placeholder + replaced[match.end :]
588
+ return replaced, selected
589
+
590
+ def replace_record(self, url: Any, content: Any) -> tuple[str, str, list[PIIMatch]]:
591
+ replaced_url, url_matches = (self.replace_text(url, "url") if self.include_url else (normalize_text(url), []))
592
+ replaced_content, content_matches = self.replace_text(content, "content")
593
+ return replaced_url, replaced_content, url_matches + content_matches
594
+
595
+
596
+ def matches_to_dict(matches: Iterable[PIIMatch]) -> list[dict[str, Any]]:
597
+ return [match.to_dict() for match in matches]
code/e5cb5ca/src/pii_residual_check.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """置換後データの PII 残存を、独立した検出器(GLiNER-ja)で確認する(監査項目12)。
2
+
3
+ ``pii_detector.py`` と同じ検出器で再走査しても残存は必ず 0 になるため、
4
+ 学習済み日本語 PII NER ``DataSign/gliner-ja-pii-v1``(Apache-2.0)で
5
+ サンプルを走査し、プレースホルダー以外に残っている氏名・電話・住所・
6
+ メール・口座番号を数える。``--original`` に置換前の parquet を渡すと、
7
+ 同じ文書で GLiNER が置換前に検出した実体のうち置換後に消えている割合
8
+ (決定的検出器の再現率の目安)も出す。
9
+
10
+ uv sync --group pii-check
11
+ uv run python abeja-cc-ja/src/pii_residual_check.py --input <replaced.parquet> --sample 500 --output pii_residual.json
12
+
13
+ モデルは最大160トークンのため、文書を文字数で分割して重なり付きで走査する。
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+ import json
20
+ import random
21
+ import time
22
+ import unicodedata
23
+ from collections import Counter, defaultdict
24
+ from datetime import datetime, timezone
25
+ from pathlib import Path
26
+ from typing import Any
27
+
28
+ import pyarrow.parquet as pq
29
+
30
+ from pii_detector import NAME_CONTEXT_WINDOW, TITLE_CONTEXT_RE, _ORG_RE, _same_sentence_window
31
+
32
+
33
+ MODEL_NAME = "DataSign/gliner-ja-pii-v1"
34
+ LABELS = ["person name", "phone number", "address", "email address", "account number"]
35
+ LABEL_TO_TYPE = {
36
+ "person name": "person_name",
37
+ "phone number": "phone",
38
+ "address": "address",
39
+ "email address": "email",
40
+ "account number": "bank_account",
41
+ }
42
+ PLACEHOLDER_MARKERS = ("<EMAIL>", "<PHONE>", "<ADDRESS>", "<PERSON_NAME>", "<PERSON_AFFILIATION>", "<MY_NUMBER>", "<CREDIT_CARD>", "<BANK_ACCOUNT>")
43
+
44
+
45
+ def load_model(device: str | None):
46
+ from gliner import GLiNER
47
+ from gliner.data_processing import WordsSplitter
48
+
49
+ class JapaneseSplitterNoWS:
50
+ def __init__(self) -> None:
51
+ self._base = WordsSplitter(splitter_type="janome")
52
+
53
+ def __call__(self, text: str):
54
+ for token, start, end in self._base(text):
55
+ if token.strip() == "":
56
+ continue
57
+ yield token, start, end
58
+
59
+ model = GLiNER.from_pretrained(MODEL_NAME, max_width=25)
60
+ model.data_processor.words_splitter = JapaneseSplitterNoWS()
61
+ if device:
62
+ try:
63
+ model = model.to(device)
64
+ except Exception: # noqa: BLE001 - デバイス非対応時はCPUのまま
65
+ pass
66
+ model.eval()
67
+ return model
68
+
69
+
70
+ def chunks(text: str, size: int, overlap: int):
71
+ start = 0
72
+ while start < len(text):
73
+ end = min(len(text), start + size)
74
+ yield start, text[start:end]
75
+ if end == len(text):
76
+ break
77
+ start = end - overlap
78
+
79
+
80
+ def predict(model, text: str, threshold: float, chunk_chars: int, overlap: int) -> list[dict[str, Any]]:
81
+ found: dict[tuple[str, int, int], dict[str, Any]] = {}
82
+ for offset, piece in chunks(text, chunk_chars, overlap):
83
+ for entity in model.predict_entities(piece, LABELS, threshold=threshold):
84
+ key = (entity["label"], offset + entity["start"], offset + entity["end"])
85
+ if key not in found:
86
+ found[key] = {"label": entity["label"], "start": key[1], "end": key[2], "text": entity["text"], "score": round(float(entity["score"]), 3)}
87
+ return sorted(found.values(), key=lambda item: (item["start"], item["end"]))
88
+
89
+
90
+ def is_placeholder(text: str) -> bool:
91
+ return any(marker in text for marker in PLACEHOLDER_MARKERS) or "<" in text
92
+
93
+
94
+ def mask(text: str) -> str:
95
+ return text[:1] + "*" * max(1, len(text) - 1)
96
+
97
+
98
+ def main(argv: list[str] | None = None) -> None:
99
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
100
+ parser.add_argument("--input", type=Path, required=True, help="置換後の parquet(url, content)")
101
+ parser.add_argument("--original", type=Path, default=None, help="置換前の parquet(同じ行順)。再現率の目安を出す")
102
+ parser.add_argument("--sample", type=int, default=500)
103
+ parser.add_argument("--seed", type=int, default=20260904)
104
+ parser.add_argument("--threshold", type=float, default=0.5)
105
+ parser.add_argument("--chunk-chars", type=int, default=200)
106
+ parser.add_argument("--overlap", type=int, default=40)
107
+ parser.add_argument("--max-chars", type=int, default=3000, help="1文書あたり走査する最大文字数")
108
+ parser.add_argument("--device", default=None, help="cpu / mps / cuda(既定はGLiNERの既定)")
109
+ parser.add_argument("--output", type=Path, required=True)
110
+ args = parser.parse_args(argv)
111
+
112
+ table = pq.read_table(args.input, columns=["url", "content"])
113
+ total = table.num_rows
114
+ rng = random.Random(args.seed)
115
+ indices = sorted(rng.sample(range(total), min(args.sample, total)))
116
+ original = pq.read_table(args.original, columns=["content"]) if args.original else None
117
+ model = load_model(args.device)
118
+
119
+ residual_counts: Counter = Counter()
120
+ residual_docs: Counter = Counter()
121
+ examples: dict[str, list[dict[str, Any]]] = defaultdict(list)
122
+ recall_found: Counter = Counter()
123
+ recall_removed: Counter = Counter()
124
+ # 「個人名+所属」の定義(同一文・前後25文字に所属か役職)に該当する人名だけの再現率
125
+ ctx_found = 0
126
+ ctx_removed = 0
127
+ started = time.perf_counter()
128
+ docs_with_residual = 0
129
+ for index in indices:
130
+ row = table.slice(index, 1).to_pylist()[0]
131
+ text = unicodedata.normalize("NFKC", row.get("content") or "")[: args.max_chars]
132
+ entities = [e for e in predict(model, text, args.threshold, args.chunk_chars, args.overlap) if not is_placeholder(e["text"])]
133
+ if entities:
134
+ docs_with_residual += 1
135
+ seen_types = set()
136
+ for entity in entities:
137
+ pii_type = LABEL_TO_TYPE[entity["label"]]
138
+ residual_counts[pii_type] += 1
139
+ seen_types.add(pii_type)
140
+ if len(examples[pii_type]) < 5:
141
+ context = text[max(0, entity["start"] - 25): entity["start"]] + "[" + mask(entity["text"]) + "]" + text[entity["end"]: entity["end"] + 25]
142
+ examples[pii_type].append({"record_index": index, "url": row.get("url"), "score": entity["score"], "context_masked": context.replace("\n", " ")})
143
+ for pii_type in seen_types:
144
+ residual_docs[pii_type] += 1
145
+ if original is not None:
146
+ original_text = unicodedata.normalize("NFKC", original.slice(index, 1).to_pylist()[0].get("content") or "")[: args.max_chars]
147
+ for entity in predict(model, original_text, args.threshold, args.chunk_chars, args.overlap):
148
+ pii_type = LABEL_TO_TYPE[entity["label"]]
149
+ recall_found[pii_type] += 1
150
+ removed = entity["text"] not in text
151
+ if removed:
152
+ recall_removed[pii_type] += 1
153
+ if pii_type == "person_name":
154
+ before, after = _same_sentence_window(original_text, entity["start"], entity["end"], NAME_CONTEXT_WINDOW)
155
+ if _ORG_RE.search(before) or _ORG_RE.search(after) or TITLE_CONTEXT_RE.search(before) or TITLE_CONTEXT_RE.search(after):
156
+ ctx_found += 1
157
+ ctx_removed += removed
158
+ elapsed = time.perf_counter() - started
159
+ result = {
160
+ "checked_at_utc": datetime.now(timezone.utc).isoformat(),
161
+ "detector": {"model": MODEL_NAME, "license": "Apache-2.0", "labels": LABELS, "threshold": args.threshold,
162
+ "chunk_chars": args.chunk_chars, "overlap": args.overlap, "max_chars": args.max_chars},
163
+ "input": str(args.input), "total_records": total, "sampled_records": len(indices), "seed": args.seed,
164
+ "elapsed_s": round(elapsed, 1),
165
+ "residual": {
166
+ "records_with_any_residual": docs_with_residual,
167
+ "records_with_residual_rate": round(docs_with_residual / max(1, len(indices)), 4),
168
+ "by_type_entities": dict(residual_counts),
169
+ "by_type_records": dict(residual_docs),
170
+ "examples_masked": examples,
171
+ },
172
+ "note_ja": "GLiNER-ja が置換後テキストで検出した実体(プレースホルダーを除く)。氏名は公人・著者名・作品中の人名も含むため、残存の要否は目視で判断する。",
173
+ }
174
+ if original is not None:
175
+ result["recall_estimate_person_name_with_affiliation_context"] = {
176
+ "gliner_found_in_original": ctx_found,
177
+ "removed_after_replacement": ctx_removed,
178
+ "removed_rate": round(ctx_removed / ctx_found, 3) if ctx_found else None,
179
+ "note_ja": "GLiNER-ja が検出した人名のうち、同一文・前後25文字に所属か役職がある(=個人名+所属の定義に該当する)ものの置換率。",
180
+ }
181
+ result["recall_estimate"] = {
182
+ pii_type: {"gliner_found_in_original": recall_found[pii_type], "removed_after_replacement": recall_removed[pii_type],
183
+ "removed_rate": round(recall_removed[pii_type] / recall_found[pii_type], 3) if recall_found[pii_type] else None}
184
+ for pii_type in sorted(recall_found)
185
+ }
186
+ args.output.parent.mkdir(parents=True, exist_ok=True)
187
+ args.output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
188
+ print(json.dumps({"sampled": len(indices), "records_with_residual": docs_with_residual, "by_type": dict(residual_counts),
189
+ "recall_estimate": result.get("recall_estimate"),
190
+ "recall_person_name_with_affiliation_context": result.get("recall_estimate_person_name_with_affiliation_context"),
191
+ "elapsed_s": round(elapsed, 1)}, ensure_ascii=False))
192
+
193
+
194
+ if __name__ == "__main__":
195
+ main()
code/e5cb5ca/src/review_tally.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """記入済みの review_samples.csv を集計し、層別の精度・見逃し率を出す。
2
+
3
+ verdict は ``harmful`` / ``not_harmful`` / ``unsure`` の3値。未記入は未確認として数える。
4
+ 出力は ``review_tally.json`` と標準出力の表。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import csv
11
+ import json
12
+ from collections import defaultdict
13
+ from datetime import datetime, timezone
14
+ from pathlib import Path
15
+
16
+
17
+ def main(argv: list[str] | None = None) -> None:
18
+ parser = argparse.ArgumentParser(description=__doc__)
19
+ parser.add_argument("--csv", type=Path, required=True)
20
+ parser.add_argument("--output", type=Path, default=None, help="既定は CSV と同じ場所の review_tally.json")
21
+ args = parser.parse_args(argv)
22
+ counts: dict[str, dict[str, int]] = defaultdict(lambda: {"harmful": 0, "not_harmful": 0, "unsure": 0, "unreviewed": 0})
23
+ reviewers: set[str] = set()
24
+ with args.csv.open(encoding="utf-8", newline="") as handle:
25
+ for row in csv.DictReader(handle):
26
+ verdict = (row.get("verdict") or "").strip().lower() or "unreviewed"
27
+ if verdict not in ("harmful", "not_harmful", "unsure"):
28
+ verdict = "unreviewed"
29
+ counts[row["stratum"]][verdict] += 1
30
+ if row.get("reviewer"):
31
+ reviewers.add(row["reviewer"])
32
+ result: dict[str, dict] = {}
33
+ for stratum, c in sorted(counts.items()):
34
+ reviewed = c["harmful"] + c["not_harmful"]
35
+ entry = dict(c)
36
+ entry["reviewed"] = reviewed
37
+ if reviewed:
38
+ if stratum.startswith(("deleted:", "cooccurrence:")):
39
+ entry["precision"] = round(c["harmful"] / reviewed, 3) # 削除の妥当性
40
+ else:
41
+ entry["harmful_rate"] = round(c["harmful"] / reviewed, 3) # 保持側の見逃し率
42
+ result[stratum] = entry
43
+ output = args.output or args.csv.with_name("review_tally.json")
44
+ payload = {"tallied_at_utc": datetime.now(timezone.utc).isoformat(), "csv": str(args.csv), "reviewers": sorted(reviewers), "strata": result}
45
+ output.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
46
+ print(f"{'stratum':40s} {'harm':>5s} {'not':>5s} {'uns':>5s} {'todo':>5s} rate")
47
+ for stratum, e in result.items():
48
+ rate = e.get("precision", e.get("harmful_rate", ""))
49
+ print(f"{stratum:40s} {e['harmful']:5d} {e['not_harmful']:5d} {e['unsure']:5d} {e['unreviewed']:5d} {rate}")
50
+
51
+
52
+ if __name__ == "__main__":
53
+ main()
code/e5cb5ca/src/run_shard.py ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """シャード単位のクレンジングパイプライン(本実行用)。
2
+
3
+ 1ファイル(parquet)ごとに次を行う。
4
+
5
+ 1. 有害コンテンツフィルタ(ワードリスト・ドメインブロックリスト・近接共起規則)
6
+ 2. 保持分に PII 置換
7
+ 3. クリーン済み parquet と監査ファイル(removed.jsonl, audit.jsonl 等)を
8
+ ``<output-root>/<シャード名>/`` に書き出し、``shard_summary.json`` にまとめる
9
+ 4. 任意で HF データセットへバッチアップロード(``--upload-repo``)。アップロード後に
10
+ ローカルを削除すれば、HF Jobs の一時ディスク(50 GB)でも全シャードを処理できる
11
+
12
+ ``--workers`` でシャード並列に処理する。各ワーカーはワードリスト・ブロックリスト・
13
+ 共起規則を1回だけ読み込む(UT1 adult リストで約1.6 GB/ワーカー)。
14
+ ``shard_summary.json`` が既にあるシャードと、``--skip-existing-in-repo`` で
15
+ リポジトリに既に出力があるシャードは飛ばすので、途中終了後の再実行ができる。
16
+
17
+ uv run python abeja-cc-ja/src/run_shard.py --input-dir <dir> --output-root <out> --workers 7 \\
18
+ --upload-repo Podtech/abeja-cc-ja-cleaned --upload-prefix outputs/common_crawl_0 --delete-local-after-upload
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import argparse
24
+ import json
25
+ import multiprocessing as mp
26
+ import os
27
+ import shutil
28
+ import time
29
+ import traceback
30
+ from datetime import datetime, timezone
31
+ from pathlib import Path
32
+ from typing import Any
33
+
34
+ import pyarrow.parquet as pq
35
+
36
+
37
+ PIPELINE_VERSION = "abeja-cc-ja-cleansing/2026-09-04"
38
+ MODE = "distinct_terms_3plus"
39
+
40
+ _WORKER: dict[str, Any] = {}
41
+
42
+
43
+ def _init_worker(config: dict[str, Any]) -> None:
44
+ """ワーカー起動時にリソースを1回だけ読み込む。"""
45
+
46
+ import sys
47
+
48
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
49
+ from cooccurrence import CooccurrenceDetector, load_rules
50
+ from domain_blocklist import DomainBlocklist
51
+
52
+ _WORKER["config"] = config
53
+ _WORKER["blocklist"] = None if config["no_blocklist"] else DomainBlocklist.load(Path(config["blocklist_dir"]), Path(config["blocklist_cache_dir"]))
54
+ _WORKER["cooccurrence"] = None if config["no_cooccurrence"] else CooccurrenceDetector(load_rules(Path(config["cooccurrence_rules"])))
55
+
56
+
57
+ def process_shard(input_path: Path, output_root: Path, config: dict[str, Any]) -> dict[str, Any]:
58
+ """1シャードを処理し、shard_summary を返す(ワーカー内で実行)。"""
59
+
60
+ from filter_pii import run_filter as run_pii
61
+ from filter_toxic import run_toxic_filters
62
+
63
+ if not _WORKER:
64
+ _init_worker(config)
65
+ shard = input_path.stem
66
+ out_dir = output_root / shard
67
+ out_dir.mkdir(parents=True, exist_ok=True)
68
+ started = time.perf_counter()
69
+ started_at = datetime.now(timezone.utc).isoformat()
70
+ input_rows = pq.ParquetFile(input_path).metadata.num_rows
71
+
72
+ t0 = time.perf_counter()
73
+ toxic = run_toxic_filters(
74
+ input_path=input_path,
75
+ output_root=out_dir / "toxic",
76
+ reference_dir=Path(config["reference_dir"]),
77
+ additional_dir=Path(config["additional_dir"]),
78
+ batch_size=config["batch_size"],
79
+ modes=[MODE],
80
+ exclude_dir=Path(config["exclude_dir"]),
81
+ blocklist=_WORKER["blocklist"],
82
+ cooccurrence=_WORKER["cooccurrence"],
83
+ )
84
+ toxic_seconds = time.perf_counter() - t0
85
+ toxic_mode = toxic["modes"][MODE]
86
+ retained_path = out_dir / "toxic" / MODE / "retained.parquet"
87
+
88
+ t0 = time.perf_counter()
89
+ pii = run_pii(
90
+ input_path=retained_path,
91
+ output_root=out_dir / "pii",
92
+ batch_size=config["batch_size"],
93
+ policy_approver=config.get("policy_approver"),
94
+ policy_approved_on=config.get("policy_approved_on"),
95
+ policy_note=config.get("policy_note"),
96
+ )
97
+ pii_seconds = time.perf_counter() - t0
98
+
99
+ final_path = out_dir / f"{shard}.parquet"
100
+ shutil.move(str(out_dir / "pii" / "pii_replaced" / "replaced.parquet"), str(final_path))
101
+ if not config.get("keep_intermediate"):
102
+ retained_path.unlink(missing_ok=True)
103
+ final_rows = pq.ParquetFile(final_path).metadata.num_rows
104
+
105
+ summary = {
106
+ "pipeline_version": PIPELINE_VERSION,
107
+ "shard": shard,
108
+ "input_file": str(input_path),
109
+ "input_rows": input_rows,
110
+ "started_at_utc": started_at,
111
+ "finished_at_utc": datetime.now(timezone.utc).isoformat(),
112
+ "seconds": {"toxic": round(toxic_seconds, 1), "pii": round(pii_seconds, 1), "total": round(time.perf_counter() - started, 1)},
113
+ "toxic": {
114
+ "mode": MODE,
115
+ "threshold": toxic_mode["threshold"],
116
+ "category_thresholds": toxic_mode.get("category_thresholds", {}),
117
+ "records_scanned": toxic_mode["total_records_scanned"],
118
+ "records_deleted": toxic_mode["records_deleted"],
119
+ "records_retained": toxic_mode["records_retained"],
120
+ "records_deleted_by_reason": toxic_mode["records_deleted_by_reason"],
121
+ "by_category": {c: {"records_with_match": v["records_with_match"], "records_deleted": v["records_deleted"]} for c, v in toxic_mode["by_category"].items()},
122
+ "domain_blocklist_by_source": {k: v for k, v in toxic_mode.get("domain_blocklist", {}).get("by_source", {}).items()},
123
+ "domain_blocklist_sources": toxic_mode.get("domain_blocklist", {}).get("sources"),
124
+ "cooccurrence_by_rule": {k: {"records_matched": v["records_matched"]} for k, v in toxic_mode.get("cooccurrence", {}).get("by_rule", {}).items()},
125
+ "wordlist_excluded_terms_by_category": toxic_mode.get("wordlist_excluded_terms_by_category"),
126
+ "wordlist_unique_terms_by_category": toxic.get("wordlist_unique_terms_by_category"),
127
+ },
128
+ "pii": {
129
+ "records_scanned": pii["total_records_scanned"],
130
+ "records_with_replacement": pii["records_with_replacement"],
131
+ "total_replacements": pii["total_replacements"],
132
+ "by_type": {k: {"records_with_match": v["records_with_match"], "replacement_count": v["replacement_count"]} for k, v in pii["by_type"].items()},
133
+ "policy": pii["pii_policy"],
134
+ "detector_version": pii.get("detector_version"),
135
+ },
136
+ "output": {
137
+ "cleaned_parquet": str(final_path),
138
+ "final_rows": final_rows,
139
+ "removed_jsonl": str(out_dir / "toxic" / MODE / "removed.jsonl"),
140
+ "cooccurrence_review_jsonl": str(out_dir / "toxic" / MODE / "cooccurrence_review.jsonl"),
141
+ "flagged_jsonl": str(out_dir / "toxic" / MODE / "flagged.jsonl"),
142
+ "borderline_jsonl": str(out_dir / "toxic" / MODE / "borderline.jsonl"),
143
+ "pii_audit_jsonl": str(out_dir / "pii" / "pii_replaced" / "audit.jsonl"),
144
+ },
145
+ }
146
+ (out_dir / "shard_summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
147
+ return summary
148
+
149
+
150
+ def _worker_entry(args: tuple[str, str, dict[str, Any]]) -> dict[str, Any]:
151
+ input_path, output_root, config = args
152
+ try:
153
+ return process_shard(Path(input_path), Path(output_root), config)
154
+ except Exception as error: # noqa: BLE001 - 1シャードの失敗で全体を止めない
155
+ return {"shard": Path(input_path).stem, "input_file": input_path, "error": repr(error), "traceback": traceback.format_exc()}
156
+
157
+
158
+ class Uploader:
159
+ """完了したシャードのディレクトリをまとめて HF データセットへアップロードする。"""
160
+
161
+ def __init__(self, repo_id: str, prefix: str, output_root: Path, batch: int, delete_local: bool, private: bool = True) -> None:
162
+ from huggingface_hub import HfApi
163
+
164
+ self.api = HfApi()
165
+ self.repo_id = repo_id
166
+ self.prefix = prefix.strip("/")
167
+ self.output_root = output_root
168
+ self.batch = max(1, batch)
169
+ self.delete_local = delete_local
170
+ self.pending: list[str] = []
171
+ self.uploaded: list[str] = []
172
+ self.api.create_repo(repo_id, repo_type="dataset", private=private, exist_ok=True)
173
+
174
+ def existing_shards(self) -> set[str]:
175
+ files = self.api.list_repo_files(self.repo_id, repo_type="dataset")
176
+ marker = f"{self.prefix}/"
177
+ return {path[len(marker):].split("/", 1)[0] for path in files if path.startswith(marker) and path.endswith("/shard_summary.json")}
178
+
179
+ def add(self, shard: str) -> None:
180
+ self.pending.append(shard)
181
+ if len(self.pending) >= self.batch:
182
+ self.flush()
183
+
184
+ def flush(self) -> None:
185
+ if not self.pending:
186
+ return
187
+ shards = list(self.pending)
188
+ for attempt in range(5):
189
+ try:
190
+ self.api.upload_folder(
191
+ repo_id=self.repo_id,
192
+ repo_type="dataset",
193
+ folder_path=str(self.output_root),
194
+ path_in_repo=self.prefix,
195
+ allow_patterns=[f"{shard}/**" for shard in shards],
196
+ commit_message=f"add {len(shards)} shard(s): {shards[0]}..{shards[-1]}",
197
+ )
198
+ break
199
+ except Exception as error: # noqa: BLE001
200
+ wait = 30 * (attempt + 1)
201
+ print(json.dumps({"event": "upload_retry", "attempt": attempt + 1, "error": repr(error), "wait_s": wait}), flush=True)
202
+ time.sleep(wait)
203
+ else:
204
+ raise RuntimeError(f"アップロードに失敗しました: {shards}")
205
+ self.uploaded.extend(shards)
206
+ self.pending.clear()
207
+ print(json.dumps({"event": "uploaded", "shards": shards, "repo": self.repo_id, "prefix": self.prefix}), flush=True)
208
+ if self.delete_local:
209
+ for shard in shards:
210
+ shutil.rmtree(self.output_root / shard, ignore_errors=True)
211
+
212
+
213
+ def main(argv: list[str] | None = None) -> None:
214
+ source_dir = Path(__file__).resolve().parent
215
+ project_root = source_dir.parent
216
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
217
+ group = parser.add_mutually_exclusive_group(required=True)
218
+ group.add_argument("--input", type=Path, action="append", help="入力parquet(複数可)")
219
+ group.add_argument("--input-dir", type=Path, help="入力parquetのディレクトリ")
220
+ parser.add_argument("--pattern", default="*.parquet")
221
+ parser.add_argument("--limit-shards", type=int, default=None, help="先頭N件だけ処理する(試運転用)")
222
+ parser.add_argument("--output-root", type=Path, required=True)
223
+ parser.add_argument("--workers", type=int, default=max(1, (os.cpu_count() or 2) - 1))
224
+ parser.add_argument("--batch-size", type=int, default=2048)
225
+ parser.add_argument("--keep-intermediate", action="store_true", help="有害フィルタ後の retained.parquet を残す")
226
+ parser.add_argument("--reference-dir", type=Path, default=source_dir / "wordlists" / "reference")
227
+ parser.add_argument("--additional-dir", type=Path, default=source_dir / "wordlists")
228
+ parser.add_argument("--exclude-dir", type=Path, default=source_dir / "wordlists" / "exclude")
229
+ parser.add_argument("--blocklist-dir", type=Path, default=source_dir / "blocklists")
230
+ parser.add_argument("--blocklist-cache-dir", type=Path, default=project_root / "data" / "blocklists" / "ut1")
231
+ parser.add_argument("--no-blocklist", action="store_true")
232
+ parser.add_argument("--cooccurrence-rules", type=Path, default=source_dir / "wordlists" / "cooccurrence" / "rules.json")
233
+ parser.add_argument("--no-cooccurrence", action="store_true")
234
+ parser.add_argument("--policy-approver", default=None)
235
+ parser.add_argument("--policy-approved-on", default=None)
236
+ parser.add_argument("--policy-note", default=None)
237
+ parser.add_argument("--upload-repo", default=None, help="出力先の HF データセット(例: Podtech/abeja-cc-ja-cleaned)。非公開で作成する")
238
+ parser.add_argument("--upload-prefix", default="outputs", help="リポジトリ内のパス接頭辞(例: outputs/common_crawl_0)")
239
+ parser.add_argument("--upload-batch", type=int, default=5, help="何シャードごとに1コミットでアップロードするか")
240
+ parser.add_argument("--delete-local-after-upload", action="store_true")
241
+ parser.add_argument("--skip-existing-in-repo", action="store_true", help="リポジトリに shard_summary.json があるシャードを飛ばす")
242
+ args = parser.parse_args(argv)
243
+
244
+ if args.input_dir:
245
+ inputs = sorted(args.input_dir.glob(args.pattern))
246
+ else:
247
+ inputs = list(args.input)
248
+ if args.limit_shards is not None:
249
+ inputs = inputs[: args.limit_shards]
250
+ if not inputs:
251
+ raise FileNotFoundError("入力parquetが見つかりません")
252
+ args.output_root.mkdir(parents=True, exist_ok=True)
253
+
254
+ uploader = None
255
+ skip: set[str] = set()
256
+ if args.upload_repo:
257
+ uploader = Uploader(args.upload_repo, args.upload_prefix, args.output_root, args.upload_batch, args.delete_local_after_upload)
258
+ if args.skip_existing_in_repo:
259
+ skip = uploader.existing_shards()
260
+ todo = []
261
+ for path in inputs:
262
+ shard = path.stem
263
+ if shard in skip or (args.output_root / shard / "shard_summary.json").exists():
264
+ print(json.dumps({"event": "skip", "shard": shard}), flush=True)
265
+ continue
266
+ todo.append(path)
267
+
268
+ config = {
269
+ "batch_size": args.batch_size,
270
+ "keep_intermediate": args.keep_intermediate,
271
+ "reference_dir": str(args.reference_dir), "additional_dir": str(args.additional_dir), "exclude_dir": str(args.exclude_dir),
272
+ "blocklist_dir": str(args.blocklist_dir), "blocklist_cache_dir": str(args.blocklist_cache_dir), "no_blocklist": args.no_blocklist,
273
+ "cooccurrence_rules": str(args.cooccurrence_rules), "no_cooccurrence": args.no_cooccurrence,
274
+ "policy_approver": args.policy_approver, "policy_approved_on": args.policy_approved_on, "policy_note": args.policy_note,
275
+ }
276
+ run_started = time.perf_counter()
277
+ results: list[dict[str, Any]] = []
278
+ print(json.dumps({"event": "start", "shards": len(todo), "skipped": len(inputs) - len(todo), "workers": args.workers, "output_root": str(args.output_root)}), flush=True)
279
+ jobs = [(str(path), str(args.output_root), config) for path in todo]
280
+ if args.workers <= 1 or len(jobs) <= 1:
281
+ _init_worker(config)
282
+ iterator = map(_worker_entry, jobs)
283
+ else:
284
+ # pyarrow がスレッドを持つため fork は子プロセスのデッドロック要因になる。spawn で各ワーカーが独立に読み込む。
285
+ context = mp.get_context("spawn")
286
+ pool = context.Pool(processes=min(args.workers, len(jobs)), initializer=_init_worker, initargs=(config,))
287
+ iterator = pool.imap_unordered(_worker_entry, jobs)
288
+ for result in iterator:
289
+ results.append(result)
290
+ if "error" in result:
291
+ print(json.dumps({"event": "error", "shard": result["shard"], "error": result["error"]}), flush=True)
292
+ continue
293
+ print(json.dumps({
294
+ "event": "done", "shard": result["shard"], "input_rows": result["input_rows"],
295
+ "toxic_deleted": result["toxic"]["records_deleted"], "pii_replacements": result["pii"]["total_replacements"],
296
+ "final_rows": result["output"]["final_rows"], "seconds": result["seconds"]["total"],
297
+ }, ensure_ascii=False), flush=True)
298
+ if uploader is not None:
299
+ uploader.add(result["shard"])
300
+ if uploader is not None:
301
+ uploader.flush()
302
+ errors = [r for r in results if "error" in r]
303
+ run_summary = {
304
+ "pipeline_version": PIPELINE_VERSION,
305
+ "finished_at_utc": datetime.now(timezone.utc).isoformat(),
306
+ "shards_processed": len(results) - len(errors),
307
+ "shards_failed": [{"shard": r["shard"], "error": r["error"]} for r in errors],
308
+ "shards_skipped": len(inputs) - len(todo),
309
+ "seconds": round(time.perf_counter() - run_started, 1),
310
+ "upload_repo": args.upload_repo,
311
+ "upload_prefix": args.upload_prefix if args.upload_repo else None,
312
+ }
313
+ (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")
314
+ print(json.dumps({"event": "finish", **run_summary}, ensure_ascii=False), flush=True)
315
+ if errors:
316
+ raise SystemExit(1)
317
+
318
+
319
+ if __name__ == "__main__":
320
+ main()
code/e5cb5ca/src/sample_for_review.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """目視確認と分類器用のサンプルを層別に抽出する(監査の第3手法の入口)。
2
+
3
+ 有害フィルタの出力(summary.json, removed.jsonl, borderline.jsonl,
4
+ cooccurrence_review.jsonl)と元の入力parquetから、次の層でサンプルを取る。
5
+
6
+ * ``deleted:<category>`` ワードリストで削除した文書(カテゴリ別、既定30件)
7
+ * ``deleted:domain_blocklist`` ドメインブロックリストで削除した文書(既定30件)
8
+ * ``cooccurrence:<rule>`` 近接共起規則の一致(規則ごとに既定100件。一致文書は全件削除される)
9
+ * ``borderline:<category>`` しきい値に1語足りず保持された文書(カテゴリ別、既定30件)
10
+ * ``retained:random`` 保持文書の無作為抽出(既定100件。見逃し率の推定に使う)
11
+
12
+ 出力は ``review_samples.csv``(人が判定を記入する)と ``review_samples.jsonl``
13
+ (``classify_qwen3guard.py`` の入力)。抽出条件は ``sampling_manifest.json`` に残す。
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+ import csv
20
+ import json
21
+ import random
22
+ from datetime import datetime, timezone
23
+ from pathlib import Path
24
+ from typing import Any
25
+
26
+ import pyarrow.parquet as pq
27
+
28
+ from filter_toxic import CATEGORIES, KeywordMatcher, load_wordlists
29
+ from textmatch import normalize
30
+
31
+
32
+ CSV_COLUMNS = [
33
+ "sample_id", "stratum", "category", "record_index", "url", "matched_terms",
34
+ "excerpt", "reviewer", "verdict", "reason", "reviewed_at",
35
+ ]
36
+
37
+
38
+ def _read_jsonl(path: Path) -> list[dict[str, Any]]:
39
+ if not path.exists():
40
+ return []
41
+ with path.open(encoding="utf-8") as handle:
42
+ return [json.loads(line) for line in handle if line.strip()]
43
+
44
+
45
+ def _excerpt(text: str, positions: list[int], length: int = 300) -> str:
46
+ if not text:
47
+ return ""
48
+ if positions:
49
+ start = max(0, positions[0] - length // 3)
50
+ else:
51
+ start = 0
52
+ return text[start:start + length].replace("\n", " ")
53
+
54
+
55
+ def main(argv: list[str] | None = None) -> None:
56
+ source_dir = Path(__file__).resolve().parent
57
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
58
+ parser.add_argument("--input", type=Path, required=True, help="元の入力parquet")
59
+ parser.add_argument("--output-root", type=Path, required=True, help="main_toxic.py の --output-root")
60
+ parser.add_argument("--mode", default="distinct_terms_3plus")
61
+ parser.add_argument("--dest", type=Path, required=True, help="サンプルの出力先ディレクトリ")
62
+ parser.add_argument("--seed", type=int, default=20260904)
63
+ parser.add_argument("--deleted-per-category", type=int, default=30)
64
+ parser.add_argument("--deleted-domain", type=int, default=30)
65
+ parser.add_argument("--borderline-per-category", type=int, default=30)
66
+ parser.add_argument("--random-retained", type=int, default=100)
67
+ parser.add_argument("--cooccurrence-limit", type=int, default=100, help="共起規則ごとの抽出上限(既定100。全件にするには 0)")
68
+ parser.add_argument("--text-chars", type=int, default=4000, help="JSONLに含める本文の最大文字数")
69
+ parser.add_argument("--reference-dir", type=Path, default=source_dir / "wordlists" / "reference")
70
+ parser.add_argument("--additional-dir", type=Path, default=source_dir / "wordlists")
71
+ parser.add_argument("--exclude-dir", type=Path, default=source_dir / "wordlists" / "exclude")
72
+ args = parser.parse_args(argv)
73
+ rng = random.Random(args.seed)
74
+ mode_dir = args.output_root / args.mode
75
+ summary = json.loads((mode_dir / "summary.json").read_text(encoding="utf-8"))
76
+ threshold = summary["threshold"]
77
+ removed = _read_jsonl(mode_dir / "removed.jsonl")
78
+ borderline = _read_jsonl(mode_dir / "borderline.jsonl")
79
+ cooccurrence = _read_jsonl(mode_dir / "cooccurrence_review.jsonl")
80
+ removed_indices = {record["_filter_record_index"] for record in removed}
81
+ row_range = summary["row_range"]
82
+
83
+ samples: list[dict[str, Any]] = []
84
+
85
+ def add(stratum: str, category: str, record_index: int, url: str, terms: list[str], text: str, positions: list[int]) -> None:
86
+ samples.append({
87
+ "stratum": stratum, "category": category, "record_index": record_index, "url": url,
88
+ "matched_terms": terms, "text": text, "match_positions": positions,
89
+ })
90
+
91
+ # 削除文書(ワードリスト)
92
+ for category in CATEGORIES:
93
+ pool = [r for r in removed if category in r["_filter_deleted_categories"]]
94
+ for record in rng.sample(pool, min(args.deleted_per_category, len(pool))):
95
+ terms = record["_filter_distinct_matched_terms_by_category"].get(category, [])
96
+ text = normalize(record.get("content") or "")
97
+ positions = sorted(p for t in terms for p in [text.find(t)] if p >= 0)
98
+ add(f"deleted:{category}", category, record["_filter_record_index"], record.get("url") or "", terms, text, positions)
99
+ # 削除文書(ドメインブロックリスト)
100
+ pool = [r for r in removed if "domain_blocklist" in r.get("_filter_deleted_by", [])]
101
+ for record in rng.sample(pool, min(args.deleted_domain, len(pool))):
102
+ sources = sorted({m["source"] + "=" + m["matched"] for m in record.get("_filter_domain_matches", [])})
103
+ add("deleted:domain_blocklist", "domain_blocklist", record["_filter_record_index"], record.get("url") or "", sources,
104
+ normalize(record.get("content") or ""), [])
105
+ # 共起規則(既定は全件)
106
+ by_rule: dict[str, list[dict[str, Any]]] = {}
107
+ for item in cooccurrence:
108
+ by_rule.setdefault(item["rule"], []).append(item)
109
+ removed_by_index = {r["_filter_record_index"]: r for r in removed}
110
+ for rule, items in by_rule.items():
111
+ chosen = items if not args.cooccurrence_limit else rng.sample(items, min(args.cooccurrence_limit, len(items)))
112
+ for item in chosen:
113
+ record = removed_by_index.get(item["record_index"], {})
114
+ text = normalize(record.get("content") or "")
115
+ positions = [pair["position"] for pair in item["pairs"][:4]]
116
+ pairs = [f"{pair['a']}×{pair['b']}" for pair in item["pairs"][:5]]
117
+ add(f"cooccurrence:{rule}", item.get("label_ja", rule), item["record_index"], item.get("url") or "", pairs, text, positions)
118
+
119
+ # 保持文書は入力parquetから本文を取る
120
+ needed: dict[int, list[tuple[str, str, list[str]]]] = {}
121
+ for category in CATEGORIES:
122
+ pool = [b for b in borderline if category in b["categories"]]
123
+ for record in rng.sample(pool, min(args.borderline_per_category, len(pool))):
124
+ needed.setdefault(record["record_index"], []).append((f"borderline:{category}", category, record["categories"][category]))
125
+ retained_pool = [i for i in range(row_range["start_row_inclusive"], row_range["end_row_exclusive"]) if i not in removed_indices]
126
+ for record_index in rng.sample(retained_pool, min(args.random_retained, len(retained_pool))):
127
+ needed.setdefault(record_index, []).append(("retained:random", "random", []))
128
+ if needed:
129
+ table = pq.read_table(args.input, columns=["url", "content"])
130
+ wordlists = load_wordlists(args.reference_dir, args.additional_dir, args.exclude_dir)
131
+ matcher = KeywordMatcher(wordlists.terms, wordlists.sources)
132
+ for record_index, entries in sorted(needed.items()):
133
+ row = table.slice(record_index, 1).to_pylist()[0]
134
+ text = normalize(row.get("content") or "")
135
+ positions = sorted({found.start() for found in matcher.pattern.finditer(text)})[:8]
136
+ for stratum, category, terms in entries:
137
+ add(stratum, category, record_index, row.get("url") or "", terms, text, positions)
138
+
139
+ args.dest.mkdir(parents=True, exist_ok=True)
140
+ with (args.dest / "review_samples.csv").open("w", encoding="utf-8", newline="") as handle:
141
+ writer = csv.DictWriter(handle, fieldnames=CSV_COLUMNS)
142
+ writer.writeheader()
143
+ for number, sample in enumerate(samples, start=1):
144
+ sample_id = f"S{number:05d}"
145
+ sample["sample_id"] = sample_id
146
+ writer.writerow({
147
+ "sample_id": sample_id, "stratum": sample["stratum"], "category": sample["category"],
148
+ "record_index": sample["record_index"], "url": sample["url"],
149
+ "matched_terms": " | ".join(sample["matched_terms"]),
150
+ "excerpt": _excerpt(sample["text"], sample["match_positions"]),
151
+ "reviewer": "", "verdict": "", "reason": "", "reviewed_at": "",
152
+ })
153
+ with (args.dest / "review_samples.jsonl").open("w", encoding="utf-8") as handle:
154
+ for sample in samples:
155
+ handle.write(json.dumps({
156
+ "id": sample["sample_id"], "stratum": sample["stratum"], "category": sample["category"],
157
+ "record_index": sample["record_index"], "url": sample["url"], "matched_terms": sample["matched_terms"],
158
+ "match_positions": sample["match_positions"], "text": sample["text"][:args.text_chars],
159
+ }, ensure_ascii=False, separators=(",", ":")) + "\n")
160
+ strata: dict[str, int] = {}
161
+ for sample in samples:
162
+ strata[sample["stratum"]] = strata.get(sample["stratum"], 0) + 1
163
+ manifest = {
164
+ "created_at_utc": datetime.now(timezone.utc).isoformat(),
165
+ "input": str(args.input), "output_root": str(args.output_root), "mode": args.mode, "seed": args.seed,
166
+ "sizes": {"deleted_per_category": args.deleted_per_category, "deleted_domain": args.deleted_domain,
167
+ "borderline_per_category": args.borderline_per_category, "random_retained": args.random_retained,
168
+ "cooccurrence_limit": args.cooccurrence_limit},
169
+ "threshold": threshold, "strata": strata, "total_samples": len(samples),
170
+ "verdict_values": ["harmful", "not_harmful", "unsure"],
171
+ }
172
+ (args.dest / "sampling_manifest.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
173
+ print(json.dumps({"total_samples": len(samples), "strata": strata}, ensure_ascii=False))
174
+
175
+
176
+ if __name__ == "__main__":
177
+ main()
code/e5cb5ca/src/textmatch.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ワードリスト照合の共通部品。正規化、語リストの読み込み、境界付きトライ正規表現。
2
+
3
+ ``filter_toxic.py`` と ``cooccurrence.py`` の両方から使うため、循環importを
4
+ 避けて独立モジュールに置く。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ import unicodedata
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+
15
+ ASCII_EDGE = "[a-z0-9]"
16
+ KATAKANA_EDGE = "[ァ-ヶー]"
17
+
18
+
19
+ def normalize(value: Any) -> str:
20
+ """ワードリストと本文を同じNFKC・小文字化規則で正規化する。"""
21
+
22
+ if value is None:
23
+ return ""
24
+ return unicodedata.normalize("NFKC", str(value)).lower()
25
+
26
+
27
+ def read_terms(path: Path) -> list[str]:
28
+ """1行1語のリストを読み、正規化する。空行と``#``始まりの行は無視する。"""
29
+
30
+ if not path.exists():
31
+ return []
32
+ terms: list[str] = []
33
+ for raw_line in path.read_text(encoding="utf-8").splitlines():
34
+ term = normalize(raw_line.strip())
35
+ if term and not term.startswith("#"):
36
+ terms.append(term)
37
+ return terms
38
+
39
+
40
+ def _edge_class(character: str) -> str | None:
41
+ """語の端の文字種。ASCII英数字とカタカナだけを境界判定の対象にする。"""
42
+
43
+ if re.fullmatch(ASCII_EDGE, character):
44
+ return ASCII_EDGE
45
+ if re.fullmatch(KATAKANA_EDGE, character):
46
+ return KATAKANA_EDGE
47
+ return None
48
+
49
+
50
+ def compile_trie_pattern(terms: list[str], boundaries: bool = True) -> re.Pattern[str]:
51
+ """多数語を共通接頭辞付き正規表現へコンパイルする。
52
+
53
+ ``boundaries`` が真のとき、語の端がASCII英数字なら英数字が隣接する位置、
54
+ 端がカタカナならカタカナ(長音を含む)が隣接する位置では一致させない。
55
+ 「メイク」中の「イク」、「DVD」中の「dv」のような単語内部の部分一致を
56
+ 防ぐ。漢字・ひらがなの端には境界を設けない。同じ位置では長い語を優先し、
57
+ 長い語が境界を満たさない場合だけ短い語で境界を確認する。
58
+ """
59
+
60
+ if not terms:
61
+ return re.compile(r"(?!x)x")
62
+ root: dict[str, Any] = {"terminal": False, "children": {}}
63
+ for term in terms:
64
+ node = root
65
+ for character in term:
66
+ node = node["children"].setdefault(character, {"terminal": False, "children": {}})
67
+ node["terminal"] = True
68
+
69
+ def lookahead(character: str) -> str:
70
+ edge = _edge_class(character) if boundaries else None
71
+ return f"(?!{edge})" if edge else ""
72
+
73
+ def render(node: dict[str, Any], last_character: str) -> str:
74
+ branches = [
75
+ re.escape(character) + render(child, character)
76
+ for character, child in sorted(node["children"].items())
77
+ ]
78
+ if not branches:
79
+ body = ""
80
+ elif len(branches) == 1:
81
+ body = branches[0]
82
+ else:
83
+ body = "(?:" + "|".join(branches) + ")"
84
+ if not node["terminal"]:
85
+ return body
86
+ end = lookahead(last_character)
87
+ if not body:
88
+ return end
89
+ return "(?:" + body + "|" + end + ")"
90
+
91
+ alternatives: list[str] = []
92
+ for character, child in sorted(root["children"].items()):
93
+ edge = _edge_class(character) if boundaries else None
94
+ # 後読みは先頭文字を消費した後に置く。分岐が後読みで始まると
95
+ # 正規表現エンジンの先頭文字による走査最適化が効かず、約4倍遅くなる。
96
+ lookbehind = f"(?<!{edge}{re.escape(character)})" if edge else ""
97
+ alternatives.append(re.escape(character) + lookbehind + render(child, character))
98
+ return re.compile("(?:" + "|".join(alternatives) + ")")
code/e5cb5ca/src/wordlists/cooccurrence/ja_howto_terms.txt ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 手引き(作り方・入手・回避)を示す語。報道で使われる「手口」、汎用の「手順」は含めない。
2
+ 作り方
3
+ 作成方法
4
+ 製造方法
5
+ 製造法
6
+ 製法
7
+ 精製方法
8
+ 精製法
9
+ 合成方法
10
+ 合成法
11
+ 栽培方法
12
+ 栽培法
13
+ 入手方法
14
+ 入手法
15
+ 購入方法
16
+ 買い方
17
+ 密輸方法
18
+ やり方
19
+ バレない
20
+ ばれない
21
+ バレずに
22
+ 足がつかない
23
+ 足のつかない
24
+ 摘発されない
25
+ 捕まらない
26
+ 逃れる方法
code/e5cb5ca/src/wordlists/cooccurrence/ja_illegal_object_terms.txt ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 違法行為の対象語。手引き語との近接共起で用いる。
2
+ # 「詐欺」「不正アクセス」「ランサムウェア」等は注意喚起・セキュリティ解説で「手順」「やり方」と
3
+ # 共起しやすく誤検出が多いため2026-09-04に外した。サイバー系はワードリスト crime で扱う。
4
+ 覚醒剤
5
+ 覚せい剤
6
+ 麻薬
7
+ 大麻
8
+ マリファナ
9
+ コカイン
10
+ ヘロイン
11
+ mdma
12
+ lsd
13
+ 危険ドラッグ
14
+ 脱法ハーブ
15
+ 違法薬物
16
+ 拳銃
17
+ 実銃
18
+ 改造銃
19
+ 爆弾
20
+ 爆発物
21
+ 火薬
22
+ 毒物
23
+ 青酸
24
+ サリン
25
+ 偽札
26
+ 闇バイト
27
+ 密輸
28
+ 密売
29
+ 脱税
30
+ マネーロンダリング
31
+ 資金洗浄
code/e5cb5ca/src/wordlists/cooccurrence/ja_minor_terms.txt ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 未成年を示す語。「js」はJavaScriptと衝突するため含めない。ASCII語・カタカナ語には文字種境界が適用される。
2
+ 小学生
3
+ 中学生
4
+ 高校生
5
+ 女子高生
6
+ 女子中学生
7
+ 女子小学生
8
+ 男子高校生
9
+ 男子中学生
10
+ 女子高校生
11
+ 未成年
12
+ 未成年者
13
+ 児童
14
+ 幼女
15
+ 幼児
16
+ 園児
17
+ ロリ
18
+ ロリータ
19
+ ランドセル
20
+ jk
21
+ jc
22
+ 女子生徒
23
+ 男子生徒
code/e5cb5ca/src/wordlists/cooccurrence/ja_sexual_terms.txt ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 性的な文脈を示す語。未成年語との近接共起で用いる。
2
+ セックス
3
+ 性行為
4
+ 性交
5
+ 性的
6
+ 挿入
7
+ エロ
8
+ わいせつ
9
+ 猥褻
10
+ 淫行
11
+ 淫ら
12
+ ヌード
13
+ 全裸
14
+ 裸体
15
+ オナニー
16
+ フェラ
17
+ 手コキ
18
+ 中出し
19
+ 射精
20
+ 精液
21
+ 勃起
22
+ ペニス
23
+ 膣
24
+ 乳首
25
+ 乳房
26
+ おっぱい
27
+ 巨乳
28
+ 陰部
29
+ 性器
30
+ 下着姿
31
+ パンチラ
32
+ 盗撮
33
+ 痴漢
34
+ レイプ
35
+ 強姦
36
+ 援交
37
+ 援助交際
38
+ パパ活
39
+ 売春
40
+ 買春
41
+ 風俗
42
+ アダルト
43
+ av女優
44
+ adult
45
+ porn
46
+ sex
47
+ hentai
code/e5cb5ca/src/wordlists/cooccurrence/rules.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "rules": [
3
+ {
4
+ "name": "minor_sexual_context",
5
+ "category": "adult_minor",
6
+ "label_ja": "未成年が登場する性的文脈",
7
+ "terms_a": "ja_minor_terms.txt",
8
+ "terms_b": "ja_sexual_terms.txt",
9
+ "window": 120,
10
+ "description_ja": "未成年を示す語と性的な語が120文字以内に共起する文書。監査項目5の『未成年が登場/読者として想定されている文脈は0件』を満たすため削除し、全件を目視確認する。事件報道や性教育も含まれ得るが、CPT用途では過剰削除を許容する。"
11
+ },
12
+ {
13
+ "name": "illegal_howto",
14
+ "category": "crime_howto",
15
+ "label_ja": "違法行為の手引き",
16
+ "terms_a": "ja_illegal_object_terms.txt",
17
+ "terms_b": "ja_howto_terms.txt",
18
+ "window": 40,
19
+ "description_ja": "薬物・武器・詐欺・不正アクセスの対象語と、作り方・入手方法・バレない方法などの手引き語が40文字以内に共起する文書。監査項目8の『手引き』を検出する。報道の『手口』は手引き語に含めない。"
20
+ }
21
+ ]
22
+ }
code/e5cb5ca/src/wordlists/exclude/ja_adult_exclude.txt ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 性的・わいせつカテゴリの除外語。既存リストは書き換えず、ここに載せた語だけを照合対象から外す。
2
+ # 根拠: common_crawl_0_filtered_0001(10万文書)での文書頻度と文脈サンプル。
3
+ # 漢字語は文字種境界が効かないため、他の語の内部に当たる汎用語を外す。
4
+ # 文書頻度 1.36%。個性的・慢性的・理性的・女性的の内部一致が大半。
5
+ 性的
6
+ # 文書頻度 0.70%。音痴・愚痴・乱痴気の内部一致。痴漢は別語として収録済み。
7
+ 痴
8
+ # 文書頻度 0.42%。自傷・自殺は暴力カテゴリで扱う(そちらには残す)。
9
+ 自殺
10
+ # ひらがな短語は動詞活用・助詞と衝突する(考えろ・答えろ、ころり・そろり、〜くんに、でっち上げ)。
11
+ えろ
12
+ ろり
13
+ でり
14
+ くんに
15
+ でっち
16
+ # 文書頻度 0.13%。「立ちはだかる」の内部一致が大半。
17
+ はだか
code/e5cb5ca/src/wordlists/exclude/ja_crime_exclude.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # 違法行為の手引きカテゴリの除外語。2026-09-04 のリスト再設計で汎用語(犯罪、drug など)を
2
+ # リスト自体から外したため、現時点では除外語なし。
code/e5cb5ca/src/wordlists/exclude/ja_discrimination_exclude.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # 差別・ヘイト・誹謗中傷カテゴリの除外語。既存リストは書き換えず、ここに載せた語だけを照合対象から外す。
2
+ # 文書頻度 0.85%。「不具合」の内部一致がほぼ全て。
3
+ 不具
4
+ # 文書頻度 0.14%。「詰めかけ」「諦めかけ」の内部一致が大半(妾のひらがな表記)。
5
+ めかけ
code/e5cb5ca/src/wordlists/exclude/ja_propaganda_conspiracy_exclude.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # 過激な政治・宗教プロパガンダ・陰謀論カテゴリの除外語。現時点では除外語なし。
2
+ # 「カルト」「デマ」の単語内部一致(オカルト、オンデマンド)は文字種境界で防がれる。
code/e5cb5ca/src/wordlists/exclude/ja_spam_exclude.txt ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # スパムカテゴリの除外語。既存リストは書き換えず、ここに載せた語だけを照合対象から外す。
2
+ # 根拠: common_crawl_0_filtered_0001(10万文書)での文書頻度と文脈サンプル。
3
+ # 一般の販促・EC文脈で高頻度に出現し、単独ではスパム性を示さない語。
4
+ # 文書頻度 7.46%(赤身肉に限定した、期間限定、数量限定、限定公開)
5
+ 限定
6
+ # 文書頻度 3.76%(クリスマスプレゼント、入賞者へのプレゼント)
7
+ プレゼント
8
+ # 文書頻度 2.56%(キャッシュバックキャンペーン、イベント情報)
9
+ キャンペーン
10
+ # 文書頻度 0.93%(無料クーポン、ぐるなびのクーポン)
11
+ クーポン
12
+ # 主題語だが、資産運用・働き方ブログなど一般文脈が大半のため除外する(2026-09-04 方針決定)。
13
+ # 文書頻度 0.71%(効率良く稼げる方法、安定して稼げるノウハウ)
14
+ 稼げる
15
+ # 文書頻度 0.67%(本業×副業×投資、趣味から副業に)
16
+ 副業
17
+ # 文書頻度 0.35%(短期売買のギャンブルをしない、ギャンブル依存症)
18
+ ギャンブル
code/e5cb5ca/src/wordlists/exclude/ja_violence_exclude.txt ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 暴力・自傷・自殺カテゴリの除外語。既存リストは書き換えず、ここに載せた語だけを照合対象から外す。
2
+ # 根拠: common_crawl_0_filtered_0001(10万文書)での文書頻度と文脈サンプル。
3
+ # 一般文脈(ニュース、医療、製品説明、日常会話)で高頻度に出現する汎用語。
4
+ # 文書頻度 1.28%(細胞を破壊、破壊力を持つ企業)
5
+ 破壊
6
+ # 文書頻度 0.46%。「破壊する」「崩壊する」の内部にも一致し、破壊と二重に数えられる。
7
+ 壊す
8
+ # 文書頻度 1.24%(恐怖心、閉所恐怖症)
9
+ 恐怖
10
+ # 文書頻度 1.11%(人はいずれ死ぬ、死ぬまで続く)
11
+ 死ぬ
12
+ # 文書頻度 0.96%(犯罪抑止、犯罪の発生件数)。犯罪の手引きそのものは crime の専門語で判定する。
13
+ 犯罪
14
+ # 文書頻度 0.60%(口喧嘩、恋人との喧嘩)
15
+ 喧嘩
16
+ # 文書頻度 0.47%。「相殺する」「乳酸菌を殺す」の内部一致。
17
+ 殺す
18
+ # 文書頻度 0.31%。「自殺した」「射殺した」の内部に一致し、自殺と二重に数えられる。
19
+ 殺した
20
+ # 主題語だが、事件報道・小説・相談記事など一般文脈が大半のため除外する(2026-09-04 方針決定)。
21
+ # 文書頻度 0.62%(性暴力の被害を告発、暴力的な排華運動)
22
+ 暴力
23
+ # 文書頻度 0.49%(殺人未遂の疑いで、殺人教唆の証拠、ドラマ紹介)
24
+ 殺人
25
+ # 文書頻度 0.42%(自殺予防に係る取組、事件報道)
26
+ 自殺
code/e5cb5ca/src/wordlists/ja_adult_keywords.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ ヌード
2
+ r18
3
+ porn
4
+ 児童買春
5
+ 性的搾取
6
+ 出会い系
7
+ 熟女
8
+ エロ漫画
9
+ アダルト動画
10
+ 素人娘
code/e5cb5ca/src/wordlists/ja_crime_keywords.txt ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 違法行為の手引きカテゴリ(2026-09-04 再設計)。
2
+ # 旧リストはサイバーセキュリティ用語中心で、セキュリティ企業の解説記事を削除していた。
3
+ # 手引きそのものは cooccurrence/rules.json の illegal_howto(対象語×手引き語)で検出し、
4
+ # このリストは違法市場・違法物の語が密集する文書(同一カテゴリ3語以上)の検出に用いる。
5
+ # 一般報道で使われる「犯罪」「詐欺」「逮捕」は入れない。
6
+ # --- 薬物 ---
7
+ 覚醒剤
8
+ 覚せい剤
9
+ 麻薬
10
+ 大麻
11
+ マリファナ
12
+ コカイン
13
+ ヘロイン
14
+ mdma
15
+ 危険ドラッグ
16
+ 脱法ハーブ
17
+ 違法薬物
18
+ 密売
19
+ 密輸
20
+ # --- 武器・危険物 ---
21
+ 拳銃
22
+ 実銃
23
+ 改造銃
24
+ 爆弾
25
+ 爆発物
26
+ 火薬
27
+ # --- 詐欺・不正取引 ---
28
+ 振り込め詐欺
29
+ オレオレ詐欺
30
+ 特殊詐欺
31
+ 架空請求
32
+ 闇バイト
33
+ 受け子
34
+ 出し子
35
+ 偽札
36
+ マネーロンダリング
37
+ 資金洗浄
38
+ 闇サイト
39
+ ダークウェブ
40
+ darkweb
41
+ scam
42
+ # --- 不正アクセス ---
43
+ 不正アクセス
44
+ ハッキング
45
+ クラッキング
46
+ マルウェア
47
+ ランサムウェア
48
+ フィッシング
49
+ hack
50
+ # --- 窃盗・その他 ---
51
+ 万引き
52
+ 盗聴
53
+ 脱税
54
+ 横領
code/e5cb5ca/src/wordlists/ja_discrimination_keywords.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 誹謗中傷
2
+ ヘイト
3
+ 人種差別
4
+ 性差別
5
+ 障害者差別
6
+ レイシスト
7
+ 排外主義
8
+ 民族差別
9
+ harassment
10
+ 優生思想
11
+ クソガキ
code/e5cb5ca/src/wordlists/ja_propaganda_conspiracy_keywords.txt ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 陰謀論
2
+ イルミナティ
3
+ ディープステート
4
+ illuminati
5
+ グレートリセット
6
+ qアノン
7
+ qanon
8
+ カルト教団に洗脳
9
+ ディープ・ステート
10
+ ケムトレイル
11
+ 大覚醒
12
+ deep state
13
+ 偽旗
14
+ フェイクニュース
15
+ デマ
16
+ 反ワクチン
17
+ 人口削減
18
+ マイクロチップ
19
+ グローバリスト
20
+ 新世界秩序
21
+ nwo
22
+ 集団ストーカー
23
+ カルト
24
+ 洗脳
25
+ 聖戦
26
+ conspiracy
27
+ new world order
code/e5cb5ca/src/wordlists/ja_spam_keywords.txt ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 迷惑メール
2
+ スパム
3
+ 今すぐ登録
4
+ 当選しました
5
+ 海賊版
6
+ 広告をクリック
7
+ 架空請求
8
+ アダルトサイト
9
+ 違法ダウンロード
10
+ 投資詐欺
11
+ crack
12
+ 必ず儲かる
13
+ torrent
14
+ フィッシングサイト
15
+ 絶対に儲かる
16
+ cracked
17
+ keygen
18
+ アフィリエイト
19
+ アフィカス
20
+ 副業
21
+ 高収入
22
+ 稼げる
23
+ 仮想通貨
24
+ オンラインカジノ
25
+ カジノ
26
+ ギャンブル
27
+ 競馬
28
+ パチンコ
29
+ ポイントサイト
30
+ クーポン
31
+ キャンペーン
32
+ 懸賞
33
+ プレゼント
34
+ 限定
35
+ 広告収入
36
+ 無料配布
37
+ 無料視聴
38
+ 違法コピー
39
+ フィッシング
40
+ アダルト
41
+ ポルノ
42
+ streaming
43
+ casino
44
+ bonus
45
+ coupon
46
+ affiliate
47
+ scam
48
+ phishing
49
+ adult
50
+ porn
51
+ xxx
52
+ warez
code/e5cb5ca/src/wordlists/ja_violence_keywords.txt ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 自殺
2
+ 飛び降り
3
+ bomb
4
+ 爆発物
5
+ murder
6
+ weapon
7
+ 首吊り
8
+ リストカット
9
+ 暴行
10
+ 強姦
11
+ 強盗
12
+ テロ
13
+ 刃物
14
+ 斬殺
15
+ 殺戮
16
+ 自爆
17
+ 殺害予告
18
+ 爆破
19
+ 銃器
20
+ 兵器
21
+ dv
22
+ torture
23
+ terrorist
24
+ assault
25
+ shooting
26
+ explosive
27
+ stab
28
+ stabbing
29
+ hostage
30
+ genocide
31
+ テロリスト
code/e5cb5ca/src/wordlists/reference/ja_adult_keywords.txt ADDED
@@ -0,0 +1,1462 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 18+
2
+ 18禁
3
+ 20禁
4
+ 21禁
5
+ 3P
6
+ 48手
7
+ AV女優
8
+ AV男優
9
+ AV監督
10
+ Aカップ
11
+ Bカップ
12
+ Cカップ
13
+ Dカップ
14
+ D乳
15
+ Eカップ
16
+ Fカップ
17
+ G spot
18
+ Gすぽっと
19
+ Gカップ
20
+ Gスポ
21
+ Gスポット
22
+ HENTAI
23
+ Holy Shit
24
+ Hした
25
+ Hしたい
26
+ Hして
27
+ Hしない?
28
+ Hしよ
29
+ Hしよっか
30
+ Hする
31
+ Hな
32
+ Hな写
33
+ Hに
34
+ Hの
35
+ Hを
36
+ Hナ
37
+ H中彼女
38
+ H写
39
+ H友達
40
+ H声
41
+ H好
42
+ H画
43
+ MANKO
44
+ MANNKO
45
+ M字
46
+ OMANKO
47
+ OMEKO
48
+ Okamoto
49
+ Onaho
50
+ Onani
51
+ SEX
52
+ SMくらぶ
53
+ SMぐっず
54
+ SMクラブ
55
+ SMグッズ
56
+ SMプレイ
57
+ SM俱樂部
58
+ Sagami
59
+ S○X
60
+ TENGA
61
+ Tバック
62
+ asoko
63
+ gすぽっと
64
+ gスポット
65
+ hしたい
66
+ hする
67
+ hな
68
+ h写
69
+ h好
70
+ h画
71
+ manko
72
+ mannko
73
+ sex
74
+ smくらぶ
75
+ xvideo
76
+ あ○る
77
+ あいえき
78
+ あいこら
79
+ あいぶ
80
+ あえぎ
81
+ あおかん
82
+ あくめ
83
+ あさだち
84
+ あだると
85
+ あなる
86
+ あへ顔
87
+ いぶつそうにゅう
88
+ いまら
89
+ いめーじくらぶ
90
+ いらま
91
+ いんけい
92
+ いんこう
93
+ いんぽ
94
+ いんもう
95
+ いんらん
96
+ う ゙ぁぎな
97
+ うらびでお
98
+ ぇ□
99
+ ぇっち
100
+ ぇろ
101
+ ぇ口
102
+ え ろとーく
103
+ え ろトーク
104
+ え□
105
+ え、ろとーく
106
+ え〇すぎる
107
+ えすえむ
108
+ えちし
109
+ えちな
110
+ えっくすびでお
111
+ えっち
112
+ えねまぐら
113
+ えろ
114
+ えろい
115
+ えろつべ
116
+ えろ写メ
117
+ えんこう
118
+ えんじょ
119
+ えんじょこうさい
120
+ えッち
121
+ え口
122
+ お な に
123
+ お○にー
124
+ お●ぱい
125
+ お◯にー
126
+ おかもと
127
+ おちOちん
128
+ おちんこ
129
+ おちんぽ
130
+ おっP
131
+ おっp
132
+ おっπ
133
+ おっさんとH
134
+ おっぱい
135
+ おっぱぶ
136
+ おっパブ
137
+ おとなのおもちゃ
138
+ おな に
139
+ おな○ー
140
+ おなった
141
+ おなでん
142
+ おなに
143
+ おなにほーる
144
+ おなにー
145
+ おなほ
146
+ おなほーる
147
+ おなる
148
+ おなろう
149
+ おな二
150
+ おな写
151
+ おな声
152
+ おな好
153
+ おな画
154
+ おな系
155
+ おな電
156
+ おまnこ
157
+ おまんこ
158
+ おめこ
159
+ おりえんと工業
160
+ おるが
161
+ おーがずむ
162
+ お掃除フェラ
163
+ かうぱー
164
+ かり頭
165
+ かわかぶり
166
+ がんしゃ
167
+ がんめんきじょうい
168
+ き○たま
169
+ きじょうい
170
+ きっこうしばり
171
+ きょこん
172
+ きょちん
173
+ きんたま
174
+ くそまん
175
+ くそマン
176
+ くりとり
177
+ くりとりす
178
+ くわえ込む
179
+ くんに
180
+ けつ毛
181
+ けつ穴
182
+ こうしんこく
183
+ こうないはっしゃ
184
+ こうはいい
185
+ こうび
186
+ こうもん
187
+ こかん
188
+ こんどーむ
189
+ ごうかん
190
+ ごむしゃく
191
+ ごむ尺
192
+ さいいんざい
193
+ さきばしりじる
194
+ さきばしりぢる
195
+ さげまん
196
+ さんぴー
197
+ ざーめん
198
+ しおふき
199
+ しこしこ
200
+ しこる
201
+ しっくすないん
202
+ しゃぶる
203
+ しょうにせいあい
204
+ しょじょ
205
+ しりがるおんな
206
+ じゅうかん
207
+ じょいん
208
+ じょうふ
209
+ すかと□
210
+ すかとろ
211
+ すかと口
212
+ すかーとめくり
213
+ すけこまし
214
+ すけすけ
215
+ すけべ
216
+ すぺるま
217
+ すまた
218
+ ずっこんばっ婚
219
+ ずりねた
220
+ ずり仙人
221
+ せ××す
222
+ せ×くす
223
+ せ○くす
224
+ せ●くす
225
+ せ❍くす
226
+ せいいん
227
+ せいえき
228
+ せいかんまっさーじ
229
+ せいかんヘルス
230
+ せいき
231
+ せいこう
232
+ せいし
233
+ せいじょうい
234
+ せいどれい
235
+ せいへき
236
+ せいよく
237
+ せくきゃば
238
+ せくはら
239
+ せくふれ
240
+ せくろす
241
+ せっ○す
242
+ せっく○
243
+ せっくす
244
+ せふ○
245
+ せふれ
246
+ せんずり
247
+ せックス
248
+ ぜつりん
249
+ ぜんぎ
250
+ ぜんしんりっぷ
251
+ そくはめ
252
+ そーぷ
253
+ そーぷらんど
254
+ たちばっく
255
+ たちまん
256
+ たまきん
257
+ たまなめ
258
+ たまぶく
259
+ たま舐め
260
+ たんぽん
261
+ だいいんしん
262
+ だっちまん
263
+ だっちわいふ
264
+ だんこん
265
+ ち○こ
266
+ ち○ぽ
267
+ ち●こ
268
+ ち◯ぽ
269
+ ちくび
270
+ ちこう
271
+ ちじょ
272
+ ちじょくぷれい
273
+ ちつがいしゃせい
274
+ ちゃH
275
+ ちんk
276
+ ちん○ん
277
+ ちん●ん
278
+ ちんかす
279
+ ちんぐり
280
+ ちんげ
281
+ ちんこ
282
+ ちんちん
283
+ ちんば
284
+ ちんぴく
285
+ ちんぼ
286
+ ちんぽ
287
+ ちんぽこ
288
+ ちんぽろ
289
+ ちんカス
290
+ ちんポロ
291
+ ちん毛
292
+ ちーんこ
293
+ てこき
294
+ てまん
295
+ てるH
296
+ てれH
297
+ てれくら
298
+ てれふぉんくらぶ
299
+ てれほんくらぶ
300
+ てんが
301
+ で●へる
302
+ でぃるど
303
+ でぃーぷきす
304
+ でぃーぷすろーと
305
+ でかちん
306
+ でかまら
307
+ でっち
308
+ でり
309
+ でりへる
310
+ でんま
311
+ とうさつ
312
+ とるこじょう
313
+ とるこぶろ
314
+ とるこ嬢
315
+ とるこ風呂
316
+ どうてい
317
+ どんびゃくしょう
318
+ なかだし
319
+ なかダシ
320
+ なか出し
321
+ なましゃく
322
+ なまそうにゅう
323
+ なま尺
324
+ におうだちふぇら
325
+ にくつぼ
326
+ にくべんき
327
+ にくぼう
328
+ にっぷる
329
+ にょいん
330
+ にょたいもり
331
+ ぬれぬれ
332
+ ぬーど
333
+ のぞきべや
334
+ のぞき部屋
335
+ はだか
336
+ はってん場
337
+ はぷにんぐば
338
+ はみちん
339
+ はみ毛
340
+ はめっこ
341
+ はめどり
342
+ はめ倒し
343
+ はめ写メ
344
+ はめ撮り
345
+ ばいあぐら
346
+ ばいぶ
347
+ ばーじん
348
+ ぱ●てぃ
349
+ ぱいおつ
350
+ ぱいすら
351
+ ぱいずり
352
+ ぱいぱん
353
+ ぱつぱつ
354
+ ぱんすけ
355
+ ぱんつ
356
+ ぱんつ丸見え
357
+ ひとりH
358
+ ひとりエッチ
359
+ ひにん
360
+ びっち
361
+ びらびら
362
+ びーちく
363
+ ぴ●さろ
364
+ ぴすとん
365
+ ぴんくさろん
366
+ ぴんくろーた
367
+ ぴんさろ
368
+ ふぁっく
369
+ ふうぞく
370
+ ふぇら
371
+ ふぇらち
372
+ ふたなり
373
+ ふにゃちん
374
+ ふーぞく
375
+ ぶてぃっくほてる
376
+ ぶらじゃー
377
+ ぶらちら
378
+ ぷっしー
379
+ へるす
380
+ へんたい
381
+ べろちゅー
382
+ ぺってぃんぐ
383
+ ぺどふぃりあ
384
+ ぺにす
385
+ ぺにすばんど
386
+ ぺにすりんぐ
387
+ ぺにばん
388
+ ほてとる
389
+ ほてへる
390
+ ほんさろ
391
+ ぼっき
392
+ ぽこちん
393
+ ぽるちお
394
+ ぽるの
395
+ ぽろり
396
+ ぽんびき
397
+ ぽん引き
398
+ ま○こ
399
+ ま●こ
400
+ ま〇汁
401
+ まいるーら
402
+ まえつき
403
+ まぐわい
404
+ まさぐり
405
+ まじっくみらー号
406
+ ますかき
407
+ ますたーべーしょん
408
+ まぞ
409
+ まな板ショー
410
+ まむこ
411
+ まんP
412
+ まん〇
413
+ まんかす
414
+ まんぐりがえし
415
+ まんぐり返し
416
+ まんげ
417
+ まんこ
418
+ まんしゅう
419
+ まんじる
420
+ まんすじ
421
+ まんちょ
422
+ まんちん
423
+ まんまん
424
+ まんカス
425
+ まん写
426
+ まん形
427
+ まん拓
428
+ まん毛
429
+ まん汁
430
+ まん臭
431
+ みるくたんく
432
+ むしゅうせい
433
+ むちむち
434
+ むっちり
435
+ むらむら
436
+ めこすじ
437
+ めこ筋
438
+ めちゃしこ
439
+ めちゃシコ
440
+ もざいく
441
+ もっこり
442
+ もりまん
443
+ もろだし
444
+ やり×ん
445
+ やりさー
446
+ やりちん
447
+ やりとも
448
+ やりまん
449
+ やりコン
450
+ やりチン
451
+ やりマン
452
+ やり友
453
+ やり逃げ
454
+ ゆびまん
455
+ ゆるまん
456
+ ゆるマン
457
+ ょぅΙ゙ょ
458
+ ようじょ
459
+ らぶほ
460
+ らぶほーる
461
+ らんこう
462
+ りあるH
463
+ りあるh
464
+ りあるでH
465
+ りょな
466
+ れ○ぷ
467
+ れ●ぷ
468
+ れいぱー
469
+ れいぷ
470
+ ろり
471
+ ろりこん
472
+ ろりぺど
473
+ ろりーた
474
+ ろーたー
475
+ わいせつ
476
+ わかめ酒
477
+ わぎな
478
+ ア○ル
479
+ ア●ル
480
+ アイコラ
481
+ アエギ
482
+ アクメ
483
+ アサダチ
484
+ アス
485
+ アスホール
486
+ アダルト
487
+ アダルトコーナー
488
+ アダルトチャット
489
+ アダルトビデオ
490
+ アナニー
491
+ アナル
492
+ アナルSEX
493
+ アナルセックス
494
+ アナルバイブ
495
+ アナルバージン
496
+ アナルパール
497
+ アナルファック
498
+ アナルフィスト
499
+ アナルプレイ
500
+ アナル拡張
501
+ アナル舐め
502
+ アニリングス
503
+ アヌス
504
+ アブノーマル
505
+ アヘ顔
506
+ アースホール
507
+ イキ顔
508
+ イク
509
+ イマラ
510
+ イマラチオ
511
+ イメクラ
512
+ イメージクラブ
513
+ イラマ
514
+ イラマチオ
515
+ インケイ
516
+ インコウ
517
+ インポ
518
+ インモウ
519
+ インラン
520
+ ウ ゙ぁぎな
521
+ ウ ゙ァギナ
522
+ ウ○コ
523
+ ウ●コ
524
+ ウラdvd
525
+ ェ□
526
+ ェロ
527
+ ェ口
528
+ エ ロトーク
529
+ エ ロ写メ
530
+ エ ロ話
531
+ エ□
532
+ エ、ロトーク
533
+ エ〇
534
+ エ〇すぎる
535
+ エっち
536
+ エっチ
537
+ エクスタシー
538
+ エスエム
539
+ エチ
540
+ エチし
541
+ エチな話
542
+ エックスビデオ
543
+ エッチ
544
+ エッチな話
545
+ エネマグラ
546
+ エロ
547
+ エロイプ
548
+ エロエロ
549
+ エロゲ
550
+ エロシャメ
551
+ エロス
552
+ エロティック
553
+ エロトーク
554
+ エロ写メ
555
+ エロ動画
556
+ エロ画像
557
+ エロ話
558
+ エンコウ
559
+ エンコー
560
+ エンジョ
561
+ エンジョコウサイ
562
+ エ口
563
+ オ○ニー
564
+ オ●ニー
565
+ オ◯ニー
566
+ オカモト
567
+ オチンコ
568
+ オチンチン
569
+ オチンポ
570
+ オッπ
571
+ オッパイ
572
+ オナ
573
+ オナ○ー
574
+ オナった
575
+ オナでん
576
+ オナる
577
+ オナろう
578
+ オナクラ
579
+ オナニ
580
+ オナニスト
581
+ オナニホール
582
+ オナニー
583
+ オナペット
584
+ オナホ
585
+ オナホール
586
+ オナロウ
587
+ オナ二
588
+ オナ写
589
+ オナ動
590
+ オナ声
591
+ オナ好
592
+ オナ画
593
+ オナ禁
594
+ オナ系
595
+ オナ電
596
+ オフパコ
597
+ オマ○コ
598
+ オマンコ
599
+ オマンマン
600
+ オメコ
601
+ オリエント工業
602
+ オルガ
603
+ オルガズム
604
+ オーガズム
605
+ オーラルセックス
606
+ オールヌード
607
+ カウパー
608
+ カウパー氏腺液
609
+ カップル喫茶
610
+ カリ頭
611
+ カント
612
+ カンノウ
613
+ ガチムチ
614
+ ガマン汁
615
+ ガンシャ
616
+ ガンメンキジョウイ
617
+ ガーターベルト
618
+ キ○タマ
619
+ キジョウイ
620
+ キチガイ
621
+ キッコウシバリ
622
+ キメオナ
623
+ キメセク
624
+ キャバクラ
625
+ キョコン
626
+ キョチン
627
+ キョニュウ
628
+ キンタマ
629
+ ク○ニ
630
+ ク●ニ
631
+ クソ
632
+ クチュクチュ
633
+ クリトリ
634
+ クリトリス
635
+ クロンボ
636
+ クンニ
637
+ クンニリングス
638
+ クン二
639
+ グチュグチュ
640
+ ケチャマン
641
+ ケツマンコ
642
+ ケツ毛
643
+ ケツ穴
644
+ コウナイハッシャ
645
+ コウビ
646
+ コウモン
647
+ コカン
648
+ コンドーム
649
+ コーマン
650
+ ゴウカン
651
+ ゴム尺
652
+ サイインザイ
653
+ サガミ
654
+ サック
655
+ サド
656
+ サノバビッチ
657
+ サンオブアビッチ
658
+ サンピー
659
+ サン・オブ・ア・ビッチ
660
+ ザーメン
661
+ シオフキ
662
+ シコる
663
+ シコシコ
664
+ シックスナイン
665
+ シット
666
+ シャブる
667
+ ショジョ
668
+ ショタ
669
+ シリガルオンナ
670
+ シーメール
671
+ ジイ
672
+ ジャップ
673
+ ジースポット
674
+ スカト□
675
+ スカトロ
676
+ スカト口
677
+ スカルファック
678
+ スカートめくり
679
+ スクリューユー
680
+ スク水
681
+ スケベ
682
+ スケベイス
683
+ スケベ椅子
684
+ ストッキング
685
+ ストリッパー
686
+ ストリップ
687
+ スパンキング
688
+ スペルマ
689
+ スマゲッチュ
690
+ スマタ
691
+ スマムビ
692
+ スラット
693
+ スワッピング
694
+ ズッコンバッ婚
695
+ ズリネタ
696
+ セ××ス
697
+ セ×クス
698
+ セ○クス
699
+ セ○レ
700
+ セ◎レ
701
+ セ●クス
702
+ セ●レ
703
+ セ❍クス
704
+ セイイン
705
+ セイエキ
706
+ セイカンマッサージ
707
+ セイキ
708
+ セイコウ
709
+ セイコウイ
710
+ セイシ
711
+ セイジョウイ
712
+ セイドレイ
713
+ セイヘキ
714
+ セイヨク
715
+ セクキャバ
716
+ セクキャブ
717
+ セクフレ
718
+ セクロス
719
+ セクース
720
+ セッ○ス
721
+ セッ●ス
722
+ セックス
723
+ セックスフレンド
724
+ セフ○
725
+ セフ◎
726
+ セフ●
727
+ セフレ
728
+ センズリ
729
+ ゼツリン
730
+ ゼンギ
731
+ ゼンシンリップ
732
+ ゼンラ
733
+ ソ○プ
734
+ ソクハメ
735
+ ソープ
736
+ ソープランド
737
+ タチバック
738
+ タチマン
739
+ タマキン
740
+ タマナメ
741
+ タンポン
742
+ ダッチ
743
+ ダッチマン
744
+ ダッチワイフ
745
+ ダンコン
746
+ チ○コ
747
+ チ○ポ
748
+ チ●コ
749
+ チ◯ポ
750
+ チクニー
751
+ チクビ
752
+ チジョクプレイ
753
+ チツ
754
+ チツガイシャセイ
755
+ チツナイシャセイ
756
+ チャH
757
+ チン○
758
+ チン●ン
759
+ チンかす
760
+ チンぐり返し
761
+ チンぽろ
762
+ チンカス
763
+ チングリ
764
+ チンゲ
765
+ チンコ
766
+ チンチン
767
+ チンピク
768
+ チンボ
769
+ チンボコ
770
+ チンポ
771
+ チンポコ
772
+ チンポロ
773
+ チンマン
774
+ チン毛
775
+ ツルマン
776
+ ティムポ
777
+ テコキ
778
+ テマン
779
+ テルH
780
+ テルエッチ
781
+ テレH
782
+ テレエッチ
783
+ テレクラ
784
+ テレフォンクラブ
785
+ テレフォンセックス
786
+ テレホンH
787
+ テレホンクラブ
788
+ テレホンクラブ "
789
+ テレホンセックス
790
+ テンガ
791
+ デ●ヘル
792
+ ディック
793
+ ディックヘッド
794
+ ディルド
795
+ ディルドー
796
+ ディープキス
797
+ ディープスロート
798
+ デカチン
799
+ デカマラ
800
+ デリ
801
+ デリバリーヘルス
802
+ デリヘル
803
+ デリ嬢
804
+ デンマ
805
+ デートクラブ
806
+ トウサツ
807
+ トップレス
808
+ トルコ嬢
809
+ トルコ風呂
810
+ ドm
811
+ ドウテイ
812
+ ナカだし
813
+ ナカダシ
814
+ ナカ出し
815
+ ナンパ
816
+ ニオウダチフェラ
817
+ ニガ
818
+ ニガー
819
+ ニクツボ
820
+ ニクベンキ
821
+ ニクボウ
822
+ ニップル
823
+ ニューハーフ
824
+ ニョイン
825
+ ニョタイモリ
826
+ ヌいて
827
+ ヌキキャバ
828
+ ヌーディスト
829
+ ノゾキベヤ
830
+ ノゾキ部屋
831
+ ノンケ
832
+ ノーパン
833
+ ノーブラ
834
+ ハ○撮り
835
+ ハイレグ
836
+ ハッテン場
837
+ ハプニング
838
+ ハプニングバ
839
+ ハプニングバー
840
+ ハミ乳
841
+ ハミ毛
842
+ ハメたい
843
+ ハメて
844
+ ハメどり
845
+ ハメまくる
846
+ ハメる
847
+ ハメドリ
848
+ ハメハメ
849
+ ハメ倒し
850
+ ハメ写メ
851
+ ハメ撮り
852
+ バイアグラ
853
+ バイブ
854
+ バイブレーター
855
+ バガー
856
+ バキュームフェラ
857
+ バクニュウ
858
+ バスタード
859
+ バター犬
860
+ バージン
861
+ パ●ティ
862
+ パイずり
863
+ パイちら
864
+ パイもみ
865
+ パイオツ
866
+ パイスラ
867
+ パイズリ
868
+ パイパン
869
+ パイ舐め
870
+ パパ活
871
+ パンちら
872
+ パンもろ
873
+ パンツ丸見え
874
+ ヒトリH
875
+ ヒトリえっち
876
+ ヒトリエッチ
877
+ ヒモパン
878
+ ヒンニュウ
879
+ ビクビク
880
+ ビッチ
881
+ ビーチク
882
+ ピ●サロ
883
+ ピス
884
+ ピストン
885
+ ピンクサロン
886
+ ピンクロータ
887
+ ピンクローター
888
+ ピンサロ
889
+ ピンサ口
890
+ フ○ラ
891
+ フ●ラ
892
+ ファッキング
893
+ ファック
894
+ ファックユー
895
+ ファッションヘルス
896
+ フィストファック
897
+ フィンガーファック
898
+ フウゾク
899
+ フェチ
900
+ フェラ
901
+ フェラチ
902
+ フェラチオ
903
+ フニャチン
904
+ フリチン
905
+ フーゾク
906
+ フードル
907
+ ブティックホテル
908
+ ブラチラ
909
+ ブルセラ
910
+ ブロージョブ
911
+ プッシー
912
+ ヘルス
913
+ ヘンタイ
914
+ ベロシャ
915
+ ベロチュー
916
+ ベロ射
917
+ ペ○ス
918
+ ペ●ス
919
+ ペッサリー
920
+ ペッティング
921
+ ペドフィリア
922
+ ペニス
923
+ ペニスバンド
924
+ ペニスリング
925
+ ペニバン
926
+ ホテトル
927
+ ホテヘル
928
+ ホンサロ
929
+ ホーリーシット
930
+ ボイン
931
+ ボッキ
932
+ ポコチン
933
+ ポルチオ
934
+ ポルノ
935
+ ポロリ
936
+ ポンビキ
937
+ ポーン
938
+ マ○コ
939
+ マ◎コ
940
+ マ●コ
941
+ マ◯コ
942
+ マ〇汁
943
+ マイクロビキニ
944
+ マイルーラ
945
+ マザーファッカー
946
+ マザーファッキング
947
+ マザーファック
948
+ マジックミラー号
949
+ マスかき
950
+ マスターベーション
951
+ マゾ
952
+ マットプレイ
953
+ マットヘルス
954
+ ママ活
955
+ マムコ
956
+ マラ
957
+ マンP
958
+ マン〇
959
+ マンかす
960
+ マンぐり返し
961
+ マンカス
962
+ マングリがえし
963
+ マングリガエシ
964
+ マングリ返し
965
+ マンゲ
966
+ マンコ
967
+ マンジル
968
+ マンスジ
969
+ マンチョ
970
+ マンチン
971
+ マン写
972
+ マン形
973
+ マン拓
974
+ マン毛
975
+ マン汁
976
+ マン臭
977
+ ミミズ千匹
978
+ ミルクタンク
979
+ ムシュウセイ
980
+ ムチムチ下半身
981
+ ムラムラ
982
+ メ○スジ
983
+ メコ○ジ
984
+ メコスジ
985
+ メコ筋
986
+ メチャシコ
987
+ モリマン
988
+ モロ出し
989
+ モロ画像
990
+ モロ見え
991
+ ヤりたい
992
+ ヤガイセックス
993
+ ヤリ×ン
994
+ ヤリちん
995
+ ヤリまん
996
+ ヤリコン
997
+ ヤリサー
998
+ ヤリチン
999
+ ヤリトモ
1000
+ ヤリマン
1001
+ ヤリモク
1002
+ ヤリ友
1003
+ ユビマン
1004
+ ユルマン
1005
+ ヨウジョ
1006
+ ライブチャット
1007
+ ラブジェル
1008
+ ラブジュース
1009
+ ラブドール
1010
+ ラブホ
1011
+ ラブホテル
1012
+ ラブホール
1013
+ ランコウ
1014
+ ランジェリーパブ
1015
+ ランパブ
1016
+ リアH
1017
+ リアルH
1018
+ リアルで
1019
+ リアルでH
1020
+ リアルエッチ
1021
+ リアルデH
1022
+ リョナ
1023
+ ルンペン
1024
+ レ○プ
1025
+ レ●プ
1026
+ レイパー
1027
+ レイプ
1028
+ レズ
1029
+ ロリ
1030
+ ロリコン
1031
+ ロリペド
1032
+ ロリータ
1033
+ ローター
1034
+ ワカメ酒
1035
+ ワキ毛
1036
+ ワギナ
1037
+ ヱロ
1038
+ ヴぁぎな
1039
+ ヴァギナ
1040
+ ヴァージン
1041
+ ㄘんㄘん
1042
+ 一人H
1043
+ 一人えっち
1044
+ 一人エッチ
1045
+ 一物
1046
+ 丁稚
1047
+ 三こすり半
1048
+ 三助
1049
+ 三所攻め
1050
+ 三角木馬
1051
+ 下乳
1052
+ 下女
1053
+ 下男
1054
+ 不倫
1055
+ 不貞
1056
+ 両刀使い
1057
+ 両刀遣い
1058
+ 中○生
1059
+ 中だし
1060
+ 中ダシ
1061
+ 中出し
1062
+ 乱パ
1063
+ 乱交
1064
+ 乳房まっさーじゃー
1065
+ 乳房マッサージャー
1066
+ 乳控
1067
+ 乳推
1068
+ 乳揺れ
1069
+ ��輪
1070
+ 乳首
1071
+ 亀甲
1072
+ 亀甲しばり
1073
+ 亀甲縛り
1074
+ 亀頭
1075
+ 二次画像
1076
+ 交差位
1077
+ 人妻
1078
+ 仁王立ちフェラ
1079
+ 会ってエッチ
1080
+ 会陰部
1081
+ 体位
1082
+ 何かっぷ
1083
+ 何カップ
1084
+ 個ちゃ
1085
+ 側位
1086
+ 側室
1087
+ 催淫
1088
+ 催淫劑
1089
+ 元気汁
1090
+ 先走り汁
1091
+ 先走り液
1092
+ 先走リ汁
1093
+ 児ぽ
1094
+ 児ポ
1095
+ 児童ぽるの
1096
+ 児童ポルノ
1097
+ 全裸
1098
+ 全身リップ
1099
+ 八の字筋
1100
+ 公開テレクラ
1101
+ 円光
1102
+ 凌辱
1103
+ 処女
1104
+ 処女膜
1105
+ 出張ヘルス
1106
+ 初夜
1107
+ 剃毛
1108
+ 前戯
1109
+ 前立腺
1110
+ 前立腺マッサージ
1111
+ 割れ目
1112
+ 勃ってる
1113
+ 勃起
1114
+ 包茎
1115
+ 千摺り
1116
+ 半乳
1117
+ 卑猥
1118
+ 即はぼ
1119
+ 即ぼん
1120
+ 即ハボ
1121
+ 即ハメ
1122
+ 即ボン
1123
+ 即尺
1124
+ 卵子
1125
+ 口まん
1126
+ 口マン
1127
+ 口交
1128
+ 口内射精
1129
+ 口内発射
1130
+ 口射
1131
+ 口暴
1132
+ 口淫
1133
+ 合法ドラッグ
1134
+ 同性愛
1135
+ 吹簫
1136
+ 周旋屋
1137
+ 和姦
1138
+ 喘ぎ
1139
+ 喘ぎ声
1140
+ 喘ぐ
1141
+ 喘げ
1142
+ 喘ギ
1143
+ 回春
1144
+ 売女
1145
+ 売春
1146
+ 壺洗い
1147
+ 处女
1148
+ 変態
1149
+ 夜這い
1150
+ 夢精
1151
+ 大人のおもちゃ
1152
+ 大人ノオモチャ
1153
+ 夫婦交換
1154
+ 女のけつ
1155
+ 女のケツ
1156
+ 女中
1157
+ 女体
1158
+ 女体もり
1159
+ 女体盛り
1160
+ 女傑
1161
+ 女給
1162
+ 女衒
1163
+ 女装
1164
+ 女陰
1165
+ 妃殿下
1166
+ 妄撮
1167
+ 妊婦とH
1168
+ 妾
1169
+ 姉妹丼
1170
+ 姦
1171
+ 姦通
1172
+ 姫始め
1173
+ 姫始メ
1174
+ 姫納め
1175
+ 姫納メ
1176
+ 娼婦
1177
+ 媚薬
1178
+ 子宮
1179
+ 官能
1180
+ 宝味
1181
+ 寝取
1182
+ 対面座位
1183
+ 射精
1184
+ 小○生
1185
+ 小児性愛
1186
+ 小陰唇
1187
+ 尺八
1188
+ 尻の穴
1189
+ 尻穴
1190
+ 屈曲位
1191
+ 屍姦
1192
+ 工□
1193
+ 工っち
1194
+ 工ろ
1195
+ 工ッチ
1196
+ 工ロ
1197
+ 工口
1198
+ 巨チン
1199
+ 巨万
1200
+ 巨乳
1201
+ 巨根
1202
+ 幼児プレイ
1203
+ 幼女
1204
+ 床上手
1205
+ 座位
1206
+ 後背位
1207
+ 得ロ
1208
+ 微乳
1209
+ 心障児
1210
+ 心障者
1211
+ 性さーびす嬢
1212
+ 性サービス嬢
1213
+ 性交
1214
+ 性器
1215
+ 性奴隷
1216
+ 性感
1217
+ 性感ヘルス
1218
+ 性感マッサージ
1219
+ 性暴力
1220
+ 性欲
1221
+ 性生活
1222
+ 性病
1223
+ 性癖
1224
+ 性的
1225
+ 性虐待
1226
+ 性行為
1227
+ 恥垢
1228
+ 恥毛
1229
+ 恥辱
1230
+ 恥部
1231
+ 恥骨
1232
+ 情夫
1233
+ 情婦
1234
+ 惨殺
1235
+ 愛奴
1236
+ 愛撫
1237
+ 愛汁
1238
+ 愛液
1239
+ 我慢汁
1240
+ 手こき
1241
+ 手でこきこき
1242
+ 手でコキコキ
1243
+ 手ぶら
1244
+ 手まん
1245
+ 手ん棒
1246
+ 手コキ
1247
+ 手マン
1248
+ 手棒
1249
+ 手淫
1250
+ 抜きキャバ
1251
+ 抜き尺
1252
+ 指まん
1253
+ 指マン
1254
+ 挿入
1255
+ 排尿
1256
+ 援 交
1257
+ 援○
1258
+ 援●
1259
+ 援コー
1260
+ 援交
1261
+ 摩羅
1262
+ 放尿
1263
+ 数の子天井
1264
+ 早漏
1265
+ 春画
1266
+ 朝勃ち
1267
+ 朝立ち
1268
+ 朝起ち
1269
+ 本さろ
1270
+ 本サロ
1271
+ 本気汁
1272
+ 松葉崩し
1273
+ 梅毒
1274
+ 欲情
1275
+ 欲求不満
1276
+ 正常位
1277
+ 死姦
1278
+ 母娘丼
1279
+ 水着居酒屋
1280
+ 汁男優
1281
+ 汚辱
1282
+ 泡姫
1283
+ 泡踊り
1284
+ 洋ピン
1285
+ 洋モノ
1286
+ 浣腸
1287
+ 海綿体
1288
+ 淋病
1289
+ 淫
1290
+ 淫ら
1291
+ 淫乱症
1292
+ 淫叫
1293
+ 淫夢
1294
+ 淫婦
1295
+ 淫慾
1296
+ 淫欲
1297
+ 淫水
1298
+ 淫液
1299
+ 淫祠
1300
+ 淫虐
1301
+ 淫語
1302
+ 淫靡
1303
+ 淫魔
1304
+ 潮吹
1305
+ 潮吹き
1306
+ 潮吹水
1307
+ 濡らす
1308
+ 濡れる
1309
+ 濡れ場
1310
+ 濡れ濡れ
1311
+ 炉利
1312
+ 無修正
1313
+ 爆乳
1314
+ 犯したい
1315
+ 犯してやる
1316
+ 犯す
1317
+ 犯る
1318
+ 犯ス
1319
+ 犯ル
1320
+ 猥褻
1321
+ 猥談
1322
+ 獣交
1323
+ 獣姦
1324
+ 獣欲
1325
+ 獸交
1326
+ 獸姦
1327
+ 玉舐め
1328
+ 玉袋
1329
+ 生H
1330
+ 生でやって
1331
+ 生でヤッて
1332
+ 生ハメ
1333
+ 生パン
1334
+ 生尺
1335
+ 生挿入
1336
+ 男女の行為
1337
+ 男根
1338
+ 痴
1339
+ 痴漢
1340
+ 発情
1341
+ 皮かぶり
1342
+ 皮被り
1343
+ 盗撮
1344
+ 着衣セックス
1345
+ 睾丸
1346
+ 短小
1347
+ 破廉恥
1348
+ 破瓜
1349
+ 神待ち
1350
+ 秘所
1351
+ 秘部
1352
+ 種付け
1353
+ 穴兄弟
1354
+ 空気人形
1355
+ 立ちばっく
1356
+ 立ちまん
1357
+ 立ちバック
1358
+ 立ちマン
1359
+ 立位
1360
+ 童貞
1361
+ 竿姉妹
1362
+ 第一ちんぽ汁
1363
+ 第一チンポ汁
1364
+ 筆おろし
1365
+ 筆下ろし
1366
+ 粗ちん
1367
+ 粗チン
1368
+ 精えき
1369
+ 精子
1370
+ 精液
1371
+ 精薄
1372
+ 精飲
1373
+ 素股
1374
+ 絶倫
1375
+ 緊縛
1376
+ 美乳
1377
+ 聖女
1378
+ 聖水
1379
+ 肉体関係
1380
+ 肉便器
1381
+ 肉壷
1382
+ 肉壺
1383
+ 肉奴隷
1384
+ 肉棒
1385
+ 肉欲
1386
+ 肛交
1387
+ 肛門
1388
+ 股間
1389
+ 胸チラ
1390
+ 脱糞
1391
+ 脳膜炎
1392
+ 膜つき
1393
+ 膣
1394
+ 自慰
1395
+ 自殺
1396
+ 興奮劑
1397
+ 舌まん
1398
+ 舌マン
1399
+ 舌入れ
1400
+ 舌技
1401
+ 花びら回転
1402
+ 菊門
1403
+ 虚乳
1404
+ 虹画像
1405
+ 虹百合
1406
+ 蜜壺
1407
+ 表日本
1408
+ 裏DVD
1409
+ 裏サイト
1410
+ 裏スジ
1411
+ 裏ビデオ
1412
+ 裏動画
1413
+ 裏本
1414
+ 裏画像
1415
+ 裏筋
1416
+ 触手
1417
+ 豊満熟女
1418
+ 貧乳
1419
+ 買春
1420
+ 赤ちゃんプレイ
1421
+ 足こき
1422
+ 足コキ
1423
+ 輪姦プレイ
1424
+ 逆援
1425
+ 遅漏
1426
+ 避妊具
1427
+ 野外SEX
1428
+ 野外セックス
1429
+ 野外プレイ
1430
+ 金玉
1431
+ 陰唇
1432
+ 陰嚢
1433
+ 陰囊
1434
+ 陰核
1435
+ 陰根
1436
+ 陰毛
1437
+ 陰茎
1438
+ 陰部
1439
+ 陵辱
1440
+ 隠し撮り
1441
+ 集団H
1442
+ 雌豚
1443
+ 電ま
1444
+ 電マ
1445
+ 電動こけし
1446
+ 電動でぃるど
1447
+ 電動オナホール
1448
+ 電動コケシ
1449
+ 電動ディルド
1450
+ 電動陰莖
1451
+ 顏射
1452
+ 顔射
1453
+ 顔面騎乗
1454
+ 顔騎
1455
+ 風俗
1456
+ 飲尿
1457
+ 騎上位
1458
+ 騎乗位
1459
+ 鬼畜
1460
+ 魔羅
1461
+ 黄金水
1462
+ 龜頭
code/e5cb5ca/src/wordlists/reference/ja_discrimination_keywords.txt ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ アイヌ系
2
+ アカ
3
+ アメ公
4
+ アル中
5
+ イカサマ
6
+ イタ公
7
+ イモ
8
+ インチキ
9
+ インディアン嘘つかない
10
+ エスキモー
11
+ エチゼンクラゲ
12
+ オカマ
13
+ オールドミス
14
+ カッペ
15
+ ガキ
16
+ ガサ
17
+ キ●ガイ
18
+ キチ
19
+ キチガ●
20
+ キチガイ
21
+ キ印
22
+ ゲンナマ
23
+ コロシ
24
+ ゴミ屋
25
+ サツ
26
+ サラ金
27
+ ザギン
28
+ シマ
29
+ ジプシー
30
+ ジャップ
31
+ ジャリ
32
+ スケ
33
+ スチュワーデス
34
+ スラム
35
+ ズージャー
36
+ タケノコ医者
37
+ ダッチマン
38
+ チビ
39
+ チャリンコ
40
+ チャンコロ
41
+ チョン
42
+ デカ
43
+ トルコ嬢
44
+ トルコ風呂
45
+ ドヤ街
46
+ ナオン
47
+ ニガー
48
+ ニグロ
49
+ ニコヨン
50
+ ノビ
51
+ バタ屋
52
+ パクる
53
+ パン助
54
+ パーマ屋
55
+ ヒモ
56
+ ブス
57
+ ブタ箱
58
+ ブツ
59
+ ブラインドタッチ
60
+ ポコペン
61
+ ポリ公
62
+ マンコ
63
+ ヤンキー
64
+ ヤー様
65
+ ヨツ
66
+ ルンペン
67
+ レントゲン技師
68
+ ロンパリ
69
+ 丁稚
70
+ 三つ口
71
+ 三助
72
+ 三国人
73
+ 三韓征伐
74
+ 上方の贅六
75
+ 下女
76
+ 下男
77
+ 不具
78
+ 不可触民
79
+ 不治の病
80
+ 中共
81
+ 乞食
82
+ 二号
83
+ 人夫
84
+ 人足
85
+ 人非人
86
+ 他力本願
87
+ 代書屋
88
+ 令嬢
89
+ 伊勢乞食
90
+ 低脳
91
+ 低脳児
92
+ 低開発国
93
+ 保母
94
+ 保線工夫
95
+ 借り腹
96
+ 健全なる精神は健全なる身体に宿る
97
+ 傴僂
98
+ 八百屋
99
+ 共稼ぎ
100
+ 処女作
101
+ 処女峰
102
+ 出戻り
103
+ 出稼ぎ
104
+ 助産婦
105
+ 労務者
106
+ 北鮮
107
+ 千摺り
108
+ ナオン
109
+ ヒモ
110
+ オールドミス
111
+ 女子供
112
+ 狂女
113
+ 下女
114
+ 下男
115
+ 女給
116
+ 女傑
117
+ 女工
118
+ 処女作
119
+ 処女峰
120
+ 女中
121
+ スケ
122
+ 端女
123
+ 醜男
124
+ 阿婆擦れ
125
+ 男のくせに
126
+ 女のくせに
127
+ 男らしく
128
+ 女らしく
129
+ 女々しい
130
+ 女だてらに
131
+ 男勝り
132
+ 紅一点
133
+ 女の腐ったような
134
+ 女の腐ったの
135
+ 売れ残り
136
+ 出戻り
137
+ めかけ
138
+ 職場の花
139
+ 二号さん
140
+ フェミナチ
141
+ あげまん
142
+ さげまん
143
+ あげちん
144
+ さげちん
145
+ まんこ
146
+ ちんこ
147
+ ビッチ
148
+ 毒女
149
+ 鬼女
150
+ ババア
code/e5cb5ca/src/wordlists/reference/ja_violence_keywords.txt ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 監禁
2
+ 生き埋め
3
+ 失血死
4
+ 死刑
5
+ はりつけ
6
+ 死ね
7
+ 恫喝
8
+ 殺人鬼
9
+ 4ね
10
+ 4ぬ
11
+ リンチ
12
+ ●す殺す
13
+ レイプ
14
+ 殺人
15
+ 暴力
16
+ 溺死
17
+ 暴言
18
+ 麻薬
19
+ 氏ね
20
+ 虐殺
21
+ パワハラ
22
+ 死ぬ
23
+ いじめ
24
+ 銃撃
25
+ 殺す
26
+ 恐喝
27
+ 蹴り
28
+ ガス室
29
+ 犯罪
30
+ 毒殺
31
+ 縊死
32
+ 武力
33
+ 処刑
34
+ 散弾銃
35
+ 腹切り
36
+ 拷問
37
+ マフィア
38
+ 薬殺
39
+ 殴る
40
+ 脅迫
41
+ 感電死
42
+ 刺殺
43
+ 根性焼き
44
+ 焼死
45
+ 射殺
46
+ 拉致
47
+ 焼き殺し
48
+ やくざ
49
+ タヒね
50
+ 殺した
51
+ 核兵器
52
+ 撲殺
53
+ ヤクザ
54
+ 絞殺
55
+ 壊す
56
+ 火あぶり
57
+ 恐怖
58
+ 皆殺し
59
+ 拳銃
60
+ 虐待
61
+ 893
62
+ イジメ
63
+ 破壊
64
+ 殴打
65
+ 火炙り
66
+ 銃殺
67
+ 罵倒
68
+ 仕返し
69
+ 危険ドラッグ
70
+ 喧嘩
71
+ 串刺し
72
+ 殺意
73
+ 流血