Using Google Translate to automate text translation

Post your working scripts, libraries and tools for AHK v1.1 and older
mryoussef79
Posts: 4
Joined: 17 Feb 2023, 05:33

Re: Using Google Translate to automate text translation

Post by mryoussef79 » 18 Feb 2023, 03:27

@MrDoge
@teadrinker
thanks for support

AbuSultan
Posts: 5
Joined: 27 Apr 2023, 08:37

Re: Using Google Translate to automate text translation

Post by AbuSultan » 27 Apr 2023, 08:46

Hello

The script is simply fantastic. Thank you so much.

I have a small request, please. I want to use Kurdish Sorani as a target language whose code is "ckb". How can I add it to the list of languages in the script and use it. Also, please consider that this language has no voice reading yet in google translate.

I hope you to help me in this concern.

Thanks in advance

teadrinker
Posts: 4331
Joined: 29 Mar 2015, 09:41
Contact:

Re: Using Google Translate to automate text translation

Post by teadrinker » 27 Apr 2023, 09:48

Sure! You can use Kurdish Sorani like this:

Code: Select all

MsgBox, % GoogleTranslate("Hello, World!", "en", "ckb")
MsgBox, % GoogleTranslate("سڵاو جیهان!", "ckb", "en")

AbuSultan
Posts: 5
Joined: 27 Apr 2023, 08:37

Re: Using Google Translate to automate text translation

Post by AbuSultan » 27 Apr 2023, 10:09

teadrinker wrote:
27 Apr 2023, 09:48
Sure! You can use Kurdish Sorani like this:

Code: Select all

MsgBox, % GoogleTranslate("Hello, World!", "en", "ckb")
MsgBox, % GoogleTranslate("سڵاو جیهان!", "ckb", "en")
Thank you for your reply.

What I wanted is how can I edit the script to translate from any language into Kurdish Sorani (ckb) language and to view the translation in the tooltip. Also, I wanted to avoid giving error in the script in case I select to read the translation because Kurdish is not yet supported to be read by voice.

Thanks again

teadrinker
Posts: 4331
Joined: 29 Mar 2015, 09:41
Contact:

Re: Using Google Translate to automate text translation

Post by teadrinker » 27 Apr 2023, 13:11

AbuSultan wrote: I wanted to avoid giving error in the script in case I select to read the translation
But which script exactly are you talking about?

AbuSultan
Posts: 5
Joined: 27 Apr 2023, 08:37

Re: Using Google Translate to automate text translation

Post by AbuSultan » 27 Apr 2023, 14:26

teadrinker wrote:
27 Apr 2023, 13:11
AbuSultan wrote: I wanted to avoid giving error in the script in case I select to read the translation
But which script exactly are you talking about?
I am talking about the following script:

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

^+t::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, 3)
	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 ==================================================

teadrinker
Posts: 4331
Joined: 29 Mar 2015, 09:41
Contact:

Re: Using Google Translate to automate text translation

Post by teadrinker » 27 Apr 2023, 15:57

This script uses my algorithm, but its author @garry.

garry
Posts: 3770
Joined: 22 Dec 2013, 12:50

Re: Using Google Translate to automate text translation

Post by garry » 28 Apr 2023, 03:04

sorry , I just added a GUI which appears at right border , if copy text (ctrl+c) see translation in GUI editor which can be copied
original example here > viewtopic.php?p=273678#p273678 ;- this script , 2nd- example 20200726 ( with Audio )
;-
add to gLabel > Language: > ckb_KurdishSorani ( but this not work with audio )
add command try to aa2 ... so don't see error message if audio not possible
;-

Code: Select all

;- https://www.autohotkey.com/boards/viewtopic.php?p=273678#p273678  ;- this script 2nd- example 20200726 ( with Audio )
;-
;- add to gLabel > Language: > ckb_KurdishSorani  ( but this not work with audio )
;............
;AUDIO:
;............
try aa2:= GetAudioFromGoogle(text, TL1, F1)   ;- don't see error message if AUDIO not possible 
/*
aa2:= GetAudioFromGoogle(text, TL1, F1)
if (aa2<>1)
  {
  msgbox, 262208, ,AA2=%aa2%`nLanguage = "%Tl1%"
  return
  }
*/  

