Files
Athena-Deck/pocket_worker.py
T

36 lines
2.0 KiB
Python

"""Resident offline Pocket worker; emits 24kHz mono PCM chunks and WAV."""
import json,sys,time,os
from pathlib import Path
def main():
import torch,numpy as np,soundfile as sf,yaml,pocket_tts
from pocket_tts import TTSModel
torch.set_num_threads(4)
config=yaml.safe_load((Path(pocket_tts.__file__).parent/'config/german.yaml').read_text())
config['weights_path']=sys.argv[1];config['weights_path_without_voice_cloning']=None
config['flow_lm']['lookup_table']['tokenizer_path']=sys.argv[2]
config_path=Path(sys.argv[3]);config_path.write_text(yaml.safe_dump(config))
try:
model=TTSModel.load_model(config=config_path)
assert model.has_voice_cloning
print(json.dumps({'ready':True}),flush=True)
except Exception:
print(json.dumps({'ready':False,'error':'Pocket konnte die lokalen deutschen Gewichte nicht laden.'}),flush=True);return
voices={}
for line in sys.stdin:
request=json.loads(line);root=Path(request['output']);start=time.monotonic()
try:
voice=Path(request['voice']);key=(str(voice),voice.stat().st_mtime_ns)
if key not in voices:voices={key:model.get_state_for_audio_prompt(voice)}
chunks=[];first=None
for i,chunk in enumerate(model.generate_audio_stream(voices[key],request['text'])):
a=chunk.detach().cpu().numpy().reshape(-1);chunks.append(a)
if first is None:first=time.monotonic()-start
if request.get('streaming'):
pcm=(np.clip(a,-1,1)*32767).astype('<i2').tobytes()
temp=root/'chunk.tmp';temp.write_bytes(pcm);temp.replace(root/f'chunk-{i:06d}.pcm')
audio=np.concatenate(chunks);sf.write(root/'result.wav',audio,model.sample_rate)
result=dict(ok=True,duration=len(audio)/model.sample_rate,sample_rate=model.sample_rate,seconds=time.monotonic()-start,first_chunk_seconds=first)
except Exception as exc:result=dict(ok=False,error='Pocket-Spracherzeugung fehlgeschlagen ('+type(exc).__name__+').')
temp=root/'result.tmp';temp.write_text(json.dumps(result));temp.replace(root/'result.json')
if __name__=='__main__':main()