zenex-ai-project / data /preprocess.py
shashankmacherla's picture
Upload full llm_project
6d5c79f verified
Raw History Blame Contribute Delete
4.39 kB
"""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()