Skip to content

fix: keep OCR text when no image2text model is configured - #18012

Merged
yuzhichang merged 5 commits into
infiniflow:mainfrom
Dhruv-kys:fix/17941-keep-ocr-text-without-vision-model
Aug 19, 2026
Merged

yuzhichang merged 5 commits into
infiniflow:mainfrom
Dhruv-kys:fix/17941-keep-ocr-text-without-vision-model

Conversation

@Dhruv-kys

@Dhruv-kys Dhruv-kys commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Summary

An image whose OCR text is shorter than the CV LLM threshold produces zero chunks when the tenant has no image2text model configured. The extracted text is discarded.

rag/app/picture.py sends short OCR output to the vision model:

if (eng and len(txt.split()) > 32) or len(txt) > 32:
    tokenize(doc, txt, eng, language=lang)
    return attach_media_context([doc], 0, image_ctx)
try:
    cv_model_config = get_tenant_default_model_by_type(tenant_id, LLMType.VISION)
    ...
except Exception as e:
    callback(prog=-1, msg=str(e))
return []

With no vision model set, get_tenant_default_model_by_type raises and return [] throws away txt, which already held usable OCR output. The success path keeps it (txt += "\n" + ans); only the failure path loses it.

This indexes the OCR text when the vision model is unavailable, and leaves the existing failure signal untouched when OCR found nothing.

Because the OCR-only result is a degraded parse rather than a clean one, the fallback reports [WARN] CV LLM unavailable (...), indexing OCR text only. via a message-only callback instead of callback(0.8, ...). A misconfigured or erroring vision model therefore stays visible to the operator rather than reading as a normal success, and the progress field is left for the parser/orchestrator to own.

Partially addresses #17941

#17941 bundled three problems. This PR covers the first:

Testing

uv run pytest test/unit_test/rag/app/test_picture_video.py
5 passed
  • test_short_ocr_text_is_kept_when_vision_model_is_missing — 0 chunks on main, 1 chunk here.
  • test_parser_reports_failure_when_ocr_finds_no_text — parametrized over empty and whitespace-only OCR output; a blank image with no vision model still reports prog=-1.
  • test_ocr_only_fallback_is_reported_as_degraded — the fallback keeps the chunk, emits exactly one [WARN] carrying the reason, and emits neither prog=-1 nor a clean 0.8. Fails on the pre-fix parser with the vision failure was not reported as a degraded parse.

ruff check on the two touched files reports the same 14 pre-existing errors as main (verified against a stashed tree); ruff format --check is clean.

The picture parser discarded OCR output when the text was under the CV LLM
threshold and the vision model lookup failed, so an image with readable text
produced no chunk at all.

Closes infiniflow#17941
@dosubot dosubot Bot added size:XS This PR changes 0-9 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Aug 7, 2026
@coderabbitai

coderabbitai Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 3ae2e6d7-346f-438e-9d6a-1e763b6db628

📥 Commits

Reviewing files that changed from the base of the PR and between f93fd40 and 1d8cacb.

📒 Files selected for processing (2)
  • rag/app/picture.py
  • test/unit_test/rag/app/test_picture_video.py

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.


📝 Walkthrough

Walkthrough

Picture parsing strips OCR text before length checks. When vision-model processing fails, available OCR text is indexed and the document keeps media context. Tests cover configurable OCR output, model lookup failures, successful fallback, and empty OCR output.

Changes

Picture OCR fallback

Layer / File(s) Summary
OCR fallback implementation
rag/app/picture.py
The parser strips OCR text before processing. When vision-model description fails, it reports the failure, tokenizes available OCR text, and returns the document with media context.
OCR fallback regression coverage
test/unit_test/rag/app/test_picture_video.py
The test harness configures OCR output and vision-model lookup failures. Tests verify OCR indexing when no vision model exists and error reporting when OCR output is absent or whitespace-only.

Estimated code review effort: 2 (Simple) | ~10 minutes

Merge Risk: 🔵 Low · up to 1d8ca

The change preserves non-empty OCR text when no vision model is available and reports degraded parsing. A broad exception handler can also misclassify unrelated processing failures as vision-model outages and fall back to OCR-only, so the PR is mergeable with explicit owner follow-up to narrow the handler.

