Share via


Python 用 Azure Form Recognizer クライアント ライブラリ - バージョン 3.0.0

Azure Cognitive Services Form Recognizer は、機械学習を使用してフォーム ドキュメントからテキストとテーブルのデータを認識するクラウド サービスです。 これには、次の主な機能が含まれます。

  • カスタム モデル - フォームからフィールド値とテーブル データを認識します。 これらのモデルは自分が用意した独自のデータでトレーニングされるため、実際のフォームに合わせて調整されます。
  • Content API - テキストとテーブルの構造と、境界ボックス座標をドキュメントから認識します。 REST サービスの Layout API に対応します。
  • 事前構築済みのレシート モデル - 事前構築済みモデルを使用して、米国の売上領収書からのデータを認識します。

ソースコード | パッケージ (PyPI) | API リファレンス ドキュメント| 製品ドキュメント | サンプル

作業の開始

前提条件

パッケージをインストールする

Python 用 Azure Form Recognizer クライアント ライブラリ - pip を使用してバージョン 3.0.0 をインストールします。

pip install azure-ai-formrecognizer

注: このバージョンのクライアント ライブラリでは、Form Recognizer サービスの v2.0 バージョンがサポートされています

Form Recognizer リソースを作成する

Form Recognizerでは、マルチサービス アクセスと単一サービス アクセスの両方がサポートされます。 1 つのエンドポイント/キーで複数の Cognitive Services にアクセスする予定の場合は、Cognitive Services リソースを作成します。 Form Recognizer アクセスのみの場合は、Form Recognizer リソースを作成します。

を使用してリソースを作成できます。

オプション 1:Azure Portal

オプション 2:Azure CLI。 CLI を使用してForm Recognizer リソースを作成する方法の例を次に示します。

# Create a new resource group to hold the form recognizer resource -
# if using an existing resource group, skip this step
az group create --name my-resource-group --location westus2
# Create form recognizer
az cognitiveservices account create \
    --name form-recognizer-resource \
    --resource-group my-resource-group \
    --kind FormRecognizer \
    --sku F0 \
    --location westus2 \
    --yes

クライアントを認証する

Form Recognizer サービスと対話するには、クライアントのインスタンスを作成する必要があります。 クライアント オブジェクトをインスタンス化するには、 エンドポイント資格情報 が必要です。

エンドポイントの参照

Form Recognizer リソースのエンドポイントは、Azure Portal または Azure CLI を使用して確認できます。

# Get the endpoint for the form recognizer resource
az cognitiveservices account show --name "resource-name" --resource-group "resource-group-name" --query "endpoint"

API キーを取得する

API キーは、Azure Portal で、または次の 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 FormRecognizerClient

endpoint = "https://<region>.api.cognitive.microsoft.com/"
credential = AzureKeyCredential("<api_key>")
form_recognizer_client = FormRecognizerClient(endpoint, credential)

Azure Active Directory 資格情報を使用してクライアントを作成する

AzureKeyCredential 認証は、このファースト ステップ ガイドの例で使用しますが、 azure-identity ライブラリを使用して Azure Active Directory で認証することもできます。 リージョン エンドポイントでは AAD 認証がサポートされないことに注意してください。 この種類の認証を使用するために、リソースの カスタム サブドメイン 名を作成します。

次に示す DefaultAzureCredential 型、または Azure SDK で提供されているその他の資格情報の種類を使用するには、パッケージを azure-identity インストールしてください。

pip install azure-identity

また、新しい AAD アプリケーションを登録し、サービス プリンシパルにロールを割り当てること"Cognitive Services User"で、Form Recognizerへのアクセス権を付与する必要があります。

完了したら、AAD アプリケーションのクライアント ID、テナント ID、およびクライアント シークレットの値を環境変数として設定します。 AZURE_CLIENT_IDAZURE_TENANT_IDAZURE_CLIENT_SECRET

from azure.identity import DefaultAzureCredential
from azure.ai.formrecognizer import FormRecognizerClient
credential = DefaultAzureCredential()

form_recognizer_client = FormRecognizerClient(
    endpoint="https://<my-custom-subdomain>.cognitiveservices.azure.com/",
    credential=credential
)

主要な概念

FormRecognizerClient

FormRecognizerClient には、以下を目的とした操作が用意されています。

  • 対象のカスタム フォームを認識するようトレーニングされたカスタム モデルを使用して、フォームのフィールドやコンテンツを認識する。 これらの値は、RecognizedForm オブジェクトのコレクションとして返されます。
  • 事前トレーニング済みのレシート モデルを使用して、米国の領収書からの共通フィールドを認識する。 これらのフィールドとメタデータは、オブジェクトの RecognizedForm コレクションで返されます。
  • モデルをトレーニングせずにフォームのコンテンツ (表、行、単語など) を認識する。 フォームのコンテンツは、FormPage オブジェクトのコレクションとして返されます。

ここでは、FormRecognizerClient を示すサンプル コード スニペットが用意されています。

FormTrainingClient

FormTrainingClient には、以下を目的とした操作が用意されています。

  • カスタム フォームで見つかったすべてのフィールドと値を認識するために、ラベルなしでカスタム モデルをトレーニングします。 モデルによって認識されるフォームの種類とそれぞれのフォームの種類で抽出されるフィールドを示す CustomFormModel が返されます。 詳細な説明については、 サービスのドキュメント を参照してください。
  • ラベルを使用してカスタム モデルをトレーニングし、カスタム フォームにラベルを付けることで指定した特定のフィールドと値を認識します。 モデルによって抽出されるフィールドと各フィールドの推定精度を示す CustomFormModel が返されます。 詳細な説明については、 サービスのドキュメント を参照してください。
  • アカウントに作成されたモデルを管理する。
  • Form Recognizer リソース間でカスタム モデルをコピーする。

モデルのトレーニングは、Form Recognizer のラベル付けツールなど、グラフィカル ユーザー インターフェイスを使用して行うこともできることに注意してください。

サンプル コード スニペットは、ここで FormTrainingClient を使用する方法を示すために提供されています。

Long-Running操作

実行時間の長い操作は、操作を開始するためにサービスに送信された最初の要求で構成される操作です。その後、間隔を指定してサービスをポーリングして、操作が完了したか失敗したか、成功したかどうかを判断して結果を取得します。

モデルのトレーニング、フォームからの値の認識、またはモデルのコピーを行うメソッドは、実行時間の長い操作としてモデル化されます。 クライアントは、 または AsyncLROPollerbegin_<method-name>返すメソッドをLROPoller公開します。 呼び出し元は、 メソッドから返された poller オブジェクトを呼び出 result() して、操作が完了するまで待機する begin_<method-name> 必要があります。 実行時間の長い操作の使用例を示すサンプル コード スニペット 用意されています

次のセクションでは、次のような最も一般的なForm Recognizer タスクをカバーするいくつかのコード スニペットを示します。

カスタム モデルを使用してフォームを認識する

フォームから名前と値のペアとテーブル データを認識します。 これらのモデルは自分が用意した独自のデータでトレーニングされるため、実際のフォームに合わせて調整されます。 最良の結果を得るには、カスタム モデルがトレーニングされたのと同じフォーム型のフォームのみを認識する必要があります。

from azure.ai.formrecognizer import FormRecognizerClient
from azure.core.credentials import AzureKeyCredential

endpoint = "https://<region>.api.cognitive.microsoft.com/"
credential = AzureKeyCredential("<api_key>")

form_recognizer_client = FormRecognizerClient(endpoint, credential)
model_id = "<your custom model id>"

with open("<path to your form>", "rb") as fd:
    form = fd.read()

poller = form_recognizer_client.begin_recognize_custom_forms(model_id=model_id, form=form)
result = poller.result()

for recognized_form in result:
    print("Form type: {}".format(recognized_form.form_type))
    for name, field in recognized_form.fields.items():
        print("Field '{}' has label '{}' with value '{}' and a confidence score of {}".format(
            name,
            field.label_data.text if field.label_data else name,
            field.value,
            field.confidence
        ))

または、フォーム URL を使用して、 メソッドを使用して begin_recognize_custom_forms_from_url カスタム フォームを認識することもできます。 メソッドは _from_url 、すべての recognize メソッドに対して存在します。

form_url = "<url_of_the_form>"
poller = form_recognizer_client.begin_recognize_custom_forms_from_url(model_id=model_id, form_url=form_url)
result = poller.result()

