Skip to content

Commit

Permalink
Refactor audio file handling and error handling in API
Browse files Browse the repository at this point in the history
  • Loading branch information
Microwave-WYB committed May 21, 2024
1 parent 858cf27 commit 57fbb58
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 9 deletions.
26 changes: 17 additions & 9 deletions phone_sensors/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ def health_check() -> str:
get_db_session()
get_redis_connection()
return "OK"
except Exception as e: # pylint: disable=broad-exception-caught
return f"Error: {e}"
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error: {e}") from e


@app.post("/upload")
Expand Down Expand Up @@ -63,12 +63,20 @@ async def upload(
)
status.add_coordinates()
audio_data = await audio_file.read()
file_name = audio_file.filename or f"{datetime.datetime.now(datetime.UTC).isoformat()}.wav"
if not file_name.endswith(".ogg"):
raise HTTPException(status_code=400, detail="Only .ogg files are supported.")
file_name = audio_file.filename
if file_name is None:
raise HTTPException(
status_code=400, detail="Missing file name, unable to determine file type."
)

file_path = Path(tempfile.gettempdir()) / file_name
with open(file_path, "wb") as file:
file.write(audio_data)
AudioSegment.from_wav(file_path).export(file_path, format="wav")
wav_file_path = file_path.with_suffix(".wav")
file_path.write_bytes(audio_data)
try:
audio: AudioSegment = AudioSegment.from_file(file_path)
audio.export(wav_file_path, format="wav")
except Exception as e:
raise HTTPException(status_code=400, detail=f"Error converting file to wav: {e}") from e

return submit_analyze_audio_job(redis_conn, file_path, status)
file_path.unlink()
return submit_analyze_audio_job(redis_conn, wav_file_path, status)
1 change: 1 addition & 0 deletions phone_sensors/birdnet.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ def analyze_audio(
)
recording.analyze()
detections = [BirdNetDetection.model_validate(d) for d in recording.detections]
file_path.unlink()
return detections, sensor_status


Expand Down

0 comments on commit 57fbb58

Please sign in to comment.