Suggested labels: 🌈 python

Suggested reviewers: xugangqiang, lynn-inf

Poem

A rabbit reads the letters bright,
When vision models lose their sight.
OCR hops into the chunk,
Empty text reports what went wrong.
Hop, hop, the picture path is clear!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the primary fix: preserving OCR text when no image-to-text model is configured.
Description check ✅ Passed The description includes the required Summary section and clearly explains the problem, fix, scope, testing, and related follow-up issues.
Docstring Coverage ✅ Passed Docstring coverage is 80.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@rag/app/picture.py`:
- Around line 113-116: Add a warning-level application log in the OCR fallback
branch of the surrounding image-processing function, alongside the existing
callback, recording the CV LLM failure and that OCR text indexing is being used.
Preserve the current tokenize and attach_media_context flow while ensuring the
warning is emitted even when callback events are not retained.
- Around line 113-116: Normalize OCR text immediately after extraction and
before the length threshold and fallback branch, so whitespace-only values such
as " \n" are treated as empty and do not produce a successful empty image chunk.
Update the logic around the OCR handling flow and add a regression case covering
ocr_text=" \n".

In `@test/unit_test/rag/app/test_picture_video.py`:
- Around line 165-167: Update the docstring of
test_failure_is_reported_when_ocr_finds_no_text() to describe parser behavior:
chunk() produces no chunks and invokes the parser failure callback. Remove
references to task failure, indexing, or task-status handling.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: fbb692b6-a5c0-4207-b888-235757e4e21d

📥 Commits

Reviewing files that changed from the base of the PR and between 8e37f55 and be36e0a.

📒 Files selected for processing (2)
  • rag/app/picture.py
  • test/unit_test/rag/app/test_picture_video.py

Comment thread rag/app/picture.py Resolved
Whitespace-only OCR output is truthy, so it reached the fallback and produced
a chunk with no searchable content. Strip the text at extraction so it is
treated as empty.
@coderabbitai

coderabbitai Bot commented Aug 13, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@JinHai-CN
JinHai-CN requested a review from xugangqiang August 18, 2026 08:18
@xugangqiang

Copy link
Copy Markdown
Contributor

Thanks for the fix — the core problem (usable OCR text being discarded when no image2text model is set) is solved and the new tests are solid. A few remaining issues I'd like to flag before merge:

1. "Closes #17941" overclaims the scope.
The PR only addresses P0-1 of #17941 (index OCR text when non-empty). P0-2 (task_executor still marks chunks == [] as progress=1.0 DONE instead of keeping the failure) is deferred to #18013, and P1 (large sparse images lose most OCR text to the 960px det downscale) is not tracked anywhere. Please soften the description to "Partially addresses #17941" or split the issue, so the bug isn't treated as fully closed.

2. Vision failure is silently swallowed as a successful parse.
In the fallback, callback(0.8, ...) is sent and a successful chunk is returned instead of prog=-1. So any image with OCR text now ends up DONE even when the vision model is misconfigured, hits a network error, or cv_mdl.describe throws — the operator only gets a logging.warning, and the task status looks successful. This is a real observability regression vs. the old prog=-1. Worth either keeping a degraded-status marker on the chunk (e.g. flag it as OCR-only) or only silently falling back when the failure is specifically "model not configured".

3. except Exception is broad.
Any exception in the vision block (programming error included) now silently degrades to an OCR-only successful chunk as long as OCR produced text. Consider narrowing the catch to the "no vision model configured" case (e.g. LookupError) so genuine runtime errors stay visible.

4. Missing test for the behavior change.
No test asserts that the fallback now emits callback(0.8, ...) rather than prog=-1. Adding one would lock in the new signal and prevent regressions.

These are not blockers for the happy path, but #1 and #2 affect how the failure is reported to users.

Question for @Dhruv-kys: would you prefer to address #1–#4 (at least #1 and the prog=-1/degraded-status part of #2, which can ride along with #18013) before merge, or merge this as-is and track the rest separately?

@Dhruv-kys

Copy link
Copy Markdown
Contributor Author

Thanks — #1, #2 and #4 are fixed. On #3 I think the specific suggestion would reintroduce the bug; details below.

#1 — scope. Description now says "Partially addresses #17941" and maps the three parts: P0-1 here, P0-2 in #18013, P1 split out as #18509.

#2 — degraded status. The fallback no longer reports a clean success. It now sends a message-only [WARN] CV LLM unavailable (...), indexing OCR text only. instead of callback(0.8, ...), so a misconfigured or erroring vision model stays visible while the usable OCR text is still indexed.

I went with the message rather than a flag on the chunk because chunk fields are schema-bound — doc_type_kwd and friends are enumerated in rag/utils/serenedb_conn.py:87 and rag/utils/ob_conn.py:61, so a new *_kwd would be a multi-backend storage change. [WARN] via a message-only callback is already the convention for a degraded-but-successful step (rag/svr/task_executor.py:1196, :1200, :1258). Dropping the positional progress also keeps this out of the way of #18013.

#3 — LookupError would not catch the case this PR fixes. The unconfigured case raises a bare Exception, at api/db/joint_services/tenant_model_service.py:196:

if not model_name:
    raise Exception(f"No default {model_type} model is set.")

Exception is not a subclass of LookupError, so except LookupError would let it fall through to callback(prog=-1) — the #17941 behaviour again. And this is the path that fires in practice: img2txt_id is null=False and seeded from settings.VISION_MDL, which defaults to "" (common/settings.py:57), so an unconfigured tenant reaches :196 with an empty string rather than a LookupError from the resolver. That matches the reporter's environment note in #17941 (Tenant.img2txt_id empty).

LookupError is raised for the misconfigured neighbours instead — model disabled (:292), wrong type (:294), not found (:321) — so narrowing to it would catch those and miss the unconfigured one.

Related: the test was faking the failure as LookupError, which does not match production on this path, so it would have stayed green through that regression. Fixed to raise a bare Exception.

If you want the catch narrowed properly, the clean way is a dedicated exception (e.g. VisionModelUnavailable) raised at :196 and caught here, but that touches shared model resolution used by every model type — I would rather do it as a follow-up than widen this PR. Happy to if you prefer.

#4 — test added. test_ocr_only_fallback_is_reported_as_degraded asserts the chunk survives, exactly one [WARN] carries the reason, and neither prog=-1 nor a clean 0.8 is emitted. It fails on the pre-fix parser with the vision failure was not reported as a degraded parse.

uv run pytest test/unit_test/rag/app/test_picture_video.py → 5 passed. ruff check on the touched files shows the same 14 pre-existing errors as main; ruff format --check clean.

The fallback that indexes OCR text when the vision model is unavailable
sent callback(0.8, ...), so a misconfigured or erroring image2text model
produced a task that looked like a clean success. Send a message-only
[WARN] instead: the OCR text is still indexed, but the vision failure
stays visible and the progress field is left untouched.

Fix the test fake to raise a bare Exception rather than LookupError.
get_tenant_default_model_by_type raises Exception for an unset default
model (tenant_model_service.py:196); LookupError is only raised for the
misconfigured cases, so the fake did not match this code path.
@codecov

codecov Bot commented Aug 19, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.65%. Comparing base (423c848) to head (1d8cacb).
⚠️ Report is 163 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #18012      +/-   ##
==========================================
- Coverage   94.56%   90.65%   -3.91%     
==========================================
  Files          10       10              
  Lines         717      717              
  Branches      118      118              
==========================================
- Hits          678      650      -28     
- Misses         25       39      +14     
- Partials       14       28      +14     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@xugangqiang

Copy link
Copy Markdown
Contributor

@yuzhichang LGTM

@xugangqiang
xugangqiang requested a review from yuzhichang August 19, 2026 10:00
@yuzhichang
yuzhichang merged commit 86c2506 into infiniflow:main Aug 19, 2026
3 checks passed
mill413 pushed a commit to mill413/ragflow that referenced this pull request Sep 3, 2026
…#18012)

An image whose OCR text is shorter than the CV LLM threshold produces zero chunks when the tenant has no image2text model configured. The extracted text is discarded.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:XS This PR changes 0-9 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants