「Microsoft Translator」を使ってみました。

詳細は下記のページです。

http://www.microsofttranslator.com/Tools/

image

上記のページから下記の「Windows Azure Marketplace」の「Microsoft Translator」のページにたどり着いたので、「¥0.00」の「2000 tx/month」を購入しました。

https://datamarket.azure.com/dataset/1899a118-d202-492c-aa16-ba21c33c06cb

image

下記のページに使用法があったので、使ってみました。

http://msdn.microsoft.com/en-us/library/hh454950.aspx

コンソールアプリケーションを作成し、SOAP web service を追加。

http://api.microsofttranslator.com/V2/Soap.svc

Oimage

image

「Access Token」を取得し、メソッドを並べてみました。

using System;
using System.IO;
using System.Net;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Text;
using System.Web;
using System.Data;
using System.Linq;
 
namespace TranslationTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string uri = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";
            string clientId = "??????????";         //get it from https://datamarket.azure.com/developer/applications
            string clientSecret = "??????????";  //get it from https://datamarket.azure.com/developer/applications
            string headerValue = "";
            string request = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com", clientId, HttpUtility.UrlEncode(clientSecret));
 
            // Get an Access Token
            try
            {
                MTAccessToken mtToken = HttpPost(uri, request);
 
                // Create a header with only the access_token property of the returned token
                headerValue = "Bearer " + mtToken.access_token;
                Console.WriteLine(headerValue + "\r\n");
            }
            catch (Exception ex)
            {
                Console.WriteLine( ex.Message);
            }
 
            // Use the Access Token in a Translate() call
            try
            {
                // Add the http header
                HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty();
                httpRequestProperty.Method = "POST";
                httpRequestProperty.Headers.Add("Authorization", headerValue);
 
                // Call Translator with the header
                using (MTService.LanguageServiceClient myClient = new MTService.LanguageServiceClient())
                {
                    using (OperationContextScope scope = new OperationContextScope(myClient.InnerChannel))
                    {
                        OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
                        
                        // AddTranslation Test(辞書に単語や文章を追加します)
                        Console.WriteLine("AddTranslation Test:Press Enter");
                        Console.ReadLine();
                        
                        myClient.AddTranslation("","translate","übersetzen","en","de",1,"text/plain","general","username",null);
                        myClient.AddTranslation("", "prospex", "プロスペックス", "en", "ja", 1, "text/plain", "general", "username", null);
                        myClient.AddTranslation("", "prospex", "株式会社プロスペックス", "en", "ja", 1, "text/plain", "general", "username", null);
                        Console.WriteLine("Your translation has been added");
                        
                        Console.WriteLine("\n");
                        
                        // BreakSentences Test(文章の一文ごとの文字数を数えます)
                        Console.WriteLine("BreakSentences Test:Press Enter");
                        Console.ReadLine();
 
                        try
                        {
                            string text = "Please break up this string into sentences. I would like this string to be broken into its respective sentences. Is this possible?";
                            string from = "en";
                            int[] sentenceLengths = myClient.BreakSentences("", text, from);
                            var breakSentencesResult = "BreakSentences broke up the above sentence into " + sentenceLengths.Length + " sentences.";
                            var lengths = String.Join(",", sentenceLengths.Select(x => x.ToString()).ToArray());
                            
                            breakSentencesResult += "The lengths of the sentences are " + lengths + " characters respectively.";
                            Console.WriteLine(breakSentencesResult);
                        }
                        catch (Exception)
                        {
                            Console.WriteLine("Something unexpected has occurred. Try again later.");
                            Console.ReadLine();
                        }
 
                        Console.WriteLine("\n");
                
                // Detect Test(文章から文字コードを取得します)
                        Console.WriteLine("Detect Test:Press Enter");
                        Console.ReadLine();
 
                        string detectResult;
                        detectResult = myClient.Detect("", "I have no idea what this language may be");
                        Console.WriteLine("The detected language friendly code is: " + detectResult);
                        
                        Console.WriteLine("\n");
                
                        // GetLanguageNames Test(文字コードの名称を指定した言語で取得します)
                        Console.WriteLine("GetLanguageNames Test:Press Enter");
                        Console.ReadLine();
 
                        string[] languageCodes = { "de", "en", "fr", "ko" };
                        string[] languageNames = myClient.GetLanguageNames("", "ja", languageCodes);
 
                        for (int i = 0; i < languageNames.Length; i++)
                        {
                            Console.WriteLine("{0} = {1}", languageCodes[i], languageNames[i]);
                        }
 
                        Console.WriteLine("\n");
       
                        // GetLanguagesForTranslate Test(使用できる言語コードの配列を取得します)
                        Console.WriteLine("GetLanguageForTranslate Test:Press Enter");
                        Console.ReadLine();
 
                        string[] languagesForTranslate = myClient.GetLanguagesForTranslate("");
                        var availableLanguages = String.Join(",", languagesForTranslate.Select(x => x.ToString()).ToArray());
                        Console.WriteLine("The languages available for translation are: " + availableLanguages);
 
                        Console.WriteLine("\n");
 
                        // GetTranslations Test(AddTranslationsで保存した単語や文章を取り出します)
                        Console.WriteLine("GetTranslations Test:Press Enter");
                        Console.ReadLine();
 
                        MTService.TranslateOptions options = new MTService.TranslateOptions(); // Use the default options
 
                        options.User = "username"; // default is all
                        MTService.GetTranslationsResponse translations = myClient.GetTranslations("", "prospex", "en", "ja", 5, options);
                        string matches = "The matches are: ";
 
                        foreach (MTService.TranslationMatch translationMatch in translations.Translations)
                        {
                            matches += "\"" + translationMatch.TranslatedText + "\"";
                        }
                        Console.WriteLine(matches);
                        
                        Console.WriteLine("\n");
 
                        // Translate Test
                        Console.WriteLine("Translate Test:Press Enter");
                        Console.ReadLine();
 
                        string input;
                        
                        while(true)
                        {
                            Console.WriteLine("Please input Japanese(or press Enter):");
                            input = Console.ReadLine();
                            if (input == "") break;
                            Console.WriteLine(myClient.Translate("", input, "ja", "en", "text/html", null) + "(" + input.Length + ")");
                            Console.WriteLine("\n");
                        }
 
                        Console.WriteLine("\n");
 
                        // TranslateArray Test
                        Console.WriteLine("TranslateArray Test:Press Enter");
                        Console.ReadLine();
 
                        string[] texts = new string[2];
 
                        options = new MTService.TranslateOptions(); // Use the default options
 
                        while (true)
                        {
                            Console.WriteLine("Please input Japanese subject(or press Enter):");
                            texts[0] = Console.ReadLine();
                            if (texts[0] == "") break;
                            Console.WriteLine("Please input Japanese body(or press Enter):");
                            texts[1] = Console.ReadLine();
                            if (texts[1] == "") break;
 
                            MTService.TranslateArrayResponse[] translatedTexts = myClient.TranslateArray("", texts, "ja", "en", options);
 
                            Console.WriteLine("\n");
                            Console.WriteLine("Subject:" + translatedTexts[0].TranslatedText + "(" + texts[0].Length + ")");
                            Console.WriteLine("Body:" + translatedTexts[1].TranslatedText + "(" + texts[1].Length + ")");
                            Console.WriteLine("\n");
                        }
 
                        Console.WriteLine("\n");
                        
                        Console.WriteLine("End:Press Enter");
                        Console.ReadLine();
                    }
                }   
            }
            catch (Exception ex)
            {
                Console.WriteLine( ex.StackTrace);
                Console.WriteLine( ex.Message);
                Console.ReadLine();
            }            
        }
 
        [DataContract]
        public class MTAccessToken
        {
            [DataMember]
            public string access_token { get; set; }
 
            [DataMember]
            public string token_type { get; set; }
 
            [DataMember]
            public string expires_in { get; set; }
 
            [DataMember]
            public string scope { get; set; }
        }
 
        private static MTAccessToken HttpPost(string uri, string parameters)
        {
            WebRequest webRequest = WebRequest.Create(uri);
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.Method = "POST";
 
            byte[] bytes = Encoding.ASCII.GetBytes(parameters);
            Stream os = null;
 
            try
            { 
                webRequest.ContentLength = bytes.Length;
                os = webRequest.GetRequestStream();
                os.Write(bytes, 0, bytes.Length);         
            }
            catch (WebException ex)
            {
                Console.WriteLine(ex.Message, "HttpPost: Request error");
                Console.ReadLine();
            }
            finally
            {
                if (os != null)
                {
                    os.Close();
                }
            }
 
            try
            { 
                // get the response
                WebResponse webResponse = webRequest.GetResponse();
 
                if (webResponse == null)return null;
 
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(MTAccessToken));
                MTAccessToken token = (MTAccessToken)serializer.ReadObject(webResponse.GetResponseStream());
 
                return token;
            }
            catch (WebException ex)
            {
                Console.WriteLine(ex.Message, "HttpPost: Response error");
                Console.ReadLine();
            }
            return null;
        }
    }
}
 

上記の「clientId」と「clientSecret」は、下記のページで登録する必要があるようなので、登録しました。(コードの「??????????」の部分です)

https://datamarket.azure.com/developer/applications

image 

あと、各メソッドの第一引数は空文字にしておくそうです。(Bing デベロッパーセンターでAppIDを登録した場合に使用するそうです)

できました。

image

「私は犬っぽい人です。」と入力すると、「I'm like a dog person.」と翻訳してくれました。

あと、個人的にはSpeakメソッドが気になるんだが……今日はここまで。