Download scripts/prepare_corpus.py from Infinity08/KAWK50M-Project: direct link, hf CLI and curl.
- Browser
- Download file 12.7 kB
-
https://huggingface.co/datasets/Infinity08/KAWK50M-Project/resolve/main/scripts/prepare_corpus.py
- Command line
-
hf download hf://datasets/Infinity08/KAWK50M-Project/scripts/prepare_corpus.py
-
curl -L -o prepare_corpus.py https://huggingface.co/datasets/Infinity08/KAWK50M-Project/resolve/main/scripts/prepare_corpus.py
12.7 kB
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import sqlite3 | |
| from collections import Counter | |
| from collections import deque | |
| from concurrent.futures import ProcessPoolExecutor | |
| from collections.abc import Iterable, Iterator | |
| from dataclasses import asdict | |
| from pathlib import Path | |
| from typing import Any | |
| from tqdm import tqdm | |
| from kawk50m.cli import configure_utf8_stdio | |
| from kawk50m.io import ShardedJsonlWriter, discover_paths, iter_documents | |
| from kawk50m.text import ( | |
| FilterConfig, | |
| canonical_hash, | |
| measure_text, | |
| near_duplicate_signature, | |
| normalize_text, | |
| quality_score, | |
| rejection_reason, | |
| split_for_hash, | |
| ) | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser( | |
| description=( | |
| "Clean, quality-filter, exactly/approximately deduplicate, " | |
| "and split Korean documents." | |
| ) | |
| ) | |
| parser.add_argument( | |
| "--input", | |
| nargs="+", | |
| required=True, | |
| help="Input files, directories, or glob patterns (.jsonl/.txt, optionally .gz).", | |
| ) | |
| parser.add_argument("--output-dir", default="data/clean") | |
| parser.add_argument("--text-field", default="text") | |
| parser.add_argument("--txt-mode", choices=("line", "document"), default="line") | |
| parser.add_argument("--documents-per-shard", type=int, default=50_000) | |
| parser.add_argument("--validation-ratio", type=float, default=0.002) | |
| parser.add_argument("--test-ratio", type=float, default=0.001) | |
| parser.add_argument("--seed", type=int, default=42) | |
| parser.add_argument("--limit", type=int, default=None) | |
| parser.add_argument( | |
| "--workers", | |
| type=int, | |
| default=1, | |
| help="Process normalization/filtering/hash batches in parallel.", | |
| ) | |
| parser.add_argument( | |
| "--worker-batch-size", | |
| type=int, | |
| default=64, | |
| help="Documents submitted to each filtering worker at once.", | |
| ) | |
| parser.add_argument("--min-chars", type=int, default=300) | |
| parser.add_argument("--max-chars", type=int, default=100_000) | |
| parser.add_argument("--min-hangul-chars", type=int, default=50) | |
| parser.add_argument("--min-hangul-ratio", type=float, default=0.70) | |
| parser.add_argument("--min-hangul-visible-ratio", type=float, default=0.55) | |
| parser.add_argument("--max-digit-ratio", type=float, default=0.08) | |
| parser.add_argument("--max-symbol-ratio", type=float, default=0.15) | |
| parser.add_argument("--max-url-per-word", type=float, default=0.01) | |
| parser.add_argument("--min-unique-line-ratio", type=float, default=0.70) | |
| parser.add_argument("--min-unique-word-ratio", type=float, default=0.20) | |
| parser.add_argument("--max-short-line-ratio", type=float, default=0.50) | |
| parser.add_argument("--max-list-line-ratio", type=float, default=0.25) | |
| parser.add_argument("--max-table-line-ratio", type=float, default=0.10) | |
| parser.add_argument( | |
| "--max-boilerplate-hits-per-1k", type=float, default=1.5 | |
| ) | |
| parser.add_argument("--max-repeated-character-run", type=int, default=20) | |
| parser.add_argument("--max-code-line-ratio", type=float, default=0.25) | |
| parser.add_argument("--max-code-math-char-ratio", type=float, default=0.15) | |
| parser.add_argument("--min-quality-score", type=float, default=0.70) | |
| parser.add_argument( | |
| "--disable-near-dedupe", | |
| action="store_true", | |
| help="Disable bottom-k paragraph/chunk near-duplicate sketches.", | |
| ) | |
| parser.add_argument( | |
| "--keep-html", action="store_true", help="Do not remove residual HTML tags." | |
| ) | |
| parser.add_argument( | |
| "--keep-pii", | |
| action="store_true", | |
| help="Do not replace email, phone, and resident-registration patterns.", | |
| ) | |
| return parser.parse_args() | |
| def process_document( | |
| document: dict[str, Any], | |
| filter_config: FilterConfig, | |
| ) -> tuple[dict[str, Any], str, str | None, str | None, str | None, float]: | |
| text = normalize_text( | |
| document["text"], | |
| strip_html=filter_config.strip_html, | |
| mask_pii=filter_config.mask_pii, | |
| ) | |
| metrics = measure_text(text) | |
| reason = rejection_reason(text, filter_config, metrics=metrics) | |
| document_hash = canonical_hash(text) if reason is None else None | |
| near_signature = ( | |
| near_duplicate_signature(text) if reason is None else None | |
| ) | |
| score = quality_score(metrics, filter_config) | |
| return document, text, reason, document_hash, near_signature, score | |
| def process_batch( | |
| documents: list[dict[str, Any]], | |
| filter_config: FilterConfig, | |
| ) -> list[ | |
| tuple[dict[str, Any], str, str | None, str | None, str | None, float] | |
| ]: | |
| return [process_document(document, filter_config) for document in documents] | |
| def document_batches( | |
| documents: Iterable[dict[str, Any]], | |
| *, | |
| batch_size: int, | |
| limit: int | None, | |
| ) -> Iterator[list[dict[str, Any]]]: | |
| batch: list[dict[str, Any]] = [] | |
| seen = 0 | |
| for document in documents: | |
| if limit is not None and seen >= limit: | |
| break | |
| batch.append(document) | |
| seen += 1 | |
| if len(batch) >= batch_size: | |
| yield batch | |
| batch = [] | |
| if batch: | |
| yield batch | |
| def processed_documents( | |
| documents: Iterable[dict[str, Any]], | |
| *, | |
| filter_config: FilterConfig, | |
| workers: int, | |
| batch_size: int, | |
| limit: int | None, | |
| ) -> Iterator[ | |
| tuple[dict[str, Any], str, str | None, str | None, str | None, float] | |
| ]: | |
| batches = document_batches(documents, batch_size=batch_size, limit=limit) | |
| if workers == 1: | |
| for batch in batches: | |
| yield from process_batch(batch, filter_config) | |
| return | |
| max_pending = workers * 2 | |
| pending: deque[Any] = deque() | |
| with ProcessPoolExecutor(max_workers=workers) as executor: | |
| for batch in batches: | |
| pending.append(executor.submit(process_batch, batch, filter_config)) | |
| if len(pending) >= max_pending: | |
| yield from pending.popleft().result() | |
| while pending: | |
| yield from pending.popleft().result() | |
| def ensure_safe_output(output_dir: Path) -> None: | |
| existing = [ | |
| *output_dir.glob("train-*.jsonl"), | |
| *output_dir.glob("validation-*.jsonl"), | |
| *output_dir.glob("test-*.jsonl"), | |
| ] | |
| if existing: | |
| names = ", ".join(path.name for path in existing[:3]) | |
| raise FileExistsError( | |
| f"{output_dir} already contains generated shards ({names}). " | |
| "Choose a new output directory to avoid overwriting data." | |
| ) | |
| def main() -> None: | |
| configure_utf8_stdio() | |
| args = parse_args() | |
| paths = discover_paths(args.input) | |
| if not paths: | |
| raise FileNotFoundError("No supported input files were found") | |
| if args.documents_per_shard <= 0: | |
| raise ValueError("--documents-per-shard must be positive") | |
| if args.workers <= 0: | |
| raise ValueError("--workers must be positive") | |
| if args.worker_batch_size <= 0: | |
| raise ValueError("--worker-batch-size must be positive") | |
| filter_config = FilterConfig( | |
| min_chars=args.min_chars, | |
| max_chars=args.max_chars, | |
| min_hangul_chars=args.min_hangul_chars, | |
| min_hangul_letter_ratio=args.min_hangul_ratio, | |
| min_hangul_visible_ratio=args.min_hangul_visible_ratio, | |
| max_digit_ratio=args.max_digit_ratio, | |
| max_symbol_ratio=args.max_symbol_ratio, | |
| max_url_per_word=args.max_url_per_word, | |
| min_unique_line_ratio=args.min_unique_line_ratio, | |
| min_unique_word_ratio=args.min_unique_word_ratio, | |
| max_short_line_ratio=args.max_short_line_ratio, | |
| max_list_line_ratio=args.max_list_line_ratio, | |
| max_table_line_ratio=args.max_table_line_ratio, | |
| max_boilerplate_hits_per_1k=args.max_boilerplate_hits_per_1k, | |
| max_repeated_character_run=args.max_repeated_character_run, | |
| max_code_line_ratio=args.max_code_line_ratio, | |
| max_code_math_char_ratio=args.max_code_math_char_ratio, | |
| min_quality_score=args.min_quality_score, | |
| strip_html=not args.keep_html, | |
| mask_pii=not args.keep_pii, | |
| ) | |
| output_dir = Path(args.output_dir) | |
| output_dir.mkdir(parents=True, exist_ok=True) | |
| ensure_safe_output(output_dir) | |
| dedupe_path = output_dir / "exact_dedupe.sqlite3" | |
| if dedupe_path.exists(): | |
| raise FileExistsError( | |
| f"{dedupe_path} already exists. Choose a new output directory." | |
| ) | |
| counters: Counter[str] = Counter() | |
| writers = { | |
| split: ShardedJsonlWriter( | |
| output_dir, split, documents_per_shard=args.documents_per_shard | |
| ) | |
| for split in ("train", "validation", "test") | |
| } | |
| connection = sqlite3.connect(dedupe_path) | |
| connection.execute("PRAGMA journal_mode=WAL") | |
| connection.execute("PRAGMA synchronous=NORMAL") | |
| connection.execute("CREATE TABLE hashes (hash TEXT PRIMARY KEY)") | |
| if not args.disable_near_dedupe: | |
| connection.execute( | |
| "CREATE TABLE near_signatures (signature TEXT PRIMARY KEY)" | |
| ) | |
| try: | |
| documents = iter_documents( | |
| paths, text_field=args.text_field, txt_mode=args.txt_mode | |
| ) | |
| processed = processed_documents( | |
| documents, | |
| filter_config=filter_config, | |
| workers=args.workers, | |
| batch_size=args.worker_batch_size, | |
| limit=args.limit, | |
| ) | |
| for index, ( | |
| document, | |
| text, | |
| reason, | |
| document_hash, | |
| near_signature, | |
| score, | |
| ) in enumerate( | |
| tqdm(processed, total=args.limit, unit="docs"), | |
| start=1, | |
| ): | |
| counters["seen"] += 1 | |
| if reason is not None: | |
| counters[f"rejected_{reason}"] += 1 | |
| else: | |
| assert document_hash is not None | |
| cursor = connection.execute( | |
| "INSERT OR IGNORE INTO hashes(hash) VALUES (?)", (document_hash,) | |
| ) | |
| if cursor.rowcount == 0: | |
| counters["rejected_exact_duplicate"] += 1 | |
| else: | |
| if not args.disable_near_dedupe: | |
| assert near_signature is not None | |
| near_cursor = connection.execute( | |
| "INSERT OR IGNORE INTO near_signatures(signature) " | |
| "VALUES (?)", | |
| (near_signature,), | |
| ) | |
| if near_cursor.rowcount == 0: | |
| counters["rejected_near_duplicate"] += 1 | |
| continue | |
| split = split_for_hash( | |
| document_hash, | |
| validation_ratio=args.validation_ratio, | |
| test_ratio=args.test_ratio, | |
| seed=args.seed, | |
| ) | |
| output_row = { | |
| "id": document["id"], | |
| "text": text, | |
| "source": document["source"], | |
| "url": document["url"], | |
| "license": document["license"], | |
| "sha256": document_hash, | |
| "quality_score": round(score, 6), | |
| } | |
| writers[split].write(output_row) | |
| counters[f"accepted_{split}"] += 1 | |
| counters["accepted_characters"] += len(text) | |
| counters["accepted_quality_score_micros"] += round( | |
| score * 1_000_000 | |
| ) | |
| if index % 10_000 == 0: | |
| connection.commit() | |
| connection.commit() | |
| finally: | |
| connection.close() | |
| for writer in writers.values(): | |
| writer.close() | |
| stats = { | |
| "inputs": [str(path) for path in paths], | |
| "filter": asdict(filter_config), | |
| "near_dedupe": { | |
| "enabled": not args.disable_near_dedupe, | |
| "method": "bottom-k paragraph/chunk sketch", | |
| }, | |
| "split": { | |
| "train": 1.0 - args.validation_ratio - args.test_ratio, | |
| "validation": args.validation_ratio, | |
| "test": args.test_ratio, | |
| "seed": args.seed, | |
| }, | |
| "counts": dict(sorted(counters.items())), | |
| } | |
| stats_path = output_dir / "prepare_stats.json" | |
| with stats_path.open("w", encoding="utf-8") as handle: | |
| json.dump(stats, handle, ensure_ascii=False, indent=2) | |
| handle.write("\n") | |
| print(json.dumps(stats["counts"], ensure_ascii=False, indent=2)) | |
| print(f"Stats: {stats_path}") | |
| if __name__ == "__main__": | |
| main() | |