增加程序内djev档位及模型目录配置

This commit is contained in:
tfarcraw 2026-11-21 11:21:14 +08:00
parent 25341c7fd2
commit ee756064aa
10 changed files with 242 additions and 7 deletions

View File

@ -20,6 +20,12 @@ Agent只能读取用户设置,不能自行提高期限或降低置信度。
## djev 快捷切换
程序内可在“运行设置 → djev 判定”选择启动档位 `lite` / `nano`,并编辑两档的模型目录,点击“保存启动配置”。
配置写入自动启动使用的安装根目录下的 `djev.json`,不随配方切换;保存前检查所选目录的模型档位,失败时保留旧配置。
保存只影响**下次 djev 服务启动**,当前服务继续运行;仅重启桌面程序仍会复用已有服务。
运行期间禁止保存。远程服务需要在服务所在机器配置。
`lite_root` / `nano_root` 可分别指定模型目录,独立 Nano 安装也能选择其他目录中的 Lite;Python 环境仍使用安装根目录的 `.venv`。
命令、桌面界面提示、步骤回测及判定结果统一称为 `djev`,使用 `lite` / `nano` 区分档位。Windows 在仓库根目录执行:
```powershell

View File

@ -17,6 +17,8 @@ pwsh -File tools/Start-HandAiD3.ps1
启动软件时会自动检查并启动本机已安装的 djev(Windows 默认 `E:\D3Lite`,可设 `SOPHELPER_D3_ROOT`)。已运行则复用,载入和失败信息写入运行日志;不会重复启动,也不会自动开始相机采集。
“运行设置 → djev 判定”可配置 `lite` / `nano` 启动档位及模型目录,点击“保存启动配置”后在下次 djev 服务启动时生效;当前已运行服务继续复用。
## 操作流程
1. 软件启动时自动应用上次选中的配方(不可用时应用列表中的可用配方),加载步骤和区域,等待手动开始采集。在“运行设置”中选择 USB(UVC)相机,新建或选择配方。抽帧、完成后自动复位和复位延时保存在独立的 `workspace/runtime-settings.json`,下次开始运行时生效,切换配方不会覆盖。

View File

@ -62,6 +62,23 @@
<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 CanSelectCamera}" HorizontalAlignment="Left" Width="120" />
<Button x:Name="SaveDjevTierButton" Grid.Column="2" Content="保存启动配置" Command="{Binding SaveDjevSelectionCommand}" />
</Grid>
<Grid ColumnDefinitions="Auto,*" IsEnabled="{Binding CanSelectCamera}">
<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 CanSelectCamera}">
<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"

View File

@ -1,4 +1,4 @@
// 运行设置视图:提供抽帧、自动复位和请求超时等全局执行参数的编辑入口。
// 运行设置视图:提供抽帧、自动复位、djev 启动档位和请求超时等全局参数的编辑入口。
using Avalonia.Controls;
using SopHelper.Core.Prism;

View File

@ -152,6 +152,9 @@ public class SopPageViewModel : ViewModelBase
catch (Exception error) { Log("warn", "打开配方目录失败:" + error.Message); }
}, () => !string.IsNullOrWhiteSpace(SelectedRecipe));
SaveDjevSelectionCommand = new DelegateCommand(SaveDjevSelection, () => CanSelectCamera && _djevSelectionStore is not null);
LoadDjevSelection();
StatusText = "就绪,请确认运行设置后开始";
LoadLastCamera();
_ = RefreshCamerasAsync();
@ -337,6 +340,50 @@ public class SopPageViewModel : ViewModelBase
get => _runtimeOptions.DjevTimeoutMs;
set { if (!CanSelectCamera || value == DjevTimeoutMs) return; _runtimeOptions.DjevTimeoutMs = value; SaveRuntimeOptions(); }
}
private DjevSelectionStore? _djevSelectionStore;
private string _djevTier = "lite", _djevLiteRoot = "", _djevNanoRoot = "", _djevSelectionStatus = "";
public IReadOnlyList<string> DjevTiers { get; } = new[] { "lite", "nano" };
public string DjevTier { get => _djevTier; set => SetProperty(ref _djevTier, value); }
public string DjevLiteRoot { get => _djevLiteRoot; set => SetProperty(ref _djevLiteRoot, value); }
public string DjevNanoRoot { get => _djevNanoRoot; set => 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 (!CanSelectCamera || _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; }
}
private void SaveRuntimeOptions()
{
_runtimeStore.Save(_runtimeOptions);
@ -415,6 +462,7 @@ public class SopPageViewModel : ViewModelBase
NewRecipeCommand?.RaiseCanExecuteChanged();
DeleteRecipeCommand?.RaiseCanExecuteChanged();
OpenRecipeFolderCommand?.RaiseCanExecuteChanged();
SaveDjevSelectionCommand?.RaiseCanExecuteChanged();
}
/// <summary>

View File

@ -0,0 +1,71 @@
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");
}
}

View File

@ -46,6 +46,23 @@ 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"));
@ -74,6 +91,8 @@ 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);
}
@ -87,6 +106,33 @@ internal static class Smoke
var userCameraBefore=File.Exists(userCameraPath)?File.ReadAllBytes(userCameraPath):null;
await Task.Delay(150);
var app=(App)Application.Current!;var window=lifetime.MainWindow!;
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"))

View File

@ -44,6 +44,38 @@ 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))
{
var process=new FakeProcess(handler);

View File

@ -18,6 +18,7 @@ class SelectionChecks(unittest.TestCase):
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"
@ -27,6 +28,16 @@ class SelectionChecks(unittest.TestCase):
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)

View File

@ -19,13 +19,15 @@ def resolve_model_root(root, ignore_selection=False):
config = json.loads(selection.read_text(encoding="utf-8-sig"))
tier = config.get("tier")
if tier == "lite":
return root
if tier == "nano":
# 独立 Nano 安装也可指定 Lite 目录;旧配置继续使用启动根目录。
selected = Path(config.get("lite_root") or root)
elif tier == "nano":
selected = Path(config.get("nano_root") or root.parent / "D3Nano")
if not selected.is_absolute():
selected = root / selected
return selected.resolve()
raise ValueError(f"Invalid djev tier in {selection}; use lite or nano")
else:
raise ValueError(f"Invalid djev tier in {selection}; use lite or nano")
if not selected.is_absolute():
selected = root / selected
return selected.resolve()
# 配置独立日志与离线模型目录,完成模型加载和预热后再启动本机 HTTP 服务。