File size: 12,972 Bytes
7c956fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
"""

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']