15 KiB
Module internals
This page documents the current implementation contract. It intentionally avoids experiment logs, corpus counts, and calibration history. Those records live in the verification plan and the research archive listed in the documentation index.
Read the relevant section before changing a subsystem. When this page and the code disagree, the code and its tests are authoritative and this page must be updated in the same change.
Architecture
The package has four main paths:
flowchart LR
Input[Input file] --> Identify[Identify provenance]
Input --> Visible[Visible mark removal]
Input --> Invisible[Diffusion regeneration]
Input --> Metadata[Metadata stripping]
Identify --> Report[ProvenanceReport]
Visible --> VisibleOutput[Localized and filled image]
Invisible --> InvisibleOutput[Regenerated image]
Metadata --> MetadataOutput[Container with AI metadata removed]
The all command runs visible removal, optional invisible regeneration, and
metadata stripping in that order.
Command line interface
cli.py owns command parsing and
user-facing exit behavior.
Important contracts:
- Single-image arguments reject directories.
visiblewrites no output when no registered mark is selected and exits withEXIT_NO_VISIBLE_MARK.invisiblewrites no output when no supported local signal is found, unless--forceis supplied.- The two no-signal conditions currently share exit code
2. - Hard processing and write failures exit with code
1. allcan still write the completed visible and metadata stages when the diffusion dependencies are unavailable, but exits with code1so the partial result is not reported as complete.batchcounts per-file failures and exits nonzero if any file failed or an applicable invisible stage was skipped because its dependencies were absent.
The decorators for diffusion options are shared by invisible, all, and
batch. The runtime help generated by Click is the source of truth for option
names and defaults.
The deprecated --auto option does not select a pipeline or change adaptive
polishing. _resolve_auto_polish emits a
warning and returns the explicit polish value unchanged.
Regression coverage:
High-level Python API
api.py provides:
remove_visiblevisible_provenance
The package root exposes both lazily through
__getattr__, keeping a plain package
import free of the heavier image and model imports.
For path inputs, remove_visible reads provenance metadata, preserves alpha,
and optionally writes and strips metadata. Array inputs are treated as BGR
arrays and have no file provenance or separate alpha plane.
When no visible mark is removed, a same-format path copy preserves the original
bytes. write_noop=False leaves the requested output path untouched instead.
Regression coverage:
Metadata and provenance
C2PA
noai/c2pa.py reads C2PA with the
official c2pa-python reader first. Its byte-level PNG parser remains a fallback
for partial and synthetic fixtures that the official reader rejects.
Vendor attribution comes from the registry in
noai/constants.py. Derived
issuer and platform maps should not be maintained separately.
Metadata scanning and stripping
metadata.py contains the shared
metadata scanners and remove_ai_metadata.
Key contracts:
scan_headis the shared cached input for bounded byte scans.- JPEG stripping walks metadata segments and preserves the entropy-coded image scan.
- ISOBMFF containers use
noai/isobmff.py. - Supported non-ISOBMFF audio and video containers use ffmpeg stream copying.
- The low-level remover is fail-safe and can copy an undecodable file through unchanged.
- A caller that reports success must use
strip_and_verify, which scans the written output for surviving markers.
Detection and removal must stay in parity. A new marker is incomplete until the scanner can find it, the remover can reach every supported placement, and a test proves that it no longer appears in the output.
Regression coverage:
Provenance report
identify.py combines metadata,
registered visible marks, and optional open invisible-watermark decoders into a
ProvenanceReport.
is_ai_generated is True or None; absence of evidence is not reported as a
human-made verdict. ai_source_kind distinguishes fully generated content from
AI-enhanced composites when the source metadata provides that distinction.
TrustMark is reported as a watermark signal but does not by itself assert AI origin because it can also protect human-authored content.
Regression coverage:
Visible mark removal
Registry and decision flow
watermark_registry.py is
the only visible-mark registry. mark_keys() supplies the CLI choices, so the
CLI must not maintain a separate mark list.
Automatic removal has three distinct stages:
- Perception: each registered detector produces strict and relaxed candidates.
- Decision: the pure
decidearbiter applies sensitivity and corroborating provenance. - Action: each selected mark is localized to a mask and passed to the shared fill function.
sensitivity="strict" never relaxes a detector. sensitivity="auto" can relax
one only when metadata or a sufficiently strong same-product sibling confirms
that product. The removed blanket assume_ai mode is rejected explicitly.
The Jimeng pill has an additional decision gate because its visual detector is weaker than the other registered marks. Keep that policy in the registry, not inside unrelated detector engines.
remove_auto_marks removes every selected mark, not only the strongest one.
This matters for images that carry marks in more than one corner.
Regression coverage:
Gemini sparkle
gemini_engine.py uses a
multi-scale shape search and a false-positive gate. Its captured sparkle assets
serve detection and mask geometry only. Pixel recovery is performed by the
shared fill backend.
detect_sparkle_confidence uses a process-wide shared engine because its loaded
assets and template ladder are immutable.
Regression coverage:
Text mark engines
_text_mark_engine.py
provides common localization, detection front ends, template caching, rival
comparison, and footprint construction.
Each vendor module supplies a TextMarkConfig and only the behavior that cannot
be represented by the shared base:
doubao_engine.pyjimeng_engine.pyqwen_engine.pykling_engine.pyyuanbao_engine.pysamsung_engine.pyrunninghub_engine.pybaidu_engine.pyliblib_engine.py
The detector and removal mask must use compatible geometry. A detector that fires while producing an empty or misplaced mask is a removal failure even if the detection test passes.
Yuanbao uses the polarity-independent contrast front end because its standard
two-line mark can be light on dark scenes or dark on light scenes. Its detector
and footprint both use the same best-match box. The separate one-line overlay
variant is not covered.
The capture-less Jimeng pill lives in
pill_engine.py. It uses a
synthetic silhouette for detection and a fixed top-left footprint.
Each engine has a corresponding test module under tests/.
Shared behavior is covered by:
Fill backends and region erasing
region_eraser.py implements the
same backends used by visible removal and the user-directed erase command:
cv2miganlama
watermark_registry.resolve_backend selects LaMa first, then MI-GAN, then
OpenCV for auto. A memory-constrained caller should explicitly select MI-GAN
or OpenCV instead of relying on auto.
MI-GAN and LaMa crop around the mask before model inference and paste back only masked pixels. Their model sessions are loaded lazily. MI-GAN uses the inverse mask polarity expected by its ONNX model.
Regression coverage:
Invisible watermark regeneration
Profiles and strength
noai/watermark_profiles.py
is the source of truth for:
- profile aliases;
- default model identifiers;
- default steps and seeds;
- vendor-adaptive strength resolution;
- the minimum viable step calculation.
The current profiles are controlnet, sdxl, qwen, and qwen-zimage.
For serverless cold starts, InvisibleEngine.preload(global_only=True) loads the
mandatory Qwen stage and YuNet while leaving the optional Z-Image and SAM face
stack lazy until a face is detected. The default preload() still loads every
stage.
default is a legacy alias for sdxl. There is no content-dependent automatic
router.
invisible_engine.py handles
image sizing, optional pre-upscaling, postprocessing, and the public engine
interface. It delegates model execution to
noai/watermark_remover.py.
The Python engine and CLI do not have identical defaults for every optional postprocessing argument. Integrations that require reproducibility should pass the relevant values explicitly.
Regression coverage:
CPU offload
CPU offload is enabled only when requested on CUDA. The standard Diffusers
profiles call enable_model_cpu_offload. The qwen-zimage profile uses the
same flag to force its face stack out of automatic device residency.
Regression coverage:
Qwen plus Z-Image
noai/qwen_zimage_pipeline.py
implements the fixed CUDA-only two-stage profile:
- Qwen Image with Canny conditioning regenerates the frame.
- YuNet locates faces, SAM builds masks, and Z-Image regenerates the selected face regions.
The profile rejects a custom model identifier. Its global and face model stack is fixed by the implementation. When tiling is enabled, only the global stage is tiled; the face stage runs once after the tiles are blended.
Regression coverage:
Tiling
noai/tiling.py contains pure
tile planning, feather weights, tile orchestration, and region compositing.
Tiling engages only when requested and the long side exceeds the tile size. It avoids an explicit full-image downscale but does not make diffusion pixel-preserving. Each tile is still regenerated.
feather_region_composite changes only the requested box and leaves pixels
outside it unchanged.
Regression coverage:
Upscaling and postprocessing
upscaler.py is the optional
Real-ESRGAN path used only when enlarging a small image to the minimum
resolution floor. Failure or an absent extra falls back to Lanczos.
humanizer.py contains explicit
grain, unsharp masking, and adaptive polish helpers.
Regression coverage:
Image input and output
image_io.py is the shared image
codec boundary.
Contracts:
- All package OpenCV file reads and writes use
image_io.imreadandimage_io.imwrite. to_bgrnormalizes grayscale and alpha-bearing arrays.read_bgr_and_alphaandwrite_bgr_with_alphapreserve the alpha plane.imwritereturns a success flag; every caller must check it.- HEIC, HEIF, and AVIF fall back to Pillow plus
pillow-heif. - A visible no-op can preserve the original file bytes.
Regression coverage:
Adding or changing behavior
For a new visible mark:
- create a synthetic detection silhouette;
- add or extend a vendor engine;
- add one registry entry;
- test detection, false positives, localization, and actual pixel change;
- update supported signals.
For a new metadata signal:
- add the scanner;
- add every supported removal placement;
- verify the output through
strip_and_verify; - add identification and removal tests;
- update supported signals and, when relevant, the watermarking landscape.
For a diffusion change:
- keep model-free logic in pure helpers where possible;
- test option propagation and dispatch without downloading models;
- run a real model smoke for the changed model path;
- treat provider-verifier results as specific to the exact checked output;
- update known limitations.