"""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()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 0deadline: 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