code 3c1a8da-dirty-bd01fd79
Browse files- code/3c1a8da-dirty-bd01fd79/src/aggregate_summaries.py +222 -0
- code/3c1a8da-dirty-bd01fd79/src/audit_report.py +239 -0
- code/3c1a8da-dirty-bd01fd79/src/blocklists/blocklist_config.json +32 -0
- code/3c1a8da-dirty-bd01fd79/src/blocklists/ja_domain_allowlist.txt +17 -0
- code/3c1a8da-dirty-bd01fd79/src/blocklists/ja_domain_token_rules.txt +6 -0
- code/3c1a8da-dirty-bd01fd79/src/blocklists/ja_domains_blocklist.txt +15 -0
- code/3c1a8da-dirty-bd01fd79/src/classify_qwen3guard.py +161 -0
- code/3c1a8da-dirty-bd01fd79/src/cooccurrence.py +136 -0
- code/3c1a8da-dirty-bd01fd79/src/doc_features.py +179 -0
- code/3c1a8da-dirty-bd01fd79/src/domain_blocklist.py +351 -0
- code/3c1a8da-dirty-bd01fd79/src/filter_noise.py +542 -0
- code/3c1a8da-dirty-bd01fd79/src/filter_pii.py +180 -0
- code/3c1a8da-dirty-bd01fd79/src/filter_toxic.py +587 -0
- code/3c1a8da-dirty-bd01fd79/src/guard_classifier.py +113 -0
- code/3c1a8da-dirty-bd01fd79/src/hf_jobs_launch.py +459 -0
- code/3c1a8da-dirty-bd01fd79/src/main_pii.py +63 -0
- code/3c1a8da-dirty-bd01fd79/src/main_toxic.py +86 -0
- code/3c1a8da-dirty-bd01fd79/src/noise/boilerplate_lines.txt +17 -0
- code/3c1a8da-dirty-bd01fd79/src/noise/llm_phrases.txt +13 -0
- code/3c1a8da-dirty-bd01fd79/src/noise/special_tokens.txt +11 -0
- code/3c1a8da-dirty-bd01fd79/src/pii_detector.py +597 -0
- code/3c1a8da-dirty-bd01fd79/src/pii_residual_check.py +195 -0
- code/3c1a8da-dirty-bd01fd79/src/quality_report.py +336 -0
- code/3c1a8da-dirty-bd01fd79/src/review_tally.py +53 -0
- code/3c1a8da-dirty-bd01fd79/src/run_guard_pass.py +314 -0
- code/3c1a8da-dirty-bd01fd79/src/run_noise_pass.py +260 -0
- code/3c1a8da-dirty-bd01fd79/src/run_shard.py +368 -0
- code/3c1a8da-dirty-bd01fd79/src/sample_for_review.py +177 -0
- code/3c1a8da-dirty-bd01fd79/src/textmatch.py +98 -0
- code/3c1a8da-dirty-bd01fd79/src/wordlists/cooccurrence/ja_howto_terms.txt +26 -0
- code/3c1a8da-dirty-bd01fd79/src/wordlists/cooccurrence/ja_illegal_object_terms.txt +31 -0
- code/3c1a8da-dirty-bd01fd79/src/wordlists/cooccurrence/ja_minor_terms.txt +23 -0
- code/3c1a8da-dirty-bd01fd79/src/wordlists/cooccurrence/ja_sexual_terms.txt +47 -0
- code/3c1a8da-dirty-bd01fd79/src/wordlists/cooccurrence/rules.json +22 -0
- code/3c1a8da-dirty-bd01fd79/src/wordlists/exclude/ja_adult_exclude.txt +17 -0
- code/3c1a8da-dirty-bd01fd79/src/wordlists/exclude/ja_crime_exclude.txt +2 -0
- code/3c1a8da-dirty-bd01fd79/src/wordlists/exclude/ja_discrimination_exclude.txt +5 -0
- code/3c1a8da-dirty-bd01fd79/src/wordlists/exclude/ja_propaganda_conspiracy_exclude.txt +2 -0
- code/3c1a8da-dirty-bd01fd79/src/wordlists/exclude/ja_spam_exclude.txt +18 -0
- code/3c1a8da-dirty-bd01fd79/src/wordlists/exclude/ja_violence_exclude.txt +26 -0
- code/3c1a8da-dirty-bd01fd79/src/wordlists/genre/genre_rules.json +52 -0
- code/3c1a8da-dirty-bd01fd79/src/wordlists/ja_adult_keywords.txt +10 -0
- code/3c1a8da-dirty-bd01fd79/src/wordlists/ja_crime_keywords.txt +54 -0
- code/3c1a8da-dirty-bd01fd79/src/wordlists/ja_discrimination_keywords.txt +11 -0
- code/3c1a8da-dirty-bd01fd79/src/wordlists/ja_propaganda_conspiracy_keywords.txt +27 -0
- code/3c1a8da-dirty-bd01fd79/src/wordlists/ja_spam_keywords.txt +52 -0
- code/3c1a8da-dirty-bd01fd79/src/wordlists/ja_violence_keywords.txt +31 -0
- code/3c1a8da-dirty-bd01fd79/src/wordlists/reference/ja_adult_keywords.txt +1462 -0
- code/3c1a8da-dirty-bd01fd79/src/wordlists/reference/ja_discrimination_keywords.txt +150 -0
- code/3c1a8da-dirty-bd01fd79/src/wordlists/reference/ja_violence_keywords.txt +73 -0
code/3c1a8da-dirty-bd01fd79/src/aggregate_summaries.py
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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, marker: str = "shard_summary.json") -> list[dict[str, Any]]:
|
| 22 |
+
return [json.loads(p.read_text(encoding="utf-8")) for p in sorted(root.rglob(marker))]
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _load_repo(repo_id: str, prefix: str, marker: str = "shard_summary.json") -> 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('/')}/**/{marker}"])
|
| 29 |
+
return _load_local(Path(local) / prefix.strip("/"), marker)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def aggregate_noise(summaries: list[dict[str, Any]]) -> dict[str, Any]:
|
| 33 |
+
"""第2パス(noise_summary.json)の集約。パターン別・項目別・理由別に合算する。"""
|
| 34 |
+
|
| 35 |
+
total = Counter()
|
| 36 |
+
by_reason = Counter()
|
| 37 |
+
by_item: dict[str, Counter] = defaultdict(Counter)
|
| 38 |
+
by_pattern: dict[str, Counter] = defaultdict(Counter)
|
| 39 |
+
pattern_meta: dict[str, dict[str, Any]] = {}
|
| 40 |
+
thresholds: Counter = Counter()
|
| 41 |
+
shards = []
|
| 42 |
+
for s in summaries:
|
| 43 |
+
shards.append(s["shard"])
|
| 44 |
+
n = s["noise"]
|
| 45 |
+
total["input_rows"] += s["input_rows"]
|
| 46 |
+
for k in ("records_deleted", "records_retained", "records_modified", "records_newline_joined", "chars_before", "chars_after_retained"):
|
| 47 |
+
total[k] += n.get(k) or 0
|
| 48 |
+
if n.get("tokens_after_retained"):
|
| 49 |
+
total["tokens_after_retained"] += n["tokens_after_retained"]
|
| 50 |
+
for k, v in n["records_deleted_by_reason"].items():
|
| 51 |
+
by_reason[k] += v
|
| 52 |
+
for item, v in n["by_item"].items():
|
| 53 |
+
for k, x in v.items():
|
| 54 |
+
by_item[item][k] += x
|
| 55 |
+
for p in n["patterns"]:
|
| 56 |
+
pattern_meta[p["id"]] = {"item": p["item"], "action": p["action"]}
|
| 57 |
+
for k in ("records_detected", "occurrences", "lines_removed", "replacements"):
|
| 58 |
+
by_pattern[p["id"]][k] += p[k]
|
| 59 |
+
thresholds[json.dumps(n["thresholds"], sort_keys=True, ensure_ascii=False)] += 1
|
| 60 |
+
return {
|
| 61 |
+
"aggregated_at_utc": datetime.now(timezone.utc).isoformat(),
|
| 62 |
+
"stage": "noise",
|
| 63 |
+
"shards": len(shards),
|
| 64 |
+
"totals": dict(total),
|
| 65 |
+
"deletion_rate": round(total["records_deleted"] / max(1, total["input_rows"]), 5),
|
| 66 |
+
"records_deleted_by_reason": dict(by_reason),
|
| 67 |
+
"by_item": {k: dict(v) for k, v in sorted(by_item.items(), key=lambda kv: int(kv[0]))},
|
| 68 |
+
"by_pattern": {k: {**pattern_meta[k], **dict(v)} for k, v in sorted(by_pattern.items(), key=lambda kv: (pattern_meta[kv[0]]["item"], kv[0]))},
|
| 69 |
+
"thresholds": [json.loads(k) for k in thresholds],
|
| 70 |
+
"shard_list": sorted(shards),
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def aggregate_guard(summaries: list[dict[str, Any]]) -> dict[str, Any]:
|
| 75 |
+
"""第3パス(guard_summary.json)の集約。候補数・分類結果・削除カテゴリ別に合算する。"""
|
| 76 |
+
|
| 77 |
+
total = Counter()
|
| 78 |
+
by_safety = Counter()
|
| 79 |
+
deleted_by_category = Counter()
|
| 80 |
+
unsafe_kept = Counter()
|
| 81 |
+
controversial = Counter()
|
| 82 |
+
match_docs = Counter()
|
| 83 |
+
thresholds: Counter = Counter()
|
| 84 |
+
seconds = Counter()
|
| 85 |
+
shards = []
|
| 86 |
+
for s in summaries:
|
| 87 |
+
shards.append(s["shard"])
|
| 88 |
+
for k in ("input_rows", "candidates", "records_deleted", "final_rows"):
|
| 89 |
+
total[k] += s.get(k) or 0
|
| 90 |
+
for k, v in (s.get("by_safety") or {}).items():
|
| 91 |
+
by_safety[k] += v
|
| 92 |
+
for k, v in (s.get("deleted_by_category") or {}).items():
|
| 93 |
+
deleted_by_category[k] += v
|
| 94 |
+
for k, v in (s.get("unsafe_kept_by_category") or {}).items():
|
| 95 |
+
unsafe_kept[k] += v
|
| 96 |
+
for k, v in (s.get("controversial_by_category") or {}).items():
|
| 97 |
+
controversial[k] += v
|
| 98 |
+
for k, v in (s.get("match_docs_by_category") or {}).items():
|
| 99 |
+
match_docs[k] += v
|
| 100 |
+
for k, v in (s.get("seconds") or {}).items():
|
| 101 |
+
seconds[k] += v
|
| 102 |
+
thresholds[json.dumps(s.get("thresholds"), sort_keys=True, ensure_ascii=False)] += 1
|
| 103 |
+
return {
|
| 104 |
+
"aggregated_at_utc": datetime.now(timezone.utc).isoformat(),
|
| 105 |
+
"stage": "guard",
|
| 106 |
+
"shards": len(shards),
|
| 107 |
+
"totals": dict(total),
|
| 108 |
+
"candidate_rate": round(total["candidates"] / max(1, total["input_rows"]), 5),
|
| 109 |
+
"deletion_rate": round(total["records_deleted"] / max(1, total["input_rows"]), 6),
|
| 110 |
+
"by_safety": dict(by_safety),
|
| 111 |
+
"deleted_by_category": dict(deleted_by_category),
|
| 112 |
+
"unsafe_kept_by_category": dict(unsafe_kept),
|
| 113 |
+
"controversial_by_category": dict(controversial),
|
| 114 |
+
"match_docs_by_category": dict(match_docs),
|
| 115 |
+
"seconds": dict(seconds),
|
| 116 |
+
"thresholds": [json.loads(k) for k in thresholds],
|
| 117 |
+
"shard_list": sorted(shards),
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def _expected_shards(repo_id: str) -> set[str]:
|
| 122 |
+
from huggingface_hub import HfApi
|
| 123 |
+
|
| 124 |
+
return {Path(p).stem for p in HfApi().list_repo_files(repo_id, repo_type="dataset") if p.endswith(".parquet")}
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def aggregate(summaries: list[dict[str, Any]]) -> dict[str, Any]:
|
| 128 |
+
total = Counter()
|
| 129 |
+
by_reason = Counter()
|
| 130 |
+
by_category_match = Counter()
|
| 131 |
+
by_category_deleted = Counter()
|
| 132 |
+
by_source_matched = Counter()
|
| 133 |
+
by_source_deleted = Counter()
|
| 134 |
+
by_rule = Counter()
|
| 135 |
+
pii_records = Counter()
|
| 136 |
+
pii_replacements = Counter()
|
| 137 |
+
seconds = Counter()
|
| 138 |
+
policies = Counter()
|
| 139 |
+
versions = Counter()
|
| 140 |
+
shards = []
|
| 141 |
+
for s in summaries:
|
| 142 |
+
shards.append(s["shard"])
|
| 143 |
+
versions[s.get("pipeline_version", "?")] += 1
|
| 144 |
+
total["input_rows"] += s["input_rows"]
|
| 145 |
+
total["toxic_deleted"] += s["toxic"]["records_deleted"]
|
| 146 |
+
total["toxic_retained"] += s["toxic"]["records_retained"]
|
| 147 |
+
total["pii_records_with_replacement"] += s["pii"]["records_with_replacement"]
|
| 148 |
+
total["pii_total_replacements"] += s["pii"]["total_replacements"]
|
| 149 |
+
total["final_rows"] += s["output"]["final_rows"]
|
| 150 |
+
for k, v in s["toxic"]["records_deleted_by_reason"].items():
|
| 151 |
+
by_reason[k] += v
|
| 152 |
+
for c, v in s["toxic"]["by_category"].items():
|
| 153 |
+
by_category_match[c] += v["records_with_match"]
|
| 154 |
+
by_category_deleted[c] += v["records_deleted"]
|
| 155 |
+
for name, v in (s["toxic"].get("domain_blocklist_by_source") or {}).items():
|
| 156 |
+
by_source_matched[name] += v.get("records_matched", 0)
|
| 157 |
+
by_source_deleted[name] += v.get("records_deleted", 0)
|
| 158 |
+
for name, v in (s["toxic"].get("cooccurrence_by_rule") or {}).items():
|
| 159 |
+
by_rule[name] += v.get("records_matched", 0)
|
| 160 |
+
for t, v in s["pii"]["by_type"].items():
|
| 161 |
+
pii_records[t] += v["records_with_match"]
|
| 162 |
+
pii_replacements[t] += v["replacement_count"]
|
| 163 |
+
for k, v in s["seconds"].items():
|
| 164 |
+
seconds[k] += v
|
| 165 |
+
p = s["pii"].get("policy") or {}
|
| 166 |
+
policies[f"{p.get('action')}|{p.get('approved_by')}|{p.get('approved_on')}|{p.get('status')}"] += 1
|
| 167 |
+
n = total["input_rows"] or 1
|
| 168 |
+
return {
|
| 169 |
+
"aggregated_at_utc": datetime.now(timezone.utc).isoformat(),
|
| 170 |
+
"shards": len(shards),
|
| 171 |
+
"pipeline_versions": dict(versions),
|
| 172 |
+
"totals": dict(total),
|
| 173 |
+
"toxic": {
|
| 174 |
+
"deletion_rate": round(total["toxic_deleted"] / n, 5),
|
| 175 |
+
"records_deleted_by_reason": dict(by_reason),
|
| 176 |
+
"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))},
|
| 177 |
+
"domain_blocklist_by_source": {k: {"records_matched": by_source_matched[k], "records_deleted": by_source_deleted[k]} for k in sorted(by_source_matched)},
|
| 178 |
+
"cooccurrence_by_rule": dict(by_rule),
|
| 179 |
+
},
|
| 180 |
+
"pii": {
|
| 181 |
+
"denominator_records": total["toxic_retained"],
|
| 182 |
+
"records_with_replacement_rate": round(total["pii_records_with_replacement"] / max(1, total["toxic_retained"]), 5),
|
| 183 |
+
"by_type": {t: {"records_with_match": pii_records[t], "replacement_count": pii_replacements[t]} for t in sorted(pii_records)},
|
| 184 |
+
"policies": dict(policies),
|
| 185 |
+
},
|
| 186 |
+
"seconds": dict(seconds),
|
| 187 |
+
"shard_list": sorted(shards),
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def main(argv: list[str] | None = None) -> None:
|
| 192 |
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 193 |
+
source = parser.add_mutually_exclusive_group(required=True)
|
| 194 |
+
source.add_argument("--root", type=Path)
|
| 195 |
+
source.add_argument("--repo")
|
| 196 |
+
parser.add_argument("--prefix", default="outputs")
|
| 197 |
+
parser.add_argument("--expected-inputs", default=None, help="入力データセット(未処理シャードの検出用)")
|
| 198 |
+
parser.add_argument("--stage", choices=("full", "noise", "guard"), default="full", help="noise: 第2パスの noise_summary.json、guard: 第3パスの guard_summary.json を集約")
|
| 199 |
+
parser.add_argument("--output", type=Path, required=True)
|
| 200 |
+
args = parser.parse_args(argv)
|
| 201 |
+
marker = {"noise": "noise_summary.json", "guard": "guard_summary.json"}.get(args.stage, "shard_summary.json")
|
| 202 |
+
summaries = _load_local(args.root, marker) if args.root else _load_repo(args.repo, args.prefix, marker)
|
| 203 |
+
result = {"noise": aggregate_noise, "guard": aggregate_guard}.get(args.stage, aggregate)(summaries)
|
| 204 |
+
if args.expected_inputs:
|
| 205 |
+
expected = _expected_shards(args.expected_inputs)
|
| 206 |
+
done = set(result["shard_list"])
|
| 207 |
+
result["completeness"] = {"expected": len(expected), "done": len(done & expected), "missing": sorted(expected - done)[:200], "missing_count": len(expected - done), "unexpected": sorted(done - expected)[:50]}
|
| 208 |
+
args.output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
| 209 |
+
t = result["totals"]
|
| 210 |
+
if args.stage == "guard":
|
| 211 |
+
print(json.dumps({"shards": result["shards"], "input_rows": t.get("input_rows"), "candidates": t.get("candidates"), "guard_deleted": t.get("records_deleted"),
|
| 212 |
+
"final_rows": t.get("final_rows"), "by_safety": result["by_safety"], "completeness": result.get("completeness", {}).get("missing_count")}, ensure_ascii=False))
|
| 213 |
+
elif args.stage == "noise":
|
| 214 |
+
print(json.dumps({"shards": result["shards"], "input_rows": t.get("input_rows"), "noise_deleted": t.get("records_deleted"), "retained": t.get("records_retained"),
|
| 215 |
+
"modified": t.get("records_modified"), "completeness": result.get("completeness", {}).get("missing_count")}, ensure_ascii=False))
|
| 216 |
+
else:
|
| 217 |
+
print(json.dumps({"shards": result["shards"], "input_rows": t.get("input_rows"), "toxic_deleted": t.get("toxic_deleted"), "final_rows": t.get("final_rows"),
|
| 218 |
+
"pii_replacements": t.get("pii_total_replacements"), "completeness": result.get("completeness", {}).get("missing_count")}, ensure_ascii=False))
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
if __name__ == "__main__":
|
| 222 |
+
main()
|
code/3c1a8da-dirty-bd01fd79/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/3c1a8da-dirty-bd01fd79/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/3c1a8da-dirty-bd01fd79/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/3c1a8da-dirty-bd01fd79/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/3c1a8da-dirty-bd01fd79/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/3c1a8da-dirty-bd01fd79/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/3c1a8da-dirty-bd01fd79/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/3c1a8da-dirty-bd01fd79/src/doc_features.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""文書特徴量(監査項目22・25〜29用)。
|
| 2 |
+
|
| 3 |
+
第2パス(``run_noise_pass.py``)で文書ごとに算出し、``features.parquet`` に書く。
|
| 4 |
+
|
| 5 |
+
* 言語判定(項目25): fastText lid.176(Facebook、CC BY-SA 3.0 のモデル)。文書先頭1,000字の判定と、
|
| 6 |
+
30字以上の行(最大50行)ごとの判定から非日本語行の比率を出す。
|
| 7 |
+
* ジャンル分類(項目29): ``wordlists/genre/genre_rules.json`` の URL 規則と手がかり語で、
|
| 8 |
+
1,000字あたりの異なり手がかり語数をスコアとし、しきい値以上で最大のジャンルを付与する。
|
| 9 |
+
製造業・重工への適合スコアは独立に記録する。
|
| 10 |
+
* 低品質フラグ(項目28): 同 JSON の定義(500字未満、記号・数字比率、行の反復、平均行長、販促定型、言語判定の低確信)。
|
| 11 |
+
* 長さ・ハッシュ(項目22・27): 文字数(入力・最終)、本文 SHA-1、URL ホスト。
|
| 12 |
+
|
| 13 |
+
fastText の python ラッパーは numpy 2 で壊れるため、C++ バインディング(``model.f.predict``)を直接使う。
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import hashlib
|
| 19 |
+
import json
|
| 20 |
+
import re
|
| 21 |
+
import statistics
|
| 22 |
+
from dataclasses import dataclass
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
from typing import Any
|
| 25 |
+
from urllib.parse import urlparse
|
| 26 |
+
|
| 27 |
+
from textmatch import compile_trie_pattern, normalize
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
FEATURE_COLUMNS = [
|
| 31 |
+
"record_index", "status", "url", "host", "perplexity",
|
| 32 |
+
"chars_input", "chars_final", "lines_final", "avg_line_len",
|
| 33 |
+
"lang", "lang_prob", "non_ja_line_ratio", "mixed_language",
|
| 34 |
+
"genre", "genre_score", "manufacturing_score",
|
| 35 |
+
"score_diary_blog", "score_affiliate", "score_game", "score_entertainment", "score_ec_product",
|
| 36 |
+
"symbol_digit_ratio", "line_repetition", "is_low_quality", "low_quality_flags",
|
| 37 |
+
"content_sha1",
|
| 38 |
+
]
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class LanguageDetector:
|
| 42 |
+
"""fastText lid.176 による言語判定。"""
|
| 43 |
+
|
| 44 |
+
def __init__(self, model_path: Path) -> None:
|
| 45 |
+
import fasttext
|
| 46 |
+
|
| 47 |
+
self.model_path = str(model_path)
|
| 48 |
+
self._model = fasttext.load_model(self.model_path)
|
| 49 |
+
|
| 50 |
+
def detect(self, text: str, max_chars: int = 1000) -> tuple[str, float]:
|
| 51 |
+
sample = text.replace("\n", " ")[:max_chars].strip()
|
| 52 |
+
if not sample:
|
| 53 |
+
return "unk", 0.0
|
| 54 |
+
out = self._model.f.predict(sample, 1, 0.0, "strict")
|
| 55 |
+
if not out:
|
| 56 |
+
return "unk", 0.0
|
| 57 |
+
prob, label = out[0]
|
| 58 |
+
return label.replace("__label__", ""), float(prob)
|
| 59 |
+
|
| 60 |
+
def line_mix(self, text: str, max_lines: int = 50, min_chars: int = 30) -> tuple[float, int]:
|
| 61 |
+
"""非日本語と判定された行の比率(対象行数も返す)。"""
|
| 62 |
+
|
| 63 |
+
lines = [line.strip() for line in text.split("\n") if len(line.strip()) >= min_chars][:max_lines]
|
| 64 |
+
if not lines:
|
| 65 |
+
return 0.0, 0
|
| 66 |
+
non_ja = sum(1 for line in lines if self.detect(line, 300)[0] != "ja")
|
| 67 |
+
return non_ja / len(lines), len(lines)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@dataclass(frozen=True)
|
| 71 |
+
class GenreRule:
|
| 72 |
+
name: str
|
| 73 |
+
label_ja: str
|
| 74 |
+
host_regex: re.Pattern[str] | None
|
| 75 |
+
host_weight: float
|
| 76 |
+
cues: re.Pattern[str]
|
| 77 |
+
cue_count: int
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class GenreClassifier:
|
| 81 |
+
def __init__(self, rules_path: Path) -> None:
|
| 82 |
+
spec = json.loads(rules_path.read_text(encoding="utf-8"))
|
| 83 |
+
self.threshold = float(spec.get("score_threshold", 2.0))
|
| 84 |
+
self.manufacturing_threshold = float(spec.get("manufacturing_threshold", 2.0))
|
| 85 |
+
self.rules: list[GenreRule] = []
|
| 86 |
+
for name, item in spec["genres"].items():
|
| 87 |
+
hosts = item.get("host_patterns") or []
|
| 88 |
+
cues = sorted({normalize(c) for c in item["cues"]}, key=lambda t: (-len(t), t))
|
| 89 |
+
self.rules.append(GenreRule(
|
| 90 |
+
name=name, label_ja=item.get("label_ja", name),
|
| 91 |
+
host_regex=re.compile("|".join(hosts), re.IGNORECASE) if hosts else None,
|
| 92 |
+
host_weight=float(item.get("host_weight", 0)),
|
| 93 |
+
cues=compile_trie_pattern(cues), cue_count=len(cues),
|
| 94 |
+
))
|
| 95 |
+
manufacturing = sorted({normalize(c) for c in spec["manufacturing"]["cues"]}, key=lambda t: (-len(t), t))
|
| 96 |
+
self.manufacturing = compile_trie_pattern(manufacturing)
|
| 97 |
+
self.low_quality_flags = spec.get("low_quality", {}).get("flags", {})
|
| 98 |
+
self.spec_summary = {
|
| 99 |
+
"rules_file": str(rules_path), "score_threshold": self.threshold, "manufacturing_threshold": self.manufacturing_threshold,
|
| 100 |
+
"genres": {r.name: {"label_ja": r.label_ja, "cues": r.cue_count, "host_weight": r.host_weight} for r in self.rules},
|
| 101 |
+
"manufacturing_cues": len(manufacturing), "low_quality_flags": self.low_quality_flags,
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
@staticmethod
|
| 105 |
+
def _distinct_per_1000(pattern: re.Pattern[str], text: str) -> float:
|
| 106 |
+
found = {m.group(0) for m in pattern.finditer(text)}
|
| 107 |
+
return len(found) / (max(len(text), 500) / 1000)
|
| 108 |
+
|
| 109 |
+
def classify(self, url: str, normalized_text: str) -> tuple[str, float, float, dict[str, float]]:
|
| 110 |
+
host = (urlparse(url).hostname or "").lower() if url else ""
|
| 111 |
+
path = (urlparse(url).path or "").lower() if url else ""
|
| 112 |
+
scores: dict[str, float] = {}
|
| 113 |
+
for rule in self.rules:
|
| 114 |
+
score = self._distinct_per_1000(rule.cues, normalized_text)
|
| 115 |
+
if rule.host_regex is not None and rule.host_weight and (rule.host_regex.search(host) or rule.host_regex.search(path)):
|
| 116 |
+
score += rule.host_weight
|
| 117 |
+
scores[rule.name] = round(score, 3)
|
| 118 |
+
manufacturing = round(self._distinct_per_1000(self.manufacturing, normalized_text), 3)
|
| 119 |
+
best = max(scores, key=scores.get) if scores else "other"
|
| 120 |
+
genre = best if scores.get(best, 0) >= self.threshold else "other"
|
| 121 |
+
return genre, scores.get(best, 0.0), manufacturing, scores
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
SYMBOL_DIGIT_RE = re.compile(r"[0-90-9\W_]")
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
class DocFeaturizer:
|
| 128 |
+
def __init__(self, rules_path: Path, lid_model_path: Path | None = None) -> None:
|
| 129 |
+
self.genres = GenreClassifier(rules_path)
|
| 130 |
+
self.lid = LanguageDetector(lid_model_path) if lid_model_path else None
|
| 131 |
+
|
| 132 |
+
def describe(self) -> dict[str, Any]:
|
| 133 |
+
return {
|
| 134 |
+
"language_detector": {"tool": "fastText lid.176", "model": self.lid.model_path if self.lid else None,
|
| 135 |
+
"doc_sample_chars": 1000, "line_min_chars": 30, "line_max": 50, "mixed_threshold": 0.3},
|
| 136 |
+
"genre_rules": self.genres.spec_summary,
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
def features(self, url: str, text: str, chars_input: int, status: str, record_index: int, perplexity: float | None = None,
|
| 140 |
+
lang: tuple[str, float] | None = None) -> dict[str, Any]:
|
| 141 |
+
text = text or ""
|
| 142 |
+
normalized = normalize(text)
|
| 143 |
+
lines = [line.strip() for line in text.split("\n") if line.strip()]
|
| 144 |
+
long_lines = [line for line in lines if len(line) >= 10]
|
| 145 |
+
avg_line = statistics.mean(len(line) for line in lines) if lines else 0.0
|
| 146 |
+
repetition = 1 - len(set(long_lines)) / len(long_lines) if long_lines else 0.0
|
| 147 |
+
stripped = text.replace("\n", "").replace(" ", "")
|
| 148 |
+
symbol_digit = len(SYMBOL_DIGIT_RE.findall(stripped)) / len(stripped) if stripped else 0.0
|
| 149 |
+
if lang is None:
|
| 150 |
+
lang = self.lid.detect(text) if self.lid else ("unk", 0.0)
|
| 151 |
+
non_ja_ratio, _ = self.lid.line_mix(text) if self.lid else (0.0, 0)
|
| 152 |
+
mixed = lang[0] == "ja" and non_ja_ratio >= 0.3
|
| 153 |
+
genre, genre_score, manufacturing, scores = self.genres.classify(url or "", normalized)
|
| 154 |
+
flags: list[str] = []
|
| 155 |
+
if len(text) < 500:
|
| 156 |
+
flags.append("short_lt500")
|
| 157 |
+
if symbol_digit > 0.30:
|
| 158 |
+
flags.append("symbol_digit_ratio_gt30")
|
| 159 |
+
if repetition > 0.30 and len(long_lines) >= 10:
|
| 160 |
+
flags.append("line_repetition_gt30")
|
| 161 |
+
if len(lines) >= 10 and avg_line < 20:
|
| 162 |
+
flags.append("avg_line_len_lt20")
|
| 163 |
+
if genre in ("affiliate", "ec_product") and genre_score >= 4.0:
|
| 164 |
+
flags.append("template_commerce")
|
| 165 |
+
if lang[1] < 0.5:
|
| 166 |
+
flags.append("low_lid_confidence")
|
| 167 |
+
return {
|
| 168 |
+
"record_index": record_index, "status": status, "url": url, "host": (urlparse(url).hostname or "") if url else "",
|
| 169 |
+
"perplexity": perplexity,
|
| 170 |
+
"chars_input": chars_input, "chars_final": len(text), "lines_final": len(lines), "avg_line_len": round(avg_line, 1),
|
| 171 |
+
"lang": lang[0], "lang_prob": round(lang[1], 3), "non_ja_line_ratio": round(non_ja_ratio, 3), "mixed_language": mixed,
|
| 172 |
+
"genre": genre, "genre_score": round(genre_score, 3), "manufacturing_score": manufacturing,
|
| 173 |
+
"score_diary_blog": scores.get("diary_blog", 0.0), "score_affiliate": scores.get("affiliate", 0.0),
|
| 174 |
+
"score_game": scores.get("game", 0.0), "score_entertainment": scores.get("entertainment", 0.0),
|
| 175 |
+
"score_ec_product": scores.get("ec_product", 0.0),
|
| 176 |
+
"symbol_digit_ratio": round(symbol_digit, 3), "line_repetition": round(repetition, 3),
|
| 177 |
+
"is_low_quality": bool(flags), "low_quality_flags": "|".join(flags),
|
| 178 |
+
"content_sha1": hashlib.sha1(text.encode("utf-8")).hexdigest() if text else "",
|
| 179 |
+
}
|
code/3c1a8da-dirty-bd01fd79/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/3c1a8da-dirty-bd01fd79/src/filter_noise.py
ADDED
|
@@ -0,0 +1,542 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""不要データ・ノイズの検出と除去(監査項目14〜21)。
|
| 2 |
+
|
| 3 |
+
文書単位の削除、行単位の削除、文字列の置換の3種類を行い、パターンごとの
|
| 4 |
+
検出文書数・出現回数・削除行数・置換回数を summary.json に記録する。
|
| 5 |
+
削除理由は優先順位で1つだけ割り当て、理由別件数の合計が総削除件数と一致する。
|
| 6 |
+
|
| 7 |
+
| 項目 | 内容 | 処理 |
|
| 8 |
+
|---|---|---|
|
| 9 |
+
| 14 | LLM 由来の回答拒否文・アシスタント口調(``noise/llm_phrases.txt``) | 文書削除 |
|
| 10 |
+
| 15 | 特殊トークン・チャットテンプレート断片(``noise/special_tokens.txt``)、制御文字・ゼロ幅文字 | 文書削除/文字除去 |
|
| 11 |
+
| 16 | base64 画像、HTML タグ、Markdown 画像リンク、URL のみの行 | 行削除・タグ除去 |
|
| 12 |
+
| 17 | 文字化け、絵文字の連続、同一記号の繰り返し | 行削除・圧縮置換・多量なら文書削除 |
|
| 13 |
+
| 18 | boilerplate(``noise/boilerplate_lines.txt``、短い行の連続) | 行削除 |
|
| 14 |
+
| 19 | 崩れた表・記号だけの行、数値の羅列だけの文書 | 行削除・文書削除 |
|
| 15 |
+
| 20 | 過剰な改行(短い行の連続、助詞・読点で終わる行) | 結合/削除/保持(``newline_policy``) |
|
| 16 |
+
| 21 | 極端に短い/長い文書 | 文書削除(文字数。トークナイザ指定時はトークン数も) |
|
| 17 |
+
|
| 18 |
+
配布元(ABEJA)が trafilatura 抽出と LightGBM 行フィルタ、100字以下除去を済ませているため
|
| 19 |
+
残存量は少ないが、監査要件(パターン一覧と件数の記録)のため自前で検出・記録する。
|
| 20 |
+
不可視文字を含む文字クラスは chr() で組み立て、ソースに直接埋め込まない。
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
from __future__ import annotations
|
| 24 |
+
|
| 25 |
+
import json
|
| 26 |
+
import re
|
| 27 |
+
import statistics
|
| 28 |
+
from collections import Counter
|
| 29 |
+
from dataclasses import dataclass, field
|
| 30 |
+
from datetime import datetime, timezone
|
| 31 |
+
from pathlib import Path
|
| 32 |
+
from typing import Any
|
| 33 |
+
|
| 34 |
+
import pyarrow as pa
|
| 35 |
+
import pyarrow.parquet as pq
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
NOISE_VERSION = "filter_noise_v1"
|
| 39 |
+
DEFAULT_MIN_CHARS = 200
|
| 40 |
+
DEFAULT_MAX_CHARS = 100_000
|
| 41 |
+
# 削除理由の優先順位。複数に該当しても最初の1つだけを理由にする。
|
| 42 |
+
DELETE_REASON_ORDER = ("llm_phrase", "special_token", "non_japanese", "mojibake_heavy", "numeric_only", "excessive_newlines", "too_short", "too_long")
|
| 43 |
+
REASON_LABELS_JA = {
|
| 44 |
+
"llm_phrase": "14 LLM 由来の回答拒否文・アシスタント口調",
|
| 45 |
+
"special_token": "15 特殊トークン・チャットテンプレート断片",
|
| 46 |
+
"non_japanese": "25 言語判定が日本語以外(fastText lid.176、確信度0.5以上)",
|
| 47 |
+
"mojibake_heavy": "17 文字化けが多い",
|
| 48 |
+
"numeric_only": "19 数値の羅列のみ",
|
| 49 |
+
"excessive_newlines": "20 過剰な改行(削除方針時)",
|
| 50 |
+
"too_short": "21 文字数が下限未満",
|
| 51 |
+
"too_long": "21 文字数が上限超過",
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _chars(*codes: int) -> str:
|
| 56 |
+
return "".join(chr(code) for code in codes)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _range(low: int, high: int) -> str:
|
| 60 |
+
return chr(low) + "-" + chr(high)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
@dataclass(frozen=True)
|
| 64 |
+
class NoisePattern:
|
| 65 |
+
id: str
|
| 66 |
+
item: int
|
| 67 |
+
action: str # delete_doc | remove_line | replace | remove_chars
|
| 68 |
+
regex: re.Pattern[str]
|
| 69 |
+
description_ja: str = ""
|
| 70 |
+
source: str = "builtin"
|
| 71 |
+
|
| 72 |
+
def describe(self) -> dict[str, Any]:
|
| 73 |
+
return {
|
| 74 |
+
"id": self.id, "item": self.item, "action": self.action,
|
| 75 |
+
"regex": self.regex.pattern.encode("unicode_escape").decode("ascii"),
|
| 76 |
+
"description_ja": self.description_ja, "source": self.source,
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _read_patterns(path: Path, item: int, action: str, flags: int, id_prefix: str) -> list[NoisePattern]:
|
| 81 |
+
patterns: list[NoisePattern] = []
|
| 82 |
+
if not path.exists():
|
| 83 |
+
return patterns
|
| 84 |
+
for number, raw in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1):
|
| 85 |
+
line = raw.strip()
|
| 86 |
+
if not line or line.startswith("#"):
|
| 87 |
+
continue
|
| 88 |
+
patterns.append(NoisePattern(f"{id_prefix}_{number:02d}", item, action, re.compile(line, flags), source=path.name))
|
| 89 |
+
return patterns
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
# --- 組み込みパターン(行・文字列レベル) --------------------------------------
|
| 93 |
+
CONTROL_CHARS_RE = re.compile("[" + _range(0x00, 0x08) + _chars(0x0B, 0x0C) + _range(0x0E, 0x1F) + chr(0x7F) + "]")
|
| 94 |
+
ZERO_WIDTH_RE = re.compile("[" + _range(0x200B, 0x200D) + _chars(0x2060, 0xFEFF) + "]")
|
| 95 |
+
BASE64_IMAGE_RE = re.compile(r"data:image/[a-z0-9.+-]+;base64,[A-Za-z0-9+/=\s]{20,}", re.IGNORECASE)
|
| 96 |
+
MD_IMAGE_RE = re.compile(r"!\[[^\]\n]*\]\([^)\n]+\)")
|
| 97 |
+
URL_ONLY_LINE_RE = re.compile(r"^\s*(?:https?://\S+\s*)+$")
|
| 98 |
+
# PII 置換のプレースホルダー(<EMAIL> 等)は HTML タグとして扱わない
|
| 99 |
+
PII_PLACEHOLDER_NAMES = "EMAIL|PHONE|ADDRESS|PERSON_NAME|PERSON_AFFILIATION|MY_NUMBER|CREDIT_CARD|BANK_ACCOUNT|PII"
|
| 100 |
+
HTML_TAG_RE = re.compile(
|
| 101 |
+
r"<(?!(?:" + PII_PLACEHOLDER_NAMES + r")>)/?[A-Za-z][A-Za-z0-9-]*(?:\s+[^<>]{0,200})?/?>|<!--.*?-->|<!DOCTYPE[^>]*>",
|
| 102 |
+
re.DOTALL,
|
| 103 |
+
)
|
| 104 |
+
# 文字化け: 置換文字、UTF-8 を Latin-1 で読んだ痕跡(ã, â€, à + 拡張ラテン)、GBK/Shift_JIS の典型的な化け文字
|
| 105 |
+
MOJIBAKE_RE = re.compile(
|
| 106 |
+
chr(0xFFFD) + "|(?:" + _chars(0xE3) + "|" + _chars(0xE2, 0x20AC) + "|" + _chars(0xC3) + ")[" + _range(0x80, 0xBF) + "]"
|
| 107 |
+
+ "|锟斤拷|縺|繧|繝|髴|蜿|荳"
|
| 108 |
+
)
|
| 109 |
+
EMOJI_RUN_RE = re.compile(
|
| 110 |
+
"((?:[" + _range(0x1F000, 0x1FAFF) + _range(0x2600, 0x27BF) + _chars(0x2B50, 0x2B55, 0x203C, 0x2049, 0x3030, 0x303D, 0x3297, 0x3299) + "]"
|
| 111 |
+
+ "[" + chr(0xFE0F) + _range(0x1F3FB, 0x1F3FF) + "]?){3,})"
|
| 112 |
+
)
|
| 113 |
+
SYMBOL_REPEAT_RE = re.compile(
|
| 114 |
+
r"([!!??・。、,,..==\-ー―─━■□●○★☆♪※**##~〜~__||//\\<><>◆◇▼▲▽△←→↑↓♥❤♡…‥])\1{9,}"
|
| 115 |
+
)
|
| 116 |
+
TABLE_RULE_LINE_RE = re.compile(r"^\s*\|?(?:\s*:?-{2,}:?\s*\|)+\s*:?-*:?\s*\|?\s*$|^\s*[||]{2,}\s*$")
|
| 117 |
+
SYMBOL_ONLY_LINE_RE = re.compile(r"^[\s\W_]{4,}$")
|
| 118 |
+
PARTICLE_END_RE = re.compile(r"[はがをにのでとへもや、,]$")
|
| 119 |
+
# 結合しない構造行: 見出し、箇条書き、番号付き、罫線、「項目: 値」「項目|値」の形
|
| 120 |
+
STRUCTURAL_LINE_RE = re.compile(r"^(?:#{1,6}\s|[-*・●○■□▪▶►◆◇]\s?|\d{1,3}[.).)]\s?|[─━―\-==_]{3,}|[^\s::||]{1,20}\s*[::||]\s*\S)")
|
| 121 |
+
SENTENCE_END_RE = re.compile(r"[。!?!?」』))\]】…]$")
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
@dataclass
|
| 125 |
+
class DocResult:
|
| 126 |
+
text: str | None
|
| 127 |
+
deleted_reason: str | None = None
|
| 128 |
+
detections: Counter = field(default_factory=Counter) # pattern_id -> occurrences
|
| 129 |
+
lines_removed: Counter = field(default_factory=Counter) # pattern_id -> lines
|
| 130 |
+
replacements: Counter = field(default_factory=Counter) # pattern_id -> replacements
|
| 131 |
+
chars_before: int = 0
|
| 132 |
+
chars_after: int = 0
|
| 133 |
+
newline_joined: bool = False
|
| 134 |
+
tokens_after: int | None = None
|
| 135 |
+
lang: str | None = None
|
| 136 |
+
lang_prob: float | None = None
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class NoiseFilter:
|
| 140 |
+
def __init__(
|
| 141 |
+
self,
|
| 142 |
+
patterns_dir: Path,
|
| 143 |
+
min_chars: int = DEFAULT_MIN_CHARS,
|
| 144 |
+
max_chars: int = DEFAULT_MAX_CHARS,
|
| 145 |
+
newline_policy: str = "join",
|
| 146 |
+
tokenizer: str | None = None,
|
| 147 |
+
min_tokens: int | None = None,
|
| 148 |
+
max_tokens: int | None = None,
|
| 149 |
+
nav_run_lines: int = 15,
|
| 150 |
+
nav_line_chars: int = 12,
|
| 151 |
+
mojibake_delete_threshold: int = 3,
|
| 152 |
+
html_strip_threshold: int = 10,
|
| 153 |
+
language_detector: Any | None = None,
|
| 154 |
+
drop_non_japanese: bool = True,
|
| 155 |
+
) -> None:
|
| 156 |
+
if newline_policy not in ("join", "delete", "keep"):
|
| 157 |
+
raise ValueError("newline_policy は join / delete / keep")
|
| 158 |
+
# 項目25: 言語判定(detect(text) -> (lang, prob) を持つオブジェクト)。日本語以外(確信度0.5以上)は削除する。
|
| 159 |
+
self.language_detector = language_detector
|
| 160 |
+
self.drop_non_japanese = drop_non_japanese
|
| 161 |
+
self.min_chars = min_chars
|
| 162 |
+
self.max_chars = max_chars
|
| 163 |
+
self.newline_policy = newline_policy
|
| 164 |
+
self.min_tokens = min_tokens
|
| 165 |
+
self.max_tokens = max_tokens
|
| 166 |
+
self.nav_run_lines = nav_run_lines
|
| 167 |
+
self.nav_line_chars = nav_line_chars
|
| 168 |
+
self.mojibake_delete_threshold = mojibake_delete_threshold
|
| 169 |
+
self.html_strip_threshold = html_strip_threshold
|
| 170 |
+
self.llm_patterns = _read_patterns(patterns_dir / "llm_phrases.txt", 14, "delete_doc", re.IGNORECASE, "llm")
|
| 171 |
+
self.token_patterns = _read_patterns(patterns_dir / "special_tokens.txt", 15, "delete_doc", re.MULTILINE, "tok")
|
| 172 |
+
self.boilerplate_patterns = _read_patterns(patterns_dir / "boilerplate_lines.txt", 18, "remove_line", re.IGNORECASE, "bp")
|
| 173 |
+
never = re.compile(r"(?!x)x")
|
| 174 |
+
self.builtin: dict[str, NoisePattern] = {
|
| 175 |
+
"control_chars": NoisePattern("control_chars", 15, "remove_chars", CONTROL_CHARS_RE, "制御文字の除去"),
|
| 176 |
+
"zero_width": NoisePattern("zero_width", 15, "remove_chars", ZERO_WIDTH_RE, "ゼロ幅文字の除去"),
|
| 177 |
+
"base64_image": NoisePattern("base64_image", 16, "replace", BASE64_IMAGE_RE, "base64 埋め込み画像の除去"),
|
| 178 |
+
"md_image": NoisePattern("md_image", 16, "replace", MD_IMAGE_RE, "Markdown 画像リンクの除去"),
|
| 179 |
+
"url_only_line": NoisePattern("url_only_line", 16, "remove_line", URL_ONLY_LINE_RE, "URL のみの行の削除"),
|
| 180 |
+
"html_tags": NoisePattern("html_tags", 16, "replace", HTML_TAG_RE, f"HTML タグ(文書内に{html_strip_threshold}個以上ある場合に除去)"),
|
| 181 |
+
"mojibake": NoisePattern("mojibake", 17, "remove_line", MOJIBAKE_RE, f"文字化け(行削除。{mojibake_delete_threshold}箇所以上なら文書削除)"),
|
| 182 |
+
"emoji_run": NoisePattern("emoji_run", 17, "replace", EMOJI_RUN_RE, "絵文字3個以上の連続を1個に圧縮"),
|
| 183 |
+
"symbol_repeat": NoisePattern("symbol_repeat", 17, "replace", SYMBOL_REPEAT_RE, "同一記号10個以上の連続を3個に圧縮"),
|
| 184 |
+
"nav_run": NoisePattern("nav_run", 18, "remove_line", never, f"{nav_line_chars}字以下の行が{nav_run_lines}行以上連続する塊(ナビ・目次)の削除"),
|
| 185 |
+
"table_rule_line": NoisePattern("table_rule_line", 19, "remove_line", TABLE_RULE_LINE_RE, "表の罫線だけの行の削除"),
|
| 186 |
+
"symbol_only_line": NoisePattern("symbol_only_line", 19, "remove_line", SYMBOL_ONLY_LINE_RE, "記号だけの行の削除"),
|
| 187 |
+
"numeric_only": NoisePattern("numeric_only", 19, "delete_doc", never, "英数字の6割超が数字の文書を削除"),
|
| 188 |
+
"excessive_newlines": NoisePattern("excessive_newlines", 20, "replace", never, f"過剰な改行(平均行長18字未満かつ10行以上、または助詞・読点で終わる行が3割超)。方針: {newline_policy}"),
|
| 189 |
+
"non_japanese": NoisePattern("non_japanese", 25, "delete_doc", never, "言語判定が日本語以外(fastText lid.176、確信度0.5以上)の文書を削除"),
|
| 190 |
+
}
|
| 191 |
+
self._tokenizer = None
|
| 192 |
+
self.tokenizer_name = tokenizer
|
| 193 |
+
if tokenizer:
|
| 194 |
+
from transformers import AutoTokenizer
|
| 195 |
+
|
| 196 |
+
self._tokenizer = AutoTokenizer.from_pretrained(tokenizer)
|
| 197 |
+
|
| 198 |
+
def pattern_list(self) -> list[dict[str, Any]]:
|
| 199 |
+
items = [p.describe() for p in self.llm_patterns + self.token_patterns + self.boilerplate_patterns]
|
| 200 |
+
items += [p.describe() for p in self.builtin.values()]
|
| 201 |
+
return items
|
| 202 |
+
|
| 203 |
+
def thresholds(self) -> dict[str, Any]:
|
| 204 |
+
return {
|
| 205 |
+
"min_chars": self.min_chars, "max_chars": self.max_chars,
|
| 206 |
+
"tokenizer": self.tokenizer_name, "min_tokens": self.min_tokens, "max_tokens": self.max_tokens,
|
| 207 |
+
"newline_policy": self.newline_policy, "nav_run_lines": self.nav_run_lines, "nav_line_chars": self.nav_line_chars,
|
| 208 |
+
"mojibake_delete_threshold": self.mojibake_delete_threshold, "html_strip_threshold": self.html_strip_threshold,
|
| 209 |
+
"language_detector": getattr(self.language_detector, "model_path", None), "drop_non_japanese": self.drop_non_japanese and self.language_detector is not None,
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
def process(self, text: Any) -> DocResult:
|
| 213 |
+
result = DocResult(text=None)
|
| 214 |
+
original = "" if text is None else str(text)
|
| 215 |
+
result.chars_before = len(original)
|
| 216 |
+
work = original
|
| 217 |
+
|
| 218 |
+
# 15: 制御文字・ゼロ幅文字
|
| 219 |
+
for pid in ("control_chars", "zero_width"):
|
| 220 |
+
work, n = self.builtin[pid].regex.subn("", work)
|
| 221 |
+
if n:
|
| 222 |
+
result.detections[pid] += n
|
| 223 |
+
result.replacements[pid] += n
|
| 224 |
+
|
| 225 |
+
# 14/15: 文書削除パターン(検出は全て数え、理由は優先順位で決める)
|
| 226 |
+
reasons: list[str] = []
|
| 227 |
+
for pattern in self.llm_patterns:
|
| 228 |
+
n = len(pattern.regex.findall(work))
|
| 229 |
+
if n:
|
| 230 |
+
result.detections[pattern.id] += n
|
| 231 |
+
reasons.append("llm_phrase")
|
| 232 |
+
for pattern in self.token_patterns:
|
| 233 |
+
n = len(pattern.regex.findall(work))
|
| 234 |
+
if n:
|
| 235 |
+
result.detections[pattern.id] += n
|
| 236 |
+
reasons.append("special_token")
|
| 237 |
+
|
| 238 |
+
# 17: 文字化け
|
| 239 |
+
mojibake_hits = len(MOJIBAKE_RE.findall(work))
|
| 240 |
+
if mojibake_hits:
|
| 241 |
+
result.detections["mojibake"] += mojibake_hits
|
| 242 |
+
if mojibake_hits >= self.mojibake_delete_threshold:
|
| 243 |
+
reasons.append("mojibake_heavy")
|
| 244 |
+
|
| 245 |
+
# 16: base64 画像・Markdown 画像・HTML タグ
|
| 246 |
+
for pid in ("base64_image", "md_image"):
|
| 247 |
+
work, n = self.builtin[pid].regex.subn(" ", work)
|
| 248 |
+
if n:
|
| 249 |
+
result.detections[pid] += n
|
| 250 |
+
result.replacements[pid] += n
|
| 251 |
+
tag_count = len(HTML_TAG_RE.findall(work))
|
| 252 |
+
if tag_count:
|
| 253 |
+
result.detections["html_tags"] += tag_count
|
| 254 |
+
if tag_count >= self.html_strip_threshold:
|
| 255 |
+
work, n = HTML_TAG_RE.subn(" ", work)
|
| 256 |
+
result.replacements["html_tags"] += n
|
| 257 |
+
|
| 258 |
+
# 17: 絵文字・記号の連続を圧縮
|
| 259 |
+
work, n = EMOJI_RUN_RE.subn(lambda m: m.group(1)[:1], work)
|
| 260 |
+
if n:
|
| 261 |
+
result.detections["emoji_run"] += n
|
| 262 |
+
result.replacements["emoji_run"] += n
|
| 263 |
+
work, n = SYMBOL_REPEAT_RE.subn(lambda m: m.group(1) * 3, work)
|
| 264 |
+
if n:
|
| 265 |
+
result.detections["symbol_repeat"] += n
|
| 266 |
+
result.replacements["symbol_repeat"] += n
|
| 267 |
+
|
| 268 |
+
# 行単位の削除(16/17/18/19)
|
| 269 |
+
kept: list[str] = []
|
| 270 |
+
for line in work.split("\n"):
|
| 271 |
+
stripped = line.strip()
|
| 272 |
+
if not stripped:
|
| 273 |
+
kept.append(line)
|
| 274 |
+
continue
|
| 275 |
+
removed_by: str | None = None
|
| 276 |
+
if URL_ONLY_LINE_RE.match(line):
|
| 277 |
+
removed_by = "url_only_line"
|
| 278 |
+
elif mojibake_hits and MOJIBAKE_RE.search(line):
|
| 279 |
+
removed_by = "mojibake"
|
| 280 |
+
elif TABLE_RULE_LINE_RE.match(line):
|
| 281 |
+
removed_by = "table_rule_line"
|
| 282 |
+
elif SYMBOL_ONLY_LINE_RE.match(line):
|
| 283 |
+
removed_by = "symbol_only_line"
|
| 284 |
+
else:
|
| 285 |
+
for pattern in self.boilerplate_patterns:
|
| 286 |
+
if pattern.regex.search(line):
|
| 287 |
+
removed_by = pattern.id
|
| 288 |
+
break
|
| 289 |
+
if removed_by:
|
| 290 |
+
result.detections[removed_by] += 1
|
| 291 |
+
result.lines_removed[removed_by] += 1
|
| 292 |
+
else:
|
| 293 |
+
kept.append(line)
|
| 294 |
+
kept = self._remove_nav_runs(kept, result)
|
| 295 |
+
work = re.sub(r"\n{3,}", "\n\n", "\n".join(kept)).strip()
|
| 296 |
+
|
| 297 |
+
# 19: 数値の羅列のみ
|
| 298 |
+
alnum = sum(c.isalnum() for c in work)
|
| 299 |
+
digits = sum(c.isdigit() for c in work)
|
| 300 |
+
if alnum >= 50 and digits / alnum > 0.6:
|
| 301 |
+
result.detections["numeric_only"] += 1
|
| 302 |
+
reasons.append("numeric_only")
|
| 303 |
+
|
| 304 |
+
# 20: 過剰な改行
|
| 305 |
+
if self._has_excessive_newlines(work):
|
| 306 |
+
result.detections["excessive_newlines"] += 1
|
| 307 |
+
if self.newline_policy == "join":
|
| 308 |
+
work = self._join_lines(work)
|
| 309 |
+
result.replacements["excessive_newlines"] += 1
|
| 310 |
+
result.newline_joined = True
|
| 311 |
+
elif self.newline_policy == "delete":
|
| 312 |
+
reasons.append("excessive_newlines")
|
| 313 |
+
|
| 314 |
+
# 25: 言語判定(整形後の本文で判定)
|
| 315 |
+
if self.language_detector is not None:
|
| 316 |
+
lang, prob = self.language_detector.detect(work)
|
| 317 |
+
result.lang, result.lang_prob = lang, prob
|
| 318 |
+
if self.drop_non_japanese and lang != "ja" and prob >= 0.5:
|
| 319 |
+
result.detections["non_japanese"] += 1
|
| 320 |
+
reasons.append("non_japanese")
|
| 321 |
+
|
| 322 |
+
# 21: 長さ
|
| 323 |
+
result.chars_after = len(work)
|
| 324 |
+
if result.chars_after < self.min_chars:
|
| 325 |
+
reasons.append("too_short")
|
| 326 |
+
elif result.chars_after > self.max_chars:
|
| 327 |
+
reasons.append("too_long")
|
| 328 |
+
if self._tokenizer is not None and "too_short" not in reasons and "too_long" not in reasons:
|
| 329 |
+
tokens = len(self._tokenizer.encode(work, add_special_tokens=False))
|
| 330 |
+
result.tokens_after = tokens
|
| 331 |
+
if self.min_tokens is not None and tokens < self.min_tokens:
|
| 332 |
+
reasons.append("too_short")
|
| 333 |
+
elif self.max_tokens is not None and tokens > self.max_tokens:
|
| 334 |
+
reasons.append("too_long")
|
| 335 |
+
|
| 336 |
+
for reason in DELETE_REASON_ORDER:
|
| 337 |
+
if reason in reasons:
|
| 338 |
+
result.deleted_reason = reason
|
| 339 |
+
return result
|
| 340 |
+
result.text = work
|
| 341 |
+
return result
|
| 342 |
+
|
| 343 |
+
def _remove_nav_runs(self, lines: list[str], result: DocResult) -> list[str]:
|
| 344 |
+
kept: list[str] = []
|
| 345 |
+
run: list[str] = []
|
| 346 |
+
|
| 347 |
+
def flush() -> None:
|
| 348 |
+
# 助詞・読点・句点で終わる行が2割以上ある塊は文の断片(項目20の対象)なので、ナビとして消さない
|
| 349 |
+
fragment_like = sum(1 for line in run if PARTICLE_END_RE.search(line.strip()) or line.strip().endswith(("。", "、", "!", "?")))
|
| 350 |
+
if len(run) >= self.nav_run_lines and fragment_like < 0.2 * len(run):
|
| 351 |
+
result.detections["nav_run"] += 1
|
| 352 |
+
result.lines_removed["nav_run"] += len(run)
|
| 353 |
+
else:
|
| 354 |
+
kept.extend(run)
|
| 355 |
+
run.clear()
|
| 356 |
+
|
| 357 |
+
for line in lines:
|
| 358 |
+
stripped = line.strip()
|
| 359 |
+
if stripped and len(stripped) <= self.nav_line_chars:
|
| 360 |
+
run.append(line)
|
| 361 |
+
else:
|
| 362 |
+
flush()
|
| 363 |
+
kept.append(line)
|
| 364 |
+
flush()
|
| 365 |
+
return kept
|
| 366 |
+
|
| 367 |
+
def _has_excessive_newlines(self, text: str) -> bool:
|
| 368 |
+
lines = [line.strip() for line in text.split("\n") if line.strip()]
|
| 369 |
+
if len(lines) < 10:
|
| 370 |
+
return False
|
| 371 |
+
average = statistics.mean(len(line) for line in lines)
|
| 372 |
+
particle = sum(1 for line in lines if PARTICLE_END_RE.search(line)) / len(lines)
|
| 373 |
+
return average < 18 or particle > 0.3
|
| 374 |
+
|
| 375 |
+
@staticmethod
|
| 376 |
+
def _join_lines(text: str) -> str:
|
| 377 |
+
"""文末記号で終わらない短い行を次の行と結合する。段落(空行)は保つ。
|
| 378 |
+
|
| 379 |
+
見出し(#)、箇条書き(-・*、番号)、罫線、コロン付きの項目行は結合の対象にも
|
| 380 |
+
結合先にもしない。仕様書の項目リストや見出しを1行に潰さないため。
|
| 381 |
+
"""
|
| 382 |
+
|
| 383 |
+
output: list[str] = []
|
| 384 |
+
buffer = ""
|
| 385 |
+
for line in text.split("\n"):
|
| 386 |
+
stripped = line.strip()
|
| 387 |
+
if not stripped:
|
| 388 |
+
if buffer:
|
| 389 |
+
output.append(buffer)
|
| 390 |
+
buffer = ""
|
| 391 |
+
output.append("")
|
| 392 |
+
continue
|
| 393 |
+
structural = STRUCTURAL_LINE_RE.match(stripped) is not None
|
| 394 |
+
can_extend = (
|
| 395 |
+
buffer
|
| 396 |
+
and not structural
|
| 397 |
+
and not STRUCTURAL_LINE_RE.match(buffer)
|
| 398 |
+
and not SENTENCE_END_RE.search(buffer)
|
| 399 |
+
and len(buffer) <= 40
|
| 400 |
+
)
|
| 401 |
+
if can_extend:
|
| 402 |
+
buffer += stripped
|
| 403 |
+
else:
|
| 404 |
+
if buffer:
|
| 405 |
+
output.append(buffer)
|
| 406 |
+
buffer = stripped
|
| 407 |
+
if buffer:
|
| 408 |
+
output.append(buffer)
|
| 409 |
+
return re.sub(r"\n{3,}", "\n\n", "\n".join(output)).strip()
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
def json_safe(value: Any) -> Any:
|
| 413 |
+
if value is None or isinstance(value, (str, int, bool)):
|
| 414 |
+
return value
|
| 415 |
+
if isinstance(value, float):
|
| 416 |
+
return value if value == value and abs(value) != float("inf") else None
|
| 417 |
+
if isinstance(value, (list, tuple)):
|
| 418 |
+
return [json_safe(item) for item in value]
|
| 419 |
+
if isinstance(value, dict):
|
| 420 |
+
return {str(key): json_safe(item) for key, item in value.items()}
|
| 421 |
+
return str(value)
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
def run_noise_filter(
|
| 425 |
+
input_path: Path,
|
| 426 |
+
output_dir: Path,
|
| 427 |
+
noise_filter: NoiseFilter,
|
| 428 |
+
batch_size: int = 2048,
|
| 429 |
+
output_name: str | None = None,
|
| 430 |
+
examples_per_pattern: int = 3,
|
| 431 |
+
on_record: Any | None = None,
|
| 432 |
+
) -> dict[str, Any]:
|
| 433 |
+
"""parquet を読み、クリーン済み parquet・removed.jsonl・summary.json を書く。
|
| 434 |
+
|
| 435 |
+
``on_record(row, result, record_index)`` を渡すと、文書ごとに呼ばれる(特徴量の算出用)。
|
| 436 |
+
"""
|
| 437 |
+
|
| 438 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 439 |
+
parquet = pq.ParquetFile(input_path)
|
| 440 |
+
schema = parquet.schema_arrow
|
| 441 |
+
cleaned_path = output_dir / (output_name or "noise_cleaned.parquet")
|
| 442 |
+
removed_path = output_dir / "removed.jsonl"
|
| 443 |
+
writer = pq.ParquetWriter(cleaned_path, schema, compression="zstd")
|
| 444 |
+
removed_handle = removed_path.open("w", encoding="utf-8", newline="\n")
|
| 445 |
+
scanned_at = datetime.now(timezone.utc).isoformat()
|
| 446 |
+
detections_docs: Counter = Counter()
|
| 447 |
+
detections_occ: Counter = Counter()
|
| 448 |
+
lines_removed: Counter = Counter()
|
| 449 |
+
replacements: Counter = Counter()
|
| 450 |
+
deleted_by_reason: Counter = Counter()
|
| 451 |
+
examples: dict[str, list[dict[str, Any]]] = {}
|
| 452 |
+
totals: Counter = Counter()
|
| 453 |
+
record_index = 0
|
| 454 |
+
try:
|
| 455 |
+
for batch in parquet.iter_batches(batch_size=batch_size):
|
| 456 |
+
rows = batch.to_pylist()
|
| 457 |
+
kept_rows: list[dict[str, Any]] = []
|
| 458 |
+
for row in rows:
|
| 459 |
+
result = noise_filter.process(row.get("content"))
|
| 460 |
+
if on_record is not None:
|
| 461 |
+
on_record(row, result, record_index)
|
| 462 |
+
totals["records_scanned"] += 1
|
| 463 |
+
totals["chars_before"] += result.chars_before
|
| 464 |
+
for pid, n in result.detections.items():
|
| 465 |
+
detections_docs[pid] += 1
|
| 466 |
+
detections_occ[pid] += n
|
| 467 |
+
if len(examples.setdefault(pid, [])) < examples_per_pattern:
|
| 468 |
+
examples[pid].append({"record_index": record_index, "url": json_safe(row.get("url")), "occurrences": n})
|
| 469 |
+
for pid, n in result.lines_removed.items():
|
| 470 |
+
lines_removed[pid] += n
|
| 471 |
+
for pid, n in result.replacements.items():
|
| 472 |
+
replacements[pid] += n
|
| 473 |
+
if result.newline_joined:
|
| 474 |
+
totals["records_newline_joined"] += 1
|
| 475 |
+
if result.deleted_reason:
|
| 476 |
+
totals["records_deleted"] += 1
|
| 477 |
+
deleted_by_reason[result.deleted_reason] += 1
|
| 478 |
+
removed_handle.write(json.dumps({
|
| 479 |
+
"record_index": record_index,
|
| 480 |
+
"url": json_safe(row.get("url")),
|
| 481 |
+
"_noise_deleted_reason": result.deleted_reason,
|
| 482 |
+
"_noise_deleted_reason_ja": REASON_LABELS_JA[result.deleted_reason],
|
| 483 |
+
"_noise_detections": dict(result.detections),
|
| 484 |
+
"_noise_chars_before": result.chars_before,
|
| 485 |
+
"_noise_chars_after": result.chars_after,
|
| 486 |
+
"content_head": json_safe((row.get("content") or "")[:300]),
|
| 487 |
+
}, ensure_ascii=False, separators=(",", ":")) + "\n")
|
| 488 |
+
else:
|
| 489 |
+
totals["records_retained"] += 1
|
| 490 |
+
totals["chars_after"] += result.chars_after
|
| 491 |
+
if result.tokens_after is not None:
|
| 492 |
+
totals["tokens_after"] += result.tokens_after
|
| 493 |
+
if result.text != (row.get("content") or ""):
|
| 494 |
+
totals["records_modified"] += 1
|
| 495 |
+
output_row = dict(row)
|
| 496 |
+
if "content" in output_row:
|
| 497 |
+
output_row["content"] = result.text
|
| 498 |
+
kept_rows.append(output_row)
|
| 499 |
+
record_index += 1
|
| 500 |
+
if kept_rows:
|
| 501 |
+
writer.write_table(pa.Table.from_pylist(kept_rows, schema=schema))
|
| 502 |
+
finally:
|
| 503 |
+
writer.close()
|
| 504 |
+
removed_handle.close()
|
| 505 |
+
pattern_rows = []
|
| 506 |
+
for spec in noise_filter.pattern_list():
|
| 507 |
+
pid = spec["id"]
|
| 508 |
+
pattern_rows.append({
|
| 509 |
+
**spec, "records_detected": detections_docs[pid], "occurrences": detections_occ[pid],
|
| 510 |
+
"lines_removed": lines_removed[pid], "replacements": replacements[pid], "examples": examples.get(pid, []),
|
| 511 |
+
})
|
| 512 |
+
by_item: dict[int, dict[str, int]] = {}
|
| 513 |
+
for row in pattern_rows:
|
| 514 |
+
entry = by_item.setdefault(row["item"], {"records_detected_sum": 0, "occurrences": 0, "lines_removed": 0, "replacements": 0})
|
| 515 |
+
entry["records_detected_sum"] += row["records_detected"]
|
| 516 |
+
entry["occurrences"] += row["occurrences"]
|
| 517 |
+
entry["lines_removed"] += row["lines_removed"]
|
| 518 |
+
entry["replacements"] += row["replacements"]
|
| 519 |
+
summary = {
|
| 520 |
+
"filter_mode": NOISE_VERSION,
|
| 521 |
+
"source_file": str(input_path),
|
| 522 |
+
"scanned_at_utc": scanned_at,
|
| 523 |
+
"thresholds": noise_filter.thresholds(),
|
| 524 |
+
"delete_reason_order": list(DELETE_REASON_ORDER),
|
| 525 |
+
"records_scanned": totals["records_scanned"],
|
| 526 |
+
"records_deleted": totals["records_deleted"],
|
| 527 |
+
"records_retained": totals["records_retained"],
|
| 528 |
+
"records_modified": totals["records_modified"],
|
| 529 |
+
"records_newline_joined": totals["records_newline_joined"],
|
| 530 |
+
"records_deleted_by_reason": {reason: deleted_by_reason[reason] for reason in DELETE_REASON_ORDER},
|
| 531 |
+
"records_deleted_by_reason_ja": {REASON_LABELS_JA[reason]: deleted_by_reason[reason] for reason in DELETE_REASON_ORDER},
|
| 532 |
+
"chars_before": totals["chars_before"],
|
| 533 |
+
"chars_after_retained": totals["chars_after"],
|
| 534 |
+
"tokens_after_retained": totals["tokens_after"] if noise_filter.tokenizer_name else None,
|
| 535 |
+
"by_item": {str(key): value for key, value in sorted(by_item.items())},
|
| 536 |
+
"patterns": pattern_rows,
|
| 537 |
+
"cleaned_parquet": str(cleaned_path),
|
| 538 |
+
"removed_jsonl": str(removed_path),
|
| 539 |
+
"note_ja": "削除理由は優先順位(14 LLM → 15 特殊トークン → 25 非日本語 → 17 文字化け → 19 数値のみ → 20 改行 → 21 長さ)で1つだけ割り当てる。行削除・置換は保持文書にも適用される。",
|
| 540 |
+
}
|
| 541 |
+
(output_dir / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
| 542 |
+
return summary
|
code/3c1a8da-dirty-bd01fd79/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/3c1a8da-dirty-bd01fd79/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/3c1a8da-dirty-bd01fd79/src/guard_classifier.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Qwen3Guard-Gen をバッチ推論するバックエンド(第3パス用)。
|
| 2 |
+
|
| 3 |
+
vLLM(GPU、既定)と transformers(左パディングの一括生成)を選べる。出力は
|
| 4 |
+
``Safety: Safe|Unsafe|Controversial`` と ``Categories: ...`` を含む短い文字列で、
|
| 5 |
+
``parse`` が安全性ラベルとカテゴリ名の一覧に分解する。
|
| 6 |
+
|
| 7 |
+
テスト用に ``FakeBackend`` を用意する(``marker`` を含む本文を Unsafe と判定する)。
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import re
|
| 13 |
+
from typing import Any
|
| 14 |
+
|
| 15 |
+
DEFAULT_MODEL = "Qwen/Qwen3Guard-Gen-0.6B"
|
| 16 |
+
SAFETY_RE = re.compile(r"Safety:\s*(Safe|Unsafe|Controversial)", re.I)
|
| 17 |
+
CATEGORY_NAMES = (
|
| 18 |
+
"Violent", "Non-violent Illegal Acts", "Sexual Content or Sexual Acts", "PII", "Suicide & Self-Harm",
|
| 19 |
+
"Unethical Acts", "Politically Sensitive Topics", "Copyright Violation", "Jailbreak",
|
| 20 |
+
)
|
| 21 |
+
CATEGORY_RE = re.compile("|".join(re.escape(name) for name in CATEGORY_NAMES), re.I)
|
| 22 |
+
CANONICAL = {name.lower(): name for name in CATEGORY_NAMES}
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def parse(raw: str) -> tuple[str | None, list[str]]:
|
| 26 |
+
"""モデル出力から (安全性ラベル, カテゴリ一覧) を取り出す。取れなければ (None, [])。"""
|
| 27 |
+
|
| 28 |
+
match = SAFETY_RE.search(raw or "")
|
| 29 |
+
categories = sorted({CANONICAL[m.lower()] for m in CATEGORY_RE.findall(raw or "")})
|
| 30 |
+
return (match.group(1).title() if match else None), categories
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class VllmBackend:
|
| 34 |
+
def __init__(self, model: str = DEFAULT_MODEL, max_chars: int = 2000, gpu_memory_utilization: float = 0.85, max_model_len: int = 4096) -> None:
|
| 35 |
+
from transformers import AutoTokenizer
|
| 36 |
+
from vllm import LLM, SamplingParams
|
| 37 |
+
|
| 38 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model)
|
| 39 |
+
self.llm = LLM(model=model, gpu_memory_utilization=gpu_memory_utilization, max_model_len=max_model_len, enable_prefix_caching=True)
|
| 40 |
+
self.params = SamplingParams(max_tokens=48, temperature=0.0)
|
| 41 |
+
self.model = model
|
| 42 |
+
self.max_chars = max_chars
|
| 43 |
+
|
| 44 |
+
def classify(self, texts: list[str]) -> list[str]:
|
| 45 |
+
prompts = [self.tokenizer.apply_chat_template([{"role": "user", "content": t[: self.max_chars]}], tokenize=False) for t in texts]
|
| 46 |
+
outputs = self.llm.generate(prompts, self.params, use_tqdm=False)
|
| 47 |
+
return [o.outputs[0].text for o in outputs]
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class TransformersBackend:
|
| 51 |
+
def __init__(self, model: str = DEFAULT_MODEL, max_chars: int = 2000, device: str = "auto", batch_size: int = 8) -> None:
|
| 52 |
+
import torch
|
| 53 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 54 |
+
|
| 55 |
+
self.torch = torch
|
| 56 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model)
|
| 57 |
+
self.tokenizer.padding_side = "left"
|
| 58 |
+
if self.tokenizer.pad_token is None:
|
| 59 |
+
self.tokenizer.pad_token = self.tokenizer.eos_token
|
| 60 |
+
kwargs: dict[str, Any] = {"device_map": "auto"} if device == "auto" else {}
|
| 61 |
+
try:
|
| 62 |
+
self.model = AutoModelForCausalLM.from_pretrained(model, dtype="auto", **kwargs)
|
| 63 |
+
except TypeError:
|
| 64 |
+
self.model = AutoModelForCausalLM.from_pretrained(model, torch_dtype="auto", **kwargs)
|
| 65 |
+
if device != "auto":
|
| 66 |
+
self.model = self.model.to(device)
|
| 67 |
+
self.model.eval()
|
| 68 |
+
self.max_chars = max_chars
|
| 69 |
+
self.batch_size = batch_size
|
| 70 |
+
|
| 71 |
+
def classify(self, texts: list[str]) -> list[str]:
|
| 72 |
+
results: list[str] = []
|
| 73 |
+
for start in range(0, len(texts), self.batch_size):
|
| 74 |
+
chunk = texts[start : start + self.batch_size]
|
| 75 |
+
prompts = [self.tokenizer.apply_chat_template([{"role": "user", "content": t[: self.max_chars]}], tokenize=False) for t in chunk]
|
| 76 |
+
inputs = self.tokenizer(prompts, return_tensors="pt", padding=True).to(self.model.device)
|
| 77 |
+
with self.torch.no_grad():
|
| 78 |
+
generated = self.model.generate(**inputs, max_new_tokens=48, do_sample=False, pad_token_id=self.tokenizer.pad_token_id)
|
| 79 |
+
new_tokens = generated[:, inputs["input_ids"].shape[1]:]
|
| 80 |
+
results.extend(self.tokenizer.batch_decode(new_tokens, skip_special_tokens=True))
|
| 81 |
+
return results
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class FakeBackend:
|
| 85 |
+
"""テスト用。``marker`` を含む本文を Unsafe(``category``)、``controversial_marker`` を含む本文を Controversial とする。"""
|
| 86 |
+
|
| 87 |
+
def __init__(self, marker: str = "UNSAFE_MARKER", category: str = "Sexual Content or Sexual Acts", controversial_marker: str = "CONTRO_MARKER") -> None:
|
| 88 |
+
self.marker = marker
|
| 89 |
+
self.category = category
|
| 90 |
+
self.controversial_marker = controversial_marker
|
| 91 |
+
self.calls = 0
|
| 92 |
+
|
| 93 |
+
def classify(self, texts: list[str]) -> list[str]:
|
| 94 |
+
self.calls += 1
|
| 95 |
+
out = []
|
| 96 |
+
for text in texts:
|
| 97 |
+
if self.marker in text:
|
| 98 |
+
out.append(f"Safety: Unsafe\nCategories: {self.category}")
|
| 99 |
+
elif self.controversial_marker in text:
|
| 100 |
+
out.append("Safety: Controversial\nCategories: Politically Sensitive Topics")
|
| 101 |
+
else:
|
| 102 |
+
out.append("Safety: Safe\nCategories: None")
|
| 103 |
+
return out
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def make_backend(name: str, model: str = DEFAULT_MODEL, max_chars: int = 2000, device: str = "auto") -> Any:
|
| 107 |
+
if name == "vllm":
|
| 108 |
+
return VllmBackend(model, max_chars)
|
| 109 |
+
if name == "transformers":
|
| 110 |
+
return TransformersBackend(model, max_chars, device)
|
| 111 |
+
if name == "fake":
|
| 112 |
+
return FakeBackend()
|
| 113 |
+
raise ValueError(f"unknown backend: {name}")
|
code/3c1a8da-dirty-bd01fd79/src/hf_jobs_launch.py
ADDED
|
@@ -0,0 +1,459 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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_noise_job_script(output_repo: str, ref: str, dir_index: int, args: argparse.Namespace) -> str:
|
| 73 |
+
"""第2パス(ノイズ除去)。出力データセットを /cleaned にマウントし、第1パスの出力を入力にする。"""
|
| 74 |
+
|
| 75 |
+
input_dir = f"/cleaned/{args.input_prefix}/common_crawl_{dir_index}"
|
| 76 |
+
run_args = [
|
| 77 |
+
"--input-dir", input_dir,
|
| 78 |
+
"--output-root", f"/work/out/common_crawl_{dir_index}",
|
| 79 |
+
"--lid-model", "/work/repo/models/lid.176.ftz",
|
| 80 |
+
"--staging-dir", "/work/staging",
|
| 81 |
+
"--upload-repo", output_repo,
|
| 82 |
+
"--upload-prefix", f"{args.noise_prefix}/common_crawl_{dir_index}",
|
| 83 |
+
"--upload-batch", str(args.upload_batch),
|
| 84 |
+
"--delete-local-after-upload",
|
| 85 |
+
"--skip-existing-in-repo",
|
| 86 |
+
"--min-chars", str(args.min_chars), "--max-chars", str(args.max_chars), "--newline-policy", args.newline_policy,
|
| 87 |
+
]
|
| 88 |
+
if args.limit_shards is not None:
|
| 89 |
+
run_args += ["--limit-shards", str(args.limit_shards)]
|
| 90 |
+
if args.tokenizer:
|
| 91 |
+
run_args += ["--tokenizer", args.tokenizer]
|
| 92 |
+
if args.min_tokens is not None:
|
| 93 |
+
run_args += ["--min-tokens", str(args.min_tokens)]
|
| 94 |
+
if args.max_tokens is not None:
|
| 95 |
+
run_args += ["--max-tokens", str(args.max_tokens)]
|
| 96 |
+
workers_expr = str(args.workers) if args.workers else '"$(( ${CPU_CORES:-2} > 1 ? ${CPU_CORES:-2} - 1 : 1 ))"'
|
| 97 |
+
snapshot = (
|
| 98 |
+
"import time; from huggingface_hub import snapshot_download\n"
|
| 99 |
+
"for attempt in range(5):\n"
|
| 100 |
+
" try:\n"
|
| 101 |
+
f" snapshot_download({output_repo!r}, repo_type='dataset', local_dir='/work/repo', allow_patterns=['code/{ref}/**', 'models/lid.176.ftz']); break\n"
|
| 102 |
+
" except Exception as error:\n"
|
| 103 |
+
" print('snapshot retry', attempt + 1, repr(error)[:200], flush=True); time.sleep(30 * (attempt + 1))\n"
|
| 104 |
+
"else:\n"
|
| 105 |
+
" raise SystemExit('code snapshot failed')\n"
|
| 106 |
+
)
|
| 107 |
+
extra = ' "transformers>=4.51"' if args.tokenizer else ""
|
| 108 |
+
lines = [
|
| 109 |
+
"set -euo pipefail",
|
| 110 |
+
"export PIP_DISABLE_PIP_VERSION_CHECK=1 PYTHONUNBUFFERED=1 HF_HUB_DOWNLOAD_TIMEOUT=120 HF_HUB_ETAG_TIMEOUT=60",
|
| 111 |
+
f'pip install -q "pyarrow>=17" "huggingface_hub>=1.0" "numpy" "fasttext-wheel"{extra}',
|
| 112 |
+
"mkdir -p /work/out && cd /work",
|
| 113 |
+
f"python -c {shlex.quote(snapshot)}",
|
| 114 |
+
f"ls /work/repo/code/{ref}/src >/dev/null",
|
| 115 |
+
"test -f /work/repo/models/lid.176.ftz",
|
| 116 |
+
f'echo "input shards: $(ls {input_dir} | wc -l)"',
|
| 117 |
+
f"python /work/repo/code/{ref}/src/run_noise_pass.py " + " ".join(shlex.quote(a) for a in run_args) + f" --workers {workers_expr}",
|
| 118 |
+
]
|
| 119 |
+
return "\n".join(lines) + "\n"
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def build_report_job_script(output_repo: str, ref: str, args: argparse.Namespace) -> str:
|
| 123 |
+
"""品質報告(項目22・25〜29)。第2パスの features.parquet を DuckDB で全件集約し、reports/ へアップロードする。"""
|
| 124 |
+
|
| 125 |
+
snapshot = (
|
| 126 |
+
"import time; from huggingface_hub import snapshot_download\n"
|
| 127 |
+
"for attempt in range(5):\n"
|
| 128 |
+
" try:\n"
|
| 129 |
+
f" snapshot_download({output_repo!r}, repo_type='dataset', local_dir='/work/repo', allow_patterns=['code/{ref}/**']); break\n"
|
| 130 |
+
" except Exception as error:\n"
|
| 131 |
+
" print('snapshot retry', attempt + 1, repr(error)[:200], flush=True); time.sleep(30 * (attempt + 1))\n"
|
| 132 |
+
"else:\n"
|
| 133 |
+
" raise SystemExit('code snapshot failed')\n"
|
| 134 |
+
)
|
| 135 |
+
# features.parquet はマウント越しではなく HTTP でローカルディスクへ取得する(マウント越しだと DuckDB の
|
| 136 |
+
# クエリごとに全ファイルを再スキャンして数時間かかる。約 2,420 ファイル・22 GB)
|
| 137 |
+
stage_features = (
|
| 138 |
+
"import time; from huggingface_hub import snapshot_download\n"
|
| 139 |
+
"for attempt in range(8):\n"
|
| 140 |
+
" try:\n"
|
| 141 |
+
f" snapshot_download({output_repo!r}, repo_type='dataset', local_dir='/work/features', max_workers=16, "
|
| 142 |
+
f"allow_patterns=['{args.noise_prefix}/*/*/features.parquet', '{args.noise_prefix}/*/*/noise_summary.json'"
|
| 143 |
+
+ (f", '{args.guard_prefix}/*/*/guard_removed.jsonl'" if args.report_with_guard else "") + "]); break\n"
|
| 144 |
+
" except Exception as error:\n"
|
| 145 |
+
" print('features download retry', attempt + 1, repr(error)[:200], flush=True); time.sleep(30 * (attempt + 1))\n"
|
| 146 |
+
"else:\n"
|
| 147 |
+
" raise SystemExit('features download failed')\n"
|
| 148 |
+
)
|
| 149 |
+
report_args = [
|
| 150 |
+
"--features-glob", f"/work/features/{args.noise_prefix}/**/features.parquet",
|
| 151 |
+
"--noise-summaries-glob", f"/work/features/{args.noise_prefix}/**/noise_summary.json",
|
| 152 |
+
"--output-dir", "/work/report",
|
| 153 |
+
"--temp-dir", "/work/duck_tmp",
|
| 154 |
+
]
|
| 155 |
+
if args.report_with_guard:
|
| 156 |
+
report_args += ["--guard-removed-glob", f"/work/features/{args.guard_prefix}/**/guard_removed.jsonl"]
|
| 157 |
+
if args.previous_low_quality_rate is not None:
|
| 158 |
+
report_args += ["--previous-low-quality-rate", str(args.previous_low_quality_rate)]
|
| 159 |
+
if args.exclude_genres:
|
| 160 |
+
report_args += ["--exclude-genres", args.exclude_genres]
|
| 161 |
+
upload = (
|
| 162 |
+
"from huggingface_hub import HfApi; import datetime; "
|
| 163 |
+
f"HfApi().upload_folder(repo_id={output_repo!r}, repo_type='dataset', folder_path='/work/report', "
|
| 164 |
+
"path_in_repo='reports/quality_' + datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ'), commit_message='quality report (items 22, 25-29)')"
|
| 165 |
+
)
|
| 166 |
+
lines = [
|
| 167 |
+
"set -euo pipefail",
|
| 168 |
+
"export PIP_DISABLE_PIP_VERSION_CHECK=1 PYTHONUNBUFFERED=1",
|
| 169 |
+
'pip install -q "pyarrow>=17" "huggingface_hub>=1.0" "duckdb>=1.0"',
|
| 170 |
+
"mkdir -p /work/report /work/features /work/duck_tmp && cd /work",
|
| 171 |
+
"df -h /work | tail -1; nproc; free -g | head -2",
|
| 172 |
+
f"python -c {shlex.quote(snapshot)}",
|
| 173 |
+
f"python -c {shlex.quote(stage_features)}",
|
| 174 |
+
f'echo "feature files: $(find /work/features/{args.noise_prefix} -name features.parquet | wc -l)"; du -sh /work/features',
|
| 175 |
+
f"python /work/repo/code/{ref}/src/quality_report.py " + " ".join(shlex.quote(a) for a in report_args),
|
| 176 |
+
f"python -c {shlex.quote(upload)}",
|
| 177 |
+
]
|
| 178 |
+
return "\n".join(lines) + "\n"
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def build_guard_job_script(output_repo: str, ref: str, dir_index: int, split_index: int, args: argparse.Namespace) -> str:
|
| 182 |
+
"""第3パス(Qwen3Guard による削除)。GPU ジョブ。第2パスの出力を HTTP で取得し、候補文書だけ分類する。"""
|
| 183 |
+
|
| 184 |
+
run_args = [
|
| 185 |
+
"--source-repo", output_repo, "--source-prefix", args.noise_prefix, "--dir-index", str(dir_index),
|
| 186 |
+
"--staging-dir", "/work/staging",
|
| 187 |
+
"--output-root", f"/work/out/common_crawl_{dir_index}",
|
| 188 |
+
"--backend", "vllm", "--model", args.guard_model, "--max-chars", str(args.guard_max_chars), "--min-terms", str(args.guard_min_terms),
|
| 189 |
+
"--chunk-size", str(args.guard_chunk_size),
|
| 190 |
+
"--upload-repo", output_repo, "--upload-prefix", f"{args.guard_prefix}/common_crawl_{dir_index}",
|
| 191 |
+
"--upload-batch", str(args.upload_batch), "--delete-local-after-upload", "--skip-existing-in-repo",
|
| 192 |
+
]
|
| 193 |
+
if args.guard_delete_categories:
|
| 194 |
+
run_args += ["--delete-categories", args.guard_delete_categories]
|
| 195 |
+
if args.limit_shards is not None:
|
| 196 |
+
run_args += ["--limit-shards", str(args.limit_shards)]
|
| 197 |
+
if args.split > 1:
|
| 198 |
+
run_args += ["--shard-index", str(split_index), "--shard-count", str(args.split)]
|
| 199 |
+
if args.workers:
|
| 200 |
+
run_args += ["--workers", str(args.workers)]
|
| 201 |
+
snapshot = (
|
| 202 |
+
"import time; from huggingface_hub import snapshot_download\n"
|
| 203 |
+
"for attempt in range(5):\n"
|
| 204 |
+
" try:\n"
|
| 205 |
+
f" snapshot_download({output_repo!r}, repo_type='dataset', local_dir='/work/repo', allow_patterns=['code/{ref}/**']); break\n"
|
| 206 |
+
" except Exception as error:\n"
|
| 207 |
+
" print('snapshot retry', attempt + 1, repr(error)[:200], flush=True); time.sleep(30 * (attempt + 1))\n"
|
| 208 |
+
"else:\n"
|
| 209 |
+
" raise SystemExit('code snapshot failed')\n"
|
| 210 |
+
)
|
| 211 |
+
lines = [
|
| 212 |
+
"set -euo pipefail",
|
| 213 |
+
"export PIP_DISABLE_PIP_VERSION_CHECK=1 PYTHONUNBUFFERED=1 HF_HUB_DOWNLOAD_TIMEOUT=120 HF_HUB_ETAG_TIMEOUT=60 HF_HUB_ENABLE_HF_TRANSFER=0",
|
| 214 |
+
"PY=$(command -v python3 || command -v python); echo \"python: $PY\"",
|
| 215 |
+
'$PY -m pip install -q "pyarrow>=17" "huggingface_hub>=1.0"',
|
| 216 |
+
"mkdir -p /work/out /work/staging && cd /work",
|
| 217 |
+
"nvidia-smi --query-gpu=name,memory.total --format=csv || true; nproc; df -h /work | tail -1",
|
| 218 |
+
"$PY -c \"import vllm, transformers; print('vllm', vllm.__version__, 'transformers', transformers.__version__)\"",
|
| 219 |
+
f"$PY -c {shlex.quote(snapshot)}",
|
| 220 |
+
f"cd /work/repo/code/{ref}/src",
|
| 221 |
+
"$PY run_guard_pass.py " + " ".join(shlex.quote(a) for a in run_args),
|
| 222 |
+
]
|
| 223 |
+
return "\n".join(lines) + "\n"
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def build_job_script(output_repo: str, ref: str, dir_index: int, args: argparse.Namespace) -> str:
|
| 227 |
+
input_dir = f"/data/data/common_crawl_{dir_index}"
|
| 228 |
+
run_args = [
|
| 229 |
+
"--input-dir", input_dir,
|
| 230 |
+
"--output-root", f"/work/out/common_crawl_{dir_index}",
|
| 231 |
+
"--blocklist-cache-dir", "/work/repo/blocklists/ut1",
|
| 232 |
+
"--staging-dir", "/work/staging",
|
| 233 |
+
"--upload-repo", output_repo,
|
| 234 |
+
"--upload-prefix", f"outputs/common_crawl_{dir_index}",
|
| 235 |
+
"--upload-batch", str(args.upload_batch),
|
| 236 |
+
"--delete-local-after-upload",
|
| 237 |
+
"--skip-existing-in-repo",
|
| 238 |
+
]
|
| 239 |
+
if args.limit_shards is not None:
|
| 240 |
+
run_args += ["--limit-shards", str(args.limit_shards)]
|
| 241 |
+
if args.policy_approver:
|
| 242 |
+
run_args += ["--policy-approver", args.policy_approver]
|
| 243 |
+
if args.policy_approved_on:
|
| 244 |
+
run_args += ["--policy-approved-on", args.policy_approved_on]
|
| 245 |
+
if args.policy_note:
|
| 246 |
+
run_args += ["--policy-note", args.policy_note]
|
| 247 |
+
workers_expr = str(args.workers) if args.workers else '"$(( ${CPU_CORES:-2} > 1 ? ${CPU_CORES:-2} - 1 : 1 ))"'
|
| 248 |
+
snapshot = (
|
| 249 |
+
"import time; from huggingface_hub import snapshot_download\n"
|
| 250 |
+
"for attempt in range(5):\n"
|
| 251 |
+
" try:\n"
|
| 252 |
+
f" snapshot_download({output_repo!r}, repo_type='dataset', local_dir='/work/repo', allow_patterns=['code/{ref}/**', 'blocklists/ut1/**']); break\n"
|
| 253 |
+
" except Exception as error:\n"
|
| 254 |
+
" print('snapshot retry', attempt + 1, repr(error)[:200], flush=True); time.sleep(30 * (attempt + 1))\n"
|
| 255 |
+
"else:\n"
|
| 256 |
+
" raise SystemExit('code snapshot failed')\n"
|
| 257 |
+
)
|
| 258 |
+
lines = [
|
| 259 |
+
"set -euo pipefail",
|
| 260 |
+
"export PIP_DISABLE_PIP_VERSION_CHECK=1 PYTHONUNBUFFERED=1 HF_HUB_DOWNLOAD_TIMEOUT=120 HF_HUB_ETAG_TIMEOUT=60",
|
| 261 |
+
'pip install -q "pyarrow>=17" "huggingface_hub>=1.0" "sudachipy>=0.6" "sudachidict_core"',
|
| 262 |
+
"mkdir -p /work/out && cd /work",
|
| 263 |
+
f"python -c {shlex.quote(snapshot)}",
|
| 264 |
+
f"ls /work/repo/code/{ref}/src >/dev/null",
|
| 265 |
+
f"test -f /work/repo/blocklists/ut1/manifest.json",
|
| 266 |
+
# pipefail 下で `ls | head` は SIGPIPE で失敗し得るため、件数だけを表示する
|
| 267 |
+
f'echo "input shards: $(ls {input_dir} | wc -l)"',
|
| 268 |
+
f"python /work/repo/code/{ref}/src/run_shard.py " + " ".join(shlex.quote(a) for a in run_args) + f" --workers {workers_expr}",
|
| 269 |
+
]
|
| 270 |
+
return "\n".join(lines) + "\n"
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def upload_code_and_blocklists(api, output_repo: str, code_dir: Path, ref: str, ut1_cache_dir: Path, dry_run: bool) -> dict[str, Any]:
|
| 274 |
+
def exists(path: str) -> bool:
|
| 275 |
+
return (not dry_run) and api.file_exists(output_repo, path, repo_type="dataset")
|
| 276 |
+
|
| 277 |
+
code_prefix = f"code/{ref}/src"
|
| 278 |
+
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"))
|
| 279 |
+
manifest = {
|
| 280 |
+
"ref": ref,
|
| 281 |
+
"uploaded_at_utc": datetime.now(timezone.utc).isoformat(),
|
| 282 |
+
"files": {p.relative_to(code_dir).as_posix(): hashlib.sha256(p.read_bytes()).hexdigest() for p in files},
|
| 283 |
+
}
|
| 284 |
+
actions: dict[str, Any] = {"code_prefix": code_prefix, "code_files": len(files), "ref": ref}
|
| 285 |
+
if dry_run:
|
| 286 |
+
actions["code_upload"] = "dry-run"
|
| 287 |
+
elif exists(f"{code_prefix}/run_shard.py"):
|
| 288 |
+
actions["code_upload"] = "already present"
|
| 289 |
+
else:
|
| 290 |
+
api.upload_folder(repo_id=output_repo, repo_type="dataset", folder_path=str(code_dir), path_in_repo=code_prefix,
|
| 291 |
+
ignore_patterns=CODE_IGNORE, commit_message=f"code {ref}")
|
| 292 |
+
api.upload_file(repo_id=output_repo, repo_type="dataset", path_or_fileobj=json.dumps(manifest, ensure_ascii=False, indent=2).encode("utf-8"),
|
| 293 |
+
path_in_repo=f"code/{ref}/MANIFEST.json", commit_message=f"code manifest {ref}")
|
| 294 |
+
actions["code_upload"] = "uploaded"
|
| 295 |
+
lid_model = ut1_cache_dir.parent.parent / "models" / "lid.176.ftz"
|
| 296 |
+
if dry_run:
|
| 297 |
+
actions["lid_model_upload"] = "dry-run"
|
| 298 |
+
elif exists("models/lid.176.ftz"):
|
| 299 |
+
actions["lid_model_upload"] = "already present"
|
| 300 |
+
elif lid_model.exists():
|
| 301 |
+
api.upload_file(repo_id=output_repo, repo_type="dataset", path_or_fileobj=str(lid_model), path_in_repo="models/lid.176.ftz",
|
| 302 |
+
commit_message="fastText lid.176 model (CC BY-SA 3.0)")
|
| 303 |
+
actions["lid_model_upload"] = "uploaded"
|
| 304 |
+
else:
|
| 305 |
+
actions["lid_model_upload"] = f"missing: {lid_model}"
|
| 306 |
+
if not (ut1_cache_dir / "manifest.json").exists():
|
| 307 |
+
raise FileNotFoundError(f"UT1 キャッシュがありません: {ut1_cache_dir}(domain_blocklist.py fetch を先に実行)")
|
| 308 |
+
if dry_run:
|
| 309 |
+
actions["blocklist_upload"] = "dry-run"
|
| 310 |
+
elif exists("blocklists/ut1/manifest.json"):
|
| 311 |
+
actions["blocklist_upload"] = "already present"
|
| 312 |
+
else:
|
| 313 |
+
api.upload_folder(repo_id=output_repo, repo_type="dataset", folder_path=str(ut1_cache_dir), path_in_repo="blocklists/ut1",
|
| 314 |
+
commit_message="UT1 blocklists snapshot")
|
| 315 |
+
actions["blocklist_upload"] = "uploaded"
|
| 316 |
+
return actions
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def main(argv: list[str] | None = None) -> None:
|
| 320 |
+
source_dir = Path(__file__).resolve().parent
|
| 321 |
+
project_root = source_dir.parent
|
| 322 |
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 323 |
+
parser.add_argument("--input-dataset", default=DEFAULT_INPUT)
|
| 324 |
+
parser.add_argument("--output-repo", default=DEFAULT_OUTPUT, help="非公開で作成される出力データセット")
|
| 325 |
+
parser.add_argument("--dirs", default="0-18", help="例: 0-18, 0,1,2")
|
| 326 |
+
parser.add_argument("--flavor", default=DEFAULT_FLAVOR)
|
| 327 |
+
parser.add_argument("--timeout", default=DEFAULT_TIMEOUT, help="例: 6h, 90m")
|
| 328 |
+
parser.add_argument("--image", default=DEFAULT_IMAGE)
|
| 329 |
+
parser.add_argument("--namespace", default=None, help="課金先。既定は出力リポジトリの所有者")
|
| 330 |
+
parser.add_argument("--workers", type=int, default=None, help="既定はジョブ内の CPU_CORES - 1")
|
| 331 |
+
parser.add_argument("--upload-batch", type=int, default=5)
|
| 332 |
+
parser.add_argument("--limit-shards", type=int, default=None, help="各ディレクトリの先頭N件だけ(試運転用)")
|
| 333 |
+
parser.add_argument("--policy-approver", default=None)
|
| 334 |
+
parser.add_argument("--policy-approved-on", default=None)
|
| 335 |
+
parser.add_argument("--policy-note", default=None)
|
| 336 |
+
parser.add_argument("--code-dir", type=Path, default=source_dir)
|
| 337 |
+
parser.add_argument("--ut1-cache-dir", type=Path, default=project_root / "data" / "blocklists" / "ut1")
|
| 338 |
+
parser.add_argument("--stage", choices=("full", "noise", "report", "guard"), default="full",
|
| 339 |
+
help="full: 有害→PII(入力データセットをマウント)。noise: 第2パス(出力データセットをマウントしてノイズ除去)。report: 品質報告(項目22・25〜29、1ジョブ)")
|
| 340 |
+
parser.add_argument("--previous-low-quality-rate", type=float, default=None, help="report: 前回レビューの低品質比率(0〜1)")
|
| 341 |
+
parser.add_argument("--exclude-genres", default="", help="report: 除外を決めたジャンル(記録用)")
|
| 342 |
+
parser.add_argument("--report-with-guard", action="store_true", help="report: 第3パス(guard)の削除を反映して集計する")
|
| 343 |
+
parser.add_argument("--guard-prefix", default="outputs_v3", help="guard: 第3パス出力の接頭辞")
|
| 344 |
+
parser.add_argument("--guard-model", default="Qwen/Qwen3Guard-Gen-0.6B")
|
| 345 |
+
parser.add_argument("--guard-max-chars", type=int, default=2000, help="guard: 分類器に渡す本文の先頭文字数")
|
| 346 |
+
parser.add_argument("--guard-min-terms", type=int, default=1, help="guard: 候補とする辞書の異なり語数")
|
| 347 |
+
parser.add_argument("--guard-chunk-size", type=int, default=512)
|
| 348 |
+
parser.add_argument("--guard-delete-categories", default="", help="guard: 削除する Unsafe カテゴリ(既定は run_guard_pass.py の既定)")
|
| 349 |
+
parser.add_argument("--split", type=int, default=1, help="guard: ディレクトリごとに N ジョブへ分割")
|
| 350 |
+
parser.add_argument("--input-prefix", default="outputs", help="noise: 第1パス出力の接頭辞")
|
| 351 |
+
parser.add_argument("--noise-prefix", default="outputs_v2", help="noise: 第2パス出力の接頭辞")
|
| 352 |
+
parser.add_argument("--min-chars", type=int, default=200)
|
| 353 |
+
parser.add_argument("--max-chars", type=int, default=100_000)
|
| 354 |
+
parser.add_argument("--newline-policy", choices=("join", "delete", "keep"), default="join")
|
| 355 |
+
parser.add_argument("--tokenizer", default=None)
|
| 356 |
+
parser.add_argument("--min-tokens", type=int, default=None)
|
| 357 |
+
parser.add_argument("--max-tokens", type=int, default=None)
|
| 358 |
+
parser.add_argument("--dry-run", action="store_true", help="ジョブ定義とスクリプトを表示するだけで起動しない")
|
| 359 |
+
parser.add_argument("--wait", action="store_true", help="全ジョブの終了を待つ")
|
| 360 |
+
args = parser.parse_args(argv)
|
| 361 |
+
|
| 362 |
+
token = os.environ.get("HF_TOKEN")
|
| 363 |
+
if not token and not args.dry_run:
|
| 364 |
+
raise SystemExit("HF_TOKEN が未設定です(uv run --env-file .env ...)")
|
| 365 |
+
dirs = parse_dirs(args.dirs)
|
| 366 |
+
ref = code_ref(args.code_dir)
|
| 367 |
+
namespace = args.namespace or args.output_repo.split("/")[0]
|
| 368 |
+
|
| 369 |
+
from huggingface_hub import HfApi, Volume
|
| 370 |
+
|
| 371 |
+
api = HfApi(token=token)
|
| 372 |
+
if not args.dry_run:
|
| 373 |
+
api.create_repo(args.output_repo, repo_type="dataset", private=True, exist_ok=True)
|
| 374 |
+
if args.stage == "noise" and not args.dry_run:
|
| 375 |
+
# 第1パスの出力が揃っていることを確認する(ボリュームは起動時点のスナップショット)
|
| 376 |
+
for dir_index in dirs:
|
| 377 |
+
marker = f"{args.input_prefix}/common_crawl_{dir_index}"
|
| 378 |
+
try:
|
| 379 |
+
entries = list(api.list_repo_tree(args.output_repo, path_in_repo=marker, repo_type="dataset", recursive=False))
|
| 380 |
+
except Exception: # noqa: BLE001
|
| 381 |
+
entries = []
|
| 382 |
+
if not entries:
|
| 383 |
+
raise SystemExit(f"第1パスの出力がありません: {marker}/")
|
| 384 |
+
actions = upload_code_and_blocklists(api, args.output_repo, args.code_dir, ref, args.ut1_cache_dir, args.dry_run)
|
| 385 |
+
print(json.dumps({"event": "prepared", **actions, "output_repo": args.output_repo, "private": True}, ensure_ascii=False), flush=True)
|
| 386 |
+
|
| 387 |
+
launched: list[dict[str, Any]] = []
|
| 388 |
+
if args.stage == "report":
|
| 389 |
+
dirs = [-1] # 報告は1ジョブ
|
| 390 |
+
if args.stage == "guard":
|
| 391 |
+
if args.flavor == DEFAULT_FLAVOR:
|
| 392 |
+
args.flavor = "l4x1"
|
| 393 |
+
if args.image == DEFAULT_IMAGE:
|
| 394 |
+
args.image = "vllm/vllm-openai:latest"
|
| 395 |
+
for dir_index in dirs:
|
| 396 |
+
marker = f"{args.noise_prefix}/common_crawl_{dir_index}"
|
| 397 |
+
if not args.dry_run:
|
| 398 |
+
try:
|
| 399 |
+
entries = list(api.list_repo_tree(args.output_repo, path_in_repo=marker, repo_type="dataset", recursive=False))
|
| 400 |
+
except Exception: # noqa: BLE001
|
| 401 |
+
entries = []
|
| 402 |
+
if not entries:
|
| 403 |
+
raise SystemExit(f"第2パスの出力がありません: {marker}/")
|
| 404 |
+
targets = [(d, k) for d in dirs for k in range(max(1, args.split) if args.stage == "guard" else 1)]
|
| 405 |
+
for dir_index, split_index in targets:
|
| 406 |
+
if args.stage == "guard":
|
| 407 |
+
script = build_guard_job_script(args.output_repo, ref, dir_index, split_index, args)
|
| 408 |
+
volume_source, mount_path = None, None
|
| 409 |
+
job_name = f"abeja-cc-ja-guard-{dir_index}" + (f"-{split_index}of{args.split}" if args.split > 1 else "")
|
| 410 |
+
elif args.stage == "report":
|
| 411 |
+
script = build_report_job_script(args.output_repo, ref, args)
|
| 412 |
+
volume_source, mount_path, job_name = args.output_repo, "/cleaned", "abeja-cc-ja-quality-report"
|
| 413 |
+
elif args.stage == "noise":
|
| 414 |
+
script = build_noise_job_script(args.output_repo, ref, dir_index, args)
|
| 415 |
+
volume_source, mount_path, job_name = args.output_repo, "/cleaned", f"abeja-cc-ja-noise-{dir_index}"
|
| 416 |
+
else:
|
| 417 |
+
script = build_job_script(args.output_repo, ref, dir_index, args)
|
| 418 |
+
volume_source, mount_path, job_name = args.input_dataset, "/data", f"abeja-cc-ja-clean-{dir_index}"
|
| 419 |
+
spec = {
|
| 420 |
+
"name": job_name,
|
| 421 |
+
"image": args.image,
|
| 422 |
+
"flavor": args.flavor,
|
| 423 |
+
"timeout": args.timeout,
|
| 424 |
+
"namespace": namespace,
|
| 425 |
+
"volumes": ([{"type": "dataset", "source": volume_source, "mount_path": mount_path, "read_only": True}] if volume_source else []),
|
| 426 |
+
"secrets": ["HF_TOKEN"],
|
| 427 |
+
"labels": {"pipeline": "abeja-cc-ja-cleansing", "stage": args.stage, "dir": f"common_crawl_{dir_index}" if dir_index >= 0 else "all", "code_ref": ref},
|
| 428 |
+
}
|
| 429 |
+
if args.dry_run:
|
| 430 |
+
print(json.dumps({"event": "dry-run", "job": spec}, ensure_ascii=False))
|
| 431 |
+
print("--- script ---\n" + script)
|
| 432 |
+
continue
|
| 433 |
+
job = api.run_job(
|
| 434 |
+
image=args.image,
|
| 435 |
+
command=["bash", "-lc", script],
|
| 436 |
+
flavor=args.flavor,
|
| 437 |
+
timeout=args.timeout,
|
| 438 |
+
secrets={"HF_TOKEN": token},
|
| 439 |
+
env={"PIPELINE_DIR": f"common_crawl_{dir_index}"},
|
| 440 |
+
volumes=([Volume(type="dataset", source=volume_source, mount_path=mount_path, read_only=True)] if volume_source else []),
|
| 441 |
+
namespace=namespace,
|
| 442 |
+
name=spec["name"],
|
| 443 |
+
labels=spec["labels"],
|
| 444 |
+
)
|
| 445 |
+
launched.append({"dir": dir_index, "job_id": job.id, "url": job.url})
|
| 446 |
+
print(json.dumps({"event": "launched", "dir": dir_index, "job_id": job.id, "url": job.url}), flush=True)
|
| 447 |
+
if launched:
|
| 448 |
+
record = project_root / "data" / f"hf_jobs_{datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')}.json"
|
| 449 |
+
record.parent.mkdir(parents=True, exist_ok=True)
|
| 450 |
+
record.write_text(json.dumps({"ref": ref, "stage": args.stage, "output_repo": args.output_repo, "jobs": launched, "flavor": args.flavor, "timeout": args.timeout}, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
| 451 |
+
print(json.dumps({"event": "recorded", "file": str(record)}), flush=True)
|
| 452 |
+
if args.wait and launched:
|
| 453 |
+
finished = api.wait_for_job(job_id=[j["job_id"] for j in launched])
|
| 454 |
+
for info in (finished if isinstance(finished, list) else [finished]):
|
| 455 |
+
print(json.dumps({"event": "finished", "job_id": info.id, "stage": info.status.stage, "message": info.status.message}), flush=True)
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
if __name__ == "__main__":
|
| 459 |
+
main()
|
code/3c1a8da-dirty-bd01fd79/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/3c1a8da-dirty-bd01fd79/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/3c1a8da-dirty-bd01fd79/src/noise/boilerplate_lines.txt
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 項目18: boilerplate 行。1行1正規表現。行全体に対して search し、該当行を削除する。
|
| 2 |
+
# --- Cookie 同意 ---
|
| 3 |
+
cookie(?:s)?(?:の使用|を使用|に同意|ポリシー|の利用|を利用)|クッキー(?:の使用|を使用|に同意|ポリシー|の利用)|(?:accept|allow|use) (?:all )?cookies
|
| 4 |
+
# --- 関連記事・おすすめ ---
|
| 5 |
+
^\s*(?:【?関連記事】?|関連記事(?:一覧)?|こちらの記事もおすすめ|あわせて読みたい|合わせて読みたい|人気記事(?:ランキング)?|新着記事|おすすめ記事|注目記事|最新記事)\s*[::]?\s*$
|
| 6 |
+
# --- フッター ---
|
| 7 |
+
all rights reserved|copyright\s*(?:©|\(c\)|\d{4})|©\s*\d{4}|^\s*(?:プライバシーポリシー|個人情報保護方針|利用規約|サイトマップ|特定商取引法に基づく表記|免責事項|お問い合わせ|会社概要)\s*(?:[||//・]\s*(?:プライバシーポリシー|個人情報保護方針|利用規約|サイトマップ|特定商取引法に基づく表記|免責事項|お問い合わせ|会社概要)\s*)*$
|
| 8 |
+
# --- コメント欄 ---
|
| 9 |
+
^\s*(?:コメント(?:を残す|を書く|を投稿|一覧|する|はまだありません)|コメント\s*[\((]\d+[\))]|返信する|返信を残す|シェアする|ツイート|いいね!?\s*\d*|Leave a (?:Reply|Comment)|Post Comment|No comments)\s*$
|
| 10 |
+
^\s*(?:名前|メールアドレス|ウェブサイト|コメント)\s*[::]?\s*(?:\*|(必須)|\(必須\))?\s*$
|
| 11 |
+
# --- 広告 ---
|
| 12 |
+
^\s*(?:スポンサー(?:ド)?リンク|スポンサー広告|\[?PR\]?|【PR】|広告|AD|advertisement)\s*$
|
| 13 |
+
# --- ナビゲーション ---
|
| 14 |
+
^\s*(?:ホーム|HOME|トップ(?:ページ)?)\s*[>>»›]|^\s*(?:前の記事|次の記事|前へ|次へ|« Previous|Next »|カテゴリー?一覧|タグ一覧|アーカイブ|月別アーカイブ|カレンダー|検索|メニュー|MENU|ログイン|新規登録|会員登録|マイページ|カート|ページ(?:の)?トップへ|ページ上部へ|TOPへ戻る)\s*$
|
| 15 |
+
^\s*(?:Posted by|投稿者|投稿日|カテゴリー?|タグ|更新日|公開日)\s*[::]?\s*\S{0,30}\s*$
|
| 16 |
+
# --- SNS シェア ---
|
| 17 |
+
^\s*(?:facebook|twitter|x|line|はてなブックマーク|hatena|pocket|pinterest|instagram|youtube)\s*(?:[||//・]\s*(?:facebook|twitter|x|line|はてなブックマーク|hatena|pocket|pinterest|instagram|youtube)\s*)*$
|
code/3c1a8da-dirty-bd01fd79/src/noise/llm_phrases.txt
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 項目14: LLM 由来の回答拒否文・アシスタント口調。1行1正規表現(大文字小文字無視)。該当文書は削除。
|
| 2 |
+
as an? (?:ai|artificial intelligence)(?: language)? model
|
| 3 |
+
as a large language model
|
| 4 |
+
i'?m (?:sorry|afraid),? but (?:i|as an ai)
|
| 5 |
+
i (?:cannot|can'?t|am unable to) (?:help|assist|provide|fulfill|comply|generate|answer) (?:with )?(?:that|this|your request)
|
| 6 |
+
i do not have (?:personal )?(?:opinions|feelings|access to real-time)
|
| 7 |
+
openai'?s? (?:content|usage|use) polic(?:y|ies)
|
| 8 |
+
私は\s?ai(?:言語モデル|アシスタント|チャットボット)?(?:なので|です(?:ので|から)?|として|であり|ですが)
|
| 9 |
+
ai言語モデル(?:として|なので|ですので|である)
|
| 10 |
+
(?:大規模)?言語モデルとして(?:は|、|の)
|
| 11 |
+
申し訳(?:ありません|ございません)が、?(?:私は)?ai(?:言語モデル|アシスタント)?(?:なので|として|には)
|
| 12 |
+
私はchatgpt|chatgptとして|chatgptなので
|
| 13 |
+
その(?:ご)?(?:質問|リクエスト)には(?:お)?答え(?:する)?ことができません
|
code/3c1a8da-dirty-bd01fd79/src/noise/special_tokens.txt
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 項目15: 他サービスの特殊トークン・チャットテンプレート断片。1行1正規表現(複数行モード)。該当文書は削除。
|
| 2 |
+
<\|endoftext\|>
|
| 3 |
+
<\|im_start\|>|<\|im_end\|>
|
| 4 |
+
\[INST\]|\[/INST\]
|
| 5 |
+
<<SYS>>|<</SYS>>
|
| 6 |
+
<\|(?:user|assistant|system)\|>
|
| 7 |
+
<\|begin_of_text\|>|<\|eot_id\|>|<\|start_header_id\|>
|
| 8 |
+
<bos>|<eos>|<pad>|<unk>
|
| 9 |
+
</s>\s*$
|
| 10 |
+
^### (?:Instruction|Response|Input|System):
|
| 11 |
+
^(?:Human|Assistant):\s
|
code/3c1a8da-dirty-bd01fd79/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/3c1a8da-dirty-bd01fd79/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/3c1a8da-dirty-bd01fd79/src/quality_report.py
ADDED
|
@@ -0,0 +1,336 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""監査項目 E(22 重複)・F(25〜27 言語・品質)・G(28〜29 ドメイン適合)の報告書を生成する。
|
| 2 |
+
|
| 3 |
+
第2パスが書く ``features.parquet``(文書ごとの言語・ジャンル・品質フラグ・文字数・perplexity・SHA-1)と
|
| 4 |
+
``noise_summary.json`` を DuckDB で集約し、JSON と Markdown を出力する。全件(約2.2億行)でも
|
| 5 |
+
DuckDB がファイルを逐次読みするため、1台のジョブ(cpu-xl 等)で処理できる。
|
| 6 |
+
|
| 7 |
+
uv run python abeja-cc-ja/src/quality_report.py --features-glob "<root>/**/features.parquet" \\
|
| 8 |
+
--noise-summaries-glob "<root>/**/noise_summary.json" --output-dir <report_dir> \\
|
| 9 |
+
[--previous-low-quality-rate 0.35] [--exclude-genres none]
|
| 10 |
+
|
| 11 |
+
項目22の配布元重複除去の記録は本スクリプト内の定数(出典 URL 付き)に置き、完全一致(本文 SHA-1、URL)の
|
| 12 |
+
再確認結果を添える。
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import argparse
|
| 18 |
+
import json
|
| 19 |
+
import time
|
| 20 |
+
from datetime import datetime, timezone
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
from typing import Any
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
UPSTREAM_DEDUP = {
|
| 26 |
+
"performed_by": "ABEJA(配布元、ABEJA-CC-JA 構築時)",
|
| 27 |
+
"methods": [
|
| 28 |
+
{"method": "URL 重複除去(同一 URL は最新のスナップショットを採用)", "threshold": "完全一致"},
|
| 29 |
+
{"method": "MinHash による近似重複除去(text-dedup、Dataproc 上で実行)", "threshold": "非公開(記事に閾値の記載なし)"},
|
| 30 |
+
],
|
| 31 |
+
"source_urls": [
|
| 32 |
+
"https://tech-blog.abeja.asia/entry/abeja-nedo-project-part2-202405",
|
| 33 |
+
"https://tech-blog.abeja.asia/entry/abeja-cc-ja-202409",
|
| 34 |
+
"https://registry.opendata.aws/abeja-cc-ja/",
|
| 35 |
+
],
|
| 36 |
+
"decision_ja": "配布元で URL 重複除去と MinHash 近似重複除去が実施済みのため、近似重複除去は再実行しない。完全一致(本文 SHA-1、URL)の残存だけを全件で再確認して記録する。",
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
GENRE_LABELS_JA = {
|
| 40 |
+
"diary_blog": "日記ブログ", "affiliate": "投資・美容・健康のアフィリエイト", "game": "ゲーム",
|
| 41 |
+
"entertainment": "芸能", "ec_product": "EC 商品ページ", "other": "その他",
|
| 42 |
+
}
|
| 43 |
+
LOW_QUALITY_FLAGS_JA = {
|
| 44 |
+
"short_lt500": "最終本文が500字未満", "symbol_digit_ratio_gt30": "記号・数字比率30%超", "line_repetition_gt30": "同一行の反復30%超",
|
| 45 |
+
"avg_line_len_lt20": "平均行長20字未満", "template_commerce": "販促・商品ページの定型", "low_lid_confidence": "言語判定の確信度0.5未満",
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def q(con, sql: str) -> list[tuple]:
|
| 50 |
+
return con.execute(sql).fetchall()
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def q1(con, sql: str):
|
| 54 |
+
return con.execute(sql).fetchone()
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def build(features_glob: str, noise_glob: str | None, previous_low_quality_rate: float | None, exclude_genres: list[str], sample_examples: int = 5,
|
| 58 |
+
db_settings: dict[str, Any] | None = None, guard_removed_glob: str | None = None) -> dict[str, Any]:
|
| 59 |
+
"""features.parquet を DuckDB で集計する。
|
| 60 |
+
|
| 61 |
+
``features_glob`` はローカルディスク上のファイルを指すこと(FUSE マウント越しだと各クエリが全ファイルを
|
| 62 |
+
再スキャンするため数時間かかる)。``db_settings`` で threads / temp_directory / memory_limit を指定できる。
|
| 63 |
+
進捗は項目ごとに標準出力へ JSON で出す。
|
| 64 |
+
"""
|
| 65 |
+
import duckdb
|
| 66 |
+
|
| 67 |
+
started = time.monotonic()
|
| 68 |
+
|
| 69 |
+
def progress(step: str, **extra: Any) -> None:
|
| 70 |
+
print(json.dumps({"event": "progress", "step": step, "elapsed_s": round(time.monotonic() - started, 1), **extra}, ensure_ascii=False), flush=True)
|
| 71 |
+
|
| 72 |
+
con = duckdb.connect()
|
| 73 |
+
for key, value in (db_settings or {}).items():
|
| 74 |
+
if value is None:
|
| 75 |
+
continue
|
| 76 |
+
con.execute(f"SET {key} = ?", [value]) if key != "threads" else con.execute(f"SET threads = {int(value)}")
|
| 77 |
+
con.execute("SET preserve_insertion_order = false")
|
| 78 |
+
con.execute(f"CREATE VIEW f0 AS SELECT * EXCLUDE (filename), regexp_extract(filename, '([^/]+)/features\\.parquet$', 1) AS shard "
|
| 79 |
+
f"FROM read_parquet('{features_glob}', union_by_name=true, filename=true)")
|
| 80 |
+
guard_info: dict[str, Any] | None = None
|
| 81 |
+
if guard_removed_glob:
|
| 82 |
+
# 第3パス(分類器)の削除を反映する。guard_removed.jsonl の record_index は第2パス出力 parquet(保持行のみ)の行番号なので、
|
| 83 |
+
# features 側では status='retained' の行を record_index 順に並べた順位と突き合わせる。
|
| 84 |
+
con.execute(
|
| 85 |
+
"CREATE TABLE guard_rows AS SELECT regexp_extract(filename, '([^/]+)/guard_removed\\.jsonl$', 1) AS shard, record_index AS rk, categories "
|
| 86 |
+
f"FROM read_json('{guard_removed_glob}', format='newline_delimited', filename=true, ignore_errors=true, "
|
| 87 |
+
"columns={'record_index': 'BIGINT', 'url': 'VARCHAR', 'safety': 'VARCHAR', 'categories': 'VARCHAR[]'})")
|
| 88 |
+
con.execute(
|
| 89 |
+
"CREATE TABLE guard_deleted AS SELECT r.shard, r.record_index FROM "
|
| 90 |
+
"(SELECT shard, record_index, row_number() OVER (PARTITION BY shard ORDER BY record_index) - 1 AS rk FROM f0 WHERE status = 'retained') r "
|
| 91 |
+
"JOIN guard_rows g ON r.shard = g.shard AND r.rk = g.rk")
|
| 92 |
+
con.execute("CREATE VIEW f AS SELECT f0.* REPLACE (CASE WHEN gd.record_index IS NOT NULL THEN 'deleted_guard:classifier' ELSE f0.status END AS status) "
|
| 93 |
+
"FROM f0 LEFT JOIN guard_deleted gd ON f0.shard = gd.shard AND f0.record_index = gd.record_index")
|
| 94 |
+
guard_rows = q1(con, "SELECT count(*) FROM guard_rows")[0]
|
| 95 |
+
guard_matched = q1(con, "SELECT count(*) FROM guard_deleted")[0]
|
| 96 |
+
guard_categories = q(con, "SELECT c, count(*) FROM (SELECT unnest(categories) AS c FROM guard_rows) GROUP BY c ORDER BY 2 DESC")
|
| 97 |
+
guard_info = {"guard_removed_glob": guard_removed_glob, "records_in_guard_removed": guard_rows, "records_matched_to_features": guard_matched,
|
| 98 |
+
"by_category": [{"category": c, "records": n} for c, n in guard_categories],
|
| 99 |
+
"note_ja": "第3パス(Qwen3Guard による削除)を features の status に 'deleted_guard:classifier' として反映。以降の保持件数はこの削除後の値。"}
|
| 100 |
+
progress("guard_join", guard_rows=guard_rows, guard_matched=guard_matched)
|
| 101 |
+
else:
|
| 102 |
+
con.execute("CREATE VIEW f AS SELECT * FROM f0")
|
| 103 |
+
total = q1(con, "SELECT count(*) FROM f")[0]
|
| 104 |
+
retained = q1(con, "SELECT count(*) FROM f WHERE status = 'retained'")[0]
|
| 105 |
+
progress("counts", records_total=total, records_retained=retained)
|
| 106 |
+
report: dict[str, Any] = {"generated_at_utc": datetime.now(timezone.utc).isoformat(), "features_glob": features_glob,
|
| 107 |
+
"records_total": total, "records_retained": retained}
|
| 108 |
+
if guard_info is not None:
|
| 109 |
+
report["guard_pass"] = guard_info
|
| 110 |
+
|
| 111 |
+
# --- 22 重複 ---
|
| 112 |
+
dup_sha = q1(con, "SELECT count(*) - count(DISTINCT content_sha1) FROM f WHERE status = 'retained' AND content_sha1 <> ''")[0]
|
| 113 |
+
dup_url = q1(con, "SELECT count(*) - count(DISTINCT url) FROM f WHERE status = 'retained' AND url <> ''")[0]
|
| 114 |
+
report["item22_dedup"] = {
|
| 115 |
+
"upstream": UPSTREAM_DEDUP,
|
| 116 |
+
"exact_duplicate_check": {
|
| 117 |
+
"scope": ("第3パス後の保持文書(全件)" if guard_info else "第2パス後の保持文書(全件)"),
|
| 118 |
+
"content_sha1_duplicates": dup_sha, "url_duplicates": dup_url,
|
| 119 |
+
"content_sha1_duplicate_rate": round(dup_sha / max(1, retained), 6), "url_duplicate_rate": round(dup_url / max(1, retained), 6),
|
| 120 |
+
},
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
progress("item22")
|
| 124 |
+
# --- 25 言語 ---
|
| 125 |
+
langs = q(con, "SELECT lang, count(*) FROM f WHERE status NOT LIKE 'deleted_toxic%' GROUP BY lang ORDER BY 2 DESC")
|
| 126 |
+
lang_total = sum(n for _, n in langs)
|
| 127 |
+
mixed = q1(con, "SELECT count(*) FROM f WHERE status = 'retained' AND mixed_language")[0]
|
| 128 |
+
non_ja_deleted = q1(con, "SELECT count(*) FROM f WHERE status = 'deleted_noise:non_japanese'")[0]
|
| 129 |
+
report["item25_language"] = {
|
| 130 |
+
"tool": "fastText lid.176(文書先頭1,000字。行判定は30字以上の行を最大50行)",
|
| 131 |
+
"scope": "第1パス後の文書(有害フィルタ削除分を除く)",
|
| 132 |
+
"distribution": [{"lang": l, "records": n, "ratio": round(n / max(1, lang_total), 5)} for l, n in langs[:15]],
|
| 133 |
+
"japanese_ratio": round(next((n for l, n in langs if l == "ja"), 0) / max(1, lang_total), 5),
|
| 134 |
+
"mixed_language_records": mixed, "mixed_definition": "文書は日本語判定だが、30字以上の行のうち非日本語判定が3割以上",
|
| 135 |
+
"processing": {"non_japanese": f"削除({non_ja_deleted} 文書、確信度0.5以上)", "mixed": "保持し件数のみ記録(非日本語行は行単位で削除しない)"},
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
progress("item25")
|
| 139 |
+
# --- 26 perplexity ---
|
| 140 |
+
has_ppl = q1(con, "SELECT count(*) FROM f WHERE perplexity IS NOT NULL")[0] > 0
|
| 141 |
+
if has_ppl:
|
| 142 |
+
quant = q1(con, "SELECT min(perplexity), quantile_cont(perplexity, 0.05), quantile_cont(perplexity, 0.25), quantile_cont(perplexity, 0.5), quantile_cont(perplexity, 0.75), quantile_cont(perplexity, 0.95), max(perplexity) FROM f WHERE perplexity IS NOT NULL")
|
| 143 |
+
hist = q(con, "SELECT floor(perplexity/5)*5 AS b, count(*) FROM f WHERE perplexity IS NOT NULL GROUP BY b ORDER BY b")
|
| 144 |
+
near_threshold = q(con, f"SELECT url, perplexity, chars_final, genre FROM f WHERE status='retained' AND perplexity >= 38 ORDER BY perplexity DESC LIMIT {sample_examples}")
|
| 145 |
+
low = q(con, f"SELECT url, perplexity, chars_final, genre FROM f WHERE status='retained' AND perplexity IS NOT NULL ORDER BY perplexity ASC LIMIT {sample_examples}")
|
| 146 |
+
report["item26_perplexity"] = {
|
| 147 |
+
"filter": {"applied_by": "Podtech(入力データセット abeja-cc-ja-filtered の作成時)", "model": "KenLM(lighttransport/japanese-scoring-model)", "threshold": "perplexity < 40 を保持",
|
| 148 |
+
"source_url": "https://huggingface.co/datasets/Podtech/abeja-cc-ja-filtered"},
|
| 149 |
+
"distribution_retained": {"min": quant[0], "p5": quant[1], "p25": quant[2], "p50": quant[3], "p75": quant[4], "p95": quant[5], "max": quant[6]},
|
| 150 |
+
"histogram_bin5": [{"bin_start": int(b), "records": n} for b, n in hist],
|
| 151 |
+
"examples_near_threshold_retained": [{"url": u, "perplexity": p, "chars": c, "genre": g} for u, p, c, g in near_threshold],
|
| 152 |
+
"examples_lowest_perplexity": [{"url": u, "perplexity": p, "chars": c, "genre": g} for u, p, c, g in low],
|
| 153 |
+
"note_ja": "閾値以上(除外側)の文書は入力データに含まれないため、除外例は配布元データ(S3 の原本)からの抽出が必要。ここでは保持側の分布と閾値付近の残存例を示す。",
|
| 154 |
+
}
|
| 155 |
+
else:
|
| 156 |
+
report["item26_perplexity"] = {"note_ja": "perplexity 列が無いため未集計"}
|
| 157 |
+
|
| 158 |
+
progress("item26")
|
| 159 |
+
# --- 27 文書長の分布(前後) ---
|
| 160 |
+
def dist(col: str, where: str) -> dict[str, Any]:
|
| 161 |
+
r = q1(con, f"SELECT count(*), min({col}), quantile_cont({col}, 0.05), quantile_cont({col}, 0.5), quantile_cont({col}, 0.95), max({col}), avg({col}), sum({col}) FROM f WHERE {where}")
|
| 162 |
+
return {"records": r[0], "min": r[1], "p5": r[2], "p50": r[3], "p95": r[4], "max": r[5], "mean": round(r[6], 1) if r[6] else None, "sum": r[7]}
|
| 163 |
+
by_genre_status = q(con, "SELECT genre, split_part(status, ':', 1) AS st, count(*) FROM f GROUP BY genre, st ORDER BY genre, st")
|
| 164 |
+
genre_rates: dict[str, dict[str, Any]] = {}
|
| 165 |
+
for g, st, n in by_genre_status:
|
| 166 |
+
genre_rates.setdefault(g, {"label_ja": GENRE_LABELS_JA.get(g, g), "records": 0})
|
| 167 |
+
genre_rates[g][st] = n
|
| 168 |
+
genre_rates[g]["records"] += n
|
| 169 |
+
for g, v in genre_rates.items():
|
| 170 |
+
v["deleted_rate"] = round((v.get("deleted_toxic", 0) + v.get("deleted_noise", 0) + v.get("deleted_guard", 0)) / max(1, v["records"]), 5)
|
| 171 |
+
report["item27_length"] = {
|
| 172 |
+
"chars_input_all": dist("chars_input", "chars_input IS NOT NULL"),
|
| 173 |
+
"chars_final_retained": dist("chars_final", "status = 'retained'"),
|
| 174 |
+
"chars_input_deleted_toxic": dist("chars_input", "status LIKE 'deleted_toxic%'"),
|
| 175 |
+
"chars_input_deleted_noise": dist("chars_input", "status LIKE 'deleted_noise%'"),
|
| 176 |
+
"chars_input_deleted_guard": dist("chars_input", "status LIKE 'deleted_guard%'") if guard_info else None,
|
| 177 |
+
"deletion_rate_by_genre": genre_rates,
|
| 178 |
+
"tokens_note_ja": "トークン数は方針によりトークナイザを指定しないため未集計(文字数のみ)。",
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
progress("item27")
|
| 182 |
+
# --- 28 低品質 ---
|
| 183 |
+
lq = q1(con, "SELECT count(*) FROM f WHERE status = 'retained' AND is_low_quality")[0]
|
| 184 |
+
flags = q(con, "SELECT flag, count(*) FROM (SELECT unnest(string_split(low_quality_flags, '|')) AS flag FROM f WHERE status = 'retained' AND low_quality_flags <> '') GROUP BY flag ORDER BY 2 DESC")
|
| 185 |
+
lq_by_genre = q(con, "SELECT genre, count(*), sum(CASE WHEN is_low_quality THEN 1 ELSE 0 END) FROM f WHERE status = 'retained' GROUP BY genre ORDER BY 2 DESC")
|
| 186 |
+
report["item28_low_quality"] = {
|
| 187 |
+
"definition_ja": "保持文書のうち次のいずれかに該当: " + "、".join(f"{k}({v})" for k, v in LOW_QUALITY_FLAGS_JA.items()),
|
| 188 |
+
"method_ja": "第2パスで文書ごとに決定的規則で判定(doc_features.py)。分類の妥当性はサンプルの目視で確認する。",
|
| 189 |
+
"records_retained": retained, "low_quality_records": lq, "low_quality_rate": round(lq / max(1, retained), 5),
|
| 190 |
+
"by_flag": [{"flag": f_, "label_ja": LOW_QUALITY_FLAGS_JA.get(f_, f_), "records": n, "ratio": round(n / max(1, retained), 5)} for f_, n in flags],
|
| 191 |
+
"by_genre": [{"genre": g, "label_ja": GENRE_LABELS_JA.get(g, g), "records": n, "low_quality": m, "rate": round(m / max(1, n), 4)} for g, n, m in lq_by_genre],
|
| 192 |
+
"previous_review_rate": previous_low_quality_rate,
|
| 193 |
+
"comparison_ja": (f"前回レビュー指摘値 {previous_low_quality_rate:.1%} に対し今回 {lq / max(1, retained):.1%}" if previous_low_quality_rate is not None else "前回レビューの指摘値が未入力のため比較なし"),
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
progress("item28")
|
| 197 |
+
# --- 29 ジャンル ---
|
| 198 |
+
genres = q(con, "SELECT genre, count(*) FROM f WHERE status = 'retained' GROUP BY genre ORDER BY 2 DESC")
|
| 199 |
+
manufacturing = q1(con, "SELECT count(*) FROM f WHERE status = 'retained' AND manufacturing_score >= 2.0")[0]
|
| 200 |
+
report["item29_genre"] = {
|
| 201 |
+
"method_ja": "wordlists/genre/genre_rules.json の URL 規則と手がかり語で、1,000字あたりの異なり手がかり語数をスコア化(しきい値2.0)。製造業・重工の適合スコアは独立に算出。",
|
| 202 |
+
"distribution_retained": [{"genre": g, "label_ja": GENRE_LABELS_JA.get(g, g), "records": n, "ratio": round(n / max(1, retained), 5)} for g, n in genres],
|
| 203 |
+
"manufacturing_relevant_records": manufacturing, "manufacturing_relevant_ratio": round(manufacturing / max(1, retained), 5),
|
| 204 |
+
"exclusion_decision": {"excluded_genres": exclude_genres, "note_ja": "除外するジャンルは方針として決める。除外する場合は第3パスで genre 列を条件に削除し、件数を記録する。"},
|
| 205 |
+
}
|
| 206 |
+
progress("item29")
|
| 207 |
+
if noise_glob:
|
| 208 |
+
report["noise_summaries_glob"] = noise_glob
|
| 209 |
+
return report
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def to_markdown(r: dict[str, Any]) -> str:
|
| 213 |
+
L: list[str] = []
|
| 214 |
+
L.append("# 品質監査報告(E 重複・F 言語/品質・G ドメイン適合)")
|
| 215 |
+
L.append("")
|
| 216 |
+
L.append(f"- 生成日時: {r['generated_at_utc']}")
|
| 217 |
+
L.append(f"- 対象文書: {r['records_total']:,}(保持 {r['records_retained']:,})")
|
| 218 |
+
L.append("")
|
| 219 |
+
if r.get("guard_pass"):
|
| 220 |
+
g = r["guard_pass"]
|
| 221 |
+
L.append("## 第3パス(分類器による削除)の反映")
|
| 222 |
+
L.append("")
|
| 223 |
+
L.append(f"- {g['note_ja']}")
|
| 224 |
+
L.append(f"- 削除記録 {g['records_in_guard_removed']:,} 件、features に突合できた件数 {g['records_matched_to_features']:,}")
|
| 225 |
+
L.append("- カテゴリ別: " + ", ".join(f"{x['category']} {x['records']:,}" for x in g["by_category"]))
|
| 226 |
+
L.append("")
|
| 227 |
+
d = r["item22_dedup"]
|
| 228 |
+
L.append("## 項目22: 重複除去")
|
| 229 |
+
L.append("")
|
| 230 |
+
L.append(f"- 配布元の実施: {d['upstream']['performed_by']}")
|
| 231 |
+
for m in d["upstream"]["methods"]:
|
| 232 |
+
L.append(f" - {m['method']}(閾値: {m['threshold']})")
|
| 233 |
+
L.append("- 出典: " + ", ".join(d["upstream"]["source_urls"]))
|
| 234 |
+
L.append(f"- 判断: {d['upstream']['decision_ja']}")
|
| 235 |
+
e = d["exact_duplicate_check"]
|
| 236 |
+
L.append(f"- 完全一致の再確認({e['scope']}): 本文 SHA-1 重複 {e['content_sha1_duplicates']:,}({e['content_sha1_duplicate_rate']:.4%})、URL 重複 {e['url_duplicates']:,}")
|
| 237 |
+
L.append("")
|
| 238 |
+
l = r["item25_language"]
|
| 239 |
+
L.append("## 項目25: 言語判定")
|
| 240 |
+
L.append("")
|
| 241 |
+
L.append(f"- ツール: {l['tool']}。対象: {l['scope']}")
|
| 242 |
+
L.append(f"- 日本語比率: {l['japanese_ratio']:.4%}。混在文書({l['mixed_definition']}): {l['mixed_language_records']:,}")
|
| 243 |
+
L.append("- 処理: " + "、".join(f"{k}: {v}" for k, v in l["processing"].items()))
|
| 244 |
+
L.append("")
|
| 245 |
+
L.append("| 言語 | 文書数 | 比率 |")
|
| 246 |
+
L.append("|---|---:|---:|")
|
| 247 |
+
for x in l["distribution"][:8]:
|
| 248 |
+
L.append(f"| {x['lang']} | {x['records']:,} | {x['ratio']:.4%} |")
|
| 249 |
+
L.append("")
|
| 250 |
+
p = r["item26_perplexity"]
|
| 251 |
+
L.append("## 項目26: perplexity フィルタ")
|
| 252 |
+
L.append("")
|
| 253 |
+
if "filter" in p:
|
| 254 |
+
L.append(f"- 適用者: {p['filter']['applied_by']}、モデル: {p['filter']['model']}、閾値: {p['filter']['threshold']}({p['filter']['source_url']})")
|
| 255 |
+
ds = p["distribution_retained"]
|
| 256 |
+
L.append(f"- 保持側の分布: min {ds['min']:.1f} / p5 {ds['p5']:.1f} / p50 {ds['p50']:.1f} / p95 {ds['p95']:.1f} / max {ds['max']:.1f}")
|
| 257 |
+
L.append("- ヒストグラム(5刻み): " + ", ".join(f"{h['bin_start']}-{h['bin_start']+5}: {h['records']:,}" for h in p["histogram_bin5"]))
|
| 258 |
+
L.append("- 閾値付近の残存例:")
|
| 259 |
+
for x in p["examples_near_threshold_retained"]:
|
| 260 |
+
L.append(f" - {x['url'][:90]} (ppl {x['perplexity']:.1f}, {x['chars']}字, {x['genre']})")
|
| 261 |
+
L.append(f"- 注記: {p['note_ja']}")
|
| 262 |
+
else:
|
| 263 |
+
L.append(f"- {p['note_ja']}")
|
| 264 |
+
L.append("")
|
| 265 |
+
n = r["item27_length"]
|
| 266 |
+
L.append("## 項目27: 文書長の分布(フィルタ前後)")
|
| 267 |
+
L.append("")
|
| 268 |
+
L.append("| 区分 | 文書数 | min | p5 | p50 | p95 | max | 平均 |")
|
| 269 |
+
L.append("|---|---:|---:|---:|---:|---:|---:|---:|")
|
| 270 |
+
for key, label in (("chars_input_all", "入力(全件)"), ("chars_final_retained", "最終(保持)"), ("chars_input_deleted_toxic", "有害フィルタで削除"), ("chars_input_deleted_noise", "ノイズで削除")):
|
| 271 |
+
x = n[key]
|
| 272 |
+
if x["records"]:
|
| 273 |
+
L.append(f"| {label} | {x['records']:,} | {x['min']:.0f} | {x['p5']:.0f} | {x['p50']:.0f} | {x['p95']:.0f} | {x['max']:.0f} | {x['mean']} |")
|
| 274 |
+
L.append("")
|
| 275 |
+
L.append("ジャンル別の削除率(特定ジャンルだけが大量に落ちていないかの確認):")
|
| 276 |
+
L.append("")
|
| 277 |
+
L.append("| ジャンル | 文書数 | 有害で削除 | ノイズで削除 | 削除率 |")
|
| 278 |
+
L.append("|---|---:|---:|---:|---:|")
|
| 279 |
+
for g, v in sorted(n["deletion_rate_by_genre"].items(), key=lambda kv: -kv[1]["records"]):
|
| 280 |
+
L.append(f"| {v['label_ja']} | {v['records']:,} | {v.get('deleted_toxic', 0):,} | {v.get('deleted_noise', 0):,} | {v['deleted_rate']:.2%} |")
|
| 281 |
+
L.append(f"\n{n['tokens_note_ja']}")
|
| 282 |
+
L.append("")
|
| 283 |
+
lq = r["item28_low_quality"]
|
| 284 |
+
L.append("## 項目28: 低品質ページ")
|
| 285 |
+
L.append("")
|
| 286 |
+
L.append(f"- 定義: {lq['definition_ja']}")
|
| 287 |
+
L.append(f"- 方法: {lq['method_ja']}")
|
| 288 |
+
L.append(f"- 比率: {lq['low_quality_records']:,} / {lq['records_retained']:,} = {lq['low_quality_rate']:.2%}。{lq['comparison_ja']}")
|
| 289 |
+
L.append("")
|
| 290 |
+
L.append("| 該当条件 | 文書数 | 比率 |")
|
| 291 |
+
L.append("|---|---:|---:|")
|
| 292 |
+
for x in lq["by_flag"]:
|
| 293 |
+
L.append(f"| {x['label_ja']} | {x['records']:,} | {x['ratio']:.2%} |")
|
| 294 |
+
L.append("")
|
| 295 |
+
g = r["item29_genre"]
|
| 296 |
+
L.append("## 項目29: 無関係ジャンルの比率")
|
| 297 |
+
L.append("")
|
| 298 |
+
L.append(f"- 方法: {g['method_ja']}")
|
| 299 |
+
L.append("")
|
| 300 |
+
L.append("| ジャンル | 文書数 | 比率 |")
|
| 301 |
+
L.append("|---|---:|---:|")
|
| 302 |
+
for x in g["distribution_retained"]:
|
| 303 |
+
L.append(f"| {x['label_ja']} | {x['records']:,} | {x['ratio']:.2%} |")
|
| 304 |
+
L.append("")
|
| 305 |
+
L.append(f"- 製造業・重工に適合(スコア2.0以上): {g['manufacturing_relevant_records']:,}({g['manufacturing_relevant_ratio']:.2%})")
|
| 306 |
+
L.append(f"- 除外の判断: 除外ジャンル = {g['exclusion_decision']['excluded_genres'] or 'なし'}。{g['exclusion_decision']['note_ja']}")
|
| 307 |
+
L.append("")
|
| 308 |
+
return "\n".join(L) + "\n"
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def main(argv: list[str] | None = None) -> None:
|
| 312 |
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 313 |
+
parser.add_argument("--features-glob", required=True, help="features.parquet の glob(DuckDB 形式、例: /cleaned/outputs_v2/**/features.parquet)")
|
| 314 |
+
parser.add_argument("--noise-summaries-glob", default=None)
|
| 315 |
+
parser.add_argument("--output-dir", type=Path, required=True)
|
| 316 |
+
parser.add_argument("--previous-low-quality-rate", type=float, default=None, help="前回レビューの低品質比率(0〜1)")
|
| 317 |
+
parser.add_argument("--exclude-genres", default="", help="除外を決めたジャンル(カンマ区切り、記録用)")
|
| 318 |
+
parser.add_argument("--threads", type=int, default=None, help="DuckDB のスレッド数(既定は CPU 数)")
|
| 319 |
+
parser.add_argument("--temp-dir", default=None, help="DuckDB の一時ディレクトリ(メモリに収まらない集計の退避先)")
|
| 320 |
+
parser.add_argument("--memory-limit", default=None, help="DuckDB のメモリ上限(例: 40GB)")
|
| 321 |
+
parser.add_argument("--guard-removed-glob", default=None, help="第3パスの guard_removed.jsonl の glob(指定すると分類器の削除を反映した件数で集計)")
|
| 322 |
+
args = parser.parse_args(argv)
|
| 323 |
+
excluded = [x for x in args.exclude_genres.split(",") if x]
|
| 324 |
+
settings = {"threads": args.threads, "temp_directory": args.temp_dir, "memory_limit": args.memory_limit}
|
| 325 |
+
report = build(args.features_glob, args.noise_summaries_glob, args.previous_low_quality_rate, excluded, db_settings=settings,
|
| 326 |
+
guard_removed_glob=args.guard_removed_glob)
|
| 327 |
+
args.output_dir.mkdir(parents=True, exist_ok=True)
|
| 328 |
+
(args.output_dir / "quality_report.json").write_text(json.dumps(report, ensure_ascii=False, indent=2, default=str) + "\n", encoding="utf-8")
|
| 329 |
+
(args.output_dir / "quality_report.md").write_text(to_markdown(report), encoding="utf-8")
|
| 330 |
+
print(json.dumps({"records_total": report["records_total"], "retained": report["records_retained"],
|
| 331 |
+
"japanese_ratio": report["item25_language"]["japanese_ratio"], "low_quality_rate": report["item28_low_quality"]["low_quality_rate"],
|
| 332 |
+
"manufacturing_ratio": report["item29_genre"]["manufacturing_relevant_ratio"], "output": str(args.output_dir)}, ensure_ascii=False))
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
if __name__ == "__main__":
|
| 336 |
+
main()
|
code/3c1a8da-dirty-bd01fd79/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/3c1a8da-dirty-bd01fd79/src/run_guard_pass.py
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""第3パス: 辞書の語が1語以上ある文書に Qwen3Guard を適用し、有害と判定された文書を削除する。
|
| 2 |
+
|
| 3 |
+
背景: 第1パスの辞書(同一カテゴリ3語以上)は、保持文書 3,000 件の無作為抽出で 0.7% が分類器 Unsafe、
|
| 4 |
+
うち性的コンテンツ 9 件は辞書の語が 1〜2 語しか一致しないため保持されていた。全 2 億文書に分類器を
|
| 5 |
+
当てるのは GPU 費用が大きいので、辞書の語が ``--min-terms`` 語以上一致する文書(候補)だけに適用する。
|
| 6 |
+
|
| 7 |
+
入力は第2パスの出力(``<prefix>/common_crawl_N/<shard>/<shard>.parquet``、列 url/content/perplexity)。
|
| 8 |
+
``--source-repo`` を指定すると HF から HTTP で取得する(マウントは使わない)。
|
| 9 |
+
|
| 10 |
+
削除規則: 安全性が ``Unsafe`` で、カテゴリが ``--delete-categories`` のいずれかに該当する文書を削除する。
|
| 11 |
+
``Controversial`` と、Politically Sensitive Topics / Copyright Violation / PII / Jailbreak のみの Unsafe は
|
| 12 |
+
保持して件数を記録する(監査基準では報道・解説・時事は有害としない)。
|
| 13 |
+
|
| 14 |
+
出力(シャードごと): ``<shard>.parquet``(保持文書)、``guard_removed.jsonl``(削除文書の URL・分類・抜粋)、
|
| 15 |
+
``guard_results.jsonl``(候補全件の判定)、``guard_summary.json``。
|
| 16 |
+
|
| 17 |
+
uv run python abeja-cc-ja/src/run_guard_pass.py --input-dir <第2パス出力/common_crawl_0> --output-root out --backend fake --limit-shards 1
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import argparse
|
| 23 |
+
import json
|
| 24 |
+
import os
|
| 25 |
+
import shutil
|
| 26 |
+
import time
|
| 27 |
+
import traceback
|
| 28 |
+
from concurrent.futures import Future, ProcessPoolExecutor
|
| 29 |
+
from collections import Counter
|
| 30 |
+
from datetime import datetime, timezone
|
| 31 |
+
from pathlib import Path
|
| 32 |
+
from typing import Any
|
| 33 |
+
|
| 34 |
+
import pyarrow as pa
|
| 35 |
+
import pyarrow.parquet as pq
|
| 36 |
+
|
| 37 |
+
from filter_toxic import CATEGORIES, KeywordMatcher, _distinct_terms_by_category, load_wordlists
|
| 38 |
+
from guard_classifier import DEFAULT_MODEL, make_backend, parse
|
| 39 |
+
from run_shard import Uploader
|
| 40 |
+
|
| 41 |
+
GUARD_PASS_VERSION = "abeja-cc-ja-guard/2026-09-06"
|
| 42 |
+
DEFAULT_DELETE_CATEGORIES = ("Sexual Content or Sexual Acts", "Violent", "Suicide & Self-Harm", "Non-violent Illegal Acts", "Unethical Acts")
|
| 43 |
+
RECORD_ONLY_CATEGORIES = ("Politically Sensitive Topics", "Copyright Violation", "PII", "Jailbreak")
|
| 44 |
+
|
| 45 |
+
_MATCHER: KeywordMatcher | None = None
|
| 46 |
+
_CONFIG: dict[str, Any] = {}
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _init_worker(config: dict[str, Any]) -> None:
|
| 50 |
+
global _MATCHER, _CONFIG
|
| 51 |
+
_CONFIG = config
|
| 52 |
+
wordlists = load_wordlists(Path(config["reference_dir"]), Path(config["additional_dir"]), Path(config["exclude_dir"]))
|
| 53 |
+
_MATCHER = KeywordMatcher(wordlists.terms, wordlists.sources)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _fetch_with_retry(repo: str, path_in_repo: str, local_dir: Path, attempts: int = 6) -> Path:
|
| 57 |
+
from huggingface_hub import hf_hub_download
|
| 58 |
+
|
| 59 |
+
last: Exception | None = None
|
| 60 |
+
for attempt in range(1, attempts + 1):
|
| 61 |
+
try:
|
| 62 |
+
return Path(hf_hub_download(repo, path_in_repo, repo_type="dataset", local_dir=str(local_dir)))
|
| 63 |
+
except Exception as error: # noqa: BLE001
|
| 64 |
+
last = error
|
| 65 |
+
print(json.dumps({"event": "download_retry", "path": path_in_repo, "attempt": attempt, "error": repr(error)[:160]}), flush=True)
|
| 66 |
+
time.sleep(20 * attempt)
|
| 67 |
+
raise RuntimeError(f"download failed: {path_in_repo} ({last!r})")
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def prepare_shard(task: dict[str, Any]) -> dict[str, Any]:
|
| 71 |
+
"""ワーカー側: 入力 parquet を取得して辞書照合し、候補の本文を返す。"""
|
| 72 |
+
|
| 73 |
+
assert _MATCHER is not None
|
| 74 |
+
started = time.perf_counter()
|
| 75 |
+
shard = task["shard"]
|
| 76 |
+
try:
|
| 77 |
+
if task.get("source_repo"):
|
| 78 |
+
local = _fetch_with_retry(task["source_repo"], task["path_in_repo"], Path(task["staging_dir"]))
|
| 79 |
+
else:
|
| 80 |
+
local = Path(task["input_path"])
|
| 81 |
+
table = pq.read_table(local, columns=["url", "content", "perplexity"])
|
| 82 |
+
urls = table.column("url").to_pylist()
|
| 83 |
+
contents = table.column("content").to_pylist()
|
| 84 |
+
min_terms = int(_CONFIG.get("min_terms", 1))
|
| 85 |
+
candidate_categories = set(_CONFIG.get("candidate_categories") or CATEGORIES)
|
| 86 |
+
max_chars = int(_CONFIG.get("max_chars", 2000))
|
| 87 |
+
candidates: list[dict[str, Any]] = []
|
| 88 |
+
match_docs = Counter()
|
| 89 |
+
for index, (url, content) in enumerate(zip(urls, contents)):
|
| 90 |
+
content = content or ""
|
| 91 |
+
distinct = _distinct_terms_by_category(_MATCHER.match_record(url, content))
|
| 92 |
+
if not distinct:
|
| 93 |
+
continue
|
| 94 |
+
for category in distinct:
|
| 95 |
+
match_docs[category] += 1
|
| 96 |
+
total = sum(len(terms) for category, terms in distinct.items() if category in candidate_categories)
|
| 97 |
+
if total >= min_terms:
|
| 98 |
+
candidates.append({"record_index": index, "url": url, "text": content[:max_chars],
|
| 99 |
+
"matches": {category: len(terms) for category, terms in distinct.items()}})
|
| 100 |
+
return {"shard": shard, "local_input": str(local), "staged": bool(task.get("source_repo")), "rows": table.num_rows,
|
| 101 |
+
"candidates": candidates, "match_docs_by_category": dict(match_docs), "prepare_seconds": round(time.perf_counter() - started, 1)}
|
| 102 |
+
except Exception as error: # noqa: BLE001
|
| 103 |
+
return {"shard": shard, "error": repr(error), "traceback": traceback.format_exc()}
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def classify_candidates(candidates: list[dict[str, Any]], backend: Any, chunk_size: int) -> None:
|
| 107 |
+
for start in range(0, len(candidates), chunk_size):
|
| 108 |
+
chunk = candidates[start : start + chunk_size]
|
| 109 |
+
raws = backend.classify([c["text"] for c in chunk])
|
| 110 |
+
for candidate, raw in zip(chunk, raws):
|
| 111 |
+
safety, categories = parse(raw)
|
| 112 |
+
candidate["safety"] = safety
|
| 113 |
+
candidate["categories"] = categories
|
| 114 |
+
candidate["raw_output"] = (raw or "").strip()
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def write_shard_outputs(prepared: dict[str, Any], output_root: Path, delete_categories: set[str], config: dict[str, Any],
|
| 118 |
+
classify_seconds: float) -> dict[str, Any]:
|
| 119 |
+
shard = prepared["shard"]
|
| 120 |
+
out_dir = output_root / shard
|
| 121 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 122 |
+
candidates = prepared["candidates"]
|
| 123 |
+
deleted_indices: set[int] = set()
|
| 124 |
+
by_safety = Counter()
|
| 125 |
+
deleted_by_category = Counter()
|
| 126 |
+
unsafe_kept_by_category = Counter()
|
| 127 |
+
controversial_by_category = Counter()
|
| 128 |
+
with (out_dir / "guard_results.jsonl").open("w", encoding="utf-8") as results, (out_dir / "guard_removed.jsonl").open("w", encoding="utf-8") as removed:
|
| 129 |
+
for c in candidates:
|
| 130 |
+
safety = c.get("safety")
|
| 131 |
+
categories = c.get("categories") or []
|
| 132 |
+
by_safety[safety or "unparsed"] += 1
|
| 133 |
+
delete = safety == "Unsafe" and any(cat in delete_categories for cat in categories)
|
| 134 |
+
if delete:
|
| 135 |
+
deleted_indices.add(c["record_index"])
|
| 136 |
+
for cat in categories:
|
| 137 |
+
deleted_by_category[cat] += 1
|
| 138 |
+
removed.write(json.dumps({"record_index": c["record_index"], "url": c["url"], "safety": safety, "categories": categories,
|
| 139 |
+
"dictionary_matches": c["matches"], "raw_output": c.get("raw_output", ""),
|
| 140 |
+
"excerpt": c["text"][:200]}, ensure_ascii=False) + "\n")
|
| 141 |
+
elif safety == "Unsafe":
|
| 142 |
+
for cat in categories or ["(none)"]:
|
| 143 |
+
unsafe_kept_by_category[cat] += 1
|
| 144 |
+
elif safety == "Controversial":
|
| 145 |
+
for cat in categories or ["(none)"]:
|
| 146 |
+
controversial_by_category[cat] += 1
|
| 147 |
+
results.write(json.dumps({"record_index": c["record_index"], "url": c["url"], "safety": safety, "categories": categories,
|
| 148 |
+
"dictionary_matches": c["matches"], "deleted": delete}, ensure_ascii=False) + "\n")
|
| 149 |
+
table = pq.read_table(prepared["local_input"], columns=["url", "content", "perplexity"])
|
| 150 |
+
if deleted_indices:
|
| 151 |
+
keep = pa.array([i not in deleted_indices for i in range(table.num_rows)], type=pa.bool_())
|
| 152 |
+
retained = table.filter(keep)
|
| 153 |
+
else:
|
| 154 |
+
retained = table
|
| 155 |
+
pq.write_table(retained, out_dir / f"{shard}.parquet", compression="zstd")
|
| 156 |
+
summary = {
|
| 157 |
+
"pipeline_version": GUARD_PASS_VERSION, "shard": shard, "stage": "guard",
|
| 158 |
+
"finished_at_utc": datetime.now(timezone.utc).isoformat(),
|
| 159 |
+
"input_rows": prepared["rows"], "candidates": len(candidates), "candidate_rate": round(len(candidates) / max(1, prepared["rows"]), 5),
|
| 160 |
+
"match_docs_by_category": prepared["match_docs_by_category"],
|
| 161 |
+
"by_safety": dict(by_safety),
|
| 162 |
+
"records_deleted": len(deleted_indices), "deletion_rate": round(len(deleted_indices) / max(1, prepared["rows"]), 6),
|
| 163 |
+
"deleted_by_category": dict(deleted_by_category),
|
| 164 |
+
"unsafe_kept_by_category": dict(unsafe_kept_by_category),
|
| 165 |
+
"controversial_by_category": dict(controversial_by_category),
|
| 166 |
+
"final_rows": retained.num_rows,
|
| 167 |
+
"seconds": {"prepare": prepared["prepare_seconds"], "classify": round(classify_seconds, 1)},
|
| 168 |
+
"docs_per_s": round(len(candidates) / classify_seconds, 2) if classify_seconds > 0 else None,
|
| 169 |
+
"thresholds": {"min_terms": config["min_terms"], "candidate_categories": sorted(config["candidate_categories"] or CATEGORIES),
|
| 170 |
+
"delete_categories": sorted(delete_categories), "record_only_categories": list(RECORD_ONLY_CATEGORIES),
|
| 171 |
+
"max_chars": config["max_chars"], "model": config["model"], "backend": config["backend"]},
|
| 172 |
+
}
|
| 173 |
+
(out_dir / "guard_summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
| 174 |
+
return summary
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def discover_local(input_dir: Path) -> list[dict[str, Any]]:
|
| 178 |
+
nested = sorted(p for p in input_dir.glob("*/*.parquet") if p.stem == p.parent.name)
|
| 179 |
+
flat = sorted(p for p in input_dir.glob("*.parquet"))
|
| 180 |
+
return [{"shard": p.stem, "input_path": str(p)} for p in (nested or flat)]
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def discover_repo(repo: str, prefix: str, dir_index: int, staging_dir: Path) -> list[dict[str, Any]]:
|
| 184 |
+
from huggingface_hub import HfApi
|
| 185 |
+
|
| 186 |
+
api = HfApi()
|
| 187 |
+
base = f"{prefix}/common_crawl_{dir_index}"
|
| 188 |
+
for attempt in range(5):
|
| 189 |
+
try:
|
| 190 |
+
entries = list(api.list_repo_tree(repo, path_in_repo=base, repo_type="dataset", recursive=False))
|
| 191 |
+
break
|
| 192 |
+
except Exception as error: # noqa: BLE001
|
| 193 |
+
print(json.dumps({"event": "list_retry", "attempt": attempt + 1, "error": repr(error)[:160]}), flush=True)
|
| 194 |
+
time.sleep(30 * (attempt + 1))
|
| 195 |
+
else:
|
| 196 |
+
raise RuntimeError("list_repo_tree failed")
|
| 197 |
+
shards = sorted(e.path.rsplit("/", 1)[-1] for e in entries if type(e).__name__ == "RepoFolder")
|
| 198 |
+
return [{"shard": s, "source_repo": repo, "path_in_repo": f"{base}/{s}/{s}.parquet", "staging_dir": str(staging_dir)} for s in shards]
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def main(argv: list[str] | None = None) -> None:
|
| 202 |
+
source_dir = Path(__file__).resolve().parent
|
| 203 |
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 204 |
+
group = parser.add_mutually_exclusive_group(required=True)
|
| 205 |
+
group.add_argument("--input-dir", type=Path, help="第2パス出力のディレクトリ(<shard>/<shard>.parquet)")
|
| 206 |
+
group.add_argument("--source-repo", default=None, help="HF データセットから HTTP で取得する")
|
| 207 |
+
parser.add_argument("--source-prefix", default="outputs_v2")
|
| 208 |
+
parser.add_argument("--dir-index", type=int, default=None, help="--source-repo のとき common_crawl_N の N")
|
| 209 |
+
parser.add_argument("--staging-dir", type=Path, default=None)
|
| 210 |
+
parser.add_argument("--output-root", type=Path, required=True)
|
| 211 |
+
parser.add_argument("--limit-shards", type=int, default=None)
|
| 212 |
+
parser.add_argument("--shard-index", type=int, default=0, help="この番号のシャードだけ処理(分割実行用、0 始まり)")
|
| 213 |
+
parser.add_argument("--shard-count", type=int, default=1)
|
| 214 |
+
parser.add_argument("--workers", type=int, default=max(1, min(6, (os.cpu_count() or 2) - 1)), help="辞書照合の並列数(先読み)")
|
| 215 |
+
parser.add_argument("--prefetch", type=int, default=3, help="分類中に先読みするシャード数")
|
| 216 |
+
parser.add_argument("--backend", choices=("vllm", "transformers", "fake", "none"), default="vllm")
|
| 217 |
+
parser.add_argument("--model", default=DEFAULT_MODEL)
|
| 218 |
+
parser.add_argument("--device", default="auto")
|
| 219 |
+
parser.add_argument("--max-chars", type=int, default=2000, help="分類器に渡す本文の先頭文字数")
|
| 220 |
+
parser.add_argument("--chunk-size", type=int, default=512)
|
| 221 |
+
parser.add_argument("--min-terms", type=int, default=1, help="候補とする辞書の異なり語数(全カテゴリ合計)")
|
| 222 |
+
parser.add_argument("--candidate-categories", default="", help="候補判定に使うカテゴリ(カンマ区切り、既定は全カテゴリ)")
|
| 223 |
+
parser.add_argument("--delete-categories", default=",".join(DEFAULT_DELETE_CATEGORIES), help="Unsafe のうち削除するカテゴリ(カンマ区切り)")
|
| 224 |
+
parser.add_argument("--reference-dir", type=Path, default=source_dir / "wordlists" / "reference")
|
| 225 |
+
parser.add_argument("--additional-dir", type=Path, default=source_dir / "wordlists")
|
| 226 |
+
parser.add_argument("--exclude-dir", type=Path, default=source_dir / "wordlists" / "exclude")
|
| 227 |
+
parser.add_argument("--upload-repo", default=None)
|
| 228 |
+
parser.add_argument("--upload-prefix", default="outputs_v3")
|
| 229 |
+
parser.add_argument("--upload-batch", type=int, default=5)
|
| 230 |
+
parser.add_argument("--delete-local-after-upload", action="store_true")
|
| 231 |
+
parser.add_argument("--skip-existing-in-repo", action="store_true")
|
| 232 |
+
args = parser.parse_args(argv)
|
| 233 |
+
|
| 234 |
+
if args.source_repo:
|
| 235 |
+
if args.dir_index is None:
|
| 236 |
+
raise SystemExit("--source-repo には --dir-index が必要です")
|
| 237 |
+
staging = args.staging_dir or (args.output_root / "_staging")
|
| 238 |
+
staging.mkdir(parents=True, exist_ok=True)
|
| 239 |
+
tasks = discover_repo(args.source_repo, args.source_prefix, args.dir_index, staging)
|
| 240 |
+
else:
|
| 241 |
+
tasks = discover_local(args.input_dir)
|
| 242 |
+
if args.shard_count > 1:
|
| 243 |
+
tasks = [t for i, t in enumerate(tasks) if i % args.shard_count == args.shard_index]
|
| 244 |
+
if args.limit_shards is not None:
|
| 245 |
+
tasks = tasks[: args.limit_shards]
|
| 246 |
+
if not tasks:
|
| 247 |
+
raise FileNotFoundError("入力シャードが見つかりません")
|
| 248 |
+
args.output_root.mkdir(parents=True, exist_ok=True)
|
| 249 |
+
uploader = None
|
| 250 |
+
skip: set[str] = set()
|
| 251 |
+
if args.upload_repo:
|
| 252 |
+
uploader = Uploader(args.upload_repo, args.upload_prefix, args.output_root, args.upload_batch, args.delete_local_after_upload)
|
| 253 |
+
if args.skip_existing_in_repo:
|
| 254 |
+
skip = uploader.existing_shards(marker="guard_summary.json")
|
| 255 |
+
todo = [t for t in tasks if t["shard"] not in skip and not (args.output_root / t["shard"] / "guard_summary.json").exists()]
|
| 256 |
+
config = {
|
| 257 |
+
"reference_dir": str(args.reference_dir), "additional_dir": str(args.additional_dir), "exclude_dir": str(args.exclude_dir),
|
| 258 |
+
"min_terms": args.min_terms, "candidate_categories": [c for c in args.candidate_categories.split(",") if c] or None,
|
| 259 |
+
"max_chars": args.max_chars, "model": args.model, "backend": args.backend,
|
| 260 |
+
}
|
| 261 |
+
delete_categories = {c.strip() for c in args.delete_categories.split(",") if c.strip()}
|
| 262 |
+
print(json.dumps({"event": "start", "stage": "guard", "shards": len(todo), "skipped": len(tasks) - len(todo), "workers": args.workers,
|
| 263 |
+
"backend": args.backend, "model": args.model, "min_terms": args.min_terms, "max_chars": args.max_chars,
|
| 264 |
+
"delete_categories": sorted(delete_categories)}, ensure_ascii=False), flush=True)
|
| 265 |
+
backend = None if args.backend == "none" else make_backend(args.backend, args.model, args.max_chars, args.device)
|
| 266 |
+
run_started = time.perf_counter()
|
| 267 |
+
results: list[dict[str, Any]] = []
|
| 268 |
+
with ProcessPoolExecutor(max_workers=max(1, args.workers), initializer=_init_worker, initargs=(config,)) as pool:
|
| 269 |
+
pending: list[Future] = []
|
| 270 |
+
queue = list(todo)
|
| 271 |
+
while queue and len(pending) < max(1, args.prefetch):
|
| 272 |
+
pending.append(pool.submit(prepare_shard, queue.pop(0)))
|
| 273 |
+
while pending:
|
| 274 |
+
future = pending.pop(0)
|
| 275 |
+
prepared = future.result()
|
| 276 |
+
if queue:
|
| 277 |
+
pending.append(pool.submit(prepare_shard, queue.pop(0)))
|
| 278 |
+
if "error" in prepared:
|
| 279 |
+
print(json.dumps({"event": "error", "shard": prepared["shard"], "error": prepared["error"]}), flush=True)
|
| 280 |
+
results.append(prepared)
|
| 281 |
+
continue
|
| 282 |
+
started = time.perf_counter()
|
| 283 |
+
if backend is not None and prepared["candidates"]:
|
| 284 |
+
classify_candidates(prepared["candidates"], backend, args.chunk_size)
|
| 285 |
+
classify_seconds = time.perf_counter() - started
|
| 286 |
+
summary = write_shard_outputs(prepared, args.output_root, delete_categories, config, classify_seconds)
|
| 287 |
+
if prepared.get("staged"):
|
| 288 |
+
Path(prepared["local_input"]).unlink(missing_ok=True)
|
| 289 |
+
results.append(summary)
|
| 290 |
+
print(json.dumps({"event": "done", "shard": summary["shard"], "input_rows": summary["input_rows"], "candidates": summary["candidates"],
|
| 291 |
+
"deleted": summary["records_deleted"], "by_safety": summary["by_safety"], "seconds": summary["seconds"],
|
| 292 |
+
"docs_per_s": summary["docs_per_s"]}, ensure_ascii=False), flush=True)
|
| 293 |
+
if uploader is not None:
|
| 294 |
+
uploader.add(summary["shard"])
|
| 295 |
+
if uploader is not None:
|
| 296 |
+
uploader.flush()
|
| 297 |
+
errors = [r for r in results if "error" in r]
|
| 298 |
+
run_summary = {
|
| 299 |
+
"pipeline_version": GUARD_PASS_VERSION, "stage": "guard", "finished_at_utc": datetime.now(timezone.utc).isoformat(),
|
| 300 |
+
"shards_processed": len(results) - len(errors), "shards_failed": [{"shard": r["shard"], "error": r["error"]} for r in errors],
|
| 301 |
+
"shards_skipped": len(tasks) - len(todo), "seconds": round(time.perf_counter() - run_started, 1),
|
| 302 |
+
"upload_repo": args.upload_repo, "upload_prefix": args.upload_prefix if args.upload_repo else None,
|
| 303 |
+
}
|
| 304 |
+
(args.output_root / f"run_summary_guard_{datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')}.json").write_text(
|
| 305 |
+
json.dumps(run_summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
| 306 |
+
print(json.dumps({"event": "finish", **run_summary}, ensure_ascii=False), flush=True)
|
| 307 |
+
if args.source_repo and args.staging_dir is None:
|
| 308 |
+
shutil.rmtree(args.output_root / "_staging", ignore_errors=True)
|
| 309 |
+
if errors:
|
| 310 |
+
raise SystemExit(1)
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
if __name__ == "__main__":
|
| 314 |
+
main()
|
code/3c1a8da-dirty-bd01fd79/src/run_noise_pass.py
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ノイズ除去の第2パス(監査項目14〜21)。
|
| 2 |
+
|
| 3 |
+
第1パス(``run_shard.py``: 有害フィルタ → PII 置換)のクリーン済み出力
|
| 4 |
+
``<input-dir>/<shard>/<shard>.parquet`` を入力にし、``<output-root>/<shard>/`` に
|
| 5 |
+
``<shard>.parquet``(ノイズ除去後)、``noise/removed.jsonl``、``noise/summary.json``、
|
| 6 |
+
``noise_summary.json`` を書く。``--upload-repo`` を付けると HF データセットへ
|
| 7 |
+
バッチアップロードしてローカルを削除する(HF Jobs の一時ディスク対策)。
|
| 8 |
+
|
| 9 |
+
uv run python abeja-cc-ja/src/run_noise_pass.py --input-dir <outputs/common_crawl_0> --output-root <out> --workers 7 \\
|
| 10 |
+
--upload-repo Podtech/abeja-cc-ja-cleaned --upload-prefix outputs_v2/common_crawl_0 --delete-local-after-upload
|
| 11 |
+
|
| 12 |
+
トークン数の閾値を使う場合は ``--tokenizer <HFモデル名>`` と ``--min-tokens/--max-tokens`` を指定する
|
| 13 |
+
(transformers が必要。既定は文字数のみ)。
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import argparse
|
| 19 |
+
import json
|
| 20 |
+
import multiprocessing as mp
|
| 21 |
+
import os
|
| 22 |
+
import shutil
|
| 23 |
+
import time
|
| 24 |
+
import traceback
|
| 25 |
+
from datetime import datetime, timezone
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
from typing import Any
|
| 28 |
+
|
| 29 |
+
import pyarrow as pa
|
| 30 |
+
import pyarrow.parquet as pq
|
| 31 |
+
|
| 32 |
+
from run_shard import Uploader, stage_input
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
NOISE_PASS_VERSION = "abeja-cc-ja-noise-pass/2026-09-04"
|
| 36 |
+
_WORKER: dict[str, Any] = {}
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _init_worker(config: dict[str, Any]) -> None:
|
| 40 |
+
import sys
|
| 41 |
+
|
| 42 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 43 |
+
from doc_features import DocFeaturizer, LanguageDetector
|
| 44 |
+
from filter_noise import NoiseFilter
|
| 45 |
+
|
| 46 |
+
_WORKER["config"] = config
|
| 47 |
+
lid = LanguageDetector(Path(config["lid_model"])) if config.get("lid_model") else None
|
| 48 |
+
_WORKER["filter"] = NoiseFilter(
|
| 49 |
+
Path(config["patterns_dir"]),
|
| 50 |
+
min_chars=config["min_chars"], max_chars=config["max_chars"], newline_policy=config["newline_policy"],
|
| 51 |
+
tokenizer=config.get("tokenizer"), min_tokens=config.get("min_tokens"), max_tokens=config.get("max_tokens"),
|
| 52 |
+
language_detector=lid, drop_non_japanese=config.get("drop_non_japanese", True),
|
| 53 |
+
)
|
| 54 |
+
featurizer = DocFeaturizer(Path(config["genre_rules"]), None)
|
| 55 |
+
featurizer.lid = lid
|
| 56 |
+
_WORKER["featurizer"] = featurizer
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def process_shard(input_path: Path, output_root: Path, config: dict[str, Any]) -> dict[str, Any]:
|
| 60 |
+
from filter_noise import run_noise_filter
|
| 61 |
+
|
| 62 |
+
if not _WORKER:
|
| 63 |
+
_init_worker(config)
|
| 64 |
+
shard = input_path.stem
|
| 65 |
+
out_dir = output_root / shard
|
| 66 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 67 |
+
started = time.perf_counter()
|
| 68 |
+
started_at = datetime.now(timezone.utc).isoformat()
|
| 69 |
+
input_rows = pq.ParquetFile(input_path).metadata.num_rows
|
| 70 |
+
featurizer = _WORKER["featurizer"]
|
| 71 |
+
feature_rows: list[dict[str, Any]] = []
|
| 72 |
+
|
| 73 |
+
def on_record(row: dict[str, Any], result: Any, record_index: int) -> None:
|
| 74 |
+
status = "retained" if result.deleted_reason is None else f"deleted_noise:{result.deleted_reason}"
|
| 75 |
+
text = result.text if result.deleted_reason is None else (row.get("content") or "")
|
| 76 |
+
lang = (result.lang, result.lang_prob) if result.lang is not None else None
|
| 77 |
+
feature_rows.append(featurizer.features(row.get("url") or "", text, result.chars_before, status, record_index, row.get("perplexity"), lang))
|
| 78 |
+
|
| 79 |
+
summary = run_noise_filter(input_path, out_dir / "noise", _WORKER["filter"], batch_size=config["batch_size"], output_name="cleaned.parquet", on_record=on_record)
|
| 80 |
+
# 第1パスで有害フィルタにより削除された文書も、ジャンル別の削除率(項目27)のため特徴量を出す
|
| 81 |
+
toxic_removed = Path(config.get("source_dir") or input_path.parent) / "toxic" / "distinct_terms_3plus" / "removed.jsonl"
|
| 82 |
+
toxic_count = 0
|
| 83 |
+
if toxic_removed.exists():
|
| 84 |
+
with toxic_removed.open(encoding="utf-8") as handle:
|
| 85 |
+
for line in handle:
|
| 86 |
+
if not line.strip():
|
| 87 |
+
continue
|
| 88 |
+
record = json.loads(line)
|
| 89 |
+
content = record.get("content") or ""
|
| 90 |
+
reasons = "+".join(record.get("_filter_deleted_by") or [])
|
| 91 |
+
feature_rows.append(featurizer.features(record.get("url") or "", content, len(content), f"deleted_toxic:{reasons}", record.get("_filter_record_index", -1), record.get("perplexity")))
|
| 92 |
+
toxic_count += 1
|
| 93 |
+
if feature_rows:
|
| 94 |
+
pq.write_table(pa.Table.from_pylist(feature_rows), out_dir / "features.parquet", compression="zstd")
|
| 95 |
+
final_path = out_dir / f"{shard}.parquet"
|
| 96 |
+
shutil.move(str(out_dir / "noise" / "cleaned.parquet"), str(final_path))
|
| 97 |
+
shard_summary = {
|
| 98 |
+
"pipeline_version": NOISE_PASS_VERSION,
|
| 99 |
+
"stage": "noise",
|
| 100 |
+
"shard": shard,
|
| 101 |
+
"input_file": str(input_path),
|
| 102 |
+
"input_rows": input_rows,
|
| 103 |
+
"started_at_utc": started_at,
|
| 104 |
+
"finished_at_utc": datetime.now(timezone.utc).isoformat(),
|
| 105 |
+
"seconds": round(time.perf_counter() - started, 1),
|
| 106 |
+
"noise": {
|
| 107 |
+
"thresholds": summary["thresholds"],
|
| 108 |
+
"records_scanned": summary["records_scanned"],
|
| 109 |
+
"records_deleted": summary["records_deleted"],
|
| 110 |
+
"records_retained": summary["records_retained"],
|
| 111 |
+
"records_modified": summary["records_modified"],
|
| 112 |
+
"records_newline_joined": summary["records_newline_joined"],
|
| 113 |
+
"records_deleted_by_reason": summary["records_deleted_by_reason"],
|
| 114 |
+
"chars_before": summary["chars_before"],
|
| 115 |
+
"chars_after_retained": summary["chars_after_retained"],
|
| 116 |
+
"tokens_after_retained": summary["tokens_after_retained"],
|
| 117 |
+
"by_item": summary["by_item"],
|
| 118 |
+
"patterns": [
|
| 119 |
+
{k: p[k] for k in ("id", "item", "action", "records_detected", "occurrences", "lines_removed", "replacements")}
|
| 120 |
+
for p in summary["patterns"]
|
| 121 |
+
],
|
| 122 |
+
},
|
| 123 |
+
"features": {
|
| 124 |
+
"file": str(out_dir / "features.parquet"), "rows": len(feature_rows), "toxic_deleted_rows": toxic_count,
|
| 125 |
+
"describe": featurizer.describe(),
|
| 126 |
+
},
|
| 127 |
+
"output": {"cleaned_parquet": str(final_path), "final_rows": summary["records_retained"], "removed_jsonl": str(out_dir / "noise" / "removed.jsonl")},
|
| 128 |
+
}
|
| 129 |
+
(out_dir / "noise_summary.json").write_text(json.dumps(shard_summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
| 130 |
+
return shard_summary
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def _worker_entry(args: tuple[str, str, dict[str, Any]]) -> dict[str, Any]:
|
| 134 |
+
input_path, output_root, config = args
|
| 135 |
+
staging_dir = Path(config["staging_dir"]) if config.get("staging_dir") else None
|
| 136 |
+
local_input: Path | None = None
|
| 137 |
+
last_error: Exception | None = None
|
| 138 |
+
for attempt in range(1, 4):
|
| 139 |
+
try:
|
| 140 |
+
local_input = stage_input(Path(input_path), staging_dir)
|
| 141 |
+
# 有害フィルタの removed.jsonl は元のディレクトリから読むため、入力の場所を config で渡す
|
| 142 |
+
result = process_shard(local_input, Path(output_root), {**config, "source_dir": str(Path(input_path).parent)})
|
| 143 |
+
result["input_file"] = input_path
|
| 144 |
+
return result
|
| 145 |
+
except OSError as error:
|
| 146 |
+
last_error = error
|
| 147 |
+
print(json.dumps({"event": "io_retry", "shard": Path(input_path).stem, "attempt": attempt, "error": repr(error)[:160]}), flush=True)
|
| 148 |
+
time.sleep(30 * attempt)
|
| 149 |
+
except Exception as error: # noqa: BLE001
|
| 150 |
+
return {"shard": Path(input_path).stem, "input_file": input_path, "error": repr(error), "traceback": traceback.format_exc()}
|
| 151 |
+
finally:
|
| 152 |
+
if local_input is not None and staging_dir is not None and local_input != Path(input_path):
|
| 153 |
+
local_input.unlink(missing_ok=True)
|
| 154 |
+
return {"shard": Path(input_path).stem, "input_file": input_path, "error": repr(last_error), "traceback": ""}
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def discover_inputs(input_dir: Path) -> list[Path]:
|
| 158 |
+
"""``<dir>/<shard>/<shard>.parquet``(第1パス出力)か ``<dir>/*.parquet`` を列挙する。"""
|
| 159 |
+
|
| 160 |
+
nested = sorted(p for p in input_dir.glob("*/*.parquet") if p.stem == p.parent.name)
|
| 161 |
+
return nested or sorted(input_dir.glob("*.parquet"))
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def main(argv: list[str] | None = None) -> None:
|
| 165 |
+
source_dir = Path(__file__).resolve().parent
|
| 166 |
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 167 |
+
parser.add_argument("--input-dir", type=Path, required=True)
|
| 168 |
+
parser.add_argument("--output-root", type=Path, required=True)
|
| 169 |
+
parser.add_argument("--limit-shards", type=int, default=None)
|
| 170 |
+
parser.add_argument("--workers", type=int, default=max(1, (os.cpu_count() or 2) - 1))
|
| 171 |
+
parser.add_argument("--batch-size", type=int, default=2048)
|
| 172 |
+
parser.add_argument("--patterns-dir", type=Path, default=source_dir / "noise")
|
| 173 |
+
parser.add_argument("--min-chars", type=int, default=200)
|
| 174 |
+
parser.add_argument("--max-chars", type=int, default=100_000)
|
| 175 |
+
parser.add_argument("--newline-policy", choices=("join", "delete", "keep"), default="join")
|
| 176 |
+
parser.add_argument("--tokenizer", default=None, help="トークン数を数える HF トークナイザ名(任意)")
|
| 177 |
+
parser.add_argument("--lid-model", type=Path, default=source_dir.parent / "data" / "models" / "lid.176.ftz", help="fastText 言語判定モデル。無ければ言語判定を行わない")
|
| 178 |
+
parser.add_argument("--keep-non-japanese", action="store_true", help="日本語以外と判定された文書を削除しない(記録のみ)")
|
| 179 |
+
parser.add_argument("--genre-rules", type=Path, default=source_dir / "wordlists" / "genre" / "genre_rules.json")
|
| 180 |
+
parser.add_argument("--min-tokens", type=int, default=None)
|
| 181 |
+
parser.add_argument("--max-tokens", type=int, default=None)
|
| 182 |
+
parser.add_argument("--upload-repo", default=None)
|
| 183 |
+
parser.add_argument("--upload-prefix", default="outputs_v2")
|
| 184 |
+
parser.add_argument("--upload-batch", type=int, default=5)
|
| 185 |
+
parser.add_argument("--delete-local-after-upload", action="store_true")
|
| 186 |
+
parser.add_argument("--skip-existing-in-repo", action="store_true")
|
| 187 |
+
parser.add_argument("--staging-dir", type=Path, default=None, help="入力parquetを処理前にコピーするローカルディレクトリ(マウントの I/O エラー対策)")
|
| 188 |
+
args = parser.parse_args(argv)
|
| 189 |
+
|
| 190 |
+
inputs = discover_inputs(args.input_dir)
|
| 191 |
+
if args.limit_shards is not None:
|
| 192 |
+
inputs = inputs[: args.limit_shards]
|
| 193 |
+
if not inputs:
|
| 194 |
+
raise FileNotFoundError(f"入力parquetが見つかりません: {args.input_dir}")
|
| 195 |
+
args.output_root.mkdir(parents=True, exist_ok=True)
|
| 196 |
+
uploader = None
|
| 197 |
+
skip: set[str] = set()
|
| 198 |
+
if args.upload_repo:
|
| 199 |
+
uploader = Uploader(args.upload_repo, args.upload_prefix, args.output_root, args.upload_batch, args.delete_local_after_upload)
|
| 200 |
+
if args.skip_existing_in_repo:
|
| 201 |
+
skip = uploader.existing_shards(marker="noise_summary.json")
|
| 202 |
+
todo = []
|
| 203 |
+
for path in inputs:
|
| 204 |
+
if path.stem in skip or (args.output_root / path.stem / "noise_summary.json").exists():
|
| 205 |
+
print(json.dumps({"event": "skip", "shard": path.stem}), flush=True)
|
| 206 |
+
continue
|
| 207 |
+
todo.append(path)
|
| 208 |
+
config = {
|
| 209 |
+
"patterns_dir": str(args.patterns_dir), "batch_size": args.batch_size,
|
| 210 |
+
"min_chars": args.min_chars, "max_chars": args.max_chars, "newline_policy": args.newline_policy,
|
| 211 |
+
"tokenizer": args.tokenizer, "min_tokens": args.min_tokens, "max_tokens": args.max_tokens,
|
| 212 |
+
"lid_model": str(args.lid_model) if args.lid_model and args.lid_model.exists() else None,
|
| 213 |
+
"drop_non_japanese": not args.keep_non_japanese, "genre_rules": str(args.genre_rules),
|
| 214 |
+
"staging_dir": str(args.staging_dir) if args.staging_dir else None,
|
| 215 |
+
}
|
| 216 |
+
if config["lid_model"] is None:
|
| 217 |
+
print(json.dumps({"event": "warning", "message": f"言語判定モデルが見つからないため項目25の判定を行いません: {args.lid_model}"}, ensure_ascii=False), flush=True)
|
| 218 |
+
print(json.dumps({"event": "start", "stage": "noise", "shards": len(todo), "skipped": len(inputs) - len(todo), "workers": args.workers, "thresholds": config}, ensure_ascii=False), flush=True)
|
| 219 |
+
jobs = [(str(p), str(args.output_root), config) for p in todo]
|
| 220 |
+
if args.workers <= 1 or len(jobs) <= 1:
|
| 221 |
+
_init_worker(config)
|
| 222 |
+
iterator = map(_worker_entry, jobs)
|
| 223 |
+
else:
|
| 224 |
+
context = mp.get_context("spawn")
|
| 225 |
+
pool = context.Pool(processes=min(args.workers, len(jobs)), initializer=_init_worker, initargs=(config,))
|
| 226 |
+
iterator = pool.imap_unordered(_worker_entry, jobs)
|
| 227 |
+
results: list[dict[str, Any]] = []
|
| 228 |
+
run_started = time.perf_counter()
|
| 229 |
+
for result in iterator:
|
| 230 |
+
results.append(result)
|
| 231 |
+
if "error" in result:
|
| 232 |
+
print(json.dumps({"event": "error", "shard": result["shard"], "error": result["error"]}), flush=True)
|
| 233 |
+
continue
|
| 234 |
+
print(json.dumps({
|
| 235 |
+
"event": "done", "shard": result["shard"], "input_rows": result["input_rows"],
|
| 236 |
+
"noise_deleted": result["noise"]["records_deleted"], "modified": result["noise"]["records_modified"],
|
| 237 |
+
"final_rows": result["output"]["final_rows"], "seconds": result["seconds"],
|
| 238 |
+
}), flush=True)
|
| 239 |
+
if uploader is not None:
|
| 240 |
+
uploader.add(result["shard"])
|
| 241 |
+
if uploader is not None:
|
| 242 |
+
uploader.flush()
|
| 243 |
+
errors = [r for r in results if "error" in r]
|
| 244 |
+
run_summary = {
|
| 245 |
+
"pipeline_version": NOISE_PASS_VERSION, "stage": "noise",
|
| 246 |
+
"finished_at_utc": datetime.now(timezone.utc).isoformat(),
|
| 247 |
+
"shards_processed": len(results) - len(errors),
|
| 248 |
+
"shards_failed": [{"shard": r["shard"], "error": r["error"]} for r in errors],
|
| 249 |
+
"shards_skipped": len(inputs) - len(todo),
|
| 250 |
+
"seconds": round(time.perf_counter() - run_started, 1),
|
| 251 |
+
"upload_repo": args.upload_repo, "upload_prefix": args.upload_prefix if args.upload_repo else None,
|
| 252 |
+
}
|
| 253 |
+
(args.output_root / f"run_summary_noise_{datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')}.json").write_text(json.dumps(run_summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
| 254 |
+
print(json.dumps({"event": "finish", **run_summary}, ensure_ascii=False), flush=True)
|
| 255 |
+
if errors:
|
| 256 |
+
raise SystemExit(1)
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
if __name__ == "__main__":
|
| 260 |
+
main()
|
code/3c1a8da-dirty-bd01fd79/src/run_shard.py
ADDED
|
@@ -0,0 +1,368 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 stage_input(input_path: Path, staging_dir: Path | None, attempts: int = 5, wait_seconds: int = 20) -> Path:
|
| 151 |
+
"""マウントされたデータセット(FUSE)は読み取り中に I/O エラー(errno 5)を起こすことがあるため、
|
| 152 |
+
まずローカルディスクへコピーしてから処理する。コピー自体も再試行する。"""
|
| 153 |
+
|
| 154 |
+
if staging_dir is None:
|
| 155 |
+
return input_path
|
| 156 |
+
staging_dir.mkdir(parents=True, exist_ok=True)
|
| 157 |
+
local = staging_dir / input_path.name
|
| 158 |
+
last_error: Exception | None = None
|
| 159 |
+
for attempt in range(1, attempts + 1):
|
| 160 |
+
try:
|
| 161 |
+
shutil.copyfile(input_path, local)
|
| 162 |
+
if local.stat().st_size == input_path.stat().st_size:
|
| 163 |
+
return local
|
| 164 |
+
last_error = OSError(f"size mismatch after copy: {local}")
|
| 165 |
+
except OSError as error:
|
| 166 |
+
last_error = error
|
| 167 |
+
print(json.dumps({"event": "stage_retry", "shard": input_path.stem, "attempt": attempt, "error": repr(last_error)[:160]}), flush=True)
|
| 168 |
+
time.sleep(wait_seconds * attempt)
|
| 169 |
+
raise OSError(f"入力の退避に失敗しました: {input_path} ({last_error!r})")
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def _worker_entry(args: tuple[str, str, dict[str, Any]]) -> dict[str, Any]:
|
| 173 |
+
input_path, output_root, config = args
|
| 174 |
+
staging_dir = Path(config["staging_dir"]) if config.get("staging_dir") else None
|
| 175 |
+
local_input: Path | None = None
|
| 176 |
+
last_error: Exception | None = None
|
| 177 |
+
for attempt in range(1, 4):
|
| 178 |
+
try:
|
| 179 |
+
local_input = stage_input(Path(input_path), staging_dir)
|
| 180 |
+
result = process_shard(local_input, Path(output_root), config)
|
| 181 |
+
result["input_file"] = input_path
|
| 182 |
+
return result
|
| 183 |
+
except OSError as error: # マウント由来の I/O エラーは間を置いて再試行
|
| 184 |
+
last_error = error
|
| 185 |
+
print(json.dumps({"event": "io_retry", "shard": Path(input_path).stem, "attempt": attempt, "error": repr(error)[:160]}), flush=True)
|
| 186 |
+
time.sleep(30 * attempt)
|
| 187 |
+
except Exception as error: # noqa: BLE001 - 1シャードの失敗で全体を止めない
|
| 188 |
+
return {"shard": Path(input_path).stem, "input_file": input_path, "error": repr(error), "traceback": traceback.format_exc()}
|
| 189 |
+
finally:
|
| 190 |
+
if local_input is not None and staging_dir is not None and local_input != Path(input_path):
|
| 191 |
+
local_input.unlink(missing_ok=True)
|
| 192 |
+
return {"shard": Path(input_path).stem, "input_file": input_path, "error": repr(last_error), "traceback": ""}
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
class Uploader:
|
| 196 |
+
"""完了したシャードのディレクトリをまとめて HF データセットへアップロードする。"""
|
| 197 |
+
|
| 198 |
+
def __init__(self, repo_id: str, prefix: str, output_root: Path, batch: int, delete_local: bool, private: bool = True) -> None:
|
| 199 |
+
from huggingface_hub import HfApi
|
| 200 |
+
|
| 201 |
+
self.api = HfApi()
|
| 202 |
+
self.repo_id = repo_id
|
| 203 |
+
self.prefix = prefix.strip("/")
|
| 204 |
+
self.output_root = output_root
|
| 205 |
+
self.batch = max(1, batch)
|
| 206 |
+
self.delete_local = delete_local
|
| 207 |
+
self.pending: list[str] = []
|
| 208 |
+
self.uploaded: list[str] = []
|
| 209 |
+
self.api.create_repo(repo_id, repo_type="dataset", private=private, exist_ok=True)
|
| 210 |
+
|
| 211 |
+
def existing_shards(self, marker: str = "shard_summary.json") -> set[str]:
|
| 212 |
+
"""接頭辞直下のディレクトリ名を返す。全ファイル一覧はリポジトリが数万ファイルになると数分かかるため使わない。
|
| 213 |
+
シャードは upload_folder で1コミットにまとめるので、ディレクトリの存在=完了とみなす。"""
|
| 214 |
+
|
| 215 |
+
for attempt in range(5):
|
| 216 |
+
try:
|
| 217 |
+
entries = self.api.list_repo_tree(self.repo_id, path_in_repo=self.prefix, repo_type="dataset", recursive=False)
|
| 218 |
+
return {e.path.rsplit("/", 1)[-1] for e in entries if type(e).__name__ == "RepoFolder"}
|
| 219 |
+
except Exception as error: # noqa: BLE001
|
| 220 |
+
if "404" in repr(error) or "not found" in repr(error).lower():
|
| 221 |
+
return set()
|
| 222 |
+
time.sleep(30 * (attempt + 1))
|
| 223 |
+
raise RuntimeError("list_repo_tree failed after retries")
|
| 224 |
+
|
| 225 |
+
def add(self, shard: str) -> None:
|
| 226 |
+
self.pending.append(shard)
|
| 227 |
+
if len(self.pending) >= self.batch:
|
| 228 |
+
self.flush()
|
| 229 |
+
|
| 230 |
+
def flush(self) -> None:
|
| 231 |
+
if not self.pending:
|
| 232 |
+
return
|
| 233 |
+
shards = list(self.pending)
|
| 234 |
+
for attempt in range(5):
|
| 235 |
+
try:
|
| 236 |
+
self.api.upload_folder(
|
| 237 |
+
repo_id=self.repo_id,
|
| 238 |
+
repo_type="dataset",
|
| 239 |
+
folder_path=str(self.output_root),
|
| 240 |
+
path_in_repo=self.prefix,
|
| 241 |
+
allow_patterns=[f"{shard}/**" for shard in shards],
|
| 242 |
+
commit_message=f"add {len(shards)} shard(s): {shards[0]}..{shards[-1]}",
|
| 243 |
+
)
|
| 244 |
+
break
|
| 245 |
+
except Exception as error: # noqa: BLE001
|
| 246 |
+
wait = 30 * (attempt + 1)
|
| 247 |
+
print(json.dumps({"event": "upload_retry", "attempt": attempt + 1, "error": repr(error), "wait_s": wait}), flush=True)
|
| 248 |
+
time.sleep(wait)
|
| 249 |
+
else:
|
| 250 |
+
raise RuntimeError(f"アップロードに失敗しました: {shards}")
|
| 251 |
+
self.uploaded.extend(shards)
|
| 252 |
+
self.pending.clear()
|
| 253 |
+
print(json.dumps({"event": "uploaded", "shards": shards, "repo": self.repo_id, "prefix": self.prefix}), flush=True)
|
| 254 |
+
if self.delete_local:
|
| 255 |
+
for shard in shards:
|
| 256 |
+
shutil.rmtree(self.output_root / shard, ignore_errors=True)
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def main(argv: list[str] | None = None) -> None:
|
| 260 |
+
source_dir = Path(__file__).resolve().parent
|
| 261 |
+
project_root = source_dir.parent
|
| 262 |
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 263 |
+
group = parser.add_mutually_exclusive_group(required=True)
|
| 264 |
+
group.add_argument("--input", type=Path, action="append", help="入力parquet(複数可)")
|
| 265 |
+
group.add_argument("--input-dir", type=Path, help="入力parquetのディレクトリ")
|
| 266 |
+
parser.add_argument("--pattern", default="*.parquet")
|
| 267 |
+
parser.add_argument("--limit-shards", type=int, default=None, help="先頭N件だけ処理する(試運転用)")
|
| 268 |
+
parser.add_argument("--output-root", type=Path, required=True)
|
| 269 |
+
parser.add_argument("--workers", type=int, default=max(1, (os.cpu_count() or 2) - 1))
|
| 270 |
+
parser.add_argument("--batch-size", type=int, default=2048)
|
| 271 |
+
parser.add_argument("--keep-intermediate", action="store_true", help="有害フィルタ後の retained.parquet を残す")
|
| 272 |
+
parser.add_argument("--reference-dir", type=Path, default=source_dir / "wordlists" / "reference")
|
| 273 |
+
parser.add_argument("--additional-dir", type=Path, default=source_dir / "wordlists")
|
| 274 |
+
parser.add_argument("--exclude-dir", type=Path, default=source_dir / "wordlists" / "exclude")
|
| 275 |
+
parser.add_argument("--blocklist-dir", type=Path, default=source_dir / "blocklists")
|
| 276 |
+
parser.add_argument("--blocklist-cache-dir", type=Path, default=project_root / "data" / "blocklists" / "ut1")
|
| 277 |
+
parser.add_argument("--no-blocklist", action="store_true")
|
| 278 |
+
parser.add_argument("--cooccurrence-rules", type=Path, default=source_dir / "wordlists" / "cooccurrence" / "rules.json")
|
| 279 |
+
parser.add_argument("--no-cooccurrence", action="store_true")
|
| 280 |
+
parser.add_argument("--policy-approver", default=None)
|
| 281 |
+
parser.add_argument("--policy-approved-on", default=None)
|
| 282 |
+
parser.add_argument("--policy-note", default=None)
|
| 283 |
+
parser.add_argument("--upload-repo", default=None, help="出力先の HF データセット(例: Podtech/abeja-cc-ja-cleaned)。非公開で作成する")
|
| 284 |
+
parser.add_argument("--upload-prefix", default="outputs", help="リポジトリ内のパス接頭辞(例: outputs/common_crawl_0)")
|
| 285 |
+
parser.add_argument("--upload-batch", type=int, default=5, help="何シャードごとに1コミットでアップロードするか")
|
| 286 |
+
parser.add_argument("--delete-local-after-upload", action="store_true")
|
| 287 |
+
parser.add_argument("--skip-existing-in-repo", action="store_true", help="リポジトリに shard_summary.json があるシャードを飛ばす")
|
| 288 |
+
parser.add_argument("--staging-dir", type=Path, default=None, help="入力parquetを処理前にコピーするローカルディレクトリ(マウントの I/O エラー対策)")
|
| 289 |
+
args = parser.parse_args(argv)
|
| 290 |
+
|
| 291 |
+
if args.input_dir:
|
| 292 |
+
inputs = sorted(args.input_dir.glob(args.pattern))
|
| 293 |
+
else:
|
| 294 |
+
inputs = list(args.input)
|
| 295 |
+
if args.limit_shards is not None:
|
| 296 |
+
inputs = inputs[: args.limit_shards]
|
| 297 |
+
if not inputs:
|
| 298 |
+
raise FileNotFoundError("入力parquetが見つかりません")
|
| 299 |
+
args.output_root.mkdir(parents=True, exist_ok=True)
|
| 300 |
+
|
| 301 |
+
uploader = None
|
| 302 |
+
skip: set[str] = set()
|
| 303 |
+
if args.upload_repo:
|
| 304 |
+
uploader = Uploader(args.upload_repo, args.upload_prefix, args.output_root, args.upload_batch, args.delete_local_after_upload)
|
| 305 |
+
if args.skip_existing_in_repo:
|
| 306 |
+
skip = uploader.existing_shards()
|
| 307 |
+
todo = []
|
| 308 |
+
for path in inputs:
|
| 309 |
+
shard = path.stem
|
| 310 |
+
if shard in skip or (args.output_root / shard / "shard_summary.json").exists():
|
| 311 |
+
print(json.dumps({"event": "skip", "shard": shard}), flush=True)
|
| 312 |
+
continue
|
| 313 |
+
todo.append(path)
|
| 314 |
+
|
| 315 |
+
config = {
|
| 316 |
+
"batch_size": args.batch_size,
|
| 317 |
+
"keep_intermediate": args.keep_intermediate,
|
| 318 |
+
"reference_dir": str(args.reference_dir), "additional_dir": str(args.additional_dir), "exclude_dir": str(args.exclude_dir),
|
| 319 |
+
"blocklist_dir": str(args.blocklist_dir), "blocklist_cache_dir": str(args.blocklist_cache_dir), "no_blocklist": args.no_blocklist,
|
| 320 |
+
"cooccurrence_rules": str(args.cooccurrence_rules), "no_cooccurrence": args.no_cooccurrence,
|
| 321 |
+
"policy_approver": args.policy_approver, "policy_approved_on": args.policy_approved_on, "policy_note": args.policy_note,
|
| 322 |
+
"staging_dir": str(args.staging_dir) if args.staging_dir else None,
|
| 323 |
+
}
|
| 324 |
+
run_started = time.perf_counter()
|
| 325 |
+
results: list[dict[str, Any]] = []
|
| 326 |
+
print(json.dumps({"event": "start", "shards": len(todo), "skipped": len(inputs) - len(todo), "workers": args.workers, "output_root": str(args.output_root)}), flush=True)
|
| 327 |
+
jobs = [(str(path), str(args.output_root), config) for path in todo]
|
| 328 |
+
if args.workers <= 1 or len(jobs) <= 1:
|
| 329 |
+
_init_worker(config)
|
| 330 |
+
iterator = map(_worker_entry, jobs)
|
| 331 |
+
else:
|
| 332 |
+
# pyarrow がスレッドを持つため fork は子プロセスのデッドロック要因になる。spawn で各ワーカーが独立に読み込む。
|
| 333 |
+
context = mp.get_context("spawn")
|
| 334 |
+
pool = context.Pool(processes=min(args.workers, len(jobs)), initializer=_init_worker, initargs=(config,))
|
| 335 |
+
iterator = pool.imap_unordered(_worker_entry, jobs)
|
| 336 |
+
for result in iterator:
|
| 337 |
+
results.append(result)
|
| 338 |
+
if "error" in result:
|
| 339 |
+
print(json.dumps({"event": "error", "shard": result["shard"], "error": result["error"]}), flush=True)
|
| 340 |
+
continue
|
| 341 |
+
print(json.dumps({
|
| 342 |
+
"event": "done", "shard": result["shard"], "input_rows": result["input_rows"],
|
| 343 |
+
"toxic_deleted": result["toxic"]["records_deleted"], "pii_replacements": result["pii"]["total_replacements"],
|
| 344 |
+
"final_rows": result["output"]["final_rows"], "seconds": result["seconds"]["total"],
|
| 345 |
+
}, ensure_ascii=False), flush=True)
|
| 346 |
+
if uploader is not None:
|
| 347 |
+
uploader.add(result["shard"])
|
| 348 |
+
if uploader is not None:
|
| 349 |
+
uploader.flush()
|
| 350 |
+
errors = [r for r in results if "error" in r]
|
| 351 |
+
run_summary = {
|
| 352 |
+
"pipeline_version": PIPELINE_VERSION,
|
| 353 |
+
"finished_at_utc": datetime.now(timezone.utc).isoformat(),
|
| 354 |
+
"shards_processed": len(results) - len(errors),
|
| 355 |
+
"shards_failed": [{"shard": r["shard"], "error": r["error"]} for r in errors],
|
| 356 |
+
"shards_skipped": len(inputs) - len(todo),
|
| 357 |
+
"seconds": round(time.perf_counter() - run_started, 1),
|
| 358 |
+
"upload_repo": args.upload_repo,
|
| 359 |
+
"upload_prefix": args.upload_prefix if args.upload_repo else None,
|
| 360 |
+
}
|
| 361 |
+
(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")
|
| 362 |
+
print(json.dumps({"event": "finish", **run_summary}, ensure_ascii=False), flush=True)
|
| 363 |
+
if errors:
|
| 364 |
+
raise SystemExit(1)
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
if __name__ == "__main__":
|
| 368 |
+
main()
|
code/3c1a8da-dirty-bd01fd79/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/3c1a8da-dirty-bd01fd79/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/3c1a8da-dirty-bd01fd79/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/3c1a8da-dirty-bd01fd79/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/3c1a8da-dirty-bd01fd79/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/3c1a8da-dirty-bd01fd79/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/3c1a8da-dirty-bd01fd79/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/3c1a8da-dirty-bd01fd79/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/3c1a8da-dirty-bd01fd79/src/wordlists/exclude/ja_crime_exclude.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 違法行為の手引きカテゴリの除外語。2026-09-04 のリスト再設計で汎用語(犯罪、drug など)を
|
| 2 |
+
# リスト自体から外したため、現時点では除外語なし。
|
code/3c1a8da-dirty-bd01fd79/src/wordlists/exclude/ja_discrimination_exclude.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 差別・ヘイト・誹謗中傷カテゴリの除外語。既存リストは書き換えず、ここに載せた語だけを照合対象から外す。
|
| 2 |
+
# 文書頻度 0.85%。「不具合」の内部一致がほぼ全て。
|
| 3 |
+
不具
|
| 4 |
+
# 文書頻度 0.14%。「詰めかけ」「諦めかけ」の内部一致が大半(妾のひらがな表記)。
|
| 5 |
+
めかけ
|
code/3c1a8da-dirty-bd01fd79/src/wordlists/exclude/ja_propaganda_conspiracy_exclude.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 過激な政治・宗教プロパガンダ・陰謀論カテゴリの除外語。現時点では除外語なし。
|
| 2 |
+
# 「カルト」「デマ」の単語内部一致(オカルト、オンデマンド)は文字種境界で防がれる。
|
code/3c1a8da-dirty-bd01fd79/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/3c1a8da-dirty-bd01fd79/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/3c1a8da-dirty-bd01fd79/src/wordlists/genre/genre_rules.json
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"description_ja": "監査項目28・29用のジャンル分類規則。URL のホスト・パスの正規表現と本文の手がかり語で、1,000文字あたりの異なり手がかり語数(スコア)を出し、しきい値以上で最大スコアのジャンルを付与する。どれにも達しなければ other。manufacturing は主用途(製造業・重工)への適合度で、他ジャンルと独立に記録する。",
|
| 3 |
+
"score_threshold": 2.0,
|
| 4 |
+
"manufacturing_threshold": 2.0,
|
| 5 |
+
"genres": {
|
| 6 |
+
"diary_blog": {
|
| 7 |
+
"label_ja": "日記ブログ",
|
| 8 |
+
"host_patterns": ["ameblo\\.jp", "blog\\.fc2\\.com", "[a-z0-9-]+\\.fc2\\.com$", "hatenablog\\.(?:com|jp)", "hateblo\\.jp", "hatenadiary\\.(?:com|jp)", "blog\\.livedoor\\.jp", "livedoor\\.biz", "seesaa\\.net", "exblog\\.jp", "blog\\.goo\\.ne\\.jp", "jugem\\.jp", "yaplog\\.jp", "cocolog-nifty\\.com", "blogspot\\.com", "blog\\.jp$", "blog\\.so-net\\.ne\\.jp", "plaza\\.rakuten\\.co\\.jp", "note\\.com"],
|
| 9 |
+
"host_weight": 1.5,
|
| 10 |
+
"cues": ["今日は", "今日の", "昨日は", "行ってきました", "食べました", "買いました", "見てきました", "作りました", "遊びに", "お出かけ", "お天気", "いい天気", "久しぶりに", "帰ってきました", "起きて", "寝ました", "娘", "息子", "旦那", "うちの", "我が家", "ランチ", "ディナー", "お昼", "晩ごはん", "晩御飯", "夕飯", "おやつ", "カフェ", "散歩", "日記", "ブログ", "更新", "ポチッと", "ランキングに参加", "応援クリック", "読者登録"]
|
| 11 |
+
},
|
| 12 |
+
"affiliate": {
|
| 13 |
+
"label_ja": "投資・美容・健康のアフィリエイト",
|
| 14 |
+
"host_patterns": [],
|
| 15 |
+
"host_weight": 0,
|
| 16 |
+
"cues": ["アフィリエイト", "公式サイトはこちら", "公式サイト", "今なら", "初回限定", "初回", "無料体験", "お試し", "定期コース", "解約", "返金保証", "口コミ", "評判", "効果なし", "効果あり", "効果", "おすすめランキング", "ランキング", "比較", "最安値", "キャンペーン中", "申し込み", "申込", "副業", "稼ぐ", "稼げる", "FX", "仮想通貨", "投資信託", "積立", "NISA", "iDeCo", "不動産投資", "ポイ活", "クレジットカード", "カードローン", "キャッシング", "借入", "脱毛", "美白", "シミ", "しわ", "たるみ", "毛穴", "エステ", "美容液", "化粧水", "サプリ", "サプリメント", "ダイエット", "痩せ", "酵素", "プロテイン", "育毛", "薄毛", "AGA", "バストアップ", "ホワイトニング", "マットレス", "ウォーターサーバー", "転職エージェント", "婚活", "マッチングアプリ", "光回線", "格安SIM", "wifi", "WiMAX"]
|
| 17 |
+
},
|
| 18 |
+
"game": {
|
| 19 |
+
"label_ja": "ゲーム",
|
| 20 |
+
"host_patterns": ["game", "gamewith", "appmedia", "altema", "game8", "wiki\\.", "wikiwiki", "atwiki", "dqx", "ff14", "pokemon"],
|
| 21 |
+
"host_weight": 1.0,
|
| 22 |
+
"cues": ["攻略", "ガチャ", "レベル上げ", "レベル", "プレイ", "ステージ", "クエスト", "ボス", "キャラ", "スキル", "パーティ", "装備", "ダンジョン", "リセマラ", "課金", "無課金", "イベント報酬", "周回", "ドロップ", "経験値", "HP", "MP", "PS4", "PS5", "Switch", "Steam", "Xbox", "ゲーム", "アプリ", "ダウンロード", "アップデート", "eスポーツ", "実況", "モンスト", "パズドラ", "FGO", "原神", "ポケモン", "マイクラ", "スプラトゥーン", "フォートナイト", "ドラクエ", "ファイナルファンタジー", "ゼルダ", "モンハン"]
|
| 23 |
+
},
|
| 24 |
+
"entertainment": {
|
| 25 |
+
"label_ja": "芸能",
|
| 26 |
+
"host_patterns": ["geinou", "geino", "entame", "oricon", "modelpress", "natalie\\.mu", "cinematoday", "crank-in", "thetv\\.jp", "excite\\.co\\.jp/news", "news\\.dwango", "johnnys", "akb48"],
|
| 27 |
+
"host_weight": 1.0,
|
| 28 |
+
"cues": ["芸能人", "女優", "俳優", "アイドル", "タレント", "芸人", "お笑い", "ジャニーズ", "AKB", "乃木坂", "熱愛", "交際", "破局", "不倫", "結婚発表", "離婚", "妊娠", "出産", "ドラマ", "映画", "主演", "出演", "共演", "番組", "テレビ", "バラエティ", "紅白", "ライブ", "コンサート", "ツアー", "新曲", "MV", "ファン", "スキャンダル", "週刊文春", "フライデー", "報道", "インスタ", "ツイッター", "YouTuber", "声優", "アニメ", "K-POP", "BTS"]
|
| 29 |
+
},
|
| 30 |
+
"ec_product": {
|
| 31 |
+
"label_ja": "EC 商品ページ",
|
| 32 |
+
"host_patterns": ["rakuten\\.co\\.jp", "amazon\\.co\\.jp", "shopping\\.yahoo\\.co\\.jp", "store\\.shopping", "mercari", "zozo", "yodobashi", "biccamera", "kakaku\\.com", "monotaro", "askul", "dmm\\.com", "shop\\.", "store\\.", "cart", "item/", "/products?/", "/goods/", "/shop/"],
|
| 33 |
+
"host_weight": 1.0,
|
| 34 |
+
"cues": ["カートに入れる", "カートに追加", "買い物かご", "在庫あり", "在庫なし", "在庫", "送料無料", "送料", "税込", "税抜", "円(税込)", "円(税込)", "価格", "販売価格", "定価", "割引", "OFF", "ポイント還元", "ポイント", "レビュー", "お客様の声", "商品説明", "商品番号", "商品コード", "型番", "JAN", "サイズ", "カラー", "素材", "数量", "購入", "注文", "ご注文", "お届け", "配送", "返品", "ギフト", "ラッピング", "メーカー希望小売価格", "セール", "アウトレット", "お気に入りに追加", "再入荷"]
|
| 35 |
+
}
|
| 36 |
+
},
|
| 37 |
+
"manufacturing": {
|
| 38 |
+
"label_ja": "製造業・重工(主用途への適合)",
|
| 39 |
+
"cues": ["製造", "製造業", "工場", "生産", "生産ライン", "加工", "機械加工", "切削", "研削", "旋盤", "フライス", "マシニング", "溶接", "鋳造", "鍛造", "板金", "プレス", "塗装", "めっき", "熱処理", "金属", "鋼", "鋼材", "ステンレス", "アルミ", "合金", "樹脂", "射出成形", "部品", "部材", "図面", "CAD", "CAM", "設計", "公差", "寸法", "品質管理", "品質保証", "検査", "不良", "歩留まり", "工程", "治具", "金型", "工作機械", "NC", "産業用ロボット", "FA", "PLC", "制御", "センサ", "計測", "油圧", "空圧", "モーター", "ポンプ", "コンプレッサ", "バルブ", "配管", "ボイラー", "タービン", "エンジン", "発電", "発電所", "プラント", "造船", "船舶", "航空機", "エアロ", "宇宙", "ロケット", "鉄道車両", "重機", "建設機械", "クレーン", "橋梁", "原子力", "火力", "風力", "水素", "燃料電池", "電池", "半導体", "設備", "保全", "メンテナンス", "安全", "ISO", "JIS", "規格", "材料", "強度", "疲労", "腐食", "耐熱", "熱交換", "溶接構造", "構造解析", "CAE", "シミュレーション"]
|
| 40 |
+
},
|
| 41 |
+
"low_quality": {
|
| 42 |
+
"description_ja": "低品質ページの定義(項目28)。いずれかに該当すれば low_quality。",
|
| 43 |
+
"flags": {
|
| 44 |
+
"short_lt500": "最終的な本文が500字未満",
|
| 45 |
+
"symbol_digit_ratio_gt30": "記号・数字の比率が30%超",
|
| 46 |
+
"line_repetition_gt30": "同一行の繰り返しが30%超(10字以上の行)",
|
| 47 |
+
"avg_line_len_lt20": "平均行長が20字未満(10行以上)",
|
| 48 |
+
"template_commerce": "ジャンルが affiliate か ec_product でスコアが4以上(定型の販促・商品ページ)",
|
| 49 |
+
"low_lid_confidence": "言語判定の確信度が0.5未満"
|
| 50 |
+
}
|
| 51 |
+
}
|
| 52 |
+
}
|
code/3c1a8da-dirty-bd01fd79/src/wordlists/ja_adult_keywords.txt
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
ヌード
|
| 2 |
+
r18
|
| 3 |
+
porn
|
| 4 |
+
児童買春
|
| 5 |
+
性的搾取
|
| 6 |
+
出会い系
|
| 7 |
+
熟女
|
| 8 |
+
エロ漫画
|
| 9 |
+
アダルト動画
|
| 10 |
+
素人娘
|
code/3c1a8da-dirty-bd01fd79/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/3c1a8da-dirty-bd01fd79/src/wordlists/ja_discrimination_keywords.txt
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
誹謗中傷
|
| 2 |
+
ヘイト
|
| 3 |
+
人種差別
|
| 4 |
+
性差別
|
| 5 |
+
障害者差別
|
| 6 |
+
レイシスト
|
| 7 |
+
排外主義
|
| 8 |
+
民族差別
|
| 9 |
+
harassment
|
| 10 |
+
優生思想
|
| 11 |
+
クソガキ
|
code/3c1a8da-dirty-bd01fd79/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/3c1a8da-dirty-bd01fd79/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/3c1a8da-dirty-bd01fd79/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/3c1a8da-dirty-bd01fd79/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/3c1a8da-dirty-bd01fd79/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/3c1a8da-dirty-bd01fd79/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 |
+
流血
|