diff --git a/docs/benchmark-kernel.md b/docs/benchmark-kernel.md index 06aaee9..71a3804 100644 --- a/docs/benchmark-kernel.md +++ b/docs/benchmark-kernel.md @@ -41,7 +41,7 @@ The fixed fields are: | `case_id` | Unique case identity. | | `pair_id` | Groups related clean, marked, attacked, and removed cases. | | `media_type` | `image`, `audio`, or `video` in schema v1. | -| `adapter` | `dwt-dct`, `trustmark`, or `pixelseal` for `image`; `audioseal` or `perth` for `audio`; `videoseal` for `video`. The loader rejects a known adapter named against the wrong media type. | +| `adapter` | `dwt-dct`, `trustmark`, `trustmark-q`, `trustmark-c`, `pixelseal`, `videoseal-image`, `perth`, or `treering` for `image`; `audioseal` or `perth` for `audio`; `videoseal` for `video`. The loader rejects a known adapter named against the wrong media type. | | `arm` | `positive`, `matched_negative`, `wrong_key`, or `hard_negative`. | | `state` | `clean`, `marked`, `attacked`, `removed`, or `forged`. `forged` names an artifact carrying a watermark with a message different from the adapter oracle's fixed one. Expected detection depends on the adapter: PixelSeal and VideoSeal check the fixed message, while AudioSeal's presence rule can still report `detected` for a foreign message. Perth has an implicit fixed mark and no message payload, so it has no meaningful forged arm. The study records message accuracy separately where the scheme exposes a message. | | `path`, `sha256` | Artifact path and pinned content digest. | @@ -216,11 +216,118 @@ and cleaned audio scored 1.000, and the source and output packet streams share `sha256:d6be870baea63ef8dceea97b2c04b27a1a35ba3bd1500cd022ccb167fd0795c6`. This directly confirms that the current video pipeline does not affect Perth. -PixelSeal removal was not run on this Apple Silicon host. The applicable -`qwen-zimage`, `sdxl-zimage`, and `chroma-zimage` invisible-removal profiles -require an NVIDIA CUDA device; MPS is not a supported execution path. The -missing removed-state rows are therefore an explicit hardware gap, not a clean -or failed result. +PixelSeal removal was not run in the initial Apple Silicon baseline because +`qwen-zimage`, `sdxl-zimage`, and `chroma-zimage` require an NVIDIA CUDA +device (`mps` is unsupported). `scripts/perth_pixelseal_study.py` now emits +both `pixelseal` and `videoseal-image` image sets, including `resize-75` and +`crop-5` geometric attacks alongside `jpeg-q90`, and automatically populates +the `qwen-zimage`, `sdxl-zimage`, and `chroma-zimage` `removed`-state rows when +run on a CUDA host with the invisible removal engine installed. + +### Modal H100 diffusion-removal evaluation, 2026-11-08 + +A 210-case CUDA evaluation on `NVIDIA H100 80GB HBM3` (Modal) scored both +`pixelseal` (`com.aiwatermark.pixelseal.1`) and `videoseal-image` +(`me.reconize.videoseal.1`, `y_256b_img.jit` with `is_video=False`) across the +two 512x512 engine-selection study carriers (`openai/00.png` and +`meta/00.png`), the three 512x512 synthetic cohort carriers (`texture`, +`gradient`, `low-detail`), all three production invisible-removal profiles at +their default settings (`qwen-zimage` at resolution-adaptive `s=0.084`, +`sdxl-zimage` at `s=0.50`, and `chroma-zimage` at `s=0.50`), and a 7-rung +strength ladder (`s = 0.03, 0.05, 0.084, 0.10, 0.12, 0.25, 0.50`) on the two +study carriers. The local evaluation archive in +`.local-eval/pixelseal-videoseal-modal-2026-11-08/` has manifest +`sha256:f51425edea3402de15318e870b04911944181a16a5e68fc33af97c6cdce66eb4` and +results +`sha256:49c72ecfaa6a8a726057a7728b6a836261e4a96052823e67e717c99148ff7a7c`. + +| Adapter, cohort, and state | Cases | Detected | Not detected | Bit accuracy | PSNR (dB) | +| --- | ---: | ---: | ---: | --- | --- | +| PixelSeal study (`openai-00`, `meta-00`) clean | 2 | 0 | 2 | 0.473-0.504 | - | +| PixelSeal study marked | 2 | 2 | 0 | 1.000 on both | 46.15-49.46 | +| PixelSeal study `jpeg-q90` / `resize-75` / `crop-5` | 6 | 6 | 0 | 0.996-1.000 | 15.51-40.05 | +| PixelSeal study `forged` (seed 8) | 2 | 0 | 2 | 0.469-0.473 | 46.20-49.54 | +| PixelSeal study `removed-qwen-zimage` (`s=0.084`) | 2 | 0 | 2 | 0.523-0.539 | 22.31-28.56 | +| PixelSeal study `removed-sdxl-zimage` (`s=0.50`) | 2 | 0 | 2 | 0.488 on both | 18.11-21.68 | +| PixelSeal study `removed-chroma-zimage` (`s=0.50`) | 2 | 0 | 2 | 0.484-0.504 | 18.13-22.69 | +| VideoSeal-Image study (`openai-00`, `meta-00`) clean | 2 | 0 | 2 | 0.500-0.551 | - | +| VideoSeal-Image study marked | 2 | 2 | 0 | 1.000 on both | 43.57-47.06 | +| VideoSeal-Image study `jpeg-q90` / `resize-75` / `crop-5` | 6 | 6 | 0 | 0.996-1.000 | 15.51-39.69 | +| VideoSeal-Image study `forged` (seed 8) | 2 | 0 | 2 | 0.469 on both | 43.62-47.26 | +| VideoSeal-Image study `removed-qwen-zimage` (`s=0.084`) | 2 | 0 | 2 | 0.512-0.535 | 22.30-28.56 | +| VideoSeal-Image study `removed-sdxl-zimage` (`s=0.50`) | 2 | 0 | 2 | 0.508-0.531 | 18.06-21.39 | +| VideoSeal-Image study `removed-chroma-zimage` (`s=0.50`) | 2 | 0 | 2 | 0.500-0.523 | 18.15-22.72 | +| PixelSeal synthetic (`texture`, `gradient`, `low-detail`) marked | 3 | 3 | 0 | 0.996-1.000 | 42.19-57.16 | +| PixelSeal synthetic `jpeg-q90` / `resize-75` / `crop-5` | 9 | 9 | 0 | 0.902-1.000 | 24.42-56.01 | +| PixelSeal synthetic `removed` (`qwen`/`sdxl`/`chroma`) | 9 | 0 | 9 | 0.426-0.535 | 17.56-35.51 | +| VideoSeal-Image synthetic (`texture`, `gradient`, `low-detail`) marked | 3 | 2 | 1 | 1.000, 0.918, 0.891 (`low-detail`) | 39.73-57.74 | +| VideoSeal-Image synthetic `removed` (`qwen`/`sdxl`/`chroma`) | 9 | 0 | 9 | 0.508-0.562 | 17.58-35.24 | + +On both `pixelseal` and `videoseal-image`, all three default invisible-removal +profiles (`qwen-zimage`, `sdxl-zimage`, and `chroma-zimage`) scored `0/2` +detected on the study carriers and `0/3` detected on the synthetic carriers, +driving 256-bit message accuracy from `1.000` down to random chance +(`0.484-0.539` on the study carriers). On the near-flat `low-detail` synthetic +carrier, VideoSeal's JND attenuation embedded at `57.74 dB` PSNR (`mae_8bit` +`0.10`), leaving the unattacked `marked` bit accuracy at `0.891` (`228/256` +bits, two bits shy of the `0.90` gate), whereas PixelSeal reached `0.996` at +`57.16 dB` PSNR on the same carrier. + +The strength-ladder sweep on the two study carriers shows why ultra-low +diffusion strengths (`s <= 0.05`) are insufficient even when they drop below the +`0.90` matched-message threshold: + +| Strength `s` | PixelSeal `qwen-zimage` acc | PixelSeal `sdxl-zimage` acc | PixelSeal `chroma-zimage` acc | VideoSeal-Image `qwen-zimage` acc | VideoSeal-Image `sdxl-zimage` acc | VideoSeal-Image `chroma-zimage` acc | +| ---: | --- | --- | --- | --- | --- | --- | +| `0.030` | 0.625-0.656 | 0.488-0.527 | 0.535-0.855 | 0.691-0.727 | 0.590-0.652 | 0.832-0.879 | +| `0.050` | 0.496-0.602 | 0.484-0.504 | 0.484-0.762 | 0.523-0.594 | 0.508-0.578 | 0.684-0.770 | +| `0.084` | 0.523-0.539 | 0.465-0.488 | 0.531-0.547 | 0.512-0.535 | 0.473-0.492 | 0.480-0.520 | +| `0.100` | 0.516 on both | 0.453-0.516 | 0.473-0.508 | 0.520-0.531 | 0.508-0.512 | 0.477-0.555 | +| `0.120` | 0.484-0.547 | 0.496-0.508 | 0.461-0.504 | 0.523-0.559 | 0.512-0.547 | 0.496-0.516 | +| `0.250` | 0.496-0.531 | 0.469-0.539 | 0.477-0.531 | 0.492-0.500 | 0.500-0.512 | 0.484-0.520 | +| `0.500` | 0.484-0.535 | 0.488 on both | 0.484-0.504 | 0.527-0.539 | 0.508-0.531 | 0.500-0.523 | + +At `s = 0.03` and `s = 0.05`, `chroma-zimage` retains `0.684-0.879` bit +accuracy and `qwen-zimage` retains `0.594-0.727`. From `s = 0.084` (the +512x512 resolution-adaptive default of `qwen-zimage`) and `s = 0.100` +(`QWEN_ZIMAGE_META_STRENGTH`, used when C2PA declares `com.aiwatermark.pixelseal.*` +or `me.reconize.videoseal.*`) upward, all three pipelines collapse both +`PixelSeal` and `VideoSeal Image` to the `~0.50` chance baseline (`0.453-0.555` +bit accuracy), while `qwen-zimage` preserves `28.56 dB` PSNR on `openai-00` and +`22.30-22.31 dB` PSNR on `meta-00` (`s=0.084`). + +### Amazon Bedrock (`Nova Canvas` and `Titan Image Generator`) oracle study, 2026-11-08 + +Six MIT-0-cleared carriers from `aws-samples/amazon-nova-samples@ad2fe2074cbc260b9f1dbcec94a4ec3561c1159a` +(three `Nova Canvas Core Model` images: `dog.png` 1280x720, `kites_and_plane.png` +1024x1024, `phone-001.png` 1280x720; three `Titan Image Generator Core Model` +images: `ron_ft_1.png` 1024x1024, `smila_ft_1.png` 1024x1024, `ron_ft_2.png` +768x768) were processed on Modal (`NVIDIA H100 80GB HBM3`) and verified against +the AWS Bedrock Watermark detection oracle +(`POST https://bedrock-runtime.us-east-1.amazonaws.com/detect-generated-content`, +archived locally in `.local-eval/bedrock-nova-study-2026-11-08/`): + +| Model family and state | Cases | `GENERATED` | `NOT_GENERATED` | Confidence / PSNR (dB) | +| --- | ---: | ---: | ---: | --- | +| Nova Canvas original & lossless `stripped` | 6 | 6 | 0 | `HIGH` on all 6 | +| Titan Image original & lossless `stripped` | 6 | 6 | 0 | `HIGH` on all 6 | +| Nova Canvas `jpeg-q90` / `resize-75` / `crop-5` | 9 | 0 | 9 | all 9 cleared without diffusion | +| Titan Image `jpeg-q90` | 3 | 2 | 1 | `MEDIUM` on `ron_ft_1`, `smila_ft_1`; `NOT_GENERATED` on `ron_ft_2` | +| Titan Image `resize-75` | 3 | 1 | 2 | `HIGH` on `ron_ft_2`; `NOT_GENERATED` on `ron_ft_1`, `smila_ft_1` | +| Titan Image `crop-5` | 3 | 2 | 1 | `MEDIUM` on `ron_ft_1`, `ron_ft_2`; `NOT_GENERATED` on `smila_ft_1` | +| Nova + Titan `removed` (`qwen-zimage` default `0.090-0.099`) | 6 | 0 | 6 | mean `24.45 dB` (`19.56-29.43 dB`) | +| Nova + Titan `removed` (`sdxl-zimage` default `0.50`) | 6 | 0 | 6 | mean `21.57 dB` (`17.88-24.30 dB`) | +| Nova + Titan `removed` (`chroma-zimage` default `0.50`) | 6 | 0 | 6 | mean `20.55 dB` (`17.62-24.97 dB`) | +| Nova + Titan `qwen-zimage` `s = 0.030` | 6 | 0 | 6 | mean `28.02 dB` (`21.92-33.65 dB`) | +| Nova + Titan `qwen-zimage` `s = 0.050` | 6 | 0 | 6 | mean `26.58 dB` (`20.91-31.96 dB`) | +| Nova (`kites`) + Titan (`ron_ft_1`) `sdxl-zimage` `s = 0.050` | 2 | 0 | 2 | mean `23.57 dB` (`20.14-27.00 dB`) | +| Nova (`kites`) + Titan (`ron_ft_1`) `chroma-zimage` `s = 0.050` | 2 | 0 | 2 | mean `26.85 dB` (`22.92-30.79 dB`) | + +Because even `s = 0.030` (`qwen-zimage`) and `s = 0.050` (`sdxl-zimage`, +`chroma-zimage`) clear both `Nova Canvas Core Model` and `Titan Image Generator +Core Model` (`0/16` detected), the resolution-adaptive `qwen-zimage` default +(`0.090-0.099` on 768x768-1024x1024) has a `3x` safety margin and needs no +separate vendor strength override in `watermark_profiles.py`. ## Audio cohort v1 diff --git a/docs/known-limitations.md b/docs/known-limitations.md index 4be4bfa..80a5cbc 100644 --- a/docs/known-limitations.md +++ b/docs/known-limitations.md @@ -141,6 +141,13 @@ signal, and has no external detector that recognizes the positive control. The supported claim is therefore local payload invalidation, not certified removal by Microsoft. +Adobe TrustMark also has a direct neural removal path in +`trustmark_detector.remove_trustmark` (`trustmark` extra) using the upstream +variant-matched removal network (`P`, `Q`, or `C`). It writes atomically only +after the re-encoded output no longer passes the durable re-encode gate for that +variant. Like the local Paint path, it is an explicit library helper rather than +the default `invisible` diffusion pipeline. + Text, tables, and UI screenshots are the worst case for a forced scrub: the model redraws glyphs as plausible-but-wrong shapes. Do not run the invisible stage on such content unless a locally-detectable invisible signal exists. @@ -666,7 +673,10 @@ and transformations. A negative result is not a universal negative. The `trustmark` extra adds Adobe TrustMark decoding. The implementation retains an additional JPEG re-encode gate and requires the binary payload and schema to 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 +It accepts schemas 0-2 across Variants P, Q, and C (`identify` scans Variant P +by default and adds Variant Q or C when C2PA declares `com.adobe.trustmark.Q` or +`com.adobe.trustmark.C`, while direct API callers can pass +`variant="P" | "Q" | "C"` to `detect_trustmark` and `remove_trustmark`), and schema 3 is rejected at the measured precision threshold. The extra requires `trustmark>=0.9.2`, which supports NumPy 2 and Python 3.13-3.14. The current TrustMark dependency line resolves `lightning` and `pytorch-lightning` 2.6.6, which contain the published fixes diff --git a/docs/module-internals.md b/docs/module-internals.md index e0224e3..a765ffb 100644 --- a/docs/module-internals.md +++ b/docs/module-internals.md @@ -730,11 +730,21 @@ pixel-watermark identifier in Microsoft Paint output. An InvisMark soft binding keeps the invisible-removal gate fail-safe even when the C2PA asset binding has since become invalid, because metadata damage does not prove the pixel carrier disappeared. `identify` retains the generic `soft_binding` signal for schema-1 -compatibility and adds `invismark` as the stable pixel-removal signal. +compatibility and adds `invismark` as the stable pixel-removal signal across +the reader, portable-record, and raw-byte fallback paths. When the C2PA manifest +is structurally usable, `invismark` also asserts AI provenance and sets the +`"Microsoft (Copilot / Designer)"` fallback platform; in integrity-clash checks +it shares `_C2PA_MANIFEST_SOURCE` with `c2pa` and `soft_binding` so multi-actor +Microsoft + OpenAI manifests do not self-clash. `vendor_for_strength` includes +non-reader fallback containers carrying `com.microsoft.invismark.1` when +selecting the `"microsoft"` floor. Registry entries of type `fingerprint` remain durable-provenance signals but are not added to the watermark inventory, do not trigger pixel regeneration, and do not suppress independently established SynthID watermark evidence. A registered -watermark or an unknown soft-binding algorithm keeps that inference fail-safe. +watermark or an unknown soft-binding algorithm keeps that inference fail-safe, +and `c2pa_info_has_removal_hint` plus `identify.report_has_removal_hint` keep +`c2pa_identity_ai` and fallback `invismark`/`soft_binding` signals fail-safe for +invisible removal even when the C2PA signature or hard binding is invalid. The local Paint reader treats C2PA as corroboration, not as the pixel detector. It extracts 4-by-4 blocks from the luminance Haar LL plane, reads the largest @@ -1571,8 +1581,13 @@ AI-enhanced composites when the source metadata provides that distinction. TrustMark is reported as a watermark signal but does not by itself assert AI origin because it can also protect human-authored content. The decoder requests binary mode, matching Adobe's Durable Content Credentials example, then requires -the same payload and schema after a quality-95 JPEG round-trip. Only Variant P -schemas 0-2 count as positives. Schema 3 is below the precision threshold: all +the same payload and schema after a quality-95 JPEG round-trip. Uncorroborated +`identify` scans run Variant P only and accept schemas 0-2; when C2PA soft +bindings declare `com.adobe.trustmark.Q` or `com.adobe.trustmark.C`, `identify` +also checks that declared variant under the same re-encode and schema 0-2 gate. +Direct API callers can pass `variant="P" | "Q" | "C"` to `detect_trustmark`, +`detect_trustmark_image`, `detect_trustmark_detailed`, and `remove_trustmark`. +Schema 3 is below the precision threshold: all 38 measured historical false-positive candidates used it, and six retained the same false payload after re-encoding. The official Adobe Variant P schema-1 fixture in `data/fixtures/provenance/` is the positive regression control. diff --git a/docs/python-api.md b/docs/python-api.md index 8d1f9ae..5e19359 100644 --- a/docs/python-api.md +++ b/docs/python-api.md @@ -202,6 +202,23 @@ The direct call needs the `pixels` extra. It writes atomically only after the encoded output no longer decodes as a valid local payload. The result does not claim acceptance by a proprietary Microsoft detector. +Callers with the `trustmark` extra can similarly inspect or apply Adobe +TrustMark's variant-matched neural remover (`"P"`, `"Q"`, or `"C"`) directly: + +```python +from remove_ai_watermarks.trustmark_detector import ( + detect_trustmark_detailed, + remove_trustmark, +) + +detection = detect_trustmark_detailed("adobe.jpg", variant="P") +if detection is not None: + removed = remove_trustmark("adobe.jpg", "clean.jpg", variant=detection.variant) +``` + +`remove_trustmark` writes atomically only when the input passes the durable +re-encode gate for `variant` and the written file no longer passes that gate. + The complete field set, with the shipped defaults: | Field | Default | Effect | diff --git a/docs/supported-signals.md b/docs/supported-signals.md index 79884f2..75585d8 100644 --- a/docs/supported-signals.md +++ b/docs/supported-signals.md @@ -121,9 +121,11 @@ The inspection and stripping code handles signals in these groups: - Samsung AI editing markers; - Higgsfield job metadata (the `hf-job-id` PNG chunk); - open Stable Diffusion style DWT-DCT watermarks with the `detect` extra; -- Adobe TrustMark Variant P schemas 0-2 with the `trustmark` extra. Variant Q - needs a different model, while schema 3 is deliberately rejected because it - produced persistent false positives on unrelated generators. +- Adobe TrustMark Variant P schemas 0-2 by default with the `trustmark` extra, + plus Variants Q (`com.adobe.trustmark.Q`) and C (`com.adobe.trustmark.C`) when + explicitly requested or corroborated by a C2PA soft-binding assertion. Schema + 3 is deliberately rejected because it produced persistent false positives on + unrelated generators. `identify` combines detected signals into a `ProvenanceReport`. It reports unknown when evidence is absent. It never treats missing metadata as proof that @@ -176,9 +178,10 @@ use their format specific paths. ## Invisible watermarks -The `invisible` command uses diffusion regeneration. A specialized Python API can +The `invisible` command uses diffusion regeneration. Specialized Python APIs can instead apply decoder-guided disruption to a positively identified local -Microsoft Paint payload. +Microsoft Paint payload or official neural removal to a confirmed Adobe +TrustMark payload. Current diffusion pipeline values, all CUDA-only: @@ -276,6 +279,26 @@ The seal survives resizing, JPEG recompression, and metadata stripping; it dies to center crops of a third to a half, matching the Reuters 2026-07-11 finding that Meta's detector missed 55% of cropped Muse images. +Amazon Bedrock (`Nova Canvas Core Model` and `Titan Image Generator Core Model`) +embeds a proprietary invisible pixel watermark verified through the Bedrock +Watermark detection console and `POST /detect-generated-content` +(`DetectGeneratedContent`). A 2026-11-08 evaluation on six MIT-0-cleared +carriers from `aws-samples/amazon-nova-samples` (three Nova Canvas images at +1280x720 and 1024x1024 with C2PA signed `Amazon Web Services, Inc.`, and three +Titan Image Generator images at 1024x1024 and 768x768) confirmed that lossless +metadata stripping leaves `6/6` detected at `HIGH` confidence (`3/3 Nova Canvas +Core Model`, `3/3 Titan Image Generator Core Model`). Non-diffusion attacks +already clear Nova Canvas (`0/3` on `jpeg-q90`, `resize-75`, and `crop-5`), +while Titan Image partially survives (`2/3` `MEDIUM` on `jpeg-q90`, `1/3` +`HIGH` on `resize-75`, `2/3` `MEDIUM` on `crop-5`). Diffusion regeneration on +Modal (`NVIDIA H100 80GB HBM3`) cleared `6/6` across all three default profiles +(`qwen-zimage` at resolution-adaptive `0.090-0.099`, `sdxl-zimage` at `0.50`, +and `chroma-zimage` at `0.50`: `0/18` detected) and already cleared `6/6` on +`qwen-zimage` at `s = 0.03` and `s = 0.05` (`0/12` detected) as well as on +`sdxl-zimage` and `chroma-zimage` at `s = 0.05`, so the standard +resolution-adaptive `qwen-zimage` default (`0.090-0.099`) provides a 3x safety +margin with no separate vendor strength floor needed. + For MP4, MOV, and M4V, `video invisible` or the explicit `video all --invisible` option can regenerate the video through a VAE and strip source metadata. The shipped profile is oracle-certified, but it is not a local @@ -302,7 +325,7 @@ not a universal clean verdict. | 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 | +| Adobe Firefly | None registered | Optional TrustMark decoder and neural remover (`P`, `Q`, `C`); diffusion fallback when C2PA declares `com.adobe.trustmark.*` | C2PA | | Midjourney | None registered | No registered pixel decoder | EXIF, XMP, and IPTC signals | | Luma AI | None registered | No registered pixel decoder | PNG text generator tags (Uni-1) | | ByteDance generators | Doubao, Jimeng, Dola, and Seedance marks | No registered pixel decoder | TC260 AIGC (Doubao, Jimeng, Volcano Engine), supported C2PA (Dreamina, Dola, Pippit AI, BytePlus), and exact app-export AIGC disclosures | @@ -313,7 +336,7 @@ not a universal clean verdict. | Kling AI | Kling AI image and video marks | No registered pixel decoder | TC260 AIGC and the video SEI tag | | Vidu (ShengShu) | Vidu video mark | No registered pixel decoder | TC260 AIGC in the MP4 `AIGC` key | | Runway | None measured on paid-plan output | No registered pixel decoder | C2PA signed `RUNWAY AI, INC.` on its own models; third-party models keep their vendor's manifest | -| Amazon Bedrock (Nova Canvas, Nova Reel) | None | Invisible watermark readable only through the Bedrock API | C2PA signed `Amazon Web Services, Inc.`, claim generator `Amazon Bedrock` | +| Amazon Bedrock (Nova Canvas, Titan Image, Nova Reel) | None | Diffusion regeneration for Nova Canvas and Titan Image, oracle-verified against `DetectGeneratedContent` (`0/18` across `qwen-zimage`, `sdxl-zimage`, `chroma-zimage`; already `0/6` at `qwen-zimage` `s=0.03`) | C2PA signed `Amazon Web Services, Inc.`, claim generator `Amazon Bedrock` | | Wan (Alibaba) | Wan image mark | No registered pixel decoder | TC260 AIGC in XMP | | 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 | diff --git a/docs/verification-plan.md b/docs/verification-plan.md index 87ca6fe..5898e53 100644 --- a/docs/verification-plan.md +++ b/docs/verification-plan.md @@ -455,8 +455,9 @@ audio-path attacks separately. Its carriers are synthetic non-speech audio and its oracle is AudioSeal, so it validates the copy semantics, not provider audio marks. The audio and video arms are now first-class benchmark rows: [benchmark kernel](benchmark-kernel.md) accepts `media_type: audio` and -`media_type: video` with the revision-pinned `audioseal`, `perth`, and -`videoseal` adapters, plus the `pixelseal` image adapter. The Perth and +`media_type: video` with the revision-pinned `audioseal`, `perth`, and `videoseal` adapters, plus +the `pixelseal`, `videoseal-image`, `perth`, `treering`, `trustmark-q`, and +`trustmark-c` image adapters. The Perth and PixelSeal study records matched negatives, marked rows, attacks, fixed-message accuracy, and the copied-audio path as strict manifest cases. The temporal layer is closed too: videoseal detection records carry per-frame bit accuracy, diff --git a/scripts/perth_pixelseal_study.py b/scripts/perth_pixelseal_study.py index 7e030b6..cbf407c 100755 --- a/scripts/perth_pixelseal_study.py +++ b/scripts/perth_pixelseal_study.py @@ -28,6 +28,7 @@ sys.path.insert(0, str(REPO / "scripts")) import perth_oracle # noqa: E402 import pixelseal_oracle # noqa: E402 +import videoseal_oracle # noqa: E402 from audioseal_experiment import ( # noqa: E402 FRAME_COUNT, SPEECH_VOICES, @@ -47,6 +48,7 @@ from audioseal_experiment import ( # noqa: E402 wav_pcm16_bytes, ) from watermark_benchmark import SCHEMA_VERSION, run_benchmark, sha256_file, write_jsonl # noqa: E402 +from watermark_benchmark_cohort import attack_image, attack_parameters # noqa: E402 from remove_ai_watermarks.video import remove_video_visible # noqa: E402 @@ -54,6 +56,7 @@ log = logging.getLogger("perth_pixelseal_study") RECIPE_VERSION = "perth-pixelseal-study-v2" IMAGE_SIZE = 512 +REMOVAL_PROFILES: tuple[str, ...] = ("qwen-zimage", "sdxl-zimage", "chroma-zimage") IMAGE_CARRIERS: tuple[Path, ...] = ( REPO / "data/evaluations/engine-selection/originals/openai/00.png", REPO / "data/evaluations/engine-selection/originals/meta/00.png", @@ -103,47 +106,74 @@ def _row( } -def _save_rgb(path: Path, values: np.ndarray) -> None: +def _save_rgb(path: Path, values: np.ndarray) -> Image.Image: pixels = np.rint(np.clip(values, 0.0, 1.0) * 255.0).astype(np.uint8) - Image.fromarray(pixels, "RGB").save(path) + image = Image.fromarray(pixels, "RGB") + image.save(path) + return image -def _build_pixelseal_rows(output_dir: Path, artifacts: Path) -> list[dict[str, object]]: - if not pixelseal_oracle.available(): - failure = pixelseal_oracle.import_failure() - raise SystemExit(f"PixelSeal development stack is unavailable: {failure}") - model = pixelseal_oracle.load_model() - fixed = pixelseal_oracle.message_bits() - foreign = pixelseal_oracle.message_bits(seed=8) - pins = { - "source_commit": pixelseal_oracle.SOURCE_COMMIT, - "checkpoint_sha256": pixelseal_oracle.CHECKPOINT_SHA256, - "model_card_sha256": pixelseal_oracle.MODEL_CARD_SHA256, - "message": list(fixed), - } +def _invisible_engine_available() -> bool: + from remove_ai_watermarks.invisible_engine import is_available + + return is_available() + + +def _run_pixelseal_removal_profile(profile: str, source_path: Path, output_path: Path) -> None: + from remove_ai_watermarks.invisible_engine import InvisibleEngine + + engine = InvisibleEngine(pipeline=profile) + engine.remove_watermark(image_path=source_path, output_path=output_path) + + +def _build_image_seal_rows( + output_dir: Path, + artifacts: Path, + *, + adapter: str, + stack_label: str, + oracle: object, + embed_fn: object, + pins: dict[str, object], +) -> tuple[list[dict[str, object]], dict[str, object]]: + if not oracle.available(): # type: ignore[attr-defined] + failure = oracle.import_failure() # type: ignore[attr-defined] + raise SystemExit(f"{stack_label} development stack is unavailable: {failure}") + model = oracle.load_model() # type: ignore[attr-defined] + fixed = oracle.message_bits() # type: ignore[attr-defined] + foreign = oracle.message_bits(seed=8) # type: ignore[attr-defined] + source_commit = str(oracle.SOURCE_COMMIT) # type: ignore[attr-defined] + message_seed = int(oracle.MESSAGE_SEED) # type: ignore[attr-defined] + full_pins = {**pins, "message": list(fixed)} rows: list[dict[str, object]] = [] source_manifest = REPO / "data/evaluations/engine-selection/carrier-manifest.csv" source_revision = f"engine-selection@sha256:{sha256_file(source_manifest)}" + marked_pairs: list[tuple[str, Path, Path]] = [] for source in IMAGE_CARRIERS: provider = source.parent.name - pair_id = f"pixelseal-{provider}-00" + pair_id = f"{adapter}-{provider}-00" clean_path = artifacts / f"{pair_id}-clean.png" clean = Image.open(source).convert("RGB").resize((IMAGE_SIZE, IMAGE_SIZE), Image.Resampling.LANCZOS) clean.save(clean_path) clean_values = np.asarray(clean, dtype=np.float32) / 255.0 marked_path = artifacts / f"{pair_id}-marked.png" - _save_rgb(marked_path, np.asarray(pixelseal_oracle.embed(model, clean_values, fixed))) + marked_image = _save_rgb(marked_path, np.asarray(embed_fn(model, clean_values, fixed))) # type: ignore[operator] attacked_path = artifacts / f"{pair_id}-jpeg-q90.jpg" - Image.open(marked_path).save(attacked_path, quality=90, subsampling=0) + marked_image.save(attacked_path, quality=90, subsampling=0) + resize_path = artifacts / f"{pair_id}-resize-75.png" + attack_image(marked_image, "resize-75").save(resize_path) + crop_path = artifacts / f"{pair_id}-crop-5.png" + attack_image(marked_image, "crop-5").save(crop_path) forged_path = artifacts / f"{pair_id}-forged.png" - _save_rgb(forged_path, np.asarray(pixelseal_oracle.embed(model, clean_values, foreign))) + _save_rgb(forged_path, np.asarray(embed_fn(model, clean_values, foreign))) # type: ignore[operator] + marked_pairs.append((pair_id, clean_path, marked_path)) common = { "root": output_dir, "pair_id": pair_id, "media_type": "image", - "adapter": "pixelseal", + "adapter": adapter, "source_revision": source_revision, } rows.extend( @@ -168,10 +198,10 @@ def _build_pixelseal_rows(output_dir: Path, artifacts: Path) -> list[dict[str, o state="marked", path=marked_path, reference=clean_path, - transform_name="pixelseal-embed", - transform_revision=f"videoseal@{pixelseal_oracle.SOURCE_COMMIT}", - parameters=pins, - seed=pixelseal_oracle.MESSAGE_SEED, + transform_name=f"{adapter}-embed", + transform_revision=f"videoseal@{source_commit}", + parameters=full_pins, + seed=message_seed, expected="detected", ), _row( @@ -183,7 +213,33 @@ def _build_pixelseal_rows(output_dir: Path, artifacts: Path) -> list[dict[str, o reference=clean_path, transform_name="jpeg", transform_revision="pillow", - parameters={"quality": 90, "subsampling": 0, **pins}, + parameters={**attack_parameters("jpeg-q90"), **full_pins}, + seed=None, + expected="unresolved", + ), + _row( + **common, + case_id=f"{pair_id}-resize-75", + arm="positive", + state="attacked", + path=resize_path, + reference=clean_path, + transform_name="resize-75", + transform_revision="pillow", + parameters={**attack_parameters("resize-75"), **full_pins}, + seed=None, + expected="unresolved", + ), + _row( + **common, + case_id=f"{pair_id}-crop-5", + arm="positive", + state="attacked", + path=crop_path, + reference=clean_path, + transform_name="crop-5", + transform_revision="pillow", + parameters={**attack_parameters("crop-5"), **full_pins}, seed=None, expected="unresolved", ), @@ -194,9 +250,9 @@ def _build_pixelseal_rows(output_dir: Path, artifacts: Path) -> list[dict[str, o state="forged", path=forged_path, reference=clean_path, - transform_name="pixelseal-embed-foreign-message", - transform_revision=f"videoseal@{pixelseal_oracle.SOURCE_COMMIT}", - parameters={**pins, "foreign_message": list(foreign), "foreign_message_seed": 8}, + transform_name=f"{adapter}-embed-foreign-message", + transform_revision=f"videoseal@{source_commit}", + parameters={**full_pins, "foreign_message": list(foreign), "foreign_message_seed": 8}, seed=8, expected="not_detected", ), @@ -204,7 +260,79 @@ def _build_pixelseal_rows(output_dir: Path, artifacts: Path) -> list[dict[str, o ) del model gc.collect() - return rows + + if not _cuda_available(): + removal_summary: dict[str, object] = { + "status": "not_run", + "reason": "qwen-zimage, sdxl-zimage, and chroma-zimage require an NVIDIA CUDA device", + "profiles": [], + } + elif not _invisible_engine_available(): + removal_summary = { + "status": "not_run", + "reason": "invisible removal dependencies are not installed", + "profiles": [], + } + else: + for profile in REMOVAL_PROFILES: + for pair_id, clean_path, marked_path in marked_pairs: + removed_path = artifacts / f"{pair_id}-removed-{profile}.png" + _run_pixelseal_removal_profile(profile, marked_path, removed_path) + rows.append( + _row( + root=output_dir, + pair_id=pair_id, + media_type="image", + adapter=adapter, + source_revision=source_revision, + case_id=f"{pair_id}-removed-{profile}", + arm="positive", + state="removed", + path=removed_path, + reference=clean_path, + transform_name=f"remove-invisible-{profile}", + transform_revision=RECIPE_VERSION, + parameters={"profile": profile, **full_pins}, + seed=0, + expected="unresolved", + ) + ) + removal_summary = { + "status": "executed", + "profiles": list(REMOVAL_PROFILES), + } + return rows, removal_summary + + +def _build_pixelseal_rows(output_dir: Path, artifacts: Path) -> tuple[list[dict[str, object]], dict[str, object]]: + return _build_image_seal_rows( + output_dir, + artifacts, + adapter="pixelseal", + stack_label="PixelSeal", + oracle=pixelseal_oracle, + embed_fn=pixelseal_oracle.embed, + pins={ + "source_commit": pixelseal_oracle.SOURCE_COMMIT, + "checkpoint_sha256": pixelseal_oracle.CHECKPOINT_SHA256, + "model_card_sha256": pixelseal_oracle.MODEL_CARD_SHA256, + }, + ) + + +def _build_videoseal_image_rows(output_dir: Path, artifacts: Path) -> tuple[list[dict[str, object]], dict[str, object]]: + return _build_image_seal_rows( + output_dir, + artifacts, + adapter="videoseal-image", + stack_label="VideoSeal", + oracle=videoseal_oracle, + embed_fn=videoseal_oracle.embed_image, + pins={ + "source_commit": videoseal_oracle.SOURCE_COMMIT, + "checkpoint_sha256": videoseal_oracle.JIT_SHA256, + }, + ) def _extract_audio(ffmpeg: str, source: Path, target: Path) -> None: @@ -436,7 +564,9 @@ def build_and_run(output_dir: Path) -> Path: output_dir.mkdir(parents=True) artifacts = output_dir / "artifacts" artifacts.mkdir() - rows = _build_pixelseal_rows(output_dir, artifacts) + rows, removal_summary = _build_pixelseal_rows(output_dir, artifacts) + videoseal_rows, videoseal_removal = _build_videoseal_image_rows(output_dir, artifacts) + rows.extend(videoseal_rows) perth_rows, pass_through = _build_perth_rows(output_dir, artifacts, ffmpeg) rows.extend(perth_rows) manifest = output_dir / "manifest.jsonl" @@ -447,10 +577,12 @@ def build_and_run(output_dir: Path) -> Path: "pixelseal": { "source_commit": pixelseal_oracle.SOURCE_COMMIT, "checkpoint_sha256": pixelseal_oracle.CHECKPOINT_SHA256, - "removal_profiles": { - "status": "not_run" if not _cuda_available() else "available_not_automatic", - "reason": "qwen-zimage, sdxl-zimage, and chroma-zimage require an NVIDIA CUDA device", - }, + "removal_profiles": removal_summary, + }, + "videoseal_image": { + "source_commit": videoseal_oracle.SOURCE_COMMIT, + "checkpoint_sha256": videoseal_oracle.JIT_SHA256, + "removal_profiles": videoseal_removal, }, "perth": { "source_commit": perth_oracle.SOURCE_COMMIT, diff --git a/scripts/videoseal_oracle.py b/scripts/videoseal_oracle.py index 4e242a1..6fdcf69 100644 --- a/scripts/videoseal_oracle.py +++ b/scripts/videoseal_oracle.py @@ -51,12 +51,11 @@ CACHE_DIR = Path( @dataclass(frozen=True) -class VideoSealReading: - """Aggregated decode of one video against the oracle's fixed message.""" +class VideoSealImageReading: + """Decoded bits and matched-message accuracy for one image.""" bit_accuracy: float decoded_bits: tuple[int, ...] - per_frame_bit_accuracy: tuple[float, ...] @property def detected(self) -> bool: @@ -68,6 +67,13 @@ class VideoSealReading: return "".join(f"{byte:02x}" for byte in _bytes(self.decoded_bits)) +@dataclass(frozen=True) +class VideoSealReading(VideoSealImageReading): + """Aggregated decode of one video against the oracle's fixed message.""" + + per_frame_bit_accuracy: tuple[float, ...] + + def _bytes(bits: Sequence[int]) -> bytes: return bytes(sum(bit << (7 - index) for index, bit in enumerate(bits[i : i + 8])) for i in range(0, len(bits), 8)) @@ -144,13 +150,32 @@ def embed(model: object, frames: object, message: Sequence[int]) -> object: return marked.permute(0, 2, 3, 1).numpy() -def embed_image(model: object, pixels: object, message: Sequence[int]) -> object: - """Embed a message into one RGB image in [0, 1] (H, W, 3).""" +def _image_pixels_f32(pixels: object) -> object: + import numpy as np + + array = np.asarray(pixels) + if array.ndim != 3 or array.shape[2] != 3: + raise ValueError(f"VideoSeal image mode expects HxWx3 RGB pixels, got {array.shape}") + values = array.astype(np.float32) / 255.0 if array.dtype == np.uint8 else np.asarray(array, dtype=np.float32) + if not np.isfinite(values).all() or float(values.min()) < 0.0 or float(values.max()) > 1.0: + raise ValueError("VideoSeal image RGB pixels must be finite and in [0, 1]") + return values + + +def _image_tensor(pixels: object) -> object: import numpy as np import torch - array = torch.from_numpy(np.ascontiguousarray(pixels, dtype=np.float32)) - tensor = array.permute(2, 0, 1).unsqueeze(0) + values = _image_pixels_f32(pixels) + array = torch.from_numpy(np.ascontiguousarray(values, dtype=np.float32)) + return array.permute(2, 0, 1).unsqueeze(0) + + +def embed_image(model: object, pixels: object, message: Sequence[int]) -> object: + """Embed a message into one RGB image in [0, 1] (H, W, 3).""" + import torch + + tensor = _image_tensor(pixels) msg = torch.tensor([list(message)], dtype=torch.float32) with torch.no_grad(): marked = model.embed(tensor, msg, is_video=False) @@ -159,11 +184,9 @@ def embed_image(model: object, pixels: object, message: Sequence[int]) -> object def decode_image(model: object, pixels: object) -> tuple[int, ...]: """Decode the message bits from one RGB image.""" - import numpy as np import torch - array = torch.from_numpy(np.ascontiguousarray(pixels, dtype=np.float32)) - tensor = array.permute(2, 0, 1).unsqueeze(0) + tensor = _image_tensor(pixels) with torch.no_grad(): predictions = model.detect(tensor, is_video=False) if isinstance(predictions, dict): @@ -171,6 +194,21 @@ def decode_image(model: object, pixels: object) -> tuple[int, ...]: return tuple(int(bit) for bit in (predictions[:, 1:] > 0).to(torch.int64).view(-1).tolist()) +def read_image( + model: object, + pixels: object, + *, + message: Sequence[int] | None = None, +) -> VideoSealImageReading: + """Decode one image and compare its bits with the oracle's fixed message.""" + expected = message_bits() if message is None else tuple(message) + decoded = decode_image(model, pixels) + if len(decoded) != len(expected): + raise ValueError(f"decoded bit count {len(decoded)} does not match expected {len(expected)}") + accuracy = sum(int(bit == want) for bit, want in zip(decoded, expected, strict=True)) / len(expected) + return VideoSealImageReading(bit_accuracy=accuracy, decoded_bits=decoded) + + def _aggregate_bit_preds(bit_preds: object, aggregation: str) -> object: """Aggregate per-frame bit logits exactly as upstream ``extract_message``. diff --git a/scripts/watermark_benchmark.py b/scripts/watermark_benchmark.py index a9467b5..81f4351 100644 --- a/scripts/watermark_benchmark.py +++ b/scripts/watermark_benchmark.py @@ -73,6 +73,7 @@ ADAPTER_MEDIA: dict[str, Media] = { "dwt-dct": "image", "trustmark": "image", "pixelseal": "image", + "videoseal-image": "image", "audioseal": "audio", "perth": "audio", "videoseal": "video", @@ -212,6 +213,25 @@ class PerthAdapter: ) +def _detect_message_image_oracle( + image: NDArray[Any], + *, + module_name: str, + read_fn: Any, +) -> DetectorOutcome: + import cv2 + + from remove_ai_watermarks.image_io import to_bgr + + rgb = cv2.cvtColor(to_bgr(image), cv2.COLOR_BGR2RGB) + reading = read_fn(_oracle_model(module_name), rgb) + return DetectorOutcome( + status="detected" if reading.detected else "not_detected", + label=reading.label if reading.detected else None, + message_bit_accuracy=reading.bit_accuracy, + ) + + @dataclass(frozen=True) class PixelSealAdapter: """Adapter for PixelSeal's fixed-message image verifier.""" @@ -227,18 +247,29 @@ class PixelSealAdapter: return available() def detect(self, path: Path, image: NDArray[Any]) -> DetectorOutcome: - import cv2 from pixelseal_oracle import read - from remove_ai_watermarks.image_io import to_bgr + return _detect_message_image_oracle(image, module_name="pixelseal_oracle", read_fn=read) - rgb = cv2.cvtColor(to_bgr(image), cv2.COLOR_BGR2RGB) - reading = read(_oracle_model("pixelseal_oracle"), rgb) - return DetectorOutcome( - status="detected" if reading.detected else "not_detected", - label=reading.label if reading.detected else None, - message_bit_accuracy=reading.bit_accuracy, - ) + +@dataclass(frozen=True) +class VideoSealImageAdapter: + """Adapter for VideoSeal's 256-bit image mode (me.reconize.videoseal.1).""" + + name: str + source_file: Path + + @property + def available(self) -> bool: + """Probe the optional stack only when a VideoSeal image row is evaluated.""" + from videoseal_oracle import available + + return available() + + def detect(self, path: Path, image: NDArray[Any]) -> DetectorOutcome: + from videoseal_oracle import read_image + + return _detect_message_image_oracle(image, module_name="videoseal_oracle", read_fn=read_image) def sha256_file(path: Path) -> str: @@ -496,6 +527,10 @@ def default_adapters() -> dict[str, DetectorAdapter]: name="pixelseal", source_file=pixel_oracle_source, ), + "videoseal-image": VideoSealImageAdapter( + name="videoseal-image", + source_file=video_oracle_source, + ), "audioseal": FunctionAdapter( name="audioseal", source_file=audio_oracle_source, diff --git a/scripts/watermark_benchmark_cohort.py b/scripts/watermark_benchmark_cohort.py index 6d1fdec..e2caa93 100755 --- a/scripts/watermark_benchmark_cohort.py +++ b/scripts/watermark_benchmark_cohort.py @@ -41,7 +41,7 @@ from watermark_benchmark import SCHEMA_VERSION, load_manifest, sha256_file, writ log = logging.getLogger(__name__) RECIPE_VERSION = "watermark-benchmark-cohort-v1" -AdapterName = Literal["dwt-dct", "trustmark"] +AdapterName = Literal["dwt-dct", "trustmark", "videoseal-image"] AttackName = Literal["jpeg-q90", "resize-75", "crop-5"] DEFAULT_CARRIERS = ( @@ -54,7 +54,8 @@ DEFAULT_CARRIERS = ( ) DEFAULT_DWT_SCHEMES = ("sdxl", "flux", "sd1") DEFAULT_ATTACKS: tuple[AttackName, ...] = ("jpeg-q90", "resize-75", "crop-5") -_ADAPTERS: tuple[AdapterName, ...] = ("dwt-dct", "trustmark") +DEFAULT_ADAPTERS: tuple[AdapterName, ...] = ("dwt-dct", "trustmark") +_ADAPTERS: tuple[AdapterName, ...] = ("dwt-dct", "trustmark", "videoseal-image") _DWT_SCHEMES = frozenset(DEFAULT_DWT_SCHEMES) _ATTACKS = frozenset(DEFAULT_ATTACKS) @@ -541,10 +542,133 @@ def append_trustmark_rows( ) +def append_videoseal_image_rows( + rows: list[dict[str, Any]], + *, + root: Path, + artifacts: Path, + carriers: Sequence[tuple[CarrierSpec, Image.Image]], + attacks: Sequence[AttackName], + source_revision: str, + dependencies: dict[str, str], + size: int, + carrier_metadata: Mapping[str, Mapping[str, Any]] | None = None, + clean_transform_name: str = "synthetic-carrier", + clean_transform_revision: str = RECIPE_VERSION, + attack_transform_revision: str = RECIPE_VERSION, +) -> None: + """Append matched 256-bit VideoSeal image cases (me.reconize.videoseal.1).""" + import numpy as np + import videoseal_oracle + + model = videoseal_oracle.load_model() + fixed = videoseal_oracle.message_bits() + foreign = videoseal_oracle.message_bits(seed=8) + for spec, clean in carriers: + clean_path = artifacts / f"{spec.name}--{size}px--clean.png" + if not clean_path.exists(): + save_rgb_png(clean, clean_path) + pair_id = f"videoseal-image--{spec.name}--{size}px" + base_parameters: dict[str, Any] = { + "carrier": spec.name, + "size": [size, size], + "dependencies": dependencies, + "source_commit": videoseal_oracle.SOURCE_COMMIT, + "checkpoint_sha256": videoseal_oracle.JIT_SHA256, + "message": list(fixed), + } + if carrier_metadata is not None: + base_parameters["source"] = dict(carrier_metadata[spec.name]) + rows.append( + benchmark_row( + root=root, + case_id=f"{pair_id}--clean", + pair_id=pair_id, + adapter="videoseal-image", + arm="matched_negative", + state="clean", + path=clean_path, + reference=clean_path, + source_revision=source_revision, + transform_name=clean_transform_name, + transform_revision=clean_transform_revision, + parameters=base_parameters, + seed=spec.seed, + expected="not_detected", + ) + ) + clean_values = np.asarray(clean.convert("RGB"), dtype=np.float32) / 255.0 + marked_values = np.asarray(videoseal_oracle.embed_image(model, clean_values, fixed)) + marked = Image.fromarray(np.rint(np.clip(marked_values, 0.0, 1.0) * 255.0).astype(np.uint8), "RGB") + marked_path = save_rgb_png(marked, artifacts / f"{spec.name}--{size}px--videoseal-image--marked.png") + rows.append( + benchmark_row( + root=root, + case_id=f"{pair_id}--marked", + pair_id=pair_id, + adapter="videoseal-image", + arm="positive", + state="marked", + path=marked_path, + reference=clean_path, + source_revision=source_revision, + transform_name="videoseal-image-embed", + transform_revision=f"videoseal@{videoseal_oracle.SOURCE_COMMIT}", + parameters=base_parameters, + seed=videoseal_oracle.MESSAGE_SEED, + expected="detected", + ) + ) + for attack in attacks: + attacked_path = save_rgb_png( + attack_image(marked, attack), + artifacts / f"{spec.name}--{size}px--videoseal-image--{attack}.png", + ) + rows.append( + benchmark_row( + root=root, + case_id=f"{pair_id}--{attack}", + pair_id=pair_id, + adapter="videoseal-image", + arm="positive", + state="attacked", + path=attacked_path, + reference=clean_path, + source_revision=source_revision, + transform_name=f"videoseal-image-embed-then-{attack}", + transform_revision=attack_transform_revision, + parameters=base_parameters | attack_parameters(attack), + seed=videoseal_oracle.MESSAGE_SEED, + expected="unresolved", + ) + ) + forged_values = np.asarray(videoseal_oracle.embed_image(model, clean_values, foreign)) + forged = Image.fromarray(np.rint(np.clip(forged_values, 0.0, 1.0) * 255.0).astype(np.uint8), "RGB") + forged_path = save_rgb_png(forged, artifacts / f"{spec.name}--{size}px--videoseal-image--forged.png") + rows.append( + benchmark_row( + root=root, + case_id=f"{pair_id}--forged", + pair_id=pair_id, + adapter="videoseal-image", + arm="wrong_key", + state="forged", + path=forged_path, + reference=clean_path, + source_revision=source_revision, + transform_name="videoseal-image-embed-foreign-message", + transform_revision=f"videoseal@{videoseal_oracle.SOURCE_COMMIT}", + parameters=base_parameters | {"foreign_message": list(foreign), "foreign_message_seed": 8}, + seed=8, + expected="not_detected", + ) + ) + + def build_cohort( output_dir: Path, *, - adapters: Sequence[AdapterName] = _ADAPTERS, + adapters: Sequence[AdapterName] = DEFAULT_ADAPTERS, carriers: Sequence[CarrierSpec] = tuple(CarrierSpec(name, seed) for name, seed in DEFAULT_CARRIERS), dwt_schemes: Sequence[str] = DEFAULT_DWT_SCHEMES, attacks: Sequence[AttackName] = DEFAULT_ATTACKS, @@ -604,6 +728,26 @@ def build_cohort( dependencies=dependencies, size=size, ) + if "videoseal-image" in adapters: + append_videoseal_image_rows( + rows, + root=output_dir, + artifacts=artifacts, + carriers=carrier_images, + attacks=attacks, + source_revision=source_revision, + dependencies=dependencies, + size=size, + ) + _append_hard_negative( + rows, + root=output_dir, + artifacts=artifacts, + adapter="videoseal-image", + source_revision=source_revision, + dependencies=dependencies, + size=size, + ) manifest = output_dir / "manifest.jsonl" write_jsonl(manifest, rows) @@ -625,14 +769,14 @@ def main() -> None: action="append", choices=_ADAPTERS, dest="adapters", - help="adapter to include; repeat to select both (default: both)", + help="adapter to include; repeat to select multiple (default: dwt-dct and trustmark)", ) args = parser.parse_args() logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") try: manifest = build_cohort( args.output_dir, - adapters=tuple(args.adapters or _ADAPTERS), + adapters=tuple(args.adapters or DEFAULT_ADAPTERS), size=args.size, ) except (FileExistsError, ImportError, OSError, RuntimeError, ValueError) as exc: diff --git a/scripts/watermark_benchmark_real_cohort.py b/scripts/watermark_benchmark_real_cohort.py index 0ea47dd..97b8538 100755 --- a/scripts/watermark_benchmark_real_cohort.py +++ b/scripts/watermark_benchmark_real_cohort.py @@ -50,6 +50,7 @@ from watermark_benchmark_cohort import ( # noqa: E402 CarrierSpec, append_dwt_rows, append_trustmark_rows, + append_videoseal_image_rows, benchmark_dependencies, validate_cohort_options, ) @@ -60,7 +61,7 @@ RECIPE_VERSION = "watermark-benchmark-real-cohort-v1" DEFAULT_SOURCE_MANIFEST = REPO / "data" / "evaluations" / "engine-selection" / "content-manifest.csv" REUSE_BASIS = SOURCE_REUSE_BASIS DEFAULT_ADAPTERS: tuple[AdapterName, ...] = ("dwt-dct", "trustmark") -_ADAPTERS = frozenset(DEFAULT_ADAPTERS) +_ADAPTERS = frozenset(("dwt-dct", "trustmark", "videoseal-image")) def _standardize(carrier: RealCarrier, *, size: int) -> Image.Image: @@ -185,6 +186,21 @@ def build_real_cohort( clean_transform_revision=recipe_revision, attack_transform_revision=helper_revision, ) + if "videoseal-image" in adapters: + append_videoseal_image_rows( + rows, + root=output_dir, + artifacts=artifacts, + carriers=prepared, + attacks=attacks, + source_revision=source_revision, + dependencies=dependencies, + size=size, + carrier_metadata=metadata, + clean_transform_name="real-carrier-standardize", + clean_transform_revision=recipe_revision, + attack_transform_revision=helper_revision, + ) manifest = output_dir / "manifest.jsonl" write_jsonl(manifest, rows) diff --git a/src/remove_ai_watermarks/_internal/c2pa.py b/src/remove_ai_watermarks/_internal/c2pa.py index 3d6321f..e69eb3f 100644 --- a/src/remove_ai_watermarks/_internal/c2pa.py +++ b/src/remove_ai_watermarks/_internal/c2pa.py @@ -393,12 +393,23 @@ def c2pa_vendor_platform(text: str) -> str | None: def c2pa_info_has_invismark(info: dict[str, Any]) -> bool: """Return whether parsed C2PA info declares Microsoft InvisMark.""" soft_bindings = info.get("soft_binding_vendors") - return isinstance(soft_bindings, list) and "Microsoft InvisMark" in soft_bindings + if isinstance(soft_bindings, list) and "Microsoft InvisMark" in soft_bindings: + return True + soft_binding = info.get("soft_binding") + if isinstance(soft_binding, str) and "Microsoft InvisMark" in soft_binding: + return True + algorithm = info.get("soft_binding_algorithm") + return isinstance(algorithm, str) and "com.microsoft.invismark" in algorithm def c2pa_info_has_removal_hint(info: dict[str, Any]) -> bool: """Return whether a C2PA AI or watermark claim should keep removal fail-safe.""" - return bool(info.get("ai_source_kind") or info.get("synthid_watermark") or c2pa_info_has_invismark(info)) + return bool( + info.get("ai_source_kind") + or info.get("c2pa_identity_ai") + or info.get("synthid_watermark") + or c2pa_info_has_invismark(info) + ) def _has_suffix(codes: list[str], suffixes: tuple[str, ...]) -> bool: @@ -839,6 +850,7 @@ def _populate_registry_fields(buffer: bytes, info: dict[str, Any]) -> bool: if soft_bindings: info["soft_binding_vendors"] = soft_bindings info["soft_binding"] = ", ".join(soft_bindings) + info["soft_binding_algorithm"] = ", ".join(entry.algorithm for entry in soft_binding_entries) return ai_source diff --git a/src/remove_ai_watermarks/_internal/watermark_profiles.py b/src/remove_ai_watermarks/_internal/watermark_profiles.py index 901bd11..aeb6b05 100644 --- a/src/remove_ai_watermarks/_internal/watermark_profiles.py +++ b/src/remove_ai_watermarks/_internal/watermark_profiles.py @@ -349,8 +349,9 @@ def vendor_for_strength(image_path: Path) -> Literal["openai", "google", "micros c2pa_info_has_invalid_credential, c2pa_info_has_invismark, extract_c2pa_info, + soft_binding_vendors_in, ) - from remove_ai_watermarks.metadata import synthid_source + from remove_ai_watermarks.metadata import c2pa_marker_in, scan_head, synthid_source info = extract_c2pa_info(image_path) evidence = (synthid_source(image_path, c2pa_info=info) or "").casefold() @@ -360,6 +361,15 @@ def vendor_for_strength(image_path: Path) -> Literal["openai", "google", "micros return "google" if "openai" in evidence: return "openai" - if not c2pa_info_has_invalid_credential(info) and c2pa_info_has_invismark(info): + if c2pa_info_has_invalid_credential(info): + return None + if c2pa_info_has_invismark(info): return "microsoft" + if info.get("c2pa_validation_source") != "reader": + try: + data = scan_head(image_path) + if c2pa_marker_in(data) and "Microsoft InvisMark" in soft_binding_vendors_in(data): + return "microsoft" + except Exception: + return None return None diff --git a/src/remove_ai_watermarks/api.py b/src/remove_ai_watermarks/api.py index d1ef1ee..f0281ae 100644 --- a/src/remove_ai_watermarks/api.py +++ b/src/remove_ai_watermarks/api.py @@ -387,13 +387,12 @@ class _SourceEvidence: if evidence is None: return True try: - from remove_ai_watermarks._internal.c2pa import c2pa_info_has_removal_hint - from remove_ai_watermarks.identify import identify_from_evidence + from remove_ai_watermarks.identify import identify_from_evidence, report_has_removal_hint report = identify_from_evidence(evidence, image_path=self._path, check_invisible=True) except Exception: return True - return report.ai_from_metadata or c2pa_info_has_removal_hint(evidence.c2pa_info) + return report_has_removal_hint(report, evidence.c2pa_info) def _provenance_from_report(report: Any, path: Path) -> frozenset[str]: diff --git a/src/remove_ai_watermarks/identify.py b/src/remove_ai_watermarks/identify.py index b66efdd..bf97cc9 100644 --- a/src/remove_ai_watermarks/identify.py +++ b/src/remove_ai_watermarks/identify.py @@ -79,10 +79,13 @@ from remove_ai_watermarks.watermark_registry import GEMINI_SPARKLE_TRUST_CONF from remove_ai_watermarks.watermark_registry import known_marks as _known_marks if TYPE_CHECKING: + from collections.abc import Iterable, Sequence from pathlib import Path from numpy.typing import NDArray + from remove_ai_watermarks._internal.constants import C2paSoftBindingAlgorithm + from remove_ai_watermarks.trustmark_detector import TrustMarkVariant from remove_ai_watermarks.watermark_registry import MarkDetection logger = logging.getLogger(__name__) @@ -935,7 +938,11 @@ def _vendor_of(text: str | None) -> str | None: # the camera device label is read from this manifest, so an AI marker is a clash # only when its source differs from this (i.e. it is genuinely independent). _C2PA_MANIFEST_SOURCE = "c2pa_manifest" -_CLASH_SOURCE: dict[str, str] = {"c2pa": _C2PA_MANIFEST_SOURCE, "synthid": _C2PA_MANIFEST_SOURCE} +_CLASH_SOURCE: dict[str, str] = { + "c2pa": _C2PA_MANIFEST_SOURCE, + "synthid": _C2PA_MANIFEST_SOURCE, + "invismark": _C2PA_MANIFEST_SOURCE, +} def _integrity_clashes( @@ -1081,7 +1088,30 @@ def _invisible_watermark(image_path: Path, decode: _SharedDecode) -> str | None: return detect_invisible_watermark(image_path, image=decode.get()) -def _trustmark(image_path: Path) -> str | None: +_TRUSTMARK_ALGORITHM_VARIANTS: tuple[tuple[str, TrustMarkVariant], ...] = ( + ("com.adobe.trustmark.Q", "Q"), + ("com.adobe.trustmark.C", "C"), +) + + +def _trustmark_variants_for_entries( + entries: Iterable[C2paSoftBindingAlgorithm], +) -> tuple[TrustMarkVariant, ...]: + """Return the TrustMark decoder variants to check for a file. + + Variant P (``com.adobe.trustmark.P``) always runs first because it is Adobe's + shipping default and the only variant safe for blind scanning. Variants Q and C + are checked only when the file's C2PA soft-binding assertion names them. + """ + algorithms = {entry.algorithm for entry in entries} + return ("P", *(variant for algorithm, variant in _TRUSTMARK_ALGORITHM_VARIANTS if algorithm in algorithms)) + + +def _trustmark( + image_path: Path, + *, + variants: Sequence[TrustMarkVariant] = ("P",), +) -> str | None: """Adobe TrustMark scheme name or None. Optional: needs the ``trustmark`` decoder (extra ``trustmark``). Returns None @@ -1089,7 +1119,11 @@ def _trustmark(image_path: Path) -> str | None: """ from remove_ai_watermarks.trustmark_detector import detect_trustmark - return detect_trustmark(image_path) + for variant in variants: + scheme = detect_trustmark(image_path) if variant == "P" else detect_trustmark(image_path, variant=variant) + if scheme is not None: + return scheme + return None class _SharedDecode: @@ -1433,7 +1467,14 @@ def _identify_from_evidence( # ── C2PA soft-binding: a registered watermark or content fingerprint ─ # Present in the manifest even when the binding cannot be resolved locally. - soft_binding = meta.get("soft_binding") or (", ".join(soft_binding_vendors) if soft_binding_vendors else None) + has_invismark = ( + "Microsoft InvisMark" in soft_binding_vendors or c2pa_info_has_invismark(info) or c2pa_info_has_invismark(meta) + ) + soft_binding = ( + meta.get("soft_binding") + or info.get("soft_binding") + or (", ".join(soft_binding_vendors) if soft_binding_vendors else None) + ) if soft_binding: soft_binding_value = meta.get("soft_binding_value") or info.get("soft_binding_value") soft_binding_details = "; ".join( @@ -1451,7 +1492,7 @@ def _identify_from_evidence( "high" if c2pa_level == "verified" else "medium", ) ) - if c2pa_info_has_invismark(info): + if has_invismark: # Keep the generic soft-binding row for schema-1 compatibility, and add # the pixel-removal target as its own stable signal for clients that need # to select diffusion without parsing human-readable detail. @@ -1462,6 +1503,10 @@ def _identify_from_evidence( "high" if c2pa_level == "verified" else "medium", ) ) + if has_c2pa and c2pa_usable: + ai_vendor_claims["invismark"] = "Microsoft" + if platform is None or platform.endswith(_NO_AI_GENERATOR_SUFFIX): + platform = "Microsoft (Copilot / Designer)" if soft_binding_watermarks: watermark_details = ( soft_binding_details if not soft_binding_fingerprints else ", ".join(soft_binding_watermarks) @@ -1595,7 +1640,12 @@ def _identify_from_evidence( # The watermark behind Adobe Durable Content Credentials. Decoded locally, # but it binds provenance for human-authored content too, so it enriches the # watermark inventory without by itself asserting AI origin. - if check_invisible and pixel_path is not None and (tm_scheme := _trustmark(pixel_path)) is not None: + if ( + check_invisible + and pixel_path is not None + and (tm_scheme := _trustmark(pixel_path, variants=_trustmark_variants_for_entries(soft_binding_entries))) + is not None + ): signals.append(Signal("trustmark", tm_scheme, "high")) watermarks.append(f"Adobe TrustMark invisible watermark ({tm_scheme})") if platform is None: @@ -1606,7 +1656,7 @@ def _identify_from_evidence( exif_gen = any(s.name == "exif_generator" for s in signals) xai_sig = any(s.name == "xai_signature" for s in signals) ai_from_metadata = bool( - (has_c2pa and c2pa_usable and (c2pa_is_ai or synthid)) + (has_c2pa and c2pa_usable and (c2pa_is_ai or synthid or has_invismark)) or standalone_iptc or iptc_ai or aigc @@ -1616,7 +1666,7 @@ def _identify_from_evidence( or xai_sig ) high_ai_from_metadata = bool( - (has_c2pa and c2pa_level == "verified" and (c2pa_is_ai or synthid)) + (has_c2pa and c2pa_level == "verified" and (c2pa_is_ai or synthid or has_invismark)) or standalone_iptc or iptc_ai or aigc @@ -1632,7 +1682,9 @@ def _identify_from_evidence( # whiteboard photos reach 0.67, so no threshold separates them. Two # Higgsfield downloads (a valid OpenAI C2PA, a Kuaishou TC260 label) scored # 0.53 on wood texture (2026-09-24). - trusted_claims = {k: v for k, v in ai_vendor_claims.items() if k != "c2pa" or c2pa_level == "verified"} + trusted_claims = { + k: v for k, v in ai_vendor_claims.items() if k not in ("c2pa", "invismark") or c2pa_level == "verified" + } non_google = next((v for v in trusted_claims.values() if v != "Google"), None) platform = _collect_visible_signals( pixel_path, signals, watermarks, platform, decode, caveats, non_google_vendor=non_google @@ -1753,6 +1805,16 @@ def identify( ) +def report_has_removal_hint(report: ProvenanceReport, c2pa_info: dict[str, Any]) -> bool: + """Return whether a report or its raw C2PA info retains a pixel-removal target.""" + return ( + report.ai_from_metadata + or c2pa_info_has_removal_hint(c2pa_info) + or any(s.name == "invismark" for s in report.signals) + or any(w.startswith("SynthID watermark") for w in report.watermarks) + ) + + def has_invisible_target(image_path: Path) -> bool: """True when a locally-detectable invisible/metadata AI signal is present. @@ -1790,4 +1852,4 @@ def has_invisible_target(image_path: Path) -> bool: # An asset edit can invalidate the C2PA binding while leaving the declared pixel # watermark intact. Keep the removal gate fail-safe without promoting that broken # claim back into the provenance verdict. - return report.ai_from_metadata or c2pa_info_has_removal_hint(evidence.c2pa_info) + return report_has_removal_hint(report, evidence.c2pa_info) diff --git a/src/remove_ai_watermarks/trustmark_detector.py b/src/remove_ai_watermarks/trustmark_detector.py index e811397..1aad0ee 100644 --- a/src/remove_ai_watermarks/trustmark_detector.py +++ b/src/remove_ai_watermarks/trustmark_detector.py @@ -1,12 +1,14 @@ -"""Detect Adobe TrustMark invisible watermarks. +"""Detect and remove Adobe TrustMark invisible watermarks. TrustMark (github.com/adobe/trustmark, MIT) is the open, keyless image watermark behind Adobe "Durable Content Credentials": when a C2PA manifest is stripped, a TrustMark soft binding can still re-link the asset to its manifest in a -repository. Unlike SynthID it has a PUBLIC decoder with no secret key, so a -TrustMark-stamped image can be identified locally. Adobe's shipping products use -Variant P (the ``com.adobe.trustmark.P`` soft-binding ``alg``); this wrapper -loads that model. +repository. Unlike SynthID it has a PUBLIC decoder and remover with no secret +key, so a TrustMark-stamped image can be identified and scrubbed locally. +Adobe's shipping products default to Variant P (the ``com.adobe.trustmark.P`` +soft-binding ``alg``); Variants Q (``com.adobe.trustmark.Q``) and C +(``com.adobe.trustmark.C``) are also supported when explicitly requested or +corroborated by a C2PA soft-binding assertion. Optional dependency (extra: ``trustmark``); the model weights download on first use. ``detect_trustmark`` returns None when the package is absent. This detects @@ -22,27 +24,60 @@ signal, not proof of AI origin. from __future__ import annotations import logging +import os +import tempfile import threading -from typing import TYPE_CHECKING, Any +from dataclasses import dataclass +from pathlib import Path +from typing import TYPE_CHECKING, Any, Literal if TYPE_CHECKING: - from pathlib import Path - from PIL import Image logger = logging.getLogger(__name__) +TrustMarkVariant = Literal["P", "Q", "C"] +SUPPORTED_VARIANTS: tuple[TrustMarkVariant, ...] = ("P", "Q", "C") # Adobe ships Variant P in production (com.adobe.trustmark.P). -_MODEL_TYPE = "P" +_MODEL_TYPE: TrustMarkVariant = "P" # Schema 3 (BCH_3) is below the detector's measured precision threshold; the # calibration history is canonical in docs/module-internals.md. _SUPPORTED_SCHEMAS = frozenset({0, 1, 2}) -# Lazily constructed singleton -- model load + first-use download is expensive. +# Lazily constructed singletons -- model load + first-use download is expensive. # Guarded by a lock so concurrent callers don't double-construct/double-download. _tm: Any = None +_tm_by_variant: dict[TrustMarkVariant, Any] = {} _tm_lock = threading.Lock() +@dataclass(frozen=True, slots=True) +class TrustMarkDetection: + """A durable Adobe TrustMark watermark decoded from image pixels.""" + + variant: TrustMarkVariant + schema: int + payload: str + + @property + def label(self) -> str: + """Human-readable scheme label matching :func:`detect_trustmark`.""" + return f"Adobe TrustMark (variant {self.variant}, schema {self.schema})" + + +@dataclass(frozen=True, slots=True) +class TrustMarkRemoval(TrustMarkDetection): + """A removed durable Adobe TrustMark watermark and its output path.""" + + output: Path + + +def _validate_variant(variant: str) -> TrustMarkVariant: + normalized = variant.strip().upper() + if normalized not in SUPPORTED_VARIANTS: + raise ValueError(f"unsupported TrustMark variant {variant!r}; expected one of {', '.join(SUPPORTED_VARIANTS)}") + return normalized + + def is_available() -> bool: """True if the optional ``trustmark`` package is installed.""" from .optional_deps import module_available @@ -61,6 +96,22 @@ def _decoder() -> Any: return _tm +def _decoder_for_variant(variant: TrustMarkVariant) -> Any: + resolved = _validate_variant(variant) + if resolved == _MODEL_TYPE: + return _decoder() + cached = _tm_by_variant.get(resolved) + if cached is None: + with _tm_lock: + cached = _tm_by_variant.get(resolved) + if cached is None: + from trustmark import TrustMark + + cached = TrustMark(verbose=False, model_type=resolved) + _tm_by_variant[resolved] = cached + return cached + + # JPEG quality for the false-positive durability gate (see detect_trustmark). # Deliberately mild: a genuine TrustMark survives far harsher. The round-trip # still needs payload and schema validation because content-correlated false @@ -68,10 +119,16 @@ def _decoder() -> Any: _REENCODE_QUALITY = 95 -def _detect_cover(cover: Image.Image, source: object) -> str | None: +def _detect_cover_detailed( + cover: Image.Image, + source: object, + *, + variant: TrustMarkVariant = _MODEL_TYPE, +) -> TrustMarkDetection | None: """Decode one RGB cover after availability and image loading are resolved.""" + resolved = _validate_variant(variant) try: - decoder = _decoder() + decoder = _decoder_for_variant(resolved) wm_secret, wm_present, wm_schema = decoder.decode(cover, "binary") if not wm_present: return None @@ -88,11 +145,17 @@ def _detect_cover(cover: Image.Image, source: object) -> str | None: except Exception as exc: # model download / decode failure logger.debug("TrustMark decode failed for %s: %s", source, exc) return None - return f"Adobe TrustMark (variant {_MODEL_TYPE}, schema {wm_schema})" + return TrustMarkDetection(variant=resolved, schema=int(wm_schema), payload=str(wm_secret)) -def detect_trustmark_image(image: Image.Image, *, source: object = "decoded image") -> str | None: +def detect_trustmark_image( + image: Image.Image, + *, + source: object = "decoded image", + variant: TrustMarkVariant = _MODEL_TYPE, +) -> str | None: """Detect a durable TrustMark in an already decoded Pillow image.""" + resolved = _validate_variant(variant) if not is_available(): return None try: @@ -100,10 +163,36 @@ def detect_trustmark_image(image: Image.Image, *, source: object = "decoded imag except Exception as exc: logger.debug("TrustMark image conversion failed for %s: %s", source, exc) return None - return _detect_cover(cover, source) + detection = _detect_cover_detailed(cover, source, variant=resolved) + return detection.label if detection is not None else None -def detect_trustmark(image_path: Path) -> str | None: +def detect_trustmark_detailed( + image_path: str | Path, + *, + variant: TrustMarkVariant = _MODEL_TYPE, +) -> TrustMarkDetection | None: + """Return structured TrustMark detection details if a durable mark is decoded, else None.""" + resolved = _validate_variant(variant) + if not is_available(): + return None + path = Path(image_path) + try: + from PIL import Image + + with Image.open(path) as img: + cover = img.convert("RGB") + except Exception as exc: # unreadable image + logger.debug("TrustMark decode failed for %s: %s", path, exc) + return None + return _detect_cover_detailed(cover, path, variant=resolved) + + +def detect_trustmark( + image_path: str | Path, + *, + variant: TrustMarkVariant = _MODEL_TYPE, +) -> str | None: """Return a TrustMark scheme note if a *durable* TrustMark watermark is decoded, else None. Returns e.g. ``"Adobe TrustMark (variant P, schema 0)"`` when the decoder @@ -122,17 +211,82 @@ def detect_trustmark(image_path: Path) -> str | None: JPEG round-trip and require the same binary payload and schema both times. Only the calibrated schemas 0-2 count as high-precision positives. """ + detection = detect_trustmark_detailed(image_path, variant=variant) + return detection.label if detection is not None else None + + +def remove_trustmark( + source: str | Path, + output: str | Path, + *, + variant: TrustMarkVariant = _MODEL_TYPE, +) -> TrustMarkRemoval | None: + """Remove a confirmed durable TrustMark watermark with the official neural remover. + + No output is written unless ``detect_trustmark_detailed`` first confirms a + durable mark for ``variant`` and the encoded output no longer decodes as + watermarked under that variant. Alpha channels and display tags are + preserved via ``image_io.write_bgr_with_alpha``. + """ + resolved = _validate_variant(variant) if not is_available(): return None - try: - from PIL import Image - with Image.open(image_path) as img: + import numpy as np + from PIL import Image + + from remove_ai_watermarks import image_io + + source_path, output_path = Path(source), Path(output) + try: + with Image.open(source_path) as img: cover = img.convert("RGB") - except Exception as exc: # unreadable image - logger.debug("TrustMark decode failed for %s: %s", image_path, exc) + except Exception as exc: + raise ValueError(f"Could not read image: {source}") from exc + + detection = _detect_cover_detailed(cover, source_path, variant=resolved) + if detection is None: return None - return _detect_cover(cover, image_path) + + bgr, alpha = image_io.read_bgr_and_alpha(source_path) + if bgr is None: + raise ValueError(f"Could not read image: {source}") + + decoder = _decoder_for_variant(resolved) + cleaned_rgb_img = decoder.remove_watermark(cover).convert("RGB") + if cleaned_rgb_img.size != (bgr.shape[1], bgr.shape[0]): + cleaned_rgb_img = cleaned_rgb_img.resize((bgr.shape[1], bgr.shape[0]), Image.Resampling.LANCZOS) + cleaned_rgb = np.asarray(cleaned_rgb_img, dtype=np.uint8) + cleaned_bgr = np.ascontiguousarray(cleaned_rgb[..., ::-1]) + + output_path.parent.mkdir(parents=True, exist_ok=True) + file_descriptor, temporary_name = tempfile.mkstemp( + prefix=f".{output_path.stem}-", suffix=output_path.suffix, dir=output_path.parent + ) + os.close(file_descriptor) + temporary_path = Path(temporary_name) + try: + if not image_io.write_bgr_with_alpha( + temporary_path, + cleaned_bgr, + alpha, + display_tags_from=source_path, + orientation_applied=False, + ): + raise OSError(f"failed to write output (is the destination writable?): {output_path}") + if detect_trustmark_detailed(temporary_path, variant=resolved) is not None: + return None + os.replace(temporary_path, output_path) + finally: + if temporary_path.exists(): + temporary_path.unlink() + + return TrustMarkRemoval( + variant=detection.variant, + schema=detection.schema, + payload=detection.payload, + output=output_path, + ) def _survives_reencode(decoder: Any, cover: Any, payload: str, schema: int) -> bool: diff --git a/tests/test_identify.py b/tests/test_identify.py index f0e45cc..f36b9fc 100644 --- a/tests/test_identify.py +++ b/tests/test_identify.py @@ -1672,6 +1672,112 @@ class TestIdentifySoftBinding: assert watermark_id in soft_binding.detail assert any(signal.name == "invismark" for signal in report.signals) + def test_invismark_asserts_ai_and_microsoft_platform_on_store_and_raw_fallback(self, tmp_path: Path): + store_record = { + "c2pa_store": { + "active_manifest": "paint", + "manifests": { + "paint": { + "assertions": [ + { + "label": "c2pa.soft-binding", + "data": { + "alg": "com.microsoft.invismark.1", + "blocks": [{"scope": "the entire image", "value": "uuid-1"}], + }, + } + ] + } + }, + } + } + store_report = identify_from_evidence(evidence_from_metadata_record(store_record, path=tmp_path / "paint.png")) + assert store_report.is_ai_generated is True + assert store_report.ai_from_metadata is True + assert store_report.platform == "Microsoft (Copilot / Designer)" + assert any(signal.name == "invismark" for signal in store_report.signals) + + fallback_path = tmp_path / "fallback.jpg" + fallback_path.write_bytes(b"\xff\xd8\xff\xe1 c2pa jumb com.microsoft.invismark.1 \xff\xd9") + fallback_report = identify(fallback_path, check_visible=False, check_invisible=False) + assert fallback_report.is_ai_generated is True + assert fallback_report.ai_from_metadata is True + assert fallback_report.platform == "Microsoft (Copilot / Designer)" + assert any(signal.name == "invismark" for signal in fallback_report.signals) + + def test_invismark_participates_in_integrity_clashes_as_c2pa_manifest_source(self): + # Multi-actor Microsoft Designer wrapping OpenAI in one C2PA manifest does not clash. + assert ( + _integrity_clashes( + {"c2pa": "OpenAI", "invismark": "Microsoft"}, + "Microsoft (Copilot / Designer)", + camera_has_ai_marker=False, + ) + == [] + ) + # Independent external stamp (EXIF generator) naming Ideogram clashes with InvisMark. + clashes = _integrity_clashes( + {"invismark": "Microsoft", "exif_generator": "Ideogram"}, + "Microsoft (Copilot / Designer)", + camera_has_ai_marker=False, + ) + assert len(clashes) == 1 + assert "Microsoft" in clashes[0] + assert "Ideogram" in clashes[0] + + def test_removal_hints_include_c2pa_identity_ai_and_fallback_soft_binding_signals(self, tmp_path: Path): + from remove_ai_watermarks._internal.c2pa import c2pa_info_has_removal_hint + from remove_ai_watermarks.identify import report_has_removal_hint + + assert c2pa_info_has_removal_hint({"c2pa_identity_ai": True}) is True + + fallback_path = tmp_path / "broken-invismark.jpg" + fallback_path.write_bytes(b"\xff\xd8\xff\xe1 c2pa jumb com.microsoft.invismark.1 \xff\xd9") + invalid_info = { + "has_c2pa": True, + "soft_binding": "Microsoft InvisMark", + "soft_binding_algorithm": "com.microsoft.invismark.1", + "c2pa_validation_source": "reader", + "c2pa_integrity": "invalid", + "c2pa_signature": "valid", + "c2pa_signer_validity": "valid", + } + evidence = _evidence(fallback_path, invalid_info, fallback_path.read_bytes()) + report = identify_from_evidence(evidence) + assert report.is_ai_generated is None + assert report_has_removal_hint(report, {}) is True + + def test_c2pa_soft_binding_corroborates_trustmark_variant_q_and_c( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ): + from PIL import Image + + from remove_ai_watermarks import trustmark_detector + + path = tmp_path / "trustmark-q.jpg" + Image.new("RGB", (32, 32)).save(path, "JPEG") + data = path.read_bytes() + segment = _jpeg_segment(0xEB, b"c2pa jumb com.adobe.trustmark.Q") + path.write_bytes(data[:2] + segment + data[2:]) + + called_variants: list[str] = [] + + def fake_detect(_path: Path, *, variant: str = "P") -> str | None: + called_variants.append(variant) + if variant == "Q": + return "Adobe TrustMark (variant Q, schema 1)" + return None + + monkeypatch.setattr(trustmark_detector, "detect_trustmark", fake_detect) + + report = identify(path, check_visible=False, check_invisible=True) + + assert called_variants == ["P", "Q"] + assert any( + signal.name == "trustmark" and signal.detail == "Adobe TrustMark (variant Q, schema 1)" + for signal in report.signals + ) + class TestIdentifyIptcAi: """IPTC 2025.1 AISystemUsed drives an AI verdict + platform attribution.""" diff --git a/tests/test_platform.py b/tests/test_platform.py index 6312793..a5e5648 100644 --- a/tests/test_platform.py +++ b/tests/test_platform.py @@ -409,6 +409,17 @@ class TestVendorForStrength: with patch("remove_ai_watermarks.metadata.synthid_source", side_effect=OSError): assert vendor_for_strength(Path("x.png")) is None + def test_non_png_fallback_invismark_selects_microsoft_floor(self, tmp_path: Path): + from remove_ai_watermarks._internal.watermark_profiles import vendor_for_strength + + jpeg = tmp_path / "invismark-fallback.jpg" + jpeg.write_bytes(b"\xff\xd8\xff\xeb\x00\x2cc2pa jumb com.microsoft.invismark.1\xff\xd9") + with ( + self._patch(None), + patch("remove_ai_watermarks._internal.c2pa.extract_c2pa_info", return_value={}), + ): + assert vendor_for_strength(jpeg) == "microsoft" + # ── Format utilities ──────────────────────────────────────────────── diff --git a/tests/test_trustmark_detector.py b/tests/test_trustmark_detector.py index 20bf171..2668af9 100644 --- a/tests/test_trustmark_detector.py +++ b/tests/test_trustmark_detector.py @@ -16,7 +16,13 @@ from PIL import Image from remove_ai_watermarks import trustmark_detector from remove_ai_watermarks.identify import identify -from remove_ai_watermarks.trustmark_detector import detect_trustmark, detect_trustmark_image, is_available +from remove_ai_watermarks.trustmark_detector import ( + detect_trustmark, + detect_trustmark_detailed, + detect_trustmark_image, + is_available, + remove_trustmark, +) _OFFICIAL_FIXTURE = ( Path(__file__).resolve().parent.parent / "data" / "fixtures" / "provenance" / "adobe-trustmark-p.png" @@ -32,6 +38,7 @@ class _FakeDecoder: def __init__(self, *results: tuple[str, bool, int]): self._results = list(results) self.calls = 0 + self.removed = 0 def decode(self, _img: object, mode: str = "binary") -> tuple[str, bool, int]: assert mode == "binary" @@ -39,6 +46,10 @@ class _FakeDecoder: self.calls += 1 return result + def remove_watermark(self, img: Image.Image) -> Image.Image: + self.removed += 1 + return img.copy() + def test_detect_never_raises(tmp_clean_png: Path): # Whether or not trustmark is installed, a clean image must yield None @@ -130,3 +141,80 @@ def test_official_adobe_variant_p_fixture_is_provenance_not_ai(): def test_official_adobe_variant_p_fixture_digest(): assert hashlib.sha256(_OFFICIAL_FIXTURE.read_bytes()).hexdigest() == _OFFICIAL_FIXTURE_SHA256 + + +class TestVariantsAndRemoval: + """Variant selection (`P`, `Q`, `C`), structured detection, and neural removal.""" + + @pytest.fixture(autouse=True) + def _force_available(self, monkeypatch: pytest.MonkeyPatch): + monkeypatch.setattr(trustmark_detector, "is_available", lambda: True) + + def test_variants_q_and_c_report_their_variant_labels(self, monkeypatch: pytest.MonkeyPatch, tmp_clean_png: Path): + decoders = { + "Q": _FakeDecoder(("bits-q", True, 1), ("bits-q", True, 1)), + "C": _FakeDecoder(("bits-c", True, 2), ("bits-c", True, 2)), + } + monkeypatch.setattr(trustmark_detector, "_decoder_for_variant", lambda variant: decoders[variant]) + + detailed_q = detect_trustmark_detailed(tmp_clean_png, variant="Q") + assert detailed_q is not None + assert detailed_q.variant == "Q" + assert detailed_q.schema == 1 + assert detailed_q.payload == "bits-q" + assert detailed_q.label == "Adobe TrustMark (variant Q, schema 1)" + assert detect_trustmark(tmp_clean_png, variant="C") == "Adobe TrustMark (variant C, schema 2)" + + def test_unsupported_variant_raises_value_error(self, tmp_clean_png: Path): + with pytest.raises(ValueError, match="unsupported TrustMark variant"): + detect_trustmark(tmp_clean_png, variant="B") # type: ignore[arg-type] + + def test_remove_trustmark_removes_detected_watermark_and_verifies_output( + self, monkeypatch: pytest.MonkeyPatch, tmp_clean_png: Path, tmp_path: Path + ): + # First two decode calls verify durability before removal; the third verifies + # that the written output no longer carries a durable watermark. + decoder = _FakeDecoder(("1010", True, 1), ("1010", True, 1), ("", False, -1)) + monkeypatch.setattr(trustmark_detector, "_decoder", lambda: decoder) + out = tmp_path / "cleaned.png" + + outcome = remove_trustmark(tmp_clean_png, out) + + assert outcome is not None + assert outcome.variant == "P" + assert outcome.schema == 1 + assert outcome.payload == "1010" + assert outcome.output == out + assert decoder.removed == 1 + assert out.exists() + + def test_remove_trustmark_returns_none_and_writes_nothing_on_clean_or_surviving_mark( + self, monkeypatch: pytest.MonkeyPatch, tmp_clean_png: Path, tmp_path: Path + ): + clean_decoder = _FakeDecoder(("", False, -1)) + monkeypatch.setattr(trustmark_detector, "_decoder", lambda: clean_decoder) + clean_out = tmp_path / "clean_out.png" + + assert remove_trustmark(tmp_clean_png, clean_out) is None + assert clean_decoder.removed == 0 + assert not clean_out.exists() + + surviving_decoder = _FakeDecoder(("1010", True, 1), ("1010", True, 1), ("1010", True, 1), ("1010", True, 1)) + monkeypatch.setattr(trustmark_detector, "_decoder", lambda: surviving_decoder) + surviving_out = tmp_path / "surviving_out.png" + + assert remove_trustmark(tmp_clean_png, surviving_out) is None + assert surviving_decoder.removed == 1 + assert not surviving_out.exists() + + +@pytest.mark.skipif(not is_available(), reason="trustmark not installed") +def test_official_adobe_variant_p_fixture_removal_end_to_end(tmp_path: Path): + out = tmp_path / "removed.png" + outcome = remove_trustmark(_OFFICIAL_FIXTURE, out, variant="P") + + assert outcome is not None + assert outcome.variant == "P" + assert outcome.schema == 1 + assert outcome.output == out + assert detect_trustmark(out) is None diff --git a/tests/test_videoseal_oracle.py b/tests/test_videoseal_oracle.py index d2dee11..d6d777f 100644 --- a/tests/test_videoseal_oracle.py +++ b/tests/test_videoseal_oracle.py @@ -121,3 +121,25 @@ class TestImageMode: np.testing.assert_allclose(marked, pixels) assert videoseal_oracle.decode_image(Model(), marked) == message + + def test_read_image_scores_uint8_and_float32_pixels(self) -> None: + torch = pytest.importorskip("torch") + message = (1, 1, 1, 1, 1, 1, 1, 1, 0, 0) + + class Model: + def detect(self, tensor: object, *, is_video: bool) -> object: + assert is_video is False + assert tensor.dtype == torch.float32 + assert float(tensor.min()) >= 0.0 + assert float(tensor.max()) <= 1.0 + return {"preds": torch.tensor([[9.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0]])} + + uint8_pixels = np.full((2, 4, 3), 128, dtype=np.uint8) + reading = videoseal_oracle.read_image(Model(), uint8_pixels, message=message) + + assert reading.bit_accuracy == pytest.approx(0.9) + assert reading.detected is True + assert reading.label == "ff40" + + with pytest.raises(ValueError, match="does not match expected 4"): + videoseal_oracle.read_image(Model(), uint8_pixels, message=(1, 0, 1, 0)) diff --git a/tests/test_watermark_benchmark.py b/tests/test_watermark_benchmark.py index 5f15b46..ee1b136 100644 --- a/tests/test_watermark_benchmark.py +++ b/tests/test_watermark_benchmark.py @@ -393,10 +393,19 @@ def test_jsonl_writer_refuses_overwrite_and_emits_strict_json(tmp_path: Path) -> def test_builtin_adapters_name_their_exact_source_files() -> None: adapters = MODULE.default_adapters() - assert set(adapters) == {"dwt-dct", "trustmark", "pixelseal", "audioseal", "perth", "videoseal"} + assert set(adapters) == { + "dwt-dct", + "trustmark", + "pixelseal", + "videoseal-image", + "audioseal", + "perth", + "videoseal", + } assert adapters["dwt-dct"].source_file.name == "invisible_watermark.py" assert adapters["trustmark"].source_file.name == "trustmark_detector.py" assert adapters["pixelseal"].source_file.name == "pixelseal_oracle.py" + assert adapters["videoseal-image"].source_file.name == "videoseal_oracle.py" assert adapters["audioseal"].source_file.name == "audioseal_oracle.py" assert adapters["perth"].source_file.name == "perth_oracle.py" assert adapters["videoseal"].source_file.name == "videoseal_oracle.py" @@ -776,3 +785,33 @@ def test_run_benchmark_records_videoseal_temporal_evidence(tmp_path: Path, monke record = json.loads(output.read_text(encoding="utf-8")) assert record["detection"]["temporal"]["frames"] == 3 + + +def test_videoseal_image_adapter_enforces_image_media_and_records_bit_accuracy( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + import videoseal_oracle + + artifact = _image(tmp_path / "marked.png", 100) + video_row = _row(artifact) + video_row["adapter"] = "videoseal-image" + video_row["media_type"] = "video" + with pytest.raises(ValueError, match="'videoseal-image' measures image artifacts, not video"): + MODULE.load_manifest(_write_manifest(tmp_path / "bad.jsonl", [video_row])) + + monkeypatch.setattr(videoseal_oracle, "load_model", lambda: object()) + monkeypatch.setattr( + videoseal_oracle, + "read_image", + lambda _model, _pixels: videoseal_oracle.VideoSealImageReading( + bit_accuracy=0.95, + decoded_bits=(1,) * 8 + (0,) * 8, + ), + ) + + adapter = MODULE.default_adapters()["videoseal-image"] + outcome = adapter.detect(artifact, np.full((32, 40, 3), 100, dtype=np.uint8)) + + assert outcome.status == "detected" + assert outcome.label == "ff00" + assert outcome.message_bit_accuracy == 0.95 diff --git a/tests/test_watermark_benchmark_cohort.py b/tests/test_watermark_benchmark_cohort.py index d38921d..47ce17a 100644 --- a/tests/test_watermark_benchmark_cohort.py +++ b/tests/test_watermark_benchmark_cohort.py @@ -111,3 +111,98 @@ def test_trustmark_cohort_includes_removed_observation(tmp_path: Path) -> None: removed = next(row for row in rows if row.state == "removed") assert removed.reference_path is not None assert removed.transform.name == "trustmark-remove" + + +def test_videoseal_image_cohort_has_matched_positive_attack_and_hard_negative_arms( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + import videoseal_oracle + + monkeypatch.setattr(videoseal_oracle, "available", lambda: True) + monkeypatch.setattr(videoseal_oracle, "load_model", lambda: object()) + monkeypatch.setattr( + videoseal_oracle, + "embed_image", + lambda _model, pixels, _message: (pixels + 0.01).clip(0.0, 1.0), + ) + output = tmp_path / "cohort" + + manifest = MODULE.build_cohort( + output, + adapters=("videoseal-image",), + carriers=(MODULE.CarrierSpec("texture", 7),), + attacks=("jpeg-q90",), + size=256, + ) + rows = MODULE.load_manifest(manifest) + + assert len(rows) == 5 + assert {row.adapter for row in rows} == {"videoseal-image"} + assert {(row.arm, row.state, row.expected) for row in rows} == { + ("matched_negative", "clean", "not_detected"), + ("positive", "marked", "detected"), + ("positive", "attacked", "unresolved"), + ("wrong_key", "forged", "not_detected"), + ("hard_negative", "clean", "not_detected"), + } + + +def test_pixelseal_study_includes_geometric_attacks_and_optional_removal_rows( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + import shutil + + import pixelseal_oracle + import videoseal_oracle + + study_path = Path(__file__).resolve().parents[1] / "scripts" / "perth_pixelseal_study.py" + spec = importlib.util.spec_from_file_location("perth_pixelseal_study", study_path) + assert spec is not None + assert spec.loader is not None + study = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = study + spec.loader.exec_module(study) + + carrier_dir = tmp_path / "alpha" + carrier_dir.mkdir() + carrier_path = carrier_dir / "carrier.png" + Image.new("RGB", (256, 256), (40, 80, 120)).save(carrier_path) + + monkeypatch.setattr(pixelseal_oracle, "available", lambda: True) + monkeypatch.setattr(pixelseal_oracle, "load_model", lambda: object()) + monkeypatch.setattr( + pixelseal_oracle, + "embed", + lambda _model, pixels, _message: pixels.copy(), + ) + monkeypatch.setattr(videoseal_oracle, "available", lambda: True) + monkeypatch.setattr(videoseal_oracle, "load_model", lambda: object()) + monkeypatch.setattr( + videoseal_oracle, + "embed_image", + lambda _model, pixels, _message: pixels.copy(), + ) + monkeypatch.setattr(study, "IMAGE_CARRIERS", (carrier_path,)) + monkeypatch.setattr(study, "_cuda_available", lambda: True) + monkeypatch.setattr(study, "_invisible_engine_available", lambda: True) + monkeypatch.setattr( + study, + "_run_pixelseal_removal_profile", + lambda _profile, source, target: shutil.copyfile(source, target), + ) + + output_dir = tmp_path / "study" + artifacts = output_dir / "artifacts" + artifacts.mkdir(parents=True) + rows, removal_summary = study._build_pixelseal_rows(output_dir, artifacts) + videoseal_rows, videoseal_removal = study._build_videoseal_image_rows(output_dir, artifacts) + + transforms = {row["transform"]["name"] for row in rows} + assert {"jpeg", "resize-75", "crop-5"} <= transforms + assert {f"remove-invisible-{profile}" for profile in study.REMOVAL_PROFILES} <= transforms + assert removal_summary == {"status": "executed", "profiles": list(study.REMOVAL_PROFILES)} + + videoseal_transforms = {row["transform"]["name"] for row in videoseal_rows} + assert {"jpeg", "resize-75", "crop-5"} <= videoseal_transforms + assert {f"remove-invisible-{profile}" for profile in study.REMOVAL_PROFILES} <= videoseal_transforms + assert videoseal_removal == {"status": "executed", "profiles": list(study.REMOVAL_PROFILES)} diff --git a/tests/test_watermark_benchmark_real_cohort.py b/tests/test_watermark_benchmark_real_cohort.py index 7247aca..78389db 100644 --- a/tests/test_watermark_benchmark_real_cohort.py +++ b/tests/test_watermark_benchmark_real_cohort.py @@ -129,3 +129,40 @@ def test_real_cohort_requires_provider_balance(tmp_path: Path) -> None: with pytest.raises(ValueError, match="at least two providers"): MODULE.load_real_carriers(source_manifest) + + +def test_real_cohort_supports_videoseal_image_adapter(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + import videoseal_oracle + + monkeypatch.setattr(videoseal_oracle, "available", lambda: True) + monkeypatch.setattr(videoseal_oracle, "load_model", lambda: object()) + monkeypatch.setattr( + videoseal_oracle, + "embed_image", + lambda _model, pixels, _message: (pixels + 0.01).clip(0.0, 1.0), + ) + source_manifest = _write_source_manifest( + tmp_path, + [ + _source_row(tmp_path, "alpha", (20, 80, 140)), + _source_row(tmp_path, "beta", (160, 90, 30)), + ], + ) + + manifest = MODULE.build_real_cohort( + tmp_path / "cohort", + source_manifest=source_manifest, + adapters=("videoseal-image",), + attacks=("jpeg-q90",), + size=256, + ) + rows = MODULE.load_manifest(manifest) + + assert len(rows) == 8 + assert {row.adapter for row in rows} == {"videoseal-image"} + assert {(row.arm, row.state) for row in rows} == { + ("matched_negative", "clean"), + ("positive", "marked"), + ("positive", "attacked"), + ("wrong_key", "forged"), + }