""" Three-Pass Humanization Engine Self-contained rewriting system with three internal passes """ import re import random import statistics from typing import List, Tuple from config import settings class ThreePassHumanizer: """Three-pass humanization engine""" def __init__(self): self.passes = settings.passes self.temperature = settings.temperature self.top_p = settings.top_p # Vocabulary transformations for different passes self.pass1_transforms = self._get_pass1_transforms() self.pass2_transforms = self._get_pass2_transforms() self.pass3_transforms = self._get_pass3_transforms() def _get_pass1_transforms(self) -> List[Tuple[re.Pattern, str]]: """Pass 1: Fix clarity and flow""" transforms = [ # Remove redundant phrases (r'\bremains a challenge\b', 'stays difficult'), (r'\bcontinues to be\b', 'stays'), (r'\brequire knowledge of\b', 'need to know'), (r'\brequire understanding of\b', 'need to know'), (r'\baddresses these challenges\b', 'solves these problems'), (r'\btackles these challenges\b', 'handles these issues'), # Simplify complex words (r'\butilizing\b', 'using'), (r'\binterprets\b', 'reads'), (r'\bunderstands\b', 'gets'), (r'\bgenerate\b', 'make'), (r'\bcreate\b', 'build'), (r'\bautomatically selects\b', 'picks'), (r'\bappropriate\b', 'right'), (r'\bsuitable\b', 'fitting'), (r'\bintegrates\b', 'adds'), (r'\brelevant\b', 'related'), (r'\bcustomizes\b', 'changes'), (r'\badjusts\b', 'tweaks'), # Improve flow (r'\bIn today\'s modern online environment\b', 'In the current digital world'), (r'\bIn the modern digital landscape\b', 'In today\'s online space'), (r'\bnon-technical users\b', 'people without tech skills'), (r'\balong with\b', 'and'), ] return [(re.compile(p, re.IGNORECASE), r) for p, r in transforms] def _get_pass2_transforms(self) -> List[Tuple[re.Pattern, str]]: """Pass 2: Vary rhythm, remove robotic patterns""" transforms = [ # Vary sentence structure (r'\bsimply describe\b', 'just say'), (r'\bjust explain\b', 'just tell'), (r'\bfully functional\b', 'working'), (r'\bcomplete\b', 'full'), (r'\bvisual elements\b', 'design bits'), (r'\bdesign features\b', 'design parts'), (r'\binteract with\b', 'work with'), (r'\bimproving\b', 'boosting'), (r'\benhancing\b', 'improving'), # Remove robotic patterns (r'\bpersonalization\b', 'personal touch'), (r'\bcustomization\b', 'personal setup'), (r'\bover time\b', 'bit by bit'), (r'\bgradually\b', 'step by step'), (r'\badaptability\b', 'flexibility'), (r'\bensures\b', 'makes sure'), (r'\bguarantees\b', 'ensures'), (r'\bincreasingly\b', 'more and more'), # Add variation (r'\bintuitive\b', 'easy'), (r'\buser-friendly\b', 'simple'), (r'\beffective\b', 'useful'), (r'\befficient\b', 'effective'), (r'\boffers\b', 'gives'), (r'\bprovides\b', 'offers'), ] return [(re.compile(p, re.IGNORECASE), r) for p, r in transforms] def _get_pass3_transforms(self) -> List[Tuple[re.Pattern, str]]: """Pass 3: Deeply human tone, organic phrasing""" transforms = [ # Organic phrasing (r'\bcost-effective\b', 'affordable'), (r'\baffordable\b', 'budget-friendly'), (r'\bscalable\b', 'flexible'), (r'\balternative\b', 'option'), (r'\btraditional\b', 'standard'), (r'\bconventional\b', 'traditional'), (r'\benhancements\b', 'upgrades'), (r'\bimprovements\b', 'enhancements'), # Conversational shifts (r'\bdemocratizing\b', 'opening up'), (r'\bmaking accessible\b', 'democratizing'), (r'\bplain English processing\b', 'natural language processing'), (r'\beveryday language\b', 'plain language'), (r'\bBuilt for\b', 'Made for'), (r'\bUpcoming features\b', 'Future additions'), # Contractions for natural speech (r'\bcannot\b', "can't"), (r'\bdo not\b', "don't"), (r'\bdoes not\b', "doesn't"), (r'\bwill not\b', "won't"), (r'\bis not\b', "isn't"), (r'\bare not\b', "aren't"), (r'\bwould not\b', "wouldn't"), (r'\bcould not\b', "couldn't"), (r'\bshould not\b', "shouldn't"), (r'\bit is\b', "it's"), (r'\bthat is\b', "that's"), (r'\bwhat is\b', "what's"), ] return [(re.compile(p, re.IGNORECASE), r) for p, r in transforms] def _apply_transforms(self, text: str, transforms: List[Tuple[re.Pattern, str]]) -> str: """Apply transformations to text""" for pattern, repl in transforms: text = pattern.sub(repl, text) return text def _pass1_clarity_flow(self, text: str) -> str: """Pass 1: Fix clarity and flow""" # Apply clarity transforms text = self._apply_transforms(text, self.pass1_transforms) # Improve sentence structure sentences = self._split_sentences(text) sentences = self._improve_clarity(sentences) return self._join_sentences(sentences) def _pass2_rhythm_variation(self, text: str) -> str: """Pass 2: Vary rhythm, remove robotic patterns""" # Apply rhythm transforms text = self._apply_transforms(text, self.pass2_transforms) # Vary sentence length and structure sentences = self._split_sentences(text) sentences = self._vary_rhythm(sentences) return self._join_sentences(sentences) def _pass3_human_tone(self, text: str) -> str: """Pass 3: Deeply human tone, organic phrasing""" # Apply human tone transforms text = self._apply_transforms(text, self.pass3_transforms) # Add organic phrasing and natural variation sentences = self._split_sentences(text) sentences = self._add_human_touch(sentences) return self._join_sentences(sentences) def _split_sentences(self, text: str) -> List[str]: """Split text into sentences""" if not text.strip(): return [] sentences = re.split(r'(?<=[.!?])\s+(?=[A-Z])', text.strip()) return [s.strip() for s in sentences if s.strip()] def _join_sentences(self, sentences: List[str]) -> str: """Join sentences into text""" return ' '.join(sentences) def _improve_clarity(self, sentences: List[str]) -> List[str]: """Improve clarity of sentences""" result = [] for sentence in sentences: # Remove redundant words sentence = re.sub(r'\bvery\s+', '', sentence, flags=re.IGNORECASE) sentence = re.sub(r'\breally\s+', '', sentence, flags=re.IGNORECASE) sentence = re.sub(r'\bquite\s+', '', sentence, flags=re.IGNORECASE) # Simplify complex structures sentence = re.sub(r'\bin order to\b', 'to', sentence, flags=re.IGNORECASE) sentence = re.sub(r'\bwith the purpose of\b', 'to', sentence, flags=re.IGNORECASE) result.append(sentence) return result def _vary_rhythm(self, sentences: List[str]) -> List[str]: """Vary sentence rhythm""" if len(sentences) < 2: return sentences result = [] i = 0 while i < len(sentences): current = sentences[i] word_count = len(current.split()) # Merge short sentences (30% chance) if word_count < 10 and i + 1 < len(sentences) and random.random() < 0.3: next_sent = sentences[i + 1] connectors = ['; ', ', and ', ', while ', ', but '] connector = random.choice(connectors) # Lowercase first letter of second sentence next_lower = next_sent[0].lower() + next_sent[1:] if len(next_sent) > 1 else next_sent merged = current.rstrip('.!?') + connector + next_lower result.append(merged) i += 2 else: result.append(current) i += 1 return result def _add_human_touch(self, sentences: List[str]) -> List[str]: """Add human touch to sentences""" result = [] for i, sentence in enumerate(sentences): words = sentence.split() # Add occasional em-dash for dramatic pause (15% chance) if len(words) > 12 and random.random() < 0.15: split_point = len(words) // 2 first_part = ' '.join(words[:split_point]) second_part = ' '.join(words[split_point:]) sentence = f"{first_part} — {second_part}" # Add conversational transitions (20% chance for non-first sentences) if i > 0 and random.random() < 0.2: transitions = ['In fact, ', 'Notably, ', 'Essentially, ', 'What\'s more, '] transition = random.choice(transitions) sentence = transition + sentence[0].lower() + sentence[1:] result.append(sentence) return result def humanize(self, text: str) -> str: """ Perform three-pass humanization Returns ONLY the final Pass 3 output """ if not text.strip(): return text # Preserve Markdown formatting by processing line by line lines = text.split('\n') result_lines = [] for line in lines: if not line.strip(): result_lines.append('') continue # Skip Markdown headers, lists, etc. if self._is_markdown_element(line): result_lines.append(line) continue # Perform three-pass rewriting pass1 = self._pass1_clarity_flow(line) pass2 = self._pass2_rhythm_variation(pass1) pass3 = self._pass3_human_tone(pass2) result_lines.append(pass3) return '\n'.join(result_lines) def _is_markdown_element(self, line: str) -> bool: """Check if line is a Markdown element that should be preserved""" line = line.strip() # Markdown headers if re.match(r'^#{1,6}\s', line): return True # Lists if re.match(r'^[•\-*+]\s', line) or re.match(r'^\d+[.)]\s', line): return True # Code blocks if line.startswith('```') or line.startswith('`'): return True # Horizontal rules if re.match(r'^[-*_]{3,}$', line): return True # Blockquotes if line.startswith('>'): return True return False # Quality check functions def passes_quality_check(text: str) -> bool: """Check if text passes quality thresholds""" sentences = re.findall(r'[^.!?]+[.!?]+', text) or [] if len(sentences) < 2: return True # Short texts pass by default # Calculate variety score unique_starts = set() for sent in sentences: start = sent.strip()[:30] unique_starts.add(start) variety_score = len(unique_starts) / len(sentences) # Check for AI phrases ai_phrase_hits = 0 text_lower = text.lower() for phrase in settings.AI_PHRASES: if phrase in text_lower: ai_phrase_hits += 1 return variety_score > settings.min_variety_score and ai_phrase_hits <= settings.max_ai_phrase_hits # Create global instance humanizer = ThreePassHumanizer() # Export the quality check function __all__ = ['humanizer', 'passes_quality_check']