"""Native SoulX-Singer UI backend, sharing Deck's voice-mode admission protocol.""" import json,os,signal,subprocess,queue,threading from pathlib import Path from applio import Applio def soulx_singer_model(model):return bool(model and model.get('kind')=='voice' and model.get('repo')=='Soul-AILab/SoulX-Singer' and model.get('file')=='model-svc.pt' and (model.get('runtime_metadata') or {}).get('architecture')=='soulx_singer') class SoulXSinger(Applio): label="SoulX-Singer" def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) if not self.settings_path.exists():self.settings={'device':'5080'} self.launch_queue=queue.Queue() threading.Thread(target=self._launch_owner,daemon=True).start() def _launch_owner(self): # Linux PDEATHSIG follows the spawning thread. Keep that thread alive across # HTTP handlers and one-time activation threads, for the whole Deck lifetime. while not self.stop_event.is_set(): try:args,kwargs,event,result=self.launch_queue.get(timeout=.2) except queue.Empty:continue try:result['process']=subprocess.Popen(args,**kwargs) except Exception as exc:result['error']=exc finally:event.set() def _spawn(self,args,**kwargs): event=threading.Event();result={};self.launch_queue.put((args,kwargs,event,result)) if not event.wait(30):raise ValueError('SoulX-Prozessstart nicht bestätigt.') if 'error' in result:raise result['error'] return result['process'] def selected(self):return next((p for p in self.profiles.status()['profiles'] if soulx_singer_model(p.get('model')) and p['id'] in self.enabled() and p['runnable']),None) def blockers(self,p):return [] if self.runtime.status()['installed'] else ['SoulX-Singer-Laufzeit unter Laufzeiten installieren.'] def status(self): installed=self.runtime.status()['installed'] if installed:self.ensure() selected=self.selected() return dict(installed=installed,device=self.settings['device'],active=self.active,backend_running=bool(self.process and self.process.poll() is None),selected_profile=selected['name'] if selected else None) def unload_idle(self): if self.active:raise ValueError('SoulX-Singer-Auftrag läuft; Wechsel erst danach möglich.') if self.process and self.process.poll() is None: try:os.killpg(self.process.pid,signal.SIGTERM);self.process.wait(10) except subprocess.TimeoutExpired:os.killpg(self.process.pid,signal.SIGKILL);self.process.wait() except ProcessLookupError:pass self.process=None self.ensure() # fresh CPU-only UI process; no weights load before the next lease def configure(self,data): if set(data)!={'device'} or data['device'] not in ('3060','5080'):raise ValueError('RTX 3060 oder RTX 5080 auswählen.') with self.lock: if self.active:raise ValueError('SoulX-Singer-Auftrag läuft; GPU erst danach ändern.') self.settings=dict(data);temp=self.settings_path.with_suffix('.tmp');temp.write_text(json.dumps(data));temp.replace(self.settings_path) self.unload_idle() return self.status() def ensure(self): with self.lock: if self.process and self.process.poll() is None:return python,source=self.runtime.paths() if not python.is_file():return from image_test import probe gpu=next((g for g in probe() if self.settings['device'] in g['name']),None) if not gpu:return for name in ('results','uploads','tmp'):(self.root/name).mkdir(exist_ok=True) env={k:v for k,v in os.environ.items() if not k.startswith(('HF_','DECK_'))} env.update(SOULX_SINGER_BIND=os.environ.get('DECK_BIND_HOST','127.0.0.1'),SOULX_WHISPER_PATH=str(source.parent/'assets/whisper-base'),SOULX_SINGER_SOURCE=str(source),SOULX_SINGER_ASSETS=str(source.parent/'assets'),SOULX_SINGER_OUTPUT=str(self.root/'results'),SOULX_SINGER_LEASE_SOCKET=str(self.socket),SOULX_SINGER_BRIDGE_KEY_FILE=str(self.root/'bridge-key'),CUDA_VISIBLE_DEVICES=gpu['uuid'],HF_HUB_OFFLINE='1',HF_HUB_DISABLE_TELEMETRY='1',GRADIO_ANALYTICS_ENABLED='False',GRADIO_TEMP_DIR=str(self.root/'uploads'),TMPDIR=str(self.root/'tmp'),OMP_NUM_THREADS='4',PYTHONPATH=str(source)) script=Path(__file__).parent/'deploy/soulx-singer-web/native_ui.py';log=(self.root/'backend.log').open('a') self.process=self._spawn([str(python),str(Path(__file__).parent/'applio_worker.py'),'--exec',str(python),str(script)],cwd=source,env=env,stdout=log,stderr=log,start_new_session=True);log.close()