Integrate trained Kikiri Anna CPU TTS with stable endpoint and restore recipe

This commit is contained in:
Mikei386 committed 2026-10-28 13:32:48 +01:00
1 parent 7e2cd643d6
commit 2ef16dc1ee
25 files changed
+872 -21

No files matched your search

+6 -3
View File
@@ -7,11 +7,12 @@ from pathlib import Path
MODES=('auto','warm','per_request') MODES=('auto','warm','per_request')
class AudioPolicy: class AudioPolicy:
def __init__(self,path,profiles,tts,stt,scheduler,endpoint,pocket=None,qwen_native=None,articulino=None): def __init__(self,path,profiles,tts,stt,scheduler,endpoint,pocket=None,qwen_native=None,articulino=None,kikiri=None):
self.kikiri=kikiri
self.articulino=articulino self.articulino=articulino
self.pocket=pocket self.pocket=pocket
self.qwen_native=qwen_native self.qwen_native=qwen_native
self.cpu_workers=[w for w in (pocket,qwen_native,articulino) if w is not None] self.cpu_workers=[w for w in (pocket,qwen_native,articulino,kikiri) if w is not None]
self.path=Path(path);self.profiles=profiles;self.tts=tts;self.stt=stt;self.scheduler=scheduler;self.endpoint=endpoint self.path=Path(path);self.profiles=profiles;self.tts=tts;self.stt=stt;self.scheduler=scheduler;self.endpoint=endpoint
self.lock=threading.RLock();self.settings={kind:{'mode':'auto','profile_id':None} for kind in ('tts','stt')};self.errors={};self.retry_after={} self.lock=threading.RLock();self.settings={kind:{'mode':'auto','profile_id':None} for kind in ('tts','stt')};self.errors={};self.retry_after={}
if self.path.exists(): if self.path.exists():
@@ -61,6 +62,7 @@ class AudioPolicy:
if not automatic and item['mode']!='warm':continue if not automatic and item['mode']!='warm':continue
if kind=='tts' and self.cpu_workers: if kind=='tts' and self.cpu_workers:
from pocket_runtime import supported from pocket_runtime import supported
from kikiri_runtime import supported as kikiri_supported
from articulino_runtime import supported as articulino_supported from articulino_runtime import supported as articulino_supported
# A warm profile disabled by the user must not override a sole newly # A warm profile disabled by the user must not override a sole newly
# published CPU TTS profile. Persisted preference remains unchanged. # published CPU TTS profile. Persisted preference remains unchanged.
@@ -70,7 +72,8 @@ class AudioPolicy:
from qwen_native_runtime import supported as native_supported from qwen_native_runtime import supported as native_supported
rows=[p for p in self.endpoint.rows() if p['kind']=='audio' and (p['enabled'] if automatic else p['id']==ident)] rows=[p for p in self.endpoint.rows() if p['kind']=='audio' and (p['enabled'] if automatic else p['id']==ident)]
if len(rows)==1: if len(rows)==1:
if self.articulino and articulino_supported(rows[0].get('model')):worker=self.articulino if self.kikiri and kikiri_supported(rows[0].get('model')):worker=self.kikiri
elif self.articulino and articulino_supported(rows[0].get('model')):worker=self.articulino
elif self.pocket and supported(rows[0].get('model')):worker=self.pocket elif self.pocket and supported(rows[0].get('model')):worker=self.pocket
elif self.qwen_native and native_supported(rows[0].get('model')):worker=self.qwen_native elif self.qwen_native and native_supported(rows[0].get('model')):worker=self.qwen_native
for other in [self.tts,*self.cpu_workers]: for other in [self.tts,*self.cpu_workers]:
+12 -4
View File
@@ -124,7 +124,7 @@ def validate(doc):
validate_profiles(settings['separator-profiles.json']) validate_profiles(settings['separator-profiles.json'])
validate_record(doc.get('credentials')) validate_record(doc.get('credentials'))
runtimes=doc.get('runtimes') runtimes=doc.get('runtimes')
if not isinstance(runtimes,dict) or set(runtimes)-{'llama','llama_builds','image','tts','enhancers','swarm_nodes','ltx_original','audio_cpp','separator','voxcpm','omnivoice','acestep','applio','xvc','seed_vc','soulx_singer','music_remix','strata','pocket','articulino'} or not {'llama','llama_builds','image','tts','enhancers','swarm_nodes'}<=set(runtimes):raise ValueError('Ungültiges Laufzeitrezept.') if not isinstance(runtimes,dict) or set(runtimes)-{'llama','llama_builds','image','tts','enhancers','swarm_nodes','ltx_original','audio_cpp','separator','voxcpm','omnivoice','acestep','applio','xvc','seed_vc','soulx_singer','music_remix','strata','pocket','articulino','kikiri'} or not {'llama','llama_builds','image','tts','enhancers','swarm_nodes'}<=set(runtimes):raise ValueError('Ungültiges Laufzeitrezept.')
if any(qwen_voice_alias(m) for m in models) and runtimes.get('tts') is not True:raise ValueError('Qwen-Stimmklon benötigt das vollständige TTS-Laufzeitrezept.') if any(qwen_voice_alias(m) for m in models) and runtimes.get('tts') is not True:raise ValueError('Qwen-Stimmklon benötigt das vollständige TTS-Laufzeitrezept.')
if 'separator' in runtimes: if 'separator' in runtimes:
from separator_runtime import MODELS from separator_runtime import MODELS
@@ -133,6 +133,7 @@ def validate(doc):
if 'sources' in value: if 'sources' in value:
from separator_runtime import SOURCES from separator_runtime import SOURCES
if value['sources']!={name:SOURCES[name] for name in value['models']}:raise ValueError('Audio-Separator-Quellen stimmen nicht mit dem geprüften Rezept überein.') if value['sources']!={name:SOURCES[name] for name in value['models']}:raise ValueError('Audio-Separator-Quellen stimmen nicht mit dem geprüften Rezept überein.')
if 'kikiri' in runtimes and type(runtimes['kikiri']) is not bool:raise ValueError('Ungültige Kikiri-Laufzeit.')
if 'articulino' in runtimes and type(runtimes['articulino']) is not bool:raise ValueError('Ungültige Articulino-Laufzeit.') if 'articulino' in runtimes and type(runtimes['articulino']) is not bool:raise ValueError('Ungültige Articulino-Laufzeit.')
if 'pocket' in runtimes and type(runtimes['pocket']) is not bool:raise ValueError('Ungültige Pocket-Laufzeit.') if 'pocket' in runtimes and type(runtimes['pocket']) is not bool:raise ValueError('Ungültige Pocket-Laufzeit.')
if 'strata' in runtimes and type(runtimes['strata']) is not bool:raise ValueError('Ungültige Strata-Laufzeit.') if 'strata' in runtimes and type(runtimes['strata']) is not bool:raise ValueError('Ungültige Strata-Laufzeit.')
@@ -214,6 +215,8 @@ class Backup:
network=s.network.call('backup-export') network=s.network.call('backup-export')
else:warnings.append('Deck-Netzwerkmodul deaktiviert; fremder WireGuard-Gateway wird nicht gesichert.') else:warnings.append('Deck-Netzwerkmodul deaktiviert; fremder WireGuard-Gateway wird nicht gesichert.')
document=dict(format='athena-deck',version=VERSION,created_at=time.time(),settings=settings,models=models,credentials=s.credentials.read(),theme=theme,network=network,services=services,runtime_versions=dict(image=dict(comfy=s.image_runtime.status()['comfy_revision'],gguf=s.image_runtime.status()['gguf_revision']),tts=s.tts_runtime.status()['revision']),runtimes=dict(audio_cpp=bool(getattr(s,'audio_cpp_runtime',None) and s.audio_cpp_runtime.status()['installed']),ltx_original=bool(getattr(s,'ltx_original_runtime',None) and s.ltx_original_runtime.status()['installed']),llama=llama,llama_builds=[dict(commit=b['commit'],backend=b['backend']) for b in state['builds']],image=s.image_runtime.status()['installed'],tts=s.tts_runtime.status()['installed'],enhancers={task:data['revision'] for task in ('t2i','i2i') if (data:=s.prompt_enhancer.installed(task))},swarm_nodes=(self.root/'video/swarm-comfy-nodes').is_dir()),warnings=warnings) document=dict(format='athena-deck',version=VERSION,created_at=time.time(),settings=settings,models=models,credentials=s.credentials.read(),theme=theme,network=network,services=services,runtime_versions=dict(image=dict(comfy=s.image_runtime.status()['comfy_revision'],gguf=s.image_runtime.status()['gguf_revision']),tts=s.tts_runtime.status()['revision']),runtimes=dict(audio_cpp=bool(getattr(s,'audio_cpp_runtime',None) and s.audio_cpp_runtime.status()['installed']),ltx_original=bool(getattr(s,'ltx_original_runtime',None) and s.ltx_original_runtime.status()['installed']),llama=llama,llama_builds=[dict(commit=b['commit'],backend=b['backend']) for b in state['builds']],image=s.image_runtime.status()['installed'],tts=s.tts_runtime.status()['installed'],enhancers={task:data['revision'] for task in ('t2i','i2i') if (data:=s.prompt_enhancer.installed(task))},swarm_nodes=(self.root/'video/swarm-comfy-nodes').is_dir()),warnings=warnings)
if getattr(s,'kikiri_runtime',None):
document['runtimes']['kikiri']=s.kikiri_runtime.status()['installed'];document['runtime_versions']['kikiri']=s.kikiri_runtime.status()['revision']
if getattr(s,'articulino_runtime',None): if getattr(s,'articulino_runtime',None):
document['runtimes']['articulino']=s.articulino_runtime.status()['installed'];document['runtime_versions']['articulino']=s.articulino_runtime.status()['revision'] document['runtimes']['articulino']=s.articulino_runtime.status()['installed'];document['runtime_versions']['articulino']=s.articulino_runtime.status()['revision']
if getattr(s,'pocket_runtime',None): if getattr(s,'pocket_runtime',None):
@@ -276,6 +279,9 @@ class Backup:
elif s.network.status().get('enabled') or s.network.status().get('mode')!='lan':blockers.append('Deck-Tunnel vor Netzwerk-Restore im bestätigten LAN-Modus deaktivieren.') elif s.network.status().get('enabled') or s.network.status().get('mode')!='lan':blockers.append('Deck-Tunnel vor Netzwerk-Restore im bestätigten LAN-Modus deaktivieren.')
if doc['network']['mode']!='lan':warnings.append('Tunnelzugang wird mit Rückfallzeit aktiviert und muss über den Tunnel bestätigt werden.') if doc['network']['mode']!='lan':warnings.append('Tunnelzugang wird mit Rückfallzeit aktiviert und muss über den Tunnel bestätigt werden.')
versions=doc.get('runtime_versions',{}) versions=doc.get('runtime_versions',{})
if versions.get('kikiri'):
from kikiri_runtime import REVISION as KIKIRI_REVISION
if versions['kikiri']!=KIKIRI_REVISION:blockers.append('Backup verlangt eine andere Kikiri-Version. Passende Deck-Version verwenden.')
if versions.get('articulino'): if versions.get('articulino'):
from articulino_runtime import REVISION as ARTICULINO_REVISION from articulino_runtime import REVISION as ARTICULINO_REVISION
if versions['articulino']!=ARTICULINO_REVISION:blockers.append('Backup verlangt eine andere Articulino-Version. Passende Deck-Version verwenden.') if versions['articulino']!=ARTICULINO_REVISION:blockers.append('Backup verlangt eine andere Articulino-Version. Passende Deck-Version verwenden.')
@@ -317,7 +323,7 @@ class Backup:
if versions.get('applio'): if versions.get('applio'):
from applio_runtime import REVISION as APPLIO_REVISION from applio_runtime import REVISION as APPLIO_REVISION
if versions['applio']!=APPLIO_REVISION:blockers.append('Backup verlangt eine andere Applio-Version.') if versions['applio']!=APPLIO_REVISION:blockers.append('Backup verlangt eine andere Applio-Version.')
if versions and {k:v for k,v in versions.items() if k not in ('ltx_original','audio_cpp','separator','voxcpm','omnivoice','acestep','applio','xvc','seed_vc','soulx_singer','music_remix','strata','pocket','articulino')}!=dict(image=dict(comfy=s.image_runtime.status()['comfy_revision'],gguf=s.image_runtime.status()['gguf_revision']),tts=s.tts_runtime.status()['revision']):blockers.append('Backup verlangt andere Bild-/TTS-Laufzeitversionen. Passende Deck-Version oder geprüftes Runtime-Upgrade verwenden.') if versions and {k:v for k,v in versions.items() if k not in ('ltx_original','audio_cpp','separator','voxcpm','omnivoice','acestep','applio','xvc','seed_vc','soulx_singer','music_remix','strata','pocket','articulino','kikiri')}!=dict(image=dict(comfy=s.image_runtime.status()['comfy_revision'],gguf=s.image_runtime.status()['gguf_revision']),tts=s.tts_runtime.status()['revision']):blockers.append('Backup verlangt andere Bild-/TTS-Laufzeitversionen. Passende Deck-Version oder geprüftes Runtime-Upgrade verwenden.')
for c in doc['services']: for c in doc['services']:
if not c.get('registry') and not c.get('build_recipe'):warnings.append(c['name']+': Image nur lokal vorhanden; Registry-/Buildquelle fehlt.') if not c.get('registry') and not c.get('build_recipe'):warnings.append(c['name']+': Image nur lokal vorhanden; Registry-/Buildquelle fehlt.')
ports=s.endpoint.allowed_ports ports=s.endpoint.allowed_ports
@@ -346,7 +352,7 @@ class Backup:
if getattr(getattr(s,'xvc',None),'active',False):raise ValueError('X-VC-Auftrag zuerst abschließen.') if getattr(getattr(s,'xvc',None),'active',False):raise ValueError('X-VC-Auftrag zuerst abschließen.')
if getattr(getattr(s,'soulx_singer',None),'active',False):raise ValueError('SoulX-Singer-Auftrag zuerst abschließen.') if getattr(getattr(s,'soulx_singer',None),'active',False):raise ValueError('SoulX-Singer-Auftrag zuerst abschließen.')
if getattr(getattr(s,'applio',None),'active',False):raise ValueError('Applio-Auftrag zuerst abschließen.') if getattr(getattr(s,'applio',None),'active',False):raise ValueError('Applio-Auftrag zuerst abschließen.')
if s.catalog.pending or s.catalog.job and s.catalog.job['state']=='downloading' or s.runtime.busy or any((getattr(o,'job',None) or {}).get('state')=='running' for o in (getattr(s,'articulino_runtime',None),getattr(s,'articulino',None),s.image_runtime,s.tts_runtime,s.ltx_original_runtime,getattr(s,'strata_runtime',None),getattr(s,'audio_cpp_runtime',None),getattr(s,'acestep_runtime',None),getattr(s,'applio_runtime',None),getattr(s,'xvc_runtime',None),getattr(s,'soulx_singer_runtime',None),getattr(s,'music',None),getattr(s,'remix_runtime',None),getattr(s,'remix',None),getattr(s,'separator_runtime',None),getattr(s,'separator_tests',None),s.prompt_enhancer,s.auto_tests,s.chat_tests,s.image_tests,s.tts_tests,s.stt)):raise ValueError('Zuerst laufende Downloads, Builds und Tests abschließen oder abbrechen.') if s.catalog.pending or s.catalog.job and s.catalog.job['state']=='downloading' or s.runtime.busy or any((getattr(o,'job',None) or {}).get('state')=='running' for o in (getattr(s,'kikiri_runtime',None),getattr(s,'kikiri',None),getattr(s,'articulino_runtime',None),getattr(s,'articulino',None),s.image_runtime,s.tts_runtime,s.ltx_original_runtime,getattr(s,'strata_runtime',None),getattr(s,'audio_cpp_runtime',None),getattr(s,'acestep_runtime',None),getattr(s,'applio_runtime',None),getattr(s,'xvc_runtime',None),getattr(s,'soulx_singer_runtime',None),getattr(s,'music',None),getattr(s,'remix_runtime',None),getattr(s,'remix',None),getattr(s,'separator_runtime',None),getattr(s,'separator_tests',None),s.prompt_enhancer,s.auto_tests,s.chat_tests,s.image_tests,s.tts_tests,s.stt)):raise ValueError('Zuerst laufende Downloads, Builds und Tests abschließen oder abbrechen.')
self.cancel.clear();self.job=dict(id=secrets.token_hex(16),state='running',phase='Wiederherstellung vorbereiten',completed=0,total=len(doc['models'])+len(data['services'])+5,items=[],started_at=time.time(),theme=doc.get('theme','deck')) self.cancel.clear();self.job=dict(id=secrets.token_hex(16),state='running',phase='Wiederherstellung vorbereiten',completed=0,total=len(doc['models'])+len(data['services'])+5,items=[],started_at=time.time(),theme=doc.get('theme','deck'))
self._save();threading.Thread(target=self._restore,args=(copy.deepcopy(doc),data['services'],data['restore_credentials']),daemon=True).start();self.plan=None self._save();threading.Thread(target=self._restore,args=(copy.deepcopy(doc),data['services'],data['restore_credentials']),daemon=True).start();self.plan=None
return self.status() return self.status()
@@ -368,6 +374,8 @@ class Backup:
return value return value
def _runtimes(self,doc): def _runtimes(self,doc):
s=self.server;r=doc['runtimes'] s=self.server;r=doc['runtimes']
if r.get('kikiri') and not s.kikiri_runtime.status()['installed']:
self._phase('Kikiri-CPU-Laufzeit installieren · privaten Anna-Stand vorher wiederherstellen');s.kikiri_runtime.start();self._wait(s.kikiri_runtime.status)
if r.get('articulino') and not s.articulino_runtime.status()['installed']: if r.get('articulino') and not s.articulino_runtime.status()['installed']:
self._phase('Articulino-CPU-Laufzeit und gepinnte ONNX-Dateien installieren');s.articulino_runtime.start();self._wait(s.articulino_runtime.status) self._phase('Articulino-CPU-Laufzeit und gepinnte ONNX-Dateien installieren');s.articulino_runtime.start();self._wait(s.articulino_runtime.status)
if r.get('pocket') and not s.pocket_runtime.status()['installed']: if r.get('pocket') and not s.pocket_runtime.status()['installed']:
@@ -560,7 +568,7 @@ class Backup:
with self.lock: with self.lock:
self.cancel.set() self.cancel.set()
if self.busy(): if self.busy():
self.server.articulino.stop();self.server.articulino_runtime.stop();self.server.catalog.stop();self.server.runtime.stop();self.server.image_runtime.stop();self.server.tts_runtime.stop();self.server.ltx_original_runtime.stop(); self.server.kikiri.stop();self.server.kikiri_runtime.stop();self.server.articulino.stop();self.server.articulino_runtime.stop();self.server.catalog.stop();self.server.runtime.stop();self.server.image_runtime.stop();self.server.tts_runtime.stop();self.server.ltx_original_runtime.stop();
if getattr(self.server,'separator_runtime',None):self.server.separator_runtime.stop() if getattr(self.server,'separator_runtime',None):self.server.separator_runtime.stop()
if getattr(self.server,'separator_tests',None):self.server.separator_tests.stop() if getattr(self.server,'separator_tests',None):self.server.separator_tests.stop()
if getattr(self.server,'music',None):self.server.music.stop() if getattr(self.server,'music',None):self.server.music.stop()
+3
View File
@@ -48,3 +48,6 @@ COPY deploy/import_pocket.py /app/deploy/import_pocket.py
COPY deploy/pocket-requirements.lock /app/deploy/pocket-requirements.lock COPY deploy/pocket-requirements.lock /app/deploy/pocket-requirements.lock
COPY seedvc.py seedvc_runtime.py seedvc_worker.py /app/ COPY seedvc.py seedvc_runtime.py seedvc_worker.py /app/
COPY kikiri.py kikiri_runtime.py kikiri_worker.py /app/
COPY deploy/kikiri /app/deploy/kikiri
+2 -2
View File
@@ -15,7 +15,7 @@ import urllib.request
ROOT = Path(__file__).resolve().parent.parent ROOT = Path(__file__).resolve().parent.parent
LABEL = 'de.casaderoll.athena-deck.standalone' LABEL = 'de.casaderoll.athena-deck.standalone'
FILES = ['deploy/articulino/register_profile.py','deploy/scheduled_backup.py','deploy/articulino/bootstrap.py','articulino.py','articulino_runtime.py','articulino_worker.py','deploy/articulino/assets.json','deploy/articulino/requirements.lock','deploy/articulino/download.py','deploy/seedvc/bootstrap.py','deploy/seedvc/download.py','deploy/seedvc/requirements.lock','deploy/seedvc/assets.json','deploy/seedvc/versions.json','deploy/seedvc/README.md','seedvc.py','seedvc_runtime.py','seedvc_worker.py','humaneness_pitch.py','humaneness.py','humaneness_runtime.py','deploy/humaneness/bootstrap.py','deploy/humaneness/assets.json','deploy/humaneness/upstream-requirements.txt','deploy/humaneness/requirements.lock','deploy/humaneness/component-assets.json','deploy/humaneness/README.md','stimmatelier_proxy.py','qwen_native.py','qwen_native_worker.py','qwen_native_runtime.py','deploy/qwen-native-requirements.lock','deploy/import_qwen_native.py','deploy/install_strata_vision.py','assets/tts-presets/bundle.safetensors','assets/tts-presets/bundle.json','deploy/applio-requirements.lock','deploy/activate_applio.py','deploy/import_applio.py','deploy/backup_applio_data.py','applio.py','applio_runtime.py','applio_worker.py','applio-ui.js','deploy/activate_acestep.py','acestep_models.py','deploy/import_acestep.py','deploy/acestep-web/Dockerfile','deploy/acestep-web/app.py','deploy/acestep-web/index.html','acestep.py','acestep_worker.py','acestep_runtime.py','acestep-ui.js','deploy/acestep-requirements.lock','deploy/omnivoice-requirements.lock','omnivoice_runtime.py','omnivoice_worker.py','deploy/voice-web/Dockerfile','deploy/voice-web/base.Dockerfile','deploy/voice-web/bridge.py','deploy/patch_yue2_residency.py','embeddings.py','voxcpm_test.py','voxcpm_worker.py','qwen_clone_worker.py','voice-ui.js','voxcpm_runtime.py','voxcpm-ui.js','deploy/voxcpm-requirements.lock','network/native.py','deploy/setup_network_helper.py','separator_sources.json','deploy/separator-web/Dockerfile','deploy/separator-web/app.py','deploy/separator-web/index.html','separator.py','separator_runtime.py','separator_worker.py','separator-ui.js','deploy/ladypoly/Dockerfile','deploy/ladypoly/bridge.py','music.py','music-ui.js','audio_cpp_runtime.py','audio-cpp-ui.js','ltx_original_runtime.py','ltx_original_entry.py','video_original.py','ltx-original-ui.js','deploy/ltx-original-requirements.lock','backup.py','backup_codec.py','backup-ui.js','deploy/docker_backup.py','deploy/swarm-ui/Dockerfile','deploy/swarm-ui/patch-source.py','deploy/swarm-ui/proxy.py','deploy/swarm-ui/entrypoint.py','deploy/Dockerfile.app-update','video_comfy.py','video_comfy_node.py','video_comfy_proxy.py','prompt_enhancer.py','prompt_enhancer_worker.py','image_upload.py','audio_policy.py','deploy/tts-requirements.lock','stt.py','parakeet_runtime.py','stt-ui.js','api_compat.py','responses_compat.py','execution_setup.py','pocket.py','pocket_worker.py','pocket_runtime.py','deploy/pocket-requirements.lock','deploy/import_pocket.py','tts_runtime.py','tts_test.py','tts_worker.py','tts-ui.js','auto_test.py','auto-test-ui.js','chat_test.py','chat-test-ui.js','endpoint.py','inference.py','endpoint-ui.js','docker_support.py','docker-ui.js','deploy/docker_helper.py','deploy/setup_docker_helper.py','image_encoder_node.py','image_runtime.py','image_test.py','image-test-ui.js','profiles.py','profiles-ui.js','capacity.py','runtime.py','runtime-ui.js','video.py','video_proxy.py','video-ui.js','catalog.py','hub_auth.py','catalog-ui.js','server.py','auth.py','collect_hardware.py','dashboard_data.py','dashboard_history.py','dashboard-ui.js','dashboard.css','themes.css','deploy/import_dashboard_history.py','index.html','app.js','studio.js','style.css','login.html','login.js','access-ui.js','network-ui.js','network/__init__.py','network/client.py','network/config.py','network/hosts.py','network/policy.py','network/rpc.py','deploy/Dockerfile','deploy/image-requirements.lock'] FILES = ['kikiri.py','kikiri_runtime.py','kikiri_worker.py','deploy/kikiri/install.py','deploy/kikiri/bootstrap.py','deploy/kikiri/import_voice.py','deploy/kikiri/requirements.lock','deploy/kikiri/README.md','deploy/articulino/register_profile.py','deploy/scheduled_backup.py','deploy/articulino/bootstrap.py','articulino.py','articulino_runtime.py','articulino_worker.py','deploy/articulino/assets.json','deploy/articulino/requirements.lock','deploy/articulino/download.py','deploy/seedvc/bootstrap.py','deploy/seedvc/download.py','deploy/seedvc/requirements.lock','deploy/seedvc/assets.json','deploy/seedvc/versions.json','deploy/seedvc/README.md','seedvc.py','seedvc_runtime.py','seedvc_worker.py','humaneness_pitch.py','humaneness.py','humaneness_runtime.py','deploy/humaneness/bootstrap.py','deploy/humaneness/assets.json','deploy/humaneness/upstream-requirements.txt','deploy/humaneness/requirements.lock','deploy/humaneness/component-assets.json','deploy/humaneness/README.md','stimmatelier_proxy.py','qwen_native.py','qwen_native_worker.py','qwen_native_runtime.py','deploy/qwen-native-requirements.lock','deploy/import_qwen_native.py','deploy/install_strata_vision.py','assets/tts-presets/bundle.safetensors','assets/tts-presets/bundle.json','deploy/applio-requirements.lock','deploy/activate_applio.py','deploy/import_applio.py','deploy/backup_applio_data.py','applio.py','applio_runtime.py','applio_worker.py','applio-ui.js','deploy/activate_acestep.py','acestep_models.py','deploy/import_acestep.py','deploy/acestep-web/Dockerfile','deploy/acestep-web/app.py','deploy/acestep-web/index.html','acestep.py','acestep_worker.py','acestep_runtime.py','acestep-ui.js','deploy/acestep-requirements.lock','deploy/omnivoice-requirements.lock','omnivoice_runtime.py','omnivoice_worker.py','deploy/voice-web/Dockerfile','deploy/voice-web/base.Dockerfile','deploy/voice-web/bridge.py','deploy/patch_yue2_residency.py','embeddings.py','voxcpm_test.py','voxcpm_worker.py','qwen_clone_worker.py','voice-ui.js','voxcpm_runtime.py','voxcpm-ui.js','deploy/voxcpm-requirements.lock','network/native.py','deploy/setup_network_helper.py','separator_sources.json','deploy/separator-web/Dockerfile','deploy/separator-web/app.py','deploy/separator-web/index.html','separator.py','separator_runtime.py','separator_worker.py','separator-ui.js','deploy/ladypoly/Dockerfile','deploy/ladypoly/bridge.py','music.py','music-ui.js','audio_cpp_runtime.py','audio-cpp-ui.js','ltx_original_runtime.py','ltx_original_entry.py','video_original.py','ltx-original-ui.js','deploy/ltx-original-requirements.lock','backup.py','backup_codec.py','backup-ui.js','deploy/docker_backup.py','deploy/swarm-ui/Dockerfile','deploy/swarm-ui/patch-source.py','deploy/swarm-ui/proxy.py','deploy/swarm-ui/entrypoint.py','deploy/Dockerfile.app-update','video_comfy.py','video_comfy_node.py','video_comfy_proxy.py','prompt_enhancer.py','prompt_enhancer_worker.py','image_upload.py','audio_policy.py','deploy/tts-requirements.lock','stt.py','parakeet_runtime.py','stt-ui.js','api_compat.py','responses_compat.py','execution_setup.py','pocket.py','pocket_worker.py','pocket_runtime.py','deploy/pocket-requirements.lock','deploy/import_pocket.py','tts_runtime.py','tts_test.py','tts_worker.py','tts-ui.js','auto_test.py','auto-test-ui.js','chat_test.py','chat-test-ui.js','endpoint.py','inference.py','endpoint-ui.js','docker_support.py','docker-ui.js','deploy/docker_helper.py','deploy/setup_docker_helper.py','image_encoder_node.py','image_runtime.py','image_test.py','image-test-ui.js','profiles.py','profiles-ui.js','capacity.py','runtime.py','runtime-ui.js','video.py','video_proxy.py','video-ui.js','catalog.py','hub_auth.py','catalog-ui.js','server.py','auth.py','collect_hardware.py','dashboard_data.py','dashboard_history.py','dashboard-ui.js','dashboard.css','themes.css','deploy/import_dashboard_history.py','index.html','app.js','studio.js','style.css','login.html','login.js','access-ui.js','network-ui.js','network/__init__.py','network/client.py','network/config.py','network/hosts.py','network/policy.py','network/rpc.py','deploy/Dockerfile','deploy/image-requirements.lock']
FILES += ['soulx_singer.py','soulx_singer_runtime.py','soulx-singer-ui.js','deploy/prepare_soulx_singer.py'] FILES += ['soulx_singer.py','soulx_singer_runtime.py','soulx-singer-ui.js','deploy/prepare_soulx_singer.py']
@@ -272,7 +272,7 @@ def update(base, rollback=False, force=False, api_ports=None, reuse_runtime=Fals
backup_name=config['name']+'-previous' backup_name=config['name']+'-previous'
if inspect(backup_name):raise RuntimeError('Rückfall-Containername belegt. Keine Änderung ausgeführt.') if inspect(backup_name):raise RuntimeError('Rückfall-Containername belegt. Keine Änderung ausgeführt.')
stamp=str(time.time_ns()) stamp=str(time.time_ns())
shutil.copytree(base/'state',base/'backups'/stamp,ignore=shutil.ignore_patterns('articulino-runtime','articulino-jobs','seedvc-runtime','seedvc-jobs','humaneness-runtime','humaneness-jobs','stimmatelier-ui','qwen-native-runtime','qwen-native-jobs','strata-runtime','strata-worker','strata-data','strata-ssd','strata-install-src','soulx_singer-runtime','soulx_singer-data','seed_vc-runtime','seed_vc-data','seed_vc-prepare','reference-models','xvc-runtime','xvc-data','xvc-prepare','cache','omni-reference-check.py','omni-cache-clean.py','applio-runtime','applio-data','applio-checkout','applio-runtime.py','import_applio.py','applio-migration.log','acestep-runtime','acestep-jobs','acestep-setup-code','acestep-checkout','acestep-source-files','acestep-test-tmp','music-verification','music-test-temp','music-jobs','music-remix-runtime','separator-runtime','separator-tests','voxcpm-runtime','omnivoice-runtime','voice-worker-check','voice-integration-check','voice-setup-code','audio-cpp-runtime','ltx-original-runtime','original-work','tts-runtime','tts-tests','voice-tests','models','runtime','runtime-verification','image-tests','image-verification','image-verification-*','image-runtime','video-runtime','video-verification','video-verification-*','comfy-work','router-verification-*')) shutil.copytree(base/'state',base/'backups'/stamp,ignore=shutil.ignore_patterns('kikiri-runtime','kikiri-jobs','kikiri-data','articulino-runtime','articulino-jobs','seedvc-runtime','seedvc-jobs','humaneness-runtime','humaneness-jobs','stimmatelier-ui','qwen-native-runtime','qwen-native-jobs','strata-runtime','strata-worker','strata-data','strata-ssd','strata-install-src','soulx_singer-runtime','soulx_singer-data','seed_vc-runtime','seed_vc-data','seed_vc-prepare','reference-models','xvc-runtime','xvc-data','xvc-prepare','cache','omni-reference-check.py','omni-cache-clean.py','applio-runtime','applio-data','applio-checkout','applio-runtime.py','import_applio.py','applio-migration.log','acestep-runtime','acestep-jobs','acestep-setup-code','acestep-checkout','acestep-source-files','acestep-test-tmp','music-verification','music-test-temp','music-jobs','music-remix-runtime','separator-runtime','separator-tests','voxcpm-runtime','omnivoice-runtime','voice-worker-check','voice-integration-check','voice-setup-code','audio-cpp-runtime','ltx-original-runtime','original-work','tts-runtime','tts-tests','voice-tests','models','runtime','runtime-verification','image-tests','image-verification','image-verification-*','image-runtime','video-runtime','video-verification','video-verification-*','comfy-work','router-verification-*'))
was_running=previous['State']['Running'] was_running=previous['State']['Running']
if was_running:run('docker','stop','--time','15',config['name']) if was_running:run('docker','stop','--time','15',config['name'])
run('docker','rename',config['name'],backup_name) run('docker','rename',config['name'],backup_name)
+5
View File
@@ -0,0 +1,5 @@
ARG DECK_BASE
FROM ${DECK_BASE}
COPY --chmod=0644 kikiri.py kikiri_runtime.py kikiri_worker.py audio_policy.py backup.py endpoint.py execution_setup.py profiles.py server.py tts-ui.js /app/
COPY --chmod=0644 deploy/kikiri/*.py deploy/kikiri/requirements.lock deploy/kikiri/README.md /app/deploy/kikiri/
RUN python3 -c "import ast;from pathlib import Path;[ast.parse(Path(p).read_text()) for p in ('/app/kikiri.py','/app/kikiri_runtime.py','/app/kikiri_worker.py','/app/server.py','/app/endpoint.py')]"
+98
View File
@@ -0,0 +1,98 @@
# Kikiri: private trained Anna, native CPU
Selected voice: the exact Anna full20 +20 checkpoint/voicepack accepted on
27 October 2026, with the narrow confirmed Vögel/Vögeln/Vögelchen phoneme fix.
No further training, additional sentence gaps, breath smoothing, pitch shift
or reference-voice approximation is part of this adapter. It uses FP32 and
four CPU threads, 24-kHz mono PCM16. Granular breath texture and some unusual
sentence emphasis remain known listening limitations, not solved claims.
## Explicit dependencies and preparation
Native prerequisites: supported Debian x86_64, Python >=3.12 for the operator
scripts, Git, CA roots, libstdc++6, libgomp1, FFmpeg (MP3 endpoint output), and
the normal Deck service-user/state layout. No running container, global Torch,
CUDA library, another model environment or experiment folder is a prerequisite.
`install.py` independently downloads SHA256-verified CPython3.11.18 and uv0.13.6,
then installs CPU-only Torch2.6.0 and the exact qualified package set in
`requirements.lock`. Kokoro fork `b96fef95e6a746495f92443fac7c688f90fc57fc` and
Misaki fork `6d252a2e02f3b030f22f56686f1a73786c16ffc8` are immutable source pins.
The original public config is Kikiri source
`a12d0410e89841e6f3c09958ae5c072f90ae1d49`, `training/config.json`, with its
fixed checksum in `kikiri_runtime.py`. eSpeak library/data come from the
qualified loader wheel; no host speech package is silently assumed.
As the Deck data owner, import the separately supplied **private** files first:
```sh
python3 deploy/kikiri/import_voice.py --state /var/lib/athena-deck \
--model /protected/anna-plus20/model.pth \
--voice /protected/anna-plus20/voice.pt \
--config /protected/anna-plus20/config.json
python3 deploy/kikiri/bootstrap.py --state /var/lib/athena-deck
```
The importer verifies all three fixed hashes before copying; a different voice
or corrupt existing destination is rejected. Originals are not changed. The
private bundle lives in `STATE/kikiri-data/anna-plus20`, the separately pinned
CPU environment in `STATE/kikiri-runtime/ID`. The main weight is imported into
the library as `local/kikiri-anna`, content revision equal to its SHA256; it has
no fictitious public download location. Private model/voice/config files are
not in Git. The original recording is not needed for inference.
Use an executable private TMPDIR inside the runtime/jobs root: phonemizer
copies its shared library there. A noexec `/tmp` is preserved. Readiness is
published only after validation; failed setup removes only its own candidate
environment and does not destroy an existing active runtime.
## Profile, endpoint and warm worker
Create an audio profile in the authenticated existing Deck UI, select the
imported Anna model, use `speed=1`, title **Kikiri Anna CPU**, API ID
`kikiri-anna-cpu`. Keep it unpublished until its direct test passes. The native
operator equivalent may call `Profiles.save` only with Deck stopped at confirmed
idle; never rewrite a live profiles.json behind the application.
The existing TTS page recognizes this model; its own `/api/v1/kikiri` test routes
use the same bounded job/audio contract. Shared `/v1/audio/speech` supports
explicit `kikiri-anna-cpu` and the neutral `tts` alias, WAV/MP3/PCM, German,
`voice=default`/`Anna`, speed1. Publish exactly one dedicated audio profile to
switch the neutral alias. Hermes remains configured to `model: tts` on the NAS;
no per-bot or Mac/Conduit change is needed. Existing central text preparation
remains optional and unchanged. The worker itself only performs the selected
German frontend mapping and the narrow Vögel correction.
The CPU worker uses the configured speech affinity pool, nice10, four Torch
threads and one inter-op thread. CPU-only Torch and hidden GPU devices are
verified. It requests no GPU lease, does not unload Strata, and refuses startup
with less than1.5GiB cgroup headroom. Load and a short frontend/decoder warmup
complete before readiness. Warm residency follows the published TTS profile
using the existing audio policy; switching publication does not rewrite the
saved user preference. Cancellation is cooperative between native chunks,
not a claim to interrupt a single model pass. Inputs remain bounded to1000
characters and PCM to32MiB; unknown/dropped phonemes fail explicitly.
## Update, restore and present acceptance limits
Git publication does not activate this adapter. Install the reviewed Deck files
with the normal native service-update method; restart only after explicit Go
and confirmed completion of all accepted/queued work. Preserve the current
LLM profile/settings and restore it afterwards. In the current read-only Docker
deployment a thin image on the exact current base carries only the changed app
files; no base-image, driver or Strata rebuild is required. No hot monkeypatch
or additional permanent TTS service is used.
Existing encrypted user-data backup sources now explicitly include
`kikiri-data`, `kikiri-jobs` and the local Kikiri library directory. Runtime
source/version metadata is included in the configuration recipe. No new backup
is run by this change. Restore private media/library first, rebuild the public
CPU environment with the pinned recipe, then restore/recheck profile and single
TTS publication. A configuration-only backup cannot recreate a private voice
and explicitly reports that missing local model. Do not try to download Anna
from Hugging Face. A fresh-Debian encrypted end-to-end restore is not tested.
Rollback selects the previous TTS publication; retain Articulino, Qwen, original
Anna and their settings. Any app rollback uses its normal separately approved
maintenance path. At preparation time production activation and native-client
listening acceptance are still pending; report them separately from tests.
+12
View File
@@ -0,0 +1,12 @@
"""Install the native CPU recipe after restoring/importing the private voice."""
import argparse,json,sys
from pathlib import Path
sys.path.insert(0,str(Path(__file__).resolve().parents[2]))
from kikiri_runtime import KikiriRuntime
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('--state',required=True,type=Path);a=p.parse_args()
runtime=KikiriRuntime(a.state/'kikiri-runtime')
if not runtime.status()['installed']:
runtime.start()
while runtime.worker.is_alive():runtime.worker.join(1)
status=runtime.status();print(json.dumps(status));sys.exit(0 if status['installed'] else 1)
+27
View File
@@ -0,0 +1,27 @@
"""Import ONLY the selected private +20 model/voice/config, no profile publication."""
import argparse,hashlib,json,os,shutil,sys,tempfile
from pathlib import Path
sys.path.insert(0,str(Path(__file__).resolve().parents[2]))
from kikiri_runtime import KikiriRuntime,ASSETS,verify_assets
def import_voice(state,model,voice,config):
state=Path(state);target=state/'kikiri-data/anna-plus20';os.umask(0o077)
sources={'model.pth':Path(model),'voice.pt':Path(voice),'config.json':Path(config)}
for name,source in sources.items():
if source.is_symlink() or not source.is_file():raise ValueError('Normale lokale Datei erforderlich: '+name)
with source.open('rb') as f:digest=hashlib.file_digest(f,'sha256').hexdigest()
if digest!=ASSETS[name][1]:raise ValueError('Nicht der ausgewählte Anna-Stand: '+name)
if target.exists():verify_assets(target)
else:
target.parent.mkdir(parents=True,exist_ok=True,mode=0o700)
with tempfile.TemporaryDirectory(dir=target.parent,prefix='.import-') as work:
work=Path(work)
for name,source in sources.items():shutil.copyfile(source,work/name);(work/name).chmod(0o600)
verify_assets(work);work.rename(target)
ident=KikiriRuntime(state/'kikiri-runtime').ensure_library()
return dict(imported=True,model_id=ident,private_assets='kikiri-data/anna-plus20',profile_published=False)
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('--state',required=True,type=Path)
for name in ('model','voice','config'):p.add_argument('--'+name,required=True,type=Path)
a=p.parse_args();print(json.dumps(import_voice(a.state,a.model,a.voice,a.config)))
+42
View File
@@ -0,0 +1,42 @@
"""Reproducible native CPU environment; public code only, no private voice download."""
import argparse,hashlib,json,os,subprocess,tarfile,urllib.request,zipfile
from pathlib import Path
PYTHON_URL='https://github.com/astral-sh/python-build-standalone/releases/download/20261026/cpython-3.11.18%2B20261026-x86_64-unknown-linux-gnu-install_only.tar.gz'
PYTHON_SHA='a87ee63646c8f8438b7af3954b2135ed2af91d033c631f12a8f20af903046d06'
UV_URL='https://files.pythonhosted.org/packages/5c/43/0688ff5142934238f2812e348f4a24e09b57d48bfb38dd8f850325a0d9de/uv-0.13.6-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl'
UV_SHA='22759b8895e1103578de6fb4cd27e94b4399d021023378d29f01333717751fba'
def download(url,path,expected):
with urllib.request.urlopen(url,timeout=120) as source,path.open('wb') as out:
while block:=source.read(1024*1024):out.write(block)
with path.open('rb') as f:assert hashlib.file_digest(f,'sha256').hexdigest()==expected,'Public download hash mismatch'
def install(root):
root=Path(root).resolve();root.mkdir(parents=True,exist_ok=True,mode=0o700)
archive=root/'python.tar.gz';download(PYTHON_URL,archive,PYTHON_SHA)
with tarfile.open(archive) as t:t.extractall(root,filter='data')
archive.unlink()
wheel=root/'uv.whl';download(UV_URL,wheel,UV_SHA)
with zipfile.ZipFile(wheel) as z:
names=[n for n in z.namelist() if n.endswith('/uv')];assert len(names)==1
uv=root/'uv';uv.write_bytes(z.read(names[0]));uv.chmod(0o700)
wheel.unlink()
(root/'tmp').mkdir(mode=0o700,exist_ok=True)
# phonemizer copies its shared library into TMPDIR. The production /tmp is
# intentionally noexec; use this runtime's own private executable data mount.
env=dict(os.environ,TMPDIR=str(root/'tmp'),CUDA_VISIBLE_DEVICES='',UV_NO_CONFIG='1',UV_CACHE_DIR=str(root/'cache'),UV_PYTHON_DOWNLOADS='never',GIT_TERMINAL_PROMPT='0')
def run(*args):subprocess.run([str(x) for x in args],env=env,check=True)
py=root/'venv/bin/python'
run(uv,'venv','--python',root/'python/bin/python3.11',root/'venv')
run(uv,'pip','install','--python',py,'--index-url','https://download.pytorch.org/whl/cpu','torch==2.6.0+cpu')
run(uv,'pip','install','--python',py,'--extra-index-url','https://download.pytorch.org/whl/cpu',
'--index-strategy','unsafe-best-match','-r',Path(__file__).with_name('requirements.lock'))
run(uv,'pip','check','--python',py)
run(py,'-c','import torch;from kokoro import KModel,KPipeline;from misaki.de import DEG2P;assert torch.version.cuda is None;assert DEG2P()("Die Stimme ist bereit.")[0]')
(root/'requirements-resolved.txt').write_text(subprocess.check_output([str(uv),'pip','freeze','--python',str(py)],env=env,text=True))
# Wheel/Git build caches are not needed by offline inference.
import shutil
shutil.rmtree(root/'cache',ignore_errors=True)
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('--root',required=True,type=Path);a=p.parse_args();install(a.root)
+98
View File
@@ -0,0 +1,98 @@
# Qualified CPython 3.11 x86_64 CPU environment, 27 October 2026.
addict==2.4.0
annotated-doc==0.0.5
annotated-types==0.7.0
attrs==25.1.0
babel==2.17.0
blis==1.2.0
catalogue==2.0.10
certifi==2025.1.31
cffi==2.0.0
charset-normalizer==3.4.1
click==8.1.8
clldutils==3.21.0
cloudpathlib==0.20.0
cloudpickle==3.1.2
colorama==0.4.6
colorlog==6.9.0
confection==0.1.5
csvw==3.5.1
curated-tokenizers==0.0.9
curated-transformers==0.1.1
cymem==2.0.11
dlinfo==2.0.0
docopt==0.6.2
espeakng-loader==0.2.4
filelock==3.17.0
fsspec==2025.2.0
huggingface-hub==0.28.1
idna==3.10
isodate==0.7.2
jinja2==3.1.5
joblib==1.4.2
jsonschema==4.23.0
jsonschema-specifications==2024.10.1
kokoro @ git+https://github.com/semidark/kokoro@b96fef95e6a746495f92443fac7c688f90fc57fc
langcodes==3.5.0
language-data==1.3.0
language-tags==1.2.0
loguru==0.7.3
lxml==5.3.1
marisa-trie==1.2.1
markdown==3.7
markdown-it-py==3.0.0
markupsafe==3.0.2
mdurl==0.1.2
misaki[en,de] @ git+https://github.com/semidark/misaki@6d252a2e02f3b030f22f56686f1a73786c16ffc8
mpmath==1.3.0
murmurhash==1.0.12
networkx==3.6.1
num2words==0.5.14
numpy==1.26.4
packaging==24.2
phonemizer-fork==3.3.2
pip==26.0.1
preshed==3.0.9
pycparser==3.0
pydantic==2.10.6
pydantic-core==2.27.2
pygments==2.19.1
pylatexenc==2.10
pyparsing==3.2.1
python-dateutil==2.9.0.post0
pyyaml==6.0.2
rdflib==7.1.3
referencing==0.36.2
regex==2024.11.6
requests==2.32.3
rfc3986==1.5.0
rich==13.9.4
rpds-py==0.22.3
safetensors==0.5.2
segments==2.2.1
setuptools==75.8.0
shellingham==1.5.4
six==1.17.0
smart-open==7.1.0
soundfile==0.14.0
spacy==3.8.4
spacy-curated-transformers==0.3.0
spacy-legacy==3.0.12
spacy-loggers==1.0.5
srsly==2.5.1
sympy==1.13.1
tabulate==0.9.0
termcolor==3.3.0
thinc==8.3.4
tokenizers==0.21.0
torch==2.6.0+cpu
tqdm==4.67.1
transformers==4.48.3
typer==0.15.1
typing-extensions==4.12.2
tzdata==2026.5
uritemplate==4.1.1
urllib3==2.3.0
wasabi==1.1.3
weasel==0.4.1
wrapt==1.17.2
+50
View File
@@ -0,0 +1,50 @@
"""Scoped real CPU worker test with synthetic text; no production request/switch."""
import argparse,hashlib,json,time,wave
from pathlib import Path
import sys
from types import SimpleNamespace
sys.path.insert(0,str(Path(__file__).resolve().parents[2]))
from kikiri_runtime import KikiriRuntime,REPO,MODEL_REVISION,MODEL_FILE,MODEL_SHA
from kikiri import Kikiri
def verify(state):
state=Path(state);root=state/'kikiri-verification-jobs'
root.mkdir(exist_ok=True,mode=0o700)
watched=('profiles.json','endpoint.json','audio-policy.json','cpu-partition.json')
def hashes():return {n:hashlib.sha256((state/n).read_bytes()).hexdigest() for n in watched if (state/n).is_file()}
before=hashes();runtime=KikiriRuntime(state/'kikiri-runtime');assert runtime.status()['installed']
model=dict(kind='audio',repo=REPO,revision=MODEL_REVISION,file=MODEL_FILE,sha256=MODEL_SHA)
row=dict(id='c'*32,revision=1,runnable=True,parameters={'speed':1},model=model)
worker=Kikiri(root,SimpleNamespace(status=lambda:{'profiles':[row]}),runtime)
cases={
'expressive':'Guten Morgen, Michael. Schön, dass du wieder da bist! Draußen rauscht der Regen, und die Vögel suchen Schutz unter dem Dach. Wirklich? Das hätte ich nicht gedacht. Heute nehmen wir uns ein wenig Zeit und machen alles ganz in Ruhe.',
'technical':'Home Assistant läuft auf Unraid. Der Docker-Container meldet 47 Grad. Im Logfile stehen keine Fehler. Der freie Speicher beträgt 512 MiB. Die Verbindung liefert 100 Mbit pro Sekunde. Um 18:30 CEST beginnt der nächste Scan.'}
results=[];began=time.monotonic()
try:
for case,text in cases.items():
if case=='technical':
from tts_text_enhancer import prepare
text=prepare(text,'German')
job=worker.start(row['id'],text,streaming=True);deadline=time.monotonic()+150
while True:
current=worker.job_status(job['id'])
if current['state']!='running':break
if time.monotonic()>deadline:raise RuntimeError('Own worker test timed out')
time.sleep(.1)
assert current['state']=='complete',current['phase']
directory=root/job['id'];pcm=b''.join(p.read_bytes() for p in sorted(directory.glob('chunk-*.pcm')))
with wave.open(str(directory/'result.wav')) as w:
assert (w.getframerate(),w.getnchannels(),w.getsampwidth())==(24000,1,2)
assert w.readframes(w.getnframes())==pcm
item={k:current[k] for k in ('id','duration','sample_rate','seconds','first_chunk_seconds')}
item.update(case=case,rtf=current['seconds']/current['duration'],pcm_matches_wav=True)
results.append(item)
finally:worker.stop()
result=dict(complete=len(results)==2,runs=results,wall_seconds=time.monotonic()-began,
production_config_unchanged=before==hashes(),own_worker_stopped=worker.process is None)
(root/'verification.json').write_text(json.dumps(result,indent=2)+'\n')
print(json.dumps(result),flush=True)
assert result['complete'] and result['production_config_unchanged']
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('--state',required=True,type=Path);a=p.parse_args();verify(a.state)
+2 -2
View File
@@ -23,11 +23,11 @@ def key():
return KEY.read_bytes().strip()+b'\n' return KEY.read_bytes().strip()+b'\n'
def sources(): def sources():
names=('articulino-jobs','seedvc-jobs','humaneness-jobs','qwen-native-jobs','speech-voices','pocket-jobs','soulx_singer-data','legacy-userdata','applio-data','xvc-data','voice-tests','music-jobs','acestep-jobs','separator-tests','image-tests','tts-tests') names=('kikiri-data','kikiri-jobs','articulino-jobs','seedvc-jobs','humaneness-jobs','qwen-native-jobs','speech-voices','pocket-jobs','soulx_singer-data','legacy-userdata','applio-data','xvc-data','voice-tests','music-jobs','acestep-jobs','separator-tests','image-tests','tts-tests')
roots=[(STATE/n,'deck/'+n) for n in names]+[(STATE/'video/original-work/outputs','deck/video/original-work/outputs'),(STATE/'video/original-work/remote-inputs','deck/video/original-work/remote-inputs'),(STATE/'video/original-work/deskweb','deck/video/original-work/deskweb'),(Path('/opt/athena-ladypoly/data'),'services/ladypoly'),(Path('/opt/athena-deck-docker-apps'),'services/web-studios')] roots=[(STATE/n,'deck/'+n) for n in names]+[(STATE/'video/original-work/outputs','deck/video/original-work/outputs'),(STATE/'video/original-work/remote-inputs','deck/video/original-work/remote-inputs'),(STATE/'video/original-work/deskweb','deck/video/original-work/deskweb'),(Path('/opt/athena-ladypoly/data'),'services/ladypoly'),(Path('/opt/athena-deck-docker-apps'),'services/web-studios')]
# Private locally-trained voices have no public replacement source. # Private locally-trained voices have no public replacement source.
for p in (STATE/'models').glob('*/entry.json'): for p in (STATE/'models').glob('*/entry.json'):
if json.loads(p.read_text()).get('repo','').startswith('local/mikes-applio'):roots.append((p.parent,'deck/models/'+p.parent.name)) if json.loads(p.read_text()).get('repo','').startswith(('local/mikes-applio','local/kikiri-anna')):roots.append((p.parent,'deck/models/'+p.parent.name))
return roots return roots
def files(roots): def files(roots):
@@ -0,0 +1,95 @@
# Kikiri Anna endpoint integration · 28 October 2026
Michael authorized integrating the selected trained Anna TTS profile. The
selected +20 model/voicepack and the confirmed narrow Vögel correction are
retained; no further training, smoothing, pitch change or artificial sentence
pauses. The current Strata/Qwen workload must not be unloaded without a
separate explicit Go. Clients continue to request the shared neutral `tts` alias.
## Prepared implementation
- Separate CPU-only worker and reproducible pinned environment; public native
CPython3.11.18, Torch2.6.0+cpu, fixed Kokoro/Misaki forks and qualified packages.
- Private selected weights/voice/config imported with exact SHA256 checks to
`STATE/kikiri-data/anna-plus20`, owner65534:65534, private modes. Originals
remain unchanged. No experiment-folder dependency or public Anna download.
- Main library entry `local/kikiri-anna`, ID
`210821ba56d02267f6cbfaca80542acf6317ee24e8eb8ca673a89e6faab22e99`.
- Profile **Kikiri Anna CPU**, API ID `kikiri-anna-cpu`, profile ID
`55674c73a9604e1fa6e9c4a85a5f9692`, speed1. Created through the authenticated
existing Deck UI; the exact model ID was independently read back. It is
**not published** while the old app lacks this adapter.
- Existing profile/test/library UI, `model=tts`/explicit-model routing,
WAV/MP3/PCM, cancellation, warm residency, deletion protection and CPU
resource rules are integrated. No Hermes, Mac or Conduit source/config change.
- Configuration backup recipes and explicit encrypted media-source lists include
the private voice and its local library directory. No backup was executed.
Reproduction/update/restore instructions: [native recipe](../../../deploy/kikiri/README.md).
The first installation reached package compatibility but failed because
phonemizer copies its shared library into the noexec production `/tmp`.
The corrected recipe supplies its own private executable TMPDIR inside the
runtime/jobs root. No global mount/security flags changed; the failed own
candidate environment was removed. The corrected native install completed.
The first synthetic driver invocation unnecessarily constrained its own
affinity before the shared CPU-layout validator checked the whole layout.
Removing that outer restriction lets the actual worker apply the existing
speech affinity itself. No saved CPU mask or production setting was changed.
## Verification
The complete local synthetic regression suite passes **711 tests in82.175s**.
This includes nine new Kikiri tests for exact voice qualification, narrow
Unicode-aware pronunciation, neutral-alias/format routing, safe voice selection,
cooperative cancellation, PCM/WAV parity, corrupt assets, unknown phonemes and
CPU warm selection. An old model-management expectation omitted the two
already-published Strata pipeline defaults (`groups=1`, batch-MTP=true); only
that fixture was updated, no Strata behavior changed. Initial failures and the
restricted-socket repeat are not counted as successful tests. The final
17-test packaging/Kikiri subset also passes with its synthetic socket allowed.
The real installed CPU worker ran two synthetic passages, then was stopped:
| Case | Audio | Synthesis | RTF | PCM/WAV |
| --- | ---: | ---: | ---: | --- |
| Selected expressive paragraph | 15.525s | 4.570s | 0.2943 | Identical samples |
| Technical text through existing preparation | 20.625s | 6.107s | 0.2961 | Identical samples |
About3.4× realtime, four CPU threads. These are short generation measurements,
not a sustained Strata-load stress test or a first-sample latency guarantee.
The native chunk arrives after its synthesis; this adapter does not claim
incremental audio within one model pass. [Worker record](worker-check.json).
Local Parakeet recognized all40 expressive words, including **Vögel**, with
punctuation ignored. Technical recognition retains known term discrepancies
around Unraid, log wording, Mebibyte, CEST and Scan; ASR alone cannot attribute
all of these to TTS or establish voice identity. No claim of perfect technical
pronunciation. [Synthetic-only STT record](synthetic-stt.json).
The worker check confirmed unchanged production config hashes and stopped
only its own worker. Deck still has start time
`2026-10-28T11:44:30.359091352Z`, PID916651; its scoped process family includes
Strata PID917398. No Deck, model, Hermes, container or host restart occurred.
Only the newly requested unpublished profile/library/voice and preparation
files were added. Existing Articulino remains the sole published dedicated TTS.
## Candidate and pending activation
App-only image `athena-deck-standalone:kikiri-anna-20261028` built successfully
on the currently running `strata-pipeline-config-20261028` base. No apt, CUDA,
Strata or large base-image rebuild. Model weights/private audio are absent
from the image and Git. The image is a candidate, **not the running container**.
The adapter cannot be loaded into the already running read-only app without
restarting Deck. Do not monkeypatch it or replace a current worker behind the
app. Await Michael's explicit Go for an idle Deck restart and the corresponding
temporary end/reload of Qwen. Before switching re-read current image, accepted
and queued requests, active profile and settings; preserve concurrent changes.
After Go restore that exact chat profile/settings, then switch the single TTS
publication via authenticated UI, verify neutral alias/PCM/MP3 and obtain native
client listening acceptance. A new browser login may be needed after restart.
No productive activation, final endpoint/client acceptance or fresh-Debian
encrypted restore is claimed by this preparation. Keep Articulino/Qwen and
original/private training data. Full VPN exclusion remains binding.
@@ -0,0 +1,12 @@
[
{
"case": "expressive",
"seconds": 1.1513857230020221,
"recognized": "Guten Morgen Michael, schön, dass du wieder da bist. Draußen rauscht der Regen und die Vögel suchen Schutz unter dem Dach. Wirklich, das hätte ich nicht gedacht. Heute nehmen wir uns ein wenig Zeit und machen alles ganz in Ruhe."
},
{
"case": "technical",
"seconds": 1.7048103419947438,
"recognized": "Home Assistant läuft auf Anreit. Der Docker Container meldet 47 Grad. Im Logdatei stehen keine Fehler. Der freie Speicher beträgt 512 Mebibüte. Die Verbindung liefert 100 Mbit pro Sekunde. Um 18,30 Uhr KST beginnt der nächste Scarn."
}
]
@@ -0,0 +1,28 @@
{
"complete": true,
"runs": [
{
"id": "1c56cb639f9242d3bde55be0169f8531",
"duration": 15.525,
"sample_rate": 24000,
"seconds": 4.5696970260178205,
"first_chunk_seconds": 4.568761560018174,
"case": "expressive",
"rtf": 0.2943444139141913,
"pcm_matches_wav": true
},
{
"id": "afe8f9ca2ccf4403bf9ab1060da160cd",
"duration": 20.625,
"sample_rate": 24000,
"seconds": 6.106619570025941,
"first_chunk_seconds": 6.105532149027567,
"case": "technical",
"rtf": 0.29607852460731837,
"pcm_matches_wav": true
}
],
"wall_seconds": 17.803943233011523,
"production_config_unchanged": true,
"own_worker_stopped": true
}
+14 -1
View File
@@ -162,6 +162,7 @@ class Endpoint:
for key,kind in [('llm','chat'),('image','image'),('tts','audio'),('stt','stt'),('music','music'),('voice','voice')]: for key,kind in [('llm','chat'),('image','image'),('tts','audio'),('stt','stt'),('music','music'),('voice','voice')]:
subset=[p for p in rows if p['kind']==kind] subset=[p for p in rows if p['kind']==kind]
counts[key]=dict(enabled=sum(p['enabled'] for p in subset),available=sum(p['enabled'] and p['runnable'] for p in subset),loaded=bool(worker['state']=='ready' and kind=='chat') if kind=='chat' else bool(self.tts and self.tts.status().get('loaded')) if kind=='audio' else bool(self.stt and self.stt.status().get('loaded')) if kind=='stt' else bool(self.music and self.music.status().get('loaded')) if kind=='music' else bool(self.voxcpm and self.voxcpm.status().get('loaded')) if kind=='voice' else bool(kind=='image' and job and job['state']=='running'),supported=kind in ('chat','image') or (kind=='audio' and self.tts is not None) or (kind=='stt' and self.stt is not None) or (kind=='music' and self.music is not None) or (kind=='voice' and self.voxcpm is not None)) counts[key]=dict(enabled=sum(p['enabled'] for p in subset),available=sum(p['enabled'] and p['runnable'] for p in subset),loaded=bool(worker['state']=='ready' and kind=='chat') if kind=='chat' else bool(self.tts and self.tts.status().get('loaded')) if kind=='audio' else bool(self.stt and self.stt.status().get('loaded')) if kind=='stt' else bool(self.music and self.music.status().get('loaded')) if kind=='music' else bool(self.voxcpm and self.voxcpm.status().get('loaded')) if kind=='voice' else bool(kind=='image' and job and job['state']=='running'),supported=kind in ('chat','image') or (kind=='audio' and self.tts is not None) or (kind=='stt' and self.stt is not None) or (kind=='music' and self.music is not None) or (kind=='voice' and self.voxcpm is not None))
if getattr(self,'kikiri',None):counts['tts']['loaded']=counts['tts']['loaded'] or self.kikiri.status()['loaded']
if getattr(self,'articulino',None):counts['tts']['loaded']=counts['tts']['loaded'] or self.articulino.status()['loaded'] if getattr(self,'articulino',None):counts['tts']['loaded']=counts['tts']['loaded'] or self.articulino.status()['loaded']
if getattr(self,'pocket',None):counts['tts']['loaded']=counts['tts']['loaded'] or self.pocket.status()['loaded'] if getattr(self,'pocket',None):counts['tts']['loaded']=counts['tts']['loaded'] or self.pocket.status()['loaded']
if getattr(self,'qwen_native',None):counts['tts']['loaded']=counts['tts']['loaded'] or self.qwen_native.status()['loaded'] if getattr(self,'qwen_native',None):counts['tts']['loaded']=counts['tts']['loaded'] or self.qwen_native.status()['loaded']
@@ -221,6 +222,9 @@ class Endpoint:
if not data['enabled'] and row['kind']=='audio' and getattr(self,'pocket',None): if not data['enabled'] and row['kind']=='audio' and getattr(self,'pocket',None):
status=self.pocket.status() status=self.pocket.status()
if status.get('profile_id')==row['id'] and (status.get('job') or {}).get('state')!='running':self.pocket.stop() if status.get('profile_id')==row['id'] and (status.get('job') or {}).get('state')!='running':self.pocket.stop()
if not data['enabled'] and row['kind']=='audio' and getattr(self,'kikiri',None):
status=self.kikiri.status()
if status.get('profile_id')==row['id'] and (status.get('job') or {}).get('state')!='running':self.kikiri.stop()
if not data['enabled'] and row['kind']=='audio' and getattr(self,'articulino',None): if not data['enabled'] and row['kind']=='audio' and getattr(self,'articulino',None):
status=self.articulino.status() status=self.articulino.status()
if status.get('profile_id')==row['id'] and (status.get('job') or {}).get('state')!='running':self.articulino.stop() if status.get('profile_id')==row['id'] and (status.get('job') or {}).get('state')!='running':self.articulino.stop()
@@ -269,6 +273,7 @@ class Endpoint:
if getattr(self,'pocket',None):self.pocket.stop() if getattr(self,'pocket',None):self.pocket.stop()
if getattr(self,'seedvc',None):self.seedvc.stop() if getattr(self,'seedvc',None):self.seedvc.stop()
if getattr(self,'humaneness',None):self.humaneness.stop() if getattr(self,'humaneness',None):self.humaneness.stop()
if getattr(self,'kikiri',None):self.kikiri.stop()
if getattr(self,'articulino',None):self.articulino.stop() if getattr(self,'articulino',None):self.articulino.stop()
if getattr(self,'qwen_native',None):self.qwen_native.stop() if getattr(self,'qwen_native',None):self.qwen_native.stop()
if self.embeddings:self.embeddings.stop() if self.embeddings:self.embeddings.stop()
@@ -537,9 +542,17 @@ class APIHandler(BaseHTTPRequestHandler):
from qwen_native_runtime import supported as native_model from qwen_native_runtime import supported as native_model
native_row=next((p for p in ep.rows() if native_model(p.get('model')) and data.get('model') in [p.get('api_id',p['name']),p['name'],*p.get('api_aliases',[])] and p['enabled']),None) native_row=next((p for p in ep.rows() if native_model(p.get('model')) and data.get('model') in [p.get('api_id',p['name']),p['name'],*p.get('api_aliases',[])] and p['enabled']),None)
pocket_row=next((p for p in ep.rows() if pocket_model(p.get('model')) and data.get('model') in [p.get('api_id',p['name']),p['name'],*p.get('api_aliases',[])] and p['enabled']),None) pocket_row=next((p for p in ep.rows() if pocket_model(p.get('model')) and data.get('model') in [p.get('api_id',p['name']),p['name'],*p.get('api_aliases',[])] and p['enabled']),None)
from kikiri_runtime import supported as kikiri_model
kikiri_row=next((p for p in ep.rows() if kikiri_model(p.get('model')) and data.get('model') in [p.get('api_id',p['name']),p['name'],*p.get('api_aliases',[])] and p['enabled']),None)
from articulino_runtime import supported as articulino_model from articulino_runtime import supported as articulino_model
articulino_row=next((p for p in ep.rows() if articulino_model(p.get('model')) and data.get('model') in [p.get('api_id',p['name']),p['name'],*p.get('api_aliases',[])] and p['enabled']),None) articulino_row=next((p for p in ep.rows() if articulino_model(p.get('model')) and data.get('model') in [p.get('api_id',p['name']),p['name'],*p.get('api_aliases',[])] and p['enabled']),None)
if articulino_row: if kikiri_row:
profile=ep.find_profile(data.get('model'),'audio');backend=getattr(ep,'kikiri',None)
if not backend:raise APIError('Kikiri-CPU-Laufzeit nicht eingerichtet.',503,'kikiri_unavailable')
profile_seconds=time.monotonic()-started
try:job=backend.start(profile['id'],data.get('input'),speaker=data.get('voice','default'),language=data.get('language','German'),speed=data.get('speed'),wait=True,streaming=streaming)
except ValueError as exc:raise APIError(str(exc)) from None
elif articulino_row:
profile=ep.find_profile(data.get('model'),'audio');backend=getattr(ep,'articulino',None) profile=ep.find_profile(data.get('model'),'audio');backend=getattr(ep,'articulino',None)
if not backend:raise APIError('Articulino-CPU-Laufzeit nicht eingerichtet.',503,'articulino_unavailable') if not backend:raise APIError('Articulino-CPU-Laufzeit nicht eingerichtet.',503,'articulino_unavailable')
profile_seconds=time.monotonic()-started profile_seconds=time.monotonic()-started
+10
View File
@@ -13,6 +13,12 @@ def _assess(model, installed, profile=None):
if not file_role(filename)['profile_eligible']: if not file_role(filename)['profile_eligible']:
result.update(state='component',label='Zusatzdatei',message='Diese Datei wird einem kompatiblen Modellprofil zugeordnet und benötigt keine eigene Laufzeit.') result.update(state='component',label='Zusatzdatei',message='Diese Datei wird einem kompatiblen Modellprofil zugeordnet und benötigt keine eigene Laufzeit.')
return result return result
from kikiri_runtime import supported as kikiri_model
if kikiri_model(model):
ready=bool(installed.get('kikiri'))
result.update(family='Kikiri Anna',evidence='Gepinnter CPU-FP32-Worker mit privatem Anna-plus20-Stand',runtime='Kikiri Anna · CPU',route='#tts-runtime',installed=ready,state='setup' if ready else 'runtime_missing',label='Kikiri Anna · CPU',components=['Trainierter Anna-Stand'],message='Trainierte Anna-Stimme, WAV/MP3/PCM. Private Gewichte und Voicepack importieren; vier CPU-Threads, kein Entladen von Strata.')
if profile:result.update(state='ready' if profile.get('runnable') else 'profile_incomplete',blockers=profile.get('blockers',[]))
return result
from articulino_runtime import supported as articulino_model from articulino_runtime import supported as articulino_model
if articulino_model(model): if articulino_model(model):
ready=bool(installed.get('articulino')) ready=bool(installed.get('articulino'))
@@ -115,6 +121,10 @@ def _assess_candidates(model, installed, profile=None):
meta=model.get('runtime_metadata') or {};family=str(meta.get('architecture') or '').lower() meta=model.get('runtime_metadata') or {};family=str(meta.get('architecture') or '').lower()
def add(id,label,key,route,reason,maintained=True): def add(id,label,key,route,reason,maintained=True):
result['candidates'].append(dict(id=id,label=label,installed=bool(installed.get(key)),route=route,installation_available=maintained,evidence=reason)) result['candidates'].append(dict(id=id,label=label,installed=bool(installed.get(key)),route=route,installation_available=maintained,evidence=reason))
from kikiri_runtime import supported as kikiri_model
if kikiri_model(model):
add('kikiri','Kikiri Anna · CPU','kikiri','#tts-runtime','Trainierter privater Anna-plus20-Stand, ohne CUDA')
return result
from articulino_runtime import supported as articulino_model from articulino_runtime import supported as articulino_model
if articulino_model(model): if articulino_model(model):
add('articulino','Articulino · CPU','articulino','#tts-runtime','Gepinnte ONNX-CPU-Laufzeit ohne CUDA oder PyTorch') add('articulino','Articulino · CPU','articulino','#tts-runtime','Gepinnte ONNX-CPU-Laufzeit ohne CUDA oder PyTorch')
+49
View File
@@ -0,0 +1,49 @@
"""Private trained Anna on CPU, independent of the GPU/LLM scheduler."""
import json,os,select,subprocess
from pathlib import Path
from pocket import Pocket
from kikiri_runtime import supported
import cpu_partition
class Kikiri(Pocket):
name='Kikiri Anna'
cooperative_cancel=True
def voice_path(self,name):
if name not in ('default','Anna','anna'):raise ValueError('Dieses Kikiri-Profil verwendet voice=default oder Anna.')
path=self.runtime.paths()[1]/'voice.pt'
if path.is_symlink() or not path.is_file():raise ValueError('Die trainierte Anna-Stimme fehlt.')
return path.resolve()
def cancel_job(self,ident):
with self.lock:
if self.job and self.job['id']==ident and self.job.get('state')=='running':
self.cancel.set();(self.root/ident/'cancel').touch()
def blockers(self,p):
if not supported(p.get('model')):return ['Nur der geprüfte Kikiri-Anna-plus20-Stand ist qualifiziert.']
errors=[]
if not self.runtime.status()['installed']:errors.append('Kikiri-CPU-Laufzeit und privaten Anna-Stand unter TTS → Einrichten bereitstellen.')
return errors
def _profile(self,ident):
p=next((p for p in self.profiles.status()['profiles'] if p['id']==ident and supported(p.get('model'))),None)
if not p or not p['runnable']:raise ValueError('Kikiri-Anna-Profil ist nicht ausführbar.')
if p['parameters'].get('speed',1)!=1:raise ValueError('Kikiri benötigt hier speed=1.')
return p
def _ensure_cpu(self,p):
python,bundle=self.runtime.paths();layout=cpu_partition.load(self.root.parent);cpus=layout['qwen_tts'] if layout else []
key=(p['id'],p['revision'],str(python),tuple(cpus))
if self.process and self.process.poll() is None and self.session_key==key:return self.process
from inference import cgroup_headroom
available=cgroup_headroom()
if available is not None and available<1536*1024**2:raise ValueError('Kikiri benötigt 1,5 GiB freien Deck-RAM; laufende Modelle bleiben erhalten.')
self.unload_idle();self.root.mkdir(parents=True,exist_ok=True,mode=0o700)
(self.root/'tmp').mkdir(exist_ok=True,mode=0o700)
env={k:v for k,v in os.environ.items() if not k.startswith(('HF_','DECK_','LLAMA_','OPENAI_'))}
env.update(CUDA_VISIBLE_DEVICES='',HF_HUB_OFFLINE='1',HF_HUB_DISABLE_TELEMETRY='1',HF_HUB_DISABLE_IMPLICIT_TOKEN='1',
OMP_NUM_THREADS='4',MKL_NUM_THREADS='4',OPENBLAS_NUM_THREADS='1',HOME=str(self.root),TMPDIR=str(self.root/'tmp'),XDG_CACHE_HOME=str(self.root/'cache'))
argv=[str(python),str(Path(__file__).with_name('kikiri_worker.py')),str(bundle)]
process=subprocess.Popen(cpu_partition.command(argv,cpus),stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.DEVNULL,env=env,start_new_session=True,text=True,bufsize=1)
with self.lock:self.process=process;self.profile_id=p['id']
if not select.select([process.stdout],[],[],90)[0]:self.unload_idle();raise ValueError('Zeitlimit beim Laden von Kikiri Anna.')
try:ready=json.loads(process.stdout.readline())
except ValueError:ready={}
if not ready.get('ready'):self.unload_idle();raise ValueError('Kikiri-CPU-Worker konnte nicht starten. Privaten Anna-Stand und Laufzeit prüfen.')
self.session_key=key;return process
+83
View File
@@ -0,0 +1,83 @@
"""Pinned CPU inference with a separately restored private Anna bundle."""
import hashlib,json,os,shutil,sys,time
from pathlib import Path
from ltx_original_runtime import LTXOriginalRuntime
VERSION='1.0.0'
REVISION='kikiri-anna-plus20-cpu-v1'
REPO='local/kikiri-anna'
MODEL_SHA='eac26cd33205c3ea3054102943ea956dd9f56e1751a5203bb7788fbbfd3d7d53'
MODEL_REVISION=MODEL_SHA # Local content revision, not a public Git commit.
MODEL_FILE='anna-full20-plus20.pth'
ASSETS={
'model.pth':(327187851,MODEL_SHA),
'voice.pt':(523739,'5c5f913c31155bc55c89076b1c46d58f4a843b45494e3b8dacfa9851484a8ee7'),
'config.json':(None,'5abb01e2403b072bf03d04fde160443e209d7a0dad49a423be15196b9b43c17f')}
def supported(model):
return bool(model and model.get('kind')=='audio' and model.get('repo')==REPO and model.get('revision')==MODEL_REVISION and model.get('file')==MODEL_FILE and model.get('sha256')==MODEL_SHA)
def verify_assets(directory):
directory=Path(directory)
if directory.is_symlink():raise ValueError('Kikiri-Stimmordner darf kein Symlink sein.')
for name,(size,expected) in ASSETS.items():
path=directory/name
if path.is_symlink() or not path.is_file() or size is not None and path.stat().st_size!=size:raise ValueError('Kikiri-Datei fehlt oder ist unvollständig: '+name)
with path.open('rb') as f:digest=hashlib.file_digest(f,'sha256').hexdigest()
if digest!=expected:raise ValueError('Kikiri-Prüfsumme abweichend: '+name)
class KikiriRuntime(LTXOriginalRuntime):
name='Kikiri Anna · CPU'
def __init__(self,root):super().__init__(root,None)
def paths(self):
bundle=self.root.parent/'kikiri-data/anna-plus20'
try:
ident=json.loads((self.root/'active.json').read_text())['id']
if len(ident)==32 and all(c in '0123456789abcdef' for c in ident):
base=self.root/ident
if (base/'ready').read_text().strip()==REVISION:return base/'venv/bin/python',bundle
except (OSError,ValueError,KeyError,TypeError):pass
return self.root/'missing-python',bundle
def status(self):
python,bundle=self.paths()
private=all(not (bundle/n).is_symlink() and (bundle/n).is_file() and (size is None or (bundle/n).stat().st_size==size) for n,(size,_) in ASSETS.items())
return dict(installed=python.is_file() and private,environment_installed=python.is_file(),voice_installed=private,
revision=REVISION,version=VERSION,device='cpu',required_disk_gib=3,job=dict(self.job) if self.job else None,
speakers=['default','Anna'],languages=['German'],origin='https://github.com/semidark/kikiri-tts')
def ensure_library(self):
_,bundle=self.paths();verify_assets(bundle)
ident=hashlib.sha256((REPO+MODEL_REVISION+MODEL_FILE).encode()).hexdigest()
target=self.root.parent/'models'/ident
if target.is_symlink():raise ValueError('Ungültiger Kikiri-Bibliotheksordner.')
target.mkdir(parents=True,exist_ok=True,mode=0o700);dest=target/'model.pth'
if not dest.exists():
temp=target/'import.tmp'
try:os.link(bundle/'model.pth',temp)
except OSError:shutil.copyfile(bundle/'model.pth',temp)
temp.chmod(0o600);temp.replace(dest)
if dest.is_symlink():raise ValueError('Ungültige Kikiri-Modelldatei.')
with dest.open('rb') as f:digest=hashlib.file_digest(f,'sha256').hexdigest()
if digest!=MODEL_SHA:raise ValueError('Vorhandenes Kikiri-Modell abweichend; nicht überschrieben.')
entry=dict(repo=REPO,revision=MODEL_REVISION,file=MODEL_FILE,size=ASSETS['model.pth'][0],sha256=digest,
kind='audio',state='downloaded',runtime_ready=True,local_only=True,downloaded_at=time.time())
temp=target/'entry.tmp';temp.write_text(json.dumps(entry));temp.chmod(0o600);temp.replace(target/'entry.json')
return ident
def _run(self):
base=self.root/self.job['id'];state='failed';phase='Kikiri-CPU-Einrichtung fehlgeschlagen.'
try:
verify_assets(self.paths()[1])
base.mkdir(mode=0o700)
env={k:v for k,v in os.environ.items() if not k.startswith(('HF_','DECK_','LLAMA_','OPENAI_'))}
env.update(CUDA_VISIBLE_DEVICES='',HF_HUB_DISABLE_IMPLICIT_TOKEN='1',GIT_TERMINAL_PROMPT='0',HOME=str(base))
self._phase('Eigene gepinnte Kikiri-CPU-Umgebung erstellen · keine GPU')
self._command([sys.executable,Path(__file__).parent/'deploy/kikiri/install.py','--root',base],env)
if self.cancel.is_set():raise InterruptedError()
self.ensure_library()
(base/'ready').write_text(REVISION)
temp=self.root/'active.tmp';temp.write_text(json.dumps({'id':base.name}));temp.replace(self.root/'active.json')
state='complete';phase='Kikiri Anna CPU bereit · Endpunktfreigabe separat'
except InterruptedError:state='cancelled';phase='Kikiri-Einrichtung abgebrochen.'
except Exception as exc:phase=str(exc)
finally:
if state!='complete':shutil.rmtree(base,ignore_errors=True)
with self.lock:self.process=None;self.job.update(state=state,phase=phase,finished_at=time.time());self._save()
+90
View File
@@ -0,0 +1,90 @@
"""Offline FP32 Anna +20, narrow Vögel fix, bounded WAV/PCM protocol."""
import contextlib,json,os,re,sys,time,unicodedata,wave
from pathlib import Path
RATE=24000
MAX_PCM=32*1024**2
WORD=re.compile(r'\bvögel(?:n|chen)?\b',re.IGNORECASE)
PHONE=re.compile(r'(?<!\S)v(?=ˈøːɡəl(?:n|çən)?(?=[\s.,!?;:]|$))')
def correct(text,phonemes):
return PHONE.sub('f',phonemes) if WORD.search(unicodedata.normalize('NFC',text)) else phonemes
def generate(pipeline,voice,request,vocab,reset_seed):
import numpy as np
text=request['text']
if not isinstance(text,str) or not 1<=len(text.strip())<=1000:raise ValueError('Text mit 1–1000 Zeichen erforderlich.')
directory=Path(request['output']);cancel=directory/'cancel'
reset_seed();started=time.monotonic();first=None;total=0;count=0
# Native pipeline segmentation only: no additional sentence gaps, breath
# smoothing, pitch change or synthetic voice/reference replacement.
with wave.open(str(directory/'result.wav'),'wb') as out:
out.setnchannels(1);out.setsampwidth(2);out.setframerate(RATE)
stream=pipeline(text,voice=voice,speed=1)
try:
for result in stream:
if cancel.exists():return dict(ok=True,cancelled=True)
if not result.phonemes or len(result.phonemes)>510 or any(c not in vocab for c in result.phonemes):raise ValueError('Kikiri-Phoneme unvollständig; keine gekürzte Ausgabe.')
chunk=result.audio.detach().cpu().numpy().reshape(-1)
if not chunk.size or not np.isfinite(chunk).all():raise ValueError('Ungültige Kikiri-Audioausgabe.')
pcm=(np.clip(chunk,-1,1)*32767).astype('<i2').tobytes();total+=len(pcm)
if total>MAX_PCM:raise ValueError('Kikiri-Audio überschreitet 32 MiB.')
if first is None:first=time.monotonic()-started
out.writeframes(pcm)
if request.get('streaming'):
temp=directory/f'chunk-{count:06d}.tmp';temp.write_bytes(pcm);temp.replace(temp.with_suffix('.pcm'))
count+=1
finally:
if hasattr(stream,'close'):stream.close()
if cancel.exists():return dict(ok=True,cancelled=True)
if not total:raise ValueError('Kikiri lieferte kein Audio.')
return dict(ok=True,duration=total/2/RATE,sample_rate=RATE,seconds=time.monotonic()-started,first_chunk_seconds=first)
def load(bundle):
import random,numpy as np,torch
from kokoro import KModel,KPipeline
from kikiri_runtime import verify_assets
verify_assets(bundle)
assert torch.version.cuda is None and not torch.cuda.is_available(),'CPU-only Torch required'
torch.set_num_threads(4);torch.set_num_interop_threads(1)
def seed():random.seed(42);np.random.seed(42);torch.manual_seed(42)
seed()
model=KModel(repo_id='hexgrad/Kokoro-82M',config=str(bundle/'config.json'),model=str(bundle/'model.pth')).to('cpu').eval()
weights=torch.load(bundle/'model.pth',map_location='cpu',weights_only=True)
for name,state in weights.items():
component=getattr(model,name);state={k.removeprefix('module.'):v for k,v in state.items()}
result=component.load_state_dict(state,strict=False)
assert not result.unexpected_keys
current=component.state_dict()
for key in result.missing_keys:
path,param=key.rsplit('.',1);layer=component.get_submodule(path)
assert isinstance(layer,torch.nn.InstanceNorm1d) and layer.affine and param in ('weight','bias')
assert torch.all(current[key]==(1 if param=='weight' else 0))
state[key]=current[key]
component.load_state_dict(state,strict=True)
del weights
voice=torch.load(bundle/'voice.pt',map_location='cpu',weights_only=True)
assert voice.shape==(510,1,256) and torch.isfinite(voice).all()
pipeline=KPipeline(lang_code='d',repo_id='hexgrad/Kokoro-82M',model=model,device='cpu');g2p=pipeline.g2p
def front(text):
phones,tokens=g2p(text)
return correct(text,phones.replace('ʏ','y')),tokens
pipeline.g2p=front
# Warm the frontend and decoder before announcing readiness.
list(pipeline('Die Stimme ist bereit.',voice=voice,speed=1))
return pipeline,voice,model.vocab,seed
def main():
control=sys.stdout
try:
with contextlib.redirect_stdout(sys.stderr):
os.nice(10);pipeline,voice,vocab,seed=load(Path(sys.argv[1]))
except Exception:
print(json.dumps(dict(ready=False,error='Kikiri-CPU-Laufzeit oder Anna-Stand ungültig.')),file=control,flush=True);return
print(json.dumps(dict(ready=True,sample_rate=RATE,device='cpu')),file=control,flush=True)
for line in sys.stdin:
request=json.loads(line);directory=Path(request['output'])
try:
with contextlib.redirect_stdout(sys.stderr):result=generate(pipeline,voice,request,vocab,seed)
except Exception:result=dict(ok=False,error='Kikiri-Erzeugung fehlgeschlagen. Text, Laufzeit und Ressourcen prüfen.')
temp=directory/'result.tmp';temp.write_text(json.dumps(result));temp.replace(directory/'result.json')
if __name__=='__main__':main()
+2
View File
@@ -402,6 +402,8 @@ class Profiles:
from pocket_runtime import supported as pocket_model,COMPONENTS as POCKET_COMPONENTS from pocket_runtime import supported as pocket_model,COMPONENTS as POCKET_COMPONENTS
from parakeet_runtime import supported as redux_supported from parakeet_runtime import supported as redux_supported
from articulino_runtime import supported as articulino_model from articulino_runtime import supported as articulino_model
from kikiri_runtime import supported as kikiri_model
if kikiri_model(model):return dict(supported=True,requirements=[],no_components=True,source='https://github.com/semidark/kikiri-tts',license='Private Anna-Stimme; öffentliche Laufzeit separat',runtime='Kikiri Anna · CPU · FP32',runtime_route='#tts-runtime',runtime_installed=bool(getattr(self,'kikiri_runtime_ready',lambda:False)()),worker_available=True,message='Eigener trainierter Anna-plus20-Stand. Vier CPU-Threads, 24 kHz Mono, Vögel-Korrektur. Kein GPU-Speicher, kein Entladen von Strata. Private Gewichte separat sichern.')
if articulino_model(model):return dict(supported=True,requirements=[],no_components=True,source='https://github.com/eigenhand/articulino-onnx',license='Apache-2.0',runtime='Articulino · CPU · FP32',runtime_route='#tts-runtime',runtime_installed=bool(getattr(self,'articulino_runtime_ready',lambda:False)()),worker_available=True,message='Vollständiges gepinntes ONNX-Paket in eigener CPU-Laufzeit. Anna-Referenz wird bis acht Sekunden verwendet. Sehr schnell; die Stimmähnlichkeit ist nur eine Annäherung. Kein GPU-Speicher, kein Entladen von Strata.') if articulino_model(model):return dict(supported=True,requirements=[],no_components=True,source='https://github.com/eigenhand/articulino-onnx',license='Apache-2.0',runtime='Articulino · CPU · FP32',runtime_route='#tts-runtime',runtime_installed=bool(getattr(self,'articulino_runtime_ready',lambda:False)()),worker_available=True,message='Vollständiges gepinntes ONNX-Paket in eigener CPU-Laufzeit. Anna-Referenz wird bis acht Sekunden verwendet. Sehr schnell; die Stimmähnlichkeit ist nur eine Annäherung. Kein GPU-Speicher, kein Entladen von Strata.')
if redux_supported(model):return dict(supported=True,requirements=[],no_components=True,worker_available=True,source='https://github.com/mudler/parakeet.cpp',license='CC-BY-4.0',runtime='parakeet.cpp · CPU/AVX2',message='Gepacktes Redux-GGUF, kein separater Projektor. Gepinnte CPU-Laufzeit aus dem Vorbereitungsrezept verwenden.') if redux_supported(model):return dict(supported=True,requirements=[],no_components=True,worker_available=True,source='https://github.com/mudler/parakeet.cpp',license='CC-BY-4.0',runtime='parakeet.cpp · CPU/AVX2',message='Gepacktes Redux-GGUF, kein separater Projektor. Gepinnte CPU-Laufzeit aus dem Vorbereitungsrezept verwenden.')
from soulx_singer import soulx_singer_model from soulx_singer import soulx_singer_model
+30 -6
View File
@@ -117,10 +117,15 @@ class Server(ThreadingHTTPServer):
from articulino import Articulino from articulino import Articulino
self.articulino_runtime=ArticulinoRuntime(self.catalog.root.parent/'articulino-runtime') self.articulino_runtime=ArticulinoRuntime(self.catalog.root.parent/'articulino-runtime')
self.articulino=Articulino(self.catalog.root.parent/'articulino-jobs',self.profiles,self.articulino_runtime) self.articulino=Articulino(self.catalog.root.parent/'articulino-jobs',self.profiles,self.articulino_runtime)
from kikiri_runtime import KikiriRuntime,supported as kikiri_model
from kikiri import Kikiri
self.kikiri_runtime=KikiriRuntime(self.catalog.root.parent/'kikiri-runtime')
self.kikiri=Kikiri(self.catalog.root.parent/'kikiri-jobs',self.profiles,self.kikiri_runtime)
self.profiles.kikiri_runtime_ready=lambda:self.kikiri_runtime.status()['installed']
self.profiles.articulino_runtime_ready=lambda:self.articulino_runtime.status()['installed'] self.profiles.articulino_runtime_ready=lambda:self.articulino_runtime.status()['installed']
self.profiles.qwen_native_runtime_ready=lambda:self.qwen_native_runtime.status()['installed'] self.profiles.qwen_native_runtime_ready=lambda:self.qwen_native_runtime.status()['installed']
self.profiles.pocket_runtime_ready=lambda:self.pocket_runtime.status()['installed'] self.profiles.pocket_runtime_ready=lambda:self.pocket_runtime.status()['installed']
self.profiles.tts_blockers=lambda p:self.articulino.blockers(p) if articulino_model(p.get('model')) else self.qwen_native.blockers(p) if native_qwen_model(p.get('model')) else self.pocket.blockers(p) if pocket_model(p.get('model')) else self.tts_tests.blockers(p) self.profiles.tts_blockers=lambda p:self.kikiri.blockers(p) if kikiri_model(p.get('model')) else self.articulino.blockers(p) if articulino_model(p.get('model')) else self.qwen_native.blockers(p) if native_qwen_model(p.get('model')) else self.pocket.blockers(p) if pocket_model(p.get('model')) else self.tts_tests.blockers(p)
self.docker = DockerSupport() self.docker = DockerSupport()
self.hardware = HardwareProvider() self.hardware = HardwareProvider()
self.started = time.time() self.started = time.time()
@@ -179,6 +184,7 @@ class Server(ThreadingHTTPServer):
self.endpoint.embeddings=self.embeddings self.endpoint.embeddings=self.embeddings
self.endpoint.tts=self.tts_tests self.endpoint.tts=self.tts_tests
self.endpoint.pocket=self.pocket self.endpoint.pocket=self.pocket
self.endpoint.kikiri=self.kikiri
self.endpoint.articulino=self.articulino self.endpoint.articulino=self.articulino
self.endpoint.qwen_native=self.qwen_native self.endpoint.qwen_native=self.qwen_native
self.endpoint.voxcpm=self.voxcpm_tests self.endpoint.voxcpm=self.voxcpm_tests
@@ -228,7 +234,7 @@ class Server(ThreadingHTTPServer):
self.chat_tests=ChatTests(self.profiles,self.worker,self.scheduler) self.chat_tests=ChatTests(self.profiles,self.worker,self.scheduler)
self.auto_tests=AutoTests(self.catalog.root.parent/'auto-tests.json',self.profiles,self.worker,self.scheduler) self.auto_tests=AutoTests(self.catalog.root.parent/'auto-tests.json',self.profiles,self.worker,self.scheduler)
def stop_gpu_work(): def stop_gpu_work():
self.seedvc.stop();self.humaneness.stop();self.articulino.stop();self.qwen_native.stop();self.pocket.stop();self.strata_runtime.stop();self.remix.stop();self.voxcpm_tests.stop();self.separator_tests.stop();self.music.close();self.auto_tests.stop();self.chat_tests.stop();self.image_tests.stop();self.prompt_enhancer.stop_preview();self.tts_tests.stop();self.worker.stop() self.seedvc.stop();self.humaneness.stop();self.kikiri.stop();self.articulino.stop();self.qwen_native.stop();self.pocket.stop();self.strata_runtime.stop();self.remix.stop();self.voxcpm_tests.stop();self.separator_tests.stop();self.music.close();self.auto_tests.stop();self.chat_tests.stop();self.image_tests.stop();self.prompt_enhancer.stop_preview();self.tts_tests.stop();self.worker.stop()
from video_original import VideoRuntimes from video_original import VideoRuntimes
from ltx_original_runtime import LTXOriginalRuntime from ltx_original_runtime import LTXOriginalRuntime
from audio_cpp_runtime import AudioCppRuntime from audio_cpp_runtime import AudioCppRuntime
@@ -261,7 +267,7 @@ class Server(ThreadingHTTPServer):
if self.endpoint.config['autostart']: if self.endpoint.config['autostart']:
try:self.endpoint.start() try:self.endpoint.start()
except ValueError as exc:self.endpoint.error=str(exc) except ValueError as exc:self.endpoint.error=str(exc)
self.audio_policy=AudioPolicy(self.catalog.root.parent/'audio-policy.json',self.profiles,self.tts_tests,self.stt,self.scheduler,self.endpoint,pocket=self.pocket,qwen_native=self.qwen_native,articulino=self.articulino) self.audio_policy=AudioPolicy(self.catalog.root.parent/'audio-policy.json',self.profiles,self.tts_tests,self.stt,self.scheduler,self.endpoint,pocket=self.pocket,qwen_native=self.qwen_native,articulino=self.articulino,kikiri=self.kikiri)
self.sessions = {} self.sessions = {}
self.login_attempts = [] self.login_attempts = []
self.auth_lock = threading.Lock() self.auth_lock = threading.Lock()
@@ -485,7 +491,7 @@ class Handler(BaseHTTPRequestHandler):
else self.server.video.runtime) else self.server.video.runtime)
return {'embeddings':chat,'stt':chat,'chat':chat, return {'embeddings':chat,'stt':chat,'chat':chat,
'image':self.server.image_runtime.status().get('installed',False), 'image':self.server.image_runtime.status().get('installed',False),
'seedvc':self.server.seedvc_runtime.status()['installed'],'humaneness':self.server.humaneness_runtime.status()['installed'],'articulino':self.server.articulino_runtime.status()['installed'],'qwen_native':self.server.qwen_native_runtime.status()['installed'],'pocket':self.server.pocket_runtime.status()['installed'],'audio':self.server.tts_runtime.status().get('installed',False),'parakeet':self.server.stt.parakeet.status()['installed'], 'seedvc':self.server.seedvc_runtime.status()['installed'],'humaneness':self.server.humaneness_runtime.status()['installed'],'kikiri':self.server.kikiri_runtime.status()['installed'],'articulino':self.server.articulino_runtime.status()['installed'],'qwen_native':self.server.qwen_native_runtime.status()['installed'],'pocket':self.server.pocket_runtime.status()['installed'],'audio':self.server.tts_runtime.status().get('installed',False),'parakeet':self.server.stt.parakeet.status()['installed'],
'video':video_runtime.status().get('installed',False), 'video':video_runtime.status().get('installed',False),
'acestep':self.server.acestep_runtime.status()['installed'], 'acestep':self.server.acestep_runtime.status()['installed'],
'audio_cpp':self.server.audio_cpp_runtime.status()['installed'], 'audio_cpp':self.server.audio_cpp_runtime.status()['installed'],
@@ -542,6 +548,10 @@ class Handler(BaseHTTPRequestHandler):
except (ValueError,OSError) as exc:return self.respond({'error':str(exc)},400) except (ValueError,OSError) as exc:return self.respond({'error':str(exc)},400)
if self.path == '/api/v1/tts':return self.respond(self.server.tts_tests.status()) if self.path == '/api/v1/tts':return self.respond(self.server.tts_tests.status())
if self.path == '/api/v1/pocket':return self.respond(self.server.pocket.status()) if self.path == '/api/v1/pocket':return self.respond(self.server.pocket.status())
if self.path == '/api/v1/kikiri':return self.respond(self.server.kikiri.status())
if urlsplit(self.path).path == '/api/v1/kikiri/audio':
try:return self.respond(self.server.kikiri.audio(parse_qs(urlsplit(self.path).query).get('id',[''])[0]),mime='audio/wav')
except (ValueError,OSError) as exc:return self.respond({'error':str(exc)},400)
if self.path == '/api/v1/articulino':return self.respond(self.server.articulino.status()) if self.path == '/api/v1/articulino':return self.respond(self.server.articulino.status())
if urlsplit(self.path).path == '/api/v1/articulino/audio': if urlsplit(self.path).path == '/api/v1/articulino/audio':
try:return self.respond(self.server.articulino.audio(parse_qs(urlsplit(self.path).query).get('id',[''])[0]),mime='audio/wav') try:return self.respond(self.server.articulino.audio(parse_qs(urlsplit(self.path).query).get('id',[''])[0]),mime='audio/wav')
@@ -962,6 +972,17 @@ class Handler(BaseHTTPRequestHandler):
if self.path.endswith('/cancel') and not data:return self.respond(self.server.qwen_native.stop()) if self.path.endswith('/cancel') and not data:return self.respond(self.server.qwen_native.stop())
raise ValueError('Ungültige Qwen-CPU-Aktion.') raise ValueError('Ungültige Qwen-CPU-Aktion.')
except (ValueError,TypeError,KeyError) as exc:return self.respond({'error':str(exc)},400) except (ValueError,TypeError,KeyError) as exc:return self.respond({'error':str(exc)},400)
if self.path in ('/api/v1/kikiri/install','/api/v1/kikiri/install-cancel','/api/v1/kikiri/start','/api/v1/kikiri/cancel'):
try:
data=self.read_json()
if self.path.endswith('/install') and not data:return self.respond(self.server.kikiri_runtime.start())
if self.path.endswith('/install-cancel') and not data:return self.respond(self.server.kikiri_runtime.stop())
if self.path.endswith('/start') and set(data)=={'profile_id','text','speaker','language'}:
if self.api_token_authenticated() and not any(p['id']==data['profile_id'] and p['kind']=='audio' and p['enabled'] for p in self.server.endpoint.rows()):raise ValueError('Kikiri-Profil ist am Endpunkt nicht freigegeben.')
return self.respond(self.server.kikiri.start(**data))
if self.path.endswith('/cancel') and not data:return self.respond(self.server.kikiri.stop())
raise ValueError('Ungültige Kikiri-Aktion.')
except (ValueError,OSError) as exc:return self.respond({'error':str(exc)},400)
if self.path in ('/api/v1/articulino/install','/api/v1/articulino/install-cancel','/api/v1/articulino/start','/api/v1/articulino/cancel'): if self.path in ('/api/v1/articulino/install','/api/v1/articulino/install-cancel','/api/v1/articulino/start','/api/v1/articulino/cancel'):
try: try:
data=self.read_json() data=self.read_json()
@@ -1043,7 +1064,9 @@ class Handler(BaseHTTPRequestHandler):
if self.path == '/api/v1/profiles/delete': if self.path == '/api/v1/profiles/delete':
try: try:
data=self.read_json() data=self.read_json()
with self.server.image_tests.lock, self.server.tts_tests.lock, self.server.stt.lock, self.server.voxcpm_tests.lock, self.server.pocket.lock, self.server.qwen_native.lock, self.server.articulino.lock: with self.server.image_tests.lock, self.server.tts_tests.lock, self.server.stt.lock, self.server.voxcpm_tests.lock, self.server.pocket.lock, self.server.qwen_native.lock, self.server.articulino.lock, self.server.kikiri.lock:
kikiri_job=self.server.kikiri.job
if kikiri_job and kikiri_job.get('state')=='running' and kikiri_job.get('profile_id')==data.get('id'):raise ValueError('Kikiri-Profil wird gerade ausgeführt. Zuerst Auftrag beenden.')
art_job=self.server.articulino.job art_job=self.server.articulino.job
if art_job and art_job.get('state')=='running' and art_job.get('profile_id')==data.get('id'):raise ValueError('Articulino-Profil wird gerade ausgeführt. Zuerst Auftrag beenden.') if art_job and art_job.get('state')=='running' and art_job.get('profile_id')==data.get('id'):raise ValueError('Articulino-Profil wird gerade ausgeführt. Zuerst Auftrag beenden.')
native_job=self.server.qwen_native.job native_job=self.server.qwen_native.job
@@ -1059,6 +1082,7 @@ class Handler(BaseHTTPRequestHandler):
job=self.server.image_tests.job job=self.server.image_tests.job
if job and job.get('state')=='running' and job.get('profile_id')==data.get('id'):raise ValueError('Dieses Profil wird gerade ausgeführt. Zuerst den Auftrag beenden.') if job and job.get('state')=='running' and job.get('profile_id')==data.get('id'):raise ValueError('Dieses Profil wird gerade ausgeführt. Zuerst den Auftrag beenden.')
result=self.server.profiles.delete(data) result=self.server.profiles.delete(data)
if self.server.kikiri.profile_id==data.get('id'):self.server.kikiri.stop()
if self.server.articulino.profile_id==data.get('id'):self.server.articulino.stop() if self.server.articulino.profile_id==data.get('id'):self.server.articulino.stop()
if self.server.pocket.profile_id==data.get('id'):self.server.pocket.stop() if self.server.pocket.profile_id==data.get('id'):self.server.pocket.stop()
if self.server.qwen_native.profile_id==data.get('id'):self.server.qwen_native.stop() if self.server.qwen_native.profile_id==data.get('id'):self.server.qwen_native.stop()
@@ -1141,7 +1165,7 @@ def main():
server.video.close() server.video.close()
server.endpoint.close() server.endpoint.close()
server.stt.stop() server.stt.stop()
server.soulx_singer.stop();server.soulx_singer_runtime.stop();server.applio.stop();server.applio_runtime.stop();server.voxcpm_tests.stop();server.tts_tests.stop();server.articulino.stop();server.articulino_runtime.stop();server.qwen_native.stop();server.qwen_native_runtime.stop();server.pocket.stop();server.pocket_runtime.stop() server.soulx_singer.stop();server.soulx_singer_runtime.stop();server.applio.stop();server.applio_runtime.stop();server.voxcpm_tests.stop();server.tts_tests.stop();server.kikiri.stop();server.kikiri_runtime.stop();server.articulino.stop();server.articulino_runtime.stop();server.qwen_native.stop();server.qwen_native_runtime.stop();server.pocket.stop();server.pocket_runtime.stop()
server.tts_runtime.stop();server.voxcpm_runtime.stop();server.omnivoice_runtime.stop() server.tts_runtime.stop();server.voxcpm_runtime.stop();server.omnivoice_runtime.stop()
server.image_runtime.stop() server.image_runtime.stop()
server.ltx_original_runtime.stop() server.ltx_original_runtime.stop()
+97
View File
@@ -0,0 +1,97 @@
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()
+1 -1
View File
@@ -39,7 +39,7 @@ class ManagementTests(unittest.TestCase):
req.update(id=saved['id'],revision=1) req.update(id=saved['id'],revision=1)
self.profiles.save(req) self.profiles.save(req)
restarted=Profiles(self.root/'profiles.json',self.catalog) restarted=Profiles(self.root/'profiles.json',self.catalog)
self.assertEqual(restarted.status()['profiles'][0]['parameters'],dict(params,reasoning_budget={'enabled':False,'limits':{'low':None,'medium':None,'high':None}},chat_runtime='llama',strata_layer_split=16,strata_experts='resident',load_mode='none',min_p=0.0,repeat_penalty=1.0,presence_penalty=0.0,frequency_penalty=0.0,mtp=False,mtp_tokens=2,mtp_min_p=.05,gpu_offload='auto',gpu_reserve_mode='auto',gpu_reserve_mib={},vision_projector=None,vision_device='cpu',cache_type_k='q4_0',cache_type_v='q4_0')) self.assertEqual(restarted.status()['profiles'][0]['parameters'],dict(params,reasoning_budget={'enabled':False,'limits':{'low':None,'medium':None,'high':None}},chat_runtime='llama',strata_layer_split=16,strata_experts='resident',strata_batch_groups='1',strata_batch_mtp=True,load_mode='none',min_p=0.0,repeat_penalty=1.0,presence_penalty=0.0,frequency_penalty=0.0,mtp=False,mtp_tokens=2,mtp_min_p=.05,gpu_offload='auto',gpu_reserve_mode='auto',gpu_reserve_mib={},vision_projector=None,vision_device='cpu',cache_type_k='q4_0',cache_type_v='q4_0'))
for change in [dict(gpu_offload='unknown'),dict(mtp='yes'),dict(mtp_tokens=0),dict(mtp_tokens=True),dict(mtp_min_p=1.1),dict(gpu_devices=devices*2),dict(tensor_split=[85]),dict(split_mode='none'),dict(top_p=1.1),dict(temperature=float('nan')),dict(top_k=True),dict(tensor_split=[0,100]),dict(gpu_devices=['CUDA0','CUDA1'])]: for change in [dict(gpu_offload='unknown'),dict(mtp='yes'),dict(mtp_tokens=0),dict(mtp_tokens=True),dict(mtp_min_p=1.1),dict(gpu_devices=devices*2),dict(tensor_split=[85]),dict(split_mode='none'),dict(top_p=1.1),dict(temperature=float('nan')),dict(top_k=True),dict(tensor_split=[0,100]),dict(gpu_devices=['CUDA0','CUDA1'])]:
with self.subTest(change=change),self.assertRaises(ValueError):self.profiles.save(dict(req,revision=2,parameters=dict(params,**change))) with self.subTest(change=change),self.assertRaises(ValueError):self.profiles.save(dict(req,revision=2,parameters=dict(params,**change)))
+4 -2
View File
@@ -1,13 +1,13 @@
window.TTSUI=(()=>{ window.TTSUI=(()=>{
const e=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c])); const e=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
async function api(path='',data){const r=await fetch('/api/v1/'+path,(data===undefined)?{}:{method:'POST',headers:{'Content-Type':'application/json','X-Athena-Deck':'1'},body:JSON.stringify(data)});const x=await r.json();if(!r.ok)throw Error(x.error||'TTS-Anfrage fehlgeschlagen');return x;} async function api(path='',data){const r=await fetch('/api/v1/'+path,(data===undefined)?{}:{method:'POST',headers:{'Content-Type':'application/json','X-Athena-Deck':'1'},body:JSON.stringify(data)});const x=await r.json();if(!r.ok)throw Error(x.error||'TTS-Anfrage fehlgeschlagen');return x;}
function html(setup=false){return `<section id="tts-panel" class="card"><h2>${setup?'TTS einrichten':'Sprache ausprobieren'}</h2><p id="tts-status" role="status"></p><p id="tts-error" role="alert"></p>${setup?'<h3>Articulino · Anna · CPU</h3><p>Sehr schnelle lokale Sprachausgabe mit Anna-Referenz, 24 kHz Mono. Stimmähnlichkeit nur näherungsweise. Eigene CPU-Umgebung und rund 537 MB öffentliche FP32-Modelle; keine GPU-Reservierung. Profil am API-Endpunkt separat freigeben.</p><button id="articulino-install">Articulino-CPU-Laufzeit installieren</button><button id="articulino-install-cancel" class="secondary">Abbrechen</button><p id="articulino-status" role="status"></p><h3>Qwen3-TTS 0.6B Q8/Q4 · CPU</h3><p>Native CPU-Laufzeit mit gespeicherter Anna-Referenz, ohne GPU-Speicher. Benötigt Talker und Q8-Sprach-Codec als Bibliotheksdateien. Vier Generierungs-/vier Decoder-Threads, 160-ms-Blöcke. Die Installation lädt keine Gewichte oder privaten Stimmen.</p><button id="qwen-native-install">Native Qwen-CPU-Laufzeit installieren</button><button id="qwen-native-install-cancel" class="secondary">Abbrechen</button><p id="qwen-native-status" role="status"></p><h3>Pocket TTS · CPU</h3><p>Deutsch mit gespeicherter Anna-Stimme, ohne GPU-Speicher. Die Laufzeitinstallation lädt keine Modelle oder privaten Stimmen.</p><button id="pocket-install">Pocket-CPU-Laufzeit installieren</button><button id="pocket-install-cancel" class="secondary">Abbrechen</button><p id="pocket-status" role="status"></p><h3>Qwen3-TTS · GPU</h3><p>Die Einrichtung installiert eine eigene CUDA-Laufzeit und das offizielle Qwen3-TTS 1.7B Base mit den Preset-Stimmen des bisherigen Routers. Dafür werden mehrere GB heruntergeladen. MLX-Dateien sind für Apple-Geräte; vorhandene Dateien werden nicht gelöscht.</p><button id="tts-install">TTS-Laufzeit und Modell einrichten</button><button class="secondary" id="tts-install-cancel">Einrichtung abbrechen</button><h3>Vorhandenes TTS-Profil verbinden</h3><p>Ersetzt im ausgewählten Profil die Modellzuordnung durch die eingerichtete CUDA-Variante. Der Profilname bleibt erhalten.</p><select id="tts-profile"></select><button id="tts-assign">CUDA-Modell diesem Profil zuordnen</button><h3>Textaufbereitung am API-Endpunkt</h3><label><input id="tts-enhancer" type="checkbox"> Deutschen Text vor dem Vorlesen aufbereiten</label><p>Gemeinsam für alle am Endpunkt freigegebenen TTS-Profile. Experimentell: entfernt Markdown und spricht ausgewählte Zeichen und Abkürzungen aus; verhindert keine Modellschleifen oder Auslassungen. Andere explizite Sprachen bleiben unverändert. Gilt für API-Aufrufe, nicht für das direkte Testformular.</p><p id="tts-enhancer-state" role="status"></p><h3>Speicherverhalten</h3><p>Automatisch lädt das einzige am Endpunkt freigegebene TTS-Profil im LLM-Betrieb vor und hält es bereit: Qwen 1.7B auf der RTX 3060, natives Qwen Q8/Q4, Articulino und Pocket auf der CPU. Immer bereit lädt das gewählte Profil im LLM-Betrieb vor, soweit Ressourcen frei sind. Nach jeder Anfrage entladen gibt Speicher sofort frei.</p><label>Verhalten<select id="tts-policy"><option value="auto">Automatisch · TTS vom Endpunkt</option><option value="warm">Immer bereit</option><option value="per_request">Nach jeder Anfrage entladen</option></select></label><label>Profil für „Immer bereit“<select id="tts-warm-profile"></select></label><button id="tts-policy-save">Speicherverhalten speichern</button><p id="tts-policy-state" role="status"></p>':'<form id="tts-form"><label>Profil<select id="tts-profile" required></select></label><div class="form-grid"><label>Stimme<select id="tts-speaker"></select></label><label>Sprache<select id="tts-language"></select></label></div><label>Text<textarea id="tts-text" rows="5" maxlength="1000" required placeholder="Was soll vorgelesen werden?"></textarea></label><button id="tts-generate">Sprache erzeugen</button><button type="button" id="tts-cancel" class="secondary">Abbrechen</button></form><div id="tts-result"></div><p id="tts-device-note">Qwen 1.7B nutzt die RTX 3060; natives Qwen Q8/Q4, Articulino und Pocket nutzen die CPU. Andere Deck-Modellaufträge werden koordiniert; fremde Dienste werden nicht gestoppt. Text wird nicht dauerhaft gespeichert. Ergebnisdateien bleiben auf Athena.</p>'}</section>`;} function html(setup=false){return `<section id="tts-panel" class="card"><h2>${setup?'TTS einrichten':'Sprache ausprobieren'}</h2><p id="tts-status" role="status"></p><p id="tts-error" role="alert"></p>${setup?'<h3>Kikiri · trainierte Anna · CPU</h3><p>Der ausgewählte Anna-plus20-Stand, 24 kHz Mono und vier CPU-Threads. Kein GPU-Speicher. Private Stimme zuerst importieren oder aus verschlüsselter Sicherung wiederherstellen. Endpunktfreigabe separat.</p><button id="kikiri-install">Kikiri-CPU-Laufzeit installieren</button><button id="kikiri-install-cancel" class="secondary">Abbrechen</button><p id="kikiri-status" role="status"></p><h3>Articulino · Anna · CPU</h3><p>Sehr schnelle lokale Sprachausgabe mit Anna-Referenz, 24 kHz Mono. Stimmähnlichkeit nur näherungsweise. Eigene CPU-Umgebung und rund 537 MB öffentliche FP32-Modelle; keine GPU-Reservierung. Profil am API-Endpunkt separat freigeben.</p><button id="articulino-install">Articulino-CPU-Laufzeit installieren</button><button id="articulino-install-cancel" class="secondary">Abbrechen</button><p id="articulino-status" role="status"></p><h3>Qwen3-TTS 0.6B Q8/Q4 · CPU</h3><p>Native CPU-Laufzeit mit gespeicherter Anna-Referenz, ohne GPU-Speicher. Benötigt Talker und Q8-Sprach-Codec als Bibliotheksdateien. Vier Generierungs-/vier Decoder-Threads, 160-ms-Blöcke. Die Installation lädt keine Gewichte oder privaten Stimmen.</p><button id="qwen-native-install">Native Qwen-CPU-Laufzeit installieren</button><button id="qwen-native-install-cancel" class="secondary">Abbrechen</button><p id="qwen-native-status" role="status"></p><h3>Pocket TTS · CPU</h3><p>Deutsch mit gespeicherter Anna-Stimme, ohne GPU-Speicher. Die Laufzeitinstallation lädt keine Modelle oder privaten Stimmen.</p><button id="pocket-install">Pocket-CPU-Laufzeit installieren</button><button id="pocket-install-cancel" class="secondary">Abbrechen</button><p id="pocket-status" role="status"></p><h3>Qwen3-TTS · GPU</h3><p>Die Einrichtung installiert eine eigene CUDA-Laufzeit und das offizielle Qwen3-TTS 1.7B Base mit den Preset-Stimmen des bisherigen Routers. Dafür werden mehrere GB heruntergeladen. MLX-Dateien sind für Apple-Geräte; vorhandene Dateien werden nicht gelöscht.</p><button id="tts-install">TTS-Laufzeit und Modell einrichten</button><button class="secondary" id="tts-install-cancel">Einrichtung abbrechen</button><h3>Vorhandenes TTS-Profil verbinden</h3><p>Ersetzt im ausgewählten Profil die Modellzuordnung durch die eingerichtete CUDA-Variante. Der Profilname bleibt erhalten.</p><select id="tts-profile"></select><button id="tts-assign">CUDA-Modell diesem Profil zuordnen</button><h3>Textaufbereitung am API-Endpunkt</h3><label><input id="tts-enhancer" type="checkbox"> Deutschen Text vor dem Vorlesen aufbereiten</label><p>Gemeinsam für alle am Endpunkt freigegebenen TTS-Profile. Experimentell: entfernt Markdown und spricht ausgewählte Zeichen und Abkürzungen aus; verhindert keine Modellschleifen oder Auslassungen. Andere explizite Sprachen bleiben unverändert. Gilt für API-Aufrufe, nicht für das direkte Testformular.</p><p id="tts-enhancer-state" role="status"></p><h3>Speicherverhalten</h3><p>Automatisch lädt das einzige am Endpunkt freigegebene TTS-Profil im LLM-Betrieb vor und hält es bereit: Qwen 1.7B auf der RTX 3060, natives Qwen Q8/Q4, Kikiri, Articulino und Pocket auf der CPU. Immer bereit lädt das gewählte Profil im LLM-Betrieb vor, soweit Ressourcen frei sind. Nach jeder Anfrage entladen gibt Speicher sofort frei.</p><label>Verhalten<select id="tts-policy"><option value="auto">Automatisch · TTS vom Endpunkt</option><option value="warm">Immer bereit</option><option value="per_request">Nach jeder Anfrage entladen</option></select></label><label>Profil für „Immer bereit“<select id="tts-warm-profile"></select></label><button id="tts-policy-save">Speicherverhalten speichern</button><p id="tts-policy-state" role="status"></p>':'<form id="tts-form"><label>Profil<select id="tts-profile" required></select></label><div class="form-grid"><label>Stimme<select id="tts-speaker"></select></label><label>Sprache<select id="tts-language"></select></label></div><label>Text<textarea id="tts-text" rows="5" maxlength="1000" required placeholder="Was soll vorgelesen werden?"></textarea></label><button id="tts-generate">Sprache erzeugen</button><button type="button" id="tts-cancel" class="secondary">Abbrechen</button></form><div id="tts-result"></div><p id="tts-device-note">Qwen 1.7B nutzt die RTX 3060; natives Qwen Q8/Q4, Kikiri, Articulino und Pocket nutzen die CPU. Andere Deck-Modellaufträge werden koordiniert; fremde Dienste werden nicht gestoppt. Text wird nicht dauerhaft gespeichert. Ergebnisdateien bleiben auf Athena.</p>'}</section>`;}
function bind(setup=false){const root=document.querySelector('#tts-panel');if(!root)return;const el=id=>root.querySelector('#'+id);let state,profiles=[],busy=false,lastResult='',backend='tts';const error=x=>{if(root.isConnected)el('tts-error').textContent=x;}; function bind(setup=false){const root=document.querySelector('#tts-panel');if(!root)return;const el=id=>root.querySelector('#'+id);let state,profiles=[],busy=false,lastResult='',backend='tts';const error=x=>{if(root.isConnected)el('tts-error').textContent=x;};
async function refresh(){try{state=await api(setup?'tts':backend);if(!root.isConnected)return;const rt=state.runtime,j=state.job;el('tts-status').textContent=setup?(rt.job?.phase||(rt.installed?'TTS ist eingerichtet.':'Noch nicht eingerichtet.')):(j?.phase||'Profil wählen und Text eingeben.')+` · ${backend!=='tts'?'CPU':'RTX 3060'} ${state.loaded?'geladen':'nicht geladen'}`; async function refresh(){try{state=await api(setup?'tts':backend);if(!root.isConnected)return;const rt=state.runtime,j=state.job;el('tts-status').textContent=setup?(rt.job?.phase||(rt.installed?'TTS ist eingerichtet.':'Noch nicht eingerichtet.')):(j?.phase||'Profil wählen und Text eingeben.')+` · ${backend!=='tts'?'CPU':'RTX 3060'} ${state.loaded?'geladen':'nicht geladen'}`;
if(setup){el('tts-install').disabled=busy||rt.installed||rt.job?.state==='running';el('tts-install-cancel').disabled=rt.job?.state!=='running';el('tts-assign').disabled=busy||!rt.installed||!profiles.length;} if(setup){el('tts-install').disabled=busy||rt.installed||rt.job?.state==='running';el('tts-install-cancel').disabled=rt.job?.state!=='running';el('tts-assign').disabled=busy||!rt.installed||!profiles.length;}
else{el('tts-generate').disabled=busy||j?.state==='running'||!profiles.length||!rt.installed;el('tts-cancel').disabled=j?.state!=='running';if(j?.state==='complete'&&lastResult!==j.id){lastResult=j.id;el('tts-result').innerHTML=`<h3>Ergebnis</h3><audio controls src="/api/v1/${backend}/audio?id=${e(j.id)}"></audio><p><a class="link" download="athena-sprache.wav" href="/api/v1/${backend}/audio?id=${e(j.id)}">WAV herunterladen</a></p>`;}} else{el('tts-generate').disabled=busy||j?.state==='running'||!profiles.length||!rt.installed;el('tts-cancel').disabled=j?.state!=='running';if(j?.state==='complete'&&lastResult!==j.id){lastResult=j.id;el('tts-result').innerHTML=`<h3>Ergebnis</h3><audio controls src="/api/v1/${backend}/audio?id=${e(j.id)}"></audio><p><a class="link" download="athena-sprache.wav" href="/api/v1/${backend}/audio?id=${e(j.id)}">WAV herunterladen</a></p>`;}}
}catch(err){error(err.message);}finally{if(root.isConnected)setTimeout(refresh,2000);}} }catch(err){error(err.message);}finally{if(root.isConnected)setTimeout(refresh,2000);}}
async function load(){const p=await api('profiles');if(!root.isConnected)return;profiles=p.profiles.filter(p=>p.kind==='audio'&&(setup||p.runnable));el('tts-profile').innerHTML=profiles.map(p=>`<option value="${e(p.id)}">${e(p.name)}</option>`).join('')||'<option value="">Zuerst ein TTS-Profil anlegen und unter Einrichten verbinden</option>';if(!setup){el('tts-profile').onchange=async()=>{const selectedModel=profiles.find(p=>p.id===el('tts-profile').value)?.model;backend=selectedModel?.repo==='eigenhand/Articulino-DE-EN-Realtime-Stream-TTS-ONNX'?'articulino':selectedModel?.repo==='kyutai/pocket-tts'?'pocket':selectedModel?.repo==='Serveurperso/Qwen3-TTS-GGUF'&&['qwen-talker-0.6b-base-Q8_0.gguf','qwen-talker-0.6b-base-Q4_K_M.gguf'].includes(selectedModel?.file)?'qwen-native':'tts';lastResult='';try{const s=await api(backend);if(!root.isConnected)return;el('tts-speaker').innerHTML=s.runtime.speakers.map(v=>`<option ${v==='Ryan'?'selected':''}>${e(v)}</option>`).join('');el('tts-language').innerHTML=s.runtime.languages.map(v=>`<option ${v==='German'?'selected':''}>${e(v)}</option>`).join('');}catch(x){error(x.message);}};await el('tts-profile').onchange();}} async function load(){const p=await api('profiles');if(!root.isConnected)return;profiles=p.profiles.filter(p=>p.kind==='audio'&&(setup||p.runnable));el('tts-profile').innerHTML=profiles.map(p=>`<option value="${e(p.id)}">${e(p.name)}</option>`).join('')||'<option value="">Zuerst ein TTS-Profil anlegen und unter Einrichten verbinden</option>';if(!setup){el('tts-profile').onchange=async()=>{const selectedModel=profiles.find(p=>p.id===el('tts-profile').value)?.model;backend=selectedModel?.repo==='local/kikiri-anna'?'kikiri':selectedModel?.repo==='eigenhand/Articulino-DE-EN-Realtime-Stream-TTS-ONNX'?'articulino':selectedModel?.repo==='kyutai/pocket-tts'?'pocket':selectedModel?.repo==='Serveurperso/Qwen3-TTS-GGUF'&&['qwen-talker-0.6b-base-Q8_0.gguf','qwen-talker-0.6b-base-Q4_K_M.gguf'].includes(selectedModel?.file)?'qwen-native':'tts';lastResult='';try{const s=await api(backend);if(!root.isConnected)return;el('tts-speaker').innerHTML=s.runtime.speakers.map(v=>`<option ${v==='Ryan'?'selected':''}>${e(v)}</option>`).join('');el('tts-language').innerHTML=s.runtime.languages.map(v=>`<option ${v==='German'?'selected':''}>${e(v)}</option>`).join('');}catch(x){error(x.message);}};await el('tts-profile').onchange();}}
async function action(path,data={}){busy=true;error('');try{await api((setup?'tts':backend)+'/'+path,data);if(path==='assign'){await load();error('Profil verbunden. Jetzt den Reiter Testen öffnen.');}}catch(err){error(err.message);}finally{busy=false;}} async function action(path,data={}){busy=true;error('');try{await api((setup?'tts':backend)+'/'+path,data);if(path==='assign'){await load();error('Profil verbunden. Jetzt den Reiter Testen öffnen.');}}catch(err){error(err.message);}finally{busy=false;}}
if(setup){el('tts-install').onclick=()=>action('install');el('tts-install-cancel').onclick=()=>action('install-cancel');el('tts-assign').onclick=()=>{const p=profiles.find(p=>p.id===el('tts-profile').value);if(p)action('assign',{id:p.id,revision:p.revision});};} if(setup){el('tts-install').onclick=()=>action('install');el('tts-install-cancel').onclick=()=>action('install-cancel');el('tts-assign').onclick=()=>{const p=profiles.find(p=>p.id===el('tts-profile').value);if(p)action('assign',{id:p.id,revision:p.revision});};}
else{el('tts-form').onsubmit=ev=>{ev.preventDefault();action('start',{profile_id:el('tts-profile').value,text:el('tts-text').value,speaker:el('tts-speaker').value,language:el('tts-language').value});};el('tts-cancel').onclick=()=>action('cancel');} else{el('tts-form').onsubmit=ev=>{ev.preventDefault();action('start',{profile_id:el('tts-profile').value,text:el('tts-text').value,speaker:el('tts-speaker').value,language:el('tts-language').value});};el('tts-cancel').onclick=()=>action('cancel');}
@@ -15,6 +15,8 @@ window.TTSUI=(()=>{
const enhancer=el('tts-enhancer'),enhancerState=el('tts-enhancer-state');enhancer.disabled=true; const enhancer=el('tts-enhancer'),enhancerState=el('tts-enhancer-state');enhancer.disabled=true;
api('endpoint').then(s=>{if(root.isConnected){enhancer.checked=!!s.tts_text_enhancer;enhancer.disabled=false;}}).catch(x=>{if(root.isConnected)enhancerState.textContent=x.message;}); api('endpoint').then(s=>{if(root.isConnected){enhancer.checked=!!s.tts_text_enhancer;enhancer.disabled=false;}}).catch(x=>{if(root.isConnected)enhancerState.textContent=x.message;});
enhancer.onchange=async()=>{enhancer.disabled=true;try{const s=await api('endpoint/config',{tts_text_enhancer:enhancer.checked});enhancer.checked=!!s.tts_text_enhancer;enhancerState.textContent='Gespeichert. Gilt ab der nächsten TTS-API-Anfrage.';}catch(x){enhancer.checked=!enhancer.checked;enhancerState.textContent=x.message;}finally{enhancer.disabled=false;}}; enhancer.onchange=async()=>{enhancer.disabled=true;try{const s=await api('endpoint/config',{tts_text_enhancer:enhancer.checked});enhancer.checked=!!s.tts_text_enhancer;enhancerState.textContent='Gespeichert. Gilt ab der nächsten TTS-API-Anfrage.';}catch(x){enhancer.checked=!enhancer.checked;enhancerState.textContent=x.message;}finally{enhancer.disabled=false;}};
async function kikiriStatus(){try{const d=await api('kikiri'),rt=d.runtime;el('kikiri-status').textContent=rt.job?.phase||(rt.installed?'Kikiri Anna CPU bereit.':!rt.voice_installed?'Privater Anna-plus20-Stand muss zuerst importiert/wiederhergestellt werden.':'CPU-Laufzeit noch nicht installiert.');el('kikiri-install').disabled=rt.environment_installed||!rt.voice_installed||rt.job?.state==='running';el('kikiri-install-cancel').disabled=rt.job?.state!=='running';}catch(x){error(x.message);}finally{if(root.isConnected)setTimeout(kikiriStatus,2000);}}
el('kikiri-install').onclick=()=>api('kikiri/install',{}).catch(x=>error(x.message));el('kikiri-install-cancel').onclick=()=>api('kikiri/install-cancel',{}).catch(x=>error(x.message));kikiriStatus();
async function articulinoStatus(){try{const d=await api('articulino'),rt=d.runtime;el('articulino-status').textContent=rt.job?.phase||(rt.installed?'Articulino-CPU-Laufzeit bereit.':'Noch nicht installiert.');el('articulino-install').disabled=rt.installed||rt.job?.state==='running';el('articulino-install-cancel').disabled=rt.job?.state!=='running';}catch(x){error(x.message);}finally{if(root.isConnected)setTimeout(articulinoStatus,2000);}} async function articulinoStatus(){try{const d=await api('articulino'),rt=d.runtime;el('articulino-status').textContent=rt.job?.phase||(rt.installed?'Articulino-CPU-Laufzeit bereit.':'Noch nicht installiert.');el('articulino-install').disabled=rt.installed||rt.job?.state==='running';el('articulino-install-cancel').disabled=rt.job?.state!=='running';}catch(x){error(x.message);}finally{if(root.isConnected)setTimeout(articulinoStatus,2000);}}
el('articulino-install').onclick=()=>api('articulino/install',{}).catch(x=>error(x.message));el('articulino-install-cancel').onclick=()=>api('articulino/install-cancel',{}).catch(x=>error(x.message));articulinoStatus(); el('articulino-install').onclick=()=>api('articulino/install',{}).catch(x=>error(x.message));el('articulino-install-cancel').onclick=()=>api('articulino/install-cancel',{}).catch(x=>error(x.message));articulinoStatus();
async function nativeStatus(){try{const d=await api('qwen-native'),rt=d.runtime;el('qwen-native-status').textContent=rt.job?.phase||(rt.installed?'Native Qwen-CPU-Laufzeit bereit.':'Noch nicht installiert.');el('qwen-native-install').disabled=rt.installed||rt.job?.state==='running';el('qwen-native-install-cancel').disabled=rt.job?.state!=='running';}catch(x){error(x.message);}finally{if(root.isConnected)setTimeout(nativeStatus,2000);}} async function nativeStatus(){try{const d=await api('qwen-native'),rt=d.runtime;el('qwen-native-status').textContent=rt.job?.phase||(rt.installed?'Native Qwen-CPU-Laufzeit bereit.':'Noch nicht installiert.');el('qwen-native-install').disabled=rt.installed||rt.job?.state==='running';el('qwen-native-install-cancel').disabled=rt.job?.state!=='running';}catch(x){error(x.message);}finally{if(root.isConnected)setTimeout(nativeStatus,2000);}}