批量OCR期间高峰内存
同时运行多个PDF段段段段的OCR会增加内存使用。 每个任务通过OcrInput渲染全页面位图,并为每个段段重新加载语言模型文件时使用新的IronTesseract引擎。在处理器全并发时,这将使峰值内存进入多GB范围,内存受限环境中会有失败的峰值。
OCR本身是内存密集型的。 每个OcrInput渲染全页面位图,并且每个IronTesseract引擎将语言模型文件加载到内存中。 为每个分段创建一个新的引擎会反复重新加载这些模型,而每个CPU核心运行一个OCR任务(Environment.ProcessorCount)允许许多重度位图任务并行运行。在没有限制任务数量的情况下,峰值内存直接随并发性而增长。
修复方法是限制正在进行的作业数量:限制并发,通过池重用引擎,并用信号量闸口工作。
解决方案
1. 限制OCR并发数
限制同时运行的OCR任务数量到一个小值。 较少的并发任务意味着内存中同时只有较少的整页位图,直接降低峰值。 根据机器的能力调整上限。
// 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. 池化引擎
在启动时为每个并发槽精确创建一个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.
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())
)一次性构建池会将语言模型加载成本摊在整个运行中,而不是每段段段段都支付。
3. 使用信号量控制作业
初始化SemaphoreSlim到并发限制并用using包装。 每个任务在开始前调用WaitAsync(),并在finally中调用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 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 UsingWaitAsync()调用会阻塞直到一个槽空出,并在内finally中返回引擎,将预加载的引擎直接交给下一个等待的段。
4. 为每个段段段段处置OcrInput
将每个OcrInput封装在using中,以便在段被读取时立即释放已渲染的页面位图,然后下一个任务占用槽之前。
OcrInput上的using是防止位图内存在段间累积的关键; 没有它,释放的槽位仍然持有它们的页面位图。5. 限制每个读取中的并行性
上述步骤限制了同时运行的段的数量,但每个IronTesseract在单个Read调用内也并行读取页面,默认每个逻辑处理器一个页面。 这两个限制相乘:四个并发分段与默认的16个是64个本机引擎,而不是四个。 在每个池化引擎上设置MaxDegreeOfParallelism,以便内部层也受到限制。
// 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
Next请参阅如何控制并行OCR内存使用,以了解这两个属性如何交互以及每个并发页面的成本。
Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。