Google Translate For The Win

Okay, it doesn't get you perfect contextual translations, but its awesome to be able to batch translate all your strings and see your application working in a different language with something approximating real data.

You get to see font issues, and see where string manipulation is not going to work for multiple languages (and where you forget to send your UI data through the correct localization code paths!).

Here's some example c# code using their paid servive (very easy to sign up and get an account, very reasonable/ neglible price per word).

 string key = "MySecretKeyGoogleGaveMe";
            string url = string.Format(@"https://www.googleapis.com/language/translate/v2?key={0}&source={1}&target={2}&q={3}",
                                       key, fromCulture, toCulture, HttpUtility.UrlEncode(textToTranslate));

Cultures are simple strings like "es" or "en".

            // Retrieve Translation with HTTP GET call
            string jsonData = null;
            try
            {
                WebClient web = new WebClient();
                web.Encoding = Encoding.UTF8;
                jsonData = web.DownloadString(url);
            }

The response is a json object. I use Newtonsoft's Json serializer a lot in C#

TranslateResponse response = JsonConvert.DeserializeObject<TranslateResponse>(jsonData);

Where TranslateResponse looks like this:
        [JsonObject(MemberSerialization.OptOut)]
        public class Translation
        {
            public string translatedText = "";
        }

        [JsonObject(MemberSerialization.OptOut)]
        public class TranslationData
        {
            public List<Translation> translations = new List<Translation>();
        }

This gets you your data in a nice structure and here's the final output (the HtmlDecode gets rid of character codes from your resultant strings):

string result = response.data.translations[0].translatedText;
return = WebUtility.HtmlDecode(result);

Really not too tricky. In my case I added a little local cache to avoid hitting their servers too much.

Even gets you Japenese, though their dictionary seems thinner on the ground there than the core European languages and its difficult for me to tell if any of the strings returned 

At some-point I was thinking of a cross translation verify between all the different language cache's I've built up - for interest more than anything else.

Comments

  1. Wow! Thank you! I constantly wanted to write on my site something like that. Can I take a portion of your post to my website? Best language translation services service provider.

    ReplyDelete

Post a Comment

Popular Posts