Google und Bing Übersetzer per GUI nutzen

Veröffentliche deine funktionierenden Skripte und Funktionen

Moderator: jNizM

User avatar
fump2000
Posts: 313
Joined: 04 Oct 2013, 17:31

Google und Bing Übersetzer per GUI nutzen

08 Oct 2015, 03:49

Hallo zusammen,

da die Google API nicht immer mitspielt und "tmplinshi" hier http://ahkscript.org/boards/viewtopic.p ... 115#p54115 eine super Alternative für den Bing Translator gepostet hat, habe ich mir erlaubt diese zur GUI hinzuzufügen. Die GUI bietet nun beide Möglichkeiten. Sowohl Google als auch Bing können genutzt werden. Beim ersten Start ist Bing voreingestellt. Bei weiteren aufrufen merkt es sich die Auswahl.

Die Google API blockt leider bei zu intensiver Nutzung weitere Anfragen ab. Daher funktioniert die anfrage an Google nicht immer. Per Bing funktioniert es zuverlässiger. Daher habe ich Bing voreingestellt.

Hier nun der neue Code:

Code: Select all

;============================================================================
; Translate text using Google Translator & Bing Translator in a GUI.
;
; v1.1
;
; Tested with AHK v1.1.22.06 L Unicode x86 
;
; Original author Google: Mikhail Kuropyatnikov (micdelt@mail.ru)
; Original author Bing: tmplinshi
; Changed by fump2000
; Thanks to just me
; 
; Update 27.05.2015 - nötig da altes Script nicht mehr funktionierte.
; Neuer Code von fid75 und tmplinshi, siehe: http://ahkscript.org/boards/viewtopic.php?f=5&t=7143
; Update 08.10.2015 - Bing Translator hinzugefügt.
; Neuer Code für Bing von tmplinshi, siehe: http://ahkscript.org/boards/viewtopic.php?p=54115#p54115
;============================================================================
#NoEnv
#Persistent
#SingleInstance ignore
SetBatchLines, -1
OnMessage(0x201, "WM_LBUTTONDOWN") ; Necessary for Guis without caption.
CoordMode, Mouse, Screen
TransMode:=0
;============================================================================
 
;============================================================================
; To = die Sprache zu der im Grunde immer übersetzt werden soll.
; Anti = die Sprache zu der Übersetzt wird wenn Deutsch erkannt wird.
;============================================================================
^t::
TransText:=
TextToT:=GetTextFromClipboard()
IfWinExist, ahk_id %h_GetText%
	{
		GuiControl, GetText:,NewText,%TextToT%
		GoSub NewTranslate
		Return
	}
To:="de"
Anti:="en"
GoSub StartTranslate
Return
;----------------------------------------------------------------------------
; Funktion um Inhalte zu kopieren.
;----------------------------------------------------------------------------
GetTextFromClipboard()
	{
		ClipSaved := ClipboardAll
		Clipboard :=
		SendInput, ^c
		ClipWait, 0.5
		If ErrorLevel
			{
				Clipboard := ClipSaved
				ClipSaved =
				Return
			}
		v := Clipboard
		Clipboard := ClipSaved
		ClipSaved :=
		Return v
	}
;----------------------------------------------------------------------------
; Wurde kein Inhalt kopiert wird nur die GUI aufgerufen.
;----------------------------------------------------------------------------
StartTranslate:
TranslateTo:=To
if (TextToT="")
	{
		GoSub GetText
		return
	}
else
	GoSub translate
Return
;----------------------------------------------------------------------------
; Startet die Übersetzung
;----------------------------------------------------------------------------
translate:
if (TransMode=0)
	TransText:=mTranslate(TextToT, To, Anti)
else
	TransText:=gTranslate(TextToT, To, Anti)
StringReplace, TransText, TransText, \n, `n`r, 1
if (GuiOn=1)
	GuiControl, GetText:,NewTransText,%TransText%
else
	{
		WithText:=1
		Gosub GetText
	}
Return

