From a8555d131588de519f413a71e03d65da9f013bb0 Mon Sep 17 00:00:00 2001 From: RevLayDust <225862333+RevLayDust@users.noreply.github.com> Date: Sun, 11 Oct 2026 21:16:31 +0700 Subject: [PATCH] feat(installer): port package installer to 5-phase PowerShell pipeline with Pester test suite - Implement modular 5-phase architecture (Detect -> Plan -> Verify -> Install -> Validate + Record) compatible with PowerShell 5.1 - Consolidate all dependency pins, thresholds, and URLs in Config.ps1 as single source of truth - Pure, deterministic Plan generator supporting non-destructive DryRun - Hardware and invariant verification gate (NVIDIA CC >= 8.0 for TRT-RTX, min driver 570, disk space, process locks) - Safe mutation engine with pip freeze snapshot rollback and atomic install_record.json persistence - Add Pester test suite covering 15 scenarios across planning, verification, and recording - Convert install_packages.bat into thin CRLF launcher delegating to Install-UVR.ps1 --- install/Install-UVR.ps1 | 201 ++++++++ install/install_packages.bat | 850 +-------------------------------- install/lib/Common.ps1 | 280 +++++++++++ install/lib/Config.ps1 | 68 +++ install/lib/Detect.ps1 | 523 ++++++++++++++++++++ install/lib/Install.ps1 | 297 ++++++++++++ install/lib/Plan.ps1 | 364 ++++++++++++++ install/lib/Record.ps1 | 110 +++++ install/lib/Validate.ps1 | 207 ++++++++ install/lib/Verify.ps1 | 224 +++++++++ install/tests/Fixtures.ps1 | 140 ++++++ install/tests/Plan.Tests.ps1 | 102 ++++ install/tests/Record.Tests.ps1 | 47 ++ install/tests/Verify.Tests.ps1 | 88 ++++ 14 files changed, 2654 insertions(+), 847 deletions(-) create mode 100644 install/Install-UVR.ps1 create mode 100644 install/lib/Common.ps1 create mode 100644 install/lib/Config.ps1 create mode 100644 install/lib/Detect.ps1 create mode 100644 install/lib/Install.ps1 create mode 100644 install/lib/Plan.ps1 create mode 100644 install/lib/Record.ps1 create mode 100644 install/lib/Validate.ps1 create mode 100644 install/lib/Verify.ps1 create mode 100644 install/tests/Fixtures.ps1 create mode 100644 install/tests/Plan.Tests.ps1 create mode 100644 install/tests/Record.Tests.ps1 create mode 100644 install/tests/Verify.Tests.ps1 diff --git a/install/Install-UVR.ps1 b/install/Install-UVR.ps1 new file mode 100644 index 0000000..d3bde6d --- /dev/null +++ b/install/Install-UVR.ps1 @@ -0,0 +1,201 @@ +# Install-UVR.ps1 - Main entry point orchestrating the 5-phase installer pipeline +[CmdletBinding()] +param( + [Parameter(Mandatory = $false)] + [ValidateSet('A', 'B', 'C')] + [string]$Mode = '', + + [Parameter(Mandatory = $false)] + [switch]$Yes = $false, + + [Parameter(Mandatory = $false)] + [switch]$DryRun = $false, + + [Parameter(Mandatory = $false)] + [ValidateSet('Y', 'N')] + [string]$ReuseVenv = 'Y', + + [Parameter(Mandatory = $false)] + [string]$LogPath = '' +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' + +$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path +$rootDir = Split-Path -Parent $scriptDir +$libDir = Join-Path -Path $scriptDir -ChildPath 'lib' + +# Import library modules +. (Join-Path -Path $libDir -ChildPath 'Config.ps1') +. (Join-Path -Path $libDir -ChildPath 'Common.ps1') +. (Join-Path -Path $libDir -ChildPath 'Detect.ps1') +. (Join-Path -Path $libDir -ChildPath 'Plan.ps1') +. (Join-Path -Path $libDir -ChildPath 'Verify.ps1') +. (Join-Path -Path $libDir -ChildPath 'Install.ps1') +. (Join-Path -Path $libDir -ChildPath 'Validate.ps1') +. (Join-Path -Path $libDir -ChildPath 'Record.ps1') + +$config = Get-InstallerConfig + +$logDir = if ($LogPath) { Split-Path -Parent $LogPath } else { Join-Path -Path $rootDir -ChildPath 'install_logs' } +Initialize-InstallerLogger -LogDirectory $logDir + +Show-InstallerBanner -AppName $config.App.Name -PythonVersion $config.App.PythonVersion -TorchVersion $config.Torch.Version +Write-InstallerLog -Message "Starting $($config.App.Name) installer pipeline..." -Level INFO + +try { + # ---------------------------------------------------- + # Phase 1: Detect (Read-Only) + # ---------------------------------------------------- + Write-InstallerLog -Message "Phase 1: Detecting system, hardware, and environment..." -Level STEP + $facts = Get-InstallFacts -RootDirectory $rootDir -Config $config + + Write-InstallerLog -Message "Detected OS: $($facts.OS.VersionString) ($($facts.OS.Architecture))" -Level INFO + if ($facts.Gpu.HasNvidiaAdapter) { + Write-InstallerLog -Message "Detected GPU: $($facts.Gpu.Name) (Driver: $($facts.Gpu.DriverVersion), CC: $($facts.Gpu.ComputeCapability))" -Level INFO + } elseif ($facts.Gpu.HasAmd) { + Write-InstallerLog -Message "Detected AMD GPU: $($facts.Gpu.AmdName)" -Level INFO + } else { + Write-InstallerLog -Message "No dedicated GPU detected; using CPU." -Level INFO + } + + # ---------------------------------------------------- + # User Choice Resolution + # ---------------------------------------------------- + $choice = Resolve-UserChoice -Facts $facts -ExplicitMode $Mode -Yes:$Yes + Write-InstallerLog -Message "Selected installation option: [$choice]" -Level INFO + + # ---------------------------------------------------- + # Phase 2: Plan (Pure Function) + # ---------------------------------------------------- + Write-InstallerLog -Message "Phase 2: Generating installation plan..." -Level STEP + $plan = New-InstallPlan -Facts $facts -Choice $choice -Config $config -ReuseVenv $ReuseVenv + + # ---------------------------------------------------- + # Phase 3: Verification (Read-Only Gate) + # ---------------------------------------------------- + Write-InstallerLog -Message "Phase 3: Verifying plan against hardware invariants..." -Level STEP + $verdict = Test-InstallPlan -Facts $facts -Choice $choice -Plan $plan -Config $config + + if ($verdict.Status -eq 'Blocked') { + Write-Host "" + Write-Host "============================================================" -ForegroundColor Red + Write-Host " [BLOCKED] Installation cannot proceed on current system:" -ForegroundColor Red + Write-Host "============================================================" -ForegroundColor Red + foreach ($c in ($verdict.Checks | Where-Object { $_.Result -eq 'Fail' })) { + Write-Host " - $($c.Message)" -ForegroundColor Red + if ($c.Remediation) { + Write-Host " Remediation: $($c.Remediation)" -ForegroundColor Yellow + } + } + Write-Host "" + Write-InstallerLog -Message "Installation blocked at verification gate. No changes made." -Level ERROR + exit 2 + } + + if ($verdict.Status -eq 'Adjusted') { + Write-Host "" + Write-Host "============================================================" -ForegroundColor Yellow + Write-Host " [ADJUSTED] System requirements adjusted your selection:" -ForegroundColor Yellow + Write-Host "============================================================" -ForegroundColor Yellow + Write-Host " Reason: $($verdict.RecommendedReason)" -ForegroundColor Yellow + Write-Host " Target mode adjusted from [$choice] to [$($verdict.RecommendedOption)]." -ForegroundColor Cyan + Write-Host "" + + if (-not $Yes) { + $confirmAdjust = Prompt-UserChoice -PromptText "Proceed with adjusted mode [$($verdict.RecommendedOption)]? [Y/N, default Y]: " -ValidOptions @('Y', 'N') -DefaultOption 'Y' + if ($confirmAdjust -eq 'N') { + Write-InstallerLog -Message "Installation cancelled by user on adjustment prompt." -Level WARN + exit 10 + } + } + $choice = $verdict.RecommendedOption + $plan = New-InstallPlan -Facts $facts -Choice $choice -Config $config -ReuseVenv $ReuseVenv + } + + # Print Plan Table + Write-Host "" + Write-Host "Installation Plan for Profile [$choice]:" -ForegroundColor Cyan + $plan.Actions | Format-Table -Property Order, Component, Action, Current, Target, Reason -AutoSize + + if ($DryRun) { + Write-Host "" + Write-Host "============================================================" -ForegroundColor Cyan + Write-Host " [DRY-RUN] Verification status: $($verdict.Status)" -ForegroundColor Green + Write-Host " No changes were made to the system." -ForegroundColor Cyan + Write-Host "============================================================" -ForegroundColor Cyan + Write-InstallerLog -Message "Dry-run execution completed successfully." -Level INFO + exit 0 + } + + # ---------------------------------------------------- + # Phase 4: Install (Mutation) + # ---------------------------------------------------- + Write-InstallerLog -Message "Phase 4: Executing installation plan..." -Level STEP + $installResult = Invoke-InstallPlan -Plan $plan -Facts $facts -Config $config + + if (-not $installResult.Success) { + Write-Host "" + Write-Host "============================================================" -ForegroundColor Red + Write-Host " [ERROR] Installation failed during execution:" -ForegroundColor Red + Write-Host " $($installResult.ErrorMessage)" -ForegroundColor Red + if ($installResult.SnapshotPath) { + Write-Host " Environment rollback snapshot: $($installResult.SnapshotPath)" -ForegroundColor Yellow + } + Write-Host "============================================================" -ForegroundColor Red + Write-InstallerLog -Message "Installation failed: $($installResult.ErrorMessage)" -Level ERROR + exit 3 + } + + # ---------------------------------------------------- + # Phase 5: Validate (+ Fallback Ladder + Record) + # ---------------------------------------------------- + Write-InstallerLog -Message "Phase 5: Validating installed runtime..." -Level STEP + $validationReport = Test-InstalledStack -Plan $plan -Facts $facts -Config $config + + if (-not $validationReport.Passed) { + Write-Host "" + Write-Host "============================================================" -ForegroundColor Red + Write-Host " [ERROR] Runtime validation failed after installation." -ForegroundColor Red + Write-Host "============================================================" -ForegroundColor Red + foreach ($chk in ($validationReport.Checks | Where-Object { $_.Result -eq 'Fail' })) { + Write-Host " - $($chk.Message)" -ForegroundColor Red + } + Write-InstallerLog -Message "Runtime validation failed." -Level ERROR + exit 4 + } + + # Atomic Record + Write-InstallRecord -Facts $facts -Choice $choice -Plan $plan -Result $installResult -Report $validationReport -Config $config + + # Final Summary + Write-Host "" + Write-Host "============================================================" -ForegroundColor Green + Write-Host " Installation complete successfully!" -ForegroundColor Green + Write-Host "============================================================" -ForegroundColor Green + Write-Host " Effective Mode : $($validationReport.EffectiveOption)" -ForegroundColor Cyan + Write-Host " Log File : $($script:InstallerLogger.LogPath)" + Write-Host "" + Write-Host " Run UVR using : .\run_uvr.bat" -ForegroundColor Cyan + Write-Host "" + + if (-not $Yes) { + $runNow = Prompt-UserChoice -PromptText "Run UVR application now? [Y/N, default N]: " -ValidOptions @('Y', 'N') -DefaultOption 'N' + if ($runNow -eq 'Y') { + $runBat = Join-Path -Path $rootDir -ChildPath 'run_uvr.bat' + if (Test-Path -LiteralPath $runBat) { + Start-Process -FilePath 'cmd.exe' -ArgumentList @('/c', "`"$runBat`"") + } + } + } + + Write-InstallerLog -Message "Installer finished successfully with exit code 0." -Level INFO + exit 0 + +} catch { + Write-Host "" + Write-Host "[FATAL ERROR] An unexpected exception occurred: $($_.Exception.Message)" -ForegroundColor Red + Write-InstallerLog -Message "Fatal unexpected exception: $($_.Exception.ToString())" -Level ERROR + exit 1 +} diff --git a/install/install_packages.bat b/install/install_packages.bat index d99681a..bb8d735 100644 --- a/install/install_packages.bat +++ b/install/install_packages.bat @@ -1,849 +1,5 @@ @echo off -setlocal EnableExtensions EnableDelayedExpansion - +setlocal cd /d "%~dp0" - -set "INSTALLER_FILE=%~f0" -powershell -NoProfile -Command "$previous = -1; foreach ($byte in [IO.File]::ReadAllBytes($env:INSTALLER_FILE)) { if ($byte -eq 10 -and $previous -ne 13) { exit 1 }; $previous = $byte }; exit 0" >nul 2>&1 -if errorlevel 1 ( - echo. - echo [ERROR] install_packages.bat has invalid Unix LF line endings. - echo Convert this file to Windows CRLF or restore it from Git before running it. - pause - exit /b 1 -) -set "INSTALLER_FILE=" - -set "APP_NAME=RLD UVR-Opt" -set "PYTHON_VERSION=3.11.9" -set "VENV_DIR=..\venv" -set "VENV_PYTHON=%VENV_DIR%\Scripts\python.exe" -set "REQ_FILE=requirements.txt" -set "LOG_DIR=..\install_logs" -set "LOG_FILE=%LOG_DIR%\install_%DATE:/=-%_%TIME::=-%.log" -set "LOG_FILE=%LOG_FILE: =0%" -set "CPU_REQ_FILE=%LOG_DIR%\requirements_cpu.generated.txt" -set "UV_LINK_MODE=copy" -set "ROOT_DIR=.." -set "FFMPEG_URL=https://www.gyan.dev/ffmpeg/builds/ffmpeg-release-essentials.zip" -set "RUBBERBAND_URL=https://breakfastquay.com/files/releases/rubberband-3.1.2-gpl-executable-windows.zip" - -set "TORCH_VERSION=2.11.0" -set "TORCHVISION_VERSION=0.26.0" -set "TORCHAUDIO_VERSION=2.11.0" -set "TORCH_PACKAGES=torch==%TORCH_VERSION% torchvision==%TORCHVISION_VERSION% torchaudio==%TORCHAUDIO_VERSION%" -set "TORCH_CU128=https://download.pytorch.org/whl/cu128" -set "TORCH_CPU=https://download.pytorch.org/whl/cpu" -set "MIN_DRIVER_MAJOR=570" - -if not exist "%LOG_DIR%" mkdir "%LOG_DIR%" >nul 2>&1 - -call :banner -call :log "Starting installer in %CD%" - -if not exist "%REQ_FILE%" ( - call :fail "requirements.txt was not found in this folder." - exit /b 1 -) - -call :check_windows -call :detect_gpu -call :check_previous_install -call :choose_mode -call :ensure_uv -if errorlevel 1 exit /b 1 -call :create_venv -if errorlevel 1 exit /b 1 -call :verify_venv -if errorlevel 1 exit /b 1 - -if /i "%INSTALL_MODE%"=="CPU" ( - call :install_cpu_stack -) else if /i "%INSTALL_MODE%"=="TENSORRT_RTX" ( - call :install_trt_rtx_stack -) else ( - call :install_nvidia_stack -) -if errorlevel 1 exit /b 1 - -call :install_base_deps -if errorlevel 1 exit /b 1 - -call :ensure_vcredist - -call :ensure_external_tools -if errorlevel 1 exit /b 1 - -call :smoke_test -if errorlevel 1 exit /b 1 -call :record_install -call :done -exit /b 0 - -:banner -echo. -echo ============================================================ -echo %APP_NAME% - Modern Installer -echo ============================================================ -echo Target : NVIDIA RTX 20-series or newer, with CPU fallback -echo Python : %PYTHON_VERSION% -echo PyTorch: %TORCH_VERSION% -echo CUDA : cu128 primary -echo ============================================================ -echo. -exit /b 0 - -:check_windows -if /i not "%OS%"=="Windows_NT" ( - call :warn "This installer is designed for Windows. Not compatible with Linux and Mac OS for now." -) -exit /b 0 - -:verify_venv -if not exist "%VENV_PYTHON%" ( - call :fail "The virtual environment Python executable was not found: %VENV_PYTHON%" - exit /b 1 -) - -if defined CONDA_PREFIX ( - echo Active Conda environment detected: %CONDA_PREFIX% - call :warn "Conda is active, but it will be bypassed. Every command is pinned to %VENV_PYTHON%." -) - -set "VENV_CHECK_LOG=%TEMP%\uvr_venv_check_%RANDOM%%RANDOM%.log" -"%VENV_PYTHON%" -c "import sys; print(sys.executable); raise SystemExit(sys.prefix == sys.base_prefix)" >"!VENV_CHECK_LOG!" 2>&1 -if errorlevel 1 ( - call :warn "Virtual environment diagnostic output:" - if exist "!VENV_CHECK_LOG!" type "!VENV_CHECK_LOG!" - if exist "!VENV_CHECK_LOG!" del "!VENV_CHECK_LOG!" >nul 2>&1 - call :fail "The existing virtual environment is invalid or could not be started. Choose N when asked to reuse it so the installer can rebuild it." - exit /b 1 -) - -set /p "RESOLVED_VENV_PYTHON=" <"!VENV_CHECK_LOG!" -del "!VENV_CHECK_LOG!" >nul 2>&1 -echo Using isolated Python : !RESOLVED_VENV_PYTHON! -call :log "Using isolated Python: !RESOLVED_VENV_PYTHON!" -exit /b 0 - -:detect_gpu -set "HAS_NVIDIA=0" -set "HAS_AMD=0" -set "GPU_NAME=Not detected" -set "AMD_GPU_NAME=Not detected" -set "GPU_DRIVER=Unknown" -set "RTX_SUPPORTED=0" -set "DRIVER_SUPPORTED=0" - -for /f "usebackq delims=" %%A in (`powershell -NoProfile -Command "$gpu = Get-CimInstance Win32_VideoController | Where-Object { $_.Name -match 'AMD|Radeon' } | Select-Object -First 1 -ExpandProperty Name; if ($gpu) { $gpu }" 2^>nul`) do ( - set "HAS_AMD=1" - set "AMD_GPU_NAME=%%A" -) - -where nvidia-smi >nul 2>&1 -if errorlevel 1 ( - call :warn "nvidia-smi was not found. The NVIDIA driver may be missing, or PATH may not be configured correctly." - if "!HAS_AMD!"=="1" ( - echo Detected AMD GPU : !AMD_GPU_NAME! - call :warn "AMD GPUs are not supported by this UVR installer yet. CPU fallback will be used." - call :log "Detected AMD GPU: !AMD_GPU_NAME!. AMD is unsupported; using CPU fallback." - ) - exit /b 0 -) - -for /f "tokens=1,* delims=," %%A in ('nvidia-smi --query-gpu=name^,driver_version --format=csv^,noheader 2^>nul') do ( - set "HAS_NVIDIA=1" - set "GPU_NAME=%%A" - set "GPU_DRIVER=%%B" - goto :gpu_detected -) - -:gpu_detected -if "%HAS_NVIDIA%"=="0" ( - call :warn "No NVIDIA GPU was detected." - if "!HAS_AMD!"=="1" ( - echo Detected AMD GPU : !AMD_GPU_NAME! - call :warn "AMD GPUs are not supported by this UVR installer yet. CPU fallback will be used." - call :log "Detected AMD GPU: !AMD_GPU_NAME!. AMD is unsupported; using CPU fallback." - ) - exit /b 0 -) - -for /f "tokens=* delims= " %%A in ("!GPU_NAME!") do set "GPU_NAME=%%A" -for /f "tokens=* delims= " %%A in ("!GPU_DRIVER!") do set "GPU_DRIVER=%%A" - -echo Detected NVIDIA GPU : !GPU_NAME! -echo NVIDIA Driver : !GPU_DRIVER! -call :log "Detected NVIDIA GPU: !GPU_NAME!, driver: !GPU_DRIVER!" - -echo !GPU_NAME! | findstr /i /r "RTX.*20 RTX.*30 RTX.*40 RTX.*50 RTX A RTX Ada RTX PRO" >nul && set "RTX_SUPPORTED=1" - -for /f "tokens=1 delims=." %%A in ("!GPU_DRIVER!") do set "DRIVER_MAJOR=%%A" -set "DRIVER_CHECK=0" -set /a DRIVER_CHECK=1!DRIVER_MAJOR!-1000 >nul 2>&1 -if !DRIVER_CHECK! GEQ %MIN_DRIVER_MAJOR% set "DRIVER_SUPPORTED=1" - -if "!RTX_SUPPORTED!"=="0" ( - call :warn "This GPU does not match the official RTX 20-series-or-newer target. GPU installation can still be attempted, but it is not recommended." -) - -if "!DRIVER_SUPPORTED!"=="0" ( - call :warn "The NVIDIA driver appears older than the CUDA 12.8 recommendation. Updating the driver is recommended before using NVIDIA mode." -) -exit /b 0 - -:check_previous_install -set "PREV_RECORD_EXISTS=0" -set "PREV_MODE=" -set "PREV_OPTION=" -set "VENV_TORCH_TYPE=NONE" -set "VENV_TORCH_VER=NONE" -set "VENV_TORCH_CUDA=NONE" -set "VENV_ORT_TYPE=NONE" -set "VENV_ORT_VER=NONE" - -if exist "%VENV_PYTHON%" ( - for /f "tokens=1,2 delims==" %%A in ('"%VENV_PYTHON%" "%~dp0install_record.py" inspect-stack 2^>nul') do ( - if "%%A"=="TORCH_TYPE" set "VENV_TORCH_TYPE=%%B" - if "%%A"=="TORCH_VER" set "VENV_TORCH_VER=%%B" - if "%%A"=="TORCH_CUDA" set "VENV_TORCH_CUDA=%%B" - if "%%A"=="ORT_TYPE" set "VENV_ORT_TYPE=%%B" - if "%%A"=="ORT_VER" set "VENV_ORT_VER=%%B" - ) -) - -if exist "%~dp0install_record.json" if exist "%VENV_PYTHON%" ( - for /f "tokens=1,2 delims==" %%A in ('"%VENV_PYTHON%" "%~dp0install_record.py" read 2^>nul') do ( - if "%%A"=="MODE" set "PREV_MODE=%%B" - if "%%A"=="OPTION" set "PREV_OPTION=%%B" - set "PREV_RECORD_EXISTS=1" - ) -) -if "!PREV_RECORD_EXISTS!"=="1" ( - echo Previous installation detected : [!PREV_OPTION!] !PREV_MODE! - call :log "Previous install detected: Option !PREV_OPTION!, Mode !PREV_MODE!" -) -if not "!VENV_TORCH_TYPE!"=="NONE" ( - echo Current environment stack : Torch=!VENV_TORCH_TYPE! [!VENV_TORCH_VER!], ORT=!VENV_ORT_TYPE! [!VENV_ORT_VER!] - call :log "Current venv stack: Torch !VENV_TORCH_TYPE! [!VENV_TORCH_VER!], ORT !VENV_ORT_TYPE! [!VENV_ORT_VER!]" -) -exit /b 0 - -:choose_mode -set "INSTALL_MODE=NVIDIA" -set "USER_FORCED_NVIDIA=0" -echo. -echo Choose installation mode: -echo [A] CUDA EP - Choose this for the stable and safe option (RTX 20+ / Turing or newer) -echo [B] TensorRT-RTX EP - Choose this if you like experimental, fast, and optimized (Requires RTX 30+ / Ampere; CUDA EP will still exist as a stable fallback) -echo [C] CPU - safest fallback, including AMD systems because AMD is not supported yet -if "%HAS_NVIDIA%"=="0" if "%HAS_AMD%"=="1" echo Note: AMD GPU detected, but AMD acceleration is not supported yet. Auto will use CPU. -echo. -call :prompt_choice MODE_CHOICE "Mode [A/B/C, default A]: " "A B C" "A" "A, B, or C" -if /i "!MODE_CHOICE!"=="A" ( - set "INSTALL_MODE=NVIDIA" - set "USER_FORCED_NVIDIA=1" -) -if /i "!MODE_CHOICE!"=="B" ( - set "INSTALL_MODE=TENSORRT_RTX" - set "USER_FORCED_NVIDIA=1" - echo !GPU_NAME! | findstr /i /r "RTX.*20" >nul - if not errorlevel 1 ( - call :warn "Turing architecture (RTX 20-series) does not support TensorRT-RTX EP. UVR will automatically fall back to CUDA EP at runtime." - ) -) -if /i "!MODE_CHOICE!"=="C" set "INSTALL_MODE=CPU" - -if not "!INSTALL_MODE!"=="CPU" if "%USER_FORCED_NVIDIA%"=="1" ( - if "%HAS_NVIDIA%"=="0" call :confirm_risky "NVIDIA was not detected. Force GPU stack installation anyway?" - if /i "!INSTALL_MODE!"=="CPU" goto :choose_mode_done - if "%RTX_SUPPORTED%"=="0" call :confirm_risky "The GPU is outside the RTX 20+ target. Force GPU stack installation anyway?" - if /i "!INSTALL_MODE!"=="CPU" goto :choose_mode_done - if "%DRIVER_SUPPORTED%"=="0" call :confirm_risky "The driver is older than the CUDA 12.8 recommendation. Force GPU stack installation anyway?" -) - -:choose_mode_done -echo Selected mode: !INSTALL_MODE! -call :log "Selected install mode: !INSTALL_MODE!" -exit /b 0 - -:ensure_uv -where uv >nul 2>&1 -if not errorlevel 1 ( - echo uv already installed. - uv --version - exit /b 0 -) - -echo Installing uv... -call :log "Installing uv" -powershell -NoProfile -ExecutionPolicy Bypass -Command "irm https://astral.sh/uv/install.ps1 | iex" -if errorlevel 1 ( - call :fail "Failed to install uv. Check your internet connection or PowerShell policy." - exit /b 1 -) - -where uv >nul 2>&1 -if errorlevel 1 ( - set "PATH=%USERPROFILE%\.local\bin;%USERPROFILE%\.cargo\bin;%PATH%" -) - -where uv >nul 2>&1 -if errorlevel 1 ( - call :fail "uv was installed, but it was not found in PATH. Close this terminal and try again." - exit /b 1 -) -uv --version -exit /b 0 - -:create_venv -set "VENV_CLEAR=" -set "NEED_TORCH_REPLACE=0" -set "NEED_ORT_REPLACE=0" - -if exist "%VENV_DIR%\Scripts\python.exe" ( - echo Existing virtual environment found: %VENV_DIR% - call :prompt_choice REUSE_VENV "Reuse existing venv? [Y/N, default Y]: " "Y N" "Y" "Y or N" - if /i "!REUSE_VENV!"=="Y" ( - call :check_stack_transition - exit /b 0 - ) - set "VENV_CLEAR=--clear" - set "VENV_TORCH_TYPE=NONE" - set "VENV_ORT_TYPE=NONE" -) - -echo Creating virtual environment with Python %PYTHON_VERSION%... -call :log "Creating venv with Python %PYTHON_VERSION%" -uv venv %VENV_CLEAR% "%VENV_DIR%" --python %PYTHON_VERSION% -if errorlevel 1 ( - call :warn "Python %PYTHON_VERSION% was not available automatically. Trying any available Python 3.11 installation." - uv venv %VENV_CLEAR% "%VENV_DIR%" --python 3.11 - if errorlevel 1 ( - call :fail "Failed to create the venv. Install Python 3.11 first or check uv connectivity." - exit /b 1 - ) -) -exit /b 0 - -:check_stack_transition -set "NEED_TORCH_REPLACE=0" -set "NEED_ORT_REPLACE=0" - -rem -- Case 1: Upgrading from CPU to GPU (Option A or Option B) -if not "%INSTALL_MODE%"=="CPU" if "!VENV_TORCH_TYPE!"=="CPU" ( - echo. - echo ============================================================ - echo [UPGRADE] Migrating environment from CPU to %INSTALL_MODE% - echo ============================================================ - echo Existing CPU PyTorch and ONNX Runtime will be replaced with - echo CUDA-accelerated packages seamlessly. - echo ============================================================ - set "NEED_TORCH_REPLACE=1" - set "NEED_ORT_REPLACE=1" - call :log "Stack transition: Upgrading from CPU to %INSTALL_MODE%" - exit /b 0 -) - -rem -- Case 2: Switching from GPU to CPU fallback (Option C) -if "%INSTALL_MODE%"=="CPU" if "!VENV_TORCH_TYPE!"=="CUDA" ( - echo. - echo ============================================================ - echo [SWITCH] Switching environment from GPU to CPU fallback - echo ============================================================ - echo CUDA packages will be replaced with CPU builds seamlessly. - echo ============================================================ - set "NEED_TORCH_REPLACE=1" - set "NEED_ORT_REPLACE=1" - call :log "Stack transition: Switching from GPU to CPU fallback" - exit /b 0 -) - -rem -- Case 3: Switching between GPU options (A <-> B) -if "%INSTALL_MODE%"=="TENSORRT_RTX" ( - if not "!VENV_ORT_TYPE!"=="GPU_TRT" set "NEED_ORT_REPLACE=1" - if not "!VENV_ORT_VER!"=="1.24.4" set "NEED_ORT_REPLACE=1" - if "!NEED_ORT_REPLACE!"=="1" ( - echo. - echo [UPGRADE] Transitioning ONNX Runtime stack to TensorRT-RTX [ORT 1.24.4 + TRT-RTX plugin]... - call :log "Stack transition: Switching ORT stack to TensorRT-RTX" - ) -) -if "%INSTALL_MODE%"=="NVIDIA" ( - if "!VENV_ORT_TYPE!"=="GPU_TRT" set "NEED_ORT_REPLACE=1" - if not "!VENV_ORT_VER!"=="1.22.0" set "NEED_ORT_REPLACE=1" - if "!NEED_ORT_REPLACE!"=="1" ( - echo. - echo [SWITCH] Transitioning ONNX Runtime stack to standard CUDA EP [ORT 1.22.0]... - call :log "Stack transition: Switching ORT stack to standard CUDA EP" - ) -) - -rem -- Case 4: PyTorch CUDA integrity check (ensure cu128 and not partial/mismatched) -if not "%INSTALL_MODE%"=="CPU" ( - if not "!VENV_TORCH_CUDA!"=="12.8" ( - if not "!VENV_TORCH_TYPE!"=="NONE" ( - set "NEED_TORCH_REPLACE=1" - echo [UPGRADE] PyTorch CUDA version mismatch: !VENV_TORCH_CUDA! vs 12.8. Replacing with cu128... - call :log "Stack transition: Replacing PyTorch with cu128 due to version mismatch" - ) - ) -) -exit /b 0 - -:install_base_deps -echo. -echo Preparing base dependencies... -set "INSTALL_REQ=%REQ_FILE%" -if /i "%INSTALL_MODE%"=="CPU" ( - call :make_cpu_requirements - if errorlevel 1 exit /b 1 - set "INSTALL_REQ=%CPU_REQ_FILE%" -) -if /i "%INSTALL_MODE%"=="TENSORRT_RTX" ( - set "INSTALL_REQ=requirements_trt_rtx.txt" -) - -if exist "%~dp0wheels\diffq-0.2.4-cp311-cp311-win_amd64.whl" ( - call :log "Pre-installing local binary wheel for diffq" - uv pip install --python "%VENV_PYTHON%" --no-deps "%~dp0wheels\diffq-0.2.4-cp311-cp311-win_amd64.whl" >nul 2>&1 -) - -echo Installing base dependencies... -call :log "Installing requirements from !INSTALL_REQ!" -uv pip install --python "%VENV_PYTHON%" --find-links "%~dp0wheels" -r "!INSTALL_REQ!" -set "BASE_INSTALL_EXIT=!ERRORLEVEL!" -if /i "%INSTALL_MODE%"=="CPU" if exist "%CPU_REQ_FILE%" del "%CPU_REQ_FILE%" >nul 2>&1 -if not "!BASE_INSTALL_EXIT!"=="0" ( - call :fail "Failed to install base dependencies. See %LOG_FILE% for details." - exit /b 1 -) -exit /b 0 - -:make_cpu_requirements -if exist "%CPU_REQ_FILE%" del "%CPU_REQ_FILE%" >nul 2>&1 -type nul >"%CPU_REQ_FILE%" -if errorlevel 1 ( - call :fail "Failed to create the CPU requirements file in %LOG_DIR%." - exit /b 1 -) - -for /f "usebackq delims=" %%L in ("%REQ_FILE%") do ( - set "LINE=%%L" - set "SKIP=0" - echo !LINE! | findstr /i /b "torch== torchvision== torchaudio==" >nul && set "SKIP=1" - echo !LINE! | findstr /i /b "cupy-cuda cuda-pathfinder onnxruntime-gpu nvidia-" >nul && set "SKIP=1" - echo !LINE! | findstr /i /b "polygraphy nvidia-modelopt onnx-graphsurgeon" >nul && set "SKIP=1" - if "!SKIP!"=="0" echo !LINE!>>"%CPU_REQ_FILE%" -) - -for %%A in ("%CPU_REQ_FILE%") do if %%~zA EQU 0 ( - call :fail "The generated CPU requirements file is empty." - exit /b 1 -) -exit /b 0 - -:install_nvidia_stack -echo. -echo Installing NVIDIA CUDA PyTorch stack (Option A - CUDA EP)... -call :log "Installing PyTorch CUDA from %TORCH_CU128%" - -if "!NEED_TORCH_REPLACE!"=="1" ( - echo [UPGRADE] Replacing existing PyTorch with CUDA 12.8 packages... - call :log "Replacing existing PyTorch packages with CUDA 12.8" - uv pip uninstall --python "%VENV_PYTHON%" torch torchvision torchaudio >nul 2>&1 - uv pip install --python "%VENV_PYTHON%" --reinstall-package torch --reinstall-package torchvision --reinstall-package torchaudio %TORCH_PACKAGES% --index-url "%TORCH_CU128%" -) else ( - uv pip install --python "%VENV_PYTHON%" %TORCH_PACKAGES% --index-url "%TORCH_CU128%" -) -if errorlevel 1 ( - call :warn "PyTorch CUDA installation failed. Offering CPU fallback." - call :prompt_choice CPU_FALLBACK "Install CPU stack instead? [Y/N, default Y]: " "Y N" "Y" "Y or N" - if /i "!CPU_FALLBACK!"=="N" ( - call :fail "PyTorch CUDA installation failed and CPU fallback was cancelled." - exit /b 1 - ) - set "INSTALL_MODE=CPU" - call :install_cpu_stack - exit /b 0 -) - -echo Installing ONNX Runtime GPU compatibility package (1.22.0)... -uv pip uninstall --python "%VENV_PYTHON%" onnxruntime onnxruntime-ep-nv-tensorrt-rtx-cu12 >nul 2>&1 -uv pip install --python "%VENV_PYTHON%" --reinstall-package onnxruntime-gpu onnxruntime-gpu==1.22.0 -if errorlevel 1 call :warn "Failed to install onnxruntime-gpu. UVR can still use PyTorch CUDA, but ONNX models may fall back or fail." -exit /b 0 - -:install_trt_rtx_stack -echo. -echo Installing NVIDIA CUDA PyTorch stack (Option B - TensorRT-RTX EP)... -call :log "Installing PyTorch CUDA from %TORCH_CU128%" - -if "!NEED_TORCH_REPLACE!"=="1" ( - echo [UPGRADE] Replacing existing PyTorch with CUDA 12.8 packages... - call :log "Replacing existing PyTorch packages with CUDA 12.8" - uv pip uninstall --python "%VENV_PYTHON%" torch torchvision torchaudio >nul 2>&1 - uv pip install --python "%VENV_PYTHON%" --reinstall-package torch --reinstall-package torchvision --reinstall-package torchaudio %TORCH_PACKAGES% --index-url "%TORCH_CU128%" -) else ( - uv pip install --python "%VENV_PYTHON%" %TORCH_PACKAGES% --index-url "%TORCH_CU128%" -) -if errorlevel 1 ( - call :warn "PyTorch CUDA installation failed. Offering CPU fallback." - call :prompt_choice CPU_FALLBACK "Install CPU stack instead? [Y/N, default Y]: " "Y N" "Y" "Y or N" - if /i "!CPU_FALLBACK!"=="N" ( - call :fail "PyTorch CUDA installation failed and CPU fallback was cancelled." - exit /b 1 - ) - set "INSTALL_MODE=CPU" - call :install_cpu_stack - exit /b 0 -) - -echo Preparing TensorRT-RTX packages (ONNX Runtime GPU 1.24.4 + TRT-RTX EP)... -uv pip uninstall --python "%VENV_PYTHON%" onnxruntime >nul 2>&1 -uv pip install --python "%VENV_PYTHON%" --reinstall-package onnxruntime-gpu onnxruntime-gpu==1.24.4 onnxruntime-ep-nv-tensorrt-rtx-cu12==0.4.0 -if errorlevel 1 call :warn "Failed to install TensorRT-RTX packages. Standard CUDA EP will still be used as fallback." -exit /b 0 - -:install_cpu_stack -echo. -echo Installing CPU fallback stack (Option C - CPU)... -call :log "Installing PyTorch CPU from %TORCH_CPU%" - -if "!NEED_TORCH_REPLACE!"=="1" ( - echo [SWITCH] Replacing existing PyTorch with CPU packages... - call :log "Replacing existing PyTorch packages with CPU packages" - uv pip uninstall --python "%VENV_PYTHON%" torch torchvision torchaudio >nul 2>&1 - uv pip install --python "%VENV_PYTHON%" --reinstall-package torch --reinstall-package torchvision --reinstall-package torchaudio %TORCH_PACKAGES% --index-url "%TORCH_CPU%" -) else ( - uv pip install --python "%VENV_PYTHON%" %TORCH_PACKAGES% --index-url "%TORCH_CPU%" -) -if errorlevel 1 ( - call :fail "Failed to install PyTorch CPU." - exit /b 1 -) - -echo Installing ONNX Runtime CPU package (1.22.0)... -uv pip uninstall --python "%VENV_PYTHON%" onnxruntime-gpu onnxruntime-ep-nv-tensorrt-rtx-cu12 cupy-cuda12x cuda-pathfinder polygraphy onnx-graphsurgeon >nul 2>&1 -uv pip install --python "%VENV_PYTHON%" --reinstall-package onnxruntime onnxruntime==1.22.0 -if errorlevel 1 call :warn "Failed to install ONNX Runtime CPU. PyTorch models can still run, but ONNX models may fail." -exit /b 0 - -:ensure_vcredist -echo. -echo ============================================================ -echo Checking Visual C++ Redistributable 2015-2022 (x64) -echo ============================================================ -call :log "Checking Visual C++ Redistributable" - -set "VCREDIST_OK=0" - -rem -- Primary check: Visual Studio 2015-2022 x64 runtime registry key (Version must be >= 14.40) -for /f "tokens=1,2,*" %%A in ('reg query "HKLM\SOFTWARE\Microsoft\VisualStudio\14.0\VC\Runtimes\X64" /v Version 2^>nul ^| findstr /i "Version"') do ( - set "VCREDIST_VER=%%C" -) -if defined VCREDIST_VER ( - set "VCREDIST_VER=!VCREDIST_VER:v=!" - for /f "tokens=1,2 delims=." %%M in ("!VCREDIST_VER!") do ( - set "VCREDIST_MAJOR=%%M" - set "VCREDIST_MINOR=%%N" - ) - if defined VCREDIST_MAJOR if defined VCREDIST_MINOR ( - if !VCREDIST_MAJOR! GTR 14 set "VCREDIST_OK=1" - if "!VCREDIST_MAJOR!"=="14" ( - if !VCREDIST_MINOR! GEQ 40 set "VCREDIST_OK=1" - ) - ) -) - -rem -- Secondary check: Installed and Minor DWORD keys if Version string was inconclusive -if "!VCREDIST_OK!"=="0" ( - for /f "tokens=1,2,*" %%A in ('reg query "HKLM\SOFTWARE\Microsoft\VisualStudio\14.0\VC\Runtimes\X64" /v Installed 2^>nul ^| findstr /i "Installed"') do ( - if "%%C"=="0x1" ( - for /f "tokens=1,2,*" %%X in ('reg query "HKLM\SOFTWARE\Microsoft\VisualStudio\14.0\VC\Runtimes\X64" /v Minor 2^>nul ^| findstr /i "Minor"') do ( - set /a "VCREDIST_MINOR_DEC=%%Z" 2^>nul - if !VCREDIST_MINOR_DEC! GEQ 40 set "VCREDIST_OK=1" - ) - ) - ) -) - -rem -- Fallback: check Uninstall registry for 64-bit VC++ 2015-2022 / 2022 runtimes -if "!VCREDIST_OK!"=="0" ( - for /f "tokens=*" %%K in ('reg query "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" /s /f "Visual C++" /d /reg:64 2^>nul ^| findstr /i "X64" ^| findstr /i /c:"2015" /c:"2017" /c:"2019" /c:"2022"') do ( - set "VCREDIST_OK=1" - ) -) - -if "!VCREDIST_OK!"=="1" ( - echo [OK] Visual C++ Redistributable 2015-2022 x64 is already installed. - call :log "VC++ Redistributable already present." - exit /b 0 -) - -echo Visual C++ Redistributable 2015-2022 x64 was not found. -echo Downloading and installing the latest VC++ Redistributable... -call :log "VC++ Redistributable missing. Downloading from Microsoft..." - -set "VCREDIST_URL=https://aka.ms/vs/17/release/vc_redist.x64.exe" -set "VCREDIST_EXE=%TEMP%\vc_redist_%RANDOM%.exe" - -powershell -NoProfile -ExecutionPolicy Bypass -Command "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; if (Get-Command curl.exe -ErrorAction SilentlyContinue) { curl.exe -f -L --progress-bar -o '%VCREDIST_EXE%' '%VCREDIST_URL%' } else { (New-Object System.Net.WebClient).DownloadFile('%VCREDIST_URL%', '%VCREDIST_EXE%') }" -if errorlevel 1 ( - if exist "%VCREDIST_EXE%" del "%VCREDIST_EXE%" >nul 2>&1 - call :warn "Failed to download VC++ Redistributable. Some C-extension modules may not load." - exit /b 0 -) - -echo Installing VC++ Redistributable silently (this may take a moment)... -"%VCREDIST_EXE%" /install /quiet /norestart -set "VCREDIST_INSTALL_EXIT=!ERRORLEVEL!" -if exist "%VCREDIST_EXE%" del "%VCREDIST_EXE%" >nul 2>&1 - -if "!VCREDIST_INSTALL_EXIT!"=="0" ( - echo [OK] Visual C++ Redistributable installed successfully. - call :log "VC++ Redistributable installed successfully." -) else if "!VCREDIST_INSTALL_EXIT!"=="3010" ( - echo [OK] Visual C++ Redistributable installed. A system reboot is recommended but not required. - call :log "VC++ Redistributable installed (exit 3010 = reboot recommended)." -) else ( - call :warn "VC++ Redistributable installer exited with code !VCREDIST_INSTALL_EXIT!. Continuing anyway." -) -exit /b 0 - -:ensure_external_tools -echo. -echo ============================================================ -echo Checking External Media Binaries (FFmpeg ^& Rubber Band) -echo ============================================================ -call :log "Checking external media binaries" - -call :ensure_ffmpeg -call :ensure_rubberband -echo. -exit /b 0 - -:ensure_ffmpeg -set "HAS_FFMPEG=0" -set "DETECTED_FFMPEG=" - -if exist "%ROOT_DIR%\ffmpeg.exe" ( - set "HAS_FFMPEG=1" - set "DETECTED_FFMPEG=%ROOT_DIR%\ffmpeg.exe" - echo [OK] FFmpeg found in root directory: !DETECTED_FFMPEG! - call :log "FFmpeg found in root: !DETECTED_FFMPEG!" - exit /b 0 -) - -where ffmpeg >nul 2>&1 -if not errorlevel 1 ( - for /f "delims=" %%A in ('where ffmpeg 2^>nul') do ( - set "HAS_FFMPEG=1" - set "DETECTED_FFMPEG=%%A" - goto :ffmpeg_path_found - ) -) - -:ffmpeg_path_found -if "!HAS_FFMPEG!"=="1" ( - echo [OK] FFmpeg detected in system PATH: !DETECTED_FFMPEG! - call :log "FFmpeg detected in system PATH: !DETECTED_FFMPEG!" - exit /b 0 -) - -echo FFmpeg was not detected in system PATH or root folder. -echo Downloading portable FFmpeg to application root... -call :log "Downloading portable FFmpeg from %FFMPEG_URL%" -set "FFMPEG_ZIP=%TEMP%\uvr_ffmpeg_%RANDOM%.zip" -powershell -NoProfile -ExecutionPolicy Bypass -Command "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; if (Get-Command curl.exe -ErrorAction SilentlyContinue) { curl.exe -f -L --progress-bar -o '%FFMPEG_ZIP%' '%FFMPEG_URL%' } else { (New-Object System.Net.WebClient).DownloadFile('%FFMPEG_URL%', '%FFMPEG_ZIP%') }" -if errorlevel 1 ( - if exist "%FFMPEG_ZIP%" del "%FFMPEG_ZIP%" >nul 2>&1 - call :warn "Failed to download portable FFmpeg. Non-WAV audio conversion may be unavailable." - exit /b 0 -) - -echo Extracting ffmpeg.exe to %ROOT_DIR%... -powershell -NoProfile -ExecutionPolicy Bypass -Command "Add-Type -AssemblyName System.IO.Compression.FileSystem; $archive = [System.IO.Compression.ZipFile]::OpenRead('%FFMPEG_ZIP%'); foreach ($entry in $archive.Entries) { if ($entry.Name -eq 'ffmpeg.exe' -or $entry.Name -eq 'ffprobe.exe') { [System.IO.Compression.ZipFileExtensions]::ExtractToFile($entry, (Join-Path '%ROOT_DIR%' $entry.Name), $true) } }; $archive.Dispose()" -if exist "%FFMPEG_ZIP%" del "%FFMPEG_ZIP%" >nul 2>&1 - -if exist "%ROOT_DIR%\ffmpeg.exe" ( - echo [OK] FFmpeg portable installed successfully: %ROOT_DIR%\ffmpeg.exe - call :log "FFmpeg portable installed to %ROOT_DIR%\ffmpeg.exe" -) else ( - call :warn "FFmpeg archive downloaded, but ffmpeg.exe could not be extracted." -) -exit /b 0 - -:ensure_rubberband -set "HAS_RB=0" -set "DETECTED_RB=" - -if exist "%ROOT_DIR%\rubberband.exe" ( - set "HAS_RB=1" - set "DETECTED_RB=%ROOT_DIR%\rubberband.exe" - echo [OK] rubberband-cli found in root directory: !DETECTED_RB! - call :log "rubberband-cli found in root: !DETECTED_RB!" - exit /b 0 -) - -where rubberband >nul 2>&1 -if not errorlevel 1 ( - for /f "delims=" %%A in ('where rubberband 2^>nul') do ( - set "HAS_RB=1" - set "DETECTED_RB=%%A" - goto :rb_path_found - ) -) - -where rubberband-cli >nul 2>&1 -if not errorlevel 1 ( - for /f "delims=" %%A in ('where rubberband-cli 2^>nul') do ( - set "HAS_RB=1" - set "DETECTED_RB=%%A" - goto :rb_path_found - ) -) - -:rb_path_found -if "!HAS_RB!"=="1" ( - echo [OK] rubberband-cli detected in system PATH: !DETECTED_RB! - call :log "rubberband-cli detected in system PATH: !DETECTED_RB!" - exit /b 0 -) - -echo rubberband-cli was not detected in system PATH or root folder. -echo Downloading portable Rubber Band to application root... -call :log "Downloading portable Rubber Band from %RUBBERBAND_URL%" -set "RB_ZIP=%TEMP%\uvr_rubberband_%RANDOM%.zip" -powershell -NoProfile -ExecutionPolicy Bypass -Command "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; if (Get-Command curl.exe -ErrorAction SilentlyContinue) { curl.exe -f -L --progress-bar -o '%RB_ZIP%' '%RUBBERBAND_URL%' } else { (New-Object System.Net.WebClient).DownloadFile('%RUBBERBAND_URL%', '%RB_ZIP%') }" -if errorlevel 1 ( - if exist "%RB_ZIP%" del "%RB_ZIP%" >nul 2>&1 - call :warn "Failed to download portable Rubber Band. Time-stretch and pitch-shift tools will be unavailable." - exit /b 0 -) - -echo Extracting rubberband.exe and sndfile.dll to %ROOT_DIR%... -powershell -NoProfile -ExecutionPolicy Bypass -Command "Add-Type -AssemblyName System.IO.Compression.FileSystem; $archive = [System.IO.Compression.ZipFile]::OpenRead('%RB_ZIP%'); foreach ($entry in $archive.Entries) { if ($entry.Name -eq 'rubberband.exe' -or $entry.Name -eq 'sndfile.dll') { [System.IO.Compression.ZipFileExtensions]::ExtractToFile($entry, (Join-Path '%ROOT_DIR%' $entry.Name), $true) } }; $archive.Dispose()" -if exist "%RB_ZIP%" del "%RB_ZIP%" >nul 2>&1 - -if exist "%ROOT_DIR%\rubberband.exe" ( - echo [OK] rubberband-cli portable installed successfully: %ROOT_DIR%\rubberband.exe - call :log "rubberband-cli portable installed to %ROOT_DIR%\rubberband.exe" -) else ( - call :warn "Rubber Band archive downloaded, but rubberband.exe could not be extracted." -) -exit /b 0 - -:smoke_test -echo. -echo Running smoke test... -"%VENV_PYTHON%" -c "import sys, torch; print('Python executable:', sys.executable); print('Python:', sys.version.split()[0]); print('Torch:', torch.__version__); print('CUDA available:', torch.cuda.is_available()); print('CUDA build:', torch.version.cuda); print('GPU:', torch.cuda.get_device_name(0) if torch.cuda.is_available() else 'CPU mode')" -if errorlevel 1 ( - call :fail "PyTorch smoke test failed." - exit /b 1 -) - -"%VENV_PYTHON%" -c "import onnxruntime as ort; print('ONNX Runtime providers:', ort.get_available_providers())" -if errorlevel 1 call :warn "ONNX Runtime smoke test failed. UVR can still run non-ONNX models." - -if /i "%INSTALL_MODE%"=="TENSORRT_RTX" ( - "%VENV_PYTHON%" -c "import onnxruntime as ort; import onnxruntime_ep_nv_tensorrt_rtx as trt_ep; ort.register_execution_provider_library(trt_ep.get_ep_name(), trt_ep.get_library_path()); print('TensorRT-RTX plugin loaded successfully.')" 2>nul - if errorlevel 1 call :warn "TensorRT-RTX EP plugin could not be initialized. CUDA EP will still be used as stable fallback." -) - -if not "%INSTALL_MODE%"=="CPU" ( - "%VENV_PYTHON%" -c "import torch, sys; sys.exit(0 if torch.cuda.is_available() else 2)" - if errorlevel 1 ( - call :warn "GPU mode is installed, but torch.cuda.is_available() is still False." - call :warn "Likely causes: outdated driver, DLL conflict, or incompatible PyTorch wheel." - ) -) -exit /b 0 - -:record_install -echo. -echo Recording install state... -"%VENV_PYTHON%" "%~dp0install_record.py" write --option "!MODE_CHOICE!" --mode "!INSTALL_MODE!" --reuse-venv "!REUSE_VENV!" --has-uv "1" --has-ffmpeg "!HAS_FFMPEG!" --has-rubberband "!HAS_RB!" --has-vc-redist "!VC_INSTALLED!" >nul 2>&1 -if not errorlevel 1 ( - call :log "Successfully wrote install record to install_record.json" -) -exit /b 0 - - -:done -echo. -echo ============================================================ -echo Installation complete. -echo ============================================================ -echo Mode : %INSTALL_MODE% -echo Log : %LOG_FILE% -echo. -echo Run UVR with: run_uvr.bat -echo. -call :prompt_choice RUN_NOW "Run run_uvr.bat now? [Y/N, default N]: " "Y N" "N" "Y or N" -if /i "!RUN_NOW!"=="Y" call ../run_uvr.bat -pause -exit /b 0 - -:confirm_risky -echo. -call :warn "%~1" -call :prompt_choice RISK_OK "Continue anyway? [Y/N, default N]: " "Y N" "N" "Y or N" -if /i "!RISK_OK!"=="N" ( - echo Switching to CPU fallback. - set "INSTALL_MODE=CPU" -) -exit /b 0 - -:prompt_choice -setlocal EnableDelayedExpansion -set "PROMPT_OPTIONS=%~3" -set "PROMPT_DEFAULT=%~4" -set "PROMPT_HINT=%~5" - -:prompt_choice_retry -set "PROMPT_VALUE=" -set /p "PROMPT_VALUE=%~2" -if not defined PROMPT_VALUE ( - if defined PROMPT_DEFAULT ( - set "PROMPT_VALUE=!PROMPT_DEFAULT!" - ) else ( - call :warn "Input is required. Enter !PROMPT_HINT! exactly." - goto :prompt_choice_retry - ) -) - -set "PROMPT_MATCH=" -for %%O in (!PROMPT_OPTIONS!) do ( - if /i "!PROMPT_VALUE!"=="%%O" set "PROMPT_MATCH=%%O" -) - -if not defined PROMPT_MATCH ( - if defined PROMPT_DEFAULT ( - call :warn "Invalid input. Enter !PROMPT_HINT! exactly, or press Enter for default [!PROMPT_DEFAULT!]." - ) else ( - call :warn "Invalid input. Enter !PROMPT_HINT! exactly." - ) - goto :prompt_choice_retry -) - -endlocal & set "%~1=%PROMPT_MATCH%" -exit /b 0 - -:warn -echo [WARNING] %~1 -call :log "[WARNING] %~1" -exit /b 0 - -:fail -echo. -echo [ERROR] %~1 -call :log "[ERROR] %~1" -echo. -echo Installer stopped. Log: %LOG_FILE% -pause -exit /b 1 - -:log ->>"%LOG_FILE%" echo [%DATE% %TIME%] %~1 -exit /b 0 +powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0Install-UVR.ps1" %* +exit /b %ERRORLEVEL% diff --git a/install/lib/Common.ps1 b/install/lib/Common.ps1 new file mode 100644 index 0000000..ee4eb7d --- /dev/null +++ b/install/lib/Common.ps1 @@ -0,0 +1,280 @@ +# Common.ps1 - Core logging, native process runner, download, and UI helpers +Set-StrictMode -Version Latest + +# Global logger state container +$script:InstallerLogger = @{ + LogPath = $null +} + +function Initialize-InstallerLogger { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$LogDirectory + ) + + if (-not (Test-Path -LiteralPath $LogDirectory)) { + New-Item -ItemType Directory -Path $LogDirectory -Force | Out-Null + } + + $now = Get-Date + $fileName = "install_{0:yyyy-MM-dd_HH-mm-ss}.log" -f $now + $script:InstallerLogger.LogPath = Join-Path -Path $LogDirectory -ChildPath $fileName +} + +function Write-InstallerLog { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$Message, + + [Parameter(Mandatory = $false)] + [ValidateSet('INFO', 'WARN', 'ERROR', 'DEBUG', 'STEP')] + [string]$Level = 'INFO' + ) + + $timestamp = (Get-Date).ToString('yyyy-MM-dd HH:mm:ss') + $formatted = "[{0}] [{1}] {2}" -f $timestamp, $Level, $Message + + # Console display with suitable colors + switch ($Level) { + 'WARN' { Write-Host $formatted -ForegroundColor Yellow } + 'ERROR' { Write-Host $formatted -ForegroundColor Red } + 'STEP' { Write-Host "`n=== $Message ===" -ForegroundColor Cyan } + default { Write-Host $formatted } + } + + if ($script:InstallerLogger.LogPath) { + try { + [System.IO.File]::AppendAllText( + $script:InstallerLogger.LogPath, + $formatted + "`r`n", + (New-Object System.Text.UTF8Encoding($false)) + ) + } catch { + # Ignore file logging failure to prevent crashing installer + } + } +} + +function Invoke-Native { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$FilePath, + + [Parameter(Mandatory = $false)] + [string[]]$ArgumentList = @(), + + [Parameter(Mandatory = $false)] + [string]$WorkingDirectory = $null, + + [Parameter(Mandatory = $false)] + [int]$TimeoutSeconds = 300 + ) + + $cmdLine = "$FilePath $($ArgumentList -join ' ')" + Write-InstallerLog -Message "Executing: $cmdLine" -Level DEBUG + + $prevEAP = $ErrorActionPreference + $ErrorActionPreference = 'Continue' + + $stdoutLines = @() + $stderrLines = @() + $exitCode = 0 + + $prevLocation = Get-Location + if ($WorkingDirectory -and (Test-Path -LiteralPath $WorkingDirectory)) { + Set-Location -LiteralPath $WorkingDirectory + } + + try { + if ($ArgumentList.Count -gt 0) { + $rawOutput = & $FilePath @ArgumentList 2>&1 + } else { + $rawOutput = & $FilePath 2>&1 + } + $exitCode = if ($null -ne $LASTEXITCODE) { $LASTEXITCODE } else { 0 } + + if ($rawOutput) { + foreach ($item in $rawOutput) { + if ($item -is [System.Management.Automation.ErrorRecord]) { + $stderrLines += $item.ToString() + } else { + $stdoutLines += $item.ToString() + } + } + } + + $stdoutStr = $stdoutLines -join "`r`n" + $stderrStr = $stderrLines -join "`r`n" + + Write-InstallerLog -Message "Completed ($exitCode): $cmdLine" -Level DEBUG + + return [PSCustomObject]@{ + ExitCode = $exitCode + StdOut = $stdoutStr + StdErr = $stderrStr + Success = ($exitCode -eq 0) + } + } catch { + Write-InstallerLog -Message "Execution failed ($cmdLine): $($_.Exception.Message)" -Level ERROR + return [PSCustomObject]@{ + ExitCode = -1 + StdOut = '' + StdErr = $_.Exception.Message + Success = $false + } + } finally { + if ($WorkingDirectory -and (Test-Path -LiteralPath $WorkingDirectory)) { + Set-Location -LiteralPath $prevLocation + } + $ErrorActionPreference = $prevEAP + } +} + +function Write-FileUtf8NoBom { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$Path, + + [Parameter(Mandatory = $true)] + [string]$Content + ) + + $dir = Split-Path -Path $Path -Parent + if ($dir -and (-not (Test-Path -LiteralPath $dir))) { + New-Item -ItemType Directory -Path $dir -Force | Out-Null + } + + [System.IO.File]::WriteAllText( + $Path, + $Content, + (New-Object System.Text.UTF8Encoding($false)) + ) +} + +function Invoke-DownloadWithRetry { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$Uri, + + [Parameter(Mandatory = $true)] + [string]$OutFile, + + [Parameter(Mandatory = $false)] + [int]$MaxAttempts = 3, + + [Parameter(Mandatory = $false)] + [int]$DelaySeconds = 2 + ) + + [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 + $prevProgress = $ProgressPreference + $ProgressPreference = 'SilentlyContinue' + + $hasCurl = $null -ne (Get-Command 'curl.exe' -ErrorAction SilentlyContinue) + + $attempt = 1 + $downloadSuccess = $false + + while ($attempt -le $MaxAttempts) { + Write-InstallerLog -Message "Downloading from $Uri (attempt $attempt/$MaxAttempts)..." -Level INFO + + try { + if ($hasCurl) { + $res = Invoke-Native -FilePath 'curl.exe' -ArgumentList @('-f', '-L', '--retry', '2', '-o', "`"$OutFile`"", "`"$Uri`"") + if ($res.Success -and (Test-Path -LiteralPath $OutFile) -and ((Get-Item -LiteralPath $OutFile).Length -gt 0)) { + $downloadSuccess = $true + break + } + } else { + $webClient = New-Object System.Net.WebClient + try { + $webClient.DownloadFile($Uri, $OutFile) + if ((Test-Path -LiteralPath $OutFile) -and ((Get-Item -LiteralPath $OutFile).Length -gt 0)) { + $downloadSuccess = $true + break + } + } finally { + $webClient.Dispose() + } + } + } catch { + Write-InstallerLog -Message "Download attempt $attempt failed: $($_.Exception.Message)" -Level WARN + } + + if (Test-Path -LiteralPath $OutFile) { + Remove-Item -LiteralPath $OutFile -Force -ErrorAction SilentlyContinue + } + + Start-Sleep -Seconds $DelaySeconds + $attempt++ + } + + $ProgressPreference = $prevProgress + return $downloadSuccess +} + +function Prompt-UserChoice { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$PromptText, + + [Parameter(Mandatory = $true)] + [string[]]$ValidOptions, + + [Parameter(Mandatory = $false)] + [string]$DefaultOption = '' + ) + + $validLower = @($ValidOptions | ForEach-Object { $_.ToLowerInvariant() }) + + while ($true) { + Write-Host -NoNewline $PromptText + $inputVal = Read-Host + + if ([string]::IsNullOrWhiteSpace($inputVal)) { + if (-not [string]::IsNullOrEmpty($DefaultOption)) { + return $DefaultOption.ToUpperInvariant() + } + Write-Host "Input is required. Options: ($($ValidOptions -join '/'))" -ForegroundColor Yellow + continue + } + + $trimmed = $inputVal.Trim().ToLowerInvariant() + if ($validLower -contains $trimmed) { + return $trimmed.ToUpperInvariant() + } + + Write-Host "Invalid choice '$inputVal'. Please choose from: ($($ValidOptions -join '/'))" -ForegroundColor Yellow + } +} + +function Show-InstallerBanner { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$AppName, + + [Parameter(Mandatory = $true)] + [string]$PythonVersion, + + [Parameter(Mandatory = $true)] + [string]$TorchVersion + ) + + Write-Host "" + Write-Host "============================================================" -ForegroundColor Cyan + Write-Host " $AppName - Modern Installer" -ForegroundColor Cyan + Write-Host "============================================================" -ForegroundColor Cyan + Write-Host " Target : NVIDIA RTX 20-series or newer, with CPU fallback" + Write-Host " Python : $PythonVersion" + Write-Host " PyTorch: $TorchVersion" + Write-Host " CUDA : cu128 primary" + Write-Host "============================================================" -ForegroundColor Cyan + Write-Host "" +} diff --git a/install/lib/Config.ps1 b/install/lib/Config.ps1 new file mode 100644 index 0000000..1e381ee --- /dev/null +++ b/install/lib/Config.ps1 @@ -0,0 +1,68 @@ +# Config.ps1 - Single source of truth for all installer configuration values +Set-StrictMode -Version Latest + +function Get-InstallerConfig { + [CmdletBinding()] + param() + + return [PSCustomObject]@{ + App = [PSCustomObject]@{ + Name = 'RLD UVR-Opt' + PythonVersion = '3.11.9' + MinDriverMajor = 570 + } + + Torch = [PSCustomObject]@{ + Version = '2.11.0' + VisionVersion = '0.26.0' + AudioVersion = '2.11.0' + Packages = @('torch==2.11.0', 'torchvision==0.26.0', 'torchaudio==2.11.0') + Cu128IndexUrl = 'https://download.pytorch.org/whl/cu128' + CpuIndexUrl = 'https://download.pytorch.org/whl/cpu' + TargetCuda = '12.8' + } + + Ort = [PSCustomObject]@{ + CudaVersion = '1.22.0' + CpuVersion = '1.22.0' + TrtGpuVersion = '1.24.4' + TrtPluginVersion = '0.4.0' + TrtPluginPkg = 'onnxruntime-ep-nv-tensorrt-rtx-cu12==0.4.0' + } + + Hardware = [PSCustomObject]@{ + MinTrtComputeCapability = 8.0 + MinFreeDiskSpaceBytes = 5368709120 # 5 GB + MinDriverMajor = 570 + } + + ExternalTools = [PSCustomObject]@{ + FFmpegUrl = 'https://www.gyan.dev/ffmpeg/builds/ffmpeg-release-essentials.zip' + RubberbandUrl = 'https://breakfastquay.com/files/releases/rubberband-3.1.2-gpl-executable-windows.zip' + VcRedistUrl = 'https://aka.ms/vs/17/release/vc_redist.x64.exe' + VcRedistMinMajor = 14 + VcRedistMinMinor = 40 + } + + Network = [PSCustomObject]@{ + TimeoutSeconds = 10 + HostsToCheck = @( + 'https://download.pytorch.org/whl/cu128', + 'https://pypi.org/simple', + 'https://www.gyan.dev', + 'https://breakfastquay.com', + 'https://aka.ms' + ) + } + + Files = [PSCustomObject]@{ + RequirementsMain = 'reqs/requirements.txt' + RequirementsTrtRtx = 'reqs/requirements_trt_rtx.txt' + RequirementsCpu = 'reqs/requirements_cpu.txt' + InstallRecordJson = 'install_record.json' + InstallRecordPy = 'install_record.py' + InstallStateJson = 'install_state.json' + RollbackSnapshot = 'rollback_snapshot.txt' + } + } +} diff --git a/install/lib/Detect.ps1 b/install/lib/Detect.ps1 new file mode 100644 index 0000000..d2f8c2a --- /dev/null +++ b/install/lib/Detect.ps1 @@ -0,0 +1,523 @@ +# Detect.ps1 - Phase 1: Pure inspection gathering real machine facts +Set-StrictMode -Version Latest + +function Get-InstallFacts { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$RootDirectory, + + [Parameter(Mandatory = $true)] + [PSCustomObject]$Config + ) + + Write-InstallerLog -Message "Gathering system and environment facts..." -Level INFO + + $installDir = Join-Path -Path $RootDirectory -ChildPath 'install' + $venvDir = Join-Path -Path $RootDirectory -ChildPath 'venv' + $venvPython = Join-Path -Path $venvDir -ChildPath 'Scripts\python.exe' + + # 1. OS Facts + $osArch = [System.Environment]::GetEnvironmentVariable('PROCESSOR_ARCHITECTURE') + $is64Bit = [System.Environment]::Is64BitOperatingSystem + $isArm64 = ($osArch -eq 'ARM64') + $psVersion = $PSVersionTable.PSVersion.ToString() + + $isAdmin = $false + try { + $identity = [Security.Principal.WindowsIdentity]::GetCurrent() + $principal = New-Object Security.Principal.WindowsPrincipal($identity) + $isAdmin = $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) + } catch { + $isAdmin = $false + } + + $osFacts = [PSCustomObject]@{ + VersionString = [System.Environment]::OSVersion.VersionString + IsWindows = ($env:OS -eq 'Windows_NT') + Is64Bit = $is64Bit + IsArm64 = $isArm64 + Architecture = $osArch + PSVersion = $psVersion + IsAdmin = $isAdmin + } + + # 2. GPU Facts + $allAdapters = @() + $hasAmd = $false + $hasIntel = $false + $hasNvidiaAdapter = $false + $amdName = '' + $intelName = '' + + try { + $adapters = Get-CimInstance Win32_VideoController -ErrorAction SilentlyContinue + if ($adapters) { + foreach ($ad in $adapters) { + $name = [string]$ad.Name + $drv = [string]$ad.DriverVersion + $ram = 0 + if ($ad.AdapterRAM) { + $ram = [math]::Round([double]$ad.AdapterRAM / 1MB) + } + + $adapterObj = [PSCustomObject]@{ + Name = $name + DriverVersion = $drv + VramMB = $ram + } + $allAdapters += $adapterObj + + if ($name -match 'AMD|Radeon') { + $hasAmd = $true + $amdName = $name + } + if ($name -match 'Intel') { + $hasIntel = $true + $intelName = $name + } + if ($name -match 'NVIDIA') { + $hasNvidiaAdapter = $true + } + } + } + } catch { + Write-InstallerLog -Message "Could not query Win32_VideoController: $($_.Exception.Message)" -Level WARN + } + + # Query nvidia-smi if available + $nvidiaSmiPath = $null + $hasNvidiaSmi = $false + $nvidiaName = 'Unknown' + $nvidiaDriver = 'Unknown' + $nvidiaDriverMajor = 0 + $nvidiaComputeCap = 0.0 + $nvidiaVramMB = 0 + $hasNvidiaDriver = $false + + $smiCmd = Get-Command 'nvidia-smi.exe' -ErrorAction SilentlyContinue + if ($smiCmd) { + $nvidiaSmiPath = $smiCmd.Source + $hasNvidiaSmi = $true + } elseif (Test-Path -LiteralPath 'C:\Windows\System32\nvidia-smi.exe') { + $nvidiaSmiPath = 'C:\Windows\System32\nvidia-smi.exe' + $hasNvidiaSmi = $true + } + + if ($hasNvidiaSmi) { + $smiRes = Invoke-Native -FilePath $nvidiaSmiPath -ArgumentList @('--query-gpu=name,driver_version,compute_cap,memory.total', '--format=csv,noheader,nounits') -TimeoutSeconds 10 + if ($smiRes.Success -and (-not [string]::IsNullOrWhiteSpace($smiRes.StdOut))) { + $lines = @($smiRes.StdOut -split "`r?`n" | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }) + if ($lines.Count -gt 0) { + $primaryGpu = $lines[0] -split ',' + if ($primaryGpu.Count -ge 2) { + $nvidiaName = $primaryGpu[0].Trim() + $nvidiaDriver = $primaryGpu[1].Trim() + $hasNvidiaDriver = $true + + $driverParts = $nvidiaDriver -split '\.' + if ($driverParts.Count -ge 1) { + [int]::TryParse($driverParts[0], [ref]$nvidiaDriverMajor) | Out-Null + } + } + if ($primaryGpu.Count -ge 3) { + $ccStr = $primaryGpu[2].Trim() + [double]::TryParse($ccStr, [System.Globalization.NumberStyles]::Any, [System.Globalization.CultureInfo]::InvariantCulture, [ref]$nvidiaComputeCap) | Out-Null + } + if ($primaryGpu.Count -ge 4) { + $vramStr = $primaryGpu[3].Trim() + [int]::TryParse($vramStr, [ref]$nvidiaVramMB) | Out-Null + } + } + } + } + + $isRtxSupported = ($nvidiaName -match 'RTX.*20|RTX.*30|RTX.*40|RTX.*50|RTX A|RTX Ada|RTX PRO') + + $gpuFacts = [PSCustomObject]@{ + AllAdapters = $allAdapters + HasAmd = $hasAmd + AmdName = $amdName + HasIntel = $hasIntel + IntelName = $intelName + HasNvidiaAdapter = $hasNvidiaAdapter + HasNvidiaSmi = $hasNvidiaSmi + HasNvidiaDriver = $hasNvidiaDriver + Name = $nvidiaName + DriverVersion = $nvidiaDriver + DriverMajor = $nvidiaDriverMajor + ComputeCapability = $nvidiaComputeCap + VramMB = $nvidiaVramMB + IsRtxSupported = $isRtxSupported + } + + # 3. Venv Facts + $venvExists = (Test-Path -LiteralPath $venvPython) + $venvPythonVer = 'Unknown' + $venvIs64Bit = $true + + if ($venvExists) { + $pyVerRes = Invoke-Native -FilePath $venvPython -ArgumentList @('-c', "`"import sys; print(sys.version.split()[0]); print(sys.maxsize > 2**32)`"") -TimeoutSeconds 5 + if ($pyVerRes.Success) { + $pyLines = @($pyVerRes.StdOut -split "`r?`n" | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }) + if ($pyLines.Count -ge 1) { $venvPythonVer = $pyLines[0].Trim() } + if ($pyLines.Count -ge 2) { $venvIs64Bit = ($pyLines[1].Trim() -eq 'True') } + } + } + + $venvFacts = [PSCustomObject]@{ + Exists = $venvExists + Path = $venvDir + PythonExe = $venvPython + PythonVersion = $venvPythonVer + Is64Bit = $venvIs64Bit + } + + # 4. Package Facts (inspecting venv site-packages dist-info without importing torch) + $sitePackagesDir = Join-Path -Path $venvDir -ChildPath 'Lib\site-packages' + $pkgFacts = [PSCustomObject]@{ + TorchInstalled = $false + TorchVersion = 'None' + TorchVariant = 'None' # CUDA, CPU, or UNKNOWN + TorchLocalTag = '' # cu128, cpu, or none + TorchvisionInstalled = $false + TorchvisionVersion = 'None' + TorchvisionVariant = 'None' + TorchaudioInstalled = $false + TorchaudioVersion = 'None' + TorchaudioVariant = 'None' + HasOrtCpu = $false + OrtCpuVersion = 'None' + HasOrtGpu = $false + OrtGpuVersion = 'None' + HasOrtConflict = $false + HasTrtPlugin = $false + TrtPluginVersion = 'None' + } + + if (Test-Path -LiteralPath $sitePackagesDir) { + $distInfos = Get-ChildItem -LiteralPath $sitePackagesDir -Directory -Filter '*.dist-info' -ErrorAction SilentlyContinue + + foreach ($di in $distInfos) { + $folderName = $di.Name + + # Helper to inspect METADATA Version field + $metaPath = Join-Path -Path $di.FullName -ChildPath 'METADATA' + $versionInMeta = $null + if (Test-Path -LiteralPath $metaPath) { + $verLine = Get-Content -LiteralPath $metaPath -TotalCount 20 -ErrorAction SilentlyContinue | Where-Object { $_ -match '^Version:\s*(.+)$' } + if ($verLine) { + $versionInMeta = $Matches[1].Trim() + } + } + + # Inspect torch + if ($folderName -match '^torch-([0-9\.]+.*?)\.dist-info$') { + $rawVer = if ($versionInMeta) { $versionInMeta } else { $Matches[1] } + $pkgFacts.TorchInstalled = $true + $pkgFacts.TorchVersion = $rawVer + if ($rawVer -match '\+cu([0-9]+)') { + $pkgFacts.TorchVariant = 'CUDA' + $pkgFacts.TorchLocalTag = "cu$($Matches[1])" + } elseif ($rawVer -match '\+cpu') { + $pkgFacts.TorchVariant = 'CPU' + $pkgFacts.TorchLocalTag = 'cpu' + } else { + $pkgFacts.TorchVariant = 'CPU' # PyPI plain wheel without tag is CPU + $pkgFacts.TorchLocalTag = 'none' + } + } + + # Inspect torchvision + if ($folderName -match '^torchvision-([0-9\.]+.*?)\.dist-info$') { + $rawVer = if ($versionInMeta) { $versionInMeta } else { $Matches[1] } + $pkgFacts.TorchvisionInstalled = $true + $pkgFacts.TorchvisionVersion = $rawVer + if ($rawVer -match '\+cu') { + $pkgFacts.TorchvisionVariant = 'CUDA' + } else { + $pkgFacts.TorchvisionVariant = 'CPU' + } + } + + # Inspect torchaudio + if ($folderName -match '^torchaudio-([0-9\.]+.*?)\.dist-info$') { + $rawVer = if ($versionInMeta) { $versionInMeta } else { $Matches[1] } + $pkgFacts.TorchaudioInstalled = $true + $pkgFacts.TorchaudioVersion = $rawVer + if ($rawVer -match '\+cu') { + $pkgFacts.TorchaudioVariant = 'CUDA' + } else { + $pkgFacts.TorchaudioVariant = 'CPU' + } + } + + # Inspect onnxruntime (CPU) + if ($folderName -match '^onnxruntime-([0-9\.]+.*?)\.dist-info$' -and $folderName -notmatch 'gpu' -and $folderName -notmatch 'ep') { + $pkgFacts.HasOrtCpu = $true + $pkgFacts.OrtCpuVersion = if ($versionInMeta) { $versionInMeta } else { $Matches[1] } + } + + # Inspect onnxruntime-gpu + if ($folderName -match '^onnxruntime_gpu-([0-9\.]+.*?)\.dist-info$') { + $pkgFacts.HasOrtGpu = $true + $pkgFacts.OrtGpuVersion = if ($versionInMeta) { $versionInMeta } else { $Matches[1] } + } + + # Inspect TRT-RTX plugin + if ($folderName -match '^onnxruntime_ep_nv_tensorrt_rtx_cu12-([0-9\.]+.*?)\.dist-info$') { + $pkgFacts.HasTrtPlugin = $true + $pkgFacts.TrtPluginVersion = if ($versionInMeta) { $versionInMeta } else { $Matches[1] } + } + } + + $pkgFacts.HasOrtConflict = ($pkgFacts.HasOrtCpu -and $pkgFacts.HasOrtGpu) + } + + # 5. External Tools Facts + # uv + $uvInstalled = $false + $uvVersion = 'None' + $uvCmd = Get-Command 'uv.exe' -ErrorAction SilentlyContinue + if ($uvCmd) { + $uvRes = Invoke-Native -FilePath $uvCmd.Source -ArgumentList @('--version') -TimeoutSeconds 5 + if ($uvRes.Success) { + $uvInstalled = $true + $uvVersion = $uvRes.StdOut.Trim() + } + } + + # ffmpeg + $ffmpegInstalled = $false + $ffmpegPath = '' + $ffmpegSource = 'None' + $rootFfmpeg = Join-Path -Path $RootDirectory -ChildPath 'ffmpeg.exe' + if (Test-Path -LiteralPath $rootFfmpeg) { + $ffmpegInstalled = $true + $ffmpegPath = $rootFfmpeg + $ffmpegSource = 'Root' + } else { + $sysFfmpeg = Get-Command 'ffmpeg.exe' -ErrorAction SilentlyContinue + if ($sysFfmpeg) { + $ffmpegInstalled = $true + $ffmpegPath = $sysFfmpeg.Source + $ffmpegSource = 'SystemPath' + } + } + + # rubberband + $rbInstalled = $false + $rbPath = '' + $rbSource = 'None' + $rootRb = Join-Path -Path $RootDirectory -ChildPath 'rubberband.exe' + if (Test-Path -LiteralPath $rootRb) { + $rbInstalled = $true + $rbPath = $rootRb + $rbSource = 'Root' + } else { + $sysRb = Get-Command 'rubberband.exe' -ErrorAction SilentlyContinue + if (-not $sysRb) { + $sysRb = Get-Command 'rubberband-cli.exe' -ErrorAction SilentlyContinue + } + if ($sysRb) { + $rbInstalled = $true + $rbPath = $sysRb.Source + $rbSource = 'SystemPath' + } + } + + # Visual C++ Redistributable + $vcOk = $false + $vcVersion = 'None' + $vcMajor = 0 + $vcMinor = 0 + + try { + $vcKey = 'HKLM:\SOFTWARE\Microsoft\VisualStudio\14.0\VC\Runtimes\X64' + if (Test-Path -LiteralPath $vcKey) { + $props = Get-ItemProperty -LiteralPath $vcKey -ErrorAction SilentlyContinue + if ($props -and $props.Version) { + $vcVersion = [string]$props.Version -replace '^v', '' + $parts = $vcVersion -split '\.' + if ($parts.Count -ge 2) { + [int]::TryParse($parts[0], [ref]$vcMajor) | Out-Null + [int]::TryParse($parts[1], [ref]$vcMinor) | Out-Null + if ($vcMajor -gt $Config.ExternalTools.VcRedistMinMajor) { + $vcOk = $true + } elseif ($vcMajor -eq $Config.ExternalTools.VcRedistMinMajor -and $vcMinor -ge $Config.ExternalTools.VcRedistMinMinor) { + $vcOk = $true + } + } + } elseif ($props -and $props.Installed -eq 1 -and $props.Minor -ge $Config.ExternalTools.VcRedistMinMinor) { + $vcOk = $true + $vcMajor = 14 + $vcMinor = [int]$props.Minor + } + } + } catch { } + + $toolFacts = [PSCustomObject]@{ + UvInstalled = $uvInstalled + UvVersion = $uvVersion + FFmpegInstalled = $ffmpegInstalled + FFmpegPath = $ffmpegPath + FFmpegSource = $ffmpegSource + RubberbandInstalled = $rbInstalled + RubberbandPath = $rbPath + RubberbandSource = $rbSource + VcRedistOk = $vcOk + VcRedistVersion = $vcVersion + VcRedistMajor = $vcMajor + VcRedistMinor = $vcMinor + } + + # 6. Resources & Connectivity Facts + $installDrive = (Get-Item -LiteralPath $RootDirectory).PSDrive.Name + $rootDriveObj = Get-PSDrive -Name $installDrive -ErrorAction SilentlyContinue + $freeSpaceRoot = if ($rootDriveObj) { $rootDriveObj.Free } else { 0 } + + $tempPath = [System.IO.Path]::GetTempPath() + $tempDriveName = (Get-Item -LiteralPath $tempPath).PSDrive.Name + $tempDriveObj = Get-PSDrive -Name $tempDriveName -ErrorAction SilentlyContinue + $freeSpaceTemp = if ($tempDriveObj) { $tempDriveObj.Free } else { 0 } + + $connectivity = @{} + foreach ($h in $Config.Network.HostsToCheck) { + $connected = $false + try { + $req = [System.Net.WebRequest]::Create($h) + $req.Method = 'HEAD' + $req.Timeout = 5000 + $resp = $req.GetResponse() + $connected = $true + $resp.Close() + } catch { + $connected = $false + } + $connectivity[$h] = $connected + } + + $resourceFacts = [PSCustomObject]@{ + FreeDiskSpaceBytes = $freeSpaceRoot + FreeTempSpaceBytes = $freeSpaceTemp + Connectivity = $connectivity + } + + # 7. History Facts + $recordFile = Join-Path -Path $installDir -ChildPath $Config.Files.InstallRecordJson + $hasRecord = $false + $prevOption = 'None' + $prevMode = 'None' + $recordData = $null + + if (Test-Path -LiteralPath $recordFile) { + try { + $jsonRaw = Get-Content -LiteralPath $recordFile -Raw -ErrorAction SilentlyContinue + if ($jsonRaw) { + $parsed = $jsonRaw | ConvertFrom-Json + if ($parsed -and $parsed.install_mode) { + $hasRecord = $true + $prevMode = [string]$parsed.install_mode + $prevOption = [string]$parsed.selected_option + $recordData = $parsed + } + } + } catch { } + } + + $historyFacts = [PSCustomObject]@{ + HasRecord = $hasRecord + PrevOption = $prevOption + PrevMode = $prevMode + RecordData = $recordData + } + + # 8. Locking Process Facts + $lockingProcesses = @() + try { + $pyProcs = Get-Process -Name 'python', 'pythonw' -ErrorAction SilentlyContinue + if ($pyProcs) { + foreach ($p in $pyProcs) { + try { + $procPath = $p.Path + if ($procPath -and ($procPath -like "$venvDir*" -or $procPath -like "$RootDirectory*")) { + $lockingProcesses += [PSCustomObject]@{ + Id = $p.Id + Name = $p.ProcessName + Path = $procPath + } + } + } catch { } + } + } + } catch { } + + return [PSCustomObject]@{ + RootDirectory = $RootDirectory + InstallDirectory = $installDir + OS = $osFacts + Gpu = $gpuFacts + Venv = $venvFacts + Packages = $pkgFacts + Tools = $toolFacts + Resources = $resourceFacts + History = $historyFacts + LockingProcesses = $lockingProcesses + } +} + +function Resolve-UserChoice { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [PSCustomObject]$Facts, + + [Parameter(Mandatory = $false)] + [string]$ExplicitMode = '', + + [Parameter(Mandatory = $false)] + [switch]$Yes = $false + ) + + # If explicit valid mode is provided (A, B, or C) + if ($ExplicitMode -and ($ExplicitMode -match '^[ABC]$')) { + return $ExplicitMode.ToUpperInvariant() + } + + # Determine automated recommendation based on Facts + $recOption = 'A' + $recReason = 'Stable and safe option with NVIDIA CUDA acceleration.' + + if (-not $Facts.Gpu.HasNvidiaAdapter) { + $recOption = 'C' + if ($Facts.Gpu.HasAmd) { + $recReason = "AMD GPU detected ($($Facts.Gpu.AmdName)), but AMD acceleration is not yet supported. Recommended: CPU." + } else { + $recReason = "No dedicated NVIDIA GPU detected. Recommended: CPU." + } + } elseif ($Facts.Gpu.ComputeCapability -ge 8.0 -and $Facts.Gpu.DriverMajor -ge 570) { + $recOption = 'B' + $recReason = "Ampere+ NVIDIA GPU detected ($($Facts.Gpu.Name), CC $($Facts.Gpu.ComputeCapability)). TensorRT-RTX EP available." + } elseif ($Facts.Gpu.IsRtxSupported) { + $recOption = 'A' + $recReason = "RTX 20-series (Turing) detected. CUDA EP is recommended." + } + + Write-Host "" + Write-Host "Hardware recommendation: [$recOption] - $recReason" -ForegroundColor Cyan + Write-Host "" + Write-Host "Choose installation mode:" + Write-Host " [A] CUDA EP - Stable and safe option (RTX 20+ / Turing or newer)" + Write-Host " [B] TensorRT-RTX EP - Experimental, fast, and optimized (Requires RTX 30+ / Ampere; CUDA EP fallback)" + Write-Host " [C] CPU - Safest fallback (CPU inference)" + Write-Host "" + + if ($Yes) { + Write-Host "Auto-selecting recommended mode [$recOption] due to -Yes switch." -ForegroundColor Green + return $recOption + } + + $promptText = "Mode [A/B/C, default $recOption]: " + $choice = Prompt-UserChoice -PromptText $promptText -ValidOptions @('A', 'B', 'C') -DefaultOption $recOption + return $choice +} diff --git a/install/lib/Install.ps1 b/install/lib/Install.ps1 new file mode 100644 index 0000000..d4822ee --- /dev/null +++ b/install/lib/Install.ps1 @@ -0,0 +1,297 @@ +# Install.ps1 - Phase 4: State mutation executing the verified installation plan +Set-StrictMode -Version Latest + +function Invoke-InstallPlan { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [PSCustomObject]$Plan, + + [Parameter(Mandatory = $true)] + [PSCustomObject]$Facts, + + [Parameter(Mandatory = $false)] + [PSCustomObject]$Config = $null + ) + + if ($null -eq $Config) { + $Config = Get-InstallerConfig + } + + $stepResults = @() + $root = $Facts.RootDirectory + $installDir = $Facts.InstallDirectory + $venvDir = $Facts.Venv.Path + $venvPython = $Facts.Venv.PythonExe + $logDir = Join-Path -Path $root -ChildPath 'install_logs' + $stateFile = Join-Path -Path $installDir -ChildPath $Config.Files.InstallStateJson + + # 1. Snapshot if destructive changes are planned + $snapshotPath = $null + if ($Plan.HasDestructive -and (Test-Path -LiteralPath $venvPython)) { + Write-InstallerLog -Message "Creating environment rollback snapshot..." -Level STEP + $nowStr = (Get-Date).ToString('yyyyMMdd_HHmmss') + $snapshotPath = Join-Path -Path $logDir -ChildPath "snapshot_$nowStr.txt" + $freezeRes = Invoke-Native -FilePath 'uv.exe' -ArgumentList @('pip', 'freeze', '--python', "`"$venvPython`"") + if ($freezeRes.Success) { + Write-FileUtf8NoBom -Path $snapshotPath -Content $freezeRes.StdOut + Write-InstallerLog -Message "Rollback snapshot saved to $snapshotPath" -Level INFO + } + } + + # 2. Prerequisites: uv + $uvAction = $Plan.Actions | Where-Object { $_.Component -eq 'uv' } + if ($uvAction -and $uvAction.Action -eq 'Install') { + Write-InstallerLog -Message "Installing uv..." -Level STEP + $uvInstallScript = Join-Path -Path $env:TEMP -ChildPath "uv_install_$([guid]::NewGuid().ToString('N')).ps1" + $downloadOk = Invoke-DownloadWithRetry -Uri 'https://astral.sh/uv/install.ps1' -OutFile $uvInstallScript + if (-not $downloadOk) { + return [PSCustomObject]@{ Success = $false; ErrorMessage = 'Failed to download uv installer.'; SnapshotPath = $snapshotPath } + } + $instRes = Invoke-Native -FilePath 'powershell.exe' -ArgumentList @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', "`"$uvInstallScript`"") + Remove-Item -LiteralPath $uvInstallScript -Force -ErrorAction SilentlyContinue + if (-not $instRes.Success) { + return [PSCustomObject]@{ Success = $false; ErrorMessage = 'Failed to install uv.'; SnapshotPath = $snapshotPath } + } + $env:PATH = "$env:USERPROFILE\.local\bin;$env:USERPROFILE\.cargo\bin;$env:PATH" + } + + # 3. Prerequisites: VC++ Redistributable + $vcAction = $Plan.Actions | Where-Object { $_.Component -eq 'VCRedist' } + if ($vcAction -and $vcAction.Action -eq 'Install') { + Write-InstallerLog -Message "Downloading Visual C++ Redistributable 2015-2022 (x64)..." -Level STEP + $vcExe = Join-Path -Path $env:TEMP -ChildPath "vc_redist_$([guid]::NewGuid().ToString('N')).exe" + $downloadOk = Invoke-DownloadWithRetry -Uri $Config.ExternalTools.VcRedistUrl -OutFile $vcExe + if ($downloadOk) { + Write-InstallerLog -Message "Installing Visual C++ Redistributable..." -Level INFO + $vcRes = Invoke-Native -FilePath $vcExe -ArgumentList @('/install', '/quiet', '/norestart') + Remove-Item -LiteralPath $vcExe -Force -ErrorAction SilentlyContinue + if ($vcRes.ExitCode -in @(0, 3010)) { + Write-InstallerLog -Message "Visual C++ Redistributable installed successfully (Exit $($vcRes.ExitCode))." -Level INFO + } else { + Write-InstallerLog -Message "Visual C++ Redistributable installer returned code $($vcRes.ExitCode). Continuing." -Level WARN + } + } else { + Write-InstallerLog -Message "Failed to download Visual C++ Redistributable. Some C-modules might fail to load." -Level WARN + } + } + + # 4. Prerequisites: FFmpeg + $ffAction = $Plan.Actions | Where-Object { $_.Component -eq 'FFmpeg' } + if ($ffAction -and $ffAction.Action -eq 'Install') { + Write-InstallerLog -Message "Downloading portable FFmpeg..." -Level STEP + $ffZip = Join-Path -Path $env:TEMP -ChildPath "ffmpeg_$([guid]::NewGuid().ToString('N')).zip" + $downloadOk = Invoke-DownloadWithRetry -Uri $Config.ExternalTools.FFmpegUrl -OutFile $ffZip + if ($downloadOk) { + Write-InstallerLog -Message "Extracting FFmpeg to application root..." -Level INFO + try { + Add-Type -AssemblyName System.IO.Compression.FileSystem + $archive = [System.IO.Compression.ZipFile]::OpenRead($ffZip) + foreach ($entry in $archive.Entries) { + if ($entry.Name -in @('ffmpeg.exe', 'ffprobe.exe')) { + $targetPath = Join-Path -Path $root -ChildPath $entry.Name + [System.IO.Compression.ZipFileExtensions]::ExtractToFile($entry, $targetPath, $true) + } + } + $archive.Dispose() + Write-InstallerLog -Message "FFmpeg binaries installed successfully." -Level INFO + } catch { + Write-InstallerLog -Message "Failed to extract FFmpeg: $($_.Exception.Message)" -Level WARN + } finally { + Remove-Item -LiteralPath $ffZip -Force -ErrorAction SilentlyContinue + } + } + } + + # 5. Prerequisites: Rubber Band + $rbAction = $Plan.Actions | Where-Object { $_.Component -eq 'Rubberband' } + if ($rbAction -and $rbAction.Action -eq 'Install') { + Write-InstallerLog -Message "Downloading portable Rubber Band..." -Level STEP + $rbZip = Join-Path -Path $env:TEMP -ChildPath "rubberband_$([guid]::NewGuid().ToString('N')).zip" + $downloadOk = Invoke-DownloadWithRetry -Uri $Config.ExternalTools.RubberbandUrl -OutFile $rbZip + if ($downloadOk) { + Write-InstallerLog -Message "Extracting Rubber Band to application root..." -Level INFO + try { + Add-Type -AssemblyName System.IO.Compression.FileSystem + $archive = [System.IO.Compression.ZipFile]::OpenRead($rbZip) + foreach ($entry in $archive.Entries) { + if ($entry.Name -in @('rubberband.exe', 'sndfile.dll')) { + $targetPath = Join-Path -Path $root -ChildPath $entry.Name + [System.IO.Compression.ZipFileExtensions]::ExtractToFile($entry, $targetPath, $true) + } + } + $archive.Dispose() + Write-InstallerLog -Message "Rubber Band binaries installed successfully." -Level INFO + } catch { + Write-InstallerLog -Message "Failed to extract Rubber Band: $($_.Exception.Message)" -Level WARN + } finally { + Remove-Item -LiteralPath $rbZip -Force -ErrorAction SilentlyContinue + } + } + } + + # 6. Virtual Environment Provisioning + $venvAction = $Plan.Actions | Where-Object { $_.Component -eq 'Venv' } + if ($venvAction -and $venvAction.Action -in @('Create', 'Recreate')) { + Write-InstallerLog -Message "$($venvAction.Action) virtual environment with Python $($Config.App.PythonVersion)..." -Level STEP + $venvArgs = @('venv', "`"$venvDir`"", '--python', $Config.App.PythonVersion) + if ($venvAction.Action -eq 'Recreate') { + $venvArgs = @('venv', '--clear', "`"$venvDir`"", '--python', $Config.App.PythonVersion) + } + $venvRes = Invoke-Native -FilePath 'uv.exe' -ArgumentList $venvArgs + if (-not $venvRes.Success) { + Write-InstallerLog -Message "Automatic Python $($Config.App.PythonVersion) not available. Trying any available Python 3.11..." -Level WARN + $fallbackArgs = @('venv', "`"$venvDir`"", '--python', '3.11') + $venvRes = Invoke-Native -FilePath 'uv.exe' -ArgumentList $fallbackArgs + if (-not $venvRes.Success) { + return [PSCustomObject]@{ Success = $false; ErrorMessage = "Failed to create virtual environment: $($venvRes.StdErr)"; SnapshotPath = $snapshotPath } + } + } + Write-InstallerLog -Message "Virtual environment provisioned at $venvDir" -Level INFO + } + + # 7. Uninstall Conflicting Components + $removeActions = $Plan.Actions | Where-Object { $_.Action -in @('Remove', 'Replace') } + foreach ($rem in $removeActions) { + switch ($rem.Component) { + 'PyTorch' { + Write-InstallerLog -Message "Uninstalling conflicting PyTorch ecosystem builds..." -Level STEP + Invoke-Native -FilePath 'uv.exe' -ArgumentList @('pip', 'uninstall', '--python', "`"$venvPython`"", 'torch', 'torchvision', 'torchaudio') | Out-Null + } + 'onnxruntime-cpu' { + Write-InstallerLog -Message "Uninstalling CPU onnxruntime..." -Level STEP + Invoke-Native -FilePath 'uv.exe' -ArgumentList @('pip', 'uninstall', '--python', "`"$venvPython`"", 'onnxruntime') | Out-Null + } + 'onnxruntime-gpu' { + Write-InstallerLog -Message "Uninstalling GPU onnxruntime..." -Level STEP + Invoke-Native -FilePath 'uv.exe' -ArgumentList @('pip', 'uninstall', '--python', "`"$venvPython`"", 'onnxruntime-gpu') | Out-Null + } + 'TRT-RTX-Plugin' { + Write-InstallerLog -Message "Uninstalling TensorRT-RTX plugin..." -Level STEP + Invoke-Native -FilePath 'uv.exe' -ArgumentList @('pip', 'uninstall', '--python', "`"$venvPython`"", 'onnxruntime-ep-nv-tensorrt-rtx-cu12') | Out-Null + } + } + } + + # 8. Install Target PyTorch + $torchAction = $Plan.Actions | Where-Object { $_.Component -eq 'PyTorch' } + if ($torchAction -and $torchAction.Action -in @('Install', 'Replace')) { + Write-InstallerLog -Message "Installing PyTorch ($($Plan.TargetTorchVariant)) from $($Plan.TargetTorchIndex)..." -Level STEP + $torchInstallArgs = @( + 'pip', 'install', '--python', "`"$venvPython`"", + '--reinstall-package', 'torch', + '--reinstall-package', 'torchvision', + '--reinstall-package', 'torchaudio' + ) + $Config.Torch.Packages + @('--index-url', $Plan.TargetTorchIndex) + + $torchRes = Invoke-Native -FilePath 'uv.exe' -ArgumentList $torchInstallArgs -TimeoutSeconds 600 + if (-not $torchRes.Success) { + return [PSCustomObject]@{ Success = $false; ErrorMessage = "Failed to install PyTorch: $($torchRes.StdErr)"; SnapshotPath = $snapshotPath } + } + Write-InstallerLog -Message "PyTorch ($($Plan.TargetTorchVariant)) installed successfully." -Level INFO + } + + # 9. Install Target ONNX Runtime & Plugins + if ($Plan.Profile -eq 'A') { + $ortAction = $Plan.Actions | Where-Object { $_.Component -eq 'onnxruntime-gpu' } + if ($ortAction -and $ortAction.Action -in @('Install', 'Replace')) { + Write-InstallerLog -Message "Installing onnxruntime-gpu $($Config.Ort.CudaVersion)..." -Level STEP + $ortRes = Invoke-Native -FilePath 'uv.exe' -ArgumentList @('pip', 'install', '--python', "`"$venvPython`"", '--reinstall-package', 'onnxruntime-gpu', "onnxruntime-gpu==$($Config.Ort.CudaVersion)") + if (-not $ortRes.Success) { + Write-InstallerLog -Message "Failed to install onnxruntime-gpu: $($ortRes.StdErr)" -Level WARN + } + } + } elseif ($Plan.Profile -eq 'B') { + Write-InstallerLog -Message "Installing ONNX Runtime GPU 1.24.4 and TensorRT-RTX EP plugin..." -Level STEP + $ortTrtArgs = @( + 'pip', 'install', '--python', "`"$venvPython`"", + '--reinstall-package', 'onnxruntime-gpu', + '--reinstall-package', 'onnxruntime-ep-nv-tensorrt-rtx-cu12', + "onnxruntime-gpu==$($Config.Ort.TrtGpuVersion)", + $Config.Ort.TrtPluginPkg + ) + $ortRes = Invoke-Native -FilePath 'uv.exe' -ArgumentList $ortTrtArgs + if (-not $ortRes.Success) { + Write-InstallerLog -Message "Failed to install TensorRT-RTX packages: $($ortRes.StdErr). CUDA EP will remain as fallback." -Level WARN + } + } else { + # Profile C + $ortAction = $Plan.Actions | Where-Object { $_.Component -eq 'onnxruntime-cpu' } + if ($ortAction -and $ortAction.Action -in @('Install', 'Replace')) { + Write-InstallerLog -Message "Installing onnxruntime CPU $($Config.Ort.CpuVersion)..." -Level STEP + $ortRes = Invoke-Native -FilePath 'uv.exe' -ArgumentList @('pip', 'install', '--python', "`"$venvPython`"", '--reinstall-package', 'onnxruntime', "onnxruntime==$($Config.Ort.CpuVersion)") + if (-not $ortRes.Success) { + Write-InstallerLog -Message "Failed to install onnxruntime CPU: $($ortRes.StdErr)" -Level WARN + } + } + } + + # 10. Install Pre-built Wheels and Requirements + Write-InstallerLog -Message "Installing base dependencies from $($Plan.RequirementsFile)..." -Level STEP + $wheelsDir = Join-Path -Path $installDir -ChildPath 'wheels' + $diffqWheel = Join-Path -Path $wheelsDir -ChildPath 'diffq-0.2.4-cp311-cp311-win_amd64.whl' + if (Test-Path -LiteralPath $diffqWheel) { + Write-InstallerLog -Message "Pre-installing local binary wheel for diffq..." -Level DEBUG + Invoke-Native -FilePath 'uv.exe' -ArgumentList @('pip', 'install', '--python', "`"$venvPython`"", '--no-deps', "`"$diffqWheel`"") | Out-Null + } + + $reqFilePath = Join-Path -Path $installDir -ChildPath $Plan.RequirementsFile + if (-not (Test-Path -LiteralPath $reqFilePath)) { + $candidateReqs = Join-Path -Path (Join-Path -Path $installDir -ChildPath 'reqs') -ChildPath $Plan.RequirementsFile + if (Test-Path -LiteralPath $candidateReqs) { + $reqFilePath = $candidateReqs + } else { + $reqFilePath = Join-Path -Path $root -ChildPath $Plan.RequirementsFile + if (-not (Test-Path -LiteralPath $reqFilePath)) { + $candidateRootReqs = Join-Path -Path (Join-Path -Path $root -ChildPath 'reqs') -ChildPath $Plan.RequirementsFile + if (Test-Path -LiteralPath $candidateRootReqs) { + $reqFilePath = $candidateRootReqs + } + } + } + } + + $reqInstallFile = $reqFilePath + $tempFilteredReq = $null + + # If Profile C, filter out GPU packages to match .bat behavior + if ($Plan.Profile -eq 'C') { + $tempFilteredReq = Join-Path -Path $env:TEMP -ChildPath "req_cpu_$([guid]::NewGuid().ToString('N')).txt" + $rawReqLines = Get-Content -LiteralPath $reqFilePath -ErrorAction SilentlyContinue + $filteredLines = @() + foreach ($line in $rawReqLines) { + $skip = $false + if ($line -match '^(torch==|torchvision==|torchaudio==)') { $skip = $true } + if ($line -match '^(cupy-cuda|cuda-pathfinder|onnxruntime-gpu|nvidia-)') { $skip = $true } + if ($line -match '^(polygraphy|nvidia-modelopt|onnx-graphsurgeon)') { $skip = $true } + if (-not $skip -and -not [string]::IsNullOrWhiteSpace($line)) { + $filteredLines += $line + } + } + Write-FileUtf8NoBom -Path $tempFilteredReq -Content ($filteredLines -join "`r`n") + $reqInstallFile = $tempFilteredReq + } + + $reqArgs = @('pip', 'install', '--python', "`"$venvPython`"") + if (Test-Path -LiteralPath $wheelsDir) { + $reqArgs += @('--find-links', "`"$wheelsDir`"") + } + $reqArgs += @('-r', "`"$reqInstallFile`"") + + $reqRes = Invoke-Native -FilePath 'uv.exe' -ArgumentList $reqArgs -TimeoutSeconds 600 + + if ($tempFilteredReq -and (Test-Path -LiteralPath $tempFilteredReq)) { + Remove-Item -LiteralPath $tempFilteredReq -Force -ErrorAction SilentlyContinue + } + + if (-not $reqRes.Success) { + return [PSCustomObject]@{ Success = $false; ErrorMessage = "Failed to install base dependencies: $($reqRes.StdErr)"; SnapshotPath = $snapshotPath } + } + Write-InstallerLog -Message "Base dependencies installed successfully." -Level INFO + + return [PSCustomObject]@{ + Success = $true + ErrorMessage = '' + SnapshotPath = $snapshotPath + } +} diff --git a/install/lib/Plan.ps1 b/install/lib/Plan.ps1 new file mode 100644 index 0000000..580d562 --- /dev/null +++ b/install/lib/Plan.ps1 @@ -0,0 +1,364 @@ +# Plan.ps1 - Phase 2: Pure deterministic function producing an install plan +Set-StrictMode -Version Latest + +function New-InstallPlan { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [PSCustomObject]$Facts, + + [Parameter(Mandatory = $true)] + [ValidateSet('A', 'B', 'C')] + [string]$Choice, + + [Parameter(Mandatory = $false)] + [PSCustomObject]$Config = $null, + + [Parameter(Mandatory = $false)] + [string]$ReuseVenv = 'Y' + ) + + if ($null -eq $Config) { + $Config = Get-InstallerConfig + } + + $actions = @() + $orderIndex = 1 + + # 1. Venv Strategy + $venvStrategy = 'Reuse' + $venvReason = 'Venv already exists and is healthy.' + + if (-not $Facts.Venv.Exists) { + $venvStrategy = 'Create' + $venvReason = 'Virtual environment does not exist.' + } elseif ($ReuseVenv -eq 'N') { + $venvStrategy = 'Recreate' + $venvReason = 'User chose not to reuse existing venv.' + } elseif (-not $Facts.Venv.Is64Bit) { + $venvStrategy = 'Recreate' + $venvReason = 'Existing venv is not 64-bit.' + } elseif ($Facts.Venv.PythonVersion -ne 'Unknown' -and -not ($Facts.Venv.PythonVersion -like '3.11*')) { + $venvStrategy = 'Recreate' + $venvReason = "Existing venv uses Python $($Facts.Venv.PythonVersion), but 3.11.x is required." + } + + $actions += [PSCustomObject]@{ + Component = 'Venv' + Current = if ($Facts.Venv.Exists) { "Python $($Facts.Venv.PythonVersion)" } else { 'None' } + Target = "Python $($Config.App.PythonVersion)" + Action = $venvStrategy + Reason = $venvReason + Destructive = ($venvStrategy -eq 'Recreate') + Order = $orderIndex++ + } + + # 2. Prerequisites: uv, VC++ Redistributable, FFmpeg, Rubberband + # uv + if ($Facts.Tools.UvInstalled) { + $actions += [PSCustomObject]@{ + Component = 'uv' + Current = $Facts.Tools.UvVersion + Target = 'Latest' + Action = 'Keep' + Reason = 'uv is already installed.' + Destructive = $false + Order = $orderIndex++ + } + } else { + $actions += [PSCustomObject]@{ + Component = 'uv' + Current = 'None' + Target = 'Latest' + Action = 'Install' + Reason = 'uv is required for fast environment management.' + Destructive = $false + Order = $orderIndex++ + } + } + + # VC++ Redistributable + if ($Facts.Tools.VcRedistOk) { + $actions += [PSCustomObject]@{ + Component = 'VCRedist' + Current = $Facts.Tools.VcRedistVersion + Target = ">= $($Config.ExternalTools.VcRedistMinMajor).$($Config.ExternalTools.VcRedistMinMinor)" + Action = 'Keep' + Reason = 'Visual C++ Redistributable meets version requirement.' + Destructive = $false + Order = $orderIndex++ + } + } else { + $actions += [PSCustomObject]@{ + Component = 'VCRedist' + Current = $Facts.Tools.VcRedistVersion + Target = ">= $($Config.ExternalTools.VcRedistMinMajor).$($Config.ExternalTools.VcRedistMinMinor)" + Action = 'Install' + Reason = 'Required runtime for C-extension modules.' + Destructive = $false + Order = $orderIndex++ + } + } + + # FFmpeg + if ($Facts.Tools.FFmpegInstalled) { + $actions += [PSCustomObject]@{ + Component = 'FFmpeg' + Current = "$($Facts.Tools.FFmpegSource): $($Facts.Tools.FFmpegPath)" + Target = 'Present' + Action = 'Keep' + Reason = 'FFmpeg already available.' + Destructive = $false + Order = $orderIndex++ + } + } else { + $actions += [PSCustomObject]@{ + Component = 'FFmpeg' + Current = 'None' + Target = 'Present (Root)' + Action = 'Install' + Reason = 'Required for audio decoding and conversions.' + Destructive = $false + Order = $orderIndex++ + } + } + + # Rubberband + if ($Facts.Tools.RubberbandInstalled) { + $actions += [PSCustomObject]@{ + Component = 'Rubberband' + Current = "$($Facts.Tools.RubberbandSource): $($Facts.Tools.RubberbandPath)" + Target = 'Present' + Action = 'Keep' + Reason = 'Rubberband already available.' + Destructive = $false + Order = $orderIndex++ + } + } else { + $actions += [PSCustomObject]@{ + Component = 'Rubberband' + Current = 'None' + Target = 'Present (Root)' + Action = 'Install' + Reason = 'Required for time-stretch and pitch-shift tools.' + Destructive = $false + Order = $orderIndex++ + } + } + + # 3. PyTorch Stack + $targetTorchVariant = if ($Choice -in @('A', 'B')) { 'CUDA' } else { 'CPU' } + $targetTorchIndex = if ($targetTorchVariant -eq 'CUDA') { $Config.Torch.Cu128IndexUrl } else { $Config.Torch.CpuIndexUrl } + $targetTorchVer = "$($Config.Torch.Version)$(if ($targetTorchVariant -eq 'CUDA') { '+cu128' } else { '+cpu' })" + + $torchAction = 'Install' + $torchReason = 'Install target PyTorch packages.' + $torchDestructive = $false + + $expectedTag = if ($targetTorchVariant -eq 'CUDA') { 'cu128' } else { 'cpu' } + + if ($venvStrategy -eq 'Recreate' -or -not $Facts.Packages.TorchInstalled) { + $torchAction = 'Install' + $torchReason = "Fresh installation of PyTorch $targetTorchVariant." + } elseif ($Facts.Packages.TorchVariant -ne $targetTorchVariant) { + $torchAction = 'Replace' + $torchReason = "Torch variant mismatch: current is $($Facts.Packages.TorchVariant), target is $targetTorchVariant." + $torchDestructive = $true + } elseif ($Facts.Packages.TorchLocalTag -ne $expectedTag) { + $torchAction = 'Replace' + $torchReason = "Torch build mismatch: $($Facts.Packages.TorchLocalTag) vs $($Config.Torch.TargetCuda)." + $torchDestructive = $true + } elseif ($Facts.Packages.TorchvisionVariant -ne $targetTorchVariant -or $Facts.Packages.TorchaudioVariant -ne $targetTorchVariant) { + $torchAction = 'Replace' + $torchReason = "Ecosystem mismatch: torchvision ($($Facts.Packages.TorchvisionVariant)) or torchaudio ($($Facts.Packages.TorchaudioVariant)) differs from target $targetTorchVariant." + $torchDestructive = $true + } else { + $torchAction = 'Keep' + $torchReason = "PyTorch $targetTorchVariant stack is already correct." + } + + $actions += [PSCustomObject]@{ + Component = 'PyTorch' + Current = "$($Facts.Packages.TorchVariant) ($($Facts.Packages.TorchVersion))" + Target = "$targetTorchVariant ($targetTorchVer)" + Action = $torchAction + Reason = $torchReason + Destructive = $torchDestructive + Order = $orderIndex++ + } + + # 4. ONNX Runtime & Plugins + if ($Choice -eq 'A') { + # Profile A: onnxruntime-gpu==1.22.0, NO onnxruntime (cpu), NO TRT-RTX plugin + if ($Facts.Packages.HasOrtCpu) { + $actions += [PSCustomObject]@{ + Component = 'onnxruntime-cpu' + Current = $Facts.Packages.OrtCpuVersion + Target = 'None' + Action = 'Remove' + Reason = 'Conflicting CPU ONNX Runtime package must be uninstalled for CUDA EP.' + Destructive = $true + Order = $orderIndex++ + } + } + if ($Facts.Packages.HasTrtPlugin) { + $actions += [PSCustomObject]@{ + Component = 'TRT-RTX-Plugin' + Current = $Facts.Packages.TrtPluginVersion + Target = 'None' + Action = 'Remove' + Reason = 'Switching to standard CUDA EP; removing TRT-RTX plugin.' + Destructive = $true + Order = $orderIndex++ + } + } + $ortAction = 'Install' + $ortReason = "Install onnxruntime-gpu $($Config.Ort.CudaVersion)." + $ortDestructive = $false + if ($Facts.Packages.HasOrtGpu -and $Facts.Packages.OrtGpuVersion -eq $Config.Ort.CudaVersion -and -not $Facts.Packages.HasOrtCpu) { + $ortAction = 'Keep' + $ortReason = 'onnxruntime-gpu 1.22.0 already matches target.' + } elseif ($Facts.Packages.HasOrtGpu) { + $ortAction = 'Replace' + $ortReason = "Version change ($($Facts.Packages.OrtGpuVersion) -> $($Config.Ort.CudaVersion))." + $ortDestructive = $true + } + $actions += [PSCustomObject]@{ + Component = 'onnxruntime-gpu' + Current = if ($Facts.Packages.HasOrtGpu) { $Facts.Packages.OrtGpuVersion } else { 'None' } + Target = $Config.Ort.CudaVersion + Action = $ortAction + Reason = $ortReason + Destructive = $ortDestructive + Order = $orderIndex++ + } + } elseif ($Choice -eq 'B') { + # Profile B: onnxruntime-gpu==1.24.4 + TRT-RTX plugin 0.4.0, NO onnxruntime (cpu) + if ($Facts.Packages.HasOrtCpu) { + $actions += [PSCustomObject]@{ + Component = 'onnxruntime-cpu' + Current = $Facts.Packages.OrtCpuVersion + Target = 'None' + Action = 'Remove' + Reason = 'Conflicting CPU ONNX Runtime package must be uninstalled for TensorRT-RTX.' + Destructive = $true + Order = $orderIndex++ + } + } + $ortAction = 'Install' + $ortReason = "Install onnxruntime-gpu $($Config.Ort.TrtGpuVersion)." + $ortDestructive = $false + if ($Facts.Packages.HasOrtGpu -and $Facts.Packages.OrtGpuVersion -eq $Config.Ort.TrtGpuVersion -and -not $Facts.Packages.HasOrtCpu) { + $ortAction = 'Keep' + $ortReason = "onnxruntime-gpu $($Config.Ort.TrtGpuVersion) already matches target." + } elseif ($Facts.Packages.HasOrtGpu) { + $ortAction = 'Replace' + $ortReason = "Version upgrade ($($Facts.Packages.OrtGpuVersion) -> $($Config.Ort.TrtGpuVersion))." + $ortDestructive = $true + } + $actions += [PSCustomObject]@{ + Component = 'onnxruntime-gpu' + Current = if ($Facts.Packages.HasOrtGpu) { $Facts.Packages.OrtGpuVersion } else { 'None' } + Target = $Config.Ort.TrtGpuVersion + Action = $ortAction + Reason = $ortReason + Destructive = $ortDestructive + Order = $orderIndex++ + } + $pluginAction = 'Install' + $pluginReason = "Install TensorRT-RTX plugin $($Config.Ort.TrtPluginVersion)." + $pluginDestructive = $false + if ($Facts.Packages.HasTrtPlugin -and $Facts.Packages.TrtPluginVersion -eq $Config.Ort.TrtPluginVersion) { + $pluginAction = 'Keep' + $pluginReason = 'TensorRT-RTX plugin already matches target.' + } elseif ($Facts.Packages.HasTrtPlugin) { + $pluginAction = 'Replace' + $pluginReason = "Plugin version upgrade ($($Facts.Packages.TrtPluginVersion) -> $($Config.Ort.TrtPluginVersion))." + $pluginDestructive = $true + } + $actions += [PSCustomObject]@{ + Component = 'TRT-RTX-Plugin' + Current = if ($Facts.Packages.HasTrtPlugin) { $Facts.Packages.TrtPluginVersion } else { 'None' } + Target = $Config.Ort.TrtPluginVersion + Action = $pluginAction + Reason = $pluginReason + Destructive = $pluginDestructive + Order = $orderIndex++ + } + } else { + # Profile C: onnxruntime==1.22.0, NO onnxruntime-gpu, NO TRT-RTX plugin + if ($Facts.Packages.HasOrtGpu) { + $actions += [PSCustomObject]@{ + Component = 'onnxruntime-gpu' + Current = $Facts.Packages.OrtGpuVersion + Target = 'None' + Action = 'Remove' + Reason = 'Conflicting GPU ONNX Runtime package must be uninstalled for CPU mode.' + Destructive = $true + Order = $orderIndex++ + } + } + if ($Facts.Packages.HasTrtPlugin) { + $actions += [PSCustomObject]@{ + Component = 'TRT-RTX-Plugin' + Current = $Facts.Packages.TrtPluginVersion + Target = 'None' + Action = 'Remove' + Reason = 'GPU TensorRT plugin uninstalled for CPU mode.' + Destructive = $true + Order = $orderIndex++ + } + } + $ortAction = 'Install' + $ortReason = "Install onnxruntime CPU $($Config.Ort.CpuVersion)." + $ortDestructive = $false + if ($Facts.Packages.HasOrtCpu -and $Facts.Packages.OrtCpuVersion -eq $Config.Ort.CpuVersion -and -not $Facts.Packages.HasOrtGpu) { + $ortAction = 'Keep' + $ortReason = 'onnxruntime CPU already matches target.' + } elseif ($Facts.Packages.HasOrtCpu) { + $ortAction = 'Replace' + $ortReason = "Version change ($($Facts.Packages.OrtCpuVersion) -> $($Config.Ort.CpuVersion))." + $ortDestructive = $true + } + $actions += [PSCustomObject]@{ + Component = 'onnxruntime-cpu' + Current = if ($Facts.Packages.HasOrtCpu) { $Facts.Packages.OrtCpuVersion } else { 'None' } + Target = $Config.Ort.CpuVersion + Action = $ortAction + Reason = $ortReason + Destructive = $ortDestructive + Order = $orderIndex++ + } + } + + # 5. Base Dependencies + $reqFile = switch ($Choice) { + 'A' { $Config.Files.RequirementsMain } + 'B' { $Config.Files.RequirementsTrtRtx } + 'C' { $Config.Files.RequirementsCpu } + } + $actions += [PSCustomObject]@{ + Component = 'Requirements' + Current = 'State-Dependent' + Target = $reqFile + Action = 'Install' + Reason = "Install application dependencies from $reqFile." + Destructive = $false + Order = $orderIndex++ + } + + $isAnyDestructive = @($actions | Where-Object { $_.Destructive -eq $true }).Count -gt 0 + $isNothingToDo = @($actions | Where-Object { $_.Action -notin @('Keep') }).Count -eq 0 + + return [PSCustomObject]@{ + Profile = $Choice + TargetTorchVariant = $targetTorchVariant + TargetTorchIndex = $targetTorchIndex + TargetTorchVer = $targetTorchVer + RequirementsFile = $reqFile + VenvStrategy = $venvStrategy + HasDestructive = $isAnyDestructive + IsNothingToDo = $isNothingToDo + Actions = $actions + } +} diff --git a/install/lib/Record.ps1 b/install/lib/Record.ps1 new file mode 100644 index 0000000..fb7c32a --- /dev/null +++ b/install/lib/Record.ps1 @@ -0,0 +1,110 @@ +# Record.ps1 - Phase 5: Atomic recording of installation state with additive schema +Set-StrictMode -Version Latest + +function Write-InstallRecord { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [PSCustomObject]$Facts, + + [Parameter(Mandatory = $true)] + [string]$Choice, + + [Parameter(Mandatory = $true)] + [PSCustomObject]$Plan, + + [Parameter(Mandatory = $true)] + [PSCustomObject]$Result, + + [Parameter(Mandatory = $true)] + [PSCustomObject]$Report, + + [Parameter(Mandatory = $false)] + [PSCustomObject]$Config = $null + ) + + if ($null -eq $Config) { + $Config = Get-InstallerConfig + } + + $installDir = $Facts.InstallDirectory + $recordFile = Join-Path -Path $installDir -ChildPath $Config.Files.InstallRecordJson + $recordPy = Join-Path -Path $installDir -ChildPath $Config.Files.InstallRecordPy + $venvPython = $Facts.Venv.PythonExe + + $effectiveOpt = $Report.EffectiveOption + $effectiveMode = switch ($effectiveOpt) { + 'A' { 'NVIDIA' } + 'B' { 'TENSORRT_RTX' } + 'C' { 'CPU' } + } + + $hasFfmpegStr = if ($Facts.Tools.FFmpegInstalled) { '1' } else { '0' } + $hasRbStr = if ($Facts.Tools.RubberbandInstalled) { '1' } else { '0' } + $hasVcStr = if ($Facts.Tools.VcRedistOk) { '1' } else { '0' } + $reuseVenvStr = if ($Plan.VenvStrategy -eq 'Reuse') { 'Y' } else { 'N' } + + Write-InstallerLog -Message "Recording installation state to $recordFile..." -Level INFO + + # Step 1: Call install_record.py write for backwards-compatible base schema + if (Test-Path -LiteralPath $venvPython) { + $pyArgs = @( + "`"$recordPy`"", 'write', + '--option', $effectiveOpt, + '--mode', $effectiveMode, + '--reuse-venv', $reuseVenvStr, + '--has-uv', '1', + '--has-ffmpeg', $hasFfmpegStr, + '--has-rubberband', $hasRbStr, + '--has-vc-redist', $hasVcStr + ) + Invoke-Native -FilePath $venvPython -ArgumentList $pyArgs | Out-Null + } + + # Step 2: Read written JSON, add additive enhancements, and write atomically (UTF-8 without BOM) + $recordObj = $null + if (Test-Path -LiteralPath $recordFile) { + try { + $rawJson = Get-Content -LiteralPath $recordFile -Raw -ErrorAction SilentlyContinue + if ($rawJson) { + $recordObj = $rawJson | ConvertFrom-Json + } + } catch { } + } + + if ($null -eq $recordObj) { + $recordObj = [PSCustomObject]@{ + schema_version = 1 + timestamp_utc = (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ') + selected_option = $effectiveOpt + install_mode = $effectiveMode + } + } + + # Additive fields + $recordObj | Add-Member -MemberType NoteProperty -Name 'requested_option' -Value $Choice -Force + $recordObj | Add-Member -MemberType NoteProperty -Name 'effective_option' -Value $effectiveOpt -Force + $recordObj | Add-Member -MemberType NoteProperty -Name 'fallback_reason' -Value $Report.FallbackReason -Force + + $detectedObj = [PSCustomObject]@{ + gpu_name = $Facts.Gpu.Name + driver_version = $Facts.Gpu.DriverVersion + compute_capability = $Facts.Gpu.ComputeCapability + vram_mb = $Facts.Gpu.VramMB + os_version = $Facts.OS.VersionString + os_arch = $Facts.OS.Architecture + vc_redist_ver = $Facts.Tools.VcRedistVersion + } + $recordObj | Add-Member -MemberType NoteProperty -Name 'detected' -Value $detectedObj -Force + + $recordObj | Add-Member -MemberType NoteProperty -Name 'validation' -Value $Report.Checks -Force + + # Write atomically via temp file + $tempFile = Join-Path -Path $installDir -ChildPath "record_tmp_$([guid]::NewGuid().ToString('N')).json" + $jsonOutput = $recordObj | ConvertTo-Json -Depth 6 + + Write-FileUtf8NoBom -Path $tempFile -Content $jsonOutput + Move-Item -LiteralPath $tempFile -Destination $recordFile -Force + + Write-InstallerLog -Message "Successfully written installation record." -Level INFO +} diff --git a/install/lib/Validate.ps1 b/install/lib/Validate.ps1 new file mode 100644 index 0000000..89ba262 --- /dev/null +++ b/install/lib/Validate.ps1 @@ -0,0 +1,207 @@ +# Validate.ps1 - Phase 5: Deep runtime verification of PyTorch, ORT, and external tools +Set-StrictMode -Version Latest + +# Minimal valid ONNX model (Identity graph, opset 17, IR version 8, float32 [1, 2] tensor) encoded in Base64 +# Compatible across all ONNX Runtime versions including 1.22.0 (max IR 10) and 1.24.4+ (max IR 13) +$script:MinimalOnnxBase64 = 'CAg6QgoQCgFYEgFZIghJZGVudGl0eRIEdGVzdFoTCgFYEg4KDAgBEggKAggBCgIIAmITCgFZEg4KDAgBEggKAggBCgIIAkIECgAQEQ==' + +function Test-InstalledStack { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [PSCustomObject]$Plan, + + [Parameter(Mandatory = $true)] + [PSCustomObject]$Facts, + + [Parameter(Mandatory = $false)] + [PSCustomObject]$Config = $null + ) + + if ($null -eq $Config) { + $Config = Get-InstallerConfig + } + + Write-InstallerLog -Message "Starting end-to-end runtime validation..." -Level STEP + + $root = $Facts.RootDirectory + $venvPython = $Facts.Venv.PythonExe + $checks = @() + $effectiveOption = $Plan.Profile + $fallbackReason = '' + $validationPassed = $true + + # 1. External Media Binaries Runtime Test + # FFmpeg + $ffmpegPath = Join-Path -Path $root -ChildPath 'ffmpeg.exe' + if (-not (Test-Path -LiteralPath $ffmpegPath)) { + $sysFf = Get-Command 'ffmpeg.exe' -ErrorAction SilentlyContinue + if ($sysFf) { $ffmpegPath = $sysFf.Source } + } + if (Test-Path -LiteralPath $ffmpegPath) { + $ffRes = Invoke-Native -FilePath $ffmpegPath -ArgumentList @('-version') -TimeoutSeconds 5 + if ($ffRes.Success) { + $checks += [PSCustomObject]@{ Id = 'TOOL_FFMPEG'; Result = 'Pass'; Message = 'FFmpeg executable runs successfully.' } + } else { + $checks += [PSCustomObject]@{ Id = 'TOOL_FFMPEG'; Result = 'Warn'; Message = "FFmpeg execution failed: $($ffRes.StdErr)" } + } + } else { + $checks += [PSCustomObject]@{ Id = 'TOOL_FFMPEG'; Result = 'Warn'; Message = 'FFmpeg executable not found.' } + } + + # Rubber Band + $rbPath = Join-Path -Path $root -ChildPath 'rubberband.exe' + if (-not (Test-Path -LiteralPath $rbPath)) { + $sysRb = Get-Command 'rubberband.exe' -ErrorAction SilentlyContinue + if (-not $sysRb) { $sysRb = Get-Command 'rubberband-cli.exe' -ErrorAction SilentlyContinue } + if ($sysRb) { $rbPath = $sysRb.Source } + } + if (Test-Path -LiteralPath $rbPath) { + $rbRes = Invoke-Native -FilePath $rbPath -ArgumentList @('--version') -TimeoutSeconds 5 + if ($rbRes.Success -or $rbRes.ExitCode -eq 0) { + $checks += [PSCustomObject]@{ Id = 'TOOL_RUBBERBAND'; Result = 'Pass'; Message = 'Rubber Band executable runs successfully.' } + } else { + $checks += [PSCustomObject]@{ Id = 'TOOL_RUBBERBAND'; Result = 'Warn'; Message = "Rubber Band execution failed: $($rbRes.StdErr)" } + } + } else { + $checks += [PSCustomObject]@{ Id = 'TOOL_RUBBERBAND'; Result = 'Warn'; Message = 'Rubber Band executable not found.' } + } + + # 2. PyTorch Runtime Verification + Write-InstallerLog -Message "Validating PyTorch runtime..." -Level INFO + $torchScript = @" +import sys +try: + import torch + is_cuda_req = ('$($Plan.TargetTorchVariant)' == 'CUDA') + if is_cuda_req: + if not torch.cuda.is_available(): + print('ERR: torch.cuda.is_available() is False') + sys.exit(2) + dev_name = torch.cuda.get_device_name(0) + t = torch.zeros(1, device='cuda') + 1.0 + if t.item() != 1.0: + print('ERR: Tensor calculation on GPU failed') + sys.exit(3) + print(f'OK: PyTorch CUDA operational on {dev_name}') + sys.exit(0) + else: + t = torch.zeros(1) + 1.0 + if t.item() != 1.0: + sys.exit(3) + print('OK: PyTorch CPU operational') + sys.exit(0) +except Exception as e: + print(f'ERR: {e}') + sys.exit(1) +"@ + + $torchRes = Invoke-Native -FilePath $venvPython -ArgumentList @('-c', "`"$torchScript`"") -TimeoutSeconds 30 + if ($torchRes.Success) { + $checks += [PSCustomObject]@{ Id = 'PYTORCH_RUNTIME'; Result = 'Pass'; Message = $torchRes.StdOut.Trim() } + Write-InstallerLog -Message "PyTorch runtime verification passed." -Level INFO + } else { + $checks += [PSCustomObject]@{ Id = 'PYTORCH_RUNTIME'; Result = 'Fail'; Message = "PyTorch runtime failed: $($torchRes.StdOut) $($torchRes.StdErr)" } + Write-InstallerLog -Message "PyTorch runtime verification failed." -Level ERROR + $validationPassed = $false + } + + # 3. ONNX Runtime & Execution Provider Verification + Write-InstallerLog -Message "Validating ONNX Runtime Execution Provider..." -Level INFO + $ortProfile = $Plan.Profile + + $ortScript = @" +import sys, base64 +import numpy as np + +try: + import torch + import onnxruntime as ort + from engine.tensorrt_rtx import register_trt_rtx_libraries, is_trt_rtx_available + + register_trt_rtx_libraries() + + profile = '$ortProfile' + b64_model = '$script:MinimalOnnxBase64' + model_bytes = base64.b64decode(b64_model) + + avail = ort.get_available_providers() + print('ORT Available providers:', avail) + + if profile == 'B': + # Try TRT-RTX first via application session factory + trt_ok = False + if is_trt_rtx_available(0): + try: + from engine.tensorrt_rtx.session import create_trt_rtx_session + sess = create_trt_rtx_session(model_bytes) + out = sess.run(None, {'X': np.array([[1.0, 2.0]], dtype=np.float32)}) + active = sess.get_providers()[0] if hasattr(sess, 'get_providers') else '' + if active == 'CUDAExecutionProvider': + print('CUDA_FALLBACK_OK: Fallback to CUDAExecutionProvider succeeded') + sys.exit(10) + print('TRT_RTX_OK: Session created and evaluated successfully on', active) + trt_ok = True + sys.exit(0) + except Exception as trt_err: + print('TRT_RTX_FAIL:', trt_err) + if not trt_ok: + # Fallback to CUDA + sess_cuda = ort.InferenceSession(model_bytes, providers=['CUDAExecutionProvider']) + out_cuda = sess_cuda.run(None, {'X': np.array([[1.0, 2.0]], dtype=np.float32)}) + print('CUDA_FALLBACK_OK: Fallback to CUDAExecutionProvider succeeded') + sys.exit(10) # Code 10 indicates TRT-RTX failed but CUDA fallback worked + sys.exit(0) + + elif profile == 'A': + sess = ort.InferenceSession(model_bytes, providers=['CUDAExecutionProvider']) + out = sess.run(None, {'X': np.array([[1.0, 2.0]], dtype=np.float32)}) + print('CUDA_OK: Session created and evaluated successfully') + sys.exit(0) + + else: + # Profile C + sess = ort.InferenceSession(model_bytes, providers=['CPUExecutionProvider']) + out = sess.run(None, {'X': np.array([[1.0, 2.0]], dtype=np.float32)}) + print('CPU_OK: Session created and evaluated successfully') + sys.exit(0) + +except Exception as exc: + print('ORT_FATAL:', exc) + sys.exit(1) +"@ + + $ortRes = Invoke-Native -FilePath $venvPython -ArgumentList @('-c', "`"$ortScript`"") -TimeoutSeconds 45 -WorkingDirectory $root + if ($ortRes.ExitCode -eq 0) { + $checks += [PSCustomObject]@{ Id = 'ORT_RUNTIME'; Result = 'Pass'; Message = $ortRes.StdOut.Trim() } + Write-InstallerLog -Message "ONNX Runtime verification passed." -Level INFO + } elseif ($ortRes.ExitCode -eq 10 -and $Plan.Profile -eq 'B') { + # Fallback ladder step 1: B runtime failed -> downgrade to A + Write-InstallerLog -Message "TensorRT-RTX EP runtime test failed. Gracefully falling back to stable CUDA EP [A]." -Level WARN + $checks += [PSCustomObject]@{ Id = 'ORT_RUNTIME'; Result = 'Warn'; Message = 'TensorRT-RTX session creation failed; CUDA EP fallback verified.' } + $effectiveOption = 'A' + $fallbackReason = 'TensorRT-RTX session creation failed during verification; CUDA EP fallback active.' + } else { + $checks += [PSCustomObject]@{ Id = 'ORT_RUNTIME'; Result = 'Fail'; Message = "ONNX Runtime validation failed: $($ortRes.StdOut) $($ortRes.StdErr)" } + Write-InstallerLog -Message "ONNX Runtime verification failed." -Level ERROR + $validationPassed = $false + } + + # 4. Smoke Import of Application Core Modules + Write-InstallerLog -Message "Running smoke import test for application core modules..." -Level INFO + $smokeScript = "import sys; import gui_data.constants; import separate; print('UVR_CORE_IMPORTS_OK')" + $smokeRes = Invoke-Native -FilePath $venvPython -ArgumentList @('-c', "`"$smokeScript`"") -TimeoutSeconds 20 -WorkingDirectory $root + if ($smokeRes.Success) { + $checks += [PSCustomObject]@{ Id = 'UVR_CORE_IMPORTS'; Result = 'Pass'; Message = 'Core application modules imported successfully.' } + Write-InstallerLog -Message "Core application modules imported successfully." -Level INFO + } else { + $checks += [PSCustomObject]@{ Id = 'UVR_CORE_IMPORTS'; Result = 'Warn'; Message = "Warning during core module imports: $($smokeRes.StdErr)" } + } + + return [PSCustomObject]@{ + Passed = $validationPassed + EffectiveOption = $effectiveOption + FallbackReason = $fallbackReason + Checks = $checks + } +} diff --git a/install/lib/Verify.ps1 b/install/lib/Verify.ps1 new file mode 100644 index 0000000..f13559d --- /dev/null +++ b/install/lib/Verify.ps1 @@ -0,0 +1,224 @@ +# Verify.ps1 - Phase 3: Read-only gate verifying user choice against machine facts +Set-StrictMode -Version Latest + +function Test-InstallPlan { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [PSCustomObject]$Facts, + + [Parameter(Mandatory = $true)] + [ValidateSet('A', 'B', 'C')] + [string]$Choice, + + [Parameter(Mandatory = $true)] + [PSCustomObject]$Plan, + + [Parameter(Mandatory = $false)] + [PSCustomObject]$Config = $null + ) + + if ($null -eq $Config) { + $Config = Get-InstallerConfig + } + + $checks = @() + $status = 'Approved' + $recOption = $Choice + $recReason = '' + + # 1. OS & Architecture Check + if (-not $Facts.OS.IsWindows) { + $checks += [PSCustomObject]@{ + Id = 'OS_PLATFORM' + Result = 'Fail' + Message = "Operating system is not Windows ($($Facts.OS.VersionString))." + Remediation = 'This installer only supports Windows 10/11 64-bit.' + } + $status = 'Blocked' + } elseif (-not $Facts.OS.Is64Bit -or $Facts.OS.IsArm64) { + $checks += [PSCustomObject]@{ + Id = 'OS_ARCH' + Result = 'Fail' + Message = "Unsupported processor architecture: $($Facts.OS.Architecture)." + Remediation = 'Only Windows 64-bit (x64 / AMD64) is supported. 32-bit and ARM64 are unsupported.' + } + $status = 'Blocked' + } else { + $checks += [PSCustomObject]@{ + Id = 'OS_ARCH' + Result = 'Pass' + Message = "Windows 64-bit verified ($($Facts.OS.Architecture))." + Remediation = '' + } + } + + # 2. Process Locking Check + if ($Facts.LockingProcesses.Count -gt 0) { + $procNames = ($Facts.LockingProcesses | ForEach-Object { "$($_.Name) (PID $($_.Id))" }) -join ', ' + $checks += [PSCustomObject]@{ + Id = 'PROCESS_LOCK' + Result = 'Fail' + Message = "Active process is locking application files: $procNames" + Remediation = 'Please close Ultimate Vocal Remover (UVR) or running Python instances before running installer.' + } + $status = 'Blocked' + } else { + $checks += [PSCustomObject]@{ + Id = 'PROCESS_LOCK' + Result = 'Pass' + Message = 'No active processes locking venv or application files.' + Remediation = '' + } + } + + # 3. Disk Space Check + $minSpace = $Config.Hardware.MinFreeDiskSpaceBytes + if ($Facts.Resources.FreeDiskSpaceBytes -lt $minSpace) { + $freeGB = [math]::Round($Facts.Resources.FreeDiskSpaceBytes / 1GB, 2) + $needGB = [math]::Round($minSpace / 1GB, 2) + $checks += [PSCustomObject]@{ + Id = 'DISK_SPACE' + Result = 'Fail' + Message = "Insufficient free disk space on install drive ($freeGB GB available, $needGB GB required)." + Remediation = "Free up at least $needGB GB on the destination drive." + } + $status = 'Blocked' + } else { + $freeGB = [math]::Round($Facts.Resources.FreeDiskSpaceBytes / 1GB, 2) + $checks += [PSCustomObject]@{ + Id = 'DISK_SPACE' + Result = 'Pass' + Message = "Sufficient disk space available ($freeGB GB)." + Remediation = '' + } + } + + # 4. Network Connectivity Check + $isPyPIOnline = $Facts.Resources.Connectivity['https://pypi.org/simple'] + $isTorchOnline = $Facts.Resources.Connectivity['https://download.pytorch.org/whl/cu128'] + if (-not $isPyPIOnline -and -not $isTorchOnline) { + $checks += [PSCustomObject]@{ + Id = 'NETWORK' + Result = 'Fail' + Message = 'No network connectivity to PyPI or PyTorch repositories.' + Remediation = 'Check your internet connection or proxy/firewall settings.' + } + $status = 'Blocked' + } else { + $checks += [PSCustomObject]@{ + Id = 'NETWORK' + Result = 'Pass' + Message = 'Network connectivity verified.' + Remediation = '' + } + } + + # 5. Hardware & Profile Validation + if ($Choice -in @('A', 'B')) { + # Check NVIDIA presence + if (-not $Facts.Gpu.HasNvidiaAdapter) { + $checks += [PSCustomObject]@{ + Id = 'GPU_NVIDIA_PRESENCE' + Result = 'Fail' + Message = 'No NVIDIA GPU adapter was detected on this system.' + Remediation = 'Switch to CPU fallback mode [C].' + } + if ($status -ne 'Blocked') { + $status = 'Adjusted' + $recOption = 'C' + $recReason = 'No NVIDIA GPU detected; CPU mode [C] is required.' + } + } elseif (-not $Facts.Gpu.HasNvidiaSmi -or -not $Facts.Gpu.HasNvidiaDriver) { + $checks += [PSCustomObject]@{ + Id = 'GPU_NVIDIA_DRIVER' + Result = 'Fail' + Message = 'NVIDIA adapter found, but nvidia-smi or display driver is not installed.' + Remediation = 'Install the latest official NVIDIA graphics driver from nvidia.com.' + } + $status = 'Blocked' + } else { + # Check Driver version >= 570 + if ($Facts.Gpu.DriverMajor -lt $Config.Hardware.MinDriverMajor) { + $checks += [PSCustomObject]@{ + Id = 'GPU_DRIVER_VERSION' + Result = 'Fail' + Message = "NVIDIA driver ($($Facts.Gpu.DriverVersion)) is older than minimum required version ($($Config.Hardware.MinDriverMajor).xx for CUDA 12.8)." + Remediation = "Update NVIDIA driver to version $($Config.Hardware.MinDriverMajor) or newer from nvidia.com." + } + $status = 'Blocked' + } else { + $checks += [PSCustomObject]@{ + Id = 'GPU_DRIVER_VERSION' + Result = 'Pass' + Message = "NVIDIA driver $($Facts.Gpu.DriverVersion) meets requirement (>= $($Config.Hardware.MinDriverMajor))." + Remediation = '' + } + } + + # Check Option B (TensorRT-RTX) hardware requirement (Ampere+ / CC >= 8.0) + if ($Choice -eq 'B') { + if ($Facts.Gpu.ComputeCapability -lt $Config.Hardware.MinTrtComputeCapability) { + $checks += [PSCustomObject]@{ + Id = 'GPU_TRT_ARCHITECTURE' + Result = 'Warn' + Message = "GPU $($Facts.Gpu.Name) has Compute Capability $($Facts.Gpu.ComputeCapability). TensorRT-RTX EP requires Ampere or newer (Compute Capability >= $($Config.Hardware.MinTrtComputeCapability)). Turing (RTX 20-series) is unsupported." + Remediation = 'Downgrade to Option A (CUDA EP).' + } + if ($status -ne 'Blocked') { + $status = 'Adjusted' + $recOption = 'A' + $recReason = "GPU compute capability $($Facts.Gpu.ComputeCapability) does not support TensorRT-RTX. Downgrading to CUDA EP [A]." + } + } else { + $checks += [PSCustomObject]@{ + Id = 'GPU_TRT_ARCHITECTURE' + Result = 'Pass' + Message = "GPU architecture verified for TensorRT-RTX (Compute Capability $($Facts.Gpu.ComputeCapability) >= $($Config.Hardware.MinTrtComputeCapability))." + Remediation = '' + } + } + } + } + } else { + # Option C (CPU) is always valid + $checks += [PSCustomObject]@{ + Id = 'CPU_PROFILE' + Result = 'Pass' + Message = 'CPU profile is valid on any compatible x64 Windows machine.' + Remediation = '' + } + } + + # 6. Plan Invariant Checks + # Exactly one ORT package in target actions + $ortTargetCount = 0 + foreach ($act in $Plan.Actions) { + if ($act.Component -in @('onnxruntime-cpu', 'onnxruntime-gpu') -and $act.Action -in @('Install', 'Keep', 'Replace')) { + $ortTargetCount++ + } + } + if ($ortTargetCount -ne 1) { + $checks += [PSCustomObject]@{ + Id = 'PLAN_ORT_INVARIANT' + Result = 'Fail' + Message = "Plan violates ORT invariant: expected 1 target ORT variant, got $ortTargetCount." + Remediation = 'Internal Plan generation bug.' + } + $status = 'Blocked' + } else { + $checks += [PSCustomObject]@{ + Id = 'PLAN_ORT_INVARIANT' + Result = 'Pass' + Message = 'Target ONNX Runtime variant invariant holds exactly 1 package.' + Remediation = '' + } + } + + return [PSCustomObject]@{ + Status = $status + RecommendedOption = $recOption + RecommendedReason = $recReason + Checks = $checks + } +} diff --git a/install/tests/Fixtures.ps1 b/install/tests/Fixtures.ps1 new file mode 100644 index 0000000..546870f --- /dev/null +++ b/install/tests/Fixtures.ps1 @@ -0,0 +1,140 @@ +# Fixtures.ps1 - Factory generating test $Facts structures for Plan & Verify tests +Set-StrictMode -Version Latest + +function New-TestFacts { + [CmdletBinding()] + param( + [string]$GpuVendor = 'NVIDIA', # NVIDIA, AMD, INTEL, NONE + [string]$GpuName = 'NVIDIA GeForce RTX 4070', + [int]$DriverMajor = 570, + [double]$ComputeCapability = 8.9, + [bool]$HasNvidiaSmi = $true, + [bool]$VenvExists = $true, + [string]$TorchVariant = 'None', # CUDA, CPU, None + [string]$TorchVersion = 'None', + [string]$TorchLocalTag = '', + [string]$TorchvisionVariant = 'None', + [string]$TorchaudioVariant = 'None', + [bool]$HasOrtCpu = $false, + [string]$OrtCpuVer = 'None', + [bool]$HasOrtGpu = $false, + [string]$OrtGpuVer = 'None', + [bool]$HasTrtPlugin = $false, + [string]$TrtPluginVer = 'None', + [long]$FreeDiskSpaceBytes = 10737418240, # 10 GB + [bool]$IsOnline = $true, + [int]$LockingProcessCount = 0 + ) + + $hasNvidia = ($GpuVendor -eq 'NVIDIA') + $hasAmd = ($GpuVendor -eq 'AMD') + $hasIntel = ($GpuVendor -eq 'INTEL') + + $adapters = @() + if ($hasNvidia) { + $adapters += [PSCustomObject]@{ Name = $GpuName; DriverVersion = "$DriverMajor.00"; VramMB = 8192 } + } + if ($hasAmd) { + $adapters += [PSCustomObject]@{ Name = 'AMD Radeon RX 6700 XT'; DriverVersion = '31.0.0'; VramMB = 12288 } + } + if ($hasIntel) { + $adapters += [PSCustomObject]@{ Name = 'Intel Iris Xe Graphics'; DriverVersion = '31.0.0'; VramMB = 2048 } + } + + $lockingProcs = @() + if ($LockingProcessCount -gt 0) { + 1..$LockingProcessCount | ForEach-Object { + $lockingProcs += [PSCustomObject]@{ Id = 1000 + $_; Name = 'python'; Path = "D:\UVR\venv\Scripts\python.exe" } + } + } + + $connectivity = @{ + 'https://download.pytorch.org/whl/cu128' = $IsOnline + 'https://pypi.org/simple' = $IsOnline + 'https://www.gyan.dev' = $IsOnline + 'https://breakfastquay.com' = $IsOnline + 'https://aka.ms' = $IsOnline + } + + return [PSCustomObject]@{ + RootDirectory = 'D:\UVR' + InstallDirectory = 'D:\UVR\install' + OS = [PSCustomObject]@{ + VersionString = 'Microsoft Windows 11 Pro 10.0.22631' + IsWindows = $true + Is64Bit = $true + IsArm64 = $false + Architecture = 'AMD64' + PSVersion = '5.1.22621.1' + IsAdmin = $false + } + Gpu = [PSCustomObject]@{ + AllAdapters = $adapters + HasAmd = $hasAmd + AmdName = if ($hasAmd) { 'AMD Radeon RX 6700 XT' } else { '' } + HasIntel = $hasIntel + IntelName = if ($hasIntel) { 'Intel Iris Xe Graphics' } else { '' } + HasNvidiaAdapter = $hasNvidia + HasNvidiaSmi = ($hasNvidia -and $HasNvidiaSmi) + HasNvidiaDriver = ($hasNvidia -and $HasNvidiaSmi) + Name = if ($hasNvidia) { $GpuName } else { 'Unknown' } + DriverVersion = if ($hasNvidia) { "$DriverMajor.14" } else { 'Unknown' } + DriverMajor = if ($hasNvidia) { $DriverMajor } else { 0 } + ComputeCapability = if ($hasNvidia) { $ComputeCapability } else { 0.0 } + VramMB = if ($hasNvidia) { 8192 } else { 0 } + IsRtxSupported = ($hasNvidia -and $GpuName -match 'RTX') + } + Venv = [PSCustomObject]@{ + Exists = $VenvExists + Path = 'D:\UVR\venv' + PythonExe = 'D:\UVR\venv\Scripts\python.exe' + PythonVersion = if ($VenvExists) { '3.11.9' } else { 'Unknown' } + Is64Bit = $true + } + Packages = [PSCustomObject]@{ + TorchInstalled = ($TorchVariant -ne 'None') + TorchVersion = $TorchVersion + TorchVariant = $TorchVariant + TorchLocalTag = $TorchLocalTag + TorchvisionInstalled = ($TorchvisionVariant -ne 'None') + TorchvisionVersion = '0.26.0' + TorchvisionVariant = $TorchvisionVariant + TorchaudioInstalled = ($TorchaudioVariant -ne 'None') + TorchaudioVersion = '2.11.0' + TorchaudioVariant = $TorchaudioVariant + HasOrtCpu = $HasOrtCpu + OrtCpuVersion = $OrtCpuVer + HasOrtGpu = $HasOrtGpu + OrtGpuVersion = $OrtGpuVer + HasOrtConflict = ($HasOrtCpu -and $HasOrtGpu) + HasTrtPlugin = $HasTrtPlugin + TrtPluginVersion = $TrtPluginVer + } + Tools = [PSCustomObject]@{ + UvInstalled = $true + UvVersion = 'uv 0.6.5' + FFmpegInstalled = $true + FFmpegPath = 'D:\UVR\ffmpeg.exe' + FFmpegSource = 'Root' + RubberbandInstalled = $true + RubberbandPath = 'D:\UVR\rubberband.exe' + RubberbandSource = 'Root' + VcRedistOk = $true + VcRedistVersion = '14.40.33810' + VcRedistMajor = 14 + VcRedistMinor = 40 + } + Resources = [PSCustomObject]@{ + FreeDiskSpaceBytes = $FreeDiskSpaceBytes + FreeTempSpaceBytes = 10737418240 + Connectivity = $connectivity + } + History = [PSCustomObject]@{ + HasRecord = $false + PrevOption = 'None' + PrevMode = 'None' + RecordData = $null + } + LockingProcesses = $lockingProcs + } +} diff --git a/install/tests/Plan.Tests.ps1 b/install/tests/Plan.Tests.ps1 new file mode 100644 index 0000000..5426e12 --- /dev/null +++ b/install/tests/Plan.Tests.ps1 @@ -0,0 +1,102 @@ +# Plan.Tests.ps1 - Pester tests for Phase 2: Install Plan generation +Set-StrictMode -Version Latest + +$testDir = Split-Path -Parent $MyInvocation.MyCommand.Path +$libDir = Join-Path -Path (Split-Path -Parent $testDir) -ChildPath 'lib' + +. (Join-Path -Path $libDir -ChildPath 'Config.ps1') +. (Join-Path -Path $libDir -ChildPath 'Plan.ps1') +. (Join-Path -Path $testDir -ChildPath 'Fixtures.ps1') + +Describe 'Phase 2: Plan Generation Tests' { + + It 'Scenario 6: CPU venv, user picks Option A -> Replaces torch CPU with CUDA, replaces ORT CPU with GPU' { + $facts = New-TestFacts -TorchVariant 'CPU' -TorchVersion '2.11.0' -TorchLocalTag 'cpu' -TorchvisionVariant 'CPU' -TorchaudioVariant 'CPU' -HasOrtCpu $true -OrtCpuVer '1.22.0' + $plan = New-InstallPlan -Facts $facts -Choice 'A' + + $plan.Profile | Should Be 'A' + $plan.TargetTorchVariant | Should Be 'CUDA' + $plan.HasDestructive | Should Be ($true) + + $torchAction = $plan.Actions | Where-Object { $_.Component -eq 'PyTorch' } + $torchAction.Action | Should Be 'Replace' + $torchAction.Destructive | Should Be ($true) + + $ortCpuAction = $plan.Actions | Where-Object { $_.Component -eq 'onnxruntime-cpu' } + $ortCpuAction.Action | Should Be 'Remove' + + $ortGpuAction = $plan.Actions | Where-Object { $_.Component -eq 'onnxruntime-gpu' } + $ortGpuAction.Action | Should Be 'Install' + + $uvAction = $plan.Actions | Where-Object { $_.Component -eq 'uv' } + $uvAction.Action | Should Be 'Keep' + } + + It 'Scenario 7: Option A venv, user picks Option B -> Torch remains Keep, only ORT upgrades and plugin installs' { + $facts = New-TestFacts -TorchVariant 'CUDA' -TorchVersion '2.11.0' -TorchLocalTag 'cu128' -TorchvisionVariant 'CUDA' -TorchaudioVariant 'CUDA' -HasOrtGpu $true -OrtGpuVer '1.22.0' -HasTrtPlugin $false + $plan = New-InstallPlan -Facts $facts -Choice 'B' + + $plan.Profile | Should Be 'B' + $plan.TargetTorchVariant | Should Be 'CUDA' + + $torchAction = $plan.Actions | Where-Object { $_.Component -eq 'PyTorch' } + $torchAction.Action | Should Be 'Keep' + + $ortAction = $plan.Actions | Where-Object { $_.Component -eq 'onnxruntime-gpu' } + $ortAction.Action | Should Be 'Replace' + $ortAction.Target | Should Be '1.24.4' + + $pluginAction = $plan.Actions | Where-Object { $_.Component -eq 'TRT-RTX-Plugin' } + $pluginAction.Action | Should Be 'Install' + } + + It 'Scenario 8: Option B venv, user picks Option A -> Torch remains Keep, plugin is removed, ORT downgraded to 1.22.0' { + $facts = New-TestFacts -TorchVariant 'CUDA' -TorchVersion '2.11.0' -TorchLocalTag 'cu128' -TorchvisionVariant 'CUDA' -TorchaudioVariant 'CUDA' -HasOrtGpu $true -OrtGpuVer '1.24.4' -HasTrtPlugin $true -TrtPluginVer '0.4.0' + $plan = New-InstallPlan -Facts $facts -Choice 'A' + + $plan.Profile | Should Be 'A' + + $torchAction = $plan.Actions | Where-Object { $_.Component -eq 'PyTorch' } + $torchAction.Action | Should Be 'Keep' + + $pluginAction = $plan.Actions | Where-Object { $_.Component -eq 'TRT-RTX-Plugin' } + $pluginAction.Action | Should Be 'Remove' + + $ortAction = $plan.Actions | Where-Object { $_.Component -eq 'onnxruntime-gpu' } + $ortAction.Action | Should Be 'Replace' + $ortAction.Target | Should Be '1.22.0' + } + + It 'Scenario 9: Venv has both onnxruntime and onnxruntime-gpu conflict -> Removes conflicting variant' { + $facts = New-TestFacts -TorchVariant 'CUDA' -TorchVersion '2.11.0' -TorchLocalTag 'cu128' -TorchvisionVariant 'CUDA' -TorchaudioVariant 'CUDA' -HasOrtCpu $true -OrtCpuVer '1.22.0' -HasOrtGpu $true -OrtGpuVer '1.22.0' + $plan = New-InstallPlan -Facts $facts -Choice 'A' + + $ortCpuAction = $plan.Actions | Where-Object { $_.Component -eq 'onnxruntime-cpu' } + $ortCpuAction.Action | Should Be 'Remove' + + $ortGpuAction = $plan.Actions | Where-Object { $_.Component -eq 'onnxruntime-gpu' } + $ortGpuAction.Action | Should Be 'Replace' + } + + It 'Scenario 10: Plain torch with no local tag (2.11.0) -> Treated as CPU, replaced when user picks A' { + $facts = New-TestFacts -TorchVariant 'CPU' -TorchVersion '2.11.0' -TorchLocalTag 'none' -TorchvisionVariant 'CPU' -TorchaudioVariant 'CPU' + $plan = New-InstallPlan -Facts $facts -Choice 'A' + + $torchAction = $plan.Actions | Where-Object { $_.Component -eq 'PyTorch' } + $torchAction.Action | Should Be 'Replace' + $torchAction.Reason | Should Match 'Torch variant mismatch' + } + + It 'Scenario 14: Rerun with the exact same choice -> Everything is Keep, no destructive actions' { + $facts = New-TestFacts -TorchVariant 'CUDA' -TorchVersion '2.11.0' -TorchLocalTag 'cu128' -TorchvisionVariant 'CUDA' -TorchaudioVariant 'CUDA' -HasOrtGpu $true -OrtGpuVer '1.22.0' -HasTrtPlugin $false + $plan = New-InstallPlan -Facts $facts -Choice 'A' + + $torchAction = $plan.Actions | Where-Object { $_.Component -eq 'PyTorch' } + $torchAction.Action | Should Be 'Keep' + + $ortAction = $plan.Actions | Where-Object { $_.Component -eq 'onnxruntime-gpu' } + $ortAction.Action | Should Be 'Keep' + + $plan.HasDestructive | Should Be ($false) + } +} diff --git a/install/tests/Record.Tests.ps1 b/install/tests/Record.Tests.ps1 new file mode 100644 index 0000000..b866e55 --- /dev/null +++ b/install/tests/Record.Tests.ps1 @@ -0,0 +1,47 @@ +# Record.Tests.ps1 - Pester tests for Phase 5: Install Record writing +Set-StrictMode -Version Latest + +$testDir = Split-Path -Parent $MyInvocation.MyCommand.Path +$libDir = Join-Path -Path (Split-Path -Parent $testDir) -ChildPath 'lib' + +. (Join-Path -Path $libDir -ChildPath 'Config.ps1') +. (Join-Path -Path $libDir -ChildPath 'Common.ps1') +. (Join-Path -Path $libDir -ChildPath 'Plan.ps1') +. (Join-Path -Path $libDir -ChildPath 'Record.ps1') +. (Join-Path -Path $testDir -ChildPath 'Fixtures.ps1') + +Describe 'Phase 5: Record Writing Tests' { + It 'Writes install record without syntax or runtime error' { + $tempDir = Join-Path -Path $env:TEMP -ChildPath "uvr_test_rec_$([guid]::NewGuid().ToString('N'))" + New-Item -ItemType Directory -Path $tempDir -Force | Out-Null + + try { + $facts = New-TestFacts + $facts.InstallDirectory = $tempDir + + $plan = New-InstallPlan -Facts $facts -Choice 'B' + $result = [PSCustomObject]@{ Success = $true; ErrorMessage = ''; SnapshotPath = '' } + $report = [PSCustomObject]@{ + Passed = $true + EffectiveOption = 'B' + FallbackReason = 'None' + Checks = @() + } + + { Write-InstallRecord -Facts $facts -Choice 'B' -Plan $plan -Result $result -Report $report } | Should Not Throw + + $recordPath = Join-Path -Path $tempDir -ChildPath 'install_record.json' + Test-Path -LiteralPath $recordPath | Should Be $true + + $content = Get-Content -LiteralPath $recordPath -Raw | ConvertFrom-Json + $content.selected_option | Should Be 'B' + $content.effective_option | Should Be 'B' + $content.requested_option | Should Be 'B' + } + finally { + if (Test-Path -LiteralPath $tempDir) { + Remove-Item -LiteralPath $tempDir -Recurse -Force -ErrorAction SilentlyContinue + } + } + } +} diff --git a/install/tests/Verify.Tests.ps1 b/install/tests/Verify.Tests.ps1 new file mode 100644 index 0000000..256f007 --- /dev/null +++ b/install/tests/Verify.Tests.ps1 @@ -0,0 +1,88 @@ +# Verify.Tests.ps1 - Pester tests for Phase 3: Plan Verification and Gates +Set-StrictMode -Version Latest + +$testDir = Split-Path -Parent $MyInvocation.MyCommand.Path +$libDir = Join-Path -Path (Split-Path -Parent $testDir) -ChildPath 'lib' + +. (Join-Path -Path $libDir -ChildPath 'Config.ps1') +. (Join-Path -Path $libDir -ChildPath 'Plan.ps1') +. (Join-Path -Path $libDir -ChildPath 'Verify.ps1') +. (Join-Path -Path $testDir -ChildPath 'Fixtures.ps1') + +Describe 'Phase 3: Verification & Gate Tests' { + + It 'Scenario 1: No GPU, user picks Option A -> Status is Adjusted, recommends Option C' { + $facts = New-TestFacts -GpuVendor 'NONE' + $plan = New-InstallPlan -Facts $facts -Choice 'A' + $verdict = Test-InstallPlan -Facts $facts -Choice 'A' -Plan $plan + + $verdict.Status | Should Be 'Adjusted' + $verdict.RecommendedOption | Should Be 'C' + } + + It 'Scenario 2: AMD GPU only, user picks Option A or B -> Status is Adjusted, recommends Option C' { + $facts = New-TestFacts -GpuVendor 'AMD' + $plan = New-InstallPlan -Facts $facts -Choice 'B' + $verdict = Test-InstallPlan -Facts $facts -Choice 'B' -Plan $plan + + $verdict.Status | Should Be 'Adjusted' + $verdict.RecommendedOption | Should Be 'C' + } + + It 'Scenario 3: NVIDIA Turing (CC 7.5), user picks Option B -> Status is Adjusted, recommends Option A' { + $facts = New-TestFacts -GpuVendor 'NVIDIA' -GpuName 'NVIDIA GeForce RTX 2080 Ti' -DriverMajor 570 -ComputeCapability 7.5 + $plan = New-InstallPlan -Facts $facts -Choice 'B' + $verdict = Test-InstallPlan -Facts $facts -Choice 'B' -Plan $plan + + $verdict.Status | Should Be 'Adjusted' + $verdict.RecommendedOption | Should Be 'A' + } + + It 'Scenario 4: RTX 50-series (CC 12.0, driver 617), picks Option B -> Status is Approved' { + $facts = New-TestFacts -GpuVendor 'NVIDIA' -GpuName 'NVIDIA GeForce RTX 5060 Ti' -DriverMajor 617 -ComputeCapability 12.0 + $plan = New-InstallPlan -Facts $facts -Choice 'B' + $verdict = Test-InstallPlan -Facts $facts -Choice 'B' -Plan $plan + + $verdict.Status | Should Be 'Approved' + } + + It 'Scenario 5: NVIDIA GPU present but driver is too old (< 570) -> Status is Blocked' { + $facts = New-TestFacts -GpuVendor 'NVIDIA' -DriverMajor 535 + $plan = New-InstallPlan -Facts $facts -Choice 'A' + $verdict = Test-InstallPlan -Facts $facts -Choice 'A' -Plan $plan + + $verdict.Status | Should Be 'Blocked' + $failedCheck = $verdict.Checks | Where-Object { $_.Id -eq 'GPU_DRIVER_VERSION' } + $failedCheck.Result | Should Be 'Fail' + } + + It 'Scenario 11: Offline (no connection to repositories) -> Status is Blocked' { + $facts = New-TestFacts -IsOnline $false + $plan = New-InstallPlan -Facts $facts -Choice 'C' + $verdict = Test-InstallPlan -Facts $facts -Choice 'C' -Plan $plan + + $verdict.Status | Should Be 'Blocked' + $netCheck = $verdict.Checks | Where-Object { $_.Id -eq 'NETWORK' } + $netCheck.Result | Should Be 'Fail' + } + + It 'Scenario 12: Insufficient disk space (< 5GB) -> Status is Blocked' { + $facts = New-TestFacts -FreeDiskSpaceBytes 1048576000 # 1 GB + $plan = New-InstallPlan -Facts $facts -Choice 'C' + $verdict = Test-InstallPlan -Facts $facts -Choice 'C' -Plan $plan + + $verdict.Status | Should Be 'Blocked' + $diskCheck = $verdict.Checks | Where-Object { $_.Id -eq 'DISK_SPACE' } + $diskCheck.Result | Should Be 'Fail' + } + + It 'Scenario 13: UVR or Python is currently running and holding files -> Status is Blocked' { + $facts = New-TestFacts -LockingProcessCount 2 + $plan = New-InstallPlan -Facts $facts -Choice 'C' + $verdict = Test-InstallPlan -Facts $facts -Choice 'C' -Plan $plan + + $verdict.Status | Should Be 'Blocked' + $lockCheck = $verdict.Checks | Where-Object { $_.Id -eq 'PROCESS_LOCK' } + $lockCheck.Result | Should Be 'Fail' + } +}