Translating a curl command to R using httr (specifically '--data-binary @')

∥☆過路亽.° 提交于 2019-12-11 07:18:50

问题


I am trying to transcribe some sound files to text using bing speech-to-text.

The following command works in command line (using git bash on Windows 10):

curl  -v -X POST "https://speech.platform.bing.com/speech/recognition/interactive/
cognitiveservices/v1?language=<LANG>&format=detailed" -H "Transfer-Encoding: 
chunked" -H "Ocp-Apim-Subscription-Key: <MY KEY>" -H "Content-type: 
audio/wav; codec=audio/pcm; samplerate=16000" --data-binary @<MY .WAV-FILE>

I've tried this, but it doesnt work:

httr::POST(url = myURL,
           add_headers("Ocp-Apim-Subscription-Key" = key,
                       "Content-type" = "audio/wav; codec=audio/pcm; samplerate=16000",
                       "Transfer-Encoding" = "chunked"),
           body = (list("file" = upload_file("PATH_TO_FILE.wav"))),
           verbose())

It returns this output: Response

[https://speech.platform.bing.com/speech/recognition/dictation/
cognitiveservices/v1?language=<LANG>&format=detailed]
Date: 2017-11-29 13:29
Status: 200
Content-Type: text/plain
Size: 75 B

I believe that the request is related to the interpretation of the .wav file, and that I need to somehow add the '--data-binary' tag to the httr-request. I can see that my "content-type" is plain text, although i've specified. Furthermore: the API documentation specifies that i need to prefix my wav-file with an at-sign.

Any help would be much appreciated.

cheers.

EDIT: Link to API documentation https://docs.microsoft.com/da-dk/azure/cognitive-services/speech/getstarted/getstartedrest?tabs=curl#tabpanel_AFC9x30-dR_curl


回答1:


I figured it out.

The key is to set the proper MIME type in the body. Not setting this MIME type can result in wrongful interpretation on the receiving end, even though we get a response 200 back.

body <- list(file = httr::upload_file(
  paste0(path, "/", f),
  type = "audio/wav; codec=audio/pcm; samplerate=16000"))

where paste0(path, "/", f) is a path to an audio file.

myURL <- sprintf('https://speech.platform.bing.com/speech/recognition/%s/cognitiveservices/v1?language=%s&format=%s',
"dictation",
"da-DK",
"detailed")

rs <- httr::POST(
  url = myURL,
  httr::add_headers(.headers = c("Ocp-Apim-Subscription-Key" = key)),
  httr::add_headers(.headers = c("Transfer-Encoding" = "chunked")),
  body = body)


来源:https://stackoverflow.com/questions/47554132/translating-a-curl-command-to-r-using-httr-specifically-data-binary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!