轻松解析Amazon Textract返回的JSON。
项目描述
Textract响应解析器
您可以使用Textract响应解析器库轻松解析Amazon Textract返回的JSON。库解析JSON并为编程语言提供特定结构,以便处理文档的不同部分。textractor是利用Textract响应解析器库的PoC批处理工具的一个示例,它能够以多种格式生成输出。
安装
python -m pip install amazon-textract-response-parser
管道和序列化/反序列化
序列化/反序列化
基于marshmallow框架,序列化/反序列化允许创建Textract JSON响应的对象表示。
反序列化Textract JSON
# j holds the Textract JSON dict
from trp.trp2 import TDocument, TDocumentSchema
t_doc = TDocumentSchema().load(j)
序列化Textract
from trp.trp2 import TDocument, TDocumentSchema
t_doc = TDocumentSchema().dump(t_doc)
反序列化Textract AnalyzeId JSON
# j holds the Textract JSON
from trp.trp2_analyzeid import TAnalyzeIdDocument, TAnalyzeIdDocumentSchema
t_doc = TAnalyzeIdDocumentSchema().load(json.loads(j))
将Textract AnalyzeId对象序列化为JSON
from trp.trp2_analyzeid import TAnalyzeIdDocument, TAnalyzeIdDocumentSchema
t_doc = TAnalyzeIdDocumentSchema().dump(t_doc)
管道
我们添加了一些常用功能,作为易于消费的组件,这些组件可以修改Textract JSON模式,并且理想情况下不需要对现有工作流程进行重大更改。
按几何y轴排序块(WORDS、LINES、TABLE、KEY_VALUE_SET)
默认情况下,Textract不会在JSON响应中按顺序放置识别的元素。
Serializer/Deserializer的示例实现order_blocks_by_geo
函数展示了如何更改结构并排序元素,同时保持模式。这样就不需要集成到现有处理中。
# the sample code below makes use of the amazon-textract-caller
python -m pip install amazon-textract-caller
from textractcaller.t_call import call_textract, Textract_Features
from trp.trp2 import TDocument, TDocumentSchema
from trp.t_pipeline import order_blocks_by_geo
import trp
import json
j = call_textract(input_document="path_to_some_document (PDF, JPEG, PNG)", features=[Textract_Features.FORMS, Textract_Features.TABLES])
# the t_doc will be not ordered
t_doc = TDocumentSchema().load(j)
# the ordered_doc has elements ordered by y-coordinate (top to bottom of page)
ordered_doc = order_blocks_by_geo(t_doc)
# send to trp for further processing logic
trp_doc = trp.Document(TDocumentSchema().dump(ordered_doc))
页面方向(以度为单位)
Amazon Textract支持所有平面文档旋转。然而,响应中不包含一个单独的数字来表示度数,而是每个单词和行都有多边形点,可以用来计算旋转度数。以下代码将此信息作为自定义字段添加到Amazon Textract JSON响应中。
from trp.t_pipeline import add_page_orientation
import trp.trp2 as t2
import trp as t1
# assign the Textract JSON dict to j
j = <call_textract(input_document="path_to_some_document (PDF, JPEG, PNG)") or your JSON dict>
t_document: t2.TDocument = t2.TDocumentSchema().load(j)
t_document = add_page_orientation(t_document)
doc = t1.Document(t2.TDocumentSchema().dump(t_document))
# page orientation can be read now for each page
for page in doc.pages:
print(page.custom['PageOrientationBasedOnWords'])
在命令行上使用管道
amazon-textract-response-parser包还包括一个命令行工具,用于测试管道组件,如add_page_orientation或order_blocks_by_geo。
以下是一个使用示例(与amazon-textract-helper中的amazon-textract
命令和jq
工具(https://stedolan.github.io/jq/)结合使用)
> amazon-textract --input-document "s3://somebucket/some-multi-page-pdf.pdf" | amazon-textract-pipeline --components add_page_orientation | jq '.Blocks[] | select(.BlockType=="PAGE") | .Custom'm
{
"Orientation": 7
}
{
"Orientation": 11
}
...
{
"Orientation": -7
}
{
"Orientation": 0
}
跨页面合并或链接表格
有时表格开始于一页并继续到下一页或更多页。此组件根据列数以及后续表格中是否存在标题来识别这种情况,并可以修改输出Textract JSON模式以进行下游处理。还可以为特定用例开发其他自定义逻辑。
MergeOptions.MERGE合并表格,使它们在后续处理中看起来像一个整体,缺点是几何信息不再准确。因此,使用边界框叠加将不会准确。
MergeOptions.LINK保持几何结构,并使用表元素之间的链接丰富表信息。在Textract JSON模式中的TABLE块中添加了自定义['previus_table']和custom['next_table']属性。
用法简单
from trp.t_pipeline import pipeline_merge_tables
import trp.trp2 as t2
j = <call_textract(input_document="path_to_some_document (PDF, JPEG, PNG)") or your JSON dict>
t_document: t2.TDocument = t2.TDocumentSchema().load(j)
t_document = pipeline_merge_tables(t_document, MergeOptions.MERGE, None, HeaderFooterType.NONE)
从命令行使用示例
# from the root of the repository
cat src-python/tests/data/gib_multi_page_table_merge.json | amazon-textract-pipeline --components merge_tables | amazon-textract --stdin --pretty-print TABLES
# compare to cat src-python/tests/data/gib_multi_page_table_merge.json | amazon-textract --stdin --pretty-print TABLES
将OCR置信度分数添加到KEY和VALUE
对于某些用例,验证来自具有表单功能的分析操作的给定KEY或VALUE的置信度分数可能很有用。
BlockType 'KEY_VALUE_SET'的Confidence属性表示对特定预测是KEY或VALUE的置信度,但不表示底层文本值的置信度。
简化示例
{
"Confidence": 95.5,
"Geometry": {<...>},
"Id": "v1",
"Relationships": [{"Type": "CHILD", "Ids": ["c1"]}],
"EntityTypes": ["VALUE"],
"BlockType": "KEY_VALUE_SET"
},
{
"Confidence": 99.2610092163086,
"TextType": "PRINTED",
"Geometry": {<...>},
"Id": "c1",
"Text": "2021-Apr-08",
"BlockType": "WORD"
},
在此示例中,预测VALUE是键/值关系中实际值的置信度为95.5。
实际文本表示的置信度为99.2610092163086。为了简化,在此示例中值仅由一个单词组成,但不仅限于一个单词,可以包含多个单词。
KV_OCR_Confidence管道组件将底层OCR的置信度分数添加到JSON。执行示例后,JSON将如下所示
{
"Confidence": 95.5,
"Geometry": {<...>},
"Id": "v1",
"Relationships": [{"Type": "CHILD", "Ids": ["c1"]}],
"EntityTypes": ["VALUE"],
"BlockType": "KEY_VALUE_SET",
"Custom": {"OCRConfidence": {"mean": 99.2610092163086, "min": 99.2610092163086}}
},
{
"Confidence": 99.2610092163086,
"TextType": "PRINTED",
"Geometry": {<...>},
"Id": "c1",
"Text": "2021-Apr-08",
"BlockType": "WORD"
},
用法简单
from trp.t_pipeline import add_kv_ocr_confidence
import trp.trp2 as t2
j = <call_textract(input_document="path_to_some_document (PDF, JPEG, PNG)") or your JSON dict>
t_document: t2.TDocument = t2.TDocumentSchema().load(j)
t_document = add_kv_ocr_confidence(t_document)
# further processing
从命令行使用示例和验证输出
# from the root of the repository
cat "src-python/tests/data/employment-application.json" | amazon-textract-pipeline --components kv_ocr_confidence | jq '.Blocks[] | select(.BlockType=="KEY_VALUE_SET") '
解析来自Textract的JSON响应
from trp import Document
doc = Document(response)
# Iterate over elements in the document
for page in doc.pages:
# Print lines and words
for line in page.lines:
print("Line: {}--{}".format(line.text, line.confidence))
for word in line.words:
print("Word: {}--{}".format(word.text, word.confidence))
# Print tables
for table in page.tables:
for r, row in enumerate(table.rows):
for c, cell in enumerate(row.cells):
print("Table[{}][{}] = {}-{}".format(r, c, cell.text, cell.confidence))
# Print fields
for field in page.form.fields:
print("Field: Key: {}, Value: {}".format(field.key.text, field.value.text))
# Get field by key
key = "Phone Number:"
field = page.form.getFieldByKey(key)
if(field):
print("Field: Key: {}, Value: {}".format(field.key, field.value))
# Search fields by key
key = "address"
fields = page.form.searchFieldsByKey(key)
for field in fields:
print("Field: Key: {}, Value: {}".format(field.key, field.value))
测试
- 克隆仓库并运行pytest
git clone https://github.com/aws-samples/amazon-textract-response-parser.git
cd amazon-textract-response-parser
python -m venv virtualenv
virtualenv/bin/activate
python -m pip install --upgrade pip setuptools
python -m pip install -e .[dev]
pytest
其他资源
许可总结
此示例代码根据Apache License Version 2.0提供。请参阅LICENSE文件。
项目详情
散列值 for amazon-textract-response-parser-1.0.3.tar.gz
算法 | 散列摘要 | |
---|---|---|
SHA256 | 7d7f56702bb576e24949ff5ca98d75d546fec12923ee97e399f6b72f5c6db018 |
|
MD5 | d994390210c9dcf195f3f5047733f08e |
|
BLAKE2b-256 | aa02ddb91991661ba7728df7e816694c758eac45508abb3261e5aee25a434ba2 |
散列值 for amazon_textract_response_parser-1.0.3-py2.py3-none-any.whl
算法 | 散列摘要 | |
---|---|---|
SHA256 | 834ffcec01085b82565b3f55625572f3425885918f09380cbe9e7fb02a7c8de7 |
|
MD5 | 5cbdc548f4a4f096cfbd19429edb82a6 |
|
BLAKE2b-256 | 84ef6c18d048a64e1a7b8372ebaf154f989299110fa5909b4893f06e99db588b |