Esoteric Delights
A blog dedicated to all things esoteric in the lands of programming, music, life, and other hermetic musings.

Calling Google Ajax Language API for Translation and Language Detection from C#

November 26, 2008 18:22 by Eric

I have to give Google props for creating a solid API for language detection and translation services in the cloud.  Using their free service, I've now added some cool new functionality to help people out when using the Esoteric Delights Gematria Database.  In the first panel for translation, I'm using the Google Ajax Language API to detect if someone is entering Hebrew or English into the input box, and then proposing a "feeling lucky" kind of translation.

I've wrapped this functionality inside some C# classes that allow you to consume the Google services from the server side or from non-web apps with an internet connection, and have made a code sample available for download as a Visual Studio 2005 solution here.  Calling the Google API for translation and language detection can be as simple as this in .NET:

string s = TextBoxTranslateEnglishToHebrew.Text;
string key = "YOUR GOOGLE AJAX API KEY";
GoogleLangaugeDetector detector =
   new GoogleLangaugeDetector(s, VERSION.ONE_POINT_ZERO, key);
 
GoogleTranslator gTranslator = new GoogleTranslator(s, VERSION.ONE_POINT_ZERO,
   detector.LanguageDetected.Equals("iw") ? LANGUAGE.HEBREW : LANGUAGE.ENGLISH,
   detector.LanguageDetected.Equals("iw") ? LANGUAGE.ENGLISH : LANGUAGE.HEBREW,
   key);
 
TextBoxTranslation.Text = gTranslator.Translation;

 

The code sample above takes user input (e.g., from a TextBox web control), detects the language using a custom C# implementation of the language detection provided by the Google API (in this case, if the user is entering English or Hebrew), and then gets a translation using a custom C# implementation of the translation service from Google (in this case, if Hebrew was entered, the language pair is set-up to translate from Hebrew to English, and vice versa).  The object model for the C# class implementation for the encapsulation of these two services looks like this:  

Since the Google API is provide a RESTful interface that returns JSON response streams, the basic idea is to construct a URI for an HTTP request and then deserialize the JSON response into .NET.  To do this, you need to make .NET classes that represent the classes as defined in the Google Class Reference for Translation API documentation.  You must mark these classes with the [Serializable] attribute so that you can later deserialize the JSON response using the .NET DataContractJsonSerializer class in the System.Runtime.Serialization.Json namespace.  Please note that even though I've provided a Visual Studio 2005 project for backwards compatability, this namespace is part of the .NET 3.5 Framework, so you'll have to install that if you haven't already.

Basically, you need to create a URI and send it to Google that looks like:

http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=hello%20worled&langpair=en%7ciw&key=your_google_api_key_goes_here

This tells the API that you want to translate "hello world" from English to Hebrew, to which Google's JSON response would look like:

{"responseData": {"translatedText":"שלום העולם"}, "responseDetails": null, "responseStatus": 200}

I chose to make a base class that represents a typical Google JSON response:

[Serializable]
public class JSONResponse
{
   public string responseDetails = null;
   public string responseStatus = null;
}

Then, a Translation object that inherits from this class:

[Serializable]
public class Translation: JSONResponse
{
   public TranslationResponseData responseData = 
	new TranslationResponseData();
}

This Translation class has a TranslationResponseData object that looks like this:

[Serializable]
public class TranslationResponseData
{
   public string translatedText;
}

Finally, we can make the GoogleTranslator class:

using System;

using System.Collections.Generic;

using System.Text;

 

using System.Web;

using System.Net;

using System.IO;

using System.Runtime.Serialization.Json;

 

namespace GoogleTranslationAPI

{

 

   public class GoogleTranslator

   {

      private string _q = "";

      private string _v = "";

      private string _key = "";

      private string _langPair = "";

      private string _requestUrl = "";

      private string _translation = "";

 

      public GoogleTranslator(string queryTerm, VERSION version, LANGUAGE languageFrom,

         LANGUAGE languageTo, string key)

      {

         _q = HttpUtility.UrlPathEncode(queryTerm);

         _v = HttpUtility.UrlEncode(EnumStringUtil.GetStringValue(version));

         _langPair =

            HttpUtility.UrlEncode(EnumStringUtil.GetStringValue(languageFrom) +

            "|" + EnumStringUtil.GetStringValue(languageTo));

         _key = HttpUtility.UrlEncode(key);

 

         string encodedRequestUrlFragment =

            string.Format("?v={0}&q={1}&langpair={2}&key={3}",

            _v, _q, _langPair, _key);

 

         _requestUrl = EnumStringUtil.GetStringValue(BASEURL.TRANSLATE) + encodedRequestUrlFragment;

 

         GetTranslation();

      }

 

      public string Translation

      {

         get { return _translation; }

         private set { _translation = value; }

      }

 

      private void GetTranslation()

      {

         try

         {

            WebRequest request = WebRequest.Create(_requestUrl);

            WebResponse response = request.GetResponse();

 

            StreamReader reader = new StreamReader(response.GetResponseStream());

            string json = reader.ReadLine();

            using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))

            {

               DataContractJsonSerializer ser =

                  new DataContractJsonSerializer(typeof(Translation));

               Translation translation = ser.ReadObject(ms) as Translation;

 

               _translation = translation.responseData.translatedText;

            }

         }

         catch (Exception) { }

      }

   }

}

I've also encapsulated some common Google enums into C#, like Language, Version, and Base URL.  Hoefully with a little tweaking, you can easily extend these .NET classes for other Google API classes. 

Happy coding!


Currently rated 3.4 by 15 people

  • Currently 3.4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Related posts

Comments

June 3. 2009 06:35

Thanigainathan

Hi,

Your article is very very helpful for me.

Thanks,
Thani

Thanigainathan

October 24. 2009 01:07

pingback

Pingback from jobpros.org

Google Translation Api Script | Job Pros

jobpros.org