Making this awesome Google Translate Script work for DeepL Topic is solved

Get help with using AutoHotkey and its commands and hotkeys
wyw
Posts: 89
Joined: 12 Dec 2015, 19:11

Making this awesome Google Translate Script work for DeepL

27 Oct 2018, 04:26

I came across the best Google Translate Script I found on the internet so far. It's very very easy to use. Just highlight any text, press F1 and Ctrl+V and you have what you need.


But I literally just discovered DeepL, and in my opinion it is way better than Google Translate. You get better results. There's unfortunately no translator script for it on the internet (so far).

Therefore, I politely ask you pros whether you can help "us" make something like this for DeepL, including DeepL's Auto-Correct if possible (which this Google Translate Script does not have). This can be so useful in so many ways. I'm very sure that I'm not the only one on this. I would love to see this!



Here is the script:

Code: Select all

$F1::
   Clipboard := ""
   SendInput, ^c
   ClipWait, 1
   if ErrorLevel
      Return
   Clipboard := GoogleTranslate(Clipboard).main
   SoundBeep
   Return
 
GoogleTranslate(str, from := "auto", to := "en")  {
   JSON := new JSON
   JS := JSON.JS, JS.( GetJScript() )
   
   sJson := SendRequest(JS, str, to, from)
   oJSON := JSON.Parse(sJson)
 
   if !IsObject(oJSON[2])  {
      for k, v in oJSON[1]
         trans .= v[1]
   }
   else  {
      MainTransText := oJSON[1, 1, 1]
      for k, v in oJSON[2]  {
         trans .= "`n+"
         for i, txt in v[2]
            trans .= (MainTransText = txt ? "" : "`n" . txt)
      }
   }
   if !IsObject(oJSON[2])
      MainTransText := trans := Trim(trans, ",+`n ")
   else
      trans := MainTransText . "`n+`n" . Trim(trans, ",+`n ")
 
   from := oJSON[3]
   trans := Trim(trans, ",+`n ")
   Return {main: MainTransText, full: trans, from: from}
}
 
SendRequest(JS, str, tl, sl)  {
   ComObjError(false)
   url := "https://translate.google.com/translate_a/single?client=t&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=1&ssel=3&tsel=3&pc=1&kc=2"
        . "&tk=" . JS.("tk").(str)
   body := "q=" . URIEncode(str)
   contentType := "application/x-www-form-urlencoded;charset=utf-8"
   userAgent := "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0"
   Return JSON.GetFromUrl(url, body, contentType, userAgent)
}
 
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
}
 
class JSON
{
   static JS := JSON._GetJScripObject()
   
   Parse(JsonString)  {
      try oJSON := this.JS.("(" JsonString ")")
      catch  {
         MsgBox, Wrong JsonString!
         Return
      }
      Return this._CreateObject(oJSON)
   }
   
   GetFromUrl(url, body := "", contentType := "", userAgent := "")  {
      XmlHttp := ComObjCreate("Microsoft.XmlHttp")
      XmlHttp.Open("GET", url, false)
      ( contentType && XmlHttp.SetRequestHeader("Content-Type", contentType) )
      ( userAgent && XmlHttp.SetRequestHeader("User-Agent", userAgent) )
      XmlHttp.Send(body)
      Return XmlHttp.ResponseText
   }
 
   _GetJScripObject()  {
      VarSetCapacity(tmpFile, (MAX_PATH := 260) << !!A_IsUnicode, 0)
      DllCall("GetTempFileName", Str, A_Temp, Str, "AHK", UInt, 0, Str, tmpFile)
     
      FileAppend,
      (
      <component>
      <public><method name='eval'/></public>
      <script language='JScript'></script>
      </component>
      ), % tmpFile
     
      JS := ObjBindMethod( ComObjGet("script:" . tmpFile), "eval" )
      FileDelete, % tmpFile
      JSON._AddMethods(JS)
      Return JS
   }
 
   _AddMethods(ByRef JS)  {
      JScript =
      (
         Object.prototype.GetKeys = function () {
            var keys = []
            for (var k in this)
               if (this.hasOwnProperty(k))
                  keys.push(k)
            return keys
         }
         Object.prototype.IsArray = function () {
            var toStandardString = {}.toString
            return toStandardString.call(this) == '[object Array]'
         }
      )
      JS.("delete ActiveXObject; delete GetObject;")
      JS.(JScript)
   }
 
   _CreateObject(ObjJS)  {
      res := ObjJS.IsArray()
      if (res = "")
         Return ObjJS
     
      else if (res = -1)  {
         obj := []
         Loop % ObjJS.length
            obj[A_Index] := this._CreateObject(ObjJS[A_Index - 1])
      }
      else if (res = 0)  {
         obj := {}
         keys := ObjJS.GetKeys()
         Loop % keys.length
            k := keys[A_Index - 1], obj[k] := this._CreateObject(ObjJS[k])
      }
      Return obj
   }
}
User avatar
SL5
Posts: 877
Joined: 12 May 2015, 02:10
GitHub: sl5net
Contact:

Re: Making this awesome Google Translate Script work for DeepL

30 Oct 2018, 02:54

maybe little more readable:

$F1::
Clipboard := ""
SendInput, ^c ClipWait, 1 if ErrorLevel Return Clipboard := GoogleTranslate(Clipboard).main SoundBeep Return GoogleTranslate(str, from := "auto", to := "en") {
JSON := new JSON JS := JSON.JS, JS.( GetJScript() ) sJson := SendRequest(JS, str, to, from) oJSON := JSON.Parse(sJson) if !IsObject(oJSON[2]) { for k, v in oJSON[1] trans .= v[1] }else { MainTransText := oJSON[1, 1, 1] for k, v in oJSON[2] { trans .= "`n+" for i, txt in v[2] trans .= (MainTransText = txt ? "" : "`n" . txt) } } if !IsObject(oJSON[2]) MainTransText := trans := Trim(trans, ",+`n ") else trans := MainTransText . "`n+`n" . Trim(trans, ",+`n ") from := oJSON[3] trans := Trim(trans, ",+`n ") Return {main: MainTransText, full: trans, from: from} } SendRequest(JS, str, tl, sl) { ComObjError(false) url := "https://translate.google.com/translate_ ... ient=t&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=1&ssel=3&tsel=3&pc=1&kc=2" . "&tk=" . JS.("tk").(str) body := "q=" . URIEncode(str) contentType := "application/x-www-form-urlencoded;charset=utf-8" userAgent := "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0" Return JSON.GetFromUrl(url, body, contentType, userAgent) } 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 } class JSON { static JS := JSON._GetJScripObject() Parse(JsonString) { try oJSON := this.JS.("(" JsonString ")") catch { MsgBox, Wrong JsonString! Return } Return this._CreateObject(oJSON) } GetFromUrl(url, body := "", contentType := "", userAgent := "") { XmlHttp := ComObjCreate("Microsoft.XmlHttp") XmlHttp.Open("GET", url, false) ( contentType && XmlHttp.SetRequestHeader("Content-Type", contentType) ) ( userAgent && XmlHttp.SetRequestHeader("User-Agent", userAgent) ) XmlHttp.Send(body) Return XmlHttp.ResponseText } _GetJScripObject() { VarSetCapacity(tmpFile, (MAX_PATH := 260) << !!A_IsUnicode, 0) DllCall("GetTempFileName", Str, A_Temp, Str, "AHK", UInt, 0, Str, tmpFile) FileAppend, ( <component> <public><method name='eval'/></public> <script language='JScript'></script> </component> ), % tmpFile JS := ObjBindMethod( ComObjGet("script:" . tmpFile), "eval" ) FileDelete, % tmpFile JSON._AddMethods(JS) Return JS } _AddMethods(ByRef JS) { JScript = ( Object.prototype.GetKeys = function () { var keys = [] for (var k in this) if (this.hasOwnProperty(k)) keys.push(k) return keys } Object.prototype.IsArray = function () { var toStandardString = {}.toString return toStandardString.call(this) == '[object Array]' } ) JS.("delete ActiveXObject; delete GetObject;") JS.(JScript) } _CreateObject(ObjJS) { res := ObjJS.IsArray() if (res = "") Return ObjJS else if (res = -1) { obj := [] Loop % ObjJS.length obj[A_Index] := this._CreateObject(ObjJS[A_Index - 1]) }else if (res = 0) { obj := {} keys := ObjJS.GetKeys() Loop % keys.length k := keys[A_Index - 1], obj[k] := this._CreateObject(ObjJS[k]) }
Return obj } }$F1::
Clipboard := ""
SendInput, ^c ClipWait, 1 if ErrorLevel Return Clipboard := GoogleTranslate(Clipboard).main SoundBeep Return GoogleTranslate(str, from := "auto", to := "en") { JSON := new JSON JS := JSON.JS, JS.( GetJScript() ) sJson := SendRequest(JS, str, to, from) oJSON := JSON.Parse(sJson) if !IsObject(oJSON[2]) { for k, v in oJSON[1] trans .= v[1] }else { MainTransText := oJSON[1, 1, 1] for k, v in oJSON[2] { trans .= "`n+" for i, txt in v[2] trans .= (MainTransText = txt ? "" : "`n" . txt) } } if !IsObject(oJSON[2]) MainTransText := trans := Trim(trans, ",+`n ") else trans := MainTransText . "`n+`n" . Trim(trans, ",+`n ") from := oJSON[3] trans := Trim(trans, ",+`n ") Return {main: MainTransText, full: trans, from: from} } SendRequest(JS, str, tl, sl) { ComObjError(false) url := "https://translate.google.com/translate_ ... ient=t&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=1&ssel=3&tsel=3&pc=1&kc=2" . "&tk=" . JS.("tk").(str) body := "q=" . URIEncode(str) contentType := "application/x-www-form-urlencoded;charset=utf-8" userAgent := "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0" Return JSON.GetFromUrl(url, body, contentType, userAgent) } 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 } class JSON { static JS := JSON._GetJScripObject() Parse(JsonString) { try oJSON := this.JS.("(" JsonString ")") catch { MsgBox, Wrong JsonString! Return } Return this._CreateObject(oJSON) } GetFromUrl(url, body := "", contentType := "", userAgent := "") { XmlHttp := ComObjCreate("Microsoft.XmlHttp") XmlHttp.Open("GET", url, false) ( contentType && XmlHttp.SetRequestHeader("Content-Type", contentType) ) ( userAgent && XmlHttp.SetRequestHeader("User-Agent", userAgent) ) XmlHttp.Send(body) Return XmlHttp.ResponseText } _GetJScripObject() { VarSetCapacity(tmpFile, (MAX_PATH := 260) << !!A_IsUnicode, 0) DllCall("GetTempFileName", Str, A_Temp, Str, "AHK", UInt, 0, Str, tmpFile) FileAppend, ( <component> <public><method name='eval'/></public> <script language='JScript'></script> </component> ), % tmpFile JS := ObjBindMethod( ComObjGet("script:" . tmpFile), "eval" ) FileDelete, % tmpFile JSON._AddMethods(JS) Return JS } _AddMethods(ByRef JS) { JScript = ( Object.prototype.GetKeys = function () { var keys = [] for (var k in this) if (this.hasOwnProperty(k)) keys.push(k) return keys } Object.prototype.IsArray = function () { var toStandardString = {}.toString return toStandardString.call(this) == '[object Array]' } ) JS.("delete ActiveXObject; delete GetObject;") JS.(JScript) } _CreateObject(ObjJS) { res := ObjJS.IsArray() if (res = "") Return ObjJS else if (res = -1) { obj := [] Loop % ObjJS.length obj[A_Index] := this._CreateObject(ObjJS[A_Index - 1]) }else if (res = 0) { obj := {} keys := ObjJS.GetKeys() Loop % keys.length k := keys[A_Index - 1], obj[k] := this._CreateObject(ObjJS[k]) }
Return obj } }
return
wyw
Posts: 89
Joined: 12 Dec 2015, 19:11

Re: Making this awesome Google Translate Script work for DeepL

30 Oct 2018, 05:23

Oh men, looks like this is a bug with the new version of the site (?). You can "fix" this if you sign out of your account, then it will show the old one. Atleast for me.
wyw
Posts: 89
Joined: 12 Dec 2015, 19:11

Re: Making this awesome Google Translate Script work for DeepL

30 Oct 2018, 11:33

MannyKSoSo wrote:
30 Oct 2018, 07:10
I would take a look a this post https://autohotkey.com/boards/viewtopic ... pl#p238850
This has a good class for using deepl
Thanks for the link buddy.


I came across the topic a few times already. Looks very promising...


I don't want to sound ridiculous here, but I don't even have the slightest idea on what I need to do to integrate it into the script, therefore I decided to ask for help. :)

Hopefully we'll get somewhere.
MannyKSoSo
Posts: 434
Joined: 28 Apr 2018, 21:59

Re: Making this awesome Google Translate Script work for DeepL  Topic is solved

30 Oct 2018, 12:03

So its fairly simple on how to use the DeepL class version. The first thing is to grab the class and either save it as its own or just include inside your main script (might be easier within the main script). Then set up the new class via translate := new DeepLTranslator() which will turn the class on and connect you to the deepl server which will do the translation. Once that is done all you need next is to get your hotkey and set that up with whatever you want and the call to do the translate. Once you call the method translate() it will return the data that it finds back to you. In the end you should have something like this

Code: Select all

[c]translator := new DeepLTranslator()[/c]

[c]$F1::[/c]
[c]SendInput, ^C[/c]
[c]ClipWait, 1 [/c]
[c]if ErrorLevel [/c]
[c]	Return[/c]
[c]MsgBox % translator.translate(Clipboard, "en")[/c]
[c]Return[/c]

[c]class DeepLTranslator { [/c]
[c]	static formatURL := "https://www.deepl.com/en/translator#{2:s}/{3:s}/{1:s}" [/c]
[c]	__New() { [/c]
[c]		this.IE := ComObjCreate("InternetExplorer.Application") [/c]
[c]	}[/c]
[c]	__Delete() { [/c]
[c]		this.IE.Quit [/c]
[c]	} [/c]
[c]	translate(sourceText, languageOut, languageIn := "auto") { [/c]
[c]		sourceURL := this.uriEncode(sourceText) [/c]
[c]		url := Format(This.formatURL, sourceURL, languageIn, languageOut) [/c]
[c]		this.navigate(url) [/c]
[c]		return this.translation()[/c]
[c]	} [/c]
[c]	navigate(url) { [/c]
[c]		this.IE.Navigate(url) [/c]
[c]		While (this.IE.readyState != 4 || this.IE.document.readyState != "complete" || this.IE.busy) [/c]
[c]		Sleep 50[/c]
[c]	} [/c]
[c]	translation() { [/c]
[c]		While ((result := this.IE.document.getElementsByTagName("textarea")[1].value) = "") [/c]
[c]		Sleep 50 [/c]
[c]		return result [/c]
[c]	} [/c]
[c]	uriEncode(sourceText) { [/c]
[c]		return StrReplace(sourceText, " ", "%20")[/c]
[c]		} [/c]
[c]}[/c]
wyw
Posts: 89
Joined: 12 Dec 2015, 19:11

Re: Making this awesome Google Translate Script work for DeepL

30 Oct 2018, 17:26

MannyKSoSo wrote:
30 Oct 2018, 12:03
So its fairly simple on how to use the DeepL class version. The first thing is to grab the class and either save it as its own or just include inside your main script (might be easier within the main script). Then set up the new class via translate := new DeepLTranslator() which will turn the class on and connect you to the deepl server which will do the translation. Once that is done all you need next is to get your hotkey and set that up with whatever you want and the call to do the translate. Once you call the method translate() it will return the data that it finds back to you. In the end you should have something like this

Code: Select all

[c]translator := new DeepLTranslator()[/c]

[c]$F1::[/c]
[c]SendInput, ^C[/c]
[c]ClipWait, 1 [/c]
[c]if ErrorLevel [/c]
[c]	Return[/c]
[c]MsgBox % translator.translate(Clipboard, "en")[/c]
[c]Return[/c]

[c]class DeepLTranslator { [/c]
[c]	static formatURL := "https://www.deepl.com/en/translator#{2:s}/{3:s}/{1:s}" [/c]
[c]	__New() { [/c]
[c]		this.IE := ComObjCreate("InternetExplorer.Application") [/c]
[c]	}[/c]
[c]	__Delete() { [/c]
[c]		this.IE.Quit [/c]
[c]	} [/c]
[c]	translate(sourceText, languageOut, languageIn := "auto") { [/c]
[c]		sourceURL := this.uriEncode(sourceText) [/c]
[c]		url := Format(This.formatURL, sourceURL, languageIn, languageOut) [/c]
[c]		this.navigate(url) [/c]
[c]		return this.translation()[/c]
[c]	} [/c]
[c]	navigate(url) { [/c]
[c]		this.IE.Navigate(url) [/c]
[c]		While (this.IE.readyState != 4 || this.IE.document.readyState != "complete" || this.IE.busy) [/c]
[c]		Sleep 50[/c]
[c]	} [/c]
[c]	translation() { [/c]
[c]		While ((result := this.IE.document.getElementsByTagName("textarea")[1].value) = "") [/c]
[c]		Sleep 50 [/c]
[c]		return result [/c]
[c]	} [/c]
[c]	uriEncode(sourceText) { [/c]
[c]		return StrReplace(sourceText, " ", "%20")[/c]
[c]		} [/c]
[c]}[/c]


Thank you very much buddy! Truly appreciate it.

I modified it to my liking, and so far it's actually working fine! Made it like the Google one. If I ever run into problems I'll come back here if that is okay.

There is something though, do you mind helping me with something real quick please? I want to use it in Firefox, but whenever I press F1 (no matter what HotKey) it brings up this "Inspect Element" window. What do I exactly have to do to avoid that?

Edit: Fixed it.
swagfag
Posts: 3087
Joined: 11 Jan 2017, 17:59

Re: Making this awesome Google Translate Script work for DeepL

30 Oct 2018, 22:22

whr implementation, handling of funky chars not guaranteed:
https://p.ahkscript.org/?p=7bea5a00

Code: Select all

#NoEnv
#SingleInstance Force
#Warn ClassOverwrite
SetBatchLines -1

#Include JSON.ahk ; https://github.com/cocobelgica/AutoHotkey-JSON
Deep := new DeepL()

q::Deep.print(Deep.translate(Clipboard, "en", "de"))
Esc::ExitApp

class DeepL
{
	__New() {
		JSON_STR =
		(LTrim Join
			{
				"jsonrpc":"2.0",
				"method": "LMT_handle_jobs",
				"params": {
					"jobs": [
						{
							"kind":"default",
							"raw_en_sentence":"{1:}",
							"raw_en_context_before":[],
							"raw_en_context_after":[]
						}
					],
					"lang": {
						"user_preferred_langs": ["FR","ES","IT","NL","DE","PL","EN"],
						"source_lang_computed":"{2:U}",
						"target_lang":"{3:U}"
					},
					"priority":1,
					"timestamp":0
				}
			,"id":0
			}
		)
		this.JSON_STR := JSON_STR

		this.WinHttpRequest := ComObjCreate("WinHttp.WinHttpRequest.5.1")
		this.WinHttpRequest.Open("POST", "https://www2.deepl.com/jsonrpc", false)
		this.WinHttpRequest.SetRequestHeader("Content-Type", "text/plain")
	}

	translate(query, srcLang := "en", dstLang := "de") {
		this.WinHttpRequest.Send(Format(this.JSON_STR, query, srcLang, dstLang))
		Response := JSON.Load(this.WinHttpRequest.ResponseText)

		Result := []
		for each, Translation in Response.result.translations[1].beams
			Result.Push(Translation.postprocessed_sentence)

		return Result
	}

	print(Result) {
		for each, translation in Result
			res .= Format("{}. {}`n", A_Index, translation)

		MsgBox % res
	}
}
robmar-zl
Posts: 16
Joined: 05 Feb 2015, 04:57

Re: Making this awesome Google Translate Script work for DeepL

31 Oct 2018, 08:09

@swagfag: Great solution, and very very fast.

I want to extend it a little bit but I doesn't work 100% like I want it to do.

I want to make it work in both directions english-> german and german-> english depending on the input.
The best solution would be an "auto" detection of the source language and translate it into german, if it's a german text translate into english.

My actual solution is to translate it from english into german and if the result is the same than the Clipboard translate it from german to english.

Is there a better solution?
swagfag
Posts: 3087
Joined: 11 Jan 2017, 17:59

