Practical application of Google AJAX Language API - we embed a translator in our project.


    Greetings, dear readers! Perhaps somewhat immodestly, but let me announce that there will be the very first review in Runet and a description of the practical application of the recently opened Google AJAX Language API for accessing translation services from JavaScript applications. Everywhere I saw so far only announcements and attempts to analyze what this could turn out for developers and users, but I haven’t read the instructions for embedding into my website or project yet, so I decided to figure it out and write it myself.

    And so, first, general information. As you know, Google has a translation service that can translate texts in more than a dozen languages. There are much more pairs of translations, but for some languages ​​only translations into one or two languages ​​are available, for others, for example, English - into many. Previously, you could use this service to translate web pages on the fly, or translate individual words and sentences in a browser, but remote access to the service using AJAX made it possible only the other day by opening the corresponding API and posting code examples.

    The API includes functions to automatically determine the language of the source text, and, in fact, the translation itself. Thirteen different languages ​​and twenty-nine translation options are supported so far. Unfortunately, Russian is only supported as a pair of Russian <> English, that is, translation from Russian into English and vice versa, and the largest number of translations is, of course, for English. However, they promise to replenish the possibilities of translations in the future, so do not despair.

    The translation itself is performed on the server, the client code sends the text for language recognition and translation and receives a response, displaying it to the user. Note that there is no background function for determining the language for translation, so you always need to first determine the language of your text (if you do not specify it manually), and then send it to the translation.

    So far nothing seems to be known about the restrictions on the number of requests, but the restriction on the length of the text in one request (500 characters) may already be annoying. However, I think you yourself will figure out how to get around it (cutting the test into such pieces and translating them one by one is quite simple).

    So where and how can these opportunities be used? Well, offhand, at least two options - translate some kind of short texts, for example, product descriptions or article annotations, and automatically translate the interface and / or hint system into the user's language.

    Let's now look at a specific example of a module for a website (any) where such a solution can be applied. I did it for one of my projects, so you can change what you need to work on your resource.

    Since not all languages ​​have completely all directions of translation, and we do not always need all the features, first we will determine all the options of translation that interest us. Let's make the global variable trans_var, in which there will be the following array:
    var trans_var = {"en":[{"code":"zh","lang":"Chinese"},{"code":"fr","lang":"French"},
    {"code":"de","lang":"German"},{"code":"ru","lang":"Russian"},
    {"code":"es","lang":"Spanish"}
    ],
    "ru":[{"code":"en","lang":"English"}],
    "de":[{"code":"en","lang":"English"},{"code":"fr","lang":"French"}],
    "zh":[{"code":"en","lang":"English"}]};

    It means that our source text can be in English, Russian, German and Chinese, we also determined which languages ​​each version of the source text can be translated into. The biggest list for English. Chinese I mentioned here more for the sake of the test, there are several options, so you should, in theory, take into account the spelling (traditional or simplified), but you will add this yourself if necessary.

    Now let's approach the visual side of things or design an interface. I decided to make it of the following type:



    Depending on the specific language of the text, we automatically generate a list of languages ​​for translation (based on the definitions in trans_var, for each of which we display the image of the national flag, as well as the cancel button (returns the translated text to its original form). Flag images are taken from this set , and the files themselves are renamed according to the language codes. By the way, you can find out the language codes themselves that Google uses here .

    The construction of such an interface itself is banal simple: we get the language of the source text, load an array of supported translations from a variable, and loop through all the objects, form an HTML string on them with a link to the flag drawing and write a link next to which we insert the translation function call (about it a little further), passing as a parameter the language code.

    My translated text replaces the original with me, so before translating I save it in a special internal variable, so that when I call the "restore the original" function, I can put it back in place - because you might want to translate it again into another language.

    Although the API has its own function for defining the language, I decided to write a small wrapper over it, and put it in one common wrapper with the interface rendering function, by calling it you will do everything automatically after loading the page - determine the language of the article and immediately display the desired translation interface.

    It should be noted that the definition of the language, as well as the translation, does not occur instantly, because you need to send data to the server and wait for the answer, so the callback function that is passed to the API is used to process the response.

    I wrote my wrapper - _detect_lang_code, which takes the name of the DOM element that contains the text needed for translation, and a link to the function that needs to be called after determining the language. In our case, such a function would be the previously described rendering of the interface for translation. Inside, we first get the text itself. Since no third-party libraries are used, I get it through the usual innerHTML property (it’s a pity that there will be tags for the formatted text there, they need to be cut), and if the browser is IE, I immediately use the innerText property. Next, it is desirable to check the length of the text and trim it - the language detection function requires much less characters than the translation limit, so to reduce traffic, you can limit the line to the first 50 or 100 characters. Now we call the method to determine the language - in the API it is called google.language.detectand takes two parameters - a string with text and a callback function, in our case anonymous, which parses the answer. Here is a small nuance, compared with the examples on the official website. There, after determining the language, its name is completely displayed, and we only need to find out its code, so we will only be interested in the index of the internal array google.language.Languages , which is the language code (the server returns the full name of the language). That's all, we assign the resulting code to the global variable origin_text_lang and immediately call the interface rendering function. For the source text in English ( en code ) we get the interface shown in the figure above.

    The translation function is our translate_text function., which, for universality, immediately takes two parameters - the language codes of the source text and the one into which we translate. Since we generated the call code when we created the interface, the code for each language is already written there, and the source code is stored in the global variable origin_text_lang, so we immediately pass it (although, of course, you can simplify the example). Further, if necessary, we can once again check the validity of such a translation pair, and if necessary, we break our text into blocks divisible by 500 characters. If you want the translation to be inserted instead of the original text, then save it in a variable - I use _tmp_original_text for this .

    Actually, the translation itself is performed by calling the google.language.translate API function,which contains a string with text, an original language code, a language code into which we translate, as well as a link to a callback function that is executed after the translation and processes the result. Since the library takes on all low-level functions, we get only the result object , which contains the returned data. We check the result.translation property , if it is not false, then the translation is successful and it contains the translated string of text. Hooray, just replace the source text with the translated one and that’s it!

    That's all! Without touching purely linguistic issues of translation quality, we just got a quick opportunity to show our visitors the text in the selected language. Of course, often he is far from ideal, but often it is still better than nothing at all.

    And now, for a snack, one interesting trick. Want to make your interface also be translated into another language? For example, in my one project there is a top menu that is available to the user after registration, and there are various items, such as “messages”, “help”, “my programs” and the like. Of course, all of them are accompanied by pictograms that closely reflect the essence of the menu, but still I would like to translate. Very simple! First you need to arrange the translation as a string, and for further processing we will form a JSON string, an array of all menu items. Something like this:

    [“my programs”, “subscriptions”, “messages”, “my statistics”, “exit”, “home”, “search”, “help”]

    Yes, if you feed this line to the translator, then all the service characters will remain untouched! After the translation into English, we will receive:

    ["my programs", "subscribe", "message", "my statistics", "Exit", "home", "Search", "help"]

    As you can see, the translation is accurate enough to your visitors were able to use it without any problems to work with the site. By the way, in order to translate into all languages, it is necessary to translate not the native interface (if it is Russian), but separately create an array with English symbols, and then translate it into any of the supported ones. This array is subsequently elementary transformed into a JavaScript object or used through your favorite framework, and you can figure out how to replace the original inscriptions in the menu yourself, right?

    Related links :


    PS This is a cross-post from my personal blog. The original is here .

    Also popular now: