File size: 4,394 Bytes
6d5c79f | 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 | """Local preprocessing pipeline: dedup, license filter, quality filter, PII scrub."""
from __future__ import annotations
import argparse
import json
import logging
import re
from pathlib import Path
from typing import Iterable
from datasketch import MinHash, MinHashLSH
LOGGER = logging.getLogger(__name__)
PERMISSIVE_LICENSE_PATTERNS = [
re.compile(r"\bMIT\b", re.IGNORECASE),
re.compile(r"Apache(?:\s+License)?\s+2(?:\.0)?", re.IGNORECASE),
re.compile(r"\bBSD(?:\s+[23]-Clause)?\b", re.IGNORECASE),
]
PII_PATTERNS = [
re.compile(r"\b[\w\.-]+@[\w\.-]+\.\w+\b"),
re.compile(r"\b\+?\d{1,3}[\s-]?\(?\d{2,4}\)?[\s-]?\d{3,4}[\s-]?\d{3,4}\b"),
re.compile(r"\b\d{3}-\d{2}-\d{4}\b"),
re.compile(r"\b(?:\d[ -]*?){13,16}\b"),
]
def iter_jsonl(path: Path) -> Iterable[dict]:
"""Yield records from JSONL input."""
with path.open("r", encoding="utf-8") as f:
for line in f:
if line.strip():
yield json.loads(line)
def text_to_minhash(text: str, num_perm: int = 128) -> MinHash:
"""Create MinHash signature from text n-grams."""
mh = MinHash(num_perm=num_perm)
tokens = text.split()
for i in range(max(1, len(tokens) - 4)):
gram = " ".join(tokens[i : i + 5]).encode("utf-8", errors="ignore")
mh.update(gram)
return mh
def is_permissive_license(license_text: str) -> bool:
"""Allow only MIT/Apache/BSD-compatible licenses."""
return any(pattern.search(license_text) for pattern in PERMISSIVE_LICENSE_PATTERNS)
def pii_scrub(text: str) -> str:
"""Remove common PII patterns from text."""
for pattern in PII_PATTERNS:
text = pattern.sub("[REDACTED]", text)
return text
def simple_quality_score(text: str) -> float:
"""Heuristic local quality scoring fallback when fastText is unavailable."""
if not text:
return 0.0
alpha = sum(c.isalpha() for c in text)
printable = sum(c.isprintable() for c in text)
return (alpha / max(1, len(text))) * (printable / max(1, len(text)))
def validate_syntax(language: str, code: str) -> bool:
"""Language-aware syntax validation for selected languages."""
if language.lower() == "python":
try:
compile(code, "<string>", "exec")
return True
except SyntaxError:
return False
# For non-Python languages, parser hooks can be added using tree-sitter.
return True
def preprocess_file(input_path: Path, output_path: Path, min_quality: float = 0.15) -> int:
"""Preprocess a JSONL file and write cleaned JSONL output."""
lsh = MinHashLSH(threshold=0.9, num_perm=128)
kept = 0
output_path.parent.mkdir(parents=True, exist_ok=True)
with output_path.open("w", encoding="utf-8") as out_f:
for i, rec in enumerate(iter_jsonl(input_path)):
text = rec.get("text", "")
license_text = rec.get("license", "")
language = rec.get("language", "text")
if license_text and not is_permissive_license(license_text):
continue
text = pii_scrub(text)
if simple_quality_score(text) < min_quality:
continue
if language.lower() in {"python", "py"} and not validate_syntax("python", text):
continue
sig = text_to_minhash(text)
key = f"doc-{i}"
if lsh.query(sig):
continue
lsh.insert(key, sig)
rec["text"] = text
out_f.write(json.dumps(rec, ensure_ascii=False) + "\n")
kept += 1
return kept
def parse_args() -> argparse.Namespace:
"""Parse CLI arguments."""
parser = argparse.ArgumentParser(description="Local preprocessing pipeline")
parser.add_argument("--input", type=Path, required=True, help="Input JSONL path")
parser.add_argument("--output", type=Path, required=True, help="Output JSONL path")
parser.add_argument("--min-quality", type=float, default=0.15)
return parser.parse_args()
def main() -> None:
"""CLI entrypoint."""
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
args = parse_args()
kept = preprocess_file(args.input, args.output, min_quality=args.min_quality)
LOGGER.info("Preprocessing complete. Kept records: %d", kept)
if __name__ == "__main__":
main()
|