import io,unittest,wave from types import SimpleNamespace from stt import validate_wav,read_upload,supported,REPO,REVISION,MODEL,STT def audio(): out=io.BytesIO() with wave.open(out,'wb') as w:w.setnchannels(1);w.setsampwidth(2);w.setframerate(16000);w.writeframes(b'\0\0'*1600) return out.getvalue() class STTTests(unittest.TestCase): def test_wav(self): validate_wav(audio()) for b in [b'',b'bad',audio()[:-2]]: with self.assertRaises(ValueError):validate_wav(b) def test_recipe(self): self.assertTrue(supported(dict(repo=REPO,revision=REVISION,file=MODEL))) self.assertFalse(supported(dict(repo=REPO,revision='other',file=MODEL))) def test_multipart(self): body=b'--x\r\nContent-Disposition: form-data; name="file"; filename="audio.wav"\r\n\r\n'+audio()+b'\r\n--x\r\nContent-Disposition: form-data; name="model"\r\n\r\nASR\r\n--x--\r\n' h=SimpleNamespace(headers={'Content-Type':'multipart/form-data; boundary=x','Content-Length':str(len(body))},rfile=io.BytesIO(body),connection=SimpleNamespace(settimeout=lambda n:None)) fields,data=read_upload(h);self.assertEqual(fields['model'],'ASR');validate_wav(data) h.headers['Transfer-Encoding']='chunked' with self.assertRaises(ValueError):read_upload(h) def test_missing_runtime(self): s=STT(None,None,SimpleNamespace(status=lambda:{'active':None})) with self.assertRaises(ValueError):s.build() class BrowserUploadTests(unittest.TestCase): def test_valid_pcm_upload_preserves_audio_from_the_first_frame(self): from stt import normalize_transcription_audio import struct out=io.BytesIO();samples=struct.pack('<1600h',*([9000,-9000]*800)) with wave.open(out,'wb') as w:w.setnchannels(1);w.setsampwidth(2);w.setframerate(16000);w.writeframes(samples) raw=out.getvalue();self.assertEqual(normalize_transcription_audio(raw),raw) def handler(self,body,headers=None): return SimpleNamespace(headers=headers or {'Transfer-Encoding':'chunked'},rfile=io.BytesIO(body)) def test_chunked_upload(self): from stt import read_chunked_upload self.assertEqual(read_chunked_upload(self.handler(b'3\r\nabc\r\n2;ext=yes\r\nde\r\n0\r\n\r\n'),5),b'abcde') def test_invalid_chunked_uploads(self): from stt import read_chunked_upload for body in (b'6\r\nabcdef\r\n0\r\n\r\n',b'zz\r\n',b'3\r\nab',b'0\r\nx: y\r\n\r\n'): with self.assertRaises(ValueError):read_chunked_upload(self.handler(body),5) with self.assertRaises(ValueError):read_chunked_upload(self.handler(b'0\r\n\r\n',{'Transfer-Encoding':'chunked','Content-Length':'0'}),5) def test_normalizes_non_16khz_wav(self): from stt import normalize_transcription_audio out=io.BytesIO() with wave.open(out,'wb') as w:w.setnchannels(2);w.setsampwidth(2);w.setframerate(48000);w.writeframes(bytes(4800*4)) converted=normalize_transcription_audio(out.getvalue());validate_wav(converted) with wave.open(io.BytesIO(converted)) as w:self.assertAlmostEqual(w.getnframes()/w.getframerate(),.1,places=2) def test_rejects_invalid_audio(self): from stt import normalize_transcription_audio with self.assertRaisesRegex(ValueError,'Audioformat'):normalize_transcription_audio(b'not an audio file') class ReferenceTranscriptionTests(unittest.TestCase): def test_reference_normalized_and_transcribed_without_download(self): import threading from types import SimpleNamespace from unittest.mock import Mock,patch from stt import STT,validate_wav stt=STT.__new__(STT);stt.lock=threading.RLock();stt.profiles=Mock() stt.profiles.status.return_value={'profiles':[dict(id='cpu-asr',kind='stt',runnable=True)]} stt.start=Mock(return_value={'id':'ours'});stt.job=dict(id='ours',state='complete',text=' Referenztext ') with patch('stt.subprocess.run',return_value=SimpleNamespace(returncode=0,stdout=b'\0\0'*16000)): self.assertEqual(stt.transcribe_reference(b'reference',threading.Event()),'Referenztext') args=stt.start.call_args.args;self.assertEqual(args[0],'cpu-asr');validate_wav(args[1]);self.assertEqual(args[2],'auto') def test_reference_never_uses_unrelated_stt_result(self): import threading from types import SimpleNamespace from unittest.mock import Mock,patch from stt import STT stt=STT.__new__(STT);stt.lock=threading.RLock();stt.profiles=Mock() stt.profiles.status.return_value={'profiles':[dict(id='cpu-asr',kind='stt',runnable=True)]} stt.start=Mock(return_value={'id':'ours'});stt.job=dict(id='someone-else',state='complete',text='Other audio') with patch('stt.subprocess.run',return_value=SimpleNamespace(returncode=0,stdout=b'\0\0'*16000)): with self.assertRaisesRegex(ValueError,'ersetzt'):stt.transcribe_reference(b'reference',threading.Event()) class LongReferenceTests(unittest.TestCase): def test_long_reference_is_transcribed_in_chunks_without_truncation(self): import threading from types import SimpleNamespace from unittest.mock import Mock,patch from stt import STT,validate_wav stt=STT.__new__(STT);stt.profiles=Mock() stt.profiles.status.return_value={'profiles':[dict(id='cpu-asr',kind='stt',runnable=True)]} stt._transcribe_reference_chunk=Mock(side_effect=['First','Second','Third']) pcm=b'\0\0'*(241*16000) with patch('stt.subprocess.run',return_value=SimpleNamespace(returncode=0,stdout=pcm)): self.assertEqual(stt.transcribe_reference(b'long-reference',threading.Event()),'First Second Third') lengths=[] for call in stt._transcribe_reference_chunk.call_args_list: validate_wav(call.args[1]) with wave.open(io.BytesIO(call.args[1])) as w:lengths.append(w.getnframes()/w.getframerate()) self.assertEqual(lengths,[120,120,1])