After having some fun building a Factor wrapper for the Google Charts API, I decided to implement the Google Translate API. We will be using version 2, which returns JSON over HTTP.
The Google Translate API requires the use of an API key, which you can get from the Google APIs console.
USING: assocs google http.client io json.reader kernel locals namespaces sequences urls urls.secure ;
Translate
First, we define a global symbol to store the API key:
SYMBOL: google-api-key
Next, we make a simple word to create translation URLs:
:: translate-url ( text source target -- url ) URL" https://www.googleapis.com/language/translate/v2" google-api-key get-global "key" set-query-param source "source" set-query-param target "target" set-query-param text "q" set-query-param ;
We can translate a string of text from a source language into a target language:
: translate ( text source target -- text' ) translate-url http-get nip json> { "data" "translations" } [ swap at ] each first "translatedText" swap at ;
Once you've set your API key, you can try it out:
( scratchpad ) "Hello world!" "en" "es" translate print ¡Hola, mundo!
Google Translate supports many languages, which makes it pretty useful.
Translation Party
If you haven't seen the Translation Party website, you should check it out. Basically, it translates a phrase from English into Japanese and back again until it reaches a stable equilibrium. Some of the results are pretty funny. We are going to build this in Factor, but supporting any source and target language.
:: translation-party ( text source target -- ) text dup print [ dup source target translate dup print target source translate dup print swap dupd = not ] loop drop ;
For example, we can translate the phrase "Type anything here and you'll get funny" and you get:
( scratchpad ) "Type anything here and you'll get funny" "en" "ja" translation-party Type anything here and you'll get funny ここに何も入力すると、面白い取得します Here you enter anything gets interesting ここでは、何が面白いの入力 Here is something interesting input ここで何か面白いものが入力される Something interesting is entered here 何かが興味深いここで入力されている Are entered here is something interesting 何かが興味深いここで入力されていますが Has been entered here is something interesting ここで入力されている何か面白いです What is interesting is entered here 興味深いのは、ここに入力されている Interestingly, that is entered here 興味深いことに、ここに入力されている Interestingly, that is entered here
The code for this is on my Github.
No comments:
Post a Comment