mcpField
A
azure-ai-translation-ts

azure-ai-translation-ts

github.com/sickn33ドキュメント48.7k68 回インストール今日更新
リポジトリ

azure-ai-translation-ts について

Azure Translation の REST スタイルクライアントでテキストやドキュメントを翻訳する TypeScript 向けスキルです。言語検出、文字変換、対応言語・形式の確認、ドキュメントの一括処理も扱います。

主な機能

  1. 01テキストとドキュメントの翻訳
  2. 02言語検出と文字変換
  3. 03対応言語と形式の確認
  4. 04一括処理と状態確認

活用シーン

  1. 01テキストを指定した言語に翻訳
  2. 02単一または複数のドキュメントを翻訳
  3. 03テキストの言語検出や文字体系の変換

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/sickn33/agentic-awesome-skills --skill azure-ai-translation-ts

インストール後、Claude Code で/azure-ai-translation-tsを入力して読み込まれたか確認します。

詳細

TypeScript 用 Azure Translation SDK

REST スタイルのクライアントを使用したテキストおよびドキュメントの翻訳です。

インストール

# Text translation
npm install @azure-rest/ai-translation-text @azure/identity

# Document translation
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>  # e.g., westus, eastus

テキスト翻訳クライアント

認証
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);
テキストを翻訳する
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}`);
  }
}
オプションを指定して翻訳する
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
          },
        ],
      },
    ],
  },
});
サポートされている言語を取得する
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})`);
}
文字を変換する
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 } from "@azure/identity";

const endpoint = "https://<translator>.cognitiveservices.azure.com";

// TokenCredential
const client = DocumentTranslationClient(endpoint, new DefaultAzureCredential());

// API Key
const client2 = DocumentTranslationClient(endpoint, { key: "<api-key>" });
単一ドキュメントの翻訳
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);
}
ドキュメントの一括翻訳
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();
翻訳ステータスを取得する
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}`);
}
サポートされている形式を取得する
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(", ")}`);
  }
}

主な型

// 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";

ベストプラクティス

  1. ソース言語を自動検出する - language パラメーターを省略すると、自動的に検出されます
  2. リクエストをまとめる - 効率化のため、1 回の呼び出しで複数のテキストを翻訳します
  3. SAS トークンを使用する - ドキュメント翻訳では、有効期間を限定した SAS URL を使用します
  4. エラーを処理する - 本文にアクセスする前に、必ず isUnexpected(response) を確認します
  5. リージョン別エンドポイントを使用する - レイテンシを抑えるため、リージョン別エンドポイントを使用します

使用する場面

このスキルは、概要で説明されているワークフローまたはアクションを実行する場合に適用できます。

制限事項

  • このスキルは、タスクが上記の説明範囲に明確に該当する場合にのみ使用してください。
  • 出力を、環境固有の検証、テスト、または専門家によるレビューの代わりとして扱わないでください。
  • 必要な入力、権限、安全性の境界、または成功基準が不足している場合は、停止して確認を求めてください。

これらのコード断片は、インストール済みの Translator パッケージ/API バージョンおよび選択したリソースのエンドポイントに適合している必要があります。ドキュメント操作のポーリングを開始する前に、レスポンスのステータスと operation-location の存在および有効性を確認してください。ポーリングには上限を設け、失敗状態やキャンセル状態を処理してください。テキスト/ドキュメントおよび SAS URL はローカル環境の外部に送信されます。その転送を許可し、範囲を限定した有効期間の短い SAS 権限を使用し、ログに記録しないでください。

コメント