Skip to content

Commit 623912f

Browse files
Refactor audio conversion and cleanup in BotService and Transcriber classes
1 parent 920f68f commit 623912f

3 files changed

Lines changed: 8 additions & 12 deletions

File tree

src/audio_converter.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -97,16 +97,15 @@ def convert_to_wav(self, audio_bytes: bytes, mime: str) -> str | None:
9797
Caller must delete the file (e.g. via os.unlink in a finally block).
9898
Blocking — must be called via run_in_executor.
9999
"""
100-
from pydub import AudioSegment # noqa: PLC0415
100+
from pydub import AudioSegment
101101

102102
fmt = _pydub_format(mime)
103103
try:
104104
seg = AudioSegment.from_file(io.BytesIO(audio_bytes), format=fmt)
105105
seg = seg.set_frame_rate(16000).set_channels(1).set_sample_width(2)
106-
tmp = tempfile.NamedTemporaryFile(suffix=".wav", delete=False)
107-
seg.export(tmp.name, format="wav")
108-
tmp.close()
109-
return tmp.name
106+
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp:
107+
seg.export(tmp.name, format="wav")
108+
return tmp.name
110109
except Exception:
111110
logger.exception("Audio conversion failed (mime=%s)", mime)
112111
return None

src/bot_service.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from __future__ import annotations
22

33
import asyncio
4+
import contextlib
45
import logging
56
import os
67
import time
@@ -97,10 +98,8 @@ async def handle_audio_event(
9798
wav_path,
9899
)
99100
finally:
100-
try:
101+
with contextlib.suppress(OSError):
101102
os.unlink(wav_path)
102-
except OSError:
103-
pass
104103

105104
if not transcript or not transcript.strip():
106105
await self._send_plain(room.room_id, self.strings.transcription_failed) # type: ignore[attr-defined]

src/transcriber.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,10 @@ def __init__(self, model: object) -> None:
1717
self._model = model
1818

1919
@classmethod
20-
def load(cls, model_name: str) -> "Transcriber":
20+
def load(cls, model_name: str) -> Transcriber:
21+
import nemo.collections.asr as nemo_asr
2122
import torch
2223

23-
# Local import so this module is importable without nemo installed (e.g. lint CI)
24-
import nemo.collections.asr as nemo_asr # noqa: PLC0415
25-
2624
logger.info("Loading ASR model: %s", model_name)
2725
model = nemo_asr.models.ASRModel.from_pretrained(model_name, map_location="cpu")
2826
model = model.to(torch.device("cpu"))

0 commit comments

Comments
 (0)