AS handler to translate string variables between languages.

Hey Scripters.

I was looking for a handler to translate a string variable to another language, and since I couldn’t get the script from http://macscripter.net/viewtopic.php?id=31218 to work, I began making one myself. I gave up on Google Translate since the source html doesn’t include the translated word (and I know absolutely no Java).

So I tried lots of different online translation services and finally landed on http://translate.reference.com which could be grabbed by a simple curl. I used a modified version of the find & replace handler from http://macscripter.net/viewtopic.php?id=13008 to replace a key code that was returned in stead of an apostrophe. Please note that this key code isn’t in the script below below because apparently it’s automatically turned into an apostrophe by the web page.
This line: set _translation to switchText(_translation, “'”, “'”)
Should read: set _translation to switchText(_translation, “& # 3 9 ;”, “'”) --without spaces between the symbols.

The handler works for everything I’ve tested it with so far (although it doesn’t accept question marks), but I’m still a fairly new scripter so a lot could probably be improved. I’d especially like know of better/easier ways to filter a curl. I know there are some UNIX commands for it but when I look at the man pages for something like sed I feel like a complete retard. Human advice would be much appreciated!

Oh, before I forget :slight_smile:
I’ve started writing a blog about my progress as a scripter, containing the best tips, tricks and handlers I’ve picked up. It’s at http://scriptlife.tumblr.com

Here’s the handler.

(* 
This AppleScript handler translates a text string using the online service translate.reference.com or dictionary.com.
Usage: translateThis("en","th","airport")
This example translates the text "airport" from English to Thai.
All available language codes can be found at the end of the script.

In the event that the output contains a character code in stead of the correct letter/symbol, just duplicate this line:
set _translation to switchText(_translation,"'", "'")
replace "'" with the code you wish to replace and replace "'" with the correct letter/symbol.

Both handlers need to be present in your script.
*)

on translateThis(inputLanguage, outputLanguage, textString)
	set textString to switchText(textString, " ", "+")
	set curlString to "curl -i -L \"http://translate.reference.com/translate?query=" & textString & "&src=" & inputLanguage & "&dst=" & outputLanguage & "&v=1.0\""
	set _webSource to (do shell script curlString)
	if _webSource does not contain "dictionary.com/translation" then
		set _start to "<div id=\"content\" class=\"PD_10\">"
		set _stop to "</div>"
	else
		set _start to "<textarea  id=\"tabr1\" name=\"text2\" readonly=\"readonly\">"
		set _stop to "</textarea>"
	end if
	set atid to text item delimiters
	set text item delimiters to _start
	set _translation to text item 2 of _webSource
	set text item delimiters to _stop
	set _translation to text item 1 of _translation
	set text item delimiters to atid
	set _translation to switchText(_translation, "'", "'")
	return _translation
end translateThis

on switchText(_text, _from, _to)
	set _tid to text item delimiters
	set text item delimiters to _from
	try
		set _text to _text's text items
		set text item delimiters to _to
		tell _text to set _text to beginning & ({""} & rest)
	end try
	set text item delimiters to _tid
	return _text
end switchText

(*
Afrikaans = af
Albanian = sq
Arabic = ar
Belarusian = be
Bulgarian = bg
Catalan = ca
Chinese (Simplified) = zh-CN
Chinese (Traditional) = zh-TW
Croatian = hr
Czech = cs
Danish = da
Dutch = nl
English = en
Estonian = et
Finnish = fi
French = fr
Galician = gl
German = de
Greek = el
Haitian Creole = ht
Hebrew = iw
Hindi = hi
Hungarian = hu
Icelandic = is
Indonesian = id
Irish = ga
Italian = it
Japanese = ja
Korean = ko
Latvian = lv
Lithuanian = lt
Macedonian = mk
Malay = ms
Maltese = mt
Norwegian = no
Persian = fa
Polish = pl
Portuguese = pt
Portuguese (Portugal) = pt-PT
Romanian = ro
Russian = ru
Serbian = sr
Slovak = sk
Slovenian = sl
Spanish = es
Swahili = sw
Swedish = sv
Tagalog = tl
Thai = th
Turkish = tr
Ukranian = uk
Vietnamese = vi
Welsh = cy
Yiddish = yi
*)

Hi Monostratos,

Thanks for doing this and posting it.

Unfortunately, as I’m still an AppleScript beginner I haven’t been able to figure out how to input text and get a translation.

Can you point me in the right direction?

Thanks, too, for the link to your Tumblr site.

Cheers,

Bowjest

Above the handler, or in the on run handler, enter this:

translateThis("en","es","This will be translated from English to Spanish!")

Thanks.

I’d like to run this as a free-standing program, so have added a bit of script for text input, but can’t figure out how to get the results displayed in their own window.

Here is what the full script looks like now:

(* 
This AppleScript handler translates a text string using the online service translate.reference.com or dictionary.com.
Usage: translateThis("en","th","airport")
This example translates the text "airport" from English to Thai.
All available language codes can be found at the end of the script.

In the event that the output contains a character code in stead of the correct letter/symbol, just duplicate this line:
set _translation to switchText(_translation,"'", "'")
replace "'" with the code you wish to replace and replace "'" with the correct letter/symbol.

Both handlers need to be present in your script.
*)

set search to text returned of (display dialog "Enter Search Query:" default answer "" buttons {"Search", "Cancel"} default button "Search")

translateThis("de", "en", search)

on translateThis(inputLanguage, outputLanguage, textString)
	set textString to switchText(textString, " ", "+")
	set curlString to "curl -i -L \"http://translate.reference.com/translate?query=" & textString & "&src=" & inputLanguage & "&dst=" & outputLanguage & "&v=1.0\""
	set _webSource to (do shell script curlString)
	if _webSource does not contain "dictionary.com/translation" then
		set _start to "<div id=\"content\" class=\"PD_10\">"
		set _stop to "</div>"
	else
		set _start to "<textarea  id=\"tabr1\" name=\"text2\" readonly=\"readonly\">"
		set _stop to "</textarea>"
	end if
	set atid to text item delimiters
	set text item delimiters to _start
	set _translation to text item 2 of _webSource
	set text item delimiters to _stop
	set _translation to text item 1 of _translation
	set text item delimiters to atid
	set _translation to switchText(_translation, "'", "'")
	return _translation
end translateThis

on switchText(_text, _from, _to)
	set _tid to text item delimiters
	set text item delimiters to _from
	try
		set _text to _text's text items
		set text item delimiters to _to
		tell _text to set _text to beginning & ({""} & rest)
	end try
	set text item delimiters to _tid
	return _text
end switchText

(*
Afrikaans = af
Albanian = sq
Arabic = ar
Belarusian = be
Bulgarian = bg
Catalan = ca
Chinese (Simplified) = zh-CN
Chinese (Traditional) = zh-TW
Croatian = hr
Czech = cs
Danish = da
Dutch = nl
English = en
Estonian = et
Finnish = fi
French = fr
Galician = gl
German = de
Greek = el
Haitian Creole = ht
Hebrew = iw
Hindi = hi
Hungarian = hu
Icelandic = is
Indonesian = id
Irish = ga
Italian = it
Japanese = ja
Korean = ko
Latvian = lv
Lithuanian = lt
Macedonian = mk
Malay = ms
Maltese = mt
Norwegian = no
Persian = fa
Polish = pl
Portuguese = pt
Portuguese (Portugal) = pt-PT
Romanian = ro
Russian = ru
Serbian = sr
Slovak = sk
Slovenian = sl
Spanish = es
Swahili = sw
Swedish = sv
Tagalog = tl
Thai = th
Turkish = tr
Ukranian = uk
Vietnamese = vi
Welsh = cy
Yiddish = yi
*)

Any ideas how I can add a window to display the results? I tried taking part of the Google search script in the other post, but this failed to work (most probably because I don’t really understand the syntax).

Here is what I tried to use:

set finalText to (display dialog "_translation" buttons {"Quit", "Ok"})

As I say, that got me nowhere. :frowning:

Any help would be appreciated.

Ok, I’ve gotten it to return the translation in a dialog box. :slight_smile:

I’ve also set it to copy the result to the clipboard for further use if needed. Easier than I thought!

I’d now like to be able to keep the app open/loop back to the initial input dialog so further translations can take place, but can’t figure out where to put the “repeat / end repeat”.

I tried putting “repeat” before the start of the input dialog and “end repeat” at the end of the script, but it seems to become unhappy because of the “on translateThis” (is this case statement or routine?).

Can anyone help me further along?

Look at the first two lines of the script.

(* 
This AppleScript handler translates a text string using the online service translate.reference.com or dictionary.com.
Usage: translateThis("en","th","airport")
This example translates the text "airport" from English to Thai.
All available language codes can be found at the end of the script.

In the event that the output contains a character code in stead of the correct letter/symbol, just duplicate this line:
set _translation to switchText(_translation,"'", "'")
replace "'" with the code you wish to replace and replace "'" with the correct letter/symbol.

Both handlers need to be present in your script.
*)


repeat

set search to text returned of (display dialog "Enter Search Query:" default answer "" buttons {"Search", "Cancel"} default button "Search")

if button returned of result = "Cancel" then exit repeat

translateThis("de", "en", search)

end repeat


on translateThis(inputLanguage, outputLanguage, textString)
	set textString to switchText(textString, " ", "+")
	set curlString to "curl -i -L \"http://translate.reference.com/translate?query=" & textString & "&src=" & inputLanguage & "&dst=" & outputLanguage & "&v=1.0\""
	set _webSource to (do shell script curlString)
	if _webSource does not contain "dictionary.com/translation" then
		set _start to "<div id=\"content\" class=\"PD_10\">"
		set _stop to "</div>"
	else
		set _start to "<textarea  id=\"tabr1\" name=\"text2\" readonly=\"readonly\">"
		set _stop to "</textarea>"
	end if
	set atid to text item delimiters
	set text item delimiters to _start
	set _translation to text item 2 of _webSource
	set text item delimiters to _stop
	set _translation to text item 1 of _translation
	set text item delimiters to atid
	set _translation to switchText(_translation, "'", "'")
	return _translation
end translateThis

on switchText(_text, _from, _to)
	set _tid to text item delimiters
	set text item delimiters to _from
	try
		set _text to _text's text items
		set text item delimiters to _to
		tell _text to set _text to beginning & ({""} & rest)
	end try
	set text item delimiters to _tid
	return _text
end switchText

(*
Afrikaans = af
Albanian = sq
Arabic = ar
Belarusian = be
Bulgarian = bg
Catalan = ca
Chinese (Simplified) = zh-CN
Chinese (Traditional) = zh-TW
Croatian = hr
Czech = cs
Danish = da
Dutch = nl
English = en
Estonian = et
Finnish = fi
French = fr
Galician = gl
German = de
Greek = el
Haitian Creole = ht
Hebrew = iw
Hindi = hi
Hungarian = hu
Icelandic = is
Indonesian = id
Irish = ga
Italian = it
Japanese = ja
Korean = ko
Latvian = lv
Lithuanian = lt
Macedonian = mk
Malay = ms
Maltese = mt
Norwegian = no
Persian = fa
Polish = pl
Portuguese = pt
Portuguese (Portugal) = pt-PT
Romanian = ro
Russian = ru
Serbian = sr
Slovak = sk
Slovenian = sl
Spanish = es
Swahili = sw
Swedish = sv
Tagalog = tl
Thai = th
Turkish = tr
Ukranian = uk
Vietnamese = vi
Welsh = cy
Yiddish = yi
*)

Thanks for your reply.

I tried that, but each time I get the message:

Can’t get button returned of “term_entered” (where term_entered is the word I used as input).

Any idea what I can try instead?

Thanks,

Bowjest

oops. That was an error. Sorry. Do this:

set {search,theButton} to {text returned, button returned] of (display dialog "Enter Search Query:" default answer "" buttons {"Search", "Cancel"} default button "Search")

if theButton = "Cancel" then exit repeat

translateThis("de", "en", search)

Thanks.

I initially had a problem with:

{text returned, button returned]

because I think the second bracket was mis-matched, but I changed that to } and it saved and ran fine, but still doesn’t repeat.

But it’s not a biggie. I’ve expanded things a bit to include a choice of four languages, so adding a repeat would probably be more complicated now. Here is the script as it currently stands:

(* 
This AppleScript handler translates a text string using the online service translate.reference.com or dictionary.com.
Usage: translateThis("en","th","airport")
This example translates the text "airport" from English to Thai.
All available language codes can be found at the end of the script.

In the event that the output contains a character code in stead of the correct letter/symbol, just duplicate this line:
set _translation to switchText(_translation,"'", "'")
replace "'" with the code you wish to replace and replace "'" with the correct letter/symbol.

Both handlers need to be present in your script.
*)

-- ---------------------------------------------------------
-- Produces a text box so free text can be inserted
-- and source language selected
-- ---------------------------------------------------------

set search to text returned of (display dialog "Enter Search Query:" default answer "" buttons {"Search", "Cancel"} default button "Search")
set lang to {"German", "Dutch", "French", "Spanish"}
set langSelect to (choose from list lang with prompt "Make Language Selection:" without multiple selections allowed) as text
if langSelect is "German" then
	set inputLanguage to {"de"}
else if langSelect is "Dutch" then
	set inputLanguage to {"nl"}
else if langSelect is "French" then
	set inputLanguage to {"fr"}
else if langSelect is "Spanish" then
	set inputLanguage to {"es"}
