Files
Athena-Deck/kikiri_runtime.py
T

84 lines
4.7 KiB
Python

"""Pinned CPU inference with a separately restored private Anna bundle."""
import hashlib,json,os,shutil,sys,time
from pathlib import Path
from ltx_original_runtime import LTXOriginalRuntime
VERSION='1.0.0'
REVISION='kikiri-anna-plus20-cpu-v1'
REPO='local/kikiri-anna'
MODEL_SHA='eac26cd33205c3ea3054102943ea956dd9f56e1751a5203bb7788fbbfd3d7d53'
MODEL_REVISION=MODEL_SHA # Local content revision, not a public Git commit.
MODEL_FILE='anna-full20-plus20.pth'
ASSETS={
'model.pth':(327187851,MODEL_SHA),
'voice.pt':(523739,'5c5f913c31155bc55c89076b1c46d58f4a843b45494e3b8dacfa9851484a8ee7'),
'config.json':(None,'5abb01e2403b072bf03d04fde160443e209d7a0dad49a423be15196b9b43c17f')}
def supported(model):
return bool(model and model.get('kind')=='audio' and model.get('repo')==REPO and model.get('revision')==MODEL_REVISION and model.get('file')==MODEL_FILE and model.get('sha256')==MODEL_SHA)
def verify_assets(directory):
directory=Path(directory)
if directory.is_symlink():raise ValueError('Kikiri-Stimmordner darf kein Symlink sein.')
for name,(size,expected) in ASSETS.items():
path=directory/name
if path.is_symlink() or not path.is_file() or size is not None and path.stat().st_size!=size:raise ValueError('Kikiri-Datei fehlt oder ist unvollständig: '+name)
with path.open('rb') as f:digest=hashlib.file_digest(f,'sha256').hexdigest()
if digest!=expected:raise ValueError('Kikiri-Prüfsumme abweichend: '+name)
class KikiriRuntime(LTXOriginalRuntime):
name='Kikiri Anna · CPU'
def __init__(self,root):super().__init__(root,None)
def paths(self):
bundle=self.root.parent/'kikiri-data/anna-plus20'
try:
ident=json.loads((self.root/'active.json').read_text())['id']
if len(ident)==32 and all(c in '0123456789abcdef' for c in ident):
base=self.root/ident
if (base/'ready').read_text().strip()==REVISION:return base/'venv/bin/python',bundle
except (OSError,ValueError,KeyError,TypeError):pass
return self.root/'missing-python',bundle
def status(self):
python,bundle=self.paths()
private=all(not (bundle/n).is_symlink() and (bundle/n).is_file() and (size is None or (bundle/n).stat().st_size==size) for n,(size,_) in ASSETS.items())
return dict(installed=python.is_file() and private,environment_installed=python.is_file(),voice_installed=private,
revision=REVISION,version=VERSION,device='cpu',required_disk_gib=3,job=dict(self.job) if self.job else None,
speakers=['default','Anna'],languages=['German'],origin='https://github.com/semidark/kikiri-tts')
def ensure_library(self):
_,bundle=self.paths();verify_assets(bundle)
ident=hashlib.sha256((REPO+MODEL_REVISION+MODEL_FILE).encode()).hexdigest()
target=self.root.parent/'models'/ident
if target.is_symlink():raise ValueError('Ungültiger Kikiri-Bibliotheksordner.')
target.mkdir(parents=True,exist_ok=True,mode=0o700);dest=target/'model.pth'
if not dest.exists():
temp=target/'import.tmp'
try:os.link(bundle/'model.pth',temp)
except OSError:shutil.copyfile(bundle/'model.pth',temp)
temp.chmod(0o600);temp.replace(dest)
if dest.is_symlink():raise ValueError('Ungültige Kikiri-Modelldatei.')
with dest.open('rb') as f:digest=hashlib.file_digest(f,'sha256').hexdigest()
if digest!=MODEL_SHA:raise ValueError('Vorhandenes Kikiri-Modell abweichend; nicht überschrieben.')
entry=dict(repo=REPO,revision=MODEL_REVISION,file=MODEL_FILE,size=ASSETS['model.pth'][0],sha256=digest,
kind='audio',state='downloaded',runtime_ready=True,local_only=True,downloaded_at=time.time())
temp=target/'entry.tmp';temp.write_text(json.dumps(entry));temp.chmod(0o600);temp.replace(target/'entry.json')
return ident
def _run(self):
base=self.root/self.job['id'];state='failed';phase='Kikiri-CPU-Einrichtung fehlgeschlagen.'
try:
verify_assets(self.paths()[1])
base.mkdir(mode=0o700)
env={k:v for k,v in os.environ.items() if not k.startswith(('HF_','DECK_','LLAMA_','OPENAI_'))}
env.update(CUDA_VISIBLE_DEVICES='',HF_HUB_DISABLE_IMPLICIT_TOKEN='1',GIT_TERMINAL_PROMPT='0',HOME=str(base))
self._phase('Eigene gepinnte Kikiri-CPU-Umgebung erstellen · keine GPU')
self._command([sys.executable,Path(__file__).parent/'deploy/kikiri/install.py','--root',base],env)
if self.cancel.is_set():raise InterruptedError()
self.ensure_library()
(base/'ready').write_text(REVISION)
temp=self.root/'active.tmp';temp.write_text(json.dumps({'id':base.name}));temp.replace(self.root/'active.json')
state='complete';phase='Kikiri Anna CPU bereit · Endpunktfreigabe separat'
except InterruptedError:state='cancelled';phase='Kikiri-Einrichtung abgebrochen.'
except Exception as exc:phase=str(exc)
finally:
if state!='complete':shutil.rmtree(base,ignore_errors=True)
with self.lock:self.process=None;self.job.update(state=state,phase=phase,finished_at=time.time());self._save()