跳转到主要内容

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中得到支持。有关迁移详情,请参阅此文档

入门

先决条件

安装包

使用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_IDAZURE_TENANT_IDAZURE_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_documentbegin_analyze_document_from_url API提供分析输入文档的操作,使用预构建和自定义模型。使用model_id参数选择分析模型的类型。有关支持的完整模型列表,请参阅此处。《DocumentAnalysisClient》还通过begin_classify_documentbegin_classify_document_from_url API提供对文档进行分类的操作。自定义分类模型可以分类输入文件中的每一页以识别文档,也可以识别输入文件中的多个文档或单个文档的多个实例。

提供了示例代码片段来展示如何使用DocumentAnalysisClient此处。有关分析文档的更多信息,包括支持的特性、区域和文档类型,请参阅服务文档

文档模型管理客户端

DocumentModelAdministrationClient 提供以下操作:

  • 通过标记您的自定义文档来构建用于分析您指定的特定字段的自定义模型。返回一个 DocumentModelDetails 对象,指示模型可以分析哪些文档类型,以及每个字段的估计置信度。有关更详细的解释,请参阅服务文档
  • 从现有模型集合中创建一个组合模型。
  • 管理您账户中创建的模型。
  • 列出操作或获取在过去24小时内创建的特定模型操作。
  • 将自定义模型从一个表单识别资源复制到另一个。
  • 构建并管理自定义分类模型,以对您应用程序中处理的文档进行分类。

请注意,您还可以使用如图形用户界面(例如文档智能工作室)之类的工具来构建模型。

以下提供了示例代码片段,以说明如何使用 此处 的 DocumentModelAdministrationClient。

长时间运行的操作

长时间运行的操作是指由向服务发送初始请求以启动操作组成,然后以一定时间间隔轮询服务以确定操作是否完成或失败,如果成功,则获取结果的操作。

分析文档、构建模型或复制/组合模型的操作被建模为长时间运行的操作。客户端公开了一个返回 LROPollerAsyncLROPollerbegin_<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_RESOLUTIONLANGUAGESBARCODESFORMULASKEY_VALUE_PAIRSSTYLE_FONT
  • ResourceDetails 模型中的 custom_neural_document_model_builds 属性重命名为 neural_document_model_quota
  • AzureBlobSource 模型重命名为 BlobSource
  • AzureBlobFileListSource 模型重命名为 BlobFileListSource
  • ResourceDetails 中的 neural_document_model_quota 标记为可选。

其他更改

  • DocumentWordDocumentSelectionMarkDocumentLine 上的 polygon 属性进行了类型修正。
  • DocumentPage 上的 wordslinesselection_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_familyfont_stylefont_weightcolorbackground_color
  • DocumentModelAdministrationClient 上添加了对自定义文档分类的支持:begin_build_document_classifierlist_document_classifiersget_document_classifierdelete_document_classifier
  • DocumentAnalysisClient 上添加了对文档分类的支持:begin_classify_documentbegin_classify_document_from_url
  • 添加了 ClassifierDocumentTypeDetails 以与 begin_build_document_classifier() 一起使用。
  • ResourceDetails 上添加了模型 QuotaDetails 和属性 custom_neural_document_model_builds
  • OperationSummaryOperationDetails 上添加了类型 documentClassifierBuild
  • DocumentModelDetailsDocumentModelSummary 上添加了属性 expires_on
  • DocumentParagraph 上添加了类型 formulaBlock
  • DocumentKeyValuePair 上添加了属性 common_name
  • CurrencyValue 上添加了属性 code
  • AddressValue 上添加了属性 unitcity_districtstate_districtsuburbhouselevel
  • DocumentField 上添加了 "boolean" value_typebool value
  • DocumentPage 上添加了属性 annotationsimagesformulasbarcodes
  • 添加了模型 DocumentAnnotationDocumentImageDocumentFormulaDocumentBarcode

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_countdocument_model_limit 属性。
  • DocumentModelOperationDetails 重命名为 OperationDetails
  • DocumentModelOperationSummary 重命名为 OperationSummary
  • 移除了 DocumentContentElement
  • DocumentSelectionMark 中移除了 kindcontent 属性。
  • 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
  • 长时间运行的操作元数据现在可以通过返回的 DocumentModelAdministrationLROPollerAsyncDocumentModelAdministrationLROPoller 实例上的 details 属性访问。

