Invalid audio channel count for single channel audio file - speech-to-text

I have a wav audio file, which i have converted to single channel and further onto FLAC audio form.
sound = AudioSegment.from_wav("/Users/tcssig/Downloads/sample.wav")
sound.channels
1
request.json
{
"config": {
"encoding":"FLAC",
"languageCode": "fi-FI"
},
"audio": {
"uri":"gs://g_stt/fin11.flac"
}
}
API Request
import requests
headers = {
'Content-Type': 'application/json',
}
params = (
('key', '****************************'),
)
data = open('/Users/tcssig/Documents/request.json', 'rb').read()
response = requests.post('https://speech.googleapis.com/v1/speech:longrunningrecognize', headers=headers, params=params, data=data)
Using the google speech to text api for generating a transcript, it gives me the error response :
{'error': {'code': 400,
'message': 'Invalid audio channel count',
'status': 'INVALID_ARGUMENT'}}
Because the API supports Mono channel and not the stereo channel, i can not understand why is this happening for a single audio channel file in FLAC format.

Related

Python Requests Post - Additional field is not recognized for file upload

I have to post a file using Multipart upload to a company-internal REST service. The endpoint needs the file as property "file" and it needs an additional property "DestinationPath". Here is what I do:
url = r"http://<Internal IP>/upload"
files = {
"DestinationPath": "/some/where/foo.txt",
"file": open("test.txt", "rb")
}
response = requests.post(url, files=files)
The server complains that it can't get the "DestinationPath". Full error message I receive is:
{'errors': {'DestinationPath': ['The DestinationPath field is required.']},
'status': 400,
'title': 'One or more validation errors occurred.',
'traceId': '00-1993fbc53ab2ee418b683915dd7a440a-2338bd9cf34d414a-00',
'type': 'https://tools.ietf.org/html/rfc7231#section-6.5.1'}
The file upload works in curl, thus it must be python specific.
You might want to try using the data argument instead of files.
response = requests.post(url, data=files)
Thanks to #etemple1 I found the solution to my question:
url = r"http://<Internal IP>/upload"
data = {
"DestinationPath": "/some/where/foo.txt",
}
with open("test.txt", "rb") as content:
files = {
"file": content.read(),
}
response = requests.post(url, data=data, files=files)
The data for the multipart upload needed to be divided between "data" and "files". They are later combined in the body of the http post by the requests library.

How to upload video as a multipart/form body content in Python for Video Indexer API?

I am trying to upload a video file from local machine using VideoIndexer API in Python. I am expected to upload video as a multipart/form body content. Following is my code (Variable values like accountID, name, location are not pasted below),
# Request headers
headers = {
'x-ms-client-request-id': '',
'Content-Type': 'multipart/form-data',
'Ocp-Apim-Subscription-Key': 'xxxxxxxxx',
}
# Request parameters
params = urllib.parse.urlencode({
'privacy': 'Private',
'description': 'testing',
})
try:
conn = http.client.HTTPSConnection('api.videoindexer.ai')
conn.request("POST", "/" + location + "/Accounts/" + accountId + "/Videos?name=" + name + "&accessToken=" + accessToken + "&%s" % params, body = open('TestAudio1.mp4', 'rb').read(), headers = headers)
response = conn.getresponse()
data = response.read()
print(data)
conn.close()
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
I am getting the following error,
{"ErrorType":"INVALID_INPUT","Message":"Input is invalid. Input must specify either a video url, an asset id or provide a multipart content body."}
How can I fix this issue?

Django DRF Post with files and data works in Postman, not Python. No TemporaryUploadedFile

