Skip to content

fix: OCR.detect() returns truthy None-tuple causing NoneType subscript crash - #13951

Merged
KevinHuSh merged 1 commit into
infiniflow:mainfrom
octo-patch:fix/issue-13851-ocr-detect-none-return
May 11, 2026
Merged

KevinHuSh merged 1 commit into
infiniflow:mainfrom
octo-patch:fix/issue-13851-ocr-detect-none-return

Conversation

@octo-patch

@octo-patch octo-patch commented Apr 7, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #13851

Problem

OCR.detect() in deepdoc/vision/ocr.py returns None, None, time_dict (a truthy 3-tuple) when the text detector fails or receives a None image. However, the caller in pdf_parser.py:__ocr() checks:

bxs = self.ocr.detect(np.array(img), device_id)
if not bxs:  # False! (None, None, time_dict) is a non-empty tuple → truthy
    self.boxes.append([])
    return
bxs = [(line[0], line[1][0]) for line in bxs]  # iterates (None, None, time_dict)
# line = None → None[0] → TypeError: 'NoneType' object is not subscriptable

This causes the NoneType object is not subscriptable error that appears after "OCR started" in the chunking pipeline when using PDF + General parser.

Solution

Simplified OCR.detect() to return None (falsy) instead of None, None, time_dict on failure. The time_dict was unused by the only caller of this method. The early-return guard if not bxs: in pdf_parser.py then correctly catches it.

Testing

  • The method's only caller (pdf_parser.py:__ocr) already has a if not bxs: guard that handles the None return correctly.
  • No other callers of OCR.detect() exist in the codebase.

Summary by CodeRabbit

  • Refactor
    • Modified OCR detection function return behavior to streamline output. The function now returns detection results only, without timing metadata. Error cases now return None instead of empty tuple values.

@dosubot dosubot Bot added size:S This PR changes 10-29 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Apr 7, 2026
@yingfeng yingfeng added the ci Continue Integration label Apr 8, 2026
@yingfeng
yingfeng marked this pull request as draft April 8, 2026 01:58
@yingfeng
yingfeng marked this pull request as ready for review April 8, 2026 01:58
@coderabbitai

coderabbitai Bot commented Apr 8, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

The OCR.detect() method in deepdoc/vision/ocr.py has been refactored to remove timing metadata tracking. The function now returns None on failure and a zip iterator without timing information on success, replacing the previous 3-tuple return value (boxes, texts, time_dict).

Changes

Cohort / File(s) Summary
OCR Timing Removal
deepdoc/vision/ocr.py
Removed timing metadata tracking from OCR.detect() method. Function now returns None on failure and a zip iterator without timing information on success, eliminating the time_dict return value from all code paths.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Poem

🐰 Tick-tock away! The timer's done,
Our detect hops lighter in the sun,
No more tuple troubles here,
Simpler returns, crystal clear! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title directly describes the main fix: OCR.detect() returning a truthy None-tuple that causes a subscript crash, matching the core issue being resolved.
Description check ✅ Passed The description includes problem context, solution explanation, and testing notes, covering most required template sections despite not explicitly checking all checkboxes.
Linked Issues check ✅ Passed The PR successfully addresses issue #13851 by fixing OCR.detect() to return None instead of a truthy tuple, preventing the NoneType subscript error during chunking.
Out of Scope Changes check ✅ Passed All changes are scoped to fixing OCR.detect()'s return behavior to resolve issue #13851; no unrelated modifications are present.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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

@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.

🧹 Nitpick comments (1)
deepdoc/vision/ocr.py (1)

673-682: Fix correctly addresses the truthy-tuple bug.

Returning None on failure paths (lines 674, 679) ensures the caller's if not bxs: guard properly catches failures. The zip iterator on success (lines 681-682) maintains compatibility with the caller's iteration pattern [(line[0], line[1][0]) for line in bxs].

Consider adding debug logging on failure paths for observability, as failures here are silent. As per coding guidelines, "Add logging for new flows".

💡 Optional: Add logging for failure paths
     if img is None:
+        logging.debug("OCR.detect called with None image")
         return None

     dt_boxes, _ = self.text_detector[device_id](img)

     if dt_boxes is None:
+        logging.debug("OCR.detect: text detector returned None")
         return None