其他更改

  • 此版本不再支持 Python 3.6。请使用 Python 3.7 或更高版本。

3.2.0b5 (2022-06-07)

添加的功能

  • AnalyzeResult 上添加了 paragraphs 属性。
  • 添加了新的 DocumentParagraph 模型来表示文档段落。
  • 添加了新的 AddressValue 模型来表示文档中找到的地址字段。
  • DocumentPage 上添加了 kind 属性。

重大更改

  • BoundingRegionDocumentContentElementDocumentLineDocumentSelectionMarkDocumentWord 上将 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_countmodel_limit 重命名为 document_model_countdocument_model_limit

已修复的bug

  • DocumentField 上固定了 to_dict()from_dict() 方法,以支持将列表、字典和 CurrenyValue 字段类型转换为和从字典。

其他更改

  • sample_copy_model.pysample_copy_model_async.py3.2-beta 样例文件夹下重命名为 sample_copy_model_to.pysample_copy_model_to_async.py。更新了样例以使用重命名的复制模型方法。

3.2.0b3 (2022-02-10)

添加的功能

  • 添加了新的 CurrencyValue 模型,用于表示文档中找到的金额和货币符号值。
  • 添加了 DocumentBuildMode 枚举,具有 templateneural 等值。这些枚举值可以用于 begin_build_model() 中的 build_mode 参数。
  • ModelOperationModelOperationInfoDocumentModelDocumentModelInfo 上添加了 api_versiontags 属性。
  • DocTypeInfo 上添加了 build_mode 属性。
  • begin_build_model()begin_create_composed_model()get_copy_authorization() 上添加了 tags 关键字参数。
  • AnalyzeResult 上添加了 languages 属性。
  • 添加了包含文档中检测到的语言信息的模型 DocumentLanguage
  • v3.2-beta 样例目录下添加了 sample_analyze_read.pysample_analyze_read_async.py。这些样例使用服务添加的新 prebuilt-read 模型。
  • v3.2-beta 样例目录下添加了 sample_analyze_tax_us_w2.pysample_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.pysample_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_documentbegin_analyze_document_from_url 方法。使用这些方法与最新的表单识别器 API 版本一起分析文档,使用预构建和自定义模型。
  • 添加了新的模型,可用于新的 DocumentAnalysisClientAnalyzeResultAnalyzedDocumentBoundingRegionDocumentElementDocumentEntityDocumentFieldDocumentKeyValuePairDocumentKeyValueElementDocumentLineDocumentPageDocumentSelectionMarkDocumentSpanDocumentStyleDocumentTableDocumentTableCellDocumentWord
  • 添加了新的 DocumentModelAdministrationClient,具有方法:begin_build_modelbegin_create_composed_modelbegin_copy_modelget_copy_authorizationget_modeldelete_modellist_modelsget_operationlist_operationsget_account_infoget_document_analysis_client
  • 添加了新的模型以与新的 DocumentModelAdministrationClient 一起使用:DocumentModelDocumentModelInfoDocTypeInfoModelOperationModelOperationInfoAccountInfoDocumentAnalysisErrorDocumentAnalysisInnerError
  • /samples/v3.2-beta 下添加了使用 DocumentAnalysisClientDocumentModelAdministrationClient 的示例。
  • 添加了 DocumentAnalysisApiVersion 以与 DocumentAnalysisClientDocumentModelAdministrationClient 一起使用。

其他更改

  • 本版本不再支持 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_namestyle_confidence 属性,这些属性曾是 TextStyle 对象的一部分。
  • 已删除模型 TextStyle
  • FieldValueType 枚举中删除了字段值类型 "gender" 和 "country"。
  • FieldValueType 枚举中添加了字段值类型 "countryRegion"。
  • 将身份证明文件的字段名称从 "Country" 重命名为 "CountryRegion"。

