Files
Athena-Deck/tts_worker.py
T

53 lines
2.4 KiB
Python

"""Persistent offline Qwen-TTS worker; line-delimited stdin, no prompt logging."""
import contextlib,json,re,sys
from pathlib import Path
def text_chunks(text,limit=256):
chunks=[];current=''
for sentence in re.split(r'(?<=[.!?])\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 main():
model_path=sys.argv[1]
try:
with contextlib.redirect_stdout(sys.stderr):
import torch,soundfile as sf
from qwen_tts import Qwen3TTSModel
model=Qwen3TTSModel.from_pretrained(model_path,device_map='cuda:0',dtype=torch.bfloat16,attn_implementation='sdpa',local_files_only=True)
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):
for text in text_chunks(request['text']):
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])
# Release temporary allocator blocks between sentences; weights stay loaded.
torch.cuda.empty_cache()
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'])
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())