Repository navigation
fix: always convert frames to RGB for the NSFW frame check - #1972
Open
shreyanshj10 wants to merge 2 commits into
Open
shreyanshj10 wants to merge 2 commits into
shreyanshj10 wants to merge 2 commits into
Conversation
opennsfw2.preprocess_image expects an RGB PIL image, but predict_frame converted BGR to RGB only when the color-correction toggle was on. With the toggle off, which is the default, the model received frames with red and blue swapped. The conversion was unconditional when it was first added and only became conditional when the Fix Blueish Cam toggle was threaded through every BGR2RGB call site. Add a regression test that asserts the channel order reaching preprocess_image, with the model stubbed.
Contributor
Reviewer's GuideImplementationRemove the color-correction dependency and always convert BGR frames to RGB before passing them to the NSFW preprocessor.
TestsAdd stubbed regression tests verifying that blue frames reach the NSFW preprocessor with RGB channel order regardless of the color-correction setting.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Contributor
There was a problem hiding this comment.
Hey - I've found 1 issue
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="tests/test_predicter_channel_order.py" line_range="55-56" />
<code_context>
+ added.append(name)
+ # opennsfw2 must be ours even if the real package is installed, so that
+ # no model is ever built.
+ sys.modules["opennsfw2"] = stubs["opennsfw2"]
+ added.append("opennsfw2")
+
+ sys.modules.pop("modules.predicter", None)
</code_context>
<issue_to_address>
**Later imports see altered module state**
When the test process has already imported `opennsfw2` or `modules.predicter`, `_load_predicter` replaces or removes cached modules, and `_restore` pops them instead of restoring their prior values, so later imports see missing modules or duplicate module instances with reset module-level state and test results depend on execution order.
Save the prior `sys.modules` entries and restore them during cleanup.
Also at `tests/test_predicter_channel_order.py:58-81`.
</issue_to_address>Linked issues
#1963 NSFW preview check receives red/blue-swapped frames when Color Correction is off (default) - predict_frame converts BGR to RGB only inside the color-correction branch · 1 of 1 met
| # | Requirement | Status | Notes |
|---|---|---|---|
| 1 | Always convert BGR frames to RGB before the NSFW frame check, regardless of Color Correction. | ✅ Met | predict_frame now converts unconditionally before creating the PIL image; the regression tests check the channel order with Color Correction both off and on. |
Sourcery assessment
Approval pending. 1 finding to address first.
Blocking findings: tests/test_predicter_channel_order.py:56
The stubs were installed by hand and torn down by popping the names, so a pre-existing opennsfw2 or modules.predicter was deleted rather than put back and later imports in the same process saw a missing or duplicate module. Use patch.dict, as tests/test_core_map_faces_fallback.py already does, which restores sys.modules exactly.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
With Color Correction off — the default — the NSFW filter's frame check runs on frames whose red and blue channels are swapped.
predict_frameconverted BGR to RGB only inside the color-correction branch (modules/predicter.py#L28-L33):Image.fromarrayon a 3-channeluint8array produces modeRGBand reinterprets the bytes as-is, so with the toggle off the model is told every blue pixel is red and every red pixel is blue. No error, no crash — just quietly degraded probabilities on the one path a user turns the filter on for.Root cause
The channel order
opennsfw2needs has nothing to do with the color-correction toggle, and the two were only ever connected by accident. The conversion went in unconditionally in79c6615("use mjpeg and convert bgr to rgb"). Thirteen minutes laterc91ab8badded the "Fix Blueish Cam" toggle and wrapped everyBGR2RGBcall site in the new flag — including this one, which is not a display path and does not belong to that feature.Unconditional is the correct order for two independent reasons:
opennsfw2.preprocess_imageexpects an RGBPIL.Image. It does the flip to the model's BGR input itself (image = image[:, :, ::-1]) before subtracting the VGG channel means, so handing it BGR cancels that flip out._bgr_to_qpixmap(modules/ui.py#L275), and the twoImage.fromarray(gpu_cvt_color(...))sites at #L305 and #L1435. Frames in the pipeline are BGR; the predictor was the only place treating that as conditional.With Color Correction on, the conversion already ran, so that path's behaviour is unchanged by this PR.
The only
ndarraycaller is the still-preview check at modules/ui.py#L1115;predict_imageandpredict_videouseopennsfw2's own loaders and were never affected.Changes
predict_framealways converts BGR to RGB, inline, matching theImage.fromarray(gpu_cvt_color(...))form used elsewhere in the codebase.import modules.globalsfrommodules/predicter.py.Three lines of production code; no behaviour change anywhere else.
Tests
Added
tests/test_predicter_channel_order.py. It pushes a pure-blue OpenCV frame —(B, G, R) = (255, 0, 0)— throughpredict_frameand asserts the array that reachespreprocess_imageis[0, 0, 255].opennsfw2is stubbed, so no model is built or downloaded and the test is fast.The Color-Correction-off case is the regression test: it fails with
[255, 0, 0]before this change and passes after. The Color-Correction-on case passes either way and is there to pin that order down too, so the condition cannot come back inverted.ruff checkand thecompileallcheck are clean.Checklist status
Verified: the new regression test,
ruff, and the compile check.Not exercised: the full CONTRIBUTING checklist (enhancer on/off, map faces, camera listing, 15-minute soak). This change touches only the NSFW check's input conversion, not the swap or render pipeline, so FPS and boot time are unaffected — but I have not run the soak.
Branch
CONTRIBUTING asks for
premain, but there is nopremainbranch on the remote, and recent merges (#1959, #1942, #1938) all landed onmain, so this targetsmain. Happy to retarget if there is a branch I should be using instead.Fixes #1963
Summary by Sourcery
Correct the NSFW frame-check input color order independently of the color-correction setting.
Bug Fixes:
Tests: