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

텍스트 번역은 신경망 기계 번역 기술을 사용하여 지원되는 모든 언어에서 실시간으로 빠르고 정확한 원본-대상 텍스트 번역을 가능하게 하는 Translator 서비스의 클라우드 기반 REST API 기능입니다.

Python용 텍스트 번역 클라이언트 라이브러리를 사용하여 다음을 수행합니다.

  • 번역, 음역 및 사전 작업에서 지원하는 언어 목록을 반환합니다.

  • 단일 요청으로 단일 소스 언어 텍스트를 여러 대상 언어 텍스트에 렌더링합니다.

  • 원본 언어의 텍스트를 다른 스크립트의 문자로 변환합니다.

  • 원본 용어에 해당하는 단어를 대상 언어로 반환합니다.

  • 원본 용어 및 대상 용어 쌍에 대한 문법 구조 및 컨텍스트 예제를 반환합니다.

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

시작

필수 구성 요소

  • 이 패키지를 사용하려면 Python 3.7 이상이 필요합니다.
  • 기존 Translator 서비스 또는 Cognitive Services 리소스입니다.

패키지 설치

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

pip install azure-ai-translation-text

Translator 서비스 리소스 만들기

Translator 리소스 만들기에 따라 Translator 리소스를 만들 수 있습니다.

클라이언트 인증

클라이언트 라이브러리를 사용하는 서비스와의 상호 작용은 TextTranslationClient 클래스의 instance 만드는 것으로 시작합니다. API 키가 필요하거나 TokenCredential 클라이언트 개체를 인스턴스화해야 합니다. Cognitive Services를 사용하여 인증하는 방법에 대한 자세한 내용은 Translator Service에 대한 요청 인증을 참조하세요.

API 키 가져오기

Azure PortalendpointCognitive Services 리소스 또는 Translator 서비스 리소스 정보에서 및 API keyRegion 를 가져올 수 있습니다.

또는 아래 Azure CLI 코드 조각을 사용하여 Translator 서비스 리소스에서 API 키를 가져옵니다.

az cognitiveservices account keys list --resource-group <your-resource-group-name> --name <your-resource-name>

TextTranslationClient API 키 및 지역 자격 증명을 사용하여 만들기

API 키 및 지역에 대한 값이 있으면 를 만듭니다 TranslatorCredential. 이렇게 하면 새 클라이언트를 만들지 않고 API 키를 업데이트할 수 있습니다.

엔드포인트 TranslatorCredential 의 값과 를 Region사용하여 TextTranslationClient를 만들 수 있습니다.

text_translator = TextTranslationClient(credential = TranslatorCredential("<apiKey>", "<apiRegion>"));

주요 개념

TextTranslationClient

TextTranslationClient 텍스트 번역 클라이언트 라이브러리를 사용하는 개발자를 위한 기본 인터페이스입니다. 지원되는 언어 검색 또는 텍스트 번역 가져오기와 같은 특정 텍스트 번역기 사용에 액세스하기 위한 동기 및 비동기 작업을 모두 제공합니다.

입력

text 요소(string)는 Translator 서비스의 번역 모델에서 처리할 단일 입력 단위입니다. 에 대한 TextTranslationClient 작업은 단일 텍스트 요소 또는 텍스트 요소의 컬렉션을 취할 수 있습니다. 텍스트 요소 길이 제한, 최대 요청 크기 및 지원되는 텍스트 인코딩은 여기를 참조 하세요.

예제

다음 섹션에서는 위에서 만든 를 사용하여 client 여러 코드 조각을 제공하고 이 클라이언트 라이브러리에 있는 기본 기능을 다룹니다. 아래 코드 조각의 대부분은 동기 서비스 호출을 사용하지만 Python용 텍스트 번역 라이브러리 패키지는 동기 및 비동기 API를 모두 지원합니다.

지원되는 언어 가져오기

현재 Translator의 다른 작업에서 지원되는 언어 집합을 가져옵니다.

try:
    response = text_translator.get_languages()

    print(f"Number of supported languages for translate operation: {len(response.translation) if response.translation is not None else 0}")
    print(f"Number of supported languages for transliterate operation: {len(response.transliteration) if response.transliteration is not None else 0}")
    print(f"Number of supported languages for dictionary operations: {len(response.dictionary) if response.dictionary is not None else 0}")

    if response.translation is not None:
        print("Translation Languages:")
        for key, value in response.translation.items():
            print(f"{key} -- name: {value.name} ({value.native_name})")

    if response.transliteration is not None:
        print("Transliteration Languages:")
        for key, value in response.transliteration.items():
            print(f"{key} -- name: {value.name}, supported script count: {len(value.scripts)}")

    if response.dictionary is not None:
        print("Dictionary Languages:")
        for key, value in response.dictionary.items():
            print(f"{key} -- name: {value.name}, supported target languages count: {len(value.translations)}")

except HttpResponseError as exception:
    print(f"Error Code: {exception.error.code}")
    print(f"Message: {exception.error.message}")

엔드포인트 사용에 대한 샘플은 languages 여기에서 더 많은 샘플을 참조 하세요.

언어에 대한 개념적 논의는 서비스 설명서를 참조하세요.

Translate

한 요청에서 단일 소스 언어 텍스트를 여러 대상 언어 텍스트로 렌더링합니다.

