@echo off setlocal chcp 65001 >nul title FoundryManager Studio - Install and Run set "FM_BOOTSTRAP_SELF=%~f0" powershell.exe -NoLogo -NoProfile -ExecutionPolicy Bypass -Command "$raw=[IO.File]::ReadAllText($env:FM_BOOTSTRAP_SELF);$mark='#==POWERSHELL==';$at=$raw.LastIndexOf($mark);if($at -lt 0){throw 'Bootstrap payload not found'};& ([scriptblock]::Create($raw.Substring($at)))" set "FM_EXIT=%ERRORLEVEL%" if not "%FM_EXIT%"=="0" ( echo. echo [ERROR] FoundryManager Studio could not start. See the message above. pause ) exit /b %FM_EXIT% #==POWERSHELL== $ErrorActionPreference = "Stop" [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false) [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 $Product = "FoundryManager Studio" $Root = Join-Path $env:LOCALAPPDATA "FoundryManagerStudio" $DataDir = Join-Path $Root "data" $ProfilesDir = Join-Path $DataDir "profiles" $ReleasesDir = Join-Path $Root "releases" $VenvDir = Join-Path $Root "venv" $CurrentFile = Join-Path $Root "current.txt" $RequirementStamp = Join-Path $Root "requirements.sha256" $ManifestUrls = @( "https://huggingface.co/datasets/DangPhamPham/foundrymanager-studio/resolve/main/manifest.json", "https://huggingface.co/datasets/phamdangdangild/foundrymanager-studio/resolve/main/manifest.json" ) $AllowedReleasePrefixes = @( "https://huggingface.co/datasets/DangPhamPham/foundrymanager-studio/resolve/", "https://huggingface.co/datasets/phamdangdangild/foundrymanager-studio/resolve/" ) function Step([string]$Message) { Write-Host ("[*] " + $Message) -ForegroundColor Cyan } function Good([string]$Message) { Write-Host ("[OK] " + $Message) -ForegroundColor Green } function Warn([string]$Message) { Write-Host ("[!] " + $Message) -ForegroundColor Yellow } function Test-Administrator { $identity = [Security.Principal.WindowsIdentity]::GetCurrent() $principal = [Security.Principal.WindowsPrincipal]::new($identity) return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) } function Get-WorkingPython { $candidates = [System.Collections.Generic.List[string]]::new() $portable = Join-Path $Root "runtime\python-portable\python.exe" if (Test-Path -LiteralPath $portable -PathType Leaf) { $candidates.Add($portable) } $managed = Join-Path $Root "runtime\python\python.exe" if (Test-Path -LiteralPath $managed -PathType Leaf) { $candidates.Add($managed) } if ($env:FM_FORCE_PORTABLE_PYTHON -eq "1") { foreach ($candidate in ($candidates | Select-Object -Unique)) { try { & $candidate -c "import sys;raise SystemExit(0 if sys.version_info >= (3,10) else 1)" 2>$null if ($LASTEXITCODE -eq 0) { return $candidate } } catch {} } return $null } try { $py = Get-Command py.exe -ErrorAction Stop $resolved = (& $py.Source -3 -c "import sys;print(sys.executable)" 2>$null | Select-Object -First 1) if ($LASTEXITCODE -eq 0 -and $resolved) { $candidates.Add($resolved.Trim()) } } catch {} foreach ($command in @("python.exe", "python3.exe")) { try { $candidates.Add((Get-Command $command -ErrorAction Stop).Source) } catch {} } foreach ($candidate in ($candidates | Select-Object -Unique)) { try { $valid = & $candidate -c "import sys;raise SystemExit(0 if sys.version_info >= (3,10) else 1)" 2>$null if ($LASTEXITCODE -eq 0) { return $candidate } } catch {} } return $null } function Install-ManagedPython([string]$SessionDir) { Step "Python 3.10+ chưa có; tải Python portable chính chủ (không chạy installer)" $version = "3.12.10" $arch = if ([Environment]::Is64BitOperatingSystem) { "amd64" } else { "win32" } if ($env:PROCESSOR_ARCHITECTURE -eq "ARM64" -or $env:PROCESSOR_IDENTIFIER -match "ARM") { $arch = "arm64" } $fileName = "python-$version-$arch.zip" $url = "https://www.python.org/ftp/python/$version/$fileName" $expectedHashes = @{ "amd64" = "8649692de846c56a7189d6dae5c322ab20deb1b5908b6f39426b62a36f39415d" "arm64" = "20a5b1a707d899ffdfc5e3086d7372f7cc95eeea344d48ae256047cb7075cf63" "win32" = "b665393cbead6570e9445d9178e30160581149de2b09f29c8230a28718324801" } $archive = Join-Path $SessionDir $fileName Invoke-WebRequest -UseBasicParsing -Uri $url -OutFile $archive -TimeoutSec 300 $actualHash = (Get-FileHash -Algorithm SHA256 -LiteralPath $archive).Hash.ToLowerInvariant() if ($actualHash -ne $expectedHashes[$arch]) { throw "SHA256 Python portable không khớp; đã dừng để bảo vệ VPS." } $stage = Join-Path $SessionDir "python-portable" New-Item -ItemType Directory -Path $stage | Out-Null Expand-VerifiedZip $archive $stage $stagePython = Join-Path $stage "python.exe" if (-not (Test-Path -LiteralPath $stagePython -PathType Leaf)) { throw "Gói Python portable thiếu python.exe." } & $stagePython -c "import ensurepip, venv, sys; raise SystemExit(0 if sys.version_info >= (3,10) else 1)" 2>$null if ($LASTEXITCODE -ne 0) { throw "Python portable tải về không vượt qua kiểm tra runtime." } $target = Join-Path $Root "runtime\python-portable" New-Item -ItemType Directory -Force -Path (Split-Path $target -Parent) | Out-Null if (Test-Path -LiteralPath $target) { $backup = $target + ".replaced-" + [DateTime]::UtcNow.ToString("yyyyMMddHHmmss") Move-Item -LiteralPath $target -Destination $backup } Move-Item -LiteralPath $stage -Destination $target Good "Python portable $version ($arch) đã sẵn sàng; không thay đổi Windows." return (Join-Path $target "python.exe") } function Get-Manifest { foreach ($url in $ManifestUrls) { try { Step "Kiểm tra bản phát hành từ Hugging Face" $cacheBust = if ($url.Contains("?")) { "&" } else { "?" } $response = Invoke-WebRequest -UseBasicParsing -Uri ($url + $cacheBust + "t=" + [DateTimeOffset]::UtcNow.ToUnixTimeSeconds()) -TimeoutSec 45 $manifest = $response.Content | ConvertFrom-Json if ($manifest.version -notmatch '^\d+\.\d+\.\d+$') { throw "version không hợp lệ" } if ($manifest.sha256 -notmatch '^[a-fA-F0-9]{64}$') { throw "SHA256 không hợp lệ" } foreach ($releaseUrl in @([string]$manifest.zip_url) + @($manifest.mirrors)) { $allowed = $false foreach ($prefix in $AllowedReleasePrefixes) { if ($releaseUrl -like ($prefix + "*")) { $allowed = $true; break } } if (-not $allowed) { throw "release URL ngoài repo cho phép" } } return $manifest } catch { Warn ("Không đọc được " + $url + ": " + $_.Exception.Message) } } return $null } function Expand-VerifiedZip([string]$ZipPath, [string]$Destination) { Add-Type -AssemblyName System.IO.Compression.FileSystem $archive = [IO.Compression.ZipFile]::OpenRead($ZipPath) try { $rootPath = [IO.Path]::GetFullPath($Destination + [IO.Path]::DirectorySeparatorChar) foreach ($entry in $archive.Entries) { $target = [IO.Path]::GetFullPath((Join-Path $Destination $entry.FullName)) if (-not $target.StartsWith($rootPath, [StringComparison]::OrdinalIgnoreCase)) { throw "ZIP chứa đường dẫn không an toàn: $($entry.FullName)" } } } finally { $archive.Dispose() } [IO.Compression.ZipFile]::ExtractToDirectory($ZipPath, $Destination) } function Test-StudioServer { try { return Invoke-RestMethod -Uri "http://127.0.0.1:8799/api/health" -TimeoutSec 2 } catch { return $null } } Write-Host "============================================================" -ForegroundColor DarkCyan Write-Host " FoundryManager Studio - one-file installer / updater" -ForegroundColor White Write-Host "============================================================" -ForegroundColor DarkCyan if (Test-Administrator) { Warn "Đang chạy elevated. Tool vẫn chạy nhưng không cần quyền admin. Nếu UAC dùng một Windows account khác, Studio sẽ không thấy browser/Azure CLI session của user thường." } New-Item -ItemType Directory -Force -Path $Root, $DataDir, $ProfilesDir, $ReleasesDir | Out-Null $session = Join-Path $env:TEMP ("foundry-studio-" + [guid]::NewGuid().ToString("N")) New-Item -ItemType Directory -Path $session | Out-Null try { $manifest = Get-Manifest $version = $null $releaseDir = $null if ($manifest) { $version = [string]$manifest.version $releaseDir = Join-Path $ReleasesDir $version $releaseStamp = Join-Path $releaseDir ".release.sha256" $installedHash = if (Test-Path -LiteralPath $releaseStamp) { (Get-Content -LiteralPath $releaseStamp -Raw).Trim() } else { "" } if ($installedHash -ne ([string]$manifest.sha256).ToLowerInvariant()) { Step "Tải FoundryManager Studio $version" $zipPath = Join-Path $session "release.zip" $actualHash = ""; $downloadErrors = @() foreach ($releaseUrl in @([string]$manifest.zip_url) + @($manifest.mirrors)) { try { Invoke-WebRequest -UseBasicParsing -Uri $releaseUrl -OutFile $zipPath -TimeoutSec 300 $actualHash = (Get-FileHash -Algorithm SHA256 -LiteralPath $zipPath).Hash.ToLowerInvariant() if ($actualHash -ne ([string]$manifest.sha256).ToLowerInvariant()) { throw "SHA256 không khớp" } break } catch { $downloadErrors += ($releaseUrl + ": " + $_.Exception.Message); $actualHash = "" } } if (-not $actualHash) { throw ("Không tải được release đã xác minh. " + ($downloadErrors -join " | ")) } $stage = Join-Path $session "app" New-Item -ItemType Directory -Path $stage | Out-Null Expand-VerifiedZip $zipPath $stage foreach ($required in @("app.py", "arm.py", "foundry.py", "requirements.lock", "VERSION", "static\studio.html")) { if (-not (Test-Path -LiteralPath (Join-Path $stage $required) -PathType Leaf)) { throw "Release thiếu $required" } } if (Test-Path -LiteralPath $releaseDir) { $backup = $releaseDir + ".replaced-" + [DateTime]::UtcNow.ToString("yyyyMMddHHmmss") Move-Item -LiteralPath $releaseDir -Destination $backup } Move-Item -LiteralPath $stage -Destination $releaseDir Set-Content -LiteralPath $releaseStamp -Value $actualHash -Encoding ascii Good "Đã xác minh SHA256 và cài release $version" } else { Good "Release $version đã có và đúng checksum" } Set-Content -LiteralPath $CurrentFile -Value $version -Encoding ascii } elseif (Test-Path -LiteralPath $CurrentFile) { $version = (Get-Content -LiteralPath $CurrentFile -Raw).Trim() $releaseDir = Join-Path $ReleasesDir $version Warn "Không kết nối được Hugging Face; dùng bản đã cài $version." } else { throw "Không tải được manifest và máy chưa có bản Studio để chạy offline." } if (-not (Test-Path -LiteralPath (Join-Path $releaseDir "app.py") -PathType Leaf)) { throw "Release hiện tại bị thiếu app.py" } $python = Get-WorkingPython if (-not $python) { $python = Install-ManagedPython $session } Good ("Python: " + (& $python --version 2>&1)) $venvPython = Join-Path $VenvDir "Scripts\python.exe" $venvReady = $false if (Test-Path -LiteralPath $venvPython -PathType Leaf) { try { & $venvPython -c "import sys" 2>$null; $venvReady = ($LASTEXITCODE -eq 0) } catch {} } if (-not $venvReady) { if (Test-Path -LiteralPath $VenvDir) { $venvBackup = $VenvDir + ".replaced-" + [DateTime]::UtcNow.ToString("yyyyMMddHHmmss") Move-Item -LiteralPath $VenvDir -Destination $venvBackup } Step "Tạo môi trường Python riêng" & $python -m venv $VenvDir if ($LASTEXITCODE -ne 0) { throw "Không tạo được Python venv." } } $requirements = Join-Path $releaseDir "requirements.lock" $requirementsHash = (Get-FileHash -Algorithm SHA256 -LiteralPath $requirements).Hash.ToLowerInvariant() $oldRequirementsHash = if (Test-Path -LiteralPath $RequirementStamp) { (Get-Content -LiteralPath $RequirementStamp -Raw).Trim() } else { "" } $dependenciesReady = $false try { & $venvPython -c "import flask" 2>$null; $dependenciesReady = ($LASTEXITCODE -eq 0) } catch {} if ($oldRequirementsHash -ne $requirementsHash -or -not $dependenciesReady) { Step "Cài thư viện đã khóa phiên bản" & $venvPython -m pip install --disable-pip-version-check --quiet -r $requirements if ($LASTEXITCODE -ne 0) { throw "pip không cài được dependencies." } Set-Content -LiteralPath $RequirementStamp -Value $requirementsHash -Encoding ascii } & $venvPython -c "import flask" 2>$null if ($LASTEXITCODE -ne 0) { throw "Môi trường Flask chưa sẵn sàng." } if ($env:FM_INSTALL_ONLY -eq "1") { Good "Install-only hoàn tất; chưa khởi động local server." exit 0 } $server = Test-StudioServer if ($server) { Good ("Studio đang chạy (version " + $server.version + "); mở thêm tab mới.") if ([string]$server.version -ne $version) { Warn "Bản mới đã cài. Đóng cửa sổ Studio cũ rồi chạy BAT lại để kích hoạt." } Start-Process "http://127.0.0.1:8799/" exit 0 } $env:FM_PROFILES_DIR = $ProfilesDir $env:FM_HOST = "127.0.0.1" $env:FM_PORT = "8799" if (-not $env:FM_OPEN_BROWSER) { $env:FM_OPEN_BROWSER = "1" } Good "Profile được lưu riêng tại $ProfilesDir" Good "Mở Studio ở tab mới: http://127.0.0.1:8799/" Set-Location $releaseDir & $venvPython (Join-Path $releaseDir "app.py") exit $LASTEXITCODE } finally { if ($session -and (Test-Path -LiteralPath $session)) { $tempRoot = [IO.Path]::GetFullPath($env:TEMP + [IO.Path]::DirectorySeparatorChar) $sessionFull = [IO.Path]::GetFullPath($session) if ($sessionFull.StartsWith($tempRoot, [StringComparison]::OrdinalIgnoreCase) -and (Split-Path $sessionFull -Leaf) -like "foundry-studio-*") { Remove-Item -LiteralPath $sessionFull -Recurse -Force -ErrorAction SilentlyContinue } } }