azure-ai-translation-ts
microsoft/skills
Azure Translation SDK for TypeScript를 사용하여 텍스트 번역, 문자 간 전사, 언어 감지 및 일괄 문서 번역을 수행합니다.
...모든 것을 확장하십시오TypeScript용 Azure 번역 SDK
REST 스타일 클라이언트를 사용한 텍스트 및 문서 번역.
설치
# 텍스트 번역
npm install @azure-rest/ai-translation-text @azure/identity
# 문서 번역
npm install @azure-rest/ai-translation-document @azure/identity
환경 변수
TRANSLATOR_ENDPOINT=https://api.cognitive.microsofttranslator.com
TRANSLATOR_SUBSCRIPTION_KEY=<your-api-key>
TRANSLATOR_REGION=<your-region> # 예: westus, eastus
AZURE_TOKEN_CREDENTIALS=prod # 프로덕션에서 DefaultAzureCredential를 사용하는 경우에만 필요
</your-region></your-api-key>텍스트 번역 클라이언트
인증
import TextTranslationClient, { TranslatorCredential } from "@azure-rest/ai-translation-text";
// API 키 + 리전
const credential: TranslatorCredential = {
key: process.env.TRANSLATOR_SUBSCRIPTION_KEY!,
region: process.env.TRANSLATOR_REGION!,
};
const client = TextTranslationClient(process.env.TRANSLATOR_ENDPOINT!, credential);
// 또는 자격 증명만 사용 (전역 엔드포인트 사용)
const client2 = TextTranslationClient(credential);
텍스트 번역
import TextTranslationClient, { isUnexpected } from "@azure-rest/ai-translation-text";
const response = await client.path("/translate").post({
body: {
inputs: [
{
text: "Hello, how are you?",
language: "en", // 소스 (선택 사항, 자동 감지)
targets: [
{ language: "es" },
{ language: "fr" },
],
},
],
},
});
if (isUnexpected(response)) {
throw response.body.error;
}
for (const result of response.body.value) {
for (const translation of result.translations) {
console.log(`${translation.language}: ${translation.text}`);
}
}
옵션으로 번역
const response = await client.path("/translate").post({
body: {
inputs: [
{
text: "Hello world",
language: "en",
textType: "Plain", // 또는 "Html"
targets: [
{
language: "de",
profanityAction: "NoAction", // "Marked" | "Deleted"
tone: "formal", // LLM 전용
},
],
},
],
},
});
지원되는 언어 가져오기
const response = await client.path("/languages").get();
if (isUnexpected(response)) {
throw response.body.error;
}
// 번역 언어
for (const [code, lang] of Object.entries(response.body.translation || {})) {
console.log(`${code}: ${lang.name} (${lang.nativeName})`);
}
문자 전사
const response = await client.path("/transliterate").post({
body: { inputs: [{ text: "这是个测试" }] },
queryParameters: {
language: "zh-Hans",
fromScript: "Hans",
toScript: "Latn",
},
});
if (!isUnexpected(response)) {
for (const t of response.body.value) {
console.log(`${t.script}: ${t.text}`); // Latn: zhè shì gè cè shì
}
}
언어 감지
const response = await client.path("/detect").post({
body: { inputs: [{ text: "Bonjour le monde" }] },
});
if (!isUnexpected(response)) {
for (const result of response.body.value) {
console.log(`Language: ${result.language}, Score: ${result.score}`);
}
}
문서 번역 클라이언트
인증
import DocumentTranslationClient from "@azure-rest/ai-translation-document";
import { DefaultAzureCredential, ManagedIdentityCredential } from "@azure/identity";
const endpoint = "https://<translator>.cognitiveservices.azure.com";
// 로컬 개발: DefaultAzureCredential. 프로덕션: AZURE_TOKEN_CREDENTIALS=prod 또는 AZURE_TOKEN_CREDENTIALS=<specific_credential> 설정
const credential = new DefaultAzureCredential({requiredEnvVars: ["AZURE_TOKEN_CREDENTIALS"]});
// 또는 프로덕션에서 특정 자격 증명을 직접 사용:
// https://learn.microsoft.com/javascript/api/overview/azure/identity-readme?view=azure-node-latest#credential-classes 참조
// const credential = new ManagedIdentityCredential();
// TokenCredential
const client = DocumentTranslationClient(endpoint, credential);
// API 키
const client2 = DocumentTranslationClient(endpoint, { key: "<api-key>" });
</api-key></specific_credential></translator>단일 문서 번역
import DocumentTranslationClient from "@azure-rest/ai-translation-document";
import { writeFile } from "node:fs/promises";
const response = await client.path("/document:translate").post({
queryParameters: {
targetLanguage: "es",
sourceLanguage: "en", // 선택 사항
},
contentType: "multipart/form-data",
body: [
{
name: "document",
body: "Hello, this is a test document.",
filename: "test.txt",
contentType: "text/plain",
},
],
}).asNodeStream();
if (response.status === "200") {
await writeFile("translated.txt", response.body);
}
배치 문서 번역
import { ContainerSASPermissions, BlobServiceClient } from "@azure/storage-blob";
// 소스 및 대상 컨테이너에 대한 SAS URL 생성
const sourceSas = await sourceContainer.generateSasUrl({
permissions: ContainerSASPermissions.parse("rl"),
expiresOn: new Date(Date.now() + 24 * 60 * 60 * 1000),
});
const targetSas = await targetContainer.generateSasUrl({
permissions: ContainerSASPermissions.parse("rwl"),
expiresOn: new Date(Date.now() + 24 * 60 * 60 * 1000),
});
// 배치 번역 시작
const response = await client.path("/document/batches").post({
body: {
inputs: [
{
source: { sourceUrl: sourceSas },
targets: [
{ targetUrl: targetSas, language: "fr" },
],
},
],
},
});
// 헤더에서 작업 ID 가져오기
const operationId = new URL(response.headers["operation-location"])
.pathname.split("/").pop();
번역 상태 가져오기
import { isUnexpected, paginate } from "@azure-rest/ai-translation-document";
const statusResponse = await client.path("/document/batches/{id}", operationId).get();
if (!isUnexpected(statusResponse)) {
const status = statusResponse.body;
console.log(`Status: ${status.status}`);
console.log(`Total: ${status.summary.total}`);
console.log(`Success: ${status.summary.success}`);
}
// 페이지네이션으로 문서 목록
const docsResponse = await client.path("/document/batches/{id}/documents", operationId).get();
const documents = paginate(client, docsResponse);
for await (const doc of documents) {
console.log(`${doc.id}: ${doc.status}`);
}
지원되는 형식 가져오기
const response = await client.path("/document/formats").get();
if (!isUnexpected(response)) {
for (const format of response.body.value) {
console.log(`${format.format}: ${format.fileExtensions.join(", ")}`);
}
}
주요 형식
// 텍스트 번역
import type {
TranslatorCredential,
TranslatorTokenCredential,
} from "@azure-rest/ai-translation-text";
// 문서 번역
import type {
DocumentTranslateParameters,
StartTranslationDetails,
TranslationStatus,
} from "@azure-rest/ai-translation-document";
모범 사례
- 소스 자동 감지 -
language매개변수를 생략하여 자동 감지 - 배치 요청 - 효율성을 위해 한 번의 호출로 여러 텍스트 번역
- SAS 토큰 사용 - 문서 번역의 경우 시간 제한이 있는 SAS URL 사용
- 오류 처리 - body에 접근하기 전에 항상
isUnexpected(response)확인 - 지역별 엔드포인트 - 낮은 지연 시간을 위해 지역별 엔드포인트 사용
---
name: azure-ai-translation-ts
description: Translate text, transliterate between scripts, detect languages, and perform batch document translation using Azure Translation SDKs for TypeScript.
license: MIT
---
# Azure Translation SDKs for TypeScript
Text and document translation with REST-style clients.
## Installation
```bash
# Text translation
npm install @azure-rest/ai-translation-text @azure/identity
# Document translation
npm install @azure-rest/ai-translation-document @azure/identity
```
## Environment Variables
```bash
TRANSLATOR_ENDPOINT=https://api.cognitive.microsofttranslator.com
TRANSLATOR_SUBSCRIPTION_KEY=<your-api-key>
TRANSLATOR_REGION=<your-region> # e.g., westus, eastus
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
```
## Text Translation Client
### Authentication
```typescript
import TextTranslationClient, { TranslatorCredential } from "@azure-rest/ai-translation-text";
// API Key + Region
const credential: TranslatorCredential = {
key: process.env.TRANSLATOR_SUBSCRIPTION_KEY!,
region: process.env.TRANSLATOR_REGION!,
};
const client = TextTranslationClient(process.env.TRANSLATOR_ENDPOINT!, credential);
// Or just credential (uses global endpoint)
const client2 = TextTranslationClient(credential);
```
### Translate Text
```typescript
import TextTranslationClient, { isUnexpected } from "@azure-rest/ai-translation-text";
const response = await client.path("/translate").post({
body: {
inputs: [
{
text: "Hello, how are you?",
language: "en", // source (optional, auto-detect)
targets: [
{ language: "es" },
{ language: "fr" },
],
},
],
},
});
if (isUnexpected(response)) {
throw response.body.error;
}
for (const result of response.body.value) {
for (const translation of result.translations) {
console.log(`${translation.language}: ${translation.text}`);
}
}
```
### Translate with Options
```typescript
const response = await client.path("/translate").post({
body: {
inputs: [
{
text: "Hello world",
language: "en",
textType: "Plain", // or "Html"
targets: [
{
language: "de",
profanityAction: "NoAction", // "Marked" | "Deleted"
tone: "formal", // LLM-specific
},
],
},
],
},
});
```
### Get Supported Languages
```typescript
const response = await client.path("/languages").get();
if (isUnexpected(response)) {
throw response.body.error;
}
// Translation languages
for (const [code, lang] of Object.entries(response.body.translation || {})) {
console.log(`${code}: ${lang.name} (${lang.nativeName})`);
}
```
### Transliterate
```typescript
const response = await client.path("/transliterate").post({
body: { inputs: [{ text: "这是个测试" }] },
queryParameters: {
language: "zh-Hans",
fromScript: "Hans",
toScript: "Latn",
},
});
if (!isUnexpected(response)) {
for (const t of response.body.value) {
console.log(`${t.script}: ${t.text}`); // Latn: zhè shì gè cè shì
}
}
```
### Detect Language
```typescript
const response = await client.path("/detect").post({
body: { inputs: [{ text: "Bonjour le monde" }] },
});
if (!isUnexpected(response)) {
for (const result of response.body.value) {
console.log(`Language: ${result.language}, Score: ${result.score}`);
}
}
```
## Document Translation Client
### Authentication
```typescript
import DocumentTranslationClient from "@azure-rest/ai-translation-document";
import { DefaultAzureCredential, ManagedIdentityCredential } from "@azure/identity";
const endpoint = "https://<translator>.cognitiveservices.azure.com";
// Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
const credential = new DefaultAzureCredential({requiredEnvVars: ["AZURE_TOKEN_CREDENTIALS"]});
// Or use a specific credential directly in production:
// See https://learn.microsoft.com/javascript/api/overview/azure/identity-readme?view=azure-node-latest#credential-classes
// const credential = new ManagedIdentityCredential();
// TokenCredential
const client = DocumentTranslationClient(endpoint, credential);
// API Key
const client2 = DocumentTranslationClient(endpoint, { key: "<api-key>" });
```
### Single Document Translation
```typescript
import DocumentTranslationClient from "@azure-rest/ai-translation-document";
import { writeFile } from "node:fs/promises";
const response = await client.path("/document:translate").post({
queryParameters: {
targetLanguage: "es",
sourceLanguage: "en", // optional
},
contentType: "multipart/form-data",
body: [
{
name: "document",
body: "Hello, this is a test document.",
filename: "test.txt",
contentType: "text/plain",
},
],
}).asNodeStream();
if (response.status === "200") {
await writeFile("translated.txt", response.body);
}
```
### Batch Document Translation
```typescript
import { ContainerSASPermissions, BlobServiceClient } from "@azure/storage-blob";
// Generate SAS URLs for source and target containers
const sourceSas = await sourceContainer.generateSasUrl({
permissions: ContainerSASPermissions.parse("rl"),
expiresOn: new Date(Date.now() + 24 * 60 * 60 * 1000),
});
const targetSas = await targetContainer.generateSasUrl({
permissions: ContainerSASPermissions.parse("rwl"),
expiresOn: new Date(Date.now() + 24 * 60 * 60 * 1000),
});
// Start batch translation
const response = await client.path("/document/batches").post({
body: {
inputs: [
{
source: { sourceUrl: sourceSas },
targets: [
{ targetUrl: targetSas, language: "fr" },
],
},
],
},
});
// Get operation ID from header
const operationId = new URL(response.headers["operation-location"])
.pathname.split("/").pop();
```
### Get Translation Status
```typescript
import { isUnexpected, paginate } from "@azure-rest/ai-translation-document";
const statusResponse = await client.path("/document/batches/{id}", operationId).get();
if (!isUnexpected(statusResponse)) {
const status = statusResponse.body;
console.log(`Status: ${status.status}`);
console.log(`Total: ${status.summary.total}`);
console.log(`Success: ${status.summary.success}`);
}
// List documents with pagination
const docsResponse = await client.path("/document/batches/{id}/documents", operationId).get();
const documents = paginate(client, docsResponse);
for await (const doc of documents) {
console.log(`${doc.id}: ${doc.status}`);
}
```
### Get Supported Formats
```typescript
const response = await client.path("/document/formats").get();
if (!isUnexpected(response)) {
for (const format of response.body.value) {
console.log(`${format.format}: ${format.fileExtensions.join(", ")}`);
}
}
```
## Key Types
```typescript
// Text Translation
import type {
TranslatorCredential,
TranslatorTokenCredential,
} from "@azure-rest/ai-translation-text";
// Document Translation
import type {
DocumentTranslateParameters,
StartTranslationDetails,
TranslationStatus,
} from "@azure-rest/ai-translation-document";
```
## Best Practices
1. **Auto-detect source** - Omit `language` parameter to auto-detect
2. **Batch requests** - Translate multiple texts in one call for efficiency
3. **Use SAS tokens** - For document translation, use time-limited SAS URLs
4. **Handle errors** - Always check `isUnexpected(response)` before accessing body
5. **Regional endpoints** - Use regional endpoints for lower latency
모든 파일
0개 파일azure-ai-translation-ts 설치
스킬 파일을 다운로드하여 .claude/skills/ 디렉토리에 추출하세요.
ZIP 다운로드저장소를 클론하고 스킬 파일을 프로젝트에 복사하세요.
git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-typescript/skills/azure-ai-translation-ts # Copy SKILL.md to your .claude/skills/ directory
복사





집
