-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmd2html.py
More file actions
330 lines (277 loc) · 11.3 KB
/
Copy pathmd2html.py
File metadata and controls
330 lines (277 loc) · 11.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
#!/usr/bin/env python3
"""
MD → HTML 转换器(静态 HTML 生成)
用法: python md2html.py input.md [output.html]
"""
import sys
import re
from pathlib import Path
def md_to_html(md_text: str) -> str:
"""将 Markdown 文本转换为 HTML 内容(不含完整页面结构)"""
lines = md_text.split('\n')
html_parts = []
in_code_block = False
code_lang = ''
code_lines = []
in_table = False
table_rows = []
i = 0
while i < len(lines):
line = lines[i]
# 代码块开始
if line.strip().startswith('```'):
if in_code_block:
# 代码块结束
code_content = '\n'.join(code_lines)
escaped = code_content.replace('&', '&').replace('<', '<').replace('>', '>')
if code_lang:
html_parts.append(f'<pre><code class="language-{code_lang}">{escaped}</code></pre>')
else:
html_parts.append(f'<pre><code>{escaped}</code></pre>')
in_code_block = False
code_lines = []
code_lang = ''
else:
# 代码块开始
in_code_block = True
code_lang = line.strip()[3:].strip()
i += 1
continue
if in_code_block:
code_lines.append(line)
i += 1
continue
# 空行
if not line.strip():
if in_table and table_rows:
# 表格结束
html_parts.append(render_table(table_rows))
table_rows = []
in_table = False
i += 1
continue
# 表格行
if line.strip().startswith('|') and line.strip().endswith('|'):
# 检查是否是分隔行(|---|---|)
if re.match(r'^\|[\s\-:|]+\|$', line.strip()):
i += 1
continue
cells = [c.strip() for c in line.strip().split('|')[1:-1]]
table_rows.append(cells)
in_table = True
i += 1
continue
# 如果之前在表格中,结束表格
if in_table and table_rows:
html_parts.append(render_table(table_rows))
table_rows = []
in_table = False
# HTML 标签直接透传(details/summary, div class 等)
if line.strip().startswith('<'):
html_parts.append(line)
i += 1
continue
# 标题
if line.startswith('#'):
match = re.match(r'^(#{1,6})\s+(.+)$', line)
if match:
level = len(match.group(1))
text = process_inline(match.group(2))
html_parts.append(f'<h{level}>{text}</h{level}>')
i += 1
continue
# 引用
if line.startswith('>'):
quote_lines = []
while i < len(lines) and lines[i].startswith('>'):
quote_lines.append(lines[i][1:].strip())
i += 1
content = process_inline(' '.join(quote_lines))
html_parts.append(f'<blockquote>{content}</blockquote>')
continue
# 分隔线
if re.match(r'^[-*_]{3,}\s*$', line.strip()):
html_parts.append('<hr>')
i += 1
continue
# 无序列表
if re.match(r'^[\s]*[-*]\s', line):
items = [] # [(level, text)]
while i < len(lines) and re.match(r'^[\s]*[-*]\s', lines[i]):
indent = len(lines[i]) - len(lines[i].lstrip())
level = indent // 2
item_text = re.sub(r'^[\s]*[-*]\s', '', lines[i])
items.append((level, process_inline(item_text)))
i += 1
# 递归生成嵌套列表 HTML
def build_list(items, start=0, current_level=0):
if start >= len(items):
return '', start
html = '<ul>'
idx = start
while idx < len(items):
level, text = items[idx]
if level < current_level:
# 回退到上一级
break
elif level > current_level:
# 进入子列表
sub_html, idx = build_list(items, idx, level)
# 将子列表添加到上一个 <li> 中
if html.endswith('</li>'):
html = html[:-5] + sub_html + '</li>'
else:
html += f'<li>{sub_html}</li>'
else:
# 同级列表项
html += f'<li>{text}</li>'
idx += 1
html += '</ul>'
return html, idx
list_html, _ = build_list(items, 0, 0)
html_parts.append(list_html)
continue
# 有序列表
if re.match(r'^[\s]*\d+\.\s', line):
list_items = []
while i < len(lines) and re.match(r'^[\s]*\d+\.\s', lines[i]):
item_text = re.sub(r'^[\s]*\d+\.\s', '', lines[i])
list_items.append(f'<li>{process_inline(item_text)}</li>')
i += 1
html_parts.append('<ol>' + ''.join(list_items) + '</ol>')
continue
# 普通段落
para_lines = []
while i < len(lines) and lines[i].strip() and not lines[i].startswith('#') and not lines[i].startswith('>') and not lines[i].startswith('```') and not re.match(r'^[-*]\s', lines[i]) and not re.match(r'^\d+\.\s', lines[i]) and not lines[i].strip().startswith('<'):
para_lines.append(lines[i])
i += 1
if para_lines:
content = process_inline(' '.join(para_lines))
html_parts.append(f'<p>{content}</p>')
continue
i += 1
# 处理未结束的表格
if in_table and table_rows:
html_parts.append(render_table(table_rows))
return '\n'.join(html_parts)
def render_table(rows: list) -> str:
"""渲染表格"""
if not rows:
return ''
html = '<table>\n'
# 第一行作为表头
html += '<thead>\n<tr>\n'
for cell in rows[0]:
html += f'<th>{process_inline(cell)}</th>\n'
html += '</tr>\n</thead>\n'
# 其他行作为表体
if len(rows) > 1:
html += '<tbody>\n'
for row in rows[1:]:
html += '<tr>\n'
for cell in row:
html += f'<td>{process_inline(cell)}</td>\n'
html += '</tr>\n'
html += '</tbody>\n'
html += '</table>'
return html
def process_inline(text: str) -> str:
"""处理行内标记"""
# 转义 HTML 特殊字符(但保留已有标签)
# 先保护已有标签
tags = []
def save_tag(match):
tags.append(match.group(0))
return f'__TAG{len(tags)-1}__'
text = re.sub(r'<[^>]+>', save_tag, text)
# 转义特殊字符
text = text.replace('&', '&')
text = text.replace('<', '<')
text = text.replace('>', '>')
# 恢复标签
for idx, tag in enumerate(tags):
text = text.replace(f'__TAG{idx}__', tag)
# 粗体 **text**
text = re.sub(r'\*\*(.+?)\*\*', r'<strong>\1</strong>', text)
# 斜体 *text*
text = re.sub(r'\*(.+?)\*', r'<em>\1</em>', text)
# 行内代码 `code`
text = re.sub(r'`(.+?)`', r'<code>\1</code>', text)
# 链接 [text](url)
text = re.sub(r'\[(.+?)\]\((.+?)\)', r'<a href="\2">\1</a>', text)
# 图片 
text = re.sub(r'!\[(.+?)\]\((.+?)\)', r'<img src="\2" alt="\1">', text)
return text
def wrap_html(content: str, title: str = 'Agent 输出') -> str:
"""将 HTML 内容包装成完整页面"""
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>{title}</title>
<style>
body {{
font-family: -apple-system, "Microsoft YaHei", "PingFang SC", sans-serif;
max-width: 900px;
margin: 40px auto;
padding: 0 20px;
line-height: 1.8;
color: #333;
background: #fafafa;
}}
h1 {{ color: #1a1a1a; border-bottom: 2px solid #e0e0e0; padding-bottom: 10px; margin: 24px 0 16px; }}
h2 {{ color: #2c5f8a; margin: 32px 0 12px; }}
h3 {{ color: #4a7fb5; margin: 24px 0 8px; }}
p {{ margin: 12px 0; }}
ul, ol {{ margin: 12px 0; padding-left: 24px; }}
li {{ margin: 4px 0; }}
code {{ background: #f0f0f0; padding: 2px 6px; border-radius: 3px; font-size: 0.9em; }}
pre {{ background: #2d2d2d; color: #f8f8f2; padding: 16px; border-radius: 6px; overflow-x: auto; margin: 16px 0; }}
pre code {{ background: none; padding: 0; color: inherit; }}
blockquote {{ border-left: 4px solid #4a90d9; padding: 12px 16px; margin: 16px 0; background: #f0f7ff; }}
table {{ border-collapse: collapse; width: 100%; margin: 16px 0; }}
th, td {{ border: 1px solid #ddd; padding: 8px 12px; text-align: left; }}
th {{ background: #f0f4f8; font-weight: 600; }}
tr:nth-child(even) {{ background: #f9f9f9; }}
details {{ margin: 16px 0; padding: 12px 16px; border: 1px solid #e0e0e0; border-radius: 6px; background: #fff; }}
details[open] {{ background: #f9f9f9; }}
summary {{ cursor: pointer; font-weight: 600; color: #2c5f8a; padding: 4px 0; }}
summary:hover {{ color: #1a5a8a; }}
.tip {{ background: #e8f5e9; border-left: 4px solid #4caf50; padding: 12px 16px; margin: 16px 0; border-radius: 0 4px 4px 0; }}
.warning {{ background: #fff3e0; border-left: 4px solid #ff9800; padding: 12px 16px; margin: 16px 0; border-radius: 0 4px 4px 0; }}
.danger {{ background: #ffebee; border-left: 4px solid #f44336; padding: 12px 16px; margin: 16px 0; border-radius: 0 4px 4px 0; }}
hr {{ border: none; border-top: 1px solid #e0e0e0; margin: 24px 0; }}
a {{ color: #4a90d9; text-decoration: none; }}
a:hover {{ text-decoration: underline; }}
</style>
</head>
<body>
{content}
</body>
</html>'''
def main():
if len(sys.argv) < 2:
print('用法: python md2html.py input.md [output.html]')
print('示例: python md2html.py README.md README.html')
sys.exit(1)
input_path = Path(sys.argv[1])
if not input_path.exists():
print(f'错误: 文件不存在 - {input_path}')
sys.exit(1)
# 输出文件名
if len(sys.argv) >= 3:
output_path = Path(sys.argv[2])
else:
output_path = input_path.with_suffix('.html')
# 读取 MD
md_text = input_path.read_text(encoding='utf-8')
# 转换
content = md_to_html(md_text)
html = wrap_html(content, title=input_path.stem)
# 写入
output_path.write_text(html, encoding='utf-8')
print(f'✅ 已生成: {output_path}')
print(f' 大小: {output_path.stat().st_size:,} 字节')
if __name__ == '__main__':
main()