Jump to content
Velislav

Simple Google Translate

Recommended Posts

Hi, All!
I have wanted for a very long time to contribute with something to our community, not only to gain great ideas and examples from all of you guys! Respect for everything you have shared!

I don't pretend that this is something great but it works. At least for me. I have made search in this forum and couldn't find a solution so that's why I am sharing this with you:

Get's what it is in the clipboard and auto translate it to Bulgarian. You can always change the outcome language.

If you have better ideas, or ideas how to improve this code it would be great.

 

#include <IE.au3>

$translateText = clipget()

$textResault = TranslateFromGGL($translateText,"bg")

ConsoleWrite($textResault)

Func TranslateFromGGL($sTextToTranslate,$ToLanguageCode)


$URL = "https://translate.google.com/?um=1&ie=UTF-8&hl=en&client=tw-ob#view=home&op=translate&sl=auto&tl=" & $ToLanguageCode & "&text=" & $sTextToTranslate
Global $oIE = _IECreate($URL, 0, 0, 1)

$oTranslated = GetObj("span","class","tlid-translation translation",$oIE)
If @error Then
    $oIE.quit
    $TranslateFromGGL = "It was not able to translate your request"
    Exit
EndIf

Local $html = $oTranslated.innerText
If @error Then
    $TranslateFromGGL = "It was not able to trasnlate your request!"
Else
    $TranslateFromGGL = $html
EndIf
$oIE.quit

Return $TranslateFromGGL
EndFunc



Func GetObj($Tag, $Attribute, $AttributeValue, $oIE = $oIE)
    $aTags = _IETagNameGetCollection($oIE, $Tag)

    For $aTag In $aTags
        If StringLower($Attribute) = "innertext" Then
            If StringInStr($aTag.innerText, $AttributeValue) > 0 Then
                $GetObj = $aTag
                ExitLoop
            EndIf
        ElseIf StringLower($Attribute) = "class" Or StringLower($Attribute) = "classname" Then
            If StringInStr($aTag.classname, $AttributeValue) > 0 Then
                $GetObj = $aTag
                ;MsgBox("","","found" & $aTag.innerText)
                ExitLoop
            EndIf
        Else
            If StringInStr($aTag.getAttribute($Attribute), $AttributeValue) > 0 Then
                $GetObj = $aTag
                ExitLoop
            EndIf
        EndIf
    Next
    If $GetObj = "" Then

    Else
        Return $GetObj
    EndIf
EndFunc   ;==>GetObj

 

Share this post


Link to post
Share on other sites
Posted (edited)

Some time ago, I created a Q&D code snippet that uses the Microsoft.XMLHTTP object. However, the regular expression still needs some fine-tuning ;).

; Example :
; -> Source (engl.) : This is an English text to be translated into Italian.
; -> Result (ital.) : Questo è un testo inglese da tradurre in italiano.

Global $g_sMytext, $g_sFrom, $g_sTo, $g_Url, $g_oHTTP, $g_sData

$g_sMytext = "This is an English text to be translated into Italian."
$g_sFrom   = "en"
$g_sTo     = "it"
$g_Url     = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=" & $g_sFrom & "&tl=" & $g_sTo & "&dt=t&q=" & $g_sMytext
$g_oHTTP   = ObjCreate("Microsoft.XMLHTTP")
$g_oHTTP.Open("POST", $g_Url, False)
$g_oHTTP.Send()
$g_sData = StringRegExpReplace($g_oHTTP.ResponseText, '.*?\["(.*?)(?<!\\)"[^\[]*', "$1" & @CRLF)

ConsoleWrite("+ Source : " & $g_sMytext & @CRLF)
ConsoleWrite("> Result : " & $g_sData & @CRLF)

Language codes ->: https://developers.google.com/admin-sdk/directory/v1/languages

Edited by Musashi
typo

Musashi-C64.png

"In the beginning the Universe was created. This has made a lot of people very angry and been widely regarded as a bad move."

Share this post


Link to post
Share on other sites
Posted (edited)

@Velislav and @Musashi, Thank you for great ideas.

What if I use Inetread()? And regular expression is always a sour grape for me.
 

Global $g_sMytext, $g_sFrom, $g_sTo, $g_Url, $g_oHTTP, $g_sData
$g_sMytext = 'This is an English text to be translated into Italian.'
$g_sFrom   = "en"
$g_sTo     = "it"
$g_Url     = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=" & $g_sFrom & "&tl=" & $g_sTo & "&dt=t&q=" & $g_sMytext
$g_sData = BinaryToString(InetRead($g_Url), 4)
$g_sData = StringMid($g_sData, 5, StringInStr($g_sData, '","')-5) & @CRLF

