Jump to content

Script for using the Google Translate API - Help needed - (Moved)


Go to solution Solved by tomasi,

Recommended Posts

Hello, dear Autoit experts.

I have found an Autoit script on the Internet that sends text to the Google Translate API so that it is translated there and the translation is then scaled and output as a file or to the clipboard. The script works great and is basically exactly what I need for my work as a translator. However, I don't need all the functionality for translating entire files and outputting them to a file, nor do I need all the other message boxes and user prompts. For me, it would be ideal if the script sent the contents of the clipboard to Google for translation every time I called it with a key combination and then copied Google's response to the clipboard so that I could use it from there in my translation software. As I said, the whole thing should run silently in the background, without any message boxes or prompts. Unfortunately, I'm not a programmer and can't figure it out myself. I've tried to revise the If and Else parts accordingly, but unfortunately I'm messing everything up because I just don't have enough insight. Perhaps one of you would like to modify the script accordingly, I can imagine that this would be a piece of cake for an experienced Autoit expert, and I hope the author doesn't mind, or should I ask his permission? Many thanks in advance anyway.

Here the script:

simplegoog v5 ###.au3

; #Au3Stripper_Parameters=/MO

#include <Inet.au3>
#include <Array.au3>
#include <String.au3>

Global $searchstring
Global $bigtranslation
$bigtranslation = ""

#cs

    Rename your script from simplegoog###.au3 to simplegoog#YOUR_API_KEY#source_language#target_language.au3

    1. Script gets API key, SL and TL from its own name.
    2. Script asks for input and output files.
    3. Ask user if it's okay to split by sentence. If yes:
    - replace ESPs with ESP##
    - find/replace abbreviation+## with abbreviation
    - replace ## with CRLF
    (if fileexists abbreviations.txt then use that file, one abbr per line)
    4. Split input file by CRLF and TAB.
    5. Use 10 lines at a time, encode them, adds them to the URL, and sends it to GT.
    6. Parse replies

    To parce JSON reply:
    Split by:
    "translatedText": "
    Then split [2] by "

    Also encode/decode any URL text.
    http://www.w3schools.com/tags/ref_urlencode.asp

    And write to a file.
    With a TrayTip telling the progress.

#ce

If StringInStr(@ScriptName, "###", 1) Then
    $apikey = InputBox("Enter API key", "What is your API key?")
    If @error = 1 Then
        Exit
    EndIf
    $SL = InputBox("Enter source language", "What is your source language?")
    If @error = 1 Then
        Exit
    EndIf
    $TL = InputBox("Enter target language", "What is your target language?")
    If @error = 1 Then
        Exit
    EndIf
Else
    $scriptnamesplit = StringSplit(@ScriptName, "#", 1)
    If $scriptnamesplit[0] = 4 Then
        $apikey = $scriptnamesplit[2]
        $SL = $scriptnamesplit[3]
        $TL = StringTrimRight($scriptnamesplit[4], 4)
        $scriptnamesplitinfo = MsgBox(4, "Is this information correct?", "API key: " & $apikey & @CRLF & "Source language code: " & $SL & @CRLF & "Target language code: " & $TL, 0)
        If $scriptnamesplitinfo = 7 Then
            $apikey = InputBox("Enter API key", "What is your API key?", $apikey)
            If @error = 1 Then
                Exit
            EndIf
            $SL = InputBox("Enter source language", "What is your source language?", $SL)
            If @error = 1 Then
                Exit
            EndIf
            $TL = InputBox("Enter target language", "What is your target language?", $TL)
            If @error = 1 Then
                Exit
            EndIf
        EndIf
    Else
        MsgBox(0, "Error 2", "Could not get API key, source language code or target language code from script file name." & @CRLF & "The script will now exit.", 0)
        Exit
    EndIf
EndIf

$mustaskforfile = 0

If $CmdLine[0] > 0 Then
    $inputfileopendialog = $CmdLine[1]
    $inputfile = FileRead(FileOpen($inputfileopendialog, 128))
    $cliporno = 7
Else
    $cliporno = MsgBox(4, "Translate the clipboard?", "Do you want to translate the clipboard, or a file?" & @CRLF & "Say 'Yes' to translate the clipboard.", 0)
    If $cliporno = 6 Then
        $inputfile = ClipGet()
        If @error > 0 Then
            MsgBox(0, "Clipboard error", "Unable to access clipboad, or clipboard is empty.", 0)
            Exit
        EndIf
    Else
        $mustaskforfile = 1
    EndIf
EndIf


If FileExists(@ScriptDir & "\abbreviationlist.txt") Then
    $abbreviationlistfile = FileRead(FileOpen(@ScriptDir & "\abbreviationlist.txt", 128))
    $abbreviationlist = StringSplit($abbreviationlistfile, ",", 1)
