Using Google Translate to automate text translation

Post your working scripts, libraries and tools for AHK v1.1 and older
User avatar
kunkel321
Posts: 976
Joined: 30 Nov 2015, 21:19

Re: Using Google Translate to automate text translation

23 Jan 2021, 14:01

Hey cool! Thanks Garry! Now I'll have to try out your version of the script too. :- }
ste(phen|ve) kunkel
garry
Posts: 3740
Joined: 22 Dec 2013, 12:50

Re: Using Google Translate to automate text translation

23 Jan 2021, 14:58

@teadrinker thank you for your excellent script and for the whole list from google translator
was also searching for language konkani and visayan , ( not included in google translator ) , example konkani language :
https://www.goaholidayhomes.com/information/learn-konkani.html
teadrinker
Posts: 4309
Joined: 29 Mar 2015, 09:41
Contact:

Re: Using Google Translate to automate text translation

23 Jan 2021, 16:23

@garry
If there isn't a language in the list I linked, I think Google Translate does not support this language.
garry
Posts: 3740
Joined: 22 Dec 2013, 12:50

Re: Using Google Translate to automate text translation

23 Jan 2021, 17:04

@teadrinker yes , thank you for the google translator list ( updated 2021-01-12 ), has already 109 languages
CyberKlabauter
Posts: 44
Joined: 26 Jan 2017, 17:59

Re: Using Google Translate to automate text translation

23 Jan 2021, 20:10

Hi all,

I adapted the script to my needs. I made the following changes based on Garrys version:
  • Auto-translate to native language or to second language if selected text is in native language already
  • Replace selected text with translation and restore Clipboard
  • Show a tooltip menu which let you choose between all alternative translations for a single word and replace selected text (or copy it to clipboard if Shift key is pressed)

Code: Select all

; GitHub:       -
; Forum:        https://www.autohotkey.com/boards/viewtopic.php?f=6&t=63835
; Author:       teadrinker, garry 
; Mod: 	    CyberKlabauter


#NoEnv ; For security
#SingleInstance force
SendMode Input
SetBatchLines, -1
SetWorkingDir %A_ScriptDir%

global tl1,JS,txt22,h1
rssini=%a_scriptdir%\translate.ini

IfNotExist, %rssini%   ;- first run
		{
		translateto=de     ;- german
		IniWrite,%translateto%, %rssini%, Language01, NativeLanguage
		IniWrite,en, %rssini%, Language01, SecondLanguage
		IniWrite,Shift, %rssini%, Hotkeys, CopyModifierKey
		}
IniRead, NativeLanguage, %rssini%, Language01, NativeLanguage
IniRead, SecondLanguage, %rssini%, Language01, SecondLanguage
IniRead, ModifierKey, %rssini%,Lang1, CopyModifierKey
tl1 := NativeLanguage

^+ü::TranslateMenu(NativeLanguage, SecondLanguage)

Esc::
	menu, TranslationMenu, DeleteAll
	Gui, destroy
	return




; --------------------------------------------------------------------------------------
; --------------------------------------------------------------------------------------
; --------------------         Google Audio Translate GUI          ---------------------
; --------------------------------------------------------------------------------------
; --------------------------------------------------------------------------------------

TranslationAndAudioGui:
   ; tl1:=""
   Gui,1:default
   Gui,1: +AlwaysOnTop  
   Gui,1: -DPIScale
   SS_REALSIZECONTROL := 0x40
   wa:=a_screenwidth,ha:=a_screenheight,xx:=100
;   clipboard=
;   cl=
   transform,s,chr,32
   gosub,language

   Gui,1:Color,f5fff9,f5fff9 ; Background color: White Gui
   ; Gui,1:Color,Black,Black ; Background color
   Gui,1:Font,s14 c242424 ,Calibri Light ; Font color
   ; Gui,1:Font,s14 cFFFFFF ,Calibri Light ; Font color
