Files
Athena-Deck/audio_policy.py
T
Mikei386 c0bc5d3a1b Integrate Basalt telemetry and shared GPU speech runtimes
Publish the reviewed accumulated runtime, scheduler, profile, UI, native recipes and historical maintenance evidence. Includes Qwen GPU ASR correction and shared Anna/atelier ownership. Validated with 784 local tests, Python/JSON parsing and eight JavaScript syntax checks. Live GPU acceptance and full fresh-host restore limits remain documented.
2026-11-03 21:16:41 +01:00

122 lines
7.1 KiB
Python

"""Persisted residency preferences for Deck-owned speech workers."""
import json
import threading
import time
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,articulino=None,kikiri=None):
self.kikiri=kikiri
self.articulino=articulino
self.pocket=pocket
self.qwen_native=qwen_native
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.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():
try:
stored=json.loads(self.path.read_text())
for kind in self.settings:
value=stored.get(kind,{})
if value.get('mode') in MODES and (value.get('profile_id') is None or isinstance(value.get('profile_id'),str)):
self.settings[kind]=dict(mode=value['mode'],profile_id=value.get('profile_id'))
except (OSError,ValueError,AttributeError,TypeError):pass
self.tts.policy=self.settings['tts']['mode'];self.stt.policy=self.settings['stt']['mode']
for cpu_worker in self.cpu_workers:cpu_worker.policy=self.settings['tts']['mode']
self.thread=threading.Thread(target=self._loop,daemon=True);self.thread.start()
def status(self):
with self.lock:return dict(settings={k:dict(v) for k,v in self.settings.items()},errors=dict(self.errors))
def configure(self,data):
if not isinstance(data,dict) or set(data)!={'kind','mode','profile_id'}:raise ValueError('Art, Modus und Profil-ID erforderlich.')
kind=data['kind'];mode=data['mode'];ident=data['profile_id']
if kind not in self.settings or mode not in MODES:raise ValueError('Ungültiger Audio-Modus.')
if ident is not None and (not isinstance(ident,str) or len(ident)>128):raise ValueError('Ungültige Profil-ID.')
if mode=='warm':
profile_kind='audio' if kind=='tts' else 'stt'
if not ident or not any(p['id']==ident and p['kind']==profile_kind and p['runnable'] for p in self.profiles.status()['profiles']):raise ValueError('Für „Immer bereit“ ein ausführbares Profil auswählen.')
with self.lock:
updated={k:dict(v) for k,v in self.settings.items()};updated[kind]=dict(mode=mode,profile_id=ident)
self.path.parent.mkdir(parents=True,exist_ok=True);temp=self.path.with_suffix('.tmp');temp.write_text(json.dumps(updated));temp.replace(self.path)
self.settings=updated;self.errors.pop(kind,None);self.retry_after={k:v for k,v in self.retry_after.items() if k[0]!=kind}
worker=self.tts if kind=='tts' else self.stt;worker.policy=mode
if kind=='tts':
for cpu_worker in self.cpu_workers:cpu_worker.policy=mode
if mode=='per_request':
for worker in ([self.tts,*self.cpu_workers] if kind=='tts' else [worker]):
with worker.lock:active=bool(worker.job and worker.job.get('state')=='running')
if not active:worker.unload_idle()
return self.status()
def _loop(self):
while True:
time.sleep(2)
self.reconcile()
def reconcile(self):
"""Resolve automatic TTS from endpoint publication, never a model name."""
with self.lock:settings={k:dict(v) for k,v in self.settings.items()}
if self.endpoint.state!='running' or self.scheduler.gpu_mode=='restoring':return
for kind,worker in (('stt',self.stt),('tts',self.tts)):
item=settings[kind];ident=item['profile_id']
automatic=kind=='tts' and item['mode']=='auto'
if not automatic and item['mode']!='warm':continue
if kind=='tts' and self.cpu_workers:
from pocket_runtime import supported
from kikiri_runtime import supported as kikiri_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.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.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
if other is self.tts and getattr(other,'shared_clone_resident',False):continue
with other.lock:busy=other.warming or other.job and other.job.get('state')=='running'
if not busy and other.process:other.unload_idle()
if kind=='tts' and worker is self.tts and getattr(worker,'shared_clone_resident',False):
with worker.lock:
if worker.process and worker.process.poll() is None:continue
if kind=='tts' and worker not in self.cpu_workers:
with self.scheduler.cv:
if self.scheduler.gpu_mode!='llm' or self.scheduler.transition or self.scheduler.queue or self.scheduler.key and self.scheduler.key[0]!='chat':continue
if automatic:
rows=[p for p in self.endpoint.rows() if p['kind']=='audio' and p['enabled']]
if len(rows)!=1 or not rows[0]['runnable']:
with worker.lock:busy=worker.warming or worker.job and worker.job.get('state')=='running'
if not busy:worker.unload_idle()
with self.lock:
if len(rows)>1:self.errors[kind]='Mehrere TTS-Profile freigegeben. Für automatisches Vorladen genau eines freigeben oder unter „Immer bereit“ ein Profil auswählen.'
elif rows:self.errors[kind]='Das freigegebene TTS-Profil ist nicht ausführbar. Einrichtung und Komponenten prüfen.'
else:self.errors.pop(kind,None)
continue
ident=rows[0]['id']
if kind=='stt' and item['mode']=='warm':
rows=[p for p in self.endpoint.rows() if p['kind']=='stt' and p['enabled'] and p['runnable']]
if len(rows)==1:ident=rows[0]['id']
with worker.lock:
if worker.warming or worker.job and worker.job.get('state')=='running':continue
loaded=bool(worker.process and worker.process.poll() is None)
if loaded and kind=='stt' and isinstance(getattr(worker,'session_device',None),str):
profile=next((p for p in self.profiles.status()['profiles'] if p['id']==ident),None)
if profile is None or worker.session_device!=worker.device(profile):loaded=False
if loaded and ((not automatic and kind!='stt') or getattr(worker,'profile_id',ident)==ident):continue
if loaded:worker.unload_idle()
with self.lock:
retry_key=(kind,ident)
if time.monotonic()<self.retry_after.get(retry_key,0):continue
try:
worker.warm(ident)
with self.lock:self.errors.pop(kind,None)
except Exception as exc:
with self.lock:
self.errors[kind]=str(exc) if isinstance(exc,ValueError) else 'Vorladen fehlgeschlagen. Ressourcen und Laufzeit prüfen.'
self.retry_after[retry_key]=time.monotonic()+60