使用神经网络提取PDF表格工具来了,支持图片,关键是能白嫖谷歌GPU资源

贾浩楠 发自 凹非寺
量子位 报道 | 公众号 QbitAI

“表哥表姐”们还在为大量PDF文件中的表格发愁吗?

百度一下,网上有大量提取PDF表格的工具,但是,它们都只支持文本格式PDF。

但扫描生成的图片表格怎么办?

别着急,一种使用深度神经网络识别提取表格的开源工具可以帮助你。

兼容图片、高准确率、还不占用本地运算资源,如此实用的工具值得你拥有。

测试实例

如果在输入的PDF文件中检测的表格,模型会在边界框(bounding box)标出表格边框:

然后,表格数据会被转化为Panda数据框架,方便后续处理:

怎么样,是不是很实用?那这个工具如何使用呢?

使用姿势详解

神经网络算法,还不占用本地运算资源?

对,你没听错,这个工具的所有代码都可以在谷歌Colab上运行。也就是说你可以利用Colab云端资源完成训练和推理,无需本地安装。

这个工具使用到的深度神经网络是Keras-RetinaNet,首先要在Colab上安装Keras-RetinaNet,通过一下一行代码就可以完成:

git clone https://github.com/fizyr/keras-retinanet

同时需要安装必要的库:

pip install .
python setup.py build_ext — inplace

训练Keras-RetinaNet识别表格

首先要构建或一个训练使用的数据库。

这里要用到Colab工具PDF2Img,将PDF文件转为JPG格式供算法学习。

然后将转好的图片保存在Images文件夹中。接下来需要手动给这些训练数据打标签,这里推荐使用在线标记工具makesense.ai。

将XML注释文件保存在注释文件夹中,并创建用于培训和测试的PDF文件列表,将该列表导入train.txt和test.txt中。

接下来,克隆Github项目https://github.com/ferrygun/PDFTableExtract,并安装beautifulsoup。

运行以下命令以将PASCALVOC格式转换为Keras-RetinaNet所需的格式:

python build_logos.py

运行上述命令后,会得到retinanet_classes.csv,retinanet_test.csv和retinanet_train.csv。

在retinanet_classses.csv中,由于只识别PDF文档中的表,所以只有到一个class,即class 0。

如果你在打标签的过程中加入页眉页脚等标签,相应能得到多个class。

完整的文件和文件夹结构的列表:

然后,将retinanet_classes.csv,retinanet_test.csv,retinanet_train.csv,train.txt和test.txt 导入keras-retinanet的根文件夹中:

接下来,运行Colab TrainOCR,可以根据要训练的JPG文件数量来调整训练的epoch数量。

训练完成后,就会得到权重文件output.h5,下载此文件并将其保存到本地主机。后面将使用该文件来运行测试。

这里需要注意的一点是,在Colab中,已将文件上传到Git并进行了Git克隆。

运行测试

运行测试前,还需要安装处理PDF文件必要的库。

PyPDF2是一个python工具库,能够提取文档信息,裁剪页面等。

使用以下命令安装此库:

pip install PyPDF2

Camelot是专门用于解析PDF页面表格的python库。

使用以下命令安装此库:

pip install camelot-py[cv]

PDF2IMG是将Python转换为PIL Image对象的python库。

使用以下命令安装此库:

pip install pdf2imag

在运行预测之前,需要使用从训练中获得的权重文件output.h5加载模型,并从retinanet_classes.csv定义标签class 0。

model_path = ‘output.h5’
model = models.load_model(model_path, backbone_name=’resnet50’)
labels = ‘retinanet_classes.csv’
LABELS = open(labels).read().strip().split(‘\n’)
LABELS = {int(L.split(‘,’)[1]): L.split(‘,’)[0] for L in LABELS}
print(LABELS)
{0: ‘tabel’}

接下来运行测试

import numpy as np
import cv2
import matplotlib.pyplot as plt


image_path = imgfname
#image = cv2.imread(image_path)
image = read_image_bgr(image_path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)


output = image.copy()
output = cv2.cvtColor(output, cv2.COLOR_BGR2RGB)
print(output.shape) # row (height) x column (width) x color (3)


image = preprocess_image(image)
(image, scale) = resize_image(image)
image = np.expand_dims(image, axis=0)


# detect objects in the input image and correct for the image scale
(boxes, scores, labels) = model.predict_on_batch(image)
boxes /= scale


confidence =  0.2
from google.colab.patches import cv2_imshow
import matplotlib.pyplot as plt
label_out = []
result = ""


# loop over the detections
for (box, score, label) in zip(boxes[0], scores[0], labels[0]):
  # filter out weak detections
  if score < confidence:
    continue


  # convert the bounding box coordinates from floats to integers
  box = box.astype("int")


  # build the label and draw the label + bounding box on the output
  # image
  labeli = label
  label = "{}: {:.2f}".format(LABELS[label], score)
  print(label)


  if LABELS[labeli] not in label_out:
      label_out.append(LABELS[labeli])
      cv2.rectangle(output, (box[0], box[1]), (box[2], box[3]), (255, 0, 0), 12)
      print(box[0])
      print(box[1])
      print(box[2])
      print(box[3])
      #result      
      cv2.putText(output, label, (box[0], box[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 4.5, (255, 1, 1), 12)


plt.figure(figsize=(20, 20))
plt.imshow(output)
plt.show()

如果检测的表格,模型会在边界框(bounding box)标出表格边框:

边界框坐标(x1,y1,x2,y2),将table_area输入到Camelot read_pdf函数中,table_area是已标准化的边界框。

interesting_areas=[]


output = [[x1, y1, x2, y2]]
for x in output:
  [x1, y1, x2, y2] = bboxes_pdf(img, pdf_page, x)
  bbox_camelot = [
            ",".join([str(x1), str(y1), str(x2), str(y2)])
        ][0]  # x1,y1,x2,y2 where (x1, y1) -> left-top and (x2, y2) -> right-bottom in PDF coordinate space
        #print(bbox_camelot)
  interesting_areas.append(bbox_camelot)




print(interesting_areas)
output_camelot = camelot.read_pdf(
    filepath=pdf_file, pages=str(pg), flavor="stream", table_areas=interesting_areas
)


output_camelot[0].df

这样就可以将表格数据转化为Panda数据框架,方便后续处理:

图片怎么办

针对扫描图片格式的PDF表格,可以使用Ocrmypdf包来将图片格式PDF转为文本格式。

Ocrmypdf是一个python软件包,可将基于图像的pdf转换为基于文本的PDF。

安装ocrmypdf,可以通过以下命令行将其用于macOS和Linux:

brew install ocrmypdf

通过以下命令调用:

ocrmypdf input_file.pdf output_file.pdf

之后就可以按照上面的方法进行表格提取了。

怎么样,这款兼容图片,又能白嫖谷歌GPU的PDF表格工具对你有帮助吗?

传送门

项目地址:
https://github.com/ferrygun/PDFTableExtract

在线打标签工具:
https://www.makesense.ai/

本文系网易新闻•网易号特色内容激励计划签约账号【量子位】原创内容,未经账号授权,禁止随意转载。

每天5分钟,抓住行业发展机遇

如何关注、学习、用好人工智能? 

每个工作日,量子位AI内参精选全球科技和研究最新动态,汇总新技术、新产品和新应用,梳理当日最热行业趋势和政策,搜索有价值的论文、教程、研究等。

同时,AI内参群为大家提供了交流和分享的平台,更好地满足大家获取AI资讯、学习AI技术的需求。扫码即可订阅:

加入AI社群,与优秀的人交流

量子位 QbitAI · 头条号签约作者

վ'ᴗ' ի 追踪AI技术和产品新动态

喜欢就点「在看」吧 !

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值