diff --git a/tools/win-ci/gvr.ps1 b/tools/win-ci/gvr.ps1 new file mode 100644 index 0000000..08c42ef --- /dev/null +++ b/tools/win-ci/gvr.ps1 @@ -0,0 +1,150 @@ + +# ================================================================== +# 겜녹이 (game_voice_recorder) Windows 검증 · 빌드 +# $TargetRev : 검증할 커밋 (run.sh 가 박는다) +# $Phase : worker = 워커 테스트 + OCR + PyInstaller / full = + Electron 포터블 exe 빌드 · 기동 확인 +# 결과는 호스트 /home/claude/win-ci/results/gvr-* 로 회수된다. +# 이 블록은 실패해도 exit 0 (agent 가 무한 재시도하지 않게) - 판정은 summary 로 한다. +# ================================================================== +$TargetRev = '__REV__' +$Phase = '__PHASE__' +$Repo = 'C:\win-ci\gvr' +$OutDir = 'C:\win-ci\gvr-out' +New-Item -ItemType Directory -Force -Path $OutDir | Out-Null + +function Send-Artifact($name, $path) { + if (-not (Test-Path $path)) { return } + try { + $bytes = [IO.File]::ReadAllBytes($path) + $req = @{ Uri = "http://10.0.2.2:8099/artifact/$name"; Method = 'Post'; TimeoutSec = 3600; Body = $bytes; ContentType = 'application/octet-stream' } + Invoke-RestMethod @req | Out-Null + Log " -> 호스트로 $name ($($bytes.Length) bytes)" + } catch { + Log " -> $name 업로드 실패: $($_.Exception.Message)" + } +} + +function Step($name, $block) { + $log = Join-Path $OutDir "$name.log" + Remove-Item $log -Force -ErrorAction SilentlyContinue + Log "--- [$name] 시작" + $sw = [IO.StreamWriter]::new($log, $false, [Text.UTF8Encoding]::new($false)) + $sw.AutoFlush = $true + $tail = [System.Collections.Generic.Queue[string]]::new() + $ok = $true + $t0 = Get-Date + try { + & $block 2>&1 | ForEach-Object { + $line = "$_" + $sw.WriteLine($line) + $tail.Enqueue($line) + if ($tail.Count -gt 15) { [void]$tail.Dequeue() } + } + } catch { + $ok = $false + $sw.WriteLine("[step 예외] $($_.Exception.Message)") + } + $sw.WriteLine("[소요] $([int]((Get-Date) - $t0).TotalSeconds)s") + $sw.Close() + foreach ($l in $tail) { Log " $l" } + if ($ok) { Log "--- [$name] 통과" } else { Log "--- [$name] 실패" } + Send-Artifact "gvr-$name.log" $log + return $ok +} + +$ErrorActionPreference = 'Continue' +$env:PYTHONUTF8 = '1' +$env:PYTHONIOENCODING = 'utf-8' +$r = [ordered]@{} +try { + Sync-Path + if (-not (Test-Path $Repo)) { + Log "gvr clone" + & git clone -q https://git.tkrmagid.kr/tkrmagid/game_voice_recorder $Repo + } + Push-Location $Repo + & git fetch --all -q + & git reset --hard $TargetRev -q + & git clean -fdq -e node_modules -e .venv -e worker/dist -e worker/build + Log "gvr rev $(& git rev-parse --short HEAD)" + + $py = Join-Path $Repo 'worker\.venv\Scripts\python.exe' + $r['worker_setup'] = Step 'worker_setup' { + Push-Location (Join-Path $Repo 'worker') + if (-not (Test-Path $py)) { & python -m venv .venv } + & $py -m pip install --upgrade pip -q + & $py -m pip install -r requirements.txt -r requirements-dev.txt -q + if ($LASTEXITCODE -ne 0) { Pop-Location; throw "pip exit $LASTEXITCODE" } + & $py -c "import faster_whisper, ctranslate2, winrt.windows.media.ocr as o; print('faster-whisper', faster_whisper.__version__, 'ct2', ctranslate2.__version__)" + Pop-Location + } + # 한국어 OCR 언어 기능 (롤 채팅 OCR 에 필요. 게임 PC 에서는 첫 실행 마법사가 안내) + $r['ocr_lang'] = Step 'ocr_lang' { + $cap = Get-WindowsCapability -Online -Name 'Language.OCR~~~ko-KR~0.0.1.0' + "상태: $($cap.State)" + if ($cap.State -ne 'Installed') { Add-WindowsCapability -Online -Name 'Language.OCR~~~ko-KR~0.0.1.0' | Out-String } + (Get-WindowsCapability -Online -Name 'Language.OCR~~~ko-KR~0.0.1.0').State + } + $r['worker_pytest'] = Step 'worker_pytest' { + Push-Location (Join-Path $Repo 'worker') + & $py -m pytest -q -rf + $c = $LASTEXITCODE + Pop-Location + if ($c -ne 0) { throw "pytest exit $c" } + } + $r['win_smoke'] = Step 'win_smoke' { + & $py worker\scripts\win_smoke.py --out (Join-Path $OutDir 'win_smoke.json') + if ($LASTEXITCODE -ne 0) { throw "smoke exit $LASTEXITCODE" } + } + Send-Artifact 'gvr-win_smoke.json' (Join-Path $OutDir 'win_smoke.json') + $r['worker_build'] = Step 'worker_build' { + Push-Location (Join-Path $Repo 'worker') + & $py -m PyInstaller gvr-worker.spec --noconfirm --clean + $c = $LASTEXITCODE + Pop-Location + if ($c -ne 0) { throw "PyInstaller exit $c" } + "크기 $([math]::Round((Get-ChildItem worker\dist\gvr-worker -Recurse | Measure-Object Length -Sum).Sum / 1MB, 1)) MB" + } + $r['worker_exe_smoke'] = Step 'worker_exe_smoke' { + & $py worker\scripts\win_smoke.py --exe worker\dist\gvr-worker\gvr-worker.exe --out (Join-Path $OutDir 'win_smoke_exe.json') + if ($LASTEXITCODE -ne 0) { throw "exe smoke exit $LASTEXITCODE" } + } + + if ($Phase -eq 'full') { + $r['app_build'] = Step 'app_build' { + Push-Location (Join-Path $Repo 'app') + & npm ci --no-audit --no-fund + if ($LASTEXITCODE -ne 0) { Pop-Location; throw "npm ci exit $LASTEXITCODE" } + & npm run dist:win + $c = $LASTEXITCODE + Pop-Location + if ($c -ne 0) { throw "electron-builder exit $c" } + Get-ChildItem app\release -File | ForEach-Object { "$($_.Name) $([math]::Round($_.Length / 1MB, 1)) MB" } + } + $r['app_smoke'] = Step 'app_smoke' { + $exe = Get-ChildItem app\release\win-unpacked\GameVoiceRecorder.exe + $data = Join-Path $OutDir 'smoke-data' + Remove-Item $data -Recurse -Force -ErrorAction SilentlyContinue + $p = Start-Process $exe.FullName -ArgumentList '--smoke', "--data-dir=$data" -PassThru -Wait + Get-Content (Join-Path $data 'smoke.json') -ErrorAction SilentlyContinue + if ($p.ExitCode -ne 0) { throw "app smoke exit $($p.ExitCode)" } + } + if ($r['app_build'] -and $r['app_smoke']) { + foreach ($f in Get-ChildItem app\release -File -Include *.exe, *.zip) { Send-Artifact $f.Name $f.FullName } + } + } + + $rev = (& git rev-parse --short HEAD 2>&1 | Select-Object -First 1) + $sum = Join-Path $OutDir 'summary.log' + $lines = @("rev=$rev", "phase=$Phase", "utc=$([DateTime]::UtcNow.ToString('yyyy-MM-dd HH:mm:ss'))") + foreach ($k in $r.Keys) { $lines += ("{0,-18} {1}" -f $k, $(if ($r[$k]) { 'PASS' } else { 'FAIL' })) } + Set-Content -Path $sum -Value $lines -Encoding UTF8 + foreach ($l in $lines) { Log $l } + Send-Artifact 'gvr-summary.log' $sum + Pop-Location +} catch { + Log "gvr 검증 준비 실패: $($_.Exception.Message)" + try { Pop-Location } catch {} +} +Log "=== gvr 끝 ===" +exit 0 diff --git a/tools/win-ci/preamble.ps1 b/tools/win-ci/preamble.ps1 new file mode 100644 index 0000000..25bb565 --- /dev/null +++ b/tools/win-ci/preamble.ps1 @@ -0,0 +1,244 @@ +# win-ci VM 설치 스크립트 (호스트가 HTTP 로 내려준다 - agent.ps1 이 실행) +# +# 이 파일은 호스트의 /home/claude/win-ci/serve/stage2.ps1 이다. 고치면 게스트가 +# 20초 안에 알아서 새로 받아 실행한다. Windows 재설치 필요 없다. +# +# 규칙: 반드시 idempotent. 이미 깔린 건 건너뛴다. 중간에 죽어도 다시 돌 수 있다. +# +# LTSC 2024 에는 winget(스토어)이 없다. 그래서 설치 파일을 직접 받는다. + +$ErrorActionPreference = 'Stop' +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 + +# 자식 프로세스 stdout 을 UTF-8 로 해독한다. +# +# 이게 없으면 PowerShell 이 자식의 출력을 콘솔 코드페이지(LTSC en-US = 437)로 +# 읽는다. python 쪽은 PYTHONUTF8=1 로 UTF-8 을 내보내므로 한글이 전부 깨져서 +# 호스트로 회수한 증거 파일의 실패 메시지를 읽을 수 없다. 여기서 바꾸는 건 +# '해독' 쪽이라 파일 저장 인코딩(StreamWriter 는 UTF-8 고정)과는 무관하다. +try { [Console]::OutputEncoding = [Text.UTF8Encoding]::new($false) } catch { } + +$Dl = 'C:\win-ci\dl' +New-Item -ItemType Directory -Force -Path $Dl | Out-Null + +# Write-Output 를 쓰면 안 된다. 함수 안에서 부르면 그 함수의 반환값에 +# 로그 문자열이 섞여 들어가 $f 가 배열이 되고, Start-Process 가 +# "Cannot convert System.Object[] to System.String" 으로 죽는다. +# 실제로 이것 때문에 Git 설치가 실패했다. +function Log($m) { Write-Host "$m" } + +function Get-File($url, $name) { + $out = Join-Path $Dl $name + if ((Test-Path $out) -and (Get-Item $out).Length -gt 1mb) { Log "캐시 사용 $name"; return $out } + for ($i = 1; $i -le 3; $i++) { + try { + Log "다운로드 ($i/3) $name" + Invoke-WebRequest -Uri $url -OutFile $out -UseBasicParsing -TimeoutSec 600 + return $out + } catch { + Log "실패: $($_.Exception.Message)" + if ($i -eq 3) { throw } + Start-Sleep -Seconds 10 + } + } +} + +function Sync-Path { + $m = [Environment]::GetEnvironmentVariable('Path', 'Machine') + $u = [Environment]::GetEnvironmentVariable('Path', 'User') + $env:Path = "$m;$u" +} + +function Have($exe) { Sync-Path; return [bool](Get-Command $exe -ErrorAction SilentlyContinue) } + +# ------------------------------------------------------------------ Git +# actions/checkout@v4 가 git 을 쓴다. 없으면 소스를 못 받는다. +if (Have 'git') { + Log "git 이미 있음: $(git --version)" +} else { + $f = Get-File 'https://github.com/git-for-windows/git/releases/download/v2.55.0.windows.5/Git-2.55.0.5-64-bit.exe' 'git.exe' + Log "Git 설치 중" + Start-Process $f -ArgumentList '/VERYSILENT', '/NORESTART', '/NOCANCEL', '/SP-' -Wait + if (-not (Have 'git')) { throw 'git 설치 실패' } + Log "git 설치 완료: $(git --version)" +} + +# ------------------------------------------------------------------ pwsh 7 +# 워크플로가 shell: pwsh 를 쓴다. Windows 기본은 5.1 이라 별도로 필요하다. +if (Have 'pwsh') { + Log "pwsh 이미 있음: $(pwsh --version)" +} else { + $f = Get-File 'https://github.com/PowerShell/PowerShell/releases/download/v7.4.6/PowerShell-7.4.6-win-x64.msi' 'pwsh.msi' + Log "PowerShell 7 설치 중" + Start-Process 'msiexec.exe' -ArgumentList '/i', "`"$f`"", '/qn', '/norestart', 'ADD_PATH=1' -Wait + if (-not (Have 'pwsh')) { throw 'pwsh 설치 실패' } + Log "pwsh 설치 완료: $(pwsh --version)" +} + +# ------------------------------------------------------------------ Python 3.12 +if (Have 'python') { + Log "python 이미 있음: $(python --version 2>&1)" +} else { + $f = Get-File 'https://www.python.org/ftp/python/3.12.10/python-3.12.10-amd64.exe' 'python.exe' + Log "Python 3.12 설치 중" + Start-Process $f -ArgumentList '/quiet', 'InstallAllUsers=1', 'PrependPath=1', ` + 'Include_test=0', 'Include_launcher=1', 'AssociateFiles=0' -Wait + if (-not (Have 'python')) { throw 'python 설치 실패' } + Log "python 설치 완료: $(python --version 2>&1)" +} + +# ------------------------------------------------------------------ Node +# act_runner 의 host 모드는 JS 액션(checkout, upload-artifact)을 돌리려고 +# PATH 의 node 를 쓴다. 없으면 그 단계들이 전부 실패한다. +if (Have 'node') { + Log "node 이미 있음: $(node --version)" +} else { + $f = Get-File 'https://nodejs.org/dist/v22.20.0/node-v22.20.0-x64.msi' 'node.msi' + Log "Node.js 설치 중" + Start-Process 'msiexec.exe' -ArgumentList '/i', "`"$f`"", '/qn', '/norestart' -Wait + if (-not (Have 'node')) { throw 'node 설치 실패' } + Log "node 설치 완료: $(node --version)" +} + +# ------------------------------------------------------------------ CMake +# native\process_loopback 빌드용. 워크플로에서 continue-on-error 지만 있으면 검증된다. +if (Have 'cmake') { + Log "cmake 이미 있음: $(cmake --version | Select-Object -First 1)" +} else { + $f = Get-File 'https://github.com/Kitware/CMake/releases/download/v3.31.6/cmake-3.31.6-windows-x86_64.msi' 'cmake.msi' + Log "CMake 설치 중" + Start-Process 'msiexec.exe' -ArgumentList '/i', "`"$f`"", '/qn', '/norestart', 'ADD_CMAKE_TO_PATH=System' -Wait + Sync-Path + if (Have 'cmake') { Log "cmake 설치 완료: $(cmake --version | Select-Object -First 1)" } + else { Log "WARN cmake 설치 실패 - 워크플로의 native 빌드 단계는 건너뛰어진다" } +} + +# ------------------------------------------------------ VS 2022 Build Tools (C++) +# livesub_capture.exe (native\process_loopback) 는 WASAPI 프로세스 루프백을 쓴다. +# 그 헤더(audioclientactivationparams.h)와 WRL 은 Windows SDK + MSVC 에만 있다. +# cmake 만 깔면 "generator 는 있는데 컴파일러가 없다"로 configure 에서 죽는다. +# +# 왜 빠뜨리면 안 되나: 이 exe 가 없으면 포터블 빌드가 그대로 성공하되 +# 프로그램별 캡처가 장치 전체 캡처로 조용히 폴백된다. 즉 "게임 소리만 받는다"는 +# 핵심 기능이 빠진 채로 exe 가 나온다. 실제로 그 상태의 exe 가 한 번 나왔다. +$VsWhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe' +function Get-MsvcRoot { + if (-not (Test-Path $VsWhere)) { return $null } + $p = & $VsWhere -latest -products * ` + -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 ` + -property installationPath 2>$null + if ($p) { return ($p | Select-Object -First 1) } + return $null +} +$msvc = Get-MsvcRoot +if ($msvc) { + Log "MSVC 이미 있음: $msvc" +} else { + $f = Get-File 'https://aka.ms/vs/17/release/vs_BuildTools.exe' 'vs_BuildTools.exe' + Log "VS 2022 Build Tools 설치 중 (C++ 워크로드, 수 GB - 20분 이상 걸린다)" + # --wait 없이 Start-Process -Wait 만 쓰면 부트스트래퍼가 먼저 반환해 버려 + # 설치가 끝나기 전에 다음 단계로 넘어간다. 둘 다 있어야 한다. + $p = Start-Process $f -Wait -PassThru -ArgumentList ` + '--quiet', '--wait', '--norestart', '--nocache', ` + '--add', 'Microsoft.VisualStudio.Workload.VCTools', '--includeRecommended' + # 3010 = 설치는 됐고 재부팅만 권고. 실패가 아니다. + Log "Build Tools 설치기 종료코드 $($p.ExitCode)" + $msvc = Get-MsvcRoot + if ($msvc) { Log "MSVC 설치 완료: $msvc" } + else { Log "WARN MSVC 설치 실패 - livesub_capture.exe 를 빌드할 수 없다" } +} + +# ------------------------------------------------------------------ act_runner +$RunnerDir = 'C:\gitea-runner' +$RunnerExe = Join-Path $RunnerDir 'act_runner.exe' +New-Item -ItemType Directory -Force -Path $RunnerDir | Out-Null +if (Test-Path $RunnerExe) { + Log "act_runner 이미 있음" +} else { + Log "act_runner 다운로드" + Invoke-WebRequest -Uri 'https://dl.gitea.com/act_runner/0.2.13/act_runner-0.2.13-windows-amd64.exe' ` + -OutFile $RunnerExe -UseBasicParsing -TimeoutSec 300 + Log "act_runner 받음: $((Get-Item $RunnerExe).Length) bytes" +} + +# GPU 러너와 달리 이건 CPU 러너지만, 같은 원칙으로 capacity 1 로 고정한다. +# 이 VM 은 vCPU 4개뿐이라 두 작업이 동시에 돌면 둘 다 느려지고 타임아웃 위험이 생긴다. +$cfg = Join-Path $RunnerDir 'config.yaml' +if (-not (Test-Path $cfg)) { + @' +log: + level: info +runner: + capacity: 1 + timeout: 60m + shutdown_timeout: 3m + insecure: false + fetch_timeout: 5s + fetch_interval: 2s +container: + network: "" + privileged: false + force_pull: false +host: + workdir_parent: C:\gitea-runner\work +'@ | Set-Content -Path $cfg -Encoding ASCII + Log "config.yaml 생성 (capacity 1)" +} + +# ------------------------------------------- 러너 등록 (토큰이 호스트에 있을 때만) +# 호스트의 serve/runner-token.txt 에 등록 토큰을 넣어주면 여기서 등록한다. +# 없으면 이 단계만 건너뛰고 나머지는 전부 완료로 본다. +$registered = Test-Path (Join-Path $RunnerDir '.runner') +if ($registered) { + Log "러너 이미 등록됨" +} else { + $tok = $null + try { + $tok = (Invoke-WebRequest -Uri 'http://10.0.2.2:8099/runner-token.txt' -UseBasicParsing -TimeoutSec 10).Content + if ($tok -is [byte[]]) { $tok = [Text.Encoding]::ASCII.GetString($tok) } + $tok = $tok.Trim() + } catch { $tok = $null } + + if ([string]::IsNullOrWhiteSpace($tok)) { + Log "등록 토큰 없음 (serve/runner-token.txt) - 러너 등록은 건너뜀. 사전 설치는 전부 끝났다." + } else { + Log "러너 등록 시도 (토큰 길이 $($tok.Length))" + Push-Location $RunnerDir + $out = & $RunnerExe register --no-interactive ` + --instance 'https://git.tkrmagid.kr' ` + --token $tok ` + --name 'win-ci' ` + --labels 'windows:host' 2>&1 | Out-String + Pop-Location + Log "register -> $($out.Trim())" + if (-not (Test-Path (Join-Path $RunnerDir '.runner'))) { throw "러너 등록 실패" } + + # 서비스로 만들지 않는다. SYSTEM 권한이 되고, 데스크톱 세션이 없어 + # GUI 테스트/스크린샷이 전부 실패한다. 로그온 예약 작업이어야 한다. + & schtasks.exe /Create /TN 'gitea-runner' /SC ONLOGON /RL HIGHEST /F ` + /TR "cmd.exe /c cd /d C:\gitea-runner && act_runner.exe daemon --config config.yaml" | Out-Null + & schtasks.exe /Run /TN 'gitea-runner' | Out-Null + Log "러너 등록 + 로그온 작업 등록 완료, daemon 시작" + } +} + +# ------------------------------------------------------------------ 요약 +Sync-Path +Log "=== 설치 요약 ===" +foreach ($c in 'git', 'pwsh', 'python', 'node', 'cmake') { + $v = try { (& $c --version 2>&1 | Select-Object -First 1) } catch { '없음' } + Log ("{0,-8} {1}" -f $c, $v) +} +Log "act_runner $(if (Test-Path $RunnerExe) { 'OK' } else { '없음' }) 등록=$(Test-Path (Join-Path $RunnerDir '.runner'))" + +# 모니터 2개가 실제로 잡혔는지 - virtio-gpu 드라이버가 들어갔는지 확인하는 지표다. +try { + Add-Type -AssemblyName System.Windows.Forms -ErrorAction Stop + $screens = [System.Windows.Forms.Screen]::AllScreens + Log "화면 $($screens.Count)개: $(($screens | ForEach-Object { $_.Bounds.Width.ToString() + 'x' + $_.Bounds.Height }) -join ', ')" + $gpu = Get-CimInstance Win32_VideoController | ForEach-Object { $_.Name } + Log "비디오 어댑터: $($gpu -join ', ')" +} catch { + Log "화면 열거 실패: $($_.Exception.Message)" +} +Log "=== stage2 완료 ===" diff --git a/tools/win-ci/restore.sh b/tools/win-ci/restore.sh new file mode 100755 index 0000000..8878625 --- /dev/null +++ b/tools/win-ci/restore.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +# 공용 win-ci VM 의 stage2.ps1 을 겜녹이 작업 전 상태로 되돌린다 +D=/home/claude/win-ci +[ -f $D/serve/stage2.ps1.bak-gvr ] && mv $D/serve/stage2.ps1.bak-gvr $D/serve/stage2.ps1 && echo "복원 완료" diff --git a/tools/win-ci/run.sh b/tools/win-ci/run.sh new file mode 100755 index 0000000..483edf9 --- /dev/null +++ b/tools/win-ci/run.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +# win-ci VM 에서 겜녹이 검증·빌드를 돌린다. tools/win-ci/run.sh [rev] +# - 공용 VM 이다. 기존 stage2.ps1 은 serve/stage2.ps1.bak-gvr 로 보관하고, 끝나면 restore.sh 로 되돌린다. +# - 결과: /home/claude/win-ci/results/gvr-summary.log, gvr-*.log, 산출물(exe/zip) +set -euo pipefail +PHASE=${1:-worker} +REV=${2:-$(git -C "$(dirname "$0")" rev-parse --short HEAD)} +D=/home/claude/win-ci +HERE="$(cd "$(dirname "$0")" && pwd)" +[ -f $D/serve/stage2.ps1.bak-gvr ] || cp $D/serve/stage2.ps1 $D/serve/stage2.ps1.bak-gvr +rm -f $D/results/gvr-summary.log +{ cat "$HERE/preamble.ps1"; sed "s/__REV__/$REV/; s/__PHASE__/$PHASE/" "$HERE/gvr.ps1"; } > $D/serve/stage2.ps1.new +mv $D/serve/stage2.ps1.new $D/serve/stage2.ps1 +echo "stage2 배포: phase=$PHASE rev=$REV (게스트가 20초 안에 받아간다)" diff --git a/worker/scripts/win_smoke.py b/worker/scripts/win_smoke.py new file mode 100644 index 0000000..6f0cd01 --- /dev/null +++ b/worker/scripts/win_smoke.py @@ -0,0 +1,92 @@ +"""Windows 실기 확인 (win-ci VM / 게임 PC): 워커를 프로토콜로 띄워 hello · gpu_info · OCR · r3dlog · STT(tiny) 를 돌린다. + + python scripts/win_smoke.py [--exe dist/gvr-worker/gvr-worker.exe] [--out result.json] + +종료 코드 0 = OCR 이 예시 3줄 중 2줄 이상 읽고 STT 가 한국어를 냈다. +""" +from __future__ import annotations + +import argparse +import json +import os +import subprocess +import sys +import tempfile +import threading +import time +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +SAMPLE_PNG = ROOT / "app" / "resources" / "diag" / "lol-chat-sample.png" +SAMPLE_OGG = ROOT / "app" / "resources" / "diag" / "speech_ko.ogg" + + +class Worker: + def __init__(self, cmd: list[str], env: dict[str, str]) -> None: + self.p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + env=env, cwd=str(ROOT / "worker"), text=True, encoding="utf-8", bufsize=1) + self.seq = 0 + self.err: list[str] = [] + threading.Thread(target=self._drain, daemon=True).start() + + def _drain(self) -> None: + assert self.p.stderr + for line in self.p.stderr: + self.err.append(line.rstrip()) + + def req(self, op: str, timeout: float = 600, **kw): + self.seq += 1 + rid = str(self.seq) + assert self.p.stdin and self.p.stdout + self.p.stdin.write(json.dumps({"id": rid, "op": op, **kw}, ensure_ascii=False) + "\n") + self.p.stdin.flush() + t0 = time.time() + while time.time() - t0 < timeout: + line = self.p.stdout.readline() + if not line: + raise RuntimeError("worker exited: " + "\n".join(self.err[-20:])) + msg = json.loads(line) + if msg.get("id") == rid and "event" not in msg: + return msg + raise TimeoutError(op) + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--exe") + ap.add_argument("--out", default="win_smoke.json") + a = ap.parse_args() + data = Path(tempfile.mkdtemp(prefix="gvr-smoke-")) + env = {**os.environ, "GVR_DATA_DIR": str(data), "PYTHONUTF8": "1", "PYTHONIOENCODING": "utf-8"} + cmd = [a.exe] if a.exe else [sys.executable, "-m", "gvr_worker"] + w = Worker(cmd, env) + res: dict = {} + res["hello"] = w.req("hello", 60) + res["gpu_info"] = w.req("gpu_info", 60) + res["ocr_image"] = w.req("ocr_image", 120, path=str(SAMPLE_PNG), lang="ko") + logs = data / "GameLogs" / "2026-10-15T12-00-00" + logs.mkdir(parents=True) + (logs / "2026-10-15T12-00-00_r3dlog.txt").write_text( + "000754.123| ALWAYS| [팀] 민수 (아리): 드래곤 가자\n000760.500| ALWAYS| [전체] 상대1 (가렌): gg\n", encoding="utf-8") + res["r3dlog_read"] = w.req("r3dlog_read", 60, logs_dir=str(data / "GameLogs"), since_ms=None) + res["download_tiny"] = w.req("download", 1200, target="model", name="tiny") + res["load"] = w.req("load", 600, slot="realtime", model="tiny", device="cpu", compute_type="int8") + res["transcribe"] = w.req("transcribe", 300, slot="realtime", path=str(SAMPLE_OGG), hotwords="레이즈 로테", + corrections=[], dictionary=["레이즈", "로테"], target_lufs=-18, noise_sensitivity=0.5, + denoise=False, profile_lufs=None) + w.req("shutdown", 30) + lines = [l.get("text", "") for l in (res["ocr_image"].get("result") or {}).get("lines", [])] + want = ["드래곤가자", "gg", "바텀갱간다"] + hit = sum(1 for x in want if any(x in l.replace(" ", "") for l in lines)) + text = ((res["transcribe"].get("result") or {}).get("text") or "") + res["summary"] = {"ocr_lines": lines, "ocr_hit": hit, "stt_text": text, + "r3dlog_lines": len((res["r3dlog_read"].get("result") or {}).get("lines", []))} + Path(a.out).write_text(json.dumps(res, ensure_ascii=False, indent=2), encoding="utf-8") + print(json.dumps(res["summary"], ensure_ascii=False)) + ok = hit >= 2 and "레이즈" in text + print("WIN SMOKE", "PASS" if ok else "FAIL") + return 0 if ok else 1 + + +if __name__ == "__main__": + raise SystemExit(main())