Files
Athena-Deck/kikiri_worker.py
T

91 lines
4.6 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.
"""Offline FP32 Anna +20, narrow Vögel fix, bounded WAV/PCM protocol."""
import contextlib,json,os,re,sys,time,unicodedata,wave
from pathlib import Path
RATE=24000
MAX_PCM=32*1024**2
WORD=re.compile(r'\bvögel(?:n|chen)?\b',re.IGNORECASE)
PHONE=re.compile(r'(?<!\S)v(?=ˈøːɡəl(?:n|çən)?(?=[\s.,!?;:]|$))')
def correct(text,phonemes):
return PHONE.sub('f',phonemes) if WORD.search(unicodedata.normalize('NFC',text)) else phonemes
def generate(pipeline,voice,request,vocab,reset_seed):
import numpy as np
text=request['text']
if not isinstance(text,str) or not 1<=len(text.strip())<=1000:raise ValueError('Text mit 1–1000 Zeichen erforderlich.')
directory=Path(request['output']);cancel=directory/'cancel'
reset_seed();started=time.monotonic();first=None;total=0;count=0
# Native pipeline segmentation only: no additional sentence gaps, breath
# smoothing, pitch change or synthetic voice/reference replacement.
with wave.open(str(directory/'result.wav'),'wb') as out:
out.setnchannels(1);out.setsampwidth(2);out.setframerate(RATE)
stream=pipeline(text,voice=voice,speed=1)
try:
for result in stream:
if cancel.exists():return dict(ok=True,cancelled=True)
if not result.phonemes or len(result.phonemes)>510 or any(c not in vocab for c in result.phonemes):raise ValueError('Kikiri-Phoneme unvollständig; keine gekürzte Ausgabe.')
chunk=result.audio.detach().cpu().numpy().reshape(-1)
if not chunk.size or not np.isfinite(chunk).all():raise ValueError('Ungültige Kikiri-Audioausgabe.')
pcm=(np.clip(chunk,-1,1)*32767).astype('<i2').tobytes();total+=len(pcm)
if total>MAX_PCM:raise ValueError('Kikiri-Audio überschreitet 32 MiB.')
if first is None:first=time.monotonic()-started
out.writeframes(pcm)
if request.get('streaming'):
temp=directory/f'chunk-{count:06d}.tmp';temp.write_bytes(pcm);temp.replace(temp.with_suffix('.pcm'))
count+=1
finally:
if hasattr(stream,'close'):stream.close()
if cancel.exists():return dict(ok=True,cancelled=True)
if not total:raise ValueError('Kikiri lieferte kein Audio.')
return dict(ok=True,duration=total/2/RATE,sample_rate=RATE,seconds=time.monotonic()-started,first_chunk_seconds=first)
def load(bundle):
import random,numpy as np,torch
from kokoro import KModel,KPipeline
from kikiri_runtime import verify_assets
verify_assets(bundle)
assert torch.version.cuda is None and not torch.cuda.is_available(),'CPU-only Torch required'
torch.set_num_threads(4);torch.set_num_interop_threads(1)
def seed():random.seed(42);np.random.seed(42);torch.manual_seed(42)
seed()
model=KModel(repo_id='hexgrad/Kokoro-82M',config=str(bundle/'config.json'),model=str(bundle/'model.pth')).to('cpu').eval()
weights=torch.load(bundle/'model.pth',map_location='cpu',weights_only=True)
for name,state in weights.items():
component=getattr(model,name);state={k.removeprefix('module.'):v for k,v in state.items()}
result=component.load_state_dict(state,strict=False)
assert not result.unexpected_keys
current=component.state_dict()
for key in result.missing_keys:
path,param=key.rsplit('.',1);layer=component.get_submodule(path)
assert isinstance(layer,torch.nn.InstanceNorm1d) and layer.affine and param in ('weight','bias')
assert torch.all(current[key]==(1 if param=='weight' else 0))
state[key]=current[key]
component.load_state_dict(state,strict=True)
del weights
voice=torch.load(bundle/'voice.pt',map_location='cpu',weights_only=True)
assert voice.shape==(510,1,256) and torch.isfinite(voice).all()
pipeline=KPipeline(lang_code='d',repo_id='hexgrad/Kokoro-82M',model=model,device='cpu');g2p=pipeline.g2p
def front(text):
phones,tokens=g2p(text)
return correct(text,phones.replace('ʏ','y')),tokens
pipeline.g2p=front
# Warm the frontend and decoder before announcing readiness.
list(pipeline('Die Stimme ist bereit.',voice=voice,speed=1))
return pipeline,voice,model.vocab,seed
def main():
control=sys.stdout
try:
with contextlib.redirect_stdout(sys.stderr):
os.nice(10);pipeline,voice,vocab,seed=load(Path(sys.argv[1]))
except Exception:
print(json.dumps(dict(ready=False,error='Kikiri-CPU-Laufzeit oder Anna-Stand ungültig.')),file=control,flush=True);return
print(json.dumps(dict(ready=True,sample_rate=RATE,device='cpu')),file=control,flush=True)
for line in sys.stdin:
request=json.loads(line);directory=Path(request['output'])
try:
with contextlib.redirect_stdout(sys.stderr):result=generate(pipeline,voice,request,vocab,seed)
except Exception:result=dict(ok=False,error='Kikiri-Erzeugung fehlgeschlagen. Text, Laufzeit und Ressourcen prüfen.')
temp=directory/'result.tmp';temp.write_text(json.dumps(result));temp.replace(directory/'result.json')
if __name__=='__main__':main()