Files
Athena-Deck/articulino_worker.py
T

55 lines
2.9 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.
"""Bounded sentence PCM/WAV protocol. Private text/voice never sent to a service."""
import contextlib,json,os,sys,time,wave
from pathlib import Path
RATE=24000
MAX_PCM=32*1024**2
def generate(tts,request):
import numpy as np
from speech_text import prepare_for_speech
directory=Path(request['output']);cancel=directory/'cancel';started=time.monotonic();first=None;total=0;count=0
text=request['text']
if not isinstance(text,str) or not 1<=len(text.strip())<=1000:raise ValueError('Text mit 1–1000 Zeichen erforderlich.')
# Preserve Deck's common German pronunciation/Markdown handling, then let the
# model's own frontend perform its native sentence segmentation/normalization.
text=prepare_for_speech(text,'German')
tts.set_voice(request['voice']) # Official loader truncates to eight seconds.
with wave.open(str(directory/'result.wav'),'wb') as out:
out.setnchannels(1);out.setsampwidth(2);out.setframerate(RATE)
stream=tts.stream(text,language='de',seed=42,normalize=True)
try:
for chunk in stream:
if cancel.exists():return dict(ok=True,cancelled=True)
chunk=np.asarray(chunk)
if chunk.ndim!=1 or not chunk.size or not np.isfinite(chunk).all():raise ValueError('Ungültige Articulino-Audioausgabe.')
pcm=(np.clip(chunk,-1,1)*32767).astype('<i2').tobytes();total+=len(pcm)
if total>MAX_PCM:raise ValueError('Articulino-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('Articulino lieferte kein Audio.')
return dict(ok=True,duration=total/2/RATE,sample_rate=RATE,seconds=time.monotonic()-started,first_chunk_seconds=first)
def main():
# Keep the line-based control channel free of upstream progress output.
control=sys.stdout
with contextlib.redirect_stdout(sys.stderr):
from articulino_onnx import TTS
from articulino_runtime import verify_assets
verify_assets(sys.argv[1]);os.nice(10)
tts=TTS.from_pretrained(Path(sys.argv[1]),precision='fp32',providers=['CPUExecutionProvider'],threads=4)
assert all(s.get_providers()==['CPUExecutionProvider'] for s in tts.engine.sessions.values())
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(tts,request)
except Exception:result=dict(ok=False,error='Articulino-Erzeugung fehlgeschlagen. Referenz, Laufzeit und Ressourcen prüfen.')
temp=directory/'result.tmp';temp.write_text(json.dumps(result));temp.replace(directory/'result.json')
if __name__=='__main__':main()