Compare commits
11
Commits
69a1ee0bdf
...
09cf474c2d
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
09cf474c2d | ||
|
|
ed7f111c95 | ||
|
|
9adc98b0f5 | ||
|
|
c59ddf5eb4 | ||
|
|
49a3d35227 | ||
|
|
27b03e71ef | ||
|
|
bb621b89b7 | ||
|
|
6aa1a2789b | ||
|
|
5a9bebcf71 | ||
|
|
29e46692fc | ||
|
|
89c673864f |
@@ -118,7 +118,7 @@ mcp_servers:
|
||||
| `skill` | ✓ | ✗ | ✓ | `skill` 工具与 `lab` |
|
||||
| `disable` | ✗ | ✗ | ✗ | 无人 |
|
||||
|
||||
`skill` 用于「能力包在技能后面」的场景:工具照常发现并注册,只是不进模型的 tools 数组,改为以技能形式暴露——`{"list":"all"}` 能看到它,`{"get":"<名>"}` 直接返回 MCP 原始的 `description` + `input_schema`,`{"run":"<名>","args":{…}}` 转发给服务。不用在 `skills/` 里建目录。旧字段 `enable` 已废弃,`mode: silent` 已移除(启动会报错并提示改用 `skill`)。
|
||||
`skill` 用于「能力包在技能后面」的场景:工具照常发现并注册,只是不进模型的 tools 数组,改为以技能形式暴露——`{"op":"list"}` 能看到它,`{"op":"get","name":"<名>"}` 直接返回 MCP 原始的 `description` + `input_schema`,`{"op":"run","name":"<名>","args":{…}}` 转发给服务。不用在 `skills/` 里建目录。旧字段 `enable` 已废弃,`mode: silent` 已移除(启动会报错并提示改用 `skill`)。
|
||||
|
||||
工具发现只在启动时做一次,因此发现失败后会自动按 **2s / 20s / 1min 重试 3 次**(覆盖 compose 并行拉起与宿主机重启后的容器乱序);成功后工具在下一轮请求即可用,三次都失败则需重启 core。三个 MCP 服务都配了 `/health` 健康检查,`docker ps` 可直接看状态。
|
||||
|
||||
@@ -224,7 +224,7 @@ platforms:
|
||||
通用模型字段:
|
||||
|
||||
- `enable: false`:模型不进池,不参与分配。
|
||||
- `vision: false`:读图时不回传像素,只给文字占位。
|
||||
- `vision: false`:读图时不回传像素,回执只给结构化说明(`reason: no_vision`)。
|
||||
- `profile: <名>`:引用 `model_profiles`,不配则使用默认全量 prompt 与工具。
|
||||
- `reasoning_ack_field`:需要把思考链回传给上游时填写,例如 DeepSeek 系的 `reasoning_content`。
|
||||
|
||||
@@ -263,7 +263,7 @@ platforms:
|
||||
| `terminal` | 执行 shell 命令;默认在会话目录,超时可终止 |
|
||||
| `fetch` | 抓取 HTTP/HTTPS 并转 Markdown;带 SSRF 防护与分段续读 |
|
||||
| `mint_public_link` | 为会话内文件签发短期公网链接 |
|
||||
| `skill` | 技能:`{"list":"all"}` / `{"get":"<名>"}` / `{"run":"<名>","args":{...}}`(动词作键,三选一) |
|
||||
| `skill` | 技能:`op` = `list` / `get` / `run`;`name` 指技能,`args` 传参数 |
|
||||
| `db` | 操作会话本地 `data.db`:`exec`、`query`、`insert`、`tables`、`schema` |
|
||||
| `schedule` | 定时任务 `get` / `list` / `create` / `update` / `delete` |
|
||||
| `profile` | 用户画像 `list` / `set` / `add` / `remove` |
|
||||
@@ -287,7 +287,7 @@ skills/my-skill/
|
||||
```
|
||||
|
||||
- `SKILL.md` 的 `description` 会进入 system prompt,模型启动时就知道有哪些技能。
|
||||
- `input_schema.required` 在 `{"run":"<名>","args":{...}}` 前校验。
|
||||
- `input_schema.required` 在 `op=run` 前校验。
|
||||
- MCP 工具不用建目录:给该服务配 `mode: skill`,平台会自动把它暴露成技能(`get` 返回 MCP 原始的
|
||||
`input_schema`,`run` 转发),见上文「同栈 MCP 服务」。
|
||||
- 入口脚本以绝对路径启动;远端执行时 cwd 是会话目录,本地开发时是技能目录。相对路径参数会先按会话目录转成绝对路径。
|
||||
|
||||
+22
-7
@@ -138,7 +138,19 @@ POST /api/sessions/:id/messages
|
||||
- 含图消息:DB 里存 `{"__blocks__":[...]}` 哨兵 JSON(`encodeBlocks`/`decodeBlocks`);
|
||||
发请求时 `image_ref` 现签公网短链(`mintUrl`,每次请求重签、不会中途过期)。
|
||||
`tool` 回执里的未消费图片会**挪出回执**,合并成该批回执之后的一条 `user` 消息
|
||||
(`tool` 角色带图是非标准形态,很多上游会吞图);已消费的图降级为文字占位。
|
||||
(`tool` 角色带图是非标准形态,很多上游会吞图);已消费的图只省略像素块,回执原样保留。
|
||||
- `read_file` 读图的回执是**结构化 JSON**(`tools/executor.js` 的 `imageReceipt`:`ok` /
|
||||
`image_attached` / `reason` / `width` / `height` …),不是散文。发送侧改写只限两种真事件
|
||||
(engine 同回合/同批去重、`buildMessages` 签外链失败),一律走 `patchImageReceipt` **只改字段**。
|
||||
- **已消费的图重放时只省略像素块,不改写回执**:回执是「那次读取」的历史事实,把当时成功的
|
||||
读图改写成 `image_attached:false` 会让模型以为当时就没拿到画面 → 反复重读同一条(实测循环)。
|
||||
- 图片注入消息的两条硬约束(踩过循环):①**消费判据是「最后一条写过文本的 assistant」**
|
||||
(不要求无 `tool_calls`)——旧判据只认收尾回复,多步任务里图永远「未消费」;②**只有本批新增的图
|
||||
带「一句话说明」的祈使句**,早前批次静默携带。两者合起来才断得掉「每轮要求描述 → 模型描述并继续
|
||||
调工具 → 图仍算未消费」的自维持重复循环。
|
||||
- 重读去重(engine `run.imgDelivered`)**只拦同一批 tool call 内的重复读**(一次请求里塞两份同样的图
|
||||
没意义);跨批次重读一律放行。不要写成「一回合只投递一次」,也不要靠推测「图还在不在上下文里」——
|
||||
模型说拿不到就得给,而且文件可能已重新生成(路径相同、内容不同);拦掉只会把新像素挡在门外。
|
||||
- 占位裁剪(`agent.trim_write_rounds` / `trim_result_rounds`):距尾 ≥N 个 assistant 轮的
|
||||
`write_file.content`、`fetch`/`read_file` 回执换成单行占位。**只改发给上游的副本**,DB 与 UI 不动。
|
||||
- `compressMessages` = `buildMessages` + 末尾一条压缩指令 `user`。**铁律**:压缩请求必须与上一次
|
||||
@@ -165,7 +177,7 @@ POST /api/sessions/:id/messages
|
||||
出现即报配置错(不静默忽略)。
|
||||
- `executeTool(baseCtx, name, args)`:先查 `HANDLERS` 表,未命中再交给 MCP 注册表。
|
||||
`ctx = {sessionId, taskDir, run, cfg, db, vision}`;工具返回字符串,`read_file` 读图时返回
|
||||
`{text, image_rel}`(由 engine 转成 `image_ref` 块)。
|
||||
`{text, image_rel}`(`text` 是结构化 JSON 回执,由 engine 转成 `image_ref` 块)。
|
||||
- **路径沙箱**:所有路径经 `resolveInTask` 解析到 `taskDir` 内;`/tmp` 会被映射到
|
||||
`<taskDir>/.tmp`(与 executor 容器里 `/tmp` 的 bind 对齐)。符号链接越界一律拒绝。
|
||||
- **跨会话只读**:`@<session-id>/<rel>` 只允许 `list_directory`、`read_file`、`copy_path` 的
|
||||
@@ -173,11 +185,14 @@ POST /api/sessions/:id/messages
|
||||
- `checkToolArgs` + `unwrapToolArgs`:前者做结构性预检并生成 `errAck`,后者按 schema 逐层剥掉
|
||||
弱模型多包的信封。两者都是纯函数并已导出,便于回归验证。
|
||||
- 技能(`tools/skills.js`):`SKILL.md` front matter 提供 `description`/`input_schema`。
|
||||
工具参数是「动词作键」:`{"list":"all"}` / `{"get":"<名>"}` / `{"run":"<名>","args":{...}}`,
|
||||
三者恰好给一个(无法用 `required` 表达,校验在 `toolSkill` 里做)。`input_schema.required` 在
|
||||
`run` 前校验;相对路径参数按会话目录转绝对路径;入口一律用绝对路径(远端 cwd 是会话目录)。
|
||||
配了 executor 就走 `remote-exec`,否则本地 `spawn`。旧形状 `{op, name, input_args}` 仅由
|
||||
`toolSkill` 兜底翻译(存量技能文档里还写着它),不再对外文档化。
|
||||
front matter 的 `thinking: true` 会在 `get` 时把 `run.deepThink` 置真(不影响脚本本身);
|
||||
每回合只触发一次,engine 经 SSE `think_auto` 同步前端,开启后保持到用户手动关闭。
|
||||
工具参数是扁平的 `{op, name, args}`:`op` 必填且三选一(`list`/`get`/`run`),`name` 供
|
||||
get/run 指认技能,`args` 仅 run 用;条件必填写不进 schema,由 `toolSkill` 校验并点名。
|
||||
`toolSkill` 在入口把旧字段名 `input_args` 归一化成 `args`,之后只走一条分派路径
|
||||
(曾有两条路径,其中一条只读 `input_args`,会静默丢参)。
|
||||
`input_schema.required` 在 `run` 前校验;相对路径参数按会话目录转绝对路径;入口一律用绝对路径
|
||||
(远端 cwd 是会话目录)。配了 executor 就走 `remote-exec`,否则本地 `spawn`。
|
||||
模型可见的技能清单是 `listCallableSkills`(目录技能 + `mode=skill` 的 MCP 工具,同名时目录胜出);
|
||||
设置页的技能 API 仍只用 `listSkills`(按目录增删改),两者不要混用。
|
||||
mode=skill 的 MCP 技能在 `runSkill` 里位于 `absolutizeArgs` **之前**:直接 `mcp.callTool` 转发
|
||||
|
||||
+41
-18
@@ -2,7 +2,7 @@
|
||||
// 单进程内存模型:JS 单线程 + better-sqlite3 同步 API,不存在跨进程竞争。
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { buildMessages, callModel, encodeBlocks, decodeBlocks, compressMessages, titleMessages, setProfilePrompts } = require('./llm');
|
||||
const { buildMessages, callModel, encodeBlocks, decodeBlocks, compressMessages, titleMessages, setProfilePrompts, patchImageReceipt } = require('./llm');
|
||||
const { executeTool, resolveInTask } = require('./tools/executor');
|
||||
const publicFiles = require('./public-files');
|
||||
const mcp = require('./mcp');
|
||||
@@ -616,8 +616,7 @@ async function runLoopInner(sessionId, run) {
|
||||
}
|
||||
const txt = String(m.content || '');
|
||||
return m.role + (m.tool_calls ? '[calls]' : '')
|
||||
+ (txt.includes('图片数据已省略') ? '[图已省]' : '')
|
||||
+ (txt.includes('本回合已投递过') ? '[图重复读挡回]' : '');
|
||||
+ (txt.includes('"already_delivered"') ? '[图重复读挡回]' : '');
|
||||
}).join(' '));
|
||||
}
|
||||
// 内置工具 + 启动时发现的 MCP 工具(按 profile 白名单过滤),一起随 system prompt 发给模型(压缩回合不发)
|
||||
@@ -763,7 +762,13 @@ async function runLoopInner(sessionId, run) {
|
||||
} else {
|
||||
try {
|
||||
output = await executeTool({ sessionId, taskDir: taskDirOf(sessionId), run, cfg, db, vision,
|
||||
onTaskCreated: () => { run.taskWrap = true; }, onCard: (card) => bus.emit(sessionId, 'ui_card', card) }, // 通用 UI 卡片 → SSE(ctx 由 executeTool 透传给 MCP 与内置工具) // 定时即下班:工具只打标记,收口在 finalize(回合结束后才能解绑归档)
|
||||
onTaskCreated: () => { run.taskWrap = true; }, onCard: (card) => bus.emit(sessionId, 'ui_card', card),
|
||||
onDeepThink: (info) => {
|
||||
const m = (cfg.models || []).find(x => x.id === session.model_id);
|
||||
const supported = !!(m && m.thinking_params && Object.keys(m.thinking_params).length);
|
||||
log.info('skills', sessionId + ' 技能 ' + (info && info.skill) + ' 要求深度思考,本回合自动开启' + (supported ? '' : '(当前模型未配置 thinking_params,不生效)'));
|
||||
bus.emit(sessionId, 'think_auto', { on: true, skill: info && info.skill, supported });
|
||||
} }, // 通用 UI 卡片 → SSE(ctx 由 executeTool 透传给 MCP 与内置工具) // 定时即下班:工具只打标记,收口在 finalize(回合结束后才能解绑归档)
|
||||
|
||||
tc.function.name, chk.args);
|
||||
} catch (err) {
|
||||
@@ -771,31 +776,49 @@ async function runLoopInner(sessionId, run) {
|
||||
isError = true;
|
||||
}
|
||||
}
|
||||
// 工具可返回 {text, image_rel}(read_file 读图且模型支持 vision,压缩产物在 .imgcache/):
|
||||
// 落库时以 image_ref 内容块拼进 tool 消息(哨兵 JSON,见 llm.js encodeBlocks);
|
||||
// buildMessages 发请求前把未消费的图现签成公网外链 image_url 块,并入该批回执之后的
|
||||
// 一条 user 消息发送(tool 角色带图非标准形态,上游支持度差);前端工具卡走带 cookie 的下载路由渲染。
|
||||
// 工具可返回 {text, image_rel}(read_file 读图且模型支持 vision,压缩产物在 .imgcache/,
|
||||
// text 是 imageReceipt 生成的结构化 JSON 回执):落库时以 image_ref 内容块拼进 tool 消息
|
||||
// (哨兵 JSON,见 llm.js encodeBlocks);buildMessages 发请求前把未消费的图现签成公网
|
||||
// 外链 image_url 块,并入该批回执之后的一条 user 消息发送(tool 角色带图非标准形态,
|
||||
// 上游支持度差);前端工具卡走带 cookie 的下载路由渲染。
|
||||
let outText;
|
||||
let imageRel = null;
|
||||
if (output && typeof output === 'object' && output.image_rel) {
|
||||
outText = String(output.text || '');
|
||||
imageRel = String(output.image_rel);
|
||||
if (output && typeof output === 'object' && typeof output.text === 'string') {
|
||||
outText = output.text;
|
||||
if (output.image_rel) imageRel = String(output.image_rel);
|
||||
} else {
|
||||
outText = String(output == null ? '' : output);
|
||||
}
|
||||
if (run.cancelled && !isError) outText = (outText ? outText + '\n' : '') + '(用户已终止任务)';
|
||||
// 死循环护栏:同回合内同一张图只投递一次——上游能认多图(探针实测同消息双外链全对),
|
||||
// 不再按批次限流;但模型若因惯性叙事反复重读同一文件,每轮都签新图就是纯烧 token,
|
||||
// 故已投递过的图再读只回文字提示(run 随回合销毁,新回合自动重置,追问重看不受影响)。
|
||||
// 只拦「同一批 tool call 里重复读同一文件」:一次请求里塞两份完全相同的图没意义。
|
||||
// 跨批次重读一律放行。不按「本回合投递过没有」拦,也不按「图还在不在上下文里」拦:
|
||||
// 前者会把第二次读取永久锁死(实测模型被逼去重新造图);后者靠服务端推测模型看没看到,
|
||||
// 一厢情愿——模型说拿不到就该给。再者文件可能已被重新生成,路径相同内容不同,
|
||||
// 拦掉就是把新像素挡在门外(压缩产物的 rel 含 size+mtime,不同内容自然是不同 rel)。
|
||||
if (imageRel) {
|
||||
if (!run.imgDelivered) run.imgDelivered = new Set();
|
||||
if (run.imgDelivered.has(imageRel)) {
|
||||
outText += '\n[该图片本回合已投递过,不再重复携带;若你未看到它,请直接告知用户,勿反复重读同一文件]';
|
||||
if (!run.imgDelivered) run.imgDelivered = new Map();
|
||||
if (run.imgDelivered.get(imageRel) === iter) {
|
||||
const patched = patchImageReceipt(outText, {
|
||||
image_attached: false, reason: 'already_delivered', retryable: true,
|
||||
hint: '同一批 tool call 里已为这个文件投递过图片,本次不再重复;需要重看时在下一轮再读即可',
|
||||
});
|
||||
outText = patched !== null
|
||||
? patched
|
||||
: outText + '\n[同一批 tool call 里已为这个文件投递过图片,本次不再重复;需要重看时在下一轮再读即可]';
|
||||
imageRel = null;
|
||||
} else {
|
||||
run.imgDelivered.add(imageRel);
|
||||
run.imgDelivered.set(imageRel, iter);
|
||||
}
|
||||
}
|
||||
// 回执自报的「环境故障」也算失败(UI 打 ✕、库里 is_error=true),预期拒绝不算:
|
||||
// no_vision / too_large / past_session / already_delivered / link_unavailable 都是正常答复。
|
||||
// 限定工具名再解析,避免把 db 的大块查询结果白解一遍。
|
||||
if (!isError && tc.function.name === 'read_file' && typeof outText === 'string' && outText.charAt(0) === '{') {
|
||||
try {
|
||||
const o = JSON.parse(outText);
|
||||
if (o && o.kind === 'image' && o.ok === false && (o.reason === 'decode_failed' || o.reason === 'sharp_missing')) isError = true;
|
||||
} catch (_) { /* 非结构化回执(旧格式)不处理 */ }
|
||||
}
|
||||
log.debug('tool', sessionId + ' ' + tc.function.name + (isError ? ' 失败: ' : ' 完成: ') + outText);
|
||||
const toolContent = imageRel
|
||||
? encodeBlocks([
|
||||
|
||||
+93
-35
@@ -114,7 +114,7 @@ function decodeBlocks(content) {
|
||||
// 含图行的解析缓存:哨兵 JSON 带 base64 大字段,工具循环里每个请求都整段 JSON.parse,
|
||||
// 已消费的图片解析完还只留文字块,纯重复劳动。按行 id 把解析结果挂在 session 上:
|
||||
// 单进程内存模型,行内容入库后不再变更,同一行只解析一次。
|
||||
// 缓存的是原始块数组而非「消费后投影」——消费与否仍按 lastAssistant 实时判定,
|
||||
// 缓存的是原始块数组而非「消费后投影」——消费与否仍按 lastAck 实时判定,
|
||||
// 删除后续 assistant 让图片回到「未消费」(需重新携带 base64)时也自然正确。
|
||||
function cachedDecodeBlocks(session, row) {
|
||||
if (typeof row.content !== 'string' || !row.content.startsWith('{"__blocks__":')) return null;
|
||||
@@ -126,22 +126,52 @@ function cachedDecodeBlocks(session, row) {
|
||||
return blocks;
|
||||
}
|
||||
|
||||
// read_file 图片回执是单个 JSON 对象(字段契约见 tools/executor.js 的 imageReceipt)。
|
||||
// 发送侧要改写回执时只动字段,绝不追加句子:拼在 JSON 后面会让整条回执不可解析,
|
||||
// 模型又退回「从自然语言里猜像素到底到没到」。非 JSON / 非图片回执(旧库散文、文本读取正文)
|
||||
// 返回 null,调用方自行回退。
|
||||
function patchImageReceipt(text, patch) {
|
||||
if (typeof text !== 'string' || text.charAt(0) !== '{') return null;
|
||||
let o;
|
||||
try { o = JSON.parse(text); } catch (_) { return null; }
|
||||
if (!o || o.kind !== 'image') return null;
|
||||
return JSON.stringify(Object.assign(o, patch));
|
||||
}
|
||||
// 图片编号标签:从回执字段生成「read_file <path> 1080×1920」,只用于把图与回执对上号。
|
||||
// 旧库散文回执退回首行(历史行照旧可读)。
|
||||
function imageLabel(text) {
|
||||
if (typeof text === 'string' && text.charAt(0) === '{') {
|
||||
try {
|
||||
const o = JSON.parse(text);
|
||||
if (o && o.kind === 'image') return 'read_file ' + (o.path || '') + (o.width && o.height ? ' ' + o.width + '×' + o.height : '');
|
||||
} catch (_) { /* 落到下面按散文取首行 */ }
|
||||
}
|
||||
return (text || 'read_file 图片回传').split('\n')[0];
|
||||
}
|
||||
|
||||
// 将 DB 消息行转为 OpenAI messages 数组(不含 system,由调用方拼接)。
|
||||
// 图片两种形态:旧库/用户粘贴附件的 image_url 块(data: URL)原样透传;
|
||||
// 新版 read_file 读图存的是 image_ref 块({rel},指向任务目录 .imgcache/ 产物)。
|
||||
// tool 回执里的未消费图不放在回执内发送——tool 角色带 image_url 非标准形态,
|
||||
// 大量 OpenAI 兼容上游会整批忽略或只认批次最后一张,模型看不到图却见回执写着
|
||||
// 「已回传」,会反复 read_file 补看(死循环烧 token,见多模态回退复盘);
|
||||
// 故回执降级为纯文本,图块现签成 image_url(mintUrl 公网链回调)后统一并入
|
||||
// 故回执里只留文字(read_file 读图时是一个结构化 JSON 对象,字段见
|
||||
// tools/executor.js 的 imageReceipt;发送侧只改字段、不追加句子),图块现签成
|
||||
// image_url(mintUrl 公网链回调)后统一并入
|
||||
// 该批之后的一条 user 消息(user 角色各家通吃):逐图说明文字全部置顶、图块按回执顺序紧随
|
||||
//(对齐官方示例排布;探针实测 DS 对交替排布也兼容,取低风险形态),
|
||||
// 并附「先逐张简述再继续任务」指令——兼作送达自检,破弱模型的“没收到”惯性叙事;
|
||||
// 并只对本批新增的图附「一句话说明」的自检指令——兼作送达自检,破弱模型的“没收到”
|
||||
// 惯性叙事;早前批次不再重复要求描述(旧版对全部未消费图每轮重发祈使句,驱动了重复循环);
|
||||
// 签不到(base_url 未配等)降级为文字占位,绝不把 image_ref 这种非标准块发上游。
|
||||
// 省 token:图块保留到最后一条「收尾回复」(无 tool_calls 的 assistant)之前;
|
||||
// 中间轮只发 tool_calls 不算看过,图继续携带——14:33 实测 pt 证明图已进上下文而模型
|
||||
// 仍自述没看到(弱模型行为不可靠),行为鲁棒优先于极致省钱;更早的视为已消费,
|
||||
// 之前的视为已消费,发请求时替换为文字标记(措辞不再催促重读)。DB 始终存全量:
|
||||
// UI 历史照常渲染图片,模型如需重看可再次 read_file(新回执在尾部,会重新携带图片)。
|
||||
// 省 token:图块保留到「最后一次写过文本的 assistant」之前——模型把图片描述写在 content
|
||||
// 里、同时继续发 tool_calls,就是它确实看到像素的证据。旧判据只认「无 tool_calls 的收尾
|
||||
// 回复」,于正常的多步任务(工具轮不停)里图永远算未消费,每轮都把「逐张简述…然后继续
|
||||
// 完成用户的任务」重发一遍,模型照做又产生 tool_calls——自我维持的重复循环(2026-10 实机:
|
||||
// 同一批图被反复描述直到人工终止)。没写任何文本的中间轮仍算「没看过」,图继续随请求
|
||||
// 携带(14:33 实测:图已进上下文而模型仍自述没看到,行为鲁棒优先于极致省钱)。
|
||||
// DB 始终存全量:UI 历史照常渲染图片,模型如需重看可再次 read_file(新回执在尾部)。
|
||||
// 重放时只省略像素块、**不改写回执字段**:回执是历史事实,改写成「未投递」会让模型
|
||||
// 把当时成功的读图误判为失败,进而反复重读同一条(2026-10 实机循环的直接成因)。
|
||||
// 压缩摘要相关行(见 engine.runLoopInner / summarizeContext):
|
||||
// - type='summary'(assistant,收尾答复):不跳过。它是压缩后后续轮次的上下文起点,
|
||||
// 正常以 assistant 历史行发给模型;压缩收尾时打此标。
|
||||
@@ -190,14 +220,23 @@ function buildMessages(session, language, mintUrl, profile, withProfile, trimOn)
|
||||
// tool 回执按 tool_call_id 索引:给 errAck 行拼错误提示时取执行时挡下的原因
|
||||
const toolRowById = new Map();
|
||||
for (const row of history) if (row.role === 'tool' && row.tool_call_id) toolRowById.set(row.tool_call_id, row);
|
||||
// 「已消费」分界 = 最后一条给出收尾回复(无 tool_calls)的 assistant:模型只发
|
||||
// tool_calls 的中间轮不算已阅图,图继续随请求携带直到它真正答复过一次。
|
||||
// 「已消费」分界 = 最后一条**写过文本**的 assistant 行(不要求无 tool_calls):
|
||||
// 描述写在 content 里 + 继续调工具,就是模型真看到图的证据(见文件头注释的循环复盘)。
|
||||
// errAck / archived 不发模型,不算回复:它们之前的图不算被消费。
|
||||
let lastAssistant = -1;
|
||||
let lastAck = -1;
|
||||
for (let i = history.length - 1; i >= 0; i--) {
|
||||
const r = history[i];
|
||||
if (r.role === 'assistant' && r.type !== 'errAck' && r.type !== 'archived' && !r.tool_calls) { lastAssistant = i; break; }
|
||||
if (r.role !== 'assistant' || r.type === 'errAck' || r.type === 'archived') continue;
|
||||
if (String(r.content || '').trim()) { lastAck = i; break; }
|
||||
}
|
||||
// 「本批新增」起点 = 最后一条 assistant 行之后的 tool 回执(engine 每轮把新回执行追加在末尾)。
|
||||
// 只有这些图带「请描述」的祈使句;更早批次仍未消费的图只静默携带,否则模型每轮都被
|
||||
// 要求重述一遍旧图,进而把旧任务再推一遍。
|
||||
let lastAssistantRow = -1;
|
||||
for (let i = history.length - 1; i >= 0; i--) {
|
||||
if (history[i].role === 'assistant') { lastAssistantRow = i; break; }
|
||||
}
|
||||
const newFrom = lastAssistantRow + 1;
|
||||
const dropToolCallIds = new Set();
|
||||
// 旧版 summarize_request 「已答复」判定的前置信息:最后一次「回合收尾回复」(无 tool_calls 的 assistant)的位置。
|
||||
// 指令行在其之后 = 还在等 AI 响应这条指令(旧版压缩回合未收尾),应发给模型;在其之前 = 旧指令,跳过防污染。
|
||||
@@ -212,6 +251,7 @@ function buildMessages(session, language, mintUrl, profile, withProfile, trimOn)
|
||||
const pendingImages = []; // 待投递的图块(按回执顺序;签不到时不占位)
|
||||
const pendingLabels = []; // 每图一行「对应回执」说明,合并进首条文字块(text 置顶、图在后)
|
||||
let imgSeq = 0;
|
||||
let newCount = 0; // 其中本批新增的图数:为 0 时不带「请描述」的祈使句
|
||||
history.forEach((row, i) => {
|
||||
// archived:UI 可见,但不进入模型上下文(节省 token)
|
||||
if (row.type === 'archived') return;
|
||||
@@ -266,29 +306,42 @@ function buildMessages(session, language, mintUrl, profile, withProfile, trimOn)
|
||||
const blocks = cachedDecodeBlocks(session, row);
|
||||
let content = row.content || '';
|
||||
if (blocks) {
|
||||
if (i < lastAssistant) {
|
||||
content = blocks.filter(b => b && b.type === 'text').map(b => b.text).join('\n') +
|
||||
'\n[图片数据已省略:本图已随上一条回执发送过,不再重复携带;若你当时未能识别其内容,请直接告知用户,勿反复重读同一文件]';
|
||||
if (i < lastAck) {
|
||||
// 已消费的图重放时**只省略像素,不改写回执**:回执记的是「那次读取发生了什么」
|
||||
//(当时确实投递了);「这次重放不重复发」只是传输细节,不该写进历史事实。
|
||||
// 若改写成 image_attached:false / reason:omitted_already_sent / retryable:false,
|
||||
// 模型会把历史读图当成失败、认为「这次没拿到画面」,于是反复重读同一条(实测循环)。
|
||||
// 确实需要重看时它自己再 read_file 即可,那条新回执会是完整的成功回执。
|
||||
content = blocks.filter(b => b && b.type === 'text').map(b => b.text).join('\n');
|
||||
} else if (row.role === 'tool') {
|
||||
// 未消费的图:回执只留文字,图块挪进批次后的 user 合并消息(见 pendingImages/Labels)
|
||||
const texts = blocks.filter(b => b && b.type === 'text').map(b => b.text);
|
||||
content = texts.join('\n');
|
||||
const label = (texts[0] || 'read_file 图片回传').split('\n')[0];
|
||||
const label = imageLabel(texts[0]);
|
||||
const isNew = i >= newFrom;
|
||||
let mintFailed = false;
|
||||
for (const b of blocks) {
|
||||
if (!b || (b.type !== 'image_ref' && b.type !== 'image_url')) continue;
|
||||
const seq = ++imgSeq;
|
||||
if (b.type === 'image_url') { // 旧库内联 data: URL 原样
|
||||
pendingLabels.push('[图片 ' + seq + '] ' + label);
|
||||
pendingImages.push(b);
|
||||
continue;
|
||||
}
|
||||
let block = b;
|
||||
if (b.type === 'image_ref') {
|
||||
const url = mintUrl ? mintUrl(b.rel) : null;
|
||||
if (url) {
|
||||
pendingLabels.push('[图片 ' + seq + '] ' + label);
|
||||
pendingImages.push({ type: 'image_url', image_url: { url } });
|
||||
} else {
|
||||
pendingLabels.push('[图片 ' + seq + '] ' + label + '(外链不可用,未取得像素:请直接告知用户,勿反复重读同一文件)');
|
||||
if (!url) { mintFailed = true; continue; } // 签不到就不占编号:没图可描述
|
||||
block = { type: 'image_url', image_url: { url } };
|
||||
}
|
||||
const seq = ++imgSeq;
|
||||
if (isNew) newCount++;
|
||||
pendingImages.push(block);
|
||||
pendingLabels.push('[图片 ' + seq + ']' + (isNew ? '(本批新增)' : '') + ' ' + label
|
||||
+ (isNew ? '' : '(早前批次,已投递过,不要重复描述)'));
|
||||
}
|
||||
// 签不到外链 = 本次请求像素确实到不了:当场把回执字段降级,让模型拿到的是
|
||||
// 「ok 但 image_attached=false + reason」,而不是一句需要它自己解读的说明。
|
||||
if (mintFailed) {
|
||||
const degraded = patchImageReceipt(content, {
|
||||
image_attached: false, reason: 'link_unavailable', retryable: false,
|
||||
hint: '服务端签不出图片外链,本张图的像素未能随本次请求送达;重读也无法送达,请直接告知用户',
|
||||
});
|
||||
if (degraded !== null) content = degraded;
|
||||
}
|
||||
} else {
|
||||
// user 行(粘贴附件/旧形态):image_url 块(data: URL)原样;image_ref → 现签公网外链
|
||||
@@ -307,16 +360,21 @@ function buildMessages(session, language, mintUrl, profile, withProfile, trimOn)
|
||||
messages.push({ role: row.role, content });
|
||||
}
|
||||
});
|
||||
// 该批未消费图片合并发送:单条 text 置顶列出逐图对应说明,图块按编号顺序紧随;
|
||||
// 「先简述每张图再继续」兼作送达自检——模型描述得出来 = 像素真到了;描述不出 = 真没到,
|
||||
// 不会再像 14:33 那样带着图却沿“没收到”的叙事惯性重读。
|
||||
if (pendingImages.length || pendingLabels.length) {
|
||||
// 未消费图片合并发送:图上文字置顶、图块紧随(同序)。
|
||||
// 只有「本批新增」的图才能带祈使句——旧版对所有未消费图每轮都写「逐张简述…然后
|
||||
// 继续完成用户的任务」,模型把它当成新的用户任务,描述完继续干活→又产生 tool_calls→
|
||||
// 图仍算未消费→再要求描述,自维持重复。早前批次只静默携带并明确「不要重复描述」。
|
||||
if (pendingImages.length) {
|
||||
const tail = newCount
|
||||
? '\n标注「本批新增」的图片是本轮新投递的:各用一句话说明里面有什么(确认像素已收到),'
|
||||
+ '然后继续你手头的工具流程。本条不是新的用户任务,不要在这里展开分析。'
|
||||
: '\n以上均为早前批次已投递过的图片(像素仍在上下文中):不要重复描述,专注完成用户的任务。';
|
||||
messages.push({
|
||||
role: 'user',
|
||||
content: [{ type: 'text',
|
||||
text: '[系统提示] 以下不是用户新输入,是上面这批 tool 回执对应的图片(read_file 回传):\n'
|
||||
text: '[系统提示] 以下不是用户新输入,是你此前 read_file 回传的图片(按回执顺序):\n'
|
||||
+ pendingLabels.join('\n')
|
||||
+ (pendingImages.length ? '\n请按编号顺序逐张简述每张图片里有什么(表明像素确实送达),然后继续完成用户的任务。' : '') }]
|
||||
+ tail }]
|
||||
.concat(pendingImages),
|
||||
});
|
||||
}
|
||||
@@ -328,7 +386,7 @@ function buildMessages(session, language, mintUrl, profile, withProfile, trimOn)
|
||||
// 页面可重抓;write 参数只是当时快照(后续 edit_file 一次就失真,本就不该被当现势引用)。
|
||||
// 组装请求时对「距尾 ≥N 个 assistant 轮」的行换单行占位:纯函数、DB 不动(UI 工具卡照旧
|
||||
// 可展全量)、与压缩归档正交(archived 行本来就不进模型)。距离按现存行数 assistant 轮:
|
||||
// 删中间消息可让已占位行短暂复活全文(一次性断前缀缓存,与图片消费 i<lastAssistant 同一
|
||||
// 删中间消息可让已占位行短暂复活全文(一次性断前缀缓存,与图片消费 i<lastAck 同一
|
||||
// 语义,接受)。阈值可配(config agent.trim_write_rounds / trim_result_rounds,0=关),
|
||||
// 启动时 setPayloadTrim 注入。
|
||||
let TRIM = { writeRounds: 1, resultRounds: 2 };
|
||||
@@ -646,4 +704,4 @@ async function callModel(cfg, modelId, messages, tools, options) {
|
||||
return { content, reasoning, tool_calls: Array.from(toolCalls.values()), finish_reason: finishReason, usage, aborted, sseFrames };
|
||||
}
|
||||
|
||||
module.exports = { callModel, buildMessages, buildSystemPrompt, systemPromptText, setSkillListText, setPayloadTrim, setProfilePrompts, encodeBlocks, decodeBlocks, compressMessages, titleMessages };
|
||||
module.exports = { callModel, buildMessages, buildSystemPrompt, systemPromptText, setSkillListText, setPayloadTrim, setProfilePrompts, encodeBlocks, decodeBlocks, compressMessages, titleMessages, patchImageReceipt };
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
// ---------- 输入区 ----------
|
||||
const ta = $('msg-input');
|
||||
function autosize() { ta.style.height = 'auto'; ta.style.height = Math.min(ta.scrollHeight, 120) + 'px'; }
|
||||
ta.addEventListener('input', autosize);
|
||||
// 输入内容变化直接影响发送键两态:运行中一旦有字就恢复「发送」(可插话),清空后又变回「停止」
|
||||
ta.addEventListener('input', () => { autosize(); updateSendBtn(); });
|
||||
// 触屏设备(手机/平板)上:Enter 走默认行为(插入 \n),发消息靠发送按钮,
|
||||
// 避免软键盘的回车键直接被吞走导致连换行都打不出来。桌面/笔记本继续走 Enter=发送。
|
||||
// 用 (hover:none)&&(pointer:coarse) 判定「以触摸为主」的设备,标准且不依赖 UA 字符串。
|
||||
@@ -29,11 +30,12 @@
|
||||
send();
|
||||
}
|
||||
});
|
||||
// 发送键双职:生成中变「停止」(白色方块),点击终止当前回合;否则正常发送。
|
||||
// 发送键双职:生成中且输入框为空时变「停止」(白色方块),点击终止当前回合;
|
||||
// 输入框有字时它仍是「发送」——运行中允许插话,直接发出去(后端 live 追投)。
|
||||
// 400ms 内重复点击忽略:防双击重复 abort(服务端 status 事件回来前按钮仍是停止态)。
|
||||
let stopClickAt = 0;
|
||||
$('send-btn').addEventListener('click', () => {
|
||||
if (state.status === 'active') {
|
||||
if (stopModeActive()) {
|
||||
if (Date.now() - stopClickAt < 400) return;
|
||||
stopClickAt = Date.now();
|
||||
stopSession();
|
||||
|
||||
@@ -15,7 +15,8 @@ const PV_PLAIN = /\.(txt|log)$/i;
|
||||
const PV_TEXT = /\.(md|markdown|txt|log|csv|tsv|json|jsonl|xml|yml|yaml|toml|ini|conf|cfg|properties|env|py|pyw|js|mjs|cjs|ts|tsx|jsx|java|kt|c|h|cpp|hpp|cc|cs|go|rs|rb|php|swift|sh|bash|zsh|bat|ps1|sql|lua|r|dart|vue|css|less|scss|srt|vtt)$/i;
|
||||
const PV_TEXT_MAX = 512 * 1024; // 文本预览截断阈值(字符),超出提示下载看全文
|
||||
let pvSeq = 0; // 预览序号:快速连点时旧请求不许再动 DOM
|
||||
const pvState = { name: null, url: null, blobUrl: null, drawerWasOpen: false, mobilePush: false };
|
||||
// reload: 当前内容的"重新载入"动作(文本类无 iframe,按名重开);为 null 时回退到 reload iframe
|
||||
const pvState = { name: null, url: null, blobUrl: null, reload: null, drawerWasOpen: false, mobilePush: false };
|
||||
|
||||
function pvDesktop() { return window.matchMedia('(min-width: 960px)').matches; }
|
||||
|
||||
@@ -34,9 +35,15 @@ function pvKind(name) {
|
||||
return 'none';
|
||||
}
|
||||
|
||||
// 刷新/新窗口两个钮对**所有**预览类型统一开放:
|
||||
// refresh → pvState.reload(各类型都注入「按同一路径重开」,与地址条回车同一条路)
|
||||
// popup → pvState.url(office=预览网关;文本/HTML/图片/PDF=blob URL;不支持的类型=下载地址)
|
||||
// 服务端文件响应一律是 attachment,直接导航只会触发下载,所以能用 blob 的一律走 blob。
|
||||
function pvToolbar(o) {
|
||||
document.getElementById('pv-refresh').classList.toggle('hidden', !o.refresh);
|
||||
document.getElementById('pv-popup').classList.toggle('hidden', !o.popup);
|
||||
pvState.reload = typeof o.reload === 'function' ? o.reload : null;
|
||||
pvState.url = o.url === undefined ? null : o.url;
|
||||
}
|
||||
|
||||
// 每次展示内容都过一遍:标题显示相对路径(子目录可见),右上角下载钮随文件走
|
||||
@@ -50,6 +57,8 @@ function pvHeader(name, sizeText) {
|
||||
|
||||
function pvClearBody() {
|
||||
document.getElementById('pv-body').innerHTML = '';
|
||||
pvState.reload = null; // 换内容/关窗后旧的刷新动作立即失效
|
||||
pvState.url = null; // 新窗口地址同理:不清会残留上一份内容的 blob/网关 URL
|
||||
if (pvState.blobUrl) { try { URL.revokeObjectURL(pvState.blobUrl); } catch (_) {} pvState.blobUrl = null; }
|
||||
}
|
||||
|
||||
@@ -114,7 +123,7 @@ async function pvOpenOffice(name, sizeText) {
|
||||
let load;
|
||||
if (desk) {
|
||||
pvOpenPane(); pvClearBody();
|
||||
pvHeader(name, sizeText); pvToolbar({ refresh: true, popup: false });
|
||||
pvHeader(name, sizeText); pvToolbar({ refresh: true, popup: true, reload: () => openFilePreview(name, sizeText), url });
|
||||
load = pvLoadingBox();
|
||||
document.getElementById('pv-body').appendChild(load); // 开窗即刻可见,冷启动转圈等首帧
|
||||
} else {
|
||||
@@ -128,15 +137,19 @@ async function pvOpenOffice(name, sizeText) {
|
||||
const missing = head && head.status === 404;
|
||||
if (missing) {
|
||||
const node = pvInfoNode(name, sizeText, '预览服务中暂无这份文档 —— 只有 AI 在本任务中生成/编辑过的文档才能在线预览(较旧的文档可能已被自动清理)。');
|
||||
if (desk) { pvClearBody(); document.getElementById('pv-body').appendChild(node); }
|
||||
else { const b = document.getElementById('fs-body'); b.innerHTML = ''; b.appendChild(node); }
|
||||
if (desk) {
|
||||
// pvClearBody 会清掉 reload/url:占位卡仍要保留刷新/新窗口,否则按钮可见但点了没反应
|
||||
pvClearBody(); document.getElementById('pv-body').appendChild(node);
|
||||
const dl = '/api/sessions/' + encodeURIComponent(state.sessionId) + '/files/download?path=' + encodeURIComponent(name);
|
||||
pvToolbar({ refresh: true, popup: true, reload: () => openFilePreview(name, sizeText), url: dl });
|
||||
} else { const b = document.getElementById('fs-body'); b.innerHTML = ''; b.appendChild(node); }
|
||||
return;
|
||||
}
|
||||
const fr = document.createElement('iframe');
|
||||
fr.className = desk ? 'pv-frame' : 'fs-html-frame';
|
||||
fr.title = String(name);
|
||||
fr.src = url;
|
||||
if (desk) { try { load.remove(); } catch (_) {} document.getElementById('pv-body').appendChild(fr); pvToolbar({ refresh: true, popup: true }); }
|
||||
if (desk) { try { load.remove(); } catch (_) {} document.getElementById('pv-body').appendChild(fr); pvToolbar({ refresh: true, popup: true, reload: () => openFilePreview(name, sizeText), url }); }
|
||||
else { const b = document.getElementById('fs-body'); b.innerHTML = ''; b.appendChild(fr); }
|
||||
pvState.url = url;
|
||||
}
|
||||
@@ -149,9 +162,15 @@ async function openFilePreview(name, sizeText) {
|
||||
if (kind === 'pdf' && !navigator.pdfViewerEnabled) kind = 'none'; // WebView 内嵌不了 PDF:给占位卡,不再自动下载
|
||||
const desk = pvDesktop();
|
||||
const my = ++pvSeq;
|
||||
// 工具栏两动作全局统一:刷新 = 按同一路径重开(与地址条回车同一条路),
|
||||
// 新窗口 = 打开当前内容;没有可打开的 URL 时(不支持预览/读失败)退回下载地址。
|
||||
const reload = () => openFilePreview(name, sizeText);
|
||||
const downloadUrl = '/api/sessions/' + encodeURIComponent(state.sessionId) + '/files/download?path=' + encodeURIComponent(name);
|
||||
const tbAll = { refresh: true, popup: true, reload, url: downloadUrl };
|
||||
if (desk) {
|
||||
pvOpenPane(); pvClearBody(); // 立即开窗 + 转圈,点击零延迟可见
|
||||
pvHeader(name, sizeText); pvToolbar({ refresh: false, popup: false });
|
||||
pvHeader(name, sizeText);
|
||||
pvToolbar(tbAll);
|
||||
document.getElementById('pv-body').appendChild(pvLoadingBox());
|
||||
}
|
||||
const show = (node, tb) => {
|
||||
@@ -159,7 +178,7 @@ async function openFilePreview(name, sizeText) {
|
||||
if (desk) {
|
||||
pvClearBody(); pvHeader(name, sizeText);
|
||||
document.getElementById('pv-body').appendChild(node);
|
||||
if (tb) pvToolbar(tb);
|
||||
pvToolbar(tb || tbAll);
|
||||
} else pvOverlayShow(node);
|
||||
};
|
||||
if (kind === 'none') {
|
||||
@@ -167,7 +186,7 @@ async function openFilePreview(name, sizeText) {
|
||||
const hint = /\.pdf$/i.test(low)
|
||||
? '当前浏览器不支持页内预览 PDF,请下载后用系统查看器打开。'
|
||||
: '该格式暂不支持在线预览,可下载后本地打开。';
|
||||
show(pvInfoNode(name, sizeText, hint), { refresh: false, popup: false });
|
||||
show(pvInfoNode(name, sizeText, hint), tbAll);
|
||||
return;
|
||||
}
|
||||
let r;
|
||||
@@ -176,38 +195,44 @@ async function openFilePreview(name, sizeText) {
|
||||
if (r.status === 401) { if (my === pvSeq) location.href = '/login?next=' + encodeURIComponent(location.pathname + location.search); return; }
|
||||
if (!r.ok) { let msg = 'HTTP ' + r.status; try { msg = (await r.json()).error || msg; } catch (_) {} throw new Error(msg); }
|
||||
} catch (e) {
|
||||
if (my === pvSeq) { desk ? show(pvInfoNode(name, sizeText, '读取失败:' + e.message), { refresh: false, popup: false }) : (pvCloseOverlayQuiet(), toast('预览失败:' + e.message)); }
|
||||
if (my === pvSeq) { desk ? show(pvInfoNode(name, sizeText, '读取失败:' + e.message), tbAll) : (pvCloseOverlayQuiet(), toast('预览失败:' + e.message)); }
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (!desk) { await pvRenderLegacy(name, r, my); return; }
|
||||
let node = null, tb = { refresh: false, popup: false };
|
||||
let node = null, tb = tbAll;
|
||||
// blob URL 不能在此登记到 pvState:show() 内部先调 pvClearBody(),那会把"刚建的"这个也一并撤销,
|
||||
// 于是 img/iframe 真正去取时 URL 已失效(Chrome 报 net::ERR_FILE_NOT_FOUND;Safari 撤回更宽松才没暴露)。
|
||||
// 统一等 show() 之后登记,陈旧序号则立即撤销防泄漏。
|
||||
let newBlobUrl = null;
|
||||
if (kind === 'html') {
|
||||
const src = rewriteHtmlDocSrcs(await r.text(), name); // 相对资源改写,否则 about:srcdoc/blob 基准下全 404
|
||||
const fr = document.createElement('iframe');
|
||||
fr.className = 'pv-frame';
|
||||
fr.setAttribute('sandbox', 'allow-same-origin allow-scripts');
|
||||
fr.srcdoc = rewriteHtmlDocSrcs(await r.text(), name); // 相对资源改写,否则 about:srcdoc 基准下全 404
|
||||
fr.srcdoc = src;
|
||||
newBlobUrl = URL.createObjectURL(new Blob([src], { type: 'text/html;charset=utf-8' }));
|
||||
tb = Object.assign({}, tbAll, { url: newBlobUrl }); // 新窗口=改写后的页面(与面板里同一份)
|
||||
node = fr;
|
||||
} else if (kind === 'pdf') {
|
||||
const u = URL.createObjectURL(await r.blob());
|
||||
newBlobUrl = u;
|
||||
const fr = document.createElement('iframe');
|
||||
fr.className = 'pv-frame'; fr.title = String(name); fr.src = u; // 不加 sandbox:内建查看器插件需要 unrestricted 帧
|
||||
node = fr; tb = { refresh: false, popup: true };
|
||||
node = fr; tb = Object.assign({}, tbAll, { url: u });
|
||||
} else if (kind === 'img') {
|
||||
const u = URL.createObjectURL(await r.blob());
|
||||
newBlobUrl = u;
|
||||
const im = document.createElement('img');
|
||||
im.className = 'pv-img'; im.src = u; im.alt = String(name);
|
||||
im.addEventListener('click', () => openImageViewer(u, String(name).split('/').pop()));
|
||||
node = im; tb = { refresh: false, popup: true };
|
||||
node = im; tb = Object.assign({}, tbAll, { url: u });
|
||||
} else { // text/md/代码/json/csv
|
||||
node = await pvTextNode(name, sizeText, r);
|
||||
if (node.__tb) { tb = node.__tb; delete node.__tb; }
|
||||
if (node.__tb) {
|
||||
tb = Object.assign({}, tbAll, node.__tb); delete node.__tb;
|
||||
if (/^blob:/.test(tb.url || '')) newBlobUrl = tb.url;
|
||||
}
|
||||
}
|
||||
show(node, tb);
|
||||
if (newBlobUrl) {
|
||||
@@ -215,11 +240,30 @@ async function openFilePreview(name, sizeText) {
|
||||
else { try { URL.revokeObjectURL(newBlobUrl); } catch (_) {} }
|
||||
}
|
||||
} catch (e) {
|
||||
if (my === pvSeq) desk ? show(pvInfoNode(name, sizeText, '预览失败:' + e.message), { refresh: false, popup: false }) : toast('预览失败:' + e.message);
|
||||
if (my === pvSeq) desk ? show(pvInfoNode(name, sizeText, '预览失败:' + e.message), tbAll) : toast('预览失败:' + e.message);
|
||||
}
|
||||
}
|
||||
function pvCloseOverlayQuiet() { const fs = document.getElementById('fs-viewer'); if (!fs.classList.contains('hidden') && fs.querySelector('.pv-loading')) closeFullscreen(); }
|
||||
|
||||
// 文本类「新窗口」承载:md 用面板同一份渲染 HTML(图片已改写成绝对下载地址),
|
||||
// 其余按 text/plain 原样打开——服务端文件响应一律 attachment,直接导航只会触发下载。
|
||||
// md 里原样透传的 <script> 在面板(innerHTML)本就不执行,但 blob 文档会执行,故先剔除以保持一致。
|
||||
function pvMdDoc(html, name) {
|
||||
const css =
|
||||
'body{margin:0;padding:24px 32px 48px;max-width:900px;font:15px/1.7 -apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;color:#1f2328;background:#fff}' +
|
||||
'img{max-width:100%;height:auto}pre{background:#f6f8fa;padding:12px 14px;border-radius:8px;overflow:auto}' +
|
||||
'code{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:.92em}' +
|
||||
'table{border-collapse:collapse}th,td{border:1px solid #d8dee4;padding:6px 10px}' +
|
||||
'blockquote{margin:0;padding:0 14px;color:#57606a;border-left:3px solid #d8dee4}' +
|
||||
'a{color:#0969da}';
|
||||
const title = esc(String(name || '').split('/').pop() || '预览');
|
||||
return '<!DOCTYPE html><html><head><meta charset="utf-8">' +
|
||||
'<meta name="viewport" content="width=device-width,initial-scale=1">' +
|
||||
'<title>' + title + '</title><style>' + css + '</style></head><body>' +
|
||||
html.replace(/<script\b[\s\S]*?(?:<\/script\s*>|$)/gi, '') + '</body></html>';
|
||||
}
|
||||
function pvTextUrl(text) { return URL.createObjectURL(new Blob([text], { type: 'text/plain;charset=utf-8' })); }
|
||||
|
||||
// 桌面文本渲染:md 走气泡 markdown;txt/log 原文排版;代码/配置/数据等宽 pre;二进制嗅探回退占位卡
|
||||
async function pvTextNode(name, sizeText, r) {
|
||||
const text = await r.text();
|
||||
@@ -234,14 +278,18 @@ async function pvTextNode(name, sizeText, r) {
|
||||
wrap.className = 'msg other';
|
||||
wrap.innerHTML = '<div class="' + cls + ' pv-doc">' + html + '</div>';
|
||||
decorateCodePre(wrap);
|
||||
const n = wrap.firstChild; n.__tb = { refresh: false, popup: false };
|
||||
const n = wrap.firstChild;
|
||||
// q.fmt=false 表示 marked 不可用、面板就是原文排版:新窗口也按纯文本开,避免空白被折叠
|
||||
n.__tb = q.fmt
|
||||
? { popup: true, url: URL.createObjectURL(new Blob([pvMdDoc(html, name)], { type: 'text/html;charset=utf-8' })) }
|
||||
: { popup: true, url: pvTextUrl(text) };
|
||||
return n;
|
||||
}
|
||||
if (PV_PLAIN.test(low)) {
|
||||
const wrap = document.createElement('div');
|
||||
wrap.className = 'msg other';
|
||||
wrap.innerHTML = '<div class="bubble-ai pv-doc">' + esc(text) + '</div>';
|
||||
const n = wrap.firstChild; n.__tb = { refresh: false, popup: false };
|
||||
const n = wrap.firstChild; n.__tb = { popup: true, url: pvTextUrl(text) };
|
||||
return n;
|
||||
}
|
||||
const frag = document.createDocumentFragment();
|
||||
@@ -260,7 +308,7 @@ async function pvTextNode(name, sizeText, r) {
|
||||
const holder = document.createElement('div');
|
||||
holder.className = 'pv-plain';
|
||||
holder.appendChild(frag);
|
||||
holder.__tb = { refresh: false, popup: false };
|
||||
holder.__tb = { popup: true, url: pvTextUrl(text) }; // 新窗口用全文,不受面板截断影响
|
||||
return holder;
|
||||
}
|
||||
|
||||
@@ -326,6 +374,7 @@ document.getElementById('pv-max').addEventListener('click', () => {
|
||||
pvSetMaxUI(max);
|
||||
});
|
||||
document.getElementById('pv-refresh').addEventListener('click', () => {
|
||||
if (typeof pvState.reload === 'function') { pvState.reload(); return; }
|
||||
const f = document.getElementById('pv-body').querySelector('iframe');
|
||||
if (!f) return;
|
||||
try { f.contentWindow.location.reload(); } catch (_) { const s = f.src; f.src = ''; f.src = s; }
|
||||
|
||||
@@ -290,6 +290,21 @@
|
||||
return state.sessionId ? (state.modelId || '') : (state.pendingModel || '');
|
||||
}
|
||||
|
||||
// 发送键两态:只有「正在生成且输入框为空」才是停止。一开始输入文字就恢复发送——
|
||||
// 运行中允许插话(后端 postUserMessage 返回 delivered:'live',下一轮迭代会带上这条消息)。
|
||||
// 输入框按 trim 判空:纯空白等同于空(与 send() 的裁剪一致,不能因为一个空格就发不了消息)。
|
||||
function stopModeActive() {
|
||||
return state.status === 'active' && !(($('msg-input') || {}).value || '').trim();
|
||||
}
|
||||
function updateSendBtn() {
|
||||
const sb = $('send-btn');
|
||||
if (!sb) return;
|
||||
const stop = stopModeActive();
|
||||
sb.dataset.state = stop ? 'stop' : 'send';
|
||||
sb.title = stop ? '停止生成' : '发送';
|
||||
sb.setAttribute('aria-label', stop ? '停止生成' : '发送');
|
||||
}
|
||||
|
||||
function updateHeaderActions() {
|
||||
const inChat = state.view === 'chat' && !!state.sessionId;
|
||||
const running = state.status === 'active';
|
||||
@@ -341,12 +356,8 @@
|
||||
ssub.classList.toggle('hidden', !t);
|
||||
}
|
||||
// 发送键在生成中切「停止」:同一按钮换图标,尺寸不变,输入区不跳动
|
||||
const sb = $('send-btn');
|
||||
if (sb) {
|
||||
sb.dataset.state = running ? 'stop' : 'send';
|
||||
sb.title = running ? '停止生成' : '发送';
|
||||
sb.setAttribute('aria-label', running ? '停止生成' : '发送');
|
||||
}
|
||||
// (是否真的显示停止还取决于输入框是否有字,见 stopModeActive)
|
||||
updateSendBtn();
|
||||
}
|
||||
|
||||
function openHeaderMenu() {
|
||||
|
||||
@@ -11,10 +11,9 @@
|
||||
|
||||
async function send() {
|
||||
const ta = $('msg-input');
|
||||
// 生成中发送键已变「停止」:不接受新消息(不做排队发送,停止后再发)
|
||||
if (state.status === 'active') { toast('正在生成中,请先停止'); return; }
|
||||
const content = ta.value.trim();
|
||||
// 没有文字就不发(避免产生空消息);上传文件告知行在发送时拼在正文前(见下)。
|
||||
// 运行中也是这条规则:有字就发(后端 live 追投),没字时按钮本身是「停止」。
|
||||
if (!content) {
|
||||
if (state.attachments.length) toast('附件需随一条文字消息发送');
|
||||
return;
|
||||
@@ -25,6 +24,7 @@
|
||||
renderAttachChips();
|
||||
ta.value = '';
|
||||
autosize();
|
||||
updateSendBtn(); // 清空后若仍在生成中,按钮应回到「停止」
|
||||
|
||||
try {
|
||||
const id = await ensureSession();
|
||||
@@ -46,7 +46,9 @@
|
||||
state.sessionTitle = content.length > 24 ? content.slice(0, 24) : content;
|
||||
}
|
||||
renderHeader();
|
||||
addTyping();
|
||||
// 运行中插话:正文字流进行中已有一个气泡作「活着」的信号,不再挂打字占位
|
||||
//(刚挂上就会被下一个 delta 移除,只会闪一下);工具间隙里补上占位反而有用。
|
||||
if (!state.streaming) addTyping();
|
||||
loadSessionList();
|
||||
} catch (e) {
|
||||
// 发送失败:附件还原+草稿文本回填(发送前已清空输入框,挂起/失败不能让文字蒸发),
|
||||
@@ -56,6 +58,7 @@
|
||||
if (content) {
|
||||
ta.value = content + (ta.value ? '\n' + ta.value : '');
|
||||
autosize();
|
||||
updateSendBtn(); // 文字回填了:按钮回到「发送」(即使仍在生成中)
|
||||
}
|
||||
toast('发送失败:' + e.message);
|
||||
}
|
||||
@@ -136,7 +139,7 @@
|
||||
state.lastSseAt = Date.now(); // 建连即重置静默计时
|
||||
// 任何具名事件都算连接存活:静默看门狗与回前台宽限共用(error 不列,原生连接错误也走 error)
|
||||
['ping', 'status', 'assistant_delta', 'reasoning_delta', 'assistant_message', 'tool_call_start',
|
||||
'tool_call_args', 'tool_call', 'tool_result', 'ui_card', 'auto_compress', 'done', 'title']
|
||||
'tool_call_args', 'tool_call', 'tool_result', 'ui_card', 'auto_compress', 'done', 'title', 'think_auto']
|
||||
.forEach(function (n) { es.addEventListener(n, function () { markSseAlive(n); }); });
|
||||
es.addEventListener('status', ev => {
|
||||
const d = JSON.parse(ev.data);
|
||||
@@ -146,6 +149,17 @@
|
||||
updateHeaderActions();
|
||||
updateScrollBottomBtn(); // 状态切换同步右下角转圈(开始/结束干活)
|
||||
});
|
||||
es.addEventListener('think_auto', ev => {
|
||||
const d = JSON.parse(ev.data);
|
||||
if (!d.supported) {
|
||||
toast('当前模型未配置思考参数,技能 ' + d.skill + ' 的深度思考要求无法生效');
|
||||
return;
|
||||
}
|
||||
if (state.deepThink) return;
|
||||
state.deepThink = true;
|
||||
$('deep-think-btn').classList.add('on');
|
||||
toast('技能 ' + d.skill + ' 需要深度思考,已自动开启');
|
||||
});
|
||||
es.addEventListener('assistant_delta', ev => {
|
||||
const d = JSON.parse(ev.data);
|
||||
removeTyping();
|
||||
|
||||
@@ -77,7 +77,7 @@ function absInSkill(dir, rel) {
|
||||
// 技能发生任何变更(创建/重命名/删除/文件增删改都经过本模块)后,
|
||||
// 重建 system prompt 的 “可用技能” 段落(llm.setSkillListText):
|
||||
// 模型立即感知新技能或改名,无需重启。fire-and-forget:扫描失败不影响 API 响应,
|
||||
// skill {"list":"all"} 仍是实时兜底。
|
||||
// skill op=list 仍是实时兜底。
|
||||
function refreshSkillPrompt() {
|
||||
listCallableSkills({ cfg: engine.getConfig() })
|
||||
.then(list => llm.setSkillListText(formatSkillListForPrompt(list)))
|
||||
|
||||
@@ -178,8 +178,8 @@ function dumpPromptBundle() {
|
||||
// 启动时先发现各 MCP 服务的工具(单个服务失败只警告,不阻止启动),
|
||||
// 并对技能列表做快照(注入 system prompt,见 llm.setSkillListText),完成后开始监听。
|
||||
mcp.init(cfg).then(async () => {
|
||||
// 技能列表快照:模型直接感知已有技能,免先 {"list":"all"} 探索;
|
||||
// 此处失败不阻塞启动,{"list":"all"} 仍可做实时兜底。
|
||||
// 技能列表快照:模型直接感知已有技能,免先 op=list 探索;
|
||||
// 此处失败不阻塞启动,op=list 仍可做实时兜底。
|
||||
try {
|
||||
const list = await skills.listCallableSkills({ cfg });
|
||||
llm.setSkillListText(skills.formatSkillListForPrompt(list));
|
||||
|
||||
@@ -11,12 +11,14 @@ You are a file / data / information processing assistant. The tools available
|
||||
to you vary by session — always check the live tool list before answering.
|
||||
|
||||
In scope: understanding images (describe, OCR, read charts); deterministic image
|
||||
operations (format conversion, resize, crop, watermark); charts and diagrams
|
||||
operations (format conversion, resize, crop, watermark); generative image
|
||||
creation and editing when an image skill/tool is available; charts and diagrams
|
||||
from data; document processing and conversion (PDF / Markdown / Word / Excel /
|
||||
PowerPoint); data processing; running scripts and commands; fetching and
|
||||
summarizing web information; audio/video transcoding and basic editing;
|
||||
generative media when a tool for it is present in the current session (read that
|
||||
tool's own description for its capabilities and limits); SQLite operations.
|
||||
generative media when a tool or skill for it is present in the current session
|
||||
(read that tool's or skill's own description for its capabilities and limits);
|
||||
SQLite operations.
|
||||
|
||||
Out of scope: capabilities no available tool exposes in this session. Do not
|
||||
fake results — no placeholder files, no claiming a file was created, no crude
|
||||
@@ -65,7 +67,8 @@ When the user asks for something that seems out of scope:
|
||||
scope — do not hand-write scripts to accomplish what a required skill already
|
||||
does. For other skills, prefer them when they match the task.
|
||||
- `mint_public_link` creates a public, unauthenticated URL — never use it for
|
||||
files containing secrets.
|
||||
files containing secrets. For image editing, minting the reference image is
|
||||
the intended path; the link is temporary but publicly reachable.
|
||||
|
||||
{APP_SKILLS_SECTION}
|
||||
|
||||
@@ -92,8 +95,10 @@ When the user asks for something that seems out of scope:
|
||||
carry state across calls.
|
||||
- Python 3.11 is available; the system Python and its packages are read-only.
|
||||
To add packages, create a virtualenv inside the working directory
|
||||
(`python3 -m venv .venv`, then `.venv/bin/pip` and `.venv/bin/python`). Keep
|
||||
it in the working directory, not `/tmp`.
|
||||
(`python3 -m venv --system-site-packages .venv`, then `.venv/bin/pip` and `.venv/bin/python`).
|
||||
Keep it in the working directory, not `/tmp`.
|
||||
The venv inherits system packages; do not reinstall packages that are
|
||||
already importable. Only install what is missing.
|
||||
- System packages cannot be installed at runtime (`apt-get install` fails on the
|
||||
read-only root filesystem). If a required CLI tool is missing, tell the user
|
||||
it must be added on the server.
|
||||
|
||||
@@ -219,7 +219,7 @@
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "read_file",
|
||||
"description": "Reads the content of a file.\n\nText files: each returned line is prefixed with a line number right-aligned in a 6-character field, followed by a tab, then the line content.\n\nCross-session peek: `path` accepts '@<session-id>/<rel>' to read a text file from your OWN past session, read-only (find the id with recall op=search, browse with list_directory). It is a look, not an import: nothing lands in your session directory, so `terminal`, grep and `edit_file` cannot see it, and past images are refused. When you need to work with a file or view a past image, `copy_path` it first (its `source_path` takes the same '@' form). '@' is never accepted by `write_file` or `edit_file`.\n\nLarge text files (roughly over 16 KB) are not returned in full: you get an outline listing top-level symbols (or Markdown headings) with line numbers instead. The outline IS a successful response — do NOT retry the same call without a line range; use the outline line numbers with `start_line` / `end_line` to read specific sections. If no outline can be extracted, a first-1KB excerpt is returned instead. Supplying `start_line` or `end_line` disables outline mode.\n\nImage files (PNG, JPEG, WebP, GIF, BMP, TIFF) are returned as visual content you can analyze directly, but only if the current model supports vision; otherwise a text placeholder is returned — that placeholder is not an error. The tool result itself carries a text notice only; the actual image pixels arrive in a separate user message right after the batch of tool results: that message lists per-image labels matching each image to its read_file receipt, then the image blocks in receipt order, and asks you to briefly describe each image before continuing. Never re-read an image already delivered in the current turn; if pixels never arrive, tell the user instead of retrying. Very large images (roughly over 50 MB) are skipped, and images may be downscaled (long edge ~2000 px, re-encoded as JPEG) before being returned.\n\nBinary files are not returned as text; a short notice is returned instead. Text files over 32 MB cannot be read by this tool — use `terminal` (grep -n / head / sed -n).",
|
||||
"description": "Reads the content of a file.\n\nText files: each returned line is prefixed with a line number right-aligned in a 6-character field, followed by a tab, then the line content.\n\nCross-session peek: `path` accepts '@<session-id>/<rel>' to read a text file from your OWN past session, read-only (find the id with recall op=search, browse with list_directory). It is a look, not an import: nothing lands in your session directory, so `terminal`, grep and `edit_file` cannot see it, and past images are refused. When you need to work with a file or view a past image, `copy_path` it first (its `source_path` takes the same '@' form). '@' is never accepted by `write_file` or `edit_file`.\n\nLarge text files (roughly over 16 KB) are not returned in full: you get an outline listing top-level symbols (or Markdown headings) with line numbers instead. The outline IS a successful response — do NOT retry the same call without a line range; use the outline line numbers with `start_line` / `end_line` to read specific sections. If no outline can be extracted, a first-1KB excerpt is returned instead. Supplying `start_line` or `end_line` disables outline mode.\n\nImage files (PNG, JPEG, WebP, GIF, BMP, TIFF): the receipt is a single JSON object, not prose — read its fields instead of interpreting the text. Success shape: {\"ok\":true,\"tool\":\"read_file\",\"kind\":\"image\",\"path\":\"...\",\"image_attached\":true,\"width\":1080,\"height\":1920,\"format\":\"jpeg\",\"bytes_in\":3550000,\"bytes_out\":210000,\"resized\":true,\"source_width\":4000,\"source_height\":7111}. `width`/`height` are the delivered pixel size; `source_width`/`source_height` appear only when the image was downscaled. `image_attached:true` means the server produced the image and it will arrive as an image block in the separate user message that immediately follows the batch of tool results; that message labels each image `[图片 N] read_file <path> <w>×<h>` and asks you to describe it before continuing. The tool result itself never carries pixels. Refusal or failure shape: {\"ok\":false,\"kind\":\"image\",\"path\":\"...\",\"image_attached\":false,\"reason\":\"...\",\"retryable\":false,\"hint\":\"...\"} where `reason` is one of no_vision (this model cannot see images), too_large (roughly over 50 MB), past_session (import it with copy_path first), decode_failed, sharp_missing, already_delivered (this same image was already delivered by an earlier call in the SAME batch of tool calls, so this duplicate was not attached again — reading it again in a later batch always delivers the current pixels, which may have changed since), link_unavailable (no public URL could be minted, so the pixels did not arrive for that request). `ok:true` with `image_attached:false` is still a successful call, e.g. a deduplicated re-read. When `retryable` is false do not retry — tell the user instead. Images may be downscaled (long edge ~2000 px, re-encoded as JPEG) before delivery.\n\nBinary files are not returned as text; a short notice is returned instead. Text files over 32 MB cannot be read by this tool — use `terminal` (grep -n / head / sed -n).",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
@@ -337,25 +337,23 @@
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "skill",
|
||||
"description": "Run or inspect the skills installed on this server. A skill is a directory under the skill root whose SKILL.md defines its purpose and input_schema.\n\nPass EXACTLY ONE verb key:\n{\"list\":\"all\"} List every installed skill with a one-line description, read live from the skill root; an empty list is not an error.\n{\"get\":\"<name>\"} Return the skill's full raw SKILL.md (front matter included): purpose, input_schema and usage notes. Call it before run for a skill you have not used in this conversation.\n{\"run\":\"<name>\",\"args\":{...}} Execute the skill; args are key/value pairs matching its input_schema, and may be omitted for skills that take none.\n\nrun returns the skill's combined stdout+stderr as plain text after it exits (exit 0 with no output yields '(无输出)'); a non-zero exit raises an error containing the output and [exit code: N]. Relative paths in args are resolved against the session working directory, so pass output paths explicitly and never rely on the skill's cwd. Default timeout 120 seconds: the process group is killed and the error includes partial output collected so far (a timeout is not a skill failure).",
|
||||
"description": "Run or inspect the skills installed on this server. Each skill describes its purpose and input_schema.\n\n{\"op\":\"list\"} list every skill with a one-line description\n{\"op\":\"get\",\"name\":\"<skill>\"} return the skill's full details; call it before the first run\n{\"op\":\"run\",\"name\":\"<skill>\",\"args\":{...}} execute it; args follow its input_schema\n\nop is required. op=get and op=run require name. Put skill arguments inside args, never at the top level.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"required": ["op"],
|
||||
"properties": {
|
||||
"list": {
|
||||
"op": {
|
||||
"type": "string",
|
||||
"description": "Scope of the listing. The only scope today is \"all\" (every installed skill)."
|
||||
"enum": ["list", "get", "run"],
|
||||
"description": "Operation to perform on skills."
|
||||
},
|
||||
"get": {
|
||||
"name": {
|
||||
"type": "string",
|
||||
"description": "Skill name (subdirectory name under the skill root): return its SKILL.md."
|
||||
},
|
||||
"run": {
|
||||
"type": "string",
|
||||
"description": "Skill name: execute it with args."
|
||||
"description": "Skill name. Required with op=get and op=run."
|
||||
},
|
||||
"args": {
|
||||
"type": "object",
|
||||
"description": "Only with run: the skill's input arguments, e.g. {\"input\": \"file.md\", \"output\": \"out.pdf\"}. Omit it for skills that take no arguments."
|
||||
"description": "Only with op=run: the skill's input arguments, e.g. {\"input\":\"a.md\",\"output\":\"b.pdf\"}. Omit for skills that take no arguments."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+120
-78
@@ -129,6 +129,9 @@ const IMAGE_EXTS = new Set(['.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp', '.
|
||||
// read_file 读图(仅当会话绑定的模型 vision: true):sharp 压缩后落盘到任务目录 .imgcache/,
|
||||
// 返回 {text, image_rel};engine 拼成 image_ref 内容块落库,llm.buildMessages 发请求前
|
||||
// 现签成公网外链(GET /p/<id>)进 image_url 块,base64 不再进 DB/请求体。
|
||||
// text 一律是 imageReceipt 生成的 JSON 对象(字段契约见下),不是散文:
|
||||
// 这份回执会被三层改写(executor 产出 / engine 同回合去重 / llm 签外链失败降级),
|
||||
// 散文回执让模型只能靠语义猜「到底有没有图」,历史事故是反复 read_file 补看烧 token。
|
||||
const IMG_MAX_INPUT_BYTES = 50 * 1024 * 1024; // 与上传上限一致
|
||||
const IMG_MAX_SIDE = 2000; // 长边压缩阈值(px)
|
||||
const IMG_JPEG_QUALITY = 80;
|
||||
@@ -178,14 +181,51 @@ function outlineWrapper(outlineText) {
|
||||
'For example, to read a function shown as [L100-150], use start_line: 100 and end_line: 150.';
|
||||
}
|
||||
|
||||
// read_file 图片回执的统一信封。字段是模型唯一可判定的事实,回执不再写中文句子:
|
||||
// ok 调用本身是否成功(ok=true + image_attached=false 是合法形态:同回合重复读被去重)
|
||||
// path 模型请求的路径(@ 历史形原样保留);投递产物路径只在服务端内部用,不回执
|
||||
// image_attached 服务端是否产出了图块、会随本批回执之后的那条 user 消息投递(≠上游已收到)
|
||||
// reason 仅 image_attached=false 时有值,稳定枚举(no_vision / too_large / past_session /
|
||||
// decode_failed / sharp_missing / already_delivered / link_unavailable)——
|
||||
// 模型按它分支,不要读 hint 猜。注意:重放省略像素不属于回执事件,不写 reason。
|
||||
// retryable 重试同一调用是否有意义(图片这条路上恒 false:同样的字节只会得到同样的结果)
|
||||
// width/height 实际投递的像素尺寸;source_width/height + resized 只在确实缩放过时出现
|
||||
// hint 一句人话补充,仅供解释,不承载判定
|
||||
function imageReceipt(o) {
|
||||
const out = { ok: o.ok === true, tool: 'read_file', kind: 'image', path: o.path, image_attached: o.image_attached === true };
|
||||
for (const k of ['reason', 'retryable', 'width', 'height', 'format', 'bytes_in', 'bytes_out',
|
||||
'resized', 'source_width', 'source_height', 'hint']) {
|
||||
if (o[k] !== undefined) out[k] = o[k];
|
||||
}
|
||||
return JSON.stringify(out);
|
||||
}
|
||||
|
||||
// 用 sharp 压缩(按 EXIF 摆正、长边 ≤2000px、JPEG 质量 80)并落盘 .imgcache/。
|
||||
// 成功返回 {text, image_rel};产物文件名带源文件指纹(mtime+size),同图重复读复用同一份不增殖。
|
||||
// 成功返回 {text, image_rel},失败返回 {text}(text 都是 imageReceipt 的 JSON)。
|
||||
// 产物文件名带源文件指纹(mtime+size),同图重复读复用同一份不增殖。
|
||||
// 无收益守卫(与浏览器端压缩同款):重编码 JPEG 反而 ≥ 原图时不落盘,image_rel 直指原文件。
|
||||
// sharp 缺失或解码失败时退回纯文本提示,不让整个工具回合报错。
|
||||
// sharp 缺失或解码失败时只回执原因,不让整个工具回合报错。
|
||||
async function readImageAsBlocks(ctx, abs, rel, size) {
|
||||
let sharp;
|
||||
try { sharp = require('sharp'); }
|
||||
catch (_) { return '[图片文件] ' + rel + '(' + size + ' 字节)。服务端未安装 sharp,无法压缩回传图片内容。'; }
|
||||
catch (_) {
|
||||
return {
|
||||
text: imageReceipt({
|
||||
ok: false, path: rel, image_attached: false, reason: 'sharp_missing', retryable: false, bytes_in: size,
|
||||
hint: '服务端未安装 sharp,无法压缩回传图片内容',
|
||||
}),
|
||||
};
|
||||
}
|
||||
// 源尺寸只读文件头(metadata 不解码像素);EXIF orientation 5-8 表示显示时旋转 90°,
|
||||
// 宽高要交换才与模型最终看到的画面一致(sharp 的 rotate() 会真的转)。
|
||||
let src = null;
|
||||
try {
|
||||
const m = await sharp(abs).metadata();
|
||||
if (m && m.width && m.height) {
|
||||
const swap = Number(m.orientation) >= 5;
|
||||
src = { w: swap ? m.height : m.width, h: swap ? m.width : m.height, format: m.format || null };
|
||||
}
|
||||
} catch (_) { src = null; }
|
||||
try {
|
||||
const r = await sharp(abs)
|
||||
.rotate()
|
||||
@@ -195,7 +235,13 @@ async function readImageAsBlocks(ctx, abs, rel, size) {
|
||||
if (r.data.length >= size) {
|
||||
// 低内容熵图(截图/线稿/纯色)JPEG 重编码可能比原图还大:不产出缓存,外链直接指向原文件
|
||||
return {
|
||||
text: '[图片文件] ' + rel + '(' + size + ' 字节,压缩无收益,按原图回传)',
|
||||
text: imageReceipt({
|
||||
ok: true, path: rel, image_attached: true,
|
||||
width: src ? src.w : undefined, height: src ? src.h : undefined,
|
||||
format: src && src.format ? src.format : undefined,
|
||||
bytes_in: size, bytes_out: size, resized: false,
|
||||
hint: '压缩无收益,按原图回传',
|
||||
}),
|
||||
image_rel: rel,
|
||||
};
|
||||
}
|
||||
@@ -208,13 +254,21 @@ async function readImageAsBlocks(ctx, abs, rel, size) {
|
||||
await fsp.mkdir(path.dirname(outAbs), { recursive: true });
|
||||
await fsp.writeFile(outAbs, r.data);
|
||||
}
|
||||
return {
|
||||
text: '[图片文件] ' + rel + '(原 ' + size + ' 字节,已压缩为 ' + r.info.width + '×' + r.info.height +
|
||||
' JPEG ' + r.data.length + ' 字节)',
|
||||
image_rel: cacheRel,
|
||||
const receipt = {
|
||||
ok: true, path: rel, image_attached: true,
|
||||
width: r.info.width, height: r.info.height, format: 'jpeg',
|
||||
bytes_in: size, bytes_out: r.data.length,
|
||||
resized: src ? (r.info.width !== src.w || r.info.height !== src.h) : undefined,
|
||||
};
|
||||
if (src) { receipt.source_width = src.w; receipt.source_height = src.h; }
|
||||
return { text: imageReceipt(receipt), image_rel: cacheRel };
|
||||
} catch (err) {
|
||||
return '[图片文件] ' + rel + '(' + size + ' 字节),图片解码/压缩失败:' + (err && err.message || err);
|
||||
return {
|
||||
text: imageReceipt({
|
||||
ok: false, path: rel, image_attached: false, reason: 'decode_failed', retryable: false, bytes_in: size,
|
||||
hint: '图片解码/压缩失败:' + (err && err.message || err),
|
||||
}),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -244,15 +298,29 @@ async function toolReadFile(ctx, args) {
|
||||
// 不做「偷偷复制」:图片要出现在模型视野里,字节必须落到本会话才能签外链(engine 的
|
||||
// mintImageUrl 与前端下载路由都以当前 taskDir 为根),那本质已是一次导入——与其藏进
|
||||
// .imgcache 不进文件表,不如让模型明确知道历史图片必须先 copy_path。
|
||||
return '[图片文件] ' + disp + '(' + st.size + ' 字节)历史会话图片不支持直接读取。' +
|
||||
'图片需要先 copy_path(source_path 用这个 @ 路径)导入本会话,再 read_file——导入后图片、terminal、mint 全量生效。';
|
||||
return {
|
||||
text: imageReceipt({
|
||||
ok: false, path: disp, image_attached: false, reason: 'past_session', retryable: false, bytes_in: st.size,
|
||||
hint: '历史会话图片不支持直接读取:先 copy_path(source_path 用这个 @ 路径)导入本会话,再 read_file——导入后图片、terminal、mint 全量生效',
|
||||
}),
|
||||
};
|
||||
}
|
||||
const rel = relOf(ctx.taskDir, abs);
|
||||
if (!ctx.vision) {
|
||||
return '[图片文件] ' + rel + '(' + st.size + ' 字节)。图片文件,当前模型不支持视觉识别,无法回传图片内容。';
|
||||
return {
|
||||
text: imageReceipt({
|
||||
ok: false, path: rel, image_attached: false, reason: 'no_vision', retryable: false, bytes_in: st.size,
|
||||
hint: '当前模型不支持视觉识别,无法回传图片像素;请基于文件名/大小作答,或直接告知用户',
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (st.size > IMG_MAX_INPUT_BYTES) {
|
||||
return '[图片文件] ' + rel + '(' + st.size + ' 字节)过大(上限 ' + IMG_MAX_INPUT_BYTES + ' 字节),已跳过回传。';
|
||||
return {
|
||||
text: imageReceipt({
|
||||
ok: false, path: rel, image_attached: false, reason: 'too_large', retryable: false, bytes_in: st.size,
|
||||
hint: '超过回传上限 ' + IMG_MAX_INPUT_BYTES + ' 字节;可先用 terminal 缩小(如 ImageMagick)再读',
|
||||
}),
|
||||
};
|
||||
}
|
||||
return await readImageAsBlocks(ctx, abs, rel, st.size);
|
||||
}
|
||||
@@ -1498,18 +1566,14 @@ function toolDb(ctx, args) {
|
||||
}
|
||||
}
|
||||
|
||||
// skill:技能三件套(list/get/run)合并后的单工具(依据 docs/tool-design.md §一)。
|
||||
// 参数形状是「动词作键、技能名作值」,三者恰好给一个:
|
||||
// {list:"all"} / {get:"<名>"} / {run:"<名>", args:{...}}
|
||||
// list 的值是范围而非布尔:将来技能分类落地时直接扩成 {list:"<分类>"},调用形状不变,
|
||||
// 模型不用学第二套写法。今天只认 "all" 且报错点名——静默返回全部会让错拼的分类名
|
||||
// 看起来「能用」,将来接分类时更难排查。
|
||||
// {list:"all"} 的清单 = 目录技能 + mode=skill 的 MCP 工具;get/run 对两者一视同仁:
|
||||
// 目录技能读 SKILL.md,MCP 技能直接回注册表里的原始 input_schema。
|
||||
// args 仅 run 用且可缺省:runSkill 把 null 视作 {},真正缺哪些字段由各技能 input_schema
|
||||
// 校验点名报错(工具层再 gate 一层是双重门槛,无益)。
|
||||
// 旧形状 {op, name, input_args} 仍接受:存量技能文档的调用示例里写的是它,模型 get 到
|
||||
// 旧示例就会照着发;仅作兼容兜底,不再对外文档化(文档只体现新形状)。
|
||||
// skill:技能三件套(list/get/run)合并后的单工具(依据 docs/tool-design.md §一/§二/§三)。
|
||||
// 扁平参数:op 是唯一必填的开关,name 供 get/run 指认技能,args 仅 run 用;条件必填写不进
|
||||
// schema,由 toolSkill 校验并在报错里点名(§四/§五)。
|
||||
// 旧字段名 input_args 在入口归一化成 args(存量技能文档里仍写着它),之后只走一条分派路径——
|
||||
// 曾有两条执行路径,其中一条只读 input_args,{op:"run", args:{...}} 的参数会被静默丢弃。
|
||||
// 上一版「动词作键」不再兼容:schema 的 required:["op"] 会在 checkToolArgs 阶段先拦下,
|
||||
// 留着分支只会是死代码(lab 直调除外,不值得为它多一条路径)。
|
||||
// op=list 的清单取 listCallableSkills:目录技能 + mode=skill 的 MCP 工具;get/run 对两者一视同仁。
|
||||
// visit_url(front matter 可选):页面产物类技能声明访问路径模板,run 成功后在本层拼
|
||||
// public_link.base_url(与 mint_public_link 同源)追加完整「访问地址」——技能进程跑在
|
||||
// executor 隔离视图里不知道公网前缀,AI 拿到相对路径就会原样转给用户,而相对路径打不开。
|
||||
@@ -1531,67 +1595,44 @@ async function runSkillWithVisit(ctx, name, inputArgs) {
|
||||
: rel + '(站内路径:public_link.base_url 未配置,拼不出公网前缀)');
|
||||
}
|
||||
|
||||
const SKILL_USAGE = 'skill 用法:{"list":"all"} / {"get":"<技能名>"} / {"run":"<技能名>","args":{...}},三者恰好给一个';
|
||||
|
||||
// 技能名必须是单 token:它要原样塞进 {run:"<名>"} 的值里,空格与等号会让日志与
|
||||
// 报错里的表达产生歧义('/' 与 '..' 由 skills.skillDir 拦下)。
|
||||
function skillNameArg(value, verb) {
|
||||
if (typeof value !== 'string' || !value.trim()) {
|
||||
throw new Error('skill ' + verb + ' 需要一个技能名字符串,收到:' + JSON.stringify(value).slice(0, 60) + '。' + SKILL_USAGE);
|
||||
}
|
||||
const name = value.trim();
|
||||
if (/[\s=]/.test(name)) throw new Error('技能名不能含空格或等号:"' + name + '"');
|
||||
return name;
|
||||
}
|
||||
const SKILL_USAGE = 'skill 用法:{"op":"list"} / {"op":"get","name":"<技能名>"} / {"op":"run","name":"<技能名>","args":{...}}';
|
||||
|
||||
// list/get 带非空 args 一律报错而不是静默丢弃:否则模型会以为参数生效了。
|
||||
function rejectSkillArgs(a, verb) {
|
||||
if (!a.args || typeof a.args !== 'object' || !Object.keys(a.args).length) return;
|
||||
throw new Error(verb + ' 不接受 args,只有 run 才带参数。' + SKILL_USAGE);
|
||||
}
|
||||
|
||||
// 旧形状 {op, name, input_args} 的等价翻译(兼容存量技能文档,见上方注释)。
|
||||
async function legacyToolSkill(ctx, a) {
|
||||
const op = String(a.op == null ? '' : a.op).trim().toLowerCase();
|
||||
const name = String(a.name == null ? '' : a.name).trim();
|
||||
switch (op) {
|
||||
case 'list':
|
||||
return JSON.stringify(await skills.listCallableSkills(ctx), null, 2);
|
||||
case 'get':
|
||||
if (!name) throw new Error('op=get 缺少技能名。' + SKILL_USAGE);
|
||||
return skills.getSkillInfo(ctx, name);
|
||||
case 'run':
|
||||
if (!name) throw new Error('op=run 缺少技能名。' + SKILL_USAGE);
|
||||
return runSkillWithVisit(ctx, name, a.input_args);
|
||||
default:
|
||||
throw new Error('未知的 op:"' + op + '"。' + SKILL_USAGE);
|
||||
}
|
||||
function rejectSkillArgs(skillArgs, op) {
|
||||
if (!skillArgs || typeof skillArgs !== 'object' || !Object.keys(skillArgs).length) return;
|
||||
throw new Error('op=' + op + ' 不接受 args,只有 op=run 才带参数。' + SKILL_USAGE);
|
||||
}
|
||||
|
||||
// 旧字段名 input_args 在这里归一化成 args,再走同一条分派(见上方注释)。
|
||||
async function toolSkill(ctx, args) {
|
||||
const a = args || {};
|
||||
const verbs = ['list', 'get', 'run'].filter(k => a[k] !== undefined && a[k] !== null && a[k] !== false);
|
||||
if (!verbs.length) {
|
||||
// 三个动词键都没给时才回落到旧形状:两种都给时以新形状为准。
|
||||
if (a.op !== undefined || a.name !== undefined || a.input_args !== undefined) return legacyToolSkill(ctx, a);
|
||||
throw new Error(SKILL_USAGE);
|
||||
}
|
||||
if (verbs.length > 1) {
|
||||
throw new Error('skill 一次只能给一个动词键,收到 ' + verbs.join(' + ') + '。' + SKILL_USAGE);
|
||||
}
|
||||
const verb = verbs[0];
|
||||
if (verb === 'list') {
|
||||
const scope = String(a.list).trim().toLowerCase();
|
||||
if (scope !== 'all') throw new Error('list 目前只支持 "all"(技能分类尚未提供),收到:"' + scope + '"');
|
||||
rejectSkillArgs(a, 'list');
|
||||
const op = String(a.op == null ? '' : a.op).trim().toLowerCase();
|
||||
const name = String(a.name == null ? '' : a.name).trim();
|
||||
const skillArgs = a.args !== undefined ? a.args : a.input_args;
|
||||
if (!op) throw new Error('skill 缺少必填参数 op(list / get / run)。' + SKILL_USAGE);
|
||||
switch (op) {
|
||||
case 'list':
|
||||
rejectSkillArgs(skillArgs, 'list');
|
||||
return JSON.stringify(await skills.listCallableSkills(ctx), null, 2);
|
||||
case 'get': {
|
||||
if (!name) throw new Error('op=get 缺少必填参数 name。' + SKILL_USAGE);
|
||||
rejectSkillArgs(skillArgs, 'get');
|
||||
const info = await skills.getSkillInfo(ctx, name);
|
||||
if (ctx.run && !ctx.run.deepThink && skills.parseFrontMatter(info).thinking === true) {
|
||||
ctx.run.deepThink = true;
|
||||
if (!ctx.run.thinkAuto) {
|
||||
ctx.run.thinkAuto = true;
|
||||
if (typeof ctx.onDeepThink === 'function') ctx.onDeepThink({ skill: name });
|
||||
}
|
||||
const name = skillNameArg(a[verb], verb);
|
||||
if (verb === 'get') {
|
||||
rejectSkillArgs(a, 'get');
|
||||
return skills.getSkillInfo(ctx, name);
|
||||
}
|
||||
return runSkillWithVisit(ctx, name, a.args);
|
||||
return info;
|
||||
}
|
||||
case 'run':
|
||||
if (!name) throw new Error('op=run 缺少必填参数 name。' + SKILL_USAGE);
|
||||
return runSkillWithVisit(ctx, name, skillArgs);
|
||||
default:
|
||||
throw new Error('未知的 op:' + JSON.stringify(op) + '。' + SKILL_USAGE);
|
||||
}
|
||||
}
|
||||
|
||||
// lab:全工具统一入口(元工具,tools 数组收缩到 1 个仍可达内置 + MCP 全部能力)。
|
||||
@@ -1696,7 +1737,8 @@ const HANDLERS = {
|
||||
};
|
||||
|
||||
// ctx: {sessionId, taskDir, run, cfg, db, vision}
|
||||
// 返回值一般为字符串;read_file 读图且 ctx.vision 为 true 时返回 {text, image_rel}。
|
||||
// 返回值一般为字符串;read_file 读图时返回 {text, image_rel},text 是结构化 JSON 回执
|
||||
// (见 imageReceipt),image_rel 缺省表示本次不投递像素。
|
||||
// 内置工具优先;未命中时交给 MCP 注册表(启动时发现的服务工具)。
|
||||
async function executeTool(baseCtx, name, args) {
|
||||
const handler = HANDLERS[name];
|
||||
|
||||
+15
-3
@@ -25,9 +25,8 @@
|
||||
- 跨 op 共享的参数放顶层,description 说明哪些 op 用它;
|
||||
- op 专属参数也放顶层,description 说明 `op=X 时必填`;
|
||||
- 仅当参数结构在工具定义时无法确定时,才用自由对象 `{ "type": "object" }`。
|
||||
- 动词 + 单 token 标识可以折叠成「动词作键、标识作值」(技能的 `{"get":"<名>"}` 即此形)。
|
||||
多个动词互斥时 `required` 表达不了,必须在代码里校验,并在报错里回显全部合法形态;
|
||||
取值范围暂只有一个时(如 `{"list":"all"}`)仍用字符串而非布尔,便于后续扩成分类等子集。
|
||||
- 互斥的多动作一律用枚举开关 `op` + 各自顶层参数,不要把动作编码进键名:键名方案无法用
|
||||
`required` 约束(漏键只能到运行时才发现),弱模型也更容易漏写。
|
||||
|
||||
### 四、条件必填
|
||||
|
||||
@@ -66,3 +65,16 @@ system prompt 不重复 schema 已表达的内容。
|
||||
### 八、上下文成本
|
||||
|
||||
tools 数组每轮请求完整重发。新工具进来时,先问"能不能装进已有工具",再问"要不要新建"。
|
||||
|
||||
### 九、回执形态
|
||||
|
||||
- **内容型**工具(`read_file` 的文本、`fetch` 的正文、`db` 的查询结果)回执就是内容本身,不要套 JSON 信封。
|
||||
- **结果型**动作(读图、裁剪、转换)回执用**单个 JSON 对象**,把判定写进字段,不写自然语言:模型按字段分支,
|
||||
不要再让它从句子里猜。字段名跨工具保持一致:`ok`(调用是否成功)/ `reason`(稳定枚举)/ `retryable` /
|
||||
`width` `height` 之类的事实字段 / `hint`(仅解释,不承载判定)。
|
||||
- 回执可能被多层改写(发送前裁剪、同回合去重、投递失败降级):改写**只动字段**,不得在 JSON 后追加句子——
|
||||
追加会把回执变成不可解析的尾巴,等于把判定权又还给语义猜测。
|
||||
- **回执是「那次调用」的历史事实,不是当前状态**:发送侧为了省 token 省略内容时,不要改写回执
|
||||
(典型错例:把当时成功的图片投递改写成 `image_attached:false`)。模型会把历史读图当成失败,
|
||||
于是反复重读同一条;省略、重放、缓存这类传输层细节不属于回执语义。
|
||||
- `ok:true` 不等于「结果已送达」:另有字段(如 `image_attached`)描述投递状态,两者不要混成一个布尔。
|
||||
|
||||
+6
-5
@@ -5,7 +5,7 @@
|
||||
| 目录 | 容器名 | 作用 | 容器内端口 | MCP 端点 |
|
||||
|---|---|---|---|---|
|
||||
| `web_search/` | `mcp_web_search` | 免费网页搜索(Parallel / Exa,无需 key) | `3000` | `POST /` |
|
||||
| `image_task/` | `mcp_image_task` | 智谱 CogView 图片生成(单工具 op=create) | `3000` | `POST /mcp` |
|
||||
| `image_task/` | `mcp_image_task` | 图片生成 / 编辑(智谱原生或任意 OpenAI 兼容 `/images/generations`,单工具 op=create/get) | `3000` | `POST /mcp` |
|
||||
| `video_task/` | `mcp_video_task` | 智谱 CogVideo 视频生成(异步,单工具 op=create/get) | `3000` | `POST /mcp` |
|
||||
|
||||
**这些服务一个宿主机端口都不占**——它们只挂在 `agent-mcp-net` 上,由 `agent-core` / `agent-executor`
|
||||
@@ -37,9 +37,10 @@ mcp_servers:
|
||||
|
||||
> 从旧的「agent + mcp 双仓库」部署升级:先在旧 mcp 仓库目录 `docker compose down`(只需一次,否则同名容器与网络会冲突),再 `up` 本栈。
|
||||
|
||||
`image_task` / `video_task` 需要智谱 token,但 token **不由服务端保存**——每个请求从 header 读取
|
||||
(agent 侧配在 `config.yml` 的 `mcp_servers[].headers`,`init.sh` 会用 `BIGMODEL_KEY` 自动写入)。
|
||||
所以这里不用配任何密钥。
|
||||
`image_task` / `video_task` 的 token **不由服务端保存**——每个请求从 `Authorization` header 读取
|
||||
(agent 侧配在 `config.yml` 的 `mcp_servers[].headers`)。`video_task` 用智谱 token;
|
||||
`image_task` 用对应上游(智谱或 OpenAI 兼容网关)的 token,上游地址与模型分别由
|
||||
`X-Image-Task-Base-Url` / `X-Image-Task-Model` 指定。所以这里不用配任何密钥。
|
||||
|
||||
### 调试端口
|
||||
|
||||
@@ -75,7 +76,7 @@ AI 把拿到的 URL 当 image_url 交给 video_task:3000/mcp
|
||||
| 服务 | 公网暴露 | 说明 |
|
||||
|---|---|---|
|
||||
| `mcp_web_search` | 无 | 服务端无鉴权,**永远不要映射出去**(会被白嫖搜索额度);agent 走内网访问 |
|
||||
| `mcp_image_task` | 无 | token 由调用方自带,暴露后可被拿去消耗你的智谱额度 |
|
||||
| `mcp_image_task` | 无 | token 由调用方自带,暴露后可被拿去消耗你的上游图片额度 |
|
||||
| `mcp_video_task` | 无 | 它需要的公开临时 URL 由 agent 侧集成的工具提供,自己不占端口 |
|
||||
|
||||
## 单独调试
|
||||
|
||||
+197
-96
@@ -1,12 +1,18 @@
|
||||
# MCP Image Task
|
||||
|
||||
一个基于 [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) 的图片生成服务,对接智谱 BigModel 的 `CogView` 系列模型。每次调用通过 HTTP header 传入智谱 API 的 Bearer Token。只有一个工具 `image_task`,用 `op` 区分动作(`create` / `get`),对外提供与 `video_task` 一致的**异步任务**契约;上游为同步接口,异步语义由服务自维护的任务表模拟(见「架构与文件」)。
|
||||
一个基于 [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) 的图片生成 / 编辑服务。
|
||||
对外只有一个工具 `image_task`,用 `op` 区分动作(`create` / `get`),异步任务契约与 `video_task` 一致。
|
||||
|
||||
上游支持两种协议,由 `X-Image-Task-Base-Url` 选择:
|
||||
|
||||
| 通道 | 上游 | 请求体 |
|
||||
|---|---|---|
|
||||
| 智谱原生 | `https://open.bigmodel.cn/api/paas/v4/images/generations` | `{ model, prompt }` |
|
||||
| OpenAI 兼容 | 任意实现 `/images/generations` 的网关(如 `https://wb.ai.foresh.com/v1`) | `{ model, prompt, n: 1, response_format: "url", images? }` |
|
||||
|
||||
- 协议:MCP **Streamable HTTP**(单端点 `/mcp`,支持 SSE 流)
|
||||
- 上游:[智谱 BigModel Images Generations API](https://open.bigmodel.cn/dev/api#images)
|
||||
- 默认模型:`CogView-3-Flash`
|
||||
- 端口:`3000`
|
||||
- 鉴权:**无服务端密钥**,每次请求必须从 header 携带智谱 token
|
||||
- 端口:容器内 `3000`(**不映射宿主机**,只在 `agent-mcp-net` 内被 agent 访问)
|
||||
- 鉴权:**无服务端密钥**,每次请求从 `Authorization` header 读取上游 key
|
||||
|
||||
---
|
||||
|
||||
@@ -14,16 +20,13 @@
|
||||
|
||||
### 启动(docker-compose)
|
||||
|
||||
仓库根目录 `docker-compose.yml` 已包含本服务:
|
||||
|
||||
```bash
|
||||
cd /root/workspace/tools/agent
|
||||
docker compose up -d --build mcp_image_task
|
||||
```
|
||||
|
||||
服务容器名 `mcp_image_task`,容器内端口 3000,**默认不占宿主端口**:agent 走 `agent-mcp-net`
|
||||
按容器名访问(`http://mcp_image_task:3000/mcp`)。需要从宿主机 curl 调试时,去仓库根
|
||||
`docker-compose.yml` 把 `mcp_image_task` 注释掉的 `ports` 两行打开(默认写的是 8082),调试完记得注释回去。
|
||||
服务容器名 `mcp_image_task`。要从宿主机 curl 调试,把根 `docker-compose.yml` 里
|
||||
`mcp_image_task` 注释掉的 `ports` 两行打开(默认 8082),调试完记得注释回去。
|
||||
|
||||
```bash
|
||||
# 不占端口的健康检查
|
||||
@@ -33,67 +36,55 @@ docker exec mcp_image_task node -e "fetch('http://localhost:3000/health').then(r
|
||||
|
||||
### MCP 客户端配置
|
||||
|
||||
#### Claude Desktop / Cursor 等支持 `headers` 配置的客户端
|
||||
|
||||
```jsonc
|
||||
// Claude Desktop: ~/Library/Application Support/Claude/claude_desktop_config.json
|
||||
// Cursor: ~/.cursor/mcp.json
|
||||
{
|
||||
"mcpServers": {
|
||||
"image_task": {
|
||||
"url": "http://localhost:8082/mcp",
|
||||
"headers": {
|
||||
"Authorization": "Bearer <your-zhipu-api-key>"
|
||||
"Authorization": "Bearer <upstream-api-key>",
|
||||
"X-Image-Task-Base-Url": "zhipu",
|
||||
"X-Image-Task-Model": "CogView-4"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> 上面 `url` 里的端口 `8082` 需要先把 compose 里注释的 `ports` 打开(默认不占宿主端口)。
|
||||
|
||||
> **重要**:客户端必须在 **每一个 HTTP 请求**(`initialize` / `notifications/initialized` / `tools/call`)都带上 `Authorization` header。配置在 `headers` 里、由客户端自动重发即可。直连模式下 token 不在 session 间共享。
|
||||
|
||||
#### 不支持 `headers` 字段的客户端
|
||||
|
||||
如果客户端只支持 `command`/`args` 启动方式,可改用 stdio 模式(需自行包一层把 token 注入环境变量,再让工具回调从环境变量读——当前实现 HTTP 模式下不依赖环境变量,需自行扩展)。
|
||||
> 客户端必须在**每一个 HTTP 请求**(`initialize` / `notifications/initialized` / `tools/call`)都带上
|
||||
> `Authorization`。`X-Image-Task-Base-Url` / `X-Image-Task-Model` 在 `tools/call` 时读取。
|
||||
|
||||
---
|
||||
|
||||
## 工具:image_task
|
||||
|
||||
管理图片生成异步任务。典型流程:`op=create` 拿 `task_id`,然后不断 `op=get` 直到 `task_status` 为 `SUCCESS` 或 `FAIL`。
|
||||
典型流程:`op=create` 拿 `task_id`,然后不断 `op=get` 直到 `task_status` 为 `SUCCESS` 或 `FAIL`。
|
||||
|
||||
| op | 作用 | 说明 |
|
||||
|---|---|---|
|
||||
| `create` | 提交图片生成任务,**立即**返回 `task_id`,生成在后台执行 | 需要 `prompt` |
|
||||
| `create` | 提交图片生成 / 编辑任务,**立即**返回 `task_id`,生成在后台执行 | 需要 `prompt` |
|
||||
| `get` | 查询任务状态;`SUCCESS` 时返回图片 URL | 需要 `task_id` |
|
||||
|
||||
> 上游智谱 images 接口是同步阻塞的;这里的异步是对外的统一形态(对齐 `video_task`),服务内部把同步调用丢到后台跑并回写任务表。
|
||||
> 上游是同步阻塞的;这里的异步是对外统一形态(对齐 `video_task`),服务内部把同步调用丢到后台跑并回写任务表。
|
||||
|
||||
### 参数(AI 可见)
|
||||
|
||||
| 名称 | 类型 | 必填 | 说明 |
|
||||
|---|---|---|---|
|
||||
| `op` | `"create"` \| `"get"` | ✅ | 要执行的操作 |
|
||||
| `prompt` | string | op=create 时 ✅ | 图片生成提示词,描述想要的画面内容 |
|
||||
| `prompt` | string | op=create 时 ✅ | 提示词;文生图描述画面,图生图描述要改成什么样 |
|
||||
| `task_id` | string | op=get 时 ✅ | `op=create` 返回的任务 ID |
|
||||
| `image` | string | ❌ | 一张图的公网 `http(s)` URL,用于图生图 / 修图 |
|
||||
|
||||
> 图片尺寸不再透传,走上游默认;尺寸档位与成本/成功率挂钩,AI 传错值经常直接报错。
|
||||
`image` 是模式开关:
|
||||
|
||||
### Model 控制(不在工具参数中暴露)
|
||||
- 不传 → **文生图**;
|
||||
- 传一个公网 URL → **图生图 / 编辑**。
|
||||
|
||||
模型名由调用方在 **tools/call 这一次的 HTTP header** 中传递,**AI 看不到也填不了**,避免其误传。识别顺序(首个非空值生效):
|
||||
本地图片先用 `mint_public_link` 换成公网 URL,再传给 `image`。
|
||||
|
||||
| 优先级 | Header |
|
||||
|---|---|
|
||||
| 1 | `X-Image-Task-Model` |
|
||||
| 2 | `X-Mcp-Model` |
|
||||
| 3 | `X-Model` |
|
||||
|
||||
如果都没传,走代码内常量 `DEFAULT_MODEL = "CogView-3-Flash"`。
|
||||
|
||||
**为什么不放进工具参数?** 调用方一般是 AI 助手(Claude / Cursor 等),它不需要也没能力选择用哪个模型;模型选择属于部署/路由策略,由请求的发起方在 HTTP header 里注入更可控。
|
||||
> 尺寸、质量、模型、上游地址都**不是**工具参数:它们属于部署策略,由调用方在 header 里固定,
|
||||
> 避免 AI 乱填尺寸档位或模型名白烧额度。智谱原生通道也不接受尺寸,直接走上游默认值。
|
||||
|
||||
### 返回
|
||||
|
||||
@@ -102,62 +93,150 @@ docker exec mcp_image_task node -e "fetch('http://localhost:3000/health').then(r
|
||||
```jsonc
|
||||
{
|
||||
"content": [
|
||||
{ "type": "text", "text": "Model: CogView-3-Flash\ntask_id: <uuid>\ntask_status: PROCESSING\n\nImage generation is running in background. Call this tool again with op=\"get\" and task_id=\"<uuid>\" to fetch the result." }
|
||||
{ "type": "text", "text": "Model: CogView-4\nProvider: zhipu\nMode: text-to-image\ntask_id: <uuid>\ntask_status: PROCESSING\n\nImage generation is running in background. Call this tool again with op=\"get\" and task_id=\"<uuid>\" to fetch the result." }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
`op=get` 按任务状态返回:
|
||||
|
||||
- `PROCESSING`:提示几秒后再查;
|
||||
- `SUCCESS`:单个 `text` 块,摘要后跟图片 URL(单图直接给 `Image URL:`,多图按 `Image N:` 逐行列出):
|
||||
- `PROCESSING`:带上已等待秒数 `elapsed`,建议等待 `min(30, 3 + floor(elapsed / 5))` 秒后再查;
|
||||
- `SUCCESS`:单个 `text` 块,摘要后跟图片 URL(单图直接给 `Image URL:`,多图按 `Image N:` 逐行列出);`elapsed` 为从 `create` 到完成的总耗时:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"content": [
|
||||
{ "type": "text", "text": "task_id: <uuid>\nmodel: CogView-3-Flash\ntask_status: SUCCESS\nImage URL: https://maas-watermark-prod-new.cn-wlcb.ufileos.com/..." }
|
||||
{ "type": "text", "text": "task_id: <uuid>\nmodel: CogView-4\nprovider: zhipu\nelapsed: 12s\ntask_status: SUCCESS\nImage URL: https://..." }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
- `FAIL`:`isError: true`,正文含 `task_status: FAIL` 与错误信息(上游 4xx/5xx、无 URL 返回等都会归档到这里)。
|
||||
- `FAIL`:`isError: true`,正文含 `task_status: FAIL`、总耗时 `elapsed` 与错误信息(上游 4xx/5xx、无 URL 返回等都会归档到这里)。
|
||||
|
||||
URL 由智谱签名下发,**带有效期**(通常 24h),如需长期保存请在收到后及时转存到自己的存储。
|
||||
URL 由上游签名下发,**带有效期**(通常 24h),需要长期保存请及时转存。
|
||||
|
||||
---
|
||||
|
||||
## 鉴权细节
|
||||
## Headers(只有三个)
|
||||
|
||||
每个 HTTP 请求必须携带智谱 API Token,server 从以下 header 字段按顺序识别,**首个非空值生效**:
|
||||
|
||||
| 优先级 | Header | 说明 |
|
||||
| Header | 必填 | 说明 |
|
||||
|---|---|---|
|
||||
| 1 | `X-Image-Task-Token: <token>` | 直传,避免与客户端自身的 Authorization 冲突 |
|
||||
| 2 | `X-Mcp-Token: <token>` | 通用兜底 |
|
||||
| 3 | `Authorization: Bearer <token>` | 标准 OAuth 风格(排最后是为避免误用) |
|
||||
| `Authorization` | ✅ | `Bearer <key>`,原样作为上游 Bearer token |
|
||||
| `X-Image-Task-Base-Url` | ❌ | 别名或完整 URL;缺省 `zhipu` |
|
||||
| `X-Image-Task-Model` | 见下 | 模型名原样透传 |
|
||||
|
||||
Token 仅在每次 tool call 时从 header 读取,不写入任何存储、不进 session。
|
||||
### Base-Url 别名
|
||||
|
||||
### 错误响应
|
||||
| 值 | 实际地址 | 协议 |
|
||||
|---|---|---|
|
||||
| `zhipu`(默认) | `https://open.bigmodel.cn/api/paas/v4` | 智谱原生 |
|
||||
|
||||
其余值必须是完整的 `http(s)` URL:
|
||||
|
||||
```yaml
|
||||
X-Image-Task-Base-Url: "https://wb.ai.foresh.com/v1"
|
||||
```
|
||||
|
||||
- 已经给到 `/images/generations` 全路径就直接用,否则自动补 `/images/generations`。
|
||||
- 解析后的 host 是 `bigmodel.cn`(含子域)→ 智谱原生请求体;其余 host → OpenAI 兼容请求体。
|
||||
- 因此把网关地址填进来即可,不需要额外指定“用哪家协议”。
|
||||
|
||||
### 模型
|
||||
|
||||
| 场景 | `X-Image-Task-Model` |
|
||||
|---|---|
|
||||
| Base-Url = `zhipu` | 可省略,缺省 `CogView-3-Flash` |
|
||||
| 其他 Base-Url | **必填**(不会把 CogView 误发到网关) |
|
||||
|
||||
模型只由 header 决定,AI 看不到也填不了。换模型 = 改 header 后重启 core。
|
||||
|
||||
### 图生图
|
||||
|
||||
`image` 只对 OpenAI 兼容通道生效:
|
||||
|
||||
| Base-Url | 传 `image` |
|
||||
|---|---|
|
||||
| `zhipu` | 直接返回错误:智谱不支持图生图(只做文生图) |
|
||||
| 网关 URL | 上游请求体带 `images: [url]` |
|
||||
|
||||
### 请求体差异
|
||||
|
||||
| 字段 | 智谱原生 | OpenAI 兼容 |
|
||||
|---|---|---|
|
||||
| `model` / `prompt` | ✅ | ✅ |
|
||||
| `n` | ❌ | 固定 `1` |
|
||||
| `response_format` | ❌ | 固定 `"url"` |
|
||||
| `size` / `quality` | ❌ | ❌(交给上游默认值) |
|
||||
| `images` | ❌ | 传图时带,数组形式 `[url]` |
|
||||
|
||||
---
|
||||
|
||||
## 配置示例
|
||||
|
||||
### 智谱直连(默认)
|
||||
|
||||
```yaml
|
||||
- name: image_task
|
||||
url: "http://mcp_image_task:3000/mcp"
|
||||
headers:
|
||||
Authorization: "Bearer <智谱 KEY>"
|
||||
X-Image-Task-Model: "CogView-4"
|
||||
mode: skill
|
||||
```
|
||||
|
||||
### OpenAI 兼容网关(文生图)
|
||||
|
||||
```yaml
|
||||
- name: image_task
|
||||
url: "http://mcp_image_task:3000/mcp"
|
||||
headers:
|
||||
Authorization: "Bearer <网关 KEY>"
|
||||
X-Image-Task-Base-Url: "https://wb.ai.foresh.com/v1"
|
||||
X-Image-Task-Model: "global:gpt-image-2.5-sunburst"
|
||||
mode: skill
|
||||
```
|
||||
|
||||
### OpenAI 兼容网关(图生图 / 修图)
|
||||
|
||||
```yaml
|
||||
- name: image_task
|
||||
url: "http://mcp_image_task:3000/mcp"
|
||||
headers:
|
||||
Authorization: "Bearer <网关 KEY>"
|
||||
X-Image-Task-Base-Url: "https://wb.ai.foresh.com/v1"
|
||||
X-Image-Task-Model: "cn:hunyuan-image-alpha"
|
||||
mode: skill
|
||||
```
|
||||
|
||||
同一个网关换模型只改 `X-Image-Task-Model`;换供应商只改 `X-Image-Task-Base-Url`。
|
||||
|
||||
---
|
||||
|
||||
## 错误响应
|
||||
|
||||
| 场景 | HTTP 状态 | 表现 |
|
||||
|---|---|---|
|
||||
| initialize 时缺 token | `401` | JSON-RPC `error.message` 提示补充 header |
|
||||
| op=create 缺 prompt / op=get 缺 task_id | `200`(MCP 工具返回) | `isError: true`,参数提示 |
|
||||
| op=get 查不到任务(ID 错/已过期/服务重启过) | `200`(MCP 工具返回) | `isError: true`,提示 unknown task_id |
|
||||
| 智谱 API 4xx/5xx | `200`(MCP 工具返回) | 在 `op=get` 中以 `isError: true` + `task_status: FAIL` 呈现,正文含智谱返回的状态码和 body |
|
||||
| 网络失败 | `200`(MCP 工具返回) | 同上,`task_status: FAIL`,正文含 `fetch` 错误信息 |
|
||||
| 上游挂住不回(超时 >120s) | `200`(MCP 工具返回) | 同上,`task_status: FAIL`,正文提示 timed out;不会出现永久 PROCESSING 的僵尸任务 |
|
||||
| 缺 `Authorization` | `200`(MCP 工具返回) | `isError: true`,提示补 header |
|
||||
| `X-Image-Task-Base-Url` 非法 | `200`(MCP 工具返回) | `isError: true`,列出可用别名 |
|
||||
| 非 zhipu 通道缺 `X-Image-Task-Model` | `200`(MCP 工具返回) | `isError: true`,提示补 header |
|
||||
| zhipu 通道传了 `image` | `200`(MCP 工具返回) | `isError: true`,提示智谱不支持图生图,改用 OpenAI 兼容端点 |
|
||||
| `image` 不是公网 http(s) URL | `200`(MCP 工具返回) | `isError: true`,提示只接受公网 URL,不接受文件上传 / base64 |
|
||||
| `op=create` 缺 prompt / `op=get` 缺 task_id | `200`(MCP 工具返回) | `isError: true`,参数提示 |
|
||||
| `op=get` 查不到任务 | `200`(MCP 工具返回) | `isError: true`,提示 unknown task_id |
|
||||
| 上游 4xx/5xx | `200`(MCP 工具返回) | 在 `op=get` 中以 `task_status: FAIL` 呈现,正文含上游状态码和 body |
|
||||
| 上游只回 `b64_json` | `200`(MCP 工具返回) | `task_status: FAIL`,提示本服务只接受 URL |
|
||||
| 网络失败 / 超时(>180s) | `200`(MCP 工具返回) | `task_status: FAIL`,不会出现永久 PROCESSING 的僵尸任务 |
|
||||
|
||||
> JSON 请求体上限保持 2MB:`image` 只接受 URL,不接收文件或 base64。
|
||||
|
||||
---
|
||||
|
||||
## 用 curl 手工调试
|
||||
|
||||
MCP Streamable HTTP 不是普通 REST,**必须按顺序**:`initialize` → `notifications/initialized` → `tools/call`。下面用一行版串起来:
|
||||
MCP Streamable HTTP **必须按顺序**:`initialize` → `notifications/initialized` → `tools/call`。
|
||||
|
||||
```bash
|
||||
# 把 <your-zhipu-api-key> 替换成你智谱的 API Key
|
||||
TOKEN="<your-zhipu-api-key>"
|
||||
TOKEN="<upstream-api-key>"
|
||||
|
||||
# 1. initialize 拿 sessionId
|
||||
SESSION=$(curl -s -D - -X POST http://localhost:8082/mcp \
|
||||
@@ -185,19 +264,12 @@ curl -s -X POST http://localhost:8082/mcp \
|
||||
-H "Mcp-Session-Id: $SESSION" \
|
||||
-d '{"jsonrpc": "2.0", "method": "notifications/initialized"}'
|
||||
|
||||
# 3. 列出工具(可选验证)
|
||||
curl -s -X POST http://localhost:8082/mcp \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Accept: application/json, text/event-stream" \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "Mcp-Session-Id: $SESSION" \
|
||||
-d '{"jsonrpc": "2.0", "id": 2, "method": "tools/list"}'
|
||||
|
||||
# 4. 调 image_task(op=create,立即返回 task_id)
|
||||
# 3. 文生图(智谱通道;换成网关时补 X-Image-Task-Base-Url / X-Image-Task-Model)
|
||||
curl -s -X POST http://localhost:8082/mcp \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Accept: application/json, text/event-stream" \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "X-Image-Task-Model: CogView-4" \
|
||||
-H "Mcp-Session-Id: $SESSION" \
|
||||
-d '{
|
||||
"jsonrpc": "2.0",
|
||||
@@ -212,7 +284,29 @@ curl -s -X POST http://localhost:8082/mcp \
|
||||
}
|
||||
}'
|
||||
|
||||
# 5. 拿上一步返回的 task_id 轮询结果(直到 SUCCESS / FAIL)
|
||||
# 4. 图生图(OpenAI 兼容通道)
|
||||
curl -s -X POST http://localhost:8082/mcp \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Accept: application/json, text/event-stream" \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "X-Image-Task-Base-Url: https://wb.ai.foresh.com/v1" \
|
||||
-H "X-Image-Task-Model: global:gpt-image-2.5-sunburst" \
|
||||
-H "Mcp-Session-Id: $SESSION" \
|
||||
-d '{
|
||||
"jsonrpc": "2.0",
|
||||
"id": 4,
|
||||
"method": "tools/call",
|
||||
"params": {
|
||||
"name": "image_task",
|
||||
"arguments": {
|
||||
"op": "create",
|
||||
"prompt": "把背景改成雪夜,其他保持不变",
|
||||
"image": "https://example.com/input.png"
|
||||
}
|
||||
}
|
||||
}'
|
||||
|
||||
# 5. 轮询结果
|
||||
curl -s -X POST http://localhost:8082/mcp \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Accept: application/json, text/event-stream" \
|
||||
@@ -220,7 +314,7 @@ curl -s -X POST http://localhost:8082/mcp \
|
||||
-H "Mcp-Session-Id: $SESSION" \
|
||||
-d '{
|
||||
"jsonrpc": "2.0",
|
||||
"id": 4,
|
||||
"id": 5,
|
||||
"method": "tools/call",
|
||||
"params": {
|
||||
"name": "image_task",
|
||||
@@ -250,22 +344,23 @@ image_task/
|
||||
|
||||
### 关键设计
|
||||
|
||||
- **单工具 + `op` 分发**:`image_task(op=create|get)`,与 `video_task` 的服务形态完全一致,agent 侧一套轮询逻辑通吃图片/视频
|
||||
- **同步上游 → 异步契约**:智谱 images 接口只支持同步,所以服务自维护一张任务表来模拟异步:
|
||||
- **单工具 + `op` 分发**:`image_task(op=create|get)`,与 `video_task` 的服务形态一致,agent 侧一套轮询逻辑通吃图片/视频
|
||||
- **同步上游 → 异步契约**:上游同步阻塞,所以服务自维护一张任务表来模拟异步:
|
||||
- `create` 本地生成 `task_id`(`randomUUID`),登记 `PROCESSING`,把同步调用丢后台(fire-and-forget),立即返回
|
||||
- 后台完成时回写 `SUCCESS`(含 URLs)或 `FAIL`(含错误);上游同步调用带 120s 超时(`AbortSignal.timeout`),超时记 `FAIL`,杜绝僵尸 `PROCESSING`
|
||||
- 后台完成时回写 `SUCCESS`(含 URLs)或 `FAIL`(含错误);上游同步调用带 180s 超时(`AbortSignal.timeout`),超时记 `FAIL`,杜绝僵尸 `PROCESSING`
|
||||
- `get` 只读本地表,不碰上游
|
||||
- 表为进程内存 Map:已完成任务保留 1 小时(TTL)、容量上限 1000,每次 `create` 顺带淘汰;**容器重启后任务丢失**,`get` 会报 unknown task_id;**不适用于多副本部署**(表不互通)
|
||||
- token/model 在 `create` 那一刻从请求 header 捕获进闭包,后台完成前不再读取,保持「每请求读 header」的无状态设计
|
||||
- **每 session 一个 transport + server**:通过 `Mcp-Session-Id` 复用,避免每请求重建
|
||||
- **模型参数不入 schema**:model 只从 HTTP header 读取(`X-Image-Task-Model` / `X-Mcp-Model` / `X-Model`),AI 不可见
|
||||
- **URL 提取**:`response.data[].url` 为准,若返回 `b64_json` 也会一并归档进任务表
|
||||
- 表为进程内存 Map:已完成任务保留 1 小时(TTL)、容量上限 1000,每次 `create` 顺带淘汰;**容器重启后任务丢失**,`get` 会报 unknown task_id;**不适用于多副本部署**
|
||||
- token / 上游地址 / 模型在 `create` 那一刻从请求 header 捕获进闭包,后台完成前不再读取
|
||||
- **每 session 一个 transport + server**:通过 `Mcp-Session-Id` 复用
|
||||
- **模型 / 上游地址不入 schema**:只从 HTTP header 读取,AI 不可见
|
||||
- **`image` 单一开关**:不传 = 文生图,传一个公网 URL = 图生图;`image` 是单个字符串,只接受公网 `http(s)` URL
|
||||
- **URL 提取**:只接受 `data[].url` 形式的 http(s) URL;上游若回 `b64_json` 则记 `FAIL` 并给出明确错误
|
||||
|
||||
### 默认模型
|
||||
|
||||
```js
|
||||
// src/mcp-server.js
|
||||
const DEFAULT_MODEL = "CogView-3-Flash";
|
||||
const DEFAULT_MODEL = "CogView-3-Flash"; // 仅 Base-Url=zhipu 时生效
|
||||
```
|
||||
|
||||
修改后 `docker compose up -d --build mcp_image_task` 即可生效。
|
||||
@@ -275,31 +370,37 @@ const DEFAULT_MODEL = "CogView-3-Flash";
|
||||
## 常见问题
|
||||
|
||||
**Q: AI 不知道有哪些 model 可选,怎么办?**
|
||||
A: 这是设计意图。模型选择属于路由策略,不让 AI 决策。调用方在 HTTP header `X-Image-Task-Model` 里注入即可。
|
||||
A: 这是设计意图。模型选择属于部署 / 路由策略,由调用方在 `X-Image-Task-Model` 里固定,不让 AI 决策。
|
||||
|
||||
**Q: 换模型需要重连 MCP session 吗?**
|
||||
A: 不需要。Model header 在每次 `tools/call` 都从当前请求读取,不需要重建 session。
|
||||
**Q: 换模型 / 换供应商要重连 MCP session 吗?**
|
||||
A: 不需要重建 session,但 core 的 `mcp_servers[].headers` 是启动时读取的,改完要 `docker compose restart agent-core`。
|
||||
|
||||
**Q: 为什么只支持一张参考图?**
|
||||
A: 当前上游契约只稳定支持单张;`image` 因此是单个 URL 字符串。
|
||||
|
||||
**Q: 图生图为什么在 zhipu 通道报错?**
|
||||
A: 智谱原生接口不支持图生图。把 `X-Image-Task-Base-Url` 指向支持 `images` 字段的 OpenAI 兼容网关即可。
|
||||
|
||||
**Q: 本地图片怎么传?**
|
||||
A: 先调用 agent 内置的 `mint_public_link` 工具,把会话目录里的文件换成短期公网 URL,再传给 `image`。本服务不接受文件上传或 base64,上游服务器也无法访问你的本地路径。
|
||||
|
||||
**Q: 上游是同步接口,为什么对外做成异步?**
|
||||
A: 为了和 `video_task` 保持同一套任务型契约,agent 侧只需维护一种「create 后轮询 get」的调用模式。同步调用被放到后台执行,对 AI 而言表现为标准异步任务。
|
||||
A: 和 `video_task` 保持同一套任务型契约;同时避免一次生图把 core 的 `tools/call` 拖超时。
|
||||
|
||||
**Q: 任务一直 PROCESSING 会不会没完没了?**
|
||||
A: 不会。上游同步调用封顶 120s(`AbortSignal.timeout`),超时直接记 `FAIL`,`get` 会拿到明确的 timed out 错误;不存在僵尸任务。
|
||||
A: 不会。上游调用封顶 180s,超时直接记 `FAIL`。
|
||||
|
||||
**Q: 为什么 PROCESSING 时建议的等待时间会变长?**
|
||||
A: 轮询间隔按 `min(30, 3 + floor(elapsed / 5))` 退避:前期密查尽快拿到结果,后期拉长间隔减少无意义轮询,封顶 30s。
|
||||
|
||||
**Q: create 之后服务容器重启了,get 会怎样?**
|
||||
A: 任务表在进程内存里,重启即丢失,`get` 会返回 unknown task_id 的 `isError`。需要重新 `create`。图片生成只跑几秒,受影响窗口很小;若将来要上多副本或需要可靠恢复,再把表换成持久化存储。
|
||||
|
||||
**Q: 为什么 get 不需要等上游?**
|
||||
A: `get` 只读本地任务表,上游调用只发生在 `create` 的后台一次,不会因轮询而重复计费/重复生图。
|
||||
|
||||
**Q: 为什么 Model 优先级不是「工具参数 > header」?**
|
||||
A: 因为我们故意不在 schema 暴露 model 参数,AI 根本不会传 model,所以「工具参数 > header」这条分支实际上不存在。
|
||||
A: 任务表在进程内存里,重启即丢失,`get` 会返回 unknown task_id。需要重新 `create`。
|
||||
|
||||
**Q: Token 会不会泄露到日志?**
|
||||
A: 当前实现只在 session 内存里持有,不会写入 stdout/stderr。Container 日志只打印 session id。
|
||||
A: 不会。只从 header 读取,不写入日志。
|
||||
|
||||
**Q: 收到 `Missing valid Mcp-Session-Id` 错误?**
|
||||
A: 漏发了 `Mcp-Session-Id` header,或调 `tools/call` 前没先 `initialize`。
|
||||
|
||||
**Q: URL 多久过期?**
|
||||
A: 智谱签发 URL 默认 24h 左右,详见响应里的 `Expires` 参数。需要长期使用请自行转存到 OSS/S3。
|
||||
A: 上游签发的 URL 通常 24h 左右。需要长期使用请自行转存。
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "mcp_image_task",
|
||||
"version": "1.0.0",
|
||||
"description": "MCP server for image generation via Zhipu BigModel CogView (single tool image_task with op=create)",
|
||||
"description": "MCP server for image generation and editing via Zhipu BigModel CogView or any OpenAI-compatible /images/generations endpoint (single tool image_task with op=create/get)",
|
||||
"type": "module",
|
||||
"main": "src/mcp-server.js",
|
||||
"scripts": {
|
||||
|
||||
@@ -6,8 +6,14 @@ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/
|
||||
import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
|
||||
import { z } from "zod";
|
||||
|
||||
const ZHIPU_API_URL =
|
||||
"https://open.bigmodel.cn/api/paas/v4/images/generations";
|
||||
// 上游地址既支持完整 URL,也支持别名。zhipu 走智谱原生协议(body 只有
|
||||
// model/prompt);其余地址一律按 OpenAI 兼容的 /images/generations 协议
|
||||
// (body 加 n / response_format=url)。别名目前只保留 zhipu。
|
||||
const BASE_URL_ALIASES = {
|
||||
zhipu: "https://open.bigmodel.cn/api/paas/v4",
|
||||
};
|
||||
// 只有智谱需要走原生请求体,其余主机一律按 OpenAI 兼容处理。
|
||||
const ZHIPU_HOST_SUFFIX = "bigmodel.cn";
|
||||
const DEFAULT_MODEL = "CogView-3-Flash";
|
||||
|
||||
// 上游同步调用耗时上限(出图几十秒量级,留足余量)。
|
||||
@@ -49,43 +55,102 @@ function parseArgs(argv) {
|
||||
return args;
|
||||
}
|
||||
|
||||
function pickToken(headers) {
|
||||
// 对外只有三个 header:Authorization / X-Image-Task-Base-Url / X-Image-Task-Model。
|
||||
// 不再支持 X-Image-Task-Token、X-Mcp-Token、X-Mcp-Model、X-Model 等旧写法。
|
||||
function pickAuthToken(headers) {
|
||||
if (!headers) return null;
|
||||
const candidates = [
|
||||
headers["x-image-task-token"],
|
||||
headers["x-mcp-token"],
|
||||
headers["authorization"],
|
||||
];
|
||||
for (const v of candidates) {
|
||||
if (!v) continue;
|
||||
const s = String(v).trim();
|
||||
if (!s) continue;
|
||||
const s = String(headers["authorization"] || "").trim();
|
||||
if (!s) return null;
|
||||
if (/^Bearer\s+/i.test(s)) {
|
||||
const t = s.replace(/^Bearer\s+/i, "").trim();
|
||||
if (t) return t;
|
||||
} else {
|
||||
return t || null;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function pickModel(headers) {
|
||||
function pickHeaderString(headers, name) {
|
||||
if (!headers) return null;
|
||||
const v =
|
||||
headers["x-image-task-model"] ||
|
||||
headers["x-mcp-model"] ||
|
||||
headers["x-model"];
|
||||
if (!v) return null;
|
||||
const v = headers[name];
|
||||
if (v === undefined || v === null) return null;
|
||||
const s = String(v).trim();
|
||||
return s || null;
|
||||
}
|
||||
|
||||
async function callZhipuImagesGenerations({ token, model, prompt }) {
|
||||
const body = { model, prompt };
|
||||
function pickBaseUrl(headers) {
|
||||
return pickHeaderString(headers, "x-image-task-base-url");
|
||||
}
|
||||
|
||||
function pickModel(headers) {
|
||||
return pickHeaderString(headers, "x-image-task-model");
|
||||
}
|
||||
|
||||
// 解析 Base-Url:别名优先,否则必须是 http(s) URL。
|
||||
// 返回 { provider, url }:url 是最终 POST 的完整地址。
|
||||
function resolveEndpoint(rawBase) {
|
||||
const raw = String(rawBase || "zhipu").trim().replace(/\/+$/, "");
|
||||
const alias = BASE_URL_ALIASES[raw.toLowerCase()];
|
||||
const base = alias || raw;
|
||||
|
||||
let host;
|
||||
try {
|
||||
if (!/^https?:\/\//i.test(base)) throw new Error("not http(s)");
|
||||
host = new URL(base).hostname.toLowerCase();
|
||||
} catch {
|
||||
throw new Error(
|
||||
`Invalid X-Image-Task-Base-Url "${raw}": use an alias (${Object.keys(BASE_URL_ALIASES).join(", ")}) ` +
|
||||
"or a full http(s) URL."
|
||||
);
|
||||
}
|
||||
|
||||
// 已经给到 /images/generations 就直接用;否则补在 base 后面。
|
||||
const url = /\/images\/generations$/i.test(base)
|
||||
? base
|
||||
: base + "/images/generations";
|
||||
const provider =
|
||||
host === ZHIPU_HOST_SUFFIX || host.endsWith("." + ZHIPU_HOST_SUFFIX)
|
||||
? "zhipu"
|
||||
: "openai";
|
||||
return { provider, url };
|
||||
}
|
||||
|
||||
// 模型只由 header 决定,AI 看不到也填不了。
|
||||
// zhipu 通道有默认模型;其他通道必须显式给 —— 否则会把 CogView 发到网关,
|
||||
// 换来的只是一个含义不明的 400。
|
||||
function resolveModel(headers, provider) {
|
||||
const model = pickModel(headers);
|
||||
if (model) return model;
|
||||
if (provider === "zhipu") return DEFAULT_MODEL;
|
||||
throw new Error(
|
||||
"X-Image-Task-Model is required when X-Image-Task-Base-Url is not the zhipu alias."
|
||||
);
|
||||
}
|
||||
|
||||
// 一次解析出本次请求的上游、凭据、模型。
|
||||
// 配置问题同步抛错,由 create 直接回给调用方,不登记注定失败的任务。
|
||||
function resolveTarget(headers) {
|
||||
const token = pickAuthToken(headers);
|
||||
if (!token) {
|
||||
throw new Error('Missing Authorization: use "Authorization: Bearer <token>".');
|
||||
}
|
||||
const { provider, url } = resolveEndpoint(pickBaseUrl(headers));
|
||||
return { provider, url, token, model: resolveModel(headers, provider) };
|
||||
}
|
||||
|
||||
async function callImagesGenerations({ provider, url, token, model, prompt, image }) {
|
||||
// 智谱原生只认 model/prompt;OpenAI 兼容通道固定单图,并要求返回 URL
|
||||
// (b64_json 几十 MB,既塞不进任务表也没法给模型看)。尺寸/质量一律不传,
|
||||
// 交给上游默认值 —— 各家(尤其 CogView)对尺寸的限制并不一致。
|
||||
// 传了 image 就是图生图;上游字段是数组,所以这里包一层。
|
||||
const body =
|
||||
provider === "zhipu"
|
||||
? { model, prompt }
|
||||
: Object.assign(
|
||||
{ model, prompt, n: 1, response_format: "url" },
|
||||
image ? { images: [image] } : null
|
||||
);
|
||||
let resp;
|
||||
try {
|
||||
resp = await fetch(ZHIPU_API_URL, {
|
||||
resp = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
@@ -110,8 +175,9 @@ async function callZhipuImagesGenerations({ token, model, prompt }) {
|
||||
data = { raw: text };
|
||||
}
|
||||
if (!resp.ok) {
|
||||
const label = provider === "zhipu" ? "Zhipu" : "OpenAI-compatible";
|
||||
const err = new Error(
|
||||
`Zhipu API error: ${resp.status} ${resp.statusText} - ${text}`
|
||||
`${label} API error: ${resp.status} ${resp.statusText} - ${text}`
|
||||
);
|
||||
err.status = resp.status;
|
||||
err.detail = data;
|
||||
@@ -120,15 +186,24 @@ async function callZhipuImagesGenerations({ token, model, prompt }) {
|
||||
return data;
|
||||
}
|
||||
|
||||
// 只认 http(s) URL。b64_json 不再当 URL 存:它会把任务表撑爆,模型也读不了。
|
||||
function extractUrls(data) {
|
||||
if (!data) return [];
|
||||
if (Array.isArray(data.data)) {
|
||||
return data.data
|
||||
.map((it) => it && (it.url || it.b64_json))
|
||||
.filter(Boolean);
|
||||
}
|
||||
if (typeof data.url === "string") return [data.url];
|
||||
return [];
|
||||
const items = Array.isArray(data.data)
|
||||
? data.data
|
||||
: typeof data.url === "string"
|
||||
? [data]
|
||||
: [];
|
||||
return items
|
||||
.map((it) => (it && typeof it.url === "string" ? it.url.trim() : ""))
|
||||
.filter((u) => /^https?:\/\//i.test(u));
|
||||
}
|
||||
|
||||
function hasInlineBase64(data) {
|
||||
return (
|
||||
Array.isArray(data && data.data) &&
|
||||
data.data.some((it) => it && typeof it.b64_json === "string")
|
||||
);
|
||||
}
|
||||
|
||||
// ===== 自维护任务表(异步语义全靠这层模拟) =====
|
||||
@@ -163,19 +238,31 @@ function pruneTasks() {
|
||||
}
|
||||
|
||||
// 后台跑同步上游调用,结果回写任务表(fire-and-forget,不 await)
|
||||
function runImageTask({ task, token, model, prompt }) {
|
||||
callZhipuImagesGenerations({ token, model, prompt })
|
||||
function runImageTask({ task, target, prompt, image }) {
|
||||
callImagesGenerations({
|
||||
provider: target.provider,
|
||||
url: target.url,
|
||||
token: target.token,
|
||||
model: target.model,
|
||||
prompt,
|
||||
image,
|
||||
})
|
||||
.then((data) => {
|
||||
task.finishedAt = Date.now();
|
||||
const urls = extractUrls(data);
|
||||
if (urls.length === 0) {
|
||||
task.status = "FAIL";
|
||||
task.error = `Zhipu returned no image URL. Raw response: ${JSON.stringify(data)}`;
|
||||
task.error = hasInlineBase64(data)
|
||||
? "Upstream returned b64_json instead of a URL; this service only returns URLs. " +
|
||||
"Use a model that supports response_format=url."
|
||||
: `Upstream returned no image URL. Raw response: ${JSON.stringify(data)}`;
|
||||
} else {
|
||||
task.status = "SUCCESS";
|
||||
task.urls = urls;
|
||||
}
|
||||
})
|
||||
.catch((e) => {
|
||||
task.finishedAt = Date.now();
|
||||
task.status = "FAIL";
|
||||
task.error = `${e.message}${
|
||||
e.detail ? ` Details: ${JSON.stringify(e.detail)}` : ""
|
||||
@@ -184,7 +271,7 @@ function runImageTask({ task, token, model, prompt }) {
|
||||
}
|
||||
|
||||
// ===== op=create:提交图片生成(立即返回 task_id,后台执行)=====
|
||||
async function handleCreate({ args, headers, token }) {
|
||||
async function handleCreate({ args, headers }) {
|
||||
// schema 只约束了 min(1)," " 这种纯空白能通过校验并白跑一次出图,所以这里 trim 后再判。
|
||||
// 顺手用 trim 过的值:上游拿到的 prompt 不带首尾空白。
|
||||
const prompt = typeof args.prompt === "string" ? args.prompt.trim() : "";
|
||||
@@ -195,26 +282,76 @@ async function handleCreate({ args, headers, token }) {
|
||||
};
|
||||
}
|
||||
|
||||
// model 完全由 HTTP header 控制(X-Image-Task-Model / X-Mcp-Model / X-Model),
|
||||
// 不存进 session,每次从本次请求的 header 读取,未设置则用默认 CogView-3-Flash。
|
||||
// AI 看不到 model 参数(schema 中已删除),避免其误传。
|
||||
const model = pickModel(headers) || DEFAULT_MODEL;
|
||||
// image 是文生图/图生图开关:不传 = 文生图;传一个公网 URL = 修图。
|
||||
// 只接受公网 http(s) URL;本地文件请先由调用方用 mint_public_link 换成公网链接。
|
||||
if (args.image !== undefined && typeof args.image !== "string") {
|
||||
return {
|
||||
isError: true,
|
||||
content: [{ type: "text", text: 'op=create: "image" must be a string.' }],
|
||||
};
|
||||
}
|
||||
const image = typeof args.image === "string" ? args.image.trim() : "";
|
||||
if (image && !/^https?:\/\//i.test(image)) {
|
||||
return {
|
||||
isError: true,
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text:
|
||||
'op=create: "image" must be a public http(s) URL. ' +
|
||||
"For a local file, call mint_public_link first to get a public URL.",
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
// 上游地址、模型、凭据全部来自本次请求的 header(Authorization /
|
||||
// X-Image-Task-Base-Url / X-Image-Task-Model),AI 看不到也填不了。
|
||||
// 配置类错误直接回错,不登记一个必然失败的任务。
|
||||
let target;
|
||||
try {
|
||||
target = resolveTarget(headers);
|
||||
} catch (e) {
|
||||
return {
|
||||
isError: true,
|
||||
content: [{ type: "text", text: e.message }],
|
||||
};
|
||||
}
|
||||
|
||||
// 智谱原生接口不支持图生图;带 image 的请求只能走 OpenAI 兼容端点。
|
||||
if (image && target.provider === "zhipu") {
|
||||
return {
|
||||
isError: true,
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text:
|
||||
'Image editing is not supported by the configured model. ' +
|
||||
'Remove "image" for text-to-image.',
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
pruneTasks();
|
||||
const taskId = randomUUID();
|
||||
const task = {
|
||||
status: "PROCESSING",
|
||||
model,
|
||||
provider: target.provider,
|
||||
model: target.model,
|
||||
prompt,
|
||||
createdAt: Date.now(),
|
||||
};
|
||||
tasks.set(taskId, task);
|
||||
|
||||
// token/model 在此刻从本次请求 header 捕获进闭包,后台完成前无需再取
|
||||
runImageTask({ task, token, model, prompt });
|
||||
// target 与 image 在此刻从本次请求捕获进闭包,后台完成前无需再取
|
||||
runImageTask({ task, target, prompt, image });
|
||||
|
||||
const mode = image ? "edit" : "text-to-image";
|
||||
const summary =
|
||||
`Model: ${model}\n` +
|
||||
`Model: ${target.model}\n` +
|
||||
`Provider: ${target.provider}\n` +
|
||||
`Mode: ${mode}\n` +
|
||||
`task_id: ${taskId}\n` +
|
||||
`task_status: PROCESSING\n` +
|
||||
`\n` +
|
||||
@@ -224,6 +361,20 @@ async function handleCreate({ args, headers, token }) {
|
||||
return { content: [{ type: "text", text: summary }] };
|
||||
}
|
||||
|
||||
// 从 create 到完成(未完成则到当前)的累计秒数。
|
||||
// 已完成任务用 finishedAt 定格,避免它留在表里越查越大。
|
||||
function elapsedSeconds(task) {
|
||||
const end = task.status === "PROCESSING"
|
||||
? Date.now()
|
||||
: (task.finishedAt || Date.now());
|
||||
return Math.max(0, Math.round((end - task.createdAt) / 1000));
|
||||
}
|
||||
|
||||
// 轮询退避:起步 3s,之后每多等 5s 加 1s,封顶 30s。
|
||||
function pollIntervalSeconds(elapsed) {
|
||||
return Math.min(30, 3 + Math.floor(elapsed / 5));
|
||||
}
|
||||
|
||||
// ===== op=get:查询任务状态(只读本地表,不碰上游)=====
|
||||
async function handleGet({ args }) {
|
||||
// 与 handleCreate 同理:纯空白 task_id 应报"缺参数",而不是得到 Unknown task_id " " 这种含糊错误。
|
||||
@@ -251,6 +402,8 @@ async function handleGet({ args }) {
|
||||
}
|
||||
|
||||
if (task.status === "PROCESSING") {
|
||||
const elapsed = elapsedSeconds(task);
|
||||
const retryAfter = pollIntervalSeconds(elapsed);
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
@@ -258,9 +411,11 @@ async function handleGet({ args }) {
|
||||
text:
|
||||
`task_id: ${taskId}\n` +
|
||||
`model: ${task.model}\n` +
|
||||
`provider: ${task.provider}\n` +
|
||||
`elapsed: ${elapsed}s\n` +
|
||||
`task_status: PROCESSING\n` +
|
||||
`\n` +
|
||||
`Call op="get" again in a few seconds.`,
|
||||
`Task is still processing. Sleep for ${retryAfter} seconds, then call op="get" again.`,
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -272,7 +427,12 @@ async function handleGet({ args }) {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: `task_id: ${taskId}\ntask_status: FAIL\nerror: ${task.error}`,
|
||||
text:
|
||||
`task_id: ${taskId}\n` +
|
||||
`provider: ${task.provider}\n` +
|
||||
`elapsed: ${elapsedSeconds(task)}s\n` +
|
||||
`task_status: FAIL\n` +
|
||||
`error: ${task.error}`,
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -287,6 +447,8 @@ async function handleGet({ args }) {
|
||||
const summary =
|
||||
`task_id: ${taskId}\n` +
|
||||
`model: ${task.model}\n` +
|
||||
`provider: ${task.provider}\n` +
|
||||
`elapsed: ${elapsedSeconds(task)}s\n` +
|
||||
`task_status: SUCCESS\n` +
|
||||
`${lines}`;
|
||||
return { content: [{ type: "text", text: summary }] };
|
||||
@@ -307,17 +469,18 @@ function buildServer() {
|
||||
|
||||
server.tool(
|
||||
"image_task",
|
||||
`AI image generation task.
|
||||
`AI image generation and editing task.
|
||||
|
||||
Operations:
|
||||
- \`create\`: Create a new generation task. Requires \`prompt\`. Returns \`task_id\` immediately; generation runs in background.
|
||||
- \`get\`: Check an existing task. Requires \`task_id\`. Returns status and, on SUCCESS, image URLs.
|
||||
- \`create\`: Create a generation task. Requires \`prompt\`. Returns \`task_id\` immediately; generation runs in background. Optionally pass \`image\` for image-to-image editing.
|
||||
- \`get\`: Check a task. Requires \`task_id\`. Returns status and, on SUCCESS, image URLs.
|
||||
|
||||
Examples:
|
||||
- New image request → \`{"op":"create","prompt":"A cat sitting in a garden"}\`
|
||||
- Check task result → \`{"op":"get","task_id":"<task_id from create>"}\`
|
||||
- New image → \`{"op":"create","prompt":"A cat sitting in a garden"}\`
|
||||
- Edit an image → \`{"op":"create","prompt":"Make it snow","image":"https://..."}\`
|
||||
- Check result → \`{"op":"get","task_id":"<task_id from create>"}\`
|
||||
|
||||
Workflow: call \`create\` once, then call \`get\` with the returned \`task_id\` until \`task_status\` is \`SUCCESS\` or \`FAIL\`. Never call \`get\` without a \`task_id\`, and never submit duplicate tasks just to check status.`,
|
||||
Workflow: call \`create\` once, then \`get\` with the returned \`task_id\` until \`task_status\` is \`SUCCESS\` or \`FAIL\`.`,
|
||||
{
|
||||
op: z
|
||||
.enum(["create", "get"])
|
||||
@@ -334,12 +497,20 @@ Workflow: call \`create\` once, then call \`get\` with the returned \`task_id\`
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("task_id returned by create. Required for get; omit for create."),
|
||||
image: z
|
||||
.string()
|
||||
.min(1)
|
||||
.regex(/^https?:\/\//i)
|
||||
.optional()
|
||||
.describe(
|
||||
"One public image URL to edit; omit for text-to-image. For a local file, call mint_public_link first to get a public URL."
|
||||
),
|
||||
},
|
||||
async (args, extra) => {
|
||||
// SDK 在 tool callback 的 extra.requestInfo.headers 里会透传当前 HTTP 请求的 headers
|
||||
// (参见 webStandardStreamableHttp.js: buildRequestInfo 段)
|
||||
const headers = extra?.requestInfo?.headers;
|
||||
const token = pickToken(headers);
|
||||
const token = pickAuthToken(headers);
|
||||
if (!token) {
|
||||
return {
|
||||
isError: true,
|
||||
@@ -347,7 +518,7 @@ Workflow: call \`create\` once, then call \`get\` with the returned \`task_id\`
|
||||
{
|
||||
type: "text",
|
||||
text:
|
||||
"Missing authentication token.",
|
||||
'Missing Authorization: use "Authorization: Bearer <token>".',
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -355,7 +526,7 @@ Workflow: call \`create\` once, then call \`get\` with the returned \`task_id\`
|
||||
|
||||
switch (args.op) {
|
||||
case "create":
|
||||
return await handleCreate({ args, headers, token });
|
||||
return await handleCreate({ args, headers });
|
||||
case "get":
|
||||
return await handleGet({ args });
|
||||
default:
|
||||
|
||||
+12
-9
@@ -8,9 +8,9 @@
|
||||
|
||||
技能是一个自包含的目录,通常存放在技能根目录(默认为 `skills/`)下。每个技能包含一个描述文件(`SKILL.md`)和一个可执行入口(`run.py` 或 `run.sh`)。Agent 通过以下流程使用技能:
|
||||
|
||||
1. 调用 `skill` 的 `{"list":"all"}` 查看所有可用技能的名称和简介;
|
||||
2. 调用 `skill` 的 `{"get":"<技能名>"}` 获取某个技能的详细说明;
|
||||
3. 调用 `skill` 的 `{"run":"<技能名>","args":{...}}` 执行技能,传入所需参数。
|
||||
1. 调用 `skill` 的 `{"op":"list"}` 查看所有可用技能的名称和简介;
|
||||
2. 调用 `skill` 的 `{"op":"get","name":"<技能名>"}` 获取某个技能的详细说明;
|
||||
3. 调用 `skill` 的 `{"op":"run","name":"<技能名>","args":{...}}` 执行技能,传入所需参数。
|
||||
|
||||
技能可以处理任何任务,例如文件格式转换、数据处理、网页抓取等。
|
||||
|
||||
@@ -53,11 +53,14 @@ input_schema:
|
||||
output_schema:
|
||||
# 输出描述
|
||||
visit_url: /app/{task_id}/ # 可选:页面类技能的访问路径模板
|
||||
thinking: true # 可选:get 时自动开启本回合的深度思考
|
||||
---
|
||||
```
|
||||
|
||||
- `name`:技能名称,应与目录名一致。
|
||||
- `description`:一句话描述技能功能,用于 `{"list":"all"}` 的清单展示。
|
||||
- `description`:一句话描述技能功能,用于 `op=list` 的清单展示。
|
||||
- `thinking`:(可选)为 `true` 时,模型调用 `get` 会自动开启深度思考(合并模型的
|
||||
`thinking_params`),开启后保持,直到用户手动关闭;模型未配置思考参数时不生效。只影响模型回合,不影响脚本本身。
|
||||
- `input_schema`:输入参数的 JSON Schema 定义,用于参数校验和文档生成。
|
||||
- `output_schema`:输出结果的描述(可选)。
|
||||
- `visit_url`:(可选)页面类技能声明的访问路径模板,`{task_id}` 占位执行时替换为会话 id。`run` 成功后由 core(tools/executor.js)拼上 `public_link.base_url`,在输出末尾追加一行「访问地址:<完整 URL>」——技能进程跑在 executor 隔离视图里不知道公网地址,完整链接只能 core 补;AI 拿到相对路径会原样转给用户,而相对路径打不开。
|
||||
@@ -80,7 +83,7 @@ visit_url: /app/{task_id}/ # 可选:页面类技能的访问路径模板
|
||||
- 自动处理某某
|
||||
|
||||
## 使用说明
|
||||
通过 `skill` 的 `{"run":"<技能名>","args":{...}}` 调用,参数:
|
||||
通过 `skill` 的 `{"op":"run","name":"<技能名>","args":{...}}` 调用,参数:
|
||||
- `input`:某某路径(必填)
|
||||
- `output`:某某路径(可选,默认与输入同名)
|
||||
```
|
||||
@@ -92,10 +95,10 @@ visit_url: /app/{task_id}/ # 可选:页面类技能的访问路径模板
|
||||
把 `config.yml` 里某个 MCP 服务配成 `mode: skill` 即可:它的每个工具会自动成为技能,不需要
|
||||
`SKILL.md`,也不需要入口脚本。
|
||||
|
||||
- `{"list":"all"}` 里出现工具名,描述取 MCP `description` 的第一行;
|
||||
- `{"get":"<工具名>"}` 直接返回 MCP 原始的 `description` + `input_schema`(单一来源,不会与
|
||||
- `{"op":"list"}` 里出现工具名,描述取 MCP `description` 的第一行;
|
||||
- `{"op":"get","name":"<工具名>"}` 直接返回 MCP 原始的 `description` + `input_schema`(单一来源,不会与
|
||||
实现漂移);
|
||||
- `{"run":"<工具名>","args":{…}}` 把 `args` 原样透传成 MCP 的 `arguments`,由 core 直接转发。
|
||||
- `{"op":"run","name":"<工具名>","args":{…}}` 把 `args` 原样透传成 MCP 的 `arguments`,由 core 直接转发。
|
||||
|
||||
几个约束:
|
||||
|
||||
@@ -251,7 +254,7 @@ input_schema:
|
||||
---
|
||||
|
||||
## 使用说明
|
||||
通过 `skill` 的 `{"run":"<技能名>","args":{...}}` 调用,参数:
|
||||
通过 `skill` 的 `{"op":"run","name":"<技能名>","args":{...}}` 调用,参数:
|
||||
- `text`:要回显的文本(必填)
|
||||
```
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ visit_url: /app/{task_id}/
|
||||
|
||||
## 初始化
|
||||
|
||||
调用 `skill {"run":"data-page"}`,无需参数。它会把以下文件复制到 `.app/`:
|
||||
调用 `skill {"op":"run","name":"data-page"}`,无需参数。它会把以下文件复制到 `.app/`:
|
||||
|
||||
- `table.html` / `dashboard.html` / `kanban.html` —— 三个数据页模板
|
||||
- `nav.html` —— 多页导航首页模板(静态卡片,无 config)
|
||||
@@ -80,7 +80,7 @@ const taskId = location.pathname.split('/').filter(Boolean)[1];
|
||||
|
||||
1. **明确数据结构**:与用户确认字段。如果描述模糊,可以建议合理的结构。
|
||||
2. **创建表并录入数据**:用 `db` 工具完成。
|
||||
3. **初始化**:调用 `skill {"run":"data-page"}`。
|
||||
3. **初始化**:调用 `skill {"op":"run","name":"data-page"}`。
|
||||
4. **为每个要生成的页面写 config 文件**(见下一节)。**不要读也不要改模板本身**。
|
||||
5. **选定入口页 `.app/index.html`**(index 是副本,允许编辑;模板本体不动):
|
||||
- **用到 ≥2 个模板页** → `cp .app/nav.html .app/index.html`,改标题为业务名,并把未启用页面的卡片删掉(没配过的页点开会报 no such table)。子页标题左侧的「‹」返回键链回此导航页。
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
---
|
||||
name: document-photo-to-pdf
|
||||
description: 把手机拍摄的纸质文档照片拉正、去背景,按顺序合并为一个 PDF
|
||||
thinking: true
|
||||
---
|
||||
|
||||
# 文档照片转 PDF
|
||||
|
||||
手机拍的纸质材料 → 一个版正字清的 PDF。适用于合同、票据、证照、手写稿等多页纸质材料,纸张尺寸不限。
|
||||
|
||||
## 怎么跑
|
||||
|
||||
本技能没有 `run` 入口,用 `terminal` 直接执行命令。脚本装在技能目录,而 terminal 的
|
||||
cwd 是会话任务目录——两者不是同一个目录,所以**脚本一律用绝对路径调用**,图片和
|
||||
`out/` 用任务目录里的相对路径:
|
||||
|
||||
```sh
|
||||
python3 /workspace/skills/document-photo-to-pdf/doc_deskew/pipeline.py <子命令> ...
|
||||
```
|
||||
|
||||
## 铁律
|
||||
|
||||
> 以下 8 条为硬约束,违反任一条即视为任务失败:立即停手、向用户说明,不得"先改完再说"。
|
||||
|
||||
1. **先说再做。** 每次调脚本前用一句话说明这次干什么(要标注步骤编号)。
|
||||
2. **坐标只能靠眼睛读,禁止一切自建脚本。** 不另造任何纸张处理的辅助的代码,一次性脚本也不行。确实无法达成目的需要新能力=先停下问用户,不许自己造。
|
||||
3. **不裁切、不放大、不逐角看。** 四个角在同一张网格图上一次读全,直接报 4 组数字。不为了"读准一点"造局部图、加刻度、逐个角反复看。
|
||||
4. **每张图读 2 次,且每次都要有目的。** 网格 1 次 + 角标 1 次,看完就交付。
|
||||
- **读之前先说清这次要确认什么。** 说不出目的就不读。"再看一眼确认一下"不算目的。
|
||||
- **不为读而读。** 允许重读,但必须是被动的、有明确对象的:图没送达/像素没收到、要核对某个具体数字或某条边。没有新对象就直接用手上已有的数字。
|
||||
- **只读这两类图。** 网格、角标。原图、局部放大图、成品图、自己另造的辅助图都不读。
|
||||
- 没把握就按"宁可外扩"给保守值,交给角标图验证,不在读图阶段磨。
|
||||
5. **一次成件,禁止试错。** 一条 `build` 出件 + 检验。一轮里每页最多跑 1 次 `build`;不调参、不重取角点、不换方法、不"先出一版看看"。不通过就报诊断,停下等确认。
|
||||
6. **只有用户明确说"再改"才允许修复。** 完整一轮 = `prepare` → `set`(每页一次)→ `build`(一次)→ 看角标 → 交付。这一轮内发现的任何偏差(框偏了、裁到内容、比例不对),一律只报诊断和坐标建议,**不自行改、不重跑、不补做**。用户在本轮交付后明确说"再改/重做"时才能动手,且还是只跑一轮,改完重新过角标关。
|
||||
7. **指标 ≠ 成品。** 校验只查"框内"像素,框漏掉的内容查不出来。角标图必须亲眼看。
|
||||
8. **违规即停。** 一旦意识到自己正在写脚本、造辅助图、二次 build 或擅自修复,立即停手,向用户说明,不带病交付。
|
||||
|
||||
### 交付前自检(有一项为"是"就停手报告)
|
||||
|
||||
- 本轮是否新建/修改过任何脚本或辅助图?
|
||||
- 本轮 `build` 是否跑超过 1 次?
|
||||
- 是否在用户没说过"再改"时自行调整过角点或重出件?
|
||||
- 每张图是否只读了网格、角标各 1 次?
|
||||
- 校验未过的项是否只报告、没自行修?
|
||||
|
||||
## 流程
|
||||
|
||||
### 1 · 出网格图
|
||||
|
||||
```sh
|
||||
python3 /workspace/skills/document-photo-to-pdf/doc_deskew/pipeline.py prepare 图1.jpg 图2.jpg
|
||||
```
|
||||
|
||||
不传图片名 = 取当前目录所有图片。输出 `out/N-网格-<名称>.png`(100px 红色主线带坐标刻度、50px 蓝色辅助线,两者同宽)。
|
||||
|
||||
### 2 · 从网格图中读出角点,一张图一条命令
|
||||
|
||||
顺序固定:左上 → 右上 → 右下 → 左下(屏幕坐标,原点左上)。
|
||||
|
||||
**要找的是纸张本身真实的四个角**——纸面这个四边形的 4 个顶点,**坐标的质量直接决定最终成品的质量!**。
|
||||
|
||||
读数方法:
|
||||
1. 先找离目标点最近的红线(整百、带数字刻度)读基准值;
|
||||
2. 再识别目标点相对相邻蓝线(50px)的偏移;
|
||||
3. 把目的坐标复述成一句话,例如“右下:x 在 1000 红线右 52px,y 在 1700 红线下 22px → 1052,1722”。
|
||||
|
||||
读数要求:
|
||||
- 读之前先定好这一张要报的 4 组数字,看完立刻 `set` 落盘到 `out/corners.json`。
|
||||
- 角被遮挡:沿两条可见纸边延长交会出顶点。
|
||||
- 角出画面:顺两条边的趋势延长,坐标可为负或超界(脚本接受)。
|
||||
|
||||
写入坐标:
|
||||
```sh
|
||||
python3 /workspace/skills/document-photo-to-pdf/doc_deskew/pipeline.py set 图1.jpg \
|
||||
--quad "左上x,左上y;右上x,右上y;右下x,右下y;左下x,左下y"
|
||||
```
|
||||
- 一次只写一张图,脚本已强制拦截多图(防串页)。
|
||||
- 落盘 `out/corners.json`,同名键覆盖并打印旧值对比;`show` 可随时查看。
|
||||
- 报给用户的只能是 `--quad` 串或 4 组坐标数字,禁止"约 (140,390)、纸略倾斜"这类描述。
|
||||
|
||||
### 3 · 一条命令出件
|
||||
|
||||
```sh
|
||||
python3 /workspace/skills/document-photo-to-pdf/doc_deskew/pipeline.py build \
|
||||
--out 文档照片_校正.pdf --paper a4 --force
|
||||
```
|
||||
|
||||
内部依次:回画角标 → 角点几何校验 → 透视校正+按纸比例拉正+提亮 → 合并 PDF → PDF 渲染检验 → 打印汇总。
|
||||
|
||||
参数:
|
||||
- `--paper`:标准纸必须传 —— `a4`(0.707)、`letter`(0.773)、`16k`(0.712)、`b5`(0.704),或数字比例。票据、异形纸不确定就省略,保留原始比例。
|
||||
- `--force`:角点校验不过也出件(默认)。
|
||||
- 位置参数传图名:只出指定页,如 `build 图2.jpg --out 结果.pdf`(输出 PDF 只含这一页)。
|
||||
- `--dpi`:PDF 检验渲染 dpi,默认 100。
|
||||
|
||||
### 4 · 看角标图(强制,一次)
|
||||
|
||||
**角标图是决定图像处理质量的唯一标准!**
|
||||
|
||||
读 `out/N-角标-*.png`(原图 + 同一套网格 + 四角标注),四个角在同一张图上核对:
|
||||
1. 绿线是否压在纸边交界?
|
||||
2. 纸张上内容是否全在绿线框内?
|
||||
3. 4个角标是否都在纸张实际的角上!
|
||||
|
||||
**只看不改:** 发现问题只记进报告,记录修正前后角标坐标的表格、不重跑 `build`、不补造辅助图。
|
||||
|
||||
| 页码 | 实际使用的角点坐标 | 修正后的角点坐标 |
|
||||
|---|---|---|
|
||||
| 1 | x1,y1;x2,y2;x3,y3;x4,y4 | x1',y1';x2',y2';x3',y3';x4',y4' |
|
||||
|
||||
## 判定与报告
|
||||
|
||||
| 检查项 | 判据 | 不达标含义 |
|
||||
|---|---|---|
|
||||
| 页数 | 与源图数一致 | 合并出错 |
|
||||
| 纸面短边 | ≥ 533px @100dpi | 角点错或分辨率过低 |
|
||||
| 纸张比例 | 仅提示 | 传了 `--paper` 应≈1.00,偏差大说明角点有误 |
|
||||
| 边缘背景残留 | 边带亮度 ≥ 纸面 80% | 角点落在背景上,内收 3~5px |
|
||||
| 内容贴边 | 页边无成片文字级暗像素 | 内容被切,外扩 5px |
|
||||
|
||||
- **全部通过**:给产物路径、大小、页数、指标,加一句角标图上确认的结果。
|
||||
- **"外侧纸面占比 100%"一律当角点错误**,误差是几十到上百 px,回第 2 步重读,不是微调。
|
||||
- **不达标**:只报诊断+ 建议,**不自行改、不重跑、不换方法**。用户明确说"再改"后,才改动后重跑一轮,然后交用户决策。
|
||||
- **用户没发话就交付**:即使只差 1px、即使一眼看出能更好,也不许动。报告里可写建议,手不能动。
|
||||
|
||||
## 内容安全
|
||||
|
||||
**禁止用生成式模型处理这类图片。** 生成模型是重绘而非变换,会改写文档内容,且结果看起来完全正常。本流程只做纯几何变换 + 全局等比提亮,文字、金额、印章保持原始像素。
|
||||
|
||||
## 命令速查
|
||||
|
||||
下表省略公共前缀 `python3 /workspace/skills/document-photo-to-pdf/doc_deskew/`。
|
||||
|
||||
| 场景 | 命令 |
|
||||
|---|---|
|
||||
| 出网格图 | `pipeline.py prepare 图1.jpg 图2.jpg` |
|
||||
| 写角点(一张一次) | `pipeline.py set 图1.jpg --quad "x1,y1;x2,y2;x3,y3;x4,y4"` |
|
||||
| 查看已落盘 | `pipeline.py show` |
|
||||
| 出件 | `pipeline.py build --out 结果.pdf --paper a4` |
|
||||
| 只出指定页(PDF 只含该页) | `pipeline.py build 图2.jpg --out 结果.pdf` |
|
||||
| 复检已有 PDF(不重新出件) | `pipeline.py check 结果.pdf --expect-pages 2` |
|
||||
|
||||
底层模块(与 `pipeline.py` 同目录,由它调用,日常不用直接执行):
|
||||
|
||||
| 模块 | 职责 |
|
||||
|---|---|
|
||||
| `grid.py` | 画带坐标的网格图 |
|
||||
| `preview_quad.py` | 画角标图(叠网格) |
|
||||
| `verify_quad.py` | 角点几何校验 |
|
||||
| `homography.py` | 透视变换 + 提亮 |
|
||||
| `run.py` | 拉正 + 拼页(纯模块,无 CLI) |
|
||||
| `make_pdf.py` | 多页合成 PDF |
|
||||
| `check.py` | 成品 PDF 检验 |
|
||||
|
||||
## 已知边界
|
||||
|
||||
- 纸张出画面的部分无法还原,角点可外扩到画面外。
|
||||
- 不为凑标准比例拉坐标;比例偏离通常是取点不准或纸张非该规格。
|
||||
- 拍摄时四边各留 3%~5% 背景余量。
|
||||
@@ -0,0 +1,202 @@
|
||||
"""PDF 产出的通用质量检验(渲染真实页面后评估)。
|
||||
|
||||
检验对象是最终交付的 PDF,不是中间图:把每页按固定 DPI 渲染成位图,
|
||||
在渲染结果上做统计判定,所见即交付物。
|
||||
|
||||
检验项:
|
||||
1. 页数与源图数一致
|
||||
2. 有效内容分辨率(页面渲染后纸面区域的像素尺寸)
|
||||
3. 纸张比例失真(纸面外接框的宽高比,对照页面书写比例)
|
||||
4. 纸面外背景残留(边带亮度显著低于纸面)
|
||||
5. 内容贴边被切(页边存在成片文字级暗像素)
|
||||
|
||||
判据全部基于该页自身像素分布自适应(Otsu / 分位数),不含针对特定文档的常量。
|
||||
|
||||
用法:
|
||||
python3 doc_deskew/check.py 结果.pdf [--expect-pages 2] [--dpi 100]
|
||||
python3 doc_deskew/check.py 结果.pdf --render # 导出渲染图供目视
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
|
||||
def render(pdf, dpi=100, outdir='.tmp/pdfcheck'):
|
||||
os.makedirs(outdir, exist_ok=True)
|
||||
for f in os.listdir(outdir):
|
||||
if f.startswith('page'):
|
||||
os.remove(os.path.join(outdir, f))
|
||||
base = os.path.join(outdir, 'page')
|
||||
if shutil.which('pdftoppm'):
|
||||
subprocess.run(['pdftoppm', '-r', str(dpi), '-png', pdf, base], check=True)
|
||||
else: # 退路:pypdfium2
|
||||
import pypdfium2 as pdfium
|
||||
doc = pdfium.PdfDocument(pdf)
|
||||
scale = dpi / 72
|
||||
for i in range(len(doc)):
|
||||
doc[i].render(scale=scale).to_pil().save('%s-%d.png' % (base, i + 1))
|
||||
files = sorted(f for f in os.listdir(outdir) if f.startswith('page') and f.endswith('.png'))
|
||||
return [os.path.join(outdir, f) for f in files]
|
||||
|
||||
|
||||
def otsu(vals):
|
||||
v = np.asarray(vals, dtype=np.float64).ravel()
|
||||
if v.size == 0:
|
||||
return 128.0
|
||||
hist, edges = np.histogram(v, bins=64)
|
||||
centers = (edges[:-1] + edges[1:]) / 2.0
|
||||
total = hist.sum()
|
||||
w0 = np.cumsum(hist)
|
||||
w1 = total - w0
|
||||
m0 = np.cumsum(hist * centers)
|
||||
mt = m0[-1]
|
||||
with np.errstate(divide='ignore', invalid='ignore'):
|
||||
score = (mt * w0 / total - m0) ** 2 / (w0 * w1 / total ** 2)
|
||||
score = np.nan_to_num(score)
|
||||
return float(centers[int(np.argmax(score))])
|
||||
|
||||
|
||||
def analyse(img):
|
||||
g = np.asarray(img.convert('L')).astype(np.float32)
|
||||
h, w = g.shape
|
||||
res = {'w': w, 'h': h, 'ratio': w / h}
|
||||
|
||||
# 纸面亮度:取全图高分位(纸面是主体亮区)
|
||||
res['paper'] = float(np.percentile(g, 80))
|
||||
# 背景亮度:低分位
|
||||
res['back'] = float(np.percentile(g, 2))
|
||||
# 内容区阈值
|
||||
res['ink'] = min(otsu(g), res['paper'] * 0.8)
|
||||
|
||||
# 纸面内容框:A4 页面上纸面之外是纯白留白,故"非纯白"区域即实际纸面
|
||||
# 用相对亮度判定,避免把扫描白纸的轻微灰底误判成内容
|
||||
flat = float(np.percentile(g, 99.5))
|
||||
nonwhite = g < (flat - 8)
|
||||
row_frac = nonwhite.mean(axis=1)
|
||||
col_frac = nonwhite.mean(axis=0)
|
||||
# 取占比超过 5% 的连续范围作为纸面主体
|
||||
rows = np.where(row_frac > 0.05)[0]
|
||||
cols = np.where(col_frac > 0.05)[0]
|
||||
if rows.size > 4 and cols.size > 4:
|
||||
res['paper_box'] = (int(cols[0]), int(rows[0]), int(cols[-1]), int(rows[-1]))
|
||||
pw = cols[-1] - cols[0] + 1
|
||||
ph = rows[-1] - rows[0] + 1
|
||||
res['paper_ratio'] = pw / ph
|
||||
res['paper_px'] = (int(pw), int(ph))
|
||||
else:
|
||||
res['paper_box'] = None
|
||||
res['paper_ratio'] = res['ratio']
|
||||
res['paper_px'] = (w, h)
|
||||
|
||||
# 边缘背景残留:四周窄带的平均亮度明显低于纸面亮度
|
||||
# 边带宽度按比例取,过窄会漏判
|
||||
b = max(4, int(min(w, h) * 0.012))
|
||||
border = {
|
||||
'top': float(g[:b, :].mean()), 'bottom': float(g[-b:, :].mean()),
|
||||
'left': float(g[:, :b].mean()), 'right': float(g[:, -b:].mean()),
|
||||
}
|
||||
res['border'] = border
|
||||
res['border_bad'] = [k for k, v in border.items() if v < res['paper'] * 0.80]
|
||||
# 另一路判据:边带内是否存在"整行整列偏暗"的条带(纸外背景)
|
||||
edge_dark = {}
|
||||
for k, band in (('top', g[:b, :]), ('bottom', g[-b:, :]),
|
||||
('left', g[:, :b]), ('right', g[:, -b:])):
|
||||
edge_dark[k] = float((band < res['paper'] * 0.6).mean())
|
||||
res['edge_dark'] = edge_dark
|
||||
|
||||
# 内容贴边:最外窄带内成片文字级暗像素 <=> 内容被切
|
||||
m = max(2, int(min(w, h) * 0.003))
|
||||
cut = []
|
||||
for k, band in (('top', g[:m, :]), ('bottom', g[-m:, :]),
|
||||
('left', g[:, :m]), ('right', g[:, -m:])):
|
||||
frac = float((band < res['ink']).mean())
|
||||
if frac > 0.05:
|
||||
cut.append((k, frac))
|
||||
res['cut'] = cut
|
||||
return res
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument('pdf')
|
||||
ap.add_argument('--expect-pages', type=int, default=None)
|
||||
ap.add_argument('--dpi', type=int, default=100)
|
||||
ap.add_argument('--min-short', type=int, default=800)
|
||||
ap.add_argument('--ratio-tol', type=float, default=0.08)
|
||||
ap.add_argument('--render', action='store_true')
|
||||
args = ap.parse_args()
|
||||
|
||||
if not os.path.exists(args.pdf):
|
||||
raise SystemExit('找不到 PDF: %s' % args.pdf)
|
||||
|
||||
files = render(args.pdf, args.dpi)
|
||||
print('PDF: %s' % args.pdf)
|
||||
print('文件大小: %.0f KB' % (os.path.getsize(args.pdf) / 1024))
|
||||
print('页数: %d' % len(files))
|
||||
|
||||
ok = True
|
||||
if args.expect_pages is not None:
|
||||
good = len(files) == args.expect_pages
|
||||
ok &= good
|
||||
print(' [%s] 页数与源图一致(期望 %d,实际 %d)'
|
||||
% ('OK' if good else 'XX', args.expect_pages, len(files)))
|
||||
|
||||
for i, f in enumerate(files, 1):
|
||||
img = Image.open(f)
|
||||
r = analyse(img)
|
||||
print('\n第 %d 页 渲染 %dx%d px @%ddpi' % (i, r['w'], r['h'], args.dpi))
|
||||
|
||||
# 纸张实际像素尺寸(按渲染图里纸面外接框估算,换算回原分辨率)
|
||||
if r['paper_box']:
|
||||
x0, y0, x1, y1 = r['paper_box']
|
||||
scale = 1.0 # 渲染已是实际像素
|
||||
short = min(x1 - x0, y1 - y0)
|
||||
good = short >= args.min_short * args.dpi / 150.0
|
||||
ok &= good
|
||||
print(' [%s] 纸面短边 %d px(下限 %d)'
|
||||
% ('OK' if good else 'XX', short,
|
||||
int(args.min_short * args.dpi / 150.0)))
|
||||
|
||||
# 纸张比例本身不是硬性标准:非 A4 材料(Letter / 16K / 票据)
|
||||
# 塞进 A4 页面时必然有留白,纸张比例 != 页面比例是正常的。
|
||||
# 这里只做"提示",判错交给内容贴边与背景残留两项。
|
||||
dev = abs(r['paper_ratio'] - r['ratio']) / r['ratio'] * 100
|
||||
note = '' if dev <= args.ratio_tol else '(留白 %.1f%%,非 A4 纸张属正常)' % dev
|
||||
print(' [--] 纸张比例 %.3f(页面 %.3f)%s'
|
||||
% (r['paper_ratio'], r['ratio'], note))
|
||||
else:
|
||||
print(' [XX] 未能识别纸面区域')
|
||||
ok = False
|
||||
|
||||
bad_dark = [k for k, v in r.get('edge_dark', {}).items() if v > 0.35]
|
||||
good = (not r['border_bad']) and (not bad_dark)
|
||||
ok &= good
|
||||
detail = ', '.join('%s=%.0f' % (k, v) for k, v in r['border'].items())
|
||||
print(' [%s] 边缘背景残留 %s(纸面 %.0f / 背景 %.0f)'
|
||||
% ('OK' if good else 'XX',
|
||||
'无' if good else '、'.join(r['border_bad']), r['paper'], r['back']))
|
||||
if not good:
|
||||
print(' 边带亮度: %s' % detail)
|
||||
if bad_dark:
|
||||
print(' 偏高暗占比: %s'
|
||||
% '、'.join('%s %.0f%%' % (k, r['edge_dark'][k] * 100) for k in bad_dark))
|
||||
|
||||
good = not r['cut']
|
||||
ok &= good
|
||||
print(' [%s] 内容贴边 %s'
|
||||
% ('OK' if good else 'XX',
|
||||
'、'.join('%s %.1f%%' % (k, v * 100) for k, v in r['cut']) if r['cut'] else '无'))
|
||||
|
||||
print('\n总判定:%s' % ('全部通过' if ok else '存在不达标项'))
|
||||
if args.render:
|
||||
print('渲染图: .tmp/pdfcheck/')
|
||||
return 0 if ok else 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,45 @@
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
import sys
|
||||
|
||||
FONT = '/usr/share/fonts/opentype/noto/NotoSerifCJK-Bold.ttc'
|
||||
|
||||
# 网格配色:100px 红线(主线,带坐标刻度)+ 50px 蓝线(辅助),两者同宽,
|
||||
# 只靠颜色分主次;线太细时缩略图上看不见,所以不靠粗细区分。
|
||||
COLOR_MAJOR = (255, 0, 0, 110)
|
||||
COLOR_MINOR = (0, 96, 255, 70)
|
||||
LINE_WIDTH = 2
|
||||
|
||||
|
||||
def draw_grid_on(im, step=50, major=100):
|
||||
"""在原图上叠加坐标网格,返回同一个 Image 对象(不落盘)。"""
|
||||
W, H = im.size
|
||||
d = ImageDraw.Draw(im, 'RGBA')
|
||||
try:
|
||||
f = ImageFont.truetype(FONT, 18)
|
||||
except Exception:
|
||||
f = ImageFont.load_default()
|
||||
for x in range(0, W, step):
|
||||
d.line([(x, 0), (x, H)],
|
||||
fill=COLOR_MAJOR if x % major == 0 else COLOR_MINOR,
|
||||
width=LINE_WIDTH)
|
||||
for y in range(0, H, step):
|
||||
d.line([(0, y), (W, y)],
|
||||
fill=COLOR_MAJOR if y % major == 0 else COLOR_MINOR,
|
||||
width=LINE_WIDTH)
|
||||
# 坐标数字:每 100px 在顶部和左侧标注
|
||||
for x in range(0, W, major):
|
||||
d.rectangle([x + 1, 1, x + 38, 21], fill=(255, 255, 255, 220))
|
||||
d.text((x + 3, 1), str(x), fill=(200, 0, 0), font=f)
|
||||
for y in range(0, H, major):
|
||||
d.rectangle([1, y + 1, 46, y + 21], fill=(255, 255, 255, 220))
|
||||
d.text((2, y + 1), str(y), fill=(0, 0, 200), font=f)
|
||||
return im
|
||||
|
||||
|
||||
def draw_grid(src, dst, step=50, major=100):
|
||||
im = draw_grid_on(Image.open(src).convert('RGB'), step, major)
|
||||
im.save(dst)
|
||||
print('written', dst, im.size)
|
||||
|
||||
if __name__ == '__main__':
|
||||
draw_grid(sys.argv[1], sys.argv[2])
|
||||
@@ -0,0 +1,81 @@
|
||||
"""纯 numpy 单应变换:等价于 cv2.warpPerspective,只依赖 Pillow + numpy。
|
||||
|
||||
用法:
|
||||
python homography.py in.jpg out.png --quad x1,y1 x2,y2 x3,y3 x4,y4
|
||||
四角顺序:左上、右上、右下、左下。不给 --quad 时按整幅图重采样。
|
||||
"""
|
||||
import argparse
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
|
||||
def _solve_h(src, dst):
|
||||
A = []
|
||||
for (x, y), (u, v) in zip(src, dst):
|
||||
A.append([x, y, 1, 0, 0, 0, -u * x, -u * y, -u])
|
||||
A.append([0, 0, 0, x, y, 1, -v * x, -v * y, -v])
|
||||
_, _, vt = np.linalg.svd(np.asarray(A, dtype=np.float64))
|
||||
return vt[-1].reshape(3, 3)
|
||||
|
||||
|
||||
def warp_perspective(img, quad, out_size=None, fill=(255, 255, 255)):
|
||||
arr = np.asarray(img.convert('RGB') if isinstance(img, Image.Image) else img)
|
||||
quad = np.asarray(quad, dtype=np.float64)
|
||||
tl, tr, br, bl = quad
|
||||
if out_size is None:
|
||||
w = int(round(max(np.linalg.norm(tr - tl), np.linalg.norm(br - bl))))
|
||||
h = int(round(max(np.linalg.norm(bl - tl), np.linalg.norm(br - tr))))
|
||||
out_size = (w, h)
|
||||
out_w, out_h = out_size
|
||||
dst = np.array([[0, 0], [out_w - 1, 0], [out_w - 1, out_h - 1], [0, out_h - 1]],
|
||||
dtype=np.float64)
|
||||
Hinv = np.linalg.inv(_solve_h(quad, dst))
|
||||
xs, ys = np.meshgrid(np.arange(out_w), np.arange(out_h))
|
||||
dst_h = np.stack([xs.ravel(), ys.ravel(), np.ones(xs.size)]).astype(np.float64)
|
||||
src_h = Hinv @ dst_h
|
||||
sx = src_h[0] / src_h[2]
|
||||
sy = src_h[1] / src_h[2]
|
||||
h, w = arr.shape[:2]
|
||||
valid = (sx >= 0) & (sx <= w - 1) & (sy >= 0) & (sy <= h - 1)
|
||||
sx = np.clip(sx, 0, w - 1); sy = np.clip(sy, 0, h - 1)
|
||||
x0 = np.floor(sx).astype(np.int32); x1 = np.minimum(x0 + 1, w - 1)
|
||||
y0 = np.floor(sy).astype(np.int32); y1 = np.minimum(y0 + 1, h - 1)
|
||||
fx = (sx - x0)[:, None]; fy = (sy - y0)[:, None]
|
||||
a = arr[y0, x0].astype(np.float64); b = arr[y0, x1].astype(np.float64)
|
||||
c = arr[y1, x0].astype(np.float64); d = arr[y1, x1].astype(np.float64)
|
||||
out = (a * (1 - fx) * (1 - fy) + b * fx * (1 - fy) +
|
||||
c * (1 - fx) * fy + d * fx * fy)
|
||||
out[~valid] = fill
|
||||
out = np.clip(out, 0, 255).astype(np.uint8).reshape(out_h, out_w, -1)
|
||||
return Image.fromarray(out)
|
||||
|
||||
|
||||
def trim(img, px=3):
|
||||
w, h = img.size
|
||||
px = max(0, min(px, (min(w, h) - 1) // 2))
|
||||
return img.crop((px, px, w - px, h - px))
|
||||
|
||||
|
||||
def brighten(img, target=245, pct=97):
|
||||
arr = np.asarray(img.convert('RGB')).astype(np.float32)
|
||||
hi = np.percentile(arr, pct)
|
||||
if hi > 1:
|
||||
arr = np.clip(arr * (target / hi), 0, 255)
|
||||
return Image.fromarray(arr.astype(np.uint8))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument('src'); ap.add_argument('dst')
|
||||
ap.add_argument('--quad', nargs=4, metavar='x,y')
|
||||
ap.add_argument('--trim', type=int, default=3)
|
||||
a = ap.parse_args()
|
||||
im = Image.open(a.src).convert('RGB')
|
||||
if a.quad:
|
||||
quad = [tuple(float(v) for v in p.split(',')) for p in a.quad]
|
||||
else:
|
||||
w, h = im.size
|
||||
quad = [(0, 0), (w - 1, 0), (w - 1, h - 1), (0, h - 1)]
|
||||
out = trim(brighten(warp_perspective(im, quad)), a.trim)
|
||||
out.save(a.dst)
|
||||
print('written %s %dx%d' % (a.dst, out.size[0], out.size[1]))
|
||||
@@ -0,0 +1,25 @@
|
||||
"""多张图等比缩放居中,合并为一个 PDF。默认 A4 纵向 @150dpi。"""
|
||||
import sys
|
||||
from PIL import Image
|
||||
|
||||
A4_W, A4_H = 1240, 1754
|
||||
MARGIN = 40
|
||||
DPI = 150
|
||||
|
||||
|
||||
def fit_page(path):
|
||||
im = Image.open(path).convert('RGB')
|
||||
bw, bh = A4_W - MARGIN * 2, A4_H - MARGIN * 2
|
||||
s = min(bw / im.width, bh / im.height)
|
||||
nw, nh = max(1, int(round(im.width * s))), max(1, int(round(im.height * s)))
|
||||
im = im.resize((nw, nh), Image.LANCZOS)
|
||||
page = Image.new('RGB', (A4_W, A4_H), 'white')
|
||||
page.paste(im, ((A4_W - nw) // 2, (A4_H - nh) // 2))
|
||||
return page
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
*srcs, out = sys.argv[1:]
|
||||
pages = [fit_page(p) for p in srcs]
|
||||
pages[0].save(out, 'PDF', resolution=DPI, save_all=True, append_images=pages[1:])
|
||||
print('written %s (%d pages)' % (out, len(pages)))
|
||||
@@ -0,0 +1,416 @@
|
||||
#!/usr/bin/env python3
|
||||
"""文档照片 -> 校正 PDF:全流程串起来的一站式脚本。
|
||||
|
||||
把原来手工分步的活(网格图 -> 读角点 -> 落盘 -> 回画确认 -> 出 PDF -> 检验)
|
||||
压成几条命令,且**产物都落在 out/ 里按序号命名**:
|
||||
|
||||
out/1-网格-<原图名>.png 每页的坐标网格图(读角点用)
|
||||
out/1-角标-<原图名>.png 每页角点回画图(原图 + 网格 + 四角标注,核查是否贴纸边)
|
||||
out/1-成品-<原图名>.png 每页矫正后的页面图
|
||||
out/corners.json 角点坐标(落盘,跨会话可用)
|
||||
out/<名字>.pdf 最终 PDF
|
||||
|
||||
角点约定(顺序固定,别写反):
|
||||
左上 ; 右上 ; 右下 ; 左下 —— 屏幕坐标,原点在图片左上角,单位像素
|
||||
|
||||
子命令:
|
||||
prepare 出网格图 + 生成 corners.json 模板(坐标留空待填)
|
||||
set 把某一页的四角坐标写进 corners.json(可反复调用)
|
||||
build 回画角标图 + 校验 + 出 PDF + 出成品图 + PDF 检验,一次跑完
|
||||
all prepare + build 合体(角点已存在则直接 build)
|
||||
check 复检已有 PDF(只渲染检验,不重新出件)
|
||||
|
||||
典型用法(脚本用绝对路径调用:cwd 是会话任务目录,不是本目录):
|
||||
# 1) 出网格图
|
||||
python3 /workspace/skills/document-photo-to-pdf/doc_deskew/pipeline.py prepare 图1.jpg 图2.jpg
|
||||
# 2) 看 out/1-网格-图1.png,把坐标写进文件
|
||||
python3 /workspace/skills/document-photo-to-pdf/doc_deskew/pipeline.py set "图1.jpg" --quad "150,360;1020,355;1050,1690;90,1660"
|
||||
python3 /workspace/skills/document-photo-to-pdf/doc_deskew/pipeline.py set "图2.jpg" --quad "120,345;1010,345;1010,1710;120,1710"
|
||||
# 3) 一路出 PDF
|
||||
python3 /workspace/skills/document-photo-to-pdf/doc_deskew/pipeline.py build --out 合同_校正.pdf
|
||||
|
||||
# 想一步到位(角点已落盘):
|
||||
python3 /workspace/skills/document-photo-to-pdf/doc_deskew/pipeline.py all 图1.jpg 图2.jpg --out 合同_校正.pdf
|
||||
|
||||
# 列出 / 检查已落盘角点
|
||||
python3 /workspace/skills/document-photo-to-pdf/doc_deskew/pipeline.py show
|
||||
|
||||
退出码:0 全部通过;2 角点校验未通过(已出件但需人工判断);3 PDF 检验未通过。
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, HERE)
|
||||
|
||||
# 提示里回显的命令:cwd 是会话任务目录,必须用脚本绝对路径,写相对的跑不起来
|
||||
SELF = 'python3 ' + os.path.join(HERE, 'pipeline.py')
|
||||
|
||||
OUT_DIR = 'out'
|
||||
CORNERS = os.path.join(OUT_DIR, 'corners.json')
|
||||
LABELS = ('左上', '右上', '右下', '左下')
|
||||
|
||||
IMG_EXT = ('.jpg', '.jpeg', '.png', '.webp', '.bmp', '.tif', '.tiff')
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 基础工具
|
||||
|
||||
def natural_key(name):
|
||||
return [int(t) if t.isdigit() else t.lower()
|
||||
for t in re.split(r'(\d+)', os.path.basename(name))]
|
||||
|
||||
|
||||
def quad_to_str(quad):
|
||||
return ';'.join('%g,%g' % (p[0], p[1]) for p in quad)
|
||||
|
||||
|
||||
def load_corners(path=CORNERS):
|
||||
if not os.path.exists(path):
|
||||
return {}
|
||||
with open(path, encoding='utf-8') as f:
|
||||
raw = json.load(f)
|
||||
out = {}
|
||||
for name, v in raw.items():
|
||||
if isinstance(v, dict):
|
||||
v = v.get('quad') or v.get('corners')
|
||||
if not v:
|
||||
continue
|
||||
out[name] = [(float(p[0]), float(p[1])) for p in v]
|
||||
return out
|
||||
|
||||
|
||||
def save_corners(data, path=CORNERS):
|
||||
os.makedirs(os.path.dirname(os.path.abspath(path)) or '.', exist_ok=True)
|
||||
tmp = path + '.tmp'
|
||||
with open(tmp, 'w', encoding='utf-8') as f:
|
||||
json.dump({k: [[int(c) if float(c).is_integer() else c for c in p]
|
||||
for p in v] for k, v in data.items()},
|
||||
f, ensure_ascii=False, indent=2)
|
||||
f.write('\n')
|
||||
os.replace(tmp, path)
|
||||
|
||||
|
||||
def parse_quad(text):
|
||||
quad = []
|
||||
for pt in text.replace(';', ';').split(';'):
|
||||
pt = pt.strip()
|
||||
if not pt:
|
||||
continue
|
||||
xy = pt.replace(' ', '').split(',')
|
||||
if len(xy) != 2:
|
||||
raise SystemExit('角点格式不对:%r(应为 x,y)' % pt)
|
||||
try:
|
||||
quad.append((float(xy[0]), float(xy[1])))
|
||||
except ValueError:
|
||||
raise SystemExit('角点不是数字:%r' % pt)
|
||||
if len(quad) != 4:
|
||||
raise SystemExit('角点必须 4 个(左上;右上;右下;左下),实际 %d 个' % len(quad))
|
||||
return quad
|
||||
|
||||
|
||||
def collect_images(args):
|
||||
"""参数里的图片 + 当前目录全部图片(去重、按自然序)。"""
|
||||
names = list(args)
|
||||
if not names:
|
||||
names = [f for f in os.listdir('.')
|
||||
if f.lower().endswith(IMG_EXT) and os.path.isfile(f)]
|
||||
seen, out = set(), []
|
||||
for n in names:
|
||||
if n not in seen:
|
||||
seen.add(n)
|
||||
out.append(n)
|
||||
if not out:
|
||||
raise SystemExit('没有找到图片:可在命令后面直接列文件名')
|
||||
missing = [n for n in out if not os.path.exists(n)]
|
||||
if missing:
|
||||
raise SystemExit('图片不存在:%s' % ', '.join(missing))
|
||||
return sorted(out, key=natural_key)
|
||||
|
||||
|
||||
def page_tag(i):
|
||||
return '%d' % i
|
||||
|
||||
|
||||
def out_path(prefix, i, name, ext='.png'):
|
||||
base = os.path.splitext(os.path.basename(name))[0]
|
||||
return os.path.join(OUT_DIR, '%s-%s-%s%s' % (page_tag(i), prefix, base, ext))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- prepare
|
||||
|
||||
def cmd_prepare(images):
|
||||
os.makedirs(OUT_DIR, exist_ok=True)
|
||||
from grid import draw_grid
|
||||
data = load_corners()
|
||||
for i, name in enumerate(images, 1):
|
||||
dst = out_path('网格', i, name)
|
||||
draw_grid(name, dst)
|
||||
data.setdefault(name, None)
|
||||
save_corners({k: v for k, v in data.items() if v})
|
||||
print('\n网格图已写入 %s/' % OUT_DIR)
|
||||
print('下一步:照着网格图读数,把角点写进 %s:' % CORNERS)
|
||||
for i, name in enumerate(images, 1):
|
||||
print(' %s set "%s" --quad "左上x,左上y;右上x,右上y;'
|
||||
'右下x,右下y;左下x,左下y"' % (SELF, name))
|
||||
return 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- set / show
|
||||
|
||||
def cmd_set(args):
|
||||
"""一次只写一张图:参数是 图片 + 一个 --quad,不批配、不错位。"""
|
||||
if '|' in args.image or ':' in args.image:
|
||||
raise SystemExit('图片名里不要带 : 或 |:%s' % args.image)
|
||||
if not os.path.exists(args.image):
|
||||
raise SystemExit('图片不存在:%s' % args.image)
|
||||
if len(args.quad) != 1:
|
||||
raise SystemExit('set 只能给一个 --quad(实际 %d 个)。一张图一次。'
|
||||
% len(args.quad))
|
||||
|
||||
name = args.image
|
||||
quad_s = args.quad[0]
|
||||
|
||||
data = load_corners()
|
||||
old = data.get(name)
|
||||
data[name] = parse_quad(quad_s)
|
||||
save_corners(data)
|
||||
if old is not None:
|
||||
print('已更新 %-36s %s(原 %s)'
|
||||
% (name, quad_to_str(data[name]), quad_to_str(old)))
|
||||
else:
|
||||
print('已写入 %-36s %s' % (name, quad_to_str(data[name])))
|
||||
print('→ %s(已存:%s)'
|
||||
% (CORNERS, '、'.join(sorted(data, key=natural_key))))
|
||||
left = [n for n in data if not os.path.exists(n)]
|
||||
if left:
|
||||
print('[注意] 这些图在 corners.json 里但文件不存在:%s' % '、'.join(left))
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_show():
|
||||
data = load_corners()
|
||||
if not data:
|
||||
print('%s 里还没有角点' % CORNERS)
|
||||
return 1
|
||||
for i, name in enumerate(sorted(data, key=natural_key), 1):
|
||||
print('%d. %-40s %s' % (i, name, quad_to_str(data[name])))
|
||||
return 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 角标图
|
||||
|
||||
def draw_marks(name, pts, dst):
|
||||
"""把四角画回原图(底图叠加与网格图相同的网格),供人工核查。"""
|
||||
from preview_quad import draw_quad
|
||||
im = draw_quad(name, pts, with_grid=True)
|
||||
im.save(dst)
|
||||
return dst
|
||||
|
||||
|
||||
def make_zooms(name, marked_png, idx, zoom):
|
||||
"""从角标图上裁出四侧放大块,命名同其它核查图的序号规则。"""
|
||||
from PIL import Image
|
||||
from preview_quad import zoom_boxes
|
||||
im = Image.open(marked_png)
|
||||
boxes = zoom_boxes(im, [(0, 0), (im.width, 0), (im.width, im.height), (0, im.height)])
|
||||
keys = list(boxes) if zoom == 'all' else [zoom]
|
||||
base = os.path.join(OUT_DIR, '%d-角标放大-%s' % (idx, os.path.basename(name)))
|
||||
base = os.path.splitext(base)[0]
|
||||
for k in keys:
|
||||
box = tuple(int(v) for v in boxes[k])
|
||||
if box[2] <= box[0] or box[3] <= box[1]:
|
||||
continue
|
||||
crop = im.crop(box)
|
||||
# 细长条按方向切成两段,否则 585x5760 没法看
|
||||
segs = []
|
||||
if k in ('left', 'right') and crop.height > crop.width * 2.2:
|
||||
h = crop.height // 2
|
||||
segs = [('上', crop.crop((0, 0, crop.width, h))),
|
||||
('下', crop.crop((0, h, crop.width, crop.height)))]
|
||||
elif k in ('top', 'bottom') and crop.width > crop.height * 2.2:
|
||||
w = crop.width // 2
|
||||
segs = [('左', crop.crop((0, 0, w, crop.height))),
|
||||
('右', crop.crop((w, 0, crop.width, crop.height)))]
|
||||
else:
|
||||
segs = [('', crop)]
|
||||
for tag, c in segs:
|
||||
f = min(3.0, max(1.0, 700.0 / max(1, c.width)))
|
||||
if f > 1.0:
|
||||
c = c.resize((int(c.width * f), int(c.height * f)), Image.LANCZOS)
|
||||
z = '%s-%s%s.png' % (base, k, tag)
|
||||
c.save(z)
|
||||
print(' 放大块 %s (%dx%d)' % (z, c.width, c.height))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- build
|
||||
|
||||
def cmd_build(images, out_pdf, paper, dpi, force, zoom):
|
||||
data = load_corners()
|
||||
if images:
|
||||
names = images
|
||||
else:
|
||||
names = sorted(data, key=natural_key)
|
||||
if not names:
|
||||
raise SystemExit('还没有角点。先跑 prepare 出网格图,再用 set 落盘角点。')
|
||||
|
||||
lacking = [n for n in names if n not in data]
|
||||
if lacking:
|
||||
raise SystemExit('这些图还没有角点:%s\n先跑 %s set ...'
|
||||
% (', '.join(lacking), SELF))
|
||||
|
||||
os.makedirs(OUT_DIR, exist_ok=True)
|
||||
from verify_quad import check as verify_quad
|
||||
from run import build, PAPERS
|
||||
|
||||
ratio = None
|
||||
if paper:
|
||||
key = paper.strip().lower()
|
||||
ratio = PAPERS.get(key)
|
||||
if ratio is None:
|
||||
try:
|
||||
ratio = float(paper)
|
||||
except ValueError:
|
||||
raise SystemExit('未知纸张:%s(可选 %s 或数字比例)'
|
||||
% (paper, '/'.join(PAPERS)))
|
||||
|
||||
# 1. 角标图 + 校验
|
||||
print('=== 步骤 1/4:回画角点(核查用) ===')
|
||||
verdicts = []
|
||||
for i, name in enumerate(names, 1):
|
||||
dst = out_path('角标', i, name)
|
||||
draw_marks(name, data[name], dst)
|
||||
print('\n第 %d 页 %s → %s' % (i, name, dst))
|
||||
ok = verify_quad(name, data[name])
|
||||
verdicts.append(ok)
|
||||
if zoom:
|
||||
make_zooms(name, dst, i, zoom)
|
||||
print('\n>>> 请打开上面这些 角标 图,逐个角确认是否压在纸角上。\n')
|
||||
|
||||
bad_pages = [i for i, ok in enumerate(verdicts, 1) if not ok]
|
||||
if bad_pages:
|
||||
print('!! 角点校验未通过:第 %s 页(上面标 [XX] 的项)。'
|
||||
% '、'.join(map(str, bad_pages)))
|
||||
if not force:
|
||||
print('已停止,未出件。按上面的提示调整角点,再重跑 set + build。')
|
||||
return 2
|
||||
print('已按 --force 继续出件:结果需人工确认,不能当作校验通过交付。\n')
|
||||
|
||||
# 2. 出 PDF
|
||||
print('=== 步骤 2/4:透视矫正 + 合成 PDF ===')
|
||||
workdir = os.path.join(OUT_DIR, '_pages')
|
||||
specs = ['%s:%s' % (n, quad_to_str(data[n])) for n in names]
|
||||
pages = build(specs, out_pdf, workdir, ratio)
|
||||
|
||||
# 成品图按页序号重命名进 out/
|
||||
for i, (name, page) in enumerate(zip(names, pages), 1):
|
||||
dst = out_path('成品', i, name)
|
||||
os.replace(page, dst)
|
||||
print(' 成品图 %s' % dst)
|
||||
|
||||
# 3. PDF 检验
|
||||
print('\n=== 步骤 3/4:最终 PDF 检验 ===')
|
||||
rc = subprocess.run([sys.executable, os.path.join(HERE, 'check.py'), out_pdf,
|
||||
'--dpi', str(dpi), '--expect-pages', str(len(names))]).returncode
|
||||
|
||||
# 4. 汇总
|
||||
bad = bad_pages
|
||||
print('\n=== 步骤 4/4:汇总 ===')
|
||||
print('PDF :%s(%.0f KB,%d 页)' % (out_pdf, os.path.getsize(out_pdf) / 1024, len(names)))
|
||||
print('角点校验 :%s' % ('全部通过' if not bad else '第 %s 页未通过' % '、'.join(map(str, bad))))
|
||||
print('PDF 检验 :%s' % ('通过' if rc == 0 else '未通过'))
|
||||
print('核查材料 :')
|
||||
for i, name in enumerate(names, 1):
|
||||
print(' %s %s %s' % (out_path('网格', i, name), out_path('角标', i, name),
|
||||
out_path('成品', i, name)))
|
||||
if bad or rc != 0:
|
||||
print('注意:以上为原样结果,未做任何自动修正。')
|
||||
return 2 if bad else 3
|
||||
return 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- check
|
||||
|
||||
def cmd_check(pdf, expect_pages, dpi):
|
||||
"""复检已有 PDF:只渲染检验,不重新校正、不改动文件。"""
|
||||
if not os.path.exists(pdf):
|
||||
raise SystemExit('找不到 PDF:%s' % pdf)
|
||||
cmd = [sys.executable, os.path.join(HERE, 'check.py'), pdf, '--dpi', str(dpi)]
|
||||
if expect_pages is not None:
|
||||
cmd += ['--expect-pages', str(expect_pages)]
|
||||
return subprocess.run(cmd).returncode
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- main
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(
|
||||
description='文档照片 -> 校正 PDF 全流程脚本',
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
epilog=__doc__)
|
||||
sub = ap.add_subparsers(dest='cmd', required=True)
|
||||
|
||||
p = sub.add_parser('prepare', help='出网格图(out/1-网格-*.png)')
|
||||
p.add_argument('images', nargs='*', help='图片名,省略则取当前目录所有图片')
|
||||
|
||||
p = sub.add_parser('set', help='把一张图的角点写进 out/corners.json')
|
||||
p.add_argument('image', metavar='IMG', help='图片名(一次一张)')
|
||||
p.add_argument('--quad', action='append', default=[], required=True,
|
||||
metavar='左上x,左上y;右上x,右上y;右下x,右下y;左下x,左下y',
|
||||
help='这一张图的四个角点(顺序固定:左上 右上 右下 左下)')
|
||||
|
||||
p = sub.add_parser('show', help='查看已落盘角点')
|
||||
|
||||
p = sub.add_parser('check', help='复检已有 PDF(只渲染检验,不重新出件)')
|
||||
p.add_argument('pdf', metavar='PDF')
|
||||
p.add_argument('--expect-pages', type=int, default=None)
|
||||
p.add_argument('--dpi', type=int, default=100)
|
||||
|
||||
p = sub.add_parser('build', help='回画角标 + 校验 + 出 PDF + 检验')
|
||||
p.add_argument('images', nargs='*', help='图片名,省略则用 corners.json 里的全部')
|
||||
p.add_argument('--out', default='文档_校正.pdf')
|
||||
p.add_argument('--paper', default=None, help='a4/letter/16k/b5 或比例数字')
|
||||
p.add_argument('--dpi', type=int, default=100, help='PDF 检验渲染 dpi')
|
||||
p.add_argument('--force', action='store_true', help='角点校验不通过也继续')
|
||||
p.add_argument('--zoom', default=None,
|
||||
choices=['left', 'right', 'top', 'bottom', 'all'],
|
||||
help='另存边角放大块,便于细看')
|
||||
|
||||
p = sub.add_parser('all', help='prepare + build 一步到位')
|
||||
p.add_argument('images', nargs='*')
|
||||
p.add_argument('--out', default='文档_校正.pdf')
|
||||
p.add_argument('--paper', default=None)
|
||||
p.add_argument('--dpi', type=int, default=100)
|
||||
p.add_argument('--force', action='store_true')
|
||||
p.add_argument('--zoom', default=None)
|
||||
|
||||
args = ap.parse_args()
|
||||
|
||||
if args.cmd == 'prepare':
|
||||
return cmd_prepare(collect_images(args.images))
|
||||
if args.cmd == 'set':
|
||||
return cmd_set(args)
|
||||
if args.cmd == 'show':
|
||||
return cmd_show()
|
||||
if args.cmd == 'check':
|
||||
return cmd_check(args.pdf, args.expect_pages, args.dpi)
|
||||
if args.cmd == 'build':
|
||||
imgs = collect_images(args.images) if args.images else []
|
||||
return cmd_build(imgs, args.out, args.paper, args.dpi, args.force, args.zoom)
|
||||
if args.cmd == 'all':
|
||||
imgs = collect_images(args.images)
|
||||
cmd_prepare(imgs)
|
||||
data = load_corners()
|
||||
lacking = [n for n in imgs if n not in data]
|
||||
if lacking:
|
||||
print('\n这些图还没有角点,填好后重跑 build:%s' % ', '.join(lacking))
|
||||
return 2
|
||||
return cmd_build(imgs, args.out, args.paper, args.dpi, args.force, args.zoom)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,185 @@
|
||||
"""角点回画预览:把已落盘的四角画回原图,供二次确认。
|
||||
|
||||
用途:把落盘的数字角点重新变成可看的画面。
|
||||
本脚本把四边形 + 四角标记 + 边标签画回原图,让"数字"重新变成可看的画面,
|
||||
在出件前确认四条边是否真的压在纸张亮面与桌面暗面的交界线上。
|
||||
|
||||
图上元素:
|
||||
绿色四边形 —— 当前角点连线,应紧贴纸边
|
||||
红色十字 + 序号 —— 四个角点(1左上 2右上 3右下 4左下)
|
||||
黄色短刻度线 —— 每条边中点的外法线,用于看边是否贴边
|
||||
右下角文字 —— 两行:文件名 / 角点串(避开顶部/左侧刻度)
|
||||
|
||||
用法:
|
||||
python3 doc_deskew/preview_quad.py 图1.jpg 图2.jpg
|
||||
python3 doc_deskew/preview_quad.py --corners .tmp/corners.json
|
||||
python3 doc_deskew/preview_quad.py --corners .tmp/corners.json --zoom 右
|
||||
|
||||
输出:.tmp/quad_<名称>.png
|
||||
--zoom 另存右侧/左侧/上边/下边放大块,.tmp/quad_<名称>_<区域>.png
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, HERE)
|
||||
|
||||
DEFAULT_CORNERS = '.tmp/corners.json'
|
||||
OUT_DIR = '.tmp'
|
||||
|
||||
LABELS = ['1 左上', '2 右上', '3 右下', '4 左下']
|
||||
COLOR_QUAD = (0, 255, 0)
|
||||
COLOR_CORNER = (255, 40, 40)
|
||||
COLOR_EDGE = (255, 220, 0)
|
||||
|
||||
|
||||
def load_corners(path):
|
||||
with open(path, encoding='utf-8') as f:
|
||||
data = json.load(f)
|
||||
out = {}
|
||||
for name, quad in data.items():
|
||||
if isinstance(quad, dict):
|
||||
quad = quad.get('quad') or quad.get('corners')
|
||||
out[name] = [(float(p[0]), float(p[1])) for p in quad]
|
||||
return out
|
||||
|
||||
|
||||
def get_font(size=26):
|
||||
# 先找中文字体(图上要画 "1 左上" 这类标签,西文字体会变成豆腐块)
|
||||
for p in ('/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc',
|
||||
'/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc',
|
||||
'/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc',
|
||||
'/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf',
|
||||
'/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf'):
|
||||
if os.path.exists(p):
|
||||
try:
|
||||
return ImageFont.truetype(p, size)
|
||||
except Exception:
|
||||
pass
|
||||
return ImageFont.load_default()
|
||||
|
||||
|
||||
def draw_quad(img_path, pts, scale=1.0, with_grid=False):
|
||||
im = Image.open(img_path).convert('RGB')
|
||||
# 角标图默认叠上与网格图同一套网格:坐标读数与框边可以对着看
|
||||
if with_grid:
|
||||
from grid import draw_grid_on
|
||||
im = draw_grid_on(im)
|
||||
if scale != 1.0:
|
||||
im = im.resize((int(im.width * scale), int(im.height * scale)),
|
||||
Image.LANCZOS)
|
||||
d = ImageDraw.Draw(im)
|
||||
font = get_font(max(14, int(26 * min(1.0, scale + 0.15))))
|
||||
sml = get_font(max(11, int(18 * min(1.0, scale + 0.15))))
|
||||
w = max(2, int(3 * scale + 0.5))
|
||||
P = [(x * scale, y * scale) for x, y in pts]
|
||||
|
||||
# 四边形
|
||||
d.line(P + [P[0]], fill=COLOR_QUAD, width=w)
|
||||
|
||||
# 四角十字 + 序号
|
||||
r = max(10, int(22 * scale + 0.5))
|
||||
for i, (x, y) in enumerate(P):
|
||||
d.line([(x - r, y), (x + r, y)], fill=COLOR_CORNER, width=w)
|
||||
d.line([(x, y - r), (x, y + r)], fill=COLOR_CORNER, width=w)
|
||||
tx, ty = x + r + 4, y - r - 4
|
||||
d.text((tx, ty), LABELS[i], fill=COLOR_CORNER, font=sml,
|
||||
stroke_width=2, stroke_fill=(0, 0, 0))
|
||||
|
||||
# 每条边中点外法线刻度
|
||||
cx = sum(p[0] for p in P) / 4.0
|
||||
cy = sum(p[1] for p in P) / 4.0
|
||||
L = max(16, int(40 * scale + 0.5))
|
||||
for i in range(4):
|
||||
a, b = P[i], P[(i + 1) % 4]
|
||||
mx, my = (a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0
|
||||
dx, dy = mx - cx, my - cy
|
||||
n = (dx * dx + dy * dy) ** 0.5 or 1.0
|
||||
dx, dy = dx / n, dy / n
|
||||
d.line([(mx, my), (mx + dx * L, my + dy * L)],
|
||||
fill=COLOR_EDGE, width=max(2, w - 1))
|
||||
|
||||
# 右下角信息条(避开顶部/左侧的网格刻度):第一行文件名,第二行角点串
|
||||
lines = [os.path.basename(img_path),
|
||||
';'.join('%g,%g' % (p[0], p[1]) for p in pts)]
|
||||
pad = 8
|
||||
gap = 6
|
||||
tw = int(max(d.textlength(s, font=font) for s in lines))
|
||||
ascent, descent = font.getmetrics()
|
||||
line_h = ascent + descent
|
||||
th = line_h * len(lines) + gap * (len(lines) - 1)
|
||||
tx = max(pad, im.width - tw - pad * 2)
|
||||
ty = max(pad, im.height - th - pad * 2)
|
||||
d.rectangle([tx - 4, ty - 4, tx + tw + 4, ty + th + 4], fill=(0, 0, 0))
|
||||
for i, s in enumerate(lines):
|
||||
d.text((tx, ty + i * (line_h + gap)), s, fill=(255, 255, 255), font=font)
|
||||
return im
|
||||
|
||||
|
||||
def zoom_boxes(im, pts):
|
||||
"""按角点外接框给出四侧放大区域。"""
|
||||
xs = [p[0] for p in pts]
|
||||
ys = [p[1] for p in pts]
|
||||
x0, x1, y0, y1 = min(xs), max(xs), min(ys), max(ys)
|
||||
W, H = im.size
|
||||
mx = (x1 - x0) * 0.18
|
||||
my = (y1 - y0) * 0.18
|
||||
boxes = {
|
||||
'left': (max(0, x0 - mx), max(0, y0 - my), min(W, x0 + mx), min(H, y1 + my)),
|
||||
'right': (max(0, x1 - mx), max(0, y0 - my), min(W, x1 + mx), min(H, y1 + my)),
|
||||
'top': (max(0, x0 - mx), max(0, y0 - my), min(W, x1 + mx), min(H, y0 + my)),
|
||||
'bottom': (max(0, x0 - mx), max(0, y1 - my), min(W, x1 + mx), min(H, y1 + my)),
|
||||
}
|
||||
return boxes
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description='把角点画回原图做二次确认')
|
||||
ap.add_argument('images', nargs='*', help='图片文件名(角点已在 corners.json 中)')
|
||||
ap.add_argument('--corners', default=DEFAULT_CORNERS)
|
||||
ap.add_argument('--zoom', choices=['left', 'right', 'top', 'bottom', 'all'],
|
||||
default=None, help='另存某侧放大块')
|
||||
ap.add_argument('--scale', type=float, default=1.0, help='整体缩放,>1 放大')
|
||||
ap.add_argument('--out', default=None, help='输出目录,默认 .tmp')
|
||||
args = ap.parse_args()
|
||||
|
||||
data = load_corners(args.corners)
|
||||
names = args.images or list(data.keys())
|
||||
missing = [n for n in names if n not in data]
|
||||
if missing:
|
||||
raise SystemExit('corners.json 中没有这些图的角点:%s' % ', '.join(missing))
|
||||
|
||||
outdir = args.out or OUT_DIR
|
||||
os.makedirs(outdir, exist_ok=True)
|
||||
|
||||
for name in names:
|
||||
pts = data[name]
|
||||
im = draw_quad(name, pts, args.scale)
|
||||
base = os.path.splitext(os.path.basename(name))[0]
|
||||
dst = os.path.join(outdir, 'quad_%s.png' % base)
|
||||
im.save(dst)
|
||||
print('written %s (%dx%d) %s' % (dst, im.width, im.height,
|
||||
';'.join('%g,%g' % p for p in pts)))
|
||||
if args.zoom:
|
||||
boxes = zoom_boxes(im, [(x * args.scale, y * args.scale) for x, y in pts])
|
||||
keys = list(boxes) if args.zoom == 'all' else [args.zoom]
|
||||
for k in keys:
|
||||
box = tuple(int(v) for v in boxes[k])
|
||||
if box[2] <= box[0] or box[3] <= box[1]:
|
||||
continue
|
||||
crop = im.crop(box)
|
||||
f = min(3.0, max(1.0, 700.0 / max(1, crop.width)))
|
||||
if f > 1.0:
|
||||
crop = crop.resize((int(crop.width * f), int(crop.height * f)),
|
||||
Image.LANCZOS)
|
||||
z = os.path.join(outdir, 'quad_%s_%s.png' % (base, k))
|
||||
crop.save(z)
|
||||
print('written %s (%dx%d)' % (z, crop.width, crop.height))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,69 @@
|
||||
"""拉正合成的核心模块:四边形透视变换 + 按页拼版。
|
||||
|
||||
由 pipeline.py 的 build 子命令调用,不单独提供命令行入口(原来那套
|
||||
--grid/--page/--check 已分别由 prepare / build / check 接管,免得两个入口各说各话)。
|
||||
|
||||
设计原则:
|
||||
1. 不做中间校正。角点只用来定义纸张四边,几何变换一次到位,
|
||||
校正结果直接进 PDF;所有质量判定都在最终 PDF 上做。
|
||||
2. 不在流程里"自动收紧/自动修补"。这类启发式规则容易误裁内容,
|
||||
只保留能明确判定对错的检验项。
|
||||
3. 判定阈值来自每页图像自身统计,不是针对某份文档调出来的常量。
|
||||
"""
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, HERE)
|
||||
|
||||
import numpy as np
|
||||
from homography import brighten, warp_perspective
|
||||
from PIL import Image
|
||||
|
||||
# 纸张宽高比(宽/高):pipeline 与 run 共用这一份,避免两套系数漂移
|
||||
PAPERS = {'a4': 210 / 297, 'letter': 8.5 / 11, '16k': 185 / 260, 'b5': 176 / 250}
|
||||
|
||||
|
||||
def parse_page(spec):
|
||||
src, _, quad_s = spec.partition(':')
|
||||
if not src or not quad_s:
|
||||
raise SystemExit('格式应为 "图片:左上;右上;右下;左下":%s' % spec)
|
||||
quad = []
|
||||
for pt in quad_s.split(';'):
|
||||
x, y = pt.split(',')
|
||||
quad.append((float(x), float(y)))
|
||||
if len(quad) != 4:
|
||||
raise SystemExit('角点必须 4 个:%s' % spec)
|
||||
return src, quad
|
||||
|
||||
|
||||
def build(specs, out_pdf, workdir='out', ratio=None):
|
||||
"""一次几何变换得到页面图,直接合并。不做二次裁切。
|
||||
|
||||
ratio=None 时按四边形自然尺寸输出(保留照片原始比例);
|
||||
给定 ratio(如 A4=0.707)时强制映射到该纸张比例,纠正透视压缩。
|
||||
"""
|
||||
os.makedirs(workdir, exist_ok=True)
|
||||
pages = []
|
||||
for i, spec in enumerate(specs, 1):
|
||||
src, quad = parse_page(spec)
|
||||
im = Image.open(src).convert('RGB')
|
||||
if ratio is None:
|
||||
page = brighten(warp_perspective(im, quad))
|
||||
else:
|
||||
q = np.array(quad, float)
|
||||
wpx = (np.linalg.norm(q[1] - q[0]) + np.linalg.norm(q[2] - q[3])) / 2
|
||||
hpx = wpx / ratio
|
||||
page = brighten(warp_perspective(
|
||||
im, quad, out_size=(int(round(wpx)), int(round(hpx)))))
|
||||
path = os.path.join(workdir, 'p%d.png' % i)
|
||||
page.save(path)
|
||||
pages.append(path)
|
||||
nw, nh = page.size
|
||||
print(' 第 %d 页 %-28s -> %s %dx%d 比例 %.3f'
|
||||
% (i, os.path.basename(src), path, nw, nh, nw / nh))
|
||||
|
||||
subprocess.run([sys.executable, os.path.join(HERE, 'make_pdf.py')]
|
||||
+ pages + [out_pdf], check=True)
|
||||
return pages
|
||||
@@ -0,0 +1,185 @@
|
||||
"""几何校验:四角坐标是否合理覆盖了纸张。
|
||||
|
||||
不依赖图像亮度,只看几何关系,因此不受白底干扰:
|
||||
1. 四边形必须凸,且顺序为 左上→右上→右下→左下
|
||||
2. 四边形必须落在源图范围内(允许少量越界,用于角点出画面的情况)
|
||||
3. 四边形内应基本是纸面(亮像素占多数),说明没有取到桌面
|
||||
4. 沿四条边外侧一圈应是桌面(暗像素占多数),说明没有少取纸张
|
||||
|
||||
任一项失败即说明该角点需调整,并指出是哪条边。
|
||||
|
||||
用法:
|
||||
python3 doc_deskew/verify_quad.py 图.jpg "左上;右上;右下;左下"
|
||||
"""
|
||||
import argparse
|
||||
import sys
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
|
||||
def parse(qs):
|
||||
pts = []
|
||||
for pt in qs.split(';'):
|
||||
x, y = pt.split(',')
|
||||
pts.append((float(x), float(y)))
|
||||
if len(pts) != 4:
|
||||
raise SystemExit('需要 4 个角点')
|
||||
return pts
|
||||
|
||||
|
||||
def sample_map(a, pts, n=60, shrink=1.0, outward=0.0):
|
||||
"""在四边形内部取网格点(shrink<1 向内收),或在外部环带取点(outward>0)。"""
|
||||
|
||||
h, w = a.shape
|
||||
tl, tr, br, bl = [np.asarray(p, float) for p in pts]
|
||||
c = (tl + tr + br + bl) / 4.0
|
||||
if shrink != 1.0:
|
||||
tl, tr, br, bl = [c + (p - c) * shrink for p in (tl, tr, br, bl)]
|
||||
if outward > 0:
|
||||
tl, tr, br, bl = [c + (p - c) * (1 + outward) for p in (tl, tr, br, bl)]
|
||||
vals = []
|
||||
for u in np.linspace(0.03, 0.97, n):
|
||||
p1 = tl + (tr - tl) * u
|
||||
p2 = bl + (br - bl) * u
|
||||
for v in np.linspace(0.03, 0.97, n):
|
||||
x, y = p1 + (p2 - p1) * v
|
||||
xi, yi = int(round(x)), int(round(y))
|
||||
if 0 <= xi < w and 0 <= yi < h:
|
||||
vals.append(a[yi, xi])
|
||||
return np.asarray(vals)
|
||||
|
||||
|
||||
def cross(o, a, b):
|
||||
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
|
||||
|
||||
|
||||
def check(img, pts, verbose=True):
|
||||
a = np.asarray(Image.open(img).convert('L')).astype(np.float32)
|
||||
h, w = a.shape
|
||||
paper = float(np.percentile(a, 80))
|
||||
back = float(np.percentile(a, 2))
|
||||
thr = back + (paper - back) * 0.5
|
||||
ok = True
|
||||
|
||||
# 1. 凸性与顺序
|
||||
signs = [cross(pts[i], pts[(i + 1) % 4], pts[(i + 2) % 4]) for i in range(4)]
|
||||
convex = all(s > 0 for s in signs)
|
||||
if verbose:
|
||||
print(' [%s] 角点顺序/凸性' % ('OK' if convex else 'XX'))
|
||||
if not convex:
|
||||
print(' 方向不一致,顺序应为 左上→右上→右下→左下')
|
||||
ok = False
|
||||
|
||||
# 2. 越界幅度
|
||||
xs = [p[0] for p in pts]; ys = [p[1] for p in pts]
|
||||
out = [max(0, -min(xs)), max(0, max(xs) - w), max(0, -min(ys)), max(0, max(ys) - h)]
|
||||
oob = max(out) / max(w, h) * 100
|
||||
good = oob < 15
|
||||
if verbose:
|
||||
print(' [%s] 越界幅度 %.1f%%(角点出画面属正常,上限 15%%)'
|
||||
% ('OK' if good else 'XX', oob))
|
||||
ok &= good
|
||||
|
||||
# 3. 内部应是纸面(亮)
|
||||
inner = sample_map(a, pts, shrink=0.88)
|
||||
frac_paper = float((inner > thr).mean())
|
||||
good = frac_paper > 0.6
|
||||
if verbose:
|
||||
print(' [%s] 框内纸面占比 %.0f%%(应 >60%%,偏低说明取到桌面)'
|
||||
% ('OK' if good else 'XX', frac_paper * 100))
|
||||
ok &= good
|
||||
|
||||
# 4. 四条边外侧应是桌面(暗)——逐边判定,指出问题边
|
||||
names = ['上边', '右边', '下边', '左边']
|
||||
bad_edges = []
|
||||
for i in range(4):
|
||||
p1, p2 = pts[i], pts[(i + 1) % 4]
|
||||
mid = (np.asarray(p1) + np.asarray(p2)) / 2
|
||||
c = sum(np.asarray(p, float) for p in pts) / 4
|
||||
d = mid - c
|
||||
norm = np.linalg.norm(d)
|
||||
if norm < 1e-6:
|
||||
continue
|
||||
d = d / norm
|
||||
# 沿该边外侧取样
|
||||
tc = (np.asarray(p1) + np.asarray(p2)) / 2
|
||||
fracs = []
|
||||
for t in np.linspace(0.15, 0.85, 12):
|
||||
base = np.asarray(p1) + (np.asarray(p2) - np.asarray(p1)) * t
|
||||
span = max(w, h)
|
||||
for k in (span * 0.02, span * 0.035, span * 0.05): # 外移 2%%~5%% 图幅
|
||||
x, y = base + d * k
|
||||
xi, yi = int(round(x)), int(round(y))
|
||||
if 0 <= xi < w and 0 <= yi < h:
|
||||
fracs.append(a[yi, xi])
|
||||
if len(fracs) < 8:
|
||||
continue
|
||||
fracs = np.asarray(fracs)
|
||||
dark_frac = float((fracs < thr).mean())
|
||||
# 外侧大部分应是暗背景;若几乎全亮,说明该边取进了纸内,纸边被切
|
||||
if dark_frac < 0.35:
|
||||
bad_edges.append((names[i], dark_frac))
|
||||
# 5. 沿四条边内侧取样: 应全是纸面; 若混入桌面说明该边取到纸外
|
||||
outside_edges = []
|
||||
for i in range(4):
|
||||
p1, p2 = pts[i], pts[(i + 1) % 4]
|
||||
mid = (np.asarray(p1) + np.asarray(p2)) / 2
|
||||
c = sum(np.asarray(p, float) for p in pts) / 4
|
||||
d = mid - c
|
||||
norm = np.linalg.norm(d)
|
||||
if norm < 1e-6:
|
||||
continue
|
||||
d = d / norm
|
||||
vals = []
|
||||
span = max(w, h)
|
||||
for t in np.linspace(0.15, 0.85, 12):
|
||||
base = np.asarray(p1) + (np.asarray(p2) - np.asarray(p1)) * t
|
||||
for k in (span * 0.015, span * 0.03, span * 0.045):
|
||||
x, y = base - d * k # 向内
|
||||
xi, yi = int(round(x)), int(round(y))
|
||||
if 0 <= xi < w and 0 <= yi < h:
|
||||
vals.append(a[yi, xi])
|
||||
if len(vals) < 8:
|
||||
continue
|
||||
vals = np.asarray(vals)
|
||||
paper_frac = float((vals > thr).mean())
|
||||
if paper_frac < 0.75:
|
||||
outside_edges.append((names[i], paper_frac))
|
||||
good2 = not outside_edges
|
||||
|
||||
if verbose:
|
||||
if not bad_edges:
|
||||
print(' [OK] 四边外侧检测到桌面,纸边已被框住')
|
||||
else:
|
||||
# 外侧仍偏亮有两种可能:取点偏内(会切内容),或纸边本身倾斜导致
|
||||
# 固定外移采样仍落在纸内。二者无法用亮度区分,故只作提示不判错。
|
||||
print(' [--] 提示:下列边外侧仍偏亮(可能取点偏内,也可能是纸边倾斜):')
|
||||
for n, f in bad_edges:
|
||||
print(' %s 外侧纸面占比 %.0f%% → 可尝试再向外扩 3~5px 后目视确认'
|
||||
% (n, (1 - f) * 100))
|
||||
|
||||
if verbose:
|
||||
if good2:
|
||||
print(' [OK] 四边内侧均为纸面')
|
||||
else:
|
||||
print(' [XX] 下列边内侧混入桌面,说明取点落在纸外:')
|
||||
for n, f in outside_edges:
|
||||
print(' %s(内侧纸面仅 %.0f%%)→ 该边角点向内收 5px' % (n, f * 100))
|
||||
ok &= good2
|
||||
return ok
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument('img'); ap.add_argument('quad')
|
||||
a = ap.parse_args()
|
||||
pts = parse(a.quad)
|
||||
print('校验 %s 角点 %s' % (a.img, a.quad))
|
||||
ok = check(a.img, pts)
|
||||
print('\n结论:%s' % ('角点可用' if ok else '需调整上面标 XX 的项'))
|
||||
return 0 if ok else 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -87,7 +87,7 @@ output_schema:
|
||||
- `grid`:把同一目录下多张图拼成一张 contact sheet(缩略图网格)
|
||||
|
||||
## 使用说明
|
||||
通过 `skill` 的 `{"run":"image-process","args":{...}}` 调用,参数:
|
||||
通过 `skill` 的 `{"op":"run","name":"image-process","args":{...}}` 调用,参数:
|
||||
- `action`:操作类型(必填)
|
||||
- `input`:输入图片或目录(必填;相对会话工作目录的路径即可,会自动转绝对路径)
|
||||
- `output`:输出路径(建议给全;不给时自动生成 `<原名>_<动作>.<原扩展名>`,绝不覆盖原图)
|
||||
|
||||
@@ -66,7 +66,7 @@ output_schema:
|
||||
|
||||
## 调用方式
|
||||
|
||||
通过 `skill` 的 `{"run":"x2pdf","args":{...}}` 调用,参数:
|
||||
通过 `skill` 的 `{"op":"run","name":"x2pdf","args":{...}}` 调用,参数:
|
||||
- `input`:输入文件路径(必填)
|
||||
- `output`:PDF 输出路径(可选,默认与输入同名)
|
||||
- `css`:自定义 CSS 文件路径(可选,仅 md/html/txt)
|
||||
|
||||
Reference in New Issue
Block a user