Files
Athena-Deck/tts_worker.py

104 lines
5.4 KiB
Python

"""Persistent offline Qwen-TTS worker; line-delimited stdin, no prompt logging."""
import contextlib,json,re,sys
from speech_text import prepare_for_speech
from pathlib import Path
class PresetBaseModel:
"""Keep the old router's preset embeddings and Base voice-clone path."""
def __init__(self,model,presets):self.model=model;self.presets=presets
def _kwargs(self,text,language,speaker,**kwargs):
return dict(text=text,language=language,voice_clone_prompt=[self.presets[speaker.lower()]],**kwargs)
def generate_custom_voice(self,**kwargs):return self.model.generate_voice_clone(**self._kwargs(**kwargs))
def generate_custom_voice_streaming(self,**kwargs):return self.model.generate_voice_clone_streaming(**self._kwargs(**kwargs))
def _warmup(self,**kwargs):return self.model._warmup(**kwargs)
def base_presets():
import torch
from safetensors.torch import load_file
from qwen_tts import VoiceClonePromptItem
rows=load_file(str(Path(__file__).parent/'assets/tts-presets/bundle.safetensors'))
return {name:VoiceClonePromptItem(ref_code=None,ref_spk_embedding=row.to(device='cuda:0',dtype=torch.bfloat16).contiguous(),x_vector_only_mode=True,icl_mode=False,ref_text=None) for name,row in rows.items()}
def text_chunks(text,limit=256):
chunks=[];current=''
for sentence in re.split(r'(?<=[!?])\s+|(?<!\d\.)(?<=\.)\s+',text.strip()):
for word in re.findall(r'\S+\s*',sentence+' '):
if current and len(current)+len(word)>limit:chunks.append(current.strip());current=''
while len(word.strip())>limit:
chunks.append(word[:limit]);word=word[limit:]
current+=word
if current:chunks.append(current.strip());current=''
return chunks
def spoken_chunks(request):
text=prepare_for_speech(request['text'],request['language'])
if not text:raise ValueError('No speakable text')
return text_chunks(text)
def streaming_wave(model,request):
import numpy as np
root=Path(request['output']);parts=[];rate=None;index=0;total=0
for text in spoken_chunks(request):
for audio,current_rate,_ in model.generate_custom_voice_streaming(text=text,language=request['language'],speaker=request['speaker'],max_new_tokens=1024,chunk_size=4):
if current_rate!=24000 or rate is not None and rate!=current_rate:raise ValueError('Unsupported streaming sample rate')
rate=current_rate;wave=np.asarray(audio).reshape(-1)
if not len(wave):continue
if not np.isfinite(wave).all():raise ValueError('Invalid audio samples')
pcm=(np.clip(wave,-1,1)*32767).astype('<i2').tobytes();total+=len(pcm)
if total>32*1024**2:raise ValueError('Streaming audio too large')
# Atomic publication: consumers never see a partial PCM chunk.
tmp=root/'chunk.tmp';tmp.write_bytes(pcm);tmp.replace(root/f'chunk-{index:06d}.pcm')
parts.append(wave);index+=1
if not parts:raise ValueError('Empty streaming audio')
return np.concatenate(parts),rate
def main():
model_path=sys.argv[1]
try:
with contextlib.redirect_stdout(sys.stderr):
import torch,soundfile as sf
from faster_qwen3_tts import FasterQwen3TTS
torch.set_float32_matmul_precision('high')
model=FasterQwen3TTS.from_pretrained(model_path,device='cuda:0',dtype=torch.bfloat16,attn_implementation='sdpa',backend='torch',local_files_only=True)
config=Path(model_path)/'config.json'
if config.is_file() and json.loads(config.read_text()).get('tts_model_type')=='base':model=PresetBaseModel(model,base_presets())
# Pinned 0.3.0 uses this entry point; capture before advertising readiness.
model._warmup(prefill_len=100)
# Initialize the codec too, so its first-use cost stays out of live replies.
model.generate_custom_voice(text="Hallo.",language="German",speaker="Ryan",max_new_tokens=32)
torch.cuda.empty_cache()
except Exception as exc:
print(json.dumps(dict(ready=False,error='CUDA-Speicher reicht nicht aus.' if 'outofmemory' in type(exc).__name__.lower() or 'out of memory' in str(exc).lower() else 'TTS-Modell konnte nicht geladen werden.')),flush=True)
return 1
print(json.dumps(dict(ready=True)),flush=True)
for line in sys.stdin:
root=None
try:
request=json.loads(line);root=Path(request['output'])
pieces=[];rate=None
with contextlib.redirect_stdout(sys.stderr):
if request.get('streaming'):
wave,rate=streaming_wave(model,request);pieces=[wave]
else:
for text in spoken_chunks(request):
waves,current_rate=model.generate_custom_voice(text=text,language=request['language'],speaker=request['speaker'],max_new_tokens=1024)
if rate is not None and rate!=current_rate:raise ValueError('Inconsistent sample rate')
rate=current_rate;pieces.append(waves[0])
# Keep captured graph pools and model weights resident across sentences.
if len(pieces)==1:wave=pieces[0]
else:
import numpy as np
wave=np.concatenate(pieces)
if request['speed']!=1:
import librosa
wave=librosa.effects.time_stretch(wave,rate=request['speed'])
# Release unused codec workspace, not live graph buffers or model weights.
torch.cuda.empty_cache()
sf.write(root/'result.wav',wave,rate,subtype='PCM_16')
(root/'result.json').write_text(json.dumps(dict(ok=True,sample_rate=rate,duration=len(wave)/rate)))
except Exception as exc:
if root is not None:
(root/'result.json').write_text(json.dumps(dict(ok=False,error='CUDA-Speicher reicht nicht aus.' if 'outofmemory' in type(exc).__name__.lower() or 'out of memory' in str(exc).lower() else 'TTS-Ausführung fehlgeschlagen: '+type(exc).__name__)))
return 0
if __name__=='__main__':sys.exit(main())