From c4f7900d06c09e287f1c552cf73e28979b2a4272 Mon Sep 17 00:00:00 2001 From: Victor Kuznetsov Date: Sun, 15 Nov 2026 09:06:11 -0800 Subject: [PATCH] Add Kling 4.0 marks, metadata parity, and Hub runner, release 0.62.1 --- .claude/rules/development.md | 2 +- docs/module-internals.md | 17 +- docs/python-api.md | 3 +- docs/source-classify-hf/README.md | 6 +- docs/source-classify-hf/demo.ipynb | 148 ++++++++++ docs/source-classify-hf/infer.py | 270 ++++++++++++++++++ docs/supported-signals.md | 8 +- pyproject.toml | 2 +- scripts/corpus_gap_scan.py | 117 ++++++-- scripts/publish_source_classify_hf.py | 2 +- scripts/render_vendor_silhouettes.py | 18 +- server.json | 4 +- src/remove_ai_watermarks/__init__.py | 2 +- .../_internal/constants.py | 6 + src/remove_ai_watermarks/_internal/isobmff.py | 243 ++++++++++++---- .../assets/kling_4_alpha.png | Bin 0 -> 3122 bytes .../assets/kling_latin_4_alpha.png | Bin 0 -> 2763 bytes src/remove_ai_watermarks/identify.py | 13 +- src/remove_ai_watermarks/kling_engine.py | 51 ++-- src/remove_ai_watermarks/metadata.py | 115 +++++--- src/remove_ai_watermarks/source_classify.py | 6 +- src/remove_ai_watermarks/video.py | 25 +- src/remove_ai_watermarks/video_visible.py | 27 +- .../watermark_registry.py | 7 +- tests/test_identify.py | 99 +++++++ tests/test_kling_engine.py | 53 +++- tests/test_metadata.py | 59 ++++ tests/test_publish_source_classify_hf.py | 79 +++++ tests/test_signal_discovery_scripts.py | 45 ++- tests/test_video.py | 130 +++++++++ uv.lock | 2 +- 31 files changed, 1373 insertions(+), 186 deletions(-) create mode 100644 docs/source-classify-hf/demo.ipynb create mode 100644 docs/source-classify-hf/infer.py create mode 100644 src/remove_ai_watermarks/assets/kling_4_alpha.png create mode 100644 src/remove_ai_watermarks/assets/kling_latin_4_alpha.png diff --git a/.claude/rules/development.md b/.claude/rules/development.md index 59166bc..e3785af 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 source-export classifier in `test_source_classify.py` and `test_source_features_v4.py`: the Hub revision and artifact hash are immutable, `_resolve_weights_path` fetches `config.json` before the `.npz` artifact and verifies SHA-256, the pickle-free `v3`/`v4`/`v5` schemas, Regime-FiLM `SiLU` residual trunks, decoupled acceptance/attribution invariance, joint posterior confidence calibration, and exact `GELU` are validated, threshold mutation changes the real decision, and `identify` and `has_invisible_target` never import `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, `resolve_weights_path` fetches `config.json` before the `.npz` artifact and verifies SHA-256, the pickle-free `v3`/`v4`/`v5` schemas, Regime-FiLM `SiLU` residual trunks, decoupled acceptance/attribution invariance, joint posterior confidence calibration, and exact `GELU` are validated, threshold mutation changes the real decision, and `identify` and `has_invisible_target` never import `remove_ai_watermarks.source_classify`; - 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. Keep `test_every_field_arrives_at_the_engine_with_the_caller_s_value`, which sets every `InvisibleOptions` field off its default and asserts each value arrives; a defaults comparison does not replace it. diff --git a/docs/module-internals.md b/docs/module-internals.md index 77c1eb2..1255b1f 100644 --- a/docs/module-internals.md +++ b/docs/module-internals.md @@ -1494,9 +1494,10 @@ derived results influence detection. ### Source-pipeline classifier [`source_classify.py`](../src/remove_ai_watermarks/source_classify.py) provides -the opt-in 10-provider source-pipeline classifier (`classify_source` and CLI -command `classify-source`). By default it downloads `config.json` (for Hub -download telemetry) and `multi-provider-source-v6.npz` +the opt-in 10-provider source-pipeline classifier (`classify_source`, +`resolve_weights_path`, and CLI command `classify-source`). By default it +downloads `config.json` (for Hub download telemetry) and +`multi-provider-source-v6.npz` (`allow_pickle=False`, verified by SHA-256 from `wiltodelta/raiw-source-classify` or overridden via `RAIW_SOURCE_CLASSIFY_WEIGHTS`), while supporting pickle-free runtime loading across three `.npz` bundle schemas: @@ -1901,10 +1902,12 @@ check remains mandatory. The pill is a separate action rather than a distant component unioned into the bottom mask, keeping LaMa and MI-GAN crops local to each mark. -Kling keeps two independently gated silhouettes under one registry key. The -older measured cohort uses `可灵AI 3.0`; a direct authenticated IMAGE 3.0 export -on 2026-09-04 uses `KlingAI 3.0`. The Latin template scored 0.429 on that 1024 x -1024 provider original. Its narrow 0.9/1.0/1.1 scale ladder scored at most 0.349 +Kling keeps independently gated silhouettes under one registry key. The older +measured cohort uses `可灵AI 3.0` (`kling_alpha.png`, plus `kling_4_alpha.png` +for `可灵AI 4.0`); a direct authenticated IMAGE 3.0 export on 2026-09-04 uses +`KlingAI 3.0` (`kling_latin_alpha.png`), and Kling 4.0 consumer exports use +`KlingAI 4.0` (`kling_latin_4_alpha.png`). The Latin template scored 0.429 on +that 1024 x 1024 provider original (and 0.434 on 720 x 1280 Kling 4.0 frames). Its narrow 0.9/1.0/1.1 scale ladder scored at most 0.349 across the 94 available neighboring real and synthetic image controls, while an adversarial solid corner blob reached 0.379, so its strict gate is 0.40. This is one-positive provisional calibration, intentionally separate from the older diff --git a/docs/python-api.md b/docs/python-api.md index f71213d..73c3592 100644 --- a/docs/python-api.md +++ b/docs/python-api.md @@ -787,8 +787,9 @@ provenance, and either substantial overlap or a full-clip Veo run against a partial Sora run. The Veo detector recognizes the current four-point diamond and the legacy `Veo` text. Seedance recognizes the boxed `AI` label, Doubao recognizes -the fixed `豆包AI生成` label, and Dola recognizes +the fixed `豆包AI生成` label, Dola recognizes its compact text label, Hailuo AI recognizes the composite MINIMAX/Hailuo AI label, +Vidu recognizes the two-loop logo and `Vidu AI` wordmark, and Kling AI recognizes its bottom-right logo, wordmark, and version suffix. Each variant has an independent synthetic silhouette and calibrated temporal policy. After each accepted frame is filled, `temporal_consistency=True` motion-aligns diff --git a/docs/source-classify-hf/README.md b/docs/source-classify-hf/README.md index ac0bf45..88c3d42 100644 --- a/docs/source-classify-hf/README.md +++ b/docs/source-classify-hf/README.md @@ -31,6 +31,8 @@ This model is **not a SynthID detector** and does not decode or verify any crypt ## Quickstart (pure NumPy, CPU-only, no PyTorch required) +[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/wiltodelta/remove-ai-watermarks/blob/main/docs/source-classify-hf/demo.ipynb) + ```bash pip install "remove-ai-watermarks[source-classify]" ``` @@ -43,10 +45,12 @@ print(res.label, res.version_subfamily, round(res.confidence, 4)) # e.g. 'openai' 'openai:gpt_image_1_5' 0.9942 (or 'unknown' None 0.9815 on real photos) ``` -Command line: +Command line (installed CLI or zero-setup `uv run` with the bundled `infer.py`): ```bash remove-ai-watermarks classify-source image.jpg --json +uv run https://huggingface.co/wiltodelta/raiw-source-classify/resolve/main/infer.py image.jpg --json +uv run https://huggingface.co/wiltodelta/raiw-source-classify/resolve/main/infer.py --inspect-weights ``` Try it in your browser on the [Remove AI Watermarks Hugging Face Space](https://huggingface.co/spaces/wiltodelta/remove-ai-watermarks) or at [raiw.cc](https://raiw.cc). Set `RAIW_SOURCE_CLASSIFY_WEIGHTS` to `multi-provider-source-v6.npz` or its parent directory for air-gapped deployments. diff --git a/docs/source-classify-hf/demo.ipynb b/docs/source-classify-hf/demo.ipynb new file mode 100644 index 0000000..81d02d9 --- /dev/null +++ b/docs/source-classify-hf/demo.ipynb @@ -0,0 +1,148 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "cell-intro", + "metadata": {}, + "source": [ + "# RAIW 10-provider source-pipeline classifier (`multi-provider-source-v6`)\n", + "\n", + "This notebook demonstrates the compact (`15.52 MB`), CPU-only, pickle-free (`allow_pickle=False`) NumPy classifier published at [`wiltodelta/raiw-source-classify`](https://huggingface.co/wiltodelta/raiw-source-classify).\n", + "\n", + "- **10 AI provider families + open-set abstention:** `openai`, `google`, `bytedance`, `flux`, `stable_diffusion`, `meta`, `midjourney`, `ideogram`, `firefly`, `xai`, plus `unknown`.\n", + "- **Stage-2 model/version attribution (`version_subfamily`):** identifies specific generator subfamilies when an image clears the calibrated regime-aware acceptance threshold.\n", + "- **Scope boundary:** pixel source-pipeline classification is **not** provenance verification and **not** a SynthID or invisible-watermark detector (`watermark_truth=\"unknown\"`)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-install", + "metadata": {}, + "outputs": [], + "source": [ + "%pip install -q \"remove-ai-watermarks[source-classify]>=0.62.0\"" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-inspect-weights", + "metadata": {}, + "outputs": [], + "source": [ + "import hashlib\n", + "import json\n", + "import sys\n", + "from pathlib import Path\n", + "\n", + "import numpy as np\n", + "from huggingface_hub import hf_hub_download\n", + "\n", + "from remove_ai_watermarks import source_classify as sc\n", + "\n", + "weights_path = Path(\n", + " hf_hub_download(\n", + " repo_id=sc.WEIGHTS_REPO,\n", + " filename=sc.MODEL_FILE,\n", + " revision=sc.WEIGHTS_REVISION,\n", + " )\n", + ")\n", + "with weights_path.open(\"rb\") as handle:\n", + " sha256 = hashlib.file_digest(handle, \"sha256\").hexdigest()\n", + "if sha256 != sc.MODEL_SHA256:\n", + " raise ValueError(f\"Unexpected SHA-256: {sha256}\")\n", + "\n", + "with np.load(weights_path, allow_pickle=False) as bundle:\n", + " schema = str(np.asarray(bundle[\"schema\"]).item())\n", + " providers = [str(x) for x in np.asarray(bundle[\"provider_classes\"]).tolist()]\n", + " stage2_heads = {\n", + " str(p): [str(s) for s in np.asarray(bundle[f\"s2_{p}_subfamilies\"]).tolist()]\n", + " for p in np.asarray(bundle[\"stage2_version_classes\"]).tolist()\n", + " }\n", + "\n", + "sys.stdout.write(\n", + " json.dumps(\n", + " {\n", + " \"artifact\": weights_path.name,\n", + " \"size_mb\": round(weights_path.stat().st_size / (1024 * 1024), 2),\n", + " \"sha256\": sha256,\n", + " \"schema\": schema,\n", + " \"providers\": providers,\n", + " \"stage2_version_heads\": stage2_heads,\n", + " },\n", + " indent=2,\n", + " )\n", + " + \"\\n\"\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-abstention-demo", + "metadata": {}, + "outputs": [], + "source": [ + "from PIL import Image, ImageDraw\n", + "\n", + "import remove_ai_watermarks as raiw\n", + "\n", + "# Construct a clean non-AI procedural graphic (chart / UI card)\n", + "canvas = Image.new(\"RGB\", (768, 512), color=(248, 250, 252))\n", + "draw = ImageDraw.Draw(canvas)\n", + "draw.rectangle((48, 48, 720, 464), outline=(148, 163, 184), width=3)\n", + "for idx, bar_h in enumerate((120, 210, 165, 290, 245, 330)):\n", + " x0 = 96 + idx * 96\n", + " draw.rectangle((x0, 420 - bar_h, x0 + 56, 420), fill=(59, 130, 246))\n", + "\n", + "res = raiw.classify_source(canvas)\n", + "sys.stdout.write(\n", + " json.dumps(\n", + " {\n", + " \"label\": res.label,\n", + " \"version_subfamily\": res.version_subfamily,\n", + " \"reason\": res.reason,\n", + " \"confidence\": round(res.confidence, 4),\n", + " \"watermark_truth\": res.watermark_truth,\n", + " },\n", + " indent=2,\n", + " )\n", + " + \"\\n\"\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-custom-image", + "metadata": {}, + "outputs": [], + "source": [ + "from pathlib import Path\n", + "\n", + "# Set IMAGE_PATH to any local PNG/JPEG/WebP file (or upload one in Colab's Files sidebar)\n", + "IMAGE_PATH = \"\" # e.g. \"sample.jpg\"\n", + "\n", + "if IMAGE_PATH and Path(IMAGE_PATH).is_file():\n", + " prediction = raiw.classify_source(IMAGE_PATH)\n", + " sys.stdout.write(json.dumps(prediction.to_dict(), indent=2) + \"\\n\")\n", + "else:\n", + " sys.stdout.write(\"Set IMAGE_PATH to an image file to inspect its provider and version_subfamily prediction.\\n\")" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python", + "version": "3.12" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/docs/source-classify-hf/infer.py b/docs/source-classify-hf/infer.py new file mode 100644 index 0000000..6fde550 --- /dev/null +++ b/docs/source-classify-hf/infer.py @@ -0,0 +1,270 @@ +#!/usr/bin/env python3 +# /// script +# requires-python = ">=3.11,<3.15" +# dependencies = [ +# "remove-ai-watermarks[source-classify]>=0.62.0", +# ] +# /// +"""Standalone reference runner and pickle-free `.npz` weight inspector for `wiltodelta/raiw-source-classify`. + +Run directly without setting up a virtual environment via `uv`: + + uv run infer.py image.jpg + uv run infer.py ./images --json + uv run infer.py --inspect-weights + +This model identifies the likely AI generation/export pixel pipeline across 10 +provider families (`openai`, `google`, `bytedance`, `flux`, `stable_diffusion`, +`meta`, `midjourney`, `ideogram`, `firefly`, `xai`) or abstains with `unknown`. +It is not a provenance verifier and does not detect or verify SynthID or any +invisible watermark (`watermark_truth="unknown"`). +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import logging +import os +import sys +from pathlib import Path +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from collections.abc import Sequence + +_REPO_SRC = Path(__file__).resolve().parents[2] / "src" +if (_REPO_SRC / "remove_ai_watermarks").is_dir() and str(_REPO_SRC) not in sys.path: + sys.path.insert(0, str(_REPO_SRC)) + +log = logging.getLogger(__name__) + +SUPPORTED_IMAGE_SUFFIXES: frozenset[str] = frozenset( + {".png", ".jpg", ".jpeg", ".jpe", ".jfif", ".webp", ".heic", ".heif", ".avif"} +) + + +def _sha256_file(path: Path) -> str: + with path.open("rb") as handle: + return hashlib.file_digest(handle, "sha256").hexdigest() + + +def _resolve_artifact_path(weights_path: Path | None = None) -> Path: + from remove_ai_watermarks import source_classify as sc + + resolver = getattr(sc, "resolve_weights_path", None) + if callable(resolver): + return Path(resolver(weights_path)) + if weights_path is not None: + candidate = Path(weights_path).expanduser() + return candidate / sc.MODEL_FILE if candidate.is_dir() else candidate + override = os.environ.get(sc.WEIGHTS_ENV, "").strip() + if override: + candidate = Path(override).expanduser() + return candidate / sc.MODEL_FILE if candidate.is_dir() else candidate + from huggingface_hub import hf_hub_download + + downloaded = Path( + hf_hub_download( + repo_id=sc.WEIGHTS_REPO, + filename=sc.MODEL_FILE, + revision=sc.WEIGHTS_REVISION, + ) + ) + if _sha256_file(downloaded).lower() != sc.MODEL_SHA256.lower(): + raise RuntimeError(f"SHA-256 mismatch for {downloaded.name}") + return downloaded + + +def inspect_weights(weights_path: Path | None = None) -> dict[str, Any]: + """Inspect a pickle-free `.npz` source-classifier artifact (`allow_pickle=False`).""" + import numpy as np + + resolved = _resolve_artifact_path(weights_path) + size_bytes = resolved.stat().st_size + sha256 = _sha256_file(resolved) + + with np.load(resolved, allow_pickle=False) as data: + schema = str(np.asarray(data["schema"]).item()) + feature_dim = int(np.asarray(data["feature_dim"], dtype=np.int64).squeeze()) + cls_key = "provider_classes" if "provider_classes" in data else "all_ai_classes" + providers = [str(item) for item in np.asarray(data[cls_key]).tolist()] + + thresholds: dict[str, float] = {} + global_ai_threshold: float | None = None + if "det_thresholds" in data: + det_thr = np.asarray(data["det_thresholds"], dtype=np.float64).reshape(-1) + for idx, prov in enumerate(providers): + if idx < det_thr.shape[0]: + thresholds[prov] = round(float(det_thr[idx]), 6) + if det_thr.shape[0] > len(providers): + global_ai_threshold = round(float(det_thr[len(providers)]), 6) + elif "router_thresholds" in data: + r_thr = np.asarray(data["router_thresholds"], dtype=np.float64).reshape(-1) + for prov, val in zip(providers, r_thr.tolist(), strict=False): + thresholds[prov] = round(float(val), 6) + + version_subfamilies: dict[str, list[str]] = {} + if "stage2_version_classes" in data: + for p_cls in (str(x) for x in np.asarray(data["stage2_version_classes"]).tolist()): + key = f"s2_{p_cls}_subfamilies" + if key in data: + version_subfamilies[p_cls] = [str(x) for x in np.asarray(data[key]).tolist()] + + if "sub_names" in data and "sub_providers" in data: + sub_names = [str(x) for x in np.asarray(data["sub_names"]).tolist()] + sub_provs = [str(x) for x in np.asarray(data["sub_providers"]).tolist()] + for prov in providers: + if prov not in version_subfamilies: + subs = list( + dict.fromkeys( + s_name for s_name, s_prov in zip(sub_names, sub_provs, strict=False) if s_prov == prov + ) + ) + if subs: + version_subfamilies[prov] = subs + + array_count = len(data.files) + + summary: dict[str, Any] = { + "artifact_file": resolved.name, + "resolved_path": str(resolved), + "size_bytes": size_bytes, + "sha256": sha256, + "pickle_free": True, + "schema": schema, + "feature_dim": feature_dim, + "array_count": array_count, + "providers": providers, + "abstain_label": "unknown", + "watermark_truth": "unknown", + "thresholds": thresholds, + "version_subfamilies": version_subfamilies, + } + if global_ai_threshold is not None: + summary["global_ai_threshold"] = global_ai_threshold + return summary + + +def _expand_targets(targets: Sequence[Path]) -> list[Path]: + expanded: list[Path] = [] + for target in targets: + if target.is_dir(): + expanded.extend( + sorted( + path + for path in target.iterdir() + if path.is_file() and path.suffix.lower() in SUPPORTED_IMAGE_SUFFIXES + ) + ) + else: + expanded.append(target) + return expanded + + +def classify_targets( + targets: Sequence[Path], + *, + weights_path: Path | None = None, +) -> list[dict[str, Any]]: + """Run `classify_source` over image files or directories and return JSON-ready rows.""" + import remove_ai_watermarks as raiw + + rows: list[dict[str, Any]] = [] + for image_path in _expand_targets(targets): + res = raiw.classify_source(image_path, weights_path=weights_path) + rows.append({"path": str(image_path), **res.to_dict()}) + return rows + + +def _write_human_inspection(summary: dict[str, Any]) -> None: + lines = [ + f"Artifact: {summary['artifact_file']} ({summary['size_bytes']:,} bytes, allow_pickle=False)", + f"SHA-256: {summary['sha256']}", + f"Schema: {summary['schema']} (feature_dim={summary['feature_dim']}, arrays={summary['array_count']})", + f"Classes: {', '.join(summary['providers'])} + {summary['abstain_label']}", + "Scope: pixel source/export pipeline attribution only (watermark_truth='unknown')", + "Stage-2 version subfamilies:", + ] + for prov in summary["providers"]: + subs = summary["version_subfamilies"].get(prov, []) + if subs: + lines.append(f" - {prov}: {', '.join(subs)}") + sys.stdout.write("\n".join(lines) + "\n") + + +def _write_human_predictions(rows: Sequence[dict[str, Any]]) -> None: + for row in rows: + sub = row.get("version_subfamily") or "-" + conf = float(row.get("confidence", 0.0)) + sys.stdout.write( + f"{row['path']}\tlabel={row['label']}\tversion={sub}\t" + f"confidence={conf:.4f}\treason={row['reason']}\twatermark_truth={row['watermark_truth']}\n" + ) + + +def main(argv: Sequence[str] | None = None) -> int: + """CLI entry point for standalone weight inspection and batch/single inference.""" + parser = argparse.ArgumentParser( + description="Run or inspect the CPU-only RAIW 10-provider source-pipeline classifier." + ) + parser.add_argument( + "targets", + nargs="*", + type=Path, + help="Image file(s) or directory(ies) to classify.", + ) + parser.add_argument( + "--weights", + type=Path, + default=None, + help="Optional local .npz file or directory override (defaults to Hub or RAIW_SOURCE_CLASSIFY_WEIGHTS).", + ) + parser.add_argument( + "--inspect-weights", + action="store_true", + help="Inspect the pickle-free .npz artifact schema, thresholds, and Stage-2 version subfamilies.", + ) + parser.add_argument( + "--json", + action="store_true", + help="Emit structured JSON output.", + ) + args = parser.parse_args(list(argv) if argv is not None else None) + logging.basicConfig(level=logging.WARNING, format="%(levelname)s: %(message)s") + + if not args.inspect_weights and not args.targets: + parser.print_usage(sys.stderr) + log.error("Provide one or more image/directory targets, or pass --inspect-weights.") + return 2 + + missing = [str(p) for p in args.targets if not p.exists()] + if missing: + log.error("Target path does not exist: %s", ", ".join(missing)) + return 2 + + if args.inspect_weights and not args.targets: + summary = inspect_weights(args.weights) + if args.json: + sys.stdout.write(json.dumps(summary, indent=2) + "\n") + else: + _write_human_inspection(summary) + return 0 + + rows = classify_targets(args.targets, weights_path=args.weights) + if args.inspect_weights: + payload = {"weights": inspect_weights(args.weights), "predictions": rows} + sys.stdout.write(json.dumps(payload, indent=2) + "\n") + return 0 + + if args.json: + out: Any = rows[0] if len(rows) == 1 and args.targets[0].is_file() else rows + sys.stdout.write(json.dumps(out, indent=2) + "\n") + else: + _write_human_predictions(rows) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/docs/supported-signals.md b/docs/supported-signals.md index deeada5..6ec5e39 100644 --- a/docs/supported-signals.md +++ b/docs/supported-signals.md @@ -15,7 +15,7 @@ The `visible` command registers these mark keys: | `jimeng` | `★ 即梦AI` | Bottom right | Vendor specific text detector. | | `qwen` | `千问AI生成` or the three-lobe Qwen symbol | Bottom right | Separate strict templates cover the text and Qwen Create symbol variants. | | `wan` | Wan logo and `Wan` wordmark | Bottom right, hugging the corner | Provisional: one real Wan 2.7 Pro export. Requires NCC >= 0.55 and a match that ends within 0.015 of the short side from both edges. | -| `kling` | `可灵AI 3.0` or `KlingAI 3.0` | Bottom right | Separate calibrated silhouettes cover the older CJK and current IMAGE 3.0 Latin variants; a glyph-detail gate rejects plain UI boundaries. | +| `kling` | `可灵AI 3.0`/`4.0` or `KlingAI 3.0`/`4.0` | Bottom right | Separate calibrated silhouettes cover the CJK and Latin 3.0/4.0 variants; a glyph-detail gate rejects plain UI boundaries. | | `yuanbao` | `元宝` over `AI生成` | Bottom right | Separate strict and provenance-corroborated templates cover the measured two-line rasterizations. | | `dola` | `Dola AI` | Bottom right | Text detector and detector-aligned wordmark footprint. | | `workbuddy` | `AI生成` and `WORKBUDDY>_` | Bottom right | Separate templates cover the single-line and stacked two-line layouts; corroborated by the registered Tencent WorkBuddy TC260 producer code. | @@ -63,7 +63,7 @@ pill detector; the generic pill shape does not attribute LiblibAI on its own. `video identify`, `video visible`, and `video all` share this registry and the same temporal arbiter. It is separate from the image registry because selection is made over a sequence rather than one raster. The default `auto` mode scans -all seven entries in one decode pass and selects the first temporally stable +all eight entries in one decode pass and selects the first temporally stable match in table order, subject to the Veo/Sora overlap exception above; an explicit mark restricts the scan to that row. Accepted fills are motion-aligned across adjacent frames by default. The prior @@ -369,7 +369,9 @@ not a universal clean verdict. | Honor YOYO AI editing | No registered AI mark; forum account overlay is separate | No registered pixel decoder | EXIF UserComment TC260 AIGC with nested RSA/content signature, reported unsupported | | Samsung Galaxy AI | One locale specific mark | No registered pixel decoder | C2PA and Samsung markers | | Google Photos AI edits | None | SynthID provenance inference: 4/4 earlier edits positive (2026-09-25); large eraser and restyle positive, two small edits indeterminate (2026-10-01 UTC). No SynthID action in the manifest | C2PA signed "Google Photos" with a `compositeWithTrainedAlgorithmicMedia` action, plus XMP `photoshop:Credit` `Edited with Google AI` | -| Apple Image Playground and Photos Clean Up | None | No registered pixel decoder; SynthID announced by Apple for a later update | XMP `photoshop:Credit` (`Apple Image Playground`, `Apple Photos Generative Edit: Clean Up`) plus IPTC digitalSourceType; no C2PA on measured 2026-09 output | +| Apple Image Playground and Photos Clean Up | None | No registered pixel decoder; SynthID announced by Apple for a later update | XMP `photoshop:Credit` (`Apple Image Playground`, `Apple Photos Generative Edit: Clean Up`) with or without IPTC `digitalSourceType`; no C2PA on measured 2026-09 output | +| xAI Grok / Aurora / Grok Imagine | None | No registered pixel decoder | C2PA signed `xAI Grok Imagine`, legacy EXIF/XMP/PNG/IPTC `Signature: ` + UUID pair, and ISOBMFF `\xa9cmt` / `comment` `Signature: ` video tag | +| Topaz Labs and CyberLink PhotoDirector | None | No registered pixel decoder | C2PA attribution when an AI `DigitalSourceType` is present (`asserts_ai=False`), plus ISOBMFF `topazcloud*` / `videoai*` video metadata | For detector thresholds, measured limits, and incident history, see [module internals](module-internals.md) and diff --git a/pyproject.toml b/pyproject.toml index 79e80a9..57fb1c3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ # on it, including the ComfyUI node package. The console script below carries # the same weight, since users have it on PATH. name = "remove-ai-watermarks" -version = "0.62.0" +version = "0.62.1" description = "AI watermark remover for visible, invisible, and provenance marks in images and video" readme = "README.md" requires-python = ">=3.11,<3.15" diff --git a/scripts/corpus_gap_scan.py b/scripts/corpus_gap_scan.py index 52b3460..ff18dae 100644 --- a/scripts/corpus_gap_scan.py +++ b/scripts/corpus_gap_scan.py @@ -49,6 +49,7 @@ from pathlib import Path from typing import TYPE_CHECKING, Any if TYPE_CHECKING: + from collections.abc import Mapping, Sequence from datetime import date import click @@ -60,7 +61,9 @@ from remove_ai_watermarks.identify import extract_provenance_evidence, identify_ from remove_ai_watermarks.metadata import ( IPTC_AI_FIELD_MARKERS, IPTC_AI_MARKERS, + KLING_SEI_TAG, aigc_label_from_metadata, + app_generator_from_metadata, c2pa_marker_in, samsung_genai_in, scan_head, @@ -79,22 +82,46 @@ MARKERS: tuple[bytes, ...] = ( # AI source-type / labeling schemes that are meaningful by presence. b"trainedAlgorithmicMedia", b"AISystemUsed", + b"c2pa.ai-disclosure", b"hf-job-id", - # Distinctive multi-word generator strings only. Bare single words (Luma, - # Gemini, Sora, ...) are omitted: they collide with unrelated metadata prose - # (e.g. "Luma" in Lightroom's EnhanceDenoiseLumaAmount), defeating precision. + # Distinctive multi-word or domain-scoped generator strings only. Bare single + # words (Luma, Gemini, Sora, ...) are omitted: they collide with unrelated + # metadata prose (e.g. "Luma" in Lightroom's EnhanceDenoiseLumaAmount), + # defeating precision. b"Midjourney", b"Stable Diffusion", b"StableDiffusion", b"ComfyUI", b"Automatic1111", + b"InvokeAI", b"DALL-E", + b"gpt-image", + b"GPT Image", b"Ideogram AI", b"Adobe Firefly", b"Black Forest", b"volcengine", + b"Byteplus", b"Nano Banana", b"Stability AI", + b"DreamStudio", + b"NightCafe", + b"NovelAI", + b"reve.com", + b"Luma AI", + b"lumalabs", + b"Aphrodite AI", + b"Apple Image Playground", + b"Apple Photos Generative Edit", + b"Apple Photos Clean Up", + b"Grok Imagine", + b"Amazon Bedrock", + b"Higgsfield AI", + b"recraft.ai", + b"fal-ai", + b"Producer.ai", + b"Synchronicity Labs", + b"Runway AI", ) REPORT_FIELDS: tuple[str, ...] = ( "report_schema_version", @@ -139,20 +166,51 @@ def _row(rep, *, path: str, suffix: str, lib_version: str) -> dict[str, str]: # } +_LOWERED_MARKERS: tuple[tuple[str, bytes], ...] = tuple( + (marker.decode("latin-1", "replace"), marker.lower()) for marker in MARKERS +) +_STRUCTURAL_VIDEO_METADATA_KEYS: frozenset[str] = frozenset( + { + "actions", + "c2pa_manifest", + "c2pa_signer_validity", + "c2pa_validation_source", + "c2pa_validation_state", + "claim_generator", + "issuer", + "source_type", + } +) + + +def _c2pa_fields(mapping: Mapping[str, object]) -> dict[str, str]: + return { + "c2pa_issuer": str(mapping.get("issuer", "")), + "c2pa_claim_generator": str(mapping.get("claim_generator", "")), + "c2pa_actions": str(mapping.get("actions", "")), + "c2pa_source_type": str(mapping.get("source_type", "")), + "c2pa_validation": str(mapping.get("c2pa_validation_state", "")), + } + + def _marker_hits(region: bytes) -> list[str]: """Return high-precision marker labels found in one metadata region.""" folded = region.lower() - hits = {marker.decode("latin-1", "replace") for marker in MARKERS if marker.lower() in folded} + hits = {label for label, lowered in _LOWERED_MARKERS if lowered in folded} if c2pa_marker_in(region): hits.add("C2PA/JUMBF") if aigc_label_from_metadata(region) is not None: hits.add("TC260 AIGC") + if app_generator_from_metadata(region) is not None: + hits.add("App AIGC disclosure") if any(marker in region for marker in IPTC_AI_MARKERS + IPTC_AI_FIELD_MARKERS): hits.add("IPTC AI disclosure") if samsung_genai_in(region) is not None: hits.add("Samsung genAIType") if xai_signature_in_metadata(region): hits.add("xAI signature pair") + if KLING_SEI_TAG in region: + hits.add("Kling SEI tag") return sorted(hits) @@ -164,7 +222,7 @@ def _marker_hits_for_path(path: Path) -> list[str]: return [] -def _candidate_classes(rep: Any, hits: list[str]) -> list[str]: +def _candidate_classes(rep: Any, hits: Sequence[str]) -> list[str]: """Classify review-worthy outcomes without treating them as proven bugs.""" classes: list[str] = [] if hits and not rep.is_ai_generated and not rep.signals: @@ -190,10 +248,38 @@ def _files(corpus: Path, since: date | None) -> list[Path]: def _scan_one(args: tuple[str, str, str]) -> dict[str, str]: """Scan one path in a worker process and always return a report row.""" + from types import SimpleNamespace + + from remove_ai_watermarks.video import VIDEO_EXTENSIONS, identify_video + path_str, relative_path, lib_version = args path = Path(path_str) suffix = path.suffix.lower() try: + if suffix in VIDEO_EXTENSIONS: + vrep = identify_video(path, check_visible=False) + markers_str = "|".join(vrep.metadata_markers.keys()) + row = { + **_base_row(relative_path, suffix, lib_version), + "is_ai": str(vrep.is_ai_generated), + "platform": vrep.platform or "", + "confidence": vrep.confidence, + "watermarks": markers_str, + "signals": markers_str, + **_c2pa_fields(vrep.metadata_markers), + } + hits = _marker_hits_for_path(path) + ai_signals = sorted(set(vrep.metadata_markers.keys()) - _STRUCTURAL_VIDEO_METADATA_KEYS) + video_summary = SimpleNamespace( + is_ai_generated=vrep.is_ai_generated, + platform=vrep.platform, + signals=ai_signals, + integrity_clashes=(), + ) + row["markers"] = "|".join(hits) + row["candidate_classes"] = "|".join(_candidate_classes(video_summary, hits)) + return row + evidence = extract_provenance_evidence(path) rep = identify_from_evidence(evidence) except Exception as exc: @@ -201,21 +287,14 @@ def _scan_one(args: tuple[str, str, str]) -> dict[str, str]: row = _base_row(relative_path, suffix, lib_version) row["candidate_classes"] = "identify_error" row["error"] = f"{type(exc).__name__}: {exc}"[:300].replace("\n", " ") - else: - row = _row(rep, path=relative_path, suffix=suffix, lib_version=lib_version) - c2pa = evidence.c2pa_info - row.update( - c2pa_issuer=str(c2pa.get("issuer", "")), - c2pa_claim_generator=str(c2pa.get("claim_generator", "")), - c2pa_actions=str(c2pa.get("actions", "")), - c2pa_source_type=str(c2pa.get("source_type", "")), - c2pa_validation=str(c2pa.get("c2pa_validation_state", "")), - ) - hits = _marker_hits(identify_metadata_region(evidence.scan)) - row["markers"] = "|".join(hits) - row["candidate_classes"] = "|".join(_candidate_classes(rep, hits)) + row["markers"] = "|".join(_marker_hits_for_path(path)) return row - row["markers"] = "|".join(_marker_hits_for_path(path)) + + row = _row(rep, path=relative_path, suffix=suffix, lib_version=lib_version) + row.update(_c2pa_fields(evidence.c2pa_info)) + hits = _marker_hits(identify_metadata_region(evidence.scan)) + row["markers"] = "|".join(hits) + row["candidate_classes"] = "|".join(_candidate_classes(rep, hits)) return row diff --git a/scripts/publish_source_classify_hf.py b/scripts/publish_source_classify_hf.py index 165a482..1cc46d3 100644 --- a/scripts/publish_source_classify_hf.py +++ b/scripts/publish_source_classify_hf.py @@ -35,7 +35,7 @@ RETIRED_FILES = ( ) REPO_ROOT = Path(__file__).resolve().parents[1] CARD_DIR = REPO_ROOT / "docs" / "source-classify-hf" -TRACKED_CARD_FILES = ("README.md", "metrics.json") +TRACKED_CARD_FILES = ("README.md", "metrics.json", "infer.py", "demo.ipynb") PUBLIC_FILES = (*TRACKED_CARD_FILES, CONFIG_FILE, MODEL_FILE) diff --git a/scripts/render_vendor_silhouettes.py b/scripts/render_vendor_silhouettes.py index 44aeafb..0678b65 100644 --- a/scripts/render_vendor_silhouettes.py +++ b/scripts/render_vendor_silhouettes.py @@ -43,12 +43,15 @@ MARKS = { # is dominant. "yuanbao_alpha.png": "元宝\nAI生成", # Older Kling (可灵) exports stamp a thin light-gray one-line "可灵AI 3.0" - # bottom-right. The leading spiral logo is NOT rendered (logos vary; the text - # run discriminates). + # bottom-right, and 4.0 exports update the trailing major version. The leading + # spiral logo is NOT rendered (logos vary; the text run discriminates). "kling_alpha.png": "可灵AI 3.0", - # Current IMAGE 3.0 exports use the Latin ``KlingAI 3.0`` run. Keep it as a - # second installed silhouette rather than replacing the measured CJK variant. + "kling_4_alpha.png": "可灵AI 4.0", + # Current IMAGE 3.0 / 4.0 exports use the Latin ``KlingAI 3.0`` / ``KlingAI 4.0`` + # runs. Keep them as separate installed silhouettes rather than replacing the + # measured CJK variants. "kling_latin_alpha.png": "KlingAI 3.0", + "kling_latin_4_alpha.png": "KlingAI 4.0", # The "cat-logo" candidate stamps an outline cat-head plus bold "AI生成", # bottom-right. It remains unregistered pending sufficient calibration coverage. "catlogo_alpha.png": "cat logo + AI生成", @@ -107,11 +110,12 @@ MARK_OPTS: dict[str, dict[str, Any]] = { # LibLibAI uses an Arial-class grotesque. "liblib_alpha.png": {"font": "/System/Library/Fonts/Supplemental/Arial.ttf"}, "kling_latin_alpha.png": {"font": "/System/Library/Fonts/HelveticaNeue.ttc", "font_index": 1}, + "kling_latin_4_alpha.png": {"font": "/System/Library/Fonts/HelveticaNeue.ttc", "font_index": 1}, } -# ``kling_latin`` is a variant of the registered ``kling`` row, not a second -# registry key, so it cannot be derived from ``mark_keys()`` above. -_REGISTERED.add("kling_latin_alpha.png") +# Variant silhouettes of the registered ``kling`` row cannot be derived from +# ``mark_keys()`` above because they share the single ``kling`` registry key. +_REGISTERED.update({"kling_4_alpha.png", "kling_latin_alpha.png", "kling_latin_4_alpha.png"}) def _fit_font( diff --git a/server.json b/server.json index 4a4c13d..3ed9387 100644 --- a/server.json +++ b/server.json @@ -3,7 +3,7 @@ "name": "io.github.wiltodelta/remove-ai-watermarks", "title": "Remove AI Watermarks", "description": "Identify and clean AI watermarks and provenance in your own images, video, and text.", - "version": "0.62.0", + "version": "0.62.1", "repository": { "url": "https://github.com/wiltodelta/remove-ai-watermarks", "source": "github" @@ -14,7 +14,7 @@ "registryType": "pypi", "registryBaseUrl": "https://pypi.org", "identifier": "remove-ai-watermarks", - "version": "0.62.0", + "version": "0.62.1", "runtimeHint": "uvx", "transport": { "type": "stdio" diff --git a/src/remove_ai_watermarks/__init__.py b/src/remove_ai_watermarks/__init__.py index c8d0050..253405e 100644 --- a/src/remove_ai_watermarks/__init__.py +++ b/src/remove_ai_watermarks/__init__.py @@ -39,7 +39,7 @@ _os.environ.setdefault("TRANSFORMERS_VERBOSITY", "error") _warnings.filterwarnings("ignore", message=r".*ImageProcessorFast.*") -__version__ = "0.62.0" +__version__ = "0.62.1" __all__ = [ "BatchItemResult", diff --git a/src/remove_ai_watermarks/_internal/constants.py b/src/remove_ai_watermarks/_internal/constants.py index 4eea6f5..03eb793 100644 --- a/src/remove_ai_watermarks/_internal/constants.py +++ b/src/remove_ai_watermarks/_internal/constants.py @@ -186,6 +186,11 @@ C2PA_AI_VENDORS: tuple[C2paAiVendor, ...] = ( # conformance list spells the organization "Runway AI, Inc". _vendor(b"RUNWAY AI, INC.", "Runway", "Runway", "Runway"), _vendor(b"Runway AI, Inc", "Runway", "Runway", "Runway"), + # Topaz Labs and CyberLink PhotoDirector sign both AI-enhanced exports (which + # record compositeWithTrainedAlgorithmicMedia) and non-AI edits, so identity + # alone never asserts AI origin (asserts_ai=False, matching Adobe and Canva). + _vendor(b"Topaz Labs", "Topaz Labs", "Topaz Labs", "Topaz"), + _vendor(b"PhotoDirector", "CyberLink PhotoDirector", "CyberLink PhotoDirector", "CyberLink"), _vendor(b"Truepic", "Truepic", None, None), ) @@ -320,6 +325,7 @@ AI_GENERATOR_TOKENS = frozenset( "invokeai", "imagen", "gpt-image", + "gpt image", "nano banana", "nightcafe", "ideogram", diff --git a/src/remove_ai_watermarks/_internal/isobmff.py b/src/remove_ai_watermarks/_internal/isobmff.py index f816634..784e874 100644 --- a/src/remove_ai_watermarks/_internal/isobmff.py +++ b/src/remove_ai_watermarks/_internal/isobmff.py @@ -28,6 +28,7 @@ Reference: ISO/IEC 14496-12 (ISOBMFF) and C2PA 2.1 spec §11. from __future__ import annotations +import base64 import io import logging import os @@ -37,9 +38,11 @@ import struct from typing import TYPE_CHECKING, Any, BinaryIO if TYPE_CHECKING: - from collections.abc import Iterator + from collections.abc import Callable, Iterable, Iterator from pathlib import Path + _RawMetadataItem = tuple[bytes, tuple[int, int], bytes | None, tuple[int, int] | None, int, int, bytes] + from remove_ai_watermarks.metadata import ( AIGC_MARKERS, C2PA_UUID, @@ -48,8 +51,11 @@ from remove_ai_watermarks.metadata import ( KLING_SEI_TAG, LOCAL_GENERATION_METADATA_KEYS, MAX_TC260_VALUE_BYTES, + TOPAZ_AI_DESCRIPTION, + TOPAZ_VIDEO_METADATA_KEYS, app_generator_from_metadata, app_provenance_from_metadata, + generator_from_metadata, parse_tc260_aigc_json, ) @@ -72,6 +78,9 @@ _AI_LABEL_MARKERS: tuple[bytes, ...] = AIGC_MARKERS + IPTC_AI_MARKERS + IPTC_AI_ # out of reach of the top-level box stripper, so an AI-label packet there is # blanked in place (see ``blank_ai_xmp_packets``). _XMP_PACKET_RE = re.compile(rb"<\?xpacket begin=.*?<\?xpacket end=[^>]*?\?>", re.DOTALL) +_ISOBMFF_XAI_SIG_RE = re.compile(rb"Signature:\s*([A-Za-z0-9+/=]{64,})\s*") +_XAI_REGION_SENTINEL_START = b"\xa9cmt\x00" +_XAI_REGION_SENTINEL_END = b"\x00" _STREAM_COPY_BYTES = 1024 * 1024 STREAM_SCAN_BYTES = 4 * 1024 * 1024 @@ -247,6 +256,8 @@ def _iter_tc260_meta_boxes( def _tc260_aigc_regions( stream: BinaryIO, file_size: int, + *, + raw_items: Iterable[_RawMetadataItem] | None = None, ) -> list[tuple[tuple[int, int] | None, int, int, bytes]]: """Locate validated native TC260 entries without reading media payloads. @@ -256,19 +267,27 @@ def _tc260_aigc_regions( iOS export writes, where the JSON sits in a bare ``ilst`` data item with no key name to blank. """ + items = ( + ( + (key_name, key_span, value_start, value_end, value) + for _item_type, _item_span, key_name, key_span, value_start, value_end, value in raw_items + ) + if raw_items is not None + else _metadata_items(stream, file_size) + ) return [ (key_span, value_start, value_end, value) - for key_name, key_span, value_start, value_end, value in _metadata_items(stream, file_size) + for key_name, key_span, value_start, value_end, value in items if (key_name is None or key_name == b"AIGC") and parse_tc260_aigc_json(value) is not None ] -def _moov_metadata_items( +def _moov_raw_metadata_items( stream: BinaryIO, moov_payload: int, moov_end: int, -) -> Iterator[tuple[bytes | None, tuple[int, int] | None, int, int, bytes]]: - """Yield bounded keyed or keyless metadata-list values from one ``moov`` box.""" +) -> Iterator[tuple[bytes, tuple[int, int], bytes | None, tuple[int, int] | None, int, int, bytes]]: + """Yield bounded keyed or keyless metadata-list entries with item-box spans.""" for meta_payload, meta_end in _iter_tc260_meta_boxes(stream, moov_payload, moov_end): keys: dict[int, tuple[bytes, tuple[int, int]]] = {} ilst_boxes: list[tuple[int, int]] = [] @@ -286,7 +305,7 @@ def _moov_metadata_items( if not ilst_boxes: continue for ilst_payload, ilst_end in ilst_boxes: - for _item_start, item_end, item_type, item_payload in iter_file_boxes( + for item_start, item_end, item_type, item_payload in iter_file_boxes( stream, ilst_payload, ilst_end, @@ -302,6 +321,7 @@ def _moov_metadata_items( # validation below. continue key_name, key_span = key if key is not None else (None, None) + item_type_span = (item_start + 4, item_start + 8) for _data_start, data_end, data_type, data_payload in iter_file_boxes( stream, item_payload, @@ -314,7 +334,98 @@ def _moov_metadata_items( stream.seek(value_start) value = stream.read(value_size) if len(value) == value_size: - yield key_name, key_span, value_start, data_end, value + yield item_type, item_type_span, key_name, key_span, value_start, data_end, value + + +def _raw_metadata_items( + stream: BinaryIO, + file_size: int, +) -> Iterator[tuple[bytes, tuple[int, int], bytes | None, tuple[int, int] | None, int, int, bytes]]: + """Yield bounded keyed or keyless metadata-list entries across all ``moov`` boxes.""" + for _moov_start, moov_end, moov_type, moov_payload in iter_file_boxes(stream, 0, file_size): + if moov_type == b"moov": + yield from _moov_raw_metadata_items(stream, moov_payload, moov_end) + + +def _is_isobmff_xai_signature(item_type: bytes, key_name: bytes | None, value: bytes) -> bool: + """Whether one ISOBMFF comment item holds an xAI Grok Imagine ``Signature: `` blob.""" + is_comment = (key_name is None and item_type == b"\xa9cmt") or ( + key_name is not None and key_name.lower() in {b"comment", b"com.apple.quicktime.comment"} + ) + if not is_comment: + return False + match = _ISOBMFF_XAI_SIG_RE.fullmatch(value) + if match is None: + return False + blob = match.group(1) + if len(blob) % 4 != 0: + return False + try: + base64.b64decode(blob, validate=True) + except ValueError: + return False + return True + + +def _xai_signature_regions( + stream: BinaryIO, + file_size: int, + *, + raw_items: Iterable[_RawMetadataItem] | None = None, +) -> list[tuple[tuple[int, int], int, int, bytes]]: + """Locate xAI Grok Imagine ``Signature:`` comment items in ``moov`` metadata lists.""" + items = raw_items if raw_items is not None else _raw_metadata_items(stream, file_size) + return [ + (key_span if key_span is not None else item_span, value_start, value_end, value) + for item_type, item_span, key_name, key_span, value_start, value_end, value in items + if _is_isobmff_xai_signature(item_type, key_name, value) + ] + + +def _read_isobmff_payloads( + path: str | Path, + region_fn: Callable[[BinaryIO, int], Iterable[tuple[Any, int, int, bytes]]], + *, + strict: bool = False, +) -> tuple[bytes, ...]: + """Read validated payload bytes from an ISOBMFF region finder without loading ``mdat``.""" + try: + with open(path, "rb") as stream: + if not is_isobmff(stream.read(8)): + return () + stream.seek(0, 2) + file_size = stream.tell() + return tuple(region[3] for region in region_fn(stream, file_size)) + except OSError: + if strict: + raise + return () + + +def isobmff_xai_signature_payloads(path: str | Path, *, strict: bool = False) -> tuple[bytes, ...]: + """Read validated xAI Grok Imagine comment signatures without reading media payloads.""" + return _read_isobmff_payloads(path, _xai_signature_regions, strict=strict) + + +def has_isobmff_xai_signature(path: str | Path, *, strict: bool = False) -> bool: + """Whether an ISOBMFF container carries an xAI Grok Imagine comment signature.""" + return bool(isobmff_xai_signature_payloads(path, strict=strict)) + + +def isobmff_xai_signature_in_region(data: bytes) -> bool: + """Whether an ISOBMFF metadata region carries an xAI Grok Imagine comment signature.""" + if not is_isobmff(data): + return False + if _xai_signature_regions(io.BytesIO(data), len(data)): + return True + start = data.find(_XAI_REGION_SENTINEL_START) + while start != -1: + val_start = start + len(_XAI_REGION_SENTINEL_START) + val_end = data.find(_XAI_REGION_SENTINEL_END, val_start) + if val_end != -1 and _is_isobmff_xai_signature(b"\xa9cmt", None, data[val_start:val_end]): + return True + start = data.find(_XAI_REGION_SENTINEL_START, start + 1) + return False def _metadata_items( @@ -322,40 +433,40 @@ def _metadata_items( file_size: int, ) -> Iterator[tuple[bytes | None, tuple[int, int] | None, int, int, bytes]]: """Yield bounded keyed or keyless metadata-list values from a media file.""" - for _moov_start, moov_end, moov_type, moov_payload in iter_file_boxes(stream, 0, file_size): - if moov_type == b"moov": - yield from _moov_metadata_items(stream, moov_payload, moov_end) + for _item_type, _item_span, key_name, key_span, value_start, data_end, value in _raw_metadata_items( + stream, + file_size, + ): + yield key_name, key_span, value_start, data_end, value def tc260_aigc_payloads(path: str | Path, *, strict: bool = False) -> tuple[bytes, ...]: """Read native TC260 ``AIGC`` values, optionally propagating I/O failures.""" - try: - with open(path, "rb") as stream: - if not is_isobmff(stream.read(8)): - return () - stream.seek(0, 2) - file_size = stream.tell() - return tuple(region[3] for region in _tc260_aigc_regions(stream, file_size)) - except OSError: - if strict: - raise - return () + return _read_isobmff_payloads(path, _tc260_aigc_regions, strict=strict) def _ai_metadata_regions( stream: BinaryIO, file_size: int, + *, + raw_items: Iterable[_RawMetadataItem] | None = None, ) -> list[tuple[tuple[int, int], int, int, str, bytes]]: """Locate keyed generation metadata without reading media payloads.""" + items = raw_items if raw_items is not None else _raw_metadata_items(stream, file_size) regions: list[tuple[tuple[int, int], int, int, str, bytes]] = [] - for name_bytes, key_span, value_start, value_end, value in _metadata_items(stream, file_size): + for _item_type, _item_span, name_bytes, key_span, value_start, value_end, value in items: if name_bytes is None or key_span is None: continue try: name = name_bytes.decode("utf-8") except UnicodeDecodeError: continue - if name.lower() in LOCAL_GENERATION_METADATA_KEYS: + lowered = name.lower() + if ( + lowered in LOCAL_GENERATION_METADATA_KEYS + or lowered in TOPAZ_VIDEO_METADATA_KEYS + or (lowered in {"description", "com.apple.quicktime.description"} and value.strip() == TOPAZ_AI_DESCRIPTION) + ): regions.append((key_span, value_start, value_end, name, value)) return regions @@ -363,6 +474,8 @@ def _ai_metadata_regions( def _app_metadata_regions( stream: BinaryIO, file_size: int, + *, + raw_items: Iterable[_RawMetadataItem] | None = None, ) -> list[tuple[tuple[int, int] | None, int, int]]: """Locate keyed or keyless values carrying an app-export provenance object. @@ -370,9 +483,10 @@ def _app_metadata_regions( second copy under ``com.apple.quicktime.artwork``). The file-level scan reads it from the raw head bytes, so removal must blank every item it would match. """ + items = raw_items if raw_items is not None else _raw_metadata_items(stream, file_size) return [ (key_span, value_start, value_end) - for _name, key_span, value_start, value_end, value in _metadata_items(stream, file_size) + for _item_type, _item_span, _name, key_span, value_start, value_end, value in items if app_provenance_from_metadata(value) or app_generator_from_metadata(value) ] @@ -568,14 +682,27 @@ def scan_c2pa_region(path: str | Path, *, max_total: int = 4 * 1024 * 1024, stri if to_read > 0: collected += f.read(to_read) elif box_type == b"moov": - for _key_name, _key_span, _val_start, _val_end, value in _moov_metadata_items( + for ( + item_type, + _item_span, + key_name, + _key_span, + _val_start, + _val_end, + value, + ) in _moov_raw_metadata_items( f, payload_off, pos + size, ): - to_read = min(len(value), max_total - len(collected)) + entry = ( + _XAI_REGION_SENTINEL_START + value + _XAI_REGION_SENTINEL_END + if _is_isobmff_xai_signature(item_type, key_name, value) + else value + ) + to_read = min(len(entry), max_total - len(collected)) if to_read > 0: - collected += value[:to_read] + collected += entry[:to_read] pos += size except OSError: if strict: @@ -584,6 +711,11 @@ def scan_c2pa_region(path: str | Path, *, max_total: int = 4 * 1024 * 1024, stri return bytes(collected) +def _has_ai_label_or_generator(payload: bytes) -> bool: + """Whether a metadata payload carries an AI-label marker or known AI generator.""" + return any(marker in payload for marker in _AI_LABEL_MARKERS) or generator_from_metadata((), payload) is not None + + def _payload_has_ai_label( stream: BinaryIO, start: int, @@ -601,7 +733,7 @@ def _payload_has_ai_label( if not chunk: return False searchable = overlap + chunk - if any(marker in searchable for marker in _AI_LABEL_MARKERS): + if _has_ai_label_or_generator(searchable): return True overlap = searchable[-(longest_marker - 1) :] remaining -= len(chunk) @@ -698,9 +830,28 @@ def strip_isobmff_media_file( file_size, max_scan=max_box_scan, ) - tc260_regions = _tc260_aigc_regions(stream, file_size) if targets is not None else [] - ai_metadata_regions = _ai_metadata_regions(stream, file_size) if targets is not None else [] - app_regions = _app_metadata_regions(stream, file_size) if targets is not None else [] + raw_items = list(_raw_metadata_items(stream, file_size)) if targets is not None else [] + blank_regions: list[tuple[tuple[int, int] | None, int, int]] = [] + if targets is not None: + blank_regions.extend( + (key_span, value_start, value_end) + for key_span, value_start, value_end, _value in _tc260_aigc_regions( + stream, file_size, raw_items=raw_items + ) + ) + blank_regions.extend( + (key_span, value_start, value_end) + for key_span, value_start, value_end, _name, _value in _ai_metadata_regions( + stream, file_size, raw_items=raw_items + ) + ) + blank_regions.extend(_app_metadata_regions(stream, file_size, raw_items=raw_items)) + blank_regions.extend( + (key_span, value_start, value_end) + for key_span, value_start, value_end, _value in _xai_signature_regions( + stream, file_size, raw_items=raw_items + ) + ) mdat_ranges = ( [ (payload, end) @@ -710,9 +861,7 @@ def strip_isobmff_media_file( if targets is not None else [] ) - tc260_key_spans = {region[0] for region in tc260_regions if region[0] is not None} - ai_metadata_key_spans = {region[0] for region in ai_metadata_regions} - app_key_spans = {region[0] for region in app_regions if region[0] is not None} + blanked_key_spans = {key_span for key_span, _v0, _v1 in blank_regions if key_span is not None} with atomic_video_output(output_path) as temporary_path: with source_path.open("rb") as source_stream, temporary_path.open("r+b") as temporary: @@ -722,19 +871,11 @@ def strip_isobmff_media_file( temporary.seek(box_start + 4) temporary.write(b"free") _overwrite_range(temporary, payload_start, box_end, byte=b"\x00") - for key_span, value_start, value_end, _value in tc260_regions: + for key_span, value_start, value_end in blank_regions: if key_span is not None: + span_len = key_span[1] - key_span[0] temporary.seek(key_span[0]) - temporary.write(b"free") - _overwrite_range(temporary, value_start, value_end, byte=b" ") - for key_span, value_start, value_end, _name, _value in ai_metadata_regions: - temporary.seek(key_span[0]) - temporary.write(b"free" + b" " * (key_span[1] - key_span[0] - 4)) - _overwrite_range(temporary, value_start, value_end, byte=b" ") - for key_span, value_start, value_end in app_regions: - if key_span is not None: - temporary.seek(key_span[0]) - temporary.write(b"free" + b" " * (key_span[1] - key_span[0] - 4)) + temporary.write((b"free" + b" " * max(0, span_len - 4))[:span_len]) _overwrite_range(temporary, value_start, value_end, byte=b" ") # Spaces keep the SEI message well-formed: its length fields stand, # and a 0x20 run cannot form an emulation-prevention sequence. @@ -751,7 +892,10 @@ def strip_isobmff_media_file( ) return 0, 0 # Every copy of the Kling tag is one tag, however many samples repeat it. - return len(targets), len(tc260_key_spans | ai_metadata_key_spans | app_key_spans) + bool(kling_sei_offsets) + return ( + len(targets), + len(blanked_key_spans) + bool(kling_sei_offsets), + ) def _blank_box(data: bytes, start: int, end: int, payload_off: int) -> bytes: @@ -797,8 +941,9 @@ def strip_c2pa_boxes(data: bytes) -> tuple[bytes, int]: provenance = box_type == b"jumb" if box_type == b"uuid": # uuid boxes carry the 16-byte UUID immediately after the type. - is_c2pa = payload_off + 16 <= end and data[payload_off : payload_off + 16] == C2PA_UUID - provenance = is_c2pa or any(marker in data[payload_off:end] for marker in _AI_LABEL_MARKERS) + payload = data[payload_off:end] + is_c2pa = len(payload) >= 16 and payload[:16] == C2PA_UUID + provenance = is_c2pa or _has_ai_label_or_generator(payload) if provenance: stripped += 1 out.extend(_blank_box(data, start, end, payload_off)) @@ -840,7 +985,7 @@ def blank_ai_xmp_packets(data: bytes) -> tuple[bytes, int]: def _scrub(match: re.Match[bytes]) -> bytes: nonlocal blanked packet = match.group() - if any(marker in packet for marker in _AI_LABEL_MARKERS): + if _has_ai_label_or_generator(packet): blanked += 1 return b" " * len(packet) return packet diff --git a/src/remove_ai_watermarks/assets/kling_4_alpha.png b/src/remove_ai_watermarks/assets/kling_4_alpha.png new file mode 100644 index 0000000000000000000000000000000000000000..9c4f81e68b418697d709719f551fa4f1468d5aaa GIT binary patch literal 3122 zcmV-249)Y2P)+sNU6b_0B+T!Ru9>Q@tGj>m z^;chg_0Qc90>B#j>Z;Yq&o1-D&`1-Xqp?#?WwGXhh5Cw(VoO9hy(- zhP(PAohM?MG?N&OMUM#zCOb*IdZ8e=me7OiY+ zwB8P?p<;TQAm2j8if-^daLl)I&6$vf%dJ`WxgsQ!2v}+`w=J$wF>c$Jpy0)xuDZEZ zShuVpaBH_&YpScNDl5v%N=u6G-i1n=J_D~hd&p~MEVmy}L2mzva%qvu%4aH|vZ_aY zaq9(&r1PtF#VnbwtHm42?RYB4ZD%wc*&Wo?Q}FB^s>%j5qp<5rOi?`1d?RP;?LHKh zOvJ(er7U&zjxA73iq-ZLzDUc?D=aIkthCmEpFnw+Is1@woVg=7BrG&MGOFD*;%g)+ zK0h#euW=o3i53(Lcn*q#|8{Rk8sAFN)cA$Q+|XHg4Q3e8Rgu(FrJmGp@Wne=4aFhj zY=UFx*S87sEil}*1!ybOy4rZSJ%A6^e;c0$uet42F3jy35IW6h2}l27M8mYVdg${s z6o<~N@U#$hK~Rde&*2WFZY!gu_+L66UsZNg!~siRJS)qZ{Jg1 zny!{ySkcW7he zHqipb3QEYnOYkvXV3MqhmdQxLD-{C5sMX&x+iIZN{BR@WHuME3?xYYx=t}q;X~a0X zu@e-#KM)bdd2SlJ@q0LeV~Sw<44WRx_$f0dzo@jlvbx4bsmWvxvNUTE5p`eZ?hkGf zx(mY*hvBBR@ak?~2C0rCVZoCc0jyl|OgVa7-GB)uVaWJ>7lE3Doi#cpy-7fk1FeuVr z6B7>xM>yBYZY=;uA-X|w8^~#UY5)|wesol#78i5d=@zbvfNp54ei>q8n#ae%~Q~=TcmXOc?jhz7jPSbeM(?H57*TL%@=}I zcp?^|qqseBDtYXrs|x22f%8c1u>wQcsSZP<3k#neYzXFai}ari$ZMJ>g-Z#LX)Pp)1bJbirAv! zM$|fgsm*3AU-(7%6eLS??FmT_a1&<=u_3UkWjMD9_@1p)DcDZ*dFHvE#XD?igT*fK zQ{2gOLy((dn!V*u_yzJF=xchS`AbmbZd27-*Fe#ALM^T&t;&ps;zptu=T!5D1vJO5 z97}`Z9YsgZtFB}+#aN@8Q+blZcMQnGe2KvNNp0aEGal} zF8$7%v+iOH+UQ8A}6@n8XhRJOR6a6 zD0#pX=@t^GZ*IH)Raz}CF$X37L-Z8Axz~g)&e@tMo_H0Cl4;(J%=RM5I<+;iRimB7 zjobRR31x86h_EZ$L?a19AJyqHz?wo8X`U*32_ zna|l8i%*qO%|{V3C?#w4AeL=dfOm+iIPN%o1d4fHjT)UclG@^e`?8G^LwE~5ZV_~x zuq&`%y*ePU?l1*Ja3Kk?9+d)FE(w#pp z?tfbCadxXhoosgXBeDGiSE89Nw+levxS}RT-U3T$mP7r=P;C=NaFbk_ls2r1b*jV# zW4TRs-0t&^n&(k*ah~9j2$-Y2bmG8d9=8KUxowdJ0?LfIcUO2vTA}bs zkHBZEhaLbv!yZ(d2t2V1q%ti&;5N^}tt&=62P^idhV=31d}MGpm?0MOxScJ?tp&HV z;mirK9Jv|}x>^P=K=-vJnwr@aN4d{+?sf=1?H_%>?J)c;b zC5`hnPJ`QJ!uGby{3BL6$MwB8Zd6Dn@lgJ+FVsdP-7I#Fk1DLiJLbf35Z|a1GQ1ayt=yEt=b2X?7?r zUDSdfDGF}l zD)BaU9$jDDlHiwd@Ic&IthGMrYi>;=(Z)zm?{tod`9tTeRen606EJ9?Fg>zl_m$kz zyo~=Wd!n|fJ=(Y_!mVlW-<*>hTA)-WljDCTBoux!n-yZbR}ogD$E~?{Tna{T5$D_% z@h0PI=s@=8Z;tKU`2GvdDD)W{>ln6!Hu7AgcEjV>9drIk2f)6@BiSd$^AC$k(^B4< zCGw|0O%5R^Y0Zs8+t<9i+^LX^4Xi^i;BcbCdDiqQ;1#v%B1-N}^AO{)B7zfFR@hI8 z%ojE6eVg~?DWn4WLC~g&4Q@P?vp5Slp%%J6mosPSumbmZIdRGOVYhJr7d2eKo$c=E zsZek0o^d)!5MguVIU9nt8g*|#4zbC|(%2`nMQ*o!ozPCC*FH-xJGv|qo0m65U<_8q z?oPZ6hr(Sm*}+35ViWd)aY!aj1zzWfUd4hI{e1Pr7wQ}i19xg2+qdQ7SlS#tz`%@A3-JvRiq8^-sWoe?oN7Xc9Gj7{9DBKzwlb%w zY=kIH#hFqX5=#t4#0kL&TRu`TMINKb`*mks?%Cho=XK9M=bo$AHRtz-=iA@eXWz|t z_Wky^zrC*r85kHC7#J8B7~C{W`ZYD-TPHN?%8W>ycyEZWrTJp@;eDs=S6yqteYGf25^!a>R;mXZ|Fcrvqn=H|sju8pro zx12{kK#YpgtI@<~n5zbTvG+l`Jbu@KQJPHq*6)a1JNXB6>v^1#({*Zd=vL;cV@nf- zs<_fg8cdt@ysKF@BAO~J?ypOmrfqkyRvld!ELH}5`D@jtU9pD9SL0p5vgkK-A@E^c z+FUV>wWi-bKPk1>=f6;C+GTGL`Re2<_@R5hke*-GBT)p&cBEjD3T`>4w#h7fY&4`NNc6Utn5 zJxDDZqWuQn_r?uSyejj4q(Z@29VB+E9ZlE1sbMUiVcm2{X|Y&NIvm$N#&6JGTpJ6u zY9ef!@YA4L#5`&r+C^sHy7=#rYp}GRKrwopgDsAFm%Z+jSm>NxVH2toVcb5&YTEH% zc)Flv5idT_V@eO;w8Ryy5c$igJbobZC4Jx z`A}ckn}fVvjtTc*saRrhriGWsv)7%5-$Ex9IlX(86HIeJ=VqsodkRSSRzF42vZ0w+ z`mOB}b}v^xV*TKL(-Oyp4(e&CIaR#-qWEdIl^FrntNVZ<6EnVlz5t;s+rCQ zyl{w<{E~Md?M&u+UfJ@1a^*NId{sx39eH@Y8uyOWLjun~vWB?zx-p{K%ITTaxI6

I z85}|owV11)Qi&X5X5321hOHyLXsSW!lo`S#6BS z8z6q@?=mw}C?xZ;5vr(?j~W>H)tk0!)pDllVOaR7iB^-)TFJCN`BC~=7QF@iA^20@ z_{}5`Aq2@RY`}&sRwoL>HY`?K-#kCHz1Fq`txWY{kl>hr<1!Y8+BdD|zo@D5F!&Lz zgh(kFzy0lFg*nPm-aXYyvxgq{kSJ{(Kg)_=~H;Nn6r zE&ZCk%y#|wL&gUnr+baBuNPHd$=7cBC32LexJ7vv+i#qFZOl)gvn>n|ihyrO<;)sR zDoE;-X$ju*&xL&#@CXA*u+C2K2e#{voQ0Kv1&qLdw1_IOnASU&Io~G7!Xi$%%q=G< zfBytl^e!bcL&+=B4f%7^IYPO;eU}|Q4tNA}j(^{^eL*wpBM{2K=i2DTf`_UNoS2u8 zV-$P|;{G3mrp2Qd?JTDr*?3*DrNtgRe}GW!0j!9ZNl@Ei6}Pnd1N(FWrnS9UBr2*i zEy{$|oi=hP8P-j<0fT&Dp$Fe>D@}Xt`-6%K;ZvqGwcU!%vR!v~w& z$P4}z0Luy1kFe;hdN6NZ`g3kY4}KXgW-q5hD1C?s!-_z`sz zSvt2Pu;RFyr=a_ST&I^PRFE}oYhn@lGnKE{#J+bV-yPmt&h3 z89?uOYI?_K>kpG6znPcrY*qHQb!tb3FaKfA}|>sWfZ_SW{ieGsXnw-O%3*LCSD5qt^h{U z5`TE?b)-`SCI?vv@xSii_kc;tGie&*p;qmX{iOS8HSAknf*l;iu4GZkwt3F*Wmljt zyfZL9)L{t@hWIapPT4sJywizh)7m+r+sdZxOz+kw0+Xc_3)AWS)GX1-03Y6-&n=tC zzQMwHvJZp&l0~-}7P@7x5!uJ_9GDog&7Domne?ov-U4r=ObYv14UHUtMC~7m@;RK8 z>D>c52H*5@r7jVeEPEjA4K2hG%@aG^?D&KECIS5$@h#7Vh!tO9D<%^p=mz%{t*&Ya ziF$2I@-8r5`V=fhtinOK?I2)=XBaF_r7113d3eFMeMf)P_yK(zVZp_qul8 zM2|p@hy8=wBM9COUuNpWEX$1gpT8ofMqn?J^oW0ES$*s2t^AYgLYsXiUZ;__6AP!7 zoJHvoECrXX8RO+OdQ}DN;$EQ6lQ0D zKY=tbtD>dl2baR1Cv0M8sg}?>YF%`H6{pl%5AhgavrHSZC6^CQzNkMb&>g$Elc8` zrJR!6#p1GB+l20mJFE0BFZ3^lDW6h&*_74ubq-_(}NLD z=ax5gb~c{a{){tnE6yVcn^v4nxIJ)sep8tx*oM4~UzCCc2M?tGKl1=MEP8efYR0>Y zqF>+`u+kqJ(Q=do%%)vfNv3`S)qF%Ib38K-cn_<3CHBY+SPAa}+cvC!(7&I5)XKA< z;SRtWXyZAHEY;khI|GgUP0q6CMi@4A4D(C9l9v6N`G12kkYz@d*syg^-bRZ@7skB! z5P#%WtyFdH(DiVoaWO3MzR2N&eLC72FPtkacA5Wu!N9=4z`(%3zyP^E{{wZh0*J4f Rd6fVF002ovPDHLkV1lS(V{iZf literal 0 HcmV?d00001 diff --git a/src/remove_ai_watermarks/identify.py b/src/remove_ai_watermarks/identify.py index bf97cc9..c7690d3 100644 --- a/src/remove_ai_watermarks/identify.py +++ b/src/remove_ai_watermarks/identify.py @@ -836,6 +836,7 @@ def _attribute_platform(issuers: list[str], *, is_ai: bool = True) -> str | None # so order specific tokens before brand umbrellas where they overlap. _AI_VENDOR_TOKENS: tuple[tuple[str, str], ...] = ( ("gpt-image", "OpenAI"), + ("gpt image", "OpenAI"), ("dall", "OpenAI"), ("sora", "OpenAI"), ("openai", "OpenAI"), @@ -897,6 +898,9 @@ _AI_VENDOR_TOKENS: tuple[tuple[str, str], ...] = ( ("apple image playground", "Apple"), ("luma ai", "Luma AI"), ("lumalabs", "Luma AI"), + ("topaz", "Topaz Labs"), + ("photodirector", "CyberLink"), + ("cyberlink", "CyberLink"), ) @@ -914,6 +918,11 @@ _APPLE_CREDIT_PLATFORMS = ( ) +def _apple_credit_platform(source: bytes | str) -> str | None: + haystack = source if isinstance(source, bytes) else source.encode("utf-8", "ignore") + return next((name for credit, name in _APPLE_CREDIT_PLATFORMS if credit in haystack), None) + + def _vendor_of(text: str | None) -> str | None: """Normalize a platform/generator string to a coarse origin-vendor key, or None.""" if not text: @@ -1525,7 +1534,7 @@ def _identify_from_evidence( # shared IPTC value. Without such product-specific evidence the standard # names no platform and must not imply a vendor watermark. if platform is None: - platform = next((name for credit, name in _APPLE_CREDIT_PLATFORMS if credit in head), None) + platform = _apple_credit_platform(head) # ── IPTC 2025.1 AI-disclosure fields (Iptc4xmpExt:AISystemUsed etc.) ─ iptc_ai = any(m in head for m in IPTC_AI_FIELD_MARKERS) @@ -1583,7 +1592,7 @@ def _identify_from_evidence( signals.append(Signal("exif_generator", f"Embedded generator tag: {generator_tag}", "high")) watermarks.append(f"Embedded generator tag: {generator_tag}") if platform is None: - platform = f"{generator_tag} (embedded generator tag)" + platform = _apple_credit_platform(generator_tag) or f"{generator_tag} (embedded generator tag)" if v := _vendor_of(generator_tag): ai_vendor_claims["exif_generator"] = v diff --git a/src/remove_ai_watermarks/kling_engine.py b/src/remove_ai_watermarks/kling_engine.py index de81c70..cc88824 100644 --- a/src/remove_ai_watermarks/kling_engine.py +++ b/src/remove_ai_watermarks/kling_engine.py @@ -3,16 +3,17 @@ Kling AI stamps its generations with a thin, light-gray text strip in the bottom-right corner, preceded by the vendor's spiral logo (not part of the detection silhouette -- logos vary between releases, the text run is what -discriminates). Separate silhouettes cover the older "可灵AI 3.0" release and -the current IMAGE 3.0 "KlingAI 3.0" release. An "Omni" suffix and a version-less -"可灵AI" remain outside the calibrated pair. +discriminates). Separate silhouettes cover the CJK "可灵AI 3.0" / "可灵AI 4.0" +releases and the Latin "KlingAI 3.0" / "KlingAI 4.0" releases. An "Omni" suffix +and a version-less "可灵AI" remain outside the calibrated set. Detection matches the bundled glyph silhouette against the corner. Removal unions the pixel-derived footprint with the known silhouettes aligned to the winning match box, then sends the hybrid mask through the shared **localize -> fill** path in -``region_eraser``; it is not reverse-alpha. This module supplies two tuned -:class:`TextMarkConfig` instances (``assets/kling_alpha.png`` and -``assets/kling_latin_alpha.png`` -- font-rendered synthetic silhouettes from +``region_eraser``; it is not reverse-alpha. This module supplies tuned +:class:`TextMarkConfig` instances (``assets/kling_alpha.png``, +``assets/kling_4_alpha.png``, ``assets/kling_latin_alpha.png``, and +``assets/kling_latin_4_alpha.png`` -- font-rendered synthetic silhouettes from ``scripts/render_vendor_silhouettes.py``, never cut from an upload). The detector also feeds ``identify`` as the medium-confidence ``visible_kling`` signal via the registry. @@ -60,6 +61,7 @@ import numpy as np from remove_ai_watermarks import _text_mark_engine from remove_ai_watermarks._text_mark_engine import TextMarkConfig, TextMarkDetection, TextMarkEngine +from remove_ai_watermarks._text_mark_variants import TextMarkVariantsMixin if TYPE_CHECKING: from numpy.typing import NDArray @@ -134,6 +136,11 @@ _CONFIG = TextMarkConfig( # reaches 0.379, so the 0.40 gate stays above both measured negative arms. Keep # this a separate silhouette and gate: # replacing the CJK template would discard the older measured release. +_CJK_4_CONFIG = replace( + _CONFIG, + asset_name="kling_4_alpha.png", +) + _LATIN_CONFIG = replace( _CONFIG, asset_name="kling_latin_alpha.png", @@ -147,6 +154,11 @@ _LATIN_CONFIG = replace( detect_ncc_threshold=0.40, ) +_LATIN_4_CONFIG = replace( + _LATIN_CONFIG, + asset_name="kling_latin_4_alpha.png", +) + def _alpha_template() -> NDArray[Any] | None: """The bundled Kling AI alpha template (float [0,1]), or None.""" @@ -183,26 +195,15 @@ class _KlingTextEngine(TextMarkEngine): return max(0.0, min(score, detail_score)), box -class KlingEngine(_KlingTextEngine): - """Detect/localize Kling AI's CJK and Latin 3.0 marks (locate -> mask -> fill).""" +class KlingEngine(TextMarkVariantsMixin, _KlingTextEngine): + """Detect/localize Kling AI's CJK and Latin 3.0/4.0 marks (locate -> mask -> fill).""" def __init__(self) -> None: super().__init__(_CONFIG) - self._latin = _KlingTextEngine(_LATIN_CONFIG) - - def detect(self, image: NDArray[Any], *, provenance: bool = False) -> TextMarkDetection: - """Return the strongest CJK or Latin Kling wordmark verdict.""" - return _text_mark_engine.best_detection( - super().detect(image, provenance=provenance), - self._latin.detect(image, provenance=provenance), - ) - - def detect_both(self, image: NDArray[Any] | None) -> tuple[TextMarkDetection, TextMarkDetection]: - """Scan each immutable variant once and combine strict/relaxed verdicts.""" - cjk_strict, cjk_relaxed = super().detect_both(image) - latin_strict, latin_relaxed = self._latin.detect_both(image) - return _text_mark_engine.best_detection(cjk_strict, latin_strict), _text_mark_engine.best_detection( - cjk_relaxed, latin_relaxed + self._variants = ( + _KlingTextEngine(_CJK_4_CONFIG), + _KlingTextEngine(_LATIN_CONFIG), + _KlingTextEngine(_LATIN_4_CONFIG), ) def footprint_mask( @@ -222,12 +223,12 @@ class KlingEngine(_KlingTextEngine): shared geometry-box behavior. """ if force or image is None or image.size == 0: - return super().footprint_mask(image, force=force, dilate=dilate, detection=detection) + return TextMarkEngine.footprint_mask(self, image, force=force, dilate=dilate, detection=detection) det = detection if detection is not None else self.detect(image) if not det.detected: return None - engine = self._latin if det.template_asset == _LATIN_CONFIG.asset_name else self + engine = self.variant_engine(det) legacy = TextMarkEngine.footprint_mask(engine, image, force=False, dilate=dilate, detection=det) radius = _FOOTPRINT_DILATE if dilate is None else max(0, dilate) result = legacy diff --git a/src/remove_ai_watermarks/metadata.py b/src/remove_ai_watermarks/metadata.py index 432f946..0589a0c 100644 --- a/src/remove_ai_watermarks/metadata.py +++ b/src/remove_ai_watermarks/metadata.py @@ -17,7 +17,7 @@ from typing import TYPE_CHECKING, Any, cast from remove_ai_watermarks._internal.tc260_producers import uscc_of as uscc_of if TYPE_CHECKING: - from collections.abc import Callable, Iterable + from collections.abc import Callable, Iterable, Mapping from pathlib import Path from remove_ai_watermarks._internal.constants import ( @@ -65,6 +65,19 @@ AI_METADATA_KEYS: frozenset[str] = frozenset( LOCAL_GENERATION_METADATA_KEYS: frozenset[str] = frozenset( AI_METADATA_KEYS & {"parameters", "prompt", "negative_prompt", "workflow", "comfyui", "invokeai_metadata", "dream"} ) +TOPAZ_VIDEO_METADATA_KEYS: frozenset[str] = frozenset( + { + "topazcloud", + "topazcloud_provider", + "topazcloud_application", + "topazcloud_timestamp", + "videoai", + "videoai_provider", + "videoai_application", + "videoai_timestamp", + } +) +TOPAZ_AI_DESCRIPTION = b"AI-enhanced using Topaz Labs" AI_KEYWORDS: tuple[str, ...] = ( "stable_diffusion", @@ -146,6 +159,7 @@ _STREAMING_ISOBMFF_EXTS: frozenset[str] = frozenset({".mp4", ".mov", ".m4v", ".m _FFMPEG_STRIP_EXTS: frozenset[str] = frozenset( {".webm", ".mkv", ".mka", ".avi", ".flv", ".mp3", ".wav", ".flac", ".ogg", ".oga", ".opus", ".aac"} ) +_NON_IMAGE_MEDIA_EXTS: frozenset[str] = _STREAMING_ISOBMFF_EXTS | _FFMPEG_STRIP_EXTS # China's mandatory AI-content labeling (TC260, the national cybersecurity # standards committee). AI generators serving China embed an XMP block in the @@ -493,12 +507,14 @@ def has_ai_metadata(image_path: Path) -> bool: # PIL may not handle AVIF/HEIF/JPEG-XL without the optional plugins, and a # third-party plugin autoload can raise a non-OSError (e.g. ModuleNotFoundError), # so any open failure falls through to the binary scan. + exif_candidates: list[str] = [] try: with Image.open(image_path) as img: for key in img.info: if isinstance(key, str) and _is_ai_key(key): return True - exif_bytes = img.info.get("exif") + exif_bytes = exif_bytes_from_image(img) + exif_candidates = _exif_generator_candidates(img.info, exif_bytes) if exif_bytes and any(_app_metadata_evidence(exif_bytes)): return True except Exception as exc: @@ -533,6 +549,14 @@ def has_ai_metadata(image_path: Path) -> bool: # Higgsfield job marker (hf-job-id PNG text chunk). if huggingface_job(image_path): return True + from remove_ai_watermarks._internal.isobmff import ai_metadata_tags, is_isobmff + + if is_isobmff(data) and ai_metadata_tags(image_path): + return True + if image_path.suffix.lower() not in _NON_IMAGE_MEDIA_EXTS: + head_full = scan_head(image_path) + if generator_from_metadata(exif_candidates, head_full) is not None: + return True # xAI / Grok signature + UUID pair, including container-native transcodes. return xai_signature(image_path) @@ -898,18 +922,18 @@ def synthid_source(image_path: Path, *, c2pa_info: dict[str, Any] | None = None) return ", ".join(matched) if matched else None +_XMP_GENERATOR_RE = re.compile(rb"(?:CreatorTool|photoshop:Credit)[>\"'=\s]{1,4}([^<\"']{1,80})") + + def generator_from_metadata(candidates: Iterable[str], scan: bytes = b"") -> str | None: """Return a known AI generator from collected EXIF, PNG, or XMP values.""" from remove_ai_watermarks._internal.constants import AI_GENERATOR_TOKENS - if app_generator := app_generator_from_metadata(scan): + if scan and (app_generator := app_generator_from_metadata(scan)): return app_generator - creator_tools = ( - match.group(1).decode("latin1", "replace") - for match in re.finditer(rb"CreatorTool[>\"'=\s]{1,4}([^<\"']{1,80})", scan) - ) - for value in itertools.chain(candidates, creator_tools): + xmp_generators = (match.group(1).decode("latin1", "replace") for match in _XMP_GENERATOR_RE.finditer(scan)) + for value in itertools.chain(candidates, xmp_generators): if app_generator := app_generator_from_metadata(value): return app_generator if structured_generator := _structured_generator_from_metadata(value): @@ -973,10 +997,17 @@ _CAPCUT_AI_FLAG_RE = re.compile( ) +_APP_METADATA_BYTES_HINT_RE = re.compile(rb"product|aigc_info", re.IGNORECASE) + + def _normalized_app_metadata(value: object) -> str: if isinstance(value, bytes): + if not value or _APP_METADATA_BYTES_HINT_RE.search(value) is None: + return "" text = value.decode("latin-1", "ignore") elif isinstance(value, str): + if not value: + return "" text = value else: return "" @@ -1026,36 +1057,19 @@ def app_generator_from_metadata(value: str | bytes) -> str | None: return _app_metadata_evidence(value)[1] -def exif_generator(image_path: Path) -> str | None: - """Return an AI-generator name from the EXIF ``Software`` / XMP ``CreatorTool`` - field (or a PNG text chunk), if it matches a known generator (see - ``AI_GENERATOR_TOKENS``), else None. - - Cross-format: EXIF is read via PIL + piexif for any container PIL can open - (JPEG/WebP/AVIF/PNG); an XMP ``CreatorTool`` raw-byte scan additionally covers - HEIF/JPEG-XL that PIL can't open without plugins. PNG ``tEXt`` chunks are read - too -- NovelAI stamps its generator in ``Software``/``Source``/``Title`` text - chunks rather than EXIF. Only AI tokens match, so ordinary editors (plain - "Adobe Photoshop", "GIMP") are not flagged. - """ +def _exif_generator_candidates(info: Mapping[Any, Any], exif_bytes: bytes | None) -> list[str]: + """Collect candidate generator strings from decoded image info and raw EXIF bytes.""" candidates: list[str] = [] - - # EXIF Software / Artist / ImageDescription (0th IFD) via PIL exif bytes, - # plus PNG text chunks (NovelAI writes Software/Source/Title there, not EXIF). - try: + # PNG tEXt/iTXt chunks land in img.info too (same idiom as the other + # PNG-text readers in this module); NovelAI stamps Software/Source/Title. + for key in ("Software", "Source", "Title", "Description"): + value = info.get(key) + if isinstance(value, str) and value: + candidates.append(value) + if exif_bytes: import piexif - from PIL import Image - with Image.open(image_path) as img: - info = img.info - exif_bytes = exif_bytes_from_image(img) - # PNG tEXt/iTXt chunks land in img.info too (same idiom as the other - # PNG-text readers in this module); NovelAI stamps Software/Source/Title. - for key in ("Software", "Source", "Title", "Description"): - value = info.get(key) - if isinstance(value, str) and value: - candidates.append(value) - if exif_bytes: + with contextlib.suppress(Exception): loaded = piexif.load(exif_bytes) tags = loaded.get("0th", {}) exif_tags: dict[int, Any] = loaded.get("Exif") or {} @@ -1074,6 +1088,30 @@ def exif_generator(image_path: Path) -> str | None: user_comment = exif_tags.get(piexif.ExifIFD.UserComment) if isinstance(user_comment, bytes): candidates.append(user_comment.decode("latin1", "replace")) + return candidates + + +def exif_generator(image_path: Path) -> str | None: + """Return an AI-generator name from the EXIF ``Software`` / XMP ``CreatorTool`` + field (or a PNG text chunk), if it matches a known generator (see + ``AI_GENERATOR_TOKENS``), else None. + + Cross-format: EXIF is read via PIL + piexif for any container PIL can open + (JPEG/WebP/AVIF/PNG); an XMP ``CreatorTool`` raw-byte scan additionally covers + HEIF/JPEG-XL that PIL can't open without plugins. PNG ``tEXt`` chunks are read + too -- NovelAI stamps its generator in ``Software``/``Source``/``Title`` text + chunks rather than EXIF. Only AI tokens match, so ordinary editors (plain + "Adobe Photoshop", "GIMP") are not flagged. + """ + candidates: list[str] = [] + + # EXIF Software / Artist / ImageDescription (0th IFD) via PIL exif bytes, + # plus PNG text chunks (NovelAI writes Software/Source/Title there, not EXIF). + try: + from PIL import Image + + with Image.open(image_path) as img: + candidates = _exif_generator_candidates(img.info, exif_bytes_from_image(img)) except Exception as exc: # unopenable format / malformed EXIF logger.debug("EXIF generator read failed for %s: %s", image_path, exc) @@ -1197,6 +1235,10 @@ def xai_signature_in_metadata(data: bytes) -> bool: names inside one APP segment or RDF description; an unrelated XMP UUID must not complete the pair. """ + from remove_ai_watermarks._internal.isobmff import isobmff_xai_signature_in_region + + if isobmff_xai_signature_in_region(data): + return True payloads = _jpeg_app_payloads(data) if payloads: return any( @@ -1464,6 +1506,8 @@ def get_ai_metadata(image_path: Path) -> dict[str, str]: # Samsung Galaxy AI editing marker (genAIType in PhotoEditor_Re_Edit_Data). if (genai := samsung_genai(image_path)) is not None: result.setdefault("samsung_genai", f"Samsung Galaxy AI editing marker (genAIType={genai})") + if image_path.suffix.lower() not in _NON_IMAGE_MEDIA_EXTS and (generator := exif_generator(image_path)): + result.setdefault("exif_generator", generator[:200] + ("…" if len(generator) > 200 else "")) return result @@ -1530,6 +1574,7 @@ def _jpeg_app_carries_ai(marker: int, payload: bytes) -> bool: or any(m in payload for m in IPTC_AI_MARKERS) or any(m in payload for m in IPTC_AI_FIELD_MARKERS) or xai_signature_in_metadata(payload) + or generator_from_metadata((), payload) is not None ) ): return True diff --git a/src/remove_ai_watermarks/source_classify.py b/src/remove_ai_watermarks/source_classify.py index d98c15b..522f1ab 100644 --- a/src/remove_ai_watermarks/source_classify.py +++ b/src/remove_ai_watermarks/source_classify.py @@ -399,7 +399,8 @@ def _resolve_hub_weights( return downloaded -def _resolve_weights_path(weights_path: Path | None = None) -> Path: +def resolve_weights_path(weights_path: Path | None = None) -> Path: + """Resolve the verified local or Hugging Face Hub `.npz` weights artifact path.""" if weights_path is not None: path = Path(weights_path).expanduser() return path / MODEL_FILE if path.is_dir() else path @@ -417,6 +418,9 @@ def _resolve_weights_path(weights_path: Path | None = None) -> Path: return resolved +_resolve_weights_path = resolve_weights_path + + @functools.lru_cache(maxsize=1) def _spectral_grid_masks() -> tuple[ tuple[FloatArray, FloatArray, FloatArray, FloatArray], diff --git a/src/remove_ai_watermarks/video.py b/src/remove_ai_watermarks/video.py index c4ce90b..ca4cdd9 100644 --- a/src/remove_ai_watermarks/video.py +++ b/src/remove_ai_watermarks/video.py @@ -1,9 +1,9 @@ """High-level video processing API. The product path covers provenance identification, container-level AI metadata -removal, temporally stabilized visible Sora, Veo, Seedance, Dola, Hailuo AI, and -Kling AI removal, and explicit VAE profiles for video SynthID and experimental -Seedance processing. +removal, temporally stabilized visible Sora, Veo, Seedance, Doubao, Dola, +Hailuo AI, Vidu, and Kling AI removal, and explicit VAE profiles for video +SynthID and experimental Seedance processing. The visible pixel path reuses the image package's shared fill backends. """ @@ -28,6 +28,7 @@ if TYPE_CHECKING: VIDEO_EXTENSIONS: frozenset[str] = frozenset({".mp4", ".mov", ".m4v", ".webm", ".mkv", ".avi", ".flv"}) VIDEO_VISIBLE_MARKS = ("sora", "veo", "seedance", "doubao", "dola", "hailuo", "vidu", "kling") +_EXPECTED_VIDEO_MARKS = f"{', '.join(('auto', *VIDEO_VISIBLE_MARKS[:-1]))}, or {VIDEO_VISIBLE_MARKS[-1]}" _ISOBMFF_VIDEO_EXTENSIONS: frozenset[str] = frozenset({".mp4", ".mov", ".m4v"}) _EBML_VIDEO_EXTENSIONS: frozenset[str] = frozenset({".webm", ".mkv"}) _RIFF_VIDEO_EXTENSIONS: frozenset[str] = frozenset({".avi"}) @@ -381,7 +382,11 @@ def _platform_from_video_metadata(markers: dict[str, str]) -> str | None: """Map supported C2PA-derived marker text to its generating platform.""" from remove_ai_watermarks._internal.c2pa import c2pa_vendor_platform, claim_generator_platform from remove_ai_watermarks._internal.constants import C2PA_SIGNER_PLATFORM_BY_ORG - from remove_ai_watermarks.metadata import LOCAL_GENERATION_METADATA_KEYS + from remove_ai_watermarks.metadata import ( + LOCAL_GENERATION_METADATA_KEYS, + TOPAZ_AI_DESCRIPTION, + TOPAZ_VIDEO_METADATA_KEYS, + ) generator = markers.get("claim_generator", "") ai_tool = markers.get("ai_tool", "") @@ -412,6 +417,12 @@ def _platform_from_video_metadata(markers: dict[str, str]) -> str | None: return app_provenance.removeprefix("App export provenance (").removesuffix(")") if "kling_sei" in markers: return _tc260_video_platform("kling") + if "xai_signature" in markers: + return "xAI Grok Imagine" + if any(key.lower() in TOPAZ_VIDEO_METADATA_KEYS for key in markers) or ( + markers.get("description", "").strip() == TOPAZ_AI_DESCRIPTION.decode("ascii") + ): + return "Topaz Labs" if any(key.lower() in LOCAL_GENERATION_METADATA_KEYS for key in markers): return "Stable Diffusion / local pipeline (Automatic1111, ComfyUI, InvokeAI)" return None @@ -546,7 +557,7 @@ def remove_video_visible( the first stable match in specificity order, except a Veo diamond nested in a Sora cross-match or spanning the full clip against a partial Sora run, with valid Google AI-video provenance. Explicit marks are - ``sora``, ``veo``, ``seedance``, ``doubao``, ``dola``, ``hailuo``, and ``kling``. The full + ``sora``, ``veo``, ``seedance``, ``doubao``, ``dola``, ``hailuo``, ``vidu``, and ``kling``. The full sequence is scanned before pixels change, and only recurring candidates are accepted. Complete audio is copied without re-encoding; video is transcoded because the pixels change. ``temporal_consistency=True`` motion-aligns a @@ -562,7 +573,7 @@ def remove_video_visible( from remove_ai_watermarks.watermark_registry import resolve_backend if mark not in {"auto", *VIDEO_VISIBLE_MARKS}: - raise ValueError("Unsupported visible video mark; expected auto, sora, veo, seedance, dola, hailuo, or kling") + raise ValueError(f"Unsupported visible video mark; expected {_EXPECTED_VIDEO_MARKS}") if backend not in {"auto", "cv2", "migan", "lama"}: raise ValueError("Unsupported fill backend; expected auto, cv2, migan, or lama") @@ -798,7 +809,7 @@ def remove_video_batch( if mode not in {"all", "visible", "metadata"}: raise ValueError("Unsupported video batch mode; expected all, visible, or metadata") if mark not in {"auto", *VIDEO_VISIBLE_MARKS}: - raise ValueError("Unsupported visible video mark; expected auto, sora, veo, seedance, dola, hailuo, or kling") + raise ValueError(f"Unsupported visible video mark; expected {_EXPECTED_VIDEO_MARKS}") if backend not in {"auto", "cv2", "migan", "lama"}: raise ValueError("Unsupported fill backend; expected auto, cv2, migan, or lama") if include_invisible and mode != "all": diff --git a/src/remove_ai_watermarks/video_visible.py b/src/remove_ai_watermarks/video_visible.py index 6bcf368..0eb1067 100644 --- a/src/remove_ai_watermarks/video_visible.py +++ b/src/remove_ai_watermarks/video_visible.py @@ -731,23 +731,28 @@ def _white_fraction(roi: NDArray[Any]) -> float: """Share of bright, low-saturation pixels, the color of the white video labels. A light UI card or navigation bar with dark text has a high share of white - background pixels, and its narrow inter-letter gaps can correlate with a - morphological top-hat template. In that inverted polarity the dark excursion - below the patch median exceeds the bright excursion above it, whereas a white - label on a darker background has positive bright excursion above the median. + background pixels (``median >= 180``), and its narrow inter-letter gaps can + correlate with a morphological top-hat template. In that bright-background + inverted polarity the dark excursion below the patch median exceeds the + bright excursion above it, whereas a white label over a non-white scene + (including two-tone midtone-plus-shadow backgrounds where ``median < 180``) + keeps its white-stroke share. """ if roi.size == 0: return 0.0 if roi.ndim == 2: - value = roi.astype(np.float32) - white = roi >= 180 + value = roi + bright = value >= 180 + white = bright else: hsv = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV) - value = hsv[:, :, 2].astype(np.float32) - white = (hsv[:, :, 1] <= 55) & (hsv[:, :, 2] >= 180) - median = float(np.median(value)) - if float(np.mean(np.maximum(0.0, value - median))) < float(np.mean(np.maximum(0.0, median - value))): - return 0.0 + value = hsv[:, :, 2] + bright = value >= 180 + white = (hsv[:, :, 1] <= 55) & bright + if int(np.count_nonzero(bright)) * 2 >= value.size: + median = float(np.median(value)) + if median >= 180.0 and float(value.mean()) < median: + return 0.0 return float(np.mean(white)) diff --git a/src/remove_ai_watermarks/watermark_registry.py b/src/remove_ai_watermarks/watermark_registry.py index b2e6271..6b29be6 100644 --- a/src/remove_ai_watermarks/watermark_registry.py +++ b/src/remove_ai_watermarks/watermark_registry.py @@ -22,7 +22,8 @@ Entries: - ``doubao`` -- ByteDance Doubao "豆包AI生成" text strip, bottom-right. - ``jimeng`` -- ByteDance Jimeng / Dreamina "★ 即梦AI" wordmark, bottom-right. - ``qwen`` -- Alibaba Cloud Qwen "千问AI生成" text or three-lobe symbol, bottom-right. - - ``kling`` -- Kuaishou Kling AI "可灵AI 3.0" / "KlingAI 3.0" strip, bottom-right. + - ``wan`` -- Alibaba Wan logo and "Wan" wordmark, bottom-right. + - ``kling`` -- Kuaishou Kling AI "可灵AI 3.0/4.0" / "KlingAI 3.0/4.0" strip, bottom-right. - ``yuanbao`` -- Tencent Yuanbao "元宝 / AI生成" two-line mark, bottom-right. - ``dola`` -- ByteDance Dola "Dola AI" image disclosure, bottom-right. - ``workbuddy`` -- Tencent WorkBuddy "AI生成 / WORKBUDDY" disclosure, bottom-right. @@ -739,9 +740,9 @@ _REGISTRY: tuple[KnownMark, ...] = ( ), _text_mark( "kling", - "Kling AI 可灵AI / KlingAI 3.0 text", + "Kling AI 可灵AI / KlingAI 3.0/4.0 text", "bottom-right", - platform="Kuaishou Kling AI (visible 可灵AI / KlingAI 3.0 mark detected)", + platform="Kuaishou Kling AI (visible 可灵AI / KlingAI mark detected)", manufacturer="kuaishou", ), _text_mark( diff --git a/tests/test_identify.py b/tests/test_identify.py index f36b9fc..af902b4 100644 --- a/tests/test_identify.py +++ b/tests/test_identify.py @@ -2759,3 +2759,102 @@ class TestSignalDiscovery20261027Gaps: assert report.platform == "Xiaomi" assert not any("Google Gemini visible watermark" in watermark for watermark in report.watermarks) assert any("not reported as a Gemini mark" in caveat for caveat in report.caveats) + + def test_gpt_image_2_xmp_creatortool_maps_to_openai_vendor(self, tmp_path: Path): + from PIL import Image + from PIL.PngImagePlugin import PngInfo + + path = tmp_path / "gpt_image_2.png" + png_info = PngInfo() + png_info.add_itxt( + "XML:com.adobe.xmp", + "OpenAI GPT Image 2", + zip=True, + ) + Image.new("RGB", (48, 48)).save(path, pnginfo=png_info) + + report = identify(path, check_visible=False, check_invisible=False) + + assert report.is_ai_generated is True + assert report.platform == "OpenAI GPT Image 2 (embedded generator tag)" + assert _vendor_of("GPT Image 2") == "OpenAI" + + @pytest.mark.parametrize( + ("credit", "expected_platform"), + [ + ("Apple Photos Generative Edit: Clean Up", "Apple Photos (Clean Up AI edit)"), + ("Apple Image Playground", "Apple Image Playground"), + ], + ) + def test_standalone_apple_credit_without_digital_source_type_attributes_platform( + self, + tmp_path: Path, + credit: str, + expected_platform: str, + ): + from PIL import Image + + from remove_ai_watermarks.identify import identify_metadata_record + from remove_ai_watermarks.metadata_record import collect_metadata_record + + base_jpg = tmp_path / "base.jpg" + Image.new("RGB", (48, 48), (90, 100, 110)).save(base_jpg, format="JPEG") + raw_jpg = base_jpg.read_bytes() + xmp_payload = ( + b"http://ns.adobe.com/xap/1.0/\x00" + f''.encode() + ) + app1_seg = _jpeg_segment(0xE1, xmp_payload) + path = tmp_path / "apple_credit.jpg" + path.write_bytes(raw_jpg[:2] + app1_seg + raw_jpg[2:]) + + report = identify(path, check_visible=False, check_invisible=False) + record_report = identify_metadata_record(collect_metadata_record(path), path=path) + + assert report.is_ai_generated is True + assert report.platform == expected_platform + assert record_report.is_ai_generated is True + assert record_report.platform == expected_platform + + @pytest.mark.parametrize( + ("claim_generator", "issuer", "expected_platform"), + [ + ("Topaz Labs", "Topaz Labs", "Topaz Labs"), + ("PhotoDirector 365", "CyberLink Corp.", "CyberLink PhotoDirector"), + ], + ) + def test_topaz_and_photodirector_c2pa_attribute_only_when_ai_source_present( + self, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + claim_generator: str, + issuer: str, + expected_platform: str, + ): + from PIL import Image + + path = tmp_path / "edited.png" + Image.new("RGB", (48, 48)).save(path) + + ai_info = { + "c2pa_manifest": "present", + "claim_generator": claim_generator, + "issuer": issuer, + "ai_source": "compositeWithTrainedAlgorithmicMedia", + "ai_source_kind": "enhanced", + "c2pa_validation_source": "c2pa-python", + "c2pa_validation_state": "Valid", + "c2pa_integrity": "valid", + "c2pa_signature": "valid", + "c2pa_signer_trust": "trusted", + "c2pa_signer_validity": "valid", + } + monkeypatch.setattr("remove_ai_watermarks.identify.extract_c2pa_info", lambda _p: dict(ai_info)) + ai_report = identify(path, check_visible=False, check_invisible=False) + assert ai_report.is_ai_generated is True + assert ai_report.platform == expected_platform + assert ai_report.ai_source_kind == "enhanced" + + non_ai_info = {k: v for k, v in ai_info.items() if k not in {"ai_source", "ai_source_kind"}} + monkeypatch.setattr("remove_ai_watermarks.identify.extract_c2pa_info", lambda _p: dict(non_ai_info)) + non_ai_report = identify(path, check_visible=False, check_invisible=False) + assert non_ai_report.is_ai_generated is None diff --git a/tests/test_kling_engine.py b/tests/test_kling_engine.py index c94bbee..8fe5eba 100644 --- a/tests/test_kling_engine.py +++ b/tests/test_kling_engine.py @@ -28,16 +28,28 @@ _MARK_FRAC = 0.12 # measured mark width, fraction of the short side (unimodal) _MARGIN = 0.03 # measured right/bottom margin of the real mark -def _compose(w: int, h: int, mode: float = _MARK_FRAC, bg: float = 100.0): - """Composite the Kling silhouette at the measured size onto a flat bg.""" +def _compose( + w: int, + h: int, + mode: float = _MARK_FRAC, + bg: float = 100.0, + *, + asset_name: str | None = None, + margin_x: float = _MARGIN, + margin_y: float = _MARGIN, +): + """Composite a Kling silhouette at the measured size onto a flat bg.""" + from remove_ai_watermarks import _text_mark_engine + img = np.full((h, w, 3), bg, np.float32) - at = _alpha_template() + at = _alpha_template() if asset_name is None else _text_mark_engine.load_alpha_template(asset_name) + assert at is not None short = min(w, h) gw = int(mode * short) - gh = max(4, int(mode * (_ALPHA_HEIGHT_FRAC / _ALPHA_WIDTH_FRAC) * short)) - margin = int(_MARGIN * short) - ax = w - margin - gw - ay = h - margin - gh + aspect = (_ALPHA_HEIGHT_FRAC / _ALPHA_WIDTH_FRAC) if asset_name is None else (at.shape[0] / at.shape[1]) + gh = max(4, int(gw * aspect)) + ax = w - int(margin_x * short) - gw + ay = h - int(margin_y * short) - gh amap = np.zeros((h, w), np.float32) amap[ay : ay + gh, ax : ax + gw] = cv2.resize(at, (gw, gh)) a3 = amap[:, :, None] @@ -168,3 +180,30 @@ class TestFootprintMaskAndRemoval: def test_clean_frame_produces_no_mask(self): clean = cv2.GaussianBlur(np.full((640, 853, 3), 120, np.uint8), (5, 5), 0) assert KlingEngine().footprint_mask(clean, force=False) is None + + @pytest.mark.parametrize( + ("asset_name", "mode", "margin_x", "margin_y"), + [ + ("kling_4_alpha.png", _MARK_FRAC, _MARGIN, _MARGIN), + ("kling_latin_4_alpha.png", 0.14, 0.015, 0.015), + ], + ) + def test_kling_4_cjk_and_latin_marks_detect_and_remove( + self, + asset_name: str, + mode: float, + margin_x: float, + margin_y: float, + ): + wm, _ = _compose(1280, 720, mode=mode, bg=96.0, asset_name=asset_name, margin_x=margin_x, margin_y=margin_y) + + det = KlingEngine().detect(wm) + assert det.detected + assert det.template_asset == asset_name + + mark = registry.get_mark("kling") + before = mark.detect(wm) + assert before.detected + out, region = mark.remove(wm, backend="cv2", detection=before) + assert region is not None + assert not KlingEngine().detect(out).detected diff --git a/tests/test_metadata.py b/tests/test_metadata.py index e3850cd..73bf987 100644 --- a/tests/test_metadata.py +++ b/tests/test_metadata.py @@ -2690,3 +2690,62 @@ class TestIsobmffStripKeepsOffsets: assert len(cleaned) == len(data) assert cleaned.index(b"mdat") == data.index(b"mdat") assert cleaned == ftyp + _blanked(c2pa_box) + mdat + + +class TestXmpGeneratorAndAppleCreditParity: + """Detection and lossless removal stay in parity for XMP CreatorTool and Apple AI Credit.""" + + def test_gpt_image_2_xmp_creatortool_png_and_jpeg_parity(self, tmp_path: Path): + xmp = ( + b'' + b"" + b"OpenAI GPT Image 2" + b"" + b'' + ) + png_info = PngInfo() + png_info.add_itxt("XML:com.adobe.xmp", xmp.decode("utf-8"), zip=True) + png_src = tmp_path / "gpt_image_2.png" + Image.new("RGB", (48, 48), (60, 70, 80)).save(png_src, pnginfo=png_info) + assert exif_generator(png_src) == "OpenAI GPT Image 2" + assert has_ai_metadata(png_src) is True + assert get_ai_metadata(png_src).get("exif_generator") == "OpenAI GPT Image 2" + png_out = remove_ai_metadata(png_src, tmp_path / "gpt_clean.png") + assert exif_generator(png_out) is None + assert has_ai_metadata(png_out) is False + + jpg_src = TestXaiSignature._jpeg_app_pair( + tmp_path, + b"\xff\xe1", + b"http://ns.adobe.com/xap/1.0/\x00" + xmp, + "gpt_image_2.jpg", + ) + assert exif_generator(jpg_src) == "OpenAI GPT Image 2" + assert has_ai_metadata(jpg_src) is True + jpg_out = remove_ai_metadata(jpg_src, tmp_path / "gpt_clean.jpg") + assert exif_generator(jpg_out) is None + assert has_ai_metadata(jpg_out) is False + + def test_standalone_apple_credit_without_digital_source_type_parity(self, tmp_path: Path): + ai_xmp = ( + b"http://ns.adobe.com/xap/1.0/\x00" + b'' + b"" + ) + ai_src = TestXaiSignature._jpeg_app_pair(tmp_path, b"\xff\xe1", ai_xmp, "apple_credit_only.jpg") + assert exif_generator(ai_src) == "Apple Photos Generative Edit: Clean Up" + assert has_ai_metadata(ai_src) is True + ai_out = remove_ai_metadata(ai_src, tmp_path / "apple_clean.jpg") + assert exif_generator(ai_out) is None + assert has_ai_metadata(ai_out) is False + + human_xmp = ( + b"http://ns.adobe.com/xap/1.0/\x00" + b'' + b"" + ) + human_src = TestXaiSignature._jpeg_app_pair(tmp_path, b"\xff\xe1", human_xmp, "human_credit.jpg") + assert exif_generator(human_src) is None + assert has_ai_metadata(human_src) is False + human_out = remove_ai_metadata(human_src, tmp_path / "human_clean.jpg") + assert b'photoshop:Credit="Jane Doe"' in human_out.read_bytes() diff --git a/tests/test_publish_source_classify_hf.py b/tests/test_publish_source_classify_hf.py index 1e69bb4..1047333 100644 --- a/tests/test_publish_source_classify_hf.py +++ b/tests/test_publish_source_classify_hf.py @@ -100,3 +100,82 @@ def test_publish_uploads_allowlist_and_deletes_retired_hub_repos( assert len(uploads) == 1 assert uploads[0]["allow_patterns"] == list(publish.PUBLIC_FILES) assert ("wiltodelta/raiw-photo-classify", "model", True) in deleted + + +def test_stage_release_includes_standalone_infer_script_and_colab_notebook() -> None: + assert "infer.py" in publish.TRACKED_CARD_FILES + assert "demo.ipynb" in publish.TRACKED_CARD_FILES + assert (publish.CARD_DIR / "infer.py").is_file() + assert (publish.CARD_DIR / "demo.ipynb").is_file() + + +def _load_module(name: str, path: Path) -> object: + import importlib.util + + spec = importlib.util.spec_from_file_location(name, path) + assert spec is not None + assert spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def test_standalone_infer_script_inspects_weights_and_classifies_images(tmp_path: Path) -> None: + from typing import Any + + import numpy as np + from PIL import Image + + sc_mod: Any = _load_module("raiw_test_source_classify", Path(__file__).with_name("test_source_classify.py")) + infer_mod: Any = _load_module("raiw_hf_infer", publish.CARD_DIR / "infer.py") + + weights = sc_mod._write_synthetic_v5_npz( + tmp_path / "synthetic_v5.npz", + det_winner="openai", + attr_winner="openai", + det_score=-2.0, + det_threshold=2.0, + ) + summary = infer_mod.inspect_weights(weights) + assert summary["schema"] == "multi-provider-source-v5" + assert summary["feature_dim"] == 512 + assert len(summary["providers"]) == 10 + assert summary["abstain_label"] == "unknown" + assert summary["watermark_truth"] == "unknown" + assert "openai" in summary["version_subfamilies"] + + sample_img = tmp_path / "gradient.png" + y, x = np.ogrid[:320, :320] + arr = np.stack( + ( + (x * 3 + y * 5) % 256, + np.broadcast_to((x * 7) % 256, (320, 320)), + np.broadcast_to((y * 11) % 256, (320, 320)), + ), + axis=-1, + ).astype(np.uint8) + Image.fromarray(arr, mode="RGB").save(sample_img) + + exit_inspect = infer_mod.main(["--inspect-weights", "--weights", str(weights), "--json"]) + assert exit_inspect == 0 + + rows = infer_mod.classify_targets([sample_img], weights_path=weights) + assert len(rows) == 1 + assert rows[0]["label"] == "unknown" + assert rows[0]["reason"] == "abstained" + assert rows[0]["watermark_truth"] == "unknown" + + +def test_demo_notebook_is_valid_nbformat_and_compiles_cleanly() -> None: + nb_path = publish.CARD_DIR / "demo.ipynb" + nb = json.loads(nb_path.read_text(encoding="utf-8")) + assert nb["nbformat"] == 4 + assert isinstance(nb["cells"], list) + assert len(nb["cells"]) >= 4 + + code_cells = [c for c in nb["cells"] if c.get("cell_type") == "code"] + assert len(code_cells) >= 3 + for idx, cell in enumerate(code_cells): + assert cell.get("outputs") == [] + source_lines = [line for line in cell["source"] if not line.lstrip().startswith(("%", "!"))] + compile("".join(source_lines), f"demo.ipynb#cell-{idx}", "exec") diff --git a/tests/test_signal_discovery_scripts.py b/tests/test_signal_discovery_scripts.py index 1511808..36e08a6 100644 --- a/tests/test_signal_discovery_scripts.py +++ b/tests/test_signal_discovery_scripts.py @@ -31,12 +31,32 @@ def test_gap_markers_are_case_insensitive(): assert "ComfyUI" in gap._marker_hits(b"COMFYUI WORKFLOW") +def test_gap_markers_cover_current_provenance_and_generator_inventory(): + from remove_ai_watermarks.metadata import KLING_SEI_TAG + + assert "c2pa.ai-disclosure" in gap._marker_hits(b"assertion c2pa.ai-disclosure payload") + assert "Kling SEI tag" in gap._marker_hits(b"\x00\x00\x01\x06" + KLING_SEI_TAG) + for token in ( + b"Grok Imagine", + b"Amazon Bedrock", + b"Higgsfield AI", + b"recraft.ai", + b"Luma AI", + b"NovelAI", + b"InvokeAI", + b"Apple Image Playground", + b"Byteplus", + ): + assert gap._marker_hits(token), f"expected gap._marker_hits to detect {token!r}" + + def test_gap_markers_require_structural_provenance_evidence(): - noise = b"c2pa digitalSourceType Samsung Galaxy Doubao PhotoEditor_Re_Edit Signature: " + b"A" * 80 + noise = b"c2pa digitalSourceType Samsung Galaxy Doubao Dreamina PhotoEditor_Re_Edit Signature: " + b"A" * 80 assert gap._marker_hits(noise) == [] tc260 = b'{"AIGC":{"label":"1","contentProducer":"synthetic"}}' assert "TC260 AIGC" in gap._marker_hits(tc260) + assert "App AIGC disclosure" in gap._marker_hits(b'{"product":"dreamina","exportType":"generation"}') assert "Samsung genAIType" in gap._marker_hits(b'PhotoEditor_Re_Edit_Data{"genAIType":1}') @@ -246,3 +266,26 @@ def test_legacy_watermark_strings_align_with_current_signal_names(): watermarks=sidecar["watermarks"], ) assert regression.sidecar_families(sidecar) == regression.report_families(report) + + +def test_corpus_gap_scan_routes_video_through_identify_video_and_ignores_empty_dreamina_slot( + tmp_path: Path, +) -> None: + from remove_ai_watermarks.metadata import KLING_SEI_TAG + + ftyp = b"\x00\x00\x00\x18ftypmp42\x00\x00\x00\x00mp42isom" + sei_mdat = (8 + len(KLING_SEI_TAG)).to_bytes(4, "big") + b"mdat" + KLING_SEI_TAG + kling_mp4 = tmp_path / "kling.mp4" + kling_mp4.write_bytes(ftyp + sei_mdat) + + row = gap._scan_one((str(kling_mp4), "kling.mp4", "test")) + assert row["is_ai"] == "True" + assert row["platform"] == "Kuaishou Kling AI" + assert row["candidate_classes"] == "" + + # Non-AI CapCut mobile exports carry an empty ``DreaminaMetaInfo`` key slot + # ``{"data":{}}`` without ``aigc_info``; only structural app AIGC disclosures fire. + empty_slot = b'mdtaDreaminaMetaInfo\x00\x00\x00\x14data\x00\x00\x00\x01\x00\x00\x00\x00{"data":{}}' + assert gap._marker_hits(empty_slot) == [] + dreamina_gen = b'{"product":"dreamina","exportType":"generation"}' + assert "App AIGC disclosure" in gap._marker_hits(dreamina_gen) diff --git a/tests/test_video.py b/tests/test_video.py index ec9f302..fd419b9 100644 --- a/tests/test_video.py +++ b/tests/test_video.py @@ -3720,3 +3720,133 @@ class TestSignalDiscovery20261027VideoGaps: assert _white_fraction(frame[1840:1867, 785:931]) == 0.0 assert detect_hailuo_frame(frame, frame_index=0).region is None assert detect_kling_frame(frame, frame_index=0).region is None + + def test_unsupported_video_mark_error_lists_every_registered_mark(self, tmp_path): + from remove_ai_watermarks.video import VIDEO_VISIBLE_MARKS, remove_video_batch, remove_video_visible + + clip = tmp_path / "clip.mp4" + clip.write_bytes(b"") + batch_dir = tmp_path / "videos" + batch_dir.mkdir() + + with pytest.raises(ValueError, match="Unsupported visible video mark") as single_exc: + remove_video_visible(clip, mark="unsupported-mark") + with pytest.raises(ValueError, match="Unsupported visible video mark") as batch_exc: + remove_video_batch(batch_dir, mark="unsupported-mark") + + for expected in ("auto", *VIDEO_VISIBLE_MARKS): + assert expected in str(single_exc.value) + assert expected in str(batch_exc.value) + + def test_white_kling_4_mark_over_two_tone_non_white_background_is_detected(self): + from remove_ai_watermarks.video_visible import _kling_logo_template, _white_fraction, detect_kling_frame + + # Real KlingAI 4.0 exports place semi-transparent white text over split + # backgrounds (e.g. skin/midtone V~165 beside dark hair/shadow V~20), + # where patch median < 180 and dark excursion below median exceeds the + # thin white strokes' excursion above median. + frame = np.full((720, 1280, 3), 165, dtype=np.uint8) + frame[665:715, 1110:1185] = 20 + ring = cv2.resize(_kling_logo_template(), (24, 24), interpolation=cv2.INTER_AREA) + ring_alpha = (ring[:, :, None].astype(np.float32) / 255.0) * 0.72 + roi_logo = frame[678:702, 1126:1150].astype(np.float32) + frame[678:702, 1126:1150] = np.clip(roi_logo * (1.0 - ring_alpha) + 255.0 * ring_alpha, 0, 255).astype(np.uint8) + overlay = np.zeros_like(frame) + cv2.putText( + overlay, "KlingAI 4.0", (1154, 697), cv2.FONT_HERSHEY_SIMPLEX, 0.56, (255, 255, 255), 2, cv2.LINE_AA + ) + alpha = (overlay.astype(np.float32) / 255.0) * 0.72 + frame = np.clip(frame.astype(np.float32) * (1.0 - alpha) + 255.0 * alpha, 0, 255).astype(np.uint8) + + assert _white_fraction(frame[672:706, 1120:1268]) > 0.035 + detection = detect_kling_frame(frame, frame_index=0) + assert detection.region is not None + assert detection.confidence >= 0.24 + + def test_inspects_and_removes_xai_grok_imagine_isobmff_comment_signature(self, tmp_path: Path): + from remove_ai_watermarks.metadata import has_ai_metadata + from remove_ai_watermarks.video import identify_video, inspect_video_metadata, remove_video_metadata + + sig_value = b"Signature: " + (b"QUJD" * 30) # 120 valid base64 chars + cmt_item = _box(b"\xa9cmt", _box(b"data", b"\x00\x00\x00\x01\x00\x00\x00\x00" + sig_value)) + title_item = _box(b"\xa9nam", _box(b"data", b"\x00\x00\x00\x01\x00\x00\x00\x00standard title")) + meta = _box(b"meta", b"\x00\x00\x00\x00" + _hdlr(b"mdir") + _box(b"ilst", cmt_item + title_item)) + big_mdat = _box(b"mdat", b"x" * (4 * 1024 * 1024 + 128)) + source = tmp_path / "grok_imagine.mp4" + source.write_bytes(_MP4_FTYP + big_mdat + _box(b"moov", _box(b"udta", meta))) + + assert has_ai_metadata(source) is True + inspected = inspect_video_metadata(source) + assert inspected.has_ai_metadata is True + assert "xai_signature" in inspected.markers + + identified = identify_video(source, check_visible=False) + assert identified.is_ai_generated is True + assert identified.platform == "xAI Grok Imagine" + + result = remove_video_metadata(source, tmp_path / "clean.mp4") + cleaned = result.output.read_bytes() + assert result.remaining == {} + assert has_ai_metadata(result.output) is False + assert len(cleaned) == source.stat().st_size + assert sig_value not in cleaned + assert b"standard title" in cleaned + + # Ordinary human comment in \xa9cmt is untouched and not flagged. + plain_cmt = _box(b"\xa9cmt", _box(b"data", b"\x00\x00\x00\x01\x00\x00\x00\x00Shot in Kyoto")) + plain_meta = _box(b"meta", b"\x00\x00\x00\x00" + _hdlr(b"mdir") + _box(b"ilst", plain_cmt)) + plain = tmp_path / "plain.mp4" + plain.write_bytes(_MP4_FTYP + _box(b"mdat", _VIDEO_PAYLOAD) + _box(b"moov", _box(b"udta", plain_meta))) + assert has_ai_metadata(plain) is False + assert inspect_video_metadata(plain).has_ai_metadata is False + + @pytest.mark.parametrize( + ("extra_keys", "extra_vals"), + [ + ( + (b"topazcloud_provider", b"description", b"topazcloud", b"topazcloud_application"), + (b"Topaz Labs", b"AI-enhanced using Topaz Labs", b"slp-2.6", b"Topaz Cloud"), + ), + ( + (b"videoai_provider", b"description", b"videoai", b"videoai_application"), + (b"Topaz Labs", b"Vacation clip", b"Enhanced using ganim-1", b"Topaz Video 1.7.1"), + ), + ], + ) + def test_inspects_and_removes_topaz_isobmff_video_metadata( + self, + tmp_path: Path, + extra_keys: tuple[bytes, ...], + extra_vals: tuple[bytes, ...], + ): + from remove_ai_watermarks.metadata import has_ai_metadata + from remove_ai_watermarks.video import identify_video, inspect_video_metadata, remove_video_metadata + + keys = _box( + b"keys", + b"\x00\x00\x00\x00" + len(extra_keys).to_bytes(4, "big") + b"".join(_metadata_key(k) for k in extra_keys), + ) + ilst = _box( + b"ilst", + b"".join(_metadata_value(idx, val) for idx, val in enumerate(extra_vals, start=1)), + ) + meta = _box(b"meta", b"\x00\x00\x00\x00" + _hdlr(b"mdta") + keys + ilst) + source = tmp_path / "topaz.mp4" + source.write_bytes(_MP4_FTYP + _box(b"mdat", _VIDEO_PAYLOAD) + _box(b"moov", _box(b"udta", meta))) + + assert has_ai_metadata(source) is True + inspected = inspect_video_metadata(source) + assert inspected.has_ai_metadata is True + + identified = identify_video(source, check_visible=False) + assert identified.is_ai_generated is True + assert identified.platform == "Topaz Labs" + + result = remove_video_metadata(source, tmp_path / "clean.mp4") + cleaned = result.output.read_bytes() + assert result.remaining == {} + assert has_ai_metadata(result.output) is False + assert len(cleaned) == source.stat().st_size + assert b"Topaz Labs" not in cleaned + if b"Vacation clip" in extra_vals: + assert b"Vacation clip" in cleaned diff --git a/uv.lock b/uv.lock index c9c3f48..aad773a 100644 --- a/uv.lock +++ b/uv.lock @@ -3514,7 +3514,7 @@ wheels = [ [[package]] name = "remove-ai-watermarks" -version = "0.62.0" +version = "0.62.1" source = { editable = "." } dependencies = [ { name = "c2pa-python" },