Sathya-UM commited on
Commit
cdaf104
·
verified ·
1 Parent(s): c25f760

fix: decode compressed audio via temp file + ffmpeg

Browse files
Files changed (1) hide show
  1. api.py +12 -2
api.py CHANGED
@@ -21,8 +21,8 @@ runnable anywhere. Requires the numpy<2 inference stack (see requirements-api.tx
21
  """
22
  from __future__ import annotations
23
 
24
- import io
25
  import os
 
26
 
27
  import numpy as np
28
  from fastapi import FastAPI, File, Form, UploadFile
@@ -80,10 +80,20 @@ async def identify(audio: UploadFile = File(...), contribute: str = Form("no")):
80
 
81
  m = model()
82
  raw = await audio.read()
 
 
 
 
83
  try:
84
- y, sr = librosa.load(io.BytesIO(raw), sr=None, mono=True)
 
85
  except Exception as e: # noqa: BLE001
86
  return JSONResponse({"error": "could not decode audio", "detail": str(e)[:200]}, status_code=400)
 
 
 
 
 
87
 
88
  windows, tonic, heard, pcd = pitch_extract.audio_to_features(y, sr)
89
  if not windows:
 
21
  """
22
  from __future__ import annotations
23
 
 
24
  import os
25
+ import tempfile
26
 
27
  import numpy as np
28
  from fastapi import FastAPI, File, Form, UploadFile
 
80
 
81
  m = model()
82
  raw = await audio.read()
83
+ # Write to a temp file so librosa can fall back to ffmpeg (audioread) for compressed formats
84
+ # (webm/opus from the browser, m4a/mp3 from uploads); soundfile-on-BytesIO can't read those.
85
+ suffix = os.path.splitext(audio.filename or "")[1] or ".webm"
86
+ tmp = tempfile.NamedTemporaryFile(suffix=suffix, delete=False)
87
  try:
88
+ tmp.write(raw); tmp.flush(); tmp.close()
89
+ y, sr = librosa.load(tmp.name, sr=None, mono=True)
90
  except Exception as e: # noqa: BLE001
91
  return JSONResponse({"error": "could not decode audio", "detail": str(e)[:200]}, status_code=400)
92
+ finally:
93
+ try:
94
+ os.unlink(tmp.name)
95
+ except OSError:
96
+ pass
97
 
98
  windows, tonic, heard, pcd = pitch_extract.audio_to_features(y, sr)
99
  if not windows: