fix issues

This commit is contained in:
2026-09-01 12:11:09 +08:00
parent 7acf61a600
commit b13b9de2bc
2 changed files with 211 additions and 23 deletions
+4 -4
View File
@@ -349,7 +349,7 @@
],
"properties": {
"skill_name": {
"description": "技能名称(即技能根目录下的子目录名,如 md2pdf)",
"description": "技能名称(即技能根目录下的子目录名)",
"type": "string"
}
},
@@ -361,7 +361,7 @@
"type": "function",
"function": {
"name": "run_skill",
"description": "执行指定技能,传入所需参数,自动检查与安装依赖(pip install --target 装入共享 deps 目录并以 PYTHONPATH 注入,或执行 install.sh),返回技能运行的标准输出或错误信息。\n\n技能入口脚本约定接收一个 JSON 字符串作为唯一命令行参数,其中包含全部输入参数键值对。\n\n- 执行前会根据 SKILL.md 的 input_schema.required 校验必填参数。\n- 依赖安装有缓存标记 .deps_installed,仅当 requirements.txt / install.sh 变化时重装。\n- 默认超时 120 秒。\n- input_args 中的相对路径会按会话工作目录自动解析并转为绝对路径(技能进程的工作目录是技能目录,不是会话目录),直接传相对路径即可。",
"description": "执行指定技能,传入所需参数,自动检查与安装依赖,返回技能运行的标准输出或错误信息。\n技能入口脚本约定接收一个 JSON 字符串作为唯一命令行参数,其中包含全部输入参数键值对。\n- 执行前会根据 SKILL.md 的 input_schema.required 校验必填参数。\n- 默认超时 120 秒。\n- 参数中的相对路径会按会话工作目录自动解析并转为绝对路径,直接传相对路径即可。",
"parameters": {
"required": [
"skill_name",
@@ -369,11 +369,11 @@
],
"properties": {
"skill_name": {
"description": "技能名称(技能根目录下的子目录名,如 md2pdf)",
"description": "技能名称(技能根目录下的子目录名)",
"type": "string"
},
"input_args": {
"description": "技能所需的输入参数字典(对象),键值对形式。例如 {\"input\": \"file.md\", \"output\": \"out.pdf\"}。具体字段以 get_skill_info 查看的 SKILL.md 为准。路径参数可传相对会话工作目录的路径,也可传绝对路径,后者原样使用。",
"description": "技能所需的输入参数字典(对象),键值对形式。例如 {\"input\": \"file.md\", \"output\": \"out.pdf\"}。具体字段以 get_skill_info 查看的 SKILL.md 为准。路径参数建议传相对会话工作目录的路径,也可传绝对路径。",
"type": "object"
}
},
+207 -19
View File
@@ -2,10 +2,9 @@
# -*- coding: utf-8 -*-
"""
md2pdf 技能主入口:将 Markdown 转换为 PDF(支持中文和常用格式)
依赖 `install.sh` 预先准备好中文字体(fonts/cjk.ttf),本脚本只负责注册和转换。
依赖 install.sh 预先准备好中文字体(fonts/cjk.ttf),本脚本只负责注册和转换。
"""
import sys
import os
import json
import re
from pathlib import Path
@@ -16,7 +15,9 @@ from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.enums import TA_LEFT
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import SimpleDocTemplate, Paragraph, ListFlowable, ListItem, HRFlowable
from reportlab.platypus import (
SimpleDocTemplate, Paragraph, Spacer, ListFlowable, ListItem, HRFlowable
)
# ---------- 字体注册 ----------
def register_font():
@@ -34,9 +35,204 @@ def register_font():
print("未找到准备好的字体文件 fonts/cjk.ttf,请确认 install.sh 已执行", file=sys.stderr)
return None
# ---------- 样式与 Markdown 解析(与之前相同,此处省略详细代码) ----------
# ...(保留原有的 parse_inline、parse_markdown、markdown_to_pdf 等)
# ---------- 样式定义 ----------
def build_styles(normal_font, bold_font):
"""构建 PDF 样式,使用指定字体"""
return {
"title": ParagraphStyle(
name="Title",
fontName=bold_font,
fontSize=22,
leading=28,
alignment=1, # 居中
spaceAfter=12,
),
"h1": ParagraphStyle(
name="H1",
fontName=bold_font,
fontSize=18,
leading=24,
spaceBefore=16,
spaceAfter=8,
textColor="#1a3d6d",
),
"h2": ParagraphStyle(
name="H2",
fontName=bold_font,
fontSize=15,
leading=20,
spaceBefore=12,
spaceAfter=6,
textColor="#2c3e50",
),
"h3": ParagraphStyle(
name="H3",
fontName=bold_font,
fontSize=12.5,
leading=17,
spaceBefore=10,
spaceAfter=4,
textColor="#34495e",
),
"body": ParagraphStyle(
name="Body",
fontName=normal_font,
fontSize=10.5,
leading=16,
spaceAfter=4,
alignment=TA_LEFT,
),
"quote": ParagraphStyle(
name="Quote",
fontName=normal_font,
fontSize=10.5,
leading=16,
leftIndent=12,
rightIndent=12,
spaceBefore=4,
spaceAfter=4,
textColor="#555555",
backColor="#f8f8f8",
borderPadding=(6, 6, 6, 6),
),
"list_item": ParagraphStyle(
name="List",
fontName=normal_font,
fontSize=10.5,
leading=16,
leftIndent=4,
),
}
# ---------- Markdown 解析辅助 ----------
def escape_xml(text):
"""转义 XML 特殊字符(但保留已生成的 <b>、<i> 等标签)"""
# 注意:此函数在 parse_inline 之后调用,因此只处理未被替换的字符
return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
def parse_inline(text):
"""处理行内格式:加粗、斜体、行内代码"""
# 加粗 **text**
text = re.sub(r'\*\*(.+?)\*\*', r'<b>\1</b>', text)
# 斜体 *text*(避免匹配加粗中的单个星号)
text = re.sub(r'(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)', r'<i>\1</i>', text)
# 行内代码 `code`
text = re.sub(r'`(.+?)`', r'<font face="Courier">\1</font>', text)
return text
def is_ordered_list(line):
"""判断是否为有序列表行"""
return re.match(r'^\d+\.\s+', line)
# ---------- Markdown 解析主函数 ----------
def parse_markdown(md_text, styles):
"""解析 Markdown 文本,返回 platypus 故事列表"""
story = []
lines = md_text.split('\n')
current_list = [] # 当前列表项
current_list_type = None # 'ul' 或 'ol'
def flush_list():
nonlocal current_list, current_list_type
if current_list:
items = [
ListItem(Paragraph(item, styles["list_item"]), leftIndent=18)
for item in current_list
]
if current_list_type == 'ol':
flowable = ListFlowable(items, bulletType='1', start='1', leftIndent=18)
else:
flowable = ListFlowable(items, bulletType='bullet', start='circle', leftIndent=18)
story.append(flowable)
current_list = []
current_list_type = None
for raw_line in lines:
line = raw_line.strip()
if not line:
flush_list()
continue
# 分隔线
if re.match(r'^(-{3,}|\*{3,})$', line):
flush_list()
story.append(HRFlowable(
width="100%", thickness=0.5, color="#cccccc",
spaceBefore=8, spaceAfter=8
))
continue
# 标题
if line.startswith('# '):
flush_list()
story.append(Paragraph(escape_xml(parse_inline(line[2:])), styles["title"]))
elif line.startswith('## '):
flush_list()
story.append(Paragraph(escape_xml(parse_inline(line[3:])), styles["h1"]))
elif line.startswith('### '):
flush_list()
story.append(Paragraph(escape_xml(parse_inline(line[4:])), styles["h2"]))
elif line.startswith('#### '):
flush_list()
story.append(Paragraph(escape_xml(parse_inline(line[5:])), styles["h3"]))
# 无序列表
elif line.startswith(('- ', '* ')):
if current_list_type != 'ul':
flush_list()
current_list_type = 'ul'
current_list.append(escape_xml(parse_inline(line[2:])))
# 有序列表
elif is_ordered_list(line):
if current_list_type != 'ol':
flush_list()
current_list_type = 'ol'
text = re.sub(r'^\d+\.\s+', '', line)
current_list.append(escape_xml(parse_inline(text)))
# 引用
elif line.startswith('> '):
flush_list()
story.append(Paragraph(escape_xml(parse_inline(line[2:])), styles["quote"]))
# 普通段落
else:
flush_list()
story.append(Paragraph(escape_xml(parse_inline(line)), styles["body"]))
flush_list()
return story
# ---------- 主转换函数 ----------
def markdown_to_pdf(md_path, pdf_path):
"""读取 Markdown 文件并转换为 PDF"""
md_text = Path(md_path).read_text(encoding="utf-8")
# 注册字体
font_pair = register_font()
if font_pair:
normal_font, bold_font = font_pair
print(f"使用中文字体:{normal_font}")
else:
normal_font, bold_font = "Helvetica", "Helvetica-Bold"
print("使用 Helvetica(中文可能显示为方块)")
# 构建样式
styles = build_styles(normal_font, bold_font)
# 解析 Markdown
story = parse_markdown(md_text, styles)
# 创建 PDF
doc = SimpleDocTemplate(
pdf_path,
pagesize=A4,
leftMargin=20 * mm,
rightMargin=20 * mm,
topMargin=18 * mm,
bottomMargin=18 * mm,
title=Path(md_path).stem,
)
doc.build(story)
# ---------- 入口 ----------
def main():
if len(sys.argv) != 2:
print("Usage: python3 run.py '<json_string>'")
@@ -45,28 +241,20 @@ def main():
try:
args = json.loads(sys.argv[1])
except json.JSONDecodeError as e:
print(f"Invalid JSON argument: {e}")
print(f"Invalid JSON argument: {e}", file=sys.stderr)
sys.exit(1)
input_path = args.get("input")
if not input_path:
print("Error: 'input' field is required")
print("Error: 'input' field is required", file=sys.stderr)
sys.exit(1)
output_path = args.get("output") or str(Path(input_path).with_suffix(".pdf"))
output_path = args.get("output")
if not output_path:
output_path = str(Path(input_path).with_suffix(".pdf"))
try:
font_pair = register_font()
if font_pair:
normal, bold = font_pair
print(f"使用中文字体:{normal}")
else:
normal, bold = "Helvetica", "Helvetica-Bold"
print("使用 Helvetica(中文可能显示为方块)")
# 构建样式、解析 Markdown、生成 PDF
# ...(调用已有的函数)
markdown_to_pdf(input_path, output_path)
print(f"PDF generated: {output_path}")
except Exception as e:
print(f"Error during conversion: {e}", file=sys.stderr)