ConsoleWrite("+ Source : " & $g_sMytext & @CRLF)
ConsoleWrite("> Result : " & $g_sData & @CRLF)

 

Edited by CYCho

Share this post


Link to post
Share on other sites
Posted (edited)
1 hour ago, CYCho said:

What if I use Inetread()? And regular expression is always a sour grape for me.

InetRead() itself is ok, but it does not seem to work with longer texts, because "," appears multiple times as a delimiter.

Global $g_sMytext, $g_sFrom, $g_sTo, $g_Url, $g_oHTTP, $g_sData

$g_sMytext  = 'This is an English text to be translated into Italian. ' & _
              'The Moderation team will do their best to act in fair and reasonable manner. Sanctions will ' & _
              'only be applied as a last resort and any action taken will be explained in the relevant thread. ' & _
              'If moderation action is taken, you will need to acknowledge this through a dialog or you ' & _
              'will be unable to post further in the forum. Please note that this dialog is not an agreement ' & _
              'that the warning was justified - it is only there so that members are aware that moderation ' & _
              'action has been taken and that they may have certain restrictions applied to their account. ' & _
              'If you feel that you have been unfairly moderated then contact the Moderator concerned - ' & _
              'using a PM or the "Report" button is preferable to opening a new thread (although new members '  & _
              'may have to do this). But do be aware that the Moderation team has the final word - the rules ' & _
              'are set out by the site owner and you are only welcome here if you respect his wishes.'

$g_sFrom   = "en"
$g_sTo     = "it"
$g_Url     = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=" & $g_sFrom & "&tl=" & $g_sTo & "&dt=t&q=" & $g_sMytext
ConsoleWrite("+ Source : " & @CRLF & $g_sMytext & @CRLF)

; Variation 1 :
$g_oHTTP   = ObjCreate("Microsoft.XMLHTTP")
$g_oHTTP.Open("POST", $g_Url, False)
$g_oHTTP.Send()
$g_sData = StringRegExpReplace($g_oHTTP.ResponseText, '.*?\["(.*?)(?<!\\)"[^\[]*', "$1" & @CRLF)
ConsoleWrite("> Result Musashi : " & @CRLF & $g_sData & @CRLF)

ConsoleWrite("! -------------------------------------------------------------- " & @CRLF)

; Variation by CYCho :
$g_sData = BinaryToString(InetRead($g_Url), 4)
$g_sData = StringMid($g_sData, 5, StringInStr($g_sData, '","')-5) & @CRLF
ConsoleWrite("> Result CYCho : " & @CRLF & $g_sData & @CRLF)

We need a better RegEx :lol:.

EDIT : Result from Google (in both cases) :

Spoiler

[[["Questo è un testo inglese da tradurre in italiano. ","This is an English text to be translated into Italian.",null,null,3,null,null,null,[[["eac5d28c1f1511d513db14f24eb56870","tea_en_it_2019q2.md"]
]
]
]
,["Il team di moderazione farà del proprio meglio per agire in modo equo e ragionevole. ","The Moderation team will do their best to act in fair and reasonable manner.",null,null,3,null,null,null,[[["eac5d28c1f1511d513db14f24eb56870","tea_en_it_2019q2.md"]
]
]
]
,["Le sanzioni verranno applicate solo come ultima risorsa e qualsiasi azione intrapresa verrà spiegata nel relativo thread. ","Sanctions will only be applied as a last resort and any action taken will be explained in the relevant thread.",null,null,3,null,null,null,[[["eac5d28c1f1511d513db14f24eb56870","tea_en_it_2019q2.md"]
]
]
]
,["Se viene intrapresa un'azione di moderazione, sarà necessario riconoscerlo tramite una finestra di dialogo o non sarà possibile pubblicare ulteriori post nel forum. ","If moderation action is taken, you will need to acknowledge this through a dialog or you will be unable to post further in the forum.",null,null,3,null,null,null,[[["eac5d28c1f1511d513db14f24eb56870","tea_en_it_2019q2.md"]
]
]
]
,["Si noti che questa finestra di dialogo non è un accordo sul fatto che l'avvertimento era giustificato: è solo lì che i membri sono consapevoli che sono state prese misure di moderazione e che possono avere alcune restrizioni applicate al proprio account. ","Please note that this dialog is not an agreement that the warning was justified - it is only there so that members are aware that moderation action has been taken and that they may have certain restrictions applied to their account.",null,null,3,null,null,null,[[["eac5d28c1f1511d513db14f24eb56870","tea_en_it_2019q2.md"]
]
]
]
,["Se ritieni di essere stato moderato ingiustamente, contatta il moderatore interessato - è preferibile utilizzare un PM o il pulsante \"Segnala\" per aprire una nuova discussione (anche se i nuovi membri potrebbero doverlo fare). ","If you feel that you have been unfairly moderated then contact the Moderator concerned - using a PM or the \"Report\" button is preferable to opening a new thread (although new members may have to do this).",null,null,3,null,null,null,[[["eac5d28c1f1511d513db14f24eb56870","tea_en_it_2019q2.md"]
]
]
]
,["Ma tieni presente che il team di moderazione ha l'ultima parola: le regole sono stabilite dal proprietario del sito e sei il benvenuto qui solo se rispetti i suoi desideri.","But do be aware that the Moderation team has the final word - the rules are set out by the site owner and you are only welcome here if you respect his wishes.",null,null,3,null,null,null,[[["eac5d28c1f1511d513db14f24eb56870","tea_en_it_2019q2.md"]
]
]
]
]
,null,"en",null,null,null,null,[]
]

 

 

