Download kawk50m/text.py from Infinity08/KAWK50M-Project: direct link, hf CLI and curl.
- Browser
- Download file 11.8 kB
-
https://huggingface.co/datasets/Infinity08/KAWK50M-Project/resolve/main/kawk50m/text.py
- Command line
-
hf download hf://datasets/Infinity08/KAWK50M-Project/kawk50m/text.py
-
curl -L -o text.py https://huggingface.co/datasets/Infinity08/KAWK50M-Project/resolve/main/kawk50m/text.py
11.8 kB
| from __future__ import annotations | |
| import hashlib | |
| import html | |
| import math | |
| import re | |
| import unicodedata | |
| from dataclasses import asdict, dataclass | |
| HANGUL_RE = re.compile(r"[가-힣]") | |
| LATIN_RE = re.compile(r"[A-Za-z]") | |
| CJK_RE = re.compile(r"[\u3400-\u4dbf\u4e00-\u9fff]") | |
| URL_RE = re.compile(r"(?:https?://|www\.)\S+", re.IGNORECASE) | |
| EMAIL_RE = re.compile(r"\b[\w.+-]+@[\w.-]+\.[A-Za-z]{2,}\b") | |
| PHONE_RE = re.compile(r"(?<!\d)(?:\+?82[- ]?)?0?1[016789][ -]?\d{3,4}[ -]?\d{4}(?!\d)") | |
| RRN_RE = re.compile(r"(?<!\d)\d{6}[ -]?[1-4]\d{6}(?!\d)") | |
| SCRIPT_STYLE_RE = re.compile( | |
| r"<(?:script|style)\b[^>]*>.*?</(?:script|style)>", | |
| re.IGNORECASE | re.DOTALL, | |
| ) | |
| HTML_TAG_RE = re.compile(r"<[^>\n]{1,500}>") | |
| MULTISPACE_RE = re.compile(r"[ \t]{2,}") | |
| MANY_NEWLINES_RE = re.compile(r"\n{3,}") | |
| CODE_LINE_RE = re.compile( | |
| r"^\s*(?:" | |
| r"(?:def|class|import|from|function|const|let|var|public|private)\s+" | |
| r"|#include\b|package\s+\w+|using\s+namespace\b" | |
| r"|[{}[\];]{2,}|</?\w+[^>]*>" | |
| r")" | |
| ) | |
| CODE_MATH_CHARS = frozenset("{}[]<>=+*/\\^_|~`$") | |
| WORD_RE = re.compile(r"[가-힣A-Za-z0-9]+") | |
| LIST_LINE_RE = re.compile( | |
| r"^\s*(?:[-*•·▪◦▶▷■□]|(?:\d+|[가-힣A-Za-z])[.)])\s+" | |
| ) | |
| BOILERPLATE_RE = re.compile( | |
| r"(?:로그인|회원가입|개인정보\s*처리방침|이용약관|전체\s*메뉴|" | |
| r"장바구니|상품\s*후기|배송\s*조회|쿠폰|고객\s*센터|" | |
| r"무단\s*전재|재배포\s*금지|관련\s*기사|실시간\s*뉴스)" | |
| ) | |
| REPEATED_CHARACTER_RE = re.compile(r"(.)\1+") | |
| NON_CONTENT_RE = re.compile(r"[\W_]+", re.UNICODE) | |
| class FilterConfig: | |
| min_chars: int = 300 | |
| max_chars: int = 100_000 | |
| min_hangul_chars: int = 50 | |
| min_hangul_letter_ratio: float = 0.70 | |
| min_hangul_visible_ratio: float = 0.55 | |
| max_digit_ratio: float = 0.08 | |
| max_symbol_ratio: float = 0.15 | |
| max_url_per_word: float = 0.01 | |
| min_unique_line_ratio: float = 0.70 | |
| min_unique_word_ratio: float = 0.20 | |
| max_short_line_ratio: float = 0.50 | |
| max_list_line_ratio: float = 0.25 | |
| max_table_line_ratio: float = 0.10 | |
| max_boilerplate_hits_per_1k: float = 1.5 | |
| max_repeated_character_run: int = 20 | |
| max_code_line_ratio: float = 0.25 | |
| max_code_math_char_ratio: float = 0.15 | |
| min_quality_score: float = 0.70 | |
| strip_html: bool = True | |
| mask_pii: bool = True | |
| class TextMetrics: | |
| characters: int | |
| visible_characters: int | |
| hangul_characters: int | |
| latin_characters: int | |
| cjk_characters: int | |
| digit_characters: int | |
| symbol_characters: int | |
| hangul_letter_ratio: float | |
| hangul_visible_ratio: float | |
| digit_ratio: float | |
| symbol_ratio: float | |
| url_per_word: float | |
| unique_line_ratio: float | |
| unique_word_ratio: float | |
| short_line_ratio: float | |
| list_line_ratio: float | |
| table_line_ratio: float | |
| boilerplate_hits_per_1k: float | |
| repeated_character_run: int | |
| code_line_ratio: float | |
| code_math_char_ratio: float | |
| def to_dict(self) -> dict[str, int | float]: | |
| return asdict(self) | |
| def normalize_text( | |
| text: str, | |
| *, | |
| strip_html: bool = True, | |
| mask_pii: bool = True, | |
| ) -> str: | |
| if not isinstance(text, str): | |
| raise TypeError(f"text must be str, got {type(text).__name__}") | |
| text = unicodedata.normalize("NFC", text) | |
| text = text.replace("\r\n", "\n").replace("\r", "\n") | |
| text = text.replace("\u00a0", " ").replace("\u200b", "") | |
| text = text.replace("\u200c", "").replace("\u200d", "") | |
| text = "".join( | |
| character | |
| for character in text | |
| if character in "\n\t" or unicodedata.category(character) != "Cc" | |
| ) | |
| if strip_html: | |
| text = SCRIPT_STYLE_RE.sub(" ", text) | |
| text = HTML_TAG_RE.sub(" ", text) | |
| text = html.unescape(text) | |
| if mask_pii: | |
| text = EMAIL_RE.sub("<EMAIL>", text) | |
| text = PHONE_RE.sub("<PHONE>", text) | |
| text = RRN_RE.sub("<RRN>", text) | |
| lines = [MULTISPACE_RE.sub(" ", line).strip() for line in text.splitlines()] | |
| text = "\n".join(line for line in lines if line) | |
| text = MANY_NEWLINES_RE.sub("\n\n", text) | |
| return text.strip() | |
| def measure_text(text: str) -> TextMetrics: | |
| visible = [character for character in text if not character.isspace()] | |
| hangul_count = len(HANGUL_RE.findall(text)) | |
| latin_count = len(LATIN_RE.findall(text)) | |
| cjk_count = len(CJK_RE.findall(text)) | |
| digit_count = sum(character.isdigit() for character in visible) | |
| symbol_count = sum( | |
| unicodedata.category(character).startswith(("P", "S")) | |
| for character in visible | |
| ) | |
| letter_count = hangul_count + latin_count + cjk_count | |
| lines = [line for line in text.splitlines() if line.strip()] | |
| words = text.split() | |
| content_words = WORD_RE.findall(text.casefold()) | |
| code_lines = sum(bool(CODE_LINE_RE.search(line)) for line in lines) | |
| code_math_count = sum(character in CODE_MATH_CHARS for character in visible) | |
| short_lines = sum(len(line.strip()) < 20 for line in lines) | |
| list_lines = sum(bool(LIST_LINE_RE.search(line)) for line in lines) | |
| table_lines = sum(line.count("|") >= 2 for line in lines) | |
| boilerplate_hits = len(BOILERPLATE_RE.findall(text)) | |
| repeated_runs = [ | |
| len(match.group(0)) for match in REPEATED_CHARACTER_RE.finditer(text) | |
| ] | |
| return TextMetrics( | |
| characters=len(text), | |
| visible_characters=len(visible), | |
| hangul_characters=hangul_count, | |
| latin_characters=latin_count, | |
| cjk_characters=cjk_count, | |
| digit_characters=digit_count, | |
| symbol_characters=symbol_count, | |
| hangul_letter_ratio=hangul_count / max(letter_count, 1), | |
| hangul_visible_ratio=hangul_count / max(len(visible), 1), | |
| digit_ratio=digit_count / max(len(visible), 1), | |
| symbol_ratio=symbol_count / max(len(visible), 1), | |
| url_per_word=len(URL_RE.findall(text)) / max(len(words), 1), | |
| unique_line_ratio=len(set(lines)) / max(len(lines), 1), | |
| unique_word_ratio=len(set(content_words)) / max(len(content_words), 1), | |
| short_line_ratio=short_lines / max(len(lines), 1), | |
| list_line_ratio=list_lines / max(len(lines), 1), | |
| table_line_ratio=table_lines / max(len(lines), 1), | |
| boilerplate_hits_per_1k=boilerplate_hits * 1000 / max(len(text), 1), | |
| repeated_character_run=max(repeated_runs, default=1), | |
| code_line_ratio=code_lines / max(len(lines), 1), | |
| code_math_char_ratio=code_math_count / max(len(visible), 1), | |
| ) | |
| def rejection_reason( | |
| text: str, | |
| config: FilterConfig, | |
| *, | |
| metrics: TextMetrics | None = None, | |
| ) -> str | None: | |
| metrics = metrics or measure_text(text) | |
| if metrics.characters < config.min_chars: | |
| return "too_short" | |
| if metrics.characters > config.max_chars: | |
| return "too_long" | |
| if metrics.hangul_characters < config.min_hangul_chars: | |
| return "too_little_hangul" | |
| if metrics.hangul_letter_ratio < config.min_hangul_letter_ratio: | |
| return "low_hangul_letter_ratio" | |
| if metrics.hangul_visible_ratio < config.min_hangul_visible_ratio: | |
| return "low_hangul_visible_ratio" | |
| if metrics.digit_ratio > config.max_digit_ratio: | |
| return "digit_heavy" | |
| if metrics.symbol_ratio > config.max_symbol_ratio: | |
| return "symbol_heavy" | |
| if metrics.repeated_character_run > config.max_repeated_character_run: | |
| return "repeated_character_run" | |
| if metrics.url_per_word > config.max_url_per_word: | |
| return "too_many_urls" | |
| if ( | |
| len(text.splitlines()) >= 5 | |
| and metrics.unique_line_ratio < config.min_unique_line_ratio | |
| ): | |
| return "repeated_lines" | |
| if len(WORD_RE.findall(text)) >= 100 and ( | |
| metrics.unique_word_ratio < config.min_unique_word_ratio | |
| ): | |
| return "low_unique_word_ratio" | |
| if ( | |
| len(text.splitlines()) >= 8 | |
| and metrics.short_line_ratio > config.max_short_line_ratio | |
| ): | |
| return "short_line_heavy" | |
| if ( | |
| len(text.splitlines()) >= 8 | |
| and metrics.list_line_ratio > config.max_list_line_ratio | |
| ): | |
| return "list_heavy" | |
| if ( | |
| len(text.splitlines()) >= 4 | |
| and metrics.table_line_ratio > config.max_table_line_ratio | |
| ): | |
| return "table_heavy" | |
| if metrics.boilerplate_hits_per_1k > config.max_boilerplate_hits_per_1k: | |
| return "boilerplate_heavy" | |
| if ( | |
| len(text.splitlines()) >= 4 | |
| and metrics.code_line_ratio > config.max_code_line_ratio | |
| ): | |
| return "code_heavy" | |
| if metrics.code_math_char_ratio > config.max_code_math_char_ratio: | |
| return "code_or_math_heavy" | |
| if quality_score(metrics, config) < config.min_quality_score: | |
| return "low_quality_score" | |
| return None | |
| def quality_score(metrics: TextMetrics, config: FilterConfig) -> float: | |
| """Return a conservative 0..1 heuristic used for corpus auditing.""" | |
| hangul_score = min( | |
| 1.0, | |
| metrics.hangul_visible_ratio | |
| / max(config.min_hangul_visible_ratio * 1.5, 1e-9), | |
| ) | |
| digit_score = max( | |
| 0.0, | |
| 1.0 | |
| - metrics.digit_ratio / max(config.max_digit_ratio * 2.0, 1e-9), | |
| ) | |
| symbol_score = max( | |
| 0.0, | |
| 1.0 | |
| - metrics.symbol_ratio / max(config.max_symbol_ratio * 2.0, 1e-9), | |
| ) | |
| line_score = min(1.0, metrics.unique_line_ratio) | |
| word_score = min(1.0, metrics.unique_word_ratio / 0.50) | |
| score = ( | |
| 0.35 * hangul_score | |
| + 0.20 * digit_score | |
| + 0.15 * symbol_score | |
| + 0.15 * line_score | |
| + 0.15 * word_score | |
| ) | |
| return max(0.0, min(1.0, score)) | |
| def near_duplicate_signature(text: str, *, sketch_size: int = 4) -> str: | |
| """Build a bottom-k paragraph/chunk sketch for conservative near deduplication.""" | |
| if sketch_size <= 0: | |
| raise ValueError("sketch_size must be positive") | |
| canonical_blocks: list[str] = [] | |
| for paragraph in re.split(r"\n+", text): | |
| canonical = NON_CONTENT_RE.sub("", paragraph.casefold()) | |
| if len(canonical) < 40: | |
| continue | |
| if len(canonical) <= 320: | |
| canonical_blocks.append(canonical) | |
| continue | |
| for start in range(0, len(canonical), 240): | |
| chunk = canonical[start : start + 320] | |
| if len(chunk) >= 80: | |
| canonical_blocks.append(chunk) | |
| if not canonical_blocks: | |
| canonical = NON_CONTENT_RE.sub("", text.casefold()) | |
| canonical_blocks = [ | |
| canonical[start : start + 320] | |
| for start in range(0, len(canonical), 240) | |
| if len(canonical[start : start + 320]) >= 40 | |
| ] | |
| fingerprints = sorted( | |
| { | |
| hashlib.blake2b( | |
| block.encode("utf-8"), digest_size=8, person=b"kawk-v2" | |
| ).hexdigest() | |
| for block in canonical_blocks | |
| } | |
| ) | |
| length_bucket = int(math.log2(max(len(text), 1)) * 4) | |
| selected = fingerprints[:sketch_size] | |
| return f"{length_bucket}:" + ":".join(selected) | |
| def canonical_hash(text: str) -> str: | |
| canonical = " ".join(text.casefold().split()) | |
| return hashlib.sha256(canonical.encode("utf-8")).hexdigest() | |
| def split_for_hash( | |
| document_hash: str, | |
| *, | |
| validation_ratio: float, | |
| test_ratio: float, | |
| seed: int, | |
| ) -> str: | |
| if validation_ratio < 0 or test_ratio < 0: | |
| raise ValueError("split ratios must be non-negative") | |
| if validation_ratio + test_ratio >= 1: | |
| raise ValueError("validation_ratio + test_ratio must be less than 1") | |
| digest = hashlib.blake2b( | |
| f"{seed}:{document_hash}".encode("ascii"), digest_size=8 | |
| ).digest() | |
| value = int.from_bytes(digest, "big") / 2**64 | |
| if value < test_ratio: | |
| return "test" | |
| if value < test_ratio + validation_ratio: | |
| return "validation" | |
| return "train" | |