Microsoft Azure Form Recognizer Python客户端库
项目描述
Azure表单识别器Python客户端库
Azure文档智能(以前称为表单识别器)是一个云服务,它使用机器学习分析您的文档中的文本和结构化数据。它包括以下主要功能
- 布局 - 从文档中提取内容结构(例如,单词、选择标记、表格)。
- 文档 - 除了一般布局外,分析文档中的键值对。
- 读取 - 从文档中读取页面信息。
- 预建 - 使用预建模型从选定的文档类型(例如收据、发票、名片、身份证件、美国W-2税务文件等)中提取常用字段值。
- 自定义 - 使用自己的数据构建自定义模型,以从文档中提取定制的字段值,包括一般布局。
- 分类器 - 构建自定义分类模型,结合布局和语言特征,以准确检测和识别您在应用程序中处理的文档。
- 附加功能 - 提取条形码/二维码、公式、字体/样式等,或为大型文档启用高分辨率模式,可选参数。
源代码 | 包(PyPI) | 包(Conda) | API参考文档 | 产品文档 | 示例
免责声明
本包支持以下服务API版本:2.0、2.1、2022-08-31和2023-07-31。服务API版本2023-10-31-preview及以后的版本在包azure-ai-documentintelligence中得到支持。有关迁移详情,请参阅此文档。
入门
先决条件
- 使用此包需要Python 3.8或更高版本。
- 您必须拥有一个Azure订阅和一个认知服务或表单识别资源才能使用此包。
安装包
使用pip安装Azure表单识别Python客户端库
pip install azure-ai-formrecognizer
注意:此版本客户端库默认使用服务的
2023-07-31版本。
此表显示了SDK版本与服务支持的API版本之间的关系
| SDK版本 | 服务支持的API版本 |
|---|---|
| 3.3.X - 最新GA版本 | 2.0、2.1、2022-08-31、2023-07-31(默认) |
| 3.2.X | 2.0、2.1、2022-08-31(默认) |
| 3.1.X | 2.0、2.1(默认) |
| 3.0.0 | 2.0 |
注意:从版本
3.2.X开始,引入了一套新客户端以利用文档智能服务的新功能。请参阅迁移指南,了解如何将应用程序代码从客户端库版本3.1.X或更低版本更新到最新版本。此外,请参阅更改日志以获取更多信息。以下表格描述了每个客户端及其支持的API版本
| API版本 | 支持的客户端 |
|---|---|
| 2023-07-31 | DocumentAnalysisClient和DocumentModelAdministrationClient |
| 2022-08-31 | DocumentAnalysisClient和DocumentModelAdministrationClient |
| 2.1 | FormRecognizerClient和FormTrainingClient |
| 2.0 | FormRecognizerClient和FormTrainingClient |
创建认知服务或表单识别资源
文档智能服务支持多服务和单服务访问。如果您计划通过单个端点/密钥访问多个认知服务,请创建认知服务资源。仅用于文档智能服务访问,请创建表单识别资源。请注意,如果您打算使用Azure Active Directory身份验证,则需要单服务资源。
您可以使用以下方式创建资源
以下是如何使用CLI创建表单识别资源的示例
# Create a new resource group to hold the Form Recognizer resource
# if using an existing resource group, skip this step
az group create --name <your-resource-name> --location <location>
# Create form recognizer
az cognitiveservices account create \
--name <your-resource-name> \
--resource-group <your-resource-group-name> \
--kind FormRecognizer \
--sku <sku> \
--location <location> \
--yes
有关创建资源或获取位置和SKU信息的更多信息,请参阅此处。
客户端认证
为了与文档智能服务交互,您需要创建一个客户端实例。创建客户端对象需要端点和凭据。
获取端点
您可以通过Azure门户或Azure CLI找到您的表单识别器资源的端点。
# Get the endpoint for the Form Recognizer resource
az cognitiveservices account show --name "resource-name" --resource-group "resource-group-name" --query "properties.endpoint"
可以使用区域端点或自定义子域进行认证。它们的格式如下
Regional endpoint: https://<region>.api.cognitive.microsoft.com/
Custom subdomain: https://<resource-name>.cognitiveservices.azure.com/
区域端点在区域内的每个资源中都是相同的。可以在此处查看支持的完整区域端点列表此处。请注意,区域端点不支持Azure Active Directory认证。
另一方面,自定义子域是表单识别器资源独有的名称。它们只能由单服务资源使用。
获取API密钥
API密钥可以在Azure门户中找到,或者通过运行以下Azure CLI命令来获取
az cognitiveservices account keys list --name "<resource-name>" --resource-group "<resource-group-name>"
使用AzureKeyCredential创建客户端
要将API密钥作为credential参数,请将密钥作为字符串传递到AzureKeyCredential的一个实例中。
from azure.core.credentials import AzureKeyCredential
from azure.ai.formrecognizer import DocumentAnalysisClient
endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/"
credential = AzureKeyCredential("<api_key>")
document_analysis_client = DocumentAnalysisClient(endpoint, credential)
使用Azure Active Directory凭据创建客户端
本指南中的示例使用AzureKeyCredential认证,但您也可以使用azure-identity库通过Azure Active Directory进行认证。请注意,区域端点不支持AAD认证。为了使用此类型认证,请为您的资源创建一个自定义子域名称。
要使用以下示例中的DefaultAzureCredential类型或其他由Azure SDK提供的凭据类型,请安装azure-identity包
pip install azure-identity
您还需要注册一个新的Azure Active Directory应用程序并授予访问权限,通过将"Cognitive Services User"角色分配给您的服务主体来实现对文档智能的访问。
完成操作后,将Azure Active Directory应用程序的客户端ID、租户ID和客户端机密作为环境变量设置值:AZURE_CLIENT_ID、AZURE_TENANT_ID、AZURE_CLIENT_SECRET。
"""DefaultAzureCredential will use the values from these environment
variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET
"""
from azure.ai.formrecognizer import DocumentAnalysisClient
from azure.identity import DefaultAzureCredential
endpoint = os.environ["AZURE_FORM_RECOGNIZER_ENDPOINT"]
credential = DefaultAzureCredential()
document_analysis_client = DocumentAnalysisClient(endpoint, credential)
关键概念
DocumentAnalysisClient
DocumentAnalysisClient通过begin_analyze_document和begin_analyze_document_from_url API提供分析输入文档的操作,使用预构建和自定义模型。使用model_id参数选择分析模型的类型。有关支持的完整模型列表,请参阅此处。《DocumentAnalysisClient》还通过begin_classify_document和begin_classify_document_from_url API提供对文档进行分类的操作。自定义分类模型可以分类输入文件中的每一页以识别文档,也可以识别输入文件中的多个文档或单个文档的多个实例。
提供了示例代码片段来展示如何使用DocumentAnalysisClient此处。有关分析文档的更多信息,包括支持的特性、区域和文档类型,请参阅服务文档。
文档模型管理客户端
DocumentModelAdministrationClient 提供以下操作:
- 通过标记您的自定义文档来构建用于分析您指定的特定字段的自定义模型。返回一个
DocumentModelDetails对象,指示模型可以分析哪些文档类型,以及每个字段的估计置信度。有关更详细的解释,请参阅服务文档。 - 从现有模型集合中创建一个组合模型。
- 管理您账户中创建的模型。
- 列出操作或获取在过去24小时内创建的特定模型操作。
- 将自定义模型从一个表单识别资源复制到另一个。
- 构建并管理自定义分类模型,以对您应用程序中处理的文档进行分类。
请注意,您还可以使用如图形用户界面(例如文档智能工作室)之类的工具来构建模型。
以下提供了示例代码片段,以说明如何使用 此处 的 DocumentModelAdministrationClient。
长时间运行的操作
长时间运行的操作是指由向服务发送初始请求以启动操作组成,然后以一定时间间隔轮询服务以确定操作是否完成或失败,如果成功,则获取结果的操作。
分析文档、构建模型或复制/组合模型的操作被建模为长时间运行的操作。客户端公开了一个返回 LROPoller 或 AsyncLROPoller 的 begin_<method-name> 方法。调用者应通过在从 begin_<method-name> 方法返回的轮询对象上调用 result() 来等待操作完成。以下提供了示例代码片段,以说明如何使用长时间运行的操作如下。
示例
以下部分提供了几个代码片段,涵盖了文档智能的一些最常见任务,包括
提取布局
从文档中提取文本、选择标记、文本样式和表格结构,以及它们的边界区域坐标。
from azure.core.credentials import AzureKeyCredential
from azure.ai.formrecognizer import DocumentAnalysisClient
endpoint = os.environ["AZURE_FORM_RECOGNIZER_ENDPOINT"]
key = os.environ["AZURE_FORM_RECOGNIZER_KEY"]
document_analysis_client = DocumentAnalysisClient(
endpoint=endpoint, credential=AzureKeyCredential(key)
)
with open(path_to_sample_documents, "rb") as f:
poller = document_analysis_client.begin_analyze_document(
"prebuilt-layout", document=f
)
result = poller.result()
for idx, style in enumerate(result.styles):
print(
"Document contains {} content".format(
"handwritten" if style.is_handwritten else "no handwritten"
)
)
for page in result.pages:
print("----Analyzing layout from page #{}----".format(page.page_number))
print(
"Page has width: {} and height: {}, measured with unit: {}".format(
page.width, page.height, page.unit
)
)
for line_idx, line in enumerate(page.lines):
words = line.get_words()
print(
"...Line # {} has word count {} and text '{}' within bounding polygon '{}'".format(
line_idx,
len(words),
line.content,
line.polygon,
)
)
for word in words:
print(
"......Word '{}' has a confidence of {}".format(
word.content, word.confidence
)
)
for selection_mark in page.selection_marks:
print(
"...Selection mark is '{}' within bounding polygon '{}' and has a confidence of {}".format(
selection_mark.state,
selection_mark.polygon,
selection_mark.confidence,
)
)
for table_idx, table in enumerate(result.tables):
print(
"Table # {} has {} rows and {} columns".format(
table_idx, table.row_count, table.column_count
)
)
for region in table.bounding_regions:
print(
"Table # {} location on page: {} is {}".format(
table_idx,
region.page_number,
region.polygon,
)
)
for cell in table.cells:
print(
"...Cell[{}][{}] has content '{}'".format(
cell.row_index,
cell.column_index,
cell.content,
)
)
for region in cell.bounding_regions:
print(
"...content on page {} is within bounding polygon '{}'".format(
region.page_number,
region.polygon,
)
)
print("----------------------------------------")
使用通用文档模型
使用 Document Intelligence 服务提供的通用文档模型从文档中分析键值对、表格、样式和选择标记。通过将 model_id="prebuilt-document" 传递给 begin_analyze_document 方法来选择通用文档模型
from azure.core.credentials import AzureKeyCredential
from azure.ai.formrecognizer import DocumentAnalysisClient
endpoint = os.environ["AZURE_FORM_RECOGNIZER_ENDPOINT"]
key = os.environ["AZURE_FORM_RECOGNIZER_KEY"]
document_analysis_client = DocumentAnalysisClient(
endpoint=endpoint, credential=AzureKeyCredential(key)
)
with open(path_to_sample_documents, "rb") as f:
poller = document_analysis_client.begin_analyze_document(
"prebuilt-document", document=f
)
result = poller.result()
for style in result.styles:
if style.is_handwritten:
print("Document contains handwritten content: ")
print(",".join([result.content[span.offset:span.offset + span.length] for span in style.spans]))
print("----Key-value pairs found in document----")
for kv_pair in result.key_value_pairs:
if kv_pair.key:
print(
"Key '{}' found within '{}' bounding regions".format(
kv_pair.key.content,
kv_pair.key.bounding_regions,
)
)
if kv_pair.value:
print(
"Value '{}' found within '{}' bounding regions\n".format(
kv_pair.value.content,
kv_pair.value.bounding_regions,
)
)
for page in result.pages:
print("----Analyzing document from page #{}----".format(page.page_number))
print(
"Page has width: {} and height: {}, measured with unit: {}".format(
page.width, page.height, page.unit
)
)
for line_idx, line in enumerate(page.lines):
words = line.get_words()
print(
"...Line # {} has {} words and text '{}' within bounding polygon '{}'".format(
line_idx,
len(words),
line.content,
line.polygon,
)
)
for word in words:
print(
"......Word '{}' has a confidence of {}".format(
word.content, word.confidence
)
)
for selection_mark in page.selection_marks:
print(
"...Selection mark is '{}' within bounding polygon '{}' and has a confidence of {}".format(
selection_mark.state,
selection_mark.polygon,
selection_mark.confidence,
)
)
for table_idx, table in enumerate(result.tables):
print(
"Table # {} has {} rows and {} columns".format(
table_idx, table.row_count, table.column_count
)
)
for region in table.bounding_regions:
print(
"Table # {} location on page: {} is {}".format(
table_idx,
region.page_number,
region.polygon,
)
)
for cell in table.cells:
print(
"...Cell[{}][{}] has content '{}'".format(
cell.row_index,
cell.column_index,
cell.content,
)
)
for region in cell.bounding_regions:
print(
"...content on page {} is within bounding polygon '{}'\n".format(
region.page_number,
region.polygon,
)
)
print("----------------------------------------")
- 有关
prebuilt-document模型提供的功能的更多信息,请参阅此处。
使用预构建模型
使用 Document Intelligence 服务提供的预构建模型从选定的文档类型(如收据、发票、名片、身份证件和美国的 W-2 税收文件)中提取字段。
例如,要分析销售收据的字段,请使用通过将 model_id="prebuilt-receipt" 传递给 begin_analyze_document 方法提供的预构建收据模型
from azure.core.credentials import AzureKeyCredential
from azure.ai.formrecognizer import DocumentAnalysisClient
endpoint = os.environ["AZURE_FORM_RECOGNIZER_ENDPOINT"]
key = os.environ["AZURE_FORM_RECOGNIZER_KEY"]
document_analysis_client = DocumentAnalysisClient(
endpoint=endpoint, credential=AzureKeyCredential(key)
)
with open(path_to_sample_documents, "rb") as f:
poller = document_analysis_client.begin_analyze_document(
"prebuilt-receipt", document=f, locale="en-US"
)
receipts = poller.result()
for idx, receipt in enumerate(receipts.documents):
print(f"--------Analysis of receipt #{idx + 1}--------")
print(f"Receipt type: {receipt.doc_type if receipt.doc_type else 'N/A'}")
merchant_name = receipt.fields.get("MerchantName")
if merchant_name:
print(
f"Merchant Name: {merchant_name.value} has confidence: "
f"{merchant_name.confidence}"
)
transaction_date = receipt.fields.get("TransactionDate")
if transaction_date:
print(
f"Transaction Date: {transaction_date.value} has confidence: "
f"{transaction_date.confidence}"
)
if receipt.fields.get("Items"):
print("Receipt items:")
for idx, item in enumerate(receipt.fields.get("Items").value):
print(f"...Item #{idx + 1}")
item_description = item.value.get("Description")
if item_description:
print(
f"......Item Description: {item_description.value} has confidence: "
f"{item_description.confidence}"
)
item_quantity = item.value.get("Quantity")
if item_quantity:
print(
f"......Item Quantity: {item_quantity.value} has confidence: "
f"{item_quantity.confidence}"
)
item_price = item.value.get("Price")
if item_price:
print(
f"......Individual Item Price: {item_price.value} has confidence: "
f"{item_price.confidence}"
)
item_total_price = item.value.get("TotalPrice")
if item_total_price:
print(
f"......Total Item Price: {item_total_price.value} has confidence: "
f"{item_total_price.confidence}"
)
subtotal = receipt.fields.get("Subtotal")
if subtotal:
print(f"Subtotal: {subtotal.value} has confidence: {subtotal.confidence}")
tax = receipt.fields.get("TotalTax")
if tax:
print(f"Total tax: {tax.value} has confidence: {tax.confidence}")
tip = receipt.fields.get("Tip")
if tip:
print(f"Tip: {tip.value} has confidence: {tip.confidence}")
total = receipt.fields.get("Total")
if total:
print(f"Total: {total.value} has confidence: {total.confidence}")
print("--------------------------------------")
您不仅限于收据!还有几个预构建模型可供选择,每个模型都有自己的支持字段集。请参阅其他支持预构建模型此处。
构建自定义模型
在自己的文档类型上构建自定义模型。该模型可以用于分析其训练过的文档类型的值。提供存储训练文档的 Azure 存储Blob 容器中的容器 SAS URL。
有关设置容器和所需文件结构的更多详细信息,请参阅服务文档。
from azure.ai.formrecognizer import (
DocumentModelAdministrationClient,
ModelBuildMode,
)
from azure.core.credentials import AzureKeyCredential
endpoint = os.environ["AZURE_FORM_RECOGNIZER_ENDPOINT"]
key = os.environ["AZURE_FORM_RECOGNIZER_KEY"]
container_sas_url = os.environ["CONTAINER_SAS_URL"]
document_model_admin_client = DocumentModelAdministrationClient(
endpoint, AzureKeyCredential(key)
)
poller = document_model_admin_client.begin_build_document_model(
ModelBuildMode.TEMPLATE,
blob_container_url=container_sas_url,
description="my model description",
)
model = poller.result()
print(f"Model ID: {model.model_id}")
print(f"Description: {model.description}")
print(f"Model created on: {model.created_on}")
print(f"Model expires on: {model.expires_on}")
print("Doc types the model can recognize:")
for name, doc_type in model.doc_types.items():
print(
f"Doc Type: '{name}' built with '{doc_type.build_mode}' mode which has the following fields:"
)
for field_name, field in doc_type.field_schema.items():
print(
f"Field: '{field_name}' has type '{field['type']}' and confidence score "
f"{doc_type.field_confidence[field_name]}"
)
使用自定义模型分析文档
分析文档字段、表格、选择标记等。这些模型是用您自己的数据进行训练的,因此它们针对您的文档进行了定制。为了获得最佳结果,您应仅分析与构建自定义模型相同的文档类型的文档。
from azure.core.credentials import AzureKeyCredential
from azure.ai.formrecognizer import DocumentAnalysisClient
endpoint = os.environ["AZURE_FORM_RECOGNIZER_ENDPOINT"]
key = os.environ["AZURE_FORM_RECOGNIZER_KEY"]
model_id = os.getenv("CUSTOM_BUILT_MODEL_ID", custom_model_id)
document_analysis_client = DocumentAnalysisClient(
endpoint=endpoint, credential=AzureKeyCredential(key)
)
# Make sure your document's type is included in the list of document types the custom model can analyze
with open(path_to_sample_documents, "rb") as f:
poller = document_analysis_client.begin_analyze_document(
model_id=model_id, document=f
)
result = poller.result()
for idx, document in enumerate(result.documents):
print(f"--------Analyzing document #{idx + 1}--------")
print(f"Document has type {document.doc_type}")
print(f"Document has document type confidence {document.confidence}")
print(f"Document was analyzed with model with ID {result.model_id}")
for name, field in document.fields.items():
field_value = field.value if field.value else field.content
print(
f"......found field of type '{field.value_type}' with value '{field_value}' and with confidence {field.confidence}"
)
# iterate over tables, lines, and selection marks on each page
for page in result.pages:
print(f"\nLines found on page {page.page_number}")
for line in page.lines:
print(f"...Line '{line.content}'")
for word in page.words:
print(f"...Word '{word.content}' has a confidence of {word.confidence}")
if page.selection_marks:
print(f"\nSelection marks found on page {page.page_number}")
for selection_mark in page.selection_marks:
print(
f"...Selection mark is '{selection_mark.state}' and has a confidence of {selection_mark.confidence}"
)
for i, table in enumerate(result.tables):
print(f"\nTable {i + 1} can be found on page:")
for region in table.bounding_regions:
print(f"...{region.page_number}")
for cell in table.cells:
print(
f"...Cell[{cell.row_index}][{cell.column_index}] has text '{cell.content}'"
)
print("-----------------------------------")
或者,也可以使用文档URL来通过begin_analyze_document_from_url方法分析文档。
document_url = "<url_of_the_document>"
poller = document_analysis_client.begin_analyze_document_from_url(model_id=model_id, document_url=document_url)
result = poller.result()
管理您的模型
管理您账户中附加的自定义模型。
from azure.ai.formrecognizer import DocumentModelAdministrationClient
from azure.core.credentials import AzureKeyCredential
from azure.core.exceptions import ResourceNotFoundError
endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/"
credential = AzureKeyCredential("<api_key>")
document_model_admin_client = DocumentModelAdministrationClient(endpoint, credential)
account_details = document_model_admin_client.get_resource_details()
print("Our account has {} custom models, and we can have at most {} custom models".format(
account_details.custom_document_models.count, account_details.custom_document_models.limit
))
# Here we get a paged list of all of our models
models = document_model_admin_client.list_document_models()
print("We have models with the following ids: {}".format(
", ".join([m.model_id for m in models])
))
# Replace with the custom model ID from the "Build a model" sample
model_id = "<model_id from the Build a Model sample>"
custom_model = document_model_admin_client.get_document_model(model_id=model_id)
print("Model ID: {}".format(custom_model.model_id))
print("Description: {}".format(custom_model.description))
print("Model created on: {}\n".format(custom_model.created_on))
# Finally, we will delete this model by ID
document_model_admin_client.delete_document_model(model_id=custom_model.model_id)
try:
document_model_admin_client.get_document_model(model_id=custom_model.model_id)
except ResourceNotFoundError:
print("Successfully deleted model with id {}".format(custom_model.model_id))
附加功能
文档智能支持更高级的分析功能。这些可选功能可以根据文档提取场景启用或禁用。
以下附加功能自2023-07-31(GA)及以后版本可用
请注意,某些附加功能将产生额外费用。请参阅定价:https://azure.microsoft.com/pricing/details/ai-document-intelligence/。
故障排除
常规
表单识别器客户端库将引发定义在Azure Core中的异常。文档智能服务引发的错误代码和消息可以在服务文档中找到。
日志记录
此库使用标准的logging库进行日志记录。
在INFO级别记录HTTP会话的基本信息(URL、标题等)。
可以通过在客户端或每个操作中启用logging_enable关键字参数来启用详细的DEBUG级别日志记录,包括请求/响应体和未脱敏的标题。
有关示例的完整SDK日志记录文档,请参阅此处。
可选配置
可以在客户端和每个操作级别传递可选关键字参数。azure-core的参考文档描述了重试、日志记录、传输协议等可用的配置。
下一步
更多示例代码
请参阅示例README,其中包含几个代码片段,展示了在Form Recognizer Python API中使用的常见模式。
其他文档
有关Azure AI文档智能的更详细文档,请参阅docs.microsoft.com上的文档智能文档。
贡献
此项目欢迎贡献和建议。大多数贡献都需要您同意贡献者许可协议(CLA),声明您有权并且实际上确实授予我们使用您的贡献的权利。有关详细信息,请访问cla.microsoft.com。
当您提交拉取请求时,CLA-bot将自动确定您是否需要提供CLA,并相应地装饰PR(例如,标签、注释)。只需遵循机器人提供的说明即可。您只需在整个使用我们的CLA的存储库中这样做一次。
此项目采用了Microsoft开源行为准则。有关更多信息,请参阅行为准则FAQ或联系opencode@microsoft.com,如有任何其他问题或评论。
发布历史
3.3.3 (2024-04-09)
其他更改
- 添加了对Python 3.12的支持。
- Python 3.7不再受支持。请使用Python版本3.8或更高版本。
- 将默认轮询间隔从5秒更改为1秒。
3.3.2 (2023-11-07)
已修复的bug
- 修复了返回公式对象的错误数据类型。
3.3.1 (2023-10-10)
添加的功能
- 在客户端的每个客户端中公开了
send_request()方法,以使用客户端现有的管道发送自定义请求。(#32151)
3.3.0 (2023-08-08)
此客户端库的此版本默认为服务API版本2023-07-31。
重大更改
注意:以下更改仅相对于以前的beta版本是破坏性的。它们不是相对于以前稳定版本的破坏性更改。
- 从现在起,此库将默认使用服务API版本
2023-07-31。 - 从
begin_analyze_document()和begin_analyze_document_from_url()中移除了query_fields关键字参数。 - 从
DocumentPage中移除了kind属性。 - 从
DocumentPage中移除了images属性。 - 移除了
DocumentImage模型。 - 从
DocumentPage中移除了annotations属性。 - 移除了
DocumentAnnotation模型。 - 从
DocumentKeyValuePair中移除了common_name属性。 - 修改了
AnalysisFeature枚举成员名称和值。支持的枚举成员有:OCR_HIGH_RESOLUTION、LANGUAGES、BARCODES、FORMULAS、KEY_VALUE_PAIRS、STYLE_FONT。 - 将
ResourceDetails模型中的custom_neural_document_model_builds属性重命名为neural_document_model_quota。 - 将
AzureBlobSource模型重命名为BlobSource。 - 将
AzureBlobFileListSource模型重命名为BlobFileListSource。 - 将
ResourceDetails中的neural_document_model_quota标记为可选。
其他更改
- 在
DocumentWord、DocumentSelectionMark、DocumentLine上的polygon属性进行了类型修正。 - 在
DocumentPage上的words、lines和selection_marks属性进行了类型修正。 - 将样本目录重命名为
v3.2_and_later/以支持 3.2 及更高版本。
3.3.0b1 (2023-04-13)
此版本客户端库默认使用服务 API 版本 2023-02-28-preview。
添加的功能
- 在
begin_analyze_document()和begin_analyze_document_from_url()上添加了features关键字参数。 - 在
begin_analyze_document()和begin_analyze_document_from_url()上添加了query_fields关键字参数。 - 添加了
AnalysisFeature枚举,以支持可选的文档分析功能。 - 在
begin_build_document_model()上添加了file_list关键字参数。 - 在
DocumentStyle类上添加了以下可选属性:similar_font_family、font_style、font_weight、color、background_color。 - 在
DocumentModelAdministrationClient上添加了对自定义文档分类的支持:begin_build_document_classifier、list_document_classifiers、get_document_classifier和delete_document_classifier。 - 在
DocumentAnalysisClient上添加了对文档分类的支持:begin_classify_document和begin_classify_document_from_url。 - 添加了
ClassifierDocumentTypeDetails以与begin_build_document_classifier()一起使用。 - 在
ResourceDetails上添加了模型QuotaDetails和属性custom_neural_document_model_builds。 - 在
OperationSummary和OperationDetails上添加了类型documentClassifierBuild。 - 在
DocumentModelDetails和DocumentModelSummary上添加了属性expires_on。 - 在
DocumentParagraph上添加了类型formulaBlock。 - 在
DocumentKeyValuePair上添加了属性common_name。 - 在
CurrencyValue上添加了属性code。 - 在
AddressValue上添加了属性unit、city_district、state_district、suburb、house和level。 - 在
DocumentField上添加了 "boolean"value_type和boolvalue。 - 在
DocumentPage上添加了属性annotations、images、formulas和barcodes。 - 添加了模型
DocumentAnnotation、DocumentImage、DocumentFormula和DocumentBarcode。
3.2.1 (2023-03-07)
已修复的bug
- 在异步
FormRecognizerClient上的begin_recognize_invoices()中对invoice参数进行了类型修正。 - 修复了在
DocumentField上调用to_dict()时,地址和货币字段未返回value的问题。 - 在
RecognizedForm上的form_type_confidence属性进行了类型修正。 - 在
FormLine上的appearance属性进行了类型修正。
其他更改
- 改进了静态类型。
3.2.0 (2022-09-08)
添加的功能
- 支持文档分析和模型构建的内容类型
image/heif。 - 在
ResourceDetails上添加了custom_document_models属性。 - 添加了新的
CustomDocumentModelsDetails模型以表示给定表单识别资源中自定义文档模型的详细信息。
重大更改
- 从此版本开始,此库将默认使用服务 API 版本
2022-08-31。 - 从
DocumentPage中移除了kind属性。 - 将
begin_build_model()重命名为begin_build_document_model()在DocumentModelAdministrationClient上。 - 将
begin_compose_model()重命名为begin_compose_document_model()在DocumentModelAdministrationClient上。 - 将
begin_copy_model_to()重命名为begin_copy_document_model_to()在DocumentModelAdministrationClient上。 - 将
list_models()重命名为list_document_models()在DocumentModelAdministrationClient上。 - 将
get_model()重命名为get_document_model()在DocumentModelAdministrationClient上。 - 将
delete_model()重命名为delete_document_model()在DocumentModelAdministrationClient上。 - 从
ResourceDetails中移除了document_model_count和document_model_limit属性。 - 将
DocumentModelOperationDetails重命名为OperationDetails。 - 将
DocumentModelOperationSummary重命名为OperationSummary。 - 移除了
DocumentContentElement。 - 从
DocumentSelectionMark中移除了kind和content属性。 - 从
DocumentWord中移除了kind。
已修复的bug
- 将
DocumentParagraph添加到__all__。
3.2.0b6 (2022-08-09)
添加的功能
- 添加了类型为
dict[str, str]的TargetAuthorization。
重大更改
- 在
begin_build_model()中将source参数重命名为blob_container_url并使其成为必选的只关键字参数。 - 更改了
begin_build_model()中的参数顺序。首先期望的参数是build_mode,然后是blob_container_url。 - 将
DocumentModelAdministrationClient上的begin_create_composed_model()重命名为begin_compose_model()。 - 将
DocumentModelAdministrationClient上的get_account_info()重命名为get_resource_details()。 - 将
DocumentBuildMode重命名为ModelBuildMode。 - 将
AccountInfo模型重命名为ResourceDetails。 - 将
DocTypeInfo模型重命名为DocumentTypeDetails。 - 将
DocumentModelInfo模型重命名为DocumentModelSummary。 - 将
DocumentModel重命名为DocumentModelDetails。 - 将
ModelOperation重命名为DocumentModelOperationDetails。 - 将
ModelOperationInfo重命名为DocumentModelOperationSummary。 - 在
begin_analyze_document()和begin_analyze_document_from_url()中将model参数重命名为model_id。 - 从
DocumentAnalysisClient上的begin_analyze_document()和begin_analyze_document_from_url()以及从DocumentModelAdministrationClient上的begin_build_model()、begin_compose_model()和begin_copy_model_to()中移除了continuation_token关键字。 - 将
get_copy_authorization()的返回类型从dict[str, str]更改为TargetAuthorization。 - 在
begin_copy_to()中将期望的target参数从dict[str, str]更改为TargetAuthorization。 - 长时间运行的操作元数据现在可以通过返回的
DocumentModelAdministrationLROPoller和AsyncDocumentModelAdministrationLROPoller实例上的details属性访问。
其他更改
- 此版本不再支持 Python 3.6。请使用 Python 3.7 或更高版本。
3.2.0b5 (2022-06-07)
添加的功能
- 在
AnalyzeResult上添加了paragraphs属性。 - 添加了新的
DocumentParagraph模型来表示文档段落。 - 添加了新的
AddressValue模型来表示文档中找到的地址字段。 - 在
DocumentPage上添加了kind属性。
重大更改
- 在
BoundingRegion、DocumentContentElement、DocumentLine、DocumentSelectionMark和DocumentWord上将bounding_box重命名为polygon。 - 在
DocumentLanguage上将language_code重命名为locale。 - 之前可能返回字符串的地址相关字段的一些模型现在可能返回
AddressValue。提示:使用DocumentModelAdministrationClient上的get_model()来查看更新的预构建模型模式。 - 从
AnalyzeResult中移除了entities属性。 - 移除了
DocumentEntity模型。
3.2.0b4 (2022-04-05)
重大更改
- 将
begin_copy_model()重命名为begin_copy_model_to()。 - 在
begin_create_composed_model()中,将必选参数model_ids重命名为component_model_ids。 - 将
AccountInfo上的model_count和model_limit重命名为document_model_count和document_model_limit。
已修复的bug
- 在
DocumentField上固定了to_dict()和from_dict()方法,以支持将列表、字典和 CurrenyValue 字段类型转换为和从字典。
其他更改
- 将
sample_copy_model.py和sample_copy_model_async.py在3.2-beta样例文件夹下重命名为sample_copy_model_to.py和sample_copy_model_to_async.py。更新了样例以使用重命名的复制模型方法。
3.2.0b3 (2022-02-10)
添加的功能
- 添加了新的
CurrencyValue模型,用于表示文档中找到的金额和货币符号值。 - 添加了
DocumentBuildMode枚举,具有template和neural等值。这些枚举值可以用于begin_build_model()中的build_mode参数。 - 在
ModelOperation、ModelOperationInfo、DocumentModel和DocumentModelInfo上添加了api_version和tags属性。 - 在
DocTypeInfo上添加了build_mode属性。 - 在
begin_build_model()、begin_create_composed_model()和get_copy_authorization()上添加了tags关键字参数。 - 在
AnalyzeResult上添加了languages属性。 - 添加了包含文档中检测到的语言信息的模型
DocumentLanguage。 - 在
v3.2-beta样例目录下添加了sample_analyze_read.py和sample_analyze_read_async.py。这些样例使用服务添加的新prebuilt-read模型。 - 在
v3.2-beta样例目录下添加了sample_analyze_tax_us_w2.py和sample_analyze_tax_us_w2_async.py。这些样例使用服务添加的新prebuilt-tax.us.w2模型。
重大更改
- 将
begin_build_model()的新必需参数build_mode添加。 - 一些之前返回浮点数作为与货币相关的字段值的模型现在可能返回一个
CurrencyValue。提示:使用DocumentModelAdministrationClient上的get_model()来查看更新的预构建模型模式。
已修复的bug
- 当不与模型操作信息一起返回时,将
percent_completed属性默认为 0。
其他更改
- 本版本不再支持 Python 2.7。请使用 Python 3.6 或更高版本。
- 将
azure-core的最小依赖版本从1.13.0提高到1.20.1。 - 更新了调用
begin_build_model()的样例,以发送build_mode参数。
3.2.0b2 (2021-11-09)
添加的功能
- 在
DocumentLine上添加了get_words()。 - 在
/samples/v3.2-beta下添加了演示如何使用DocumentLine上的get_words()的样例:sample_get_words_on_document_line.py和sample_get_words_on_document_line_async.py。
重大更改
- 将
DocumentElement重命名为DocumentContentElement。
3.2.0b1 (2021-10-07)
此版本的 SDK 默认为最新支持的 API 版本,目前为 2021-09-30-preview。
注意:从 2021-09-30-preview 版本开始,引入了一套新的客户端来利用表单识别器服务的最新功能。请参阅迁移指南,以获取如何从客户端库版本 3.1.X 或更低版本更新应用程序代码到最新版本的详细说明。有关库的更多信息,请参阅README。
添加的功能
- 添加了新的
DocumentAnalysisClient,具有begin_analyze_document和begin_analyze_document_from_url方法。使用这些方法与最新的表单识别器 API 版本一起分析文档,使用预构建和自定义模型。 - 添加了新的模型,可用于新的
DocumentAnalysisClient:AnalyzeResult、AnalyzedDocument、BoundingRegion、DocumentElement、DocumentEntity、DocumentField、DocumentKeyValuePair、DocumentKeyValueElement、DocumentLine、DocumentPage、DocumentSelectionMark、DocumentSpan、DocumentStyle、DocumentTable、DocumentTableCell、DocumentWord。 - 添加了新的
DocumentModelAdministrationClient,具有方法:begin_build_model、begin_create_composed_model、begin_copy_model、get_copy_authorization、get_model、delete_model、list_models、get_operation、list_operations、get_account_info、get_document_analysis_client。 - 添加了新的模型以与新的
DocumentModelAdministrationClient一起使用:DocumentModel、DocumentModelInfo、DocTypeInfo、ModelOperation、ModelOperationInfo、AccountInfo、DocumentAnalysisError、DocumentAnalysisInnerError。 - 在
/samples/v3.2-beta下添加了使用DocumentAnalysisClient和DocumentModelAdministrationClient的示例。 - 添加了
DocumentAnalysisApiVersion以与DocumentAnalysisClient和DocumentModelAdministrationClient一起使用。
其他更改
- 本版本不再支持 Python 3.5。
3.1.2 (2021-08-10)
已修复的bug
- 当
F0级别表单识别资源的调用配额量超过时,将立即抛出HttpResponseError。
其他更改
- 将
azure-core的最小依赖版本从1.8.2提升至1.13.0。
3.1.1 (2021-06-08)
错误修复
- 处理没有检测到子行项目字段的发票。
3.1.0 (2021-05-26)
此版本的 SDK 默认使用最新支持的 API 版本,当前为 v2.1。
注意:此版本将是最后一个官方支持 Python 3.5 的版本,未来版本将需要 Python 2.7 或 Python 3.6+。
重大更改
begin_recognize_id_documents已重命名为begin_recognize_identity_documents。begin_recognize_id_documents_from_url已重命名为begin_recognize_identity_documents_from_url。- 模型
TextAppearance现在包括style_name和style_confidence属性,这些属性曾是TextStyle对象的一部分。 - 已删除模型
TextStyle。 - 从
FieldValueType枚举中删除了字段值类型 "gender" 和 "country"。 - 向
FieldValueType枚举中添加了字段值类型 "countryRegion"。 - 将身份证明文件的字段名称从 "Country" 重命名为 "CountryRegion"。
新功能
- 向所有模型添加了
to_dict和from_dict方法。
3.1.0b4 (2021-04-06)
新功能
- 向 SDK 中引入了新方法
begin_recognize_id_documents和begin_recognize_id_documents_from_url。使用这些方法从身份证明文件中识别数据。 - 在
FieldValueType枚举中描述了新的字段值类型 "gender" 和 "country"。 - 自定义表单和训练方法现在支持内容类型
image/bmp。 - 为名片、收据、自定义表单和发票添加了关键字参数
pages,以指定要处理的文档的页面。 - 向
begin_recognize_content和begin_recognize_content_from_url添加了关键字参数reading_order。
依赖项更新
- 将
msrest要求从0.6.12提升至0.6.21。
3.1.0b3 (2021-02-09)
重大更改
Appearance已重命名为TextAppearance。Style已重命名为TextStyle。- 不再公开客户端属性
api_version。通过将关键字参数api_version传递给客户端来选择 API 版本。
依赖项更新
- 将
six要求从1.6提升至1.11.0。
3.1.0b2 (2021-01-12)
错误修复
- 软件包需要 azure-core 版本 1.8.2 或更高版本。
3.1.0b1 (2020-11-23)
此版本的 SDK 默认使用最新支持的 API 版本,当前为 v2.1-preview。
新功能
- 向 SDK 中引入了新方法
begin_recognize_business_cards和begin_recognize_business_cards_from_url。使用这些方法从名片中识别数据。 - 向 SDK 中引入了新方法
begin_recognize_invoices和begin_recognize_invoices_from_url。使用这些方法从发票中识别数据。 - 识别收据的方法现在可以接受关键字参数
locale,以可选地指示收据的区域设置,从而提高结果。 - 通过调用方法
begin_create_composed_model(),现在可以从FormTrainingClient创建组合模型。 - 添加了对带有选择标记(如复选框和单选按钮)的自定义表单的训练和识别的支持。此功能仅适用于带有标签训练的模型。
- 向
FormPage添加了属性selection_marks,其中包含FormSelectionMark列表。 - 当传递
include_field_elements=True时,FieldData和FormTableCell上的field_elements属性也会填充页面上的任何选择标记 - 将属性
model_name和properties添加到类型CustomFormModel和CustomFormModelInfo - 将关键字参数
model_name添加到begin_training()和begin_create_composed_model() - 添加了模型类型
CustomFormModelProperties,其中包含模型是否为组合模型等信息 - 将属性
model_id添加到CustomFormSubmodel和TrainingDocumentInfo - 将属性
model_id和form_type_confidence添加到RecognizedForm - 向
FormLine添加了appearance属性,以指示提取文本的样式,例如“手写”或“其他” - 将关键字参数
pages添加到begin_recognize_content和begin_recognize_content_from_url,以指定要分析的页面编号 - 向
FormTable添加了属性bounding_box - 内容类型
image/bmp现在由内容识别和预构建模型支持 - 将关键字参数
language添加到begin_recognize_content和begin_recognize_content_from_url,以指定处理文档的语言
依赖项更新
- 该包现在需要azure-common版本1.1
3.0.0 (2020-08-20)
azure-ai-formrecognizer客户端库的第一个稳定版本。
新功能
- 可以通过客户端级别的关键字参数
api_version来指定要使用的服务API版本。目前仅支持v2.0。有关支持的API版本,请参阅枚举FormRecognizerApiVersion。 FormWord和FormLine现在有属性kind,它指定了元素的类型,例如“单词”或“行”
3.0.0b1 (2020-08-11)
该包的版本现在针对服务的v2.0 API。
重大更改
- 客户端库版本提升到
3.0.0b1 - 枚举
FormContentType、LengthUnit、TrainingStatus和CustomFormModelStatus的值现在为大写 TrainingDocumentInfo上的document_name已重命名为namebegin_training方法上的关键字参数include_sub_folders已重命名为include_subfolders
新功能
FormField现在有属性value_type,它包含字段值的语义数据类型。有关value_type的选项,请参阅枚举FieldValueType
修复和改进
- 修复了一个错误,在该错误中,如果在轮询操作失败时返回
HttpResponseError,则不会返回错误代码和消息 FormField属性value_data现在在它的FieldData没有返回值时设置为None。在此之前,value_data在上述情况下返回一个所有属性都设置为None的FieldData
1.0.0b4 (2020-07-07)
重大更改
- 已删除
RecognizedReceipts类。 begin_recognize_receipts和begin_recognize_receipts_from_url现在返回RecognizedFormCustomFormModel和CustomFormModelInfo上的requested_on已重命名为training_started_on,completed_on已重命名为training_completed_onFieldText已重命名为FieldDataFormContent已重命名为FormElementbegin_recognize_receipts、begin_recognize_receipts_from_url、begin_recognize_custom_forms和begin_recognize_custom_forms_from_url上的参数include_text_content已重命名为include_field_elementsFieldData和FormTableCell上的text_content已重命名为field_elements
修复和改进
- 修复了一个错误,其中
text_angle返回了指定的区间(-180, 180]之外的值
1.0.0b3 (2020-06-10)
重大更改
- 所有异步长时间运行操作方法现在从
azure-core返回一个AsyncLROPoller实例 - 所有异步长时间运行操作方法现在都使用
begin_前缀重命名,以指示返回一个AsyncLROPollertrain_model已重命名为begin_trainingrecognize_receipts已重命名为begin_recognize_receiptsrecognize_receipts_from_url已重命名为begin_recognize_receipts_from_urlrecognize_content已重命名为begin_recognize_contentrecognize_content_from_url已重命名为begin_recognize_content_from_urlrecognize_custom_forms已重命名为begin_recognize_custom_formsrecognize_custom_forms_from_url已重命名为begin_recognize_custom_forms_from_url
- 同步方法
begin_train_model已重命名为begin_training begin_training的training_files参数已重命名为training_files_urlbegin_training的use_labels参数已重命名为use_training_labelslist_model_infos方法已重命名为list_custom_models- 从
FormRecognizerClient中移除了get_form_training_client - 向
FormTrainingClient中添加了get_form_recognizer_client - 如果从
begin_training方法返回的模型状态为"invalid",则会引发HttpResponseError PageRange已重命名为FormPageRangeFormPageRange上的first_page和last_page分别重命名为first_page_number和last_page_numberFormField没有页面编号use_training_labels现在是begin_trainingAPI 中的必需位置参数FormRecognizerClient方法上的stream和url参数已分别重命名为form和form_url- 对于
begin_recognize_receipt方法,参数已重命名为receipt和receipt_url - 在
CustomFormModel和CustomFormModelInfo模型中,created_on和last_modified已重命名为requested_on和completed_on CustomFormModel的models属性已重命名为submodelsCustomFormSubModel已重命名为CustomFormSubmodelbegin_recognize_receiptsAPI 现在返回一个RecognizedReceipt列表,而不是USReceipt- 已移除
USReceipt。有关如何处理begin_recognize_receipts的返回值,请参阅 samples 目录 中的识别收据示例。 - 已移除
USReceiptItem。有关如何访问收据上的各个项,请参阅 samples 目录 中的识别收据示例。 - 已移除
USReceiptType和RecognizedReceipt中的receipt_type属性。有关详细信息,请参阅 samples 目录 中的识别收据示例。
新功能
- 支持将自定义模型从一个表单识别资源复制到另一个资源
- 现在支持使用
azure-identity凭据进行身份验证- 有关更多信息,请参阅 Azure Identity 文档
- 已向
FormTable添加page_number属性 - 所有长运行操作方法现在都接受关键字参数
continuation_token以从保存的状态重新启动轮询器
依赖项更新
- 已采用 azure-core 版本 1.6.0 或更高版本
1.0.0b2 (2020-05-06)
修复和改进
- 修复了将
confidence==0.0错误地设置为1.0的错误 - 已向所有模型添加
__repr__
1.0.0b1 (2020-04-23)
版本 (1.0.0b1) 是我们为 Azure 表单识别器创建用户友好且符合 Pythonic 客户端库努力的第一个预览版。此库替代了以下位置找到的包:https://pypi.ac.cn/project/azure-cognitiveservices-formrecognizer/
有关此信息和 Azure SDK 库的其他预览版本的信息,请访问 https://azure.github.io/azure-sdk/releases/latest/python.html。
重大变更:新的 API 设计
- 新的命名空间/包名
- 表单识别客户端库的命名空间/包名已从
azure.cognitiveservices.formrecognizer更改为azure.ai.formrecognizer
- 表单识别客户端库的命名空间/包名已从
- 两种客户端设计
- FormRecognizerClient 用于分析自定义表单、收据和表单内容/布局的字段/值
- FormTrainingClient 用于训练自定义模型(带/不带标签),并管理账户中的自定义模型
- 根据输入类型的不同分析方法:文件流或 URL。
- URL 输入应使用后缀为
from_url的方法 - 流方法将自动检测输入文件的 content-type
- URL 输入应使用后缀为
- 在
azure.ai.formrecognizer.aio命名空间下添加了异步 API - 支持使用来自
azure.core.credentials的AzureKeyCredential("<api_key>")进行 API 密钥认证 - 基于 azure-core 库的新底层 REST 管道实现
- 现在可以通过关键字参数在客户端级别和每个操作级别进行客户端和管道配置。请参阅 README 以获取可选配置参数的链接
- 新的错误层次结构
- 所有服务错误现在都将使用基类:
azure.core.exceptions.HttpResponseError
- 所有服务错误现在都将使用基类:
项目详情
下载文件
下载您平台的文件。如果您不确定选择哪个,请了解有关 安装包 的更多信息。
源分发
构建分发
azure-ai-formrecognizer-3.3.3.tar.gz 的哈希值
| 算法 | 哈希摘要 | |
|---|---|---|
| SHA256 | 9fc09788bbb65866630fa870cca1933bfd7298b8055236530bcc0e40d81fcccf |
|
| MD5 | 16687d91d4f368d7a18d2fa17c750f2d |
|
| BLAKE2b-256 | 1c03ab76ece556f13e84481d74d79dc74ad8f8e84bd030468f01ae81adebfb52 |
哈希值 for azure_ai_formrecognizer-3.3.3-py3-none-any.whl
| 算法 | 哈希摘要 | |
|---|---|---|
| SHA256 | 81fc1abda8bd898426ee3bbc1b9c6bd164514201ce282129a31d4664f9d1f3bc |
|
| MD5 | c7a6a192e8b5956306d61688bafb14e4 |
|
| BLAKE2b-256 | 6ec088b760e94bb330a1b31af204378563524c72d48f1c62c338fe1d18fdc894 |