Edited by Musashi

Musashi-C64.png

"In the beginning the Universe was created. This has made a lot of people very angry and been widely regarded as a bad move."

Share this post


Link to post
Share on other sites

Since the Google translator seems to pass a JSON structure, here is a solution using the JSON UDF by @AspirinJunkie . Maybe not the most elegant implementation (by me ;)), but seems to work.

#include <Array.au3>
#include "Json.au3" ; by @AspirinJunkie

Global $g_sMytext, $g_sFrom, $g_sTo, $g_Url, $g_oHTTP, $g_JSONData, $g_aData, $g_sResponse, $g_sOutput

$g_sMytext  = 'This is an English text to be translated into French. ' & _
              'The Moderation team will do their best to act in fair and reasonable manner. Sanctions will ' & _
              'only be applied as a last resort and any action taken will be explained in the relevant thread. ' & _
              'If moderation action is taken, you will need to acknowledge this through a dialog or you ' &  _
              'will be unable to post further in the forum. Please note that this dialog is not an agreement ' & _
              'that the warning was justified - it is only there so that members are aware that moderation ' & _
              'action has been taken and that they may have certain restrictions applied to their account. ' & _
              'If you feel that you have been unfairly moderated then contact the Moderator concerned - ' & _
              'using a PM or the "Report" button is preferable to opening a new thread (although new members '  & _
              'may have to do this). But do be aware that the Moderation team has the final word - the rules ' & _
              'are set out by the site owner and you are only welcome here if you respect his wishes.'

$g_sFrom   = "en"
$g_sTo     = "fr"
$g_Url     = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=" & $g_sFrom & "&tl=" & $g_sTo & "&dt=t&q=" & $g_sMytext
$g_oHTTP   = ObjCreate("Microsoft.XMLHTTP")
$g_oHTTP.Open("POST", $g_Url, False)
$g_oHTTP.Send()
$g_sResponse = $g_oHTTP.ResponseText

$g_JSONData = _JSON_Parse($g_sResponse)
If VarGetType($g_JSONData) = 'Array' Then
    $g_aData = $g_JSONData[0]
    If VarGetType($g_aData) = 'Array' Then
        For $i = 0 To UBound($g_aData) -1 Step 1
            $g_sOutput &= ($g_aData[$i])[0] & @CRLF
        Next
        ConsoleWrite("+ Translated >>>>> : " & @CRLF & $g_sOutput & @CRLF)
    EndIf
EndIf

 

JSON.au3


Musashi-C64.png

"In the beginning the Universe was created. This has made a lot of people very angry and been widely regarded as a bad move."

Share this post


Link to post
Share on other sites

Brief question : Does my example with JSON work satisfactorily for you ?


Musashi-C64.png

"In the beginning the Universe was created. This has made a lot of people very angry and been widely regarded as a bad move."

Share this post


Link to post
Share on other sites

@Musashi, It works fine with me. First I used the  Json.au3 which I was using for WebDriver UDF  and it failed. Later I found that it was a different one with same name. With the new file it works fine.

I don't know how many variations there could be in Google API's return strings, but, assuming that it would be same format as this one, the following code works for me, too. Please take a look and see if there are any problems I don't see. As an amateur who started learning AutoIt at a pretty old age, I am always amazed at your expertise. Thank you for sharing your knowledge.

Global $g_sMytext, $g_sFrom, $g_sTo, $g_Url, $g_oHTTP, $g_sData, $g_aData, $g_sResult
$g_sMytext = 'This is an English text to be translated into Italian. ' & _
              'The Moderation team will do their best to act in fair and reasonable manner. Sanctions will ' & _
              'only be applied as a last resort and any action taken will be explained in the relevant thread. ' & _
              'If moderation action is taken, you will need to acknowledge this through a dialog or you ' & _
              'will be unable to post further in the forum. Please note that this dialog is not an agreement ' & _
              'that the warning was justified - it is only there so that members are aware that moderation ' & _
              'action has been taken and that they may have certain restrictions applied to their account. ' & _
              'If you feel that you have been unfairly moderated then contact the Moderator concerned - ' & _
              'using a PM or the "Report" button is preferable to opening a new thread (although new members '  & _
              'may have to do this). But do be aware that the Moderation team has the final word - the rules ' & _
              'are set out by the site owner and you are only welcome here if you respect his wishes.'
