Altos picos de memoria durante OCR masivo
Ejecutar OCR sobre muchos segmentos de PDF a la vez multiplica el uso de memoria. Cada tarea renderiza mapas de bits de página completa a través de un OcrInput, y un nuevo motor IronTesseract por segmento recarga los archivos del modelo de lenguaje cada vez. A plena concurrencia del procesador, esto lleva la memoria máxima al rango de varios GB, con picos que fallan en entornos con limitaciones de memoria.
OCR es intensivo en memoria por naturaleza. Cada OcrInput renderiza mapas de bits de página completa, y cada motor IronTesseract carga archivos de modelo de lenguaje en la memoria. Crear un nuevo motor por segmento recarga esos modelos repetidamente, y ejecutar una tarea de OCR por núcleo de CPU (Environment.ProcessorCount) permite que muchos trabajos con muchos mapas de bits se ejecuten simultáneamente. Sin nada que limite la cantidad de tareas activas, la memoria máxima escala directamente con la concurrencia.
La solución es limitar el número de trabajos en tránsito: limitar la concurrencia, reutilizar motores de un recurso y administrar el trabajo con un semáforo.
Solución
1. Limite la concurrencia de OCR
Limite el número de tareas OCR simultáneas a un techo pequeño. Menos tareas concurrentes significan menos mapas de bits de página completa en la memoria al mismo tiempo, lo que reduce directamente el pico. Ajuste el techo a la capacidad de la máquina.
// Clamp concurrency to avoid memory saturation and CPU over-subscription.
int concurrency = Math.Clamp(Environment.ProcessorCount / 2, 1, 4);Dim concurrency As Integer = Math.Clamp(Environment.ProcessorCount \ 2, 1, 4)Dim concurrency As Integer = Math.Clamp(Environment.ProcessorCount \ 2, 1, 4)2. Agrupe los motores
Cree exactamente un motor IronTesseract por cada ranura concurrente al iniciar y reutilícelos en cada segmento, en lugar de construir un nuevo motor y recargar el modelo de lenguaje cada vez.
// Pre-create one engine per concurrent slot and reuse them across segments.
var enginePool = new ConcurrentBag<IronTesseract>(
Enumerable.Range(0, concurrency).Select(_ => new IronTesseract())
);// Pre-create one engine per concurrent slot and reuse them across segments.
var enginePool = new ConcurrentBag<IronTesseract>(
Enumerable.Range(0, concurrency).Select(_ => new IronTesseract())
);' Pre-create one engine per concurrent slot and reuse them across segments.
Dim enginePool = New ConcurrentBag(Of IronTesseract)(
Enumerable.Range(0, concurrency).Select(Function(_) New IronTesseract())
)' Pre-create one engine per concurrent slot and reuse them across segments.
Dim enginePool = New ConcurrentBag(Of IronTesseract)(
Enumerable.Range(0, concurrency).Select(Function(_) New IronTesseract())
)Construir el grupo una vez amortiza el costo de carga del modelo de lenguaje durante toda la ejecución en lugar de pagarlo por segmento.
3. Administre el trabajo con un semáforo
Inicialice un SemaphoreSlim al límite de concurrencia y envuélvalo en using. Cada tarea llama WaitAsync() antes de comenzar y Release() en un finally, por lo que solo el número permitido de segmentos están en vuelo al mismo tiempo.
using var semaphore = new SemaphoreSlim(concurrency);
await semaphore.WaitAsync();
try
{
// Rent a pre-loaded engine from the pool.
if (!enginePool.TryTake(out var ocr))
ocr = new IronTesseract(); // Defensive fallback; should never be reached.
try
{
using var input = new OcrInput();
input.LoadPdf(segmentStream); // page-range segment produced upstream
var ocrResult = await ocr.ReadAsync(input);
ocrResult.SaveAsSearchablePdf(outputPath);
}
finally
{
enginePool.Add(ocr); // Return engine to pool for the next waiting segment.
}
}
finally
{
semaphore.Release();
}using var semaphore = new SemaphoreSlim(concurrency);
await semaphore.WaitAsync();
try
{
// Rent a pre-loaded engine from the pool.
if (!enginePool.TryTake(out var ocr))
ocr = new IronTesseract(); // Defensive fallback; should never be reached.
try
{
using var input = new OcrInput();
input.LoadPdf(segmentStream); // page-range segment produced upstream
var ocrResult = await ocr.ReadAsync(input);
ocrResult.SaveAsSearchablePdf(outputPath);
}
finally
{
enginePool.Add(ocr); // Return engine to pool for the next waiting segment.
}
}
finally
{
semaphore.Release();
}Using semaphore As New SemaphoreSlim(concurrency)
Await semaphore.WaitAsync()
Try
' Rent a pre-loaded engine from the pool.
Dim ocr As IronTesseract
If Not enginePool.TryTake(ocr) Then
ocr = New IronTesseract() ' Defensive fallback; should never be reached.
End If
Try
Using input As New OcrInput()
input.LoadPdf(segmentStream) ' page-range segment produced upstream
Dim ocrResult = Await ocr.ReadAsync(input)
ocrResult.SaveAsSearchablePdf(outputPath)
End Using
Finally
enginePool.Add(ocr) ' Return engine to pool for the next waiting segment.
End Try
Finally
semaphore.Release()
End Try
End UsingUsing semaphore As New SemaphoreSlim(concurrency)
Await semaphore.WaitAsync()
Try
' Rent a pre-loaded engine from the pool.
Dim ocr As IronTesseract
If Not enginePool.TryTake(ocr) Then
ocr = New IronTesseract() ' Defensive fallback; should never be reached.
End If
Try
Using input As New OcrInput()
input.LoadPdf(segmentStream) ' page-range segment produced upstream
Dim ocrResult = Await ocr.ReadAsync(input)
ocrResult.SaveAsSearchablePdf(outputPath)
End Using
Finally
enginePool.Add(ocr) ' Return engine to pool for the next waiting segment.
End Try
Finally
semaphore.Release()
End Try
End UsingLa llamada WaitAsync() bloquea hasta que se libera una ranura, y devolver el motor en el finally interno entrega un motor precargado directamente al siguiente segmento en espera.
4. Dispose OcrInput por segmento
Envuelva cada OcrInput en using para que sus mapas de bits de página renderizados se liberen en el momento en que se lea el segmento, antes de que la siguiente tarea reclame la ranura.
using en OcrInput es lo que impide que la memoria de mapas de bits se acumule en los segmentos; sin ella, las ranuras liberadas aún retendrán sus mapas de bits de página.5. Limitar el paralelismo dentro de cada lectura
Los pasos anteriores limitan cuántos segmentos se ejecutan a la vez, pero cada IronTesseract también lee páginas en paralelo dentro de una sola llamada Read, predeterminando una página por procesador lógico. Los dos límites se multiplican: cuatro segmentos concurrentes contra un predeterminado de 16 son 64 motores nativos, no cuatro. Establezca MaxDegreeOfParallelism en cada motor agrupado para que la capa interna también esté limitada.
// Bound the inner layer as well as the outer one.
// Without this, each of the `concurrency` segments still fans out
// across every logical processor.
foreach (var engine in enginePool)
engine.MaxDegreeOfParallelism = 2;// Bound the inner layer as well as the outer one.
// Without this, each of the `concurrency` segments still fans out
// across every logical processor.
foreach (var engine in enginePool)
engine.MaxDegreeOfParallelism = 2;' Bound the inner layer as well as the outer one.
' Without this, each of the `concurrency` segments still fans out
' across every logical processor.
For Each engine In enginePool
engine.MaxDegreeOfParallelism = 2
Next' Bound the inner layer as well as the outer one.
' Without this, each of the `concurrency` segments still fans out
' across every logical processor.
For Each engine In enginePool
engine.MaxDegreeOfParallelism = 2
NextVea cómo controlar el uso de memoria OCR paralelo para entender cómo interactúan las dos propiedades y cuánto cuesta cada página concurrente.
Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien estructurados y visualmente atractivos.