Jump to content

Simple Google Translate


Velislav
 Share

Recommended Posts

2 hours ago, Deye said:

@Musashi, is it still working for you ?

Yes !

Here the script with a longer text :

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

Global $sRead1 = 'This text will be translated into another language. ' & _
                 '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.'


ConsoleWrite("+ >> ORIGINAL: " & $sRead1 & @CRLF)
ConsoleWrite("+ ------------------------------------------------------------------------------ " & @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

Result :

Spoiler

+ >> ORIGINAL: This text will be translated into another language. 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.
+ ------------------------------------------------------------------------------
> >> EN->DE  : Dieser Text wird in eine andere Sprache übersetzt. Das Moderationsteam wird sein Bestes tun, um fair und angemessen zu handeln. Sanktionen werden nur als letztes Mittel verhängt und alle ergriffenen Maßnahmen werden im entsprechenden Thread erläutert. Wenn Sie das Gefühl haben, dass Sie zu Unrecht moderiert wurden, wenden Sie sich an den betreffenden Moderator – per PN oder über die Schaltfläche „Melden“ ist das Eröffnen eines neuen Threads vorzuziehen (obwohl neue Mitglieder dies möglicherweise tun müssen). Aber seien Sie sich bewusst, dass das Moderationsteam das letzte Wort hat – die Regeln werden vom Websitebesitzer festgelegt und Sie sind hier nur willkommen, wenn Sie seine Wünsche respektieren.
> >> EN->FR  : Ce texte sera traduit dans une autre langue. L'équipe de modération fera de son mieux pour agir de manière juste et raisonnable. Les sanctions ne seront appliquées qu'en dernier recours et toute mesure prise sera expliquée dans le fil de discussion correspondant. Si vous estimez que vous avez été injustement modéré, contactez le modérateur concerné - l'utilisation d'un MP ou du bouton "Signaler" est préférable à l'ouverture d'un nouveau fil (bien que les nouveaux membres puissent être amenés à le faire). Mais sachez que l'équipe de modération a le dernier mot - les règles sont définies par le propriétaire du site et vous n'êtes le bienvenu ici que si vous respectez ses souhaits.
> >> EN->ES  : Este texto será traducido a otro idioma. El equipo de moderación hará todo lo posible para actuar de manera justa y razonable. Las sanciones solo se aplicarán como último recurso y cualquier acción tomada se explicará en el hilo correspondiente. Si cree que ha sido moderado injustamente, comuníquese con el Moderador en cuestión; es preferible usar un PM o el botón "Informar" que abrir un nuevo hilo (aunque es posible que los nuevos miembros tengan que hacerlo). Pero tenga en cuenta que el equipo de moderación tiene la última palabra: las reglas las establece el propietario del sitio y solo es bienvenido si respeta sus deseos.

 

 

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."

Link to comment
Share on other sites

  • 6 months later...

Can this be used to translate an English GUI?

For instance, A Label text such as, GUICtrlCreateLabel('Hello', 350, 175, 145, 18) and a button, and a checkbox and so on?

If so, an example would be appreciated as I am having a hard time wrapping my head around its usage as such.

Edited by Shark007
Link to comment
Share on other sites

On 3/1/2023 at 10:20 AM, musicstashall said:

Friends, how do I get a list of all supported languages from Google in this form:
["ps","Pashto"]
...
Then create a two-dimensional array from this.

@musicstashall

Why do you need the intermediate form ["code", "language"] and the array?  The example script below does happen to create that intermediate form, but it is only generated in an intermediate step while filtering the JSON in order to create a TSV list, which is then used to create the 2D AutoIt array.  As you can see in the image below, part of the example script's jq filter produces your intermediate result.  The only difference between the filter in the image and the filter in the script is the last part, "@tsv", which converts the JSON arrays to a TSV list.

image.png.efb495dfc59a7587f9cb9085fde5c22c.png

Example script below:

Spoiler

The comments in the example below should be sufficient to understand how it got the result.

Example script:

#AutoIt3Wrapper_AU3Check_Parameters=-w 3 -w 4 -w 5 -w 6 -d

#include <Constants.au3>
#include <Array.au3>
#include <xml2json\xml2json.au3> ;https://www.autoitscript.com/forum/topic/208932-xml2json-udf-transform-xml-to-json/
#include <jq\jq.au3>             ;https://www.autoitscript.com/forum/files/file/502-jq-udf-a-powerful-flexible-json-processor/

Const $JQ_EXE   = "C:\Utils\jq\jq-win64.exe", _ ;Modify path as needed
      $LANG_URL = "https://cloud.google.com/translate/docs/languages"


example()

Func example()
    Const $JQ_FILTER = _
        '#For each table row'                        & @CRLF & _
        '.tbody.tr[]'                                & @CRLF & _
        ''                                           & @CRLF & _
        '| #Create an array with [code, language]'   & @CRLF & _
        '['                                          & @CRLF & _
        '  #if language has array of codes'          & @CRLF & _
        '  if (.td[1].code | type) == "array" then'  & @CRLF & _
        '    #Get first code'                        & @CRLF & _
        '    .td[1].code[0].text'                    & @CRLF & _
        '  else'                                     & @CRLF & _
        '    #Get code'                              & @CRLF & _
        '    .td[1].code.text'                       & @CRLF & _
        '  end, '                                    & @CRLF & _
        ''                                           & @CRLF & _
        '  #Get language'                            & @CRLF & _
        '  .td[0].td'                                & @CRLF & _
        ']'                                          & @CRLF & _
        ''                                           & @CRLF & _
        '| #Convert arrays into TSV list'            & @CRLF & _
        '@tsv'


    Local $sJson      = "", _
          $sWebpage   = "", _
          $sLangTable = "", _
          $sOutput    = ""

    Local $aResult

    Local $hTimer


    $hTimer = TimerInit() ;Start timer

    ;Get web page (Use whatever method works for you COM, cURL, Inet*, etc.)
    $sWebpage = InetRead($LANG_URL)
    If @error Then Exit MsgBox($MB_ICONERROR, "InetRead Error", "@error = " & @error)
    $sWebpage = BinaryToString($sWebpage, $SB_UTF8)

    ConsoleWrite("Time to get webpage         = " & StringFormat("%.3f seconds", TimerDiff($hTimer) / 1000) & @CRLF)

    $hTimer = TimerInit() ;Reset timer

    ;Extract table body from the webpage
    $aResult = StringRegExp($sWebpage, '(?s)<tbody>.*?</tbody>', $STR_REGEXPARRAYMATCH)
    If @error Then Exit MsgBox($MB_ICONERROR, "StringRegExp Error", "@error = " & @error)
    $sLangTable = $aResult[0]

    ;Convert XML (HTML) table to JSON
    $sJson = _Xml2Json($sLangTable)
    If @error Then Exit MsgBox($MB_ICONERROR, "Error", "xml2json failed with @error = " & @error)

    ;Query JSON for TSV list of languages
    _jqInit($JQ_EXE)
    If @error Then Exit MsgBox($MB_ICONERROR, "_jqInit Error", "@error = " & @error)

    $sOutput = _jqExec($sJson, $JQ_FILTER)
    If @error Then Exit MsgBox($MB_ICONERROR, "_jqExec Error", "@error = " & @error)

    ;Convert TSV list to array
    ReDim $aResult[0][2]
    _ArrayAdd($aResult, $sOutput, 0, @TAB)
    If @error Then Exit MsgBox($MB_ICONERROR, "_ArrayAdd Error", "@error = " & @error)

    ;Display elapsed time
    ConsoleWrite("Time to parse & build array = " & StringFormat("%.3f seconds", TimerDiff($hTimer) / 1000) & @CRLF)

    ;Display array
    _ArrayDisplay($aResult, "Supported Languages", "", 0, Default, "Code|Language")
EndFunc

Console Output:

Time to get webpage         = 0.611 seconds
Time to parse & build array = 0.062 seconds

Array:

image.png.29178dbc5eb97952702604b38eb42403.png

 

 

 

Edited by TheXman
Corrected typos in comments
Link to comment
Share on other sites

On 3/2/2023 at 11:35 PM, TheXman said:

Why do you need the intermediate form ["code", "language"] and the array?

Combobox with images of flags of countries are created in my application. Actually, the language of the source and target is selected in the combobox. Your option is not entirely satisfactory, because the page you are parsing has a limited number of display languages. I need to be able to see the page in different languages, respectively, and have the array in different languages too. Try to extract the necessary data from these pages:

$sUrl  = 'https://translate.google.com/?hl=en'
$sUrl  = 'https://translate.google.com/?hl=ru'

Interested in this line:

Spoiler

 

initAft()</script><script id="_ij" nonce="4yDHP_r0rw-pqOulC-d5Rw">window.IJ_values = ['https:\/\/translate.google.com\/about\/?hl\x3dru', true ,[null,null,"",false,null,null,null,false],'0', true ,'https:\/\/translate.google.com\/', null ,'boq_translate-webserver_20230301.07_p0','translate.google.com', 300.0 , false , 0.0 ,'','4yDHP_r0rw-pqOulC-d5Rw','6qmsELr-WxSax3p_nycqWg','DEFAULT','', 2023.0 ,'https:\/\/translate.google.com\/', null ,[["af","ar","az","be","bg","ca","cs","da","de","en","eo","es","eu","fa","fi","fr","gl","gu","hi","hy","id","is","it","iw","ja","ka","kn","ky","mk","ml","mn","ms","ne","nl","no","pa","pl","pt","ru","sk","sq","sr","sv","sw","te","th","tl","uk","ur","uz","zu"],[["af",[["en"]]],["ar",[["en","fr"]]],["as",[["en"]]],["az",[["en"]]],["be",[["en"]]],["bg",[["en"]]],["bn",[["en"]]],["br",[["en"]]],["bs",[["en"]]],["ca",[["en"]]],["ceb",[["en"]]],["cs",[["de","en"]]],["cy",[["en"]]],["da",[["en"]]],["de",[["cs","en","es","pl","ru","tr"]]],["el",[["en"]]],["en",[["af","ar","as","az","be","bg","bn","br","bs","ca","ceb","cs","cy","da","de","el","es","et","eu","fa","fi","fj","fo","fr","fy","ga","gl","gu","ha","hi","hmn","hr","ht","hu","hy","id","ig","is","it","iw","ja","jw","ka","kk","km","kn","ko","ku","la","lah","lo","lt","lv","mi","mk","ml","mn","mr","ms","mt","my","ne","nl","no","ny","pl","pt","ro","ru","sk","sl","so","sq","sr","su","sv","sw","ta","te","tg","th","tl","tr","uk","ur","uz","vi","yi","yo","zh-CN","zh-TW","zu"]]],["es",[["de","en"]]],["et",[["en"]]],["eu",[["en"]]],["fa",[["en"]]],["fi",[["en"]]],["fj",[["en"]]],["fo",[["en"]]],["fr",[["ar","en","pl","ru"]]],["fy",[["en"]]],["ga",[["en"]]],["gl",[["en"]]],["gu",[["en"]]],["ha",[["en"]]],["hi",[["en"]]],["hmn",[["en"]]],["hr",[["en"]]],["ht",[["en"]]],["hu",[["en"]]],["hy",[["en"]]],["id",[["en"]]],["ig",[["en"]]],["is",[["en"]]],["it",[["en"]]],["iw",[["en","ru"]]],["ja",[["en"]]],["jw",[["en"]]],["ka",[["en"]]],["kk",[["en"]]],["km",[["en"]]],["kn",[["en"]]],["ko",[["en"]]],["ku",[["en"]]],["la",[["en"]]],["lah",[["en"]]],["lo",[["en"]]],["lt",[["en"]]],["lv",[["en"]]],["mi",[["en"]]],["mk",[["en"]]],["ml",[["en"]]],["mn",[["en"]]],["mr",[["en"]]],["ms",[["en"]]],["mt",[["en"]]],["my",[["en"]]],["ne",[["en"]]],["nl",[["en"]]],["no",[["en"]]],["ny",[["en"]]],["pl",[["de","en","fr"]]],["pt",[["en"]]],["ro",[["en"]]],["ru",[["de","en","fr","iw"]]],["sk",[["en"]]],["sl",[["en"]]],["so",[["en"]]],["sq",[["en"]]],["sr",[["en"]]],["su",[["en"]]],["sv",[["en"]]],["sw",[["en"]]],["ta",[["en"]]],["te",[["en"]]],["tg",[["en"]]],["th",[["en"]]],["tl",[["en"]]],["tr",[["de","en"]]],["uk",[["en"]]],["ur",[["en"]]],["uz",[["en"]]],["vi",[["en"]]],["yi",[["en"]]],["yo",[["en"]]],["zh-CN",[["en"]]],["zh-TW",[["en"]]],["zu",[["en"]]]]],'ltr', true , false , true , true , true , false , true , false , true , true , false , true , false , true , false , true ,'application\/pdf, application\/vnd.openxmlformats-officedocument.presentationml.presentation, application\/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application\/vnd.openxmlformats-officedocument.wordprocessingml.document, .pdf, .pptx, .xlsx, .docx','http:\/\/go\/file-tw-dogfood-bug-desktop', false , true ,'https:\/\/accounts.google.com\/AccountChooser?continue\x3dhttps:\/\/translate.google.com\/?hl%3DRU\x26hl\x3dru','https:\/\/accounts.google.com\/ServiceLogin?hl\x3dru\x26continue\x3dhttps:\/\/translate.google.com\/?hl%3DRU','https:\/\/accounts.google.com\/SignOutOptions?continue\x3dhttps:\/\/translate.google.com\/?hl%3DRU','image\/jpeg, image\/png, .jpeg, .jpg, .png', true , false , false , false , false ,'ru','ru', true ,'ru', 3.0 , 3.0 ,'https:\/\/goto2.corp.google.com\/mdtredirect?data_id_filter\x3dtranslate.google.com\x26system_name\x3dtranslate-webserver',[],'https:\/\/myactivity.google.com\/product\/google_translate?utm_source\x3dtranslate_web', null , 10.0 ,'https:\/\/myaccount.google.com\/privacypolicy?hl\x3dru', false ,["Обратный перевод (Ctrl + Shift + S)"], false , false ,'','https:\/\/myaccount.google.com\/termsofservice?hl\x3dru', 5000.0 , null , false , null ,]; window.IJ_valuesCb && window.IJ_valuesCb();</script><script nonce="4yDHP_r0rw-pqOulC-d5Rw">AF_initDataCallback({key: 'ds:0', hash: '1', data:[null,null,true,null,null,1,null,true,true], sideChannel: {}});</script><script nonce="4yDHP_r0rw-pqOulC-d5Rw">AF_initDataCallback({key: 'ds:6', hash: '2', data:[[["af",200],["ar",200],["bg",200],["bn",200],["bs",200],["ca",200],["cs",200],["da",200],["de",200],["el",200],["en",200],["es",200],["et",200],["fi",200],["fr",200],["gu",200],["hi",200],["hr",200],["hu",200],["id",200],["is",200],["it",200],["iw",200],["ja",200],["jw",200],["km",200],["kn",200],["ko",200],["la",200],["lv",200],["ml",200],["mr",200],["ms",200],["my",200],["ne",200],["nl",200],["no",200],["pl",200],["pt",200],["ro",200],["ru",200],["si",200],["sk",200],["sq",200],["sr",200],["su",200],["sv",200],["sw",200],["ta",200],["te",200],["th",200],["tl",200],["tr",200],["uk",200],["ur",200],["vi",200],["zh",200],["zh-CN",200],["zh-TW",200]]], sideChannel: {}});</script><script nonce="4yDHP_r0rw-pqOulC-d5Rw">AF_initDataCallback({key: 'ds:7', hash: '3', data:[null,[["af",["af-ZA",false]],["am",["am-ET",false]],["ar",["ar-EG",true]],["az",["az-AZ",false]],["bg",["bg-BG",false]],["bn",["bn-BD",true]],["ca",["ca-ES",true]],["cs",["cs-CZ",true]],["da",["da-DK",true]],["de",["de-DE",true]],["el",["el-GR",true]],["en",["en-US",true]],["es",["es-US",true]],["et",["et-EE",false]],["eu",["eu-ES",false]],["fa",["fa-IR",true]],["fi",["fi-FI",true]],["fr",["fr-FR",true]],["gl",["gl-ES",false]],["gu",["gu-IN",true]],["hi",["hi-IN",true]],["hr",["hr-HR",true]],["hu",["hu-HU",true]],["hy",["hy-AM",false]],["id",["id-ID",true]],["is",["is-IS",false]],["it",["it-IT",true]],["iw",["he-IL",true]],["ja",["ja-JP",true]],["jw",["jv-ID",false]],["ka",["ka-GE",false]],["kk",["kk-KZ",false]],["km",["km-KH",false]],["kn",["kn-IN",true]],["ko",["ko-KR",true]],["lo",["lo-LA",false]],["lt",["lt-LT",false]],["lv",["lv-LV",false]],["mk",["mk-MK",false]],["ml",["ml-IN",true]],["mn",["mn-MN",false]],["mr",["mr-IN",true]],["ms",["ms-MY",true]],["my",["my-MM",false]],["ne",["ne-NP",false]],["nl",["nl-NL",true]],["no",["nb-NO",true]],["pa",["pa-Guru-IN",false]],["pl",["pl-PL",true]],["pt",["pt-BR",true]],["ro",["ro-RO",true]],["ru",["ru-RU",true]],["si",["si-LK",false]],["sk",["sk-SK",true]],["sl",["sl-SI",true]],["sq",["sq-AL",false]],["sr",["sr-RS",true]],["su",["su-ID",false]],["sv",["sv-SE",true]],["sw",["sw",false]],["ta",["ta-IN",true]],["te",["te-IN",true]],["th",["th-TH",true]],["tl",["fil-PH",true]],["tr",["tr-TR",true]],["uk",["uk-UA",true]],["ur",["ur-PK",true]],["uz",["uz-UZ",false]],["vi",["vi-VN",true]],["zh-CN",["cmn-Hans-CN",true]],["zh-TW",["cmn-Hant-TW",true]],["zu",["zu-ZA",true]]]], sideChannel: {}});</script><script nonce="4yDHP_r0rw-pqOulC-d5Rw">AF_initDataCallback({key: 'ds:4', hash: '4', data:[[],[]], sideChannel: {}});</script><script nonce="4yDHP_r0rw-pqOulC-d5Rw">AF_initDataCallback({key: 'ds:2', hash: '5', data:[["ru","en","de","es","fr"],["ru","en","uk"]], sideChannel: {}});</script><script nonce="4yDHP_r0rw-pqOulC-d5Rw">AF_initDataCallback({key: 'ds:1', hash: '6', data:["auto","ru"], sideChannel: {}});</script><script nonce="4yDHP_r0rw-pqOulC-d5Rw">AF_initDataCallback({key: 'ds:5', hash: '7', data:[["auto","az","ay","sq","am","en","ar","hy","as","af","bm","eu","be","bn","my","bg","bs","bho","cy","hu","vi","haw","gl","el","ka","gn","gu","da","doi","zu","iw","ig","yi","ilo","id","ga","is","es","it","yo","kk","kn","ca","qu","ky","zh-TW","zh-CN","gom","ko","co","xh","ht","kri","ku","ckb","km","lo","la","lv","ln","lt","lg","lb","mai","mk","mg","ms","ml","dv","mt","mi","mr","mni-Mtei","lus","mn","de","ne","nl","no","or","om","pa","fa","pl","pt","ps","rw","ro","ru","sm","sa","ceb","nso","sr","st","si","sd","sk","sl","so","sw","su","tg","th","ta","tt","te","ti","ts","tr","tk","uz","ug","uk","ur","tl","fi","fr","fy","ha","hi","hmn","hr","ak","ny","cs","sv","sn","gd","ee","eo","et","jw","ja"],["az","ay","sq","am","en","ar","hy","as","af","bm","eu","be","bn","my","bg","bs","bho","cy","hu","vi","haw","gl","el","ka","gn","gu","da","doi","zu","iw","ig","yi","ilo","id","ga","is","es","it","yo","kk","kn","ca","qu","ky","zh-TW","zh-CN","gom","ko","co","xh","ht","kri","ku","ckb","km","lo","la","lv","ln","lt","lg","lb","mai","mk","mg","ms","ml","dv","mt","mi","mr","mni-Mtei","lus","mn","de","ne","nl","no","or","om","pa","fa","pl","pt","ps","rw","ro","ru","sm","sa","ceb","nso","sr","st","si","sd","sk","sl","so","sw","su","tg","th","ta","tt","te","ti","ts","tr","tk","uz","ug","uk","ur","tl","fi","fr","fy","ha","hi","hmn","hr","ak","ny","cs","sv","sn","gd","ee","eo","et","jw","ja"]], sideChannel: {}});</script><script nonce="4yDHP_r0rw-pqOulC-d5Rw">AF_initDataCallback({key: 'ds:3', hash: '8', data:[[["auto","Определить язык"],["az","азербайджанский"],["ay","аймара"],["sq","албанский"],["am","амхарский"],["en","английский"],["ar","арабский"],["hy","армянский"],["as","ассамский"],["af","африкаанс"],["bm","бамбара"],["eu","баскский"],["be","белорусский"],["bn","бенгальский"],["my","бирманский"],["bg","болгарский"],["bs","боснийский"],["bho","бходжпури"],["cy","валлийский"],["hu","венгерский"],["vi","вьетнамский"],["haw","гавайский"],["gl","галисийский"],["el","греческий"],["ka","грузинский"],["gn","гуарани"],["gu","гуджарати"],["da","датский"],["doi","догри"],["zu","зулу"],["iw","иврит"],["ig","игбо"],["yi","идиш"],["ilo","илоканский"],["id","индонезийский"],["ga","ирландский"],["is","исландский"],["es","испанский"],["it","итальянский"],["yo","йоруба"],["kk","казахский"],["kn","каннада"],["ca","каталанский"],["qu","кечуа"],["ky","киргизский"],["zh-TW","китайский (традиционный)"],["zh-CN","китайский (упрощенный)"],["gom","конкани"],["ko","корейский"],["co","корсиканский"],["xh","коса"],["ht","креольский (гаити)"],["kri","крио"],["ku","курдский (курманджи)"],["ckb","курдский (сорани)"],["km","кхмерский"],["lo","лаосский"],["la","латинский"],["lv","латышский"],["ln","лингала"],["lt","литовский"],["lg","луганда"],["lb","люксембургский"],["mai","майтхили"],["mk","македонский"],["mg","малагасийский"],["ms","малайский"],["ml","малаялам"],["dv","мальдивский"],["mt","мальтийский"],["mi","маори"],["mr","маратхи"],["mni-Mtei","мейтейлон (манипури)"],["lus","мизо"],["mn","монгольский"],["de","немецкий"],["ne","непальский"],["nl","нидерландский"],["no","норвежский"],["or","ория"],["om","оромо"],["pa","панджаби"],["fa","персидский"],["pl","польский"],["pt","португальский"],["ps","пушту"],["rw","руанда"],["ro","румынский"],["ru","русский"],["sm","самоанский"],["sa","санскрит"],["ceb","себуанский"],["nso","сепеди"],["sr","сербский"],["st","сесото"],["si","сингальский"],["sd","синдхи"],["sk","словацкий"],["sl","словенский"],["so","сомалийский"],["sw","суахили"],["su","сунданский"],["tg","таджикский"],["th","тайский"],["ta","тамильский"],["tt","татарский"],["te","телугу"],["ti","тигринья"],["ts","тсонга"],["tr","турецкий"],["tk","туркменский"],["uz","узбекский"],["ug","уйгурский"],["uk","украинский"],["ur","урду"],["tl","филиппинский"],["fi","финский"],["fr","французский"],["fy","фризский"],["ha","хауса"],["hi","хинди"],["hmn","хмонг"],["hr","хорватский"],["ak","чви"],["ny","чева"],["cs","чешский"],["sv","шведский"],["sn","шона"],["gd","шотландский (гэльский)"],["ee","эве"],["eo","эсперанто"],["et","эстонский"],["jw","яванский"],["ja","японский"]],[["az","азербайджанский"],["ay","аймара"],["sq","албанский"],["am","амхарский"],["en","английский"],["ar","арабский"],["hy","армянский"],["as","ассамский"],["af","африкаанс"],["bm","бамбара"],["eu","баскский"],["be","белорусский"],["bn","бенгальский"],["my","бирманский"],["bg","болгарский"],["bs","боснийский"],["bho","бходжпури"],["cy","валлийский"],["hu","венгерский"],["vi","вьетнамский"],["haw","гавайский"],["gl","галисийский"],["el","греческий"],["ka","грузинский"],["gn","гуарани"],["gu","гуджарати"],["da","датский"],["doi","догри"],["zu","зулу"],["iw","иврит"],["ig","игбо"],["yi","идиш"],["ilo","илоканский"],["id","индонезийский"],["ga","ирландский"],["is","исландский"],["es","испанский"],["it","итальянский"],["yo","йоруба"],["kk","казахский"],["kn","каннада"],["ca","каталанский"],["qu","кечуа"],["ky","киргизский"],["zh-TW","китайский (традиционный)"],["zh-CN","китайский (упрощенный)"],["gom","конкани"],["ko","корейский"],["co","корсиканский"],["xh","коса"],["ht","креольский (гаити)"],["kri","крио"],["ku","курдский (курманджи)"],["ckb","курдский (сорани)"],["km","кхмерский"],["lo","лаосский"],["la","латинский"],["lv","латышский"],["ln","лингала"],["lt","литовский"],["lg","луганда"],["lb","люксембургский"],["mai","майтхили"],["mk","македонский"],["mg","малагасийский"],["ms","малайский"],["ml","малаялам"],["dv","мальдивский"],["mt","мальтийский"],["mi","маори"],["mr","маратхи"],["mni-Mtei","мейтейлон (манипури)"],["lus","мизо"],["mn","монгольский"],["de","немецкий"],["ne","непальский"],["nl","нидерландский"],["no","норвежский"],["or","ория"],["om","оромо"],["pa","панджаби"],["fa","персидский"],["pl","польский"],["pt","португальский"],["ps","пушту"],["rw","руанда"],["ro","румынский"],["ru","русский"],["sm","самоанский"],["sa","санскрит"],["ceb","себуанский"],["nso","сепеди"],["sr","сербский"],["st","сесото"],["si","сингальский"],["sd","синдхи"],["sk","словацкий"],["sl","словенский"],["so","сомалийский"],["sw","суахили"],["su","сунданский"],["tg","таджикский"],["th","тайский"],["ta","тамильский"],["tt","татарский"],["te","телугу"],["ti","тигринья"],["ts","тсонга"],["tr","турецкий"],["tk","туркменский"],["uz","узбекский"],["ug","уйгурский"],["uk","украинский"],["ur","урду"],["tl","филиппинский"],["fi","финский"],["fr","французский"],["fy","фризский"],["ha","хауса"],["hi","хинди"],["hmn","хмонг"],["hr","хорватский"],["ak","чви"],["ny","чева"],["cs","чешский"],["sv","шведский"],["sn","шона"],["gd","шотландский (гэльский)"],["ee","эве"],["eo","эсперанто"],["et","эстонский"],["jw","яванский"],["ja","японский"]]], sideChannel: {}});</script><script id="wiz_jd" nonce="4yDHP_r0rw-pqOulC-d5Rw">if (window['_wjdc']) {const wjd = {}; window['_wjdc'](wjd); delete window['_wjdc'];}</script><script aria-hidden="true" id="WIZ-footer" nonce="4yDHP_r0rw-pqOulC-d5Rw">window.wiz_progress&&window.wiz_progress(); window.stopScanForCss&&window.stopScanForCss(); ccTick('bl');</script></body></html><script nonce="4yDHP_r0rw-pqOulC-d5Rw">this.gbar_=this.gbar_||{};(function(_){var window=this;

 

Edited by musicstashall
Link to comment
Share on other sites

12 hours ago, musicstashall said:

Your option is not entirely satisfactory

My "example" was completely satisfactory based on the information that you provided.  You did not mention anything about being able to display the result in different languages.  In my opinion, based on your expanded definition, I think it was your initial request which was not entirely satisfactory. :)  In other words, if you want better answers, learn how to ask better questions. ;)

 

12 hours ago, musicstashall said:

$sUrl  = 'https://translate.google.com/?hl=en'
$sUrl  = 'https://translate.google.com/?hl=ru'

Looking at the source of the 2 pages that you provided, I can see that the language-specific information is coming from a single URL, based on the language that is desired.  Those URL's provide the results in JSON. Each result contains the native and local language descriptions.  For example, the Russian URL provided the following native and local language description.  Personally, I think getting the information from the result of calling the URL is a better method than trying to extract the information from the source of an inline script in the HTML.  I have also attached the response from a call to the RU-specific language descriptions so you can see the content that is provided, how it is formatted, and how I used it.

Native language descriptions:

image.thumb.png.ddc8692ad444b12f61ff3e441d804ab9.png

Local (RU) language descriptions:

image.thumb.png.49b7f9d23eeff69d23495531022dc69a.png

With just a few slight modification to my original example, you should be able to get your new, more detailed results.  The only changes are a different URI, extracting and modifying the JSON from that new result, and small changes to the jq filter (as I have alluded to).

My example only shows one of the ways that I might go about trying to get the desired result.  It was not meant to be a complete solution.  It was meant for you to learn from if you choose to use some of the concepts, techniques, and tools that I've shown.

I hope it helps.

ru_uri_response.txt

Edited by TheXman
Corrected references to which results were native and which were local.
Link to comment
Share on other sites

59 minutes ago, TheXman said:

You show me something very beautiful and cool, but you don't give it to me, it's more like banter or mockery. Of course, I thank you for your attempt to teach me something new. But I prefer to study thoroughly, and not so from the top. In this case, I needed a quick result. And I don't think I can use your arsenal. How do you imagine that I would dump this arsenal next to my executable file??

Edited by musicstashall
Link to comment
Share on other sites

Not mockery or banter, just facts.  When you do not clearly state what it is you are looking for, it tends to waste your time and the time of the person trying to help you.

 

On 3/4/2023 at 9:31 AM, musicstashall said:

How do you imagine that I would dump this arsenal next to my executable file??

What arsenal?  The only external tool in my example script is the jq executable, the rest are just UDF's.   You don't even need to use jq to process the JSON, you can use whatever you like.  I only provided concepts and techniques.  How you implement them is totally up to you.  So I'm not sure what you mean.

In case you missed it, I provided a fully working example script.  Did you not see it?  It is under the section that says: "Reveal hidden contents".  It showed, among other things, how to get the information in the images.

 

On 3/4/2023 at 9:31 AM, musicstashall said:

In this case, I needed a quick result.

As it says at the bottom of my About Me, I'm not interested in helping those that are merely looking for solutions & answers.  I'm only interested in helping people that are actively trying to learn.

Edited by TheXman
Link to comment
Share on other sites

  • 1 year later...
Posted (edited)

@Musashi It's been a long time :)

Thanks for this interesting script you provided above in this thread, which translates nicely from one language to another, using Google api & Json.au3 (by @AspirinJunkie)

I got a problem when there are end of lines inside the original text (@crlf or @cr or @lf) as they are all lost inside the translated text. For example, with this original german text (which will be translated to english)

Global $sRead1 = "Hallo. Wie geht's dir?" & @crlf & "Gut, danke."

If I understand correctly, this is what the script does actually, depending on this line :

$sOutput &= ($aData[$i])[0] ; & @CRLF
or
$sOutput &= ($aData[$i])[0] & @CRLF

In the 1st case, the english output will be a single line :

Hello. How are you?Good, thank you.

In the 2nd case, it will become 2 lines (because a dot followed by a space has been found ?)

Hello.
How are you?Good, thank you.

Both preceding outputs aren't really satisfying. What I would like is the following output, where the original EOL's are found at the same place in the translated text :

germantoenglish.png.1deb618359baa2f9e2fa72608852bb64.png

So I tried a workaround in the script below and it seems to work. I'm keeping all commented lines in it, in case someone is interested in them. To run the script :

* copy to the clipboard (ctrl+c) any german (or spanish, french etc...) text containing some end of lines, for example this german text :

Hallo. Wie geht's dir?
Gut, Danke.

* then run the following script, which should translate to english (due to the line : Local $sLangTO = "en")
* If you run the script from Scite, you'll have the translated text in the Console & MsgBox
* If not run from Scite, it will be translated in MsgBox only.

If you guys have some ideas to improve this, please indicate them here, thanks.

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

;========================
Local $sLangFROM = "auto"
Local $sLangTO = "en"   ; <===== change this line for the language of the translated text
;========================

; Local $sClipGet = ClipGet()
; Local $sClipGet = StringReplace(ClipGet(), @crlf, Chr(255))    ; personal solution to prevent loss of eventual @crlf in translated text
Local $sClipGet = StringRegExpReplace(ClipGet(), "\R", Chr(255)) ; ditto

; ConsoleWrite("ORIGINAL: " & $sClipGet & @CRLF)
; ConsoleWrite("ORIGINAL: " & ClipGet() & @CRLF)
ConsoleWrite("ORIGINAL: " & BinaryToString(StringToBinary(ClipGet(), 4), 1) & @CRLF)
ConsoleWrite("--------------------------------------------------------------------------------------------------------------------" & @CRLF)

Local $sTranslated = _GoogleAPITranslate($sClipGet, $sLangFROM, $sLangTO)

; ConsoleWrite($sTranslated & @CRLF) ; bad pour caractères accentués français dans la console

; https://www.autoitscript.com/forum/topic/181796-consolewrite-only-outputting-asciiansi/?do=findComment&comment=1305566
ConsoleWrite(BinaryToString(StringToBinary($sTranslated, 4), 1) & @CRLF) ; jchd syntax ok pour caractères accentués français dans la console

MsgBox(262144, "Translated From " & $sLangFROM & " To " & $sLangTO, $sTranslated) ; $MB_TOPMOST = 262144

;==============================================
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

                ; Original script line with commented @CRLF (all translated text will become a single line)
                ; $sOutput &= ($aData[$i])[0] ; & @CRLF

                ; Original script line with uncommented @CRLF (each dot separator followed by a space (?) will generate a new line)
                ; $sOutput &= ($aData[$i])[0] & @CRLF

                ; Replace each @CRLF at the same place than the original text
                $sOutput &= StringReplace(($aData[$i])[0], Chr(255), @crlf) ; personal solution to prevent loss of eventual EOLs in translated text

            Next
        EndIf
    EndIf
    Return $sOutput
EndFunc  ;==>_GoogleAPITranslate

; https://www.autoitscript.com/forum/topic/202204-simple-google-translate/?do=findComment&comment=1505984

; par défaut, les sauts de lignes disparaissent dans la traduction ! Trouvé un wokaround pour empêcher ça...
; ... mais on ne peut mettre n'importe quoi comme workaround (ex. Chr(255) semble marcher, d'autres chaines plus longues, non parfois car
; ... elles seraient 'coupées' en leur milieu parfois, au retour, pas approfondi)