$g_sFrom   = "en"
$g_sTo     = "it"
$g_Url     = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=" & $g_sFrom & "&tl=" & $g_sTo & "&dt=t&q=" & $g_sMytext
$g_sData   = BinaryToString(InetRead($g_Url), 4)
$g_sData   = StringRegExpReplace($g_sData, ',null,null.+md"', "")
$g_aData   = StringRegExp($g_sData, '\["(.*?)","', 3)

For $i = 0 To UBound($g_aData)-1
    $g_sResult &= $g_aData[$i]
Next

ConsoleWrite("+ Source : " & $g_sMytext & @CRLF)
ConsoleWrite("> Result : " & $g_sResult & @CRLF)


 

Share this post


Link to post
Share on other sites
16 minutes ago, CYCho said:

Please take a look and see if there are any problems I don't see.

The result is almost the same. Exception : Areas with double quotation marks are masked by Google with \", and not adjusted by your code.

... "xxx" ... -> Google : ... \"xxx\" ...

But this can be easily filtered - apart from that, "Good Job" :lol: .

 

30 minutes ago, CYCho said:

First I used the  Json.au3 which I was using for WebDriver UDF  and it failed. Later I found that it was a different one with same name. With the new file it works fine.

Yes, the JSON UDF I use here was developed by @AspirinJunkie (a very respected member in the German forum, but not so active here)

Thread : https://autoit.de/thread/85435-json-udf/


Musashi-C64.png

"In the beginning the Universe was created. This has made a lot of people very angry and been widely regarded as a bad move."

Share this post


Link to post
Share on other sites
Posted (edited)

@Musashi, I found that your and my codes do a pretty good job in translating from English to Korean but not vice versa. It seems that when the source language is in double-byte characters the result text becomes illegible. This may be applicable to Chinese and Japanese, too. Do you know if Google has a different api url structure to handle oriental languages as source?

Edited by CYCho

Share this post


Link to post
Share on other sites
3 hours ago, CYCho said:

[...] good job in translating from English to Korean but not vice versa [...]

Do you know if Google has a different api url structure to handle oriental languages as source?

Hi CYCho ! (BTW : I had expected something like this already)

Just to give you a quick feedback : "No, sorry, I don't have a ready-to-use solution which means, I would have to do some research myself first. Unfortunately, I don't have the time for this at the moment, because I' m working on an urgent project. Other members may already know more about this problem. If I find the time, I will try to take a closer look at it over the next days."


Musashi-C64.png

"In the beginning the Universe was created. This has made a lot of people very angry and been widely regarded as a bad move."

Share this post


Link to post
Share on other sites
2 hours ago, CYCho said:

I found the solution. Encoding the source text did the trick.

Yes, there may be other options, but I can confirm that this works 👍.
Korean text : 한국어로 번역 할 영어 텍스트입니다. (hangug-eolo beon-yeog hal yeong-eo tegseuteu-ibnida.)
English translation : English text to translate into Korean.


Musashi-C64.png

"In the beginning the Universe was created. This has made a lot of people very angry and been widely regarded as a bad move."

Share this post


Link to post
Share on other sites
Posted (edited)

I found a new, simpler way of encoding URI.
 

$sText    = ClipGet()

$sText = StringReplace($sText, Chr(13), "")
$s1 = StringToBinary($sText, 4)
$sSource = ""
For $j = 1 To BinaryLen($s1)
    $sSource &= "%" & StringTrimLeft(BinaryMid($s1, $j, 1), 2)
Next

$sFrom = "en"
$sTo   = "ko"
$sUrl  = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=" & $sFrom & "&tl=" & $sTo & "&dt=t&q=" & $sSource
$sData = BinaryToString(InetRead($sUrl), 4)
$aData = StringSplit($sData, "]", 1)
$sResult = ""
For $i = 1 To $aData[0]
    $s1 = StringStripWS($aData[$i], 3)
    If StringLeft($s1, 4) = '[[["' Or StringLeft($s1, 3) = ',["' Then
        $s1 = StringMid($s1, StringInStr($s1, '"')+1)
        $s1 = StringLeft($s1, StringInStr($s1, '","')-1)
        $n1 = 0
        While StringInStr($s1, "\n")
            $s1 = StringReplace($s1, "\n", "")
            $n1 += 1
        WEnd
        For $j = 1 To $n1
            $s1 = $s1 & " " & @CRLF
        Next
        $sResult &= $s1 & " " & @CRLF
    EndIf
Next
$sResult = StringReplace(StringLeft($sResult, StringLen($sResult)-3), '\"', '"')

ConsoleWrite("+ Source : " & $sText & @CRLF)
ConsoleWrite("> Result : " & $sResult & @CRLF)

ClipPut($sResult)

 

Edited by CYCho

Share this post


Link to post
Share on other sites

Guys! You are awesome! This is so great! 

I really like @CYCho solution!

I am thinking about to receive all suggestions for the current translation. Do you think it is possible? To store all other suggestions for translating the requested word in an array? If you can do it I can try to help with GUI interface :) to choose which one is the best one for the user!

Share this post


Link to post
Share on other sites
Posted (edited)

@Velislav How are you? I hope you and your love ones are alright.

A Korean portal, Naver.com, has a translation service called Papago. Their menu covers 15 languages. Unfortunately, however, they do not service Bulgarian. Anyway, I am writing a code to work with this website. Even though they have an api service, it requires a user key which can be obtained only after registration. So I plan to access their service through a hidden IE object as follows. Here I have a favour to ask of you. Please run the following code and upload the resulting HTML body text. They must be producing different results depending on the locale of the Windows. In fact I would appreciate if anyone reading this post could do the same for me.
 

#include <IE.au3>

$sText = "This is a sample text to be translated to German."

$s1 =StringToBinary($sText, 4)
$sSource = ""
For $j = 1 To BinaryLen($s1)
    $sSource &= "%" & StringTrimLeft(BinaryMid($s1, $j, 1), 2)
Next

$sFrom = "auto"
$sTo = "de"

$sResult = ""
$sUrl = "https://papago.naver.com/?sk=" & $sFrom & "&tk=" & $sTo & "&st=" & $sSource
$oIE = _IECreate($sUrl, 0, 0, 1)
Sleep(5000)
$sResult = _IEBodyReadText($oIE)
_IEQuit($oIE)
MsgBox(0, "Papago", $sResult)

ClipPut($sResult)


 

Edited by CYCho

Share this post


Link to post
Share on other sites
Posted (edited)

huh... very cool... you guys get me kinda interested... here's with the gui setup, though unfinished... dunno if I'll work on it more, but it does work as-is (at least for the AF language anyways) this is designed to copy the source text and then translate multiple languages at once when set with the combobox(once you set the comboboxes up)
711100.jpg.8e40270e0c4799ae24fe5a8bd22bd81d.jpg

#include <Array.au3>

Global $FromCombo1
Global $ToCombo1
Global $FromComboData1
Global $ToComboData1

Global $aArray[5][2] = [["--English--", "EN"], ["(Afan) Oromo", "OM"], ["Abkhazian", "AB"], ["Afar", "AA"], ["Afrikaans", "AF"]]
$sList = ""
For $i = 0 To UBound($aArray,1) -1
    $sList &= "|" & $aArray[$i][0]
Next

GUICreate("GUItest", 450, 300, @DesktopWidth/2, @DesktopHeight/2)

GUICtrlCreateGroup("Source",7,1,85,285)
GUICtrlCreateGroup("Output",232,1,85,285)

$FromCombo1 = GUICtrlCreateCombo("--From-->", 95, 15, 65, 18)
GUICtrlSetData($FromCombo1, $sList)
$Source1 = GUICtrlCreateInput("",10,15,80,21)
$ToCombo1 = GUICtrlCreateCombo("--To-->", 165, 15, 65, 18)
GUICtrlSetData($ToCombo1, $sList)
$Output1 = GUICtrlCreateInput("",235,15,80,21)
$Go1 = GUICtrlCreateButton("Go", 320,14,25,23)
GUICtrlSetTip($Go1, "Translate")
$CopySource1 = GUICtrlCreateButton("Copy Source", 355,14,75,23)
GUICtrlSetTip($CopySource1, "Transl. from the source, to all other sources by their respective languages")

$2 = GUICtrlCreateInput("",10,50,80,18)
$3 = GUICtrlCreateInput("",10,70,80,18)
$4 = GUICtrlCreateInput("",10,90,80,18)
$5 = GUICtrlCreateInput("",10,110,80,18)
$6 = GUICtrlCreateInput("",10,130,80,18)
$7 = GUICtrlCreateInput("",10,150,80,18)
$8 = GUICtrlCreateInput("",10,170,80,18)

$fLangLabel1 = GUICtrlCreateLabel("", 300, 80, 50, 20)
$tLangLabel1 = GUICtrlCreateLabel("", 300, 100, 50, 20)

