首页 > 解决方案 > 基于 Python 的统计模型,用于自动检测 PDF 上表单字段的坐标

问题描述

我想检测可填充 PDF 表单的坐标,更准确地说是要放置特定文本字段(字符串)的文本框的边界框坐标。

目前,我正在使用一种硬编码的 Python-Pdfminer 方法,使用 LTTBox 根据某些字符串的存在来检测坐标。

例子:

def identifyTextboxes(path, fieldName, fieldType):
    # reading the file and setting prams
    fp = open(path, 'rb')
    rsrcmgr = PDFResourceManager()
    laparams = LAParams()
    device = PDFPageAggregator(rsrcmgr, laparams=laparams)
    interpreter = PDFPageInterpreter(rsrcmgr, device)
    pages = PDFPage.get_pages(fp)

    # defining key-terms of custodian:
    names=["Name of entity:", "Name of Investor (Please Print or Type)", "Print Name of Entity", "Name of Prospective Investor ", 
    "Investor's Name", "Name (the “Applicant” or “We”)", "On Behalf of:", "Name of Business"]

    num_pages = 0
    output = []
    for page in pages:
        temp_dict = {}
        interpreter.process_page(page)
        layout = device.get_result()
        num_pages += 1

        # fetching the coordinates of the text via bbox
        for lobj in layout:
            if isinstance(lobj, LTTextBox):
                (x, y, xw, yh), text = lobj.bbox, lobj.get_text()
                for name in names:
                    ResSearch = re.search(name, text)                
                    if ResSearch:break
                    field='textbox'
            if ResSearch:break
        if ResSearch:
            temp_dict['label'] = fieldName
            temp_dict['type'] = fieldType
            temp_dict["value"] = ''
            temp_dict['group'] = ''
            temp_dict["overlay"] = {'page': num_pages, 'left': (xw)-90, 'top':((y-10)-(yh-y))+90, 'height': 20, 'width':240}
            output.append(temp_dict)
            print(lobj)
    return output

在上面的代码中,我从列表名称中检测到匹配字符串出现的位置,并根据 LTTBox 坐标和固定值定义外观右侧文本框的坐标,正如您在返回输出中看到的那样[ '覆盖']。

这个过程是非常硬编码的,当 PDF 中出现任何未知字符串或情况时会失败,因此不是那么健壮。

我想推动一种数据驱动的统计方法,通过 CNN/RNN/CNN+RNN 检测边界框的坐标。我已经通过了EAST 检测器,但这似乎并没有解决问题,所以也许训练一个更定制的网络应该更有用。

请查找随附的图片,以便更好地了解当前代码的作用。 在此处输入图像描述 在此处输入图像描述

我是 ML 新手,我需要指导来构建这种网络。非常感谢任何帮助。

标签: pythontensorflowneural-networkconv-neural-networkrecurrent-neural-network

解决方案


如果表单是正确的 PDF AcroForm 字段,您只需阅读 PDF 文件即可轻松找到它们。

只需在您的 PDF 文件中查找这样的文本:

7 0 obj
<<
/Type /Annot 
/Subtype /Widget 
/Rect [ 87.539 495.187 139.289 511.890 ] 
/F 4 
/FT /Tx 
/H /N 
/R 0 
/Ff 4194304 
/BS << /W 1 /S /S  >>
/MK <</BC [ 0.267 0.267 0.267 ] /BG [ 0.996 0.839 0.804 ]  >>
/T (name1[first])
/TU (<FE><FF>)
/DV ()
/DA (/F2 9.9 Tf 0.000 g)
/NM (0007-5003)
/M (D:20181012063448)
>>

另一个例子:

23 0 obj
<</Type/Annot/Subtype/Widget/F 4
/Rect[165.7 388.3 315.7 402.5]
/FT/Tx
/P 1 0 R
/T(Address 1 Text Box)
/V <FEFF>
/DV <FEFF>
/MaxLen 40
/DR<</Font 6 0 R>>
/DA(0 0 0 rg /F3 11 Tf)
/AP<<
/N 60 0 R
>>
>>
endobj

字段的坐标是 之后的数字/Rect,按左、下、右、上的顺序排列。

可能是有问题的对象被压缩了。在这种情况下,您不会将其视为文本。在这种情况下,我建议使用mutool clean -d input.pdf readable.pdf解压缩 PDF 文件中的所有对象,使文件在文本编辑器中可读。mutoolmupdf附带的命令行工具。


推荐阅读