end if

translateThis(inputLanguage, "en", search)

on translateThis(inputLanguage, outputLanguage, textString)
	set textString to switchText(textString, " ", "+")
	set curlString to "curl -i -L \"http://translate.reference.com/translate?query=" & textString & "&src=" & inputLanguage & "&dst=" & outputLanguage & "&v=1.0\""
	set _webSource to (do shell script curlString)
	if _webSource does not contain "dictionary.com/translation" then
		set _start to "<div id=\"content\" class=\"PD_10\">"
		set _stop to "</div>"
	else
		set _start to "<textarea  id=\"tabr1\" name=\"text2\" readonly=\"readonly\">"
		set _stop to "</textarea>"
	end if
	set atid to text item delimiters
	set text item delimiters to _start
	set _translation to text item 2 of _webSource
	set text item delimiters to _stop
	set _translation to text item 1 of _translation
	set text item delimiters to atid
	set _translation to switchText(_translation, "'", "'")
	
	-- --------------------------------------------------
	-- This will copy _translation to the
	-- clipboard for further use in another
	-- text (if needed)
	-- --------------------------------------------------
	
	set the clipboard to _translation
	
	-- ---------------------------------------------------
	-- Edit out "return translation" line as this is
	-- blocking the dialog window from displaying
	-- the result
	-- ---------------------------------------------------	
	#return _translation
	display dialog _translation