;   IniRead, tl1, %rssini%,Lang1 ,key1
;   global tl1,JS,txt22,h1
   x:=(wa*.5)/xx,W :=(wa*18)/xx,H :=(ha*10)/xx,y:=(ha*.5)/xx
   Gui,add,dropdownlist, x%x% y%y% w%w% vDDL1 gddl2 ,%e5x%
   x:=(wa*20)/xx,W :=(wa*8)/xx,H :=(ha*2.4)/xx,y:=(ha*.5)/xx
   Gui,add,button,x%x% y%y%  w%w% h%h% gAudio, Read aloud
   x:=(wa*.5)/xx,W :=(wa*29)/xx , H :=(ha*88)/xx , y:=(ha*3.5)/xx
   Gui,add,edit,x%x% y%y%  w%w% h%h% vED1  -border -E0x200,
   W :=(wa*30)/xx , H :=(ha*91)/xx  , x:=(wa-w),y:=(ha*2)/xx
   ;Gui, Show,x%x% y%y% w%w% h%h% ,TRANSLATE
   Gui, Show,x%x% y0 w%w% h%h% ,TRANSLATE
   ;GuiControl,1:Choose,ddl1,%tl1% , 
   GuiControl, ChooseString, ddl1, %tl1%  ; select translate to language
   GuiControl, Focus,ED1
   WinID := WinExist("A")
   WinSetTitle, ahk_id %WinID%,, TRANSLATE_to_%tl1%
   E0x200 = WS_EX_CLIENTEDGE
   gosub ShowAudioGui
   RETURN
   
Guiclose:
;	cl=
;	clipboard=
	Gui, destroy
	return
	
;-----  CTRL+C Clipboardchange ---------------------
ShowAudioGui:
;	If (A_EventInfo=1)  {
	Gui, Show,
	GuiControl, Focus,ED1
;	ClipWait,
;	if (!ErrorLevel)  {
;		cl:=clipboard
;		aa:=GoogleTranslate()
		aa:=GoogleTranslate(Translation, "auto", tl1)
;		aa:= 
		ControlSetText,edit1,%aa%, ahk_class AutoHotkeyGUI
		txt22:=aa
		aa=
		GuiControl, Focus,ED1
;		}
;	}
	gosub, AUDIO
	return
	
