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