移除 djev 运行设置并固定使用 Nano 模型
This commit is contained in:
parent
ba9658abf9
commit
cc0fdc192b
58
HAND_AI.md
58
HAND_AI.md
@ -2,11 +2,9 @@
|
||||
|
||||
## 全局 djev 判定超时(2026-11-20)
|
||||
|
||||
在“运行设置 → djev 判定”中设置“判定超时(ms)”,范围1–1000 ms,默认300 ms。
|
||||
参数自动独立保存到工作区 `workspace/runtime-settings.json` 的 `DjevTimeoutMs`,
|
||||
与配方无关。切换、导入、导出或编辑配方不会改变它。运行期间禁止修改,修改后在
|
||||
下次开始运行或下一次关键帧/参考图检查时生效。旧的全局 `DjevTimeoutSeconds`
|
||||
读取时换算成毫秒并限制在新范围内;毫秒字段优先,下次保存只写毫秒字段。
|
||||
运行设置页已移除 djev 区块。已有工作区继续读取 `workspace/runtime-settings.json` 中的
|
||||
`DjevTimeoutMs`,默认 300 ms,范围 1–1000 ms。切换、导入、导出或编辑配方不会改变该值。
|
||||
旧字段 `DjevTimeoutSeconds` 读取时换算成毫秒并限制在该范围内,毫秒字段优先。
|
||||
|
||||
只计算**请求发给djev后等待响应的时间**:准备图片、裁剪/编码、构造请求在计时前完成,
|
||||
从调用HTTP发送到完整接收响应计时,响应解析和界面调度不计入,不扣预留时间。
|
||||
@ -18,30 +16,17 @@
|
||||
不会迁移成全局值。单次请求超时与每步复检总窗口、步骤超时告警分别设置,不能延长整步窗口。
|
||||
Agent只能读取用户设置,不能自行提高期限或降低置信度。
|
||||
|
||||
## djev 快捷切换
|
||||
## 本机 djev Nano
|
||||
|
||||
程序内可在“运行设置 → djev 判定”选择启动档位 `lite` / `nano`,并编辑两档的模型目录,点击“保存启动配置”。
|
||||
配置写入自动启动使用的安装根目录下的 `djev.json`,不随配方切换;保存前检查所选目录的模型档位,失败时保留旧配置。
|
||||
保存只影响**下次 djev 服务启动**,当前服务继续运行;退出桌面程序会停止有有效进程记录的本机服务,再次启动时按保存配置加载。远程服务不受影响。
|
||||
运行期间禁止保存。远程服务需要在服务所在机器配置。
|
||||
`lite_root` / `nano_root` 可分别指定模型目录,独立 Nano 安装也能选择其他目录中的 Lite;Python 环境仍使用安装根目录的 `.venv`。
|
||||
将 Nano 模型和 Python 虚拟环境分别安装到程序目录的 `D3Nano/model/` 和 `D3Nano/.venv/`,
|
||||
并把 `local-model-manifest.json` 放在 `D3Nano/` 下。桌面程序使用此固定目录启动和预热模型。
|
||||
旧 `djev.json` 和 `SOPHELPER_D3_ROOT` 已停用。启动脚本随构建和发布复制到
|
||||
`services/start_d3_lite_local.py`,日志写入工作区的 `logs/d3-service/`。
|
||||
|
||||
命令、桌面界面提示、步骤回测及判定结果统一称为 `djev`,使用 `lite` / `nano` 区分档位。Windows 在仓库根目录执行:
|
||||
|
||||
```powershell
|
||||
.\djev.cmd nano # 切到 nano
|
||||
.\djev.cmd lite # 切回 lite
|
||||
.\djev.cmd status # 查看当前档位;不带参数也可查看
|
||||
.\djev.cmd config nano # 只设置下次自动启动nano,不中断当前服务
|
||||
.\djev.cmd config lite # 只设置下次自动启动lite
|
||||
.\djev.cmd config # 查看自动启动配置
|
||||
```
|
||||
|
||||
共用 `http://127.0.0.1:8766/v1/systemone`,无需修改配方或重开 SOP 窗口。切换期间判定暂不可用;命令等待模型加载和单张 512px 图片预热完成后报告就绪。已是目标档位时直接复用。启动失败时尝试恢复此前档位;只停止端口及安装路径均匹配的本机模型进程,不关闭 SOP 界面。服务独立于命令窗口继续运行。`lite` / `nano` 切换成功后同时保存选择;`config` 只保存选择。
|
||||
|
||||
程序启动时已存在就绪的 djev 则直接复用;没有运行则按 `E:\D3Lite\djev.json` 自动拉起并预热。配置文件可手动编辑,例如 `{"tier":"nano","nano_root":"E:\\D3Nano"}`;改回 `"tier":"lite"` 即下次自动启动 lite。未创建配置时兼容默认 lite。`SOPHELPER_D3_ROOT` 指定其他安装根目录时,读取该目录的 `djev.json`;`nano_root` 可指定其他模型安装目录,不写时使用同级 `D3Nano`。配置不改变当前已运行服务,立即生效请执行切换命令。
|
||||
|
||||
安装复用现有 `E:\D3Lite`、`E:\D3Nano` 及 Lite 的 Python 环境;日志使用工作区 `scratch/logs/*-switch.stdout.log`、`*-switch.stderr.log`,同用途覆盖。上游包标识、下载地址和已有配置字段保持兼容,显示名称统一为 djev。源码更新中的界面名称在新构建启动后生效,已打开的旧程序需在方便时重新启动。
|
||||
桌面程序在后台检查默认端点 `http://127.0.0.1:8766/v1/systemone` 的健康状态,
|
||||
复用支持图片且已就绪的 Nano 服务。Lite 或其他服务占用端口时会报告冲突。
|
||||
本机等待就绪最长 180 秒。退出时先取消启动等待,再停止可识别的本机服务。
|
||||
使用 `SOPHELPER_VISION_ENDPOINT` 连接远程 Nano 时,由服务端部署模型。
|
||||
|
||||
## 2026-11-19:D3-nano 本机试用
|
||||
|
||||
@ -108,22 +93,11 @@ E:\D3Lite\.venv\Scripts\python.exe tools/benchmark_d3_lite.py --endpoint http://
|
||||
|
||||
模型列表实连诊断可运行 `dotnet run --project tests/Avalonia.Smoke -- --agent-settings-file 设置文件路径`,传入当前工作区的 `workspace/sop-agent.json`。它复制设置到临时工作区,通过真实编辑器和 HTTP 客户端获取模型列表,输出状态和模型名,不输出密钥、不改原设置,结束后删除临时数据。
|
||||
|
||||
### 当前版本:本机 D3-lite
|
||||
### 判定接口
|
||||
|
||||
本分支默认 `d3-lite` 后端、`http://127.0.0.1:8766/v1/systemone`。不设置模型名或密钥也可连接本机服务;显式的 Laya / Chat Completions provider 仍受支持。
|
||||
|
||||
桌面软件启动时会在后台检查 D3-lite 的 `/health`,已就绪则复用;本机未运行时从已安装环境自动启动,等待就绪最长 180 秒,不阻塞界面。Windows 默认环境为 `E:\D3Lite`,Linux 默认 `~/D3Lite`,可用 `SOPHELPER_D3_ROOT` 指定。启动脚本随构建/发布复制到 `services/start_d3_lite_local.py`,服务输出写入工作区 `logs/d3-service/`。环境缺失、端口被其他服务占用、子进程退出或载入超时均记录明确原因,不自动安装模型。远程 D3 地址和其他视觉 provider 不会拉起本机 D3。
|
||||
|
||||
跨进程启动锁及 PID/启动时间记录防止载入期间重复占用 GPU;等待取消或软件退出不会终止已启动的独立服务。启动探测只读取健康状态,不送判定图。`tests/D3Startup.Smoke` 覆盖上述状态,附加 `--python Python路径` 可用真实 Python 启动轻量测试服务验证进程和日志,不加载模型。
|
||||
|
||||
```powershell
|
||||
# 在仓库根目录运行;复用现有服务,或隐藏启动 E:\D3Lite 的服务,再打开 SOP。
|
||||
pwsh -File tools/Start-HandAiD3.ps1
|
||||
# 只准备服务并检查图片能力。
|
||||
pwsh -File tools/Start-HandAiD3.ps1 -CheckOnly
|
||||
```
|
||||
|
||||
脚本只在 SOP 子进程使用 D3 配置,返回时恢复调用窗口原有环境变量。服务关闭界面后继续保留,启动日志在 `artifacts/d3-integration/`。要连接其他机器上已启动的 D3 服务,可设置 `SOPHELPER_VISION_PROVIDER=d3-lite` 和完整的 `SOPHELPER_VISION_ENDPOINT`;这不会自动部署远端服务。
|
||||
SystemOne 后端默认连接本机 Nano,兼容已有的 `SOPHELPER_VISION_PROVIDER=d3-lite` 接口标识。
|
||||
显式配置的 Laya / Chat Completions provider 仍可使用。开发时执行 `dotnet run --project src/SopHelper.Avalonia`,
|
||||
默认 Debug 输出对应的模型目录为 `src/SopHelper.Avalonia/bin/Debug/net8.0/D3Nano/`。
|
||||
|
||||
每个步骤默认必须经过 AI 确认,编辑器不再提供启用/关闭勾选。直接使用步骤“说明”(YAML `description`)作为静态完成条件,例如“敞开的纸盒内部可见连接器”;动作名称写在步骤名里,不要求单帧模型证明抓取或移动历史。不单独填写或保存 `ai_confirmation.criteria`。步骤可选择三种送检方式:
|
||||
|
||||
|
||||
@ -13,7 +13,7 @@ Windows / Linux 共用一套 Avalonia 桌面程序:相机采集、双手关键
|
||||
```powershell
|
||||
dotnet build SopHelper.Avalonia.slnx
|
||||
dotnet run --project src/SopHelper.Avalonia
|
||||
# 本机 D3 环境已安装在 E:\D3Lite 时,启动/复用服务并打开界面:
|
||||
# 本机 D3 环境已安装在 程序目录下的 D3Nano 时,启动/复用服务并打开界面:
|
||||
pwsh -File tools/Start-HandAiD3.ps1
|
||||
```
|
||||
|
||||
@ -22,11 +22,8 @@ pwsh -File tools/Start-HandAiD3.ps1
|
||||
djev 是独立服务,默认地址 `http://127.0.0.1:8766/v1/systemone`,不随桌面程序一起打包。
|
||||
具体部署、协议和性能记录见 [HAND_AI.md](HAND_AI.md)。
|
||||
|
||||
启动软件时会自动检查并启动本机已安装的 djev(Windows 默认 `E:\D3Lite`,可设 `SOPHELPER_D3_ROOT`)。
|
||||
已运行则复用,载入和失败信息写入运行日志;不会重复启动,也不会自动开始相机采集。
|
||||
退出软件时先取消模型启动等待,再停止有有效进程记录的本机 djev(包括启动时复用的服务),释放模型资源;远程服务不受影响。
|
||||
|
||||
“运行设置 → djev 判定”可配置 `lite` / `nano` 启动档位及模型目录,点击“保存启动配置”后在下次 djev 服务启动时生效;当前已运行服务继续复用。
|
||||
启动软件时会自动检查并启动本机 djev Nano。安装目录固定为程序所在目录的 `D3Nano/`,其中包含 `model/`、`.venv/` 和 `local-model-manifest.json`。
|
||||
已就绪的 Nano 服务可直接复用,载入和失败信息写入运行日志。退出时先取消模型启动等待,再停止可识别的本机服务,远程服务继续运行。
|
||||
|
||||
## 操作流程
|
||||
|
||||
|
||||
@ -25,14 +25,14 @@ Windows 工位机用 SSH/SFTP 部署,目录约定与 `tools/Deploy-Linux.ps1`
|
||||
|
||||
```powershell
|
||||
# 打包模型与离线 wheel、传输、远端建 .venv、用真实图片验收后释放临时模型
|
||||
.\tools\Deploy-D3Nano.ps1 -Target Administrator@192.168.0.184 -InstallRoot D:\D3Nano
|
||||
.\tools\Deploy-D3Nano.ps1 -Target Administrator@192.168.0.184 -InstallRoot C:\sophelper\current\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`,
|
||||
- `tools/windows/install-d3nano.ps1` 解包模型、装 Python(缺则 winget)、建 `.venv`、离线装依赖,将运行环境安装到程序目录下的 `D3Nano`,
|
||||
最后校验显卡与算力,禁用旧安装的 djev 自启任务。桌面软件启动时直接拉起本机 djev,正常退出时关闭。
|
||||
- 部署验收使用 `d3nano-service.py verify`,用真实相机 JPEG 核对 noul 结果与耗时,只回收本次验收启动的服务。
|
||||
|
||||
|
||||
3
djev.cmd
3
djev.cmd
@ -1,3 +0,0 @@
|
||||
@echo off
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0tools\Switch-Djev.ps1" %*
|
||||
exit /b %errorlevel%
|
||||
@ -233,7 +233,7 @@ public partial class App : PrismApplication
|
||||
// 不使用 HttpClient 的全局超时;单次探测及整体启动期限由启动服务自行控制。
|
||||
// 将响应缓冲上限设为 64 KiB,健康检查无需接收大型响应。
|
||||
using var http=new System.Net.Http.HttpClient { Timeout=Timeout.InfiniteTimeSpan, MaxResponseContentBufferSize=65536 };
|
||||
// 从环境变量和默认目录生成配置,包含接口地址、本机 Python/启动脚本和日志位置。
|
||||
// 从接口环境变量和程序目录生成配置,包含接口地址、本机 Python/启动脚本和日志位置。
|
||||
var options=_d3Options=D3StartupOptions.FromEnvironment(AppContext.BaseDirectory,Presentation.DesktopPlatform.WorkspaceRoot);
|
||||
// 将启动过程中的状态文本交给视图模型;视图模型负责调度到界面线程更新日志。
|
||||
var progress=new Progress<string>(message=>sop.ReportD3Service(message));
|
||||
|
||||
@ -78,34 +78,6 @@
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
<Border Classes="panel">
|
||||
<StackPanel Spacing="8">
|
||||
<TextBlock Text="djev 判定" Classes="Title" />
|
||||
<!-- 档位属于服务启动配置,与当前已运行服务和配方分开显示。 -->
|
||||
<Grid ColumnDefinitions="Auto,*,Auto">
|
||||
<TextBlock Text="启动档位" VerticalAlignment="Center" Margin="0,0,12,0" />
|
||||
<ComboBox x:Name="DjevTierInput" Grid.Column="1" ItemsSource="{Binding DjevTiers}" SelectedItem="{Binding DjevTier, Mode=TwoWay}"
|
||||
IsEnabled="{Binding CanChangeModels}" HorizontalAlignment="Left" Width="120" />
|
||||
<Button x:Name="SaveDjevTierButton" Grid.Column="2" Content="保存启动配置" Command="{Binding SaveDjevSelectionCommand}" />
|
||||
</Grid>
|
||||
<Grid ColumnDefinitions="Auto,*" IsEnabled="{Binding CanChangeModels}">
|
||||
<TextBlock Text="lite 模型目录" VerticalAlignment="Center" Margin="0,0,12,0" />
|
||||
<TextBox Grid.Column="1" Text="{Binding DjevLiteRoot, Mode=TwoWay}" />
|
||||
</Grid>
|
||||
<Grid ColumnDefinitions="Auto,*" IsEnabled="{Binding CanChangeModels}">
|
||||
<TextBlock Text="nano 模型目录" VerticalAlignment="Center" Margin="0,0,12,0" />
|
||||
<TextBox Grid.Column="1" Text="{Binding DjevNanoRoot, Mode=TwoWay}" />
|
||||
</Grid>
|
||||
<TextBlock Text="配置本机 djev 的 lite / nano 档位,点击保存后在下次服务启动时生效。当前服务继续运行;退出软件会停止有有效进程记录的本机服务,再次启动时使用保存配置。" Foreground="{StaticResource FgDim}" TextWrapping="Wrap" />
|
||||
<TextBlock Text="{Binding DjevSelectionStatus}" Foreground="{StaticResource FgDim}" TextWrapping="Wrap" />
|
||||
<Grid ColumnDefinitions="Auto,*">
|
||||
<TextBlock Text="判定超时(ms)" VerticalAlignment="Center" Margin="0,0,12,0" />
|
||||
<NumericUpDown x:Name="DjevTimeoutInput" Grid.Column="1" Value="{Binding DjevTimeoutMs}" Minimum="1" Maximum="1000" Increment="1"
|
||||
IsEnabled="{Binding CanChangeSettings}" HorizontalAlignment="Left" Width="120" />
|
||||
</Grid>
|
||||
<TextBlock Text="全局生效,独立保存,不随配方切换。范围1–1000 ms,默认300 ms;只计算请求发给djev后等待响应的时间。修改后在下次判定或开始运行时生效。" Foreground="{StaticResource FgDim}" TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
<Border Classes="panel">
|
||||
<StackPanel Spacing="8">
|
||||
<TextBlock Text="当前已应用配方" Classes="Title" />
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
// 运行设置视图:提供自动登录、相机与配方、djev 启动档位等全局配置的编辑入口。
|
||||
// 运行设置视图:提供自动登录、相机、配方与流程参数等全局配置的编辑入口。
|
||||
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Interactivity;
|
||||
|
||||
@ -175,8 +175,6 @@ public class SopPageViewModel : ViewModelBase
|
||||
catch (Exception error) { Log("warn", "打开配方目录失败:" + error.Message); }
|
||||
}, () => !string.IsNullOrWhiteSpace(SelectedRecipe));
|
||||
|
||||
SaveDjevSelectionCommand = ConfigurationCommand(SaveDjevSelection, () => CanSelectCamera && _djevSelectionStore is not null, true);
|
||||
LoadDjevSelection();
|
||||
|
||||
StatusText = "就绪,请确认运行设置后开始";
|
||||
LoadLastCamera();
|
||||
@ -400,60 +398,13 @@ public class SopPageViewModel : ViewModelBase
|
||||
get => _runtimeOptions.ResetDelaySec;
|
||||
set { if (!CanChangeSettings || value == ResetDelaySec) return; _runtimeOptions.ResetDelaySec = Math.Max(1, value); SaveRuntimeOptions(); }
|
||||
}
|
||||
public int DjevTimeoutMs
|
||||
{
|
||||
get => _runtimeOptions.DjevTimeoutMs;
|
||||
set { if (!CanChangeSettings || value == DjevTimeoutMs) return; _runtimeOptions.DjevTimeoutMs = value; SaveRuntimeOptions(); }
|
||||
}
|
||||
|
||||
private bool _accessReady;
|
||||
private DjevSelectionStore? _djevSelectionStore;
|
||||
private string _djevTier = "lite", _djevLiteRoot = "", _djevNanoRoot = "", _djevSelectionStatus = "";
|
||||
public IReadOnlyList<string> DjevTiers { get; } = new[] { "lite", "nano" };
|
||||
public string DjevTier { get => _djevTier; set { if (CanChangeModels) SetProperty(ref _djevTier, value); } }
|
||||
public string DjevLiteRoot { get => _djevLiteRoot; set { if (CanChangeModels) SetProperty(ref _djevLiteRoot, value); } }
|
||||
public string DjevNanoRoot { get => _djevNanoRoot; set { if (CanChangeModels) SetProperty(ref _djevNanoRoot, value); } }
|
||||
public string DjevSelectionStatus { get => _djevSelectionStatus; private set => SetProperty(ref _djevSelectionStatus, value); }
|
||||
public DelegateCommand SaveDjevSelectionCommand { get; private set; } = null!;
|
||||
|
||||
/// <summary>读取与自动启动相同的安装配置;远程服务由服务所在机器配置档位。</summary>
|
||||
private void LoadDjevSelection()
|
||||
{
|
||||
try
|
||||
{
|
||||
var options = D3StartupOptions.FromEnvironment(AppContext.BaseDirectory, DesktopPlatform.WorkspaceRoot);
|
||||
if (!options.Endpoint.IsLoopback)
|
||||
{
|
||||
DjevSelectionStatus = "当前使用远程 djev,请在服务所在机器配置档位。";
|
||||
return;
|
||||
}
|
||||
_djevSelectionStore = new(options.Root, options.Endpoint.Port);
|
||||
var selection = _djevSelectionStore.Read();
|
||||
_djevTier = selection.Tier; _djevLiteRoot = selection.LiteRoot; _djevNanoRoot = selection.NanoRoot;
|
||||
DjevSelectionStatus = "启动配置:" + _djevSelectionStore.FilePath;
|
||||
}
|
||||
catch (Exception error) when (error is IOException or UnauthorizedAccessException or JsonException or InvalidOperationException or ArgumentException)
|
||||
{ DjevSelectionStatus = "读取 djev 配置失败:" + error.Message; }
|
||||
SaveDjevSelectionCommand.RaiseCanExecuteChanged();
|
||||
}
|
||||
|
||||
/// <summary>明确保存下次启动选择,保持当前服务运行;保存失败不显示成功或覆盖旧文件。</summary>
|
||||
private void SaveDjevSelection()
|
||||
{
|
||||
if (!CanChangeModels || _djevSelectionStore is null) return;
|
||||
try
|
||||
{
|
||||
_djevSelectionStore.Save(new(DjevTier, DjevLiteRoot, DjevNanoRoot));
|
||||
DjevSelectionStatus = $"已保存 {DjevTier},下次 djev 服务启动时生效。当前服务继续运行;退出软件会停止有有效进程记录的本机服务,再次启动时使用保存配置。";
|
||||
Log("info", DjevSelectionStatus);
|
||||
}
|
||||
catch (Exception error) when (error is IOException or UnauthorizedAccessException or JsonException or InvalidOperationException or ArgumentException)
|
||||
{ DjevSelectionStatus = "保存 djev 配置失败:" + error.Message; }
|
||||
}
|
||||
/// <summary>保存独立运行参数,供下次启动流程时读取。</summary>
|
||||
private void SaveRuntimeOptions()
|
||||
{
|
||||
_runtimeStore.Save(_runtimeOptions);
|
||||
RaisePropertyChanged(nameof(FrameStride)); RaisePropertyChanged(nameof(AutoResetOnComplete)); RaisePropertyChanged(nameof(ResetDelaySec)); RaisePropertyChanged(nameof(DjevTimeoutMs));
|
||||
RaisePropertyChanged(nameof(FrameStride)); RaisePropertyChanged(nameof(AutoResetOnComplete)); RaisePropertyChanged(nameof(ResetDelaySec));
|
||||
}
|
||||
|
||||
/// <summary>打开所选相机的独立配置窗口</summary>
|
||||
@ -536,7 +487,6 @@ public class SopPageViewModel : ViewModelBase
|
||||
ImportRecipeCommand?.RaiseCanExecuteChanged();
|
||||
ExportRecipeCommand?.RaiseCanExecuteChanged();
|
||||
OpenRecipeFolderCommand?.RaiseCanExecuteChanged();
|
||||
SaveDjevSelectionCommand?.RaiseCanExecuteChanged();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -1069,7 +1019,7 @@ public class SopPageViewModel : ViewModelBase
|
||||
var config = SopConfigLoader.Load(path);
|
||||
_runtimeOptions = _runtimeStore.LoadOrMigrate(config);
|
||||
_runtimeOptions.Apply(config);
|
||||
RaisePropertyChanged(nameof(FrameStride)); RaisePropertyChanged(nameof(AutoResetOnComplete)); RaisePropertyChanged(nameof(ResetDelaySec)); RaisePropertyChanged(nameof(DjevTimeoutMs));
|
||||
RaisePropertyChanged(nameof(FrameStride)); RaisePropertyChanged(nameof(AutoResetOnComplete)); RaisePropertyChanged(nameof(ResetDelaySec));
|
||||
|
||||
_engine.Load(config);
|
||||
|
||||
|
||||
@ -12,24 +12,12 @@ public sealed record D3StartupOptions(Uri Endpoint, string Root, string Python,
|
||||
public string MarkerPath => Path.Combine(Root, $"sophelper-d3-{Endpoint.Port}.json");
|
||||
public string LockPath => Path.Combine(Root, $"sophelper-d3-{Endpoint.Port}.lock");
|
||||
|
||||
/// <summary>读取启动配置;Windows 桌面会话尚未继承新环境变量时,直接读取用户和机器持久配置。</summary>
|
||||
/// <param name="applicationDirectory">包含服务脚本的程序目录。</param>
|
||||
/// <summary>本机模型和 Python 环境固定在程序目录下的 D3Nano;接口地址仍可由环境配置。</summary>
|
||||
/// <param name="applicationDirectory">包含服务脚本和 D3Nano 的程序目录。</param>
|
||||
/// <param name="workspace">保存服务日志的工作区。</param>
|
||||
/// <param name="readEnvironment">环境读取器;默认读取系统环境,可注入以验证旧会话的配置回退。</param>
|
||||
public static D3StartupOptions FromEnvironment(string applicationDirectory, string workspace,
|
||||
Func<string, EnvironmentVariableTarget, string?>? readEnvironment = null)
|
||||
public static D3StartupOptions FromEnvironment(string applicationDirectory, string workspace)
|
||||
{
|
||||
readEnvironment ??= Environment.GetEnvironmentVariable;
|
||||
var configuredRoot = readEnvironment("SOPHELPER_D3_ROOT", EnvironmentVariableTarget.Process);
|
||||
// setx /M 不会更新已运行的 Explorer。保留进程显式覆盖,仅在缺省时读取注册表,安装后无需注销桌面。
|
||||
if (OperatingSystem.IsWindows() && string.IsNullOrWhiteSpace(configuredRoot))
|
||||
{
|
||||
configuredRoot = readEnvironment("SOPHELPER_D3_ROOT", EnvironmentVariableTarget.User);
|
||||
if (string.IsNullOrWhiteSpace(configuredRoot))
|
||||
configuredRoot = readEnvironment("SOPHELPER_D3_ROOT", EnvironmentVariableTarget.Machine);
|
||||
}
|
||||
var root = Path.GetFullPath((string.IsNullOrWhiteSpace(configuredRoot) ? null : configuredRoot)
|
||||
?? (OperatingSystem.IsWindows() ? @"E:\D3Lite" : Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "D3Lite")));
|
||||
var root = Path.GetFullPath(Path.Combine(applicationDirectory, "D3Nano"));
|
||||
return new(new Uri(Environment.GetEnvironmentVariable("SOPHELPER_VISION_ENDPOINT") ?? "http://127.0.0.1:8766/v1/systemone"),
|
||||
root, Path.Combine(root, ".venv", OperatingSystem.IsWindows() ? @"Scripts\python.exe" : "bin/python"),
|
||||
Path.Combine(applicationDirectory, "services", "start_d3_lite_local.py"), Path.Combine(workspace, "logs", "d3-service"),
|
||||
@ -59,7 +47,7 @@ public sealed class D3ServiceStartup(HttpClient http, ID3ServiceProcess process)
|
||||
public async Task StopAsync(D3StartupOptions options, CancellationToken token)
|
||||
{
|
||||
if (!IsLocal(options.Endpoint) || !Directory.Exists(options.Root)) return;
|
||||
// 与启动、档位切换共用锁;调用方须先取消并等待本应用的启动任务,避免关停后又被拉起。
|
||||
// 与启动共用锁;调用方须先取消并等待本应用的启动任务,避免关停后又被拉起。
|
||||
FileStream? shutdownLock = null;
|
||||
try
|
||||
{
|
||||
@ -102,11 +90,11 @@ public sealed class D3ServiceStartup(HttpClient http, ID3ServiceProcess process)
|
||||
progress?.Report("检查 djev 服务");
|
||||
var health = await ProbeAsync(options, ct).ConfigureAwait(false);
|
||||
if (health == Health.Ready) return new(true, false, "djev 服务已就绪,复用现有服务");
|
||||
if (health == Health.OtherService) return new(false, false, "djev 端口被其他服务占用");
|
||||
if (health == Health.OtherService) return new(false, false, "djev 端口已被占用,需要支持图片的 Nano 服务");
|
||||
if (health == Health.Starting) return await WaitReadyAsync(null).ConfigureAwait(false);
|
||||
if (options.Endpoint.Scheme != "http") return new(false, false, "本机 djev 自动启动仅支持 HTTP 接口");
|
||||
if (!File.Exists(options.Python) || !File.Exists(Path.Combine(options.Root, "model", "decision_config.json")) || !File.Exists(options.Script))
|
||||
return new(false, false, "djev 本地环境缺失,请检查模型安装目录和服务脚本");
|
||||
return new(false, false, "djev 本地环境缺失,请检查程序目录下的 D3Nano 和服务脚本");
|
||||
// 跨进程串行启动;模型载入期间端口可能尚未监听,不能仅凭连接失败重复拉起。
|
||||
while (startupLock is null)
|
||||
{
|
||||
@ -116,7 +104,7 @@ public sealed class D3ServiceStartup(HttpClient http, ID3ServiceProcess process)
|
||||
}
|
||||
health = await ProbeAsync(options, ct).ConfigureAwait(false);
|
||||
if (health == Health.Ready) return new(true, false, "djev 服务已就绪,复用现有服务");
|
||||
if (health == Health.OtherService) return new(false, false, "djev 端口被其他服务占用");
|
||||
if (health == Health.OtherService) return new(false, false, "djev 端口已被占用,需要支持图片的 Nano 服务");
|
||||
if (health == Health.Starting) return await WaitReadyAsync(null).ConfigureAwait(false);
|
||||
D3ProcessMarker? marker = null;
|
||||
try
|
||||
@ -141,7 +129,7 @@ public sealed class D3ServiceStartup(HttpClient http, ID3ServiceProcess process)
|
||||
ct.ThrowIfCancellationRequested();
|
||||
health = await ProbeAsync(options, ct).ConfigureAwait(false);
|
||||
if (health == Health.Ready) return new(true, started, started ? "djev 已自动启动并就绪" : "djev 已就绪");
|
||||
if (health == Health.OtherService) return new(false, started, "djev 端口被其他服务占用");
|
||||
if (health == Health.OtherService) return new(false, started, "djev 端口已被占用,需要支持图片的 Nano 服务");
|
||||
if (active is not null && !process.IsAlive(active)) return new(false, started, $"djev 启动失败,日志:{options.LogDirectory}");
|
||||
await Task.Delay(options.PollInterval, ct).ConfigureAwait(false);
|
||||
}
|
||||
@ -165,7 +153,7 @@ public sealed class D3ServiceStartup(HttpClient http, ID3ServiceProcess process)
|
||||
using var response = await http.GetAsync(healthUri, deadline.Token).ConfigureAwait(false);
|
||||
if (!response.IsSuccessStatusCode) return Health.OtherService;
|
||||
using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync(deadline.Token).ConfigureAwait(false));
|
||||
if (!body.RootElement.TryGetProperty("model", out var model) || model.GetString() is not ("d3-lite" or "d3-nano")) return Health.OtherService;
|
||||
if (!body.RootElement.TryGetProperty("model", out var model) || model.GetString() != "d3-nano") return Health.OtherService;
|
||||
if (body.RootElement.TryGetProperty("status", out var status) && status.GetString() == "ready"
|
||||
&& body.RootElement.TryGetProperty("modalities", out var modes) && modes.EnumerateArray().Any(mode => mode.GetString() == "image"))
|
||||
return Health.Ready;
|
||||
|
||||
@ -1,71 +0,0 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace SopHelper.Engine.Sop;
|
||||
|
||||
/// <summary>本机 djev 下次启动所用的档位与模型目录;不代表当前端口上的实际服务。</summary>
|
||||
public sealed record DjevSelection(string Tier, string LiteRoot, string NanoRoot);
|
||||
|
||||
/// <summary>与 Python 启动器共用安装目录的 djev.json,保留扩展字段并原子替换配置。</summary>
|
||||
public sealed class DjevSelectionStore(string root, int port = 8766)
|
||||
{
|
||||
public string FilePath => Path.Combine(root, "djev.json");
|
||||
|
||||
/// <summary>兼容没有配置和仅配置 nano_root 的旧安装;Nano 独立安装默认寻找同级 Lite。</summary>
|
||||
public DjevSelection Read()
|
||||
{
|
||||
var config = ReadDocument();
|
||||
var isNano = false;
|
||||
var manifest = Path.Combine(root, "model", "MODEL_MANIFEST.json");
|
||||
if (File.Exists(manifest))
|
||||
{
|
||||
using var package = JsonDocument.Parse(File.ReadAllText(manifest));
|
||||
isNano = package.RootElement.TryGetProperty("model_name", out var model) && model.GetString() == "d3-nano";
|
||||
}
|
||||
// 没有选择文件时启动器直接使用根目录;已有文件缺少 tier 则应报错,不能显示为成功回退。
|
||||
var tier = config["tier"]?.GetValue<string>() ?? (File.Exists(FilePath)
|
||||
? throw new InvalidOperationException("djev 配置缺少 tier 档位") : isNano ? "nano" : "lite");
|
||||
ValidateTier(tier);
|
||||
return new(tier, Resolve(config["lite_root"]?.GetValue<string>(), isNano ? Path.Combine(root, "..", "D3Lite") : root),
|
||||
Resolve(config["nano_root"]?.GetValue<string>(), isNano ? root : Path.Combine(root, "..", "D3Nano")));
|
||||
}
|
||||
|
||||
/// <summary>只保存已安装且档位匹配的目标,不下载模型、不终止或重启服务;失败时保留旧配置。</summary>
|
||||
public void Save(DjevSelection selection)
|
||||
{
|
||||
ValidateTier(selection.Tier);
|
||||
var lite = Resolve(selection.LiteRoot, root);
|
||||
var nano = Resolve(selection.NanoRoot, Path.Combine(root, "..", "D3Nano"));
|
||||
var target = selection.Tier == "lite" ? lite : nano;
|
||||
var manifest = Path.Combine(target, "model", "MODEL_MANIFEST.json");
|
||||
if (!File.Exists(manifest) || !File.Exists(Path.Combine(target, "model", "decision_config.json")))
|
||||
throw new InvalidOperationException($"未找到 djev {selection.Tier} 模型,请检查目录:{target}");
|
||||
using var package = JsonDocument.Parse(File.ReadAllText(manifest));
|
||||
if (!package.RootElement.TryGetProperty("model_name", out var model) || model.GetString() != "d3-" + selection.Tier)
|
||||
throw new InvalidOperationException("模型目录与所选 djev 档位不匹配");
|
||||
// 与自动启动共用锁,避免加载模型时更改其选择;保留其他工具写入的扩展字段。
|
||||
using var startupLock = new FileStream(Path.Combine(root, $"sophelper-d3-{port}.lock"), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
|
||||
var config = ReadDocument();
|
||||
config["tier"] = selection.Tier;
|
||||
config["lite_root"] = lite;
|
||||
config["nano_root"] = nano;
|
||||
var temp = FilePath + ".tmp";
|
||||
try
|
||||
{
|
||||
File.WriteAllText(temp, config.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));
|
||||
File.Move(temp, FilePath, overwrite: true);
|
||||
}
|
||||
finally { if (File.Exists(temp)) File.Delete(temp); }
|
||||
}
|
||||
|
||||
private JsonObject ReadDocument() => File.Exists(FilePath)
|
||||
? JsonNode.Parse(File.ReadAllText(FilePath)) as JsonObject ?? throw new JsonException("djev 配置必须为 JSON 对象")
|
||||
: new JsonObject();
|
||||
|
||||
private string Resolve(string? path, string fallback) => Path.GetFullPath(string.IsNullOrWhiteSpace(path) ? fallback : path, Path.GetFullPath(root));
|
||||
|
||||
private static void ValidateTier(string tier)
|
||||
{
|
||||
if (tier is not ("lite" or "nano")) throw new InvalidOperationException("djev 档位必须为 lite 或 nano");
|
||||
}
|
||||
}
|
||||
@ -55,23 +55,6 @@ internal static class Smoke
|
||||
var previousRoot=Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT");
|
||||
var dataRoot=Path.Combine(Path.GetTempPath(),"sophelper-layout-smoke-"+Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(dataRoot);
|
||||
var djevSettingsOnly = args.Contains("--djev-settings-only");
|
||||
var djevEnvironment = new[] { "SOPHELPER_D3_ROOT", "SOPHELPER_VISION_ENDPOINT", "SOPHELPER_VISION_PROVIDER" }
|
||||
.ToDictionary(name => name, Environment.GetEnvironmentVariable);
|
||||
if (djevSettingsOnly)
|
||||
{
|
||||
// 假安装与服务提供方隔离保证界面测试不加载模型、不更改真实服务配置。
|
||||
foreach (var tier in new[] { "lite", "nano" })
|
||||
{
|
||||
var modelPath = Path.Combine(dataRoot, tier == "lite" ? "D3Lite" : "D3Nano", "model");
|
||||
Directory.CreateDirectory(modelPath);
|
||||
File.WriteAllText(Path.Combine(modelPath, "MODEL_MANIFEST.json"), JsonSerializer.Serialize(new { model_name = "d3-" + tier }));
|
||||
File.WriteAllText(Path.Combine(modelPath, "decision_config.json"), "{}");
|
||||
}
|
||||
Environment.SetEnvironmentVariable("SOPHELPER_D3_ROOT", Path.Combine(dataRoot, "D3Lite"));
|
||||
Environment.SetEnvironmentVariable("SOPHELPER_VISION_ENDPOINT", "http://127.0.0.1:8766/v1/systemone");
|
||||
Environment.SetEnvironmentVariable("SOPHELPER_VISION_PROVIDER", "test");
|
||||
}
|
||||
if(_agentSettingsFile is not null)
|
||||
{
|
||||
Directory.CreateDirectory(Path.Combine(dataRoot,"workspace"));
|
||||
@ -101,8 +84,6 @@ internal static class Smoke
|
||||
if(settingsBefore is not null)File.WriteAllBytes(settingsPath,settingsBefore);
|
||||
else if(File.Exists(settingsPath))File.Delete(settingsPath);
|
||||
Environment.SetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT",previousRoot);
|
||||
if (djevSettingsOnly)
|
||||
foreach (var item in djevEnvironment) Environment.SetEnvironmentVariable(item.Key, item.Value);
|
||||
if(!Path.GetFullPath(dataRoot).StartsWith(Path.GetFullPath(Path.GetTempPath())))throw new Exception("Unexpected test data root");
|
||||
Directory.Delete(dataRoot,true);
|
||||
}
|
||||
@ -156,33 +137,6 @@ internal static class Smoke
|
||||
Check(!window.IsVisible&&!File.Exists(options.MarkerPath)&&Camera.DisposeCount>0,"启动任务完成后清理模型记录、关闭窗口并释放相机");
|
||||
_exit=0;return;
|
||||
}
|
||||
if (Environment.GetCommandLineArgs().Contains("--djev-settings-only"))
|
||||
{
|
||||
var model = app.Container.Resolve<SopPageViewModel>();
|
||||
var view = new SopHelper.VVMs.RuntimeSettings.RuntimeSettings(model);
|
||||
var dialog = new Window { Content = view, Width = 900, Height = 900 };
|
||||
dialog.Show(); await Task.Delay(60);
|
||||
try
|
||||
{
|
||||
var tier = view.FindControl<ComboBox>("DjevTierInput")!;
|
||||
var save = view.FindControl<Button>("SaveDjevTierButton")!;
|
||||
Check((string?)tier.SelectedItem == "lite" && save.IsEnabled, "界面恢复默认Lite启动档位并允许保存");
|
||||
tier.SelectedItem = "nano"; await Task.Delay(30);
|
||||
save.Command!.Execute(null);
|
||||
var store = new SopHelper.Engine.Sop.DjevSelectionStore(Environment.GetEnvironmentVariable("SOPHELPER_D3_ROOT")!);
|
||||
Check(store.Read().Tier == "nano" && model.DjevSelectionStatus.Contains("已保存 nano"), "界面选择Nano并保存到启动器共用配置");
|
||||
model.IsRunning = true; await Task.Delay(30);
|
||||
Check(!tier.IsEffectivelyEnabled && !save.IsEffectivelyEnabled && !model.SaveDjevSelectionCommand.CanExecute(), "运行期间禁用档位选择和保存");
|
||||
model.IsRunning = false;
|
||||
tier.SelectedItem = "lite"; await Task.Delay(30); save.Command.Execute(null);
|
||||
Check(store.Read().Tier == "lite", "界面支持从Nano改回Lite");
|
||||
using var rendered = new RenderTargetBitmap(new PixelSize(900,900)); rendered.Render(dialog);
|
||||
var screenshots = Path.GetFullPath("../scratch/screenshots"); Directory.CreateDirectory(screenshots);
|
||||
rendered.Save(Path.Combine(screenshots, "djev-settings.png"));
|
||||
}
|
||||
finally { model.IsRunning = false; dialog.Close(); }
|
||||
_exit = 0; return;
|
||||
}
|
||||
if(Environment.GetCommandLineArgs().Contains("--check-progress-only"))
|
||||
{ await CheckRemainingWindowProgress(app,window);_exit=0;return; }
|
||||
if(Environment.GetCommandLineArgs().Contains("--standard-sop-only"))
|
||||
@ -277,18 +231,20 @@ internal static class Smoke
|
||||
var dialog=new Window{Content=view,Width=900,Height=720};dialog.Show();await Task.Delay(100);
|
||||
try
|
||||
{
|
||||
var deadline = view.FindControl<NumericUpDown>("DjevTimeoutInput")!;
|
||||
Check(deadline.Minimum==1&&deadline.Maximum==1000&&deadline.Value==300&&model.DjevTimeoutMs==300,
|
||||
"全局djev超时范围1–1000ms,默认300ms");
|
||||
// 旧工作区的判定超时继续生效,运行设置界面只调整其余运行参数。
|
||||
RuntimeSettingsStore.Current.Save(new RuntimeOptions { DjevTimeoutMs = 375 });
|
||||
model.ApplyRecipeCommand.Execute();
|
||||
Check(!view.GetVisualDescendants().OfType<TextBlock>().Any(text => text.Text?.Contains("djev", StringComparison.OrdinalIgnoreCase) == true)
|
||||
&& view.FindControl<NumericUpDown>("DjevTimeoutInput") is null
|
||||
&& view.FindControl<ComboBox>("DjevTierInput") is null, "运行设置已移除 djev 区块");
|
||||
view.GetVisualDescendants().OfType<Slider>().Single().Value=3;
|
||||
view.FindControl<CheckBox>("AutoResetCheckBox")!.IsChecked=false;
|
||||
view.FindControl<NumericUpDown>("ResetDelayInput")!.Value=4;
|
||||
view.FindControl<NumericUpDown>("DjevTimeoutInput")!.Value=375;
|
||||
await Task.Delay(50);
|
||||
var saved=RuntimeSettingsStore.Current.Read()!;
|
||||
Check(model.FrameStride==3&&!model.AutoResetOnComplete&&model.ResetDelaySec==4
|
||||
&&saved.FrameStride==3&&!saved.AutoResetOnComplete&&saved.ResetDelaySec==4
|
||||
&&model.DjevTimeoutMs==375&&saved.DjevTimeoutMs==375,"运行设置控件绑定并独立自动保存djev超时等运行参数");
|
||||
&&saved.DjevTimeoutMs==375,"自动保存运行参数时保留既有判定超时");
|
||||
Check(new RuntimeSettingsStore(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!).Read()!.DjevTimeoutMs==375,
|
||||
"新建设置存储实例仍能恢复全局djev超时");
|
||||
model.ApplyRecipeCommand.Execute();
|
||||
@ -296,9 +252,9 @@ internal static class Smoke
|
||||
Check(engine.Config.Sop.Settings.FrameStride==3&&!engine.Config.Sop.Settings.AutoResetOnComplete&&engine.Config.Sop.Settings.ResetDelaySec==4&&engine.Config.Sop.Settings.DjevTimeoutMs==375,
|
||||
"应用配方不会覆盖运行设置,并传给引擎");
|
||||
model.IsRunning=true;await Task.Delay(30);
|
||||
Check(!view.FindControl<CheckBox>("AutoResetCheckBox")!.IsEnabled&&!view.FindControl<NumericUpDown>("ResetDelayInput")!.IsEnabled&&!view.FindControl<NumericUpDown>("DjevTimeoutInput")!.IsEnabled,"运行中禁止修改运行参数及djev超时");
|
||||
model.AutoResetOnComplete=true;model.FrameStride=8;model.ResetDelaySec=20;model.DjevTimeoutMs=900;
|
||||
Check(model.FrameStride==3&&!model.AutoResetOnComplete&&model.ResetDelaySec==4&&model.DjevTimeoutMs==375,"运行中参数赋值也不会覆盖已保存设置");
|
||||
Check(!view.FindControl<CheckBox>("AutoResetCheckBox")!.IsEnabled&&!view.FindControl<NumericUpDown>("ResetDelayInput")!.IsEnabled,"运行中禁止修改运行参数");
|
||||
model.AutoResetOnComplete=true;model.FrameStride=8;model.ResetDelaySec=20;
|
||||
Check(model.FrameStride==3&&!model.AutoResetOnComplete&&model.ResetDelaySec==4,"运行中参数赋值也不会覆盖已保存设置");
|
||||
model.IsRunning=false;
|
||||
using var rendered=new RenderTargetBitmap(new PixelSize(900,720));rendered.Render(dialog);
|
||||
var screenshots=Path.Combine(Directory.GetCurrentDirectory(),"..","scratch","screenshots");Directory.CreateDirectory(screenshots);
|
||||
@ -1726,12 +1682,7 @@ internal static class Smoke
|
||||
var settings = new SopHelper.VVMs.RuntimeSettings.RuntimeSettings(model);
|
||||
var dialog = new Window { Content = settings, Width = 900, Height = 900 };
|
||||
dialog.Show(); await Task.Delay(60);
|
||||
Check(!settings.FindControl<ComboBox>("DjevTierInput")!.IsEffectivelyEnabled
|
||||
&& settings.FindControl<NumericUpDown>("DjevTimeoutInput")!.IsEffectivelyEnabled, "工艺师禁用模型档位但可修改运行超时");
|
||||
var tier = model.DjevTier; model.DjevTier = tier == "lite" ? "nano" : "lite";
|
||||
Check(model.DjevTier == tier && model.SaveDjevSelectionCommand.CanExecute(), "工艺师不能修改模型档位,保留保存按钮用于权限提示");
|
||||
model.SaveDjevSelectionCommand.Execute();
|
||||
await CheckPermissionPrompt("工艺师点击保存模型配置弹出无权限提示");
|
||||
Check(settings.FindControl<NumericUpDown>("ResetDelayInput")!.IsEffectivelyEnabled, "工艺师可修改运行参数");
|
||||
window.GetVisualDescendants().OfType<Button>().Single(b => Equals(b.Content, "人员管理"))
|
||||
.RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));
|
||||
await CheckPermissionPrompt("工艺师点击人员管理弹出无权限提示");
|
||||
@ -1769,7 +1720,7 @@ internal static class Smoke
|
||||
model.ImportRecipeCommand.Execute(); model.ExportRecipeCommand.Execute();
|
||||
Check(model.FrameStride == previousStride && model.SelectedRecipe == previousRecipe, "直接调用和属性写入不能绕过操作员限制");
|
||||
await CheckPermissionPrompt("受限配方按钮弹出提示,连续点击只显示一个窗口");
|
||||
Check(!settings.FindControl<NumericUpDown>("DjevTimeoutInput")!.IsEffectivelyEnabled, "已打开的运行设置同步禁用");
|
||||
Check(!settings.FindControl<NumericUpDown>("ResetDelayInput")!.IsEffectivelyEnabled, "已打开的运行设置同步禁用");
|
||||
Denied(() => access.Users(), "操作员不能读取人员管理列表");
|
||||
access.Logout();
|
||||
Check(model.StartStopCommand.CanExecute() && model.NewRecipeCommand.CanExecute(), "退出登录仍保留按钮点击反馈");
|
||||
|
||||
@ -8,7 +8,7 @@ if (args.Contains("--license-only")) { LicenseTests.Run(); return; }
|
||||
// 现场排障:读取本机正式授权记录并打印状态,触发历史主板绑定记录的迁移;不签发、不兑换授权码。
|
||||
if (args.Contains("--license-check-real")) { Console.WriteLine(LicenseTests.RealStoreCheck()); return; }
|
||||
|
||||
if(args.Length==3&&args[0]=="--djev-live")
|
||||
if(args.Length==2&&args[0]=="--djev-live")
|
||||
{
|
||||
var installed=Path.GetFullPath(args[1]);
|
||||
var liveOptions=new D3StartupOptions(new("http://127.0.0.1:8766/v1/systemone"),installed,
|
||||
@ -18,31 +18,24 @@ if(args.Length==3&&args[0]=="--djev-live")
|
||||
var result=await new D3ServiceStartup(liveHttp,new D3LocalProcess()).EnsureReadyAsync(liveOptions,null,default);
|
||||
if(!result.Ready)throw new Exception(result.Message);
|
||||
using var health=JsonDocument.Parse(await liveHttp.GetStringAsync("http://127.0.0.1:8766/health"));
|
||||
if(health.RootElement.GetProperty("model").GetString()!=args[2])throw new Exception("Configured djev tier was not loaded");
|
||||
Console.WriteLine($"PASS: djev自动拉起配置档位,started={result.Started}");
|
||||
if(health.RootElement.GetProperty("model").GetString()!="d3-nano")throw new Exception("Nano was not loaded");
|
||||
Console.WriteLine($"PASS: djev自动拉起 Nano,started={result.Started}");
|
||||
return;
|
||||
}
|
||||
|
||||
static void Check(bool value,string message){if(!value)throw new Exception(message);Console.WriteLine("PASS: "+message);}
|
||||
// 模拟安装后未注销的桌面:进程环境缺少变量,但机器配置已经写入 D 盘安装目录。
|
||||
if (OperatingSystem.IsWindows())
|
||||
// 固定路径以传入的程序目录为准,历史环境变量不得改写安装位置。
|
||||
var previousRoot = Environment.GetEnvironmentVariable("SOPHELPER_D3_ROOT");
|
||||
try
|
||||
{
|
||||
var machineRoot = Path.GetFullPath(@"D:\D3Nano");
|
||||
var userRoot = Path.GetFullPath(@"D:\UserDjev");
|
||||
var processRoot = Path.GetFullPath(@"D:\ProcessDjev");
|
||||
var resolved = D3StartupOptions.FromEnvironment("app", "workspace",
|
||||
(_, target) => target == EnvironmentVariableTarget.Machine ? machineRoot : null);
|
||||
Check(resolved.Root == machineRoot && resolved.Python == Path.Combine(machineRoot, @".venv\Scripts\python.exe"),
|
||||
"旧桌面会话未继承变量时读取机器安装目录及其Python,不回退E盘");
|
||||
resolved = D3StartupOptions.FromEnvironment("app", "workspace",
|
||||
(_, target) => target == EnvironmentVariableTarget.User ? userRoot : target == EnvironmentVariableTarget.Machine ? machineRoot : " ");
|
||||
Check(resolved.Root == userRoot, "空进程变量按缺省处理,用户安装目录优先于机器配置");
|
||||
resolved = D3StartupOptions.FromEnvironment("app", "workspace",
|
||||
(_, target) => target == EnvironmentVariableTarget.Process ? processRoot : machineRoot);
|
||||
Check(resolved.Root == processRoot, "显式进程安装目录仍优先于持久配置");
|
||||
resolved = D3StartupOptions.FromEnvironment("app", "workspace", (_, _) => null);
|
||||
Check(resolved.Root == Path.GetFullPath(@"E:\D3Lite"), "未配置安装目录时保留默认Lite目录");
|
||||
Environment.SetEnvironmentVariable("SOPHELPER_D3_ROOT", "legacy-install");
|
||||
var resolved = D3StartupOptions.FromEnvironment("app", "workspace");
|
||||
var expected = Path.GetFullPath(Path.Combine("app", "D3Nano"));
|
||||
Check(resolved.Root == expected && resolved.Python == Path.Combine(expected, ".venv",
|
||||
OperatingSystem.IsWindows() ? Path.Combine("Scripts", "python.exe") : Path.Combine("bin", "python")),
|
||||
"模型和 Python 固定使用程序目录下的 D3Nano");
|
||||
}
|
||||
finally { Environment.SetEnvironmentVariable("SOPHELPER_D3_ROOT", previousRoot); }
|
||||
var root=Path.Combine(Path.GetTempPath(),"d3-startup-"+Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(Path.Combine(root,"model"));
|
||||
var python=Path.Combine(root,"python.exe");var script=Path.Combine(root,"service.py");
|
||||
@ -50,43 +43,12 @@ File.WriteAllText(python,"");File.WriteAllText(script,"");File.WriteAllText(Path
|
||||
var options=new D3StartupOptions(new("http://127.0.0.1:8766/v1/systemone"),root,python,script,Path.Combine(root,"logs"),TimeSpan.FromSeconds(2),TimeSpan.FromMilliseconds(20));
|
||||
try
|
||||
{
|
||||
// 使用隔离的假安装验证配置,不接触本机模型和当前服务。
|
||||
var liteRoot = Path.Combine(root, "D3Lite");
|
||||
var nanoRoot = Path.Combine(root, "D3Nano");
|
||||
foreach (var (directory, model) in new[] { (liteRoot, "d3-lite"), (nanoRoot, "d3-nano") })
|
||||
{
|
||||
Directory.CreateDirectory(Path.Combine(directory, "model"));
|
||||
File.WriteAllText(Path.Combine(directory, "model", "MODEL_MANIFEST.json"), JsonSerializer.Serialize(new { model_name = model }));
|
||||
File.WriteAllText(Path.Combine(directory, "model", "decision_config.json"), "{}");
|
||||
}
|
||||
var selectionStore = new DjevSelectionStore(liteRoot);
|
||||
Check(selectionStore.Read() == new DjevSelection("lite", liteRoot, nanoRoot), "没有配置时兼容默认Lite及同级Nano目录");
|
||||
File.WriteAllText(selectionStore.FilePath, "{\"tier\":\"nano\",\"nano_root\":\"../D3Nano\",\"extension\":42}");
|
||||
Check(selectionStore.Read().NanoRoot == nanoRoot, "兼容旧配置及相对模型路径");
|
||||
selectionStore.Save(new("nano", liteRoot, nanoRoot));
|
||||
Check(new DjevSelectionStore(liteRoot).Read().Tier == "nano" && File.ReadAllText(selectionStore.FilePath).Contains("extension"),
|
||||
"档位保存后重新读取且保留扩展字段");
|
||||
var originalSelection = File.ReadAllText(selectionStore.FilePath);
|
||||
var rejectedSelection = false;
|
||||
try { selectionStore.Save(new("lite", nanoRoot, nanoRoot)); } catch (InvalidOperationException) { rejectedSelection = true; }
|
||||
Check(rejectedSelection && File.ReadAllText(selectionStore.FilePath) == originalSelection, "拒绝错误档位模型且不覆盖旧配置");
|
||||
using (var held = new FileStream(Path.Combine(liteRoot, "sophelper-d3-8766.lock"), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
|
||||
{
|
||||
rejectedSelection = false;
|
||||
try { selectionStore.Save(new("lite", liteRoot, nanoRoot)); } catch (IOException) { rejectedSelection = true; }
|
||||
Check(rejectedSelection && File.ReadAllText(selectionStore.FilePath) == originalSelection, "启动期间拒绝改写选择且保留配置");
|
||||
}
|
||||
selectionStore.Save(new("lite", liteRoot, nanoRoot));
|
||||
Check(selectionStore.Read().Tier == "lite", "可从Nano保存切回Lite");
|
||||
var nanoStore = new DjevSelectionStore(nanoRoot);
|
||||
Check(nanoStore.Read().Tier == "nano" && nanoStore.Read().LiteRoot == liteRoot && nanoStore.Read().NanoRoot == nanoRoot,
|
||||
"Nano独立安装正确显示默认档位并定位两个模型目录");
|
||||
|
||||
using(var handler=new FakeHealth{Ready=true,Model="d3-nano"})using(var http=new HttpClient(handler))
|
||||
// 旧 Lite 仍可能占用端口,启动器应报告冲突并避免拉起第二个服务。
|
||||
using(var handler=new FakeHealth{Ready=true,Model="d3-lite"})using(var http=new HttpClient(handler))
|
||||
{
|
||||
var process=new FakeProcess(handler);
|
||||
var result=await new D3ServiceStartup(http,process).EnsureReadyAsync(options with {Python="absent"},null,default);
|
||||
Check(result.Ready&&!result.Started&&process.Starts==0,"快捷切换后的Nano服务直接复用,不重复加载Lite");
|
||||
var result=await new D3ServiceStartup(http,process).EnsureReadyAsync(options,null,default);
|
||||
Check(!result.Ready&&!result.Started&&process.Starts==0&&result.Message.Contains("Nano"),"已就绪的 Lite 不会被复用");
|
||||
}
|
||||
using(var handler=new FakeHealth{Ready=true})using(var http=new HttpClient(handler))
|
||||
{
|
||||
@ -186,7 +148,7 @@ try
|
||||
print('ready')
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
payload=json.dumps(dict(status='ready',model='d3-lite',modalities=['text','image'])).encode()
|
||||
payload=json.dumps(dict(status='ready',model='d3-nano',modalities=['text','image'])).encode()
|
||||
self.send_response(200);self.send_header('Content-Length',str(len(payload)));self.end_headers();self.wfile.write(payload)
|
||||
def log_message(self,*args):pass
|
||||
HTTPServer(('127.0.0.1',args.port),Handler).serve_forever()
|
||||
@ -240,7 +202,7 @@ finally
|
||||
|
||||
sealed class FakeHealth:HttpMessageHandler
|
||||
{
|
||||
public string Model="d3-lite";
|
||||
public string Model="d3-nano";
|
||||
public volatile bool Ready,Other,Warming;
|
||||
public int Requests;
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage message,CancellationToken token)
|
||||
|
||||
@ -1,54 +0,0 @@
|
||||
"""Check djev startup selection without importing torch or loading models."""
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parents[2] / "tools/start_d3_lite_local.py"
|
||||
spec = importlib.util.spec_from_file_location("djev_launcher", SCRIPT)
|
||||
launcher = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(launcher)
|
||||
|
||||
|
||||
class SelectionChecks(unittest.TestCase):
|
||||
def test_startup_selection_and_explicit_switch(self):
|
||||
with tempfile.TemporaryDirectory() as temporary:
|
||||
root = Path(temporary).resolve() / "D3Lite"
|
||||
root.mkdir()
|
||||
config = root / "djev.json"
|
||||
self.assertEqual(launcher.resolve_model_root(root), root)
|
||||
|
||||
config.write_text(json.dumps({"tier": "nano"}), encoding="utf-8-sig")
|
||||
self.assertEqual(launcher.resolve_model_root(root), root.parent / "D3Nano")
|
||||
custom = root.parent / "custom nano"
|
||||
config.write_text(json.dumps({"tier": "nano", "nano_root": str(custom)}), encoding="utf-8")
|
||||
self.assertEqual(launcher.resolve_model_root(root), custom)
|
||||
self.assertEqual(launcher.resolve_model_root(root, ignore_selection=True), root)
|
||||
config.write_text(json.dumps({"tier": "lite", "nano_root": str(custom)}), encoding="utf-8")
|
||||
self.assertEqual(launcher.resolve_model_root(root), root)
|
||||
|
||||
def test_lite_directory_from_nano_installation(self):
|
||||
# 桌面程序写入两个目录后,两种档位均按所选目录启动,不受 Python 安装位置影响。
|
||||
with tempfile.TemporaryDirectory() as temporary:
|
||||
root = Path(temporary).resolve() / "D3Nano"
|
||||
root.mkdir()
|
||||
config = root / "djev.json"
|
||||
config.write_text(json.dumps({"tier": "lite", "lite_root": "../D3Lite"}), encoding="utf-8")
|
||||
self.assertEqual(launcher.resolve_model_root(root), root.parent / "D3Lite")
|
||||
self.assertEqual(launcher.resolve_model_root(root, ignore_selection=True), root)
|
||||
|
||||
def test_invalid_selection_does_not_silently_load_another_model(self):
|
||||
with tempfile.TemporaryDirectory() as temporary:
|
||||
root = Path(temporary)
|
||||
config = root / "djev.json"
|
||||
config.write_text('{"tier":"other"}', encoding="utf-8")
|
||||
with self.assertRaises(ValueError):
|
||||
launcher.resolve_model_root(root)
|
||||
config.write_text('{broken', encoding="utf-8")
|
||||
with self.assertRaises(json.JSONDecodeError):
|
||||
launcher.resolve_model_root(root)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
30
tests/D3Startup.Smoke/test_nano_package.py
Normal file
30
tests/D3Startup.Smoke/test_nano_package.py
Normal file
@ -0,0 +1,30 @@
|
||||
"""验证 Nano 启动前的模型包校验,无需 GPU。"""
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parents[2] / "tools/start_d3_lite_local.py"
|
||||
spec = importlib.util.spec_from_file_location("djev_launcher", SCRIPT)
|
||||
launcher = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(launcher)
|
||||
|
||||
|
||||
class NanoPackageChecks(unittest.TestCase):
|
||||
def test_accepts_only_nano_in_the_given_root(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory) / "D3Nano"
|
||||
(root / "model").mkdir(parents=True)
|
||||
# 存量档位配置不能重定向模型路径。
|
||||
(root / "djev.json").write_text('{"tier":"lite","lite_root":"../D3Lite"}', encoding="utf-8")
|
||||
manifest = root / "model" / "MODEL_MANIFEST.json"
|
||||
manifest.write_text(json.dumps({"model_name": "d3-nano"}), encoding="utf-8")
|
||||
launcher.verify_nano_package(root)
|
||||
manifest.write_text(json.dumps({"model_name": "d3-lite"}), encoding="utf-8")
|
||||
with self.assertRaisesRegex(ValueError, "Expected d3-nano"):
|
||||
launcher.verify_nano_package(root)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@ -1,6 +1,6 @@
|
||||
param(
|
||||
[string]$Target = 'Administrator@192.168.0.184',
|
||||
[string]$InstallRoot = 'D:\D3Nano',
|
||||
[string]$InstallRoot = 'C:\sophelper\current\D3Nano',
|
||||
[string]$ModelSource = 'E:\D3Nano',
|
||||
[string]$WheelsSource = 'E:\00-Inbox\aisop\scratch\wheels\d3nano',
|
||||
[string]$WheelsRemote = 'D:\d3-wheels',
|
||||
@ -66,4 +66,4 @@ if (!$SkipStart) {
|
||||
& ssh -o BatchMode=yes $Target "$venvPython $InstallRoot\d3nano-service.py verify --root $InstallRoot --port $Port --script $ServiceScript --image-root $InstallRoot\benchmark"
|
||||
if ($LASTEXITCODE) { throw 'd3-nano 真实图片请求验证失败' }
|
||||
}
|
||||
Write-Host "已部署 d3-nano 到 $Target:$InstallRoot;SOPHELPER_D3_ROOT 已写入系统环境变量。"
|
||||
Write-Host "已部署 d3-nano 到 $Target:$InstallRoot。"
|
||||
|
||||
@ -1,17 +1,19 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$D3Root = 'E:\D3Lite',
|
||||
[ValidateRange(1,65535)][int]$Port = 8766,
|
||||
[switch]$CheckOnly
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$repoRoot = Split-Path -Parent $PSScriptRoot
|
||||
# 与 dotnet run 的默认 Debug 输出共用同一个 D3Nano 安装目录。
|
||||
$applicationDirectory = Join-Path $repoRoot 'src\SopHelper.Avalonia\bin\Debug\net8.0'
|
||||
$D3Root = Join-Path $applicationDirectory 'D3Nano'
|
||||
$healthUrl = "http://127.0.0.1:$Port/health"
|
||||
|
||||
function Get-D3Health {
|
||||
try {
|
||||
$health = Invoke-RestMethod -Uri $healthUrl -TimeoutSec 2
|
||||
if ($health.status -eq 'ready' -and $health.model -in @('d3-lite', 'd3-nano') -and 'image' -in $health.modalities) { return $health }
|
||||
if ($health.status -eq 'ready' -and $health.model -eq 'd3-nano' -and 'image' -in $health.modalities) { return $health }
|
||||
} catch { }
|
||||
return $null
|
||||
}
|
||||
@ -49,7 +51,7 @@ $env:SOPHELPER_VISION_PROVIDER = 'd3-lite'
|
||||
$env:SOPHELPER_VISION_ENDPOINT = "http://127.0.0.1:$Port/v1/systemone"
|
||||
Push-Location $repoRoot
|
||||
try {
|
||||
& dotnet run --project src/SopHelper.Avalonia
|
||||
& dotnet run --configuration Debug --project src/SopHelper.Avalonia
|
||||
if ($LASTEXITCODE -ne 0) { throw "SOP 程序退出,代码:$LASTEXITCODE" }
|
||||
} finally {
|
||||
Pop-Location
|
||||
|
||||
@ -1,145 +0,0 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Position=0)][ValidateSet('lite','nano','status','config')][string]$Model = 'status',
|
||||
[Parameter(Position=1)][ValidateSet('lite','nano')][string]$Tier,
|
||||
[ValidateRange(1,65535)][int]$Port = 8766,
|
||||
[string]$LiteRoot = 'E:\D3Lite',
|
||||
[string]$NanoRoot = 'E:\D3Nano'
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$repo = Split-Path -Parent $PSScriptRoot
|
||||
$roots = @{ 'd3-lite' = [IO.Path]::GetFullPath($LiteRoot); 'd3-nano' = [IO.Path]::GetFullPath($NanoRoot) }
|
||||
$endpoint = "http://127.0.0.1:$Port"
|
||||
$logs = Join-Path (Split-Path -Parent $repo) 'scratch\logs'
|
||||
$script = Join-Path $PSScriptRoot 'start_d3_lite_local.py'
|
||||
$python = Join-Path $LiteRoot '.venv\Scripts\python.exe'
|
||||
$configPath = Join-Path $LiteRoot 'djev.json'
|
||||
|
||||
function Get-ConfiguredTier {
|
||||
if (!(Test-Path -LiteralPath $configPath)) { return 'lite' }
|
||||
$config = Get-Content -LiteralPath $configPath -Raw -Encoding UTF8 | ConvertFrom-Json
|
||||
if ($config.tier -notin @('lite','nano')) { throw 'Invalid djev tier in configuration.' }
|
||||
return $config.tier
|
||||
}
|
||||
|
||||
function Save-Selection([string]$SelectedTier) {
|
||||
$temp = "$configPath.tmp"
|
||||
$config = @{ tier = $SelectedTier; nano_root = $roots['d3-nano'] } | ConvertTo-Json
|
||||
[IO.File]::WriteAllText($temp, $config, (New-Object Text.UTF8Encoding($false)))
|
||||
if (Test-Path -LiteralPath $configPath) { [IO.File]::Replace($temp, $configPath, "$configPath.bak") }
|
||||
else { [IO.File]::Move($temp, $configPath) }
|
||||
}
|
||||
|
||||
function Get-Health {
|
||||
try { return Invoke-RestMethod "$endpoint/health" -TimeoutSec 2 } catch { return $null }
|
||||
}
|
||||
|
||||
function Show-Health($Health) {
|
||||
$configured = Get-ConfiguredTier
|
||||
if ($null -eq $Health) { Write-Host "djev | Not running Configured: $configured Endpoint: $endpoint"; return }
|
||||
$tier = switch ($Health.model) { 'd3-lite' { 'lite' }; 'd3-nano' { 'nano' }; default { 'unknown' } }
|
||||
Write-Host "djev | Tier: $tier Configured: $configured Status: $($Health.status) Endpoint: $endpoint/v1/systemone"
|
||||
}
|
||||
|
||||
# Identify only known local D3 launchers, including the venv Python child on Windows.
|
||||
function Get-ManagedProcesses {
|
||||
@(Get-CimInstance Win32_Process -Filter "name='python.exe'" | Where-Object {
|
||||
$line = $_.CommandLine
|
||||
$knownRoot = $false
|
||||
foreach ($root in $roots.Values) {
|
||||
if ($line -match ('--root\s+"?' + [regex]::Escape($root) + '"?(?=\s|$)')) { $knownRoot = $true }
|
||||
}
|
||||
$knownRoot -and $line -match '(?i)[\\/]start_d3_lite_local\.py"?\s' -and
|
||||
$line -match ('--port\s+' + $Port + '(?=\s|$)')
|
||||
})
|
||||
}
|
||||
|
||||
function Stop-Managed {
|
||||
$managed = @(Get-ManagedProcesses)
|
||||
$listeners = @(Get-NetTCPConnection -LocalPort $Port -State Listen -ErrorAction SilentlyContinue)
|
||||
foreach ($listener in $listeners) {
|
||||
if ($listener.OwningProcess -notin $managed.ProcessId) { throw "Port $Port belongs to an unmanaged process; nothing was stopped." }
|
||||
}
|
||||
# Recheck creation time before stopping, to guard against PID reuse.
|
||||
foreach ($item in $managed) {
|
||||
$live = Get-CimInstance Win32_Process -Filter "ProcessId=$($item.ProcessId)"
|
||||
if ($live -and $live.CreationDate -eq $item.CreationDate -and $live.CommandLine -eq $item.CommandLine) {
|
||||
Stop-Process -Id $item.ProcessId -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
}
|
||||
$deadline = [DateTime]::UtcNow.AddSeconds(15)
|
||||
while (@(Get-ManagedProcesses).Count -gt 0) {
|
||||
if ([DateTime]::UtcNow -gt $deadline) { throw 'Previous djev process did not stop.' }
|
||||
Start-Sleep -Milliseconds 250
|
||||
}
|
||||
}
|
||||
|
||||
function Start-Model([string]$Name) {
|
||||
$root = $roots[$Name]
|
||||
$tierName = $Name.Substring(3)
|
||||
$outLog = Join-Path $logs "djev-$tierName-switch.stdout.log"
|
||||
$errLog = Join-Path $logs "djev-$tierName-switch.stderr.log"
|
||||
$arguments = @('-u', ('"' + $script + '"'), '--root', ('"' + $root + '"'), '--port', $Port, '--warmup-image', '--ignore-selection')
|
||||
$child = Start-Process -FilePath $python -ArgumentList $arguments -WorkingDirectory $repo -WindowStyle Hidden -PassThru -RedirectStandardOutput $outLog -RedirectStandardError $errLog
|
||||
$marker = @{ Pid = $child.Id; StartedUtc = $child.StartTime.ToUniversalTime().ToString('o') } | ConvertTo-Json -Compress
|
||||
# Desktop startup checks LiteRoot's marker, even when Nano serves the shared endpoint.
|
||||
[IO.File]::WriteAllText((Join-Path $LiteRoot "sophelper-d3-$Port.json"), $marker)
|
||||
[IO.File]::WriteAllText((Join-Path $root "sophelper-d3-$Port.json"), $marker)
|
||||
Set-Content -LiteralPath (Join-Path $root 'server.pid') -Value $child.Id -Encoding ascii
|
||||
Write-Host "Loading djev ($($Name.Substring(3))) ..."
|
||||
$deadline = [DateTime]::UtcNow.AddSeconds(180)
|
||||
do {
|
||||
$health = Get-Health
|
||||
if ($health -and $health.status -eq 'ready' -and $health.model -eq $Name -and 'image' -in $health.modalities) {
|
||||
return
|
||||
}
|
||||
if ($child.HasExited) { throw "djev exited. Log: $errLog" }
|
||||
if ([DateTime]::UtcNow -gt $deadline) { throw "djev startup timed out. Log: $errLog" }
|
||||
Start-Sleep -Milliseconds 500
|
||||
} while ($true)
|
||||
}
|
||||
|
||||
$lock = $null
|
||||
try {
|
||||
if ($Model -eq 'status') { Show-Health (Get-Health); exit 0 }
|
||||
if ($Model -eq 'config' -and !$Tier) { Write-Host "djev | Configured: $(Get-ConfiguredTier) Config: $configPath"; exit 0 }
|
||||
if ($Model -ne 'config' -and $Tier) { throw 'The second argument is only used with config.' }
|
||||
if ($Model -eq 'config') { $Model = $Tier; $configOnly = $true } else { $configOnly = $false }
|
||||
$target = "d3-$Model"
|
||||
foreach ($path in @($python, $script, (Join-Path $roots[$target] 'model\MODEL_MANIFEST.json'), (Join-Path $roots[$target] 'local-model-manifest.json'))) {
|
||||
if (!(Test-Path -LiteralPath $path -PathType Leaf)) { throw "Required file missing: $path" }
|
||||
}
|
||||
$package = Get-Content -LiteralPath (Join-Path $roots[$target] 'model\MODEL_MANIFEST.json') -Raw -Encoding UTF8 | ConvertFrom-Json
|
||||
if ($package.model_name -ne $target) { throw 'djev package does not match the requested tier.' }
|
||||
New-Item -ItemType Directory -Force -Path $logs | Out-Null
|
||||
# Use the desktop startup lock too; never run two loads on the same endpoint.
|
||||
$lock = [IO.File]::Open((Join-Path $LiteRoot "sophelper-d3-$Port.lock"), 'OpenOrCreate', 'ReadWrite', 'None')
|
||||
if ($configOnly) {
|
||||
Save-Selection $Model
|
||||
Write-Host "djev | Configured: $Model Config: $configPath"
|
||||
exit 0
|
||||
}
|
||||
$previous = Get-Health
|
||||
if ($previous -and $previous.model -eq $target -and $previous.status -eq 'ready' -and 'image' -in $previous.modalities) {
|
||||
Save-Selection $Model
|
||||
Show-Health $previous
|
||||
exit 0
|
||||
}
|
||||
if ($previous -and $previous.model -notin $roots.Keys) { throw 'Endpoint is not a known djev service.' }
|
||||
Stop-Managed
|
||||
try { Start-Model $target; Save-Selection $Model; Show-Health (Get-Health) }
|
||||
catch {
|
||||
$failure = $_
|
||||
Stop-Managed
|
||||
if ($previous -and $previous.model -in $roots.Keys) {
|
||||
Write-Warning 'Switch failed; restoring previous djev service.'
|
||||
Start-Model $previous.model
|
||||
}
|
||||
throw $failure
|
||||
}
|
||||
} catch {
|
||||
Write-Error $_ -ErrorAction Continue
|
||||
exit 1
|
||||
} finally {
|
||||
if ($null -ne $lock) { $lock.Dispose() }
|
||||
}
|
||||
@ -9,42 +9,27 @@ import sys
|
||||
import time
|
||||
|
||||
|
||||
# 先解析轻量/微型模型选择,避免在模型目录尚未确定时导入 GPU 运行库。
|
||||
def resolve_model_root(root, ignore_selection=False):
|
||||
"""Resolve the configured djev tier without importing the GPU runtime."""
|
||||
root = root.resolve()
|
||||
selection = root / "djev.json"
|
||||
if ignore_selection or not selection.exists():
|
||||
return root
|
||||
config = json.loads(selection.read_text(encoding="utf-8-sig"))
|
||||
tier = config.get("tier")
|
||||
if tier == "lite":
|
||||
# 独立 Nano 安装也可指定 Lite 目录;旧配置继续使用启动根目录。
|
||||
selected = Path(config.get("lite_root") or root)
|
||||
elif tier == "nano":
|
||||
selected = Path(config.get("nano_root") or root.parent / "D3Nano")
|
||||
else:
|
||||
raise ValueError(f"Invalid djev tier in {selection}; use lite or nano")
|
||||
if not selected.is_absolute():
|
||||
selected = root / selected
|
||||
return selected.resolve()
|
||||
def verify_nano_package(root):
|
||||
"""在导入 GPU 库前检查模型包标识,防止目录里误装 Lite。"""
|
||||
package = json.loads((root / "model" / "MODEL_MANIFEST.json").read_text(encoding="utf-8"))
|
||||
if package.get("model_name") != "d3-nano":
|
||||
raise ValueError(f"Expected d3-nano in {root / 'model'}")
|
||||
|
||||
|
||||
# 配置独立日志与离线模型目录,完成模型加载和预热后再启动本机 HTTP 服务。
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--root", type=Path, default=Path(r"E:\D3Lite"))
|
||||
parser.add_argument("--root", type=Path, required=True)
|
||||
parser.add_argument("--port", type=int, default=8766)
|
||||
parser.add_argument("--log-dir", type=Path)
|
||||
parser.add_argument("--warmup-image", action="store_true", help="Warm up one 512px image before reporting ready")
|
||||
parser.add_argument("--ignore-selection", action="store_true", help="Use --root directly instead of its djev.json")
|
||||
args = parser.parse_args()
|
||||
if args.log_dir is not None:
|
||||
args.log_dir.mkdir(parents=True, exist_ok=True)
|
||||
# 文件由服务自身持有,桌面软件退出后不会因管道关闭影响服务。
|
||||
sys.stdout = (args.log_dir / f"djev-{args.port}.stdout.log").open("w", encoding="utf-8", buffering=1)
|
||||
sys.stderr = (args.log_dir / f"djev-{args.port}.stderr.log").open("w", encoding="utf-8", buffering=1)
|
||||
root = resolve_model_root(args.root, args.ignore_selection)
|
||||
root = args.root.resolve()
|
||||
verify_nano_package(root)
|
||||
os.environ["HF_HUB_OFFLINE"] = "1"
|
||||
os.environ["HF_HUB_DISABLE_TELEMETRY"] = "1"
|
||||
sys.path.insert(0, str(root / "model"))
|
||||
@ -59,12 +44,11 @@ def main():
|
||||
verify="full", max_length=2048, local_files_only=True)
|
||||
if model.image_unavailable is not None:
|
||||
raise RuntimeError(f"Vision failed to initialize: {model.image_unavailable}")
|
||||
# 默认大图预热会额外占用显存;这里先预热文本,再按开关执行单张 512 像素图像预热。
|
||||
# 先预热文本,再用一张 512 像素图像验证视觉路径,控制预热显存开销。
|
||||
model.warmup(lengths=(64, 384), images=False)
|
||||
if args.warmup_image or not args.ignore_selection:
|
||||
from PIL import Image
|
||||
model.system_one(state="", images=[Image.new("RGB", (512, 512), (128, 128, 128))],
|
||||
questions={"warmup": {"type": "noul", "instructions": "Is there an object in the image?"}})
|
||||
from PIL import Image
|
||||
model.system_one(state="", images=[Image.new("RGB", (512, 512), (128, 128, 128))],
|
||||
questions={"warmup": {"type": "noul", "instructions": "Is there an object in the image?"}})
|
||||
manifest = json.loads((root / "local-model-manifest.json").read_text(encoding="utf-8"))
|
||||
provenance = model.provenance()
|
||||
package = next(entry for entry in manifest if entry["repo"] == provenance["repo_id"])
|
||||
|
||||
@ -28,7 +28,7 @@ def health(port):
|
||||
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
|
||||
ready = data.get("status") == "ready" and data.get("model") == "d3-nano" and "image" in modalities
|
||||
data["ready"] = bool(ready)
|
||||
return data
|
||||
|
||||
@ -115,11 +115,11 @@ def serve(root, port, script, log_dir):
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("command", choices=["serve", "start", "status", "probe", "verify"])
|
||||
parser.add_argument("--root", default=r"D:\D3Nano")
|
||||
parser.add_argument("--root", default=r"C:\sophelper\current\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("--image-root", default=r"C:\sophelper\current\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")
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
param(
|
||||
[string]$InstallRoot = 'D:\D3Nano',
|
||||
[string]$InstallRoot = 'C:\sophelper\current\D3Nano',
|
||||
[string]$ModelTar = '',
|
||||
[string]$WheelsTar = '',
|
||||
[string]$WheelsDir = 'D:\d3-wheels',
|
||||
@ -8,7 +8,7 @@
|
||||
[int]$SkipModel = 0,
|
||||
[int]$SkipVenv = 0
|
||||
)
|
||||
# 远端 d3-nano 安装脚本:解包模型、建 .venv、离线装依赖、写 djev 配置并校验 CUDA 可用性。
|
||||
# 远端 d3-nano 安装脚本:解包模型、建 .venv、离线装依赖并校验 CUDA 可用性。
|
||||
# 由 tools/Deploy-D3Nano.ps1 通过 SSH 调用,参数不含空格。
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$python = Join-Path $InstallRoot '.venv\Scripts\python.exe'
|
||||
@ -67,13 +67,7 @@ if (!$SkipVenv) {
|
||||
}
|
||||
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 构建)。
|
||||
# 4. 校验:依赖导入、CUDA 可用与目标显卡算力(RTX 5060 需要 cu128 的 sm_120 构建)。
|
||||
$verify = Join-Path $env:TEMP 'd3nano-verify.py'
|
||||
@'
|
||||
import json, sys
|
||||
@ -104,6 +98,5 @@ Write-Output (ConvertTo-Json -InputObject ([ordered]@{
|
||||
installed = $InstallRoot
|
||||
python = $python
|
||||
basePython = $PythonExe
|
||||
d3RootEnv = $machineRoot
|
||||
port = $Port
|
||||
}) -Compress)
|
||||
|
||||
Loading…
Reference in New Issue
Block a user