Spaces:
Runtime error
Runtime error
Download app/core/perturbation.py from digitalytics/humanizer-engine: direct link, hf CLI and curl.
- Browser
- Download file 27.8 kB
-
https://huggingface.co/spaces/digitalytics/humanizer-engine/resolve/main/app/core/perturbation.py
- Command line
-
hf download hf://spaces/digitalytics/humanizer-engine/app/core/perturbation.py
-
curl -L -o perturbation.py https://huggingface.co/spaces/digitalytics/humanizer-engine/resolve/main/app/core/perturbation.py
27.8 kB
| """ | |
| Text Perturbation Engine -- breaks AI statistical fingerprint. | |
| Based on Wikipedia's "Signs of AI writing" (WikiProject AI Cleanup). | |
| Three layers of cleanup: | |
| 1. AI pattern elimination (rule-based, deterministic): | |
| - Negative parallelisms ("It's not just X; it's Y") | |
| - Copula avoidance ("serves as" -> "is", "stands as" -> "is") | |
| - Superficial -ing tails ("...highlighting X", "...underscoring Y") | |
| - Generic positive conclusions | |
| - Filler phrases ("In order to", "Due to the fact that", "At its core") | |
| 2. Surface cleanup: | |
| - Strip AI formatting (em-dashes, markdown, smart quotes) | |
| - Replace AI vocabulary the LLM generated fresh | |
| - Remove AI-style paragraph openers | |
| 3. Contraction variation (humans are inconsistent with contractions) | |
| Applied AFTER the LLM rewrite (Stage 3 post-processing). | |
| """ | |
| from __future__ import annotations | |
| import logging | |
| import random | |
| import re | |
| from typing import Any | |
| logger = logging.getLogger(__name__) | |
| # --------------------------------------------------------------------------- | |
| # AI formatting artifacts that MUST be stripped (100%) | |
| # --------------------------------------------------------------------------- | |
| _FORMAT_REPLACEMENTS: list[tuple[str, list[str]]] = [ | |
| ("\u2014", [", ", " -- ", " - "]), # em-dash | |
| ("\u2013", [", ", " - ", " -- "]), # en-dash | |
| ("\u2018", ["'"]), # left single smart quote | |
| ("\u2019", ["'"]), # right single smart quote | |
| ("\u201c", ['"']), # left double smart quote | |
| ("\u201d", ['"']), # right double smart quote | |
| ("\u2026", ["..."]), # ellipsis character | |
| ] | |
| # --------------------------------------------------------------------------- | |
| # Global AI vocabulary the LLM commonly GENERATES fresh. | |
| # Single-word-safe replacements only. | |
| # --------------------------------------------------------------------------- | |
| _GLOBAL_AI_WORDS: dict[str, list[str]] = { | |
| # Verbs | |
| "enhance": ["lift", "raise", "sharpen", "strengthen"], | |
| "utilize": ["use", "apply", "try"], | |
| "optimize": ["tune", "refine", "sharpen", "fix up"], | |
| "leverage": ["use", "apply", "tap"], | |
| "facilitate": ["support", "enable", "help"], | |
| "implement": ["deploy", "apply", "install"], | |
| "streamline": ["simplify", "trim", "tighten"], | |
| "prioritize": ["favor", "target", "prefer"], | |
| "navigate": ["handle", "manage", "tackle"], | |
| "foster": ["encourage", "build", "grow"], | |
| "empower": ["enable", "free", "let"], | |
| "bolster": ["strengthen", "support", "reinforce"], | |
| "mitigate": ["lessen", "ease", "soften"], | |
| "encompass": ["include", "cover", "span"], | |
| "underscore": ["highlight", "stress", "show"], | |
| "spearhead": ["lead", "drive", "champion"], | |
| "revolutionize": ["reshape", "change", "overhaul"], | |
| "elevate": ["raise", "lift", "heighten"], | |
| "cultivate": ["grow", "build", "nurture"], | |
| # Adjectives | |
| "seamless": ["smooth", "easy", "simple", "clean"], | |
| "robust": ["strong", "solid", "reliable", "sturdy"], | |
| "comprehensive": ["full", "complete", "thorough", "broad"], | |
| "innovative": ["new", "fresh", "creative", "novel"], | |
| "pivotal": ["key", "central", "critical", "vital"], | |
| "crucial": ["key", "vital", "critical", "core"], | |
| "significant": ["real", "major", "big", "notable"], | |
| "substantial": ["large", "sizable", "hefty", "major"], | |
| "remarkable": ["impressive", "striking", "notable", "unusual"], | |
| "essential": ["vital", "needed", "critical", "core"], | |
| "effective": ["solid", "strong", "good", "useful"], | |
| "efficient": ["fast", "quick", "capable"], | |
| "straightforward": ["simple", "easy", "clear", "plain"], | |
| "paramount": ["critical", "top", "supreme", "chief"], | |
| "transformative": ["major", "powerful", "radical"], | |
| "unprecedented": ["rare", "unusual", "unmatched"], | |
| "multifaceted": ["complex", "layered", "varied"], | |
| "intricate": ["complex", "detailed", "involved"], | |
| "invaluable": ["priceless", "vital", "irreplaceable"], | |
| "indispensable": ["vital", "necessary", "irreplaceable"], | |
| "noteworthy": ["interesting", "notable", "striking"], | |
| "burgeoning": ["growing", "rising", "booming"], | |
| "overarching": ["main", "broad", "central"], | |
| # Adverbs | |
| "significantly": ["really", "noticeably", "greatly", "considerably"], | |
| "dramatically": ["hugely", "massively", "sharply", "wildly"], | |
| "particularly": ["especially", "mainly", "mostly", "chiefly"], | |
| "essentially": ["basically", "really", "largely"], | |
| "increasingly": ["gradually", "steadily", "progressively"], | |
| "predominantly": ["mostly", "mainly", "largely", "chiefly"], | |
| "subsequently": ["then", "later", "next", "afterwards"], | |
| "fundamentally": ["basically", "deeply", "really", "truly"], | |
| # Nouns | |
| "landscape": ["field", "area", "scene", "world"], | |
| "paradigm": ["model", "approach", "pattern"], | |
| "realm": ["area", "field", "space", "domain"], | |
| "framework": ["structure", "system", "setup"], | |
| "methodology": ["method", "approach", "way"], | |
| "infrastructure": ["setup", "backbone", "foundation"], | |
| "trajectory": ["path", "direction", "course"], | |
| "implications": ["effects", "results", "consequences"], | |
| "dynamics": ["forces", "interactions", "workings"], | |
| "stakeholders": ["parties", "players", "groups"], | |
| "synergy": ["teamwork", "cooperation", "harmony"], | |
| # Phrases | |
| "it is important to note": ["keep in mind", "worth noting"], | |
| "plays a crucial role": ["is central", "matters greatly"], | |
| "in today's world": ["these days", "right now", "currently"], | |
| "it goes without saying": ["obviously", "clearly", "of course"], | |
| "in light of": ["given", "considering"], | |
| "serves as a": ["acts as", "works as", "is"], | |
| "has the potential to": ["could", "might", "can"], | |
| "on the other hand": ["then again", "that said"], | |
| # Common LLM transitions | |
| "furthermore": ["plus", "also", "and"], | |
| "moreover": ["also", "and", "plus"], | |
| "additionally": ["also", "plus", "and"], | |
| "consequently": ["so", "hence", "thus"], | |
| "nevertheless": ["still", "yet", "but"], | |
| } | |
| # Word substitution map for random perturbation | |
| _WORD_SUBS: dict[str, list[str]] = { | |
| "boost": ["lift", "raise", "ramp up", "bump up"], | |
| "improve": ["lift", "tighten up", "make better", "step up"], | |
| "reduce": ["cut", "trim", "bring down", "shrink"], | |
| "increase": ["bump up", "push higher", "grow", "ramp up"], | |
| "provide": ["give", "offer up", "supply"], | |
| "ensure": ["make sure", "confirm"], | |
| "require": ["need", "call for", "take"], | |
| "maintain": ["keep", "hold onto", "stick with"], | |
| "achieve": ["pull off", "reach", "get to"], | |
| "demonstrate": ["show", "prove", "make clear"], | |
| "establish": ["set up", "build", "put together"], | |
| "obtain": ["get", "grab", "pick up"], | |
| "indicate": ["point to", "suggest", "hint at"], | |
| "contribute": ["add to", "chip in", "feed into"], | |
| "determine": ["figure out", "work out", "pin down"], | |
| "develop": ["build", "put together", "grow"], | |
| "generate": ["create", "produce", "come up with"], | |
| "monitor": ["track", "keep an eye on", "watch"], | |
| "employ": ["use", "put to work", "lean on"], | |
| "address": ["deal with", "tackle", "handle"], | |
| "encounter": ["run into", "face", "come across"], | |
| "select": ["pick", "go with", "choose"], | |
| "modify": ["change", "tweak", "adjust"], | |
| "eliminate": ["get rid of", "cut out", "drop"], | |
| "evaluate": ["weigh", "size up", "assess"], | |
| "minimize": ["keep low", "cut down on", "limit"], | |
| "important": ["key", "big", "a big deal"], | |
| "various": ["different", "a mix of", "several"], | |
| "numerous": ["plenty of", "lots of", "a bunch of"], | |
| "sufficient": ["enough", "plenty"], | |
| "appropriate": ["right", "fitting", "suitable"], | |
| "relevant": ["related", "tied to", "connected"], | |
| "specific": ["exact", "particular", "precise"], | |
| "primary": ["main", "top", "chief"], | |
| "potential": ["possible", "likely"], | |
| "additional": ["extra", "more", "added"], | |
| "initial": ["first", "early", "starting"], | |
| "consistent": ["steady", "reliable", "regular"], | |
| "beneficial": ["helpful", "good for", "useful"], | |
| "prevalent": ["common", "widespread"], | |
| "extensive": ["wide", "broad", "sweeping"], | |
| "specifically": ["in particular", "namely"], | |
| "effectively": ["in practice", "really"], | |
| "traditionally": ["in the past", "historically"], | |
| "ultimately": ["in the end", "when it comes down to it"], | |
| "approximately": ["around", "roughly", "about"], | |
| "individuals": ["people", "folks"], | |
| "functionality": ["features", "what it does"], | |
| "challenges": ["problems", "issues", "hurdles"], | |
| "opportunities": ["chances", "openings"], | |
| "requirements": ["needs", "demands"], | |
| "objectives": ["goals", "targets"], | |
| "perspective": ["view", "angle", "take"], | |
| "components": ["parts", "pieces"], | |
| "aspects": ["parts", "sides", "angles"], | |
| "factors": ["things", "reasons", "pieces"], | |
| "characteristics": ["traits", "qualities", "features"], | |
| "however": ["but", "that said", "then again"], | |
| "therefore": ["so", "that's why", "because of this"], | |
| "alternatively": ["or", "another option is"], | |
| } | |
| # AI-style paragraph openers that should be replaced with direct starts | |
| _AI_OPENERS: list[tuple[re.Pattern, str]] = [ | |
| (re.compile(r'^First off,?\s+', re.IGNORECASE), ""), | |
| (re.compile(r'^Another trick is\s+', re.IGNORECASE), ""), | |
| (re.compile(r'^How about\s+\w+\?\s*', re.IGNORECASE), ""), | |
| (re.compile(r'^Now let\'?s talk about\s+', re.IGNORECASE), ""), | |
| (re.compile(r'^What about\s+\w+\?\s*', re.IGNORECASE), ""), | |
| (re.compile(r'^And don\'?t forget\s+', re.IGNORECASE), ""), | |
| (re.compile(r'^Let\'?s dive into\s+', re.IGNORECASE), ""), | |
| (re.compile(r'^Let\'?s explore\s+', re.IGNORECASE), ""), | |
| (re.compile(r'^Here\'?s the (?:thing|deal)[:,]?\s*', re.IGNORECASE), ""), | |
| (re.compile(r'^So what\'?s the bottom line\?\s*', re.IGNORECASE), ""), | |
| (re.compile(r'^Moving on,?\s+', re.IGNORECASE), ""), | |
| (re.compile(r'^Next up,?\s+', re.IGNORECASE), ""), | |
| ] | |
| # --------------------------------------------------------------------------- | |
| # Public API | |
| # --------------------------------------------------------------------------- | |
| class TextPerturber: | |
| """Introduces controlled imperfections to break AI statistical fingerprint. | |
| Works at the word/phrase level only. Does NOT restructure paragraphs, | |
| merge/split sentences, or inject fragments. Those structural changes | |
| follow LLM rewriting patterns that detectors flag. | |
| """ | |
| def __init__( | |
| self, | |
| intensity: float = 0.12, | |
| filler_rate: float = 0.05, | |
| ) -> None: | |
| self.intensity = max(0.0, min(1.0, intensity)) | |
| self.filler_rate = filler_rate # kept for interface compat but not used | |
| # Pre-compile patterns | |
| self._sub_patterns: list[tuple[re.Pattern, list[str]]] = [] | |
| for word, replacements in _WORD_SUBS.items(): | |
| pattern = re.compile(r'\b' + re.escape(word) + r'\b', re.IGNORECASE) | |
| self._sub_patterns.append((pattern, replacements)) | |
| self._ai_patterns: list[tuple[re.Pattern, list[str], str]] = [] | |
| for word, replacements in _GLOBAL_AI_WORDS.items(): | |
| pattern = re.compile(r'\b' + re.escape(word) + r'\b', re.IGNORECASE) | |
| self._ai_patterns.append((pattern, replacements, word)) | |
| # ------------------------------------------------------------------ | |
| # Main entry point | |
| # ------------------------------------------------------------------ | |
| def perturb(self, text: str) -> str: | |
| """Apply perturbations to the text. | |
| Order: | |
| 1. Wikipedia AI pattern elimination (rule-based) | |
| 2. Strip AI formatting (em-dashes, markdown, smart quotes) | |
| 3. Remove AI-style paragraph openers | |
| 4. Global AI vocabulary replacement | |
| 5. Random word substitutions | |
| 6. Contraction inconsistency | |
| """ | |
| text = self._eliminate_ai_patterns(text) | |
| text = self._strip_ai_formatting(text) | |
| text = self._remove_ai_openers(text) | |
| text = self._replace_global_ai_words(text) | |
| text = self._substitute_words(text) | |
| text = self._vary_contractions(text) | |
| return text | |
| # ------------------------------------------------------------------ | |
| # Step 0: Wikipedia AI pattern elimination (rule-based) | |
| # ------------------------------------------------------------------ | |
| # Copula avoidance -- "serves as X" -> "is X", "stands as X" -> "is X" | |
| _COPULA_PATTERNS: list[tuple[re.Pattern, str]] = [ | |
| (re.compile(r'\bserves as a\b', re.IGNORECASE), "is a"), | |
| (re.compile(r'\bserves as an\b', re.IGNORECASE), "is an"), | |
| (re.compile(r'\bserves as the\b', re.IGNORECASE), "is the"), | |
| (re.compile(r'\bstands as a\b', re.IGNORECASE), "is a"), | |
| (re.compile(r'\bstands as an\b', re.IGNORECASE), "is an"), | |
| (re.compile(r'\bstands as the\b', re.IGNORECASE), "is the"), | |
| (re.compile(r'\bacts as a\b', re.IGNORECASE), "is a"), | |
| (re.compile(r'\bacts as an\b', re.IGNORECASE), "is an"), | |
| (re.compile(r'\bfunctions as a\b', re.IGNORECASE), "is a"), | |
| (re.compile(r'\bfunctions as an\b', re.IGNORECASE), "is an"), | |
| ] | |
| # Filler phrases -- replace with shorter equivalent | |
| _FILLER_PATTERNS: list[tuple[re.Pattern, str]] = [ | |
| (re.compile(r'\bin order to\b', re.IGNORECASE), "to"), | |
| (re.compile(r'\bdue to the fact that\b', re.IGNORECASE), "because"), | |
| (re.compile(r'\bat this point in time\b', re.IGNORECASE), "now"), | |
| (re.compile(r'\bin the event that\b', re.IGNORECASE), "if"), | |
| (re.compile(r'\bhas the ability to\b', re.IGNORECASE), "can"), | |
| (re.compile(r'\bhas the potential to\b', re.IGNORECASE), "can"), | |
| (re.compile(r'\bit is important to note that\b', re.IGNORECASE), ""), | |
| (re.compile(r'\bit is worth noting that\b', re.IGNORECASE), ""), | |
| (re.compile(r'\bit goes without saying that\b', re.IGNORECASE), ""), | |
| (re.compile(r'\bit should be noted that\b', re.IGNORECASE), ""), | |
| (re.compile(r'\bthe fact that\b', re.IGNORECASE), "that"), | |
| (re.compile(r'\bat its core,?\s*', re.IGNORECASE), ""), | |
| (re.compile(r'\bfirst and foremost,?\s*', re.IGNORECASE), ""), | |
| (re.compile(r'\bneedless to say,?\s*', re.IGNORECASE), ""), | |
| ] | |
| # Negative parallelisms -- detect and flatten | |
| # These are very hard to fix cleanly without an LLM, so we just | |
| # strip the "not just X; it's" framing and keep the second half | |
| _NEG_PARALLEL_PATTERNS: list[tuple[re.Pattern, str]] = [ | |
| # "It's not just about X; it's about Y" -> "Y" | |
| (re.compile( | |
| r"It'?s not just about [^;.!?]+[;,]\s*it'?s about\s*", | |
| re.IGNORECASE | |
| ), ""), | |
| # "Not merely X; it's Y" -> "Y" | |
| (re.compile( | |
| r"Not merely [^;.!?]+[;,]\s*it'?s\s*", | |
| re.IGNORECASE | |
| ), ""), | |
| # "Not just X, it's Y" -> "Y" | |
| (re.compile( | |
| r"not just [^,;.!?]+,\s*it'?s\s*", | |
| re.IGNORECASE | |
| ), ""), | |
| ] | |
| # Superficial -ing tails at end of sentences | |
| # "...contributing to the growth of X." -> remove the tail | |
| _ING_TAIL_PATTERNS: list[tuple[re.Pattern, str]] = [ | |
| (re.compile( | |
| r',\s*(?:highlighting|underscoring|emphasizing|showcasing|reflecting' | |
| r'|symbolizing|fostering|contributing to|demonstrating)[^.!?]*[.!?]', | |
| re.IGNORECASE | |
| ), "."), | |
| (re.compile( | |
| r'\s+(?:highlighting|underscoring|emphasizing|showcasing|reflecting' | |
| r'|symbolizing|fostering)[^.!?]*[.!?]$', | |
| re.IGNORECASE | re.MULTILINE | |
| ), "."), | |
| ] | |
| # Generic positive conclusions to replace with plain endings | |
| _GENERIC_CONCLUSION_PATTERNS: list[tuple[re.Pattern, str]] = [ | |
| (re.compile( | |
| r'(?:the future looks? bright|exciting times? (?:lie|await|ahead)|' | |
| r'(?:get|start) (?:started|going) today[!.]?|' | |
| r'(?:your|the) (?:users?|audience|readers?)[^.!?]*will appreciate[^.!?]*[.!?])', | |
| re.IGNORECASE | |
| ), ""), | |
| # "X is not optional; it is survival" / "X is not just nice; it's necessary" | |
| (re.compile( | |
| r'\w[\w\s]+ is (?:not just [\w\s]+;?\s*it(?:\'s| is)|no longer optional)', | |
| re.IGNORECASE | |
| ), ""), | |
| ] | |
| def _eliminate_ai_patterns(self, text: str) -> str: | |
| """Remove Wikipedia-documented AI writing patterns from text. | |
| Applies rule-based fixes for: | |
| - Copula avoidance ("serves as" -> "is") | |
| - Filler phrases ("in order to" -> "to") | |
| - Superficial -ing tails (sentences ending with "...highlighting X") | |
| - Negative parallelisms ("It's not just X; it's Y") | |
| """ | |
| fixes = 0 | |
| # Copula avoidance | |
| for pattern, replacement in self._COPULA_PATTERNS: | |
| new_text = pattern.sub(replacement, text) | |
| if new_text != text: | |
| fixes += 1 | |
| text = new_text | |
| # Filler phrases | |
| for pattern, replacement in self._FILLER_PATTERNS: | |
| new_text = pattern.sub(replacement, text) | |
| if new_text != text: | |
| fixes += 1 | |
| text = new_text | |
| # -ing tails | |
| for pattern, replacement in self._ING_TAIL_PATTERNS: | |
| new_text = pattern.sub(replacement, text) | |
| if new_text != text: | |
| fixes += 1 | |
| text = new_text | |
| # Negative parallelisms (careful -- only apply if the pattern is clear) | |
| for pattern, replacement in self._NEG_PARALLEL_PATTERNS: | |
| new_text = pattern.sub(replacement, text) | |
| if new_text != text: | |
| # Capitalize whatever follows | |
| fixes += 1 | |
| text = new_text | |
| # Generic positive conclusions -- just strip the offending sentence | |
| for pattern, replacement in self._GENERIC_CONCLUSION_PATTERNS: | |
| new_text = pattern.sub(replacement, text) | |
| if new_text != text: | |
| fixes += 1 | |
| text = new_text | |
| # Clean up any double spaces or leading/trailing spaces on lines | |
| text = re.sub(r' +', ' ', text) | |
| text = re.sub(r'^ +', '', text, flags=re.MULTILINE) | |
| text = re.sub(r'\n{3,}', '\n\n', text) | |
| if fixes > 0: | |
| logger.info("AI pattern elimination: fixed %d pattern(s)", fixes) | |
| return text | |
| # ------------------------------------------------------------------ | |
| # Step 1: Strip AI formatting | |
| # ------------------------------------------------------------------ | |
| def _strip_ai_formatting(self, text: str) -> str: | |
| """Remove AI formatting artifacts.""" | |
| # Markdown | |
| text = re.sub(r'\*\*\*(.+?)\*\*\*', r'\1', text) | |
| text = re.sub(r'\*\*(.+?)\*\*', r'\1', text) | |
| text = re.sub(r'\*(.+?)\*', r'\1', text) | |
| text = re.sub(r'__(.+?)__', r'\1', text) | |
| text = re.sub(r'_(.+?)_', r'\1', text) | |
| text = re.sub(r'^#{1,6}\s+', '', text, flags=re.MULTILINE) | |
| # Unicode formatting characters | |
| for char, replacements in _FORMAT_REPLACEMENTS: | |
| while char in text: | |
| replacement = random.choice(replacements) | |
| text = text.replace(char, replacement, 1) | |
| # Clean up spacing | |
| text = re.sub(r' +', ' ', text) | |
| text = re.sub(r' ([,.])', r'\1', text) | |
| return text | |
| # ------------------------------------------------------------------ | |
| # Step 2: Remove AI-style paragraph openers | |
| # ------------------------------------------------------------------ | |
| def _remove_ai_openers(self, text: str) -> str: | |
| """Strip conversational hooks that LLMs add to paragraph starts. | |
| Patterns like "First off,", "Another trick is", "How about X?", | |
| "Now let's talk about" are classic AI rewrite tells. | |
| """ | |
| paragraphs = text.split('\n') | |
| result = [] | |
| removals = 0 | |
| for para in paragraphs: | |
| stripped = para.strip() | |
| if not stripped: | |
| result.append(para) | |
| continue | |
| modified = stripped | |
| for pattern, replacement in _AI_OPENERS: | |
| new_text = pattern.sub(replacement, modified) | |
| if new_text != modified: | |
| # Capitalize the first letter after removal | |
| new_text = new_text.lstrip() | |
| if new_text and new_text[0].islower(): | |
| new_text = new_text[0].upper() + new_text[1:] | |
| modified = new_text | |
| removals += 1 | |
| break # Only remove one opener per paragraph | |
| result.append(modified) | |
| if removals > 0: | |
| logger.info("Removed %d AI-style paragraph openers", removals) | |
| return '\n'.join(result) | |
| # ------------------------------------------------------------------ | |
| # Step 3: Global AI vocabulary replacement | |
| # ------------------------------------------------------------------ | |
| def _replace_global_ai_words(self, text: str) -> str: | |
| """Replace ALL AI vocabulary the LLM generated.""" | |
| replacements_made = 0 | |
| text_lower = text.lower() | |
| for pattern, replacements, original_word in self._ai_patterns: | |
| matches = list(pattern.finditer(text)) | |
| if not matches: | |
| continue | |
| safe_replacements = [ | |
| r for r in replacements if r.lower() not in text_lower | |
| ] | |
| if not safe_replacements: | |
| safe_replacements = replacements | |
| for match in reversed(matches): | |
| # Skip if part of a proper name / tool name | |
| if self._is_part_of_proper_name(text, match): | |
| continue | |
| original = match.group(0) | |
| replacement = random.choice(safe_replacements) | |
| if original[0].isupper(): | |
| replacement = replacement[0].upper() + replacement[1:] | |
| if original.isupper() and len(original) > 1: | |
| replacement = replacement.upper() | |
| text = text[:match.start()] + replacement + text[match.end():] | |
| replacements_made += 1 | |
| if replacements_made > 0: | |
| logger.info("Replaced %d AI vocabulary words", replacements_made) | |
| return text | |
| # ------------------------------------------------------------------ | |
| # Step 4: Random word substitution | |
| # ------------------------------------------------------------------ | |
| def _substitute_words(self, text: str) -> str: | |
| """Replace a fraction of common words with less predictable alternatives.""" | |
| replacements_made = 0 | |
| max_replacements = max(2, int(len(text.split()) * self.intensity)) | |
| shuffled = list(self._sub_patterns) | |
| random.shuffle(shuffled) | |
| for pattern, replacements in shuffled: | |
| if replacements_made >= max_replacements: | |
| break | |
| matches = list(pattern.finditer(text)) | |
| if not matches: | |
| continue | |
| match = random.choice(matches) | |
| original = match.group(0) | |
| # Skip if inside a heading/numbered line | |
| line_start = text.rfind('\n', 0, match.start()) + 1 | |
| line_prefix = text[line_start:match.start()].strip() | |
| if re.match(r'^\d+\.?\s*$', line_prefix): | |
| continue | |
| # Skip if part of a proper name / tool name | |
| if self._is_part_of_proper_name(text, match): | |
| continue | |
| replacement = random.choice(replacements) | |
| if original[0].isupper(): | |
| replacement = replacement[0].upper() + replacement[1:] | |
| text = text[:match.start()] + replacement + text[match.end():] | |
| replacements_made += 1 | |
| if replacements_made > 0: | |
| logger.debug("Random word substitutions: %d", replacements_made) | |
| return text | |
| # ------------------------------------------------------------------ | |
| # Helper: Proper name detection | |
| # ------------------------------------------------------------------ | |
| def _is_part_of_proper_name(text: str, match: re.Match) -> bool: | |
| """Check if a match is part of a proper name or tool name. | |
| Skips replacement if: | |
| - Preceded by a hyphen (e.g. WP-Optimize) | |
| - Followed by a hyphen (e.g. Advanced-something) | |
| - Adjacent word is capitalized (e.g. "Advanced Database Cleaner") | |
| - Inside a quoted string | |
| """ | |
| start = match.start() | |
| end = match.end() | |
| # Check for hyphen before or after | |
| if start > 0 and text[start - 1] == '-': | |
| return True | |
| if end < len(text) and text[end] == '-': | |
| return True | |
| # Check if the next word is capitalized (proper compound name) | |
| after = text[end:end + 20].lstrip() | |
| if after and after[0].isupper(): | |
| # Next word starts with uppercase => likely a proper name | |
| return True | |
| # Check if previous word is capitalized and not start of sentence | |
| 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 is capitalized and not after sentence-ending punct | |
| if ( | |
| prev_word[0].isupper() | |
| and not prev_word[-1] in '.!?' | |
| and not prev_word.endswith(',') | |
| ): | |
| return True | |
| return False | |
| # ------------------------------------------------------------------ | |
| # Step 5: Contraction variation | |
| # ------------------------------------------------------------------ | |
| _EXPANSION_MAP: dict[str, str] = { | |
| "it's": "it is", | |
| "that's": "that is", | |
| "there's": "there is", | |
| "here's": "here is", | |
| "what's": "what is", | |
| "who's": "who is", | |
| "he's": "he is", | |
| "she's": "she is", | |
| "don't": "do not", | |
| "doesn't": "does not", | |
| "didn't": "did not", | |
| "won't": "will not", | |
| "can't": "cannot", | |
| "shouldn't": "should not", | |
| "wouldn't": "would not", | |
| "isn't": "is not", | |
| "aren't": "are not", | |
| "wasn't": "was not", | |
| "weren't": "were not", | |
| "hasn't": "has not", | |
| "haven't": "have not", | |
| } | |
| def _vary_contractions(self, text: str) -> str: | |
| """Randomly expand some contractions for natural inconsistency. | |
| Real humans are inconsistent: "don't" in one sentence, | |
| "do not" in the next. This mimics that pattern. | |
| """ | |
| expansions_done = 0 | |
| max_expansions = random.randint(2, 4) | |
| items = list(self._EXPANSION_MAP.items()) | |
| random.shuffle(items) | |
| for contraction, expansion in items: | |
| if expansions_done >= max_expansions: | |
| break | |
| pattern = re.compile(re.escape(contraction), re.IGNORECASE) | |
| matches = list(pattern.finditer(text)) | |
| if not matches: | |
| continue | |
| if random.random() < 0.35: | |
| match = random.choice(matches) | |
| original = match.group(0) | |
| replacement = expansion | |
| if original[0].isupper(): | |
| replacement = replacement[0].upper() + replacement[1:] | |
| text = text[:match.start()] + replacement + text[match.end():] | |
| expansions_done += 1 | |
| return text | |