#cs
Col 0   Col 1 ( issu script "creation code langues (liste issue google).au3" )
auto    Détecter la langue
af  Afrikaans
sq  Albanais
de  Allemand
am  Amharique
en  Anglais
ar  Arabe
hy  Arménien
az  Azerbaïdjanais
eu  Basque
bn  Bengali
be  Biélorusse
my  Birman
bs  Bosniaque
bg  Bulgare
ca  Catalan
ceb Cebuano
ny  Chewa
zh-CN   Chinois (simplifié)
zh-TW   Chinois (traditionnel)
si  Cingalais
ko  Coréen
co  Corse
ht  Créole haïtien
hr  Croate
da  Danois
es  Espagnol
eo  Espéranto
et  Estonien
fi  Finnois
fr  Français
fy  Frison occidental
gd  Gaélique écossais
gl  Galicien
cy  Gallois
ka  Géorgien
gu  Goudjarati
el  Grec
ha  Haoussa
haw Hawaïen
iw  Hébreu
hi  Hindi
hmn Hmong
hu  Hongrois
ig  Igbo
id  Indonésien
ga  Irlandais
is  Islandais
it  Italien
ja  Japonais
jv  Javanais
kn  Kannada
kk  Kazakh
km  Khmer
rw  Kinyarwanda
ky  Kirghize
ku  Kurde
lo  Lao
la  Latin
lv  Letton
lt  Lituanien
lb  Luxembourgeois
mk  Macédonien
ms  Malais
ml  Malayalam
mg  Malgache
mt  Maltais
mi  Maori
mr  Marathi
mn  Mongol
nl  Néerlandais
ne  Népalais
no  Norvégien
or  Odia
ug  Ouïghour
ur  Ourdou
uz  Ouzbek
ps  Pachto
pa  Pendjabi
fa  Persan
pl  Polonais
pt  Portugais
ro  Roumain
ru  Russe
sm  Samoan
sr  Serbe
sn  Shona
sd  Sindhi
sk  Slovaque
sl  Slovène
so  Somali
st  Sotho du Sud
su  Soudanais
sv  Suédois
sw  Swahili
tg  Tadjik
tl  Tagalog
ta  Tamoul
tt  Tatar
cs  Tchèque
te  Télougou
th  Thaï
tr  Turc
tk  Turkmène
uk  Ukrainien
vi  Vietnamien
xh  Xhosa
yi  Yiddish
yo  Yoruba
zu  Zoulou
#ce

 

Edited by pixelsearch
typo
Link to comment
Share on other sites

@jchd hello !
Your knowledge in translation & encoding is required :)

I would like to translate this Russian sentence in english :

а если подумать

1) If I do it from my Opera Browser, using Google translation service, it works fine :

Operatranslation-RussiantoEnglish-ok.png.f7ddd1ea7e33c9afc3bcb6b58244e9e4.png

Complete Opera URL is :
 

https://www.google.com/search?tlsa=1&sca_esv=f42f57a008774f06&sca_upv=1&gbv=2&ei=DSM-ZtX0BvaRxc8P74iQqA8&q=Traduire&tlitesl=ru&tlitetxt=%D0%B0+%D0%B5%D1%81%D0%BB%D0%B8+%D0%BF%D0%BE%D0%B4%D1%83%D0%BC%D0%B0%D1%82%D1%8C&tlitetl=en

We can extract from the URL the russian text that has been correctly translated :

%D0%B0+%D0%B5%D1%81%D0%BB%D0%B8+%D0%BF%D0%BE%D0%B4%D1%83%D0%BC%D0%B0%D1%82%D1%8C

2) Now I try to do same with the AutoIt script from my preceding post (the one that uses Google API and JSON.au3), with this change made before :

;========================
Local $sLangFROM = "ru"
Local $sLangTO = "en"
;========================

Then we copy to the clipboard the original russian sentence (select it, then ctrl+c) and we run the script, this is the "wrong" result displayed in the Console & MessageBox :

AutoItscript-RussiantoEnglish-notok.png.c3bd118c73470045bb029469b964a3ed.png

3) If I replace the $sUrl line in the script, not using $sMytext anymore, but replacing it with the literal russian text extracted from Opera URL :

; $sUrl  = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=" & $sFrom & "&tl=" & $sTo & "&dt=t&q=" & $sMytext

$sUrl  = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=" & $sFrom & "&tl=" & $sTo & "&dt=t&q=" & _
    "%D0%B0+%D0%B5%D1%81%D0%BB%D0%B8+%D0%BF%D0%BE%D0%B4%D1%83%D0%BC%D0%B0%D1%82%D1%8C"

AutoItscript-RussiantoEnglish-ok.png.b0b9c57b8fc2b21189410ebf4fa15530.png

Now the translation is correct. So I got this issue with original russian text, but not with original german, spanish, turkish, english, french (etc...) languages.

Do you have an idea why it happens and how could it be solved ?
Because the preceding script is really useful, you can create a shortcut of the script on the Desktop and as soon as you got foreign sentence(s) to translate, a simple click on the shortcut should do it (with of course : Local $sLangFROM = "auto" in the script)

Thanks for reading

Link to comment
Share on other sites

Posted (edited)

When you copy things, the clipboard stores data and allows reading it under multiple formats. Simple ClipPut is likely to paste only ANSI text, while you need Unicode.

; For your information only
Func EnumFormats()
    _ClipBoard_Open(0)
    Local $f, $n = _ClipBoard_CountFormats()
    ConsoleWrite($n & " clipboard formats are available:" & @LF)
    Do
        $f = _ClipBoard_EnumFormats($f)
        If $f > 0 Then ConsoleWrite("Format " & $f & " = " & _ClipBoard_FormatStr($f) & @LF)
    Until $f = 0
    _ClipBoard_Close()
EndFunc

You probably need something like that:

$sText = ReadUnicodeClip()
; paste or process read data where required
; .../...

Func ReadUnicodeClip()
    _ClipBoard_Open(0)
    Local $f, $s
    Do
        $f = _ClipBoard_EnumFormats($f)
    Until _ClipBoard_FormatStr($f) = "Unicode Text"
    $s = _ClipBoard_GetData($f)
    _ClipBoard_Close()
    Return $s
EndFunc

Format numbers change depending on context, so don't rely on magic numbers and always scan formats until the one you need is found.

Edited by jchd

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

@jchd thanks for the help, unfortunately the Clipboard functions didn't solve the issue (output is still a bunch of ???)

