PiaoLedger
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
票小账 PiaoLedger —— 本地票据 MCP 工具集
火种计划 S2 参赛作品 | 赛道 01(文档工具-票据台账)+ 赛道 04(工具集成-给 Agent 加工具) 本地运行 · 数据不出云 · 双模型协同
五个工具
Tool | 做什么 | 依赖 |
| 从票据文件抽取 7 字段 JSON |
|
| 确定性台账核验(纯 Python) | 无 |
| 判断缺项 + 生成追问 |
|
| 扫描文件夹批量抽取 + 成功/失败统计 |
|
| 文件夹 → 抽取 → 核验 → 导出台账(一行闭环) |
|
Related MCP server: freeocr MCP Server
支持的输入格式
单张与批量统一走同一套格式适配层,不需要手动转图:
输入 | 处理方式 |
| 自动转 PNG(qlmanage → pdftoppm → pdf2image 降级链) |
| 直接使用(零开销) |
| 直接使用(零开销) |
| 自动转 PNG(sips → Pillow 降级链) |
编码自适应:转换层按文件魔术字节识别真实格式(不再只看扩展名),WebP 被存成
.jpg、PNG 改名等都会自动纠正为正确 MIME 再送模型,避免 LM Studio 400。
边界:多页 PDF 目前只抽第一页(单张票据场景足够),多页合并尚未支持;跨页票据请先按页拆分。
性能
指标 | 实测 |
电子发票 F1 | 99.3%(n=10) |
出租车/机打票 F1 | 95.7%(n=7) |
扫描专票 F1 | 60.3%(n=19,低分辨率扫描件) |
全量 micro-F1 | 79.5%(n=36) |
缺项召回 / 误报 | 100% / 0%(确定性兜底保证,与模型输出无关) |
单张稳态时延 | 1.05s |
批量吞吐(62 文件) | 108.6s,约 1.8s/张(含 PDF 转图) |
纯 Python 核验 | 0.08ms / 张 |
单测 | 70/70 通过(未装 openpyxl 时 xlsx 用例自动跳过) |
上述 F1 为 2026-12-01 本机复跑结果,连续两次完全一致,明细见
eval_report_p2.json(聚合指标,可复核)。 早期报告中的 100% / 100% / 81.3% 已不可复现:样本与 prompt 均未变,差别来自 LM Studio 侧模型状态,落笔以当前可复现数字为准。
快速开始
1. 安装依赖
pip install -r requirements.txt # 必装:fastmcp(已锁版本)
# 可选:openpyxl(导出 XLSX,未装自动降级 CSV)、pypdf(PDF 文本层判类型,未装则类型归为 unknown)
pip install openpyxl pypdf2. 启动 LM Studio + 加载两个模型
LM Studio → Discover → 搜索下载:
MiniCPM-OCR-1.0(OCR 抽取层)MiniCPM-V-4.7-1B(决策层)
加载后确认两个模型在 Running 状态(端口 http://localhost:1234)。
推理服务地址与模型 id 都可在 config.py 修改,或用环境变量覆盖(不设则用默认值):
环境变量 | 默认值 |
|
|
|
|
|
|
|
|
|
|
# 例:推理服务跑在局域网另一台机器上
PIAOLEDGER_LLM_BASE=http://192.168.1.10:1234/v1 python server.py3. 启动 MCP Server
cd piaoledger-mcp
python server.py
# stdio transport → MCP 客户端可直接接入4. 跑闭环演示
# 正常票据全链路 PASS + 缺项票据追问
python demo_p2.py
# 指定任意票据跑含 OCR 的完整链路
python demo_p2.py /path/to/发票.png5. 跑单测
python tests.py
# Ran 70 tests — OK(覆盖核验/批量去重/增量落盘/导出/MCP 注册层)6. 跑全量评测
python eval_p2.py
# 对 samples/ 下所有样本跑 extract_fields → 对比 ground_truth → 分组 F1批量处理
一行闭环:文件夹 → 台账
from tools import batch_folder_to_ledger
result = batch_folder_to_ledger(
folder_path="/Users/me/票据/2026Q4", # 递归扫描子目录
output_path="/Users/me/台账_2026Q4.xlsx", # 后缀决定格式:csv / xlsx / json
)
# result["batch"] → n_total_found / n_success / n_failed / total_elapsed_s
# result["export"] → path / format / n_rows / headers只抽取不导出(大目录用分片,避免超时)
from tools import batch_extract_folder
fields_all = []
offset = 0
while True:
page = batch_extract_folder(
"/Users/me/票据/2026Q4",
recursive=True,
limit=10, # 每片 10 个文件,约 20s,留足客户端超时余量
offset=offset,
)
fields_all += [r["fields"] for r in page["results"] if "fields" in r]
for f in page["failures"]:
print(f["file"], f["_error"])
if not page["has_more"]:
break
offset = page["next_offset"]分片字段:limit(每片文件数)、offset(起始位置)、返回的 has_more / next_offset。不传 limit 则一次跑完,仅适合小目录。
自动去重(两级,扫描阶段就完成):
规则 | 说明 |
衍生文件 |
|
内容重复 | 文件 md5 相同 → 只留第一个 |
返回里的 scanned_files(去重前)、skipped_derived、skipped_duplicate、n_total_found(去重后)可以直接看出省了多少。
增量落盘(中断不丢结果,可续跑)
page = batch_extract_folder(
"/Users/me/票据/2026Q4",
limit=10, offset=0,
ledger_path="/Users/me/台账.csv", # 给了就每张票处理完立即落盘
)
print(page["n_skipped_resume"]) # 续跑时跳过的已落盘文件数每处理完一个文件立即写一行并 fsync,列结构:源文件 / 发票号码 / 开票日期 / 价税合计 / 税额 / 销方名称 / 销方税号 / 购方名称 / 状态 / 备注。
失败也会记录(
状态=失败+ 错误原因),不会静默丢文件成功后
备注会提示缺失字段(如缺: 税额)同一个
ledger_path重复调用会跳过已落盘文件(resume=True),中断后从断点继续
PDF 转图缓存
转换结果按 文件 md5 + dpi + 页数 缓存,同一文件第二次直接命中:实测 0.35s → 0.00s。文件内容变化后自动失效,不需要手动清理。缓存目录默认 ~/.cache/piaoledger/converted,可用 PIAOLEDGER_CACHE_DIR 覆盖。
实战脚本:一条命令跑完整目录
分片 + 落盘 + 续跑已经封装成 CLI,不用自己写循环:
cd piaoledger-mcp
python batch_ledger.py ~/票据/2026Q4 ~/台账_2026Q4.csv --chunk 10首次运行:
📂 目录: /Users/me/票据/2026Q4
📄 台账: /Users/me/台账_2026Q4.csv
🔪 分片: 每片 10 个
🧹 去重: 扫描 62 → 唯一 45(跳过衍生 17 / 重复 0)
第 1 片 (offset=0): 成功 10 / 失败 0 / 续跑跳过 0 [15.6s]
第 2 片 (offset=10): 成功 10 / 失败 0 / 续跑跳过 0 [14.8s]
...
========================================================
✅ 完成: 共 45 个文件
本次成功 44 / 失败 1 / 续跑跳过 0
耗时 71.2s
台账 /Users/me/台账_2026Q4.csv
⚠️ 1 个文件失败(已写入台账,状态=失败):
- image_xxx.jpg: LM Studio 调用失败: HTTP 400 ...中途按 Ctrl-C 或超时中断后,重跑同一条命令即可续上:
第 1 片 (offset=0): 成功 0 / 失败 0 / 续跑跳过 10 [0.0s]
...
✅ 完成: 共 45 个文件
本次成功 34 / 失败 1 / 续跑跳过 10脚本核心循环就这些(batch_ledger.py 已封装,这里给想自己集成的):
offset = 0
while True:
page = batch_extract_folder(
folder, limit=10, offset=offset,
ledger_path="台账.csv", resume=True, progress=False,
)
if not page["has_more"]:
break
offset = page["next_offset"]参数:--chunk N 每片文件数(默认 10)、--no-recursive 不递归子目录。
批量执行带实时进度(stderr),单文件失败不影响整批(continue-on-error),失败项单独归入 failures。
发票类型(专/普)判定
发票类型(专用发票 / 普通发票 / 数电专票 / 数电普票 / 旅客运输票)不靠模型猜,按确定性优先级:
优先级 | 来源 | 说明 |
1 | 人工标注 |
|
2 | PDF 文本层 |
|
3 | 未知 | 图片/扫描件无法判定 → 标记「需人工确认」,不采信模型输出 |
抽取结果里
invoice_type为最终值,invoice_type_source∈manual/pdf-text/unknown。pypdf为可选依赖:未安装时 PDF 也归为unknown,不影响其它功能。新增人工标注:在
type_overrides.json加一行"文件名": "专用发票"即生效,批量重跑自动套用。
{ "某专票.jpg": "专用发票", "某出租票.jpg": "旅客运输票", "某普票.png": "普通发票" }实测边界:MiniCPM-OCR 对专/普几乎一律输出「普通发票」(真实专票也会判错),因此类型必须靠 PDF 文本层或人工标注,不能用模型判定。
非发票剔除:批量时按文件名/票号判为行程单等非发票的,状态=非发票、不参与核验与查重、不进入导出台账。
台账派生列
export_ledger(..., include_derived=True)(默认开启)在基础字段后追加 5 列,服务报销归类 / 进项抵扣 / 对账:
列 | 规则 |
发票类型 | 人工标注 / PDF 文本层优先;20 位号补「数电」前缀;其余按票号位数兜底 |
费用类别 | 销方关键词 → 交通 / 餐饮 / 住宿 / 办公服务 / 货物采购 / 其他 |
税率档 |
|
抵扣建议 | 专票→可抵扣;旅客运输→可计算抵扣;普票→不可抵扣;未知→需人工确认 |
对账键 | `销方名称 |
export_ledger(invoices, "ledger.csv") # 默认带派生列
export_ledger(invoices, "ledger.csv", include_derived=False) # 只要原始字段采购对账若要商品级(明细行)匹配,票头字段做不到,需另抽票面明细。
导出台账(可自定义)
from exporter import export_ledger
# 默认:7 字段 + 中文列名 + 核验状态列 → CSV
export_ledger(invoices, "ledger.csv")
# 自定义列顺序 + 列名 + 不附加核验列
export_ledger(
invoices, "summary.csv",
fields=["invoice_number", "total_amount", "issue_date"],
field_aliases={"invoice_number": "Inv#", "total_amount": "Total", "issue_date": "Date"},
include_verification=False,
)
# 输出 JSON(保留原始字段 + _verify_status / _verify_anomalies)
export_ledger(invoices, "ledger.json")
# 不落文件,直接拿行列数据
data = export_ledger(invoices) # data["headers"], data["rows"]支持格式:csv(标准库)/ xlsx(openpyxl,未装自动降级 CSV)/ json。
MCP 客户端接入示例
Claude Desktop
在 Claude Desktop 的 mcpServers 配置里加:
{
"mcpServers": {
"piaoledger": {
"command": "python",
"args": ["/path/to/piaoledger-mcp/server.py"]
}
}
}FastMCP 命令行快速验证
# 看有哪些工具
fastmcp list /path/to/piaoledger-mcp/server.py
# inspect 看合规性
fastmcp inspect /path/to/piaoledger-mcp/server.py典型调用链
from tools import extract_fields, ask_missing, verify_ledger
from exporter import export_ledger
# Step 1: 抽取(PDF / 图片均可,自动转 PNG)
fields = extract_fields("餐饮发票.pdf")
# Step 2: 决策层判断
decision = ask_missing(fields) # {action, missing_fields, question}
if decision["action"] == "verify":
# Step 3a: 台账核验
result = verify_ledger(fields)
# Step 4a: 导出
export_ledger(fields, "ledger.csv")
else:
# Step 3b: 有缺项 → 追问用户补填
print(decision["question"]) # 自然中文追问文件结构
.
├── server.py # MCP Server 入口(FastMCP,注册 5 个 tool)
├── tools.py # 工具函数(含批量),纯 Python 不依赖 FastMCP
├── verify.py # 确定性台账核验规则
├── converter.py # 格式适配层:PDF/WebP/HEIC → PNG;魔术字节识别;PDF 文本层判类型;人工标注
├── exporter.py # CSV/XLSX/JSON 导出(列/别名/格式可自定义 + 派生列)
├── llm_client.py # LM Studio HTTP 调用封装
├── postprocess.py # 免税符号/日期/字符串 null 归一化
├── config.py # 模型名/端口/必填字段
├── prompts.py # EXTRACT_PROMPT + DECIDE_PROMPT
├── type_overrides.json # 人工确认的发票类型标注(专/普)
├── tests.py # 70 条单测(unittest 零依赖)
├── requirements.txt # 依赖清单(fastmcp 锁版本;openpyxl/pypdf 可选)
├── eval_report_p2.json # 全量评测聚合报告(仅指标,不含任何样本内容)
├── batch_ledger.py # 批量台账 CLI(分片 + 增量落盘 + 断点续跑)
├── demo_p2.py # 闭环演示脚本(extract → ask_missing → verify)
├── eval_p2.py # 全量分组评测脚本
├── README.md # 本文档
├── ARTIFACTS.md # 进阶规则证据链映射表
├── LICENSE # MIT
└── samples/ # 评测样本(不随仓库分发,见下方说明)关于 samples/:出于隐私考虑,真实票据样本(含企业税号/个人信息)不随仓库公开; 但聚合评测报告
eval_report_p2.json随仓库提供(只含分组 P/R/F1 与 tp/fp/fn,无文件名、无票面内容),可对照核验下表指标。 运行demo_p2.py时可直接传入图片路径:python demo_p2.py /path/to/任意发票.png(不传且无samples/时自动退化为构造字段,只演示决策 + 核验,不跑 OCR); 运行eval_p2.py前需自备samples/(样本图 +ground_truth.json,格式见脚本注释)。
核心设计纪律
模型负责理解与抽取,代码负责判定与算术。
OCR 模型 → 图片理解 → 7 字段 JSON
VLM 决策层 → 字段语义判断 → 选工具 + 追问
Python 代码 → 格式适配、算术合计、格式校验、兜底补漏、导出交付
必填口径为 6 项(
tax_amount可选):免税票票面税额是***,抽取按规则输出 null, 核验只给 warning、不判台账失败——否则合法免税发票会被误报为缺项。
两条 prompt 经过 5 轮迭代,在 36 张标注样本上验证收敛——弱提示对 MiniCPM 不敏感,硬规则 + 后处理归一化才可靠。
决策层存在「有销方就默认有购方」的系统性漏报,由 ask_missing 中的确定性兜底代码补齐(召回 77% → 100%)。
License
MIT — 火种计划 S2 参赛作品
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
Turn receipts and invoices (photos, PDFs or a zip) into checked numbers: vendor, date, currency, line items, tax and total, each field marked ok, check or missing. Doubtful documents come back flagged with reasons instead of guessed; repeated receipts are marked as duplicates. Exports CSV, line-item CSV, QuickBooks CSV or a renamed file pack. Free daily quota, no API key. Files deleted after 24 hours, never used for training.
Read printed words from receipts, forms and book pages, then export them as JSON, CSV or Excel.
Log expenses and export clean reports for tax time - your ledger never leaves your machine.
Invoice, receipt & bank statement OCR with Decimal math audit and ready-to-import Xero CSV.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceEnables extraction of structured data from documents like invoices, receipts, and bank statements using local Vision AI (Ollama) or cloud providers (Gemini), with data stored in a local SQLite database.MIT
- AlicenseNot gradedqualityBmaintenanceLets AI assistants and editors read documents on the local machine, turning PDFs, scans, invoices, receipts and bank statements into structured fields, line items and entities over stdio. Runs fully self-hosted with no cloud calls or API keys, so sensitive files never leave the user's machine.2MIT
- AlicenseNot gradedqualityBmaintenanceEnables AI clients to read receipt and invoice files, organize them with standardized filenames, append entries to an Excel-friendly CSV ledger, and search ledger records locally without network access or deletion.MIT
- AlicenseNot gradedqualityBmaintenanceEnables AI assistants to extract invoice data from existing PDFs and create EN 16931-compliant ZUGFeRD/Factur-X e-invoices or XRechnung XML locally, without uploading documents.142 npm4MIT