#!/usr/bin/env python3 """Unprivileged native Basalt build: no Docker, model load, driver/service changes.""" import argparse import ctypes import ctypes.util import hashlib import json import os from pathlib import Path import re import shutil import subprocess import sys APP=Path(__file__).resolve().parent.parent RECIPE=json.loads((APP/'basalt_sources.json').read_text()) sys.path.insert(0,str(APP)) from basalt_tuning import install_profile def video_libraries(): """Load only the FFmpeg ABI, without a GPU, decoder, model or subprocess.""" names={'avcodec':'avcodec_version','avformat':'avformat_version','avutil':'avutil_version','swscale':'swscale_version'} versions={};libraries={} try: for name,symbol in names.items(): path=ctypes.util.find_library(name) if not path:raise ValueError('FFmpeg-Bibliothek fehlt: '+name) lib=ctypes.CDLL(path);function=getattr(lib,symbol);function.restype=ctypes.c_uint versions[name]=function()>>16;libraries[name]=path major={(60,60,58,7):6,(61,61,59,8):7,(62,62,60,9):8}.get(tuple(versions[n] for n in names)) if major is None:raise ValueError('Video benötigt zusammenpassende FFmpeg-6/7/8-Bibliotheken.') return dict(available=True,ffmpeg_major=major,libraries=libraries,abi_only=True) except (OSError,AttributeError,ValueError) as exc: return dict(available=False,reason=str(exc),abi_only=True) def install(destination,nvcc=None): destination=Path(destination).absolute() if destination==Path('/') or destination.is_symlink():raise ValueError('Eigene Laufzeitwurzel erforderlich.') destination=destination.resolve() for tool in ('git','g++'): if not shutil.which(tool):raise ValueError('Native Build-Abhängigkeit fehlt: '+tool) destination.mkdir(parents=True,exist_ok=True,mode=0o700) for name in ('home','tmp','cache','cache/pip','cache/cuda'):(destination/name).mkdir(parents=True,exist_ok=True) env=dict(os.environ,HOME=str(destination/'home'),TMPDIR=str(destination/'tmp'),XDG_CACHE_HOME=str(destination/'cache'),PIP_CACHE_DIR=str(destination/'cache/pip'),CUDA_CACHE_PATH=str(destination/'cache/cuda'),GIT_TERMINAL_PROMPT='0',PIP_NO_INPUT='1',PIP_DISABLE_PIP_VERSION_CHECK='1',CUDA_VISIBLE_DEVICES='',NVIDIA_VISIBLE_DEVICES='void') def run(args,**kwargs):return subprocess.run(list(map(str,args)),env=env,check=True,**kwargs) if not nvcc: from strata_toolkit import toolkit nvcc=str(toolkit(destination/'cuda')) version=subprocess.check_output([nvcc,'--version'],text=True) if not re.search(r'release 13\.0\b',version):raise ValueError('Dieses geprüfte Basalt-Rezept benötigt CUDA Toolkit 13.0.') source=destination/'source' if not source.exists(): run(['git','init',source]);run(['git','-C',source,'fetch','--depth','1',RECIPE['url'],RECIPE['code']]) run(['git','-C',source,'sparse-checkout','init','--no-cone']) run(['git','-C',source,'sparse-checkout','set','--no-cone','--stdin'],input='/*\n!/**/vpn/\n!/vpn/\n!/**/vpn.auth\n!/vpn.auth\n',text=True) run(['git','-C',source,'checkout','--detach','FETCH_HEAD']) if subprocess.check_output(['git','-C',source,'rev-parse','HEAD'],text=True).strip()!=RECIPE['code']:raise ValueError('Basalt-Quellversion weicht vom Rezept ab; keine automatische Überschreibung.') if subprocess.check_output(['git','-C',source,'status','--porcelain','--untracked-files=no'],text=True).strip():raise ValueError('Lokale Basalt-Quelländerungen zuerst prüfen.') python=destination/'venv/bin/python' if not python.is_file():run([sys.executable,'-m','venv',destination/'venv']) run([python,'-m','pip','install','--index-url','https://pypi.org/simple','cmake==3.31.6','ninja==1.11.1.4','-r',source/'requirements.txt']) toolkit_root=Path(nvcc).parent.parent env.update(PATH=str(python.parent)+os.pathsep+str(Path(nvcc).parent)+os.pathsep+env.get('PATH',''),LD_LIBRARY_PATH=str(toolkit_root/'lib64')+os.pathsep+str(toolkit_root/'lib')+os.pathsep+env.get('LD_LIBRARY_PATH','')) build=destination/'build' run([python.parent/'cmake','-S',source,'-B',build,'-G','Ninja','-DCMAKE_BUILD_TYPE=Release','-DBUILD_TESTING=OFF','-DCMAKE_CUDA_ARCHITECTURES=120','-DCMAKE_CUDA_COMPILER='+str(nvcc),'-DCUDAToolkit_ROOT='+str(toolkit_root),'-DCMAKE_MAKE_PROGRAM='+str(python.parent/'ninja')]) run([python.parent/'cmake','--build',build,'--target','basalt','--parallel','1']) # The encoder is independent of the text engine's SM120-only kernels. vision=destination/'build-vision' run([python.parent/'cmake','-S',source/'tools/vision','-B',vision,'-G','Ninja','-DCMAKE_BUILD_TYPE=Release','-DBUILD_TESTING=OFF','-DCMAKE_CUDA_ARCHITECTURES=86;120','-DCMAKE_CUDA_COMPILER='+str(nvcc),'-DCUDAToolkit_ROOT='+str(toolkit_root),'-DCMAKE_MAKE_PROGRAM='+str(python.parent/'ninja')]) run([python.parent/'cmake','--build',vision,'--target','basalt-vision','--parallel','1']) run([python,'-m','pip','check']) pdf_version=run([python,'-c','import pypdf;print(pypdf.__version__)'],capture_output=True,text=True).stdout.strip() if pdf_version!='7.0.1':raise ValueError('Das gepinnte PDF-Modul pypdf 7.0.1 fehlt.') output=subprocess.run([str(source/'bin/basalt'),'--help'],env=env,capture_output=True,text=True,check=True) if 'basalt serve' not in output.stdout+output.stderr:raise ValueError('Gebautes Basalt-Binary hat nicht die erwartete Server-CLI.') lock=run([python,'-m','pip','freeze','--all'],capture_output=True,text=True).stdout (destination/'python-lock.txt').write_text(lock) binary=source/'bin/basalt' if not (source/'data/profiles/qwen4exp-48x512.prof').is_file():raise ValueError('Das Basalt-Expertenprofil muss mit dem Engine-Quellbaum ausgeliefert werden.') install_profile(destination,RECIPE) marker=dict(commit=RECIPE['code'],version=RECIPE['version'],cuda='13.0',architectures=[120],vision_architectures=RECIPE['vision_architectures'],python=sys.version.split()[0],binary_sha256=hashlib.sha256(binary.read_bytes()).hexdigest(),vision_binary_sha256=hashlib.sha256((source/'bin/basalt-vision').read_bytes()).hexdigest(),pdf_version=pdf_version,video=video_libraries(),origin='native-build',inference_performed=False) pending=destination/'ready.tmp';pending.write_text(json.dumps(marker,indent=2));pending.replace(destination/'ready.json') return marker if __name__=='__main__': parser=argparse.ArgumentParser();parser.add_argument('--destination',required=True);parser.add_argument('--nvcc');args=parser.parse_args();install(args.destination,args.nvcc)