70 lines
3.7 KiB
Python
70 lines
3.7 KiB
Python
"""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 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)
|
|
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
|
|
model=q.QwenTTS(sys.argv[1],sys.argv[2],cpu_threads=4,cpu_codec_threads=4,cpu_stream_frames=2,clamp_fp16=False,use_fa=True)
|
|
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='<i2').astype(np.float32)/32768
|
|
voices.clear();voices[key]=model.extract_voice_ref(samples).ref_spk_emb
|
|
return voices[key]
|
|
# Prepare the configured default voice before declaring residency ready.
|
|
voice_for(sys.argv[3])
|
|
emit(dict(ready=True,cpu_only=True,quant=quant))
|
|
except Exception as exc:
|
|
emit(dict(ready=False,error='Qwen-CPU konnte nicht laden ('+type(exc).__name__+').'));return 1
|
|
for line in sys.stdin:
|
|
request=json.loads(line);root=Path(request['output']);start=time.monotonic()
|
|
try:
|
|
voice=voice_for(request['voice']);parts=[];first=None;index=0;total=0;cancel=JobCancellation(root)
|
|
for text in spoken_chunks(dict(text=request['text'],language='German')):
|
|
if cancel.is_set():break
|
|
with closing(model.stream(text=text,lang='german',ref_spk_emb=voice,seed=42,do_sample=False,max_new_tokens=1024,onset_silence_profile=onset,cancel_event=cancel)) as stream:
|
|
for chunk,rate in stream:
|
|
if cancel.is_set():break
|
|
if rate!=24000 or not np.isfinite(chunk).all():raise ValueError('Ungültige Qwen-Audiodaten.')
|
|
if first is None:first=time.monotonic()-start
|
|
pcm=np.rint(np.clip(chunk,-1,1)*32767).astype('<i2').tobytes();parts.append(pcm);total+=len(pcm)
|
|
if total>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())
|