Compare commits

...
36 Commits
Author SHA1 Message Date
Victor Kuznetsov 11afe68411 chore(release): v0.19.0 2026-07-23 16:20:27 -07:00
Victor Kuznetsov c11181b9b5 Detect and attribute Bria AI, fal.ai, and Apple Photos Clean Up
Corpus-mined vendor gaps (42k-file metadata scan, 2026-07-23):
- Bria AI signs C2PA as "Bria Artificial Intelligence" with source type
  empty (no trainedAlgorithmicMedia), so identify was completely blind;
  registered with asserts_ai like Dreamina.
- fal.ai ("fal - Features & Labels Inc.", fal-ai/<model> generators)
  was detected via the source type but never attributed; registered,
  also asserts_ai as a pure generative platform.
- Apple Photos Clean Up (Apple Intelligence object removal) was detected
  as a generic made-with-AI tag; now attributed as an AI edit via the
  photoshop:Credit marker, and the credit value joins
  AI_GENERATOR_TOKENS so removal strips it in parity.
Each new test was verified red without its fix.
2026-07-23 16:15:48 -07:00
Victor Kuznetsov eb544806f6 Add AI-generation scorer trained on metadata-labeled corpus
scripts/ai_score.py trains a gradient-boosted classifier on labels
derived from the scan_dataset metadata (C2PA AI generators, TC260,
local pipelines vs camera/screenshot/editor output) and scores every
file from pixel and container statistics alone, so metadata-stripped
files still get a score. Temporal holdout on the production corpus:
AUC 0.966 / AP 0.988. CLIP ViT-L/14 was evaluated as an alternative
and lost on both accuracy (0.82) and cost, so the model uses the
structural features the scanner already collects; scoring is CPU-only
and I/O-bound.
2026-07-23 16:01:35 -07:00
Victor Kuznetsov dfe69772cd Polish the scanner after review: shared b64 helper, tri-state pixel mode
Route the pixel layer's base64 through the capped _b64 helper, replace
the pixels/pixels_full booleans with one pixel_mode parameter, record a
pixel skipped marker on oversized files, read EXIF from the already-read
bytes instead of re-reading the file, chunk the noise residual
convolution and replace the mgrid with 1D broadcast in the FFT features
(bit-identical values, ~300 MB less peak memory at 2048px), and fix the
raw-only docstring to account for the derived pixel layer.
2026-07-23 11:54:08 -07:00
Victor Kuznetsov 68fb3dded6 Fix numpy-free metadata mode after the pixel-layer merge
Guard module-level numpy touchpoints so the metadata-only mode imports
and runs without numpy installed (deferred annotations, lazy DCT basis);
pixel modes now exit early with a clear numpy requirement message.
2026-07-23 11:13:13 -07:00
Victor Kuznetsov 47ef60c2a1 Add optional pixel forensics layer to the dataset scanner
--pixels adds aggregate, non-reconstructable pixel statistics (block-DCT
histograms with Benford deviation, high-pass noise stats, FFT band
energies and CFA peaks, ELA stats, gradient and color histograms) plus
per-section timing for pipeline latency planning. --pixels-full adds the
privacy-lifting artifacts behind an explicit flag (perceptual hash,
128px thumbnail, coarse ELA/noise-residual/FFT-phase maps). Expensive
maps are computed once and shared between the scalar and artifact paths
(2.2x speedup vs the first split implementation). numpy is required only
for the pixel modes; the metadata-only mode stays numpy-free.
2026-07-23 11:06:45 -07:00
Victor Kuznetsov a981eb84b1 Make the dataset scanner raw-only and harden format sniffing
Strip all derived output: the library verdict, the XMP edit-trail
parse, and the IJG quality estimate. The script now collects raw bytes
plus mechanical container decodes only, is fully standalone (no
remove_ai_watermarks import), and resumes interrupted runs. Add GIF,
BMP, and TIFF magic bytes to sniff_format (GIF files in the wild were
reported as unknown). Validated on the full 42k-file corpus: 100%
coverage, zero error records.
2026-07-22 20:32:36 -07:00
Victor Kuznetsov df62800bf1 Add standalone dataset metadata/forensics scanner script
Single-file read-only scanner producing one JSONL record per image:
AI verdict via identify (metadata-only, no visible marks), full EXIF/
IPTC/XMP/PNG/JPEG/WebP/ISOBMFF inventories, C2PA store, JPEG encoder
forensics (quant tables, IJG quality, scan script, Huffman, subsampling),
XMP edit-trail fields, hashes/timestamps, macOS download provenance,
Live Photo pairing id. Runs standalone (pillow/piexif/c2pa-python) with
the library optional; supports gzip output, resume after interruption,
and head-only scanning of oversized files.
2026-07-22 17:53:02 -07:00
Victor Kuznetsov 80cdaff2d5 chore(release): v0.18.0 2026-07-22 13:17:00 -07:00
Victor Kuznetsov f1a5eecf98 Register RunningHub, Baidu, and LibLibAI visible marks; park Qingyan and MiniMax (measured)
New engines, each calibrated on its TC260 USCC cohort and validated by a
full-corpus sweep (42009 files):
- runninghub: top-left corner (new corner="tl"), faint mid-gray text via
  the new raw-grayscale "gray" detection front-end, anchor-position gate
- baidu: text-run-only template (pill is a bright-blob magnet), load-bearing
  Doubao+Qwen rival margins, corner-extended footprint for the white tag
- liblib: bottom-center (new corner="bc"), Arial silhouette (font is the
  discriminative lever against latin UI text), logo-extended footprint

Qingyan parked (no clean-arm separation at any render/box), MiniMax/Hailuo
parked (1 visible frame, the xinghui rule); silhouettes kept as starting
points.
2026-07-22 13:03:03 -07:00
Victor Kuznetsov ba29eccc45 chore(release): v0.17.0 2026-07-22 09:15:07 -07:00
Victor Kuznetsov 5d63b9161f Register the Kling 可灵AI 3.0 visible text mark; park Yuanbao and cat-logo (measured)
Kling (USCC cohort 91110108335469089C, n=30): kling_engine.py, gate 0.35
(clean p99 0.304 / max 0.320), strict-only, unimodal 0.12/short on the
shared ladder, fitted locate box, no rival margin (crossfire 1/400 doubao
below gate, 0 jimeng, 0 clean), parity 9/9 detect->fill->re-detect.
Suppresses the jimeng pill like doubao/qwen. identify gains visible_kling.

Yuanbao: measured negative -- the two-line italic block does not separate
from clean corners on either front-end at any render/box/font setting;
the fitted recipe stays in render_vendor_silhouettes.py MARK_OPTS.

cat-logo: cohort has only 2 unique carriers, parked on evidence; the
draw_catlogo silhouette already separates (0.50 vs clean max 0.333), so
registration is a gate pick once more uniques arrive.

vendor_mark_calibrate: --fit-geometry takes locate-box overrides (two-line
marks were clipped by the inherited box) and the aspect sweep reaches 0.62.
2026-07-22 08:49:06 -07:00
Victor Kuznetsov 3a659ededc chore(release): v0.16.0 2026-07-21 18:35:04 -07:00
Victor Kuznetsov 008319c6a5 Register the Qwen 千问AI生成 visible text mark
Calibrated on the 117-frame TC260-producer cohort (vendor_cohort_harvest +
vendor_mark_calibrate, both committed here): per-mark 2-rung ladder
(0.78, 1.27) for the two measured size modes, fitted locate box (the mark
sits ~0.025 of the short side off the edge; doubao's box clipped the first
glyph), measured template aspect 0.26, gate 0.45 (clean p99 0.301).
Strict-only (the sub-gate band is non-Qwen banners), no rival margin
(0 cross-fires on 400 doubao / 298 jimeng / 286 clean frames).
83/83 real marks detector-clean after cv2 fill.

TextMarkConfig gains a per-mark ladder field; the shipped 3-rung default
is unchanged for every other mark.
2026-07-21 16:41:16 -07:00
Victor KuznetsovandClaude Opus 4.8 1d93704a4d Restructure the open items into a continuation list for the next session
The section had accumulated incremental edits: defects numbered out of order
(1, 2, 3a, 3, 5, 4), closed items mixed into the open table, and "what to do
next" spread across four subsections that partly repeated each other.

Now it opens with START HERE -- the prioritized next actions and the reason each
sits where it does -- followed by open defects only, renumbered 1-5. Closed items
move to their own subsection, keeping the faint-mask post-mortem because how it
escaped both parity and its own regression test is the instructive part.

Adds a table of the completed full runs with their artifacts and row counts, each
verified against the file on disk. That exists because the artifacts are the
answer to "did we actually cover X" -- relaunching a sweep costs hours and returns
nothing new, and this session nearly did exactly that before checking. It also
names the two fast confirmations (real_examples_e2e ~2 min, robustness_suite
~3 min) that a later change should run instead.

Adds invisible_engine.py:346 as an open defect: it still discards imwrite's
success flag, the same shape as the crash fixed in the previous commit.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-21 08:31:06 -07:00
Victor KuznetsovandClaude Opus 4.8 633fc3aa52 Report failed writes instead of crashing, and reject directories at parse time
The Tier E adversarial sweep (new, scripts/robustness_suite.py) drove the real CLI
over truncated, corrupt, zero-byte, absurdly-shaped and bomb inputs, unicode and
RTL paths, hostile output directories and concurrent runs. It found two crashes;
the /simplify review then reproduced a third and worse one.

1. A FAILED WRITE CRASHED ON THE SIZE REPORT. image_io.imwrite is contractually
   non-raising and returns False, but write_bgr_with_alpha discarded that bool and
   returned None, so no caller could tell a failed write from a successful one.
   Every write site then ran output.stat() to print the size, so a read-only
   destination died with a bare FileNotFoundError pointing at the stat rather than
   the write. The fix is deliberately NOT uniform: single-image commands exit via
   the new cli._write_output_or_exit; api._write_visible_result RAISES so a library
   caller gets an accurate error instead of a confusing FileNotFoundError from the
   downstream metadata strip; and the batch sites raise but never SystemExit,
   because the batch loop counts per-image exceptions and aborting would kill the
   whole run.

2. BATCH LOST DATA SILENTLY. Into a read-only output directory it wrote ZERO files
   for 2 inputs and exited 0 -- no traceback, no error, an empty output directory a
   wrapping service would read as a completed run. The robustness harness could not
   see this class at all, since it scored exit codes and traceback markers and this
   failure has neither; it now asserts on the artifacts written.

3. A DIRECTORY PASSED AS THE IMAGE crashed the metadata scanner with
   IsADirectoryError, because click.Path(exists=True) accepts directories. Fixed
   with dir_okay=False on all six source arguments, so argument parsing refuses it.

Also adds Tier B4 (scripts/resource_ceilings.py): peak RSS per fill backend from
1 MP to 25 MP, one fresh process per cell. migan 603->775 MB and lama 4679->4779 MB
are flat in input size, confirming the crop-around-the-mask design and both
documented figures; cv2 is the only backend that grows (74->440 MB, 5.9x). The
harness's own no-op check originally allocated a full-frame temp before reading
peak RSS and inflated the numbers with input size -- it now compares only the mask
box, and the conclusion survived re-measurement.

And scripts/real_examples_e2e.py, which drives every command over real corpus
examples and checks the outcome rather than the exit code: 6/6 provenance classes
identified, 10/10 metadata strips re-scan clean, all three fill backends write,
diffusion on MPS writes genuinely changed images. It records samsung as a real
partial (the faintest mark, 0.431 -> 0.404 against a 0.40 gate on the weakest of
its 3 corpus positives) and treats the gated pill's refusal to act as correct.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-20 22:45:02 -07:00
Victor Kuznetsov c2afb92832 Merge pull request #61 from wiltodelta/dependabot/uv/minor-and-patch-d57359b79f
chore(deps): bump the minor-and-patch group with 4 updates
2026-07-20 15:58:12 -07:00
Victor KuznetsovandClaude Opus 4.8 52eb40c2ca Mask faint text marks with the detector's match box, not a response threshold
The faint-mask fallback added for the tophat front-end thresholded the
max-normalized uint8 response at 0.5 -- which selects every non-zero pixel,
not "half the peak" as its comment claimed -- and filled ~120% of the corner
box on textured frames. Measured on 14 real faint-path frames (cv2 fill,
detector re-run after): the detector's own best-match box fills a 58.7%-median
corner box vs 120.9% for the threshold, both 100% detector-clean. Detection and
the mask now read one method, _tophat_best, whose score gates detection and
whose argmax box bounds the fill, so the two cannot drift by construction --
which is how the mismatch arose. The 0.5 constant is deleted.

Parity could not catch this (a mask that fills everything is trivially
detector-clean) and the regression test could not either: its flat fixture
gives every threshold the same box, so mutating the constant to 99.0 stayed
green. The fixture now carries texture and asserts the mask area is bounded,
not merely non-empty; it reproduces the corpus number (127% pre-fix).

Also lands the Tier B2 verification harnesses that found and bounded this:
- detector_response.py: response curves (detected AND maskable per cell); found
  the size response is a comb, contrast is near-irrelevant, no unmaskable cells.
- ladder_headroom.py: measured that a denser scale ladder recovers 7.6% of
  misses for a 2.52%->3.05% false-fire rise, and the one landscape rung that
  helps is a geometry shift that helps and hurts equally (1.7:1) -- do not add.
- cjk_tail_probe.py: a generic shared-tail (AI生成) template does not separate
  uncovered vendors from clean corners (0.407 vs clean p99 0.298).

Records the visible-parity re-run confirming the earlier front-end fix (doubao
91.8% -> 99.3%), and dedups the thrice-written stamp forward model into one
fill_quality.composite.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-20 15:41:18 -07:00
Victor KuznetsovandClaude Opus 4.8 7d00debdca Record the full visible-parity run and the per-mark residual split
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-20 11:11:27 -07:00
Victor KuznetsovandClaude Opus 4.8 ac20cf3a3d Record open defects, unrun verification tiers and the stale torch triage
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-20 11:10:12 -07:00
Victor KuznetsovandClaude Opus 4.8 21d7e05014 Drop AGENTS.md, CLAUDE.md is the single source
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-20 11:02:09 -07:00
Victor KuznetsovandClaude Opus 4.8 cd16e8129d Resync AGENTS.md with CLAUDE.md
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-20 10:57:52 -07:00
Victor KuznetsovandClaude Opus 4.8 836d87ed68 Mask faint text marks the tophat front-end detects but binarization loses
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-20 10:57:08 -07:00
Victor KuznetsovandClaude Opus 4.8 c150180acf Add full-surface verification harnesses and corpus sweep plan
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-20 08:14:50 -07:00
Victor KuznetsovandClaude Opus 4.8 cfefd9d819 Remove assume_ai, add tophat front-end and rival margin, fix two CLI defects
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-20 08:14:50 -07:00
Victor Kuznetsov a8f3536d3e Refactor watermark detection and provenance handling 2026-07-16 17:40:46 -07:00
Victor KuznetsovandClaude Opus 4.8 9618ac93c8 docs: record where the HF Space source lives and how it deploys
The Space's demo code (app.py etc.) lives in a SEPARATE private repo,
wiltodelta/raiw-hf-space, which nothing documented -- so finding it cost a long
detour through the Space's commit authorship and a hunt for a write token that
never existed locally. Record it, plus the deploy flow that replaced the old
web-UI editing: push to that repo's main -> sync-to-hf.yml mirrors the files via
HfApi.upload_folder (adds a commit on top of the Space history, never a force
push). Also call out the two automations that both touch the Space so they are
not confused: sync-to-hf.yml ships demo-code changes, while this repo's
distribute.yml factory-rebuilds the Space on a library release so its
`remove-ai-watermarks>=` pin re-resolves.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-16 10:24:46 -07:00
dependabot[bot] 976935f5fe chore(deps): bump the minor-and-patch group with 4 updates
Bumps the minor-and-patch group with 4 updates: [torch](https://github.com/pytorch/pytorch), [transformers](https://github.com/huggingface/transformers), [huggingface-hub](https://github.com/huggingface/huggingface_hub) and [ruff](https://github.com/astral-sh/ruff).


Updates `torch` from 2.12.1 to 2.13.0
- [Release notes](https://github.com/pytorch/pytorch/releases)
- [Changelog](https://github.com/pytorch/pytorch/blob/main/RELEASE.md)
- [Commits](https://github.com/pytorch/pytorch/compare/v2.12.1...v2.13.0)

Updates `transformers` from 5.13.0 to 5.13.1
- [Release notes](https://github.com/huggingface/transformers/releases)
- [Commits](https://github.com/huggingface/transformers/compare/v5.13.0...v5.13.1)

Updates `huggingface-hub` from 1.22.0 to 1.23.0
- [Release notes](https://github.com/huggingface/huggingface_hub/releases)
- [Commits](https://github.com/huggingface/huggingface_hub/compare/v1.22.0...v1.23.0)

Updates `ruff` from 0.15.20 to 0.15.21
- [Release notes](https://github.com/astral-sh/ruff/releases)
- [Changelog](https://github.com/astral-sh/ruff/blob/main/CHANGELOG.md)
- [Commits](https://github.com/astral-sh/ruff/compare/0.15.20...0.15.21)

---
updated-dependencies:
- dependency-name: torch
  dependency-version: 2.13.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: transformers
  dependency-version: 5.13.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: huggingface-hub
  dependency-version: 1.23.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: ruff
  dependency-version: 0.15.21
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-07-15 08:46:35 +00:00
Victor KuznetsovandClaude Opus 4.8 71dae8fe25 chore(release): bump version to 0.15.3
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-14 17:17:01 +03:00
Victor KuznetsovandClaude Opus 4.8 9fe12c3997 docs: note content-based strip routing + SDXL watermarker fixes
Document both fixes in CLAUDE.md (the metadata.py and watermark_remover.py
bullets). Also add a --backend flag to the visible-removal audit script so a
realistic quality pass can run the production MI-GAN fill instead of cv2
(removal SUCCESS is backend-independent, but only migan/lama reflect the
recovered-region quality a user actually gets).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-14 17:16:56 +03:00
Victor KuznetsovandClaude Opus 4.8 183793fbf2 fix(invisible): disable diffusers SDXL watermarker on removal output
The SDXL removal pipelines (sdxl + controlnet) were built without
add_watermarker=False, so diffusers embedded its default open "Stable
Diffusion XL" DWT-DCT invisible watermark on every output whenever
invisible-watermark is installed (the detect extra). A watermark REMOVER was
therefore replacing one detectable AI watermark (SynthID) with another: the
cleaned output re-read as AI (identify -> "Open invisible watermark: Stable
Diffusion XL"), observed on the SynthID validation sample.

Both SDXL loaders now call a shared _disable_sdxl_watermarker helper (mirrors
_maybe_add_fp16_vae; the ControlNetModel sub-model and the Qwen loader never
call it, since only the pipeline accepts the kwarg). Verified end to end: the
affected outputs re-run clean (is_ai=None, no open watermark).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-14 17:16:49 +03:00
Victor KuznetsovandClaude Opus 4.8 7f22852593 fix(metadata): route strip output format by content, not extension
remove_ai_metadata chose its save format (and the lossless-JPEG fast path)
from the OUTPUT file extension. On the ~2% of real uploads whose extension
lies about their content (a PNG served as .jpg is the common case, ~0.9% of
the corpus), the default flow -- which inherits the source's own extension --
re-encoded a lossless PNG/WebP into a real JPEG, silently degrading the pixels
and breaking the "work with originals" invariant.

Sniff the actual container from magic bytes (_sniff_image_format, reusing the
12-byte head already read for the ISOBMFF check) and route on content: a
misnamed lossless source (source-extension format != content) is preserved in
its true format, while a correctly-named source still honors a deliberate
output-extension conversion (source.png -> output.jpg). The JPEG-lossless gate
is likewise content-gated.

Found by a new metadata-removal parity audit over the local corpus
(scripts/metadata_removal_audit.py): 18170/18173 carriers strip cleanly, and
this fix takes the 208 pixel-integrity failures (all misnamed PNGs) to 0.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-14 17:16:36 +03:00
Victor Kuznetsov d9204e2e1f chore(release): bump version to 0.15.2 2026-07-13 12:27:06 +03:00
Victor KuznetsovandClaude Opus 4.8 2bdaa09e5f fix(metadata): strip bare AIGC in APP11 and AIGC in a standard PNG text chunk
Full-corpus strip audit surfaced 24 china_aigc survivors on real uploads:
- 19 JPEG carried the bare AIGC{...} blob in APP11 (0xEB). That marker's branch
  in _jpeg_app_carries_ai only tested for a C2PA/JUMBF manifest and RETURNED, so
  a bare AIGC there slipped past the generic AIGC check. The specific
  C2PA(APP11)/XMP(APP1)/IPTC(APP13) checks now fall through to the generic
  _is_aigc_exif_value drop, which runs for every APP marker they did not claim.
- PNG carried the {"AIGC":{...}} block in a STANDARD text chunk (Description).
  _is_ai_key keeps that key, so removal now also drops a text value carrying an
  AIGC block (_is_aigc_exif_value broadened to accept str; wired into the PNG
  re-save value filter), in parity with aigc_label's detection.

Verified on the corpus: decodable china_aigc survivors 27 -> 0; the 3 remaining
are truncated files the strip fail-safe (v0.15.1) copies through by design.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 12:27:05 +03:00
Victor Kuznetsov 72f6734b45 chore(release): bump version to 0.15.1 2026-07-13 11:54:53 +03:00
Victor KuznetsovandClaude Opus 4.8 220803c4d0 fix(metadata): remove_ai_metadata is fail-safe on a truncated/corrupt image
PIL raises OSError decoding a truncated file, which crashed remove_ai_metadata
(the PNG/WebP PIL re-save path) -- a direct library caller like a web worker
500s on a partial upload. ~0.2% of the real upload corpus is truncated. The
strip now probes decodability first and, on failure, copies the input through
unchanged and returns rather than raising (we cannot strip what we cannot parse),
mirroring strip_c2pa_boxes' fail-safe. identify already handled these.

The CLI `metadata --remove` on an unreadable file therefore now exits 0 with the
input passed through, not a clean error (exit 1) -- `visible`, which must decode
to remove a mark, still exits 1. Test updated to the per-command contract.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 11:54:33 +03:00
75 changed files with 11750 additions and 609 deletions

No files matched your search

+17 -12
View File
@@ -4,7 +4,7 @@ You are a **principal Python engineer** maintaining a CLI tool and library for r
## Scope and non-goals
The mission is removing **AI-provenance watermarks** that a platform stamps onto content the user generated themselves — SynthID, the Gemini / Nano Banana sparkle, the Doubao / Jimeng / Samsung visible AI labels, the Chinese TC260 "由…AI生成" label, and C2PA / IPTC / EXIF "Made with AI" metadata. The point is user autonomy over their own generated output.
The mission is removing **AI-provenance watermarks** that a platform stamps onto content the user generated themselves — SynthID, the Gemini / Nano Banana sparkle, the Doubao / Jimeng / Qwen / Samsung visible AI labels, the Chinese TC260 "由…AI生成" label, and C2PA / IPTC / EXIF "Made with AI" metadata. The point is user autonomy over their own generated output.
It deliberately does **not** remove watermarks that protect someone else's paid or copyrighted content — stock-agency overlays (Shutterstock, Getty, iStock, Adobe Stock), classifieds-site marks, or any tiled / diagonal "preview" watermark whose job is to gate a purchase. Stripping those makes a paid resource free off someone else's work; out of scope **by principle, not by technical difficulty**. The line: a visible mark is in scope when it labels the user's **own** AI generation, and out of scope when it protects a **third party's paid asset**.
@@ -17,11 +17,11 @@ Consequences for contributors (do not drift back into the stock niche just becau
## How to run
Per-command exit-code semantics (the no-signal / GPU-missing skip branches), test traps, and regression-guard paths live in `docs/module-internals.md` (section "CLI commands (`cli.py`)") — read it before changing any command's skip/exit behavior.
Per-command exit-code semantics (the no-signal / GPU-missing skip branches), test traps, and regression-guard paths live in `docs/module-internals.md` (section "CLI commands (`cli.py`)") — read it before changing any command's skip/exit behavior. Every single-image command's `source` argument declares `dir_okay=False`: without it `click.Path(exists=True)` accepts a directory, which then reached `open()` and raised `IsADirectoryError` (Tier E, 2026-07-20; `batch`'s `directory` already declared `file_okay=False`). Regression: `tests/test_cli_robustness.py::TestDirectoryInputIsRejected`.
- `uv run remove-ai-watermarks all <image.png> -o <output.png>` — full pipeline (visible + invisible + metadata). Same diffusion knobs as `invisible`, plus the visible-pass `--backend auto|cv2|migan|lama` (default `auto`) and `--sensitivity auto|strict|assume-ai` (default `auto`) for the localize -> fill visible removal (see the `visible` bullet). Skips step 2 (invisible/SynthID) when the `[gpu]` extra is absent or no invisible signal is detectable; see the module doc for the distinct exit codes.
- `uv run remove-ai-watermarks invisible <image.png> -o <out.png>` — diffusion SynthID removal. **Full knob set** (kept identical across `invisible`/`all`/`batch`): `--strength` (vendor-adaptive default), `--steps`, `--guidance-scale` (CFG, default 7.5), `--pipeline sdxl|controlnet|qwen` (default `controlnet`; `qwen` is a manual opt-in only — see the qwen note in the module map), `--controlnet-scale`, `--model` (HF model id, default SDXL base), `--device`, `--seed`, `--hf-token`, `--max-resolution`/`--min-resolution`, `--upscaler lanczos|esrgan`, `--humanize` (Analog Humanizer grain), `--unsharp` (final sharpen), `--adaptive-polish/--no-adaptive-polish` (**ON by default**), `--tile/--no-tile` + `--tile-size`/`--tile-overlap` (**OFF by default**), `--force/--no-force` (default skip = ON, runs the scrub even with no detected signal). `--auto` is deprecated and a no-op that only warns. Skips the diffusion when no invisible signal is detectable (the no-signal gate); see the module doc.
- `uv run remove-ai-watermarks visible <image.png> -o <out.png>` — known-visible-mark removal by **localize -> fill**: each detected mark is localized to a binary full-frame footprint mask, then one shared, swappable fill inpaints that mask. `--backend auto|cv2|migan|lama` (default `auto`) picks the fill: `cv2` (classical inpaint, no deps, the floor), `migan` (MI-GAN ONNX, light, the memory-tight pick where LaMa will not fit), `lama` (big-LaMa ONNX, best quality, heavier, auto-preferred when a learned backend is available); `auto` = LaMa > MI-GAN > cv2, best available. `--mark auto` (default) removes EVERY detected mark in one pass (a Jimeng-basic image carries the top-left "AI生成" pill AND the bottom-right "★ 即梦AI" wordmark) from: Gemini sparkle, Doubao "豆包AI生成", Jimeng "★ 即梦AI", Samsung Galaxy AI "✦ Contenuti generati dall'AI", and the capture-less Jimeng "AI生成" pill (top-left, metadata-gated); `--mark gemini|doubao|jimeng|samsung|jimeng_pill` forces one. `--sensitivity auto|strict|assume-ai` (default `auto`) sets how hard a borderline mark is trusted: `auto` relaxes a mark's gate only on same-product evidence (metadata provenance for that vendor, or a confidently detected sibling mark of the same product — clean images stay untouched); `strict` never relaxes; `assume-ai` relaxes every mark (the caller asserts the image is AI, e.g. a metadata-stripped screenshot uploaded to a remover — corpus-measured Gemini recall ~46% -> ~92%, at the cost of a small fill on some clean corners). Metadata provenance is read automatically and feeds `auto`; the library cannot infer AI from a stripped image, so only `assume-ai` reaches the high recall there. For arbitrary logos/objects use `erase`. When no known mark is detected the command writes no output and exits with the no-visible-mark code instead of re-serving the input; `--no-detect` forces the gemini fallback and proceeds. See the module doc for the routing/exit detail. `--backend` and `--sensitivity` are shared across `visible`/`all`/`batch`.
- `uv run remove-ai-watermarks all <image.png> -o <output.png>` — full pipeline (visible + invisible + metadata). Same diffusion knobs as `invisible`, plus the visible-pass `--backend auto|cv2|migan|lama` (default `auto`) and `--sensitivity auto|strict` (default `auto`) for the localize -> fill visible removal (see the `visible` bullet). Skips step 2 (invisible/SynthID) when the `[gpu]` extra is absent or no invisible signal is detectable; see the module doc for the distinct exit codes.
- `uv run remove-ai-watermarks invisible <image.png> -o <out.png>` — diffusion SynthID removal. **Full knob set** (kept identical across `invisible`/`all`/`batch`): `--strength` (vendor-adaptive default), `--steps` (**interacts with `--strength`**: diffusers derives its timesteps as `int(steps * strength)`, so a low `--steps` used to crash inside torch with `cannot reshape tensor of 0 elements` -- at the default 0.15 that was every value below 7. `noai/watermark_profiles.viable_steps` now raises the count to the minimum that denoises and logs the adjustment; keep the guard where it is, above `_generate_one`, so all three pipelines and the tiled path inherit it), `--guidance-scale` (CFG, default 7.5), `--pipeline sdxl|controlnet|qwen` (default `controlnet`; `qwen` is a manual opt-in only — see the qwen note in the module map), `--controlnet-scale`, `--model` (HF model id, default SDXL base), `--device`, `--seed`, `--hf-token`, `--max-resolution`/`--min-resolution`, `--upscaler lanczos|esrgan`, `--humanize` (Analog Humanizer grain), `--unsharp` (final sharpen), `--adaptive-polish/--no-adaptive-polish` (**ON by default**), `--tile/--no-tile` + `--tile-size`/`--tile-overlap` (**OFF by default**), `--force/--no-force` (default skip = ON, runs the scrub even with no detected signal). `--auto` is deprecated and a no-op that only warns. Skips the diffusion when no invisible signal is detectable (the no-signal gate); see the module doc.
- `uv run remove-ai-watermarks visible <image.png> -o <out.png>` — known-visible-mark removal by **localize -> fill**: each detected mark is localized to a binary full-frame footprint mask, then one shared, swappable fill inpaints that mask. `--backend auto|cv2|migan|lama` (default `auto`) picks the fill: `cv2` (classical inpaint, no deps, the floor), `migan` (MI-GAN ONNX, light, the memory-tight pick where LaMa will not fit), `lama` (big-LaMa ONNX, best quality, heavier, auto-preferred when a learned backend is available); `auto` = LaMa > MI-GAN > cv2, best available. `--mark auto` (default) removes EVERY detected mark in one pass (a Jimeng-basic image carries the top-left "AI生成" pill AND the bottom-right "★ 即梦AI" wordmark) from: Gemini sparkle, Doubao "豆包AI生成", Jimeng "★ 即梦AI", Qwen "千问AI生成", Samsung Galaxy AI "✦ Contenuti generati dall'AI", Baidu "百度 AI生成", LibLibAI wordmark (bottom-center), RunningHub "RunningHub AI生成" (top-left), and the capture-less Jimeng "AI生成" pill (top-left, metadata-gated); `--mark gemini|doubao|jimeng|qwen|kling|samsung|baidu|liblib|runninghub|jimeng_pill` forces one. `--sensitivity auto|strict` (default `auto`) sets how hard a borderline mark is trusted: `auto` relaxes a mark's gate only on same-product evidence (metadata provenance for that vendor, or a confidently detected sibling mark of the same product — clean images stay untouched); `strict` never relaxes. Metadata provenance is read automatically and feeds `auto`. (`assume-ai` was REMOVED in 0.16 — see the registry bullet; a user who can SEE a missed mark should point at it with `erase --region`, or name it with `--mark <text-mark> --no-detect`.) For arbitrary logos/objects use `erase`. When no known mark is detected the command writes no output and exits with the no-visible-mark code instead of re-serving the input; `--no-detect` forces the gemini fallback and proceeds. See the module doc for the routing/exit detail. `--backend` and `--sensitivity` are shared across `visible`/`all`/`batch`.
- `uv run remove-ai-watermarks erase <image.png> --region x,y,w,h -o <out.png>` — universal region eraser (any logo/object, any position). `--backend cv2` (default, no deps), `--backend migan` (MI-GAN via onnxruntime, extra `migan`; ~28 MB, ~1 GB RAM, near-LaMa), or `--backend lama` (big-LaMa, extra `lama`; best quality but ~4.7 GB RAM); `--region` is repeatable.
- `uv run remove-ai-watermarks identify <image>` — provenance verdict (platform + watermark inventory + confidence); `--json` for machine output, `--no-visible` to skip the cv2 sparkle detector
- `uv run remove-ai-watermarks metadata <image.png> --check` — inspect AI metadata (C2PA, EXIF, PNG chunks)
@@ -54,21 +54,26 @@ Compact map. The full per-module detail (design decisions, tuned thresholds, cal
- `noai/c2pa.py` — C2PA reading. `extract_c2pa_info(path)` uses the official **c2pa-python `Reader`** first (core dep, any container; `read_manifest_store_json` returns the WHOLE store JSON — active + ingredient manifests — so an AI marker on a parent manifest is seen), and falls back to the hand-rolled caBX/CBOR parser (`has_c2pa_metadata` / `extract_c2pa_chunk` / `_extract_c2pa_info_png`) for synthetic/partial blobs the validator rejects or a broken/absent wheel. The registry scan (issuer / source-type / SynthID / soft-binding) is shared by both paths via `_populate_registry_fields`, so the return-dict shape is identical. Do not reimplement chunk parsing; chunk reads are clamped to the remaining file size by design. `extract_c2pa_chunk`/`inject_c2pa_chunk` stay PNG-only (raw caBX bytes, test/extractor use).
- `noai/constants.py` — the single `C2PA_AI_VENDORS` registry (+ `C2PA_SOFT_BINDINGS`) from which `C2PA_ISSUERS` / `SYNTHID_C2PA_ISSUERS` / `C2PA_IDENTITY_AI_ORGS` / `identify._ISSUER_PLATFORM` are all derived. Add a new vendor as one registry entry; never edit the derived dicts and never add inline. A vendor's `asserts_ai=True` flag means its mere presence asserts AI generation even without a `trainedAlgorithmicMedia` digital-source-type (a pure-generator brand with a distinctive issuer/generator string, e.g. **Dreamina** — ByteDance's international Jimeng brand, signed as "Bytedance Pte. Ltd." with a "Dreamina/x.y" claim generator and no source-type); NEVER set it for common-word issuers (Adobe/Google/OpenAI/Microsoft) that appear incidentally in unrelated bytes — those stay source-type-gated in `identify._attribute_platform`.
- `metadata.py` — `scan_head(path)` is the shared (memoized) input for every C2PA/AIGC/IPTC byte scan; use it instead of `open().read(1MB)` for any new marker scan. Also home to `synthid_source`, `xai_signature`, `iptc_ai_system`, `aigc_label`, `huggingface_job`, `samsung_genai`, and `remove_ai_metadata` (fail-safe `strip_c2pa_boxes`). **`remove_ai_metadata` is the SINGLE metadata stripper** (the legacy PIL-re-encoding `noai/cleaner` was deleted; the diffusion core and the public `noai.remove_ai_metadata` re-export now point here). It strips **losslessly** per container: ISOBMFF (HEIC/AVIF/MP4) blanks tokens / strips boxes in place; **JPEG uses `_strip_jpeg_metadata_lossless`** — a marker-segment walk that drops the AI-bearing APP segments (C2PA APP11; XMP APP1 carrying C2PA, a China-AIGC token, OR an IPTC `digitalSourceType` / 2025.1 AI-disclosure marker; IPTC-IIM APP13) and scrubs AI EXIF tags via piexif, copying the entropy-coded scan verbatim so **the pixels are bit-identical** (no DCT re-encode). **Detection<->removal parity across every marker placement is load-bearing** — anything a scanner flags, the strip must reach, or a re-served file still reads as AI: (a) the APP1-XMP branch of `_jpeg_app_carries_ai` checks the IPTC marker sets too, not only C2PA/AIGC (the Instagram/MidJourney/Meta "Made with AI" `digitalSourceType` lives in XMP, not the APP13 IIM record); (b) a bare `AIGC{...}` / `{"AIGC":{...}}` block in a NON-standard APP segment (near JFIF on some China gens) is dropped via `_is_aigc_exif_value`, not only the APP11/APP1/APP13 cases; (c) the China TC260 `{"AIGC":{...}}` block in EXIF `UserComment`/`ImageDescription` is scrubbed by `_scrub_ai_exif` (Doubao producer + Tencent service-provider schemas); (d) the Samsung Galaxy AI `PhotoEditor_Re_Edit_Data` trailer past the JPEG EOI is truncated by `_strip_samsung_trailer` (and `samsung_genai` reads the file tail so a multi-MB photo's trailer past the 512 KB quick-scan window is still DETECTED). Pixels stay bit-identical throughout, so a `--strip-metadata` on a q100 removal output does NOT crush it back to q75; PNG/WebP re-saves are pixel-lossless (WebP written at cv2 lossless mode, quality 101 — quality 1-100 is lossy). Regression: `tests/test_metadata.py::TestHasAiMetadata::{test_jpeg_metadata_strip_is_pixel_lossless, test_jpeg_strip_removes_iptc_marker_in_xmp}`, `TestSamsungGenai::{test_remove_strips_post_eoi_trailer, test_detects_trailer_past_scan_window}`, the AIGC-EXIF/bare-APP removal tests, and `tests/test_noai.py::TestISOBMFF::{test_blank_aigc_block_in_exif, test_blank_xai_signature_pair_in_exif}`. `exif_generator` matches a VALUE against `AI_GENERATOR_TOKENS` across EXIF `Software`/`Make`/`Artist`/`ImageDescription`, XMP `CreatorTool`, AND PNG `tEXt` chunks (`Software`/`Source`/`Title`/`Description` — NovelAI stamps there, not EXIF). **Detection and removal must stay in parity:** a generator that stamps an AI-shaped VALUE under a non-AI KEY (NovelAI's `Title`/`Source`) is dropped on removal by `_is_ai_value` (value-token match, mirrors `exif_generator`), NOT by `_is_ai_key` alone — else the cleaned file still reads as that generator. Add a new no-C2PA generator = one `AI_GENERATOR_TOKENS` entry (use a distinctive token, e.g. `reve.com` not bare `reve`); detection and removal then both follow. Regression: `tests/test_metadata.py::TestExifGenerator::{test_novelai_png_text_chunk_detected,test_novelai_removal_parity}`.
- `metadata.py` — `scan_head(path)` is the shared (memoized) input for every C2PA/AIGC/IPTC byte scan; use it instead of `open().read(1MB)` for any new marker scan. Also home to `synthid_source`, `xai_signature`, `iptc_ai_system`, `aigc_label`, `huggingface_job`, `samsung_genai`, and `remove_ai_metadata` (fail-safe `strip_c2pa_boxes`). **A caller that REPORTS an outcome must use `strip_and_verify`, not `remove_ai_metadata` directly** -- the stripper is deliberately fail-safe (a file PIL cannot decode is copied through UNCHANGED rather than crashing), so its return value cannot distinguish a no-op from a real strip. `metadata --remove` and `batch --mode metadata|all` both re-scan the OUTPUT through it and fail loudly; corpus-observed on real Samsung Galaxy S22 C2PA PNGs, where the command printed "stripped" and exited 0 while the output still read as AI (2026-07-19). **`remove_ai_metadata` is the SINGLE metadata stripper** (the legacy PIL-re-encoding `noai/cleaner` was deleted; the diffusion core and the public `noai.remove_ai_metadata` re-export now point here). It strips **losslessly** per container: ISOBMFF (HEIC/AVIF/MP4) blanks tokens / strips boxes in place; **JPEG uses `_strip_jpeg_metadata_lossless`** — a marker-segment walk that drops the AI-bearing APP segments (C2PA APP11; XMP APP1 carrying C2PA, a China-AIGC token, OR an IPTC `digitalSourceType` / 2025.1 AI-disclosure marker; IPTC-IIM APP13) and scrubs AI EXIF tags via piexif, copying the entropy-coded scan verbatim so **the pixels are bit-identical** (no DCT re-encode). **Detection<->removal parity across every marker placement is load-bearing** — anything a scanner flags, the strip must reach, or a re-served file still reads as AI: (a) the APP1-XMP branch of `_jpeg_app_carries_ai` checks the IPTC marker sets too, not only C2PA/AIGC (the Instagram/MidJourney/Meta "Made with AI" `digitalSourceType` lives in XMP, not the APP13 IIM record); (b) a bare `AIGC{...}` / `{"AIGC":{...}}` block in ANY JPEG APP segment — the specific C2PA(APP11)/XMP(APP1)/IPTC(APP13) checks FALL THROUGH to a generic `_is_aigc_exif_value` drop, so a bare AIGC in APP11 (the common real-corpus placement, NOT a C2PA manifest) is caught, not swallowed by the C2PA-only 0xEB branch — plus the same AIGC block in a STANDARD **PNG text chunk** value (e.g. `Description`, which `_is_ai_key` keeps) is dropped on the value; (c) the China TC260 `{"AIGC":{...}}` block in EXIF `UserComment`/`ImageDescription` is scrubbed by `_scrub_ai_exif` (Doubao producer + Tencent service-provider schemas); (d) the Samsung Galaxy AI `PhotoEditor_Re_Edit_Data` trailer past the JPEG EOI is truncated by `_strip_samsung_trailer` (and `samsung_genai` reads the file tail so a multi-MB photo's trailer past the 512 KB quick-scan window is still DETECTED). Pixels stay bit-identical throughout, so a `--strip-metadata` on a q100 removal output does NOT crush it back to q75; PNG/WebP re-saves are pixel-lossless (WebP written at cv2 lossless mode, quality 101 — quality 1-100 is lossy). **The PIL-fallback save format is chosen by the source's CONTENT, not its file extension** (`_sniff_image_format`, and the JPEG-lossless gate is content-gated too): ~2% of real uploads are misnamed (a PNG served as `.jpg` is the common one), and routing on the extension re-encoded a lossless PNG/WebP into a real JPEG — a silent degradation that broke "work with originals" (corpus-measured ~0.9% of files). A **misnamed** lossless source (source-extension format != content) is preserved in its true format; a **correctly-named** source still honors a deliberate output-extension conversion (e.g. `source.png -> output.jpg`). Not yet handled: a 16-bit PNG is downconverted to 8-bit on the PIL re-save (rare; would need a byte-level PNG chunk stripper). Regression: `tests/test_metadata.py::TestHasAiMetadata::test_strip_preserves_lossless_content_with_mismatched_extension`. **`remove_ai_metadata` is fail-safe on an undecodable image:** a truncated/corrupt file (PIL raises `OSError` decoding it; ~0.2% of real uploads) is copied through UNCHANGED rather than crashing a direct library caller (a web worker would 500 on a partial upload), mirroring `strip_c2pa_boxes` — we cannot strip what we cannot parse, but we never raise. Regression: `tests/test_metadata.py::TestHasAiMetadata::test_remove_ai_metadata_failsafe_on_truncated_png`. Regression: `tests/test_metadata.py::TestHasAiMetadata::{test_jpeg_metadata_strip_is_pixel_lossless, test_jpeg_strip_removes_iptc_marker_in_xmp}`, `TestSamsungGenai::{test_remove_strips_post_eoi_trailer, test_detects_trailer_past_scan_window}`, the AIGC-EXIF/bare-APP removal tests, and `tests/test_noai.py::TestISOBMFF::{test_blank_aigc_block_in_exif, test_blank_xai_signature_pair_in_exif}`. `exif_generator` matches a VALUE against `AI_GENERATOR_TOKENS` across EXIF `Software`/`Make`/`Artist`/`ImageDescription`, XMP `CreatorTool`, AND PNG `tEXt` chunks (`Software`/`Source`/`Title`/`Description` — NovelAI Line truncated
- `identify.py` — aggregates every locally-readable signal into one `ProvenanceReport`; `is_ai_generated` is True or None, never asserted False. `ProvenanceReport.ai_source_kind` exposes the C2PA digital-source-type split — `"generated"` (trainedAlgorithmicMedia, fully AI) vs `"enhanced"` (compositeWithTrainedAlgorithmicMedia, a real photo with an AI-composited region), else None — so a caller branches full-frame scrub vs region-targeted clean (see `noai/tiling.feather_region_composite` + `WatermarkRemover.remove_watermark(region=...)`). The sparkle provenance threshold is the SHARED `watermark_registry.GEMINI_SPARKLE_TRUST_CONF` (imported, not a private copy) so the provenance "is there a sparkle" verdict and the removal "take the sparkle" decision can never drift. `import identify` is deliberately light (lazy `noai/__init__`, fits a 512 MB host) — keep heavy imports out (the `watermark_registry` constant import stays light: engines are lazy there). Add capture-camera tokens to `_DEVICE_C2PA_PLATFORM` only when verified against a real C2PA file; editing-app/AI-device signer tokens go to `_SIGNER_C2PA_PLATFORM`; generator/issuer platforms to `C2PA_AI_VENDORS` in `constants.py`. The IPTC `digitalSourceType` **`algorithmicMedia`** (bare) is PROCEDURAL (an algorithm not trained on sampled data), NOT AI/ML generation, so it is deliberately absent from `IPTC_AI_MARKERS` — flagging it made `identify` assert AI + `has_invisible_target` True, scrubbing clean procedural content (it is a distinct token from `trainedAlgorithmicMedia`, so real "Made with AI" labels are unaffected; regression `test_metadata.py::...test_bare_algorithmic_media_not_flagged_ai`). Integrity-clash detection is high-precision by design (only hard generator stamps feed it, source-grouped independence). `_vendor_of` normalizes ByteDance/Canva/ElevenLabs/Black Forest Labs (as well as OpenAI/Google/... ) so their C2PA claims participate in the clash check; the generic **China TC260 AIGC label names no specific vendor**, so when a TC260-applying vendor (ByteDance, `_TC260_VENDORS`) is co-attributed the label is attributed to it (a legit Doubao image carrying its own TC260 label must NOT clash), while a NON-TC260 vendor next to a TC260 label still clashes as a laundering tell. Corpus-validated: adding the vendors introduced 0 new clashes on 5000 carriers.
- `watermark_registry.py` — the single catalog of known visible watermarks (gemini / doubao / jimeng / samsung / jimeng_pill). **Removal is LOCALIZE -> FILL for every mark:** each mark is localized to a binary full-frame footprint mask (a `Localization`), then ONE shared, swappable fill inpaints that mask via `fill(image, mask, backend=...)` (delegates to `region_eraser.erase`). Reverse-alpha (the old `original = (wm - a*logo)/(1-a)` inversion of a captured alpha map + thin residual inpaint) is GONE for ALL marks; why it was dropped is recorded in `docs/module-internals.md`. Backends: `cv2` (classical inpaint, no deps, the floor), `migan` (MI-GAN ONNX, light, the memory-tight pick where LaMa will not fit), `lama` (big-LaMa ONNX, best quality, heavier, auto-preferred when a learned backend is available); `auto` = LaMa > MI-GAN > cv2, best available. The captured alpha maps (`scripts/visible_alpha_solve.py`) are still used to DETECT the marks and to shape the mask, but NOT for pixel recovery. **`--mark auto` removes EVERY detected mark in one pass** via `remove_auto_marks(image, *, sensitivity="auto", provenance=frozenset(), backend="auto")` (marks coexist -- a Jimeng-basic image has the top-left pill AND the bottom-right wordmark; a single-strongest pick would leave one). **Three orthogonal axes:** `backend` (the fill), `sensitivity` (how hard to trust a borderline mark: `auto`/`strict`/`assume_ai`, see the `Sensitivity` literal), and `provenance` (vendor keys metadata confirms -- the evidence that drives `auto`). **Perception / decision / action are separated:** `_build_candidates(image)` runs every detector at BOTH trust levels (strict + relaxed) and packages raw verdicts + features into `Candidate`s (no policy); the pure arbiter `decide(candidates, Context(sensitivity, provenance)) -> [Decision]` makes every keep/drop call (per-mark `resolve_relax` + the pill gate) with no image/IO, so it is unit-testable in isolation; then each winner is localized -> filled. Do NOT put policy back into the engines (the one exception, the Gemini FP gate, stays in `gemini_engine` because `identify` shares that confidence). `detect_marks(..., provenance=frozenset())` stays strict (identify verdict, precision over recall); `KnownMark.remove/detect/localize(..., provenance: bool)` take the already-resolved boolean. **How auto/assume decide (this is metadata-INDEPENDENT for recall):** the visual detectors are pixel-based and need no metadata; the recall gain comes from RELAXING the false-positive gate, not from metadata. `strict` never relaxes (clean images untouched); `auto` relaxes a mark only on same-product evidence -- metadata provenance for that vendor OR a confidently detected sibling mark of the SAME product (`_PRODUCT_OF`; Doubao and Jimeng are both bottom-right ByteDance but distinct products, so they do NOT cross-relax); `assume_ai` relaxes every mark (the caller asserts AI -- a metadata-stripped screenshot uploaded to a remover). Corpus finding: Gemini sparkle removal on Google-C2PA images is ~46% under `strict`/metadata-free `auto` and ~92% under `assume_ai` (recovering marks the vendor moved or re-rendered); the library CANNOT infer AI from a stripped image, so only the caller's `assume_ai` reaches the high recall there. A wrong relaxation just fills a small corner near-losslessly (the localize -> fill benign failure mode), which is what makes `assume_ai` acceptable. Metadata provenance mapping (feeds `auto`, read by `cli._visible_provenance`): Google/Gemini C2PA issuer -> gemini; China-AIGC (TC260) label -> doubao/jimeng; `samsung_genai` -> samsung. **The `jimeng_pill` is CAPTURE-LESS** (`pill_engine.py`): the top-left "AI生成" label has no captured alpha map, so it is detect-by-synthetic-silhouette; its footprint is a fixed top-left geometry box. Its weak edge-NCC detector (~7% raw false-fire) is gated in `remove_auto_marks` via **`_keep_pill`** (32k real-upload corpus validation 2026-07): the pill never rides on a **Doubao** detection, and has confirmation arms because metadata/intent confirms the platform, not pill presence. **(1) Bottom-right "★ 即梦AI" wordmark fired** — ~94% precise and survives **metadata-STRIPPED uploads** (screenshots / re-saves, ~61% of pills carry a detectable wordmark): remove **unrestricted**. **(2) TC260 metadata confirms Jimeng** (`"jimeng" in provenance`, no wordmark) **OR the caller asserts AI** (`sensitivity == "assume_ai"`) — the metadata-only arm is only ~27% precise and its false fires are **textured ceilings/walls that the fill visibly SMEARS**, so remove **only when the top-left footprint is flat enough for an invisible fill** (`pill_engine.footprint_is_flat`, median-Sobel texture ≤ `_FLAT_TEXTURE_MAX`) — the flatness guard holds even under `assume_ai`. This keeps real flat-scene pills (incl. metadata-only ones the wordmark misses) plus harmless flat false fires, and leaves the damaging textured false fires untouched. Do NOT drop the wordmark arm or loosenLine truncated
- `watermark_registry.py` — the single catalog of known visible watermarks (gemini / doubao / jimeng / qwen / kling / samsung / runninghub / baidu / liblib / jimeng_pill). **Removal is LOCALIZE -> FILL for every mark:** each mark is localized to a binary full-frame footprint mask (a `Localization`), then ONE shared, swappable fill inpaints that mask via `fill(image, mask, backend=...)` (delegates to `region_eraser.erase`). Reverse-alpha (the old `original = (wm - a*logo)/(1-a)` inversion of a captured alpha map + thin residual inpaint) is GONE for ALL marks; why it was dropped is recorded in `docs/module-internals.md`. Backends: `cv2` (classical inpaint, no deps, the floor), `migan` (MI-GAN ONNX, light, the memory-tight pick where LaMa will not fit), `lama` (big-LaMa ONNX, best quality, heavier, auto-preferred when a learned backend is available); `auto` = LaMa > MI-GAN > cv2, best available. The captured alpha maps (`scripts/visible_alpha_solve.py`) are still used to DETECT the marks and to shape the mask, but NOT for pixel recovery. **`--mark auto` removes EVERY detected mark in one pass** via `remove_auto_marks(image, *, sensitivity="auto", provenance=frozenset(), backend="auto")` (marks coexist -- a Jimeng-basic image has the top-left pill AND the bottom-right wordmark; a single-strongest pick would leave one). **Three orthogonal axes:** `backend` (the fill), `sensitivity` (how hard to trust a borderline mark: `auto`/`strict`, see the `Sensitivity` literal), and `provenance` (vendor keys metadata confirms -- the evidence that drives `auto`). **Perception / decision / action are separated:** `_build_candidates(image)` runs every detector at BOTH trust levels (strict + relaxed) and packages raw verdicts + features into `Candidate`s (no policy); the pure arbiter `decide(candidates, Context(sensitivity, provenance)) -> [Decision]` makes every keep/drop call (per-mark `resolve_trust` + the assumed-trust floor + the pill gate) with no image/IO, so it is unit-testable in isolation; then each winner is localized -> filled. Do NOT put policy back into the engines (the one exception, the Gemini FP gate, stays in `gemini_engine` because `identify` shares that confidence). `detect_marks(..., provenance=frozenset())` stays strict (identify verdict, precision over recall); `KnownMark.remove/detect/localize(..., provenance: bool)` take the already-resolved boolean. **How `auto` decides (this is metadata-INDEPENDENT for recall):** the visual detectors are pixel-based and need no metadata; the recall gain comes from RELAXING the false-positive gate, not from metadata. `strict` never relaxes (clean images untouched); `auto` relaxes a mark only on same-product evidence -- metadata provenance for that vendor OR a confidently detected sibling mark of the SAME product (`_PRODUCT_OF`; Doubao and Jimeng are both bottom-right ByteDance but distinct products, so they do NOT cross-relax). **`resolve_trust` resolves TWO levels:** `confirmed` bypasses the engine's false-positive gate, and only `confirmed` has evidence naming THAT vendor, which is exactly what the bypass is contracted to require (`GeminiEngine.detect_watermark`'s `trust_provenance` docstring: "external metadata already proves this is a Google generation"). **Historical, kept as the reason the third level is gone:** a removed `assumed` level let `assume_ai` bypass the gate on the bare assertion an image is AI. On its first form that left only the raw 0.35 detector threshold and it fired on **59.8% of 256 genuine camera captures**, filling a phantom sparkle on ~6 of every 10 CLEAN photos; a confidence floor made it tolerable, and the mode was removed outright in 0.16. Corpus-measured 2026-07-16 before removal (400 Google-C2PA positives with metadata hidden; 256 camera-capture negatives): recall strict 55.0% / auto 55.2% / assume_ai 62.8%, false fire 0.0% / 0.0% / 2.3% -- the extra recall was never free. A wrong relaxation only fills a small corner near-losslessly (the localize -> fill benign failure mode), which is what made a SMALL false-fire rate arguable; it was never a licence for a 60% one. Metadata provenance mapping (feeds `auto`, read by `cli._visible_provenance`): Google/Gemini C2PA issuer -> gemini; China-AIGC (TC260) label -> doubao/jimeng; `samsung_genai` -> samsung. **The `jimeng_pill` is CAPTURE-LESS** (`pill_engine.py`): the top-left "AI生成" label has no captured alpha map, so it is detect-by-synthetic-silhouette; its footprint is a fixed top-left geometry box. Its weak edge-NCC detector (~7% raw false-fire) is gated in `remove_auto_marks` via **`_keep_pill`** (32k real-upload corpus validation 2026-07): the pill never rides on a **Doubao**, **Qwen**, **Kling**, **RunningHub** or **Baidu** detection (each of those marks names its own product, and none is Jimeng-basic), and has confirmation arms because metadata/intent confirms the platform, not pill presence. **(1) Bottom-right "★ 即梦AI" wordmark fired** — ~94% precise and survives **metadaLine truncated
- `gemini_engine.py` — visible Gemini-sparkle detector + localizer (cv2/numpy, no GPU): top-K size-weighted fusion candidate selection (`_SELECT_TOPK`), corner-promote, false-positive gate (the provenance prior relaxes the gate + lowers the trust threshold when a Google/Gemini C2PA issuer confirms the vendor). **White-core rescue:** the FP gate demotes a low-gradient match (soft edges), but a real FAINT sparkle also has soft edges -- so the gate keeps a low-grad match that is a strong (conf ≥ `_SPARKLE_KEEP_CONF` 0.52), bright (margin), near-WHITE-core sparkle (`_core_saturation` ≤ `_SPARKLE_WHITE_SAT` 0.20): a real sparkle core is white, a clean bright corner that shape-matches (sky/sun) is colored. This recovers ~14/20 metadata-stripped faint sparkles under the DEFAULT strict/auto (no flag, no metadata) at ~1.25% clean false-fire (baseline 0.55%); the ~0.51-scoring bright-bg FPs stay demoted (below 0.52). A learned classifier on the SAME features was measured WORSE than the tuned gate (2026-07 tier-1: MLP 86.7% recall vs 90.8% at equal FP), so the heuristic stays; a patch-CNN with richer features is the only lever left (roadmapped P2, low expected value -- the wall is fundamental). Detection scores the top-K size-weighted matches by full fusion (spatial+gradient+variance) and keeps the highest — NOT the raw-NCC argmax, which re-admits the tiny-patch FPs the size weight suppresses (the osachub 2026-06-12 sub-0.85 corner-sparkle regression; see `docs/module-internals.md`). Keep the 0.85 corner-promote NCC gate; a margin/chroma-gated lower promote was measured and REJECTED 2026-06-11 (~33% FP on non-Google content). Removal is localize -> fill: `footprint_mask` returns the sparkle footprint (the captured alpha thresholded LOW so the faint halo is included, then dilated by a sparkle-relative margin), and the shared `watermark_registry.fill` inpaints it. The captured alpha maps are used only to detect and to shape the mask, not for pixel recovery. `detect_sparkle_confidence` reuses a process-wide `_shared_engine()` singleton (lru_cache) — the engine holds only constant assets (captures, alpha maps, a precomputed 16..118 template ladder) and takes the image as an arg, so do NOT reconstruct `GeminiEngine()` per call: that reloaded assets + recomputed alpha maps + rebuilt the template cache on every one of ~34k `identify` calls (−24% on the sparkle path once made a singleton, output byte-identical). `detect_watermark`/`footprint_mask` guard `image.size == 0` before `to_bgr`, and return an empty (detected=False) result when no template scale fits (short side < 16 px), rather than dereferencing an empty candidate list.
- `_text_mark_engine.py` — shared base for the three text-mark engines (extracted 2026-06-09); the per-engine modules are config-only subclasses. Detection still matches the glyph silhouette (NCC, keys on glyph shape). The removal mask is TEMPLATE-FREE: it is the bounding box of the top-hat glyph blob (`extract_mask`), filled solid + dilated, so the shared fill inpaints the whole wordmark rectangle. This drops the fixed alpha-template placement, so a re-rendered or differently-placed mark is still masked; the captured alpha maps are now used only for the detection silhouette, not for removal. New text mark = a `TextMarkConfig` + a thin subclass + one registry row. Gemini stays a separate engine (different model).
- `_text_mark_engine.py` — shared base for the text-mark engines (extracted 2026-06-09); the per-engine modules are config-only subclasses. Detection still matches the glyph silhouette (NCC, keys on glyph shape). The removal mask is TEMPLATE-FREE: it is the bounding box of the top-hat glyph blob (`extract_mask`), filled solid + dilated, so the shared fill inpaints the whole wordmark rectangle. This drops the fixed alpha-template placement, so a re-rendered or differently-placed mark is still masked; the captured alpha maps are now used only for the detection silhouette, not for removal. New text mark = a `TextMarkConfig` + a thin subclass + one registry row. Gemini stays a separate engine (different model). The corner anchor is `corner` = `br`/`bl`/`tl`/`bc` (tl added 2026-07-22 for runninghub, bc for liblib's centered wordmark); `detect_frontend` is `binary`/`tophat`/`gray` (`gray` = raw-grayscale NCC for the faint mid-gray runninghub mark, added 2026-07-22; contrast-DEPENDENT, so its gates never port). The detection scale ladder is per-mark (`TextMarkConfig.ladder`, default `(0.8, 1.0, 1.25)` -- added 2026-07-21 for qwen's two size modes; the shared default is unchanged for every other mark, and densifying the SHARED ladder was measured and rejected, see `docs/verification-plan.md` B2).
- `pill_engine.py` — the CAPTURE-LESS Jimeng-basic "AI生成" pill (top-left, issue #54). No alpha map: `detect` is edge-NCC of a synthetic font-rendered silhouette (`assets/jimeng_pill.png`, regenerate via `scripts/render_pill_silhouette.py`; committed, data-safe -- corpus stays out of the repo) in the top-left ROI, calibrated on 61 local real positives to threshold 0.22; `footprint_mask` is a generous FIXED top-left geometry box (NOT the NCC match position -- the synthetic silhouette localizes only approximately, the corner is negative space, so a geometry box fills cleanly while a match box leaves outline residue). `footprint_texture`/`footprint_is_flat` (median-Sobel over that box, `_FLAT_TEXTURE_MAX`) back the metadata-only safe-fill gate. Removal is the shared localize -> fill (MI-GAN/cv2). Detector precision is weak (~7% raw false-fire), so it is registry-gated in `remove_auto_marks` via `_keep_pill`: never on Doubao; the bottom-right wordmark removes it unrestricted (~94% precise, survives metadata-STRIPPED uploads); TC260-metadata-only removes it ONLY on a flat footprint (its textured false fires -- ceilings/walls -- are what the fill smears). Do NOT loosen those gates.
- `doubao_engine.py` / `jimeng_engine.py` / `samsung_engine.py` — thin `TextMarkEngine` subclasses: Doubao "豆包AI生成" (bottom-right), Jimeng "★ 即梦AI" (bottom-right), Samsung Galaxy AI "✦ Contenuti generati dall'AI" (bottom-LEFT, locale-specific — Italian variant calibrated). Detection matches the glyph silhouette (NCC); removal localizes the glyph blob to a solid dilated box (`extract_mask`) and hands it to the shared fill. Corpus validation: doubao and jimeng localize + remove at ~100% with clean footprints (the filled region blends into its surroundings within a few LAB levels, no color shift, no dark pit); clean images with no vendor signature had 0% false removal. **Samsung detection is calibrated only for the Italian "Contenuti generati dall'AI" string** (a pre-existing limit, unchanged by the localize -> fill refactor but now surfaced because detection gates removal): non-Italian Samsung locales are not detected, and thus not removed, even though the fill mask itself is locale-independent; other locales need their own detection silhouette (the locale string font-rendered + calibrated on real positives), NOT an app capture.
- `region_eraser.py` — universal region eraser (`erase` CLI) and the shared fill backend behind `watermark_registry.fill` for the visible localize -> fill removal. Three backends: `cv2` (default, no deps, the floor), `migan` (MI-GAN ONNX, extra `migan`, MIT, ~28 MB / ~0.19 s — the droplet-friendly tier, **the preferred default fill** when the extra is installed), `lama` (big-LaMa ONNX, extra `lama`, ~200 MB / ~4.7 GB peak — best quality, does not fit a minimal droplet, explicit opt-in only). Both `migan` and `lama` **crop a padded region around the mask** before inference and paste only masked pixels back, so peak RAM is bounded by the MARK size, not the image (`migan` ~0.6-0.9 GB regardless of upload size — feeding the whole frame scaled it to ~2.4 GB at 25 MP; `migan` feeds the crop at native resolution, `lama` resizes to its fixed 512²). **MI-GAN mask polarity is INVERTED** (0=hole/255=known) vs this package's 255-erase convention; `erase_migan` inverts before feeding the model (feeding 255=hole regenerates the whole frame into stripes — corpus-validated). Both ONNX models download on first use, never bundled. The `erase` command keeps its own `--backend`/`--inpaint-method` (unchanged).
- `qwen_engine.py` — the Qwen (Alibaba Tongyi Qianwen) "千问AI生成" text mark (bottom-right), registered 2026-07-21 off the 117-frame TC260-producer cohort (`scripts/vendor_cohort_harvest.py` + `scripts/vendor_mark_calibrate.py`; the full calibration record is in `docs/module-internals.md`). Same `TextMarkEngine` subclass shape, but EVERY tuned number is measured on the cohort, not inherited from doubao: `scale_basis=short`, a **per-mark 2-rung `ladder=(0.78, 1.27)`** (the mark sits in two size modes ~0.124/~0.203 of the short side, ratio 1.64 -- wider than the shared ladder's 1.5625 span, so the best single fraction covers only 74.5% and the small mode falls into the comb's collapse zone; `TextMarkConfig.ladder` was added for this, default `(0.8, 1.0, 1.25)` unchanged for every other mark), a fitted locate box (the real mark sits ~0.025 of short off the right edge and doubao's 0.004-margin box clipped the first glyph, 0.73 -> 0.26 NCC), `alpha_height_frac` from the measured 0.260 aspect (not the silhouette's, not doubao's), gate **0.45** (clean p99 0.301; 83 of ~96 eyeballed visible marks fire = 86% recall of visible marks). **STRICT ONLY** (`provenance_ncc_factor` 1.0, no provenance mapping): the sub-gate band is dominated by non-Qwen banners (夸克 strip 0.274, 造点 mark 0.253), so a relaxed arm would be mostly false fills. **No rival margin** (0 cross-fires on 400 doubao / 298 jimeng / 286 clean frames at the gate; a 0.10 margin would cost ~10% of genuine qwen detections). A confident qwen detection suppresses the jimeng pill like doubao's does. Parity: 83/83 real marks detector-clean after cv2 fill. **Calibration trap for the next vendor:** the 2026-07-18 `present: []` clean labels are in the vocabulary of the REGISTERED marks only -- qwen-cohort frames visibly carrying 千问AI生成 sat in the "clean" arm and were its whole top tail (p99 0.69); `vendor_mark_calibrate.load_sets` now excludes every frame in ANY TC260 cohort.
- `kling_engine.py` — the Kling (Kuaishou 可灵) "可灵AI 3.0" text mark (bottom-right), registered 2026-07-21 off the 30-frame TC260-producer cohort, same playbook as qwen. UNIMODAL at 0.12 of the short side, so it keeps the shared 3-rung ladder and gets a fitted locate box (margins ~0.03/0.023); gate **0.35** (clean p99 0.304 / max 0.320), STRICT ONLY (the faint "Omni"-suffix / latin "KlingAI" / version-less variants score 0.17-0.25, inside the clean arm's top tail -- unreachable, capping recall at ~47% of visible marks, precision 9/9), no rival margin (crossfire 1/400 doubao below gate, 0 jimeng, 0 clean). Parity 9/9. Suppresses the jimeng pill like doubao/qwen. **元宝 (Tencent Yuanbao) was attempted the same day and PARKED as a measured negative** -- its two-line italic-slanted block does not separate from clean corners on either front-end at any render/box setting (full record in `docs/verification-plan.md`); the fitted render recipe stays in `render_vendor_silhouettes.py` `MARK_OPTS` as the starting point for a future structural/learned lever. The **cat-logo** cohort was also probed and parked: 19 frames but only 2 unique carriers, so nothing to calibrate recall against; the `draw_catlogo` silhouette already separates (mark 0.50 vs clean max 0.333) and registration is a gate pick (~0.42) once more unique carriers arrive.
- `runninghub_engine.py` — the RunningHub "RunningHub AI生成" mark (**top-left**, the first `corner="tl"`), registered 2026-07-22 off the 73-frame TC260 cohort. Faint mid-gray text that the top-hat suppresses to clean-arm levels, so it introduced the **third detection front-end `gray`** (raw-grayscale silhouette NCC, contrast-DEPENDENT, one `_gray_best` method serving detection and mask): positives 0.38-0.54 vs clean max 0.295, gate **0.34**, STRICT ONLY. Two measured traps: the tight ladder `(0.95, 1.0, 1.05)` sits exactly on the measured 0.32-of-width (the comb is razor-sharp: 0.537 on-size vs 0.223 at +5.6%), and an **anchor gate** in `detect` (match must sit at x<=0.025 / y<=0.015 of the frame) kills the 37/42009 full-corpus false fires (hair, shelves, CJK banners) that no NCC threshold separates from the 0.381 positives. Footprint is always the detector's match box (the binary blob under-segments the faint head glyphs and left "Runni" unremoved on the first try).
- `baidu_engine.py` — the Baidu "百度 AI生成" mark (bottom-right), registered 2026-07-22 off the 16-frame cohort (USCC names Baidu). Detection keys on the 百度 **text run ONLY** (a text+pill template was a measured bright-blob magnet with no separation); the white "AI生成" tag is still removed because the custom `footprint_mask` extends the match box right to the corner (the tag's flat white interior gives no top-hat response, so a blob bbox left it as a ghost). Gate settled at **0.48** after three measured steps (0.37 clean-arm; the 741-eval set fired on 12 Qwen marks + one 抖音 mark, so `rivals=("doubao_alpha.png","qwen_alpha.png")` with load-bearing margins; the full-corpus sweep put true outside-cohort carriers at 0.50-0.66 vs the false arm max 0.47). Cohort 7/16, all true, plus 6 metadata-stripped true carriers the cohort cannot see. STRICT ONLY.
- `liblib_engine.py` — the LibLibAI (哩布哩布AI) "LibLibAI" wordmark (**bottom-center**, the first `corner="bc"`), registered 2026-07-22 off the 15-frame cohort. The discriminative lever is the silhouette **font**: STHeiti scored the cohort at the false arm's level (latin UI text bands); measured across 7 fonts, **Arial** lifts the cohort to 0.42-0.73 and drops the false arm to max 0.398. Gate **0.42**, STRICT ONLY, plus a per-mark size floor (`_MIN_SHORT_SIDE=480`: the one remaining false fire was a 200x200 icon on a 20px template). Custom footprint = match box extended left ~1.3 glyph heights for the triangle logo (the blob bbox bled into background structure and never owned the logo). **Zhipu Qingyan (清言·AI生成) and MiniMax/Hailuo were attempted the same day and PARKED** as measured negatives (qingyan: cohort 0.34-0.39 vs clean max 0.34-0.37, no separation at any render/box; minimax: 1 of 6 frames visibly marked, the xinghui rule) -- record in `docs/verification-plan.md` ("The 2026-07-22 vendor round").
- `region_eraser.py` — universal region eraser (`erase` CLI) and the shared fill backend behind `watermark_registry.fill` for the visible localize -> fill removal. Three backends: `cv2` (default, no deps, the floor), `migan` (MI-GAN ONNX, extra `migan`, MIT, ~28 MB / ~0.19 s — the droplet-friendly tier, **the preferred default fill** when the extra is installed), `lama` (big-LaMa ONNX, extra `lama`, ~200 MB / ~4.7 GB peak — best quality, does not fit a minimal droplet, explicit opt-in only). Both `migan` and `lama` **crop a padded region around the mask** before inference and paste only masked pixels back, so peak RAM is bounded by the MARK size, not the image (`migan` ~0.6-0.9 GB regardless of upload size — feeding the whole frame scaled it to ~2.4 GB at 25 MP; `migan` feeds the crop at native resolution, `lama` resizes to its fixed 512²). **Measured end to end 2026-07-20** (`scripts/resource_ceilings.py`, fresh process per cell, 1 MP → 25 MP): `migan` 603 → 775 MB and `lama` 4679 → 4779 MB, both **flat in input size** — the crop-around-the-mask design holds and both documented figures reproduce. **`cv2` is the only backend that GROWS with the input** (74 → 440 MB, 5.9x) because it inpaints the full frame rather than a crop; still the cheapest tier, but size it for the largest upload accepted. Cold wall time 0.02-0.12 s (cv2) / ~0.6 s (migan) / ~3.8 s (lama), model load included. (The harness's own no-op check originally allocated a full-frame temp before reading peak RSS and inflated these by up to 17% at 25 MP; it now compares only the mask box. The conclusion survived re-measurement, the digits moved.) **MI-GAN mask polarity is INVERTED** (0=hole/255=known) vs this package's 255-erase convention; `erase_migan` inverts before feeding the model (feeding 255=hole regenerates the whole frame into stripes — corpus-validated). Both ONNX models download on first use, never bundled. The `erase` command keeps its own `--backend`/`--inpaint-method` (unchanged).
- `invisible_watermark.py` — decodes the OPEN DWT-DCT watermarks (SD / SDXL / FLUX) via `imwatermark` (extra `detect`, pulls torch). Fragile two ways: (1) does not survive JPEG re-encode/resize; (2) **carrier-fragile on a broad class of pristine images** -- a clean encode->decode round-trip recovers 48/48 on chatgpt/firefly/random but FAILS (28-39/48, below the `_MATCH_48`=44 gate) on the FLUX fox, doubao, a flat FLUX generation, AND a clean synthetic flat fill with no watermark. The failure does NOT track texture; it goes with a degenerate **all-ones decode that is a CARRIER ARTIFACT, not a watermark** (synthetic clean image reproduces it). So `detect_invisible_watermark` is **positive-only**: trust a hit; a `None` is inconclusive unless a same-carrier positive-control embed first recovers >=44. Verified 2026-06-19; full caveat in `docs/watermarking-landscape.md`.
- `trustmark_detector.py` — Adobe TrustMark open decoder (extra `trustmark`). Do NOT remove the JPEG re-encode false-positive gate — a lone TrustMark hit without it is almost always content noise.
- `noai/watermark_remover.py` — `WatermarkRemover` with three diffusion pipelines selected by the explicit `pipeline` ctor arg, never inferred from `model_id`: `sdxl` (plain SDXL img2img), `controlnet` (SDXL + canny ControlNet, **the DEFAULT since 2026-06-09**), and `qwen` (Qwen-Image 20B MMDiT img2img, Apache-2.0, CUDA/cloud-class — best **text** preservation (incl. CJK); `_load_qwen_pipeline`/`_run_qwen`, bf16, no MPS fallback; call shape in the pure `_build_qwen_kwargs` using `true_cfg_scale`). Removal comes from the img2img `strength`; ControlNet only preserves text/face STRUCTURE — SynthID CAN survive controlnet on photoreal content at low strength. Qwen CERTIFIED oracle floors (2026-06-20): OpenAI **0.10** (seed-robust, clean on seeds 0-4), Gemini **0.25** (seed 0 verified, pin a seed — Gemini oracle rate-limits volume; higher than the controlnet Gemini floor 0.15). `resolve_strength(..., pipeline="qwen")` carries the Qwen ladder (`_QWEN_VENDOR_STRENGTH`), so `--pipeline qwen` gets the 0.25 Gemini floor automatically (the old manual `--strength 0.25` workaround is retired). `_build_qwen_kwargs` passes an explicit `height`/`width` from the input (floored to /16 via `_qwen_target_size`) — without it the pipeline defaults to a 1024x1024 SQUARE and silently squishes non-square inputs (fixed 2026-06-20). **`qwen` is a MANUAL opt-in only — there is NO auto-router.** Measured (`scripts/fidelity_metrics.py`, OCR-CER / ArcFace / LPIPS / Laplacian-var, NOT eyeball): qwen beats controlnet on ONE niche only — **clean body text on a plain background, no faces** (openai_1/2 CER 0.241 vs 0.385). controlnet wins FACES (it always has) AND **display/decorative text in a scene** (abba poster: controlnet CER 0.114 vs qwen 0.379 — canny holds letter shapes, qwen re-renders and garbles them). So a content `--pipeline auto` router and a faces+text **mixed dual-pass** were prototyped and **DROPPED** (2026-06-20): on the canonical faces+text case controlnet wins every metric incl. text, so mixed loses; and "text→qwen" can't be auto-decided (it is body-vs-display text that matters, undetectable cheaply). qwen stays for callers who KNOW their content is clean-text-heavy and face-free. No face-restore extra ships, by validated decision (every restore approach looked MORE AI-generated). `remove_watermark(region=(x,y,w,h), region_feather=...)` runs the regeneration but feather-composites only the AI box back over the original (via `noai/tiling.feather_region_composite`), preserving the real photo elsewhere — the **AI-enhanced composite** path (`identify` `ai_source_kind == "enhanced"`); the box is supplied by the caller (a C2PA composite manifest carries no reliable machine-readable region, so we do not fabricate one).
- `noai/watermark_remover.py` — `WatermarkRemover` with three diffusion pipelines selected by the explicit `pipeline` ctor arg, never inferred from `model_id`: `sdxl` (plain SDXL img2img), `controlnet` (SDXL + canny ControlNet, **the DEFAULT since 2026-06-09**), and `qwen` (Qwen-Image 20B MMDiT img2img, Apache-2.0, CUDA/cloud-class — best **text** preservation (incl. CJK); `_load_qwen_pipeline`/`_run_qwen`, bf16, no MPS fallback; call shape in the pure `_build_qwen_kwargs` using `true_cfg_scale`). Removal comes from the img2img `strength`; ControlNet only preserves text/face STRUCTURE — SynthID CAN survive controlnet on photoreal content at low strength. **Both SDXL loaders (`_load_pipeline`, `_load_controlnet_pipeline`) pass `add_watermarker=False`** — diffusers otherwise embeds an open "Stable Diffusion XL" DWT-DCT invisible watermark on EVERY SDXL output whenever `invisible-watermark` is installed (the `detect` extra), so a watermark REMOVER would re-stamp a detectable AI watermark and the cleaned output re-reads as AI (`identify` → "Open invisible watermark: Stable Diffusion XL"; corpus-observed on the SynthID sample before the fix). Only the pipeline accepts the kwarg, not the `ControlNetModel` sub-model; qwen is not SDXL and has no such watermarker. Regression: `tests/test_platform.py::TestNoReembeddedWatermark`. Qwen CERTIFIED oracle floors (2026-06-20): OpenAI **0.10** (seed-robust, clean on seeds 0-4), Gemini **0.25** (seed 0 verified, pin a seed — Gemini oracle rate-limits volume; higher than the controlnet Gemini floor 0.15). `resolve_strength(..., pipeline="qwen")` carries the Qwen ladder (`_QWEN_VENDOR_STRENGTH`), so `--pipeline qwen` gets the 0.25 Gemini floor automatically (the old manual `--strength 0.25` workaround is retired). `_build_qwen_kwargs` passes an explicit `height`/`width` from the input (floored to /16 via `_qwen_target_size`) — without it the pipeline defaults to a 1024x1024 SQUARE and silently squishes non-square inputs (fixed 2026-06-20). **`qwen` is a MANUAL opt-in only — there is NO auto-router.** Measured (`scripts/fidelity_metrics.py`, OCR-CER / ArcFace / LPIPS / Laplacian-var, NOT eyeball): qwen beats controlnet on ONE niche only — **clean body text on a plain background, no faces** (openai_1/2 CER 0.241 vs 0.385). controlnet wins FACES (it always has) AND **display/decorative text in a scene** (abba poster: controlnet CER 0.114 vs qwen 0.379 — canny holds letter shapes, qwen re-renders and garbles them). So a content `--pipeline auto` router and a faces+text **mixed dual-pass** were prototyped and **DROPPED** (2026-06-20): on the canonical faces+text case controlnet wins every metric incl. text, so mixed loses; and "text→qwen" can't be auto-decided (it is body-vs-display text that matters, undetectable cheaply). qwen stays for callers who KNOW their content is clean-text-heavy and face-free. No face-restore extra ships, by validated decision (every restore approach looked MORE AI-generated). `remove_watermark(region=(x,y,w,h), region_feather=...)` runs the regeneration but feather-composites only the AI box back over the original (via `noai/tiling.feather_region_composite`), preserving the real photo elsewhere — the **AI-enhanced composite** path (`identify` `ai_source_kind == "enhanced"`); the box is supplied by the caller (a C2PA composite manifest carries no reliable machine-readable region, so we do not fabricate one).
- `noai/tiling.py` — sliding-window tiled diffusion for large inputs (CLI `--tile`). `WatermarkRemover.remove_watermark` branches to `run_tiled` when `tile` is set AND the long side exceeds `tile_size`, refactoring the single-pass `_generate` into a per-tile `_generate_one` (the ControlNet edge map is rebuilt per tile inside it). Pure helpers `plan_tiles` (uniform-size tiles, last one flush to the edge) and `feather_weights` (strictly-positive separable taper -> partition-of-unity blend) are unit-tested without the model. Also home to `feather_region_composite(base, regenerated, box, *, feather)` — the pure region-targeted compositor for **AI-enhanced composites** (`ai_source_kind == "enhanced"`): blends the regenerated AI box back over the original with a feathered seam, leaving the real photo OUTSIDE the box pixel-exact. It backs `WatermarkRemover.remove_watermark(region=...)` (regenerate ONLY the AI region, not the whole frame); the no-model lossless region path stays `region_eraser.erase`. New tile/region-blend tuning goes in these pure helpers; do not inline blend math into the runner.
- `auto_config.py` + the content-detection layer were REMOVED 2026-06-09; `--auto` is a deprecated no-op (controlnet is the default pipeline and the adaptive polish is ON by default and self-gates to a no-op where there is no detail deficit).
- `upscaler.py` — optional Real-ESRGAN pre-diffusion super-resolution for small inputs (extra `esrgan`, spandrel only). Manual opt-in; the default `--upscaler` stays `lanczos` and the engine always falls back to Lanczos on absence/error. ESRGAN can degrade faces and thin text.
- `image_io.py` — Unicode-safe cv2 IO (issue #17). Every cv2 file read/write in the package routes through `imread`/`imwrite`; do not call `cv2.imread`/`cv2.imwrite` directly. `to_bgr(image)` is the shared channel normalizer — use it instead of inlining `cvtColor` branches. `read_bgr_and_alpha`/`write_bgr_with_alpha` (+ `ALPHA_FORMATS`) are the alpha-preserving IO helpers shared by the CLI and the library `api` (moved here from cli so both use ONE implementation; the write MUST NOT zero alpha in the mark bbox — issue #30 white box). cv2/numpy import lazily, so importing `image_io` is cheap. **`imread` has a Pillow fallback (`_pil_read`) for HEIC/AVIF**: cv2 can't decode those containers, so when its decode returns None it opens via Pillow (AVIF native; HEIC via the core `pillow-heif` dep, whose libheif also covers AVIF) and converts to the same BGR/BGRA layout the flags imply — so the pixel/removal path reads iPhone HEIC and AVIF, not just the metadata path. Normal PNG/JPEG/WebP never reach the fallback. Corpus-verified: 54/55 HEIC+AVIF now decode (the 1 miss is a truncated upload). **`imwrite` PRESERVES the input format at max quality** ("work with originals"): the removal only touches the mark footprint (cv2 AND MI-GAN fills composite over the original — untouched pixels are bit-exact), so the container re-encode must not degrade the rest. JPEG is written at quality 100 / 4:4:4 (no chroma subsampling) — PSNR ~55 dB vs the old default-95's ~48; HEIC/AVIF write via Pillow (`_pil_write`) since cv2 has NO encoder for them (writing `.heic` via cv2 RAISES — a HEIC input used to crash on save). `imwrite` never raises (catches `cv2.error`). **`api.remove_visible` copies the original bytes verbatim on a no-op** (nothing removed + same output format) rather than a lossy re-encode, so a clean image round-trips byte-identical. `noai/constants.SUPPORTED_FORMATS` now includes `.heic`/`.heif`/`.avif` alongside png/jpg/jpeg/webp (pillow-heif is core, so read+write both work), so `batch` discovers them and the CLI no longer warns on an iPhone HEIC; JPEG-XL stays OUT (metadata/strip-only, no pixel decoder without pillow-jxl). **The invisible/SynthID path is inherently a full-frame diffusion regeneration (every pixel changes by design — you cannot "work with originals" there), but it no longer piles gratuitous re-encodes on top:** `watermark_remover` saves the regenerated output through `image_io.imwrite` (not raw `PIL.save`, which defaults to JPEG q75), `invisible_engine` writes its pre-diffusion temp as lossless PNG (not a re-compressed copy of a JPEG input), and the output metadata strip goes through the byte-level `metadata.remove_ai_metadata` (see its bullet) which for JPEG does NOT re-encode the DCT at all — pixels stay bit-identical.
- `image_io.py` — Unicode-safe cv2 IO (issue #17). Every cv2 file read/write in the package routes through `imread`/`imwrite`; do not call `cv2.imread`/`cv2.imwrite` directly. `to_bgr(image)` is the shared channel normalizer — use it instead of inlining `cvtColor` branches. `read_bgr_and_alpha`/`write_bgr_with_alpha` (+ `ALPHA_FORMATS`) are the alpha-preserving IO helpers shared by the CLI and the library `api` (moved here from cli so both use ONE implementation; the write MUST NOT zero alpha in the mark bbox — issue #30 white box). **`write_bgr_with_alpha` RETURNS `imwrite`'s success flag and every caller must check it** — `imwrite` is contractually non-raising, so that bool is the ONLY signal the file was not created. The wrapper used to return `None` and swallow it, so a write that a read-only directory silently prevented ran on to `output.stat()` and died with a bare `FileNotFoundError` traceback pointing at the stat rather than the write (Tier E, 2026-07-20). **Three different layers each needed their own handling, and the right one is NOT the same everywhere:** the single-image commands (`visible --mark <name>`, `erase`, `all`) write through the shared `cli._write_output_or_exit`, which exits; `api._write_visible_result` (behind `visible --mark auto`) RAISES `OSError` so a library caller gets an accurate error instead of a confusing `FileNotFoundError` from the downstream metadata strip; and the **batch** sites raise too, never `SystemExit` — the batch loop catches per-image exceptions, counts them and exits non-zero, so aborting there would kill the whole run. Discarding the flag in batch made a read-only output directory produce **zero files and still exit 0** — silent data loss contradicting the documented batch contract. Regression: `tests/test_cli_robustness.py`. cv2/numpy import lazily, so importing `image_io` is cheap. **`imread` has a Pillow fallback (`_pil_read`) for HEIC/AVIF**: cv2 can't decode those containers, so when its decode returns None it opens via Pillow (AVIF native; HEIC via the core `pillow-heif` dep, whose libheif also covers AVIF) and converts to the same BGR/BGRA layout the flags imply — so the pixel/removal path reads iPhone HEIC and AVIF, not just the metadata path. Normal PNG/JPEG/WebP never reach the fallback. Corpus-verified: 54/55 HEIC+AVIF now decode (the 1 miss is a truncated upload). **`imwrite` PRESERVES the input format at max quality** ("work with originals"): the removal only touches the mark footprint (cv2 AND MI-GAN fills composite over the original — untouched pixels are bit-exact), so the container re-encode must not degrade the rest. JPEG is written at quality 100 / 4:4:4 (no chroma subsampling) — PSNR ~55 dB vs the old default-95's ~48; HEIC/AVIF write via Pillow (`_pil_write`) since cv2 has NO encoder for them (writing `.heic` via cv2 RAISES — a HEIC input used to crash on save). `imwrite` never raises (catches `cv2.error`). **`api.remove_visible` copies the original bytes verbatim on a no-op** (nothing removed + same output format) rather than a lossy re-encode, so a clean image round-trips byte-identical. `noai/constants.SUPPORTED_FORMATS` now includes `.heic`/`.heif`/`.avif` alongside png/jpg/jpeg/webp (pillow-heif is core, so read+write both work), so `batch` discovers them and the CLI no longer warns on an iPhone HEIC; JPEG-XL stays OUT (metadata/strip-only, no pixel decoder without pillow-jxl). **The invisible/SynthID path is inherently a full-frame diffusion regeneration (every pixel changes by design — you cannot "work with originals" there), but it no longer piles gratuitous re-encodes on top:** `watermark_remover` saves the regenerated output through `image_io.imwrite` (not raw `PIL.save`, which defaults to JPEG q75), `invisible_engine` writes its pre-diffusion temp as lossless PNG (not a re-compressed copy of a JPEG input), and the output metadata strip goes through the byte-level `metadata.remove_ai_metadata` (see its bullet) which for JPEG does NOT re-encode the DCT at all — pixels stay bit-identical.
- `api.py` — the high-level convenience API, re-exported lazily at the package top level via `__init__.__getattr__` (PEP 562, so `import remove_ai_watermarks` stays cheap): `remove_visible(source, output=None, *, sensitivity="auto", backend="auto", strip_metadata=True, write_noop=True) -> (result_bgr, [labels])` (source = path OR BGR ndarray; a PATH auto-reads metadata provenance and preserves alpha, an ARRAY does neither; `write_noop=True` writes a clean passthrough copy when nothing is removed, `False` leaves `output` untouched so a "no mark = produce nothing" caller like the CLI `visible` command does not clobber a pre-existing file there) and `visible_provenance(path) -> frozenset[str]` (the single metadata→vendor-keys mapper; `cli._visible_provenance` is a thin None-guarded wrapper over it). **`remove_visible` is the ONE path the CLI and library share** — `cli.cmd_visible`'s `--mark auto` branch delegates entirely to it (read → provenance → `remove_auto_marks` → write → `strip_metadata`), so there is no CLI-vs-library drift; `strip_metadata` defaults True to match `visible --strip-metadata`. This is where a library caller should start — NOT the engines directly (`GeminiEngine`/`TextMarkEngine` have no `remove_watermark` any more; removal is registry `remove_auto_marks`/`KnownMark.remove`; the old single-strongest `best_auto_mark` is gone — removal takes EVERY mark). `identify` is NOT top-level re-exported (it collides with the `identify` submodule); use `from remove_ai_watermarks.identify import identify`.
For the Doubao alpha-distillation history (why content-image reverse-alpha distillation fails by physics and controlled captures were required), see `docs/research-doubao-distillation.md`.
@@ -81,7 +86,7 @@ Who embeds what (C2PA / IPTC / EXIF / TC260 AIGC / xAI signature / open and prop
Compact list. Full measurements, incident history, and oracle-validation runs live in `docs/known-limitations.md` — **read the relevant section there before changing the diffusion pipelines, strength defaults, resolution handling, or metadata coverage.**
- **Visible-mark fill quality is background/backend-dependent.** The fill only touches the mark footprint (no outside-box damage) and whether the mark is removed is fill-independent — cv2/MI-GAN/LaMa all strip the shape; only the recovered region's *quality* differs. Flat backgrounds: all clean (cv2 often crispest). Textured/regular-structured (fabric, grid): cv2 smears, MI-GAN can ghost/hallucinate, LaMa best. The old reverse-alpha recovered true pixels so it was sometimes cleaner on structure, but localize -> fill trades that for robustness (moved/re-rendered marks, no per-mark capture); `auto` = LaMa > MI-GAN > cv2 with a one-time cv2-fallback warning. Head-to-head vs v0.12.1 on the full visible set: doubao/jimeng identical (100%/100%), gemini strict coverage a few points lower (the metadata-stripped faint ones now mostly recovered by the default white-core rescue in the gemini FP gate; the residual via `assume-ai`), clearance ~98% both. Detail in `docs/known-limitations.md`.
- **Visible-mark fill quality is background/backend-dependent.** The fill only touches the mark footprint (no outside-box damage) and whether the mark is removed is fill-independent — cv2/MI-GAN/LaMa all strip the shape; only the recovered region's *quality* differs. Flat backgrounds: all clean (cv2 often crispest). Textured/regular-structured (fabric, grid): cv2 smears, MI-GAN can ghost/hallucinate, LaMa best. The old reverse-alpha recovered true pixels so it was sometimes cleaner on structure, but localize -> fill trades that for robustness (moved/re-rendered marks, no per-mark capture); `auto` = LaMa > MI-GAN > cv2 with a one-time cv2-fallback warning. Head-to-head vs v0.12.1 on the full visible set: doubao/jimeng identical (100%/100%), gemini strict coverage a few points lower (the metadata-stripped faint ones now mostly recovered by the default white-core rescue in the gemini FP gate), clearance ~98% both. Detail in `docs/known-limitations.md`.
- `invisible` processes at native resolution for inputs >= 1024px long side and auto-upscales smaller inputs to a 1024px floor (`--min-resolution 0` disables; `--max-resolution N` is an opt-in cap to bound GPU/MPS memory). MPS OOM is memory-tier dependent, not a hard limit: ~24 GB unified memory falls back to CPU (slow but weight-identical output), 32 GB runs native on MPS. The native-vs-cap-vs-floor decision lives in the pure helper `invisible_engine._target_size` — keep the logic there, unit-tested without the model. For large inputs that OOM, `--tile` is the **lossless** alternative to `--max-resolution`: sliding-window diffusion at native resolution, each tile near SDXL's 1024 training size, feather-blended over the overlap (`noai/tiling.py`). It only engages when the long side exceeds `--tile-size`; the geometry (`plan_tiles`) and the blend window (`feather_weights`) are pure and unit-tested (`tests/test_tiling.py`). Caveat: each tile is an independent low-strength regeneration, so at the certified removal strengths (0.20-0.30) tile drift is minimal but not zero; tiling is a memory workaround, not a quality upgrade over a single native pass.
- fp16 VAE black-output (issues #29/#41): the fp16-fixed SDXL VAE (`madebyollin/sdxl-vae-fp16-fix`) is swapped in for the default SDXL checkpoint on cuda/xpu fp16, plus a model-agnostic backstop that detects a degenerate (all-black) fp16 output and re-runs once in fp32. cpu/mps run fp32 and never reproduce the bug.
- Pyright first run is slow (2-3 min) due to ML deps (torch/diffusers/transformers stubs); full-project `uv run pyright` can stall for many minutes — scope it to changed files.
+22 -15
View File
@@ -21,13 +21,13 @@ If this tool saves you time, consider [sponsoring its development](https://githu
## Scope
This tool removes **AI-provenance watermarks** that a platform stamps onto content **you generated yourself** — SynthID, the Gemini / Nano Banana sparkle, the Doubao / Jimeng / Samsung visible AI labels, the Chinese TC260 "由…AI生成" label, and C2PA / IPTC / EXIF "Made with AI" metadata. The point is your autonomy over your own output.
This tool removes **AI-provenance watermarks** that a platform stamps onto content **you generated yourself** — SynthID, the Gemini / Nano Banana sparkle, the Doubao / Jimeng / Qwen / Kling / Baidu / LibLibAI / RunningHub / Samsung visible AI labels, the Chinese TC260 "由…AI生成" label, and C2PA / IPTC / EXIF "Made with AI" metadata. The point is your autonomy over your own output.
It does **not** target watermarks that protect someone else's paid or copyrighted content — stock-agency overlays (Shutterstock, Getty, iStock, Adobe Stock), classifieds-site marks, or any tiled "preview" watermark whose job is to gate a purchase. Removing those is out of scope by design. `erase` is a generic, user-driven region tool for your own objects, not an automatic stock-watermark remover.
## Features
- **Visible watermark removal** — a registry of known marks in their usual places: the Gemini / Nano Banana sparkle, the Doubao "豆包AI生成" text strip, the Jimeng "★ 即梦AI" wordmark, and the Samsung Galaxy AI "✦ Contenuti generati dall'AI" strip (bottom-left, locale-specific). Each mark is **localized to a footprint mask, then filled**: the engine finds the mark, builds a binary mask over its footprint, and one shared, swappable fill inpaints that region. Choose the fill with `--backend`: `cv2` (classical inpaint, no deps, the floor), `migan` (MI-GAN, light, the memory-tight pick where LaMa will not fit), or `lama` (big-LaMa, best quality, heavier, auto-preferred when a learned backend is available); the default `auto` uses LaMa > MI-GAN > cv2, best available. The localizer is cheap CPU (cv2/numpy), so it runs anywhere; the heavier MI-GAN/LaMa fill is opt-in. Detection keys on each mark's own shape (NCC against a captured silhouette; the alpha captures rebuilt by `scripts/visible_alpha_solve.py` are used to detect and to shape the mask, not for pixel recovery). The visual detector needs no metadata, but a borderline (faint or moved) mark is only trusted with corroboration: `--sensitivity` (default `auto`) relaxes a mark's gate when local metadata confirms the vendor or a same-product sibling mark is found; `--sensitivity assume-ai` relaxes every mark on the assertion that the image is AI, recovering the moved or re-rendered marks the conservative gate skips on a metadata-stripped screenshot (`strict` never relaxes). `visible --mark auto` finds and removes every detected mark in one pass. Fast, offline, no GPU. (For arbitrary logos/objects, see `erase`.)
- **Visible watermark removal** — a registry of known marks in their usual places: the Gemini / Nano Banana sparkle, the Doubao "豆包AI生成" text strip, the Jimeng "★ 即梦AI" wordmark, the Qwen "千问AI生成" and Kling "可灵AI 3.0" text strips, the Baidu "百度 AI生成" text + tag, the LibLibAI wordmark (bottom-center), the RunningHub "RunningHub AI生成" text (top-left), and the Samsung Galaxy AI "✦ Contenuti generati dall'AI" strip (bottom-left, locale-specific). Each mark is **localized to a footprint mask, then filled**: the engine finds the mark, builds a binary mask over its footprint, and one shared, swappable fill inpaints that region. Choose the fill with `--backend`: `cv2` (classical inpaint, no deps, the floor), `migan` (MI-GAN, light, the memory-tight pick where LaMa will not fit), or `lama` (big-LaMa, best quality, heavier, auto-preferred when a learned backend is available); the default `auto` uses LaMa > MI-GAN > cv2, best available. The localizer is cheap CPU (cv2/numpy), so it runs anywhere; the heavier MI-GAN/LaMa fill is opt-in. Detection keys on each mark's own shape (NCC against a captured silhouette; the alpha captures rebuilt by `scripts/visible_alpha_solve.py` are used to detect and to shape the mask, not for pixel recovery). The visual detector needs no metadata, but a borderline (faint or moved) mark is only trusted with corroboration: `--sensitivity` (default `auto`) relaxes a mark's gate when local metadata confirms the vendor or a same-product sibling mark is found; `strict` never relaxes. There is deliberately no "assume this is AI" mode: asserting that an image is AI says nothing about *which* vendor made it or *where* the mark is, which is exactly what a gate bypass needs. If you can SEE a mark the detector missed, point at it with `erase --region x,y,w,h`, or force a known text mark by name with `--mark <name> --no-detect` -- both act on what you actually see instead of relaxing every detector at once. `visible --mark auto` finds and removes every detected mark in one pass. Fast, offline, no GPU. (For arbitrary logos/objects, see `erase`.)
- **Universal region eraser (`erase`)** — remove any logo / watermark / object inside boxes you specify, regardless of position or color. Default cv2 inpainting (CPU, instant); optional big-LaMa via onnxruntime (`lama` extra) for higher quality
- **Invisible watermark removal** — SynthID, StableSignature, TreeRing via diffusion-based regeneration (needs a local GPU, or run it with no setup on [raiw.cc](https://raiw.cc))
- **AI metadata stripping** — EXIF, PNG text chunks, C2PA provenance manifests (PNG / JPEG / AVIF / HEIF / JPEG-XL, **MP4 / MOV / M4V / M4A** at the container level, and **WebM / MP3 / WAV / FLAC / OGG** losslessly via ffmpeg), XMP DigitalSourceType
@@ -36,7 +36,7 @@ It does **not** target watermarks that protect someone else's paid or copyrighte
- **Text and face preservation (default)** — the default pipeline is a canny ControlNet that keeps text and face structure sharp through the removal pass (without copying original pixels, so SynthID is still removed). Use `--pipeline sdxl` for plain SDXL img2img (lighter, no extra model download) on inputs without text or faces. An experimental `--pipeline qwen` runs Qwen-Image (20B, Apache-2.0) img2img, which preserves **text** (including CJK and small text) better than SDXL at equal strength; it is CUDA/cloud-class (does not fit MPS), and its strength floors are not yet certified (pass an explicit `--strength`, especially for Gemini content). Note: measured fidelity (`scripts/fidelity_metrics.py`) shows Qwen wins on text but controlnet preserves **faces** better (Qwen smooths skin more), so Qwen is not a universal upgrade. Canny preserves face *structure*, not *identity* (the regenerated face drifts in likeness). The library does not ship a face-restore extra: every approach evaluated (GFPGAN-on-cleaned, PhotoMaker-V2, InstantID txt2img, InstantID img2img-on-cleaned) regenerated the face via SDXL and made the output look more AI-generated than the cleaned image. The cleaned controlnet output is the least-AI face state achievable without re-introducing SynthID.
- **Batch processing** — process entire directories
- **Detection** — three-stage NCC watermark detection with confidence scoring
- **Provenance detection (`identify`)** — aggregate C2PA issuer, the C2PA soft-binding forensic-watermark vendor (Adobe TrustMark, Digimarc, Imatag, ...), IPTC "Made with AI" plus the IPTC 2025.1 `AISystemUsed` field, embedded SD/ComfyUI params, EXIF/XMP generator tags, the xAI/Grok EXIF signature, the China TC260 AIGC label (XMP, PNG chunk, EXIF, or JPEG segment), the HuggingFace `hf-job-id` job marker, the SynthID metadata proxy, the C2PA cloud-manifest reference (Adobe Durable Content Credentials, when the embedded manifest is stripped), the visible marks (Gemini sparkle plus the Doubao "豆包AI生成" / Jimeng "即梦AI" / Samsung Galaxy AI "Contenuti generati dall'AI" text marks), the open SD/SDXL/FLUX invisible watermark, and (with the `trustmark` extra) the open Adobe TrustMark watermark into one origin-platform + watermark-inventory verdict (`--json` for machine output)
- **Provenance detection (`identify`)** — aggregate C2PA issuer, the C2PA soft-binding forensic-watermark vendor (Adobe TrustMark, Digimarc, Imatag, ...), IPTC "Made with AI" plus the IPTC 2025.1 `AISystemUsed` field, embedded SD/ComfyUI params, EXIF/XMP generator tags, the xAI/Grok EXIF signature, the China TC260 AIGC label (XMP, PNG chunk, EXIF, or JPEG segment), the HuggingFace `hf-job-id` job marker, the SynthID metadata proxy, the C2PA cloud-manifest reference (Adobe Durable Content Credentials, when the embedded manifest is stripped), the visible marks (Gemini sparkle plus the Doubao "豆包AI生成" / Jimeng "即梦AI" / Qwen "千问AI生成" / Kling "可灵AI 3.0" / Baidu "百度 AI生成" / LibLibAI / RunningHub "RunningHub AI生成" / Samsung Galaxy AI "Contenuti generati dall'AI" text marks), the open SD/SDXL/FLUX invisible watermark, and (with the `trustmark` extra) the open Adobe TrustMark watermark into one origin-platform + watermark-inventory verdict (`--json` for machine output)
## Examples
@@ -61,14 +61,19 @@ It does **not** target watermarks that protect someone else's paid or copyrighte
| **Meta AI** | — | — | ✅ IPTC "Made with AI" (digitalSourceType) | Metadata strip (removes the label) |
| **Doubao** (ByteDance) / China AIGC generators | ✅ "豆包AI生成" text strip (bottom-right) | — | ✅ TC260 AIGC label (`<TC260:AIGC>` XMP, `AIGC` PNG chunk, or EXIF JSON) **+ C2PA** signed by ByteDance Volcano Engine (`volcengine`) | Localize glyph footprint + fill + metadata strip |
| **Jimeng / Dreamina** (即梦AI, ByteDance) | ✅ "★ 即梦AI" wordmark (bottom-right) | — | ✅ TC260 AIGC label + C2PA (Volcano Engine) | Localize glyph footprint + fill + metadata strip |
| **Qwen / Tongyi Qianwen** (千问, Alibaba) | ✅ "千问AI生成" text strip (bottom-right) | — | ✅ TC260 AIGC label | Localize glyph footprint + fill + metadata strip |
| **Kling** (可灵, Kuaishou) | ✅ "可灵AI 3.0" text strip (bottom-right) | — | ✅ TC260 AIGC label | Localize glyph footprint + fill + metadata strip |
| **Baidu** | ✅ "百度 AI生成" text + tag (bottom-right) | — | ✅ TC260 AIGC label | Localize glyph footprint + fill + metadata strip |
| **LibLibAI** (哩布哩布AI) | ✅ "LibLibAI" wordmark (bottom-center) | — | ✅ TC260 AIGC label | Localize glyph footprint + fill + metadata strip |
| **RunningHub** | ✅ "RunningHub AI生成" text (top-left) | — | ✅ TC260 AIGC label | Localize glyph footprint + fill + metadata strip |
| **Samsung Galaxy AI** (Generative Edit, Sketch to Image, ...) | ✅ "✦ Contenuti generati dall'AI" strip (bottom-left, Italian-locale detection) | — | ✅ C2PA (signer "Samsung Galaxy") + `trainedAlgorithmicMedia` / proprietary `genAIType` marker | Localize glyph footprint + fill + metadata strip |
| **Black Forest Labs** (FLUX API) | — | — | ✅ C2PA (`Black Forest Labs API` + `c2pa.ai_generated_content` + `trainedAlgorithmicMedia`) | Metadata strip |
| **StableSignature** (Meta) | — | ✅ In-model watermark | — | Diffusion regeneration |
| **TreeRing** | — | ✅ Latent space watermark | — | Diffusion regeneration |
> Visible overlays are used by Google Gemini / Nano Banana (sparkle logo), by ByteDance's Doubao ("豆包AI生成" corner text) and Jimeng / Dreamina ("★ 即梦AI" wordmark), and by Samsung Galaxy AI ("✦ Contenuti generati dall'AI" strip, bottom-left, locale-specific). All are removed by localizing the mark to a footprint mask and inpainting it with one shared fill (cv2 by default, MI-GAN or big-LaMa via `--backend`); the localizer is CPU-cheap and the heavier fills are opt-in. Other services rely on invisible watermarks and/or metadata; our diffusion-based regeneration works against any invisible watermark in pixel or frequency domain. For a visible mark from any other source (any position, any color), use the universal `erase --region` command.
> Visible overlays are used by Google Gemini / Nano Banana (sparkle logo), by ByteDance's Doubao ("豆包AI生成" corner text) and Jimeng / Dreamina ("★ 即梦AI" wordmark), by Alibaba's Qwen / Tongyi Qianwen ("千问AI生成" corner text), by Kuaishou's Kling ("可灵AI 3.0" corner text), by Baidu ("百度 AI生成" text + tag), by LibLibAI ("LibLibAI" wordmark, bottom-center), by RunningHub ("RunningHub AI生成", top-left), and by Samsung Galaxy AI ("✦ Contenuti generati dall'AI" strip, bottom-left, locale-specific). All are removed by localizing the mark to a footprint mask and inpainting it with one shared fill (cv2 by default, MI-GAN or big-LaMa via `--backend`); the localizer is CPU-cheap and the heavier fills are opt-in. Other services rely on invisible watermarks and/or metadata; our diffusion-based regeneration works against any invisible watermark in pixel or frequency domain. For a visible mark from any other source (any position, any color), use the universal `erase --region` command.
> **Detection:** `remove-ai-watermarks identify <image>` reports the origin platform and watermark inventory for all the signals above — C2PA issuer, the C2PA soft-binding forensic-watermark vendor (TrustMark / Digimarc / Imatag / ...), IPTC "Made with AI" plus the IPTC 2025.1 `AISystemUsed` field, the China TC260 AIGC label (XMP, PNG chunk, EXIF, or JPEG segment), the HuggingFace `hf-job-id` job marker, embedded generation params, EXIF/XMP generator tags, the xAI/Grok EXIF signature, the SynthID metadata proxy, the C2PA cloud-manifest reference (Adobe Durable Content Credentials, when the embedded manifest is stripped), the visible marks (Gemini sparkle plus the Doubao "豆包AI生成" / Jimeng "即梦AI" / Samsung Galaxy AI "Contenuti generati dall'AI" text marks), and (with the `[detect]` / `[trustmark]` extras) the open SD/SDXL/FLUX and Adobe TrustMark invisible watermarks. SynthID and the proprietary soft-binding watermarks (Digimarc etc.) have no local decoder, so they are reported by metadata proxy / vendor name only.
> **Detection:** `remove-ai-watermarks identify <image>` reports the origin platform and watermark inventory for all the signals above — C2PA issuer, the C2PA soft-binding forensic-watermark vendor (TrustMark / Digimarc / Imatag / ...), IPTC "Made with AI" plus the IPTC 2025.1 `AISystemUsed` field, the China TC260 AIGC label (XMP, PNG chunk, EXIF, or JPEG segment), the HuggingFace `hf-job-id` job marker, embedded generation params, EXIF/XMP generator tags, the xAI/Grok EXIF signature, the SynthID metadata proxy, the C2PA cloud-manifest reference (Adobe Durable Content Credentials, when the embedded manifest is stripped), the visible marks (Gemini sparkle plus the Doubao "豆包AI生成" / Jimeng "即梦AI" / Qwen "千问AI生成" / Kling "可灵AI 3.0" / Baidu "百度 AI生成" / LibLibAI / RunningHub "RunningHub AI生成" / Samsung Galaxy AI "Contenuti generati dall'AI" text marks), and (with the `[detect]` / `[trustmark]` extras) the open SD/SDXL/FLUX and Adobe TrustMark invisible watermarks. SynthID and the proprietary soft-binding watermarks (Digimarc etc.) have no local decoder, so they are reported by metadata proxy / vendor name only.
## How it works
@@ -331,21 +336,23 @@ remove-ai-watermarks identify image.png
# Visible watermark only — fast, offline, CPU. --mark auto (default) removes every
# detected known mark (Gemini sparkle / Doubao "豆包AI生成" / Jimeng "即梦AI" /
# Samsung Galaxy AI "Contenuti generati dall'AI"); force one with
# --mark gemini / doubao / jimeng / samsung. Removal localizes each mark to a
# Qwen "千问AI生成" / Kling "可灵AI 3.0" / Baidu "百度 AI生成" / LibLibAI /
# RunningHub "RunningHub AI生成" / Samsung Galaxy AI "Contenuti generati dall'AI");
# force one with --mark gemini / doubao / jimeng / qwen / kling / baidu / liblib /
# runninghub / samsung. Removal localizes each mark to a
# footprint mask and inpaints it with a shared fill; --backend auto|cv2|migan|lama
# (default auto) picks the fill (auto = LaMa > MI-GAN > cv2, best available).
# --sensitivity auto|strict|assume-ai (default auto) sets how hard a borderline
# mark is trusted; use assume-ai on a metadata-stripped screenshot to recover a
# moved or faint mark the conservative gate would skip.
# --sensitivity auto|strict (default auto) sets how hard a borderline mark is
# trusted; there is no "assume this is AI" mode -- to act on a mark you can see
# but the detector missed, point at it with `erase --region` (below).
# If no known visible mark is found, it writes no output and exits 2 (not 0),
# pointing you to `all` (for an invisible/metadata mark) or `erase` (for an
# arbitrary logo) instead of handing back the unchanged image.
remove-ai-watermarks visible image.png -o clean.png
# Metadata-stripped screenshot: assert it is AI to relax detection and recover
# a moved/faint mark (a wrong guess just fills a small corner near-losslessly).
remove-ai-watermarks visible screenshot.png --sensitivity assume-ai -o clean.png
# Metadata-stripped screenshot where you can SEE the mark but detection missed it:
# point at it. This executes what you see instead of relaxing every detector at once.
remove-ai-watermarks erase screenshot.png --region 812,1180,190,44 -o clean.png
# Erase arbitrary region(s) — universal, any logo/watermark/object, any position.
# Default cv2 inpainting (CPU). --backend lama uses big-LaMa (extra 'lama').
@@ -393,7 +400,7 @@ remove-ai-watermarks batch ./images/ --mode all
### Python API
One high-level call removes every detected visible mark (Gemini sparkle, Doubao / Jimeng / Samsung text, the Jimeng pill) by localize then fill. For a file it reads metadata provenance automatically and preserves the alpha channel; `import remove_ai_watermarks` stays cheap (the heavy deps load lazily on first use).
One high-level call removes every detected visible mark (Gemini sparkle, Doubao / Jimeng / Qwen / Samsung text, the Jimeng pill) by localize then fill. For a file it reads metadata provenance automatically and preserves the alpha channel; `import remove_ai_watermarks` stays cheap (the heavy deps load lazily on first use).
```python
import remove_ai_watermarks as raiw
@@ -409,7 +416,7 @@ clean, removed = raiw.remove_visible(cv2.imread("in.png"), backend="cv2")
# Metadata-stripped screenshot you know is AI-generated: relax detection to recover a
# moved or faint mark (a wrong guess just fills a small corner near-losslessly).
raiw.remove_visible("screenshot.png", "clean.png", sensitivity="assume_ai")
raiw.remove_visible("screenshot.png", "clean.png", sensitivity="strict")
# What the file's metadata confirms (drives the default `auto` sensitivity):
raiw.visible_provenance("in.png") # e.g. frozenset({'gemini'})
+172 -8
View File
@@ -29,7 +29,7 @@ module.
**AI-generated vs AI-enhanced** (`ProvenanceReport.ai_source_kind`, roadmap item): the C2PA digital-source-type is split into `"generated"` (trainedAlgorithmicMedia, fully synthetic) vs `"enhanced"` (compositeWithTrainedAlgorithmicMedia, a real photo with an AI-composited region) — the two byte strings are unambiguous (`compositeWithTrainedAlgorithmicMedia` capitalizes the inner "Trained", so a lowercase `trainedAlgorithmicMedia` match is standalone full generation; full generation wins when both appear). `ai_source_kind` is set only when the AI verdict actually came from the C2PA source type (a non-C2PA AI signal — IPTC/AIGC/local gen/xAI — leaves it None). It lets a caller branch a full-frame scrub (`generated`) from a region-targeted clean that preserves the real photo (`enhanced`; see `noai/tiling.feather_region_composite`). The CLI verdict line reads "AI-generated (fully synthetic)" vs "AI-enhanced (real content with an AI-composited region)".
**Visible-mark detection** (`check_visible`, signals `visible_sparkle` / `visible_doubao` / `visible_jimeng` / `visible_samsung`): the Gemini sparkle keeps its own file-level path (`_visible_sparkle` → `gemini_engine.detect_sparkle_confidence`, promoted only at confidence ≥ `_SPARKLE_THRESHOLD`, which is the SHARED `watermark_registry.GEMINI_SPARKLE_TRUST_CONF` (0.5) — imported, not a private copy, so the provenance detect threshold and the removal `detect_marks` / `_gemini_detect` arbitration gate can never drift (the detect-vs-remove desync from roadmap P0#7; regression-guarded by `tests/test_identify.py::TestSparkleDetectRemoveAlignment`, which composites the real demo sparkle at borderline opacities and asserts identify and `detect_marks` AGREE on either side of the line). Lowering the gate to recover faint sub-0.5 sparkles was evaluated 2026-06-20 and REJECTED: a real Doubao text mark scores ~0.40-0.42 as a gemini match with a HIGHER core-ring brightness margin than a genuine faint sparkle, so neither confidence nor the brightness gate separates them in the [0.35, 0.5) band — lowering trades a rare miss for false-positive removals on clean images. Corpus-tuned to separate Gemini sparkles ≥0.56 from non-sparkle ≤0.49), while Doubao/Jimeng/Samsung reuse the registry detectors (`_visible_text_marks` → `watermark_registry`, iterating `_VISIBLE_MARK_PLATFORM`), each gated by its own engine NCC threshold via `MarkDetection.detected` (Doubao 0.4, Jimeng 0.45, Samsung 0.4). Doubao/Jimeng are normally also caught by the TC260 AIGC metadata label and Samsung by its C2PA + `genAIType` marker, so the visible path is their stripped-metadata fallback. Visible marks set `platform` only when no harder signal already did, and (like the sparkle) are excluded from integrity-clash vendor claims. The cv2 dependency lives in the engines, not here.
**Visible-mark detection** (`check_visible`, signals `visible_sparkle` / `visible_doubao` / `visible_jimeng` / `visible_qwen` / `visible_samsung`): the Gemini sparkle keeps its own file-level path (`_visible_sparkle` → `gemini_engine.detect_sparkle_confidence`, promoted only at confidence ≥ `_SPARKLE_THRESHOLD`, which is the SHARED `watermark_registry.GEMINI_SPARKLE_TRUST_CONF` (0.5) — imported, not a private copy, so the provenance detect threshold and the removal `detect_marks` / `_gemini_detect` arbitration gate can never drift (the detect-vs-remove desync from roadmap P0#7; regression-guarded by `tests/test_identify.py::TestSparkleDetectRemoveAlignment`, which composites the real demo sparkle at borderline opacities and asserts identify and `detect_marks` AGREE on either side of the line). Lowering the gate to recover faint sub-0.5 sparkles was evaluated 2026-06-20 and REJECTED: a real Doubao text mark scores ~0.40-0.42 as a gemini match with a HIGHER core-ring brightness margin than a genuine faint sparkle, so neither confidence nor the brightness gate separates them in the [0.35, 0.5) band — lowering trades a rare miss for false-positive removals on clean images. Corpus-tuned to separate Gemini sparkles ≥0.56 from non-sparkle ≤0.49), while Doubao/Jimeng/Qwen/Samsung reuse the registry detectors (`_visible_text_marks` → `watermark_registry`, iterating `_VISIBLE_MARK_PLATFORM`), each gated by its own engine NCC threshold via `MarkDetection.detected` (Doubao 0.50, Jimeng 0.45, Qwen 0.45, Samsung 0.40). Doubao/Jimeng are normally also caught by the TC260 AIGC metadata label and Samsung by its C2PA + `genAIType` marker, so the visible path is their stripped-metadata fallback. Visible marks set `platform` only when no harder signal already did, and (like the sparkle) are excluded from integrity-clash vendor claims. The cv2 dependency lives in the engines, not here.
**`import identify` is deliberately light** (~26 MB; ~36 MB with cv2 loaded by a visible-mark run, ~106 MB for a full `check_visible` run): it imports the `noai.c2pa`/`noai.constants` submodules, and `noai/__init__` is lazy (see "Test and lint"), so torch/diffusers are NOT pulled at import even in a full `gpu`/`detect` install — fits a 512 MB host. `noai.c2pa` does eagerly import the **c2pa-python** binary (Rust + cryptography, ~+5 MB RSS, no torch) for the primary `Reader` path — light enough to stay on the dependency-light host; a broken/absent wheel degrades to the byte-scan parser (`reader_available()` False). The heavy paths are opt-in: `check_invisible=True` needs the `detect`/`trustmark` extras (each pulls **torch**; TrustMark also **downloads weights**), so on a core-only deploy leave `check_invisible` off (it is a no-op there anyway). Before the lazy `__init__`, the mere presence of torch in the env inflated `import identify` to ~420 MB.
@@ -53,7 +53,7 @@ module.
**Independence is source-grouped (`_CLASH_SOURCE`, added 2026-06-02):** the C2PA issuer attribution (`c2pa`) and the SynthID proxy (`synthid`) are NOT independent — the proxy is inferred from the *same* manifest — so they share one source and two vendors named within a single manifest do not clash. This killed a false-positive class found on the spaces corpus: legitimate multi-actor manifests where a product wraps another vendor's engine (Microsoft Designer on OpenAI → `OpenAI, Microsoft`; Microsoft on Google → `Microsoft, Google LLC, Google C2PA Core Generator Library`) or an edit chain re-signs (Adobe over a Gemini original → Adobe c2pa + Google synthid) — 19 such files across the 2026-06-01/02 batches read as clashes before the fix. Rule 1 still fires when a manifest vendor disagrees with a genuinely independent stamp (EXIF/XMP generator, IPTC `AISystemUsed`, AIGC, xAI); each non-`c2pa`/`synthid` family is its own source (`test_identify.py::TestIntegrityClashes::{test_multi_actor_manifest_no_clash,test_manifest_vendor_vs_independent_signal_clashes}`). Vendor normalization is `_vendor_of` over `_AI_VENDOR_TOKENS` (so a C2PA "Google (Gemini)" issuer and a SynthID-Google proxy agree, while different vendors clash). `_AI_VENDOR_TOKENS` covers ByteDance (all brands: bytedance/doubao/jimeng/dreamina/volcengine), Canva, ElevenLabs, and Black Forest Labs in addition to the OpenAI/Google/Adobe/... set — without them a transplanted ByteDance/Canva/BFL C2PA manifest next to an independent conflicting stamp was silently missed. **The generic `China AIGC (TC260)` label names no SPECIFIC vendor** (any Chinese generator applies it), so it cannot vendor-conflict in the spoofing sense: when a Chinese TC260-applying vendor (`_TC260_VENDORS`, today `{ByteDance}`) is co-attributed, Rule 1 attributes the label to that vendor (a legit Doubao image carries BOTH a ByteDance C2PA manifest and its own TC260 label and must not clash); against a NON-TC260 vendor (OpenAI etc.) the label stays generic and still clashes as a laundering tell (`test_bytedance_c2pa_plus_own_aigc_no_clash`, `test_foreign_vendor_plus_aigc_still_clashes`, `test_bytedance_c2pa_plus_foreign_generator_clashes`). Corpus-validated: 0 new clashes on 5000 ByteDance/AIGC/Canva/FLUX carriers.
**High-precision by design:** only hard generator stamps feed it (C2PA-issuer when source is AI, SynthID, EXIF/XMP generator, IPTC `AISystemUsed`, xAI, AIGC); the fuzzy visible sparkle and the open invisible watermark are **excluded** (the latter can be a by-product of our own SDXL removal pass). The c2pa vendor is classified from the issuer attribution / generator, NOT the resolved `platform` (a camera label like "Google Pixel" would mis-normalize to "Google"). All real single-origin fixtures (chatgpt/firefly/doubao/grok/mj) verified to produce **zero** clashes (false-positive guard in `test_identify.py::TestRealSamplesHaveNoClash`).
**High-precision by design:** only hard generator stamps feed it (C2PA-issuer when source is AI, SynthID, EXIF/XMP generator, IPTC `AISystemUsed`, xAI, AIGC); the fuzzy visible sparkle and the open invisible watermark are **excluded** (both are low-precision/positive-only signals; the open watermark was also historically a by-product of our own SDXL removal pass, until `watermark_remover` was fixed to load the SDXL pipelines with `add_watermarker=False` — it stays excluded as a fuzzy signal regardless). The c2pa vendor is classified from the issuer attribution / generator, NOT the resolved `platform` (a camera label like "Google Pixel" would mis-normalize to "Google"). All real single-origin fixtures (chatgpt/firefly/doubao/grok/mj) verified to produce **zero** clashes (false-positive guard in `test_identify.py::TestRealSamplesHaveNoClash`).
**`ai_from_metadata` field + `has_invisible_target` helper (P0#5, 2026-06-22):** the high-confidence union (everything that sets `confidence == "high"`: C2PA AI-issuer / SynthID proxy, IPTC, AIGC, local gen params, EXIF/xAI, open DWT-DCT / TrustMark — the medium-confidence `hf_only`/`visible_only`/`samsung_only` are excluded) is now surfaced as the public `ProvenanceReport.ai_from_metadata` boolean, so callers gate on intent rather than on the `confidence` string. `has_invisible_target(path)` wraps `identify(path, check_visible=False, check_invisible=True)` and returns that field — it is the decision gate for the diffusion scrub (the CLI `invisible`/`all`/`batch` no-signal skip, `cli._no_invisible_signal_exit`): a visible-only or no-signal image has it False, so regeneration (which would only degrade a clean image) does not run. It fails SAFE — any detector exception returns True so the removal still runs (leaving a watermark on a paid removal is worse than over-regenerating). It does NOT prove a pixel SynthID is absent (SynthID is detectable only via its metadata proxy, gone once stripped), so a False means "no locally-detectable target", never "clean". Guarded by `test_identify.py::{TestIdentifyRealSamples::test_has_invisible_target_*,TestHasInvisibleTargetFailSafe}`.
@@ -61,17 +61,135 @@ module.
`watermark_registry.py` — **single catalog of known visible watermarks**, the unified "find known marks in their usual places, recognize, remove" entry.
**Localize -> fill by policy (replaced reverse-alpha):** each mark is localized to a binary full-frame footprint mask (a `Localization`), and one shared, swappable fill inpaints that mask via `fill(image, mask, backend=...)` (delegates to `region_eraser.erase`). This replaced the old reverse-alpha removal (invert a captured alpha map, `original = (wm - a*logo)/(1-a)`, plus a thin residual inpaint) for ALL marks — gemini, doubao, jimeng, samsung, and jimeng_pill. **Why it changed:** reverse-alpha depended on a fixed captured alpha map at a fixed position, so it broke whenever a vendor moved or re-rendered its mark; and it was not color-lossless even with the right map (it amplifies 8-bit quantization and JPEG-chroma error by `1/(1-a)`), which showed up as "the color just changed, not removed" reports. Localize -> fill has a benign failure mode: a slightly-off localization just inpaints a small region near-losslessly instead of leaving a color-shifted smear. The captured alpha maps are still used to DETECT the marks and to shape the mask (gemini's footprint), but NOT for pixel recovery. Fill backends: `cv2` (classical inpaint, no deps, the floor), `migan` (MI-GAN ONNX, light, the memory-tight pick where LaMa will not fit), `lama` (big-LaMa ONNX, best quality, heavier, auto-preferred when a learned backend is available); `auto` = LaMa > MI-GAN > cv2, best available. Each `KnownMark` ties a key to {usual `location`, `in_auto` flag, a `_detect` callable → uniform `MarkDetection`, a `_mask` callable → full-frame footprint mask}; `KnownMark.remove(image, *, backend="auto", provenance=False, force=False)`. Entries today: `gemini` (bottom-right sparkle), `doubao` (bottom-right "豆包AI生成"), `jimeng` (bottom-right "★ 即梦AI"), `samsung` (bottom-**LEFT** "✦ Contenuti generati dall'AI", Samsung Galaxy AI, Italian locale), and the capture-less `jimeng_pill` (top-left "AI生成"). `detect_marks(image, *, provenance=frozenset())` scans all (strict, for the identify verdict); `remove_auto_marks(image, *, sensitivity="auto", provenance=frozenset(), backend="auto")` removes every detected mark in one pass. **Sensitivity (`auto`/`strict`/`assume_ai`)** decides how hard a borderline mark is trusted: the visual detectors are pixel-based (no metadata needed) and the recall gain comes from relaxing the false-positive gate, not from metadata. `resolve_relax` turns the policy + evidence into the per-mark relaxation boolean — `strict` never relaxes, `assume_ai` always relaxes (the caller asserts AI, e.g. a metadata-stripped screenshot; ~46% -> ~92% Gemini recall, at the cost of a small near-lossless fill on some clean corners), `auto` relaxes only on same-product evidence (metadata provenance for that vendor, or a confidently strict-detected sibling of the same `_PRODUCT_OF` — Doubao and Jimeng are both bottom-right ByteDance but distinct products, so they do NOT cross-relax). **Perception / decision / action are separated three ways** (the removal path only; `identify` keeps calling `KnownMark.detect` directly, so its verdict is untouched): `_build_candidates(image)` is PERCEPTION — it runs each detector at both trust levels and packages raw verdicts + the pill's flatness feature into `Candidate`s, no policy; `decide(candidates, Context(sensitivity, provenance)) -> [Decision]` is the pure DECISION arbiter — all keep/drop policy (`resolve_relax` cross-mark corroboration + the pill gate) in one image-free, unit-testable function (`tests/test_watermark_registry.py::TestArbiter`); then `remove_auto_marks` does the ACTION, localizing -> filling each winner. The Gemini FP gate deliberately stays inside `gemini_engine` (not the arbiter) because `identify` reads that same gated confidence — pulling it out would drift the provenance verdict. Behavior is byte-identical to the pre-arbiter two-pass (corpus-verified: strict/auto 46%, assume_ai 92% Gemini recall unchanged).
**Localize -> fill by policy (replaced reverse-alpha):** each mark is localized to a binary full-frame footprint mask (a `Localization`), and one shared, swappable fill inpaints that mask via `fill(image, mask, backend=...)` (delegates to `region_eraser.erase`). This replaced the old reverse-alpha removal (invert a captured alpha map, `original = (wm - a*logo)/(1-a)`, plus a thin residual inpaint) for ALL marks — gemini, doubao, jimeng, samsung, and jimeng_pill. **Why it changed:** reverse-alpha depended on a fixed captured alpha map at a fixed position, so it broke whenever a vendor moved or re-rendered its mark; and it was not color-lossless even with the right map (it amplifies 8-bit quantization and JPEG-chroma error by `1/(1-a)`), which showed up as "the color just changed, not removed" reports. Localize -> fill has a benign failure mode: a slightly-off localization just inpaints a small region near-losslessly instead of leaving a color-shifted smear. The captured alpha maps are still used to DETECT the marks and to shape the mask (gemini's footprint), but NOT for pixel recovery. Fill backends: `cv2` (classical inpaint, no deps, the floor), `migan` (MI-GAN ONNX, light, the memory-tight pick where LaMa will not fit), `lama` (big-LaMa ONNX, best quality, heavier, auto-preferred when a learned backend is available); `auto` = LaMa > MI-GAN > cv2, best available. Each `KnownMark` ties a key to {usual `location`, `in_auto` flag, a `_detect` callable → uniform `MarkDetection`, a `_mask` callable → full-frame footprint mask}; `KnownMark.remove(image, *, backend="auto", provenance=False, force=False)`. Entries today: `gemini` (bottom-right sparkle), `doubao` (bottom-right "豆包AI生成"), `jimeng` (bottom-right "★ 即梦AI"), `qwen` (bottom-right "千问AI生成", Alibaba Tongyi Qianwen), `samsung` (bottom-**LEFT** "✦ Contenuti generati dall'AI", Samsung Galaxy AI, Italian locale), and the capture-less `jimeng_pill` (top-left "AI生成"). `detect_marks(image, *, provenance=frozenset())` scans all (strict, for the identify verdict); `remove_auto_marks(image, *, sensitivity="auto", provenance=frozenset(), backend="auto")` removes every detected mark in one pass. **Sensitivity (`auto`/`strict`/`assume_ai`)** decides how hard a borderline mark is trusted: the visual detectors are pixel-based (no metadata needed) and the recall gain comes from relaxing the false-positive gate, not from metadata. `resolve_trust` turns the policy + evidence into the per-mark trust level the engines consume as `provenance = level != "strict"` — `strict` never relaxes; `auto` relaxes only on same-product evidence (metadata provenance for that vendor, or a confidently strict-detected sibling of the same `_PRODUCT_OF` — Doubao and Jimeng are both bottom-right ByteDance but distinct products, so they do NOT cross-relax); `assume_ai` relaxes every mark (the caller asserts AI, e.g. a metadata-stripped screenshot). **Three levels, not two: `strict` / `assumed` / `confirmed`.** Relaxing bypasses the engine's false-positive gate outright, and that bypass is contracted to mean the vendor is CONFIRMED (`GeminiEngine.detect_watermark`'s `trust_provenance`: "external metadata already proves this is a Google generation"). An `assume_ai` caller asserts the image is AI, which says nothing about WHICH vendor, so a mark relaxed on assumption alone must also clear `_ASSUMED_CONF_FLOOR` (`assumed_floor_ok`; gemini 0.50) — see "Assumed-trust confidence floor" below. **Perception / decision / action are separated three ways** (the removal path only; `identify` keeps calling `KnownMark.detect` directly, so its verdict is untouched): `_build_candidates(image)` is PERCEPTION — it runs each detector at both trust levels and packages raw verdicts + the pill's flatness feature into `Candidate`s, no policy; `decide(candidates, Context(sensitivity, provenance)) -> [Decision]` is the pure DECISION arbiter — all keep/drop policy (`resolve_trust` cross-mark corroboration + the assumed-trust floor + the pill gate) in one image-free, unit-testable function (`tests/test_watermark_registry.py::TestArbiter`); then `remove_auto_marks` does the ACTION, localizing -> filling each winner. The Gemini FP gate deliberately stays inside `gemini_engine` (not the arbiter) because `identify` reads that same gated confidence — pulling it out would drift the provenance verdict. Behavior was byte-identical to the pre-arbiter two-pass when the arbiter landed; `assume_ai` has since gained the assumed-trust confidence floor (see below), which deliberately changes its verdict on weak gate-bypassed matches.
**Head-to-head validation (v0.12.1 reverse-alpha vs the current localize -> fill):** run over the full labelled visible-mark set, with the cv2 / MI-GAN / LaMa fills each compared against the old reverse-alpha. **doubao and jimeng are identical** across every backend -- 100% coverage and 100% clearance either way. **gemini** strict coverage is a few points below reverse-alpha's (the deliberate false-positive tightening), but the metadata-stripped faint ones are now mostly recovered by the DEFAULT white-core rescue in the FP gate (`gemini_engine`: a bright near-WHITE core distinguishes a real faint sparkle from a colored bright corner -- ~14/20 recovered at ~1.25% clean false-fire; a learned classifier on the same features measured worse, 2026-07 tier-1), the residual under `assume_ai`; clearance is equal (~98% both), and neither version touches pixels outside the mark box (outside-box PSNR ~99). **Clearance is fill-independent** -- cv2, MI-GAN and LaMa all strip the mark's shape equally, so the re-detect metric does not separate them; the difference is purely the *visual fill quality* on the recovered region, and it is background-dependent. reverse-alpha recovered textured and especially regular/structured backgrounds (a lattice, a grid) more cleanly than any inpaint; **LaMa closes most of that gap** (the best learned backend), **MI-GAN can ghost or hallucinate structure**, and **cv2 smears** (the last-resort floor). This is why `auto` resolves `LaMa > MI-GAN > cv2` (`preferred_inpaint_backend`) and warns once on the cv2 fallback; on flat backgrounds every backend is clean.
**Provenance prior:** when local metadata already confirms the vendor, the mark's detection trust gate is relaxed (a confirmed vendor means the mark is present with high prior, so a mark the conservative detector would demote as a content false positive is trusted). `detect_marks` / `remove_auto_marks` take a `provenance` frozenset and `KnownMark.remove` a `provenance` flag. Mapping: a Google/Gemini C2PA issuer relaxes gemini (skips its false-positive gate and lowers the trust threshold from 0.5 to 0.35); a China-AIGC (TC260) label relaxes doubao/jimeng; `samsung_genai` relaxes samsung. Corpus finding: on Google-C2PA images, Gemini sparkle recall rose from ~46% (plain detector) to ~90% with the provenance prior (recovering marks the vendor moved or re-rendered). The localizer is cheap CPU (cv2/numpy), so a memory-tight caller runs it anywhere; the heavy MI-GAN/LaMa fill is opt-in and chosen by the caller.
**`assume_ai` removed (2026-07-19).** It relaxed EVERY mark's false-positive gate on the caller's bare assertion that an image is AI. That assertion says nothing about WHICH vendor or WHERE the mark is, which is exactly what a gate bypass is contracted to require -- before it carried a confidence floor it filled a phantom sparkle on 59.8% of genuine camera photos, and even with the floor it was a statistical gamble rather than an instruction. It also had no place in the product's model: detector finds a mark -> remove it; detector finds nothing -> leave the image alone; the USER sees a mark and says so -> act on that.
Removing it collapsed the trust ladder from three levels to two (`strict` / `confirmed`) and took `_ASSUMED_CONF_FLOOR`, `assumed_floor_ok` and the `assumed` level with it. `_keep_pill` lost its `sensitivity` parameter (its assume-arm is gone; the metadata arm and its flatness guard are unchanged). Verified on the 240-image unbiased recall sample: doubao 92%/99%, gemini 96%/80%, jimeng 71%/71%, pill 50%/60% -- identical before and after, so nothing on the default path moved.
**The replacement advice is PER MARK, because the forced paths are not equally reliable** (measured 2026-07-19):
| path | reliability |
|---|---|
| `erase --region x,y,w,h` | sound by construction -- the user supplies the coordinates |
| `--mark <text-mark> --no-detect` | reasonable: the forced mask is the real glyph blob, non-empty on 13/13 missed doubao marks |
| `--mark gemini --no-detect` | **NOT recommended** -- falls back to a fixed default sparkle slot, which covered the true sparkle on only **31% of 97** sparkles the strict gate missed (median offset 63px up-and-left). The other 69% fill a clean corner AND report a removal that did not happen. |
`cli._no_visible_mark_exit` therefore recommends `erase --region` first and a named text mark second, and never suggests forcing gemini. It previously recommended `--sensitivity assume-ai`, i.e. the product's own hint contradicted its model.
**Migration is LOUD, not silent.** `Sensitivity` is a `Literal` and unenforced at runtime, so a 0.15 caller passing `sensitivity="assume_ai"` would otherwise get `auto` behaviour in silence -- a quiet semantic change on exactly the release where they need telling. `validate_sensitivity` (called by `api.remove_visible` and by `Context.__post_init__`) raises a `ValueError` naming the replacement. Regression: `tests/test_watermark_registry.py::TestNoBlanketRelaxation`.
**Continuous top-hat detection front-end (`detect_frontend` / `tophat_response`, 2026-07-18).** `extract_mask` thresholds the white top-hat into a 0/255 glyph blob and correlates a binary silhouette against it. That is fine for a mark stamped bold and opaque, and destructive for a faint one: a thin translucent overlay shatters into specks under the threshold, and no template can match a blob that is not there (千问 measured 0.170 mean NCC, **0%** over its gate, against doubao's 0.723 / 82% -- same pipeline, each with its own template). The `tophat` front-end never binarizes: the saturation and absolute-luma gates become WEIGHTS instead of hard cuts, so a faint stroke contributes in proportion to its strength, and the response is max-normalized, which makes the score contrast-invariant.
Doubao is switched to it; jimeng and samsung stay `binary` until measured, because a front-end change must be measured per mark before it ships. Corpus effect on the 240-image unbiased recall sample:
| mark | recall before | recall after | precision before | precision after |
|---|---|---|---|---|
| doubao | 89% | **92%** | 99% | **99%** |
| jimeng / gemini / pill | unchanged | unchanged | unchanged | unchanged |
**The gate is FRONT-END SPECIFIC and must be re-calibrated, not ported.** The continuous response scores higher overall (mean 0.809 vs 0.723 on the same 90 positives), so the binary-era 0.40 left the provenance-relaxed gate (x0.7) far too low: at 0.40 the arm ran 96% recall / 91% precision (8 false fires), at 0.50 it runs 92% / 99% (1 false fire). 0.50 was chosen because it beats the binary front-end on recall at IDENTICAL precision -- a front-end that only trades one for the other would not have been worth shipping. A first pass at 0.40 also silently depressed the PILL (recall 50% -> 33%), because `_keep_pill` suppresses the pill whenever doubao fires; a coupling worth remembering when tuning any bottom-right mark.
**The removal MASK must ride the same front-end, and how it does so was fixed twice.** `tophat` detection does not binarize, but `extract_mask` (which bounds the fill) still does, so a mark faint enough to be found only by the continuous response produced an EMPTY binary blob: `localize` returned `mask=None`, `remove()` was a silent no-op, and `identify` reported `visible_doubao` while `visible` said "no visible mark" on the same file (corpus-measured 2026-07-20: 57 of 60 sampled still-detected Doubao marks untouched, ~8% of its detections). The FIRST fallback (2026-07-19) thresholded the continuous response and took the bounding box of everything above the level -- but the level was `0.5` compared against the max-normalized **uint8 0..255** response, so it selected every non-zero pixel and filled ~120% of the corner box on textured frames (a padded whole-ROI box). It passed parity (a mask that fills everything is trivially detector-clean) and its regression test (a FLAT fixture, where the response is non-zero only on the glyph, so every threshold yields the same box). The SECOND fallback (2026-07-20) uses the detector's OWN best-match box instead: `_tophat_score` was split into **`_tophat_best(image, loc) -> (score, box)`**, the single method whose score gates detection and whose argmax box bounds the mask -- so the two cannot drift by construction, which is how the mismatch arose in the first place. Measured over 14 real faint-path frames (cv2 fill, detector re-run after): the match box fills a **58.7%**-median corner box vs the threshold's **120.9%**, both 100% detector-clean. The largest-connected-component alternative was tighter (10.5%) but removed the mark on only 21% of frames, so it does not cover it and was rejected. Regression: `tests/test_text_mark_faint_mask.py`, whose fixture now carries texture (the flatness of the old one is exactly why it could not see the threshold bug -- mutating the constant to 99.0 left it green). **Any future front-end change must move both the detection and the mask path, or re-check this.**
**Vendor ATTRIBUTION for the shared-suffix marks -- solved for 千问 by exact sizing, not by a generic template.** The 2026-07-18 worry was that "千问AI生成" and "豆包AI生成" share the `AI生成` tail (four of six glyph cells), so their templates would cross-fire. That held while Qwen was scored at the WRONG SIZE (AUC 0.41-0.59, a coin flip). Re-measured 2026-07-21 at the fitted geometry on real pools (`scripts/vendor_mark_calibrate.py --crossfire`): Qwen's template scores p50 0.224 / p90 0.242 on 400 Doubao-marked frames against a 0.45 gate -- **0 cross-fires**, and 0 on 298 Jimeng-marked frames and 286 clean frames -- because an exact-size 6-glyph template is specific enough that the 2-glyph prefix mismatch dominates the shared tail. Qwen was therefore registered WITHOUT a rival margin (a 0.10 margin would have suppressed ~10% of genuine Qwen detections, whose margin p10 sits at 0.00). A GENERIC shared-tail template remains a harvesting aid, not a detector (measured: 0.407 on a bold positive vs clean p99 0.298).
**千问 is registered since 2026-07-21; 星绘 is NOT (still one confirmed example).** The 2026-07-18 measurement below is why 千问 was originally held out -- it is kept because it records the failure CLASS that the registration then had to solve. Measured back then on 14 hand-verified corpus positives, same pipeline, each mark scored with its OWN template:
| mark | n | mean NCC | median | above the 0.40 gate |
|---|---|---|---|---|
| doubao | 40 | 0.723 | 0.835 | **82%** |
| qwen | 14 | 0.170 | 0.179 | **0%** |
Three candidate explanations were ruled out in order, each by measurement:
1. **Not the synthetic render.** A template cut from an ACTUAL Qwen mark scores the same as the font-rendered one (real-vs-real 0.307 vs synthetic 0.308), and real masks do not match EACH OTHER.
2. **Not the morphology kernel.** `MORPH_OPEN`/`MORPH_CLOSE` use fixed 5px kernels regardless of mark size (~9% of a 57px-tall box, ~2.7% of a 188px one). Scaling them with the box height gained +0.014 mean and moved nothing across the gate.
3. **Not the appearance thresholds.** Sweeping `tophat_delta` / `logo_min_luma` / kernel size peaked at mean 0.35 with 4/14 over the gate.
The blocker was named as SEGMENTATION on a faint mark -- and the `tophat` front-end (built for Doubao the same week) removed exactly that blocker, yet 千问 still did not register, because the real residual was never segmentation alone: it was **mis-sized geometry** (two size modes the shared 3-rung ladder cannot straddle, plus a locate box that clipped the first glyph). The 2026-07-21 cohort harvest (117 labelled frames) and the full calibration chain are in the `qwen_engine.py` section below and `docs/verification-plan.md`. 星绘 remains where it was: ONE confirmed corpus example, so nothing to calibrate a gate against -- do not register it off a single frame. The synthetic renderer and the evidence chain are kept in `scripts/render_vendor_silhouettes.py`; researched vendor specs are in `docs/watermarking-landscape.md`.
**RECALL, measured at last (unbiased random sample, 2026-07-18).** Every earlier round sampled where detectors FIRED, so recall was structurally unmeasurable. This round draws 240 images at RANDOM within each provenance class (160 TC260, 80 Google-C2PA) and labels them EXHAUSTIVELY -- both corners shown at native scale, so a missed mark is visible as a miss rather than absent from the data. Build it with `scripts/visible_recall_sample.py`; labels live in the gitignored research dir.
| mark | present | recall | 95% CI | precision | 95% CI |
|---|---|---|---|---|---|
| doubao | 90 | **89%** | 81-94% | **99%** | 93-100% |
| gemini | 46 | **96%** | 85-99% | **80%** | 68-88% |
| jimeng | 14 | 71% | 45-88% | 71% | 45-88% |
| jimeng_pill | 6 | 50% | 19-81% | 60% | 23-88% |
Effect of the `scale_basis` fix on the same sample (strict verdicts recorded before it): **doubao recall 71% -> 89%**, gemini 91% -> 96%, jimeng 64% -> 71%. Part of the doubao gain is the provenance relaxation rather than the basis alone, since the after-numbers run the full `auto` path.
**Three corrections this forced to earlier numbers:**
* **Gemini precision is 80% on an unbiased sample, not the 41% the addition-sampled harness reports.** The 41% is precision restricted to relaxation ADDITIONS, which are by construction the marginal cases; production sees mostly strict fires, which are near-perfect. Quote 80% for the product and 41% only when discussing the relaxation arm.
* Doubao is in excellent shape (89/99) and is no longer the problem it looked like before the basis fix.
* Landscape is improved but NOT solved: doubao recall by aspect is portrait 92% / square 92% / **landscape 79%**, so a residual geometry gap remains beyond the basis.
**Where the remaining loss actually is:** jimeng and the pill, both at small n with intervals too wide to tune against (a 14-positive and a 6-positive sample), plus **uncovered vendors at 6% of all sampled images** (千问/百度/星绘/抖音-class marks that no registered detector can ever fire on). Adding those vendors is now a larger win than any further tuning of the covered four, and `docs/watermarking-landscape.md` carries their researched specs.
**Per-mark geometry scaling (`scale_basis` / `scale_base`, 2026-07-18) -- the largest single recall defect found so far.** Every tuned fraction in `TextMarkConfig` was calibrated on PORTRAIT captures, where the width and the short side coincide, so the scaling basis was never exercised until landscape inputs were measured. Corpus-measured on 2572 unique TC260 carriers, BEFORE the fix:
| aspect ratio | detected | missed | miss rate |
|---|---|---|---|
| tall portrait <0.70 | 323 | 212 | 40% |
| portrait 0.70-0.95 | 607 | 533 | 47% |
| square ~1.0 | 190 | 272 | 59% |
| landscape 1.15-1.6 | 0 | 143 | **100%** |
| wide >1.6 | 0 | 292 | **100%** |
**Not one landscape image in the corpus ever produced a detection** -- 435 of them, zero. A width-scaled box is inflated by the aspect ratio on a wide image, so the glyph never lands inside it and the blob never gets scored: of the 1452 no-detection TC260 images the median doubao NCC was **0.057**, with 49% at ~zero. This is a LOCALIZATION failure, not a threshold one -- only 2.7% of those images sat in the band a threshold change could reach, which is why a day of threshold tuning could never have found it. Re-running the previously-undetected set with a short-side basis recovers **56% of landscape** (12% square, 4% portrait; 20% overall).
**The basis is PER MARK because the vendors genuinely differ.** The same switch took jimeng's labelled landscape positives from 13/13 to **0/13**: the Jimeng wordmark tracks the WIDTH while the Doubao strip tracks the short side, even though both are ByteDance and share a corner. So doubao is `short`, jimeng is `width`, and samsung stays `width` because there is no corpus evidence either way (1 addition corpus-wide) and an unmeasured change is not an improvement. China's GB 45438-2025 clause 5.2(e) mandates glyph height >= 5% of "the shortest side", which is why short-side is the natural prior -- but jimeng's measured behaviour overrides the prior. Regression: `tests/test_text_mark_engine.py::TestScaleBasis`.
**How this was missed for so long:** precision was measured repeatedly and recall never was. The eval harness now reports a `missed` column for exactly this reason, and it is what caught the jimeng regression the short-side switch introduced.
**Competitive detection among same-corner marks (`rivals` / `_rival_margin_ok`, 2026-07-18).** Detection was purely ABSOLUTE -- every engine scored its own template against its own threshold, so nothing ever asked the discriminative question "does this blob match the NEIGHBOUR's mark better than mine?". Doubao "豆包AI生成" and Jimeng "★ 即梦AI" both sit bottom-right in near-white CJK and survive the top-hat binarization as very similar blobs, so no absolute gate can separate them. Measured on hand-labelled examples, scoring BOTH templates against the SAME glyph blob (n=40 jimeng / 75 doubao / 20 other-vendor labels / 89 clean):
| feature | separability (0.5 = useless, 1.0 = perfect) |
|---|---|
| absolute `ncc_jimeng` | 0.96 |
| `ncc_jimeng` MINUS `ncc_doubao` | **0.99** |
At a 0.10 margin: real Jimeng wordmarks pass **100%**, Doubao strips 8%, other vendors' AI labels (千问/百度/星绘/抖音) 55%, no-mark corners 12%. Corpus effect (`scripts/visible_eval.py`, 741 labelled images): **jimeng precision 38% -> 63%, genuine detections unchanged at 40, false fires 65 -> 23.** Because real marks pass at 100% this is a pure precision gain, unlike raising a threshold -- so the earlier 0.85 relaxation patch was REVERTED to 0.70 and the recall it had sacrificed came back. **The gate is deliberately asymmetric:** doubao declares no rival, because the symmetric gate cost it 7 genuine detections to prevent 5 false ones (1.4:1 against) while jimeng gained 25pp for free -- doubao's absolute detector is already 86% precise and has nothing to buy. A rival's config is looked up lazily by asset name (`_rival_config`) so its template is scored at ITS own geometry; scoring it at the host mark's geometry would compare a correctly-sized template against a mis-sized one and hand the margin a free win. Regression: `tests/test_text_mark_engine.py::TestRivalMargin`.
**Evaluation harness (`scripts/visible_eval.py` + `scripts/visible_groundtruth.py`, 2026-07-18).** Run before AND after any detector change; `--save NAME` snapshots, `--vs NAME` diffs. Ground truth is 741 blind-labelled corpus images (779 cells across two rounds, two-sided control each). Three properties of the harness are load-bearing and were each added after the naive version produced a wrong number:
* **Adjudication scope.** A crop centred on one mark only lets the labeller rule on marks visible IN THAT CROP. Scoring jimeng against a pill-round image (top-left crop) books real bottom-right detections as false fires -- ~61% of pills carry a wordmark. Each image records which marks its crop could rule on; bottom-right marks co-adjudicate each other.
* **Provenance must come from METADATA, never from the labels.** A relaxation arm only fires when provenance names the vendor, so label-derived provenance hands the detector the answer: it scored gemini at 99% instead of the true 41%.
* **Recall is NOT reported.** The labelled set was sampled where detectors fired, so images every detector missed are absent by construction; a recall computed here would divide by a denominator that excludes exactly the failures recall exists to expose. The `missed` column catches a change LOSING marks it used to find, nothing more. True recall needs a random corpus sample labelled exhaustively -- not yet done.
Baseline at the time of writing (sensitivity `auto`, provenance from metadata): gemini 41% (321 fires), doubao 86% (77), jimeng 63% (63), jimeng_pill 64% (83), samsung unmeasurable (1 addition corpus-wide).
**Per-mark provenance NCC relaxation + the corroboration gate (2026-07-18).** Two defects, both on the DEFAULT `auto` path (no flag, driven by TC260 metadata), found by blind hand-labelling the ADDITIONS (accepted with provenance, rejected without) over 4417 unique TC260 carriers. Two-sided control: labeller sensitivity 100% (doubao) / 96% (jimeng), specificity 100% / 100% — the controls are what make the low numbers trustworthy, and the "clean" stratum is structural (another vendor's C2PA image, where a ByteDance mark cannot exist) rather than detector-defined, so it is not circular.
(1) **One shared `_PROVENANCE_NCC_FACTOR = 0.7` meant two different things per mark:**
| mark | band | precision | 95% CI | n |
|---|---|---|---|---|
| doubao | whole arm | 76% | 61-87% | 42 |
| | [0.280,0.340) | 58% | 36-77% | 19 |
| | [0.340,0.400) | 91% | 73-98% | 23 |
| jimeng | whole arm | 17% | 10-27% | 82 |
| | [0.315,0.383) | 12% | 6-22% | 68 |
| | [0.383,0.450) | 43% | 21-67% | 14 |
The factor is now a per-mark `TextMarkConfig.provenance_ncc_factor`. Doubao stays 0.70 — both bands return more true marks than false fills, so tightening would cost 11 genuine recoveries to prevent 8. Jimeng moves to 0.85 (gate 0.3825), dropping the 12% band: −8 genuine recoveries, −60 false fills (7.5:1), arm precision 17% → 43%. **Why jimeng fails is a detector problem, not a threshold one:** of its 68 false additions, 33 were DOUBAO marks and 17 were other vendors' AI labels (千问 / 百度 / 星绘 / 抖音) — relaxed, the silhouette keys on "some text in the bottom-right corner", not on "★ 即梦AI". Damage was scored separately because doubao and jimeng share a corner: 45 of the 68 fill a corner nothing else would touch, the other 23 are harmless (doubao fires strictly there and fills the same box anyway). A better silhouette, not a lower factor, is the real fix.
(2) **A weak detector must not corroborate a sibling (`_CANNOT_CORROBORATE`).** `resolve_trust` grants `confirmed` on a strict-detected sibling of the same `_PRODUCT_OF`, and `confirmed` bypasses the sibling's FP gate outright. The pill (~7% documented raw false-fire; 5.5% on 578 vendor negatives) maps to product "jimeng", so it could hand that bypass to the wordmark — a closed loop: pill false-fires on clean non-ByteDance content → jimeng relaxes 0.45 → 0.3825 and false-fires → `_keep_pill` sees "jimeng" in keys and takes the WORDMARK arm, removing the pill **unrestricted**, skipping the flatness guard written to stop exactly that smear. 3 of 578 negatives ran the full loop, one with `footprint_flat=0`. The fix costs nothing: negatives 3 → 0, TC260 carriers unchanged (jimeng 398 → 398, pill 117 → 117). `_keep_pill` already encoded this distrust for the pill's ACTION; the gap was that its TESTIMONY was ungated.
**Pill arms, re-measured on the same corpus** (149 blind-labelled TC260-arm fires, 35 wordmark, 33 unconfirmed): wordmark **94%** (CI 81-98%, confirming the original claim), TC260-metadata-only **21%** raw (CI 16-29%, consistent with the original ~27%) — **29%** (CI 20-40%) among the flat footprints the guard PASSES vs 14% among those it blocks. The guard works directionally but weakly: the shipped arm still runs at ~2.4 false fills per genuine one. Whether an arm that inaccurate belongs on the default path is a product call, not a tuning one.
**Samsung's relaxation is UNMEASURED and not measurable here:** the corpus holds 14 `samsung_genai` carriers and 3 visible Samsung detections total. Any precision estimate would carry a Wilson interval spanning most of [0,1]. Likely structural — detection is calibrated to the Italian locale string only.
**Provenance prior:** when local metadata already confirms the vendor, the mark's detection trust gate is relaxed (a confirmed vendor means the mark is present with high prior, so a mark the conservative detector would demote as a content false positive is trusted). `detect_marks` / `remove_auto_marks` take a `provenance` frozenset and `KnownMark.remove` a `provenance` flag. Mapping: a Google/Gemini C2PA issuer relaxes gemini (skips its false-positive gate and lowers the trust threshold from 0.5 to 0.35); a China-AIGC (TC260) label relaxes doubao/jimeng; `samsung_genai` relaxes samsung. Corpus finding: on Google-C2PA images, Gemini sparkle recall rose from ~46% (plain detector) to ~90% with the provenance prior (recovering marks the vendor moved or re-rendered). That gain is why the bypass exists, and it is conditional on the metadata actually naming the vendor — a caller merely ASSUMING the image is AI does not get it unconditionally (see the assumed-trust confidence floor above). The localizer is cheap CPU (cv2/numpy), so a memory-tight caller runs it anywhere; the heavy MI-GAN/LaMa fill is opt-in and chosen by the caller.
**Cross-engine confidences aren't directly comparable**, so the gemini adapter applies the corpus-validated 0.5 sparkle threshold (`_GEMINI_AUTO_MIN_CONF`) for its `detected` flag (lowered to 0.35 under the Google/Gemini provenance prior) — otherwise the gemini engine's loose internal threshold weakly fires (~0.36) on the Doubao text and hijacks `auto`. The shape-keyed Doubao/Jimeng/Samsung NCC detectors don't cross-fire (jimeng scores ~0.22 on the Doubao strip, well under its 0.45 threshold; Samsung is bottom-left so it shares no corner with the others, and scored 0.0 on Doubao/Jimeng captures and they 0.0 on a real Samsung photo), so `auto` picks the right one. `cli.cmd_visible` is registry-driven: `--mark auto` → `remove_auto_marks` (removes every detected mark), `--mark <key>` → that mark; `--mark` choices come from `mark_keys()`.
**`cli._remove_visible_auto` is the shared visible-removal helper used by `cmd_all`/`cmd_batch` too** (they no longer hardcode `GeminiEngine`), so `all`/`batch` remove Doubao/Jimeng/Samsung text marks, not just the Gemini sparkle (regression-guarded by `test_all_visible_step_uses_registry`). The three text-mark adapters were consolidated 2026-06-09: a single `_text_mark(key, label, location)` builds the registry row from one parameterized `_text_mark_detect`/`_text_mark_remove` pair (the remove adapter localizes the glyph footprint and hands it to the shared `fill` only when detected/forced, else skipped); the gemini adapters stay bespoke. Add a new visible mark = one `_text_mark(...)` row + its `TextMarkConfig` (with a captured alpha map for the detection silhouette); do not re-add per-mark `if` branches or copy-paste adapters.
**`cli._remove_visible_auto` is the shared visible-removal helper used by `cmd_all`/`cmd_batch` too** (they no longer hardcode `GeminiEngine`), so `all`/`batch` remove Doubao/Jimeng/Qwen/Samsung text marks, not just the Gemini sparkle (regression-guarded by `test_all_visible_step_uses_registry`). The three text-mark adapters were consolidated 2026-06-09: a single `_text_mark(key, label, location)` builds the registry row from one parameterized `_text_mark_detect`/`_text_mark_remove` pair (the remove adapter localizes the glyph footprint and hands it to the shared `fill` only when detected/forced, else skipped); the gemini adapters stay bespoke. Add a new visible mark = one `_text_mark(...)` row + its `TextMarkConfig` (with a captured alpha map for the detection silhouette); do not re-add per-mark `if` branches or copy-paste adapters.
**Alpha-on-save policy (issue #30):** `cli._write_bgr_with_alpha` rejoins the input's alpha plane **unchanged** — it must NOT zero alpha in the watermark bbox. The fill reconstructs real pixels there, so zeroing alpha punched a transparent hole that renders as a solid **white box** on any non-transparent viewer (Gemini app exports are opaque RGBA, so every user hit it; regression-guarded by `test_visible_keeps_alpha_opaque_in_watermark_region`). The registry `remove()` still returns its region, but the CLI no longer uses it to clear alpha.
**Alpha-on-save policy (issue #30):** `image_io.write_bgr_with_alpha` (it lives in `image_io`, not `cli` — moved so the CLI and the library `api` share ONE implementation) rejoins the input's alpha plane **unchanged** — it must NOT zero alpha in the watermark bbox. The fill reconstructs real pixels there, so zeroing alpha punched a transparent hole that renders as a solid **white box** on any non-transparent viewer (Gemini app exports are opaque RGBA, so every user hit it; regression-guarded by `test_visible_keeps_alpha_opaque_in_watermark_region`). The registry `remove()` still returns its region, but the CLI no longer uses it to clear alpha. **It returns `imwrite`'s success flag and callers must check it** (2026-07-20): `imwrite` is contractually non-raising, so that bool is the only signal the file was not created. The wrapper previously returned `None` and swallowed it, so every CLI write site ran `output.stat()` to report the size and a read-only destination died with a bare `FileNotFoundError` traceback pointing at the stat instead of the write. The CLI now writes through the shared `cli._write_output_or_exit`. Regression: `tests/test_cli_robustness.py::TestFailedWriteIsReported`.
## `gemini_engine.py`
@@ -97,7 +215,7 @@ The cost (mislabel ~8-33% of non-Gemini content as Gemini) outweighs the benefit
## `_text_mark_engine.py`
`_text_mark_engine.py` — **shared base for the three text-mark engines (Doubao/Jimeng/Samsung), extracted 2026-06-09** (they were ~90% byte-identical clones). `TextMarkEngine(config: TextMarkConfig)` owns the `locate → extract_mask → detect` detection pipeline plus the removal that localizes the glyph blob to a footprint mask and hands it to the shared `watermark_registry.fill` (+ the asset-keyed `load_alpha_template`/`glyph_silhouette`/`template_match_score` caches). Detection still matches the glyph silhouette (NCC against the captured template); the removal MASK is TEMPLATE-FREE — it is the bounding box of the top-hat glyph blob from `extract_mask`, filled solid + dilated, so a re-rendered or differently-placed mark is still masked. This dropped the fixed alpha-template placement; the captured alpha maps are now used only for the detection silhouette, not for removal. Each engine module is a thin subclass supplying only its `TextMarkConfig` (the tuned constants, the bundled asset, and the bounded structural deltas — `corner` br/bl, `margin_floor` 4/2, `morph_open_size` 5/3, `min_gw` 8/16) plus the test-facing module shims (`_alpha_template`/`_glyph_silhouette`/`_template_match_score` + the constants). Gemini stays a SEPARATE engine (its multi-size fixed-slot sparkle model is genuinely different). Add a new text mark = a new `TextMarkConfig` + a thin subclass + one registry `_text_mark(...)` row. The engine bullets below describe each mark's calibration history; the LOGIC lives here. **Small-image detection guard (`_MIN_DETECT_SHORT_SIDE` 200, added 2026-06-26):** `detect` returns not-detected when the image short side is below 200px. Below that the glyph template degrades to the `min_gw` floor (~8px) and `TM_CCOEFF_NORMED` on a few pixels is noise, so an unrelated small geometric shape can spuriously correlate with the CJK silhouette — a 48×48 app-icon chevron scored Doubao 0.41 / Jimeng 0.47 (both above their thresholds), a pure small-size artifact (the same icon upscaled collapses to ~0.06–0.10 NCC at ≥256px). A real AI-generation label is stamped on a full-resolution render (the captured samples are 1086–2048px wide, the smallest positive test image is 1086px), so the floor sits far below any genuine mark while killing the icon/thumbnail band (≤96px); `identify` falls back to "unknown" (the safe default) and removal, gated on detection, is suppressed too. Regression-guarded by `test_{doubao,jimeng,samsung}_engine.py::TestDetect::test_small_image_guarded_from_false_positive`.
`_text_mark_engine.py` — **shared base for the three text-mark engines (Doubao/Jimeng/Samsung), extracted 2026-06-09** (they were ~90% byte-identical clones). `TextMarkEngine(config: TextMarkConfig)` owns the `locate → extract_mask → detect` detection pipeline plus the removal that localizes the glyph blob to a footprint mask and hands it to the shared `watermark_registry.fill` (+ the asset-keyed `load_alpha_template`/`glyph_silhouette`/`template_match_score` caches). Detection still matches the glyph silhouette (NCC against the captured template); the removal MASK is TEMPLATE-FREE — it is the bounding box of the top-hat glyph blob from `extract_mask`, filled solid + dilated, so a re-rendered or differently-placed mark is still masked. This dropped the fixed alpha-template placement; the captured alpha maps are now used only for the detection silhouette, not for removal. Each engine module is a thin subclass supplying only its `TextMarkConfig` (the tuned constants, the bundled asset, and the bounded structural deltas — `corner` br/bl, `margin_floor` 4/2, `morph_open_size` 5/3, `min_gw` 8/16, and since 2026-07-21 `ladder` — the scale rungs `_tophat_best` sweeps, per-mark because 千问's two size modes do not fit the shared 3-rung comb (default `(0.8, 1.0, 1.25)`, unchanged for every other mark; densifying the SHARED ladder was measured and rejected -- see the verification plan's B2). plus the test-facing module shims (`_alpha_template`/`_glyph_silhouette`/`_template_match_score` + the constants). Gemini stays a SEPARATE engine (its multi-size fixed-slot sparkle model is genuinely different). Add a new text mark = a new `TextMarkConfig` + a thin subclass + one registry `_text_mark(...)` row. The engine bullets below describe each mark's calibration history; the LOGIC lives here. **Small-image detection guard (`_MIN_DETECT_SHORT_SIDE` 200, added 2026-06-26):** `detect` returns not-detected when the image short side is below 200px. Below that the glyph template degrades to the `min_gw` floor (~8px) and `TM_CCOEFF_NORMED` on a few pixels is noise, so an unrelated small geometric shape can spuriously correlate with the CJK silhouette — a 48×48 app-icon chevron scored Doubao 0.41 / Jimeng 0.47 (both above their thresholds), a pure small-size artifact (the same icon upscaled collapses to ~0.06–0.10 NCC at ≥256px). A real AI-generation label is stamped on a full-resolution render (the captured samples are 1086–2048px wide, the smallest positive test image is 1086px), so the floor sits far below any genuine mark while killing the icon/thumbnail band (≤96px); `identify` falls back to "unknown" (the safe default) and removal, gated on detection, is suppressed too. Regression-guarded by `test_{doubao,jimeng,samsung}_engine.py::TestDetect::test_small_image_guarded_from_false_positive`.
**Removal is localize -> fill.** The engine localizes the glyph blob (`extract_mask` over the located box) into a solid, dilated footprint mask and hands it to the shared `watermark_registry.fill` (cv2 / MI-GAN / big-LaMa). The template-free mask (bounding box of the glyph blob, not the fixed alpha template) means a re-rendered or moved mark is still covered, and the fill reconstructs the box from its surroundings. On corpus images doubao and jimeng localize + remove at ~100% with clean footprints (the filled region blends into its surroundings within a few LAB levels, no color shift, no dark pit); clean images with no vendor signature had 0% false removal.
@@ -135,6 +253,50 @@ The cost (mislabel ~8-33% of non-Gemini content as Gemini) outweighs the benefit
**No committed real sample** (only the flat calibration captures are committed) — `tests/test_samsung_engine.py` synthesizes a mark from the bundled template (bottom-left geometry), with `test_recovers_shifted_mark_on_texture` guarding the localize-on-shift path. Samsung Galaxy AI edits are independently caught by C2PA + the `genAIType` marker in `metadata`/`identify`, so this engine is the visible-mark *removal* path; it also feeds `identify` as the medium-confidence `visible_samsung` signal via the registry (the stripped-metadata fallback).
## `qwen_engine.py`
`qwen_engine.py` — **a thin `TextMarkEngine` subclass (config only), registered 2026-07-21.** visible Qwen (Alibaba Tongyi Qianwen) "千问AI生成" detector + localizer (cv2/numpy, no GPU), bottom-right, the same GB 45438-2025 6-glyph house style as Doubao (2-glyph vendor prefix + mandated `AI生成` tail; the vendor's tri-lobe logo precedes the text and is deliberately NOT in the silhouette -- logos vary between releases, the CJK run is what discriminates). The detection silhouette `assets/qwen_alpha.png` is font-rendered synthetic (`scripts/render_vendor_silhouettes.py`), never cut from an upload. Feeds `identify` as the medium-confidence `visible_qwen` signal via the registry.
**Why this registration took two attempts:** the 2026-07-18 attempt died at n=1 positives; the unlock was the TC260 label's `ContentProducer` field, whose USCC names the signing entity and partitions carriers into per-vendor cohorts from metadata alone (`scripts/vendor_cohort_harvest.py` -- 117 labelled Qwen frames, owing nothing to any pixel detector). Every constant was then MEASURED on that cohort against 286 hand-labelled clean frames (`scripts/vendor_mark_calibrate.py`), not inherited from Doubao:
* **Basis `short`** (frac_short CV 0.189 vs width 0.273).
* **Per-mark 2-rung `ladder=(0.78, 1.27)`** against `alpha_width_frac` 0.160: the mark sits in TWO size modes (~0.124 and ~0.203 of the short side, ratio 1.64, both clusters tight) -- wider than the shared 3-rung ladder's 1.5625 span, so the best single fraction covers only 74.5% and the small mode lands in the comb's collapse zone (real marks at the exact rung score ~0.94 vs ~0.67 on the shared ladder). A 4-rung variant scored strictly worse (its big-mode rung sits 4.6% off the mode). The shared default is untouched for every other mark.
* **Fitted locate box** (`width_frac` 0.231, `height_frac` 0.074, margins ~0.021): the real mark sits ~0.025 of the short side off the right edge, and Doubao's box (0.004 margin) clipped the first glyph -- an exact-size template collapsed 0.73 -> 0.26 on a real frame.
* **`alpha_height_frac` 0.0416 from the aspect fit** (p50 aspect 0.260 at the winning width) -- not the silhouette's own aspect (0.2219) and not Doubao's ratio.
* **Gate 0.45**: clean p99 0.301 / max 0.316 (286 frames), and every cohort frame >= 0.45 carries a visible mark (83 of ~96 eyeballed visible marks fire = 86% recall of visible marks; the misses are white-on-near-white contrast losses). 0.45 was picked over 0.32 for margin against unseen clean content at zero measured recall cost.
* **STRICT ONLY (`provenance_ncc_factor` 1.0):** the score band just below the gate is dominated by non-Qwen banners on same-cohort frames (a 夸克 anti-forgery strip at 0.274, a 造点 mark at 0.253), so a provenance-relaxed arm would be mostly false fills. There is no provenance mapping for qwen and no relaxed arm.
* **No rival margin:** 0 cross-fires on 400 Doubao-marked / 298 Jimeng-marked / 286 clean frames at the gate, while a 0.10 margin would have cost ~10% of genuine Qwen detections. A confident Qwen detection suppresses the Jimeng pill exactly like Doubao's does (`_keep_pill` -- a Qwen frame is TC260 too but is not Jimeng-basic).
**Parity:** detect -> cv2 fill -> re-detect is clean on **83/83** real cohort marks, no empty masks (the `tophat` faint-mask fallback rides the same `_tophat_best`); the e2e suite drives one live cohort positive through the real CLI (`scripts/real_examples_e2e.py`, qwen bucket = symlinks under the gitignored `_visible_datasets/`). Regression: `tests/test_qwen_engine.py` (pins the ladder, the strict-only factor, the box anchor, and both size modes at a score floor that discriminates the shared-ladder and Doubao-margin mutations).
**The clean-arm contamination trap (load-bearing for any future calibration):** the 2026-07-18 `present: []` labels are in the vocabulary of the REGISTERED marks only, so 146 of the 432 "clean" frames sit in a TC260 cohort -- including Qwen-cohort frames visibly carrying 千问AI生成. They made up the clean arm's entire top tail (clean p99 0.37 -> 0.69). `vendor_mark_calibrate.load_sets` now excludes every frame in ANY TC260 cohort from the clean arm; a gate read off the unguarded arm is meaningless.
## `runninghub_engine.py`
`runninghub_engine.py` — **thin `TextMarkEngine` subclass, registered 2026-07-22.** RunningHub (hosted ComfyUI platform, USCC 91340100MAEB4N8H76, 73-frame cohort) "RunningHub AI生成" detector + localizer, **top-left** (the first `corner="tl"` mark), faint mid-gray latin+CJK text. Feeds `identify` as `visible_runninghub`.
* **`gray` front-end (the third one, added for this mark):** the mark's faint gray is suppressed by the white top-hat to clean-arm levels (positives 0.16-0.23 vs clean p99 0.31), while raw-grayscale silhouette NCC separates (positives 0.38-0.54 vs clean p99 0.264 / max 0.304 on 283 guarded clean frames). It is contrast-DEPENDENT, unlike tophat -- one method `_gray_best` serves both detection and the mask, same one-method parity contract as `_tophat_best`.
* **Tight ladder (0.95, 1.0, 1.05) exactly on the measured 0.32-of-width:** the NCC comb is razor-sharp in size (0.537 on-size, 0.223 at +5.6% off -- Qwen's comb behaviour, measured again here), so the shared 3 rungs (nearest rung 5.6% off) collapsed the match to 0.22 and the first calibration showed no separation at all.
* **Anchor gate in `detect`:** the full-corpus sweep (`data/spaces/_sweep_new_marks.py`, 42009 files) fired on 37 outside-cohort frames at 0.34-0.38 (hair tops, shelves, window frames, CJK banners) -- no NCC threshold separates them from the 0.381 positives. Every positive sits at the measured corner (x 0.008-0.014, y 0.005-0.007 of the frame) and every false fire off it (x 0.013-0.150, y 0.009-0.045), so detection additionally requires the match box inside x<=0.025 / y<=0.015 of the frame. 0/37 false, 4/4 positives kept.
* **Footprint is always the detector's match box** (never the binary blob): the blob under-segments the faint head glyphs and left "Runni" unremoved (caught visually on the first removal). Gate 0.34, STRICT ONLY. Regression: `tests/test_runninghub_engine.py`.
## `baidu_engine.py`
`baidu_engine.py` — **thin `TextMarkEngine` subclass with a custom `footprint_mask`, registered 2026-07-22.** Baidu (USCC 91110000802100433B, 16-frame cohort) "百度 AI生成" detector + localizer, bottom-right: a white bold 百度 text run + a separate white rounded tag with dark "AI生成". Feeds `identify` as `visible_baidu`.
* **Detection keys on the 百度 text run ONLY.** A two-component (text+pill) template was measured and rejected: the solid white pill is a bright-blob magnet and both front-ends scored the clean arm at cohort levels (tophat clean p95 0.445 / gray clean p95 0.487 vs cohort ~0.5). The text-only silhouette separates (cohort 0.39-0.65 vs clean max 0.352). The white tag is still removed: the footprint extends to the corner (below).
* **Two load-bearing rival margins** (`rivals=("doubao_alpha.png","qwen_alpha.png")`): 百度 vs 豆包 share their second glyph, and 百度 vs 千问 are near-identical after binarization -- at the 0.37 gate the template fired on 45.8% of 400 Doubao-marked frames and, on the 741-frame blind-labelled eval set, on 12 Qwen-marked frames at 0.38-0.43. Doubao's template beats it by ~0.56 on Doubao marks, Qwen's by 0.17-0.35 on Qwen marks; the 0.10 margin suppresses all crossfire at zero genuine-Baidu cost (cohort fire+m == fire).
* **Gate history, each step measured:** 0.37 from the clean arm (max 0.352) -> 0.43 after the eval-set crossfires (the one 抖音 AI创作 fire at 0.425 named no registered rival) -> **0.48** after the full-corpus sweep put outside-cohort TRUE carriers at 0.50-0.66 vs the false arm max 0.47 (大众点评 UI, a math blackboard, an 80s banner). Cohort keeps 7/16 (all true); the sweep also found 6 metadata-STRIPPED true Baidu carriers the TC260 cohort cannot see -- the direct evidence that registration pays beyond the cohort.
* **Custom `footprint_mask`:** the tag's flat white interior gives no top-hat response (a top-hat answers edges, not flats), so the base blob bbox ended at the text run and the fill left the tag as a ghost. The mask is the detector's match box extended RIGHT to the corner. STRICT ONLY. Regression: `tests/test_baidu_engine.py`.
## `liblib_engine.py`
`liblib_engine.py` — **thin `TextMarkEngine` subclass with a custom `footprint_mask`, registered 2026-07-22.** LibLibAI (哩布哩布AI, USCC 91110105MACJ6K1C8A, 15-frame cohort) triangle logo + "LibLibAI" wordmark detector + localizer, **bottom-CENTER** (the first `corner="bc"` mark; the locate box is horizontally centered). Feeds `identify` as `visible_liblib`.
* **The discriminative lever is the silhouette FONT.** With the CJK house font (STHeiti) the cohort scored 0.31-0.47 against a full-corpus false arm (latin UI text bands, website screenshots) at 0.50 -- no separation at any gate. Measured across 7 candidate fonts, **Arial** lifts the cohort to 0.42-0.73 and DROPS the false arm to max 0.398: generic latin text matches the wrong font less, which is where the discrimination comes from. Gate 0.42 keeps all 8 marked cohort frames (0.43-0.59).
* **Per-mark size floor (`_MIN_SHORT_SIDE=480`):** the one false fire with the final template was a 200x200 icon (0.444, on a 20px template). The shared `_MIN_DETECT_SHORT_SIDE` (200) is a crash guard, not a discrimination floor; the template needs ~48px to discriminate.
* **Custom `footprint_mask`:** the base blob bbox was wrong in both directions -- it bled UP into background structure (ate a shirt's real print on the 768x1024 cohort frame) and never owned the triangle logo. The mask is the detector's match box extended LEFT by ~1.3 glyph heights (the logo is ~1.0x the glyph height, gap ~0.3x, measured on the cohort zoom). STRICT ONLY. Regression: `tests/test_liblib_engine.py`.
## `region_eraser.py`
`region_eraser.py` — universal region eraser (`erase` CLI) AND the shared fill backend behind `watermark_registry.fill` for the visible localize -> fill removal. `erase(image, boxes=|mask=, backend=)` accepts grayscale (2D) and RGBA (4-channel) inputs on **all** backends (each splits off any alpha plane and re-attaches it unchanged, and promotes grayscale to BGR): `boxes_to_mask` → one of three backends.
@@ -220,6 +382,8 @@ KEPT from that work (independently valid for the manual `--pipeline qwen`): the
Full per-command behavior for the skip/exit branches summarized in `CLAUDE.md`'s "How to run". The CLI distinguishes three exit codes: success (0), hard error (1), and a "nothing to do" code (2, `EXIT_NO_VISIBLE_MARK` / `EXIT_NO_INVISIBLE_SIGNAL`) so a wrapping service (raiw.cc) can surface guidance instead of treating an unchanged image as done (the production "it didn't work" / score-0 trap).
**Every single-image command's `source` argument declares `dir_okay=False`** (2026-07-20). `click.Path(exists=True)` accepts a directory unless told otherwise, so `identify <dir>` sailed past argument parsing and raised `IsADirectoryError` out of `metadata.scan_head`'s `open()` — a traceback, not a usage error. Refusing it at the argument layer is the right place: every command gets it, and none needs its own check. (`batch`'s `directory` argument was already correct with `file_okay=False`.) Found by the Tier E adversarial sweep; regression: `tests/test_cli_robustness.py::TestDirectoryInputIsRejected`.
### `all`
Full pipeline (visible + invisible + metadata). Same diffusion knobs as `invisible`, plus the visible-pass `--backend auto|cv2|migan|lama` (default `auto`) that picks the fill for the localize -> fill visible removal. **When the `[gpu]` extra is absent, step 2 (invisible/SynthID) is skipped** — `all` still writes an output (visible mark + metadata stripped) but prints a prominent end-of-run banner ("the invisible (SynthID) watermark was NOT removed") AND exits **non-zero** (1), so a skipped SynthID pass is not mistaken for a clean result (the recurring #14/#47 trap, where the old quiet inline warning was missed). `invisible` already hard-errors without the extra; only `all` continued, hence the loud end-banner. Regression-guarded by `tests/test_cli.py::TestAllCommand::test_all_loud_warning_and_nonzero_exit_when_gpu_missing`. **No-signal skip (P0#5):** step 2 also runs the same `has_invisible_target` gate (see `invisible` below) — when no invisible watermark is detectable and `--force` is not set, step 2 is skipped and the pixels are left intact, but unlike the GPU-missing skip this is a **SUCCESS (exit 0)**: the visible pass + metadata strip still ran and a file is written (the message says so without claiming the image is clean). Distinct exit semantics by design: GPU-missing = couldn't do the work (non-zero); no-signal = nothing to do (zero). Regression-guarded by `test_all_skips_invisible_on_no_signal_but_succeeds`. **Test trap:** any `all` test that exercises the full pipeline MUST `patch("remove_ai_watermarks.invisible_engine.is_available", return_value=True)` — CI installs core+dev only (no `[gpu]`), so an unpatched `all` test takes the skip branch and now hits the non-zero exit. This passed locally (gpu present → `is_available()` True) but red-failed every matrix cell on the v0.11.0 commit (`test_all_basic`/`test_all_visible_step_uses_registry` asserted exit 0); both now patch `is_available` True.
@@ -230,7 +394,7 @@ Diffusion SynthID removal. The `--tile/--no-tile` knob is the *lossless* alterna
### `visible`
Known-visible-mark removal by **localize -> fill**: each detected mark is localized to a binary full-frame footprint mask, then one shared, swappable fill inpaints that mask. `--backend auto|cv2|migan|lama` (default `auto`) picks the fill: `cv2` (classical inpaint, no deps, the floor), `migan` (MI-GAN ONNX, the memory-tight pick where LaMa will not fit), `lama` (big-LaMa ONNX, best quality, heavier, auto-preferred when a learned backend is available); `auto` = LaMa > MI-GAN > cv2, best available (LaMa is auto-preferred when a learned backend is present; a memory-tight deploy pins migan). `--sensitivity auto|strict|assume-ai` (default `auto`) controls how hard a borderline mark is trusted (see the registry section: the visual detectors are metadata-independent; `auto` relaxes a mark only on same-product evidence, `assume-ai` relaxes every mark on the caller's AI assertion — the only path to high recall on a metadata-stripped screenshot). `--backend` and `--sensitivity` are shared across `visible`/`all`/`batch`. Detection keys on each mark's own shape, and under `auto` the trust gate is relaxed when local metadata confirms the vendor (a Google/Gemini C2PA issuer relaxes gemini, a China-AIGC label relaxes doubao/jimeng, `samsung_genai` relaxes samsung), so a moved or re-rendered mark is still caught. `--mark auto` (default) removes EVERY detected mark in one pass (`registry.remove_auto_marks`, not the single strongest -- a Jimeng-basic image carries both the top-left pill and the bottom-right wordmark) from: the Gemini sparkle, the Doubao "豆包AI生成" text strip, the Jimeng "★ 即梦AI" wordmark, the Samsung Galaxy AI "✦ Contenuti generati dall'AI" strip (bottom-LEFT, Italian-locale detection), and the capture-less Jimeng "AI生成" pill (top-left, `pill_engine`). The pill's weak edge-NCC detector is gated in `remove_auto_marks` via `_keep_pill` (32k real-upload corpus validation 2026-07): never on Doubao, and two confirmation arms since metadata confirms the platform, not pill presence. (1) The bottom-right wordmark fired — ~94% precise and survives metadata-STRIPPED uploads (screenshots / re-saves) — removes the pill unrestricted. (2) TC260 metadata confirms Jimeng (`"jimeng" in provenance`, from `cli._visible_provenance`) OR the caller asserts AI (`sensitivity == "assume_ai"`), no wordmark — ~27% precise, its false fires are textured ceilings/walls that the fill visibly SMEARS — removes the pill ONLY when the top-left footprint is flat enough for an invisible fill (`pill_engine.footprint_is_flat`, median-Sobel ≤ `_FLAT_TEXTURE_MAX`; the flatness guard holds even under `assume_ai`). No confirmation → never removed. `--mark gemini|doubao|jimeng|samsung|jimeng_pill` forces one (choices come from the registry). Corpus validation: doubao and jimeng localize + remove at ~100% with clean footprints (the filled region blends into its surroundings within a few LAB levels, no color shift, no dark pit); clean images with no vendor signature had 0% false removal. For arbitrary logos/objects use `erase`. **When `--mark auto` finds no known mark (the common case — ~74% of real uploads carry no registered visible mark), the command does NOT silently re-serve the input as a finished result.** It runs a cheap metadata-only `identify`, prints actionable guidance (if the image carries an invisible/metadata mark, e.g. an OpenAI/Gemini C2PA image, it points to `all`; otherwise it does NOT imply the image is clean -- it warns that an invisible pixel watermark like SynthID cannot be detected once the metadata proxy is gone and routes to both `all` and `erase --region`), writes NO output file, and exits **`EXIT_NO_VISIBLE_MARK` (2)** — distinct from success (0) and a hard error (1) so a wrapping service (raiw.cc) can surface the message instead of treating the unchanged image as done (the production "it didn't work" / score-0 trap). Same handling for an explicit `--mark <name>` that is not detected. Helper `cli._no_visible_mark_exit`; regression-guarded by `tests/test_cli.py::TestVisibleCommand::test_visible_auto_no_mark_exits_two_with_eraser_hint` and `test_visible_auto_no_mark_routes_to_all_when_metadata`. `--no-detect` still forces the gemini fallback and proceeds (exit 0).
Known-visible-mark removal by **localize -> fill**: each detected mark is localized to a binary full-frame footprint mask, then one shared, swappable fill inpaints that mask. `--backend auto|cv2|migan|lama` (default `auto`) picks the fill: `cv2` (classical inpaint, no deps, the floor), `migan` (MI-GAN ONNX, the memory-tight pick where LaMa will not fit), `lama` (big-LaMa ONNX, best quality, heavier, auto-preferred when a learned backend is available); `auto` = LaMa > MI-GAN > cv2, best available (LaMa is auto-preferred when a learned backend is present; a memory-tight deploy pins migan). `--sensitivity auto|strict|assume-ai` (default `auto`) controls how hard a borderline mark is trusted (see the registry section: the visual detectors are metadata-independent; `auto` relaxes a mark only on same-product evidence, `assume-ai` relaxes every mark on the caller's AI assertion, subject to the assumed-trust confidence floor where the vendor is unconfirmed — the only path to higher recall on a metadata-stripped screenshot). `--backend` and `--sensitivity` are shared across `visible`/`all`/`batch`. Detection keys on each mark's own shape, and under `auto` the trust gate is relaxed when local metadata confirms the vendor (a Google/Gemini C2PA issuer relaxes gemini, a China-AIGC label relaxes doubao/jimeng, `samsung_genai` relaxes samsung), so a moved or re-rendered mark is still caught. `--mark auto` (default) removes EVERY detected mark in one pass (`registry.remove_auto_marks`, not the single strongest -- a Jimeng-basic image carries both the top-left pill and the bottom-right wordmark) from: the Gemini sparkle, the Doubao "豆包AI生成" text strip, the Jimeng "★ 即梦AI" wordmark, the Qwen "千问AI生成" text strip, the Samsung Galaxy AI "✦ Contenuti generati dall'AI" strip (bottom-LEFT, Italian-locale detection), and the capture-less Jimeng "AI生成" pill (top-left, `pill_engine`). The pill's weak edge-NCC detector is gated in `remove_auto_marks` via `_keep_pill` (32k real-upload corpus validation 2026-07): never on Doubao or Qwen, and two confirmation arms since metadata confirms the platform, not pill presence. (1) The bottom-right wordmark fired — ~94% precise and survives metadata-STRIPPED uploads (screenshots / re-saves) — removes the pill unrestricted. (2) TC260 metadata confirms Jimeng (`"jimeng" in provenance`, from `cli._visible_provenance`) OR the caller asserts AI (`sensitivity == "assume_ai"`), no wordmark — **re-measured 2026-07-18 on 149 blind-labelled pill fires: 21% precise raw (CI 16-29%), 29% (CI 20-40%) among the flat footprints the guard actually PASSES, 14% among those it blocks** — its false fires are textured ceilings/walls that the fill visibly SMEARS — removes the pill ONLY when the top-left footprint is flat enough for an invisible fill (`pill_engine.footprint_is_flat`, median-Sobel ≤ `_FLAT_TEXTURE_MAX`; the flatness guard holds even under `assume_ai`). No confirmation → never removed. `--mark gemini|doubao|jimeng|qwen|samsung|jimeng_pill` forces one (choices come from the registry). Corpus validation: doubao and jimeng localize + remove at ~100% with clean footprints (the filled region blends into its surroundings within a few LAB levels, no color shift, no dark pit); clean images with no vendor signature had 0% false removal. For arbitrary logos/objects use `erase`. **When `--mark auto` finds no known mark (the common case — ~74% of real uploads carry no registered visible mark), the command does NOT silently re-serve the input as a finished result.** It runs a cheap metadata-only `identify`, prints actionable guidance (if the image carries an invisible/metadata mark, e.g. an OpenAI/Gemini C2PA image, it points to `all`; otherwise it does NOT imply the image is clean -- it warns that an invisible pixel watermark like SynthID cannot be detected once the metadata proxy is gone and routes to both `all` and `erase --region`), writes NO output file, and exits **`EXIT_NO_VISIBLE_MARK` (2)** — distinct from success (0) and a hard error (1) so a wrapping service (raiw.cc) can surface the message instead of treating the unchanged image as done (the production "it didn't work" / score-0 trap). Same handling for an explicit `--mark <name>` that is not detected. Helper `cli._no_visible_mark_exit`; regression-guarded by `tests/test_cli.py::TestVisibleCommand::test_visible_auto_no_mark_exits_two_with_eraser_hint` and `test_visible_auto_no_mark_routes_to_all_when_metadata`. `--no-detect` still forces the gemini fallback and proceeds (exit 0).
### `batch`
+4 -1
View File
@@ -16,6 +16,8 @@ stays in `CLAUDE.md`; read this before cutting a release.
**This is now AUTOMATED:** the main repo's `.github/workflows/distribute.yml` fires on the GitHub Release `published` event, waits for the sdist to appear on PyPI (poll loop, the Release event races publish.yml's upload), rewrites the formula's `url`+`sha256`, and pushes to the tap using the `HOMEBREW_TAP_TOKEN` repo secret (a fine-grained PAT with Contents:write on `homebrew-tap`). The SAME workflow also factory-rebuilds the HF Space (`HfApi.restart_space(..., factory_reboot=True)`, `HF_TOKEN` secret) so the Space reinstalls the new sdist (it pins `remove-ai-watermarks>=...` and only re-resolves on a rebuild). The manual Homebrew steps above are the fallback / what the workflow automates — a normal release needs no Homebrew or HF action.
**Where the HF Space's own source lives (its demo code, NOT this library):** the private repo **`wiltodelta/raiw-hf-space`** (locally `~/Documents/GitHub/raiw-hf-space`) — `app.py` (CPU-core Gradio demo), `requirements.txt`, `README.md` (the Space card), `assets/`, `examples/`. **Deploying it is a plain `git push` to that repo's `main`:** its `.github/workflows/sync-to-hf.yml` mirrors the files onto the Space via the Hub API (`HfApi.upload_folder`, secret `HF_TOKEN` = a **write**-role token), which adds a commit on top of the Space's own history — deliberately NOT a `git push --force` to the Space, which would clobber it. Do NOT edit the Space through the huggingface.co web UI any more: that was the pre-2026-07-16 workflow (it is why every Space commit before then is authored `@users.noreply.huggingface.co` and why no local write token ever existed), and a web edit now silently diverges from the GitHub source of truth. Note the demo tracks the library's **CPU-core** surface only (`identify` / `visible` / `metadata`); the invisible/SynthID path needs a GPU and stays out. Two distinct automations touch the Space and must not be confused: `sync-to-hf.yml` (in `raiw-hf-space`) ships **demo code changes**; `distribute.yml` (in this repo) factory-rebuilds the Space on a **library release** so its `remove-ai-watermarks>=...` pin re-resolves to the new version.
**If the distribute.yml Homebrew job fails with "Bad credentials" (or the tap push 403s),** the `HOMEBREW_TAP_TOKEN` secret has expired or been revoked — fine-grained PATs expire on a fixed date, so this recurs. Fix: rotate the PAT (a fine-grained token with Contents:write on `wiltodelta/homebrew-tap`), update the `HOMEBREW_TAP_TOKEN` repo secret, then re-run the failed job (`gh run rerun <run-id> --failed`). While the token is being rotated, the manual formula bump above unblocks the release. The same rotate-secret-and-rerun applies to any distribute.yml credential failure (`HF_TOKEN` for the Space rebuild).
**Other distribution channels:** (1) **conda-forge** — recipe source of truth committed at `packaging/conda/recipe.yaml` (v1 `recipe.yaml`, noarch core-only: pillow/piexif/numpy/py-opencv/click/python-dotenv); the initial submission is `conda-forge/staged-recipes` PR #33674 (went green only after **`pip_check: false`** in the python test — rattler-build's `pip check` defaults to ON and fails on the ancient conda-forge `piexif py_2` build's stale metadata with "piexif 1.1.3 is not supported on this platform", though the package installs/imports/works; keep it disabled). Once that merges and the `remove-ai-watermarks-feedstock` exists, the `regro-cf-autotick-bot` auto-opens a version-bump PR on the feedstock when each new PyPI sdist is detected — just review + merge it (hand-edit only if run-deps changed; keep `packaging/conda/recipe.yaml` in sync as the reference copy). (2) **ComfyUI Registry** — the node package is a SEPARATE repo `wiltodelta/ComfyUI-remove-ai-watermarks` with its OWN `pyproject.toml` `version` (independent of the library version). Publish a new node version by bumping that `version` in the node repo's `pyproject.toml` and pushing to `main` — the node repo's `.github/workflows/publish.yml` (`Comfy-Org/publish-node-action@main`, triggered on a push that touches `pyproject.toml`, secret `COMFY_REGISTRY_TOKEN`) **auto-publishes** it; `comfy node publish --token <registry-PAT>` is the manual/local fallback. It is NOT auto-published on a library release (the node has its own version), so only bump it when the node code or its `remove-ai-watermarks>=` dependency floor changes.
@@ -33,4 +35,5 @@ The standing `uv-secure` gate in `maintain.sh` is clean; this is the changelog o
- **idna** bumped 3.11 -> 3.16, fixing GHSA-65pc-fj4g-8rjx.
- **aiohttp** bumped 3.13.5 -> 3.14.0 via `uv lock --upgrade-package aiohttp`, fixing GHSA-hg6j-4rv6-33pg + GHSA-jg22-mg44-37j8.
- **basicsr** Dependabot alert GHSA-86w8-vhw6-q9qq is resolved by removal: the experimental `restore` extra was retired and basicsr is no longer anywhere in the dependency tree.
- **torch** Dependabot alert **GHSA-rrmf-rvhw-rf47** (`torch.jit.script` memory corruption, vulnerable `<= 2.12.0`) is **dismissed as `not_used`** (2026-06-10): torch is a transitive dep of the optional `gpu` extra only, the codebase never calls `torch.jit` (grep-verified), and **no patched torch version exists** (`first_patched_version` is null), so it cannot be closed by an upgrade — do not re-triage it.
- **torch** Dependabot alert **GHSA-rrmf-rvhw-rf47** (`torch.jit.script` memory corruption, alert range `<= 2.12.1`) was dismissed `not_used` on 2026-06-10 (torch is a transitive dep of the optional `gpu` extra only and the codebase never calls `torch.jit`) and **resolved by upgrade on 2026-07-21**: the lock carries torch **2.13.0**, above the patched floor, so `uv-secure` is clean. If the GitHub alert has not auto-closed on the lock bump, close it manually as fixed.
- **setuptools** bumped 81.0.0 -> 83.0.0 (2026-07-21), fixing PYSEC-2026-3447.
File diff suppressed because it is too large. Load diff
+27
View File
@@ -52,3 +52,30 @@ Grok JPEG downloads (Aurora model) carry **no C2PA, no XMP, no SynthID, no IPTC*
**Visible-mark landscape beyond the registry.** Meta stamps a visible "Imagined with AI" mark (bottom-LEFT, a small symbol) on its OWN Meta AI / "Imagine" output; for third-party images it relies on C2PA / IPTC, not a visible mark. Samsung Galaxy AI additionally uses a **four-star icon** variant in a corner alongside the localized text wordmark `samsung_engine` calibrates (only the Italian text variant is covered) -- the icon is a distinct, uncovered variant. Every source agrees visible + metadata marks are trivially removable (crop / screenshot, ~2 s), which is the tool's premise.
**Regulatory driver -- China GB 45438-2025 is the strongest VISIBLE-mark mandate.** The CAC / TC260 "Measures for Labeling AI-Generated Synthesized Content" (issued March 2025, **effective 2025-09-01**, technical standard **GB 45438-2025**, building on the TC260 Aug-2023 practice guide) MANDATE a **visible** label for AI images -- a visible textual mark whose height must be **>= 5% of the image's shortest side** -- plus the metadata (implicit) label. So every major Chinese platform now ships visible "AI生成"-style text marks (we cover Doubao / Jimeng; expect more CJK-text marks under this driver). By contrast EU AI Act Article 50 mandates only the MACHINE-READABLE mark (enforceable 2026-08-02, grace to 2026-12-02); a visible label is proposed and modality-specific (visible for images) but is NOT a hard "fixed icon" mandate -- a claim that Art 50 requires a clearly-visible fixed icon for images was refuted in verification. Primary-source dates verified against the article/standard text, not search summaries.
## Uncovered visible marks: implementation specs (deep-research 2026-07-18)
Triggered by a corpus finding: **50% of TC260-labelled uploads (1452 of 2896 unique) produced no detection at all**, and hand-inspection showed the bulk are MISSED Doubao marks (a localization defect, now fixed -- see `scale_basis` in `docs/module-internals.md`) plus a minority of genuinely uncovered vendors. Verification status is labelled per claim; treat (b)/(c) as leads, not ground truth.
**GB 45438-2025 clause 5.2, the binding constraint for every Chinese mark (VERIFIED (a) -- full standard text extracted from the TC260-hosted PDF).** Verbatim requirements for an image's explicit label:
- 应采用文字提示 (must be a TEXT prompt);
- must contain BOTH an AI element (`人工智能` or `AI`) AND a generation element (`生成` and/or `合成`);
- 应位于图片的边或角 -- **edge OR corner**, so bottom-right is NOT mandated (Annex C.2's bottom-right figure is a non-normative example);
- 字型应清晰可辨 (legible typeface -- no family named);
- **文字高度不应低于画面最短边长度的 5%** -- glyph HEIGHT >= 5% of the frame's SHORTEST side, with a note defining the shortest side for non-rectangular images.
Two consequences we can exploit: (1) the 5% floor is a **scale prior** -- a compliant CN mark's glyphs are large (>= 51 px on a 1024² image), so a CN silhouette ladder can be anchored at ~5-10% of the short side instead of swept broadly, which should cut false fires; (2) every compliant string shares the tail `AI生成` / `AI合成`, so a shared suffix silhouette plus a per-vendor prefix may beat five independent templates. NOT established: whether 文字高度 means cap height, em box, or rendered bounding box (a ~1.3x spread in template scale). Sources: `https://www.tc260.org.cn/upload/2025-03-15/1742009439794081593.pdf`, parent CAC measure `https://www.cac.gov.cn/2025-03/14/c_1743654684782215.htm` (the CAC text itself specifies no size or corner).
**Alibaba Qwen -- two surfaces that differ (API tier VERIFIED (a)).** Model Studio docs state verbatim that the API adds a `Qwen-Image` watermark 在图像右下角 and 默认值为 false -- so API output is **unwatermarked by default**, and when enabled the mark is a LATIN wordmark, not CJK, and not GB-compliant in wording. The consumer app's `千问AI生成` (bottom-right) is (b) secondary only -- no Alibaba primary page states it. So Qwen needs TWO templates, and its absence is never evidence of a clean image. Source: `https://help.aliyun.com/zh/model-studio/qwen-image-api`.
**星绘 is ByteDance (VERIFIED (a): Baidu Baike + App Store listing, now branded 豆包旗下, team folded into Doubao April 2025).** So `星绘AI生成` is very likely the Doubao house style -- same typeface, same corner, possibly the same top-left `AI生成` pill. Starting from the Doubao `TextMarkConfig` and swapping the two lead glyphs is the cheap path. String/position themselves are (c) inferred.
**Baidu: RESOLVED 2026-07-22, registered (`baidu_engine.py`).** The mark is a white bold "百度" text run + a separate white rounded tag with dark "AI生成", bottom-right -- settled by the TC260 USCC cohort harvest (16 frames, USCC 91110000802100433B), not by web research. Detection keys on the text run only; details in `docs/module-internals.md`.
**Meta `Imagined with AI` (string VERIFIED (a) from Meta's own newsroom; POSITION NOT VERIFIED).** Sources conflict (bottom-left vs bottom-right) and one claims newer Meta models dropped the visible mark for invisible watermarking; none survived a fetch. Do NOT encode a corner without a corpus sample. Meta also embeds IPTC + invisible watermarks, which `identify` already reads. Source: `https://about.fb.com/news/2024/02/labeling-ai-generated-images-on-facebook-instagram-and-threads/`.
**Samsung English/other locales: still not established.** Samsung's own support page says only that "A Galaxy AI watermark will appear on AI-generated images" -- no string, no corner. Every community thread carrying the exact English string returned HTTP 403 to WebFetch, so the search paraphrase (bottom-left) is deliberately NOT recorded as fact. Feature-tier detail (b): the mark is applied by Generative Edit / sketch-to-image but reportedly NOT by Object Eraser, so Samsung absence is feature-dependent. The four-star icon variant: nothing found.
**The one document that would settle ByteDance placement is BLOCKED.** Douyin's 《抖音关于人工智能生成内容标识的水印与元数据规范》 aims to give AI tools a unified watermark style and position, which would cover Doubao / Jimeng / 星绘 at once. Both mirrors return HTTP 403 to WebFetch; a secondary report (b, unconfirmed) says the watermark is `AI生成` + tool name + company name placed **top-left** -- which would explain the Jimeng pill's top-left position but contradicts the GB annex's bottom-right example. Worth one retry through Chrome MCP with a real browser session.
**No vendor publishes typeface, colour, opacity, plate, or margin for ANY of these marks.** The only font-adjacent requirement anywhere is GB's "legible typeface". So each synthetic silhouette's font must be calibrated against corpus positives exactly as the Jimeng pill was; candidate CJK families by platform convention (inference): HarmonyOS Sans / Source Han Sans / Noto Sans CJK SC for Android-origin apps, PingFang SC for iOS-origin.
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "remove-ai-watermarks"
version = "0.15.0"
version = "0.19.0"
description = "AI watermark remover: strip visible and invisible AI watermarks (Gemini / Nano Banana sparkle, SynthID) and provenance metadata (C2PA, EXIF) from images"
readme = "README.md"
requires-python = ">=3.10"
+224
View File
@@ -0,0 +1,224 @@
"""AI-generation scorer for scanned datasets.
Trains a gradient-boosted classifier on the metadata-derived labels of a
scan_dataset.py output and scores every file, WITHOUT needing the
metadata to be present at scoring time: the features are pixel and
container statistics, so a metadata-stripped file still gets a score.
Measured on the production corpus (temporal holdout, honest for drift):
structural-feature GBM reaches AUC ~0.94-0.96 on-distribution. The model
is distribution-specific by design (it is trained on this service's
traffic); do not expect the same numbers on unrelated data. CLIP-ViT-L/14
features were evaluated as an alternative and scored lower (0.82) while
being ~30x slower, so the shipped model uses the structural features the
scanner already collects.
Modes:
uv run --with scikit-learn python scripts/ai_score.py train <scan_glob> <model.pkl>
uv run --with scikit-learn python scripts/ai_score.py score <scan_glob> <model.pkl> <out.jsonl>
<scan_glob> is a glob of scan_dataset shards, e.g. 'data/scan/part_*.jsonl'.
score output: one JSON line per file with file, sha256, ai_score, and the
label evidence when a metadata label existed (for monitoring drift).
"""
import glob
import json
import pickle
import sys
from pathlib import Path
from typing import Any
import numpy as np
# AI-generator names in C2PA claim_generator_info (metadata-level truth).
AI_GENERATORS = (
"openai",
"adobe firefly",
"adobe_firefly",
"microsoft responsible ai",
"microsoft_designer",
"black forest labs",
"fal-ai",
"bria",
"chatgpt",
"stability",
"dreamina",
"canva",
)
# Human-origin software (negative evidence, NOT proof by itself).
HUMAN_SOFTWARE = (
"photoshop",
"lightroom",
"picsart",
"snapseed",
"paint.net",
"gimp",
"capture one",
"meitu",
"xingtu",
"snow",
)
_FEAT_SCALAR = [
("noise", "noise_std"),
("noise", "noise_kurtosis"),
("fft", "cfa_peak"),
("ela", "ela_mean"),
("ela", "ela_p95"),
("gradient", "laplacian_var"),
("color", "saturation_mean"),
("color", "value_mean"),
("dct", "benford_mad"),
]
def label_of(record: dict[str, Any]) -> int | None:
"""1 = strong metadata AI, 0 = human-origin, None = unlabeled."""
store = record.get("c2pa_store") or {}
for m in (store.get("manifests") or {}).values():
for cgi in m.get("claim_generator_info") or []:
if any(g in str(cgi.get("name", "")).lower() for g in AI_GENERATORS):
return 1
for a in m.get("assertions") or []:
d = a.get("data") if isinstance(a.get("data"), dict) else {}
if "trainedAlgorithmicMedia" in str(d.get("digitalSourceType", "")):
return 1
for c in record.get("png_chunks", []):
t = c.get("text", "")
kw = t.split("\x00")[0]
if kw in ("prompt", "workflow", "parameters") or "AIGC" in t[:80]:
return 1
exif = record.get("exif", {})
z = exif.get("0th") or {}
e = exif.get("Exif") or {}
if z.get("Make") and z.get("Model") and (e.get("MakerNote") or e.get("LensModel") or e.get("LensMake")):
return 0
for c in record.get("png_chunks", []):
if c.get("apple_screenshot_marker"):
return 0
for v in (record.get("iptc") or {}).values():
if str(v).strip() == "Screenshot":
return 0
if any(t in str(z.get("Software", "")).lower() for t in HUMAN_SOFTWARE):
return 0
return None
def features_of(record: dict[str, Any]) -> list[float]:
"""The structural feature vector (pixel + container stats, no metadata)."""
v = [float((record.get(s) or {}).get(k, np.nan)) for s, k in _FEAT_SCALAR]
for b in (record.get("fft") or {}).get("fft_band_energy", []):
v.append(float(b))
for h in (record.get("gradient") or {}).get("gradient_hist", []):
v.append(float(h))
for h in (record.get("color") or {}).get("color_hist_4x4x4", []):
v.append(float(h))
jf = record.get("jpeg_forensics") or {}
v.append(1.0 if jf.get("subsampling") == "4:4:4" else 0.0)
v.append(1.0 if jf.get("progressive") else 0.0)
pil = record.get("pil") or {}
w, h = pil.get("width") or 0, pil.get("height") or 0
v += [float(w * h) / 1e6, float(w) / max(h, 1)]
fmt = record.get("content_format")
v += [1.0 if fmt == "jpeg" else 0.0, 1.0 if fmt == "png" else 0.0]
return v
def iter_records(pattern: str) -> Any:
for path in sorted(glob.glob(pattern)):
with open(path) as fh:
for line in fh:
yield json.loads(line)
def cmd_train(pattern: str, model_path: str) -> None:
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.impute import SimpleImputer
from sklearn.metrics import average_precision_score, roc_auc_score
from sklearn.model_selection import train_test_split
X, y, dates = [], [], []
for r in iter_records(pattern):
if "noise" not in r:
continue
lab = label_of(r)
if lab is None:
continue
X.append(features_of(r))
y.append(lab)
dates.append(Path(r["file"]).parent.name)
X, y = np.array(X), np.array(y)
print(f"labeled: {len(y)} (pos {int(y.sum())}, neg {int((1 - y).sum())}, features {X.shape[1]})")
Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)
imp = SimpleImputer(strategy="median").fit(Xtr)
clf = HistGradientBoostingClassifier(random_state=0, max_iter=300)
clf.fit(imp.transform(Xtr), ytr)
p = clf.predict_proba(imp.transform(Xte))[:, 1]
print(f"holdout: AUC {roc_auc_score(yte, p):.4f} | AP {average_precision_score(yte, p):.4f}")
uniq = sorted(set(dates))
cutoff = uniq[int(len(uniq) * 0.7)]
tr = np.array([d < cutoff for d in dates])
if tr.sum() > 100 and (~tr).sum() > 100:
clf_t = HistGradientBoostingClassifier(random_state=0, max_iter=300)
imp_t = SimpleImputer(strategy="median").fit(X[tr])
clf_t.fit(imp_t.transform(X[tr]), y[tr])
pt = clf_t.predict_proba(imp_t.transform(X[~tr]))[:, 1]
auc_t = roc_auc_score(y[~tr], pt)
ap_t = average_precision_score(y[~tr], pt)
print(f"temporal (<{cutoff}): AUC {auc_t:.4f} | AP {ap_t:.4f}")
imp = SimpleImputer(strategy="median").fit(X)
clf = HistGradientBoostingClassifier(random_state=0, max_iter=300)
clf.fit(imp.transform(X), y)
with open(model_path, "wb") as f:
pickle.dump({"imputer": imp, "clf": clf}, f)
print(f"model written: {model_path}")
def cmd_score(pattern: str, model_path: str, out_path: str) -> None:
# the model file is produced locally by `train`; do not load third-party pickles
with open(model_path, "rb") as f:
bundle = pickle.load(f) # noqa: S301
imp, clf = bundle["imputer"], bundle["clf"]
n = 0
with open(out_path, "w") as out:
for r in iter_records(pattern):
if "noise" not in r:
continue
score = float(clf.predict_proba(imp.transform([features_of(r)]))[0, 1])
lab = label_of(r)
out.write(
json.dumps(
{
"file": r["file"],
"sha256": r.get("sha256"),
"ai_score": round(score, 4),
"metadata_label": lab,
}
)
+ "\n"
)
n += 1
if n % 5000 == 0:
print(f" {n}", flush=True)
print(f"scored {n} -> {out_path}")
def main() -> None:
if len(sys.argv) < 2 or sys.argv[1] not in ("train", "score"):
print(__doc__)
sys.exit(2)
if sys.argv[1] == "train" and len(sys.argv) == 4:
cmd_train(sys.argv[2], sys.argv[3])
elif sys.argv[1] == "score" and len(sys.argv) == 5:
cmd_score(sys.argv[2], sys.argv[3], sys.argv[4])
else:
print(__doc__)
sys.exit(2)
if __name__ == "__main__":
main()
+272
View File
@@ -0,0 +1,272 @@
"""Can one GENERIC template cover the CJK AI labels no per-vendor detector fires on?
THE OPPORTUNITY
Corpus inspection of doubao-provenance misses turned up `千问AI生成` (Alibaba Qwen) and
`百度 AI生成` (Baidu) sitting in the same bottom-right corner as the marks we do cover,
bold and plainly legible, with no detector able to fire on either. `docs/...landscape`
puts uncovered vendors at ~6% of sampled images -- larger than any tuning gain left in
the covered ones (a dense scale ladder recovers 1 miss in 26; see ladder_headroom.py).
WHY A SHARED TEMPLATE IS EVEN PLAUSIBLE
China's GB 45438-2025 mandates the label, and every compliant vendor ends it with the
same run: `AI生成`. The vendor PREFIX varies (豆包 / 千问 / 百度 / 星绘) and is what makes
per-vendor silhouettes expensive; the TAIL is guaranteed. So the tail is the part worth
detecting, and vendor attribution -- which the shared tail cannot provide anyway
(measured 千问-vs-doubao AUC ~0.5) -- moves to metadata, where it is reliable.
WHY IT IS WORTH RETRYING NOW
`render_vendor_silhouettes.py` records 千问 as ruled out, and its reasoning was sound:
the then-current front-end binarized the glyph, and a thin translucent overlay shatters
into specks that no template can match. It closes by naming what would be needed --
"a detection front-end that does not depend on binarizing the glyph (grayscale/edge
correlation on the raw top-hat)". That front-end now EXISTS: `detect_frontend="tophat"`
was built for doubao and correlates a soft template against the continuous response.
The blocker was removed by unrelated work, so the ruling deserves re-measurement rather
than inheritance.
THE MEASUREMENT
Three arms, one scorer (the tail template on the tophat response, swept over a dense
size ladder because an unregistered vendor's glyph size is genuinely unknown -- the one
place a dense ladder earns its cost):
covered a registered mark already fires -- a sanity arm; the tail is inside those
marks too, so a tail template that cannot score THESE is simply broken
uncovered TC260 provenance but no detector fires -- the target population
clean no metadata signal at all -- the precision arm
The decision rests on whether `uncovered` carries a high-scoring subpopulation that
`clean` does not. It does NOT rest on the raw rate: TC260 provenance does not imply a
visible mark, so a modest fire rate on that arm is expected even if the detector is
perfect. Any threshold this suggests must then be confirmed by eyeballing the crops it
selects -- the script writes a contact sheet for exactly that.
DATA SAFETY
Corpus images are user uploads: read-only, local analysis, gitignored output. The
template is font-rendered synthetic, never cut from a user upload.
uv run python scripts/cjk_tail_probe.py --n 6000
"""
from __future__ import annotations
import argparse
import glob
import json
import os
import random
import sys
from concurrent.futures import ProcessPoolExecutor, as_completed
from pathlib import Path
from typing import Any
import cv2
import numpy as np
sys.path.insert(0, str(Path(__file__).parent.parent))
sys.path.insert(0, str(Path(__file__).parent))
REPO = Path(__file__).resolve().parents[1]
CORPUS = REPO / "data" / "spaces" / "originals"
OUT = REPO / "data" / "spaces" / "_cjk_tail_probe.jsonl"
# Cached under the gitignored data dir, not in scripts/: this is a probe artifact, not a
# product asset. If the tail mark is ever registered, `render_vendor_silhouettes.py` is
# what writes the committed silhouette into src/.../assets/.
TAIL_PNG = REPO / "data" / "spaces" / "_cjk_tail_silhouette.png"
# The tail is a fraction of a full vendor mark's width (`豆包AI生成` is ~5 CJK widths,
# `AI生成` ~3), and the prefix length differs per vendor, so the size is genuinely
# unknown here -- unlike a registered mark, whose fraction is calibrated. Hence a wide,
# dense ladder: this is the case a dense ladder is actually for.
TAIL_SCALES = tuple(round(0.30 * (1.08**i), 4) for i in range(18)) # ~0.30 .. ~1.15
def build_tail_silhouette() -> np.ndarray:
"""Font-rendered `AI生成` silhouette, cached next to this script (data-safe)."""
if TAIL_PNG.exists():
img = cv2.imread(str(TAIL_PNG), cv2.IMREAD_GRAYSCALE)
if img is not None:
return img
from render_vendor_silhouettes import render
sil = render("AI生成", width=200)
cv2.imwrite(str(TAIL_PNG), sil)
return sil
def tail_score(engine: Any, image: np.ndarray, sil: np.ndarray) -> tuple[float, float]:
"""Best tail correlation over the size ladder; returns (score, winning_scale)."""
loc = engine.locate(image)
resp = engine.tophat_response(image, loc)
if resp is None:
return (0.0, 0.0)
c = engine.config
base = engine.scale_base(image)
ar = sil.shape[0] / max(1, sil.shape[1])
best, best_s = 0.0, 0.0
for s in TAIL_SCALES:
gw = max(12, int(c.alpha_width_frac * base * s))
gh = max(6, int(gw * ar))
if gw >= resp.shape[1] or gh >= resp.shape[0]:
continue
t = cv2.resize(sil, (gw, gh), interpolation=cv2.INTER_AREA)
v = float(cv2.matchTemplate(resp, t, cv2.TM_CCOEFF_NORMED).max())
if v > best:
best, best_s = v, s
return (best, best_s)
def _one(path_str: str) -> dict[str, Any] | None:
from remove_ai_watermarks.api import visible_provenance
from remove_ai_watermarks.doubao_engine import DoubaoEngine
from remove_ai_watermarks.identify import identify
from remove_ai_watermarks.image_io import imread
from remove_ai_watermarks.watermark_registry import detect_marks
path = Path(path_str)
try:
prov = visible_provenance(path)
except Exception:
return None
tc260 = bool({"doubao", "jimeng"} & prov)
if not tc260:
try:
if identify(path, check_visible=False).signals:
return None # some other provenance: neither target nor clean control
except Exception:
return None
img = imread(path_str)
if img is None or min(img.shape[:2]) < 200:
return None
try:
fired = [d.key for d in detect_marks(img) if d.detected]
except Exception:
return None
if fired:
arm = "covered"
elif tc260:
arm = "uncovered"
else:
arm = "clean"
score, scale = tail_score(DoubaoEngine(), img, build_tail_silhouette())
return {
"src": path.name,
"arm": arm,
"fired": fired,
"tail_score": round(score, 4),
"tail_scale": scale,
}
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--n", type=int, default=6000)
ap.add_argument("--workers", type=int, default=max(1, (os.cpu_count() or 4) - 2))
ap.add_argument("--out", type=Path, default=OUT)
ap.add_argument("--report-only", action="store_true")
ap.add_argument(
"--sheet-at", type=float, default=0.0, help="write a contact sheet of `uncovered` crops scoring >= this"
)
a = ap.parse_args()
if a.report_only:
rows = [json.loads(x) for x in a.out.read_text(encoding="utf-8").splitlines() if x.strip()]
report(rows)
if a.sheet_at:
contact_sheet(rows, a.sheet_at)
return
build_tail_silhouette()
pool = glob.glob(str(CORPUS / "*" / "*"))
random.Random(19).shuffle(pool) # noqa: S311 -- deterministic sampling, not crypto
pool = pool[: a.n]
print(f"scanning {len(pool)} corpus files workers={a.workers}")
print(f"tail ladder {TAIL_SCALES[0]} .. {TAIL_SCALES[-1]} ({len(TAIL_SCALES)} rungs)\n", flush=True)
rows: list[dict[str, Any]] = []
a.out.parent.mkdir(parents=True, exist_ok=True)
with open(a.out, "w", encoding="utf-8") as fh, ProcessPoolExecutor(max_workers=a.workers) as ex:
futures = [ex.submit(_one, p) for p in pool]
for i, fut in enumerate(as_completed(futures), 1):
try:
rec = fut.result()
except Exception: # noqa: S112 -- one bad file must not kill the sweep
continue
if rec is None:
continue
fh.write(json.dumps(rec) + "\n")
rows.append(rec)
if i % 500 == 0:
fh.flush()
print(f" {i}/{len(pool)} usable={len(rows)}", flush=True)
report(rows)
if a.sheet_at:
contact_sheet(rows, a.sheet_at)
def report(rows: list[dict[str, Any]]) -> None:
arms = {k: [r for r in rows if r["arm"] == k] for k in ("covered", "uncovered", "clean")}
print(f"\n{'=' * 80}\nGENERIC CJK TAIL PROBE ({', '.join(f'{k}={len(v)}' for k, v in arms.items())})\n{'=' * 80}")
print("\nScore distribution of the shared `AI生成` tail on the tophat response\n")
print(f"{'arm':11s} {'n':>6s} {'p50':>7s} {'p75':>7s} {'p90':>7s} {'p95':>7s} {'p99':>7s} {'max':>7s}")
for k, v in arms.items():
if not v:
continue
s = np.array([r["tail_score"] for r in v])
qs = [np.percentile(s, q) for q in (50, 75, 90, 95, 99)]
print(f"{k:11s} {len(v):6d} " + " ".join(f"{q:7.3f}" for q in qs) + f" {s.max():7.3f}")
if arms["clean"] and arms["uncovered"]:
clean = np.array([r["tail_score"] for r in arms["clean"]])
unc = np.array([r["tail_score"] for r in arms["uncovered"]])
print("\n\nOPERATING POINTS -- threshold set on the CLEAN arm, yield read on `uncovered`")
print("`clean` fires are the cost; `uncovered` fires are candidate recoveries that")
print("still need eyeballing, since TC260 provenance does not imply a visible mark.\n")
print(f"{'threshold':>10s} {'clean fire':>12s} {'uncovered fire':>16s} {'candidates':>12s}")
for q in (95, 97.5, 99, 99.5, 99.9):
t = float(np.percentile(clean, q))
cf = float((clean >= t).mean())
uf = float((unc >= t).mean())
print(f"{t:10.3f} {100 * cf:11.2f}% {100 * uf:15.1f}% {int((unc >= t).sum()):12d}")
cov = arms["covered"]
if cov:
s = np.array([r["tail_score"] for r in cov])
print(f"\n\nSANITY: on frames where a registered mark fires, the tail scores median {np.median(s):.3f}.")
print("A tail template that cannot score these is broken, whatever it does elsewhere.")
def contact_sheet(rows: list[dict[str, Any]], thresh: float, limit: int = 30) -> None:
"""Crop the corner of the top-scoring `uncovered` frames so the fires can be judged."""
from remove_ai_watermarks.doubao_engine import DoubaoEngine
from remove_ai_watermarks.image_io import imread
eng = DoubaoEngine()
picks = sorted(
(r for r in rows if r["arm"] == "uncovered" and r["tail_score"] >= thresh),
key=lambda r: -r["tail_score"],
)[:limit]
tiles = []
for r in picks:
hits = glob.glob(str(CORPUS / "*" / r["src"]))
if not hits:
continue
img = imread(hits[0])
if img is None:
continue
loc = eng.locate(img)
crop = img[loc.y : loc.y + loc.h, loc.x : loc.x + loc.w]
if crop.size:
tiles.append(cv2.resize(crop, (320, 96), interpolation=cv2.INTER_AREA))
if tiles:
dest = REPO / "data" / "spaces" / "_cjk_tail_sheet.png"
cv2.imwrite(str(dest), np.vstack(tiles))
print(f"\ncontact sheet ({len(tiles)} crops, score >= {thresh:.3f}) -> {dest}")
print("scores: " + ", ".join(f"{r['tail_score']:.2f}" for r in picks[: len(tiles)]))
if __name__ == "__main__":
main()
+319
View File
@@ -0,0 +1,319 @@
"""Tier B2: detector response curves -- recall vs mark size, contrast, background and aspect.
WHY THIS EXISTS
Every recall number the project quotes rests on found positives: doubao 89% on n=240,
jimeng 71% on n=14, the pill 50% on n=6. Those tell you how the detectors do on the
marks a corpus happened to contain, and nothing about WHERE they fall over. Two bugs
have now shipped in exactly that blind spot:
* `scale_basis` -- doubao detected 0 of 435 LANDSCAPE marks, a 100% miss, because
every fraction was calibrated on portrait captures where width == short side.
* the front-end mismatch -- detection moved to the continuous `tophat` response while
the removal mask still came from the BINARIZED blob, so ~8% of doubao detections
produced an empty mask and removal was a silent no-op.
Both are geometry/plumbing failures at the edge of the operating range, and both were
invisible to a corpus sweep because the corpus is concentrated in the middle of it.
This harness constructs the edges instead of waiting for them to turn up.
THE AGGREGATE HERE IS NOT RECALL
The grid deliberately visits sizes and opacities the engines were never calibrated for,
so a mark counted as missed at size=0.6 is not evidence of a weak detector -- it is the
point of the sweep. Quote the NOMINAL cell (size=1.0, alpha=1.0) as the reference, and
read the per-axis tables for shape. Production recall comes from an unbiased corpus
sample (`scripts/visible_recall_sample.py`), never from here.
WHAT IT MEASURES -- TWO NUMBERS, NOT ONE
`detected` the detector fires.
`maskable` the same call path then yields a NON-EMPTY removal mask.
The second is the one that has no natural home anywhere else. A mark that is detected
but not maskable is reported by `identify` and silently skipped by `visible` -- the user
sees a mark the tool says it removed. Anything that measures only detection scores that
bug as a success. They are reported side by side and their GAP is the headline.
THE CONSTRUCTION
Take a verified-clean corpus image, stamp a real mark onto it with the forward model the
reverse-alpha work established (`stamped = (1-a)*bg + a*white`), and sweep two knobs the
engine's own geometry normally pins:
size multiplies the glyph box the engine would use (a re-rendered or rescaled mark)
alpha multiplies the captured opacity (bold stamp -> faint translucent overlay)
Background texture and frame aspect are not swept -- they come from the corpus and are
recorded, so the grid is crossed with real backgrounds rather than synthetic flats.
WHY EVERY SOURCE ALSO RUNS UNSTAMPED
A recall curve with no false-fire baseline is uninterpretable in the same way a fill
PSNR with no damage baseline is: "detected on 70% of faint marks" is a triumph or a
scandal depending on whether the detector also fires on 70% of the clean frames those
marks were stamped onto. The control runs the identical call path on the identical
image with no stamp.
READING `mask_hit`
Fraction of the stamped glyph box the removal mask covers -- real localization accuracy
for the text marks and gemini, because the mask has to be placed from a detection.
For `jimeng_pill` it is CONSTRUCTED and means nothing: the pill's footprint is a fixed
top-left geometry box, so it covers the stamp by definition. Reported, and flagged.
DATA SAFETY
Corpus images are user uploads: read-only, local analysis, gitignored output under
data/spaces/. Records source filenames and measurements, never image content.
uv run python scripts/detector_response.py --n 12 # trial, measures throughput
uv run python scripts/detector_response.py --n 150 # the real run, resumable
"""
from __future__ import annotations
import argparse
import collections
import json
import math
import os
import sys
from concurrent.futures import ProcessPoolExecutor, as_completed
from pathlib import Path
from typing import Any
import numpy as np
sys.path.insert(0, str(Path(__file__).parent.parent))
sys.path.insert(0, str(Path(__file__).parent))
from fill_quality import SLOT_STAMPABLE, STAMPABLE, clean_sources, stamp_any, texture_of
REPO = Path(__file__).resolve().parents[1]
OUT = REPO / "data" / "spaces" / "_detector_response.jsonl"
# 1.0 = the geometry/opacity the engine's own constants assume. The sweep reaches below
# it (a mark rendered smaller, or a faint translucent overlay -- the class the tophat
# front-end was introduced for) and above it (a larger re-render, or an upscaled upload).
SIZES = (0.6, 0.8, 1.0, 1.3)
ALPHAS = (0.3, 0.5, 0.75, 1.0)
MARKS = (*STAMPABLE, *SLOT_STAMPABLE)
def aspect_of(image: np.ndarray) -> str:
h, w = image.shape[:2]
r = w / max(1, h)
return "portrait" if r < 0.9 else ("landscape" if r > 1.1 else "square")
def _probe(image: np.ndarray, mark_key: str, box: tuple[int, int, int, int] | None) -> dict[str, Any]:
"""Run the product detect -> localize path once and score it.
``box`` is the stamped glyph box, or None for the unstamped control.
"""
from remove_ai_watermarks.watermark_registry import get_mark
mark = get_mark(mark_key)
loc = mark.localize(image, force=False)
mask_px = 0 if loc.mask is None else int(np.count_nonzero(loc.mask))
hit = None
if box is not None and loc.mask is not None:
x, y, w, h = box
inside = loc.mask[y : y + h, x : x + w]
hit = round(float(np.count_nonzero(inside)) / max(1, w * h), 3)
return {
"detected": bool(loc.detected),
"confidence": round(float(loc.confidence), 4),
"maskable": mask_px > 0,
"mask_px": mask_px,
"mask_hit": hit,
}
def _one_source(path_str: str) -> list[dict[str, Any]]:
"""Every (mark, size, alpha) cell for one clean background, plus its controls."""
from remove_ai_watermarks.image_io import imread
base = imread(path_str)
if base is None:
return []
name = Path(path_str).name
asp = aspect_of(base)
h, w = base.shape[:2]
rows: list[dict[str, Any]] = []
for key in MARKS:
common = {"src": name, "mark": key, "aspect": asp, "px": w * h}
# Control first: the same call path on the same frame with nothing stamped.
rows.append({**common, "cell": "control", "size": None, "alpha": None, **_probe(base, key, None)})
for size in SIZES:
for alpha in ALPHAS:
st = stamp_any(base, key, size_mult=size, alpha_mult=alpha)
if st is None:
continue
stamped, box = st
# Texture of the region the mark sits on, from the CLEAN frame -- the
# same median-Sobel proxy the pill's flatness gate uses.
x, y, gw, gh = box
rows.append(
{
**common,
"cell": "stamped",
"size": size,
"alpha": alpha,
"texture": round(texture_of(base[y : y + gh, x : x + gw]), 2),
**_probe(stamped, key, box),
}
)
return rows
def wilson(k: int, n: int, z: float = 1.96) -> tuple[float, float]:
if n == 0:
return (0.0, 0.0)
p, d = k / n, 1 + z * z / n
c = (p + z * z / (2 * n)) / d
hw = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d
return (100 * (c - hw), 100 * (c + hw))
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--n", type=int, default=150, help="verified-clean source images")
ap.add_argument("--workers", type=int, default=max(1, (os.cpu_count() or 4) - 2))
ap.add_argument("--out", type=Path, default=OUT)
ap.add_argument("--restart", action="store_true")
ap.add_argument("--report-only", action="store_true", help="re-read --out and print the report")
a = ap.parse_args()
if a.report_only:
rows = [json.loads(line) for line in a.out.read_text(encoding="utf-8").splitlines() if line.strip()]
report(rows)
return
if a.restart and a.out.exists():
a.out.unlink()
done: set[str] = set()
if a.out.exists():
with open(a.out, encoding="utf-8") as fh:
for line in fh:
try:
done.add(json.loads(line)["src"])
except Exception: # noqa: S112 -- tolerate a torn last line
continue
print(f"selecting {a.n} verified-clean sources (already measured: {len(done)})...", flush=True)
sources = [p for p in clean_sources(a.n) if p.name not in done]
print(f"to do {len(sources)} workers {a.workers} grid {len(MARKS)}x{len(SIZES)}x{len(ALPHAS)}\n", flush=True)
rows: list[dict[str, Any]] = []
a.out.parent.mkdir(parents=True, exist_ok=True)
with open(a.out, "a", encoding="utf-8") as fh, ProcessPoolExecutor(max_workers=a.workers) as ex:
futures = {ex.submit(_one_source, str(p)): p for p in sources}
for i, fut in enumerate(as_completed(futures), 1):
try:
got = fut.result()
except Exception as e: # a crashed source must not kill the sweep
print(f" source failed: {type(e).__name__}: {e}", flush=True)
continue
for r in got:
fh.write(json.dumps(r) + "\n")
rows += got
if i % 10 == 0:
fh.flush()
print(f" {i}/{len(sources)}", flush=True)
if done: # merge the resumed rows so the report covers the whole file
rows = [json.loads(line) for line in a.out.read_text(encoding="utf-8").splitlines() if line.strip()]
report(rows)
def _rate(rs: list[dict[str, Any]], field: str) -> tuple[float, float, float, int]:
k, n = sum(bool(r[field]) for r in rs), len(rs)
lo, hi = wilson(k, n)
return (100 * k / n if n else 0.0, lo, hi, n)
def report(rows: list[dict[str, Any]]) -> None:
stamped = [r for r in rows if r["cell"] == "stamped"]
control = [r for r in rows if r["cell"] == "control"]
if not stamped:
print("no measurements")
return
srcs = len({r["src"] for r in rows})
print(f"\n{'=' * 84}\nDETECTOR RESPONSE {len(stamped)} stamped cells over {srcs} clean backgrounds\n{'=' * 84}")
# Lead with the nominal cell. The grid deliberately includes sizes and opacities the
# engines were never calibrated for, so an aggregate over the whole grid is an
# adversarial score, NOT production recall -- quoting it as recall would understate
# the detectors badly. The nominal cell is the honest reference point: the mark at the
# exact geometry and opacity the engine assumes, on a real clean background.
print("\nNOMINAL CELL (size=1.0, alpha=1.0) -- a mark exactly as the engine expects it.")
print("Read every other number against THIS, not as production recall: the grid is")
print("adversarial by design and its aggregate is not a recall figure.\n")
print(f"{'mark':13s} {'n':>5s} {'detected':>10s} {'maskable':>10s}")
for key in MARKS:
rs = [r for r in stamped if r["mark"] == key and r["size"] == 1.0 and r["alpha"] == 1.0]
if rs:
print(f"{key:13s} {len(rs):5d} {_rate(rs, 'detected')[0]:9.1f}% {_rate(rs, 'maskable')[0]:9.1f}%")
print("\n\nFALSE FIRE on the unstamped controls (the baseline every recall below is read against)\n")
print(f"{'mark':13s} {'n':>5s} {'fires':>8s} {'95% CI':>16s}")
for key in MARKS:
rs = [r for r in control if r["mark"] == key]
if rs:
pct, lo, hi, n = _rate(rs, "detected")
print(f"{key:13s} {n:5d} {pct:7.1f}% {f'{lo:.1f}-{hi:.1f}':>16s}")
print("\n\nDETECTED vs MASKABLE by mark. The GAP is the silent-no-op rate:")
print("a mark counted here as detected-but-not-maskable is reported by `identify` and")
print("skipped by `visible`, so the user is told it was removed when it was not.\n")
print(f"{'mark':13s} {'n':>6s} {'detected':>10s} {'maskable':>10s} {'gap':>7s} {'mask_hit':>9s}")
for key in MARKS:
rs = [r for r in stamped if r["mark"] == key]
if not rs:
continue
det = [r for r in rs if r["detected"]]
d, m = _rate(rs, "detected")[0], _rate(rs, "maskable")[0]
gap = (100 * sum(1 for r in det if not r["maskable"]) / len(det)) if det else 0.0
hits = [r["mask_hit"] for r in det if r["mask_hit"] is not None]
note = " (constructed)" if key == "jimeng_pill" else ""
hv = f"{float(np.median(hits)):.2f}" if hits else "-"
print(f"{key:13s} {len(rs):6d} {d:9.1f}% {m:9.1f}% {gap:6.1f}% {hv:>9s}{note}")
for axis, label in (("alpha", "CONTRAST (alpha multiplier)"), ("size", "SIZE (glyph box multiplier)")):
print(f"\n\nRECALL BY {label} -- 1.0 is the geometry/opacity the engine assumes\n")
vals = sorted({r[axis] for r in stamped})
print(f"{'mark':13s}" + "".join(f"{v:>12}" for v in vals))
for key in MARKS:
cells = []
for v in vals:
rs = [r for r in stamped if r["mark"] == key and r[axis] == v]
cells.append(f"{_rate(rs, 'detected')[0]:10.0f}%" if rs else f"{'-':>11s}")
print(f"{key:13s}" + "".join(f"{c:>12}" for c in cells))
print("\n\nRECALL BY FRAME ASPECT -- the axis the `scale_basis` bug lived on\n")
asps = ["portrait", "square", "landscape"]
print(f"{'mark':13s}" + "".join(f"{x:>14s}" for x in asps))
for key in MARKS:
cells = []
for asp in asps:
rs = [r for r in stamped if r["mark"] == key and r["aspect"] == asp]
cells.append(f"{_rate(rs, 'detected')[0]:.0f}% (n={len(rs)})" if rs else "-")
print(f"{key:13s}" + "".join(f"{c:>14s}" for c in cells))
tex = sorted(r["texture"] for r in stamped if "texture" in r)
if tex:
t1, t2 = tex[len(tex) // 3], tex[2 * len(tex) // 3]
print(f"\n\nRECALL BY BACKGROUND TEXTURE (terciles at {t1:.1f} / {t2:.1f} median-Sobel)\n")
print(f"{'mark':13s}" + "".join(f"{x:>14s}" for x in ("flat", "mid", "textured")))
for key in MARKS:
cells = []
for lo, hi in ((-1, t1), (t1, t2), (t2, 1e9)):
rs = [r for r in stamped if r["mark"] == key and lo < r.get("texture", -2) <= hi]
cells.append(f"{_rate(rs, 'detected')[0]:.0f}% (n={len(rs)})" if rs else "-")
print(f"{key:13s}" + "".join(f"{c:>14s}" for c in cells))
worst = collections.Counter((r["mark"], r["size"], r["alpha"]) for r in stamped if not r["detected"]).most_common(8)
if worst:
print("\n\nWORST CELLS (most misses)\n")
for (mark, size, alpha), n in worst:
print(f" {mark:13s} size={size} alpha={alpha} {n} misses")
if __name__ == "__main__":
main()
+345
View File
@@ -0,0 +1,345 @@
"""Tier B1: measure visible-mark FILL quality against a constructed ground truth.
THE PROBLEM THIS SOLVES
A real watermarked image has no clean counterpart, so fill quality has only ever been
eyeballed ("cv2 smears on texture, LaMa is best") and never carried a number. The docs
state a preference order for `--backend auto` that rests on no measurement.
THE CONSTRUCTION
Take a VERIFIED-CLEAN corpus image, stamp a known mark onto it using the mark's own
captured alpha map (the forward model the reverse-alpha work established:
`stamped = (1-a)*bg + a*white`), then remove it and compare against the TRUE original.
The original is the answer key that reality never provides.
TWO MEASUREMENT DECISIONS THAT MAKE OR BREAK THIS
* Score INSIDE the footprint only. The fill touches a tiny corner, so whole-frame PSNR
sits near 60 dB whatever the backend does and would rank them all "excellent".
* Report the DAMAGE baseline (stamped vs original) next to the recovery (filled vs
original). Without it a PSNR is uninterpretable: 30 dB is a triumph if the mark cost
12 dB and a failure if it cost 29 dB. The honest metric is how much of the gap the
fill closes.
WHAT IT DOES NOT MEASURE
Detection. The mark is localized with `force=True`, so a miss cannot contaminate the
fill numbers -- this isolates the FILL. Detection accuracy is Tier C's job.
DATA SAFETY
Corpus images are user uploads: read-only, local analysis, output under a gitignored
data/spaces/ path. No image content is written into the report.
uv run python scripts/fill_quality.py --n 60
"""
from __future__ import annotations
import argparse
import collections
import glob
import json
import random
import sys
from pathlib import Path
from typing import Any
import cv2
import numpy as np
sys.path.insert(0, str(Path(__file__).parent.parent))
sys.path.insert(0, str(Path(__file__).parent))
from invisible_quality_audit import _ssim # reuse, do not reimplement a third SSIM
REPO = Path(__file__).resolve().parents[1]
CORPUS = REPO / "data" / "spaces" / "originals"
OUT = REPO / "data" / "spaces" / "_fill_quality.jsonl"
# Text marks: a bundled alpha PNG plus the engine's own corner geometry.
STAMPABLE = ("doubao", "jimeng", "samsung")
# Marks with no bundled alpha asset. Both expose a default footprint via
# `footprint_mask(force=True)`, so they are stamped by fitting their own alpha source
# into that slot: Gemini's alpha is derived from its background captures, the pill's
# from its synthetic font-rendered silhouette.
SLOT_STAMPABLE = ("gemini", "jimeng_pill")
def psnr(a: np.ndarray, b: np.ndarray) -> float:
mse = float(np.mean((a.astype(np.float64) - b.astype(np.float64)) ** 2))
return float("inf") if mse == 0 else 10 * float(np.log10(255.0**2 / mse))
def texture_of(box: np.ndarray) -> float:
"""Median Sobel magnitude -- the same texture proxy the pill's flatness gate uses."""
g = cv2.cvtColor(box, cv2.COLOR_BGR2GRAY) if box.ndim == 3 else box
gx = cv2.Sobel(g, cv2.CV_32F, 1, 0, ksize=3)
gy = cv2.Sobel(g, cv2.CV_32F, 0, 1, ksize=3)
return float(np.median(cv2.magnitude(gx, gy)))
def engine_for(mark_key: str) -> Any:
"""The TextMarkEngine instance for a mark key (the registry does not expose one)."""
import importlib
mod = importlib.import_module(f"remove_ai_watermarks.{mark_key}_engine")
cls = next(
obj
for name, obj in vars(mod).items()
# Exclude the imported base class: it takes a `config` arg, the subclasses do not.
if isinstance(obj, type) and name.endswith("Engine") and name != "TextMarkEngine"
)
return cls()
def composite(image: np.ndarray, alpha: np.ndarray, x: int, y: int) -> np.ndarray:
"""The single forward model every stamp uses: ``stamped = (1-a)*bg + a*white``.
``alpha`` is float and clipped to [0,1] here, so a caller may pre-multiply it by an
opacity factor without worrying about overflow. Shared by ``stamp``/``stamp_slot``
here and by ``scripts/detector_response.py`` (which imports it) so the model is
written ONCE.
"""
gh, gw = alpha.shape[:2]
out = image.copy()
roi = out[y : y + gh, x : x + gw].astype(np.float32)
a3 = np.clip(alpha, 0.0, 1.0)[..., None]
out[y : y + gh, x : x + gw] = np.clip(roi * (1 - a3) + 255.0 * a3, 0, 255).astype(np.uint8)
return out
def stamp(
image: np.ndarray, mark_key: str, *, size_mult: float = 1.0, alpha_mult: float = 1.0
) -> tuple[np.ndarray, tuple[int, int, int, int]] | None:
"""Composite a mark's alpha glyph into its canonical corner. Returns (stamped, bbox).
``size_mult`` scales the glyph box off the engine's nominal geometry and ``alpha_mult``
its opacity -- both default to 1.0 (the geometry the engine assumes), and
`scripts/detector_response.py` sweeps them to build response curves.
"""
from remove_ai_watermarks._text_mark_engine import load_alpha_template
engine = engine_for(mark_key)
cfg = engine.config
alpha = load_alpha_template(cfg.asset_name)
if alpha is None:
return None
loc = engine.locate(image)
base = engine.scale_base(image)
gw = max(cfg.min_gw, int(cfg.alpha_width_frac * base * size_mult))
gh = max(4, int(cfg.alpha_height_frac * base * size_mult))
if gw < 8 or gh < 4 or gw > loc.w or gh > loc.h:
return None
a = cv2.resize(alpha, (gw, gh), interpolation=cv2.INTER_AREA).astype(np.float32) * alpha_mult
x = loc.x + (loc.w - gw) // 2
y = loc.y + (loc.h - gh) // 2
return composite(image, a, x, y), (x, y, gw, gh)
def _slot_alpha(mark_key: str) -> np.ndarray | None:
"""The alpha source for a mark that ships no bundled alpha PNG."""
if mark_key == "gemini":
from remove_ai_watermarks.gemini_engine import _shared_engine
# _shared_engine is the package's own lru_cache singleton: constructing
# GeminiEngine() per image reloads its captures, recomputes both alpha maps and
# rebuilds the whole template ladder -- the exact cost that singleton exists to
# avoid. Private attribute access is deliberate (no accessor exists); a
# measurement script may reach in, product code must not.
return np.asarray(_shared_engine()._alpha_large, dtype=np.float32)
if mark_key == "jimeng_pill":
from remove_ai_watermarks._text_mark_engine import load_alpha_template
return load_alpha_template("jimeng_pill.png")
return None
def stamp_slot(
image: np.ndarray, mark_key: str, *, size_mult: float = 1.0, alpha_mult: float = 1.0
) -> tuple[np.ndarray, tuple[int, int, int, int]] | None:
"""Stamp a mark into its OWN default footprint slot (the `--no-detect` geometry).
Used for gemini and the pill, which have no bundled alpha asset with corner
fractions. The mark is fitted into the middle of its slot so the fill has to
recover the same kind of region it would in production. ``size_mult``/``alpha_mult``
match ``stamp`` (both default to 1.0).
"""
from remove_ai_watermarks.watermark_registry import get_mark
alpha = _slot_alpha(mark_key)
if alpha is None:
return None
loc = get_mark(mark_key).localize(image, force=True)
if loc.mask is None:
return None
ys, xs = np.nonzero(loc.mask)
if ys.size == 0:
return None
y0, y1, x0, x1 = int(ys.min()), int(ys.max()), int(xs.min()), int(xs.max())
bw, bh = x1 - x0 + 1, y1 - y0 + 1
gw, gh = max(8, int(bw * 0.7 * size_mult)), max(8, int(bh * 0.7 * size_mult))
a = cv2.resize(alpha, (gw, gh), interpolation=cv2.INTER_AREA).astype(np.float32) * alpha_mult
x, y = x0 + (bw - gw) // 2, y0 + (bh - gh) // 2
# A large size_mult can grow the glyph past its slot and push x/y negative; guard so
# composite never writes out of bounds (numpy would wrap a negative index silently).
if x < 0 or y < 0 or x + gw > image.shape[1] or y + gh > image.shape[0]:
return None
return composite(image, a, x, y), (x, y, gw, gh)
def stamp_any(
image: np.ndarray, mark_key: str, *, size_mult: float = 1.0, alpha_mult: float = 1.0
) -> tuple[np.ndarray, tuple[int, int, int, int]] | None:
fn = stamp if mark_key in STAMPABLE else stamp_slot
return fn(image, mark_key, size_mult=size_mult, alpha_mult=alpha_mult)
def clean_sources(n: int, seed: int = 11) -> list[Path]:
"""Corpus images with NO metadata signal and NO mark detection -- verified clean."""
from remove_ai_watermarks.identify import identify
from remove_ai_watermarks.image_io import imread
from remove_ai_watermarks.watermark_registry import detect_marks
pool = glob.glob(str(CORPUS / "*" / "*"))
random.Random(seed).shuffle(pool) # noqa: S311 -- deterministic sampling, not crypto
out: list[Path] = []
for p in pool:
if len(out) >= n:
break
path = Path(p)
try:
img = imread(str(path))
if img is None or min(img.shape[:2]) < 400:
continue
# check_visible=False: identify would otherwise decode the file a second
# time and run the very same visible detectors as detect_marks below.
if identify(path, check_visible=False).signals:
continue
if any(d.detected for d in detect_marks(img)):
continue
except Exception: # noqa: S112 -- a bad corpus file just is not a candidate
continue
out.append(path)
return out
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--n", type=int, default=60, help="clean source images")
ap.add_argument("--out", type=Path, default=OUT)
a = ap.parse_args()
from remove_ai_watermarks.image_io import imread
from remove_ai_watermarks.region_eraser import lama_available, migan_available
from remove_ai_watermarks.watermark_registry import fill, get_mark
backends = ["cv2"] + (["migan"] if migan_available() else []) + (["lama"] if lama_available() else [])
print(f"backends under test: {backends}")
print(f"selecting {a.n} verified-clean sources...", flush=True)
sources = clean_sources(a.n)
print(f"got {len(sources)}\n", flush=True)
rows: list[dict[str, Any]] = []
with open(a.out, "w", encoding="utf-8") as fh:
for i, src in enumerate(sources, 1):
base = imread(str(src))
if base is None:
continue
for key in (*STAMPABLE, *SLOT_STAMPABLE):
st = stamp_any(base, key)
if st is None:
continue
stamped, (x, y, w, h) = st
# Score a slightly padded box: the fill dilates, so a tight glyph box
# would miss damage the backend does just outside the glyph.
pad = 8
y0, y1 = max(0, y - pad), min(base.shape[0], y + h + pad)
x0, x1 = max(0, x - pad), min(base.shape[1], x + w + pad)
truth = base[y0:y1, x0:x1]
dmg_psnr = psnr(stamped[y0:y1, x0:x1], truth)
dmg_ssim = _ssim(
cv2.cvtColor(stamped[y0:y1, x0:x1], cv2.COLOR_BGR2GRAY), cv2.cvtColor(truth, cv2.COLOR_BGR2GRAY)
)
tex = texture_of(truth)
mark = get_mark(key)
loc = mark.localize(stamped, force=True)
if loc.mask is None:
continue
for backend in backends:
try:
filled = fill(stamped, loc.mask, backend=backend)
except Exception as e:
rows.append({"src": src.name, "mark": key, "backend": backend, "error": str(e)[:150]})
continue
# Invariant: the fill must not touch anything outside its mask.
outside = loc.mask == 0
untouched = bool(np.array_equal(filled[outside], stamped[outside]))
rec = {
"src": src.name,
"mark": key,
"backend": backend,
"texture": round(tex, 2),
"damage_psnr": round(dmg_psnr, 2),
"damage_ssim": round(dmg_ssim, 4),
"filled_psnr": round(psnr(filled[y0:y1, x0:x1], truth), 2),
"filled_ssim": round(
_ssim(
cv2.cvtColor(filled[y0:y1, x0:x1], cv2.COLOR_BGR2GRAY),
cv2.cvtColor(truth, cv2.COLOR_BGR2GRAY),
),
4,
),
"outside_mask_untouched": untouched,
}
rows.append(rec)
fh.write(json.dumps(rec) + "\n")
if i % 10 == 0:
fh.flush()
print(f" {i}/{len(sources)}", flush=True)
report(rows, a.out)
def report(rows: list[dict[str, Any]], out: Path) -> None:
good = [r for r in rows if "error" not in r]
if not good:
print("no measurements")
return
tex = sorted(r["texture"] for r in good)
t1, t2 = tex[len(tex) // 3], tex[2 * len(tex) // 3]
def bucket(t: float) -> str:
return "flat" if t <= t1 else ("mid" if t <= t2 else "textured")
print(f"\n{'=' * 78}\nFILL QUALITY n={len(good)} measurements (texture terciles at {t1:.1f} / {t2:.1f})")
print(f"{'=' * 78}")
print("recovered = filled PSNR minus damaged PSNR; how much of the mark's damage the fill undoes\n")
hdr = f"{'mark':9s} {'backend':8s} {'bg':9s} {'n':>4s} {'damaged':>9s} {'filled':>9s}"
print(f"{hdr} {'recovered':>10s} {'ssim':>7s}")
agg: dict[tuple[str, str, str], list[dict[str, Any]]] = collections.defaultdict(list)
for r in good:
agg[(r["mark"], r["backend"], bucket(r["texture"]))].append(r)
for (mark, backend, bg), rs in sorted(agg.items()):
# MEDIAN, not mean: a fill that reproduces a flat background EXACTLY scores
# PSNR=inf, and a single inf makes the mean inf -- which reported "+inf" for
# every flat bucket on the first run and hid the real numbers.
finite = [r for r in rs if np.isfinite(r["filled_psnr"])]
perfect = len(rs) - len(finite)
d = float(np.median([r["damage_psnr"] for r in rs]))
f = float(np.median([r["filled_psnr"] for r in finite])) if finite else float("inf")
sv = float(np.median([r["filled_ssim"] for r in rs]))
# Recovery is the MEDIAN OF THE PER-IMAGE DIFFERENCES, not the difference of the
# two medians. Those are not the same statistic on skewed data and they can even
# disagree in SIGN: the first version of this report subtracted medians and
# produced a backend ranking that a paired comparison did not support.
rec = float(np.median([r["filled_psnr"] - r["damage_psnr"] for r in finite])) if finite else float("inf")
tail = f" ({perfect} exact)" if perfect else ""
print(f"{mark:9s} {backend:8s} {bg:9s} {len(rs):4d} {d:9.2f} {f:9.2f} {rec:+10.2f} {sv:7.4f}{tail}")
bad = [r for r in good if not r["outside_mask_untouched"]]
print(f"\noutside-mask invariant violations: {len(bad)}" + (" <-- BUG" if bad else " (none)"))
print(f"records: {out}")
if __name__ == "__main__":
main()
+305
View File
@@ -0,0 +1,305 @@
"""How much recall is the coarse scale ladder costing, and what would a denser one cost?
THE FINDING THIS MEASURES
`_tophat_score` sweeps three rungs -- (0.8, 1.0, 1.25) -- and the `binary` front-end
sweeps none at all. Measured on stamped marks over controlled backgrounds
(`scripts/detector_response.py`), the response is a COMB: doubao scores 0.99 exactly at
each rung and collapses to 0.37-0.48 between them, against a 0.50 gate. So a mark whose
rendered size lands mid-gap is missed at FULL contrast. Jimeng (binary, one nominal
size) holds a single 0.90-1.20 lobe; samsung only 0.95-1.05.
WHY A SYNTHETIC SWEEP IS NOT ENOUGH TO JUSTIFY A FIX
Dead zones only cost recall if real marks land in them. The fractions were calibrated on
real captures, so it is entirely possible that real marks cluster at ratio 1.0 and the
gaps are never visited. That question is not answerable by stamping -- it needs the
corpus.
THE MEASUREMENT
Positives are images carrying INDEPENDENT vendor provenance (TC260 / C2PA metadata
naming the vendor), which is evidence that does not come from the pixel detector we are
grading -- the same discriminator that settled the pill gate. For every such image the
detector currently MISSES, rescore at a dense ladder and ask whether it would now cross
the gate, and at which scale.
Negatives are images with NO metadata signal at all. That is deliberately NOT "and no
mark was detected": defining the set by the detector's own verdict would make its
false-fire rate 0 by construction and the comparison vacuous. The cost is that a
metadata-stripped screenshot of a marked image sits in the negative set and its correct
detection is counted as a false fire -- but that impurity is identical under both
ladders, so the DELTA between them, which is what the fix is judged on, stays sound.
Two more impurities to keep in view when reading the positive arm. Provenance says the
vendor produced the file, not that a visible mark is on it. And the TC260 label names no
specific vendor, so `visible_provenance` maps it to BOTH doubao and jimeng -- a "doubao
positive" may carry a jimeng mark or none. Both inflate the miss count, so the recovery
percentage is an upper bound on what a denser ladder buys.
DATA SAFETY
Corpus images are user uploads: read-only, local analysis, gitignored output.
uv run python scripts/ladder_headroom.py --mark doubao --n 4000
"""
from __future__ import annotations
import argparse
import collections
import glob
import json
import math
import os
import random
import sys
from concurrent.futures import ProcessPoolExecutor, as_completed
from pathlib import Path
from typing import Any
import cv2
import numpy as np
sys.path.insert(0, str(Path(__file__).parent.parent))
REPO = Path(__file__).resolve().parents[1]
CORPUS = REPO / "data" / "spaces" / "originals"
OUT = REPO / "data" / "spaces" / "_ladder_headroom.jsonl"
# The rungs the product ships today, and the dense ladder under evaluation. The dense one
# is geometric with a ~6% step, chosen from the measured half-width of a rung's lobe
# (doubao holds >=0.5 for about +/-6% around each peak), so no gap is left uncovered.
SHIPPED = (0.8, 1.0, 1.25)
LADDERS: dict[str, tuple[float, ...]] = {
# A geometric ~6% step across the whole plausible range. Measures the CEILING of what
# any ladder change can buy, and the worst case of what it costs in false fires.
"dense": tuple(round(0.70 * (1.06**i), 4) for i in range(13)), # 0.70 .. ~1.49
# The targeted alternative. On the full run, 26 of 28 recoveries came from ONE rung
# (~1.116) and 22 of 28 were LANDSCAPE frames -- that is a geometry gap, not a density
# gap, so the honest comparison is one extra rung against thirteen.
"plus_one": (0.8, 1.0, 1.1157, 1.25),
"shipped": SHIPPED,
}
DENSE = LADDERS["dense"]
# Score every rung any candidate ladder might use and store them all, so a new candidate
# is evaluated by re-reading the JSONL instead of re-running the hour-long sweep.
PROBE_SCALES: tuple[float, ...] = tuple(sorted({s for rungs in LADDERS.values() for s in rungs}))
def wilson(k: int, n: int, z: float = 1.96) -> tuple[float, float]:
if n == 0:
return (0.0, 0.0)
p, d = k / n, 1 + z * z / n
c = (p + z * z / (2 * n)) / d
hw = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d
return (100 * (c - hw), 100 * (c + hw))
def score_at_scales(engine: Any, image: np.ndarray, scales: tuple[float, ...]) -> dict[float, float]:
"""`_tophat_score`'s inner loop, opened up so the ladder is a parameter.
Deliberately reaches into the engine (`tophat_response`, `_glyph_silhouette`): a
measurement script may, product code may not. Kept a faithful copy of the shipped
scoring -- if it drifts, the numbers below stop describing the product.
"""
c = engine.config
loc = engine.locate(image)
resp = engine.tophat_response(image, loc)
sil = engine._glyph_silhouette()
if resp is None or sil is None:
return {}
base = engine.scale_base(image)
out: dict[float, float] = {}
for scale in scales:
gw = max(c.min_gw, int(c.alpha_width_frac * base * scale))
gh = max(4, int(c.alpha_height_frac * base * scale))
if gw >= resp.shape[1] or gh >= resp.shape[0]:
continue
tmpl = cv2.resize(sil, (gw, gh), interpolation=cv2.INTER_AREA).astype(np.float32)
if c.template_blur > 0:
tmpl = cv2.GaussianBlur(tmpl, (0, 0), sigmaX=c.template_blur, sigmaY=c.template_blur)
out[scale] = float(cv2.matchTemplate(resp, tmpl.astype(np.uint8), cv2.TM_CCOEFF_NORMED).max())
return out
def _one(args: tuple[str, str]) -> dict[str, Any] | None:
path_str, mark_key = args
from remove_ai_watermarks.api import visible_provenance
from remove_ai_watermarks.identify import identify
from remove_ai_watermarks.image_io import imread
from remove_ai_watermarks.watermark_registry import get_mark
path = Path(path_str)
try:
prov = visible_provenance(path)
except Exception:
return None
positive = mark_key in prov
if not positive:
# A negative is a frame with NO metadata signal at all -- evidence independent of
# the detector being graded. Do NOT also require that no mark was detected: that
# defines the negative set by the very verdict under test, and "false fire today"
# would then be 0 by construction on every run.
try:
if identify(path, check_visible=False).signals:
return None
except Exception:
return None
img = imread(path_str)
if img is None or min(img.shape[:2]) < 200:
return None
mark = get_mark(mark_key)
det = mark.detect(img)
import importlib
mod = importlib.import_module(f"remove_ai_watermarks.{mark_key}_engine")
cls = next(
o for n, o in vars(mod).items() if isinstance(o, type) and n.endswith("Engine") and n != "TextMarkEngine"
)
engine = cls()
scores = score_at_scales(engine, img, PROBE_SCALES)
if not scores:
return None
gate = engine.config.detect_ncc_threshold
dense = {s: v for s, v in scores.items() if s in LADDERS["dense"]}
best_scale = max(dense, key=lambda s: dense[s]) if dense else 0.0
h, w = img.shape[:2]
return {
"src": path.name,
"arm": "positive" if positive else "negative",
"detected_now": bool(det.detected),
"conf_now": round(float(det.confidence), 4),
"gate": gate,
# Every rung, so a new candidate ladder is evaluated by re-reading this file.
"scores": {str(s): round(v, 4) for s, v in scores.items()},
"dense_best": round(dense[best_scale], 4) if dense else 0.0,
"dense_best_scale": best_scale,
"dense_crosses": bool(dense) and dense[best_scale] >= gate,
"aspect": "portrait" if w / h < 0.9 else ("landscape" if w / h > 1.1 else "square"),
}
def main() -> None:
ap = argparse.ArgumentParser()
# doubao only, and that is not laziness. `score_at_scales` reproduces the TOPHAT
# front-end, which is the only one with a ladder to widen; scoring it for jimeng or
# samsung would measure a code path their detectors never run. Doubao is also the one
# mark that declares NO rival, so crossing its NCC gate really is the whole verdict --
# for a mark with rivals, `dense_crosses` would ignore the competitive margin and read
# optimistically. Widening the binary front-end is a separate experiment.
ap.add_argument("--mark", default="doubao", choices=["doubao"])
ap.add_argument("--n", type=int, default=4000, help="corpus files to scan")
ap.add_argument("--workers", type=int, default=max(1, (os.cpu_count() or 4) - 2))
ap.add_argument("--out", type=Path, default=OUT)
ap.add_argument("--report-only", action="store_true")
a = ap.parse_args()
out = a.out.with_name(f"{a.out.stem}_{a.mark}{a.out.suffix}")
if a.report_only:
report([json.loads(x) for x in out.read_text(encoding="utf-8").splitlines() if x.strip()], a.mark)
return
pool = glob.glob(str(CORPUS / "*" / "*"))
random.Random(19).shuffle(pool) # noqa: S311 -- deterministic sampling, not crypto
pool = pool[: a.n]
print(f"mark={a.mark} scanning {len(pool)} corpus files workers={a.workers}")
print(f"shipped ladder {SHIPPED}\ndense ladder {DENSE}\n", flush=True)
rows: list[dict[str, Any]] = []
out.parent.mkdir(parents=True, exist_ok=True)
with open(out, "w", encoding="utf-8") as fh, ProcessPoolExecutor(max_workers=a.workers) as ex:
futures = [ex.submit(_one, (p, a.mark)) for p in pool]
for i, fut in enumerate(as_completed(futures), 1):
try:
rec = fut.result()
except Exception: # noqa: S112 -- one bad file must not kill the sweep
continue
if rec is None:
continue
fh.write(json.dumps(rec) + "\n")
rows.append(rec)
if i % 500 == 0:
fh.flush()
pos = sum(1 for r in rows if r["arm"] == "positive")
print(f" {i}/{len(pool)} usable={len(rows)} (pos={pos})", flush=True)
report(rows, a.mark)
def report(rows: list[dict[str, Any]], mark: str) -> None:
pos = [r for r in rows if r["arm"] == "positive"]
neg = [r for r in rows if r["arm"] == "negative"]
print(f"\n{'=' * 82}\nLADDER HEADROOM mark={mark} positives={len(pos)} verified-clean negatives={len(neg)}")
print(f"{'=' * 82}")
if not pos and not neg:
print("no usable rows")
return
if pos:
miss = [r for r in pos if not r["detected_now"]]
rec = [r for r in miss if r["dense_crosses"]]
now = len(pos) - len(miss)
lo, hi = wilson(len(rec), len(miss)) if miss else (0.0, 0.0)
print("\nPOSITIVE ARM (images whose METADATA names this vendor -- an upper bound,")
print("provenance says the vendor produced the file, not that a mark is visible on it)\n")
print(f" detected today {now:5d} / {len(pos)} ({100 * now / len(pos):.1f}%)")
print(f" of the {len(miss)} misses, the dense ladder crosses the gate on {len(rec)}")
if miss:
print(f" ({100 * len(rec) / len(miss):.1f}%, 95% CI {lo:.1f}-{hi:.1f})")
after = now + len(rec)
print(f" detection would go {100 * now / len(pos):.1f}% -> {100 * after / len(pos):.1f}%")
if rec:
by_scale = collections.Counter(r["dense_best_scale"] for r in rec)
print("\n which rung recovers them (a rung near a SHIPPED one recovering many means")
print(" the gain is the finer STEP, not the wider RANGE):")
for s, n in sorted(by_scale.items()):
near = " <- shipped" if any(abs(s - x) < 0.02 for x in SHIPPED) else ""
print(f" scale {s:<6} {n:4d}{near}")
by_asp = collections.Counter(r["aspect"] for r in rec)
print(f"\n by aspect: {dict(by_asp)}")
if neg:
fires_now = sum(1 for r in neg if r["detected_now"])
fires_dense = sum(1 for r in neg if r["dense_crosses"])
lo0, hi0 = wilson(fires_now, len(neg))
lo1, hi1 = wilson(fires_dense, len(neg))
print("\n\nNEGATIVE ARM (no metadata signal; NOT filtered on the detector's own verdict)\n")
p0, p1 = 100 * fires_now / len(neg), 100 * fires_dense / len(neg)
print(f" false fire today {fires_now:4d} / {len(neg)} {p0:.2f}% (CI {lo0:.2f}-{hi0:.2f})")
print(f" false fire, dense ladder {fires_dense:4d} / {len(neg)} {p1:.2f}% (CI {lo1:.2f}-{hi1:.2f})")
print("\n This is the price. A denser ladder gives a spurious blob more chances to")
print(" match at SOME scale, so the gain above is only real if this line barely moves.")
ladder_table(pos, neg)
def _crosses(row: dict[str, Any], rungs: tuple[float, ...]) -> bool:
"""Would this frame cross its gate on the given ladder, from the stored per-rung scores."""
sc = row.get("scores") or {}
gate = row["gate"]
return any(v >= gate for k, v in sc.items() if float(k) in rungs)
def ladder_table(pos: list[dict[str, Any]], neg: list[dict[str, Any]]) -> None:
"""Every candidate ladder side by side: what it recovers against what it costs."""
if not (pos and neg) or "scores" not in pos[0]:
return # older run without per-rung scores
miss = [r for r in pos if not r["detected_now"]]
base_fire = sum(1 for r in neg if r["detected_now"])
print("\n\nLADDER CANDIDATES -- recovered marks against the false fires they cost\n")
print("A candidate is only worth shipping if the recovered column beats the added-fires")
print("column by enough to survive the base rates: clean frames vastly outnumber marked")
print("ones in real traffic, so a small percentage on the negative arm is a large count.\n")
hdr = f"{'ladder':10s} {'rungs':>6s} {'recovered':>10s} {'of misses':>10s}"
print(f"{hdr} {'false fire':>11s} {'added':>7s} {'ratio':>7s}")
for name, rungs in LADDERS.items():
rec = sum(1 for r in miss if _crosses(r, rungs))
fire = sum(1 for r in neg if _crosses(r, rungs) or r["detected_now"])
added = fire - base_fire
ratio = f"{rec / added:.1f}:1" if added > 0 else ("inf" if rec else "-")
pct = 100 * rec / len(miss) if miss else 0.0
print(f"{name:10s} {len(rungs):6d} {rec:10d} {pct:9.1f}% {100 * fire / len(neg):10.2f}% {added:7d} {ratio:>7s}")
if __name__ == "__main__":
main()
+256
View File
@@ -0,0 +1,256 @@
"""Audit AI-metadata REMOVAL over a local image corpus (detection<->removal parity).
`corpus_gap_scan.py` proves the DETECTOR sees a marker; this proves the STRIPPER
reaches it. For every file that carries an AI-metadata signal, run
``remove_ai_metadata`` and re-scan the output with the SAME oracle
(``get_ai_metadata``). Any signal that survives is a real parity bug: a re-served
file still reads as AI. Also assert the strip is lossless -- decoded pixels
(and alpha) bit-identical before/after -- since the removal must only touch
metadata, never the coded image.
A no-op control set (clean images with no AI metadata) verifies the stripper
neither ADDS a signal nor corrupts pixels on files it should leave alone.
Operates on gitignored data only (data/spaces/...); writes nothing tracked.
uv run python scripts/metadata_removal_audit.py \
--corpus data/spaces/originals --identify data/spaces/identify \
--out data/spaces/_metadata_removal_audit.csv --jobs 8
"""
from __future__ import annotations
import csv
import json
import logging
import random
import tempfile
from collections import Counter
from concurrent.futures import ProcessPoolExecutor, as_completed
from pathlib import Path
import click
import numpy as np
from remove_ai_watermarks.noai.constants import SUPPORTED_FORMATS
log = logging.getLogger(__name__)
# identify-JSON watermark substrings that imply a METADATA-borne signal (as
# opposed to a purely visual sparkle/text mark). Used only to pick the candidate
# population fast; get_ai_metadata is the per-file ground truth.
_META_HINTS = (
"C2PA",
"Content Credentials",
"IPTC",
"Made with AI",
"AIGC",
"TC260",
"EXIF",
"Signature",
"SynthID",
"hf-job",
"HuggingFace",
"Samsung",
"soft-binding",
"metadata",
)
def _pixels(path: Path) -> tuple[np.ndarray | None, np.ndarray | None]:
"""Decoded BGR + alpha, for the lossless-strip integrity check."""
from remove_ai_watermarks import image_io
return image_io.read_bgr_and_alpha(path)
def _same_pixels(a: Path, b: Path) -> bool | None:
"""True/False if both decode; None if either is undecodable (can't compare)."""
try:
bgr_a, al_a = _pixels(a)
bgr_b, al_b = _pixels(b)
except Exception:
return None
if bgr_a is None or bgr_b is None:
return None
if bgr_a.shape != bgr_b.shape or not np.array_equal(bgr_a, bgr_b):
return False
if (al_a is None) != (al_b is None):
return False
return al_a is None or al_b is None or np.array_equal(al_a, al_b)
def _audit_one(path_str: str) -> dict[str, object]:
"""Worker: detect -> strip -> re-detect + pixel-integrity for one file."""
from remove_ai_watermarks.metadata import get_ai_metadata, remove_ai_metadata
path = Path(path_str)
row: dict[str, object] = {
"path": path.name,
"ext": path.suffix.lower(),
"carrier": False,
"before": "",
"after": "",
"parity_ok": "",
"pixels_identical": "",
"status": "ok",
}
try:
before = get_ai_metadata(path)
except Exception as exc:
row["status"] = f"scan_error:{type(exc).__name__}"
return row
row["before"] = "|".join(sorted(before))
row["carrier"] = bool(before)
with tempfile.TemporaryDirectory() as td:
out = Path(td) / f"clean{path.suffix.lower()}"
try:
remove_ai_metadata(path, out)
except Exception as exc:
row["status"] = f"strip_error:{type(exc).__name__}"
return row
if not out.exists():
row["status"] = "no_output"
return row
try:
after = get_ai_metadata(out)
except Exception as exc:
row["status"] = f"rescan_error:{type(exc).__name__}"
return row
row["after"] = "|".join(sorted(after))
row["parity_ok"] = not after # every AI signal must be gone
same = _same_pixels(path, out)
row["pixels_identical"] = "" if same is None else same
return row
def _candidate_paths(corpus: Path, identify: Path | None, clean_sample: int) -> tuple[list[Path], list[Path]]:
"""Return (carriers, clean_controls). Uses identify JSONs when present to pick
metadata carriers fast; falls back to scanning every file."""
if identify is None or not identify.exists():
files = sorted(p for p in corpus.rglob("*") if p.is_file() and p.suffix.lower() in SUPPORTED_FORMATS)
return files, []
carriers: list[Path] = []
clean: list[Path] = []
for jf in identify.rglob("*.json"):
try:
d = json.loads(jf.read_text())
except Exception: # noqa: S112 -- skip an unreadable identify JSON, not security-relevant
continue
src = d.get("src")
if not src:
continue
img = corpus / jf.parent.name / src
if not img.exists() or img.suffix.lower() not in SUPPORTED_FORMATS:
continue
wm = " | ".join(d.get("watermarks") or [])
if any(h in wm for h in _META_HINTS):
carriers.append(img)
elif not d.get("is_ai_generated"):
clean.append(img)
rng = random.Random(0) # noqa: S311 -- deterministic sampling seed, not cryptographic
rng.shuffle(clean)
return carriers, clean[:clean_sample]
@click.command()
@click.option(
"--corpus", type=click.Path(exists=True, file_okay=False, path_type=Path), default=Path("data/spaces/originals")
)
@click.option(
"--identify",
type=click.Path(path_type=Path),
default=Path("data/spaces/identify"),
help="identify-JSON dir to pick carriers (skip = scan all).",
)
@click.option("--out", type=click.Path(path_type=Path), default=Path("data/spaces/_metadata_removal_audit.csv"))
@click.option(
"--clean-sample", type=int, default=1500, help="No-op control: N clean images to prove the strip is a no-op."
)
@click.option("--limit", type=int, default=0, help="Cap carriers scanned (0 = all).")
@click.option("--jobs", type=int, default=8)
def main(corpus: Path, identify: Path | None, out: Path, clean_sample: int, limit: int, jobs: int) -> None:
logging.basicConfig(level=logging.ERROR, format="%(message)s")
carriers, clean = _candidate_paths(corpus, identify, clean_sample)
if limit:
carriers = carriers[:limit]
tasks = [(p, "carrier") for p in carriers] + [(p, "clean") for p in clean]
click.echo(f"Carriers: {len(carriers)} | clean controls: {len(clean)} | jobs {jobs}")
rows: list[dict[str, object]] = []
with ProcessPoolExecutor(max_workers=jobs) as ex:
futs = {ex.submit(_audit_one, str(p)): k for p, k in tasks}
for done, fut in enumerate(as_completed(futs), 1):
row = fut.result()
row["kind"] = futs[fut]
rows.append(row)
if done % 500 == 0:
click.echo(f" {done}/{len(tasks)}")
out.parent.mkdir(parents=True, exist_ok=True)
fields = ["kind", "path", "ext", "carrier", "before", "after", "parity_ok", "pixels_identical", "status"]
with out.open("w", newline="") as f:
w = csv.DictWriter(f, fieldnames=fields)
w.writeheader()
for r in rows:
w.writerow({k: r.get(k, "") for k in fields})
# ---- Summary ----
car = [r for r in rows if r["kind"] == "carrier"]
ctl = [r for r in rows if r["kind"] == "clean"]
real_carriers = [r for r in car if r["carrier"] and r["status"] == "ok"]
parity_fail = [r for r in real_carriers if r["parity_ok"] is False]
pixel_fail = [r for r in real_carriers if r["pixels_identical"] is False]
errors = [r for r in rows if r["status"] != "ok"]
click.echo("\n===== METADATA REMOVAL PARITY =====")
click.echo(f"Carrier candidates: {len(car)}")
click.echo(f"Confirmed carriers: {len(real_carriers)} (get_ai_metadata non-empty)")
click.echo(f"Parity FAILS (signal survives strip): {len(parity_fail)}")
click.echo(f"Pixel-integrity FAILS (strip altered pixels): {len(pixel_fail)}")
click.echo(f"Errors (scan/strip/decode): {len(errors)}")
# Per-signal parity breakdown.
sig_total: Counter[str] = Counter()
sig_fail: Counter[str] = Counter()
for r in real_carriers:
for s in str(r["before"]).split("|"):
if s:
sig_total[s] += 1
if r["parity_ok"] is False:
for s in str(r["after"]).split("|"):
if s:
sig_fail[s] += 1
click.echo("\nPer-signal (carriers / surviving-after-strip):")
for s, n in sig_total.most_common():
click.echo(f" {s:24} {n:6} survived: {sig_fail.get(s, 0)}")
click.echo("\n===== NO-OP CONTROL (clean images) =====")
ctl_ok = [r for r in ctl if r["status"] == "ok"]
added = [r for r in ctl_ok if r["after"]] # strip must not ADD a signal
corrupted = [r for r in ctl_ok if r["pixels_identical"] is False]
click.echo(f"Clean controls scanned: {len(ctl_ok)}")
click.echo(f"Strip ADDED a signal: {len(added)}")
click.echo(f"Strip corrupted pixels: {len(corrupted)}")
if parity_fail:
click.echo("\n--- Parity failures (first 30) ---")
for r in parity_fail[:30]:
click.echo(f" {r['ext']:6} survived=[{r['after']}] {r['path']}")
if pixel_fail:
click.echo("\n--- Pixel-integrity failures (first 30) ---")
for r in pixel_fail[:30]:
click.echo(f" {r['ext']:6} {r['path']}")
if errors:
ec: Counter[str] = Counter(str(r["status"]) for r in errors)
click.echo("\n--- Errors by kind ---")
for k, n in ec.most_common():
click.echo(f" {n:5} {k}")
click.echo(f"\nReport: {out}")
if __name__ == "__main__":
main()
+224
View File
@@ -0,0 +1,224 @@
"""Measure the Jimeng pill on the PRODUCT path, not the raw detector.
WHY THIS EXISTS
`visible_removal_audit.py` calls `get_mark(key).remove` directly, which bypasses
`_keep_pill`. For the pill that is the wrong path and it reads as a disaster: on a
300-image sample the raw path was "detector still fires after removal" 68-75% of the
time. The product does not do that -- `--mark auto` gates the pill hard (never on
Doubao; unrestricted only when the bottom-right wordmark fired; otherwise only on a
flat footprint). Measured through the gate on the same sample, 7 of 80 raw detections
survived to removal and 6 of those were corroborated real.
That sample was too small to state a precision (95% CI 49-97%). This script runs the
gated path over EVERY pill positive in the corpus so the interval is usable.
THE CORROBORATION PROXY AND ITS BIAS
"Real pill" here means: TC260 metadata names Jimeng, OR the bottom-right "★ 即梦AI"
wordmark is detected. Both are independent of the pill detector, which is the point.
But the proxy MISSES a real pill on a metadata-stripped screenshot with no visible
wordmark -- so measured precision is a LOWER BOUND, not a point estimate. Do not quote
it as if it were exact.
Corpus images are user uploads: read-only, local analysis, gitignored output.
uv run python scripts/pill_gate_audit.py --jobs 7
"""
from __future__ import annotations
import argparse
import collections
import json
import math
import os
import sys
from concurrent.futures import ProcessPoolExecutor, as_completed
from concurrent.futures import TimeoutError as FutureTimeout
from concurrent.futures.process import BrokenProcessPool
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent))
REPO = Path(__file__).resolve().parents[1]
POSITIVES = REPO / "data" / "spaces" / "_visible_positives.jsonl"
OUT = REPO / "data" / "spaces" / "_pill_gate_audit.jsonl"
def wilson(k: int, n: int, z: float = 1.96) -> tuple[float, float]:
if n == 0:
return (0.0, 0.0)
p = k / n
d = 1 + z * z / n
c = (p + z * z / (2 * n)) / d
h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d
return (100 * (c - h), 100 * (c + h))
def _one(path_str: str) -> dict[str, object]:
from remove_ai_watermarks.api import visible_provenance
from remove_ai_watermarks.image_io import imread
from remove_ai_watermarks.pill_engine import PillEngine
from remove_ai_watermarks.watermark_registry import detect_marks, get_mark, remove_auto_marks
rec: dict[str, object] = {"path": Path(path_str).name, "status": "ok"}
try:
img = imread(path_str)
if img is None:
return {**rec, "status": "unreadable"}
prov = visible_provenance(Path(path_str))
dets = {d.key: d for d in detect_marks(img) if d.detected}
wordmark = "jimeng" in dets
tc260 = "jimeng" in prov
eng = PillEngine()
_, labels = remove_auto_marks(img, sensitivity="auto", provenance=prov, backend="cv2")
# Match the EXACT pill label. A substring test on "AI生成" also matches Doubao's
# label ("Doubao 豆包AI生成 text"), which counted Doubao removals as pill removals
# and inflated the pill's measured precision.
pill_label = get_mark("jimeng_pill").label
removed = any(str(x) == pill_label for x in labels)
# The gate reads the ARBITRATED keys, not strict detection: jimeng can be accepted
# on its relaxed (provenance-confirmed) arm, which `detect_marks` never shows. Take
# the arm from what was actually removed, or every such case lands in "other".
jimeng_decided = any(str(x) == get_mark("jimeng").label for x in labels)
return {
**rec,
"removed_by_product": bool(removed),
"corroborated": bool(wordmark or tc260),
"wordmark": bool(wordmark),
"jimeng_decided": bool(jimeng_decided),
"tc260": bool(tc260),
"doubao_fired": "doubao" in dets,
"footprint_flat": bool(eng.footprint_is_flat(img)),
}
except Exception as e:
return {**rec, "status": f"error:{type(e).__name__}"}
def _batch(paths: list[str], jobs: int, timeout: int) -> list[dict[str, object]]:
try:
with ProcessPoolExecutor(max_workers=jobs) as ex:
futs = [ex.submit(_one, p) for p in paths]
return [f.result() for f in as_completed(futs, timeout=timeout)]
except (FutureTimeout, BrokenProcessPool, OSError, RuntimeError):
out = []
for p in paths:
try:
out.append(_one(p))
except BaseException: # a native crash costs one file, not the sweep
out.append({"path": Path(p).name, "status": "crashed"})
return out
def report(rows: list[dict[str, object]]) -> None:
ok = [r for r in rows if r.get("status") == "ok"]
if not ok:
print("no usable rows")
return
removed = [r for r in ok if r["removed_by_product"]]
corro = [r for r in ok if r["corroborated"]]
tp = [r for r in removed if r["corroborated"]]
missed = [r for r in corro if not r["removed_by_product"]]
print(f"\n{'=' * 76}\nJIMENG PILL ON THE PRODUCT PATH n={len(ok)} raw detections\n{'=' * 76}")
print(f"raw detections corroborated as real : {len(corro):5d} ({100 * len(corro) / len(ok):.1f}%)")
print(f"the gate lets through to removal : {len(removed):5d} ({100 * len(removed) / len(ok):.1f}%)")
if removed:
lo, hi = wilson(len(tp), len(removed))
pct = 100 * len(tp) / len(removed)
print(f" of those, corroborated real : {len(tp):5d} -> precision {pct:.1f}% (95% CI {lo:.1f}-{hi:.1f})")
if corro:
lo, hi = wilson(len(tp), len(corro))
pct = 100 * len(tp) / len(corro)
head = f"corroborated pills removed : {len(tp):5d}/{len(corro)}"
print(f"{head} -> recall {pct:.1f}% (95% CI {lo:.1f}-{hi:.1f})")
print(f"corroborated pills the gate suppressed: {len(missed):5d}")
print("\nprecision is a LOWER BOUND: the corroboration proxy cannot see a real pill on a")
print("metadata-stripped image whose wordmark is absent or missed.\n")
print("which gate arm let it through:")
arms: collections.Counter[str] = collections.Counter()
for r in removed:
if r.get("jimeng_decided"):
arms["jimeng wordmark accepted -> unrestricted"] += 1
elif r["tc260"]:
arms["tc260 metadata + flat footprint"] += 1
else:
arms["other (unexpected -- the gate has no third arm)"] += 1
for k, v in arms.most_common():
print(f" {v:5d} {k}")
print("\nwhy the rest were suppressed:")
sup: collections.Counter[str] = collections.Counter()
for r in ok:
if r["removed_by_product"]:
continue
if r["doubao_fired"]:
sup["doubao fired (pill never rides on it)"] += 1
elif not r["corroborated"]:
sup["no corroboration (no wordmark, no TC260)"] += 1
elif not r["footprint_flat"]:
sup["corroborated but footprint too textured"] += 1
else:
sup["other"] += 1
for k, v in sup.most_common():
print(f" {v:5d} {k}")
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--jobs", type=int, default=max(1, (os.cpu_count() or 4) - 2))
ap.add_argument("--limit", type=int, default=0)
ap.add_argument("--batch", type=int, default=200)
ap.add_argument("--timeout", type=int, default=900)
ap.add_argument("--out", type=Path, default=OUT)
ap.add_argument("--restart", action="store_true")
a = ap.parse_args()
paths = []
with open(POSITIVES, encoding="utf-8") as fh:
for line in fh:
try:
r = json.loads(line)
except Exception: # noqa: S112
continue
if "jimeng_pill" in (r.get("keys") or []):
paths.append(r["path"])
paths.sort()
if a.limit:
paths = paths[: a.limit]
done: set[str] = set()
if a.restart and a.out.exists():
a.out.unlink() # --restart must TRUNCATE; appending kept the old rows in the report
if a.out.exists() and not a.restart:
with open(a.out, encoding="utf-8") as fh:
for line in fh:
try:
done.add(json.loads(line)["path"])
except Exception: # noqa: S112
continue
todo = [p for p in paths if Path(p).name not in done]
print(f"pill positives {len(paths)} done {len(done)} to do {len(todo)} jobs {a.jobs}", flush=True)
rows: list[dict[str, object]] = []
with open(a.out, "a", encoding="utf-8") as fh:
for i in range(0, len(todo), a.batch):
for rec in _batch(todo[i : i + a.batch], a.jobs, a.timeout):
fh.write(json.dumps(rec) + "\n")
rows.append(rec)
fh.flush()
print(f" {len(rows)}/{len(todo)}", flush=True)
with open(a.out, encoding="utf-8") as fh:
allrows = []
for line in fh:
try:
allrows.append(json.loads(line))
except Exception: # noqa: S112
continue
report(allrows)
print(f"records -> {a.out}")
if __name__ == "__main__":
main()
+328
View File
@@ -0,0 +1,328 @@
"""End-to-end confidence run: drive the ACTUAL CLI over REAL corpus examples.
WHY THIS EXISTS AND WHAT IT IS NOT
The 849-test suite and `smoke_matrix.py` prove the code paths behave on fixtures and
synthetic inputs. This is the other half: run the real `remove-ai-watermarks` entry point,
as a user would, over real corpus images spanning every command and every provenance
class, and CHECK THE OUTPUT -- not that it exited 0, but that it did the right thing (the
mark is actually gone on re-detect, the metadata actually strips, the diffusion actually
writes a changed image). A green exit is not evidence the work happened.
WHAT IT COVERS
identify one real image per provenance class -> the verdict is right
metadata real AI-metadata files -> --check detects, --remove strip-and-verifies clean
visible real marked images per mark -> the mark is gone on re-detect, output written
erase a real image, each fill backend (cv2 / migan / lama) -> output written
invisible a real SynthID image on MPS at reduced resolution -> a CHANGED image is written
all a real marked image through the full pipeline -> output written
batch a real directory -> every input produces an output
invisible/all run the diffusion model, so they are gated behind --diffusion and run at a
small --max-resolution on MPS (the user's "reduced size on MPS" path). Everything else is
cv2/numpy and fast.
DATA SAFETY
Corpus images are user uploads: read-only, local analysis, outputs to a gitignored temp
dir. Records example uids and pass/fail, never image content.
uv run python scripts/real_examples_e2e.py # fast surface (no diffusion)
uv run python scripts/real_examples_e2e.py --diffusion # + invisible/all on MPS
"""
from __future__ import annotations
import argparse
import glob
import json
import random
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent))
REPO = Path(__file__).resolve().parents[1]
CORPUS = REPO / "data" / "spaces" / "originals"
DATASETS = REPO / "data" / "spaces" / "_visible_datasets"
SAMPLES = REPO / "data" / "samples"
_UV = shutil.which("uv") or "uv" # full path avoids the partial-executable lint
def run(args: list[str], timeout: int = 300) -> tuple[int, str]:
"""Invoke the real installed CLI. Returns (exit_code, combined output)."""
proc = subprocess.run( # noqa: S603 -- fixed argv, the whole point is the real entry point
[_UV, "run", "remove-ai-watermarks", *args],
cwd=REPO,
capture_output=True,
text=True,
timeout=timeout,
check=False,
)
return proc.returncode, (proc.stdout + proc.stderr)
def find_visible_positive(mark: str) -> Path | None:
"""A real corpus image the parity run bucketed as carrying this mark, that the current
detector STILL fires on (the bucket was built by an older run; re-confirm live)."""
from remove_ai_watermarks.image_io import imread
from remove_ai_watermarks.watermark_registry import detect_marks
pool = sorted(glob.glob(str(DATASETS / mark / "*")))
random.Random(3).shuffle(pool) # noqa: S311 -- deterministic sampling, not cryptography
for p in pool[:60]:
img = imread(p)
if img is None:
continue
if any(d.detected and d.key == mark for d in detect_marks(img)):
return Path(p)
return None
class Results:
"""Collects one row per checked behaviour.
A FAIL keeps the command's OUTPUT. That is not cosmetic: the first run of this harness
discarded it, an `all` invocation failed once with exit 1, and because the output was
gone there was no way to tell which of that command's three distinct `SystemExit(1)`
paths had fired -- the failure was undiagnosable and did not reproduce. Keep the tail
so a transient is at least identifiable after the fact.
"""
def __init__(self) -> None:
self.rows: list[tuple[str, str, bool, str, str]] = []
def add(self, cmd: str, example: str, ok: bool, detail: str, output: str = "") -> None:
self.rows.append((cmd, example, ok, detail, "" if ok else output[-800:]))
mark = "PASS" if ok else "FAIL"
print(f" [{mark}] {cmd:28s} {example:26s} {detail}", flush=True)
def report(self) -> int:
n = len(self.rows)
bad = [r for r in self.rows if not r[2]]
print(f"\n{'=' * 78}\nREAL-EXAMPLE E2E {n - len(bad)}/{n} passed")
print(f"{'=' * 78}")
for cmd, ex, ok, detail, out in self.rows:
if not ok:
print(f" FAIL {cmd} {ex} {detail}")
if out.strip():
print(" --- command output (tail) ---")
for line in out.strip().splitlines()[-12:]:
print(f" {line}")
if not bad:
print(" every command produced the right result on real corpus examples")
return 1 if bad else 0
def check_identify(res: Results) -> None:
"""One real image per provenance class -> the verdict is right (--json must parse)."""
print("\nidentify -- real image per provenance class")
cases = [
("chatgpt-1.png", True),
("firefly-1.png", True),
("mj-1.png", True),
("doubao-1.png", True),
("grok-1.jpg", True),
("flux-1.jpg", True),
]
for name, want_ai in cases:
p = SAMPLES / name
if not p.exists():
res.add("identify", name, False, "sample missing")
continue
code, out = run(["identify", str(p), "--json"])
try:
data = json.loads(out[out.index("{") : out.rindex("}") + 1])
except (ValueError, json.JSONDecodeError):
res.add("identify", name, False, f"json did not parse (exit {code})")
continue
is_ai = data.get("is_ai_generated")
plat = (data.get("platform") or "").lower()
ok = bool(is_ai) is want_ai
res.add("identify", name, ok, f"is_ai={is_ai} platform={plat or '-'}")
def check_metadata(res: Results, tmp: Path) -> None:
"""Real AI-metadata files -> --check detects, --remove strip-and-verifies clean."""
print("\nmetadata -- real AI-metadata files, detect then strip-and-verify")
for name in ("chatgpt-1.png", "doubao-1.png", "mj-1.png", "grok-1.jpg", "flux-1.jpg"):
p = SAMPLES / name
if not p.exists():
res.add("metadata --check", name, False, "sample missing")
continue
code, out = run(["metadata", str(p), "--check"])
detected = "no ai" not in out.lower() and code == 0
res.add("metadata --check", name, detected, "AI metadata detected" if detected else "nothing detected")
outp = tmp / f"stripped_{name}"
code, out = run(["metadata", str(p), "--remove", "-o", str(outp)])
# strip-and-verify: the command re-scans the OUTPUT and fails loudly on leftovers.
clean = outp.exists() and code == 0 and "still" not in out.lower()
res.add("metadata --remove", name, clean, "output re-scanned clean" if clean else f"exit {code}")
def check_visible(res: Results, tmp: Path) -> None:
"""Real marked images -> the PRODUCT'S DECISION is honoured, and a removed mark clears.
The success criterion is not "the mark is always gone" -- it is "the product did what it
decided, and the decision is right". Two designed behaviours make a blind re-detect
misleading:
* The pill is GATED (`_keep_pill`): a low-confidence pill with no corroboration is
deliberately NOT removed, so `visible` correctly writes nothing and exits 2. That is
the gate working, not a miss -- checked by asking `remove_auto_marks` whether it
chose to act.
* Samsung is the faintest mark (peak alpha ~0.38) at a razor-thin 0.40 gate, so a
borderline positive can be reduced yet re-detect just above threshold. Reported as
the measured before->after confidence, not a bare pass/fail.
"""
from remove_ai_watermarks.image_io import imread
from remove_ai_watermarks.watermark_registry import detect_marks, get_mark, remove_auto_marks
print("\nvisible --mark auto -- real marked image per mark, product decision then re-detect")
for mark in ("doubao", "jimeng", "qwen", "gemini", "samsung", "jimeng_pill"):
src = find_visible_positive(mark)
if src is None:
res.add("visible", mark, True, "no live positive in bucket (skipped, not a failure)")
continue
img = imread(str(src))
conf_before = next((d.confidence for d in detect_marks(img) if d.detected and d.key == mark), 0.0)
# What does the product DECIDE to do? (labels lists the marks it removed.)
_out_img, labels = remove_auto_marks(img, sensitivity="auto", provenance=frozenset(), backend="cv2")
acted = get_mark(mark).label in labels
outp = tmp / f"visible_{mark}{src.suffix}"
code, out = run(["visible", str(src), "--mark", "auto", "-o", str(outp)])
if not acted:
# The gate declined this mark. The CLI must then write nothing and exit 2 --
# that is the correct outcome, so verify the CLI agrees with the decision.
ok = code == 2 and not outp.exists()
res.add(
"visible", mark, ok, f"gate declined (conf {conf_before:.2f}); CLI exit {code}, no output -- correct"
)
continue
if not outp.exists():
res.add("visible", mark, False, f"product removed it but CLI wrote no output (exit {code})", out)
continue
cleaned = imread(str(outp))
conf_after = next((d.confidence for d in detect_marks(cleaned) if d.detected and d.key == mark), 0.0)
clean = conf_after == 0.0
if clean:
res.add("visible", mark, True, f"removed, re-detect clean ({conf_before:.2f} -> below gate)")
else:
# Reduced but still over the gate: a real residual. Honest partial, flagged.
res.add(
"visible",
mark,
False,
f"reduced {conf_before:.2f} -> {conf_after:.2f} but still over gate (faint-mark residual)",
)
def check_erase(res: Results, tmp: Path) -> None:
"""A real image, each fill backend actually runs and writes an output."""
from remove_ai_watermarks.region_eraser import lama_available, migan_available
print("\nerase --region -- each fill backend on a real image")
src = next((Path(p) for p in sorted(glob.glob(str(CORPUS / "*" / "*"))) if Path(p).stat().st_size > 50_000), None)
if src is None:
res.add("erase", "-", False, "no corpus image")
return
backends = ["cv2"] + (["migan"] if migan_available() else []) + (["lama"] if lama_available() else [])
for backend in backends:
outp = tmp / f"erase_{backend}{src.suffix}"
code, out = run(["erase", str(src), "--region", "10,10,120,60", "--backend", backend, "-o", str(outp)])
ok = outp.exists() and code == 0 and outp.stat().st_size > 0
res.add(f"erase --backend {backend}", src.name[:12], ok, "output written" if ok else f"exit {code}", out)
def check_diffusion(res: Results, tmp: Path, gemini_src: str, openai_src: str) -> None:
"""The GPU path: invisible + all on MPS at reduced resolution -> a CHANGED image."""
import numpy as np
from remove_ai_watermarks.image_io import imread
print("\ninvisible / all -- real SynthID image on MPS, reduced resolution")
for label, src in (("invisible/gemini", gemini_src), ("invisible/openai", openai_src)):
if not src:
res.add(label, "-", True, "no real positive found (skipped)")
continue
sp = Path(src)
outp = tmp / f"inv_{sp.stem}.png"
code, out = run(
["invisible", src, "-o", str(outp), "--device", "mps", "--max-resolution", "512", "--seed", "0"],
timeout=1200,
)
if not outp.exists():
res.add(label, sp.name[:12], False, f"no output (exit {code})", out)
continue
before, after = imread(src), imread(str(outp))
# Diffusion regenerates every pixel; the output must actually differ from the input.
# A DIFFERENT SHAPE is itself proof it changed (the pipeline resizes), so treat it
# as changed rather than comparing arrays that cannot be compared. The first
# version wrote `array_equal(after, before if shapes match else after)`, which
# compares `after` WITH ITSELF on the mismatch branch and is therefore always
# "unchanged" -- it would have reported a genuinely resized output as a no-op.
changed = (
after is not None
and before is not None
and (before.shape != after.shape or not np.array_equal(before, after))
)
res.add(label, sp.name[:12], changed, "diffusion wrote a changed image" if changed else "output == input", out)
if gemini_src:
sp = Path(gemini_src)
outp = tmp / f"all_{sp.stem}.png"
code, out = run(
["all", gemini_src, "-o", str(outp), "--device", "mps", "--max-resolution", "512", "--seed", "0"],
timeout=1200,
)
ok = outp.exists() and outp.stat().st_size > 0
res.add("all (full pipeline)", sp.name[:12], ok, "output written" if ok else f"exit {code}", out)
def check_batch(res: Results, tmp: Path) -> None:
"""A real directory -> every supported input produces an output."""
print("\nbatch -- a real directory")
indir = tmp / "batch_in"
indir.mkdir(exist_ok=True)
picks = sorted(glob.glob(str(DATASETS / "doubao" / "*")))[:5]
for p in picks:
shutil.copy2(p, indir / Path(p).name)
n_in = len(list(indir.glob("*")))
if n_in == 0:
res.add("batch", "-", False, "no inputs to seed")
return
outdir = tmp / "batch_out"
code, out = run(["batch", str(indir), "-o", str(outdir), "--mode", "visible"], timeout=600)
n_out = len(list(outdir.glob("*"))) if outdir.exists() else 0
ok = code == 0 and n_out >= n_in
res.add("batch --mode visible", f"{n_in} imgs", ok, f"{n_out}/{n_in} outputs (exit {code})", out)
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--diffusion", action="store_true", help="also run invisible/all on MPS (slow)")
ap.add_argument("--gemini", default="")
ap.add_argument("--openai", default="")
a = ap.parse_args()
res = Results()
with tempfile.TemporaryDirectory(prefix="raiw_e2e_") as td:
tmp = Path(td)
check_identify(res)
check_metadata(res, tmp)
check_visible(res, tmp)
check_erase(res, tmp)
check_batch(res, tmp)
if a.diffusion:
check_diffusion(res, tmp, a.gemini, a.openai)
else:
print("\n(diffusion skipped -- pass --diffusion to run invisible/all on MPS)")
raise SystemExit(res.report())
if __name__ == "__main__":
main()
+291
View File
@@ -0,0 +1,291 @@
"""Render SYNTHETIC detection silhouettes for the CJK vendor text marks (data-safe).
Adding a mark needs only a DETECTION silhouette, and it must be font-rendered rather
than derived from user uploads: the corpus is real user content and may never reach a
tracked asset (see the repo CLAUDE.md data-safety rule). Seeing real samples to learn
the glyphs, weight and layout is fine; the committed template stays synthetic.
Covered here:
qwen "千问AI生成" -- Alibaba Tongyi Qianwen, bottom-right, 3-lobed logo + text
xinghui "星绘AI生成" -- ByteDance 星绘, bottom-right, 4-point sparkle + text
yuanbao "元宝\nAI生成" -- Tencent Yuanbao, bottom-right, two-line italic block
(MEASURED NEGATIVE 2026-07-21, parked: the slanted two-line template does
not separate the cohort from clean corners on either front-end; the recipe
+ MARK_OPTS stay as the starting point if a structural/learned lever is
built -- full record in docs/verification-plan.md)
kling "可灵AI 3.0" -- Kuaishou Kling, bottom-right, spiral logo + text
(REGISTERED 2026-07-21, kling_engine.py)
The leading LOGO is deliberately NOT rendered. It is the part that varies most between
releases and is hardest to reproduce synthetically, while the CJK run is stable and is
what actually discriminates one vendor from another (the shared `AI生成` tail is exactly
what does NOT discriminate -- see the rival-margin mechanism in _text_mark_engine).
Regenerate with: uv run python scripts/render_vendor_silhouettes.py
STATUS 2026-07-21: `qwen_alpha.png` IS registered (`qwen_engine.py`) -- the 2026-07-18
blocker quoted below turned out to be mis-sized GEOMETRY (two size modes + a locate box
that clipped the first glyph), not segmentation, and was solved by the TC260-producer
cohort harvest + `vendor_mark_calibrate.py` (117 labelled frames; full record in
`docs/verification-plan.md`). `xinghui_alpha.png` is still NOT registered: one confirmed
corpus example is nothing to calibrate a gate against.
--- the 2026-07-18 record, kept as the history of the failed first attempt ---
Measured on 14 hand-verified 千问 positives from the corpus,
the then-current detect architecture (top-hat glyph blob -> binary TM_CCOEFF_NORMED)
could not see this mark AT ALL:
same pipeline, each mark scored with its OWN template, on real positives
doubao n=40 mean NCC 0.723 median 0.835 >= 0.40 gate: 82%
qwen n=14 mean NCC 0.170 median 0.179 >= 0.40 gate: 0%
Three checks ruled out the obvious explanations, in order:
1. NOT the synthetic render. A template cut from an ACTUAL Qwen mark scores the same
as the font-rendered one (real-vs-real 0.307 vs synthetic 0.308) -- and real masks
do not even match EACH OTHER.
2. NOT the morphology kernel size. Scaling MORPH_OPEN/CLOSE with the box height (they
are fixed 5px, ~9% of a 57px-tall box) gained only +0.014 mean and moved nothing
across the gate.
3. NOT the appearance thresholds. Sweeping tophat_delta / logo_min_luma / kernel
reached at best mean 0.35 with 4/14 over the gate.
The blocker was named SEGMENTATION on a faint mark: Doubao is stamped bold and opaque,
so the white top-hat returns a clean glyph blob; the Qwen mark is a thin translucent
overlay that shatters into specks, and no template can match a blob that is not there.
The `tophat` front-end (built later, for doubao) removed that blocker -- and 千问 STILL
did not register, because the real residual was geometry. See the 2026-07-21 status
above.
星绘 additionally has only ONE confirmed example in the corpus, so even a working
front-end could not have its threshold calibrated yet.
UPDATE 2026-07-20: the named blocker is GONE, and the retry is still inconclusive.
`detect_frontend="tophat"` (built later, for doubao) is exactly the "grayscale correlation
on the raw top-hat" this note asked for, so the 2026-07-18 ruling rests on a premise that
no longer holds and must not simply be inherited. Two things were measured against it, and
neither settles the question:
* A GENERIC template of the shared `AI生成` tail -- attractive because GB 45438-2025
guarantees that run across vendors, so one template would cover 千问 / 百度 / 星绘 and
anything compliant that ships next. Measured on the tophat front-end at the shipped
3-rung ladder: a bold 千问 positive scores 0.407 against clean corners at p99 0.298 /
max 0.321. It separates on that one frame, but only by a hair, and a 4-glyph template
is inherently less specific than a 6-glyph one -- the shorter the run, the more
arbitrary corner structure correlates with it.
* The FULL 千问 template on the same front-end scores 0.248 against a clean max of 0.537,
i.e. no separation at all -- WORSE than the generic tail, which is the opposite of
what the specificity argument predicts and is itself a reason to distrust n=1.
The blocker is now EVIDENCE, not architecture: this session found exactly one 千问 and one
百度 positive (both by eyeballing doubao-provenance misses), and the 14 positives quoted
above were not preserved anywhere the current scripts can reach. Nothing should be
registered off a single frame.
UPDATE 2026-07-21 (the resolution): the evidence arrived via the TC260 producer-USCC
cohort trick (`scripts/vendor_cohort_harvest.py` -- 117 labelled 千问 frames from metadata
alone), and the registration shipped the same day (`qwen_engine.py`). The "no separation
at all" reading above was the MIS-SIZED geometry, not the mark: at the fitted geometry the
full template separates the cohort from clean corners 0.662 vs 0.134 (p50). The traps
below still bind any NEXT vendor: score with `alpha_height_frac`, not the silhouette's own
aspect ratio (the latter inflated the clean p99 from 0.30 to 0.58 and made every
comparison meaningless); keep the ladder at the shipped rungs for gate-setting, since a
wide sweep hands clean corners many extra chances to match; and re-filter the clean arm
per candidate -- the 2026-07-18 `present: []` labels mean "no REGISTERED mark", so qwen
-cohort frames visibly carrying 千问AI生成 sat in it (see `vendor_mark_calibrate.load_sets`).
"""
from __future__ import annotations
import sys
from pathlib import Path
from typing import Any
import numpy as np
from PIL import Image, ImageDraw, ImageFont
_ASSETS = Path(__file__).resolve().parents[1] / "src" / "remove_ai_watermarks" / "assets"
# STHeiti Medium approximates the semibold CJK sans these marks are set in; the exact
# family is unpublished for every vendor (GB 45438-2025 only requires a legible face).
_FONT = "/System/Library/Fonts/STHeiti Medium.ttc"
MARKS = {
"qwen_alpha.png": "千问AI生成",
"xinghui_alpha.png": "星绘AI生成",
# Yuanbao's stamp is a TWO-LINE block (元宝 over AI生成), left-aligned, tightly
# stacked and ITALIC-SLANTED (measured on the 2026-07-21 cohort sheet + real tophat
# responses); a rare one-line variant exists but the stacked block is dominant.
"yuanbao_alpha.png": "元宝\nAI生成",
# Kling (可灵) stamps a thin light-gray one-line "可灵AI 3.0" bottom-right (an
# "Omni" suffix variant and a latin "KlingAI 3.0" variant also exist; the CJK
# run without the suffix is the common core). The leading spiral logo is NOT
# rendered (logos vary; the text run discriminates).
"kling_alpha.png": "可灵AI 3.0",
# The "cat-logo" cohort (USCC 91110108562144110X) stamps an outline cat-head +
# bold "AI生成", bottom-right. PARKED 2026-07-21: the cohort is 19 copies of
# only 2 unique carriers -- nothing to calibrate recall against (the xinghui
# rule). The probe is ready: this silhouette scores 0.50 on the mark vs 0.333
# max on a diverse clean arm, so registration is a gate pick (0.42) the moment
# more unique carriers arrive.
"catlogo_alpha.png": "CATLOGO", # sentinel: drawn by draw_catlogo(), not font-rendered
# RunningHub (ComfyUI platform, USCC 91340100MAEB4N8H76, 73-frame cohort
# 2026-07-22): white one-line "RunningHub AI生成" text mark.
"runninghub_alpha.png": "RunningHub AI生成",
# LibLibAI / 哩布哩布AI (USCC 91110105MACJ6K1C8A, 15-frame cohort): white
# "LibLibAI" wordmark with a triangle logo (logo not rendered, logos vary).
"liblib_alpha.png": "LibLibAI",
# Zhipu Qingyan (USCC 91110108MA01KP2T5U, 7-frame cohort): white bold
# "清言·AI生成" with a circular logo (logo not rendered). PARKED 2026-07-22
# as a measured negative: on both front-ends the cohort scores 0.34-0.39
# against a clean-arm max of 0.34-0.37 -- no separation at any render/box
# setting (text-only and logo-composite templates both plateau ~0.34 raw;
# the white semi-transparent text on variable backgrounds is the wall).
# Silhouette stays as the starting point for a structural/learned lever.
"qingyan_alpha.png": "清言·AI生成",
# MiniMax / Hailuo (6-frame cohort): "MINIMAX" + "Hailuo AI" latin wordmarks.
# PARKED 2026-07-22: only 1 of the 6 cohort frames carries a visible mark --
# nothing to calibrate recall against (the xinghui rule). Registration is a
# gate pick once more unique carriers arrive.
"hailuo_alpha.png": "Hailuo AI",
# Baidu (USCC 91110000802100433B, 16-frame cohort): white bold "百度" text
# + a separate white rounded tag with dark "AI生成", bottom-right. Detection
# keys on the 百度 text run ONLY: a two-component template (text+pill) scored
# at clean-arm levels (pill = bright-blob magnet, clean p95 0.45-0.55 vs cohort
# ~0.5, no separation on either front-end, 2026-07-22); the text-only silhouette
# separates (cohort 0.39-0.65 vs clean max 0.352). The white tag is removed
# with the mark because the fill blob covers both bright components.
"baidu_alpha.png": "百度",
}
# Per-mark post-processing for the multi-line / slanted stamps (see render()).
MARK_OPTS: dict[str, dict[str, Any]] = {
# Fitted against real tophat responses on the Yuanbao cohort (2026-07-21): a
# right-aligned, gapped, unslanted render plateaued at ~0.34 NCC; left-align +
# tight gap + stroke dilation + shear -0.75 reaches 0.65-0.70 on the same frames,
# at/above the real-vs-real ceiling (~0.6).
"yuanbao_alpha.png": {"gap_frac": 0.05, "dilate": 2, "shear": -0.75},
# Qingyan's real stamp is a heavier weight than STHeiti Medium -- Hiragino
# Sans GB W6 matches the measured stroke (2026-07-22; with Medium the
# silhouette aspect came out 0.19 vs the real 0.28 and NCC plateaued ~0.3).
"qingyan_alpha.png": {"font": "/System/Library/Fonts/Hiragino Sans GB.ttc", "font_index": 2},
# LibLibAI's wordmark is set in an Arial-class grotesque, not STHeiti:
# measured 2026-07-22 across 7 candidate fonts, Arial lifts the cohort
# positives from 0.31-0.47 to 0.42-0.73 while the full-corpus false-fire arm
# DROPS to max 0.398 (generic latin UI text matches the wrong font less).
"liblib_alpha.png": {"font": "/System/Library/Fonts/Supplemental/Arial.ttf"},
}
def render(text: str, width: int = 335, opts: dict[str, Any] | None = None) -> np.ndarray:
"""Binary glyph silhouette (255 = glyph), sized to the doubao asset's convention.
Matching doubao's 335px asset width keeps the `alpha_*_frac` numbers transferable,
since these marks are the same house style and scale. A "\n" in ``text`` renders a
multi-line block: lines drawn left-aligned at one shared font size with a tight
gap, then optional stroke dilation and an italic shear (see MARK_OPTS).
"""
opts = opts or {}
gap_frac = float(opts.get("gap_frac", 0.15))
dilate = int(opts.get("dilate", 0))
shear_k = float(opts.get("shear", 0.0))
font_path = str(opts.get("font", _FONT))
font_index = int(opts.get("font_index", 0))
probe = Image.new("L", (10, 10))
d0 = ImageDraw.Draw(probe)
lines = text.split("\n")
size = 8
while size < 200: # grow until the LONGEST line fills the target width
f = ImageFont.truetype(font_path, size, index=font_index)
if max(d0.textbbox((0, 0), ln, font=f)[2] for ln in lines) >= width * 0.98:
break
size += 1
font = ImageFont.truetype(font_path, size, index=font_index)
boxes = [d0.textbbox((0, 0), ln, font=font) for ln in lines]
line_h = max(bb[3] - bb[1] for bb in boxes)
gap = max(1, int(line_h * gap_frac))
w = max(bb[2] - bb[0] for bb in boxes)
h = line_h * len(lines) + gap * (len(lines) - 1)
pad = max(2, int(line_h * 0.12))
im = Image.new("L", (w + 2 * pad, h + 2 * pad), 0)
draw = ImageDraw.Draw(im)
y = pad
for ln, bb in zip(lines, boxes, strict=True):
draw.text((pad - bb[0], y - bb[1]), ln, font=font, fill=255)
y += line_h + gap
sil = np.array(im)
if dilate or shear_k:
import cv2
if dilate:
sil = cv2.dilate(sil, np.ones((dilate, dilate), np.uint8))
if shear_k:
hh, ww = sil.shape
sil = cv2.warpAffine(sil, np.float32([[1, shear_k, 0], [0, 1, 0]]), (ww + int(abs(shear_k) * hh), hh))
return sil
def draw_catlogo(width: int = 335) -> np.ndarray:
"""The cat-logo mark: an outline cat-head (integrated pointy ears, two dot eyes)
+ a bold "AI生成" run, drawn synthetically from the measured layout (cat ~1.08x
the glyph height, stroke ~9%, gap ~35%). Proportions were iterated against a real
tophat response (2026-07-21): a solid filled head scored 0.35, this outline form
0.50 -- the parked probe, see MARKS."""
probe = Image.new("L", (10, 10))
d0 = ImageDraw.Draw(probe)
text = "AI生成"
size = 8
while size < 200:
f = ImageFont.truetype(_FONT, size)
if d0.textbbox((0, 0), text, font=f)[2] >= width * 0.60:
break
size += 1
font = ImageFont.truetype(_FONT, size)
bb = d0.textbbox((0, 0), text, font=font)
tw, th = bb[2] - bb[0], bb[3] - bb[1]
cs = int(th * 1.08)
stroke = max(2, int(th * 0.09))
gap = int(th * 0.35)
def head(s: int) -> Image.Image:
im = Image.new("L", (s, s), 0)
d = ImageDraw.Draw(im)
f = float(s)
pts = [
(0.12 * f, 0.95 * f),
(0.10 * f, 0.45 * f),
(0.12 * f, 0.30 * f),
(0.20 * f, 0.05 * f), # left ear tip
(0.40 * f, 0.24 * f), # left ear valley
(0.60 * f, 0.24 * f), # right ear valley
(0.80 * f, 0.05 * f), # right ear tip
(0.88 * f, 0.30 * f),
(0.90 * f, 0.45 * f),
(0.88 * f, 0.95 * f),
]
d.line([*pts, pts[0]], fill=255, width=stroke, joint="curve")
r = max(1.5, stroke * 0.7)
d.ellipse([0.35 * f - r, 0.60 * f - r, 0.35 * f + r, 0.60 * f + r], fill=255)
d.ellipse([0.65 * f - r, 0.60 * f - r, 0.65 * f + r, 0.60 * f + r], fill=255)
return im
w = cs + gap + tw
h = max(th, cs)
pad = max(2, int(h * 0.12))
im = Image.new("L", (w + 2 * pad, h + 2 * pad), 0)
im.paste(head(cs), (pad, pad + (h - cs) // 2))
ImageDraw.Draw(im).text((pad + cs + gap - bb[0], pad + (h - th) // 2 - bb[1]), text, font=font, fill=255)
return np.array(im)
def main() -> None:
try:
for name, text in MARKS.items():
sil = draw_catlogo() if text == "CATLOGO" else render(text, opts=MARK_OPTS.get(name))
Image.fromarray(sil).save(_ASSETS / name)
print(f"wrote {_ASSETS / name} ({sil.shape[1]}x{sil.shape[0]}) text={text!r}")
except OSError as e:
print(f"Font not found ({e}); install a CJK font or edit _FONT.", file=sys.stderr)
raise SystemExit(1) from e
if __name__ == "__main__":
main()
+156
View File
@@ -0,0 +1,156 @@
"""Tier B4: peak RSS and wall time per fill backend across input sizes.
WHY THIS EXISTS
The docs describe the backends in CAPABILITY prose -- "MI-GAN is the memory-tight pick",
"big-LaMa does not fit a minimal droplet", "~0.6-0.9 GB regardless of upload size". Those
numbers were measured once, informally, and are now load-bearing for a real deployment
decision (the free tier runs `migan`, the paid tier runs `lama`). This measures them.
WHAT IT MEASURES
For each (backend, input size): peak RSS of a FRESH process doing exactly one erase, and
the wall time. A fresh subprocess per measurement is the point -- peak RSS inside a
long-lived process is contaminated by whatever ran before it, and the question here is
what a per-request worker actually needs.
The mask is a fixed, small corner region at every size, because the claim under test is
that the learned backends crop around the mask and so their memory is bounded by the MARK
size, not the image size. If that holds, the curve is flat in input size; if it does not,
it climbs and the droplet sizing is wrong.
READING IT
RSS is the peak resident set of the whole worker, which includes the interpreter, numpy,
cv2 and (for the learned backends) onnxruntime plus the model. That is the honest number
for sizing a container -- not the model tensor alone.
DATA SAFETY
Generates its own synthetic inputs. Reads nothing from the corpus, writes nothing tracked.
uv run python scripts/resource_ceilings.py # cv2 + whatever is installed
uv run python scripts/resource_ceilings.py --max-mp 25 # push to 25 MP
"""
from __future__ import annotations
import argparse
import json
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent))
REPO = Path(__file__).resolve().parents[1]
_UV = shutil.which("uv") or "uv"
# (label, width, height) -- 1 MP up to 25 MP, the range a phone photo upload spans.
SIZES = (("1MP", 1000, 1000), ("4MP", 2000, 2000), ("12MP", 4000, 3000), ("25MP", 5000, 5000))
# The child process: build an image, erase one small corner region, report peak RSS.
# Kept as a string so each measurement is a genuinely fresh interpreter.
_CHILD = """
import json, resource, sys, time
import numpy as np
from remove_ai_watermarks.region_eraser import erase
w, h, backend = int(sys.argv[1]), int(sys.argv[2]), sys.argv[3]
rng = np.random.default_rng(0)
# Textured, not flat: a flat image compresses and can let a backend shortcut work.
img = rng.integers(0, 255, (h, w, 3), dtype=np.uint8)
box = (w - 320, h - 90, 300, 70) # a mark-sized corner region at every input size
t0 = time.monotonic()
try:
out = erase(img, boxes=[box], backend=backend)
# Assert the fill actually RAN. A wrong call signature or a silently-declining
# backend would otherwise report the process's numpy footprint as if it were the
# backend's cost -- the first version of this script did exactly that on all 12
# cells and the numbers looked plausible.
# Compare ONLY the mask box. A full-frame `(out != img).any()` allocates a boolean
# temp the size of the image BEFORE getrusage is read -- 75 MB at 25 MP, ~17% of the
# cv2 figure, and it GROWS with the input, so the harness would partly manufacture
# the very "cv2 scales with input size" conclusion it is measuring.
bx, by, bw_, bh_ = box
changed = int((out[by:by+bh_, bx:bx+bw_] != img[by:by+bh_, bx:bx+bw_]).any())
err = "" if changed else "NO-OP: backend did not modify the masked region"
except Exception as e:
err = f"{type(e).__name__}: {e}"[:200]
elapsed = time.monotonic() - t0
peak_kb = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
print("RESULT" + json.dumps({"peak_kb": peak_kb, "sec": round(elapsed, 2), "error": err}))
"""
def peak_rss_mb(peak_kb: int) -> float:
"""ru_maxrss is BYTES on macOS and KILOBYTES on Linux -- normalize to MB.
Getting this wrong silently reports 1024x off, which would look like a dramatic
finding rather than a unit bug.
"""
return peak_kb / (1024 * 1024) if sys.platform == "darwin" else peak_kb / 1024
def measure(backend: str, w: int, h: int, timeout: int = 900) -> dict[str, object] | None:
with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False) as fh:
fh.write(_CHILD)
child = fh.name
try:
p = subprocess.run( # noqa: S603 -- fixed argv, our own child script
[_UV, "run", "python", child, str(w), str(h), backend],
cwd=REPO,
capture_output=True,
text=True,
timeout=timeout,
check=False,
)
except subprocess.TimeoutExpired:
return {"error": f"TIMEOUT >{timeout}s", "sec": float(timeout), "peak_mb": float("nan")}
finally:
Path(child).unlink(missing_ok=True)
line = next((x for x in p.stdout.splitlines() if x.startswith("RESULT")), None)
if line is None:
return {"error": (p.stderr or p.stdout)[-200:], "sec": 0.0, "peak_mb": float("nan")}
data = json.loads(line[len("RESULT") :])
return {"error": data["error"], "sec": data["sec"], "peak_mb": round(peak_rss_mb(data["peak_kb"]), 1)}
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--max-mp", type=int, default=25, help="skip sizes above this megapixel count")
a = ap.parse_args()
from remove_ai_watermarks.region_eraser import lama_available, migan_available
backends = ["cv2"] + (["migan"] if migan_available() else []) + (["lama"] if lama_available() else [])
sizes = [s for s in SIZES if (s[1] * s[2]) / 1e6 <= a.max_mp + 0.5]
print(f"backends: {backends}\nsizes: {[s[0] for s in sizes]}")
print("\nOne FRESH process per cell; the mask is a fixed small corner at every size.")
print("If the learned backends really crop around the mask, RSS stays flat in input size.\n")
print(f"{'backend':8s} {'size':6s} {'peak RSS':>11s} {'wall':>8s} note")
rows: list[tuple[str, str, dict[str, object]]] = []
for backend in backends:
for label, w, h in sizes:
r = measure(backend, w, h)
if r is None:
continue
rows.append((backend, label, r))
note = str(r["error"])[:48] or "ok"
print(f"{backend:8s} {label:6s} {r['peak_mb']:8} MB {r['sec']:7}s {note}", flush=True)
print(f"\n{'=' * 72}\nRESOURCE CEILINGS\n{'=' * 72}")
for backend in backends:
cells = [(lbl, r) for b, lbl, r in rows if b == backend and not r["error"]]
if not cells:
continue
peaks = [float(r["peak_mb"]) for _, r in cells] # type: ignore[arg-type]
lo, hi = min(peaks), max(peaks)
growth = "flat in input size" if hi <= lo * 1.6 else f"GROWS {hi / max(lo, 0.1):.1f}x with input size"
print(f" {backend:6s} peak {lo:.0f}-{hi:.0f} MB across {cells[0][0]}..{cells[-1][0]} -- {growth}")
print("\nRSS is the whole worker (interpreter + numpy + cv2 + any model), i.e. the")
print("number to size a container with, not the model tensor alone.")
if __name__ == "__main__":
main()
+341
View File
@@ -0,0 +1,341 @@
"""Tier E: does the real CLI fail GRACEFULLY on adversarial and degenerate inputs?
WHAT "PASS" MEANS HERE
Not "it succeeded" -- most of these inputs SHOULD be rejected. A pass is a graceful
outcome: a clear message, a sane exit code, and **no unhandled traceback**, within the
timeout. The failure modes this is hunting are the ones a user actually hits and that no
unit test covers, because unit tests feed well-formed fixtures:
* an unhandled traceback -- the library crashed instead of reporting
* a hang -- worse than a crash for a batch caller
* a silent success on garbage -- it "processed" a corrupt file and wrote something
A non-zero exit with a readable error is a PASS. A Python traceback is a FAIL even when
the exit code looks tidy.
WHY THESE INPUTS
Every case is drawn from something real: ~0.2% of corpus uploads are truncated, ~2% carry
a mismatched extension, Unicode filenames were issue #17, and a wrapping service will run
concurrent jobs against one path. Decompression bombs and absurd geometry are the cheap
denial-of-service shapes any tool taking user uploads must survive.
DATA SAFETY
Builds its own inputs (synthetic, or truncated copies of committed fixtures) inside a
temp dir. Reads corpus images read-only for the one large-input case. Writes nothing
tracked.
uv run python scripts/robustness_suite.py
"""
from __future__ import annotations
import argparse
import os
import shutil
import stat
import subprocess
import sys
import tempfile
import zlib
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent))
REPO = Path(__file__).resolve().parents[1]
SAMPLES = REPO / "data" / "samples"
_UV = shutil.which("uv") or "uv"
# A traceback in the output means the failure escaped the error handling, whatever the
# exit code says.
_CRASH_MARKERS = ("Traceback (most recent call last)", "Fatal Python error", "Segmentation fault")
class Results:
def __init__(self) -> None:
self.rows: list[tuple[str, str, bool, str, str]] = []
def add(self, case: str, cmd: str, ok: bool, detail: str, output: str = "") -> None:
self.rows.append((case, cmd, ok, detail, "" if ok else output[-600:]))
print(f" [{'PASS' if ok else 'FAIL'}] {case:34s} {cmd:10s} {detail}", flush=True)
def report(self) -> int:
bad = [r for r in self.rows if not r[2]]
print(f"\n{'=' * 78}\nROBUSTNESS (Tier E) {len(self.rows) - len(bad)}/{len(self.rows)} graceful")
print(f"{'=' * 78}")
for case, cmd, ok, detail, out in self.rows:
if not ok:
print(f" FAIL {case} ({cmd}) {detail}")
for line in out.strip().splitlines()[-10:]:
print(f" {line}")
if not bad:
print(" every adversarial input was handled without a crash or a hang")
return 1 if bad else 0
def run(args: list[str], timeout: int = 120) -> tuple[int, str, bool]:
"""Returns (exit_code, output, timed_out)."""
try:
p = subprocess.run( # noqa: S603 -- fixed argv, driving our own CLI on purpose
[_UV, "run", "remove-ai-watermarks", *args],
cwd=REPO,
capture_output=True,
text=True,
timeout=timeout,
check=False,
)
except subprocess.TimeoutExpired:
return (-1, "", True)
return (p.returncode, p.stdout + p.stderr, False)
def graceful(res: Results, case: str, cmd: str, args: list[str], timeout: int = 120) -> None:
"""Run one adversarial case and score it on gracefulness, not on success."""
code, out, timed_out = run(args, timeout=timeout)
if timed_out:
res.add(case, cmd, False, f"HUNG (> {timeout}s)", out)
return
crashed = next((m for m in _CRASH_MARKERS if m in out), None)
if crashed:
res.add(case, cmd, False, f"unhandled {crashed} (exit {code})", out)
return
res.add(case, cmd, True, f"handled cleanly, exit {code}")
def make_inputs(tmp: Path) -> dict[str, Path]:
"""Build the adversarial corpus. Each entry is something a real upload can be."""
import numpy as np
from remove_ai_watermarks.image_io import imwrite
made: dict[str, Path] = {}
# A well-formed baseline, so a failure elsewhere is attributable to the input.
good = tmp / "good.png"
imwrite(good, np.full((600, 800, 3), 128, np.uint8))
made["good"] = good
# Truncated: a real PNG cut mid-stream (~0.2% of real uploads).
src = SAMPLES / "chatgpt-1.png"
if src.exists():
raw = src.read_bytes()
trunc = tmp / "truncated.png"
trunc.write_bytes(raw[: len(raw) // 3])
made["truncated"] = trunc
# Corrupt: correct magic bytes, garbage body.
corrupt = tmp / "corrupt.png"
corrupt.write_bytes(b"\x89PNG\r\n\x1a\n" + os.urandom(4096))
made["corrupt"] = corrupt
# Zero-byte file with a valid extension.
empty = tmp / "empty.png"
empty.write_bytes(b"")
made["empty"] = empty
# Not an image at all, but named like one.
text = tmp / "actually_text.jpg"
text.write_bytes(b"this is not an image, it is a text file pretending\n" * 50)
made["not_an_image"] = text
# Degenerate geometry: a 1x1, and a 1-pixel-tall sliver (the shape that once faulted
# cv2's GaussianBlur natively on Windows).
imwrite(tmp / "tiny.png", np.full((1, 1, 3), 200, np.uint8))
made["tiny_1x1"] = tmp / "tiny.png"
imwrite(tmp / "sliver.png", np.full((1, 4000, 3), 200, np.uint8))
made["sliver_1x4000"] = tmp / "sliver.png"
# Decompression bomb: a tiny file that decodes to a huge canvas. Hand-built so the
# on-disk size stays trivial while the declared dimensions are enormous.
bomb = tmp / "bomb.png"
bomb.write_bytes(_png_bomb(16000, 16000))
made["decompression_bomb"] = bomb
# Unicode + RTL filenames (issue #17 was Unicode-safe IO).
uni = tmp / "изображение-测试-🎨.png"
shutil.copy2(good, uni)
made["unicode_filename"] = uni
rtl = tmp / "صورة-اختبار.png"
shutil.copy2(good, rtl)
made["rtl_filename"] = rtl
# Mismatched extension: PNG content named .jpg (~2% of real uploads).
mismatch = tmp / "png_named_jpg.jpg"
shutil.copy2(good, mismatch)
made["mismatched_extension"] = mismatch
return made
def _png_bomb(w: int, h: int) -> bytes:
"""A valid PNG header declaring a huge canvas over highly-compressible data."""
def chunk(tag: bytes, data: bytes) -> bytes:
return len(data).to_bytes(4, "big") + tag + data + zlib.crc32(tag + data).to_bytes(4, "big")
ihdr = w.to_bytes(4, "big") + h.to_bytes(4, "big") + bytes([8, 2, 0, 0, 0]) # 8-bit RGB
raw = b"".join(b"\x00" + b"\x00" * (w * 3) for _ in range(h))
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(raw, 9)) + chunk(b"IEND", b"")
def check_bad_inputs(res: Results, tmp: Path, inputs: dict[str, Path]) -> None:
print("\nmalformed and degenerate inputs -- every command must refuse, not crash")
out = tmp / "out.png"
for case in ("truncated", "corrupt", "empty", "not_an_image", "tiny_1x1", "sliver_1x4000"):
src = inputs.get(case)
if src is None:
continue
graceful(res, case, "identify", ["identify", str(src)])
graceful(res, case, "visible", ["visible", str(src), "-o", str(out)])
graceful(res, case, "metadata", ["metadata", str(src), "--check"])
def check_bomb(res: Results, tmp: Path, inputs: dict[str, Path]) -> None:
print("\ndecompression bomb -- must not exhaust memory or hang")
bomb = inputs.get("decompression_bomb")
if bomb is None:
return
size_kb = bomb.stat().st_size / 1024
print(f" (bomb is {size_kb:.0f} KB on disk, declares 16000x16000)")
graceful(res, "decompression_bomb", "identify", ["identify", str(bomb)], timeout=180)
graceful(res, "decompression_bomb", "visible", ["visible", str(bomb), "-o", str(tmp / "b.png")], timeout=180)
def check_filenames(res: Results, tmp: Path, inputs: dict[str, Path]) -> None:
"""Unicode/RTL paths must round-trip on BOTH read and write (issue #17)."""
print("\nunicode / RTL / mismatched-extension paths")
for case in ("unicode_filename", "rtl_filename", "mismatched_extension"):
src = inputs.get(case)
if src is None:
continue
# Write to a Unicode OUTPUT path too -- the read side alone does not prove the IO.
outp = tmp / f"вывод-{case}-📤.png"
code, out, timed = run(["identify", str(src)])
if timed or any(m in out for m in _CRASH_MARKERS):
res.add(case, "identify", False, "crashed or hung", out)
else:
res.add(case, "identify", True, f"read fine, exit {code}")
code, out, timed = run(["erase", str(src), "--region", "5,5,50,30", "-o", str(outp)])
wrote = outp.exists() and outp.stat().st_size > 0
crash = any(m in out for m in _CRASH_MARKERS)
res.add(case, "erase", wrote and not crash and not timed, f"unicode output written={wrote} exit={code}", out)
def check_output_paths(res: Results, tmp: Path, inputs: dict[str, Path]) -> None:
print("\nhostile output paths")
good = inputs["good"]
# A nested output dir that does not exist yet -- the CLI should create it.
nested = tmp / "a" / "b" / "c" / "out.png"
code, out, timed = run(["erase", str(good), "--region", "5,5,40,20", "-o", str(nested)])
crash = any(m in out for m in _CRASH_MARKERS)
res.add(
"nonexistent_nested_outdir",
"erase",
nested.exists() and not crash and not timed,
f"created={nested.exists()} exit={code}",
out,
)
# A READ-ONLY output directory -- must report, not traceback.
ro = tmp / "readonly"
ro.mkdir(exist_ok=True)
ro.chmod(stat.S_IRUSR | stat.S_IXUSR)
try:
graceful(
res, "readonly_output_dir", "erase", ["erase", str(good), "--region", "5,5,40,20", "-o", str(ro / "x.png")]
)
finally:
ro.chmod(stat.S_IRWXU) # restore so the temp dir can be cleaned up
# A directory where a file is expected.
graceful(res, "directory_as_input", "identify", ["identify", str(tmp)])
# A path that simply is not there.
graceful(res, "missing_input", "identify", ["identify", str(tmp / "nope.png")])
def check_concurrency(res: Results, tmp: Path, inputs: dict[str, Path]) -> None:
"""A wrapping service will run jobs in parallel against one input path."""
print("\nconcurrent runs against a single input")
good = inputs["good"]
def one(i: int) -> tuple[int, str, bool]:
return run(["erase", str(good), "--region", "5,5,40,20", "-o", str(tmp / f"conc_{i}.png")])
with ThreadPoolExecutor(max_workers=4) as ex:
outs = list(ex.map(one, range(4)))
crashed = [o for o in outs if any(m in o[1] for m in _CRASH_MARKERS) or o[2]]
all_written = all((tmp / f"conc_{i}.png").exists() for i in range(4))
res.add(
"4x concurrent on one input",
"erase",
not crashed and all_written,
f"{sum(1 for i in range(4) if (tmp / f'conc_{i}.png').exists())}/4 outputs, {len(crashed)} crashed",
"".join(o[1] for o in crashed),
)
def check_batch_silent_loss(res: Results, tmp: Path, inputs: dict[str, Path]) -> None:
"""The nastiest shape: NO output files AND a success exit code.
`graceful()` cannot see this class -- it scores exit code and traceback markers, and a
run that writes nothing while exiting 0 has neither. Corpus-reproduced 2026-07-20:
`batch --mode visible` into a read-only directory wrote 0 of 2 files and exited 0, so a
wrapping service would treat an empty output directory as a completed run. Any check
for a silent no-op must assert on the ARTIFACTS, not on the status.
"""
print("\nbatch into a read-only output dir -- must NOT exit 0 with nothing written")
indir = tmp / "loss_in"
indir.mkdir(exist_ok=True)
for i in range(2):
shutil.copy2(inputs["good"], indir / f"img{i}.png")
ro = tmp / "loss_out"
ro.mkdir(exist_ok=True)
ro.chmod(stat.S_IRUSR | stat.S_IXUSR)
try:
code, out, timed = run(["batch", str(indir), "-o", str(ro)], timeout=180)
written = len(list(ro.glob("*")))
finally:
ro.chmod(stat.S_IRWXU)
ok = not timed and not (code == 0 and written == 0)
res.add(
"batch_readonly_outdir", "batch", ok, f"exit {code}, {written}/2 written (exit 0 + 0 files = data loss)", out
)
def check_batch_edges(res: Results, tmp: Path) -> None:
print("\nbatch edge cases")
empty_dir = tmp / "empty_dir"
empty_dir.mkdir(exist_ok=True)
graceful(res, "batch_on_empty_dir", "batch", ["batch", str(empty_dir), "-o", str(tmp / "bo")])
# A directory of junk: nothing decodable, must not crash the whole run.
junk = tmp / "junk_dir"
junk.mkdir(exist_ok=True)
(junk / "a.png").write_bytes(b"\x89PNG\r\n\x1a\n" + os.urandom(500))
(junk / "b.jpg").write_bytes(b"not an image at all")
graceful(res, "batch_on_undecodable_dir", "batch", ["batch", str(junk), "-o", str(tmp / "jo")], timeout=180)
def main() -> None:
ap = argparse.ArgumentParser()
ap.parse_args()
res = Results()
with tempfile.TemporaryDirectory(prefix="raiw_robust_") as td:
tmp = Path(td)
print("building adversarial inputs...")
inputs = make_inputs(tmp)
print(f"built {len(inputs)} inputs\n")
check_bad_inputs(res, tmp, inputs)
check_bomb(res, tmp, inputs)
check_filenames(res, tmp, inputs)
check_output_paths(res, tmp, inputs)
check_concurrency(res, tmp, inputs)
check_batch_silent_loss(res, tmp, inputs)
check_batch_edges(res, tmp)
raise SystemExit(res.report())
if __name__ == "__main__":
main()
File diff suppressed because it is too large. Load diff
+216
View File
@@ -0,0 +1,216 @@
"""Tier A1: diff today's `identify` against the verdicts recorded in the corpus sidecars.
`data/spaces/identify/<day>/<uid>.json` holds the verdict a past run produced for
`data/spaces/originals/<day>/<uid>_src.<ext>`. Re-running identify and diffing turns the
corpus into a ~39k-image behavioral regression suite that needs no new labelling.
WHAT A DIFF MEANS -- READ THIS BEFORE PANICKING
The sidecars were written by OLDER versions, so an intended improvement shows up as a
diff exactly like a regression does. The output is therefore CLASSIFIED, not pass/fail:
lost_ai verdict was AI, now is not <- the alarm; almost always a bug
lost_signal a signal family stopped firing <- the alarm
new_ai verdict was not AI, now is <- usually an improvement
new_signal a signal family started firing <- usually an improvement
platform attribution changed
confidence confidence level changed
unchanged identical on every compared axis
Only `lost_*` is a regression by default. Everything else needs a look before the
baseline is moved.
WHY FAMILIES, NOT RAW STRINGS
Watermark descriptions are human-readable prose and their WORDING has changed between
versions ("C2PA Content Credentials (OpenAI)" vs "... (OpenAI, Truepic)"). Diffing raw
strings would report every rewording as a lost+new signal pair and bury the real
regressions. Signals are normalized to families (c2pa, synthid, visible_sparkle, ...)
so the comparison tracks BEHAVIOR, not phrasing.
DATA SAFETY
Corpus images are user uploads: read-only, local analysis. Output goes to a gitignored
path under data/spaces/ and records uids, never image content.
uv run python scripts/sidecar_regression.py --sample 500 # representative trial
uv run python scripts/sidecar_regression.py # full corpus, resumable
Use `--sample` for a trial, never `--limit`: the sidecar list is sorted by day, so
`--limit N` reads only the EARLIEST day and its result does not generalize (the first
trial run of this script took 200 files that were all 2026-05-29).
"""
from __future__ import annotations
import argparse
import collections
import glob
import json
import os
import random
import sys
from concurrent.futures import ProcessPoolExecutor, as_completed
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent))
REPO = Path(__file__).resolve().parents[1]
IDENTIFY_DIR = REPO / "data" / "spaces" / "identify"
ORIGINALS = REPO / "data" / "spaces" / "originals"
OUT = REPO / "data" / "spaces" / "_sidecar_regression.jsonl"
# Map a watermark description to a stable behavior family. Order matters: the first
# matching pattern wins, so put the specific tokens above the generic ones.
_FAMILIES: tuple[tuple[str, tuple[str, ...]], ...] = (
("synthid", ("synthid",)),
("visible_sparkle", ("sparkle",)),
("visible_doubao", ("豆包", "doubao")),
("visible_jimeng", ("即梦", "jimeng")),
("visible_samsung", ("galaxy ai", "generati dall")),
("aigc_tc260", ("aigc", "tc260")),
("iptc", ("iptc", "digitalsourcetype", "made with ai", "made-with-ai")),
("c2pa", ("c2pa", "content credentials")),
("trustmark", ("trustmark",)),
("open_invisible", ("open invisible", "dwt", "stable diffusion xl")),
("xai_signature", ("xai", "grok signature")),
("exif_generator", ("exif", "software tag", "png text")),
)
def family_of(description: str) -> str:
low = description.lower()
for name, tokens in _FAMILIES:
if any(t in low for t in tokens):
return name
return "other"
def families(descriptions: list[str]) -> set[str]:
return {family_of(d) for d in descriptions or []}
def compare(sidecar: dict, report: object) -> dict:
"""Classify the difference between a recorded verdict and a fresh one."""
old_ai, new_ai = sidecar.get("is_ai_generated"), getattr(report, "is_ai_generated", None)
old_fam = families(sidecar.get("watermarks") or [])
new_fam = families(list(getattr(report, "watermarks", []) or []))
old_plat, new_plat = sidecar.get("platform"), getattr(report, "platform", None)
old_conf, new_conf = sidecar.get("confidence"), getattr(report, "confidence", None)
classes: list[str] = []
# Treat only a real True->not-True transition as lost. None means "unknown", and the
# library never asserts False, so None->None is not a change.
if bool(old_ai) and not bool(new_ai):
classes.append("lost_ai")
if not bool(old_ai) and bool(new_ai):
classes.append("new_ai")
if old_fam - new_fam:
classes.append("lost_signal")
if new_fam - old_fam:
classes.append("new_signal")
if old_plat != new_plat:
classes.append("platform")
if old_conf != new_conf:
classes.append("confidence")
return {
"classes": classes or ["unchanged"],
"old_ai": old_ai,
"new_ai": new_ai,
"lost_families": sorted(old_fam - new_fam),
"new_families": sorted(new_fam - old_fam),
"old_platform": old_plat,
"new_platform": new_plat,
"old_confidence": old_conf,
"new_confidence": new_conf,
}
def _one(sidecar_path: str) -> dict:
uid = os.path.basename(sidecar_path)[:-5]
day = os.path.basename(os.path.dirname(sidecar_path))
try:
with open(sidecar_path, encoding="utf-8") as fh:
sidecar = json.load(fh)
except Exception as e: # a corrupt sidecar must not kill the sweep
return {"uid": uid, "day": day, "status": "sidecar_unreadable", "error": str(e)[:200]}
src = sidecar.get("src") or ""
image = ORIGINALS / day / src
if not src or not image.exists():
found = glob.glob(str(ORIGINALS / day / f"{uid}*"))
if not found:
return {"uid": uid, "day": day, "status": "image_missing"}
image = Path(found[0])
try:
from remove_ai_watermarks.identify import identify
report = identify(image)
except Exception as e: # record and continue; a crash IS a finding
return {"uid": uid, "day": day, "status": "identify_raised", "error": f"{type(e).__name__}: {e}"[:300]}
return {"uid": uid, "day": day, "status": "ok", **compare(sidecar, report)}
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--limit", type=int, default=0, help="only N sidecars (trial run)")
ap.add_argument(
"--sample",
type=int,
default=0,
help="randomly sample N across ALL days -- use this for a trial, not --limit: "
"the sidecar list is sorted, so --limit takes one day and is not representative",
)
ap.add_argument("--workers", type=int, default=max(1, (os.cpu_count() or 4) - 2))
ap.add_argument("--out", type=Path, default=OUT)
ap.add_argument("--restart", action="store_true", help="ignore existing output and start over")
a = ap.parse_args()
sidecars = sorted(glob.glob(str(IDENTIFY_DIR / "*" / "*.json")))
if a.sample:
random.Random(7).shuffle(sidecars) # noqa: S311 -- deterministic sampling, not crypto
sidecars = sorted(sidecars[: a.sample])
elif a.limit:
sidecars = sidecars[: a.limit]
if not sidecars:
raise SystemExit(f"no sidecars under {IDENTIFY_DIR}")
# Resume: a full sweep is ~1 h, so never redo work an interrupted run already did.
done: set[str] = set()
if a.restart and a.out.exists():
a.out.unlink() # --restart must TRUNCATE; the file is reopened in append mode below
if a.out.exists() and not a.restart:
with open(a.out, encoding="utf-8") as fh:
for line in fh:
try:
done.add(json.loads(line)["uid"])
except Exception: # noqa: S112 -- tolerate a torn last line from an interrupted run
continue
todo = [s for s in sidecars if os.path.basename(s)[:-5] not in done]
print(f"sidecars {len(sidecars)} already done {len(done)} to do {len(todo)} workers {a.workers}")
counts: collections.Counter[str] = collections.Counter()
a.out.parent.mkdir(parents=True, exist_ok=True)
with open(a.out, "a", encoding="utf-8") as fh, ProcessPoolExecutor(max_workers=a.workers) as ex:
futures = {ex.submit(_one, s): s for s in todo}
for i, fut in enumerate(as_completed(futures), 1):
rec = fut.result()
fh.write(json.dumps(rec, ensure_ascii=False) + "\n")
if rec["status"] != "ok":
counts[rec["status"]] += 1
else:
for c in rec["classes"]:
counts[c] += 1
if i % 500 == 0:
fh.flush()
print(f" {i}/{len(todo)} " + " ".join(f"{k}={v}" for k, v in counts.most_common(6)), flush=True)
print(f"\n{'=' * 70}\nSIDECAR REGRESSION processed={len(todo)}\n{'=' * 70}")
for k, v in counts.most_common():
flag = " <-- REGRESSION" if k.startswith("lost_") or k in ("identify_raised",) else ""
print(f" {k:22s} {v:7d}{flag}")
print(f"\nfull records: {a.out}")
if __name__ == "__main__":
main()
+621
View File
@@ -0,0 +1,621 @@
"""Release smoke matrix: exercise every CLI parameter CHOICE on REAL data.
Run before a release. This is not a unit-test substitute -- it drives the real CLI as a
subprocess, so it covers argument parsing, exit-code semantics and the file-writing
contracts that unit tests with fakes cannot.
WHAT IT COVERS AND WHY THAT SHAPE
* Every choice-valued flag at least once (`--backend`, `--sensitivity`, `--mark`,
`--mode`, `--inpaint-method`, ...). Full permutation is combinatorially large and
mostly meaningless; dead branches and typos hide in the CHOICES, not in their
products.
* Every input FORMAT and shape edge case through the pixel paths -- PNG/JPEG/WebP/
HEIC/AVIF, alpha, unicode names, misnamed extensions, truncated files, tiny and
landscape frames. Real-world breakage lives here far more than in flag combos.
* CONTRACTS, not just exit codes: `visible` must write NO output and exit 2 when no
mark is found (re-serving the input reads as success -- the recurring "it didn't
work" report); a no-op must be byte-identical; `metadata --remove` must actually
strip; a JPEG strip must not touch the pixels. Note the pixel-lossless contract is
the DEFAULT path's -- `--remove-all` deliberately re-encodes (see metadata.py).
* The diffusion bodies under `--diffusion`, at `--max-resolution 512` so they fit MPS
(~1 min/image on 32 GB unified memory). Not just exit codes: `invisible` must
restore the input resolution and must NOT re-stamp SDXL's own open watermark.
WHAT IT DOES NOT COVER, DELIBERATELY AND LOUDLY
* Without `--diffusion`, the model-running bodies are reported as SKIPPED with a
reason, never as passes -- a green run that quietly skipped half the surface is
worse than a red one.
* Removal STRENGTH is never certified here. Whether a watermark is actually gone
needs the per-vendor oracles (docs/known-limitations.md); these rows prove the
paths run and keep their contracts, nothing more.
* The re-embed row is gated on a POSITIVE CONTROL. imwatermark is positive-only and
fails to round-trip on some pristine carriers, so "no watermark found" proves
nothing there; the row degrades to a skip rather than a false pass.
uv run python scripts/smoke_matrix.py # corpus + fixtures
uv run python scripts/smoke_matrix.py --quick # fixtures only, no corpus
uv run python scripts/smoke_matrix.py --diffusion # + the SDXL model paths
"""
from __future__ import annotations
import argparse
import json
import random
import shutil
import subprocess
import tempfile
from dataclasses import dataclass, field
from pathlib import Path
REPO = Path(__file__).resolve().parents[1]
SAMPLES = REPO / "data" / "samples"
CORPUS = REPO / "data" / "spaces" / "originals"
EXIT_NO_VISIBLE_MARK = 2
def _capture(args: list[str]) -> str:
"""Run the CLI and return stdout (for the rows that inspect output, not exit code)."""
exe = shutil.which("uv") or "uv"
p = subprocess.run( # noqa: S603
[exe, "run", "remove-ai-watermarks", *args], capture_output=True, text=True, cwd=REPO, check=False
)
return p.stdout
@dataclass
class Result:
name: str
status: str # pass | FAIL | skip
detail: str = ""
cmd: str = ""
@dataclass
class Runner:
tmp: Path
results: list[Result] = field(default_factory=list)
def run(self, name: str, args: list[str], *, expect_exit: int | None = 0, timeout: int = 180) -> Result:
exe = shutil.which("uv") or "uv"
cmd = [exe, "run", "remove-ai-watermarks", *args]
try:
p = subprocess.run( # noqa: S603
cmd, capture_output=True, text=True, timeout=timeout, cwd=REPO, check=False
)
except subprocess.TimeoutExpired:
r = Result(name, "FAIL", f"timeout after {timeout}s", " ".join(args))
self.results.append(r)
return r
ok = expect_exit is None or p.returncode == expect_exit
detail = "" if ok else f"exit {p.returncode} (want {expect_exit}): {(p.stderr or p.stdout).strip()[-200:]}"
r = Result(name, "pass" if ok else "FAIL", detail, " ".join(args))
self.results.append(r)
return r
def check(self, name: str, ok: bool, detail: str = "") -> None:
self.results.append(Result(name, "pass" if ok else "FAIL", "" if ok else detail))
def skip(self, name: str, why: str) -> None:
self.results.append(Result(name, "skip", why))
def corpus_pick(n: int, suffixes: tuple[str, ...]) -> list[Path]:
"""Real uploads, chosen deterministically so a failure is reproducible."""
if not CORPUS.exists():
return []
pool = [p for p in CORPUS.glob("*/*") if p.suffix.lower() in suffixes]
random.Random(7).shuffle(pool) # noqa: S311 -- deterministic sampling, not cryptography
return pool[:n]
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--quick", action="store_true", help="fixtures only; skip the corpus rows")
ap.add_argument(
"--diffusion", action="store_true", help="also run the model-running paths (SDXL weights, ~1 min/image)"
)
a = ap.parse_args()
tmp = Path(tempfile.mkdtemp(prefix="raiw-smoke-"))
r = Runner(tmp)
doubao = SAMPLES / "doubao-1.png"
chatgpt = SAMPLES / "chatgpt-1.png"
grok = SAMPLES / "grok-1.jpg"
# ---- identify: every flag, and JSON must actually parse -------------------
r.run("identify plain", ["identify", str(doubao)])
r.run("identify --no-visible", ["identify", str(doubao), "--no-visible"])
try:
json.loads(_capture(["identify", str(doubao), "--json"]))
r.check("identify --json parses", True)
except Exception as e:
r.check("identify --json parses", False, str(e))
# ---- metadata: check/remove, and the strip must be REAL ------------------
r.run("metadata --check", ["metadata", str(doubao), "--check"])
out = tmp / "meta.png"
r.run("metadata --remove", ["metadata", str(doubao), "--remove", "-o", str(out)])
if out.exists():
try:
rep = json.loads(_capture(["identify", str(out), "--json"]))
# Scope the assert to METADATA. doubao-1 also carries a visible pixel mark,
# which `metadata --remove` must NOT touch -- demanding an empty watermark
# list would fail on correct behavior (and hide a real metadata leak behind
# a permanently-red row).
leftover = [s for s in rep.get("signals", []) if not s.get("name", "").startswith("visible_")]
r.check(
"metadata --remove strips every metadata signal",
not leftover and not rep.get("ai_from_metadata"),
f"still reports metadata signals {[s.get('name') for s in leftover]}",
)
r.check(
"metadata --remove leaves the visible mark alone",
any(s.get("name", "").startswith("visible_") for s in rep.get("signals", [])),
"the pixel mark vanished -- a metadata strip must not touch pixels",
)
except Exception as e:
r.check("metadata --remove strips every metadata signal", False, str(e))
# The pixel-lossless contract belongs to the DEFAULT path. `--remove-all`
# (keep_standard=False) deliberately falls through to the full PIL re-encode
# (metadata.py: the lossless marker walk preserves standard segments, so it cannot
# serve a strip-everything caller), which is lossy for JPEG -- measured ~49 dB.
# Asserting losslessness there tested a contract the code never made.
import numpy as np
from remove_ai_watermarks.image_io import imread
out2 = tmp / "meta2.jpg"
r.run("metadata --remove (jpeg, default)", ["metadata", str(grok), "--remove", "-o", str(out2)])
if out2.exists():
a_, b_ = imread(str(grok)), imread(str(out2))
same = a_ is not None and b_ is not None and a_.shape == b_.shape and bool(np.array_equal(a_, b_))
r.check("jpeg metadata strip is pixel-lossless", same, "pixels changed -- the strip re-encoded")
out3 = tmp / "meta3.jpg"
r.run("metadata --remove --remove-all (jpeg)", ["metadata", str(grok), "--remove", "--remove-all", "-o", str(out3)])
if out3.exists():
rep3 = json.loads(_capture(["identify", str(out3), "--json"]))
r.check(
"--remove-all strips the AI metadata too",
not [s for s in rep3.get("signals", []) if not s.get("name", "").startswith("visible_")],
f"still reports {rep3.get('signals')}",
)
# ---- visible: every --mark choice, every --backend, every --sensitivity ---
for mark in ("auto", "gemini", "doubao", "jimeng", "samsung", "jimeng_pill"):
# doubao-1 carries only the doubao mark, so every other --mark must exit 2
want = 0 if mark in ("auto", "doubao") else EXIT_NO_VISIBLE_MARK
r.run(
f"visible --mark {mark}",
["visible", str(doubao), "--mark", mark, "-o", str(tmp / f"m_{mark}.png")],
expect_exit=want,
)
# Every backend CHOICE, not just the two that need no extra. migan/lama were
# measured at library level (scripts/fill_quality.py) but had never been driven
# through the CLI, which is a different code path (resolve_backend + the warning).
from remove_ai_watermarks.region_eraser import lama_available, migan_available
for backend in ("auto", "cv2", "migan", "lama"):
have = {"migan": migan_available(), "lama": lama_available()}.get(backend, True)
if not have:
r.skip(f"visible --backend {backend}", f"the `{backend}` extra is not installed")
continue
r.run(
f"visible --backend {backend}",
["visible", str(doubao), "--backend", backend, "-o", str(tmp / f"b_{backend}.png")],
timeout=600,
)
for sens in ("auto", "strict"):
r.run(
f"visible --sensitivity {sens}",
["visible", str(doubao), "--sensitivity", sens, "-o", str(tmp / f"s_{sens}.png")],
)
r.run("visible --keep-metadata", ["visible", str(doubao), "--keep-metadata", "-o", str(tmp / "keep.png")])
r.run("visible --no-detect (forced)", ["visible", str(doubao), "--no-detect", "-o", str(tmp / "force.png")])
for removed in ("assume-ai", "aggressive"):
r.run(
f"visible rejects --sensitivity {removed}",
["visible", str(doubao), "--sensitivity", removed],
expect_exit=2,
)
# CONTRACT: no mark -> no output file, exit 2 (never re-serve the input as success)
noout = tmp / "must_not_exist.png"
r.run("visible no-mark exits 2", ["visible", str(chatgpt), "-o", str(noout)], expect_exit=EXIT_NO_VISIBLE_MARK)
r.check("visible no-mark writes NO output", not noout.exists(), "wrote an output for an undetected mark")
# ---- erase: backends, methods, repeated regions, dilate ------------------
for method in ("telea", "ns"):
r.run(
f"erase --inpaint-method {method}",
[
"erase",
str(doubao),
"--region",
"10,10,60,30",
"--inpaint-method",
method,
"-o",
str(tmp / f"e_{method}.png"),
],
)
r.run(
"erase repeated --region",
["erase", str(doubao), "--region", "10,10,40,20", "--region", "80,80,40,20", "-o", str(tmp / "e_multi.png")],
)
r.run(
"erase --dilate",
["erase", str(doubao), "--region", "10,10,40,20", "--dilate", "5", "-o", str(tmp / "e_dil.png")],
)
for backend in ("cv2", "migan", "lama"):
have = {"migan": migan_available(), "lama": lama_available()}.get(backend, True)
if not have:
r.skip(f"erase --backend {backend}", f"the `{backend}` extra is not installed")
continue
r.run(
f"erase --backend {backend}",
[
"erase",
str(doubao),
"--region",
"10,10,40,20",
"--backend",
backend,
"-o",
str(tmp / f"e_{backend}.png"),
],
timeout=600,
)
r.run(
"erase --dilate 0 (no dilation)",
["erase", str(doubao), "--region", "10,10,40,20", "--dilate", "0", "-o", str(tmp / "e_d0.png")],
)
r.run("erase rejects a malformed --region", ["erase", str(doubao), "--region", "not,a,box"], expect_exit=2)
# ---- global + explicit-default flags that had never been exercised -------
r.run("--verbose", ["--verbose", "identify", str(doubao)])
r.run("--version", ["--version"])
r.run("metadata --keep-standard (explicit)", ["metadata", str(doubao), "--check", "--keep-standard"])
r.run(
"visible --strip-metadata (explicit)",
["visible", str(doubao), "--strip-metadata", "-o", str(tmp / "sm.png")],
)
r.run("visible --detect (explicit default)", ["visible", str(doubao), "--detect", "-o", str(tmp / "det.png")])
# ---- batch: the non-diffusion modes -------------------------------------
bd = tmp / "batch_in"
bd.mkdir()
for f in (doubao, chatgpt):
shutil.copy(f, bd / f.name)
for mode in ("visible", "metadata"):
r.run(
f"batch --mode {mode}",
["batch", str(bd), "--mode", mode, "-o", str(tmp / f"batch_{mode}")],
expect_exit=None,
)
# ---- diffusion: argument handling always; the model body under --diffusion ----
r.run("invisible --help parses full knob set", ["invisible", "--help"])
r.run("all --help parses full knob set", ["all", "--help"])
_media_rows(r, tmp)
if a.diffusion:
_diffusion_rows(r, tmp, doubao)
else:
for name in ("invisible", "all", "batch --mode invisible"):
r.skip(f"{name} (model-running body)", "pass --diffusion to exercise it (needs the SDXL weights)")
# ---- real-data formats and shapes ---------------------------------------
if not a.quick:
picks: list[tuple[str, Path]] = []
for suf, label in ((".heic", "heic"), (".avif", "avif"), (".webp", "webp"), (".jpeg", "jpeg")):
picks += [(label, p) for p in corpus_pick(2, (suf,))]
picks += [("png", p) for p in corpus_pick(3, (".png",))]
if not picks:
r.skip("real-format rows", "corpus not present (data/spaces/originals)")
for label, p in picks:
r.run(f"identify real {label}", ["identify", str(p), "--json"])
r.run(
f"visible auto real {label}",
["visible", str(p), "-o", str(tmp / f"r_{label}_{p.stem[:8]}.png")],
expect_exit=None,
) # 0 or 2 are both correct; a CRASH is not
# unicode + misnamed extension + truncated: the documented real-world traps
if picks:
src = picks[0][1]
uni = tmp / "тест изображение 测试.png"
shutil.copy(src, uni)
r.run("unicode filename", ["identify", str(uni), "--json"])
mis = tmp / "actually_png.jpg" # content PNG, extension JPEG
shutil.copy(SAMPLES / "chatgpt-1.png", mis)
r.run("misnamed extension", ["identify", str(mis), "--json"])
trunc = tmp / "truncated.png"
trunc.write_bytes((SAMPLES / "chatgpt-1.png").read_bytes()[:4096])
r.run("truncated file does not crash", ["identify", str(trunc), "--json"], expect_exit=None)
# ---- report --------------------------------------------------------------
bad = [x for x in r.results if x.status == "FAIL"]
skipped = [x for x in r.results if x.status == "skip"]
ok = [x for x in r.results if x.status == "pass"]
print(f"\n{'=' * 74}\nSMOKE MATRIX pass={len(ok)} FAIL={len(bad)} skipped={len(skipped)}\n{'=' * 74}")
for x in skipped:
print(f" SKIP {x.name:46s} {x.detail}")
for x in bad:
print(f" FAIL {x.name:46s} {x.detail}")
if x.cmd:
print(f" cmd: {x.cmd}")
if not bad:
print(" no failures")
print(f"\ntmp artifacts: {tmp}")
raise SystemExit(1 if bad else 0)
def _knob_rows(r: Runner, tmp: Path, img: Path) -> None:
"""Every diffusion knob the matrix never touched.
Deliberately cheap (`--steps 4`, `--max-resolution 384`): these rows answer "is the
knob accepted and does the run complete", NOT "is the output good". Quality per knob
needs a per-knob oracle and most of them have none (`--humanize` has no oracle at
all), so claiming more here would be dishonest.
"""
from remove_ai_watermarks import upscaler
# --steps 20 is the floor that WORKS, not an arbitrary choice: effective timesteps
# are int(steps * strength), so at the default strength 0.15 anything below
# --steps 7 rounds to ZERO and the pipeline dies inside torch. The first version of
# these rows used --steps 4 and every single one failed with the same reshape error.
fast = ["--max-resolution", "384", "--min-resolution", "0", "--steps", "20", "--force", "--seed", "0"]
def run(name: str, extra: list[str], *, tag: str, expect: int | None = 0) -> None:
r.run(
name,
["invisible", str(img), "-o", str(tmp / f"k_{tag}.png"), *fast, *extra],
expect_exit=expect,
timeout=2400,
)
run("--pipeline sdxl", ["--pipeline", "sdxl"], tag="sdxl")
run("--pipeline controlnet", ["--pipeline", "controlnet"], tag="cnet")
run("--strength", ["--strength", "0.2"], tag="strength")
run("--guidance-scale", ["--guidance-scale", "5.0"], tag="gs")
run("--controlnet-scale", ["--controlnet-scale", "0.5"], tag="cns")
run("--humanize", ["--humanize", "0.3"], tag="hum")
run("--unsharp", ["--unsharp", "0.5"], tag="uns")
run("--no-adaptive-polish", ["--no-adaptive-polish"], tag="nap")
run("--tile", ["--tile", "--tile-size", "256", "--tile-overlap", "64"], tag="tile")
run("--device mps", ["--device", "mps"], tag="mps")
run("--upscaler lanczos", ["--upscaler", "lanczos"], tag="lanczos")
run("--auto (deprecated no-op)", ["--auto"], tag="auto")
if upscaler.is_available():
run("--upscaler esrgan", ["--upscaler", "esrgan"], tag="esrgan")
else:
r.skip("--upscaler esrgan", "the `esrgan` extra is not installed")
# CPU is correctness-relevant (it is the documented MPS-OOM fallback) but slow, so
# it gets the smallest possible run rather than being skipped.
r.run(
"--device cpu",
[
"invisible",
str(img),
"-o",
str(tmp / "k_cpu.png"),
"--device",
"cpu",
"--max-resolution",
"256",
"--min-resolution",
"0",
"--steps",
"20",
"--force",
"--seed",
"0",
],
timeout=3600,
)
# qwen is CUDA-class by design (bf16 MMDiT, no MPS fallback). On this host the
# honest outcome is a CLEAN failure, not a crash -- assert it does not hang or
# dump a traceback at the user.
try:
import torch
cuda = bool(torch.cuda.is_available())
except Exception:
cuda = False
if cuda:
run("--pipeline qwen", ["--pipeline", "qwen"], tag="qwen")
else:
r.skip("--pipeline qwen", "CUDA-class pipeline; no CUDA device on this host")
# --model and --hf-token are deliberately not exercised: one would download a second
# multi-GB checkpoint, the other needs a real credential. Skipped loudly, not passed.
r.skip("--model", "would download a second multi-GB checkpoint")
r.skip("--hf-token", "needs a real credential; cannot be exercised meaningfully here")
# CONTRACT, not just execution: the same seed must reproduce the same pixels.
a_out, b_out = tmp / "seed_a.png", tmp / "seed_b.png"
for out in (a_out, b_out):
r.run(
f"seed determinism run ({out.name})",
["invisible", str(img), "-o", str(out), *fast],
timeout=2400,
)
if a_out.exists() and b_out.exists():
import numpy as np
from remove_ai_watermarks.image_io import imread
x, y = imread(str(a_out)), imread(str(b_out))
r.check(
"same --seed reproduces identical pixels",
x is not None and y is not None and x.shape == y.shape and bool(np.array_equal(x, y)),
"two runs with the same seed differed",
)
def _media_rows(r: Runner, tmp: Path) -> None:
"""Audio/video metadata strip via ffmpeg -- a supported path with no corpus coverage.
The corpus is images only, so the media is synthesized here with ffmpeg rather than
left untested.
"""
if not shutil.which("ffmpeg"):
r.skip("audio/video metadata strip", "ffmpeg not on PATH")
return
for name, gen in (
("mp4", ["-f", "lavfi", "-i", "testsrc=duration=1:size=128x128:rate=8", "-pix_fmt", "yuv420p"]),
("mp3", ["-f", "lavfi", "-i", "sine=frequency=440:duration=1"]),
):
src = tmp / f"media.{name}"
ff = shutil.which("ffmpeg") or "ffmpeg"
made = subprocess.run( # noqa: S603
[ff, "-y", *gen, "-metadata", "comment=Made with AI", str(src)],
capture_output=True,
check=False,
)
if made.returncode != 0 or not src.exists():
r.skip(f"{name} metadata strip", "ffmpeg could not synthesize the fixture")
continue
out = tmp / f"media_clean.{name}"
r.run(f"{name} metadata strip runs", ["metadata", str(src), "--remove", "-o", str(out)], expect_exit=None)
if out.exists():
r.check(f"{name} strip produced a non-empty file", out.stat().st_size > 0, "empty output")
def _sdxl_watermark_bits(img: object) -> float:
"""Bits of the open SDXL DWT-DCT watermark recovered from `img` (128 = perfect)."""
import numpy as np
from imwatermark import WatermarkDecoder
truth = np.frombuffer(b"StableDiffusionV1"[:16], dtype=np.uint8)
rec = WatermarkDecoder("bytes", 128).decode(img, "dwtDct")
return float(128 - np.unpackbits(truth ^ np.frombuffer(bytes(rec), dtype=np.uint8)).sum())
def _diffusion_rows(r: Runner, tmp: Path, doubao: Path) -> None:
"""Exercise the model-running bodies at a reduced resolution (MPS-friendly).
Bounded with `--max-resolution 512` and a fixed seed: the point is that the paths
RUN and keep their contracts, not to certify removal strength (that needs the
per-vendor oracles, see docs/known-limitations.md).
"""
import numpy as np
from remove_ai_watermarks.image_io import imread
small = ["--max-resolution", "512", "--seed", "0"]
# `invisible` must restore the original resolution and NOT re-stamp SDXL's own
# open watermark (add_watermarker=False; a remover that re-marks its output is the
# regression this row exists for).
#
# The carrier matters: imwatermark is positive-only and fails to round-trip on some
# pristine images, so an "absent" verdict on a fragile carrier proves NOTHING. mj-1
# is used because it round-trips at 128/128; the control is re-checked on the actual
# OUTPUT and the row degrades to a skip rather than a false pass if it goes fragile.
mj = SAMPLES / "mj-1.png"
inv = tmp / "inv_mj.png"
res = r.run("invisible runs (mps, 512px)", ["invisible", str(mj), "-o", str(inv), "--force", *small], timeout=1800)
if res.status == "pass" and inv.exists():
src_img, out_img = imread(str(mj)), imread(str(inv))
r.check(
"invisible restores the input resolution",
src_img is not None and out_img is not None and src_img.shape == out_img.shape,
f"{None if src_img is None else src_img.shape} -> {None if out_img is None else out_img.shape}",
)
try:
from imwatermark import WatermarkEncoder
enc = WatermarkEncoder()
enc.set_watermark("bytes", b"StableDiffusionV1"[:16])
control = _sdxl_watermark_bits(enc.encode(np.array(out_img).copy(), "dwtDct"))
if control < 118:
r.skip("invisible does not re-embed an SDXL watermark", f"carrier fragile (control {control:.0f}/128)")
else:
bits = _sdxl_watermark_bits(out_img)
r.check(
"invisible does not re-embed an SDXL watermark",
bits < 118,
f"re-embedded: {bits:.0f}/128 recovered (control {control:.0f}/128)",
)
except ImportError:
r.skip("invisible does not re-embed an SDXL watermark", "imwatermark absent (extra `detect`)")
# `all`: every stage must land -- the visible mark AND the metadata both gone.
allout = tmp / "all_out.png"
res = r.run("all runs (mps, 512px)", ["all", str(doubao), "-o", str(allout), *small], timeout=1800)
if res.status == "pass" and allout.exists():
rep = json.loads(_capture(["identify", str(allout), "--json"]))
r.check(
"all clears visible + metadata in one pass",
not rep.get("signals"),
f"still reports {[s.get('name') for s in rep.get('signals', [])]}",
)
_knob_rows(r, tmp, mj)
# `batch --mode invisible`: every input must produce an output (a silent short
# write is the failure this row guards).
bd = tmp / "batch_inv"
bd.mkdir(exist_ok=True)
for f in (SAMPLES / "chatgpt-2.png", mj):
shutil.copy(f, bd / f.name)
bout = tmp / "batch_inv_out"
res = r.run(
"batch --mode invisible runs (mps, 512px)",
["batch", str(bd), "--mode", "invisible", "-o", str(bout), *small],
expect_exit=None,
timeout=3600,
)
if res.status == "pass":
produced = len(list(bout.glob("*"))) if bout.exists() else 0
r.check("batch invisible writes one output per input", produced == 2, f"{produced} outputs for 2 inputs")
# `batch --mode all` -- the only --mode value the matrix never ran.
aout = tmp / "batch_all_out"
r.run(
"batch --mode all runs (mps, 512px)",
["batch", str(bd), "--mode", "all", "-o", str(aout), *small],
expect_exit=None,
timeout=3600,
)
# The AI-enhanced composite path: regenerate ONLY a region and feather it back,
# leaving everything outside the box pixel-exact. Library-level -- the CLI has no
# flag for it, so it would otherwise never be exercised on real data.
try:
import numpy as np
from remove_ai_watermarks.image_io import imread
from remove_ai_watermarks.noai.watermark_remover import WatermarkRemover
src = imread(str(mj))
h, w = src.shape[:2]
box = (w // 4, h // 4, w // 4, h // 4)
rem = WatermarkRemover(pipeline="controlnet")
rout = tmp / "region_composite.png"
rem.remove_watermark(mj, rout, strength=0.15, num_inference_steps=20, seed=0, region=box)
got = imread(str(rout))
if got is None or got.shape != src.shape:
r.check("region composite keeps the frame outside the box", False, "shape changed or unreadable")
else:
mask = np.ones(src.shape[:2], dtype=bool)
x, y, bw, bh = box
# Outside the box PLUS the feather margin must be untouched.
pad = 96
mask[max(0, y - pad) : y + bh + pad, max(0, x - pad) : x + bw + pad] = False
r.check(
"region composite keeps the frame outside the box",
bool(np.array_equal(src[mask], got[mask])),
"pixels changed outside the regenerated region",
)
except Exception as e:
r.skip("region composite (remove_watermark(region=...))", f"{type(e).__name__}: {e}"[:120])
if __name__ == "__main__":
main()
+241
View File
@@ -0,0 +1,241 @@
"""Partition China-AIGC carriers into VENDOR COHORTS by their TC260 producer code.
THE PROBLEM THIS SOLVES
Coverage of uncovered vendors is the largest remaining detection lever
(`docs/verification-plan.md`, "Where detection work should go next"), and it is
blocked on EVIDENCE: nothing may be registered off a single frame, and the
previous session found exactly one confirmed positive each for `千问` and `百度`.
Harvesting more by PIXELS is circular -- a detector is what we are trying to
build -- and the generic shared-tail probe is too weak to label with (0.407 on a
bold positive against a clean p99 of 0.298; see `cjk_tail_probe.py`).
THE KEY
The TC260 label is not anonymous. Its `ContentProducer` field carries the
producer's Chinese Unified Social Credit Code (USCC), e.g.
``001191110102MACQD9K64010000`` -> USCC ``91110102MACQD9K640``, which names a
specific legal entity. So the metadata partitions carriers into per-ENTITY
cohorts without looking at a single pixel. A cohort is a LABEL: once one frame
in it is eyeballed, every frame in it is a labelled example of that vendor's
mark. That is what turns "one confirmed positive" into "30+ per vendor".
CLAUDE.md's "the generic TC260 label names no specific vendor" is about the
label MARKER (the bare presence of `TC260:AIGC`), which indeed names nobody.
The producer FIELD inside the block is a different thing and does name one.
Caveat kept in view: the code names the SIGNING ENTITY, which is not always the
consumer brand (an aggregator or a cloud host signs for several apps, and one
vendor can hold several codes). So a cohort is a strong grouping key and a
hypothesis about the brand -- the brand itself is settled by reading the crop,
which is what `--sheets` is for.
WHAT IT COSTS
Metadata only. The expensive pixel pass is NOT re-run: which detectors fired is
joined from `_visible_positives.jsonl` (the completed full-corpus artifact), per
the standing rule against relaunching finished sweeps to re-check them.
DATA SAFETY
Corpus images are real user uploads: read-only, local analysis, gitignored
output. Contact sheets stay under `data/spaces/`; nothing here is committed.
uv run python scripts/vendor_cohort_harvest.py
uv run python scripts/vendor_cohort_harvest.py --report-only --sheets 12
"""
from __future__ import annotations
import argparse
import glob
import json
import os
import sys
from collections import Counter
from concurrent.futures import ProcessPoolExecutor, as_completed
from pathlib import Path
from typing import Any
sys.path.insert(0, str(Path(__file__).parent.parent))
sys.path.insert(0, str(Path(__file__).parent))
REPO = Path(__file__).resolve().parents[1]
CORPUS = REPO / "data" / "spaces" / "originals"
OUT = REPO / "data" / "spaces" / "_vendor_cohorts.jsonl"
FIRED = REPO / "data" / "spaces" / "_visible_positives.jsonl"
SHEET_DIR = REPO / "data" / "spaces" / "_vendor_cohort_sheets"
# A producer code is `001` + `1` + USCC(18) + a 5-digit app/product suffix, so two
# codes sharing the USCC are the same legal entity registering different products.
# Slicing is defensive: anything not matching the layout is grouped by its raw value.
_USCC_START, _USCC_END = 4, 22
def uscc_of(code: str) -> str:
"""The 18-char Unified Social Credit Code embedded in a TC260 producer code."""
if len(code) >= _USCC_END and code[:3] == "001":
return code[_USCC_START:_USCC_END]
return code
def _one(path_str: str) -> dict[str, Any] | None:
from remove_ai_watermarks.metadata import aigc_label
try:
label = aigc_label(Path(path_str))
except Exception:
return None
if not label:
return None
producer = str(label.get("ContentProducer") or "")
return {
"path": path_str,
"producer": producer,
"uscc": uscc_of(producer),
"propagator": str(label.get("ContentPropagator") or ""),
"service_provider": str(label.get("ServiceProvider") or ""),
}
def load_fired() -> dict[str, list[str]]:
"""path -> detector keys that fired, from the completed full-corpus artifact."""
if not FIRED.exists():
print(f"WARNING: {FIRED.name} missing; cohorts will show no detector state")
return {}
out: dict[str, list[str]] = {}
for line in FIRED.read_text(encoding="utf-8").splitlines():
if not line.strip():
continue
rec = json.loads(line)
out[rec["path"]] = rec.get("keys") or []
return out
def scan(limit: int, workers: int, out_path: Path) -> list[dict[str, Any]]:
pool = sorted(glob.glob(str(CORPUS / "*" / "*")))
if limit:
pool = pool[:limit]
print(f"scanning {len(pool)} corpus files for TC260 labels workers={workers}", flush=True)
rows: list[dict[str, Any]] = []
out_path.parent.mkdir(parents=True, exist_ok=True)
with open(out_path, "w", encoding="utf-8") as fh, ProcessPoolExecutor(max_workers=workers) as ex:
futures = [ex.submit(_one, p) for p in pool]
for i, fut in enumerate(as_completed(futures), 1):
try:
rec = fut.result()
except Exception: # noqa: S112 -- one bad file must not kill the scan
continue
if rec is not None:
fh.write(json.dumps(rec) + "\n")
rows.append(rec)
if i % 5000 == 0:
fh.flush()
print(f" {i}/{len(pool)} carriers={len(rows)}", flush=True)
return rows
def report(rows: list[dict[str, Any]], fired: dict[str, list[str]], min_size: int) -> None:
by_uscc: dict[str, list[dict[str, Any]]] = {}
for r in rows:
by_uscc.setdefault(r["uscc"], []).append(r)
print(f"\n{'=' * 92}\nVENDOR COHORTS ({len(rows)} TC260 carriers, {len(by_uscc)} distinct entities)\n{'=' * 92}")
print("\n`fires` = share of the cohort where SOME registered detector fires.")
print("A large cohort with a low fire rate is an uncovered vendor -- the harvest target.\n")
print(f"{'entity (USCC)':22s} {'n':>6s} {'fires':>7s} {'detectors seen':38s} {'products':>8s}")
print("-" * 92)
cohorts = sorted(by_uscc.items(), key=lambda kv: -len(kv[1]))
for uscc, members in cohorts:
if len(members) < min_size:
continue
keys: Counter[str] = Counter()
hit = 0
for m in members:
ks = fired.get(m["path"], [])
if ks:
hit += 1
keys.update(ks)
seen = ", ".join(f"{k}:{c}" for k, c in keys.most_common(4)) or "-- none --"
products = len({m["producer"] for m in members})
print(f"{uscc:22s} {len(members):6d} {100 * hit / len(members):6.1f}% {seen:38s} {products:8d}")
small = sum(1 for _, m in cohorts if len(m) < min_size)
if small:
print(f"\n({small} cohorts below --min-size {min_size} not shown)")
def _bands(img: Any, width: int, band: int) -> list[Any]:
"""Full-width top and bottom bands, scaled to a readable common width.
An unregistered vendor's placement is unknown, so cropping the bottom-RIGHT
corner (where the marks we already cover happen to sit) would beg the
question. Full-width bands catch any horizontal position, and the two bands
together cover every corner the standard's implementers actually use.
"""
import cv2
h = img.shape[0]
strip = max(24, int(h * band))
out = []
for piece in (img[:strip], img[h - strip :]):
scale = width / max(1, piece.shape[1])
out.append(cv2.resize(piece, (width, max(12, int(piece.shape[0] * scale))), interpolation=cv2.INTER_AREA))
return out
def sheets(rows: list[dict[str, Any]], fired: dict[str, list[str]], per: int, min_size: int) -> None:
"""Top/bottom bands per uncovered cohort, so the vendor and mark can be read off."""
import cv2
import numpy as np
from remove_ai_watermarks.image_io import imread
by_uscc: dict[str, list[dict[str, Any]]] = {}
for r in rows:
by_uscc.setdefault(r["uscc"], []).append(r)
SHEET_DIR.mkdir(parents=True, exist_ok=True)
print(f"\nwriting contact sheets -> {SHEET_DIR}")
for uscc, members in sorted(by_uscc.items(), key=lambda kv: -len(kv[1])):
if len(members) < min_size:
continue
quiet = [m for m in members if not fired.get(m["path"])]
if not quiet:
continue
width = 900
tiles: list[Any] = []
for m in quiet[:per]:
img = imread(m["path"])
if img is None:
continue
for b in _bands(img, width, 0.10):
tiles.append(b)
tiles.append(np.full((3, width, 3), 60, np.uint8))
if tiles:
dest = SHEET_DIR / f"{uscc}_n{len(members)}_quiet{len(quiet)}.png"
cv2.imwrite(str(dest), np.vstack(tiles))
print(f" {dest.name} ({len(tiles) // 4} frames)")
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--limit", type=int, default=0, help="cap files scanned (0 = whole corpus)")
ap.add_argument("--workers", type=int, default=max(1, (os.cpu_count() or 4) - 2))
ap.add_argument("--out", type=Path, default=OUT)
ap.add_argument("--report-only", action="store_true")
ap.add_argument("--min-size", type=int, default=5, help="hide cohorts smaller than this")
ap.add_argument("--sheets", type=int, default=0, help="crops per cohort contact sheet")
a = ap.parse_args()
if a.report_only:
rows = [json.loads(x) for x in a.out.read_text(encoding="utf-8").splitlines() if x.strip()]
else:
rows = scan(a.limit, a.workers, a.out)
fired = load_fired()
report(rows, fired, a.min_size)
if a.sheets:
sheets(rows, fired, a.sheets, a.min_size)
if __name__ == "__main__":
main()
+620
View File
@@ -0,0 +1,620 @@
"""Calibrate a candidate text-mark detector for an UNCOVERED vendor, on real positives.
WHERE THE POSITIVES COME FROM
`vendor_cohort_harvest.py` partitions China-AIGC carriers into per-entity cohorts by
their TC260 producer code, so a cohort is a vendor LABEL that owes nothing to any
pixel detector. That is what makes this calibration non-circular: the previous attempt
(`render_vendor_silhouettes.py`, 2026-07-18) died at n=1 because the only way it knew
to find 千问 frames was to eyeball the misses of a detector that cannot see them.
A cohort is NOT automatically a set of visible-mark positives: TC260 provenance is
metadata, and a vendor may label a frame without stamping it. So the cohort is the
CANDIDATE pool, and mark presence is settled by eye -- `--sheets` writes the corner
crops sorted by score, which makes that pass cheap and makes the separation (or its
absence) visible directly.
NEGATIVES
The 432 frames hand-labelled `present: []` in the 2026-07-18 round -- already-adjudicated
no-visible-mark images, so the false-fire arm rests on human labels rather than on the
absence of a detection.
THE TRAPS, INHERITED FROM THE 2026-07-18 MEASUREMENT
Both are encoded below rather than left to the caller:
* size the template with `alpha_height_frac`, NOT the silhouette's own aspect ratio
(the latter inflated the clean p99 from 0.30 to 0.58 and made comparison meaningless)
* keep the ladder at the shipped 3 rungs -- a wide sweep hands clean corners extra
chances to match, which flatters the positives and the negatives alike
DATA SAFETY
Corpus images are real user uploads: read-only, local, gitignored output. The template
is font-rendered synthetic (`render_vendor_silhouettes.py`), never cut from an upload.
uv run python scripts/vendor_mark_calibrate.py --cohort 91440101MA9Y9T4H7A \\
--asset qwen_alpha.png --sheets
"""
from __future__ import annotations
import argparse
import json
import os
import sys
from concurrent.futures import ProcessPoolExecutor, as_completed
from pathlib import Path
from typing import Any
sys.path.insert(0, str(Path(__file__).parent.parent))
sys.path.insert(0, str(Path(__file__).parent))
REPO = Path(__file__).resolve().parents[1]
COHORTS = REPO / "data" / "spaces" / "_vendor_cohorts.jsonl"
SHEET_DIR = REPO / "data" / "spaces" / "_vendor_calib_sheets"
OUT = REPO / "data" / "spaces" / "_vendor_calibration.jsonl"
def build_config(
asset: str,
name: str,
scale_basis: str = "short",
overrides: dict[str, Any] | None = None,
) -> Any:
"""A candidate config: doubao's tuned geometry with this vendor's silhouette.
Transferring doubao's numbers is justified by LAYOUT, not by hope: every one of these
marks is the same GB 45438-2025 house style -- a 2-glyph vendor prefix, then the
mandated `AI生成` tail, set in a semibold CJK sans in the bottom-right corner. So
`豆包AI生成` and `千问AI生成` are the same 6 glyph cells at the same scale, and the
width/height fractions carry over. The NCC gate does NOT carry over and is what this
script exists to measure. Any tuned value can be overridden with what
`--fit-geometry` measured -- inheriting the locate box blindly clipped the big-mode
qwen mark, which is exactly the trap this tool exists to avoid.
"""
import dataclasses
from remove_ai_watermarks._text_mark_engine import TextMarkConfig
from remove_ai_watermarks.doubao_engine import _CONFIG
return dataclasses.replace(
TextMarkConfig(**dataclasses.asdict(_CONFIG)),
name=name,
asset_name=asset,
scale_basis=scale_basis,
**(overrides or {}),
)
ScoreArgs = tuple[str, str, str, str, "dict[str, Any]"]
def _score(args: ScoreArgs) -> dict[str, Any] | None:
path_str, asset, name, basis, overrides = args
from remove_ai_watermarks._text_mark_engine import TextMarkEngine
from remove_ai_watermarks.image_io import imread
img = imread(path_str)
if img is None or min(img.shape[:2]) < 64:
return None
eng = TextMarkEngine(build_config(asset, name, basis, overrides))
loc = eng.locate(img)
try:
score, box = eng._tophat_best(img, loc)
except Exception:
return None
return {"path": path_str, "score": round(float(score), 4), "box": box}
NEGATIVES = REPO / "data" / "spaces" / "_research_20260718_textmark_relaxation" / "groundtruth.jsonl"
def load_sets(cohort: str) -> tuple[list[str], list[str]]:
pos = [
json.loads(x)["path"]
for x in COHORTS.read_text(encoding="utf-8").splitlines()
if x.strip() and json.loads(x)["uscc"] == cohort
]
# The 2026-07-18 labels are in the vocabulary of the REGISTERED marks only
# (gemini/doubao/jimeng/jimeng_pill): `present: []` means "no registered mark", NOT
# "no mark at all" -- 146 of the 432 sit in a TC260 cohort, and qwen-cohort frames
# visibly carrying 千问AI生成 are labelled `present: []` there (measured 2026-07-21:
# they made up the clean arm's whole top tail, clean p99 0.37 -> 0.69). A gate read
# off that arm is meaningless, so the clean arm excludes every frame in ANY TC260
# cohort -- cohort membership is the cheap proxy for "may carry a CJK AI label".
in_any_cohort = {
str(Path(json.loads(x)["path"]).resolve())
for x in COHORTS.read_text(encoding="utf-8").splitlines()
if x.strip()
}
neg: list[str] = []
dropped = 0
for line in NEGATIVES.read_text(encoding="utf-8").splitlines():
if not line.strip():
continue
rec = json.loads(line)
if rec.get("present"):
continue
p = str((REPO / rec["path"]).resolve())
if p in in_any_cohort:
dropped += 1
continue
neg.append(p)
if dropped:
print(f"clean arm: dropped {dropped} negatives that sit in a TC260 cohort (contamination guard)")
return pos, neg
def run(
paths: list[str],
asset: str,
name: str,
workers: int,
basis: str = "short",
overrides: dict[str, Any] | None = None,
) -> list[dict[str, Any]]:
out: list[dict[str, Any]] = []
with ProcessPoolExecutor(max_workers=workers) as ex:
futs = [ex.submit(_score, (p, asset, name, basis, overrides or {})) for p in paths]
for f in as_completed(futs):
try:
r = f.result()
except Exception: # noqa: S112 -- one bad file must not kill the sweep
continue
if r:
out.append(r)
return out
def report(pos: list[dict[str, Any]], neg: list[dict[str, Any]], name: str) -> None:
import numpy as np
p = np.array([r["score"] for r in pos])
n = np.array([r["score"] for r in neg])
print(f"\n{'=' * 78}\n{name}: candidate-cohort vs hand-labelled clean\n{'=' * 78}")
print(f"\n{'arm':10s} {'n':>5s} {'p10':>7s} {'p50':>7s} {'p90':>7s} {'p95':>7s} {'p99':>7s} {'max':>7s}")
for label, arr in (("cohort", p), ("clean", n)):
if not len(arr):
continue
qs = [np.percentile(arr, q) for q in (10, 50, 90, 95, 99)]
print(f"{label:10s} {len(arr):5d} " + " ".join(f"{q:7.3f}" for q in qs) + f" {arr.max():7.3f}")
if len(p) and len(n):
print("\n\nOPERATING POINTS -- gate set on the CLEAN arm")
print("`cohort fire` is an UPPER BOUND on recall: the cohort also holds")
print("metadata-only frames that carry no visible mark to find.\n")
print(f"{'gate':>7s} {'clean fire':>12s} {'cohort fire':>13s} {'cohort n':>10s}")
for q in (90, 95, 99, 99.5, 100):
t = float(np.percentile(n, q))
cf, pf = 100 * float((n >= t).mean()), 100 * float((p >= t).mean())
print(f"{t:7.3f} {cf:11.2f}% {pf:12.1f}% {int((p >= t).sum()):10d}")
def sheets(pos: list[dict[str, Any]], name: str, per_sheet: int = 24) -> None:
"""Corner crops sorted by score, so mark presence and the gate are read in one pass."""
import cv2
import numpy as np
from remove_ai_watermarks._text_mark_engine import TextMarkEngine
from remove_ai_watermarks.image_io import imread
eng = TextMarkEngine(build_config("doubao_alpha.png", "roi"))
SHEET_DIR.mkdir(parents=True, exist_ok=True)
ranked = sorted(pos, key=lambda r: -r["score"])
width = 660
for start in range(0, len(ranked), per_sheet):
chunk = ranked[start : start + per_sheet]
tiles: list[Any] = []
for rank, r in enumerate(chunk, start + 1):
img = imread(r["path"])
if img is None:
continue
loc = eng.locate(img)
crop = img[loc.y : loc.y + loc.h, loc.x : loc.x + loc.w]
if not crop.size:
continue
tile = cv2.resize(crop, (width, 96), interpolation=cv2.INTER_AREA)
cv2.rectangle(tile, (0, 0), (118, 22), (0, 0, 0), -1)
cv2.putText(tile, f"#{rank} {r['score']:.3f}", (4, 16), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)
tiles.append(tile)
tiles.append(np.full((2, width, 3), 70, np.uint8))
if tiles:
dest = SHEET_DIR / f"{name}_ranked_{start // per_sheet:02d}.png"
cv2.imwrite(str(dest), np.vstack(tiles))
print(f" {dest.name} (#{start + 1}..#{start + len(chunk)})")
# Wide and dense, for the geometry FIT only. An unregistered vendor's glyph size is
# genuinely unknown, which is the one case a dense ladder earns its cost -- but it also
# hands clean corners extra chances to match, so it must never set a gate.
_FIT_SCALES = tuple(round(0.4 * (1.03**i), 4) for i in range(80)) # 0.40 .. ~4.1
# The ladder the product actually ships (`_text_mark_engine._tophat_best`).
_SHIPPED_LADDER = (0.8, 1.0, 1.25)
def _fit_one(args: tuple[str, str, dict[str, Any]]) -> dict[str, Any] | None:
"""Best match over the WIDE ladder, reported as a mark width in pixels.
Also measures the template ASPECT at the winning width: the mark's true height is
fitted by sweeping gh at the winning gw and reading the argmax, because
`alpha_height_frac` must be measured, not taken from the silhouette's own aspect
(that inflated the clean p99 from 0.30 to 0.58 on the 2026-07-18 attempt) and not
inherited from doubao.
"""
path_str, asset, overrides = args
import cv2
import numpy as np
from remove_ai_watermarks._text_mark_engine import TextMarkEngine
from remove_ai_watermarks.image_io import imread
cfg = build_config(asset, "fit", "width", overrides)
eng = TextMarkEngine(cfg)
img = imread(path_str)
if img is None:
return None
loc = eng.locate(img)
resp = eng.tophat_response(img, loc)
sil = eng._glyph_silhouette()
if resp is None or sil is None:
return None
w = img.shape[1]
best, best_gw = 0.0, 0
best_tl = (0, 0)
for s in _FIT_SCALES:
gw = max(cfg.min_gw, int(cfg.alpha_width_frac * w * s))
gh = max(4, int(cfg.alpha_height_frac * w * s))
if gw >= resp.shape[1] or gh >= resp.shape[0]:
continue
t = cv2.resize(sil, (gw, gh), interpolation=cv2.INTER_AREA)
res = cv2.matchTemplate(resp, t, cv2.TM_CCOEFF_NORMED)
_, v, _, tl = cv2.minMaxLoc(res)
if v > best:
best, best_gw, best_tl = v, gw, (int(tl[0]), int(tl[1]))
# Aspect fit at the winning width: sweep gh/gw and keep the argmax. Range covers
# everything between samsung's 0.12 and jimeng's 0.29 house styles, plus the
# two-line stacked marks (Yuanbao ~0.45), plus slack.
best_aspect = 0.0
if best_gw > 0:
best_gh_score = -1.0
# Upper bound raised 0.42 -> 0.62 for two-line marks (Yuanbao's stacked block
# has silhouette aspect ~0.45; the old range's 0.12 floor was its own trap --
# the fit "won" by squashing the template to a one-line strip).
for ratio in np.arange(0.12, 0.62, 0.01):
gh = max(4, int(best_gw * float(ratio)))
if gh >= resp.shape[0]:
continue
t = cv2.resize(sil, (best_gw, gh), interpolation=cv2.INTER_AREA)
v = float(cv2.matchTemplate(resp, t, cv2.TM_CCOEFF_NORMED).max())
if v > best_gh_score:
best_gh_score, best_aspect = v, float(ratio)
# The ABSOLUTE mark rect, so the LOCATE box fractions can be fitted too: inheriting
# doubao's corner box clipped the big-mode qwen mark's first glyph (the qwen mark
# sits ~0.025 of the short side off the right edge, doubao's box assumes ~0.004),
# which collapsed an exact-size template to 0.26.
ax = loc.x + best_tl[0]
ay = loc.y + best_tl[1]
return {
"path": path_str,
"best": round(best, 4),
"mark_w": best_gw,
"aspect": round(best_aspect, 3),
"x": ax,
"y": ay,
"w": w,
"h": img.shape[0],
}
def fit_geometry(
paths: list[str],
asset: str,
workers: int,
floor: float = 0.50,
paths_name: str = "cohort",
overrides: dict[str, Any] | None = None,
) -> None:
"""Which basis and fraction does this vendor's mark actually scale with?
Only frames matching above ``floor`` are used: below it the winning size is the
ladder's best fit to background texture, not a measurement of the mark.
``overrides`` adjusts the LOCATE box for the fit (a two-line mark like Yuanbao's
is taller than Doubao's inherited box -- scoring it in the inherited box clips
the template to zero overlap).
"""
import numpy as np
rows: list[dict[str, Any]] = []
with ProcessPoolExecutor(max_workers=workers) as ex:
for f in as_completed([ex.submit(_fit_one, (p, asset, overrides or {})) for p in paths]):
try:
r = f.result()
except Exception: # noqa: S112 -- one bad file must not kill the fit
continue
if r:
rows.append(r)
strong = [r for r in rows if r["best"] >= floor]
fit_out = REPO / "data" / "spaces" / f"_vendor_fit_{paths_name}.jsonl"
fit_out.write_text("\n".join(json.dumps(r) for r in rows), encoding="utf-8")
print(f"\n{'=' * 78}\nGEOMETRY FIT (n={len(rows)}, usable best>={floor}: {len(strong)})\n{'=' * 78}")
print(f"rows -> {fit_out}")
if len(strong) < 20:
print("too few strong frames to fit a basis -- do not ship a fraction off this")
return
mw = np.array([r["mark_w"] for r in strong], float)
w = np.array([r["w"] for r in strong], float)
h = np.array([r["h"] for r in strong], float)
bases = {
"width": w,
"height": h,
"short": np.minimum(w, h),
"long": np.maximum(w, h),
"sqrt(w*h)": np.sqrt(w * h),
"diagonal": np.hypot(w, h),
}
print(f"\n{'basis':12s} {'mean frac':>10s} {'CV':>8s} {'p10':>8s} {'p90':>8s}")
print("-" * 52)
for nm, b in sorted(bases.items(), key=lambda kv: float(np.std(mw / kv[1]) / np.mean(mw / kv[1]))):
r = mw / b
print(
f"{nm:12s} {np.mean(r):10.4f} {float(np.std(r) / np.mean(r)):8.3f} "
f"{np.percentile(r, 10):8.4f} {np.percentile(r, 90):8.4f}"
)
lo_l, hi_l = _SHIPPED_LADDER[0], _SHIPPED_LADDER[-1]
print(f"\nCoverage by a single fraction on the SHIPPED ladder ({lo_l} .. {hi_l}, span {hi_l / lo_l:.3f}x):")
print(f"{'basis':12s} {'frac':>7s} {'window':>16s} {'covered':>9s}")
for nm in ("short", "sqrt(w*h)", "width"):
fs = mw / bases[nm]
best_f, best_cov = 0.0, -1.0
for f in np.arange(float(fs.min()) * 0.9, float(fs.max()) * 1.1, 0.002):
cov = float(((fs >= f * lo_l) & (fs <= f * hi_l)).mean())
if cov > best_cov:
best_f, best_cov = float(f), cov
print(f"{nm:12s} {best_f:7.3f} {best_f * lo_l:7.3f}-{best_f * hi_l:.3f} {100 * best_cov:8.1f}%")
# The raw distribution behind the coverage number: where the mark actually sits,
# so the mode structure (and what a 4th rung would recover) is visible directly.
fs = mw / bases["short"]
qs = [np.percentile(fs, q) for q in (5, 25, 50, 75, 95)]
print(f"\nfrac_short distribution: p5 {qs[0]:.3f} p25 {qs[1]:.3f} p50 {qs[2]:.3f} p75 {qs[3]:.3f} p95 {qs[4]:.3f}")
hist, edges = np.histogram(fs, bins=16)
for c, e0, e1 in zip(hist, edges[:-1], edges[1:], strict=True):
print(f" {e0:.3f}-{e1:.3f} {'#' * c}")
# Template aspect at the winning width -> the alpha_height_frac recommendation.
# Measured, per the standing rule: not the silhouette's own aspect, not doubao's.
aspects = np.array([r["aspect"] for r in strong if r["aspect"] > 0], float)
if len(aspects) >= 20:
med = float(np.median(aspects))
print(
f"\nASPECT FIT (n={len(aspects)}): p10 {np.percentile(aspects, 10):.3f} "
f"p50 {med:.3f} p90 {np.percentile(aspects, 90):.3f}"
)
print("alpha_height_frac = alpha_width_frac * p50(aspect), per basis:")
for nm in ("short", "sqrt(w*h)", "width"):
fxs = mw / bases[nm]
best_f = max(
np.arange(float(fxs.min()) * 0.9, float(fxs.max()) * 1.1, 0.002),
key=lambda f: float(((fxs >= f * lo_l) & (fxs <= f * hi_l)).mean()),
)
print(f" {nm:12s} width {best_f:.3f} -> height {best_f * med:.4f}")
# LOCATE-box fit. The box fractions are as mark-specific as the template size:
# doubao's box clipped qwen's big-mode mark (see _fit_one). Derive the box from the
# measured absolute mark rects: margins must not exceed the mark's own (else the
# mark exits the anchored box), and the box must cover the mark plus NCC slack.
if len(aspects) >= 20:
short = np.minimum(w, h).astype(float)
mark_h = np.array([r["mark_w"] * r["aspect"] for r in strong], float)
ax = np.array([r["x"] for r in strong], float)
ay = np.array([r["y"] for r in strong], float)
right = (w - (ax + mw)) / short # frame right edge to mark right edge
bottom = (h - (ay + mark_h)) / short
print(f"\nLOCATE FIT (basis=short, n={len(strong)}):")
print(f" right-margin frac p5 {np.percentile(right, 5):.4f} p50 {np.percentile(right, 50):.4f}")
print(f" bottom-margin frac p5 {np.percentile(bottom, 5):.4f} p50 {np.percentile(bottom, 50):.4f}")
print(
f" mark height frac p50 {np.percentile(mark_h / short, 50):.4f} "
f"p95 {np.percentile(mark_h / short, 95):.4f}"
)
mx = max(0.002, float(np.percentile(right, 5)) - 0.004)
mb = max(0.002, float(np.percentile(bottom, 5)) - 0.004)
need_w = float(np.percentile(mw / short + right, 95)) - mx + 0.02
need_h = float(np.percentile(mark_h / short + bottom, 95)) - mb + 0.015
print(f" recommended: margin_x_frac={mx:.4f} margin_bottom_frac={mb:.4f}")
print(f" width_frac={need_w:.3f} height_frac={need_h:.3f}")
print("\nThese are DIAGNOSTIC. Re-score both arms on the shipped ladder with the")
print("fitted geometry before reading any gate off the clean arm.")
FIRED = REPO / "data" / "spaces" / "_visible_positives.jsonl"
def _fired_pool(mark: str, limit: int, seed: int = 7) -> list[str]:
"""Paths where ``mark`` fired, from the COMPLETED full-corpus artifact -- the
standing rule: detector firings are joined, never re-run."""
import random
pool = [
json.loads(x)["path"]
for x in FIRED.read_text(encoding="utf-8").splitlines()
if x.strip() and mark in (json.loads(x).get("keys") or [])
]
rng = random.Random(seed) # noqa: S311 -- reproducible sampling, not crypto
rng.shuffle(pool)
return pool[:limit]
def _cross_score(args: tuple[str, Any, Any]) -> dict[str, Any] | None:
"""One frame scored by BOTH the candidate and the doubao production configs."""
path_str, cand_cfg, db_cfg = args
from remove_ai_watermarks._text_mark_engine import TextMarkEngine
from remove_ai_watermarks.image_io import imread
img = imread(path_str)
if img is None or min(img.shape[:2]) < 200:
return None
out: dict[str, Any] = {"path": path_str}
for key, cfg in (("cand", cand_cfg), ("doubao", db_cfg)):
eng = TextMarkEngine(cfg)
loc = eng.locate(img)
try:
score, _ = eng._tophat_best(img, loc)
except Exception:
return None
out[key] = round(float(score), 4)
return out
def crossfire(
pools: dict[str, list[str]],
cand_cfg: Any,
workers: int,
gate: float,
margin: float = 0.10,
) -> None:
"""Score the candidate AND doubao's production template on the same frames.
The registration question a cohort-vs-clean run cannot answer: the candidate shares
the mandated `AI生成` tail with doubao (4 of 6 glyph cells), so its template will
correlate with doubao marks too. If the candidate fires on the doubao pool at the
candidate gate, registering it double-fills every doubao frame and mislabels it --
unless the rival margin suppresses it, which then has to be shown NOT to kill the
candidate on its own marks. Measured here in the tophat domain (the gate's domain);
production's `_rival_margin_ok` runs the same comparison on the binary blob.
"""
import numpy as np
from remove_ai_watermarks.doubao_engine import _CONFIG as db_cfg
print(f"\n{'=' * 78}\nCROSSFIRE -- candidate vs doubao, same frames, tophat domain\n{'=' * 78}")
print(f"candidate gate {gate:.3f} | rival margin {margin:.2f}\n")
print(
f"{'pool':8s} {'n':>5s} {'cand p50':>9s} {'cand p90':>9s} {'db p50':>7s} {'db p90':>7s} "
f"{'m-d p10':>8s} {'m-d p50':>8s} {'fire':>7s} {'fire+m':>7s}"
)
with ProcessPoolExecutor(max_workers=workers) as ex:
for pool_name, paths in pools.items():
rows: list[dict[str, Any]] = []
futs = [ex.submit(_cross_score, (p, cand_cfg, db_cfg)) for p in paths]
for f in as_completed(futs):
try:
r = f.result()
except Exception: # noqa: S112 -- one bad file must not kill the pool
continue
if r:
rows.append(r)
if not rows:
continue
c = np.array([r["cand"] for r in rows])
d = np.array([r["doubao"] for r in rows])
m = c - d
fire = c >= gate
fire_m = fire & (m >= margin)
print(
f"{pool_name:8s} {len(rows):5d} {np.percentile(c, 50):9.3f} {np.percentile(c, 90):9.3f} "
f"{np.percentile(d, 50):7.3f} {np.percentile(d, 90):7.3f} "
f"{np.percentile(m, 10):8.3f} {np.percentile(m, 50):8.3f} "
f"{100 * float(fire.mean()):6.1f}% {100 * float(fire_m.mean()):6.1f}%"
)
print("\nReading: on `qwen` the margin column must stay high (the candidate keeps its")
print("own marks); on `doubao` fire+m must sit near zero (the candidate stays off")
print("doubao marks). If fire is high on `doubao` and fire+m is not, the rival margin")
print("is load-bearing for registration; if both are high, the mark cannot be")
print("registered on this front-end at all.")
def _parse_ladder(raw: str) -> tuple[float, ...] | None:
if not raw:
return None
return tuple(float(x) for x in raw.split(","))
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--cohort", required=True, help="cohort USCC from vendor_cohort_harvest.py")
ap.add_argument("--asset", required=True, help="silhouette asset name, e.g. qwen_alpha.png")
ap.add_argument("--name", default="", help="label for output files (defaults to the asset stem)")
ap.add_argument("--workers", type=int, default=max(1, (os.cpu_count() or 4) - 2))
ap.add_argument("--scale-basis", choices=("short", "width"), default="short")
ap.add_argument(
"--corner",
choices=("br", "bl", "tl"),
default=None,
help="override the inherited br corner (e.g. tl for RunningHub)",
)
ap.add_argument("--sheets", action="store_true")
ap.add_argument(
"--fit-geometry",
action="store_true",
help="fit the basis + fraction + template aspect the mark scales with",
)
ap.add_argument("--width-frac", type=float, default=None, help="fitted alpha_width_frac (default: inherit doubao)")
ap.add_argument(
"--height-frac", type=float, default=None, help="fitted alpha_height_frac (default: inherit doubao)"
)
ap.add_argument("--ladder", default="", help="comma scale rungs, e.g. 0.8,1.0,1.25,1.6 (default: shipped 3)")
ap.add_argument("--gate", type=float, default=0.45, help="candidate gate for the crossfire fire rates")
ap.add_argument("--box-width-frac", type=float, default=None, help="fitted locate width_frac")
ap.add_argument("--box-height-frac", type=float, default=None, help="fitted locate height_frac")
ap.add_argument("--margin-x-frac", type=float, default=None, help="fitted locate margin_x_frac")
ap.add_argument("--margin-bottom-frac", type=float, default=None, help="fitted locate margin_bottom_frac")
ap.add_argument(
"--crossfire",
action="store_true",
help="score the candidate AND doubao on the cohort, the doubao/jimeng pools and the clean arm",
)
a = ap.parse_args()
name = a.name or a.asset.split("_")[0]
ladder = _parse_ladder(a.ladder)
overrides: dict[str, Any] = {}
for arg, field in (
(a.width_frac, "alpha_width_frac"),
(a.height_frac, "alpha_height_frac"),
(a.box_width_frac, "width_frac"),
(a.box_height_frac, "height_frac"),
(a.margin_x_frac, "margin_x_frac"),
(a.margin_bottom_frac, "margin_bottom_frac"),
):
if arg is not None:
overrides[field] = arg
if a.corner is not None:
overrides["corner"] = a.corner
if ladder is not None:
overrides["ladder"] = ladder
pos_paths, neg_paths = load_sets(a.cohort)
if a.fit_geometry:
print(f"cohort {a.cohort}: {len(pos_paths)} candidates")
fit_geometry(pos_paths, a.asset, a.workers, paths_name=name, overrides=overrides)
return
if a.crossfire:
cand = build_config(a.asset, name, a.scale_basis, overrides)
pools = {
"qwen": pos_paths,
"doubao": _fired_pool("doubao", 400),
"jimeng": _fired_pool("jimeng", 300),
"clean": neg_paths,
}
print("pools: " + ", ".join(f"{k}={len(v)}" for k, v in pools.items()))
crossfire(pools, cand, a.workers, a.gate)
return
print(f"cohort {a.cohort}: {len(pos_paths)} candidates | clean: {len(neg_paths)} hand-labelled")
print(f"scale_basis={a.scale_basis} overrides={overrides}")
pos = run(pos_paths, a.asset, name, a.workers, a.scale_basis, overrides)
neg = run(neg_paths, a.asset, name, a.workers, a.scale_basis, overrides)
OUT.write_text(
"\n".join(json.dumps({**r, "arm": arm}) for arm, rows in (("cohort", pos), ("clean", neg)) for r in rows),
encoding="utf-8",
)
report(pos, neg, name)
if a.sheets:
print(f"\nsheets -> {SHEET_DIR}")
sheets(pos, name)
if __name__ == "__main__":
main()
+164
View File
@@ -0,0 +1,164 @@
"""Benchmark harness for the visible-mark detectors.
Run this before AND after any detector change. It re-runs perception over the
hand-labelled ground truth and reports, per mark, how often a fire is correct --
with Wilson intervals, so a change inside the noise is visible as such.
uv run python scripts/visible_eval.py # score current code
uv run python scripts/visible_eval.py --save baseline # snapshot for comparison
uv run python scripts/visible_eval.py --vs baseline # diff against a snapshot
WHAT THIS SET CAN AND CANNOT MEASURE -- read before quoting a number:
* PRECISION: sound. Every labelled crop is centred on the region a detector
pointed at, so "the detector fired mark K here, was K actually there" is
exactly the question the labels answer.
* RECALL: NOT measurable here, and the harness refuses to print it. The labelled
images were SAMPLED WHERE DETECTORS FIRED (relaxation additions plus controls),
so images carrying a mark that every detector missed are absent by construction.
Computing recall on this set would divide by a denominator that excludes exactly
the failures recall is meant to expose, and would report a flattering number.
Recall needs a RANDOM corpus sample laballed exhaustively -- a separate round.
* `other_ai_label` (千问 / 百度 / 星绘 / 抖音) counts as a FALSE fire for any
registered mark, because it is a different vendor's label. It is tracked
separately in the confusion output since it is the dominant jimeng failure.
"""
from __future__ import annotations
import argparse
import json
import math
import sys
from collections import Counter
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
from remove_ai_watermarks import watermark_registry as wr
from remove_ai_watermarks.image_io import imread
GT = Path("data/spaces/_research_20260718_textmark_relaxation/groundtruth.jsonl")
SNAP = Path("data/spaces/_research_20260718_textmark_relaxation/snapshots")
MARKS = ("gemini", "doubao", "jimeng", "samsung", "jimeng_pill")
def wilson(k: int, n: int) -> tuple[float, float]:
if n == 0:
return (0.0, 0.0)
z, p = 1.96, k / n
d = 1 + z * z / n
c = p + z * z / (2 * n)
s = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n))
return ((c - s) / d, (c + s) / d)
def provenance_for(rec: dict) -> frozenset[str]:
"""The provenance production would have: read from the file's own METADATA.
Never derive this from the labels. A relaxation arm only fires when provenance
names the vendor, so label-derived provenance silently tells the detector the
answer and every arm scores near-perfect (observed: gemini 99% instead of 34%).
"""
return frozenset(rec.get("provenance", []))
def score(sensitivity: str = "auto") -> dict:
recs = [json.loads(line) for line in GT.open()]
per: dict[str, Counter] = {m: Counter() for m in MARKS}
confusion: dict[str, Counter] = {m: Counter() for m in MARKS}
missing = 0
for rec in recs:
img = imread(rec["path"])
if img is None:
missing += 1
continue
cands = wr._build_candidates(img)
ctx = wr.Context(sensitivity=sensitivity, provenance=provenance_for(rec))
fired = {d.candidate.key for d in wr.decide(cands, ctx)}
for m in MARKS:
# Only score a mark on images whose shown crop could rule on it. Scoring
# outside that scope books real detections as false fires -- see the
# adjudication note in visible_groundtruth.py.
if m not in rec.get("adjudicated", []):
continue
if m not in fired:
per[m]["fn"] += 1 if m in rec["present"] else 0
continue
if m in rec["present"]:
per[m]["tp"] += 1
else:
per[m]["fp"] += 1
for s in rec["seen"]:
confusion[m][s] += 1
scope = {m: sum(1 for r in recs if m in r.get("adjudicated", [])) for m in MARKS}
return {
"per": {m: dict(c) for m, c in per.items()},
"scope": scope,
"confusion": {m: dict(c) for m, c in confusion.items()},
"missing": missing,
"n": len(recs),
"sensitivity": sensitivity,
}
def report(res: dict, prev: dict | None = None) -> None:
print(f"\nground truth: {res['n']} images ({res['missing']} unreadable) sensitivity={res['sensitivity']}")
print("=" * 78)
print(
f"{'mark':12s} {'scope':>6s} {'fires':>6s} {'correct':>8s} "
f"{'precision':>11s} {'95% CI':>13s} {'missed':>7s} delta"
)
print("-" * 78)
for m in MARKS:
c = res["per"][m]
tp, fp, fn = c.get("tp", 0), c.get("fp", 0), c.get("fn", 0)
n = tp + fp
scope = res["scope"].get(m, 0)
if n == 0:
print(f"{m:12s} {scope:6d} {0:6d} {'-':>8s} {'-':>11s} {'-':>13s} {fn:7d}")
continue
lo, hi = wilson(tp, n)
delta = ""
if prev:
pc = prev["per"][m]
pn = pc.get("tp", 0) + pc.get("fp", 0)
if pn:
d = tp / n - pc.get("tp", 0) / pn
delta = f"{d:+.1%} (fires {pn}->{n})"
print(f"{m:12s} {scope:6d} {n:6d} {tp:8d} {tp / n:10.0%} {lo:5.0%}-{hi:<6.0%} {fn:7d} {delta}")
print("\nwhat the FALSE fires actually were:")
for m in MARKS:
conf = {k: v for k, v in res["confusion"][m].items() if k != m}
if conf:
print(f" {m:12s} {dict(sorted(conf.items(), key=lambda kv: -kv[1]))}")
print("\n'scope' = images whose crop could rule on that mark; 'missed' = labelled marks it did not fire on.")
print("NOTE: 'missed' is NOT recall -- this set was sampled where detectors fired, so images")
print(" every detector missed are absent by construction. Use it only to catch a change")
print(" LOSING marks it used to find; an unbiased random sample is needed for true recall.")
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--save", metavar="NAME")
ap.add_argument("--vs", metavar="NAME")
ap.add_argument("--sensitivity", default="auto")
a = ap.parse_args()
res = score(a.sensitivity)
prev = None
if a.vs:
f = SNAP / f"{a.vs}.json"
if f.exists():
prev = json.loads(f.read_text())
else:
print(f"(no snapshot {f}; showing absolute numbers)")
report(res, prev)
if a.save:
SNAP.mkdir(parents=True, exist_ok=True)
(SNAP / f"{a.save}.json").write_text(json.dumps(res, indent=1))
print(f"\nsaved snapshot -> {SNAP / f'{a.save}.json'}")
if __name__ == "__main__":
main()
+134
View File
@@ -0,0 +1,134 @@
"""Consolidate the hand-labelled contact-sheet rounds into ONE ground-truth file.
Ground truth is `uid -> the set of visible marks actually present`, hand-labelled
blind against contact sheets with a two-sided control in every round. Rounds so far:
2026-07-18 text-mark/pill round : 423 cells (doubao / jimeng / jimeng_pill arms)
2026-07-18 gemini round : 356 cells (gemini relaxation additions)
DATA SAFETY: the corpus is real user uploads. This script reads the gitignored
corpus and writes a gitignored ground-truth file. Neither the images nor this
output may be committed; only the harness is. See the repo CLAUDE.md.
The labels record what the LABELLER SAW in the crop, one of:
doubao | jimeng | pill | sparkle | other_ai_label | none | uncertain
`other_ai_label` is a real visible AI label from a vendor we do NOT have a mark for
(千问 / 百度 / 星绘 / 抖音); it is NOT a positive for any registered mark, but it is
also not "clean" -- it is exactly what the relaxed jimeng detector confuses.
`uncertain` rows are EXCLUDED from scoring rather than coerced, so a labeller's
honest doubt never becomes a fabricated data point.
"""
from __future__ import annotations
import csv
import json
import sys
from pathlib import Path
SEEN_TO_MARK = {
"doubao": "doubao",
"jimeng": "jimeng",
"pill": "jimeng_pill",
"sparkle": "gemini",
}
# Which marks a crop centred on `key` lets the labeller rule on (same corner = visible
# in the same crop). Doubao and Jimeng share the bottom-right corner.
_ADJUDICATES = {
"doubao": ("doubao", "jimeng"),
"jimeng": ("doubao", "jimeng"),
"jimeng_pill": ("jimeng_pill",),
"gemini": ("gemini",),
"samsung": ("samsung",),
}
ROUNDS = [
("textmark", "labels.csv", "manifest.csv"),
("gemini", "gemini_labels.csv", "gemini_manifest.csv"),
]
def metadata_provenance(path: str) -> list[str]:
"""The vendor keys LOCAL METADATA confirms -- what cli._visible_provenance reads.
Must come from the file's own metadata, never from the labels: deriving it from
the ground truth would hand the detector the answer it is being scored on (a
relaxation only fires when provenance names the vendor, so label-derived
provenance makes every arm look near-perfect). Read from the corpus `identify`
sidecar, which is the same signal production computes.
"""
p = Path(path)
sidecar = Path(str(p.parent).replace("/originals/", "/identify/")) / (p.name.split("_src")[0] + ".json")
if not sidecar.exists():
return []
try:
with sidecar.open() as fh:
wm = " | ".join(json.load(fh).get("watermarks", []))
except Exception:
return []
keys: list[str] = []
if "China AIGC label" in wm:
keys += ["doubao", "jimeng"]
if "C2PA Content Credentials (Google LLC" in wm:
keys.append("gemini")
if "Samsung Galaxy AI" in wm:
keys.append("samsung")
return keys
def main() -> None:
root = Path(sys.argv[1] if len(sys.argv) > 1 else "data/spaces/_research_20260718_textmark_relaxation")
out = root / "groundtruth.jsonl"
rows: dict[str, dict] = {}
stats: dict[str, int] = {}
for round_name, labels_file, manifest_file in ROUNDS:
with (root / labels_file).open() as fh:
labels = {int(r["idx"]): r["seen"] for r in csv.DictReader(fh)}
with (root / manifest_file).open() as fh:
manifest_rows = list(csv.DictReader(fh))
for m in manifest_rows:
seen = labels.get(int(m["idx"]))
if seen is None:
continue
stats[seen] = stats.get(seen, 0) + 1
if seen == "uncertain":
continue # excluded by design -- never coerce a doubt into a label
rec = rows.setdefault(
m["uid"],
{"uid": m["uid"], "path": m["path"], "present": [], "seen": [], "rounds": [], "adjudicated": []},
)
# ADJUDICATION SCOPE -- load-bearing. A crop centred on one mark only lets
# the labeller rule on marks visible IN THAT CROP. A pill crop (top-left)
# says nothing about a bottom-right wordmark, so scoring jimeng against a
# pill-round image would book real detections as false fires (~61% of pills
# carry a wordmark). Bottom-right marks co-adjudicate each other: one crop
# of that corner shows whichever of Doubao/Jimeng is there.
for k in _ADJUDICATES.get(m["key"], (m["key"],)):
if k not in rec["adjudicated"]:
rec["adjudicated"].append(k)
mark = SEEN_TO_MARK.get(seen)
if mark and mark not in rec["present"]:
rec["present"].append(mark)
if seen not in rec["seen"]:
rec["seen"].append(seen)
if round_name not in rec["rounds"]:
rec["rounds"].append(round_name)
for r in rows.values():
r["provenance"] = metadata_provenance(r["path"])
with out.open("w") as fh:
for r in rows.values():
fh.write(json.dumps(r) + "\n")
print(f"wrote {out} images={len(rows)}")
print("label distribution across all rounds:", dict(sorted(stats.items(), key=lambda kv: -kv[1])))
n_pos = sum(1 for r in rows.values() if r["present"])
print(f"images with at least one registered mark: {n_pos}; clean-of-registered-marks: {len(rows) - n_pos}")
adj: dict[str, int] = {}
for r in rows.values():
for k in r["adjudicated"]:
adj[k] = adj.get(k, 0) + 1
print("images each mark can be SCORED on (adjudication scope):", dict(sorted(adj.items())))
if __name__ == "__main__":
main()
+141
View File
@@ -0,0 +1,141 @@
"""Parallel detection pass: list every corpus image carrying a known visible mark.
Why this exists separately from `visible_removal_audit.py`: that audit is single-process,
so a full-corpus sweep costs ~10 h and running it once per backend costs ~30 h. But its
expensive half is DETECTION, and detection does not depend on the fill backend. Splitting
it out means detecting once in parallel and then feeding the positives to the audit via
its `--paths-file` seam, over a few thousand images instead of forty thousand.
CRASH TOLERANCE IS NOT OPTIONAL AT THIS SCALE
cv2/libpng decode native-crash on some real uploads. A plain `ProcessPoolExecutor.map`
over 39k files then DEADLOCKS: the worker dies without a Python traceback and the parent
waits forever on a result that never arrives (observed 2026-07-19 -- 26 min of work lost
because results were only written at the end). So this script:
* writes every result to JSONL as it arrives -- a kill never costs more than a batch;
* is resumable -- an interrupted run skips what it already recorded;
* runs a FRESH pool per batch with a timeout, so one poisoned file costs one batch,
and that batch is retried serially to find and record the offender.
Corpus images are user uploads: read-only, local analysis, gitignored output.
uv run python scripts/visible_positives.py --jobs 6
"""
from __future__ import annotations
import argparse
import collections
import glob
import json
import os
import sys
from concurrent.futures import ProcessPoolExecutor, as_completed
from concurrent.futures import TimeoutError as FutureTimeout
from concurrent.futures.process import BrokenProcessPool
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent))
# The package's own format set. An inlined copy here silently skipped .heif, which
# CLAUDE.md documents as supported.
from remove_ai_watermarks.noai.constants import SUPPORTED_FORMATS as _EXTS
REPO = Path(__file__).resolve().parents[1]
CORPUS = REPO / "data" / "spaces" / "originals"
OUT = REPO / "data" / "spaces" / "_visible_positives.jsonl"
PATHS = REPO / "data" / "spaces" / "_visible_positives.txt"
def _one(path: str) -> dict[str, object]:
from remove_ai_watermarks.image_io import imread
from remove_ai_watermarks.watermark_registry import detect_marks
try:
img = imread(path)
if img is None:
return {"path": path, "keys": [], "status": "unreadable"}
return {"path": path, "keys": [d.key for d in detect_marks(img) if d.detected], "status": "ok"}
except Exception as e:
return {"path": path, "keys": [], "status": f"error:{type(e).__name__}"}
def _run_batch(batch: list[str], jobs: int, timeout: int) -> list[dict[str, object]]:
"""One batch in a fresh pool. On a native worker crash or timeout, retry serially so
the poisoned file is identified and recorded instead of stalling the whole sweep."""
try:
with ProcessPoolExecutor(max_workers=jobs) as ex:
futs = {ex.submit(_one, p): p for p in batch}
return [f.result() for f in as_completed(futs, timeout=timeout)]
except (FutureTimeout, BrokenProcessPool, OSError, RuntimeError):
out: list[dict[str, object]] = []
for p in batch:
try:
out.append(_one(p))
except BaseException: # a native crash here kills only this file, not the sweep
out.append({"path": p, "keys": [], "status": "crashed"})
return out
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--jobs", type=int, default=max(1, (os.cpu_count() or 4) - 2))
ap.add_argument("--limit", type=int, default=0)
ap.add_argument("--batch", type=int, default=200)
ap.add_argument("--timeout", type=int, default=600, help="seconds per batch before falling back to serial")
ap.add_argument("--out", type=Path, default=OUT)
ap.add_argument("--restart", action="store_true")
a = ap.parse_args()
files = sorted(p for p in glob.glob(str(CORPUS / "*" / "*")) if Path(p).suffix.lower() in _EXTS)
if a.limit:
files = files[: a.limit]
done: set[str] = set()
if a.restart and a.out.exists():
a.out.unlink() # --restart must TRUNCATE; the file is reopened in append mode below
if a.out.exists() and not a.restart:
with open(a.out, encoding="utf-8") as fh:
for line in fh:
try:
done.add(json.loads(line)["path"])
except Exception: # noqa: S112 -- tolerate a torn last line
continue
todo = [p for p in files if p not in done]
print(f"images {len(files)} already done {len(done)} to do {len(todo)} jobs {a.jobs}", flush=True)
counts: collections.Counter[str] = collections.Counter()
status: collections.Counter[str] = collections.Counter()
seen = 0
with open(a.out, "a", encoding="utf-8") as fh:
for start in range(0, len(todo), a.batch):
for rec in _run_batch(todo[start : start + a.batch], a.jobs, a.timeout):
fh.write(json.dumps(rec) + "\n")
status[str(rec["status"])] += 1
for k in rec["keys"]: # type: ignore[union-attr]
counts[str(k)] += 1
seen += 1
fh.flush()
print(f" {seen}/{len(todo)} {dict(counts)} {dict(status)}", flush=True)
# Rebuild the paths file from the FULL record set, not just this run's slice.
hits = []
with open(a.out, encoding="utf-8") as fh:
for line in fh:
try:
r = json.loads(line)
except Exception: # noqa: S112
continue
if r.get("keys"):
hits.append(r["path"])
# Derive the paths file from --out so a trial run with a scratch --out cannot
# overwrite the shared list a full sweep produced.
paths_out = a.out.with_suffix(".txt")
paths_out.write_text("\n".join(sorted(set(hits))) + "\n", encoding="utf-8")
print(f"\npositives: {len(set(hits))} images")
for k, v in counts.most_common():
print(f" {v:6d} {k}")
print(f"statuses: {dict(status)}\npaths -> {paths_out}\nrecords -> {a.out}")
if __name__ == "__main__":
main()
+126
View File
@@ -0,0 +1,126 @@
"""Build an UNBIASED random sample for measuring visible-mark RECALL.
Every earlier labelling round sampled where detectors FIRED, so images that every
detector missed were absent by construction and recall was unmeasurable. This round
samples at random within a provenance class and shows the labeller the corners where
a mark can physically be, so a MISSED mark is visible as such.
Design decisions that matter:
* SAMPLING FRAME is per provenance class, not the whole corpus. Recall is only
meaningful against a denominator where the mark CAN occur: TC260 carriers for the
ByteDance marks and the pill, Google-C2PA for the sparkle. Reporting one blended
recall over all uploads would mostly measure how often each vendor appears.
* NATIVE RESOLUTION crops, never a downscaled whole image: a 220px preview destroys a
faint mark (measured in an earlier round), which would inflate the miss count with
the labeller's own blindness rather than the detector's.
* BOTH corners per image (top-left pill, bottom-right wordmark/strip/sparkle), so one
pass adjudicates every registered mark instead of one mark per crop.
* The detector's verdict is NOT shown and is not in the sheet order -- the manifest
holds it and must not be opened until labelling ends.
"""
from __future__ import annotations
import csv
import json
import random
import sys
from pathlib import Path
from typing import TYPE_CHECKING, Any
import cv2
import numpy as np
if TYPE_CHECKING:
from numpy.typing import NDArray
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
from remove_ai_watermarks.image_io import imread
CELL_W = 300
COLS, ROWS = 4, 3
PER = COLS * ROWS
def corner_strip(img: NDArray[Any]) -> NDArray[Any] | None:
"""Top-left and bottom-right corners stacked, at (near) native scale.
Crop size is a fraction of the SHORT side because that is what marks scale with
(China's GB 45438-2025 sizes the mandated label off the shortest side).
"""
h, w = img.shape[:2]
short = min(h, w)
cw, ch = int(short * 0.46), int(short * 0.17)
cw, ch = min(cw, w), min(ch, h)
tl = img[0:ch, 0:cw]
br = img[h - ch : h, w - cw : w]
strip = np.vstack([tl, np.full((6, cw, 3), 90, np.uint8), br])
s = min(1.0, CELL_W / strip.shape[1]) # never UPSCALE past native
if s < 1.0:
strip = cv2.resize(strip, (CELL_W, max(1, int(strip.shape[0] * s))), interpolation=cv2.INTER_AREA)
return strip
def main() -> None:
scan = Path(sys.argv[1])
out = Path(sys.argv[2])
n_tc260 = int(sys.argv[3]) if len(sys.argv) > 3 else 160
n_google = int(sys.argv[4]) if len(sys.argv) > 4 else 80
out.mkdir(parents=True, exist_ok=True)
recs = [json.loads(line) for line in scan.open() if '"marks"' in line]
seen: dict[tuple, dict] = {}
for r in recs: # exact-duplicate uploads share the whole NCC vector
seen.setdefault(tuple(r.get("shape", ())) + tuple(sorted((k, m["conf"]) for k, m in r["marks"].items())), r)
uniq = list(seen.values())
tc = [r for r in uniq if r["cls"] == "tc260"]
goog = [r for r in uniq if r["cls"] == "neg" and "Google" in r.get("platform", "")]
rng = random.Random(2026) # noqa: S311 -- sampling, not cryptography
rng.shuffle(tc)
rng.shuffle(goog)
picked = [("tc260", r) for r in tc[:n_tc260]] + [("google", r) for r in goog[:n_google]]
rng.shuffle(picked)
manifest, cells = [], []
for cls, r in picked:
img = imread(r["path"])
if img is None:
continue
strip = corner_strip(img)
if strip is None:
continue
cells.append(strip)
manifest.append(
{
"idx": len(cells) - 1,
"uid": r["uid"],
"cls": cls,
"path": r["path"],
"fired": "|".join(sorted(k for k, m in r["marks"].items() if m["strict"])),
**{f"ncc_{k}": m["conf"] for k, m in r["marks"].items()},
}
)
cell_h = max(c.shape[0] for c in cells)
for si in range(0, len(cells), PER):
chunk = cells[si : si + PER]
sheet = np.full((ROWS * (cell_h + 26), COLS * (CELL_W + 8), 3), 40, np.uint8)
for i, c in enumerate(chunk):
rr, cc = divmod(i, COLS)
y0, x0 = rr * (cell_h + 26) + 22, cc * (CELL_W + 8) + 4
sheet[y0 : y0 + c.shape[0], x0 : x0 + c.shape[1]] = c
cv2.putText(sheet, f"{si + i:03d}", (x0, y0 - 6), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)
cv2.imwrite(str(out / f"r{si // PER:02d}.png"), sheet)
with (out / "MANIFEST_DO_NOT_OPEN.csv").open("w", newline="") as fh:
w = csv.DictWriter(fh, fieldnames=list(manifest[0]))
w.writeheader()
w.writerows(manifest)
print(f"cells={len(cells)} sheets={(len(cells) + PER - 1) // PER} -> {out}")
print("each cell = TOP-LEFT corner above, BOTTOM-RIGHT corner below, near native scale")
if __name__ == "__main__":
main()
+14 -2
View File
@@ -10,6 +10,11 @@ NOT sufficient (their NCC detector is fooled by a thin residual outline -- see
CLAUDE.md). Treat a detector-clean Doubao/Jimeng as "detector passes"; visual
residual is a separate check.
Backend: for a REALISTIC quality audit pass ``--backend migan`` (the production
fill), not ``cv2``. Removal SUCCESS (detector-clean) is backend-independent, so cv2
is fine for a fast pass/fail sweep, but only migan/lama reflect the recovered-region
quality a user actually gets. Run migan when validating the visible pipeline for real.
Operates on gitignored data only (data/spaces/...); writes nothing tracked.
uv run python scripts/visible_removal_audit.py \
@@ -54,7 +59,14 @@ def _rel(p: Path, corpus: Path) -> str:
help="Audit only these paths (one per line), skipping the full rglob.",
)
@click.option("--limit", type=int, default=0, help="Scan at most N files (0 = all).")
def main(corpus: Path, out: Path, dataset_root: Path, paths_file: Path | None, limit: int) -> None:
@click.option(
"--backend",
type=click.Choice(["auto", "cv2", "migan", "lama"]),
default="auto",
help="Fill backend for removal. Removal SUCCESS (detector-clean) is backend-independent; "
"cv2 is fastest for a bulk audit, migan/lama only change recovered-region quality.",
)
def main(corpus: Path, out: Path, dataset_root: Path, paths_file: Path | None, limit: int, backend: str) -> None:
logging.basicConfig(level=logging.WARNING, format="%(message)s")
if paths_file is not None:
files = [Path(s) for line in paths_file.read_text().splitlines() if (s := line.strip()) and Path(s).is_file()]
@@ -86,7 +98,7 @@ def main(corpus: Path, out: Path, dataset_root: Path, paths_file: Path | None, l
shutil.copy2(p, ddir / p.name)
# Remove, then re-detect with the SAME mark's detector.
try:
cleaned, _ = mark.remove(img)
cleaned, _ = mark.remove(img, backend=backend)
after = mark.detect(cleaned)
except Exception as exc:
log.warning("remove failed on %s (%s): %s", p.name, det.key, exc)
+101
View File
@@ -0,0 +1,101 @@
"""Build BLIND contact sheets for hand-labelling relaxation additions.
Crops are centered on the DETECTED REGION (not the corner), padded by ~0.9x the mark
size, and resized to 240px with INTER_NEAREST -- a downscaled preview destroys a faint
mark, so nothing here may smooth. The manifest is written to a separate file that must
NOT be read until labelling is finished.
Each sheet mixes three strata in shuffled order:
add - the relaxation additions whose precision we are measuring
pos - strict-consistent detections (a mark is really there): labeller sensitivity
clean - verified-clean negatives (no mark can be there): labeller specificity
The two control strata are what make a low measured precision trustworthy.
"""
import csv
import json
import random
import sys
from pathlib import Path
from typing import Any
import cv2
import numpy as np
from numpy.typing import NDArray
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
from remove_ai_watermarks import watermark_registry as wr
from remove_ai_watermarks.image_io import imread
CELL = 240
COLS, ROWS = 6, 3
PER = COLS * ROWS
def region_for(path: str, key: str) -> tuple[int, int, int, int] | None:
"""Re-detect to recover the mark bbox (Candidate carries no region)."""
img = imread(path)
if img is None:
return None
mark = next(m for m in wr._REGISTRY if m.key == key)
d = mark.detect(img, provenance=True)
return d.region if d.region else None
def crop(path: str, region: tuple[int, int, int, int] | None, pad_factor: float = 0.9) -> NDArray[Any] | None:
img = imread(path)
if img is None:
return None
h, w = img.shape[:2]
if region:
x, y, rw, rh = region
else:
return None
px, py = int(rw * pad_factor), int(rh * pad_factor)
x0, y0 = max(0, x - px), max(0, y - py)
x1, y1 = min(w, x + rw + px), min(h, y + rh + py)
c = img[y0:y1, x0:x1]
if c.size == 0:
return None
s = CELL / max(c.shape[0], c.shape[1])
return cv2.resize(c, (max(1, int(c.shape[1] * s)), max(1, int(c.shape[0] * s))), interpolation=cv2.INTER_NEAREST)
def main() -> None:
with open(sys.argv[1]) as fh:
items = json.load(fh) # [{uid,path,key,stratum,conf}]
outdir = Path(sys.argv[2])
outdir.mkdir(parents=True, exist_ok=True)
random.Random(1234).shuffle(items) # noqa: S311 -- sheet ordering, not cryptography
manifest = []
cells = []
for it in items:
reg = region_for(it["path"], it["key"])
c = crop(it["path"], reg)
if c is None:
continue
cells.append((it, c))
for si in range(0, len(cells), PER):
chunk = cells[si : si + PER]
sheet = np.full((ROWS * (CELL + 26), COLS * (CELL + 8), 3), 40, np.uint8)
for i, (it, c) in enumerate(chunk):
r, col = divmod(i, COLS)
y0 = r * (CELL + 26) + 22
x0 = col * (CELL + 8) + 4
sheet[y0 : y0 + c.shape[0], x0 : x0 + c.shape[1]] = c
label = f"{si + i:04d}" # index ONLY -- no stratum, no confidence
cv2.putText(sheet, label, (x0, y0 - 6), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)
manifest.append({"idx": si + i, **it})
cv2.imwrite(str(outdir / f"sheet_{si // PER:03d}.png"), sheet)
with open(outdir / "MANIFEST_DO_NOT_OPEN.csv", "w", newline="") as fh:
w = csv.DictWriter(fh, fieldnames=list(manifest[0]))
w.writeheader()
w.writerows(manifest)
print(f"sheets={(len(cells) + PER - 1) // PER} cells={len(cells)} -> {outdir}")
if __name__ == "__main__":
main()
+1 -1
View File
@@ -25,7 +25,7 @@ _os.environ.setdefault("TRANSFORMERS_VERBOSITY", "error")
_warnings.filterwarnings("ignore", message=r".*ImageProcessorFast.*")
__version__ = "0.15.0"
__version__ = "0.19.0"
__all__ = ["__version__", "remove_visible", "visible_provenance"]
+365 -31
View File
@@ -1,8 +1,8 @@
"""Shared base for the visible text-mark detectors/localizers (localize -> fill).
The Doubao "豆包AI生成", Jimeng "★ 即梦AI", and Samsung "✦ Contenuti generati
dall'AI" marks are the SAME algorithm: anchor a bottom-corner box by width-relative
geometry, extract the light low-saturation glyph candidate (white top-hat), detect
dall'AI" marks are the SAME algorithm: anchor a bottom-corner box by geometry
relative to the image's SHORT side, extract the light low-saturation glyph candidate (white top-hat), detect
by matching the bundled alpha-glyph silhouette via ``TM_CCOEFF_NORMED``, and build a
removal MASK from the glyph blob's bounding box (:meth:`footprint_mask`) for the
shared fill (region_eraser). The mask is template-FREE -- the top-hat glyph bbox, not
@@ -54,10 +54,41 @@ _MIN_DETECT_SHORT_SIDE = 200
# Provenance-confirmed NCC relaxation. When external metadata already confirms the
# vendor (so the mark is present with high prior), a faint or slightly re-rendered
# glyph that scores just below the standard NCC gate is still trusted. 0.7 recovers
# the near-threshold marks without dropping so low that an unrelated corner texture
# on a (provenance-confirmed) image would match -- the coverage gate still applies.
_PROVENANCE_NCC_FACTOR = 0.7
# glyph that scores just below the standard NCC gate is still trusted. The relaxed
# gate is ``detect_ncc_threshold * provenance_ncc_factor``; the coverage gate still
# applies on top.
#
# This used to be ONE shared 0.7 for every text mark. Measured 2026-07-18 on the
# `auto` path (the default -- no flag, driven by TC260 metadata), it turned out to
# mean two completely different things per mark. Blind hand-label of the ADDITIONS
# (accepted with provenance, rejected without) over 4417 unique TC260 carriers,
# two-sided control (labeller sensitivity 100%/96%, specificity 100%/100%):
#
# mark band precision 95% CI n
# doubao whole arm 76% 61-87% 42
# [0.280,0.340) 58% 36-77% 19
# [0.340,0.400) 91% 73-98% 23
# jimeng whole arm 17% 10-27% 82
# [0.315,0.383) 12% 6-22% 68
# [0.383,0.450) 43% 21-67% 14
#
# Doubao stays at 0.70: both its bands return more true marks than false fills, so
# tightening would cost 11 genuine recoveries to prevent 8 false ones.
#
# Jimeng moves to 0.85. Its relaxed detector does not key on the "★ 即梦AI" wordmark
# any more -- it keys on "some text in the bottom-right corner": of 68 false
# additions, 33 were DOUBAO marks and 17 were other vendors' AI labels (千问, 百度,
# 星绘, 抖音). 45 of those 68 fill a corner nothing else would touch (the other 23
# are harmless -- doubao fires strictly there and fills the same box anyway). At
# 0.85 the [0.315,0.383) band is dropped: 8 genuine recoveries lost, 60 false fills
# prevented (7.5:1). A false fill is the worse error -- it destroys pixels AND makes
# the caller report a removal that did not happen, while a miss leaves the image
# untouched.
#
# NOTE: 0.85 is a patch on a detector problem, not a fix. Jimeng's silhouette is not
# discriminative against Doubao's (same corner, same script, both ByteDance), and no
# threshold repairs that -- it needs a better detection silhouette.
_DEFAULT_PROVENANCE_NCC_FACTOR = 0.7
@dataclass(frozen=True)
@@ -66,9 +97,11 @@ class TextMarkConfig:
name: str # short label for log lines (e.g. "Doubao")
asset_name: str # bundled alpha PNG under assets/ (e.g. "doubao_alpha.png")
corner: Literal["br", "bl"] # bottom-right (Doubao/Jimeng) or bottom-left (Samsung)
corner: Literal[
"br", "bl", "tl", "bc"
] # bottom-right (Doubao/Jimeng), bottom-left (Samsung), top-left (RunningHub), bottom-center (LibLibAI)
margin_floor: int # min margin in px for locate (4 for br marks, 2 for Samsung)
# locate geometry (fraction of image WIDTH)
# locate geometry (fraction of scale_base -- see scale_base())
width_frac: float
height_frac: float
margin_x_frac: float # right margin (br) or left margin (bl)
@@ -81,12 +114,44 @@ class TextMarkConfig:
# detection
detect_min_coverage: float
detect_ncc_threshold: float
# alpha-map glyph geometry (fraction of WIDTH) emitted by
# alpha-map glyph geometry (fraction of scale_base) emitted by
# scripts/visible_alpha_solve.py, sizing the detection silhouette for
# template_match_score
alpha_width_frac: float
alpha_height_frac: float
min_gw: int # minimum glyph width for the template match (8 br, 16 Samsung)
# Asset names of RIVAL marks that occupy the same corner and can therefore be
# scored against the same glyph blob. Detection becomes COMPETITIVE: this mark's
# template must beat every rival's by `rival_margin`. See _rival_margin_ok.
# Detection front-end. "binary" thresholds the top-hat into a glyph blob and
# correlates a binary silhouette against it; "tophat" correlates the CONTINUOUS
# top-hat response against a soft template and never binarizes. See
# TextMarkEngine.tophat_response for the measurement that motivated the split.
# "gray" correlates the silhouette against the raw GRAYSCALE of the locate box:
# for a faint mid-gray mark (RunningHub) the top-hat's background-subtraction and
# max-normalization suppress the response to clean-arm levels (positives 0.16-0.23
# vs clean p99 0.31), while raw gray NCC separates (positives 0.38-0.54 vs clean
# p99 0.264 / max 0.304, measured 2026-07-22). Contrast-DEPENDENT, unlike tophat.
detect_frontend: Literal["binary", "tophat", "gray"] = "binary"
# Gaussian sigma applied to the template in the "tophat" front-end (0 = none).
template_blur: float = 0.0
# Which image dimension the mark's size and margins scale with. VENDOR-SPECIFIC,
# measured, not assumed -- see TextMarkEngine.scale_base. "short" = min(h, w), "width" = w.
scale_basis: Literal["short", "width"] = "width"
# Scale rungs ``_tophat_best`` sweeps (the detection comb). PER-MARK: a vendor
# whose stamp sizes do not land on the shared 3-rung comb carries its own ladder
# (measured for 千问, whose marks sit in two size modes ~1.6x apart -- one fraction
# on 3 rungs covers only ~75% of them). Densifying the SHARED ladder for everyone
# was measured and rejected (false fire 2.52% -> 3.05%; see docs/verification-plan.md
# B2), so the default stays the shipped 3 rungs and a deviation must be calibrated
# per mark on real positives, never ported.
ladder: tuple[float, ...] = (0.8, 1.0, 1.25)
rivals: tuple[str, ...] = ()
rival_margin: float = 0.10
# Multiplier applied to detect_ncc_threshold when provenance confirms the vendor.
# Per-mark, NOT shared: see _DEFAULT_PROVENANCE_NCC_FACTOR for the measured
# precision that forced the split. Last field so it can carry a default.
provenance_ncc_factor: float = _DEFAULT_PROVENANCE_NCC_FACTOR
@dataclass
@@ -146,18 +211,49 @@ def glyph_silhouette(asset_name: str) -> NDArray[Any] | None:
return _silhouette_cache[asset_name]
def template_match_score(box_mask: NDArray[Any], image_width: int, config: TextMarkConfig) -> float:
_RIVAL_MODULES = {
"doubao_alpha.png": "remove_ai_watermarks.doubao_engine",
"jimeng_alpha.png": "remove_ai_watermarks.jimeng_engine",
"samsung_alpha.png": "remove_ai_watermarks.samsung_engine",
}
def _rival_config(asset_name: str, fallback: TextMarkConfig) -> TextMarkConfig:
"""The rival mark's own config, for scoring its template on a shared blob.
Looked up LAZILY by asset name: a rival's template geometry
(``alpha_*_frac`` / ``min_gw``) is its own, and scoring it with this mark's
geometry would compare a correctly-sized template against a mis-sized one and
hand the margin a free win. Lazy because the engine modules import this one.
"""
mod_path = _RIVAL_MODULES.get(asset_name)
if mod_path is None:
return fallback
from importlib import import_module
try:
return import_module(mod_path)._CONFIG
except Exception: # a missing/renamed engine must not break detection
logger.debug("rival config %s unavailable; skipping its margin check.", asset_name)
return fallback
def template_match_score(box_mask: NDArray[Any], scale_base: int, config: TextMarkConfig) -> float:
"""Zero-mean normalized correlation of the alpha-template glyph silhouette
(scaled to the mark's expected size) against the candidate ``box_mask``.
``TM_CCOEFF_NORMED`` keys on glyph SHAPE, not coverage, so a dense textured
corner does not score highly -- only the actual glyph shape does.
``scale_base`` is the mark's own scaling dimension (:meth:`TextMarkEngine.scale_base`),
not always the width: sizing the template on the wrong basis stretches it by the
aspect ratio on landscape inputs and the correlation collapses.
"""
sil = glyph_silhouette(config.asset_name)
if sil is None or box_mask.size == 0:
return 0.0
gw = min(box_mask.shape[1] - 1, max(config.min_gw, int(config.alpha_width_frac * image_width)))
gh = min(box_mask.shape[0] - 1, max(4, int(config.alpha_height_frac * image_width)))
gw = min(box_mask.shape[1] - 1, max(config.min_gw, int(config.alpha_width_frac * scale_base)))
gh = min(box_mask.shape[0] - 1, max(4, int(config.alpha_height_frac * scale_base)))
if gw < config.min_gw or gh < 4:
return 0.0
template = cv2.resize(sil, (gw, gh), interpolation=cv2.INTER_NEAREST)
@@ -178,21 +274,216 @@ class TextMarkEngine:
def _glyph_silhouette(self) -> NDArray[Any] | None:
return glyph_silhouette(self.config.asset_name)
def _template_match_score(self, box_mask: NDArray[Any], image_width: int) -> float:
return template_match_score(box_mask, image_width, self.config)
def _template_match_score(self, box_mask: NDArray[Any], scale_base: int) -> float:
return template_match_score(box_mask, scale_base, self.config)
def _rival_margin_ok(self, score: float, box_mask: NDArray[Any], scale_base: int) -> bool:
"""Whether this mark's template beats every same-corner RIVAL's on the SAME blob.
Detection was purely ABSOLUTE -- each engine scored its own template and
compared against its own threshold, so nothing ever asked the discriminative
question "does this blob look more like the neighbour's mark than like mine?".
Two marks sharing a corner and a script (Doubao "豆包AI生成" and Jimeng
"★ 即梦AI", both bottom-right, both near-white CJK) survive binarization into
very similar blobs, so an absolute gate cannot separate them -- and under the
provenance relaxation it stopped trying: 33 of jimeng's 68 false additions
were Doubao marks (corpus-measured 2026-07-18).
Measured separability on hand-labelled examples, scoring BOTH templates
against the same glyph blob (n=40 jimeng / 75 doubao / 20 other-vendor labels
/ 89 clean):
feature separability (0.5 = useless, 1.0 = perfect)
absolute ncc_jimeng 0.96
ncc_jimeng MINUS ncc_doubao 0.99
At a 0.10 margin: real Jimeng wordmarks pass 100%, Doubao strips 8%, other
vendors' AI labels (千问/百度/星绘/抖音) 55%, no-mark corners 12%. Because the
real marks pass at 100%, this costs NO recall -- it is a pure precision gain,
unlike raising the threshold, which trades recall away.
Marks with no same-corner rival declare `rivals=()` and are unaffected.
"""
c = self.config
if not c.rivals:
return True
for rival_asset in c.rivals:
rival = _rival_config(rival_asset, c)
if score - template_match_score(box_mask, scale_base, rival) < c.rival_margin:
logger.debug("%s detect: loses the %s rival margin; rejecting.", c.name, rival_asset)
return False
return True
# ── Locate ──────────────────────────────────────────────────────────
def tophat_response(self, image: NDArray[Any], loc: TextMarkLocation) -> NDArray[Any] | None:
"""The CONTINUOUS white top-hat in the located box -- the glyph signal, unbinarized.
:meth:`extract_mask` thresholds this same response into a 0/255 glyph blob. That
is fine for a mark stamped bold and opaque, and destructive for a faint one: a
thin translucent overlay shatters into specks under the threshold, and no
template can match a blob that is not there.
Measured 2026-07-18 on hand-verified corpus positives (40 doubao, 14 千问, 60
verified-clean), scoring each mark with its own template:
front-end doubao clean neg AUC doubao/neg
binary 0.723 ~0.12 --
tophat 0.781 0.122 1.00
The gates that were hard cuts in the binary path (saturation, absolute luma)
become WEIGHTS here, so a faint stroke contributes in proportion to its strength
instead of being dropped at a threshold. The response is max-normalized, which
makes the score contrast-invariant -- the point of the exercise.
Kept per-mark (``detect_frontend``) rather than switched globally, because a
front-end change must be measured per mark before it ships.
"""
c = self.config
x, y, bw, bh = loc.bbox
if bh < 16 or bw < 16:
return None
roi = image_io.to_bgr(image[y : y + bh, x : x + bw]).astype(np.float32)
luma = roi.mean(axis=2)
sat = roi.max(axis=2) - roi.min(axis=2)
sigma = max(4.0, bh * 0.4)
tophat = luma - cv2.GaussianBlur(luma, (0, 0), sigmaX=sigma, sigmaY=sigma)
resp = np.clip(tophat, 0, None) * (sat < c.max_saturation)
peak = float(resp.max())
if peak <= 1e-6:
return None
return (resp / peak * 255).astype(np.uint8)
def _tophat_best(
self, image: NDArray[Any], loc: TextMarkLocation
) -> tuple[float, tuple[int, int, int, int] | None]:
"""Best TM_CCOEFF_NORMED of a soft template against the continuous response, and
the ROI-local box (x0, y0, x1, y1) where that best match sits.
Sweeps the mark's scale ladder: the nominal glyph size is derived from the mark's
geometry, but a vendor re-rasterization shifts it by a few percent and the
continuous response is sharp enough that an exact-size template would miss. The
ladder is per-mark (``TextMarkConfig.ladder``), defaulting to the shipped 3 rungs.
Detection and the removal mask BOTH read this one method -- the score gates
detection, the box bounds the fill. Sharing it is deliberate: the standing rule is
that detection and the mask use the same front-end, and the way that rule was last
broken was a drift between two separate implementations. One method makes the drift
impossible instead of merely discouraged.
"""
c = self.config
resp = self.tophat_response(image, loc)
sil = self._glyph_silhouette()
if resp is None or sil is None:
return (0.0, None)
base = self.scale_base(image)
best_score = 0.0
best_box: tuple[int, int, int, int] | None = None
for scale in c.ladder:
gw = max(c.min_gw, int(c.alpha_width_frac * base * scale))
gh = max(4, int(c.alpha_height_frac * base * scale))
if gw >= resp.shape[1] or gh >= resp.shape[0]:
continue
tmpl = cv2.resize(sil, (gw, gh), interpolation=cv2.INTER_AREA).astype(np.float32)
if c.template_blur > 0:
tmpl = cv2.GaussianBlur(tmpl, (0, 0), sigmaX=c.template_blur, sigmaY=c.template_blur)
result = cv2.matchTemplate(resp, tmpl.astype(np.uint8), cv2.TM_CCOEFF_NORMED)
_, score, _, top_left = cv2.minMaxLoc(result)
if score > best_score:
tx, ty = int(top_left[0]), int(top_left[1])
best_score, best_box = float(score), (tx, ty, tx + gw - 1, ty + gh - 1)
return (best_score, best_box)
def _tophat_score(self, image: NDArray[Any], loc: TextMarkLocation) -> float:
"""The detection score alone -- the box the removal mask needs is discarded here."""
return self._tophat_best(image, loc)[0]
def _gray_best(self, image: NDArray[Any], loc: TextMarkLocation) -> tuple[float, tuple[int, int, int, int] | None]:
"""Best TM_CCOEFF_NORMED of the silhouette against the raw GRAYSCALE ROI, and
the ROI-local box (x0, y0, x1, y1) of that best match.
Mirrors :meth:`_tophat_best` (same ladder sweep, same one-method contract so
detection and the removal mask can never drift), but skips the top-hat
entirely: the RunningHub mark is a faint mid-gray text the top-hat's
background subtraction suppresses to clean-arm levels, while raw gray NCC
separates (see ``TextMarkConfig.detect_frontend``). Contrast-DEPENDENT by
construction, so the gate must be picked against the clean arm, which is
what ``scripts/vendor_mark_calibrate.py`` does.
"""
c = self.config
x, y, bw, bh = loc.bbox
if bh < 16 or bw < 16:
return (0.0, None)
roi = cv2.cvtColor(image_io.to_bgr(image[y : y + bh, x : x + bw]), cv2.COLOR_BGR2GRAY)
sil = self._glyph_silhouette()
if sil is None:
return (0.0, None)
base = self.scale_base(image)
best_score = 0.0
best_box: tuple[int, int, int, int] | None = None
for scale in c.ladder:
gw = max(c.min_gw, int(c.alpha_width_frac * base * scale))
gh = max(4, int(c.alpha_height_frac * base * scale))
if gw >= roi.shape[1] or gh >= roi.shape[0]:
continue
tmpl = cv2.resize(sil, (gw, gh), interpolation=cv2.INTER_AREA)
result = cv2.matchTemplate(roi, tmpl, cv2.TM_CCOEFF_NORMED)
_, score, _, top_left = cv2.minMaxLoc(result)
if score > best_score:
tx, ty = int(top_left[0]), int(top_left[1])
best_score, best_box = float(score), (tx, ty, tx + gw - 1, ty + gh - 1)
return (best_score, best_box)
def scale_base(self, image: NDArray[Any]) -> int:
"""The image dimension this mark's geometry scales with.
Per-mark, and MEASURED -- a single shared basis is wrong. The tuned fractions
were all calibrated on PORTRAIT captures, where width and short side coincide,
so the basis was never exercised until landscape inputs were measured.
Corpus-measured 2026-07-18 (2572 unique TC260 carriers; the harness is
`scripts/visible_eval.py`). Before any fix, doubao detection by aspect ratio:
portrait 60%, square 41%, **landscape 0% (0 of 435)** -- the width-scaled box
is inflated by the aspect ratio on a wide image and the glyph never lands in
it. Re-running the previously-undetected set with a short-side basis recovered
**56% of landscape** images (12% square, 4% portrait).
But the same switch took JIMENG's labelled landscape positives from 13/13 to
0/13: its wordmark tracks the WIDTH. Both marks are ByteDance and share a
corner, and they still scale differently -- so this is a per-mark measurement,
not a house rule to generalize. Samsung keeps ``width`` because there is no
corpus evidence either way (1 addition corpus-wide) and an unmeasured change
is not an improvement.
China's GB 45438-2025 clause 5.2(e) mandates glyph height >= 5% of "the
shortest side" for CN marks, which is why a short-side basis is the natural
prior -- but Jimeng's measured behaviour overrides the prior, and measurement
wins over the standard's wording.
"""
return min(image.shape[:2]) if self.config.scale_basis == "short" else image.shape[1]
def locate(self, image: NDArray[Any]) -> TextMarkLocation:
"""Anchor the watermark box in the configured bottom corner by geometry."""
"""Anchor the watermark box in the configured corner, scaled by ``scale_basis``.
Every fraction is taken against ``scale_base(image)`` -- see
:data:`TextMarkConfig.scale_basis`, which is per-mark because the vendors
genuinely differ.
"""
c = self.config
h, w = image.shape[:2]
wm_w = max(40, int(w * c.width_frac))
wm_h = max(16, int(w * c.height_frac))
margin_x = max(c.margin_floor, int(w * c.margin_x_frac))
margin_b = max(c.margin_floor, int(w * c.margin_bottom_frac))
x = max(0, w - margin_x - wm_w) if c.corner == "br" else min(margin_x, max(0, w - wm_w))
y = max(0, h - margin_b - wm_h)
base = self.scale_base(image)
wm_w = max(40, int(base * c.width_frac))
wm_h = max(16, int(base * c.height_frac))
margin_x = max(c.margin_floor, int(base * c.margin_x_frac))
margin_b = max(c.margin_floor, int(base * c.margin_bottom_frac))
if c.corner == "br":
x = max(0, w - margin_x - wm_w)
elif c.corner == "bc": # bottom-center: horizontally centered, margin_x unused
x = max(0, (w - wm_w) // 2)
else:
x = min(margin_x, max(0, w - wm_w))
# "tl" anchors at the top instead: margin_bottom_frac is then the TOP margin.
y = min(margin_b, max(0, h - wm_h)) if c.corner == "tl" else max(0, h - margin_b - wm_h)
wm_w = min(wm_w, w - x)
wm_h = min(wm_h, h - y)
return TextMarkLocation(x=x, y=y, w=wm_w, h=wm_h, is_fallback=True)
@@ -251,7 +542,8 @@ class TextMarkEngine:
(China-AIGC / byteimg for Doubao/Jimeng, ``samsung_genai`` for Samsung); the
NCC gate exists to keep a corner texture on an UNRELATED image from matching
the glyph silhouette, so when provenance confirms the vendor it is relaxed by
``_PROVENANCE_NCC_FACTOR`` to recover a faint or slightly re-rendered mark.
the mark's own ``provenance_ncc_factor`` to recover a faint or slightly
re-rendered mark (per-mark, not shared -- see _DEFAULT_PROVENANCE_NCC_FACTOR).
"""
c = self.config
det = TextMarkDetection()
@@ -274,11 +566,29 @@ class TextMarkEngine:
coverage = float((box > 0).sum()) / float(max(1, bw * bh))
det.region = loc.bbox
det.coverage = coverage
if coverage >= c.detect_min_coverage:
score = self._template_match_score(box, image.shape[1])
threshold = c.detect_ncc_threshold * (_PROVENANCE_NCC_FACTOR if provenance else 1.0)
if c.detect_frontend == "tophat":
# The continuous front-end does not depend on the binarized blob, so the
# coverage gate (a blob-area heuristic) does not apply to it.
score = self._tophat_score(image, loc)
threshold = c.detect_ncc_threshold * (c.provenance_ncc_factor if provenance else 1.0)
det.confidence = score
det.detected = score >= threshold
det.detected = score >= threshold and self._rival_margin_ok(score, box, self.scale_base(image))
logger.debug("%s detect (tophat): ncc=%.2f thr=%.2f detected=%s", c.name, score, threshold, det.detected)
return det
if c.detect_frontend == "gray":
# Same no-coverage-gate reasoning as tophat: the gray front-end never
# binarizes, so a blob-area heuristic does not apply to it either.
score = self._gray_best(image, loc)[0]
threshold = c.detect_ncc_threshold * (c.provenance_ncc_factor if provenance else 1.0)
det.confidence = score
det.detected = score >= threshold and self._rival_margin_ok(score, box, self.scale_base(image))
logger.debug("%s detect (gray): ncc=%.2f thr=%.2f detected=%s", c.name, score, threshold, det.detected)
return det
if coverage >= c.detect_min_coverage:
score = self._template_match_score(box, self.scale_base(image))
threshold = c.detect_ncc_threshold * (c.provenance_ncc_factor if provenance else 1.0)
det.confidence = score
det.detected = score >= threshold and self._rival_margin_ok(score, box, self.scale_base(image))
logger.debug(
"%s detect: coverage=%.3f ncc=%.2f thr=%.2f detected=%s",
c.name,
@@ -325,12 +635,36 @@ class TextMarkEngine:
bx, by, bw, bh = loc.bbox
glyph = self.extract_mask(image, loc) # box-sized, 255 = glyph
ys, xs = np.where(glyph > 0)
if xs.size >= self._MIN_GLYPH_PIXELS:
box: tuple[int, int, int, int] | None = None
if self.config.detect_frontend == "gray" and self.detect(image).detected:
# The gray front-end exists for marks the top-hat under-segments, so the
# binary blob is NOT authoritative here: trusting it first bounded the
# fill by a PARTIAL blob (the faint head glyphs dropped out) and left the
# leftmost "Runni" of "RunningHub AI生成" unremoved (2026-07-22). Use the
# detector's own best-match box, same as the tophat faint path below.
_, box = self._gray_best(image, loc)
elif xs.size >= self._MIN_GLYPH_PIXELS:
box = (int(xs.min()), int(ys.min()), int(xs.max()), int(ys.max()))
elif self.config.detect_frontend == "tophat" and self.detect(image).detected:
# A mark found only by the CONTINUOUS front-end has no binary glyph blob to
# bound, so the mask came back empty and removal was a silent no-op while
# `identify` still reported the mark (corpus-measured 2026-07-20: 57 of 60
# sampled still-detected Doubao marks were untouched, ~8% of its detections).
# Use the DETECTOR'S OWN best-match box: the correlation already located the
# mark at a position and scale, and thresholding the response was a strictly
# worse proxy for that. An earlier fix thresholded the max-normalized uint8
# response at 0.5 -- which selects every non-zero pixel, not "half the peak" as
# its comment claimed -- and filled ~120% of the corner box on textured frames
# (measured: whole corner vs 58.7% for the match box, both detector-clean).
# Gated on an actual detection: on a clean corner the box would be spurious.
_, box = self._tophat_best(image, loc)
if box is not None:
gx0, gy0, gx1, gy1 = box
pad = max(4, int(0.10 * bh))
rx1 = max(0, bx + int(xs.min()) - pad)
rx2 = min(w, bx + int(xs.max()) + 1 + pad)
ry1 = max(0, by + int(ys.min()) - pad)
ry2 = min(h, by + int(ys.max()) + 1 + pad)
rx1 = max(0, bx + gx0 - pad)
rx2 = min(w, bx + gx1 + 1 + pad)
ry1 = max(0, by + gy0 - pad)
ry2 = min(h, by + gy1 + 1 + pad)
elif force:
rx1, ry1, rx2, ry2 = bx, by, min(w, bx + bw), min(h, by + bh)
else:
+94 -43
View File
@@ -8,7 +8,7 @@ up metadata provenance, or preserve the alpha channel by hand:
import remove_ai_watermarks as raiw
raiw.remove_visible("in.png", "out.png") # path -> file, provenance auto
result, removed = raiw.remove_visible(bgr_array) # array -> array
raiw.remove_visible("shot.png", "out.png", sensitivity="assume_ai")
raiw.remove_visible("shot.png", "out.png", sensitivity="strict")
raiw.visible_provenance("in.png") # -> frozenset({"gemini"})
Imports stay lazy (inside the functions), so ``import remove_ai_watermarks`` is cheap.
@@ -16,6 +16,7 @@ Imports stay lazy (inside the functions), so ``import remove_ai_watermarks`` is
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, Any
@@ -25,6 +26,16 @@ if TYPE_CHECKING:
from remove_ai_watermarks.watermark_registry import Backend, Sensitivity
@dataclass(frozen=True)
class _VisibleInput:
"""Normalized visible-removal input with its file-only context."""
bgr: NDArray[Any]
alpha: NDArray[Any] | None = None
path: Path | None = None
provenance: frozenset[str] = frozenset()
def visible_provenance(source: str | Path) -> frozenset[str]:
"""Vendor keys that the file's local metadata confirms, the evidence that drives
the ``auto`` sensitivity (relaxing a corroborated mark's detection trust gate).
@@ -36,19 +47,76 @@ def visible_provenance(source: str | Path) -> frozenset[str]:
"""
import contextlib
keys: set[str] = set()
path = Path(source)
with contextlib.suppress(Exception):
from remove_ai_watermarks import identify, metadata
from remove_ai_watermarks import identify
rep = identify.identify(Path(source), check_visible=False, check_invisible=False)
rep = identify.identify(path, check_visible=False, check_invisible=False)
signal_names = {signal.name for signal in rep.signals}
keys: set[str] = set()
platform = (rep.platform or "").lower()
if "google" in platform or "gemini" in platform:
keys.add("gemini")
if metadata.aigc_label(Path(source)):
if "aigc" in signal_names:
keys |= {"doubao", "jimeng"}
if metadata.samsung_genai(Path(source)):
if "samsung_genai" in signal_names:
keys.add("samsung")
return frozenset(keys)
return frozenset(keys)
return frozenset()
def _load_visible_input(source: str | Path | NDArray[Any]) -> _VisibleInput:
"""Normalize a path/array source without making the public operation stateful."""
if not isinstance(source, (str, Path)):
return _VisibleInput(source)
from remove_ai_watermarks import image_io
path = Path(source)
bgr, alpha = image_io.read_bgr_and_alpha(path)
if bgr is None:
raise ValueError(f"Could not read image: {source}")
return _VisibleInput(bgr=bgr, alpha=alpha, path=path, provenance=visible_provenance(path))
def _write_visible_result(
loaded: _VisibleInput,
result: NDArray[Any],
removed: list[str],
output: str | Path,
*,
strip_metadata: bool,
write_noop: bool,
) -> None:
"""Write one visible-removal result while preserving a true no-op losslessly."""
if not removed and not write_noop:
return
from remove_ai_watermarks import image_io
out_path = Path(output)
out_path.parent.mkdir(parents=True, exist_ok=True)
source_path = loaded.path
if not removed and source_path is not None and source_path.suffix.lower() == out_path.suffix.lower():
# Copy the ORIGINAL bytes instead of lossily re-encoding a no-op. An in-place
# call needs no copy and would otherwise raise shutil.SameFileError.
if source_path.resolve() != out_path.resolve():
import shutil
shutil.copyfile(source_path, out_path)
else:
# imwrite is contractually NON-RAISING, so this bool is the only signal the file
# was not created. Unchecked, the metadata strip below ran on a nonexistent path
# and surfaced as a confusing "cannot read image <INPUT>" naming the OUTPUT path
# (Tier E, 2026-07-20). Raise here so a library caller and the CLI both get an
# accurate message about the write.
if not image_io.write_bgr_with_alpha(out_path, result, loaded.alpha):
raise OSError(f"failed to write output (is the destination writable?): {out_path}")
if strip_metadata:
from remove_ai_watermarks import metadata
metadata.remove_ai_metadata(out_path, out_path)
def remove_visible(
@@ -72,10 +140,8 @@ def remove_visible(
array is always returned as well, so an empty ``removed`` list tells a caller nothing
known was found (e.g. route to the diffusion ``all`` path or ``erase``).
``sensitivity`` (``auto``/``strict``/``assume_ai``) and ``backend``
``sensitivity`` (``auto``/``strict``) and ``backend``
(``auto``/``cv2``/``migan``/``lama``) are the same knobs as the CLI. Pass
``sensitivity="assume_ai"`` for a metadata-stripped screenshot the caller knows is
AI-generated (best recall, at the cost of a small near-lossless fill on a clean
corner if the guess is wrong).
``strip_metadata`` (default True, matching the CLI ``visible --strip-metadata``)
@@ -88,40 +154,25 @@ def remove_visible(
output path untouched, so a caller that treats "no mark" as "produce nothing" (the CLI
``visible`` no-mark contract) does not clobber a pre-existing file at that path.
"""
from remove_ai_watermarks import image_io, watermark_registry
alpha: NDArray[Any] | None = None
provenance: frozenset[str] = frozenset()
if isinstance(source, (str, Path)):
path = Path(source)
bgr, alpha = image_io.read_bgr_and_alpha(path)
if bgr is None:
raise ValueError(f"Could not read image: {source}")
provenance = visible_provenance(path)
else:
bgr = source
from remove_ai_watermarks import watermark_registry
# Reject a removed sensitivity loudly; `Sensitivity` is a Literal and not enforced
# at runtime, so a 0.15 caller would otherwise get `auto` behaviour in silence.
watermark_registry.validate_sensitivity(sensitivity)
loaded = _load_visible_input(source)
result, removed = watermark_registry.remove_auto_marks(
bgr, sensitivity=sensitivity, provenance=provenance, backend=backend
loaded.bgr,
sensitivity=sensitivity,
provenance=loaded.provenance,
backend=backend,
)
if output is not None and (removed or write_noop):
out_path = Path(output)
out_path.parent.mkdir(parents=True, exist_ok=True)
same_format = isinstance(source, (str, Path)) and Path(source).suffix.lower() == out_path.suffix.lower()
if not removed and same_format:
# Nothing was removed: copy the ORIGINAL bytes verbatim instead of a lossy
# re-encode of its decode, so the pixels stay bit-identical (the metadata
# strip below is lossless, so it does not disturb them either). Skip the copy
# for an in-place call (output == source): the bytes are already there, and
# shutil.copyfile would raise SameFileError.
if Path(source).resolve() != out_path.resolve(): # type: ignore[arg-type]
import shutil
shutil.copyfile(source, out_path) # type: ignore[arg-type]
else:
image_io.write_bgr_with_alpha(out_path, result, alpha)
if strip_metadata:
from remove_ai_watermarks import metadata
metadata.remove_ai_metadata(out_path, out_path)
if output is not None:
_write_visible_result(
loaded,
result,
removed,
output,
strip_metadata=strip_metadata,
write_noop=write_noop,
)
return result, removed
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

+203
View File
@@ -0,0 +1,203 @@
"""Baidu visible watermark detector/localizer.
Baidu stamps its generations with a white bold "百度" text run plus a separate
white rounded tag carrying dark "AI生成", bottom-right -- the China TC260
explicit AIGC label. Detection keys on the **百度 text run only**: a
two-component template (text + pill tag) was measured and REJECTED -- the solid
white pill is a bright-blob magnet and both front-ends scored the clean arm at
cohort levels (tophat clean p95 0.445 / gray clean p95 0.487 vs cohort ~0.5,
2026-07-22). The text-only silhouette separates cleanly (below). The white tag
is still removed with the mark: the fill blob covers both bright components in
the corner box.
Removal is the shared **localize -> fill** (:meth:`footprint_mask` ->
``region_eraser``). This module supplies only Baidu's tuned
:class:`TextMarkConfig` (``assets/baidu_alpha.png`` -- a font-rendered
synthetic silhouette from ``scripts/render_vendor_silhouettes.py``, never cut
from an upload).
Measured on the vendor cohort (16 TC260 carriers whose producer USCC
91110000802100433B names Baidu, harvested 2026-07-22 by
``scripts/vendor_cohort_harvest.py``), NOT inherited from Doubao:
* The 百度 text run is 0.090 of the SHORT side wide (measured on 720/768/
1024-px frames), with its right edge ~0.099 of short off the right edge
(the pill tag sits between the text and the corner), bottom margin
~0.006; the locate box below covers the whole mark (text + tag).
* Gate 0.43 (tophat front-end): on 278 hand-labelled clean frames
(cohort-contamination-guarded) the max is 0.352 / p99 0.314, and the
visibly-marked cohort frames score 0.386-0.65. Picked over the clean-arm
0.37 after a full-corpus check on the 741-frame blind-labelled eval set
surfaced 13 cross-fires at 0.38-0.43 (12 Qwen marks + one 抖音 mark) --
see DETECT_NCC_THRESHOLD below. At 0.43 the cohort keeps 7 detections
(0.61-0.65) and the whole 741 set fires only on the true Baidu frame.
* STRICT ONLY (``provenance_ncc_factor`` 1.0): the cohort is small (16) and
the sub-gate band is unmeasured, so no provenance relaxation exists.
"""
# The module-level _alpha_template / _glyph_silhouette / _template_match_score below
# are thin test-facing shims (imported by tests/), so pyright's src-only pass sees them
# as unused; the use is cross-module.
# pyright: reportUnusedFunction=false
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from remove_ai_watermarks import _text_mark_engine
from remove_ai_watermarks._text_mark_engine import TextMarkConfig, TextMarkDetection, TextMarkEngine
if TYPE_CHECKING:
from pathlib import Path
from numpy.typing import NDArray
# Locate geometry as a fraction of the image SHORT side (measured basis). The
# box covers the text run AND the pill tag to its right (tag right edge ~0.002
# off the frame edge, text run left edge ~0.19 off).
WM_WIDTH_FRAC = 0.25
WM_HEIGHT_FRAC = 0.07
MARGIN_RIGHT_FRAC = 0.002
MARGIN_BOTTOM_FRAC = 0.002
# Glyph appearance: white bold text on a usually-darker background (white
# top-hat), same overlay class as Doubao -- inherited, harmless because the
# tophat front-end turns these gates into weights.
MAX_SATURATION = 55
LOGO_MIN_LUMA = 150
TOPHAT_DELTA = 12
DETECT_MIN_COVERAGE = 0.04 # unused by the tophat front-end (kept for config parity)
# Calibrated 2026-07-22 on the vendor cohort vs 278 hand-labelled clean frames
# (clean p99 0.314 / max 0.352), THEN raised 0.37 -> 0.43 after a full-corpus
# check: on the 741-frame blind-labelled eval set the 0.37 gate fired 14 times
# outside the cohort, and only ONE was the vendor -- 12 were 千问AI生成 (Qwen)
# marks (the 百/千 first glyphs are near-identical after binarization) and one
# was a 抖音 AI创作 mark at 0.425. The Qwen fires are handled by the rival
# margin (Qwen scores 0.58-0.76 there, beating Baidu by 0.17-0.35), but the
# 抖音 one named no registered rival, so the gate moved above it. Cost: the
# cohort's low trio at 0.386 (3 genuine marks) -- precision over recall on a
# small cohort. Raised again 0.43 -> 0.48 after the full-corpus sweep
# (2026-07-22): outside-cohort true Baidu carriers score 0.50-0.66 while the
# false fires (大众点评 UI, a math blackboard, an 80s banner, a checkerboard)
# top out at 0.47. Remaining cohort detections: 7 at 0.61-0.65, plus the 6
# metadata-stripped true carriers the cohort cannot see.
DETECT_NCC_THRESHOLD = 0.48
# Detection-silhouette geometry (fraction of the short side): the 百度 text run
# only, measured 0.090 wide with aspect 0.51.
_ALPHA_WIDTH_FRAC = 0.090
_ALPHA_HEIGHT_FRAC = 0.046
# Tight ladder: the NCC comb is sharp in size (see runninghub_engine), so the
# nominal sits exactly on the measured 0.090 with +-5% rungs.
_LADDER = (0.95, 1.0, 1.05)
_CONFIG = TextMarkConfig(
name="Baidu",
asset_name="baidu_alpha.png",
corner="br",
margin_floor=4,
width_frac=WM_WIDTH_FRAC,
height_frac=WM_HEIGHT_FRAC,
margin_x_frac=MARGIN_RIGHT_FRAC,
margin_bottom_frac=MARGIN_BOTTOM_FRAC,
max_saturation=MAX_SATURATION,
logo_min_luma=LOGO_MIN_LUMA,
tophat_delta=TOPHAT_DELTA,
morph_open_size=5,
detect_min_coverage=DETECT_MIN_COVERAGE,
detect_ncc_threshold=DETECT_NCC_THRESHOLD,
detect_frontend="tophat",
scale_basis="short",
ladder=_LADDER,
alpha_width_frac=_ALPHA_WIDTH_FRAC,
alpha_height_frac=_ALPHA_HEIGHT_FRAC,
min_gw=8,
# Load-bearing rival margins (crossfire measured 2026-07-22): the 百度 and
# 豆包 silhouettes share their second glyph and a similar first, and 百度 vs
# 千问 are near-identical after binarization -- at the 0.37 gate this
# template fires on 45.8% of 400 Doubao-marked frames AND on Qwen-marked
# frames at 0.38-0.43. Doubao's template beats it by ~0.56 on Doubao marks,
# Qwen's by 0.17-0.35 on Qwen marks, so the 0.10 margin suppresses all of
# that crossfire at zero genuine-Baidu cost (cohort fire+m == fire).
rivals=("doubao_alpha.png", "qwen_alpha.png"),
# STRICT ONLY: small cohort, the relaxed band is unmeasured.
provenance_ncc_factor=1.0,
)
BaiduDetection = TextMarkDetection
def _alpha_template() -> NDArray[Any] | None:
"""The bundled Baidu alpha template (float [0,1]), or None."""
return _text_mark_engine.load_alpha_template(_CONFIG.asset_name)
def _glyph_silhouette() -> NDArray[Any] | None:
"""Binary "百度" silhouette (255 = glyph) from the alpha map, or None."""
return _text_mark_engine.glyph_silhouette(_CONFIG.asset_name)
def _template_match_score(box_mask: NDArray[Any], scale_base: int) -> float:
"""TM_CCOEFF_NORMED of the Baidu glyph silhouette against ``box_mask``."""
return _text_mark_engine.template_match_score(box_mask, scale_base, _CONFIG)
class BaiduEngine(TextMarkEngine):
"""Detect/localize the visible Baidu "百度 AI生成" mark (bottom-right; localize -> fill)."""
def __init__(self) -> None:
super().__init__(_CONFIG)
def footprint_mask(
self, image: NDArray[Any] | None, *, force: bool = False, dilate: int | None = None
) -> NDArray[Any] | None:
"""Full-frame mask of the WHOLE mark (text run + the pill tag to its right).
The base class's blob-bbox footprint UNDERCOVERS this mark: the white tag's
flat interior gives no top-hat response (a top-hat answers edges, not flats),
so the blob ends at the text run and the fill leaves the tag's right half as
a ghost (measured 2026-07-22 on the 768x1024 cohort frame: blob bbox x
632..746 vs the tag ending ~758). The layout is measured and fixed -- the
text run is at the left of the locate box, the tag runs to the corner -- so
the footprint is the detector's match box extended RIGHT to the corner.
"""
if image is None or image.size == 0:
return None
from remove_ai_watermarks import image_io, region_eraser
image = image_io.to_bgr(image)
h, w = image.shape[:2]
if h < 32 or w < 64:
return None
loc = self.locate(image)
bx, by, bw, bh = loc.bbox
if force:
rx1, ry1, rx2, ry2 = bx, by, min(w, bx + bw), min(h, by + bh)
else:
if not self.detect(image).detected:
return None
_, box = self._tophat_best(image, loc)
if box is None:
return None
gx0, gy0, _gx1, gy1 = box
pad = max(4, int(0.15 * bh))
rx1 = max(0, bx + gx0 - pad)
ry1 = max(0, by + gy0 - pad)
rx2 = min(w, bx + bw) # the tag runs to the corner end of the box
ry2 = min(h, by + gy1 + 1 + pad)
if rx1 >= rx2 or ry1 >= ry2:
return None
d = dilate if dilate is not None else max(3, int(0.02 * bw))
return region_eraser.boxes_to_mask((h, w), [(rx1, ry1, rx2 - rx1, ry2 - ry1)], dilate=d)
def load_image_bgr(path: str | Path) -> NDArray[Any]:
"""Read an image as BGR ndarray (helper for scripts/tests)."""
from remove_ai_watermarks import image_io
img = image_io.imread(path)
if img is None:
raise FileNotFoundError(f"Failed to read image: {path}")
return img
+339 -221
View File
@@ -12,6 +12,7 @@ import contextlib
import json
import logging
import time
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal, NoReturn
@@ -306,13 +307,13 @@ _visible_backend_option = click.option(
_visible_sensitivity_option = click.option(
"--sensitivity",
"sensitivity",
type=click.Choice(["auto", "strict", "assume-ai"]),
type=click.Choice(["auto", "strict"]),
default="auto",
help="How hard to trust a borderline mark. auto: relax a mark only when metadata "
"or a same-product sibling mark corroborates it (safe; clean images untouched). "
"strict: high-precision visual gate only, never relaxed. assume-ai: treat the "
"image as AI and relax every mark (best recall on metadata-stripped screenshots, "
"at the cost of a small fill on some clean corners).",
"strict: high-precision visual gate only, never relaxed. To act on a mark YOU can "
"see but the detector missed, use 'erase --region' or '--mark <name> --no-detect' "
"rather than a blanket relaxation.",
)
@@ -394,13 +395,12 @@ def _remove_visible_auto(
def _parse_sensitivity(value: str) -> watermark_registry.Sensitivity:
"""Map the CLI ``--sensitivity`` choice (kebab ``assume-ai``) to the registry
literal (``assume_ai``); ``auto``/``strict`` pass through unchanged."""
if value == "assume-ai":
return "assume_ai"
if value == "strict":
return "strict"
return "auto"
"""Map the CLI ``--sensitivity`` choice to the registry literal.
A pass-through since ``assume-ai`` was removed (2026-07-19); kept as the single
conversion point so a future kebab-cased choice has an obvious home.
"""
return "strict" if value == "strict" else "auto"
# Exit code for the standalone ``visible`` command when no visible mark was
@@ -410,21 +410,52 @@ def _parse_sensitivity(value: str) -> watermark_registry.Sensitivity:
EXIT_NO_VISIBLE_MARK = 2
def _no_visible_mark_exit(source: Path, *, sensitivity: str = "auto") -> NoReturn:
def _write_output_or_exit(output: Path, bgr: NDArray[Any], alpha: NDArray[Any] | None) -> None:
"""Write the final image, or fail with a readable error instead of a traceback.
`image_io.imwrite` is contractually NON-RAISING: it returns False when the codec
rejects the image or the path cannot be written. Every caller here follows its write
with `output.stat()` to report the size, so a silently-failed write (read-only
directory, full disk) died with a bare `FileNotFoundError` traceback pointing at the
stat, not at the write. Found by the Tier E adversarial sweep 2026-07-20.
Regression: `tests/test_cli_robustness.py::TestFailedWriteIsReported`.
"""
output.parent.mkdir(parents=True, exist_ok=True)
if not image_io.write_bgr_with_alpha(output, bgr, alpha):
console.print(f" Error: failed to write output (is the destination writable?): {output}")
raise SystemExit(1)
def _no_visible_mark_exit(source: Path) -> NoReturn:
"""Explain why no visible watermark was removed, then exit non-zero.
The visible registry handles only known visual marks (the Gemini sparkle and
the Doubao/Jimeng/Samsung text strips). Most real uploads carry no such mark
the Doubao/Jimeng/Qwen/Samsung text strips). Most real uploads carry no such mark
-- frequently an invisible/metadata watermark instead (e.g. an OpenAI or
Gemini image whose only signal is C2PA + SynthID). Returning the input
unchanged with exit 0 reads as success to a caller and re-serves the
watermarked image -- the recurring "it didn't work" report. Instead, run a
cheap metadata-only :func:`identify`, tell the user what the image actually
carries and which command removes it, and exit
:data:`EXIT_NO_VISIBLE_MARK`. When the conservative detector found nothing and
the user has NOT already asked for the aggressive pass, point them at
``--sensitivity assume-ai`` (a faint or moved visible mark may be sitting just
below the default gate).
:data:`EXIT_NO_VISIBLE_MARK`.
When the user can SEE a mark the detector missed, the honest next step is one that
executes their instruction rather than guessing harder. This used to recommend
``--sensitivity assume-ai``, which did the opposite -- it relaxed every mark's gate
on a blanket assumption -- and that mode is gone (2026-07-19).
The advice is per-mark, because the forced paths are not equally reliable
(measured 2026-07-19):
* ``erase --region`` is always sound: the user supplies the coordinates, so there
is nothing to guess. This is the primary recommendation.
* ``--mark <text-mark> --no-detect`` is reasonable for the TEXT marks: the forced
mask is built from the actual glyph blob, non-empty on 13/13 real marks the
detector missed.
* ``--mark gemini --no-detect`` is NOT recommended and is deliberately not
suggested here: with no detection it falls back to a fixed default sparkle slot,
which covered the real sparkle on only **31% of 97** genuine sparkles the strict
gate missed (median offset 63px up-and-left). The other 69% fill a clean corner
AND report a removal that did not happen -- the worst outcome the tool has.
"""
from remove_ai_watermarks.identify import identify
@@ -446,12 +477,13 @@ def _no_visible_mark_exit(source: Path, *, sensitivity: str = "auto") -> NoRetur
" If instead there is a logo or object to remove, target it with the region eraser:\n"
f" remove-ai-watermarks erase {source.name} --region x,y,w,h"
)
if sensitivity != "assume_ai":
console.print(
" If you know this image is AI-generated, retry the visible pass with\n"
f" remove-ai-watermarks visible {source.name} --sensitivity assume-ai\n"
" which relaxes detection to catch a faint or moved mark the default gate skips."
)
console.print(
" If you can SEE a mark here that was not detected, point at it directly --\n"
" that removes what you actually see instead of guessing:\n"
f" remove-ai-watermarks erase {source.name} --region x,y,w,h\n"
" For a known CJK text mark you can also force it by name:\n"
f" remove-ai-watermarks visible {source.name} --mark doubao --no-detect"
)
raise SystemExit(EXIT_NO_VISIBLE_MARK)
@@ -525,8 +557,114 @@ def main(ctx: click.Context, verbose: bool) -> None:
# ── Visible (Gemini) watermark removal ──
def _run_visible_auto(
source: Path,
output: Path,
*,
backend: watermark_registry.Backend,
sensitivity: watermark_registry.Sensitivity,
strip_metadata: bool,
) -> None:
"""Run the registry-wide visible pass and render its CLI result."""
from remove_ai_watermarks import api
t0 = time.monotonic()
try:
with console.status("Detecting & removing visible marks..."):
result, removed = api.remove_visible(
str(source),
str(output),
sensitivity=sensitivity,
backend=backend,
strip_metadata=strip_metadata,
write_noop=False,
)
except RuntimeError as e: # selected migan/lama backend whose extra is absent
console.print(f" Error: {e}")
raise SystemExit(1) from e
except (ValueError, OSError) as e:
# Covers BOTH an unreadable input and an unwritable output, so the message must
# not assert which: it used to say "cannot read image <input>" while quoting the
# OUTPUT path, blaming the wrong file (Tier E, 2026-07-20).
console.print(f" Error: {e}")
raise SystemExit(1) from e
elapsed = time.monotonic() - t0
h, w = result.shape[:2]
console.print(f" Input: {source.name} ({w}x{h})")
if not removed:
# write_noop=False means nothing was written, so a pre-existing output is intact.
console.print(" No known visible mark detected (gemini / doubao / jimeng / jimeng-pill / samsung).")
_no_visible_mark_exit(source)
console.print(f" Removed: {', '.join(removed)}")
size_kb = output.stat().st_size / 1024
console.print(f" Saved: {output} ({size_kb:.0f} KB, {elapsed:.2f}s)")
def _run_visible_explicit(
ctx: click.Context,
source: Path,
output: Path,
*,
detect: bool,
mark: str,
backend: watermark_registry.Backend,
sensitivity: watermark_registry.Sensitivity,
resolved_backend: str,
strip_metadata: bool,
) -> None:
"""Run one explicitly selected visible-mark detector/remover."""
image, alpha = image_io.read_bgr_and_alpha(source)
if image is None:
console.print(f"Error: Failed to read image: {source}")
raise SystemExit(1)
h, w = image.shape[:2]
console.print(f" Input: {source.name} ({w}x{h})")
provenance = _visible_provenance(source)
target = "gemini" if mark == "auto" else mark # --no-detect auto: gemini fallback
chosen = watermark_registry.get_mark(target)
# A single explicit mark has no sibling corroboration. Keep its trust resolution
# aligned with the registry arbiter.
trust = watermark_registry.resolve_trust(
chosen.key,
sensitivity=sensitivity,
provenance=provenance,
strict_keys=set(),
)
relax = trust != "strict"
detection = chosen.detect(image, provenance=relax)
if detect and not detection.detected:
console.print(f" {chosen.label} not detected (conf {detection.confidence:.2f}). Use --no-detect to force.")
_no_visible_mark_exit(source)
if detection.detected:
console.print(f" {chosen.label} detected ({chosen.location}, conf {detection.confidence:.2f})")
t0 = time.monotonic()
try:
with console.status(f"Removing {chosen.label}... ({resolved_backend})"):
result, _ = chosen.remove(image, backend=backend, provenance=relax, force=not detect)
except RuntimeError as e: # selected migan/lama backend whose extra is absent
console.print(f" Error: {e}")
raise SystemExit(1) from e
elapsed = time.monotonic() - t0
_write_output_or_exit(output, result, alpha)
if strip_metadata:
try:
from remove_ai_watermarks.metadata import remove_ai_metadata
remove_ai_metadata(output, output)
except Exception as e:
if ctx.obj.get("verbose"):
console.print(f" Warning: Failed to strip metadata: {e}")
size_kb = output.stat().st_size / 1024
console.print(f" Saved: {output} ({size_kb:.0f} KB, {elapsed:.2f}s)")
@main.command("visible")
@click.argument("source", type=click.Path(exists=True, path_type=Path))
@click.argument("source", type=click.Path(exists=True, dir_okay=False, path_type=Path))
@click.option(
"-o", "--output", type=click.Path(path_type=Path), default=None, help="Output path (default: <source>_clean.<ext>)."
)
@@ -554,24 +692,22 @@ def cmd_visible(
) -> None:
"""Remove a known visible AI watermark from an image.
Finds a known mark in its usual place (Gemini sparkle / Doubao-Jimeng-Samsung
Finds a known mark in its usual place (Gemini sparkle / Doubao-Jimeng-Qwen-Samsung
text) via the watermark registry and removes it by LOCALIZING the mark to a mask
and filling that mask with the chosen ``--backend`` (auto: best available, LaMa >
MI-GAN > cv2). ``--mark auto`` removes every detected mark in one
pass. For arbitrary logos/objects, use ``erase``.
"""
from remove_ai_watermarks import watermark_registry as registry
_banner()
source = _validate_image(source)
if output is None:
output = source.with_stem(source.stem + "_clean")
bk: registry.Backend = backend # type: ignore[assignment]
bk: watermark_registry.Backend = backend # type: ignore[assignment]
sens = _parse_sensitivity(sensitivity)
resolved_backend = registry.resolve_backend(bk)
if resolved_backend == "cv2" and not registry.inpaint_model_available():
resolved_backend = watermark_registry.resolve_backend(bk)
if resolved_backend == "cv2" and not watermark_registry.inpaint_model_available():
console.print(" Note: using cv2 fill (install the 'migan' extra for a lightweight ONNX model).")
# ``auto`` removes EVERY detected in_auto mark in one pass (a Jimeng-basic image
@@ -579,82 +715,20 @@ def cmd_visible(
# read -> provenance -> localize/fill -> write -> metadata-strip to the library
# entry point, so the CLI and the library go through ONE path (no drift).
if mark == "auto" and detect:
from remove_ai_watermarks import api
t0 = time.monotonic()
try:
with console.status("Detecting & removing visible marks..."):
result, removed = api.remove_visible(
str(source),
str(output),
sensitivity=sens,
backend=bk,
strip_metadata=strip_metadata,
write_noop=False,
)
except RuntimeError as e: # e.g. a selected migan/lama backend whose extra is absent
console.print(f" Error: {e}")
raise SystemExit(1) from e
except (ValueError, OSError) as e: # unreadable / truncated / non-image input
console.print(f" Error: cannot read image {source.name}: {e}")
raise SystemExit(1) from e
elapsed = time.monotonic() - t0
h, w = result.shape[:2]
console.print(f" Input: {source.name} ({w}x{h})")
if not removed:
# write_noop=False means nothing was written, so a pre-existing file at the
# output path is left intact (the no-mark contract writes nothing).
console.print(" No known visible mark detected (gemini / doubao / jimeng / jimeng-pill / samsung).")
_no_visible_mark_exit(source, sensitivity=sens)
console.print(f" Removed: {', '.join(removed)}")
size_kb = output.stat().st_size / 1024
console.print(f" Saved: {output} ({size_kb:.0f} KB, {elapsed:.2f}s)")
_run_visible_auto(source, output, backend=bk, sensitivity=sens, strip_metadata=strip_metadata)
return
# Explicit single mark (or --no-detect): needs the decoded array + the per-mark gate,
# so it keeps its own read/remove/write (still through the shared io + registry).
image, alpha = image_io.read_bgr_and_alpha(source)
if image is None:
console.print(f"Error: Failed to read image: {source}")
raise SystemExit(1)
h, w = image.shape[:2]
console.print(f" Input: {source.name} ({w}x{h})")
provenance = _visible_provenance(source)
target = "gemini" if mark == "auto" else mark # --no-detect auto: gemini fallback
chosen = registry.get_mark(target)
# A single explicit mark has no cross-mark pass (no sibling corroboration), so use the
# canonical arbiter policy with an empty strict-sibling set instead of re-deriving it
# inline (keeps this in lockstep with `decide`).
prov = registry.resolve_relax(chosen.key, sensitivity=sens, provenance=provenance, strict_keys=set())
det = chosen.detect(image, provenance=prov)
if detect and not det.detected:
console.print(f" {chosen.label} not detected (conf {det.confidence:.2f}). Use --no-detect to force.")
_no_visible_mark_exit(source, sensitivity=sens)
if det.detected:
console.print(f" {chosen.label} detected ({chosen.location}, conf {det.confidence:.2f})")
t0 = time.monotonic()
try:
with console.status(f"Removing {chosen.label}... ({resolved_backend})"):
result, _ = chosen.remove(image, backend=bk, provenance=prov, force=not detect)
except RuntimeError as e: # e.g. a selected migan/lama backend whose extra is absent
console.print(f" Error: {e}")
raise SystemExit(1) from e
elapsed = time.monotonic() - t0
# Save (rejoins the original alpha plane unchanged) + strip metadata.
output.parent.mkdir(parents=True, exist_ok=True)
image_io.write_bgr_with_alpha(output, result, alpha)
if strip_metadata:
try:
from remove_ai_watermarks.metadata import remove_ai_metadata
remove_ai_metadata(output, output)
except Exception as e:
if ctx.obj.get("verbose"):
console.print(f" Warning: Failed to strip metadata: {e}")
size_kb = output.stat().st_size / 1024
console.print(f" Saved: {output} ({size_kb:.0f} KB, {elapsed:.2f}s)")
_run_visible_explicit(
ctx,
source,
output,
detect=detect,
mark=mark,
backend=bk,
sensitivity=sens,
resolved_backend=resolved_backend,
strip_metadata=strip_metadata,
)
# ── Universal region eraser ──
@@ -673,7 +747,7 @@ def _parse_region(spec: str) -> tuple[int, int, int, int]:
@main.command("erase")
@click.argument("source", type=click.Path(exists=True, path_type=Path))
@click.argument("source", type=click.Path(exists=True, dir_okay=False, path_type=Path))
@click.option("--region", "regions", multiple=True, required=True, help="x,y,w,h box to erase (repeatable).")
@click.option(
"-o", "--output", type=click.Path(path_type=Path), default=None, help="Output path (default: <source>_clean.<ext>)."
@@ -731,8 +805,7 @@ def cmd_erase(
raise SystemExit(1) from e
elapsed = time.monotonic() - t0
output.parent.mkdir(parents=True, exist_ok=True)
image_io.write_bgr_with_alpha(output, result, alpha)
_write_output_or_exit(output, result, alpha)
if strip_metadata:
try:
@@ -749,7 +822,7 @@ def cmd_erase(
# ── Invisible watermark removal ──
@main.command("invisible")
@click.argument("source", type=click.Path(exists=True, path_type=Path))
@click.argument("source", type=click.Path(exists=True, dir_okay=False, path_type=Path))
@click.option(
"-o", "--output", type=click.Path(path_type=Path), default=None, help="Output path (default: <source>_clean.<ext>)."
)
@@ -885,7 +958,7 @@ def cmd_invisible(
# ── Metadata operations ──
@main.command("metadata")
@click.argument("source", type=click.Path(exists=True, path_type=Path))
@click.argument("source", type=click.Path(exists=True, dir_okay=False, path_type=Path))
@click.option("--check", is_flag=True, help="Check for AI metadata (don't modify).")
@click.option("--remove", is_flag=True, help="Remove AI metadata.")
@click.option(
@@ -909,7 +982,7 @@ def cmd_metadata(
from WebM/MP3/WAV/FLAC/OGG. The coded image, audio, and video data are left
untouched.
"""
from remove_ai_watermarks.metadata import get_ai_metadata, has_ai_metadata, remove_ai_metadata
from remove_ai_watermarks.metadata import get_ai_metadata, has_ai_metadata, strip_and_verify
# No _validate_image() here: unlike the image-only commands, metadata also
# accepts video/audio containers, so the image-format warning would misfire.
@@ -937,16 +1010,22 @@ def cmd_metadata(
# Remove
try:
out = remove_ai_metadata(source, output, keep_standard=keep_standard)
out, leftover = strip_and_verify(source, output, keep_standard=keep_standard)
except (OSError, ValueError) as e: # unreadable / truncated / non-image (PIL raises OSError subclasses)
console.print(f" Error: cannot process {source.name}: {e}")
raise SystemExit(1) from e
if leftover:
console.print(f" FAILED: {len(leftover)} AI metadata marker(s) survived in {out}")
console.print(f" still present: {', '.join(sorted(leftover))}")
console.print(" the file could not be decoded, so it was copied through unchanged")
raise SystemExit(1)
console.print(f" AI metadata stripped -> {out}")
# ── Provenance identification ──
@main.command("identify")
@click.argument("source", type=click.Path(exists=True, path_type=Path))
@click.argument("source", type=click.Path(exists=True, dir_okay=False, path_type=Path))
@click.option(
"--no-visible",
is_flag=True,
@@ -1015,7 +1094,7 @@ def cmd_identify(ctx: click.Context, source: Path, no_visible: bool, as_json: bo
# ── Combined "all" mode ──
@main.command("all")
@click.argument("source", type=click.Path(exists=True, path_type=Path))
@click.argument("source", type=click.Path(exists=True, dir_okay=False, path_type=Path))
@click.option(
"-o", "--output", type=click.Path(path_type=Path), default=None, help="Output path (default: <source>_clean.<ext>)."
)
@@ -1216,12 +1295,11 @@ def cmd_all(
# The invisible step (and downstream cv2.IMREAD_COLOR paths) drops alpha,
# so re-attach the original alpha plane unchanged when writing the final
# output for transparent formats.
output.parent.mkdir(parents=True, exist_ok=True)
final_bgr, _ = image_io.read_bgr_and_alpha(tmp_path)
if final_bgr is None:
console.print(f"Error: Failed to read intermediate file: {tmp_path}")
raise SystemExit(1)
image_io.write_bgr_with_alpha(output, final_bgr, alpha)
_write_output_or_exit(output, final_bgr, alpha)
finally:
# Clean up temp file if it still exists
@@ -1257,8 +1335,104 @@ def _passthrough_copy(img_path: Path, out_path: Path) -> None:
"""Copy the input's pixels through to ``out_path`` unchanged (the invisible-mode skip
paths), so the output dir stays complete without touching the pixels."""
src_bgr, src_alpha = image_io.read_bgr_and_alpha(img_path)
if src_bgr is not None:
image_io.write_bgr_with_alpha(out_path, src_bgr, src_alpha)
if src_bgr is not None and not image_io.write_bgr_with_alpha(out_path, src_bgr, src_alpha):
# The point of this copy is to keep the output dir COMPLETE. A silently-dropped
# copy defeats that and leaves a hole the caller cannot see (Tier E, 2026-07-20).
raise OSError(f"failed to copy input through to output: {out_path}")
@dataclass(frozen=True)
class _BatchOptions:
"""Validated processing options shared by every image in one batch.
Click necessarily exposes these as individual command parameters, but the
processing core should receive one coherent value instead of a 21-argument
call. Keeping the object immutable also makes it safe to reuse while the
batch caches model instances in ``ctx.obj``.
"""
strength: float | None
steps: int
pipeline: str
device: str
seed: int | None
hf_token: str | None
humanize: float
backend: str = "auto"
sensitivity: str = "auto"
unsharp: float = 0.0
max_resolution: int = 0
min_resolution: int = 1024
controlnet_scale: float = 1.0
upscaler: str = "lanczos"
model: str | None = None
guidance_scale: float | None = None
adaptive_polish: bool = False
tile: bool = False
tile_size: int = 1024
tile_overlap: int = 128
force: bool = False
def _run_batch_invisible(
ctx: click.Context,
img_path: Path,
out_path: Path,
mode: str,
options: _BatchOptions,
) -> bool:
"""Run or safely skip the invisible pass for one batch image.
Returns ``True`` only when a detectable target could not be processed because
the GPU dependencies are missing. The availability probe is intentionally
evaluated once so branching cannot observe inconsistent optional-dependency
state.
"""
from remove_ai_watermarks.invisible_engine import is_available as invisible_available
skip_no_signal = _should_skip_invisible_scrub(options.force, img_path)
available = invisible_available()
if available and not skip_no_signal:
from remove_ai_watermarks.invisible_engine import InvisibleEngine
# Cache the engine in ctx.obj so the batch builds it once (pipeline is a
# single CLI value, constant across the run).
engines = ctx.obj.setdefault("_inv_engines", {})
if options.pipeline not in engines:
engines[options.pipeline] = InvisibleEngine(
model_id=options.model,
device=None if options.device == "auto" else options.device,
pipeline=options.pipeline,
hf_token=options.hf_token,
controlnet_conditioning_scale=options.controlnet_scale,
)
engines[options.pipeline].remove_watermark(
img_path if mode == "invisible" else out_path,
out_path,
strength=options.strength,
num_inference_steps=options.steps,
guidance_scale=options.guidance_scale,
seed=options.seed,
humanize=options.humanize,
unsharp=options.unsharp,
adaptive_polish=options.adaptive_polish,
max_resolution=options.max_resolution,
min_resolution=options.min_resolution,
upscaler=options.upscaler,
tile=options.tile,
tile_size=options.tile_size,
tile_overlap=options.tile_overlap,
# Detect the vendor from the pristine original (`img_path`), not the
# visible-processed `out_path` whose C2PA is already gone.
vendor=vendor_for_strength(img_path),
)
return False
# Invisible-only mode has no preceding visible pass to create ``out_path``.
# Preserve a complete output directory while deliberately leaving pixels intact.
if mode == "invisible" and not out_path.exists():
_passthrough_copy(img_path, out_path)
return not available and not skip_no_signal
def _process_batch_image(
@@ -1266,27 +1440,7 @@ def _process_batch_image(
img_path: Path,
out_path: Path,
mode: str,
strength: float | None,
steps: int,
pipeline: str,
device: str,
seed: int | None,
hf_token: str | None,
humanize: float,
backend: str = "auto",
sensitivity: str = "auto",
unsharp: float = 0.0,
max_resolution: int = 0,
min_resolution: int = 1024,
controlnet_scale: float = 1.0,
upscaler: str = "lanczos",
model: str | None = None,
guidance_scale: float | None = None,
adaptive_polish: bool = False,
tile: bool = False,
tile_size: int = 1024,
tile_overlap: int = 128,
force: bool = False,
options: _BatchOptions,
) -> bool:
"""Process a single image for batch mode.
@@ -1312,83 +1466,44 @@ def _process_batch_image(
if image is None:
raise ValueError("Failed to read image")
result, _ = _remove_visible_auto(image, source_path=img_path, backend=backend, sensitivity=sensitivity)
result, _ = _remove_visible_auto(
image,
source_path=img_path,
backend=options.backend,
sensitivity=options.sensitivity,
)
image_io.write_bgr_with_alpha(out_path, result, alpha)
# RAISE, never SystemExit: the batch loop catches per-image exceptions, counts
# them and exits non-zero. Discarding this flag made a read-only output directory
# produce ZERO files and still exit 0 -- silent data loss that also contradicted
# the documented batch contract (Tier E, 2026-07-20).
if not image_io.write_bgr_with_alpha(out_path, result, alpha):
raise OSError(f"failed to write output (is the destination writable?): {out_path}")
saved_alpha = alpha
if mode in ("invisible", "all"):
from remove_ai_watermarks.invisible_engine import (
is_available as invisible_available,
)
# Skip the destructive regeneration when no invisible watermark is locally
# detectable (would only degrade a clean image). Read the pristine `img_path`;
# `out_path` may already be the visible-processed result. --force overrides.
skip_no_signal = _should_skip_invisible_scrub(force, img_path)
if invisible_available() and not skip_no_signal:
from remove_ai_watermarks.invisible_engine import InvisibleEngine
# Cache the engine in ctx.obj so the batch builds it once (pipeline is a
# single CLI value, constant across the run).
engines = ctx.obj.setdefault("_inv_engines", {})
if pipeline not in engines:
engines[pipeline] = InvisibleEngine(
model_id=model,
device=None if device == "auto" else device,
pipeline=pipeline,
hf_token=hf_token,
controlnet_conditioning_scale=controlnet_scale,
)
engine_inv = engines[pipeline]
engine_inv.remove_watermark(
img_path if mode == "invisible" else out_path,
out_path,
strength=strength,
num_inference_steps=steps,
guidance_scale=guidance_scale,
seed=seed,
humanize=humanize,
unsharp=unsharp,
adaptive_polish=adaptive_polish,
max_resolution=max_resolution,
min_resolution=min_resolution,
upscaler=upscaler,
tile=tile,
tile_size=tile_size,
tile_overlap=tile_overlap,
# Detect the vendor from the pristine original (`img_path`), not the
# visible-processed `out_path` whose C2PA is already gone.
vendor=vendor_for_strength(img_path),
)
elif not invisible_available() and not skip_no_signal:
# An invisible signal IS present but the GPU deps are missing, so the
# SynthID scrub cannot run. Mirror the single `all` command's loud skip:
# flag it for a batch-level warning + non-zero exit (a silently retained
# SynthID watermark is the #1 "it didn't work" report). For invisible mode
# nothing wrote out_path yet -> copy the input through so the output dir is
# complete with the pixels deliberately left intact (without this, a
# signal-bearing image in a GPU-less --mode invisible run got NO output).
synthid_skipped = True
if mode == "invisible" and not out_path.exists():
_passthrough_copy(img_path, out_path)
elif skip_no_signal and mode == "invisible" and not out_path.exists():
# No invisible target and the visible/all pass did not write out_path
# (invisible mode): copy the input through so the output dir is complete
# with the pixels deliberately left intact.
_passthrough_copy(img_path, out_path)
synthid_skipped = _run_batch_invisible(ctx, img_path, out_path, mode, options)
if mode in ("metadata", "all"):
from remove_ai_watermarks.metadata import remove_ai_metadata
from remove_ai_watermarks.metadata import strip_and_verify
remove_ai_metadata(img_path if mode == "metadata" else out_path, out_path)
# Same verification the single-image command does: the fail-safe copy-through
# would otherwise leave an AI-reading output and still exit 0, contradicting the
# batch contract that a failed image must make the run exit non-zero.
_, leftover = strip_and_verify(img_path if mode == "metadata" else out_path, out_path)
if leftover:
msg = f"AI metadata survived the strip ({', '.join(sorted(leftover))}); file could not be decoded"
raise RuntimeError(msg)
# In "all" mode, the invisible step (color-only OpenCV paths) drops alpha,
# so re-attach the cached alpha when the input had transparency.
if mode == "all" and saved_alpha is not None:
final_bgr, _ = image_io.read_bgr_and_alpha(out_path)
if final_bgr is not None:
image_io.write_bgr_with_alpha(out_path, final_bgr, saved_alpha)
if final_bgr is not None and not image_io.write_bgr_with_alpha(out_path, final_bgr, saved_alpha):
raise OSError(f"failed to re-attach alpha to output: {out_path}")
return synthid_skipped
@@ -1485,6 +1600,29 @@ def cmd_batch(
if mode in ("invisible", "all"):
_warn_if_esrgan_unavailable(upscaler)
adaptive_polish = _resolve_auto_polish(auto, adaptive_polish)
options = _BatchOptions(
strength=strength,
steps=steps,
pipeline=pipeline,
device=device,
seed=seed,
hf_token=hf_token,
humanize=humanize,
backend=backend,
sensitivity=sensitivity,
unsharp=unsharp,
max_resolution=max_resolution,
min_resolution=min_resolution,
controlnet_scale=controlnet_scale,
upscaler=upscaler,
model=model,
guidance_scale=guidance_scale,
adaptive_polish=adaptive_polish,
tile=tile,
tile_size=tile_size,
tile_overlap=tile_overlap,
force=force,
)
processed = 0
errors = 0
@@ -1510,27 +1648,7 @@ def cmd_batch(
img_path=img_path,
out_path=out_path,
mode=mode,
strength=strength,
steps=steps,
pipeline=pipeline,
device=device,
seed=seed,
hf_token=hf_token,
humanize=humanize,
backend=backend,
sensitivity=sensitivity,
unsharp=unsharp,
max_resolution=max_resolution,
min_resolution=min_resolution,
controlnet_scale=controlnet_scale,
upscaler=upscaler,
model=model,
guidance_scale=guidance_scale,
adaptive_polish=adaptive_polish,
tile=tile,
tile_size=tile_size,
tile_overlap=tile_overlap,
force=force,
options=options,
):
synthid_skipped_count += 1
processed += 1
+23 -3
View File
@@ -47,7 +47,21 @@ TOPHAT_DELTA = 12 # glyph must exceed the local background by this many levels
# Shape-consistent detection: match the bundled alpha glyph silhouette against the
# corner candidate via TM_CCOEFF_NORMED (keys on glyph SHAPE, not coverage; #23).
DETECT_MIN_COVERAGE = 0.04
DETECT_NCC_THRESHOLD = 0.4
# NOTE: this gate is FRONT-END SPECIFIC. The continuous top-hat front-end scores higher
# overall than the binary one (mean 0.809 vs 0.723 on the same 90 positives), so the
# binary-era 0.40 left the provenance-relaxed gate (x0.7) far too low and admitted false
# fires. Calibrated on the 240-image unbiased recall sample, full auto path:
#
# gate relaxed recall precision true false
# 0.40 0.280 96% 91% 86 8
# 0.45 0.315 94% 93% 85 6
# 0.50 0.350 92% 99% 83 1 <- chosen
# 0.60 0.420 87% 99% 78 1
#
# 0.50 beats the binary front-end on recall (92% vs 89%) at identical precision (99%),
# which is the only reason the front-end switch is worth it. Do not port this number to
# a binary-front-end mark; re-calibrate per front-end.
DETECT_NCC_THRESHOLD = 0.50
# Detection-silhouette geometry, emitted by scripts/visible_alpha_solve.py at the
# captured width. Sizes the glyph silhouette for the TM_CCOEFF_NORMED detection match
@@ -71,6 +85,12 @@ _CONFIG = TextMarkConfig(
morph_open_size=5,
detect_min_coverage=DETECT_MIN_COVERAGE,
detect_ncc_threshold=DETECT_NCC_THRESHOLD,
detect_frontend="tophat",
scale_basis="short", # measured: recovers 56% of landscape misses (see scale_base)
# No rival margin: measured 2026-07-18, the symmetric gate cost Doubao 7 genuine
# detections to prevent 5 false ones (1.4:1 against). Doubao's absolute detector
# is already 86% precise, so it has nothing to buy; Jimeng's is 38% and gains 25pp
# for free. The confusion is asymmetric, so the remedy is too.
alpha_width_frac=_ALPHA_WIDTH_FRAC,
alpha_height_frac=_ALPHA_HEIGHT_FRAC,
min_gw=8,
@@ -90,9 +110,9 @@ def _glyph_silhouette() -> NDArray[Any] | None:
return _text_mark_engine.glyph_silhouette(_CONFIG.asset_name)
def _template_match_score(box_mask: NDArray[Any], image_width: int) -> float:
def _template_match_score(box_mask: NDArray[Any], scale_base: int) -> float:
"""TM_CCOEFF_NORMED of the Doubao glyph silhouette against ``box_mask``."""
return _text_mark_engine.template_match_score(box_mask, image_width, _CONFIG)
return _text_mark_engine.template_match_score(box_mask, scale_base, _CONFIG)
class DoubaoEngine(TextMarkEngine):
+55 -31
View File
@@ -312,6 +312,9 @@ _AI_VENDOR_TOKENS: tuple[tuple[str, str], ...] = (
("elevenlabs", "ElevenLabs"),
("eleven labs", "ElevenLabs"),
("black forest", "Black Forest Labs"),
("fal-ai", "fal.ai"),
("bria", "Bria"),
("apple photos clean up", "Apple"),
)
@@ -446,12 +449,17 @@ def _visible_sparkle(image_path: Path, *, image: NDArray[Any] | None = None) ->
_VISIBLE_MARK_PLATFORM = {
"doubao": "ByteDance Doubao (visible 豆包AI生成 mark detected)",
"jimeng": "ByteDance Jimeng / Dreamina (visible 即梦AI mark detected)",
"qwen": "Alibaba Tongyi Qianwen (visible 千问AI生成 mark detected)",
"kling": "Kuaishou Kling (visible 可灵AI 3.0 mark detected)",
"samsung": "Samsung Galaxy AI (visible 'Contenuti generati dall'AI' mark detected)",
"runninghub": "RunningHub (visible RunningHub AI生成 mark detected)",
"baidu": "Baidu (visible 百度 AI生成 mark detected)",
"liblib": "LibLibAI (visible LibLibAI mark detected)",
}
def _visible_text_marks(image_path: Path, *, image: NDArray[Any] | None = None) -> list[MarkDetection]:
"""Detected visible Doubao/Jimeng marks (registry ``MarkDetection`` list).
"""Detected visible text marks (registry ``MarkDetection`` list).
The Gemini sparkle keeps its own ``_visible_sparkle`` path (file-level
confidence); these two text marks reuse the registry detectors, which apply
@@ -505,6 +513,42 @@ def _trustmark(image_path: Path) -> str | None:
return detect_trustmark(image_path)
def _collect_visible_signals(
image_path: Path,
signals: list[Signal],
watermarks: list[str],
platform: str | None,
) -> str | None:
"""Decode once, append every trusted visible-mark signal, and return platform.
Keeping this stage separate from metadata aggregation makes the optional cv2
boundary explicit and guarantees that all visible detectors share one decoded
BGR array. A decode failure preserves the detectors' historical fallback/no-op
behavior.
"""
image: NDArray[Any] | None = None
try:
from remove_ai_watermarks.image_io import imread
image = imread(image_path)
except Exception as exc: # cv2 missing - detectors fall back / no-op
logger.debug("visible-mark decode unavailable: %s", exc)
sparkle_conf = _visible_sparkle(image_path, image=image)
if sparkle_conf is not None and sparkle_conf >= _SPARKLE_THRESHOLD:
signals.append(Signal("visible_sparkle", f"NCC confidence {sparkle_conf:.2f}", "medium"))
watermarks.append(f"Visible Gemini sparkle (confidence {sparkle_conf:.2f})")
if platform is None:
platform = "Google Gemini family (visible sparkle detected)"
for detection in _visible_text_marks(image_path, image=image):
signals.append(Signal(f"visible_{detection.key}", f"NCC confidence {detection.confidence:.2f}", "medium"))
watermarks.append(f"Visible {detection.label} (confidence {detection.confidence:.2f})")
if platform is None:
platform = _VISIBLE_MARK_PLATFORM[detection.key]
return platform
def identify(image_path: Path, *, check_visible: bool = True, check_invisible: bool = True) -> ProvenanceReport:
"""Identify an image's origin platform and watermark inventory.
@@ -632,7 +676,15 @@ def identify(image_path: Path, *, check_visible: bool = True, check_invisible: b
watermarks.append("IPTC digitalSourceType (Made with AI)")
caveats.append(_IPTC_ONLY_CAVEAT)
if platform is None:
platform = "Made-with-AI tag (e.g. Meta AI); platform not specified"
# Apple Photos Clean Up (Apple Intelligence object removal) marks
# the edit with photoshop:Credit / IPTC "Apple Photos Clean Up"
# next to compositeWithTrainedAlgorithmicMedia -- corpus-measured
# 2026-07-23 (35 files); it was detected but never attributed.
platform = (
"Apple Photos (Clean Up AI edit)"
if b"Apple Photos Clean Up" in head
else "Made-with-AI tag (e.g. Meta AI); platform not specified"
)
# ── IPTC 2025.1 AI-disclosure fields (Iptc4xmpExt:AISystemUsed etc.) ─
iptc_ai = any(m in head for m in IPTC_AI_FIELD_MARKERS)
@@ -755,36 +807,8 @@ def identify(image_path: Path, *, check_visible: bool = True, check_invisible: b
or xai_sig
)
# Decode the file ONCE for every visible-mark detector. The sparkle and the
# text-mark detectors both consume a BGR array; letting each re-read the file
# was two full cv2 decodes of the same bitmap, which spikes memory on a small
# worker. None (cv2 missing / unreadable container) makes each detector fall
# back to its own read, preserving the old behavior.
vis_image: NDArray[Any] | None = None
if check_visible:
try:
from remove_ai_watermarks.image_io import imread
vis_image = imread(image_path)
except Exception as exc: # cv2 missing - detectors fall back / no-op
logger.debug("visible-mark decode unavailable: %s", exc)
# ── Visible Gemini sparkle (fallback for stripped-metadata case) ─
sparkle_conf = _visible_sparkle(image_path, image=vis_image) if check_visible else None
if sparkle_conf is not None and sparkle_conf >= _SPARKLE_THRESHOLD:
signals.append(Signal("visible_sparkle", f"NCC confidence {sparkle_conf:.2f}", "medium"))
watermarks.append(f"Visible Gemini sparkle (confidence {sparkle_conf:.2f})")
if platform is None:
platform = "Google Gemini family (visible sparkle detected)"
# ── Visible Doubao / Jimeng text marks (registry; same stripped-metadata
# fallback role as the Gemini sparkle above) ─
if check_visible:
for det in _visible_text_marks(image_path, image=vis_image):
signals.append(Signal(f"visible_{det.key}", f"NCC confidence {det.confidence:.2f}", "medium"))
watermarks.append(f"Visible {det.label} (confidence {det.confidence:.2f})")
if platform is None:
platform = _VISIBLE_MARK_PLATFORM[det.key]
platform = _collect_visible_signals(image_path, signals, watermarks, platform)
visible_only = any(s.name.startswith("visible_") for s in signals) and not ai_from_metadata
hf_only = bool(hf_job) and not ai_from_metadata
+10 -5
View File
@@ -221,8 +221,8 @@ def read_bgr_and_alpha(path: str | Path) -> tuple[NDArray[Any] | None, NDArray[A
return image, None
def write_bgr_with_alpha(path: str | Path, bgr: NDArray[Any], alpha: NDArray[Any] | None) -> None:
"""Write BGR (with optional alpha) to ``path``.
def write_bgr_with_alpha(path: str | Path, bgr: NDArray[Any], alpha: NDArray[Any] | None) -> bool:
"""Write BGR (with optional alpha) to ``path``. Returns ``imwrite``'s success flag.
When ``alpha`` is provided and the output extension supports it, the original
alpha plane is rejoined unchanged. The watermark region is NOT made transparent:
@@ -230,10 +230,15 @@ def write_bgr_with_alpha(path: str | Path, bgr: NDArray[Any], alpha: NDArray[Any
transparent hole that renders as a white box on any non-transparent viewer
(issue #30). Preserving the input alpha keeps genuinely transparent backgrounds
intact without inventing new holes.
Returning the flag is load-bearing: :func:`imwrite` is contractually non-raising, so
this is the ONLY signal a caller gets that the file was not created. Discarding it let
a failed write (read-only directory, full disk) run on to ``output.stat()`` and die
with a bare ``FileNotFoundError`` traceback instead of a readable error.
Regression: ``tests/test_cli_robustness.py::TestFailedWriteIsReported``.
"""
import numpy as np
if alpha is None or Path(path).suffix.lower() not in ALPHA_FORMATS:
imwrite(path, bgr)
return
imwrite(path, np.dstack([bgr, alpha]))
return imwrite(path, bgr)
return imwrite(path, np.dstack([bgr, alpha]))
+16 -2
View File
@@ -42,9 +42,21 @@ TOPHAT_DELTA = 12
# Shape-consistent detection. Threshold 0.45 cleanly separates real Jimeng marks
# (>=0.81) from the Doubao strip (0.21), so the two ByteDance marks do not cross-fire.
#
# That separation holds at the STRICT threshold ONLY. Relaxed under provenance it
# collapses: at the old shared 0.7 factor (gate 0.315) the arm ran at 17% precision
# and 33 of its 68 false additions were Doubao marks (corpus-measured 2026-07-18 --
# full table at _DEFAULT_PROVENANCE_NCC_FACTOR). That was patched with a tighter 0.85
# factor at the time; the competitive rival margin replaced it -- see below.
DETECT_MIN_COVERAGE = 0.02
DETECT_NCC_THRESHOLD = 0.45
# Back to the 0.70 default. The 0.85 patch (2026-07-18) existed only to blunt the
# Doubao cross-fire by sacrificing recall; the competitive RIVAL MARGIN below
# discriminates directly and passes real wordmarks at 100%, so the recall the patch
# gave up is no longer the price of precision. See _rival_margin_ok.
PROVENANCE_NCC_FACTOR = 0.7
# Detection-silhouette geometry, emitted by scripts/visible_alpha_solve.py from the
# gray capture at the captured width (sizes the silhouette for the detection match;
# removal is the template-free glyph-bbox footprint mask).
@@ -67,6 +79,8 @@ _CONFIG = TextMarkConfig(
morph_open_size=5,
detect_min_coverage=DETECT_MIN_COVERAGE,
detect_ncc_threshold=DETECT_NCC_THRESHOLD,
provenance_ncc_factor=PROVENANCE_NCC_FACTOR,
rivals=("doubao_alpha.png",),
alpha_width_frac=_ALPHA_WIDTH_FRAC,
alpha_height_frac=_ALPHA_HEIGHT_FRAC,
min_gw=8,
@@ -85,9 +99,9 @@ def _glyph_silhouette() -> NDArray[Any] | None:
return _text_mark_engine.glyph_silhouette(_CONFIG.asset_name)
def _template_match_score(box_mask: NDArray[Any], image_width: int) -> float:
def _template_match_score(box_mask: NDArray[Any], scale_base: int) -> float:
"""TM_CCOEFF_NORMED of the Jimeng glyph silhouette against ``box_mask``."""
return _text_mark_engine.template_match_score(box_mask, image_width, _CONFIG)
return _text_mark_engine.template_match_score(box_mask, scale_base, _CONFIG)
class JimengEngine(TextMarkEngine):
+149
View File
@@ -0,0 +1,149 @@
"""Kling (可灵, Kuaishou) visible watermark detector/localizer.
Kling stamps its generations with a thin, light-gray "可灵AI 3.0" text strip in the
bottom-right corner, preceded by the vendor's spiral logo (not part of the detection
silhouette -- logos vary between releases, the text run is what discriminates).
Known variants: an "Omni" suffix release, a latin "KlingAI 3.0" release, and a
version-less "可灵AI" -- the silhouette targets the common "可灵AI 3.0" core, so the
suffix variants are only caught when the core run is bold enough (measured below).
Detection matches the bundled glyph silhouette against the corner; removal is the
shared **localize -> fill** (the glyph-bbox :meth:`footprint_mask` feeds
``region_eraser``), NOT reverse-alpha. This module supplies only Kling's tuned
:class:`TextMarkConfig` (``assets/kling_alpha.png`` -- a font-rendered synthetic
silhouette from ``scripts/render_vendor_silhouettes.py``, never cut from an
upload). It also feeds ``identify`` as the medium-confidence ``visible_kling``
signal via the registry.
EVERY tuned number below was measured on the vendor cohort (30 TC260 carriers whose
producer USCC 91110108335469089C names the entity, 2026-07-21; harness
``scripts/vendor_mark_calibrate.py``), NOT inherited from Doubao:
* The mark scales with the SHORT side at ~0.12 of it (mark_w/short measured
0.118-0.122 across portrait AND landscape carriers -- unimodal, so the shipped
3-rung ladder covers it) and sits ~0.03 off the right/bottom edges; the locate
box fractions below are fitted from the measured absolute mark rects.
* ``alpha_height_frac`` comes from the silhouette aspect (0.239) at the fitted
width, matching the aspect the fit converged on (0.25).
* Gate 0.35, one step above the clean arm's max: on the cohort-vs-clean run
(cohort-contamination-guarded, 286 hand-labelled clean frames) the clean arm
scored p99 0.304 / max 0.320, and every cohort frame >= 0.35 carries a visible
可灵AI 3.0 mark (9 of ~19 eyeballed visible marks fire = ~47% recall of visible
marks; the misses are the faint "Omni"-suffix release, the latin "KlingAI"
release and the version-less "可灵AI", which score 0.17-0.25 and cannot be
reached without engulfing the clean arm).
* STRICT ONLY (``provenance_ncc_factor`` 1.0): the sub-gate band holds real Kling
variants AND the clean arm's top (clean p90 0.220 vs variant marks at 0.17-0.25
-- they overlap), so a provenance-relaxed arm cannot separate them. No
provenance relaxation exists for this mark.
* No rival margin: at the shipped gate the template fires on 1 of 400
Doubao-marked frames (0.2%, a 豆包 frame sitting INSIDE the Kling cohort, still
below the gate), 0 of 298 Jimeng-marked frames and 0 of 286 hand-labelled clean
frames, and a 0.10 rival margin costs zero genuine Kling detections -- so it is
simply unnecessary (same conclusion shape as Qwen).
"""
# The module-level _alpha_template / _glyph_silhouette / _template_match_score below
# are thin test-facing shims (imported by tests/), so pyright's src-only pass sees them
# as unused; the use is cross-module.
# pyright: reportUnusedFunction=false
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from remove_ai_watermarks import _text_mark_engine
from remove_ai_watermarks._text_mark_engine import TextMarkConfig, TextMarkDetection, TextMarkEngine
if TYPE_CHECKING:
from pathlib import Path
from numpy.typing import NDArray
# Locate geometry as a fraction of the image SHORT side (measured basis -- see
# scale_base). The box is fitted to the measured mark rects: the mark's right
# margin is ~0.034 of the short side and its bottom margin ~0.027; width/height
# cover the mark plus NCC slack.
WM_WIDTH_FRAC = 0.19
WM_HEIGHT_FRAC = 0.05
MARGIN_RIGHT_FRAC = 0.03
MARGIN_BOTTOM_FRAC = 0.023
# Glyph appearance: a light, low-saturation gray rendered brighter than the local
# background (white top-hat), same overlay class as Doubao -- inherited, and
# harmless because the tophat front-end turns these gates into weights.
MAX_SATURATION = 55
LOGO_MIN_LUMA = 150
TOPHAT_DELTA = 12
DETECT_MIN_COVERAGE = 0.04 # unused by the tophat front-end (kept for config parity)
# Calibrated 2026-07-21 on the vendor cohort vs 286 hand-labelled clean frames
# (cohort-contamination-guarded): clean p99 0.304 / max 0.320, and every cohort
# frame scoring >= 0.35 carries a visible 可灵AI 3.0 mark. 0.35 was picked over
# 0.33 (also zero clean fires) for margin against unseen clean content at a cost
# of zero measured cohort detections.
DETECT_NCC_THRESHOLD = 0.35
# Detection-silhouette geometry (fraction of the short side), fitted on the
# cohort: the mark's width (0.12, unimodal) and the silhouette aspect (0.239).
_ALPHA_WIDTH_FRAC = 0.12
_ALPHA_HEIGHT_FRAC = 0.0287
_CONFIG = TextMarkConfig(
name="Kling",
asset_name="kling_alpha.png",
corner="br",
margin_floor=4,
width_frac=WM_WIDTH_FRAC,
height_frac=WM_HEIGHT_FRAC,
margin_x_frac=MARGIN_RIGHT_FRAC,
margin_bottom_frac=MARGIN_BOTTOM_FRAC,
max_saturation=MAX_SATURATION,
logo_min_luma=LOGO_MIN_LUMA,
tophat_delta=TOPHAT_DELTA,
morph_open_size=5,
detect_min_coverage=DETECT_MIN_COVERAGE,
detect_ncc_threshold=DETECT_NCC_THRESHOLD,
detect_frontend="tophat",
scale_basis="short", # measured: mark_w/short 0.118-0.122 across orientations
alpha_width_frac=_ALPHA_WIDTH_FRAC,
alpha_height_frac=_ALPHA_HEIGHT_FRAC,
min_gw=8,
# STRICT ONLY: the sub-gate band (real Kling variants at 0.17-0.25) overlaps
# the clean arm's top (p90 0.220), so provenance relaxation is disabled
# outright (factor 1.0 = never relaxed).
provenance_ncc_factor=1.0,
)
KlingDetection = TextMarkDetection
def _alpha_template() -> NDArray[Any] | None:
"""The bundled Kling alpha template (float [0,1]), or None."""
return _text_mark_engine.load_alpha_template(_CONFIG.asset_name)
def _glyph_silhouette() -> NDArray[Any] | None:
"""Binary "可灵AI 3.0" silhouette (255 = glyph) from the alpha map, or None."""
return _text_mark_engine.glyph_silhouette(_CONFIG.asset_name)
def _template_match_score(box_mask: NDArray[Any], scale_base: int) -> float:
"""TM_CCOEFF_NORMED of the Kling glyph silhouette against ``box_mask``."""
return _text_mark_engine.template_match_score(box_mask, scale_base, _CONFIG)
class KlingEngine(TextMarkEngine):
"""Detect/localize the visible Kling "可灵AI 3.0" watermark (locate -> mask; mask feeds the fill)."""
def __init__(self) -> None:
super().__init__(_CONFIG)
def load_image_bgr(path: str | Path) -> NDArray[Any]:
"""Read an image as BGR ndarray (helper for scripts/tests)."""
from remove_ai_watermarks import image_io
img = image_io.imread(path)
if img is None:
raise FileNotFoundError(f"Failed to read image: {path}")
return img
+189
View File
@@ -0,0 +1,189 @@
"""LibLibAI visible watermark detector/localizer.
LibLibAI (哩布哩布AI, USCC 91110105MACJ6K1C8A) stamps its generations with a
white triangle logo + "LibLibAI" latin wordmark at **bottom-center** (not a
corner -- the locate box is horizontally centered). Detection matches the
bundled font-rendered "LibLibAI" silhouette (the triangle logo is NOT rendered
-- logos vary, the wordmark discriminates); removal is the shared **localize ->
fill** (the glyph blob covers logo + wordmark, both bright).
This module supplies only LibLibAI's tuned :class:`TextMarkConfig`
(``assets/liblib_alpha.png`` from ``scripts/render_vendor_silhouettes.py``,
never cut from an upload).
Measured on the vendor cohort (15 TC260 carriers, harvested 2026-07-22 by
``scripts/vendor_cohort_harvest.py``), NOT inherited from Doubao:
* The wordmark is ~0.10 of the frame WIDTH wide, centered horizontally, its
baseline ~0.94-0.95 of the height; consistent across 768..2240-px frames.
* The silhouette font is Arial, NOT the STHeiti the CJK marks use: the real
wordmark is a grotesque, and measured across 7 candidate fonts Arial lifts
the cohort positives from 0.31-0.47 to 0.42-0.73 while the full-corpus
false arm (latin UI text) drops to max 0.398. A 200x200 icon false-fired
at 0.444, so a per-mark size floor (``_MIN_SHORT_SIDE``) backs the gate.
* Gate 0.42 (tophat front-end): false arm max 0.398, cohort 0.43-0.59.
* STRICT ONLY (``provenance_ncc_factor`` 1.0): small cohort, the relaxed band
is unmeasured.
"""
# The module-level _alpha_template / _glyph_silhouette / _template_match_score below
# are thin test-facing shims (imported by tests/), so pyright's src-only pass sees them
# as unused; the use is cross-module.
# pyright: reportUnusedFunction=false
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from remove_ai_watermarks import _text_mark_engine
from remove_ai_watermarks._text_mark_engine import TextMarkConfig, TextMarkDetection, TextMarkEngine
if TYPE_CHECKING:
from pathlib import Path
from numpy.typing import NDArray
# Locate geometry as a fraction of the image WIDTH (measured basis). The box is
# horizontally centered (corner="bc") and covers the logo + wordmark with NCC
# slack around the measured 0.10 width.
WM_WIDTH_FRAC = 0.20
WM_HEIGHT_FRAC = 0.09
MARGIN_BOTTOM_FRAC = 0.02
# Glyph appearance: white wordmark on a usually-darker background (white
# top-hat), same overlay class as Doubao -- inherited, harmless because the
# tophat front-end turns these gates into weights.
MAX_SATURATION = 55
LOGO_MIN_LUMA = 150
TOPHAT_DELTA = 12
DETECT_MIN_COVERAGE = 0.04 # unused by the tophat front-end (kept for config parity)
# Calibrated 2026-07-22 on the vendor cohort vs 286 hand-labelled clean frames
# (clean p99 0.315 / max 0.367) and re-measured after the font fix: the wordmark
# is set in an Arial-class grotesque, and the Arial silhouette lifts the cohort
# positives to 0.43-0.59 while the full-corpus false arm (latin UI text bands,
# website screenshots) drops to max 0.398 -- generic latin text matches the
# wrong font less, which is exactly where the discrimination comes from. Gate
# 0.42 keeps all 8 marked cohort frames with a 0.022 margin over the false arm.
DETECT_NCC_THRESHOLD = 0.42
# Detection-silhouette geometry (fraction of the frame width): the wordmark,
# measured 0.10 wide with aspect 0.26.
_ALPHA_WIDTH_FRAC = 0.10
_ALPHA_HEIGHT_FRAC = 0.026
# Tight ladder: the NCC comb is sharp in size (see runninghub_engine).
_LADDER = (0.9, 1.0, 1.1)
_CONFIG = TextMarkConfig(
name="LibLibAI",
asset_name="liblib_alpha.png",
corner="bc",
margin_floor=4,
width_frac=WM_WIDTH_FRAC,
height_frac=WM_HEIGHT_FRAC,
margin_x_frac=0.0, # unused for corner="bc" (horizontally centered)
margin_bottom_frac=MARGIN_BOTTOM_FRAC,
max_saturation=MAX_SATURATION,
logo_min_luma=LOGO_MIN_LUMA,
tophat_delta=TOPHAT_DELTA,
morph_open_size=5,
detect_min_coverage=DETECT_MIN_COVERAGE,
detect_ncc_threshold=DETECT_NCC_THRESHOLD,
detect_frontend="tophat",
scale_basis="width",
ladder=_LADDER,
alpha_width_frac=_ALPHA_WIDTH_FRAC,
alpha_height_frac=_ALPHA_HEIGHT_FRAC,
min_gw=8,
# STRICT ONLY: small cohort, the relaxed band is unmeasured.
provenance_ncc_factor=1.0,
)
LibLibDetection = TextMarkDetection
def _alpha_template() -> NDArray[Any] | None:
"""The bundled LibLibAI alpha template (float [0,1]), or None."""
return _text_mark_engine.load_alpha_template(_CONFIG.asset_name)
def _glyph_silhouette() -> NDArray[Any] | None:
"""Binary "LibLibAI" silhouette (255 = glyph) from the alpha map, or None."""
return _text_mark_engine.glyph_silhouette(_CONFIG.asset_name)
def _template_match_score(box_mask: NDArray[Any], scale_base: int) -> float:
"""TM_CCOEFF_NORMED of the LibLibAI glyph silhouette against ``box_mask``."""
return _text_mark_engine.template_match_score(box_mask, scale_base, _CONFIG)
class LibLibEngine(TextMarkEngine):
"""Detect/localize the visible LibLibAI wordmark (bottom-center; localize -> fill)."""
# Per-mark size floor: the wordmark template is 0.10 of the frame width, so
# below ~480px short side it degrades under ~48px -- the one full-corpus
# false fire with the final Arial template was a 200x200 icon (0.444, above
# the gate, on a 20px template; measured 2026-07-22). The smallest true
# carrier in the cohort is 768px.
_MIN_SHORT_SIDE = 480
def __init__(self) -> None:
super().__init__(_CONFIG)
def detect(self, image: NDArray[Any] | None, *, provenance: bool = False) -> TextMarkDetection:
if image is None or not image.size or min(image.shape[:2]) < self._MIN_SHORT_SIDE:
return TextMarkDetection()
return super().detect(image, provenance=provenance)
def footprint_mask(
self, image: NDArray[Any] | None, *, force: bool = False, dilate: int | None = None
) -> NDArray[Any] | None:
"""Full-frame mask of the logo + wordmark, bounded by the detector's match box.
The base class's blob-bbox footprint is wrong in both directions here: the
blob bleeds UP into bright background structure (on the 768x1024 cohort
frame it reached y 931 and the fill ate the shirt's own print) and it does
not own the triangle logo anyway. The match box bounds the wordmark exactly
(that is what the NCC localized); the logo sits its own height to the LEFT
of the text (measured on the cohort zoom: logo ~1.0x the glyph height, gap
~0.3x), so the footprint is the match box extended left by ~1.3 heights.
"""
if image is None or image.size == 0:
return None
from remove_ai_watermarks import image_io, region_eraser
image = image_io.to_bgr(image)
h, w = image.shape[:2]
if h < 32 or w < 64:
return None
loc = self.locate(image)
bx, by, bw, bh = loc.bbox
if force:
rx1, ry1, rx2, ry2 = bx, by, min(w, bx + bw), min(h, by + bh)
else:
if not self.detect(image).detected:
return None
_, box = self._tophat_best(image, loc)
if box is None:
return None
gx0, gy0, gx1, gy1 = box
gh = gy1 - gy0 + 1
pad = max(3, int(0.25 * gh))
rx1 = max(0, bx + gx0 - int(1.3 * gh)) # the triangle logo, left of the text
ry1 = max(0, by + gy0 - pad)
rx2 = min(w, bx + gx1 + 1 + pad)
ry2 = min(h, by + gy1 + 1 + pad)
if rx1 >= rx2 or ry1 >= ry2:
return None
d = dilate if dilate is not None else max(3, int(0.02 * bw))
return region_eraser.boxes_to_mask((h, w), [(rx1, ry1, rx2 - rx1, ry2 - ry1)], dilate=d)
def load_image_bgr(path: str | Path) -> NDArray[Any]:
"""Read an image as BGR ndarray (helper for scripts/tests)."""
from remove_ai_watermarks import image_io
img = image_io.imread(path)
if img is None:
raise FileNotFoundError(f"Failed to read image: {path}")
return img
+120 -36
View File
@@ -347,7 +347,7 @@ def has_ai_metadata(image_path: Path) -> bool:
return True
# China TC260 AIGC label as a PNG text chunk (the byte scan above catches
# only the XMP form; the raw-JSON tEXt chunk needs the PIL-based parse).
if aigc_label(image_path):
if aigc_label(image_path) is not None:
return True
# HuggingFace-hosted job marker (hf-job-id PNG text chunk).
if huggingface_job(image_path):
@@ -751,8 +751,11 @@ def _is_aigc_exif_value(raw: object) -> bool:
``UserComment`` / ``ImageDescription`` by China-served generators (Doubao's
producer schema AND Tencent Cloud's service-provider schema, both keyed under
``_TC260_FIELDS``). Gated on both the ``AIGC`` marker and a TC260 field so a
coincidental token cannot false-drop a genuine caption/comment.
coincidental token cannot false-drop a genuine caption/comment. Accepts a ``str``
too (a PNG ``tEXt``/``iTXt`` value), not only EXIF bytes.
"""
if isinstance(raw, str):
raw = raw.encode("latin-1", "ignore")
if not isinstance(raw, (bytes, bytearray)):
return False
if b"AIGC" not in raw:
@@ -884,7 +887,7 @@ def get_ai_metadata(image_path: Path) -> dict[str, str]:
result["soft_binding"] = ", ".join(vendors)
# China TC260 AI-content label (Doubao and other China-served generators).
if aigc := aigc_label(image_path):
if (aigc := aigc_label(image_path)) is not None:
producer = aigc.get("ContentProducer", "")
result["aigc_label"] = f"China AIGC label (TC260){f'; producer {producer}' if producer else ''}"
@@ -951,25 +954,37 @@ def _jpeg_app_carries_ai(marker: int, payload: bytes) -> bool:
APP11, an AI XMP packet in APP1, an IPTC "Made with AI" record in APP13). EXIF
(APP1 ``Exif``) is NOT dropped here -- it is scrubbed tag-by-tag via piexif so
genuine camera EXIF survives."""
if marker == 0xEB: # APP11: C2PA / JUMBF manifest
return c2pa_marker_in(payload) or b"jumb" in payload[:256].lower()
if marker == 0xE1 and payload.startswith(b"http://ns.adobe.com/xap/"): # APP1 XMP
return (
if not (0xE0 <= marker <= 0xEF): # only APPn segments carry these
return False
# C2PA / JUMBF manifest (APP11).
if marker == 0xEB and (c2pa_marker_in(payload) or b"jumb" in payload[:256].lower()):
return True
# AI XMP packet (APP1): C2PA, a China-AIGC token, or an IPTC digitalSourceType /
# 2025.1 AI-disclosure marker (which live in XMP, not only the APP13 IIM record).
if (
marker == 0xE1
and payload.startswith(b"http://ns.adobe.com/xap/")
and (
c2pa_marker_in(payload)
or any(m in payload for m in AIGC_MARKERS)
or any(m in payload for m in IPTC_AI_MARKERS) # digitalSourceType in XMP, not only APP13
or any(m in payload for m in IPTC_AI_FIELD_MARKERS) # IPTC 2025.1 AI-disclosure fields
or any(m in payload for m in IPTC_AI_MARKERS)
or any(m in payload for m in IPTC_AI_FIELD_MARKERS)
)
if marker == 0xED: # APP13: Photoshop / IPTC
return any(m in payload for m in IPTC_AI_MARKERS) or any(m in payload for m in IPTC_AI_FIELD_MARKERS)
# A bare / wrapped China TC260 AIGC block (``AIGC{...}`` or ``{"AIGC":{...}}``) that
# some China-served generators glue into a non-standard APP segment near the JFIF
# header. ``aigc_label`` detects it anywhere in the scan head, so removal must drop
# the carrying segment too (detection<->removal parity). Skip APP1-EXIF (0xE1
# ``Exif``): its camera tags are scrubbed tag-by-tag via piexif, and the AIGC-in-
# UserComment/ImageDescription placement is handled there, so it must not be dropped
# wholesale here.
if 0xE0 <= marker <= 0xEF and not (marker == 0xE1 and payload.startswith(b"Exif")):
):
return True
# IPTC "Made with AI" record (APP13).
if marker == 0xED and (
any(m in payload for m in IPTC_AI_MARKERS) or any(m in payload for m in IPTC_AI_FIELD_MARKERS)
):
return True
# A bare / wrapped China TC260 AIGC block (``AIGC{...}`` or ``{"AIGC":{...}}``) glued
# into ANY APP segment -- some China gens use APP11, APP1, or a near-JFIF APPn. This
# runs for every APP marker the specific checks above did NOT already claim, so a bare
# AIGC in APP11 (not a C2PA manifest) is no longer missed by the 0xEB C2PA-only check.
# ``aigc_label`` detects it anywhere, so removal must drop the carrying segment too
# (detection<->removal parity). Skip APP1-EXIF (0xE1 ``Exif``): its camera tags are
# scrubbed tag-by-tag via piexif, not dropped wholesale.
if not (marker == 0xE1 and payload.startswith(b"Exif")):
return _is_aigc_exif_value(payload)
return False
@@ -1039,6 +1054,49 @@ def _strip_jpeg_metadata_lossless(source_path: Path, output_path: Path) -> bool:
return True
# Fallback extension -> PIL save format, used only when the content sniff is
# inconclusive (never for JPEG re-encode of lossless content).
_EXT_TO_PIL_FORMAT = {".jpg": "JPEG", ".jpeg": "JPEG", ".webp": "WEBP", ".png": "PNG"}
def _sniff_image_format(head: bytes) -> str | None:
"""Actual raster format from a file's leading magic bytes (>= 12 bytes), as a PIL
format name ("JPEG"/"PNG"/"WEBP"), or None when unrecognized. The file EXTENSION is
unreliable: ~2% of real uploads carry a mismatched one (a PNG served as ``.jpg`` is
common). Choosing the save format by extension re-encodes a lossless PNG/WebP into a
real JPEG, silently degrading the pixels -- so the strip routes on content instead.
ISOBMFF/GIF are handled before this point or fall through to PNG; only the
lossy-vs-lossless distinction that matters here is resolved."""
if head[:2] == b"\xff\xd8":
return "JPEG"
if head[:8] == b"\x89PNG\r\n\x1a\n":
return "PNG"
if head[:4] == b"RIFF" and head[8:12] == b"WEBP":
return "WEBP"
return None
def strip_and_verify(
source_path: Path,
output_path: Path | None = None,
*,
keep_standard: bool = True,
) -> tuple[Path, dict[str, str]]:
"""Strip AI metadata, then RE-SCAN the output and report what survived.
:func:`remove_ai_metadata` is deliberately fail-safe: a file PIL cannot decode is
copied through UNCHANGED rather than crashing a caller, and the path it returns is
indistinguishable from a real strip. Any caller that reports an outcome to a user
therefore cannot tell a no-op from a success -- corpus-observed on real Samsung
Galaxy S22 C2PA PNGs, where `metadata --remove` printed "stripped" and exited 0 while
the output still read as AI (2026-07-19 parity audit).
Returns ``(output_path, surviving_markers)``; an empty mapping means a real strip.
"""
out = remove_ai_metadata(source_path, output_path, keep_standard=keep_standard)
return out, get_ai_metadata(out)
def remove_ai_metadata(
source_path: Path,
output_path: Path | None = None,
@@ -1106,6 +1164,12 @@ def remove_ai_metadata(
if source_path.suffix.lower() in _FFMPEG_STRIP_EXTS:
return _strip_with_ffmpeg(source_path, output_path)
# Route on the ACTUAL content format, not the extension (which lies on ~2% of real
# uploads -- a PNG served as .jpg, etc.). Trusting the extension would push a
# lossless PNG/WebP through the lossy JPEG re-encode below just because its name
# ends .jpg, breaking the "work with originals" invariant.
true_fmt = _sniff_image_format(head) # reuse the 12 bytes already read above
# JPEG: strip AI metadata at the byte level so the DCT scan (the pixels) is NOT
# re-encoded. The PIL open+save path below is lossy for JPEG (a q95 re-encode that
# would undo the quality-preserving writes of the removal pipelines); this keeps a
@@ -1113,21 +1177,42 @@ def remove_ai_metadata(
# non-parseable JPEG. Only when keep_standard: the lossless walk drops AI segments
# but preserves standard ones, so a keep_standard=False caller (strip EVERYTHING)
# must use the full re-encode path below instead.
if (
keep_standard
and output_path.suffix.lower() in (".jpg", ".jpeg")
and _strip_jpeg_metadata_lossless(source_path, output_path)
):
if keep_standard and true_fmt == "JPEG" and _strip_jpeg_metadata_lossless(source_path, output_path):
return output_path
# Fail-safe for a truncated / corrupt image: PIL raises OSError when it decodes a
# partial file (`img.copy()` / `img.save()` below), which would crash a direct
# library caller (a web worker 500s on a partial upload). Probe decodability first;
# if it fails, copy the input through unchanged and return -- we cannot strip what we
# cannot parse, but we never raise (mirrors strip_c2pa_boxes' fail-safe).
try:
with Image.open(source_path) as _probe:
_probe.load()
except Exception:
logger.warning("Could not decode %s to strip metadata (truncated/corrupt); copied through", source_path)
if output_path != source_path:
import shutil
output_path.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(source_path, output_path)
return output_path
# Read image and filter metadata
with Image.open(source_path) as img:
img = img.copy()
fmt = output_path.suffix.lower()
# Pick the save format. Honor the caller's output extension (so a deliberate
# source.png -> output.jpg conversion still works) UNLESS the SOURCE is misnamed
# -- a lossless PNG/WebP whose extension lies (served as .jpg). There the output
# extension only inherited the source's wrong name, so re-encoding to JPEG would
# silently degrade an original; preserve the true content format instead.
source_ext_fmt = _EXT_TO_PIL_FORMAT.get(source_path.suffix.lower())
if true_fmt is not None and true_fmt != source_ext_fmt:
fmt = true_fmt # misnamed source: never let a lying extension force a re-encode
else:
fmt = _EXT_TO_PIL_FORMAT.get(output_path.suffix.lower()) or true_fmt or "PNG"
save_kwargs: dict[str, Any] = {}
if fmt in (".jpg", ".jpeg"):
save_kwargs["format"] = "JPEG"
save_kwargs: dict[str, Any] = {"format": fmt}
if fmt == "JPEG":
# JPEG output is unavoidably lossy, so minimize the loss: high quality
# and no chroma subsampling (4:4:4). Without these PIL defaults to
# quality 75 + 4:2:0, which visibly degrades a re-saved image.
@@ -1135,15 +1220,12 @@ def remove_ai_metadata(
save_kwargs["subsampling"] = 0
if img.mode in ("RGBA", "P"):
img = img.convert("RGB")
elif fmt == ".webp":
elif fmt == "WEBP":
# Preserve the WebP container losslessly instead of silently rewriting
# it as PNG (which changes the format and bloats the file).
save_kwargs["format"] = "WEBP"
save_kwargs["lossless"] = True
if img.mode == "P": # WebP cannot encode palette mode
img = img.convert("RGBA" if "transparency" in img.info else "RGB")
else:
save_kwargs["format"] = "PNG"
# Collect non-AI metadata
kept_meta: dict[str, str] = {}
@@ -1154,10 +1236,12 @@ def remove_ai_metadata(
continue
if _is_ai_key(key):
continue
# Drop a generic text chunk whose VALUE names an AI generator (NovelAI
# writes its stamp into Title/Source under non-AI keys) -- keeps removal
# in parity with exif_generator's value-based detection.
if isinstance(value, str) and _is_ai_value(value):
# Drop a text chunk whose VALUE names an AI generator (NovelAI writes its
# stamp into Title/Source under non-AI keys) OR carries a China TC260 AIGC
# block (some China gens put `{"AIGC":{...}}` in a STANDARD chunk like
# Description, which _is_ai_key would keep) -- keeps removal in parity with
# exif_generator / aigc_label's value-based detection.
if isinstance(value, str) and (_is_ai_value(value) or _is_aigc_exif_value(value)):
continue
if key == "exif":
with contextlib.suppress(Exception):
@@ -184,6 +184,20 @@ C2PA_AI_VENDORS: tuple[C2paAiVendor, ...] = (
# manifest alone marks AI generation. Verified against the mined retained
# corpus, 2026-06-20. ElevenLabs does not use SynthID.
C2paAiVendor(b"Eleven Labs", "ElevenLabs", "ElevenLabs", "ElevenLabs"),
# fal.ai (generative inference platform, issuer "fal - Features & Labels
# Inc." / common name "fal.ai", claim generators like "fal-ai/seedvr",
# "fal-ai/gpt-image-2"). Corpus-measured 2026-07-23 on the retained
# uploads (17 files): the files carry trainedAlgorithmicMedia, so the
# verdict already fired, but the platform stayed unattributed. fal.ai is
# a pure generative platform, so ``asserts_ai`` also covers its output
# that omits the source-type.
C2paAiVendor(b"fal-ai", "fal.ai", "fal.ai", "fal.ai", asserts_ai=True),
# Bria AI (bria.ai, generative platform) signs as "Bria Artificial
# Intelligence" with a "Bria Ai" claim generator and source type
# ``empty`` (NOT trainedAlgorithmicMedia), so a real signed file was
# completely missed by identify -- corpus-found 2026-07-23. A pure-AI
# vendor with distinctive strings, so ``asserts_ai`` is safe here.
C2paAiVendor(b"Bria", "Bria Artificial Intelligence", "Bria AI", "Bria", asserts_ai=True),
# Truepic is a C2PA signing authority, not an AI generator: no platform label,
# never asserts is_ai (the verdict comes from the digital-source-type).
C2paAiVendor(b"Truepic", "Truepic", None, None),
@@ -307,6 +321,13 @@ AI_GENERATOR_TOKENS: frozenset[str] = frozenset(
"novelai",
"reve.com",
"aphrodite ai",
# Corpus-mined 2026-07-23:
# - Apple Photos Clean Up (Apple Intelligence object removal): XMP
# photoshop:Credit / IPTC credit value; composite source-type
# covered detection, this token covers removal parity (35 files).
# - fal-ai: generative-platform generator string (17 files).
"apple photos clean up",
"fal-ai",
}
)
@@ -5,6 +5,7 @@ Pure configuration and lookup functions with no ML dependencies.
from __future__ import annotations
import math
from typing import TYPE_CHECKING, Literal
if TYPE_CHECKING:
@@ -137,6 +138,30 @@ def resolve_strength(strength: float | None, vendor: str | None = None, pipeline
return _VENDOR_STRENGTH.get(vendor or "", UNKNOWN_STRENGTH)
def viable_steps(num_inference_steps: int, strength: float) -> int:
"""The smallest step count >= ``num_inference_steps`` that actually denoises.
diffusers derives its img2img timesteps as ``int(steps * strength)``. When that
rounds to ZERO the pipeline builds an empty latent and dies deep inside attention
with ``cannot reshape tensor of 0 elements into shape [0, -1, 1, 512]`` -- an opaque
torch error for what is really "these two options cannot work together".
The combination is reachable with entirely valid CLI arguments: at the default
strength 0.15 every ``--steps`` below 7 crashed, and nothing told the user that
``--steps`` and ``--strength`` interact (found by the release smoke matrix,
2026-07-19). Raising the count to the minimum that denoises keeps the caller's intent
-- they asked for "few steps", not "zero" -- and the engine logs the adjustment.
A non-positive ``strength`` cannot denoise at any step count; return the caller's
value unchanged rather than dividing by zero.
"""
if strength <= 0:
return num_inference_steps
if int(num_inference_steps * strength) >= 1:
return num_inference_steps
return math.ceil(1 / strength)
def vendor_for_strength(image_path: Path) -> Literal["openai", "google"] | None:
"""Detect the SynthID vendor for strength selection: ``"openai"`` / ``"google"`` / None.
@@ -49,6 +49,7 @@ from remove_ai_watermarks.noai.watermark_profiles import (
QWEN_MODEL_ID,
normalize_profile,
resolve_strength,
viable_steps,
)
logger = logging.getLogger(__name__)
@@ -447,6 +448,19 @@ class WatermarkRemover:
self._set_progress("Loading fp16-fixed SDXL VAE (avoids black output)...")
load_kwargs["vae"] = AutoencoderKL.from_pretrained(_SDXL_FP16_VAE_ID, torch_dtype=torch.float16)
@staticmethod
def _disable_sdxl_watermarker(load_kwargs: dict[str, Any]) -> None:
"""Turn off the diffusers default invisible watermarker on an SDXL pipeline.
diffusers embeds an open "Stable Diffusion XL" DWT-DCT invisible watermark on
EVERY SDXL output whenever ``invisible-watermark`` is installed (the ``detect``
extra). A watermark REMOVER must not re-stamp a detectable AI watermark, or the
cleaned output re-reads as AI (``identify`` -> "Open invisible watermark: Stable
Diffusion XL"). Shared by both SDXL loaders; the ``ControlNetModel`` sub-model
and the Qwen loader never call it (only the pipeline accepts the kwarg).
"""
load_kwargs["add_watermarker"] = False
def _move_to_device_and_optimize(self, pipeline: Any) -> Any:
"""Move a freshly-loaded pipeline to ``self.device`` + enable memory opts.
@@ -520,6 +534,7 @@ class WatermarkRemover:
load_kwargs = self._base_load_kwargs()
load_kwargs["safety_checker"] = None
load_kwargs["requires_safety_checker"] = False
self._disable_sdxl_watermarker(load_kwargs)
self._maybe_add_fp16_vae(load_kwargs)
pipeline = self._load_from_pretrained(AutoImg2ImgPipeline, self.model_id, **load_kwargs) # type: ignore
@@ -549,6 +564,7 @@ class WatermarkRemover:
load_kwargs = self._base_load_kwargs()
load_kwargs["controlnet"] = controlnet
self._disable_sdxl_watermarker(load_kwargs)
self._maybe_add_fp16_vae(load_kwargs)
self._set_progress(f"Loading model weights: {self.model_id}")
@@ -675,6 +691,20 @@ class WatermarkRemover:
self._set_progress(f"Setting reproducible seed: {seed}")
generator = _make_seed_generator(self.device, seed)
# A step count whose product with strength rounds to zero kills the pipeline
# inside attention with an opaque reshape error, so raise it to the minimum that
# denoises. Must be applied to the value HANDED TO THE PIPELINE -- the old
# max(1, ...) below only clamped the number in the log line.
adjusted = viable_steps(num_inference_steps, strength)
if adjusted != num_inference_steps:
logger.warning(
"steps=%s at strength=%s denoises 0 steps and would crash; using steps=%s (1 effective)",
num_inference_steps,
strength,
adjusted,
)
num_inference_steps = adjusted
effective_steps = max(1, int(num_inference_steps * strength))
self._set_progress(
f"Config: strength={strength}, steps={num_inference_steps} "
+157
View File
@@ -0,0 +1,157 @@
"""Qwen (Tongyi Qianwen, Alibaba) visible watermark detector/localizer.
Qwen stamps its generations with a visible "千问AI生成" text strip in the
bottom-right corner -- the explicit AIGC label mandated by China's GB 45438-2025
(the same 6-glyph house style as Doubao's "豆包AI生成": a 2-glyph vendor prefix
plus the shared `AI生成` tail), preceded by the vendor's tri-lobe logo (not part
of the detection silhouette -- logos vary between releases, the CJK run is what
discriminates).
Detection matches the bundled glyph silhouette against the corner; removal is the
shared **localize -> fill** (the glyph-bbox :meth:`footprint_mask` feeds
``region_eraser``), NOT reverse-alpha. This module supplies only Qwen's tuned
:class:`TextMarkConfig` (``assets/qwen_alpha.png`` -- a font-rendered synthetic
silhouette from ``scripts/render_vendor_silhouettes.py``, never cut from an
upload). It also feeds ``identify`` as the medium-confidence ``visible_qwen``
signal via the registry.
EVERY tuned number below was measured on the vendor cohort (117 TC260 carriers
whose producer USCC 91440101MA9Y9T4H7A names the entity, 2026-07-21; harness
``scripts/vendor_mark_calibrate.py``), NOT inherited from Doubao:
* The mark sits in TWO size modes (frac of the short side ~0.124 and ~0.203,
ratio 1.64 -- wider than the shared 3-rung ladder's 1.5625 span), so a single
fraction on the shared ladder covers ~75% of marks and the rest land in the
comb's collapse zone. Qwen therefore carries its OWN 2-rung ladder
(``TextMarkConfig.ladder``), one rung centred on each mode; the shared
default is untouched for every other mark.
* The mark also sits FARTHER off the corner than Doubao's box assumes (right
margin ~0.025 vs 0.004 of the short side), so Doubao's locate box clipped the
first glyph and collapsed an exact-size template to 0.26; the box fractions
below are fitted from the measured absolute mark rects.
* ``alpha_height_frac`` comes from the aspect fit at the winning width (p50
aspect 0.26), not from the silhouette's own aspect (0.2219) and not from
Doubao's ratio.
* STRICT ONLY (``provenance_ncc_factor`` 1.0): the score band just below the
gate is dominated by non-Qwen banners on same-cohort frames (a 夸克
anti-forgery strip at 0.274, a 造点 mark at 0.253), so a provenance-relaxed
arm would be mostly false fills. No provenance relaxation exists for this
mark.
* No rival margin: at the shipped gate the template fires on 0 of 400
Doubao-marked frames, 0 of 298 Jimeng-marked frames and 0 of 286 hand-labelled
clean frames (the shared tail correlates at ~0.22, far below the gate), while
a 0.10 rival margin would have suppressed ~10% of genuine Qwen detections.
"""
# The module-level _alpha_template / _glyph_silhouette / _template_match_score below
# are thin test-facing shims (imported by tests/), so pyright's src-only pass sees them
# as unused; the use is cross-module.
# pyright: reportUnusedFunction=false
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from remove_ai_watermarks import _text_mark_engine
from remove_ai_watermarks._text_mark_engine import TextMarkConfig, TextMarkDetection, TextMarkEngine
if TYPE_CHECKING:
from pathlib import Path
from numpy.typing import NDArray
# Locate geometry as a fraction of the image SHORT side (measured basis -- see
# scale_base). The box is fitted to the measured mark rects: the mark's right
# margin is ~0.025 of the short side (not Doubao's 0.004), so the box anchor is
# wider off the corner; width/height cover the big size mode plus NCC slack.
WM_WIDTH_FRAC = 0.231
WM_HEIGHT_FRAC = 0.074
MARGIN_RIGHT_FRAC = 0.0203
MARGIN_BOTTOM_FRAC = 0.0218
# Glyph appearance: a light, low-saturation gray rendered brighter than the local
# background (white top-hat), same overlay class as Doubao -- inherited, and
# harmless because the tophat front-end turns these gates into weights.
MAX_SATURATION = 55
LOGO_MIN_LUMA = 150
TOPHAT_DELTA = 12
DETECT_MIN_COVERAGE = 0.04 # unused by the tophat front-end (kept for config parity)
# Calibrated 2026-07-21 on the vendor cohort vs 286 hand-labelled clean frames
# (cohort-contamination-guarded): clean p99 0.301 / max 0.316, and every cohort
# frame scoring >= 0.45 carries a visible 千问AI生成 mark (86% of the eyeballed
# visible marks fire, the misses being white-on-near-white contrast losses).
# 0.45 was picked over 0.32 (identical clean fire) for margin against unseen
# clean content at zero measured recall cost.
DETECT_NCC_THRESHOLD = 0.45
# Detection-silhouette geometry (fraction of the short side), fitted on the
# cohort: the mark's width modes and its aspect (0.26) at the winning width.
_ALPHA_WIDTH_FRAC = 0.160
_ALPHA_HEIGHT_FRAC = 0.0416
# The two measured size modes as scale rungs: 0.124 and 0.203 of the short side,
# expressed against the 0.160 nominal. Measured, not rounded: off-mode rungs drop
# NCC from ~0.73 to ~0.37 on real marks (the comb), and a 4-rung variant scored
# strictly worse (the extra rungs cover nothing and the big mode lands 4.6% off
# its nearest rung).
_LADDER = (0.78, 1.27)
_CONFIG = TextMarkConfig(
name="Qwen",
asset_name="qwen_alpha.png",
corner="br",
margin_floor=4,
width_frac=WM_WIDTH_FRAC,
height_frac=WM_HEIGHT_FRAC,
margin_x_frac=MARGIN_RIGHT_FRAC,
margin_bottom_frac=MARGIN_BOTTOM_FRAC,
max_saturation=MAX_SATURATION,
logo_min_luma=LOGO_MIN_LUMA,
tophat_delta=TOPHAT_DELTA,
morph_open_size=5,
detect_min_coverage=DETECT_MIN_COVERAGE,
detect_ncc_threshold=DETECT_NCC_THRESHOLD,
detect_frontend="tophat",
scale_basis="short", # measured: frac_short CV 0.189 vs width 0.273
ladder=_LADDER,
alpha_width_frac=_ALPHA_WIDTH_FRAC,
alpha_height_frac=_ALPHA_HEIGHT_FRAC,
min_gw=8,
# STRICT ONLY: the sub-gate band is dominated by non-Qwen banners, so
# provenance relaxation is disabled outright (factor 1.0 = never relaxed).
provenance_ncc_factor=1.0,
)
QwenDetection = TextMarkDetection
def _alpha_template() -> NDArray[Any] | None:
"""The bundled Qwen alpha template (float [0,1]), or None."""
return _text_mark_engine.load_alpha_template(_CONFIG.asset_name)
def _glyph_silhouette() -> NDArray[Any] | None:
"""Binary "千问AI生成" silhouette (255 = glyph) from the alpha map, or None."""
return _text_mark_engine.glyph_silhouette(_CONFIG.asset_name)
def _template_match_score(box_mask: NDArray[Any], scale_base: int) -> float:
"""TM_CCOEFF_NORMED of the Qwen glyph silhouette against ``box_mask``."""
return _text_mark_engine.template_match_score(box_mask, scale_base, _CONFIG)
class QwenEngine(TextMarkEngine):
"""Detect/localize the visible Qwen "千问AI生成" watermark (locate -> mask; mask feeds the fill)."""
def __init__(self) -> None:
super().__init__(_CONFIG)
def load_image_bgr(path: str | Path) -> NDArray[Any]:
"""Read an image as BGR ndarray (helper for scripts/tests)."""
from remove_ai_watermarks import image_io
img = image_io.imread(path)
if img is None:
raise FileNotFoundError(f"Failed to read image: {path}")
return img
@@ -0,0 +1,180 @@
"""RunningHub visible watermark detector/localizer.
RunningHub (a hosted ComfyUI platform, USCC 91340100MAEB4N8H76) stamps its
generations with a faint light-gray "RunningHub AI生成" text mark in the
**top-left** corner -- the China TC260 explicit AIGC label, but placed top-left
(unlike the GB 45438-2025 house style bottom-right of Doubao/Qwen/Kling) and
rendered in a mid-gray that the white top-hat front-end suppresses to clean-arm
levels.
Detection therefore uses the ``gray`` front-end (raw-grayscale silhouette NCC,
see ``TextMarkConfig.detect_frontend``); removal is the shared **localize ->
fill** (the detector's best-match box feeds :meth:`footprint_mask` ->
``region_eraser``). This module supplies only RunningHub's tuned
:class:`TextMarkConfig` (``assets/runninghub_alpha.png`` -- a font-rendered
synthetic silhouette from ``scripts/render_vendor_silhouettes.py``, never cut
from an upload).
EVERY tuned number below was measured on the vendor cohort (73 TC260 carriers
whose producer USCC names the entity, harvested 2026-07-22 by
``scripts/vendor_cohort_harvest.py``), NOT inherited from Doubao:
* Only ~4 of the 73 cohort frames carry a visible mark (the rest are
metadata-only TC260 carriers -- the platform labels frames it does not
stamp), so recall of visible marks is 4/4 but the cohort fire rate is not
a recall estimate. Positions/geometry are consistent across the positives.
* The mark's width is ~0.32 of the frame WIDTH (0.319 measured on 832/1080/
1536-wide frames) at ~0.008/0.006 x/y margins; the locate box below covers
it with NCC slack.
* ``alpha_height_frac`` comes from the silhouette aspect (0.128) at the
measured width (0.27 * 1.25 rung ~= 0.3375 >= 0.32), per the standing rule
that it is measured, not inherited.
* STRICT ONLY (``provenance_ncc_factor`` 1.0): raw gray NCC is
contrast-DEPENDENT and the sub-gate band of a corner-anchored gray match is
unmeasured beyond the clean arm, so no provenance relaxation exists.
* Gate 0.34: on 283 hand-labelled clean frames (cohort-contamination-guarded)
corner-anchored gray NCC p99 is 0.264 / max 0.304, while the 4 positives
score 0.38-0.54. 0.34 sits above the clean max with a small margin; the
positives are few, so the margin is deliberately thin on the recall side.
"""
# The module-level _alpha_template / _glyph_silhouette / _template_match_score below
# are thin test-facing shims (imported by tests/), so pyright's src-only pass sees them
# as unused; the use is cross-module.
# pyright: reportUnusedFunction=false
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Any
from remove_ai_watermarks import _text_mark_engine
from remove_ai_watermarks._text_mark_engine import TextMarkConfig, TextMarkDetection, TextMarkEngine
logger = logging.getLogger(__name__)
if TYPE_CHECKING:
from pathlib import Path
from numpy.typing import NDArray
# Locate geometry as a fraction of the image WIDTH (the measured basis: every
# positive is portrait, where width == short side). The mark hugs the top-left
# corner (~0.008 of width off the left edge, ~0.006 of height off the top).
WM_WIDTH_FRAC = 0.45
WM_HEIGHT_FRAC = 0.10
MARGIN_LEFT_FRAC = 0.002
MARGIN_TOP_FRAC = 0.002
# Glyph appearance fields are unused by the gray front-end (it never binarizes)
# and kept only for config parity with the other text marks.
MAX_SATURATION = 55
LOGO_MIN_LUMA = 150
TOPHAT_DELTA = 12
DETECT_MIN_COVERAGE = 0.04 # unused by the gray front-end (kept for config parity)
# Calibrated 2026-07-22 on the vendor cohort vs 283 hand-labelled clean frames:
# corner-anchored gray NCC, clean p99 0.264 / max 0.304; positives 0.38-0.54.
DETECT_NCC_THRESHOLD = 0.34
# Detection-silhouette geometry (fraction of the image width), measured on the
# positives: mark width is ~0.320 of width on all three frame sizes (266px at 832,
# 345px at 1080, 491px at 1536), and the NCC is razor-sharp in size (0.537 on-size,
# 0.223 at +5.6% -- the same comb behaviour Qwen measured), so the nominal sits
# exactly on the measured size with a TIGHT ladder around it, not the shared 3 rungs
# (whose nearest rung landed 5.6% off and collapsed the match to 0.22).
_ALPHA_WIDTH_FRAC = 0.32
_ALPHA_HEIGHT_FRAC = 0.04
_LADDER = (0.95, 1.0, 1.05)
_CONFIG = TextMarkConfig(
name="RunningHub",
asset_name="runninghub_alpha.png",
corner="tl",
margin_floor=4,
width_frac=WM_WIDTH_FRAC,
height_frac=WM_HEIGHT_FRAC,
margin_x_frac=MARGIN_LEFT_FRAC,
margin_bottom_frac=MARGIN_TOP_FRAC, # top margin for corner="tl"
max_saturation=MAX_SATURATION,
logo_min_luma=LOGO_MIN_LUMA,
tophat_delta=TOPHAT_DELTA,
morph_open_size=5,
detect_min_coverage=DETECT_MIN_COVERAGE,
detect_ncc_threshold=DETECT_NCC_THRESHOLD,
detect_frontend="gray",
scale_basis="width", # measured: mark width tracks the frame width (0.32)
ladder=_LADDER,
alpha_width_frac=_ALPHA_WIDTH_FRAC,
alpha_height_frac=_ALPHA_HEIGHT_FRAC,
min_gw=8,
# STRICT ONLY: contrast-dependent gray NCC; the relaxed band is unmeasured.
provenance_ncc_factor=1.0,
)
RunningHubDetection = TextMarkDetection
def _alpha_template() -> NDArray[Any] | None:
"""The bundled RunningHub alpha template (float [0,1]), or None."""
return _text_mark_engine.load_alpha_template(_CONFIG.asset_name)
def _glyph_silhouette() -> NDArray[Any] | None:
"""Binary "RunningHub AI生成" silhouette (255 = glyph) from the alpha map, or None."""
return _text_mark_engine.glyph_silhouette(_CONFIG.asset_name)
def _template_match_score(box_mask: NDArray[Any], scale_base: int) -> float:
"""TM_CCOEFF_NORMED of the RunningHub glyph silhouette against ``box_mask``."""
return _text_mark_engine.template_match_score(box_mask, scale_base, _CONFIG)
class RunningHubEngine(TextMarkEngine):
"""Detect/localize the visible RunningHub "RunningHub AI生成" mark (top-left; localize -> fill)."""
def __init__(self) -> None:
super().__init__(_CONFIG)
# Anchor window for the match position, as a fraction of the FRAME: the true
# mark hugs the corner (measured x 0.008-0.014, y 0.005-0.007 of the frame on
# every cohort positive), while the full-corpus false fires (hair, shelves,
# window frames, CJK banners -- 37 of 42009 outside-cohort frames at the 0.34
# gate, 2026-07-22 sweep) match off-anchor at x 0.013-0.150 / y 0.009-0.045.
# No NCC gate separates them (false max 0.384 vs two positives at 0.381), but
# position does: every false fire sits outside this window, every positive
# inside. Contrast-dependent raw-gray NCC keys on "some text-like structure
# anywhere in the box"; the anchor is what makes it about THIS mark.
_ANCHOR_MAX_X = 0.025
_ANCHOR_MAX_Y = 0.015
def detect(self, image: NDArray[Any], *, provenance: bool = False) -> TextMarkDetection:
det = super().detect(image, provenance=provenance)
if not det.detected:
return det
loc = self.locate(image)
_, box = self._gray_best(image, loc)
if box is None:
det.detected = False
return det
h, w = image.shape[:2]
ax = (loc.x + box[0]) / w
ay = (loc.y + box[1]) / h
if ax > self._ANCHOR_MAX_X or ay > self._ANCHOR_MAX_Y:
logger.debug(
"RunningHub detect: score %.3f but match off-anchor (x=%.3f y=%.3f); demoting.",
det.confidence,
ax,
ay,
)
det.detected = False
return det
def load_image_bgr(path: str | Path) -> NDArray[Any]:
"""Read an image as BGR ndarray (helper for scripts/tests)."""
from remove_ai_watermarks import image_io
img = image_io.imread(path)
if img is None:
raise FileNotFoundError(f"Failed to read image: {path}")
return img
+2 -2
View File
@@ -92,9 +92,9 @@ def _glyph_silhouette() -> NDArray[Any] | None:
return _text_mark_engine.glyph_silhouette(_CONFIG.asset_name)
def _template_match_score(box_mask: NDArray[Any], image_width: int) -> float:
def _template_match_score(box_mask: NDArray[Any], scale_base: int) -> float:
"""TM_CCOEFF_NORMED of the Samsung glyph silhouette against ``box_mask``."""
return _text_mark_engine.template_match_score(box_mask, image_width, _CONFIG)
return _text_mark_engine.template_match_score(box_mask, scale_base, _CONFIG)
class SamsungEngine(TextMarkEngine):
+179 -52
View File
@@ -20,8 +20,13 @@ Entries:
- ``gemini`` -- Google Gemini / Nano Banana sparkle, bottom-right.
- ``doubao`` -- ByteDance Doubao "豆包AI生成" text strip, bottom-right.
- ``jimeng`` -- ByteDance Jimeng / Dreamina "★ 即梦AI" wordmark, bottom-right.
- ``qwen`` -- Alibaba Tongyi Qianwen "千问AI生成" text strip, bottom-right.
- ``kling`` -- Kuaishou Kling "可灵AI 3.0" text strip, bottom-right.
- ``samsung`` -- Samsung Galaxy AI "Contenuti generati dall'AI" strip, bottom-left.
- ``jimeng_pill`` -- Jimeng-basic "AI生成" pill, top-left (capture-less).
- ``runninghub`` -- RunningHub "RunningHub AI生成" text, top-left (gray front-end).
- ``baidu`` -- Baidu "百度 AI生成" text + white tag, bottom-right.
- ``liblib`` -- LibLibAI "LibLibAI" wordmark, bottom-center.
"""
from __future__ import annotations
@@ -50,15 +55,28 @@ Backend = Literal["auto", "cv2", "migan", "lama"]
# a clean corner). Lowest recall on faint/moved marks.
# * ``auto`` (default): relax a mark's gate ONLY when the image carries same-product
# evidence the mark is there -- metadata provenance for that vendor, or a confidently
# detected sibling mark of the same product (see ``resolve_relax``). No evidence ->
# detected sibling mark of the same product (see ``resolve_trust``). No evidence ->
# stays strict. Safe: it only escalates where the mark is corroborated.
# * ``assume_ai``: relax every mark's gate regardless of evidence -- the caller asserts
# the image is AI and wants the mark gone (e.g. a metadata-stripped screenshot uploaded
# to a watermark remover). Recovers the faint/moved marks the strict gate demotes
# (~49% -> ~89% Gemini recall, corpus-measured), at the cost of a harmless small fill
# on some clean corners. The library CANNOT infer this from a stripped image -- only the
# caller's out-of-band context (the user uploaded to remove a mark) justifies it.
Sensitivity = Literal["auto", "strict", "assume_ai"]
#
# REMOVED 2026-07-19: ``assume_ai`` relaxed every mark's gate on the caller's bare
# assertion that the image is AI. It was a statistical gamble, not an instruction:
# "this image is AI" says nothing about WHICH vendor or WHERE, which is exactly what a
# gate bypass needs, so it took a confidence floor to be tolerable at all (before that
# floor it filled a phantom sparkle on 59.8% of genuine camera photos). It also had no
# place in the product's own model -- detector finds a mark, remove it; detector finds
# nothing, leave the image alone; the USER sees a mark and says so, act on that. A user
# who can see the mark is better served by pointing at it (``erase --region``) or naming
# it (``--mark X --no-detect`` for a text mark), both of which execute an instruction
# instead of guessing. Removing it also collapsed the trust ladder from three levels to
# two. See docs/module-internals.md for the measurements.
Sensitivity = Literal["auto", "strict"]
# The trust level a mark's detection gate is resolved to (see ``resolve_trust``).
# ``confirmed`` bypasses the engine's false-positive gate, and that bypass is documented
# to require evidence naming THIS vendor (see GeminiEngine.detect_watermark's
# ``trust_provenance`` contract) -- so it is only ever reached from same-product evidence.
# A third ``assumed`` level existed for ``assume_ai`` and went with it (2026-07-19).
Trust = Literal["strict", "confirmed"]
# Product family per mark, for the ``auto`` cross-mark corroboration: a confidently
# detected mark relaxes only OTHER marks of the SAME product (different corners, one
@@ -70,10 +88,41 @@ _PRODUCT_OF: dict[str, str] = {
"doubao": "doubao",
"jimeng": "jimeng",
"jimeng_pill": "jimeng", # same product as the Jimeng wordmark
"qwen": "qwen",
"kling": "kling",
"samsung": "samsung",
"runninghub": "runninghub",
"baidu": "baidu",
"liblib": "liblib",
}
# Marks whose own detection is too weak to serve as EVIDENCE for a sibling of the
# same product, even though they share one. Sibling corroboration grants ``confirmed``
# trust, which bypasses the sibling's false-positive gate outright -- so a detector
# that false-fires often must not be able to hand that bypass to anyone.
#
# The pill qualifies on its own documented numbers: ~7% raw false-fire (5.5% measured
# on 578 vendor negatives, 2026-07-18). Letting it corroborate produced a closed loop
# on the DEFAULT auto path, no user flag involved:
# pill false-fires on a clean non-ByteDance image
# -> _PRODUCT_OF maps it to "jimeng", so jimeng resolves to `confirmed`
# -> jimeng's NCC gate drops 0.45 -> 0.3825 and it false-fires too
# -> _keep_pill now sees "jimeng" in keys and takes the WORDMARK arm, which
# removes the pill unrestricted -- skipping the flatness guard that exists
# precisely to stop the fill smearing a textured corner.
# Measured on the corpus: 3 of 578 negatives ran the full loop, one of them with
# footprint_flat=0 (the exact case the guard was written to block). Cutting the pill
# out of corroboration removed all 3 and cost NOTHING on 4417 TC260 carriers
# (jimeng fires 398 -> 398), so this is a defect fix, not a recall trade.
#
# `_keep_pill` already encodes the same distrust for the pill's own ACTION; this
# closes the gap that its TESTIMONY was never gated.
# Regression: tests/test_watermark_registry.py::TestArbiter::
# test_weak_pill_detection_does_not_confirm_the_jimeng_wordmark
_CANNOT_CORROBORATE: frozenset[str] = frozenset({"jimeng_pill"})
@dataclass(frozen=True)
class MarkDetection:
"""Uniform detection result for a known mark (across heterogeneous engines)."""
@@ -101,6 +150,32 @@ class Localization:
mask: NDArray[Any] | None
_REMOVED_SENSITIVITIES = {
"assume_ai": (
"sensitivity='assume_ai' was removed in 0.16: it relaxed EVERY mark's detection "
"gate on the bare assertion that an image is AI, which says nothing about which "
"vendor made it or where the mark is. If you can see a mark the detector missed, "
"act on what you see: erase(image, region=(x, y, w, h)), or the CLI "
"`--mark <name> --no-detect` for a known text mark. Use sensitivity='auto' for "
"the default evidence-driven behaviour."
)
}
def validate_sensitivity(value: str) -> Sensitivity:
"""Reject a removed sensitivity LOUDLY instead of silently falling back to ``auto``.
``Sensitivity`` is a ``Literal``, which is not enforced at runtime, so a caller
upgrading from 0.15 would pass ``"assume_ai"`` and quietly get ``auto`` behaviour --
a silent semantic change on the one release where they most need to be told.
"""
if value in _REMOVED_SENSITIVITIES:
raise ValueError(_REMOVED_SENSITIVITIES[value])
if value not in ("auto", "strict"):
raise ValueError(f"unknown sensitivity {value!r}; expected 'auto' or 'strict'")
return value # type: ignore[return-value]
@dataclass(frozen=True)
class Context:
"""The evidence + policy the removal arbiter decides against (perception is
@@ -112,6 +187,9 @@ class Context:
sensitivity: Sensitivity = "auto"
provenance: frozenset[str] = frozenset()
def __post_init__(self) -> None:
validate_sensitivity(self.sensitivity)
@dataclass(frozen=True)
class Candidate:
@@ -119,7 +197,8 @@ class Candidate:
Carries the mark's verdict at BOTH trust levels (``detected_strict`` = the
conservative gate, ``detected_relaxed`` = the gate the engine relaxes to under
provenance/assume), so the arbiter can pick per mark without re-running detection.
provenance), so the arbiter can pick per mark without re-running detection.
``features`` is a generic bag of physical measurements a mark's gate may need (the
mark owns which it reports via ``KnownMark._features``); e.g. the pill supplies
``footprint_flat`` (0/1). Empty for marks whose gate needs no extra evidence."""
@@ -229,16 +308,41 @@ GEMINI_SPARKLE_TRUST_CONF = 0.5
_GEMINI_AUTO_MIN_CONF = GEMINI_SPARKLE_TRUST_CONF
# Provenance-confirmed Gemini trust gate. When external metadata already proves the
# image is a Google generation (C2PA issuer "Google"/"Gemini"), the [0.35, 0.5)
# band that the no-provenance gate leaves out is no longer ambiguous with Doubao
# text: a Doubao image carries ByteDance provenance, not Google, so it never reaches
# this relaxed gate. The vendor moving/re-rendering the sparkle (bigger, lighter,
# shifted north-west) drops a real sparkle into this band, and the fixed-slot
# detector demotes it -- provenance is exactly the extra evidence that lets us trust
# it. Set to the engine's own internal `detected` floor (0.35); combined with the
# engine's FP-gate being skipped under provenance (see gemini_engine), this recovers
# the moved-mark misses without touching the no-provenance precision.
_GEMINI_PROVENANCE_MIN_CONF = 0.35
# image is a Google generation (C2PA issuer "Google"/"Gemini"), the [gate, 0.5) band
# that the no-provenance gate leaves out is no longer ambiguous with Doubao text: a
# Doubao image carries ByteDance provenance, not Google, so it never reaches this
# relaxed gate. The vendor moving/re-rendering the sparkle (bigger, lighter, shifted
# north-west) drops a real sparkle into this band, and the fixed-slot detector demotes
# it -- provenance is exactly the extra evidence that lets us trust it.
#
# The gate was originally the engine's own `detected` floor (0.35). Raised to 0.42
# on 2026-07-18 after measuring what this arm actually admits, because the Doubao
# argument above -- while correct -- is not the binding constraint. Google C2PA is
# carried by Imagen, API generations and NotebookLM exports, none of which stamp a
# visible sparkle at all, so the relaxed gate spends most of its budget on images
# that never had a mark rather than on moved ones.
#
# Measured blind on 954 unique Google-metadata uploads (detector never saw the
# metadata), hand-labelled against a two-sided control (labeller sensitivity ~88%,
# specificity 100%). "Additions" = accepted with provenance but not without:
#
# band precision 95% CI population
# 0.35-0.42 13% 5-30% 120
# 0.42-0.46 35% 19-54% 47
# 0.46-0.50 27% 14-46% 44
# 0.50-0.54 40% 20-64% 15
#
# Precision is flat above 0.42 and collapses below it, and that bottom band alone is
# half the arm's volume -- so this is a step, not a gradient, and 0.42 is where it
# sits. Raising the gate here drops ~16 genuine recoveries to prevent ~104 false
# fills (6.5:1), cutting false fills from 18.7% to 7.8% of Google-metadata uploads.
# A false fill is the worse error: it destroys pixels AND makes the caller report a
# removal that did not happen, while a miss leaves the image untouched.
#
# NOTE: even at 0.42 this arm runs at ~33% precision (two false fills per genuine
# recovery). Whether an arm that inaccurate should exist at all is a product call,
# not a tuning one -- do not read this constant as "now correct".
_GEMINI_PROVENANCE_MIN_CONF = 0.42
# ── Engine adapters (lazy singletons; engines are cv2-only, no model load) ──
@@ -259,6 +363,14 @@ def _engine(key: str) -> Any:
from remove_ai_watermarks.jimeng_engine import JimengEngine
_engines[key] = JimengEngine()
elif key == "qwen":
from remove_ai_watermarks.qwen_engine import QwenEngine
_engines[key] = QwenEngine()
elif key == "kling":
from remove_ai_watermarks.kling_engine import KlingEngine
_engines[key] = KlingEngine()
elif key == "samsung":
from remove_ai_watermarks.samsung_engine import SamsungEngine
@@ -267,6 +379,18 @@ def _engine(key: str) -> Any:
from remove_ai_watermarks.pill_engine import PillEngine
_engines[key] = PillEngine()
elif key == "runninghub":
from remove_ai_watermarks.runninghub_engine import RunningHubEngine
_engines[key] = RunningHubEngine()
elif key == "baidu":
from remove_ai_watermarks.baidu_engine import BaiduEngine
_engines[key] = BaiduEngine()
elif key == "liblib":
from remove_ai_watermarks.liblib_engine import LibLibEngine
_engines[key] = LibLibEngine()
else: # pragma: no cover - guarded by the registry keys
raise KeyError(key)
return _engines[key]
@@ -400,7 +524,7 @@ def _pill_mask(
def _pill_features(image: NDArray[Any]) -> dict[str, float]:
"""The pill's own gate feature: top-left footprint flatness (1.0 = flat enough for
an invisible fill), read by the metadata/assume arm of :func:`_keep_pill`."""
an invisible fill), read by the metadata arm of :func:`_keep_pill`."""
return {"footprint_flat": float(_engine("jimeng_pill").footprint_is_flat(image))}
@@ -408,7 +532,12 @@ _REGISTRY: tuple[KnownMark, ...] = (
KnownMark("gemini", "Google Gemini sparkle", "bottom-right", True, _gemini_detect, _gemini_mask),
_text_mark("doubao", "Doubao 豆包AI生成 text", "bottom-right"),
_text_mark("jimeng", "Jimeng 即梦AI wordmark", "bottom-right"),
_text_mark("qwen", "Qwen 千问AI生成 text", "bottom-right"),
_text_mark("kling", "Kling 可灵AI 3.0 text", "bottom-right"),
_text_mark("samsung", "Samsung Galaxy AI text", "bottom-left"),
_text_mark("runninghub", "RunningHub AI生成 text", "top-left"),
_text_mark("baidu", "Baidu 百度 AI生成 text", "bottom-right"),
_text_mark("liblib", "LibLibAI wordmark", "bottom-center"),
KnownMark("jimeng_pill", "Jimeng AI生成 pill", "top-left", True, _pill_detect, _pill_mask, _pill_features),
)
@@ -446,31 +575,32 @@ def detect_marks(
return [m.detect(image, provenance=m.key in provenance) for m in _REGISTRY if include_explicit or m.in_auto]
def resolve_relax(
def resolve_trust(
key: str,
*,
sensitivity: Sensitivity,
provenance: frozenset[str],
strict_keys: set[str],
) -> bool:
"""Whether mark ``key``'s detection gate is relaxed (strict -> assume level).
) -> Trust:
"""The trust level mark ``key``'s detection gate is resolved to.
The single place that turns the ``sensitivity`` policy + evidence into a per-mark
boolean (which the engines consume): ``strict`` never relaxes, ``assume_ai`` always
relaxes, and ``auto`` relaxes only on same-product evidence -- the vendor confirmed
by metadata (``key in provenance``) or a confidently strict-detected sibling of the
same product (``_PRODUCT_OF``)."""
level (which the engines consume as ``provenance = level != "strict"``). ``strict``
never relaxes. A mark is ``confirmed`` only on same-product evidence -- the vendor
confirmed by metadata (``key in provenance``) or a confidently strict-detected
sibling of the same product (``_PRODUCT_OF``, minus the marks too weak to vouch,
:data:`_CANNOT_CORROBORATE`). Without that evidence a mark stays ``strict``: there is
no path that relaxes a gate on anything less than same-product evidence."""
if sensitivity == "strict":
return False
if sensitivity == "assume_ai":
return True
if key in provenance:
return True
return "strict"
product = _PRODUCT_OF[key]
return any(_PRODUCT_OF[k] == product for k in strict_keys if k != key)
confirmed = key in provenance or any(
_PRODUCT_OF[k] == product for k in strict_keys if k != key and k not in _CANNOT_CORROBORATE
)
return "confirmed" if confirmed else "strict"
def _keep_pill(keys: set[str], *, provenance: frozenset[str], sensitivity: Sensitivity, footprint_flat: bool) -> bool:
def _keep_pill(keys: set[str], *, provenance: frozenset[str], footprint_flat: bool) -> bool:
"""Whether to auto-remove the capture-less 'AI生成' pill given the fired marks.
Pure decision (the flatness feature is precomputed at perception time and passed
@@ -480,19 +610,19 @@ def _keep_pill(keys: set[str], *, provenance: frozenset[str], sensitivity: Sensi
its false fires were textured ceilings/walls that the fill visibly SMEARS. Arms:
* bottom-right "★ 即梦AI" wordmark fired -> ~94% precise, and it survives
metadata-STRIPPED uploads: remove the pill unrestricted;
* TC260 metadata confirms Jimeng (``"jimeng" in provenance``, no wordmark) OR the
caller asserts AI (``sensitivity == "assume_ai"``) -> remove ONLY when the
* TC260 metadata confirms Jimeng (``"jimeng" in provenance``, no wordmark) -> remove ONLY when the
top-left footprint is flat enough for an invisible fill (``footprint_flat``),
so real flat-scene pills (and harmless flat false fires) are cleaned while the
damaging textured false fires are left untouched even under assume_ai.
damaging textured false fires are left untouched.
A Doubao image is TC260 too but is not Jimeng-basic, so the pill never rides on a
Doubao detection. No confirmation at all -> never remove (blocks false fires on
non-Jimeng content)."""
if "doubao" in keys:
Doubao detection; a Qwen image likewise (another vendor's bottom-right mark naming
its own product), so a confident Qwen detection suppresses the pill the same way.
No confirmation at all -> never remove (blocks false fires on non-Jimeng content)."""
if "doubao" in keys or "qwen" in keys or "kling" in keys or "runninghub" in keys or "baidu" in keys:
return False
if "jimeng" in keys:
return True
if "jimeng" in provenance or sensitivity == "assume_ai":
if "jimeng" in provenance:
return footprint_flat
return False
@@ -523,28 +653,25 @@ def decide(candidates: list[Candidate], context: Context) -> list[Decision]:
"""The removal ARBITER: a pure function turning perception + context into the
ordered list of marks to remove (and the trust level each was accepted at).
All policy lives here, in one place: per-mark relaxation (:func:`resolve_relax`,
All policy lives here, in one place: per-mark trust resolution (:func:`resolve_trust`,
which needs the strict-detected siblings for ``auto`` cross-mark corroboration) and
the capture-less pill gate (:func:`_keep_pill`). No image, no I/O -- so it is
unit-testable in isolation and the same decision drives every caller."""
the capture-less pill gate (:func:`_keep_pill`). No image, no I/O -- so it is unit-testable in isolation and
the same decision drives every caller."""
strict_keys = {c.key for c in candidates if c.detected_strict}
fired: list[Decision] = []
for c in candidates:
relax = resolve_relax(
trust = resolve_trust(
c.key, sensitivity=context.sensitivity, provenance=context.provenance, strict_keys=strict_keys
)
if c.detected_relaxed if relax else c.detected_strict:
relax = trust != "strict"
ok = c.detected_relaxed if relax else c.detected_strict
if ok:
fired.append(Decision(c, relax))
keys = {d.candidate.key for d in fired}
if "jimeng_pill" in keys:
pill = next(d for d in fired if d.candidate.key == "jimeng_pill")
flat = bool(pill.candidate.features.get("footprint_flat", 0.0))
if not _keep_pill(
keys,
provenance=context.provenance,
sensitivity=context.sensitivity,
footprint_flat=flat,
):
if not _keep_pill(keys, provenance=context.provenance, footprint_flat=flat):
fired = [d for d in fired if d.candidate.key != "jimeng_pill"]
return fired
+19 -1
View File
@@ -49,7 +49,7 @@ class TestRemoveVisibleArray:
def test_array_accepts_knobs(self):
arr = np.zeros((256, 256, 3), np.uint8)
result, removed = raiw.remove_visible(arr, sensitivity="assume_ai", backend="cv2")
result, removed = raiw.remove_visible(arr, sensitivity="strict", backend="cv2")
assert removed == []
assert result.shape == arr.shape
@@ -104,6 +104,24 @@ class TestVisibleProvenance:
def test_unreadable_path_is_empty(self, tmp_path):
assert raiw.visible_provenance(tmp_path / "missing.png") == frozenset()
def test_uses_report_signals_for_falsy_metadata_values(self, monkeypatch, tmp_path):
"""An empty TC260 object and Samsung genAIType=0 are still present signals.
The report has already normalized those values, so the public API must not
re-read the file and accidentally discard them by truthiness.
"""
from types import SimpleNamespace
from remove_ai_watermarks import identify
report = SimpleNamespace(
platform=None,
signals=[SimpleNamespace(name="aigc"), SimpleNamespace(name="samsung_genai")],
)
monkeypatch.setattr(identify, "identify", lambda *args, **kwargs: report)
assert raiw.visible_provenance(tmp_path / "synthetic.png") == frozenset({"doubao", "jimeng", "samsung"})
class TestRemoveVisibleOutputPath:
"""Output-path robustness: in-place clean (#3) and a missing output dir (#4)."""
+133
View File
@@ -0,0 +1,133 @@
"""Tests for the Baidu ("百度 AI生成") visible-watermark engine.
Every tuned constant in ``baidu_engine`` was measured on the 16-frame vendor
cohort (2026-07-22); these tests pin the load-bearing ones: detection keys on
the 百度 text run ONLY (the text+pill template was a measured bright-blob
magnet), the load-bearing Doubao rival margin, the strict-only gate, and the
corner-extended footprint (the tag's flat white interior gives no top-hat
response, so a blob-bbox mask leaves the tag as a ghost).
"""
from __future__ import annotations
import cv2
import numpy as np
from remove_ai_watermarks import watermark_registry as registry
from remove_ai_watermarks.baidu_engine import (
_ALPHA_HEIGHT_FRAC,
_ALPHA_WIDTH_FRAC,
BaiduEngine,
_alpha_template,
)
_TEXT_FRAC = 0.090 # measured 百度 text-run width, fraction of the short side
_TEXT_RIGHT = 0.099 # measured right margin of the text run (the tag is right of it)
_TAG_FRAC = 0.075 # the white tag's width, approx (text-right to corner)
def _compose(w: int, h: int, bg: float = 100.0):
"""Composite the 百度 text run + a solid white tag at the measured layout."""
img = np.full((h, w, 3), bg, np.float32)
at = _alpha_template()
short = min(w, h)
gw = int(_TEXT_FRAC * short)
gh = max(4, int(_TEXT_FRAC * (_ALPHA_HEIGHT_FRAC / _ALPHA_WIDTH_FRAC) * short))
margin_b = int(0.006 * short)
ax = w - int(_TEXT_RIGHT * short) - gw
ay = h - margin_b - gh
amap = np.zeros((h, w), np.float32)
amap[ay : ay + gh, ax : ax + gw] = cv2.resize(at, (gw, gh))
# the white rounded tag between the text and the corner
tx0 = w - int(0.015 * short) - int(_TAG_FRAC * short)
amap[ay - gh // 8 : ay + gh + gh // 8, tx0 : w - int(0.015 * short)] = 1.0
a3 = amap[:, :, None]
wm = (a3 * 255.0 + (1 - a3) * img).clip(0, 255).astype(np.uint8)
return wm, (ax, ay, gw, gh, tx0)
class TestLocate:
def test_box_anchored_bottom_right(self):
eng = BaiduEngine()
img = np.zeros((2048, 2048, 3), np.uint8)
loc = eng.locate(img)
assert 2048 - (loc.x + loc.w) < 40
assert 2048 - (loc.y + loc.h) < 40
def test_box_scales_with_short_side(self):
eng = BaiduEngine()
landscape = eng.locate(np.zeros((640, 1280, 3), np.uint8))
wider = eng.locate(np.zeros((640, 2560, 3), np.uint8))
assert wider.w == landscape.w
class TestConfig:
def test_tophat_frontend(self):
assert BaiduEngine().config.detect_frontend == "tophat"
def test_doubao_rival_margin(self):
# 百度 vs 豆包 share a glyph and a corner: the candidate fires on 45.8% of
# Doubao-marked frames at the gate, and the 0.10 margin suppresses ALL of
# it at zero genuine-detection cost (crossfire, 2026-07-22).
assert "doubao_alpha.png" in BaiduEngine().config.rivals
def test_strict_only_no_provenance_relaxation(self):
assert BaiduEngine().config.provenance_ncc_factor == 1.0
def test_gate_above_clean_arm_max(self):
# Clean arm scored p99 0.314 / max 0.352 on 278 hand-labelled frames;
# the 741-frame eval set surfaced cross-fires up to 0.426 (a 抖音
# AI创作 mark no rival can suppress), and the full-corpus sweep put the
# outside-cohort false arm at 0.47 max vs true carriers at 0.50-0.66,
# so the gate sits at 0.48.
assert BaiduEngine().config.detect_ncc_threshold >= 0.48
def test_qwen_is_a_rival(self):
# 百度 vs 千问 are near-identical after binarization: 12 of 14 full-corpus
# cross-fires at the 0.37 gate were Qwen marks (Qwen's template beats
# Baidu's there by 0.17-0.35, so the margin suppresses them).
assert "qwen_alpha.png" in BaiduEngine().config.rivals
def test_registry_row(self):
mark = registry.get_mark("baidu")
assert mark.location == "bottom-right"
assert mark.in_auto
class TestDetectAndMask:
def test_detects_composed_mark(self):
eng = BaiduEngine()
wm, _ = _compose(1024, 1024)
det = eng.detect(wm)
assert det.detected, f"composed mark missed (conf={det.confidence:.3f})"
def test_clean_frame_stays_quiet(self):
eng = BaiduEngine()
img = np.full((1024, 1024, 3), 100, np.uint8)
assert not eng.detect(img).detected
def test_mask_extends_to_the_corner_tag(self):
"""Regression (2026-07-22): the tag's flat white interior gives no top-hat
response, so a blob-bbox mask ended at the text run and the fill left the
tag as a ghost. The footprint must extend right to the corner."""
eng = BaiduEngine()
wm, (ax, _ay, gw, _gh, tx0) = _compose(1024, 1024)
mask = eng.footprint_mask(wm)
assert mask is not None
_ys, xs = np.where(mask > 0)
assert xs.min() <= ax + int(0.1 * gw) # covers the text run's left edge
assert xs.max() >= tx0 + 10 # covers the white tag right of the text
def test_no_mask_on_clean_frame(self):
eng = BaiduEngine()
img = np.full((1024, 1024, 3), 100, np.uint8)
assert eng.footprint_mask(img) is None
class TestPillInteraction:
def test_confident_baidu_detection_suppresses_the_jimeng_pill(self):
# A Baidu image is TC260 too but is not Jimeng-basic: like Doubao/Qwen/
# Kling, a confident Baidu detection must veto the pill (``_keep_pill``).
from remove_ai_watermarks.watermark_registry import _keep_pill
assert not _keep_pill({"baidu"}, provenance=frozenset({"jimeng"}), footprint_flat=1.0)
+39 -7
View File
@@ -573,6 +573,31 @@ class TestMetadataCommand:
assert result.exit_code == 0
assert "stripped" in result.output
def test_metadata_remove_reports_failure_when_the_strip_was_a_no_op(self, runner, tmp_path):
"""A file PIL cannot decode is copied through UNCHANGED by the fail-safe.
That is correct (never crash a worker on a partial upload) but the command used
to print "AI metadata stripped ->" and exit 0 for it, so a caller could not tell
a real strip from a no-op and the output still read as AI. Found on real Samsung
Galaxy S22 C2PA PNGs during the corpus parity audit, 2026-07-19.
"""
# PNG signature + a C2PA (caBX) chunk, then garbage: the byte scanner sees the
# marker, PIL cannot decode it.
src = tmp_path / "undecodable.png"
payload = b"c2pa" + b"\x00" * 32
chunk = len(payload).to_bytes(4, "big") + b"caBX" + payload + b"\x00\x00\x00\x00"
src.write_bytes(b"\x89PNG\r\n\x1a\n" + chunk + b"NOTAPNG" * 8)
out = tmp_path / "cleaned.png"
result = runner.invoke(main, ["metadata", str(src), "--remove", "-o", str(out)])
from remove_ai_watermarks.metadata import get_ai_metadata
if not get_ai_metadata(src):
pytest.skip("fixture does not register as an AI-metadata carrier")
assert result.exit_code != 0, "a no-op strip must not report success"
assert "stripped ->" not in result.output
def test_metadata_remove_in_place(self, runner, tmp_png_with_ai_metadata):
"""With ``-o`` omitted, the strip overwrites the source in place (default
output_path=None). Previously every test passed an explicit ``-o``."""
@@ -949,14 +974,21 @@ def test_visible_backend_runtime_error_exits_cleanly(runner, tmp_path, monkeypat
)
@pytest.mark.parametrize("cmd", [["metadata", "--remove"], ["visible", "--backend", "cv2"]])
def test_unreadable_input_exits_cleanly(runner, tmp_path, name, content, cmd):
"""Regression: a corrupt / empty / non-image file (real prod uploads include
truncated files) must produce a clean 'Error: cannot read/process' + exit 1, NOT a
raw PIL.UnidentifiedImageError / OSError / ValueError traceback. Found by the runtime
mode fuzz across metadata --remove and visible."""
"""Regression: a corrupt / empty / non-image file (real prod uploads include ~0.2%
truncated files) must NEVER leak a raw PIL/OSError/ValueError traceback. `metadata
--remove` is fail-safe -- an undecodable file is copied through unchanged (exit 0),
a strip that cannot parse the file is a no-op, not a crash; `visible` must decode to
remove a mark, so it is a clean error (exit 1). Found by the runtime mode fuzz."""
bad = tmp_path / name
bad.write_bytes(content)
out = tmp_path / "out.png"
result = runner.invoke(main, [cmd[0], str(bad), "-o", str(out), *cmd[1:]])
assert result.exit_code == 1, result.output
assert isinstance(result.exception, SystemExit), f"leaked a raw traceback: {result.exception!r}"
assert "Error" in result.output
assert result.exception is None or isinstance(result.exception, SystemExit), (
f"leaked a raw traceback: {result.exception!r}"
)
if cmd[0] == "metadata":
assert result.exit_code == 0, result.output # fail-safe copy-through
assert out.read_bytes() == content # input passed through unchanged
else:
assert result.exit_code == 1, result.output # cannot remove a mark from unreadable input
assert "Error" in result.output
+114
View File
@@ -0,0 +1,114 @@
"""A failed write and a directory input must REPORT, not raise a traceback.
Both found 2026-07-20 by the Tier E adversarial sweep (`scripts/robustness_suite.py`),
which drives the real CLI over degenerate inputs. Neither was reachable from the 849-test
suite, because unit tests feed well-formed fixtures into writable directories.
1. READ-ONLY OUTPUT DIRECTORY. `image_io.imwrite` is contractually non-raising -- it
returns False when the codec rejects the image or the path cannot be written. But
`write_bgr_with_alpha` discarded that bool and returned None, so no caller could tell a
failed write from a successful one. `cmd_erase` then ran `output.stat()` on a file that
was never created and died with `FileNotFoundError`. The signal existed the whole way
down and was thrown away by the wrapper.
2. A DIRECTORY PASSED WHERE A FILE IS EXPECTED. `click.Path(exists=True)` accepts
directories unless told otherwise, so `identify <dir>` reached the metadata scanner and
raised `IsADirectoryError` from `open()`. (`batch` was already correct: it declares
`file_okay=False`.)
"""
from __future__ import annotations
import numpy as np
import pytest
from click.testing import CliRunner
from remove_ai_watermarks import image_io
from remove_ai_watermarks.cli import main
@pytest.fixture
def bgr() -> np.ndarray:
return np.full((60, 80, 3), 128, np.uint8)
class TestFailedWriteIsReported:
def test_write_bgr_with_alpha_reports_failure(self, tmp_path, bgr):
"""The wrapper must PROPAGATE imwrite's failure signal, not swallow it.
Uses a nonexistent directory rather than `chmod`: CI runs windows-latest, where
`os.chmod` cannot make a DIRECTORY unwritable, so a chmod-based assertion would be
a platform-dependent flake. `write_bgr_with_alpha` does no mkdir of its own, so a
missing parent is a genuine write failure on every platform.
"""
assert image_io.write_bgr_with_alpha(tmp_path / "no-such-dir" / "x.png", bgr, None) is False
def test_write_bgr_with_alpha_reports_success(self, tmp_path, bgr):
"""The other direction, so the assertion above cannot pass by always being False."""
assert image_io.write_bgr_with_alpha(tmp_path / "ok.png", bgr, None) is True
def test_erase_reports_a_failed_write_without_a_traceback(self, tmp_path, bgr, monkeypatch):
"""The CLI must exit non-zero with a readable message, not raise FileNotFoundError.
The write is forced to fail by patching, not by `chmod`: the CLI mkdirs the parent,
so a missing directory would not reproduce it, and chmod on a directory is a no-op
on Windows. Patching states the condition under test directly -- "the write failed".
"""
src = tmp_path / "in.png"
image_io.imwrite(src, bgr)
monkeypatch.setattr(image_io, "write_bgr_with_alpha", lambda *a, **k: False)
result = CliRunner().invoke(main, ["erase", str(src), "--region", "5,5,20,10", "-o", str(tmp_path / "x.png")])
assert result.exit_code != 0
assert not isinstance(result.exception, FileNotFoundError), "write failure escaped as a traceback"
assert "write" in result.output.lower() or "failed" in result.output.lower()
def test_batch_counts_a_failed_write_instead_of_exiting_zero(self, tmp_path, bgr, monkeypatch):
"""The worst shape of this bug: no output files AND a success exit code.
Corpus-reproduced 2026-07-20 -- `batch --mode visible` into a read-only directory
wrote ZERO files for 2 inputs and exited 0, so a wrapping service would treat an
empty output directory as a completed run. The batch loop counts per-image
exceptions, so the write must RAISE there, never `SystemExit` (which would abort
the whole run instead of failing one image).
"""
indir = tmp_path / "in"
indir.mkdir()
for i in range(2):
image_io.imwrite(indir / f"img{i}.png", bgr)
monkeypatch.setattr(image_io, "write_bgr_with_alpha", lambda *a, **k: False)
result = CliRunner().invoke(main, ["batch", str(indir), "-o", str(tmp_path / "out"), "--mode", "visible"])
assert result.exit_code != 0, "a batch that wrote nothing must not exit 0"
class TestApiReportsFailedWrite:
"""The same bug lived one layer down, in the library API, with a misleading message.
`api._write_visible_result` also discarded the write flag, then ran the metadata strip
on a file that was never created. The resulting `FileNotFoundError` surfaced through
the CLI as `cannot read image <INPUT>: ... <OUTPUT path>` -- it blamed the input while
quoting the output. A library caller got the same confusing error with no CLI at all.
"""
def test_remove_visible_raises_a_clear_error_on_unwritable_output(self, tmp_path, bgr, monkeypatch):
"""Patched rather than chmod'd: `_write_visible_result` mkdirs the parent, so a
missing directory would not reproduce it, and chmod on a directory is a no-op on
the Windows CI runner."""
from remove_ai_watermarks.api import remove_visible
monkeypatch.setattr(image_io, "write_bgr_with_alpha", lambda *a, **k: False)
with pytest.raises(OSError, match="failed to write output"):
remove_visible(bgr, tmp_path / "out.png", strip_metadata=False)
class TestDirectoryInputIsRejected:
@pytest.mark.parametrize("cmd", ["identify", "visible", "erase", "metadata", "invisible", "all"])
def test_directory_as_source_is_a_clean_usage_error(self, tmp_path, cmd):
"""A directory must be refused by argument parsing, never reach the scanners."""
args = [cmd, str(tmp_path)]
if cmd == "erase":
args += ["--region", "1,1,5,5"]
if cmd == "metadata":
args += ["--check"]
result = CliRunner().invoke(main, args)
assert result.exit_code != 0
assert not isinstance(result.exception, IsADirectoryError), "directory reached the file reader"
+31
View File
@@ -171,6 +171,23 @@ class TestIdentifyNonPng:
assert r.platform == "ElevenLabs"
assert not any("SynthID" in w for w in r.watermarks) # ElevenLabs does not use SynthID
def test_fal_ai_attributed(self, tmp_path: Path):
# fal.ai signs as "fal - Features & Labels Inc." with a "fal-ai/<model>"
# claim generator; corpus-measured 2026-07-23 (17 files).
path = self._c2pa_jpeg(tmp_path, b"fal - Features & Labels Inc. fal-ai/seedvr trainedAlgorithmicMedia")
r = identify(path, check_visible=False, check_invisible=False)
assert r.is_ai_generated is True
assert r.platform == "fal.ai"
def test_bria_attributed_without_source_type(self, tmp_path: Path):
# Bria signs as "Bria Artificial Intelligence" with source type ``empty``
# (NO trainedAlgorithmicMedia) -- a pure-generator asserts_ai vendor, so
# the issuer/generator strings alone must flag AI. Corpus-found 2026-07-23.
path = self._c2pa_jpeg(tmp_path, b"Bria Artificial Intelligence Bria Ai c2pa.created c2pa.edited")
r = identify(path, check_visible=False, check_invisible=False)
assert r.is_ai_generated is True
assert r.platform == "Bria AI"
def test_stability_ai_issuer_attributed_no_synthid(self, tmp_path: Path):
path = self._c2pa_jpeg(tmp_path, b"Stability AI ... trainedAlgorithmicMedia")
r = identify(path, check_visible=False)
@@ -285,6 +302,20 @@ class TestIdentifyRealSamples:
assert r.is_ai_generated is True
assert any("IPTC" in w for w in r.watermarks)
def test_apple_clean_up_attributed(self, tmp_path: Path):
# Apple Photos Clean Up (Apple Intelligence object removal) marks the
# AI edit via photoshop:Credit next to compositeWithTrainedAlgorithmicMedia
# -- it must be attributed, not reported as a generic made-with-AI tag.
# Corpus-measured 2026-07-23 (35 files).
p = tmp_path / "apple_cleanup.jpg"
p.write_bytes(
b'\xff\xd8\xff\xe1<x:xmpmeta photoshop:Credit="Apple Photos Clean Up" '
b"Iptc4xmpExt:DigitalSourceType=compositeWithTrainedAlgorithmicMedia></x:xmpmeta>\xff\xd9"
)
r = identify(p, check_visible=False, check_invisible=False)
assert r.is_ai_generated is True
assert r.platform == "Apple Photos (Clean Up AI edit)"
def test_flux_bfl_c2pa_png(self):
# flux-1.png: real Black Forest Labs FLUX.2 Playground output (signed C2PA).
r = identify(SAMPLES_DIR / "flux-1.png", check_visible=False)
+149
View File
@@ -0,0 +1,149 @@
"""Tests for the Kling (可灵AI 3.0) visible-watermark engine (localize -> fill).
Every tuned constant in ``kling_engine`` was measured on the 30-frame vendor
cohort (2026-07-21, ``scripts/vendor_mark_calibrate.py``); these tests pin the
load-bearing ones so a later "cleanup" cannot silently re-inherit Doubao's
geometry or relax the measured strict-only gate.
"""
from __future__ import annotations
import cv2
import numpy as np
import pytest
from remove_ai_watermarks import watermark_registry as registry
from remove_ai_watermarks.kling_engine import (
_ALPHA_HEIGHT_FRAC,
_ALPHA_WIDTH_FRAC,
KlingEngine,
_alpha_template,
_glyph_silhouette,
)
_MARK_FRAC = 0.12 # measured mark width, fraction of the short side (unimodal)
_MARGIN = 0.03 # measured right/bottom margin of the real mark
def _compose(w: int, h: int, mode: float = _MARK_FRAC, bg: float = 100.0):
"""Composite the Kling silhouette at the measured size onto a flat bg."""
img = np.full((h, w, 3), bg, np.float32)
at = _alpha_template()
short = min(w, h)
gw = int(mode * short)
gh = max(4, int(mode * (_ALPHA_HEIGHT_FRAC / _ALPHA_WIDTH_FRAC) * short))
margin = int(_MARGIN * short)
ax = w - margin - gw
ay = h - margin - gh
amap = np.zeros((h, w), np.float32)
amap[ay : ay + gh, ax : ax + gw] = cv2.resize(at, (gw, gh))
a3 = amap[:, :, None]
wm = (a3 * 255.0 + (1 - a3) * img).clip(0, 255).astype(np.uint8)
return wm, amap > 0.2
class TestLocate:
def test_box_anchored_bottom_right(self):
eng = KlingEngine()
img = np.zeros((2048, 2048, 3), np.uint8)
loc = eng.locate(img)
assert 2048 - (loc.x + loc.w) == pytest.approx(2048 * 0.03, rel=0.15)
assert 2048 - (loc.y + loc.h) == pytest.approx(2048 * 0.023, rel=0.15)
def test_box_scales_with_short_side_not_width(self):
# scale_basis="short" (measured: mark_w/short 0.118-0.122 across orientations).
eng = KlingEngine()
landscape = eng.locate(np.zeros((640, 1280, 3), np.uint8))
wider = eng.locate(np.zeros((640, 2560, 3), np.uint8))
assert wider.w == landscape.w # same short side -> same box
bigger = eng.locate(np.zeros((1280, 1920, 3), np.uint8)) # 2x the short side
assert bigger.w == pytest.approx(landscape.w * 2, rel=0.05)
class TestConfig:
def test_shared_ladder_default(self):
# The mark is unimodal at 0.12 of the short side, so Kling keeps the shared
# 3-rung ladder (Qwen's per-mark ladder is the measured exception, not a norm).
assert KlingEngine().config.ladder == (0.8, 1.0, 1.25)
def test_strict_only_no_provenance_relaxation(self):
# The sub-gate band (real Kling variants at 0.17-0.25) overlaps the clean
# arm's top (p90 0.220), so a relaxed arm cannot separate: factor pinned 1.0.
assert KlingEngine().config.provenance_ncc_factor == 1.0
def test_gate_above_clean_arm_max(self):
# Clean arm scored p99 0.304 / max 0.320 on 286 hand-labelled frames; the
# gate must sit above that with margin.
assert KlingEngine().config.detect_ncc_threshold > 0.32
def test_registry_row(self):
mark = registry.get_mark("kling")
assert mark.location == "bottom-right"
assert "可灵AI" in mark.label
assert mark.in_auto
def test_confident_kling_detection_suppresses_the_jimeng_pill(self):
# A Kling image is TC260 too but is not Jimeng-basic: like Doubao and Qwen,
# a confident Kling detection must veto the pill (``_keep_pill``).
from remove_ai_watermarks.watermark_registry import _keep_pill
assert not _keep_pill({"kling"}, provenance=frozenset({"jimeng"}), footprint_flat=1.0)
class TestDetect:
def test_clean_gradient_not_detected(self):
eng = KlingEngine()
ramp = np.tile(np.linspace(0, 255, 1024, dtype=np.uint8), (1024, 1))
img = cv2.cvtColor(ramp, cv2.COLOR_GRAY2BGR)
assert not eng.detect(img).detected
def test_solid_blob_corner_not_detected(self):
eng = KlingEngine()
img = np.zeros((1024, 1024, 3), np.uint8)
x, y, bw, bh = eng.locate(img).bbox
img[y + bh // 4 : y + bh * 3 // 4, x : x + bw // 2] = 200
assert not eng.detect(img).detected
def test_silhouette_loads(self):
sil = _glyph_silhouette()
assert sil is not None
assert set(np.unique(sil)).issubset({0, 255})
def test_composed_mark_detected(self):
# The registration's core claim: a mark at the measured size scores over the
# gate. The floor is deliberately far above the gate: the synthetic mark is
# clean, so it scores high when the geometry is right.
wm, _ = _compose(853, 640)
det = KlingEngine().detect(wm)
assert det.detected
assert det.confidence >= 0.80
def test_small_image_guarded(self):
wm, _ = _compose(853, 640)
eng = KlingEngine()
assert eng.detect(wm).detected
assert not eng.detect(cv2.resize(wm, (150, 112))).detected
class TestFootprintMaskAndRemoval:
def test_removes_composed_mark(self):
wm, mark = _compose(853, 640)
assert float(np.abs(wm.astype(np.float32)[mark] - 100.0).mean()) > 15 # mark visible
assert KlingEngine().detect(wm).detected
out, region = registry.get_mark("kling").remove(wm, backend="cv2")
assert region is not None
assert not KlingEngine().detect(out).detected
h, w = wm.shape[:2]
assert np.array_equal(out[: h // 2, : w // 2], wm[: h // 2, : w // 2]) # far region exact
def test_footprint_mask_in_bottom_right(self):
wm, _ = _compose(853, 640)
mask = KlingEngine().footprint_mask(wm)
assert mask is not None
ys, xs = np.where(mask > 0)
assert ys.mean() > wm.shape[0] / 2
assert xs.mean() > wm.shape[1] / 2
def test_clean_frame_produces_no_mask(self):
clean = cv2.GaussianBlur(np.full((640, 853, 3), 120, np.uint8), (5, 5), 0)
assert KlingEngine().footprint_mask(clean, force=False) is None
+114
View File
@@ -0,0 +1,114 @@
"""Tests for the LibLibAI ("LibLibAI" wordmark) visible-watermark engine.
Every tuned constant in ``liblib_engine`` was measured on the 15-frame vendor
cohort (2026-07-22); these tests pin the load-bearing ones: the bottom-CENTER
anchor, the strict-only gate, and the match-box footprint (the blob bbox both
bled into background structure and did not own the triangle logo).
"""
from __future__ import annotations
import cv2
import numpy as np
import pytest
from remove_ai_watermarks import watermark_registry as registry
from remove_ai_watermarks.liblib_engine import (
_ALPHA_HEIGHT_FRAC,
_ALPHA_WIDTH_FRAC,
LibLibEngine,
_alpha_template,
)
_MARK_FRAC = 0.10 # measured wordmark width, fraction of the frame WIDTH
def _compose(w: int, h: int, bg: float = 100.0):
"""Composite a triangle logo + the LibLibAI wordmark, bottom-center."""
img = np.full((h, w, 3), bg, np.float32)
at = _alpha_template()
gw = int(_MARK_FRAC * w)
gh = max(4, int(_MARK_FRAC * (_ALPHA_HEIGHT_FRAC / _ALPHA_WIDTH_FRAC) * w))
ax = (w - gw) // 2
ay = int(0.94 * h) - gh
amap = np.zeros((h, w), np.float32)
amap[ay : ay + gh, ax : ax + gw] = cv2.resize(at, (gw, gh))
# the triangle logo, its own height to the LEFT of the wordmark
lx1 = ax - int(0.3 * gh)
lx0 = lx1 - gh
cv2.fillPoly(amap, [np.array([(lx0, ay + gh), (lx1, ay + gh), (lx1, ay)])], 1.0)
a3 = amap[:, :, None]
wm = (a3 * 255.0 + (1 - a3) * img).clip(0, 255).astype(np.uint8)
return wm, (ax, ay, gw, gh, lx0)
class TestLocate:
def test_box_horizontally_centered(self):
eng = LibLibEngine()
img = np.zeros((2048, 1536, 3), np.uint8)
loc = eng.locate(img)
assert (1536 - loc.w) // 2 == pytest.approx(loc.x, abs=2) # corner="bc"
assert 2048 - (loc.y + loc.h) > 0 # bottom-anchored
def test_box_scales_with_width(self):
eng = LibLibEngine()
narrow = eng.locate(np.zeros((2048, 1024, 3), np.uint8))
wide = eng.locate(np.zeros((2048, 2048, 3), np.uint8))
assert wide.w == pytest.approx(narrow.w * 2, rel=0.05)
class TestConfig:
def test_tophat_frontend(self):
assert LibLibEngine().config.detect_frontend == "tophat"
def test_strict_only_no_provenance_relaxation(self):
assert LibLibEngine().config.provenance_ncc_factor == 1.0
def test_gate_above_clean_arm_max(self):
# With the Arial silhouette the full-corpus false arm (latin UI text)
# tops out at 0.398 while the cohort sits at 0.43-0.59; gate 0.42.
assert LibLibEngine().config.detect_ncc_threshold >= 0.42
def test_small_image_size_floor(self):
# The one full-corpus false fire with the final template was a 200x200
# icon on a 20px template; the engine refuses small images outright.
eng = LibLibEngine()
assert not eng.detect(np.full((200, 200, 3), 100, np.uint8)).detected
wm, _ = _compose(200, 200)
assert not eng.detect(wm).detected # even a composed mark under the floor
def test_registry_row(self):
mark = registry.get_mark("liblib")
assert mark.location == "bottom-center"
assert mark.in_auto
class TestDetectAndMask:
def test_detects_composed_mark(self):
eng = LibLibEngine()
wm, _ = _compose(1792, 2400)
det = eng.detect(wm)
assert det.detected, f"composed mark missed (conf={det.confidence:.3f})"
def test_clean_frame_stays_quiet(self):
eng = LibLibEngine()
img = np.full((2400, 1792, 3), 100, np.uint8)
assert not eng.detect(img).detected
def test_mask_covers_logo_and_wordmark(self):
"""The footprint must cover the triangle logo LEFT of the wordmark while
staying bounded by the match box vertically (the blob bbox bled into
background structure and ate real content, 2026-07-22)."""
eng = LibLibEngine()
wm, (ax, ay, gw, gh, lx0) = _compose(1792, 2400)
mask = eng.footprint_mask(wm)
assert mask is not None
ys, xs = np.where(mask > 0)
assert xs.min() <= lx0 + gh // 2 # covers the logo
assert xs.max() >= ax + gw - int(0.05 * gw) # covers the wordmark's right edge
assert ys.min() >= ay - gh # does not bleed far above the mark
def test_no_mask_on_clean_frame(self):
eng = LibLibEngine()
img = np.full((2400, 1792, 3), 100, np.uint8)
assert eng.footprint_mask(img) is None
+120 -3
View File
@@ -179,6 +179,37 @@ class TestHasAiMetadata:
assert np.array_equal(before, after), f"{name}: pixels changed (DCT was re-encoded)"
assert not has_ai_metadata(out), f"{name}: AI metadata survived the strip"
def test_strip_preserves_lossless_content_with_mismatched_extension(self, tmp_path: Path):
"""F1 regression: the save format is chosen by CONTENT, not the file extension.
A PNG served with a .jpg name (common on real uploads -- ~1% of the corpus is a
PNG/WebP under a .jpg extension) must be stripped losslessly as PNG, NOT
re-encoded into a real JPEG. The extension-driven path silently degraded it,
breaking the 'work with originals' invariant."""
import numpy as np
from PIL import Image
from PIL.PngImagePlugin import PngInfo
from remove_ai_watermarks import image_io
from remove_ai_watermarks.metadata import remove_ai_metadata
# Random noise: JPEG (even q95 4:4:4) provably shifts it; PNG stays exact.
arr = np.random.default_rng(0).integers(0, 256, (64, 64, 3), dtype=np.uint8)
info = PngInfo()
info.add_text("parameters", "Stable Diffusion prompt") # an AI-provenance key
src = tmp_path / "actually_png.jpg" # PNG bytes under a .jpg name
Image.fromarray(arr).save(src, format="PNG", pnginfo=info)
assert has_ai_metadata(src)
out = tmp_path / "cleaned.jpg"
remove_ai_metadata(src, out)
before = image_io.imread(str(src))
after = image_io.imread(str(out))
assert before is not None
assert after is not None
assert np.array_equal(before, after), "misnamed PNG was lossily re-encoded to JPEG"
assert not has_ai_metadata(out), "AI metadata survived the strip"
@staticmethod
def _xmp_iptc_jpeg(tmp_path: Path, name: str, marker: bytes) -> Path:
"""A real (decodable) JPEG carrying the IPTC AI marker in a well-formed APP1
@@ -226,6 +257,27 @@ class TestHasAiMetadata:
assert np.array_equal(before, after), "pixels changed: the DCT scan was re-encoded"
assert not has_ai_metadata(out), "IPTC AI marker in XMP survived the strip"
def test_remove_ai_metadata_failsafe_on_truncated_png(self, tmp_path: Path):
"""Regression: a truncated / corrupt image must NOT crash remove_ai_metadata (a
direct library caller like a web worker would 500 on a partial upload). PIL raises
OSError decoding a truncated PNG; the strip must fail SAFE -- copy the input through
unchanged and return, mirroring strip_c2pa_boxes. Real prod corpus: ~0.2% of
uploads are truncated."""
import cv2
import numpy as np
from remove_ai_watermarks.metadata import remove_ai_metadata
real = tmp_path / "real.png"
cv2.imwrite(str(real), np.random.default_rng(0).integers(0, 256, (128, 128, 3), dtype=np.uint8))
truncated = tmp_path / "truncated.png"
truncated.write_bytes(real.read_bytes()[: real.stat().st_size // 2]) # chop the IDAT stream
out = tmp_path / "out.png"
# Must not raise; output is the input copied through (undecodable -> nothing to strip).
result = remove_ai_metadata(truncated, out)
assert result == out
assert out.read_bytes() == truncated.read_bytes()
class TestC2paMarkerIn:
"""The C2PA presence check requires a JUMBF wrapper or the C2PA uuid box, so
@@ -725,6 +777,23 @@ class TestExifGenerator:
remove_ai_metadata(src, out)
assert exif_generator(out) is None
def test_apple_clean_up_removal_parity(self, tmp_path: Path):
# The "Apple Photos Clean Up" credit is an AI-edit VALUE under a
# non-AI key, so removal must drop it by value too (corpus 2026-07-23).
from PIL.PngImagePlugin import PngInfo
from remove_ai_watermarks.metadata import remove_ai_metadata
info = PngInfo()
info.add_text("Software", "Apple Photos Clean Up")
src = tmp_path / "apple.png"
Image.new("RGB", (64, 64)).save(src, pnginfo=info)
assert exif_generator(src) is not None
out = tmp_path / "clean.png"
remove_ai_metadata(src, out)
assert exif_generator(out) is None
def test_imagedescription_tag_ai_tool_detected(self, tmp_path: Path):
# ...and the EXIF ImageDescription field.
exif = piexif.dump(
@@ -926,6 +995,19 @@ class TestAIGCLabel:
assert "aigc_label" in meta
assert "TC260" in meta["aigc_label"]
def test_empty_namespaced_label_is_still_surfaced(self, tmp_path: Path):
"""The namespaced element is unambiguous even when its JSON object is empty."""
from remove_ai_watermarks.metadata import aigc_label
p = tmp_path / "empty_aigc.png"
Image.new("RGB", (32, 32)).save(p)
with open(p, "ab") as f:
f.write(b"<TC260:AIGC>{}</TC260:AIGC>")
assert aigc_label(p) == {}
assert has_ai_metadata(p)
assert "aigc_label" in get_ai_metadata(p)
def _aigc_chunk_png(self, tmp_path: Path, producer: str = "doubao") -> Path:
"""Doubao writes the TC260 object as a PNG ``tEXt`` chunk keyed ``AIGC``
with raw JSON (no XMP, no namespaced marker)."""
@@ -1046,16 +1128,19 @@ class TestAIGCLabel:
assert aigc_label(out) is None
assert not has_ai_metadata(out)
def _aigc_bare_jpeg(self, tmp_path: Path, producer: str = "00119144030008867405X210002") -> Path:
def _aigc_bare_jpeg(
self, tmp_path: Path, producer: str = "00119144030008867405X210002", marker: bytes = b"\xff\xe9"
) -> Path:
"""Some China-served generators glue the TC260 label straight to its JSON
as a bare ``AIGC{...}`` blob inside a JPEG APP segment (no ``"AIGC":``
key wrapper, no PNG chunk, no namespaced XMP) -- seen near the JFIF
header on real 2026-06 downloads."""
header on real 2026-06 downloads. ``marker`` selects the APP segment
(default APP9; the real corpus also uses APP11)."""
p = tmp_path / "aigc_bare.jpg"
Image.new("RGB", (32, 32)).save(p)
raw = p.read_bytes()
blob = b'AIGC{"Label":"1","ContentProducer":"' + producer.encode() + b'","ProduceID":"8F995586"}'
segment = b"\xff\xe9" + (len(blob) + 2).to_bytes(2, "big") + blob # APP9
segment = marker + (len(blob) + 2).to_bytes(2, "big") + blob
p.write_bytes(raw[:2] + segment + raw[2:]) # splice after SOI
return p
@@ -1082,6 +1167,38 @@ class TestAIGCLabel:
assert aigc_label(out) is None
assert not has_ai_metadata(out)
def test_remove_strips_bare_aigc_in_app11(self, tmp_path: Path):
"""Regression (real corpus, 19/27 survivors): the bare ``AIGC{...}`` blob lives
in APP11 (0xEB) on many China gens. That marker's branch in _jpeg_app_carries_ai
only checked for a C2PA/JUMBF manifest and RETURNED, so the AIGC blob slipped past
the generic check -> survived the strip. The specific checks must fall through to
the generic AIGC check."""
from remove_ai_watermarks.metadata import aigc_label, remove_ai_metadata
src = self._aigc_bare_jpeg(tmp_path, marker=b"\xff\xeb") # APP11
assert aigc_label(src) is not None
out = tmp_path / "clean.jpg"
remove_ai_metadata(src, out)
assert aigc_label(out) is None
assert not has_ai_metadata(out)
def test_remove_strips_aigc_in_png_text_chunk(self, tmp_path: Path):
"""Regression (real corpus, 2 survivors): the TC260 ``{"AIGC":{...}}`` block in a
STANDARD PNG text chunk (Description) -- _is_ai_key keeps that key, so removal
must also drop it on the VALUE carrying an AIGC block."""
from PIL.PngImagePlugin import PngInfo
from remove_ai_watermarks.metadata import aigc_label, remove_ai_metadata
p = tmp_path / "aigc_desc.png"
info = PngInfo()
info.add_text("Description", '{"AIGC":{"Label":"1","ContentProducer":"00119144030008867405X210002"}}')
Image.new("RGB", (32, 32)).save(p, pnginfo=info)
assert aigc_label(p) is not None
out = tmp_path / "clean.png"
remove_ai_metadata(p, out)
assert aigc_label(out) is None
def test_bare_aigc_without_tc260_field_ignored(self, tmp_path: Path):
"""A bare ``AIGC{...}`` blob with no TC260 field must not false-positive."""
from remove_ai_watermarks.metadata import aigc_label
+7 -13
View File
@@ -107,10 +107,10 @@ class TestPillRegistry:
class TestPillGate:
"""Pill removal is gated (``_keep_pill``): the reliable bottom-right wordmark
removes it unrestricted, the metadata (``"jimeng"`` provenance) / assume_ai arm
removes it ONLY on a flat footprint (safe fill), Doubao/no-confirmation never
remove it. Fakes each mark's detect so no image content is needed; cv2 backend so
nothing downloads. Frame flatness matters, so tests pass a flat or textured frame."""
removes it unrestricted, the metadata arm (``"jimeng"`` provenance) removes it ONLY
on a flat footprint (safe fill), Doubao/no-confirmation never remove it. Fakes each
mark's detect so no image content is needed; cv2 backend so nothing downloads. Frame
flatness matters, so tests pass a flat or textured frame."""
@staticmethod
def _fakes(monkeypatch: pytest.MonkeyPatch, keys: set[str]) -> None:
@@ -149,16 +149,10 @@ class TestPillGate:
_, removed = registry.remove_auto_marks(_textured_frame())
assert "Jimeng AI生成 pill" in removed
def test_pill_kept_via_assume_ai_on_flat_footprint(self, monkeypatch: pytest.MonkeyPatch) -> None:
# assume_ai (no metadata) removes the pill on a flat footprint (safe fill)...
def test_pill_dropped_on_textured_footprint(self, monkeypatch: pytest.MonkeyPatch) -> None:
# The metadata arm keeps the flatness guard: textured false fires visibly smear.
self._fakes(monkeypatch, {"jimeng_pill"})
_, removed = registry.remove_auto_marks(np.full((400, 300, 3), 150, np.uint8), sensitivity="assume_ai")
assert "Jimeng AI生成 pill" in removed
def test_pill_dropped_via_assume_ai_on_textured_footprint(self, monkeypatch: pytest.MonkeyPatch) -> None:
# ...but even assume_ai keeps the flatness guard (textured false fires smear).
self._fakes(monkeypatch, {"jimeng_pill"})
_, removed = registry.remove_auto_marks(_textured_frame(), sensitivity="assume_ai")
_, removed = registry.remove_auto_marks(_textured_frame(), provenance=frozenset({"jimeng"}))
assert "Jimeng AI生成 pill" not in removed
def test_pill_dropped_without_metadata_or_wordmark(self, monkeypatch: pytest.MonkeyPatch) -> None:
+48
View File
@@ -178,6 +178,54 @@ class TestFp16WeightVariant:
assert "variant" not in cls.from_pretrained.call_args.kwargs
class TestNoReembeddedWatermark:
"""F2 regression: the SDXL removal pipelines must disable the diffusers default
invisible watermarker (``add_watermarker=False``).
diffusers stamps an open "Stable Diffusion XL" DWT-DCT watermark onto every SDXL
output whenever ``invisible-watermark`` is installed. A watermark REMOVER that left
it on would replace one detectable AI watermark (SynthID) with another -- the cleaned
output re-reads as AI. The ControlNet sub-model load must NOT receive the kwarg (it
is not a pipeline and does not accept it).
"""
def _remover(self, profile: str):
if not is_watermark_removal_available():
pytest.skip("torch/diffusers not installed")
from remove_ai_watermarks.noai.watermark_remover import WatermarkRemover
return WatermarkRemover(device="cpu", pipeline=profile)
def _capture(self, monkeypatch, remover):
from remove_ai_watermarks.noai.watermark_remover import WatermarkRemover
calls: list[tuple[str, dict]] = []
def fake_load(self, cls, model_id, **kwargs):
calls.append((getattr(cls, "__name__", str(cls)), kwargs))
return MagicMock()
monkeypatch.setattr(WatermarkRemover, "_load_from_pretrained", fake_load)
monkeypatch.setattr(WatermarkRemover, "_move_to_device_and_optimize", lambda self, p: p)
return calls
def test_sdxl_pipeline_disables_watermarker(self, monkeypatch: pytest.MonkeyPatch):
remover = self._remover("sdxl")
calls = self._capture(monkeypatch, remover)
remover._load_pipeline()
assert any(kw.get("add_watermarker") is False for _, kw in calls), calls
def test_controlnet_pipeline_disables_watermarker(self, monkeypatch: pytest.MonkeyPatch):
remover = self._remover("controlnet")
calls = self._capture(monkeypatch, remover)
remover._load_controlnet_pipeline()
by_cls = dict(calls)
# the SDXL pipeline load disables the watermarker...
assert by_cls["StableDiffusionXLControlNetImg2ImgPipeline"].get("add_watermarker") is False
# ...but the ControlNet sub-model load must not carry the kwarg (it would error).
assert "add_watermarker" not in by_cls["ControlNetModel"]
class _StubImage:
"""Minimal PIL.Image stand-in: just the ``width``/``height`` the pure helper reads."""
+155
View File
@@ -0,0 +1,155 @@
"""Tests for the Qwen (千问AI生成) visible-watermark engine (localize -> fill).
Every tuned constant in ``qwen_engine`` was measured on the 117-frame vendor
cohort (2026-07-21, ``scripts/vendor_mark_calibrate.py``); these tests pin the
load-bearing ones so a later "cleanup" cannot silently re-inherit Doubao's
geometry (the exact failure the calibration had to fix).
"""
from __future__ import annotations
import cv2
import numpy as np
import pytest
from remove_ai_watermarks import watermark_registry as registry
from remove_ai_watermarks.qwen_engine import (
_ALPHA_HEIGHT_FRAC,
_ALPHA_WIDTH_FRAC,
_LADDER,
QwenEngine,
_alpha_template,
_glyph_silhouette,
)
# The two measured size modes (fraction of the short side): a single fraction on
# the shared 3-rung ladder covers only ~75% of marks; the per-mark 2-rung ladder
# centres one rung on each mode.
_BIG_MODE, _SMALL_MODE = 0.203, 0.124
_MARGIN = 0.025 # measured right/bottom margin of the real mark
def _compose(w: int, h: int, mode: float = _BIG_MODE, bg: float = 100.0):
"""Composite the Qwen silhouette at a measured size mode onto a flat bg."""
img = np.full((h, w, 3), bg, np.float32)
at = _alpha_template()
short = min(w, h)
gw = int(mode * short)
gh = max(4, int(mode * (_ALPHA_HEIGHT_FRAC / _ALPHA_WIDTH_FRAC) * short))
margin = int(_MARGIN * short)
ax = w - margin - gw
ay = h - margin - gh
amap = np.zeros((h, w), np.float32)
amap[ay : ay + gh, ax : ax + gw] = cv2.resize(at, (gw, gh))
a3 = amap[:, :, None]
wm = (a3 * 255.0 + (1 - a3) * img).clip(0, 255).astype(np.uint8)
return wm, amap > 0.2
class TestLocate:
def test_box_anchored_bottom_right_off_the_corner(self):
# The measured right margin (~0.025 of short) is wider than Doubao's 0.004;
# inheriting Doubao's anchor clipped the first glyph (0.73 -> 0.26 NCC).
eng = QwenEngine()
img = np.zeros((2048, 2048, 3), np.uint8)
loc = eng.locate(img)
assert 2048 - (loc.x + loc.w) == pytest.approx(2048 * 0.0203, rel=0.15)
assert 2048 - (loc.y + loc.h) == pytest.approx(2048 * 0.0218, rel=0.15)
def test_box_scales_with_short_side_not_width(self):
# scale_basis="short" (measured: frac_short CV 0.189 vs width 0.273).
eng = QwenEngine()
landscape = eng.locate(np.zeros((640, 1280, 3), np.uint8))
wider = eng.locate(np.zeros((640, 2560, 3), np.uint8))
assert wider.w == landscape.w # same short side -> same box
bigger = eng.locate(np.zeros((1280, 1920, 3), np.uint8)) # 2x the short side
assert bigger.w == pytest.approx(landscape.w * 2, rel=0.05)
class TestConfig:
def test_per_mark_ladder_and_shared_default_untouched(self):
# Qwen's two size modes need their own 2-rung ladder; every other mark must
# keep the shipped 3-rung default (the field's whole point is per-mark).
assert _LADDER == (0.78, 1.27)
assert QwenEngine().config.ladder == (0.78, 1.27)
from remove_ai_watermarks.doubao_engine import _CONFIG as db
from remove_ai_watermarks.jimeng_engine import _CONFIG as jm
from remove_ai_watermarks.samsung_engine import _CONFIG as ss
assert db.ladder == jm.ladder == ss.ladder == (0.8, 1.0, 1.25)
def test_strict_only_no_provenance_relaxation(self):
# The sub-gate band is dominated by non-Qwen banners on same-cohort frames,
# so the relaxed arm was measured to be mostly false fills: factor pinned 1.0.
assert QwenEngine().config.provenance_ncc_factor == 1.0
def test_registry_row(self):
mark = registry.get_mark("qwen")
assert mark.location == "bottom-right"
assert "千问AI生成" in mark.label
assert mark.in_auto
class TestDetect:
def test_clean_gradient_not_detected(self):
eng = QwenEngine()
ramp = np.tile(np.linspace(0, 255, 1024, dtype=np.uint8), (1024, 1))
img = cv2.cvtColor(ramp, cv2.COLOR_GRAY2BGR)
assert not eng.detect(img).detected
def test_solid_blob_corner_not_detected(self):
eng = QwenEngine()
img = np.zeros((1024, 1024, 3), np.uint8)
x, y, bw, bh = eng.locate(img).bbox
img[y + bh // 4 : y + bh * 3 // 4, x : x + bw // 2] = 200
assert not eng.detect(img).detected
def test_silhouette_loads(self):
sil = _glyph_silhouette()
assert sil is not None
assert set(np.unique(sil)).issubset({0, 255})
@pytest.mark.parametrize("mode", [_BIG_MODE, _SMALL_MODE])
def test_both_size_modes_detected(self, mode):
# The registration's core claim: a mark at EITHER measured mode scores over
# the gate (a single fraction on the shared ladder lost the small mode).
# The floor is deliberately far above the gate: the synthetic mark is clean,
# so it scores ~0.88/~0.94 when the geometry is right, but ~0.49 with Doubao's
# box margins (the first glyph is clipped) and ~0.67 on the shared 3-rung
# ladder -- the floor is what makes this test discriminate both regressions
# (every variant passes a bare gate check on the synthetic).
wm, _ = _compose(853, 640, mode=mode)
det = QwenEngine().detect(wm)
assert det.detected
assert det.confidence >= 0.80
def test_small_image_guarded(self):
wm, _ = _compose(853, 640)
eng = QwenEngine()
assert eng.detect(wm).detected
assert not eng.detect(cv2.resize(wm, (150, 112))).detected
class TestFootprintMaskAndRemoval:
@pytest.mark.parametrize("mode", [_BIG_MODE, _SMALL_MODE])
def test_removes_composed_mark_at_both_modes(self, mode):
wm, mark = _compose(853, 640, mode=mode)
assert float(np.abs(wm.astype(np.float32)[mark] - 100.0).mean()) > 15 # mark visible
assert QwenEngine().detect(wm).detected
out, region = registry.get_mark("qwen").remove(wm, backend="cv2")
assert region is not None
assert not QwenEngine().detect(out).detected
h, w = wm.shape[:2]
assert np.array_equal(out[: h // 2, : w // 2], wm[: h // 2, : w // 2]) # far region exact
def test_footprint_mask_in_bottom_right(self):
wm, _ = _compose(853, 640)
mask = QwenEngine().footprint_mask(wm)
assert mask is not None
ys, xs = np.where(mask > 0)
assert ys.mean() > wm.shape[0] / 2
assert xs.mean() > wm.shape[1] / 2
def test_clean_frame_produces_no_mask(self):
clean = cv2.GaussianBlur(np.full((640, 853, 3), 120, np.uint8), (5, 5), 0)
assert QwenEngine().footprint_mask(clean, force=False) is None
+135
View File
@@ -0,0 +1,135 @@
"""Tests for the RunningHub ("RunningHub AI生成") visible-watermark engine.
Every tuned constant in ``runninghub_engine`` was measured on the 73-frame
vendor cohort (2026-07-22, ``scripts/vendor_cohort_harvest.py`` +
``scripts/vendor_mark_calibrate.py``); these tests pin the load-bearing ones:
the top-left corner, the gray front-end, the exact-size tight ladder, the
strict-only gate, and the mask/coverage parity regression (the partial-blob
"Runni" miss).
"""
from __future__ import annotations
import cv2
import numpy as np
import pytest
from remove_ai_watermarks import watermark_registry as registry
from remove_ai_watermarks.runninghub_engine import (
_ALPHA_HEIGHT_FRAC,
_ALPHA_WIDTH_FRAC,
RunningHubEngine,
_alpha_template,
)
_MARK_FRAC = 0.32 # measured mark width, fraction of the frame WIDTH
def _compose(w: int, h: int, mode: float = _MARK_FRAC, bg: float = 100.0):
"""Composite the RunningHub silhouette at the measured size, top-left."""
img = np.full((h, w, 3), bg, np.float32)
at = _alpha_template()
gw = int(mode * w)
gh = max(4, int(mode * (_ALPHA_HEIGHT_FRAC / _ALPHA_WIDTH_FRAC) * w))
ax, ay = int(0.008 * w), int(0.006 * h)
amap = np.zeros((h, w), np.float32)
amap[ay : ay + gh, ax : ax + gw] = cv2.resize(at, (gw, gh))
a3 = amap[:, :, None]
wm = (a3 * 255.0 + (1 - a3) * img).clip(0, 255).astype(np.uint8)
return wm, (ax, ay, gw, gh)
class TestLocate:
def test_box_anchored_top_left(self):
eng = RunningHubEngine()
img = np.zeros((2048, 1536, 3), np.uint8)
loc = eng.locate(img)
assert loc.x < 40 # hugs the left edge
assert loc.y < 40 # hugs the top edge (corner="tl")
def test_box_scales_with_width(self):
# scale_basis="width" (measured: mark width is 0.32 of the frame width).
eng = RunningHubEngine()
narrow = eng.locate(np.zeros((2048, 1024, 3), np.uint8))
wide = eng.locate(np.zeros((2048, 2048, 3), np.uint8))
assert wide.w == pytest.approx(narrow.w * 2, rel=0.05)
class TestConfig:
def test_gray_frontend(self):
# The mark is a faint mid-gray the top-hat suppresses to clean-arm levels;
# the raw-grayscale front-end is what separates (measured 2026-07-22).
assert RunningHubEngine().config.detect_frontend == "gray"
def test_tight_ladder(self):
# The NCC comb is razor-sharp in size (0.537 on-size, 0.223 at +5.6%), so
# the nominal sits exactly on the measured 0.32 with +-5% rungs.
assert RunningHubEngine().config.ladder == (0.95, 1.0, 1.05)
assert RunningHubEngine().config.alpha_width_frac == pytest.approx(0.32)
def test_strict_only_no_provenance_relaxation(self):
assert RunningHubEngine().config.provenance_ncc_factor == 1.0
def test_gate_above_clean_arm_max(self):
# Clean arm scored p99 0.273 / max 0.295 on 286 hand-labelled frames.
assert RunningHubEngine().config.detect_ncc_threshold > 0.295
def test_registry_row(self):
mark = registry.get_mark("runninghub")
assert mark.location == "top-left"
assert mark.in_auto
class TestDetectAndMask:
def test_detects_composed_mark(self):
eng = RunningHubEngine()
wm, _ = _compose(1080, 1620)
det = eng.detect(wm)
assert det.detected, f"composed mark missed (conf={det.confidence:.3f})"
def test_clean_frame_stays_quiet(self):
eng = RunningHubEngine()
img = np.full((1620, 1080, 3), 100, np.uint8)
assert not eng.detect(img).detected
def test_mask_covers_the_whole_mark(self):
"""Regression (2026-07-22): the binary blob under-segments the faint head
glyphs, so a blob-bbox mask left "Runni" unremoved. The gray front-end's
mask must come from the detector's own match box and cover the mark."""
eng = RunningHubEngine()
wm, (ax, ay, gw, gh) = _compose(1080, 1620)
mask = eng.footprint_mask(wm)
assert mask is not None
ys, xs = np.where(mask > 0)
assert xs.min() <= ax + int(0.05 * gw) # covers the LEFT edge of the mark
assert xs.max() >= ax + gw - int(0.05 * gw)
assert ys.min() <= ay + gh // 2 <= ys.max()
def test_no_mask_on_clean_frame(self):
eng = RunningHubEngine()
img = np.full((1620, 1080, 3), 100, np.uint8)
assert eng.footprint_mask(img) is None
def test_anchor_window_rejects_off_corner_match(self):
"""The raw-gray front-end false-fires on text-like structure ANYWHERE in
the box (37/42009 outside-cohort frames in the 2026-07-22 sweep); the
anchor window is what keeps it about THIS mark. A composed mark placed
off the measured corner anchor must NOT be detected."""
eng = RunningHubEngine()
wm, _ = _compose(1080, 1620)
det = eng.detect(wm)
assert det.detected # on-anchor control
# the same mark shifted right/down, off the anchor window
shifted = np.full((1620, 1080, 3), 100, np.uint8)
region = wm[10:60, 12:360]
shifted[100 : 100 + region.shape[0], 200 : 200 + region.shape[1]] = region
assert not eng.detect(shifted).detected
class TestPillInteraction:
def test_confident_runninghub_detection_suppresses_the_jimeng_pill(self):
# A RunningHub frame names its own product; its detection must veto the
# Jimeng pill the same way Doubao/Qwen/Kling do (``_keep_pill``).
from remove_ai_watermarks.watermark_registry import _keep_pill
assert not _keep_pill({"runninghub"}, provenance=frozenset({"jimeng"}), footprint_flat=1.0)
+191
View File
@@ -0,0 +1,191 @@
"""Policy-level tests for the shared text-mark engine config.
These assert TUNING that was set by corpus measurement, not algorithm behaviour --
they exist so a future edit cannot silently revert a calibrated constant back to a
value that was measured to be wrong. The measurements themselves live in
`docs/module-internals.md` and in the comment at
`_text_mark_engine._DEFAULT_PROVENANCE_NCC_FACTOR`.
"""
class TestRivalMargin:
"""Detection among same-corner marks is COMPETITIVE, not just absolute.
Doubao "豆包AI生成" and Jimeng "★ 即梦AI" both sit bottom-right in near-white CJK
and survive binarization as similar blobs, so an absolute NCC gate cannot tell
them apart -- 33 of jimeng's 68 false additions were Doubao marks. Measured
separability scoring both templates on the SAME blob (n=40 jimeng / 75 doubao):
absolute ncc_jimeng 0.96, ncc_jimeng MINUS ncc_doubao 0.99. Corpus effect of the
margin gate: jimeng precision 38% -> 63% with genuine detections unchanged at 40
(false fires 65 -> 23).
"""
def test_jimeng_competes_against_doubao(self):
from remove_ai_watermarks import jimeng_engine
assert "doubao_alpha.png" in jimeng_engine._CONFIG.rivals
def test_doubao_has_no_rival_margin(self):
"""Asymmetric by measurement, not oversight: the symmetric gate cost Doubao 7
genuine detections to prevent 5 false ones (1.4:1 against), while Jimeng gained
25pp for free. Doubao's absolute detector is already 86% precise."""
from remove_ai_watermarks import doubao_engine
assert doubao_engine._CONFIG.rivals == ()
def test_a_doubao_shaped_blob_loses_the_jimeng_margin(self):
"""The decisive case: a blob matching Doubao BETTER than Jimeng must not be
booked as a Jimeng wordmark, however high its absolute Jimeng score."""
import numpy as np
from remove_ai_watermarks import jimeng_engine
from remove_ai_watermarks._text_mark_engine import glyph_silhouette
eng = jimeng_engine.JimengEngine()
doubao_blob = glyph_silhouette("doubao_alpha.png")
assert doubao_blob is not None
canvas = np.zeros((doubao_blob.shape[0] + 20, doubao_blob.shape[1] + 20), np.uint8)
canvas[10 : 10 + doubao_blob.shape[0], 10 : 10 + doubao_blob.shape[1]] = doubao_blob
width = int(doubao_blob.shape[1] / jimeng_engine._CONFIG.alpha_width_frac)
jimeng_score = eng._template_match_score(canvas, width)
assert not eng._rival_margin_ok(jimeng_score, canvas, width)
class TestPerMarkProvenanceRelaxation:
"""The provenance NCC relaxation is PER MARK, not one shared multiplier.
Corpus-measured 2026-07-18 on the default `auto` path (4417 unique TC260
carriers, blind hand-label, two-sided control): the single shared 0.7 ran at
76% precision on doubao but 17% on jimeng, because jimeng's relaxed silhouette
keys on "text in the bottom-right corner" rather than the wordmark -- 33 of its
68 false additions were DOUBAO marks. Full table at
`_text_mark_engine._DEFAULT_PROVENANCE_NCC_FACTOR`.
"""
class TestScaleBasis:
"""Mark geometry scales with a PER-MARK image dimension, measured not assumed.
Every tuned fraction was calibrated on PORTRAIT captures, where width and short
side coincide, so the basis was never exercised until landscape inputs were
measured. Corpus-measured 2026-07-18 (2572 unique TC260 carriers): doubao
detection was portrait 60% / square 41% / **landscape 0% of 435** -- a width-scaled
box is inflated by the aspect ratio on a wide image and the glyph never lands in
it. A short-side basis recovered 56% of the previously-undetected landscape set.
The same switch broke JIMENG (labelled landscape positives 13/13 -> 0/13), whose
wordmark tracks the width -- hence per-mark, not a house rule.
"""
def test_doubao_scales_with_the_short_side(self):
from remove_ai_watermarks import doubao_engine
assert doubao_engine._CONFIG.scale_basis == "short"
def test_jimeng_scales_with_width(self):
"""Measured, not an oversight: the short-side basis took jimeng's labelled
landscape positives from 13/13 to 0/13."""
from remove_ai_watermarks import jimeng_engine
assert jimeng_engine._CONFIG.scale_basis == "width"
def test_samsung_keeps_width_because_it_is_unmeasured(self):
"""1 addition corpus-wide, so there is no evidence either way; an unmeasured
change is not an improvement."""
from remove_ai_watermarks import samsung_engine
assert samsung_engine._CONFIG.scale_basis == "width"
def test_basis_only_differs_on_non_square_images(self):
"""The basis is a no-op wherever width IS the short side, which is why the bug
survived: every calibration capture was portrait."""
import numpy as np
from remove_ai_watermarks import doubao_engine, jimeng_engine
portrait = np.zeros((1600, 900, 3), np.uint8)
landscape = np.zeros((900, 1600, 3), np.uint8)
d, j = doubao_engine.DoubaoEngine(), jimeng_engine.JimengEngine()
assert d.scale_base(portrait) == j.scale_base(portrait) == 900
assert d.scale_base(landscape) == 900
assert j.scale_base(landscape) == 1600
def test_landscape_box_stays_inside_the_frame(self):
"""The concrete failure: a width-scaled box on a wide image overshoots the
mark's real footprint. The short-side box must be proportionally smaller."""
import numpy as np
from remove_ai_watermarks import doubao_engine
landscape = np.zeros((900, 2400, 3), np.uint8)
loc = doubao_engine.DoubaoEngine().locate(landscape)
assert loc.w < int(2400 * doubao_engine._CONFIG.width_frac)
assert loc.x + loc.w <= 2400
assert loc.y + loc.h <= 900
class TestTophatFrontend:
"""Detection can correlate the CONTINUOUS top-hat instead of a binarized blob.
`extract_mask` thresholds the top-hat into a 0/255 glyph blob, which is fine for a
mark stamped bold and opaque and destructive for a faint one -- a thin translucent
overlay shatters into specks and no template can match a blob that is not there
(measured: 千问 scored 0.170 mean vs doubao's 0.723 through the binary path, 0% over
the gate). The `tophat` front-end never binarizes: the saturation/luma gates become
weights, and the response is max-normalized so the score is contrast-invariant.
Corpus effect on the 240-image unbiased recall sample: doubao recall 89% -> 92% at
an unchanged 99% precision.
"""
def test_doubao_uses_the_continuous_frontend(self):
from remove_ai_watermarks import doubao_engine
assert doubao_engine._CONFIG.detect_frontend == "tophat"
def test_other_marks_stay_binary_until_measured(self):
"""A front-end switch must be measured per mark before it ships; jimeng and
samsung have no such measurement yet."""
from remove_ai_watermarks import jimeng_engine, samsung_engine
assert jimeng_engine._CONFIG.detect_frontend == "binary"
assert samsung_engine._CONFIG.detect_frontend == "binary"
def test_response_is_contrast_invariant(self):
"""The whole point: a faint mark and a bold one produce the same response, so a
single threshold works for both. Binarizing is what loses the faint one."""
import numpy as np
from remove_ai_watermarks import doubao_engine
eng = doubao_engine.DoubaoEngine()
h, w = 400, 900
out = []
for amplitude in (12, 90): # a barely-there overlay and a bold one
img = np.full((h, w, 3), 100, np.uint8)
loc = eng.locate(img)
x, y, bw, bh = loc.bbox
img[y + bh // 3 : y + 2 * bh // 3, x + bw // 4 : x + 3 * bw // 4] = 100 + amplitude
resp = eng.tophat_response(img, loc)
assert resp is not None
out.append(resp)
# max-normalized, so the two responses agree despite a 7.5x contrast difference
assert abs(int(out[0].max()) - int(out[1].max())) <= 1
def test_flat_input_yields_no_response(self):
"""A blank corner has no top-hat at all; the engine must return None rather
than divide by a zero peak."""
import numpy as np
from remove_ai_watermarks import doubao_engine
eng = doubao_engine.DoubaoEngine()
img = np.full((400, 900, 3), 128, np.uint8)
assert eng.tophat_response(img, eng.locate(img)) is None
def test_threshold_is_frontend_specific(self):
"""The continuous front-end scores higher overall (0.809 vs 0.723 mean on the
same positives), so it needs its own gate; the binary-era 0.40 left the
provenance-relaxed gate low enough to admit 8 false fires where 0.50 admits 1."""
from remove_ai_watermarks import doubao_engine
assert doubao_engine._CONFIG.detect_ncc_threshold == 0.50
+141
View File
@@ -0,0 +1,141 @@
"""A mark the `tophat` front-end DETECTS must also be MASKABLE.
Corpus-found 2026-07-20: Doubao's detection moved to the continuous `tophat` front-end
(which does not binarize, and that is where its recall 89% -> 92% came from), but the
removal mask still came from the BINARIZED glyph blob. A mark faint enough to be found
only by the continuous response therefore produced an empty binary blob, `localize`
returned mask=None, and `remove()` was a silent no-op: `identify` reported
`visible_doubao` while `visible` said "no visible mark" on the same file. Measured on the
full corpus parity sweep: 57 of 60 sampled still-detected Doubao marks were untouched
no-ops, ~8% of all Doubao detections.
"""
from __future__ import annotations
import cv2
import numpy as np
import pytest
from remove_ai_watermarks.doubao_engine import DoubaoEngine
def _faint_mark_image(w: int = 900, h: int = 1200, alpha: float = 0.06, textured: bool = False) -> np.ndarray:
"""A frame carrying the REAL Doubao glyph shape at very low opacity.
The shape has to be genuine or the NCC detector will not fire and the test would be
exercising nothing; the low ``alpha`` is what keeps the binarizing path from finding
a blob. Composited with the same forward model the marks use:
``stamped = (1-a)*bg + a*white``.
``textured`` adds fine luminance noise to the background. It is not decoration: on a
FLAT frame the top-hat response is non-zero only on the glyph, so every threshold
yields the same bounding box and a test built on a flat fixture cannot see a wrong
threshold at all -- mutating the constant to an absurd value left the flat tests green.
Texture puts response outside the glyph, which is the condition under which the mask's
sizing actually matters, and is what real corner backgrounds look like.
"""
from remove_ai_watermarks._text_mark_engine import load_alpha_template
tmpl = load_alpha_template("doubao_alpha.png")
if tmpl is None:
pytest.skip("doubao alpha asset unavailable")
img = np.full((h, w, 3), 120, np.uint8)
if textured:
rng = np.random.default_rng(7)
noise = rng.normal(0, 14, (h, w, 1)).repeat(3, axis=2)
img = np.clip(img.astype(np.float32) + noise, 0, 255).astype(np.uint8)
img = cv2.GaussianBlur(img, (0, 0), sigmaX=1.2)
eng = DoubaoEngine()
loc = eng.locate(img)
base = eng.scale_base(img)
gw = max(eng.config.min_gw, int(eng.config.alpha_width_frac * base))
gh = max(4, int(eng.config.alpha_height_frac * base))
a = cv2.resize(tmpl, (gw, gh), interpolation=cv2.INTER_AREA).astype(np.float32) * alpha
x = loc.x + (loc.w - gw) // 2
y = loc.y + (loc.h - gh) // 2
roi = img[y : y + gh, x : x + gw].astype(np.float32)
a3 = a[..., None]
img[y : y + gh, x : x + gw] = np.clip(roi * (1 - a3) + 255.0 * a3, 0, 255).astype(np.uint8)
return img
class TestFaintMarkIsMaskable:
def test_binary_glyph_blob_is_empty_on_a_faint_mark(self):
"""The premise: this is the input class the binarizing path cannot segment."""
eng = DoubaoEngine()
img = _faint_mark_image()
loc = eng.locate(img)
glyph = eng.extract_mask(img, loc)
assert int((glyph > 0).sum()) < eng._MIN_GLYPH_PIXELS
def test_footprint_mask_is_not_empty_when_the_continuous_response_has_signal(self):
"""The fix: a faint mark must still yield a removal mask, without --no-detect.
Without it `localize` returns None and removal silently does nothing while
`identify` keeps reporting the mark.
"""
eng = DoubaoEngine()
img = _faint_mark_image()
mask = eng.footprint_mask(img, force=False)
assert mask is not None, "a detectable faint mark produced no removal mask"
assert int((mask > 0).sum()) > 0
def test_a_clean_frame_still_produces_no_mask(self):
"""The guard: the fallback must not turn every flat corner into a fill."""
eng = DoubaoEngine()
clean = cv2.GaussianBlur(np.full((1200, 900, 3), 120, np.uint8), (5, 5), 0)
assert eng.footprint_mask(clean, force=False) is None
@pytest.mark.parametrize("alpha", [0.5, 0.9])
def test_a_bold_mark_is_unaffected(self, alpha: float):
"""A mark the binary path already segments must keep its tight glyph box."""
eng = DoubaoEngine()
img = _faint_mark_image(alpha=alpha)
mask = eng.footprint_mask(img, force=False)
assert mask is not None
assert int((mask > 0).sum()) > 0
class TestFaintMaskStaysTight:
"""The faint fallback must cover the mark WITHOUT filling the whole corner.
Corpus-found 2026-07-20: the first version of the fallback thresholded the continuous
response at 0.5, but `tophat_response` returns uint8 0..255 -- so it selected every
non-zero pixel, not "half the peak" as its comment claimed. On 12 of 12 real frames
taking this path the resulting box covered 100% of the corner ROI, so removal inpainted
the entire corner instead of the glyph. Parity could not see it: parity asks whether
the detector is clean afterwards, and a mask that fills everything passes trivially.
The cost, not the outcome, was the defect.
"""
def test_mask_does_not_swallow_the_whole_corner_on_a_textured_frame(self):
eng = DoubaoEngine()
img = _faint_mark_image(alpha=0.10, textured=True)
# Asserted, not skipped: a skip here would silently stop guarding the moment the
# detector changed, which is exactly when this needs to be guarding.
assert eng.detect(img).detected, "fixture must reach the faint path to test it"
mask = eng.footprint_mask(img, force=False)
assert mask is not None, "a detected faint mark must still produce a mask"
area = int((mask > 0).sum())
loc = eng.locate(img)
roi = loc.w * loc.h
# The mark's own glyph box is ~40% of the corner ROI and the mask pads it, so a
# correct mask lands near 60%. The pre-fix behaviour measured 120.9% (the whole
# ROI plus padding), which this bound excludes.
assert area < 0.85 * roi, f"mask covers {100 * area / roi:.0f}% of the corner box"
def test_mask_still_covers_the_stamped_glyph(self):
"""Tightness is only a virtue if the mark is still inside. Guards the other way."""
eng = DoubaoEngine()
img = _faint_mark_image(alpha=0.10, textured=True)
assert eng.detect(img).detected, "fixture must reach the faint path to test it"
mask = eng.footprint_mask(img, force=False)
assert mask is not None
loc = eng.locate(img)
base = eng.scale_base(img)
gw = max(eng.config.min_gw, int(eng.config.alpha_width_frac * base))
gh = max(4, int(eng.config.alpha_height_frac * base))
x = loc.x + (loc.w - gw) // 2
y = loc.y + (loc.h - gh) // 2
covered = int(np.count_nonzero(mask[y : y + gh, x : x + gw])) / max(1, gw * gh)
assert covered > 0.6, f"mask covers only {100 * covered:.0f}% of the stamped glyph"
+48
View File
@@ -0,0 +1,48 @@
"""Pure tests for the strength/steps profile helpers (no model, no torch needed)."""
from __future__ import annotations
import pytest
from remove_ai_watermarks.noai.watermark_profiles import resolve_strength, viable_steps
class TestViableSteps:
"""Guards the crash found by the release smoke matrix on 2026-07-19.
diffusers derives its img2img timesteps as ``int(steps * strength)``. When that
rounds to zero the pipeline builds an empty tensor and dies deep inside attention
with "cannot reshape tensor of 0 elements into shape [0, -1, 1, 512]". At the
default strength 0.15 that was every ``--steps`` below 7, reachable with entirely
valid CLI arguments and no special flags.
"""
@pytest.mark.parametrize(
("steps", "strength"),
[(1, 0.15), (2, 0.15), (5, 0.15), (6, 0.15), (5, 0.10), (9, 0.10), (1, 0.5)],
)
def test_never_returns_a_count_that_denoises_zero_steps(self, steps: int, strength: float):
assert int(viable_steps(steps, strength) * strength) >= 1
@pytest.mark.parametrize(
("steps", "strength"),
[(50, 0.15), (20, 0.15), (7, 0.15), (10, 0.10), (2, 0.5), (50, 1.0)],
)
def test_leaves_a_workable_count_untouched(self, steps: int, strength: float):
assert viable_steps(steps, strength) == steps
def test_raises_only_to_the_minimum_needed(self):
# strength 0.15 needs 7 (int(7*0.15)==1); it must not jump to some larger default.
assert viable_steps(5, 0.15) == 7
assert viable_steps(1, 0.10) == 10
def test_the_vendor_defaults_all_have_a_reachable_floor(self):
for vendor in (None, "openai", "google"):
strength = resolve_strength(None, vendor)
assert int(viable_steps(1, strength) * strength) >= 1
@pytest.mark.parametrize("strength", [0.0, -0.1])
def test_a_non_positive_strength_cannot_loop_or_divide_by_zero(self, strength: float):
# No denoising is possible at all here; return the caller's value rather than
# dividing by zero or spinning.
assert viable_steps(20, strength) == 20
+161 -24
View File
@@ -14,7 +14,18 @@ DOUBAO_SAMPLE = Path(__file__).resolve().parents[1] / "data" / "samples" / "doub
class TestCatalog:
def test_keys(self):
assert reg.mark_keys() == ["gemini", "doubao", "jimeng", "samsung", "jimeng_pill"]
assert reg.mark_keys() == [
"gemini",
"doubao",
"jimeng",
"qwen",
"kling",
"samsung",
"runninghub",
"baidu",
"liblib",
"jimeng_pill",
]
def test_all_in_auto(self):
assert all(m.in_auto for m in reg.known_marks())
@@ -43,7 +54,18 @@ class TestScan:
def test_detect_marks_scans_all(self):
img = np.zeros((256, 256, 3), np.uint8)
keys = {d.key for d in reg.detect_marks(img)}
assert keys == {"gemini", "doubao", "jimeng", "samsung", "jimeng_pill"}
assert keys == {
"gemini",
"doubao",
"jimeng",
"qwen",
"kling",
"samsung",
"runninghub",
"baidu",
"liblib",
"jimeng_pill",
}
def test_blank_image_no_auto_mark(self):
dets = reg.detect_marks(np.zeros((256, 256, 3), np.uint8), include_explicit=False)
@@ -67,7 +89,7 @@ class TestScan:
forced remove on a zero-size ndarray crashed (cv2.error on an empty Mat). detect
already guarded this; footprint_mask must too. Covers the text + gemini engines."""
empty = np.zeros(shape, np.uint8)
for key in ("doubao", "jimeng", "samsung", "gemini"):
for key in ("doubao", "jimeng", "qwen", "samsung", "gemini"):
_result, mask = reg.get_mark(key).remove(empty, force=True)
assert mask is None
@@ -113,24 +135,51 @@ class TestFill:
class TestProvenanceGate:
"""The Gemini trust gate relaxes from 0.5 to 0.35 when provenance confirms Google;
tested deterministically by stubbing the engine's raw detection confidence."""
"""The Gemini trust gate relaxes from GEMINI_SPARKLE_TRUST_CONF to
_GEMINI_PROVENANCE_MIN_CONF when provenance confirms Google; tested
deterministically by stubbing the engine's raw detection confidence."""
def _stub(self, monkeypatch: pytest.MonkeyPatch, conf: float) -> None:
from remove_ai_watermarks.gemini_engine import DetectionResult
# `detected` mirrors the engine's own internal floor (0.35), which is
# independent of the registry gate under test here.
def fake_detect(image, force_size=None, *, trust_provenance=False):
return DetectionResult(detected=conf >= 0.35, confidence=conf, region=(10, 10, 48, 48))
monkeypatch.setattr(reg._engine("gemini"), "detect_watermark", fake_detect)
def test_midband_conf_needs_provenance(self, monkeypatch: pytest.MonkeyPatch):
# conf 0.42 sits in [0.35, 0.5): demoted without provenance, trusted with it.
self._stub(monkeypatch, 0.42)
# Comfortably inside the relaxed band: demoted without provenance, trusted with it.
conf = (reg._GEMINI_PROVENANCE_MIN_CONF + reg.GEMINI_SPARKLE_TRUST_CONF) / 2
self._stub(monkeypatch, conf)
img = np.zeros((256, 256, 3), np.uint8)
assert reg.get_mark("gemini").detect(img).detected is False
assert reg.get_mark("gemini").detect(img, provenance=True).detected is True
def test_below_provenance_gate_rejected_even_with_provenance(self, monkeypatch: pytest.MonkeyPatch):
"""Provenance relaxes the gate, it does not remove it.
Guards the 2026-07-18 raise of _GEMINI_PROVENANCE_MIN_CONF (0.35 -> 0.42).
The engine still reports `detected` down at its own 0.35 floor, so without
the registry gate this confidence would be accepted and inpainted. Measured
precision just below the gate was 13% (n=30, 95% CI 5-30%) on real
Google-metadata uploads -- i.e. ~7 of 8 accepts there destroy pixels on an
image that never carried a sparkle, and report a removal that did not happen.
"""
# 0.38 is inside the measured 13%-precision band and above the engine's own
# 0.35 floor, so the engine reports `detected` and only the registry gate can
# reject it. Hardcoded on purpose: if the gate is ever lowered back under this
# value, this test must fail on the BEHAVIOUR below, not on its own arithmetic.
self._stub(monkeypatch, 0.38)
img = np.zeros((256, 256, 3), np.uint8)
assert reg.get_mark("gemini").detect(img).detected is False
assert reg.get_mark("gemini").detect(img, provenance=True).detected is False
def test_provenance_gate_stays_below_the_strict_gate(self):
"""The relaxed gate must actually relax, and must not collapse onto the floor."""
assert 0.35 < reg._GEMINI_PROVENANCE_MIN_CONF < reg.GEMINI_SPARKLE_TRUST_CONF
def test_high_conf_detected_either_way(self, monkeypatch: pytest.MonkeyPatch):
self._stub(monkeypatch, 0.72)
img = np.zeros((256, 256, 3), np.uint8)
@@ -165,44 +214,97 @@ class TestLocalizeFill:
class TestSensitivity:
"""``resolve_relax`` turns the sensitivity policy + evidence into the per-mark
relaxation boolean the engines consume."""
"""``resolve_trust`` turns the sensitivity policy + evidence into the per-mark
trust level the engines consume."""
def test_strict_never_relaxes(self):
# even with metadata provenance, strict keeps the conservative gate
assert (
reg.resolve_relax("gemini", sensitivity="strict", provenance=frozenset({"gemini"}), strict_keys=set())
is False
reg.resolve_trust("gemini", sensitivity="strict", provenance=frozenset({"gemini"}), strict_keys=set())
== "strict"
)
def test_assume_ai_always_relaxes(self):
assert reg.resolve_relax("gemini", sensitivity="assume_ai", provenance=frozenset(), strict_keys=set()) is True
def test_auto_relaxes_on_own_metadata(self):
assert (
reg.resolve_relax("gemini", sensitivity="auto", provenance=frozenset({"gemini"}), strict_keys=set()) is True
reg.resolve_trust("gemini", sensitivity="auto", provenance=frozenset({"gemini"}), strict_keys=set())
== "confirmed"
)
def test_auto_strict_without_evidence(self):
assert reg.resolve_relax("gemini", sensitivity="auto", provenance=frozenset(), strict_keys=set()) is False
assert reg.resolve_trust("gemini", sensitivity="auto", provenance=frozenset(), strict_keys=set()) == "strict"
def test_auto_cross_mark_same_product(self):
# a detected Jimeng wordmark relaxes the Jimeng pill (same product, other corner)
assert (
reg.resolve_relax("jimeng_pill", sensitivity="auto", provenance=frozenset(), strict_keys={"jimeng"}) is True
reg.resolve_trust("jimeng_pill", sensitivity="auto", provenance=frozenset(), strict_keys={"jimeng"})
== "confirmed"
)
def test_auto_no_cross_mark_across_products(self):
# a detected Jimeng wordmark must NOT relax Doubao (distinct products, same corner)
assert reg.resolve_relax("doubao", sensitivity="auto", provenance=frozenset(), strict_keys={"jimeng"}) is False
assert (
reg.resolve_trust("doubao", sensitivity="auto", provenance=frozenset(), strict_keys={"jimeng"}) == "strict"
)
def test_remove_auto_marks_accepts_all_sensitivities(self):
blank = np.zeros((256, 256, 3), np.uint8)
for s in ("auto", "strict", "assume_ai"):
for s in ("auto", "strict"):
_, removed = reg.remove_auto_marks(blank, sensitivity=s, backend="cv2")
assert removed == []
class TestNoBlanketRelaxation:
"""There is NO path that relaxes a mark's gate without same-product evidence.
``assume_ai`` was that path and was removed 2026-07-19: it bypassed every mark's
false-positive gate on the caller's bare assertion that the image is AI, which says
nothing about WHICH vendor or WHERE -- exactly what the bypass is contracted to
require. Before it carried a confidence floor it filled a phantom sparkle on 59.8%
of genuine camera photos. A user who can SEE a mark is served by `erase --region`
(they supply the coordinates) or `--mark <name> --no-detect` for a text mark.
"""
def test_sensitivity_has_exactly_two_levels(self):
import typing
assert set(typing.get_args(reg.Sensitivity)) == {"auto", "strict"}
def test_trust_ladder_has_no_assumed_level(self):
import typing
assert set(typing.get_args(reg.Trust)) == {"strict", "confirmed"}
def test_no_sensitivity_relaxes_without_same_product_evidence(self):
for sens in ("auto", "strict"):
assert reg.resolve_trust("gemini", sensitivity=sens, provenance=frozenset(), strict_keys=set()) == "strict"
def test_the_assumed_floor_helper_is_gone(self):
"""It existed only to make the blanket relaxation tolerable."""
assert not hasattr(reg, "assumed_floor_ok")
assert not hasattr(reg, "_ASSUMED_CONF_FLOOR")
def test_the_removed_value_raises_instead_of_silently_meaning_auto(self):
"""`Sensitivity` is a Literal and unenforced at runtime, so a 0.15 caller passing
the removed value would quietly get `auto` -- a silent semantic change on exactly
the release where they need to be told. The error names the replacement."""
import pytest
with pytest.raises(ValueError, match="erase"):
reg.validate_sensitivity("assume_ai")
with pytest.raises(ValueError, match="unknown sensitivity"):
reg.validate_sensitivity("aggressive")
assert reg.validate_sensitivity("auto") == "auto"
assert reg.validate_sensitivity("strict") == "strict"
def test_context_rejects_it_too(self):
"""The arbiter's own entry point validates, so a direct `decide()` caller cannot
smuggle the removed mode past the public API."""
import pytest
with pytest.raises(ValueError, match=r"removed in 0\.16"):
reg.Context(sensitivity="assume_ai")
class TestArbiter:
"""``decide`` is the PURE removal arbiter: (candidates, context) -> ordered
winners, no image / no I/O. Tested in isolation by handing it fabricated
@@ -223,11 +325,6 @@ class TestArbiter:
# relaxed-only detection must NOT fire under strict
assert self._keys([self._c("gemini", relaxed=True)], reg.Context(sensitivity="strict")) == set()
def test_assume_ai_uses_relaxed(self):
fired = reg.decide([self._c("gemini", relaxed=True)], reg.Context(sensitivity="assume_ai"))
assert [d.candidate.key for d in fired] == ["gemini"]
assert fired[0].relax is True
def test_auto_relaxes_on_provenance(self):
c = [self._c("gemini", relaxed=True)]
assert self._keys(c, reg.Context(provenance=frozenset({"gemini"}))) == {"gemini"}
@@ -246,6 +343,17 @@ class TestArbiter:
assert "doubao" in keys
assert "jimeng_pill" not in keys
def test_pill_dropped_on_qwen(self):
# A Qwen frame is TC260 too but is not Jimeng-basic either: a confident
# bottom-right 千问AI生成 detection suppresses the pill exactly like Doubao's.
cands = [
self._c("qwen", strict=True, relaxed=True),
self._c("jimeng_pill", strict=True, relaxed=True, flat=True),
]
keys = self._keys(cands, reg.Context(provenance=frozenset({"jimeng"})))
assert "qwen" in keys
assert "jimeng_pill" not in keys
def test_pill_metadata_arm_gated_on_flatness(self):
ctx = reg.Context(provenance=frozenset({"jimeng"}))
assert self._keys([self._c("jimeng_pill", strict=True, relaxed=True, flat=True)], ctx) == {"jimeng_pill"}
@@ -259,6 +367,35 @@ class TestArbiter:
]
assert "jimeng_pill" in self._keys(cands, reg.Context())
def test_weak_pill_detection_does_not_confirm_the_jimeng_wordmark(self):
"""The pill is too false-fire-prone (~7%) to grant a sibling `confirmed` trust.
Corpus-measured defect (2026-07-18): a pill false fire on clean non-ByteDance
content confirmed jimeng, relaxing its NCC gate 0.45 -> 0.3825; jimeng then
false-fired, and _keep_pill's wordmark arm removed the pill UNRESTRICTED,
skipping the flatness guard. Closed loop on the default `auto` path.
"""
# Only the pill is strictly detected. jimeng scores in the band that is
# reachable ONLY via the relaxed gate.
cands = [
self._c("jimeng_pill", strict=True, relaxed=True, flat=False),
self._c("jimeng", strict=False, relaxed=True),
]
fired = {d.candidate.key for d in reg.decide(cands, reg.Context("auto", frozenset()))}
assert "jimeng" not in fired, "a weak pill hit must not relax the jimeng wordmark"
# and with jimeng gone, the pill loses the wordmark arm too -- no unrestricted
# removal of a textured footprint on content nothing confirmed.
assert "jimeng_pill" not in fired
def test_real_jimeng_wordmark_still_corroborates_the_pill(self):
"""The fix removes only the pill's TESTIMONY, not the wordmark's."""
cands = [
self._c("jimeng", strict=True, relaxed=True),
self._c("jimeng_pill", strict=True, relaxed=True, flat=False),
]
fired = {d.candidate.key for d in reg.decide(cands, reg.Context("auto", frozenset()))}
assert fired == {"jimeng", "jimeng_pill"}
class TestProvenanceMaskThreading:
"""Regression for the provenance-relaxed Gemini no-op (#1) and the false 'removed'
Generated
+103 -95
View File
@@ -678,42 +678,51 @@ wheels = [
[[package]]
name = "cuda-toolkit"
version = "13.0.2"
version = "13.0.3.0"
source = { registry = "https://pypi.org/simple" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/57/b2/453099f5f3b698d7d0eab38916aac44c7f76229f451709e2eb9db6615dcd/cuda_toolkit-13.0.2-py2.py3-none-any.whl", hash = "sha256:b198824cf2f54003f50d64ada3a0f184b42ca0846c1c94192fa269ecd97a66eb", size = 2364, upload-time = "2025-12-19T23:24:07.328Z" },
{ url = "https://files.pythonhosted.org/packages/d1/c7/a79086a62c98befcdb8349656c6f114e2db3b8b2422f6e25c97a7f2a9a3c/cuda_toolkit-13.0.3.0-py2.py3-none-any.whl", hash = "sha256:d693caaa261214ddd7dbb60d68e71cbed884e68c2be7509778f3051da0b91c3f", size = 2512, upload-time = "2026-04-14T00:50:08.173Z" },
]
[package.optional-dependencies]
cublas = [
{ name = "nvidia-cublas", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" },
{ name = "nvidia-cuda-nvrtc", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" },
]
cudart = [
{ name = "nvidia-cuda-runtime", marker = "sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "nvidia-cuda-runtime", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" },
]
cufft = [
{ name = "nvidia-cufft", marker = "sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "nvidia-cufft", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" },
{ name = "nvidia-nvjitlink", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" },
]
cufile = [
{ name = "nvidia-cufile", marker = "sys_platform == 'linux'" },
{ name = "nvidia-cufile", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
]
cupti = [
{ name = "nvidia-cuda-cupti", marker = "sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "nvidia-cuda-cupti", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" },
]
curand = [
{ name = "nvidia-curand", marker = "sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "nvidia-curand", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" },
]
cusolver = [
{ name = "nvidia-cusolver", marker = "sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "nvidia-cublas", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" },
{ name = "nvidia-cusolver", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" },
{ name = "nvidia-cusparse", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" },
{ name = "nvidia-nvjitlink", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" },
]
cusparse = [
{ name = "nvidia-cusparse", marker = "sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "nvidia-cusparse", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" },
{ name = "nvidia-nvjitlink", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" },
]
nvjitlink = [
{ name = "nvidia-nvjitlink", marker = "sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "nvidia-nvjitlink", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" },
]
nvrtc = [
{ name = "nvidia-cuda-nvrtc", marker = "sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "nvidia-cuda-nvrtc", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" },
]
nvtx = [
{ name = "nvidia-nvtx", marker = "sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "nvidia-nvtx", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" },
]
[[package]]
@@ -1020,7 +1029,7 @@ wheels = [
[[package]]
name = "huggingface-hub"
version = "1.22.0"
version = "1.23.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "click" },
@@ -1033,9 +1042,9 @@ dependencies = [
{ name = "tqdm" },
{ name = "typing-extensions" },
]
sdist = { url = "https://files.pythonhosted.org/packages/77/ea/dc54b4dda5841cb3a7812a178695be776e7c15c597887c2ed892f17d015a/huggingface_hub-1.22.0.tar.gz", hash = "sha256:e2dfe5fe1ec3b87ba2709aa34555b23e3f3f6ad4d7255238e13ddb8348e6bbfa", size = 914232, upload-time = "2026-07-03T09:46:44.685Z" }
sdist = { url = "https://files.pythonhosted.org/packages/1a/8f/999e4dda11c6187c78f090eac00895a47e11a0049308f07579bcb7aa3aa2/huggingface_hub-1.23.0.tar.gz", hash = "sha256:c04997fb8bbdace1e57b7703d30ed7678af51f70d00d241819ff411b92ae9a88", size = 919163, upload-time = "2026-07-09T14:49:32.315Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/64/9c/a1a377265abd8b823a2c661c665028ccb6b9fba1ca9d08e52ff679c20ecd/huggingface_hub-1.22.0-py3-none-any.whl", hash = "sha256:b09e19309ae09ee0a71892701c4fe70af39ab4e00817321dc62f2289a977249b", size = 765085, upload-time = "2026-07-03T09:46:42.832Z" },
{ url = "https://files.pythonhosted.org/packages/f1/ce/13b2ba57838b8db1e6bd033c1b21ce0b9f6153b87d4e4939f77074e41eb0/huggingface_hub-1.23.0-py3-none-any.whl", hash = "sha256:b1d604788f5adc7f0eb246e03e0ec19011ca06e38400218c347dccc3dffa64a2", size = 770336, upload-time = "2026-07-09T14:49:30.597Z" },
]
[[package]]
@@ -2750,7 +2759,7 @@ wheels = [
[[package]]
name = "remove-ai-watermarks"
version = "0.15.0"
version = "0.19.0"
source = { editable = "." }
dependencies = [
{ name = "c2pa-python" },
@@ -2887,27 +2896,27 @@ wheels = [
[[package]]
name = "ruff"
version = "0.15.20"
version = "0.15.21"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/43/dc/35b341fc554ba02f217fc10da57d1a75168cfbcf75b0ef2202176d4c4f2d/ruff-0.15.20.tar.gz", hash = "sha256:1416eb04349192646b54de98f146c4f59afe37d0decfc02c3cbbf396f3a28566", size = 4755489, upload-time = "2026-06-25T17:20:37.578Z" }
sdist = { url = "https://files.pythonhosted.org/packages/0f/36/6f65aa9989acdec45d417192d8f4e7921931d8a6cf87ac74bce3eed98a8e/ruff-0.15.21.tar.gz", hash = "sha256:d0cfc841c572283c36548f82664a54ce6565567f1b0d5b4cf2caac693d8b7500", size = 4769401, upload-time = "2026-07-09T20:01:34.005Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/94/d9/2d5014f0253ba541d2061d9fa7193f48e941c8b21bb88a7ff9bbe0bd0596/ruff-0.15.20-py3-none-linux_armv6l.whl", hash = "sha256:00e188c53e499c3c1637f73c91dcf2fb56d576cab76ce1be50a27c4e80e37078", size = 10839665, upload-time = "2026-06-25T17:19:44.702Z" },
{ url = "https://files.pythonhosted.org/packages/c6/d3/ac1798ba64f670698867fcfc591d50e7e421bef137db564858f619a30fcf/ruff-0.15.20-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:9ebd1fd9b9c95fc0bd7b2761aebec1f030013d2e193a2901b224af68fe47251b", size = 11208649, upload-time = "2026-06-25T17:19:48.787Z" },
{ url = "https://files.pythonhosted.org/packages/47/47/d3ac899991202095dfcf3d5176be4272642be3cf981a2f1a30f72a2afb95/ruff-0.15.20-py3-none-macosx_11_0_arm64.whl", hash = "sha256:c5b16cdd67ca108185cd36dce98c576350c03b1660a751de725fb049193a0632", size = 10622638, upload-time = "2026-06-25T17:19:51.354Z" },
{ url = "https://files.pythonhosted.org/packages/33/13/4e043fe30aa94d4ff5213a9881fc296d12960f5971b234a5263fdc225312/ruff-0.15.20-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3413bb3c3d2ca6a8208f1f4809cd2dca3c6de6d0b491c0e70847672bde6e6efd", size = 10984227, upload-time = "2026-06-25T17:19:54.044Z" },
{ url = "https://files.pythonhosted.org/packages/76/e6/92e7bf40388bc5800073b96564f56264f7e48bfd1a498f5ced6ae6d5a769/ruff-0.15.20-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:bd7ec42b3bb3da066488db093308a69c4ac5ee6d2af333a86ba6e2eb2e7dd44b", size = 10622882, upload-time = "2026-06-25T17:19:57.037Z" },
{ url = "https://files.pythonhosted.org/packages/13/7a/43460be3f24495a3aa46d4b16873e2c4941b3b5f0b00cf88c03b7b94b339/ruff-0.15.20-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e1a36ad0eb77fba9aabfb69ede54de6f376d04ac18ebea022847046d340a8267", size = 11474808, upload-time = "2026-06-25T17:20:00.357Z" },
{ url = "https://files.pythonhosted.org/packages/27/a0/f37077884873221c6b33b4ab49eb18f9f88e54a16a25a5bca59bef46dd66/ruff-0.15.20-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:b6df3b1e4610432f0386dba04d853b5f08cbbc903410c6fcc02f620f05aff53c", size = 12293094, upload-time = "2026-06-25T17:20:03.446Z" },
{ url = "https://files.pythonhosted.org/packages/a6/74/165545b60256a9704c21ac0ec4a0d07933b320812f9584836c9f4aca4292/ruff-0.15.20-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e89f198a1ea6ef0d727c1cf16088bc91a6cb0ab947dedc966715691647186eae", size = 11526176, upload-time = "2026-06-25T17:20:06.301Z" },
{ url = "https://files.pythonhosted.org/packages/86/b1/a976a136d40ade83ce743578399865f57001003a409acadc0ecbb3051082/ruff-0.15.20-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:309809086c2acb67624950a3c8133e80f32d0d3e27106c0cd60ff26657c9f24b", size = 11520767, upload-time = "2026-06-25T17:20:09.191Z" },
{ url = "https://files.pythonhosted.org/packages/19/0f/f032696cb01c9b54c0263fa393474d7758f1cdc021a01b04e3cbc2500999/ruff-0.15.20-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:2d2374caa2f2c2f9e2b7da0a50802cfb8b79f55a9b5e49379f564544fbf56487", size = 11500132, upload-time = "2026-06-25T17:20:13.602Z" },
{ url = "https://files.pythonhosted.org/packages/4b/f4/51b1a14bc69e8c224b15dab9cce8e99b425e0455d462caa2b3c9be2b6a8e/ruff-0.15.20-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:a1ed17b65293e0c2f22fc387bc13198a5de94bf4429589b0ff6946b0feaf21a3", size = 10943828, upload-time = "2026-06-25T17:20:16.635Z" },
{ url = "https://files.pythonhosted.org/packages/71/4b/fe267640783cd02bf6c5cc290b1df1051be2ec294c678b5c15fe19e52343/ruff-0.15.20-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:f701305e66b38ea6c91882490eb73459796808e4c6362a1b765255e0cdcd4053", size = 10645418, upload-time = "2026-06-25T17:20:19.4Z" },
{ url = "https://files.pythonhosted.org/packages/b0/c0/a65aa4ec2f5e87a1df32dc3ec1fede434fe3dfd5cbcf3b503cafc676ab54/ruff-0.15.20-py3-none-musllinux_1_2_i686.whl", hash = "sha256:5b9c0c367ad8e5d0d5b5b8537864c469a0a0e55417aadfbeca41fa61333be9f4", size = 11211770, upload-time = "2026-06-25T17:20:22.033Z" },
{ url = "https://files.pythonhosted.org/packages/5a/a4/0caa331d954ae2723d729d351c989cb4ca8b6077d5c6c2cb6de75e98c041/ruff-0.15.20-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:01cc00dd58f0df339d0e902219dd53990ea99996a0344e5d9cc8d45d5307e460", size = 11618698, upload-time = "2026-06-25T17:20:25.259Z" },
{ url = "https://files.pythonhosted.org/packages/10/9b/5f14927848d2fd4aa891fd88d883788c5a7baba561c7874732364045708c/ruff-0.15.20-py3-none-win32.whl", hash = "sha256:ed65ef510e43a137207e0f01cfcf998aeddb1aeeda5c9d35023e910284d7cf21", size = 10857322, upload-time = "2026-06-25T17:20:28.612Z" },
{ url = "https://files.pythonhosted.org/packages/fa/f0/fe47c501f9dea92a26d788ff98bb5d92ed4cb4c88792c5c88af6b697dc8e/ruff-0.15.20-py3-none-win_amd64.whl", hash = "sha256:a525c81c70fb0380344dd1d8745d8cc1c890b7fc94a58d5a07bd8eb9557b8415", size = 11993274, upload-time = "2026-06-25T17:20:31.871Z" },
{ url = "https://files.pythonhosted.org/packages/d7/2b/9555445e1201d92b3195f45cdb153a0b68f24e0a4273f6e3d5ab46e212bb/ruff-0.15.20-py3-none-win_arm64.whl", hash = "sha256:2f5b2a6d614e8700388806a14996c40fab2c47b819ef57d790a34878858ed9ca", size = 11343498, upload-time = "2026-06-25T17:20:35.03Z" },
{ url = "https://files.pythonhosted.org/packages/d0/c6/ede15cac6839f3dbce52565c8f5164a8210e669c7bc4decb03e5bdf47d0d/ruff-0.15.21-py3-none-linux_armv6l.whl", hash = "sha256:63ea0e965e5d73c90e95b2434beeafc70820536717f561b32ab6e777cb9bdf5d", size = 10854342, upload-time = "2026-07-09T20:00:53.998Z" },
{ url = "https://files.pythonhosted.org/packages/28/9d/d825b07ee7ea9e2d61df92a860033c94e06e7300d50a1c2653aac27d24fe/ruff-0.15.21-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:0f212c5d7d54c01bbfe6dcab02b724a39300f3e34ed7acbe995ccb320a2c58bd", size = 11139539, upload-time = "2026-07-09T20:00:57.809Z" },
{ url = "https://files.pythonhosted.org/packages/f5/de/3b107712e642f063c7a9e0887c427b22cb44097de5aab36c05f2e280670c/ruff-0.15.21-py3-none-macosx_11_0_arm64.whl", hash = "sha256:e6312e41bc96791299614995ea3a977c5857c3b5662b1ecef6755b02b87cb646", size = 10595437, upload-time = "2026-07-09T20:01:00.006Z" },
{ url = "https://files.pythonhosted.org/packages/9a/6f/b4523cc90ba239ede441447a19d0c968846a3012e5a0b0c5b62831a3d5e3/ruff-0.15.21-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:01d65b4831c6b2a4ba8ee6faa84049d44d982b7a706e622c4094c509e51673be", size = 10990053, upload-time = "2026-07-09T20:01:02.187Z" },
{ url = "https://files.pythonhosted.org/packages/92/cc/c6a9872a5375f0628875481cf2f66b13d7d865bf3ca2e57f91c7e762d976/ruff-0.15.21-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:2c5a913a589120ce67933d5d05fd6ddbcc2481c6a054980ee767f7414c72b4fd", size = 10666096, upload-time = "2026-07-09T20:01:04.299Z" },
{ url = "https://files.pythonhosted.org/packages/ab/97/c621f7a17e097f1790fa3af6374138823b330b2d03fc38337945daca212c/ruff-0.15.21-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:5ef04b681d02ad4dc9620f00f83ac5c22f652d0e9a9cfe431d219b16ad5ccc41", size = 11537011, upload-time = "2026-07-09T20:01:06.771Z" },
{ url = "https://files.pythonhosted.org/packages/ea/51/d928727e476e25ccc57c6f449ffd80241a651a973ad949d39cfb2a771d28/ruff-0.15.21-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:16d090c0740916594157e75b80d666eab8e78083b39b3b0e1d698f4670a17b86", size = 12347101, upload-time = "2026-07-09T20:01:08.859Z" },
{ url = "https://files.pythonhosted.org/packages/1e/88/8cd62026802b16018ad06931d87997cf795ba2a6239ab659606c87d96bf0/ruff-0.15.21-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:3a10e74757dd65004d779b73e2f3c5210156d9980b41224d50d2ebcf1db51e67", size = 11572001, upload-time = "2026-07-09T20:01:11.092Z" },
{ url = "https://files.pythonhosted.org/packages/b2/97/f63084cf55444fc110e8cb985ebfcc592af47f597d44453d778cb81bc156/ruff-0.15.21-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bab0905d2f29e0d9fbc3c373ed23db0095edaa3f71f1f4f519ec15134d9e85c8", size = 11549239, upload-time = "2026-07-09T20:01:13.27Z" },
{ url = "https://files.pythonhosted.org/packages/9d/77/f107da4a2874b7715914b03f09ba9c54424de3ff8a1cc5d015d3ee2ce0ac/ruff-0.15.21-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:00eca240af5789fec6fe7df74c088cc1f9644ed83027113468efba7c92b94075", size = 11535340, upload-time = "2026-07-09T20:01:15.206Z" },
{ url = "https://files.pythonhosted.org/packages/d5/e9/601deb322d3303a7bf212b0100ead6f2ee3f6a044d89c30f2f92bf83c731/ruff-0.15.21-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:262ab31557a75141325e32d3357f3597645a7f084e732b6b054dde428ecd9341", size = 10964048, upload-time = "2026-07-09T20:01:17.723Z" },
{ url = "https://files.pythonhosted.org/packages/ea/2e/0f2176d1e99c15192caea19c8c3a0a955246b4cb4de795042eeb616345cd/ruff-0.15.21-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:659c4e7a4212f83306045ec7c5e5a356d16d9a6ef4ae0c7a4d872914fc655d9d", size = 10667055, upload-time = "2026-07-09T20:01:19.73Z" },
{ url = "https://files.pythonhosted.org/packages/48/60/abd74a02e0c4214f12a68becfd30af7165cfdcb0e661ecdc60bbb949c09a/ruff-0.15.21-py3-none-musllinux_1_2_i686.whl", hash = "sha256:9e866eab611a5f959d36df2d10e446973a3610bc42b0c15b31dc27977d59c233", size = 11242043, upload-time = "2026-07-09T20:01:21.947Z" },
{ url = "https://files.pythonhosted.org/packages/b2/c6/583075d8ccabb4b229345edcaf1545eb3d8d6be90f686a479d7e94088bbf/ruff-0.15.21-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:e89bc93c0d3803ba870b55c29671bad9dc6d94bb1eb181b056b52eb05b52854f", size = 11648064, upload-time = "2026-07-09T20:01:24.023Z" },
{ url = "https://files.pythonhosted.org/packages/3a/3c/37d0ecb729a7cc2d393ea7dce316fc585680f35d93b8d62139d7d0a3700c/ruff-0.15.21-py3-none-win32.whl", hash = "sha256:01f8d5be84823c172b389e123174f781f9daf86d6c58719d603f941932195cdd", size = 10896555, upload-time = "2026-07-09T20:01:26.941Z" },
{ url = "https://files.pythonhosted.org/packages/c0/b8/e43466b2a6067ce91e669068f6e28d6c719a920f014b070d5c8731725de3/ruff-0.15.21-py3-none-win_amd64.whl", hash = "sha256:d4b8d9a2f0f12b816b50447f6eccb9f4bb01a6b82c86b50fb3b5354b458dc6d3", size = 12038772, upload-time = "2026-07-09T20:01:29.497Z" },
{ url = "https://files.pythonhosted.org/packages/dd/75/e90ab9aeece218a9fc5a5bc3ec97d0ee6bb3c4ff95869463c1de58e29a1c/ruff-0.15.21-py3-none-win_arm64.whl", hash = "sha256:6e83115d4b9377c1cbc13abf0e051f069fab0ef815ea0504a8a008cee24dd0a8", size = 11375265, upload-time = "2026-07-09T20:01:31.772Z" },
]
[[package]]
@@ -2936,11 +2945,11 @@ wheels = [
[[package]]
name = "setuptools"
version = "81.0.0"
version = "83.0.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/0d/1c/73e719955c59b8e424d015ab450f51c0af856ae46ea2da83eba51cc88de1/setuptools-81.0.0.tar.gz", hash = "sha256:487b53915f52501f0a79ccfd0c02c165ffe06631443a886740b91af4b7a5845a", size = 1198299, upload-time = "2026-02-06T21:10:39.601Z" }
sdist = { url = "https://files.pythonhosted.org/packages/34/26/f5d29e25ffdb535afef2d35cdb55b325298f96debd670da4c325e08d70f4/setuptools-83.0.0.tar.gz", hash = "sha256:025bccbbf0fa05b6192bc64ae1e7b16e001fd6d6d4d5de03c97b1c1ade523bef", size = 1154254, upload-time = "2026-07-04T15:31:22.699Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/e1/e3/c164c88b2e5ce7b24d667b9bd83589cf4f3520d97cad01534cd3c4f55fdb/setuptools-81.0.0-py3-none-any.whl", hash = "sha256:fdd925d5c5d9f62e4b74b30d6dd7828ce236fd6ed998a08d81de62ce5a6310d6", size = 1062021, upload-time = "2026-02-06T21:10:37.175Z" },
{ url = "https://files.pythonhosted.org/packages/5d/40/e1e72872c6354b306daef1703549e8e83b4d43cfea356311bf722a043752/setuptools-83.0.0-py3-none-any.whl", hash = "sha256:29b23c360f22f414dc7336bb39178cc7bcbf6021ed2733cde173f09dba19abb3", size = 1008090, upload-time = "2026-07-04T15:31:20.885Z" },
]
[[package]]
@@ -3115,51 +3124,50 @@ wheels = [
[[package]]
name = "torch"
version = "2.12.1"
version = "2.13.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "cuda-bindings", marker = "sys_platform == 'linux'" },
{ name = "cuda-toolkit", extra = ["cudart", "cufft", "cufile", "cupti", "curand", "cusolver", "cusparse", "nvjitlink", "nvrtc", "nvtx"], marker = "sys_platform == 'linux'" },
{ name = "cuda-bindings", marker = "python_full_version < '3.15' and sys_platform == 'linux'" },
{ name = "cuda-toolkit", extra = ["cublas", "cudart", "cufft", "cufile", "cupti", "curand", "cusolver", "cusparse", "nvjitlink", "nvrtc", "nvtx"], marker = "sys_platform == 'linux'" },
{ name = "filelock" },
{ name = "fsspec" },
{ name = "jinja2" },
{ name = "networkx", version = "3.4.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
{ name = "networkx", version = "3.6.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },
{ name = "nvidia-cublas", marker = "sys_platform == 'linux'" },
{ name = "nvidia-cudnn-cu13", marker = "sys_platform == 'linux'" },
{ name = "nvidia-cusparselt-cu13", marker = "sys_platform == 'linux'" },
{ name = "nvidia-nccl-cu13", marker = "sys_platform == 'linux'" },
{ name = "nvidia-nvshmem-cu13", marker = "sys_platform == 'linux'" },
{ name = "setuptools" },
{ name = "sympy" },
{ name = "triton", marker = "sys_platform == 'linux'" },
{ name = "triton", marker = "python_full_version < '3.15' and sys_platform == 'linux'" },
{ name = "typing-extensions" },
]
wheels = [
{ url = "https://files.pythonhosted.org/packages/db/ed/ff0c4f8cef63977a646dc80e40c05cae873f4097b12dc87e1cd7e1cecf42/torch-2.12.1-cp310-cp310-macosx_14_0_arm64.whl", hash = "sha256:ec56e82be6a8b0c036771a77f7d32ad3c299770571af9815b3dafe61434389d5", size = 87967927, upload-time = "2026-06-17T21:08:43.16Z" },
{ url = "https://files.pythonhosted.org/packages/85/1b/c8ecf60c9dba535f9ea341c359c600c0bd877a7ca14b3296f13316321847/torch-2.12.1-cp310-cp310-manylinux_2_28_aarch64.whl", hash = "sha256:42cd7339bf266f14944710e8274be63e7e012bb937834a8d85a8327a9860eba6", size = 426366829, upload-time = "2026-06-17T21:07:18.574Z" },
{ url = "https://files.pythonhosted.org/packages/ab/d6/73d4a3f27e00526e98086f3a64ab609af1345cca62367749fbc3c8e4b83c/torch-2.12.1-cp310-cp310-manylinux_2_28_x86_64.whl", hash = "sha256:a7817f0f89a796d9de239d06f69faf5d7e19a6a5db6710a5ead777c912f9f50a", size = 532144834, upload-time = "2026-06-17T21:08:00.633Z" },
{ url = "https://files.pythonhosted.org/packages/e3/51/4010c8fa6f9d1f42c054a321970ca95ec58e4e4494f5b53a34c3f3c9e310/torch-2.12.1-cp310-cp310-win_amd64.whl", hash = "sha256:2af3d9cc866e0a15ae7635ff0a9c61d6624a353ad657f5bcd8d86c26cdc64693", size = 122949863, upload-time = "2026-06-17T21:08:39.016Z" },
{ url = "https://files.pythonhosted.org/packages/59/38/7028d3be540f1dcdf41660a2b01d0c51d2cb73915fe370d84e4d277a6d47/torch-2.12.1-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:ef81f503912effea2ce3d9b12a2e3a6ed488943e91271c90c7a829f60baf6aa2", size = 87975425, upload-time = "2026-06-17T21:08:34.094Z" },
{ url = "https://files.pythonhosted.org/packages/5a/e3/750b3e3548635ceac03ba255daa26dbc7ed66ca3484dc4b4d955ab7f4501/torch-2.12.1-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:107df6888624bdea41508f9aeb6149d9333c737a5530ceecb56c904e811369ae", size = 426379894, upload-time = "2026-06-17T21:06:55.077Z" },
{ url = "https://files.pythonhosted.org/packages/dc/ca/ed24783da629ff3e640ba3f70a7639e9045d3d88b93ee6bc47b8a28a1f2c/torch-2.12.1-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:6e29e7e74d05bda7d955c75e99459f878ebd970ef851b4057edbd3b34a5eb4a3", size = 532169264, upload-time = "2026-06-17T21:08:17.65Z" },
{ url = "https://files.pythonhosted.org/packages/46/61/c63f0158446f3a98ea672b004d761b848911eba567ea4a624c7db5aadc04/torch-2.12.1-cp311-cp311-win_amd64.whl", hash = "sha256:a513506cfda3c1c78dabeb6574c1597538c0254b3d39af174dde35d8177f4ce3", size = 122953086, upload-time = "2026-06-17T21:08:27.69Z" },
{ url = "https://files.pythonhosted.org/packages/f0/54/efb7ebca77970012b0cc21687a55d70eb2ba514b2c2b8e18d9fb1222f3be/torch-2.12.1-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:d2dd0f2c5f7ccbddaf34cade0deaf476808368f902b9cdb7f36a2ab42301bc0e", size = 87991951, upload-time = "2026-06-17T21:07:49.309Z" },
{ url = "https://files.pythonhosted.org/packages/1e/00/4210d76ca7424981f04033ebe7e48816ab83287a62538747a58825db770c/torch-2.12.1-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:2de4e19b88a481482c6c75291f2d6a52eda3ce51f311b29aa9b68499c830c07c", size = 426382721, upload-time = "2026-06-17T21:06:41.842Z" },
{ url = "https://files.pythonhosted.org/packages/76/1f/bc9f5a5aa569307076365f25afcebacb22e9c754b1bcfbaaa146627c7fda/torch-2.12.1-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:649e4ced014ba646f76f8cb9c9726735a6323eb321b7919f942790a923f90921", size = 532261322, upload-time = "2026-06-17T21:06:06.673Z" },
{ url = "https://files.pythonhosted.org/packages/9e/49/c549461daa008159d006a76a991fbc2f26fa8bac27a4030c858463dcb20f/torch-2.12.1-cp312-cp312-win_amd64.whl", hash = "sha256:e86550597877fb272ddc52db2f85b82cb601ea7bd932576a0340152cae2200b3", size = 122988095, upload-time = "2026-06-17T21:07:44.9Z" },
{ url = "https://files.pythonhosted.org/packages/ff/4a/0300261818e1560d72cc160ac826005507e8b7ca0a35788b591436d05b4a/torch-2.12.1-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:c75e93173c700bccd6bfcc4a9d19ce242ab6dacd1f1781483027a16239b9e650", size = 87992358, upload-time = "2026-06-17T21:07:40.299Z" },
{ url = "https://files.pythonhosted.org/packages/30/a7/874a5ca05e8f159211dca7921060f7057acc1adb26431e119fd150623efc/torch-2.12.1-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:fcb61ccd20784b62bdd78ec84238a5cfb383b4994902e03bac95505ab360884c", size = 426386134, upload-time = "2026-06-17T21:07:31.481Z" },
{ url = "https://files.pythonhosted.org/packages/e1/75/20bb8fe9c1ad6538cce8cd0391b51927ae5af0b17ed1eab44b8824465dc1/torch-2.12.1-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:f4afc8083dff08719edbea346644476e3cec0cf40ebe256be0ee5d5b7c7e8c0d", size = 532268019, upload-time = "2026-06-17T21:05:37.925Z" },
{ url = "https://files.pythonhosted.org/packages/d1/fa/824ddb662af55b2eabc0dbb7b57c7c0b1bcd93693754a2b8509ec4d16490/torch-2.12.1-cp313-cp313-win_amd64.whl", hash = "sha256:f92609e3b3ce72f25e2eb780d043ced2480c1a86c47c852604fc7a9108648386", size = 122987777, upload-time = "2026-06-17T21:07:09.49Z" },
{ url = "https://files.pythonhosted.org/packages/63/b7/1b49fe7086ea36839cc80abc43174c43d0ab6f676c0891c871c162f44fe3/torch-2.12.1-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:e9b6f7d2dd66ea87a3ae620069d31335d594c06effb1a383bdd21cfe61e44ece", size = 88010025, upload-time = "2026-06-17T21:07:03.934Z" },
{ url = "https://files.pythonhosted.org/packages/d7/06/5b44063a6545036dcc680d2d303b137d9176cfb2cc1e1863e3ef94abeb52/torch-2.12.1-cp314-cp314-manylinux_2_28_aarch64.whl", hash = "sha256:7973ccd3d2cd35c74449213f7bded199bec6c6247e705cbeda7407af79703d91", size = 426392891, upload-time = "2026-06-17T21:05:52.261Z" },
{ url = "https://files.pythonhosted.org/packages/f8/dd/c9ce9a4b0eb3c5bb92d9ea56766e2c22559f0b45171149188494edcce80f/torch-2.12.1-cp314-cp314-manylinux_2_28_x86_64.whl", hash = "sha256:c64ac4aac16be5e296dcd912305605804b203333c690bf98c55bc09494ee92ad", size = 532272494, upload-time = "2026-06-17T21:06:22.72Z" },
{ url = "https://files.pythonhosted.org/packages/21/7c/f3a601fc1b1f663ff269bfe553654e638651939aa6563e8daa7167c33098/torch-2.12.1-cp314-cp314-win_amd64.whl", hash = "sha256:f6dc4caf7eb4adb38a2d9f536b51db56310fdd1254e69a2d96767e1367c892b3", size = 122987254, upload-time = "2026-06-17T21:06:33.199Z" },
{ url = "https://files.pythonhosted.org/packages/e6/8c/b8087556cf81ddd808dbeb34afb8396d7ae7a1694ab489f08b1a0004e7d0/torch-2.12.1-cp314-cp314t-macosx_14_0_arm64.whl", hash = "sha256:2afbb2bdaa8a95040e733f05492ddf133c3967c9b7ce0abd218d704b6cab437d", size = 88303173, upload-time = "2026-06-17T21:05:06.603Z" },
{ url = "https://files.pythonhosted.org/packages/4a/07/fe09d1699fbed2afa10ebc692ff2b99d113f2605b6748cea633989e2789a/torch-2.12.1-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:97eba061fcb042fed191400b15568990073d67eaacaa6ee9b7ca01dd8b790fe9", size = 426404009, upload-time = "2026-06-17T21:04:57.557Z" },
{ url = "https://files.pythonhosted.org/packages/2e/f7/0ce4f6c1962c60ded7270e0a9eb560fb615c92b89d332cf9e3dff36d5ecc/torch-2.12.1-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:3867b861391701012adb2df93360efb88494dca245a185e3bb7624495cfe3f33", size = 532184292, upload-time = "2026-06-17T21:05:17.526Z" },
{ url = "https://files.pythonhosted.org/packages/70/db/e384c12aba30320ca92aaaf557456cbcb26f04b4df307728bb8f019f5000/torch-2.12.1-cp314-cp314t-win_amd64.whl", hash = "sha256:dd15595f8fc764cffde8c6361a3beb6ef69a028c851b1b3e70e077f615980d4e", size = 123231142, upload-time = "2026-06-17T21:05:27.061Z" },
{ url = "https://files.pythonhosted.org/packages/7f/e7/19894fdb51c7dbaf94f5a79bb0871da0992e8e4241e579cb006da46d2e58/torch-2.13.0-cp310-cp310-macosx_14_0_arm64.whl", hash = "sha256:94f0de129916f77b8dc2c7a8eff644cfeddfe59e39c9f55e9f6e17543410281d", size = 111178962, upload-time = "2026-07-08T16:05:49.855Z" },
{ url = "https://files.pythonhosted.org/packages/d1/5c/b1d5de470c54e339b30a92d96683a71bcebd78f5f2a7fc714cd6dc6bbd68/torch-2.13.0-cp310-cp310-manylinux_2_28_aarch64.whl", hash = "sha256:0ab4b69f3ee03a62a002cfbf77b1ca5e88aceb4ea64cb4388bb28f638ddbb045", size = 427198333, upload-time = "2026-07-08T16:05:36.847Z" },
{ url = "https://files.pythonhosted.org/packages/50/c0/68a84105e1fcb8970144b388ff3d3e5dc15a3be28c1e247841f7d7247e41/torch-2.13.0-cp310-cp310-manylinux_2_28_x86_64.whl", hash = "sha256:c78b7b4d04461855a764cf01bae9a462bb88bc93defcfa11235cbc8fdf3e12c4", size = 526555154, upload-time = "2026-07-08T16:05:06.507Z" },
{ url = "https://files.pythonhosted.org/packages/2e/c9/0bb9d097b03cbaf96bb75b15e867347b8e41bfcdfe0539452d17d9e63993/torch-2.13.0-cp310-cp310-win_amd64.whl", hash = "sha256:2bd30b6b730d987fa386ce3898933762c5cb8cc82eb0535211d787cc3ce2dfeb", size = 122015602, upload-time = "2026-07-08T16:05:45.25Z" },
{ url = "https://files.pythonhosted.org/packages/5b/fe/cba54dc58523434919b66f13a667e36e436deddd77ca519e96553617d4ec/torch-2.13.0-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:e76f9bcecc52b8ff711239a2f7547d5353df95878ab232f0773c1d95928b92f8", size = 111187938, upload-time = "2026-07-08T16:05:17.065Z" },
{ url = "https://files.pythonhosted.org/packages/c2/59/1e3160e18e12aa3038390efab3ce02b36a9d4d6a527ecdd8520dca2e68d8/torch-2.13.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:092790c696a760c729fd5722835f50b9d81fd7c8f141571f3f3cf4081a8f664c", size = 427199369, upload-time = "2026-07-08T16:04:51.054Z" },
{ url = "https://files.pythonhosted.org/packages/01/79/1f2d34ad7034ee1c7ffc1cf8bf0f8213af2a81df6ecdb3997ecec107c09d/torch-2.13.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:60fcdcb2f3876e21146cb4524ef06397d727ca9ad5f020818547e25075fe3cb7", size = 526574961, upload-time = "2026-07-08T16:04:07.075Z" },
{ url = "https://files.pythonhosted.org/packages/6c/fd/0f2ce40f58aefbdb3392f9acce3c8171940943ae2d661f70558bfa73befb/torch-2.13.0-cp311-cp311-win_amd64.whl", hash = "sha256:a0d8b11f16a48d60e2015d8213aa0390744cbebb98e58b62b3514dddc656e330", size = 122015870, upload-time = "2026-07-08T16:05:27.59Z" },
{ url = "https://files.pythonhosted.org/packages/c4/3a/ed0f4d4d1dcde03bced7aac9a28e800abcdc0cbd06b6775044c9fbd877b7/torch-2.13.0-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:2fe228aba290d14b9f31b049be550dbd469c3fd3013d7a19705b30454da97027", size = 111213045, upload-time = "2026-07-08T16:05:22.997Z" },
{ url = "https://files.pythonhosted.org/packages/df/a9/f6a2a4d763ff1df02e9a64c477029db614295bc9367f4131223791ccc243/torch-2.13.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:572df8be8ffb4599c88cbd6a0726f1f854f4da65d2e3c09f0e2c2283333cd6d4", size = 427210998, upload-time = "2026-07-08T16:04:37.708Z" },
{ url = "https://files.pythonhosted.org/packages/f3/82/fea946351658e6534db52d2cc12bc53087cbf87f9440c5f180f367c1950b/torch-2.13.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:796633c4cdf0fe2cdced72d8f88f22e73dbcfce83132763162f6d4bff13b820b", size = 526605292, upload-time = "2026-07-08T16:04:22.81Z" },
{ url = "https://files.pythonhosted.org/packages/21/d6/e8f3c6f7e01f626f77259de9860d2a78bc84c40539e28e79b7e98b0bb659/torch-2.13.0-cp312-cp312-win_amd64.whl", hash = "sha256:024c6cc0c1b085f2f91f20a3dc27b0471d021c31ce84b81be3afdc39f791fd9d", size = 122057313, upload-time = "2026-07-08T16:03:53.43Z" },
{ url = "https://files.pythonhosted.org/packages/0d/fa/c1c10b7aff4a9a3e8956d4f0a5f468fa6db7abc3208805719076772b4833/torch-2.13.0-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:33449899ce5496c1b84b4853179d94fd102028ae1407314d9fb956bb79e70d09", size = 111213743, upload-time = "2026-07-08T16:03:28.579Z" },
{ url = "https://files.pythonhosted.org/packages/11/18/9ecb37b56293a0be8d80f810bf672a72fe7e02f8b475d5ef1b9bf8a0d748/torch-2.13.0-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:1e09d6a722504957c694faceca843acde562786df1144ebcc5a74075ec7f6005", size = 427213008, upload-time = "2026-07-08T16:03:44.106Z" },
{ url = "https://files.pythonhosted.org/packages/d4/5a/7c50ba1b7b713d71d34669c6d13dab0a11531a3eceb0307a5162dbfec0f7/torch-2.13.0-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:a3a9a21312872af8a26950b2c15680335a386a1f56ed03e780653d78b9607e9e", size = 526602329, upload-time = "2026-07-08T16:03:12.649Z" },
{ url = "https://files.pythonhosted.org/packages/91/3d/e7adcc6aaf36961cd18f56cf8ad0f3058c3a5c84ccf391762176c94581b8/torch-2.13.0-cp313-cp313-win_amd64.whl", hash = "sha256:49b58f1e2c52440abb6f17c28f0335fe6c6d01ad1a7f55b0183b81e4b34d64e6", size = 122057920, upload-time = "2026-07-08T16:03:01.808Z" },
{ url = "https://files.pythonhosted.org/packages/36/76/6dcc7f0c07052102dd36f83cbc5800842a909c8c3fbf1a7f8a5844954de9/torch-2.13.0-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:d849b390e07d8d333ce8ecaf91b273c656c598379a19c9acf1318a883f6b391c", size = 111227066, upload-time = "2026-07-08T16:03:33.6Z" },
{ url = "https://files.pythonhosted.org/packages/e9/09/2c10e8cd0e00fa5d23c052df6ce467eaa7182399f5e0f824f1e4ff42ccae/torch-2.13.0-cp314-cp314-manylinux_2_28_aarch64.whl", hash = "sha256:a3893dc2da0a972a8ca5d698c85a9f967559ac5f8ee1797b77408aa8734d073c", size = 427226309, upload-time = "2026-07-08T16:02:53.127Z" },
{ url = "https://files.pythonhosted.org/packages/76/c6/22c2102bbef14ca6a6cb4c20e42f088e49c5f812be4e160ae57502e325f9/torch-2.13.0-cp314-cp314-manylinux_2_28_x86_64.whl", hash = "sha256:49f1ea385c754e54919408a9bb3b5a72b0b755bbe2c916c1d6f70afbec4908a2", size = 526614507, upload-time = "2026-07-08T16:02:16.441Z" },
{ url = "https://files.pythonhosted.org/packages/2b/0c/7d1deb6bce5bc3e6042caf39100ac768eba3b9a098e1dddd16f75bd6489b/torch-2.13.0-cp314-cp314-win_amd64.whl", hash = "sha256:4f8573e3ce9ebcd53fe922f01077a6085ccdfbe5f12fd215883a9d87d7a744fd", size = 122051871, upload-time = "2026-07-08T16:03:23.521Z" },
{ url = "https://files.pythonhosted.org/packages/f4/ce/aa8b7f9949d32e0f2f624f342bc3b48112c1b8a130288465938bc83bcbf9/torch-2.13.0-cp314-cp314t-macosx_14_0_arm64.whl", hash = "sha256:c28def70706c2f9ecc752574766e8ae4da9b810ab6676b611166761a78a9f1e1", size = 111537025, upload-time = "2026-07-08T16:02:44.28Z" },
{ url = "https://files.pythonhosted.org/packages/69/d1/491e3a0389430946145888b0203f2b6a759ce2a61481b96a85c2da4f2ced/torch-2.13.0-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:31061ff56ed8fbf26c749806905aeb749ebeb819810fd5d52508aa5afd90dddc", size = 427219769, upload-time = "2026-07-08T16:02:31.18Z" },
{ url = "https://files.pythonhosted.org/packages/9a/1d/38006e045bf0a1fc28ef01e757c554e59e59a8770c284bc4f47b14e60441/torch-2.13.0-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:cc26eead4cf51d0b544e31e364dcf000846549c273bd148936fe9d24d29acb92", size = 526571320, upload-time = "2026-07-08T16:01:59.348Z" },
{ url = "https://files.pythonhosted.org/packages/56/94/655c91992a882bd5071aa0b5d22a07dbb130d801e872be97c0b627a7c693/torch-2.13.0-cp314-cp314t-win_amd64.whl", hash = "sha256:a7de8a313090dc5c7d7ba4bfe5c3be222528f9a4dba1acc83bddb1157360c4b8", size = 122306773, upload-time = "2026-07-08T16:02:39.832Z" },
]
[[package]]
@@ -3179,7 +3187,7 @@ wheels = [
[[package]]
name = "torchvision"
version = "0.27.1"
version = "0.28.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "numpy" },
@@ -3187,30 +3195,30 @@ dependencies = [
{ name = "torch" },
]
wheels = [
{ url = "https://files.pythonhosted.org/packages/c9/10/8e3e5a70dded1f86368bc987d93fa0436e73a79060aead75a8783b040ebd/torchvision-0.27.1-cp310-cp310-macosx_14_0_arm64.whl", hash = "sha256:68ba63b48af92f06db995adb23d8411993dba1dee705a4e92411b83a00930b7f", size = 1852109, upload-time = "2026-06-17T21:09:34.966Z" },
{ url = "https://files.pythonhosted.org/packages/4c/32/1a3eddb92e6d8ae69f38a20c60b7788c67c6ef32d6d4d1dc5d5fbd1f109c/torchvision-0.27.1-cp310-cp310-manylinux_2_28_aarch64.whl", hash = "sha256:aabe47970a00a3c0574360bfbd4ca3d6162a51f3fa1283a29cd528018dd13088", size = 7829870, upload-time = "2026-06-17T21:09:18.695Z" },
{ url = "https://files.pythonhosted.org/packages/13/1c/6b45992279b4177d26b5b851f554ee5d99115e7bd02eeb99459ad41027bf/torchvision-0.27.1-cp310-cp310-manylinux_2_28_x86_64.whl", hash = "sha256:a9ea9a8abdd23466a5f1c09523cb27dc61e36c16fc7e5e88b337ca54f530b1ef", size = 7658441, upload-time = "2026-06-17T21:09:23.803Z" },
{ url = "https://files.pythonhosted.org/packages/7e/6b/09d2d6f04c3465a346202624a09cfcfb954f2b334d19de886a63056f86f9/torchvision-0.27.1-cp310-cp310-win_amd64.whl", hash = "sha256:d0b00ae58379e6c936ce4816b1b8b94cefb1bd1c2a88eccbadfc993de7a430ca", size = 3493503, upload-time = "2026-06-17T21:09:28.426Z" },
{ url = "https://files.pythonhosted.org/packages/64/46/bc0ebd93282aeedc1759f054a252c6fadf14b42a0535db3233c85cce4ae5/torchvision-0.27.1-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:ad8743a9c12c8c124ad0a1491e54c3ca0c749e91e374e3d92136060b22c9e0f4", size = 1852118, upload-time = "2026-06-17T21:09:32.448Z" },
{ url = "https://files.pythonhosted.org/packages/b2/00/752adc57b6aa8bb833f5b0672acb9538aa5535d64998b9d8dd48ee51fa80/torchvision-0.27.1-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:a726707e4cbe438fcc507d787af7acf6bca52de30bf4b03579f1dfc0675da829", size = 7831256, upload-time = "2026-06-17T21:09:26.767Z" },
{ url = "https://files.pythonhosted.org/packages/fa/8a/c474fb27faba02e84dc40e0ac9ea1aa828d6d3557a378f7d0a22468bb2a3/torchvision-0.27.1-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:a1d6a123009af59ad288459f579f67a65cbe8f59372dc7b97e41bc01a6a9b767", size = 7659995, upload-time = "2026-06-17T21:09:25.325Z" },
{ url = "https://files.pythonhosted.org/packages/eb/7c/e254f8e242a921adc2cc62c11674fa8a16d33e0a1b6c6f5436cb91628ee7/torchvision-0.27.1-cp311-cp311-win_amd64.whl", hash = "sha256:f3b57a984283896f15c9698562418282f828332886c77315bf269936e6ba0280", size = 3807497, upload-time = "2026-06-17T21:09:31.234Z" },
{ url = "https://files.pythonhosted.org/packages/88/82/2e8fdc19e4f0bbe31d403a55d78318bcea4afcd3083e1e4700ef61ebb893/torchvision-0.27.1-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:448abfc3baba984da4577f737209e445da6be93e3b5f4799d90162bf61e3f485", size = 1852105, upload-time = "2026-06-17T21:09:33.695Z" },
{ url = "https://files.pythonhosted.org/packages/43/42/103fa8f9366cfd1329fe449d6b1a25a640c0c17862ed48f21c4af94af322/torchvision-0.27.1-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:9edfb5a549fc2f30ccadb24eca907901e92e426c91a59316be6703a9360e5098", size = 7830902, upload-time = "2026-06-17T21:09:29.739Z" },
{ url = "https://files.pythonhosted.org/packages/97/70/fa6052a42110a3657fc94073648da6171220469f4bf9f27e6a0b9378075c/torchvision-0.27.1-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:ae3d49e57c4abc8eafc1a1971f80fc4948a6268fa69340737ca4466936def080", size = 7664211, upload-time = "2026-06-17T21:09:17.206Z" },
{ url = "https://files.pythonhosted.org/packages/d0/95/27aca854da7e536a339f46bab1ef67823ac2ac97c59ab2b3203b373d46cf/torchvision-0.27.1-cp312-cp312-win_amd64.whl", hash = "sha256:0b6e3aa98b7433506bbce1d0d05cb13ec787fc6eb8c5fbd998b26ce05f047543", size = 4079076, upload-time = "2026-06-17T21:09:15.907Z" },
{ url = "https://files.pythonhosted.org/packages/32/bb/b21e0f598ca191bb2a9e9fda2fee37c06ad113313b43c6769dbefa0e921d/torchvision-0.27.1-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:d60311a6d08df905f9656a3a312f0a8f55f0d46321bc737bad30a8dec9644309", size = 1852110, upload-time = "2026-06-17T21:09:22.577Z" },
{ url = "https://files.pythonhosted.org/packages/2f/90/d61171daa5d6cd5f9315f84f9ef947b047a9fdf283d53241327045a8dd6d/torchvision-0.27.1-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:08aa33bc8e062cca32aefa90ac714916c5a855cbe1ab4c6148fc0453eb40ca5a", size = 7789476, upload-time = "2026-06-17T21:09:13.105Z" },
{ url = "https://files.pythonhosted.org/packages/b8/dc/b21d7801562c23a770e7037989814582f22ca4db479204293561de4b62e8/torchvision-0.27.1-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:916448be4b19676677b0dbf47d08f68b7955ea0abec7fc79340c31e217a824ba", size = 7664256, upload-time = "2026-06-17T21:09:07.549Z" },
{ url = "https://files.pythonhosted.org/packages/b9/b3/4386976ff77eda55f0aed504a288564f3ff8d170b6db49ee22e172eddfac/torchvision-0.27.1-cp313-cp313-win_amd64.whl", hash = "sha256:18bc906235bfa901c135acd239f05b8c8ab90d502830cf1ef2cba3301e1f8a23", size = 4150710, upload-time = "2026-06-17T21:09:14.457Z" },
{ url = "https://files.pythonhosted.org/packages/ff/74/1d237c61f665bf46d02e15f67c9d40be42b1b634f87164b9cefd257450e7/torchvision-0.27.1-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:9f5ef59ad60e695796eca6b64e97cb9b21b9d5463cac5ac0ef86cfb72b6e5db9", size = 1852112, upload-time = "2026-06-17T21:09:21.445Z" },
{ url = "https://files.pythonhosted.org/packages/24/84/f0d772e7ed85891f084755bd5d7f6f7fd279992a02652c653c1c8429dd84/torchvision-0.27.1-cp314-cp314-manylinux_2_28_aarch64.whl", hash = "sha256:ab2f8047c2da5bf6742fec6da86840e5feaeb0cea76930d0536f3520df31e166", size = 7789751, upload-time = "2026-06-17T21:09:11.51Z" },
{ url = "https://files.pythonhosted.org/packages/76/68/3febd41b6eef453a83fb7a0178446334fbb0405eb4b0c40b00efaf99a2dc/torchvision-0.27.1-cp314-cp314-manylinux_2_28_x86_64.whl", hash = "sha256:b44ef28ad1963f8cba5bf82f3564c454c74be300df9f79efa43f773312d17d6c", size = 7664350, upload-time = "2026-06-17T21:09:04.486Z" },
{ url = "https://files.pythonhosted.org/packages/52/49/a23e199faf29e42a90f7d6b76437ade5d17e3185da3c64d368973ba8243e/torchvision-0.27.1-cp314-cp314-win_amd64.whl", hash = "sha256:b3e9bc71854fddbf94ddb69ed8d88983945f3f28f78ee104214b0088669af66a", size = 4177297, upload-time = "2026-06-17T21:09:10.273Z" },
{ url = "https://files.pythonhosted.org/packages/ba/48/b3240eaf0fe3676dcf677ce8930ef477fe77d7f69ebe58ca8d0941384952/torchvision-0.27.1-cp314-cp314t-macosx_14_0_arm64.whl", hash = "sha256:c2fd9902f23b56b6ac667213171672fb6c89287ff011918b04af053852a2c4eb", size = 1852118, upload-time = "2026-06-17T21:09:20.223Z" },
{ url = "https://files.pythonhosted.org/packages/73/01/6c8f3158994a9e5bb0c7b1bacc361d60e015ad79487af88fa4d7ce72c2b6/torchvision-0.27.1-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:8abb6d5cacd56486ca2240e5580750e53ac559412e472ea6a3cee83231a77ca7", size = 7791242, upload-time = "2026-06-17T21:09:02.062Z" },
{ url = "https://files.pythonhosted.org/packages/1b/e6/f66733fc411a9ce070c0d899c1ae562ff11654a0bc708511e23efe9d6872/torchvision-0.27.1-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:d11da1ce8a5cc7fc527f2d5e0fe25efba93687897fe9339382b593910b1d1c6e", size = 7664934, upload-time = "2026-06-17T21:09:06.221Z" },
{ url = "https://files.pythonhosted.org/packages/90/aa/d6179812ec52b70a7a8f5e99fe7937895d28c535106df1ca0d03f5f51425/torchvision-0.27.1-cp314-cp314t-win_amd64.whl", hash = "sha256:12deaee20d0d9dec6302025d3f93354266befeb692f5c50bca0137b395598b9e", size = 4284412, upload-time = "2026-06-17T21:09:08.989Z" },
{ url = "https://files.pythonhosted.org/packages/b4/df/1ba039ad6cfe6e69209c36766b9b6e8c6fe92481c6d4e4ca52296f5f699d/torchvision-0.28.0-cp310-cp310-macosx_14_0_arm64.whl", hash = "sha256:2a1ef4b6f4bf5828b48cfad97372c8982db906830884b2868ba5c3df937a7d81", size = 1856019, upload-time = "2026-07-08T16:07:59.283Z" },
{ url = "https://files.pythonhosted.org/packages/88/ea/5c70ecf86f8e95174a85061cea78683a7bb7f422f09c3f3d4f30b7600fa9/torchvision-0.28.0-cp310-cp310-manylinux_2_28_aarch64.whl", hash = "sha256:546fd85345cf8652f6cd099d4f9884b0ca5c2f3fae78689a21dd2f35ea6b622f", size = 7838211, upload-time = "2026-07-08T16:07:27.023Z" },
{ url = "https://files.pythonhosted.org/packages/46/22/2f7ff1997d793e45d85fafa8374ee25348b7dae9ac521ba8751d7e1c75d5/torchvision-0.28.0-cp310-cp310-manylinux_2_28_x86_64.whl", hash = "sha256:6dfb0f45e2b4ceb4e76f158c3fbb5f44387099f3c466e3423a09ab665a194aba", size = 7669419, upload-time = "2026-07-08T16:07:41.648Z" },
{ url = "https://files.pythonhosted.org/packages/42/d0/2b3c30834ff23acd3854d0ff59bc580711f4b36d725de40105a852ed3719/torchvision-0.28.0-cp310-cp310-win_amd64.whl", hash = "sha256:7fad44dc9582570c7d92c4487d36ac46998f40cc39b438e8b8f5111a935ce4e8", size = 3500355, upload-time = "2026-07-08T16:07:56.865Z" },
{ url = "https://files.pythonhosted.org/packages/7a/b2/1e010052079e4c577007b789db336ea7075f1a426e84d17121fbc3745516/torchvision-0.28.0-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:83fe6c020866a85acd7d97deccc45ff11d66daf42916d04396a4309c66c0ccb8", size = 1856017, upload-time = "2026-07-08T16:07:55.533Z" },
{ url = "https://files.pythonhosted.org/packages/27/be/1b9c5de9c655ca2df4a74100fa671a7b848532ff787e077ccde14a7dea2a/torchvision-0.28.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:5a38bc6da3d72621be003400b66f66a2b4c6d644fde05f680c2cb7ca8cf8dd6c", size = 7841822, upload-time = "2026-07-08T16:07:49.207Z" },
{ url = "https://files.pythonhosted.org/packages/0b/9b/f1e68e861d4462e3e195a642c2b448e7b7d3fad5f209487162b9a2133d9b/torchvision-0.28.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:7e80f543b22503d9415e126db5f0ff3917036925e38560ee6b9ae38c571a4002", size = 7670718, upload-time = "2026-07-08T16:07:46.525Z" },
{ url = "https://files.pythonhosted.org/packages/f5/de/1494610ff54cbb154beb55033cc2cd50f3de04dac132fa2dd00e4f2b2556/torchvision-0.28.0-cp311-cp311-win_amd64.whl", hash = "sha256:9a45ea67235d965ef52187130d20002a4de20c54ea3d927a24286961d268dc37", size = 3814319, upload-time = "2026-07-08T16:07:37.153Z" },
{ url = "https://files.pythonhosted.org/packages/15/49/c1cab1ecbb3ff1a380a3f99283db1dee61b8afe354f6352c643b65937130/torchvision-0.28.0-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:e9f54c30cd52e3ef7fd034cc69b7bb7e0964e1c8f8743e018ab92e95b40f9eee", size = 1856020, upload-time = "2026-07-08T16:07:52.182Z" },
{ url = "https://files.pythonhosted.org/packages/f0/4c/95233776e2def960e5abb7a07931230a545f43717a56a1e1140162033598/torchvision-0.28.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:5cf78ebc401ce64ae19b8c55de866bb836797d559a4de9c25ccbe74cfa642d3a", size = 7842127, upload-time = "2026-07-08T16:07:53.446Z" },
{ url = "https://files.pythonhosted.org/packages/93/e4/e9b2495d0d57b9f60d63c57d0a910410a81b4b073bf70917bef815291119/torchvision-0.28.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:028a3d481b37d785605620d7cdad897064c5a55bae2aa1f2658766333e291940", size = 7675040, upload-time = "2026-07-08T16:07:58.017Z" },
{ url = "https://files.pythonhosted.org/packages/7c/9c/55ed9cb6dfe3ee9c837df5cd0e758372e5829aa38b8dd71343aa632cc4e2/torchvision-0.28.0-cp312-cp312-win_amd64.whl", hash = "sha256:87dc16b2df427c1318ad335f1e2be2b3b15b2cf20f7934c83b0505a48425ee5d", size = 4085785, upload-time = "2026-07-08T16:07:50.928Z" },
{ url = "https://files.pythonhosted.org/packages/20/55/08a726c14c67b37c8aca04b077766909f1c7ed23f76116884fe63b9bd033/torchvision-0.28.0-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:d483b4aa3f5237569053f749cd1a2b5bb548ca456e40461a5dd087f21149d123", size = 1856021, upload-time = "2026-07-08T16:07:45.386Z" },
{ url = "https://files.pythonhosted.org/packages/db/8f/40beacd53809194f5259e590d1afaeaa8ad57da15f77c646e6560bcc4616/torchvision-0.28.0-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:bb6dd6918460ed89cc7644adcc2402991474d6933cf1ce92b390641cb233fddf", size = 7797014, upload-time = "2026-07-08T16:07:43.04Z" },
{ url = "https://files.pythonhosted.org/packages/32/db/062cdb5a84380a60439775311fff34d89229760d2a50680393dc18699956/torchvision-0.28.0-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:ad7b3a439265cc3739a4ab5b4c998c0e38ea99c0ee7ca4dea35c5d0b099ec237", size = 7674669, upload-time = "2026-07-08T16:07:38.91Z" },
{ url = "https://files.pythonhosted.org/packages/f3/a6/b4081e2d04e1541abf82785ac9e5178a494c19330391f551356c8c18b7b3/torchvision-0.28.0-cp313-cp313-win_amd64.whl", hash = "sha256:7e9dd6f60d6e15f8dc27d4f877fdb6002fc70d70272412135f1c2ff9cfa08d3b", size = 4157380, upload-time = "2026-07-08T16:07:40.22Z" },
{ url = "https://files.pythonhosted.org/packages/c5/b9/da40eca5bbe9596c12ae9899ab7abaf887f5e20f29d08b924b4633714821/torchvision-0.28.0-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:3bd9dba55224a9db4a2d77f6feaa5651770d8c8e86d3d0ddb0fa6bec54c8712b", size = 1856014, upload-time = "2026-07-08T16:07:44.282Z" },
{ url = "https://files.pythonhosted.org/packages/06/d6/313aafd3df4eaf5f330211bd4e75b7598bddbfee4f55580d3b58536e1b20/torchvision-0.28.0-cp314-cp314-manylinux_2_28_aarch64.whl", hash = "sha256:89f90e29b0966352811b12589f3a3c61943bf2bb9487b9d7bbec10efb1096bb5", size = 7796873, upload-time = "2026-07-08T16:07:30.907Z" },
{ url = "https://files.pythonhosted.org/packages/b3/41/31f8e959ab8f942600b6357f8999c21d779d5fd3304b0fd204ff4b518239/torchvision-0.28.0-cp314-cp314-manylinux_2_28_x86_64.whl", hash = "sha256:36beb0782976906069ca03d4c9aacaf4b6b838b06ed6c20960ea9c51cce7acdd", size = 7674634, upload-time = "2026-07-08T16:07:29.657Z" },
{ url = "https://files.pythonhosted.org/packages/15/15/4c5115253fd470672cdac0a1cf139e06b4f3e29d041238a2b255937f63be/torchvision-0.28.0-cp314-cp314-win_amd64.whl", hash = "sha256:3557cc7b539f46dabcda2b6f2b14017ccbeef024de466d4fc5835fc3f287f769", size = 4184005, upload-time = "2026-07-08T16:07:35.805Z" },
{ url = "https://files.pythonhosted.org/packages/6a/80/822a6163da716f8a78141cf6678d74e26a572285d4ea866ef8aa657bb307/torchvision-0.28.0-cp314-cp314t-macosx_14_0_arm64.whl", hash = "sha256:09ce8f56e81f19b9c378ae7bb109f83f6659fd8bc3cd14241a48e4af46e9ed49", size = 1856011, upload-time = "2026-07-08T16:07:33.404Z" },
{ url = "https://files.pythonhosted.org/packages/7f/d1/cd3f9463b39a790ec8c0c2f6e6c8061edb1562114d04fcdfa786ed889345/torchvision-0.28.0-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:62c7d110f86a039245b587e4fae60278c649f3bd42ff79cfbc1178eca4e72542", size = 7796742, upload-time = "2026-07-08T16:07:28.339Z" },
{ url = "https://files.pythonhosted.org/packages/d9/82/3e0a7ad18e99831e2d7f4713d3be717b7159ff5a920862dd5c23c454aa71/torchvision-0.28.0-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:904cf89af220f8c6b2ed0296bb5065b474ce43b77558e48b2bf9de8b0ba17204", size = 7675526, upload-time = "2026-07-08T16:07:34.572Z" },
{ url = "https://files.pythonhosted.org/packages/18/d4/23aea03b28297bc66a4461f55ae4296368a9d85fa9a454bafcb2a5348bd7/torchvision-0.28.0-cp314-cp314t-win_amd64.whl", hash = "sha256:46f581979c010ad6da6bd85ee602aa707e1ff44312670223b7a0ee517ad06d47", size = 4291452, upload-time = "2026-07-08T16:07:32.236Z" },
]
[[package]]
@@ -3227,7 +3235,7 @@ wheels = [
[[package]]
name = "transformers"
version = "5.13.0"
version = "5.13.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "huggingface-hub" },
@@ -3240,9 +3248,9 @@ dependencies = [
{ name = "tqdm" },
{ name = "typer" },
]
sdist = { url = "https://files.pythonhosted.org/packages/ec/e1/720ff7ff666b04279fea5bb7ac3ef8675e98f0ddbc1b8cb8bc9f3889d62e/transformers-5.13.0.tar.gz", hash = "sha256:940c1428e42a4238f9ccf0cd41e63c590701aa63c19fd2ce3d7d602222d68495", size = 9195801, upload-time = "2026-07-03T16:05:39.362Z" }
sdist = { url = "https://files.pythonhosted.org/packages/6e/f7/418169401560cec2b61512e6bf37b0cfb4c8e27700cfa868a1de073cb65d/transformers-5.13.1.tar.gz", hash = "sha256:1e2452d6778a7482158df5d5dacf6bf775d5b2fdcfce33caaf7f6b0e5f3e3397", size = 9196891, upload-time = "2026-07-11T09:15:50.845Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/a5/3a/d99704c5effe10c6339c98cb236259161103e159bb99a78468b6729572ec/transformers-5.13.0-py3-none-any.whl", hash = "sha256:8adbc1d20bd5463cd6876b2eb7cb31971e1065788e7dc6bc12bab597a7c504b7", size = 11503730, upload-time = "2026-07-03T16:05:35.569Z" },
{ url = "https://files.pythonhosted.org/packages/29/47/54eacf96b5c835bbd6ca631aa2740e7705ed63d9e3a8afd2d2cc6d09cae5/transformers-5.13.1-py3-none-any.whl", hash = "sha256:53f0ea8aa397e29244c2377ba981bcaf0c87adcf44fbdd447ef6306522afcacd", size = 11503977, upload-time = "2026-07-11T09:15:46.801Z" },
]
[[package]]