import markdown
import os
from loguru import logger
def convert_md_to_html(md_content: str, title: str = "AlphaEar Report") -> str:
"""
将 Markdown 转换为带样式的 HTML
"""
# 转换 Markdown 为 HTML
# 启用 table, toc 等扩展
# 使用 'md_in_html' 来正确处理 markdown 中的 HTML 块
html_body = markdown.markdown(
md_content,
extensions=['extra', 'toc', 'nl2br', 'md_in_html']
)
# 简单的 Premium CSS 模板
html_template = f"""
{title}
{html_body}
"""
return html_template
def save_report_as_html(md_path: str, output_path: str = None):
if not output_path:
output_path = md_path.replace(".md", ".html")
try:
with open(md_path, "r", encoding="utf-8") as f:
md_content = f.read()
title = "AlphaEar 市场研报"
# 尝试从第一行获取标题
lines = md_content.split('\n')
if lines and lines[0].startswith('# '):
title = lines[0].replace('# ', '').strip()
html_content = convert_md_to_html(md_content, title)
with open(output_path, "w", encoding="utf-8") as f:
f.write(html_content)
logger.info(f"✅ HTML Report saved to: {output_path}")
return output_path
except Exception as e:
logger.error(f"Failed to convert report to HTML: {e}")
return None
if __name__ == "__main__":
import sys
if len(sys.argv) > 1:
save_report_as_html(sys.argv[1])
else:
print("Usage: python3 md_to_html.py ")