Re: Making this awesome Google Translate Script work for DeepL

31 Oct 2018, 15:48

only de-en-de support:
https://p.ahkscript.org/?p=eb5b7d9b

Code: Select all

#NoEnv
#SingleInstance Force
#Warn ClassOverwrite
SetBatchLines -1

#Include JSON.ahk

Deep := new DeepL()

q::Deep.print(Deep.translate(Clipboard))
Esc::ExitApp

class DeepL
{
	__New() {
		JSON_STR =
		(LTrim Join
		{
			"jsonrpc":"2.0",
			"method":"LMT_handle_jobs",
			"params":{
				"jobs":[
					{
						"kind":"default",
						"raw_en_sentence":"{1:}",
						"raw_en_context_before":[],
						"raw_en_context_after":[],
						"quality":"fast"
					}
				],
				"lang":{
					"user_preferred_langs":["EN", "DE"],
					"source_lang_user_selected":"{2:}",
					"target_lang":"{3:}"
				},
				"priority":1,
				"timestamp":1
			},
			"id":1
		}
		)
		this.JSON_STR := JSON_STR

		this.WinHttpRequest := ComObjCreate("WinHttp.WinHttpRequest.5.1")
		this.WinHttpRequest.Open("POST", "https://www2.deepl.com/jsonrpc", false)
		this.WinHttpRequest.SetRequestHeader("Content-Type", "text/plain")
	}

	translate(query, srcLang := "auto", dstLang := "en") {
		this.WinHttpRequest.Send(Format(this.JSON_STR, query, srcLang, dstLang))
		Response := JSON.Load(this.WinHttpRequest.ResponseText)

		Result := []
		for each, Translation in Response.result.translations[1].beams
			Result.Push(Translation.postprocessed_sentence)

		return Result
	}

	print(Result) {
		for each, translation in Result
			res .= Format("{}. {}`n`n", A_Index, translation)

		MsgBox % res
	}
}
wyw
Posts: 89
Joined: 12 Dec 2015, 19:11

Re: Making this awesome Google Translate Script work for DeepL

01 Nov 2018, 05:39

Sorry for the late reply, but thank you very much swagfag for your helpful participation! Your way of dealing with translations is better than the other one. And fixes these two issues.
Nixcalo
Posts: 26
Joined: 06 Feb 2018, 04:24

Re: Making this awesome Google Translate Script work for DeepL

19 Jun 2019, 19:32

As of today, swagfag's script does not seem to be working. When pressing Q I only get an empty MsgBox.

And of course my autohotkey expertise level is millions of light-years away of even having an inkling of what this script does or how to solve it... I barely got to know that I needed a JSON.ahk library!!!

So something in the website must have changed, or the JSON call is no longer valid or has a different structure, but this is really interesting for me. Could you please look it up and see what's changed in the deepl website? I know many many people would be interested. Certainly me as well!!!

It might seem that this was using the free DeepL and now they have a paid API so they are blocking Access to www2.deepl.com? Certainly looks like that...
swagfag
Posts: 3087
Joined: 11 Jan 2017, 17:59

Re: Making this awesome Google Translate Script work for DeepL

21 Jun 2019, 12:46

nothing about the code needs changing
Image
this is after 2 tries, http 429 - too many requests. theyre probably monitoring for keyboard activity to verify ure actually typing the sentences there on their webpage, and restrict access whenever requests are just posted

they must have caught wind of the fact that there were probably hordes upon hordes of translators abusing this on the daily and seeing how this is now a commercial product apparently, well... u can put two and two together
shame
Nixcalo
Posts: 26
Joined: 06 Feb 2018, 04:24

Re: Making this awesome Google Translate Script work for DeepL

22 Jun 2019, 05:27

Hah hah,,, it seems clear enough. I don't think there are hordes of translators doing this, however, we are not THAT computer-savvy as a rule heh heh. However, I am a DeepL Pro user but I wouldn't know where to start to adapt this script, unfortunately. The only documentation I have been able to see is about POST requests, not JSON (not that I know anything about POST requests either... it's what I Just read in the DeepL page)

Anyway, thank you for your reply!

Return to “Ask For Help”

Who is online

Users browsing this forum: Google [Bot], wineguy and 228 guests