"""Stage: PC information (GPU, driver, CPU, RAM, disk, monitors).""" from __future__ import annotations import ctypes import json import os import platform import shutil import subprocess import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) from m0lib.common import IS_WINDOWS, StageResult, nvidia_smi, say, stage_args # noqa: E402 def _ps_json(script: str) -> object: out = subprocess.run(["powershell", "-NoProfile", "-NonInteractive", "-Command", f"[Console]::OutputEncoding=[Text.Encoding]::UTF8; {script} | ConvertTo-Json -Depth 4"], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=60) text = out.stdout.strip() return json.loads(text) if text else None def _nvidia() -> dict: exe = nvidia_smi() if not exe: return {"found": False} fields = ["name", "driver_version", "memory.total", "memory.used", "pcie.link.gen.max", "pcie.link.width.max", "power.limit", "compute_cap"] info: dict = {"found": True} try: line = subprocess.run([exe, f"--query-gpu={','.join(fields)}", "--format=csv,noheader,nounits"], capture_output=True, text=True, timeout=20).stdout.strip().splitlines()[0] info.update({k: v.strip() for k, v in zip(fields, line.split(","))}) except Exception as e: info["query_error"] = str(e) try: head = subprocess.run([exe], capture_output=True, text=True, timeout=20).stdout for part in head.split("|"): if "CUDA Version" in part: info["cuda_version"] = part.split("CUDA Version:")[1].strip().split()[0] except Exception: pass try: major = int(str(info.get("driver_version", "0")).split(".")[0]) info["driver_ok_for_cuda13"] = major >= 580 except ValueError: pass return info def _monitors() -> list[dict]: if not IS_WINDOWS: return [] from ctypes import wintypes user32 = ctypes.windll.user32 try: ctypes.windll.shcore.SetProcessDpiAwareness(2) except Exception: pass shcore = ctypes.windll.shcore class MONITORINFOEXW(ctypes.Structure): _fields_ = [("cbSize", wintypes.DWORD), ("rcMonitor", wintypes.RECT), ("rcWork", wintypes.RECT), ("dwFlags", wintypes.DWORD), ("szDevice", wintypes.WCHAR * 32)] # Declare handle types: a 64-bit HMONITOR passed as a plain int overflows. user32.GetMonitorInfoW.argtypes = [wintypes.HMONITOR, ctypes.c_void_p] shcore.GetDpiForMonitor.argtypes = [wintypes.HMONITOR, ctypes.c_int, ctypes.POINTER(ctypes.c_uint), ctypes.POINTER(ctypes.c_uint)] mons: list[dict] = [] proc_t = ctypes.WINFUNCTYPE(ctypes.c_int, wintypes.HMONITOR, wintypes.HDC, ctypes.POINTER(wintypes.RECT), wintypes.LPARAM) def cb(hmon, _hdc, _rect, _lp): mi = MONITORINFOEXW() mi.cbSize = ctypes.sizeof(MONITORINFOEXW) user32.GetMonitorInfoW(hmon, ctypes.byref(mi)) dx, dy = ctypes.c_uint(), ctypes.c_uint() try: shcore.GetDpiForMonitor(hmon, 0, ctypes.byref(dx), ctypes.byref(dy)) except Exception: dx.value = 96 r = mi.rcMonitor mons.append({"index": len(mons) + 1, "x": r.left, "y": r.top, "width": r.right - r.left, "height": r.bottom - r.top, "primary": bool(mi.dwFlags & 1), "scale_percent": round(dx.value / 96 * 100)}) return 1 user32.EnumDisplayMonitors(None, None, proc_t(cb), 0) return mons def _discord() -> dict: base = Path(os.environ.get("LOCALAPPDATA", "")) / "Discord" if not base.exists(): return {"installed": False} versions = sorted(p.name for p in base.glob("app-*")) return {"installed": True, "version": versions[-1][4:] if versions else None} def _hags() -> object: if not IS_WINDOWS: return None import winreg try: with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Control\GraphicsDrivers") as k: v, _ = winreg.QueryValueEx(k, "HwSchMode") return {1: "off", 2: "on"}.get(v, v) except OSError: return "unknown" def main() -> int: out, work, _ = stage_args() r = StageResult("sysinfo", out) r["os"] = {"platform": platform.platform(), "release": platform.release(), "version": platform.version(), "python": sys.version.split()[0]} r["gpu"] = _nvidia() say(f" GPU: {r['gpu'].get('name')} / 드라이버 {r['gpu'].get('driver_version')}") du = shutil.disk_usage(work) r["workdir_disk"] = {"total_gb": round(du.total / 1e9), "free_gb": round(du.free / 1e9)} say(f" 작업 폴더 디스크 남은 공간: {r['workdir_disk']['free_gb']} GB") if IS_WINDOWS: for key, script in { "cpu": "Get-CimInstance Win32_Processor | Select-Object Name,NumberOfCores,NumberOfLogicalProcessors,MaxClockSpeed", "ram_modules": "Get-CimInstance Win32_PhysicalMemory | Select-Object Capacity,Speed,ConfiguredClockSpeed", "os_detail": "Get-CimInstance Win32_OperatingSystem | Select-Object Caption,Version,BuildNumber,TotalVisibleMemorySize", "disks": "Get-PhysicalDisk | Select-Object FriendlyName,MediaType,BusType,Size", "video_controllers": "Get-CimInstance Win32_VideoController | Select-Object Name,DriverVersion,CurrentHorizontalResolution,CurrentVerticalResolution,CurrentRefreshRate", }.items(): try: r[key] = _ps_json(script) except Exception as e: r.error(key, e) try: mods = r.get("ram_modules") or [] mods = mods if isinstance(mods, list) else [mods] r["ram_total_gb"] = round(sum(int(m.get("Capacity") or 0) for m in mods) / 2**30) say(f" RAM: {r['ram_total_gb']} GB") except Exception as e: r.error("ram_total", e) try: r["monitors"] = _monitors() say(f" 모니터: {len(r['monitors'])}대") except Exception as e: r.error("monitors", e) r["hardware_gpu_scheduling"] = _hags() r["discord"] = _discord() r.save("ok" if not r["errors"] else "partial") return 0 if __name__ == "__main__": sys.exit(main())