"""VoxCPM2 speech and reference-voice generation, serialized by Deck GPU scheduler.""" import io,json,os,shutil,signal,subprocess,threading,time,uuid,wave,secrets from pathlib import Path from tts_test import TTSTests from image_test import probe,cgroup_headroom from profiles import voice_recipe,omni_recipe,qwen_clone_model WORKER=Path(__file__).with_name('voxcpm_worker.py') MAX_REFERENCE=512*1024**2 def validate_reference(audio): if not isinstance(audio,bytes) or not 0MAX_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.qwen_runtime if qwen_clone_model(p['model']) else self.omni_runtime if omni_recipe(p['model']) else self.runtime def blockers(self,p): if qwen_clone_model(p['model']): return [] if self.qwen_runtime.status()['installed'] else ['Vorhandene Qwen-TTS-Base-Laufzeit fehlt. Unter TTS einrichten.'] if not voice_recipe(p['model']):return ['Diese Stimm-Modellfamilie wird noch nicht unterstützt.'] errors=[] if not self.runtime_for(p).status()['installed']:errors.append(('OmniVoice' if omni_recipe(p['model']) else 'VoxCPM')+'-Laufzeit unter Laufzeiten installieren.') for role,info in voice_recipe(p['model']).items(): try:self.profiles._component(p['model'],role,p.get('components',{}).get(role)) except ValueError:errors.append(info['label']+' fehlt oder ist noch nicht zugeordnet. Unter Einrichtung & Komponenten ergänzen.') return errors def stage(self,p,root): if qwen_clone_model(p['model']): _,model=self.qwen_runtime.paths();(root/'model').symlink_to(model.resolve(),target_is_directory=True);return model=root/'model';model.mkdir();entries=[p['model']]+[self.profiles._component(p['model'],r,p.get('components',{}).get(r)) for r in voice_recipe(p['model'])] for entry in entries: src=self.profiles.catalog.root/entry['id']/('model'+Path(entry['file']).suffix) target=model/entry['file'];target.parent.mkdir(parents=True,exist_ok=True);target.symlink_to(src.resolve()) def start(self,profile_id,text,device='5080',cfg=2.0,steps=10,seed=None,reference=None,wait=False,reference_text='',language='',instruct='',speed=1.0,duration=0.0,denoise=True,preprocess_prompt=True,postprocess_output=True): 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 seed is not None and (type(seed)!=int or not -1<=seed<=2147483647):raise ValueError('Ungültige Guidance, Schritte oder Seed.') 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']) or qwen_clone_model(p['model'])):raise ValueError('Stimmprofil nicht gefunden.') if qwen_clone_model(p['model']) and reference is None:raise ValueError('Qwen-Stimmklonen benötigt eine Referenz-WAV. Für Preset-Stimmen TTS verwenden.') if seed is None:seed=-1 if omni_recipe(p['model']) else 42 if seed==-1:seed=secrets.randbelow(2147483648) if not omni_recipe(p['model']) and (cfg<.5 or steps>50):raise ValueError('VoxCPM2: Guidance 0,5–5 und Schritte 1–50 verwenden.') 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.') if omni_recipe(p['model']) and reference is not None and not reference_text.strip() and not callable(getattr(self,'reference_transcriber',None)):raise ValueError('OmniVoice: Referenztranskript eingeben oder vorhandene Spracherkennung anbinden.') errors=self.blockers(p) if errors:raise ValueError(' '.join(errors)) # Claim local job before scheduler admission to prevent races between two callers. with self.lock: if self.job and self.job['state']=='running':raise ValueError('Stimmgenerierung läuft bereits.') self.cancel.clear();ident=uuid.uuid4().hex;self.job=dict(id=ident,state='running',phase='GPU wird reserviert',profile_id=profile_id,started_at=time.time(),seed=seed) release=None try: release=self.acquire(wait) 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 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=('Qwen1.7B' if qwen_clone_model(p['model']) else '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']) or qwen_clone_model(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,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','--seed',str(request.get('seed',42))],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'],reference_start_seconds=result.get('start_seconds',0),reference_end_seconds=result.get('end_seconds',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() 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() if self.cancel.is_set():raise InterruptedError() if not (root/'result.json').exists():raise ValueError('Stimmworker beendet ohne Ergebnis. Speicher oder Laufzeit prüfen.') result=json.loads((root/'result.json').read_text()) if not result['ok']:raise ValueError(result['error']) 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 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: 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('qwen_clone_worker.py') if qwen_clone_model(p['model']) else 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