;--------------------------
;--------------------------
ddl2:
	Gui,1:submit,nohide
	h1:=""
	h2:=""
	; tl1 := Ddl2  ; CK
	if (DDL1 <> "")  {
		StringSplit,h,ddl1,`_
		if (h1 <> "")  {
		  IniWrite,%h1%, %rssini% ,Lang1, key1
		  tl1 := h1
		  WinSetTitle, ahk_id %WinID%,, TRANSLATE_to_%h2%
		  gosub,translateddlchange
		  gosub,Audio ; CB
		  }
	}
	return
	
;----------------------------------------
;------- translate changed language -----
translateddlchange:
	Guicontrolget,ed1
	ControlGet, Language, Choice, , , ahk_class AutoHotkeyGUI
	Language := SubStr(Language, 1, 2)
	ControlGetText,aa, edit1, ahk_class AutoHotkeyGUI
	if (ed1 <> "") {
		aa:=GoogleTranslate(aa, "auto", Language)      ;- translate clipboard again in other language
		ControlSetText,edit1,%aa%, 
		txt22:=aa
		aa=
		}
	return




; --------------------------------------------------------------------------------------
; --------------------------------------------------------------------------------------
; ---------------------        Google Translate Functions         ----------------------
; --------------------------------------------------------------------------------------
; --------------------------------------------------------------------------------------
TranslateMenu(NativeLanguage:="de", SecondLanguage:="en")  {
	global Translation
	Gui, destroy
	SavedClipboard := ClipboardAll
	Clipboard := ""
    Send, ^c
    ClipWait, 0
	ClipboardContent := Clipboard
	Clipboard := SavedClipboard
	Translation := GoogleTranslate(ClipboardContent, "auto", NativeLanguage)
	tl1 := NativeLanguage
	; Check: If terms is in native language use second language to translate to 
	; Ideas for improvements are welcome. This is not the best approach. Some word get auto corrected by google. In this case this the native language is not detected. 
	If (SubStr(ClipboardContent, 1, 30) = SubStr(Translation, 1, StrLen(SubStr(ClipboardContent, 1, 30)))) {
        Translation := GoogleTranslate(ClipboardContent, NativeLanguage, SecondLanguage) 
		tl1 := SecondLanguage
		}
	AlternativeTranslations := ""
	if ((PositionAlternativeTranslations:=InStr(Translation,"`n")) > 0)  {
		if (SubStr(Translation, PositionAlternativeTranslations, 3) = "`n+`n")  {
			AlternativeTranslations := SubStr(Translation, PositionAlternativeTranslations + 3)
			Translation := SubStr(Translation, 1, PositionAlternativeTranslations - 1)
			}	
		}
	If (StrLen(Translation) > 30)
        TranslationTeaser := SubStr(Translation, 1, 30) "…" 
    Else 
        TranslationTeaser := Translation
	
	menu, TranslationMenu, add, % TranslationTeaser, ShowPasteMenu
	menu, TranslationMenu, Default, % TranslationTeaser
	menu, TranslationMenu, Add
	if (AlternativeTranslations != "")	; Loop through all + alternatives and create their own menu entry
		Loop, Parse, AlternativeTranslations, `n, `r
			{
			menu, TranslationMenu, add, % A_LoopField, ShowPasteMenu			
			}
	menu, TranslationMenu, Add
	menu, TranslationMenu, Add
	menu, TranslationMenu, add, Copy to Clipboard , CopyToClipboard
	menu, TranslationMenu, add, Read translation , TranslationAndAudioGui
	menu, TranslationMenu, useErrorLevel
	menu, TranslationMenu, show
	menu, TranslationMenu, deleteAll
	return
	
	ShowPasteMenu:
		if (GetKeyState(ModifierKey, "P"))  {
			if (AlternativeTranslations != "")	
				Clipboard := A_ThisMenuItem
			else
				Clipboard := Translation
			}
		else {
			SavedClipboard := ClipboardAll
			Clipboard := ""
			if (AlternativeTranslations != "")	
				Clipboard := A_ThisMenuItem
			else
				Clipboard := Translation
			ClipWait, 0
			Send, ^v
			Sleep, 3000
			Clipboard := SavedClipboard
			}
		return
		
	CopyToClipboard: 
		Clipboard := Translation "`n" AlternativeTranslations
		return
	}


GoogleTranslate(str, from := "auto", to := "en")  {
	static JS := CreateScriptObj(), _ := JS.( GetJScript() ) := JS.("delete ActiveXObject; delete GetObject;")
   
	json := SendRequest(JS, str, to, from, proxy := "")
	oJSON := JS.("(" . json . ")")

	if !IsObject(oJSON[1])  {
		Loop % oJSON[0].length
			trans .= oJSON[0][A_Index - 1][0]
			}
   else  {
      MainTransText := oJSON[0][0][0]
      Loop % oJSON[1].length  {
        trans .= "`n+"
        obj := oJSON[1][A_Index-1][1]
        Loop % obj.length  {
            txt := obj[A_Index - 1]
            trans .= (MainTransText = txt ? "" : "`n" txt)
			}
		}
	}
	if !IsObject(oJSON[1])
		MainTransText := trans := Trim(trans, ",+`n ")
	else
		trans := MainTransText . "`n+`n" . Trim(trans, ",+`n ")

	from := oJSON[2]
	trans := Trim(trans, ",+`n ")
	Return trans
	}

SendRequest(JS, str, tl, sl, proxy) {
	static http
	ComObjError(false)
	if !http
		{
		http := ComObjCreate("WinHttp.WinHttpRequest.5.1")
		( proxy && http.SetProxy(2, proxy) )
		http.open( "get", "https://translate.google.com", 1 )
		http.SetRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0")
		http.send()
		http.WaitForResponse(-1)
		}
	http.open( "POST", "https://translate.google.com/translate_a/single?client=webapp&sl="
      . sl . "&tl=" . tl . "&hl=" . tl
      . "&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&ie=UTF-8&oe=UTF-8&otf=0&ssel=0&tsel=0&pc=1&kc=1"
      . "&tk=" . JS.("tk").(str), 1 )

	http.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
	http.SetRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0")
	http.send("q=" . URIEncode(str))
	http.WaitForResponse(-1)
	Return http.responsetext
	}

