Jump to content

AutoIT translate language [UDF] Use Azure Cognitive Services Translator APIs


Recommended Posts

Get Subscription Key/Region from Resource Management Keys and Endpoint  portal azure page !

Standalone script:

;#include <String.au3>
;#include <File.au3>
Opt("MustDeclareVars", 1) ;0=no, 1=require pre-declaration
Global $oErrorHandler = ObjEvent("AutoIt.Error", "__COMErrFunc")

; ============================================================================================================================
; Require Microsoft Azure Account and Bing Translator Text API Subscription Key
Global $sSubscription_Key = '' ; ENTER YOUR Subscription Key HERE
Global $sSubscription_Region = 'eastasia' ; ENTER YOUR Subscription Region HERE

; Define the source and target languages
Global $slang_From = "auto"
Global $slang_TO = "en"

;Eg 1
Global $vi_Text = "Tôi Yêu Bạn"
MsgBox(0, 'Bing Translate', "Translate from " & $slang_From & "= " & $vi_Text & @CRLF & "Translated to " & $slang_TO & "= " & _Bing_TranslateText($vi_Text, $slang_From, $slang_TO))
; End eg 1 !

;Eg 2
; Specify the folder containing the text files
Global $sWorkingDir = @ScriptDir & "\TEST"
Global $sFileTranslated_Prefix = '_translated'

