"""Persistent Q8/Q4 CPU worker. Native stdout is excluded from the JSON protocol.""" import json,os,resource,sys,time,wave from pathlib import Path from contextlib import closing class JobCancellation: def __init__(self,root):self.marker=root/'cancel' def is_set(self):return self.marker.exists() def onset_profile(quant): if quant=='Q8':return 'qwen3_tts_12hz_0_6b_base_q8_v1' if quant=='Q4':return 'off' raise ValueError('Unbekannte Qwen-Quantisierung.') def thread_options(generation=4,codec=4): if any(type(n) is not int or not 1<=n<=4 for n in (generation,codec)):raise ValueError('Ungültige Qwen-Threadzahl.') return dict(cpu_threads=generation,cpu_codec_threads=codec) def main(): protocol=os.fdopen(os.dup(1),'w',buffering=1);os.dup2(2,1) def emit(value):protocol.write(json.dumps(value)+'\n');protocol.flush() try: quant=sys.argv[4] if len(sys.argv)>4 else 'Q8' onset=onset_profile(quant) cpus=sys.argv[5] if len(sys.argv)>5 else '' threads=thread_options(int(sys.argv[6]),int(sys.argv[7])) if len(sys.argv)>7 else thread_options() os.nice(10) resource.setrlimit(resource.RLIMIT_AS,(8*1024**3,8*1024**3)) import numpy as np import qwentts_cpp_cpu as q from tts_worker import spoken_chunks assert q.CPU_ONLY is True and q.QT_ABI_VERSION==5 # Inherit the process's TTS CPU set. Additional per-thread native pinning # oversubscribes two physical cores when generation and codec overlap. model=q.QwenTTS(sys.argv[1],sys.argv[2],cpu_stream_frames=2,clamp_fp16=False,use_fa=True,**threads) voices={} def voice_for(path): path=Path(path);key=(str(path),path.stat().st_mtime_ns) if key not in voices: with wave.open(str(path),'rb') as w: if w.getframerate()!=24000 or w.getnchannels()!=1 or w.getsampwidth()!=2:raise ValueError('Qwen-Referenz benötigt 24 kHz Mono PCM16.') samples=np.frombuffer(w.readframes(min(w.getnframes(),24000*120)),dtype='32*1024**2:raise ValueError('Qwen-Audio überschreitet Größenlimit.') if request.get('streaming'): tmp=root/'chunk.tmp';tmp.write_bytes(pcm);tmp.replace(root/f'chunk-{index:06d}.pcm');index+=1 if model.last_stream_profile.get('producer_alive_after_close'):raise RuntimeError('Native Synthese hat den Abbruch noch nicht bestätigt.') if cancel.is_set():raise InterruptedError() if not parts:raise ValueError('Keine Audiodaten erzeugt.') with wave.open(str(root/'result.wav'),'wb') as w: w.setnchannels(1);w.setsampwidth(2);w.setframerate(24000);w.writeframes(b''.join(parts)) result=dict(ok=True,quant=quant,duration=total/48000,sample_rate=24000,seconds=time.monotonic()-start,first_chunk_seconds=first) except InterruptedError:result=dict(ok=True,cancelled=True,seconds=time.monotonic()-start) except Exception as exc:result=dict(ok=False,error='Native Qwen-Spracherzeugung fehlgeschlagen ('+type(exc).__name__+').') tmp=root/'result.tmp';tmp.write_text(json.dumps(result));tmp.replace(root/'result.json') model.close() return 0 if __name__=='__main__':sys.exit(main())