From a967d5aa5e8f73cbfd673b76fcea6d10aa52bdb9 Mon Sep 17 00:00:00 2001 From: Victor Kuznetsov Date: Sat, 14 Nov 2026 10:49:16 -0800 Subject: [PATCH] Upgrade photo classifier to v6 Model 2, calibrate confidence, fix C2PA parameters --- .claude/rules/development.md | 2 +- .../workflows/publish-photo-classify-hf.yml | 43 ++- docs/ai-generated-image-classifiers.md | 2 +- docs/cli.md | 11 +- docs/index.md | 2 +- docs/known-limitations.md | 15 +- docs/module-internals.md | 73 +++-- docs/photo-classify-hf/README.md | 309 +++++++---------- docs/photo-classify-hf/operating-point.json | 70 ++-- docs/photo-classify-training.md | 9 +- docs/photo-classify.md | 175 +++++----- docs/python-api.md | 16 +- docs/release-and-distribution.md | 13 +- scripts/publish_photo_classify_hf.py | 31 +- .../references/commands.md | 11 +- src/remove_ai_watermarks/_internal/c2pa.py | 5 + .../_internal/forensic_124d.py | 2 +- src/remove_ai_watermarks/classify.py | 197 +++++------ src/remove_ai_watermarks/cli.py | 8 +- src/remove_ai_watermarks/source_classify.py | 14 +- tests/test_classify.py | 310 +++++++++++------- tests/test_designer_synthid_suppression.py | 206 ++++++++++++ tests/test_publish_photo_classify_hf.py | 33 +- tests/test_source_classify.py | 72 ++++ 24 files changed, 991 insertions(+), 638 deletions(-) diff --git a/.claude/rules/development.md b/.claude/rules/development.md index 2d3fc8e..62e9a99 100644 --- a/.claude/rules/development.md +++ b/.claude/rules/development.md @@ -78,7 +78,7 @@ Do not classify an entire module as untestable because its main path downloads a - tiling geometry and blending in `test_tiling.py`; - prompt-embedding cache keying, storage round-trip, and the cross-pipeline reuse that lets a stack load without its text encoder, in `test_qwen_zimage_pipeline.py`; - the face stack's dtype in `test_qwen_zimage_pipeline.py`: a subclass that changes the pipeline dtype must not change an inherited stage's. When one profile inherits another's stage, guard the invariants that stage relies on; -- the photo-classify gate in `test_classify.py`: DEFINITELY is ridge AND MLP, POSSIBLY does not emit a provider, and `identify` does not import `remove_ai_watermarks.classify`; +- the photo-classify gate in `test_classify.py`: DEFINITELY is ridge AND MLP, POSSIBLY and receipt-gated inputs do not run the 10-provider `multi-provider-source-v6.npz` Model 2, Model 2 SHA-256 mismatches fail closed, and `identify` imports neither `remove_ai_watermarks.classify` nor `remove_ai_watermarks.source_classify`; - the source-export classifier in `test_source_classify.py` and `test_source_features_v4.py`: the Hub revision and artifact hash are immutable, the pickle-free `v3`/`v4`/`v5` schemas, Regime-FiLM `SiLU` residual trunks, decoupled acceptance/attribution invariance, and exact `GELU` are validated, threshold mutation changes the real decision, and `identify` never consumes the result as watermark evidence; - the `InvisibleOptions` defaults in `test_api.py`, compared field by field with the signature they mirror and without an exception table: a field that needs one belongs elsewhere. diff --git a/.github/workflows/publish-photo-classify-hf.yml b/.github/workflows/publish-photo-classify-hf.yml index 5a26581..602160a 100644 --- a/.github/workflows/publish-photo-classify-hf.yml +++ b/.github/workflows/publish-photo-classify-hf.yml @@ -6,9 +6,10 @@ name: Publish photo classifier to Hugging Face # Hub model: wiltodelta/raiw-photo-classify # Secret: HF_TOKEN, write-role Hugging Face token (same secret Space sync uses). # -# Weights are not in git. Full mode downloads the frozen PyTorch files from a -# GitHub Release, exports the vision-only ONNX graph, then uploads everything -# with the card from docs/photo-classify-hf/. +# Weights are not in git. Full mode downloads the frozen Model 1 + receipt-gate +# files and the frozen multi-provider-source-v6.npz Model 2 bundle from GitHub +# Releases, exports the vision-only ONNX graph, then uploads everything with the +# card from docs/photo-classify-hf/. on: workflow_dispatch: @@ -17,16 +18,20 @@ on: description: "Type publish" required: true mode: - description: "full = card plus weights from the release tag; card = README, operating-point, and receipt gate only" + description: "full = card plus weights from the release tags; card = README, operating-point, and fallback receipt gate only" type: choice options: - full - card default: full weights_tag: - description: "GitHub Release tag that holds clip-l-ft.pt, probe, detector.pt, provider.pt" + description: "GitHub Release tag holding clip-l-ft.pt, probe-weights-clip-l-ft.npz, detector.pt, and receipt-gate.npz" required: false - default: photo-classify-freeze-2026-08-31 + default: photo-classify-freeze-2026-09-07 + source_weights_tag: + description: "GitHub Release tag holding multi-provider-source-v6.npz" + required: false + default: source-classify-v6-freeze-2026-11-13 jobs: publish: @@ -42,15 +47,35 @@ jobs: with: python-version: "3.12" - - name: Download freeze weights from the GitHub Release + - name: Download freeze weights from GitHub Releases if: ${{ github.event.inputs.mode == 'full' }} env: GH_TOKEN: ${{ github.token }} - TAG: ${{ github.event.inputs.weights_tag }} + TAG: ${{ github.event.inputs.weights_tag || 'photo-classify-freeze-2026-09-07' }} + SOURCE_TAG: ${{ github.event.inputs.source_weights_tag || 'source-classify-v6-freeze-2026-11-13' }} run: | set -euo pipefail + IFS=$'\t' read -r artifact expected < <( + jq -r '[.model2.artifact, .model2.artifact_sha256] | @tsv' docs/photo-classify-hf/operating-point.json + ) + test -n "$artifact" && test "$artifact" != "null" + test "${#expected}" -eq 64 mkdir -p weights - gh release download "$TAG" --repo "${{ github.repository }}" --dir weights + gh release download "$TAG" \ + --repo "${{ github.repository }}" \ + --pattern clip-l-ft.pt \ + --pattern detector.pt \ + --pattern probe-weights-clip-l-ft.npz \ + --pattern receipt-gate.npz \ + --dir weights & + pid_model1=$! + gh release download "$SOURCE_TAG" \ + --repo "${{ github.repository }}" \ + --pattern "$artifact" \ + --dir weights & + pid_model2=$! + wait "$pid_model1" "$pid_model2" + echo "$expected weights/$artifact" | sha256sum --check ls -l weights - name: Export the vision-only ONNX graph diff --git a/docs/ai-generated-image-classifiers.md b/docs/ai-generated-image-classifiers.md index 6473625..bf9f433 100644 --- a/docs/ai-generated-image-classifiers.md +++ b/docs/ai-generated-image-classifiers.md @@ -3,7 +3,7 @@ > Research archive for metadata-free `ai_generated` versus > `not_ai_generated` classifiers. These are not SynthID detectors and are not `identify` verdicts. The 2026-08-31 freeze is consumed only by explicit -> `classify` / `classify_pixels`. Current behavior: +> `classify` / `classify_pixels` (Model 1 + `receipt-gate.npz` from this archive, paired since 2026-11 with the 10-provider `multi-provider-source-v6.npz` Model 2). Current behavior: > [photo pixel classification](photo-classify.md), > [supported signals](supported-signals.md), > and [known limitations](known-limitations.md). diff --git a/docs/cli.md b/docs/cli.md index 23dc9de..32b3f3d 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -92,8 +92,10 @@ remove-ai-watermarks classify image.png --json The command runs the frozen photo detector (CLIP-L-ft ridge AND freeze MLP). Only a DEFINITELY result is reported as `ai`. On that result only, the receipt-document gate abstains receipt photographs to `unknown` before the -124-d provider head, which may return `openai`, `google`, `bytedance`, or -`muse-image`. +512-d `multi-provider-source-v6.npz` Model 2 ensemble, which attributes +`provider` across 10 families (`openai`, `google`, `bytedance`, `flux`, +`stable_diffusion`, `meta`, `midjourney`, `ideogram`, `firefly`, `xai`) or +abstains to `none` (`null` in JSON). POSSIBLY is `unknown`. Camera-like photographs are `human`. The call does not run cleanup and does not set `is_ai_generated`. @@ -101,9 +103,8 @@ The contract is AI versus camera. Receipts abstain through the gate but are not a supported verdict; UI and digital art are out of scope. Microsoft is not a pixel class: a DALL-E Bing image scores as `openai`, an Imagen Designer image as `google`. `bytedance` names the shared -Doubao+Jimeng generator lineage. The rest of China's generators (Qwen, -Kling, ...) are peers of the named ones but have no honest class yet; -their residual head abstains, so that content publishes no provider. Weights download on first use from +Doubao+Jimeng generator lineage. Generators outside the 10 named families +(Qwen, Kling, Yuanbao, ...) abstain and publish no provider. Weights download on first use from [`wiltodelta/raiw-photo-classify`](https://huggingface.co/wiltodelta/raiw-photo-classify), or from `RAIW_CLASSIFY_WEIGHTS` if that directory already holds the freeze files. diff --git a/docs/index.md b/docs/index.md index 000cb59..fc1ad96 100644 --- a/docs/index.md +++ b/docs/index.md @@ -42,7 +42,7 @@ The current behavior is defined by the code, tests, README, and user guides. - [Qwen improvement research](qwen-improvement-research.md) - [Doubao reverse-alpha research](research-doubao-distillation.md) - [AI-generated image classifiers](ai-generated-image-classifiers.md) (photo AI-versus-camera freeze consumed by `classify_pixels`, not `identify`) -- [Photo classifier Hugging Face card](photo-classify-hf/README.md) (Hub publication text of the 2026-08-31 freeze) +- [Photo classifier Hugging Face card](photo-classify-hf/README.md) (Hub publication text of the Model 1 freeze + 10-provider `multi-provider-source-v6` cascade) - [SynthID source classifiers](synthid-classifiers.md) (metadata-free OpenAI/Gemini source finding and provider-lineage experiments) - [Source-pipeline classifier model card](source-classify-hf/README.md) (published derivative weights, aggregate evaluation, and intended-use boundary) - [SynthID local detector research](synthid-detector-research.md) diff --git a/docs/known-limitations.md b/docs/known-limitations.md index 50e4fd3..dea1f21 100644 --- a/docs/known-limitations.md +++ b/docs/known-limitations.md @@ -24,13 +24,14 @@ the pixels look rather than read a mark, and none of these paths targets them. `classify` / `classify_pixels` is AI versus camera, not a universal AI detector. UI screenshots and digital art are out of contract. Receipt photographs are -abstained by the 2026-09-02 receipt gate on DEFINITELY: they report `unknown` -with `detector=definitely` instead of a false `ai` (field measurements: -19/59 false verdicts before, 2/59 after; CORD 89/99 before, 0/99 after; the -gate abstains on 7/1,847 ai_test images). A photorealistic AI receipt can -still score as `human`. POSSIBLY is reported as `unknown`. Provider -attribution runs only after DEFINITELY and can abstain when 124-d extraction -refuses the file. Microsoft is not a pixel class. +abstained by `receipt-gate.npz` on DEFINITELY: they report `unknown` with +`detector=definitely` instead of a false `ai` (`59/59` field phone receipts +gated on `receipt-gate.npz`, `0/99` false `ai` on CORD, at a `5/1,847` +`ai_test` cost). A photorealistic AI receipt can still score as `human`. +POSSIBLY is reported as `unknown`. Provider attribution (`multi-provider-source-v6.npz` +across 10 provider families) runs only after DEFINITELY and abstains to `None` +for unsupported generators, degraded post-processing, or images smaller than +`256x256`. Microsoft is not a pixel class. The command is never started by `identify`. A no-signal provenance result stays unknown. This is not a clean verdict and it does not run cleanup. Full guide: diff --git a/docs/module-internals.md b/docs/module-internals.md index dd1306b..e918c01 100644 --- a/docs/module-internals.md +++ b/docs/module-internals.md @@ -784,7 +784,12 @@ The structured walk also treats an exact known AI product in a reachable `claim_generator` as an AI assertion. This covers update chains where the active manifest names only `c2pa-tool` while a validated ingredient names Dreamina, and Firefly chains that identify `Adobe_Firefly` without repeating a digital source -type. Unreachable manifests remain excluded. +type. For Adobe partner-model actions (`com.adobe.type: "remoteProvider.3rdParty"`), +`_structured_manifest_fields` also reads `parameters["com.adobe.digitalSourceType"]` +alongside top-level `action["digitalSourceType"]` while keeping SynthID vendor +inference strictly scoped to signer and claim-generator `identity_strings` so a +parameter-only third-party model name (`gemini-flash`) does not fabricate vendor +provenance. Unreachable manifests remain excluded. The fallback soft-binding scan checks literal identifier presence before its ASCII token-boundary regex. This avoids running every registry regex on files @@ -1488,41 +1493,35 @@ derived results influence detection. ### Photo pixel classifier -[`classify.py`](../src/remove_ai_watermarks/classify.py) is the 2026-08-31 -photo freeze: CLIP-L-ft ridge AND freeze MLP, then 124-d focal heads only on -DEFINITELY. Since 2026-09-02 a linear receipt-document gate runs first on -that DEFINITELY path, on the same CLIP vector: a hit publishes `unknown` -(detector stays `definitely`, provider is not read, 124-d extraction is -skipped). The head ships with the model: since 2026-09-07 under the -STABLE name `receipt-gate.npz` in the Hub snapshot or -`RAIW_CLASSIFY_WEIGHTS` directory, with the legacy dated spelling -`receipt-gate-2026-09-02.npz` still readable and the package asset -`src/remove_ai_watermarks/assets/receipt-gate-2026-09-02.npz` as -the fallback for weights directories frozen before the gate existed (the -head is fitted on the freeze CLIP-L-ft embedding space, so it versions -with the model, not with the code). Head and threshold are read from ONE -artifact: the threshold travels inside the npz and -`classify_from_scores` resolves it from the loaded gate, so a model-side -gate update needs no lib release. `RECEIPT_GATE_THRESHOLD` in -`classify.py` is only the legacy pinned value for the package fallback -and its pinned tests. -Training data and certification live in -`receipt-gate-shipped-2026-09-02/report.json` in the research tree; positives -are CORD-v2 train (800, CC BY 4.0, disjoint from the CORD test split the -eval corpus uses) plus regenerable synthetic receipts, negatives are ai_train -rows. `tests/test_classify.py` pins the asset threshold, the downgrade, and -that the gate skips forensics. The public label is `ai` / `human` / -`unknown`. POSSIBLY is `unknown`. The named class is `openai` / `google` / -`muse-image` / `bytedance` / `None`. `bytedance` is the shared ByteDance -generator lineage (Doubao and Jimeng render with one model family; -measured 83.9% on the frozen test cell). `tc260` covers the REST of -China's generator ecosystem, providers that are peers of -openai/google/meta; no mixed head can honestly name the group, so its -argmax win abstains to `None` (measured 2026-09-07: without the veto -207/379 China test rows would be falsely named openai/google/muse-image). The freeze file keys the Muse -Image head `meta_muse_image`. Tests in `tests/test_classify.py` pin the -gate without downloads and pin that `identify` does not import this -module. +[`classify.py`](../src/remove_ai_watermarks/classify.py) runs the two-stage +photo cascade: Model 1 (2026-08-31 CLIP-L-ft ridge AND freeze MLP), then on +`definitely` only, the receipt-document gate followed by the 10-provider +`multi-provider-source-v6.npz` Model 2 ensemble (`512-d`, pure NumPy, +SHA-256 `87868eea08b8b811999f675186b82b067c4de655981cb7f25114aac00b1dd284`). +Since 2026-09-02 the linear receipt-document gate runs first on that +`definitely` path on the same CLIP vector: a hit publishes `unknown` (detector +stays `definitely`, provider is not read, 512-d extraction is skipped). The +gate ships with the model: since 2026-09-07 under the STABLE name +`receipt-gate.npz` in the Hub snapshot or `RAIW_CLASSIFY_WEIGHTS` directory, +with the legacy dated spelling `receipt-gate-2026-09-02.npz` still readable and +the package asset `src/remove_ai_watermarks/assets/receipt-gate-2026-09-02.npz` +as the fallback for weights directories frozen before the gate existed (the +head is fitted on the freeze CLIP-L-ft embedding space, so it versions with the +model, not with the code). Head and threshold are read from ONE artifact: the +threshold travels inside the npz and `classify_from_scores` resolves it from +the loaded gate, so a model-side gate update needs no lib release. +`RECEIPT_GATE_THRESHOLD` in `classify.py` is only the legacy pinned value for +the package fallback and its pinned tests. +`tests/test_classify.py` pins the asset threshold, the downgrade, and that the +gate skips 512-d extraction. The public label is `ai` / `human` / `unknown`. +POSSIBLY is `unknown`. On `ai`, `provider` is one of the 10 canonical provider +classes (`openai`, `google`, `bytedance`, `flux`, `stable_diffusion`, `meta`, +`midjourney`, `ideogram`, `firefly`, `xai`) or `None` when Model 2 abstains or +the image is under `256x256`. `bytedance` is the shared ByteDance generator +lineage (Doubao and Jimeng); unsupported Chinese generators (`tc260` rest: +Qwen, Yuanbao, Kling, Hailuo, Hunyuan) abstain to `None`. Tests in +`tests/test_classify.py` pin the gate without downloads and pin that `identify` +does not import this module. Weights stay out of git. The Hub snapshot is `wiltodelta/raiw-photo-classify`. `RAIW_CLASSIFY_WEIGHTS` overrides it. The extra is `classify`. The optional @@ -1554,6 +1553,8 @@ runtime loading across three `.npz` bundle schemas: acceptance detector standardized by a 2-layer heteroscedastic skip regime null (`null_h_w`, `null_lin_mu_w`, `null_lin_sig_w` with aligned `[-8.0, 8.0]` clipping), a threshold-invariant `LayerNorm` + `SiLU` skip attribution head, + joint posterior confidence calibration (`sigmoid(min(conf_scale * accept_excess, max(0.0, top1 - top2)))` + when `accept_excess >= 0`, preserving `confidence >= 0.5 <=> label != "unknown"`), and Stage-2 version heads blending packed `HistGradientBoosting` trees with regularized linear logits (`hgb_weight`). - `multi-provider-source-v4` (`512-d`, legacy schema supported via explicit diff --git a/docs/photo-classify-hf/README.md b/docs/photo-classify-hf/README.md index 124ef3b..09fa5d7 100644 --- a/docs/photo-classify-hf/README.md +++ b/docs/photo-classify-hf/README.md @@ -16,24 +16,21 @@ datasets: - detection-datasets/coco --- -# Photo AI-versus-camera classifier (archived) +# Photo AI-versus-camera classifier -> **Archived / legacy as of 2026-09-20. Not recommended for new integrations.** -> This model repository is retained for reproducibility and compatibility with -> existing users. Published weights and historical revisions remain available. -> The documentation and measurements below describe the archived model, not -> a current recommendation. No replacement model is linked at this time. - -Two heads, one call. Model 1 decides whether a **photograph** looks generated -or camera-like. Model 2 names a provider only after Model 1 is DEFINITELY AI. +Two stages, one call. Model 1 decides whether a **photograph** looks generated +or camera-like. When Model 1 returns `definitely` and the receipt-document gate +clears the image, Model 2 attributes the likely rendering pipeline across 10 AI +provider families (`openai`, `google`, `bytedance`, `flux`, `stable_diffusion`, +`meta`, `midjourney`, `ideogram`, `firefly`, `xai`) or abstains to `None`. This is not a SynthID decoder. It is not provenance. It is not a universal -"AI or not" detector for UI or digital art. Receipt photographs are -detected by the bundled receipt gate and abstain to `unknown` rather than -a false `ai`. The Python package +"AI or not" detector for UI or digital art. Receipt photographs are detected by +the bundled receipt gate and abstain to `unknown` rather than a false `ai`. +The Python package [`remove-ai-watermarks`](https://github.com/wiltodelta/remove-ai-watermarks) -loads these files through an explicit `classify` extra. `identify` never -starts this model, including after a no-signal metadata scan. +loads these files through the explicit `classify` extra. `identify` never starts +this model, including after a no-signal metadata scan. Library guide: [photo pixel classification](https://github.com/wiltodelta/remove-ai-watermarks/blob/main/docs/photo-classify.md). @@ -47,85 +44,69 @@ The training catalog is not in this Hub repository and is not on GitHub. ## Intended use -Use it when you have a photographic still and you want a pixel opinion after +Use it when you have a photographic still and want a pixel opinion after metadata is gone: -- `label=ai` plus `provider=openai|google|bytedance|muse-image` on a stripped ChatGPT, - Gemini, ByteDance (Doubao/Jimeng), or Muse Image photograph; a stripped - photograph from the rest of China's generators (Qwen, Kling, ...) - publishes `provider=None` (the residual head abstains) +- `label=ai` plus `provider` in `openai`, `google`, `bytedance`, `flux`, + `stable_diffusion`, `meta`, `midjourney`, `ideogram`, `firefly`, or `xai` + when Model 1 is `definitely`, the receipt gate misses, and Model 2 clears its + calibrated acceptance threshold +- `label=ai, provider=None` on generators outside those 10 families (such as + Qwen, Kling, Yuanbao, Hailuo, or Hunyuan), when Model 2 abstains, or when + 512-d features cannot be extracted (for example below 256x256) - `label=human` on camera photographs at a low false-positive rate -- `label=unknown` when the detector is only POSSIBLY AI -- `label=ai, provider=None` when the detector is DEFINITELY AI but 124-d - features cannot be extracted (unless the receipt gate abstains) +- `label=unknown` when Model 1 is `possibly`, or when the receipt gate abstains + a receipt photograph (`detector=definitely, label=unknown, provider=None`) Do not use it to assert that a file is clean. Do not use it as a legal -authorship test. Do not run Model 2 on every image. +authorship test. Do not treat `provider` as a decoded watermark payload. ## Approach -Content embeddings and forensic residuals answer different questions. +Content embeddings and physics-grounded pixel residuals answer different +questions. CLIP-L, after a light vision-block fine-tune, separates **generated photographs** from **camera photographs**. It does not reliably separate -generated photographs from UI, charts, or illustration; receipts live -inside the AI region too, which is why the shipped receipt gate (below) -abstains them on the DEFINITELY path instead of trying to fix Model 1. A -ridge trained on that embedding at a 1% Open Images false-positive cut is -the strongest Model 1 we measured. A small MLP on the same vectors, ANDed -with the ridge, is the freeze DEFINITELY gate. +generated photographs from UI, charts, or illustration; receipts live inside +the AI region too, which is why the shipped receipt gate abstains them on the +`definitely` path instead of trying to force Model 1 to solve document routing. +A ridge probe trained on that embedding at a 1% Open Images false-positive cut +is paired with a small MLP (`768-512-128-1`) via logical AND to form the +`definitely` gate. -The receipt gate ships in this repository alongside the freeze files, so -it versions with the embedding space it was fitted on. Since 2026-09-07 -the artifact carries the STABLE name `receipt-gate.npz` with the -threshold inside, so head and operating point move together and a gate -update needs no library release; the legacy dated spelling stays -readable, and the Python package carries a fallback copy for weights -directories frozen before the gate existed. +The receipt gate ships in this repository under the stable name +`receipt-gate.npz` with its threshold inside the artifact (plus +`receipt-gate-2026-09-02.npz` for legacy compatibility). -The 124-d bank is a different feature: patch-local residual ratios (FFT band -energy, comb contrast, autocovariance) on 256 px tiles. On that bank, OpenAI -versus Gemini is easy (AUC 0.989 in the research sweep) while "AI or not" is -the wrong job. Firefly and PixelBin sit near Google on those residuals, which -is why a provider finder must keep foreign generators in the test and must -abstain. - -The two heads therefore stay specialized: +Model 2 (`multi-provider-source-v6.npz`, SHA-256 +`87868eea08b8b811999f675186b82b067c4de655981cb7f25114aac00b1dd284`) runs in +pure NumPy (`allow_pickle=False`) on a 512-dimensional physics-grounded +descriptor (`112-d` adaptive SRM residuals + `128-d` phase-resolved modulo-8/16 +sublattice and `8x8` DCT comb features + `144-d` Moisan periodic-plus-smooth +spectral profiles + `96-d` CFA/shot-noise/chromatic-aberration sensor cues + +`32-d` codec and geometry regime features). It decouples regime-standardized +supported-AI acceptance from 10-way provider attribution. ```mermaid flowchart TD - image[Photograph] --> m1[Model 1: CLIP-L-ft ridge AND MLP] - m1 -->|likely_human| human[label human, provider none] - m1 -->|possibly| unk[label unknown, provider none] - m1 -->|definitely| rg[Receipt gate on the same CLIP vector] - rg -->|receipt document| rgu[label unknown, detector definitely] - rg -->|not a receipt| m2[Model 2: 124-d one-vs-rest focal] - m2 -->|openai google muse-image bytedance| named[label ai plus provider] - m2 -->|china group wins| none2[label ai, provider none] - m2 -->|no_ai or extract fail| aiOnly[label ai, provider none] + image["Photograph"] --> m1["Model 1: CLIP-L-ft ridge AND MLP"] + m1 -->|likely_human| human["label human, provider none"] + m1 -->|possibly| unk["label unknown, provider none"] + m1 -->|definitely| rg["Receipt gate on the same CLIP vector"] + rg -->|receipt document| rgu["label unknown, detector definitely, provider none"] + rg -->|not a receipt| m2["Model 2: 512-d v6 10-provider ensemble"] + m2 -->|accepted| named["label ai plus 1 of 10 providers"] + m2 -->|abstained or under 256 px| aiOnly["label ai, provider none"] ``` -CLIP content space is the wrong place to train "UI versus rest" if the -product contract is photographic; that domain remains open. For receipts a -narrower question is solvable in CLIP space: receipts versus AI on the -DEFINITELY path separates perfectly, and the bundled receipt gate (linear -head, CORD-v2 train plus synthetic capture-style positives, threshold -certified on held-out validation) answers it. It abstains to `unknown`; -it is not a receipt-versus-rest specialist and adds no provider class. - -Provider attribution tracks the **renderer**, not the front-end. Bing Image -Creator rows signed Microsoft, OpenAI score as `openai`. Designer rows signed -Microsoft, Google LLC score as `google`. Native Designer is mixed. There is -no Microsoft pixel class -- measured 2026-09-07: a head trained on -Microsoft-brand rows recognizes 8% of its own test cell, and Microsoft -attribution stays a metadata (C2PA) job. `openai` and `google` are provider classes. -`muse-image` is Muse Image output, not a general Meta class. Instagram -`made_with_ai` is not that class. `bytedance` names the shared -ByteDance generator lineage: Doubao and Jimeng render with one model -family (separate heads cross-fire even at 3.5x train mass; the union -holds 83.9% on the frozen test cell). `tc260` covers the REST of China's -generator ecosystem -- producers that are peers of openai/google/meta; -no mixed head can honestly name that group, so its win abstains. +Provider attribution tracks the **renderer**, not the front-end UI. Bing Image +Creator rows rendered by DALL-E score as `openai`; Microsoft Designer rows +rendered by Imagen score as `google`. Microsoft has no separate pixel class and +remains a C2PA metadata attribution. `bytedance` names the shared Doubao and +Jimeng generator lineage. Unsupported Chinese generators (Qwen, Kling, Yuanbao, +Hailuo, Hunyuan) are rejected by the acceptance gate and publish +`provider=None`. ## Architecture @@ -134,117 +115,74 @@ no mixed head can honestly name that group, so its win abstains. - Backbone: `openai/clip-vit-large-patch14` - Fine-tune: last two vision blocks, visual projection, post-layernorm - Preprocess: 224 letterbox, pad RGB `(123, 117, 104)`, BICUBIC, L2-normalized - `get_image_features` (`pooler_output` when present) -- Ridge: linear probe on 768-d vectors, threshold `thr_oi_1pct` = 0.3056 - from the locked `photo_dev_oi` 1% cut -- MLP: `768-512-128-1` with dropout 0.3 / 0.1, threshold 5.9586, 1.67% - photo-dev quantile -- DEFINITELY = ridge AND MLP. POSSIBLY = either. The public `label` is `ai` - only on DEFINITELY. + vision features +- Ridge: linear probe on 768-d vectors, threshold `thr_oi_1pct = 0.3056` +- MLP: `768-512-128-1` with dropout `0.3 / 0.1`, threshold `5.9586` +- `definitely` = ridge AND MLP; `possibly` = either; public `label` is `ai` + only on `definitely` (when not abstained by the receipt gate) ### Model 2 -- Input: 124-d residual vector, or abstain if the image is smaller than - 256 px or the extractor refuses -- Heads: one-vs-rest focal MLP `124-64-1` per class - (`openai`, `google`, `bytedance`, `tc260`, `meta_muse_image`, `no_ai`) -- Decision: a class wins only if it beats `no_ai` by margin 0.30, then argmax - among those that passed -- Public name `muse-image` is the Muse Image class. The freeze file still - keys that head `meta_muse_image`. `bytedance` is the shared - Doubao+Jimeng generator lineage. `tc260` covers the rest of China's - generator ecosystem; no mixed head can honestly name the group, so its - argmax win publishes `provider=None`. `no_ai` is not reported as - `human`; it becomes `provider=None` on an `ai` label (for example FLUX) +- Artifact: `multi-provider-source-v6.npz` (`schema = multi-provider-source-v5`, + SHA-256 `87868eea08b8b811999f675186b82b067c4de655981cb7f25114aac00b1dd284`) +- Input: 512-d physics-grounded residual/sublattice/spectral/sensor/regime + vector, or abstain to `provider=None` when smaller than `256x256` +- Ensemble: 12-output Regime-FiLM residual MLP trunks + packed binary + `HistGradientBoosting` specialists, 2D concordance/veto/pairwise gates, an + 11-channel acceptance detector standardized by a 2-layer heteroscedastic skip + regime null, and a 10-way `LayerNorm + SiLU` skip attribution head across + `openai`, `google`, `bytedance`, `flux`, `stable_diffusion`, `meta`, + `midjourney`, `ideogram`, `firefly`, and `xai` -## Training +## Cascade evaluation -CPU. Two consecutive freeze runs from the same catalog and caches were -byte-identical. +Model 1 + `receipt-gate.npz` + `multi-provider-source-v6.npz` measured on the +photographic cascade benchmark (reporting both the subset strictly disjoint +from all `v6` training and calibration splits and the full benchmark): -| Item | Value | -| --- | --- | -| Catalog identity | sha256 of file bytes, 32,690 listed files | -| CLIP-L embeddings keyed | 26,573 | -| Detector seed | 20260940 | -| Provider seed | 20260956 | -| Sample seed for provider OpenAI/Google draws | 20260821 | -| MLP epochs / width | 40 / 512 | -| Provider focal gamma / epochs | 2.0 / 40 | -| Private UI in train | 0. Replaced with 150 CC Flickr screenshots via Openverse, host `live.staticflickr.com` only | +| Cell | Model 1 `definitely` | Model 2 conditional (strictly unseen by `v6`) | Model 2 conditional (all rows) | +| --- | ---: | ---: | ---: | +| AI-test (`n=1,847`) | 92.4% (`1,707/1,847`) | - | - | +| Open Images fresh (`n=3,000`, expect `None`) | 1.3% (`38/3,000`) | **100.0%** abstain (`8/8`, `0` false provider labels) | **100.0%** abstain (`38/38`, `0` false provider labels) | +| Kodak (`n=24`) | 0.0% (`0/24`) | `0/8` ungated false labels | `0/24` ungated false labels | +| Field phone receipts (`n=60`, `receipt-gate.npz`) | 60.0% (`36/60` -> all `36` gated to `unknown`) | `0/17` ungated false labels | `0/60` ungated false labels | +| OpenAI (`openai`) | 92.4% (`352/381`) | **92.7%** (`102/110`) | **95.2%** (`335/352`) | +| Google (`google`) | 90.5% (`341/377`) | **87.9%** (`109/124`) | **91.2%** (`311/341`) | +| ByteDance (`bytedance`, Doubao+Jimeng) | 97.6% (`621/636`) | **81.4%** (`232/285`, `0` cross-provider errors) | **88.7%** (`551/621`, `0` cross-provider errors) | +| Meta (`meta`, pooled `v2 + v3`) | 71.8% (`199/277`) | **100.0%** (`81/81`) | **100.0%** (`199/199`) | +| FLUX hold-out (`flux`) | 83.0% (`249/300`) | **95.5%** (`63/66` named `flux`) | **94.8%** (`236/249` named `flux`) | +| Unsupported China generators (`tc260` rest, expect `None`) | 95.6% (`109/114`) | **80.6%** abstain (`87/108` `None`) | **80.7%** abstain (`88/109` `None`) | -Flickr licenses in that replacement cell: CC BY 2.0 42, CC BY-NC 2.0 42, -CC BY-SA 2.0 29, CC BY-NC-SA 2.0 28, CC BY-NC-ND 2.0 6, CC BY-ND 2.0 2, -CC0 1. - -The pixel catalog is **not published on the Hub**. Head retrain uses -sha256-keyed CLIP-L and 124-d caches plus `catalog.json` roles. The original -files remain stored privately so embeddings and 124-d features can be rebuilt. -Public named sources in those roles include COCO, Open Images, Kodak, Picsum, -Hugging Face FLUX, Openverse CC Flickr, and Meta Muse API hold-out v3. -In-house labeled OpenAI, Gemini, and TC260 photographs stay private. See -[photo-classify-training.md](https://github.com/wiltodelta/remove-ai-watermarks/blob/main/docs/photo-classify-training.md). - -## Evaluation (run 1 = run 2) - -DEFINITELY is the shipped operating point. - -| Head | Cell | Result | -| --- | --- | ---: | -| Detector DEFINITELY | AI-test | 92.4% (n=1,847) | -| Detector DEFINITELY | Open Images fresh | 1.3% (n=3,000) | -| Detector DEFINITELY | Kodak | 0/24 | -| Detector DEFINITELY | FLUX hold | 83.0% (n=300) | -| Class | OpenAI test | 90.8% (345/380 of 381) | -| Class | Google test | 90.9% (339/373 of 377) | -| Class | Bytedance test (Doubao+Jimeng) | 83.9% (271/323; 83.6% extended with the historical harvest) | -| Class | Muse Image hold-out v2 | 85.7% (66/77 listed 79) | -| Class | Muse Image hold-out v3 | 89.4% (177/198) | -| Class | Muse Image hold-out pooled | 88.4% (243/275 listed 277) | -| Class | meme templates, ungated | Withdrawn: recorded percentage and fraction disagree; source row must be recovered | - -Model 2 must remain gated on DEFINITELY. The historical ungated meme -measurement is not usable evidence until its contradictory counts are reconciled. - -Ridge-only Model 1 at the earlier 1% Open Images cut (before the AND with -the freeze MLP) is documented in the research page: Kodak 0/24, fresh 1.7%, -AI-test 93.0%, FLUX 92.7%, Firefly 94.0%. Nobody in that sweep hit both -≤1% fresh FPR and ≥90% TPR. The freeze AND is stricter on photos (1.3% -DEF) at a small recall cost. +Standalone 10-provider metrics across all 10 provider families (`locked_test` +`N=10,585`, out-of-distribution negatives, and post-processing perturbations) +are documented in +[`source-classify-hf/README.md`](https://github.com/wiltodelta/remove-ai-watermarks/blob/main/docs/source-classify-hf/README.md). ## Limitations -- **Photographs only.** UI, scans of forms, maps, and community digital art - sit in the AI region of CLIP-L. Receipt photographs are abstained by the - 2026-09-02 receipt gate: they report `unknown` with `detector=definitely` - instead of a false `ai` (field false-AI fell from 19/59 to 2/59, CORD - 89/99 to 0/99, at a 7/1,847 ai_test cost). A photorealistic AI receipt - can still score as `human`. -- **Not SynthID.** A `provider=openai` result means the pixels look like an - OpenAI-rendered photograph, not that a payload was decoded. -- **Not provenance.** C2PA, IPTC, and visible marks stay on `identify`. -- **124-d can refuse.** Some sizes and some images yield no vector. The - detector can still return DEFINITELY; provider is then `None`. -- **Microsoft has no head.** Route by renderer, or use C2PA for the - front-end name. -- **Open-world generators.** FLUX is a hold-out at 83% DEF, not 100%. - Unknown generators may land on `ai` with `provider=None`, or miss - DEFINITELY. -- **`bytedance` is one lineage, not two products.** Doubao and Jimeng - render with one ByteDance model family, so the class names the lineage. - The residual China head (`tc260`: Qwen, Yuanbao, Kling, ...) never - publishes a value; per-producer classes return by `ContentProducer` - when their train mass holds its own cells (qwen at 64 train rows: - 27%, stays in the fallback). +- **Photographs only.** UI, scans of forms, maps, and community digital art sit + in the AI region of CLIP-L. Receipt photographs abstain through + `receipt-gate.npz` (`unknown` with `detector=definitely`). A photorealistic + AI receipt can still score as `human`. +- **Not SynthID and not provenance.** A `provider=google` or `provider=openai` + result means the pixels match that rendering/export pipeline, not that an + invisible watermark was decoded. Use `identify` for C2PA, IPTC, and visible + marks. +- **256x256 minimum for Model 2.** Images with shortest side below `256` px + cannot yield 512-d features; Model 1 still runs and `provider` abstains to + `None`. +- **Post-processing sensitivity.** Heavy crop, resize, screenshot recapture, or + aggressive recompression degrades pixel source signatures toward abstention + (`provider=None`). +- **Microsoft has no pixel class.** Route by renderer, or use C2PA for the + front-end product name. ## How to use -Install the extra. First call downloads this repository into the Hugging -Face cache, or reads `RAIW_CLASSIFY_WEIGHTS` if you already have the files. - ```bash uv tool install --force "remove-ai-watermarks[classify]" remove-ai-watermarks classify image.png +remove-ai-watermarks classify image.png --json ``` ```python @@ -255,32 +193,25 @@ result = classify_pixels(Path("image.png")) # result.label, result.detector, result.provider ``` -`device` is a library parameter (`None` / `"auto"` / `"cpu"` / `"cuda"`), -not a CLI option. Pin a Hub revision in production so a later upload cannot -silently change the heads. +`device` is a library parameter (`None` / `"auto"` / `"cpu"` / `"cuda"`), not a +CLI option. `backend="onnx"` selects the optional CPU-only FP32 vision runtime +(`pip install "remove-ai-watermarks[classify-onnx]"`). ## Files in this repository | File | Role | | --- | --- | | `clip-l-ft.pt` | HeadedCLIP state dict (CLIP-L plus unused linear head) | -| `clip-l-ft-vision-fp32.onnx` | Static batch-one vision tower and projection for the optional CPU backend | +| `clip-l-ft-vision-fp32.onnx` | Static batch-one vision tower and projection for `backend="onnx"` | | `probe-weights-clip-l-ft.npz` | Ridge mean, scale, weights, `thr_oi_1pct` | -| `detector.pt` | Freeze MLP | -| `provider.pt` | Focal heads keyed `openai`, `google`, `bytedance`, `tc260`, `meta_muse_image`, `no_ai` | -| `operating-point.json` | Seeds, thresholds, margin | - -The image catalog is not in this repository. +| `detector.pt` | Freeze MLP (`768-512-128-1`) | +| `multi-provider-source-v6.npz` | Pure-NumPy 512-d 10-provider Model 2 bundle (SHA-256 `87868eea08b8b811999f675186b82b067c4de655981cb7f25114aac00b1dd284`) | +| `receipt-gate.npz` | Model-side receipt-document gate with bundled threshold | +| `receipt-gate-2026-09-02.npz` | Legacy receipt-gate artifact kept for pre-0.39 compatibility | +| `operating-point.json` | Freeze metadata, thresholds, provider classes, and file list | ## License -Apache-2.0 for the trained heads and this card. CLIP-L inherits its upstream -license from [`openai/clip-vit-large-patch14`](https://huggingface.co/openai/clip-vit-large-patch14). -Flickr replacement images are CC-licensed per file; they are not redistributed -here. - -## Citation - -Package [`remove-ai-watermarks`](https://github.com/wiltodelta/remove-ai-watermarks). -Protocol and rejected variants: [docs/ai-generated-image-classifiers.md](https://github.com/wiltodelta/remove-ai-watermarks/blob/main/docs/ai-generated-image-classifiers.md). -Provider renderer study: [docs/synthid-classifiers.md](https://github.com/wiltodelta/remove-ai-watermarks/blob/main/docs/synthid-classifiers.md). +Apache-2.0 for the trained heads, NumPy ensemble, and this card. CLIP-L +inherits its upstream license from +[`openai/clip-vit-large-patch14`](https://huggingface.co/openai/clip-vit-large-patch14). diff --git a/docs/photo-classify-hf/operating-point.json b/docs/photo-classify-hf/operating-point.json index 78a9278..b8e584f 100644 --- a/docs/photo-classify-hf/operating-point.json +++ b/docs/photo-classify-hf/operating-point.json @@ -1,11 +1,13 @@ { - "freeze": "2026-08-31", + "freeze": "2026-11-14", + "model1_freeze": "2026-08-31", + "receipt_gate_freeze": "2026-09-07", + "model2_freeze": "2026-11-13", "task": "photo_ai_versus_camera", "not": ["synthid_decoder", "provenance", "universal_ai_detector"], "seeds": { "sample": 20260821, - "detector": 20260940, - "provider": 20260956 + "detector": 20260940 }, "model1": { "backbone": "openai/clip-vit-large-patch14", @@ -19,42 +21,60 @@ "public_ai_label": "definitely_only" }, "model2": { - "feature_width": 124, - "margin": 0.3, - "classes": ["openai", "google", "bytedance", "tc260", "muse-image", "no_ai"], - "class_kind": { - "openai": "provider", - "google": "provider", - "bytedance": "provider", - "tc260": "abstain-veto", - "muse-image": "model", - "no_ai": "negative" - }, - "public_values": ["openai", "google", "bytedance", "muse-image", null], - "bytedance_note": "Doubao and Jimeng render with one ByteDance model family; the class names that shared generator lineage. Measured 2026-09-07 on the frozen test cell: 83.9% (271/323), extended with the historical harvest 83.6% (529/633).", - "tc260_note": "the head covers the REST of China's generator ecosystem -- producers (Qwen, Yuanbao, Kling, ...) that are peers of openai/google/meta, not one vendor. No mixed head can honestly name the group, so its argmax win abstains (provider=None). Measured 2026-09-07: without the veto 207/379 China test rows would be falsely named openai/google/muse-image. Per-producer classes return when their train mass holds their own cells (qwen measured at 64 train rows: 27% -- stays in the fallback).", - "checkpoint_keys": { - "muse-image": "meta_muse_image" - }, - "snapshot_tolerance": "provider.pt snapshots predating bytedance load with five heads; absent heads are skipped and their rows fall to the tc260 veto", + "artifact": "multi-provider-source-v6.npz", + "artifact_sha256": "87868eea08b8b811999f675186b82b067c4de655981cb7f25114aac00b1dd284", + "schema": "multi-provider-source-v5", + "feature_width": 512, + "min_side_px": 256, + "classes": [ + "openai", + "google", + "bytedance", + "flux", + "stable_diffusion", + "meta", + "midjourney", + "ideogram", + "firefly", + "xai" + ], + "public_values": [ + "openai", + "google", + "bytedance", + "flux", + "stable_diffusion", + "meta", + "midjourney", + "ideogram", + "firefly", + "xai", + null + ], + "bytedance_note": "Doubao and Jimeng render with one shared ByteDance generator lineage.", + "abstain_note": "Decoupled 11-channel regime-standardized acceptance detector plus 10-way skip attribution head in pure NumPy. Unsupported generators (such as Qwen, Kling, Yuanbao, Hailuo, Hunyuan) and images below the calibrated acceptance threshold or under 256x256 abstain to provider=null.", "runs_only_after": "definitely" }, "receipt_gate": { "added": "2026-09-02", + "stable_asset": "receipt-gate.npz", + "stable_threshold": 2.0109003260214737, "asset": "receipt-gate-2026-09-02.npz", "threshold": 2.0432573877459697, "runs_only_after": "definitely", "on_hit": "unknown", "head": "linear on the CLIP-L-ft 768-d vector Model 1 already computes", - "train": "CORD-v2 train 800 (CC BY 4.0) + 200 synthetic receipts + 2400 ai_train negatives", - "certified": "min of 1st-percentile scores on CORD validation and a synthetic holdout; no field-receipt pixels in training or threshold selection", - "measured": "field receipts false-AI 19/59 -> 2/59; CORD 89/99 -> 0/99; ai_test DEFINITELY cost 7/1847" + "train": "CORD-v2 train 800 (CC BY 4.0) + 200 synthetic receipts + phone positives (dup3 in 2026-09-07 stable gate) + 2400 ai_train negatives", + "certified": "min of 1st-percentile scores on CORD validation and a synthetic holdout; no field-receipt pixels in threshold selection", + "measured": "field receipts 59/59 gated on stable receipt-gate.npz (57/59 on 2026-09-02 fallback); CORD 99/99 gated; ai_test DEFINITELY cost 5/1847 (0.27%)" }, "files": [ "clip-l-ft.pt", "clip-l-ft-vision-fp32.onnx", "probe-weights-clip-l-ft.npz", "detector.pt", - "provider.pt" + "multi-provider-source-v6.npz", + "receipt-gate.npz", + "receipt-gate-2026-09-02.npz" ] } diff --git a/docs/photo-classify-training.md b/docs/photo-classify-training.md index 412ca67..a62a318 100644 --- a/docs/photo-classify-training.md +++ b/docs/photo-classify-training.md @@ -1,8 +1,11 @@ # Photo classifier training and data -How the 2026-08-31 freeze was fit, what a retrain needs, and where those -files come from. Inference is [photo-classify.md](photo-classify.md). The -campaign log is [ai-generated-image-classifiers.md](ai-generated-image-classifiers.md). +How the 2026-08-31 Model 1 freeze (and legacy 124-d heads) was fit, what a +retrain needs, and where those files come from. Current inference pairs Model 1 +and `receipt-gate.npz` with the 512-d 10-provider `multi-provider-source-v6.npz` +Model 2 ([photo-classify.md](photo-classify.md), +[source-classify.md](source-classify.md)). The campaign log is +[ai-generated-image-classifiers.md](ai-generated-image-classifiers.md). The shipped package does not include the catalog or the embeddings. Fitting the heads again uses the cache pack. The original pixels still have to be diff --git a/docs/photo-classify.md b/docs/photo-classify.md index 3d5ffb5..1af5f06 100644 --- a/docs/photo-classify.md +++ b/docs/photo-classify.md @@ -1,12 +1,12 @@ # Photo pixel classification `classify` gives a pixel opinion on a **photograph**: camera-like, generated, -or unknown, and optionally which renderer it resembles. It is a separate -command from `identify`. Metadata inspection never starts it. +or unknown, and optionally which of 10 AI rendering pipelines it resembles. It +is a separate command from `identify`. Metadata inspection never starts it. This page is the library guide. The Hugging Face model card is the same freeze written for Hub publication: [photo-classify-hf/README.md](photo-classify-hf/README.md). -Campaign notes and rejected variants live in +Campaign notes and historical ablations live in [AI-generated image classifiers](ai-generated-image-classifiers.md). ## When to use it @@ -14,11 +14,11 @@ Campaign notes and rejected variants live in Use `identify` for C2PA, IPTC, visible marks, and other provenance. Use `classify` when those signals are gone and the file is still a photograph. -Do not use `classify` to prove a file is clean. Do not use it on UI or -digital art. Receipt photographs are detected by the receipt-document gate -and abstain to `unknown` instead of a false `ai`; they are still not a -supported verdict. Do not treat `provider=openai` as a decoded SynthID -payload. +Do not use `classify` to prove a file is clean. Do not use it on UI or digital +art. Receipt photographs are detected by the receipt-document gate and abstain +to `unknown` instead of a false `ai`; they are still not a supported verdict. +Do not treat `provider=google` or `provider=openai` as a decoded SynthID or +watermark payload. ## Install and run @@ -48,13 +48,13 @@ Weights are not in git. First call downloads [`wiltodelta/raiw-photo-classify`](https://huggingface.co/wiltodelta/raiw-photo-classify) at the freeze revision pinned in `classify.py`, or reads `RAIW_CLASSIFY_WEIGHTS` if that directory already has `clip-l-ft.pt`, -`probe-weights-clip-l-ft.npz`, `detector.pt`, and `provider.pt`. The training -catalog is not published with the package. Deployments that pre-cache the -snapshot for offline resolution must request exactly -`classify.WEIGHTS_ALLOW_PATTERNS`. That exported list covers both backends; -the online runtime narrows its download to the selected model plus the shared -heads. A partial offline pre-cache fails resolution, even for files the runtime -would otherwise fall back on. +`probe-weights-clip-l-ft.npz`, `detector.pt`, and +`multi-provider-source-v6.npz`. The training catalog is not published with the +package. Deployments that pre-cache the snapshot for offline resolution must +request exactly `classify.WEIGHTS_ALLOW_PATTERNS`. That exported list covers +both backends; the online runtime narrows its download to the selected model +plus the shared heads. A partial offline pre-cache fails resolution, even for +files the runtime would otherwise fall back on. Generate the optional vision-only graph from the exact frozen checkpoint: @@ -66,37 +66,38 @@ uv run --with onnx python scripts/export_photo_classify_onnx.py \ ## What one call returns -One request runs both heads. The receipt gate and Model 2 run only after -Model 1 is DEFINITELY. +One request runs both stages. The receipt gate and Model 2 run only after +Model 1 is `definitely`. ```mermaid flowchart TD - image[Photograph] --> m1[Model 1 CLIP-L-ft ridge AND MLP] + image["Photograph"] --> m1["Model 1 CLIP-L-ft ridge AND MLP"] m1 -->|likely_human| human["label human, provider none"] m1 -->|possibly| unk["label unknown, provider none"] - m1 -->|definitely| rg[Receipt gate on the same CLIP vector] + m1 -->|definitely| rg["Receipt gate on the same CLIP vector"] rg -->|receipt document| rgu["label unknown, detector definitely, provider none"] - rg -->|not a receipt| m2[Model 2 124-d focal heads] - m2 -->|openai google muse-image bytedance| named["label ai plus provider"] - m2 -->|china rest wins| none["label ai, provider none"] - m2 -->|no_ai or extract fail| aiOnly["label ai, provider none"] + rg -->|not a receipt| m2["Model 2 512-d v6 10-provider ensemble"] + m2 -->|accepted| named["label ai plus 1 of 10 providers"] + m2 -->|abstained or extract fail| aiOnly["label ai, provider none"] ``` | Field | Values | Meaning | | --- | --- | --- | -| `label` | `ai`, `human`, `unknown` | Public verdict. `ai` only on DEFINITELY | +| `label` | `ai`, `human`, `unknown` | Public verdict. `ai` only on `definitely` | | `domain` | `photo` | This freeze is photographic only | | `detector` | `definitely`, `possibly`, `likely_human` | Raw Model 1 gate | -| `provider` | `openai`, `google`, `bytedance`, `muse-image`, or `None` | Model 2, only if `label` is `ai` | +| `provider` | `openai`, `google`, `bytedance`, `flux`, `stable_diffusion`, `meta`, `midjourney`, `ideogram`, `firefly`, `xai`, or `None` | Model 2, only if `label` is `ai` | `unknown` with `detector=definitely` is the receipt-document gate abstaining: the file looked AI-generated to Model 1 and like a receipt photograph to the gate, so no verdict is published and no provider is read. `human` is camera-like under this contract, not a proof of authorship. -`unknown` is POSSIBLY, or a domain this freeze does not support. `provider=None` -on an `ai` file is often FLUX or another generator that is not one of the four -heads, or a 124-d extract refusal. +`unknown` is `possibly`, or a domain this freeze does not support. +`provider=None` on an `ai` file means the generator is outside the 10 supported +families (for example Qwen, Kling, Yuanbao, Hailuo, or Hunyuan), the image did +not clear Model 2's calibrated acceptance threshold, or 512-d feature +extraction refused the file (below `256x256`). ## Approach @@ -104,90 +105,82 @@ CLIP-L content embeddings separate generated photographs from camera photographs. They do not separate generated photographs from receipts or UI. A ridge on fine-tuned CLIP-L (last two vision blocks, 224 letterbox) is Model 1. A small MLP on the same vectors, ANDed with the ridge, is the freeze -DEFINITELY gate. +`definitely` gate. -Provider attribution uses a different feature: 124-d residual ratios on 256 px -patches. OpenAI versus Gemini is a strong split there. "AI or not" is the -wrong job on that bank, which is why Model 2 is gated. +Provider attribution uses the pure-NumPy `multi-provider-source-v6.npz` bundle +on a 512-dimensional physics-grounded descriptor (adaptive SRM residuals, +phase-resolved modulo-8/16 sublattice and `8x8` DCT comb features, Moisan +spectral profiles, CFA/sensor cues, and a 32-d codec/geometry regime block). It +decouples regime-standardized supported-AI acceptance from 10-way provider +attribution and runs only after Model 1 returns `definitely` and the receipt +gate misses. -Provider names the renderer, not the product UI. Bing Image Creator signed -Microsoft, OpenAI scores `openai`. Designer signed Microsoft, Google LLC -scores `google`. There is no Microsoft pixel class, and that is measured, -not assumed (2026-09-07: a head trained on 114 Microsoft-brand rows -recognizes 8% of its own test cell and names a fresh Copilot generation -`openai`): Microsoft's products render with other vendors' models, so -Microsoft attribution is metadata, not pixels. `openai` and `google` are -provider classes. `muse-image` is Muse Image output, not a general Meta -class. `tc260` covers the REST of China's generator ecosystem, producers -that are peers of openai/google/meta, not one producer: Qwen, Yuanbao, -Kling, and others sit behind that residual class. No mixed head can -honestly name that group, so its win abstains: China-generated content -from those producers publishes `provider=None` until per-producer classes -exist. `bytedance` is the shared ByteDance generator lineage: Doubao and -Jimeng render with one model family (measured 2026-09-07: separate heads -cross-fire even at 3.5x train mass, the union holds its cell), so the -class names the lineage, not the app that signed. +Provider names the renderer, not the product UI. Bing Image Creator rendered by +DALL-E scores as `openai`; Microsoft Designer rendered by Imagen scores as +`google`. There is no Microsoft pixel class (a head trained on Microsoft-brand +rows recognizes 8% of its own test cell and names a fresh Copilot generation +`openai`): Microsoft's products render with other vendors' models, so Microsoft +attribution is metadata, not pixels. `bytedance` is the shared Doubao and +Jimeng generator lineage. Unsupported Chinese generators (Qwen, Yuanbao, Kling, +Hailuo, Hunyuan) abstain to `provider=None`. ## Evaluation -Two CPU retrains were byte-identical. DEFINITELY is the shipped cut. +Model 1 + `receipt-gate.npz` + `multi-provider-source-v6.npz` on the +photographic cascade benchmark (reporting both the subset strictly disjoint +from all `v6` training/calibration splits and all rows): -| Head | Cell | Result | -| --- | --- | ---: | -| Detector DEFINITELY | AI-test | 92.4% (n=1,847) | -| Detector DEFINITELY | Open Images fresh | 1.3% (n=3,000) | -| Detector DEFINITELY | Kodak | 0/24 | -| Detector DEFINITELY | FLUX hold | 83.0% (n=300) | -| Class | OpenAI | 90.8% (345/380 of 381) | -| Class | Google | 90.9% (339/373 of 377) | -| Class | Bytedance (Doubao+Jimeng lineage) | 83.9% (271/323 of 323; 83.6% extended 529/633 with the historical harvest) | -| Class | Muse Image hold-out v3 | 89.4% (177/198) | -| Class | Muse Image hold-out pooled | 88.4% (243/275 listed 277) | -| Class | meme templates, ungated | 29.1% leak | - -The ungated meme row is why Model 2 never runs on `human` or `unknown`. +| Stage | Cell | Result (strictly unseen by `v6`) | Result (all rows) | +| --- | --- | ---: | ---: | +| Model 1 `definitely` | AI-test | 92.5% (`630/681`) | 92.4% (`1,707/1,847`) | +| Model 1 `definitely` | Open Images fresh | 1.1% (`8/702`) | 1.3% (`38/3,000`) | +| Model 1 `definitely` | Kodak | `0/8` | `0/24` | +| Model 1 `definitely` | FLUX hold-out | 84.6% (`66/78`) | 83.0% (`249/300`) | +| Model 2 conditional | Open Images fresh (expect `None`) | **100.0%** abstain (`8/8`, `0` false labels) | **100.0%** abstain (`38/38`, `0` false labels) | +| Model 2 conditional | OpenAI (`openai`) | **92.7%** (`102/110`) | **95.2%** (`335/352`) | +| Model 2 conditional | Google (`google`) | **87.9%** (`109/124`) | **91.2%** (`311/341`) | +| Model 2 conditional | ByteDance (`bytedance`, Doubao+Jimeng) | **81.4%** (`232/285`, `0` cross-provider errors) | **88.7%** (`551/621`, `0` cross-provider errors) | +| Model 2 conditional | Meta (`meta`, pooled `v2 + v3`) | **100.0%** (`81/81`) | **100.0%** (`199/199`) | +| Model 2 conditional | FLUX hold-out (`flux`) | **95.5%** (`63/66`) | **94.8%** (`236/249`) | +| Model 2 conditional | Unsupported China generators (`tc260` rest, expect `None`) | **80.6%** abstain (`87/108`) | **80.7%** abstain (`88/109`) | ## Receipt-document gate -Added 2026-09-02. A linear head on the CLIP-L-ft vector Model 1 already -computes, trained on CORD-v2 train (800, CC BY 4.0) plus 200 synthetic -capture-style receipts against 2,400 ai_train negatives. The threshold is -certified on CORD validation plus a synthetic holdout; no field-receipt -pixels were used for training or the threshold. On DEFINITELY only: a hit -publishes `unknown` and skips the 124-d provider pass. +Added 2026-09-02 and updated 2026-09-07 under the stable name +`receipt-gate.npz`. A linear head on the CLIP-L-ft vector Model 1 already +computes, certified on CORD validation plus a synthetic holdout with no +field-receipt pixels in threshold selection. On `definitely` only: a hit +publishes `unknown` and skips the 512-d Model 2 pass. | Cell | Result | | --- | ---: | -| Field phone receipts, false `ai` before | 19/59 -> **2/59** | -| Field phone receipts, gated to `unknown` | 57/59 | +| Field phone receipts gated (`receipt-gate.npz`) | **59/59** (`57/59` on 2026-09-02 fallback) | | CORD photographs (99) | **0/99** false `ai` | -| ai_test DEFINITELY cost | 7/1,847 (0.38%) | +| `ai_test` `definitely` cost | `5/1,847` (`0.27%`) | -Artifacts: `receipt-gate-shipped-2026-09-02/report.json` and -`receipt-gate-retrain-2026-09-07/report.json` (private research tree). -The head ships with the model under the STABLE name `receipt-gate.npz` -in the Hub snapshot with the threshold inside the artifact (legacy dated -spelling still readable, package asset as the fallback for pre-gate -freezes); the operating point records it in +The head ships with the model under the stable name `receipt-gate.npz` in the +Hub snapshot with the threshold inside the artifact (legacy dated spelling +still readable, package asset as the fallback for pre-gate freezes); the +operating point records it in [photo-classify-hf/operating-point.json](photo-classify-hf/operating-point.json). ## Limits -- Receipts abstain through the 2026-09-02 gate (below); a photorealistic AI - receipt can still score as `human`. UI, scans, maps, and community art - remain out of contract. +- Receipts abstain through `receipt-gate.npz`; a photorealistic AI receipt can + still score as `human`. UI, scans, maps, and community art remain out of + contract. - Not SynthID, not C2PA, not `is_ai_generated`. -- Images under 256 px cannot yield 124-d features, so provider abstains. -- FLUX is a hold-out at 83% DEF, not a named provider class. -- China's generator ecosystem splits by generator: `bytedance` (the - shared Doubao+Jimeng lineage) is named; the rest (Qwen, Yuanbao, - Kling, ...) abstains until per-producer train mass holds its own cells - (qwen measured at 64 train rows: 27%, stays in the fallback). +- Images with shortest side under `256` px cannot yield 512-d features, so + `provider` abstains to `None`. +- Heavy crop, resize, screenshot recapture, or aggressive recompression + degrades 512-d source signatures toward abstention (`provider=None`). +- Unsupported generators outside the 10 named families (for example Qwen, + Yuanbao, Kling, Hailuo, Hunyuan) abstain to `provider=None`. `identify`, `has_invisible_target`, `all`, and `invisible` do not import this module. A no-signal provenance result stays unknown until you call `classify` yourself. -Training data, the retrain pack (caches only, no images), and the training -scripts in `wiltodelta/raiw-classifier-training` are documented in -[photo-classify-training.md](photo-classify-training.md). +Model 1 training data and cache layout are documented in +[photo-classify-training.md](photo-classify-training.md); standalone 10-provider +Model 2 details live in [source-classify.md](source-classify.md). diff --git a/docs/python-api.md b/docs/python-api.md index c1c6412..dd01270 100644 --- a/docs/python-api.md +++ b/docs/python-api.md @@ -284,13 +284,15 @@ print(result.label, result.detector, result.provider) ``` `label` is `ai` only on a DEFINITELY detector result (ridge AND freeze MLP). -POSSIBLY is `unknown`. Camera-like photographs are `human`. `provider` is -`openai`, `google`, `bytedance`, or `muse-image` only when `label` is `ai` -and the 124-d head beats `no_ai` by the freeze margin. `bytedance` names -the shared Doubao+Jimeng generator lineage; the rest of China's -generators (Qwen, Kling, ...) have no honest class yet and their residual -head abstains to `None`. Otherwise it is `None`, including -when 124-d extraction refuses the file. +POSSIBLY is `unknown`. Camera-like photographs are `human`. `provider` is one +of the 10 canonical providers (`openai`, `google`, `bytedance`, `flux`, +`stable_diffusion`, `meta`, `midjourney`, `ideogram`, `firefly`, `xai`) only +when `label` is `ai`, the receipt gate misses, and the 512-d +`multi-provider-source-v6.npz` Model 2 ensemble clears its calibrated +acceptance threshold. `bytedance` names the shared Doubao+Jimeng generator +lineage; generators outside those 10 families (Qwen, Kling, Yuanbao, ...) +abstain to `None`. Otherwise `provider` is `None`, including when 512-d +extraction refuses images smaller than `256x256`. `device` is a library parameter: `None` / `"auto"` detect, `"cpu"` or `"cuda"` pin. It is not a CLI option. `backend="onnx"` selects the optional CPU-only diff --git a/docs/release-and-distribution.md b/docs/release-and-distribution.md index 34d1cc5..96dfdf7 100644 --- a/docs/release-and-distribution.md +++ b/docs/release-and-distribution.md @@ -88,12 +88,13 @@ release fan-out. It holds the photo-classify freeze weights. The library extra `classify` downloads that snapshot on first use, or reads `RAIW_CLASSIFY_WEIGHTS`. Update the Hub repo only with `.github/workflows/publish-photo-classify-hf.yml` (`workflow_dispatch`, -type `publish`). Full mode downloads the four weight files from the GitHub -Release tag `photo-classify-freeze-2026-08-31` (or the tag you pass), exports -the static FP32 vision-only ONNX graph from `clip-l-ft.pt`, and uploads all five -files with the card in `docs/photo-classify-hf/`. Card mode updates -the README, `operating-point.json`, and the receipt-gate head staged from -the package assets; freeze weights are untouched. A library version bump +type `publish`). Full mode downloads the frozen Model 1 + `receipt-gate.npz` +files from `photo-classify-freeze-2026-09-07` and `multi-provider-source-v6.npz` +(verified by SHA-256) from `source-classify-v6-freeze-2026-11-13`, exports the +static FP32 vision-only ONNX graph from `clip-l-ft.pt`, and uploads the full +allowlist with the card in `docs/photo-classify-hf/`. Card mode updates +the README, `operating-point.json`, and the fallback receipt-gate head staged +from the package assets; freeze weights are untouched. A library version bump alone does not upload new heads -- bump the pinned Hub revision when a new head must reach installed clients. Pin a Hub revision in production so a later freeze cannot silently change installed clients. diff --git a/scripts/publish_photo_classify_hf.py b/scripts/publish_photo_classify_hf.py index e23ca12..3428a11 100644 --- a/scripts/publish_photo_classify_hf.py +++ b/scripts/publish_photo_classify_hf.py @@ -2,8 +2,9 @@ """Publish the photo-classify freeze to Hugging Face wiltodelta/raiw-photo-classify. Manual. Not a library release step. Weights are not in git: pass --src, a -directory that holds clip-l-ft.pt, clip-l-ft-vision-fp32.onnx, and the probe, -with detector.pt and provider.pt either at the root or in run1/. +directory that holds clip-l-ft.pt, clip-l-ft-vision-fp32.onnx, +probe-weights-clip-l-ft.npz, multi-provider-source-v6.npz, and detector.pt +(either at the root or in run1/). uv run python scripts/publish_photo_classify_hf.py --src DIR uv run python scripts/publish_photo_classify_hf.py --card-only @@ -11,13 +12,16 @@ with detector.pt and provider.pt either at the root or in run1/. Needs HF_TOKEN with write role. The GitHub Action publish-photo-classify-hf.yml injects secrets.HF_TOKEN. -Card mode uploads the README, operating-point.json, and the receipt-gate -head (staged from the package assets) without touching the freeze weights. +Card mode uploads the README, operating-point.json, and the fallback +receipt-gate head (staged from the package assets) without touching the freeze +weights. """ from __future__ import annotations import argparse +import hashlib +import json import logging import os import shutil @@ -33,13 +37,16 @@ CLIP_FILE = "clip-l-ft.pt" CLIP_ONNX_FILE = "clip-l-ft-vision-fp32.onnx" PROBE_FILE = "probe-weights-clip-l-ft.npz" DETECTOR_FILE = "detector.pt" -PROVIDER_FILE = "provider.pt" -WEIGHT_FILES = (CLIP_FILE, CLIP_ONNX_FILE, PROBE_FILE, DETECTOR_FILE, PROVIDER_FILE) +RETIRED_FILES = ("provider.pt",) GATE_FILE = "receipt-gate-2026-09-02.npz" GATE_STABLE_FILE = "receipt-gate.npz" REPO_ROOT = Path(__file__).resolve().parents[1] GATE_SOURCE = REPO_ROOT / "src" / "remove_ai_watermarks" / "assets" / GATE_FILE CARD_DIR = REPO_ROOT / "docs" / "photo-classify-hf" +_OPERATING_POINT = json.loads((CARD_DIR / "operating-point.json").read_text(encoding="utf-8")) +PROVIDER_FILE: str = _OPERATING_POINT["model2"]["artifact"] +PROVIDER_SHA256: str = _OPERATING_POINT["model2"]["artifact_sha256"] +WEIGHT_FILES = (CLIP_FILE, CLIP_ONNX_FILE, PROBE_FILE, DETECTOR_FILE, PROVIDER_FILE) def weight_paths(src: Path) -> dict[str, Path]: @@ -83,8 +90,17 @@ def _place(src: Path, dest: Path) -> None: shutil.copy2(src, dest) +def _verify_sha256(path: Path, expected: str) -> None: + with path.open("rb") as handle: + actual = hashlib.file_digest(handle, "sha256").hexdigest() + if actual != expected: + raise SystemExit(f"SHA-256 mismatch for {path.name}: expected {expected}, got {actual}") + + def stage_weights(dest: Path, src: Path) -> None: - for name, path in weight_paths(src).items(): + paths = weight_paths(src) + _verify_sha256(paths[PROVIDER_FILE], PROVIDER_SHA256) + for name, path in paths.items(): _place(path, dest / name) log.info("stage %s (%s bytes)", name, path.stat().st_size) stable_gate = src / GATE_STABLE_FILE @@ -100,6 +116,7 @@ def publish(stage: Path, *, token: str, message: str) -> str: token=token, message=message, allow_patterns=["README.md", "operating-point.json", *WEIGHT_FILES, GATE_FILE, GATE_STABLE_FILE], + delete_patterns=RETIRED_FILES, ) diff --git a/skills/remove-ai-watermarks/references/commands.md b/skills/remove-ai-watermarks/references/commands.md index f855467..706c3ff 100644 --- a/skills/remove-ai-watermarks/references/commands.md +++ b/skills/remove-ai-watermarks/references/commands.md @@ -50,12 +50,15 @@ remove-ai-watermarks classify image.png --json Pixel classifier, needs the `classify` extra. It is NOT provenance: it guesses from pixels alone and `identify` never runs it. The CLI has no ONNX flag; the optional CPU ONNX runtime is library-only (`backend="onnx"`) and needs -`classify-onnx` (since CLI 0.40.0). Labels are `ai` (both models +`classify-onnx` (since CLI 0.40.0). Labels are `ai` (both Model 1 heads agree), `human`, and `unknown` -- `unknown` is an abstention, not a negative. Photographed receipts abstain to `unknown` through the bundled receipt gate -(since CLI 0.38.0), so a receipt is not reported as `ai`. Offer `classify` -only when `identify` found no signal and the user still wants a guess, and -report it as a guess. +(since CLI 0.38.0), so a receipt is not reported as `ai`. When `label` is `ai`, +Model 2 (`multi-provider-source-v6.npz`) attributes `provider` across 10 +families (`openai`, `google`, `bytedance`, `flux`, `stable_diffusion`, `meta`, +`midjourney`, `ideogram`, `firefly`, `xai`) or abstains to `none` (`null` in +JSON). Offer `classify` only when `identify` found no signal and the user still +wants a guess, and report it as a guess. ```bash remove-ai-watermarks classify-source image.png diff --git a/src/remove_ai_watermarks/_internal/c2pa.py b/src/remove_ai_watermarks/_internal/c2pa.py index 284ed6c..b36464e 100644 --- a/src/remove_ai_watermarks/_internal/c2pa.py +++ b/src/remove_ai_watermarks/_internal/c2pa.py @@ -642,6 +642,11 @@ def _structured_manifest_fields(store: dict[str, Any]) -> dict[str, Any]: source_type = action.get("digitalSourceType") if isinstance(source_type, str): source_types.append(source_type) + parameters = action.get("parameters") + if isinstance(parameters, dict): + adobe_source_type = cast("dict[object, object]", parameters).get("com.adobe.digitalSourceType") + if isinstance(adobe_source_type, str): + source_types.append(adobe_source_type) software_agent = action.get("softwareAgent") if isinstance(software_agent, dict): name = cast("dict[object, object]", software_agent).get("name") diff --git a/src/remove_ai_watermarks/_internal/forensic_124d.py b/src/remove_ai_watermarks/_internal/forensic_124d.py index e42a5db..47a105f 100644 --- a/src/remove_ai_watermarks/_internal/forensic_124d.py +++ b/src/remove_ai_watermarks/_internal/forensic_124d.py @@ -1,4 +1,4 @@ -"""124-d patch residual features for the frozen provider heads. +"""124-d patch residual features for the source-pipeline feature banks. Lifted from the 2026-08-31 freeze extractor. The vector is ratios on lattice-aligned 256 px patches: FFT band energy, comb contrast, and residual diff --git a/src/remove_ai_watermarks/classify.py b/src/remove_ai_watermarks/classify.py index 6be2916..12455a4 100644 --- a/src/remove_ai_watermarks/classify.py +++ b/src/remove_ai_watermarks/classify.py @@ -1,5 +1,5 @@ # pyright: reportUnknownMemberType=false, reportUnknownVariableType=false, reportUnknownArgumentType=false -"""Metadata-free photo classifier: Model 1 then gated Model 2. +"""Metadata-free photo classifier: Model 1 then gated 10-provider Model 2. This is not provenance and is not a cleanup command. ``identify``, ``has_invisible_target``, and ``all`` must not import this module. @@ -14,7 +14,26 @@ import os import threading from dataclasses import dataclass from pathlib import Path -from typing import Any, Literal +from typing import Any, Literal, TypeAlias + +from remove_ai_watermarks.source_classify import ( + ALL_PROVIDER_CLASSES as PROVIDER_CLASSES, +) +from remove_ai_watermarks.source_classify import ( + MIN_SIDE, + SourceClassification, + classify_source, + verify_weights_sha256, +) +from remove_ai_watermarks.source_classify import ( + MODEL_FILE as PROVIDER_FILE, +) +from remove_ai_watermarks.source_classify import ( + MODEL_SHA256 as PROVIDER_SHA256, +) +from remove_ai_watermarks.source_classify import ( + ProviderClass as _ProviderClass, +) log = logging.getLogger(__name__) @@ -27,18 +46,13 @@ CLIP_FILE = "clip-l-ft.pt" CLIP_ONNX_FILE = "clip-l-ft-vision-fp32.onnx" PROBE_FILE = "probe-weights-clip-l-ft.npz" DETECTOR_FILE = "detector.pt" -PROVIDER_FILE = "provider.pt" OPERATING_POINT_FILE = "operating-point.json" _COMMON_WEIGHT_FILES = (PROBE_FILE, DETECTOR_FILE, PROVIDER_FILE) _WEIGHT_FILES = (CLIP_FILE, *_COMMON_WEIGHT_FILES) # 2026-09-02 receipt-document gate: linear head on the same CLIP-L-ft # vector, trained on CORD-v2 train (800, CC BY 4.0) plus 200 synthetic -# capture-style receipts against 2,400 ai_train negatives. Threshold is the -# min of the 1st-percentile scores on CORD validation and a synthetic -# holdout; no field-receipt pixels were used for training or the threshold. -# The head versions with the model (Hub snapshot or RAIW_CLASSIFY_WEIGHTS -# directory); the package asset is the fallback for pre-gate freezes. +# capture-style receipts against 2,400 ai_train negatives. # 2026-09-07: the gate is MODEL-SIDE. The weights directory carries the # artifact under the STABLE name ``receipt-gate.npz`` with the threshold # inside; the dated name below stays readable as the legacy spelling, and @@ -64,41 +78,18 @@ WEIGHTS_ALLOW_PATTERNS: tuple[str, ...] = ( RECEIPT_GATE_FILE, ) -# 2026-08-31 freeze operating point. Ridge threshold is also in the probe file; -# the runtime prefers the file when weights load. +# 2026-08-31 Model 1 freeze operating point. Ridge threshold is also in the probe +# file; the runtime prefers the file when weights load. Model 2 thresholds travel +# inside multi-provider-source-v6.npz. MLP_THRESHOLD = 5.9586493237495395 RIDGE_THRESHOLD = 0.3056212276800537 -PROVIDER_MARGIN = 0.30 CLIP_WIDTH = 768 -# Checkpoint keys in provider.pt, the SUPERSET across snapshot generations. -# openai/google are provider classes; meta_muse_image is Muse Image; -# bytedance is the shared ByteDance generator lineage (Doubao and Jimeng -# render with the same model family -- measured 2026-09-07: separate heads -# cross-fire 32/22 ways even at 3.5x train mass, the union holds 83.9% -# on the frozen test cell). tc260 is NOT one class of anything: it covers -# the REST of China's generator ecosystem (Qwen, Yuanbao, Kling, ..., -# producers that are peers of openai/google/meta), whose heads do not -# exist yet at honest mass, so its argmax win abstains (provider=None). -# The loader tolerates older snapshots that predate bytedance: a head -# absent from provider.pt is skipped, and those rows fall to the veto. -# Measured on the shipped weights: deleting the veto from the argmax -# would falsely name 207/379 China test rows openai/google/muse-image -# (153 of them muse-image); the veto leaves every other cell -# byte-identical (openai 345/380, google 339/373, meta v3 177/198). -PROVIDER_LABELS = ("openai", "google", "bytedance", "tc260", "meta_muse_image", "no_ai") DetectorLevel = Literal["definitely", "possibly", "likely_human"] PixelLabel = Literal["ai", "human", "unknown"] PixelDomain = Literal["photo"] -PixelProvider = Literal["openai", "google", "muse-image", "bytedance"] +PixelProvider: TypeAlias = _ProviderClass ClassifierBackend = Literal["torch", "onnx"] -PUBLIC_PROVIDER: dict[str, PixelProvider | None] = { - "openai": "openai", - "google": "google", - "bytedance": "bytedance", - "tc260": None, - "meta_muse_image": "muse-image", -} _runtime: _Runtime | None = None _runtime_lock = threading.Lock() @@ -204,34 +195,27 @@ def label_for(level: DetectorLevel) -> PixelLabel: return "unknown" -def provider_from_scores(scores: dict[str, float], *, margin: float = PROVIDER_MARGIN) -> PixelProvider | None: - """Argmax among the named classes that beat ``no_ai`` by ``margin``. - - Candidates are the heads the LOADED snapshot actually carries, so - older provider.pt files without a generation's newest class keep - working (their rows fall to the tc260 veto and abstain). The tc260 - head joins the argmax only as a group veto: it covers the rest of - China's generator ecosystem, producers that are peers of - openai/google/meta, so until per-producer classes exist its win - abstains and ``None`` is published instead of a false company claim. - """ - no_ai = scores["no_ai"] - ai_names = [name for name in scores if name != "no_ai"] - passed = [name for name in ai_names if scores[name] > no_ai + margin] - if not passed: +def provider_from_source( + result: SourceClassification | PixelProvider | Literal["unknown"] | None, +) -> PixelProvider | None: + """Resolve a Model 2 source-pipeline result onto a public provider or ``None``.""" + if result is None: return None - best = max(passed, key=lambda name: scores[name]) - return PUBLIC_PROVIDER[best] + label: str = result if isinstance(result, str) else result.label + if label == "unknown": + return None + if label not in PROVIDER_CLASSES: + raise ValueError(f"unsupported pixel provider {label!r}") + return label # type: ignore[return-value] def classify_from_scores( ridge_score: float, mlp_score: float, - provider_scores: dict[str, float] | None, + provider: SourceClassification | PixelProvider | Literal["unknown"] | None = None, *, ridge_threshold: float = RIDGE_THRESHOLD, mlp_threshold: float = MLP_THRESHOLD, - provider_margin: float = PROVIDER_MARGIN, receipt_score: float | None = None, receipt_threshold: float | None = None, ) -> PixelClassification: @@ -254,10 +238,10 @@ def classify_from_scores( label = label_for(level) if level == "definitely" and receipt_score is not None and receipt_score >= receipt_threshold: return PixelClassification(label="unknown", domain="photo", detector=level, provider=None) - provider: PixelProvider | None = None - if label == "ai" and provider_scores is not None: - provider = provider_from_scores(provider_scores, margin=provider_margin) - return PixelClassification(label=label, domain="photo", detector=level, provider=provider) + resolved_provider: PixelProvider | None = None + if label == "ai": + resolved_provider = provider_from_source(provider) + return PixelClassification(label=label, domain="photo", detector=level, provider=resolved_provider) def classify_pixels( @@ -266,10 +250,10 @@ def classify_pixels( device: str | None = None, backend: ClassifierBackend = "torch", ) -> PixelClassification: - """Run Model 1 then, on DEFINITELY, the receipt gate and Model 2. + """Run Model 1 then, on DEFINITELY, the receipt gate and 10-provider Model 2. Never called by ``identify``. A DEFINITELY verdict that the receipt gate - accepts is published as ``unknown`` before the 124-d provider pass. + accepts is published as ``unknown`` before the 512-d Model 2 pass. """ if not is_available(): raise RuntimeError(f"pixel classification requires the classify extra. Install: pip install {CLASSIFY_EXTRA}") @@ -283,6 +267,9 @@ def classify_pixels( runtime = _get_runtime(device, backend) from PIL import Image + from remove_ai_watermarks import image_io + + image_io._register_heif() # pyright: ignore[reportPrivateUsage] with Image.open(path) as image: rgb = image.convert("RGB") clip_vector = _embed(runtime, rgb) @@ -296,20 +283,15 @@ def classify_pixels( ) gate = _load_receipt_gate(runtime.weights_dir) r_score = receipt_gate_score(clip_vector, gate) if level == "definitely" else None - provider_scores = None + source_result: SourceClassification | None = None if r_score is not None and r_score < gate["threshold"]: - forensic = _forensic(rgb) - if forensic is not None: - provider_scores = _provider_scores(runtime, forensic) - else: - log.info("124-d features unavailable for %s, provider abstains", path) + source_result = _run_model2(runtime, rgb, path=path) result = classify_from_scores( ridge, mlp, - provider_scores, + source_result, ridge_threshold=runtime.ridge_threshold, mlp_threshold=runtime.mlp_threshold, - provider_margin=runtime.provider_margin, receipt_score=r_score, receipt_threshold=gate["threshold"], ) @@ -322,17 +304,18 @@ def classify_pixels( class _Runtime: device: Any backend: ClassifierBackend + weights_override: str | None clip_model: Any processor: Any detector: Any - provider_heads: dict[str, Any] + provider_path: Path ridge_mean: Any ridge_scale: Any ridge_weights: Any ridge_threshold: float mlp_threshold: float - provider_margin: float weights_dir: Path | None + provider_verified: bool = False def _resolve_device(device: str | None) -> Any: @@ -418,17 +401,17 @@ def _require_files(folder: Path, *, backend: ClassifierBackend = "torch") -> Non raise RuntimeError( "pixel classification weights are missing " f"({', '.join(missing)}). Set {WEIGHTS_ENV} to a directory with the " - f"2026-08-31 freeze files, or install {CLASSIFY_EXTRA} and allow the " + f"freeze files, or install {CLASSIFY_EXTRA} and allow the " f"Hugging Face download from {WEIGHTS_REPO}." ) -def _operating_point(folder: Path) -> tuple[float, float]: +def _operating_point(folder: Path) -> float: path = folder / OPERATING_POINT_FILE if not path.is_file(): - return MLP_THRESHOLD, PROVIDER_MARGIN + return MLP_THRESHOLD payload = json.loads(path.read_text()) - return float(payload["model1"]["mlp_threshold"]), float(payload["model2"]["margin"]) + return float(payload["model1"]["mlp_threshold"]) def _build_detector() -> Any: @@ -445,40 +428,22 @@ def _build_detector() -> Any: ) -def _build_provider_head() -> Any: - from torch import nn - - return nn.Sequential( - nn.Linear(124, 64), - nn.ReLU(), - nn.Dropout(0.2), - nn.Linear(64, 1), - ) - - def _load_runtime(device: Any, backend: ClassifierBackend = "torch") -> _Runtime: import numpy as np import torch from remove_ai_watermarks._internal.clip_l_ft import load_headed_clip, load_onnx_vision, load_processor + override = os.environ.get(WEIGHTS_ENV) folder = _weights_dir(backend) _require_files(folder, backend=backend) probe = np.load(_weight_path(folder, PROBE_FILE)) detector = _build_detector() detector.load_state_dict(torch.load(_weight_path(folder, DETECTOR_FILE), map_location="cpu", weights_only=True)) detector.to(device).train(False) - packed = torch.load(_weight_path(folder, PROVIDER_FILE), map_location="cpu", weights_only=True) - heads = {} - for name in PROVIDER_LABELS: - if name not in packed: - log.info("provider head %s absent from this snapshot; rows it would name abstain", name) - continue - head = _build_provider_head() - head.load_state_dict(packed[name]) - heads[name] = head.to(device).train(False) + provider_path = _weight_path(folder, PROVIDER_FILE).resolve() ridge_threshold = float(probe["thr_oi_1pct"]) - mlp_threshold, provider_margin = _operating_point(folder) + mlp_threshold = _operating_point(folder) log.info("loaded photo-classify freeze from %s", folder) clip_model = ( load_onnx_vision(_weight_path(folder, CLIP_ONNX_FILE)) @@ -488,16 +453,16 @@ def _load_runtime(device: Any, backend: ClassifierBackend = "torch") -> _Runtime return _Runtime( device=device, backend=backend, + weights_override=override, clip_model=clip_model, processor=load_processor(), detector=detector, - provider_heads=heads, + provider_path=provider_path, ridge_mean=np.asarray(probe["mean"], dtype=np.float64), ridge_scale=np.asarray(probe["scale"], dtype=np.float64), ridge_weights=np.asarray(probe["weights"], dtype=np.float64), ridge_threshold=ridge_threshold, mlp_threshold=mlp_threshold, - provider_margin=provider_margin, weights_dir=folder, ) @@ -506,8 +471,14 @@ def _get_runtime(device: str | None, backend: ClassifierBackend = "torch") -> _R global _runtime resolved = _resolve_device(device) resolved_backend = _resolve_backend(backend, resolved) + override = os.environ.get(WEIGHTS_ENV) with _runtime_lock: - if _runtime is None or _runtime.device != resolved or _runtime.backend != resolved_backend: + if ( + _runtime is None + or _runtime.device != resolved + or _runtime.backend != resolved_backend + or _runtime.weights_override != override + ): _runtime = _load_runtime(resolved, resolved_backend) return _runtime @@ -520,15 +491,6 @@ def _embed(runtime: _Runtime, image: Any) -> Any: return embed_image(runtime.clip_model, runtime.processor, image, runtime.device) -def _forensic(image: Any) -> Any: - import numpy as np - - from remove_ai_watermarks._internal.forensic_124d import image_features - - pixels = np.asarray(image, dtype=np.uint8) - return image_features(pixels) - - def _mlp_score(runtime: _Runtime, clip_vector: Any) -> float: import torch @@ -537,9 +499,18 @@ def _mlp_score(runtime: _Runtime, clip_vector: Any) -> float: return float(runtime.detector(tensor).squeeze().cpu()) -def _provider_scores(runtime: _Runtime, forensic: Any) -> dict[str, float]: - import torch - - tensor = torch.from_numpy(forensic.astype("float32")).unsqueeze(0).to(runtime.device) - with torch.inference_mode(): - return {name: float(head(tensor).squeeze().cpu()) for name, head in runtime.provider_heads.items()} +def _run_model2(runtime: _Runtime, image: Any, *, path: Path | None = None) -> SourceClassification | None: + if min(image.size) < MIN_SIDE: + log.info("source features unavailable for %s (<%d px), provider abstains", path, MIN_SIDE) + return None + if not getattr(runtime, "provider_verified", False): + with _runtime_lock: + if not getattr(runtime, "provider_verified", False): + if not getattr(runtime, "weights_override", None): + verify_weights_sha256(runtime.provider_path, PROVIDER_SHA256) + runtime.provider_verified = True + result = classify_source(image, weights_path=runtime.provider_path) + if result.reason == "feature_unavailable": + log.info("source features unavailable for %s, provider abstains", path) + return None + return result diff --git a/src/remove_ai_watermarks/cli.py b/src/remove_ai_watermarks/cli.py index c4bcb7c..02384ec 100644 --- a/src/remove_ai_watermarks/cli.py +++ b/src/remove_ai_watermarks/cli.py @@ -1779,9 +1779,11 @@ def cmd_identify(ctx: click.Context, source: Path, no_visible: bool, as_json: bo def cmd_classify(source: Path, as_json: bool) -> None: """Classify a photograph as AI or camera-like from pixels. - Runs the frozen photo detector and, only on a DEFINITELY-AI result, the - provider head. This is not provenance. identify never starts this command. - Install: pip install 'remove-ai-watermarks[classify]' + Runs the frozen photo detector and, only on a DEFINITELY-AI result that + clears the receipt gate, the abstaining 10-provider Model 2 head + (openai, google, bytedance, flux, stable_diffusion, meta, midjourney, + ideogram, firefly, xai). This is not provenance. identify never starts + this command. Install: pip install 'remove-ai-watermarks[classify]' """ from remove_ai_watermarks import classify as classify_mod diff --git a/src/remove_ai_watermarks/source_classify.py b/src/remove_ai_watermarks/source_classify.py index 5fd6244..fa5f3d7 100644 --- a/src/remove_ai_watermarks/source_classify.py +++ b/src/remove_ai_watermarks/source_classify.py @@ -352,15 +352,20 @@ def _require_dependencies() -> None: ) -def _verify_sha256(path: Path, expected_sha256: str) -> None: +def verify_weights_sha256(path: Path, expected_sha256: str) -> None: + """Verify ``path`` matches ``expected_sha256``, raising :class:`RuntimeError` on mismatch.""" with path.open("rb") as handle: actual = hashlib.file_digest(handle, "sha256").hexdigest() if actual.lower() != expected_sha256.lower(): raise RuntimeError( - f"Source classifier weights hash mismatch for {path}: expected {expected_sha256}, got {actual}" + f"SHA-256 hash mismatch for {path.name}: expected {expected_sha256}, got {actual}. " + "Clear the cached artifact or point to a verified freeze directory." ) +_verify_sha256 = verify_weights_sha256 + + def _resolve_weights_path(weights_path: Path | None = None) -> Path: if weights_path is not None: path = Path(weights_path).expanduser() @@ -1479,14 +1484,17 @@ def _classify_v5_features(x_1d: FloatArray, model: _SourceModelV5) -> SourceClas thresholds: dict[str, float] = dict(zip(ALL_PROVIDER_CLASSES, prov_thr.tolist(), strict=True)) margins: dict[str, float] = dict(zip(ALL_PROVIDER_CLASSES, prov_margins.tolist(), strict=True)) - confidence = _sigmoid_scalar(model.conf_scale * accept_excess) if accept_excess >= 0.0: + part = np.partition(attr_logits, -2) + attr_gap = max(0.0, float(part[-1] - part[-2])) + confidence = _sigmoid_scalar(min(model.conf_scale * accept_excess, attr_gap)) label: SourceLabel = best_cls reason: SourceReason = "classified" fine_subfamily, version_subfamily = _resolve_two_tower_subfamilies( best_cls, mean_sub, x_1d, u_vec, model.backbone, model.version_heads ) else: + confidence = _sigmoid_scalar(model.conf_scale * accept_excess) label = "unknown" reason = "abstained" fine_subfamily = None diff --git a/tests/test_classify.py b/tests/test_classify.py index bce83ee..489e53f 100644 --- a/tests/test_classify.py +++ b/tests/test_classify.py @@ -1,7 +1,8 @@ -"""Pixel classify gate: Model 1 then gated Model 2, no downloads, no identify hook.""" +"""Pixel classify gate: Model 1 + receipt gate + 10-provider Model 2, no downloads, no identify hook.""" from __future__ import annotations +import hashlib import json import sys from pathlib import Path @@ -12,50 +13,52 @@ import pytest from click.testing import CliRunner from PIL import Image +from remove_ai_watermarks import source_classify from remove_ai_watermarks.classify import ( CLIP_ONNX_FILE, MLP_THRESHOLD, - PROVIDER_MARGIN, + PROVIDER_CLASSES, + PROVIDER_FILE, + PROVIDER_SHA256, RECEIPT_GATE_FILE, RECEIPT_GATE_THRESHOLD, RIDGE_THRESHOLD, WEIGHTS_ALLOW_PATTERNS, WEIGHTS_REPO, WEIGHTS_REVISION, + PixelClassification, classify_from_scores, classify_pixels, detector_level, label_for, - provider_from_scores, + provider_from_source, receipt_gate_score, ) from remove_ai_watermarks.cli import main +from remove_ai_watermarks.source_classify import ALL_PROVIDER_CLASSES, SourceClassification -def _scores( - *, - openai: float = 0.0, - google: float = 0.0, - tc260: float = 0.0, - meta: float = 0.0, - no_ai: float = 0.0, - bytedance: float | None = None, -) -> dict[str, float]: - scores = { - "openai": openai, - "google": google, - "tc260": tc260, - "meta_muse_image": meta, - "no_ai": no_ai, - } - if bytedance is not None: - scores["bytedance"] = bytedance - return scores +def _source_result(label: str = "unknown") -> SourceClassification: + reason = "abstained" if label == "unknown" else "classified" + conf = 0.25 if label == "unknown" else 0.90 + return SourceClassification( + label=label, # type: ignore[arg-type] + version_subfamily=f"{label}:v1" if label != "unknown" else None, + fine_subfamily=f"{label}:v1" if label != "unknown" else None, + confidence=conf, + reason=reason, # type: ignore[arg-type] + margins=dict.fromkeys(ALL_PROVIDER_CLASSES, 0.0), + thresholds=dict.fromkeys(ALL_PROVIDER_CLASSES, 1.0), + pooled_scores=dict.fromkeys(ALL_PROVIDER_CLASSES, 0.0), + ) -def test_hub_snapshot_is_the_freeze_revision() -> None: +def test_hub_snapshot_and_provider_artifact_match_source_classify() -> None: assert WEIGHTS_REPO == "wiltodelta/raiw-photo-classify" - assert WEIGHTS_REVISION == "de668f0d8a53412923478cc21382a56890748310" + assert len(WEIGHTS_REVISION) == 40 + assert PROVIDER_FILE == source_classify.MODEL_FILE == "multi-provider-source-v6.npz" + assert PROVIDER_SHA256 == source_classify.MODEL_SHA256 + assert PROVIDER_CLASSES == ALL_PROVIDER_CLASSES def test_runtime_requests_only_the_selected_backend_model(monkeypatch: pytest.MonkeyPatch) -> None: @@ -72,8 +75,6 @@ def test_runtime_requests_only_the_selected_backend_model(monkeypatch: pytest.Mo captured.append(kwargs) return "/cached/snapshot" - # huggingface_hub ships with the classify extra, not with the dev sync, - # so stub the module instead of importing it. monkeypatch.setitem(sys.modules, "huggingface_hub", SimpleNamespace(snapshot_download=fake_snapshot_download)) monkeypatch.delenv("RAIW_CLASSIFY_WEIGHTS", raising=False) @@ -82,6 +83,8 @@ def test_runtime_requests_only_the_selected_backend_model(monkeypatch: pytest.Mo assert captured[0]["revision"] == WEIGHTS_REVISION torch_patterns = captured[0]["allow_patterns"] assert "clip-l-ft.pt" in torch_patterns + assert PROVIDER_FILE in torch_patterns + assert "provider.pt" not in torch_patterns assert CLIP_ONNX_FILE not in torch_patterns assert set(_WEIGHT_FILES) <= set(WEIGHTS_ALLOW_PATTERNS) assert CLIP_ONNX_FILE in WEIGHTS_ALLOW_PATTERNS @@ -90,12 +93,13 @@ def test_runtime_requests_only_the_selected_backend_model(monkeypatch: pytest.Mo assert _weights_dir("onnx") == Path("/cached/snapshot") onnx_patterns = captured[0]["allow_patterns"] assert CLIP_ONNX_FILE in onnx_patterns + assert PROVIDER_FILE in onnx_patterns assert "clip-l-ft.pt" not in onnx_patterns assert set(torch_patterns) | set(onnx_patterns) == set(WEIGHTS_ALLOW_PATTERNS) def test_backend_requires_its_own_model_file(tmp_path: Path) -> None: - from remove_ai_watermarks.classify import DETECTOR_FILE, PROBE_FILE, PROVIDER_FILE, _require_files + from remove_ai_watermarks.classify import DETECTOR_FILE, PROBE_FILE, _require_files for name in (CLIP_ONNX_FILE, PROBE_FILE, DETECTOR_FILE, PROVIDER_FILE): (tmp_path / name).touch() @@ -143,22 +147,22 @@ def test_embed_dispatches_to_the_selected_backend(monkeypatch: pytest.MonkeyPatc def test_shipped_operating_point_matches_the_runtime_defaults() -> None: payload = json.loads(Path("docs/photo-classify-hf/operating-point.json").read_text()) + card = Path("docs/photo-classify-hf/README.md").read_text() assert payload["model1"]["mlp_threshold"] == MLP_THRESHOLD assert payload["model1"]["ridge_threshold"] == RIDGE_THRESHOLD - assert payload["model2"]["margin"] == PROVIDER_MARGIN + assert payload["model2"]["artifact"] == PROVIDER_FILE + assert payload["model2"]["artifact_sha256"] == PROVIDER_SHA256 + assert payload["model2"]["feature_width"] == 512 assert payload["model2"]["runs_only_after"] == "definitely" - assert payload["model2"]["classes"] == ["openai", "google", "bytedance", "tc260", "muse-image", "no_ai"] - assert payload["model2"]["class_kind"]["openai"] == "provider" - assert payload["model2"]["class_kind"]["google"] == "provider" - assert payload["model2"]["class_kind"]["bytedance"] == "provider" - assert payload["model2"]["class_kind"]["tc260"] == "abstain-veto" - assert payload["model2"]["class_kind"]["muse-image"] == "model" - assert payload["model2"]["public_values"] == ["openai", "google", "bytedance", "muse-image", None] - assert payload["model2"]["checkpoint_keys"]["muse-image"] == "meta_muse_image" + assert payload["model2"]["classes"] == list(PROVIDER_CLASSES) + assert payload["model2"]["public_values"] == [*PROVIDER_CLASSES, None] assert payload["receipt_gate"]["threshold"] == RECEIPT_GATE_THRESHOLD assert payload["receipt_gate"]["asset"] == RECEIPT_GATE_FILE assert payload["receipt_gate"]["runs_only_after"] == "definitely" assert payload["receipt_gate"]["on_hit"] == "unknown" + assert PROVIDER_FILE in payload["files"] + assert PROVIDER_FILE in card + assert PROVIDER_SHA256 in card def test_definitely_is_the_and_of_ridge_and_mlp() -> None: @@ -174,71 +178,48 @@ def test_only_definitely_is_ai() -> None: assert label_for("likely_human") == "human" -def test_provider_requires_margin_over_no_ai() -> None: - assert provider_from_scores(_scores(openai=1.0, no_ai=0.5)) == "openai" - assert provider_from_scores(_scores(openai=0.5, no_ai=0.4)) is None - assert provider_from_scores(_scores(google=2.0, openai=1.5, no_ai=0.0)) == "google" - assert provider_from_scores(_scores(meta=1.0, no_ai=0.0)) == "muse-image" +@pytest.mark.parametrize("provider_name", PROVIDER_CLASSES) +def test_provider_from_source_accepts_all_ten_providers(provider_name: str) -> None: + assert provider_from_source(_source_result(provider_name)) == provider_name + assert provider_from_source(provider_name) == provider_name # type: ignore[arg-type] -def test_bytedance_names_the_shared_bytedance_renderer_lineage() -> None: - """Doubao and Jimeng render with one ByteDance model family, so the - generator class is the union; the value names the lineage.""" - assert provider_from_scores(_scores(bytedance=1.0, no_ai=0.0)) == "bytedance" - assert provider_from_scores(_scores(bytedance=3.0, openai=1.0, no_ai=0.0)) == "bytedance" - assert provider_from_scores(_scores(bytedance=1.0, openai=2.0, no_ai=0.0)) == "openai" +def test_provider_from_source_abstains_and_rejects_unknown_names() -> None: + assert provider_from_source(None) is None + assert provider_from_source("unknown") is None + assert provider_from_source(_source_result("unknown")) is None + with pytest.raises(ValueError, match="unsupported pixel provider"): + provider_from_source("muse-image") # type: ignore[arg-type] -def test_older_snapshots_without_bytedance_keep_working() -> None: - """provider.pt predating bytedance has five heads; the candidate set - comes from the LOADED scores, so such snapshots run unchanged and - their would-be bytedance rows fall to the tc260 veto.""" - legacy = _scores(tc260=2.0, openai=1.0, no_ai=0.0) - assert "bytedance" not in legacy - assert provider_from_scores(legacy) is None - assert provider_from_scores(_scores(openai=3.0, no_ai=0.0)) == "openai" +def test_definitely_plus_provider_publishes_ai_and_provider() -> None: + for provider_name in ("openai", "flux", "meta", "firefly", "xai"): + result = classify_from_scores(1.0, 10.0, _source_result(provider_name)) + assert result.label == "ai" + assert result.domain == "photo" + assert result.detector == "definitely" + assert result.provider == provider_name + assert result.to_dict()["provider"] == provider_name -def test_tc260_wins_abstain_instead_of_naming_a_provider() -> None: - """tc260 is not one class of anything: it covers China's generator - ecosystem, providers that are peers of openai/google/meta. No mixed - head can honestly name that group, so its argmax win publishes None; a - row where a real provider outscores it keeps that provider.""" - assert provider_from_scores(_scores(tc260=1.0, no_ai=0.0)) is None - assert provider_from_scores(_scores(tc260=3.0, openai=1.0, no_ai=0.0)) is None - assert provider_from_scores(_scores(tc260=1.0, openai=2.0, no_ai=0.0)) == "openai" - - -def test_definitely_plus_openai_is_ai_openai() -> None: - result = classify_from_scores(1.0, 10.0, _scores(openai=1.0, no_ai=0.0)) - assert result.label == "ai" - assert result.domain == "photo" - assert result.detector == "definitely" - assert result.provider == "openai" - assert result.to_dict()["provider"] == "openai" - - -def test_definitely_without_provider_scores_stays_ai_with_no_provider() -> None: - result = classify_from_scores(1.0, 10.0, None) - assert result.label == "ai" - assert result.provider is None - - -def test_definitely_plus_no_ai_head_has_no_provider() -> None: - result = classify_from_scores(1.0, 10.0, _scores(no_ai=2.0, openai=1.0)) - assert result.label == "ai" - assert result.provider is None +def test_definitely_without_provider_or_abstained_stays_ai_with_no_provider() -> None: + assert classify_from_scores(1.0, 10.0, None) == PixelClassification( + label="ai", domain="photo", detector="definitely", provider=None + ) + assert classify_from_scores(1.0, 10.0, _source_result("unknown")) == PixelClassification( + label="ai", domain="photo", detector="definitely", provider=None + ) def test_possibly_does_not_run_provider() -> None: - result = classify_from_scores(1.0, 0.0, _scores(openai=9.0, no_ai=0.0)) + result = classify_from_scores(1.0, 0.0, _source_result("openai")) assert result.label == "unknown" assert result.detector == "possibly" assert result.provider is None def test_likely_human_does_not_run_provider() -> None: - result = classify_from_scores(0.0, 0.0, _scores(openai=9.0, no_ai=0.0)) + result = classify_from_scores(0.0, 0.0, _source_result("openai")) assert result.label == "human" assert result.detector == "likely_human" assert result.provider is None @@ -253,7 +234,12 @@ def test_shipped_receipt_gate_asset_matches_the_pinned_threshold() -> None: def test_receipt_gate_downgrades_definitely_to_unknown() -> None: - result = classify_from_scores(1.0, 10.0, _scores(openai=9.0, no_ai=0.0), receipt_score=RECEIPT_GATE_THRESHOLD + 1.0) + result = classify_from_scores( + 1.0, + 10.0, + _source_result("openai"), + receipt_score=RECEIPT_GATE_THRESHOLD + 1.0, + ) assert result.label == "unknown" assert result.detector == "definitely" assert result.provider is None @@ -263,11 +249,11 @@ def test_receipt_gate_below_threshold_keeps_ai_and_provider() -> None: result = classify_from_scores( 1.0, 10.0, - _scores(openai=1.0, no_ai=0.0), + _source_result("flux"), receipt_score=RECEIPT_GATE_THRESHOLD - 0.01, ) assert result.label == "ai" - assert result.provider == "openai" + assert result.provider == "flux" @pytest.mark.parametrize( @@ -340,18 +326,12 @@ def test_receipt_gate_stable_name_beats_the_legacy_spelling(tmp_path: Path) -> N gate = _load_receipt_gate(weights) assert gate["threshold"] == -99.0 probe = np.full(768, 1.0 / np.sqrt(768), dtype=np.float64) - # The score must come from the SAME stable-name artifact: with its - # uniform weights the score is exactly 0.5*sqrt(768), not the legacy - # package head's value. assert receipt_gate_score(probe, gate) == pytest.approx(0.5 * np.sqrt(768)) finally: _receipt_gate_cache.clear() def test_receipt_threshold_defaults_to_the_artifact_value() -> None: - """classify_from_scores without an explicit threshold resolves the - operating point from the loaded gate artifact (legacy package fallback - here), not from a code constant.""" from remove_ai_watermarks.classify import _load_receipt_gate, _receipt_gate_cache _receipt_gate_cache.clear() @@ -376,7 +356,13 @@ def test_receipt_gate_falls_back_to_the_package_asset() -> None: _receipt_gate_cache.clear() -def _patch_definitely_runtime(monkeypatch: pytest.MonkeyPatch, *, forensic_calls: list[int]) -> None: +def _patch_definitely_runtime( + monkeypatch: pytest.MonkeyPatch, + *, + model2_calls: list[int] | None = None, + provider_path: Path = Path("/unused/multi-provider-source-v6.npz"), + weights_override: str | None = "/override", +) -> SimpleNamespace: """Patch classify internals so a plain PNG scores DEFINITELY on Model 1.""" runtime = SimpleNamespace( ridge_mean=np.zeros(768), @@ -384,22 +370,26 @@ def _patch_definitely_runtime(monkeypatch: pytest.MonkeyPatch, *, forensic_calls ridge_weights=np.full(768, 0.01), ridge_threshold=RIDGE_THRESHOLD, mlp_threshold=MLP_THRESHOLD, - provider_margin=PROVIDER_MARGIN, + provider_path=provider_path, weights_dir=None, + weights_override=weights_override, + provider_verified=False, ) monkeypatch.setattr("remove_ai_watermarks.classify.is_available", lambda: True) monkeypatch.setattr("remove_ai_watermarks.classify._get_runtime", lambda device, backend="torch": runtime) monkeypatch.setattr("remove_ai_watermarks.classify._embed", lambda *args, **kwargs: np.full(768, 100.0)) monkeypatch.setattr("remove_ai_watermarks.classify._mlp_score", lambda *args, **kwargs: 10.0) - monkeypatch.setattr( - "remove_ai_watermarks.classify._forensic", - lambda image: forensic_calls.append(1) or np.zeros(124), - ) + if model2_calls is not None: + monkeypatch.setattr( + "remove_ai_watermarks.classify._run_model2", + lambda rt, image, **kwargs: model2_calls.append(1) or _source_result("openai"), + ) + return runtime -def test_receipt_gate_hit_skips_the_124d_forensics(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: +def test_receipt_gate_hit_skips_the_512d_forensics(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: calls: list[int] = [] - _patch_definitely_runtime(monkeypatch, forensic_calls=calls) + _patch_definitely_runtime(monkeypatch, model2_calls=calls) monkeypatch.setattr( "remove_ai_watermarks.classify.receipt_gate_score", lambda *args, **kwargs: RECEIPT_GATE_THRESHOLD + 5.0 ) @@ -409,26 +399,74 @@ def test_receipt_gate_hit_skips_the_124d_forensics(monkeypatch: pytest.MonkeyPat assert calls == [] -def test_receipt_gate_miss_still_runs_the_124d_forensics(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: +def test_receipt_gate_miss_runs_v6_model2_and_attributes_ten_class_provider( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + from tests.test_source_classify import _write_synthetic_v5_npz + + v6_path = _write_synthetic_v5_npz( + tmp_path / PROVIDER_FILE, + det_winner="flux", + attr_winner="ideogram", + det_score=5.0, + det_threshold=1.0, + ) calls: list[int] = [] - _patch_definitely_runtime(monkeypatch, forensic_calls=calls) + runtime = _patch_definitely_runtime( + monkeypatch, + provider_path=v6_path, + weights_override=None, + ) monkeypatch.setattr( - "remove_ai_watermarks.classify._provider_scores", - lambda runtime, forensic: _scores(), + "remove_ai_watermarks.classify.PROVIDER_SHA256", + hashlib.sha256(v6_path.read_bytes()).hexdigest(), + ) + monkeypatch.setattr( + "remove_ai_watermarks.source_classify.extract_512d_v4_features", + lambda image: calls.append(1) or np.zeros(512), ) monkeypatch.setattr( "remove_ai_watermarks.classify.receipt_gate_score", lambda *args, **kwargs: RECEIPT_GATE_THRESHOLD - 5.0 ) + result = classify_pixels(_plain_png(tmp_path, side=256)) + assert result.label == "ai" + assert result.provider == "ideogram" + assert calls == [1] + assert runtime.provider_verified is True + + +def test_small_image_below_256px_abstains_provider_while_keeping_ai_label( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + runtime = _patch_definitely_runtime(monkeypatch, weights_override=None) + monkeypatch.setattr( + "remove_ai_watermarks.classify.receipt_gate_score", lambda *args, **kwargs: RECEIPT_GATE_THRESHOLD - 5.0 + ) + # _plain_png is 32x32 (< 256x256), so _run_model2 returns None before hashing or loading v6.npz. result = classify_pixels(_plain_png(tmp_path)) assert result.label == "ai" - assert calls == [1] + assert result.detector == "definitely" + assert result.provider is None + assert runtime.provider_verified is False + + +def test_verify_sha256_enforces_hub_provider_digest(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + target = tmp_path / PROVIDER_FILE + target.write_bytes(b"corrupted") + _patch_definitely_runtime(monkeypatch, provider_path=target, weights_override=None) + monkeypatch.setattr( + "remove_ai_watermarks.classify.receipt_gate_score", lambda *args, **kwargs: RECEIPT_GATE_THRESHOLD - 5.0 + ) + with pytest.raises(RuntimeError, match=r"SHA-256 hash mismatch for multi-provider-source-v6\.npz"): + classify_pixels(_plain_png(tmp_path, side=256)) @pytest.mark.parametrize("caller", ["identify", "has_invisible_target"]) -def test_provenance_paths_do_not_import_classify(tmp_path: Path, caller: str) -> None: +def test_provenance_paths_do_not_import_classify(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, caller: str) -> None: path = tmp_path / "plain.png" Image.fromarray(np.zeros((32, 32, 3), dtype=np.uint8)).save(path) - sys.modules.pop("remove_ai_watermarks.classify", None) + monkeypatch.delitem(sys.modules, "remove_ai_watermarks.classify", raising=False) + monkeypatch.delitem(sys.modules, "remove_ai_watermarks.source_classify", raising=False) from remove_ai_watermarks.identify import has_invisible_target, identify if caller == "identify": @@ -436,17 +474,21 @@ def test_provenance_paths_do_not_import_classify(tmp_path: Path, caller: str) -> assert report.is_ai_generated is None else: assert has_invisible_target(path) is False - loaded = [name for name in sys.modules if name.startswith("remove_ai_watermarks.classify")] + loaded = [ + name + for name in sys.modules + if name.startswith(("remove_ai_watermarks.classify", "remove_ai_watermarks.source_classify")) + ] assert loaded == [] -def _plain_png(tmp_path: Path) -> Path: - path = tmp_path / "plain.png" - Image.fromarray(np.zeros((32, 32, 3), dtype=np.uint8)).save(path) +def _plain_png(tmp_path: Path, *, side: int = 32) -> Path: + path = tmp_path / f"plain-{side}.png" + Image.fromarray(np.zeros((side, side, 3), dtype=np.uint8)).save(path) return path -def test_124d_is_not_extracted_unless_definitely(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: +def test_512d_is_not_extracted_unless_definitely(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: calls: list[int] = [] runtime = SimpleNamespace( ridge_mean=np.zeros(768), @@ -454,7 +496,7 @@ def test_124d_is_not_extracted_unless_definitely(monkeypatch: pytest.MonkeyPatch ridge_weights=np.zeros(768), ridge_threshold=RIDGE_THRESHOLD, mlp_threshold=MLP_THRESHOLD, - provider_margin=PROVIDER_MARGIN, + provider_path=Path("/unused/multi-provider-source-v6.npz"), weights_dir=None, ) monkeypatch.setattr("remove_ai_watermarks.classify.is_available", lambda: True) @@ -462,8 +504,8 @@ def test_124d_is_not_extracted_unless_definitely(monkeypatch: pytest.MonkeyPatch monkeypatch.setattr("remove_ai_watermarks.classify._embed", lambda *args, **kwargs: np.zeros(768)) monkeypatch.setattr("remove_ai_watermarks.classify._mlp_score", lambda *args, **kwargs: 0.0) monkeypatch.setattr( - "remove_ai_watermarks.classify._forensic", - lambda image: calls.append(1) or np.zeros(124), + "remove_ai_watermarks.classify._run_model2", + lambda rt, image, **kwargs: calls.append(1) or None, ) result = classify_pixels(_plain_png(tmp_path)) assert result.label == "human" @@ -484,11 +526,9 @@ def test_weight_files_may_sit_in_run1(tmp_path: Path) -> None: def test_operating_point_prefers_the_sidecar(tmp_path: Path) -> None: from remove_ai_watermarks.classify import _operating_point - (tmp_path / "operating-point.json").write_text( - json.dumps({"model1": {"mlp_threshold": 1.25}, "model2": {"margin": 0.5}}) - ) - assert _operating_point(tmp_path) == (1.25, 0.5) - assert _operating_point(tmp_path / "missing") == (MLP_THRESHOLD, PROVIDER_MARGIN) + (tmp_path / "operating-point.json").write_text(json.dumps({"model1": {"mlp_threshold": 1.25}})) + assert _operating_point(tmp_path) == 1.25 + assert _operating_point(tmp_path / "missing") == MLP_THRESHOLD def test_missing_extra_raises_the_install_hint(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: @@ -516,3 +556,27 @@ def test_cli_classify_without_extra_prints_the_install_hint(monkeypatch: pytest. assert result.exit_code == 1 assert "remove-ai-watermarks[classify]" in result.output assert "pip install" in result.output + + +def test_cli_classify_json_and_text_emit_expanded_provider(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + import remove_ai_watermarks.classify as classify_mod + + monkeypatch.setattr(classify_mod, "is_available", lambda: True) + monkeypatch.setattr( + classify_mod, + "classify_pixels", + lambda _p: PixelClassification(label="ai", domain="photo", detector="definitely", provider="flux"), + ) + path = _plain_png(tmp_path) + json_res = CliRunner().invoke(main, ["classify", str(path), "--json"]) + assert json_res.exit_code == 0 + assert json.loads(json_res.output) == { + "label": "ai", + "domain": "photo", + "detector": "definitely", + "provider": "flux", + } + + text_res = CliRunner().invoke(main, ["classify", str(path)]) + assert text_res.exit_code == 0 + assert "Provider: flux" in text_res.output diff --git a/tests/test_designer_synthid_suppression.py b/tests/test_designer_synthid_suppression.py index 2191535..de17d5d 100644 --- a/tests/test_designer_synthid_suppression.py +++ b/tests/test_designer_synthid_suppression.py @@ -10,7 +10,14 @@ double-counting one forensic mark as two pixel watermarks. from __future__ import annotations +from pathlib import Path + from remove_ai_watermarks._internal.c2pa import c2pa_info_from_manifest_store +from remove_ai_watermarks.identify import ( + evidence_from_metadata_record, + identify_from_evidence, + report_has_removal_hint, +) DESIGNER_STORE = { "active_manifest": "designer", @@ -119,3 +126,202 @@ def test_vendor_agent_name_alone_is_not_the_vendors_provenance() -> None: } info = c2pa_info_from_manifest_store(store) assert info.get("synthid_watermark") is None + + +def test_adobe_partner_model_parameter_digital_source_type_establishes_ai_without_false_synthid() -> None: + """Adobe partner-model exports store digitalSourceType inside action.parameters. + + They also name the remote 3rd-party model (e.g. Gemini Flash) inside + parameters. The nested com.adobe.digitalSourceType must establish AI-generated + provenance even under a generic Adobe signer (such as Adobe Photoshop), while + the parameter-only Gemini string must not fabricate Google SynthID provenance. + """ + firefly_partner_store = { + "active_manifest": "urn:uuid:partner-firefly", + "manifests": { + "urn:uuid:partner-firefly": { + "signature_info": {"issuer": "Adobe Inc.", "common_name": "Adobe Firefly C2PA"}, + "claim_generator": "Adobe_Firefly", + "claim_generator_info": [{"name": "Adobe Firefly", "org.contentauth.c2pa_rs": "0.90.4"}], + "assertions": [ + { + "label": "c2pa.actions.v2", + "data": { + "actions": [ + { + "action": "c2pa.opened", + "parameters": { + "com.adobe.details": "Gemini Flash", + "com.adobe.digitalSourceType": ( + "http://cv.iptc.org/newscodes/digitalsourcetype/trainedAlgorithmicMedia" + ), + "com.adobe.modelId": "gemini-flash", + "com.adobe.modelVersion": "nano-banana-3", + "com.adobe.type": "remoteProvider.3rdParty", + }, + } + ] + }, + } + ], + } + }, + } + info = c2pa_info_from_manifest_store(firefly_partner_store) + assert info["source_type"] == "trainedAlgorithmicMedia (AI-generated)" + assert info["ai_source_kind"] == "generated" + assert info.get("synthid_watermark") is None + assert info.get("synthid_vendors") is None + + # Under a generic Adobe Creative Cloud signer (no "Adobe_Firefly" identity), + # com.adobe.digitalSourceType is the ONLY AI marker in the manifest. + photoshop_partner_store = { + "active_manifest": "urn:uuid:partner-ps", + "manifests": { + "urn:uuid:partner-ps": { + "signature_info": {"issuer": "Adobe Inc.", "common_name": "Adobe Photoshop"}, + "claim_generator": "Adobe_Photoshop", + "claim_generator_info": [{"name": "Adobe Photoshop"}], + "assertions": firefly_partner_store["manifests"]["urn:uuid:partner-firefly"]["assertions"], + } + }, + } + evidence = evidence_from_metadata_record({"c2pa_store": photoshop_partner_store}, path=Path("partner.png")) + report = identify_from_evidence(evidence) + assert report.is_ai_generated is True + assert report.ai_from_metadata is True + assert report.ai_source_kind == "generated" + assert not any("SynthID" in w for w in report.watermarks) + assert report_has_removal_hint(report, evidence.c2pa_info) is True + + +_GOOGLE_HEADERS: dict[str, object] = { + "signature_info": {"issuer": "Google LLC", "common_name": "Google Media Processing Services"}, + "claim_generator_info": [{"name": "Google C2PA Core Generator Library"}], +} + + +def _google_gen_manifest(*, ingredient_manifest: str | None = None) -> dict[str, object]: + manifest: dict[str, object] = { + **_GOOGLE_HEADERS, + "assertions": [ + { + "label": "c2pa.actions.v2", + "data": { + "actions": [ + { + "action": "c2pa.created", + "digitalSourceType": ( + "http://cv.iptc.org/newscodes/digitalsourcetype/trainedAlgorithmicMedia" + ), + "description": "Created by Google Generative AI.", + }, + { + "action": "c2pa.edited", + "digitalSourceType": ( + "http://cv.iptc.org/newscodes/digitalsourcetype/trainedAlgorithmicMedia" + ), + "description": "Applied imperceptible SynthID watermark.", + }, + ] + }, + } + ], + } + if ingredient_manifest is not None: + manifest["ingredients"] = [{"active_manifest": ingredient_manifest}] + return manifest + + +def test_firefly_ingredient_edited_by_google_generative_ai_preserves_synthid_verdict() -> None: + """Multi-manifest Firefly ingredient edited by Google Generative AI keeps SynthID provenance.""" + store = { + "active_manifest": "urn:c2pa:google-export", + "manifests": { + "urn:c2pa:firefly-base": { + "signature_info": {"issuer": "Adobe Inc."}, + "assertions": [ + { + "label": "c2pa.actions.v2", + "data": { + "actions": [ + { + "action": "c2pa.placed", + "softwareAgent": {"name": "Adobe Firefly"}, + "digitalSourceType": ( + "http://cv.iptc.org/newscodes/digitalsourcetype/trainedAlgorithmicMedia" + ), + } + ] + }, + } + ], + }, + "urn:c2pa:google-gen": _google_gen_manifest(ingredient_manifest="urn:c2pa:firefly-base"), + "urn:c2pa:google-export": { + **_GOOGLE_HEADERS, + "ingredients": [{"active_manifest": "urn:c2pa:google-gen"}], + "assertions": [ + { + "label": "c2pa.actions.v2", + "data": { + "actions": [ + {"action": "c2pa.opened"}, + { + "action": "c2pa.edited", + "digitalSourceType": "http://cv.iptc.org/newscodes/digitalsourcetype/composite", + "description": "Added visible watermark", + }, + {"action": "c2pa.converted", "description": "Converted to .png"}, + ] + }, + } + ], + }, + }, + } + evidence = evidence_from_metadata_record({"c2pa_store": store}, path=Path("chained.png")) + report = identify_from_evidence(evidence) + assert report.is_ai_generated is True + assert report.ai_from_metadata is True + assert report.ai_source_kind == "generated" + assert any("SynthID watermark (present according to Google LLC provenance)" in w for w in report.watermarks) + assert report_has_removal_hint(report, evidence.c2pa_info) is True + + +def test_google_c2pa_chain_with_algorithmically_enhanced_transcode_preserves_generated_verdict() -> None: + """A Google C2PA transcode wrapper (algorithmicallyEnhanced) keeps inner AI + SynthID provenance.""" + store = { + "active_manifest": "urn:c2pa:google-transcode", + "manifests": { + "urn:c2pa:google-origin": _google_gen_manifest(), + "urn:c2pa:google-transcode": { + **_GOOGLE_HEADERS, + "ingredients": [{"active_manifest": "urn:c2pa:google-origin"}], + "assertions": [ + { + "label": "c2pa.actions.v2", + "data": { + "actions": [ + {"action": "c2pa.opened", "description": "Opened by Google"}, + { + "action": "c2pa.transcoded", + "digitalSourceType": ( + "http://cv.iptc.org/newscodes/digitalsourcetype/algorithmicallyEnhanced" + ), + }, + ] + }, + } + ], + }, + }, + } + evidence = evidence_from_metadata_record({"c2pa_store": store}, path=Path("reshared.png")) + report = identify_from_evidence(evidence) + assert report.is_ai_generated is True + assert report.ai_from_metadata is True + assert report.platform == "Google (Gemini / Imagen)" + assert report.ai_source_kind == "generated" + assert any("SynthID watermark (present according to Google LLC provenance)" in w for w in report.watermarks) + assert report_has_removal_hint(report, evidence.c2pa_info) is True diff --git a/tests/test_publish_photo_classify_hf.py b/tests/test_publish_photo_classify_hf.py index 1aca62f..f1aa2d8 100644 --- a/tests/test_publish_photo_classify_hf.py +++ b/tests/test_publish_photo_classify_hf.py @@ -1,7 +1,8 @@ -"""Path resolution for Hub photo-classify publish, no network.""" +"""Path resolution and SHA-256 checks for Hub photo-classify publish, no network.""" from __future__ import annotations +import hashlib import sys from pathlib import Path @@ -14,9 +15,17 @@ import publish_photo_classify_hf as publish # noqa: E402 def test_hub_ids_match_the_runtime_loader() -> None: # The workflow runs this script with --no-project, so it cannot import the package constants. - from remove_ai_watermarks.classify import RECEIPT_GATE_FILE, RECEIPT_GATE_STABLE_FILE, WEIGHTS_REPO + from remove_ai_watermarks.classify import ( + PROVIDER_FILE, + PROVIDER_SHA256, + RECEIPT_GATE_FILE, + RECEIPT_GATE_STABLE_FILE, + WEIGHTS_REPO, + ) assert publish.HUB_REPO == WEIGHTS_REPO + assert publish.PROVIDER_FILE == PROVIDER_FILE + assert publish.PROVIDER_SHA256 == PROVIDER_SHA256 assert publish.GATE_FILE == RECEIPT_GATE_FILE assert publish.GATE_STABLE_FILE == RECEIPT_GATE_STABLE_FILE assert publish.GATE_SOURCE.is_file() @@ -29,19 +38,36 @@ def test_publish_freeze_includes_both_clip_runtimes() -> None: assert publish.CLIP_ONNX_FILE in publish.WEIGHT_FILES assert set(publish.WEIGHT_FILES) == {*_WEIGHT_FILES, CLIP_ONNX_FILE} assert set(publish.WEIGHT_FILES) <= set(WEIGHTS_ALLOW_PATTERNS) + assert "provider.pt" in publish.RETIRED_FILES def test_weight_paths_accepts_run1_layout(tmp_path: Path) -> None: (tmp_path / "clip-l-ft.pt").write_bytes(b"clip") (tmp_path / "clip-l-ft-vision-fp32.onnx").write_bytes(b"onnx") (tmp_path / "probe-weights-clip-l-ft.npz").write_bytes(b"probe") + (tmp_path / "multi-provider-source-v6.npz").write_bytes(b"source-v6") run1 = tmp_path / "run1" run1.mkdir() (run1 / "detector.pt").write_bytes(b"det") - (run1 / "provider.pt").write_bytes(b"prov") found = publish.weight_paths(tmp_path) assert found["detector.pt"] == run1 / "detector.pt" assert found["clip-l-ft.pt"] == tmp_path / "clip-l-ft.pt" + assert found["multi-provider-source-v6.npz"] == tmp_path / "multi-provider-source-v6.npz" + + +def test_stage_weights_rejects_mismatched_provider_sha256(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + src = tmp_path / "src" + src.mkdir() + for name in publish.WEIGHT_FILES: + (src / name).write_bytes(f"payload-{name}".encode()) + dest = tmp_path / "dest" + with pytest.raises(SystemExit, match=r"SHA-256 mismatch for multi-provider-source-v6\.npz"): + publish.stage_weights(dest, src) + + good_sha = hashlib.sha256(b"payload-multi-provider-source-v6.npz").hexdigest() + monkeypatch.setattr(publish, "PROVIDER_SHA256", good_sha) + publish.stage_weights(dest, src) + assert (dest / "multi-provider-source-v6.npz").is_file() def test_weight_paths_requires_every_file(tmp_path: Path) -> None: @@ -58,3 +84,4 @@ def test_stage_card_copies_tracked_files(tmp_path: Path) -> None: assert (dest / "operating-point.json").is_file() text = (dest / "operating-point.json").read_text() assert "clip-l-ft.pt" in text + assert "multi-provider-source-v6.npz" in text diff --git a/tests/test_source_classify.py b/tests/test_source_classify.py index 3ce9663..bb626cc 100644 --- a/tests/test_source_classify.py +++ b/tests/test_source_classify.py @@ -721,3 +721,75 @@ def test_v5_stage2_linear_blend_and_schema_validation(tmp_path: Path) -> None: ) with pytest.raises(ValueError, match="Incomplete Stage-2 linear blend keys for ideogram"): source_classify._load_model(w_partial) + + +def test_v5_joint_posterior_confidence_caps_ambiguous_attribution(tmp_path: Path) -> None: + x_512 = np.zeros(source_classify.FEATURE_DIM_V4, dtype=np.float64) + n_cls = len(source_classify.ALL_PROVIDER_CLASSES) + ideo_idx = source_classify.ALL_PROVIDER_CLASSES.index("ideogram") + google_idx = source_classify.ALL_PROVIDER_CLASSES.index("google") + + # 1) High acceptance excess (+4.0 -> sigmoid(4.0) ~= 0.982), near-tie in attribution (gap = 0.05): + # joint confidence must be capped by sigmoid(0.05) ~= 0.5125 while keeping confidence >= 0.5. + near_tie_b2 = np.full(n_cls, -1.0, dtype=np.float64) + near_tie_b2[ideo_idx] = 2.05 + near_tie_b2[google_idx] = 2.00 + w_near_tie = _write_synthetic_v5_npz( + tmp_path / "v5_near_tie.npz", + det_winner="flux", + attr_winner="ideogram", + det_score=6.0, + det_threshold=2.0, + overrides={"attr_b2": near_tie_b2}, + ) + res_near_tie = source_classify.classify_source_features(x_512, weights_path=w_near_tie) + assert res_near_tie.label == "ideogram" + assert res_near_tie.reason == "classified" + assert res_near_tie.confidence == pytest.approx(source_classify._sigmoid_scalar(0.05), abs=1e-6) + assert 0.5 < res_near_tie.confidence < 0.52 + + # 2) Exact attribution tie (gap = 0.0) while accepted (accept_excess = +4.0 > 0): + # confidence hits the exact 0.5 boundary while preserving confidence >= 0.5 <=> label != "unknown". + exact_tie_b2 = near_tie_b2.copy() + exact_tie_b2[ideo_idx] = 2.00 + w_exact_tie = _write_synthetic_v5_npz( + tmp_path / "v5_exact_tie.npz", + det_winner="flux", + attr_winner="ideogram", + det_score=6.0, + det_threshold=2.0, + overrides={"attr_b2": exact_tie_b2}, + ) + res_exact_tie = source_classify.classify_source_features(x_512, weights_path=w_exact_tie) + assert res_exact_tie.label != "unknown" + assert res_exact_tie.reason == "classified" + assert res_exact_tie.confidence == pytest.approx(0.5, abs=1e-12) + + # 3) Unambiguous attribution (gap = 4.5) with moderate acceptance excess (+0.5): + # acceptance excess binds, so confidence equals sigmoid(conf_scale * accept_excess). + w_wide = _write_synthetic_v5_npz( + tmp_path / "v5_wide_gap.npz", + det_winner="flux", + attr_winner="ideogram", + det_score=2.5, + det_threshold=2.0, + overrides={"conf_scale": np.asarray(1.2, dtype=np.float64)}, + ) + res_wide = source_classify.classify_source_features(x_512, weights_path=w_wide) + assert res_wide.label == "ideogram" + assert res_wide.confidence == pytest.approx(source_classify._sigmoid_scalar(0.6), abs=1e-6) + + # 4) Abstained input (accept_excess = -0.5 < 0) stays strictly below 0.5 regardless of large attr_gap. + w_abstain = _write_synthetic_v5_npz( + tmp_path / "v5_abstain_wide.npz", + det_winner="flux", + attr_winner="ideogram", + det_score=1.5, + det_threshold=2.0, + overrides={"conf_scale": np.asarray(1.2, dtype=np.float64)}, + ) + res_abstain = source_classify.classify_source_features(x_512, weights_path=w_abstain) + assert res_abstain.label == "unknown" + assert res_abstain.reason == "abstained" + assert res_abstain.confidence == pytest.approx(source_classify._sigmoid_scalar(-0.6), abs=1e-6) + assert res_abstain.confidence < 0.5