AbuSultan
Posts: 5
Joined: 27 Apr 2023, 08:37

Re: Using Google Translate to automate text translation

Post by AbuSultan » 28 Apr 2023, 11:52

garry wrote:
28 Apr 2023, 03:04
sorry , I just added a GUI which appears at right border , if copy text (ctrl+c) see translation in GUI editor which can be copied
original example here > viewtopic.php?p=273678#p273678 ;- this script , 2nd- example 20200726 ( with Audio )
;-
add to gLabel > Language: > ckb_KurdishSorani ( but this not work with audio )
add command try to aa2 ... so don't see error message if audio not possible
;-

Code: Select all

;- https://www.autohotkey.com/boards/viewtopic.php?p=273678#p273678  ;- this script 2nd- example 20200726 ( with Audio )
;-
;- add to gLabel > Language: > ckb_KurdishSorani  ( but this not work with audio )
;............
;AUDIO:
;............
try aa2:= GetAudioFromGoogle(text, TL1, F1)   ;- don't see error message if AUDIO not possible 
/*
aa2:= GetAudioFromGoogle(text, TL1, F1)
if (aa2<>1)
  {
  msgbox, 262208, ,AA2=%aa2%`nLanguage = "%Tl1%"
  return
  }
*/  
Thank you @garry for your reply.
Can you do me a favor please? I'll be thankful to you if you help me to make an updated version of the script as follows:

What I want is that when I select some text, I want to use some shortcut to show the translated text from any language into Kurdish in a message box so that I can copy and paste it if I want.

Thank you in advance

AbuSultan
Posts: 5
Joined: 27 Apr 2023, 08:37

Re: Using Google Translate to automate text translation

Post by AbuSultan » 28 Apr 2023, 15:39

Thanks a lot dear Mr. @garry for your help. That was a very kind of you. Also, I want to thank the main creator of the script Mr. @teadrinker . You're really fantastic. I hope you all the best.

teadrinker
Posts: 4331
Joined: 29 Mar 2015, 09:41
Contact:

Re: Using Google Translate to automate text translation

Post by teadrinker » 28 Apr 2023, 16:16

@AbuSultan, thanks, glad to help! :)

User avatar
rommmcek
Posts: 1475
Joined: 15 Aug 2014, 15:18

Re: Using Google Translate to automate text translation

Post by rommmcek » 29 May 2023, 15:06

To get US accent use:

Code: Select all

url := "https://translate.google.com/translate_tts?ie=UTF-8&tl="
         . (lng="en"? "en-US": lng) . "&total=1&idx=0&client=t&prev=input&textlen="
         . StrLen(text) . "&tk=" . JS.("tk").(text) . "&q=" . URIEncodeS(text)
Anybody know how to change the voice ((lng="en"? "en-US&voice=en-US-Wavenet-B": lng) does not work)?

teadrinker
Posts: 4331
Joined: 29 Mar 2015, 09:41
Contact:

Re: Using Google Translate to automate text translation

Post by teadrinker » 29 May 2023, 15:42

I don't think this is possible through the api used in this script.
How To Change The Voice On Google Translate

User avatar
rommmcek
Posts: 1475
Joined: 15 Aug 2014, 15:18

Re: Using Google Translate to automate text translation

Post by rommmcek » 29 May 2023, 16:17

Thanks!
Just noticed that not every LanguageCode works either.

FCALIZZ
Posts: 7
Joined: 23 Jun 2023, 12:17

Re: Using Google Translate to automate text translation

Post by FCALIZZ » 23 Jun 2023, 12:42

Hello, thanks to @teadrinker @rommmcek @garry for this awesome script. i'm currently using this version attached below, however it's not ideal for me to use the ctrl + c shortcut since it interferes with other contents i copy in the clipboard, i would prefer if i could select the text i want to be translated and then press for example Alt + M instead of Ctrl + C . I don't know if it's possible. Thanks for your help.

Code: Select all


