File size: 10,216 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
"""目視確認と分類器用のサンプルを層別に抽出する(監査の第3手法の入口)。

有害フィルタの出力(summary.json, removed.jsonl, borderline.jsonl,
cooccurrence_review.jsonl)と元の入力parquetから、次の層でサンプルを取る。

* ``deleted:<category>``      ワードリストで削除した文書(カテゴリ別、既定30件)
* ``deleted:domain_blocklist`` ドメインブロックリストで削除した文書(既定30件)
* ``cooccurrence:<rule>``     近接共起規則の一致(規則ごとに既定100件。一致文書は全件削除される)
* ``borderline:<category>``   しきい値に1語足りず保持された文書(カテゴリ別、既定30件)
* ``retained:random``         保持文書の無作為抽出(既定100件。見逃し率の推定に使う)

出力は ``review_samples.csv``(人が判定を記入する)と ``review_samples.jsonl``
(``classify_qwen3guard.py`` の入力)。抽出条件は ``sampling_manifest.json`` に残す。
"""

from __future__ import annotations

import argparse
import csv
import json
import random
from datetime import datetime, timezone
from pathlib import Path
from typing import Any

import pyarrow.parquet as pq

from filter_toxic import CATEGORIES, KeywordMatcher, load_wordlists
from textmatch import normalize


CSV_COLUMNS = [
    "sample_id", "stratum", "category", "record_index", "url", "matched_terms",
    "excerpt", "reviewer", "verdict", "reason", "reviewed_at",
]


def _read_jsonl(path: Path) -> list[dict[str, Any]]:
    if not path.exists():
        return []
    with path.open(encoding="utf-8") as handle:
        return [json.loads(line) for line in handle if line.strip()]


def _excerpt(text: str, positions: list[int], length: int = 300) -> str:
    if not text:
        return ""
    if positions:
        start = max(0, positions[0] - length // 3)
    else:
        start = 0
    return text[start:start + length].replace("\n", " ")


def main(argv: list[str] | None = None) -> None:
    source_dir = Path(__file__).resolve().parent
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--input", type=Path, required=True, help="元の入力parquet")
    parser.add_argument("--output-root", type=Path, required=True, help="main_toxic.py の --output-root")
    parser.add_argument("--mode", default="distinct_terms_3plus")
    parser.add_argument("--dest", type=Path, required=True, help="サンプルの出力先ディレクトリ")
    parser.add_argument("--seed", type=int, default=20260904)
    parser.add_argument("--deleted-per-category", type=int, default=30)
    parser.add_argument("--deleted-domain", type=int, default=30)
    parser.add_argument("--borderline-per-category", type=int, default=30)
    parser.add_argument("--random-retained", type=int, default=100)
    parser.add_argument("--cooccurrence-limit", type=int, default=100, help="共起規則ごとの抽出上限(既定100。全件にするには 0)")
    parser.add_argument("--text-chars", type=int, default=4000, help="JSONLに含める本文の最大文字数")
    parser.add_argument("--reference-dir", type=Path, default=source_dir / "wordlists" / "reference")
    parser.add_argument("--additional-dir", type=Path, default=source_dir / "wordlists")
    parser.add_argument("--exclude-dir", type=Path, default=source_dir / "wordlists" / "exclude")
    args = parser.parse_args(argv)
    rng = random.Random(args.seed)
    mode_dir = args.output_root / args.mode
    summary = json.loads((mode_dir / "summary.json").read_text(encoding="utf-8"))
    threshold = summary["threshold"]
    removed = _read_jsonl(mode_dir / "removed.jsonl")
    borderline = _read_jsonl(mode_dir / "borderline.jsonl")
    cooccurrence = _read_jsonl(mode_dir / "cooccurrence_review.jsonl")
    removed_indices = {record["_filter_record_index"] for record in removed}
    row_range = summary["row_range"]

    samples: list[dict[str, Any]] = []

    def add(stratum: str, category: str, record_index: int, url: str, terms: list[str], text: str, positions: list[int]) -> None:
        samples.append({
            "stratum": stratum, "category": category, "record_index": record_index, "url": url,
            "matched_terms": terms, "text": text, "match_positions": positions,
        })

    # 削除文書(ワードリスト)
    for category in CATEGORIES:
        pool = [r for r in removed if category in r["_filter_deleted_categories"]]
        for record in rng.sample(pool, min(args.deleted_per_category, len(pool))):
            terms = record["_filter_distinct_matched_terms_by_category"].get(category, [])
            text = normalize(record.get("content") or "")
            positions = sorted(p for t in terms for p in [text.find(t)] if p >= 0)
            add(f"deleted:{category}", category, record["_filter_record_index"], record.get("url") or "", terms, text, positions)
    # 削除文書(ドメインブロックリスト)
    pool = [r for r in removed if "domain_blocklist" in r.get("_filter_deleted_by", [])]
    for record in rng.sample(pool, min(args.deleted_domain, len(pool))):
        sources = sorted({m["source"] + "=" + m["matched"] for m in record.get("_filter_domain_matches", [])})
        add("deleted:domain_blocklist", "domain_blocklist", record["_filter_record_index"], record.get("url") or "", sources,
            normalize(record.get("content") or ""), [])
    # 共起規則(既定は全件)
    by_rule: dict[str, list[dict[str, Any]]] = {}
    for item in cooccurrence:
        by_rule.setdefault(item["rule"], []).append(item)
    removed_by_index = {r["_filter_record_index"]: r for r in removed}
    for rule, items in by_rule.items():
        chosen = items if not args.cooccurrence_limit else rng.sample(items, min(args.cooccurrence_limit, len(items)))
        for item in chosen:
            record = removed_by_index.get(item["record_index"], {})
            text = normalize(record.get("content") or "")
            positions = [pair["position"] for pair in item["pairs"][:4]]
            pairs = [f"{pair['a']}×{pair['b']}" for pair in item["pairs"][:5]]
            add(f"cooccurrence:{rule}", item.get("label_ja", rule), item["record_index"], item.get("url") or "", pairs, text, positions)

    # 保持文書は入力parquetから本文を取る
    needed: dict[int, list[tuple[str, str, list[str]]]] = {}
    for category in CATEGORIES:
        pool = [b for b in borderline if category in b["categories"]]
        for record in rng.sample(pool, min(args.borderline_per_category, len(pool))):
            needed.setdefault(record["record_index"], []).append((f"borderline:{category}", category, record["categories"][category]))
    retained_pool = [i for i in range(row_range["start_row_inclusive"], row_range["end_row_exclusive"]) if i not in removed_indices]
    for record_index in rng.sample(retained_pool, min(args.random_retained, len(retained_pool))):
        needed.setdefault(record_index, []).append(("retained:random", "random", []))
    if needed:
        table = pq.read_table(args.input, columns=["url", "content"])
        wordlists = load_wordlists(args.reference_dir, args.additional_dir, args.exclude_dir)
        matcher = KeywordMatcher(wordlists.terms, wordlists.sources)
        for record_index, entries in sorted(needed.items()):
            row = table.slice(record_index, 1).to_pylist()[0]
            text = normalize(row.get("content") or "")
            positions = sorted({found.start() for found in matcher.pattern.finditer(text)})[:8]
            for stratum, category, terms in entries:
                add(stratum, category, record_index, row.get("url") or "", terms, text, positions)

    args.dest.mkdir(parents=True, exist_ok=True)
    with (args.dest / "review_samples.csv").open("w", encoding="utf-8", newline="") as handle:
        writer = csv.DictWriter(handle, fieldnames=CSV_COLUMNS)
        writer.writeheader()
        for number, sample in enumerate(samples, start=1):
            sample_id = f"S{number:05d}"
            sample["sample_id"] = sample_id
            writer.writerow({
                "sample_id": sample_id, "stratum": sample["stratum"], "category": sample["category"],
                "record_index": sample["record_index"], "url": sample["url"],
                "matched_terms": " | ".join(sample["matched_terms"]),
                "excerpt": _excerpt(sample["text"], sample["match_positions"]),
                "reviewer": "", "verdict": "", "reason": "", "reviewed_at": "",
            })
    with (args.dest / "review_samples.jsonl").open("w", encoding="utf-8") as handle:
        for sample in samples:
            handle.write(json.dumps({
                "id": sample["sample_id"], "stratum": sample["stratum"], "category": sample["category"],
                "record_index": sample["record_index"], "url": sample["url"], "matched_terms": sample["matched_terms"],
                "match_positions": sample["match_positions"], "text": sample["text"][:args.text_chars],
            }, ensure_ascii=False, separators=(",", ":")) + "\n")
    strata: dict[str, int] = {}
    for sample in samples:
        strata[sample["stratum"]] = strata.get(sample["stratum"], 0) + 1
    manifest = {
        "created_at_utc": datetime.now(timezone.utc).isoformat(),
        "input": str(args.input), "output_root": str(args.output_root), "mode": args.mode, "seed": args.seed,
        "sizes": {"deleted_per_category": args.deleted_per_category, "deleted_domain": args.deleted_domain,
                  "borderline_per_category": args.borderline_per_category, "random_retained": args.random_retained,
                  "cooccurrence_limit": args.cooccurrence_limit},
        "threshold": threshold, "strata": strata, "total_samples": len(samples),
        "verdict_values": ["harmful", "not_harmful", "unsure"],
    }
    (args.dest / "sampling_manifest.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    print(json.dumps({"total_samples": len(samples), "strata": strata}, ensure_ascii=False))


if __name__ == "__main__":
    main()