"""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 streaming_wave(model,request): import numpy as np root=Path(request['output']);parts=[];rate=None;index=0;total=0 for text in text_chunks(request['text']): 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('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) # 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 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']) # 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())