Files
Athena-Deck/applio.py

87 lines
6.3 KiB
Python

"""Native custom Applio backend with Deck-controlled GPU leases."""
import json,os,secrets,signal,socket,subprocess,threading,time,urllib.request
from pathlib import Path
from applio_runtime import REVISION
def applio_model(model):return bool(model and model.get('kind')=='voice' and model.get('file','').endswith('.pth') and (model.get('runtime_metadata') or {}).get('architecture')=='rvc')
class Applio:
def __init__(self,root,runtime,scheduler,profiles,enabled):
self.root=Path(root);self.runtime=runtime;self.scheduler=scheduler;self.profiles=profiles;self.enabled=enabled;self.lock=threading.RLock();self.process=None;self.stop_event=threading.Event();self.active=False
self.root.mkdir(parents=True,exist_ok=True,mode=0o700)
key=self.root/'bridge-key'
if not key.exists():key.write_text(secrets.token_urlsafe(48));key.chmod(0o600)
self.key=key.read_text().strip();self.settings_path=self.root/'settings.json';self.settings=json.loads(self.settings_path.read_text()) if self.settings_path.exists() else {'device':'3060'}
self.socket=self.root/'lease.sock';self.socket.unlink(missing_ok=True);self.listener=socket.socket(socket.AF_UNIX);self.listener.bind(str(self.socket));self.socket.chmod(0o600);self.listener.listen(4);self.listener.settimeout(1)
threading.Thread(target=self._accept,daemon=True).start()
def selected(self):return next((p for p in self.profiles.status()['profiles'] if applio_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 ['Applio-Laufzeit unter Laufzeiten installieren.']
def status(self):
installed=self.runtime.status()['installed']
if installed:self.ensure()
return dict(installed=installed,version='3.6.5',device=self.settings['device'],active=self.active,backend_running=bool(self.process and self.process.poll() is None),model_count=len(list((self.root/'logs').rglob('*.pth'))),selected_profile=self.selected()['name'] if self.selected() else None,custom_data_backup='Eigene Stimmen und Trainingsdaten sind lokale Originale. Deck-Konfigurationsbackup enthält diese großen Dateien nicht; separater Datenexport erforderlich.')
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('Applio-Auftrag läuft; GPU erst danach ändern.')
self.unload_idle();self.settings=dict(data);tmp=self.settings_path.with_suffix('.tmp');tmp.write_text(json.dumps(data));tmp.replace(self.settings_path)
return self.status()
def _accept(self):
while not self.stop_event.is_set():
try:c,_=self.listener.accept()
except socket.timeout:continue
except OSError:return
threading.Thread(target=self._lease,args=(c,),daemon=True).start()
def _lease(self,c):
release=None;owned=False
try:
c.settimeout(10);request=json.loads(c.makefile('rb').readline(8193))
if request!={'action':'reserve'}:raise ValueError('Ungültige Ressourcenanfrage.')
with self.lock:
if self.active:raise ValueError(getattr(self,'label','Applio')+' arbeitet bereits.')
if self.scheduler.gpu_mode!='voice' or not self.selected():raise ValueError(getattr(self,'label','Applio')+'-Profil in Deck aktivieren und Steuerung → Stimmwerkzeuge starten.')
self.active=True;owned=True
release=self.scheduler.image_reservation(False,kind='voice')
from image_test import probe
gpu=next((g for g in probe() if self.settings['device'] in g['name']),None)
if not gpu:raise ValueError('Ausgewählte GPU nicht verfügbar.')
c.sendall((json.dumps({'ok':True,'gpu':gpu['uuid']})+'\n').encode());c.settimeout(None)
c.recv(1) # EOF or explicit release; a crashed backend cannot leak a lease.
except Exception as exc:
try:c.sendall((json.dumps({'error':str(exc)})+'\n').encode())
except OSError:pass
finally:
if release:release()
if owned:
with self.lock:self.active=False
c.close()
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
for name in ('logs','datasets','jobs','results','uploads'):(self.root/name).mkdir(exist_ok=True)
# Only the NEW runtime links to Deck's mutable project data.
logs=source/'logs'
if not logs.is_symlink():
if logs.exists():
import shutil;shutil.rmtree(logs)
logs.symlink_to(self.root/'logs',target_is_directory=True)
env={k:v for k,v in os.environ.items() if not k.startswith(('HF_','DECK_'))}
env.update(PYTHONPATH=str(Path(__file__).parent/'deploy/applio-web/backend'),APPLIO_PATH=str(source),APPLIO_WORKDIR=str(source),APPLIO_PYTHON=str(python),APPLIO_LEASE_SOCKET=str(self.socket),APPLIO_REALTIME_URL='ws://127.0.0.1:6970/ws-audio',APPLIO_BRIDGE_KEY_FILE=str(self.root/'bridge-key'),APPLIO_WORKER_SCRIPT=str(Path(__file__).parent/'applio_worker.py'),FRONTEND_DIR=str(Path(__file__).parent/'deploy/applio-web/frontend'),HF_HUB_OFFLINE='1',OMP_NUM_THREADS='4')
for name in ('MODELS','DATASETS','JOBS','RESULTS','UPLOADS'):env[name+'_DIR']=str(self.root/('logs' if name=='MODELS' else name.lower()))
for name in ('MODELS','DATASETS','RESULTS','UPLOADS'):env['APPLIO_'+name+'_DIR']=env[name+'_DIR']
log=(self.root/'backend.log').open('a');self.process=subprocess.Popen([str(python),str(Path(__file__).parent/'applio_worker.py'),'--exec',str(python),'-m','uvicorn','app.main:app','--host',os.environ.get('DECK_BIND_HOST','127.0.0.1'),'--port','8134','--no-access-log'],cwd=Path(__file__).parent/'deploy/applio-web/backend',env=env,stdout=log,stderr=log,start_new_session=True);log.close()
def unload_idle(self):
if self.active:raise ValueError('Applio-Auftrag läuft.')
if self.process and self.process.poll() is None:
try:
req=urllib.request.Request('http://127.0.0.1:8134/api/deck/unload',data=b'{}',headers={'X-Applio-Bridge':self.key,'Content-Type':'application/json'})
with urllib.request.urlopen(req,timeout=15):pass
except OSError as exc:raise ValueError("Applio-Worker konnte nicht entladen werden; Moduswechsel abgebrochen.") from exc
def stop(self):
self.stop_event.set();self.listener.close()
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