Keep native Qwen TTS resident after cooperative stream cancellation

This commit is contained in:
Mikei386 committed 2026-10-19 12:03:47 +02:00
1 parent 3435379ce0
commit 182c8a1e8f
6 files changed
+98 -14

No files matched your search

+19 -8
View File
@@ -1,6 +1,11 @@
"""Persistent Q8 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 main():
protocol=os.fdopen(os.dup(1),'w',buffering=1);os.dup2(2,1)
@@ -30,19 +35,25 @@ def main():
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
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')):
for chunk,rate in model.stream(text=text,lang='german',ref_spk_emb=voice,seed=42,do_sample=False,max_new_tokens=1024,onset_silence_profile='qwen3_tts_12hz_0_6b_base_q8_v1'):
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 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='qwen3_tts_12hz_0_6b_base_q8_v1',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,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()