Skip to content

Commit

Permalink
better error message for unsupported audio formats uploaded via url
Browse files Browse the repository at this point in the history
  • Loading branch information
SanderGi committed Oct 23, 2023
1 parent c0111cd commit 2a40f15
Showing 1 changed file with 26 additions and 14 deletions.
40 changes: 26 additions & 14 deletions daras_ai_v2/asr.py
Original file line number Diff line number Diff line change
Expand Up @@ -539,20 +539,32 @@ def audio_url_to_wav(audio_url: str) -> tuple[str, int]:


def audio_bytes_to_wav(audio_bytes: bytes) -> tuple[bytes | None, int]:
with tempfile.NamedTemporaryFile() as infile:
infile.write(audio_bytes)
infile.flush()

if check_wav_audio_format(infile.name):
# already a wav file
return None, os.path.getsize(infile.name)

with tempfile.NamedTemporaryFile(suffix=".wav") as outfile:
# convert audio to single channel wav
args = ["ffmpeg", "-y", "-i", infile.name, *FFMPEG_WAV_ARGS, outfile.name]
print("\t$ " + " ".join(args))
subprocess.check_call(args)
return outfile.read(), os.path.getsize(outfile.name)
try:
with tempfile.NamedTemporaryFile() as infile:
infile.write(audio_bytes)
infile.flush()

if check_wav_audio_format(infile.name):
# already a wav file
return None, os.path.getsize(infile.name)

with tempfile.NamedTemporaryFile(suffix=".wav") as outfile:
# convert audio to single channel wav
args = [
"ffmpeg",
"-y",
"-i",
infile.name,
*FFMPEG_WAV_ARGS,
outfile.name,
]
print("\t$ " + " ".join(args))
subprocess.check_call(args)
return outfile.read(), os.path.getsize(outfile.name)
except subprocess.CalledProcessError:
raise ValueError(
"Invalid audio file. Could not convert audio to wav format. Please confirm the file is not corrupted and has a supported format (google 'ffmpeg supported audio file types')"
)


def check_wav_audio_format(filename: str) -> bool:
Expand Down

0 comments on commit 2a40f15

Please sign in to comment.