ongudidan commited on
Commit
12d8590
·
1 Parent(s): 6cd9ca2

feat: add wav_to_mp3 conversion and update return values to provide MP3 output files

Browse files
Files changed (1) hide show
  1. app.py +24 -3
app.py CHANGED
@@ -127,6 +127,23 @@ def ensure_wav(filepath: str) -> str:
127
  return filepath
128
 
129
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
  import torchaudio.functional as F_audio
131
 
132
  def post_process_audio(waveform: Tensor, sr: int) -> Tensor:
@@ -222,19 +239,23 @@ def demo_fn(
222
  enhanced_wav = tempfile.NamedTemporaryFile(suffix="enhanced.wav", delete=False).name
223
  save_audio(enhanced_wav, enhanced, sr)
224
 
225
- logger.info(f"saved audios: {noisy_wav}, {enhanced_wav}")
 
 
 
 
226
 
227
  ax_noisy.clear()
228
  ax_enh.clear()
229
  noisy_im = spec_im(sample, sr=sr, figure=fig_noisy, ax=ax_noisy)
230
  enh_im = spec_im(enhanced, sr=sr, figure=fig_enh, ax=ax_enh)
231
 
232
- filter = [speech_upl, noisy_wav, enhanced_wav]
233
  if mic_input is not None and mic_input != "":
234
  filter.append(mic_input)
235
  cleanup_tmp(filter)
236
 
237
- return noisy_wav, noisy_im, enhanced_wav, enh_im
238
 
239
  def specshow(
240
  spec,
 
127
  return filepath
128
 
129
 
130
+ def wav_to_mp3(wav_path: str) -> str:
131
+ """Convert temporary WAV output to MP3 using ffmpeg for smaller file size."""
132
+ mp3_path = wav_path.rsplit(".", 1)[0] + ".mp3"
133
+ subprocess.run(
134
+ ["ffmpeg", "-y", "-i", wav_path, "-vn", "-ar", "44100", "-ac", "1", "-b:a", "128k", mp3_path],
135
+ check=True,
136
+ stdout=subprocess.DEVNULL,
137
+ stderr=subprocess.DEVNULL
138
+ )
139
+ # Remove the temporary wav file
140
+ try:
141
+ os.remove(wav_path)
142
+ except Exception as e:
143
+ logger.warning(f"Failed to remove temp WAV file {wav_path}: {e}")
144
+ return mp3_path
145
+
146
+
147
  import torchaudio.functional as F_audio
148
 
149
  def post_process_audio(waveform: Tensor, sr: int) -> Tensor:
 
239
  enhanced_wav = tempfile.NamedTemporaryFile(suffix="enhanced.wav", delete=False).name
240
  save_audio(enhanced_wav, enhanced, sr)
241
 
242
+ logger.info("Converting outputs to MP3...")
243
+ noisy_mp3 = wav_to_mp3(noisy_wav)
244
+ enhanced_mp3 = wav_to_mp3(enhanced_wav)
245
+
246
+ logger.info(f"saved audios: {noisy_mp3}, {enhanced_mp3}")
247
 
248
  ax_noisy.clear()
249
  ax_enh.clear()
250
  noisy_im = spec_im(sample, sr=sr, figure=fig_noisy, ax=ax_noisy)
251
  enh_im = spec_im(enhanced, sr=sr, figure=fig_enh, ax=ax_enh)
252
 
253
+ filter = [speech_upl, noisy_mp3, enhanced_mp3]
254
  if mic_input is not None and mic_input != "":
255
  filter.append(mic_input)
256
  cleanup_tmp(filter)
257
 
258
+ return noisy_mp3, noisy_im, enhanced_mp3, enh_im
259
 
260
  def specshow(
261
  spec,