LayoutLM-FUNSD 是一个专门针对表单文档结构化理解的预训练模型,基于 Microsoft LayoutLM 架构在 FUNSD 数据集上完成微调。该模型的核心能力在于能同时利用文本语义和版面布局信息,对扫描文档中的文字进行精准的语义角色标注。
模型支持识别以下七类标签:非实体(O)、标题头(HEADER)、问题描述(QUESTION)、答案内容(ANSWER),以及这三类实体的开始(B-)和内部(I-)标记,实现对文档结构的完整解析。
传统 NLP 模型仅关注文本本身的语义,而 LayoutLM 的独特之处在于引入了二维位置编码机制。对于文档中的每个词,模型不仅学习其文本含义,还学习其在页面上的物理位置(x 坐标、y 坐标、宽度、高度),这使得模型能够感知"表格的哪一列"、"页面的哪个区域"等空间信息,从而更准确地理解文档结构。
部署前请确保环境满足以下配置:
pip install torch torch_npu transformers fastapi uvicorn pydantic Pillow numpy服务端启动只需要一条命令:
cd /opt/atomgit/layoutlm-funsd && python3 inference.py启动后服务会在 0.0.0.0:8000 上监听,模型自动加载到 NPU 并完成预热。如需调整端口或 NPU 设备号,可通过环境变量指定:
DEVICE_ID=1 PORT=8080 python3 inference.py服务就绪后,调用健康检查接口确认状态:
curl http://localhost:8000/health正常响应中包含设备信息、模型名称和架构类型,可据此确认部署是否成功。如果服务未就绪,可能是模型正在加载中,等待约 2~3 秒后重试即可。
模型推理的输入数据需要包含两部分:文档中的每个单词(word)及其对应的边界框坐标(box)。数据通常来源于以下两种途径:
使用 Tesseract、PaddleOCR 等工具从扫描文档图像中提取文字和坐标:
# 伪代码示例
from PIL import Image
import pytesseract
image = Image.open("invoice.png")
# OCR 返回单词列表和对应的边界框
data = pytesseract.image_to_data(image, output_type=pytesseract.Output.DICT)
words = [data["text"][i] for i in range(len(data["text"])) if data["text"][i].strip()]
boxes = [[data["left"][i], data["top"][i],
data["left"][i] + data["width"][i],
data["top"][i] + data["height"][i]]
for i in range(len(data["text"])) if data["text"][i].strip()]如果已经拥有文档的结构化数据(如 PDF 解析结果),可以直接传入:
words = ["INVOICE", "Date:", "2024-01-15", "Total:", "$1,234.56"]
boxes = [[50, 20, 200, 60], [50, 80, 120, 105],
[130, 80, 230, 105], [50, 120, 130, 145],
[140, 120, 250, 145]]import requests
api = "http://localhost:8000/inference"
payload = {
"words": ["INVOICE", "Date:", "2024-01-15"],
"boxes": [[50, 20, 200, 60], [50, 80, 120, 105], [130, 80, 230, 105]],
"max_length": 512
}
resp = requests.post(api, json=payload).json()
print("推理耗时:", resp["inference_time_ms"], "ms")
for ent in resp["entities"]:
print(f"[{ent['type']}] {ent['text']} 置信度:{ent['score']:.2%}")curl -X POST http://localhost:8000/inference \
-H "Content-Type: application/json" \
-d '{"words":["INVOICE","Date:","2024-01-15"],"boxes":[[50,20,200,60],[50,80,120,105],[130,80,230,105]]}'import requests
try:
resp = requests.post("http://localhost:8000/inference", json={
"words": ["Test"],
"boxes": [[0, 0, 100, 100]],
"max_length": 512
}, timeout=30)
if resp.status_code == 200:
result = resp.json()
if result["success"]:
print("推理成功:", result["entities"])
else:
print("推理失败")
elif resp.status_code == 422:
print("输入验证错误:", resp.json()["detail"])
elif resp.status_code == 503:
print("模型未加载,请稍后重试")
else:
print(f"服务异常: {resp.status_code}")
except requests.exceptions.ConnectionError:
print("无法连接到服务,请确认服务是否启动")
except requests.exceptions.Timeout:
print("请求超时,请检查输入长度或服务负载")在 Ascend 910B 设备上的实测数据:
该模型在 FUNSD 评测集上取得的指标如下:
| 类别 | 精确率 | 召回率 | F1 分数 |
|---|---|---|---|
| Answer | 73.48% | 80.84% | 76.99% |
| Header | 44.29% | 52.10% | 47.88% |
| Question | 82.11% | 84.04% | 83.06% |
| 整体 | 75.99% | 80.83% | 78.66% |
模型在 Question 和 Answer 类别上表现较好,Header 类别由于样本量较少(119 个)指标相对偏低。整体准确率达到 81.06%。
GET /health
返回服务状态和模型信息。
POST /inference
请求体:
| 字段 | 类型 | 必填 | 说明 |
|---|---|---|---|
| words | List[str] | 是 | 文档中的单词列表 |
| boxes | List[List[int]] | 是 | 对应的边界框坐标 [x0, y0, x1, y1] |
| max_length | int | 否 | 最大 token 长度,默认 512 |
响应体:
| 字段 | 类型 | 说明 |
|---|---|---|
| success | bool | 推理是否成功 |
| inference_time_ms | float | 推理耗时(毫秒) |
| num_tokens | int | 处理的 token 数量 |
| tokens | List[str] | 解码后的 token 列表 |
| labels | List[str] | 每个 token 的预测标签 |
| scores | List[float] | 每个 token 的置信度分数 |
| entities | List[Dict] | 聚合后的实体列表 |
| id2label | Dict[str, str] | 标签 ID 到标签名的映射 |