112 lines
5.0 KiB
Python
112 lines
5.0 KiB
Python
"""Isolated native A/B worker; reuses Anna in memory, never copies her reference."""
|
|
import json, os, resource, sys, threading, time, wave
|
|
from pathlib import Path
|
|
from contextlib import closing
|
|
|
|
protocol = os.fdopen(os.dup(1), 'w', buffering=1)
|
|
os.dup2(2, 1)
|
|
def emit(value):
|
|
protocol.write(json.dumps(value)+'\n')
|
|
protocol.flush()
|
|
|
|
def failure(kind, value, trace):
|
|
locations = []
|
|
while trace is not None:
|
|
locations.append(Path(trace.tb_frame.f_code.co_filename).name+':'+str(trace.tb_lineno))
|
|
trace = trace.tb_next
|
|
emit(dict(event='error', error_type=kind.__name__, locations=locations))
|
|
sys.excepthook = failure
|
|
|
|
config = json.loads(sys.stdin.readline())
|
|
os.sched_setaffinity(0, config['cpus'])
|
|
os.nice(10)
|
|
resource.setrlimit(resource.RLIMIT_AS, (8*1024**3, 8*1024**3))
|
|
os.environ.update(CUDA_VISIBLE_DEVICES='', HF_HUB_OFFLINE='1',
|
|
HF_HUB_DISABLE_IMPLICIT_TOKEN='1', OMP_NUM_THREADS='2',
|
|
OPENBLAS_NUM_THREADS='1', QWENTTS_CPU_FLASH_ATTN='0')
|
|
sys.path.insert(0, '/app')
|
|
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
|
|
start = time.monotonic()
|
|
model = q.QwenTTS(config['model'], config['codec'], cpu_threads=2,
|
|
cpu_codec_threads=2, cpu_stream_frames=2,
|
|
clamp_fp16=False, use_fa=True)
|
|
with wave.open(config['voice'], 'rb') as reference:
|
|
assert reference.getframerate() == 24000
|
|
assert reference.getnchannels() == 1 and reference.getsampwidth() == 2
|
|
samples = np.frombuffer(reference.readframes(min(reference.getnframes(), 24000*120)),
|
|
dtype='<i2').astype(np.float32)/32768
|
|
voice = model.extract_voice_ref(samples).ref_spk_emb
|
|
del samples
|
|
emit(dict(event='ready', pid=os.getpid(), load_seconds=time.monotonic()-start,
|
|
cpus=sorted(os.sched_getaffinity(0))))
|
|
|
|
try:
|
|
for line in sys.stdin:
|
|
request = json.loads(line)
|
|
if request['action'] == 'exit':
|
|
break
|
|
label = request['label']
|
|
assert label in ('warmup', 'q8-a', 'q8-b', 'q4-a', 'q4-b')
|
|
cancel = threading.Event()
|
|
watchdog = threading.Timer(60, cancel.set)
|
|
watchdog.daemon = True
|
|
started = time.monotonic()
|
|
watchdog.start()
|
|
first = latest = None
|
|
total = count = 0
|
|
maxgap = deficit = 0.0
|
|
pcm = []
|
|
profiles = []
|
|
emit(dict(event='started', at=started))
|
|
try:
|
|
for text in spoken_chunks(dict(text=request['text'], language='German')):
|
|
with closing(model.stream(text=text, lang='german', ref_spk_emb=voice,
|
|
seed=42, do_sample=False, max_new_tokens=1024,
|
|
onset_silence_profile='off', cancel_event=cancel)) as stream:
|
|
for chunk, rate in stream:
|
|
if cancel.is_set():
|
|
raise TimeoutError('Synthetic synthesis exceeded 60seconds')
|
|
assert rate == 24000 and np.isfinite(chunk).all()
|
|
now = time.monotonic()
|
|
if first is None:
|
|
first = now
|
|
else:
|
|
maxgap = max(maxgap, now-latest)
|
|
deficit = max(deficit, now-first-total/48000)
|
|
block = np.rint(np.clip(chunk, -1, 1)*32767).astype('<i2').tobytes()
|
|
pcm.append(block)
|
|
total += len(block)
|
|
latest = now
|
|
count += 1
|
|
assert total < 32*1024**2
|
|
profile = model.last_stream_profile
|
|
assert not profile.get('producer_alive_after_close')
|
|
# Only scalar technical counters; no embeddings or reference data.
|
|
profiles.append({k:v for k,v in profile.items()
|
|
if type(v) in (int,float,bool) or v is None})
|
|
ended = time.monotonic()
|
|
assert total and first is not None
|
|
if label != 'warmup':
|
|
output = Path(__file__).with_name(label+'.wav')
|
|
with wave.open(str(output), 'wb') as audio:
|
|
audio.setnchannels(1)
|
|
audio.setsampwidth(2)
|
|
audio.setframerate(24000)
|
|
audio.writeframes(b''.join(pcm))
|
|
emit(dict(event='result', started=started, ended=ended,
|
|
seconds=ended-started, first_pcm_seconds=first-started,
|
|
audio_seconds=total/48000, bytes=total,
|
|
rtf=(ended-started)/(total/48000), packets=count,
|
|
longest_packet_gap_seconds=maxgap,
|
|
required_buffer_after_first_pcm_seconds=max(0,deficit),
|
|
native_profiles=profiles,
|
|
rss_kib=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss))
|
|
finally:
|
|
watchdog.cancel()
|
|
finally:
|
|
model.close()
|