Compare commits

...
6 Commits
Author SHA1 Message Date
Victor Kuznetsov 86ce55ced6 Release 0.34.0 2026-08-27 21:08:07 -07:00
Victor Kuznetsov ee561308ef Keep maintainer help portable on Windows 2026-08-27 20:09:54 -07:00
Victor Kuznetsov a8d4bce14a Align watermark content with detector coverage 2026-08-27 20:05:03 -07:00
Victor Kuznetsov 17408b958e Reject the uncalibrated text-manifest tiling and verify Content Seal transforms
Tiled diffusion was never provider-oracle calibrated with verified text
restoration: the tiled VAE donor path ran anyway and produced results no
oracle had certified. The combination is now rejected at both the
pipeline and the engine seam (ValueError with the reason), and the CLI
help no longer implies support. The invisible help is generalized and
the metadata container list corrected (MKA/OGA/Opus/AAC).

scripts/contentseal_transforms.py reproduces the deterministic crop,
resize, and JPEG variants of the Content Seal corpus from manifest.csv,
hash-verifying every output; its README gains scripts/README.md context
and new data tests. The corpus README is honest about the one crop the
daily oracle limit left unchecked, and the eval CSVs carry the updated
verdicts. The byte-scan SynthID suppression hoists its soft-binding
lookup so the guard is computed once.

Staged on top of 0.33.1; no version bump in this commit.
2026-08-27 16:53:34 -07:00
Victor Kuznetsov 834342db07 Follow the seal bet in the Likely-source line
A standalone-tag file showed 'platform not specified' while the panel
below priced the Muse Content Seal removal - the platform line lagged
the attribution the seal signal and the strength router already make.
The fallback now attributes 'Meta Muse Image (attributed by the
standalone AI digital-source tag)' when no more specific attribution
applies, so the source line and the priced target agree. Apple Photos
Clean Up keeps its own attribution; the hedge names the attribution
basis, not a detection.
2026-08-27 16:41:28 -07:00
Victor Kuznetsov dcc1bf5e07 Emit the Content Seal as its own signal on standalone-AI-tag files
The strength router already bets that a file whose only provenance is
the standalone AI digital-source tag is Meta Muse output (C2PA issuers
win first), and Muse stamps every output with the invisible Content
Seal. identify now surfaces that same bet as evidence: the additive
content_seal signal (medium confidence - an attribution, not a decode,
since no public decoder exists) plus the watermark string, emitted on
exactly the standalone_iptc condition that routes the cohort. Clients
select pixel removal from the signal list instead of parsing caveats,
the way InvisMark is additive over soft_binding. The API's invisible
gate already runs on ai_from_metadata, so all/invisible behavior is
unchanged; has_invisible_target needs no edit.
2026-08-27 16:25:11 -07:00
86 changed files with 1530 additions and 378 deletions

No files matched your search

