Jump to content

JSON POST not working using Curl


Recommended Posts

I'm trying to upload to a text-to-speech website. (Beege rewrite of Curl.au3).

#include <Date.au3>
#include <WinAPIDiag.au3>
#include <Curl\Curl.au3>

Test()

Func Test()

    ;Create an array of request headers
    Local $arrHeaders = Curl_Slist_Append(0, "Accept: application/json")
    $arrHeaders = Curl_Slist_Append($arrHeaders, "Content-Type: application/json")

    ;Set up and execute cURL request
    $hCurl = Curl_Easy_Init()
    If Not $hCurl Then Return MsgBox($MB_ICONERROR, "Error", "Curl_Easy_Init() failed.")

    Curl_Easy_Setopt($hCurl, $CURLOPT_URL, "https://speechgen.io/index.php?r=api/text")
    Curl_Easy_Setopt($hCurl, $CURLOPT_HTTPHEADER, $aHeaders)
    Curl_Easy_Setopt($hCurl, $CURLOPT_USERAGENT, "AutoIt/cURL")
    Curl_Easy_Setopt($hCurl, $CURLOPT_VERBOSE, 1)
    Curl_Easy_Setopt($hCurl, $CURLOPT_SSL_VERIFYPEER, 0)
    Curl_Easy_Setopt($hCurl, $CURLOPT_READFUNCTION, Curl_DataReadCallback())
    Curl_Easy_Setopt($hCurl, $CURLOPT_CUSTOMREQUEST, "PUT")
    Curl_Easy_Setopt($hCurl, $CURLOPT_UPLOAD, 1)
    $data = '{"Token":"{redacted}","email":"email@gmail.com","voice":"Ostap","format":"mp3","speed":"0.8","emotion":"good", _
            "pause_sentence":"300","pause_paragraph":"400","bitrate":"48000",'
    $data = $data & '"text":"' & 'Heo світ' & '"}'
    ConsoleWrite(@crlf & $data & @crlf & @crlf)

    Curl_Easy_Setopt($hCurl, $CURLOPT_POSTFIELDS, $data)

    ;Get response code and response
    $iRespCode = Curl_Easy_Perform($hCurl)
    If $iRespCode <> $CURLE_OK Then Return ConsoleWrite("Status Message: " & Curl_Easy_StrError($iRespCode) & @LF)
    $sResponse = BinaryToString(Curl_Data_Get($hCurl))

    ;Clean up curl environment
    Curl_Easy_Cleanup($hCurl)
    Curl_Data_Cleanup($hCurl)

    ;Display response
    ConsoleWrite($sResponse & @CRLF)
EndFunc   ;==>Test

The result is:

* Host speechgen.io:443 was resolved.
* IPv6: (none)
* IPv4: 5.45.72.182
*   Trying 5.45.72.182:443...
* ALPN: curl offers h2,http/1.1
* SSL connection using TLSv1.3 / TLS_AES_256_GCM_SHA384 / [blank] / UNDEF
* ALPN: server accepted http/1.1
* Server certificate:
*  subject: CN=speechgen.io
*  start date: Sep 15 23:13:56 2024 GMT
*  expire date: Dec 14 23:13:55 2024 GMT
*  subjectAltName: host "speechgen.io" matched cert's "speechgen.io"
*  issuer: C=US; O=Let's Encrypt; CN=R10
*  SSL certificate verify result: unable to get local issuer certificate (20), continuing anyway.
*   Certificate level 0: Public key type ? (2048/112 Bits/secBits), signed using sha256WithRSAEncryption
*   Certificate level 1: Public key type ? (2048/112 Bits/secBits), signed using sha256WithRSAEncryption
* Connected to speechgen.io (5.45.72.182) port 443
* using HTTP/1.x
> PUT /index.php?r=api/text HTTP/1.1
Host: speechgen.io
User-Agent: AutoIt/cURL
Accept: */*
Content-Type: application/json
Content-Length: 4
* upload completely sent off: 4 bytes
< HTTP/1.1 200 OK
< Server: nginx/1.14.1
< Date: Mon, 11 Nov 2024 16:06:28 GMT
< Content-Type: text/html; charset=UTF-8
< Transfer-Encoding: chunked
< Connection: keep-alive
< X-Powered-By: PHP/7.3.33
< Access-Control-Allow-Origin: *
< Access-Control-Allow-Methods: GET, POST
< Access-Control-Allow-Headers: X-Requested-With
< Expires: Thu, 19 Nov 1981 08:52:00 GMT
< Cache-Control: no-store, no-cache, must-revalidate
< Pragma: no-cache
< Set-Cookie: PHPSESSID=e271ada2cc0504802aa013ef915dfc55; path=/
< 
* Connection #0 to host speechgen.io left intact
{"id":0,"status":-1,"file":"","file_cors":"","parts":0,"parts_done":0,"duration":0,"format":"mp3","error":"Data is empty , use Post or Get request","balans":0}

Apparently it's not getting my data as a POST request??

Edited by JonF
Link to comment
Share on other sites

  • Developers

Did you also fix this line?: 

$data = '{"Token":"{redacted}","email":"email@gmail.com","voice":"Ostap","format":"mp3","speed":"0.8","emotion":"good", _
            "pause_sentence":"300","pause_paragraph":"400","bitrate":"48000",'

which should be:

$data = '{"Token":"{redacted}","email":"email@gmail.com","voice":"Ostap","format":"mp3","speed":"0.8","emotion":"good",' & _
            '"pause_sentence":"300","pause_paragraph":"400","bitrate":"48000",'

Try something like this and see what that does:

#include <Date.au3>
#include <WinAPIDiag.au3>
#include <Curl\Curl.au3>

Test()

Func Test()

    ;Create an array of request headers
    Local $arrHeaders = Curl_Slist_Append(0, "Accept: application/json")
    $arrHeaders = Curl_Slist_Append($arrHeaders, "Content-Type: application/json")

    ;Set up and execute cURL request
    $hCurl = Curl_Easy_Init()
    If Not $hCurl Then Return MsgBox($MB_ICONERROR, "Error", "Curl_Easy_Init() failed.")

    Curl_Easy_Setopt($hCurl, $CURLOPT_URL, "https://speechgen.io/index.php?r=api/text")
    Curl_Easy_Setopt($hCurl, $CURLOPT_HTTPHEADER, $arrHeaders)
    Curl_Easy_Setopt($hCurl, $CURLOPT_USERAGENT, "AutoIt/cURL")
    Curl_Easy_Setopt($hCurl, $CURLOPT_VERBOSE, 1)
    Curl_Easy_Setopt($hCurl, $CURLOPT_SSL_VERIFYPEER, 0)
    Curl_Easy_Setopt($hCurl, $CURLOPT_READFUNCTION, Curl_DataReadCallback())
    ;Curl_Easy_Setopt($hCurl, $CURLOPT_CUSTOMREQUEST, "PUT")
    ;Curl_Easy_Setopt($hCurl, $CURLOPT_UPLOAD, 1)
    $data = '{"Token":"-redacted-","email":"email@gmail.com","voice":"Ostap","format":"mp3","speed":"0.8","emotion":"good",' & _
            '"pause_sentence":"300","pause_paragraph":"400","bitrate":"48000",' & _
            '"text":"Heo світ"}'
    ConsoleWrite(@crlf & $data & @crlf & @crlf)

    Curl_Easy_Setopt($hCurl, $CURLOPT_POSTFIELDS, $data)

    ;Get response code and response
    $iRespCode = Curl_Easy_Perform($hCurl)
    If $iRespCode <> $CURLE_OK Then Return ConsoleWrite("Status Message: " & Curl_Easy_StrError($iRespCode) & @LF)
    $sResponse = BinaryToString(Curl_Data_Get($hCurl))

    ;Clean up curl environment
    Curl_Easy_Cleanup($hCurl)
    Curl_Data_Cleanup($hCurl)

    ;Display response
    ConsoleWrite($sResponse & @CRLF)
EndFunc   ;==>Test

 

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

Thanks for catching another error, but that's not it. It's the value of CURLOPT_POSTFIELDS.

I've discovered that the site wants the data URI encoded in a weird format with the only header  "Content-Type: application/x-www-form-urlencoded". I have had success with  ShellExecuteWait with curl.exe:

#include <FileConstants.au3>
#include <StringConstants.au3>

Func _URIEncode($sData)
  ; Prog@ndy
  Local $aData = StringSplit(BinaryToString(StringToBinary($sData, 4), 1), "")
  Local $nChar
  $sData = ""
  For $i = 1 To $aData[0]
    ; ConsoleWrite($aData[$i] & @CRLF)
    $nChar = Asc($aData[$i])
    Switch $nChar
      Case 45, 46, 48 To 57, 65 To 90, 95, 97 To 122, 126
        $sData &= $aData[$i]
      Case 32
        $sData &= "+"
      Case Else
        $sData &= "%" & Hex($nChar, 2)
    EndSwitch
  Next
  Return $sData
EndFunc   ;==>_URIEncode

Global $Text,$data, $sAddress = 'https://speechgen.io/index.php?r=api/text', $cURLPath = "C:\Program Files\curl-8.11.0_1\bin\curl"

$Text = 'Привіт шановний'

$Command = ' --data "token=-redacted-&email=email%40gmail.com&' & _
    'voice=Ostap&format=mp3&speed=0.8&emotion=good&pause_sentence=300&pause_paragraph=400&bitrate=48000&text=' & _
    _URIEncode($Text) & '" -k -H "Content-Type: application/x-www-form-urlencoded" ' _
     & $sAddress & ' >' & @ScriptDir & '\Result.txt'

$Result = ShellExecuteWait($cURLPath, $Command, "", "", @SW_MINIMIZE)

(Note the encoded "@" in the email adress.) Which produces:

{"id":"32796442","status":1,"file":"https:\/\/speechgen.io\/texttomp3\/20241104\/p_32107758_128.mp3","file_cors":"https:\/\/speechgen.io\/index.php?r=site\/download&prj=32796442&cors=28ee739ca163e1cb41b3b241d677d499","parts":0,"parts_done":0,"duration":"2","format":"mp3","error":"","balans":"19691","cost":"0"}

However, this:

#include <WinAPIDiag.au3>
#include <Curl\Curl.au3> ; Beege rewrite
#include <Constants.au3>

Func _URIEncode($sData)
  Local $aData = StringSplit(BinaryToString(StringToBinary($sData,4),1),"")
  Local $nChar
  $sData=""
  For $i = 1 To $aData[0]
      $nChar = Asc($aData[$i])
      Switch $nChar
          Case 45, 46, 48 To 57, 65 To 90, 95, 97 To 122, 126
              $sData &= $aData[$i]
          Case 32
              $sData &= "+"
          Case Else
              $sData &= "%" & Hex($nChar,2)
      EndSwitch
  Next
  Return $sData
EndFunc

Test()

Func Test()

  Local $arrHeaders = Curl_Slist_Append(0, "Content-Type: application/x-www-form-urlencoded")

  $Text = "Привіт шановний"

  ;Set up and execute cURL request
  $hCurl = Curl_Easy_Init()
  If Not $hCurl Then Return MsgBox($MB_ICONERROR, "Error", "Curl_Easy_Init() failed.")

  Curl_Easy_Setopt($hCurl, $CURLOPT_URL, "https://speechgen.io/index.php?r=api/text")
  Curl_Easy_Setopt($hCurl, $CURLOPT_HTTPHEADER, $arrHeaders)
  Curl_Easy_Setopt($hCurl, $CURLOPT_VERBOSE, 1)
  Curl_Easy_Setopt($hCurl, $CURLOPT_USERAGENT, "AutoIt/cURL")
  Curl_Easy_Setopt($hCurl, $CURLOPT_SSL_VERIFYPEER, 0)
  Curl_Easy_Setopt($hCurl, $CURLOPT_READFUNCTION, Curl_DataReadCallback())
  Curl_Easy_Setopt($hCurl, $CURLOPT_CUSTOMREQUEST, "PUT")
  Curl_Easy_Setopt($hCurl, $CURLOPT_UPLOAD, 1)
  Curl_Easy_Setopt($hCurl, $CURLOPT_POST, 1)
  $data = '"token=-redacted-&email=email%40gmail.com&', & _
         'voice=Ostap&format=mp3&speed=0.8&emotion=good&pause_sentence=300&pause_paragraph=400&bitrate=48000&text=' & _
         _URIEncode($Text) & '"'
  ConsoleWrite(@crlf & $data & @crlf & @crlf)

  Curl_Easy_Setopt($hCurl, $CURLOPT_POSTFIELDS, $data)

  $iRespCode = Curl_Easy_Perform($hCurl)
  If $iRespCode <> $CURLE_OK Then Return ConsoleWrite("Status Message: " & Curl_Easy_StrError($iRespCode) & @LF)
  $sResponse = BinaryToString(Curl_Data_Get($hCurl))

  ;Clean up curl environment
  Curl_Easy_Cleanup($hCurl)
  Curl_Data_Cleanup($hCurl)

  ;Display response
  ConsoleWrite($sResponse & @CRLF)
EndFunc

Produces:

{"id":0,"status":-1,"file":"","file_cors":"","parts":0,"parts_done":0,"duration":0,"format":"mp3","error":"Data is empty , use Post or Get request","balans":0}+>09:44:47 AutoIt3.exe ended.rc:0

Note  "error":"Data is empty , use Post or Get request"

I tried setting up a pointer a found at:

 

;Create binary buffer and store http post data in it
    $tByteBuffer = DllStructCreate("byte buffer[1000];")
    If @error Then Exit MsgBox($MB_ICONERROR + $MB_TOPMOST, "ERROR", "Failed to create string buffer - @error = " & @error)
    $tByteBuffer.buffer = $data
    Curl_Easy_Setopt($hCurl, $CURLOPT_POSTFIELDS, $tByteBuffer.buffer)

But it made no difference.

Link to comment
Share on other sites

  • Developers

What about this version?: 

#include <Date.au3>
#include <WinAPIDiag.au3>
#include <Curl.au3>

Test()

Func Test()
    ;Set up and execute cURL request
    $hCurl = Curl_Easy_Init()
    If Not $hCurl Then Return MsgBox($MB_ICONERROR, "Error", "Curl_Easy_Init() failed.")

    $url = "https://speechgen.io/index.php?r=api/text" ;
    $Text = "Привіт шановний"
    $data = 'token=-redacted-' & _
            '&email=' & _URIEncode('email@gmail.com') & _
            '&voice=Ostap' & _
            '&format=mp3' & _
            '&speed=0.8' & _
            '&emotion=good' & _
            '&pause_sentence=300' & _
            '&pause_paragraph=400' & _
            '&bitrate=48000' & _
            '&text=' & _URIEncode($Text)
    ConsoleWrite("Data: " & $data & @CRLF)
    $CURLOPT_RETURNTRANSFER = 19913
    Curl_Easy_Setopt($hCurl, $CURLOPT_RETURNTRANSFER, 1) ;
    Curl_Easy_Setopt($hCurl, $CURLOPT_URL, $url) ;
    Curl_Easy_Setopt($hCurl, $CURLOPT_HEADER, False) ;
    Curl_Easy_Setopt($hCurl, $CURLOPT_SSL_VERIFYHOST, False) ;
    Curl_Easy_Setopt($hCurl, $CURLOPT_POST, 1) ;
    Curl_Easy_Setopt($hCurl, $CURLOPT_POSTFIELDS, $data)

    ;Get response code and response
    $iRespCode = Curl_Easy_Perform($hCurl)
    If $iRespCode <> $CURLE_OK Then Return ConsoleWrite("Status Message: " & Curl_Easy_StrError($iRespCode) & @LF)
    $sResponse = BinaryToString(Curl_Data_Get($hCurl))

    ;Clean up curl environment
    Curl_Easy_Cleanup($hCurl)
    Curl_Data_Cleanup($hCurl)

    ;Display response
    ConsoleWrite($sResponse & @CRLF)
EndFunc   ;==>Test

Func _URIEncode($sData)
    ; Prog@ndy
    Local $aData = StringSplit(BinaryToString(StringToBinary($sData, 4), 1), "")
    Local $nChar
    $sData = ""
    For $i = 1 To $aData[0]
        ; ConsoleWrite($aData[$i] & @CRLF)
        $nChar = Asc($aData[$i])
        Switch $nChar
            Case 45, 46, 48 To 57, 65 To 90, 95, 97 To 122, 126
                $sData &= $aData[$i]
            Case 32
                $sData &= "+"
            Case Else
                $sData &= "%" & Hex($nChar, 2)
        EndSwitch
    Next
    Return $sData
EndFunc   ;==>_URIEncode

I took the Example of a short text voiceover in PHP variant 1  from their WebSite and converted that to Autoit3.

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

Why are you insisting on using UDFs that are based on the libcurl API's?  That is probably THE most difficult to use for novices and requires a much deeper understanding of HTTP requests and the libcurl APIs themselves..  As you probably read in the post you referenced above, in the last post, I mentioned several other ways that you can do your request to speechgen.io.  Most of those alternative ways are much easier to understand, script, and maintain.  If you are adamant about using Beege's UDF lib, then try the script below.  There were a few different ways to resolve the issues.  The script below is the simplest of the ways and didn't require and DllStructs.  If it does not work, then please post the output.

Keep in mind that without a valid speechgen.io token, I am not able to test and verify that the script works.  So there may be minor tweaks that are needed.  The output from the script below will let me know.

If you have questions about the script, please feel free to ask.

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

#include <Constants.au3>
#include <curl-beege\curl.au3> ; <== Modify path to UDF as needed


curl_post_example()

Func curl_post_example()
    Local $hCurl        = Null, _
          $hReqHeaders  = Null, _
          $hRespBody    = 1, _
          $hRespHeaders = 2

    Local $iRetCode    = 0, _
          $iRespCode   = 0

    Local $sPostData       = _
        '{'                             & _
        '  "Token": "1234-redacted",'   & _  ;<== Enter your token
        '  "email": "email@gmail.com",' & _
        '  "voice": "Ostap",'           & _
        '  "format": "mp3",'            & _
        '  "speed": "0.8",'             & _
        '  "emotion": "good",'          & _
        '  "pause_sentence": "300",'    & _
        '  "pause_paragraph": "400",'   & _
        '  "bitrate": "48000",'         & _
        '  "text": "Привіт шановний"'   & _
        '}'


    ;Initialize EasyCurl POST request and set options
    $hCurl       = Curl_Easy_Init()
    $hReqHeaders = Curl_Slist_Append($hReqHeaders, "Content-Type: application/json")
    $hReqHeaders = Curl_Slist_Append($hReqHeaders, "Accept: application/json")

    Curl_Easy_Setopt($hCurl, $CURLOPT_URL, "https://speechgen.io/index.php?r=api/text")
    Curl_Easy_Setopt($hCurl, $CURLOPT_HTTPHEADER, $hReqHeaders)
    Curl_Easy_Setopt($hCurl, $CURLOPT_SSL_VERIFYPEER, 0)
    Curl_Easy_Setopt($hCurl, $CURLOPT_FOLLOWLOCATION, 1)
    Curl_Easy_Setopt($hCurl, $CURLOPT_WRITEFUNCTION, Curl_DataWriteCallback())
    Curl_Easy_Setopt($hCurl, $CURLOPT_WRITEDATA, $hRespBody)
    Curl_Easy_Setopt($hCurl, $CURLOPT_HEADERFUNCTION, Curl_DataWriteCallback())
    Curl_Easy_Setopt($hCurl, $CURLOPT_HEADERDATA, $hRespHeaders)
    Curl_Easy_Setopt($hCurl, $CURLOPT_COPYPOSTFIELDS, $sPostData)

    ;Submit request
    $iRetCode = Curl_Easy_Perform($hCurl)
    If $iRetCode <> $CurlE_OK Then Exit MsgBox($MB_ICONERROR + $MB_TOPMOST, "ERROR", "Request failed." & @CRLF & $iRetCode & " " & Curl_Easy_StrError($iRetCode))

    ;Display response info
    ConsoleWrite("POST Data:      " & $sPostData & @CRLF)
    ConsoleWrite("Curl RetCode:   " & $iRespCode & " " & Curl_Easy_StrError($iRetCode) & @CRLF)
    ConsoleWrite("HTTP Resp Code: " & Curl_Easy_GetInfo($hCurl, $CurlINFO_RESPONSE_CODE) & @CRLF)
    ConsoleWrite("Content Type:   " & Curl_Easy_GetInfo($hCurl, $CurlINFO_CONTENT_TYPE)  & @CRLF)
    ConsoleWrite("Content Size:   " & Curl_Easy_GetInfo($hCurl, $CurlINFO_SIZE_DOWNLOAD) & @CRLF)
    ConsoleWrite(@CRLF & "Response Headers:" & @CRLF & BinaryToString(Curl_Data_Get($hRespHeaders), $SB_UTF8) & @CRLF)
    ConsoleWrite(@CRLF & "Response Body:"    & @CRLF & BinaryToString(Curl_Data_Get($hRespBody)   , $SB_UTF8) & @CRLF)

    ;Clean up
    Curl_Data_Cleanup($hRespBody)
    Curl_Data_Cleanup($hRespHeaders)
    Curl_Slist_Free_All($hReqHeaders)
    Curl_Easy_Cleanup($hCurl)
EndFunc

 

Edited by TheXman
Link to comment
Share on other sites

I appreciate your attempt, but perhaps you should have read the tropic before stepping in. The site will not accept those headers and will not accept a JSON formatted query and will not accept an unencoded string for the "text" parameter. 

After modifying until it works it fails in the same manner:

POST Data:      "token=-redacted-&email=email%40gmail.com&voice=Ostap&format=mp3&speed=0.8&emotion=good&pause_sentence=300&pause_paragraph=400&bitrate=48000&text=%D0%9F%D1%80%D0%B8%D0%B2%D1%96%D1%82+%D1%88%D0%B0%D0%BD%D0%BE%D0%B2%D0%BD%D0%B8%D0%B9"
Curl RetCode:   0 No error
HTTP Resp Code: 200
Content Type:   text/html; charset=UTF-8
Content Size:   159

Response Headers:


Response Body:
HTTP/1.1 200 OK
Server: nginx/1.14.1
Date: Thu, 14 Nov 2024 19:36:04 GMT
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
X-Powered-By: PHP/7.3.33
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: X-Requested-With
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate
Pragma: no-cache
Set-Cookie: PHPSESSID=3f0b423fffdf24f42b2f966cba92c010; path=/

{"id":0,"status":-1,"file":"","file_cors":"","parts":0,"parts_done":0,"duration":0,"format":"mp3","error":"Data is empty , use Post or Get request","balans":0}

I looked at winhttp and couldn't make head nor tail of it. Using COM objects I don't understand at all. I'll try that again.

I'm a novice at AUtoIT but give me FORTRAN, Basic, i386 assembly language, or IBM 370 assembly language I can run rings around you.

I'll look at WinHTTP.au3 again.

Edited by JonF
Link to comment
Share on other sites

On 11/14/2024 at 7:41 PM, JonF said:

perhaps you should have read the tropic before stepping in

As I said, without a token, I can't test the script and that it may need to be tweaked.  Changing the POST data format and encoding some of its values are small tweaks.  

Pardon me for "stepping in" to try to help you.  It won't happen again.  :bye:

 


 

Edit:

For the record, I bought a token so I could test my script.  After changing the post data to the correct format, it worked just fine.  It was a VERY simple change. 

For someone who would say they can "run rings around me", when they know nothing about me, says more about you than it does about me.  By the way,  ALC/COBOL/CICS/RPG/DB2/IMS on IBM MVS 370, were my first professional languages out of college back in the 80's.  Could you can "run rings around me" back then, maybe, but I seriously doubt it. :rolleyes:

Result:

{
  "id": "32XXXXXX",
  "status": 1,
  "file": "https://speechgen.io/texttomp3/20241116/p_33027160_669.mp3",
  "file_cors": "https://speechgen.io/index.php?r=site/download&prj=329XXXX6&cors=be7aed14388cb88e754998eXXXXXXXX",
  "parts": 0,
  "parts_done": 0,
  "duration": "1",
  "format": "mp3",
  "error": "",
  "balans": "25489",
  "cost": "0"
}

:muttley:

Edited by TheXman
Link to comment
Share on other sites

Your edited example doesn't work for me. I changed only the cURL path, token, and email.

Response Body:
{"id":0,"status":-1,"file":"","file_cors":"","parts":0,"parts_done":0,"duration":0,"format":"mp3","error":"Data is empty , use Post or Get request","balans":0}
Link to comment
Share on other sites

On 11/16/2024 at 3:18 PM, JonF said:

Your edited example doesn't work for me.

I didn't edit the script in my previous post.  I only changed a grammatical error in the text of that post.  The change I made to the POST data was made locally on my PC.

As I said before, me "stepping in" to help you would not and will not happen again.

Edited by TheXman
Link to comment
Share on other sites

I followed TheXman's advice and got it to work using COM.

; Example of using the Windows Component Object Model to call the SpeechGen API

#include <MsgBoxConstants.au3>
#include <StringConstants.au3>

; Data for SpeechGen
Local $Token = "SecretKeyInYourProfile", _
    $Email = "YourEmail@gmail.com, _
    $Text = "Привіт шановний", _
    $Voice = "Ostap", _
    $Format = "mp3", _
    $Speed = "0.8"


; All arguments are strings. Arguments given defalt values are optional, but you cannot
; specify any arguments after using an argument with a default. See the test below, where
; $sFormat must be specified because $sSpeed is specified.
; Return value: URL of the speak file and set @error=0 if the process worked,
;               error message string and set @error=1 if it did not.
Func SpeechGen($sToken, $sEmail, $sData, $sVoice, $sFormat = "mp3", $sSpeed = "1.0", $sEmotion = "good", _
    $sPause_sentence = "300", $sPause_paragraph = "400", $sBitrate = "48000")

  $sRequest = 'token=' & $sToken & '&email=' & $sEmail & '&voice=' & $sVoice _
       & '&format=' & $sFormat & '$speed=' & $sSpeed & '&emotion=' & $sEmotion _
       & '&pause_sentence=' & $sPause_sentence & '&pause_paragraph=' _
       & $sPause_paragraph & '&bitrate=' & $sBitrate & '&text=' & $sData
  ; MsgBox($MB_OK, "Request",$sRequest)
  Global $oMyError = ObjEvent("AutoIt.Error", "MyCOMErrFunc") ; Initialize a COM error handler
  Local $oHTTP = ObjCreate("winhttp.winhttprequest.5.1")
  $oHTTP.Open("POST", "https://speechgen.io/index.php?r=api/text", False)
  $oHTTP.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded")
  $oHTTP.Send($sRequest)
  Local $oReceived = $oHTTP.ResponseText
  $SpeechGenError = StringRegExp($oReceived, 'https:.*?\.mp3', $STR_REGEXPARRAYMATCH)
  ConsoleWrite(@CRLF & "Received: " & $oReceived & @CRLF)
  ;MsgBox($MB_OK, "Received", $oReceived)
  Local $SpeechGenError = StringRegExp($oReceived, 'error":".*?"', $STR_REGEXPARRAYMATCH)
  If StringLen($SpeechGenError[0]) > 9 Then
    Local $sErrorMessage = StringReplace(StringTrimLeft($SpeechGenError[0], 7), '"', "")
    MsgBox(BitOR($MB_ICONERROR, $MB_OK), "Error", $sErrorMessage & @CRLF & @CRLF & $oReceived, 10)
    Return SetError(1, 1, $sErrorMessage)
  Else
    $sURLReceived = StringRegExp($oReceived, 'https:.*?\.mp3', $STR_REGEXPARRAYMATCH)
    ConsoleWrite(@CRLF & "URL: " & StringReplace($sURLReceived[0], "\", "") & @CRLF & @CRLF)
    Return SetError(0, 0, StringReplace($sURLReceived[0], "\", ""))
  EndIf
EndFunc   ;==>SpeechGen

; COM error handler
Func MyCOMErrFunc()
  MsgBox(0, "AutoItCOM", "We intercepted a COM Error !" & @CRLF & @CRLF & _
      "err.description is: " & @TAB & $oMyError.description & @CRLF & _
      "err.windescription:" & @TAB & $oMyError.windescription & @CRLF & _
      "err.number is: " & @TAB & Hex($oMyError.number, 8) & @CRLF & _
      "err.lastdllerror is: " & @TAB & $oMyError.lastdllerror & @CRLF & _
      "err.scriptline is: " & @TAB & $oMyError.scriptline & @CRLF & _
      "err.source is: " & @TAB & $oMyError.source & @CRLF & _
      "err.helpfile is: " & @TAB & $oMyError.helpfile & @CRLF & _
      "err.helpcontext is: " & @TAB & $oMyError.helpcontext _
      )
EndFunc   ;==>MyCOMErrFunc

; Test the system
Func TestSpeechGen()
  Local $Result = SpeechGen($Token, $Email, $Text, $Voice, $Format, $Speed)
  If @error = 0 Then
    MsgBox($MB_OK, "URL of file", $Result)
    ; Un-comment to download the MP3
    ; InetGet($Result, @ScriptDir & "\Result.mp3")
  Else
    MsgBox(BitOR($MB_ICONERROR, $MB_OK), "Error", $Result)
  EndIf
EndFunc   ;==>TestSpeechGen

 

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