gTranslate(str, tolang = "", switchLang = "") {
	static whr := ComObjCreate("WinHttp.WinHttpRequest.5.1"), _ := ComObjError(0)
 
	str := StrReplace(str, "`r", "%0D")
	str := StrReplace(str, "`n", "%0A")
 
	url := "https://translate.google.com/translate_a/single?client=t&sl=&tl=" tolang
		 . "&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&dt=at&ie=UTF-8"
		 . "&oe=UTF-8&otf=2&srcrom=0&ssel=0&tsel=3&q=" str
	whr.Open("GET", url, true)
	whr.SetRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko)")
 
	Loop {
		whr.Send()
		If !retCode := whr.WaitForResponse(5) ; Wait up to 5 seconds
			Sleep, 1000
	} Until (retCode = -1) ; Success = -1, Timeout = 0, No response = Empty String
 
	If RegExMatch(whr.ResponseText, ",[\d.]+,,\[\[""\K[\w-]+", sl) && (sl = tolang && switchLang)
		Return A_ThisFunc.(str, switchLang)
 
	For i, arr in ParseJson(whr.ResponseText).1
		result .= StrReplace(arr.1, "\n", "`n")
	Return result
}

mTranslate(str, tolang := "zh-CHS", switchLang := "en") {
	static appid

	; -------- Get appId
	If !appid {
		url     := "http://www.bing.com/translator/dynamic/223578/js/LandingPage.js?phenabled=&rttenabled=&v=223578"
		referer := "http://www.bing.com/translator/"
		While, !WinHttpRequest(url, ioData := "", ioHdr := hdr(referer))
			Sleep, 1000
		If !RegExMatch(ioData, "i)appId:""\K[^""]+", appid) {
			MsgBox, 48, , Failed to getting appid.
			Return
		}
	}

	; -------- Format input string
	texts := RegExReplace(str, "\R+", "`n")
	texts := Trim(texts, "`n")
	texts := JSON_FromObj( StrSplit(texts, "`n") )
	texts := UriEncode(texts)

	; -------- Translate...
	url := "
	(LTrim Join&
		http://api.microsofttranslator.com/v2/ajax.svc/TranslateArray2?appId=" appid "
		texts=" texts "
		from=%22%22
		to=%22" tolang "%22
		options=%7B%7D
		oncomplete=onComplete_1
		onerror=onError_1
		_=" unixNow() "
	)"
	
	referer := "http://www.bing.com/translator/?ref=SALL"
	While, !WinHttpRequest(url, ioData := "", ioHdr := hdr(referer))
		Sleep, 1000

	; -------- Parse result data
	If InStr(ioData, "onError_1(""ArgumentException: The token has expired") {
		appid := ""
		Return %A_ThisFunc%(str, tolang, switchLang)
	}

	RegExMatch(ioData, "\[.*\]", ioData)
	result := JSON_ToObj(ioData)
	If (result[1]["from"] = tolang) && switchLang
		Return %A_ThisFunc%(str, switchLang)

	For i, obj in result
		out .= obj.TranslatedText . "`n"

	Return Trim(out, "`n")
}

hdr(referer := "") {
	Return "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko" . "`n"
	     . "Referer: " . referer
}

unixNow() {
	HumanTimestamp := A_Now
	HumanTimestamp -= 1970010108, s
	Return HumanTimestamp A_MSec
}


;----------------------------------------------------------------------------
; Gui zum anzeigen von übersetzen Text oder zur Eingabe von neuem Text.
;----------------------------------------------------------------------------
GetText:
MouseGetPos, TextX, TextY
Gui, GetText:Color, AAAAAA
Gui, GetText:+LastFound +AlwaysOnTop -Caption +ToolWindow +Border +HWNDh_GetText
Gui, GetText:Font, s10
Gui, GetText:Add, Text, x0 y3 w350 h17 +Center, Text der Übersetzt werden soll:
Gui, GetText:Add, Edit, x0 y20 w350 h60 cBlue vNewText +border gNewTranslate,%TextToT%
Gui, GetText:Add, Text, x0 y83 w150 h17 +Center +ReadOnly, Übersetzung:
Gui, GetText:Add, Radio, x155 y83 w80 h17 vTransModeChange1 gTransModeChange, Bing
Gui, GetText:Add, Radio, x240 y83 w80 h17 vTransModeChange2 gTransModeChange, Google
if (TransMode=0)
	GuiControl, GetText:, TransModeChange1, 1
