Harden API memory and CPU usage across Phases 19–22.
CI / changes (push) Successful in 17s
dotnet8-ci / build-and-test (push) Successful in 8m23s
CI / backend (push) Successful in 8m24s
node-ci / build (push) Failing after 2m1s
CI / frontend (push) Failing after 2m2s

Bound list/PDF payloads, stream MinIO I/O with cancellation, paginate history and FHIR $everything, tighten OCR lifetimes/buffers, and add phase tracking docs.
This commit is contained in:
2026-11-30 23:55:56 +08:00
parent 192cb36dc7
commit a17bc2b734
46 changed files with 1677 additions and 215 deletions
@@ -1,6 +1,5 @@
using Azure;
using Azure.AI.DocumentIntelligence;
using Microsoft.Extensions.Options;
public class AzureDocumentOcrService : IOcrService
{
@@ -56,26 +55,24 @@ public class AzureDocumentOcrService : IOcrService
private readonly ILogger<AzureDocumentOcrService> _logger;
public AzureDocumentOcrService(
IOptions<OcrOptions> options,
DocumentIntelligenceClient client,
ILogger<AzureDocumentOcrService> logger)
{
var opts = options.Value.Azure;
_client = new DocumentIntelligenceClient(
new Uri(opts.Endpoint),
new AzureKeyCredential(opts.ApiKey));
_client = client;
_logger = logger;
}
public async Task<OcrExtractionResult> ExtractAsync(
Stream documentStream, string contentType)
Stream documentStream, string contentType, CancellationToken ct = default)
{
var sw = System.Diagnostics.Stopwatch.StartNew();
var content = BinaryData.FromStream(documentStream);
var content = await BinaryData.FromStreamAsync(documentStream, ct);
var operation = await _client.AnalyzeDocumentAsync(
WaitUntil.Completed,
"prebuilt-document",
content);
content,
cancellationToken: ct);
var result = operation.Value;
var fields = new List<OcrExtractedField>();
@@ -10,18 +10,20 @@ public class ImagePreprocessor
private const int PdfRenderWidth = 2550;
private const int PdfRenderHeight = 3300;
public Stream Preprocess(Stream input, string contentType)
public async Task<Stream> PreprocessAsync(
Stream input, string contentType, CancellationToken ct = default)
{
Stream? pdfRenderStream = null;
try
{
if (contentType == "application/pdf")
{
pdfRenderStream = RenderPdfFirstPage(input);
pdfRenderStream = await RenderPdfFirstPageAsync(input, ct);
input = pdfRenderStream;
}
using var image = Image.Load(input);
ct.ThrowIfCancellationRequested();
using var image = await Image.LoadAsync(input, ct);
image.Mutate(ctx => ctx
.Grayscale()
@@ -29,22 +31,26 @@ public class ImagePreprocessor
.BinaryThreshold(0.5f));
var output = new MemoryStream();
image.SaveAsPng(output);
await image.SaveAsPngAsync(output, ct);
output.Position = 0;
return output;
}
finally
{
pdfRenderStream?.Dispose();
if (pdfRenderStream is not null)
await pdfRenderStream.DisposeAsync();
}
}
private static Stream RenderPdfFirstPage(Stream pdfStream)
private static async Task<Stream> RenderPdfFirstPageAsync(
Stream pdfStream, CancellationToken ct)
{
using var buffer = new MemoryStream();
pdfStream.CopyTo(buffer);
await pdfStream.CopyToAsync(buffer, 81920, ct);
var pdfBytes = buffer.ToArray();
ct.ThrowIfCancellationRequested();
using var docReader = DocLib.Instance.GetDocReader(
pdfBytes,
new PageDimensions(PdfRenderWidth, PdfRenderHeight));
@@ -59,7 +65,7 @@ public class ImagePreprocessor
using var image = Image.LoadPixelData<Bgra32>(rawBytes, width, height);
var output = new MemoryStream();
image.SaveAsPng(output);
await image.SaveAsPngAsync(output, ct);
output.Position = 0;
return output;
}
@@ -37,8 +37,12 @@ public class OcrDraftPreFiller
}
public async Task PreFillAsync(
Guid batchId, BatchType batchType, OcrExtractionResult extraction)
Guid batchId,
BatchType batchType,
OcrExtractionResult extraction,
CancellationToken ct = default)
{
ct.ThrowIfCancellationRequested();
var requirements = BatchTypeFieldRequirements.ForBatchType(batchType);
var confidentFields = extraction.Fields
.Where(f => f.Confidence >= _options.ConfidenceThreshold)
@@ -54,7 +58,7 @@ public class OcrDraftPreFiller
if (requirements.ShowObservations)
await PreFillObservationsAsync(batchId, confidentFields);
await _db.SaveChangesAsync();
await _db.SaveChangesAsync(ct);
}
private async Task PreFillPatientAsync(
@@ -2,7 +2,7 @@ using System.Text.RegularExpressions;
using Microsoft.Extensions.Options;
using Tesseract;
public class TesseractOcrService : IOcrService
public class TesseractOcrService : IOcrService, IDisposable
{
private static readonly (Regex Pattern, string FieldName)[] ClinicalPatterns =
[
@@ -25,6 +25,9 @@ public class TesseractOcrService : IOcrService
private readonly TesseractOcrOptions _options;
private readonly ImagePreprocessor _preprocessor;
private readonly ILogger<TesseractOcrService> _logger;
private readonly object _engineLock = new();
private TesseractEngine? _engine;
private bool _disposed;
public TesseractOcrService(
IOptions<OcrOptions> options,
@@ -37,28 +40,57 @@ public class TesseractOcrService : IOcrService
}
public async Task<OcrExtractionResult> ExtractAsync(
Stream documentStream, string contentType)
Stream documentStream, string contentType, CancellationToken ct = default)
{
var sw = System.Diagnostics.Stopwatch.StartNew();
using var preprocessed = _preprocessor.Preprocess(documentStream, contentType);
using var memStream = new MemoryStream();
await preprocessed.CopyToAsync(memStream);
var imageBytes = memStream.ToArray();
await using var preprocessed = await _preprocessor.PreprocessAsync(
documentStream, contentType, ct);
using var engine = new TesseractEngine(
_options.DataPath, _options.Language, EngineMode.Default);
using var pix = Pix.LoadFromMemory(imageBytes);
using var page = engine.Process(pix);
ct.ThrowIfCancellationRequested();
byte[] imageBytes;
if (preprocessed is MemoryStream ms)
{
imageBytes = ms.ToArray();
}
else
{
using var copy = new MemoryStream();
await preprocessed.CopyToAsync(copy, ct);
imageBytes = copy.ToArray();
}
ct.ThrowIfCancellationRequested();
string rawText;
float meanConfidence;
lock (_engineLock)
{
var engine = GetEngine();
using var pix = Pix.LoadFromMemory(imageBytes);
using var page = engine.Process(pix);
rawText = page.GetText();
meanConfidence = page.GetMeanConfidence();
}
var rawText = page.GetText();
var meanConfidence = page.GetMeanConfidence();
var fields = ParseClinicalText(rawText, meanConfidence);
sw.Stop();
_logger.LogDebug(
"Tesseract OCR finished in {DurationMs}ms with {FieldCount} fields",
sw.ElapsedMilliseconds, fields.Count);
return new OcrExtractionResult(fields, rawText, (int)sw.ElapsedMilliseconds);
}
private TesseractEngine GetEngine()
{
ObjectDisposedException.ThrowIf(_disposed, this);
return _engine ??= new TesseractEngine(
_options.DataPath, _options.Language, EngineMode.Default);
}
private static List<OcrExtractedField> ParseClinicalText(string text, float meanConfidence)
{
var fields = new List<OcrExtractedField>();
@@ -87,4 +119,13 @@ public class TesseractOcrService : IOcrService
return fields;
}
public void Dispose()
{
if (_disposed)
return;
_disposed = true;
_engine?.Dispose();
_engine = null;
}
}