コンテンツを認識する

文書からテキストとテーブルの構造とその境界ボックス座標を認識します。

from azure.ai.formrecognizer import FormRecognizerClient
from azure.core.credentials import AzureKeyCredential

endpoint = "https://<region>.api.cognitive.microsoft.com/"
credential = AzureKeyCredential("<api_key>")

form_recognizer_client = FormRecognizerClient(endpoint, credential)

with open("<path to your form>", "rb") as fd:
    form = fd.read()

poller = form_recognizer_client.begin_recognize_content(form)
page = poller.result()

table = page[0].tables[0] # page 1, table 1
print("Table found on page {}:".format(table.page_number))
for cell in table.cells:
    print("Cell text: {}".format(cell.text))
    print("Location: {}".format(cell.bounding_box))
    print("Confidence score: {}\n".format(cell.confidence))

領収書を認識する

事前構築済みモデルを使用して、米国の売上領収書からのデータを認識します。 サービスによって認識される領収書フィールドについては、 こちらを参照してください

from azure.ai.formrecognizer import FormRecognizerClient
from azure.core.credentials import AzureKeyCredential

endpoint = "https://<region>.api.cognitive.microsoft.com/"
credential = AzureKeyCredential("<api_key>")

form_recognizer_client = FormRecognizerClient(endpoint, credential)

with open("<path to your receipt>", "rb") as fd:
    receipt = fd.read()

poller = form_recognizer_client.begin_recognize_receipts(receipt)
result = poller.result()

for receipt in result:
    for name, field in receipt.fields.items():
        if name == "Items":
            print("Receipt Items:")
            for idx, items in enumerate(field.value):
                print("...Item #{}".format(idx+1))
                for item_name, item in items.value.items():
                    print("......{}: {} has confidence {}".format(item_name, item.value, item.confidence))
        else:
            print("{}: {} has confidence {}".format(name, field.value, field.confidence))

モデルをトレーニングする

独自のフォームの種類でカスタム モデルをトレーニングします。 結果のモデルを使用して、トレーニング対象のフォームの種類から値を認識できます。 トレーニング ドキュメントを格納する Azure Storage BLOB コンテナーにコンテナー SAS URL を指定します。 トレーニング ファイルがコンテナー内のサブフォルダー内にある場合は、 prefix キーワード引数を使用して、トレーニングするフォルダーを指定します。

コンテナーの設定と必要なファイル構造の詳細については、 サービスドキュメントを参照してください

from azure.ai.formrecognizer import FormTrainingClient
from azure.core.credentials import AzureKeyCredential

endpoint = "https://<region>.api.cognitive.microsoft.com/"
credential = AzureKeyCredential("<api_key>")

form_training_client = FormTrainingClient(endpoint, credential)

container_sas_url = "<container-sas-url>"  # training documents uploaded to blob storage
poller = form_training_client.begin_training(
    container_sas_url, use_training_labels=False
)
model = poller.result()

# Custom model information
print("Model ID: {}".format(model.model_id))
print("Status: {}".format(model.status))
print("Training started on: {}".format(model.training_started_on))
print("Training completed on: {}".format(model.training_completed_on))

print("\nRecognized fields:")
for submodel in model.submodels:
    print(
        "The submodel with form type '{}' has recognized the following fields: {}".format(
            submodel.form_type,
            ", ".join(
                [
                    field.label if field.label else name
                    for name, field in submodel.fields.items()
                ]
            ),
        )
    )

# Training result information
for doc in model.training_documents:
    print("Document name: {}".format(doc.name))
    print("Document status: {}".format(doc.status))
    print("Document page count: {}".format(doc.page_count))
    print("Document errors: {}".format(doc.errors))

モデルの管理

アカウントにアタッチされているカスタム モデルを管理します。

from azure.ai.formrecognizer import FormTrainingClient
from azure.core.credentials import AzureKeyCredential
from azure.core.exceptions import ResourceNotFoundError

endpoint = "https://<region>.api.cognitive.microsoft.com/"
credential = AzureKeyCredential("<api_key>")

form_training_client = FormTrainingClient(endpoint, credential)

account_properties = form_training_client.get_account_properties()
print("Our account has {} custom models, and we can have at most {} custom models".format(
    account_properties.custom_model_count, account_properties.custom_model_limit
))