+1 -1
View File
@@ -4,7 +4,7 @@ name: Distribute on release
# PyPI is handled by publish.yml. This workflow event-drives the three channels
# that would otherwise be manual:
# - Homebrew tap: rewrite the formula's url + sha256 to the new sdist.
# - HF Space: factory-rebuild so it reinstalls the latest sdist from PyPI.
# - HF Space: factory-rebuild the version already pinned in the Space repo.
# - ComfyUI: sync, test, and publish the node against the exact library release.
# All wait for the freshly published sdist to appear on PyPI first, since the
# Release event fires in parallel with publish.yml's upload.
+19 -10
View File
@@ -2,18 +2,19 @@
Remove AI provenance marks from images and video you generated yourself:
- known visible labels such as the Gemini sparkle and vendor text marks;
- known visible labels such as the Google Gemini sparkle watermark and vendor text marks;
- invisible pixel watermarks through diffusion regeneration;
- C2PA, EXIF, XMP, IPTC, and related AI metadata.
Video support covers provenance identification, complete visible-plus-metadata
cleaning, directory batches, visible Sora, Veo, Seedance, Dola, Hailuo, and
Kling mark removal, and oracle-certified VAE regeneration for video SynthID
cleaning, directory batches, visible Sora, Veo, Seedance, Dola, Hailuo AI, and
Kling AI mark removal, and oracle-certified VAE regeneration for video SynthID
removal.
> [raiw.cc](https://raiw.cc) runs this library as a hosted service, with the GPU
> included and nothing to install. Visible mark and metadata removal are free
> there; invisible watermark removal is paid.
> included and nothing to install. Visible mark and metadata removal at Standard
> output up to 12 MP are free there; original resolution above 12 MP and invisible
> watermark removal are paid.
[![PyPI](https://img.shields.io/pypi/v/remove-ai-watermarks?logo=pypi&logoColor=white)](https://pypi.org/project/remove-ai-watermarks/)
[![Python](https://img.shields.io/pypi/pyversions/remove-ai-watermarks?logo=python&logoColor=white)](https://pypi.org/project/remove-ai-watermarks/)
@@ -168,8 +169,8 @@ the specificity order shown below. Pass an explicit mark to restrict detection
to one provider.
Sora covers the moving Sora 2 mascot and wordmark. Veo covers both the current
four-point diamond and the legacy `Veo` text. Seedance covers the fixed boxed
`AI` label, Dola covers the fixed `Dola AI` text, Hailuo covers the composite
`MINIMAX | hailuo AI` label, and Kling covers the bottom-right `KLING AI`
`AI` label, Dola covers the fixed `Dola AI` text, Hailuo AI covers the composite
`MINIMAX | hailuo AI` label, and Kling AI covers the bottom-right `KLING AI`
label with its version suffix. A completed encode is published atomically. No
output is written when no stable mark is found.
HDR, PQ/HLG, and greater-than-8-bit inputs are rejected before encoding rather
@@ -230,6 +231,13 @@ features, and development setup.
| --- | --- |
| ![Image with a visible Gemini watermark](demo_banana_before.png) | ![Image after visible watermark removal](demo_banana_after.png) |
The `after` raster is generated from the tracked `before` raster by the public path:
```bash
uv run remove-ai-watermarks visible demo_banana_before.png \
--backend cv2 -o demo_banana_after.png
```
### High quality invisible removal
`qwen-zimage` is the default profile: a Qwen-Image-2512 Lightning pass under Canny
@@ -311,8 +319,9 @@ remove-ai-watermarks batch ./images --mode all
Visible mark support includes:
- Google Gemini and Nano Banana sparkle;
- Doubao, Jimeng, Qwen, Kling, Yuanbao, Baidu, LibLibAI, and RunningHub labels;
- Google Gemini and Nano Banana visible sparkle watermark;
- Doubao, Jimeng, Qwen, Kling AI, Yuanbao, Baidu, LiblibAI, and RunningHub labels;
- one calibrated Microsoft top-right white AI-badge variant;
- one calibrated Samsung Galaxy AI label variant.
Metadata and provenance inspection covers C2PA, EXIF, XMP, IPTC, common
@@ -396,7 +405,7 @@ invisible removal.
detail.
- Visible video removal recognizes the moving Sora 2 wordmark, the current Veo
diamond plus legacy `Veo` text, the Seedance boxed `AI` label, and the fixed
Dola, Hailuo, and Kling labels. It does not recognize the older Sora Turbo
Dola, Hailuo AI, and Kling AI labels. It does not recognize the older Sora Turbo
corner swirl or unregistered layouts from those providers.
The classical OpenCV backend can smear structured backgrounds; use MI-GAN or
LaMa when recovery quality matters.
+5 -4
View File
@@ -48,16 +48,17 @@ runtime assets.
video removal profile works, so it is also the source of truth for three shipped
defaults: `tests/test_video_invisible.py` asserts that `noise_std`, `long_side`,
and `fps` together match a row this manifest records as certified. Changing one
of those three without adding the row that certifies it fails the suite. `vae` is
deliberately outside that check because neither tracked row records one; add it
to the assertion in the same commit as the first row that does.
of those three without adding the row that certifies it fails the suite. Both
historical rows mark `vae` as `unrecorded`: the repository must not infer a model
identity from the current default. Add it to the assertion in the same commit as
the first oracle row that records and verifies one.
| Column | Meaning |
| --- | --- |
| `date`, `source_url`, `source_sha256` | Identify the carrier. |
| `source_width`, `source_height`, `source_fps` | Carrier geometry. Without it the actual downscale factor of a row cannot be recovered later. |
| `duration_seconds`, `source_verdict` | Clip length submitted and the verifier's reading of the untouched carrier. |
| `vae`, `noise_std`, `long_side`, `fps`, `seed` | The full run configuration. |
| `vae`, `noise_std`, `long_side`, `fps`, `seed` | The run configuration. `unrecorded` means the historical run did not preserve the VAE identity. |
| `output_sha256` | Identifies the exact submitted file. |
| `output_verdict` | One of `detected`, `not_detected`, `indeterminate`, `refused`. |
| `output_verdict_text` | The verifier's wording, verbatim. |
+21 -9
View File
@@ -16,9 +16,12 @@ plus hash and is not stored.
embedded in the watermark payload. Both survived a 512 px LANCZOS resize and
a full-size JPEG q85 re-encode (same ID returned), so the payload is more
robust than the detection threshold.
- Center crops lose the seal: 50% and 33% linear center crops of two different
images all returned "No AI signatures from Meta were found", consistent with
the Reuters 2026-07-11 analysis (55% missed after cropping).
- Three checked center crops lost the seal: 50% and 33% linear crops of the fox
and the 50% crop of the text poster returned "No AI signatures from Meta were
found". The text poster's 33% crop was not checked because the daily oracle
limit was reached, so its empty verdict is not evidence either way. The checked
results are consistent with the Reuters 2026-07-11 analysis (55% missed after
cropping).
- API outputs carry XMP `iptcExt:DigitalSourceType =
trainedAlgorithmicMedia`, so local `identify` flags them via the existing
Made-with-AI path. Metadata-stripping transforms fall back to unknown, and
@@ -62,8 +65,8 @@ the calibration rows below is the race-free variant.
The library resolves strength per vendor with measured floors (OpenAI
0.07675 / Google 0.27 / Microsoft InvisMark 0.15 in
`_internal/watermark_profiles.py`). Meta Content Seal has no floor yet; the
goal of these rows is to measure one by that same methodology: independent
`_internal/watermark_profiles.py`). Meta Content Seal had no floor before this
calibration; these rows measure one by the same methodology: independent
generations, each one's first-clean boundary, floor = worst boundary plus the
observed cross-source spread.
@@ -83,7 +86,16 @@ Measured (2026-08-26/27, oracle `meta.ai/identification`):
names it explicitly on stripped files (implying the scrub runs).
## Regeneration
API key is not stored in this repository. Regenerate with the script pattern
from the session (env `MUSE_API_KEY`, endpoint
`https://api.meta.ai/v1/images/generations`, model `muse-image-1.0`); prompts
are recorded per file in `manifest.csv`.
The eight deterministic crop, resize, and JPEG variants can be reproduced and
hash-checked from the tracked originals:
```bash
uv run python scripts/contentseal_transforms.py /tmp/contentseal-derived
```
The Meta API generations and remote GPU outputs are not reproducible from this
repository alone. Their prompts, exact output hashes, model/profile settings,
and oracle results are recorded in `manifest.csv`, but the generation API is
stochastic and the private worker environment is not tracked. `MUSE_API_KEY` and
the anonymous detector session are deliberately absent. A new calibration must
therefore create new manifest rows rather than claiming to recreate these bytes.
@@ -1,4 +1,4 @@
date,source_commit,fixture,variant,model,model_revision,model_sha256,ocr_route,text_cer,img_lpips,ssim,psnr_db,output_sha256,provider_oracle,notes
2026-08-13,2d03a00,Gemini_Generated_Image_633uuy633uuy633u.png,qwen-zimage,,,,"Paddle ch",0.074,0.289,0.696,23.3,4b05489c7a79f993d35d32528de792baad5a3e33ee950afa147caf5d3e0621,not_run,Exact Qwen baseline reused from text-restoration benchmark
2026-08-13,2d03a00,Gemini_Generated_Image_633uuy633uuy633u.png,qwen-zimage,,,,"Paddle ch",0.074,0.289,0.696,23.3,4b05489c7a79f993d35d32528de792baad5a3e33ee950afa147caf5d3e0621a6,not_run,Exact Qwen baseline reused from text-restoration benchmark
2026-08-13,2d03a00,Gemini_Generated_Image_633uuy633uuy633u.png,qwen-zimage-anytext2-default,AnyText2-SD1.5,b06c583a583818f3679665ef67b51363f107853c,7d5d593928d842500e0da101ab6a1ae28a8d21403441ca62c813c4f92529ace8,"Paddle ch",0.185,0.338,0.642,18.2,87729fe7e0482d2cead6d3b7c7dd386ecc75ab3d8658131c54e67528b8f9feeb,not_run,Fidelity gate failed; padded crop recognition CER 0.074 still shows two substituted characters; locally composited three-line edit; 20 DDIM steps; seed 0
2026-08-13,2d03a00,Gemini_Generated_Image_633uuy633uuy633u.png,qwen-zimage-anytext2-mimic,AnyText2-SD1.5,b06c583a583818f3679665ef67b51363f107853c,7d5d593928d842500e0da101ab6a1ae28a8d21403441ca62c813c4f92529ace8,"Paddle ch",0.222,0.345,0.644,17.9,f5198d8f2365b79880aba8ea6b0c3885142b9de21c9f7f4f6712ac4a0db8dd85,not_run,Fidelity gate failed; source glyph masks supplied as font hints; 20 DDIM steps; seed 0
1 date source_commit fixture variant model model_revision model_sha256 ocr_route text_cer img_lpips ssim psnr_db output_sha256 provider_oracle notes
2 2026-08-13 2d03a00 Gemini_Generated_Image_633uuy633uuy633u.png qwen-zimage Paddle ch 0.074 0.289 0.696 23.3 4b05489c7a79f993d35d32528de792baad5a3e33ee950afa147caf5d3e0621 4b05489c7a79f993d35d32528de792baad5a3e33ee950afa147caf5d3e0621a6 not_run Exact Qwen baseline reused from text-restoration benchmark
3 2026-08-13 2d03a00 Gemini_Generated_Image_633uuy633uuy633u.png qwen-zimage-anytext2-default AnyText2-SD1.5 b06c583a583818f3679665ef67b51363f107853c 7d5d593928d842500e0da101ab6a1ae28a8d21403441ca62c813c4f92529ace8 Paddle ch 0.185 0.338 0.642 18.2 87729fe7e0482d2cead6d3b7c7dd386ecc75ab3d8658131c54e67528b8f9feeb not_run Fidelity gate failed; padded crop recognition CER 0.074 still shows two substituted characters; locally composited three-line edit; 20 DDIM steps; seed 0
4 2026-08-13 2d03a00 Gemini_Generated_Image_633uuy633uuy633u.png qwen-zimage-anytext2-mimic AnyText2-SD1.5 b06c583a583818f3679665ef67b51363f107853c 7d5d593928d842500e0da101ab6a1ae28a8d21403441ca62c813c4f92529ace8 Paddle ch 0.222 0.345 0.644 17.9 f5198d8f2365b79880aba8ea6b0c3885142b9de21c9f7f4f6712ac4a0db8dd85 not_run Fidelity gate failed; source glyph masks supplied as font hints; 20 DDIM steps; seed 0
+2 -2
View File
@@ -1,3 +1,3 @@
date,source_url,source_sha256,source_width,source_height,source_fps,duration_seconds,source_verdict,vae,noise_std,long_side,fps,seed,output_sha256,output_verdict,output_verdict_text,output_detected_range,track,session_id,stratum,psnr_db,temporal_residual_ratio
2026-07-31,https://storage.googleapis.com/gdm-deepmind-com-prod-public/media/media/veo__veo-3__off-road.mp4,79a552b9406a079682440c31f14d33a10ba8e1b8b2e96425f5de70f63350299d,1920,1080,24,8,detected_all_frames,,0.10,512,12,0,079165105d4c56e1612091987c08c2627049423025f74c0d4e245fb47c2ff0e3,detected,,,,,,26.2932,1.0072
2026-07-31,https://storage.googleapis.com/gdm-deepmind-com-prod-public/media/media/veo__veo-3__off-road.mp4,79a552b9406a079682440c31f14d33a10ba8e1b8b2e96425f5de70f63350299d,1920,1080,24,8,detected_all_frames,,0.15,512,12,0,1c4046bcfdead138353b4e2a73339ba227bb5e544878d80c5bc6cd8427c7b00e,not_detected,,,,,,25.3911,1.0578
2026-07-31,https://storage.googleapis.com/gdm-deepmind-com-prod-public/media/media/veo__veo-3__off-road.mp4,79a552b9406a079682440c31f14d33a10ba8e1b8b2e96425f5de70f63350299d,1920,1080,24,8,detected_all_frames,unrecorded,0.10,512,12,0,079165105d4c56e1612091987c08c2627049423025f74c0d4e245fb47c2ff0e3,detected,,,,,,26.2932,1.0072
2026-07-31,https://storage.googleapis.com/gdm-deepmind-com-prod-public/media/media/veo__veo-3__off-road.mp4,79a552b9406a079682440c31f14d33a10ba8e1b8b2e96425f5de70f63350299d,1920,1080,24,8,detected_all_frames,unrecorded,0.15,512,12,0,1c4046bcfdead138353b4e2a73339ba227bb5e544878d80c5bc6cd8427c7b00e,not_detected,,,,,,25.3911,1.0578
1 date source_url source_sha256 source_width source_height source_fps duration_seconds source_verdict vae noise_std long_side fps seed output_sha256 output_verdict output_verdict_text output_detected_range track session_id stratum psnr_db temporal_residual_ratio
2 2026-07-31 https://storage.googleapis.com/gdm-deepmind-com-prod-public/media/media/veo__veo-3__off-road.mp4 79a552b9406a079682440c31f14d33a10ba8e1b8b2e96425f5de70f63350299d 1920 1080 24 8 detected_all_frames unrecorded 0.10 512 12 0 079165105d4c56e1612091987c08c2627049423025f74c0d4e245fb47c2ff0e3 detected 26.2932 1.0072
3 2026-07-31 https://storage.googleapis.com/gdm-deepmind-com-prod-public/media/media/veo__veo-3__off-road.mp4 79a552b9406a079682440c31f14d33a10ba8e1b8b2e96425f5de70f63350299d 1920 1080 24 8 detected_all_frames unrecorded 0.15 512 12 0 1c4046bcfdead138353b4e2a73339ba227bb5e544878d80c5bc6cd8427c7b00e not_detected 25.3911 1.0578
+1 -1
View File
@@ -160,7 +160,7 @@ sparkle; the SynthID *pixel* itself has no local detector (oracle only).
Key takeaways:
- The same model differs by *surface*: Gemini app wraps C2PA, AI Studio (API/playground) emits none -- only the pixel + sparkle survive.
- Microsoft Designer's DALL-E backend inherits OpenAI's C2PA+SynthID (issuer "OpenAI, Microsoft"); Bing now runs Microsoft's own **MAI-Image** and signs C2PA as "Microsoft" (not OpenAI/DALL-E).
- Microsoft Designer's DALL·E backend inherits OpenAI's C2PA+SynthID (issuer "OpenAI, Microsoft"); Bing now runs Microsoft's own **MAI-Image** and signs C2PA as "Microsoft" (not OpenAI/DALL·E).
- Meta uses the IPTC `digitalSourceType` marker, not C2PA or SynthID.
- The open imwatermark fires only on *pristine* output from a pipeline that runs the encoder (diffusers default, official BFL) -- not from re-hosts (Krea, Stability hosted SDXL) or re-encoded design exports (Recraft, Canva). Ideogram's only signal is the EXIF `Make` tag.
- Bing and Grok web UIs are uncooperative for autonomous capture (no document_idle for screenshots; blob downloads intermittently no-op; low-res in-chat previews). Use their native download button manually if a full-res sample is needed.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.6 MiB

After

Width:  |  Height:  |  Size: 5.8 MiB

+6 -6
View File
@@ -317,7 +317,7 @@ remove-ai-watermarks video visible kling.mp4 --mark kling -o kling_clean.mp4
The command supports the moving Sora mascot and wordmark, two Veo
corner variants, the Seedance boxed `AI` label, the `Dola AI` text label, the
composite `MINIMAX | hailuo AI` label, and the bottom-right Kling label. Sora
composite `MINIMAX | hailuo AI` label, and the bottom-right Kling AI label. Sora
searches the whole frame at multiple scales. The other detectors search bounded
lower-frame regions with separate synthetic silhouettes. Kling additionally
requires its bright low-saturation label near the frame edge. Every mark
@@ -328,7 +328,7 @@ provenance-aware marks; metadata alone never creates a detection.
`--mark auto` is the default. It evaluates all providers in one decode pass and
selects the first stable match in specificity order: Sora, Veo, Seedance, Dola,
Hailuo, then Kling. Their confidence scores are independently calibrated and
Hailuo AI, then Kling AI. Their confidence scores are independently calibrated and
are not compared across providers. Pass an explicit `--mark` to scan only that
provider.
@@ -434,10 +434,10 @@ user can act on rather than after a model load.
### Restore operator-verified text
`--text-manifest` enables the experimental `vae-glyphs` post-pass. It reconstructs
the source with the Qwen VAE, blends 15% of that reconstruction into the normal
`qwen-zimage` result, erases the annotated candidate glyphs with LaMa, and composites
only the reconstructed glyph cores through source-derived silhouettes. It does not
run OCR or choose which strings are correct.
the source with the Qwen VAE, erases the annotated candidate glyphs with LaMa, and
composites only the reconstructed glyph cores through source-derived silhouettes. It
does not run OCR or choose which strings are correct. The optional `--fidelity-anchor`
described below additionally blends 15% of the reconstruction across the full frame.
Install the combined extra and run only with an operator-verified manifest:
+1 -1
View File
@@ -641,7 +641,7 @@ photo only).
**Sources.** https://arxiv.org/abs/2206.11253 (CodeFormer) · https://github.com/sczhou/CodeFormer ·
https://arxiv.org/pdf/2401.07519 (InstantID) ·
https://openaccess.thecvf.com/content/WACV2024/papers/Suin_Diffuse_and_Restore... (region-adaptive) ·
https://openaccess.thecvf.com/content/WACV2024/html/Suin_Diffuse_and_Restore_A_Region-Adaptive_Diffusion_Model_for_Identity-Preserving_Blind_WACV_2024_paper.html (region-adaptive) ·
https://arxiv.org/pdf/2504.12809 (saliency-aware watermark removal)
## Provenance
+4
View File
@@ -1,5 +1,9 @@
# Development
Standalone evaluation, calibration, and release utilities are catalogued in
[`scripts/README.md`](../scripts/README.md). They are maintainer tools rather than
installed commands, and their local data inputs remain outside the repository.
Read this reference for environment setup, dependency recovery, CI behavior, and fixture policy. The always-loaded invariants remain in [`.claude/rules/development.md`](../.claude/rules/development.md).
## Local environment
+6 -2
View File
@@ -114,6 +114,7 @@ application actually uses:
| `lama` | big-LaMa ONNX fill backend | `visible`, ONNX Runtime | Model download, no Torch |
| `qwen-zimage` | Invisible image-watermark removal, both CUDA-only profiles | `diffusion`, DiffSynth | Yes |
| `text-restoration` | Opt-in verified Qwen-VAE glyph restoration | `qwen-zimage`, `lama` | Yes |
| `text-draft` | Draft OCR proposals for operator verification | PaddleOCR, PaddlePaddle | Model download, no Torch |
| `all` | Every production feature available on the active Python | All compatible rows above | Yes |
| `dev` | Tests, linting, typing, and upstream parity checks | `video`, `detect`, upstream invisible-watermark | Yes, for parity tests |
@@ -130,12 +131,15 @@ flowchart LR
qwen["qwen-zimage"] --> diffusion
text["text-restoration"] --> qwen
text --> lama
draft["text-draft"]
heif
trustmark
```
`heif` and `trustmark` are independent branches. Combine them explicitly with
another feature when required. TrustMark requires NumPy 1.x, which has no
`heif`, `trustmark`, and `text-draft` are independent branches. Combine them
explicitly with another feature when required. `text-draft` is excluded from
`all` because it proposes unverified OCR annotations and is not a production
removal path. TrustMark requires NumPy 1.x, which has no
CPython 3.13 or 3.14 wheels, so that branch is available only on Python
3.11-3.12. The `all` bundle contains every production branch compatible with
the active Python and never includes `dev`.
+9 -6
View File
@@ -31,11 +31,14 @@ an unsupported locale, a different position, or a crop may be missed.
Known examples:
- The Microsoft detector covers one calibrated top-right white pill. Microsoft's
[documented feature](https://support.microsoft.com/en-us/topic/include-a-watermark-when-content-from-microsoft-365-is-ai-generated-b00a656e-ae61-4692-8086-67d004421030)
can instead use a Copilot icon, `AI-Generated` text, or another position.
- Samsung detection is calibrated for the Italian
`Contenuti generati dall'AI` text variant.
- The Jimeng top-left pill has a weak visual detector and is intentionally
subject to additional product and background checks.
- Kling support covers the calibrated variants rather than every Kling label.
- Kling AI support covers the calibrated variants rather than every Kling AI label.
Use `erase --region` when you can see and select an unsupported or missed mark.
@@ -310,11 +313,11 @@ supported AI provenance metadata without transcoding streams.
`video visible` and `remove_video_visible` additionally support the moving
Sora 2 mascot and wordmark, the current Veo four-point diamond, the legacy
`Veo` text, the Seedance boxed `AI` label, the fixed `Dola AI` text, the Hailuo
MINIMAX/Hailuo composite label, and the bottom-right Kling label with its
`Veo` text, the Seedance boxed `AI` label, the fixed `Dola AI` text, the Hailuo AI
MINIMAX/Hailuo AI composite label, and the bottom-right Kling AI label with its
version suffix. Detection requires a recurring visual candidate across
adjacent frames. Fixed-mark candidates must remain anchored rather than
drifting with a scene object. Kling also requires a bright low-saturation
drifting with a scene object. Kling AI also requires a bright low-saturation
candidate near the expected frame edge. Provider provenance can recover
low-contrast runs only after visual evidence exists for the marks that define a
provenance prior, so metadata alone does not erase a clean API export.
@@ -325,7 +328,7 @@ policies and selects the first stable result in specificity order. Use an
explicit mark when the provider is already known.
Historical Sora Turbo exports use a small OpenAI swirl in the corner rather
than the moving mascot-and-wordmark design; that earlier variant is not
detected by the `sora` video mark. Hailuo and Kling coverage is specific to the
detected by the `sora` video mark. Hailuo AI and Kling AI coverage is specific to the
verified lower-edge layouts; a new provider layout needs a separate calibrated
silhouette. Other provider video labels are not supported yet. Google video
SynthID has an oracle-certified VAE removal path, while other proprietary
@@ -416,7 +419,7 @@ remain identical because isolated decoder hits can otherwise be content noise.
It accepts Variant P schemas 0-2. Variant Q requires a different model, and
schema 3 is rejected at the measured precision threshold. Its NumPy 1.x runtime
limits the extra to Python 3.11-3.12; the rest of the package remains supported
through Python 3.14. Through 0.29.0 the extra also resolves lightning 2.6.5
through Python 3.14. The current TrustMark dependency line also resolves lightning 2.6.5
(PYSEC-2026-3624, no fixed release yet); the vulnerable `load_from_checkpoint`
path is unreachable here because TrustMark loads its checksummed checkpoints
with plain `torch.load`. Bump lightning and cut a patch release when a fix
+46 -19
View File
@@ -296,13 +296,13 @@ from the gate. The full-clip oracle floor is
detected while `0.15` did not.
[`video_visible.py`](../src/remove_ai_watermarks/video_visible.py) implements
the first pixel stages for Sora, Veo, Seedance, Dola, Hailuo, and Kling. The
the first pixel stages for Sora, Veo, Seedance, Dola, Hailuo AI, and Kling AI. The
Sora detector searches a normalized frame with a fully synthetic
mascot-and-text silhouette at several scales. The Veo detector uses separate
synthetic silhouettes for the current four-point diamond and legacy `Veo`
text. Seedance uses a synthetic rounded boxed-`AI` silhouette, while Dola uses
an OpenCV-font `Dola AI` silhouette. Hailuo uses a synthetic waveform,
MINIMAX/Hailuo text, separator, and ring. Kling combines synthetic font
an OpenCV-font `Dola AI` silhouette. Hailuo AI uses a synthetic waveform,
MINIMAX/Hailuo AI text, separator, and ring. Kling AI combines synthetic font
variants with a ring approximation of its swirl; the logo path rescues
wordmarks whose version or font differs, while the edge and white-label gates
reject recurring scene texture. All fixed-mark searches are bounded to the
@@ -323,23 +323,23 @@ Every per-frame result is untrusted. Each provider's floors, minimum-run policy,
fill padding and mask style are one row in `VISIBLE_MARK_POLICIES`, and every mark
enters the same `stabilize_localizations` entry point; the recurrence
implementation underneath knows nothing about providers. That policy row also
carries `accepts_provenance`, which forces `provenance=False` for Hailuo and Kling
carries `accepts_provenance`, which forces `provenance=False` for Hailuo AI and Kling AI
— they have no metadata that could confirm them, and the guarantee used to be
structural (their wrappers took no `provenance` parameter at all). Provenance can relax a low-contrast run only
after recurring visual evidence exists. Sora transition frames follow the
nearest confirmed moving position only with Sora provenance. Seedance, Dola,
Hailuo, and Kling additionally require candidates to remain anchored to the
Hailuo AI, and Kling AI additionally require candidates to remain anchored to the
start of a run. This rejects slowly drifting scene details that still have
high frame-to-frame overlap. Hailuo and Kling do not infer provenance from
high frame-to-frame overlap. Hailuo AI and Kling AI do not infer provenance from
technical encoder tags; their confirmed public samples carried no provider
metadata.
Removal runs in a second decode pass. Sora, legacy Veo text, Dola text,
Seedance, Hailuo, and Kling use box masks. Seedance deliberately fills the
Seedance, Hailuo AI, and Kling AI use box masks. Seedance deliberately fills the
complete localized box: a synthetic outline mask passed repeat detection but
left part of the real translucent border visible during visual end-to-end
review. Hailuo expands beyond the matched core to cover both provider icons.
Kling expands around the wordmark or swirl to include the version and optional
review. Hailuo AI expands beyond the matched core to cover both provider icons.
Kling AI expands around the wordmark or swirl to include the version and optional
`PRO` suffix. The square Veo diamond uses a synthetic shape mask so transparent
corners do not erase unrelated pixels. Every mask goes through the shared
`watermark_registry.fill` backends. ffmpeg encodes the changed video stream and
@@ -451,7 +451,9 @@ For an AI C2PA claim, a recognized product in `claim_generator` takes precedence
over the certificate issuer: an application can sign through an upstream model
provider without becoming that provider's product. Only exact product mappings
receive this precedence; an unknown claim generator still falls back to issuer
attribution.
attribution. An unmapped issuer org reads as unknown-signer C2PA with no platform;
that is how Ideogram was surfaced (4 corpus uploads signed "Ideogram, Inc",
2026-08-08) before its vendor row was added on 2026-08-27.
### Metadata scanning and stripping
@@ -746,9 +748,9 @@ capture-less pill is too weak to attribute.
The set of marks that veto the pill is DERIVED from the registry rows: every mark
under the same label regime (`tc260`) belonging to a different product. It used to
be a hand-written list of keys, and that list drifted -- LibLibAI was registered
alongside RunningHub and Baidu, both of which were added to it, and LibLibAI was
not, so a confident LibLibAI detection did not suppress the pill the way its two
be a hand-written list of keys, and that list drifted -- LiblibAI was registered
alongside RunningHub and Baidu, both of which were added to it, and LiblibAI was
not, so a confident LiblibAI detection did not suppress the pill the way its two
siblings did. Marks outside the TC260 regime (Gemini, Samsung) are deliberately
not vetoers: neither can put `jimeng` into `provenance`, so neither can enable the
arm it would be vetoing.
@@ -800,6 +802,29 @@ be represented by the shared base:
- [`runninghub_engine.py`](../src/remove_ai_watermarks/runninghub_engine.py)
- [`baidu_engine.py`](../src/remove_ai_watermarks/baidu_engine.py)
- [`liblib_engine.py`](../src/remove_ai_watermarks/liblib_engine.py)
- [`microsoft_engine.py`](../src/remove_ai_watermarks/microsoft_engine.py)
The measured Microsoft badge variant (2026-08-27 registration) is the first
`tr`-corner mark and the first `long`-side scale basis: the pill tracks the
render dimension, so a
1024x1536 portrait carries the same pill as 1536x1024, and a width basis
undersized the template by the aspect ratio (portrait carriers fell to
0.15-0.32 NCC until the basis was measured). The silhouette is a white pill with
its synthetic internal shapes knocked out - the holes are what separate it from
any other bright rounded corner element (a plain white pill scores below the gate
in the tests). It does not claim coverage of Microsoft's other documented icon,
wording, or position variants.
The 2026-08-27 rerun used the registered engine through
`scripts/registered_mark_calibrate.py`, rather than a copied detector
configuration. The manifest kept three evidence classes separate: 17 visually
confirmed carriers, 343 Microsoft-provenance files without a visual adjudication,
and 1200 non-overlapping no-signal controls. At the strict 0.38 gate, 15/17
confirmed carriers fired (min 0.249, p50 0.519, p90 0.578, max 0.579), while
0/1200 controls fired (p99 0.200, max 0.293). The provenance cohort produced
78/343 fires, but that is not a recall measurement because provenance identifies
the provider, not the presence of this visible layout. No provenance relaxation
ships until that cohort is visually labeled.
The detector and removal mask must use compatible geometry. A detector that
fires while producing an empty or misplaced mask is a removal failure even if
@@ -818,7 +843,7 @@ were briefly skipped there for exactly that reason.
A mark whose removable footprint differs from what the detector localizes
overrides `_footprint_rect` (which policy) and `_extend_match_box` (how far the
box grows), not the whole `footprint_mask`. Baidu extends right to the corner tag
and LibLibAI extends left to the triangle logo; both inherit every guard around
and LiblibAI extends left to the triangle logo; both inherit every guard around
that arithmetic.
Yuanbao uses the polarity-independent `contrast` front end because its standard
@@ -1020,11 +1045,13 @@ Validation happens before model loading. The library never treats OCR confidence
verification, and geometry-only operators do not need to invent text or script fields.
When enabled, `QwenZImagePipeline` reconstructs the source once through its already
loaded Qwen VAE, runs the ordinary global and face stages, blends 15% of the VAE
reconstruction into that clean result, and calls the shared restoration compositor.
The compositor derives binary source and candidate silhouettes, groups nearby lines,
uses LaMa for the initial and residual-glyph erase passes, paints fresh silhouette
edges, then copies the Qwen-VAE core with a 0.5-pixel feather. The evaluation script
loaded Qwen VAE, runs the ordinary global and face stages, and calls the shared
restoration compositor. The optional fidelity anchor first blends 15% of the VAE
reconstruction into the clean result; it is off by default because the blend returned
detector-visible OpenAI SynthID in the measured poster fixtures. The compositor derives
binary source and candidate silhouettes, groups nearby lines, uses LaMa for the initial
and residual-glyph erase passes, paints fresh silhouette edges, then copies the Qwen-VAE
core with a 0.5-pixel feather. The evaluation script
imports these same mask and compositing helpers so the two implementations cannot
silently drift. Silhouette crops start 12% of line height beyond each horizontal
side, then expand each side independently while a foreground component anchored
+6 -6
View File
@@ -563,8 +563,8 @@ independently and are not compared across detectors. Pass one of those explicit
values to restrict the scan to a single provider. The Veo detector recognizes
the current four-point diamond and the
legacy `Veo` text. Seedance recognizes the boxed `AI` label, Dola recognizes
its compact text label, Hailuo recognizes the composite MINIMAX/Hailuo label,
and Kling recognizes its bottom-right logo, wordmark, and version suffix. Each
its compact text label, Hailuo AI recognizes the composite MINIMAX/Hailuo AI label,
and Kling AI recognizes its bottom-right logo, wordmark, and version suffix. Each
variant has an independent synthetic silhouette and calibrated temporal policy.
After each accepted frame is filled, `temporal_consistency=True` motion-aligns
the preceding accepted fill and blends it only when the warped prior mask
@@ -644,10 +644,10 @@ engine.remove_watermark(
Install `remove-ai-watermarks[text-restoration]`. The manifest schema and safety
constraints are documented in the CLI guide. The engine verifies its decoded RGB
hash before loading the diffusion models and rejects SDXL, downscaling, and
postprocessing combinations that were not evaluated. Tiling is allowed: the VAE
donor uses the same overlapping tiles as the global pass. `InvisibleOptions` exposes the
same field for `remove_all`; after a visible-stage edit, the manifest must be built
against the staged pixels rather than the pristine source.
postprocessing combinations that were not evaluated. Tiling is also rejected because
the combined tiled-restoration path has no provider-oracle calibration. `InvisibleOptions`
exposes the same field for `remove_all`; after a visible-stage edit, the manifest must
be built against the staged pixels rather than the pristine source.
Use manifest schema 1 for manually reviewed text plus script metadata. Automated
operators that verify only text-region geometry should emit schema 2 lines with a
+4
View File
@@ -29,6 +29,10 @@ The package version appears in:
Update the first two, then refresh the lock file with uv. Do not edit a
line-number-specific location in `uv.lock`; its package order changes.
Before choosing a version, verify it is absent from git tags, GitHub Releases,
and PyPI. An unpublished remote tag still reserves that version; never move it,
publish the next version instead.
## Publish flow
PyPI publishing is triggered by a published GitHub Release, not by a tag push
+14 -7
View File
@@ -10,7 +10,7 @@ The `visible` command registers these mark keys:
| Key | Mark | Expected area | Important limit |
| --- | --- | --- | --- |
| `gemini` | Google Gemini sparkle | Usually bottom right | Detection includes a false positive gate. |
| `gemini` | Google Gemini visible watermark (sparkle) | Usually bottom right | Detection includes a false positive gate. |
| `doubao` | `豆包AI生成` | Bottom right | Vendor specific text detector. |
| `jimeng` | `★ 即梦AI` | Bottom right | Vendor specific text detector. |
| `qwen` | `千问AI生成` | Bottom right | Strict visual gate. |
@@ -19,7 +19,8 @@ The `visible` command registers these mark keys:
| `samsung` | `✦ Contenuti generati dall'AI` | Bottom left | Calibrated for the Italian text variant. |
| `runninghub` | `RunningHub AI生成` | Top left | Strict visual and position gates. |
| `baidu` | `百度 AI生成` | Bottom right | Detector and extended removal footprint. |
| `liblib` | `LibLibAI` | Bottom center | Includes a minimum image size gate. |
| `liblib` | `LiblibAI` | Bottom center | Includes a minimum image size gate. |
| `microsoft` | One Microsoft white AI-badge variant | Top right | Strict gate; other documented icon, text, and position variants are not covered. |
| `jimeng_pill` | `AI生成` pill | Top left | Weak detector with additional product and background gates. |
`--mark auto` evaluates all registered marks and removes every selected match.
@@ -38,7 +39,7 @@ when you can select the affected area yourself.
| `seedance` | Boxed `AI` label | Fixed bottom-right corner | Requires an anchored recurring match; the full localized box is filled because a thinner synthetic shape mask leaves the real translucent rim behind. |
| `dola` | `Dola AI` text | Fixed bottom-right corner | Requires an anchored recurring match; ByteDance or BytePlus provenance can relax only an existing visual run. |
| `hailuo` | `MINIMAX \| hailuo AI` composite label | Fixed lower edge | Uses a synthetic waveform, text, separator, and ring silhouette; the complete recurring label box is filled. A TC260 label naming MiniMax as producer can relax only an existing stable run. |
| `kling` | Kling swirl, `KLING AI`, version, and optional `PRO` suffix | Fixed bottom-right edge | Combines a synthetic logo rescue with font variants, an edge gate, a white-label gate, and anchored temporal recurrence. |
| `kling` | Kling AI swirl, `KLING AI`, version, and optional `PRO` suffix | Fixed bottom-right edge | Combines a synthetic logo rescue with font variants, an edge gate, a white-label gate, and anchored temporal recurrence. |
`video identify`, `video visible`, and `video all` share this registry and the
same temporal arbiter. It is separate from the image registry because selection
@@ -165,7 +166,12 @@ This project has no local Content Seal decoder. Meta Model API outputs and
Meta CDN copies carry an XMP `iptcExt:DigitalSourceType =
trainedAlgorithmicMedia` companion tag, which `identify` reports through the
existing Made-with-AI path; that IPTC code is a standard, not a Meta-exclusive
signal, so it cannot key a strength cohort the way the C2PA issuer does. The
signal, so it cannot key a strength cohort the way the C2PA issuer does. Since
0.33.0 a standalone AI digital-source tag (no C2PA manifest) additionally emits
the additive `content_seal` signal - the strength router's Meta bet as evidence,
medium confidence, with the same caveat - so clients select pixel removal from
the signal list exactly the way InvisMark is additive over `soft_binding`. It
is an attribution, never a decode. The
external oracle is `https://meta.ai/identification`: anonymous, no login,
accepts image, video, and audio, enforces an unspecified daily identification
limit, and answers with model attribution (`Muse Image 1 - Meta`) plus a
@@ -211,6 +217,7 @@ not a universal clean verdict.
| OpenAI image generators | None registered | Diffusion regeneration for supported invisible signals | C2PA and generator provenance |
| Meta Muse Image | None on Muse output (legacy `Imagined with AI` unregistered) | Diffusion regeneration for Content Seal, oracle-verified on the default profile | XMP IPTC `trainedAlgorithmicMedia` companion tag; no local Content Seal decoder |
| Microsoft Paint and Photos | None registered | External Microsoft oracle for InvisMark; no validated local decoder | Paint C2PA soft-binding algorithm and identifier |
| Microsoft image outputs (measured variant) | One top-right white AI-badge variant | No registered pixel decoder | C2PA attribution |
| Stable Diffusion and SDXL | None registered | Diffusion regeneration; optional open decoder | Embedded parameters and text metadata |
| FLUX | None registered | Diffusion regeneration; optional open decoder | C2PA for supported sources |
| Adobe Firefly | None registered | Optional TrustMark Variant P decoder | C2PA |
@@ -218,10 +225,10 @@ not a universal clean verdict.
| Luma AI | None registered | No registered pixel decoder | PNG text generator tags (Uni-1) |
| ByteDance generators | Doubao and Jimeng marks | No registered pixel decoder | TC260 AIGC, supported C2PA, and exact app-export AIGC disclosures |
| Qwen | Qwen mark | No registered pixel decoder | TC260 AIGC |
| Kling | Kling image and video marks | No registered pixel decoder | TC260 AIGC |
| Hailuo / MiniMax video | Hailuo composite video label | No registered pixel decoder | TC260 AIGC where present |
| Kling AI | Kling AI image and video marks | No registered pixel decoder | TC260 AIGC |
| Hailuo AI / MiniMax video | Hailuo AI composite video label | No registered pixel decoder | TC260 AIGC where present |
| Baidu | Baidu mark | No registered pixel decoder | TC260 AIGC |
| LibLibAI | LibLibAI mark | No registered pixel decoder | TC260 AIGC |
| LiblibAI | LiblibAI mark | No registered pixel decoder | TC260 AIGC |
| RunningHub | RunningHub mark | No registered pixel decoder | TC260 AIGC |
| Samsung Galaxy AI | One locale specific mark | No registered pixel decoder | C2PA and Samsung markers |
+5 -5
View File
@@ -24,7 +24,7 @@ Performance depends on format, enabled extras, and hardware. Measure it locally
## Tier A -- self-evident oracles (full corpus, unattended)
Properties that are true or false without anyone labelling anything. These are the
Properties that are true or false without anyone labeling anything. These are the
backbone: they scale to large local datasets and catch regressions with zero human cost.
### A1. Recorded-verdict regression
@@ -128,7 +128,7 @@ which read like twelve broken features. It was one bad harness parameter (`--ste
sitting on top of one real bug. An error that is IDENTICAL across unrelated rows is
evidence of a common cause, not of many faults -- check the shared input first.
## Tier B -- constructed ground truth (automatable, no labelling)
## Tier B -- constructed ground truth (automatable, no labeling)
Where reality gives no answer key, build one. This is the tier that closes the two biggest
holes: fill quality and detector response at the edge of the operating range.
@@ -169,7 +169,7 @@ Peak RSS and wall time per backend x input size, up to 25 MP. The memory-constra
tier is a real constraint (MI-GAN must stay ~0.6-0.9 GB by cropping around the mask); a
regression here is invisible today and would only surface under load.
## Tier C -- human-labelled accuracy (bounded by labelling effort)
## Tier C -- human-labeled accuracy (bounded by labeling effort)
The machinery exists: `visible_recall_sample.py` -> `visible_sheets.py` ->
`visible_groundtruth.py` -> `visible_eval.py`.
@@ -291,7 +291,7 @@ on one file. The bar is never "handles it" but **never raises and never silently
4. **B2 detector curves** -- cheap, and directly guards the geometry class of bug.
5. **A5 contract sweep over a representative local set**.
6. **B4 resource ceilings**, **E robustness**.
7. **C recall expansion** -- gated by labelling appetite.
7. **C recall expansion** -- gated by labeling appetite.
8. **D oracles** -- manual, per release.
Every tier writes a versioned snapshot so runs are comparable over time; a run that cannot
@@ -326,7 +326,7 @@ Per mark, what actually goes away when metadata is stripped:
### Measure before improving
Use Tier B2 detector-response curves before tuning a detector with sparse labelled
Use Tier B2 detector-response curves before tuning a detector with sparse labeled
examples. Sweep size, contrast, aspect, and background texture so geometry regressions
are visible without exposing private evaluation statistics.
+15 -15
View File
@@ -10,7 +10,7 @@ Who embeds what, and whether it is locally detectable (so we know which gaps are
**Root cause and external confirmation (deep-research 2026-06-19, adversarially verified).** This is the SCHEME's ceiling, not our usage — there is no better decoder to adopt. The imwatermark maintainers state verbatim (both the ShieldMnt and Stability-AI READMEs) that the algorithm "cannot guarantee to decode the original watermarks 100% accurately even though we don't apply any attack." Independent measurement (WMAdapter, arXiv:2406.08337 Table 2) puts dwtDct at only **~0.79 bit accuracy on CLEAN images (~38/48 bits — already below our 44 gate)**, collapsing to ~0.50 (chance) under crop/JPEG. Two code-verified + locally-reproduced mechanisms drive the content-dependent failures: (1) the decoder reads each bit as the **highest-magnitude DCT coefficient per block**, so any content coefficient exceeding the encoded target flips the bit; (2) the default embed is in the **YUV chroma channel, which 8-bit-clamps on white/bright pixels** (a +36 chroma delta survives a white-fill round-trip as only +4, ~89% loss) — this is the mechanism behind the bright-flat / minimalist failures and the all-ones degenerate decode. No maintained fork or detector decodes this scheme reliably: the WAVES benchmark (arXiv:2401.08573) relegates DWT-DCT to supplementary appendix G.5 and targets Stable Signature / Tree-Ring / StegaStamp instead; learned encoder/decoder schemes reach ~0.98-0.99 clean but are a DIFFERENT watermark class (not what SDXL/FLUX stamp). `dwtDctSvd` does not help (SDXL embeds `dwtDct`; dwtDctSvd cannot decode it, and its clean accuracy ~0.72 is lower). **Authoritative conclusion: the open DWT-DCT mark cannot be turned from positive-only into a reliable real-world detector; keep it positive-only and rely on C2PA.** (Refuted along the way: that the library is unmaintained, and that it is robust to JPEG but only fails on geometric attacks — both did not survive verification.)
Consequence for the FLUX hosted-output question (BFL Playground, FLUX.2 [pro] + FLUX.1 [dev], 2026-06-19): all samples carry the signed C2PA manifest (issuer "Black Forest Labs"); the open DWT-DCT decode returned `None`, but every available FLUX carrier (textured fox AND a minimalist-flat generation) failed the positive control (28/48), so the detector is blind on them and **whether BFL hosted output embeds the open pixel watermark is UNRESOLVED** (an earlier note here wrongly asserted it absent — overstated; a later note blamed "high texture" — also wrong, flat carriers fail too). What IS established: C2PA is the reliable FLUX identifier; the `_BITS_48` pattern is correct (round-trips on chatgpt/firefly/random). Resolving the hosted question needs a hosted FLUX carrier that first passes a >=44/48 positive control, which neither a textured nor a flat prompt produced — low priority (the open mark is only a stripped-metadata fallback).
- **C2PA / IPTC (covered by the issuer/marker scan):** OpenAI, Google, Adobe Firefly, Microsoft (Copilot + Designer; Bing Image Creator collected 2026-05-24 still signs as "Microsoft" and now runs **MAI-Image**, NOT OpenAI/DALL-E), **Stability AI** (collected from Brand Studio / DreamStudio successor; signs C2PA as "Stability AI Ltd", no SynthID, no imwatermark on its current Stable Image model — issuer added to `C2PA_ISSUERS`), and **Canva** (Magic Media signs C2PA as "Canva" + `trainedAlgorithmicMedia` with a generic `c2pa-rs` claim generator, no SynthID — issuer `b"Canva"` → "Canva (Magic Media)"; verified samples disproved the earlier assumption that Canva downloads always strip C2PA). Still unsampled: Getty, Shutterstock. Midjourney embeds NO C2PA and no invisible watermark (our `mj-*` sample carried only the IPTC tag).
- **C2PA / IPTC (covered by the issuer/marker scan):** OpenAI, Google, Adobe Firefly, Microsoft (Copilot + Designer; Bing Image Creator collected 2026-05-24 still signs as "Microsoft" and now runs **MAI-Image**, NOT OpenAI/DALL·E), **Stability AI** (collected from Brand Studio / DreamStudio successor; signs C2PA as "Stability AI Ltd", no SynthID, no imwatermark on its current Stable Image model — issuer added to `C2PA_ISSUERS`), and **Canva** (Magic Media signs C2PA as "Canva" + `trainedAlgorithmicMedia` with a generic `c2pa-rs` claim generator, no SynthID — issuer `b"Canva"` → "Canva (Magic Media)"; verified samples disproved the earlier assumption that Canva downloads always strip C2PA). Still unsampled: Getty, Shutterstock. Midjourney embeds NO C2PA and no invisible watermark (our `mj-*` sample carried only the IPTC tag).
**Samsung Galaxy AI** signs supported edits with C2PA and may carry the
proprietary `genAIType` marker. The registered visible detector covers the
@@ -28,7 +28,7 @@ take precedence over issuer attribution. Supported mappings include Higgsfield
AI, Topaz Labs Image API, and TikTok Ad Creative Toolbox; an unknown claim
generator still falls back to the certificate issuer.
**ByteDance Volcano Engine (Volcengine)** — the cloud behind Doubao / Jimeng — signs its AI image output with a cert from `certificate_center@volcengine.com` + `trainedAlgorithmicMedia` (issuer `b"volcengine"` → "ByteDance (Volcano Engine)", platform "ByteDance (Doubao / Jimeng / Dreamina / Volcano Engine)"); note this is the C2PA-signed surface, distinct from the XMP/PNG TC260 `AIGC` label Doubao also uses. ByteDance's **international brand (BytePlus / Seedream / Seededit)** signs the same content as **"Byteplus Pte. Ltd."**. The bare `volcengine` needle missed it, so BytePlus output was mis-attributed to "Adobe Firefly" through an incidental "Adobe XMP" toolkit string. Issuer `b"Byteplus"` now maps directly to "BytePlus (ByteDance)". ByteDance's consumer app **Dreamina** (the international Jimeng brand) signs as **"Bytedance Pte. Ltd."** with a `Dreamina/x.y` claim generator but, unlike the Volcano Engine surface, ships **no `trainedAlgorithmicMedia`**. Issuer `b"Dreamina"` maps to "ByteDance (Dreamina)" with **`asserts_ai=True`**. Registering the broader **issuer** `b"Bytedance Pte"` was deliberately avoided because that same entity also signs non-AI CapCut edits; keying on the `Dreamina` generator token is precise.
**ByteDance Volcano Engine (Volcengine)** — the cloud behind Doubao / Jimeng — signs its AI image output with a cert from `certificate_center@volcengine.com` + `trainedAlgorithmicMedia` (issuer `b"volcengine"` → "ByteDance (Volcano Engine)", platform "ByteDance Volcano Engine"); note this is the C2PA-signed surface, distinct from the XMP/PNG TC260 `AIGC` label Doubao also uses. ByteDance's **international brand (BytePlus / Seedream / Seededit)** signs the same content as **"Byteplus Pte. Ltd."**. The bare `volcengine` needle missed it, so BytePlus output was mis-attributed to "Adobe Firefly" through an incidental "Adobe XMP" toolkit string. Issuer `b"Byteplus"` maps directly to "BytePlus (ByteDance)". ByteDance's consumer app **Dreamina** (the international Jimeng brand) signs as **"Bytedance Pte. Ltd."** with a `Dreamina/x.y` claim generator but, unlike the Volcano Engine surface, ships **no `trainedAlgorithmicMedia`**. Issuer `b"Dreamina"` maps to "ByteDance Dreamina" with **`asserts_ai=True`**. Registering the broader **issuer** `b"Bytedance Pte"` was deliberately avoided because that same entity also signs non-AI CapCut edits; keying on the `Dreamina` generator token is precise.
- **EXIF/XMP/PNG-text generator tag (caught by `exif_generator`):** **Ideogram** writes EXIF `Make="Ideogram AI"` (collected 2026-05-24 — no C2PA, no SynthID, no imwatermark; the Make tag is the only signal). Additional verified generator stamps include **NovelAI** (`Software`, `Source`, and `Title` PNG text chunks), **Reve** (`Software` or XMP `CreatorTool` = `reve.com`), and **Aphrodite AI** (`Make` or `Software` = `Aphrodite AI`).
- **App-export provenance and AIGC JSON:** supported ByteDance-family exports can place a JSON object in EXIF `ImageDescription` or `UserComment`, independently of C2PA or TC260. Exact `product` values for Doubao, Xinghui, and Dreamina are removable product provenance, but do not alone prove that the pixels were generated. Dreamina additionally requires `exportType=generation` for that verdict. A nested Aweme `aigc_type=1` or private ByteDance `aigc_label_type=1` / `2` is an AIGC disclosure; `0` is inconclusive and can occur on a Dreamina generation export. Plain Aweme, retouch, and `lv` exports are preserved. The lower-case private field is deliberately not interpreted as the normative TC260 `Label`, whose values `1` / `2` / `3` mean generated / possibly generated / suspected generated under [GB 45438-2025](https://www.tc260.org.cn/upload/2025-03-15/1742009439794081593.pdf).
- **xAI / Grok — its own EXIF signature scheme, NOT C2PA (DETECTED by `metadata.xai_signature`, built 2026-05-26).**
@@ -58,7 +58,7 @@ defines two more native serializations. AVI stores an `AIGC` child in
bounded RIFF and FLV readers validate the JSON field set and skip media
payloads. Removal remuxes either container through ffmpeg with stream copy.
- **HuggingFace-hosted job (caught by `metadata.huggingface_job`, surfaced by `identify` as the `hf_job` signal, MEDIUM confidence):** HuggingFace Jobs / Spaces can stamp generated PNGs with an `hf-job-id` tEXt chunk holding the job UUID. It marks the *hosting job*, not a model, so it lifts an Unknown verdict to a tentative AI via `hf_only` but never overrides a hard metadata signal. `_HF_JOB_CAVEAT` states the limit. Removal drops the chunk through the PNG metadata whitelist.
- **Hugging Face-hosted job (caught by `metadata.huggingface_job`, surfaced by `identify` as the `hf_job` signal, MEDIUM confidence):** Hugging Face Jobs / Spaces can stamp generated PNGs with an `hf-job-id` tEXt chunk holding the job UUID. It marks the *hosting job*, not a model, so it lifts an Unknown verdict to a tentative AI via `hf_only` but never overrides a hard metadata signal. `_HF_JOB_CAVEAT` states the limit. Removal drops the chunk through the PNG metadata whitelist.
- **No detectable signal on some downloads:** Recraft exports and some hosted
FLUX surfaces can arrive without a supported local signal. Midjourney samples
may carry IPTC metadata but no registered C2PA or pixel watermark. The open
@@ -70,7 +70,7 @@ payloads. Removal remuxes either container through ffmpeg with stream copy.
- **Built in the dated batch:** soft-binding vendor detection, IPTC Photo
Metadata AI-disclosure fields, C2PA detection and stripping for supported
ISOBMFF video, the optional Adobe TrustMark decoder, and temporally stabilized
visible Sora, Veo, Seedance, Dola, Hailuo, and Kling removal. Other visible
visible Sora, Veo, Seedance, Dola, Hailuo AI, and Kling AI removal. Other visible
video logos and proprietary audio-watermark detection remain outside the
package.
Metadata stripping for supported audio containers is a separate implemented
@@ -116,12 +116,12 @@ every frame, then requires an anchored temporal run. This extra anchor check
was necessary because a moving clean scene detail could retain enough adjacent
overlap to pass a recurrence-only gate.
**Hailuo and Kling use larger fixed composite labels.** Verified Hailuo exports
carry a lower-edge waveform, `MINIMAX`, separator, Hailuo ring, and
`hailuo AI` text. Verified Kling exports carry a bottom-right swirl,
**Hailuo AI and Kling AI use larger fixed composite labels.** Verified Hailuo AI exports
carry a lower-edge waveform, `MINIMAX`, separator, Hailuo AI ring, and
`hailuo AI` text. Verified Kling AI exports carry a bottom-right swirl,
`KLING AI`, a changing version suffix, and sometimes `PRO`. The detectors use
only synthetic primitives and fonts. Hailuo expands the matched core to cover
the complete composite. Kling combines a version-independent text core with a
only synthetic primitives and fonts. Hailuo AI expands the matched core to cover
the complete composite. Kling AI combines a version-independent text core with a
synthetic ring rescue, then requires the recurring candidate to reach the
expected frame edge and contain enough bright low-saturation pixels. Those
extra gates were added after clean Luma and PixVerse scene details passed shape
@@ -131,17 +131,17 @@ instead uses Florence-2 to identify arbitrary watermarks before LaMa
inpainting. That is broader, but it carries a much heavier model and a less
auditable detection boundary than the provider-specific synthetic path here.
**The faint-visible-mark precision/recall wall is fundamental, not a heuristic artifact.** The visible-watermark-detection literature has moved to LEARNED segmentation / object-detection (WDNet WACV'21 arXiv:2012.07616; SLBR ACM MM'21, open code+weights; the PRCV'18 large-scale detector; Su et al. survey 2025), but three verified findings bound what a learned detector actually buys: (1) a claim that a confidence threshold "cleanly separates" true from false matches even with a learned CNN front-end was **REFUTED** in verification (arXiv:1705.08593) -- the precision/recall wall persists even with learned features. (2) Learned detectors need a LARGE, pattern-diverse labeled dataset trained on synthetic composites (PRCV'18: 60k images / 80 watermark classes; CLWD: 60k / 160 marks), and off-distribution degradation is a documented real axis (models trained on limited-pattern LVW transfer worse; diversity of training patterns drives generalization). (3) Inference is cheap (WDNet ~8 ms at 256x256) -- the cost is the data pipeline, not runtime. Net: a learned detector shifts the frontier but does NOT remove the wall; for a SINGLE mark the cheapest next step is a small patch classifier (real-sparkle vs false-positive) on top of the existing NCC localizer, not a full segmentation model. SLBR is a ready baseline. The current NCC + false-positive gate (core-ring brightness margin + gradient-NCC crispness + white-core saturation) is a sound operating point, and the residual miss is the information-theoretic wall the literature confirms.
**Learned detectors change the visible-mark precision/recall tradeoff; they do not establish a universal separator.** The visible-watermark-detection literature has moved to learned segmentation and object detection (WDNet WACV'21 arXiv:2012.07616; SLBR ACM MM'21, open code and weights; the PRCV'18 large-scale detector; Su et al. survey 2025). The cited arXiv:1705.08593 paper reports a method that significantly reduces false matches and eliminates them after rejecting a small fraction of matches on its electron-microscopy task; it does not prove an information-theoretic limit for watermark detection. Learned watermark detectors also rely on large, pattern-diverse labeled datasets built with synthetic composites (PRCV'18: 60k images / 80 watermark classes; CLWD: 60k / 160 marks), and transfer depends on the diversity represented in training. Inference can be cheap (WDNet reports roughly 8 ms at 256x256), while the labeled-data and evaluation pipeline remain the larger project cost. A learned detector is therefore a possible future operating point, not evidence that the current NCC gate is theoretically optimal.
**Visible-mark landscape beyond the registry.** Since Muse Image (2026-07) Meta's own generation output carries NO visible mark, only the invisible proprietary Content Seal; the legacy visible "Imagined with AI" mark (bottom-LEFT, a small symbol) belongs to the pre-2026 Meta AI / "Imagine" pipeline and remains unregistered (string verified, position not). For third-party images Meta 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.
**Visible-mark landscape beyond the registry.** Since Muse Image (2026-07) Meta's own generation output carries no visible mark, only the invisible proprietary Content Seal; the legacy visible "Imagined with AI" mark belongs to the pre-2026 Meta AI / "Imagine" pipeline and remains unregistered (string verified, position not). For third-party images Meta relies on C2PA / IPTC, not a visible mark. The Samsung detector covers only the measured Italian text wordmark; no separate icon-only variant has been verified. Visible overlays and embedded metadata can usually be removed without changing the underlying generation model, 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. Several such CJK text marks are now registered; see [supported signals](supported-signals.md) for the current list. 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)
Compatibility testing showed that TC260-labelled images can still produce no visible-mark
Compatibility testing showed that TC260-labeled images can still produce no visible-mark
detection. The main causes were a fixed Doubao localization defect and genuinely
uncovered vendors. Verification status is labelled per claim; treat (b)/(c) as leads,
uncovered vendors. Verification status is labeled 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:
@@ -153,7 +153,7 @@ not ground truth.
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`.
**Alibaba Cloud 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.
@@ -165,7 +165,7 @@ Two consequences we can exploit: (1) the 5% floor is a **scale prior** -- a comp
**Meta `Imagined with AI` (string VERIFIED (a) from Meta's own newsroom; POSITION NOT VERIFIED).** Sources conflict on placement. Do not encode a corner without a verified sample. A dedicated 2026-08-27 sample hunt failed to obtain one: the Feb-2024 newsroom images are UI mockups whose photos carry no in-pixel mark; community posts (Threads `C8_rS_MuEId` titled "lower left corner", a Facebook share) corroborate bottom-LEFT verbally but their files defeat pixel verification; press screenshots predate the mark (Dec 2023); `imagine.meta.com` is dead (redirects to meta.ai) and its Wayback captures are broken SPA error pages. The mark's generator no longer exists (Muse output has no visible mark), so no fresh sample can be made. Removal stays on the generic `erase --region` path until a legacy capture surfaces. 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.
**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. No separate icon-only variant was established.
**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.
+1 -1
View File
@@ -4,7 +4,7 @@
# on it, including the ComfyUI node package. The console script below carries
# the same weight, since users have it on PATH.
name = "remove-ai-watermarks"
version = "0.32.1"
version = "0.34.0"
description = "AI watermark remover for visible, invisible, and provenance marks in images and video"
readme = "README.md"
requires-python = ">=3.11,<3.15"
+69
View File
@@ -0,0 +1,69 @@
# Maintainer scripts
These scripts are development and evaluation tools, not installed CLI commands. Run
them from the repository root with `uv run python scripts/<name>.py --help`. Inputs
under `.local-eval/` and generated reports remain untracked unless a data README
explicitly names a tracked canonical result.
## Audits and release checks
| Script | Purpose |
| --- | --- |
| `corpus_gap_scan.py` | Compare a local image corpus with the library's `identify` results. |
| `detection_timing.py` | Record per-method metadata and verdict timings. |
| `detection_timing_report.py` | Aggregate timing records by method and segment. |
| `fidelity_metrics.py` | Compute objective image-fidelity metrics for paired outputs. |
| `invisible_quality_audit.py` | Pair originals and invisible-removal outputs for quality review. |
| `metadata_removal_audit.py` | Check metadata detection/removal parity over a corpus. |
| `pill_gate_audit.py` | Measure the Jimeng pill detector on the product path. |
| `real_examples_e2e.py` | Run end-to-end confidence checks over local examples. |
| `record_parity_audit.py` | Compare record-based and file-based identification. |
| `resource_ceilings.py` | Measure peak RSS and runtime for fill backends. |
| `robustness_suite.py` | Exercise CLI failures on adversarial and degenerate inputs. |
| `sidecar_regression.py` | Compare current identification with recorded sidecars. |
| `smoke_matrix.py` | Exercise CLI parameter choices on real local data. |
| `video_fidelity_probe.py` | Compare delivered video fidelity with its source. |
| `visible_eval.py` | Benchmark registered visible-mark detectors. |
| `visible_removal_audit.py` | Audit visible-removal results over a local corpus. |
## Calibration and corpus preparation
| Script | Purpose |
| --- | --- |
| `contentseal_transforms.py` | Reproduce and hash-check deterministic Content Seal variants. |
| `detector_response.py` | Measure detector response over mark size, contrast, background, and aspect. |
| `fill_quality.py` | Measure visible-fill quality against constructed ground truth. |
| `ladder_headroom.py` | Measure recall cost from the coarse scale ladder. |
| `registered_mark_calibrate.py` | Measure a registered detector without conflating visual positives, metadata cohorts, adjudicated negatives, and unlabeled controls. |
| `synthid_corpus.py` | Ingest and inspect the local SynthID reference corpus. |
| `vendor_cohort_harvest.py` | Partition TC260 carriers by producer code. |
| `vendor_mark_calibrate.py` | Calibrate a candidate vendor text detector. |
| `visible_alpha_solve.py` | Rebuild visible-watermark alpha assets from controlled captures. |
| `visible_groundtruth.py` | Consolidate blinded contact-sheet labels into ground truth. |
| `visible_positives.py` | List corpus images carrying a registered visible mark. |
| `visible_recall_sample.py` | Build an unbiased blinded sample for recall measurement. |
| `visible_sheets.py` | Build blinded contact sheets for relaxation candidates. |
## Research and diagnostic prototypes
| Script | Purpose |
| --- | --- |
| `cjk_tail_probe.py` | Test a generic template for otherwise uncovered CJK labels. |
| `controlnet_sweep.py` | Sweep the historical ControlNet removal prototype. |
| `infer_text_lines.py` | Draft stable source-text lines without modifying pixels. |
| `qwen_scrub_prototype.py` | Probe low-strength Qwen regeneration on a GPU. |
| `selective_text_restoration.py` | Evaluate text restoration over a scrubbed image. |
| `synthid_pixel_probe.py` | Run the experimental local SynthID carrier probe. |
| `video_synthid_sweep.py` | Build oracle-gated video regeneration candidates. |
## Generated assets
| Script | Purpose |
| --- | --- |
| `render_pill_silhouette.py` | Render the synthetic Jimeng pill silhouette. |
| `render_vendor_silhouettes.py` | Render synthetic vendor text-mark silhouettes. |
## Shared helpers
`_plain_console.py` provides plain-text fallbacks for Rich output, and
`_text_eval.py` contains normalization helpers shared by text-evaluation scripts.
@@ -0,0 +1,26 @@
# Unregistered visible-mark candidates
Synthetic detection silhouettes for marks that are measured but NOT registered:
none of these separates its positives from clean negatives yet, so shipping them
would attribute and fill corners on content that carries no mark (a false fill
is the worse error). Assets are regenerated by
`scripts/render_vendor_silhouettes.py`; a candidate is deleted from here on the
day its mark registers (the asset moves to the package `assets/`).
Measurements below are local calibration snapshots. Candidate pools are
provenance cohorts, not automatically visible-mark positives; comparison controls
are independently selected no-signal images and are not adjudicated negatives.
Each needs capture-solved alphas or vendor-accurate font work before it can
ship; `scripts/vendor_mark_calibrate.py` is the candidate-detector harness.
| Asset | Mark | Evidence | Result |
| --- | --- | --- | --- |
| `samsung_en_alpha.png` | Samsung Galaxy AI label, English locale ("AI-generated content", bottom-left) | 5 corpus files | POS 0.11-0.30 vs NEG max 0.40 (binary); tophat/gray tried, no separation. The registered Italian engine scores 0.18-0.31 on the same files -- same layout class, wrong glyph template. |
| `gemini_text_alpha.png` | "Generated with Gemini" text label (bottom-right; the registered gemini mark is the sparkle icon) | 3 corpus files | POS 0.07-0.22 vs NEG max 0.32; coverage gate finds the blob (0.29-0.35) but the Arial silhouette misses Google's letterforms. |
| `notebooklm_alpha.png` | NotebookLM wordmark (bottom-right) | 12 corpus files | locate geometry not yet fitted; POS max 0.12. |
| `dola_alpha.png` | DolaAI on images (the video mark is registered) | 12 corpus files | POS 0.11-0.21 vs NEG max 0.30. |
| `mindvideo_alpha.png` | MindVideo.AI (top-right) | 11 corpus files | POS 0.29-0.32 vs NEG max 0.30 -- borderline overlap, not shippable. |
| `xinghui_alpha.png` | 星绘AI生成 (parked before this set) | -- | prior parking, unchanged. |
| `qingyan_alpha.png` | 清言·AI生成 (parked before this set) | -- | prior parking, unchanged. |
| `hailuo_alpha.png` | Hailuo AI image wordmark (parked before this set; the VIDEO label is registered) | -- | prior parking, unchanged. |
| `catlogo_alpha.png` | outline cat-head + AI生成 (parked before this set) | -- | prior parking, unchanged. |
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

+1 -1
View File
@@ -1,7 +1,7 @@
"""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
Corpus inspection of doubao-provenance misses turned up `千问AI生成` (Alibaba Cloud 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
+82
View File
@@ -0,0 +1,82 @@
#!/usr/bin/env python3
"""Reproduce the deterministic Content Seal crop, resize, and JPEG variants."""
from __future__ import annotations
import argparse
import csv
import hashlib
import logging
from pathlib import Path
from PIL import Image
log = logging.getLogger(__name__)
ROOT = Path(__file__).resolve().parents[1]
CORPUS = ROOT / "data" / "contentseal"
MANIFEST = CORPUS / "manifest.csv"
def _rows() -> dict[str, dict[str, str]]:
with MANIFEST.open(newline="", encoding="utf-8") as stream:
return {row["name"]: row for row in csv.DictReader(stream)}
def _write_and_verify(image: Image.Image, path: Path, row: dict[str, str], *, format: str, quality: int) -> None:
image.save(path, format=format, quality=quality)
digest = hashlib.sha256(path.read_bytes()).hexdigest()
if digest != row["sha256"]:
raise RuntimeError(f"{row['name']} hash mismatch: expected {row['sha256']}, got {digest}")
log.info("Verified %s", path)
def reproduce_transforms(output_dir: Path) -> list[Path]:
"""Write and hash-check the eight deterministic manifest variants."""
rows = _rows()
output_dir.mkdir(parents=True, exist_ok=True)
outputs: list[Path] = []
for prefix, source_name in (("fox", "gen_fox_forest"), ("text", "gen_text_poster")):
with Image.open(CORPUS / rows[source_name]["file"]) as opened:
source = opened.convert("RGB")
for fraction in (0.5, 0.33):
width = int(source.width * fraction)
height = int(source.height * fraction)
left = (source.width - width) // 2
top = (source.height - height) // 2
name = f"{prefix}_crop{int(fraction * 100)}"
path = output_dir / f"{name}.webp"
crop = source.crop((left, top, left + width, top + height))
_write_and_verify(crop, path, rows[name], format="WEBP", quality=95)
outputs.append(path)
scale = 512 / max(source.size)
resized = source.resize(
(round(source.width * scale), round(source.height * scale)),
Image.Resampling.LANCZOS,
)
name = f"{prefix}_res512"
path = output_dir / f"{name}.webp"
_write_and_verify(resized, path, rows[name], format="WEBP", quality=95)
outputs.append(path)
name = f"{prefix}_jpeg85"
path = output_dir / f"{name}.jpg"
_write_and_verify(source, path, rows[name], format="JPEG", quality=85)
outputs.append(path)
return outputs
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("output_dir", type=Path, help="Directory for regenerated variants")
args = parser.parse_args()
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
reproduce_transforms(args.output_dir)
if __name__ == "__main__":
main()
+1 -1
View File
@@ -39,7 +39,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))
from detection_timing import COMPONENTS as _TIMED
# Taken from the script that WROTE the rows, in its order, so a probe added, removed
# or reordered there cannot silently leave a column missing or mislabelled here.
# or reordered there cannot silently leave a column missing or mislabeled here.
COMPONENTS = tuple(name for name, _ in _TIMED)
METHODS = (
("cold_extract_evidence_ms", "extract_provenance_evidence (cold)"),
+2 -2
View File
@@ -81,7 +81,7 @@ def find_visible_positive(mark: str) -> Path | None:
class Results:
"""Collects one row per checked behaviour.
"""Collects one row per checked behavior.
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
@@ -166,7 +166,7 @@ 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
decided, and the decision is right". Two designed behaviors 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
+175
View File
@@ -0,0 +1,175 @@
"""Measure a registered visible-mark detector on independently labeled arms.
The input is a JSONL manifest with exactly two fields per row:
``path``
Absolute path, or a path relative to the manifest.
``arm``
``positive`` for a visually confirmed carrier, ``metadata`` for a
provenance-only cohort, ``negative`` for an independently adjudicated
no-mark image, or ``control`` for an unlabeled comparison image with no
known local signal.
The arms stay separate because metadata names a provider, not the presence of a
visible mark, and missing local signals do not make an image a true negative. The
script imports the registered engine and reads its shipped gate, so calibration
cannot silently use a copied configuration.
Input images and manifests are read-only. Keep private inputs and generated
manifests outside the repository or in a gitignored evaluation directory.
uv run python scripts/registered_mark_calibrate.py microsoft manifest.jsonl
"""
from __future__ import annotations
import argparse
import json
import math
import sys
from collections import Counter
from pathlib import Path
from typing import Any, Literal, TypedDict, cast
REPO = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(REPO / "src"))
from remove_ai_watermarks import watermark_registry # noqa: E402
from remove_ai_watermarks.image_io import imread # noqa: E402
Arm = Literal["positive", "metadata", "negative", "control"]
_ARMS: tuple[Arm, ...] = ("positive", "metadata", "negative", "control")
class ManifestRow(TypedDict):
path: str
arm: Arm
class ArmSummary(TypedDict):
n: int
unreadable: int
min: float | None
p50: float | None
p90: float | None
p99: float | None
max: float | None
fires: int
def _percentile(ordered: list[float], fraction: float) -> float | None:
"""Return a nearest-rank percentile from values sorted in ascending order."""
if not ordered:
return None
return ordered[max(0, math.ceil(fraction * len(ordered)) - 1)]
def summarize(values: list[float], *, unreadable: int, fires: int) -> ArmSummary:
"""Summarize one independently defined arm without inferring its label."""
ordered = sorted(values)
return {
"n": len(values),
"unreadable": unreadable,
"min": _percentile(ordered, 0.0),
"p50": _percentile(ordered, 0.5),
"p90": _percentile(ordered, 0.9),
"p99": _percentile(ordered, 0.99),
"max": _percentile(ordered, 1.0),
"fires": fires,
}
def load_manifest(path: Path) -> list[ManifestRow]:
"""Load and validate a manifest, resolving relative paths beside it."""
rows: list[ManifestRow] = []
seen: set[Path] = set()
with path.open(encoding="utf-8") as manifest:
for line_number, line in enumerate(manifest, 1):
if not line.strip():
continue
raw = json.loads(line)
if not isinstance(raw, dict) or set(raw) != {"path", "arm"}:
raise ValueError(f"{path}:{line_number}: expected exactly path and arm")
raw_path = raw["path"]
raw_arm = raw["arm"]
if not isinstance(raw_path, str) or not raw_path:
raise ValueError(f"{path}:{line_number}: path must be a non-empty string")
if raw_arm not in _ARMS:
raise ValueError(f"{path}:{line_number}: arm must be one of {', '.join(_ARMS)}")
image_path = Path(raw_path)
if not image_path.is_absolute():
image_path = path.parent / image_path
image_path = image_path.resolve()
if image_path in seen:
raise ValueError(f"{path}:{line_number}: duplicate image path {image_path}")
seen.add(image_path)
rows.append({"path": str(image_path), "arm": cast("Arm", raw_arm)})
if not rows:
raise ValueError(f"{path}: manifest is empty")
return rows
def measure(mark: str, rows: list[ManifestRow]) -> tuple[float, dict[Arm, ArmSummary]]:
"""Score every row with the registered engine and its current shipped gate."""
registered_mark = watermark_registry.get_mark(mark)
# Calibration intentionally resolves the registry's concrete engine so it
# cannot drift onto a copied configuration.
engine = watermark_registry._engine(mark)
config = getattr(engine, "config", None)
gate = getattr(config, "detect_ncc_threshold", None)
if not isinstance(gate, int | float):
raise ValueError(f"registered mark {mark!r} does not expose a text-detector NCC gate")
scores: dict[Arm, list[float]] = {arm: [] for arm in _ARMS}
unreadable: Counter[Arm] = Counter()
fires: Counter[Arm] = Counter()
for row in rows:
image = imread(row["path"])
if image is None:
unreadable[row["arm"]] += 1
continue
detection: Any = registered_mark.detect(image)
scores[row["arm"]].append(float(detection.confidence))
fires[row["arm"]] += bool(detection.detected)
threshold = float(gate)
return threshold, {arm: summarize(scores[arm], unreadable=unreadable[arm], fires=fires[arm]) for arm in _ARMS}
def _format_stat(value: float | None) -> str:
return "-" if value is None else f"{value:.3f}"
def print_report(mark: str, gate: float, summaries: dict[Arm, ArmSummary]) -> None:
"""Print a compact human-readable calibration report."""
print(f"registered mark: {mark} gate: {gate:.3f}")
print(
f"{'arm':10s} {'n':>5s} {'bad':>5s} {'min':>7s} {'p50':>7s} {'p90':>7s} {'p99':>7s} {'max':>7s} {'fires':>7s}"
)
for arm in _ARMS:
row = summaries[arm]
print(
f"{arm:10s} {row['n']:5d} {row['unreadable']:5d} "
f"{_format_stat(row['min']):>7s} {_format_stat(row['p50']):>7s} "
f"{_format_stat(row['p90']):>7s} {_format_stat(row['p99']):>7s} "
f"{_format_stat(row['max']):>7s} {row['fires']:7d}"
)
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("mark", choices=watermark_registry.mark_keys())
parser.add_argument("manifest", type=Path)
parser.add_argument("--json", action="store_true", help="emit machine-readable JSON")
args = parser.parse_args()
rows = load_manifest(args.manifest)
gate, summaries = measure(args.mark, rows)
if args.json:
print(json.dumps({"mark": args.mark, "gate": gate, "arms": summaries}, sort_keys=True))
else:
print_report(args.mark, gate, summaries)
if __name__ == "__main__":
main()
+123 -17
View File
@@ -12,11 +12,14 @@ from __future__ import annotations
import sys
from pathlib import Path
from typing import Any
from typing import TYPE_CHECKING, Any
import numpy as np
from PIL import Image, ImageDraw, ImageFont
if TYPE_CHECKING:
from collections.abc import Callable
_ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(_ROOT / "src"))
@@ -42,7 +45,7 @@ MARKS = {
"kling_alpha.png": "可灵AI 3.0",
# The "cat-logo" candidate stamps an outline cat-head plus bold "AI生成",
# bottom-right. It remains unregistered pending sufficient calibration coverage.
"catlogo_alpha.png": "CATLOGO", # sentinel: drawn by draw_catlogo(), not font-rendered
"catlogo_alpha.png": "cat logo + AI生成",
# RunningHub top-left text mark.
"runninghub_alpha.png": "RunningHub AI生成",
# LibLibAI bottom-center wordmark.
@@ -53,6 +56,19 @@ MARKS = {
"hailuo_alpha.png": "Hailuo AI",
# Baidu bottom-right text run.
"baidu_alpha.png": "百度",
# Measured Microsoft top-right white AI-badge variant. Sentinel: drawn by
# draw_msbadge(), not font-rendered.
"microsoft_alpha.png": "Made with AI",
# Samsung Galaxy AI label, English locale (the registered samsung_alpha.png is
# the Italian "Contenuti generati dall'AI" silhouette; EN is the literal
# translation with the same leading sparkle). Sentinel: draw_samsung_en().
"samsung_en_alpha.png": "AI-generated content",
# Gemini text-form label (the registered gemini mark is the sparkle icon).
"gemini_text_alpha.png": "Generated with Gemini",
# Candidate wordmarks measured on a local evaluation corpus (unregistered).
"notebooklm_alpha.png": "NotebookLM",
"dola_alpha.png": "DolaAI",
"mindvideo_alpha.png": "MindVideo.AI",
}
_REGISTERED = {f"{key}_alpha.png" for key in mark_keys()} & MARKS.keys()
@@ -74,6 +90,24 @@ MARK_OPTS: dict[str, dict[str, Any]] = {
}
def _fit_font(
font_path: str,
reaches_target: Callable[[ImageFont.FreeTypeFont], bool],
*,
index: int = 0,
) -> ImageFont.FreeTypeFont:
"""Return the smallest 8-200 px font that reaches a render target."""
low, high = 8, 200
while low < high:
size = (low + high) // 2
font = ImageFont.truetype(font_path, size, index=index)
if reaches_target(font):
high = size
else:
low = size + 1
return ImageFont.truetype(font_path, low, index=index)
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.
@@ -91,13 +125,11 @@ def render(text: str, width: int = 335, opts: dict[str, Any] | None = None) -> n
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)
font = _fit_font(
font_path,
lambda f: max(d0.textbbox((0, 0), ln, font=f)[2] for ln in lines) >= width * 0.98,
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))
@@ -138,13 +170,7 @@ def draw_catlogo(width: int = 335) -> np.ndarray:
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)
font = _fit_font(_FONT, lambda f: d0.textbbox((0, 0), text, font=f)[2] >= width * 0.60)
bb = d0.textbbox((0, 0), text, font=font)
tw, th = bb[2] - bb[0], bb[3] - bb[1]
cs = int(th * 1.08)
@@ -182,10 +208,90 @@ def draw_catlogo(width: int = 335) -> np.ndarray:
return np.array(im)
def _star_pts(cx: float, cy: float, r: float, waist: float) -> list[tuple[float, float]]:
return [
(cx, cy - r),
(cx + r * waist, cy - r * waist),
(cx + r, cy),
(cx + r * waist, cy + r * waist),
(cx, cy + r),
(cx - r * waist, cy + r * waist),
(cx - r, cy),
(cx - r * waist, cy - r * waist),
]
def _sparkle(draw: ImageDraw.ImageDraw, cx: float, cy: float, r: float) -> None:
"""Draw the four-point cutout used by synthetic candidate silhouettes."""
draw.polygon(_star_pts(cx, cy, r, 0.22), fill=0)
def draw_msbadge(width: int = 335) -> np.ndarray:
"""Synthetic silhouette for the measured Microsoft top-right white pill.
The top-hat front-end sees the bright pill with dark-text holes, so the template
carries the same holes -- that is what discriminates this pill from any other
white rounded element in the top-right corner. The text and four-point cutout
approximate the measured internal shape; they do not assert one universal
Microsoft icon or wording. Geometry measured on 17 visually confirmed carriers
on 2026-08-27: pill 0.152W x 0.040W, margins ~0.010W right / ~0.007W top,
glyph height ~0.39 of pill height.
"""
h = round(width / 3.78)
im = Image.new("L", (width, h), 0)
d = ImageDraw.Draw(im)
d.rounded_rectangle([0, 0, width - 1, h - 1], radius=h // 2, fill=255)
font_path = "/System/Library/Fonts/Supplemental/Arial Bold.ttf"
text = "Made with AI"
probe = Image.new("L", (10, 10))
d0 = ImageDraw.Draw(probe)
font = _fit_font(font_path, lambda f: d0.textbbox((0, 0), text, font=f)[3] >= h * 0.39)
bb = d0.textbbox((0, 0), text, font=font)
th = bb[3] - bb[1]
r = h * 0.20 # sparkle radius, ~half the text height
pad_l = h * 0.22
cx = pad_l + r
cy = h / 2 - 1
tx = int(pad_l + 2 * r + h * 0.22)
d.text((tx - bb[0], (h - th) // 2 - bb[1]), text, font=font, fill=0)
_sparkle(d, cx, cy, r)
return np.array(im)
def draw_samsung_en(width: int = 335) -> np.ndarray:
"""Samsung Galaxy AI English label: "AI-generated content" with the leading
4-point sparkle, light-gray glyphs (same class as the registered Italian asset)."""
text = "AI-generated content"
font_path = "/System/Library/Fonts/Supplemental/Arial.ttf"
probe = Image.new("L", (10, 10))
d0 = ImageDraw.Draw(probe)
font = _fit_font(font_path, lambda f: d0.textbbox((0, 0), text, font=f)[2] >= width * 0.80)
bb = d0.textbbox((0, 0), text, font=font)
tw, th = bb[2] - bb[0], bb[3] - bb[1]
r = th * 0.55
gap = th * 0.45
im = Image.new("L", (int(tw + gap + 2 * r + 8), th + 8), 0)
d = ImageDraw.Draw(im)
# sparkle as bright glyph (this silhouette is light-glyph class, not a pill)
d.polygon(_star_pts(4 + r, 4 + th / 2, r, 0.22), fill=255)
d.text((4 + 2 * r + gap - bb[0], 4 - bb[1]), text, font=font, fill=255)
arr = np.array(im)
ys, xs = np.where(arr > 0)
return arr[ys.min() : ys.max() + 1, xs.min() : xs.max() + 1]
_CUSTOM_RENDERERS = {
"catlogo_alpha.png": draw_catlogo,
"microsoft_alpha.png": draw_msbadge,
"samsung_en_alpha.png": draw_samsung_en,
}
def main() -> None:
try:
for name, text in MARKS.items():
sil = draw_catlogo() if text == "CATLOGO" else render(text, opts=MARK_OPTS.get(name))
renderer = _CUSTOM_RENDERERS.get(name)
sil = renderer() if renderer is not None else render(text, opts=MARK_OPTS.get(name))
output_dir = _PACKAGE_ASSETS if name in _REGISTERED else _CANDIDATE_ASSETS
output_dir.mkdir(parents=True, exist_ok=True)
output = output_dir / name
+1 -1
View File
@@ -15,7 +15,7 @@ THE KEY
``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
in it is eyeballed, every frame in it is a labeled 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
+4 -4
View File
@@ -14,7 +14,7 @@ WHERE THE POSITIVES COME FROM
absence) visible directly.
NEGATIVES
The 432 frames hand-labelled `present: []` in the 2026-07-18 round -- already-adjudicated
The 432 frames hand-labeled `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.
@@ -115,7 +115,7 @@ def load_sets(cohort: str) -> tuple[list[str], list[str]]:
# 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:
# visibly carrying 千问AI生成 are labeled `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".
@@ -168,7 +168,7 @@ def report(pos: list[dict[str, Any]], neg: list[dict[str, Any]], name: str) -> N
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{'=' * 78}\n{name}: candidate-cohort vs hand-labeled 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):
@@ -602,7 +602,7 @@ def main() -> None:
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"cohort {a.cohort}: {len(pos_paths)} candidates | clean: {len(neg_paths)} hand-labeled")
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)
+4 -4
View File
@@ -1,7 +1,7 @@
"""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 --
hand-labeled 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
@@ -10,10 +10,10 @@ with Wilson intervals, so a change inside the noise is visible as such.
WHAT THIS SET CAN AND CANNOT MEASURE -- read before quoting a number:
* PRECISION: sound. Every labelled crop is centred on the region a detector
* PRECISION: sound. Every labeled crop is centered 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
* RECALL: NOT measurable here, and the harness refuses to print it. The labeled
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
@@ -133,7 +133,7 @@ def report(res: dict, prev: dict | None = None) -> None:
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("\n'scope' = images whose crop could rule on that mark; 'missed' = labeled 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.")
+18 -9
View File
@@ -1,6 +1,6 @@
"""Consolidate the hand-labelled contact-sheet rounds into ONE ground-truth file.
"""Consolidate the hand-labeled contact-sheet rounds into ONE ground-truth file.
Ground truth is `uid -> the set of visible marks actually present`, hand-labelled
Ground truth is `uid -> the set of visible marks actually present`, hand-labeled
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)
@@ -10,20 +10,20 @@ DATA SAFETY: treat the input dataset as sensitive. This script reads a gitignore
dataset 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:
The labels record what the labeler 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
`uncertain` rows are EXCLUDED from scoring rather than coerced, so a labeler's
honest doubt never becomes a fabricated data point.
"""
from __future__ import annotations
import argparse
import csv
import json
import sys
from pathlib import Path
SEEN_TO_MARK = {
@@ -32,7 +32,7 @@ SEEN_TO_MARK = {
"pill": "jimeng_pill",
"sparkle": "gemini",
}
# Which marks a crop centred on `key` lets the labeller rule on (same corner = visible
# Which marks a crop centered on `key` lets the labeler rule on (same corner = visible
# in the same crop). Doubao and Jimeng share the bottom-right corner.
_ADJUDICATES = {
"doubao": ("doubao", "jimeng"),
@@ -46,6 +46,7 @@ ROUNDS = [
("textmark", "labels.csv", "manifest.csv"),
("gemini", "gemini_labels.csv", "gemini_manifest.csv"),
]
_HELP_DESCRIPTION = "Consolidate hand-labeled contact-sheet rounds into one ground-truth file."
def metadata_provenance(path: str) -> list[str]:
@@ -77,7 +78,15 @@ def metadata_provenance(path: str) -> list[str]:
def main() -> None:
root = Path(sys.argv[1] if len(sys.argv) > 1 else ".local-eval/textmark-relaxation")
parser = argparse.ArgumentParser(description=_HELP_DESCRIPTION)
parser.add_argument(
"root",
type=Path,
nargs="?",
default=Path(".local-eval/textmark-relaxation"),
help="Directory containing the blinded labeling rounds",
)
root = parser.parse_args().root
out = root / "groundtruth.jsonl"
rows: dict[str, dict] = {}
stats: dict[str, int] = {}
@@ -97,8 +106,8 @@ def main() -> None:
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)
# ADJUDICATION SCOPE -- load-bearing. A crop centered on one mark only lets
# the labeler 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
+17 -9
View File
@@ -1,8 +1,8 @@
"""Build an UNBIASED random sample for measuring visible-mark RECALL.
Every earlier labelling round sampled where detectors FIRED, so images that every
Every earlier labeling 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
samples at random within a provenance class and shows the labeler the corners where
a mark can physically be, so a MISSED mark is visible as such.
Design decisions that matter:
@@ -13,19 +13,19 @@ Design decisions that matter:
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.
the labeler'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.
holds it and must not be opened until labeling ends.
"""
from __future__ import annotations
import argparse
import csv
import json
import random
import sys
from pathlib import Path
from typing import TYPE_CHECKING, Any
@@ -35,6 +35,8 @@ import numpy as np
if TYPE_CHECKING:
from numpy.typing import NDArray
import sys
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
from remove_ai_watermarks.image_io import imread
@@ -63,10 +65,16 @@ def corner_strip(img: NDArray[Any]) -> NDArray[Any] | None:
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
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("scan", type=Path, help="JSONL corpus scan produced by the visible evaluation harness")
parser.add_argument("output", type=Path, help="Directory for contact sheets and the blinded manifest")
parser.add_argument("--tc260", type=int, default=160, help="Number of TC260 carriers to sample")
parser.add_argument("--google", type=int, default=80, help="Number of Google-provenance carriers to sample")
args = parser.parse_args()
scan = args.scan
out = args.output
n_tc260 = args.tc260
n_google = args.google
out.mkdir(parents=True, exist_ok=True)
recs = [json.loads(line) for line in scan.open() if '"marks"' in line]
+11 -6
View File
@@ -1,17 +1,18 @@
"""Build BLIND contact sheets for hand-labelling relaxation additions.
"""Build BLIND contact sheets for hand-labeling 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.
NOT be read until labeling 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
pos - strict-consistent detections (a mark is really there): labeler sensitivity
clean - verified-clean negatives (no mark can be there): labeler specificity
The two control strata are what make a low measured precision trustworthy.
"""
import argparse
import csv
import json
import random
@@ -62,9 +63,13 @@ def crop(path: str, region: tuple[int, int, int, int] | None, pad_factor: float
def main() -> None:
with open(sys.argv[1]) as fh:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("input", type=Path, help="JSON candidate list")
parser.add_argument("output", type=Path, help="Directory for blinded contact sheets")
args = parser.parse_args()
with args.input.open() as fh:
items = json.load(fh) # [{uid,path,key,stratum,conf}]
outdir = Path(sys.argv[2])
outdir = args.output
outdir.mkdir(parents=True, exist_ok=True)
random.Random(1234).shuffle(items) # noqa: S311 -- sheet ordering, not cryptography
+1 -1
View File
@@ -32,7 +32,7 @@ _os.environ.setdefault("TRANSFORMERS_VERBOSITY", "error")
_warnings.filterwarnings("ignore", message=r".*ImageProcessorFast.*")
__version__ = "0.32.1"
__version__ = "0.34.0"
__all__ = [
"BatchSummary",
+2 -2
View File
@@ -624,16 +624,16 @@ def _populate_registry_fields(buffer: bytes, info: dict[str, Any]) -> bool:
if b"c2pa.watermarked" in buffer:
info["watermarked"] = True
soft_bindings = soft_binding_vendors_in(buffer)
synthid = (
[]
if soft_binding_vendors_in(buffer)
if soft_bindings
else synthid_evidence_vendors_in(buffer, has_watermark_action=info.get("watermarked", False))
)
if ai_source and synthid:
info["synthid_vendors"] = synthid
info["synthid_watermark"] = synthid_verdict(", ".join(synthid))
soft_bindings = soft_binding_vendors_in(buffer)
if soft_bindings:
info["soft_binding_vendors"] = soft_bindings
info["soft_binding"] = ", ".join(soft_bindings)
+23 -18
View File
@@ -70,7 +70,7 @@ C2PA_AI_VENDORS: tuple[C2paAiVendor, ...] = (
_vendor(
b"OpenAI",
"OpenAI",
"OpenAI (ChatGPT / gpt-image / DALL-E / Sora)",
"OpenAI (ChatGPT / GPT Image / DALL·E / Sora)",
"OpenAI",
synthid=True,
synthid_requires_watermark_action=True,
@@ -81,29 +81,32 @@ C2PA_AI_VENDORS: tuple[C2paAiVendor, ...] = (
_vendor(
b"volcengine",
"ByteDance (Volcano Engine)",
"ByteDance (Doubao / Jimeng / Dreamina / Volcano Engine)",
"ByteDance",
"ByteDance Volcano Engine",
"Volcano Engine",
),
_vendor(
"北京火山引擎科技有限公司",
"ByteDance (Volcano Engine)",
"ByteDance (Doubao / Jimeng / Dreamina / Volcano Engine)",
"ByteDance",
),
_vendor(
b"Byteplus", "BytePlus (ByteDance)", "ByteDance (Doubao / Jimeng / Dreamina / Volcano Engine)", "ByteDance"
"ByteDance Volcano Engine",
"Volcano Engine",
),
_vendor(b"Byteplus", "BytePlus (ByteDance)", "BytePlus (ByteDance)", "BytePlus"),
_vendor(
b"Dreamina",
"ByteDance (Dreamina)",
"ByteDance (Doubao / Jimeng / Dreamina / Volcano Engine)",
"ByteDance",
"ByteDance Dreamina",
"Dreamina",
asserts_ai=True,
),
_vendor(b"Canva", "Canva", "Canva (Magic Media)", "Canva"),
_vendor(b"Eleven Labs", "ElevenLabs", "ElevenLabs", "ElevenLabs"),
_vendor(b"fal-ai", "fal.ai", "fal.ai", "fal.ai", asserts_ai=True),
_vendor(b"Bria", "Bria Artificial Intelligence", "Bria AI", "Bria", asserts_ai=True),
# Ideogram signs its downloads' Content Credentials with "Ideogram, Inc"; the
# issuer token is the org prefix (same substring-match class as "Bria" in
# "Bria Artificial Intelligence"). Found as an unmapped signer on 4 corpus
# uploads 2026-08-08 that identify reported as unknown-signer C2PA.
_vendor(b"Ideogram", "Ideogram", "Ideogram", "Ideogram", asserts_ai=True),
_vendor(b"Truepic", "Truepic", None, None),
)
@@ -116,7 +119,7 @@ C2PA_IDENTITY_AI_ORGS = frozenset(vendor.org for vendor in C2PA_AI_VENDORS if ve
C2PA_CLAIM_GENERATOR_PLATFORMS: tuple[tuple[str, str], ...] = (
("adobe_firefly", "Adobe Firefly"),
("firefly", "Adobe Firefly"),
("dreamina", "ByteDance (Doubao / Jimeng / Dreamina / Volcano Engine)"),
("dreamina", "ByteDance Dreamina"),
("higgsfield ai", "Higgsfield AI"),
("topaz labs image api", "Topaz Labs"),
("tiktok ad creative toolbox", "TikTok Ad Creative Toolbox"),
@@ -128,8 +131,8 @@ C2PA_AI_TOOLS = {
("GPT-4o", "GPT-4o"),
("ChatGPT", "ChatGPT"),
("Sora", "Sora"),
("DALL-E", "DALL-E"),
("DALL", "DALL-E"),
("DALL-E", "DALL·E"),
("DALL", "DALL·E"),
("Imagen", "Imagen"),
("Firefly", "Firefly"),
("Dreamina", "Dreamina"),
@@ -138,16 +141,18 @@ C2PA_AI_TOOLS = {
C2PA_SOFT_BINDINGS = {
b"com.adobe.trustmark": "Adobe TrustMark",
b"com.adobe.icn": "Adobe (content fingerprint)",
b"com.digimarc": "Digimarc",
b"com.adobe.icn": "Adobe Image Comparator Network",
b"com.digimarc": "Digimarc Validate",
b"com.imatag.lamark": "Imatag (Lamark)",
b"ai.steg": "Steg.AI",
b"com.microsoft.invismark": "Microsoft InvisMark",
b"com.microsoft.wavmark": "Microsoft WavMark",
b"com.verimatrix": "Verimatrix",
b"com.nagra.nexguard": "NAGRA NexGuard",
b"com.aiwatermark": "AIWatermark (Meta PixelSeal)",
b"ai.trufo": "Trufo",
b"com.aiwatermark.pixelseal": "AIWatermark PixelSeal",
b"com.aiwatermark.videoseal": "AIWatermark VideoSeal",
b"com.aiwatermark.audioseal": "AIWatermark AudioSeal",
b"ai.trufo": "Trufo PawPrint",
b"app.overlai": "Overlai",
b"com.markany": "MarkAny",
b"com.mentaport": "Mentaport",
@@ -199,7 +204,7 @@ C2PA_ACTIONS = {f"c2pa.{action}".encode(): action for action in _C2PA_ACTION_NAM
# what stops a newly registered TC260 vendor from silently falling back to ByteDance.
#
# What a TC260 label confirms when its producer is absent or unmapped. Historical
# behaviour, kept as the fallback so an unrecognized producer never regresses to no
# behavior, kept as the fallback so an unrecognized producer never regresses to no
# relaxation at all: ByteDance's two products are the ones the relaxed band was
# calibrated on (see _text_mark_engine._DEFAULT_PROVENANCE_NCC_FACTOR).
TC260_FALLBACK_VENDORS: frozenset[str] = frozenset({"doubao", "jimeng"})
@@ -1074,29 +1074,14 @@ class QwenZImagePipeline:
fidelity_anchor: bool = False,
) -> Image.Image:
"""Execute global regeneration and masked face repair."""
if text_manifest is not None and tile:
raise ValueError("Verified text restoration is not calibrated with tiled diffusion")
self._require_cuda()
seed = resolve_seed(seed)
donor = None
if text_manifest is not None:
self._progress("Reconstructing the verified text donor with the Qwen VAE...")
if tile and max(image.size) > tile_size:
from remove_ai_watermarks._internal.tiling import run_tiled
donor = run_tiled(
self._qwen_vae_roundtrip,
image,
tile_size,
tile_overlap,
lambda message: self._progress(
message.replace(
"Tiled diffusion",
"Reconstructing the verified text donor",
1,
)
),
)
else:
donor = self._qwen_vae_roundtrip(image)
donor = self._qwen_vae_roundtrip(image)
global_strength = (
resolution_adaptive_denoise(image.width, image.height) if strength is None else float(strength)
)
+22 -13
View File
@@ -52,8 +52,8 @@ _MIN_DETECT_SHORT_SIDE = 200
# 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 a labelled TC260 evaluation set,
# two-sided control (labeller sensitivity 100%/96%, specificity 100%/100%):
# (accepted with provenance, rejected without) over a labeled TC260 evaluation set,
# two-sided control (labeler sensitivity 100%/96%, specificity 100%/100%):
#
# mark band precision 95% CI n
# doubao whole arm 76% 61-87% 42
@@ -89,8 +89,8 @@ 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", "tl", "bc"
] # bottom-right (Doubao/Jimeng), bottom-left (Samsung), top-left (RunningHub), bottom-center (LibLibAI)
"br", "bl", "tl", "tr", "bc"
] # br (Doubao/Jimeng), bl (Samsung), tl (RunningHub), tr (Microsoft), bc (LiblibAI)
margin_floor: int # min margin in px for locate (4 for br marks, 2 for Samsung)
# locate geometry (fraction of scale_base -- see scale_base())
width_frac: float
@@ -131,7 +131,7 @@ class TextMarkConfig:
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_basis: Literal["short", "width", "long"] = "width"
# Scale rungs ``_ladder_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
@@ -309,7 +309,7 @@ class TextMarkEngine:
provenance relaxation it stopped trying because many Jimeng false additions
were actually Doubao marks.
Measured separability on hand-labelled examples, scoring BOTH templates
Measured separability on hand-labeled examples, scoring BOTH templates
against the same glyph blob:
feature separability (0.5 = useless, 1.0 = perfect)
@@ -480,10 +480,19 @@ class TextMarkEngine:
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
prior -- but Jimeng's measured behavior overrides the prior, and measurement
wins over the standard's wording.
"long" (max of the two sides) is the Microsoft badge's measured basis: the
pill tracks the RENDER dimension, so on a 1024x1536 portrait it scales with
the 1536 (a width basis undersized the template by the aspect ratio and the
portrait carriers fell to 0.15-0.32 NCC; measured 2026-08-27).
"""
return min(image.shape[:2]) if self.config.scale_basis == "short" else image.shape[1]
if self.config.scale_basis == "short":
return min(image.shape[:2])
if self.config.scale_basis == "long":
return max(image.shape[:2])
return image.shape[1]
def locate(self, image: NDArray[Any]) -> TextMarkLocation:
"""Anchor the watermark box in the configured corner, scaled by ``scale_basis``.
@@ -499,14 +508,14 @@ class TextMarkEngine:
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":
if c.corner == "br" or c.corner == "tr":
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)
# "tl"/"tr" anchor at the top instead: margin_bottom_frac is then the TOP margin.
y = min(margin_b, max(0, h - wm_h)) if c.corner in ("tl", "tr") 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)
@@ -695,7 +704,7 @@ class TextMarkEngine:
OVERRIDABLE, and the override contract is specifically the DETECTOR'S MATCH BOX:
a mark whose removable footprint reaches beyond what the NCC localizes -- Baidu's
flat white tag right of the text run, LibLibAI's triangle logo left of the
flat white tag right of the text run, LiblibAI's triangle logo left of the
wordmark -- supplies its own extension here and inherits the rest of the
footprint path. The blob-bbox branch never routes through an override.
"""
@@ -771,7 +780,7 @@ class TextMarkEngine:
"""Footprint policy for a mark whose fill must be bounded by the DETECTOR's match
box and never by the binary glyph blob.
Baidu's white tag has a flat interior a top-hat cannot answer, and LibLibAI's
Baidu's white tag has a flat interior a top-hat cannot answer, and LiblibAI's
blob bleeds up into background structure; in both cases the blob bbox is
measurably wrong and the NCC match box is right. ``force`` takes priority here,
unlike the default policy: a ``--no-detect`` caller named the mark, so the whole
+6 -5
View File
@@ -73,7 +73,7 @@ def _tc260_vendors(path: Path) -> frozenset[str]:
An absent, unreadable or unmapped producer falls back to the historical pair rather
than to nothing: the caller has already established that the AIGC signal fired, so
the image IS China-AIGC labelled, and dropping to no relaxation would lose the
the image IS China-AIGC labeled, and dropping to no relaxation would lose the
detections the fallback recovers today. The re-read is deliberately isolated -- a
failure here must narrow the answer, never discard the rest of the provenance.
"""
@@ -156,9 +156,10 @@ def remove_visible(
) -> tuple[NDArray[Any], list[str]]:
"""Remove every detected known visible AI mark through localize then fill.
The registry currently covers the Gemini sparkle; Doubao, Jimeng, Qwen, Kling,
Yuanbao, Samsung, RunningHub, Baidu, and LibLibAI text marks; and the Jimeng
pill. Returns ``(result_bgr, [labels removed])``.
The registry currently covers the Gemini visible watermark; Doubao, Jimeng,
Qwen, Kling AI, Yuanbao, Samsung, RunningHub, Baidu, and LiblibAI text marks;
one Microsoft top-right AI-badge variant; and the Jimeng pill. Returns
``(result_bgr, [labels removed])``.
``source`` is a file path OR a BGR ndarray. For a PATH, metadata provenance is read
automatically (so ``sensitivity="auto"`` recovers a moved/faint mark whenever the
@@ -184,7 +185,7 @@ def remove_visible(
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.
# at runtime, so a 0.15 caller would otherwise get `auto` behavior in silence.
watermark_registry.validate_sensitivity(sensitivity)
loaded = _load_visible_input(source)
result, removed = watermark_registry.remove_auto_marks(
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

+5 -5
View File
@@ -307,7 +307,7 @@ _seed_option = click.option(
help="Random seed for reproducibility. Default 0: both profiles are certified "
"at a fixed seed, because SynthID removal near the strength floor is seed-dependent.",
)
_hf_token_option = click.option("--hf-token", type=str, default=None, help="HuggingFace API token.")
_hf_token_option = click.option("--hf-token", type=str, default=None, help="Hugging Face API token.")
_humanize_option = click.option(
"--humanize", type=float, default=0.0, help="Analog Humanizer film grain intensity (0 = off, typical: 2.0-6.0)."
)
@@ -541,7 +541,7 @@ def _should_skip_invisible_scrub(force: bool, image_path: Path) -> bool:
@click.option("-v", "--verbose", is_flag=True, help="Enable verbose logging.")
@click.pass_context
def main(ctx: click.Context, verbose: bool) -> None:
"""Remove visible and invisible AI watermarks from images, plus provenance metadata from video."""
"""Remove visible and invisible AI watermarks, plus metadata provenance marks, from images and video."""
from dotenv import load_dotenv
load_dotenv() # Load .env (e.g. HF_TOKEN)
@@ -859,7 +859,7 @@ def cmd_invisible(
text_manifest: Path | None,
fidelity_anchor: bool,
) -> None:
"""Remove invisible AI watermarks (SynthID, StableSignature, TreeRing).
"""Attempt to disrupt invisible AI watermarks through pixel regeneration.
Regenerates the pixels with the two-stage diffusion profile. CUDA-only:
pip install 'remove-ai-watermarks[qwen-zimage]'
@@ -1001,8 +1001,8 @@ def cmd_metadata(
Strips EXIF AI tags, PNG text chunks, C2PA provenance manifests, and the
China TC260 AIGC label. Beyond images (PNG/JPEG/WebP/AVIF/HEIF/JXL) it also
strips provenance metadata from MP4/MOV/M4V/M4A containers and, via ffmpeg,
from WebM/MKV/AVI/FLV/MP3/WAV/FLAC/OGG. The coded image, audio, and video
data are left untouched.
from WebM/MKV/MKA/AVI/FLV/MP3/WAV/FLAC/OGG/OGA/Opus/AAC. The coded image,
audio, and video data are left untouched.
"""
from remove_ai_watermarks.metadata import get_ai_metadata, has_ai_metadata, strip_and_verify
+1 -1
View File
@@ -97,7 +97,7 @@ class _DecodeMaxDct:
return decoded
def _plane_bits(self, trimmed: NDArray[Any], channel: int, scale: int) -> NDArray[Any]:
"""Block bits for one colour plane, a strip of block-rows at a time.
"""Block bits for one color plane, a strip of block-rows at a time.
``dwt2`` is ``dwtn``: it transforms along axis 0, then along axis 1 over
both halves, and three of the four bands it returns are discarded here.
+36 -16
View File
@@ -145,7 +145,7 @@ _INVISIBLE_WM_CAVEAT = (
"or resizing, so it confirms origin only on a pristine (un-re-encoded) file."
)
_HF_JOB_CAVEAT = (
"The hf-job-id tag marks a HuggingFace-hosted job (commonly diffusion "
"The hf-job-id tag marks a Hugging Face-hosted job (commonly diffusion "
"generation) but names neither the model nor the content type, so it is a "
"medium-confidence signal, not proof the pixels are AI-generated."
)
@@ -445,7 +445,7 @@ def evidence_from_metadata_record(
if iptc_system:
ai_metadata.setdefault("ai_system", f"IPTC 2025.1 AI disclosure ({iptc_system})")
if hf_job:
ai_metadata.setdefault("huggingface_job", f"HuggingFace-hosted job ({hf_job})")
ai_metadata.setdefault("huggingface_job", f"Hugging Face-hosted job ({hf_job})")
if samsung is not None:
ai_metadata.setdefault("samsung_genai", f"Samsung Galaxy AI editing marker (genAIType={samsung})")
@@ -953,7 +953,7 @@ def _visible_sparkle(image_path: Path, *, image: NDArray[Any] | None = None) ->
# metadata label); the per-engine detection thresholds live in the registry.
# Text mark -> the platform sentence this report prints when that mark is the strongest
# evidence, DERIVED from the registry rows so registering a mark is one edit. It was a
# hand-maintained copy, and that class of copy is how LibLibAI ended up registered but
# hand-maintained copy, and that class of copy is how LiblibAI ended up registered but
# missing from the pill veto. Insertion order is the registry's, which is what fixes the
# scan order below. The Gemini sparkle and the capture-less pill carry no platform of
# their own (`KnownMark.platform is None`) and are excluded here: the sparkle has its
@@ -1105,7 +1105,7 @@ def _collect_visible_signals(
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})")
watermarks.append(f"Google Gemini visible watermark (sparkle; confidence {sparkle_conf:.2f})")
if platform is None:
platform = "Google Gemini family (visible sparkle detected)"
@@ -1278,12 +1278,12 @@ def _identify_from_evidence(
# vendor-token inference must not add a second, differently-attributed
# invisible watermark (Microsoft Designer: "Azure OpenAI ImageGen" agent +
# the InvisMark watermarked action read as "SynthID per OpenAI").
soft_binding_vendors = soft_binding_vendors_in(region)
if (
not synthid
and trained_source
and c2pa_marker_in(head)
and not soft_binding_vendors_in(region)
and not soft_binding_vendors
and (vendors := synthid_evidence_vendors_in(region))
):
synthid = synthid_verdict(", ".join(vendors))
@@ -1300,7 +1300,7 @@ def _identify_from_evidence(
# ── C2PA soft-binding: a named forensic/third-party watermark vendor ─
# (Adobe TrustMark, Digimarc, Imatag, ...). Present in the manifest even when
# the watermark itself can't be decoded; names whose watermark stamped the pixels.
soft_binding = meta.get("soft_binding") or (", ".join(v) if (v := soft_binding_vendors_in(region)) else None)
soft_binding = meta.get("soft_binding") or (", ".join(soft_binding_vendors) if soft_binding_vendors else None)
if soft_binding:
soft_binding_algorithm = meta.get("soft_binding_algorithm") or info.get("soft_binding_algorithm")
soft_binding_value = meta.get("soft_binding_value") or info.get("soft_binding_value")
@@ -1334,6 +1334,21 @@ def _identify_from_evidence(
if standalone_iptc:
signals.append(Signal("iptc", "digitalSourceType (Made with AI)", "high"))
watermarks.append("IPTC digitalSourceType (Made with AI)")
# Muse Image stamps every output with the invisible Content Seal, and this
# tag is the only provenance such a file carries - the same measured bet
# the strength router makes (vendor_for_strength -> "meta"). Emit the seal
# as its own stable signal, the way InvisMark is additive over
# soft_binding, so clients select pixel removal from the signal list
# instead of parsing caveats. It is an attribution, not a decode: no
# public Content Seal decoder exists, hence "medium".
signals.append(
Signal(
"content_seal",
"Meta Muse Content Seal pixel watermark (attributed by the standalone AI digital-source tag)",
"medium",
)
)
watermarks.append("Invisible Content Seal watermark (Meta Muse attribution)")
caveats.append(_IPTC_ONLY_CAVEAT)
caveats.append(_CONTENT_SEAL_CAVEAT)
if platform is None:
@@ -1341,11 +1356,16 @@ def _identify_from_evidence(
# the edit with photoshop:Credit / IPTC "Apple Photos Clean Up"
# next to compositeWithTrainedAlgorithmicMedia. It was detected but
# previously 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"
)
if b"Apple Photos Clean Up" in head:
platform = "Apple Photos (Clean Up AI edit)"
else:
# The platform line follows the same measured bet the seal signal
# and the strength router make: Muse Image is the tag writer whose
# outputs this profile targets, so a hedged Muse attribution is
# more useful than "platform not specified" while the panel below
# already prices the Content Seal removal. The hedge stays in the
# wording - it names the attribution basis, not a detection.
platform = "Meta Muse Image (attributed by the standalone AI digital-source tag)"
# ── IPTC 2025.1 AI-disclosure fields (Iptc4xmpExt:AISystemUsed etc.) ─
iptc_ai = any(m in head for m in IPTC_AI_FIELD_MARKERS)
@@ -1406,17 +1426,17 @@ def _identify_from_evidence(
platform = "xAI (Grok / Aurora)"
ai_vendor_claims["xai"] = "xAI"
# ── HuggingFace-hosted job marker (hf-job-id PNG text chunk) ─────
# ── Hugging Face-hosted job marker (hf-job-id PNG text chunk) ─────
# Marks the hosting job, not a model -- medium confidence (commonly diffusion
# output). Like the visible sparkle, it lifts an otherwise-Unknown verdict to
# a tentative AI, but never overrides a high-confidence metadata signal.
hf_job = evidence.huggingface_job
if hf_job:
signals.append(Signal("hf_job", f"HuggingFace job {hf_job}", "medium"))
watermarks.append("HuggingFace-hosted job (hf-job-id)")
signals.append(Signal("hf_job", f"Hugging Face job {hf_job}", "medium"))
watermarks.append("Hugging Face-hosted job (hf-job-id)")
caveats.append(_HF_JOB_CAVEAT)
if platform is None:
platform = "HuggingFace-hosted job (model not identified)"
platform = "Hugging Face-hosted job (model not identified)"
# ── Samsung Galaxy AI editing marker (genAIType) ─────────────────
# Galaxy AI tools stamp a proprietary genAIType in PhotoEditor_Re_Edit_Data.
+6 -5
View File
@@ -33,7 +33,7 @@ warnings.filterwarnings("ignore", category=UserWarning, module="huggingface_hub"
warnings.filterwarnings("ignore", category=UserWarning, module="diffusers")
warnings.filterwarnings("ignore", module="transformers")
# Suppress HuggingFace internal logging
# Suppress Hugging Face internal logging
os.environ["TRANSFORMERS_VERBOSITY"] = "error"
os.environ["DIFFUSERS_VERBOSITY"] = "error"
@@ -104,7 +104,7 @@ class InvisibleEngine:
global pass, vendor-adaptive strength because an SDXL global stage
needs more of it). BOTH ARE CUDA-ONLY -- there is no CPU or MPS path
for invisible-watermark removal.
hf_token: HuggingFace API token.
hf_token: Hugging Face API token.
progress_callback: Optional callback for progress messages.
controlnet_conditioning_scale: Canny ControlNet structure-preservation
strength on the global stage of both profiles.
@@ -187,9 +187,8 @@ class InvisibleEngine:
pixels. Enables the experimental Qwen-VAE ``vae-glyphs`` post-pass.
Requires the ``text-restoration`` extra and the ``qwen-zimage``
profile. Incompatible with downscaling, humanize, unsharp, and
adaptive polish. Tiling is supported: the VAE donor uses the same
overlapping tiles as the global pass, then glyph restore runs on
the blended full frame.
adaptive polish. Tiling is rejected because that combination has
no provider-oracle calibration.
fidelity_anchor: Blend 15% of the Qwen-VAE donor across the whole frame
before glyph restoration. OFF by default since 0.27.1: that global
blend was measured to return detector-visible OpenAI SynthID on
@@ -211,6 +210,8 @@ class InvisibleEngine:
if text_manifest is not None:
if self._remover.model_profile != QWEN_ZIMAGE_PROFILE:
raise ValueError("--text-manifest is supported only by the qwen-zimage profile")
if tile:
raise ValueError("--text-manifest is not calibrated with --tile")
if max_resolution != 0:
raise ValueError("--text-manifest requires --max-resolution 0")
if humanize > 0.0 or unsharp > 0.0 or adaptive_polish:
@@ -99,7 +99,7 @@ def detect_invisible_watermark(image_path: Path, *, image: NDArray[Any] | None =
# ``image`` lets a caller that has already decoded these pixels hand them in
# (mirrors gemini_engine.detect_sparkle_confidence). The decoder only reads the
# array -- it converts colour spaces into fresh buffers -- so no copy is needed.
# array -- it converts color spaces into fresh buffers -- so no copy is needed.
img = image if image is not None else image_io.imread(image_path)
if img is None:
return None
+9 -9
View File
@@ -1,6 +1,6 @@
"""Kling (可灵, Kuaishou) visible watermark detector/localizer.
"""Kling AI (可灵AI, Kuaishou) visible watermark detector/localizer.
Kling stamps its generations with a thin, light-gray "可灵AI 3.0" text strip in the
Kling AI 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
@@ -9,7 +9,7 @@ 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
``region_eraser``), NOT reverse-alpha. This module supplies only Kling AI'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``
@@ -26,7 +26,7 @@ producer USCC 91110108335469089C names the entity, 2026-07-21; harness
* ``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
(cohort-contamination-guarded, 286 hand-labeled 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"
@@ -38,7 +38,7 @@ producer USCC 91110108335469089C names the entity, 2026-07-21; harness
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
below the gate), 0 of 298 Jimeng-marked frames and 0 of 286 hand-labeled clean
frames, and a 0.10 rival margin costs zero genuine Kling detections -- so it is
simply unnecessary (same conclusion shape as Qwen).
"""
@@ -74,7 +74,7 @@ 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
# Calibrated 2026-07-21 on the vendor cohort vs 286 hand-labeled 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
@@ -87,7 +87,7 @@ _ALPHA_WIDTH_FRAC = 0.12
_ALPHA_HEIGHT_FRAC = 0.0287
_CONFIG = TextMarkConfig(
name="Kling",
name="Kling AI",
asset_name="kling_alpha.png",
corner="br",
margin_floor=4,
@@ -114,7 +114,7 @@ _CONFIG = TextMarkConfig(
def _alpha_template() -> NDArray[Any] | None:
"""The bundled Kling alpha template (float [0,1]), or None."""
"""The bundled Kling AI alpha template (float [0,1]), or None."""
return _text_mark_engine.load_alpha_template(_CONFIG.asset_name)
@@ -124,7 +124,7 @@ def _glyph_silhouette() -> NDArray[Any] | None:
class KlingEngine(TextMarkEngine):
"""Detect/localize the visible Kling "可灵AI 3.0" watermark (locate -> mask; mask feeds the fill)."""
"""Detect/localize the visible Kling AI "可灵AI 3.0" watermark (locate -> mask; mask feeds the fill)."""
def __init__(self) -> None:
super().__init__(_CONFIG)
+8 -8
View File
@@ -1,13 +1,13 @@
"""LibLibAI visible watermark detector/localizer.
"""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
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
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`
This module supplies only LiblibAI's tuned :class:`TextMarkConfig`
(``assets/liblib_alpha.png`` from ``scripts/render_vendor_silhouettes.py``,
never cut from an upload).
@@ -64,7 +64,7 @@ _ALPHA_HEIGHT_FRAC = 0.026
_LADDER = (0.9, 1.0, 1.1)
_CONFIG = TextMarkConfig(
name="LibLibAI",
name="LiblibAI",
asset_name="liblib_alpha.png",
corner="bc",
margin_floor=4,
@@ -90,12 +90,12 @@ _CONFIG = TextMarkConfig(
def _alpha_template() -> NDArray[Any] | None:
"""The bundled LibLibAI alpha template (float [0,1]), or None."""
"""The bundled LiblibAI alpha template (float [0,1]), or None."""
return _text_mark_engine.load_alpha_template(_CONFIG.asset_name)
class LibLibEngine(TextMarkEngine):
"""Detect/localize the visible LibLibAI wordmark (bottom-center; localize -> fill)."""
"""Detect/localize the visible LiblibAI wordmark (bottom-center; localize -> fill)."""
# Per-mark size floor prevents small generic icons from matching the wordmark.
_MIN_SHORT_SIDE = 480
+7 -7
View File
@@ -199,7 +199,7 @@ def parse_tc260_aigc_json(value: bytes) -> dict[str, str] | None:
return fields if TC260_AIGC_FIELDS & fields.keys() else None
# HuggingFace-hosted GPU jobs (Jobs / Spaces) stamp generated PNGs with this
# Hugging Face-hosted GPU jobs (Jobs / Spaces) stamp generated PNGs with this
# ``tEXt`` chunk key holding the job UUID. It marks the hosting job, not a
# specific model -- a medium-confidence AI signal (commonly diffusion output).
_HF_JOB_KEY: str = "hf-job-id"
@@ -413,7 +413,7 @@ def _scan_head_impl(image_path: Path, size: int) -> bytes:
# packet larger than this is not a provenance label.
_DECODED_TEXT_LIMIT = 512 * 1024
# Decoder values that are binary payloads with their own readers, not metadata text.
# An ICC profile is colour data and can run to hundreds of kilobytes; appending it
# An ICC profile is color data and can run to hundreds of kilobytes; appending it
# would bloat the buffer every later detector re-scans, for no signal.
_DECODER_BINARY_KEYS = frozenset({"icc_profile"})
@@ -510,7 +510,7 @@ def has_ai_metadata(image_path: Path) -> bool:
# only the XMP form; the raw-JSON tEXt chunk needs the PIL-based parse).
if aigc_label(image_path) is not None:
return True
# HuggingFace-hosted job marker (hf-job-id PNG text chunk).
# Hugging Face-hosted job marker (hf-job-id PNG text chunk).
if huggingface_job(image_path):
return True
# xAI / Grok: no C2PA/IPTC/XMP -- only the EXIF Signature + UUID-Artist pair.
@@ -682,10 +682,10 @@ def c2pa_cloud_manifest(image_path: Path) -> str | None:
def _huggingface_job_impl(image_path: Path) -> str | None:
"""Return the HuggingFace job id if the image carries an ``hf-job-id`` PNG
"""Return the Hugging Face job id if the image carries an ``hf-job-id`` PNG
text chunk, else None.
HuggingFace-hosted GPU jobs (Jobs / Spaces) stamp generated PNGs with an
Hugging Face-hosted GPU jobs (Jobs / Spaces) stamp generated PNGs with an
``hf-job-id`` ``tEXt`` chunk holding the job's UUID. It identifies the
*hosting job*, not a specific model, and is most commonly seen on diffusion-
generation output -- a medium-confidence AI signal, not proof of AI pixels
@@ -1216,9 +1216,9 @@ def get_ai_metadata(image_path: Path) -> dict[str, str]:
if system := iptc_ai_system(image_path):
result.setdefault("ai_system", f"IPTC 2025.1 AI disclosure ({system})")
# HuggingFace-hosted job marker (hf-job-id PNG text chunk).
# Hugging Face-hosted job marker (hf-job-id PNG text chunk).
if job := huggingface_job(image_path):
result.setdefault("huggingface_job", f"HuggingFace-hosted job ({job})")
result.setdefault("huggingface_job", f"Hugging Face-hosted job ({job})")
# Samsung Galaxy AI editing marker (genAIType in PhotoEditor_Re_Edit_Data).
if (genai := samsung_genai(image_path)) is not None:
result.setdefault("samsung_genai", f"Samsung Galaxy AI editing marker (genAIType={genai})")
@@ -0,0 +1,104 @@
"""Microsoft top-right AI-badge detector/localizer.
This engine covers one measured Microsoft output variant: a white pill with dark
internal shapes in the top-right corner. The evaluated files used both "Made with
AI" and "AI-Generated" wording. This is narrower than Microsoft's documented
watermark feature, which can use a Copilot icon or text and can place the mark in
other positions. A Microsoft provenance signal therefore does not establish that
this exact visible variant is present.
Detection matches a synthetic pill silhouette (white pill with the sparkle and
text KNOCKED OUT) against the top-hat blob of the located box: the holes are what
discriminate this pill from any other bright rounded element in the corner.
Removal is the shared **localize -> fill**; the glyph-bbox :meth:`footprint_mask`
covers the whole pill including its text.
The tuned numbers below were remeasured on 2026-08-27 with the registered engine
and ``scripts/registered_mark_calibrate.py``. The arms were kept distinct: 17
visually confirmed carriers, 343 Microsoft-provenance files whose visible-mark
status was not adjudicated, and 1200 non-overlapping no-signal controls:
* Geometry is single-mode and tight: pill 0.152 x 0.040 of the LONG side
(aspect 3.73-3.89 over 720..1536 px), margins ~0.010/0.007 of the same basis. One size
mode, so the shared 3-rung ladder is untouched and the locate box simply
wraps the pill with NCC slack.
* STRICT ONLY (``provenance_ncc_factor`` 1.0): controls max 0.293 / p99
0.200; confirmed carriers p50 0.519 / p90 0.578 / max 0.579, with 15/17
above the 0.38 gate. Provenance alone does not relax the gate: only 78/343
files in that cohort crossed it, and the rest were not visually labeled.
* Front-end "binary": the pill is a bold opaque overlay; the tophat blob is
solid with dark-text holes, exactly the template's shape.
"""
# 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, TextMarkEngine
if TYPE_CHECKING:
from numpy.typing import NDArray
# Locate geometry as a fraction of the image LONG side (measured; scale_basis="long":
# on 1024x1536 portraits the pill tracks the 1536, and a width basis undersized
# the template until the portrait carriers fell to 0.15-0.32 NCC).
# The box wraps the measured pill rect (0.152W x 0.040W) with NCC slack; margins
# sit inside the pill's own ~0.010W-right / ~0.007W-top insets.
WM_WIDTH_FRAC = 0.170
WM_HEIGHT_FRAC = 0.055
MARGIN_RIGHT_FRAC = 0.004
MARGIN_TOP_FRAC = 0.003
# Glyph appearance: a bright near-white pill (luma ~245), gray-scale (sat < 60).
MAX_SATURATION = 60
LOGO_MIN_LUMA = 170
TOPHAT_DELTA = 10
# Calibrated 2026-08-27: non-overlapping no-signal controls (n=1200) max 0.293 /
# p99 0.200; visually confirmed carriers (n=17) p50 0.519 / p90 0.578 / max
# 0.579, with 15/17 above the 0.38 gate. The two misses score 0.249 and 0.315.
DETECT_MIN_COVERAGE = 0.30 # the pill fills most of its box; content corners do not
DETECT_NCC_THRESHOLD = 0.38
# Pill silhouette geometry (fraction of width): 0.152W x 0.040W, aspect ~3.78.
_ALPHA_NATIVE_WIDTH = 335
_ALPHA_WIDTH_FRAC = 0.152
_ALPHA_HEIGHT_FRAC = 0.040
_CONFIG = TextMarkConfig(
name="Microsoft top-right AI badge",
asset_name="microsoft_alpha.png",
corner="tr",
margin_floor=2,
width_frac=WM_WIDTH_FRAC,
height_frac=WM_HEIGHT_FRAC,
margin_x_frac=MARGIN_RIGHT_FRAC,
margin_bottom_frac=MARGIN_TOP_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,
alpha_width_frac=_ALPHA_WIDTH_FRAC,
alpha_height_frac=_ALPHA_HEIGHT_FRAC,
min_gw=24,
detect_frontend="binary",
scale_basis="long",
provenance_ncc_factor=1.0,
)
def _alpha_template() -> NDArray[Any] | None:
"""The bundled Microsoft pill template (float [0,1]), or None."""
return _text_mark_engine.load_alpha_template(_CONFIG.asset_name)
class MicrosoftEngine(TextMarkEngine):
"""Detect/localize the measured Microsoft top-right AI badge."""
def __init__(self) -> None:
super().__init__(_CONFIG)
+1 -1
View File
@@ -64,7 +64,7 @@ _MASK_W, _MASK_H = 0.205, 0.115 # width of W, height of W
#
# Measured through the PRODUCT path (the `_keep_pill` gate), not the raw detector, by
# ``scripts/pill_gate_audit.py`` -- the raw path bypasses the gate and reads as a
# disaster that the shipped behaviour does not have. Re-run it when the gate changes.
# disaster that the shipped behavior does not have. Re-run it when the gate changes.
_FLAT_TEXTURE_MAX = 6.0
_silhouette: NDArray[Any] | None = None
+3 -3
View File
@@ -23,7 +23,7 @@ whose producer USCC 91440101MA9Y9T4H7A names the entity, 2026-07-21; harness
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
(``TextMarkConfig.ladder``), one rung centered 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
@@ -38,7 +38,7 @@ whose producer USCC 91440101MA9Y9T4H7A names the entity, 2026-07-21; harness
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
Doubao-marked frames, 0 of 298 Jimeng-marked frames and 0 of 286 hand-labeled
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.
"""
@@ -74,7 +74,7 @@ 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
# Calibrated 2026-07-21 on the vendor cohort vs 286 hand-labeled 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).
@@ -32,7 +32,7 @@ whose producer USCC names the entity, harvested 2026-07-22 by
* 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)
* Gate 0.34: on 283 hand-labeled 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.
@@ -75,14 +75,14 @@ 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:
# Calibrated 2026-07-22 on the vendor cohort vs 283 hand-labeled 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
# 0.223 at +5.6% -- the same comb behavior 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
+4 -4
View File
@@ -1,8 +1,8 @@
"""High-level video processing API.
The product path covers provenance identification, container-level AI metadata
removal, temporally stabilized visible Sora, Veo, Seedance, Dola, Hailuo, and
Kling removal, and an oracle-certified opt-in VAE profile for video SynthID.
removal, temporally stabilized visible Sora, Veo, Seedance, Dola, Hailuo AI, and
Kling AI removal, and an oracle-certified opt-in VAE profile for video SynthID.
The visible pixel path reuses the image package's shared fill backends.
"""
@@ -179,8 +179,8 @@ _VISIBLE_PLATFORM = {
"veo": "Google Veo",
"seedance": "ByteDance Seedance",
"dola": "ByteDance Dola",
"hailuo": "MiniMax Hailuo",
"kling": "Kuaishou Kling",
"hailuo": "MiniMax Hailuo AI",
"kling": "Kuaishou Kling AI",
}
+2 -2
View File
@@ -4,8 +4,8 @@ Supported marks use fully synthetic silhouettes made from geometric primitives,
OpenCV's built-in font, and Pillow's bundled font. Sora detection searches the
full frame because the wordmark moves. Veo detection covers both the current
four-point diamond and legacy ``Veo`` text. Seedance detects the boxed ``AI``
label, Dola detects its compact text label, Hailuo detects the composite
MINIMAX/Hailuo label, and Kling detects its version-independent wordmark core.
label, Dola detects its compact text label, Hailuo AI detects the composite
MINIMAX/Hailuo AI label, and Kling AI detects its version-independent wordmark core.
A single frame is never enough to authorize removal: the temporal arbiter
requires the candidate to recur at the same location across adjacent frames.
This keeps isolated lookalikes in clean videos from becoming removal masks.
+43 -19
View File
@@ -17,17 +17,18 @@ localizer stays cheap (cv2/numpy, CPU) so a memory-tight caller can run it on a
small worker; the heavy fill (MI-GAN / LaMa) is opt-in and chosen by the caller.
Entries:
- ``gemini`` -- Google Gemini / Nano Banana sparkle, bottom-right.
- ``gemini`` -- Google Gemini / Nano Banana visible watermark (sparkle), bottom-right.
- ``doubao`` -- ByteDance Doubao "豆包AI生成" text strip, bottom-right.
- ``jimeng`` -- ByteDance Jimeng / Dreamina "★ 即梦AI" wordmark, bottom-right.
- ``qwen`` -- Alibaba Qwen "千问AI生成" text strip, bottom-right.
- ``kling`` -- Kuaishou Kling "可灵AI 3.0" text strip, bottom-right.
- ``qwen`` -- Alibaba Cloud Qwen "千问AI生成" text strip, bottom-right.
- ``kling`` -- Kuaishou Kling AI "可灵AI 3.0" text strip, bottom-right.
- ``yuanbao`` -- Tencent Yuanbao "元宝 / AI生成" two-line mark, 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.
- ``liblib`` -- LiblibAI "LiblibAI" wordmark, bottom-center.
- ``microsoft`` -- one measured Microsoft white AI-badge variant, top-right.
"""
from __future__ import annotations
@@ -147,7 +148,7 @@ _REMOVED_SENSITIVITIES = {
"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."
"the default evidence-driven behavior."
)
}
@@ -156,7 +157,7 @@ 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 --
upgrading from 0.15 would pass ``"assume_ai"`` and quietly get ``auto`` behavior --
a silent semantic change on the one release where they most need to be told.
"""
if value in _REMOVED_SENSITIVITIES:
@@ -368,7 +369,7 @@ _GEMINI_AUTO_MIN_CONF = GEMINI_SPARKLE_TRUST_CONF
# 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%,
# metadata), hand-labeled against a two-sided control (labeler sensitivity ~88%,
# specificity 100%). "Additions" = accepted with provenance but not without:
#
# band precision 95% CI population
@@ -409,6 +410,7 @@ _ENGINE_CLASS: dict[str, tuple[str, str]] = {
"runninghub": ("runninghub_engine", "RunningHubEngine"),
"baidu": ("baidu_engine", "BaiduEngine"),
"liblib": ("liblib_engine", "LibLibEngine"),
"microsoft": ("microsoft_engine", "MicrosoftEngine"),
}
@@ -485,7 +487,14 @@ def fill(image: NDArray[Any], mask: NDArray[Any], *, backend: Backend = "auto")
def _gemini_wrap(d: Any, *, provenance: bool) -> MarkDetection:
gate = _GEMINI_PROVENANCE_MIN_CONF if provenance else _GEMINI_AUTO_MIN_CONF
detected = bool(d.detected) and d.confidence >= gate
return MarkDetection("gemini", "Google Gemini sparkle", "bottom-right", detected, d.confidence, d.region)
return MarkDetection(
"gemini",
"Google Gemini visible watermark (sparkle)",
"bottom-right",
detected,
d.confidence,
d.region,
)
def _gemini_detect(image: NDArray[Any], *, provenance: bool = False) -> MarkDetection:
@@ -561,12 +570,14 @@ def _text_mark(
label_regime: str | None = "tc260",
provenance_signals: tuple[str, ...] = ("aigc",),
tc260_producer_codes: tuple[str, ...] = (),
provenance_platform_tokens: tuple[str, ...] = (),
) -> KnownMark:
"""Build a text-mark registry row from its shared detector and mask adapters.
``product`` defaults to the key (one mark, one product); pass it only when two
marks share a product. ``label_regime`` and ``provenance_signals`` default to the
China-AIGC label because every text mark registered so far except Samsung uses it.
China-AIGC label because every text mark registered so far except Samsung and
Microsoft uses it.
"""
return KnownMark(
key,
@@ -580,6 +591,7 @@ def _text_mark(
_text_mark_mask(key),
provenance_signals=provenance_signals,
tc260_producer_codes=tc260_producer_codes,
provenance_platform_tokens=provenance_platform_tokens,
_detect_both=_text_mark_detect_both(key, label, location),
)
@@ -616,11 +628,11 @@ def _pill_features(image: NDArray[Any]) -> dict[str, float]:
_REGISTRY: tuple[KnownMark, ...] = (
# Gemini is a Google C2PA/SynthID product, not a China-AIGC labeller: label_regime
# Gemini is a Google C2PA/SynthID product, not a China-AIGC labeler: label_regime
# is None so it can never act as a TC260 sibling in _keep_pill.
KnownMark(
"gemini",
"Google Gemini sparkle",
"Google Gemini visible watermark (sparkle)",
"bottom-right",
True,
"gemini",
@@ -651,14 +663,14 @@ _REGISTRY: tuple[KnownMark, ...] = (
"qwen",
"Qwen 千问AI生成 text",
"bottom-right",
platform="Alibaba Qwen (visible 千问AI生成 mark detected)",
platform="Alibaba Cloud Qwen (visible 千问AI生成 mark detected)",
tc260_producer_codes=("91440101MA9Y9T4H7A",),
),
_text_mark(
"kling",
"Kling 可灵AI 3.0 text",
"Kling AI 可灵AI 3.0 text",
"bottom-right",
platform="Kuaishou Kling (visible 可灵AI 3.0 mark detected)",
platform="Kuaishou Kling AI (visible 可灵AI 3.0 mark detected)",
tc260_producer_codes=("91110108335469089C",),
),
_text_mark(
@@ -693,11 +705,23 @@ _REGISTRY: tuple[KnownMark, ...] = (
),
_text_mark(
"liblib",
"LibLibAI wordmark",
"LiblibAI wordmark",
"bottom-center",
platform="LibLibAI (visible LibLibAI mark detected)",
platform="LiblibAI (visible LiblibAI mark detected)",
tc260_producer_codes=("91110105MACJ6K1C8A",),
),
# One measured Microsoft visible-mark variant: a white top-right pill with
# dark internal shapes. Microsoft's documented feature also permits other
# icon, text, and placement variants, which this detector does not cover.
_text_mark(
"microsoft",
"Microsoft top-right AI badge",
"top-right",
label_regime=None,
provenance_signals=(),
platform="Microsoft (visible top-right AI badge detected)",
provenance_platform_tokens=("microsoft",),
),
# Same product as the Jimeng wordmark -- the one pair that cross-relaxes.
KnownMark(
"jimeng_pill",
@@ -794,7 +818,7 @@ def tc260_producer_vendors() -> dict[str, str]:
def _pill_suppressors() -> set[str]:
"""Marks whose detection vetoes the capture-less pill: same label regime as the
pill, different product. Derived so a newly registered TC260 mark cannot be
forgotten here -- which is exactly how LibLibAI ended up missing."""
forgotten here -- which is exactly how LiblibAI ended up missing."""
pill = get_mark("jimeng_pill")
return {
m.key
@@ -822,9 +846,9 @@ def _keep_pill(keys: set[str], *, provenance: frozenset[str], footprint_flat: bo
No confirmation at all -> never remove (blocks false fires on non-Jimeng content).
The suppressor set is DERIVED from the registry (same label regime, different
product), not hand-listed. The hand-written list had drifted: LibLibAI was
product), not hand-listed. The hand-written list had drifted: LiblibAI was
registered alongside RunningHub and Baidu but never added to it, so a confident
LibLibAI detection did not veto the pill the way its two siblings did. Marks
LiblibAI detection did not veto the pill the way its two siblings did. Marks
outside the TC260 regime (Gemini, Samsung) are deliberately NOT suppressors --
neither can put ``"jimeng"`` into ``provenance``, so neither can enable the arm
they would be vetoing."""
+2 -2
View File
@@ -228,8 +228,8 @@ class TestVisibleCommand:
# The transparent corners must remain transparent.
assert out[0, 0, 3] == 0
assert out[199, 199, 3] == 0
# The opaque centre remains opaque (the watermark region default is bottom-right,
# which doesn't overlap the centre square at 200x200).
# The opaque center remains opaque (the watermark region default is bottom-right,
# which doesn't overlap the center square at 200x200).
assert out[100, 100, 3] == 255
def test_visible_keeps_alpha_opaque_in_watermark_region(self, runner, tmp_path):
+9
View File
@@ -58,3 +58,12 @@ def test_default_pipeline_clearance_is_recorded() -> None:
rows = {row["name"]: row for row in _manifest_rows()}
for name in ("fox_modal_invisible", "text_modal_invisible"):
assert rows[name]["oracle_verdict"] == "not_detected", name
def test_deterministic_transforms_reproduce_recorded_hashes(tmp_path: Path) -> None:
from scripts.contentseal_transforms import reproduce_transforms
outputs = reproduce_transforms(tmp_path)
assert len(outputs) == 8
assert all(path.is_file() for path in outputs)
+4 -1
View File
@@ -34,7 +34,10 @@ DESIGNER_STORE = {
},
{
"label": "c2pa.soft-binding",
"data": {"alg": "com.microsoft.invismark.1", "blocks": [{"value": "bf7a2993-cc1f-47e1-b1f0-cd8839aabb22"}]},
"data": {
"alg": "com.microsoft.invismark.1",
"blocks": [{"value": "bf7a2993-cc1f-47e1-b1f0-cd8839aabb22"}],
},
},
],
}
+23
View File
@@ -0,0 +1,23 @@
"""Cross-corpus integrity checks for tracked evaluation tables."""
from __future__ import annotations
import csv
import re
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
EVALUATIONS = ROOT / "data" / "evaluations"
SHA256 = re.compile(r"^[0-9a-f]{64}$")
def test_every_recorded_evaluation_sha256_is_well_formed() -> None:
checked = 0
for path in sorted(EVALUATIONS.rglob("*.csv")):
with path.open(newline="", encoding="utf-8") as stream:
for line_number, row in enumerate(csv.DictReader(stream), start=2):
for field, value in row.items():
if field is not None and field.endswith("sha256") and value:
assert SHA256.fullmatch(value), f"{path.relative_to(ROOT)}:{line_number} {field}={value!r}"
checked += 1
assert checked > 0
+89 -20
View File
@@ -17,7 +17,11 @@ from unittest.mock import patch
import pytest
from remove_ai_watermarks._internal.c2pa import c2pa_info_from_manifest_store
from remove_ai_watermarks._internal.constants import C2PA_AI_VENDORS, C2PA_CLAIM_GENERATOR_PLATFORMS
from remove_ai_watermarks._internal.constants import (
C2PA_AI_VENDORS,
C2PA_CLAIM_GENERATOR_PLATFORMS,
C2PA_IDENTITY_AI_ORGS,
)
from remove_ai_watermarks.identify import (
ProvenanceEvidence,
ProvenanceReport,
@@ -179,7 +183,7 @@ class TestProvenanceEvidence:
assert report.is_ai_generated is True
assert report.confidence == "high"
assert report.platform == "OpenAI (ChatGPT / gpt-image / DALL-E / Sora)"
assert report.platform == "OpenAI (ChatGPT / GPT Image / DALL·E / Sora)"
assert not any("not anchored" in caveat for caveat in report.caveats)
def test_external_metadata_record_builds_equivalent_evidence(self, tmp_path: Path):
@@ -244,7 +248,7 @@ class TestProvenanceEvidence:
report = identify_from_evidence(evidence_from_metadata_record(record, path=path))
assert report.is_ai_generated is True
assert report.platform == "OpenAI (ChatGPT / gpt-image / DALL-E / Sora)"
assert report.platform == "OpenAI (ChatGPT / GPT Image / DALL·E / Sora)"
assert [signal.name for signal in report.signals] == ["c2pa"]
def test_external_generator_bytes_are_normalized(self, tmp_path: Path):
@@ -374,13 +378,12 @@ class TestAttributePlatform:
assert platform
assert "Canva" in platform
def test_byteplus_attributes_to_bytedance(self):
def test_byteplus_keeps_its_product_name(self):
# ByteDance's intl brand signs as "Byteplus Pte. Ltd."; the registry maps
# it to the ByteDance platform (was mis-read as Adobe via an incidental
# it to the ByteDance family (was mis-read as Adobe via an incidental
# "Adobe XMP" file string before the entry existed).
platform = _attribute_platform(["BytePlus (ByteDance)"])
assert platform
assert "ByteDance" in platform
assert platform == "BytePlus (ByteDance)"
def test_empty_is_none(self):
assert _attribute_platform([]) is None
@@ -444,7 +447,7 @@ class TestIdentifyNonPng:
path = self._c2pa_jpeg(tmp_path, b"certificate_center@volcengine.com ... trainedAlgorithmicMedia")
r = identify(path, check_visible=False, check_invisible=False)
assert r.is_ai_generated is True
assert "ByteDance" in (r.platform or "")
assert r.platform == "ByteDance Volcano Engine"
def test_bytedance_chinese_legal_name_attributed(self, tmp_path: Path):
# Some Volcano Engine certs name the signer with the Chinese legal entity
@@ -454,7 +457,7 @@ class TestIdentifyNonPng:
path = self._c2pa_jpeg(tmp_path, blob)
r = identify(path, check_visible=False, check_invisible=False)
assert r.is_ai_generated is True
assert "ByteDance" in (r.platform or "")
assert r.platform == "ByteDance Volcano Engine"
@pytest.mark.parametrize(
("claim_generator", "platform"),
@@ -498,7 +501,7 @@ class TestIdentifyNonPng:
path = self._c2pa_jpeg(tmp_path, b"Bytedance Pte. Ltd. Dreamina/7.5.0 c2pa.created")
r = identify(path, check_visible=False, check_invisible=False)
assert r.is_ai_generated is True
assert "ByteDance" in (r.platform or "")
assert r.platform == "ByteDance Dreamina"
def test_elevenlabs_attributed(self, tmp_path: Path):
path = self._c2pa_jpeg(tmp_path, b"Eleven Labs Inc. ... trainedAlgorithmicMedia")
@@ -666,6 +669,57 @@ class TestIdentifyRealSamples:
assert r.is_ai_generated is True
assert r.ai_source_kind == "enhanced"
def test_standalone_ai_tag_attributes_the_content_seal(self, tmp_path: Path):
"""A standalone AI digital-source tag emits the seal as its own signal.
Muse Image outputs carry no C2PA; this tag is their only provenance, and
Muse stamps every output with the invisible Content Seal. The signal is
the strength router's Meta bet as evidence - an attribution, not a decode
(no public decoder exists), so its confidence is medium and the caveat
still points at the oracle.
"""
p = tmp_path / "muse-tag.jpg"
p.write_bytes(
b'\xff\xd8\xff\xe1<x:xmpmeta Iptc4xmpExt:DigitalSourceType="trainedAlgorithmicMedia"></x:xmpmeta>\xff\xd9'
)
r = identify(p, check_visible=False, check_invisible=False)
names = [s.name for s in r.signals]
assert "iptc" in names
assert "content_seal" in names
seal = next(s for s in r.signals if s.name == "content_seal")
assert seal.confidence == "medium"
assert "Invisible Content Seal watermark (Meta Muse attribution)" in r.watermarks
assert any("meta.ai/identification" in c for c in r.caveats)
def test_seal_platform_attribution_follows_the_signal(self, tmp_path: Path):
"""The Likely-source line follows the same bet the seal signal makes.
Apple keeps its own attribution; every other standalone-tag file gets the
hedged Muse attribution instead of "platform not specified", so the panel
that prices the Content Seal and the source line agree.
"""
muse = tmp_path / "muse.jpg"
muse.write_bytes(
b'\xff\xd8\xff\xe1<x:xmpmeta Iptc4xmpExt:DigitalSourceType="trainedAlgorithmicMedia"></x:xmpmeta>\xff\xd9'
)
apple = tmp_path / "apple.jpg"
apple.write_bytes(
b'\xff\xd8\xff\xe1<x:xmpmeta Iptc4xmpExt:DigitalSourceType="compositeWithTrainedAlgorithmicMedia" '
b'photoshop:Credit="Apple Photos Clean Up"></x:xmpmeta>\xff\xd9'
)
assert identify(muse, check_visible=False, check_invisible=False).platform == (
"Meta Muse Image (attributed by the standalone AI digital-source tag)"
)
assert identify(apple, check_visible=False, check_invisible=False).platform == "Apple Photos (Clean Up AI edit)"
def test_c2pa_backed_file_gets_no_content_seal_attribution(self):
"""C2PA issuers win first: a manifest-backed file is not Meta-routed."""
r = identify(SAMPLES_DIR / "flux-1.png", check_visible=False, check_invisible=False)
assert "content_seal" not in [s.name for s in r.signals]
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)
@@ -844,7 +898,7 @@ class TestIdentifyAigcPngChunk:
assert "doubao" in signal.detail
# ── HuggingFace-hosted job marker (medium confidence) ───────────────
# ── Hugging Face-hosted job marker (medium confidence) ─────────────
class TestIdentifyHuggingFaceJob:
@@ -866,7 +920,7 @@ class TestIdentifyHuggingFaceJob:
assert r.is_ai_generated is True
assert r.confidence == "medium"
assert r.platform is not None
assert "HuggingFace" in r.platform
assert "Hugging Face" in r.platform
signal = next(s for s in r.signals if s.name == "hf_job")
assert signal.confidence == "medium"
@@ -1170,7 +1224,7 @@ class TestSynthIDProvenanceEvidence:
png = self._png(tmp_path, "dreamina.png", self._png_chunk(b"caBX", b"jumbc2pa Dreamina/7.5.0 c2pa.created"))
r = identify(png, check_visible=False, check_invisible=False)
assert r.is_ai_generated is True
assert "ByteDance" in (r.platform or "")
assert r.platform == "ByteDance Dreamina"
class TestReportSerializable:
@@ -1401,7 +1455,7 @@ class TestIdentifyAIGC:
class TestVendorOf:
def test_openai_variants(self):
assert _vendor_of("OpenAI (ChatGPT / gpt-image / DALL-E / Sora)") == "OpenAI"
assert _vendor_of("OpenAI (ChatGPT / GPT Image / DALL·E / Sora)") == "OpenAI"
assert _vendor_of("DALL-E 3") == "OpenAI"
def test_google_variants(self):
@@ -1427,17 +1481,32 @@ class TestVendorOf:
# entered clash detection (a coverage hole). They now normalize to one origin.
assert _vendor_of("Microsoft (Copilot / Designer)") == "Microsoft"
assert _vendor_of("Copilot") == "Microsoft"
assert _vendor_of("ByteDance (Doubao / Jimeng / Dreamina / Volcano Engine)") == "ByteDance"
assert _vendor_of("ByteDance Volcano Engine") == "ByteDance"
assert _vendor_of("BytePlus (ByteDance)") == "ByteDance"
assert _vendor_of("Dreamina/1.2") == "ByteDance"
assert _vendor_of("Canva (Magic Media)") == "Canva"
assert _vendor_of("Black Forest Labs (FLUX)") == "Black Forest Labs"
assert _vendor_of("Eleven Labs Inc.") == "ElevenLabs"
assert _vendor_of("Ideogram") == "Ideogram"
def test_bytedance_issuers_share_one_platform(self):
expected = "ByteDance (Doubao / Jimeng / Dreamina / Volcano Engine)"
platforms = {vendor.platform for vendor in C2PA_AI_VENDORS if vendor.needle == "ByteDance"}
assert platforms == {expected}
assert ("dreamina", expected) in C2PA_CLAIM_GENERATOR_PLATFORMS
def test_ideogram_issuer_attributed(self):
# Corpus evidence 2026-08-08: four uploads signed "Ideogram, Inc" read as
# unknown-signer C2PA with no platform. The issuer token is the org prefix.
platforms = {v.issuer: v.platform for v in C2PA_AI_VENDORS}
assert platforms[b"Ideogram"] == "Ideogram"
assert "Ideogram" in C2PA_IDENTITY_AI_ORGS
assert _issuers_in(b"...CN=Ideogram, Inc...trainedAlgorithmicMedia") == ["Ideogram"]
def test_bytedance_issuers_keep_the_source_product(self):
platforms = {
vendor.issuer: vendor.platform
for vendor in C2PA_AI_VENDORS
if vendor.org.startswith("ByteDance") or vendor.org.startswith("BytePlus")
}
assert platforms[b"volcengine"] == "ByteDance Volcano Engine"
assert platforms[b"Byteplus"] == "BytePlus (ByteDance)"
assert platforms[b"Dreamina"] == "ByteDance Dreamina"
assert ("dreamina", "ByteDance Dreamina") in C2PA_CLAIM_GENERATOR_PLATFORMS
class TestIntegrityClashesHelper:
+2 -5
View File
@@ -60,6 +60,7 @@ class TestVerifiedTextMode:
manifest.write_text("{}", encoding="utf-8")
cases = (
("sdxl-zimage", {}, "qwen-zimage"),
("qwen-zimage", {"tile": True}, "not calibrated with --tile"),
("qwen-zimage", {"max_resolution": 1024}, "max-resolution 0"),
("qwen-zimage", {"humanize": 1.0}, "humanize=0"),
("qwen-zimage", {"adaptive_polish": True}, "polish disabled"),
@@ -128,10 +129,6 @@ class TestVerifiedTextMode:
assert seen["fidelity_anchor"] is True
engine.remove_watermark(source, output, text_manifest=manifest, tile=True)
assert seen["tile"] is True
class TestNativeOutputSize:
"""Model-side latent-grid rounding must not change the public output size."""
@@ -248,7 +245,7 @@ class TestEngineResolvesThePolishPerProfile:
This is the change that stopped a library caller and a CLI caller on one profile
from producing different pixels, and it had no test: rebinding
``resolve_adaptive_polish`` to ``bool(value)`` -- exactly the pre-commit behaviour --
``resolve_adaptive_polish`` to ``bool(value)`` -- exactly the pre-commit behavior --
left the whole suite green.
"""
+1 -1
View File
@@ -72,7 +72,7 @@ class TestConfig:
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
# Clean arm scored p99 0.304 / max 0.320 on 286 hand-labeled frames; the
# gate must sit above that with margin.
assert KlingEngine().config.detect_ncc_threshold > 0.32
+4 -4
View File
@@ -1,4 +1,4 @@
"""Tests for the LibLibAI ("LibLibAI" wordmark) visible-watermark engine.
"""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
@@ -24,7 +24,7 @@ _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."""
"""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)
@@ -112,8 +112,8 @@ class TestDetectAndMask:
assert eng.footprint_mask(img) is None
def test_confident_liblib_detection_suppresses_the_jimeng_pill(self):
# A LibLibAI image is TC260 too but is not Jimeng-basic: like Doubao/Qwen/
# Kling/RunningHub/Baidu, a confident LibLibAI detection must veto the pill.
# A LiblibAI image is TC260 too but is not Jimeng-basic: like Doubao/Qwen/
# Kling/RunningHub/Baidu, a confident LiblibAI detection must veto the pill.
# It was the one mark the hand-written veto list in ``_keep_pill`` missed.
from remove_ai_watermarks.watermark_registry import _keep_pill
+6 -3
View File
@@ -1562,7 +1562,7 @@ class TestAIGCLabel:
class TestHuggingFaceJob:
"""HuggingFace-hosted job marker (``hf-job-id`` PNG text chunk)."""
"""Hugging Face-hosted job marker (``hf-job-id`` PNG text chunk)."""
def _hf_png(self, tmp_path: Path, job_id: str = "ec8380a6-2091-423a-b835-209420f99ee1") -> Path:
p = tmp_path / "hfjob.png"
@@ -1622,10 +1622,13 @@ class TestSoftBinding:
from remove_ai_watermarks._internal.c2pa import soft_binding_vendors_in
assert soft_binding_vendors_in(b"...alg...com.adobe.trustmark.P...") == ["Adobe TrustMark"]
assert soft_binding_vendors_in(b"com.digimarc.validate.1") == ["Digimarc"]
assert soft_binding_vendors_in(b"com.digimarc.validate.1") == ["Digimarc Validate"]
assert soft_binding_vendors_in(b"ai.steg.api blah") == ["Steg.AI"]
# Registry-verified vendors added in v0.6.x.
assert soft_binding_vendors_in(b"ai.trufo.gen1.image") == ["Trufo"]
assert soft_binding_vendors_in(b"ai.trufo.pawprint.watermark") == ["Trufo PawPrint"]
assert soft_binding_vendors_in(b"com.aiwatermark.pixelseal.1") == ["AIWatermark PixelSeal"]
assert soft_binding_vendors_in(b"com.aiwatermark.videoseal.1") == ["AIWatermark VideoSeal"]
assert soft_binding_vendors_in(b"com.aiwatermark.audioseal.1") == ["AIWatermark AudioSeal"]
assert soft_binding_vendors_in(b"io.iscc.v0") == ["ISCC (content code)"]
def test_vendors_in_empty_when_absent(self):
+5 -5
View File
@@ -266,8 +266,8 @@ class TestC2PA:
def test_content_fingerprint_does_not_trigger_invisible_removal(self):
info = {
"soft_binding": "Adobe (content fingerprint)",
"soft_binding_vendors": ["Adobe (content fingerprint)"],
"soft_binding": "Adobe Image Comparator Network",
"soft_binding_vendors": ["Adobe Image Comparator Network"],
}
assert c2pa_info_has_removal_hint(info) is False
@@ -1007,7 +1007,7 @@ class TestTc260ContainerRouting:
def _riff_chunk(chunk_id: bytes, payload: bytes) -> bytes:
return chunk_id + len(payload).to_bytes(4, "little") + payload + (b"\x00" if len(payload) & 1 else b"")
def _labelled_avi(self) -> bytes:
def _labeled_avi(self) -> bytes:
info = self._riff_chunk(b"AIGC", _TC260_AIGC_VALUE)
body = b"AVI " + self._riff_chunk(b"LIST", b"INFO" + info)
return b"RIFF" + len(body).to_bytes(4, "little") + body
@@ -1016,7 +1016,7 @@ class TestTc260ContainerRouting:
from remove_ai_watermarks.metadata import aigc_label
target = tmp_path / "clip.bin" # correct AVI bytes, wrong suffix
target.write_bytes(self._labelled_avi())
target.write_bytes(self._labeled_avi())
label = aigc_label(target)
assert label is not None
assert label["Label"] == "1"
@@ -1025,7 +1025,7 @@ class TestTc260ContainerRouting:
from remove_ai_watermarks.metadata import aigc_label
target = tmp_path / "clip.avi"
target.write_bytes(self._labelled_avi())
target.write_bytes(self._labeled_avi())
assert aigc_label(target) is not None
def test_webp_yields_nothing_from_the_riff_reader(self, tmp_path: Path):
+163
View File
@@ -0,0 +1,163 @@
"""Tests for the measured Microsoft top-right AI-badge engine.
The covered variant is a white top-right pill with dark internal shapes. The
2026-08-27 calibration kept visually confirmed carriers, provenance-only files,
and no-signal controls separate. These tests pin the load-bearing constants --
especially the long-side scale basis and the internal holes as the discriminator.
"""
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.microsoft_engine import (
_ALPHA_HEIGHT_FRAC,
_ALPHA_WIDTH_FRAC,
MicrosoftEngine,
_alpha_template,
)
_INSET = 0.010 # measured pill inset from the top/right edges (long-side fraction)
def _pill_geometry(w: int, h: int) -> tuple[int, int, int, int]:
long_side = max(w, h)
pw = int(_ALPHA_WIDTH_FRAC * long_side)
ph = max(4, int(_ALPHA_HEIGHT_FRAC * long_side))
pad = int(_INSET * long_side)
return w - pad - pw, pad, pw, ph
def _compose(w: int, h: int, bg: float = 110.0):
"""Composite the synthetic pill at its measured size onto a flat background."""
img = np.full((h, w, 3), bg, np.uint8)
at = _alpha_template()
x0, y0, pw, ph = _pill_geometry(w, h)
pill = cv2.resize(at, (pw, ph))
region = img[y0 : y0 + ph, x0 : x0 + pw]
bright = pill > 0.6
region[bright] = 245
# Internal holes are dark ink inside the pill, not background.
region[~bright] = 45
return img, (x0, y0, pw, ph)
def _plain_pill(w: int, h: int, text: str | None = None) -> np.ndarray:
"""Return a white rounded pill without the expected holes, or with foreign text."""
img = np.full((h, w, 3), 110.0, np.uint8)
x0, y0, pw, ph = _pill_geometry(w, h)
cv2.rectangle(img, (x0, y0), (x0 + pw, y0 + ph), (245, 245, 245), -1)
cv2.circle(img, (x0 + ph // 2, y0 + ph // 2), ph // 3, (110, 110, 110), -1)
if text:
cv2.putText(img, text, (x0 + ph, y0 + ph // 2 + ph // 6), cv2.FONT_HERSHEY_SIMPLEX, ph / 90.0, (45, 45, 45), 1)
return img
class TestLocate:
def test_box_anchored_top_right(self):
eng = MicrosoftEngine()
loc = eng.locate(np.zeros((1024, 1024, 3), np.uint8))
assert loc.x + loc.w == pytest.approx(1024 - int(0.004 * 1024), abs=2)
assert loc.y == pytest.approx(int(0.003 * 1024), abs=2)
def test_box_scales_with_long_side_not_width(self):
# Measured: the pill tracks the render dimension, so a 1024x1536 portrait
# carries the SAME pill size as 1536x1024. A width basis undersized the
# template by the aspect ratio and dropped every portrait carrier.
eng = MicrosoftEngine()
portrait = eng.locate(np.zeros((1536, 1024, 3), np.uint8))
landscape = eng.locate(np.zeros((1024, 1536, 3), np.uint8))
assert portrait.w == landscape.w
small = eng.locate(np.zeros((720, 480, 3), np.uint8))
assert small.w < portrait.w
class TestConfig:
def test_strict_only_no_provenance_relaxation(self):
# Provenance names Microsoft, not the presence of this visible layout.
assert MicrosoftEngine().config.provenance_ncc_factor == 1.0
def test_long_scale_basis(self):
assert MicrosoftEngine().config.scale_basis == "long"
def test_threshold_and_geometry_pins(self):
from remove_ai_watermarks.microsoft_engine import (
DETECT_NCC_THRESHOLD,
MARGIN_RIGHT_FRAC,
WM_WIDTH_FRAC,
)
assert pytest.approx(0.38) == DETECT_NCC_THRESHOLD # controls max 0.293; carriers max 0.579
assert pytest.approx(0.170) == WM_WIDTH_FRAC
assert pytest.approx(0.004) == MARGIN_RIGHT_FRAC
def test_registry_row(self):
mark = registry.get_mark("microsoft")
assert mark.location == "top-right"
assert mark.label == "Microsoft top-right AI badge"
assert mark.in_auto
assert mark.provenance_platform_tokens == ("microsoft",)
assert mark.label_regime is None # not a China-TC260 mark
class TestDetect:
@pytest.mark.parametrize(("w", "h"), [(1024, 1024), (1536, 1024), (1024, 1536), (720, 480), (1206, 1194)])
def test_composites_detected_across_sizes(self, w, h):
eng = MicrosoftEngine()
img, _box = _compose(w, h)
det = eng.detect(img)
assert det.detected, f"{w}x{h}: conf={det.confidence:.3f}"
assert det.confidence >= 0.38
def test_portrait_composite_region_covers_pill(self):
eng = MicrosoftEngine()
img, (x, y, pw, ph) = _compose(1024, 1536)
det = eng.detect(img)
assert det.detected
rx, ry, rw, _rh = det.region
assert abs((rx + rw) - (x + pw)) < 0.08 * pw
assert abs(ry - y) < 0.4 * ph
def test_clean_gradient_not_detected(self):
eng = MicrosoftEngine()
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_plain_white_pill_not_detected(self):
# The expected internal holes are the discriminator: any other bright rounded
# element in the corner must not attribute Microsoft.
eng = MicrosoftEngine()
assert not eng.detect(_plain_pill(1024, 1024)).detected
def test_foreign_text_pill_not_detected(self):
eng = MicrosoftEngine()
assert not eng.detect(_plain_pill(1024, 1024, text="Sample Text")).detected
def test_busy_content_corner_not_detected(self):
# A photo-like textured corner must stay under the gate.
eng = MicrosoftEngine()
rng = np.random.default_rng(7)
img = rng.integers(0, 255, (1024, 1024, 3), dtype=np.uint8)
img = cv2.GaussianBlur(img, (0, 0), 3)
assert not eng.detect(img).detected
class TestMask:
def test_footprint_covers_the_pill(self):
eng = MicrosoftEngine()
img, (x, y, pw, ph) = _compose(1536, 1024)
det = eng.detect(img)
assert det.detected
mask = eng.footprint_mask(img, detection=det)
assert mask.shape[:2] == img.shape[:2]
ys, xs = np.where(mask > 0)
assert xs.min() >= x - 0.15 * pw
assert xs.max() <= x + pw + 0.15 * pw
assert ys.min() >= y - 0.3 * ph
assert ys.max() <= y + ph + 0.3 * ph
# the fill must cover the pill area, not just the text glyphs
assert float(mask[y : y + ph, x : x + pw].mean()) > 0.4
+1 -1
View File
@@ -285,7 +285,7 @@ class TestResolveStrength:
assert SDXL_ZIMAGE_UNKNOWN_STRENGTH == SDXL_ZIMAGE_GEMINI_STRENGTH
assert resolve_strength(None, "openai", "sdxl-zimage") == SDXL_ZIMAGE_OPENAI_STRENGTH
assert resolve_strength(None, "google", "sdxl-zimage") == SDXL_ZIMAGE_GEMINI_STRENGTH
# An unrecognised issuer takes the stricter Gemini value, not the OpenAI one.
# An unrecognized issuer takes the stricter Gemini value, not the OpenAI one.
assert resolve_strength(None, "adobe", "sdxl-zimage") == SDXL_ZIMAGE_UNKNOWN_STRENGTH
assert resolve_strength(None, None, "sdxl-zimage") == SDXL_ZIMAGE_UNKNOWN_STRENGTH
+34 -25
View File
@@ -659,8 +659,7 @@ def test_no_face_path_still_runs_verified_text_restoration(monkeypatch):
restore.assert_called_with(source, anchor, donor, manifest.lines)
def test_tiled_verified_text_runs_vae_donor_per_tile(monkeypatch):
from remove_ai_watermarks._internal import qwen_zimage_pipeline, text_restoration
def test_tiled_verified_text_is_rejected_before_model_work():
from remove_ai_watermarks._internal.qwen_zimage_pipeline import QwenZImagePipeline
from remove_ai_watermarks._internal.text_restoration import VerifiedTextLine, VerifiedTextManifest
@@ -668,12 +667,6 @@ def test_tiled_verified_text_runs_vae_donor_per_tile(monkeypatch):
pipeline.device = "cuda"
pipeline.progress_callback = None
source = Image.new("RGB", (96, 80), (10, 20, 30))
restored = Image.new("RGB", (96, 80), (130, 140, 150))
pipeline._qwen_vae_roundtrip = MagicMock(side_effect=lambda tile: tile)
pipeline._run_global = MagicMock(side_effect=lambda tile, _strength, _seed: tile)
monkeypatch.setattr(qwen_zimage_pipeline, "detect_faces", lambda _image: [])
restore = MagicMock(return_value=restored)
monkeypatch.setattr(text_restoration, "restore_verified_text", restore)
manifest = VerifiedTextManifest(
"0" * 64,
96,
@@ -681,23 +674,16 @@ def test_tiled_verified_text_runs_vae_donor_per_tile(monkeypatch):
(VerifiedTextLine((4, 4, 20, 16), "Exact", "alphabetic"),),
)
result = pipeline.run(
source,
strength=0.1,
seed=0,
tile=True,
tile_size=64,
tile_overlap=16,
text_manifest=manifest,
)
assert result is restored
assert pipeline._qwen_vae_roundtrip.call_count > 1
assert pipeline._run_global.call_count > 1
restore.assert_called_once()
assert restore.call_args.args[0].size == (96, 80)
assert restore.call_args.args[1].size == (96, 80)
assert restore.call_args.args[2].size == (96, 80)
with pytest.raises(ValueError, match="not calibrated with tiled diffusion"):
pipeline.run(
source,
strength=0.1,
seed=0,
tile=True,
tile_size=64,
tile_overlap=16,
text_manifest=manifest,
)
def test_watermark_remover_dispatches_to_full_pipeline(tmp_path, monkeypatch):
@@ -757,6 +743,29 @@ def test_watermark_remover_dispatches_qwen_tiling_to_full_pipeline(tmp_path, mon
assert output.exists()
def test_watermark_remover_rejects_tiled_verified_text_before_pipeline(tmp_path, monkeypatch):
from remove_ai_watermarks._internal.text_restoration import VerifiedTextLine, VerifiedTextManifest
from remove_ai_watermarks._internal.watermark_remover import WatermarkRemover
_mock_watermark_runtime_deps(monkeypatch)
source = tmp_path / "source.png"
Image.new("RGB", (96, 80), (20, 30, 40)).save(source)
manifest = VerifiedTextManifest(
"0" * 64,
96,
80,
(VerifiedTextLine((4, 4, 20, 16), "Exact", "alphabetic"),),
)
remover = WatermarkRemover(device="cuda", pipeline="qwen-zimage")
runtime = MagicMock()
monkeypatch.setattr(remover, "_load_qwen_zimage_pipeline", lambda: runtime)
with pytest.raises(ValueError, match="not calibrated with tiled diffusion"):
remover.remove_watermark(source, text_manifest=manifest, tile=True)
runtime.run.assert_not_called()
def test_qwen_tiling_runs_global_tiles_then_one_full_frame_face_stage(monkeypatch):
from remove_ai_watermarks._internal.qwen_zimage_pipeline import (
QwenZImagePipeline,
+59
View File
@@ -0,0 +1,59 @@
"""Contracts for the registered visible-mark calibration harness."""
from __future__ import annotations
import importlib.util
import json
from pathlib import Path
import pytest
SCRIPT = Path(__file__).parents[1] / "scripts" / "registered_mark_calibrate.py"
SPEC = importlib.util.spec_from_file_location("registered_mark_calibrate", SCRIPT)
assert SPEC
assert SPEC.loader
module = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(module)
def test_manifest_preserves_evidence_arms(tmp_path: Path) -> None:
manifest = tmp_path / "manifest.jsonl"
manifest.write_text(
"\n".join(
[
json.dumps({"path": "carrier.png", "arm": "positive"}),
json.dumps({"path": "provider.png", "arm": "metadata"}),
json.dumps({"path": "comparison.png", "arm": "control"}),
]
),
encoding="utf-8",
)
rows = module.load_manifest(manifest)
assert [row["arm"] for row in rows] == ["positive", "metadata", "control"]
assert all(Path(row["path"]).is_absolute() for row in rows)
def test_manifest_rejects_one_file_in_multiple_arms(tmp_path: Path) -> None:
manifest = tmp_path / "manifest.jsonl"
manifest.write_text(
"\n".join(
[
json.dumps({"path": "same.png", "arm": "positive"}),
json.dumps({"path": "same.png", "arm": "control"}),
]
),
encoding="utf-8",
)
with pytest.raises(ValueError, match="duplicate image path"):
module.load_manifest(manifest)
def test_summary_never_relabels_a_control() -> None:
summary = module.summarize([0.1, 0.4], unreadable=1, fires=1)
assert summary["n"] == 2
assert summary["unreadable"] == 1
assert summary["fires"] == 1
+1 -1
View File
@@ -71,7 +71,7 @@ class TestConfig:
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.
# Clean arm scored p99 0.273 / max 0.295 on 286 hand-labeled frames.
assert RunningHubEngine().config.detect_ncc_threshold > 0.295
def test_registry_row(self):
+50
View File
@@ -0,0 +1,50 @@
"""Basic command-line contracts for standalone maintainer scripts."""
from __future__ import annotations
import subprocess
import sys
from os import environ
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[1]
@pytest.mark.parametrize(
"script",
[
"visible_groundtruth.py",
"visible_recall_sample.py",
"visible_sheets.py",
"registered_mark_calibrate.py",
],
)
def test_script_help_exits_cleanly(script: str) -> None:
result = subprocess.run( # noqa: S603 -- fixed interpreter and repository-owned script path
[sys.executable, str(ROOT / "scripts" / script), "--help"],
cwd=ROOT,
capture_output=True,
text=True,
check=False,
)
assert result.returncode == 0, result.stderr
assert "usage:" in result.stdout
def test_visible_groundtruth_help_is_cp1252_safe() -> None:
env = environ.copy()
env["PYTHONIOENCODING"] = "cp1252"
result = subprocess.run( # noqa: S603 -- fixed interpreter and repository-owned script path
[sys.executable, str(ROOT / "scripts" / "visible_groundtruth.py"), "--help"],
cwd=ROOT,
env=env,
capture_output=True,
text=True,
check=False,
)
assert result.returncode == 0, result.stderr
assert "usage:" in result.stdout
+2 -2
View File
@@ -1,6 +1,6 @@
"""Policy-level tests for the shared text-mark engine config.
These assert calibrated TUNING, not algorithm behaviour --
These assert calibrated TUNING, not algorithm behavior --
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
@@ -74,7 +74,7 @@ class TestScaleBasis:
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
"""Measured, not an oversight: the short-side basis took jimeng's labeled
landscape positives from 13/13 to 0/13."""
from remove_ai_watermarks import jimeng_engine
+1 -1
View File
@@ -118,7 +118,7 @@ class TestFaintMaskStaysTight:
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
# correct mask lands near 60%. The pre-fix behavior 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"
+1 -1
View File
@@ -100,7 +100,7 @@ class TestRunTiled:
def test_identity_generate_reconstructs_image(self):
# A blend of identical (unchanged) tiles must reproduce the input exactly,
# regardless of overlap -- the feather weights are a partition-of-unity once
# normalised. This is the seam-free guarantee.
# normalized. This is the seam-free guarantee.
rng = np.random.default_rng(0)
arr = rng.integers(0, 256, size=(1500, 1300, 3), dtype=np.uint8)
image = Image.fromarray(arr)
+1 -1
View File
@@ -3,7 +3,7 @@
TrustMark is an optional dependency (extra ``trustmark``) that downloads model
weights on first use, so the decode path is only exercised when it is installed
(mirrors the imwatermark handling). The always-on test pins the graceful
absent/error behaviour: detect must return None, never raise.
absent/error behavior: detect must return None, never raise.
"""
from __future__ import annotations
+7 -1
View File
@@ -860,6 +860,12 @@ class TestVideoMetadataApi:
class TestVideoProvenanceApi:
def test_c2pa_platform_keeps_the_bytedance_surface_name(self):
from remove_ai_watermarks.video import _platform_from_video_metadata
assert _platform_from_video_metadata({"issuer": "BytePlus (ByteDance)"}) == "BytePlus (ByteDance)"
assert _platform_from_video_metadata({"issuer": "ByteDance (Volcano Engine)"}) == "ByteDance Volcano Engine"
def test_identifies_metadata_without_pixel_scan(self, tmp_path: Path):
from remove_ai_watermarks.video import identify_video
@@ -870,7 +876,7 @@ class TestVideoProvenanceApi:
assert report.source == source
assert report.is_ai_generated is True
assert report.confidence == "high"
assert report.platform == "OpenAI (ChatGPT / gpt-image / DALL-E / Sora)"
assert report.platform == "OpenAI (ChatGPT / GPT Image / DALL·E / Sora)"
assert report.visible_mark is None
assert report.total_frames is None
assert report.has_ai_metadata is True
+1 -1
View File
@@ -142,7 +142,7 @@ def test_pairing_follows_the_engine_sampling_rule_not_just_the_frame_count(
in the suite that constrains the sampler's phase at all.
The clips encode losslessly, so the aligned pairing is exact and clears any
floor; the misaligned one compares frames a full colour step apart and lands
floor; the misaligned one compares frames a full color step apart and lands
near 9 dB, which is what leaves the 25 dB ceiling a wide moat rather than a
tuned threshold.
"""
+59 -3
View File
@@ -3,12 +3,14 @@
from __future__ import annotations
import csv
import math
import sys
import threading
from pathlib import Path
from types import SimpleNamespace
from typing import TYPE_CHECKING, cast
from typing import TYPE_CHECKING, Any, cast
import numpy as np
import pytest
from remove_ai_watermarks import optional_deps, video_encoding, video_invisible
@@ -92,6 +94,50 @@ def test_regeneration_rejects_noise_outside_unit_interval(tmp_path: Path) -> Non
)
@pytest.mark.parametrize(
("kwargs", "message"),
[
({"fps": 0.0}, "fps must be at least 1"),
({"batch_size": 0}, "batch_size must be at least 1"),
({"duration": 0.0}, "duration must be positive"),
({"device": "tpu"}, "device must be auto, cuda, mps, or cpu"),
],
)
def test_regeneration_rejects_invalid_controls_before_probing(
tmp_path: Path,
kwargs: dict[str, Any],
message: str,
) -> None:
with pytest.raises(ValueError, match=message):
video_invisible.regenerate_video_candidate(
tmp_path / "source.mp4",
tmp_path / "candidate.mp4",
**kwargs,
)
def test_fit_size_and_paired_psnr_validate_geometry() -> None:
assert video_invisible._fit_size(1920, 1080, 512) == (512, 288)
with pytest.raises(ValueError, match="positive"):
video_invisible._fit_size(0, 1080, 512)
with pytest.raises(ValueError, match="at least"):
video_invisible._fit_size(1920, 1080, 4)
frame = np.zeros((2, 2, 3), dtype=np.uint8)
assert video_invisible.paired_psnr(frame, frame) == math.inf
with pytest.raises(ValueError, match="matching shapes"):
video_invisible.paired_psnr(frame, frame[:1])
def test_load_runtime_rejects_invalid_device_and_missing_extra(monkeypatch: pytest.MonkeyPatch) -> None:
with pytest.raises(ValueError, match="device must be"):
video_invisible.load_video_vae_runtime(device="tpu")
monkeypatch.setattr(video_invisible, "is_available", lambda: False)
with pytest.raises(RuntimeError, match="diffusion extra"):
video_invisible.load_video_vae_runtime()
def test_encoder_and_mux_commands_separate_streaming_frames_from_source_audio(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
@@ -298,8 +344,9 @@ def test_shipped_defaults_match_a_certified_manifest_row() -> None:
rate now fails here until a ``not_detected`` row exists for that exact triple.
The tuple stops at three fields because the model is a fourth thing the oracle
was shown and neither tracked row records it. That omission is data-driven: add
``vae`` here in the same commit as the first row that records one.
was shown and neither historical row recorded it. The manifest says
``unrecorded`` rather than leaving an ambiguous empty field. Add ``vae`` here in
the same commit as the first row that records one.
"""
with ORACLE_MANIFEST.open(newline="", encoding="utf-8") as stream:
certified = {
@@ -320,6 +367,15 @@ def test_shipped_defaults_match_a_certified_manifest_row() -> None:
)
def test_oracle_manifest_marks_missing_vae_identity_explicitly() -> None:
with ORACLE_MANIFEST.open(newline="", encoding="utf-8") as stream:
rows = list(csv.DictReader(stream))
assert rows
assert all(row["vae"] for row in rows)
assert all(row["vae"] == "unrecorded" or "/" in row["vae"] for row in rows)
def test_stream_batches_consumes_only_one_batch_ahead() -> None:
consumed: list[int] = []
+13 -8
View File
@@ -25,6 +25,7 @@ class TestCatalog:
"runninghub",
"baidu",
"liblib",
"microsoft",
"jimeng_pill",
]
@@ -113,6 +114,7 @@ class TestScan:
"runninghub",
"baidu",
"liblib",
"microsoft",
"jimeng_pill",
}
@@ -219,7 +221,7 @@ class TestProvenanceGate:
# 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.
# value, this test must fail on the behavior 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
@@ -529,7 +531,7 @@ class TestMarkKnowledgeIsOnTheRow:
Product family, label regime, the platform sentence and the metadata signals that
confirm the vendor all used to live in separate hand-maintained tables across
``watermark_registry``, ``identify`` and ``api``. That is how LibLibAI ended up
``watermark_registry``, ``identify`` and ``api``. That is how LiblibAI ended up
registered but absent from the pill veto.
"""
@@ -555,15 +557,18 @@ class TestMarkKnowledgeIsOnTheRow:
if mark.label_regime == "tc260" and mark.key != "jimeng_pill":
assert "aigc" in mark.provenance_signals, mark.key
def test_only_gemini_claims_platform_tokens(self):
def test_platform_token_marks_are_the_c2pa_attributed_ones(self):
# Gemini (Google C2PA) and Microsoft (issuer "Microsoft") are the marks whose
# vendor a C2PA platform string can confirm; every other mark reaches its
# provenance through TC260 codes or product signals instead.
by_token = {m.key for m in reg.known_marks() if m.provenance_platform_tokens}
assert by_token == {"gemini"}
assert by_token == {"gemini", "microsoft"}
class TestPillSuppressors:
"""The pill veto is derived from the registry, not hand-listed.
The hand-written list drifted: LibLibAI was registered in the same commit as
The hand-written list drifted: LiblibAI was registered in the same commit as
RunningHub and Baidu, both of which were added to the veto, and it was not. A
derived set cannot be forgotten by the next registration.
"""
@@ -581,7 +586,7 @@ class TestPillSuppressors:
assert not reg._keep_pill({"liblib"}, provenance=frozenset({"jimeng"}), footprint_flat=1.0)
def test_pill_dropped_on_liblib_even_with_the_jimeng_wordmark(self):
"""The veto precedes the wordmark arm, so a co-firing LibLibAI wins.
"""The veto precedes the wordmark arm, so a co-firing LiblibAI wins.
This is the broader half of the change: it needs neither TC260 provenance nor
a flat footprint, so it is reachable on more inputs than the metadata arm.
@@ -589,7 +594,7 @@ class TestPillSuppressors:
assert not reg._keep_pill({"liblib", "jimeng"}, provenance=frozenset(), footprint_flat=1.0)
def test_pill_survives_gemini_and_samsung(self):
"""Neither is a TC260 labeller, and neither can put "jimeng" into provenance,
"""Neither is a TC260 labeler, and neither can put "jimeng" into provenance,
so neither may veto the arm it could not have enabled."""
assert reg._keep_pill({"gemini", "jimeng"}, provenance=frozenset(), footprint_flat=1.0)
assert reg._keep_pill({"samsung", "jimeng"}, provenance=frozenset(), footprint_flat=1.0)
@@ -632,4 +637,4 @@ class TestProvenanceMaskThreading:
)
monkeypatch.setattr(eng, "footprint_mask", lambda image, *, force=False, region=None, dilate=None: None)
_, removed = reg.remove_auto_marks(np.zeros((256, 256, 3), np.uint8), sensitivity="strict", backend="cv2")
assert "Google Gemini sparkle" not in removed
assert "Google Gemini visible watermark (sparkle)" not in removed
Generated
+1 -1
View File
@@ -3169,7 +3169,7 @@ wheels = [
[[package]]
name = "remove-ai-watermarks"
version = "0.32.1"
version = "0.34.0"
source = { editable = "." }
dependencies = [
{ name = "c2pa-python" },