test_transcriber.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. """Tests for the Whisper segment confidence gate."""
  2. import numpy as np
  3. import pytest
  4. from stt_daemon import pywhispercpp_transcriber as pw_mod
  5. from stt_daemon import transcriber as transcriber_mod
  6. from stt_daemon.config import Config
  7. from stt_daemon.pywhispercpp_transcriber import PyWhisperCppTranscriber
  8. from stt_daemon.transcriber import Transcriber, accept_segment
  9. class _Seg:
  10. def __init__(self, text="hello", no_speech_prob=0.1, avg_logprob=-0.3):
  11. self.text = text
  12. self.no_speech_prob = no_speech_prob
  13. self.avg_logprob = avg_logprob
  14. def test_accepts_confident_speech():
  15. assert accept_segment(_Seg(), 0.6, -1.0)
  16. def test_rejects_high_no_speech_prob():
  17. assert not accept_segment(_Seg(no_speech_prob=0.9), 0.6, -1.0)
  18. def test_rejects_low_avg_logprob():
  19. assert not accept_segment(_Seg(avg_logprob=-1.5), 0.6, -1.0)
  20. def test_threshold_boundary_is_accepted():
  21. assert accept_segment(_Seg(no_speech_prob=0.6, avg_logprob=-1.0), 0.6, -1.0)
  22. def test_missing_attributes_default_to_accept():
  23. class Bare:
  24. text = "x"
  25. assert accept_segment(Bare(), 0.6, -1.0)
  26. class _Info:
  27. def __init__(self, language="en", language_probability=1.0):
  28. self.language = language
  29. self.language_probability = language_probability
  30. class _FakeWhisperModel:
  31. """Records constructor/transcribe kwargs without loading a real model."""
  32. last = None
  33. def __init__(self, model, device, compute_type, cpu_threads=0):
  34. self.init_kwargs = {
  35. "model": model,
  36. "device": device,
  37. "compute_type": compute_type,
  38. "cpu_threads": cpu_threads,
  39. }
  40. self.transcribe_kwargs = None
  41. self.transcribe_calls = []
  42. self.segments_to_return = []
  43. self.detected_language = "en"
  44. self.detected_language_probability = 1.0
  45. _FakeWhisperModel.last = self
  46. def transcribe(self, audio, **kwargs):
  47. self.transcribe_kwargs = kwargs
  48. self.transcribe_calls.append(kwargs)
  49. return self.segments_to_return, _Info(
  50. self.detected_language, self.detected_language_probability
  51. )
  52. @pytest.fixture
  53. def fake_model(monkeypatch):
  54. monkeypatch.setattr(transcriber_mod, "WhisperModel", _FakeWhisperModel)
  55. return _FakeWhisperModel
  56. def _audio():
  57. return np.zeros(16000, dtype=np.float32)
  58. def test_cpu_threads_forwarded_to_model(fake_model):
  59. t = Transcriber(
  60. "small", device="cpu", compute_type="int8", language=None, cpu_threads=16
  61. )
  62. assert t.cpu_threads == 16
  63. assert fake_model.last.init_kwargs["cpu_threads"] == 16
  64. def test_cpu_threads_default_is_auto(fake_model):
  65. Transcriber("small", device="cpu", compute_type="int8", language=None)
  66. assert fake_model.last.init_kwargs["cpu_threads"] == 0
  67. def test_transcribe_disables_timestamps(fake_model):
  68. t = Transcriber("small", device="cpu", compute_type="int8", language=None)
  69. t.transcribe(_audio())
  70. kwargs = fake_model.last.transcribe_kwargs
  71. assert kwargs["without_timestamps"] is True
  72. assert kwargs["condition_on_previous_text"] is False
  73. def test_auto_language_stays_none_for_bilingual(fake_model):
  74. """language=auto must reach the engine as None so es/en both keep working."""
  75. t = Transcriber("small", device="cpu", compute_type="int8", language=None)
  76. t.transcribe(_audio())
  77. assert fake_model.last.transcribe_kwargs["language"] is None
  78. def test_explicit_language_is_preserved(fake_model):
  79. t = Transcriber("small", device="cpu", compute_type="int8", language="es")
  80. t.transcribe(_audio())
  81. assert fake_model.last.transcribe_kwargs["language"] == "es"
  82. def test_sticky_pins_language_after_first_detection(fake_model):
  83. """With sticky strategy, language is detected once and pinned."""
  84. t = Transcriber(
  85. "small",
  86. device="cpu",
  87. compute_type="int8",
  88. language=None,
  89. language_strategy="sticky",
  90. )
  91. fake_model.last.detected_language = "es"
  92. fake_model.last.detected_language_probability = 0.95
  93. # First call: auto-detect (language=None sent)
  94. t.transcribe(_audio())
  95. assert fake_model.last.transcribe_calls[0]["language"] is None
  96. assert t._pinned_language == "es"
  97. assert t._pinned_language_probability == 0.95
  98. # Second call: uses pinned language (language="es" sent)
  99. t.transcribe(_audio())
  100. assert fake_model.last.transcribe_calls[1]["language"] == "es"
  101. def test_sticky_reports_stored_detection_probability_when_pinned(fake_model):
  102. """When pinned, report the stored detection probability, not Whisper's 1.0."""
  103. t = Transcriber(
  104. "small",
  105. device="cpu",
  106. compute_type="int8",
  107. language=None,
  108. language_strategy="sticky",
  109. )
  110. fake_model.last.detected_language = "es"
  111. fake_model.last.detected_language_probability = 0.92
  112. # First call: auto-detect and pin
  113. result1 = t.transcribe(_audio())
  114. assert result1.language_probability == 0.92
  115. # Second call: pinned; Whisper returns 1.0 (explicit language), but we report stored
  116. fake_model.last.detected_language = "es"
  117. fake_model.last.detected_language_probability = 1.0
  118. fake_model.last.segments_to_return = [_Seg()] # Provide a segment so pin isn't cleared
  119. result2 = t.transcribe(_audio())
  120. assert result2.language_probability == 0.92 # Stored, not 1.0
  121. def test_sticky_clears_pin_when_best_logprob_too_low(fake_model):
  122. """Sticky clears the pin when the best segment's avg_logprob is below threshold."""
  123. t = Transcriber(
  124. "small",
  125. device="cpu",
  126. compute_type="int8",
  127. language=None,
  128. language_strategy="sticky",
  129. sticky_redetect_logprob=-0.8,
  130. avg_logprob_min=-1.0,
  131. )
  132. fake_model.last.detected_language = "en"
  133. fake_model.last.detected_language_probability = 0.98
  134. # Pin the language on first call with good segment
  135. fake_model.last.segments_to_return = [_Seg(avg_logprob=-0.5)]
  136. t.transcribe(_audio())
  137. assert t._pinned_language == "en"
  138. # Second call: return a segment with avg_logprob below threshold (-0.85 < -0.8)
  139. # but still accepted (above avg_logprob_min of -1.0)
  140. seg_low = _Seg(avg_logprob=-0.85)
  141. fake_model.last.segments_to_return = [seg_low]
  142. t.transcribe(_audio())
  143. # Pin should be cleared because max logprob is below sticky_redetect_logprob
  144. assert t._pinned_language is None
  145. def test_sticky_clears_pin_when_no_segments_accepted(fake_model):
  146. """Sticky clears the pin when no segments pass the confidence gate."""
  147. t = Transcriber(
  148. "small",
  149. device="cpu",
  150. compute_type="int8",
  151. language=None,
  152. language_strategy="sticky",
  153. )
  154. fake_model.last.detected_language = "en"
  155. fake_model.last.detected_language_probability = 0.99
  156. # Pin the language
  157. t.transcribe(_audio())
  158. assert t._pinned_language == "en"
  159. # Second call: return a segment that fails the gate (high no_speech_prob)
  160. seg_bad = _Seg(no_speech_prob=0.9)
  161. fake_model.last.segments_to_return = [seg_bad]
  162. t.transcribe(_audio())
  163. # Pin should be cleared because no segments were accepted
  164. assert t._pinned_language is None
  165. def test_static_strategy_never_pins(fake_model):
  166. """Static (default) strategy never pins; always sends language=None for auto-detect."""
  167. t = Transcriber(
  168. "small",
  169. device="cpu",
  170. compute_type="int8",
  171. language=None,
  172. language_strategy="static",
  173. )
  174. fake_model.last.detected_language = "es"
  175. # First call
  176. t.transcribe(_audio())
  177. assert fake_model.last.transcribe_calls[0]["language"] is None
  178. assert t._pinned_language is None
  179. # Second call
  180. t.transcribe(_audio())
  181. assert fake_model.last.transcribe_calls[1]["language"] is None
  182. assert t._pinned_language is None
  183. def test_explicit_language_with_sticky_ignores_sticky(fake_model):
  184. """When language is explicit, sticky strategy has no effect; no pinning occurs."""
  185. t = Transcriber(
  186. "small",
  187. device="cpu",
  188. compute_type="int8",
  189. language="es",
  190. language_strategy="sticky",
  191. )
  192. fake_model.last.detected_language = "es"
  193. # First call: sends language="es" (explicit)
  194. t.transcribe(_audio())
  195. assert fake_model.last.transcribe_calls[0]["language"] == "es"
  196. assert t._pinned_language is None # No pinning for explicit language
  197. # Second call: still sends language="es"
  198. t.transcribe(_audio())
  199. assert fake_model.last.transcribe_calls[1]["language"] == "es"
  200. assert t._pinned_language is None
  201. def test_sticky_tolerates_missing_avg_logprob_attribute(fake_model):
  202. """Sticky pin clearing uses getattr(..., 0.0) to tolerate missing avg_logprob."""
  203. t = Transcriber(
  204. "small",
  205. device="cpu",
  206. compute_type="int8",
  207. language=None,
  208. language_strategy="sticky",
  209. sticky_redetect_logprob=-0.8,
  210. )
  211. fake_model.last.detected_language = "en"
  212. fake_model.last.detected_language_probability = 0.99
  213. # Pin the language with a normal segment
  214. fake_model.last.segments_to_return = [_Seg(avg_logprob=-0.5)]
  215. t.transcribe(_audio())
  216. assert t._pinned_language == "en"
  217. # Second call: return a segment with no avg_logprob attribute (only text/no_speech_prob)
  218. class SegNoLogprob:
  219. text = "hello"
  220. no_speech_prob = 0.1
  221. fake_model.last.segments_to_return = [SegNoLogprob()]
  222. # Should not raise; defaulted 0.0 is above threshold -0.8, so pin is RETAINED
  223. t.transcribe(_audio())
  224. assert t._pinned_language == "en" # Pin retained because 0.0 >= -0.8
  225. class _StubPyWhisperCppTranscriber(PyWhisperCppTranscriber):
  226. """Replaces the pywhispercpp backend without touching the real package."""
  227. init_kwargs: dict
  228. def __init__(self, **kwargs):
  229. self.init_kwargs = kwargs
  230. def test_build_transcriber_faster_whisper_backend(fake_model):
  231. cfg = Config().whisper
  232. cfg.backend = "faster-whisper"
  233. t = transcriber_mod.build_transcriber(cfg)
  234. assert isinstance(t, Transcriber)
  235. assert fake_model.last.init_kwargs["model"] == cfg.model
  236. assert fake_model.last.init_kwargs["device"] == cfg.device
  237. assert fake_model.last.init_kwargs["compute_type"] == cfg.compute_type
  238. def test_build_transcriber_pywhispercpp_backend(monkeypatch):
  239. monkeypatch.setattr(pw_mod, "PyWhisperCppTranscriber", _StubPyWhisperCppTranscriber)
  240. cfg = Config().whisper
  241. cfg.backend = "pywhispercpp"
  242. t = transcriber_mod.build_transcriber(cfg)
  243. assert isinstance(t, PyWhisperCppTranscriber)
  244. assert t.init_kwargs["model"] == cfg.model
  245. assert t.init_kwargs["language"] == cfg.language
  246. assert t.init_kwargs["beam_size"] == cfg.beam_size
  247. assert t.init_kwargs["cpu_threads"] == cfg.cpu_threads
  248. assert t.init_kwargs["no_speech_prob_max"] == cfg.no_speech_prob_max
  249. assert t.init_kwargs["avg_logprob_min"] == cfg.avg_logprob_min
  250. assert t.init_kwargs["language_strategy"] == cfg.language_strategy
  251. assert t.init_kwargs["sticky_redetect_logprob"] == cfg.sticky_redetect_logprob
  252. assert t.init_kwargs["vad_filter"] == cfg.vad_filter