Files
Athena-Deck/pocket.py
T

116 lines
7.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""CPU Pocket jobs; deliberately independent of GPU reservations/LLM eviction."""
import json,os,re,select,subprocess,threading,time,uuid
from pathlib import Path
from tts_test import TTSTests
from pocket_runtime import supported,TOKENIZER_REVISION
class Pocket(TTSTests):
name='Pocket'
cooperative_cancel=False
def __init__(self,*args):
super().__init__(*args);self.gate=threading.Lock();self.session_key=None
def voice_path(self,name):
folder=self.root.parent/'speech-voices'
if name=='default':
try:name=json.loads((folder/'default.json').read_text())['voice']
except (OSError,ValueError,KeyError,TypeError):raise ValueError('Standardstimme unter speech-voices/default.json fehlt.') from None
if not isinstance(name,str) or not re.fullmatch(r'[A-Za-z0-9_-]{1,64}',name):raise ValueError('Ungültiger Pocket-Stimmname.')
path=folder/name/'pocket-german.safetensors'
if (folder/name).is_symlink() or path.is_symlink() or not path.resolve().is_relative_to(folder.resolve()):raise ValueError('Pocket-Stimmprofil muss im eigenen Stimmenordner liegen.')
if not path.is_file():raise ValueError('Gespeichertes Pocket-Stimmprofil '+name+' fehlt. Stimme zuerst mit dem deutschen Klonmodell exportieren.')
return path.resolve()
def blockers(self,p):
if not supported(p.get('model')):return ['Dieses Pocket-Modell ist noch nicht qualifiziert. Deutsches Pocket-3.3-Rezept verwenden.']
errors=[]
if not self.runtime.status()['installed']:errors.append('Pocket-CPU-Laufzeit unter TTS → Einrichten installieren.')
try:
tokenizer=self.profiles._component(p['model'],'tokenizer',p.get('components',{}).get('tokenizer'))
if tokenizer['revision']!=TOKENIZER_REVISION:raise ValueError()
except ValueError:errors.append('Den geprüften deutschen Pocket-Tokenizer zuordnen.')
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('Pocket-Profil ist nicht ausführbar.')
return p
def _ensure_cpu(self,p):
tokenizer=self.profiles._component(p['model'],'tokenizer',p.get('components',{}).get('tokenizer'))
key=(p['id'],p['revision'],tokenizer['id'],str(self.runtime.paths()[0]))
if self.process and self.process.poll() is None and self.session_key==key:return self.process
self.unload_idle();self.root.mkdir(parents=True,exist_ok=True,mode=0o700)
model=self.profiles.catalog.root/p['model']['id']/'model.safetensors'
tok=self.profiles.catalog.root/tokenizer['id']/'model.json'
env={k:v for k,v in os.environ.items() if not k.startswith(('HF_','LLAMA_','DECK_'))}
env.update(CUDA_VISIBLE_DEVICES='',HF_HUB_OFFLINE='1',HF_HUB_DISABLE_IMPLICIT_TOKEN='1',OMP_NUM_THREADS='4',MKL_NUM_THREADS='4')
process=subprocess.Popen([str(self.runtime.paths()[0]),str(Path(__file__).with_name('pocket_worker.py')),str(model),str(tok),str(self.root/'german.yaml')],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 Pocket.')
line=process.stdout.readline()
try:ready=json.loads(line)
except ValueError:ready={}
if not ready.get('ready'):self.unload_idle();raise ValueError(ready.get('error','Pocket-CPU-Worker konnte nicht starten.'))
self.session_key=key;return process
def warm(self,profile_id):
if not self.gate.acquire(False):return False
try:
with self.lock:self.warming=True;self.cancel.clear()
self._ensure_cpu(self._profile(profile_id));return True
finally:
with self.lock:self.warming=False
self.gate.release()
def prepare_reference(self,audio):raise ValueError('Dieses Profil unterstützt keine eigene Referenz.')
def start(self,profile_id,text,speaker='default',language='German',wait=False,speed=None,streaming=False,reference=None):
if not isinstance(text,str) or not 1<=len(text.strip())<=1000:raise ValueError('Text mit 1–1000 Zeichen erforderlich.')
if language not in ('German','german','de',''):raise ValueError('Dieses Pocket-Profil unterstützt Deutsch.')
if speed is not None and (type(speed) not in (int,float) or speed!=1):raise ValueError('Pocket unterstützt hier speed=1. Geschwindigkeit im Client einstellen.')
if type(streaming) is not bool:raise ValueError('Ungültiger Streaming-Modus.')
reference=self.prepare_reference(reference) if reference is not None else None
voice=self.voice_path(speaker) if reference is None else None;p=self._profile(profile_id)
if not self.gate.acquire(timeout=300 if wait else 0):raise ValueError('Pocket ist beschäftigt. Anfrage erneut versuchen.')
try:
ident=uuid.uuid4().hex;self.root.mkdir(parents=True,exist_ok=True,mode=0o700)
directory=self.root/ident;directory.mkdir(mode=0o700)
if reference is not None:
voice=directory/'reference.wav';voice.write_bytes(reference)
with self.lock:self.cancel.clear();self.job=dict(id=ident,state='running',phase=self.name+' · CPU',profile_id=profile_id,started_at=time.time())
threading.Thread(target=self._run_cpu,args=(p,ident,text,voice,streaming),daemon=True).start()
return dict(self.job)
except Exception:self.gate.release();raise
def _run_cpu(self,p,ident,text,voice,streaming):
directory=self.root/ident;state='failed';phase=self.name+'-Spracherzeugung fehlgeschlagen.';cancel_reusable=False
try:
process=self._ensure_cpu(p)
if self.cancel.is_set():
cancel_reusable=self.cooperative_cancel and process.poll() is None
raise InterruptedError()
process.stdin.write(json.dumps(dict(output=str(directory),text=text,voice=str(voice),streaming=streaming))+'\n');process.stdin.flush()
end=time.monotonic()+600
while not (directory/'result.json').is_file():
if self.cooperative_cancel:
if self.cancel.is_set():(directory/'cancel').touch()
time.sleep(.05)
elif self.cancel.wait(.05):raise InterruptedError()
if process.poll() is not None:raise ValueError(self.name+'-CPU-Worker wurde beendet. RAM und Laufzeit prüfen.')
if time.monotonic()>end:raise ValueError(self.name+'-Zeitlimit überschritten.')
result=json.loads((directory/'result.json').read_text())
if self.cooperative_cancel and (result.get('cancelled') or self.cancel.is_set()):
cancel_reusable=bool(result.get('ok') and process.poll() is None)
if not cancel_reusable:raise ValueError(result.get('error',self.name+'-Abbruch konnte nicht bestätigt werden.'))
raise InterruptedError()
if not result.get('ok'):raise ValueError(result.get('error',self.name+' fehlgeschlagen.'))
if self.cancel.is_set():raise InterruptedError()
if not 0<(directory/'result.wav').stat().st_size<=32*1024**2:raise ValueError('Ungültige Pocket-Audioausgabe.')
with self.lock:self.job.update({k:result[k] for k in ('duration','sample_rate','seconds','first_chunk_seconds')})
state='complete';phase=self.name+'-Sprache fertig · CPU'
except InterruptedError:state='cancelled';phase=self.name+' abgebrochen.'
except Exception as exc:phase=str(exc) if isinstance(exc,ValueError) else self.name+'-Ausführung fehlgeschlagen ('+type(exc).__name__+').'
finally:
if self.policy=='per_request' or state!='complete' and not (state=='cancelled' and cancel_reusable):self.unload_idle()
if state=='complete':(directory/'complete').touch()
else:
for f in directory.glob('chunk-*.pcm'):f.unlink(missing_ok=True)
with self.lock:
self.job.update(state=state,phase=phase,finished_at=time.time());(directory/'job.json').write_text(json.dumps(self.job))
if voice==directory/'reference.wav':voice.unlink(missing_ok=True)
self.gate.release()