else
	GuiControl, GetText:, TransModeChange2, 1
Gui, GetText:Add, Edit, x0 y100 w350 h60 cGreen +border vNewTransText,%TransText%
Gui, GetText:Add, Text, x0 y163 w350 h17 vLine1, ESC = Schließen - Klicke ins Graue zum verschieben.
Gui, GetText:Font
Gui, GetText:Font, s8
Gui, GetText:Add, Text, x313 y163 w35 h16 +Border cWhite +Center gWithTextGuiClose, close
if (WithText=1)
	GuiControl, GetText:Focus, Line1
else
	GuiControl, GetText:Focus, NewText
Gui, GetText:Show, h180 w350 x%TextX% y%TextY%
Hotkey, Escape, WithTextGuiClose, on
Return
;----------------------------------------------------------------------------
; Ändern des Übersetzers von Google auf Bing oder umgekehrt.
;----------------------------------------------------------------------------
TransModeChange:
GuiControlGet, TransModeChange1
if (TransModeChange1=1)
	TransMode:=0
else
	TransMode:=1
GoSub NewTranslate
Return
;----------------------------------------------------------------------------
; Bei der Eingabe von neuem Text wird direkt neu Übersetzt.
;----------------------------------------------------------------------------
NewTranslate:
GuiControl, GetText:,NewTransText,
GuiControlGet, NewText, GetText:, NewText
if (NewText="")
	GuiControl, GetText:,NewTransText,
GuiOn:=1
TextToT:=NewText
TransText:=
GoSub translate
Return
;----------------------------------------------------------------------------
; Schließt die GUI und leert die Var's.
;----------------------------------------------------------------------------
WithTextGuiClose:
GuiOn:=0
WithText:=0
TransText:=
Gui, GetText:Destroy
Hotkey, Escape, WithTextGuiClose, off
Return
;----------------------------------------------------------------------------
; Copyright 漏 2013 VxE. All rights reserved.

; Serialize an object as JSON-like text OR format a string for inclusion therein.
; NOTE: scientific notation is treated as a string and hexadecimal as a number.
; NOTE: UTF-8 sequences are encoded as-is, NOT as their intended codepoint.
json_fromobj( obj ) {

	If IsObject( obj )
	{
		isarray := 0 ; an empty object could be an array... but it ain't, says I
		for key in obj
			if ( key != ++isarray )
			{
				isarray := 0
				Break
			}

		for key, val in obj
			str .= ( A_Index = 1 ? "" : "," ) ( isarray ? "" : json_fromObj( key ) ":" ) json_fromObj( val )

		return isarray ? "[" str "]" : "{" str "}"
	}
	else if obj IS NUMBER
		return obj
;	else if obj IN null,true,false ; AutoHotkey does not natively distinguish these
;		return obj

	; Encode control characters, starting with backslash.
	StringReplace, obj, obj, \, \\, A
	StringReplace, obj, obj, % Chr(08), \b, A
	StringReplace, obj, obj, % A_Tab, \t, A
	StringReplace, obj, obj, `n, \n, A
	StringReplace, obj, obj, % Chr(12), \f, A
	StringReplace, obj, obj, `r, \r, A
	StringReplace, obj, obj, ", \", A
	StringReplace, obj, obj, /, \/, A
	While RegexMatch( obj, "[^\x20-\x7e]", key )
	{
		str := Asc( key )
		val := "\u" . Chr( ( ( str >> 12 ) & 15 ) + ( ( ( str >> 12 ) & 15 ) < 10 ? 48 : 55 ) )
				. Chr( ( ( str >> 8 ) & 15 ) + ( ( ( str >> 8 ) & 15 ) < 10 ? 48 : 55 ) )
				. Chr( ( ( str >> 4 ) & 15 ) + ( ( ( str >> 4 ) & 15 ) < 10 ? 48 : 55 ) )
				. Chr( ( str & 15 ) + ( ( str & 15 ) < 10 ? 48 : 55 ) )
		StringReplace, obj, obj, % key, % val, A
	}
	return """" obj """"
} ; json_fromobj( obj )

; Copyright 漏 2013 VxE. All rights reserved.

