tester / formatting_detector.py
devilseye2004's picture
Upload 10 files
7c956fc verified
Raw History Blame Contribute Delete
11.6 kB
"""
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()