diff --git a/articulino.py b/articulino.py new file mode 100644 index 0000000..a29923c --- /dev/null +++ b/articulino.py @@ -0,0 +1,39 @@ +"""Independent CPU TTS worker; no GPU reservation or chat-model eviction.""" +import json,os,select,subprocess +from pathlib import Path +from qwen_native import QwenNative +from articulino_runtime import supported +import cpu_partition + +class Articulino(QwenNative): + name='Articulino' + def blockers(self,p): + if not supported(p.get('model')):return ['Nur das gepinnte Articulino-FP32-Rezept ist qualifiziert.'] + errors=[] + if not self.runtime.status()['installed']:errors.append('Articulino unter TTS → Einrichten installieren.') + try:self.voice_path('default') + except ValueError as exc:errors.append(str(exc)) + 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('Articulino-Profil ist nicht ausführbar.') + if p['parameters'].get('speed',1)!=1:raise ValueError('Articulino benötigt im Profil speed=1.') + return p + def _ensure_cpu(self,p): + python,model=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 + headroom=cgroup_headroom() + if headroom is not None and headroom<1536*1024**2:raise ValueError('Articulino benötigt mindestens 1,5 GiB freien Deck-RAM; laufende Modelle bleiben erhalten.') + self.unload_idle();self.root.mkdir(parents=True,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',OPENBLAS_NUM_THREADS='1',HOME=str(self.root)) + argv=[str(python),str(Path(__file__).with_name('articulino_worker.py')),str(model)] + 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],[],[],45)[0]:self.unload_idle();raise ValueError('Zeitlimit beim Laden von Articulino.') + try:ready=json.loads(process.stdout.readline()) + except ValueError:ready={} + if not ready.get('ready'):self.unload_idle();raise ValueError('Articulino-CPU-Worker konnte nicht starten.') + self.session_key=key;return process diff --git a/articulino_runtime.py b/articulino_runtime.py new file mode 100644 index 0000000..8fa14dd --- /dev/null +++ b/articulino_runtime.py @@ -0,0 +1,77 @@ +"""Pinned CPU-only Articulino runtime and complete, checksum-verified model bundle.""" +import hashlib,json,os,shutil,sys,time +from pathlib import Path +from ltx_original_runtime import LTXOriginalRuntime + +VERSION='1.0.0' +REVISION='143d6dd5bbd67a02564be30f15bd8a578dda4987' +REPO='eigenhand/Articulino-DE-EN-Realtime-Stream-TTS-ONNX' +MODEL_REVISION='a760ce8d513534111c7679751869fa4c45ef0e54' +MODEL_FILE='fp32/dit_step.onnx' +ASSETS=Path(__file__).parent/'deploy/articulino/assets.json' + +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) + +def verify_assets(directory): + for item in json.loads(ASSETS.read_text()): + path=Path(directory)/item['file'] + if path.is_symlink() or not path.is_file() or path.stat().st_size!=item['bytes']:raise ValueError('Articulino-Datei fehlt oder ist unvollständig: '+item['file']) + with path.open('rb') as f:digest=hashlib.file_digest(f,'sha256').hexdigest() + if digest!=item['sha256']:raise ValueError('Articulino-Prüfsumme abweichend: '+item['file']) + +class ArticulinoRuntime(LTXOriginalRuntime): + name='Articulino · CPU' + def __init__(self,root):super().__init__(root,None) + def paths(self): + 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+':'+MODEL_REVISION:return base/'python/bin/python',base/'model' + except (OSError,ValueError,KeyError,TypeError):pass + return self.root/'missing-python',self.root/'missing-model' + def status(self): + python,model=self.paths() + files=json.loads(ASSETS.read_text()) + installed=python.is_file() and all((model/x['file']).is_file() and (model/x['file']).stat().st_size==x['bytes'] for x in files) + return dict(installed=installed,revision=REVISION,model_revision=MODEL_REVISION,version=VERSION,device='cpu',required_disk_gib=2,job=dict(self.job) if self.job else None,speakers=['default','Anna'],languages=['German'],origin='https://github.com/eigenhand/articulino-onnx') + def ensure_library(self): + if not self.status()['installed']:raise ValueError('Articulino zuerst installieren.') + _,model=self.paths();source=model/MODEL_FILE + expected=next(x for x in json.loads(ASSETS.read_text()) if x['file']==MODEL_FILE) + ident=hashlib.sha256((REPO+MODEL_REVISION+MODEL_FILE).encode()).hexdigest() + target=self.root.parent/'models'/ident;target.mkdir(parents=True,exist_ok=True,mode=0o700);dest=target/'model.onnx' + if not dest.exists(): + temp=target/'import.tmp' + try:os.link(source,temp) + except OSError:shutil.copyfile(source,temp) + temp.chmod(0o600);temp.replace(dest) + with dest.open('rb') as f:digest=hashlib.file_digest(f,'sha256').hexdigest() + if digest!=expected['sha256']:raise ValueError('Vorhandene Articulino-Bibliotheksdatei weicht ab; nicht überschrieben.') + entry=dict(repo=REPO,revision=MODEL_REVISION,file=MODEL_FILE,size=expected['bytes'],sha256=digest,kind='audio',upstream_hash_verified=True,downloaded_at=time.time(),state='downloaded',runtime_ready=True) + 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='Articulino-Einrichtung fehlgeschlagen.' + try: + base.mkdir(mode=0o700) + env={k:v for k,v in os.environ.items() if not k.startswith(('HF_','DECK_','LLAMA_','OPENAI_'))} + env.update(PIP_NO_INPUT='1',PIP_DISABLE_PIP_VERSION_CHECK='1',CUDA_VISIBLE_DEVICES='',HF_HUB_DISABLE_IMPLICIT_TOKEN='1') + self._phase('Eigene Articulino-CPU-Umgebung erstellen');self._command([sys.executable,'-m','venv',base/'python'],env) + python=base/'python/bin/python' + self._phase('Gepinnte ONNX-CPU-Laufzeit installieren · kein PyTorch oder CUDA') + self._command([python,'-m','pip','install','--no-cache-dir','-r',Path(__file__).parent/'deploy/articulino/requirements.lock'],env) + self._command([python,'-m','pip','check'],env) + self._command([python,'-c','import onnxruntime;from articulino_onnx import TTS;assert "CPUExecutionProvider" in onnxruntime.get_available_providers()'],env) + self._phase('Öffentliche FP32-Modelldateien laden und SHA256 prüfen · 537 MB') + self._command([sys.executable,Path(__file__).parent/'deploy/articulino/download.py','--destination',base/'model'],env) + verify_assets(base/'model') + if self.cancel.is_set():raise InterruptedError() + (base/'ready').write_text(REVISION+':'+MODEL_REVISION) + temp=self.root/'active.tmp';temp.write_text(json.dumps({'id':base.name}));temp.replace(self.root/'active.json') + self.ensure_library();state='complete';phase='Articulino bereit · Referenzstimme aus speech-voices, Endpunktfreigabe separat' + except InterruptedError:state='cancelled';phase='Articulino-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() diff --git a/articulino_worker.py b/articulino_worker.py new file mode 100644 index 0000000..405a292 --- /dev/null +++ b/articulino_worker.py @@ -0,0 +1,54 @@ +"""Bounded sentence PCM/WAV protocol. Private text/voice never sent to a service.""" +import contextlib,json,os,sys,time,wave +from pathlib import Path +RATE=24000 +MAX_PCM=32*1024**2 + +def generate(tts,request): + import numpy as np + from speech_text import prepare_for_speech + directory=Path(request['output']);cancel=directory/'cancel';started=time.monotonic();first=None;total=0;count=0 + text=request['text'] + if not isinstance(text,str) or not 1<=len(text.strip())<=1000:raise ValueError('Text mit 1–1000 Zeichen erforderlich.') + # Preserve Deck's common German pronunciation/Markdown handling, then let the + # model's own frontend perform its native sentence segmentation/normalization. + text=prepare_for_speech(text,'German') + tts.set_voice(request['voice']) # Official loader truncates to eight seconds. + with wave.open(str(directory/'result.wav'),'wb') as out: + out.setnchannels(1);out.setsampwidth(2);out.setframerate(RATE) + stream=tts.stream(text,language='de',seed=42,normalize=True) + try: + for chunk in stream: + if cancel.exists():return dict(ok=True,cancelled=True) + chunk=np.asarray(chunk) + if chunk.ndim!=1 or not chunk.size or not np.isfinite(chunk).all():raise ValueError('Ungültige Articulino-Audioausgabe.') + pcm=(np.clip(chunk,-1,1)*32767).astype('MAX_PCM:raise ValueError('Articulino-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('Articulino lieferte kein Audio.') + return dict(ok=True,duration=total/2/RATE,sample_rate=RATE,seconds=time.monotonic()-started,first_chunk_seconds=first) + +def main(): + # Keep the line-based control channel free of upstream progress output. + control=sys.stdout + with contextlib.redirect_stdout(sys.stderr): + from articulino_onnx import TTS + from articulino_runtime import verify_assets + verify_assets(sys.argv[1]);os.nice(10) + tts=TTS.from_pretrained(Path(sys.argv[1]),precision='fp32',providers=['CPUExecutionProvider'],threads=4) + assert all(s.get_providers()==['CPUExecutionProvider'] for s in tts.engine.sessions.values()) + 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(tts,request) + except Exception:result=dict(ok=False,error='Articulino-Erzeugung fehlgeschlagen. Referenz, Laufzeit und Ressourcen prüfen.') + temp=directory/'result.tmp';temp.write_text(json.dumps(result));temp.replace(directory/'result.json') +if __name__=='__main__':main() diff --git a/audio_policy.py b/audio_policy.py index 0d7a13e..759ac80 100644 --- a/audio_policy.py +++ b/audio_policy.py @@ -7,10 +7,11 @@ from pathlib import Path MODES=('auto','warm','per_request') class AudioPolicy: - def __init__(self,path,profiles,tts,stt,scheduler,endpoint,pocket=None,qwen_native=None): + def __init__(self,path,profiles,tts,stt,scheduler,endpoint,pocket=None,qwen_native=None,articulino=None): + self.articulino=articulino self.pocket=pocket self.qwen_native=qwen_native - self.cpu_workers=[w for w in (pocket,qwen_native) if w is not None] + self.cpu_workers=[w for w in (pocket,qwen_native,articulino) 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.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(): @@ -60,10 +61,17 @@ class AudioPolicy: if not automatic and item['mode']!='warm':continue if kind=='tts' and self.cpu_workers: from pocket_runtime import supported + from articulino_runtime import supported as articulino_supported + # A warm profile disabled by the user must not override a sole newly + # published CPU TTS profile. Persisted preference remains unchanged. + if item['mode']=='warm': + published=[p for p in self.endpoint.rows() if p['kind']=='audio' and p['enabled']] + if len(published)==1 and not any(p['id']==ident for p in published):ident=published[0]['id'] 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)] if len(rows)==1: - if self.pocket and supported(rows[0].get('model')):worker=self.pocket + if 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.qwen_native and native_supported(rows[0].get('model')):worker=self.qwen_native for other in [self.tts,*self.cpu_workers]: if other is worker:continue diff --git a/backup.py b/backup.py index 6d024e8..757865f 100644 --- a/backup.py +++ b/backup.py @@ -124,7 +124,7 @@ def validate(doc): validate_profiles(settings['separator-profiles.json']) validate_record(doc.get('credentials')) 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'} 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'} 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 'separator' in runtimes: from separator_runtime import MODELS @@ -133,6 +133,7 @@ def validate(doc): if 'sources' in value: 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 '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 'strata' in runtimes and type(runtimes['strata']) is not bool:raise ValueError('Ungültige Strata-Laufzeit.') if 'music_remix' in runtimes and type(runtimes['music_remix']) is not bool:raise ValueError('Ungültige Audio-Remix-Laufzeit.') @@ -213,6 +214,8 @@ class Backup: network=s.network.call('backup-export') 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) + if getattr(s,'articulino_runtime',None): + document['runtimes']['articulino']=s.articulino_runtime.status()['installed'];document['runtime_versions']['articulino']=s.articulino_runtime.status()['revision'] if getattr(s,'pocket_runtime',None): document['runtimes']['pocket']=s.pocket_runtime.status()['installed'];document['runtime_versions']['pocket']=s.pocket_runtime.status()['revision'] if getattr(s,'strata_runtime',None): @@ -273,6 +276,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.') 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',{}) + if versions.get('articulino'): + 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.get('pocket'): from pocket_runtime import REVISION as POCKET_REVISION if versions['pocket']!=POCKET_REVISION:blockers.append('Backup verlangt eine andere Pocket-Version. Passende Deck-Version verwenden.') @@ -311,7 +317,7 @@ class Backup: if versions.get('applio'): from applio_runtime import REVISION as APPLIO_REVISION 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')}!=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')}!=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']: 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 @@ -340,7 +346,7 @@ class Backup: 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,'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 (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,'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._save();threading.Thread(target=self._restore,args=(copy.deepcopy(doc),data['services'],data['restore_credentials']),daemon=True).start();self.plan=None return self.status() @@ -362,6 +368,8 @@ class Backup: return value def _runtimes(self,doc): s=self.server;r=doc['runtimes'] + 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) if r.get('pocket') and not s.pocket_runtime.status()['installed']: self._phase('Pocket-CPU-Laufzeit installieren');s.pocket_runtime.start();self._wait(s.pocket_runtime.status) if r.get('strata') and not s.strata_runtime.status()['installed']: @@ -552,7 +560,7 @@ class Backup: with self.lock: self.cancel.set() if self.busy(): - 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.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_tests',None):self.server.separator_tests.stop() if getattr(self.server,'music',None):self.server.music.stop() diff --git a/catalog.py b/catalog.py index c6e3b48..8905060 100644 --- a/catalog.py +++ b/catalog.py @@ -76,6 +76,8 @@ def file_role(filename): role,label='model','X-VC-Stimmgewicht' elif name.endswith('.pth') and not PurePosixPath(name).name.startswith(('g_','d_')) and not any(p in ('pretraineds','predictors','embedders') for p in parts): role,label='model','Stimmgewicht (PTH)' + elif name=='fp32/dit_step.onnx': + role,label='model','Articulino-FP32-Gewicht' elif name.endswith(('.gguf','.safetensors')): role,label='model','Modelldatei' else: @@ -226,7 +228,7 @@ class Catalog: name=f['rfilename'];p=PurePosixPath(name) from acestep_models import ACE_REPO,ACE_BASE_REPO,ACE_FILES,ACE_BASE_FILES recipe_file=(repo==ACE_REPO and name in ACE_FILES) or (repo==ACE_BASE_REPO and name in ACE_BASE_FILES) or (repo=='k2-fsa/OmniVoice' and name=='chat_template.jinja') - allowed=recipe_file or p.suffix.lower() in ('.gguf','.safetensors','.json','.tiktoken') or (repo=='openbmb/VoxCPM2' and name=='audiovae.pth') or (repo=='Soul-AILab/SoulX-Singer' and name=='model-svc.pt') or (repo=='chenxie95/X-VC' and name=='xvc.pt') + allowed=(repo=='eigenhand/Articulino-DE-EN-Realtime-Stream-TTS-ONNX' and name=='fp32/dit_step.onnx') or recipe_file or p.suffix.lower() in ('.gguf','.safetensors','.json','.tiktoken') or (repo=='openbmb/VoxCPM2' and name=='audiovae.pth') or (repo=='Soul-AILab/SoulX-Singer' and name=='model-svc.pt') or (repo=='chenxie95/X-VC' and name=='xvc.pt') if p.is_absolute() or '..' in p.parts or not allowed:continue size=f.get('size',f.get('lfs',{}).get('size')) if not isinstance(size,int) or size<1:continue diff --git a/deploy/articulino/README.md b/deploy/articulino/README.md new file mode 100644 index 0000000..39c7c78 --- /dev/null +++ b/deploy/articulino/README.md @@ -0,0 +1,82 @@ +# Articulino CPU runtime + +Pinned source: `eigenhand/articulino-onnx` commit +`143d6dd5bbd67a02564be30f15bd8a578dda4987` (package 1.0.0, Apache-2.0). +Public weights: `eigenhand/Articulino-DE-EN-Realtime-Stream-TTS-ONNX`, revision +`a760ce8d513534111c7679751869fa4c45ef0e54`. All five FP32 graphs, config, +LICENSE, NOTICE and publisher checksums are fixed in `assets.json` with SHA256. +The source archive is independently SHA256-pinned in `requirements.lock`. +No PyTorch, CUDA, external synthesis API or extra service is used. + +## Install / native Debian / import + +Prerequisites on supported Debian: Python >=3.10 with `venv`/pip, Git (shared +installer prerequisite), libsndfile1 and ffmpeg. Qualified application runtime: +Python 3.12, ONNX Runtime 1.23.2, numpy 2.2.6, soundfile 0.13.1 and the complete +lockfile. Install OS prerequisites as administrator; run bootstrap as the Deck +service user, with the real writable state directory: + +``` +python3 deploy/articulino/bootstrap.py --state /var/lib/athena-deck +``` + +Equivalent UI: TTS → Einrichten → Articulino-CPU-Laufzeit installieren. +Bootstrap installs an independent environment in `STATE/articulino-runtime/ID`, +checks every public file, then marks the runtime ready and imports the main +ONNX weight into the model library. Existing weights are not replaced. No +profile is auto-created/published and no private voice is downloaded. A +verified local model directory can be imported using `download.py --source +DIRECTORY --destination NEW_RUNTIME/model`; that validates all hashes rather +than trusting the experiment cache. The normal bootstrap can also redownload +all assets from their pinned public source. Test folders are not dependencies. + +Create an audio profile using the imported `fp32/dit_step.onnx`, speed=1, +API ID `articulino-anna-cpu`. The complete remaining graph bundle belongs to +this runtime. Keep this profile disabled initially. Stored default voice comes +from `STATE/speech-voices/default.json`, resolving to e.g. +`speech-voices/Anna/reference.wav`; never replace it during installation. +Articulino uses at most the first eight seconds. It approximates Anna's timbre; +it is not equivalent to Qwen's accepted voice fidelity. + +## Endpoint and residency + +Supports `/v1/audio/speech` with WAV, MP3 and streamed PCM16 mono 24 kHz. +`voice=default`, German, speed=1. Stable client model alias `tts` resolves only +when exactly one TTS profile is published. To switch, disable Qwen's endpoint +publication and enable Articulino (reverse to return to Qwen). No Hermes or +Mac-app configuration change is necessary. Two simultaneous published TTS +profiles make `model=tts` ambiguous and intentionally return 409. + +The worker runs locally in Deck's CPU affinity pool, four ONNX threads, nice10. +It does not reserve VRAM, evict Strata or use the GPU scheduler. Automatic +residency follows endpoint publication. A warm pinned profile disabled at the +endpoint yields to the sole published profile, without rewriting the user's +stored preference. Currently active production profile/settings are not changed +by creation of a disabled candidate. Cancellation is cooperative between +complete sentences; there is no claim of interrupting an ONNX sentence midway. +Bounded inputs (1000 characters), outputs (32 MiB) and 600-second worker deadline +match the existing serial TTS job protocol. Common Deck speech preparation is +followed by Articulino's native German frontend and sentence segmentation. + +## Backup / restore / update + +Configuration backups now record the Articulino runtime recipe and source +revision. Restore installs that pinned environment/bundle before reconstructing +profiles and downloads the main library weight with its original checksum. +Private `speech-voices` data remains part of the encrypted full media backup; +a settings-only backup cannot recreate a private voice. Do not commit voices, +generated audio or model files. A fresh-Debian end-to-end encrypted restore has +not been tested and is not claimed by this change. + +Deploy new app files using the existing service deployment method. For the +current read-only Docker installation a thin image on the verified current base +is sufficient; no large base-image rebuild/consolidation is required. Restart +only at confirmed idle, after all active/queued API work and setup jobs finish, +and restore the previously active chat profile. Native deployments use the +same files/runtime/state and their normal service restart. No host reboot. + +For rollback, publish the previous Qwen profile again (and disable Articulino), +then use the previous verified app release if necessary. Do not delete Qwen +weights, its environment or Anna. Install failures must not destroy an existing +working runtime. An update to Articulino source/graphs requires new pins, +hashes, CPU correctness/speed and speech checks before activation. diff --git a/deploy/articulino/assets.json b/deploy/articulino/assets.json new file mode 100644 index 0000000..46d74bd --- /dev/null +++ b/deploy/articulino/assets.json @@ -0,0 +1,47 @@ +[ + { + "file": "config.json", + "bytes": 780, + "sha256": "407b7553796634d21367546508755763349cf7ee6561842f07bc9d18f7b3ce44" + }, + { + "file": "LICENSE", + "bytes": 11358, + "sha256": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30" + }, + { + "file": "NOTICE", + "bytes": 2155, + "sha256": "ab6b0eea89750bed940a4d278cd2906235323cb563bb49adf0388361815d5a60" + }, + { + "file": "SHA256SUMS", + "bytes": 2434, + "sha256": "bd21d9834b9ed9ce8befdbf40786ba640e7869b8bfda1ef9cdda2bd254c4cc06" + }, + { + "file": "fp32/decoder.onnx", + "bytes": 90822713, + "sha256": "85a68f4a93af28452d3085740f64124cfbbe465f54348b035fad646542d0226f" + }, + { + "file": "fp32/dit_step.onnx", + "bytes": 100873462, + "sha256": "57b1d2a741b5044cb2769239e89d1c511eb5b7ffa79a55c11cde4d7670010747" + }, + { + "file": "fp32/encoder.onnx", + "bytes": 90780308, + "sha256": "0b3770a2d181ac747bb0e626293071446c6a0285f54292773256309ba09e8742" + }, + { + "file": "fp32/text.onnx", + "bytes": 83568088, + "sha256": "47bfc4a50f6ad5726fa43a549ecb247efc0d10ef6e333c7fd3ea4414e8b0c2a9" + }, + { + "file": "fp32/voice.onnx", + "bytes": 170915170, + "sha256": "3215a71aaab64fb116edb823e0f13c7001a588979d875f79c11a20024a9f88a3" + } +] \ No newline at end of file diff --git a/deploy/articulino/bootstrap.py b/deploy/articulino/bootstrap.py new file mode 100644 index 0000000..6b1bca0 --- /dev/null +++ b/deploy/articulino/bootstrap.py @@ -0,0 +1,13 @@ +"""Install the same CPU recipe in native Debian or the existing Deck runtime.""" +import argparse,json,sys,time +from pathlib import Path +sys.path.insert(0,str(Path(__file__).resolve().parents[2])) +from articulino_runtime import ArticulinoRuntime +if __name__=='__main__': + p=argparse.ArgumentParser();p.add_argument('--state',required=True,type=Path);a=p.parse_args() + runtime=ArticulinoRuntime(a.state/'articulino-runtime') + if runtime.status()['installed']:print(json.dumps(dict(installed=True,model_id=runtime.ensure_library()))) + else: + 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) diff --git a/deploy/articulino/download.py b/deploy/articulino/download.py new file mode 100644 index 0000000..dca844a --- /dev/null +++ b/deploy/articulino/download.py @@ -0,0 +1,29 @@ +"""Fetch only the pinned public Articulino assets; no user data or credentials.""" +import argparse,hashlib,json,shutil,sys +from pathlib import Path +sys.path.insert(0,str(Path(__file__).resolve().parents[2])) +from catalog import remote +from articulino_runtime import REPO,MODEL_REVISION,ASSETS,verify_assets + +def download(destination,source=None): + destination=Path(destination);destination.mkdir(parents=True,exist_ok=True,mode=0o700) + for item in json.loads(ASSETS.read_text()): + path=destination/item['file'];path.parent.mkdir(parents=True,exist_ok=True,mode=0o700) + if path.exists(): + with path.open('rb') as f:digest=hashlib.file_digest(f,'sha256').hexdigest() + if digest==item['sha256'] and path.stat().st_size==item['bytes']:continue + raise ValueError('Vorhandene Datei weicht ab: '+item['file']) + temp=path.with_name(path.name+'.part');h=hashlib.sha256();size=0 + try: + origin=(Path(source)/item['file']).open('rb') if source else remote('https://huggingface.co/'+REPO+'/resolve/'+MODEL_REVISION+'/'+item['file']) + with origin as f,temp.open('wb') as out: + while block:=f.read(1024*1024): + size+=len(block) + if size>item['bytes']:raise ValueError('Datei zu groß: '+item['file']) + out.write(block);h.update(block) + if size!=item['bytes'] or h.hexdigest()!=item['sha256']:raise ValueError('Prüfsumme abweichend: '+item['file']) + temp.chmod(0o600);temp.replace(path) + finally:temp.unlink(missing_ok=True) + verify_assets(destination) +if __name__=='__main__': + p=argparse.ArgumentParser();p.add_argument('--destination',required=True,type=Path);p.add_argument('--source',type=Path);a=p.parse_args();download(a.destination,a.source) diff --git a/deploy/articulino/requirements.lock b/deploy/articulino/requirements.lock new file mode 100644 index 0000000..6ce9cfe --- /dev/null +++ b/deploy/articulino/requirements.lock @@ -0,0 +1,15 @@ +articulino-onnx @ https://codeload.github.com/eigenhand/articulino-onnx/tar.gz/143d6dd5bbd67a02564be30f15bd8a578dda4987#sha256=7e0cfb599d4f0954835de92c63dae9adc37e360428b39bedf36e4a6972eaeb4c +cffi==2.1.1 +coloredlogs==15.0.1 +docopt==0.6.2 +flatbuffers==25.12.19 +humanfriendly==10.0 +mpmath==1.3.0 +num2words==0.5.14 +numpy==2.2.6 +onnxruntime==1.23.2 +packaging==26.3 +protobuf==7.36.2 +pycparser==3.12 +soundfile==0.13.1 +sympy==1.14.0 diff --git a/deploy/install.py b/deploy/install.py index 8fc609d..7a38466 100644 --- a/deploy/install.py +++ b/deploy/install.py @@ -15,7 +15,7 @@ import urllib.request ROOT = Path(__file__).resolve().parent.parent LABEL = 'de.casaderoll.athena-deck.standalone' -FILES = ['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 = ['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'] @@ -271,7 +271,7 @@ def update(base, rollback=False, force=False, api_ports=None, reuse_runtime=Fals backup_name=config['name']+'-previous' if inspect(backup_name):raise RuntimeError('Rückfall-Containername belegt. Keine Änderung ausgeführt.') stamp=str(time.time_ns()) - shutil.copytree(base/'state',base/'backups'/stamp,ignore=shutil.ignore_patterns('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('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'] if was_running:run('docker','stop','--time','15',config['name']) run('docker','rename',config['name'],backup_name) diff --git a/deploy/scheduled_backup.py b/deploy/scheduled_backup.py index 4b9116b..9cf9467 100644 --- a/deploy/scheduled_backup.py +++ b/deploy/scheduled_backup.py @@ -23,7 +23,7 @@ def key(): return KEY.read_bytes().strip()+b'\n' def sources(): - names=('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=('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')] # Private locally-trained voices have no public replacement source. for p in (STATE/'models').glob('*/entry.json'): diff --git a/docs/CURRENT_SYSTEM.md b/docs/CURRENT_SYSTEM.md index e1b867b..f27fe2c 100644 --- a/docs/CURRENT_SYSTEM.md +++ b/docs/CURRENT_SYSTEM.md @@ -615,3 +615,8 @@ Am 15. Oktober 2026: SSD-Live-Balken für Lesen, Schreiben und Aktivzeit aktivie Image `athena-deck-standalone:ssd-bars-fixed-20261015` (Dateirechte korrigiert). Gemeinsame adaptive, beschriftete Bandbreitenskala und feste 100-Prozent-Aktivzeitskala. Keine Modelländerung. [Umfang und Abnahme](experiments/ssd-dashboard-2026-10-14/README.md). + + +### Articulino CPU TTS candidate (27 October 2026) + +Separate optional CPU profile integration: see [runtime and restore recipe](../deploy/articulino/README.md). Qwen and the existing Anna reference are preserved; adding the profile does not publish it. Deployment/acceptance status is recorded in [integration report](maintenance/articulino-profile-2026-10-27/README.md). diff --git a/docs/maintenance/articulino-profile-2026-10-27/README.md b/docs/maintenance/articulino-profile-2026-10-27/README.md new file mode 100644 index 0000000..ae966e2 --- /dev/null +++ b/docs/maintenance/articulino-profile-2026-10-27/README.md @@ -0,0 +1,39 @@ +# Articulino endpoint profile — 27 October 2026 + +Michael authorized adding the retained CPU candidate as a separate Deck TTS +profile, initially disabled, so he can switch endpoint publication himself. +No Qwen, STT, chat model, voice, Hermes or Mac-app changes were authorized. + +Implementation adds pinned CPU-only ONNX runtime + public graph recipe, +model-library eligibility, profile setup checks, normal TTS test UI, endpoint +WAV/MP3/PCM routing, serial jobs, cooperative sentence cancellation, +residency selection, lifecycle hooks and configuration restore metadata. +The existing test UI accidentally routed the Qwen Q4 model to the CUDA worker; +its routing now covers both known native Q8 and Q4 recipes. + +Source files in the canonical export matched the local pre-change versions by +SHA256 for all nine modified app/installer files. Deploy only this integration, +not the unrelated dirty workspace. Source/graphs/dependencies and native +bootstrap are documented in `deploy/articulino/README.md`. + +Validation so far: six new focused tests passed; 127 existing tests covering +Qwen native, Pocket, audio policy, TTS, endpoint and backups passed. Local HTTP +test sockets required running these synthetic tests outside the sandbox. +No real production requests or private speech/text were used in unit tests. + +Own real CPU worker check in the current read-only container: independent +Python environment and all public assets installed successfully. Synthetic +four-sentence story: 15.69 seconds PCM/WAV, first run 0.7147 seconds synthesis +(1.773 seconds including model load and dispatch), repeat streaming 0.6297 +seconds (0.6605 seconds wall). First complete sentence 0.3483 / 0.2606 seconds. +Stream PCM bytes match the final WAV samples exactly, mono PCM16 at 24 kHz. +These are short warm/cold checks, not a broad performance guarantee. + +Production Qwen worker code, endpoint publication, audio residency policy, +CPU partition and original Anna reference remain unchanged. A thin app image +was built on the verified current image without new OS dependencies or +consolidating the large base. Runtime preparation did not restart Deck. + +User login and explicit idle Deck restart approval have been requested. +Production app activation/profile creation and native client verification +remain pending; the candidate is not yet visible as an active Deck profile. diff --git a/endpoint.py b/endpoint.py index 7ae5b57..fb96490 100644 --- a/endpoint.py +++ b/endpoint.py @@ -162,6 +162,7 @@ class Endpoint: 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] 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,'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,'qwen_native',None):counts['tts']['loaded']=counts['tts']['loaded'] or self.qwen_native.status()['loaded'] scheduler_status=self.scheduler.status() @@ -220,6 +221,9 @@ class Endpoint: if not data['enabled'] and row['kind']=='audio' and getattr(self,'pocket',None): status=self.pocket.status() 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,'articulino',None): + status=self.articulino.status() + if status.get('profile_id')==row['id'] and (status.get('job') or {}).get('state')!='running':self.articulino.stop() if not data['enabled'] and row['kind']=='audio' and getattr(self,'qwen_native',None): status=self.qwen_native.status() if status.get('profile_id')==row['id'] and (status.get('job') or {}).get('state')!='running':self.qwen_native.stop() @@ -265,6 +269,7 @@ class Endpoint: if getattr(self,'pocket',None):self.pocket.stop() if getattr(self,'seedvc',None):self.seedvc.stop() if getattr(self,'humaneness',None):self.humaneness.stop() + if getattr(self,'articulino',None):self.articulino.stop() if getattr(self,'qwen_native',None):self.qwen_native.stop() if self.embeddings:self.embeddings.stop() if self.voxcpm:self.voxcpm.stop() @@ -526,7 +531,15 @@ class APIHandler(BaseHTTPRequestHandler): 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) 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) - if native_row: + 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) + if articulino_row: + 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') + 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 native_row: profile=ep.find_profile(data.get('model'),'audio');backend=getattr(ep,'qwen_native',None) if not backend:raise APIError('Native Qwen-CPU-Laufzeit nicht eingerichtet.',503,'qwen_native_unavailable') profile_seconds=time.monotonic()-started diff --git a/execution_setup.py b/execution_setup.py index b0a8081..320fcd3 100644 --- a/execution_setup.py +++ b/execution_setup.py @@ -13,6 +13,12 @@ def _assess(model, installed, profile=None): 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.') return result + from articulino_runtime import supported as articulino_model + if articulino_model(model): + ready=bool(installed.get('articulino')) + result.update(family='Articulino',evidence='Gepinnter CPU-FP32-ONNX-Worker',runtime='Articulino · CPU',route='#tts-runtime',installed=ready,state='setup' if ready else 'runtime_missing',label='Articulino · CPU',components=['Gespeicherte Referenzstimme'],message='TTS mit Anna-Referenz, WAV/MP3/PCM. Stimmähnlichkeit näherungsweise. Vollständiges Modellpaket wird mit der Laufzeit installiert.') + if profile:result.update(state='ready' if profile.get('runnable') else 'profile_incomplete',blockers=profile.get('blockers',[])) + return result from pocket_runtime import supported as pocket_model from qwen_native_runtime import supported as native_model,model_quant if native_model(model): @@ -109,6 +115,10 @@ def _assess_candidates(model, installed, profile=None): meta=model.get('runtime_metadata') or {};family=str(meta.get('architecture') or '').lower() 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)) + from articulino_runtime import supported as articulino_model + if articulino_model(model): + add('articulino','Articulino · CPU','articulino','#tts-runtime','Gepinnte ONNX-CPU-Laufzeit ohne CUDA oder PyTorch') + return result from qwen_native_runtime import supported as native_model if native_model(model): add('qwen_native','Qwen3-TTS Q8/Q4 · CPU','qwen_native','#tts-runtime','Native CPU-only-Laufzeit, kein CUDA oder PyTorch') diff --git a/profiles.py b/profiles.py index f0a2193..ee72c5d 100644 --- a/profiles.py +++ b/profiles.py @@ -399,6 +399,8 @@ class Profiles: from qwen_native_runtime import supported as native_model from pocket_runtime import supported as pocket_model,COMPONENTS as POCKET_COMPONENTS from parakeet_runtime import supported as redux_supported + from articulino_runtime import supported as articulino_model + 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.') from soulx_singer import soulx_singer_model if soulx_singer_model(model):return dict(supported=True,requirements=[],source='https://huggingface.co/Plachta/SoulX-Singer',license='apache-2.0',runtime='SoulX-Singer · Python/PyTorch',runtime_route='#soulx-singer-runtime',runtime_installed=not bool(getattr(self,'soulx_singer_blockers',lambda p:['Laufzeit fehlt'])({'model':model})),worker_available=True,no_components=True,message='Gesangsdatei und Referenzstimme ohne Training umwandeln. Originales 24-kHz-Gesangsmodell; alle Zusatzgewichte gehören zum geprüften Laufzeitpaket. ') diff --git a/server.py b/server.py index eb65a41..0196712 100644 --- a/server.py +++ b/server.py @@ -113,9 +113,14 @@ class Server(ThreadingHTTPServer): from qwen_native import QwenNative self.qwen_native_runtime=QwenNativeRuntime(self.catalog.root.parent/'qwen-native-runtime') self.qwen_native=QwenNative(self.catalog.root.parent/'qwen-native-jobs',self.profiles,self.qwen_native_runtime) + from articulino_runtime import ArticulinoRuntime,supported as articulino_model + from articulino import Articulino + 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.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.pocket_runtime_ready=lambda:self.pocket_runtime.status()['installed'] - self.profiles.tts_blockers=lambda p: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.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.hardware = HardwareProvider() self.started = time.time() @@ -174,6 +179,7 @@ class Server(ThreadingHTTPServer): self.endpoint.embeddings=self.embeddings self.endpoint.tts=self.tts_tests self.endpoint.pocket=self.pocket + self.endpoint.articulino=self.articulino self.endpoint.qwen_native=self.qwen_native self.endpoint.voxcpm=self.voxcpm_tests from humaneness_runtime import HumanenessRuntime,supported as humaneness_model @@ -222,7 +228,7 @@ class Server(ThreadingHTTPServer): 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) def stop_gpu_work(): - self.seedvc.stop();self.humaneness.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.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 ltx_original_runtime import LTXOriginalRuntime from audio_cpp_runtime import AudioCppRuntime @@ -255,7 +261,7 @@ class Server(ThreadingHTTPServer): if self.endpoint.config['autostart']: try:self.endpoint.start() 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) + 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.sessions = {} self.login_attempts = [] self.auth_lock = threading.Lock() @@ -479,7 +485,7 @@ class Handler(BaseHTTPRequestHandler): else self.server.video.runtime) return {'embeddings':chat,'stt':chat,'chat':chat, 'image':self.server.image_runtime.status().get('installed',False), - 'seedvc':self.server.seedvc_runtime.status()['installed'],'humaneness':self.server.humaneness_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'],'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), 'acestep':self.server.acestep_runtime.status()['installed'], 'audio_cpp':self.server.audio_cpp_runtime.status()['installed'], @@ -536,6 +542,10 @@ class Handler(BaseHTTPRequestHandler): 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/pocket':return self.respond(self.server.pocket.status()) + if self.path == '/api/v1/articulino':return self.respond(self.server.articulino.status()) + 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') + except (ValueError,OSError) as exc:return self.respond({'error':str(exc)},400) if self.path == '/api/v1/qwen-native':return self.respond(self.server.qwen_native.status()) if urlsplit(self.path).path == '/api/v1/qwen-native/audio': try:return self.respond(self.server.qwen_native.audio(parse_qs(urlsplit(self.path).query).get('id',[''])[0]),mime='audio/wav') @@ -952,6 +962,16 @@ class Handler(BaseHTTPRequestHandler): if self.path.endswith('/cancel') and not data:return self.respond(self.server.qwen_native.stop()) raise ValueError('Ungültige Qwen-CPU-Aktion.') except (ValueError,TypeError,KeyError) 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'): + try: + data=self.read_json() + if self.path.endswith('/install') and not data:return self.respond(self.server.articulino_runtime.start()) + if self.path.endswith('/install-cancel') and not data:return self.respond(self.server.articulino_runtime.stop()) + if self.path.endswith('/start') and set(data)=={'profile_id','text','speaker','language'}: + return self.respond(self.server.articulino.start(**data)) + if self.path.endswith('/cancel') and not data:return self.respond(self.server.articulino.stop()) + raise ValueError('Ungültige Articulino-Aktion.') + except (ValueError,OSError) as exc:return self.respond({'error':str(exc)},400) if self.path in ('/api/v1/pocket/install','/api/v1/pocket/install-cancel','/api/v1/pocket/start','/api/v1/pocket/cancel'): try: data=self.read_json() @@ -1023,7 +1043,9 @@ class Handler(BaseHTTPRequestHandler): if self.path == '/api/v1/profiles/delete': try: 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: + 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: + 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.') native_job=self.server.qwen_native.job if native_job and native_job.get('state')=='running' and native_job.get('profile_id')==data.get('id'):raise ValueError('Qwen-CPU-Profil wird gerade ausgeführt. Zuerst Auftrag beenden.') pocket_job=self.server.pocket.job @@ -1037,6 +1059,7 @@ class Handler(BaseHTTPRequestHandler): 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.') result=self.server.profiles.delete(data) + 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.qwen_native.profile_id==data.get('id'):self.server.qwen_native.stop() if stt_job and stt_job.get('profile_id')==data.get('id'):self.server.stt.stop() @@ -1118,7 +1141,7 @@ def main(): server.video.close() server.endpoint.close() 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.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.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.image_runtime.stop() server.ltx_original_runtime.stop() diff --git a/test_articulino.py b/test_articulino.py new file mode 100644 index 0000000..a1257d9 --- /dev/null +++ b/test_articulino.py @@ -0,0 +1,78 @@ +import hashlib,json,tempfile,unittest,wave +from pathlib import Path +from unittest.mock import Mock,patch +from articulino_runtime import ArticulinoRuntime,supported,REPO,MODEL_REVISION,MODEL_FILE +from articulino import Articulino +from endpoint import APIHandler +import test_pocket + +MODEL=dict(kind='audio',repo=REPO,revision=MODEL_REVISION,file=MODEL_FILE) + +class ArticulinoTests(unittest.TestCase): + def test_pinned_recipe_library_role_and_execution_routing(self): + from catalog import file_role + from execution_setup import assess + self.assertTrue(supported(MODEL));self.assertFalse(supported(dict(MODEL,revision='0'*40))) + self.assertFalse(supported(dict(MODEL,file='fp16/dit_step.onnx'))) + self.assertTrue(file_role(MODEL_FILE)['profile_eligible']) + self.assertFalse(file_role('fp32/voice.onnx')['profile_eligible']) + result=assess(MODEL,{'articulino':True},{'runnable':True,'blockers':[]}) + self.assertEqual(result['state'],'ready');self.assertEqual(result['candidates'][0]['id'],'articulino') + def test_private_voice_guard_and_cpu_warm(self): + with tempfile.TemporaryDirectory() as d: + root=Path(d);voice=root/'speech-voices/Anna';voice.mkdir(parents=True);(voice/'reference.wav').touch() + (root/'speech-voices/default.json').write_text('{"voice":"Anna"}') + worker=Articulino(root/'jobs',Mock(),Mock()) + self.assertEqual(worker.voice_path('default'),(voice/'reference.wav').resolve()) + with self.assertRaises(ValueError):worker.voice_path('../Anna') + worker.acquire=Mock(side_effect=AssertionError('GPU touched'));worker._profile=Mock(return_value={'id':'a'});worker._ensure_cpu=Mock() + worker.warm('a');worker.acquire.assert_not_called() + def test_endpoint_routes_alias_default_and_formats_without_gpu_worker(self): + for model in ('tts','articulino-anna-cpu'): + for fmt in ('wav','pcm','mp3'): + h,ep,pocket,row=test_pocket.SpeechRoutingTests().fixture() + row.update(model=MODEL,api_id='articulino-anna-cpu');ep.articulino=Mock() + ep.articulino.start.return_value={'id':'job'} + ep.articulino.status.return_value=pocket.status.return_value + ep.articulino.job_status.return_value=pocket.job_status.return_value + ep.articulino.audio.return_value=b'RIFF-articulino' + with patch('endpoint.speech_mp3',return_value=b'MP3'): + APIHandler.speech(h,ep,dict(model=model,input='Ein synthetischer Satz.',response_format=fmt)) + ep.articulino.start.assert_called_once();pocket.start.assert_not_called();ep.tts.start.assert_not_called() + self.assertEqual(ep.articulino.start.call_args.kwargs['streaming'],fmt=='pcm') + def test_worker_pcm_matches_wav_and_cooperative_cancel(self): + import numpy as np + from articulino_worker import generate + for cancelled in (False,True): + with tempfile.TemporaryDirectory() as d: + root=Path(d);tts=Mock();tts.stream.return_value=iter([np.array([.1,-.2,0.]),np.array([.2,.3])]) + if cancelled:(root/'cancel').touch() + result=generate(tts,dict(output=d,text='Hallo Welt.',voice='private.wav',streaming=True)) + self.assertTrue(result['ok']) + if cancelled: + self.assertTrue(result['cancelled']);self.assertFalse(list(root.glob('chunk-*.pcm'))) + else: + pcm=b''.join(p.read_bytes() for p 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_corrupt_assets_never_get_published(self): + from articulino_runtime import verify_assets + with tempfile.TemporaryDirectory() as d: + root=Path(d);f=root/'assets.json';f.write_text(json.dumps([dict(file='config.json',bytes=2,sha256=hashlib.sha256(b'{}').hexdigest())])) + (root/'config.json').write_bytes(b'xx') + with patch('articulino_runtime.ASSETS',f): + with self.assertRaisesRegex(ValueError,'Prüfsumme'):verify_assets(root) + def test_endpoint_switch_warm_keeps_qwen_setting_but_selects_articulino(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":"qwen"}}') + qwen=p.Worker();art=p.Worker();ep=p.Endpoint();ep.state='running' + ep.rows=lambda:[dict(id='qwen',kind='audio',enabled=False,runnable=True,model={}),dict(id='art',kind='audio',enabled=True,runnable=True,model=MODEL)] + manager=AudioPolicy(path,p.Profiles(),p.Worker(),p.Worker(),p.Scheduler(),ep,qwen_native=qwen,articulino=art) + manager.reconcile();self.assertEqual(art.warmed,['art']);self.assertFalse(qwen.warmed) + self.assertEqual(manager.settings['tts']['profile_id'],'qwen') + +if __name__=='__main__':unittest.main() diff --git a/test_backup.py b/test_backup.py index d757c05..9996027 100644 --- a/test_backup.py +++ b/test_backup.py @@ -96,6 +96,14 @@ class RestoreTests(unittest.TestCase): restored=open_backup(seal(doc,'backup secure password'),'backup secure password') (self.root/'cpu-partition.json').unlink();self.server.backup._apply_settings(restored) self.assertEqual(json.loads((self.root/'cpu-partition.json').read_text()),plan) + def test_articulino_runtime_recipe_and_restore(self): + from articulino_runtime import REVISION + self.server.articulino_runtime.status=Mock(return_value=dict(installed=True,revision=REVISION,job=None)) + doc=self.server.backup.snapshot(include_history=False);validate(doc) + self.assertTrue(doc['runtimes']['articulino']);self.assertEqual(doc['runtime_versions']['articulino'],REVISION) + self.server.articulino_runtime.status=Mock(return_value=dict(installed=False,revision=REVISION,job=None)) + self.server.articulino_runtime.start=Mock();self.server.backup._wait=Mock();self.server.backup.job=dict(state='running',items=[],completed=0,phase='Articulino-Test') + self.server.backup._runtimes(doc);self.server.articulino_runtime.start.assert_called_once();self.server.backup.job['state']='complete' def test_remix_runtime_recipe_and_restore(self): from remix_runtime import VERSION self.server.remix_runtime.status=Mock(return_value=dict(installed=True,version=VERSION,job=None)) diff --git a/tts-ui.js b/tts-ui.js index 6bedad3..3b93945 100644 --- a/tts-ui.js +++ b/tts-ui.js @@ -1,13 +1,13 @@ window.TTSUI=(()=>{ const e=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[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;} - function html(setup=false){return `

${setup?'TTS einrichten':'Sprache ausprobieren'}

${setup?'

Qwen3-TTS 0.6B Q8/Q4 · CPU

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.

Pocket TTS · CPU

Deutsch mit gespeicherter Anna-Stimme, ohne GPU-Speicher. Die Laufzeitinstallation lädt keine Modelle oder privaten Stimmen.

Qwen3-TTS · GPU

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.

Vorhandenes TTS-Profil verbinden

Ersetzt im ausgewählten Profil die Modellzuordnung durch die eingerichtete CUDA-Variante. Der Profilname bleibt erhalten.

Textaufbereitung am API-Endpunkt

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.

Speicherverhalten

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 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.

':'

Qwen 1.7B nutzt die RTX 3060; natives Qwen Q8/Q4 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.

'}
`;} + function html(setup=false){return `

${setup?'TTS einrichten':'Sprache ausprobieren'}

${setup?'

Articulino · Anna · CPU

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.

Qwen3-TTS 0.6B Q8/Q4 · CPU

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.

Pocket TTS · CPU

Deutsch mit gespeicherter Anna-Stimme, ohne GPU-Speicher. Die Laufzeitinstallation lädt keine Modelle oder privaten Stimmen.

Qwen3-TTS · GPU

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.

Vorhandenes TTS-Profil verbinden

Ersetzt im ausgewählten Profil die Modellzuordnung durch die eingerichtete CUDA-Variante. Der Profilname bleibt erhalten.

Textaufbereitung am API-Endpunkt

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.

Speicherverhalten

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.

':'

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.

'}
`;} 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'}`; 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=`

Ergebnis

WAV herunterladen

`;}} }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=>``).join('')||'';if(!setup){el('tts-profile').onchange=async()=>{const selectedModel=profiles.find(p=>p.id===el('tts-profile').value)?.model;backend=selectedModel?.repo==='kyutai/pocket-tts'?'pocket':selectedModel?.repo==='Serveurperso/Qwen3-TTS-GGUF'&&selectedModel?.file==='qwen-talker-0.6b-base-Q8_0.gguf'?'qwen-native':'tts';lastResult='';try{const s=await api(backend);if(!root.isConnected)return;el('tts-speaker').innerHTML=s.runtime.speakers.map(v=>``).join('');el('tts-language').innerHTML=s.runtime.languages.map(v=>``).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=>``).join('')||'';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=>``).join('');el('tts-language').innerHTML=s.runtime.languages.map(v=>``).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;}} 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');} @@ -15,6 +15,8 @@ window.TTSUI=(()=>{ 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;}); 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 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(); 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);}} el('qwen-native-install').onclick=()=>api('qwen-native/install',{}).catch(x=>error(x.message));el('qwen-native-install-cancel').onclick=()=>api('qwen-native/install-cancel',{}).catch(x=>error(x.message));nativeStatus(); async function pocketStatus(){try{const d=await api('pocket'),rt=d.runtime;el('pocket-status').textContent=rt.job?.phase||(rt.installed?'Pocket-CPU-Laufzeit bereit.':'Noch nicht installiert.');el('pocket-install').disabled=rt.installed||rt.job?.state==='running';el('pocket-install-cancel').disabled=rt.job?.state!=='running';}catch(x){error(x.message);}finally{if(root.isConnected)setTimeout(pocketStatus,2000);}}