"""An unnamed model loses only metadata and visible marks; its invisible layers stay.""" from __future__ import annotations import subprocess from typing import TYPE_CHECKING import numpy as np import pytest from click.testing import CliRunner from PIL import Image from remove_ai_watermarks import api, cli, trustmark_detector, video, video_invisible from remove_ai_watermarks.metadata import get_ai_metadata, remove_ai_metadata from remove_ai_watermarks.video_tools import find_video_tool if TYPE_CHECKING: from pathlib import Path needs_ffmpeg = pytest.mark.skipif( find_video_tool("ffmpeg") is None or find_video_tool("ffprobe") is None, reason="needs ffmpeg" ) @pytest.mark.parametrize( ("markers", "mark", "known"), [ ({}, None, False), ({}, "generic_ai_label", False), ({}, "veo", True), ({}, "kling", True), ({"aigc_label": "China AIGC label (TC260)"}, None, False), ({"kling_sei": "Kling AI encoder tag"}, None, True), ({"synthid_watermark": "SynthID"}, None, True), ], ) def test_source_is_known_only_when_something_names_the_model(markers, mark, known): assert video.video_source_is_known(markers, mark) is known def _clip(path: Path) -> Path: command = [find_video_tool("ffmpeg"), "-y", "-v", "error", "-f", "lavfi", "-i", "testsrc=s=64x64:d=0.5:r=10"] subprocess.run([*command, "-pix_fmt", "yuv420p", str(path)], check=True) # noqa: S603 return path def _no_pixels(*_a, **_k): pytest.fail("pixel stage ran") @needs_ffmpeg def test_cli_invisible_on_an_unknown_video_writes_nothing(tmp_path, monkeypatch): monkeypatch.setattr(video_invisible, "regenerate_video_candidate", _no_pixels) out = tmp_path / "out.mp4" result = CliRunner().invoke(cli.main, ["video", "invisible", str(_clip(tmp_path / "a.mp4")), "-o", str(out)]) assert result.exit_code == cli.EXIT_NO_INVISIBLE_SIGNAL, result.output assert "model" in result.output assert not out.exists() @needs_ffmpeg def test_cli_all_on_an_unknown_video_keeps_the_pixels(tmp_path, monkeypatch): monkeypatch.setattr(video_invisible, "regenerate_video_candidate", _no_pixels) source, out = _clip(tmp_path / "a.mp4"), tmp_path / "out.mp4" result = CliRunner().invoke(cli.main, ["video", "all", "--invisible", str(source), "-o", str(out)]) assert result.exit_code == 0, result.output assert "model is unknown" in result.output assert out.read_bytes() == source.read_bytes() @needs_ffmpeg def test_a_visible_mark_names_the_model(tmp_path, monkeypatch): def ran(*_a, **_k): raise RuntimeError("pixel stage ran") monkeypatch.setattr(video_invisible, "regenerate_video_candidate", ran) monkeypatch.setattr("remove_ai_watermarks.video_wan.can_run_wan_on_source", lambda *_a, **_k: False) monkeypatch.setattr(video, "_stable_visible_mark", lambda *_a: "veo") with pytest.raises(RuntimeError, match="pixel stage ran"): video.remove_video_invisible(_clip(tmp_path / "a.mp4"), tmp_path / "o.mp4", include_audio_invisible=False) @needs_ffmpeg def test_a_named_bytedance_vendor_selects_the_seedance_route(tmp_path, monkeypatch): def seedance(*_a, **_k): raise RuntimeError("seedance ran") monkeypatch.setattr(video, "remove_video_seedance", seedance) monkeypatch.setattr("remove_ai_watermarks.video_wan.can_run_wan_on_source", lambda *_a, **_k: False) with pytest.raises(RuntimeError, match="seedance ran"): video.remove_video_invisible( _clip(tmp_path / "a.mp4"), tmp_path / "o.mp4", source_vendor="bytedance", include_audio_invisible=False ) @pytest.mark.parametrize( ("vendor", "known"), [("google", True), ("bytedance", True), ("meta", True), ("elevenlabs", False), ("suno", False), (None, False)], ) def test_an_audio_vendor_does_not_name_the_video_model(vendor, known): assert video.video_vendor_is_known(vendor) is known @needs_ffmpeg def test_all_with_an_audio_vendor_keeps_unknown_video_pixels(tmp_path, monkeypatch): seen = {} monkeypatch.setattr(video, "remove_video_all", lambda *_a, **k: seen.update(k) or (_ for _ in ()).throw(OSError)) CliRunner().invoke(cli.main, ["all", str(_clip(tmp_path / "a.mp4")), "--vendor", "elevenlabs"]) assert seen["include_invisible"] == "auto" def test_a_named_google_vendor_overrides_bytedance_evidence(tmp_path, monkeypatch): monkeypatch.setattr("remove_ai_watermarks.video_wan.can_run_wan_on_source", lambda *_a, **_k: False) kwargs = {"device": "cpu", "quality": "delivery", "noise_std": video.DEFAULT_VIDEO_SYNTHID_NOISE_STD} kwargs |= {"long_side": video.DEFAULT_VIDEO_SYNTHID_LONG_SIDE, "fps": None, "batch_size": 4, "seed": 0} kwargs |= {"model": video.DEFAULT_VIDEO_SYNTHID_VAE, "temporal_stabilize": True, "visible_mark": "seedance"} resolve = video._resolve_video_invisible_profile assert resolve("auto", tmp_path / "a.mp4", detected_metadata={}, **kwargs) == "seedance" assert resolve("auto", tmp_path / "a.mp4", detected_metadata={}, source_vendor="google", **kwargs) == "synthid" @needs_ffmpeg def test_batch_copies_an_unknown_video_instead_of_failing(tmp_path): folder, out = tmp_path / "in", tmp_path / "out" folder.mkdir() source = _clip(folder / "a.mp4") result = CliRunner().invoke(cli.main, ["batch", str(folder), "--mode", "invisible", "-o", str(out)]) assert result.exit_code == 0, result.output assert (out / "a.mp4").read_bytes() == source.read_bytes() def test_the_gemini_sparkle_names_the_image_cohort(tmp_path, monkeypatch): from remove_ai_watermarks import invisible_engine seen: list[str | None] = [] class Engine: def remove_watermark(self, *_a, **kwargs): seen.append(kwargs["vendor"]) return kwargs["output_path"] monkeypatch.setattr(invisible_engine, "is_available", lambda: True) source = tmp_path / "a.png" Image.fromarray(np.full((64, 64, 3), 90, np.uint8)).save(source) for visible, expected in ((None, "no-signal"), ("google", "removed")): monkeypatch.setattr(api, "_visible_vendor", lambda _keys, v=visible: v) assert api.remove_all(source, tmp_path / "o.png", engine=Engine()).invisible == expected assert seen == ["google"] monkeypatch.undo() assert api._visible_vendor(["jimeng", "gemini"]) == "google" assert api._visible_vendor(["jimeng"]) is None def test_trustmark_removal_reports_a_failed_source_check(tmp_path, monkeypatch): class Decoder: def decode(self, *_a): raise MemoryError("decoder died") monkeypatch.setattr(trustmark_detector, "is_available", lambda: True) monkeypatch.setattr(trustmark_detector, "_decoder_for_variant", lambda _v: Decoder()) source = tmp_path / "a.png" Image.new("RGB", (64, 64)).save(source) with pytest.raises(RuntimeError, match="could not check"): trustmark_detector.remove_trustmark(source, tmp_path / "o.png") def test_sampling_at_the_source_rate_keeps_every_frame(): for fps in (12.0, 7.0, 23.976, 30.0): for digits in (3, 6): times = [round(i / fps, digits) for i in range(500)] assert len(video_invisible.select_sampled_indices(times, fps)) == 500 SUNO = "made with suno; created=2026-01-02T03:04:05Z; id=01234567-89ab-cdef-0123-456789abcdef" FFMETA = """;FFMETADATA1 title=Song artist=Band comment={comment} mystery=dropped [CHAPTER] TIMEBASE=1/1000 START=0 END=500 title=Intro """ def _tagged(tmp_path: Path, suffix: str, comment: str) -> Path: meta, out = tmp_path / "m.txt", tmp_path / f"a{suffix}" meta.write_text(FFMETA.format(comment=comment.replace(";", "\\;").replace("=", "\\=")), encoding="utf-8") command = [find_video_tool("ffmpeg"), "-y", "-v", "error", "-f", "lavfi", "-i", "sine=d=1", "-i", str(meta)] subprocess.run( # noqa: S603 [*command, "-map", "0:a", "-map_metadata", "1", "-map_chapters", "1", str(out)], check=True ) return out def _tags(path: Path) -> str: command = [find_video_tool("ffprobe"), "-v", "error", "-show_format", "-show_streams", "-show_chapters"] return subprocess.run([*command, str(path)], check=True, capture_output=True, text=True).stdout # noqa: S603 @needs_ffmpeg @pytest.mark.parametrize("suffix", [".mp3", ".wav", ".flac", ".ogg", ".opus"]) def test_ordinary_tags_survive_an_ai_metadata_strip(tmp_path, suffix): source, out = _tagged(tmp_path, suffix, SUNO), tmp_path / f"o{suffix}" assert get_ai_metadata(source) remove_ai_metadata(source, out) tags = _tags(out) assert get_ai_metadata(out) == {} assert "Song" in tags assert "Band" in tags assert "suno" not in tags.lower() assert "dropped" not in tags if suffix == ".mp3": assert "Intro" in tags remove_ai_metadata(source, out, keep_standard=False) assert "Song" not in _tags(out) @needs_ffmpeg def test_matroska_tags_and_chapters_survive(tmp_path): source, out = _tagged(tmp_path, ".mkv", "an ordinary note"), tmp_path / "o.mkv" remove_ai_metadata(source, out) tags = _tags(out) for kept in ("Song", "Band", "an ordinary note", "Intro"): assert kept in tags assert "dropped" not in tags @needs_ffmpeg def test_kept_tags_that_still_read_as_ai_are_dropped(tmp_path, monkeypatch): from remove_ai_watermarks import metadata source, out = _tagged(tmp_path, ".mp3", SUNO), tmp_path / "o.mp3" monkeypatch.setattr(metadata, "_ordinary_media_tag", lambda *_a, **_k: True) remove_ai_metadata(source, out) assert get_ai_metadata(out) == {} @needs_ffmpeg @pytest.mark.parametrize("count", [3, 7]) def test_native_cadence_needs_one_time_per_frame(tmp_path, count): from tests.test_video_synthid_audio import _stub_2d_vae_runtime out = tmp_path / "o.mp4" with pytest.raises(ValueError, match=r"Decoded .* presentation times"): video_invisible.regenerate_video_candidate( _clip(tmp_path / "a.mp4"), out, device="cpu", runtime=_stub_2d_vae_runtime(), temporal_stabilize=False, _frame_stream=[np.zeros((64, 64, 3), np.uint8)] * count, ) assert not out.exists() def test_cli_passes_the_chosen_audio_streams(tmp_path, monkeypatch): seen = {} def fake(*_a, **kwargs): seen.update(kwargs) raise ValueError("stop") monkeypatch.setattr(video, "remove_video_invisible", fake) source = tmp_path / "a.mp4" source.write_bytes(b"x") CliRunner().invoke(cli.main, ["video", "invisible", str(source), "--audio-stream", "1"]) assert seen["audio_streams"] == (1,)