PP-ChatOCRv4 产线使用教程¶
1. PP-ChatOCRv4 产线介绍¶
PP-ChatOCRv4 是飞桨特色的文档和图像智能分析解决方案,结合了 LLM、MLLM 和 OCR 技术,一站式解决版面分析、生僻字、多页 pdf、表格、印章识别等常见的复杂文档信息抽取难点问题,结合文心大模型将海量数据和知识相融合,准确率高且应用广泛。本产线同时提供了灵活的服务化部署方式,支持在多种硬件上部署。不仅如此,本产线也提供了二次开发的能力,您可以基于本产线在您自己的数据集上训练调优,训练后的模型也可以无缝集成。
PP-ChatOCRv4 产线中包含版面区域检测模块、表格结构识别模块、表格分类模块、表格单元格定位模块、文本检测模块、文本识别模块、印章文本检测模块、文本图像矫正模块、文档图像方向分类模块。
PP-ChatOCRv4 产线中包含以下9个模块。每个模块均可独立进行训练和推理,并包含多个模型。有关详细信息,请点击相应模块以查看文档。
- 文档图像方向分类模块(可选)
- 文本图像矫正模块(可选)
- 版面区域检测模块
- 表格结构识别模块(可选)
- 文本检测模块
- 文本识别模块
- 文本行方向分类模块(可选)
- 公式识别模块(可选)
- 印章文本检测模块(可选)
在本产线中,您可以根据下方的基准测试数据选择使用的模型。
文档图像方向分类模块(可选):
模型 | 模型下载链接 | Top-1 Acc(%) | GPU推理耗时(ms) [常规模式 / 高性能模式] |
CPU推理耗时(ms) [常规模式 / 高性能模式] |
模型存储大小(M) | 介绍 |
---|---|---|---|---|---|---|
PP-LCNet_x1_0_doc_ori | 推理模型/训练模型 | 99.06 | 2.31 / 0.43 | 3.37 / 1.27 | 7 | 基于PP-LCNet_x1_0的文档图像分类模型,含有四个类别,即0度,90度,180度,270度 |
版面区域检测模块模型:
模型 | 模型下载链接 | mAP(0.5)(%) | GPU推理耗时(ms) [常规模式 / 高性能模式] |
CPU推理耗时(ms) [常规模式 / 高性能模式] |
模型存储大小(M) | 介绍 |
---|---|---|---|---|---|---|
PP-DocLayout-L | 推理模型/训练模型 | 90.4 | 34.6244 / 10.3945 | 510.57 / - | 123.76 M | 基于RT-DETR-L在包含中英文论文、杂志、合同、书本、试卷和研报等场景的自建数据集训练的高精度版面区域定位模型 |
PP-DocLayout-M | 推理模型/训练模型 | 75.2 | 13.3259 / 4.8685 | 44.0680 / 44.0680 | 22.578 | 基于PicoDet-L在包含中英文论文、杂志、合同、书本、试卷和研报等场景的自建数据集训练的精度效率平衡的版面区域定位模型 |
PP-DocLayout-S | 推理模型/训练模型 | 70.9 | 8.3008 / 2.3794 | 10.0623 / 9.9296 | 4.834 | 基于PicoDet-S在中英文论文、杂志、合同、书本、试卷和研报等场景上自建数据集训练的高效率版面区域定位模型 |
PicoDet_layout_1x | 推理模型/训练模型 | 86.8 | 9.03 / 3.10 | 25.82 / 20.70 | 7.4 | 基于PicoDet-1x在PubLayNet数据集训练的高效率版面区域定位模型,可定位包含文字、标题、表格、图片以及列表这5类区域 |
PicoDet_layout_1x_table | 推理模型/训练模型 | 95.7 | 8.02 / 3.09 | 23.70 / 20.41 | 7.4 M | 基于PicoDet-1x在自建数据集训练的高效率版面区域定位模型,可定位包含表格这1类区域 |
PicoDet-S_layout_3cls | 推理模型/训练模型 | 87.1 | 8.99 / 2.22 | 16.11 / 8.73 | 4.8 | 基于PicoDet-S轻量模型在中英文论文、杂志和研报等场景上自建数据集训练的高效率版面区域定位模型,包含3个类别:表格,图像和印章 |
PicoDet-S_layout_17cls | 推理模型/训练模型 | 70.3 | 9.11 / 2.12 | 15.42 / 9.12 | 4.8 | 基于PicoDet-S轻量模型在中英文论文、杂志和研报等场景上自建数据集训练的高效率版面区域定位模型,包含17个版面常见类别,分别是:段落标题、图片、文本、数字、摘要、内容、图表标题、公式、表格、表格标题、参考文献、文档标题、脚注、页眉、算法、页脚、印章 |
PicoDet-L_layout_3cls | 推理模型/训练模型 | 89.3 | 13.05 / 4.50 | 41.30 / 41.30 | 22.6 | 基于PicoDet-L在中英文论文、杂志和研报等场景上自建数据集训练的高效率版面区域定位模型,包含3个类别:表格,图像和印章 |
PicoDet-L_layout_17cls | 推理模型/训练模型 | 79.9 | 13.50 / 4.69 | 43.32 / 43.32 | 22.6 | 基于PicoDet-L在中英文论文、杂志和研报等场景上自建数据集训练的高效率版面区域定位模型,包含17个版面常见类别,分别是:段落标题、图片、文本、数字、摘要、内容、图表标题、公式、表格、表格标题、参考文献、文档标题、脚注、页眉、算法、页脚、印章 |
RT-DETR-H_layout_3cls | 推理模型/训练模型 | 95.9 | 114.93 / 27.71 | 947.56 / 947.56 | 470.1 | 基于RT-DETR-H在中英文论文、杂志和研报等场景上自建数据集训练的高精度版面区域定位模型,包含3个类别:表格,图像和印章 |
RT-DETR-H_layout_17cls | 推理模型/训练模型 | 92.6 | 115.29 / 104.09 | 995.27 / 995.27 | 470.2 | 基于RT-DETR-H在中英文论文、杂志和研报等场景上自建数据集训练的高精度版面区域定位模型,包含17个版面常见类别,分别是:段落标题、图片、文本、数字、摘要、内容、图表标题、公式、表格、表格标题、参考文献、文档标题、脚注、页眉、算法、页脚、印章 |
表格结构识别模块(可选):
模型 | 模型下载链接 | 精度(%) | GPU推理耗时(ms) [常规模式 / 高性能模式] |
CPU推理耗时(ms) [常规模式 / 高性能模式] |
模型存储大小 (M) | 介绍 |
---|---|---|---|---|---|---|
SLANet | 推理模型/训练模型 | 59.52 | 103.08 / 103.08 | 197.99 / 197.99 | 6.9 M | SLANet 是百度飞桨视觉团队自研的表格结构识别模型。该模型通过采用CPU 友好型轻量级骨干网络 PP-LCNet、高低层特征融合模块CSP-PAN、结构与位置信息对齐的特征解码模块 SLA Head,大幅提升了表格结构识别的精度和推理速度。 |
SLANet_plus | 推理模型/训练模型 | 63.69 | 140.29 / 140.29 | 195.39 / 195.39 | 6.9 M | SLANet_plus 是百度飞桨视觉团队自研的表格结构识别模型SLANet的增强版。相较于SLANet,SLANet_plus 对无线表、复杂表格的识别能力得到了大幅提升,并降低了模型对表格定位准确性的敏感度,即使表格定位出现偏移,也能够较准确地进行识别。 |
文本检测模块:
模型 | 模型下载链接 | 检测Hmean(%) | GPU推理耗时(ms) [常规模式 / 高性能模式] |
CPU推理耗时(ms) [常规模式 / 高性能模式] |
模型存储大小(M) | 介绍 |
---|---|---|---|---|---|---|
PP-OCRv5_server_det | 推理模型/训练模型 | 83.8 | 89.55 / 70.19 | 371.65 / 371.65 | 84.3 | PP-OCRv5 的服务端文本检测模型,精度更高,适合在性能较好的服务器上部署 |
PP-OCRv5_mobile_det | 推理模型/训练模型 | 79.0 | 8.79 / 3.13 | 51.00 / 28.58 | 4.7 | PP-OCRv5 的移动端文本检测模型,效率更高,适合在端侧设备部署 |
PP-OCRv4_server_det | 推理模型/训练模型 | 69.2 | 83.34 / 80.91 | 442.58 / 442.58 | 109 | PP-OCRv4 的服务端文本检测模型,精度更高,适合在性能较好的服务器上部署 |
PP-OCRv4_mobile_det | 推理模型/训练模型 | 63.8 | 8.79 / 3.13 | 51.00 / 28.58 | 4.7 | PP-OCRv4 的移动端文本检测模型,效率更高,适合在端侧设备部署 |
文本识别模块:
模型 | 模型下载链接 | 识别 Avg Accuracy(%) | GPU推理耗时(ms) [常规模式 / 高性能模式] |
CPU推理耗时(ms) [常规模式 / 高性能模式] |
模型存储大小(M) | 介绍 |
---|---|---|---|---|---|---|
PP-OCRv5_server_rec | 推理模型/训练模型 | 86.38 | 8.45/2.36 | 122.69/122.69 | 81 M | PP-OCRv5_rec 是新一代文本识别模型。该模型致力于以单一模型高效、精准地支持简体中文、繁体中文、英文、日文四种主要语言,以及手写、竖版、拼音、生僻字等复杂文本场景的识别。在保持识别效果的同时,兼顾推理速度和模型鲁棒性,为各种场景下的文档理解提供高效、精准的技术支撑。 |
PP-OCRv5_mobile_rec | 推理模型/训练模型 | 81.29 | 1.46/5.43 | 5.32/91.79 | 16 M | |
PP-OCRv4_server_rec_doc | 推理模型/训练模型 | 86.58 | 6.65 / 2.38 | 32.92 / 32.92 | 181 M | PP-OCRv4_server_rec_doc是在PP-OCRv4_server_rec的基础上,在更多中文文档数据和PP-OCR训练数据的混合数据训练而成,增加了部分繁体字、日文、特殊字符的识别能力,可支持识别的字符为1.5万+,除文档相关的文字识别能力提升外,也同时提升了通用文字的识别能力 |
PP-OCRv4_mobile_rec | 推理模型/训练模型 | 83.28 | 4.82 / 1.20 | 16.74 / 4.64 | 88 M | PP-OCRv4的轻量级识别模型,推理效率高,可以部署在包含端侧设备的多种硬件设备中 |
PP-OCRv4_server_rec | 推理模型/训练模型 | 85.19 | 6.58 / 2.43 | 33.17 / 33.17 | 151 M | PP-OCRv4的服务器端模型,推理精度高,可以部署在多种不同的服务器上 |
en_PP-OCRv4_mobile_rec | 推理模型/训练模型 | 70.39 | 4.81 / 0.75 | 16.10 / 5.31 | 66 M | 基于PP-OCRv4识别模型训练得到的超轻量英文识别模型,支持英文、数字识别 |
👉模型列表详情
* PP-OCRv5 多场景模型模型 | 模型下载链接 | 中文识别 Avg Accuracy(%) | 英文识别 Avg Accuracy(%) | 繁体中文识别 Avg Accuracy(%) | 日文识别 Avg Accuracy(%) | GPU推理耗时(ms) [常规模式 / 高性能模式] |
CPU推理耗时(ms) [常规模式 / 高性能模式] |
模型存储大小(M) | 介绍 |
---|---|---|---|---|---|---|---|---|---|
PP-OCRv5_server_rec | 推理模型/训练模型 | 86.38 | 64.70 | 93.29 | 60.35 | 1.46/5.43 | 5.32/91.79 | 81 M | PP-OCRv5_server_rec 是新一代文本识别模型。该模型致力于以单一模型高效、精准地支持简体中文、繁体中文、英文、日文四种主要语言,以及手写、竖版、拼音、生僻字等复杂文本场景的识别。在保持识别效果的同时,兼顾推理速度和模型鲁棒性,为各种场景下的文档理解提供高效、精准的技术支撑。 |
PP-OCRv5_mobile_rec | 推理模型/训练模型 | 81.29 | 66.00 | 83.55 | 54.65 | 1.46/5.43 | 5.32/91.79 | 16 M |
模型 | 模型下载链接 | 识别 Avg Accuracy(%) | GPU推理耗时(ms) [常规模式 / 高性能模式] |
CPU推理耗时(ms) [常规模式 / 高性能模式] |
模型存储大小(M) | 介绍 |
---|---|---|---|---|---|---|
PP-OCRv4_server_rec_doc | 推理模型/训练模型 | 86.58 | 6.65 / 2.38 | 32.92 / 32.92 | 91 M | PP-OCRv4_server_rec_doc是在PP-OCRv4_server_rec的基础上,在更多中文文档数据和PP-OCR训练数据的混合数据训练而成,增加了部分繁体字、日文、特殊字符的识别能力,可支持识别的字符为1.5万+,除文档相关的文字识别能力提升外,也同时提升了通用文字的识别能力 |
PP-OCRv4_mobile_rec | 推理模型/训练模型 | 83.28 | 4.82 / 1.20 | 16.74 / 4.64 | 11 M | PP-OCRv4的轻量级识别模型,推理效率高,可以部署在包含端侧设备的多种硬件设备中 |
PP-OCRv4_server_rec | 推理模型/训练模型 | 85.19 | 6.58 / 2.43 | 33.17 / 33.17 | 87 M | PP-OCRv4的服务器端模型,推理精度高,可以部署在多种不同的服务器上 |
PP-OCRv3_mobile_rec | 推理模型/训练模型 | 75.43 | 5.87 / 1.19 | 9.07 / 4.28 | 11 M | PP-OCRv3的轻量级识别模型,推理效率高,可以部署在包含端侧设备的多种硬件设备中 |
模型 | 模型下载链接 | 识别 Avg Accuracy(%) | GPU推理耗时(ms) [常规模式 / 高性能模式] |
CPU推理耗时(ms) [常规模式 / 高性能模式] |
模型存储大小(M) | 介绍 |
---|---|---|---|---|---|---|
ch_SVTRv2_rec | 推理模型/训练模型 | 68.81 | 8.08 / 2.74 | 50.17 / 42.50 | 73.9 M | SVTRv2 是一种由复旦大学视觉与学习实验室(FVL)的OpenOCR团队研发的服务端文本识别模型,其在PaddleOCR算法模型挑战赛 - 赛题一:OCR端到端识别任务中荣获一等奖,A榜端到端识别精度相比PP-OCRv4提升6%。 |
模型 | 模型下载链接 | 识别 Avg Accuracy(%) | GPU推理耗时(ms) [常规模式 / 高性能模式] |
CPU推理耗时(ms) [常规模式 / 高性能模式] |
模型存储大小(M) | 介绍 |
---|---|---|---|---|---|---|
ch_RepSVTR_rec | 推理模型/训练模型 | 65.07 | 5.93 / 1.62 | 20.73 / 7.32 | 22.1 M | RepSVTR 文本识别模型是一种基于SVTRv2 的移动端文本识别模型,其在PaddleOCR算法模型挑战赛 - 赛题一:OCR端到端识别任务中荣获一等奖,B榜端到端识别精度相比PP-OCRv4提升2.5%,推理速度持平。 |
模型 | 模型下载链接 | 识别 Avg Accuracy(%) | GPU推理耗时(ms) [常规模式 / 高性能模式] |
CPU推理耗时(ms) [常规模式 / 高性能模式] |
模型存储大小(M) | 介绍 |
---|---|---|---|---|---|---|
en_PP-OCRv4_mobile_rec | 推理模型/训练模型 | 70.39 | 4.81 / 0.75 | 16.10 / 5.31 | 6.8 M | 基于PP-OCRv4识别模型训练得到的超轻量英文识别模型,支持英文、数字识别 |
en_PP-OCRv3_mobile_rec | 推理模型/训练模型 | 70.69 | 5.44 / 0.75 | 8.65 / 5.57 | 7.8 M | 基于PP-OCRv3识别模型训练得到的超轻量英文识别模型,支持英文、数字识别 |
模型 | 模型下载链接 | 识别 Avg Accuracy(%) | GPU推理耗时(ms) [常规模式 / 高性能模式] |
CPU推理耗时(ms) [常规模式 / 高性能模式] |
模型存储大小(M) | 介绍 |
---|---|---|---|---|---|---|
korean_PP-OCRv3_mobile_rec | 推理模型/训练模型 | 60.21 | 5.40 / 0.97 | 9.11 / 4.05 | 8.6 M | 基于PP-OCRv3识别模型训练得到的超轻量韩文识别模型,支持韩文、数字识别 |
japan_PP-OCRv3_mobile_rec | 推理模型/训练模型 | 45.69 | 5.70 / 1.02 | 8.48 / 4.07 | 8.8 M | 基于PP-OCRv3识别模型训练得到的超轻量日文识别模型,支持日文、数字识别 |
chinese_cht_PP-OCRv3_mobile_rec | 推理模型/训练模型 | 82.06 | 5.90 / 1.28 | 9.28 / 4.34 | 9.7 M | 基于PP-OCRv3识别模型训练得到的超轻量繁体中文识别模型,支持繁体中文、数字识别 |
te_PP-OCRv3_mobile_rec | 推理模型/训练模型 | 95.88 | 5.42 / 0.82 | 8.10 / 6.91 | 7.8 M | 基于PP-OCRv3识别模型训练得到的超轻量泰卢固文识别模型,支持泰卢固文、数字识别 |
ka_PP-OCRv3_mobile_rec | 推理模型/训练模型 | 96.96 | 5.25 / 0.79 | 9.09 / 3.86 | 8.0 M | 基于PP-OCRv3识别模型训练得到的超轻量卡纳达文识别模型,支持卡纳达文、数字识别 |
ta_PP-OCRv3_mobile_rec | 推理模型/训练模型 | 76.83 | 5.23 / 0.75 | 10.13 / 4.30 | 8.0 M | 基于PP-OCRv3识别模型训练得到的超轻量泰米尔文识别模型,支持泰米尔文、数字识别 |
latin_PP-OCRv3_mobile_rec | 推理模型/训练模型 | 76.93 | 5.20 / 0.79 | 8.83 / 7.15 | 7.8 M | 基于PP-OCRv3识别模型训练得到的超轻量拉丁文识别模型,支持拉丁文、数字识别 |
arabic_PP-OCRv3_mobile_rec | 推理模型/训练模型 | 73.55 | 5.35 / 0.79 | 8.80 / 4.56 | 7.8 M | 基于PP-OCRv3识别模型训练得到的超轻量阿拉伯字母识别模型,支持阿拉伯字母、数字识别 |
cyrillic_PP-OCRv3_mobile_rec | 推理模型/训练模型 | 94.28 | 5.23 / 0.76 | 8.89 / 3.88 | 7.9 M | 基于PP-OCRv3识别模型训练得到的超轻量斯拉夫字母识别模型,支持斯拉夫字母、数字识别 |
devanagari_PP-OCRv3_mobile_rec | 推理模型/训练模型 | 96.44 | 5.22 / 0.79 | 8.56 / 4.06 | 7.9 M | 基于PP-OCRv3识别模型训练得到的超轻量梵文字母识别模型,支持梵文字母、数字识别 |
文本行方向分类模块(可选):
模型 | 模型下载链接 | Top-1 Acc(%) | GPU推理耗时(ms) [常规模式 / 高性能模式] |
CPU推理耗时(ms) [常规模式 / 高性能模式] |
模型存储大小(M) | 介绍 |
---|---|---|---|---|---|---|
PP-LCNet_x0_25_textline_ori | 推理模型/训练模型 | 95.54 | - | - | 0.32 | 基于PP-LCNet_x0_25的文本行分类模型,含有两个类别,即0度,180度 |
公式识别模块(可选):
模型 | 模型下载链接 | BLEU score | normed edit distance | ExpRate (%) | GPU推理耗时(ms) [常规模式 / 高性能模式] |
CPU推理耗时(ms) [常规模式 / 高性能模式] |
模型存储大小 |
---|---|---|---|---|---|---|---|
LaTeX_OCR_rec | 推理模型/训练模型 | 0.8821 | 0.0823 | 40.01 | 2047.13 / 2047.13 | 10582.73 / 10582.73 | 89.7 M |
印章文本检测模块(可选):
模型 | 模型下载链接 | 检测Hmean(%) | GPU推理耗时(ms) [常规模式 / 高性能模式] |
CPU推理耗时(ms) [常规模式 / 高性能模式] |
模型存储大小(M) | 介绍 |
---|---|---|---|---|---|---|
PP-OCRv4_server_seal_det | 推理模型/训练模型 | 98.21 | 74.75 / 67.72 | 382.55 / 382.55 | 109 | PP-OCRv4的服务端印章文本检测模型,精度更高,适合在较好的服务器上部署 |
PP-OCRv4_mobile_seal_det | 推理模型/训练模型 | 96.47 | 7.82 / 3.09 | 48.28 / 23.97 | 4.6 | PP-OCRv4的移动端印章文本检测模型,效率更高,适合在端侧部署 |
测试环境说明:
- 性能测试环境
- 测试数据集:
- 文档图像方向分类模型:PaddleOCR 自建的数据集,覆盖证件和文档等多个场景,包含 1000 张图片。
- 文本图像矫正模型:DocUNet。
- 版面区域检测模型:PaddleOCR 自建的版面区域分析数据集,包含中英文论文、杂志和研报等常见的 1w 张文档类型图片。
- 表格结构识别模型:内部自建的英文表格识别数据集。
- 文本检测模型:PaddleOCR 自建的中文数据集,覆盖街景、网图、文档、手写多个场景,其中检测包含 500 张图片。
- 中文识别模型: PaddleOCR 自建的中文数据集,覆盖街景、网图、文档、手写多个场景,其中文本识别包含 1.1w 张图片。
- ch_SVTRv2_rec:PaddleOCR算法模型挑战赛 - 赛题一:OCR端到端识别任务A榜评估集。
- ch_RepSVTR_rec:PaddleOCR算法模型挑战赛 - 赛题一:OCR端到端识别任务B榜评估集。
- 英文识别模型:PaddleOCR 自建的英文数据集。
- 多语言识别模型:PaddleOCR 自建的多语种数据集。
- 文本行方向分类模型:PaddleOCR 自建的数据集,覆盖证件和文档等多个场景,包含 1000 张图片。
- 印章文本检测模型:PaddleOCR 自建的数据集,包含500张圆形印章图像。
- 硬件配置:
- GPU:NVIDIA Tesla T4
- CPU:Intel Xeon Gold 6271C @ 2.60GHz
- 其他环境:Ubuntu 20.04 / cuDNN 8.6 / TensorRT 8.5.2.2
- 测试数据集:
- 推理模式说明
模式 | GPU配置 | CPU配置 | 加速技术组合 |
---|---|---|---|
常规模式 | FP32精度 / 无TRT加速 | FP32精度 / 8线程 | PaddleInference |
高性能模式 | 选择先验精度类型和加速策略的最优组合 | FP32精度 / 8线程 | 选择先验最优后端(Paddle/OpenVINO/TRT等) |
如您更考虑模型精度,请选择精度较高的模型,如您更考虑模型推理速度,请选择推理速度较快的模型,如您更考虑模型存储大小,请选择存储大小较小的模型
2. 快速开始¶
在本地使用 PP-ChatOCRv4 产线前,请确保您已经按照安装教程完成了wheel包安装。
在进行模型推理之前,首先需要准备大语言模型的 api_key,PP-ChatOCRv4 支持在百度云千帆平台或者本地部署的标准 OpenAI 接口大模型服务。如果使用百度云千帆平台,可以参考认证鉴权 获取 api_key。如果使用本地部署的大模型服务,可以参考PaddleNLP大模型部署文档进行大模型部署对话接口部署和向量化接口部署,并填写对应的 base_url 和 api_key 即可。如果需要使用多模态大模型进行数据融合,可以参考PaddleMIX模型文档中的OpenAI服务部署进行多模态大模型部署,并填写对应的 base_url 和 api_key 即可。
注: 如果因本地环境限制无法在本地部署多模态大模型,可以将代码中的含有“mllm”变量的行注释掉,仅使用大语言模型完成信息抽取。
2.1 命令行方式体验¶
可以下载 测试文件,使用一行命令即可快速体验产线效果:
paddleocr pp_chatocrv4_doc -i vehicle_certificate-1.png -k 驾驶室准乘人数 --qianfan_api_key your_api_key
# 通过 --invoke_mllm 和 --pp_docbee_base_url 使用多模态大模型
paddleocr pp_chatocrv4_doc -i vehicle_certificate-1.png -k 驾驶室准乘人数 --qianfan_api_key your_api_key --invoke_mllm True --pp_docbee_base_url http://127.0.0.1:8080/
命令行支持更多参数设置,点击展开以查看命令行参数的详细说明
参数 | 参数说明 | 参数类型 | 默认值 |
---|---|---|---|
input |
待预测数据,必填。如图像文件或者PDF文件的本地路径:/root/data/img.jpg ;如URL链接,如图像文件或PDF文件的网络URL:示例;如本地目录,该目录下需包含待预测图像,如本地路径:/root/data/ (当前不支持目录中包含PDF文件的预测,PDF文件需要指定到具体文件路径)。
|
str |
|
keys |
用于信息提取的键。 | str |
|
save_path |
指定推理结果文件保存的路径。如果不设置,推理结果将不会保存到本地。 | str |
|
invoke_mllm |
是否加载并使用多模态大模型。如果不设置,将默认使用产线初始化的该参数值,初始化为False 。 |
bool |
|
layout_detection_model_name |
用于版面区域检测的模型名称。如果不设置,将会使用产线默认模型。 | str |
|
layout_detection_model_dir |
版面区域检测模型的目录路径。如果不设置,将会下载官方模型。 | str |
|
doc_orientation_classify_model_name |
文档方向分类模型的名称。如果不设置,将会使用产线默认模型。 | str |
|
doc_orientation_classify_model_dir |
文档方向分类模型的目录路径。如果不设置,将会下载官方模型。 | str |
|
doc_unwarping_model_name |
文档去扭曲模型的名称。如果不设置,将会使用产线默认模型。 | str |
|
doc_unwarping_model_dir |
文档去扭曲模型的目录路径。如果不设置,将会下载官方模型。 | str |
|
text_detection_model_name |
文本检测模型的名称。如果不设置,将会使用产线默认模型。 | str |
|
text_detection_model_dir |
文本检测模型的目录路径。如果不设置,将会下载官方模型。 | str |
|
text_recognition_model_name |
文本识别模型的名称。如果不设置,将会使用产线默认模型。 | str |
|
text_recognition_model_dir |
文本识别模型的目录路径。如果不设置,将会下载官方模型。 | str |
|
text_recognition_batch_size |
文本识别模型的批处理大小。如果不设置,将默认设置批处理大小为1 。 |
int |
|
table_structure_recognition_model_name |
表格结构识别模型的名称。如果不设置,将会使用产线默认模型。 | str |
|
table_structure_recognition_model_dir |
表格结构识别模型的目录路径。如果不设置,将会下载官方模型。 | str |
|
seal_text_detection_model_name |
印章文本检测模型的名称。如果不设置,将会使用产线默认模型。 | str |
|
seal_text_detection_model_dir |
印章文本检测模型的目录路径。如果不设置,将会下载官方模型。 | str |
|
seal_text_recognition_model_name |
印章文本识别模型的名称。如果不设置,将会使用产线默认模型。 | str |
|
seal_text_recognition_model_dir |
印章文本识别模型的目录路径。如果不设置,将会下载官方模型。 | str |
|
seal_text_recognition_batch_size |
印章文本识别模型的批处理大小。如果不设置,将默认设置批处理大小为1 。 |
int |
|
use_doc_orientation_classify |
是否加载并使用文档方向分类模块。如果不设置,将默认使用产线初始化的该参数值,初始化为True 。 |
bool |
|
use_doc_unwarping |
是否加载并使用文档去扭曲模块。如果不设置,将默认使用产线初始化的该参数值,初始化为True 。 |
bool |
|
use_textline_orientation |
是否加载并使用文本行方向分类模块。如果不设置,初始化为True 。 |
bool |
|
use_seal_recognition |
是否加载并使用印章识别子产线。如果不设置,将默认使用产线初始化的该参数值,初始化为True 。 |
bool |
|
use_table_recognition |
是否加载并使用表格识别子产线。如果不设置,将默认使用产线初始化的该参数值,初始化为True 。 |
bool |
|
layout_threshold |
版面模型得分阈值。
0-1 之间的任意浮点数。如果不设置,将默认使用产线初始化的该参数值,初始化为 0.5 。
|
float |
|
layout_nms |
版面检测是否使用后处理NMS。如果不设置,将默认使用产线初始化的该参数值,初始化为True 。 |
bool |
|
layout_unclip_ratio |
版面区域检测模型检测框的扩张系数。任意大于 0 浮点数。如果不设置,将默认使用产线初始化的该参数值,初始化为 1.0 。
|
float |
|
layout_merge_bboxes_mode |
版面检测中模型输出的检测框的合并处理模式。
large 。
|
str |
|
text_det_limit_side_len |
文本检测的图像边长限制。大于 0 的任意整数。如果不设置,将默认使用产线初始化的该参数值,初始化为 960 。
|
int |
|
text_det_limit_type |
文本检测的边长度限制类型。支持 min 和 max ,min 表示保证图像最短边不小于 det_limit_side_len ,max 表示保证图像最长边不大于 limit_side_len
如果不设置,将默认使用产线初始化的该参数值,初始化为 max 。
|
str |
|
text_det_thresh |
检测像素阈值。输出的概率图中,得分大于该阈值的像素点才会被认为是文字像素点。大于 0 的任意浮点数。如果不设置,将默认使用产线初始化的该参数值 0.3 。
|
float |
|
text_det_box_thresh |
检测框阈值,检测结果边框内,所有像素点的平均得分大于该阈值时,该结果会被认为是文字区域。大于 0 的任意浮点数
。如果不设置,将默认使用产线初始化的该参数值 0.6 。
|
float |
|
text_det_unclip_ratio |
文本检测扩张系数,使用该方法对文字区域进行扩张,该值越大,扩张的面积越大。大于 0 的任意浮点数。如果不设置,将默认使用产线初始化的该参数值 2.0 。
|
float |
|
text_rec_score_thresh |
文本识别阈值,得分大于该阈值的文本结果会被保留。大于 0 的任意浮点数。如果不设置,将默认使用产线初始化的该参数值 0.0 。即不设阈值。
|
float |
|
seal_det_limit_side_len |
印章文本检测的图像边长限制。大于 0 的任意整数。如果不设置,将默认使用产线初始化的该参数值,初始化为 736 。
|
int |
|
seal_det_limit_type |
印章文本检测的图像边长限制类型。支持 min 和 max ,min 表示保证图像最短边不小于 det_limit_side_len ,max 表示保证图像最长边不大于 limit_side_len 。如果不设置,将默认使用产线初始化的该参数值,初始化为 min 。
|
str |
|
seal_det_thresh |
检测像素阈值,输出的概率图中,得分大于该阈值的像素点才会被认为是文字像素点。大于 0 的任意浮点数。如果不设置,将默认使用产线初始化的该参数值 0.2 。
|
float |
|
seal_det_box_thresh |
检测框阈值,检测结果边框内,所有像素点的平均得分大于该阈值时,该结果会被认为是文字区域。大于 0 的任意浮点数。如果不设置,将默认使用产线初始化的该参数值 0.6 。
|
float |
|
seal_det_unclip_ratio |
印章文本检测扩张系数,使用该方法对文字区域进行扩张,该值越大,扩张的面积越大。大于 0 的任意浮点数
。如果不设置,将默认使用产线初始化的该参数值 0.5 。
|
float |
|
seal_rec_score_thresh |
印章文本识别阈值,得分大于该阈值的文本结果会被保留。大于 0 的任意浮点数
。如果不设置,将默认使用产线初始化的该参数值 0.0 。即不设阈值。
|
float |
|
qianfan_api_key |
千帆平台的api_key | str |
|
pp_docbee_base_url |
多模态大模型服务的url。 | str |
|
device |
用于推理的设备。支持指定具体卡号:
|
str |
|
enable_hpi |
是否启用高性能推理。 | bool |
False |
use_tensorrt |
是否启用 Paddle Inference 的 TensorRT 子图引擎。 对于 CUDA 11.8 版本的飞桨,兼容的 TensorRT 版本为 8.x(x>=6),建议安装 TensorRT 8.6.1.6。 对于 CUDA 12.6 版本的飞桨,兼容的 TensorRT 版本为 10.x(x>=5),建议安装 TensorRT 10.5.0.18。 | bool |
False |
precision |
计算精度,如 fp32、fp16。 | str |
fp32 |
enable_mkldnn |
是否启用 MKL-DNN 加速推理。如果 MKL-DNN 不可用或模型不支持通过 MKL-DNN 加速,即使设置了此标志,也不会使用加速。 | bool |
True |
mkldnn_cache_capacity |
MKL-DNN 缓存容量。 | int |
10 |
cpu_threads |
在 CPU 上进行推理时使用的线程数。 | int |
8 |
paddlex_config |
PaddleX产线配置文件路径。 | str |
运行结果会被打印到终端上,运行结果如下:
2.2 Python脚本方式集成¶
命令行方式是为了快速体验查看效果,一般来说,在项目中,往往需要通过代码集成,可以下载 测试文件,使用如下示例代码进行推理:
from paddleocr import PPChatOCRv4Doc
chat_bot_config = {
"module_name": "chat_bot",
"model_name": "ernie-3.5-8k",
"base_url": "https://qianfan.baidubce.com/v2",
"api_type": "openai",
"api_key": "api_key", # your api_key
}
retriever_config = {
"module_name": "retriever",
"model_name": "embedding-v1",
"base_url": "https://qianfan.baidubce.com/v2",
"api_type": "qianfan",
"api_key": "api_key", # your api_key
}
mllm_chat_bot_config = {
"module_name": "chat_bot",
"model_name": "PP-DocBee2",
"base_url": "http://127.0.0.1:8080/", # your local mllm service url
"api_type": "openai",
"api_key": "api_key", # your api_key
}
pipeline = PPChatOCRv4Doc()
visual_predict_res = pipeline.visual_predict(
input="vehicle_certificate-1.png",
use_doc_orientation_classify=False,
use_doc_unwarping=False,
use_common_ocr=True,
use_seal_recognition=True,
use_table_recognition=True,
)
visual_info_list = []
for res in visual_predict_res:
visual_info_list.append(res["visual_info"])
layout_parsing_result = res["layout_parsing_result"]
vector_info = pipeline.build_vector(
visual_info_list, flag_save_bytes_vector=True, retriever_config=retriever_config
)
mllm_predict_res = pipeline.mllm_pred(
input="vehicle_certificate-1.png",
key_list=["驾驶室准乘人数"],
mllm_chat_bot_config=mllm_chat_bot_config,
)
mllm_predict_info = mllm_predict_res["mllm_res"]
chat_result = pipeline.chat(
key_list=["驾驶室准乘人数"],
visual_info=visual_info_list,
vector_info=vector_info,
mllm_predict_info=mllm_predict_info,
chat_bot_config=chat_bot_config,
retriever_config=retriever_config,
)
print(chat_result)
运行后,输出结果如下:
PP-ChatOCRv4 预测的流程、API说明、产出说明如下:
(1)调用 PPChatOCRv4Doc
方法实例化PP-ChatOCRv4产线对象。
相关参数说明如下:
参数 | 参数说明 | 参数类型 | 默认值 |
---|---|---|---|
layout_detection_model_name |
用于版面区域检测的模型名称。如果设置为None ,将会使用产线默认模型。 |
str |
None |
layout_detection_model_dir |
版面区域检测模型的目录路径。如果设置为None ,将会下载官方模型。 |
str |
None |
doc_orientation_classify_model_name |
文档方向分类模型的名称。如果设置为None ,将会使用产线默认模型。 |
str |
None |
doc_orientation_classify_model_dir |
文档方向分类模型的目录路径。如果设置为None ,将会下载官方模型。 |
str |
None |
doc_unwarping_model_name |
文档去扭曲模型的名称。如果设置为None ,将会使用产线默认模型。 |
str |
None |
doc_unwarping_model_dir |
文档去扭曲模型的目录路径。如果设置为None ,将会下载官方模型。 |
str |
None |
text_detection_model_name |
文本检测模型的名称。如果设置为None ,将会使用产线默认模型。 |
str |
None |
text_detection_model_dir |
文本检测模型的目录路径。如果设置为None ,将会下载官方模型。 |
str |
None |
text_recognition_model_name |
文本识别模型的名称。如果设置为None ,将会使用产线默认模型。 |
str |
None |
text_recognition_model_dir |
文本识别模型的目录路径。如果设置为None ,将会下载官方模型。 |
str |
None |
text_recognition_batch_size |
文本识别模型的批处理大小。如果设置为None ,将默认设置批处理大小为1 。 |
int |
None |
table_structure_recognition_model_name |
表格结构识别模型的名称。如果设置为None ,将会使用产线默认模型。 |
str |
None |
table_structure_recognition_model_dir |
表格结构识别模型的目录路径。如果设置为None ,将会下载官方模型。 |
str |
None |
seal_text_detection_model_name |
印章文本检测模型的名称。如果设置为None ,将会使用产线默认模型。 |
str |
None |
seal_text_detection_model_dir |
印章文本检测模型的目录路径。如果设置为None ,将会下载官方模型。 |
str |
None |
seal_text_recognition_model_name |
印章文本识别模型的名称。如果设置为None ,将会使用产线默认模型。 |
str |
None |
seal_text_recognition_model_dir |
印章文本识别模型的目录路径。如果设置为None ,将会下载官方模型。 |
str |
None |
seal_text_recognition_batch_size |
印章文本识别模型的批处理大小。如果设置为None ,将默认设置批处理大小为1 。 |
int |
None |
use_doc_orientation_classify |
是否加载并使用文档方向分类模块。如果设置为None ,将默认使用产线初始化的该参数值,初始化为True 。 |
bool |
None |
use_doc_unwarping |
是否加载并使用文档去扭曲模块。如果设置为None ,将默认使用产线初始化的该参数值,初始化为True 。 |
bool |
None |
use_textline_orientation |
是否加载并使用文本行方向分类模块. 如果设置为None ,将默认使用产线初始化的该参数值,初始化为True 。 |
bool |
None |
use_seal_recognition |
是否加载并使用印章识别子产线。如果设置为None ,将默认使用产线初始化的该参数值,初始化为True 。 |
bool |
None |
use_table_recognition |
是否加载并使用表格识别子产线。如果设置为None ,将默认使用产线初始化的该参数值,初始化为True 。 |
bool |
None |
layout_threshold |
版面模型得分阈值。
|
float|dict |
None |
layout_nms |
版面检测是否使用后处理NMS。如果设置为None ,将默认使用产线初始化的该参数值,初始化为True 。 |
bool |
None |
layout_unclip_ratio |
版面区域检测模型检测框的扩张系数。
|
float|Tuple[float,float]|dict |
None |
layout_merge_bboxes_mode |
版面区域检测的重叠框过滤方式。
|
str|dict |
None |
text_det_limit_side_len |
文本检测的图像边长限制。
|
int |
None |
text_det_limit_type |
文本检测的边长度限制类型。
|
str |
None |
text_det_thresh |
检测像素阈值,输出的概率图中,得分大于该阈值的像素点才会被认为是文字像素点。
|
float |
None |
text_det_box_thresh |
检测框阈值,检测结果边框内,所有像素点的平均得分大于该阈值时,该结果会被认为是文字区域。
|
float |
None |
text_det_unclip_ratio |
文本检测扩张系数,使用该方法对文字区域进行扩张,该值越大,扩张的面积越大。
|
float |
None |
text_rec_score_thresh |
文本识别阈值,得分大于该阈值的文本结果会被保留。
|
float |
None |
seal_det_limit_side_len |
印章文本检测的图像边长限制。
|
int |
None |
seal_det_limit_type |
印章文本检测的图像边长限制类型。
|
str |
None |
seal_det_thresh |
检测像素阈值,输出的概率图中,得分大于该阈值的像素点才会被认为是文字像素点。
|
float |
None |
seal_det_box_thresh |
检测框阈值,检测结果边框内,所有像素点的平均得分大于该阈值时,该结果会被认为是文字区域。
|
float |
None |
seal_det_unclip_ratio |
印章文本检测扩张系数,使用该方法对文字区域进行扩张,该值越大,扩张的面积越大。
|
float |
None |
seal_rec_score_thresh |
印章文本识别阈值,得分大于该阈值的文本结果会被保留。
|
float |
None |
retriever_config |
向量检索大模型配置参数。配置内容为如下dict:
|
dict |
None |
mllm_chat_bot_config |
多模态大模型配置参数。配置内容为如下dict:
|
dict |
None |
chat_bot_config |
大语言模型配置信息。配置内容为如下dict:
|
dict |
None |
device |
用于推理的设备。支持指定具体卡号:
|
str |
None |
enable_hpi |
是否启用高性能推理。 | bool |
False |
use_tensorrt |
是否启用 Paddle Inference 的 TensorRT 子图引擎。 对于 CUDA 11.8 版本的飞桨,兼容的 TensorRT 版本为 8.x(x>=6),建议安装 TensorRT 8.6.1.6。 对于 CUDA 12.6 版本的飞桨,兼容的 TensorRT 版本为 10.x(x>=5),建议安装 TensorRT 10.5.0.18。 | bool |
False |
precision |
计算精度,如 fp32、fp16。 | str |
"fp32" |
enable_mkldnn |
是否启用 MKL-DNN 加速推理。如果 MKL-DNN 不可用或模型不支持通过 MKL-DNN 加速,即使设置了此标志,也不会使用加速。 | bool |
True |
mkldnn_cache_capacity |
MKL-DNN 缓存容量。 | int |
10 |
cpu_threads |
在 CPU 上进行推理时使用的线程数。 | int |
8 |
paddlex_config |
PaddleX产线配置文件路径。 | str |
None |
(2)调用 PP-ChatOCRv4 产线对象的 visual_predict()
方法获取视觉预测结果,该方法会返回一个结果列表。另外,产线还提供了 visual_predict_iter()
方法。两者在参数接受和结果返回方面是完全一致的,区别在于 visual_predict_iter()
返回的是一个 generator
,能够逐步处理和获取预测结果,适合处理大型数据集或希望节省内存的场景。可以根据实际需求选择使用这两种方法中的任意一种。以下是 visual_predict()
方法的参数及其说明:
参数 | 参数说明 | 参数类型 | 默认值 |
---|---|---|---|
input |
待预测数据,支持多种输入类型,必填。
|
Python Var|str|list |
|
use_doc_orientation_classify |
是否在推理时使用文档方向分类模块。 | bool |
None |
use_doc_unwarping |
是否在推理时使用文本图像矫正模块。 | bool |
None |
use_textline_orientation |
是否加载并使用文本行方向分类模块。 | bool |
None |
use_seal_recognition |
是否在推理时使用印章识别子产线。 | bool |
None |
use_table_recognition |
是否在推理时使用表格识别子产线。 | bool |
None |
layout_threshold |
与实例化时的参数相同。 | float|dict |
None |
layout_nms |
与实例化时的参数相同。 | bool |
None |
layout_unclip_ratio |
与实例化时的参数相同。 | float|Tuple[float,float]|dict |
None |
layout_merge_bboxes_mode |
与实例化时的参数相同。 | str|dict |
None |
text_det_limit_side_len |
与实例化时的参数相同。 | int |
None |
text_det_limit_type |
与实例化时的参数相同。 | str |
None |
text_det_thresh |
与实例化时的参数相同。 | float |
None |
text_det_box_thresh |
与实例化时的参数相同。 | float |
None |
text_det_unclip_ratio |
与实例化时的参数相同。 | float |
None |
text_rec_score_thresh |
与实例化时的参数相同。 | float |
None |
seal_det_limit_side_len |
与实例化时的参数相同。 | int |
None |
seal_det_limit_type |
与实例化时的参数相同。 | str |
None |
seal_det_thresh |
与实例化时的参数相同。 | float |
None |
seal_det_box_thresh |
与实例化时的参数相同。 | float |
None |
seal_det_unclip_ratio |
与实例化时的参数相同。 | float |
None |
seal_rec_score_thresh |
与实例化时的参数相同。 | float |
None |
(3)对视觉预测结果进行处理。
每个样本的预测结果均为 `dict` 类型,包含 `visual_info` 和 `layout_parsing_result` 两个字段。通过 `visual_info` 得到视觉信息(包含 `normal_text_dict`、`table_text_list`、`table_html_list` 等信息),并将每个样本的信息放到 `visual_info_list` 列表中,该列表的内容会在之后送入大语言模型中。 当然,您也可以通过 `layout_parsing_result` 获取版面解析的结果,该结果包含文件或图片中包含的表格、文字、图片等内容,且支持打印、保存为图片、保存为`json`文件的操作:......
for res in visual_predict_res:
visual_info_list.append(res["visual_info"])
layout_parsing_result = res["layout_parsing_result"]
layout_parsing_result.print()
layout_parsing_result.save_to_img("./output")
layout_parsing_result.save_to_json("./output")
layout_parsing_result.save_to_xlsx("./output")
layout_parsing_result.save_to_html("./output")
......
方法 | 方法说明 | 参数 | 参数类型 | 参数说明 | 默认值 |
---|---|---|---|---|---|
print() |
打印结果到终端 | format_json |
bool |
是否对输出内容进行使用 JSON 缩进格式化。 |
True |
indent |
int |
指定缩进级别,以美化输出的 JSON 数据,使其更具可读性,仅当 format_json 为 True 时有效。 |
4 | ||
ensure_ascii |
bool |
控制是否将非 ASCII 字符转义为 Unicode 。设置为 True 时,所有非 ASCII 字符将被转义;False 则保留原始字符,仅当format_json 为True 时有效。 |
False |
||
save_to_json() |
将结果保存为json格式的文件 | save_path |
str |
保存的文件路径,当为目录时,保存文件命名与输入文件类型命名一致。 | 无 |
indent |
int |
指定缩进级别,以美化输出的 JSON 数据,使其更具可读性,仅当 format_json 为 True 时有效。 |
4 | ||
ensure_ascii |
bool |
控制是否将非 ASCII 字符转义为 Unicode 。设置为 True 时,所有非 ASCII 字符将被转义;False 则保留原始字符,仅当format_json 为True 时有效。 |
False |
||
save_to_img() |
将中间各个模块的可视化图像保存在png格式的图像。 | save_path |
str |
保存的文件路径,支持目录或文件路径。 | 无 |
save_to_html() |
将文件中的表格保存为html格式的文件。 | save_path |
str |
保存的文件路径,支持目录或文件路径。 | 无 |
save_to_xlsx() |
将文件中的表格保存为xlsx格式的文件。 | save_path |
str |
保存的文件路径,支持目录或文件路径。 | 无 |
属性 | 属性说明 |
---|---|
json |
获取预测的 json 格式的结果。 |
img |
获取格式为 dict 的可视化图像。 |
(4)调用PP-ChatOCRv4的产线对象的 build_vector()
方法,对文本内容进行向量构建。
以下是 `build_vector()` 方法的参数及其说明:
参数 | 参数说明 | 参数类型 | 默认值 |
---|---|---|---|
visual_info |
视觉信息,可以是包含视觉信息的dict,或者由这些dict组成的列表。 | list|dict |
None |
min_characters |
最小字符数量。为大于0的正整数,可以根据大语言模型支持的token长度来决定。 | int |
3500 |
block_size |
长文本建立向量库时分块大小。为大于0的正整数,可以根据大语言模型支持的token长度来决定。 | int |
300 |
flag_save_bytes_vector |
文字是否保存为二进制文件。 | bool |
False |
retriever_config |
向量检索大模型配置参数,与实例化时的参数相同。 | dict |
None |
(5)调用PP-ChatOCRv4的产线对象的 mllm_pred()
方法,获取多模态大模型抽取结果。
以下是 `mllm_pred()` 方法的参数及其说明:
参数 | 参数说明 | 参数类型 | 默认值 |
---|---|---|---|
input |
待预测数据,支持多种输入类型,必填。
|
Python Var|str |
|
key_list |
用于提取信息的单个键或键列表。 | Union[str, List[str]] |
None |
mllm_chat_bot_config |
多模态大模型配置参数,与实例化时的参数相同。 | dict |
None |
(6)调用PP-ChatOCRv4的产线对象的 chat()
方法,对关键信息进行抽取。
以下是 `chat()` 方法的参数及其说明:
参数 | 参数说明 | 参数类型 | 默认值 | |
---|---|---|---|---|
key_list |
用于提取信息的单个键或键列表。 | Union[str, List[str]] |
None |
|
visual_info |
视觉信息结果。 | List[dict] |
None |
|
use_vector_retrieval |
是否使用向量检索。 | bool |
True |
|
vector_info |
用于检索的向量信息。 | dict |
None |
|
min_characters |
所需的最小字符数。为大于0的正整数。 | int |
3500 |
|
text_task_description |
文本任务的描述。 | str |
None |
|
text_output_format |
文本结果的输出格式。 | str |
None |
|
text_rules_str |
生成文本结果的规则。 | str |
None |
|
text_few_shot_demo_text_content |
用于少样本演示的文本内容。 | str |
None |
|
text_few_shot_demo_key_value_list |
用于少样本演示的键值列表。/td> | str |
None |
|
table_task_description |
表任务的描述。 | str |
None |
|
table_output_format |
表结果的输出格式。 | str |
None |
|
table_rules_str |
生成表结果的规则。 | str |
None |
|
table_few_shot_demo_text_content |
表少样本演示的文本内容。 | str |
None |
|
table_few_shot_demo_key_value_list |
表少样本演示的键值列表。 | str |
None |
|
mllm_predict_info |
多模态大模型结果。 | dict |
None
|
None |
mllm_integration_strategy |
多模态大模型和大语言模型数据融合策略,支持单独使用其中一个或者融合两者结果。可选:"integration", "llm_only" and "mllm_only"。 | str |
"integration" |
chat_bot_config |
大语言模型配置信息,与实例化时的参数相同。 | dict |
None |
|
retriever_config |
向量检索大模型配置参数,与实例化时的参数相同。 | dict |
None |
3. 开发集成/部署¶
如果产线可以达到您对产线推理速度和精度的要求,您可以直接进行开发集成/部署。
若您需要将产线直接应用在您的Python项目中,可以参考 2.2 Python脚本方式中的示例代码。
此外,PaddleOCR 也提供了其他两种部署方式,详细说明如下:
🚀 高性能推理:在实际生产环境中,许多应用对部署策略的性能指标(尤其是响应速度)有着较严苛的标准,以确保系统的高效运行与用户体验的流畅性。为此,PaddleOCR 提供高性能推理功能,旨在对模型推理及前后处理进行深度性能优化,实现端到端流程的显著提速,详细的高性能推理流程请参考高性能推理。
☁️ 服务化部署:服务化部署是实际生产环境中常见的一种部署形式。通过将推理功能封装为服务,客户端可以通过网络请求来访问这些服务,以获取推理结果。详细的产线服务化部署流程请参考服务化部署。
以下是基础服务化部署的API参考与多语言服务调用示例:
API参考
对于服务提供的主要操作:
- HTTP请求方法为POST。
- 请求体和响应体均为JSON数据(JSON对象)。
- 当请求处理成功时,响应状态码为
200
,响应体的属性如下:
名称 | 类型 | 含义 |
---|---|---|
logId |
string |
请求的UUID。 |
errorCode |
integer |
错误码。固定为0 。 |
errorMsg |
string |
错误说明。固定为"Success" 。 |
result |
object |
操作结果。 |
- 当请求处理未成功时,响应体的属性如下:
名称 | 类型 | 含义 |
---|---|---|
logId |
string |
请求的UUID。 |
errorCode |
integer |
错误码。与响应状态码相同。 |
errorMsg |
string |
错误说明。 |
服务提供的主要操作如下:
analyzeImages
使用计算机视觉模型对图像进行分析,获得OCR、表格识别结果等,并提取图像中的关键信息。
POST /chatocr-visual
- 请求体的属性如下:
名称 | 类型 | 含义 | 是否必填 |
---|---|---|---|
file |
string |
服务器可访问的图像文件或PDF文件的URL,或上述类型文件内容的Base64编码结果。默认对于超过10页的PDF文件,只有前10页的内容会被处理。 要解除页数限制,请在产线配置文件中添加以下配置:
|
是 |
fileType |
integer | null |
文件类型。0 表示PDF文件,1 表示图像文件。若请求体无此属性,则将根据URL推断文件类型。 |
否 |
useDocOrientationClassify |
boolean | null |
请参阅产线对象中 visual_predict 方法的 use_doc_orientation_classify 参数相关说明。 |
否 |
useDocUnwarping |
boolean | null |
请参阅产线对象中 visual_predict 方法的 use_doc_unwarping 参数相关说明。 |
否 |
useSealRecognition |
boolean | null |
请参阅产线对象中 visual_predict 方法的 use_seal_recognition 参数相关说明。 |
否 |
useTableRecognition |
boolean | null |
请参阅产线对象中 visual_predict 方法的 use_table_recognition 参数相关说明。 |
否 |
layoutThreshold |
number | null |
请参阅产线对象中 visual_predict 方法的 layout_threshold 参数相关说明。 |
否 |
layoutNms |
boolean | null |
请参阅产线对象中 visual_predict 方法的 layout_nms 参数相关说明。 |
否 |
layoutUnclipRatio |
number | array | object | null |
请参阅产线对象中 visual_predict 方法的 layout_unclip_ratio 参数相关说明。 |
否 |
layoutMergeBboxesMode |
string | object | null |
请参阅产线对象中 visual_predict 方法的 layout_merge_bboxes_mode 参数相关说明。 |
否 |
textDetLimitSideLen |
integer | null |
请参阅产线对象中 visual_predict 方法的 text_det_limit_side_len 参数相关说明。 |
否 |
textDetLimitType |
string | null |
请参阅产线对象中 visual_predict 方法的 text_det_limit_type 参数相关说明。 |
否 |
textDetThresh |
number | null |
请参阅产线对象中 visual_predict 方法的 text_det_thresh 参数相关说明。 |
否 |
textDetBoxThresh |
number | null |
请参阅产线对象中 visual_predict 方法的 text_det_box_thresh 参数相关说明。 |
否 |
textDetUnclipRatio |
number | null |
请参阅产线对象中 visual_predict 方法的 text_det_unclip_ratio 参数相关说明。 |
否 |
textRecScoreThresh |
number | null |
请参阅产线对象中 visual_predict 方法的 text_rec_score_thresh 参数相关说明。 |
否 |
sealDetLimitSideLen |
integer | null |
请参阅产线对象中 visual_predict 方法的 seal_det_limit_side_len 参数相关说明。 |
否 |
sealDetLimitType |
string | null |
请参阅产线对象中 visual_predict 方法的 seal_det_limit_type 参数相关说明。 |
否 |
sealDetThresh |
number | null |
请参阅产线对象中 visual_predict 方法的 seal_det_thresh 参数相关说明。 |
否 |
sealDetBoxThresh |
number | null |
请参阅产线对象中 visual_predict 方法的 seal_det_box_thresh 参数相关说明。 |
否 |
sealDetUnclipRatio |
number | null |
请参阅产线对象中 visual_predict 方法的 seal_det_unclip_ratio 参数相关说明。 |
否 |
sealRecScoreThresh |
number | null |
请参阅产线对象中 visual_predict 方法的 seal_rec_score_thresh 参数相关说明。 |
否 |
- 请求处理成功时,响应体的
result
具有如下属性:
名称 | 类型 | 含义 |
---|---|---|
layoutParsingResults |
array |
使用计算机视觉模型得到的分析结果。数组长度为1(对于图像输入)或实际处理的文档页数(对于PDF输入)。对于PDF输入,数组中的每个元素依次表示PDF文件中实际处理的每一页的结果。 |
visualInfo |
array |
图像中的关键信息,可用作其他操作的输入。 |
dataInfo |
object |
输入数据信息。 |
layoutParsingResults
中的每个元素为一个object
,具有如下属性:
名称 | 类型 | 含义 |
---|---|---|
prunedResult |
object |
产线对象的 visual_predict 方法生成结果的 JSON 表示中 res 字段的简化版本,其中去除了 input_path 和 page_index 字段。 |
outputImages |
object | null |
参见产线视觉预测结果的 img 属性说明。 |
inputImage |
string | null |
输入图像。图像为JPEG格式,使用Base64编码。 |
buildVectorStore
构建向量数据库。
POST /chatocr-vector
- 请求体的属性如下:
名称 | 类型 | 含义 | 是否必填 |
---|---|---|---|
visualInfo |
array |
图像中的关键信息。由analyzeImages 操作提供。 |
是 |
minCharacters |
integer | null |
启用向量数据库的最小数据长度。 | 否 |
blockSize |
int | null |
请参阅产线对象中 build_vector 方法的 block_size 参数相关说明。 |
否 |
retrieverConfig |
object | null |
请参阅产线对象中 build_vector 方法的 retriever_config 参数相关说明。 |
否 |
- 请求处理成功时,响应体的
result
具有如下属性:
名称 | 类型 | 含义 |
---|---|---|
vectorInfo |
object |
向量数据库序列化结果,可用作其他操作的输入。 |
invokeMLLM
调用多模态大模型。
POST /chatocr-mllm
- 请求体的属性如下:
名称 | 类型 | 含义 | 是否必填 |
---|---|---|---|
image |
string |
服务器可访问的图像文件的URL或图像文件内容的Base64编码结果。 | 是 |
keyList |
array |
键列表。 | 是 |
mllmChatBotConfig |
object | null |
请参阅产线对象中 mllm_pred 方法的 mllm_chat_bot_config 参数相关说明。 |
否 |
名称 | 类型 | 含义 |
---|---|---|
mllmPredictInfo |
object |
多模态大模型调用结果。 |
chat
与大语言模型交互,利用大语言模型提炼关键信息。
POST /chatocr-chat
- 请求体的属性如下:
名称 | 类型 | 含义 | 是否必填 |
---|---|---|---|
keyList |
array |
键列表。 | 是 |
visualInfo |
object |
图像中的关键信息。由analyzeImages 操作提供。 |
是 |
useVectorRetrieval |
boolean | null |
请参阅产线对象中 chat 方法的 use_vector_retrieval 参数相关说明。 |
否 |
vectorInfo |
object | null |
向量数据库序列化结果。由buildVectorStore 操作提供。 |
否 |
minCharacters |
integer |
启用向量数据库的最小数据长度 | 否 |
textTaskDescription |
string | null |
请参阅产线对象中 chat 方法的 text_task_description 参数相关说明。 |
否 |
textOutputFormat |
string | null |
请参阅产线对象中 chat 方法的 text_output_format 参数相关说明。 |
否 |
textRulesStr |
string | null |
请参阅产线对象中 chat 方法的 text_rules_str 参数相关说明。 |
否 |
textFewShotDemoTextContent |
string | null |
请参阅产线对象中 chat 方法的 text_few_shot_demo_text_content 参数相关说明。 |
否 |
textFewShotDemoKeyValueList |
string | null |
请参阅产线对象中 chat 方法的 text_few_shot_demo_key_value_list 参数相关说明。 |
否 |
tableTaskDescription |
string | null |
请参阅产线对象中 chat 方法的 table_task_description 参数相关说明。 |
否 |
tableOutputFormat |
string | null |
请参阅产线对象中 chat 方法的 table_output_format 参数相关说明。 |
否 |
tableRulesStr |
string | null |
请参阅产线对象中 chat 方法的 table_rules_str 参数相关说明。 |
否 |
tableFewShotDemoTextContent |
string | null |
请参阅产线对象中 chat 方法的 table_few_shot_demo_text_content 参数相关说明。 |
|
tableFewShotDemoKeyValueList |
string | null |
请参阅产线对象中 chat 方法的 table_few_shot_demo_key_value_list 参数相关说明。 |
否 |
mllmPredictInfo |
object | null |
多模态大模型调用结果。由invokeMllm 操作提供。 |
否 |
mllmIntegrationStrategy |
string | null |
请参阅产线对象中 chat 方法的 mllm_integration_strategy 参数相关说明。 |
否 |
chatBotConfig |
object | null |
请参阅产线对象中 chat 方法的 chat_bot_config 参数相关说明。 |
否 |
retrieverConfig |
object | null |
请参阅产线对象中 chat 方法的 retriever_config 参数相关说明。 |
否 |
- 请求处理成功时,响应体的
result
具有如下属性:
名称 | 类型 | 含义 |
---|---|---|
chatResult |
object |
关键信息抽取结果。 |
多语言调用服务示例
Python
# 此脚本只展示了图片的用例,其他文件类型的调用请查看API参考来调整
import base64
import pprint
import sys
import requests
API_BASE_URL = "http://0.0.0.0:8080"
image_path = "./demo.jpg"
keys = ["姓名"]
with open(image_path, "rb") as file:
image_bytes = file.read()
image_data = base64.b64encode(image_bytes).decode("ascii")
payload = {
"file": image_data,
"fileType": 1,
}
resp_visual = requests.post(url=f"{API_BASE_URL}/chatocr-visual", json=payload)
if resp_visual.status_code != 200:
print(
f"Request to chatocr-visual failed with status code {resp_visual.status_code}."
)
pprint.pp(resp_visual.json())
sys.exit(1)
result_visual = resp_visual.json()["result"]
for i, res in enumerate(result_visual["layoutParsingResults"]):
print(res["prunedResult"])
for img_name, img in res["outputImages"].items():
img_path = f"{img_name}_{i}.jpg"
with open(img_path, "wb") as f:
f.write(base64.b64decode(img))
print(f"Output image saved at {img_path}")
payload = {
"visualInfo": result_visual["visualInfo"],
}
resp_vector = requests.post(url=f"{API_BASE_URL}/chatocr-vector", json=payload)
if resp_vector.status_code != 200:
print(
f"Request to chatocr-vector failed with status code {resp_vector.status_code}."
)
pprint.pp(resp_vector.json())
sys.exit(1)
result_vector = resp_vector.json()["result"]
payload = {
"image": image_data,
"keyList": keys,
}
resp_mllm = requests.post(url=f"{API_BASE_URL}/chatocr-mllm", json=payload)
if resp_mllm.status_code != 200:
print(
f"Request to chatocr-mllm failed with status code {resp_mllm.status_code}."
)
pprint.pp(resp_mllm.json())
sys.exit(1)
result_mllm = resp_mllm.json()["result"]
payload = {
"keyList": keys,
"visualInfo": result_visual["visualInfo"],
"useVectorRetrieval": True,
"vectorInfo": result_vector["vectorInfo"],
"mllmPredictInfo": result_mllm["mllmPredictInfo"],
}
resp_chat = requests.post(url=f"{API_BASE_URL}/chatocr-chat", json=payload)
if resp_chat.status_code != 200:
print(
f"Request to chatocr-chat failed with status code {resp_chat.status_code}."
)
pprint.pp(resp_chat.json())
sys.exit(1)
result_chat = resp_chat.json()["result"]
print("Final result:")
print(result_chat["chatResult"])
C++
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include "cpp-httplib/httplib.h" // https://github.com/Huiyicc/cpp-httplib
#include "nlohmann/json.hpp" // https://github.com/nlohmann/json
#include "base64.hpp" // https://github.com/tobiaslocker/base64
using json = nlohmann::json;
std::string encode_image(const std::string& path) {
std::ifstream file(path, std::ios::binary | std::ios::ate);
if (!file) throw std::runtime_error("File open error.");
std::streamsize size = file.tellg();
file.seekg(0, std::ios::beg);
std::vector buf(size);
file.read(buf.data(), size);
return base64::to_base64(std::string(buf.data(), buf.size()));
}
int main() {
httplib::Client client("localhost", 8080);
std::string imagePath = "./demo.jpg";
std::string imageData = encode_image(imagePath);
json keys = { "合格证编号" };
json payload_visual = { {"file", imageData}, {"fileType", 1} };
auto resp1 = client.Post("/chatocr-visual", payload_visual.dump(), "application/json");
if (!resp1 || resp1->status != 200) {
std::cerr << "chatocr-visual failed.\n"; return 1;
}
json result_visual = json::parse(resp1->body)["result"];
for (size_t i = 0; i < result_visual["layoutParsingResults"].size(); ++i) {
auto& res = result_visual["layoutParsingResults"][i];
std::cout << "prunedResult: " << res["prunedResult"].dump() << "\n";
if (res.contains("outputImages")) {
for (auto& [name, b64] : res["outputImages"].items()) {
std::string outPath = name + "_" + std::to_string(i) + ".jpg";
std::string decoded = base64::from_base64(b64.get());
std::ofstream out(outPath, std::ios::binary);
out.write(decoded.data(), decoded.size());
out.close();
std::cout << "Saved: " << outPath << "\n";
}
}
}
json payload_vector = { {"visualInfo", result_visual["visualInfo"]} };
auto resp2 = client.Post("/chatocr-vector", payload_vector.dump(), "application/json");
if (!resp2 || resp2->status != 200) {
std::cerr << "chatocr-vector failed.\n"; return 1;
}
json result_vector = json::parse(resp2->body)["result"];
json payload_mllm = { {"image", imageData}, {"keyList", keys} };
auto resp3 = client.Post("/chatocr-mllm", payload_mllm.dump(), "application/json");
if (!resp3 || resp3->status != 200) {
std::cerr << "chatocr-mllm failed.\n"; return 1;
}
json result_mllm = json::parse(resp3->body)["result"];
json payload_chat = {
{"keyList", keys},
{"visualInfo", result_visual["visualInfo"]},
{"useVectorRetrieval", true},
{"vectorInfo", result_vector["vectorInfo"]},
{"mllmPredictInfo", result_mllm["mllmPredictInfo"]}
};
auto resp4 = client.Post("/chatocr-chat", payload_chat.dump(), "application/json");
if (!resp4 || resp4->status != 200) {
std::cerr << "chatocr-chat failed.\n"; return 1;
}
json result_chat = json::parse(resp4->body)["result"];
std::cout << "Final chat result: " << result_chat["chatResult"] << std::endl;
return 0;
}
Java
import okhttp3.*;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Iterator;
public class Main {
public static void main(String[] args) throws IOException {
String API_BASE_URL = "http://localhost:8080";
String imagePath = "./demo.jpg";
String[] keys = {"合格证编号"};
OkHttpClient client = new OkHttpClient();
ObjectMapper objectMapper = new ObjectMapper();
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
byte[] imageBytes = java.nio.file.Files.readAllBytes(new File(imagePath).toPath());
String base64Image = Base64.getEncoder().encodeToString(imageBytes);
ObjectNode visualPayload = objectMapper.createObjectNode();
visualPayload.put("file", base64Image);
visualPayload.put("fileType", 1);
Request requestVisual = new Request.Builder()
.url(API_BASE_URL + "/chatocr-visual")
.post(RequestBody.create(JSON, visualPayload.toString()))
.build();
Response responseVisual = client.newCall(requestVisual).execute();
if (!responseVisual.isSuccessful()) {
System.err.println("chatocr-visual failed: " + responseVisual.code());
return;
}
JsonNode resultVisual = objectMapper.readTree(responseVisual.body().string()).get("result");
JsonNode layoutResults = resultVisual.get("layoutParsingResults");
for (int i = 0; i < layoutResults.size(); i++) {
JsonNode res = layoutResults.get(i);
System.out.println("prunedResult [" + i + "]: " + res.get("prunedResult").toString());
JsonNode outputImages = res.get("outputImages");
if (outputImages != null && outputImages.isObject()) {
Iterator names = outputImages.fieldNames();
while (names.hasNext()) {
String imgName = names.next();
String imgBase64 = outputImages.get(imgName).asText();
byte[] imgBytes = Base64.getDecoder().decode(imgBase64);
String imgPath = imgName + "_" + i + ".jpg";
try (FileOutputStream fos = new FileOutputStream(imgPath)) {
fos.write(imgBytes);
System.out.println("Saved image: " + imgPath);
}
}
}
}
ObjectNode vectorPayload = objectMapper.createObjectNode();
vectorPayload.set("visualInfo", resultVisual.get("visualInfo"));
Request requestVector = new Request.Builder()
.url(API_BASE_URL + "/chatocr-vector")
.post(RequestBody.create(JSON, vectorPayload.toString()))
.build();
Response responseVector = client.newCall(requestVector).execute();
if (!responseVector.isSuccessful()) {
System.err.println("chatocr-vector failed: " + responseVector.code());
return;
}
JsonNode resultVector = objectMapper.readTree(responseVector.body().string()).get("result");
ObjectNode mllmPayload = objectMapper.createObjectNode();
mllmPayload.put("image", base64Image);
mllmPayload.putArray("keyList").add(keys[0]);
Request requestMllm = new Request.Builder()
.url(API_BASE_URL + "/chatocr-mllm")
.post(RequestBody.create(JSON, mllmPayload.toString()))
.build();
Response responseMllm = client.newCall(requestMllm).execute();
if (!responseMllm.isSuccessful()) {
System.err.println("chatocr-mllm failed: " + responseMllm.code());
return;
}
JsonNode resultMllm = objectMapper.readTree(responseMllm.body().string()).get("result");
ObjectNode chatPayload = objectMapper.createObjectNode();
chatPayload.putArray("keyList").add(keys[0]);
chatPayload.set("visualInfo", resultVisual.get("visualInfo"));
chatPayload.put("useVectorRetrieval", true);
chatPayload.set("vectorInfo", resultVector.get("vectorInfo"));
chatPayload.set("mllmPredictInfo", resultMllm.get("mllmPredictInfo"));
Request requestChat = new Request.Builder()
.url(API_BASE_URL + "/chatocr-chat")
.post(RequestBody.create(JSON, chatPayload.toString()))
.build();
Response responseChat = client.newCall(requestChat).execute();
if (!responseChat.isSuccessful()) {
System.err.println("chatocr-chat failed: " + responseChat.code());
return;
}
JsonNode resultChat = objectMapper.readTree(responseChat.body().string()).get("result");
System.out.println("Final result:");
System.out.println(resultChat.get("chatResult").toString());
}
}
Go
package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
)
func sendPostRequest(url string, payload map[string]interface{}) (map[string]interface{}, error) {
bodyBytes, err := json.Marshal(payload)
if err != nil {
return nil, fmt.Errorf("error marshaling payload: %v", err)
}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(bodyBytes))
if err != nil {
return nil, fmt.Errorf("error creating request: %v", err)
}
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("error sending request: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("status code error: %d", resp.StatusCode)
}
respBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("error reading response: %v", err)
}
var result map[string]interface{}
if err := json.Unmarshal(respBytes, &result); err != nil {
return nil, fmt.Errorf("error unmarshaling response: %v", err)
}
return result["result"].(map[string]interface{}), nil
}
func main() {
apiBase := "http://localhost:8080"
imagePath := "./demo.jpg"
keys := []string{"合格证编号"}
imageBytes, err := ioutil.ReadFile(imagePath)
if err != nil {
fmt.Printf("read image failed : %v\n", err)
return
}
imageData := base64.StdEncoding.EncodeToString(imageBytes)
visualPayload := map[string]interface{}{
"file": imageData,
"fileType": 1,
}
visualResult, err := sendPostRequest(apiBase+"/chatocr-visual", visualPayload)
if err != nil {
fmt.Printf("chatocr-visual request error: %v\n", err)
return
}
layoutResults := visualResult["layoutParsingResults"].([]interface{})
for i, res := range layoutResults {
layout := res.(map[string]interface{})
fmt.Println("PrunedResult:", layout["prunedResult"])
outputImages := layout["outputImages"].(map[string]interface{})
for name, img := range outputImages {
imgBytes, _ := base64.StdEncoding.DecodeString(img.(string))
filename := fmt.Sprintf("%s_%d.jpg", name, i)
if err := os.WriteFile(filename, imgBytes, 0644); err == nil {
fmt.Printf("save image:%s\n", filename)
}
}
}
vectorPayload := map[string]interface{}{
"visualInfo": visualResult["visualInfo"],
}
vectorResult, err := sendPostRequest(apiBase+"/chatocr-vector", vectorPayload)
if err != nil {
fmt.Printf("chatocr-vector request error: %v\n", err)
return
}
mllmPayload := map[string]interface{}{
"image": imageData,
"keyList": keys,
}
mllmResult, err := sendPostRequest(apiBase+"/chatocr-mllm", mllmPayload)
if err != nil {
fmt.Printf("chatocr-mllm request error: %v\n", err)
return
}
chatPayload := map[string]interface{}{
"keyList": keys,
"visualInfo": visualResult["visualInfo"],
"useVectorRetrieval": true,
"vectorInfo": vectorResult["vectorInfo"],
"mllmPredictInfo": mllmResult["mllmPredictInfo"],
}
chatResult, err := sendPostRequest(apiBase+"/chatocr-chat", chatPayload)
if err != nil {
fmt.Printf("chatocr-chat request error: %v\n", err)
return
}
fmt.Println("final result:", chatResult["chatResult"])
}
C#
using System;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
class Program
{
static readonly string API_BASE_URL = "http://localhost:8080";
static readonly string inputFilePath = "./demo.jpg";
static readonly string[] keys = { "合格证编号" };
static async Task Main(string[] args)
{
var httpClient = new HttpClient();
byte[] imageBytes = File.ReadAllBytes(inputFilePath);
string imageData = Convert.ToBase64String(imageBytes);
var payloadVisual = new JObject
{
{ "file", imageData },
{ "fileType", 1 }
};
var respVisual = await httpClient.PostAsync($"{API_BASE_URL}/chatocr-visual",
new StringContent(payloadVisual.ToString(), Encoding.UTF8, "application/json"));
if (!respVisual.IsSuccessStatusCode)
{
Console.Error.WriteLine($"Request to chatocr-visual failed: {respVisual.StatusCode}");
Console.Error.WriteLine(await respVisual.Content.ReadAsStringAsync());
return;
}
JObject resultVisual = JObject.Parse(await respVisual.Content.ReadAsStringAsync())["result"] as JObject;
var layoutParsingResults = (JArray)resultVisual["layoutParsingResults"];
for (int i = 0; i < layoutParsingResults.Count; i++)
{
var res = layoutParsingResults[i];
Console.WriteLine($"[{i}] prunedResult:\n{res["prunedResult"]}");
JObject outputImages = res["outputImages"] as JObject;
if (outputImages != null)
{
foreach (var img in outputImages)
{
string imgName = img.Key;
string base64Img = img.Value?.ToString();
if (!string.IsNullOrEmpty(base64Img))
{
string imgPath = $"{imgName}_{i}.jpg";
File.WriteAllBytes(imgPath, Convert.FromBase64String(base64Img));
Console.WriteLine($"Output image saved at {imgPath}");
}
}
}
}
var payloadVector = new JObject
{
{ "visualInfo", resultVisual["visualInfo"] }
};
var respVector = await httpClient.PostAsync($"{API_BASE_URL}/chatocr-vector",
new StringContent(payloadVector.ToString(), Encoding.UTF8, "application/json"));
if (!respVector.IsSuccessStatusCode)
{
Console.Error.WriteLine($"Request to chatocr-vector failed: {respVector.StatusCode}");
Console.Error.WriteLine(await respVector.Content.ReadAsStringAsync());
return;
}
JObject resultVector = JObject.Parse(await respVector.Content.ReadAsStringAsync())["result"] as JObject;
var payloadMllm = new JObject
{
{ "image", imageData },
{ "keyList", new JArray(keys) }
};
var respMllm = await httpClient.PostAsync($"{API_BASE_URL}/chatocr-mllm",
new StringContent(payloadMllm.ToString(), Encoding.UTF8, "application/json"));
if (!respMllm.IsSuccessStatusCode)
{
Console.Error.WriteLine($"Request to chatocr-mllm failed: {respMllm.StatusCode}");
Console.Error.WriteLine(await respMllm.Content.ReadAsStringAsync());
return;
}
JObject resultMllm = JObject.Parse(await respMllm.Content.ReadAsStringAsync())["result"] as JObject;
var payloadChat = new JObject
{
{ "keyList", new JArray(keys) },
{ "visualInfo", resultVisual["visualInfo"] },
{ "useVectorRetrieval", true },
{ "vectorInfo", resultVector["vectorInfo"] },
{ "mllmPredictInfo", resultMllm["mllmPredictInfo"] }
};
var respChat = await httpClient.PostAsync($"{API_BASE_URL}/chatocr-chat",
new StringContent(payloadChat.ToString(), Encoding.UTF8, "application/json"));
if (!respChat.IsSuccessStatusCode)
{
Console.Error.WriteLine($"Request to chatocr-chat failed: {respChat.StatusCode}");
Console.Error.WriteLine(await respChat.Content.ReadAsStringAsync());
return;
}
JObject resultChat = JObject.Parse(await respChat.Content.ReadAsStringAsync())["result"] as JObject;
Console.WriteLine("Final result:");
Console.WriteLine(resultChat["chatResult"]);
}
}
Node.js
const axios = require('axios');
const fs = require('fs');
const path = require('path');
const API_BASE_URL = 'http://localhost:8080';
const imagePath = './demo.jpg';
const keys = ['合格证编号'];
function encodeImageToBase64(filePath) {
const bitmap = fs.readFileSync(filePath);
return Buffer.from(bitmap).toString('base64');
}
(async () => {
try {
const imageData = encodeImageToBase64(imagePath);
const respVisual = await axios.post(`${API_BASE_URL}/chatocr-visual`, {
file: imageData,
fileType: 1
});
const resultVisual = respVisual.data.result;
resultVisual.layoutParsingResults.forEach((res, i) => {
console.log(`\n[${i}] prunedResult:\n`, res.prunedResult);
const outputImages = res.outputImages || {};
for (const [imgName, base64Img] of Object.entries(outputImages)) {
const fileName = `${imgName}_${i}.jpg`;
fs.writeFileSync(fileName, Buffer.from(base64Img, 'base64'));
console.log(`Output image saved at ${fileName}`);
}
});
const respVector = await axios.post(`${API_BASE_URL}/chatocr-vector`, {
visualInfo: resultVisual.visualInfo
});
const resultVector = respVector.data.result;
const respMllm = await axios.post(`${API_BASE_URL}/chatocr-mllm`, {
image: imageData,
keyList: keys
});
const resultMllm = respMllm.data.result;
const respChat = await axios.post(`${API_BASE_URL}/chatocr-chat`, {
keyList: keys,
visualInfo: resultVisual.visualInfo,
useVectorRetrieval: true,
vectorInfo: resultVector.vectorInfo,
mllmPredictInfo: resultMllm.mllmPredictInfo
});
const resultChat = respChat.data.result;
console.log('\nFinal result:\n', resultChat.chatResult);
} catch (error) {
if (error.response) {
console.error(`❌ Request failed: ${error.response.status}`);
console.error(error.response.data);
} else {
console.error('❌ Error occurred:', error.message);
}
}
})();
PHP
<?php
$API_BASE_URL = "http://localhost:8080";
$image_path = "./demo.jpg";
$keys = ["合格证编号"];
$image_data = base64_encode(file_get_contents($image_path));
$payload_visual = [
"file" => $image_data,
"fileType" => 1
];
$response_visual_raw = send_post_raw("$API_BASE_URL/chatocr-visual", $payload_visual);
$response_visual = json_decode($response_visual_raw, true);
if (!isset($response_visual["result"])) {
echo "chatocr-visual request error\n";
print_r($response_visual);
exit(1);
}
$result_visual_raw = json_decode($response_visual_raw, false)->result;
$result_visual_arr = $response_visual["result"];
foreach ($result_visual_arr["layoutParsingResults"] as $i => $res) {
echo "[$i] prunedResult:\n";
print_r($res["prunedResult"]);
if (!empty($res["outputImages"])) {
foreach ($res["outputImages"] as $img_name => $base64_img) {
$img_path = "{$img_name}_{$i}.jpg";
file_put_contents($img_path, base64_decode($base64_img));
echo "Output image saved at $img_path\n";
}
}
}
$payload_vector = [
"visualInfo" => $result_visual_raw->visualInfo
];
$response_vector_raw = send_post_raw("$API_BASE_URL/chatocr-vector", $payload_vector);
$response_vector = json_decode($response_vector_raw, true);
if (!isset($response_vector["result"])) {
echo "chatocr-vector request error\n";
print_r($response_vector);
exit(1);
}
$result_vector_raw = json_decode($response_vector_raw, false)->result;
$payload_mllm = [
"image" => $image_data,
"keyList" => $keys
];
$response_mllm_raw = send_post_raw("$API_BASE_URL/chatocr-mllm", $payload_mllm);
$response_mllm = json_decode($response_mllm_raw, true);
if (!isset($response_mllm["result"])) {
echo "chatocr-mllm request error\n";
print_r($response_mllm);
exit(1);
}
$result_mllm_raw = json_decode($response_mllm_raw, false)->result;
$payload_chat = [
"keyList" => $keys,
"visualInfo" => $result_visual_raw->visualInfo,
"useVectorRetrieval" => true,
"vectorInfo" => $result_vector_raw->vectorInfo,
"mllmPredictInfo" => $result_mllm_raw->mllmPredictInfo
];
$response_chat_raw = send_post_raw("$API_BASE_URL/chatocr-chat", $payload_chat);
$response_chat = json_decode($response_chat_raw, true);
if (!isset($response_chat["result"])) {
echo "chatocr-chat request error\n";
print_r($response_chat);
exit(1);
}
echo "Final result:\n";
echo json_encode($response_chat["result"]["chatResult"], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) . "\n";
function send_post_raw($url, $data) {
$json_str = json_encode($data, JSON_UNESCAPED_UNICODE);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_str);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if ($response === false) {
echo "cURL error: " . curl_error($ch) . "\n";
}
curl_close($ch);
return $response;
}
?>
4. 二次开发¶
如果 PP-ChatOCRv4 产线提供的默认模型权重在您的场景中,精度或速度不满意,您可以尝试利用您自己拥有的特定领域或应用场景的数据对现有模型进行进一步的微调,以提升在您的场景中的识别效果。
4.1 模型微调¶
由于 PP-ChatOCRv4 产线包含若干模块,模型产线的效果如果不及预期,可能来自于其中任何一个模块。您可以对提取效果差的 case 进行分析,通过可视化图像,确定是哪个模块存在问题,并参考以下表格中对应的微调教程链接进行模型微调。
情形 | 微调模块 | 微调参考链接 |
---|---|---|
版面区域检测不准,如印章、表格未检出等 | 版面区域检测模块 | 链接 |
表格结构识别不准 | 表格结构识别 | 链接 |
印章文本存在漏检 | 印章文本检测模块 | 链接 |
文本存在漏检 | 文本检测模块 | 链接 |
文本内容都不准 | 文本识别模块 | 链接 |
垂直或者旋转文本行矫正不准 | 文本行方向分类模块 | 链接 |
整图旋转矫正不准 | 文档图像方向分类模块 | 链接 |
图像扭曲矫正不准 | 文本图像矫正模块 | 暂不支持微调 |
4.2 模型应用¶
当您使用私有数据集完成微调训练后,可获得本地模型权重文件,然后可以通过自定义产线配置文件的方式,使用微调后的模型权重。
- 获取产线配置文件
可调用 PaddleOCR 中 PPChatOCRv4 产线对象的 export_paddlex_config_to_yaml
方法,将当前产线配置导出为 YAML 文件:
from paddleocr import PPChatOCRv4
pipeline = PPChatOCRv4()
pipeline.export_paddlex_config_to_yaml("PP-ChatOCRv4.yaml")
- 修改配置文件
在得到默认的产线配置文件后,将微调后模型权重的本地路径替换至产线配置文件中的对应位置即可。例如
......
SubModules:
TextDetection:
module_name: text_detection
model_name: PP-OCRv5_server_det
model_dir: null # 替换为微调后的文本检测模型权重路径
limit_side_len: 960
limit_type: max
thresh: 0.3
box_thresh: 0.6
unclip_ratio: 1.5
TextRecognition:
module_name: text_recognition
model_name: PP-OCRv5_server_rec
model_dir: null # 替换为微调后的文本检测模型权重路径
batch_size: 1
score_thresh: 0
......
在产线配置文件中,不仅包含 PaddleOCR CLI 和 Python API 支持的参数,还可进行更多高级配置,具体信息可在 PaddleX模型产线使用概览 中找到对应的产线使用教程,参考其中的详细说明,根据需求调整各项配置。
- 在 CLI 中加载产线配置文件
在修改完成配置文件后,通过命令行的 --paddlex_config 参数指定修改后的产线配置文件的路径,PaddleOCR 会读取其中的内容作为产线配置。示例如下:
- 在 Python API 中加载产线配置文件
初始化产线对象时,可通过 paddlex_config 参数传入 PaddleX 产线配置文件路径或配置dict,PaddleOCR 会读取其中的内容作为产线配置。示例如下: