Python용 Azure Document Translation 클라이언트 라이브러리 - 버전 1.0.0

Azure Cognitive Services 문서 번역은 원본 문서 구조와 데이터 형식을 유지하면서 언어 및 방언 간에 여러 복잡한 문서를 번역하는 데 사용할 수 있는 클라우드 서비스입니다. 문서 번역용 클라이언트 라이브러리를 사용하여 다음을 수행합니다.

  • 다양한 대용량 파일을 Azure Blob Storage 컨테이너에서 원하는 언어로 대상 컨테이너로 번역합니다.
  • 번역 작업에서 각 문서의 번역 상태 및 진행률을 확인합니다.
  • 사용자 지정 번역 모델 또는 용어집을 적용하여 특정 사례에 맞게 번역을 조정합니다.

소스 코드 | 패키지(PyPI) | API 참조 설명서 | 제품 설명서 | 샘플

고지 사항

Python 2.7에 대한 Azure SDK Python 패키지 지원은 2022년 1월 1일에 종료되었습니다. 자세한 내용과 질문은 다음을 참조하세요. https://github.com/Azure/azure-sdk-for-python/issues/20691

시작

필수 조건

  • 이 패키지를 사용하려면 Python 3.6 이상이 필요합니다.
  • 이 패키지를 사용하려면 Azure 구독Translator 리소스 가 있어야 합니다.

패키지 설치

pip를 사용하여 Python용 Azure Document Translation 클라이언트 라이브러리를 설치합니다.

pip install azure-ai-translation-document

참고: 이 버전의 클라이언트 라이브러리는 기본적으로 v1.0 버전의 서비스로 설정됩니다.

Translator 리소스 만들기

문서 번역 기능은 단일 서비스 액세스 만 지원합니다. 서비스에 액세스하려면 Translator 리소스를 만듭니다.

를 사용하여 리소스를 만들 수 있습니다.

옵션 1:Azure Portal

옵션 2:Azure CLI. 다음은 CLI를 사용하여 Translator 리소스를 만드는 방법의 예입니다.

# Create a new resource group to hold the Translator resource -
# if using an existing resource group, skip this step
az group create --name my-resource-group --location westus2
# Create document translation
az cognitiveservices account create \
    --name document-translation-resource \
    --custom-domain document-translation-resource \
    --resource-group my-resource-group \
    --kind TextTranslation \
    --sku S1 \
    --location westus2 \
    --yes

클라이언트 인증

문서 번역 기능 서비스와 상호 작용하려면 클라이언트의 인스턴스를 만들어야 합니다. 클라이언트 개체를 인스턴스화하려면 엔드포인트자격 증명 이 필요합니다.

엔드포인트 조회

Azure Portal을 사용하여 Translator 리소스에 대한 엔드포인트를 찾을 수 있습니다.

서비스에는 사용자 지정 도메인 엔드포인트가 필요합니다. 위의 링크의 지침에 따라 엔드포인트의 서식을 지정합니다. https://{NAME-OF-YOUR-RESOURCE}.cognitiveservices.azure.com/

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.translation.document import DocumentTranslationClient

endpoint = "https://<resource-name>.cognitiveservices.azure.com/"
credential = AzureKeyCredential("<api_key>")
document_translation_client = DocumentTranslationClient(endpoint, credential)

Azure Active Directory 자격 증명을 사용하여 클라이언트 만들기

AzureKeyCredential 인증은 이 시작 가이드의 예제에서 사용되지만 azure-identity 라이브러리를 사용하여 Azure Active Directory로 인증할 수도 있습니다.

아래에 표시된 DefaultAzureCredential 형식 또는 Azure SDK와 함께 제공되는 다른 자격 증명 형식을 사용하려면 패키지를 설치 azure-identity 하세요.

pip install azure-identity

또한 서비스 주체에 역할을 할당하여 새 AAD 애플리케이션"Cognitive Services User" 등록하고 Translator 리소스에 대한 액세스 권한을 부여해야 합니다.

완료되면 AAD 애플리케이션의 클라이언트 ID, 테넌트 ID 및 클라이언트 암호 값을 환경 변수로 설정합니다. AZURE_CLIENT_ID, , AZURE_TENANT_IDAZURE_CLIENT_SECRET.

from azure.identity import DefaultAzureCredential
from azure.ai.translation.document import DocumentTranslationClient
credential = DefaultAzureCredential()

document_translation_client = DocumentTranslationClient(
    endpoint="https://<resource-name>.cognitiveservices.azure.com/",
    credential=credential
)

주요 개념

문서 번역 서비스를 사용하려면 파일을 Azure Blob Storage 원본 컨테이너에 업로드하고 번역된 문서를 쓸 수 있는 대상 컨테이너를 제공해야 합니다. 이 설정에 대한 추가 정보는 서비스 설명서에서 찾을 수 있습니다.

DocumentTranslationClient

문서 번역 클라이언트 라이브러리와의 상호 작용은 의 DocumentTranslationClient인스턴스로 시작합니다. 클라이언트는 다음에 대한 작업을 제공합니다.

  • 원본 컨테이너에서 문서를 번역하고 대상 컨테이너에 결과를 쓰는 번역 작업을 만듭니다.
  • 번역 작업에서 개별 문서의 상태를 확인하고 각 문서의 진행률을 모니터링합니다.
  • 모든 과거 및 현재 번역 작업을 열거합니다.
  • 지원되는 용어집 및 문서 형식 식별

번역 입력

클라이언트 메서드에 대한 입력은 begin_translation 두 가지 방법으로 제공할 수 있습니다.

  1. 문서가 있는 단일 원본 컨테이너를 다른 언어로 번역할 수 있습니다.
from azure.core.credentials import AzureKeyCredential
from azure.ai.translation.document import DocumentTranslationClient

document_translation_client = DocumentTranslationClient("<endpoint>", AzureKeyCredential("<api_key>"))
poller = document_translation_client.begin_translation("<sas_url_to_source>", "<sas_url_to_target>", "<target_language>")
  1. 또는 각각 고유한 대상으로 여러 원본을 제공할 수 있습니다.
from azure.core.credentials import AzureKeyCredential
from azure.ai.translation.document import DocumentTranslationClient, DocumentTranslationInput, TranslationTarget

my_input = [
    DocumentTranslationInput(
        source_url="<sas_url_to_source_A>",
        targets=[
            TranslationTarget(target_url="<sas_url_to_target_fr>", language="fr"),
            TranslationTarget(target_url="<sas_url_to_target_de>", language="de")
        ]
    ),
    DocumentTranslationInput(
        source_url="<sas_url_to_source_B>",
        targets=[
            TranslationTarget(target_url="<sas_url_to_target_fr>", language="fr"),
            TranslationTarget(target_url="<sas_url_to_target_de>", language="de")
        ]
    ),
    DocumentTranslationInput(
        source_url="<sas_url_to_source_C>",
        targets=[
            TranslationTarget(target_url="<sas_url_to_target_fr>", language="fr"),
            TranslationTarget(target_url="<sas_url_to_target_de>", language="de")
        ]
    )
]

document_translation_client = DocumentTranslationClient("<endpoint>", AzureKeyCredential("<api_key>"))
poller = document_translation_client.begin_translation(my_input)

참고: 각 대상 언어의 target_url 고유해야 합니다.

폴더 아래에서 문서를 번역하거나 특정 문서만 번역하려면 sample_begin_translation_with_filters.py를 참조하세요. 지원되는 모든 언어에 대한 서비스 설명서를 참조하세요.

Long-Running 작업

장기 실행 작업은 작업을 시작하기 위해 서비스에 전송된 초기 요청으로 구성된 작업이며, 그 다음에는 간격으로 서비스를 폴링하여 작업이 완료되었는지 또는 실패했는지, 그리고 성공했는지 여부를 확인하여 결과를 가져옵니다.

문서를 번역하는 메서드는 장기 실행 작업으로 모델링됩니다. 클라이언트는 또는 AsyncDocumentTranslationLROPollerbegin_<method-name> 반환하는 메서드를 DocumentTranslationLROPoller 노출합니다. 호출자는 메서드에서 begin_<method-name> 반환된 폴러 개체를 호출 result() 하여 작업이 완료되기를 기다려야 합니다. 샘플 코드 조각은 아래의 장기 실행 작업 를 사용하여 설명하기 위해 제공됩니다.

예제

다음 섹션에서는 다음을 포함하여 가장 일반적인 문서 번역 작업 중 일부를 다루는 몇 가지 코드 조각을 제공합니다.

문서 번역

원본 컨테이너의 모든 문서를 대상 컨테이너로 변환합니다. 폴더 아래에서 문서를 번역하거나 특정 문서만 번역하려면 sample_begin_translation_with_filters.py를 참조하세요.

from azure.core.credentials import AzureKeyCredential
from azure.ai.translation.document import DocumentTranslationClient

endpoint = "https://<resource-name>.cognitiveservices.azure.com/"
credential = AzureKeyCredential("<api_key>")
source_container_sas_url_en = "<sas-url-en>"
target_container_sas_url_es = "<sas-url-es>"

document_translation_client = DocumentTranslationClient(endpoint, credential)

poller = document_translation_client.begin_translation(source_container_sas_url_en, target_container_sas_url_es, "es")

result = poller.result()

print(f"Status: {poller.status()}")
print(f"Created on: {poller.details.created_on}")
print(f"Last updated on: {poller.details.last_updated_on}")
print(f"Total number of translations on documents: {poller.details.documents_total_count}")

print("\nOf total documents...")
print(f"{poller.details.documents_failed_count} failed")
print(f"{poller.details.documents_succeeded_count} succeeded")

for document in result:
    print(f"Document ID: {document.id}")
    print(f"Document status: {document.status}")
    if document.status == "Succeeded":
        print(f"Source document location: {document.source_document_url}")
        print(f"Translated document location: {document.translated_document_url}")
        print(f"Translated to language: {document.translated_to}\n")
    else:
        print(f"Error Code: {document.error.code}, Message: {document.error.message}\n")

여러 입력 번역

여러 원본 컨테이너의 문서로 다른 언어의 여러 대상 컨테이너로 번역을 시작합니다.

from azure.core.credentials import AzureKeyCredential
from azure.ai.translation.document import DocumentTranslationClient, DocumentTranslationInput, TranslationTarget

endpoint = "https://<resource-name>.cognitiveservices.azure.com/"
credential = AzureKeyCredential("<api_key>")
source_container_sas_url_de = "<sas-url-de>"
source_container_sas_url_en = "<sas-url-en>"
target_container_sas_url_es = "<sas-url-es>"
target_container_sas_url_fr = "<sas-url-fr>"
target_container_sas_url_ar = "<sas-url-ar>"

document_translation_client = DocumentTranslationClient(endpoint, credential)

poller = document_translation_client.begin_translation(
    [
        DocumentTranslationInput(
            source_url=source_container_sas_url_en,
            targets=[
                TranslationTarget(target_url=target_container_sas_url_es, language="es"),
                TranslationTarget(target_url=target_container_sas_url_fr, language="fr"),
            ],
        ),
        DocumentTranslationInput(
            source_url=source_container_sas_url_de,
            targets=[
                TranslationTarget(target_url=target_container_sas_url_ar, language="ar"),
            ],
        )
    ]
)

result = poller.result()

for document in result:
    print(f"Document ID: {document.id}")
    print(f"Document status: {document.status}")
    if document.status == "Succeeded":
        print(f"Source document location: {document.source_document_url}")
        print(f"Translated document location: {document.translated_document_url}")
        print(f"Translated to language: {document.translated_to}\n")
    else:
        print(f"Error Code: {document.error.code}, Message: {document.error.message}\n")

번역 작업 나열

리소스에 대해 제출된 번역 작업을 열거합니다.

from azure.core.credentials import AzureKeyCredential
from azure.ai.translation.document import DocumentTranslationClient

endpoint = "https://<resource-name>.cognitiveservices.azure.com/"
credential = AzureKeyCredential("<api_key>")

document_translation_client = DocumentTranslationClient(endpoint, credential)

operations = document_translation_client.list_translation_statuses()  # type: ItemPaged[TranslationStatus]

for operation in operations:
    print(f"\nID: {operation.id}")
    print(f"Status: {operation.status}")
    print(f"Created on: {operation.created_on}")
    print(f"Last updated on: {operation.last_updated_on}")
    print(f"Total number of translations on documents: {operation.documents_total_count}")
    print(f"Total number of characters charged: {operation.total_characters_charged}")

    print("Of total documents...")
    print(f"{operation.documents_failed_count} failed")
    print(f"{operation.documents_succeeded_count} succeeded")
    print(f"{operation.documents_canceled_count} canceled")

Azure Storage Blob에서 문서 번역 클라이언트 라이브러리를 사용하여 문서를 업로드하고, 컨테이너에 대한 SAS 토큰을 만들고, 완성된 번역된 문서를 다운로드하는 방법을 보려면 이 샘플을 참조하세요. 이 샘플을 실행하려면 azure-storage-blob 라이브러리를 설치해야 합니다.

고급 항목

다음 섹션에서는 용어집 및 사용자 지정 번역 모델과 같은 일부 고급 번역 기능에 대한 몇 가지 인사이트를 제공합니다.

용어집

용어집은 도메인별 사전입니다. 예를 들어 일부 의료 관련 문서를 번역하려는 경우 표준 번역 사전에서 찾을 수 없는 의료 분야의 많은 단어, 용어 및 관용구에 대한 지원이 필요하거나 특정 번역이 필요할 수 있습니다. 이것이 문서 번역이 용어집을 지원하는 이유입니다.

용어집 파일을 만드는 방법

문서 번역은 다음 형식의 용어집을 지원합니다.

파일 형식 내선 번호 설명 샘플
탭으로 구분된 값/TAB .tsv, .tab 위키백과에 대해 자세히 알아보기 glossary_sample.tsv
쉼표로 구분된 값 .csv 위키백과에 대해 자세히 알아보기 glossary_sample.csv
지역화 교환 파일 형식 .xlf, .xliff 위키백과에 대해 자세히 알아보기 glossary_sample.xlf

여기에서 지원되는 모든 형식을 봅니 .

문서 번역에서 용어집을 사용하는 방법

문서 번역에서 용어집을 사용하려면 먼저 용어집 파일을 Blob 컨테이너에 업로드한 다음 코드 샘플 sample_translation_with_glossaries.py와 같이 파일에 SAS URL을 제공해야 합니다.

사용자 지정 번역 모델

번역에 문서 번역 엔진을 사용하는 대신 사용자 지정 Azure 기계/딥 러닝 모델을 사용할 수 있습니다.

사용자 지정 번역 모델을 만드는 방법

사용자 고유의 사용자 지정 Azure 번역 모델을 만들고, 프로비전하고, 배포하는 방법에 대한 자세한 내용은 번역을 위해 사용자 지정 모델 빌드, 배포 및 사용의 지침을 따르세요.

문서 번역과 함께 사용자 지정 번역 모델을 사용하는 방법

문서 번역에서 사용자 지정 번역 모델을 사용하려면 먼저 모델을 만들고 배포한 다음 코드 샘플 sample_translation_with_custom_model.py 에 따라 문서 번역과 함께 사용해야 합니다.

문제 해결

일반

문서 번역 클라이언트 라이브러리는 Azure Core에 정의된 예외를 발생합니다.

로깅

이 라이브러리는 로깅에 표준 로깅 라이브러리를 사용합니다.

HTTP 세션(URL, 헤더 등)에 대한 기본 정보는 수준에서 기록됩니다 INFO .

DEBUG 요청/응답 본문 및 수정되지 않은 헤더를 포함한 자세한 수준 로깅은 클라이언트 또는 키워드 인수를 사용하여 작업 logging_enable 별로 사용하도록 설정할 수 있습니다.

여기에 예제가 포함된 전체 SDK 로깅 설명서를 참조 하세요.

선택적 구성

선택적 키워드 인수는 클라이언트 및 작업별 수준에서 전달할 수 있습니다. azure-core 참조 설명서 에서는 재시도, 로깅, 전송 프로토콜 등에 사용할 수 있는 구성에 대해 설명합니다.

다음 단계

다음 섹션에서는 문서 번역 Python 클라이언트 라이브러리에 사용되는 일반적인 패턴을 보여 주는 몇 가지 코드 조각을 제공합니다. 샘플 디렉터리 아래에서 더 많은 샘플을 찾을 수 있습니다.

추가 샘플 코드

이러한 코드 샘플은 Azure Document Translation 클라이언트 라이브러리를 사용하는 일반적인 시나리오 작업을 보여 줍니다.

비동기 샘플

이 라이브러리에는 전체 비동기 API 집합도 포함되어 있습니다. 이를 사용하려면 먼저 aiohttp와 같은 비동기 전송을 설치해야 합니다. 비동기 클라이언트는 네임스페이 azure.ai.translation.document.aio 스 아래에 있습니다.

추가 설명서

Azure Cognitive Services 문서 번역에 대한 자세한 설명서는 docs.microsoft.com 문서 번역 설명서를 참조하세요 .

참여

이 프로젝트에 대한 기여와 제안을 환영합니다. 대부분의 경우 기여하려면 권한을 부여하며 실제로 기여를 사용할 권한을 당사에 부여한다고 선언하는 CLA(기여자 라이선스 계약)에 동의해야 합니다. 자세한 내용은 cla.microsoft.com.

끌어오기 요청을 제출하면 CLA-bot은 CLA를 제공하고 PR을 적절하게 데코레이팅해야 하는지 여부를 자동으로 결정합니다(예: 레이블, 설명). 봇에서 제공하는 지침을 따르기만 하면 됩니다. 이 작업은 CLA를 사용하여 모든 리포지토리에서 한 번만 수행하면 됩니다.

이 프로젝트에는 Microsoft Open Source Code of Conduct(Microsoft 오픈 소스 준수 사항)가 적용됩니다. 자세한 내용은 Code of Conduct FAQ(규정 FAQ)를 참조하세요. 또는 추가 질문이나 의견은 opencode@microsoft.com으로 문의하세요.