I think that as soon as Unicode is involved (russian language for example) then it will be a bit hard for the script to format the russian text as required by google api for translation.

For example, let's work on a single russian character to translate, the Cyrillic Small Letter El :

л

Below is the Browser url that translates it correctly in english, and the text to be translated will become "%D0%BB" (UTF-8) as shown inside the url :

https://www.google.com/search?tlsa=1&sca_esv=f42f57a008774f06&sca_upv=1&gbv=2&ei=oWA-ZreWF9qokdUP-5SJ4As&q=Traduire&tlitesl=ru&tlitetxt=%D0%BB&tlitetl=en

л (russe)
%D0%BB
l (anglais)

For the record, on my computer, Free Clipboard Viewer 4.0 shows this for the russian character, coded as 043B (UTF16 Big Endian)

л
043B (Unicode Text Format, as indicated by Free Clipboard Viewer)

All this seems correct, according to this web page, which indicates (excerpts) :

л
Nom:             Lettre minuscule cyrillique elle[1]
Nom (anglais):   Cyrillic Small Letter El[2]
Version Unicode: 1.1 (juin 1993)[3]
Bloc:            Cyrillique, U+0400 - U+04FF[4]
...
Encodage UTF-8:  0xD0 0xBB
Encodage UTF-16: 0x043B
Encodage UTF-32: 0x0000043B

So when it comes to russian translation, to match google api requirements, we should at least add this in the script :

Local $sClipGet = StringToBinary(ClipGet(), $SB_UTF8) ; л (russian) becomes 0xD0BB

Then we should format the input string to match google requirement, transforming "0xD0BB" to "%D0%BB"
But this is only for 1 character ! Now when you see that google requires a "+" when there's a space in the input string, it would be a nightmare to check all requirements and adapt them in the script.

For example, with this other russian input string :

л.л

google requirement for translation would be: %D0%BB.%D0%BB  (a dot stays a dot) . But:

StringToBinary("л.л", $SB_UTF8) ; 0xD0BB2ED0BB (a dot becomes 2E)

So I guess I'll use the script only for languages using Ansi characters, but not for languages using Unicode characters (where translation via Google directly in the browser works very fine !)

Thanks for reading

Link to comment
Share on other sites

Posted (edited)

In fact it's not that hard to translate from russian to english with the script.
You just need to prepare a UTF-8 input string that the google api translator will recognize, for example with these few lines of script :

#include <StringConstants.au3>

Local $sInput, $sClipGet = StringToBinary(ClipGet(), $SB_UTF8) ; л (russian) becomes 0xD0BB

For $i = 3 To StringLen($sClipGet) Step 2 ; forget "0x" at beginning
    $sInput &= "%" & StringMid($sClipGet, $i, 2)
Next

ConsoleWrite("ClipGet() = " & BinaryToString($sClipGet, $SB_ANSI) & @crlf & @crlf)
ConsoleWrite("$sClipGet = " & $sClipGet & @crlf & @crlf)
ConsoleWrite("$sInput   = " & $sInput & @crlf)

AutoIt console :

ClipGet() = а если подумать  в 99,9999999999% случаев

$sClipGet = 0xD0B020D0B5D181D0BBD0B820D0BFD0BED0B4D183D0BCD0B0D182D18C2020D0B22039392C393939393939393939392520D181D0BBD183D187D0B0D0B5D0B2

$sInput   = %D0%B0%20%D0%B5%D1%81%D0%BB%D0%B8%20%D0%BF%D0%BE%D0%B4%D1%83%D0%BC%D0%B0%D1%82%D1%8C%20%20%D0%B2%20%39%39%2C%39%39%39%39%39%39%39%39%39%39%25%20%D1%81%D0%BB%D1%83%D1%87%D0%B0%D0%B5%D0%B2

Then you use the variable $sInput for the google api translator, it will translate correctly :

withcorrectutf-8string.png.a0b20e8261e1cbbfff95d1fe7491b87a.png

Same result as translating with the Browser, yes !

operatranslation.png.0431aba03f21eafcc253a099d8a702b0.png

I'll have to rework a bit the original script to integrate in it these new lines of script.

 

Edited by pixelsearch
minor (replaced constant 1 with $SB_ANSI)
Link to comment
Share on other sites

Posted (edited)

Here is the final reworked script taking care of UTF-8 encoding, so cyrillic characters shouldn't be a problem anymore.

Now that all original text is always converted to UTF-8 (no matter they were Ascii characters, Ansi, Unicode, mix) then my initial issue with end of lines has disappeared as EOL's will be restored correctly at their right place, when the translation is done (no more workaround !)

I notice the script needs the last version of AutoIt (because of Maps in Json.au3)
Though some translations will work with older versions of AutoIt (because Maps aren't always used during translation, depending on the original text), it's better to use last version of AutoIt (3.3.16.1) to cover all cases.

@AspirinJunkie I would like to know : this is what is found in your version of Json.au3 I found on the net :

; Title .........: JSON-UDF
; Version .......: 0.9
; AutoIt Version : 3.3.16.1
...
; Author(s) .....: AspirinJunkie
; Last changed ..: 2023-01-16

In case there is a newer version, could you please indicate where it can be downloaded ?
Thanks to everybody involved in this script :)

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

;========================
Local $sLangFROM = "auto"
Local $sLangTO = "en"   ; <===== change this line for the language of the translated text
;========================

Local $sInput, $sClipGet = StringToBinary(ClipGet(), $SB_UTF8) ; for example л (russian) becomes 0xD0BB

For $i = 3 To StringLen($sClipGet) Step 2 ; start at 3 to bypass "0x"
    $sInput &= "%" & StringMid($sClipGet, $i, 2)
Next

Local $sTranslated = _GoogleAPITranslate($sInput, $sLangFROM, $sLangTO)

; If (Not @compiled) And ProcessExists("scite.exe") Then ; not 100% proof to bypass the 3 following ConsoleWrite, but better than nothing.

If Not @compiled Then ; probably a bit faster than preceding line. It will be enough when script run from .a3x shortcut placed on Desktop.
    ConsoleWrite("ORIGINAL: " & BinaryToString($sClipGet, $SB_ANSI) & @crlf) ; in case of accented characters in Scite console.
    ConsoleWrite("----------------------------------------------------------------------------------------------------------------" & @crlf)
    ConsoleWrite(BinaryToString(StringToBinary($sTranslated, $SB_UTF8), $SB_ANSI) & @crlf)
EndIf

MsgBox(262144, "Translated From " & $sLangFROM & " To " & $sLangTO, $sTranslated) ; $MB_TOPMOST = 262144

;==============================================
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
                $sOutput &= ($aData[$i])[0]
            Next
        EndIf
    EndIf
    Return $sOutput
EndFunc  ;==>_GoogleAPITranslate

* Update May 11, 2024 : Added a test on @compiled to bypass (or not) all ConsoleWrite lines and the functions included in them. Though it's not 100% proof, it's better than nothing.
Other ways to detect more precisely how the script was launched can be found on the Forum, for example by using _WinAPI_GetParentProcess and _WinAPI_GetProcessName, but do we really need all this just to bypass 3 ConsoleWrite lines ? Let's test on @compiled for the moment, we'll see...

Edited by pixelsearch
Update
Link to comment
Share on other sites

15 minutes ago, pixelsearch said:

I would like to know : this is what is found in your version of Json.au3 I found on the net :

The current version actually has a higher date in the comment.
But this is also wrong 😉 - I obviously overlooked the date and didn't always adjust it.

The current version can always be found in the github repository: https://github.com/Sylvan86/autoit-json-udf
The last change there was on 21 February 2024.

Link to comment
Share on other sites

Posted (edited)

Thanks AspirinJunkie,
I just downloaded your last version 010 which replaced version 09

