98 lines
5.9 KiB
Python
98 lines
5.9 KiB
Python
import hashlib,io,json,tempfile,unittest,wave
|
||
from pathlib import Path
|
||
from types import SimpleNamespace
|
||
from unittest.mock import Mock,patch
|
||
import test_pocket
|
||
from kikiri_runtime import KikiriRuntime,supported,REPO,MODEL_REVISION,MODEL_FILE,MODEL_SHA,verify_assets
|
||
from kikiri import Kikiri
|
||
from kikiri_worker import correct,generate
|
||
from endpoint import APIHandler
|
||
|
||
MODEL=dict(kind='audio',repo=REPO,revision=MODEL_REVISION,file=MODEL_FILE,sha256=MODEL_SHA)
|
||
|
||
class KikiriTests(unittest.TestCase):
|
||
def test_exact_private_voice_not_public_victoria_or_different_weights(self):
|
||
self.assertTrue(supported(MODEL))
|
||
self.assertFalse(supported(dict(MODEL,sha256='0'*64)))
|
||
self.assertFalse(supported(dict(MODEL,repo='kikiri-tts/kikiri-german-victoria')))
|
||
self.assertEqual(MODEL_REVISION,MODEL_SHA)
|
||
def test_ui_identifies_cpu_adapter_and_missing_private_assets(self):
|
||
from execution_setup import assess
|
||
result=assess(MODEL,{'kikiri':True},{'runnable':True,'blockers':[]})
|
||
self.assertEqual(result['state'],'ready');self.assertEqual(result['candidates'][0]['id'],'kikiri')
|
||
with tempfile.TemporaryDirectory() as d:
|
||
self.assertFalse(KikiriRuntime(Path(d)/'runtime').status()['installed'])
|
||
def test_voegel_correction_is_narrow_and_unicode_safe(self):
|
||
for text in ('Vögel','Vögeln','Vögelchen','Vo\u0308gel singen.'):
|
||
phone='vˈøːɡəl'+('n' if text=='Vögeln' else 'çən' if text=='Vögelchen' else '')
|
||
self.assertEqual(correct(text,phone),'f'+phone[1:])
|
||
for text in ('Wögel','Vase','Video','Vulkan','Vogel','vier','Wörter'):
|
||
self.assertEqual(correct(text,'vˈøːɡəl'),'vˈøːɡəl')
|
||
self.assertEqual(correct('Vögel und Vase','vˈøːɡəl vˈaːzə'),'fˈøːɡəl vˈaːzə')
|
||
def test_default_alias_and_formats_use_only_kikiri_cpu(self):
|
||
for model in ('tts','kikiri-anna-cpu'):
|
||
for fmt in ('wav','pcm','mp3'):
|
||
h,ep,pocket,row=test_pocket.SpeechRoutingTests().fixture()
|
||
row.update(model=MODEL,api_id='kikiri-anna-cpu');ep.kikiri=Mock()
|
||
ep.kikiri.start.return_value={'id':'job'}
|
||
ep.kikiri.status.return_value=pocket.status.return_value
|
||
ep.kikiri.job_status.return_value=pocket.job_status.return_value
|
||
ep.kikiri.audio.return_value=b'RIFF-kikiri'
|
||
with patch('endpoint.speech_mp3',return_value=b'MP3'):
|
||
APIHandler.speech(h,ep,dict(model=model,input='Ein synthetischer Satz.',response_format=fmt))
|
||
ep.kikiri.start.assert_called_once();pocket.start.assert_not_called();ep.tts.start.assert_not_called()
|
||
self.assertEqual(ep.kikiri.start.call_args.kwargs['streaming'],fmt=='pcm')
|
||
def test_fixed_voice_cannot_read_arbitrary_reference_and_warm_never_uses_gpu(self):
|
||
with tempfile.TemporaryDirectory() as d:
|
||
root=Path(d);(root/'voice.pt').touch();runtime=Mock();runtime.paths.return_value=(root/'python',root)
|
||
worker=Kikiri(root/'jobs',Mock(),runtime)
|
||
self.assertEqual(worker.voice_path('default'),(root/'voice.pt').resolve())
|
||
for name in ('../Anna','/etc/passwd',{},None):
|
||
with self.assertRaises(ValueError):worker.voice_path(name)
|
||
worker.acquire=Mock(side_effect=AssertionError('GPU touched'));worker._profile=Mock(return_value={'id':'p'});worker._ensure_cpu=Mock()
|
||
self.assertTrue(worker.warm('p'));worker.acquire.assert_not_called()
|
||
def test_pcm_stream_matches_wav_and_cooperative_cancel(self):
|
||
import numpy as np
|
||
class Tensor:
|
||
def __init__(self,x):self.x=np.array(x,dtype=np.float32)
|
||
def detach(self):return self
|
||
def cpu(self):return self
|
||
def numpy(self):return self.x
|
||
for cancel in (False,True):
|
||
with tempfile.TemporaryDirectory() as d:
|
||
root=Path(d);pipeline=Mock(return_value=iter([SimpleNamespace(phonemes='a',audio=Tensor([.1,-.2,0.])),SimpleNamespace(phonemes='a',audio=Tensor([.3,.2]))]))
|
||
if cancel:(root/'cancel').touch()
|
||
result=generate(pipeline,Mock(),dict(output=d,text='Hallo.',streaming=True),{'a'},lambda:None)
|
||
self.assertTrue(result['ok'])
|
||
if cancel:self.assertTrue(result['cancelled']);self.assertFalse(list(root.glob('chunk-*.pcm')))
|
||
else:
|
||
pcm=b''.join(x.read_bytes() for x in sorted(root.glob('chunk-*.pcm')))
|
||
with wave.open(str(root/'result.wav')) as w:
|
||
self.assertEqual(w.getframerate(),24000);self.assertEqual(w.getnchannels(),1);self.assertEqual(w.readframes(w.getnframes()),pcm)
|
||
self.assertEqual(result['duration'],5/24000)
|
||
def test_unknown_phonemes_fail_instead_of_silently_dropping_words(self):
|
||
with tempfile.TemporaryDirectory() as d:
|
||
pipeline=Mock(return_value=iter([SimpleNamespace(phonemes='unsupported',audio=Mock())]))
|
||
with self.assertRaisesRegex(ValueError,'Phoneme'):generate(pipeline,Mock(),dict(output=d,text='Hallo.'),{'a'},lambda:None)
|
||
def test_corrupt_or_symlinked_private_assets_are_rejected(self):
|
||
with tempfile.TemporaryDirectory() as d:
|
||
root=Path(d);(root/'config.json').write_bytes(b'{}')
|
||
assets={'config.json':(2,hashlib.sha256(b'{}').hexdigest())}
|
||
with patch('kikiri_runtime.ASSETS',assets):
|
||
verify_assets(root);(root/'config.json').write_bytes(b'xx')
|
||
with self.assertRaisesRegex(ValueError,'Prüfsumme'):verify_assets(root)
|
||
(root/'config.json').unlink();(root/'config.json').symlink_to('/dev/null')
|
||
with self.assertRaises(ValueError):verify_assets(root)
|
||
def test_sole_published_kikiri_warms_without_touching_gpu_or_saved_preference(self):
|
||
import test_audio_policy as p
|
||
from audio_policy import AudioPolicy
|
||
with tempfile.TemporaryDirectory() as d,patch('audio_policy.threading.Thread.start'):
|
||
path=Path(d)/'policy.json';path.write_text('{"tts":{"mode":"warm","profile_id":"old"}}')
|
||
old=p.Worker();new=p.Worker();ep=p.Endpoint();ep.state='running'
|
||
ep.rows=lambda:[dict(id='old',kind='audio',enabled=False,runnable=True,model={}),dict(id='new',kind='audio',enabled=True,runnable=True,model=MODEL)]
|
||
manager=AudioPolicy(path,p.Profiles(),p.Worker(),p.Worker(),p.Scheduler(),ep,articulino=old,kikiri=new)
|
||
manager.reconcile();self.assertEqual(new.warmed,['new']);self.assertFalse(old.warmed)
|
||
self.assertEqual(manager.settings['tts']['profile_id'],'old')
|
||
|
||
if __name__=='__main__':unittest.main()
|