📜 ⬆️ ⬇️

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


Greetings to you, dear readers! It may be a little immodest, but let me declare that the very first review and description of the recently opened Google AJAX Language API for access from a JavaScript application to a translation service will be the next. Everywhere I have so far seen only announcements and attempts to analyze what this may mean for developers and users, but it’s not exactly the guidelines for embedding into your website or project, so I decided to figure it out myself and write.

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 a lot more translation pairs, 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 the browser, but remote access to the service using AJAX is only possible the other day with the opening of the corresponding API and placement of code examples.

The API includes functions for automatically determining the language of the source text, and, in fact, the translation itself. Thirteen different languages ​​and twenty nine variants of translation are supported so far. Unfortunately, Russian is supported only 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 further expand the possibilities of transfers, so do not despair.
')
The translation itself is performed on the server, the client code sends text for language recognition and translation and receives the answer, outputting 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, it seems that nothing is known about the restrictions on the number of requests, but the limit on the length of text in one request (500 characters) can 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 you use these features? Well, offhand, at least two options - translate some short texts, such as product descriptions or article annotations, and automatically translate the interface and / or hint system into the user's language.

Let's now consider a specific module example for a website (anyone) where you can apply such a solution. 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 possibilities, first we will define all the translation options that interest us. Make a global variable trans_var, which will have 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 ​​you can translate for each version of the source text. The largest list for English. I mentioned the Chinese here more likely for the sake of the test, there are several of its variants, so you should, in theory, take into account the writing (traditional or simplified), but you will add this yourself if necessary.

Now we come to the visual side of the case or design an interface. I decided to make it like this:



Depending on the specific language of the text, we automatically form a list of languages ​​for translation (based on the definitions in trans_var , for each of which we display an image of the national flag, as well as a cancel button (returns the translated text to its original form). The 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 used by Google here .

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

The translated text in me replaces the original with me, so before translating I save it into a special internal variable, so that when I call the “restore original” function I’ll put it back in place - after all, you may want to translate it into another language again.

Although the API has its own function for defining the language, I decided to write a small wrapper over it, and put the interface into the one together with the interface drawing function, which you will do automatically after loading the page - determine the language of the article and immediately display the necessary translation interface.

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

I wrote my own wrapper - _detect_lang_code , which takes the name of the DOM element, which contains the text to be translated, and a link to the function that needs to be called after the language has been defined. In our case, this function will be the previously described interface drawing 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 formatted text, they need to be cut out), and if the browser is IE, then I immediately use the innerText property. Further, it is desirable to check the length of the text and cut it - the function of determining the language requires much fewer 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.detect and takes two parameters - a string with text and a callback function, in our case anonymous, that parses the answer. Here is a small nuance compared to the examples on the official site. There, after determining the language, its name is displayed completely, and we only need to know its code, so we will be interested only in the index of the internal array google.language.Languages , which is the language code (the server returns the full name of the language). All, we assign the resulting code to the global variable origin_text_lang and immediately call the interface drawing function. For the source text in English ( en code) we get the interface shown in the figure above.

The translation itself is handled by our own translate_text function, which, for universality, immediately takes two parameters — the codes of the languages ​​of the source text and the one into which we are translating. Since we generated the call code when we created the interface, the code for each language is already registered 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 pair of translation, and, if necessary, we break our text into blocks of multiple 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 is passed a string with text, the original language code, the language code into which we translate, and also a link to the callback function that is executed after the translation and processes the result. Since the library assumes all low-level functions, we only get the result object, which contains the returned data. We check the property result.translation , if it is not false, then the translation is successful and it contains the translated text line. Hurray, just replace the source text with the translated one and that's it!

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

And now, for a snack, one interesting feature. Want to make your interface also translated to 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, like “messages”, “help”, “my programs” and the like. Of course, all of them are accompanied by icons that closely reflect the essence of the menu, but still I would like a translation. 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 that:

["My programs", "subscriptions", "messages", "my statistics", "exit", "home", "search", "help"]

Yes, if such a string is “fed” to a translator, then all the service characters will remain intact! After translation into English we will receive:

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

As you can see, a fairly accurate translation is so your visitors can use it to work with the site without any problems. By the way, in order to translate into all languages, you need to translate a non-native interface (if it is Russian), but separately create an array with English notation, and then translate it into any of the supported ones. This array is later simply converted into a JavaScript object, or used through your favorite framework, and how to substitute the original text in the menu you’ll make it up yourself, right?

Related Links :


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

Source: https://habr.com/ru/post/22156/


All Articles