Files
Athena-Deck/seed_vc_runtime.py
T

75 lines
6.1 KiB
Python

"""Seed-VC inference environment and immutable, verified model sources; setup is CPU-only."""
import hashlib,json,os,shutil,sys,time,urllib.request
from pathlib import Path
from ltx_original_runtime import LTXOriginalRuntime
REVISION='51383efd921027683c89e5348211d93ff12ac2a8'
MODEL_REVISION=next(x['revision'] for x in json.loads(Path(__file__).with_name('seed_vc_sources.json').read_text()) if x['repo']=='Plachta/Seed-VC')
REPO='Plachta/Seed-VC'
ASSETS=json.loads(Path(__file__).with_name('seed_vc_sources.json').read_text())
RECIPE_HASH=hashlib.sha256(json.dumps(ASSETS,sort_keys=True).encode()).hexdigest()
class SeedVCRuntime(LTXOriginalRuntime):
name='Seed-VC'
def paths(self):
try:
ident=json.loads((self.root/'active.json').read_text())['id'];base=self.root/ident
if len(ident)==32 and all(c in '0123456789abcdef' for c in ident) and (base/'ready').read_text().strip()==REVISION:return base/'python/bin/python',base/'source'
except (OSError,ValueError,KeyError):pass
return self.root/'missing-python',self.root/'missing-source'
def status(self):
python,source=self.paths()
return dict(installed=python.is_file() and (source/'app_svc.py').is_file(),revision=REVISION,model_revision=MODEL_REVISION,recipe_hash=RECIPE_HASH,job=dict(self.job) if self.job else None,required_disk_gib=15,origin=REPO,worker_available=True,message='Gesang plus Referenzstimme → Gesang in der Zielstimme, 44,1 kHz. Originalprojekt archiviert; Testintegration. Installation lädt alle Komponenten; sie startet kein Modell.')
def ensure_library(self):
_,source=self.paths();base=source.parent;main=ASSETS[0];ident=hashlib.sha256((REPO+MODEL_REVISION+main['file']).encode()).hexdigest();folder=self.root.parent/'models'/ident;folder.mkdir(parents=True,exist_ok=True)
target=folder/'model.pth'
asset=base/'assets'/(main['repo'].replace('/','--')+'/'+main['file']);relative=os.path.relpath(asset,folder)
if target.is_symlink():
old=os.readlink(target)
if old not in (relative,str(asset),'/var/lib/deck/seed_vc-runtime/'+base.name+'/assets/'+(main['repo'].replace('/','--')+'/'+main['file'])):raise ValueError('Seed-VC-Bibliothekslink zeigt auf eine fremde Datei.')
if old!=relative:target.unlink();target.symlink_to(relative)
elif not target.exists():target.symlink_to(relative)
entry=dict(repo=REPO,revision=MODEL_REVISION,file=main['file'],kind='voice',size=main['size'],sha256=main['sha256'],upstream_hash_verified=True,downloaded_at=time.time(),runtime_metadata={'architecture':'seed_vc'})
(folder/'entry.json').write_text(json.dumps(entry));return ident
def _run(self):
base=self.root/self.job['id'];state='failed';phase='Seed-VC-Einrichtung fehlgeschlagen.'
try:
base.mkdir(mode=0o700);tmp=base/'tmp';tmp.mkdir();source=base/'source'
env=dict(os.environ,CUDA_VISIBLE_DEVICES='',TMPDIR=str(tmp),PIP_NO_INPUT='1',PIP_DISABLE_PIP_VERSION_CHECK='1',GIT_TERMINAL_PROMPT='0')
self._phase('Offiziellen Seed-VC-Quellcode beziehen')
for args in (['git','init',source],['git','-C',source,'fetch','--depth','1','https://github.com/Plachtaa/seed-vc.git',REVISION],['git','-C',source,'checkout','--detach','FETCH_HEAD']):self._command(args,env)
shared=self.image_runtime.paths()[0] if self.image_runtime else Path('/missing')
self._command([shared if shared.is_file() else sys.executable,'-m','venv',base/'python'],env);python=base/'python/bin/python'
self._phase('Isolierte Seed-VC-Abhängigkeiten installieren; keine GPU-Ausführung')
self._command([python,'-m','pip','install','--no-cache-dir','torch==2.8.0','torchaudio==2.8.0','--index-url','https://download.pytorch.org/whl/cu128'],env)
self._command([python,'-m','pip','install','--no-cache-dir','-r',Path(__file__).parent/'deploy/seed-vc-requirements.lock'],env)
self._phase('Seed-VC und alle Zusatzgewichte mit Prüfsummen herunterladen')
for item in ASSETS:
if self.cancel.is_set():raise InterruptedError()
dest=base/'assets'/(item['repo'].replace('/','--')+'/'+item['file']);dest.parent.mkdir(parents=True,exist_ok=True)
prefix='https://huggingface.co/'+item['repo']+'/resolve/'+item['revision']+'/'
sha=hashlib.sha256();git=hashlib.sha1(('blob '+str(item['size'])+'\0').encode())
with urllib.request.urlopen(prefix+item['file'],timeout=90) as response,dest.open('wb') as output:
while chunk:=response.read(4*1024**2):
if self.cancel.is_set():raise InterruptedError()
output.write(chunk);sha.update(chunk);git.update(chunk)
if dest.stat().st_size!=item['size'] or (sha.hexdigest()!=item['sha256'] if item['sha256'] else git.hexdigest()!=item['git_sha1']):raise ValueError('Seed-VC-Komponenten-Prüfsumme falsch: '+item['file'])
(base/'asset-sources.json').write_text(json.dumps(ASSETS,indent=2))
# Only inference dependencies; no training or desktop GUI packages.
self._command([python,'-c','import sys;sys.path.insert(0,sys.argv[1]);import torch,transformers,gradio,munch,soundfile,librosa,dac,audiotools,app_svc;from modules.length_regulator import InterpolateRegulator;assert not torch.cuda.is_available()',source],env)
self._command([python,'-m','pip','freeze'],env)
(base/'ready').write_text(REVISION);marker=self.root/'active.tmp';marker.write_text(json.dumps({'id':base.name}));marker.replace(self.root/'active.json');self.ensure_library();state='complete';phase='Seed-VC vorbereitet · nicht gestartet, kein Profil aktiviert'
except InterruptedError:state='cancelled';phase='Seed-VC-Einrichtung abgebrochen.'
except Exception as exc:phase=str(exc)
finally:
if state!='complete':shutil.rmtree(base,ignore_errors=True)
with self.lock:self.process=None;self.job.update(state=state,phase=phase,finished_at=time.time());self._save()
if __name__=='__main__':
import argparse
parser=argparse.ArgumentParser(description='Native Seed-VC installation; no model execution')
parser.add_argument('--state-root',type=Path,required=True)
args=parser.parse_args();runtime=SeedVCRuntime(args.state_root/'seed_vc-runtime',None)
if not runtime.status()['installed']:
runtime.start();runtime.worker.join()
print(json.dumps(runtime.status(),ensure_ascii=False))
raise SystemExit(0 if runtime.status()['installed'] else 1)