"""KavaRedactor: Fast, deterministic, zero-hallucination PII redaction using Kava-Privacy-30M. Example: from redactor import KavaRedactor redactor = KavaRedactor.from_pretrained("KvcHub/Kava-Privacy-30M") result = redactor.redact("Contact Alice Smith at alice@example.com or SSN 123-45-6789.") print(result["redacted_text"]) # Contact [PERSON] at [EMAIL] or SSN [NATIONAL_ID]. """ from __future__ import annotations from typing import Any, Dict, Iterable, List, Optional, Set, Tuple import torch from transformers import AutoModelForTokenClassification, AutoTokenizer class KavaRedactor: """High-level sliding-window PII detector and deterministic redactor.""" def __init__( self, model: Any, tokenizer: Any, device: Optional[str] = None, max_length: int = 384, stride: int = 64, ) -> None: if device is None: if torch.cuda.is_available(): device = "cuda" elif torch.backends.mps.is_available(): device = "mps" else: device = "cpu" self.device = torch.device(device) self.model = model.to(self.device).eval() self.tokenizer = tokenizer self.max_length = max_length self.stride = stride self.id2label: Dict[int, str] = {int(k): v for k, v in self.model.config.id2label.items()} @classmethod def from_pretrained( cls, model_name_or_path: str = "KvcHub/Kava-Privacy-30M", device: Optional[str] = None, **kwargs: Any, ) -> "KavaRedactor": tokenizer = AutoTokenizer.from_pretrained(model_name_or_path) model = AutoModelForTokenClassification.from_pretrained(model_name_or_path) return cls(model=model, tokenizer=tokenizer, device=device, **kwargs) @torch.no_grad() def detect( self, text: str, score_threshold: float = 0.50, entities: Optional[Iterable[str]] = None, ) -> List[Dict[str, Any]]: """Detect character-level PII spans in arbitrary-length text.""" if not text or not text.strip(): return [] allowed: Optional[Set[str]] = set(entities) if entities is not None else None enc = self.tokenizer( text, add_special_tokens=True, truncation=True, max_length=self.max_length, stride=self.stride, return_overflowing_tokens=True, return_offsets_mapping=True, padding=True, return_tensors="pt", ) input_ids = enc["input_ids"].to(self.device) attention_mask = enc["attention_mask"].to(self.device) offsets_batch = enc["offset_mapping"].tolist() if self.device.type in ("cuda", "mps"): with torch.autocast(self.device.type, dtype=torch.bfloat16): logits = self.model(input_ids=input_ids, attention_mask=attention_mask).logits else: logits = self.model(input_ids=input_ids, attention_mask=attention_mask).logits probs = torch.softmax(logits.float(), dim=-1) scores, pred_ids = probs.max(dim=-1) scores_list = scores.cpu().tolist() preds_list = pred_ids.cpu().tolist() raw_spans: List[Dict[str, Any]] = [] for win_i in range(len(preds_list)): offsets = offsets_batch[win_i] w_preds = preds_list[win_i] w_scores = scores_list[win_i] cur_label: Optional[str] = None cur_start = -1 cur_end = -1 cur_scores: List[float] = [] def flush() -> None: nonlocal cur_label, cur_start, cur_end, cur_scores if cur_label is not None and cur_end > cur_start: avg_score = sum(cur_scores) / len(cur_scores) if avg_score >= score_threshold and (allowed is None or cur_label in allowed): s, e = cur_start, cur_end while s < e and text[s].isspace(): s += 1 while e > s and text[e - 1].isspace(): e -= 1 if e > s: raw_spans.append({ "start": s, "end": e, "label": cur_label, "text": text[s:e], "score": round(avg_score, 4), }) cur_label = None cur_start = -1 cur_end = -1 cur_scores = [] for tok_i, (ts, te) in enumerate(offsets): if ts == 0 and te == 0: flush() continue lbl = self.id2label.get(w_preds[tok_i], "O") sc = w_scores[tok_i] if lbl.startswith("B-"): flush() cur_label = lbl[2:] cur_start = ts cur_end = te cur_scores = [sc] elif lbl.startswith("I-"): ent = lbl[2:] if cur_label == ent and ts <= cur_end + 1: cur_end = max(cur_end, te) cur_scores.append(sc) else: flush() cur_label = ent cur_start = ts cur_end = te cur_scores = [sc] else: flush() flush() # Deduplicate overlapping spans from sliding windows (prefer higher confidence, then longer span) raw_spans.sort(key=lambda sp: (sp["start"], -sp["score"], -(sp["end"] - sp["start"]))) merged: List[Dict[str, Any]] = [] for sp in raw_spans: if not merged: merged.append(sp) continue prev = merged[-1] if sp["start"] < prev["end"]: if sp["label"] == prev["label"]: # Merge overlapping identical-type spans from adjacent windows prev["end"] = max(prev["end"], sp["end"]) prev["text"] = text[prev["start"]:prev["end"]] prev["score"] = round(max(prev["score"], sp["score"]), 4) elif sp["score"] > prev["score"]: merged[-1] = sp else: merged.append(sp) return merged def redact( self, text: str, score_threshold: float = 0.50, entities: Optional[Iterable[str]] = None, placeholder_format: str = "[{label}]", ) -> Dict[str, Any]: """Return redacted text and the exact list of detected PII spans.""" spans = self.detect(text, score_threshold=score_threshold, entities=entities) if not spans: return {"redacted_text": text, "spans": []} parts: List[str] = [] cursor = 0 for sp in spans: parts.append(text[cursor:sp["start"]]) parts.append(placeholder_format.format(label=sp["label"])) cursor = sp["end"] parts.append(text[cursor:]) return {"redacted_text": "".join(parts), "spans": spans}