Keep voice workers resident and restore long OmniVoice references
This commit is contained in:
1 parent
73cc25fc32
commit
1e575ffc92
13 files changed
+321
-79
No files matched your search
@@ -9,7 +9,14 @@ Voice Design (Beschreibung in Klammern) und Referenzstimmen über Gradio.
|
||||
Aufträge gehen an Decks geschützte `/api/v1/voice/*`-Routen. Das gewünschte
|
||||
Profil muss in Deck freigegeben sein; nur ein Stimmprofil kann aktiv sein.
|
||||
In der Steuerung Stimmwerkzeuge starten. Die zugeordnete native Laufzeit
|
||||
lädt beim Auftrag; anschließend wird das Stimmmodell entladen.
|
||||
lädt beim ersten Auftrag und bleibt für weitere Aufträge geladen. Ein Profil-,
|
||||
GPU- oder Betriebsartwechsel entlädt das Stimmmodell. Referenzen dürfen als
|
||||
WAV ab einer Sekunde lang und bis 512 MiB groß sein; eine feste maximale
|
||||
Aufnahmedauer gibt es nicht. Ohne eigenes Transkript bereitet OmniVoice die
|
||||
Referenz mit seiner originalen Funktion vor: Über 20 Sekunden lange Aufnahmen
|
||||
werden standardmäßig an einer Sprechpause auf einen kurzen Ausschnitt gekürzt.
|
||||
Deck transkribiert genau diesen Ausschnitt. Mit eigenem Transkript oder
|
||||
ausgeschalteter Vorverarbeitung findet diese Kürzung nicht statt.
|
||||
OmniVoice-Klonen nutzt ein eingetragenes Referenztranskript oder erstellt es
|
||||
automatisch mit Decks vorhandenem CPU-STT-Profil. Es wird keine zusätzliche
|
||||
Whisper-Laufzeit und kein weiteres Modell heruntergeladen.
|
||||
|
||||
@@ -70,7 +70,7 @@ def main():
|
||||
with gr.Accordion('Deck-Verbindung',open=not CONFIG.exists()):
|
||||
token=gr.Textbox(label='Deck API-Token',type='password');save=gr.Button('Verbinden');status=gr.Textbox(interactive=False);save.click(connect,token,status)
|
||||
text=gr.Textbox(label='Text (Voice Design: Beschreibung in Klammern voranstellen)',lines=5)
|
||||
ref=gr.Audio(label='Referenzstimme (optional, 1–30 Sekunden)',type='filepath')
|
||||
ref=gr.Audio(label='Referenzstimme (optional, WAV)',type='filepath')
|
||||
device=gr.Dropdown(['3060','5080'],value='3060',label='GPU')
|
||||
with gr.Row():
|
||||
cfg=gr.Slider(.5,5,value=2,step=.1,label='Guidance');steps=gr.Slider(1,50,value=10,step=1,label='Schritte');seed=gr.Number(value=42,precision=0,label='Seed')
|
||||
|
||||
@@ -102,6 +102,9 @@ class Endpoint:
|
||||
enabled.add(data['id'])
|
||||
else:enabled.discard(data['id'])
|
||||
self.config['enabled_profiles']=sorted(enabled);self.persist()
|
||||
if row['kind']=='voice' and self.voxcpm:
|
||||
current=self.voxcpm.status().get('profile_id')
|
||||
if current and (not data['enabled'] and current==row['id'] or data['enabled'] and current!=row['id']):self.voxcpm.unload_idle()
|
||||
if not data['enabled'] and row['kind']=='audio' and self.tts:
|
||||
job=self.tts.status().get('job') or {}
|
||||
if job.get('profile_id')==row['id'] and job.get('state')!='running':self.tts.stop()
|
||||
|
||||
+3
-2
@@ -19,7 +19,7 @@ class InferenceError(ValueError):
|
||||
class Scheduler:
|
||||
"""FIFO admission; same-profile requests share configured slots, switches drain."""
|
||||
def __init__(self, worker):
|
||||
self.worker=worker;self.evict_tts=lambda:None;self.cv=threading.Condition();self.queue=[];self.key=None;self.active=0;self.tts_active=0;self.transition=False;self.gpu_mode="llm"
|
||||
self.worker=worker;self.evict_voice=lambda:None;self.evict_tts=lambda:None;self.cv=threading.Condition();self.queue=[];self.key=None;self.active=0;self.tts_active=0;self.transition=False;self.gpu_mode="llm"
|
||||
def status(self):
|
||||
with self.cv:return dict(active_requests=self.active+self.tts_active,waiting_requests=len(self.queue),switching=self.transition)
|
||||
@contextlib.contextmanager
|
||||
@@ -47,6 +47,7 @@ class Scheduler:
|
||||
if self.transition:
|
||||
try:
|
||||
if switch:self.worker.stop()
|
||||
if switch and key!=('voice',):self.evict_voice()
|
||||
if key in (('image',),('separator',)) or switch:self.evict_tts()
|
||||
if prepare:prepare()
|
||||
except Exception:
|
||||
@@ -79,7 +80,7 @@ class Scheduler:
|
||||
with self.cv:
|
||||
if self.active or self.tts_active:return False
|
||||
self.transition=True
|
||||
try:self.worker.stop();self.evict_tts();self.key=None
|
||||
try:self.worker.stop();self.evict_tts();self.evict_voice();self.key=None
|
||||
finally:self.transition=False;self.cv.notify_all()
|
||||
return True
|
||||
|
||||
|
||||
+62
-19
@@ -1,24 +1,67 @@
|
||||
"""Offline OmniVoice worker. Private input/output; no model or credential logging."""
|
||||
"""Offline OmniVoice worker; persistent weights, per-request reference state."""
|
||||
import contextlib,json,sys
|
||||
from pathlib import Path
|
||||
|
||||
def write_result(root,name,result):
|
||||
temporary=root/(name+'.tmp');temporary.write_text(json.dumps(result));temporary.replace(root/name)
|
||||
|
||||
def load(root):
|
||||
import torch
|
||||
from omnivoice import OmniVoice
|
||||
return OmniVoice.from_pretrained(str(root/'model'),device_map='cuda:0',dtype=torch.float16,local_files_only=True,load_asr=False)
|
||||
|
||||
def generate(model,request,root):
|
||||
import torch,soundfile as sf
|
||||
from omnivoice import OmniVoiceGenerationConfig
|
||||
torch.manual_seed(request['seed'])
|
||||
kwargs=dict(text=request['text'],language=request.get('language') or None,instruct=request.get('instruct') or None,speed=request.get('speed',1.0),generation_config=OmniVoiceGenerationConfig(num_step=request['steps'],guidance_scale=request['cfg'],denoise=request.get('denoise',True),preprocess_prompt=request.get('preprocess_prompt',True),postprocess_output=request.get('postprocess_output',True)))
|
||||
if request.get('duration'):kwargs['duration']=request['duration']
|
||||
if (root/'reference.wav').exists():kwargs.update(ref_audio=str(root/'reference.wav'),ref_text=request['reference_text'])
|
||||
wave=model.generate(**kwargs)[0];rate=model.sampling_rate
|
||||
sf.write(root/'result.wav',wave,rate,subtype='PCM_16')
|
||||
return dict(ok=True,sample_rate=rate,duration=len(wave)/rate)
|
||||
|
||||
def failure(exc,phase):
|
||||
oom='outofmemory' in type(exc).__name__.lower() or 'out of memory' in str(exc).lower()
|
||||
return dict(ok=False,error='GPU-Speicher reicht nicht aus. Andere Deck-Modelle entladen oder andere GPU wählen.' if oom else 'OmniVoice: '+phase+' fehlgeschlagen ('+type(exc).__name__+'). Laufzeit und Komponenten prüfen.')
|
||||
|
||||
def prepare_reference(root,rate=24000):
|
||||
# Use the installed OmniVoice preprocessing, before Deck's external CPU ASR.
|
||||
# Supplying ASR text to generate() otherwise disables OmniVoice's own trimming.
|
||||
import numpy as np
|
||||
import soundfile as sf
|
||||
from omnivoice.utils.audio import trim_long_audio,remove_silence,load_audio
|
||||
audio=load_audio(str(root/'reference.wav'),rate);original=audio.shape[-1]/rate
|
||||
rms=float(np.sqrt(np.mean(audio**2)))
|
||||
if 0<rms<.1:audio=audio*.1/rms
|
||||
audio=trim_long_audio(audio,rate,trim_threshold=20.0)
|
||||
audio=remove_silence(audio,rate,mid_sil=200,lead_sil=100,trail_sil=200)
|
||||
if audio.shape[-1]==0:raise ValueError('Referenz enthält nach der Aufbereitung keine Sprache. Vorverarbeitung ausschalten oder andere Aufnahme verwenden.')
|
||||
sf.write(root/'reference.wav',audio[0],rate,subtype='PCM_16')
|
||||
return dict(ok=True,original_duration=original,duration=audio.shape[-1]/rate)
|
||||
|
||||
def main():
|
||||
root=Path(sys.argv[1]);request=json.loads(sys.stdin.read());phase='Modell laden'
|
||||
try:
|
||||
with open('/dev/null','w') as sink,contextlib.redirect_stdout(sink),contextlib.redirect_stderr(sink):
|
||||
import torch,soundfile as sf
|
||||
from omnivoice import OmniVoice,OmniVoiceGenerationConfig
|
||||
torch.manual_seed(request['seed'])
|
||||
model=OmniVoice.from_pretrained(str(root/'model'),device_map='cuda:0',dtype=torch.float16,local_files_only=True,load_asr=False)
|
||||
(root/'phase').write_text('OmniVoice: Stimme wird erzeugt');phase='Stimme erzeugen'
|
||||
kwargs=dict(text=request['text'],language=request.get('language') or None,instruct=request.get('instruct') or None,speed=request.get('speed',1.0),generation_config=OmniVoiceGenerationConfig(num_step=request['steps'],guidance_scale=request['cfg'],denoise=request.get('denoise',True),preprocess_prompt=request.get('preprocess_prompt',True),postprocess_output=request.get('postprocess_output',True)))
|
||||
if request.get('duration'):kwargs['duration']=request['duration']
|
||||
if (root/'reference.wav').exists():kwargs.update(ref_audio=str(root/'reference.wav'),ref_text=request['reference_text'])
|
||||
wave=model.generate(**kwargs)[0];rate=model.sampling_rate
|
||||
sf.write(root/'result.wav',wave,rate,subtype='PCM_16')
|
||||
result=dict(ok=True,sample_rate=rate,duration=len(wave)/rate)
|
||||
except Exception as exc:
|
||||
oom='outofmemory' in type(exc).__name__.lower() or 'out of memory' in str(exc).lower()
|
||||
result=dict(ok=False,error='GPU-Speicher reicht nicht aus. Andere Deck-Modelle entladen oder andere GPU wählen.' if oom else 'OmniVoice: '+phase+' fehlgeschlagen ('+type(exc).__name__+'). Laufzeit und Komponenten prüfen.')
|
||||
(root/'result.json').write_text(json.dumps(result));return 0 if result['ok'] else 1
|
||||
root=Path(sys.argv[1]);resident='--resident' in sys.argv[2:]
|
||||
with open('/dev/null','w') as sink,contextlib.redirect_stdout(sink),contextlib.redirect_stderr(sink):
|
||||
if '--prepare-reference' in sys.argv[2:]:
|
||||
try:
|
||||
config=json.loads(Path(sys.argv[3]).read_text());rate=config['sampling_rate']
|
||||
if type(rate)!=int or not 11025<=rate<=96000:raise ValueError('Ungültige OmniVoice-Abtastrate in der Modellkomponente.')
|
||||
result=prepare_reference(root,rate)
|
||||
except Exception as exc:result=dict(ok=False,error=str(exc) if isinstance(exc,ValueError) else 'OmniVoice: Referenzaufbereitung fehlgeschlagen ('+type(exc).__name__+').')
|
||||
write_result(root,'reference-info.json',result);return 0 if result['ok'] else 1
|
||||
try:model=load(root)
|
||||
except Exception as exc:
|
||||
write_result(root,'ready.json' if resident else 'result.json',failure(exc,'Modell laden'));return 1
|
||||
if resident:write_result(root,'ready.json',dict(ok=True))
|
||||
lines=sys.stdin if resident else [sys.stdin.read()]
|
||||
for line in lines:
|
||||
request=json.loads(line);output=Path(request['output']) if resident else root
|
||||
try:
|
||||
(output/'phase').write_text('OmniVoice: Stimme wird erzeugt')
|
||||
result=generate(model,request,output)
|
||||
except Exception as exc:result=failure(exc,'Stimme erzeugen')
|
||||
write_result(output,'result.json',result)
|
||||
if not resident:return 0 if result['ok'] else 1
|
||||
return 0
|
||||
if __name__=='__main__':sys.exit(main())
|
||||
@@ -110,6 +110,7 @@ class Server(ThreadingHTTPServer):
|
||||
self.scheduler=Scheduler(self.worker)
|
||||
self.voxcpm_tests=VoxCPMTests(self.catalog.root.parent/'voice-tests',self.profiles,self.voxcpm_runtime)
|
||||
self.voxcpm_tests.omni_runtime=self.omnivoice_runtime
|
||||
self.scheduler.evict_voice=self.voxcpm_tests.unload_idle
|
||||
self.voxcpm_tests.acquire=lambda wait=False:self.scheduler.image_reservation(wait,kind='voice')
|
||||
self.separator_runtime=SeparatorRuntime(self.catalog.root.parent/'separator-runtime')
|
||||
self.separator_tests=SeparatorTests(self.catalog.root.parent/'separator-tests',self.separator_runtime,self.scheduler)
|
||||
@@ -672,7 +673,7 @@ class Handler(BaseHTTPRequestHandler):
|
||||
if self.read_json():raise ValueError('Keine Abbruchparameter erwartet.')
|
||||
return self.respond(self.server.voxcpm_tests.stop())
|
||||
if self.headers.get('Content-Type','').startswith('multipart/form-data'):
|
||||
fields,audio=read_upload(self,validate=False,allowed_fields=('profile_id','text','device','cfg','steps','seed','reference_text','language','instruct','speed','duration','denoise','preprocess_prompt','postprocess_output'),max_field=4096)
|
||||
fields,audio=read_upload(self,validate=False,allowed_fields=('profile_id','text','device','cfg','steps','seed','reference_text','language','instruct','speed','duration','denoise','preprocess_prompt','postprocess_output'),max_field=65536,max_audio=512*1024**2)
|
||||
fields['reference']=audio
|
||||
for key in ('steps','seed'):
|
||||
if key in fields:fields[key]=int(fields[key])
|
||||
|
||||
@@ -28,7 +28,7 @@ def read_upload(handler,validate=True,max_audio=MAX_AUDIO,allowed_fields=None,ma
|
||||
try:length=int(handler.headers.get('Content-Length','0'))
|
||||
except ValueError:raise ValueError('Ungültige Upload-Länge.') from None
|
||||
content_type=handler.headers.get('Content-Type','')
|
||||
if not 0<length<=max_audio+65536 or not content_type.lower().startswith('multipart/form-data;'):raise ValueError('Multipart-Upload bis 8 MiB erforderlich.')
|
||||
if not 0<length<=max_audio+65536 or not content_type.lower().startswith('multipart/form-data;'):raise ValueError(f'Multipart-Upload bis {max_audio//1024**2} MiB erforderlich.')
|
||||
raw=handler.rfile.read(length)
|
||||
if len(raw)!=length:raise ValueError('Upload unvollständig.')
|
||||
message=BytesParser(policy=policy.default).parsebytes(b'Content-Type: '+content_type.encode()+b'\r\nMIME-Version: 1.0\r\n\r\n'+raw)
|
||||
@@ -113,11 +113,22 @@ class STT:
|
||||
# Normalize in memory for the existing CPU ASR; never fetch another model.
|
||||
p=next((p for p in self.profiles.status()['profiles'] if p['kind']=='stt' and p['runnable']),None)
|
||||
if not p:raise ValueError('Referenztranskript automatisch erstellen: ausführbares STT-Profil fehlt. Spracherkennung einrichten oder Transkript eingeben.')
|
||||
converted=subprocess.run(['ffmpeg','-nostdin','-v','error','-i','pipe:0','-ac','1','-ar','16000','-f','s16le','pipe:1'],input=audio,capture_output=True,timeout=20)
|
||||
converted=subprocess.run(['ffmpeg','-nostdin','-v','error','-i','pipe:0','-ac','1','-ar','16000','-f','s16le','pipe:1'],input=audio,capture_output=True,timeout=180)
|
||||
if converted.returncode or not converted.stdout:raise ValueError('Referenzaudio konnte nicht für die Spracherkennung vorbereitet werden.')
|
||||
buffer=io.BytesIO()
|
||||
with wave.open(buffer,'wb') as w:w.setnchannels(1);w.setsampwidth(2);w.setframerate(16000);w.writeframes(converted.stdout)
|
||||
ident=self.start(p['id'],buffer.getvalue(),'auto')['id'];deadline=time.monotonic()+300
|
||||
# Long references with preprocessing disabled retain their full transcript.
|
||||
# The existing ASR accepts 120 seconds per request, so split only for ASR.
|
||||
texts=[];chunk_bytes=120*16000*2
|
||||
for offset in range(0,len(converted.stdout),chunk_bytes):
|
||||
if cancel.is_set():raise InterruptedError()
|
||||
buffer=io.BytesIO()
|
||||
with wave.open(buffer,'wb') as w:w.setnchannels(1);w.setsampwidth(2);w.setframerate(16000);w.writeframes(converted.stdout[offset:offset+chunk_bytes])
|
||||
texts.append(self._transcribe_reference_chunk(p['id'],buffer.getvalue(),cancel))
|
||||
text=' '.join(texts)
|
||||
if len(text)>64000:raise ValueError('Referenztranskript ist zu lang. Kürzere Aufnahme oder eigenes Transkript verwenden.')
|
||||
return text
|
||||
|
||||
def _transcribe_reference_chunk(self,profile_id,audio,cancel):
|
||||
ident=self.start(profile_id,audio,'auto')['id'];deadline=time.monotonic()+300
|
||||
while True:
|
||||
with self.lock:job=dict(self.job)
|
||||
if job['id']!=ident:raise ValueError('Referenztranskription wurde durch einen anderen STT-Auftrag ersetzt. Erneut versuchen oder Transkript eingeben.')
|
||||
@@ -128,7 +139,7 @@ class STT:
|
||||
raise ValueError('Zeitlimit für Referenztranskription erreicht. Transkript eingeben oder erneut versuchen.')
|
||||
if job['state']!='running':
|
||||
text=job.get('text','').strip()
|
||||
if job['state']!='complete' or not 1<=len(text)<=1000:raise ValueError('Kein brauchbares Referenztranskript erkannt. Transkript von Hand eingeben.')
|
||||
if job['state']!='complete' or not 1<=len(text)<=64000:raise ValueError('Kein brauchbares Referenztranskript erkannt. Transkript von Hand eingeben.')
|
||||
return text
|
||||
cancel.wait(.2)
|
||||
|
||||
|
||||
@@ -374,6 +374,15 @@ class SchedulerTests(unittest.TestCase):
|
||||
with s.lease('b',timeout=0):pass
|
||||
with s.lease('b'):self.assertEqual(s.status()['active_requests'],1)
|
||||
self.assertEqual(s.status()['active_requests'],0)
|
||||
def test_voice_weights_survive_jobs_until_switch_or_stop(self):
|
||||
from unittest.mock import Mock
|
||||
s=Scheduler(FakeWorker());s.evict_voice=Mock()
|
||||
with s.lease(('voice',)):pass
|
||||
with s.lease(('voice',)):pass
|
||||
s.evict_voice.assert_not_called()
|
||||
with s.lease('chat'):pass
|
||||
self.assertEqual(s.evict_voice.call_count,1)
|
||||
s.unload_idle();self.assertEqual(s.evict_voice.call_count,2)
|
||||
def test_failed_prepare_releases_queue_and_can_retry(self):
|
||||
s=Scheduler(FakeWorker())
|
||||
with self.assertRaises(ValueError):
|
||||
|
||||
+18
@@ -46,3 +46,21 @@ class ReferenceTranscriptionTests(unittest.TestCase):
|
||||
stt.start=Mock(return_value={'id':'ours'});stt.job=dict(id='someone-else',state='complete',text='Other audio')
|
||||
with patch('stt.subprocess.run',return_value=SimpleNamespace(returncode=0,stdout=b'\0\0'*16000)):
|
||||
with self.assertRaisesRegex(ValueError,'ersetzt'):stt.transcribe_reference(b'reference',threading.Event())
|
||||
|
||||
class LongReferenceTests(unittest.TestCase):
|
||||
def test_long_reference_is_transcribed_in_chunks_without_truncation(self):
|
||||
import threading
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock,patch
|
||||
from stt import STT,validate_wav
|
||||
stt=STT.__new__(STT);stt.profiles=Mock()
|
||||
stt.profiles.status.return_value={'profiles':[dict(id='cpu-asr',kind='stt',runnable=True)]}
|
||||
stt._transcribe_reference_chunk=Mock(side_effect=['First','Second','Third'])
|
||||
pcm=b'\0\0'*(241*16000)
|
||||
with patch('stt.subprocess.run',return_value=SimpleNamespace(returncode=0,stdout=pcm)):
|
||||
self.assertEqual(stt.transcribe_reference(b'long-reference',threading.Event()),'First Second Third')
|
||||
lengths=[]
|
||||
for call in stt._transcribe_reference_chunk.call_args_list:
|
||||
validate_wav(call.args[1])
|
||||
with wave.open(io.BytesIO(call.args[1])) as w:lengths.append(w.getnframes()/w.getframerate())
|
||||
self.assertEqual(lengths,[120,120,1])
|
||||
+87
-6
@@ -33,14 +33,16 @@ class VoiceTests(unittest.TestCase):
|
||||
self.assertNotEqual((work/'model/model.safetensors').resolve(),(work/'model/audio_tokenizer/model.safetensors').resolve())
|
||||
|
||||
def test_reference_limits(self):
|
||||
for data in (b'',b'not audio',b'x'*(8*1024**2+1)):
|
||||
for data in (b'',b'not audio'):
|
||||
with self.assertRaises(ValueError):validate_reference(data)
|
||||
def wav(seconds):
|
||||
b=io.BytesIO()
|
||||
with wave.open(b,'wb') as w:w.setnchannels(1);w.setsampwidth(2);w.setframerate(16000);w.writeframes(b'\0\0'*int(seconds*16000))
|
||||
return b.getvalue()
|
||||
validate_reference(wav(2))
|
||||
with self.assertRaises(ValueError):validate_reference(wav(31))
|
||||
validate_reference(wav(32))
|
||||
validate_reference(wav(121))
|
||||
validate_reference(wav(1200))
|
||||
def test_not_installed_and_components_reported_separately(self):
|
||||
profiles=Mock();profiles._component.side_effect=ValueError('missing');runtime=Mock();runtime.status.return_value={'installed':False}
|
||||
t=VoxCPMTests('/tmp/no-voice',profiles,runtime);p=dict(model=dict(kind='voice',repo='openbmb/VoxCPM2',file='model.safetensors'),components={})
|
||||
@@ -50,6 +52,7 @@ class VoiceTests(unittest.TestCase):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
p=dict(id='test',model=dict(kind='voice',repo='openbmb/VoxCPM2',file='model.safetensors'),components={})
|
||||
profiles=Mock();profiles.status.return_value={'profiles':[p]};runtime=Mock();runtime.status.return_value={'installed':True}
|
||||
runtime.paths.return_value=(Path('/fake-python'),None)
|
||||
t=VoxCPMTests(d,profiles,runtime);release=Mock();t.acquire=Mock(return_value=release)
|
||||
with patch('voxcpm_test.probe',return_value=[]):
|
||||
with self.assertRaisesRegex(ValueError,'VRAM'):t.start('test','synthetic test')
|
||||
@@ -66,13 +69,91 @@ class VoiceTests(unittest.TestCase):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
t=VoxCPMTests(d,Mock(),Mock());ident='a'*32;t.job=dict(id=ident,state='running');t.stage=lambda p,root:(root/'model').mkdir();t.runtime.paths.return_value=(Path('/fake-python'),None)
|
||||
root=Path(d)/ident;release=Mock()
|
||||
def launch(*args,**kwargs):
|
||||
process=Mock();process.poll.return_value=None
|
||||
def generate():
|
||||
(root/'result.json').write_text('{"ok":false,"error":"synthetic OOM"}' if outcome=='failed' else '{"ok":true,"duration":1,"sample_rate":16000}')
|
||||
if outcome=='complete':
|
||||
with wave.open(str(root/'result.wav'),'wb') as w:w.setnchannels(1);w.setsampwidth(2);w.setframerate(16000);w.writeframes(b'\0\0'*16000)
|
||||
process=Mock();process.poll.return_value=0;return process
|
||||
process.stdin.flush.side_effect=generate
|
||||
if outcome=='cancelled':t.cancel.set()
|
||||
with patch('voxcpm_test.subprocess.Popen',side_effect=launch):t._run_voice({'model':{'kind':'voice','repo':'openbmb/VoxCPM2','file':'model.safetensors'}},ident,dict(text='synthetic'),b'reference',{'uuid':'test'},release)
|
||||
with patch.object(t,'_ensure_voice',return_value=process):
|
||||
if outcome=='complete':t.process=process
|
||||
t._run_voice({'model':{'kind':'voice','repo':'openbmb/VoxCPM2','file':'model.safetensors'}},ident,dict(text='synthetic'),b'reference',{'uuid':'test'},release)
|
||||
self.assertEqual(t.job['state'],outcome);release.assert_called_once()
|
||||
self.assertFalse((root/'reference.wav').exists());self.assertFalse((root/'model').exists());self.assertFalse(t.status()['loaded'])
|
||||
self.assertFalse((root/'reference.wav').exists());self.assertFalse((root/'model').exists());self.assertEqual(t.status()['loaded'],outcome=='complete')
|
||||
self.assertEqual((root/'complete').exists(),outcome=='complete')
|
||||
|
||||
class ResidencyTests(unittest.TestCase):
|
||||
def test_two_jobs_reuse_worker_and_stop_releases_weights(self):
|
||||
import sys,time
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
root=Path(d);script=root/'fake-worker.py'
|
||||
script.write_text('''import sys,json,wave
|
||||
from pathlib import Path
|
||||
root=Path(sys.argv[1]);(root/'ready.json').write_text('{"ok":true}')
|
||||
for line in sys.stdin:
|
||||
request=json.loads(line);output=Path(request['output'])
|
||||
with wave.open(str(output/'result.wav'),'wb') as w:w.setnchannels(1);w.setsampwidth(2);w.setframerate(16000);w.writeframes(b'\\0\\0'*16000)
|
||||
temp=output/'result.tmp';temp.write_text('{"ok":true,"duration":1,"sample_rate":16000}');temp.replace(output/'result.json')
|
||||
''')
|
||||
row=dict(id='vox',revision=1,kind='voice',model=dict(kind='voice',repo='openbmb/VoxCPM2',file='model.safetensors'),components={})
|
||||
profiles=Mock();profiles.status.return_value={'profiles':[row]};runtime=Mock();runtime.status.return_value={'installed':True};runtime.paths.return_value=(Path(sys.executable),None)
|
||||
t=VoxCPMTests(root/'jobs',profiles,runtime);t.blockers=lambda p:[];t.stage=lambda p,r:(r/'model').mkdir()
|
||||
def gpu():return [dict(name='RTX 3060',uuid='test',processes=1 if t.process and t.process.poll() is None else 0,free_mib=10000)]
|
||||
try:
|
||||
with patch('voxcpm_test.WORKER',script),patch('voxcpm_test.probe',side_effect=gpu),patch('voxcpm_test.cgroup_headroom',return_value=None):
|
||||
first_pid=None
|
||||
for text in ('first','second'):
|
||||
t.start('vox',text,device='3060')
|
||||
deadline=time.monotonic()+5
|
||||
while t.status()['job']['state']=='running' and time.monotonic()<deadline:time.sleep(.02)
|
||||
self.assertEqual(t.status()['job']['state'],'complete');self.assertTrue(t.status()['loaded'])
|
||||
if first_pid is None:first_pid=t.process.pid
|
||||
self.assertEqual(t.process.pid,first_pid)
|
||||
self.assertFalse((t.root/t.job['id']/'reference.wav').exists())
|
||||
t.stop();self.assertFalse(t.status()['loaded']);self.assertFalse((t.root/'session').exists())
|
||||
finally:t.stop()
|
||||
def test_pcm24_reference_converted_without_trimming(self):
|
||||
from types import SimpleNamespace
|
||||
b=io.BytesIO()
|
||||
with wave.open(b,'wb') as w:w.setnchannels(1);w.setsampwidth(3);w.setframerate(16000);w.writeframes(b'\0\0\0'*16000*32)
|
||||
with patch('voxcpm_test.subprocess.run',return_value=SimpleNamespace(returncode=0,stdout=b'\0\0'*48000*32)):
|
||||
normalized=validate_reference(b.getvalue())
|
||||
with wave.open(io.BytesIO(normalized)) as w:self.assertEqual(w.getsampwidth(),2);self.assertEqual(w.getnframes()/w.getframerate(),32)
|
||||
|
||||
class OmniReferenceTests(unittest.TestCase):
|
||||
def test_automatic_asr_receives_exact_prepared_reference(self):
|
||||
import json,threading
|
||||
from types import SimpleNamespace
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
t=VoxCPMTests(d,Mock(),Mock());t.omni_runtime=Mock();t.omni_runtime.paths.return_value=(Path('/python'),None)
|
||||
t.job=dict(state='running');t.reference_transcriber=Mock(return_value='Matched transcript')
|
||||
t.profiles._component.return_value=dict(id='preprocessor',file='preprocessor_config.json');t.profiles.catalog.root=Path(d)
|
||||
root=Path(d)/'job';process=Mock();process.poll.return_value=None
|
||||
def prepare(*args,**kwargs):
|
||||
(root/'reference.wav').write_bytes(b'prepared excerpt')
|
||||
(root/'reference-info.json').write_text(json.dumps(dict(ok=True,original_duration=1200,duration=15)))
|
||||
return SimpleNamespace(returncode=0)
|
||||
def finish():
|
||||
with wave.open(str(root/'result.wav'),'wb') as w:w.setnchannels(1);w.setsampwidth(2);w.setframerate(24000);w.writeframes(b'\0\0'*24000)
|
||||
(root/'result.json').write_text(json.dumps(dict(ok=True,sample_rate=24000,duration=1)))
|
||||
process.stdin.flush.side_effect=finish
|
||||
with patch('voxcpm_test.subprocess.run',side_effect=prepare),patch.object(t,'_ensure_voice',return_value=process):
|
||||
t._run_voice(dict(model=dict(kind='voice',repo='k2-fsa/OmniVoice',file='model.safetensors')), 'job',dict(text='Test',reference_text='',preprocess_prompt=True),b'full reference',dict(uuid='test'),Mock())
|
||||
t.reference_transcriber.assert_called_once_with(b'prepared excerpt',t.cancel)
|
||||
self.assertEqual(t.job['state'],'complete');self.assertEqual(t.job['reference_used_duration'],15)
|
||||
request=json.loads(process.stdin.write.call_args.args[0]);self.assertEqual(request['reference_text'],'Matched transcript')
|
||||
self.assertFalse((root/'reference.wav').exists())
|
||||
def test_manual_transcript_does_not_trim_or_transcribe(self):
|
||||
import json
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
t=VoxCPMTests(d,Mock(),Mock());t.job=dict(state='running');t.reference_transcriber=Mock()
|
||||
root=Path(d)/'job';process=Mock();process.poll.return_value=None
|
||||
def finish():
|
||||
self.assertEqual((root/'reference.wav').read_bytes(),b'full reference')
|
||||
with wave.open(str(root/'result.wav'),'wb') as w:w.setnchannels(1);w.setsampwidth(2);w.setframerate(24000);w.writeframes(b'\0\0'*24000)
|
||||
(root/'result.json').write_text(json.dumps(dict(ok=True,sample_rate=24000,duration=1)))
|
||||
process.stdin.flush.side_effect=finish
|
||||
with patch('voxcpm_test.subprocess.run') as prepare,patch.object(t,'_ensure_voice',return_value=process):
|
||||
t._run_voice(dict(model=dict(kind='voice',repo='k2-fsa/OmniVoice',file='model.safetensors')), 'job',dict(text='Test',reference_text='Full transcript',preprocess_prompt=True),b'full reference',dict(uuid='test'),Mock())
|
||||
prepare.assert_not_called();t.reference_transcriber.assert_not_called();self.assertEqual(t.job['state'],'complete')
|
||||
+2
-2
@@ -1,11 +1,11 @@
|
||||
window.VoiceUI=(()=>{
|
||||
const e=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||
function html(){return `<section id="voice-panel" class="card"><h2>Stimme ausprobieren · VoxCPM2 / OmniVoice</h2><p>Text erzeugt Sprache. Mit optionaler WAV-Referenz übernimmt das Modell deren Stimme. OmniVoice benötigt dazu den gesprochenen Text; ein leeres Transkriptfeld wird mit der vorhandenen Spracherkennung automatisch ergänzt.</p><p id="voice-status" role="status"></p><progress id="voice-progress" hidden aria-label="Stimmgenerierung"></progress><p id="voice-error" role="alert"></p><form id="voice-form"><label>Profil<select name="profile_id" id="voice-profile" required></select></label><label>Text<textarea name="text" rows="5" maxlength="1000" required></textarea></label><label>Referenzstimme (optional, PCM-16-WAV, 1–30 Sekunden, bis 8 MiB)<input name="file" type="file" accept="audio/wav,.wav"></label><label>Transkript der Referenz (optional; leer = automatisch erkennen)<textarea name="reference_text" maxlength="1000"></textarea></label><label>Stil / Stimme (OmniVoice)<input name="instruct" maxlength="1000"></label><div class="form-grid"><label>GPU<select name="device"><option value="3060">RTX 3060</option><option value="5080">RTX 5080</option></select></label><label>Guidance<input name="cfg" type="number" min="0.5" max="5" step="0.1" value="2"></label><label>Schritte<input name="steps" type="number" min="1" max="50" value="10"></label><label>Seed<input name="seed" type="number" min="0" max="2147483647" value="42"></label></div><button id="voice-start">Stimme erzeugen</button><button id="voice-cancel" type="button" class="secondary" disabled>Abbrechen</button></form><div id="voice-result"></div><p class="small">Im LLM- oder Stimmwerkzeuge-Modus verfügbar. Deck entlädt sein LLM vor der Stimmgenerierung und lädt es bei der nächsten Chat-Anfrage wieder. Das Stimmmodell wird nach dem Auftrag entladen. Referenzdatei wird nach dem Auftrag gelöscht; Text wird nicht gespeichert.</p></section>`;}
|
||||
function html(){return `<section id="voice-panel" class="card"><h2>Stimme ausprobieren · VoxCPM2 / OmniVoice</h2><p>Text erzeugt Sprache. Mit optionaler WAV-Referenz übernimmt das Modell deren Stimme. OmniVoice benötigt dazu den gesprochenen Text; ein leeres Transkriptfeld wird mit der vorhandenen Spracherkennung automatisch ergänzt.</p><p id="voice-status" role="status"></p><progress id="voice-progress" hidden aria-label="Stimmgenerierung"></progress><p id="voice-error" role="alert"></p><form id="voice-form"><label>Profil<select name="profile_id" id="voice-profile" required></select></label><label>Text<textarea name="text" rows="5" maxlength="1000" required></textarea></label><label>Referenzstimme (optional, WAV, ab 1 Sekunde, bis 512 MiB; automatische PCM-16-Konvertierung)<input name="file" type="file" accept="audio/wav,.wav"></label><label>Transkript der Referenz (optional; leer = automatisch erkennen)<textarea name="reference_text" maxlength="64000"></textarea></label><label><input name="preprocess_prompt" type="checkbox" checked>OmniVoice: Referenz automatisch aufbereiten</label><p class="small">Ohne Transkript wählt OmniVoice aus langen Aufnahmen automatisch einen kurzen Ausschnitt. Mit eigenem Transkript bleibt die gesamte Aufnahme erhalten.</p><label>Stil / Stimme (OmniVoice)<input name="instruct" maxlength="1000"></label><div class="form-grid"><label>GPU<select name="device"><option value="3060">RTX 3060</option><option value="5080">RTX 5080</option></select></label><label>Guidance<input name="cfg" type="number" min="0.5" max="5" step="0.1" value="2"></label><label>Schritte<input name="steps" type="number" min="1" max="50" value="10"></label><label>Seed<input name="seed" type="number" min="0" max="2147483647" value="42"></label></div><button id="voice-start">Stimme erzeugen</button><button id="voice-cancel" type="button" class="secondary" disabled>Abbrechen</button></form><div id="voice-result"></div><p class="small">Im LLM- oder Stimmwerkzeuge-Modus verfügbar. Deck entlädt sein LLM vor der Stimmgenerierung und lädt es bei der nächsten Chat-Anfrage wieder. Das Stimmmodell bleibt für weitere Texte geladen und wird beim Profil-, GPU- oder Betriebsartwechsel entladen. Referenzdatei wird nach dem Auftrag gelöscht; Text wird nicht gespeichert.</p></section>`;}
|
||||
function bind(){const root=document.querySelector('#voice-panel');if(!root)return;const el=id=>root.querySelector('#'+id);let busy=false,lastResult='',ready=false;
|
||||
async function api(path='',body){const r=await fetch('/api/v1/voice'+path,body===undefined?{}:{method:'POST',headers:body instanceof FormData?{'X-Athena-Deck':'1'}:{'X-Athena-Deck':'1','Content-Type':'application/json'},body:body instanceof FormData?body:JSON.stringify(body)});const d=await r.json();if(!r.ok)throw Error(d.error||'Stimmgenerierung fehlgeschlagen');return d;}
|
||||
async function refresh(){try{const d=await api();if(!root.isConnected)return;const j=d.job;el('voice-status').textContent=(j?.phase||'Profil wählen und Text eingeben.')+(j?.gpu?' · '+j.gpu:'');el('voice-progress').hidden=j?.state!=='running';el('voice-start').disabled=busy||!ready||!['llm','voice'].includes(d.mode)||j?.state==='running';el('voice-cancel').disabled=j?.state!=='running';if(j?.state==='complete'&&j.id!==lastResult){lastResult=j.id;el('voice-result').innerHTML=`<h3>Ergebnis · ${Number(j.duration).toFixed(1)} Sekunden</h3><audio controls src="/api/v1/voice/audio?id=${e(j.id)}"></audio><p><a class="link" download="athena-stimme.wav" href="/api/v1/voice/audio?id=${e(j.id)}">WAV herunterladen</a></p>`;}}catch(err){if(root.isConnected)el('voice-error').textContent=err.message;}finally{if(root.isConnected)setTimeout(refresh,2000);}}
|
||||
fetch('/api/v1/profiles').then(async r=>{if(!r.ok)throw Error('Profile konnten nicht geladen werden.');return r.json();}).then(d=>{if(!root.isConnected)return;const rows=d.profiles.filter(p=>p.runnable&&['openbmb/VoxCPM2','k2-fsa/OmniVoice'].includes(p.model?.repo));ready=!!rows.length;el('voice-profile').onchange=()=>{const omni=rows.find(p=>p.id===el('voice-profile').value)?.model.repo==='k2-fsa/OmniVoice';root.querySelector('[name=steps]').value=omni?32:10;root.querySelector('[name=steps]').max=omni?64:50;root.querySelector('[name=cfg]').min=omni?0:.5;};el('voice-profile').innerHTML=rows.map(p=>`<option value="${e(p.id)}">${e(p.name)}</option>`).join('')||'<option value="">Stimmprofil unter Profile → Einrichtung & Komponenten vervollständigen</option>';if(rows.length)el('voice-profile').onchange();}).catch(err=>{if(root.isConnected)el('voice-error').textContent=err.message;});
|
||||
el('voice-form').onsubmit=async event=>{event.preventDefault();busy=true;el('voice-start').disabled=true;el('voice-error').textContent='';el('voice-status').textContent='Auftrag wird gestartet …';try{const data=new FormData(event.target);if(!data.get('file')?.size)data.delete('file');await api('/start',data);}catch(err){el('voice-error').textContent=err.message;}finally{busy=false;}};
|
||||
el('voice-form').onsubmit=async event=>{event.preventDefault();busy=true;el('voice-start').disabled=true;el('voice-error').textContent='';el('voice-status').textContent='Auftrag wird gestartet …';try{const data=new FormData(event.target);data.set('preprocess_prompt',event.target.elements.preprocess_prompt.checked?'true':'false');if(!data.get('file')?.size)data.delete('file');await api('/start',data);}catch(err){el('voice-error').textContent=err.message;}finally{busy=false;}};
|
||||
el('voice-cancel').onclick=async()=>{try{await api('/cancel',{});}catch(err){el('voice-error').textContent=err.message;}};refresh();
|
||||
}
|
||||
return {html,bind};
|
||||
|
||||
+73
-22
@@ -5,15 +5,37 @@ from tts_test import TTSTests
|
||||
from image_test import probe,cgroup_headroom
|
||||
from profiles import voice_recipe,omni_recipe
|
||||
WORKER=Path(__file__).with_name('voxcpm_worker.py')
|
||||
MAX_REFERENCE=512*1024**2
|
||||
|
||||
def validate_reference(audio):
|
||||
if not isinstance(audio,bytes) or not 0<len(audio)<=8*1024**2:raise ValueError('Referenz als WAV bis 8 MiB hochladen.')
|
||||
if not isinstance(audio,bytes) or not 0<len(audio)<=MAX_REFERENCE:raise ValueError('Referenzdatei ist leer oder größer als 512 MiB. Eine WAV-Datei bis 512 MiB verwenden.')
|
||||
if audio[:4] not in (b'RIFF',b'RF64') or audio[8:12]!=b'WAVE':raise ValueError('Referenzdatei ist keine WAV-Datei. Als WAV exportieren.')
|
||||
try:
|
||||
with wave.open(io.BytesIO(audio)) as w:
|
||||
if w.getnchannels() not in (1,2) or w.getsampwidth()!=2 or not 8000<=w.getframerate()<=96000 or not 1<=w.getnframes()/w.getframerate()<=30:raise ValueError('Referenz: PCM-16-WAV, mono/stereo, 1–30 Sekunden erforderlich.')
|
||||
except (wave.Error,EOFError):raise ValueError('Ungültige WAV-Datei. PCM-16-WAV verwenden.') from None
|
||||
seconds=w.getnframes()/w.getframerate()
|
||||
if seconds<1:raise ValueError('Referenzaufnahme muss mindestens eine Sekunde lang sein.')
|
||||
if w.getsampwidth()==2 and w.getnchannels() in (1,2) and 8000<=w.getframerate()<=96000:
|
||||
if len(w.readframes(w.getnframes()))!=w.getnframes()*w.getnchannels()*2:raise ValueError('Referenz-WAV ist unvollständig. Datei erneut exportieren.')
|
||||
return audio
|
||||
except (wave.Error,EOFError):pass
|
||||
# Convert float/24-bit WAV and unusual channel/rate layouts in memory.
|
||||
try:r=subprocess.run(['ffmpeg','-nostdin','-v','error','-i','pipe:0','-ac','1','-ar','48000','-f','s16le','pipe:1'],input=audio,capture_output=True,timeout=180)
|
||||
except (OSError,subprocess.TimeoutExpired):raise ValueError('WAV-Konvertierung fehlgeschlagen. Als PCM-16-WAV exportieren.') from None
|
||||
if r.returncode or not r.stdout:raise ValueError('Referenz-WAV konnte nicht gelesen werden. Datei erneut exportieren.')
|
||||
seconds=len(r.stdout)/96000
|
||||
if seconds<1:raise ValueError('Referenzaufnahme muss mindestens eine Sekunde lang sein.')
|
||||
if len(r.stdout)>MAX_REFERENCE:raise ValueError('Die konvertierte Referenzdatei überschreitet 512 MiB.')
|
||||
out=io.BytesIO()
|
||||
with wave.open(out,'wb') as w:w.setnchannels(1);w.setsampwidth(2);w.setframerate(48000);w.writeframes(r.stdout)
|
||||
return out.getvalue()
|
||||
|
||||
class VoxCPMTests(TTSTests):
|
||||
def __init__(self,*args,**kwargs):
|
||||
super().__init__(*args,**kwargs);self.session_key=None
|
||||
def status(self):
|
||||
return dict(super().status(),profile_id=self.session_key[0] if self.session_key else None,memory_policy='Gewichte bleiben bis zum Profil-, GPU- oder Betriebsartwechsel geladen.')
|
||||
def unload_idle(self):
|
||||
super().unload_idle();self.session_key=None;shutil.rmtree(self.root/'session',ignore_errors=True)
|
||||
def runtime_for(self,p):return self.omni_runtime if omni_recipe(p['model']) else self.runtime
|
||||
def blockers(self,p):
|
||||
if not voice_recipe(p['model']):return ['Diese Stimm-Modellfamilie wird noch nicht unterstützt.']
|
||||
@@ -32,11 +54,12 @@ class VoxCPMTests(TTSTests):
|
||||
if not isinstance(text,str) or not 1<=len(text.strip())<=1000:raise ValueError('Text mit 1–1000 Zeichen erforderlich.')
|
||||
if device not in ('5080','3060'):raise ValueError('RTX 5080 oder RTX 3060 wählen.')
|
||||
if type(cfg) not in (int,float) or not 0<=cfg<=5 or type(steps)!=int or not 1<=steps<=64 or type(seed)!=int or not 0<=seed<=2147483647:raise ValueError('Ungültige Guidance, Schritte oder Seed.')
|
||||
if reference is not None:validate_reference(reference)
|
||||
if reference is not None:reference=validate_reference(reference)
|
||||
p=next((p for p in self.profiles.status()['profiles'] if p['id']==profile_id),None)
|
||||
if not p or not p['model'] or not voice_recipe(p['model']):raise ValueError('Stimmprofil nicht gefunden.')
|
||||
if not omni_recipe(p['model']) and (cfg<.5 or steps>50):raise ValueError('VoxCPM2: Guidance 0,5–5 und Schritte 1–50 verwenden.')
|
||||
for value in (reference_text,language,instruct):
|
||||
if not isinstance(reference_text,str) or len(reference_text)>64000:raise ValueError('Referenztranskript ist zu lang.')
|
||||
for value in (language,instruct):
|
||||
if not isinstance(value,str) or len(value)>1000:raise ValueError('Ungültige Stimmoption.')
|
||||
if type(speed) not in (int,float) or not .5<=speed<=2 or type(duration) not in (int,float) or not 0<=duration<=60:raise ValueError('Ungültige Geschwindigkeit oder Dauer.')
|
||||
if any(type(v) is not bool for v in (denoise,preprocess_prompt,postprocess_output)):raise ValueError('Ungültige Audio-Vorverarbeitung.')
|
||||
@@ -50,34 +73,44 @@ class VoxCPMTests(TTSTests):
|
||||
release=None
|
||||
try:
|
||||
release=self.acquire(wait)
|
||||
gpu=next((g for g in probe() if 'RTX '+device in g['name'] and not g['processes'] and g['free_mib']>=6500),None)
|
||||
key=(p['id'],p.get('revision'),device,json.dumps(p.get('components',{}),sort_keys=True),str(self.runtime_for(p).paths()[0]))
|
||||
resident=self.process is not None and self.process.poll() is None and self.session_key==key
|
||||
if not resident:self.unload_idle()
|
||||
gpu=next((g for g in probe() if ('RTX '+device in g['name'] and (g['uuid']==self.gpu_uuid and g['processes']==1 if resident else not g['processes'] and g['free_mib']>=6500))),None)
|
||||
if not gpu:raise ValueError('RTX '+device+' benötigt mindestens 6,5 GiB freien VRAM und darf nicht fremd belegt sein.')
|
||||
headroom=cgroup_headroom()
|
||||
if headroom is not None and headroom<8*1024**3:raise ValueError('Mindestens 8 GiB freier Deck-Systemspeicher erforderlich.')
|
||||
if not resident and headroom is not None and headroom<8*1024**3:raise ValueError('Mindestens 8 GiB freier Deck-Systemspeicher erforderlich.')
|
||||
self.root.mkdir(parents=True,exist_ok=True,mode=0o700)
|
||||
self.job.update(phase=('OmniVoice' if omni_recipe(p['model']) else 'VoxCPM2')+' wird geladen',gpu=gpu['name']);self.gpu_uuid=gpu['uuid']
|
||||
threading.Thread(target=self._run_voice,args=(p,ident,dict(text=text,cfg=cfg,steps=steps,seed=seed,**(dict(reference_text=reference_text,language=language,instruct=instruct,speed=speed,duration=duration,denoise=denoise,preprocess_prompt=preprocess_prompt,postprocess_output=postprocess_output) if omni_recipe(p['model']) else {})),reference,gpu,release),daemon=True).start();return dict(self.job)
|
||||
self.job.update(phase=('OmniVoice' if omni_recipe(p['model']) else 'VoxCPM2')+(' bleibt geladen' if resident else ' wird geladen'),gpu=gpu['name']);self.gpu_uuid=gpu['uuid']
|
||||
threading.Thread(target=self._run_voice,args=(p,ident,dict(text=text,cfg=cfg,steps=steps,seed=seed,**(dict(reference_text=reference_text,language=language,instruct=instruct,speed=speed,duration=duration,denoise=denoise,preprocess_prompt=preprocess_prompt,postprocess_output=postprocess_output) if omni_recipe(p['model']) else {})),reference,gpu,release,key),daemon=True).start();return dict(self.job)
|
||||
except Exception as exc:
|
||||
if release:release()
|
||||
with self.lock:self.job.update(state='failed',phase=str(exc),finished_at=time.time())
|
||||
raise
|
||||
def _run_voice(self,p,ident,request,reference,gpu,release):
|
||||
def _run_voice(self,p,ident,request,reference,gpu,release,key=None):
|
||||
root=self.root/ident;state='failed';phase='Stimm-Ausführung fehlgeschlagen'
|
||||
try:
|
||||
root.mkdir(mode=0o700)
|
||||
if reference is not None:(root/'reference.wav').write_bytes(reference)
|
||||
if omni_recipe(p['model']) and reference is not None and not request['reference_text'].strip():
|
||||
if request.get('preprocess_prompt',True):
|
||||
with self.lock:self.job['phase']='OmniVoice: Referenz wird wie im Originalstudio vorbereitet'
|
||||
env=dict(os.environ,CUDA_VISIBLE_DEVICES='',HF_HUB_OFFLINE='1',TRANSFORMERS_OFFLINE='1',OMP_NUM_THREADS='4')
|
||||
component=self.profiles._component(p['model'],'preprocessor',p.get('components',{}).get('preprocessor'))
|
||||
config=self.profiles.catalog.root/component['id']/('model'+Path(component['file']).suffix)
|
||||
prepared=subprocess.run([str(self.omni_runtime.paths()[0]),str(Path(__file__).with_name('omnivoice_worker.py')),str(root),str(config),'--prepare-reference'],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,env=env,timeout=180)
|
||||
result=json.loads((root/'reference-info.json').read_text()) if (root/'reference-info.json').exists() else {}
|
||||
if prepared.returncode or not result.get('ok'):raise ValueError(result.get('error','OmniVoice: Referenz konnte nicht vorbereitet werden.'))
|
||||
reference=(root/'reference.wav').read_bytes()
|
||||
with self.lock:self.job.update(reference_duration=result['original_duration'],reference_used_duration=result['duration'])
|
||||
with self.lock:self.job['phase']='Referenzstimme wird auf der CPU transkribiert'
|
||||
request['reference_text']=self.reference_transcriber(reference,self.cancel)
|
||||
if self.cancel.is_set():raise InterruptedError()
|
||||
root.mkdir(mode=0o700);self.stage(p,root)
|
||||
if reference is not None:(root/'reference.wav').write_bytes(reference)
|
||||
env={k:v for k,v in os.environ.items() if not k.startswith(('HF_','LLAMA_','DECK_'))};env.update(CUDA_VISIBLE_DEVICES=gpu['uuid'],HF_HUB_OFFLINE='1',TRANSFORMERS_OFFLINE='1',OMP_NUM_THREADS='4',HOME=str(root))
|
||||
with self.lock:
|
||||
if self.cancel.is_set():raise InterruptedError()
|
||||
self.process=subprocess.Popen([str(self.runtime_for(p).paths()[0]),str(Path(__file__).with_name('omnivoice_worker.py') if omni_recipe(p['model']) else WORKER),str(root)],stdin=subprocess.PIPE,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,env=env,start_new_session=True,text=True)
|
||||
process=self.process
|
||||
process.stdin.write(json.dumps(request));process.stdin.close();process.stdin=None;deadline=time.monotonic()+600
|
||||
while process.poll() is None:
|
||||
process=self._ensure_voice(p,gpu,key)
|
||||
process.stdin.write(json.dumps(dict(request,output=str(root)))+'\n');process.stdin.flush();deadline=time.monotonic()+600
|
||||
while not (root/'result.json').exists():
|
||||
if self.cancel.wait(.25):raise InterruptedError()
|
||||
if process.poll() is not None:raise ValueError('Stimmworker beendet ohne Ergebnis. Speicher oder Laufzeit prüfen.')
|
||||
if time.monotonic()>deadline:raise ValueError('Zeitlimit für Stimmgenerierung erreicht.')
|
||||
if (root/'phase').exists():
|
||||
with self.lock:self.job['phase']=(root/'phase').read_text()
|
||||
@@ -88,15 +121,33 @@ class VoxCPMTests(TTSTests):
|
||||
output=root/'result.wav'
|
||||
with wave.open(str(output)) as w:
|
||||
if w.getnframes()==0 or output.stat().st_size>32*1024**2:raise ValueError('Ungültige Audioausgabe.')
|
||||
state='complete';phase='Stimme fertig · Modell entladen'
|
||||
state='complete';phase='Stimme fertig · Modell bleibt geladen'
|
||||
with self.lock:self.job.update(duration=result['duration'],sample_rate=result['sample_rate'])
|
||||
except InterruptedError:state='cancelled';phase='Stimmgenerierung abgebrochen · Modell entladen'
|
||||
except Exception as exc:
|
||||
if self.cancel.is_set():state='cancelled';phase='Stimmgenerierung abgebrochen · Modell entladen'
|
||||
else:phase=str(exc) if isinstance(exc,ValueError) else 'Stimm-Ausführung fehlgeschlagen ('+type(exc).__name__+').'
|
||||
finally:
|
||||
self.unload_idle();shutil.rmtree(root/'model',ignore_errors=True)
|
||||
for name in ('reference.wav','phase'):(root/name).unlink(missing_ok=True)
|
||||
if state!='complete':self.unload_idle()
|
||||
for name in ('reference.wav','reference-info.json','phase'):(root/name).unlink(missing_ok=True)
|
||||
if state=='complete':(root/'complete').touch()
|
||||
with self.lock:self.job.update(state=state,phase=phase,finished_at=time.time())
|
||||
release()
|
||||
|
||||
def _ensure_voice(self,p,gpu,key):
|
||||
if self.process is not None and self.process.poll() is None and self.session_key==key:return self.process
|
||||
self.unload_idle();session=self.root/'session';session.mkdir(mode=0o700);self.stage(p,session)
|
||||
env={k:v for k,v in os.environ.items() if not k.startswith(('HF_','LLAMA_','DECK_'))};env.update(CUDA_VISIBLE_DEVICES=gpu['uuid'],HF_HUB_OFFLINE='1',TRANSFORMERS_OFFLINE='1',OMP_NUM_THREADS='4',HOME=str(session))
|
||||
with self.lock:
|
||||
if self.cancel.is_set():raise InterruptedError()
|
||||
self.process=subprocess.Popen([str(self.runtime_for(p).paths()[0]),str(Path(__file__).with_name('omnivoice_worker.py') if omni_recipe(p['model']) else WORKER),str(session),'--resident'],stdin=subprocess.PIPE,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,env=env,start_new_session=True,text=True,bufsize=1)
|
||||
self.gpu_uuid=gpu['uuid'];process=self.process
|
||||
deadline=time.monotonic()+180
|
||||
while not (session/'ready.json').exists():
|
||||
if self.cancel.wait(.2):raise InterruptedError()
|
||||
if process.poll() is not None:raise ValueError('Stimmworker konnte das Modell nicht laden.')
|
||||
if time.monotonic()>deadline:raise ValueError('Zeitlimit beim Laden des Stimmmodells.')
|
||||
result=json.loads((session/'ready.json').read_text())
|
||||
if not result['ok']:raise ValueError(result['error'])
|
||||
self.session_key=key
|
||||
return process
|
||||
+36
-19
@@ -1,24 +1,41 @@
|
||||
"""Offline one-request VoxCPM2 worker. Never persists prompt text or logs media."""
|
||||
"""Offline VoxCPM2 worker. Resident mode keeps weights, never prompt/audio state."""
|
||||
import contextlib,json,sys
|
||||
from pathlib import Path
|
||||
|
||||
def write_result(root,name,result):
|
||||
temporary=root/(name+'.tmp');temporary.write_text(json.dumps(result));temporary.replace(root/name)
|
||||
|
||||
def load(root):
|
||||
from voxcpm import VoxCPM
|
||||
return VoxCPM.from_pretrained(str(root/'model'),load_denoiser=False,local_files_only=True,optimize=False,device='cuda:0')
|
||||
|
||||
def generate(model,request,root):
|
||||
import torch,soundfile as sf
|
||||
torch.manual_seed(request['seed'])
|
||||
wave=model.generate(text=request['text'],reference_wav_path=str(root/'reference.wav') if (root/'reference.wav').exists() else None,cfg_value=request['cfg'],inference_timesteps=request['steps'],max_len=2048,normalize=False,denoise=False,retry_badcase_max_times=1)
|
||||
rate=model.tts_model.sample_rate
|
||||
sf.write(root/'result.wav',wave,rate,subtype='PCM_16')
|
||||
return dict(ok=True,sample_rate=rate,duration=len(wave)/rate)
|
||||
|
||||
def failure(exc,phase):
|
||||
oom='outofmemory' in type(exc).__name__.lower() or 'out of memory' in str(exc).lower()
|
||||
return dict(ok=False,error='GPU-Speicher reicht nicht aus. Andere Deck-Modelle entladen oder andere GPU wählen.' if oom else 'VoxCPM2: '+phase+' fehlgeschlagen ('+type(exc).__name__+'). Laufzeit und Komponenten prüfen.')
|
||||
|
||||
def main():
|
||||
root=Path(sys.argv[1]);request=json.loads(sys.stdin.read());phase='Modell laden'
|
||||
try:
|
||||
# Libraries print progress and occasionally text; discard rather than record it.
|
||||
with open('/dev/null','w') as sink,contextlib.redirect_stdout(sink),contextlib.redirect_stderr(sink):
|
||||
import torch,soundfile as sf
|
||||
from voxcpm import VoxCPM
|
||||
model=VoxCPM.from_pretrained(str(root/'model'),load_denoiser=False,local_files_only=True,optimize=False,device='cuda:0')
|
||||
(root/'phase').write_text('Stimme wird erzeugt');phase='Stimme erzeugen'
|
||||
torch.manual_seed(request['seed'])
|
||||
wave=model.generate(text=request['text'],reference_wav_path=str(root/'reference.wav') if (root/'reference.wav').exists() else None,cfg_value=request['cfg'],inference_timesteps=request['steps'],max_len=2048,normalize=False,denoise=False,retry_badcase_max_times=1)
|
||||
rate=model.tts_model.sample_rate
|
||||
sf.write(root/'result.wav',wave,rate,subtype='PCM_16')
|
||||
result=dict(ok=True,sample_rate=rate,duration=len(wave)/rate)
|
||||
except Exception as exc:
|
||||
oom='outofmemory' in type(exc).__name__.lower() or 'out of memory' in str(exc).lower()
|
||||
result=dict(ok=False,error='GPU-Speicher reicht nicht aus. Andere Deck-Modelle entladen oder andere GPU wählen.' if oom else 'VoxCPM2: '+phase+' fehlgeschlagen ('+type(exc).__name__+'). Laufzeit und Komponenten prüfen.')
|
||||
(root/'result.json').write_text(json.dumps(result))
|
||||
return 0 if result['ok'] else 1
|
||||
root=Path(sys.argv[1]);resident='--resident' in sys.argv[2:]
|
||||
with open('/dev/null','w') as sink,contextlib.redirect_stdout(sink),contextlib.redirect_stderr(sink):
|
||||
try:model=load(root)
|
||||
except Exception as exc:
|
||||
write_result(root,'ready.json' if resident else 'result.json',failure(exc,'Modell laden'));return 1
|
||||
if resident:write_result(root,'ready.json',dict(ok=True))
|
||||
lines=sys.stdin if resident else [sys.stdin.read()]
|
||||
for line in lines:
|
||||
request=json.loads(line);output=Path(request['output']) if resident else root
|
||||
try:
|
||||
(output/'phase').write_text('Stimme wird erzeugt')
|
||||
result=generate(model,request,output)
|
||||
except Exception as exc:result=failure(exc,'Stimme erzeugen')
|
||||
write_result(output,'result.json',result)
|
||||
if not resident:return 0 if result['ok'] else 1
|
||||
return 0
|
||||
if __name__=='__main__':sys.exit(main())
|
||||
Reference in new issue
Block a user