-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrender.py
More file actions
650 lines (550 loc) · 28.3 KB
/
Copy pathrender.py
File metadata and controls
650 lines (550 loc) · 28.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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
#!/usr/bin/env python3
"""
自动转换 MD → HTML 并打开浏览器
用法:
python render.py input.md # 转换并打开(带交互功能)
echo "# 标题" | python render.py # 从 stdin 读取
python render.py -o output.html # 指定输出文件名
python render.py --static input.md # 生成静态 HTML(无交互功能)
"""
import sys
import os
import re
import subprocess
import tempfile
import shutil
from pathlib import Path
from datetime import datetime
def md_to_html(md_text: str) -> str:
"""将 Markdown 文本转换为 HTML 内容"""
# 导入 md2html 模块
script_dir = Path(__file__).parent
sys.path.insert(0, str(script_dir))
from md2html import md_to_html as convert
return convert(md_text)
def wrap_interactive_html(content: str, title: str = 'Agent 输出',
archive_name: str = None) -> str:
"""将 HTML 内容包装成交互式页面(带评论和回复功能)"""
# 用于回复功能的报告链接(预留)
report_link_section = ""
if archive_name:
report_link_section = f"""
// 当前报告文件名(用于长回复链接)
const CURRENT_REPORT = '{archive_name}';
"""
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>
* {{ box-sizing: border-box; margin: 0; padding: 0; }}
body {{ font-family: -apple-system, "Microsoft YaHei", "PingFang SC", sans-serif; background: #fafafa; color: #333; line-height: 1.8; }}
.toolbar {{ position: fixed; top: 0; left: 0; right: 0; height: 48px; background: #fff; border-bottom: 1px solid #e0e0e0; display: flex; align-items: center; padding: 0 16px; z-index: 100; gap: 12px; }}
.toolbar-title {{ font-weight: 600; color: #333; margin-right: auto; }}
.toolbar-btn {{ padding: 6px 12px; background: #f5f5f5; border: 1px solid #ddd; border-radius: 4px; cursor: pointer; font-size: 13px; color: #555; }}
.toolbar-btn:hover {{ background: #e8e8e8; }}
.toolbar-btn.commit {{ background: #4caf50; color: white; border-color: #4caf50; }}
.toolbar-btn.commit:hover {{ background: #43a047; }}
.toolbar-btn.commit:disabled {{ background: #ccc; border-color: #ccc; cursor: not-allowed; }}
.comment-count {{ background: #ff9800; color: white; padding: 2px 8px; border-radius: 12px; font-size: 12px; margin-left: 4px; }}
.main {{ margin-top: 48px; padding: 32px; max-width: 900px; margin-left: auto; margin-right: auto; }}
/* 折叠块样式 */
details {{ margin: 16px 0; padding: 12px 16px; border: 1px solid #e0e0e0; border-radius: 6px; background: #fff; position: relative; }}
details[open] {{ background: #f9f9f9; }}
summary {{ cursor: pointer; font-weight: 600; color: #2c5f8a; padding: 4px 0; display: flex; align-items: center; gap: 8px; }}
summary:hover {{ color: #1a5a8a; }}
/* 评论按钮 */
.comment-btn {{ margin-left: auto; padding: 4px 8px; background: #f5f5f5; border: 1px solid #ddd; border-radius: 4px; cursor: pointer; font-size: 12px; color: #666; display: flex; align-items: center; gap: 4px; }}
.comment-btn:hover {{ background: #e8e8e8; }}
.comment-btn.has-comment {{ background: #fff3e0; border-color: #ff9800; color: #e65100; }}
/* 评论区域 */
.comment-area {{ margin-top: 12px; padding-top: 12px; border-top: 1px dashed #ddd; display: none; }}
.comment-area.visible {{ display: block; }}
.comment-input {{ width: 100%; padding: 8px 12px; border: 1px solid #ddd; border-radius: 4px; font-size: 14px; resize: vertical; min-height: 60px; font-family: inherit; }}
.comment-input:focus {{ outline: none; border-color: #4a90d9; }}
.comment-actions {{ margin-top: 8px; display: flex; gap: 8px; }}
.comment-save-btn {{ padding: 6px 12px; background: #4a90d9; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 13px; }}
.comment-save-btn:hover {{ background: #357abd; }}
.comment-delete-btn {{ padding: 6px 12px; background: #f44336; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 13px; }}
.comment-delete-btn:hover {{ background: #d32f2f; }}
/* 评论显示 */
.comment-list {{ margin-top: 12px; }}
.comment-item {{ margin-bottom: 8px; padding: 8px 12px; border-radius: 4px; font-size: 14px; }}
.comment-item.user {{ background: #e3f2fd; border-left: 3px solid #2196f3; }}
.comment-item.agent {{ background: #e8f5e9; border-left: 3px solid #4caf50; }}
.comment-header {{ display: flex; justify-content: space-between; margin-bottom: 4px; }}
.comment-author {{ font-weight: 600; }}
.comment-author.user {{ color: #1565c0; }}
.comment-author.agent {{ color: #2e7d32; }}
.comment-time {{ font-size: 12px; color: #999; }}
.comment-text {{ color: #555; }}
.comment-actions-inline {{ margin-top: 4px; display: flex; gap: 8px; }}
.reply-btn {{ padding: 2px 8px; background: transparent; border: 1px solid #ddd; border-radius: 4px; cursor: pointer; font-size: 12px; color: #666; }}
.reply-btn:hover {{ background: #f5f5f5; }}
/* 回复区域 */
.reply-area {{ margin-top: 8px; padding: 8px; background: #f9f9f9; border-radius: 4px; display: none; }}
.reply-area.visible {{ display: block; }}
.reply-input {{ width: 100%; padding: 6px 10px; border: 1px solid #ddd; border-radius: 4px; font-size: 13px; resize: vertical; min-height: 40px; font-family: inherit; }}
.reply-actions {{ margin-top: 6px; display: flex; gap: 6px; }}
.reply-short-btn {{ padding: 4px 10px; background: #4a90d9; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 12px; }}
.reply-short-btn:hover {{ background: #357abd; }}
.reply-long-btn {{ padding: 4px 10px; background: #9c27b0; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 12px; }}
.reply-long-btn:hover {{ background: #7b1fa2; }}
.reply-cancel-btn {{ padding: 4px 10px; background: #f5f5f5; border: 1px solid #ddd; border-radius: 4px; cursor: pointer; font-size: 12px; color: #666; }}
/* 回复显示 */
.reply-item {{ margin-top: 6px; padding: 6px 10px; border-radius: 4px; font-size: 13px; }}
.reply-item.user {{ background: #e3f2fd; border-left: 2px solid #2196f3; }}
.reply-item.agent {{ background: #e8f5e9; border-left: 2px solid #4caf50; }}
.reply-item.agent.long {{ background: #f3e5f5; border-left: 2px solid #9c27b0; }}
.reply-link {{ color: #9c27b0; text-decoration: none; font-weight: 600; }}
.reply-link:hover {{ text-decoration: underline; }}
/* 内容样式 */
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; }}
.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; }}
/* 提示消息 */
.toast {{ position: fixed; bottom: 24px; left: 50%; transform: translateX(-50%); background: #333; color: white; padding: 12px 24px; border-radius: 6px; font-size: 14px; z-index: 1000; opacity: 0; transition: opacity 0.3s; }}
.toast.show {{ opacity: 1; }}
.toast.success {{ background: #4caf50; }}
.toast.error {{ background: #f44336; }}
</style>
</head>
<body>
<div class="toolbar">
<span class="toolbar-title">📄 Agent 输出</span>
<span id="commentSummary" class="comment-count" style="display: none;">0 条评论</span>
<button class="toolbar-btn" id="clearBtn" onclick="clearAllComments()">🗑️ 清空评论</button>
<button class="toolbar-btn commit" id="commitBtn" onclick="commitComments()" disabled>✅ Commit</button>
</div>
<div class="main">
{content}
</div>
<div class="toast" id="toast"></div>
<script>
const STORAGE_KEY = 'md2html_comments';
const commitBtn = document.getElementById('commitBtn');
const commentSummary = document.getElementById('commentSummary');
const toast = document.getElementById('toast');
{report_link_section}
// 为折叠块添加评论按钮
function setupCommentButtons() {{
const details = document.querySelectorAll('details');
details.forEach((detail, index) => {{
// 确保有 ID
if (!detail.id) {{
detail.id = `block-${{String(index + 1).padStart(3, '0')}}`;
}}
const summary = detail.querySelector('summary');
if (summary && !summary.querySelector('.comment-btn')) {{
const blockId = detail.id;
// 创建评论按钮
const commentBtn = document.createElement('button');
commentBtn.className = 'comment-btn';
commentBtn.innerHTML = `💬 <span class="comment-count">0</span>`;
commentBtn.onclick = (e) => {{
e.stopPropagation();
toggleCommentArea(blockId);
}};
summary.appendChild(commentBtn);
// 创建评论区域
const commentArea = document.createElement('div');
commentArea.className = 'comment-area';
commentArea.id = `comment-area-${{blockId}}`;
commentArea.innerHTML = `
<textarea class="comment-input" id="comment-input-${{blockId}}"
placeholder="写下你的评论..."></textarea>
<div class="comment-actions">
<button class="comment-save-btn" onclick="saveComment('${{blockId}}', 'user')">保存评论</button>
</div>
<div class="comment-list" id="comment-list-${{blockId}}"></div>
`;
detail.appendChild(commentArea);
}}
}});
}}
// 切换评论区域显示
function toggleCommentArea(blockId) {{
const commentArea = document.getElementById(`comment-area-${{blockId}}`);
if (commentArea) {{
commentArea.classList.toggle('visible');
}}
}}
// 保存评论到 localStorage
function saveComment(blockId, author = 'user') {{
const input = document.getElementById(`comment-input-${{blockId}}`);
const comment = input.value.trim();
if (!comment) {{
showToast('请输入评论内容', 'error');
return;
}}
// 获取块标题
const detail = document.getElementById(blockId);
const summary = detail.querySelector('summary');
const title = summary.textContent.replace('💬', '').replace(/\\d+/g, '').trim();
// 保存到 localStorage
const data = getData();
if (!data[blockId]) {{
data[blockId] = {{ title: title, comments: [] }};
}}
data[blockId].comments.push({{
id: 'c' + Date.now(),
author: author,
content: comment,
timestamp: Date.now(),
replies: []
}});
localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
// 更新 UI
renderComments(blockId);
updateCommitButton();
input.value = '';
showToast('评论已保存', 'success');
}}
// 添加回复
function addReply(blockId, commentId, type, content, link = null) {{
const data = getData();
if (!data[blockId]) return;
const comment = data[blockId].comments.find(c => c.id === commentId);
if (!comment) return;
comment.replies.push({{
id: 'r' + Date.now(),
author: 'agent',
type: type,
content: content,
link: link,
timestamp: Date.now()
}});
localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
renderComments(blockId);
}}
// 渲染评论列表
function renderComments(blockId) {{
const data = getData();
const listEl = document.getElementById(`comment-list-${{blockId}}`);
if (!listEl || !data[blockId]) return;
const comments = data[blockId].comments;
let html = '';
comments.forEach(comment => {{
const time = new Date(comment.timestamp).toLocaleString();
const authorClass = comment.author === 'user' ? 'user' : 'agent';
const authorLabel = comment.author === 'user' ? '👤 用户' : '🤖 Agent';
html += `
<div class="comment-item ${{authorClass}}">
<div class="comment-header">
<span class="comment-author ${{authorClass}}">${{authorLabel}}</span>
<span class="comment-time">${{time}}</span>
</div>
<div class="comment-text">${{escapeHtml(comment.content)}}</div>
<div class="comment-actions-inline">
<button class="reply-btn" onclick="toggleReplyArea('${{blockId}}', '${{comment.id}}')">💬 回复</button>
</div>
<div class="reply-area" id="reply-area-${{comment.id}}">
<textarea class="reply-input" id="reply-input-${{comment.id}}"
placeholder="写下回复..."></textarea>
<div class="reply-actions">
<button class="reply-short-btn" onclick="saveReply('${{blockId}}', '${{comment.id}}', 'short')">短回复</button>
<button class="reply-long-btn" onclick="saveReply('${{blockId}}', '${{comment.id}}', 'long')">长回复</button>
<button class="reply-cancel-btn" onclick="toggleReplyArea('${{blockId}}', '${{comment.id}}')">取消</button>
</div>
</div>
`;
// 渲染回复
comment.replies.forEach(reply => {{
const replyTime = new Date(reply.timestamp).toLocaleString();
const replyAuthorClass = reply.author === 'user' ? 'user' : 'agent';
const replyAuthorLabel = reply.author === 'user' ? '👤 用户' : '🤖 Agent';
const typeLabel = reply.type === 'long' ? '(长回复)' : '';
const longClass = reply.type === 'long' ? ' long' : '';
let contentHtml = escapeHtml(reply.content);
if (reply.type === 'long' && reply.link) {{
contentHtml += `<br><a href="${{reply.link}}" class="reply-link">→ 查看完整报告</a>`;
}}
html += `
<div class="reply-item ${{replyAuthorClass}}${{longClass}}">
<div class="comment-header">
<span class="comment-author ${{replyAuthorClass}}">${{replyAuthorLabel}}${{typeLabel}}</span>
<span class="comment-time">${{replyTime}}</span>
</div>
<div class="comment-text">${{contentHtml}}</div>
</div>
`;
}});
html += '</div>';
}});
listEl.innerHTML = html;
// 更新评论按钮计数
const detail = document.getElementById(blockId);
const commentBtn = detail.querySelector('.comment-btn');
if (commentBtn) {{
commentBtn.classList.toggle('has-comment', comments.length > 0);
commentBtn.querySelector('.comment-count').textContent = comments.length;
}}
}}
// 切换回复区域显示
function toggleReplyArea(blockId, commentId) {{
const replyArea = document.getElementById(`reply-area-${{commentId}}`);
if (replyArea) {{
replyArea.classList.toggle('visible');
}}
}}
// 保存回复
function saveReply(blockId, commentId, type) {{
const input = document.getElementById(`reply-input-${{commentId}}`);
const content = input.value.trim();
if (!content) {{
showToast('请输入回复内容', 'error');
return;
}}
// 如果是长回复,生成报告链接
let link = null;
if (type === 'long') {{
// 这里可以集成 render.py 生成新报告
// 暂时使用占位符
link = prompt('请输入新报告的文件名(如 report_v2.html):');
if (!link) return;
}}
addReply(blockId, commentId, type, content, link);
toggleReplyArea(blockId, commentId);
showToast(type === 'short' ? '短回复已保存' : '长回复已保存', 'success');
}}
// HTML 转义
function escapeHtml(text) {{
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}}
// 获取所有数据
function getData() {{
const data = localStorage.getItem(STORAGE_KEY);
return data ? JSON.parse(data) : {{}};
}}
// 加载已保存的评论
function loadComments() {{
const data = getData();
Object.keys(data).forEach(blockId => {{
const detail = document.getElementById(blockId);
if (detail) {{
renderComments(blockId);
}}
}});
updateCommitButton();
}}
// 更新 Commit 按钮状态
function updateCommitButton() {{
const data = getData();
let totalComments = 0;
Object.values(data).forEach(block => {{
totalComments += block.comments.length;
}});
commitBtn.disabled = totalComments === 0;
commentSummary.textContent = `${{totalComments}} 条评论`;
commentSummary.style.display = totalComments > 0 ? 'inline' : 'none';
}}
// Commit 评论 - 生成报告并复制到剪贴板
function commitComments() {{
const data = getData();
const blocks = Object.keys(data);
if (blocks.length === 0) {{
showToast('没有评论可提交', 'error');
return;
}}
// 生成报告
let report = '# 用户反馈报告\\n\\n';
blocks.forEach(blockId => {{
const {{ title, comments }} = data[blockId];
report += `## 块:${{title}}\\n`;
comments.forEach(comment => {{
const authorLabel = comment.author === 'user' ? '用户' : 'Agent';
report += `${{authorLabel}}:${{comment.content}}\\n`;
// 包含回复
comment.replies.forEach(reply => {{
const replyAuthorLabel = reply.author === 'user' ? '用户' : 'Agent';
const typeLabel = reply.type === 'long' ? '(长回复)' : '';
report += ` └─ ${{replyAuthorLabel}}${{typeLabel}}:${{reply.content}}\\n`;
if (reply.link) {{
report += ` → 报告链接:${{reply.link}}\\n`;
}}
}});
}});
report += '\\n';
}});
report += '---\\n\\n请根据以上反馈迭代内容。';
// 复制到剪贴板
navigator.clipboard.writeText(report).then(() => {{
showToast(`✅ 已生成报告并复制到剪贴板`, 'success');
}}).catch(err => {{
// 降级方案:使用 textarea
const textarea = document.createElement('textarea');
textarea.value = report;
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
document.body.removeChild(textarea);
showToast(`✅ 已生成报告并复制到剪贴板`, 'success');
}});
}}
// 清空所有评论
function clearAllComments() {{
if (!confirm('确定要清空所有评论吗?')) {{
return;
}}
localStorage.removeItem(STORAGE_KEY);
// 重新初始化
setupCommentButtons();
loadComments();
showToast('所有评论已清空', 'success');
}}
// 显示提示消息
function showToast(message, type = 'success') {{
toast.textContent = message;
toast.className = `toast ${{type}} show`;
setTimeout(() => {{
toast.classList.remove('show');
}}, 3000);
}}
// 初始化
document.addEventListener('DOMContentLoaded', () => {{
setupCommentButtons();
loadComments();
}});
</script>
</body>
</html>'''
def wrap_static_html(content: str, title: str = 'Agent 输出') -> str:
"""将 HTML 内容包装成静态页面(无交互功能)"""
# 导入 md2html 模块
script_dir = Path(__file__).parent
sys.path.insert(0, str(script_dir))
from md2html import wrap_html
return wrap_html(content, title=title)
def open_in_browser(html_path: Path):
"""用默认浏览器打开 HTML 文件"""
# 转换为绝对路径
abs_path = html_path.resolve()
# Windows
if sys.platform == 'win32':
os.startfile(str(abs_path))
# macOS
elif sys.platform == 'darwin':
subprocess.run(['open', str(abs_path)])
# Linux
else:
subprocess.run(['xdg-open', str(abs_path)])
def generate_archive_path(input_path: Path) -> Path:
"""生成 archive 目录下的输出路径"""
script_dir = Path(__file__).parent
archive_dir = script_dir / 'archive'
archive_dir.mkdir(exist_ok=True)
# 生成文件名:原文件名_时间戳.html
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
filename = f'{input_path.stem}_{timestamp}.html'
return archive_dir / filename
def main():
import argparse
parser = argparse.ArgumentParser(description='MD → HTML 自动转换并打开')
parser.add_argument('input', nargs='?', help='输入的 .md 文件')
parser.add_argument('-o', '--output', help='输出的 .html 文件路径')
parser.add_argument('-c', '--clipboard', action='store_true',
help='从剪贴板读取 MD 内容')
parser.add_argument('-n', '--no-open', action='store_true',
help='只转换,不打开浏览器')
parser.add_argument('-q', '--quiet', action='store_true',
help='静默模式,不输出日志')
parser.add_argument('--static', action='store_true',
help='生成静态 HTML(无交互功能)')
parser.add_argument('--no-archive', action='store_true',
help='不保存到 archive/ 目录')
args = parser.parse_args()
# 获取 MD 内容
md_text = None
if args.clipboard:
# 从剪贴板读取
try:
import win32clipboard
win32clipboard.OpenClipboard()
try:
md_text = win32clipboard.GetClipboardData(win32clipboard.CF_UNICODETEXT)
finally:
win32clipboard.CloseClipboard()
except ImportError:
# 如果没有 win32clipboard,用 powershell
result = subprocess.run(
['powershell', '-command', 'Get-Clipboard'],
capture_output=True, text=True, encoding='utf-8'
)
md_text = result.stdout.strip()
elif args.input:
# 从文件读取
input_path = Path(args.input)
if not input_path.exists():
print(f'❌ 文件不存在: {input_path}', file=sys.stderr)
sys.exit(1)
md_text = input_path.read_text(encoding='utf-8')
elif not sys.stdin.isatty():
# 从 stdin 读取
md_text = sys.stdin.read()
else:
parser.print_help()
sys.exit(1)
if not md_text or not md_text.strip():
print('❌ 没有输入内容', file=sys.stderr)
sys.exit(1)
# 转换
content = md_to_html(md_text)
# 生成 archive 路径
archive_path = None
archive_name = None
if args.input and not args.no_archive:
archive_path = generate_archive_path(Path(args.input))
archive_name = archive_path.name
# 包装成 HTML
if args.static:
html = wrap_static_html(content, title='Agent 输出')
else:
html = wrap_interactive_html(content, title='Agent 输出', archive_name=archive_name)
# 确定输出路径
if args.output:
output_path = Path(args.output)
elif archive_path:
output_path = archive_path
else:
# 没有指定输入文件时,用临时文件
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
output_path = Path(tempfile.gettempdir()) / f'agent_output_{timestamp}.html'
# 写入文件
output_path.write_text(html, encoding='utf-8')
if not args.quiet:
mode = '静态' if args.static else '交互式'
print(f'✅ 已生成{mode} HTML: {output_path}')
print(f' 大小: {output_path.stat().st_size:,} 字节')
if archive_path:
print(f' 归档: {archive_path}')
# 打开浏览器
if not args.no_open:
if not args.quiet:
print(f'🌐 正在打开浏览器...')
open_in_browser(output_path)
# 输出路径(供脚本调用)
if args.quiet:
print(str(output_path))
if __name__ == '__main__':
main()