Happy translations :D

Edited by pixelsearch
deleted the instructions to compile the script, not really useful
Link to comment
Share on other sites

Posted (edited)

Here is a new version of the script, which outputs the translated text to an Edit control.
Although the preceding version displayed the output in a MessageBox (and in Scite Console if run from Scite); it seems better to output the translated text to an Edit control. Advantages are :

* If it's a very long text, then the MessageBox will not display it entirely (and its 'Ok' button won't show)
* We can't copy-paste the translated text from a MessageBox (if we want to keep it)

Here is an example of output in the Edit control, in its original GUI size (900 x 600) . The Gui can be maximized & resized. The Edit control can have its text wrapped or not (an eventual selection will be preserved when switching from Wrap to No Wrap) . Native scrollbars should work nicely in both cases (wrap / no wrap) . This example is the translation from a part of the AutoIt german introduction found in this webpage, copied to clipboard, then translated in english with the script below :

ClipboardtranslationinGui(lucidaconsole11).png.66083995a12df16b0e2ec7ee32ccebfd.png

#include "Json.au3" ; (by @AspirinJunkie)
#include <GUIConstantsEx.au3>
#include <GUIEdit.au3>
#include <StringConstants.au3>
#include <WindowsConstants.au3>

Opt("MustDeclareVars", 1) ;0=no, 1=require pre-declaration
Global $g_hGUI, $g_idEdit, $g_iGui_W = 900, $g_iGui_H = 600

;========================
Local $sLangFROM = "auto"
Local $sLangTO = "en"   ; <===== change this line for the language of the translated text
;========================

Local $sInput, $sClipGet = StringToBinary(ClipGet(), $SB_UTF8) ; for example л (russian) becomes 0xD0BB

For $i = 3 To StringLen($sClipGet) Step 2 ; start at 3 to bypass "0x"
    $sInput &= "%" & StringMid($sClipGet, $i, 2)
Next

Local $sTranslated = _GoogleAPITranslate($sInput, $sLangFROM, $sLangTO)

If Not @compiled Then
    ConsoleWrite("ORIGINAL: " & BinaryToString($sClipGet, $SB_ANSI) & @crlf) ; in case of accented characters in Scite console.
    ConsoleWrite("----------------------------------------------------------------------------------------------------------------" & @crlf)
    ConsoleWrite(BinaryToString(StringToBinary($sTranslated, $SB_UTF8), $SB_ANSI) & @crlf)
EndIf

; MsgBox(262144, "Clipboard translated From " & $sLangFROM & " To " & $sLangTO, $sTranslated) ; $MB_TOPMOST = 262144

_OutputInGui($sTranslated, $sLangFROM, $sLangTO)

;==============================================
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
                $sOutput &= ($aData[$i])[0]
            Next
        EndIf
    EndIf
    Return $sOutput
EndFunc  ;==>_GoogleAPITranslate

;===============================================================
Func _OutputInGui(Const ByRef $sTranslated, $sLangFROM, $sLangTO)

    $g_hGUI = GUICreate("Clipboard translated From " & $sLangFROM & " To " & $sLangTO, $g_iGui_W, $g_iGui_H, -1, -1, $WS_OVERLAPPEDWINDOW)
    _EditRecreate($sTranslated, True) ; True = word wrap (keep it True here, to match with the initial checked Menu item "Word Wrap")

    ; Menu Format
    Local $idFormatMenu = GUICtrlCreateMenu("F&ormat") ; Create the Format menu. Underline o when Alt is pressed.
    Local $idFormatMenu_WordWrap = GUICtrlCreateMenuItem("&Word Wrap" &@TAB& "", $idFormatMenu) ; Create the "Word Wrap" menu item. Underline W when Alt is pressed.
    GUICtrlSetState(-1, $GUI_CHECKED)

    GUISetState(@SW_SHOW, $g_hGUI)
    _GUICtrlEdit_SetSel($g_idEdit, -1, 0) ; deselects only when placed AFTER GUISetState()

    While 1
        Switch GUIGetMsg()
            Case $GUI_EVENT_CLOSE
                Exit
            Case $idFormatMenu_WordWrap
                _WordWrap($sTranslated, $idFormatMenu_WordWrap)
        EndSwitch
    WEnd
EndFunc  ;==>_OutputInGui

;==============================================================
Func _WordWrap(Const ByRef $sTranslated, $idFormatMenu_WordWrap)

    If BitAND(GUICtrlRead($idFormatMenu_WordWrap), $GUI_CHECKED) = $GUI_CHECKED Then ; turn off Word Wrap
        _EditRecreate($sTranslated, False) ; False = no Word Wrap
        GUICtrlSetState($idFormatMenu_WordWrap, $GUI_UNCHECKED) ; uncheck Word Wrap
    Else ; turn on Word Wrap
        _EditRecreate($sTranslated, True) ; True = Word Wrap
        GUICtrlSetState($idFormatMenu_WordWrap, $GUI_CHECKED) ; turn on Word Wrap and show checked
    EndIf
EndFunc  ;==>_WordWrap

;======================================================
Func _EditRecreate(Const ByRef $sTranslated, $bWordWrap)

    Local $idEdit_Old = $g_idEdit ; 0 at first passage

    If $idEdit_Old Then
        Local $aPos = ControlGetPos($g_hGUI, "", $idEdit_Old)
    Else ; 1st passage
        Local $aPos[4] = [20, 20, $g_iGui_W - 40, $g_iGui_H - 60]
    EndIf

    $g_idEdit = GUICtrlCreateEdit("", $aPos[0], $aPos[1], $aPos[2], $aPos[3], ($bWordWrap _
        ? BitOr($ES_WANTRETURN, $WS_VSCROLL, $ES_AUTOVSCROLL) _
        : -1)) ; control ID

    ; GUICtrlSetFont(-1, 10, 400, 0, "Courier New")  ; change default font
    GUICtrlSetFont(-1, 11, 400, 0, "Lucida Console") ; seems better than Courier New

    If $idEdit_Old Then
        _GUICtrlEdit_SetText($g_idEdit, GUICtrlRead($idEdit_Old))
        Local $aSel = _GUICtrlEdit_GetSel($idEdit_Old)
        GUICtrlDelete($idEdit_Old)
        _GUICtrlEdit_SetSel($g_idEdit, $aSel[0], $aSel[1])
    Else ; 1st passage
        _GUICtrlEdit_SetText($g_idEdit, $sTranslated)
    EndIf
EndFunc  ;==>_EditRecreate

If you want the output to be displayed first in MessageBox, then in Edit control (really ?) then uncomment the MessageBox line in the script :

; MsgBox(262144, "Clipboard translated From " & $sLangFROM & " To " & $sLangTO, $sTranslated) ; $MB_TOPMOST = 262144

_OutputInGui($sTranslated, $sLangFROM, $sLangTO)

Happy translations !

* Update May 15, 2024 : changed Font in Edit control (Lucida Console seems better than Courier New)

Next update should indicate which language Google used for translation, when we indicated "auto" as Language From. Maybe they will be other updates as I got some  ideas :)

Edited by pixelsearch
Update
Link to comment
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
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...