File size: 9,173 Bytes
cadf371
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""文書特徴量(監査項目22・25〜29用)。

第2パス(``run_noise_pass.py``)で文書ごとに算出し、``features.parquet`` に書く。

* 言語判定(項目25): fastText lid.176(Facebook、CC BY-SA 3.0 のモデル)。文書先頭1,000字の判定と、
  30字以上の行(最大50行)ごとの判定から非日本語行の比率を出す。
* ジャンル分類(項目29): ``wordlists/genre/genre_rules.json`` の URL 規則と手がかり語で、
  1,000字あたりの異なり手がかり語数をスコアとし、しきい値以上で最大のジャンルを付与する。
  製造業・重工への適合スコアは独立に記録する。
* 低品質フラグ(項目28): 同 JSON の定義(500字未満、記号・数字比率、行の反復、平均行長、販促定型、言語判定の低確信)。
* 長さ・ハッシュ(項目22・27): 文字数(入力・最終)、本文 SHA-1、URL ホスト。

fastText の python ラッパーは numpy 2 で壊れるため、C++ バインディング(``model.f.predict``)を直接使う。
"""

from __future__ import annotations

import hashlib
import json
import re
import statistics
from dataclasses import dataclass
from pathlib import Path
from typing import Any
from urllib.parse import urlparse

from textmatch import compile_trie_pattern, normalize


FEATURE_COLUMNS = [
    "record_index", "status", "url", "host", "perplexity",
    "chars_input", "chars_final", "lines_final", "avg_line_len",
    "lang", "lang_prob", "non_ja_line_ratio", "mixed_language",
    "genre", "genre_score", "manufacturing_score",
    "score_diary_blog", "score_affiliate", "score_game", "score_entertainment", "score_ec_product",
    "symbol_digit_ratio", "line_repetition", "is_low_quality", "low_quality_flags",
    "content_sha1",
]


class LanguageDetector:
    """fastText lid.176 による言語判定。"""

    def __init__(self, model_path: Path) -> None:
        import fasttext

        self.model_path = str(model_path)
        self._model = fasttext.load_model(self.model_path)

    def detect(self, text: str, max_chars: int = 1000) -> tuple[str, float]:
        sample = text.replace("\n", " ")[:max_chars].strip()
        if not sample:
            return "unk", 0.0
        out = self._model.f.predict(sample, 1, 0.0, "strict")
        if not out:
            return "unk", 0.0
        prob, label = out[0]
        return label.replace("__label__", ""), float(prob)

    def line_mix(self, text: str, max_lines: int = 50, min_chars: int = 30) -> tuple[float, int]:
        """非日本語と判定された行の比率(対象行数も返す)。"""

        lines = [line.strip() for line in text.split("\n") if len(line.strip()) >= min_chars][:max_lines]
        if not lines:
            return 0.0, 0
        non_ja = sum(1 for line in lines if self.detect(line, 300)[0] != "ja")
        return non_ja / len(lines), len(lines)


@dataclass(frozen=True)
class GenreRule:
    name: str
    label_ja: str
    host_regex: re.Pattern[str] | None
    host_weight: float
    cues: re.Pattern[str]
    cue_count: int


class GenreClassifier:
    def __init__(self, rules_path: Path) -> None:
        spec = json.loads(rules_path.read_text(encoding="utf-8"))
        self.threshold = float(spec.get("score_threshold", 2.0))
        self.manufacturing_threshold = float(spec.get("manufacturing_threshold", 2.0))
        self.rules: list[GenreRule] = []
        for name, item in spec["genres"].items():
            hosts = item.get("host_patterns") or []
            cues = sorted({normalize(c) for c in item["cues"]}, key=lambda t: (-len(t), t))
            self.rules.append(GenreRule(
                name=name, label_ja=item.get("label_ja", name),
                host_regex=re.compile("|".join(hosts), re.IGNORECASE) if hosts else None,
                host_weight=float(item.get("host_weight", 0)),
                cues=compile_trie_pattern(cues), cue_count=len(cues),
            ))
        manufacturing = sorted({normalize(c) for c in spec["manufacturing"]["cues"]}, key=lambda t: (-len(t), t))
        self.manufacturing = compile_trie_pattern(manufacturing)
        self.low_quality_flags = spec.get("low_quality", {}).get("flags", {})
        self.spec_summary = {
            "rules_file": str(rules_path), "score_threshold": self.threshold, "manufacturing_threshold": self.manufacturing_threshold,
            "genres": {r.name: {"label_ja": r.label_ja, "cues": r.cue_count, "host_weight": r.host_weight} for r in self.rules},
            "manufacturing_cues": len(manufacturing), "low_quality_flags": self.low_quality_flags,
        }

    @staticmethod
    def _distinct_per_1000(pattern: re.Pattern[str], text: str) -> float:
        found = {m.group(0) for m in pattern.finditer(text)}
        return len(found) / (max(len(text), 500) / 1000)

    def classify(self, url: str, normalized_text: str) -> tuple[str, float, float, dict[str, float]]:
        host = (urlparse(url).hostname or "").lower() if url else ""
        path = (urlparse(url).path or "").lower() if url else ""
        scores: dict[str, float] = {}
        for rule in self.rules:
            score = self._distinct_per_1000(rule.cues, normalized_text)
            if rule.host_regex is not None and rule.host_weight and (rule.host_regex.search(host) or rule.host_regex.search(path)):
                score += rule.host_weight
            scores[rule.name] = round(score, 3)
        manufacturing = round(self._distinct_per_1000(self.manufacturing, normalized_text), 3)
        best = max(scores, key=scores.get) if scores else "other"
        genre = best if scores.get(best, 0) >= self.threshold else "other"
        return genre, scores.get(best, 0.0), manufacturing, scores


SYMBOL_DIGIT_RE = re.compile(r"[0-90-9\W_]")


class DocFeaturizer:
    def __init__(self, rules_path: Path, lid_model_path: Path | None = None) -> None:
        self.genres = GenreClassifier(rules_path)
        self.lid = LanguageDetector(lid_model_path) if lid_model_path else None

    def describe(self) -> dict[str, Any]:
        return {
            "language_detector": {"tool": "fastText lid.176", "model": self.lid.model_path if self.lid else None,
                                  "doc_sample_chars": 1000, "line_min_chars": 30, "line_max": 50, "mixed_threshold": 0.3},
            "genre_rules": self.genres.spec_summary,
        }

    def features(self, url: str, text: str, chars_input: int, status: str, record_index: int, perplexity: float | None = None,
                 lang: tuple[str, float] | None = None) -> dict[str, Any]:
        text = text or ""
        normalized = normalize(text)
        lines = [line.strip() for line in text.split("\n") if line.strip()]
        long_lines = [line for line in lines if len(line) >= 10]
        avg_line = statistics.mean(len(line) for line in lines) if lines else 0.0
        repetition = 1 - len(set(long_lines)) / len(long_lines) if long_lines else 0.0
        stripped = text.replace("\n", "").replace(" ", "")
        symbol_digit = len(SYMBOL_DIGIT_RE.findall(stripped)) / len(stripped) if stripped else 0.0
        if lang is None:
            lang = self.lid.detect(text) if self.lid else ("unk", 0.0)
        non_ja_ratio, _ = self.lid.line_mix(text) if self.lid else (0.0, 0)
        mixed = lang[0] == "ja" and non_ja_ratio >= 0.3
        genre, genre_score, manufacturing, scores = self.genres.classify(url or "", normalized)
        flags: list[str] = []
        if len(text) < 500:
            flags.append("short_lt500")
        if symbol_digit > 0.30:
            flags.append("symbol_digit_ratio_gt30")
        if repetition > 0.30 and len(long_lines) >= 10:
            flags.append("line_repetition_gt30")
        if len(lines) >= 10 and avg_line < 20:
            flags.append("avg_line_len_lt20")
        if genre in ("affiliate", "ec_product") and genre_score >= 4.0:
            flags.append("template_commerce")
        if lang[1] < 0.5:
            flags.append("low_lid_confidence")
        return {
            "record_index": record_index, "status": status, "url": url, "host": (urlparse(url).hostname or "") if url else "",
            "perplexity": perplexity,
            "chars_input": chars_input, "chars_final": len(text), "lines_final": len(lines), "avg_line_len": round(avg_line, 1),
            "lang": lang[0], "lang_prob": round(lang[1], 3), "non_ja_line_ratio": round(non_ja_ratio, 3), "mixed_language": mixed,
            "genre": genre, "genre_score": round(genre_score, 3), "manufacturing_score": manufacturing,
            "score_diary_blog": scores.get("diary_blog", 0.0), "score_affiliate": scores.get("affiliate", 0.0),
            "score_game": scores.get("game", 0.0), "score_entertainment": scores.get("entertainment", 0.0),
            "score_ec_product": scores.get("ec_product", 0.0),
            "symbol_digit_ratio": round(symbol_digit, 3), "line_repetition": round(repetition, 3),
            "is_low_quality": bool(flags), "low_quality_flags": "|".join(flags),
            "content_sha1": hashlib.sha1(text.encode("utf-8")).hexdigest() if text else "",
        }