end translateThis

on switchText(_text, _from, _to)
	set _tid to text item delimiters
	set text item delimiters to _from
	try
		set _text to _text's text items
		set text item delimiters to _to
		tell _text to set _text to beginning & ({""} & rest)
	end try
	set text item delimiters to _tid
	return _text
end switchText

(*
Afrikaans = af
Albanian = sq
Arabic = ar
Belarusian = be
Bulgarian = bg
Catalan = ca
Chinese (Simplified) = zh-CN
Chinese (Traditional) = zh-TW
Croatian = hr
Czech = cs
Danish = da
Dutch = nl
English = en
Estonian = et
Finnish = fi
French = fr
Galician = gl
German = de
Greek = el
Haitian Creole = ht
Hebrew = iw
Hindi = hi
Hungarian = hu
Icelandic = is
Indonesian = id
Irish = ga
Italian = it
Japanese = ja
Korean = ko
Latvian = lv
Lithuanian = lt
Macedonian = mk
Malay = ms
Maltese = mt
Norwegian = no
Persian = fa
Polish = pl
Portuguese = pt
Portuguese (Portugal) = pt-PT
Romanian = ro
Russian = ru
Serbian = sr
Slovak = sk
Slovenian = sl
Spanish = es
Swahili = sw
Swedish = sv
Tagalog = tl
Thai = th
Turkish = tr
Ukranian = uk
Vietnamese = vi
Welsh = cy
Yiddish = yi
*)

The big challenge now, though, is getting multiple sets of data from a site such as Linguee. Would you have any interest in looking at that?

Thanks,

Bowjest

You can make this repeat without a button returned of.

repeat
set search to text returned of (display dialog "Enter Search Query:" default answer "" buttons {"Search", "Cancel"} default button "Search" cancel button "Cancel")
set lang to {"German", "Dutch", "French", "Spanish"}
set langSelect to (choose from list lang with prompt "Make Language Selection:" without multiple selections allowed) as text
if langSelect is "German" then
   set inputLanguage to {"de"}
else if langSelect is "Dutch" then
   set inputLanguage to {"nl"}
else if langSelect is "French" then
   set inputLanguage to {"fr"}
else if langSelect is "Spanish" then
   set inputLanguage to {"es"}
end if

translateThis(inputLanguage, "en", search)
end repeat 

Adding a cancel button to the dialog breaks the repeat loop.

Thanks, thewaytoapplescript.

That fixed it a treat. :slight_smile:

Much obliged for your help.

Will now press ahead with a few other similar info gathering scripts and see if I can get them to work.

Bowjest

It seems like you are interested in gathering info from webpages. You should look at my script in Code Exchange. That should be a good example to get you started.

Welcome to the word of text item delimiters. :slight_smile:

I am! I do quite a lot of web-based research work and am always looking for better ways to streamline how I gather information.

It may seem trivial, but shaving a few seconds off gather information means a lot when you have repeated items to research and tight deadlines to meet.

I’ll have a look for your script. Thanks for the tip and of course for your help. It’s very much appreciated.

Bowjest

Oops, I forgot to subscribe to this thread so I haven’t read the replies until now. Thanks thewaytoapplescript for providing support.