DocumentAnalysisClient クラス
DocumentAnalysisClient は、ドキュメントと画像からの情報を分析し、ドキュメントを分類します。 これは、事前構築済みモデル (領収書、名刺、請求書、ID ドキュメントなど) を使用した分析、ドキュメントからのレイアウトの分析、一般的なドキュメントの種類の分析、および構築されたモデルを使用したカスタム ドキュメントの分析に使用するインターフェイスです (サービスでサポートされているモデルの完全な一覧を表示するには、次 https://aka.ms/azsdk/formrecognizer/modelsを参照してください)。 URL からの入力とストリームからの入力に基づいて、さまざまなメソッドが提供されます。
注意
DocumentAnalysisClient は API バージョンで使用する必要がある
2022-08-31 以降。 API バージョン =v2.1 を <使用するには、FormRecognizerClient をインスタンス化します。
バージョン 2022-08-31 の新機能: DocumentAnalysisClient とそのクライアント メソッド。
- 継承
-
azure.ai.formrecognizer._form_base_client.FormRecognizerClientBaseDocumentAnalysisClient
コンストラクター
DocumentAnalysisClient(endpoint: str, credential: AzureKeyCredential | TokenCredential, **kwargs: Any)
パラメーター
- endpoint
- str
サポートされている Cognitive Services エンドポイント (プロトコルとホスト名など)。 https://westus2.api.cognitive.microsoft.com
- credential
- AzureKeyCredential または TokenCredential
クライアントが Azure に接続するために必要な資格情報。 API キーまたは からの identityトークン資格情報を使用している場合、これは AzureKeyCredential のインスタンスです。
- api_version
- str または DocumentAnalysisApiVersion
要求に使用するサービスの API バージョン。 既定値は最新のサービス バージョンです。 古いバージョンに設定すると、機能の互換性が低下する可能性があります。 API バージョン =v2.1 を <使用するには、FormRecognizerClient をインスタンス化します。
例
エンドポイントと API キーを使用して DocumentAnalysisClient を作成する。
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, AzureKeyCredential(key))
トークン資格情報を使用して DocumentAnalysisClient を作成する。
"""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)
メソッド
begin_analyze_document |
特定のドキュメントのフィールド テキストとセマンティック値を分析します。 バージョン 2023-07-31 の新機能: 引数キーワード (keyword)機能。 |
begin_analyze_document_from_url |
特定のドキュメントのフィールド テキストとセマンティック値を分析します。 入力は、分析するドキュメントの場所 (URL) である必要があります。 バージョン 2023-07-31 の新機能: 引数キーワード (keyword)機能。 |
begin_classify_document |
ドキュメント分類子を使用してドキュメントを分類します。 カスタム分類子モデルを構築する方法の詳細については、「」を参照してください https://aka.ms/azsdk/formrecognizer/buildclassifiermodel。 バージョン 2023-07-31 の新機能: begin_classify_document クライアント メソッド。 |
begin_classify_document_from_url |
特定のドキュメントをドキュメント分類子で分類します。 カスタム分類子モデルを構築する方法の詳細については、「」を参照してください https://aka.ms/azsdk/formrecognizer/buildclassifiermodel。 入力は、分類するドキュメントの場所 (URL) である必要があります。 バージョン 2023-07-31 の新機能: begin_classify_document_from_url クライアント メソッド。 |
close |
セッションを DocumentAnalysisClient 閉じます。 |
send_request |
クライアントの既存のパイプラインを使用してネットワーク要求を実行します。 要求 URL は、ベース URL を基準にして指定できます。 要求に使用されるサービス API のバージョンは、特に指定がない限り、クライアントと同じです。 クライアントの構成済み API バージョンを相対 URL でオーバーライドすることは、API バージョン 2022-08-31 以降のクライアントでサポートされています。 任意の API バージョンでクライアントでサポートされている絶対 URL でのオーバーライド。 応答がエラーの場合、このメソッドは発生しません。例外を発生させる場合は、返された応答オブジェクト に対して raise_for_status() を呼び出します。 このメソッドを使用してカスタム要求を送信する方法の詳細については、「」を参照してください https://aka.ms/azsdk/dpcodegen/python/send_request。 |
begin_analyze_document
特定のドキュメントのフィールド テキストとセマンティック値を分析します。
バージョン 2023-07-31 の新機能: 引数キーワード (keyword)機能。
begin_analyze_document(model_id: str, document: bytes | IO[bytes], **kwargs: Any) -> LROPoller[AnalyzeResult]
パラメーター
- model_id
- str
一意のモデル識別子は、文字列として渡すことができます。 これを使用して、カスタム モデル ID または事前構築済みモデル ID を指定します。 サポートされている事前構築済みモデル ID は、次の場所にあります。 https://aka.ms/azsdk/formrecognizer/models
ファイル ストリームまたはバイト。 サービスでサポートされるファイルの種類については、 を参照してください https://aka.ms/azsdk/formrecognizer/supportedfiles。
- pages
- str
複数ページのドキュメントのカスタム ページ番号 (PDF/TIFF)。 結果で取得するページ番号やページ範囲を入力します。 ページの範囲には、 pages="1-3, 5-6" などのハイフンを使用します。 各ページ番号または範囲をコンマで区切ります。
- locale
- str
入力ドキュメントのロケール ヒント。 サポートされているロケールについては、 https://aka.ms/azsdk/formrecognizer/supportedlocalesを参照してください。
戻り値
LROPoller のインスタンス。 poller オブジェクトで result() を呼び出して、 を AnalyzeResult返します。
の戻り値の型 :
例外
例
請求書を分析します。 その他のサンプルについては、 samples フォルダーを参照してください。
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-invoice", document=f, locale="en-US"
)
invoices = poller.result()
for idx, invoice in enumerate(invoices.documents):
print(f"--------Analyzing invoice #{idx + 1}--------")
vendor_name = invoice.fields.get("VendorName")
if vendor_name:
print(
f"Vendor Name: {vendor_name.value} has confidence: {vendor_name.confidence}"
)
vendor_address = invoice.fields.get("VendorAddress")
if vendor_address:
print(
f"Vendor Address: {vendor_address.value} has confidence: {vendor_address.confidence}"
)
vendor_address_recipient = invoice.fields.get("VendorAddressRecipient")
if vendor_address_recipient:
print(
f"Vendor Address Recipient: {vendor_address_recipient.value} has confidence: {vendor_address_recipient.confidence}"
)
customer_name = invoice.fields.get("CustomerName")
if customer_name:
print(
f"Customer Name: {customer_name.value} has confidence: {customer_name.confidence}"
)
customer_id = invoice.fields.get("CustomerId")
if customer_id:
print(
f"Customer Id: {customer_id.value} has confidence: {customer_id.confidence}"
)
customer_address = invoice.fields.get("CustomerAddress")
if customer_address:
print(
f"Customer Address: {customer_address.value} has confidence: {customer_address.confidence}"
)
customer_address_recipient = invoice.fields.get("CustomerAddressRecipient")
if customer_address_recipient:
print(
f"Customer Address Recipient: {customer_address_recipient.value} has confidence: {customer_address_recipient.confidence}"
)
invoice_id = invoice.fields.get("InvoiceId")
if invoice_id:
print(
f"Invoice Id: {invoice_id.value} has confidence: {invoice_id.confidence}"
)
invoice_date = invoice.fields.get("InvoiceDate")
if invoice_date:
print(
f"Invoice Date: {invoice_date.value} has confidence: {invoice_date.confidence}"
)
invoice_total = invoice.fields.get("InvoiceTotal")
if invoice_total:
print(
f"Invoice Total: {invoice_total.value} has confidence: {invoice_total.confidence}"
)
due_date = invoice.fields.get("DueDate")
if due_date:
print(f"Due Date: {due_date.value} has confidence: {due_date.confidence}")
purchase_order = invoice.fields.get("PurchaseOrder")
if purchase_order:
print(
f"Purchase Order: {purchase_order.value} has confidence: {purchase_order.confidence}"
)
billing_address = invoice.fields.get("BillingAddress")
if billing_address:
print(
f"Billing Address: {billing_address.value} has confidence: {billing_address.confidence}"
)
billing_address_recipient = invoice.fields.get("BillingAddressRecipient")
if billing_address_recipient:
print(
f"Billing Address Recipient: {billing_address_recipient.value} has confidence: {billing_address_recipient.confidence}"
)
shipping_address = invoice.fields.get("ShippingAddress")
if shipping_address:
print(
f"Shipping Address: {shipping_address.value} has confidence: {shipping_address.confidence}"
)
shipping_address_recipient = invoice.fields.get("ShippingAddressRecipient")
if shipping_address_recipient:
print(
f"Shipping Address Recipient: {shipping_address_recipient.value} has confidence: {shipping_address_recipient.confidence}"
)
print("Invoice items:")
for idx, item in enumerate(invoice.fields.get("Items").value):
print(f"...Item #{idx + 1}")
item_description = item.value.get("Description")
if item_description:
print(
f"......Description: {item_description.value} has confidence: {item_description.confidence}"
)
item_quantity = item.value.get("Quantity")
if item_quantity:
print(
f"......Quantity: {item_quantity.value} has confidence: {item_quantity.confidence}"
)
unit = item.value.get("Unit")
if unit:
print(f"......Unit: {unit.value} has confidence: {unit.confidence}")
unit_price = item.value.get("UnitPrice")
if unit_price:
unit_price_code = unit_price.value.code if unit_price.value.code else ""
print(
f"......Unit Price: {unit_price.value}{unit_price_code} has confidence: {unit_price.confidence}"
)
product_code = item.value.get("ProductCode")
if product_code:
print(
f"......Product Code: {product_code.value} has confidence: {product_code.confidence}"
)
item_date = item.value.get("Date")
if item_date:
print(
f"......Date: {item_date.value} has confidence: {item_date.confidence}"
)
tax = item.value.get("Tax")
if tax:
print(f"......Tax: {tax.value} has confidence: {tax.confidence}")
amount = item.value.get("Amount")
if amount:
print(
f"......Amount: {amount.value} has confidence: {amount.confidence}"
)
subtotal = invoice.fields.get("SubTotal")
if subtotal:
print(f"Subtotal: {subtotal.value} has confidence: {subtotal.confidence}")
total_tax = invoice.fields.get("TotalTax")
if total_tax:
print(
f"Total Tax: {total_tax.value} has confidence: {total_tax.confidence}"
)
previous_unpaid_balance = invoice.fields.get("PreviousUnpaidBalance")
if previous_unpaid_balance:
print(
f"Previous Unpaid Balance: {previous_unpaid_balance.value} has confidence: {previous_unpaid_balance.confidence}"
)
amount_due = invoice.fields.get("AmountDue")
if amount_due:
print(
f"Amount Due: {amount_due.value} has confidence: {amount_due.confidence}"
)
service_start_date = invoice.fields.get("ServiceStartDate")
if service_start_date:
print(
f"Service Start Date: {service_start_date.value} has confidence: {service_start_date.confidence}"
)
service_end_date = invoice.fields.get("ServiceEndDate")
if service_end_date:
print(
f"Service End Date: {service_end_date.value} has confidence: {service_end_date.confidence}"
)
service_address = invoice.fields.get("ServiceAddress")
if service_address:
print(
f"Service Address: {service_address.value} has confidence: {service_address.confidence}"
)
service_address_recipient = invoice.fields.get("ServiceAddressRecipient")
if service_address_recipient:
print(
f"Service Address Recipient: {service_address_recipient.value} has confidence: {service_address_recipient.confidence}"
)
remittance_address = invoice.fields.get("RemittanceAddress")
if remittance_address:
print(
f"Remittance Address: {remittance_address.value} has confidence: {remittance_address.confidence}"
)
remittance_address_recipient = invoice.fields.get("RemittanceAddressRecipient")
if remittance_address_recipient:
print(
f"Remittance Address Recipient: {remittance_address_recipient.value} has confidence: {remittance_address_recipient.confidence}"
)
カスタム ドキュメントを分析する。 その他のサンプルについては、 samples フォルダーを参照してください。
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("-----------------------------------")
begin_analyze_document_from_url
特定のドキュメントのフィールド テキストとセマンティック値を分析します。 入力は、分析するドキュメントの場所 (URL) である必要があります。
バージョン 2023-07-31 の新機能: 引数キーワード (keyword)機能。
begin_analyze_document_from_url(model_id: str, document_url: str, **kwargs: Any) -> LROPoller[AnalyzeResult]
パラメーター
- model_id
- str
一意のモデル識別子は、文字列として渡すことができます。 これを使用して、カスタム モデル ID または事前構築済みモデル ID を指定します。 サポートされている事前構築済みモデル ID は、次の場所にあります。 https://aka.ms/azsdk/formrecognizer/models
- document_url
- str
分析するドキュメントの URL。 入力は、有効で適切にエンコードされた (空のスペースなどの特殊文字をエンコードする)、パブリックにアクセスできる URL である必要があります。 サービスでサポートされるファイルの種類については、 を参照してください https://aka.ms/azsdk/formrecognizer/supportedfiles。
- pages
- str
複数ページのドキュメントのカスタム ページ番号 (PDF/TIFF)。 結果で取得するページ番号やページ範囲を入力します。 ページの範囲には、 pages="1-3, 5-6" などのハイフンを使用します。 各ページ番号または範囲をコンマで区切ります。
- locale
- str
入力ドキュメントのロケール ヒント。 サポートされているロケールについては、 https://aka.ms/azsdk/formrecognizer/supportedlocalesを参照してください。
戻り値
LROPoller のインスタンス。 poller オブジェクトで result() を呼び出して、 を AnalyzeResult返します。
の戻り値の型 :
例外
例
領収書を分析します。 その他のサンプルについては、 samples フォルダーを参照してください。
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)
)
url = "https://raw.githubusercontent.com/Azure/azure-sdk-for-python/main/sdk/formrecognizer/azure-ai-formrecognizer/tests/sample_forms/receipt/contoso-receipt.png"
poller = document_analysis_client.begin_analyze_document_from_url(
"prebuilt-receipt", document_url=url
)
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("--------------------------------------")
begin_classify_document
ドキュメント分類子を使用してドキュメントを分類します。 カスタム分類子モデルを構築する方法の詳細については、「」を参照してください https://aka.ms/azsdk/formrecognizer/buildclassifiermodel。
バージョン 2023-07-31 の新機能: begin_classify_document クライアント メソッド。
begin_classify_document(classifier_id: str, document: bytes | IO[bytes], **kwargs: Any) -> LROPoller[AnalyzeResult]
パラメーター
ファイル ストリームまたはバイト。 サービスでサポートされるファイルの種類については、 を参照してください https://aka.ms/azsdk/formrecognizer/supportedfiles。
戻り値
LROPoller のインスタンス。 poller オブジェクトで result() を呼び出して、 を AnalyzeResult返します。
の戻り値の型 :
例外
例
ドキュメントを分類します。 その他のサンプルについては、 samples フォルダーを参照してください。
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"]
classifier_id = os.getenv("CLASSIFIER_ID", classifier_id)
document_analysis_client = DocumentAnalysisClient(
endpoint=endpoint, credential=AzureKeyCredential(key)
)
with open(path_to_sample_documents, "rb") as f:
poller = document_analysis_client.begin_classify_document(
classifier_id, document=f
)
result = poller.result()
print("----Classified documents----")
for doc in result.documents:
print(
f"Found document of type '{doc.doc_type or 'N/A'}' with a confidence of {doc.confidence} contained on "
f"the following pages: {[region.page_number for region in doc.bounding_regions]}"
)
begin_classify_document_from_url
特定のドキュメントをドキュメント分類子で分類します。 カスタム分類子モデルを構築する方法の詳細については、「」を参照してください https://aka.ms/azsdk/formrecognizer/buildclassifiermodel。 入力は、分類するドキュメントの場所 (URL) である必要があります。
バージョン 2023-07-31 の新機能: begin_classify_document_from_url クライアント メソッド。
begin_classify_document_from_url(classifier_id: str, document_url: str, **kwargs: Any) -> LROPoller[AnalyzeResult]
パラメーター
- document_url
- str
分類するドキュメントの URL。 入力は、有効で適切にエンコードされた (空のスペースなどの特殊文字をエンコードする) と、サポートされている形式の 1 つのパブリックにアクセスできる URL である必要があります。 https://aka.ms/azsdk/formrecognizer/supportedfiles
戻り値
LROPoller のインスタンス。 poller オブジェクトで result() を呼び出して、 を AnalyzeResult返します。
の戻り値の型 :
例外
例
ドキュメントを分類します。 その他のサンプルについては、 samples フォルダーを参照してください。
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"]
classifier_id = os.getenv("CLASSIFIER_ID", classifier_id)
document_analysis_client = DocumentAnalysisClient(
endpoint=endpoint, credential=AzureKeyCredential(key)
)
url = "https://raw.githubusercontent.com/Azure/azure-sdk-for-python/main/sdk/formrecognizer/azure-ai-formrecognizer/tests/sample_forms/forms/IRS-1040.pdf"
poller = document_analysis_client.begin_classify_document_from_url(
classifier_id, document_url=url
)
result = poller.result()
print("----Classified documents----")
for doc in result.documents:
print(
f"Found document of type '{doc.doc_type or 'N/A'}' with a confidence of {doc.confidence} contained on "
f"the following pages: {[region.page_number for region in doc.bounding_regions]}"
)
close
send_request
クライアントの既存のパイプラインを使用してネットワーク要求を実行します。
要求 URL は、ベース URL を基準にして指定できます。 要求に使用されるサービス API のバージョンは、特に指定がない限り、クライアントと同じです。 クライアントの構成済み API バージョンを相対 URL でオーバーライドすることは、API バージョン 2022-08-31 以降のクライアントでサポートされています。 任意の API バージョンでクライアントでサポートされている絶対 URL でのオーバーライド。 応答がエラーの場合、このメソッドは発生しません。例外を発生させる場合は、返された応答オブジェクト に対して raise_for_status() を呼び出します。 このメソッドを使用してカスタム要求を送信する方法の詳細については、「」を参照してください https://aka.ms/azsdk/dpcodegen/python/send_request。
send_request(request: HttpRequest, *, stream: bool = False, **kwargs) -> HttpResponse
パラメーター
- stream
- bool
応答ペイロードがストリーミングされるかどうか。 既定値は False です。
戻り値
ネットワーク呼び出しの応答。 応答でエラー処理を行いません。
の戻り値の型 :
例外
Azure SDK for Python
フィードバック
https://aka.ms/ContentUserFeedback」を参照してください。
以下は間もなく提供いたします。2024 年を通じて、コンテンツのフィードバック メカニズムとして GitHub の issue を段階的に廃止し、新しいフィードバック システムに置き換えます。 詳細については、「フィードバックの送信と表示