File size: 11,648 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
"""

Smart Formatting Detector

Detects and preserves structured elements in text

"""

import re
from typing import List, Tuple, Dict, Any
import json


class FormattingDetector:
    """Detects structured elements in text for preservation"""
    
    def __init__(self):
        # Compile regex patterns for efficiency
        self.patterns = {
            # Code blocks (triple backticks with optional language)
            'code_block': re.compile(r'```(?:\w+)?\n.*?\n```', re.DOTALL | re.MULTILINE),
            
            # Inline code (single backticks)
            'inline_code': re.compile(r'`[^`\n]+`'),
            
            # Headers (Markdown headers)
            'header': re.compile(r'^(#{1,6})\s+(.+)$', re.MULTILINE),
            
            # Lists (bullet points and numbered)
            'bullet_list': re.compile(r'^[\s]*[-*+]\s+.+$', re.MULTILINE),
            'numbered_list': re.compile(r'^[\s]*\d+[.)]\s+.+$', re.MULTILINE),
            
            # Tables (Markdown tables)
            'table': re.compile(r'^\|.+\|\s*$[\n\r]^\|[-:|]+\|\s*$[\n\r]^(\|.+\|\s*$)+', re.MULTILINE),
            
            # Blockquotes
            'blockquote': re.compile(r'^>\s+.+$', re.MULTILINE),
            
            # Horizontal rules
            'horizontal_rule': re.compile(r'^[-*_]{3,}\s*$', re.MULTILINE),
            
            # JSON blocks (detect JSON-like structures)
            'json_block': re.compile(r'^\s*\{.*?\}\s*$', re.DOTALL | re.MULTILINE),
            
            # XML/HTML blocks
            'xml_block': re.compile(r'^\s*<[^>]+>.*?</[^>]+>\s*$', re.DOTALL | re.MULTILINE),
            
            # URLs
            'url': re.compile(r'https?://[^\s<>"\']+[^\s<>"\'.)]'),
            
            # Email addresses
            'email': re.compile(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'),
            
            # File paths (Unix and Windows)
            'file_path': re.compile(r'(?:/[^/\s]+)+/?(?:\s|$)|(?:[A-Za-z]:\\(?:[^\\\s]+\\)*[^\\\s]+)'),
            
            # Code-like patterns (function calls, variable assignments)
            'code_like': re.compile(r'\b(?:def|class|import|from|if|else|for|while|return|function|var|let|const)\b[^.!?]*[.;]?'),
        }
    
    def detect_structured_elements(self, text: str) -> List[Dict[str, Any]]:
        """

        Detect all structured elements in text

        Returns list of elements with type, content, and position

        """
        elements = []
        
        # Check each pattern
        for element_type, pattern in self.patterns.items():
            for match in pattern.finditer(text):
                element = {
                    'type': element_type,
                    'content': match.group(),
                    'start': match.start(),
                    'end': match.end(),
                    'preserve': True  # All detected elements should be preserved
                }
                elements.append(element)
        
        # Sort by start position
        elements.sort(key=lambda x: x['start'])
        
        # Remove overlapping elements (keep the first/largest)
        cleaned_elements = []
        last_end = 0
        
        for element in elements:
            if element['start'] >= last_end:
                cleaned_elements.append(element)
                last_end = element['end']
            # If overlap, keep the larger element
            elif element['end'] - element['start'] > (last_end - element['start']):
                if cleaned_elements:
                    cleaned_elements.pop()
                cleaned_elements.append(element)
                last_end = element['end']
        
        return cleaned_elements
    
    def tag_text(self, text: str) -> str:
        """

        Tag structured elements in text with special markers

        Returns tagged text where structured elements are wrapped

        """
        elements = self.detect_structured_elements(text)
        
        # Build tagged text by replacing elements with tags
        tagged_parts = []
        last_pos = 0
        
        for element in elements:
            # Add text before element
            if element['start'] > last_pos:
                tagged_parts.append(text[last_pos:element['start']])
            
            # Add tagged element
            tag = f"[[{element['type']}:{len(tagged_parts)}]]"
            tagged_parts.append(element['content'])
            tagged_parts.append(f"[[/{element['type']}]]")
            
            last_pos = element['end']
        
        # Add remaining text
        if last_pos < len(text):
            tagged_parts.append(text[last_pos:])
        
        return ''.join(tagged_parts)
    
    def extract_segments(self, text: str) -> List[Tuple[str, str]]:
        """

        Extract segments from text

        Returns list of (segment_type, content)

        """
        elements = self.detect_structured_elements(text)
        segments = []
        last_pos = 0
        
        for element in elements:
            # Add natural language segment before element
            if element['start'] > last_pos:
                natural_text = text[last_pos:element['start']].strip()
                if natural_text:
                    segments.append(('natural_language', natural_text))
            
            # Add structured element
            segments.append((element['type'], element['content']))
            
            last_pos = element['end']
        
        # Add remaining natural language
        if last_pos < len(text):
            natural_text = text[last_pos:].strip()
            if natural_text:
                segments.append(('natural_language', natural_text))
        
        return segments
    
    def is_structured_element(self, text: str) -> bool:
        """

        Check if text contains structured elements

        Quick check without full detection

        """
        # Quick checks for common structured patterns
        quick_checks = [
            r'```',  # Code blocks
            r'`[^`]`',  # Inline code
            r'^#{1,6}\s',  # Headers
            r'^[\s]*[-*+]\s',  # Bullet lists
            r'^\|',  # Tables
            r'^>\s',  # Blockquotes
            r'^[-*_]{3,}$',  # Horizontal rules
            r'https?://',  # URLs
            r'@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}',  # Emails
            r'\{.*\}',  # JSON-like
            r'<[^>]+>.*</[^>]+>',  # XML/HTML
        ]
        
        for pattern in quick_checks:
            if re.search(pattern, text, re.MULTILINE | re.DOTALL):
                return True
        
        return False
    
    def get_preservation_rules(self) -> Dict[str, str]:
        """

        Get rules for what to preserve for each element type

        """
        return {
            'code_block': 'preserve_exactly',
            'inline_code': 'preserve_exactly',
            'header': 'humanize_text_only',  # Humanize header text, keep #
            'bullet_list': 'humanize_items',  # Humanize list items, keep bullets
            'numbered_list': 'humanize_items',  # Humanize list items, keep numbers
            'table': 'preserve_structure',  # Keep table structure
            'blockquote': 'humanize_text_only',  # Humanize quote text, keep >
            'horizontal_rule': 'preserve_exactly',
            'json_block': 'preserve_exactly',
            'xml_block': 'preserve_exactly',
            'url': 'preserve_exactly',
            'email': 'preserve_exactly',
            'file_path': 'preserve_exactly',
            'code_like': 'preserve_exactly',
        }


# Helper functions
def preserve_formatting(text: str, humanizer_func) -> str:
    """

    Main function to preserve formatting while humanizing

    """
    detector = FormattingDetector()
    segments = detector.extract_segments(text)
    preservation_rules = detector.get_preservation_rules()
    
    processed_segments = []
    
    for segment_type, content in segments:
        if segment_type == 'natural_language':
            # Humanize natural language
            processed_segments.append(humanizer_func(content))
        else:
            # Apply preservation rule
            rule = preservation_rules.get(segment_type, 'preserve_exactly')
            
            if rule == 'preserve_exactly':
                processed_segments.append(content)
            elif rule == 'humanize_text_only':
                # For headers: humanize text after #
                if segment_type == 'header':
                    match = re.match(r'^(#{1,6}\s+)(.+)$', content)
                    if match:
                        prefix = match.group(1)
                        header_text = match.group(2)
                        humanized_text = humanizer_func(header_text)
                        processed_segments.append(f"{prefix}{humanized_text}")
                    else:
                        processed_segments.append(content)
                # For blockquotes: humanize text after >
                elif segment_type == 'blockquote':
                    lines = content.split('\n')
                    humanized_lines = []
                    for line in lines:
                        match = re.match(r'^(>\s*)(.+)$', line)
                        if match:
                            prefix = match.group(1)
                            quote_text = match.group(2)
                            humanized_text = humanizer_func(quote_text)
                            humanized_lines.append(f"{prefix}{humanized_text}")
                        else:
                            humanized_lines.append(line)
                    processed_segments.append('\n'.join(humanized_lines))
                else:
                    processed_segments.append(content)
            elif rule == 'humanize_items':
                # For lists: humanize each item
                lines = content.split('\n')
                humanized_lines = []
                for line in lines:
                    # Bullet lists
                    match = re.match(r'^([\s]*[-*+]\s+)(.+)$', line)
                    if match:
                        prefix = match.group(1)
                        item_text = match.group(2)
                        humanized_text = humanizer_func(item_text)
                        humanized_lines.append(f"{prefix}{humanized_text}")
                        continue
                    
                    # Numbered lists
                    match = re.match(r'^([\s]*\d+[.)]\s+)(.+)$', line)
                    if match:
                        prefix = match.group(1)
                        item_text = match.group(2)
                        humanized_text = humanizer_func(item_text)
                        humanized_lines.append(f"{prefix}{humanized_text}")
                        continue
                    
                    # Keep line as is (indentation, etc.)
                    humanized_lines.append(line)
                processed_segments.append('\n'.join(humanized_lines))
            elif rule == 'preserve_structure':
                # For tables: preserve structure
                processed_segments.append(content)
            else:
                processed_segments.append(content)
    
    # Reconstruct text
    return '\n'.join(processed_segments)


# Create global instance
formatting_detector = FormattingDetector()