;extraido de https://www.autohotkey.com/boards/viewtopic.php?f=6&t=63835

;-------- saved at 星期一 七月 2020-07-27  11:55 UTC --------------
;- Using Google Translate to automate text translation
;- https://www.autohotkey.com/boards/viewtopic.php?f=6&t=63835

;- https://www.autohotkey.com/boards/viewtopic.php?f=6&t=63835
;- https://www.autohotkey.com/boards/viewtopic.php?f=76&t=71993 ---
;- translator from user teadrinker / with GUI
/*
modified=20210123  modified language https://cloud.google.com/translate/docs/languages
modified=20200726  added AUDIO
modified=20200329  ( teadrinker ) edited 2 times in total.
modified=20200130  translate clipboard again in other language with dropdownlist (ddl1)
modified=20191019  ( teadrinker ) edited 1 time in total.
modified=20190422  EDIT CreateScriptObj() ( teadrinker )
created =20190419
-select language , copy marked text ctrl+c > see translation in selected language
-click AUDIO button to hear the text
*/
;-------------------------------------------------------------------------------
#NoEnv
;#Warn
MsgBox "this script automatically translate the contents of the clipboard auto detects language and outputs in the desired language in the dropdown."
setworkingdir,%a_scriptdir%
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
rssini=%a_scriptdir%\translate.ini
ifnotexist,%rssini%    ;- first run
    {
    translateto=pt     ;- portuguese
    IniWrite,%translateto%, %rssini% ,Lang1  ,key1
    }
Gui,1:Color,Black,Black
Gui,1:Font,s14 cYellow ,Lucida Console
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,AUDIO
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
GuiControl,1:Choose,ddl1,%tl1%
GuiControl, Focus,ED1
WinID := WinExist("A")
WinSetTitle, ahk_id %WinID%,, TRANSLATE_to_%tl1%
E0x200 = WS_EX_CLIENTEDGE
RETURN
;--------------------------
esc::exitapp
;--------------------------
Guiclose:
cl=
clipboard=
exitapp
;-----  CTRL+C Clipboardchange ---------------------
OnClipboardChange:
If (A_EventInfo=1)
 {
 Gui, Show,
 GuiControl, Focus,ED1
 ClipWait,
 if (!ErrorLevel)
  {
  cl:=clipboard
  aa:=GoogleTranslate(cl)
  ControlSetText,edit1,%aa%, ahk_class AutoHotkeyGUI
  txt22:=aa
  aa=
  GuiControl, Focus,ED1
  }
 }
return
;--------------------------
;--------------------------
ddl2:
Gui,1:submit,nohide
h1:=""
h2:=""
if DDL1<>
{
StringSplit,h,ddl1,`_
if h1<>
  {
  IniWrite,%h1%, %rssini% ,Lang1  ,key1
  tl1:=h1
  WinSetTitle, ahk_id %WinID%,, TRANSLATE_to_%h2%
  gosub,translateddlchange
  }
}
return
;----------------------------------------
;------- translate changed language -----
translateddlchange:
Guicontrolget,ed1
if ed1<>
{
aa:=GoogleTranslate(cl)      ;- translate clipboard again in other language
ControlSetText,edit1,%aa%, ahk_class AutoHotkeyGUI
txt22:=aa
aa=
}
return
;---------------------------------------
;====================== TRANSLATE user teadrinker =============================
;-------- saved at 星期日 七月 2020-07-26  19:57 UTC --------------
;- Using Google Translate to automate text translation
;- https://www.autohotkey.com/boards/viewtopic.php?f=6&t=63835
;MsgBox, % GoogleTranslate("今日の天気はとても良いです")
;MsgBox, % GoogleTranslate("Hello, World!", "en", "ru")
GoogleTranslate(str, from := "auto", to := "en")  {
   trans:=""
   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=" . tl1 . "&hl=" . tl1
      . "&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")  {
   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
}
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 ==================================
AUDIO:
Gui,submit,nohide
global aa2,TL1,text
F1 := a_desktop . "\test.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")
}
;====================== END AUDIO ========================================
;====================== LANGUAGEs ========================================
;-- some examples to select
;-https://cloud.google.com/translate/docs/languages
language:
e5x:=""
e5x=
(Ltrim join|
af_Afrikaans
sq_Albania
am_Amharisch
ar_Arab
hy_Armenia
az_Aserbaijan
eu_Baskisch
be_Belarus
bn_Bengal
bs_Bosnia
bg_Bulgaria
ca_Catalan
ceb_Cebuano (ISO-639-2)
zh-CN_China or zh (BCP-47)
zh-TW_China trad (BCP-47)
co_Corsica
hr_Croatia
cs_Cesko
da_Danmark
nl_Nederland
en_English
eo_Esperanto
et_Estonia
fi_Finland Suomi
fr_France
fy_Fryslan
gl_Galicia
ka_Georgia
de_German
el_Greece Elliniki
gu_Gujarati
ht_Creol Haiti
ha_Haussa
haw_Hawaii(ISO-639-2)
he_Hebräisch
iw_Hebräisch
hi_Hindi
hmn_Hmong (ISO-639-2)
hu_Hungarian Magyar
is_Iceland
ig_Igbo
id_Indonesia
ga_Irland Eire
it_Italia
ja_Japan Nippon
jv_Java
kn_Kannada
kk_Kasach
km_Khmer
rw_Kinyarwanda
ko_Korea
ku_Kurdistan
ky_Kirgisian
lo_Lao
la_Latin
lv_Lettland Latvija
lt_Litvanija Lietuva
lb_Luxemburg
mk_Mazedonia
mg_Madagascar
ms_Malaia
ml_Malayalam
mt_Malta
mi_Maori
mr_Marathi
mn_Mongolia
my_Myanmar
ne_Nepal
no_Norge
ny_Nyanja (Chichewa)
or_Odia (Oriya)
ps_Pashtun
fa_Persia
pl_Poland
pt_Portugal Brasilia
pa_Pandschabi
ro_Romania
ru_Rossija
sm_Samoa
gd_Scotia gael
sr_Serbia
st_Sesotho
sn_Shona
sd_Sindhi
si_Singhal
sk_Slovakia
sl_Slovenia
so_Somalia
es_Espana
su_Sundanesisch
sw_Swahili
sv_Sverige
tl_Tagalog (Philippines)
tg_Tadschikistan
ta_Tamil
tt_Tatar
te_Telugu
th_Thai
tr_Turkiye
tk_Turkmenistan
uk_Ukraina
ur_Urdu
ug_Uigur
uz_Uzbekistan
vi_Vietnam
cy_Wales GB
xh_Xhosa
yi_Jiddisch
yo_Yoruba
zu_Zulu
%s%
%s%
)
return
;====================== END SCRIPT ==================================================





User avatar
kunkel321
Posts: 1058
Joined: 30 Nov 2015, 21:19

Re: Using Google Translate to automate text translation

Post by kunkel321 » 23 Jun 2023, 13:55

Regarding the clipboard... Here is my own version of the script. It won't run correctly without the ini file, but you can see how the clipboard gets "backed up" to another variable, then put back when the script is done.

Code: Select all

#NoEnv
#SingleInstance force
;##############
; https://autohotkey.com/boards/viewtopic.php?f=5&t=40876
; https://www.autohotkey.com/boards/viewtopic.php?f=6&t=63835

menu, tray, icon, shell32.dll,239

AutoTrim Off  ; Retain any leading and trailing whitespace on the clipboard.
ClipboardOld = %ClipboardAll%
Clipboard =  ; Must start off blank for detection to work.
Send ^c
ClipWait, 1
if ErrorLevel  ; ClipWait timed out.
  {
    MsgBox, There is nothing on the clipboard to translate.  Please select some text with the mouse, then try again.
    ExitApp
  }

;Note: This script gets called from my MasterScript.  Therefore, I must specify the folder name where the ini is.
IniRead, FaveLangs, Translator/ListOfLangs.ini, FaveLangs ;Get the list of favorite languages.
IniRead, LastUsed, Translator/ListOfLangs.ini, LastUsed, key ;Get the number for the last-used radio choice.

;IniRead, guiColor, Translator/ListOfLangs.ini, Appearance, Color, Silver
;IniRead, FontColor, Translator/ListOfLangs.ini, Appearance, FontColor, Yellow

; Following color parts lines are specific to Steve's setup.
iniread, guiColor, S:\AutoHotkey\MasterScript\WayText\wtFiles\Settings.ini, MainSettings, GUIColor
if (strLen(guiColor) > 8)
	guiColor := subStr(guiColor, strLen(guiColor) - 5, 6)
iniread, fontColor, S:\AutoHotkey\MasterScript\WayText\wtFiles\Settings.ini, MainSettings, FontColor
if (strLen(fontColor) > 8)
	fontColor := subStr(fontColor, strLen(fontColor) - 5, 6)

;Gui tr:+Owner
Gui, tr:color, %guiColor%
Gui, tr:font, c%FontColor%  ; ### Font color not working ??
Gui, tr:font, s11
Gui, tr:Add, Text,, Select target language:
Loop, parse, FaveLangs, `n
	{
		If a_index = %LastUsed%
            Gui, tr:Add, Radio, checked vRadio%a_index%, %a_loopfield%
        Else
            Gui, tr:Add, Radio, vRadio%a_index%, %a_loopfield%
		vCount = %a_index% ; increments so next radio button is created on next loop.
	}
Gui, tr:Add, Button, default x5 gGetLang w70, OK
Gui, tr:Add, Button,  x+10 gMoreLang w70, More
Gui, tr:Show
Return

GetLang:
Gui, tr:Submit

Loop, parse, FaveLangs, `n
	{

        If Radio%a_index% <> 0
         {
			PickedLang = %a_loopfield%
            NowPicked = %a_index%
         }
	}

IniWrite, %NowPicked%, Translator/ListOfLangs.ini, LastUsed, key ;Write the last-used radio choice back to the ini.

LangCode := SubStr(PickedLang, 1, InStr(PickedLang, "_", false, 1, 1)-1) ;Need everything left of underscore.
LangName := SubStr(PickedLang, InStr(PickedLang, "_", false, 1, 1)+1, 20)

;Msgbox, PosMinus: |%PosMinus%|`nPosPlus: |%PosPlus%|`n`nLang code is: |%LangCode%|`nLang Name is: %LangName%

asOther := GoogleTranslate(Clipboard, "en", LangCode)  ; Convert contents of clipboard.
asEng := GoogleTranslate(asOther, LangCode, "en")      ; Convert contents of back to en.

MsgBox,---------------  Original ---------------`n%Clipboard%`n`n`------------- As %LangName% -------------`n%asOther%`n`n`----------- Back to English -----------`n%asEng%`n`n-------------------------------------------`n[Esc] to Cancel.`n[OK] to send translation to clipboard; then paste as needed via Ctrl+v
Clipboard := asOther

Esc::
GuiClose:
Clipboard := ClipboardOld  ; Restore previous contents of clipboard.
ClipboardOld :=    ; Free up the memory
ExitApp

MoreLang:
Run, Translator\ListOfLangs.ini
;Run, ListOfLangs.ini
;run, mtFiles\SchoolList.ini
ExitApp

;###################################
;The code down here was written by Teadrinker.  (See links at the top.)
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")
}