try:
    source_language = "en"
    target_languages = ["cs"]
    input_text_elements = [ InputTextItem(text = "This is a test") ]

    response = text_translator.translate(content = input_text_elements, to = target_languages, from_parameter = source_language)
    translation = response[0] if response else None

    if translation:
        for translated_text in translation.translations:
            print(f"Text was translated to: '{translated_text.to}' and the result is: '{translated_text.text}'.")

except HttpResponseError as exception:
    print(f"Error Code: {exception.error.code}")
    print(f"Message: {exception.error.message}")

엔드포인트 사용에 대한 샘플은 translate 여기에서 더 많은 샘플을 참조 하세요.

번역에 대한 개념적 논의는 서비스 설명서를 참조하세요.

Transliterate

소스 언어의 문자 또는 글을 대상 언어의 해당 문자 또는 글로 변환합니다.

try:
    language = "zh-Hans"
    from_script = "Hans"
    to_script = "Latn"
    input_text_elements = [ InputTextItem(text = "这是个测试。") ]

    response = text_translator.transliterate(content = input_text_elements, language = language, from_script = from_script, to_script = to_script)
    transliteration = response[0] if response else None

    if transliteration:
        print(f"Input text was transliterated to '{transliteration.script}' script. Transliterated text: '{transliteration.text}'.")

except HttpResponseError as exception:
    print(f"Error Code: {exception.error.code}")
    print(f"Message: {exception.error.message}")

엔드포인트 사용에 대한 샘플은 transliterate 여기에서 더 많은 샘플을 참조 하세요.

음역에 대한 개념적 논의는 서비스 설명서를 참조하세요.

문장 나누기

텍스트에서 문장 경계의 위치를 식별합니다.

try:
    source_language = "zh-Hans"
    source_script = "Latn"
    input_text_elements = [ InputTextItem(text = "zhè shì gè cè shì。") ]

    response = text_translator.find_sentence_boundaries(content = input_text_elements, language = source_language, script = source_script)
    sentence_boundaries = response[0] if response else None

    if sentence_boundaries:
        detected_language = sentence_boundaries.detected_language
        if detected_language:
            print(f"Detected languages of the input text: {detected_language.language} with score: {detected_language.score}.")
        print(f"The detected sentence boundaries:")
        for boundary in sentence_boundaries.sent_len:
            print(boundary)

except HttpResponseError as exception:
    print(f"Error Code: {exception.error.code}")
    print(f"Message: {exception.error.message}")

엔드포인트 사용에 대한 샘플은 break sentence 여기에서 더 많은 샘플을 참조 하세요.

중단 문장에 대한 개념적 논의는 서비스 설명서를 참조하세요.

사전 조회

소스 용어에 해당하는 단어를 대상 언어로 반환합니다.

try:
    source_language = "en"
    target_language = "es"
    input_text_elements = [ InputTextItem(text = "fly") ]

    response = text_translator.lookup_dictionary_entries(content = input_text_elements, from_parameter = source_language, to = target_language)
    dictionary_entry = response[0] if response else None

    if dictionary_entry:
        print(f"For the given input {len(dictionary_entry.translations)} entries were found in the dictionary.")
        print(f"First entry: '{dictionary_entry.translations[0].display_target}', confidence: {dictionary_entry.translations[0].confidence}.")

except HttpResponseError as exception:
    print(f"Error Code: {exception.error.code}")
    print(f"Message: {exception.error.message}")

엔드포인트 사용에 대한 샘플은 dictionary lookup 여기에서 더 많은 샘플을 참조 하세요.

사전 조회에 대한 개념적 논의는 서비스 설명서를 참조하세요.

사전 예제

원본 용어 및 대상 용어 쌍에 대한 문법 구조 및 컨텍스트 예제를 반환합니다.

from azure.ai.translation.text.models import DictionaryExampleTextItem

try:
    source_language = "en"
    target_language = "es"
    input_text_elements = [ DictionaryExampleTextItem(text = "fly", translation = "volar") ]

    response = text_translator.lookup_dictionary_examples(content = input_text_elements, from_parameter = source_language, to = target_language)
    dictionary_entry = response[0] if response else None

    if dictionary_entry:
        print(f"For the given input {len(dictionary_entry.examples)} entries were found in the dictionary.")
        print(f"First example: '{dictionary_entry.examples[0].target_prefix}{dictionary_entry.examples[0].target_term}{dictionary_entry.examples[0].target_suffix}'.")

except HttpResponseError as exception:
    print(f"Error Code: {exception.error.code}")
    print(f"Message: {exception.error.message}")

엔드포인트 사용에 대한 샘플은 dictionary examples 여기에서 더 많은 샘플을 참조 하세요.

사전 예제에 대한 개념적 논의는 서비스 설명서를 참조하세요.

문제 해결

TextTranslator 클라이언트 라이브러리를 사용하여 Translator 서비스와 상호 작용하는 경우 Translator 서비스에서 반환된 오류는 REST API 요청에 대해 반환된 동일한 HTTP 상태 코드에 해당합니다.

예를 들어 대상 번역 언어 없이 번역 요청을 제출하면 "잘못된 요청"을 400 나타내는 오류가 반환됩니다.

서비스에서 반환하는 다양한 오류 코드는 서비스 설명서에서 찾을 수 있습니다.

피드백 제공

버그가 발생하거나 제안이 있는 경우 프로젝트의 문제 섹션에 문제를 제출하세요.

다음 단계

샘플 디렉터리 아래에서 더 많은 샘플을 찾을 수 있습니다.

참여

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

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

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