S-Vetrivel commited on
Commit
4b4453a
·
1 Parent(s): b5ac8e5

Fix: Robust Base64 decoding

Browse files
Files changed (1) hide show
  1. app/audio.py +14 -2
app/audio.py CHANGED
@@ -2,6 +2,7 @@ import torch
2
  import numpy as np
3
  import io
4
  import base64
 
5
  from pydub import AudioSegment
6
  import librosa # Keep librosa for easy array handling if needed, or just use pydub + numpy
7
 
@@ -19,10 +20,21 @@ def process_audio(input_data) -> torch.Tensor:
19
  if isinstance(input_data, str):
20
  # Check if it's a file path
21
  try:
22
- audio_segment = AudioSegment.from_file(input_data)
 
 
 
23
  except:
24
  # Assume Base64 string if file load fails
25
- decoded_bytes = base64.b64decode(input_data)
 
 
 
 
 
 
 
 
26
  audio_segment = AudioSegment.from_file(io.BytesIO(decoded_bytes))
27
  elif isinstance(input_data, bytes):
28
  audio_segment = AudioSegment.from_file(io.BytesIO(input_data))
 
2
  import numpy as np
3
  import io
4
  import base64
5
+ import os
6
  from pydub import AudioSegment
7
  import librosa # Keep librosa for easy array handling if needed, or just use pydub + numpy
8
 
 
20
  if isinstance(input_data, str):
21
  # Check if it's a file path
22
  try:
23
+ if os.path.isfile(input_data):
24
+ audio_segment = AudioSegment.from_file(input_data)
25
+ else:
26
+ raise FileNotFoundError
27
  except:
28
  # Assume Base64 string if file load fails
29
+ # 1. Clean up "data:audio/mp3;base64," prefix if present
30
+ clean_b64 = input_data
31
+ if "," in clean_b64:
32
+ clean_b64 = clean_b64.split(",", 1)[1]
33
+
34
+ # 2. Remove whitespace/newlines which break some decoders
35
+ clean_b64 = clean_b64.strip().replace("\n", "").replace(" ", "")
36
+
37
+ decoded_bytes = base64.b64decode(clean_b64)
38
  audio_segment = AudioSegment.from_file(io.BytesIO(decoded_bytes))
39
  elif isinstance(input_data, bytes):
40
  audio_segment = AudioSegment.from_file(io.BytesIO(input_data))