File size: 14,685 Bytes
b5cbcc7 | 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 151 152 153 154 155 156 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 | """監査項目B(有害・倫理的に問題のあるコンテンツ、項目5〜10)の報告書を生成する。
有害フィルタの出力(summary.json, removed.jsonl, cooccurrence_review.jsonl)と、
あれば分類器の出力(classify_qwen3guard.py)、目視集計(review_tally.py)を
統合し、項目ごとに「適用した手法」「検出・除外件数」「例3件」「適用リスト」を
Markdown にまとめる。手法が1つしか適用されていない項目は「実施」と表示しない。
uv run python abeja-cc-ja/src/audit_report.py --output-root <toxic出力> \
[--classified review/classified.jsonl] [--review-tally review/review_tally.json] \
--output audit_report.md
"""
from __future__ import annotations
import argparse
import json
from collections import Counter, defaultdict
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
from textmatch import normalize
# 監査項目と、フィルタ内部のカテゴリ・規則・ブロックリストの対応。
AUDIT_ITEMS: list[dict[str, Any]] = [
{"item": 5, "title": "性的・わいせつな表現(未成年文脈は0件)",
"wordlist": ["adult"], "cooccurrence": ["minor_sexual_context"],
"blocklist": ["ut1:adult", "ut1:mixed_adult", "ut1:child", "local:domains", "local:rules"],
"classifier": ["Sexual Content or Sexual Acts"]},
{"item": 6, "title": "暴力・自傷・自殺の助長、危害を加える具体的手順",
"wordlist": ["violence"], "cooccurrence": [], "blocklist": [],
"classifier": ["Violent", "Suicide & Self-Harm"]},
{"item": 7, "title": "差別・ヘイト、誹謗中傷",
"wordlist": ["discrimination"], "cooccurrence": [], "blocklist": ["ut1:agressif"],
"classifier": ["Unethical Acts"]},
{"item": 8, "title": "違法行為の手引き(薬物、武器、詐欺、不正アクセス等)",
"wordlist": ["crime"], "cooccurrence": ["illegal_howto"],
"blocklist": ["ut1:drogue", "ut1:dangerous_material", "ut1:hacking"],
"classifier": ["Non-violent Illegal Acts"]},
{"item": 9, "title": "過激な政治・宗教プロパガンダ、陰謀論",
"wordlist": ["propaganda_conspiracy"], "cooccurrence": [], "blocklist": ["ut1:sect", "ut1:fakenews"],
"classifier": ["Politically Sensitive Topics"]},
{"item": 10, "title": "スパム・詐欺・アダルト・違法コピー配布サイト由来のページ",
"wordlist": ["spam"], "cooccurrence": [],
"blocklist": ["ut1:adult", "ut1:mixed_adult", "ut1:gambling", "ut1:phishing", "ut1:malware", "ut1:warez",
"ut1:cryptojacking", "ut1:stalkerware", "ut1:ddos", "ut1:dating", "local:domains", "local:rules"],
"classifier": ["Copyright Violation"]},
]
def _read_jsonl(path: Path) -> list[dict[str, Any]]:
if not path or not path.exists():
return []
with path.open(encoding="utf-8") as handle:
return [json.loads(line) for line in handle if line.strip()]
def _snippet(record: dict[str, Any], terms: list[str], length: int = 90) -> str:
text = normalize(record.get("content") or "")
position = -1
for term in terms:
position = text.find(term)
if position >= 0:
break
start = max(0, position - length // 3) if position >= 0 else 0
return text[start:start + length].replace("\n", " ").replace("|", "/")
def _examples_wordlist(removed: list[dict[str, Any]], category: str, limit: int = 3) -> list[str]:
rows = []
for record in removed:
if category not in record.get("_filter_deleted_categories", []):
continue
terms = record["_filter_distinct_matched_terms_by_category"].get(category, [])
rows.append(f"| {record.get('_filter_record_index')} | {record.get('url', '')[:70]} | {', '.join(terms[:5])} | {_snippet(record, terms)} |")
if len(rows) >= limit:
break
return rows
def _examples_cooccurrence(review: list[dict[str, Any]], rule: str, limit: int = 3) -> list[str]:
rows = []
for item in review:
if item["rule"] != rule:
continue
pairs = ", ".join(f"{p['a']}×{p['b']}" for p in item["pairs"][:3])
rows.append(f"| {item['record_index']} | {item.get('url', '')[:70]} | {pairs} | {item['excerpt'][:90].replace('|', '/')} |")
if len(rows) >= limit:
break
return rows
def _examples_blocklist(removed: list[dict[str, Any]], sources: list[str], limit: int = 3) -> list[str]:
rows = []
for record in removed:
hits = [m for m in record.get("_filter_domain_matches", []) if m["source"] in sources and m["action"] == "delete"]
if not hits:
continue
rows.append(f"| {record.get('_filter_record_index')} | {record.get('url', '')[:70]} | {hits[0]['source']} ({hits[0]['matched'][:40]}) | |")
if len(rows) >= limit:
break
return rows
def main(argv: list[str] | None = None) -> None:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--output-root", type=Path, required=True)
parser.add_argument("--mode", default="distinct_terms_3plus")
parser.add_argument("--classified", type=Path, default=None, help="classify_qwen3guard.py の出力JSONL")
parser.add_argument("--review-tally", type=Path, default=None, help="review_tally.py の出力JSON")
parser.add_argument("--sampling-manifest", type=Path, default=None)
parser.add_argument("--output", type=Path, default=None, help="既定は <output-root>/audit_report.md")
args = parser.parse_args(argv)
mode_dir = args.output_root / args.mode
summary = json.loads((mode_dir / "summary.json").read_text(encoding="utf-8"))
removed = _read_jsonl(mode_dir / "removed.jsonl")
review = _read_jsonl(mode_dir / "cooccurrence_review.jsonl")
classified = _read_jsonl(args.classified) if args.classified else []
tally = json.loads(args.review_tally.read_text(encoding="utf-8")) if args.review_tally and args.review_tally.exists() else None
sampling = json.loads(args.sampling_manifest.read_text(encoding="utf-8")) if args.sampling_manifest and args.sampling_manifest.exists() else None
total = summary["total_records_scanned"]
block = summary.get("domain_blocklist", {})
cooc = summary.get("cooccurrence", {})
by_reason = summary.get("records_deleted_by_reason", {})
# 分類器の集計(層別 × 判定)
classifier_by_stratum: dict[str, Counter] = defaultdict(Counter)
classifier_by_category: Counter = Counter()
for record in classified:
classifier_by_stratum[record.get("stratum", "?")][record.get("safety") or "unparsed"] += 1
for category in record.get("categories", []):
classifier_by_category[category] += 1
lines: list[str] = []
lines.append(f"# 有害コンテンツ監査報告(項目B: 5〜10)")
lines.append("")
lines.append(f"- 生成日時: {datetime.now(timezone.utc).isoformat()}")
lines.append(f"- 対象: `{summary['source_file']}`(行 {summary['row_range']['start_row_inclusive']}〜{summary['row_range']['end_row_exclusive']}、{total:,} 文書)")
lines.append(f"- 削除合計: {summary['records_deleted']:,} 文書({summary['deletion_rate']*100:.2f}%)。理由別: ワードリスト {by_reason.get('wordlist', 0):,}、ドメインブロックリスト {by_reason.get('domain_blocklist', 0):,}、近接共起 {by_reason.get('cooccurrence', 0):,}、複数理由 {by_reason.get('multiple_reasons', 0):,}")
lines.append("")
lines.append("## 適用した手法")
lines.append("")
lines.append("| 手法 | 状態 | 内容 |")
lines.append("|---|---|---|")
lines.append(f"| 辞書(ワードリスト) | 適用 | カテゴリ別語彙、同一カテゴリ{summary['threshold']}語以上で削除。除外語: " + ", ".join(f"{k} {len(v)}" for k, v in summary.get("wordlist_excluded_terms_by_category", {}).items()) + " |")
lines.append(f"| 辞書(近接共起規則) | {'適用' if cooc.get('enabled') else '未適用'} | " + "; ".join(f"{r['name']}({r['label_ja']}、{r['window']}文字以内)" for r in cooc.get("rules", [])) + " |")
lines.append(f"| ドメインブロックリスト | {'適用' if block.get('enabled') else '未適用'} | " + ", ".join(f"{s['name']}={s['entries']:,}" for s in block.get("sources", [])) + " |")
if classified:
lines.append(f"| 分類器 | 適用(サンプル) | {classified[0].get('model', '')} を {len(classified)} 文書へ適用。判定: " + ", ".join(f"{k} {v}" for k, v in sorted(Counter(r.get('safety') or 'unparsed' for r in classified).items())) + " |")
else:
lines.append("| 分類器 | 未適用 | `classify_qwen3guard.py` の出力を `--classified` で渡す |")
if tally:
reviewed = sum(e.get("reviewed", 0) for e in tally["strata"].values())
lines.append(f"| 目視 | {'適用' if reviewed else '未記入'} | 判定済み {reviewed} 件、判定者 {', '.join(tally.get('reviewers', [])) or '未記入'} |")
else:
lines.append("| 目視 | 未適用 | `sample_for_review.py` → 記入 → `review_tally.py` の結果を `--review-tally` で渡す |")
lines.append("")
methods_applied = 1 + (1 if classified else 0) + (1 if tally and any(e.get("reviewed") for e in tally["strata"].values()) else 0)
lines.append(f"手法数: {methods_applied}/3。" + ("3手法が揃っており「実施」と表示できます。" if methods_applied >= 3 else "3手法が揃うまでは「実施」としないこと。"))
lines.append("")
if block.get("enabled"):
lines.append("## 適用したドメインブロックリスト")
lines.append("")
lines.append("| リスト | 動作 | 件数 | 一致文書 | 削除文書 | 取得元 | 取得日時 | SHA-256 |")
lines.append("|---|---|---:|---:|---:|---|---|---|")
for source in block["sources"]:
stat = block["by_source"].get(source["name"], {})
lines.append(f"| {source['name']} | {source['action']} | {source['entries']:,} | {stat.get('records_matched', 0)} | {stat.get('records_deleted', 0)} | {source.get('source_url') or source.get('path')} | {source.get('fetched_at_utc') or ''} | {(source.get('sha256') or '')[:16]} |")
lines.append("")
for spec in AUDIT_ITEMS:
lines.append(f"## 項目{spec['item']}: {spec['title']}")
lines.append("")
counts_lines = []
for category in spec["wordlist"]:
cat = summary["by_category"].get(category, {})
counts_lines.append(f"- ワードリスト `{category}`: 一致 {cat.get('records_with_match', 0):,} 文書、削除 {cat.get('records_deleted', 0):,} 文書({cat.get('distinct_terms_matched', 0)} 語が一致)")
for rule in spec["cooccurrence"]:
stat = cooc.get("by_rule", {}).get(rule)
if stat is not None:
counts_lines.append(f"- 近接共起 `{rule}`({stat['label_ja']}): 一致・削除 {stat['records_matched']:,} 文書。全件を `cooccurrence_review.jsonl` で目視確認する")
for source_name in spec["blocklist"]:
stat = block.get("by_source", {}).get(source_name)
if stat is not None:
counts_lines.append(f"- ブロックリスト `{source_name}`({stat['action']}): 一致 {stat['records_matched']:,} 文書、削除 {stat['records_deleted']:,} 文書")
if classified:
hit = sum(1 for r in classified if any(c in spec["classifier"] for c in r.get("categories", [])))
counts_lines.append(f"- 分類器: サンプル {len(classified)} 件中 {hit} 件が {', '.join(spec['classifier'])} に該当")
if tally:
for stratum, entry in tally["strata"].items():
if any(stratum.endswith(":" + c) for c in spec["wordlist"] + spec["cooccurrence"]):
rate = entry.get("precision", entry.get("harmful_rate"))
counts_lines.append(f"- 目視 `{stratum}`: harmful {entry['harmful']}、not_harmful {entry['not_harmful']}、unsure {entry['unsure']}、未確認 {entry['unreviewed']}" + (f"、精度 {rate}" if rate is not None else ""))
lines.extend(counts_lines or ["- 該当する検出手段なし"])
if spec["item"] == 5:
minor = cooc.get("by_rule", {}).get("minor_sexual_context", {})
lines.append(f"- 未成年文脈: 共起規則で {minor.get('records_matched', 0):,} 文書を削除。保持データ側の残存は目視層 `cooccurrence:minor_sexual_context` と `retained:random` の確認結果で判断する")
lines.append("")
lines.append("例(最大3件):")
lines.append("")
lines.append("| record_index | URL | 該当語・規則 | 抜粋 |")
lines.append("|---|---|---|---|")
examples: list[str] = []
for category in spec["wordlist"]:
examples.extend(_examples_wordlist(removed, category))
for rule in spec["cooccurrence"]:
examples.extend(_examples_cooccurrence(review, rule))
examples.extend(_examples_blocklist(removed, spec["blocklist"]))
lines.extend(examples[:3] if examples else ["| | (該当なし) | | |"])
lines.append("")
if sampling:
lines.append("## 目視サンプル")
lines.append("")
lines.append(f"- 抽出日時 {sampling['created_at_utc']}、seed {sampling['seed']}、合計 {sampling['total_samples']} 件")
lines.append("- 層別件数: " + ", ".join(f"{k} {v}" for k, v in sampling["strata"].items()))
lines.append("")
if classified:
lines.append("## 分類器の層別結果")
lines.append("")
lines.append("| 層 | Safe | Controversial | Unsafe | 未解析 |")
lines.append("|---|---:|---:|---:|---:|")
for stratum, counter in sorted(classifier_by_stratum.items()):
lines.append(f"| {stratum} | {counter.get('Safe', 0)} | {counter.get('Controversial', 0)} | {counter.get('Unsafe', 0)} | {counter.get('unparsed', 0)} |")
lines.append("")
lines.append("カテゴリ別: " + ", ".join(f"{k} {v}" for k, v in classifier_by_category.most_common()))
lines.append("")
output = args.output or (args.output_root / "audit_report.md")
output.write_text("\n".join(lines) + "\n", encoding="utf-8")
print(f"wrote {output} ({len(lines)} lines); methods_applied={methods_applied}/3")
if __name__ == "__main__":
main()
|