Else
    $abbreviationlist = StringSplit("Apr.,Aug.,Corp.,D.,Dec.,Dept.,Dr.,D.C.,e.g.,etc.,Feb.,Jan.,Jun.,Jul.,Jr.,Inc.,i.e.,Lt.,Ltd.,Mar.,max.,min.,Mr.,Mrs.,Ms.,Oct.,Nov.,Pr.,Pres.,Rev.,rev.,Sep.,Sgt.,St.,Str.,vol.,vs.", ",", 1)
EndIf


$splitbysentence = MsgBox(4, "Segment further by sentence?", "Try to segment further by sentence?" & @CRLF & "Say 'No' if your text has one sentence per line already.", 0)


If $mustaskforfile = 1 Then
    $inputfileopendialog = FileOpenDialog("Source text file", @ScriptDir, "Text files (*.txt)|All files (*.*)")
    $inputfile = FileRead(FileOpen($inputfileopendialog, 128))
EndIf


If $splitbysentence = 6 Then
    $inputfile = StringReplace($inputfile, ".", ".###")
    $inputfile = StringReplace($inputfile, "!", "!###")
    $inputfile = StringReplace($inputfile, "?", "?###")
    For $i = 1 To $abbreviationlist[0]
        $inputfile = StringReplace($inputfile, $abbreviationlist[$i] & "###", $abbreviationlist[$i], 0, 1)
    Next
    $inputfile = StringReplace($inputfile, "###", @CRLF)
    $inputfile = StringReplace($inputfile, @CRLF & " ", @CRLF)
EndIf

$inputfile = $inputfile & @CRLF ; kludge, because now we're going to split by @CRLF

$inputfilesplit = StringSplit($inputfile, @CRLF, 1)
$startrowindex = 1

If $inputfilesplit[0] > 9 Then
    $endrowindex = 10
Else
    $endrowindex = $inputfilesplit[0]
EndIf

$numofstrings = 0
$numberofrepeats = Int($inputfilesplit[0] / 10)  ; + 1
$finalitems = $inputfilesplit[0] - ($numberofrepeats * 10)


For $j = 1 To $numberofrepeats + 1
    $searchstring = "&q=" & _ArrayToString($inputfilesplit, "&q=", $startrowindex, $endrowindex)

    If $j < $numberofrepeats Then
        $startrowindex = $startrowindex + 10
        $endrowindex = $endrowindex + 10
    ElseIf $j = $numberofrepeats Then
        $startrowindex = $startrowindex + 10
        $endrowindex = $endrowindex + $finalitems
    EndIf

    If StringRight($searchstring, 3) = "&q=" Then
        $searchstring = StringTrimRight($searchstring, 3)
    EndIf

    $searchstring = StringToBinary($searchstring, 4)
    $searchstring = StringTrimLeft($searchstring, 2)

    $searchstring = StringRegExpReplace($searchstring, "(..)", "%\1")

    $searchstring = StringReplace($searchstring, "%26%71%3D", "&q=")

    If StringRight($searchstring, 2) = "00" Then
        $searchstring = StringTrimRight($searchstring, 2)
    EndIf

    $searchstring = StringReplace($searchstring, "&q=&q=", "&q=")
    $searchstring = StringReplace($searchstring, "&q=&q=", "&q=")
    $searchstring = StringReplace($searchstring, "&q=&q=", "&q=")

    #cs

        All of this is not necessary because we now convert URLs.

        $searchstring = StringReplace ($searchstring, "%", "%25")
        $searchstring = StringReplace ($searchstring, "#", "%23")

        $searchstring = StringReplace ($searchstring, "<", "%3C")
        $searchstring = StringReplace ($searchstring, ">", "%3E")

        $searchstring = StringReplace ($searchstring, "&", "%26")
        $searchstring = StringReplace ($searchstring, "=", "%3D")
        $searchstring = StringReplace ($searchstring, "%26q%3D", "&q=")

        ; $searchstring = StringReplace ($searchstring, "&q=-", "&q=%2D")
        ; $searchstring = StringReplace ($searchstring, "$", "%24")
        ; $searchstring = StringReplace ($searchstring, "/", "%2F")
        ; $searchstring = StringReplace ($searchstring, "@", "%40")
        ; $searchstring = StringReplace ($searchstring, ":", "%3A")

    #ce

    $foo = InetRead("https://www.googleapis.com/language/translate/v2?key=" & $apikey & "&source=" & $SL & "&target=" & $TL & $searchstring, 0)

    If @error Then
        $error = @error
        ClipPut("https://www.googleapis.com/language/translate/v2?key=" & $apikey & "&source=" & $SL & "&target=" & $TL & $searchstring)
        MsgBox(0, "Error #" & $error, "Google is unhappy with the request.  We've added the URL to the clipboard.  Try pasting it in a browser and see if there's an error message. Also double-check if the URL you paste is the same as the URL that is left after the page is visited.  After you click 'OK', it will no longer be on the clipboard.", 0)
    EndIf


    $foo = BinaryToString($foo, 4)

    If StringInStr($foo, '"errors": [') Then
        MsgBox(0, "Google throws an error...", $foo, 0)
    Else

        $foosplit = StringSplit($foo, '"translatedText": "', 1)

        For $m = 2 To $foosplit[0]
            $foosplit2 = StringSplit($foosplit[$m], '"', 1)
            $translation = $foosplit2[1]

            $translation = StringReplace($translation, "\u200b", "")
            $translation = StringReplace($translation, "&#39;", "'")
            $translation = StringReplace($translation, "&quot;", '"')
            $translation = StringReplace($translation, "&amp;", '&')
            $translation = StringReplace($translation, "\u003c", '<')
            $translation = StringReplace($translation, "\u003e", '>')
            $translation = StringReplace($translation, "&lt;", '<')
            $translation = StringReplace($translation, "&gt;", '>')


            $bigtranslation = $bigtranslation & $translation & @CRLF

            $numofstrings = $numofstrings + 1
            TrayTip("Progress...", $numofstrings & " done so far out of " & $inputfilesplit[0], 100)

        Next

    EndIf