# Here we get a paged list of all of our custom models
custom_models = form_training_client.list_custom_models()
print("We have models with the following ids: {}".format(
    ", ".join([m.model_id for m in custom_models])
))

# Replace with the custom model ID from the "Train a model" sample
model_id = "<model_id from the Train a Model sample>"

custom_model = form_training_client.get_custom_model(model_id=model_id)
print("Model ID: {}".format(custom_model.model_id))
print("Status: {}".format(custom_model.status))
print("Training started on: {}".format(custom_model.training_started_on))
print("Training completed on: {}".format(custom_model.training_completed_on))

# Finally, we will delete this model by ID
form_training_client.delete_model(model_id=custom_model.model_id)

try:
    form_training_client.get_custom_model(model_id=custom_model.model_id)
except ResourceNotFoundError:
    print("Successfully deleted model with id {}".format(custom_model.model_id))

トラブルシューティング

全般

クライアント ライブラリForm Recognizer、Azure Core で定義されている例外が発生します。

ログの記録

このライブラリでは、標準の ログ記録 ライブラリを使用してログを記録します。 HTTP セッション (URL、ヘッダーなど) に関する基本情報は INFO レベルでログに記録されます。

要求/応答本文と編集されていないヘッダーを含む詳細なデバッグ レベルのログ記録は、次のように logging_enable キーワード引数を使用してクライアントで有効にすることができます。

import sys
import logging
from azure.ai.formrecognizer import FormRecognizerClient
from azure.core.credentials import AzureKeyCredential

# Create a logger for the 'azure' SDK
logger = logging.getLogger('azure')
logger.setLevel(logging.DEBUG)

# Configure a console output
handler = logging.StreamHandler(stream=sys.stdout)
logger.addHandler(handler)

endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/"
credential = AzureKeyCredential("<api_key>")

# This client will log detailed information about its HTTP sessions, at DEBUG level
form_recognizer_client = FormRecognizerClient(endpoint, credential, logging_enable=True)

同様に、logging_enable は、詳細なログ記録がクライアントで有効になっていない場合でも、1 回の操作のために有効にすることができます。

poller = form_recognizer_client.begin_recognize_receipts(receipt, logging_enable=True)

オプションの構成

省略可能なキーワード引数は、クライアントレベルおよび操作ごとのレベルで渡すことができます。 azure-core リファレンス ドキュメント では、再試行、ログ記録、トランスポート プロトコルなどの使用可能な構成について説明しています。

次のステップ

次のセクションでは、Form Recognizer Python API で使用される一般的なパターンを示すコード スニペットをいくつか示します。

その他のサンプル コード

これらのコード サンプルは、Azure Form Recognizer クライアント ライブラリでの一般的なシナリオ操作を示しています。

非同期 API

このライブラリには、Python 3.5 以降でサポートされている完全な非同期 API も含まれています。 これを使用するには、まず、 aiohttp などの非同期トランスポートをインストールする必要があります。 非同期クライアントは 名前空間の下にあります azure.ai.formrecognizer.aio

その他のドキュメント

Azure Cognitive Services Form Recognizerに関するより広範なドキュメントについては、docs.microsoft.com に関するForm Recognizerドキュメントを参照してください

共同作成

このプロジェクトでは、共同作成と提案を歓迎しています。 ほとんどの共同作成では、共同作成者使用許諾契約書 (CLA) にご同意いただき、ご自身の共同作成内容を使用する権利を Microsoft に供与する権利をお持ちであり、かつ実際に供与することを宣言していただく必要があります。 詳細については、「 cla.microsoft.com」を参照してください。

pull request を送信すると、CLA を提供して PR (ラベル、コメントなど) を適宜装飾する必要があるかどうかを CLA ボットが自動的に決定します。 ボットによって提供される手順にそのまま従ってください。 この操作は、Microsoft の CLA を使用するすべてのリポジトリについて、1 回だけ行う必要があります。

このプロジェクトでは、Microsoft オープン ソースの倫理規定を採用しています。 詳しくは、「Code of Conduct FAQ (倫理規定についてよくある質問)」を参照するか、opencode@microsoft.com 宛てに質問またはコメントをお送りください。