;GUICtrlCreateCombo
;GUICtrlCreateCombo
GUISetState(@SW_SHOW)

While 1
    SwitchCheck()
WEnd

Func SwitchCheck()
        Switch GUIGetMsg()
        Case -3
            Exit
        Case $FromCombo1
            $sName = GUICtrlRead($FromCombo1)
            $iIndex = _ArraySearch($aArray, $sName)
            If Not @error Then
              GUICtrlSetData($fLangLabel1, $aArray[$iIndex][1])
              $FromComboData1 = GUICtrlRead($fLangLabel1)
            EndIf
        Case $ToCombo1
            $sName = GUICtrlRead($ToCombo1)
            $iIndex = _ArraySearch($aArray, $sName)
            If Not @error Then
                GUICtrlSetData($tLangLabel1, $aArray[$iIndex][1])
                $ToComboData1 = GUICtrlRead($tLangLabel1)
            EndIf
        Case $Go1
            $Translate1 = GUICtrlRead($Source1)
            $Url = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=" & $FromComboData1 & "&tl=" & $ToComboData1 & "&dt=t&q=" & $Translate1
            $URLData = BinaryToString(InetRead($Url), 4)
            $URLOutput1 = StringMid($URLData, 5, StringInStr($URLData, '","')-5) & @CRLF
            GUICtrlSetData($Output1, $URLOutput1)
        Case $CopySource1
            $SourceRead1 = GUICtrlRead($Source1)
            GUICtrlSetData($2, $SourceRead1);temp
            GUICtrlSetData($3, $SourceRead1);temp
            GUICtrlSetData($4, $SourceRead1);temp
            GUICtrlSetData($5, $SourceRead1);temp
            GUICtrlSetData($6, $SourceRead1);temp
            GUICtrlSetData($7, $SourceRead1);temp
            GUICtrlSetData($8, $SourceRead1);temp
            GUISetState(@SW_SHOW)
    EndSwitch
EndFunc

;---------------------------------------A
;(Afan) Oromo   om
;Abkhazian  ab
;Afar   aa
;Afrikaans  af
;Albanian   sq
;Amharic    am
;Arabic ar
;Armenian   hy
;Assamese   as
;Aymara ay
;Azerbaijani    az
;---------------------------------------B
;Bashkir    ba
;Basque eu
;Bengali    bn
;Bhutani    dz
;Bihari bh
;Bislama    bi
;Breton br
;Bulgarian  bg
;Burmese    my
;Byelorussian   be
;---------------------------------------C
;Cambodian  km
;Catalan    ca
;Chinese    zh
;Corsican   co
;Croatian   hr
;Czech  cs
;---------------------------------------D
;Danish da
;Dutch  nl
;---------------------------------------E
;English    en
;Esperanto  eo
;Estonian   et
;---------------------------------------F
;Faeroese   fo
;Fiji   fj
;Finnish    fi
;French fr
;Frisian    fy
;---------------------------------------G
;Galician   gl
;Georgian   ka
;German de
;Greek  el
;Greenlandic    kl
;Guarani    gn
;Gujarati   gu
;---------------------------------------H
;Hausa  ha
;Hebrew (former iw) he
;Hindi  hi
;Hungarian  hu
;---------------------------------------I
;Icelandic  is
;Indonesian (former in) id
;Interlingua    ia
;Interlingue    ie
;Inupiak    ik
;Inuktitut (Eskimo) iu
;Irish  ga
;Italian    it
;---------------------------------------J
;Japanese   ja
;Javanese   jw
;---------------------------------------K
;Kannada    kn
;Kashmiri   ks
;Kazakh kk
;Kinyarwanda    rw
;Kirghiz    ky
;Kirundi    rn
;Korean ko
;Kurdish    ku
;---------------------------------------L
;Laothian   lo
;Latin  la
;Latvian, Lettish   lv
;Lingala    ln
;Lithuanian lt
;---------------------------------------M
;Macedonian mk
;Malagasy   mg
;Malay  ms
;Malayalam  ml
;Maltese    mt
;Maori  mi
;Marathi    mr
;Moldavian  mo
;Mongolian  mn
;---------------------------------------N
;Nauru  na
;Nepali ne
;Norwegian  no
;---------------------------------------O
;Occitan    oc
;Oriya  or
;---------------------------------------P
;Pashto, Pushto ps
;Persian    fa
;Polish pl
;Portuguese pt
;Punjabi    pa
;---------------------------------------Q
;Quechua    qu
;---------------------------------------R
;Rhaeto-Romance rm
;Romanian   ro
;Russian    ru
;---------------------------------------S
;Samoan sm
;Sangro sg
;Sanskrit   sa
;Scots Gaelic   gd
;Serbian    sr
;Serbo-Croatian sh
;Sesotho    st
;Setswana   tn
;Shona  sn
;Sindhi sd
;Singhalese si
;Siswati    ss
;Slovak sk
;Slovenian  sl
;Somali so
;Spanish    es
;Sudanese   su
;Swahili    sw
;Swedish    sv
;---------------------------------------T
;Tagalog    tl
;Tajik  tg
;Tamil  ta
;Tatar  tt
;Tegulu te
;Thai   th
;Tibetan    bo
;Tigrinya   ti
;Tonga  to
;Tsonga ts
;Turkish    tr
;Turkmen    tk
;Twi    tw
;---------------------------------------U
;Uigur  ug
;Ukrainian  uk
;Urdu   ur
;Uzbek  uz
;---------------------------------------V
;Vietnamese vi
;Volapuk    vo
;---------------------------------------W
;Welch  cy
;Wolof  wo
;---------------------------------------X
;Xhosa  xh
;---------------------------------------Y
;Yiddish (former ji)    yi
;Yoruba yo
;---------------------------------------Z
;Zhuang za
;Zulu   zu


