跳到正文

为 OCR 和 AI 准备文档 ​

读取收据和发票的应用,通常会把照片交给 OCR(比如 Tesseract 或某个云服务),或者交给能看图的 AI 模型。可现实中的照片往往拍歪了、带着阴影,纸张周围还露出半张桌子,这会让它们都很吃力:OCR 会漏字,模型的注意力也会被背景分散。在这个示例里,用户先把页面矫正、裁好,图片再以黑白形式发出去。

PaperPic 本身不识别文字,识别由你的服务器用你选的服务完成。在你的代码发送结果之前,照片不会离开浏览器。

下面这个函数把图片发给你的服务器,服务器识别后返回找到的字段:

ts
interface Receipt {
  date: string
  merchant: string
  total: string
}

async function readReceipt(blob: Blob, type: string): Promise<Receipt> {
  const body = new FormData()
  body.append('image', blob, `receipt.${type.split('/')[1]}`)
  const response = await fetch('/api/receipts/read', { method: 'POST', body })
  if (!response.ok) {
    throw new Error(`Reading failed with status ${response.status}`)
  }
  return response.json()
}

照片一显示,编辑就已经是黑白的了,用户只需矫正页面并应用修改:

html
<label>
  收据照片
  <input id="photo" type="file" accept="image/*" capture="environment" />
</label>
<div id="viewer" style="height: 480px"></div>
<p id="status" role="status"></p>
ts
import { PaperPic } from '@paperpic/core'
import '@paperpic/core/style.css'

const input = document.querySelector<HTMLInputElement>('#photo')!
const status = document.querySelector('#status')!

const pic = new PaperPic(document.querySelector<HTMLElement>('#viewer')!, {
  alt: '你附加的收据',
  tools: [
    'perspective',
    'crop',
    'rotate',
    'finish',
    'redact',
  ],
  maxOutputSize: 2000,
})

input.addEventListener('change', () => {
  const file = input.files?.[0]
  input.value = ''
  if (file) {
    status.textContent = ''
    pic.setOptions({ src: file })
  }
})

// 黑白只算一次修改,用户可以撤销,也可以在清理里改成灰度
pic.on('load', () => {
  pic.edit()
  pic.setFinish({ mode: 'mono' })
})

pic.on('apply', async ({ blob, type }) => {
  status.textContent = '正在读取…'
  try {
    const { merchant, total } = await readReceipt(blob, type)
    status.textContent = `${merchant}:${total}`
  }
  catch {
    status.textContent = '无法读取收据'
  }
})

说明 ​

  • 对 OCR 帮助最大的是矫正:它把页面拉平,让文字行保持水平,同时裁掉桌面。打开时它会自己找到纸张,用户只要检查四个角。tools 里去掉了翻转和调整,收据基本用不上。
  • 黑白能去掉阴影和不均匀的光线,Tesseract 这类 OCR 引擎会把它们当成噪点,而且生成的 PNG 很小。不过 AI 模型也会读颜色:如果文档里有照片、印章或高亮的总额,就去掉 setFinish(),或者让用户选择灰度。
  • AI 模型会先缩小大图再读取,不少还按图片尺寸计费。最长边 2000 像素,小字依然清晰,上传也轻巧。具体请查看你所用模型或 OCR 服务的限制。
  • 如果图片要发给外部服务,用户可以先用遮盖盖住账号、签名或人脸。应用修改时,这些区域会写进像素里,所以服务永远拿不到下面的内容。始终发送应用后的结果,不要发送原图。
  • 对于 AI 模型,你的服务器可以只要所需的字段,比如商家、日期和总额,并要求以 JSON 返回,这样服务器就能原样返回 readReceipt 需要的数据。

基于 MIT 许可证发布。