前言
LayoutParser
专为文档布局解析设计,能精准识别试卷中的文本块、标题、列表等区域,适配不同版式试卷,常作为试卷分割的优先选择,无需复杂二次开发。
环境要求
依赖中使用到了zoneinfo ,zoneinfo 模块是从 Python 3.9 开始引入的。
所以我们的Python的最低要求是3.9。
添加依赖
1 2 3 4 5 6 7 8 9 10 11
| pipenv lock --clear
pipenv install layoutparser==0.3.4
pipenv install "layoutparser[layoutmodels]"
pipenv install "layoutparser[ocr]"
|
不建议使用下面的方式安装,这种相当于跳过pipenv的版本验证,直接安装依赖的,并且依赖不会记录在Pipfile中。
1
| pipenv run pip install layoutparser
|
代码示例
编写代码实现分割:加载预训练模型,读取试卷图像并完成分割与可视化
示例代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| import layoutparser as lp from PIL import Image
model = lp.AutoLayoutModel('lp://EfficientDet/PubLayNet') print(f"模型加载结果:{model}") if model is None: raise ValueError("模型加载失败!请检查模型标识符、依赖或缓存文件")
image = Image.open("test_paper.jpg")
layout = model.detect(image)
lp.draw_box(image, layout, box_width=1, show_element_id=True, box_alpha=0.5) image.show()
|
结果
模型下载不下来,没法测试。
LayoutLMv3
在安装LayoutLMv3前,请确保您的系统已满足以下条件:
- Python 3.7及以上版本
- PyTorch 1.7.0及以上版本
- 至少4GB内存(推荐8GB以上)
- 支持CUDA的GPU(可选,用于加速计算)
Clone仓库
1 2
| git clone https://gitcode.com/hf_mirrors/microsoft/layoutlmv3-base cd layoutlmv3-base
|
虚拟环境
在项目下添加文件.env
1
| PIPENV_VENV_IN_PROJECT=1
|
当系统环境变量和.env文件同时存在某个配置的时候,pipenv 会优先使用.env里的值。
添加
Pipfile
1 2 3 4 5 6 7 8 9 10 11
| [[source]] url = "https://mirrors.huaweicloud.com/repository/pypi/simple" verify_ssl = false name = "pip_conf_index_global"
[packages]
[dev-packages]
[requires] python_version = "3.9"
|
安装依赖包
清除缓存
安装依赖
1
| pipenv install transformers torch pillow pytesseract
|
1 2 3
| git clone https://github.com/imzhuhl/LayoutLMv3-PaperSegment.git cd LayoutLMv3-PaperSegment python download_weights.py
|
文档分类
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| from transformers import LayoutLMv3Processor, LayoutLMv3ForTokenClassification
processor = LayoutLMv3Processor.from_pretrained('./') model = LayoutLMv3ForTokenClassification.from_pretrained('./')
def classify_document(image, text): encoding = processor(image, text, return_tensors="pt") outputs = model(**encoding) predictions = outputs.logits.argmax(-1) return predictions
|
数据标注框架 Label Studio
数据标注开源框架 Label Studio
安装
1 2 3 4 5 6 7 8 9 10
| conda create -n labelstudio python=3.11
conda activate labelstudio
pip install label-studio
label-studio start
label-studio start --port 9001
|