Files
Athena-Deck/tts_worker.py
T
Mikei386 c0bc5d3a1b Integrate Basalt telemetry and shared GPU speech runtimes
Publish the reviewed accumulated runtime, scheduler, profile, UI, native recipes and historical maintenance evidence. Includes Qwen GPU ASR correction and shared Anna/atelier ownership. Validated with 784 local tests, Python/JSON parsing and eight JavaScript syntax checks. Live GPU acceptance and full fresh-host restore limits remain documented.
2026-11-03 21:16:41 +01:00

127 lines
6.8 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(model=None,anna_reference=None):
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'))
presets={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()}
if anna_reference is not None:
presets['anna']=model.model.create_voice_clone_prompt(ref_audio=str(anna_reference),ref_text='',x_vector_only_mode=True)[0]
return presets
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 clone_wave(model,request):
# Keep request-local conditioning separate from every preset, especially Anna.
import torch
if not isinstance(model,PresetBaseModel):raise ValueError('Qwen-Base-Modell erforderlich.')
root=Path(request['output']);ref=root/'reference.wav'
if ref.is_symlink() or not ref.is_file():raise ValueError('Referenzaufnahme erforderlich.')
backend=model.model;ref_text=request.get('reference_text','').strip();pieces=[];rate=None
with torch.random.fork_rng(devices=[0]):
torch.manual_seed(request['seed'])
prompt=backend.model.create_voice_clone_prompt(ref_audio=str(ref),ref_text=ref_text,x_vector_only_mode=not bool(ref_text))
for text in spoken_chunks(request):
waves,current_rate=backend.generate_voice_clone(text=text,language=request['language'],voice_clone_prompt=prompt,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])
if len(pieces)==1:return pieces[0],rate
import numpy as np
return np.concatenate(pieces),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(model,sys.argv[2] if len(sys.argv)>2 else None))
# 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('kind')=='voice_clone':
wave,rate=clone_wave(model,request);pieces=[wave]
elif 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())