Download code/3c1a8da/src/doc_features.py from Podtech/abeja-cc-ja-cleaned: direct link, hf CLI and curl.
- Browser
- Download file 9.17 kB
-
https://huggingface.co/datasets/Podtech/abeja-cc-ja-cleaned/resolve/main/code/3c1a8da/src/doc_features.py
- Command line
-
hf download hf://datasets/Podtech/abeja-cc-ja-cleaned/code/3c1a8da/src/doc_features.py
-
curl -L -o doc_features.py https://huggingface.co/datasets/Podtech/abeja-cc-ja-cleaned/resolve/main/code/3c1a8da/src/doc_features.py
9.17 kB
| """文書特徴量(監査項目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) | |
| 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, | |
| } | |
| 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 "", | |
| } | |