コンテンツの分析

完了

ヒント

詳細については、「 テキストと画像 」タブを参照してください。

ファイルの内容を分析するには、Azure Content Understanding API を使用してエンドポイントに送信できます。 コンテンツを URL (インターネットにアクセスできる場所でホストされているファイルの場合) として指定したり、バイナリ ファイル データ (.pdf ドキュメント、.png イメージ、.mp3 オーディオ ファイル、.mp4 ビデオ ファイルなど) を直接アップロードしたりできます。 分析要求には、使用するアナライザーが含まれます。

分析は非同期操作です。 要求を送信すると、操作 ID を受け取ります。この ID を使用すると、操作が完了したときに状態を確認し、結果を取得できます。

たとえば、前に説明した名刺アナライザーを使用して、次のスキャンされた名刺画像から名前とメール アドレスを抽出するとします。

John Smith の名刺の写真。

Python SDK の使用

Python SDK for Content Understanding (azure-ai-contentunderstanding) は、サービスとの対話を簡略化する ContentUnderstandingClient クラスを提供します。 SDK は、非同期操作の認証、要求の書式設定、自動ポーリングを処理します。

次の Python コードでは、SDK を使用して分析用の名刺を送信し、結果を取得します。

from azure.ai.contentunderstanding import ContentUnderstandingClient
from azure.ai.contentunderstanding.models import AnalysisInput
from azure.core.credentials import AzureKeyCredential

# Authenticate the client
endpoint = "<YOUR_ENDPOINT>"
credential = AzureKeyCredential("<YOUR_API_KEY>")
client = ContentUnderstandingClient(endpoint=endpoint, credential=credential)

# Analyze the business card using the custom analyzer
analyzer_name = "business_card_analyser"
poller = client.begin_analyze(
    analyzer_id=analyzer_name,
    inputs=[AnalysisInput(url="https://host.com/business-card.png")]
)

# Wait for the operation to complete and get the results
result = poller.result()

# Extract field values from the results
content = result.contents[0]
if content.fields:
    for field_name, field_data in content.fields.items():
        if field_data.type == "string":
            print(f"{field_name}: {field_data.value}")

ヒント

SDK の begin_analyze メソッドは、ポーリング オブジェクトを返します。 ポーリングプログラムで .result() を呼び出すと、操作が完了するまでポーリングが自動的に処理されるため、独自のポーリング ループを記述する必要はありません。

REST API の使用

REST API を使用して直接分析要求を送信することもできます。 クライアント アプリケーションは、Microsoft Foundry リソースの Content Understanding エンドポイントに HTTP 呼び出しを送信し、ヘッダーに API キーを渡します。

次の Python コードは、URL を使用して分析の要求を送信し、操作が完了して結果が返されるまでサービスをポーリングします。

import json
import requests

## Use a POST request to submit the file URL to the analyzer
analyzer_name = "business_card_analyser"

headers = {
        "Ocp-Apim-Subscription-Key": "<YOUR_API_KEY>",
        "Content-Type": "application/json"}

url = f"{<YOUR_ENDPOINT>}/contentunderstanding/analyzers/{analyzer_name}:analyze?api-version=2025-11-01"

request_body = {
    "inputs": [
        {
            "url": "https://host.com/business-card.png"
        }
    ]
}

response = requests.post(url, headers=headers, json=request_body)

# Get the response and extract the ID assigned to the analysis operation
response_json = response.json()
id_value = response_json.get("id")

# Use a GET request to check the status of the analysis operation
result_url = f"{<YOUR_ENDPOINT>}/contentunderstanding/analyzerResults/{id_value}?api-version=2025-11-01"

result_response = requests.get(result_url, headers=headers)

# Keep polling until the analysis is complete
status = result_response.json().get("status")
while status == "Running":
        result_response = requests.get(result_url, headers=headers)
        status = result_response.json().get("status")

# Get the analysis results
if status == "Succeeded":
    result_json = result_response.json()


次に示すように、コンテンツ ファイルの場所の URL を指定できます。 バイナリ ファイル データを直接送信するには、代わりに analyzeBinary 操作を使用します。

分析結果の処理

結果は次の条件に依存します。

  • アナライザーが分析するように設計されているコンテンツの種類 (ドキュメント、ビデオ、画像、オーディオなど)。
  • アナライザーのスキーマ。
  • 分析されたファイルの内容。

たとえば、前に説明した名刺を分析するときの ドキュメント ベースの名刺アナライザーからの応答には、次のものが含まれます。

  • 抽出されたフィールド
  • 各ページ上のテキスト行、個々の単語、段落の位置を含む、ドキュメントの光学式文字認識 (OCR) レイアウト。