,

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@deepdoc/vision/ocr.py` around lines 673 - 682, The failure paths currently
return None silently when img is None or when dt_boxes is None; add logging
calls before each return to record context (e.g., self.logger.debug or
self.logger.error) including why it failed (e.g., "ocr: input image is None" and
"ocr: text_detector returned no boxes for device_id=%s") and keep the existing
return None and the successful zip return unchanged; reference the existing
symbols self.text_detector, device_id, img, dt_boxes, and self.sorted_boxes when
adding the log messages.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@deepdoc/vision/ocr.py`:
- Around line 673-682: The failure paths currently return None silently when img
is None or when dt_boxes is None; add logging calls before each return to record
context (e.g., self.logger.debug or self.logger.error) including why it failed
(e.g., "ocr: input image is None" and "ocr: text_detector returned no boxes for
device_id=%s") and keep the existing return None and the successful zip return
unchanged; reference the existing symbols self.text_detector, device_id, img,
dt_boxes, and self.sorted_boxes when adding the log messages.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 2ed2c6f6-1f16-4c02-b882-0677cc565c83

📥 Commits

Reviewing files that changed from the base of the PR and between c4b0aaa and 3606cb9.

📒 Files selected for processing (1)
  • deepdoc/vision/ocr.py

@codecov

codecov Bot commented Apr 8, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 96.52%. Comparing base (60ec588) to head (3606cb9).
⚠️ Report is 17 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #13951      +/-   ##
==========================================
- Coverage   98.11%   96.52%   -1.60%     
==========================================
  Files          10       10              
  Lines         690      690              
  Branches      108      108              
==========================================
- Hits          677      666      -11     
- Misses          4        8       +4     
- Partials        9       16       +7     

☔ View full report in Codecov by Sentry.
📢 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.

@yingfeng
yingfeng requested a review from xugangqiang April 8, 2026 04:01

@xugangqiang xugangqiang 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.

Appreciate for raising this PR.
On first sight, your fix should be working.
However, I am thinking on why "time_dict" is there - this value may be helpful in future.

How about this approach:

In detect method of ocr.py
A. Change the total count of return values from 3 to 2
B. If img or dt_boxes is None, return "None, time_dict"
C. Else "end=...., ret_value=zip(xxx), time_dict['all'] = end -start, return ret_value, time_dict"
In the caller (__ocr in pdf_parser.py),
bxs, time_dict = self.ocr.detect(np.array(img), device_id)
...other code follows....
Appreicate if you can add unit test for this bug under test/unit_test/deepdoc/parser

@octo-patch

Copy link
Copy Markdown
Contributor Author

@xugangqiang Thanks for the review — your approach makes sense, and keeping time_dict for future observability is the right call. I'll update the PR with:

  1. OCR.detect() returns 2 values: (result_or_None, time_dict).
  2. Failure paths (img is None / dt_boxes is None) return (None, time_dict).
  3. __ocr caller in pdf_parser.py unpacks both and checks if bxs is None:.
  4. New unit test under test/unit_test/deepdoc/parser/ covering the two failure paths.

Will push the changes in a follow-up commit.

@KevinHuSh
KevinHuSh merged commit c58906b into infiniflow:main May 11, 2026
1 check passed
tmimmanuel pushed a commit to tmimmanuel/ragflow that referenced this pull request May 14, 2026
…t crash (infiniflow#13951)

Fixes infiniflow#13851

## Problem

`OCR.detect()` in `deepdoc/vision/ocr.py` returns `None, None,
time_dict` (a truthy 3-tuple) when the text detector fails or receives a
`None` image. However, the caller in `pdf_parser.py:__ocr()` checks:

```python
bxs = self.ocr.detect(np.array(img), device_id)
if not bxs:  # False! (None, None, time_dict) is a non-empty tuple → truthy
    self.boxes.append([])
    return
bxs = [(line[0], line[1][0]) for line in bxs]  # iterates (None, None, time_dict)
# line = None → None[0] → TypeError: 'NoneType' object is not subscriptable
```

This causes the `NoneType object is not subscriptable` error that
appears after "OCR started" in the chunking pipeline when using PDF +
General parser.

## Solution

Simplified `OCR.detect()` to return `None` (falsy) instead of `None,
None, time_dict` on failure. The `time_dict` was unused by the only
caller of this method. The early-return guard `if not bxs:` in
`pdf_parser.py` then correctly catches it.

## Testing

- The method's only caller (`pdf_parser.py:__ocr`) already has a `if not
bxs:` guard that handles the `None` return correctly.
- No other callers of `OCR.detect()` exist in the codebase.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Refactor**
* Modified OCR detection function return behavior to streamline output.
The function now returns detection results only, without timing
metadata. Error cases now return `None` instead of empty tuple values.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Ricardo-M-L pushed a commit to Ricardo-M-L/ragflow that referenced this pull request Aug 17, 2026
…t crash (infiniflow#13951)

Fixes infiniflow#13851

## Problem

`OCR.detect()` in `deepdoc/vision/ocr.py` returns `None, None,
time_dict` (a truthy 3-tuple) when the text detector fails or receives a
`None` image. However, the caller in `pdf_parser.py:__ocr()` checks:

```python
bxs = self.ocr.detect(np.array(img), device_id)
if not bxs:  # False! (None, None, time_dict) is a non-empty tuple → truthy
    self.boxes.append([])
    return
bxs = [(line[0], line[1][0]) for line in bxs]  # iterates (None, None, time_dict)
# line = None → None[0] → TypeError: 'NoneType' object is not subscriptable
```

This causes the `NoneType object is not subscriptable` error that
appears after "OCR started" in the chunking pipeline when using PDF +
General parser.

## Solution

Simplified `OCR.detect()` to return `None` (falsy) instead of `None,
None, time_dict` on failure. The `time_dict` was unused by the only
caller of this method. The early-return guard `if not bxs:` in
`pdf_parser.py` then correctly catches it.

## Testing

- The method's only caller (`pdf_parser.py:__ocr`) already has a `if not
bxs:` guard that handles the `None` return correctly.
- No other callers of `OCR.detect()` exist in the codebase.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Refactor**
* Modified OCR detection function return behavior to streamline output.
The function now returns detection results only, without timing
metadata. Error cases now return `None` instead of empty tuple values.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
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:S This PR changes 10-29 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: [ERROR]Internal server error while chunking: NoneType object is not subscriptable

4 participants