RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
fix(deepdoc): align OCR-rec batching with Python (sort by ratio, <=16, 96*1 pool) (#20041)
xugangqiang3505e321356e
diff --git a/internal/deepdoc/native/session_pool.go b/internal/deepdoc/native/session_pool.goindex 4992f670be..036a8a9cf5 100644--- a/internal/deepdoc/native/session_pool.go+++ b/internal/deepdoc/native/session_pool.go@@ -258,16 +258,21 @@ func recKeyOf(modelPath, inName string, inShape []int64, outName string) recKey}const (- // recMaxShapePools caps distinct (modelPath, width) pools. Unlike the+ // recMaxShapePools caps distinct (modelPath, N, imgW) pools. Unlike the// fixed-shape DLA/TSR models, a long-running server ingesting many// differently-sized text lines would otherwise pin one pooled session (and- // its ORT tensors) per distinct width forever. The shared sessionPool- // evicts the least-recently-used width pool (Destroying its idle sessions)+ // its ORT tensors) per distinct shape forever. The shared sessionPool+ // evicts the least-recently-used shape pool (Destroying its idle sessions)// once the cap is exceeded, bounding memory.- recMaxShapePools = 64- // recShapePoolCap caps idle sessions retained per width; extras are+ recMaxShapePools = 96+ // recShapePoolCap caps idle sessions retained per shape; extras are// Destroyed on release instead of pooled.- recShapePoolCap = 4+ //+ // 96 * 1 keeps the same native-RSS budget as the prior 64 * 4 config+ // (~384 pooled sessions) while spreading it across more distinct shapes so+ // concurrent workers contending on a single width no longer serialize on one+ // idle session per shape.+ recShapePoolCap = 1)// recSessions is the dynamic-width OCR-rec pool: bounded at recMaxShapePoolsdiff --git a/internal/deepdoc/parser/pdf/parser_ocr.go b/internal/deepdoc/parser/pdf/parser_ocr.goindex 0e765691a1..9647be8b16 100644--- a/internal/deepdoc/parser/pdf/parser_ocr.go+++ b/internal/deepdoc/parser/pdf/parser_ocr.go@@ -2,6 +2,7 @@ package pdfimport ("context"+ "fmt""image""math""sort"@@ -15,6 +16,14 @@ import (util "ragflow/internal/deepdoc/parser/pdf/util")+// recBatchNum is the maximum number of crops recognized in one ONNX Run. It+// mirrors Python's TextRecognizer.rec_batch_num (=16, deepdoc/vision/ocr.py)+// so the two code paths share the same sub-batch shape distribution and the+// same CTC confidence behavior. The OCR loop sorts crops by aspect ratio and+// chunks them into sub-batches of at most this size, padding each sub-batch+// only to its own local max width — exactly what the Python reference does.+const recBatchNum = 16+func (p *Parser) ocrDetectAndRecognize(ctx context.Context, pageImg image.Image, doc pdf.DocAnalyzer, pageNum int, logLabel string, zoom float64) []pdf.TextBox {boxes, err := p.inferOCRDetect(ctx, doc, pageImg)if err != nil || len(boxes) == 0 {@@ -107,29 +116,20 @@ func (p *Parser) ocrDetectAndRecognize(ctx context.Context, pageImg image.Image,if len(cropAcc) == 0 {return nil}- allTexts := make([][]pdf.OCRText, len(cropAcc))- if p.docSupportsBatchOCR(doc) {- batch, berr := p.inferOCRRecognizeBatch(ctx, doc, cropAcc)- switch {- case berr != nil:- // A batch error must not abort the whole page: the canonical- // per-crop path below still produces correct results.- reportPageInferenceFailure(ctx, logLabel+" OCR batch recognize failed; falling back to per-crop", pageNum, berr)- case len(batch) != len(cropAcc):- // Defensive: a count mismatch (or a nil result) would corrupt the- // per-box indexing further down. Fall back to per-crop instead of- // indexing out of range.- common.Warn(logLabel+" OCR batch recognize returned unexpected count; falling back to per-crop",- zap.Int("page", pageNum), zap.Int("got", len(batch)), zap.Int("want", len(cropAcc)))- default:- allTexts = batch- }- }- // Fill any crop the batch path did not cover (unsupported doc, batch error,- // or count mismatch) with the per-crop canonical path. Stamping the- // detect-box index lets a replay DocAnalyzer route the recognition back to- // the Python-dumped text for the same box; the production analyzer ignores- // the key.+ // Recognize all crops aligned to Python: sort by aspect ratio and chunk+ // into sub-batches of at most recBatchNum, each padded to its local max+ // width. ocrRecognizeBatchAligned is built on top of the upstream batch+ // API (docSupportsBatchOCR / inferOCRRecognizeBatch); it falls back to the+ // per-crop canonical path for any sub-batch that fails. The fallback stamps+ // the detect-box index so a replay DocAnalyzer routes each per-crop+ // recognition back to the Python-dumped text for the same box; the+ // production analyzer ignores the key.+ allTexts := p.ocrRecognizeBatchAligned(ctx, doc, pageNum, cropAcc, func(ci int, c image.Image) ([]pdf.OCRText, error) {+ recCtx := context.WithValue(ctx, ocrBoxIdxCtxKey, cropBoxIdx[ci])+ return p.ocrRecognizeWithRotation(recCtx, doc, c)+ })+ // Fill any crop the aligned path left uncovered (a fallback error) with the+ // per-crop canonical path so per-box indexing further down never sees nil.for ci := range cropAcc {if allTexts[ci] != nil {continue@@ -224,6 +224,94 @@ func ocrBestScore(texts []pdf.OCRText) float64 {return best}+// cropAspectRatio returns a crop's width/height ratio. Python's+// TextRecognizer argsorts crops by this ratio before sub-batching.+func cropAspectRatio(img image.Image) float64 {+ b := img.Bounds()+ h := float64(b.Dy())+ if h <= 0 {+ return 0+ }+ return float64(b.Dx()) / h+}++// ocrRecognizeBatchAligned recognizes crops in sub-batches that mirror+// Python's TextRecognizer.__call__ (deepdoc/vision/ocr.py): sort by aspect+// ratio (W/H) ascending, then recognize chunks of at most recBatchNum (16),+// each padded to that chunk's own local max width. This matches the Python+// parity target — which pads only to each sub-batch's max rather than the+// whole page's widest line — so CTC confidence is not diluted by over-padding+// narrow lines (which also corrupts layer-2 rotation selection). It shrinks+// the OCR-rec pool's distinct-shape space, keeping native RSS bounded.+//+// Results are returned aligned to the input crop order. A crop is left nil+// when its sub-batch fails (analyzer error, count mismatch, or an analyzer+// that does not implement batch OCR); the caller fills nils via fallback,+// which stamps the box index the replay analyzer needs for routing. fallback+// is invoked for every crop when doc does not support batch OCR.+func (p *Parser) ocrRecognizeBatchAligned(ctx context.Context, doc pdf.DocAnalyzer, pageNum int, crops []image.Image, fallback func(ci int, c image.Image) ([]pdf.OCRText, error)) [][]pdf.OCRText {+ n := len(crops)+ results := make([][]pdf.OCRText, n)+ if n == 0 {+ return results+ }+ // Sort crop indices by aspect ratio ascending (np.argsort(width_list)).+ order := make([]int, n)+ for i := range order {+ order[i] = i+ }+ sort.SliceStable(order, func(a, b int) bool {+ return cropAspectRatio(crops[order[a]]) < cropAspectRatio(crops[order[b]])+ })+ // When the analyzer cannot batch, fall back per crop so the caller's+ // replay routing still works.+ if !p.docSupportsBatchOCR(doc) {+ for _, ci := range order {+ t, err := fallback(ci, crops[ci])+ if err != nil {+ reportPageInferenceFailure(ctx, "ocr: per-crop fallback failed (no batch support)", pageNum, err)+ continue+ }+ results[ci] = t+ }+ return results+ }+ for beg := 0; beg < n; beg += recBatchNum {+ end := beg + recBatchNum+ if end > n {+ end = n+ }+ chunk := order[beg:end]+ imgs := make([]image.Image, len(chunk))+ for k, ci := range chunk {+ imgs[k] = crops[ci]+ }+ recs, err := p.inferOCRRecognizeBatch(ctx, doc, imgs)+ if err != nil || len(recs) != len(chunk) {+ // A sub-batch failure must not corrupt per-box indexing: fall back+ // to per-crop for just this sub-batch instead of aborting.+ if err != nil {+ reportPageInferenceFailure(ctx, "ocr: sub-batch recognize failed; falling back per-crop", pageNum, err)+ } else {+ reportPageInferenceFailure(ctx, "ocr: sub-batch recognize returned unexpected count; falling back per-crop", pageNum, fmt.Errorf("got %d want %d", len(recs), len(chunk)))+ }+ for _, ci := range chunk {+ t, ferr := fallback(ci, crops[ci])+ if ferr != nil {+ reportPageInferenceFailure(ctx, "ocr: per-crop fallback failed", pageNum, ferr)+ continue+ }+ results[ci] = t+ }+ continue+ }+ for k, ci := range chunk {+ results[ci] = recs[k]+ }+ }+ return results+}+// ocrMergeChars runs full-page detect on a page that has embedded chars,// merges the chars into detect regions, and OCRs any regions without chars.// Matches Python's __ocr: detect → match chars to boxes → use char text@@ -581,29 +669,16 @@ func (p *Parser) buildTextBoxes(ctx context.Context, pageImg image.Image,crops = append(crops, cropped)jobs = append(jobs, ocrJob{boxIdx: idx, srcIdx: boxes[idx].srcIdx, spanStart: spanStart, spanLen: 1})}- allTexts := make([][]pdf.OCRText, len(crops))- if p.docSupportsBatchOCR(doc) {- batch, berr := p.inferOCRRecognizeBatch(ctx, doc, crops)- if berr != nil {- reportPageInferenceFailure(ctx, "ocr merge: batch recognize failed", pageNum, berr)- return nil- }- allTexts = batch- } else {- for ci, c := range crops {- // Stamp the source detect-box index so a replay DocAnalyzer- // routes this fallback to the same Python-dumped box- // (detectBoxes may have re-sorted, so use srcIdx, not the loop- // index). The production analyzer ignores the key.- recCtx := context.WithValue(ctx, ocrBoxIdxCtxKey, jobs[ci].srcIdx)- texts, rerr := p.ocrRecognizeWithRotation(recCtx, doc, c)- if rerr != nil {- reportPageInferenceFailure(recCtx, "ocr merge: recognize failed", pageNum, rerr)- continue- }- allTexts[ci] = texts- }- }+ // Recognize all crops aligned to Python: sort by aspect ratio and+ // chunk into sub-batches of at most recBatchNum, each padded to its+ // local max width. The fallback stamps the source detect-box index so+ // a replay DocAnalyzer routes each per-crop recognition to the same+ // Python-dumped box (detectBoxes may re-sort, so use srcIdx, not the+ // loop index); the production analyzer ignores the key.+ allTexts := p.ocrRecognizeBatchAligned(ctx, doc, pageNum, crops, func(ci int, c image.Image) ([]pdf.OCRText, error) {+ recCtx := context.WithValue(ctx, ocrBoxIdxCtxKey, jobs[ci].srcIdx)+ return p.ocrRecognizeWithRotation(recCtx, doc, c)+ })for _, j := range jobs {var best []pdf.OCRTextbestScore := -1.0diff --git a/internal/deepdoc/parser/pdf/parser_ocr_batch_align_test.go b/internal/deepdoc/parser/pdf/parser_ocr_batch_align_test.gonew file mode 100644index 0000000000..25826baa08--- /dev/null+++ b/internal/deepdoc/parser/pdf/parser_ocr_batch_align_test.go@@ -0,0 +1,262 @@+package pdf++import (+ "context"+ "errors"+ "fmt"+ "image"+ "sort"+ "testing"++ pdf "ragflow/internal/deepdoc/parser/pdf/type"+ doctype "ragflow/internal/deepdoc/parser/type"+)++// ── ocrRecognizeBatchAligned: Python parity (sort by W/H, ≤recBatchNum) ──+//+// Python's TextRecognizer.__call__ (deepdoc/vision/ocr.py) argsorts crops by+// aspect ratio (W/H) ascending and recognizes sub-batches of at most+// rec_batch_num=16, padding each sub-batch only to its own local max width.+// The Go OCR-rec fast path must do the same so CTC confidence is not diluted+// by over-padding narrow lines to the whole page's widest line. These tests+// pin that behavior.++// recordingBatchAnalyzer implements batchRecognizer and records how crops were+// grouped into batches so the test can assert sorting + chunking.+type recordingBatchAnalyzer struct {+ healthy bool+ failOnCall int // 1-based call index that returns an error; <1 = never+ callCount int++ batches [][]float64 // per call: aspect ratios (W/H) of imgs in call order+ batchSizes []int+}++func (a *recordingBatchAnalyzer) Health() bool { return a.healthy }+func (a *recordingBatchAnalyzer) OCRDetect(context.Context, image.Image) ([]pdf.OCRBox, error) {+ return nil, nil+}+func (a *recordingBatchAnalyzer) OCRRecognize(context.Context, image.Image) ([]pdf.OCRText, error) {+ return nil, nil+}+func (a *recordingBatchAnalyzer) DLA(context.Context, image.Image) ([]pdf.DLARegion, error) {+ return nil, nil+}+func (a *recordingBatchAnalyzer) TSR(context.Context, image.Image) ([]pdf.TSRCell, error) {+ return nil, nil+}+func (a *recordingBatchAnalyzer) OCRRecognizeBatch(_ context.Context, imgs []image.Image) ([][]pdf.OCRText, error) {+ a.callCount+++ if a.failOnCall > 0 && a.callCount == a.failOnCall {+ return nil, errors.New("injected batch failure")+ }+ ratios := make([]float64, len(imgs))+ out := make([][]pdf.OCRText, len(imgs))+ for i, im := range imgs {+ b := im.Bounds()+ ratios[i] = float64(b.Dx()) / float64(b.Dy())+ // Echo the crop's own ratio so the caller can verify round-trip mapping.+ out[i] = []pdf.OCRText{{Text: fmt.Sprintf("%.4f", ratios[i])}}+ }+ a.batches = append(a.batches, ratios)+ a.batchSizes = append(a.batchSizes, len(imgs))+ return out, nil+}++// nonBatchAnalyzer implements only the base DocAnalyzer interface (no batch).+type nonBatchAnalyzer struct{ healthy bool }++func (a *nonBatchAnalyzer) Health() bool { return a.healthy }+func (a *nonBatchAnalyzer) OCRDetect(context.Context, image.Image) ([]pdf.OCRBox, error) {+ return nil, nil+}+func (a *nonBatchAnalyzer) OCRRecognize(context.Context, image.Image) ([]pdf.OCRText, error) {+ return nil, nil+}+func (a *nonBatchAnalyzer) DLA(context.Context, image.Image) ([]pdf.DLARegion, error) {+ return nil, nil+}+func (a *nonBatchAnalyzer) TSR(context.Context, image.Image) ([]pdf.TSRCell, error) { return nil, nil }++func makeCrops(ratios []float64) []image.Image {+ // Fixed height 48 (recH); width = round(48*ratio) so W/H == ratio.+ const h = 48+ crops := make([]image.Image, len(ratios))+ for i, r := range ratios {+ w := int(r * h)+ if w < 1 {+ w = 1+ }+ crops[i] = image.NewRGBA(image.Rect(0, 0, w, h))+ }+ return crops+}++func parseRatio(s string) float64 {+ var v float64+ fmt.Sscanf(s, "%f", &v)+ return v+}++func TestOCRRecognizeBatchAligned_SortsAndChunks(t *testing.T) {+ // 40 crops with shuffled aspect ratios spanning 0.5..8.0.+ rnd := []float64{3.2, 0.8, 5.1, 1.0, 7.3, 2.0, 0.5, 8.0, 4.4, 1.5,+ 6.2, 0.9, 3.7, 2.9, 1.2, 5.8, 0.6, 4.0, 7.0, 1.8,+ 2.4, 6.6, 0.7, 3.0, 5.5, 1.1, 8.0, 4.7, 2.2, 0.55,+ 6.0, 1.6, 3.9, 9.0, 0.75, 5.0, 2.7, 1.3, 7.6, 4.2}+ if len(rnd) != 40 {+ t.Fatalf("setup: expected 40 crops, got %d", len(rnd))+ }+ crops := makeCrops(rnd)++ analyzer := &recordingBatchAnalyzer{healthy: true}+ p := NewParser(pdf.DefaultParserConfig())++ // Fallback must never be used when the batch path succeeds.+ fallbackUsed := false+ results := p.ocrRecognizeBatchAligned(t.Context(), analyzer, 0, crops, func(ci int, _ image.Image) ([]pdf.OCRText, error) {+ fallbackUsed = true+ return []pdf.OCRText{{Text: fmt.Sprintf("fallback:%d", ci)}}, nil+ })++ if fallbackUsed {+ t.Fatal("fallback should not be used when batching succeeds")+ }+ if len(results) != len(crops) {+ t.Fatalf("results len %d, want %d", len(results), len(crops))+ }++ // Chunking: 40 crops / 16 == 3 batches (16,16,8).+ wantBatches := (len(crops) + recBatchNum - 1) / recBatchNum+ if len(analyzer.batches) != wantBatches {+ t.Fatalf("batch calls = %d, want %d", len(analyzer.batches), wantBatches)+ }+ for _, sz := range analyzer.batchSizes {+ if sz > recBatchNum {+ t.Fatalf("sub-batch size %d exceeds recBatchNum=%d", sz, recBatchNum)+ }+ }+ if analyzer.batchSizes[0] != recBatchNum || analyzer.batchSizes[2] != 8 {+ t.Fatalf("unexpected chunk sizes %v", analyzer.batchSizes)+ }++ // Within every batch the ratios must be non-decreasing (ascending sort).+ for bi, b := range analyzer.batches {+ if !sort.Float64sAreSorted(b) {+ t.Fatalf("batch %d not sorted ascending: %v", bi, b)+ }+ }++ // Round-trip mapping: results[i] must correspond to the original crop i.+ for i, c := range crops {+ cb := c.Bounds()+ want := float64(cb.Dx()) / float64(cb.Dy())+ got := parseRatio(results[i][0].Text)+ if absf(got-want) > 1e-3 {+ t.Fatalf("crop %d mapping wrong: got %.4f want %.4f (ratio drift)", i, got, want)+ }+ }+}++func TestOCRRecognizeBatchAligned_FallbackOnSubBatchError(t *testing.T) {+ // 20 crops; force the batch path to fail on its 2nd call. The failed+ // sub-batch is the LAST recBatchNum-window of crops in aspect-ratio-sorted+ // order, not the last original indices — so compute the expected set from+ // the same sort the implementation uses.+ ratios := []float64{1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 0.5, 9.0,+ 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 0.6, 7.5, 8.5, 2.2}+ crops := makeCrops(ratios)++ order := make([]int, len(ratios))+ for i := range order {+ order[i] = i+ }+ sort.SliceStable(order, func(a, b int) bool { return ratios[order[a]] < ratios[order[b]] })+ wantFallback := map[int]bool{}+ for _, ci := range order[recBatchNum:] { // 2nd sub-batch (crops 16..19 in order)+ wantFallback[ci] = true+ }++ analyzer := &recordingBatchAnalyzer{healthy: true, failOnCall: 2}+ p := NewParser(pdf.DefaultParserConfig())++ var fallbackIdx []int+ results := p.ocrRecognizeBatchAligned(t.Context(), analyzer, 0, crops, func(ci int, _ image.Image) ([]pdf.OCRText, error) {+ fallbackIdx = append(fallbackIdx, ci)+ return []pdf.OCRText{{Text: fmt.Sprintf("fallback:%d", ci)}}, nil+ })++ if len(results) != len(crops) {+ t.Fatalf("results len %d, want %d", len(results), len(crops))+ }+ if len(fallbackIdx) != len(wantFallback) {+ t.Fatalf("fallback count = %d, want %d", len(fallbackIdx), len(wantFallback))+ }+ for _, ci := range fallbackIdx {+ if !wantFallback[ci] {+ t.Fatalf("crop %d fell back but is not in the failed sub-batch %v", ci, wantFallback)+ }+ if results[ci][0].Text != fmt.Sprintf("fallback:%d", ci) {+ t.Fatalf("crop %d not filled by fallback: %q", ci, results[ci][0].Text)+ }+ }+ // Crops outside the failed sub-batch keep their batch result.+ for i := range crops {+ if !wantFallback[i] && results[i][0].Text == fmt.Sprintf("fallback:%d", i) {+ t.Fatalf("crop %d wrongly fell back", i)+ }+ }+}++func TestOCRRecognizeBatchAligned_NonBatchAnalyzerFallsBackAll(t *testing.T) {+ crops := makeCrops([]float64{1.0, 2.0, 3.0, 4.0, 5.0})+ analyzer := &nonBatchAnalyzer{healthy: true}+ p := NewParser(pdf.DefaultParserConfig())++ var fallbackIdx []int+ results := p.ocrRecognizeBatchAligned(t.Context(), analyzer, 0, crops, func(ci int, _ image.Image) ([]pdf.OCRText, error) {+ fallbackIdx = append(fallbackIdx, ci)+ return []pdf.OCRText{{Text: fmt.Sprintf("fallback:%d", ci)}}, nil+ })++ if len(results) != len(crops) {+ t.Fatalf("results len %d, want %d", len(results), len(crops))+ }+ if len(fallbackIdx) != len(crops) {+ t.Fatalf("non-batch analyzer should fall back for every crop, got %d/%d", len(fallbackIdx), len(crops))+ }+}++func TestOCRRecognizeBatchAligned_UnhealthyBatchAnalyzerFallsBack(t *testing.T) {+ crops := makeCrops([]float64{1.0, 2.0, 3.0})+ analyzer := &recordingBatchAnalyzer{healthy: false}+ p := NewParser(pdf.DefaultParserConfig())++ var fallbackIdx []int+ results := p.ocrRecognizeBatchAligned(t.Context(), analyzer, 0, crops, func(ci int, _ image.Image) ([]pdf.OCRText, error) {+ fallbackIdx = append(fallbackIdx, ci)+ return []pdf.OCRText{{Text: fmt.Sprintf("fallback:%d", ci)}}, nil+ })++ if len(results) != len(crops) {+ t.Fatalf("results len %d, want %d", len(results), len(crops))+ }+ if len(fallbackIdx) != len(crops) {+ t.Fatalf("unhealthy batch analyzer should fall back for every crop, got %d/%d", len(fallbackIdx), len(crops))+ }+ // inferOCRRecognizeBatch short-circuits on !Health() before invoking the+ // analyzer (returns nil,nil), so the helper falls back via its count+ // mismatch branch without ever calling OCRRecognizeBatch.+ if analyzer.callCount != 0 {+ t.Fatalf("unhealthy batch analyzer should not invoke OCRRecognizeBatch, got %d calls", analyzer.callCount)+ }+}++func absf(x float64) float64 {+ if x < 0 {+ return -x+ }+ return x+}++var _ doctype.DocAnalyzer = (*recordingBatchAnalyzer)(nil)