Skip to content

[Fix] Rename StandardizeImag -> StandardizeImage to fix deepdoc OCR preprocessing (#7316) - #16785

Merged
yuzhichang merged 3 commits into
infiniflow:mainfrom
Taranum01:fix/7316-standardize-image-typo
Jul 11, 2026
Merged

yuzhichang merged 3 commits into
infiniflow:mainfrom
Taranum01:fix/7316-standardize-image-typo

Conversation

@Taranum01

Copy link
Copy Markdown
Contributor

Fixes #7316.

Problem

deepdoc/vision/operators.py defines the image-standardize preprocessing op as class StandardizeImag (missing the final e), but every caller — including deepdoc/vision/recognizer.py::Recognizer.preprocess — looks the class up by the canonical string "StandardizeImage" via:

op_type = new_op_info.pop("type")  # "StandardizeImage"
preprocess_ops.append(getattr(operators, op_type)(**new_op_info))

So getattr(operators, "StandardizeImage") raised AttributeError, and the "StandardizeImage" preprocessing step silently never ran for any image pipeline that used the dynamic dispatch (LayoutLMv3 and friends). The user-visible symptom is that the standardize step is missing entirely from the preprocessing chain, so the model gets un-normalized images.

Production fix

-class StandardizeImag:
+class StandardizeImage:
     """normalize image
     Args:
         mean (list): im - mean
         std (list): im / std
         is_scale (bool): whether need im / 255
         norm_type (str): type in ['mean_std', 'none']
     """

That's the entire production change — a one-character class rename. The misnamed StandardizeImag had no other references in the codebase (verified via git grep), so removing it is safe; every caller uses the canonical "StandardizeImage" string and will now resolve correctly.

Tests

New test/unit_test/deepdoc/vision/test_operators_standardize_image.py with six regression tests, all green locally:

test_standardize_image_class_resolves_by_canonical_name            PASSED
test_standardize_image_callable_matches_legacy_alias_name          PASSED
test_standardize_image_normalizes_input_with_mean_std_and_is_scale PASSED
test_standardize_image_skips_scaling_when_is_scale_false           PASSED
test_standardize_image_norm_type_none_passes_image_through         PASSED
test_standardize_image_via_module_getattr_dispatch_path            PASSED
6 passed in 0.18s

The tests:

  1. Pin the dispatch contract (hasattr(operators, "StandardizeImage")) — this is the exact check the recognizer's getattr would do, so any future regression fails the same way the runtime would.
  2. Pin that the misspelled name is gone — if a downstream caller ever relied on it, this fails loudly.
    3–5. Behavioural coverage of the three documented code paths: is_scale=True, norm_type="mean_std", is_scale=False, norm_type="mean_std", and norm_type="none".
  3. End-to-end via the same getattr(operators, "StandardizeImage") call the recognizer uses, with a real numpy image, so any rename or removal surfaces as AttributeError instead of silently skipping the step.

Verified both ways:

  • Without the fix → all 6 tests fail (Python even suggests 'StandardizeImag' → 'StandardizeImage')
  • With the fix → all 6 pass in 0.15s

The test file follows the project's existing pattern (test/unit_test/deepdoc/parser/test_html_parser.py): load the target module via importlib.util.spec_from_file_location, stub the only project-internal import (rag.utils.lazy_image), and assert against the loaded module — no full RAGFlow runtime required.

Risk

Very low. The class is renamed; no public Python API was using the misnamed class. The only reference path is the "StandardizeImage" string in recognizer.py:270, which now resolves correctly.

Out of scope

  • No other ops in operators.py are affected; checked all the others (DecodeImage, NormalizeImage, Permute, etc.) and they all use correct names.
  • The dynamic-dispatch lookups in recognizer.py for LinearResize, StandardizeImage, Permute, PadStride all use the same dispatch path; only the StandardizeImage key was broken. No other keys need fixing.

Made with Cursor

…reprocessing (infiniflow#7316)

The preprocessing operator class in `deepdoc/vision/operators.py` was
defined as `StandardizeImag` (missing the final `e`), but every caller —
including `deepdoc/vision/recognizer.py::Recognizer.preprocess` — looks the
class up by the canonical string `"StandardizeImage"` via::

    op_type = new_op_info.pop("type")  # "StandardizeImage"
    preprocess_ops.append(getattr(operators, op_type)(**new_op_info))

so `getattr(operators, "StandardizeImage")` raised `AttributeError` and the
"StandardizeImage" preprocessing step never ran for any image pipeline that
used the dynamic dispatch (LayoutLMv3 and friends).

This renames the class to match the dispatch key. No public API change —
the class is only referenced by name from within `recognizer.py`, and only
by the string `"StandardizeImage"`.

Also adds `test/unit_test/deepdoc/vision/test_operators_standardize_image.py`
with six regression tests:

- Pin that the module exposes `StandardizeImage` (contract used by recognizer)
- Pin that the legacy misspelled name is gone
- Behavioural: mean-std normalization with is_scale=True
- Behavioural: is_scale=False skips /255
- Behavioural: norm_type='none' skips mean/std
- End-to-end via the same `getattr(operators, "StandardizeImage")` call
  the recognizer uses, so any future rename or accidental removal will
  fail loudly with `AttributeError` instead of silently skipping the step.
@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. 🧪 test Pull requests that update test cases. labels Jul 9, 2026
@coderabbitai

coderabbitai Bot commented Jul 9, 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

Run ID: 9196e18c-072f-482c-9ed3-e9a70a841d1a

📥 Commits

Reviewing files that changed from the base of the PR and between 83a65da and cc7d32a.

📒 Files selected for processing (1)
  • test/unit_test/deepdoc/vision/test_operators_standardize_image.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • test/unit_test/deepdoc/vision/test_operators_standardize_image.py

📝 Walkthrough

Walkthrough

Fixes a class-name typo in deepdoc/vision/operators.py, renaming StandardizeImag to StandardizeImage. Adds regression tests that load the operator module directly, verify the exported name, and exercise its normalization and dispatch behavior.

Changes

StandardizeImage typo fix and tests

Layer / File(s) Summary
Class name correction
deepdoc/vision/operators.py
Renames the misspelled StandardizeImag class to StandardizeImage.
Test harness and normalization checks
test/unit_test/deepdoc/vision/test_operators_standardize_image.py
Adds a direct module loader with a stubbed image helper, then verifies StandardizeImage is exported, StandardizeImag is absent, normalization works across is_scale and norm_type combinations, and recognizer-style dispatch resolves the operator correctly.

Estimated code review effort: 1 (Trivial) | ~5 minutes

Poem

A tiny typo took a hop,
Then “Imag” got nudged to stop.
The bunny smiles at tests that prove
The image path now knows its groove.
Hop hop — all pixels line up right 🐇

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main change: renaming StandardizeImag to StandardizeImage to fix OCR preprocessing.
Description check ✅ Passed The description explains the bug, fix, test coverage, and risk, which is more than enough for the repository's summary template.
Linked Issues check ✅ Passed The code rename and regression tests directly satisfy issue #7316's requirement to make StandardizeImage resolve correctly.
Out of Scope Changes check ✅ Passed The added test fixture and sys.modules cleanup are test-support changes related to the fix, not unrelated scope creep.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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: 1

🤖 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 `@test/unit_test/deepdoc/vision/test_operators_standardize_image.py`:
- Around line 45-76: The _load_operators_module helper leaves temporary entries
in sys.modules for rag, rag.utils, and rag.utils.lazy_image, which can leak into
later tests. Update the test setup to isolate these stubs by using
mock.patch.dict around the sys.modules injection or by restoring the original
modules after import completes. Keep the change localized to
_load_operators_module so test_operators_standardize_image.py does not affect
other tests that import rag.utils.lazy_image or related modules.
🪄 Autofix (Beta)

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

Run ID: 77b35419-8503-4271-9ef1-2c67c6543ef2

📥 Commits

Reviewing files that changed from the base of the PR and between 8bd6257 and 83a65da.

📒 Files selected for processing (2)
  • deepdoc/vision/operators.py
  • test/unit_test/deepdoc/vision/test_operators_standardize_image.py

…w#7316 review)

CodeRabbit review on infiniflow#16785: the helper that stubs ``rag.utils.lazy_image``
into ``sys.modules`` so we can load ``deepdoc/vision/operators.py``
without the full RAGFlow runtime never restored the pre-test state. A
later test that imports the real module would silently get the
identity-passthrough stub instead.

Move the loader into a ``pytest.fixture`` that snapshots the relevant
``sys.modules`` entries before mutation and restores them in a
``finally`` teardown — including the case where the entry was already
populated at fixture entry. Tests now consume the loaded module via
the fixture parameter rather than the module-level ``operators``
constant, so the import-time side effect is gone.

Verified end-to-end with a temporary sibling probe that walks
``sys.modules`` for ``rag.utils.lazy_image`` and asserts it no longer
carries a stub ``ModuleType`` (no ``__file__``/``__loader__``). The
probe fails against the pre-fix code and passes against the new
fixture — confirming both that the leak existed and that the fixture
now closes it.

All six standardize-image tests still green.

Co-authored-by: Cursor <[email protected]>
@Taranum01

Copy link
Copy Markdown
Contributor Author

Addressed in cc7d32a. The _load_operators_module helper has been replaced with a pytest.fixture (operators_module) that snapshots the relevant sys.modules entries — rag, rag.utils, rag.utils.lazy_image — before mutation and restores them in a finally teardown (handling both the case where the entry was populated already and the case where the fixture installed it). Tests now take the loaded module as a fixture argument instead of via the module-level operators constant, so the import-time side effect is gone.

I went with a fixture rather than mock.patch.dict because:

  1. mock.patch.dict doesn't gracefully handle the "already populated" case without manually snapshotting first, which is what the fixture does internally.
  2. A fixture gives us a single point of teardown for the whole test module, no with blocks scattered across every call site.

Verified end-to-end by temporarily reverting the helper to the leaky version and adding a sibling probe that walks sys.modules for rag.utils.lazy_image — the probe failed against the original code (ModuleType with no __file__/__loader__) and passes against the new fixture, so both the existence of the leak and its closure are pinned.

All six test_operators_standardize_image.py tests still green.

@yuzhichang
yuzhichang self-requested a review July 10, 2026 08:16

@yuzhichang yuzhichang left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM

@dosubot dosubot Bot added the lgtm This PR has been approved by a maintainer label Jul 10, 2026
@yuzhichang yuzhichang added the ci Continue Integration label Jul 10, 2026
@codecov

codecov Bot commented Jul 10, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (eca8e87) to head (a30104f).
⚠️ Report is 20 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16785   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

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

@Taranum01

Copy link
Copy Markdown
Contributor Author

Friendly bump on this one — it's been clean (CI ✅, review ✅, codecov ✅) since yesterday and there are no open threads.

Happy to address any final feedback if anything's been missed. No rush; just flagging in case it got buried in the queue. Thanks!

Resolves #7316

@yuzhichang
yuzhichang merged commit 0ee02fb into infiniflow:main Jul 11, 2026
4 checks passed
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 lgtm This PR has been approved by a maintainer size:XS This PR changes 0-9 lines, ignoring generated files. 🧪 test Pull requests that update test cases.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: StandardizeImage in deepdoc/vision/operators.py has a wrong name 'StandardizeImag'

2 participants