URIEncode(str, encoding := "UTF-8")  {
   VarSetCapacity(var, StrPut(str, encoding))
   StrPut(str, &var, encoding)

   While code := NumGet(Var, A_Index - 1, "UChar")  {
      bool := (code > 0x7F || code < 0x30 || code = 0x3D)
      UrlStr .= bool ? "%" . Format("{:02X}", code) : Chr(code)
   }
   Return UrlStr
	}

GetJScript()  {
   script =
   (
      var TKK = ((function() {
        var a = 561666268;
        var b = 1526272306;
        return 406398 + '.' + (a + b);
      })());

      function b(a, b) {
        for (var d = 0; d < b.length - 2; d += 3) {
            var c = b.charAt(d + 2),
                c = "a" <= c ? c.charCodeAt(0) - 87 : Number(c),
                c = "+" == b.charAt(d + 1) ? a >>> c : a << c;
            a = "+" == b.charAt(d) ? a + c & 4294967295 : a ^ c
        }
        return a
      }

      function tk(a) {
          for (var e = TKK.split("."), h = Number(e[0]) || 0, g = [], d = 0, f = 0; f < a.length; f++) {
              var c = a.charCodeAt(f);
              128 > c ? g[d++] = c : (2048 > c ? g[d++] = c >> 6 | 192 : (55296 == (c & 64512) && f + 1 < a.length && 56320 == (a.charCodeAt(f + 1) & 64512) ?
              (c = 65536 + ((c & 1023) << 10) + (a.charCodeAt(++f) & 1023), g[d++] = c >> 18 | 240,
              g[d++] = c >> 12 & 63 | 128) : g[d++] = c >> 12 | 224, g[d++] = c >> 6 & 63 | 128), g[d++] = c & 63 | 128)
          }
          a = h;
          for (d = 0; d < g.length; d++) a += g[d], a = b(a, "+-a^+6");
          a = b(a, "+-3^+b+-f");
          a ^= Number(e[1]) || 0;
          0 > a && (a = (a & 2147483647) + 2147483648);
          a `%= 1E6;
          return a.toString() + "." + (a ^ h)
      }
   )
   Return script
}

CreateScriptObj() {
   static doc
   doc := ComObjCreate("htmlfile")
   doc.write("<meta http-equiv='X-UA-Compatible' content='IE=9'>")
   Return ObjBindMethod(doc.parentWindow, "eval")
	}





; --------------------------------------------------------------------------------------
; --------------------------------------------------------------------------------------
; -------------------     	Audio / Text to speach Functions        --------------------
; --------------------------------------------------------------------------------------
; --------------------------------------------------------------------------------------

;============================================================================
;=================================   AUDIO ==================================
	AUDIO:
	Gui,submit,nohide
	global aa2,TL1,text
	F1 := A_Temp . "\TextToRead.mp3"
	tl1=%tl1%
	;TL1:="de"
	;text:="Good evening , how are you ?"
	text:=txt22
	;msgbox, 262208, ,LNG=`n%lng%`n---------------------`nTEXT=`n%text%
	;return
	aa2:= GetAudioFromGoogle(text, TL1, F1)
	if (aa2<>1)	  {
	  msgbox, 262208, ,AA2=%aa2%`nLanguage = "%Tl1%"
	  return
	  }
	soundplay,%f1%
	filedelete,%f1%
	return
;----------------------------------------------------------------------------
;----------------------------------------------------------------------------
GetAudioFromGoogle(text,TL1, mp3filePath)  {
   url := CreateUrl(text,TL1)
   data := sendrequest2(url)
   if SubStr(data, 1, 6) = "Error!"
      Return data
   
   Return SaveDataToFile(data, mp3filePath)
	}
	
CreateUrl(text, TL1)  {
   JS := CreateScriptObj2(), JS.( GetJscript2() )
   url := "https://translate.google.ru/translate_tts?ie=UTF-8&tl="
         . TL1 . "&total=1&idx=0&client=t&prev=input&textlen="
         . StrLen(text) . "&tk=" . JS.("tk").(text) . "&q=" . uriencode2(text)
   Return url
	}
	
sendrequest2(url) {
   whr := ComObjCreate("Msxml2.XMLHTTP.6.0")
   whr.Open("GET", url, false)
   whr.Send()
   
   if (whr.Status != 200)
      Return "Error! Status: " . whr.Status . "`n`n" . whr.responseBody
   Return whr.responseBody
	}
	
SaveDataToFile(data, filePath) {
   stream := ComObjCreate("ADODB.Stream")
   stream.type := 1  ; Binary data
   stream.Open
   stream.Write(data)
   stream.SaveToFile(filePath, 2)
   stream.Close
   Return true
	}
	
;=====================================================================================
GetJscript2()  {
   script = 
   (
      var TKK = ((function() {
        var a = 561666268;
        var b = 1526272306;
        return 406398 + '.' + (a + b);
      })());
      function b(a, b) {
        for (var d = 0; d < b.length - 2; d += 3) {
            var c = b.charAt(d + 2),
                c = "a" <= c ? c.charCodeAt(0) - 87 : Number(c),
                c = "+" == b.charAt(d + 1) ? a >>> c : a << c;
            a = "+" == b.charAt(d) ? a + c & 4294967295 : a ^ c
        }
        return a
		}
		function tk(a) {
			for (var e = TKK.split("."), h = Number(e[0]) || 0, g = [], d = 0, f = 0; f < a.length; f++) {
				var c = a.charCodeAt(f);
				128 > c ? g[d++] = c : (2048 > c ? g[d++] = c >> 6 | 192 : (55296 == (c & 64512) && f + 1 < a.length && 56320 == (a.charCodeAt(f + 1) & 64512) ?
				(c = 65536 + ((c & 1023) << 10) + (a.charCodeAt(++f) & 1023), g[d++] = c >> 18 | 240,
				g[d++] = c >> 12 & 63 | 128) : g[d++] = c >> 12 | 224, g[d++] = c >> 6 & 63 | 128), g[d++] = c & 63 | 128)
			}
			a = h;
			for (d = 0; d < g.length; d++) a += g[d], a = b(a, "+-a^+6");
			a = b(a, "+-3^+b+-f");
			a ^= Number(e[1]) || 0;
			0 > a && (a = (a & 2147483647) + 2147483648);
			a `%= 1E6;
			return a.toString() + "." + (a ^ h)
		}
	)
	Return script
	}

UriEncode2(str, encoding := "UTF-8")  {
	urlstr:=""
	VarSetCapacity(var, StrPut(str, encoding))
	StrPut(str, &var, encoding)
	While code := NumGet(Var, A_Index - 1, "UChar")  {
		bool := (code > 0x7F || code < 0x30 || code = 0x3D)
		UrlStr .= bool ? "%" . Format("{:02X}", code) : Chr(code)
	}
	Return UrlStr
	}
	
CreateScriptObj2() {
   static doc
   doc := ComObjCreate("htmlfile")
   doc.write("<meta http-equiv='X-UA-Compatible' content='IE=9'>")
   Return ObjBindMethod(doc.parentWindow, "eval")
	}





;-----------------------------------------------------------------
;-- some examples to select 
language:
	e5x:=""
	e5x=
	(Ltrim join|
	de_Deutsch
	en_English
	fr_Français
	it_Italia
	el_Greek
	tr_Turkiye
	nl_Nederlands
	da_Dansk
	sv_Sverige
	no_Norge
	pt_Portugues
	es_Español
	ru_Rossija
	zh-CN_Chinese
	ja_Nippon
	ro_Romania
	ta_Tamil
	%s%
	%s%
	)
	return

/*
;-----------------------------------------------------------------
;-- some examples to select 
language:
	e5x:=""
	e5x=
	(Ltrim join|
	nl_Nederlands
	af_Suid-Afrika
	fy_Fryslân
	eu_Basque
	ca_Catalan
	de_Deutsch
	da_Dansk
	sv_Sverige
	no_Norge
	is_Iceland
	fi_Suomen
	en_English
	pt_Portugues
	es_Español
	it_Italia
	fr_Français
	ru_Rossija
	zh-CN_Chinese
	ja_Nippon
	ko_Korea
	ro_Romania
	bg_Bulgaria
	mk_Macedonia
	el_Greek
	tr_Turkiye
	sq_Albania
	hr_Croatia
	sr_Serbia
	sl_Slovenia
	hu_Hungary
	cs_Czech
	sk_Slovakia
	pl_Poland
	be_Belarus
	uk_Ukraina
	et_Estonia
	lv_Latvija
	lt_Lituania
	az_Azerbaijan 
	ka_Georgian
	ar_Arabic
	iw_Hebrew
	hi_Hindi
	id_Indonesia
	ms_Malaysia
	vi_Vietnam
	th_Thai
	ta_Tamil
	ur_Urdu
	sw_Swahili
	bn_Bengal
	%s%
	%s%
	)
	return
*/
;====================== END SCRIPT ==================================================
Didn't not clean up and optimize the code so far. Anyways, cheers.
User avatar
kunkel321
Posts: 976
Joined: 30 Nov 2015, 21:19

Re: Using Google Translate to automate text translation

24 Jan 2021, 13:29

Hey very nice CyberKlabauter!

I'm seeing several horizontal lines... Not sure if that's by design(?)
Image

Hey, is it possible to move the 'language picker drop-list' and the 'read button' to be on this menu?

It's interesting to note that this (and of course Garry's that this is based on, and Teadrinker's main code) have good potential as a language-learning tool.
ste(phen|ve) kunkel
CyberKlabauter
Posts: 44
Joined: 26 Jan 2017, 17:59

Re: Using Google Translate to automate text translation

24 Jan 2021, 16:09

kunkel321 wrote:
24 Jan 2021, 13:29
I'm seeing several horizontal lines... Not sure if that's by design(?)
Image
=> delete "menu, TranslationMenu, Add" and they are gone
kunkel321 wrote:
24 Jan 2021, 13:29
Hey, is it possible to move the 'language picker drop-list' and the 'read button' to be on this menu?
=> You could create a submenu to choose/change the language and then reload the menu. But I think it wouldn't an intuitive and fast way. I would recommend to create a second ot third shortcut with your third and fourth language.

Note every language is automatically translated to your native langaguage (no action needed). Only in case you want to translate from your native language to third and fourth langugage you need the menu.

By the way: Many thanks to Teadrinker, Garry', Osprey, rommmcek and all others who supported something. Incredible helpful tool!

@rommmcek
Are your improvements incooperated in teatrinkers version in the first post. It is a bit hard to compare the changes of the different versions.
BeamN6784
Posts: 6
Joined: 09 Mar 2020, 08:43

Re: Using Google Translate to automate text translation

25 Jan 2021, 07:02

Your script is amazing, but there are two issues:

(1) There are some weird characters appearing, sometimes.
(2) There's no way to interact with the translation--I'm going to try to fix this, myself, potentially.... Basically, that's why I'm looking at the script.
(3) This script isn't well-enough known. Hahahaha. It's super amazing and nice. I really appreciate it. You know, I spend so much of my time trying to figure out how to read characters, and I don't want to take the malware that comes with other softwares that do this. Thank you so much.

If you'd like to help me, I might bump TeaDrinker on this, also. Way back in 2014 or so, he was trying to simply output translations into a messagebox. I'd like to interact with tidy examples of how to separate different components of the translation: direct translation, phonetic version, senses, examples...

The reason I'm trying to do this is basically for personal learning and to better interact with some developers on a Fiction-writing project.
rommmcek wrote:
16 Jan 2021, 13:34
Thee must be some kind of misunderstanding. The script in your link does not contain any MsgBox.
Run the script, click with the left mouse button at the start of the desired text to translate and hold the button, drag the mouse to the end of the desired text to translate and release the left mouse button. The translation is displayed in the ToolTip. Then press Esc to delete the ToolTip. Still works for me, however script is now a bit obsolete and you should edit it at least at this line.

pgeugene wrote:
25 Dec 2020, 04:38
I found it easier and faster to double click Lbutton to select single word
Actually your question doesn't belong here! Anyway, try:
Spoiler
BeamN6784
Posts: 6
Joined: 09 Mar 2020, 08:43

Re: Using Google Translate to automate text translation

25 Jan 2021, 07:08

I was just looking at the various submissions to try to find a way to get translations to a variable/msgbox/clipboard and when I ran the code I got this: 今日の天気はとても良いです
:happybday:
teadrinker wrote:
29 Mar 2020, 16:53
I've edited the first post.
BeamN6784
Posts: 6
Joined: 09 Mar 2020, 08:43

Re: Using Google Translate to automate text translation

25 Jan 2021, 07:25

@rommmcek
I've also noticed that this will automagically convert highlighted English to Japanese. I can't find how this works by reading your script. It just says "auto" to "en", but it doesn't say "en" to "jp" anywhere!

I'd like to be able to go from English to Chinese, Russian, Spanish, or Japanese, depending on what work I'm doing. Can you please tell me what part of the code I need to change? I'm hoping that if I can get figure out how to switch target languages, somehow, I'll be able to create a pop-up HUD or a hotkey that will allow the user to rapidly swap languages without closing the script and re-starting it.
User avatar
rommmcek
Posts: 1470
Joined: 15 Aug 2014, 15:18

Re: Using Google Translate to automate text translation

25 Jan 2021, 09:11

@CyberKlabauter: I wouldn't call it improvements. teadrinker's function afaik captures all the GoogleTranlsate data. He made just an example how to use it and I made my own. If you have any ideas start your own example and if needed I'm sure you'll get help...
garry
Posts: 3740
Joined: 22 Dec 2013, 12:50

Re: Using Google Translate to automate text translation

25 Jan 2021, 11:26

@BeamN6784
... to get translations to a variable/msgbox/clipboard and when I ran the code I got this: 今日の天気はとても良いです

in notepad save your script > as ... UTF-8 with BOM

( Note : I used teadrinker's script , just added a GUI or a HotKey )

short example save to clipboard , show in msgbox the result : ( mark text and use hotkey alt+h )
example , see the last script here :
https://www.autohotkey.com/boards/viewtopic.php?f=76&t=71993

or see at first page , a GUI example here , to select language , contains also google translator list : https://cloud.google.com/translate/docs/languages
https://www.autohotkey.com/boards/viewtopic.php?f=6&t=63835

or :

Code: Select all

run,https://translate.google.com/?sl=auto&tl=zh-TW&text=Girl&op=translate
CyberKlabauter
Posts: 44
Joined: 26 Jan 2017, 17:59

Re: Using Google Translate to automate text translation

27 Jan 2021, 18:48

rommmcek wrote:
25 Jan 2021, 09:11
@CyberKlabauter: I wouldn't call it improvements. teadrinker's function afaik captures all the GoogleTranlsate data. He made just an example how to use it and I made my own. If you have any ideas start your own example and if needed I'm sure you'll get help...
Thx rommmcek for the clearification. I have to go through this with more time. I will may ask if I need help.
BeamN6784
Posts: 6
Joined: 09 Mar 2020, 08:43

Re: Using Google Translate to automate text translation

28 Jan 2021, 12:02

I see what you've done, and I think it's fantastic. Even though it significantly diverges from what I am trying to accomplish, a lot of what is done is useful towards it.

What I primarily was concerned about involves this line:

Code: Select all

r:= GoogleTranslate(clipboard,, ja)
. I changed ja to myLang. I added hotkeys at the top of the file to change the language.

Code: Select all

^+`::MsgBox, 0, , Press Ctrl+1 for Japanese-English. Press Ctrl+1 for Chinese-English.  Press Ctrl+3 for Russian-English.  More languages coming soon.`nHighlight text and wait patiently to see a translation.  Press Esc to close the translation.  `nPress Ctrl+0 to suspend the script.  More features coming soon!, 7
^0::suspend
^1::myLang := "ja"
^2::myLang := "zh-CN"
^3::myLang := "ru"
Along with a friend, we are working to re-create the GUI you made in your post. Probably we'll draw from it a lot. I love the tooltip option, honestly. I feel like it is a good idea to have the ability to make it so that a key (such as F1) causes a translation to occur because I don't want to flood Google Translate. Until I can figure out how to make translations happen less frequently, I'll use the script very sparingly.

Kind of out-of-character, but I think it may have caused some 'are you a robot' stuff to occur more often when I used it a lot. Another good reason to limit attempts, besides obviously not wanting to be totally banned by Google Translate, or see the code somehow break.

Anyway, I'd love to continue to correspond and let you know if I make more updates towards my slightly tweaked version.

Talk to you soon. Thanks for responding! :happybday:
rommmcek wrote:
26 Jul 2020, 16:05
Global Hotkeys:
F1, F5: Copy marked text and traslate it
- if there is no marked text attempts to auto-mark a word and then copy it - should work I text editors.
- if there is no marked text and IE active in youtube and subtitles visible attempts to capture them (working as of jan 26 2021)
- if there is no marked text and mpc-hc active and srt subtitles on attempts to capture them (if present in the specified path)
F2: Show Last Gui

Context sensitive Hotkeys (Main Gui Active):
Esc: Stop Google speech if it is running otherwise Hide Gui (Click on Minimize Gui Hides it too - not Minimize)
!Left and XButton1: History Back
!Right and XButton2: History Forward
^Del and !x: Delete History Item (Click on Close Gui Deletes History item too - not Close)
!Up and !Down: Expand/Shrink History capacity
F2: Show Select Language Gui
F3: Replay last speech
F4: Pause/Unpause current speech
F5: Stop the current speech
F9:: Start Speech Input
F10: Start Speech Output
^!#Esc: ExitApp

Context sensitive Hotkeys (Select Language Gui Active):
^Enter: Close Select Language Gui and set chosen settings (Click on Close Gui does the same - not just Close Gui)
Esc:: Close Select Language Gui w/o changing lang. settings

P.s.: As ever: Big thanks to teadrinker!
User avatar
kunkel321
Posts: 976
Joined: 30 Nov 2015, 21:19

Re: Using Google Translate to automate text translation

28 Jan 2021, 16:53

Oh wow, I only just now tried out Rommmcek's Google Translate json_History 2.56.ahk. It is indeed very cool! Kudos.
ste(phen|ve) kunkel
BoBo
Posts: 6564
Joined: 13 May 2014, 17:15

Re: Using Google Translate to automate text translation

11 Feb 2021, 09:35

Bullex wrote:
16 Oct 2019, 12:15
[...] The only problem is, the collected translation is NOT same as the translation provided by the Google translate webpage (https://translate.google.com/#view=home&op=translate&sl=en&tl=bn&text=Hello%20world) which is of much higher quality than the translation collected by this script. Is there any way to modify this script so that it collects the same translation provided by the Google translate webpage?
@teadrinker - I've used your script a minute ago (and now it looks that I've got blocked :shh:) so, time to ask ...
Has your updated script taken the before mentioned condition already into account? I thought about to translate the transcription of YouTube videos so people from abroad will have a chance to better follow its (German) speaker. Higher translation quality would shrink the time of necessarry corrections.

Stupid question of the day - can this script be used/reconfigured for other online translation services (bing/deepL/...) as well? :silent:
Feature request: split input in (to be specified) chunks allowing to pass Googles' 5K-char per session limit.
teadrinker
Posts: 4309
Joined: 29 Mar 2015, 09:41
Contact:

Re: Using Google Translate to automate text translation

11 Feb 2021, 09:44

BoBo wrote: Stupid question of the day - can this script be used for other online translation services (bing/deepL/...) as well?
Nope, each service has its unique algorithm for receiving and sending data.
BoBo wrote: Has your updated script taken the before mentioned condition already into account?
Yeah, my script retuns exactly the same as the Google Translate webpage.

Return to “Scripts and Functions (v1)”

Who is online

Users browsing this forum: No registered users and 127 guests