Python SDK の使用

SDK を使用する場合、 AnalysisResult オブジェクトは、結果への型指定されたアクセスを提供します。 contents プロパティには、フィールド、マークダウン、およびメタデータを含むコンテンツ オブジェクトの一覧が含まれています。 次のコードは、文字列フィールド値を抽出する方法を示しています。

# (continued from previous SDK code example)

content = result.contents[0]
if content.fields:
    for field_name, field_data in content.fields.items():
        if field_data.type == "string":
            print(f"{field_name}: {field_data.value}")

REST API の使用

REST API を使用する場合、応答はアプリケーションが解析する必要がある JSON ペイロードです。 名刺分析の完全な JSON 応答を次に示します。

{
    "id": "00000000-0000-0000-0000-a00000000000",
    "status": "Succeeded",
    "result": {
        "analyzerId": "biz_card_analyser_2",
        "apiVersion": "2025-11-01",
        "createdAt": "2025-05-16T03:51:46Z",
        "warnings": [],
        "contents": [
            {
                "markdown": "John Smith\nEmail: john@contoso.com\n",
                "fields": {
                    "ContactName": {
                        "type": "string",
                        "valueString": "John Smith",
                        "spans": [
                            {
                                "offset": 0,
                                "length": 10
                            }
                        ],
                        "confidence": 0.994,
                        "source": "D(1,69,234,333,234,333,283,69,283)"
                    },
                    "EmailAddress": {
                        "type": "string",
                        "valueString": "john@contoso.com",
                        "spans": [
                            {
                                "offset": 18,
                                "length": 16
                            }
                        ],
                        "confidence": 0.998,
                        "source": "D(1,179,309,458,309,458,341,179,341)"
                    }
                },
                "kind": "document",
                "startPageNumber": 1,
                "endPageNumber": 1,
                "unit": "pixel",
                "pages": [
                    {
                        "pageNumber": 1,
                        "angle": 0.03410444,
                        "width": 1000,
                        "height": 620,
                        "spans": [
                            {
                                "offset": 0,
                                "length": 35
                            }
                        ],
                        "words": [
                            {
                                "content": "John",
                                "span": {
                                    "offset": 0,
                                    "length": 4
                                },
                                "confidence": 0.992,
                                "source": "D(1,69,234,181,234,180,283,69,283)"
                            },
                            {
                                "content": "Smith",
                                "span": {
                                    "offset": 5,
                                    "length": 5
                                },
                                "confidence": 0.998,
                                "source": "D(1,200,234,333,234,333,282,200,283)"
                            },
                            {
                                "content": "Email:",
                                "span": {
                                    "offset": 11,
                                    "length": 6
                                },
                                "confidence": 0.995,
                                "source": "D(1,75,310,165,309,165,340,75,340)"
                            },
                            {
                                "content": "john@contoso.com",
                                "span": {
                                    "offset": 18,
                                    "length": 16
                                },
                                "confidence": 0.977,
                                "source": "D(1,179,309,458,311,458,340,179,341)"
                            }
                        ],
                        "lines": [
                            {
                                "content": "John Smith",
                                "source": "D(1,69,234,333,233,333,282,69,282)",
                                "span": {
                                    "offset": 0,
                                    "length": 10
                                }
                            },
                            {
                                "content": "Email: john@contoso.com",
                                "source": "D(1,75,309,458,309,458,340,75,340)",
                                "span": {
                                    "offset": 11,
                                    "length": 23
                                }
                            }
                        ]
                    }
                ],
                "paragraphs": [
                    {
                        "content": "John Smith Email: john@contoso.com",
                        "source": "D(1,69,233,458,233,458,340,69,340)",
                        "span": {
                            "offset": 0,
                            "length": 34
                        }
                    }
                ],
                "sections": [
                    {
                        "span": {
                            "offset": 0,
                            "length": 34
                        },
                        "elements": [
                            "/paragraphs/0"
                        ]
                    }
                ]
            }
        ]
    }
}

通常、アプリケーションは JSON を解析してフィールド値を取得する必要があります。 たとえば、次の Python コードでは、すべての 文字列 値が抽出されます。

# (continued from previous code example)

# Iterate through the fields and extract the names and type-specific values
contents = result_json["result"]["contents"]
for content in contents:
    if "fields" in content:
        fields = content["fields"]
        for field_name, field_data in fields.items():
            if field_data['type'] == "string":
                print(f"{field_name}: {field_data['valueString']}")

このコードからの出力を次に示します。

ContactName: John Smith
EmailAddress: john@contoso.com