-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathmarkdown_to_html.py
More file actions
597 lines (493 loc) · 17.3 KB
/
markdown_to_html.py
File metadata and controls
597 lines (493 loc) · 17.3 KB
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
#!/usr/bin/env python3
"""
Markdown to HTML converter for LoliProfiler memory analysis reports.
Converts markdown reports to styled HTML with syntax highlighting.
"""
import re
import sys
import argparse
from typing import Optional
def escape_html(text: str) -> str:
"""Escape HTML special characters."""
return (text
.replace('&', '&')
.replace('<', '<')
.replace('>', '>')
.replace('"', '"')
.replace("'", '''))
def convert_code_blocks(text: str) -> str:
"""Convert fenced code blocks to HTML."""
def replace_code_block(match):
lang = match.group(1) or ''
code = escape_html(match.group(2))
lang_class = f' class="language-{lang}"' if lang else ''
return f'<pre><code{lang_class}>{code}</code></pre>'
# Match ```lang ... ``` blocks
pattern = r'```(\w*)\n(.*?)```'
return re.sub(pattern, replace_code_block, text, flags=re.DOTALL)
def convert_inline_code(text: str) -> str:
"""Convert inline `code` to HTML."""
return re.sub(r'`([^`]+)`', r'<code>\1</code>', text)
def convert_headers(text: str) -> str:
"""Convert markdown headers to HTML."""
lines = text.split('\n')
result = []
for line in lines:
# Match headers
match = re.match(r'^(#{1,6})\s+(.+)$', line)
if match:
level = len(match.group(1))
content = match.group(2)
result.append(f'<h{level}>{content}</h{level}>')
else:
result.append(line)
return '\n'.join(result)
def convert_bold_italic(text: str) -> str:
"""Convert bold and italic text."""
# Bold: **text** or __text__ (single-line only)
text = re.sub(r'\*\*([^*\n]+)\*\*', r'<strong>\1</strong>', text)
text = re.sub(r'__([^_\n]+)__', r'<strong>\1</strong>', text)
# Italic: *text* or _text_ (single-line only)
text = re.sub(r'\*([^*\n]+)\*', r'<em>\1</em>', text)
text = re.sub(r'(?<![_\w])_([^_\n]+)_(?![_\w])', r'<em>\1</em>', text)
return text
def convert_lists(text: str) -> str:
"""Convert markdown lists to HTML."""
lines = text.split('\n')
result = []
in_ul = False
in_ol = False
for line in lines:
# Unordered list
ul_match = re.match(r'^(\s*)[-*]\s+(.+)$', line)
# Ordered list
ol_match = re.match(r'^(\s*)\d+\.\s+(.+)$', line)
if ul_match:
if not in_ul:
if in_ol:
result.append('</ol>')
in_ol = False
result.append('<ul>')
in_ul = True
result.append(f'<li>{ul_match.group(2)}</li>')
elif ol_match:
if not in_ol:
if in_ul:
result.append('</ul>')
in_ul = False
result.append('<ol>')
in_ol = True
result.append(f'<li>{ol_match.group(2)}</li>')
else:
if in_ul:
result.append('</ul>')
in_ul = False
if in_ol:
result.append('</ol>')
in_ol = False
result.append(line)
# Close any open lists
if in_ul:
result.append('</ul>')
if in_ol:
result.append('</ol>')
return '\n'.join(result)
def convert_horizontal_rules(text: str) -> str:
"""Convert horizontal rules (---) to HTML."""
return re.sub(r'^---+\s*$', '<hr>', text, flags=re.MULTILINE)
def convert_tables(text: str) -> str:
"""Convert markdown tables to HTML tables."""
lines = text.split('\n')
result = []
table_lines = []
in_table = False
def is_table_row(line: str) -> bool:
"""Check if line looks like a table row (starts and ends with |)."""
stripped = line.strip()
return stripped.startswith('|') and stripped.endswith('|')
def is_separator_row(line: str) -> bool:
"""Check if line is a table separator row (contains only |, -, :, spaces)."""
stripped = line.strip()
if not stripped.startswith('|') or not stripped.endswith('|'):
return False
# Remove pipes and check if remaining chars are only -, :, spaces
content = stripped[1:-1]
return bool(re.match(r'^[\s\-:|]+$', content))
def parse_table_row(line: str) -> list:
"""Parse a table row into cells."""
stripped = line.strip()
# Remove leading and trailing pipes
if stripped.startswith('|'):
stripped = stripped[1:]
if stripped.endswith('|'):
stripped = stripped[:-1]
# Split by pipe and strip each cell
cells = [cell.strip() for cell in stripped.split('|')]
return cells
def render_table(table_lines: list) -> str:
"""Render collected table lines as HTML table."""
if len(table_lines) < 2:
# Not a valid table, return as is
return '\n'.join(table_lines)
# Find separator row index
separator_idx = -1
for i, line in enumerate(table_lines):
if is_separator_row(line):
separator_idx = i
break
if separator_idx == -1:
# No separator found, not a valid table
return '\n'.join(table_lines)
# Header rows are before separator
header_lines = table_lines[:separator_idx]
# Body rows are after separator
body_lines = table_lines[separator_idx + 1:]
html = ['<table>']
# Render header
if header_lines:
html.append('<thead>')
for line in header_lines:
cells = parse_table_row(line)
html.append('<tr>')
for cell in cells:
html.append(f'<th>{cell}</th>')
html.append('</tr>')
html.append('</thead>')
# Render body
if body_lines:
html.append('<tbody>')
for line in body_lines:
cells = parse_table_row(line)
html.append('<tr>')
for cell in cells:
html.append(f'<td>{cell}</td>')
html.append('</tr>')
html.append('</tbody>')
html.append('</table>')
return '\n'.join(html)
for line in lines:
if is_table_row(line):
if not in_table:
in_table = True
table_lines.append(line)
else:
if in_table:
# End of table, render it
result.append(render_table(table_lines))
table_lines = []
in_table = False
result.append(line)
# Handle table at end of text
if in_table and table_lines:
result.append(render_table(table_lines))
return '\n'.join(result)
def convert_paragraphs(text: str) -> str:
"""Wrap text blocks in paragraph tags."""
# Split by double newlines
blocks = re.split(r'\n\n+', text)
result = []
for block in blocks:
block = block.strip()
if not block:
continue
# Don't wrap if already wrapped in HTML tags
if (block.startswith('<h') or
block.startswith('<ul') or
block.startswith('<ol') or
block.startswith('<pre') or
block.startswith('<hr') or
block.startswith('<li') or
block.startswith('<table') or
block.startswith('<p')):
result.append(block)
else:
# Check if block contains list items or table (don't wrap those in p tags)
if '<li>' in block or '<table>' in block or '<tr>' in block:
result.append(block)
else:
# Convert single newlines to <br> within paragraphs
block = block.replace('\n', '<br>\n')
result.append(f'<p>{block}</p>')
return '\n\n'.join(result)
def get_html_template(title: str, content: str) -> str:
"""Generate full HTML document with styling."""
return f'''<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{escape_html(title)}</title>
<style>
:root {{
--bg-color: #ffffff;
--text-color: #333333;
--code-bg: #f5f5f5;
--border-color: #e0e0e0;
--header-color: #2c3e50;
--link-color: #3498db;
--success-color: #27ae60;
--warning-color: #f39c12;
--danger-color: #e74c3c;
}}
@media (prefers-color-scheme: dark) {{
:root {{
--bg-color: #1a1a2e;
--text-color: #e0e0e0;
--code-bg: #16213e;
--border-color: #0f3460;
--header-color: #e94560;
--link-color: #00d9ff;
}}
}}
* {{
box-sizing: border-box;
}}
body {{
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
line-height: 1.6;
color: var(--text-color);
background-color: var(--bg-color);
max-width: 1200px;
margin: 0 auto;
padding: 20px;
}}
h1 {{
color: var(--header-color);
border-bottom: 3px solid var(--header-color);
padding-bottom: 10px;
margin-top: 0;
}}
h2 {{
color: var(--header-color);
border-bottom: 2px solid var(--border-color);
padding-bottom: 8px;
margin-top: 30px;
}}
h3 {{
color: var(--header-color);
margin-top: 25px;
}}
pre {{
background-color: var(--code-bg);
border: 1px solid var(--border-color);
border-radius: 6px;
padding: 16px;
overflow-x: auto;
font-size: 14px;
}}
code {{
font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
background-color: var(--code-bg);
padding: 2px 6px;
border-radius: 4px;
font-size: 0.9em;
}}
pre code {{
padding: 0;
background-color: transparent;
}}
hr {{
border: none;
border-top: 2px solid var(--border-color);
margin: 30px 0;
}}
ul, ol {{
padding-left: 30px;
}}
li {{
margin-bottom: 8px;
}}
strong {{
color: var(--header-color);
}}
p {{
margin: 15px 0;
}}
/* Memory analysis specific styles */
.memory-positive {{
color: var(--danger-color);
font-weight: bold;
}}
.memory-negative {{
color: var(--success-color);
font-weight: bold;
}}
/* Table styles */
table {{
border-collapse: collapse;
width: 100%;
margin: 20px 0;
}}
th, td {{
border: 1px solid var(--border-color);
padding: 12px;
text-align: left;
}}
th {{
background-color: var(--code-bg);
font-weight: bold;
}}
tr:nth-child(even) {{
background-color: var(--code-bg);
}}
/* Print styles */
@media print {{
body {{
max-width: none;
padding: 0;
}}
pre {{
white-space: pre-wrap;
word-wrap: break-word;
}}
}}
/* Responsive design */
@media (max-width: 768px) {{
body {{
padding: 10px;
}}
pre {{
padding: 10px;
font-size: 12px;
}}
}}
</style>
</head>
<body>
{content}
</body>
</html>'''
def markdown_to_html(markdown_text: str, title: Optional[str] = None) -> str:
"""
Convert markdown text to styled HTML.
Args:
markdown_text: The markdown content to convert
title: Optional title for the HTML document
Returns:
Complete HTML document as string
"""
# Extract title from first h1 if not provided
if not title:
h1_match = re.search(r'^#\s+(.+)$', markdown_text, re.MULTILINE)
title = h1_match.group(1) if h1_match else 'Memory Analysis Report'
# Process markdown in order (order matters!)
content = markdown_text
# Step 1: Extract and protect code blocks with placeholders
code_blocks = []
def save_code_block(match):
idx = len(code_blocks)
lang = match.group(1) or ''
code = escape_html(match.group(2))
lang_class = f' class="language-{lang}"' if lang else ''
code_blocks.append(f'<pre><code{lang_class}>{code}</code></pre>')
return f'\x00CODEBLOCK{idx}\x00'
content = re.sub(r'```(\w*)\n(.*?)```', save_code_block, content, flags=re.DOTALL)
# Step 2: Extract and protect inline code with placeholders
inline_codes = []
def save_inline_code(match):
idx = len(inline_codes)
code = escape_html(match.group(1))
inline_codes.append(f'<code>{code}</code>')
return f'\x00INLINECODE{idx}\x00'
content = re.sub(r'`([^`]+)`', save_inline_code, content)
# Step 3: Convert headers
content = convert_headers(content)
# Step 4: Convert horizontal rules
content = convert_horizontal_rules(content)
# Step 5: Convert tables (before lists, as tables might be mixed with other content)
content = convert_tables(content)
# Step 6: Convert lists
content = convert_lists(content)
# Step 7: Convert bold and italic (now safe - code is protected)
content = convert_bold_italic(content)
# Step 8: Restore inline code
for idx, code in enumerate(inline_codes):
content = content.replace(f'\x00INLINECODE{idx}\x00', code)
# Step 9: Wrap remaining text in paragraphs (before restoring code blocks)
content = convert_paragraphs(content)
# Step 10: Highlight memory values (positive = red, negative = green)
# Do this before restoring code blocks so code content is not affected
content = re.sub(
r'\+(\d+\.?\d*)\s*(MB|KB|GB|MiB|KiB|GiB)',
r'<span class="memory-positive">+\1 \2</span>',
content
)
content = re.sub(
r'-(\d+\.?\d*)\s*(MB|KB|GB|MiB|KiB|GiB)',
r'<span class="memory-negative">-\1 \2</span>',
content
)
# Step 11: Restore code blocks (after all text processing is done)
for idx, block in enumerate(code_blocks):
content = content.replace(f'\x00CODEBLOCK{idx}\x00', block)
return get_html_template(title, content)
def convert_file(input_file: str, output_file: str, title: Optional[str] = None) -> bool:
"""
Convert a markdown file to HTML.
Args:
input_file: Path to input markdown file
output_file: Path to output HTML file
title: Optional title for the HTML document
Returns:
True if conversion succeeded, False otherwise
"""
try:
with open(input_file, 'r', encoding='utf-8') as f:
markdown_text = f.read()
html_content = markdown_to_html(markdown_text, title)
with open(output_file, 'w', encoding='utf-8') as f:
f.write(html_content)
return True
except Exception as e:
print(f"Error converting file: {e}", file=sys.stderr)
return False
def main():
parser = argparse.ArgumentParser(
description='Convert markdown memory analysis reports to styled HTML',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Convert markdown to HTML
python markdown_to_html.py report.md -o report.html
# Convert with custom title
python markdown_to_html.py report.md -o report.html --title "Memory Report v1.0"
# Read from stdin, write to stdout
cat report.md | python markdown_to_html.py > report.html
"""
)
parser.add_argument('input', nargs='?', default='-',
help='Input markdown file (default: stdin)')
parser.add_argument('--output', '-o',
help='Output HTML file (default: stdout)')
parser.add_argument('--title', '-t',
help='HTML document title (default: extracted from h1)')
args = parser.parse_args()
# Read input
if args.input == '-':
markdown_text = sys.stdin.read()
else:
try:
with open(args.input, 'r', encoding='utf-8') as f:
markdown_text = f.read()
except FileNotFoundError:
print(f"Error: Input file not found: {args.input}", file=sys.stderr)
return 1
except Exception as e:
print(f"Error reading input file: {e}", file=sys.stderr)
return 1
# Convert
html_content = markdown_to_html(markdown_text, args.title)
# Write output
if args.output:
try:
with open(args.output, 'w', encoding='utf-8') as f:
f.write(html_content)
print(f"HTML report written to: {args.output}")
except Exception as e:
print(f"Error writing output file: {e}", file=sys.stderr)
return 1
else:
print(html_content)
return 0
if __name__ == '__main__':
sys.exit(main())