JavaScript용 Azure TextTranslation REST 클라이언트 라이브러리 - 버전 1.0.0-beta.1

텍스트 번역은 인공신경망 컴퓨터 번역 기술을 사용하여 모든 지원되는 언어에서 신속하고 정확한 소스-대상 텍스트 번역을 실시간으로 제공할 수 있도록 하는 Translator 서비스의 클라우드 기반 REST API 기능입니다.

텍스트 번역 기능에서 지원되는 메서드는 다음과 같습니다.

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

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

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

탐지. 소스 코드 언어 코드와, 검색된 언어에 대해 텍스트 번역 및 음역이 지원되는지 여부를 표시하는 부울 변수를 반환합니다.

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

사전 예제 소스 용어와 대상 용어 쌍의 문법 구조와 컨텍스트 예제를 반환합니다.

이 라이브러리를 사용하려면 REST 클라이언트 문서에 크게 의존하세요.

주요 링크:

시작

현재 지원되는 환경

  • Node.js의 LTS 버전
  • Edge, Chrome, Safar 및 Firefox의 최신 버전

사전 요구 사항

  • 기존 Translator 서비스 또는 Cognitive Services 리소스입니다.

@azure-rest/ai-translation-text 패키지를 설치합니다.

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

npm install @azure-rest/ai-translation-text

Translator 서비스 리소스 만들기

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

브라우저 지원

JavaScript 번들

브라우저에서 이 클라이언트 라이브러리를 사용하려면 먼저 번들러를 사용해야 합니다. 이 작업을 수행하는 방법에 대한 자세한 내용은 번들링 설명서를 참조하세요.

클라이언트 인증

클라이언트 라이브러리를 사용하는 서비스와의 상호 작용은 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.

TranslatorCredential 값을 사용하여 TextTranslationClient를 만들 수 있습니다.

const translateCedential = new TranslatorCredential(apiKey, region);
const translationClient = TextTranslationClient(endpoint, translateCedential);

예제

다음 섹션에서는 위에서 만든 를 사용하여 client 여러 코드 조각을 제공하고 이 클라이언트 라이브러리에 있는 기본 기능을 다룹니다.

지원되는 언어 가져오기

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

const langResponse = await translationClient.path("/languages").get();

if (isUnexpected(langResponse)) {
  throw langResponse.body;
}

const languages = langResponse.body;

if (languages.translation) {
  console.log("Translated languages:");
  for (const key in languages.translation) {
    const translationLanguage = languages.translation[key];
    console.log(`${key} -- name: ${translationLanguage.name} (${translationLanguage.nativeName})`);
  }
}

if (languages.transliteration) {
  console.log("Transliteration languages:");
  for (const key in languages.transliteration) {
    const transliterationLanguage = languages.transliteration[key];
    console.log(
      `${key} -- name: ${transliterationLanguage.name} (${transliterationLanguage.nativeName})`
    );
  }
}

if (languages.dictionary) {
  console.log("Dictionary languages:");
  for (const key in languages.dictionary) {
    const dictionaryLanguage = languages.dictionary[key];
    console.log(
      `${key} -- name: ${dictionaryLanguage.name} (${dictionaryLanguage.nativeName}), supported target languages count: ${dictionaryLanguage.translations.length}`
    );
  }
}

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

Translate

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

const inputText = [{ text: "This is a test." }];
const parameters = {
  to: "cs",
  from: "en",
};
const translateResponse = await translationClient.path("/translate").post({
  body: inputText,
  queryParameters: parameters,
});

if (isUnexpected(translateResponse)) {
  throw translateResponse.body;
}

const translations = translateResponse.body;
for (const translation of translations) {
  console.log(
    `Text was translated to: '${translation?.translations[0]?.to}' and the result is: '${translation?.translations[0]?.text}'.`
  );
}

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

Transliterate

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

const inputText = [{ text: "这是个测试。" }];
const parameters = {
  language: "zh-Hans",
  fromScript: "Hans",
  toScript: "Latn",
};
const transliterateResponse = await translationClient.path("/transliterate").post({
  body: inputText,
  queryParameters: parameters,
});

if (isUnexpected(transliterateResponse)) {
  throw transliterateResponse.body;
}

const translations = transliterateResponse.body;
for (const transliteration of translations) {
  console.log(
    `Input text was transliterated to '${transliteration?.script}' script. Transliterated text: '${transliteration?.text}'.`
  );
}

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

문장 나누기

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

const inputText = [{ text: "zhè shì gè cè shì。" }];
const parameters = {
  language: "zh-Hans",
  script: "Latn",
};
const breakSentenceResponse = await translationClient.path("/breaksentence").post({
  body: inputText,
  queryParameters: parameters,
});

if (isUnexpected(breakSentenceResponse)) {
  throw breakSentenceResponse.body;
}

const breakSentences = breakSentenceResponse.body;
for (const breakSentence of breakSentences) {
  console.log(`The detected sentece boundaries: '${breakSentence?.sentLen.join(", ")}'.`);
}

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

사전 조회

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

const inputText = [{ text: "fly" }];
const parameters = {
  to: "es",
  from: "en",
};
const dictionaryResponse = await translationClient.path("/dictionary/lookup").post({
  body: inputText,
  queryParameters: parameters,
});

if (isUnexpected(dictionaryResponse)) {
  throw dictionaryResponse.body;
}

const dictionaryEntries = dictionaryResponse.body;
for (const dictionaryEntry of dictionaryEntries) {
  console.log(
    `For the given input ${dictionaryEntry?.translations?.length} entries were found in the dictionary.`
  );
  console.log(
    `First entry: '${dictionaryEntry?.translations[0]?.displayTarget}', confidence: ${dictionaryEntry?.translations[0]?.confidence}.`
  );
}

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

사전 예제

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

const inputText = [{ text: "fly", translation: "volar" }];
const parameters = {
  to: "es",
  from: "en",
};
const dictionaryResponse = await translationClient.path("/dictionary/examples").post({
  body: inputText,
  queryParameters: parameters,
});

if (isUnexpected(dictionaryResponse)) {
  throw dictionaryResponse.body;
}

const dictionaryExamples = dictionaryResponse.body;
for (const dictionaryExample of dictionaryExamples) {
  console.log(
    `For the given input ${dictionaryExample?.examples?.length} examples were found in the dictionary.`
  );
  const firstExample = dictionaryExample?.examples[0];
  console.log(
    `Example: '${firstExample.targetPrefix + firstExample.targetTerm + firstExample.targetSuffix}'.`
  );
}

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

문제 해결

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

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

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

로깅

로깅을 사용하도록 설정하면 실패에 대한 유용한 정보를 파악하는 데 도움이 될 수 있습니다. HTTP 요청 및 응답 로그를 보려면 AZURE_LOG_LEVEL 환경 변수를 info로 설정합니다. 또는 @azure/logger에서 setLogLevel을 호출하여 런타임에 로깅을 사용하도록 설정할 수 있습니다.

const { setLogLevel } = require("@azure/logger");

setLogLevel("info");

로그를 사용하는 방법에 대한 자세한 내용은 @azure/logger package docs를 참조하세요.