콘텐츠 분석

완료됨

파일의 콘텐츠를 분석하려면 Azure Content Understanding API를 사용하여 엔드포인트에 제출할 수 있습니다. 콘텐츠를 URL(인터넷에 액세스할 수 있는 위치에 호스트된 파일의 경우)으로 지정하거나 이진 파일 데이터(예: .pdf 문서, .png 이미지, .mp3 오디오 파일 또는 .mp4 비디오 파일)를 직접 업로드할 수 있습니다. 분석 요청에는 사용할 분석기가 포함됩니다.

분석은 비동기 작업입니다. 요청을 제출한 후에는 작업을 완료할 때 상태를 확인하고 결과를 검색하는 데 사용할 수 있는 작업 ID를 받게 됩니다.

예를 들어 앞에서 설명한 명함 분석기를 사용하여 스캔한 다음 명함 이미지에서 이름 및 전자 메일 주소를 추출하려고 하는 경우를 가정해 보겠습니다.

존 스미스를 위한 명함 사진.

Python SDK 사용

Content Understanding용 Python SDK(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를 사용하여 분석 요청을 직접 제출할 수도 있습니다. 클라이언트 애플리케이션은 헤더에 API 키를 전달하여 Microsoft Foundry 리소스에 대한 Content Understanding 엔드포인트에 HTTP 호출을 제출합니다.

다음 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 각각 필드, markdown 및 메타데이터가 있는 콘텐츠 개체 목록이 포함됩니다. 다음 코드는 문자열 필드 값을 추출하는 방법을 보여줍니다.

# (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