新功能

  • 向所有模型添加了 to_dictfrom_dict 方法。

3.1.0b4 (2021-04-06)

新功能

  • 向 SDK 中引入了新方法 begin_recognize_id_documentsbegin_recognize_id_documents_from_url。使用这些方法从身份证明文件中识别数据。
  • FieldValueType 枚举中描述了新的字段值类型 "gender" 和 "country"。
  • 自定义表单和训练方法现在支持内容类型 image/bmp
  • 为名片、收据、自定义表单和发票添加了关键字参数 pages,以指定要处理的文档的页面。
  • begin_recognize_contentbegin_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_cardsbegin_recognize_business_cards_from_url。使用这些方法从名片中识别数据。
  • 向 SDK 中引入了新方法 begin_recognize_invoicesbegin_recognize_invoices_from_url。使用这些方法从发票中识别数据。
  • 识别收据的方法现在可以接受关键字参数 locale,以可选地指示收据的区域设置,从而提高结果。
  • 通过调用方法 begin_create_composed_model(),现在可以从 FormTrainingClient 创建组合模型。
  • 添加了对带有选择标记(如复选框和单选按钮)的自定义表单的训练和识别的支持。此功能仅适用于带有标签训练的模型。
  • FormPage 添加了属性 selection_marks,其中包含 FormSelectionMark 列表。
  • 当传递include_field_elements=True时,FieldDataFormTableCell上的field_elements属性也会填充页面上的任何选择标记
  • 将属性model_nameproperties添加到类型CustomFormModelCustomFormModelInfo
  • 将关键字参数model_name添加到begin_training()begin_create_composed_model()
  • 添加了模型类型CustomFormModelProperties,其中包含模型是否为组合模型等信息
  • 将属性model_id添加到CustomFormSubmodelTrainingDocumentInfo
  • 将属性model_idform_type_confidence添加到RecognizedForm
  • FormLine添加了appearance属性,以指示提取文本的样式,例如“手写”或“其他”
  • 将关键字参数pages添加到begin_recognize_contentbegin_recognize_content_from_url,以指定要分析的页面编号
  • FormTable添加了属性bounding_box
  • 内容类型image/bmp现在由内容识别和预构建模型支持
  • 将关键字参数language添加到begin_recognize_contentbegin_recognize_content_from_url,以指定处理文档的语言

依赖项更新

3.0.0 (2020-08-20)

azure-ai-formrecognizer客户端库的第一个稳定版本。

新功能

  • 可以通过客户端级别的关键字参数api_version来指定要使用的服务API版本。目前仅支持v2.0。有关支持的API版本,请参阅枚举FormRecognizerApiVersion
  • FormWordFormLine现在有属性kind,它指定了元素的类型,例如“单词”或“行”

3.0.0b1 (2020-08-11)

该包的版本现在针对服务的v2.0 API。

重大更改

  • 客户端库版本提升到3.0.0b1
  • 枚举FormContentTypeLengthUnitTrainingStatusCustomFormModelStatus的值现在为大写
  • TrainingDocumentInfo上的document_name已重命名为name
  • begin_training方法上的关键字参数include_sub_folders已重命名为include_subfolders

新功能

  • FormField现在有属性value_type,它包含字段值的语义数据类型。有关value_type的选项,请参阅枚举FieldValueType

修复和改进

  • 修复了一个错误,在该错误中,如果在轮询操作失败时返回HttpResponseError,则不会返回错误代码和消息
  • FormField属性value_data现在在它的FieldData没有返回值时设置为None。在此之前,value_data在上述情况下返回一个所有属性都设置为NoneFieldData

1.0.0b4 (2020-07-07)

重大更改

  • 已删除RecognizedReceipts类。
  • begin_recognize_receiptsbegin_recognize_receipts_from_url现在返回RecognizedForm
  • CustomFormModelCustomFormModelInfo上的requested_on已重命名为training_started_oncompleted_on已重命名为training_completed_on
  • FieldText已重命名为FieldData
  • FormContent已重命名为FormElement
  • begin_recognize_receiptsbegin_recognize_receipts_from_urlbegin_recognize_custom_formsbegin_recognize_custom_forms_from_url上的参数include_text_content已重命名为include_field_elements
  • FieldDataFormTableCell上的text_content已重命名为field_elements

