aisop/tools/Setup-Python.ps1

35 lines
2.3 KiB
PowerShell

param([switch]$Sam2, [switch]$Cpu)
$ErrorActionPreference = 'Stop'
$projectRoot = Split-Path $PSScriptRoot -Parent
$env:PIP_CACHE_DIR = Join-Path $projectRoot '.cache/pip'
$runtimeRoot = Join-Path $projectRoot 'python'
$pythonPath = Join-Path $runtimeRoot 'python.exe'
function Invoke-Checked([string]$Program, [string[]]$Arguments) {
& $Program @Arguments
if ($LASTEXITCODE -ne 0) { throw "执行失败: $Program $($Arguments -join ' ')" }
}
if (!(Test-Path -LiteralPath $pythonPath)) {
# Copy a complete runtime, independent of the system Python and venv home.
$baseRoot = & python -c "import sys; print(sys.base_prefix)"
if ($LASTEXITCODE -ne 0) { throw 'Cannot locate bootstrap Python' }
New-Item -ItemType Directory -Force -Path $runtimeRoot | Out-Null
& robocopy $baseRoot $runtimeRoot /E /XD 'site-packages' '__pycache__' /XF '*.pyc' '*.lnk' /NFL /NDL /NJH /NJS
if ($LASTEXITCODE -ge 8) { throw 'Failed to copy Python runtime' }
Invoke-Checked $pythonPath @('-m', 'ensurepip', '--upgrade')
}
Invoke-Checked $pythonPath @('-m', 'pip', 'install', '--upgrade', 'pip')
$torchFlavor = if ($Cpu) { 'cpu' } else { 'cu128' }
# Pin a matching pair: an already installed newer CPU wheel otherwise satisfies an unpinned install.
Invoke-Checked $pythonPath @('-m', 'pip', 'install', '--upgrade', "torch==2.11.0+$torchFlavor", "torchvision==0.26.0+$torchFlavor", '--index-url', "https://download.pytorch.org/whl/$torchFlavor")
Invoke-Checked $pythonPath @('-m', 'pip', 'install', '-r', (Join-Path $PSScriptRoot 'requirements.txt'))
if ($Sam2) {
# SAM2's optional CUDA extension is unnecessary for basic box propagation on Windows.
$env:SAM2_BUILD_CUDA = '0'
Invoke-Checked $pythonPath @('-m', 'pip', 'install', 'wheel', 'huggingface_hub')
Invoke-Checked $pythonPath @('-m', 'pip', 'install', '--no-build-isolation', 'git+https://github.com/facebookresearch/sam2.git@2b90b9f5ceec907a1c18123530e92e794ad901a4')
}
if (!$Cpu) {
Invoke-Checked $pythonPath @('-c', 'import torch; assert torch.cuda.is_available(), "CUDA unavailable: check the NVIDIA driver or explicitly use -Cpu"; x=torch.ones((32,32),device="cuda"); torch.cuda.synchronize(); print("GPU ready:",torch.cuda.get_device_name(0),"PyTorch",torch.__version__)')
}
Write-Host "完成。内置环境: $pythonPath;请重新构建/发布程序以携带 python 子目录。"