/*
Other languages to use:
See also: https://cloud.google.com/translate/docs/languages
af = Afrikaans
sq = Albania
am = Amharic
ar = Arabic
hy = Armenian
az = Azerbaijani
eu = Basque
bn = Bengalese
my = Burmese
bs = Bosnian
bg = Bulgarian
ceb = Cebuano
ny = Chichewa
zh-CN = Chinese
de = German
da = Danish
en = English
eo = Esperanto
et = Estonia
tl = Filipino
fi = Finnish-Suomen
fr = French
fy = Friesian
gl = Galician
ka = Georgian
el = Greek
gu = Gujarati
ht = Haitian
ha = Hausa
haw = Hawaiian
iw = Hebrew
hi = Hindi
hmn = Hmong
ig = Igbo
id = Indonesian
ga = Irish
is = Icelandic
it = Italian
ja = Japanese
jw = Javanese
yi = Yiddish
kn = Kannada
kk = Kazakh
ca = Catalan
km = Khmer
rw = kinyarwanda
ky = Kyrgyz
ko = Korean
co = Corsican
hr = Croatian
ku = Kurdish
lo = Lao
la = Latin
lv = Latvian
lt = Lithuanian
lb = Luxembourgish
mg = Malagasy
ml = Malayalam
ms = Malaysian
mt = Maltese
mi = Maori
mr = Marathi
mk = Macedonian
mn = Mongolian
ne = Nepalese
nl = Dutch-Nederlands
no = Norwegian-Norge
or = Odia-India-Odisha
ps = Pashto
fa = Persian
pl = Polish
pt = Portuguese
pa = Punjabi
ro = Romanian
ru = Russian
sm = Samoan
gd = Scottish
sv = Sverige
sr = Serbian
st = Sesotho
sn = Shona
sd = Sindhi
si = Singhalese
sk = Slovak
sl = Slovenia
so = Somalia
es = Spanish
sw = Swahili
su = Sundanese
tg = Tajik
ta = Tamil
tt = Tatar
te = Telugu
th = Thai
cs = Czech
tr = Turkish
tk = Turkmen
ug = Uighur
uk = Ukrainian
hu = Hungarian-Magyar
ur = Urdu
uz = Uzbek
vi = Vietnamese
cy = Welsh
be = Belarusian
xh = Xhosa
yo = Yoruba
zu = Zulu
*/
ste(phen|ve) kunkel

