70 lines
6.1 KiB
Python
70 lines
6.1 KiB
Python
"""X-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='49df8c591eafc48b096e466d96f9839f9c0dd739'
|
|
MODEL_REVISION='9e54747d8c4d1ef544b903e2300a4ba040dcc126'
|
|
REPO='chenxie95/X-VC'
|
|
ASSETS=json.loads(Path(__file__).with_name('xvc_sources.json').read_text())
|
|
RECIPE_HASH=hashlib.sha256(json.dumps(ASSETS,sort_keys=True).encode()).hexdigest()
|
|
class XVCRuntime(LTXOriginalRuntime):
|
|
name='X-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/'models/codec/sac/model.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=25,origin=REPO,worker_available=True,message='Audio-zu-Audio-Stimmumwandlung mit optionalem Resemble Enhance. Installation lädt alle Komponenten; sie startet kein Modell.')
|
|
def ensure_library(self):
|
|
_,source=self.paths();base=source.parent;main=next(x for x in ASSETS if x['file']=='xvc.pt');ident=hashlib.sha256((REPO+MODEL_REVISION+'xvc.pt').encode()).hexdigest();folder=self.root.parent/'models'/ident;folder.mkdir(parents=True,exist_ok=True)
|
|
target=folder/'model.pt'
|
|
asset=base/'assets'/main['target'];relative=os.path.relpath(asset,folder)
|
|
if target.is_symlink():
|
|
old=os.readlink(target)
|
|
if old not in (relative,str(asset),'/var/lib/deck/xvc-runtime/'+base.name+'/assets/'+main['target']):raise ValueError('X-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='xvc.pt',kind='voice',size=main['size'],sha256=main['sha256'],upstream_hash_verified=True,downloaded_at=time.time(),runtime_metadata={'architecture':'xvc'})
|
|
(folder/'entry.json').write_text(json.dumps(entry));return ident
|
|
def _run(self):
|
|
base=self.root/self.job['id'];state='failed';phase='X-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 X-VC-Quellcode beziehen')
|
|
for args in (['git','init',source],['git','-C',source,'fetch','--depth','1','https://github.com/Jerrister/X-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 X-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)
|
|
lock=Path(__file__).parent/'deploy/xvc-requirements.lock'
|
|
requirements=['gradio==5.49.1','huggingface_hub>=0.34,<1','transformers>=4.44,<5','hydra-core>=1.3,<2','omegaconf>=2.3,<3','x-transformers>=1.40,<3','einops>=0.8,<1','einx>=0.3,<1','numpy==1.26.4','scipy==1.11.4','soundfile==0.12.1','soxr>=0.5,<1','tqdm>=4.66,<5','librosa==0.10.1','descript-audiotools==0.7.2','matplotlib>=3.8,<4','pandas>=2.1,<3','rich>=13,<15','tabulate>=0.9,<1','uvicorn','httpx','websockets']
|
|
self._command([python,'-m','pip','install','--no-cache-dir',*(['-c',lock] if lock.exists() else []),*requirements],env)
|
|
self._command([python,'-m','pip','install','--no-cache-dir','--no-deps','resemble-enhance==0.0.1'],env)
|
|
ui=Path(__file__).parent/'deploy/xvc-web'
|
|
self._command([python,ui/'patch_resemble_enhance.py'],env);shutil.copyfile(ui/'inference_log.py',source/'utils/log.py')
|
|
self._phase('X-VC und alle Zusatzgewichte mit Prüfsummen herunterladen')
|
|
for item in ASSETS:
|
|
if self.cancel.is_set():raise InterruptedError()
|
|
dest=base/'assets'/item['target'];dest.parent.mkdir(parents=True,exist_ok=True)
|
|
prefix='https://huggingface.co/'+('spaces/' if item['repo_type']=='space' else '')+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('X-VC-Komponenten-Prüfsumme falsch: '+item['file'])
|
|
(base/'asset-sources.json').write_text(json.dumps(ASSETS,indent=2))
|
|
# Inference intentionally omits Resemble's obsolete training dependencies.
|
|
self._command([python,'-c','import torch,transformers,gradio,hydra,soundfile,librosa,audiotools; import resemble_enhance.enhancer.inference; assert not torch.cuda.is_available()'],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='X-VC vorbereitet · nicht gestartet, kein Profil aktiviert'
|
|
except InterruptedError:state='cancelled';phase='X-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()
|