Spaces:
Sleeping
Sleeping
File size: 10,715 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 | """
Markdown to Plain Text Converter
Converts Markdown formatting to user-friendly plain text
"""
import re
from typing import Optional
class MarkdownConverter:
"""Converts Markdown to plain text for copy/download"""
def __init__(self):
# Compile regex patterns for efficiency
self.patterns = {
# Headers: # Header β Header (with underline for H1)
'header': [
(re.compile(r'^#{6}\s+(.+)$', re.MULTILINE), r'\1'), # H6
(re.compile(r'^#{5}\s+(.+)$', re.MULTILINE), r'\1'), # H5
(re.compile(r'^#{4}\s+(.+)$', re.MULTILINE), r'\1'), # H4
(re.compile(r'^#{3}\s+(.+)$', re.MULTILINE), r'\1'), # H3
(re.compile(r'^#{2}\s+(.+)$', re.MULTILINE), r'\1'), # H2
(re.compile(r'^#{1}\s+(.+)$', re.MULTILINE), r'\1\n' + '=' * 50), # H1 with underline
],
# Bold/Italic: **bold** β bold, *italic* β italic
'bold_italic': [
(re.compile(r'\*\*\*(.+?)\*\*\*'), r'\1'), # ***bold italic***
(re.compile(r'\*\*(.+?)\*\*'), r'\1'), # **bold**
(re.compile(r'\*(.+?)\*'), r'\1'), # *italic*
(re.compile(r'_(.+?)_'), r'\1'), # _italic_
],
# Code: `code` β "code", ```code``` β code block
'code': [
(re.compile(r'```(?:\w+)?\n?(.*?)\n?```', re.DOTALL), r'\1'), # Code blocks
(re.compile(r'`([^`]+)`'), r'"\1"'), # Inline code
],
# Lists: - item β β’ item, 1. item β 1. item
'lists': [
(re.compile(r'^[\s]*[-*+]\s+(.+)$', re.MULTILINE), r'β’ \1'), # Bullet lists
# Numbered lists keep numbers
],
# Links: [text](url) β text (url)
'links': [
(re.compile(r'\[([^\]]+)\]\(([^)]+)\)'), r'\1 (\2)'),
],
# Images:  β [Image: alt]
'images': [
(re.compile(r'!\[([^\]]*)\]\(([^)]+)\)'), r'[Image: \1]'),
],
# Blockquotes: > quote β "quote"
'blockquotes': [
(re.compile(r'^>\s+(.+)$', re.MULTILINE), r'"\1"'),
],
# Horizontal rules: --- β ----------
'horizontal_rules': [
(re.compile(r'^[-*_]{3,}\s*$', re.MULTILINE), '-' * 50),
],
# Tables: | Header | β Header (tab-separated)
'tables': self._convert_table,
}
def _convert_table(self, text: str) -> str:
"""Convert Markdown tables to plain text"""
lines = text.split('\n')
if not lines or '|' not in lines[0]:
return text
# Find table rows
table_rows = []
for line in lines:
if '|' in line and not re.match(r'^\|?[-:|]+\|?$', line):
# Extract cells, remove leading/trailing |
cells = [cell.strip() for cell in line.split('|') if cell.strip()]
table_rows.append(cells)
if not table_rows:
return text
# Convert to plain text (tab-separated)
plain_rows = []
for row in table_rows:
plain_rows.append('\t'.join(row))
return '\n'.join(plain_rows)
def to_plain_text(self, markdown_text: str) -> str:
"""
Convert Markdown to user-friendly plain text
"""
if not markdown_text:
return ''
text = markdown_text
# Apply conversions in order
conversion_order = [
'code', # Code first (preserve content)
'links', # Links before bold/italic
'images', # Images
'bold_italic', # Bold/italic
'header', # Headers
'lists', # Lists
'blockquotes', # Blockquotes
'horizontal_rules', # Horizontal rules
]
for pattern_type in conversion_order:
if pattern_type == 'tables':
# Tables need special handling
text = self._convert_table(text)
else:
patterns = self.patterns.get(pattern_type, [])
for pattern, replacement in patterns:
text = pattern.sub(replacement, text)
# Clean up extra whitespace
text = re.sub(r'\n{3,}', '\n\n', text) # Max 2 blank lines
text = text.strip()
return text
def to_rich_text(self, markdown_text: str) -> str:
"""
Convert Markdown to rich text (preserves some formatting)
Returns text with minimal markup
"""
if not markdown_text:
return ''
text = markdown_text
# Keep only essential formatting
# Headers: Add underline for H1
text = re.sub(r'^#\s+(.+)$', r'\1\n' + '=' * 50, text, flags=re.MULTILINE)
# Remove other header markers
for i in range(2, 7):
text = re.sub(r'^' + '#' * i + r'\s+(.+)$', r'\1', text, flags=re.MULTILINE)
# Convert bold/italic to uppercase for emphasis
text = re.sub(r'\*\*(.+?)\*\*', r'\1', text)
text = re.sub(r'\*(.+?)\*', r'\1', text)
# Convert code blocks with indentation
def indent_code(match):
code = match.group(1)
lines = code.split('\n')
indented = [' ' + line for line in lines]
return '\n'.join(indented)
text = re.sub(r'```(?:\w+)?\n?(.*?)\n?```', indent_code, text, flags=re.DOTALL)
# Inline code with quotes
text = re.sub(r'`([^`]+)`', r'"\1"', text)
# Bullet lists with β’ (keep)
text = re.sub(r'^[\s]*[-*+]\s+(.+)$', r'β’ \1', text, flags=re.MULTILINE)
# Remove link markup, keep text
text = re.sub(r'\[([^\]]+)\]\([^)]+\)', r'\1', text)
# Blockquotes with >
text = re.sub(r'^>\s+(.+)$', r'"\1"', text, flags=re.MULTILINE)
# Clean up
text = re.sub(r'\n{3,}', '\n\n', text)
text = text.strip()
return text
def get_formatting_summary(self, markdown_text: str) -> dict:
"""
Analyze Markdown content and return formatting summary
"""
if not markdown_text:
return {}
patterns = {
'headers': re.compile(r'^#{1,6}\s', re.MULTILINE),
'bold': re.compile(r'\*\*.+?\*\*'),
'italic': re.compile(r'\*.+?\*'),
'code_blocks': re.compile(r'```'),
'inline_code': re.compile(r'`[^`]+`'),
'lists': re.compile(r'^[\s]*[-*+]\s', re.MULTILINE),
'numbered_lists': re.compile(r'^[\s]*\d+[.)]\s', re.MULTILINE),
'links': re.compile(r'\[.+?\]\(.+?\)'),
'images': re.compile(r'!\[.+?\]\(.+?\)'),
'blockquotes': re.compile(r'^>\s', re.MULTILINE),
'tables': re.compile(r'^\|.+\|$', re.MULTILINE),
}
summary = {}
for name, pattern in patterns.items():
matches = pattern.findall(markdown_text)
summary[name] = len(matches)
# Calculate formatting percentage
total_chars = len(markdown_text)
formatting_chars = 0
# Estimate formatting characters (markup)
formatting_patterns = [
(r'#{1,6}\s', 2), # Headers: # + space
(r'\*\*', 2), # Bold: **
(r'\*[^*]', 1), # Italic: *
(r'```', 3), # Code blocks: ```
(r'`[^`]', 1), # Inline code: `
(r'\[.*?\]\(.*?\)', 4), # Links: []()
(r'^>\s', 2), # Blockquotes: > + space
(r'^\|', 1), # Tables: |
]
for pattern, char_weight in formatting_patterns:
matches = re.findall(pattern, markdown_text, re.MULTILINE)
formatting_chars += len(matches) * char_weight
if total_chars > 0:
summary['formatting_percentage'] = round((formatting_chars / total_chars) * 100, 2)
else:
summary['formatting_percentage'] = 0
return summary
# Create global instance
markdown_converter = MarkdownConverter()
# Helper functions
def convert_for_copy(markdown_text: str) -> str:
"""Convert Markdown to plain text suitable for copying"""
return markdown_converter.to_plain_text(markdown_text)
def convert_for_display(markdown_text: str) -> str:
"""Convert Markdown to display-friendly text (keeps some formatting)"""
return markdown_converter.to_rich_text(markdown_text)
def analyze_formatting(markdown_text: str) -> dict:
"""Analyze Markdown formatting in text"""
return markdown_converter.get_formatting_summary(markdown_text)
# Test function
def test_converter():
"""Test the Markdown converter"""
test_markdown = """# Project Report
## Executive Summary
This **important** report contains *critical* data.
### Key Findings
1. Revenue increased by 25%
2. User engagement improved
3. Customer satisfaction is high
## Technical Details
Use `print("hello")` in your code:
```python
def calculate():
return 42 * 3.14
```
Visit [our website](https://example.com) for more.
> Note: All data is confidential.
"""
print("π§ͺ Testing Markdown to Plain Text Converter")
print("=" * 60)
print("\nπ Original Markdown:")
print(test_markdown)
print("\nπ Plain Text (for copy/download):")
plain = convert_for_copy(test_markdown)
print(plain)
print("\nπ¨ Rich Text (for display):")
rich = convert_for_display(test_markdown)
print(rich)
print("\nπ Formatting Analysis:")
analysis = analyze_formatting(test_markdown)
for key, value in analysis.items():
print(f" {key}: {value}")
print("\n" + "=" * 60)
print("β
Converter test completed!")
if __name__ == "__main__":
test_converter() |