57 lines
2.8 KiB
Python
57 lines
2.8 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 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)
|
|
# 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)
|
|
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])
|
|
# 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'])
|
|
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())
|