Alta Memória de Pico Durante OCR em Massa
Executar OCR em muitos segmentos de PDF de uma vez multiplica o uso de memória. Cada tarefa renderiza bitmaps de página inteira através de um OcrInput, e um novo motor IronTesseract por segmento recarrega os arquivos do modelo de linguagem toda vez. Com toda a concorrência do processador, isso eleva o pico de memória para a faixa de vários gigabytes, com picos que falham em ambientes com memória limitada.
O OCR é naturalmente pesado em memória. Cada OcrInput renderiza bitmaps de página inteira, e todo motor IronTesseract carrega arquivos de modelo de linguagem na memória. Criar um novo motor por segmento recarrega esses modelos repetidamente, e executar uma tarefa de OCR por núcleo de CPU (Environment.ProcessorCount) permite que muitos trabalhos pesados de bitmap rodem lado a lado. Sem limitar quantas tarefas estão ativas, a memória máxima escala diretamente com a concorrência.
A solução é limitar o número de tarefas em andamento: limitar a concorrência, reutilizar motores de um pool e organizar o trabalho com um semáforo.
Solução
1. Limitar a concorrência do OCR
Limite o número de tarefas de OCR simultâneas a um teto pequeno. Menos tarefas simultâneas significam menos bitmaps de página inteira na memória de uma vez, o que reduz diretamente o pico. Ajuste o teto à capacidade da 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. Pool dos motores
Crie exatamente um motor IronTesseract por slot concorrente no início e reutilize-os em cada segmento, em vez de construir um novo motor e recarregar o modelo de linguagem a 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 o pool uma vez amortiza o custo de carregar o modelo de linguagem em toda a execução em vez de pagar por isso por segmento.
3. Organizem o trabalho com um semáforo
Inicialize um SemaphoreSlim até o limite de concorrência e envolva-o em using. Cada tarefa chama WaitAsync() antes de começar e Release() em um finally, para que apenas o número permitido de segmentos esteja em processo de execução de cada vez.
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 UsingA chamada WaitAsync() bloqueia até que um slot seja liberado, e devolver o motor na parte interna finally entrega um motor pré-carregado diretamente para o próximo segmento na fila.
4. Disponibilizar OcrInput por segmento
Envolva cada OcrInput em using para que seus bitmaps de página renderizada sejam liberados no momento em que o segmento é lido, antes que a próxima tarefa reivindique o slot.
using em OcrInput é o que impede que a memória de bitmap se acumule entre segmentos; sem ela, os slots liberados ainda mantêm seus bitmaps de página.5. Limite o paralelismo dentro de cada leitura
Os passos acima limitam quantos segmentos rodam simultaneamente, mas cada IronTesseract também lê páginas em paralelo dentro de uma única chamada Read, padronizando para uma página por processador lógico. Os dois limites se multiplicam: quatro segmentos simultâneos contra um padrão de 16 são 64 motores nativos, não quatro. Defina MaxDegreeOfParallelism em cada motor agrupado para que a camada interna também seja 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
NextVeja como controlar o uso de memória paralela do OCR para entender como as duas propriedades interagem e quanto cada página simultânea custa.
Curtis Chau é bacharel em Ciência da Computação (Universidade Carleton) e se especializa em desenvolvimento front-end, com experiência em Node.js, TypeScript, JavaScript e React. Apaixonado por criar interfaces de usuário intuitivas e esteticamente agradáveis, Curtis gosta de trabalhar com frameworks modernos e criar manuais bem estruturados e visualmente atraentes.