Microsoft Translator APIを使ってみる

Microsoft Translator

とあるサイトで Google Translate API を使おうとしたら、今年から有料化していたので、同様にAPIを公開している Microsoft Translator API の使い方を紹介していきます!

無料でも 2,000,000文字/月 まで利用できるので個人で使う範囲なら問題無い。よね

Windows Azure Marketplace

Microsoft Translator API を利用するには、Windows Azure Marketplace へ登録する必要があります。

既にMicrosoftのアカウントを持っていればスムーズに登録できると思います。

Microsoft Translator API

Microsoft Translator

Microsoft Translator API の利用登録を行います。

下記のリンクからサインアップをクリックしてアプリケーションの登録を行います。

アプリケーションの登録

Microsoft_Translator_application.png

アプリケーションの情報を入力します。
登録するときには値を変更してください。リダイレクトURI は今回使用しないので適当でもおkです。

今回は、クライアントID顧客の秘密 を使用します。


 使い方

  1. アクセストークンの取得
  2. アクセストークンを渡して翻訳

Access Token

アクセストークンを取得するには
https://datamarket.accesscontrol.windows.net/v2/OAuth2-13
に以下の様なパラメータをHTTP POSTで送ればアクセストークンを取得することができます。
このアクセストークンは、有効期限が取得後10分までなので注意が必要です。

パラメータ 説明
client_id 【必須】クライアントID
client_secret 【必須】顧客の秘密
scope 【必須】http://api.microsofttranslator.com
grant_type 【必須】client_credentials

そしてこちらが返り値

{
  "token_type":"http://schemas.xmlsoap.org/ws/2009/11/swt-token-profile-1.0",
  "access_token":"http%3a%2f%2fschemas.xmlsoap.org%2fws%2f2005%2f05%2fidentity%2fclaims%2fnameidentifier...",
  "expires_in":"599",
  "scope":"http://api.microsofttranslator.com"
}

英語ですが詳しくは↓のURLから
http://msdn.microsoft.com/ja-jp/library/hh454950.aspx

翻訳

翻訳のやり方は、AJAX, HTTP, SOAP があるので、↓のURLから確認して下さい。
http://msdn.microsoft.com/ja-jp/library/ff512423.aspx

今回は Ajax で、複数語の翻訳をする例です。詳しくはこちら

リクエストURL
http://api.microsofttranslator.com/V2/Ajax.svc/TranslateArray
言語コード一覧
http://msdn.microsoft.com/ja-jp/library/hh456380.aspx
パラメータ 説明
appId 【必須】「Bearer 」+ さっきの access_token
texts 【必須】JSON形式の文字列、配列数:2000まで、文字列:10000文字まで
from 【任意】翻訳する元の言語コード、通常は自動で検出
to 【必須】翻訳する言語コード
var translate = function() {
  var from = [];

  // 適当に文字を取得
  $('h3').each(function() {
    from.push($(this).text());
  });

  // 翻訳
  $.ajax({
    type: 'post',
    url: 'http://api.microsofttranslator.com/V2/Ajax.svc/TranslateArray',
    dataType: 'jsonp',
    jsonp: 'oncomplete',
    data: {
      appId: 'Bearer http%3a%2f%2fschemas.xmlsoap.org%2fws%2f2005%2f05%2fidentity%2fclaims%2fnameidentifier...',
      texts: JSON.stringify(from),
      to: 'ja',
    }
  }).done(function(data) {
    console.log(data);
  }).fail(function(data) {
    console.log(data);
  });
}

おわり。