增加 图片识别 缓存,缓存日期有等级

This commit is contained in:
chfei committed 2026-11-09 14:23:16 +08:00
1 parent 150e8644b7
commit 9bb17a67d2
5 files changed
+176 -19

No files matched your search

@@ -1,4 +1,5 @@
using MAX.Core.DependencyInjection;
using MAX.Framework.Commons;
using MAX.Framework.Security;
using MAX.Framework.Validation;
using Microsoft.Extensions.DependencyInjection;
@@ -52,24 +53,43 @@ public sealed class ProductInspectionService(IInspectionIntegration integration,
else if (image.AsSpan(0, 4).SequenceEqual("RIFF"u8) && image.AsSpan(8, 4).SequenceEqual("WEBP"u8)) mediaType = "image/webp";
else throw new ValidationException("请上传 JPEG、PNG 或 WebP 图片。");
var cached = await database.Select<ImageAnalysisCache>().Where(x => x.CacheKey == md5).FirstAsync();
string[] result;
// 旧对象格式缺少逐项阅读顺序,重新识别成功后再覆盖。
if (cached?.RecognitionResult.TrimStart().StartsWith('[') == true)
result = JsonSerializer.Deserialize<string[]>(cached.RecognitionResult)!;
else
var result = cached?.ReadFreshResult(DateTime.UtcNow);
if (result is null)
{
await gate.WaitAsync(cancellationToken);
try
{
var useImageQuota = await imageAnalysisQuotaService.GetUserImageAnalysisQuota(new UseImageAnalysisQuotaRequest
{
UserName = request.UserName
});
if (useImageQuota <= 0)
{
throw new AppException("AI检测可用数量为0");
}
}
catch (Exception ex)
{
logger.LogError(ex, "调用图片识别扣费程序失败");
throw new AppException("AI检测可用数量为0");
}
try
{
using var stream = new MemoryStream(image, writable: false);
var recognized = await integration.AnalyzeAsync(stream, mediaType, cancellationToken);
result = recognized.Distinct(StringComparer.Ordinal).ToArray();
await database.InsertOrUpdate<ImageAnalysisCache>().SetSource(new ImageAnalysisCache
{
CacheKey = md5,
RecognitionResult = JsonSerializer.Serialize(result, CacheJsonOptions),
UpdatedAt = DateTime.UtcNow
}).ExecuteAffrowsAsync();
var entry = cached ?? new ImageAnalysisCache { CacheKey = md5 };
var previousUpdate = entry.UpdatedAt;
entry.RecognitionResult = JsonSerializer.Serialize(result, CacheJsonOptions);
entry.RecordExpiration(result.Length == 0, DateTime.UtcNow);
// 同一缓存失效后可能同时触发多次识别,只有首个写入者推进级别。
if (cached is null)
await database.InsertOrUpdate<ImageAnalysisCache>().SetSource(entry).IfExistsDoNothing().ExecuteAffrowsAsync();
else
await database.Update<ImageAnalysisCache>().SetSource(entry)
.Where(x => x.UpdatedAt == previousUpdate).ExecuteAffrowsAsync();
}
finally { gate.Release(); }
}