# JJ Ollama Manager (Windows) — src/platform/windows/03_library_monitor.ps1 : fzf / Ollama 설치 확인 # jj_ollama_manager.ps1 가 순서대로 불러옵니다 (직접 실행하지 않음). 원래 jj_ollama_manager.ps1 936~1308줄 # 전체 목록 받기 → @{ Items; Offline } function Get-Library([string]$Sort, [switch]$Force) { if (-not (Test-Path $CacheDir)) { New-Item -ItemType Directory -Path $CacheDir -Force | Out-Null } $f = Join-Path $CacheDir "library_$Sort.xml" if (-not $Force -and (Test-CacheFresh $f)) { try { return [pscustomobject]@{ Items = @(Import-Clixml $f); Offline = $false } } catch { } } Write-C "${CYAN}ollama.com에서 모델 목록을 가져오는 중...${RESET}" try { $items = @(ConvertFrom-LibraryHtml (Get-WebText "${LibraryUrl}?sort=$Sort")) if ($items.Count -gt 0) { $items | Export-Clixml -Path $f return [pscustomobject]@{ Items = $items; Offline = $false } } } catch { } if (Test-Path $f) { Write-C "${YELLOW}인터넷 연결에 실패해 이전에 받아 둔 목록($(Get-CacheAgeText $f))을 사용합니다.${RESET}" Start-Sleep -Seconds 1 try { return [pscustomobject]@{ Items = @(Import-Clixml $f); Offline = $false } } catch { } } Write-C "${YELLOW}인터넷 연결에 실패해 ⭐추천 목록(오프라인)을 대신 보여 줍니다.${RESET}" Start-Sleep -Seconds 1 return [pscustomobject]@{ Items = (Get-OfflineLibrary); Offline = $true } } # 검색어로 ollama.com 검색 function Search-Online([string]$Query) { Write-C "${CYAN}ollama.com에서 '$Query'을(를) 검색하는 중...${RESET}" try { return @(ConvertFrom-LibraryHtml (Get-WebText "${LibraryUrl}?q=$([uri]::EscapeDataString($Query))&sort=popular")) } catch { return @() } } # 태그 목록 받기 function Get-Tags([string]$Name, [switch]$Force) { if (-not (Test-Path $CacheDir)) { New-Item -ItemType Directory -Path $CacheDir -Force | Out-Null } $safe = $Name -replace '[^A-Za-z0-9._-]', '_' $f = Join-Path $CacheDir "tags_$safe.xml" if (-not $Force -and (Test-CacheFresh $f)) { try { return @(Import-Clixml $f) } catch { } } Write-C "${CYAN}$Name 태그 목록을 가져오는 중...${RESET}" try { $tags = @(ConvertFrom-TagsHtml (Get-WebText "$LibraryUrl/$Name/tags") $Name) if ($tags.Count -gt 0) { $tags | Export-Clixml -Path $f return $tags } } catch { } if (Test-Path $f) { try { return @(Import-Clixml $f) } catch { } } # 오프라인: 추천 목록에서 같은 계열 태그 $out = foreach ($m in ($Models | Where-Object { ($_.Tag -split ':')[0] -eq $Name })) { [pscustomobject]@{ Tag = (Get-NormalTag $m.Tag); Size = "$($m.Size)GB"; Ctx = ''; Input = ''; Updated = '' } } return @($out) } # 기능 이름 한글 function Get-CapLabel([string]$Cap) { switch ($Cap) { 'tools' { return '도구 호출' } 'vision' { return '비전' } 'multimodal' { return '멀티모달' } 'thinking' { return '추론' } 'embedding' { return '임베딩' } 'cloud' { return '클라우드' } 'audio' { return '음성' } default { return $Cap } } } function Get-CapShort([string]$Cap) { switch ($Cap) { 'tools' { return '도구' } 'vision' { return '비전' } 'thinking' { return '추론' } 'embedding' { return '임베딩' } 'cloud' { return '클라우드' } 'audio' { return '음성' } default { return $Cap } } } # 기능별로 거르기: Select-ByCap <모델 목록> <기능> <검색어> # vision = 이미지 입력 O, 음성 입력 X # multimodal = 음성 입력 O (ollama.com 기준 현재 모두 이미지도 받음) function Select-ByCap($Items, [string]$Cap, [string]$Query) { $q = "$Query".ToLower() return @($Items | Where-Object { $caps = @($_.Caps) $ok = $true if ($Cap -eq 'multimodal') { $ok = ($caps -contains 'audio') } elseif ($Cap -eq 'vision') { $ok = (($caps -contains 'vision') -and -not ($caps -contains 'audio')) } elseif ($Cap) { $ok = ($caps -contains $Cap) } $ok -and (-not $q -or ("$($_.Name) $($_.Desc)".ToLower().Contains($q))) }) } # -------------------------------------------------- # fzf / Ollama 설치 확인 # -------------------------------------------------- function Initialize-Fzf { if (Test-Command 'fzf') { $script:UseFzf = $true; return } $script:UseFzf = $false Clear-Host Write-C "${YELLOW}방향키 메뉴에 필요한 fzf가 설치되어 있지 않습니다.${RESET}" if (-not (Test-Command 'winget')) { Write-C 'winget이 없어 자동으로 설치할 수 없습니다.' Write-C "https://github.com/junegunn/fzf/releases 에서 받거나, 앱 설치 관리자(winget)를 설치한 뒤 ${CYAN}winget install junegunn.fzf${RESET} 를 실행해 주세요." Write-C '지금은 번호 입력 방식으로 진행합니다.' Wait-Return return } $a = Read-Host 'winget으로 fzf를 설치할까요? (y/n)' if ($a -match '^(y|yes)$') { & winget install --id junegunn.fzf -e --accept-source-agreements --accept-package-agreements Update-PathFromRegistry if (Test-Command 'fzf') { $script:UseFzf = $true Write-C "${GREEN}✅ fzf 설치가 끝났습니다. 방향키 메뉴로 진행합니다.${RESET}" Start-Sleep -Seconds 1 } else { Write-C "${RED}❌ fzf를 찾지 못했습니다. PowerShell 창을 새로 열면 인식될 수 있습니다. 지금은 번호 입력 방식으로 진행합니다.${RESET}" Wait-Return } } else { Write-C "${YELLOW}번호 입력 방식으로 진행합니다.${RESET}" Start-Sleep -Seconds 1 } } function Initialize-Ollama { $script:OllamaExe = Find-OllamaExe if ($script:OllamaExe) { return $true } Clear-Host Write-C "${YELLOW}Ollama가 설치되어 있지 않습니다.${RESET}" if (-not (Test-Command 'winget')) { Write-C "winget이 없어 자동으로 설치할 수 없습니다. ${CYAN}https://ollama.com/download${RESET} 에서 설치해 주세요." return $false } if (-not (Confirm-Choice 'winget으로 Ollama를 설치할까요?')) { Write-C "${YELLOW}Ollama 없이는 실행할 수 없습니다. https://ollama.com/download 에서 설치해 주세요.${RESET}" return $false } & winget install --id Ollama.Ollama -e --accept-source-agreements --accept-package-agreements Update-PathFromRegistry $script:OllamaExe = Find-OllamaExe if ($script:OllamaExe) { Write-C "${GREEN}✅ Ollama 설치가 끝났습니다.${RESET}" Write-C "${GRAY}설치 직후 트레이 앱이 서버를 자동으로 띄웠을 수 있습니다. 메인 화면의 '기동' 표시로 확인하세요.${RESET}" Start-Sleep -Seconds 2 return $true } Write-C "${RED}❌ Ollama를 찾지 못했습니다. PowerShell 창을 새로 열고 다시 실행해 주세요.${RESET}" return $false } # -------------------------------------------------- # 모니터링 # -------------------------------------------------- # ollama.exe 프로세스 목록 (명령줄 포함) function Get-OllamaProcesses { return @(Get-CimInstance Win32_Process -Filter "Name='ollama.exe'" -ErrorAction SilentlyContinue) } # 다른 창에서 실행 중인 모델 대화·도구 연동 function Get-ActiveClients { return @(Get-OllamaProcesses | Where-Object { $_.CommandLine -match '\s(run|launch)(\s|$)' }) } # 서버 정보 (PID, 기동 주체, 주소, 시작 시각) function Get-ServerInfo { $info = [pscustomobject]@{ ProcId = $null; Owner = ''; Bind = ''; StartTime = $null } $ls = @(Get-NetTCPConnection -LocalPort $ApiPort -State Listen -ErrorAction SilentlyContinue) if ($ls.Count -eq 0) { return $info } $info.ProcId = [int]$ls[0].OwningProcess $info.Bind = (@($ls | ForEach-Object { "$($_.LocalAddress):$($_.LocalPort)" }) | Sort-Object -Unique) -join ' ' $p = Get-Process -Id $info.ProcId -ErrorAction SilentlyContinue if ($p) { try { $info.StartTime = $p.StartTime } catch { } } $saved = Get-Content $PidFile -ErrorAction SilentlyContinue | Select-Object -First 1 if ($saved -and ([int]$saved -eq $info.ProcId)) { $info.Owner = '스크립트' } else { $cim = Get-CimInstance Win32_Process -Filter "ProcessId=$($info.ProcId)" -ErrorAction SilentlyContinue $parent = $null if ($cim) { $parent = Get-Process -Id $cim.ParentProcessId -ErrorAction SilentlyContinue } if ($parent -and $parent.ProcessName -match '^ollama app') { $info.Owner = 'Ollama 트레이 앱' } else { $info.Owner = '외부 실행(터미널 등)' } } return $info } # 실행 중인 서버의 컨텍스트 길이 (이 스크립트로 켠 서버가 아니면 $null) function Get-ServerCtx { if (-not (Test-Server)) { return $null } if (-not (Test-Path $PidFile) -or -not (Test-Path $CtxFile)) { return $null } $savedPid = Get-Content $PidFile -ErrorAction SilentlyContinue | Select-Object -First 1 if (-not $savedPid -or -not (Get-Process -Id ([int]$savedPid) -ErrorAction SilentlyContinue)) { return $null } $v = Get-Content $CtxFile -ErrorAction SilentlyContinue | Select-Object -First 1 $n = 0 if ([int]::TryParse([string]$v, [ref]$n)) { return $n } return $null } # 현재 서버 로그 파일 function Get-CurrentLogFile { $si = Get-ServerInfo if ($si.Owner -eq 'Ollama 트레이 앱' -and (Test-Path $AppLogFile)) { return $AppLogFile } if (Test-Path $LogFile) { return $LogFile } if (Test-Path $AppLogFile) { return $AppLogFile } return $LogFile } # 다른 프로세스가 쓰고 있는 로그 파일의 끝부분 읽기 function Read-LogTail([string]$Path, [int]$Bytes = 65536) { if (-not (Test-Path $Path)) { return @() } $fs = $null try { $fs = [IO.File]::Open($Path, 'Open', 'Read', 'ReadWrite') $start = [math]::Max(0, $fs.Length - $Bytes) [void]$fs.Seek($start, 'Begin') $buf = New-Object byte[] ($fs.Length - $start) [void]$fs.Read($buf, 0, $buf.Length) return @(([Text.Encoding]::UTF8.GetString($buf)) -split "`r?`n") } catch { return @() } finally { if ($fs) { $fs.Close() } } } function Format-Uptime([TimeSpan]$Span) { $s = '' if ($Span.Days -gt 0) { $s += "$($Span.Days)일 " } if ($Span.Hours -gt 0 -or $Span.Days -gt 0) { $s += "$($Span.Hours)시간 " } return "$s$($Span.Minutes)분" } # CPU 사용률(%) function Get-CpuPercent { $c = Get-CimInstance Win32_PerfFormattedData_PerfOS_Processor -Filter "Name='_Total'" -ErrorAction SilentlyContinue if ($c) { return [int]$c.PercentProcessorTime } $l = @(Get-CimInstance Win32_Processor -ErrorAction SilentlyContinue | Measure-Object -Property LoadPercentage -Average) if ($l) { return [int]$l[0].Average } return $null } # 램 사용량 function Get-RamInfo { $os = Get-CimInstance Win32_OperatingSystem -ErrorAction SilentlyContinue if (-not $os) { return $null } $total = [double]$os.TotalVisibleMemorySize / 1MB $used = $total - ([double]$os.FreePhysicalMemory / 1MB) return [pscustomobject]@{ UsedGB = [math]::Round($used, 1); TotalGB = [math]::Round($total, 0); Pct = [int]($used * 100 / $total) } } # 그래픽 카드 사용량 (NVIDIA는 nvidia-smi, 그 외는 작업 관리자와 같은 성능 카운터) function Get-GpuUsage { $res = @() $hasNvidia = $false if (Test-Command 'nvidia-smi') { $out = & nvidia-smi --query-gpu=name,utilization.gpu,memory.used,memory.total,temperature.gpu --format=csv,noheader,nounits 2>$null if ($LASTEXITCODE -eq 0 -and $out) { foreach ($l in @($out)) { $p = $l -split ',' if ($p.Count -ge 4) { $hasNvidia = $true $temp = '' if ($p.Count -ge 5) { $temp = $p[4].Trim() } $res += [pscustomobject]@{ Name = $p[0].Trim(); Util = $p[1].Trim() UsedGB = [math]::Round([double]$p[2].Trim() / 1024, 1) TotalGB = [math]::Round([double]$p[3].Trim() / 1024, 1); Temp = $temp } } } } } if ($hasNvidia) { return $res } $eng = @(Get-CimInstance Win32_PerfFormattedData_GPUPerformanceCounters_GPUEngine -ErrorAction SilentlyContinue) if ($eng.Count -eq 0) { return $res } $mem = @(Get-CimInstance Win32_PerfFormattedData_GPUPerformanceCounters_GPUAdapterMemory -ErrorAction SilentlyContinue) $byAdapter = @{} foreach ($e in $eng) { if ($e.Name -match 'luid_(0x[0-9a-fA-F]+_0x[0-9a-fA-F]+)_phys_(\d+).*engtype_(\w+)') { $k = "$($matches[1])_$($matches[2])" $t = $matches[3] if (-not $byAdapter.ContainsKey($k)) { $byAdapter[$k] = @{} } $byAdapter[$k][$t] = [double]$byAdapter[$k][$t] + [double]$e.UtilizationPercentage } } $memBy = @{} foreach ($m in $mem) { if ($m.Name -match 'luid_(0x[0-9a-fA-F]+_0x[0-9a-fA-F]+)_phys_(\d+)') { $memBy["$($matches[1])_$($matches[2])"] = [double]$m.DedicatedUsage } } $adapters = @(foreach ($k in $byAdapter.Keys) { $u = ($byAdapter[$k].Values | Measure-Object -Maximum).Maximum if ($u -gt 100) { $u = 100 } [pscustomobject]@{ Util = [int]$u; Ded = [double]$memBy[$k] } }) # 실제 그래픽 카드(전용 메모리를 쓰거나 사용 중인 어댑터)만 $adapters = @($adapters | Where-Object { $_.Ded -gt 0 -or $_.Util -gt 0 } | Sort-Object Ded -Descending) $hwGpus = @($script:HW.Gpus) for ($i = 0; $i -lt $adapters.Count; $i++) { $name = "그래픽 카드 $($i + 1)" $total = 0 if ($hwGpus.Count -eq 1 -and $i -eq 0) { $name = $hwGpus[0].Name; $total = $hwGpus[0].VramGB } $res += [pscustomobject]@{ Name = $name; Util = $adapters[$i].Util UsedGB = [math]::Round($adapters[$i].Ded / 1GB, 1); TotalGB = $total; Temp = '' } } return $res } # 메모리에 올라간 모델 function Get-LoadedModels { try { $ps = Invoke-RestMethod -Uri "$ApiUrl/api/ps" -TimeoutSec 3 -ErrorAction Stop } catch { return @() } $out = foreach ($m in @($ps.models)) { if (-not $m) { continue } $size = [double]$m.size $vram = [double]$m.size_vram $gpu = 0 if ($size -gt 0) { $gpu = [int][math]::Round($vram * 100 / $size) } $remain = '' $exp = $m.expires_at if ($exp) { try { if ($exp -is [datetime]) { $dto = [datetimeoffset]$exp } else { $dto = [datetimeoffset]::Parse(([string]$exp -replace '(\.\d{7})\d+', '$1'), [Globalization.CultureInfo]::InvariantCulture) } $diff = ($dto - [datetimeoffset]::Now).TotalMinutes if ($diff -gt 525600) { $remain = 'inf' } elseif ($diff -gt 0) { $remain = [int]$diff } else { $remain = 0 } } catch { } } [pscustomobject]@{ Name = [string]$m.name; SizeGB = [math]::Round($size / 1GB, 1); Gpu = $gpu; Remain = $remain; Ctx = [string]$m.context_length } } return @($out) } # 이 모델이 메모리에 올라가 있으면 그 정보를 돌려줌 # (원본과 한국어 전용 -ko 모델은 같은 파일이므로 어느 이름으로 올라가 있어도 적재된 것으로 봄) function Find-LoadedModel([string]$Tag, [object[]]$Loaded) { if (-not $Tag) { return $null } $base = Get-FullTag $Tag if (Test-KoVariant $base) { $base = $base.Substring(0, $base.Length - $KoSuffix.Length) } $names = @($base, "$base$KoSuffix") return (@($Loaded) | Where-Object { $_ -and ($names -contains (Get-FullTag $_.Name)) } | Select-Object -First 1) } # 적재 정보 표시 문구: [메모리 적재 18.2GB · CPU 100% · 4분 후 내림] function Format-LoadedTag($lm) { if (-not $lm) { return '' } if ($lm.Gpu -ge 100) { $where = 'GPU 100%' } elseif ($lm.Gpu -le 0) { $where = 'CPU 100%' } else { $where = "CPU $(100 - $lm.Gpu)%/GPU $($lm.Gpu)%" } $remain = '' if ($lm.Remain -eq 'inf') { $remain = ' · 계속 유지' } elseif ("$($lm.Remain)" -eq '0') { $remain = ' · 곧 내림' } elseif ("$($lm.Remain)" -ne '') { $remain = " · $($lm.Remain)분 후 내림" } return "${GREEN}[메모리 적재 $($lm.SizeGB)GB · $where$remain]${RESET}" }