Files
vigilcare-records/VigilCareRecordsAPI/Services/Ocr/TesseractOcrService.cs
T
Trent a17bc2b734
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
Harden API memory and CPU usage across Phases 19–22.
Bound list/PDF payloads, stream MinIO I/O with cancellation, paginate history and FHIR $everything, tighten OCR lifetimes/buffers, and add phase tracking docs.
2026-11-30 23:55:56 +08:00

132 lines
5.1 KiB
C#

using System.Text.RegularExpressions;
using Microsoft.Extensions.Options;
using Tesseract;
public class TesseractOcrService : IOcrService, IDisposable
{
private static readonly (Regex Pattern, string FieldName)[] ClinicalPatterns =
[
(new Regex(@"(?:Patient\s+)?Name[:\s]+(.+)", RegexOptions.IgnoreCase | RegexOptions.Multiline), "patient.fullName"),
(new Regex(@"DOB[:\s]+(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})", RegexOptions.IgnoreCase), "patient.dateOfBirth"),
(new Regex(@"(?:Date of Birth|Birth Date)[:\s]+(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})", RegexOptions.IgnoreCase), "patient.dateOfBirth"),
(new Regex(@"(?:Sex|Gender)[:\s]+(\S+)", RegexOptions.IgnoreCase), "patient.sex"),
(new Regex(@"(?:Admission Date|Admitted)[:\s]+(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})", RegexOptions.IgnoreCase), "encounter.admissionDate"),
(new Regex(@"(?:Department|Ward|Unit)[:\s]+(.+)", RegexOptions.IgnoreCase | RegexOptions.Multiline), "encounter.department"),
(new Regex(@"(?:Room(?:/Bed)?|Bed)[:\s]+(.+)", RegexOptions.IgnoreCase | RegexOptions.Multiline), "encounter.roomBed"),
(new Regex(@"HR[:\s]+(\d+(?:\.\d+)?)", RegexOptions.IgnoreCase), "observation.HEART_RATE.value"),
(new Regex(@"(?:Heart Rate|Pulse)[:\s]+(\d+(?:\.\d+)?)", RegexOptions.IgnoreCase), "observation.HEART_RATE.value"),
(new Regex(@"(?:Temp|Temperature)[:\s]+(\d+(?:\.\d+)?)", RegexOptions.IgnoreCase), "observation.TEMP_C.value"),
(new Regex(@"(?:BP Sys|Systolic)[:\s]+(\d+(?:\.\d+)?)", RegexOptions.IgnoreCase), "observation.BP_SYSTOLIC.value"),
(new Regex(@"(?:BP Dia|Diastolic)[:\s]+(\d+(?:\.\d+)?)", RegexOptions.IgnoreCase), "observation.BP_DIASTOLIC.value"),
(new Regex(@"(?:RR|Resp(?:iratory)?\s*Rate)[:\s]+(\d+(?:\.\d+)?)", RegexOptions.IgnoreCase), "observation.RESP_RATE.value"),
(new Regex(@"(?:SpO2|O2 Sat)[:\s]+(\d+(?:\.\d+)?)", RegexOptions.IgnoreCase), "observation.SPO2.value"),
];
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,
ImagePreprocessor preprocessor,
ILogger<TesseractOcrService> logger)
{
_options = options.Value.Tesseract;
_preprocessor = preprocessor;
_logger = logger;
}
public async Task<OcrExtractionResult> ExtractAsync(
Stream documentStream, string contentType, CancellationToken ct = default)
{
var sw = System.Diagnostics.Stopwatch.StartNew();
await using var preprocessed = await _preprocessor.PreprocessAsync(
documentStream, contentType, ct);
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 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>();
if (string.IsNullOrWhiteSpace(text))
return fields;
var baseConfidence = Math.Clamp(meanConfidence / 100f, 0.0, 1.0);
var matchedFields = new HashSet<string>(StringComparer.Ordinal);
foreach (var (pattern, fieldName) in ClinicalPatterns)
{
if (matchedFields.Contains(fieldName))
continue;
var match = pattern.Match(text);
if (!match.Success)
continue;
var value = match.Groups[1].Value.Trim();
if (value.Length == 0)
continue;
fields.Add(new OcrExtractedField(fieldName, value, baseConfidence));
matchedFields.Add(fieldName);
}
return fields;
}
public void Dispose()
{
if (_disposed)
return;
_disposed = true;
_engine?.Dispose();
_engine = null;
}
}