From 8233770a5f99b419df059875ff7d2679d13647fa Mon Sep 17 00:00:00 2001 From: liuwei Date: Thu, 5 Jun 2025 14:56:33 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=E4=B8=B4=E6=97=B6=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E7=AE=A1=E7=90=86=E7=AD=96=E7=95=A5=E3=80=82=E9=98=B2?= =?UTF-8?q?=E6=AD=A2=E5=88=B0=E5=A4=84=E7=94=9F=E6=88=90=E4=B8=B4=E6=97=B6?= =?UTF-8?q?=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- utils/markdown_to_image.py | 67 +++++++++++++++++++++++++++++++++----- 1 file changed, 59 insertions(+), 8 deletions(-) diff --git a/utils/markdown_to_image.py b/utils/markdown_to_image.py index f39ec1d..93173de 100644 --- a/utils/markdown_to_image.py +++ b/utils/markdown_to_image.py @@ -2,6 +2,7 @@ import subprocess import time import markdown +from pathlib import Path from playwright.async_api import async_playwright import os import asyncio @@ -234,17 +235,67 @@ async def html_to_image(html_file, output_image): # 主函数:从字符串转换 Markdown 到图片(异步版) -async def convert_md_str_to_image(md_content, output_image): +async def convert_md_str_to_image(md_content: str, output_image: str) -> str: """ 将 Markdown 字符串转换为图片(异步)。 - """ - timestamp = int(time.time()) - temp_html = f"temp_output_{timestamp}.html" - md_str_to_html(md_content, temp_html) - await html_to_image(temp_html, output_image) - logger.debug(f"图片已生成:{output_image}") - return os.path.abspath(output_image) + Args: + md_content (str): Markdown 内容字符串 + output_image (str): 输出图片的文件名(不含路径) + + Returns: + str: 生成的图片文件的绝对路径 + + Raises: + FileNotFoundError: 如果临时目录无法创建或访问 + ValueError: 如果 md_content 为空 + """ + # 验证输入 + if not md_content: + raise ValueError("Markdown content cannot be empty") + + # 获取项目根目录 + project_root = os.getcwd() + project_root_path = Path(project_root).resolve() + + # 创建临时目录 + temp_dir = project_root_path / "temp" + try: + temp_dir.mkdir(parents=True, exist_ok=True) + except Exception as e: + logger.error(f"Failed to create temp directory: {e}") + raise FileNotFoundError(f"Could not create temp directory: {temp_dir}") + + # 生成唯一的临时文件名 + timestamp = int(time.time()) + temp_html_filename = f"temp_output_{timestamp}.html" + temp_html_path = temp_dir / temp_html_filename + output_image_path = temp_dir / output_image + + # 确保输出图片路径的父目录存在 + output_image_path.parent.mkdir(parents=True, exist_ok=True) + + try: + # 将 Markdown 转换为 HTML + md_str_to_html(md_content, str(temp_html_path)) + + # 将 HTML 转换为图片 + await html_to_image(str(temp_html_path), str(output_image_path)) + + logger.debug(f"图片已生成:{output_image_path}") + return str(output_image_path.resolve()) + + except Exception as e: + logger.error(f"Error converting markdown to image: {e}") + raise + finally: + # 可选:清理临时 HTML 文件 + if temp_html_path.exists(): + try: + temp_html_path.unlink() + logger.debug(f"Deleted temporary HTML file: {temp_html_path}") + except Exception as e: + logger.warning(f"Failed to delete temporary HTML file: {e}") # 示例使用 if __name__ == "__main__":