Files
Athena-Deck/test_voxcpm_worker.py
T
Mikei386 06cacafbad Add native Applio RVC and preserve the custom studio UI
Pin Applio 3.6.5 and verified basis assets, migrate private voice provenance, and coordinate conversion/live/training with Deck GPU leases. Prepare an inactive voice profile and a restricted studio container. Move CUDA and Torch caches out of the small temporary filesystem to prevent OmniVoice reference failures. Package app updates from the explicit allowlist in one Docker layer.
2026-10-05 10:02:07 +02:00

174 lines
12 KiB
Python

import io,tempfile,unittest,wave
from pathlib import Path
from unittest.mock import Mock,patch
from voxcpm_test import VoxCPMTests,validate_reference
class VoiceTests(unittest.TestCase):
def test_omnivoice_reports_full_temp_storage_without_blame_on_reference(self):
from omnivoice_worker import failure
result=failure(FileNotFoundError(2,"No usable temporary directory found"),'Referenzaufbereitung')
self.assertFalse(result['ok']);self.assertIn('Temporärer Speicher',result['error'])
def test_worker_uses_pytorch_seed_with_pinned_voxcpm_api(self):
import sys,json
from types import SimpleNamespace
import voxcpm_worker
torch=Mock();soundfile=Mock()
def generate(*,text,reference_wav_path,cfg_value,inference_timesteps,max_len,normalize,denoise,retry_badcase_max_times):
return [0.] * 24000
model=SimpleNamespace(generate=generate,tts_model=SimpleNamespace(sample_rate=24000))
api=Mock();api.from_pretrained.return_value=model
with tempfile.TemporaryDirectory() as d:
with patch.dict(sys.modules,{'torch':torch,'soundfile':soundfile,'voxcpm':SimpleNamespace(VoxCPM=api)}),patch.object(sys,'argv',['worker',d]),patch.object(sys,'stdin',io.StringIO(json.dumps(dict(text='Test',cfg=2,steps=10,seed=42)))):
self.assertEqual(voxcpm_worker.main(),0)
self.assertTrue(json.loads((Path(d)/'result.json').read_text())['ok'])
torch.manual_seed.assert_called_once_with(42)
soundfile.write.assert_called_once()
def test_omnivoice_staging_preserves_audio_tokenizer_directory(self):
from profiles import omni_recipe
with tempfile.TemporaryDirectory() as d:
root=Path(d);catalog=root/'catalog';catalog.mkdir();work=root/'job';work.mkdir()
model=dict(id='main',kind='voice',repo='k2-fsa/OmniVoice',file='model.safetensors')
entries={role:dict(id=role,file=info['files'][0]) for role,info in omni_recipe(model).items()}
for entry in [model,*entries.values()]:
directory=catalog/entry['id'];directory.mkdir();(directory/('model'+Path(entry['file']).suffix)).write_bytes(b'synthetic')
profiles=Mock();profiles.catalog.root=catalog;profiles._component.side_effect=lambda model,role,ident:entries[role]
t=VoxCPMTests(root,profiles,Mock());t.stage(dict(model=model,components={}),work)
self.assertTrue((work/'model/model.safetensors').is_file());self.assertTrue((work/'model/audio_tokenizer/model.safetensors').is_file())
self.assertNotEqual((work/'model/model.safetensors').resolve(),(work/'model/audio_tokenizer/model.safetensors').resolve())
def test_reference_limits(self):
for data in (b'',b'not audio'):
with self.assertRaises(ValueError):validate_reference(data)
def wav(seconds):
b=io.BytesIO()
with wave.open(b,'wb') as w:w.setnchannels(1);w.setsampwidth(2);w.setframerate(16000);w.writeframes(b'\0\0'*int(seconds*16000))
return b.getvalue()
validate_reference(wav(2))
validate_reference(wav(32))
validate_reference(wav(121))
validate_reference(wav(1200))
def test_not_installed_and_components_reported_separately(self):
profiles=Mock();profiles._component.side_effect=ValueError('missing');runtime=Mock();runtime.status.return_value={'installed':False}
t=VoxCPMTests('/tmp/no-voice',profiles,runtime);p=dict(model=dict(kind='voice',repo='openbmb/VoxCPM2',file='model.safetensors'),components={})
self.assertEqual(len(t.blockers(p)),6)
runtime.status.return_value={'installed':True};self.assertEqual(len(t.blockers(p)),5)
def test_missing_gpu_releases_reservation_and_records_failure(self):
with tempfile.TemporaryDirectory() as d:
p=dict(id='test',model=dict(kind='voice',repo='openbmb/VoxCPM2',file='model.safetensors'),components={})
profiles=Mock();profiles.status.return_value={'profiles':[p]};runtime=Mock();runtime.status.return_value={'installed':True}
runtime.paths.return_value=(Path('/fake-python'),None)
t=VoxCPMTests(d,profiles,runtime);release=Mock();t.acquire=Mock(return_value=release)
with patch('voxcpm_test.probe',return_value=[]):
with self.assertRaisesRegex(ValueError,'VRAM'):t.start('test','synthetic test')
release.assert_called_once();self.assertEqual(t.job['state'],'failed')
self.assertEqual(list(Path(d).iterdir()),[])
def test_invalid_options_rejected_before_gpu_reservation(self):
t=VoxCPMTests('/tmp/no-voice',Mock(),Mock());t.acquire=Mock()
for args in (dict(text=''),dict(text='x',device='cpu'),dict(text='x',steps=0),dict(text='x',seed=-1)):
with self.assertRaises(ValueError):t.start('id',**args)
t.acquire.assert_not_called()
def test_worker_completion_failure_and_cancellation_cleanup(self):
for outcome in ('complete','failed','cancelled'):
with tempfile.TemporaryDirectory() as d:
t=VoxCPMTests(d,Mock(),Mock());ident='a'*32;t.job=dict(id=ident,state='running');t.stage=lambda p,root:(root/'model').mkdir();t.runtime.paths.return_value=(Path('/fake-python'),None)
root=Path(d)/ident;release=Mock()
process=Mock();process.poll.return_value=None
def generate():
(root/'result.json').write_text('{"ok":false,"error":"synthetic OOM"}' if outcome=='failed' else '{"ok":true,"duration":1,"sample_rate":16000}')
if outcome=='complete':
with wave.open(str(root/'result.wav'),'wb') as w:w.setnchannels(1);w.setsampwidth(2);w.setframerate(16000);w.writeframes(b'\0\0'*16000)
process.stdin.flush.side_effect=generate
if outcome=='cancelled':t.cancel.set()
with patch.object(t,'_ensure_voice',return_value=process):
if outcome=='complete':t.process=process
t._run_voice({'model':{'kind':'voice','repo':'openbmb/VoxCPM2','file':'model.safetensors'}},ident,dict(text='synthetic'),b'reference',{'uuid':'test'},release)
self.assertEqual(t.job['state'],outcome);release.assert_called_once()
self.assertFalse((root/'reference.wav').exists());self.assertFalse((root/'model').exists());self.assertEqual(t.status()['loaded'],outcome=='complete')
self.assertEqual((root/'complete').exists(),outcome=='complete')
class ResidencyTests(unittest.TestCase):
def test_two_jobs_reuse_worker_and_stop_releases_weights(self):
import sys,time
with tempfile.TemporaryDirectory() as d:
root=Path(d);script=root/'fake-worker.py'
script.write_text('''import sys,json,wave
from pathlib import Path
root=Path(sys.argv[1]);(root/'ready.json').write_text('{"ok":true}')
for line in sys.stdin:
request=json.loads(line);output=Path(request['output'])
with wave.open(str(output/'result.wav'),'wb') as w:w.setnchannels(1);w.setsampwidth(2);w.setframerate(16000);w.writeframes(b'\\0\\0'*16000)
temp=output/'result.tmp';temp.write_text('{"ok":true,"duration":1,"sample_rate":16000}');temp.replace(output/'result.json')
''')
row=dict(id='vox',revision=1,kind='voice',model=dict(kind='voice',repo='openbmb/VoxCPM2',file='model.safetensors'),components={})
profiles=Mock();profiles.status.return_value={'profiles':[row]};runtime=Mock();runtime.status.return_value={'installed':True};runtime.paths.return_value=(Path(sys.executable),None)
t=VoxCPMTests(root/'jobs',profiles,runtime);t.blockers=lambda p:[];t.stage=lambda p,r:(r/'model').mkdir()
def gpu():return [dict(name='RTX 3060',uuid='test',processes=1 if t.process and t.process.poll() is None else 0,free_mib=10000)]
try:
with patch('voxcpm_test.WORKER',script),patch('voxcpm_test.probe',side_effect=gpu),patch('voxcpm_test.cgroup_headroom',return_value=None):
first_pid=None
for text in ('first','second'):
t.start('vox',text,device='3060')
deadline=time.monotonic()+5
while t.status()['job']['state']=='running' and time.monotonic()<deadline:time.sleep(.02)
self.assertEqual(t.status()['job']['state'],'complete');self.assertTrue(t.status()['loaded'])
if first_pid is None:first_pid=t.process.pid
self.assertEqual(t.process.pid,first_pid)
self.assertFalse((t.root/t.job['id']/'reference.wav').exists())
t.stop();self.assertFalse(t.status()['loaded']);self.assertFalse((t.root/'session').exists())
finally:t.stop()
def test_pcm24_reference_converted_without_trimming(self):
from types import SimpleNamespace
b=io.BytesIO()
with wave.open(b,'wb') as w:w.setnchannels(1);w.setsampwidth(3);w.setframerate(16000);w.writeframes(b'\0\0\0'*16000*32)
with patch('voxcpm_test.subprocess.run',return_value=SimpleNamespace(returncode=0,stdout=b'\0\0'*48000*32)):
normalized=validate_reference(b.getvalue())
with wave.open(io.BytesIO(normalized)) as w:self.assertEqual(w.getsampwidth(),2);self.assertEqual(w.getnframes()/w.getframerate(),32)
class OmniReferenceTests(unittest.TestCase):
def test_automatic_asr_receives_exact_prepared_reference(self):
import json,threading
from types import SimpleNamespace
with tempfile.TemporaryDirectory() as d:
t=VoxCPMTests(d,Mock(),Mock());t.omni_runtime=Mock();t.omni_runtime.paths.return_value=(Path('/python'),None)
t.job=dict(state='running');t.reference_transcriber=Mock(return_value='Matched transcript')
t.profiles._component.return_value=dict(id='preprocessor',file='preprocessor_config.json');t.profiles.catalog.root=Path(d)
root=Path(d)/'job';process=Mock();process.poll.return_value=None
def prepare(*args,**kwargs):
(root/'reference.wav').write_bytes(b'prepared excerpt')
(root/'reference-info.json').write_text(json.dumps(dict(ok=True,original_duration=1200,duration=15)))
return SimpleNamespace(returncode=0)
def finish():
with wave.open(str(root/'result.wav'),'wb') as w:w.setnchannels(1);w.setsampwidth(2);w.setframerate(24000);w.writeframes(b'\0\0'*24000)
(root/'result.json').write_text(json.dumps(dict(ok=True,sample_rate=24000,duration=1)))
process.stdin.flush.side_effect=finish
with patch('voxcpm_test.subprocess.run',side_effect=prepare),patch.object(t,'_ensure_voice',return_value=process):
t._run_voice(dict(model=dict(kind='voice',repo='k2-fsa/OmniVoice',file='model.safetensors')), 'job',dict(text='Test',reference_text='',preprocess_prompt=True),b'full reference',dict(uuid='test'),Mock())
t.reference_transcriber.assert_called_once_with(b'prepared excerpt',t.cancel)
self.assertEqual(t.job['state'],'complete');self.assertEqual(t.job['reference_used_duration'],15)
request=json.loads(process.stdin.write.call_args.args[0]);self.assertEqual(request['reference_text'],'Matched transcript')
self.assertFalse((root/'reference.wav').exists())
def test_manual_transcript_does_not_trim_or_transcribe(self):
import json
with tempfile.TemporaryDirectory() as d:
t=VoxCPMTests(d,Mock(),Mock());t.job=dict(state='running');t.reference_transcriber=Mock()
root=Path(d)/'job';process=Mock();process.poll.return_value=None
def finish():
self.assertEqual((root/'reference.wav').read_bytes(),b'full reference')
with wave.open(str(root/'result.wav'),'wb') as w:w.setnchannels(1);w.setsampwidth(2);w.setframerate(24000);w.writeframes(b'\0\0'*24000)
(root/'result.json').write_text(json.dumps(dict(ok=True,sample_rate=24000,duration=1)))
process.stdin.flush.side_effect=finish
with patch('voxcpm_test.subprocess.run') as prepare,patch.object(t,'_ensure_voice',return_value=process):
t._run_voice(dict(model=dict(kind='voice',repo='k2-fsa/OmniVoice',file='model.safetensors')), 'job',dict(text='Test',reference_text='Full transcript',preprocess_prompt=True),b'full reference',dict(uuid='test'),Mock())
prepare.assert_not_called();t.reference_transcriber.assert_not_called();self.assertEqual(t.job['state'],'complete')
class OmniPreparationCLITests(unittest.TestCase):
def test_preparation_reads_supplied_model_configuration_without_loading_weights(self):
import json,sys,omnivoice_worker
with tempfile.TemporaryDirectory() as d:
root=Path(d);config=root/'config.json';config.write_text(json.dumps(dict(sampling_rate=24000)))
with patch.object(sys,'argv',['worker',d,str(config),'--prepare-reference']),patch.object(omnivoice_worker,'prepare_reference',return_value=dict(ok=True,original_duration=1200,duration=15)) as prepare,patch.object(omnivoice_worker,'load') as load:
self.assertEqual(omnivoice_worker.main(),0)
prepare.assert_called_once_with(root,24000);load.assert_not_called()
self.assertTrue(json.loads((root/'reference-info.json').read_text())['ok'])