File size: 5,357 Bytes
f9aa847
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""2種類の語群が近接して現れる文書を検出する近接共起規則。

単語リストの密度(同一カテゴリ3語以上)では判別できない次の2種類を扱う。

* 未成年を示す語 × 性的な語(監査項目5「未成年が登場する文脈は0件」)
* 違法行為の対象語 × 手引きを示す語(監査項目8「違法行為の手引き」)

規則は ``wordlists/cooccurrence/rules.json`` に定義し、語リストは同じ
ディレクトリの1行1語ファイルから読む。一致した文書は削除対象になると同時に、
全件が目視確認用の ``cooccurrence_review.jsonl`` へ書き出される。
"""

from __future__ import annotations

import bisect
import json
from dataclasses import dataclass
from pathlib import Path
from typing import Any

from textmatch import compile_trie_pattern, normalize, read_terms


@dataclass(frozen=True)
class CooccurrenceRule:
    name: str
    category: str
    label_ja: str
    terms_a: tuple[str, ...]
    terms_b: tuple[str, ...]
    window: int
    description_ja: str = ""
    terms_a_file: str = ""
    terms_b_file: str = ""


def load_rules(path: Path) -> list[CooccurrenceRule]:
    """規則定義JSONと語リストを読む。語リストのパスはJSONからの相対パス。"""

    spec = json.loads(path.read_text(encoding="utf-8"))
    base = path.parent
    rules: list[CooccurrenceRule] = []
    for item in spec["rules"]:
        terms_a = read_terms(base / item["terms_a"])
        terms_b = read_terms(base / item["terms_b"])
        if not terms_a or not terms_b:
            raise ValueError(f"規則 {item['name']} の語リストが空です: {item['terms_a']}, {item['terms_b']}")
        rules.append(
            CooccurrenceRule(
                name=item["name"],
                category=item["category"],
                label_ja=item["label_ja"],
                terms_a=tuple(dict.fromkeys(terms_a)),
                terms_b=tuple(dict.fromkeys(terms_b)),
                window=int(item.get("window", 100)),
                description_ja=item.get("description_ja", ""),
                terms_a_file=item["terms_a"],
                terms_b_file=item["terms_b"],
            )
        )
    return rules


class CooccurrenceDetector:
    """各規則について、語群Aと語群Bの出現位置が window 文字以内の組を探す。"""

    def __init__(self, rules: list[CooccurrenceRule]) -> None:
        self.rules = rules
        self._patterns = [
            (
                rule,
                compile_trie_pattern(sorted(rule.terms_a, key=lambda t: (-len(t), t))),
                compile_trie_pattern(sorted(rule.terms_b, key=lambda t: (-len(t), t))),
            )
            for rule in rules
        ]

    def describe(self) -> list[dict[str, Any]]:
        return [
            {
                "name": rule.name,
                "category": rule.category,
                "label_ja": rule.label_ja,
                "window": rule.window,
                "terms_a_file": rule.terms_a_file,
                "terms_a_count": len(rule.terms_a),
                "terms_b_file": rule.terms_b_file,
                "terms_b_count": len(rule.terms_b),
                "description_ja": rule.description_ja,
            }
            for rule in self.rules
        ]

    def detect(self, text: Any, max_pairs: int = 10, excerpt_margin: int = 60) -> list[dict[str, Any]]:
        normalized = normalize(text)
        if not normalized:
            return []
        results: list[dict[str, Any]] = []
        for rule, pattern_a, pattern_b in self._patterns:
            a_hits = [(found.start(), found.group(0)) for found in pattern_a.finditer(normalized)]
            if not a_hits:
                continue
            b_hits = [(found.start(), found.group(0)) for found in pattern_b.finditer(normalized)]
            if not b_hits:
                continue
            b_positions = [position for position, _ in b_hits]
            pairs: list[dict[str, Any]] = []
            for a_position, a_term in a_hits:
                low = bisect.bisect_left(b_positions, a_position - rule.window)
                high = bisect.bisect_right(b_positions, a_position + rule.window)
                for b_position, b_term in b_hits[low:high]:
                    pairs.append(
                        {
                            "a": a_term,
                            "b": b_term,
                            "distance": abs(a_position - b_position),
                            "position": min(a_position, b_position),
                        }
                    )
            if not pairs:
                continue
            pairs.sort(key=lambda pair: (pair["position"], pair["distance"]))
            first = pairs[0]
            start = max(0, first["position"] - excerpt_margin)
            end = min(len(normalized), first["position"] + rule.window + excerpt_margin)
            results.append(
                {
                    "rule": rule.name,
                    "category": rule.category,
                    "label_ja": rule.label_ja,
                    "pair_count": len(pairs),
                    "pairs": pairs[:max_pairs],
                    "excerpt": normalized[start:end].replace("\n", " "),
                }
            )
        return results