garry
Posts: 3770
Joined: 22 Dec 2013, 12:50

Re: Using Google Translate to automate text translation

Post by garry » 26 Jun 2023, 13:59

@FCALIZZ sorry for late answer
... press for example Alt + M instead of Ctrl + C
from 2nd example
viewtopic.php?p=273678#p273678

Code: Select all

;---------------------------
!m::                               ;- use hotkey alt+m   ( instead of ctrl+c )
 send,^c
 Gui, Show,
 GuiControl, Focus,ED1
 ClipWait,,1
 if (!ErrorLevel)
  {
  aa:=GoogleTranslate(clipboard)
  ControlSetText,edit1,%aa%, ahk_class AutoHotkeyGUI
  txt22:=aa
  aa=
  GuiControl, Focus,ED1
  }
clipboard=  
return
;---------------------------

;- desactivated ( or remove )
/*
;-----  CTRL+C Clipboardchange ---------------------
OnClipboardChange:
If (A_EventInfo=1)
 {
 Gui, Show,
 GuiControl, Focus,ED1
 ClipWait,
 if (!ErrorLevel)
  {
  cl:=clipboard
  aa:=GoogleTranslate(cl)
  ControlSetText,edit1,%aa%, ahk_class AutoHotkeyGUI
  txt22:=aa
  aa=
  GuiControl, Focus,ED1
  }
 }
return
;--------------------------
*/

User avatar
Tykvesh
Posts: 5
Joined: 12 Jul 2023, 04:03

Re: Using Google Translate to automate text translation

Post by Tykvesh » 11 Oct 2023, 18:05

Works great! Is there a way to continue once I send too many requests?

RussF
Posts: 1269
Joined: 05 Aug 2021, 06:36

Re: Using Google Translate to automate text translation

Post by RussF » 12 Oct 2023, 05:53

Google Translate will translate up to 500,000 characters per month for free. Anything over that is considered commercial usage and is billed at the rate of $20 USD per 1 Million characters. You can see their pricing schedule here

There may be free appetizers in this world, but there's no such thing as a free lunch.

Russ

User avatar
Tykvesh
Posts: 5
Joined: 12 Jul 2023, 04:03

Re: Using Google Translate to automate text translation

Post by Tykvesh » 12 Oct 2023, 06:48

@RussF I definitely didn't come anywhere close to that figure. I'm using it to translate chat messages, and yesterday it stopped returning anything after the ~50th time. It works now though. Is there a possibility that it thinks I'm a robot or something?

Post Reply

Return to “Scripts and Functions (v1)”