anyone know how to install languages for kanji and such? otherwise languages display as blank when translated

anyways, feel free to use it.. just need to add a bunch more languages onto the array, and change the array to match how many sequences there are... Global $aArray[6][2] when adding one new language etc... counting them up is gonna be a pain lol
just keep setting GUICtrlSetData($variable, $sList) per each new instance of GUICtrlCreateCombo. using arrays is way easier than making individual functions

 

 

I'd love to know if you edit your original code, I'm sure it'll be awesome

Edited by HankHell

Share this post


Link to post
Share on other sites
Quote

@musashi


; Example :
; -> Source (engl.) : This is an English text to be translated into Italian.
; -> Result (ital.) : Questo è un testo inglese da tradurre in italiano.

Global $g_sMytext, $g_sFrom, $g_sTo, $g_Url, $g_oHTTP, $g_sData

$g_sMytext = "This is an English text to be translated into Italian."
$g_sFrom   = "en"
$g_sTo     = "it"
$g_Url     = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=" & $g_sFrom & "&tl=" & $g_sTo & "&dt=t&q=" & $g_sMytext
$g_oHTTP   = ObjCreate("Microsoft.XMLHTTP")
$g_oHTTP.Open("POST", $g_Url, False)
$g_oHTTP.Send()
$g_sData = StringRegExpReplace($g_oHTTP.ResponseText, '.*?\["(.*?)(?<!\\)"[^\[]*', "$1" & @CRLF)

@Musashi 

 

 

You code is good but i have information from an excel sheet like C2 = Exampletext

 

$_read1 = _Excel_RangeRead($oWorkbook, "Redbubble" , "C"&$pop+$i)              ; CELL2 in the Sheet

$g_sMytext = $_read1

 

Translated:  Exampletext[[]]36578284562848325673sd3h4k

This weird number appears as a result at the end of the translation

Share this post


Link to post
Share on other sites
Posted (edited)
3 hours ago, JD943 said:

This weird number appears as a result at the end of the translation

You still use my first attempt, where I had already written, that the regular expression needs some fine-tuning ;). I was referring to those weird characters at the end of the translation.

Use a more recent version, such as :

#include "Json.au3" ; by @AspirinJunkie

Global $g_sMytext, $g_sFrom, $g_sTo, $g_Url, $g_oHTTP, $g_JSONData, $g_aData, $g_sResponse, $g_sOutput
$g_sMytext = 'This is an English text to be translated into Italian. ' & _
              'The Moderation team will do their best to act in fair and reasonable manner. Sanctions will ' & _
              'only be applied as a last resort and any action taken will be explained in the relevant thread. ' & _
              'If you feel that you have been unfairly moderated then contact the Moderator concerned - ' & _
              'using a PM or the "Report" button is preferable to opening a new thread (although new members '  & _
              'may have to do this). But do be aware that the Moderation team has the final word - the rules ' & _
              'are set out by the site owner and you are only welcome here if you respect his wishes.'

$g_sFrom   = "en"
$g_sTo     = "it"
$g_Url     = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=" & $g_sFrom & "&tl=" & $g_sTo & "&dt=t&q=" & $g_sMytext
$g_oHTTP   = ObjCreate("Microsoft.XMLHTTP")
$g_oHTTP.Open("POST", $g_Url, False)
$g_oHTTP.Send()
$g_sResponse = $g_oHTTP.ResponseText

