Files
Mikei386 06cacafbad Add native Applio RVC and preserve the custom studio UI
Pin Applio 3.6.5 and verified basis assets, migrate private voice provenance, and coordinate conversion/live/training with Deck GPU leases. Prepare an inactive voice profile and a restricted studio container. Move CUDA and Torch caches out of the small temporary filesystem to prevent OmniVoice reference failures. Package app updates from the explicit allowlist in one Docker layer.
2026-10-05 10:02:07 +02:00

105 lines
6.3 KiB
Python

"""Preserve our UI's proven artifact checks; execute in Deck's native runtime."""
import json,os,re,selectors,signal,socket,subprocess,threading,time
from pathlib import Path
from .real_runner import RealApplioRunner,_ApplioError,_CancelledError
class NativeRunner(RealApplioRunner):
def __init__(self):super().__init__();self.worker=None;self.worker_gpu=None;self.env=None;self.lock=threading.RLock()
def name(self):return 'Athena Deck · Applio 3.6.5 · native GPU-Laufzeit'
def is_available(self):return Path(self._settings.applio_python).is_file() and Path(self._settings.applio_workdir,'core.py').is_file()
def _build_cmd(self,subcommand,args):return [str(self._settings.applio_python),self._settings.applio_core_py,subcommand,*args]
def _map_host_to_container(self,value):
if not value:return ''
p=Path(value).resolve()
if any(p.is_relative_to(root.resolve()) for root in (self._settings.models_dir,self._settings.datasets_dir,self._settings.uploads_dir,self._settings.results_dir)):return str(p)
raise _ApplioError('Pfad liegt außerhalb der Applio-Projektverzeichnisse.')
def execute(self,job,cancel_event):
lease=None
try:
lease,gpu=reserve()
self.env=dict(os.environ,CUDA_VISIBLE_DEVICES=gpu,HF_HUB_OFFLINE='1')
# Physical GPUs are selected by Deck; inside the child the only GPU is 0.
job.parameters['gpu']='0'
if job.parameters.get('dataset_path'):job.parameters['dataset_path']=self._map_host_to_container(job.parameters['dataset_path'])
if job.parameters.get('embedder_model','contentvec')!='contentvec':raise _ApplioError('Für diesen Embedder fehlt das geprüfte Komponentenpaket. ContentVec verwenden.')
super().execute(job,cancel_event)
except Exception as exc:job.mark_failed(str(exc))
finally:
if lease:lease.close()
def unload(self):
with self.lock:
p=self.worker;self.worker=None;self.worker_gpu=None
if p and p.poll() is None:
try:os.killpg(p.pid,signal.SIGTERM);p.wait(5)
except subprocess.TimeoutExpired:os.killpg(p.pid,signal.SIGKILL);p.wait()
except ProcessLookupError:pass
def _reply(self,proc,cancel,timeout):
deadline=time.monotonic()+timeout
with selectors.DefaultSelector() as sel:
sel.register(proc.stdout,selectors.EVENT_READ)
while time.monotonic()<deadline:
if cancel.is_set():self.unload();raise _CancelledError()
if proc.poll() is not None:raise _ApplioError('Applio-Inferenzworker beendet. Backend-Ausgabe prüfen.')
if sel.select(.2):
line=proc.stdout.readline()
if not line:raise _ApplioError('Applio-Inferenzworker lieferte keine Antwort.')
return json.loads(line)
self.unload();raise _ApplioError('Zeitüberschreitung beim Applio-Auftrag.')
def _infer(self,cmd,job,cancel,timeout):
args=cmd[3:];values={}
while args:
flag=args.pop(0).removeprefix('--').replace('-','_');value=args.pop(0) if args and not args[0].startswith('--') else 'True'
if value in ('True','False'):value=value=='True'
elif flag in ('pitch',):value=int(value)
elif flag in ('index_rate','protect','volume_envelope','f0_autotune_strength','clean_strength'):value=float(value)
values[flag]=value
for old,new in [('input_path','audio_input_path'),('output_path','audio_output_path'),('pth_path','model_path')]:values[new]=values.pop(old)
gpu=self.env['CUDA_VISIBLE_DEVICES']
if self.worker_gpu!=gpu or not self.worker or self.worker.poll() is not None:
self.unload();log=Path(self._settings.jobs_dir,'inference-worker.log').open('a')
self.worker=subprocess.Popen([str(self._settings.applio_python),os.environ['APPLIO_WORKER_SCRIPT']],cwd=self._settings.applio_workdir,env=self.env,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=log,text=True,bufsize=1,start_new_session=True);log.close();self.worker_gpu=gpu
response=self._reply(self.worker,cancel,180)
if not response.get('ready'):raise _ApplioError('Applio-Inferenzworker ist nicht bereit.')
self.worker.stdin.write(json.dumps(values)+'\n');self.worker.stdin.flush();response=self._reply(self.worker,cancel,timeout)
if response.get('error'):raise _ApplioError(response['error'])
return subprocess.CompletedProcess(cmd,0,stdout='',stderr='')
def _run_cmd(self,cmd,job,cancel_event,timeout=3600):
if cmd[:2]==['docker','exec']:cmd=[str(self._settings.applio_python),*cmd[6:]] # old TTS helper, now native
if len(cmd)>2 and cmd[2]=='infer':return self._infer(cmd,job,cancel_event,timeout)
self.unload() # training owns the GPU, cached inference weights must release it
normalized=[]
for arg in cmd:
normalized.append(arg.replace('_','-') if arg.startswith('--') else arg)
proc=subprocess.Popen([str(self._settings.applio_python),os.environ['APPLIO_WORKER_SCRIPT'],'--exec',*normalized],cwd=self._settings.applio_workdir,env=self.env,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True,start_new_session=True)
lines=[]
def read():
for line in proc.stdout:
clean=line.rstrip();lines.append(clean);job.add_log(clean)
match=re.search(r'(?:epoch|Epoch)[^0-9]*(\d+)',clean)
if match and job.type.value=='train':
current=int(match.group(1));total=max(1,int(job.parameters.get('total_epoch',1)))
if 0<current<=total:job.progress=min(99.0,current/total*100);job.progress_message=f'Training: Epoche {current} von {total}'
thread=threading.Thread(target=read,daemon=True);thread.start();deadline=time.monotonic()+timeout
while proc.poll() is None:
if cancel_event.is_set() or time.monotonic()>deadline:
try:os.killpg(proc.pid,signal.SIGTERM);proc.wait(5)
except subprocess.TimeoutExpired:os.killpg(proc.pid,signal.SIGKILL);proc.wait()
except ProcessLookupError:pass
thread.join(5)
if cancel_event.is_set():raise _CancelledError()
raise _ApplioError('Zeitüberschreitung beim Applio-Auftrag.')
time.sleep(.2)
thread.join(5)
if proc.returncode:raise _ApplioError('Applio fehlgeschlagen (Exit '+str(proc.returncode)+'): '+'\n'.join(lines[-12:]))
return subprocess.CompletedProcess(normalized,0,stdout='\n'.join(lines),stderr='')
def reserve():
c=socket.socket(socket.AF_UNIX);c.connect(os.environ['APPLIO_LEASE_SOCKET']);c.sendall(b'{"action":"reserve"}\n');reply=json.loads(c.makefile('rb').readline(8193))
if not reply.get('ok'):c.close();raise ValueError(reply.get('error','Deck-Ressourcen nicht verfügbar.'))
return c,reply['gpu']
_runner=None
def get_native_runner():
global _runner
if _runner is None:_runner=NativeRunner()
return _runner