diff --git a/app/server/templates/advising-system.txt b/app/server/templates/advising-system.txt index ec133ae..403e47b 100644 --- a/app/server/templates/advising-system.txt +++ b/app/server/templates/advising-system.txt @@ -34,18 +34,19 @@ agent continues from the file alone. Therefore: never treat an uploaded file named task.md as the brief — writing it yourself is the commitment. - Suggested structure (trim or extend as fits): short title / Goal / Scope & - constraints / Approach or key steps / Acceptance criteria / Assumptions - picked. -- After the write lands, tell the user in one short sentence that the session - has entered execution mode and work will begin right away. + constraints / What the deliverable must contain / Acceptance criteria / + Assumptions picked. ## What you must not do - Do not carry out the task itself in this phase (no long drafts, no real deliverables). Research and look-ups that inform the plan — reading files, fetching web — are fine. -- `.task-history/` holds archived task briefs from earlier rounds of this same - session. Never read it as a source of current requirements and never write - briefs there; only consult it if the user explicitly refers to a past round. -- Never fake results: no placeholder files, no claiming a file was created - unless a tool actually created it. +- Do not prescribe technical implementation. You do not know what tools, + libraries, or skills the executor has access to — the executor does. Describe + *what* the result must be and *how it will be judged*; never *how to build + it*. + +When in doubt about whether something is a requirement or an implementation +detail, ask yourself: "Would a different executor using different tools still +need this?" If yes, it belongs in the brief. If no, leave it out. diff --git a/app/server/templates/system-prompt.txt b/app/server/templates/system-prompt.txt index ec56d8d..4081174 100644 --- a/app/server/templates/system-prompt.txt +++ b/app/server/templates/system-prompt.txt @@ -139,8 +139,9 @@ Noto CJK fonts are installed (SC/TC/JP/KR). For matplotlib, set Tesseract (`chi_sim`) already support Chinese. **Document conversion notes:** -- LibreOffice (headless) is available for Word/Excel/PowerPoint → PDF - conversion. Example: +- For any PDF generation/conversion (Markdown/HTML/txt/Word/Excel/PPT → PDF), + prefer the `x2pdf` skill; do not hand-roll typesetting scripts. +- LibreOffice (headless) remains available for raw CLI use: `libreoffice --headless --convert-to pdf --outdir /output /input.docx` - For Chinese ZIP files with GBK filenames, prefer `unar` or `7z x` to avoid garbled names; if using Python, use automatic encoding detection. diff --git a/executor/Dockerfile b/executor/Dockerfile index 7d03874..6569116 100644 --- a/executor/Dockerfile +++ b/executor/Dockerfile @@ -39,9 +39,10 @@ ENV MPLBACKEND=Agg \ # util-linux 提供 unshare/mount/umount(隔离 wrapper 必需);sudo 已刻意不装。 RUN apt-get update -y && apt-get install -y --no-install-recommends \ ca-certificates curl git python3 python3-pip python3-venv python3-dev \ - ripgrep wget jq p7zip-full unzip unar file tree \ + ripgrep wget jq p7zip-full unzip unar zip file tree \ libreoffice-writer libreoffice-calc libreoffice-impress \ fonts-noto-cjk fonts-dejavu fonts-stix \ + fonts-wqy-microhei fonts-wqy-zenhei \ poppler-utils qpdf ghostscript imagemagick \ tesseract-ocr tesseract-ocr-chi-sim \ ffmpeg sqlite3 libsqlite3-dev \ diff --git a/skills/README.md b/skills/README.md index 3e586fd..20b786f 100644 --- a/skills/README.md +++ b/skills/README.md @@ -161,7 +161,7 @@ apt-get install -y -qq some-package - `install.sh` 必须可执行(`chmod +x install.sh`)。 - 请保持幂等:init 侧以内容 hash 缓存(`.deps_installed`),构建侧靠 Docker 层缓存;脚本应在“依赖已就绪”时快速跳过。 -- 想两处都跑不报错:apt 类语句加 `|| true` 容错,并在脚本末尾自行校验“要的东西是否就绪”,就绪则 exit 0、否则 exit 1(参考 `md2pdf/install.sh`)。否则 init 阶段(根文件系统只读)的 apt 失败会让整个技能被标记为“未就绪”。 +- 想两处都跑不报错:apt 类语句加 `|| true` 容错,并在脚本末尾自行校验“要的东西是否就绪”,就绪则 exit 0、否则 exit 1(参考 `img-utils/install.sh`)。否则 init 阶段(根文件系统只读)的 apt 失败会让整个技能被标记为“未就绪”。 - 改动 `install.sh` 后:系统包需 `docker compose build agent-executor`,资产需 `docker compose up -d`(或两者一起 `build && up`)。 ### 5.3 缓存机制 @@ -266,7 +266,7 @@ A:目前所有技能共享同一个 `deps` 目录,建议锁定精确版本 ## 11. 参考资料 -查看现有的 `md2pdf` 技能(位于 `skills/md2pdf/`)可以了解一个较为完整的实现,包括如何处理系统级依赖和字体等。但请根据自身技能的实际需求进行设计,不必拘泥于该示例。 +查看现有的 `x2pdf` 技能(位于 `skills/x2pdf/`)可以了解一个较为完整的实现,包括如何自带声明 Python 依赖与系统级依赖(不假设镜像预烘)、按扩展名分派渲染后端、参数化版式 CSS 等。但请根据自身技能的实际需求进行设计,不必拘泥于该示例。 图像处理类需求可参考 `skills/img-utils/`:它演示了一个纯 Python + 预装 Pillow 的实现(转换/缩放/裁剪/压缩/水印/切片/拼图,无 requirements.txt,仅靠 install.sh 保证中文字体),并明确区分“确定性图像处理”与“AI 生成/修图”的能力边界。 diff --git a/skills/img-utils/SKILL.md b/skills/img-utils/SKILL.md index f3b5493..4e05ac7 100644 --- a/skills/img-utils/SKILL.md +++ b/skills/img-utils/SKILL.md @@ -106,5 +106,5 @@ output_schema: - 本技能**只做确定性图像处理**(转换/缩放/裁剪/压缩/水印/拼图),不含 AI 生成、抠图、换脸、扩图、修复等生成式/语义编辑能力。 - 若用户的需求属于"文生图 / AI 修图"等生成式范畴,不要用本技能硬凑,应说明能力边界并推荐第三方工具(豆包、即梦、可灵、Photoshop 等)。 - 任何操作都不会覆盖输入原图;输出目录不存在时自动创建。 -- 中文水印需要字体:优先用 `font` 参数指定;否则依赖系统字体(install.sh 会自动装文泉驿)或同仓 md2pdf 技能准备过的字体。 +- 中文水印需要字体:优先用 `font` 参数指定;否则依赖系统字体(镜像预装文泉驿,install.sh 会兑底安装)。 - 输入依赖预装的 Pillow,无需额外 Python 依赖;系统级字体依赖见 install.sh。 diff --git a/skills/img-utils/install.sh b/skills/img-utils/install.sh index 43db54c..df8da48 100644 --- a/skills/img-utils/install.sh +++ b/skills/img-utils/install.sh @@ -1,14 +1,11 @@ #!/bin/bash set -e -# 确保存在可用的中文字体(watermark 中文水印需要),Pillow 读字体无 reportlab 的 CFF 限制, +# 确保存在可用的中文字体(watermark 中文水印需要):Pillow 能读 wqy/Noto 任意字体, # 但 NotoSansCJK ttc 的默认字型(索引 0)是 JP,中文水印会出日式字形, -# 因此就绪判定只认文泉驿(系统 wqy 或同仓 md2pdf 提取的 fonts/cjk.ttf),Noto 仅作兜底。 +# 因此就绪判定优先文泉驿(镜像已预装,缺失时 apt 兑底),Noto 仅作告警兑底。 # 命中即幂等退出;依赖缓存由 Skill Manager 依据本脚本内容哈希管理。 -SKILL_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -MD2PDF_FONT="$SKILL_DIR/../md2pdf/fonts/cjk.ttf" - has_wqy() { for f in /usr/share/fonts/truetype/wqy/wqy-zenhei.ttc \ /usr/share/fonts/truetype/wqy/wqy-microhei.ttc; do @@ -22,11 +19,6 @@ if has_wqy; then exit 0 fi -if [ -s "$MD2PDF_FONT" ]; then - echo "使用同仓 md2pdf 准备的中文字体:$MD2PDF_FONT" - exit 0 -fi - if [ "$(id -u)" -eq 0 ]; then echo "未找到中文字体,安装 fonts-wqy-zenhei..." # best-effort:apt 失败不直接报错,交给下面的就绪判定兜底 @@ -34,7 +26,7 @@ if [ "$(id -u)" -eq 0 ]; then apt-get install -y -qq fonts-wqy-zenhei || true fi -if has_wqy || [ -s "$MD2PDF_FONT" ]; then +if has_wqy; then echo "中文字体就绪" elif [ -f /usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc ]; then # Noto 兜底:中文能显示,只是默认字型偏日式;不算失败 diff --git a/skills/img-utils/run.py b/skills/img-utils/run.py index e645cd8..6214959 100644 --- a/skills/img-utils/run.py +++ b/skills/img-utils/run.py @@ -37,8 +37,8 @@ CJK_FONT_CANDIDATES = [ '/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc', '/usr/share/fonts/truetype/wqy/wqy-microhei.ttc', ] -# Noto 只作最后兜底:Pillow(FreeType) 能读它的 CFF 轮廓,但 ttc 默认字型(索引 0)是 JP 字形, -# 中文水印会出日式写法;同仓 md2pdf 的 cjk.ttf(文泉驿)排在它前面。 +# Noto 只作最后兑底:Pillow(FreeType) 能读它的 CFF 轮廓,但 ttc 默认字型(索引 0)是 JP 字形, +# 中文水印会出日式写法;因此系统文泉驿(CJK_FONT_CANDIDATES)排在它前面。 NOTO_CJK_FALLBACK = '/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc' @@ -223,15 +223,13 @@ def action_compress(img, fmt, args): def find_font(explicit): - """字体查找:显式 font > 系统 wqy > 同仓 md2pdf 准备的字体 > Noto 兜底。""" + """字体查找:显式 font > 系统 wqy > Noto 兑底。""" if explicit: p = Path(explicit) if not p.exists(): raise ValueError('指定的字体不存在:%s' % explicit) return str(p) - skill_root = Path(__file__).resolve().parent.parent candidates = list(CJK_FONT_CANDIDATES) - candidates.append(str(skill_root / 'md2pdf' / 'fonts' / 'cjk.ttf')) candidates.append(NOTO_CJK_FALLBACK) for c in candidates: if Path(c).exists(): diff --git a/skills/md2pdf/.gitignore b/skills/md2pdf/.gitignore deleted file mode 100644 index 0480ebe..0000000 --- a/skills/md2pdf/.gitignore +++ /dev/null @@ -1 +0,0 @@ -fonts/ diff --git a/skills/md2pdf/SKILL.md b/skills/md2pdf/SKILL.md deleted file mode 100644 index 8b8275c..0000000 --- a/skills/md2pdf/SKILL.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -name: md2pdf -description: 将 Markdown 文件转换为 PDF -input_schema: - type: object - properties: - input: - type: string - description: 输入 Markdown 文件路径 - output: - type: string - description: 输出 PDF 文件路径(可选,默认与输入同名) - required: [input] -output_schema: - type: string - description: 生成的 PDF 文件路径 ---- - -## 功能说明 -- 该技能使用 `reportlab` 将 Markdown 转换为 PDF。 -- 支持标题、加粗、斜体、列表、引用、分隔线、图片、表格、代码段等常用 Markdown 语法 -- 列表:`-`/`*` 与 `1.` 两种;**嵌套列表**按缩进(2/4 空格或 tab)递归成子列表,两种标记可混用;条目间有空行的**松散列表**会合并为一个列表连续编号,有序列表以首项编号为起点 -- 标题:`#`~`####`,以及 setext 下划线标题(`===` → H1、`---` → H2);文首 YAML front matter(`--- … ---`)当元数据剔除,不渲染 -- 代码段:``` 或 ~~~ 围栏渲染为等宽浅底代码框,围栏内**原样输出**(不解析 Markdown,`<` `&` 无需转义);行内 `code` 用等宽字体,含中文时自动改用中文字体 -- 图片:`![alt](src)` 独立成行时嵌入 PDF(居中,超宽时等比缩到版心宽); - 相对路径按 **Markdown 文件所在目录** 解析(如任务目录里的图表),也支持绝对路径与 http(s) 图片; - 图片加载失败退回 alt 文本占位,不会静默丢失 -- 表格:`| a | b |` 管道表格(含对齐分隔行)自动识别为表格,表头加底纹、隔行斑马纹、居中显示 -- 自动处理中文字体 - -## 调用方式 -通过 `skill`(op=run)调用,参数: -- `input`:Markdown 文件路径(必填) -- `output`:PDF 输出路径(可选,默认与输入同名) diff --git a/skills/md2pdf/install.sh b/skills/md2pdf/install.sh deleted file mode 100755 index 40ac51c..0000000 --- a/skills/md2pdf/install.sh +++ /dev/null @@ -1,89 +0,0 @@ -#!/bin/bash -set -e - -# 准备中文字体 fonts/cjk.ttf。 -# 关键约束:reportlab 的 TTFont 只支持 TrueType(glyf) 轮廓, -# Noto Sans CJK / Source Han Sans 均为 OTTO(CFF) 轮廓,提取/改名后依然注册失败, -# 因此候选只保留文泉驿(wqy,glyf 轮廓),缺失时用 apt 安装。 -FONT_TARGET="fonts/cjk.ttf" - -mkdir -p fonts - -# sfnt magic 必须是 TrueType(00010000 / true / typ1)才算有效; -# 旧版本曾用 Noto(CFF) 提取出魔数为 OTTO 的假 .ttf,这里检测并自愈重建。 -is_valid_ttf() { - [ -s "$1" ] || return 1 - local magic - magic=$(od -An -N4 -tx1 "$1" | tr -d ' \n') - case "$magic" in - 00010000|74727565|74797031) return 0 ;; - *) return 1 ;; - esac -} - -if is_valid_ttf "$FONT_TARGET"; then - echo "字体文件已存在且为有效 TrueType,跳过准备" - exit 0 -fi - -if [ -s "$FONT_TARGET" ]; then - echo "现有 $FONT_TARGET 非 TrueType 轮廓(可能是旧版提取的 CFF 字体),删除重建" - rm -f "$FONT_TARGET" -fi - -# 查找系统中的文泉驿字体(仅 glyf 轮廓字体可被 reportlab 使用) -FONT_FILE="" -for f in /usr/share/fonts/truetype/wqy/wqy-microhei.ttc \ - /usr/share/fonts/truetype/wqy/wqy-zenhei.ttc; do - if [ -f "$f" ]; then - FONT_FILE="$f" - break - fi -done - -# 没有则安装文泉驿 -if [ -z "$FONT_FILE" ]; then - echo "未找到文泉驿字体,尝试安装 fonts-wqy-microhei fonts-wqy-zenhei..." - if [ "$(id -u)" -eq 0 ]; then - apt-get update -y -qq - apt-get install -y -qq fonts-wqy-microhei fonts-wqy-zenhei - for f in /usr/share/fonts/truetype/wqy/wqy-microhei.ttc \ - /usr/share/fonts/truetype/wqy/wqy-zenhei.ttc; do - if [ -f "$f" ]; then - FONT_FILE="$f" - break - fi - done - fi - if [ -z "$FONT_FILE" ]; then - echo "错误:无中文字体可用(非 root 且系统未装文泉驿)" >&2 - exit 1 - fi -fi - -echo "从 TTC 提取第一个字型到 $FONT_TARGET:$FONT_FILE" -python3 - "$FONT_FILE" <<'PY' -import sys -from fontTools.ttLib import TTCollection - -ttc_path = sys.argv[1] -out_path = "fonts/cjk.ttf" -collection = TTCollection(ttc_path) -if not collection.fonts: - print("TTC 中无字体", file=sys.stderr) - sys.exit(1) -font = collection.fonts[0] -if "glyf" not in font: - print(f"字体 {font['name'].getDebugName(4)} 不是 TrueType 轮廓,reportlab 无法使用", file=sys.stderr) - sys.exit(1) -font.save(out_path) -print(f"提取完成:{out_path}({font['name'].getDebugName(4)})") -PY - -# 兜底校验:产出的必须又是有效 TrueType -if ! is_valid_ttf "$FONT_TARGET"; then - echo "错误:提取结果不是有效 TrueType 字体" >&2 - exit 1 -fi - -echo "中文字体准备完成:$FONT_TARGET" diff --git a/skills/md2pdf/requirements.txt b/skills/md2pdf/requirements.txt deleted file mode 100644 index e5039f3..0000000 --- a/skills/md2pdf/requirements.txt +++ /dev/null @@ -1,2 +0,0 @@ -reportlab>=3.6.12 -fonttools>=4.38.0 diff --git a/skills/md2pdf/run.py b/skills/md2pdf/run.py deleted file mode 100644 index a6f5263..0000000 --- a/skills/md2pdf/run.py +++ /dev/null @@ -1,534 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -""" -md2pdf 技能主入口:将 Markdown 转换为 PDF(支持中文和常用格式) -依赖 install.sh 预先准备好中文字体(fonts/cjk.ttf),本脚本只负责注册和转换。 -""" -import sys -import io -import json -import re -import urllib.request -from pathlib import Path - -from reportlab.lib.pagesizes import A4 -from reportlab.lib.units import mm -from reportlab.lib import colors -from reportlab.lib.styles import ParagraphStyle -from reportlab.lib.enums import TA_LEFT -from reportlab.lib.utils import ImageReader -from reportlab.pdfbase import pdfmetrics -from reportlab.pdfbase.ttfonts import TTFont -from reportlab.platypus import ( - SimpleDocTemplate, Paragraph, Preformatted, Spacer, ListFlowable, ListItem, HRFlowable, Image, - Table, TableStyle -) - -# 当前正文体名字(注册成功为中文字体,失败退回 Helvetica): -# 行内代码/代码段含中文时用它渲染——Courier 没有中文字形,会变方块。 -_CJK_FONT = 'Helvetica' - -# ---------- 字体注册 ---------- -def register_font(): - """注册技能目录下的 fonts/cjk.ttf(由 install.sh 准备)""" - font_path = Path(__file__).parent / "fonts" / "cjk.ttf" - if font_path.exists() and font_path.stat().st_size > 0: - try: - pdfmetrics.registerFont(TTFont("CJK", str(font_path))) - pdfmetrics.registerFont(TTFont("CJKBold", str(font_path))) # 粗体模拟 - # 注册字体族:否则段落里的 / 标签解析后找不到 CJK 的粗/斜变体, 不生效。 - # 中文斜体可读性差且无真斜体变体,italic 映射回常规体(仅西文可见伪斜或不变)。 - pdfmetrics.registerFontFamily("CJK", normal="CJK", bold="CJKBold", italic="CJK", boldItalic="CJKBold") - return ("CJK", "CJKBold") - except Exception as e: - print(f"字体注册失败:{e},将使用 Helvetica", file=sys.stderr) - return None - else: - print("未找到准备好的字体文件 fonts/cjk.ttf,请确认 install.sh 已执行", file=sys.stderr) - return None - -# ---------- 样式定义 ---------- -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 特殊字符。必须在 parse_inline 之前调用: - 先转义原文、再注入 // 等标签;顺序反了会把生成的标签也转义成字面量。""" - return text.replace("&", "&").replace("<", "<").replace(">", ">") - -def parse_inline(text): - """处理行内格式:加粗、斜体、行内代码、链接。入参必须是 escape_xml 之后的文本。""" - # 行内代码 `code`:先占位保护,避免其中的 * [ ] 被后续规则误伤 - code_spans = [] - def _stash(m): - code_spans.append(m.group(1)) - return '\x00%d\x00' % (len(code_spans) - 1) - text = re.sub(r'`(.+?)`', _stash, text) - # 行内图片 ![alt](src):段落里无法嵌图,降级为 alt 文本;必须在链接规则之前, - # 否则 [alt](src) 部分会被下面的链接规则改写成可点链接,图片变成“!+链接”残骸 - text = re.sub(IMG_MD_RE, lambda m: m.group(1) or '[图片]', text) - # 链接 [text](url) → reportlab (可点击;转义后 URL 里的 & 已是 &,属性内合法) - text = re.sub(r'\[([^\]]+)\]\(([^)\s]+)\)', r'\1', text) - # 加粗 **text** - text = re.sub(r'\*\*(.+?)\*\*', r'\1', text) - # 斜体 *text*(避免匹配加粗中的单个星号) - text = re.sub(r'(?\1', text) - # 还原行内代码:含中文时用正文字体(Courier 无中文字形),纯西文用 Courier 保证等宽 - def _restore(m): - code = code_spans[int(m.group(1))] - face = 'Courier' if code.isascii() else _CJK_FONT - return '' + code + '' - text = re.sub(r'\x00(\d+)\x00', _restore, text) - return text - -def render_inline(text): - """统一入口:先转义再走行内格式(顺序错了标签会被转义成字面量显示)。""" - return parse_inline(escape_xml(text)) - -def is_ordered_list(line): - """判断是否为有序列表行""" - return re.match(r'^\d+\.\s+', line) - -# ---------- 图片 ---------- -# Markdown 图片语法:![alt](src) 或 ![alt](src "title") -IMG_MD_RE = re.compile(r'!\[([^\]]*)\]\(\s*([^)\s]+)(?:\s+"[^"]*")?\s*\)') - -def load_image_source(src, md_dir): - """加载 md 引用的图片,返回可交给 ImageReader 的对象(路径或 BytesIO),失败返回 None。 - 相对路径按 **md 文件所在目录** 解析:技能子进程的 cwd 是技能目录而非任务目录, - 不能直接 open 相对路径;另外兼容绝对路径与 http(s) 远程图。""" - if re.match(r'^https?://', src): - try: - req = urllib.request.Request(src, headers={'User-Agent': 'Mozilla/5.0'}) - with urllib.request.urlopen(req, timeout=15) as resp: - return io.BytesIO(resp.read()) - except Exception as e: - print(f"图片下载失败:{src}({e})", file=sys.stderr) - return None - candidates = [Path(src)] if Path(src).is_absolute() else [md_dir / src, Path.cwd() / src] - for c in candidates: - try: - if c.is_file(): - return str(c) - except OSError: - continue - print(f"图片未找到:{src}(在 {md_dir} 下未命中)", file=sys.stderr) - return None - -def image_flowable(src, md_dir, max_width): - """Markdown 图片 → platypus Image(居中,超宽时等比缩到版心宽);失败返回 None 由调用方文字兜底""" - obj = load_image_source(src, md_dir) - if obj is None: - return None - try: - iw, ih = ImageReader(obj).getSize() - except Exception as e: - print(f"图片格式不支持:{src}({e})", file=sys.stderr) - return None - if not iw or not ih: - return None - if isinstance(obj, io.BytesIO): - obj.seek(0) # getSize 读过字节,绘制前要回到开头 - # 像素按 96dpi 换算磅值;小图不放大,大图缩到版心宽 - w = min(iw * 72.0 / 96.0, max_width) - h = ih * (w / iw) - img = Image(obj, width=w, height=h) - img.hAlign = 'CENTER' - return img - -# ---------- 表格 ---------- -# 数据/表头行:| a | b |;分隔行:| --- | :---: | ---: | --- | -TABLE_ROW_RE = re.compile(r'^\|.*\|\s*$') -TABLE_SEP_RE = re.compile(r'^\|?\s*:?-{3,}:?\s*(?:\|\s*:?-{3,}:?\s*)+\|?\s*$') - -def split_row(line): - """按未转义的竖线拆分表格行,保留 `\|` 转义出来的字面竖线""" - line = line.strip() - cells = re.split(r'(? 0x2E80 for ch in code_text) - style = ParagraphStyle( - name='CodeBlock', - fontName=styles['body'].fontName if has_cjk else 'Courier', - fontSize=8.5, - leading=12.5, - textColor=colors.HexColor('#24292f'), - ) - # splitInRow=1:单元格内容(Preformatted)可跨页分裂。默认 0 时超页高的代码块会让整个转换 - # 报 "Flowable too large on page" 而失败。 - box = Table([[Preformatted(code_text, style)]], colWidths=[max_width], splitInRow=1) - box.setStyle(TableStyle([ - ('BACKGROUND', (0, 0), (-1, -1), colors.HexColor('#f6f8fa')), - ('BOX', (0, 0), (-1, -1), 0.5, colors.HexColor('#d8dee6')), - ('LEFTPADDING', (0, 0), (-1, -1), 6), - ('RIGHTPADDING', (0, 0), (-1, -1), 6), - ('TOPPADDING', (0, 0), (-1, -1), 5), - ('BOTTOMPADDING', (0, 0), (-1, -1), 5), - ('VALIGN', (0, 0), (-1, -1), 'TOP'), - ])) - box.hAlign = 'LEFT' - box.spaceBefore = 6 - box.spaceAfter = 6 - return box - -# ---------- 列表 ---------- -def indent_width(raw): - """行首缩进宽度(tab 按 4 列计)——用于判定列表嵌套层级""" - expanded = raw.expandtabs(4) - return len(expanded) - len(expanded.lstrip(' ')) - -def _normalize_levels(items): - """按缩进宽度归一化嵌套层级:[(缩进, kind, text, num)] → [(depth, ...)](首项为第 0 层)""" - out, stack = [], [] - for indent, kind, text, num in items: - while len(stack) > 1 and indent < stack[-1]: - stack.pop() - if not stack or indent > stack[-1]: - stack.append(indent) - out.append((len(stack) - 1, kind, text, num)) - return out - -def _make_list(children, kind, start): - if kind == 'ol': - return ListFlowable(children, bulletType='1', start=start, leftIndent=18) - return ListFlowable(children, bulletType='bullet', start='circle', leftIndent=18) - -def _one_list(items, pos, depth, kind, styles): - """消费连续的同层同类型条目;更深缩进的条目作为子列表挂到上一个条目下""" - children, start = [], '1' - while pos < len(items) and items[pos][0] == depth and items[pos][1] == kind: - _, _, text, num = items[pos] - if not children: - start = num or '1' # 有序列表只认首项编号 - pos += 1 - body = [Paragraph(text, styles['list_item'])] - if pos < len(items) and items[pos][0] > depth: - subs, pos = _sub_lists(items, pos, styles) - body.extend(subs) - children.append(ListItem(body, leftIndent=18)) - return _make_list(children, kind, start), pos - -def _sub_lists(items, pos, styles): - """一个条目下的全部子列表(可能跨类型、多层)""" - out = [] - child = items[pos][0] - while pos < len(items) and items[pos][0] >= child: - flowable, pos = _one_list(items, pos, items[pos][0], items[pos][1], styles) - out.append(flowable) - return out, pos - -def build_lists(items, styles): - """列表条目 → [flowable](顶层;同层类型切换会产生多个列表)""" - items = _normalize_levels(items) - out, pos = [], 0 - while pos < len(items): - flowable, pos = _one_list(items, pos, items[pos][0], items[pos][1], styles) - out.append(flowable) - return out - -def strip_front_matter(md_text): - """去掉文件开头的 YAML front matter(--- ... ---):属元数据,不该渲染进 PDF。 - 仅当第一行就是 --- 且能找到收尾 --- 时生效,避免误删以分隔线开头的正文。""" - lines = md_text.split('\n') - if not lines or lines[0].strip() != '---': - return md_text - for j in range(1, len(lines)): - if lines[j].strip() == '---': - return '\n'.join(lines[j + 1:]) - return md_text - -# ---------- Markdown 解析主函数 ---------- -def parse_markdown(md_text, styles, md_dir=None, max_width=170 * mm): - """解析 Markdown 文本,返回 platypus 故事列表""" - md_dir = md_dir or Path.cwd() - story = [] - lines = md_text.split('\n') - current_list = [] # 当前列表条目:[(缩进宽度, 'ul'|'ol', 已渲染文本, 首项编号)] - - def flush_list(): - nonlocal current_list - if current_list: - for flowable in build_lists(current_list, styles): - story.append(flowable) - current_list = [] - - i = 0 - n = len(lines) - while i < n: - raw = lines[i] - line = raw.strip() - i += 1 - if not line: - # 空行不打断列表:Markdown 允许条目间空行(松散列表), - # 否则 1./2./3. 会各自成为独立 ListFlowable,编号全部重置为 1。 - # 列表遇非列表行时,由各分支自己的 flush_list() 收尾。 - continue - - # 代码段围栏:``` 或 ~~~(可带语言标记),围栏内原样输出、不解析 Markdown - if FENCE_OPEN_RE.match(line): - flush_list() - code_lines = [] - while i < n and not FENCE_CLOSE_RE.match(lines[i].strip()): - code_lines.append(lines[i]) # 保留原始缩进 - i += 1 - if i < n: - i += 1 # 跳过收尾围栏 - story.append(code_block_flowable('\n'.join(code_lines), styles, max_width)) - 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 - - # 独立成行的图片:![alt](src) → 嵌入 PDF;加载失败退回 alt/路径文本,不丢行 - m_img = IMG_MD_RE.fullmatch(line) - if m_img: - flush_list() - alt, src = m_img.group(1), m_img.group(2) - img = image_flowable(src, md_dir, max_width) - if img is not None: - story.append(img) - else: - label = alt or src - story.append(Paragraph(render_inline('[图片缺失:' + label + ']'), styles["body"])) - continue - - # 标题 - if line.startswith('# '): - flush_list() - story.append(Paragraph(render_inline(line[2:]), styles["title"])) - elif line.startswith('## '): - flush_list() - story.append(Paragraph(render_inline(line[3:]), styles["h1"])) - elif line.startswith('### '): - flush_list() - story.append(Paragraph(render_inline(line[4:]), styles["h2"])) - elif line.startswith('#### '): - flush_list() - story.append(Paragraph(render_inline(line[5:]), styles["h3"])) - # 无序列表 - elif line.startswith(('- ', '* ')): - current_list.append((indent_width(raw), 'ul', render_inline(line[2:]), None)) - # 有序列表 - elif is_ordered_list(line): - m = re.match(r'^(\d+)\.\s+', line) - current_list.append((indent_width(raw), 'ol', render_inline(line[m.end():]), m.group(1))) - # 引用 - elif line.startswith('> '): - flush_list() - story.append(Paragraph(render_inline(line[2:]), styles["quote"])) - # 表格:当前行是表头行,且下一行是分隔行 → 收拢成整张表 - elif TABLE_ROW_RE.match(line) and i < n and TABLE_SEP_RE.match(lines[i].strip()): - flush_list() - i += 1 # 跳过分隔行 - rows = [split_row(line)] - while i < n and TABLE_ROW_RE.match(lines[i].strip()): - rows.append(split_row(lines[i].strip())) - i += 1 - story.append(table_flowable(rows, max_width, styles)) - # 普通段落(下一行是 ===/--- 下划线时按 setext 标题处理) - else: - flush_list() - if i < n and SETEXT_H1_RE.match(lines[i].strip()): - i += 1 - story.append(Paragraph(render_inline(line), styles["title"])) - elif i < n and SETEXT_H2_RE.match(lines[i].strip()): - i += 1 - story.append(Paragraph(render_inline(line), styles["h1"])) - else: - story.append(Paragraph(render_inline(line), styles["body"])) - - flush_list() - return story - -# ---------- 主转换函数 ---------- -def markdown_to_pdf(md_path, pdf_path): - """读取 Markdown 文件并转换为 PDF""" - md_text = strip_front_matter(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(中文可能显示为方块)") - global _CJK_FONT - _CJK_FONT = normal_font - - # 构建样式 - styles = build_styles(normal_font, bold_font) - - # 解析 Markdown(图片相对路径按 md 所在目录解析;版心宽 = A4 宽 - 左右边距) - story = parse_markdown(md_text, styles, md_dir=Path(md_path).resolve().parent, max_width=A4[0] - 40 * mm) - - # 创建 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 ''") - sys.exit(1) - - try: - args = json.loads(sys.argv[1]) - except json.JSONDecodeError as 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", file=sys.stderr) - sys.exit(1) - - output_path = args.get("output") - if not output_path: - output_path = str(Path(input_path).with_suffix(".pdf")) - - try: - 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) - sys.exit(1) - -if __name__ == "__main__": - main() diff --git a/skills/x2pdf/SKILL.md b/skills/x2pdf/SKILL.md new file mode 100644 index 0000000..f8ece67 --- /dev/null +++ b/skills/x2pdf/SKILL.md @@ -0,0 +1,89 @@ +--- +name: x2pdf +description: 通用 PDF 转换:Markdown / HTML / txt / Word / Excel / PPT 转 PDF(推荐生成 PDF 一律用本技能,不要手写排版脚本) +input_schema: + type: object + properties: + input: + type: string + description: 输入文件路径,支持 .md/.markdown/.txt/.html/.htm/.docx/.xlsx/.pptx/.odt/.ods/.odp + output: + type: string + description: 输出 PDF 路径(可选,默认与输入同名) + css: + type: string + description: 自定义 CSS 文件路径(可选,仅对 md/html/txt 生效,优先级最高) + page: + type: object + description: 页面设置(可选,仅对 md/html/txt 生效;Office 文档版式由原文件决定,忽略本参数) + properties: + size: + type: string + description: 页面尺寸,默认 A4;也可传 "A5"、"letter"、"210mm 297mm" 等 + margin: + type: string + description: 页边距,默认 20mm;可单值或 "上 右 下 左" 四值 + font_size: + type: string + description: 正文字号,默认 10.5pt;标题/代码等按 em 相对缩放,压页数时调小本值 + required: [input] +output_schema: + type: string + description: 生成的 PDF 文件路径 +--- + +## 功能说明 + +统一 PDF 转换入口,按扩展名自动分派两条渲染路径: + +- **md / txt / html → WeasyPrint**(CSS 排版,字体走 fontconfig,中文用系统文泉驿/Noto,无需字体文件) +- **docx / xlsx / pptx / odt / ods / odp → LibreOffice headless**(忠于原文档版式,`page`/`css` 参数不生效) + +### Markdown 输入(`.md` / `.markdown`) +- 标准语法之外,支持表格(管道语法)、围栏代码块(```/~~~)、脚注、定义列表、 + 标题锚点、属性列表、HTML 内联(Markdown `extra` 全家桶); +- 文首 YAML front matter 当元数据剔除,不渲染; +- 图片:相对路径按 **输入文件所在目录** 解析,也支持绝对路径与 http(s) 图片; +- 自动套用默认 CSS(见下)。 + +### txt 输入(`.txt`) +- **不解析**,按原文转义后整篇以等宽 `
` 渲染(保换行,超长行自动折行)。
+
+### HTML 输入(`.html` / `.htm`)
+- 文档原样渲染,**不套默认 CSS**——自带 `