Next

; Then give user end-report

$len = StringLen($inputfile)
$price = $len / 1000000 * 20


If $cliporno = 6 Then
    ClipPut($bigtranslation)
    MsgBox(0, "Translation on clipboard", "The translation is on the clipboard." & @CRLF & "Estimated cost: USD " & $price, 0)
Else
    $outputfile = FileOpen($inputfileopendialog & "_output.txt", 129)
    FileWrite($outputfile, $bigtranslation & @CRLF)
    MsgBox(0, "Translated file completed", $inputfilesplit[0] & " lines sent to Google, and translation saved to" & @CRLF & $inputfileopendialog & "_output.txt" & @CRLF & "Estimated cost: USD " & $price, 0)
EndIf

 

Edited by Jos
added codebox and tidied to code
Link to comment
Share on other sites

  • Solution

Hi guys,

I just had the idea to ask ChatGPT my question above and he created an AutoIT script in seconds that works great and does exactly what I need. That's amazing! Somehow a bit scary too. Anyway, you don't need to bother anymore, the problem is solved.
Thanks anyway and best wishes!

By the way, in case anyone is interested: I subsequently asked ChatGPT to create the same script for me in AutoHotkey and he failed miserably at it, even after several attempts in both AutHotkey version 1.1, and 2.0. Wonder why that is? I have no clue anyways ...

ChatGPT’s script version:

#include <Inet.au3>
#include <Array.au3>
#include <String.au3>
#include <Clipboard.au3>

; Set API key and language codes
Local $apikey = “XXX” ; Insert your API key here
Local $sSourceLang = “en” ; Source language, e.g. “en” for English
Local $sTargetLang = “de” ; Target language, e.g. “de” for German

; Read content of the clipboard
Local $sText = ClipGet()
If @error Then Exit ; Exits the script if the clipboard is empty or inaccessible

; URL-encode text and compose request
Local $sEncodedText = StringToBinary($sText, 4)
$sEncodedText = StringTrimLeft($sEncodedText, 2)
$sEncodedText = StringRegExpReplace($sEncodedText,(..), “%\1)
Local $sApiUrl = “https://www.googleapis.com/language/translate/v2?key=& $apikey &&source=& $sSourceLang &&target=& $sTargetLang &&q=& $sEncodedText

; Send request to Google
Local $sResponse = InetRead($sApiUrl, 0)
If @error Then Exit ; Terminates the script if an error occurs during the request

; Convert response to string and extract translated text
$sResponse = BinaryToString($sResponse, 4)
Local $aMatches = StringRegExp($sResponse, '“translatedText”:\s*“([^”]+)"', 3)
If Not IsArray($aMatches) Then Exit ; Exits the script if no translated text is found

; Copy the translation to the clipboard
ClipPut($aMatches[0])

 

Link to comment
Share on other sites

  • Developers

Moved to the appropriate AutoIt General Help and Support forum, as the Developer General Discussion forum very clearly states:

Quote

General development and scripting discussions.


Do not create AutoIt-related topics here, use the AutoIt General Help and Support or AutoIt Technical Discussion forums.

Moderation Team

SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource   Forum etiquette  Forum Rules 
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Link to comment
Share on other sites

  • Developers
12 minutes ago, tomasi said:

By the way, in case anyone is interested: I subsequently asked ChatGPT to create the same script for me in AutoHotkey and he failed miserably at it, even after several attempts in both AutHotkey version 1.1, and 2.0. Wonder why that is? I have no clue anyways ...

No need to discuss that language here, considering the history. ;) 

SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource   Forum etiquette  Forum Rules 
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

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