修复和改进

  • 修复了一个错误,其中text_angle返回了指定的区间(-180, 180]之外的值

1.0.0b3 (2020-06-10)

重大更改

  • 所有异步长时间运行操作方法现在从azure-core返回一个AsyncLROPoller实例
  • 所有异步长时间运行操作方法现在都使用begin_前缀重命名,以指示返回一个AsyncLROPoller
    • train_model已重命名为begin_training
    • recognize_receipts已重命名为begin_recognize_receipts
    • recognize_receipts_from_url 已重命名为 begin_recognize_receipts_from_url
    • recognize_content 已重命名为 begin_recognize_content
    • recognize_content_from_url 已重命名为 begin_recognize_content_from_url
    • recognize_custom_forms 已重命名为 begin_recognize_custom_forms
    • recognize_custom_forms_from_url 已重命名为 begin_recognize_custom_forms_from_url
  • 同步方法 begin_train_model 已重命名为 begin_training
  • begin_trainingtraining_files 参数已重命名为 training_files_url
  • begin_traininguse_labels 参数已重命名为 use_training_labels
  • list_model_infos 方法已重命名为 list_custom_models
  • FormRecognizerClient 中移除了 get_form_training_client
  • FormTrainingClient 中添加了 get_form_recognizer_client
  • 如果从 begin_training 方法返回的模型状态为 "invalid",则会引发 HttpResponseError
  • PageRange 已重命名为 FormPageRange
  • FormPageRange 上的 first_pagelast_page 分别重命名为 first_page_numberlast_page_number
  • FormField 没有页面编号
  • use_training_labels 现在是 begin_training API 中的必需位置参数
  • FormRecognizerClient 方法上的 streamurl 参数已分别重命名为 formform_url
  • 对于 begin_recognize_receipt 方法,参数已重命名为 receiptreceipt_url
  • CustomFormModelCustomFormModelInfo 模型中,created_onlast_modified 已重命名为 requested_oncompleted_on
  • CustomFormModelmodels 属性已重命名为 submodels
  • CustomFormSubModel 已重命名为 CustomFormSubmodel
  • begin_recognize_receipts API 现在返回一个 RecognizedReceipt 列表,而不是 USReceipt
  • 已移除 USReceipt。有关如何处理 begin_recognize_receipts 的返回值,请参阅 samples 目录 中的识别收据示例。
  • 已移除 USReceiptItem。有关如何访问收据上的各个项,请参阅 samples 目录 中的识别收据示例。
  • 已移除 USReceiptTypeRecognizedReceipt 中的 receipt_type 属性。有关详细信息,请参阅 samples 目录 中的识别收据示例。

新功能

  • 支持将自定义模型从一个表单识别资源复制到另一个资源
  • 现在支持使用 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
  • azure.ai.formrecognizer.aio 命名空间下添加了异步 API
  • 支持使用来自 azure.core.credentialsAzureKeyCredential("<api_key>") 进行 API 密钥认证
  • 基于 azure-core 库的新底层 REST 管道实现
  • 现在可以通过关键字参数在客户端级别和每个操作级别进行客户端和管道配置。请参阅 README 以获取可选配置参数的链接
  • 新的错误层次结构
    • 所有服务错误现在都将使用基类:azure.core.exceptions.HttpResponseError

项目详情


下载文件

下载您平台的文件。如果您不确定选择哪个,请了解有关 安装包 的更多信息。

源分发

azure-ai-formrecognizer-3.3.3.tar.gz (397.9 kB 查看哈希值)

上传时间

构建分发

azure_ai_formrecognizer-3.3.3-py3-none-any.whl (301.4 kB 查看哈希值)

上传时间 Python 3

由以下支持

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误日志 StatusPage StatusPage 状态页面