Global $Retun = _Translate_All_TxtFileInDir($sWorkingDir, '*', $slang_From, $slang_TO)
If $Retun Then
    If FileExists($sWorkingDir & "\*" & $sFileTranslated_Prefix & ".txt") Then
        ; Notify the user that the translation is complete
        MsgBox(0, "Translation Complete", "All files in the folder " & $sWorkingDir & @CRLF & "have been translated and saved with the prefix " & $sFileTranslated_Prefix)
    Else
        MsgBox(48, "Error /!\", "No files translated in the folder: " & $sWorkingDir)
    EndIf
Else
    MsgBox(16, "Error /!\", "No files in the folder: " & $sWorkingDir)
EndIf
; End eg 2 !

; ============================================================================================================================
; Function:
Func _Translate_All_TxtFileInDir($sFilePath, $sFilter = "*", $slang_From = 'Auto', $slang_TO = "en", $sFileTranslated_Prefix = '_translated')
    If Not FileExists($sFilePath) Then Return SetError(1, 0, 0)
    ; Get an array of all the files in the folder
    If ($sFilter == "*.*") Or ($sFilter == Default) Or ($sFilter == '') Then $sFilter = "*"
    $sFilter = $sFilter & ".txt"
    Local $aListFile, $aFileList = _FileListToArray($sFilePath, $sFilter, 1, 1)
    If Not IsArray($aFileList) Then Return SetError(1, 0, 0)
    For $i = 1 To UBound($aFileList) - 1
        If Not StringInStr($aFileList[$i], $sFileTranslated_Prefix) Then $aListFile &= '|' & $aFileList[$i]
    Next
    $aFileList = StringSplit($aListFile, '|', 2)
    Local $sFileContent, $translated_text, $hOpen, $sFilePath_translated
    ; Loop through the array of files
    For $i = 1 To UBound($aFileList) - 1
        ; Read the text file
        ConsoleWrite("- Reading the file " & $i & ":" & $aFileList[$i] & @CRLF)
        $sFileContent = FileRead($aFileList[$i])
        If (@error) Then
            ConsoleWrite("An error occurred while reading the text file:" & $aFileList[$i] & @CRLF)
            ;MsgBox(16, "Error", "An error occurred while reading the text file:" & $aFileList[$i])
            ContinueLoop
        EndIf
        ; Translate the text
        ConsoleWrite("- Start translating..." & @CRLF)
        $translated_text = _Bing_TranslateText($sFileContent, $slang_From, $slang_TO)
        If (@error) Then
            ConsoleWrite("! Error: An error occurred while translate text !" & @CRLF)
            ;MsgBox(16, "Error", "An error occurred while translate text !")
            ContinueLoop
        EndIf
        ; Write the translated text to a new file
        $sFilePath_translated = StringReplace($aFileList[$i], ".txt", $sFileTranslated_Prefix & ".txt")
        ConsoleWrite("- Writing the translated text to the file:" & $sFilePath_translated & @CRLF)
        $hOpen = FileOpen($sFilePath_translated, 2 + 8 + 128)
        FileWrite($hOpen, $translated_text)
        If (@error) Then
            FileClose($hOpen)
            ConsoleWrite("! Error: An error occurred while writing the translated text to the file:" & $sFilePath_translated & @CRLF)
            ;MsgBox(16, "Error", "An error occurred while writing the translated text to the file:" & $sFilePath_translated)
            ContinueLoop
        EndIf
        FileClose($hOpen)
        ConsoleWrite("+ " & $i & " OK !" & @CRLF)
        $sFileContent = ''
        $translated_text = ''
        $sFilePath_translated = ''
        $hOpen = 0
    Next
    Return 1
EndFunc   ;==>_Translate_All_TxtFileInDir

; Function to translate text using Bing Translator API
Func _Bing_TranslateText($sContent, $slang_From = 'Auto', $slang_TO = "en")
    Local $iSubscriptionKey = $sSubscription_Key
    If ($iSubscriptionKey == '') Then
        Exit MsgBox(16, 'Error /!\', "Ocp-Apim-Subscription-Key is Not Enter !")
        ;Return SetError(1, 0, '')
    EndIf
    Local $iSubscriptionRegion = $sSubscription_Region
    If ($iSubscriptionRegion == '') Then
        Exit MsgBox(16, 'Error /!\', "Ocp-Apim-Subscription-Region is Not Enter !")
        ;Return SetError(1, 0, '')
    EndIf
    $slang_From = StringStripWS($slang_From, 8)
    $slang_TO = StringStripWS($slang_TO, 8)
    If ($slang_From == '') Then $slang_From = 'Auto'
    ConsoleWrite("> Translate from language: " & $slang_From & ' [TO> ' & $slang_TO & @CRLF)
    ConsoleWrite("> //-------------------------- Text:" & @CRLF & $sContent & @CRLF)
    ConsoleWrite("---------------------------------- //" & @CRLF)
    $slang_From = StringLower($slang_From)
    $slang_TO = StringLower($slang_TO)
    If ($slang_From == 'auto') Then $slang_From = ''
    Local $apiURL = "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&from=" & $slang_From & "&to=" & $slang_TO
    Local $oHTTP = ObjCreate("WinHttp.WinHttpRequest.5.1")
    $oHTTP.Open("POST", $apiURL)
    $oHTTP.SetRequestHeader("Content-Type", "application/json; charset=UTF-8")
    $oHTTP.SetRequestHeader("Ocp-Apim-Subscription-Key", $iSubscriptionKey)
    $oHTTP.SetRequestHeader("Ocp-Apim-Subscription-Region", $iSubscriptionRegion)
    $oHTTP.Send('[{"Text": "' & $sContent & '"}]')
    If $oHTTP.Status <> 200 Then
        ConsoleWrite("! Error: An error occurred while connecting to the Bing Translator API. HTTP status code: " & $oHTTP.Status & " " & $oHTTP.StatusText & @CRLF)
        ;MsgBox(16, "Error", "An error occurred while connecting to the Bing Translator API. HTTP status code: " & $oHTTP.Status & " " & $oHTTP.StatusText)
        Return SetError(2, 0, "")
    EndIf
    Local $Json_Response = $oHTTP.ResponseText
    ConsoleWrite("> Microsoft Translator Response: " & $Json_Response & @CRLF)
    Local $aTranslated = _StringBetween($Json_Response, '"translations":[{"text":"', '","to":"' & $slang_TO & '"}]}')
    If @error Or (Not IsArray($aTranslated)) Then
        ConsoleWrite("! Error: An error occurred while decoding the JSON response from the Bing Translator API." & @CRLF)
        ;MsgBox(16, "Error", "An error occurred while decoding the JSON response from the Bing Translator API.")
        Return SetError(2, 0, "")
    EndIf
    Local $sContent_Translated = $aTranslated[0]
    $sContent_Translated = StringReplace($sContent_Translated, '\r\n', @CRLF)
    ConsoleWrite(">//---------------- Translated text :" & @CRLF & $sContent_Translated & @CRLF)
    ConsoleWrite("---------------------------------- //" & @CRLF)
    Return SetError(0, 0, $sContent_Translated)
EndFunc   ;==>_Bing_TranslateText

Func __COMErrFunc()
    ;Keep Script Runing on Obj Error!
EndFunc   ;==>__COMErrFunc


; ============================================================================================================================
; Functions on Include:
Func _StringBetween($sString, $sStart, $sEnd, $iMode = 0, $bCase = False)
    $sStart = $sStart ? "\Q" & $sStart & "\E" : "\A"
    If $iMode <> 1 Then $iMode = 0
    If $iMode = 0 Then
        $sEnd = $sEnd ? "(?=\Q" & $sEnd & "\E)" : "\z"
    Else
        $sEnd = $sEnd ? "\Q" & $sEnd & "\E" : "\z"
    EndIf
    If $bCase = Default Then
        $bCase = False
    EndIf
    Local $aRet = StringRegExp($sString, "(?s" & (Not $bCase ? "i" : "") & ")" & $sStart & "(.*?)" & $sEnd, 3)
    If @error Then Return SetError(1, 0, 0)
    Return $aRet
EndFunc   ;==>_StringBetween
Func _FileListToArray($sFilePath, $sFilter = "*", $iFlag = 0, $bReturnPath = False)
    Local $sDelimiter = "|", $sFileList = "", $sFileName = "", $sFullPath = ""
    $sFilePath = StringRegExpReplace($sFilePath, "[\\/]+$", "") & "\"
    If $iFlag = Default Then $iFlag = 0
    If $bReturnPath Then $sFullPath = $sFilePath
    If $sFilter = Default Then $sFilter = "*"
    If Not FileExists($sFilePath) Then Return SetError(1, 0, 0)
    If StringRegExp($sFilter, "[\\/:><\|]|(?s)^\s*$") Then Return SetError(2, 0, 0)
    If Not ($iFlag = 0 Or $iFlag = 1 Or $iFlag = 2) Then Return SetError(3, 0, 0)
    Local $hSearch = FileFindFirstFile($sFilePath & $sFilter)
    If @error Then Return SetError(4, 0, 0)
    While 1
        $sFileName = FileFindNextFile($hSearch)
        If @error Then ExitLoop
        If ($iFlag + @extended = 2) Then ContinueLoop
        $sFileList &= $sDelimiter & $sFullPath & $sFileName
    WEnd
    FileClose($hSearch)
    If $sFileList = "" Then Return SetError(4, 0, 0)
    Return StringSplit(StringTrimLeft($sFileList, 1), $sDelimiter)
EndFunc   ;==>_FileListToArray

 

Regards,
 

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