Running a Django App locally, i can use Postman to upload a zip file along with some dict data. Breaking the application in 'def Post()' i can see that Postman's successful upload:
request.data = <QueryDict: {'request_id': ['44'], 'status': [' Ready For Review'], 'is_analyzed': ['True'], 'project': ['test value'], 'plate': ['Plate_R0'], 'antigen': ['tuna'], 'experiment_type': ['test'], 'raw_file': [<TemporaryUploadedFile: testfile.zip (application/zip)>]}>
Postman offers the following python code to replicate these results in my python script:
import requests
url = "http://127.0.0.1:8000/api/upload/"
payload = {'request_id': '44',
'status': ' Ready For Review',
'is_analyzed': 'True',
'project': 'test value',
'plate': 'Plate_R0',
'antigen': 'tuna',
'experiment_type': 'test'}
files = [
('raw_file', open(r'C:/testfile.zip','rb'))
]
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
response = requests.request("POST", url, headers=headers, data = payload, files = files)
print(response.text.encode('utf8'))
running this code directly and retrieving the request.data (server side) i see the binary representation of the xlsx file is in the object and the payload data is not there (this is the error in the response).
How do i get my python script to produce the same server-side object as postman? Specifically how do i upload my data such that the file is represented as: <TemporaryUploadedFile: testfile.zip (application/zip)>
Thanks.
Turns out, inspection of the object posted by Postman shows that it was using multipart-form upload. Searching around i found this answer to a related question to describe posting as multi-part: https://stackoverflow.com/a/50595768/2917170 .
The working python is as follows:
from requests_toolbelt import MultipartEncoder
url = "http://127.0.0.1:8000/api/upload/"
zip_file = r'C:/testfile.zip'
m = MultipartEncoder([('raw_file', (os.path.basename(zip_file), open(zip_file, 'rb'))),
('request_id', '44'),
('status', 'Ready For Review'),
('is_analyzed', 'True'),
('project', 'test value'),
('plate', 'Plate_R0'),
('antigen', 'tuna'),
('experiment_type', 'test')])
header = {'content-type': m.content_type}
response = requests.post(url, headers=header, data=m, verify=True)

How to send POST request after form submit 302 in Django?

I have an implementation as follows:
There is a payment form wherein user fills all the details.(API1), here I'm getting an error 302:
On submit of that form one of the function in my views is called.
In the backend implementation ie. in views.py, I want to send a POST request to one of the gateways I have integrated.(API2)
But the problem is coming as the request is going as GET and hence it is dropping all the form data I'm sending along with the request.
Following is the code.
views.py -->
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
}
payload = {
'CustomerID': 'abc',
'TxnAmount': '1.00',
'BankID': '1',
'AdditionalInfo1': '999999999',
'AdditionalInfo2': 'test#test.test',
}
payload_encoded = urlencode(payload, quote_via=quote_plus)
response = requests.post('https://www.billdesk.com/pgidsk/PGIMerchantRequestHandler?hidRequestId=****&hidOperation=****', data=payload_encoded, headers=headers)
content = response.url
return_config = {
"type": "content",
"content": redirect(content)
}
return return_config
How do I send the 2nd request(API2) as POST request along with all parameters? What am I doing wrong here?
Thank you for your suggestions.
If the requests returns a 302 status, the new url is available in response.headers['Location']. You can keep following the new url, till you end up with a valid response.
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
}
payload = {
'CustomerID': 'abc',
'TxnAmount': '1.00',
'BankID': '1',
'AdditionalInfo1': '999999999',
'AdditionalInfo2': 'test#test.test',
}
payload_encoded = urlencode(payload, quote_via=quote_plus)
response = requests.post('https://www.billdesk.com/pgidsk/PGIMerchantRequestHandler?hidRequestId=****&hidOperation=****', data=payload_encoded, headers=headers)
while response.status_code == 302:
response = requests.post(response.headers['Location'], data=payload_encoded, headers=headers)
content = response.text
return_config = {
"type": "content",
"content": content
}
return return_config
# here you are assigning the post url to content ie. 'https://www.billdesk.com/pgidsk/PGIMerchantRequestHandler?hidRequestId=****&hidOperation=****'
content = response.url
return_config = {
"type": "content",
"content": redirect(content) # calling redirect with the response.url
}
change to:
# check status code for response
print(response)
content = response.json() # if response is of json in format
content = response.text # if response is of plain text
return_config = {
"type": "content",
"content": content
}
return return_config
request.post() returns requests.Response object. inorder to get the response data you need to access it using .text or .json() depending on the format in which the response is sent.

Problem with headers generation in image upload Python 3

I´m trying to upload an image with Python 3, this is my upload method:
def load():
headers = {'X-API-Key' : adminTokenSession}
image= {'image': open ('C:/Users/Cesar/Desktop/A-FT-DIVT.jpg', 'rb')}
res = requests.post(activityInfoURL, files= image, headers = headers)
print (res.text)
In the server I check if format is jpg or png like this:
if (files.image[0].headers['content-type'] != 'image/jpeg' && files.image[0].headers['content-type'] != 'image/png') {
logger.warn("Trying to upload a different format file")
res.json({ error: "The file must be an image" })
I´m always getting "The file must be an image" error and I think it´s because headers are not created.
Thanks in advance.
You may want to post an image, instead of an open file descriptor:
headers = {'X-API-Key' : adminTokenSession}
# Note here
with open('C:/Users/Cesar/Desktop/A-FT-DIVT.jpg', 'rb') as f:
image = {'image': f.read()}
# Note: ^^^^^^^^
res = requests.post(activityInfoURL, files= image, headers = headers)

Resources