]> gitweb.factorcode.org Git - factor.git/blob - extra/google/translate/translate.factor
factor: trim more using lists.
[factor.git] / extra / google / translate / translate.factor
1 ! Copyright (C) 2010 Doug Coleman.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: assocs combinators grouping http.client io io.files.temp
4 io.files.unique json.reader kernel make sequences urls ;
5 IN: google.translate
6
7 CONSTANT: google-translate-url "http://ajax.googleapis.com/ajax/services/language/translate"
8
9 CONSTANT: maximum-translation-size 5120
10
11 : parameters>assoc ( text from to -- assoc )
12     "|" glue [
13         [ "q" ,, ] [ "langpair" ,, ] bi*
14         "1.0" "v" ,,
15     ] { } make ;
16
17 : assoc>query-response ( assoc -- response )
18     google-translate-url http-post nip ;
19
20 TUPLE: response-error response error ;
21
22 : throw-response-error ( response -- * )
23     [ ] [ "responseDetails" of ] bi response-error boa throw ;
24
25 : check-response ( response -- response )
26     "responseStatus" over at {
27         { 200 [ ] }
28         { 400 [ throw-response-error ] }
29         [ drop throw-response-error ]
30     } case ;
31
32 : query-response>text ( response -- text )
33     json> check-response
34     "responseData" of
35     "translatedText" of ;
36
37 : (translate) ( text from to -- text' )
38     parameters>assoc
39     assoc>query-response
40     query-response>text ;
41
42 : translate ( text from to -- text' )
43     [ maximum-translation-size group ] 2dip
44     '[ _ _ (translate) ] map concat ;
45
46 :: translation-party ( text source target -- )
47     text dup print [
48         dup source target translate dup print
49         target source translate dup print
50         swap dupd = not
51     ] loop drop ;
52
53 : translate-tts ( text -- file )
54     "http://translate.google.com/translate_tts?tl=en" >url
55     swap "q" set-query-param [
56         "" ".mp3" unique-file [ download-to ] keep
57     ] with-temp-directory ;
58
59 ! Example:
60 ! "dog" "en" "de" translate .
61 ! "Hund"