Reputation: 43
I'm running a simple Flask backend that will process HTTP requests with audio files and read the data. Eventually I will like to read the data and have an ML model perform an inference with the audio data, but the first step is to simply read the data in the proper encoding format.
My code for the Flask app is below:
@app.route('/api/audio', methods=['GET', 'POST'])
def get_score():
if request.method == 'POST':
length = request.content_length
content_type = request.content_type
data = request.data
return f"""Content Type is {content_type} and data is {data} \n length is {length}"""
elif request.method == 'GET':
return 'get method received'
My test code on the client side generating the POST request is below:
def send_audio():
#print('attempting to send audio')
url = 'http://127.0.0.1:5000/api/audio'
with open('/Users/kaushikandra/laughter-detection/LaughDetection/crowd_laugh_1.wav', 'rb') as file:
data = {'uuid':'-jx-1', 'alarmType':1, 'timeDuration':10}
files = {'messageFile': file}
req = requests.post(url, files=files, json=data)
print(req.status_code)
print(req.text)
I get the following output from the server when I run the client script.
200
Content Type is multipart/form-data; boundary=d95c72e01bdfac029b16da2b8f144cbd and data is b''
length is 129722
I can see from the 200 status code that the flask app is correctly receiving the POST request, but when I try to read the data I get an empty b'' string. What is the proper method to use to decode the audio file? or is the problem with the way I'm sending the POST request in the client script?
I've looked at other questions on StackOverflow and they have mentioned to send the file as a part of the 'files' parameter in the POST request.
Upvotes: 4
Views: 12203
Reputation: 1640
For those, who wants to save and process .wav
or any files, you may use FileStorage.save
.
main.py (Flask)
@app.route('/predict_with_db', methods=['POST'])
def predictWithDb():
if request.method == 'POST':
save_path = os.path.join(dirname, "temp.wav")
request.files['music_file'].save(save_path)
#continue processing...
index.html
<input id="music_file" name="music_file" type="file" accept=".mp3,.wav" class="hidden" />
form.js
var formData = new FormData();
const fp1 = $('#music_file').prop('files')[0];
formData.append('music_file', fp1, fp1.name);
$.ajax({
type: "POST",
url: "/predict",
data: formData,
processData: false,
contentType: false,
success: (result) => {
console.log(result);
},
error: (err) => {
console.log(err);
}
});
Upvotes: 0
Reputation: 15349
Try using request.files
to get your audio file:
@app.route('/api/audio', methods=['GET', 'POST'])
def get_score():
if request.method == 'POST':
request.files['messageFile']
Also request.data is just an empty string if I recall. Use request.json()
or request.get_json(force=True)
.
Upvotes: 6