""" Post Validator -- Stage 3 of the humanization pipeline. All checks run locally (no API calls): 3a. Length validation & smart trimming 3b. Banned word auto-replacement 3c. Optional perplexity re-scoring (thorough mode) 3d. Grammar checking (language_tool_python) + NER preservation 3e. Stats aggregation """ from __future__ import annotations import json import logging import random import re import statistics import time from pathlib import Path from typing import Any, TYPE_CHECKING from app.core.perturbation import TextPerturber from app.utils.text_utils import ( count_words, split_sentences, calculate_burstiness, calculate_expansion_percentage, sentence_word_counts, ) if TYPE_CHECKING: from app.core.perplexity_scorer import PerplexityScorer logger = logging.getLogger(__name__) class PostValidator: """Stage 3 post-validation and micro-corrections. Args: nlp: Loaded spaCy model (for NER, sentence splitting). perplexity_scorer: Loaded PerplexityScorer (for thorough mode re-scoring). language_tool: Loaded language_tool_python.LanguageTool instance. vocab_path: Path to ai_vocabulary.json (for auto-replacement suggestions). """ def __init__( self, nlp: Any = None, perplexity_scorer: "PerplexityScorer | None" = None, language_tool: Any = None, vocab_path: str = "app/data/ai_vocabulary.json", ) -> None: self.nlp = nlp self.perplexity_scorer = perplexity_scorer self.language_tool = language_tool self._perturber = TextPerturber(intensity=0.12, filler_rate=0.05) self._vocab: dict[str, Any] = {} self._load_vocab(vocab_path) def _load_vocab(self, vocab_path: str) -> None: """Load AI vocabulary with suggestions for auto-replacement.""" path = Path(vocab_path) if not path.exists(): alt = Path(__file__).parent.parent / "data" / "ai_vocabulary.json" path = alt if alt.exists() else path if path.exists(): try: with open(path, "r", encoding="utf-8") as f: self._vocab = json.load(f) except Exception as exc: logger.warning("Failed to load vocabulary for post-validation: %s", exc) # ------------------------------------------------------------------ # Public API # ------------------------------------------------------------------ def validate( self, original_text: str, rewritten_text: str, analysis_result: dict[str, Any], mode: str = "standard", ) -> dict[str, Any]: """Run all post-validation checks and return corrected text + stats. Args: original_text: The original input text. rewritten_text: Stage 2 LLM output. analysis_result: Stage 1 AnalysisResult dict. mode: 'standard' or 'thorough'. Returns: Dict with 'output_text' and 'stats'. """ t0 = time.perf_counter() text = rewritten_text banned_words = analysis_result.get("banned_words", []) # 3a. Length validation text = self._validate_length(text, original_text) # 3b. Banned word auto-replacement text, words_found, words_fixed = self._fix_banned_words(text, banned_words) # 3b2. Perturbation -- break AI statistical fingerprint text = self._perturber.perturb(text) # 3d. Grammar check grammar_fixes = 0 if self.language_tool: text, grammar_fixes = self._check_grammar(text) # 3d. NER preservation check ner_warnings = self._check_ner_preservation(original_text, text) # 3c. Perplexity re-scoring (thorough mode only) output_avg_ppl = None if mode == "thorough" and self.perplexity_scorer: output_avg_ppl = self._rescore_perplexity(text) # 3e. Stats input_wc = count_words(original_text) output_wc = count_words(text) expansion = calculate_expansion_percentage(input_wc, output_wc) # Input perplexity stats from analysis ppl_data = analysis_result.get("sentence_perplexities", []) input_ppls = [s["mean_ppl"] for s in ppl_data if "mean_ppl" in s] input_avg_ppl = round(statistics.mean(input_ppls), 1) if input_ppls else None # Output burstiness out_sentences = split_sentences(text, nlp=self.nlp) out_wcs = sentence_word_counts(out_sentences) out_burst = calculate_burstiness(out_wcs) # Input burstiness from analysis input_cv = analysis_result.get("summary", {}).get("burstiness_cv", None) elapsed = round((time.perf_counter() - t0) * 1000, 1) stats = { "input_word_count": input_wc, "output_word_count": output_wc, "expansion_percentage": expansion, "input_avg_perplexity": input_avg_ppl, "output_avg_perplexity": output_avg_ppl, "input_burstiness_cv": input_cv, "output_burstiness_cv": round(out_burst["cv"], 4) if out_burst else None, "banned_words_found_in_output": words_found, "banned_words_auto_fixed": words_fixed, "instructions_generated": len(analysis_result.get("instructions", [])), "high_risk_sentences": analysis_result.get("summary", {}).get("high_risk_sentences", 0), "grammar_fixes": grammar_fixes, "ner_warnings": ner_warnings, "stage3_time_ms": elapsed, } return {"output_text": text, "stats": stats} # ------------------------------------------------------------------ # 3a. Length validation # ------------------------------------------------------------------ def _validate_length(self, text: str, original_text: str) -> str: """Trim output if expansion exceeds 40%.""" input_wc = count_words(original_text) output_wc = count_words(text) if input_wc == 0: return text expansion = (output_wc - input_wc) / input_wc * 100 if expansion <= 40.0: return text # Over 40%: trim sentences from the end until within budget. target_wc = int(input_wc * 1.35) sentences = split_sentences(text, nlp=self.nlp) trimmed = [] wc_so_far = 0 for sent in sentences: sent_wc = count_words(sent) if wc_so_far + sent_wc > target_wc and trimmed: break trimmed.append(sent) wc_so_far += sent_wc result = " ".join(trimmed) logger.info( "Length trimmed: %d -> %d words (target %d)", output_wc, count_words(result), target_wc, ) return result # ------------------------------------------------------------------ # 3b. Banned word auto-replacement # ------------------------------------------------------------------ def _fix_banned_words( self, text: str, banned_words: list[str] ) -> tuple[str, list[str], int]: """Find and replace banned words using vocabulary suggestions. Skips words that are part of proper names or tool names. Returns: (fixed_text, list_of_found_words, count_of_fixes). """ found: list[str] = [] fix_count = 0 # Sort banned words longest-first to handle phrases before single words. for word in sorted(banned_words, key=len, reverse=True): pattern = re.compile(r'\b' + re.escape(word) + r'\b', re.IGNORECASE) matches = list(pattern.finditer(text)) if not matches: continue found.append(word) replacement = self._get_replacement(word) if not replacement: continue # Replace matches that are NOT part of proper names (go backwards) for match in reversed(matches): if self._is_part_of_proper_name(text, match): continue original = match.group(0) rep = replacement if original[0].isupper(): rep = rep[0].upper() + rep[1:] text = text[:match.start()] + rep + text[match.end():] fix_count += 1 if fix_count > 0: logger.debug("Auto-replaced banned word '%s' -> '%s'", word, replacement) return text, found, fix_count @staticmethod def _is_part_of_proper_name(text: str, match: re.Match) -> bool: """Check if a match is part of a proper name / tool name.""" start = match.start() end = match.end() # Hyphen before or after if start > 0 and text[start - 1] == '-': return True if end < len(text) and text[end] == '-': return True # Next word is capitalized => likely a proper compound name after = text[end:end + 20].lstrip() if after and after[0].isupper(): return True # Previous word is capitalized (and not after punctuation) before_text = text[max(0, start - 30):start].rstrip() if before_text: prev_words = before_text.split() if prev_words: prev_word = prev_words[-1] if ( prev_word[0].isupper() and prev_word[-1] not in '.!?' and not prev_word.endswith(',') ): return True return False def _get_replacement(self, word: str) -> str | None: """Look up a replacement for a banned word from the vocabulary DB.""" word_lower = word.lower() # Check single_words single = self._vocab.get("single_words", {}) entry = single.get(word_lower) if entry: suggestions = entry.get("suggestions", []) if suggestions: return random.choice(suggestions) # Check phrases phrases = self._vocab.get("phrases", {}) entry = phrases.get(word_lower) if entry: suggestions = entry.get("suggestions", []) if suggestions: return random.choice(suggestions) return None # ------------------------------------------------------------------ # 3c. Perplexity re-scoring (thorough mode) # ------------------------------------------------------------------ def _rescore_perplexity(self, text: str) -> float | None: """Re-score the output text's perplexity. Returns average or None.""" if not self.perplexity_scorer: return None try: sentences = split_sentences(text, nlp=self.nlp) results = self.perplexity_scorer.score_sentences(sentences) ppls = [r.mean_perplexity for r in results] return round(statistics.mean(ppls), 1) if ppls else None except Exception as exc: logger.warning("Perplexity re-scoring failed: %s", exc) return None # ------------------------------------------------------------------ # 3d. Grammar check + NER preservation # ------------------------------------------------------------------ def _check_grammar(self, text: str) -> tuple[str, int]: """Run language_tool_python grammar check and apply fixes. Returns: (corrected_text, number_of_fixes). """ try: matches = self.language_tool.check(text) if not matches: return text, 0 # Apply corrections (language_tool_python utility). import language_tool_python corrected = language_tool_python.utils.correct(text, matches) return corrected, len(matches) except Exception as exc: logger.warning("Grammar check failed: %s", exc) return text, 0 def _check_ner_preservation(self, original: str, rewritten: str) -> list[str]: """Check that named entities from the original are preserved. Returns list of warning strings for any missing entities. """ if not self.nlp: return [] try: orig_doc = self.nlp(original) new_doc = self.nlp(rewritten) orig_ents = {ent.text.lower() for ent in orig_doc.ents} new_ents = {ent.text.lower() for ent in new_doc.ents} missing = orig_ents - new_ents warnings = [] for ent in missing: # Only warn about significant entities (skip single-letter matches). if len(ent) > 2: warnings.append(f"Named entity '{ent}' from original not found in output") if warnings: logger.warning("NER preservation issues: %s", warnings) return warnings except Exception as exc: logger.warning("NER check failed: %s", exc) return []