How to pass InMemoryUploadedFile as a file?

User records audio, audio gets saved into audio Blob and sent to backend. I want to get the audio file and send it to openai whisper API.

  files = request.FILES.get('audio')
  audio = whisper.load_audio(files)

Error

I've tried different ways to send the audio file but none of it seemed to work and I don't understand how it should be sent. I would prefer not to save the file. I want user recorded audio sent to whisper API from backend.

load_audio() requires a file on disk, so you'll need to cater to it – but you can use a temporary file that's automagically deleted outside the with block. (On Windows, you may need to use delete=False because of sharing permission reasons.)

import os
import tempfile

file = request.FILES.get('audio')
with tempfile.NamedTemporaryFile(suffix=os.path.splitext(file.name)[1], delete=False) as f:
    for chunk in file.chunks():
        f.write(chunk)
    f.seek(0)

try:
    audio = whisper.load_audio(f.name)
finally:
    os.unlink(f.name)

Back to Top