From 9c009ef3963759dfaf795dcf70d510b789d1ecad Mon Sep 17 00:00:00 2001 From: tfarcraw <123211521@163.com> Date: Fri, 20 Nov 2026 18:52:14 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9E=20d3-nano=20=E7=A6=BB?= =?UTF-8?q?=E7=BA=BF=E9=83=A8=E7=BD=B2=E8=84=9A=E6=9C=AC=E5=B9=B6=E9=83=A8?= =?UTF-8?q?=E7=BD=B2=20W-184=20=E5=88=A4=E5=AE=9A=E6=9C=8D=E5=8A=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- WINDOWS.md | 39 ++++++++ tools/Deploy-D3Nano.ps1 | 71 ++++++++++++++ tools/windows/d3nano-service.py | 131 +++++++++++++++++++++++++ tools/windows/install-d3nano.ps1 | 103 +++++++++++++++++++ tools/windows/probe-d3nano.py | 73 ++++++++++++++ tools/windows/register-d3nano-task.ps1 | 48 +++++++++ 6 files changed, 465 insertions(+) create mode 100644 tools/Deploy-D3Nano.ps1 create mode 100644 tools/windows/d3nano-service.py create mode 100644 tools/windows/install-d3nano.ps1 create mode 100644 tools/windows/probe-d3nano.py create mode 100644 tools/windows/register-d3nano-task.ps1 diff --git a/WINDOWS.md b/WINDOWS.md index 78e2066..9547485 100644 --- a/WINDOWS.md +++ b/WINDOWS.md @@ -21,6 +21,21 @@ Windows 工位机用 SSH/SFTP 部署,目录约定与 `tools/Deploy-Linux.ps1` - 脚本按 Windows PowerShell 5.1 编写并保存为带 BOM 的 UTF-8(无 BOM 时 5.1 会按系统代码页读取,中文注释和字符串会破坏解析)。 `tools/Publish-Avalonia.ps1`、`tools/Deploy-Linux.ps1` 使用 .NET Core 专有 API,需要 PowerShell 7。 +### d3-nano 判定服务 + +```powershell +# 打包模型与离线 wheel、传输、远端建 .venv、注册计划任务并用真实图片验收 +.\tools\Deploy-D3Nano.ps1 -Target Administrator@192.168.0.184 -InstallRoot D:\D3Nano +# 常用参数:-ModelSource 本机模型目录、-WheelsSource 本机 wheel 目录、-WheelsRemote 远端 wheel 目录、-SkipWheels 复用已传 wheel、-SkipStart 不启动服务 +``` + +- wheel 由本机 `pip download --only-binary=:all: --python-version 313 --platform win_amd64 --implementation cp` + 从 pytorch cu128 源与 PyPI 取全依赖,打包传入,远端用 `pip install --no-index --find-links` 离线安装。 + 工位机直连 pytorch 官方源只有 0.22MB/s,本机同一源 12MB/s,联网自装会拖到数小时。 +- `tools/windows/install-d3nano.ps1` 解包模型、装 Python(缺则 winget)、建 `.venv`、离线装依赖、写 `djev.json` 与机器级 `SOPHELPER_D3_ROOT`, + 最后校验 torch 能看到显卡与算力。`tools/windows/d3nano-service.py` 提供 `serve`(前台承载)、`status`、`probe` 三个入口, + `tools/windows/register-d3nano-task.ps1` 负责计划任务,`tools/windows/probe-d3nano.py` 用真实相机 JPEG 核对 noul 结果与耗时。 + ## W-184 首次部署(2026-11-20) `Administrator@192.168.0.184`(主机名 DESKTOP-MS5B7QN):Windows 11 专业版 10.0.26200、Gigabyte B550M DS3H AC R2、 @@ -40,3 +55,27 @@ Ryzen 5 5600XT、32GB 内存、NVIDIA GeForce RTX 5060(驱动 32.0.16.1088) - 未随包部署:djev 服务(该机没有 `E:\D3Lite`,程序启动时不会自动拉起,需在“运行设置 → djev”配置远端 `SOPHELPER_VISION_ENDPOINT`, 或在工位机安装 djev 后由程序自动启动)、SAM2/训练用 Python 环境(`BundlePythonRuntime=false`,`current\python` 不存在)。 - 相机:现场按 USB(UVC)接入,首次运行在“运行设置”里选择设备并确认实测 fps;本次未接相机,未做采集验证。 + +## W-184 d3-nano 部署(2026-11-20) + +该机没有 E 盘,按现场决定放 `D:\D3Nano`(部署后 D 盘剩余 712.9GB)。机器级 `SOPHELPER_D3_ROOT=D:\D3Nano`, +`D:\D3Nano\djev.json` 固定 `tier=nano`、`nano_root=D:\D3Nano`;桌面程序启动时检查 `127.0.0.1:8766/health`,就绪即复用现有服务,不会重复拉起。 + +- 模型:`D:\D3Nano\model` 24 个文件 4.15GB(`model.safetensors` 4426555160 字节),随包带 `local-model-manifest.json`, + 固定 `vllm-sr/d3-nano@8198c9f763b046605b2f4827b4999971fa2c92c4`,加载时按清单核对来源;本机 4.2GB 的 `downloads/` 下载缓存与 `__pycache__` 不传。 +- Python 与依赖:该机原本只有 WindowsApps 占位程序。官方 `python-3.13.17-amd64.exe` 由本机下载后传入,机器级安装到 `C:\Program Files\Python313`; + `D:\D3Nano\.venv`(4.47GB)离线装入 43 个 wheel:torch 2.11.0+cu128、torchvision 0.26.0+cu128、transformers 5.17.0、 + accelerate 1.15.0、safetensors 0.8.0、huggingface_hub 1.33.0、pillow 13.0.0、numpy 2.5.5。`flash-linear-attention` 未装, + 与本机 d3 环境一致,Gated DeltaNet 走 PyTorch 参考实现(Windows 无官方 triton 轮子)。 +- 显卡校验:`cudaAvailable=true`、设备 `NVIDIA GeForce RTX 5060`、算力 `[12, 0]`(sm_120 需要 cu128 构建)、显存 7.96GB,驱动 610.88。 +- 服务承载:计划任务 `SopHelper d3-nano`(`SYSTEM`、`AtStartup` 与 `AtLogOn`、无执行时限、失败重启 3 次/1 分钟、`IgnoreNew`), + 命令 `.venv\Scripts\python.exe d3nano-service.py serve --root D:\D3Nano --port 8766 --script C:\sophelper\current\services\start_d3_lite_local.py`。 + 在 SSH 会话里用分离进程启动的服务会随会话结束被 Windows OpenSSH 的作业对象回收(首次实测即如此),计划任务由 Task Scheduler 承载才能常驻。 +- 就绪与验收:任务启动到 `/health` 就绪约 13 秒,`model=d3-nano`、`modalities=[text,image,video]`、`max_input_tokens=2048`。 + 4 张真实相机 JPEG 各 2 次 noul 请求(首次为预热,不计入统计),4/4 与预期一致:空盒 0.9012、非空盒 0.3067、无手 0.0086、持物 0.9894; + 8 次请求 HTTP 平均 125.88ms、P95 128.37ms、最大 162.28ms,服务端 `server_ms` 平均 124.67ms、最大 160.9ms; + 响应返回的图片 SHA-256 与发送字节逐次核对一致。服务常驻显存 5917/8151 MiB,约剩 2.2GB 给桌面程序的 ONNX CUDA 手部模型。 + 耗时只覆盖请求发送与响应接收,不含相机取图与图片准备;样本量为 4 个既有用例,不能当作现场准确率。 +- 未验证:重启后计划任务自动拉起(已注册 `AtStartup`,未实机重启)、现场相机采集与 SOP 全流程运行。 +- 磁盘:模型 4.15GB、`.venv` 4.47GB,另有安装用 `D:\D3Nano\d3-nano-model.tar`(4.45GB)与 `d3-nano-wheels.tar`(2.63GB)保留作离线重装; + 本机对应包在 `artifacts/`,wheel 源在 `scratch/wheels/d3nano/`。 diff --git a/tools/Deploy-D3Nano.ps1 b/tools/Deploy-D3Nano.ps1 new file mode 100644 index 0000000..2c845a7 --- /dev/null +++ b/tools/Deploy-D3Nano.ps1 @@ -0,0 +1,71 @@ +param( + [string]$Target = 'Administrator@192.168.0.184', + [string]$InstallRoot = 'D:\D3Nano', + [string]$ModelSource = 'E:\D3Nano', + [string]$WheelsSource = 'E:\00-Inbox\aisop\scratch\wheels\d3nano', + [string]$WheelsRemote = 'D:\d3-wheels', + [string]$ServiceScript = 'C:\sophelper\current\services\start_d3_lite_local.py', + [int]$Port = 8766, + [switch]$SkipWheels, + [switch]$SkipStart +) +# 把 d3-nano(模型 + 离线 wheel + Python 环境)部署到远端 Windows 工位机,并实机验证服务。 +# 远端访问 pytorch 官方源很慢,wheel 由本机 pip download 后打包传入。 +$ErrorActionPreference = 'Stop' +if ($Target -notmatch '^[a-zA-Z0-9_.-]+@[a-zA-Z0-9_.-]+$') { throw 'Target must be user@host' } +if ($InstallRoot -notmatch '^[A-Za-z]:\\[A-Za-z0-9_.\\-]+$') { throw 'InstallRoot must be an absolute Windows path without spaces' } +if ($WheelsRemote -notmatch '^[A-Za-z]:\\[A-Za-z0-9_.\\-]+$') { throw 'WheelsRemote must be an absolute Windows path without spaces' } +$repo = Split-Path $PSScriptRoot -Parent +$remoteFwd = $InstallRoot.Replace('\', '/') + +# 1. 模型包:model/ 与 local-model-manifest.json,跳过 __pycache__ 与下载缓存。 +$modelTar = Join-Path $repo 'artifacts\d3-nano-model.tar' +Push-Location $ModelSource +try { + $items = Get-ChildItem -LiteralPath $ModelSource -Force | Where-Object { $_.Name -in @('model', 'local-model-manifest.json', 'local-serving-settings.json') } | Select-Object -ExpandProperty Name + if (!$items) { throw "模型源目录缺少 model/:$ModelSource" } + if (Test-Path -LiteralPath $modelTar) { Remove-Item -LiteralPath $modelTar -Force } + & tar -cf $modelTar $items + if ($LASTEXITCODE) { throw '打包模型失败' } +} finally { Pop-Location } +Write-Host ('模型包: ' + $modelTar + ' (' + [math]::Round((Get-Item $modelTar).Length/1GB,2) + ' GB)') + +# 2. wheel 包:本机 pip download 得到的 cp313 / win_amd64 / cu128 依赖。 +$wheelsTar = '' +if (!$SkipWheels) { + if (!(Test-Path -LiteralPath $WheelsSource)) { throw "缺少 wheel 目录: $WheelsSource" } + $wheelCount = @(Get-ChildItem -LiteralPath $WheelsSource -Filter *.whl).Count + if (!$wheelCount) { throw "目录中没有 wheel: $WheelsSource" } + $wheelsTar = Join-Path $repo 'artifacts\d3-nano-wheels.tar' + if (Test-Path -LiteralPath $wheelsTar) { Remove-Item -LiteralPath $wheelsTar -Force } + & tar -cf $wheelsTar -C $WheelsSource . + if ($LASTEXITCODE) { throw '打包 wheel 失败' } + Write-Host ('wheel 包: ' + $wheelsTar + ' (' + [math]::Round((Get-Item $wheelsTar).Length/1MB,1) + ' MB, ' + $wheelCount + ' 个)') +} + +# 3. 传入远端并安装。 +$payload = @($modelTar, (Join-Path $PSScriptRoot 'windows\install-d3nano.ps1'), (Join-Path $PSScriptRoot 'windows\register-d3nano-task.ps1'), (Join-Path $PSScriptRoot 'windows\d3nano-service.py'), (Join-Path $PSScriptRoot 'windows\probe-d3nano.py')) +if ($wheelsTar) { $payload += $wheelsTar } +& ssh -o BatchMode=yes $Target "New-Item -ItemType Directory -Force -Path $InstallRoot, $WheelsRemote, $InstallRoot\benchmark | Out-Null" +if ($LASTEXITCODE) { throw 'SSH failed' } +& scp -o BatchMode=yes $payload "${Target}:$remoteFwd/" +if ($LASTEXITCODE) { throw 'Transfer failed' } +$images = Get-ChildItem -LiteralPath (Join-Path $repo 'artifacts\imajev-benchmark') -Filter *-input.jpg +& scp -o BatchMode=yes $images.FullName "${Target}:$remoteFwd/benchmark/" +if ($LASTEXITCODE) { throw 'Transfer failed' } +if ($wheelsTar) { + & ssh -o BatchMode=yes $Target "tar -xf $InstallRoot\d3-nano-wheels.tar -C $WheelsRemote" + if ($LASTEXITCODE) { throw '远端解包 wheel 失败' } +} +& ssh -o BatchMode=yes $Target "powershell -NoProfile -ExecutionPolicy Bypass -File $InstallRoot\install-d3nano.ps1 -InstallRoot $InstallRoot -WheelsDir $WheelsRemote" +if ($LASTEXITCODE) { throw '安装 d3-nano 失败' } + +# 4. 注册开机自启的计划任务承载服务,并实机验证(真实相机 JPEG + noul 请求)。 +$venvPython = Join-Path $InstallRoot '.venv\Scripts\python.exe' +if (!$SkipStart) { + & ssh -o BatchMode=yes $Target "powershell -NoProfile -ExecutionPolicy Bypass -File $InstallRoot\register-d3nano-task.ps1 -InstallRoot $InstallRoot -Port $Port -Script $ServiceScript" + if ($LASTEXITCODE) { throw 'd3-nano 计划任务注册或启动失败' } + & ssh -o BatchMode=yes $Target "$venvPython $InstallRoot\d3nano-service.py probe --root $InstallRoot --port $Port --image-root $InstallRoot\benchmark" + if ($LASTEXITCODE) { throw 'd3-nano 真实图片请求验证失败' } +} +Write-Host "已部署 d3-nano 到 $Target:$InstallRoot;SOPHELPER_D3_ROOT 已写入系统环境变量。" diff --git a/tools/windows/d3nano-service.py b/tools/windows/d3nano-service.py new file mode 100644 index 0000000..e5512bb --- /dev/null +++ b/tools/windows/d3nano-service.py @@ -0,0 +1,131 @@ +"""启动、检查并验证远端 d3-nano 服务;由 tools/Deploy-D3Nano.ps1 通过 SSH 调用。 + +start 用虚拟环境的 python 拉起服务(分离进程,脱离 SSH 会话),等待 /health 就绪。 +status 打印当前 /health、监听端口与显存占用。 +probe 用真实相机 JPEG 发送 noul 请求,核对结果与耗时。 +""" +import argparse +import json +import os +import runpy +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +HEALTH_TIMEOUT_SECONDS = 300 + + +def get_json(url, timeout=10): + with urllib.request.urlopen(url, timeout=timeout) as response: + return json.loads(response.read().decode("utf-8")) + + +def health(port): + try: + data = get_json(f"http://127.0.0.1:{port}/health") + except Exception: + return {"status": "missing"} + modalities = data.get("modalities", []) + ready = data.get("status") == "ready" and data.get("model") in ("d3-lite", "d3-nano") and "image" in modalities + data["ready"] = bool(ready) + return data + + +def nvidia_memory(): + try: + out = subprocess.run(["nvidia-smi", "--query-gpu=memory.used,memory.total", "--format=csv,noheader"], + capture_output=True, text=True, timeout=20).stdout.strip() + except Exception as error: + return {"error": repr(error)} + return {"nvidia_smi": out} + + +def start(root, port, script, log_dir): + state = health(port) + if state.get("ready"): + return {"action": "reuse", "health": state} + python = Path(root) / ".venv" / "Scripts" / "python.exe" + if not python.exists(): + raise SystemExit(f"缺少虚拟环境解释器:{python}") + if not Path(script).exists(): + raise SystemExit(f"缺少服务脚本:{script}(请先部署 SopHelper win-x64 包)") + Path(log_dir).mkdir(parents=True, exist_ok=True) + stdout = (Path(log_dir) / "djev-service.stdout.log").open("w", encoding="utf-8") + stderr = (Path(log_dir) / "djev-service.stderr.log").open("w", encoding="utf-8") + creationflags = 0 + if os.name == "nt": + creationflags = subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP + process = subprocess.Popen([str(python), "-u", str(script), "--root", str(root), "--port", str(port), + "--log-dir", str(log_dir)], cwd=str(root), stdout=stdout, stderr=stderr, + stdin=subprocess.DEVNULL, creationflags=creationflags, close_fds=True) + (Path(root) / "server.pid").write_text(str(process.pid), encoding="ascii") + deadline = time.monotonic() + HEALTH_TIMEOUT_SECONDS + last = {"status": "starting"} + while time.monotonic() < deadline: + last = health(port) + if last.get("ready"): + return {"action": "started", "pid": process.pid, "health": last, "logs": str(log_dir)} + if process.poll() is not None: + raise SystemExit(f"d3-nano 启动失败,退出码 {process.returncode},日志:{log_dir}") + time.sleep(2) + raise SystemExit(f"等待 d3-nano 就绪超时({HEALTH_TIMEOUT_SECONDS}s),日志:{log_dir},最后状态:{last}") + + +def probe(port, image_root, repeat): + script = Path(__file__).with_name("probe-d3nano.py") + if not script.exists(): + raise SystemExit(f"缺少验证脚本:{script}") + if not Path(image_root).exists(): + raise SystemExit(f"缺少验证图片目录:{image_root}") + environment = dict(os.environ, PYTHONIOENCODING="utf-8") + result = subprocess.run([sys.executable, str(script), "--port", str(port), "--image-root", str(image_root), + "--repeat", str(repeat)], capture_output=True, text=True, encoding="utf-8", + errors="replace", env=environment, timeout=900) + if result.returncode: + print((result.stdout or "")[-2000:]) + print((result.stderr or "")[-4000:]) + raise SystemExit("真实图片请求验证失败") + print(result.stdout.strip()) + + +def serve(root, port, script, log_dir): + """前台运行模型服务,供计划任务承载(SSH 会话结束时子进程会被作业对象回收,不能用分离进程)。""" + if not Path(script).exists(): + raise SystemExit(f"缺少服务脚本:{script}(请先部署 SopHelper win-x64 包)") + Path(log_dir).mkdir(parents=True, exist_ok=True) + (Path(root) / "server.pid").write_text(str(os.getpid()), encoding="ascii") + sys.argv = [str(script), "--root", str(root), "--port", str(port), "--log-dir", str(log_dir)] + runpy.run_path(str(script), run_name="__main__") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("command", choices=["serve", "start", "status", "probe"]) + parser.add_argument("--root", default=r"D:\D3Nano") + parser.add_argument("--port", type=int, default=8766) + parser.add_argument("--script", default=r"C:\sophelper\current\services\start_d3_lite_local.py") + parser.add_argument("--log-dir") + parser.add_argument("--image-root", default=r"D:\D3Nano\benchmark") + parser.add_argument("--repeat", type=int, default=3) + args = parser.parse_args() + log_dir = args.log_dir or str(Path(args.root) / "logs") + if args.command == "serve": + serve(args.root, args.port, args.script, log_dir) + return + if args.command == "start": + report = start(args.root, args.port, args.script, log_dir) + elif args.command == "status": + report = {"health": health(args.port), "pid_file": (Path(args.root) / "server.pid").read_text(encoding="ascii") + if (Path(args.root) / "server.pid").exists() else None} + report.update(nvidia_memory()) + else: + probe(args.port, args.image_root, args.repeat) + report = {"health": health(args.port)} + report.update(nvidia_memory()) + print(json.dumps(report, ensure_ascii=False)) + + +if __name__ == "__main__": + main() diff --git a/tools/windows/install-d3nano.ps1 b/tools/windows/install-d3nano.ps1 new file mode 100644 index 0000000..da4bcd1 --- /dev/null +++ b/tools/windows/install-d3nano.ps1 @@ -0,0 +1,103 @@ +param( + [string]$InstallRoot = 'D:\D3Nano', + [string]$ModelTar = '', + [string]$WheelsTar = '', + [string]$WheelsDir = 'D:\d3-wheels', + [string]$PythonExe = '', + [int]$Port = 8766, + [int]$SkipModel = 0, + [int]$SkipVenv = 0 +) +# 远端 d3-nano 安装脚本:解包模型、建 .venv、离线装依赖、写 djev 配置并校验 CUDA 可用性。 +# 由 tools/Deploy-D3Nano.ps1 通过 SSH 调用,参数不含空格。 +$ErrorActionPreference = 'Stop' +$python = Join-Path $InstallRoot '.venv\Scripts\python.exe' +$logDir = Join-Path $InstallRoot 'logs' +New-Item -ItemType Directory -Force -Path $InstallRoot, $logDir | Out-Null + +# 1. 模型:model/*.safetensors 等与 local-model-manifest.json(启动脚本按清单核对来源)。 +if (!$SkipModel) { + if (!$ModelTar) { $ModelTar = Join-Path $InstallRoot 'd3-nano-model.tar' } + if (!(Test-Path -LiteralPath $ModelTar)) { throw "缺少模型包: $ModelTar" } + tar -xf $ModelTar -C $InstallRoot + if ($LASTEXITCODE) { throw "解压模型包失败: $ModelTar" } +} +foreach ($required in @('model\decision_config.json', 'model\model.safetensors', 'model\d3_runtime.py', 'local-model-manifest.json')) { + if (!(Test-Path -LiteralPath (Join-Path $InstallRoot $required))) { throw "模型不完整: $InstallRoot\$required" } +} + +# 2. Python 3.13:远端可能只有 WindowsApps 占位程序,需要真正的解释器。 +function Find-Python() { + $candidates = @('C:\Program Files\Python313\python.exe', 'C:\Program Files\Python313-3.13\python.exe', + (Join-Path $env:ProgramData 'Python313\python.exe'), (Join-Path $env:LOCALAPPDATA 'Programs\Python\Python313\python.exe')) + foreach ($candidate in $candidates) { if (Test-Path -LiteralPath $candidate) { return $candidate } } + foreach ($name in @('py', 'python')) { + $command = Get-Command $name -ErrorAction SilentlyContinue + if (!$command) { continue } + if ($command.Source -like '*WindowsApps*') { continue } + $detected = (& $name -c "import sys;print(sys.executable)" 2>$null | Out-String).Trim() + if ($detected -and (Test-Path -LiteralPath $detected)) { return $detected } + } + return '' +} +if (!$PythonExe) { $PythonExe = Find-Python } +if (!$PythonExe) { + Write-Output '未找到 Python,使用 winget 安装 Python 3.13' + & winget install --id Python.Python.3.13 --exact --scope machine --silent --accept-package-agreements --accept-source-agreements | Out-Null + $PythonExe = Find-Python +} +if (!$PythonExe) { throw '远端没有可用的 Python 3.13,请先安装后重试' } +$baseVersion = (& $PythonExe -c "import sys;print(sys.version.split()[0])" | Out-String).Trim() +$baseMinor = (& $PythonExe -c "import sys;print('%d.%d' % sys.version_info[:2])" | Out-String).Trim() +if ($baseMinor -ne '3.13') { Write-Output "警告:基础 Python 为 $baseVersion,wheel 包按 cp313 下载,版本不一致会安装失败" } + +# 3. 虚拟环境与离线依赖(远端访问 pytorch 源很慢,wheel 由本机打包传入)。 +if (!$SkipVenv) { + if (!(Test-Path -LiteralPath $python)) { + & $PythonExe -m venv (Join-Path $InstallRoot '.venv') + if ($LASTEXITCODE) { throw '创建 .venv 失败' } + } + if (!$WheelsDir -and $WheelsTar) { + tar -xf $WheelsTar -C (Split-Path $WheelsDir -Parent) + if ($LASTEXITCODE) { throw "解压 wheel 包失败: $WheelsTar" } + } + if (!(Test-Path -LiteralPath $WheelsDir)) { throw "缺少 wheel 目录: $WheelsDir" } + & $python -m pip install --no-index --find-links $WheelsDir --no-warn-script-location torch torchvision transformers accelerate safetensors huggingface_hub pillow + if ($LASTEXITCODE) { throw '离线安装 d3-nano 依赖失败' } +} +if (!(Test-Path -LiteralPath $python)) { throw "缺少虚拟环境解释器: $python" } + +# 4. 配置:djev 档位固定 nano;系统环境变量让桌面程序按此根目录自动拉起。 +$config = [ordered]@{ tier = 'nano'; nano_root = $InstallRoot } +$config | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $InstallRoot 'djev.json') -Encoding UTF8 +& setx /M SOPHELPER_D3_ROOT $InstallRoot | Out-Null +$machineRoot = [Environment]::GetEnvironmentVariable('SOPHELPER_D3_ROOT', 'Machine') + +# 5. 校验:依赖导入、CUDA 可用与目标显卡算力(RTX 5060 需要 cu128 的 sm_120 构建)。 +$verify = Join-Path $env:TEMP 'd3nano-verify.py' +@' +import json, sys +import torch, torchvision, transformers, PIL, safetensors, accelerate, huggingface_hub +print(json.dumps({ + "python": sys.version.split()[0], + "torch": torch.__version__, + "cudaBuild": torch.version.cuda, + "cudaAvailable": torch.cuda.is_available(), + "device": torch.cuda.get_device_name(0) if torch.cuda.is_available() else None, + "capability": list(torch.cuda.get_device_capability(0)) if torch.cuda.is_available() else None, + "totalMemoryGB": round(torch.cuda.get_device_properties(0).total_memory / 2 ** 30, 2) if torch.cuda.is_available() else None, + "transformers": transformers.__version__, + "torchvision": torchvision.__version__, +}, ensure_ascii=False)) +'@ | Set-Content -LiteralPath $verify -Encoding UTF8 +& $python $verify +if ($LASTEXITCODE) { throw 'd3-nano 运行环境校验失败' } +Remove-Item -LiteralPath $verify -Force + +Write-Output (ConvertTo-Json -InputObject ([ordered]@{ + installed = $InstallRoot + python = $python + basePython = $PythonExe + d3RootEnv = $machineRoot + port = $Port +}) -Compress) diff --git a/tools/windows/probe-d3nano.py b/tools/windows/probe-d3nano.py new file mode 100644 index 0000000..b60f0dc --- /dev/null +++ b/tools/windows/probe-d3nano.py @@ -0,0 +1,73 @@ +"""d3-nano 远端实机验证:/health 与真实相机 JPEG 的 noul 请求。""" +import argparse +import base64 +import hashlib +import json +import statistics +import time +import urllib.request +from pathlib import Path + +CASES = [ + ("空盒_中文", "empty_crop-input.jpg", "盒子空了没?", True), + ("非空盒_中文", "nonempty_crop-input.jpg", "盒子空了没?", False), + ("无手_中文", "no_hand-input.jpg", "手里拿着东西吗?", False), + ("持物_中文", "hikvision-imajev-holding-20261112-194959-input.jpg", "手里拿着东西吗?", True), +] + + +def get_json(url, timeout=120): + with urllib.request.urlopen(url, timeout=timeout) as response: + return json.loads(response.read().decode("utf-8")) + + +def post(endpoint, image, question): + payload = {"state": "", "questions": {"q": {"type": "noul", "instructions": question}}, + "images": ["data:image/jpeg;base64," + base64.b64encode(image).decode()]} + request = urllib.request.Request(endpoint, data=json.dumps(payload, ensure_ascii=False).encode("utf-8"), + headers={"Content-Type": "application/json; charset=utf-8"}) + started = time.perf_counter() + with urllib.request.urlopen(request, timeout=120) as response: + content = response.read() + elapsed = round((time.perf_counter() - started) * 1000, 2) + result = json.loads(content) + assert result["usage"]["image_sha256"] == [hashlib.sha256(image).hexdigest()], "返回的图片哈希与发送字节不一致" + answer = result["answers"]["q"] + if "error" in answer: + raise RuntimeError(answer) + return {"http_ms": elapsed, "server_ms": result["usage"]["server_ms"], "noul": round(answer["noul"], 4), + "actual": answer["noul"] > 0.5} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--port", type=int, default=8766) + parser.add_argument("--image-root", type=Path, required=True) + parser.add_argument("--repeat", type=int, default=3, help="每个用例的重复次数(首次计入预热,不计入统计)") + args = parser.parse_args() + base = f"http://127.0.0.1:{args.port}" + health = get_json(base + "/health", timeout=10) + endpoint = base + "/v1/systemone" + report = {"health": health, "cases": [], "latency": None} + for name, filename, question, expected in CASES: + image = (args.image_root / filename).read_bytes() + runs = [post(endpoint, image, question) for _ in range(max(1, args.repeat))] + warmup, measured = runs[0], runs[1:] + report["cases"].append({ + "case": name, "image": filename, "expected": expected, + "warmup": {"http_ms": warmup["http_ms"], "noul": warmup["noul"], "actual": warmup["actual"]}, + "noul_mean": round(statistics.mean(row["noul"] for row in measured), 4), + "match": all(row["actual"] == expected for row in measured), + "runs": measured, + }) + latencies = sorted(row["http_ms"] for case in report["cases"] for row in case["runs"]) + servers = sorted(row["server_ms"] for case in report["cases"] for row in case["runs"]) + report["latency"] = {"count": len(latencies), "mean_ms": round(statistics.mean(latencies), 2), + "p95_ms": latencies[int(0.95 * len(latencies)) - 1], "max_ms": latencies[-1], + "server_mean_ms": round(statistics.mean(servers), 2), "server_max_ms": servers[-1]} + report["passed"] = all(case["match"] for case in report["cases"]) + print(json.dumps(report, ensure_ascii=False)) + + +if __name__ == "__main__": + main() diff --git a/tools/windows/register-d3nano-task.ps1 b/tools/windows/register-d3nano-task.ps1 new file mode 100644 index 0000000..c505872 --- /dev/null +++ b/tools/windows/register-d3nano-task.ps1 @@ -0,0 +1,48 @@ +param( + [string]$InstallRoot = 'D:\D3Nano', + [int]$Port = 8766, + [string]$Script = 'C:\sophelper\current\services\start_d3_lite_local.py', + [string]$TaskName = 'SopHelper d3-nano', + [int]$StartNow = 1 +) +# 把 d3-nano 注册为开机自启计划任务:SSH 会话里用分离进程启动的服务会随会话被作业对象回收, +# 计划任务由 Task Scheduler 服务承载,服务才能常驻,桌面程序启动时直接复用。 +$ErrorActionPreference = 'Stop' +$python = Join-Path $InstallRoot '.venv\Scripts\python.exe' +$helper = Join-Path $InstallRoot 'd3nano-service.py' +foreach ($required in @($python, $helper)) { + if (!(Test-Path -LiteralPath $required)) { throw "缺少文件: $required" } +} +$argument = '-u "' + $helper + '" serve --root "' + $InstallRoot + '" --port ' + $Port + ' --script "' + $Script + '"' +$action = New-ScheduledTaskAction -Execute $python -Argument $argument -WorkingDirectory $InstallRoot +$trigger = @((New-ScheduledTaskTrigger -AtStartup), (New-ScheduledTaskTrigger -AtLogOn -User 'Administrator')) +$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable ` + -ExecutionTimeLimit ([TimeSpan]::Zero) -MultipleInstances IgnoreNew -Priority 7 ` + -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 1) +$principal = New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest +$description = 'SopHelper d3-nano 判定服务(djev),监听 127.0.0.1:' + $Port +Register-ScheduledTask -TaskName $TaskName -Action $action -Trigger $trigger -Settings $settings -Principal $principal ` + -Description $description -Force | Out-Null +Write-Output ('已注册计划任务: ' + $TaskName) +if ($StartNow) { + Start-ScheduledTask -TaskName $TaskName + $deadline = [DateTime]::UtcNow.AddSeconds(300) + $ready = $false + while ([DateTime]::UtcNow -lt $deadline) { + try { + $health = Invoke-RestMethod -Uri ('http://127.0.0.1:' + $Port + '/health') -TimeoutSec 3 + if ($health.status -eq 'ready' -and $health.model -in @('d3-lite', 'd3-nano') -and 'image' -in $health.modalities) { $ready = $true; break } + } catch { } + Start-Sleep -Seconds 3 + } + $state = (Get-ScheduledTask -TaskName $TaskName).State + $info = (Get-ScheduledTaskInfo -TaskName $TaskName) + if (!$ready) { + Write-Output ('任务状态=' + $state + ' 上次结果=' + $info.LastTaskResult + ' 日志=' + (Join-Path $InstallRoot 'logs')) + throw '等待 d3-nano 就绪超时' + } + Write-Output ('d3-nano 就绪:' + ($health | ConvertTo-Json -Compress -Depth 6)) +} +$task = Get-ScheduledTaskInfo -TaskName $TaskName +Write-Output (ConvertTo-Json -InputObject ([ordered]@{ task = $TaskName; state = (Get-ScheduledTask -TaskName $TaskName).State; + lastTaskResult = $task.LastTaskResult; numberOfRuns = $task.NumberOfRuns }) -Compress)