; Uses a two-pass iterative approach to deserialize a json string
json_toobj( str ) {

	  quot := """" ; firmcoded specifically for readability. Hardcode for (minor) performance gain
	, ws := "`t`n`r " Chr(160) ; whitespace plus NBSP. This gets trimmed from the markup
	, obj := {} ; dummy object
	, objs := [] ; stack
	, keys := [] ; stack
	, isarrays := [] ; stack
	, literals := [] ; queue
	, y := nest := 0

; First pass swaps out literal strings so we can parse the markup easily
	StringGetPos, z, str, %quot% ; initial seek
	while !ErrorLevel
	{
		; Look for the non-literal quote that ends this string. Encode literal backslashes as '\u005C' because the
		; '\u..' entities are decoded last and that prevents literal backslashes from borking normal characters
		StringGetPos, x, str, %quot%,, % z + 1
		while !ErrorLevel
		{
			StringMid, key, str, z + 2, x - z - 1
			StringReplace, key, key, \\, \u005C, A
			If SubStr( key, 0 ) != "\"
				Break
			StringGetPos, x, str, %quot%,, % x + 1
		}
	;	StringReplace, str, str, %quot%%t%%quot%, %quot% ; this might corrupt the string
		str := ( z ? SubStr( str, 1, z ) : "" ) quot SubStr( str, x + 2 ) ; this won't

	; Decode entities
		StringReplace, key, key, \%quot%, %quot%, A
		StringReplace, key, key, \b, % Chr(08), A
		StringReplace, key, key, \t, % A_Tab, A
		StringReplace, key, key, \n, `n, A
		StringReplace, key, key, \f, % Chr(12), A
		StringReplace, key, key, \r, `r, A
		StringReplace, key, key, \/, /, A
		while y := InStr( key, "\u", 0, y + 1 )
			if ( A_IsUnicode || Abs( "0x" SubStr( key, y + 2, 4 ) ) < 0x100 )
				key := ( y = 1 ? "" : SubStr( key, 1, y - 1 ) ) Chr( "0x" SubStr( key, y + 2, 4 ) ) SubStr( key, y + 6 )

		literals.insert(key)

		StringGetPos, z, str, %quot%,, % z + 1 ; seek
	}

; Second pass parses the markup and builds the object iteratively, swapping placeholders as they are encountered
	key := isarray := 1

	; The outer loop splits the blob into paths at markers where nest level decreases
	Loop Parse, str, % "]}"
	{
		StringReplace, str, A_LoopField, [, [], A ; mark any array open-brackets

		; This inner loop splits the path into segments at markers that signal nest level increases
		Loop Parse, str, % "[{"
		{
			; The first segment might contain members that belong to the previous object
			; Otherwise, push the previous object and key to their stacks and start a new object
			if ( A_Index != 1 )
			{
				objs.insert( obj )
				isarrays.insert( isarray )
				keys.insert( key )
				obj := {}
				isarray := key := Asc( A_LoopField ) = 93
			}

			; arrrrays are made by pirates and they have index keys
			if ( isarray )
			{
				Loop Parse, A_LoopField, `,, % ws "]"
					if ( A_LoopField != "" )
						obj[key++] := A_LoopField = quot ? literals.remove(1) : A_LoopField
			}
			; otherwise, parse the segment as key/value pairs
			else
			{
				Loop Parse, A_LoopField, `,
					Loop Parse, A_LoopField, :, % ws
						if ( A_Index = 1 )
							key := A_LoopField = quot ? literals.remove(1) : A_LoopField
						else if ( A_Index = 2 && A_LoopField != "" )
							obj[key] := A_LoopField = quot ? literals.remove(1) : A_LoopField
			}
			nest += A_Index > 1
		} ; Loop Parse, str, % "[{"

		If !--nest
			Break

		; Insert the newly closed object into the one on top of the stack, then pop the stack
		pbj := obj
		obj := objs.remove()
		obj[key := keys.remove()] := pbj
		If ( isarray := isarrays.remove() )
			key++

	} ; Loop Parse, str, % "]}"

	Return obj
} ; json_toobj( str )

/*
	Function: ParseJson(jsonStr)
		Converts a JSON string into an AutoHotkey object
 
	Parameters:
		jsonstr - the JSON string to convert
 
	Remarks:
		Originally by Getfree,
		http://www.autohotkey.com/board/topic/93300-what-format-to-store-settings-in/#entry588268
 
	Returns:
		The AutoHotkey object.
*/
ParseJson(jsonStr)
{
	SC := ComObjCreate("ScriptControl") 
	SC.Language := "JScript"
	ComObjError(false)
	jsCode =
	(
	function arrangeForAhkTraversing(obj){
		if(obj instanceof Array){
			for(var i=0 ; i<obj.length ; ++i)
			    obj[i] = arrangeForAhkTraversing(obj[i]) ;
			return ['array',obj] ;
		}else if(obj instanceof Object){
			var keys = [], values = [] ;
			for(var key in obj){
				keys.push(key) ;
				values.push(arrangeForAhkTraversing(obj[key])) ;
			}
			return ['object',[keys,values]] ;
		}else
			return [typeof obj,obj] ;
	}
	)
	SC.ExecuteStatement(jsCode "; obj=" jsonStr)
	return convertJScriptObjToAhks( SC.Eval("arrangeForAhkTraversing(obj)") )
}
 
/*!
	Function: convertJScriptObjToAhks(jsObj)
		Used by ParseJson()
*/
convertJScriptObjToAhks(jsObj)
{
	if(jsObj[0]="object"){
		obj := {}, keys := jsObj[1][0], values := jsObj[1][1]
		loop % keys.length
			obj[keys[A_INDEX-1]] := convertJScriptObjToAhks( values[A_INDEX-1] )
		return obj
	}else if(jsObj[0]="array"){
		array := []
		loop % jsObj[1].length
			array.insert(convertJScriptObjToAhks( jsObj[1][A_INDEX-1] ))
		return array
	}else
		return jsObj[1]
}

; http://www.autohotkey.com/board/topic/75390-ahk-l-unicode-uri-encode-url-encode-function/?p=480216
UriEncode(Uri, Enc = "UTF-8")
{
   StrPutVar(Uri, Var, Enc)
   f := A_FormatInteger
   SetFormat, IntegerFast, H
   Loop
   {
      Code := NumGet(Var, A_Index - 1, "UChar")
      If (!Code)
         Break
      If (Code >= 0x30 && Code <= 0x39 ; 0-9
         || Code >= 0x41 && Code <= 0x5A ; A-Z
         || Code >= 0x61 && Code <= 0x7A) ; a-z
         Res .= Chr(Code)
      Else
         Res .= "%" . SubStr(Code + 0x100, -1)
   }
   SetFormat, IntegerFast, %f%
   Return, Res
}

UriDecode(Uri, Enc = "UTF-8")
{
   Pos := 1
   Loop
   {
      Pos := RegExMatch(Uri, "i)(?:%[\da-f]{2})+", Code, Pos++)
      If (Pos = 0)
         Break
      VarSetCapacity(Var, StrLen(Code) // 3, 0)
      StringTrimLeft, Code, Code, 1
      Loop, Parse, Code, `%
         NumPut("0x" . A_LoopField, Var, A_Index - 1, "UChar")
      StringReplace, Uri, Uri, `%%Code%, % StrGet(&Var, Enc), All
   }
   Return, Uri
}

StrPutVar(Str, ByRef Var, Enc = "")
{
   Len := StrPut(Str, Enc) * (Enc = "UTF-16" || Enc = "CP1200" ? 2 : 1)
   VarSetCapacity(Var, Len, 0)
   Return, StrPut(Str, &Var, Enc)
}

; WinHttpRequest.ahk
; 
; Usage is similar to HTTPRequest (by VxE),
; Please visit the HTTPRequest page (http://goo.gl/CcnNOY) for more details.
; 
; Supported Options:
; 	NO_AUTO_REDIRECT
; 	Timeout: <Seconds>
; 	Proxy: <IP:Port>
; 	Codepage: <CPnnn>	- e.g. "Codepage: 65001"
; 	Charset: <Encoding>	- e.g. "Charset: UTF-8"
; 	SaveAs: <FileName>
; 	gzip_to_html		- Download html as gzip format, then decompress...
; 						  (Requies gzip.ahk and gzip.dll)
; Return:
; 	Success = -1, Timeout = 0, No response = Empty String
; 
; How to clear cookie:
; 	WinHttpRequest( [] )
; ChangeLog:
; 	2015-4-26 - Added option "gzip_to_html"
; 	2015-4-25 - Added option "Method: HEAD"
; 	2014-9-7  - Fixed a bug in "Charset:"
; 	2014-7-11 - Fixed a bug in "Charset:"
WinHttpRequest( URL, ByRef In_POST__Out_Data="", ByRef In_Out_HEADERS="", Options="" )
{
	static nothing := ComObjError(0)
	static oHTTP   := ComObjCreate("WinHttp.WinHttpRequest.5.1")
	static oADO    := ComObjCreate("adodb.stream")

	; Clear cookie
	If IsObject(URL)
		Return oHTTP := ComObjCreate("WinHttp.WinHttpRequest.5.1")

	; POST or GET
	If (In_POST__Out_Data != "") || InStr(Options, "Method: POST")
		oHTTP.Open("POST", URL, True)
	Else If InStr(Options, "Method: HEAD")
		oHTTP.Open("HEAD", URL, True)
	Else
		oHTTP.Open("GET", URL, True)

	; HEADERS
	If In_Out_HEADERS
	{
		In_Out_HEADERS := Trim(In_Out_HEADERS, " `t`r`n")
		Loop, Parse, In_Out_HEADERS, `n, `r
		{
			If !( _pos := InStr(A_LoopField, ":") )
				Continue

			Header_Name  := SubStr(A_LoopField, 1, _pos-1)
			Header_Value := SubStr(A_LoopField, _pos+1)

			If (  Trim(Header_Value) != ""  )
				oHTTP.SetRequestHeader( Header_Name, Header_Value )
		}
	}

	If (In_POST__Out_Data != "") && !InStr(In_Out_HEADERS, "Content-Type:")
		oHTTP.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded")

	; Options
	If Options
	{
		Loop, Parse, Options, `n, `r
		{
			If ( _pos := InStr(A_LoopField, "Timeout:") )
				Timeout := SubStr(A_LoopField, _pos+8)
			Else If ( _pos := InStr(A_LoopField, "Proxy:") )
				oHTTP.SetProxy( 2, SubStr(A_LoopField, _pos+6) )
			Else If ( _pos := InStr(A_LoopField, "Codepage:") )
				oHTTP.Option(2) := SubStr(A_LoopField, _pos+9)
		}

		oHTTP.Option(6) := InStr(Options, "NO_AUTO_REDIRECT") ? 0 : 1

		If InStr(Options, "gzip_to_html")
			oHTTP.SetRequestHeader("Accept-Encoding", "gzip, deflate")
	}

	If (Timeout > 30)
		oHTTP.SetTimeouts(0, 60000, 30000, Timeout * 1000)

	; Send...
	oHTTP.Send(In_POST__Out_Data)
	retCode := oHTTP.WaitForResponse(Timeout ? Timeout : -1)

	; Handle "SaveAs:" and "Charset:"
	If InStr(Options, "SaveAs:")
	{
		RegExMatch(Options, "i)SaveAs:[ \t]*\K[^\r\n]+", SavePath)

		oADO.Type := 1 ; adTypeBinary = 1
		oADO.Open()
		oADO.Write( oHTTP.ResponseBody )
		oADO.SaveToFile( SavePath, 2 )
		oADO.Close()

		In_POST__Out_Data := ""
	}
	Else If InStr(Options, "gzip_to_html") {
		RegExMatch(Options, "i)Charset:[ \t]*\K[\w-]+", Encoding)
		GZIP_DecompressResponseBody(oHTTP, In_POST__Out_Data, Encoding ? Encoding : "UTF-8")
	}
	Else If InStr(Options, "Charset:")
	{
		RegExMatch(Options, "i)Charset:[ \t]*\K[\w-]+", Encoding)

		oADO.Type     := 1 ; adTypeBinary = 1
		oADO.Mode     := 3 ; adModeReadWrite = 3
		oADO.Open()
		oADO.Write( oHTTP.ResponseBody )
		oADO.Position := 0
		oADO.Type     := 2 ; adTypeText = 2
		oADO.Charset  := Encoding
		In_POST__Out_Data := IsByRef(In_POST__Out_Data) ? oADO.ReadText() : ""
		oADO.Close()
	}
	Else
		In_POST__Out_Data := IsByRef(In_POST__Out_Data) ? oHTTP.ResponseText : ""
	
	; output headers
	In_Out_HEADERS := "HTTP/1.1 " oHTTP.Status() "`n" oHTTP.GetAllResponseHeaders()

	Return retCode ; Success = -1, Timeout = 0, No response = Empty String
}

GZIP_DecompressBuffer( ByRef var, nSz ) { ; 'Microsoft GZIP Compression DLL' SKAN 20-Sep-2010
; Decompress routine for 'no-name single file GZIP', available in process memory.
; Forum post :  www.autohotkey.com/forum/viewtopic.php?p=384875#384875
; Modified by Lexikos 25-Apr-2015 to accept the data size as a parameter.

	; ---------- Added by tmplinshi ----------
	static hModule, _
	If !hModule {
		hModule := DllCall("LoadLibrary", "Str", "gzip.dll", "Ptr")
		_ := { base: {__Delete: "GZIP_DecompressBuffer"} }
	}
	If !_
		Return DllCall("FreeLibrary", "Ptr", hModule)
	; ---------- / Added by tmplinshi ----------

 vSz :=  NumGet( var,nsz-4 ), VarSetCapacity( out,vsz,0 )
 DllCall( "GZIP\InitDecompression" )
 DllCall( "GZIP\CreateDecompression", UIntP,CTX, UInt,1 )
 If ( DllCall( "GZIP\Decompress", UInt,CTX, UInt,&var, UInt,nsz, UInt,&Out, UInt,vsz
    , UIntP,input_used, UIntP,output_used ) = 0 && ( Ok := ( output_used = vsz ) ) )
      VarSetCapacity( var,64 ), VarSetCapacity( var,0 ), VarSetCapacity( var,vsz,32 )
    , DllCall( "RtlMoveMemory", UInt,&var, UInt,&out, UInt,vsz )
 DllCall( "GZIP\DestroyDecompression", UInt,CTX ),  DllCall( "GZIP\DeInitDecompression" )
Return Ok ? vsz : 0
}

GZIP_DecompressResponseBody(ByRef oWinHttp, ByRef retHtml, encoding:="UTF-8") {
	If ( oWinHttp.GetResponseHeader("Content-Encoding") != "gzip" )
		Return True, retHtml := oWinHttp.ResponseText

	body := oWinHttp.ResponseBody
	VarSetCapacity(data, size := body.MaxIndex() + 1)
	; Lock array data and retrieve pointer.
	DllCall("oleaut32\SafeArrayAccessData", "ptr", ComObjValue(body), "ptr*", pdata)
	; Copy array data into our variable.
	DllCall("RtlMoveMemory", "ptr", &data, "ptr", pdata, "ptr", size)
	; Unlock array data.
	DllCall("oleaut32\SafeArrayUnaccessData", "ptr", ComObjValue(body))
	; Decompress data.
	size := GZIP_DecompressBuffer(data, size)
	; Decode string data.
	retHtml := StrGet(&data, size, encoding)
}
;============================================================================
 
WM_LBUTTONDOWN()
{
	if (A_Gui="GetText")
		{
			If (A_GuiControl = "") ; Klick auf den Hintergrund der GUI
				PostMessage, 0xA1, 2, 0 ; sehr sehr alter Trick von SKAN: 0xA1 = WM_NCLBUTTONDOWN
		}
}
Return
Ich denke, dass die neuen JSON Scripts die alten ersetzen könnten aber ich hab da nicht dran getraut. Wahrscheinlich könnte man Code einsparen.
Es funktioniert aber so wie es ist einwandfrei.

Viel Spaß damit!

:bravo: :dance:

MfG
fump
User avatar
fump2000
Posts: 313
Joined: 04 Oct 2013, 17:31

Re: Google und Bing Übersetzer per GUI nutzen

26 Oct 2015, 04:38

Hallo zusammen,

hier eine kleine Änderung an der mTranslate Funktion. Einfach austauschen, dann klappt es auch mit Bing wieder.

Code: Select all

mTranslate(str, tolang := "zh-CHS", switchLang := "en") {
	static appid

	; -------- Get appId
	If !appid {
		url := "http://www.bing.com/translator/"
		WinHttpRequest(url, ioData := "", ioHdr := hdr())
		If !RegExMatch(ioData, "i)(?<=src=['""])dynamic/.*?(?=['""])", url_js) {
			MsgBox, 48, Error, Get url_js failed.
			Return
		}

		url     := "http://www.bing.com/translator/" . url_js
		referer := "http://www.bing.com/translator/"
		While, !WinHttpRequest(url, ioData := "", ioHdr := hdr(referer))
			Sleep, 1000
		If !RegExMatch(ioData, "i)appId:""\K[^""]+", appid) {
			MsgBox, 48, Error, Failed to getting appid.
			Return
		}
	}

	; -------- Format input string
	texts := RegExReplace(str, "\R+", "`n")
	texts := Trim(texts, "`n")
	texts := JSON_FromObj( StrSplit(texts, "`n") )
	texts := UriEncode(texts)

	; -------- Translate...
	url := "
	(LTrim Join&
		http://api.microsofttranslator.com/v2/ajax.svc/TranslateArray2?appId=" appid "
		texts=" texts "
		from=%22%22
		to=%22" tolang "%22
		options=%7B%7D
		oncomplete=onComplete_1
		onerror=onError_1
		_=" unixNow() "
	)"
	
	referer := "http://www.bing.com/translator/?ref=SALL"
	While, !WinHttpRequest(url, ioData := "", ioHdr := hdr(referer))
		Sleep, 1000

	; -------- Parse result data
	If InStr(ioData, "onError_1(""ArgumentException: The token has expired") {
		appid := ""
		Return %A_ThisFunc%(str, tolang, switchLang)
	}

	RegExMatch(ioData, "\[.*\]", ioData)
	result := JSON_ToObj(ioData)
	If (result[1]["from"] = tolang) && switchLang
		Return %A_ThisFunc%(str, switchLang)

	For i, obj in result
		out .= obj.TranslatedText . "`n"

	Return Trim(out, "`n")
}
Metta-Man
Posts: 1
Joined: 12 Jan 2016, 09:45

Re: Google und Bing Übersetzer per GUI nutzen

12 Jan 2016, 09:47

Leider geht das Skript nicht, weil die alte StrReplace-Funktion verwendet wird. Könntest Du das reparieren?
User avatar
fump2000
Posts: 313
Joined: 04 Oct 2013, 17:31

Re: Google und Bing Übersetzer per GUI nutzen

13 Jan 2016, 02:11

Hi!
also mit autohotkey 1.1.22.06 funktioniert es einwandfrei.
Ich sehe auch nicht, dass StrReplace in einer neueren Version nicht mehr existent ist.

Welche AHK Version nutzt du denn?

MfG
fump
rommmcek
Posts: 391
Joined: 15 Aug 2014, 15:18

Re: Google und Bing Übersetzer per GUI nutzen

13 Mar 2016, 01:02

Hallo!

Ich habe dein Bild auf einem anderem Terminal erkannt.
Ich habe dir schon auf englischem Forum einen Rat zu geben versucht.
Dein "Google und Bing Übersetzer per GUI" ist Leider zu komplex für mich, angesichts der Zeit die ich zu Verfügung habe, um dir zu helfen.

Aber Ich gebe dir gerne eine grund Idee wie ich mir vorstelle die erwähnte Funktion zu nutzen, falls du schon nicht alleine drauf gekommen bist!

P.s.: Ich habe die daten von Autohotkey_H zu Autohotkey_L über Clipboard übertragen, was die einfachste, nicht aber die sicherste Methode ist.
Attachments
Run Ahk_H.ahk
(1.12 KiB) Downloaded 183 times
Google Translate API Exemp.ahk
(16.35 KiB) Downloaded 198 times

Return to “Skripte und Funktionen”

Who is online

Users browsing this forum: No registered users and 3 guests