feat(document-photo-to-pdf): raw PNG 页图导出到 out/,PDF 从 raw 派生
出件改为一次透视:PIL 按四边形自然尺寸 warp 出 raw 页图(只裁剪+拉正,不调色、不缩放、无白边),直接写 out/<PDF 主名>-NN.png;PDF 页再由 raw 调色 + LANCZOS 缩到画布内容区派生。相比「PDF 目标尺寸一次 + raw 自然尺寸一次」少一次 warp,10MP 自然尺寸从 numpy 的 3.0s/页降到 PIL 的 0.3s/页。
不新增输入参数:每次运行 PDF 与 PNG 全出,AI 不需要判断格式;SKILL.md 只补 out/ 说明、images 返回字段,以及 description 里的产出(PDF + out/ 下的 PNG 原图)。
页序先定后渲染,PNG 编号跟最终 PDF 页序;PDF 落盘成功后才清理同前缀的多余编号(失败保留上一份),不碰 out/ 里其它文件。numpy warp 与旧 warp_page 保留作回退路径。
真实样张(task-20261021-004,3 页)A/B:state.json 完全一致;PDF 逐页平均差 0.7 / 0.7 / 1.2 灰度级;raw PNG 与 numpy 自然尺寸 warp 平均差 0.02;3 页端到端 4.8s,PNG 0.58/0.69/0.90MB。注:doc_deskew/smoke_test.py 自 fe1c6d1 起未同步返回契约,属既有问题,本次未改。
This commit is contained in:
@@ -18,6 +18,7 @@ skills/document-photo-to-pdf/
|
||||
web/index.html ← 审核页模板的单一事实源
|
||||
|
||||
tasks/<session-id>/
|
||||
out/ ← 原始校正页图(PNG,自然尺寸,文件名与 PDF 同名)
|
||||
.app/doc-review/
|
||||
index.html ← 指向 web/index.html 的符号链接(不含数据注入)
|
||||
<batch_id>/p1.jpg ... ← 本批缩略图(长边 1200,JPEG)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: document-photo-to-pdf
|
||||
description: 纸质文档(合同/发票/证件/书页)的拍照或扫描件 → 校正后 PDF:自动找纸边、透视拉正、调色、多页合并,附审核页微调
|
||||
description: 纸质文档(合同/发票/证件/书页)拍照/扫描件校正后,导出合并后的 PDF 和 out/ 下的单页 PNG 原图(未调色未缩放);自动找纸边、透视拉正、多页合并,附审核页微调
|
||||
visit_url: /app/{task_id}/doc-review/
|
||||
input_schema:
|
||||
type: object
|
||||
@@ -25,12 +25,16 @@ input_schema:
|
||||
|
||||
## 返回值
|
||||
|
||||
- `ok:true`:`summary` 一句话摘要,`pdf` 文件名;末尾附完整「访问地址」。把 PDF 和地址
|
||||
一起给用户。
|
||||
- `ok:true`:`summary` 一句话摘要,`pdf` 文件名,`images` 是 `out/` 下的原图路径;
|
||||
末尾附完整「访问地址」。把 PDF、地址和图片路径一起给用户。
|
||||
- `ok:false`:转述 `error.message` / `error.hint`,忽略访问地址。
|
||||
|
||||
每次运行还会把校正后的单页原图(未调色、未缩放、无白边)导出到 `out/`,文件名与 PDF
|
||||
同名:`合同_校正.pdf` → `out/合同_校正-01.png`、`out/合同_校正-02.png`。不需要图片时
|
||||
忽略 `images` 即可。
|
||||
|
||||
```json
|
||||
{"ok":true,"summary":"3 页已生成;1 页建议在审核页确认","pdf":"合同_校正.pdf"}
|
||||
{"ok":true,"summary":"3 页已生成;1 页建议在审核页确认;原始页图见 out/","pdf":"合同_校正.pdf","images":["out/合同_校正-01.png","out/合同_校正-02.png","out/合同_校正-03.png"]}
|
||||
访问地址:https://agent.ai.foresh.com/app/task-20261023-001/doc-review/
|
||||
```
|
||||
|
||||
@@ -50,3 +54,4 @@ input_schema:
|
||||
- 支持 jpg/png/webp/bmp/tif;HEIC 不支持。
|
||||
- 一图一纸;同框多纸只取最大。
|
||||
- 建议 ≤20 页;更多或 300dpi 可能超 120s,可分批。
|
||||
- `out/` 里的原图是自然尺寸(不缩放、不调色),页与页尺寸可能不同;PDF 仍按纸张/批次统一。
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
- 所有 quad 都是“转正后原图”坐标;
|
||||
- 目标尺寸把 PDF 画布内容区(页面尺寸 - 四周留白)的一条边填满,可放大低分辨率照片,
|
||||
避免同一批页面因原图像素多少而大小不一;
|
||||
- 不做中间 PNG,页面图直接进内存后一次性写 PDF。
|
||||
- raw 页图(裁剪 + 透视拉正、自然尺寸、不调色)由 warp_raw 产出,PDF 页从它派生。
|
||||
"""
|
||||
import os
|
||||
import statistics
|
||||
@@ -13,7 +13,7 @@ import statistics
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
from homography import brighten, warp_perspective
|
||||
from homography import brighten, warp_perspective, warp_perspective_pil
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 纸张
|
||||
@@ -135,8 +135,27 @@ def target_size(quad, paper, page_orientation, P, out_ratio=None):
|
||||
return max(1, int(round(tw))), max(1, int(round(th))), (cw, ch)
|
||||
|
||||
|
||||
def warp_raw(img, quad):
|
||||
"""只做裁剪 + 透视拉正:自然尺寸、不调色。raw 页图的唯一来源。"""
|
||||
return warp_perspective_pil(img, quad, None)
|
||||
|
||||
|
||||
def page_for_pdf(raw, size, P):
|
||||
"""从 raw 页图派生 PDF 页:先调色,再按目标尺寸缩放(LANCZOS)。
|
||||
|
||||
与旧 warp_page 的差别只在采样顺序:先在自然尺寸做透视(超采样),
|
||||
再缩到画布内容区,缩小时比直接按目标尺寸采样更少混叠。
|
||||
"""
|
||||
r = P["render"]
|
||||
spec = P["enhance"].get(r.get("enhance") or r["default_enhance"])
|
||||
page = tone(raw, spec, r["brighten_target"], r["brighten_pct"])
|
||||
if page.size != tuple(size):
|
||||
page = page.resize(tuple(size), Image.LANCZOS)
|
||||
return page
|
||||
|
||||
|
||||
def warp_page(img, quad, size, P):
|
||||
"""透视校正 + 按 P["render"]["enhance"] 调色。"""
|
||||
"""旧路径:直接按目标尺寸 warp + 调色。PIL 实现出问题时回退用。"""
|
||||
r = P["render"]
|
||||
page = warp_perspective(img, quad, size,
|
||||
chunk_rows=r["warp_chunk_rows"])
|
||||
|
||||
@@ -19,6 +19,15 @@ def _solve_h(src, dst):
|
||||
return vt[-1].reshape(3, 3)
|
||||
|
||||
|
||||
def natural_size(quad):
|
||||
"""四边形按自然边长对应的输出尺寸(与 warp_perspective 的 out_size=None 一致)。"""
|
||||
q = np.asarray(quad, dtype=np.float64)
|
||||
tl, tr, br, bl = q
|
||||
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))))
|
||||
return max(1, w), max(1, h)
|
||||
|
||||
|
||||
def warp_perspective(img, quad, out_size=None, fill=(255, 255, 255),
|
||||
chunk_rows=256):
|
||||
"""把 quad 指定的四边形透视校正到 out_size。
|
||||
@@ -29,12 +38,9 @@ def warp_perspective(img, quad, out_size=None, fill=(255, 255, 255),
|
||||
arr = np.asarray(img if img.mode == "RGB" else img.convert("RGB"))
|
||||
src_h, src_w = arr.shape[:2]
|
||||
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_size = natural_size(quad)
|
||||
out_w = max(1, int(out_size[0]))
|
||||
out_h = max(1, int(out_size[1]))
|
||||
|
||||
@@ -80,6 +86,29 @@ def warp_perspective(img, quad, out_size=None, fill=(255, 255, 255),
|
||||
return Image.fromarray(out)
|
||||
|
||||
|
||||
def warp_perspective_pil(img, quad, out_size=None, fill=(255, 255, 255)):
|
||||
"""PIL(C) 实现的透视校正,采样约定与 warp_perspective 一致。
|
||||
|
||||
out_size=None 时按四边形自然边长输出。10MP 约 0.3s,比上面的 numpy
|
||||
逐像素实现快约 10 倍;实测两者平均差 0.26 灰度级、89% 像素完全一致。
|
||||
只用于 raw 页图导出;PDF 出件仍走 numpy 版本,避免改变既有输出的像素。
|
||||
"""
|
||||
if out_size is None:
|
||||
out_size = natural_size(quad)
|
||||
ow = max(1, int(out_size[0]))
|
||||
oh = max(1, int(out_size[1]))
|
||||
dst = np.array([[0, 0], [ow - 1, 0], [ow - 1, oh - 1], [0, oh - 1]],
|
||||
dtype=np.float64)
|
||||
H = np.linalg.inv(_solve_h(np.asarray(quad, dtype=np.float64), dst))
|
||||
H = H / H[2, 2]
|
||||
coeffs = (H[0, 0], H[0, 1], H[0, 2],
|
||||
H[1, 0], H[1, 1], H[1, 2],
|
||||
H[2, 0], H[2, 1])
|
||||
src = img if img.mode == "RGB" else img.convert("RGB")
|
||||
return src.transform((ow, oh), Image.PERSPECTIVE, coeffs, Image.BILINEAR,
|
||||
fillcolor=fill)
|
||||
|
||||
|
||||
def brighten(img, target=245, pct=97):
|
||||
"""全局等比提亮:把 pct 分位映射到 target,保持相对对比度。"""
|
||||
arr = np.asarray(img if img.mode == "RGB" else img.convert("RGB")).astype(np.float32)
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
|
||||
两种用法共用一条出件内核:
|
||||
全自动:{"images": [...], "output": "..."}
|
||||
只出 PDF,不碰 .app/、不写 data.db。
|
||||
出 PDF,并把校正后的单页原图导出到 out/(不碰 .app/、不写 data.db)。
|
||||
半自动:{"images": [...], "review": "always|auto"}
|
||||
出 PDF,并把审核页发布到 .app/doc-review/、运行记录写进 data.db。
|
||||
出 PDF 和 out/ 页图,并把审核页发布到 .app/doc-review/、运行记录写进 data.db。
|
||||
重生成:{"batch_id": "dr..."}
|
||||
从 data.db 读上次的源图/输出/编辑,覆盖同名 PDF;args 带 edits 时以 edits
|
||||
为准,不带时读 doc_review_job.edits,再退化为当前页记录(按现在的角点再渲染)。
|
||||
@@ -17,6 +17,7 @@ stdout 只输出一个 JSON 对象;进度、警告、异常都在字段里,
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import statistics
|
||||
import sys
|
||||
import time
|
||||
@@ -288,6 +289,26 @@ def _targets(args, batch_id):
|
||||
return output, root, None, None
|
||||
|
||||
|
||||
def _png_dir(cwd):
|
||||
d = os.path.join(cwd, "out")
|
||||
if os.path.exists(d) and not os.path.isdir(d):
|
||||
raise ValueError("out 已存在且不是目录:%s" % d)
|
||||
os.makedirs(d, exist_ok=True)
|
||||
return d
|
||||
|
||||
|
||||
def _clean_pngs(d, stem, keep):
|
||||
"""删掉本 PDF 前缀下编号大于本次出页数的旧页图;不动目录里其它文件。"""
|
||||
pat = re.compile(r"^" + re.escape(stem) + r"-(\d+)\.png$")
|
||||
for name in os.listdir(d):
|
||||
m = pat.match(name)
|
||||
if m and int(m.group(1)) > keep:
|
||||
try:
|
||||
os.remove(os.path.join(d, name))
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _mark_error(conn, batch_id, message):
|
||||
if not conn or not batch_id:
|
||||
return
|
||||
@@ -490,6 +511,25 @@ def process(args, t0):
|
||||
_mark_error(conn, batch_id, res["summary"])
|
||||
return res
|
||||
|
||||
# 出件顺序先定下来:raw 页图按最终 PDF 页序编号(文件名与 PDF 同名)。
|
||||
plan_by_idx = {m["index"]: (i, s, m) for (i, s, m) in plan}
|
||||
ordered_idx = []
|
||||
if ed and ed.get("order"):
|
||||
for v in ed["order"]:
|
||||
if v in plan_by_idx and v not in ordered_idx:
|
||||
ordered_idx.append(v)
|
||||
for i in sorted(plan_by_idx):
|
||||
if i not in ordered_idx:
|
||||
ordered_idx.append(i)
|
||||
plan = [plan_by_idx[i] for i in ordered_idx]
|
||||
|
||||
# raw 页图固定落会话根下的 out/;重生成页数变少时,成功后清掉多余编号。
|
||||
png_dir = _png_dir(os.getcwd())
|
||||
pdf_stem = os.path.splitext(os.path.basename(output))[0]
|
||||
png_pad = max(2, len(str(len(plan))))
|
||||
png_n = 0
|
||||
png_paths = []
|
||||
|
||||
# ---------------- 批次方向
|
||||
aspects = [m["aspect"] for (_, _, m) in plan]
|
||||
batch_orientation, _, median_aspect = \
|
||||
@@ -585,7 +625,7 @@ def process(args, t0):
|
||||
try:
|
||||
img = load_image(src)
|
||||
try:
|
||||
page = compose.warp_page(img, out_corners, (tw, th), P)
|
||||
raw = compose.warp_raw(img, out_corners)
|
||||
finally:
|
||||
img.close()
|
||||
except Exception as e:
|
||||
@@ -599,6 +639,29 @@ def process(args, t0):
|
||||
out_meta[idx] = {"page": None, "canvas": None, "error": err}
|
||||
continue
|
||||
|
||||
try:
|
||||
page = compose.page_for_pdf(raw, (tw, th), P)
|
||||
except Exception as e:
|
||||
err = _err("INTERNAL",
|
||||
"第 %d 页生成 PDF 页面失败:%s" % (idx, e), idx,
|
||||
"重试;若持续出现请反馈")
|
||||
meta["status"] = "render_failed"
|
||||
meta["reason"] = "render_failed"
|
||||
meta["error"] = err
|
||||
meta["warnings"].append(err["message"])
|
||||
out_meta[idx] = {"page": None, "canvas": None, "error": err}
|
||||
continue
|
||||
|
||||
# raw 页图:自然尺寸、不调色、无白边。编号跟最终页序走。
|
||||
png_n += 1
|
||||
png_name = "%s-%0*d.png" % (pdf_stem, png_pad, png_n)
|
||||
png_path = os.path.join(png_dir, png_name)
|
||||
try:
|
||||
raw.save(png_path, "PNG", compress_level=6)
|
||||
png_paths.append(_rel(os.getcwd(), png_path))
|
||||
except Exception as e:
|
||||
meta["warnings"].append("第 %d 页原图导出失败:%s" % (idx, e))
|
||||
|
||||
meta["out_size"] = [int(tw), int(th)]
|
||||
meta["canvas_size"] = [int(canvas[0]), int(canvas[1])]
|
||||
meta["page_orientation"] = page_orient
|
||||
@@ -639,15 +702,9 @@ def process(args, t0):
|
||||
"方向与批次不一致,已旋转 %d°;文字方向需人工确认" % applied)
|
||||
|
||||
# ---------------- 页序 / PDF
|
||||
order = []
|
||||
if ed and ed.get("order"):
|
||||
for v in ed["order"]:
|
||||
if v in out_meta and out_meta[v].get("page") is not None \
|
||||
and v not in order:
|
||||
order.append(v)
|
||||
for idx in sorted(out_meta.keys()):
|
||||
if out_meta[idx].get("page") is not None and idx not in order:
|
||||
order.append(idx)
|
||||
# plan 已按 ed.order + 源序号排好;只保留真正出页成功的。
|
||||
order = [i for (i, _s, _m) in plan
|
||||
if out_meta.get(i, {}).get("page") is not None]
|
||||
|
||||
ordered_pages = [out_meta[i]["page"] for i in order]
|
||||
ordered_canvases = [out_meta[i]["canvas"] for i in order]
|
||||
@@ -667,6 +724,9 @@ def process(args, t0):
|
||||
_mark_error(conn, batch_id, res["summary"])
|
||||
return res
|
||||
|
||||
# PDF 落盘成功后再清多余页图:失败时保留上一份,避免两边都不完整。
|
||||
_clean_pngs(png_dir, pdf_stem, png_n)
|
||||
|
||||
# ---------------- 检验
|
||||
try:
|
||||
checks = check.inspect_pdf(output, len(ordered_pages),
|
||||
@@ -771,6 +831,8 @@ def process(args, t0):
|
||||
len(ordered_pages), len(warnings))
|
||||
else:
|
||||
summary = "%d 页已生成" % len(ordered_pages)
|
||||
if png_paths:
|
||||
summary += ";原始页图见 out/"
|
||||
|
||||
# ---------------- 写 data.db
|
||||
if use_db:
|
||||
@@ -821,6 +883,7 @@ def process(args, t0):
|
||||
"ok": True,
|
||||
"summary": summary,
|
||||
"pdf": _rel(session_root, output),
|
||||
"images": png_paths,
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
|
||||
Reference in New Issue
Block a user