$g_JSONData = _JSON_Parse($g_sResponse)
If VarGetType($g_JSONData) = 'Array' Then
    $g_aData = $g_JSONData[0]
    If VarGetType($g_aData) = 'Array' Then
        For $i = 0 To UBound($g_aData) -1 Step 1
            $g_sOutput &= ($g_aData[$i])[0] ;*** & @CRLF
        Next
        ConsoleWrite("+ Translated >>>>> : " & @CRLF & $g_sOutput & @CRLF)
    EndIf
EndIf

You need the attached Json.au3 !

How does the translated text from your Excel spreadsheet look now? Please post the result of the SciTE console.

EDIT :

The Google API apparently does not recognize the combined word "exampletext" as valid, and returns it directly. But if you use "example text" , then the translation is "Testo di esempio". Here the API seems to differ from the translation done by the Google website. 

JSON.au3

Edited by Musashi

Musashi-C64.png

"In the beginning the Universe was created. This has made a lot of people very angry and been widely regarded as a bad move."

Share this post


Link to post
Share on other sites
Global $g_sMytext, $g_sFrom, $g_sTo, $g_Url, $g_oHTTP, $g_JSONData, $g_aData, $g_sResponse, $g_sOutput
$g_sMytext = $_read1

$g_sFrom   = "en"
$g_sTo     = "de"
$g_Url     = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=" & $g_sFrom & "&tl=" & $g_sTo & "&dt=t&q=" & $g_sMytext
$g_oHTTP   = ObjCreate("Microsoft.XMLHTTP")
$g_oHTTP.Open("POST", $g_Url, False)
$g_oHTTP.Send()
$g_sResponse = $g_oHTTP.ResponseText

$g_JSONData = _JSON_Parse($g_sResponse)
If VarGetType($g_JSONData) = 'Array' Then
    $g_aData = $g_JSONData[0]
    If VarGetType($g_aData) = 'Array' Then
        For $i = 0 To UBound($g_aData) -1 Step 1
            $g_sOutput &= ($g_aData[$i])[0] ;*** & @CRLF
        Next
        ConsoleWrite("+ Translated >>>>> : " & @CRLF & $g_sOutput & @CRLF)
    EndIf
EndIf


@Musashi Thank you for this code. this is working fine! I am completely new to autoit. Can you tell me how i can make a smart code for entering different translations for an uploading process.

 

I want to fill three lines for each translation with three different translations.

I have $_read1, $_read2 and $_read3 which must be translated in DE, FRA, ES.

 

I have a big problems with the variables. I cannot copy it one-by-one. If im only editing different names for $g_sOutput and $g_sMyTest its not working.

 

EXAMPLE:

 

#region Translate $_read1 to german
Send("{TAB}")
#region Translate $_read2 to german
Send("{TAB}")
#region Translate $_read3 to german
Mouseclick( EXAMPLE COORDINATE , 1 )

#region Translate $_read1 to francais
Send("{TAB}")
#region .... repeat with francais and espanol

I'm very thankful for your help!

 

Share this post


Link to post
Share on other sites
1 hour ago, JD943 said:

I have $_read1, $_read2 and $_read3 which must be translated in DE, FRA, ES.

I have moved the translation into a function. Now you should get the different translations easier ;).

#include "Json.au3" ; (by @AspirinJunkie)

Global $sRead1 = "This text will be translated into another language."
ConsoleWrite("! >> ORIGINAL: " & $sRead1 & @CRLF)
ConsoleWrite("> >> EN->DE  : " & _GoogleAPITranslate($sRead1, "en", "de") & @CRLF)
ConsoleWrite("> >> EN->FR  : " & _GoogleAPITranslate($sRead1, "en", "fr") & @CRLF)
ConsoleWrite("> >> EN->ES  : " & _GoogleAPITranslate($sRead1, "en", "es") & @CRLF)

; ------------ Function : ---------------
Func _GoogleAPITranslate($sMytext, $sFrom, $sTo)
    Local $sUrl, $oHTTP, $sResponse, $JSONData, $sOutput = "", $aData
    $sUrl  = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=" & $sFrom & "&tl=" & $sTo & "&dt=t&q=" & $sMytext
    $oHTTP = ObjCreate("Microsoft.XMLHTTP")
    $oHTTP.Open("POST", $sUrl, False)
    $oHTTP.Send()
    $sResponse = $oHTTP.ResponseText
    $JSONData = _JSON_Parse($sResponse)
    If VarGetType($JSONData) = 'Array' Then
        $aData = $JSONData[0]
        If VarGetType($aData) = 'Array' Then
            For $i = 0 To UBound($aData) -1 Step 1
                $sOutput &= ($aData[$i])[0] ;*** & @CRLF
            Next
        EndIf
    EndIf
    Return $sOutput
EndFunc  ;==>_GoogleAPITranslate

 


Musashi-C64.png

"In the beginning the Universe was created. This has made a lot of people very angry and been widely regarded as a bad move."

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...