66 lines
4.1 KiB
C#
66 lines
4.1 KiB
C#
using System.Diagnostics;
|
||
using System.Net.Http.Headers;
|
||
using System.Net.Http.Json;
|
||
using System.Security.Cryptography;
|
||
using System.Text.Json;
|
||
|
||
namespace SopHelper.Engine.Sop;
|
||
|
||
/// <summary>djev 原生 System One 图片接口;noul 是完成条件的正例概率。</summary>
|
||
public sealed class D3VisionDecisionClient(HttpClient http) : IVisionDecisionClient
|
||
{
|
||
public const string StatePrompt = "正在检查当前工位图片。完成条件是待验证的假设,不代表已经发生。";
|
||
public static string BuildInstructions(string criteria) =>
|
||
$"仅依据当前图片中清晰可见的证据判断。看不到判据要求的目标或关键部位、存在遮挡或不能确认时回答否。图片里是否满足这个完成条件:{criteria}";
|
||
|
||
public async Task<VisionDecisionResult> DecideAsync(VisionDecisionRequest request, CancellationToken cancellationToken)
|
||
{
|
||
if (request.EvidenceMode != VisionEvidenceMode.SingleFrame || request.Frames is { Count: > 1 })
|
||
return new(false, 0, "djev 单帧接口不支持过程时序判定", VisionDecisionStatus.Unsupported);
|
||
var endpoint = Environment.GetEnvironmentVariable("SOPHELPER_VISION_ENDPOINT")
|
||
?? "http://127.0.0.1:8766/v1/systemone";
|
||
if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var uri) || uri.Scheme is not ("http" or "https"))
|
||
throw new InvalidOperationException("djev 视觉接口地址无效");
|
||
if (request.Jpeg.Length is 0 or > 10 * 1024 * 1024 || string.IsNullOrWhiteSpace(request.Criteria))
|
||
throw new InvalidOperationException("djev 需要有效的判定图和完成条件");
|
||
|
||
using var message = new HttpRequestMessage(HttpMethod.Post, uri);
|
||
var key = Environment.GetEnvironmentVariable("SOPHELPER_VISION_API_KEY");
|
||
if (!string.IsNullOrWhiteSpace(key)) message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", key);
|
||
message.Content = JsonContent.Create(new
|
||
{
|
||
// 完成判据是待验证假设,不能在 state 中当作已知事实重复陈述。
|
||
state = StatePrompt,
|
||
images = new[] { "data:image/jpeg;base64," + Convert.ToBase64String(request.Jpeg) },
|
||
questions = new
|
||
{
|
||
step_completed = new
|
||
{
|
||
type = "noul",
|
||
instructions = BuildInstructions(request.Criteria)
|
||
}
|
||
}
|
||
});
|
||
var timer = Stopwatch.StartNew();
|
||
using var response = await http.SendAsync(message, cancellationToken).ConfigureAwait(false);
|
||
if (!response.IsSuccessStatusCode) throw new InvalidOperationException($"djev 视觉接口 HTTP {(int)response.StatusCode}");
|
||
using var document = JsonDocument.Parse(await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false));
|
||
var root = document.RootElement;
|
||
var answer = root.GetProperty("answers").GetProperty("step_completed");
|
||
if (answer.TryGetProperty("error", out _) || answer.GetProperty("type").GetString() != "noul")
|
||
throw new FormatException("djev 未返回有效的是非判定");
|
||
var probability = answer.GetProperty("noul").GetDouble();
|
||
if (!double.IsFinite(probability) || probability is < 0 or > 1)
|
||
throw new FormatException("djev 完成概率无效");
|
||
// 测试服务附带哈希时核对实际图片;标准 D3 服务没有此扩展字段也可使用。
|
||
if (root.TryGetProperty("usage", out var usage) && usage.TryGetProperty("image_sha256", out var hashes))
|
||
{
|
||
var expected = Convert.ToHexString(SHA256.HashData(request.Jpeg));
|
||
if (hashes.ValueKind != JsonValueKind.Array || hashes.GetArrayLength() != 1
|
||
|| !string.Equals(hashes[0].GetString(), expected, StringComparison.OrdinalIgnoreCase))
|
||
throw new FormatException("djev 接收到的图片与判定帧不一致");
|
||
}
|
||
return new(probability >= .5, probability, $"djev 完成概率 {probability:P1},请求耗时 {timer.Elapsed.TotalMilliseconds:F0}ms");
|
||
}
|
||
}
|