Files
remove-ai-watermarks/tests/test_review_scripts_0811.py
Victor KuznetsovandClaude Opus 5.5 c295b9966a Fix review findings and leave invisible layers alone for unknown models
Fix the P0 findings of the 0.81.0 review across metadata, audio, video, text, visible marks, and scripts, with regression tests.

When no metadata, visible mark, or caller names the model, remove only metadata and visible marks. Infer Google audio only from Google evidence or an explicit SynthID profile. Keep ordinary tags and chapters when stripping AI metadata from ffmpeg-handled containers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 18:52:34 -08:00

246 lines
10 KiB
Python

"""Regression tests for the development scripts fixed in the 0.81 review."""
from __future__ import annotations
import json
import subprocess
import sys
from pathlib import Path
from types import SimpleNamespace
from typing import TYPE_CHECKING, Any
import numpy as np
import pytest
from PIL import Image
if TYPE_CHECKING:
import argparse
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))
from scripts import benchmark_text_local_repair as local_repair # noqa: E402
from scripts import benchmark_text_pairs as paired # noqa: E402
from scripts import benchmark_text_schemes as schemes # noqa: E402
def test_scheme_worker_gets_resolved_paths_not_raw_argv(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""Workers start in the reference checkout, where a relative path names another file."""
root = tmp_path / "markllm"
root.mkdir()
(tmp_path / "frozen").mkdir()
commands: list[list[str]] = []
monkeypatch.chdir(tmp_path)
monkeypatch.setattr(
sys,
"argv",
[
"x",
*("--markllm-root", "markllm", "--output-dir", "out", "--input-dir", "frozen"),
*("--schemes", "KGW", "--languages", "en", "--model", "m", "--timeout", "7"),
],
)
monkeypatch.setattr(
schemes.importlib,
"import_module",
lambda _name: SimpleNamespace(WATERMARK_MAPPING_NAMES={"KGW": "x"}),
)
monkeypatch.setattr(schemes.subprocess, "check_output", lambda *_a, **_k: "rev")
def run(command: list[str], **_kwargs: object) -> subprocess.CompletedProcess[str]:
commands.append(command)
return subprocess.CompletedProcess(command, 0)
monkeypatch.setattr(schemes.subprocess, "run", run)
schemes.main()
(command,) = commands
for flag, name in (("--markllm-root", "markllm"), ("--output-dir", "out"), ("--input-dir", "frozen")):
assert command[command.index(flag) + 1] == str((tmp_path / name).resolve())
# The worker parses its own command line back to the same options.
seen: list[argparse.Namespace] = []
monkeypatch.setattr(schemes, "worker", seen.append)
monkeypatch.setattr(sys, "argv", command[1:])
schemes.main()
assert seen[0].worker == "KGW"
assert seen[0].languages == ["en"]
assert (seen[0].model, seen[0].timeout) == ("m", 7)
def test_frozen_replay_refuses_a_missing_report_or_case(tmp_path: Path) -> None:
with pytest.raises(ValueError, match="no report for KGW"):
schemes.frozen_case(tmp_path, "KGW", "en")
(tmp_path / "KGW.json").write_text(json.dumps({"cases": [{"language": "en"}]}), encoding="utf-8")
assert schemes.frozen_case(tmp_path, "KGW", "en")[1] == {"language": "en"}
with pytest.raises(ValueError, match="no ru case"):
schemes.frozen_case(tmp_path, "KGW", "ru")
@pytest.mark.parametrize("symmetric", [True, False])
def test_local_repair_keeps_the_comparison_protocol(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, symmetric: bool
) -> None:
outputs: dict[str, Any] = dict.fromkeys(local_repair.ARMS)
manifest: dict[str, Any] = {
"arms": list(local_repair.ARMS),
"detectors": {"d": 10},
"pairs": [
{
"id": "p",
"detector": "d",
"marked": {"source": "The marked source.", "outputs": outputs},
"clean": {"source": "The clean source.", "outputs": outputs},
}
],
}
if symmetric:
manifest["comparison_protocol"] = paired.SYMMETRIC_PROTOCOL
path = tmp_path / "in.json"
path.write_text(json.dumps(manifest), encoding="utf-8")
monkeypatch.setattr(local_repair, "_client", lambda *_a: None)
monkeypatch.setattr(local_repair, "_rewrite", lambda source, *_a: ({"source": source, "outputs": outputs}, {}))
local_repair.generate(path, tmp_path / "out", url="http://127.0.0.1/v1", model="m")
trials = paired._manifest(tmp_path / "out" / "trials.json")[2]
assert {trial.symmetric for trial in trials} == {symmetric}
def _study(monkeypatch: pytest.MonkeyPatch) -> tuple[Any, list[np.ndarray], list[np.ndarray]]:
import importlib.metadata
import watermark_forgery_study as study
measured: list[np.ndarray] = []
embedded: list[np.ndarray] = []
def embed(_generator: object, samples: np.ndarray, message: list[int]) -> np.ndarray:
embedded.append(samples)
return samples * 1.5 + 0.001 * sum(message) # beyond full scale, so encoding has to clip
def read(_detector: object, samples: np.ndarray) -> SimpleNamespace:
measured.append(samples)
return SimpleNamespace(frac_above_threshold=0.5, decoded_bits=[0] * 16)
monkeypatch.setattr(importlib.metadata, "version", lambda _name: "0")
monkeypatch.setattr(study.audioseal_oracle, "load_pinned_models", lambda: (object(), object()))
monkeypatch.setattr(study.audioseal_oracle, "embed", embed)
monkeypatch.setattr(study.audioseal_oracle, "read", read)
return study, measured, embedded
def test_forgery_audio_measures_the_decoded_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
study, measured, embedded = _study(monkeypatch)
rows = study.audio_cells(tmp_path)
cells = [row for row in rows if row["cell"] != "pins"]
saved = {study.sha256_file(path): path for path in (tmp_path / "audioseal").glob("*.wav")}
assert len(cells) == len(measured) == len(saved) == 6
for row, samples in zip(cells, measured, strict=True):
decoded, digest = study.decode_wav_artifact(saved[row["sha256"]])
assert digest == row["sha256"]
assert np.array_equal(samples, decoded)
# Later stages start from decoded samples too.
assert all(any(samples is value for value in measured) for samples in embedded)
def test_forgery_audio_refuses_a_file_changed_during_the_read(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
study, _measured, _embedded = _study(monkeypatch)
from audioseal_experiment import SAMPLE_RATE, wav_pcm16_bytes
path = tmp_path / "a.wav"
path.write_bytes(wav_pcm16_bytes(np.zeros(8, dtype=np.float32), SAMPLE_RATE))
digests = iter(["before", "after"])
monkeypatch.setattr(study, "sha256_file", lambda _path: next(digests))
with pytest.raises(ValueError, match="changed during measurement"):
study.decode_wav_artifact(path)
def test_visible_ground_truth_uses_the_production_context(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
import visible_eval
import visible_groundtruth
from remove_ai_watermarks import api
image = tmp_path / "a.png"
Image.new("RGB", (8, 8)).save(image)
monkeypatch.setattr(api, "_visible_context", lambda _path: (frozenset({"qwen"}), frozenset({"gemini"})))
record = {"schema": visible_groundtruth.GROUNDTRUTH_SCHEMA, **visible_groundtruth.metadata_context(str(image))}
context = visible_eval.context_for(record, "auto")
assert context.provenance == frozenset({"qwen"})
assert context.vetoed_marks == frozenset({"gemini"})
with pytest.raises(FileNotFoundError):
visible_groundtruth.metadata_context(str(tmp_path / "gone.png"))
with pytest.raises(ValueError, match="schema"):
visible_eval.context_for({"provenance": []}, "auto")
def test_visible_ground_truth_build_records_schema_and_vetoes(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
import visible_groundtruth
from remove_ai_watermarks import api
image = tmp_path / "a.png"
Image.new("RGB", (8, 8)).save(image)
for _round, labels, manifest in visible_groundtruth.ROUNDS:
(tmp_path / labels).write_text("idx,seen\n1,doubao\n", encoding="utf-8")
(tmp_path / manifest).write_text(f"idx,uid,path,key\n1,u,{image},doubao\n", encoding="utf-8")
monkeypatch.setattr(api, "_visible_context", lambda _path: (frozenset(), frozenset({"gemini"})))
monkeypatch.setattr(sys, "argv", ["x", str(tmp_path)])
visible_groundtruth.main()
(row,) = [json.loads(line) for line in (tmp_path / "groundtruth.jsonl").read_text().splitlines()]
assert (row["schema"], row["provenance"], row["vetoed_marks"]) == (2, [], ["gemini"])
def test_visible_eval_scores_with_the_recorded_vetoes(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
import visible_eval
row = {"schema": 2, "path": "x", "provenance": ["qwen"], "vetoed_marks": ["gemini"], "adjudicated": []}
ground_truth = tmp_path / "gt.jsonl"
ground_truth.write_text(json.dumps(row) + "\n", encoding="utf-8")
seen: list[Any] = []
monkeypatch.setattr(visible_eval, "GT", ground_truth)
monkeypatch.setattr(visible_eval, "imread", lambda _path: np.zeros((4, 4, 3), np.uint8))
monkeypatch.setattr(visible_eval.wr, "_build_candidates", lambda _img: [])
monkeypatch.setattr(visible_eval.wr, "decide", lambda _candidates, context: seen.append(context) or [])
visible_eval.score()
assert seen[0].vetoed_marks == frozenset({"gemini"})
def test_retired_openai_uploader_refuses_before_any_read(tmp_path: Path) -> None:
result = subprocess.run( # noqa: S603
[sys.executable, str(ROOT / "scripts" / "openai_provenance_check.py"), str(tmp_path / "missing.png")],
capture_output=True,
text=True,
check=False,
)
assert result.returncode == 1
assert "provider_oracles.py check-openai" in result.stderr
assert result.stdout == ""
source = (ROOT / "scripts" / "openai_provenance_check.py").read_text(encoding="utf-8")
assert "urllib" not in source
assert "provider_oracles.py check-openai" in (ROOT / ".env.example").read_text(encoding="utf-8")
@pytest.mark.parametrize(("cleaned", "passes"), [("Draft paragraph. 063", True), ("Draft\U000e0063", False)])
def test_smoke_text_row_fails_on_any_surviving_tag(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, cleaned: str, passes: bool
) -> None:
import smoke_matrix as smoke
def run(self: Any, name: str, args: list[str], **_kwargs: object) -> Any:
if "-o" in args:
Path(args[args.index("-o") + 1]).write_text(cleaned, encoding="utf-8")
return smoke.Result(name, "pass")
monkeypatch.setattr(smoke.Runner, "run", run)
monkeypatch.setattr(smoke, "_ffmpeg_media_rows", lambda *_a: None)
runner = smoke.Runner(tmp_path)
smoke._media_rows(runner, tmp_path)
assert (runner.results[-1].status != "FAIL") is passes