diff --git a/README.md b/README.md index 855b0a8..19dd8f6 100644 --- a/README.md +++ b/README.md @@ -52,9 +52,9 @@ removal. | Erase a region you select | `erase` | No | | Strip AI metadata | `metadata` | No | | Identify supported video provenance | `video identify` | No | -| Inspect audio metadata and compatible public-model evidence | `audio identify` (`--scheme auto`, `audioseal`, `wavmark`, `perth`, `silentcipher`, `silentcipher16`, or `all`) | No | +| Inspect audio metadata and compatible public-model evidence | `audio identify` (`--scheme auto`, `audioseal`, `wavmark`, `perth`, `silentcipher`, or `all`) | No | | Strip AI metadata from audio | `audio metadata` | No | -| Process a detected compatible audio watermark and verify the saved file (`.wav`, `.flac`, `.mp3`, `.m4a`, `.ogg`, `.opus`) | `audio invisible` | No | +| Process a detected compatible audio watermark and verify the saved file (`.wav`, `.flac`, `.mp3`, `.m4a`, `.ogg`, `.oga`, `.opus`, `.aac`, `.mka`) | `audio invisible` | No | | Strip AI metadata and optionally clean compatible audio watermarks | `audio all` / `audio batch` | No | | Process one or all audio tracks (`--all-streams`) while copying encoded video | `video audio` | No | | Remove visible marks, AI metadata, and opt-in video/audio invisible marks | `video all` | Depends on `--invisible` | @@ -107,7 +107,7 @@ specialized Python API can inspect and disrupt the validated local | Video SynthID removal | `remove-ai-watermarks[video,diffusion]` | | Audio sample processing and spectral disruption | `remove-ai-watermarks[audio]` | | Compatible public audio watermark detection (AudioSeal) | `remove-ai-watermarks[audio-detect]` | -| Neural audio codec resynthesis (EnCodec / FocalCodec / DAC) | `remove-ai-watermarks[audio-codec]` | +| Neural audio codec resynthesis (EnCodec / DAC / SNAC) | `remove-ai-watermarks[audio-codec]` | | Torch-free DWT-DCT detection | `remove-ai-watermarks[detect]` | | Direct local Paint InvisMark disruption | `remove-ai-watermarks[pixels]` | | Invisible image removal (needs CUDA) | `remove-ai-watermarks[qwen-zimage]` | @@ -115,7 +115,7 @@ specialized Python API can inspect and disrupt the validated local | Optional OCR proposals for operator verification | `remove-ai-watermarks[text-draft]` | Lower-level and specialized extras include `pixels`, `heif`, `trustmark`, -`migan`, `lama`, `diffusion`, `source-classify`, `audio-vocoder`, +`migan`, `lama`, `diffusion`, `source-classify`, `audio-wavmark`, `audio-perth`, and `audio-silentcipher`. The [installation guide](https://github.com/wiltodelta/remove-ai-watermarks/blob/main/docs/installation.md#feature-extras) documents their exact dependency composition, Python compatibility, and model requirements. @@ -367,8 +367,8 @@ version. One command (`remove-ai-watermarks all -o `) handles visible marks, provenance-triggered invisible removal, and metadata stripping across images -(`PNG`, `JPG`, `WebP`, `HEIC`, `TIFF`), video (`MP4`, `MOV`, `WebM`, `MKV`, -including 10-bit HEVC/HDR), audio (`WAV`, `MP3`, `M4A`, `FLAC`, `OGG`, `Opus`), +(`PNG`, `JPG`, `WebP`, `HEIC`, `TIFF`), video (`MP4`, `MOV`, `M4V`, `WebM`, `MKV`, `AVI`, `FLV`, +including 10-bit HEVC/HDR), audio (`WAV`, `FLAC`, `MP3`, `M4A`, `OGG`, `OGA`, `Opus`, `AAC`, `MKA`), and text (`MD`, `HTML`, `TXT`): ```bash diff --git a/docs/audio-video-removal.md b/docs/audio-video-removal.md index 7ec160f..1a1c05a 100644 --- a/docs/audio-video-removal.md +++ b/docs/audio-video-removal.md @@ -409,83 +409,36 @@ The `audio identify`, `audio metadata`, `audio invisible`, `audio all`, and `audio batch` commands implement the optional audio runtime. `audio` provides streaming spectral processing, `audio-detect` adds the pinned open AudioSeal verifier, and `audio-wavmark` adds the public WavMark verifier. Select -`--scheme auto`, `audioseal`, `wavmark`, `perth`, `silentcipher`, -`silentcipher16`, or `all`; `--scheme auto` scans installed production-ready -decoders (`audioseal`, `wavmark`, `perth`) and adapts candidate profiles to the -detected scheme(s), whereas a missing explicitly requested decoder prevents a -complete negative. `audio-codec` adds pinned EnCodec resynthesis (using stereo -Mid/Side coding on 2-channel audio to preserve inter-channel spatial image). -Default `--method auto` tries spectral then combined for AudioSeal and Perth v1, -neural then combined for WavMark and both experimental SilentCipher receivers, -and combined when multiple schemes require joint removal. Explicit `spectral`, -`encodec`, or `combined` fixes one profile. The default publishes `.wav`, -`.flac`, `.mp3`, `.m4a`, `.ogg`, or `.opus` only after a positive source and -fully negative saved output (re-decoded from the delivered file, including post-encode -lossy verification and Opus 48 kHz rate adaptation). Explicit force can write an -unverified or resistant candidate, with that outcome preserved in the report. -Native channels, rate (48 kHz for Opus), and sample-frame count (within codec -priming bounds on lossy containers) are checked. Fidelity is measured on the -delivered file. Whole-clip verification uses segmented `<= 30 s` windows on long -inputs; window-only discovery negatives cannot certify the whole clip. +`--scheme auto`, `audioseal`, `wavmark`, `perth`, `silentcipher`, or `all`; +`--scheme auto` scans installed production-ready decoders (`audioseal`, +`wavmark`, `perth`) and adapts candidate profiles to the detected scheme(s), +whereas a missing explicitly requested decoder prevents a complete negative. +`audio-codec` adds pinned EnCodec (using stereo Mid/Side coding on 2-channel +audio), 44.1 kHz DAC (`--method dac`, default `preserve_hf_hz=14000.0` on +`>= 44.1 kHz` tracks), and 44.1 kHz multi-scale SNAC (`--method snac`) neural +resynthesis. Default `--method auto` tries spectral then combined for AudioSeal +and Perth v1, neural then combined for WavMark and SilentCipher-44k, routes +wideband AI audio cohorts (ElevenLabs, Google SynthID, Suno, Udio, etc.) to +`dac`, and uses combined when multiple schemes require joint removal. Explicit +`spectral`, `encodec`, `combined`, `dac`, or `snac` fixes one profile. The +default publishes `.wav`, `.flac`, `.mp3`, `.m4a`, `.ogg`, `.oga`, `.opus`, +`.aac`, or `.mka` only after a positive source and fully negative saved output +(re-decoded from the delivered file, including post-encode lossy verification +and Opus 48 kHz rate adaptation). Explicit force can write an unverified or +resistant candidate, with that outcome preserved in the report. Native channels, +rate (48 kHz for Opus), and sample-frame count (within codec priming bounds on +lossy containers) are checked. Fidelity is measured on the delivered file. +Whole-clip verification uses segmented `<= 30 s` windows on long inputs; +window-only discovery negatives cannot certify the whole clip. -Explicit `--method bigvgan` adds the pinned experimental full-track mel-vocoder -through `audio-vocoder`. It uses raw mid/side for stereo and the original rational -sample grid; mono/stereo, 30-second and sample-value bounds apply. CPU/MPS/CUDA -are explicitly selected through `--vocoder-device`, without fallback or chunking. -It is excluded from auto selection and uses the same local source/saved-output -decoder gates. See the [research roadmap](media-removal-roadmap.md) for separately -recorded provider observations; those are not a built-in SynthID verifier. - -Explicit `--method mimi` uses the separate experimental pinned CPU FP32 codec -with its default 32 quantizers from `audio-codec`. Its full-track mono/stereo -route shares the native rational sample grid and bitexact WAV writer. The model -owns decoder-excess prefix selection; no external padding, normalization, -alignment or clipping is added. Auto selection excludes it, and native output -rate does not undo the internal 24 kHz bandwidth limit. Local independent Perth -examples became negative, but one short example failed the frozen relative -voice guard; provider and general fidelity qualification remain separate. - -On a later complete long native generation, EnCodec 6 was negative over the -whole file but remained positive in individual windows. The detector therefore -reported a positive overall result. Mimi passed complete full-file and window -verification on the marked file, with exact recognized words, both-reference -speaker consistency and full-duration timing. Its processed clean twin failed -exact transcript agreement, so general paired qualification still failed. -The exact marked Mimi file also passed verified public WAV and selected-track -MOV delivery. A separate AAC MP4 experiment passed fresh quality and complete -Perth checks on the actual final decoded track, preserving native count/start, -priming/tail interpretation and untouched stream packets. These are scoped -local Perth results on one native Chatterbox Nano file. They establish neither -hosted Resemble compatibility nor Google SynthID removal; short speaker -embeddings and ASR agreement are measured guards, not identity or listening -certificates. - -Explicit `--method focalcodec` uses the separate experimental pinned CPU FP32 -continuous 6-layer WavLM feature-to-Vocos resynthesizer from `audio-codec` -(`lucadellalib/focalcodec_50hz@d6d6d9524e52155c85193c2c3b8da1cf8842f019`, -matching upstream `v0.0.1` `cad8bf81d70875f756770449c34909d8b0951642` under -Apache-2.0). It operates on an internal 16 kHz grid (`8 kHz` ceiling) with -symmetric `(40, 40)` WavLM boundary context, raw mid/side stereo, exact native -sample counts, and bitexact WAV serialization, while bypassing binary spherical -quantization. Synthetic impulse and bandlimited burst probes showed that Vocos -ISTFT synthesis introduces a small consistent group delay (around `+2.38 ms`) -while randomizing carrier waveform phase. Measured with a calibrated -phase-invariant log-mel onset-flux and modulation-envelope timing observer, -FocalCodec passed complete paired clean and marked checks on that first long -native Chatterbox Nano generation across WAV, selected-track PCM MOV, and lossy -AAC MP4 (negative full-file and quarter-second Perth windows, exact words, -speaker cosine `>= 0.98` against both source references, bounded loudness/RMS -change, zero clipping, full-duration timing within `10 ms`, and untouched -non-target container packets). On a second held-out native speech generation, -FocalCodec preserved an atypical phrase (`"a wind shelf"`) where Mimi -regularized `"wind"` to `"wooden"` and failed Perth after AAC MP4 encoding, -whereas FocalCodec's Vocos STFT synthesis cross-reacted with Perth in a pause -interval (`[4.0s, 5.0s]`), including on the unwatermarked clean twin. Both -explicit experimental codecs therefore remain excluded from `auto` and gated by -mandatory saved-output verification. Both `--method focalcodec` and -`--method dac` process tracks up to `30 s` in a single pass and stream tracks -longer than `30 s` across `20 s` windows with `2 s` raised-cosine crossfades -while preserving the exact native sample-frame count. +Both `--method dac` and `--method snac` process tracks up to `30 s` in a single +pass and stream tracks longer than `30 s` across `20 s` windows with `2 s` +raised-cosine crossfades while preserving the exact native sample-frame count. +Earlier experimental prototypes (`bigvgan`, `mimi`, `focalcodec`, and the +terminated `silentcipher16` candidate) were retired in `v0.73.0` after 44.1 kHz +DAC and SNAC outperformed them across quality and live SynthID oracle checks; +their historical benchmark records remain in +[the evidence log](media-removal-evidence-log.md). ### Local exploratory study, 2026-11-09 diff --git a/docs/cli.md b/docs/cli.md index 68c419c..ea9723c 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -30,7 +30,6 @@ defaults. This page focuses on choosing the right command. | `audio identify --no-invisible` | Default package plus ffmpeg and ffprobe | | `audio identify` and verified `audio invisible` | `remove-ai-watermarks[audio-detect]` plus ffmpeg and ffprobe | | Audio `--scheme silentcipher` | `audio-silentcipher`, for the experimental public SilentCipher-44k receiver | -| Audio `--scheme silentcipher16` | `audio-silentcipher`, for the experimental terminated eight-symbol 16k pattern | | Audio `--scheme perth` | `audio-perth`, for pinned public Perth v1 | | Audio `--scheme wavmark` | `audio-wavmark`; `--scheme all` needs `audio-detect`, `audio-wavmark`, `audio-perth`, and `audio-silentcipher` | | `audio invisible --allow-unverified --no-verify` | `remove-ai-watermarks[audio]` plus ffmpeg and ffprobe | @@ -63,8 +62,8 @@ remove-ai-watermarks audio batch ./tracks -o ./tracks_clean --mode all --invisib `--json`. Inspection reports metadata, a source SHA-256, stream geometry, named compatible decoder checks, and a suggested `recommended_recipe` when AI metadata or a compatible watermark signal is found. `--no-invisible` skips model inference. -`--scheme` selects `audioseal` (default on `identify`/`invisible`), `auto` (scans every *installed* non-experimental compatible public decoder — `audioseal`, `wavmark`, and `perth` — without failing when an optional decoder extra is absent or a clip is shorter than WavMark's 1-second minimum window, leaving the overall status `unverified` only if no applicable decoder completes), `wavmark`, `perth`, `silentcipher`, `silentcipher16`, or `all` (requires all named public -models, including both experimental SilentCipher receivers). A missing explicitly requested decoder keeps the combined result unverified. +`--scheme` selects `audioseal` (default on `identify`/`invisible`), `auto` (scans every *installed* non-experimental compatible public decoder — `audioseal`, `wavmark`, and `perth` — without failing when an optional decoder extra is absent or a clip is shorter than WavMark's 1-second minimum window, leaving the overall status `unverified` only if no applicable decoder completes), `wavmark`, `perth`, `silentcipher`, or `all` (requires all named public +models, including the experimental SilentCipher-44k receiver). A missing explicitly requested decoder keeps the combined result unverified. For validated 24 and 48 kHz sources, AudioSeal checks both a resampled 16 kHz clock and the original sample clock. Other native clocks are not added automatically. JSON detections identify the clock in `decoder_sample_rate`; verification requires both clocks to be negative, across channels and windows. @@ -78,18 +77,11 @@ and records their native `decoder_sample_rate`. Custom messages and shifted/resampled framing are outside this receiver. SilentCipher-44k uses three-second windows and an experimental consistency threshold, with exhaustive phase search. Shorter sources stay unverified; CPU decoding can be slow. -Its JSON `decoder_sample_rate` is 44100 even for 16 kHz input. This receiver -does not check the 16 kHz model. The separate `silentcipher16` route checks only -an experimental terminated eight-symbol pattern, with `decoder_sample_rate=16000` -regardless of input rate. Readings label `framing="terminated8"`. JSON -`payload_symbols` contains seven ternary symbols, -not bytes. The SDK byte API and general 32-bit profile remain unqualified. -Three-second windows and the complete 103-position phase grid are required for -a negative. `all` includes both SilentCipher receivers. Neither negative +Its JSON `decoder_sample_rate` is 44100 even for 16 kHz input. Neither negative certifies a production provider, other framing, or complete payload erasure. `audio invisible` defaults to `--method auto`, an adaptive minimal-distortion profile sequence for the -requested scheme and pre-strip vendor metadata. AudioSeal and Perth v1 try spectral then combined processing; WavMark and both experimental SilentCipher receivers +requested scheme and pre-strip vendor metadata. AudioSeal and Perth v1 try spectral then combined processing; WavMark and SilentCipher-44k try neural then combined; when pre-strip C2PA/container metadata identifies ElevenLabs (`("dac", "encodec", "combined")` on mono, stereo, or tagged 5.1/7.1 when `dac` is installed, else `("encodec", "combined")`) or Google SynthID (`("dac", "combined")` on the same layouts when `dac` is installed, else `dac` alone, which fails closed), `--method auto` skips `spectral` and routes directly to neural codec resynthesis; an explicit `--vendor` cohort (`google`, `elevenlabs`, `suno`, `udio`, `openai`, `cartesia`, `meta`, `resemble`, `microsoft`) selects the same kind of vendor-matched sequence when metadata was already stripped and authorizes processing without `--allow-unverified`; when `--scheme auto` or `--scheme all` detects a specific subset of public schemes on the source, `--method auto` adapts to the lightest profile sequence covering only the positively detected schemes before falling back to `combined`. Publication requires a positive compatible source check and proceeds only after the saved output is negative in whole-clip and window checks. A resistant or @@ -99,7 +91,7 @@ No targeted source signal exits 2 without writing. Hard failures exit 1. Use `--allow-unverified` (for example with `--method dac` on proprietary audio marks or alongside `--no-verify`) to process without a local source-positive decoder match while still enforcing the saved-file SNR, RMS, and 1-second active-window integrity gate. Use `--allow-positive` only when you explicitly want to retain an output that still tests positive on the final attempt (exits 1), and `--allow-quality-override` only when you explicitly want to bypass the audio integrity gate. `--force` remains an alias enabling `--allow-unverified`, `--allow-positive`, and `--allow-quality-override` on the final attempt. Unverified processing exits 0 with `verified_removed: null`; this is not a removal certificate. `--verify` is the default. The default output is `SOURCE_processed.wav`; `-o` / `--output` -accepts `.wav`, `.flac`, `.mp3` (`libmp3lame` 256 kbps CBR with Xing header), `.m4a` (`aac` 192 kbps with faststart), `.ogg`, or `.opus` (`libopus` 192 kbps). Encoding discards AI metadata and preserves native sample +accepts `.wav`, `.flac`, `.mp3` (`libmp3lame` 256 kbps CBR with Xing header), `.m4a` (`aac` 192 kbps with faststart), `.ogg`, `.oga`, `.opus` (`libopus` 192 kbps), `.aac` (`aac` 192 kbps ADTS), or `.mka` (`flac` in Matroska). Encoding discards AI metadata and preserves native sample rate and channels (Opus internally codes on its RFC 7845 48 kHz grid and resamples back to the source clock during fidelity measurement). Reports measure fidelity (including `worst_window_rms_ratio` across 1-second active windows and stereo `max_side_mid_drift_db`) and run decoder verification on the actual saved file, so lossy recompression relapses and mid-track dropouts are caught before publication. The filter changes audible content and can fail on tonal inputs. See [audio coverage](audio-video-removal.md) for tested families and limits. @@ -113,55 +105,18 @@ See [audio coverage](audio-video-removal.md) for tested families and limits. `--method spectral` fixes the spectral profile. `--method encodec` selects optional neural resynthesis. `--bandwidth` accepts `6`, `12`, or `24` kbps and defaults to `24`; it applies only to EnCodec. -`--vocoder-device` (`cpu` default, `mps`, or `cuda`) applies to EnCodec, -`combined`, BigVGAN, and DAC; spectral, Mimi, and FocalCodec require `cpu`. +`--vocoder-device` (`auto` default, `cpu`, `mps`, or `cuda`) applies to EnCodec, +`combined`, DAC, and SNAC; `spectral` requires `cpu`. Lower bandwidth can change speech timbre or music substantially. On 2-channel stereo tracks, EnCodec resynthesizes in Mid/Side (`M/S`) space rather than independent L/R passes so stereo phantom-center phase coherence is preserved, while retaining native channels, rate, and sample-frame count using bounded context. It has the same source-positive and saved-output verification gate, and can fail even when a whole-clip reading is negative but a window remains positive. `--method combined` applies the spectral filter followed by that neural codec. It uses the same optional extra and bandwidth choices. Automatic neural fallback also needs `audio-codec`; if unavailable, output remains unpublished. -`--method bigvgan` explicitly selects the experimental pinned mel-vocoder -(`audio-vocoder` extra). It processes one complete mono/stereo track, limited -to 30 seconds and 16 million sample values, without chunking, normalization, -or added output clipping. Stereo uses raw mid/side reconstruction. Select -`--vocoder-device cpu` (default), `mps`, or `cuda`; no automatic device fallback -is performed. CUDA and short-signal perceptual quality remain unqualified. -The method is never selected by `auto`, ignores EnCodec bandwidth, and retains -the same local decoder gates. Those gates do not verify Google SynthID. -BigVGAN WAV serialization is deterministic and omits the encoder tag and RF64 -reserve padding. Exact-file provider verdicts can be reused only when the -complete output hash and verification surface match; PCM equality alone is -insufficient. FLAC output is separately encoded and needs its own qualification. -`--method mimi` selects the separate experimental CPU FP32 Mimi codec using -its fixed default 32 quantizers (`audio-codec` extra). It uses the same bounded -full-track mono/stereo collector, raw mid/side stereo, native sample grid and -bitexact WAV writer. Its internal 24 kHz grid limits representable bandwidth; -retaining the source rate is not preservation of its highest frequencies. -EnCodec bandwidth and a non-CPU vocoder device do not apply. `auto` never -selects Mimi. Local Perth experiments removed the signal on independent speech -generations, but one short generation failed the frozen relative voice guard. -Native-provider candidates remain unverified. -`--method focalcodec` selects the separate experimental CPU FP32 continuous -6-layer WavLM feature-to-Vocos resynthesizer (`audio-codec` extra, pinned to -`lucadellalib/focalcodec_50hz@d6d6d9524e52155c85193c2c3b8da1cf8842f019` and -upstream `v0.0.1` `cad8bf81d70875f756770449c34909d8b0951642`). It runs -single-pass resynthesis up to 30 seconds and raised-cosine overlap-window -streaming on longer mono/stereo audio (`> 30 s`), preserving raw mid/side stereo, exact native -sample grid, symmetric `(40, 40)` WavLM receptive-field context, smooth -source-activity pause conditioning (`-42 dBFS` active speech / `-50 dBFS` quiet -intervals), and bitexact WAV writer. Its internal 16 kHz grid limits representable -bandwidth to 8 kHz. EnCodec bandwidth and a non-CPU vocoder device do not apply, -and `auto` never selects FocalCodec. On native speech, conditioned FocalCodec -passed complete paired WAV, PCM MOV, and AAC 192 kbps MP4 checks across `LONG03`, -`LONG04`, and an untouched held-out `LONG05` generation while preserving atypical -lexical phrasing where Mimi regularized a word. None of BigVGAN, Mimi, -FocalCodec, or DAC supplies a SynthID decoder or guarantees words, voice, music, -or ambience fidelity on a new input. -`--method dac` selects the separate experimental FP32 44.1 kHz 3-codebook +`--method dac` selects the FP32 44.1 kHz 3-codebook Descript Audio Codec (`audio-codec` extra, pinned to `descript/dac_44khz@c1bc521685adf9cfe247bc39a5ca58917eda1ac4`, MIT weights in -`licenses/dac/NOTICE.txt`). It accepts mono, stereo, and tagged 5.1/7.1 layouts, +`licenses/dac/NOTICE.txt`, defaulting `preserve_hf_hz=14000.0` on `>= 44.1 kHz` tracks). It accepts mono, stereo, and tagged 5.1/7.1 layouts, and runs single-pass resynthesis up to 30 seconds and raised-cosine overlap-window streaming on longer audio (`> 30 s`), with raw mid/side stereo, stem RMS preservation, exact @@ -752,8 +707,9 @@ provider-oracle evidence covers short single-pass clips (`<= 10 s`); remove-ai-watermarks video invisible input.mp4 -o clean.mp4 --profile seedance ``` -The fixed recipe accepts owned SDR 8-bit and **10-bit HEVC/HDR** MP4 files with -even dimensions, preserving native bit depth (`yuv420p10le`), color tags +The fixed recipe accepts owned SDR 8-bit and **10-bit HEVC/HDR** video files +across all 7 supported containers (`.mp4`, `.mov`, `.m4v`, `.mkv`, `.webm`, +`.avi`, `.flv`) with even dimensions, preserving native bit depth (`yuv420p10le`), color tags (`color_primaries`, `color_trc`, `colorspace`, `color_range`), geometry, frame timestamps, terminal video duration, and source audio. `--quality delivery` (default) writes H.264 High CRF18 for 8-bit or HEVC (`libx265`, `hvc1`) CRF18 @@ -768,35 +724,32 @@ SynthID. The default profile is `auto`, which routes ByteDance/Seedance clips to the Seedance pipeline automatically and SynthID/other clips to the SynthID pipeline (or Wan 2.1 on eligible BF16 CUDA hosts). -This experimental transform reproduced the matched-control CapCut outcome +This transform reproduced the matched-control CapCut outcome recorded in [the study](seedance-video-study.md). No detector or external upload runs during processing. The standalone invisible command expects visible labels to have been handled already; `video all` runs its existing visible stage first. -## Apply the experimental CUDA 3D Wan 2.1 video diffusion profiles and `--profile auto` +## Apply the 3D Wan 2.1 video diffusion profiles and `--profile auto` On hosts with a hardware BF16-capable NVIDIA CUDA GPU (Ampere or newer; ROCm and -pre-Ampere emulation are excluded), two explicit 3D causal video diffusion -profiles preserve native resolution and frame rate on SDR 8-bit MP4, MOV, and -M4V clips within -the conservative decoded-frame budget (`<= 1920x1080` frame area and -`<= 552,960,000` total decoded pixel-frames, streaming clips longer than 193 -frames through overlapping 3D causal windows with 17-frame raised-cosine -temporal crossfades directly to the encoder without buffering the full clip in -host RAM), and `--profile auto` automatically routes eligible ByteDance/Seedance -MP4, MOV, and M4V clips (`<= 1920x1080` frame area and `>= 8 GiB` total GPU VRAM, -stepping down from 193-frame to 81-frame chunks on 1080p or `< 16 GiB` CUDA and -skipping the UMT5 text encoder whenever the static neutral prompt embedding is -cached locally) to -`wan21-seedance-experimental` on BF16 CUDA (`seedance-experimental` on CPU/MPS -for MP4, or `synthid` for MOV/M4V/MKV/WebM or when the auto Wan budget is exceeded) and -other eligible SDR 8-bit MP4, MOV, and M4V clips to -`wan21-synthid-experimental` on BF16 CUDA (`synthid` fallback otherwise): +pre-Ampere emulation are excluded) or explicit Apple Silicon `--device mps`, two +3D causal video diffusion profiles preserve native resolution and frame rate on +SDR 8-bit and 10-bit HDR clips across all 7 containers (`.mp4`, `.mov`, `.m4v`, +`.mkv`, `.webm`, `.avi`, `.flv`), using 1080p-guided high-frequency texture +restoration above `1920x1080` and streaming clips longer than 193 frames through +overlapping 3D causal windows with 17-frame raised-cosine temporal crossfades +directly to the encoder without buffering the full clip in host RAM. +`--profile auto` automatically routes eligible ByteDance/Seedance clips +(`>= 8 GiB` total GPU VRAM on BF16 CUDA, stepping down from 193-frame to +81-frame chunks on 1080p or `< 16 GiB` CUDA and skipping the UMT5 text encoder +whenever the static neutral prompt embedding is cached locally) to +`wan21-seedance` on BF16 CUDA (`seedance` on CPU/MPS) and other eligible clips +to `wan21-synthid` on BF16 CUDA (`synthid` fallback otherwise): ```bash remove-ai-watermarks video all input.mp4 -o clean.mp4 --invisible --profile auto -remove-ai-watermarks video invisible veo.mp4 -o veo_clean.mp4 --profile wan21-synthid-experimental -remove-ai-watermarks video all seedance.mp4 -o seedance_clean.mp4 --invisible --profile wan21-seedance-experimental +remove-ai-watermarks video invisible veo.mp4 -o veo_clean.mp4 --profile wan21-synthid +remove-ai-watermarks video all seedance.mp4 -o seedance_clean.mp4 --invisible --profile wan21-seedance ``` Both load pinned Apache-2.0 `Wan-AI/Wan2.1-T2V-1.3B-Diffusers` (`0fad780a534b6463e45facd96134c9f345acfa5b`, @@ -1236,7 +1189,7 @@ The JSON result includes delivered-file SSIM, PSNR, temporal measurements, and `quality_passed`. Processing accepts one video stream with optional audio streams and uniform, -zero-based video timestamps. Outputs are MP4, MOV, or M4V, defaulting to +zero-based video timestamps. Outputs are MP4, MOV, M4V, MKV, WebM, AVI, or FLV, defaulting to `SOURCE_message_processed.mp4`. Audio is copied with packet, timing, decoded sample, language, and disposition checks. Its watermarks remain unverified. Source metadata is dropped. Additional stream types and unsupported timelines diff --git a/docs/installation.md b/docs/installation.md index 6b8f2d8..e992ace 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -107,7 +107,7 @@ uv tool install --force "remove-ai-watermarks[audio-detect]" `audio` installs NumPy and SciPy, without OpenCV or Torch. `audio-detect` adds the pinned open AudioSeal runtime and downloads hash-checked detector weights on first use. It needs no CUDA. Default removal requires that decoder; explicit -`--method spectral --allow-unverified --no-verify` processing only requires `audio` while retaining the audio integrity gate. Outputs are WAV, FLAC, MP3, M4A, OGG, or Opus. +`--method spectral --allow-unverified --no-verify` processing only requires `audio` while retaining the audio integrity gate. Outputs are WAV, FLAC, MP3, M4A, OGG, OGA, Opus, AAC, or MKA. See [audio coverage and limitations](audio-video-removal.md). Add `audio-codec` for EnCodec resynthesis with `--method encodec`, `combined`, @@ -119,34 +119,16 @@ Combine it with `audio-detect` for default compatible-source verification: uv tool install --force "remove-ai-watermarks[audio-detect,audio-codec]" ``` -This backend uses Torch and Transformers on CPU and downloads pinned, +This backend uses Torch and Transformers (auto-accelerated on CUDA/MPS) and downloads pinned, hash-checked model/configuration artifacts on first use. It is a distinct processing method, with its own quality and watermark-verification results. -The same extra also supplies explicit experimental `--method mimi`, a pinned -CPU FP32 codec with 32 default quantizers, explicit experimental -`--method focalcodec`, a pinned CPU FP32 continuous 6-layer WavLM feature-to-Vocos -resynthesizer (`lucadellalib/focalcodec_50hz` at revision -`d6d6d9524e52155c85193c2c3b8da1cf8842f019`), and explicit experimental -`--method dac`, a pinned FP32 44.1 kHz 3-codebook Descript Audio Codec (CPU by -default; `--vocoder-device mps` or `cuda` also apply) -(`descript/dac_44khz` at revision `c1bc521685adf9cfe247bc39a5ca58917eda1ac4`). -Each downloads separate safetensors and configuration artifacts. -[Mimi weights](https://huggingface.co/kyutai/mimi) are CC-BY-4.0 with -attribution recorded in `licenses/mimi/NOTICE.txt`, -[FocalCodec code and weights](https://huggingface.co/lucadellalib/focalcodec_50hz) -are Apache-2.0 with attribution and third-party notices in -`licenses/focalcodec/`, and [DAC weights](https://huggingface.co/descript/dac_44khz) -are MIT with attribution in `licenses/dac/NOTICE.txt`. Model licenses remain -distinct from the library and Transformers code licenses. None of the three -methods is selected automatically, and all require the requested decoder extra -for checks. - -Add `audio-vocoder` for explicit experimental `--method bigvgan`. This installs -Torch, librosa, and Hugging Face Hub alongside the numerical audio stack. The -runtime downloads revision-pinned configuration and weights on first use, -verifies both hashes, then loads weights strictly without remote Python. -CPU is the default; `--vocoder-device mps` or `cuda` selects that device explicitly. -Retain the chosen decoder extra for verification. See the [CLI limits](cli.md). +The same extra supplies `--method dac`, a pinned FP32 44.1 kHz 3-codebook +Descript Audio Codec (`descript/dac_44khz` at revision +`c1bc521685adf9cfe247bc39a5ca58917eda1ac4`, MIT weights in +`licenses/dac/NOTICE.txt`), and `--method snac`, a pinned 44.1 kHz multi-scale +SNAC codec (`hubertsiuzdak/snac_44khz`). Model licenses remain distinct from the +library and Transformers code licenses. Retain the requested decoder extra for +verification. The explicit `video audio` route uses these same extras. It copies video packets and does not require OpenCV, PyAV, or the `video` extra. @@ -167,9 +149,6 @@ config, and weights are hash-checked before loading. Missing or incompatible installations remain unverified. Public SilentCipher-44k uses `audio-silentcipher` and `--scheme silentcipher`. -The same extra supports `--scheme silentcipher16`, an experimental terminated -eight-symbol pattern with seven ternary payload symbols. It does not qualify -the SDK byte API or general 32-bit profile. `all` includes both receivers. It installs modern Torch, librosa, and Hugging Face Hub, without the legacy SDK and its Torch upper bound. Pinned config and weights are checked before loading. The experimental receiver requires at least three seconds and checks every @@ -266,9 +245,8 @@ application actually uses: | `audio-detect` | Public AudioSeal checks | `audio`, AudioSeal, Hugging Face Hub | Yes | | `audio-wavmark` | Public WavMark checks | `audio`, WavMark | Yes | | `audio-perth` | Public Perth v1 checks | `audio`, validated Perth model modules | Yes | -| `audio-silentcipher` | Experimental SilentCipher-44k and terminated 16k receivers | `audio`, Torch, librosa, Hugging Face Hub | Yes | -| `audio-codec` | Pinned EnCodec and experimental Mimi / FocalCodec / DAC resynthesis | `audio`, Torch, Transformers, safetensors | Yes | -| `audio-vocoder` | Experimental pinned full-track BigVGAN | `audio`, Torch, librosa, Hugging Face Hub | Yes | +| `audio-silentcipher` | Experimental SilentCipher-44k receiver | `audio`, Torch, librosa, Hugging Face Hub | Yes | +| `audio-codec` | Pinned EnCodec, DAC, and SNAC neural audio resynthesis | `audio`, Torch, Transformers, safetensors | Yes | | `video-detect` | Public VideoSeal/PixelSeal/ChunkySeal known-message and blind presence checks | `video`, Torch | Yes | | `video` | Visible video identification/removal and timestamp preservation | `visible`, PyAV, FFmpeg/ffprobe bundle | No | | `detect` | Open DWT-DCT detection for Stable Diffusion, SDXL, and FLUX | `pixels`, PyWavelets | No | diff --git a/docs/known-limitations.md b/docs/known-limitations.md index 19722d9..321e052 100644 --- a/docs/known-limitations.md +++ b/docs/known-limitations.md @@ -296,30 +296,10 @@ or SilentCipher do not certify an entire song or an unsupported provider. ### Standalone `video invisible` copies the audio track unchanged The `audio identify`, `audio metadata`, `audio invisible`, `audio all`, and `audio batch` commands provide named -public AudioSeal/WavMark/Perth v1/SilentCipher-44k/16k checks (`--scheme auto` scans installed decoders) and spectral, neural-codec (with Mid/Side stereo EnCodec or 44.1 kHz DAC, which `auto` selects when pre-strip metadata identifies ElevenLabs or Google SynthID), -combined, or explicit experimental BigVGAN/Mimi/FocalCodec processing -into `.wav`, `.flac`, `.mp3`, `.m4a`, `.ogg`, or `.opus`, while `video audio` (`--stream N` or `--all-streams`) and `video all --audio-invisible` clean compatible audio tracks inside video containers. -The BigVGAN profile is full-track mono/stereo only, bounded in duration and -memory, and excluded from automatic selection. Its local decoder checks do not -verify SynthID. Fixed provider experiments have both a negative outcome on one -native Veo source and retained SynthID on independent native and speech sources; -see the [research roadmap](media-removal-roadmap.md). It is not a general solution. -Mimi is a separate CPU FP32 explicit codec, excluded from auto selection. Its -24 kHz internal grid cannot preserve higher source bandwidth. Local Perth checks -passed independent speech examples, but a short example failed the frozen -relative voice-consistency guard, and a held-out native speech example showed -lexical regularization (`"wind"` to `"wooden"`) and crossed the Perth threshold -after lossy AAC MP4 encoding. -FocalCodec is a separate CPU FP32 explicit continuous WavLM-to-Vocos profile, -excluded from auto selection, whose 16 kHz internal grid limits output bandwidth -to 8 kHz. It passed complete paired WAV, MOV, and AAC MP4 gates on one long -native speech generation and preserved exact words on the held-out generation, -but Vocos STFT synthesis cross-reacted with Perth in a pause window on that -held-out source (including on its unwatermarked twin). Native-provider -candidates remain unverified across all three explicit experimental backends. -Short-window speaker comparisons without a qualified context length remain -exploratory, not proof that a person's identity changed. -They write standalone `.wav`, `.flac`, `.mp3`, `.m4a`, `.ogg`, or `.opus` outputs. They do not change standalone `video invisible` +public AudioSeal/WavMark/Perth v1/SilentCipher-44k checks (`--scheme auto` scans installed decoders) and spectral, neural-codec (with Mid/Side stereo EnCodec, 44.1 kHz DAC with default `preserve_hf_hz=14000.0` on `>= 44.1 kHz` tracks, or 44.1 kHz SNAC; `auto` selects DAC when pre-strip metadata identifies ElevenLabs or Google SynthID), +or combined processing +into `.wav`, `.flac`, `.mp3`, `.m4a`, `.ogg`, `.oga`, `.opus`, `.aac`, or `.mka`, while `video audio` (`--stream N` or `--all-streams`) and `video all --audio-invisible` clean compatible audio tracks inside video containers. +They write standalone `.wav`, `.flac`, `.mp3`, `.m4a`, `.ogg`, `.oga`, `.opus`, `.aac`, or `.mka` outputs. They do not change standalone `video invisible` described below. The fixed spectral profile changes audible content and fails on the calibrated tone-stack carrier. Verification is limited to the pinned compatible decoders, and bounded whole-clip checks can remain unverified. @@ -327,17 +307,12 @@ WavMark also checks the published OpenVoice default message at fixed native offsets; custom messages and shifted/resampled framing remain outside that receiver. Its signature correlation does not identify a provider. `silentcipher` uses only the pinned 44.1 kHz model, including for 16 kHz input. -The separate `silentcipher16` route covers only an experimental terminated -eight-symbol pattern. Its seven ternary payload symbols are not bytes. -The published 16 kHz SDK byte framing is incompatible, and the general 32-bit -profile remains unqualified. Known-message recovery failed on exploratory -tone and noise carriers. See the [artifact analysis](audio-video-removal.md#experimental-silentcipher-44k-receiver). Missing requested decoders cannot become negative results. A negative public model check does not certify a production provider or complete payload erasure. See [audio coverage](audio-video-removal.md) before interpreting a result. The `seedance` (alias `seedance-experimental`) video profile is available through the common invisible/all/batch pipeline and the standalone -`remove_video_seedance_experimental` API. It accepts SDR 8-bit and 10-bit HEVC/HDR (`yuv420p10le`, `BT.709`/`BT.2020`, `PQ`/`HLG`) MP4 with even dimensions and preserves +`remove_video_seedance` API. It accepts SDR 8-bit and 10-bit HEVC/HDR (`yuv420p10le`, `BT.709`/`BT.2020`, `PQ`/`HLG`) in `.mp4`, `.mov`, `.m4v`, `.mkv`, `.webm`, `.avi`, or `.flv` with even dimensions and preserves the native bit depth, color tags, frame clock, and geometry. Its two encoding modes reproduce the label-free `forest` and held-out `bottle` experiments in [the study](seedance-video-study.md), where CapCut detected matched controls and did not detect processed outputs (whereas Dreamina and @@ -346,12 +321,9 @@ This result is scene-dependent, and there is no runtime CapCut detector or external upload. Visible labels must be handled before this pixel stage. Temporary guide/master videos need disk space, although pixel processing uses bounded batches. Both `all` and `video all`/`video invisible` default to `--profile auto` (`profile="auto"`), routing ByteDance/Seedance clips automatically. The `wan21-synthid` and `wan21-seedance` (legacy aliases `wan21-synthid-experimental`, `wan21-seedance-experimental`) 3D diffusion -profiles (`remove_video_wan_experimental`) require an Ampere-or-newer BF16 NVIDIA +profiles (`remove_video_wan`) require an Ampere-or-newer BF16 NVIDIA CUDA GPU, or an explicit `device="mps"` on Apple Silicon that automatic profile -selection never chooses, and SDR 8-bit or 10-bit HDR (`yuv420p10le`/`yuv422p10le`/`yuv444p10le`, `BT.2020`, `PQ`/`HLG`) MP4, MOV, or M4V input within -`WAN21_MAX_FRAME_PIXELS` (`3840x2160`, using 1080p-guided high-frequency texture -restoration above `1920x1080`) and `WAN21_MAX_TOTAL_PIXEL_FRAMES` -(`7200 * 1920 * 1080`). They stream clips longer than `193` frames across `4k+1` +selection never chooses, and accept SDR 8-bit or 10-bit HDR (`yuv420p10le`/`yuv422p10le`/`yuv444p10le`, `BT.2020`, `PQ`/`HLG`) across all 7 containers (`.mp4`, `.mov`, `.m4v`, `.mkv`, `.webm`, `.avi`, `.flv`), using 1080p-guided high-frequency texture restoration above `1920x1080`. They stream clips longer than `193` frames across `4k+1` 3D causal windows (`chunk_frames=193`, `overlap_frames=17`) with raised-cosine temporal crossfades directly to the encoder, have oracle evidence from an NVIDIA H100 at `1280x720`, and likewise perform no runtime detector diff --git a/docs/mcp-server.md b/docs/mcp-server.md index fd22680..a2f6599 100644 --- a/docs/mcp-server.md +++ b/docs/mcp-server.md @@ -70,7 +70,7 @@ when an optional backend is absent. | `remove` | `metadata --remove`, `visible` or `all` for an image; `video metadata --remove`, `video visible` or `video all` for a video; `audio metadata --remove` or `audio all --invisible` for audio; `text metadata --remove` or `text all` for text (or top-level `all --preset` when `preset` is set) | One output file, `_clean` beside the source unless `output` is given | | `batch` | `batch --mode` for images or mixed directories (`media: "all"`), with optional `--preset`; `video batch --mode` for video (`media: "video"`); or `audio batch --mode` for audio (`media: "audio"`) | A separate output directory, `_clean` unless `output_dir` is given | | `audio_identify` | `audio identify --json`; `check_invisible: false` skips models | Nothing | -| `audio_invisible` | `audio invisible --json`, with explicit `stream`, `vendor`, `allow_unverified`, `allow_positive`, `allow_quality_override`, `force`, and `verify` options | `.wav`, `.flac`, `.mp3`, `.m4a`, `.ogg`, or `.opus`, `_processed.wav` by default | +| `audio_invisible` | `audio invisible --json`, with explicit `stream`, `vendor`, `allow_unverified`, `allow_positive`, `allow_quality_override`, `force`, and `verify` options | `.wav`, `.flac`, `.mp3`, `.m4a`, `.ogg`, `.oga`, `.opus`, `.aac`, or `.mka`, `_processed.wav` by default | | `video_message_identify` | `video message identify --json`, required `reference`, optional `scheme` | Nothing | | `video_message_remove` | `video message remove --json`, same reference and scheme, profile and verification options | MP4, MOV, or M4V, `_message_processed.mp4` by default | | `video_audio` | `video audio --json`, with the same audio options plus `all_streams` | MKV/MOV with PCM or MP4 with AAC, `_audio_processed.mkv` by default | @@ -81,37 +81,20 @@ or `"combined"`, and integer `bandwidth` (`6`, `12`, or `24`, default `24`) for the optional codec backend. `audio_invisible` requires `audio-detect` for default source-positive and saved-output-negative verification. A `vendor` other than `"auto"` (`google`, `elevenlabs`, `suno`, `udio`, `openai`, `cartesia`, `meta`, `resemble`, `microsoft`) names a known source cohort for stripped files, selects a vendor-matched profile sequence, and implies `allow_unverified`. `allow_unverified: true` (for example with `method: "dac"`, or alongside `verify: false`) permits unverified processing with the `audio` extra while keeping the audio SNR/RMS/window integrity gate active (`force: true` remains an alias enabling `allow_unverified`, `allow_positive`, and `allow_quality_override`). Audio tools require ffmpeg and -ffprobe. `scheme: "audioseal"` (default), `"auto"` (scans installed non-experimental decoders `audioseal`, `wavmark`, `perth` without failing on missing optional extras), `"wavmark"`, `"perth"`, `"silentcipher"`, `"silentcipher16"`, or `"all"` selects -compatible public-model checks. WavMark needs `audio-wavmark`, Perth v1 needs `audio-perth`, and both experimental SilentCipher receivers need +ffprobe. `scheme: "audioseal"` (default), `"auto"` (scans installed non-experimental decoders `audioseal`, `wavmark`, `perth` without failing on missing optional extras), `"wavmark"`, `"perth"`, `"silentcipher"`, or `"all"` selects +compatible public-model checks. WavMark needs `audio-wavmark`, Perth v1 needs `audio-perth`, and SilentCipher-44k needs `audio-silentcipher`; `all` needs every decoder extra. Auto tries spectral then combined for AudioSeal and Perth v1, neural then -combined for WavMark and both experimental SilentCipher receivers, and combined for `all`. Neural profiles need `audio-codec`. -Explicit `method: "bigvgan"` instead needs `audio-vocoder`; `vocoder_device` -accepts `"cpu"` (default), `"mps"`, or `"cuda"`. This experimental full-track -mono/stereo profile is limited to 30 seconds and 16 million sample values. -It is excluded from auto selection; codec bandwidth does not apply. The shared -catalog exposes the same options on CLI-derived MCP, Space and ComfyUI routes. -Local decoder negatives do not certify SynthID. -Explicit `method: "mimi"` instead uses the separate CPU FP32 Mimi backend from -`audio-codec`, with fixed 32 quantizers and the same bounded full-track and -saved-output gates. Explicit `method: "focalcodec"` uses the separate CPU FP32 -FocalCodec continuous WavLM-to-Vocos backend from `audio-codec`, operating on an -internal 16 kHz grid with symmetric `(40, 40)` WavLM boundary context, single-pass -resynthesis up to 30 seconds, raised-cosine overlap-window streaming on longer -audio, and the same saved-output gates. Explicit `method: "dac"` uses the -separate FP32 44.1 kHz 3-codebook DAC backend from `audio-codec` with raw -mid/side stereo, stem RMS preservation, and the same single-pass / overlap-window -streaming path. Keep `vocoder_device: "cpu"` for Mimi and FocalCodec; DAC, -EnCodec, and `combined` also accept `"mps"` or `"cuda"`. Bandwidth applies only -to EnCodec. All three methods are experimental, have no -built-in provider verifier (`mimi` and `focalcodec` are excluded from `auto`; -`dac` is selected by `auto` only when pre-strip metadata identifies ElevenLabs or -Google SynthID, or `vendor` names a cohort), and are exposed by -legacy tools and the shared operation catalog. -`silentcipher16` covers only a terminated eight-symbol pattern. Its -readings label `framing="terminated8"`; `payload_symbols` are seven ternary -symbols, not bytes. Its decoder clock is -16000 regardless of the source rate. The SDK byte API and general 32-bit -profile remain unqualified. `all` requests both SilentCipher receivers. +combined for WavMark and SilentCipher-44k, and combined for `all`. Neural profiles need `audio-codec`. +Explicit `method: "dac"` uses the FP32 44.1 kHz 3-codebook DAC backend from +`audio-codec` (defaulting `preserve_hf_hz=14000.0` on `>= 44.1 kHz` tracks) with +raw mid/side stereo, stem RMS preservation, and single-pass / overlap-window +streaming. Explicit `method: "snac"` uses the 44.1 kHz multi-scale SNAC backend +from `audio-codec`. `vocoder_device` (`"auto"` default, `"cpu"`, `"mps"`, or +`"cuda"`) applies to DAC, SNAC, EnCodec, and `combined`. Bandwidth applies only +to EnCodec. `dac` is selected by `auto` when pre-strip metadata identifies +ElevenLabs or Google SynthID, or `vendor` names a cohort. Neither DAC nor SNAC +provides a built-in provider verifier; both are exposed by legacy tools and the +shared operation catalog. `mode` is `metadata` (the default), `visible` or `all`. For an image, `all` adds the invisible-watermark scrub where the installed extras and a CUDA GPU diff --git a/docs/media-removal-evidence-log.md b/docs/media-removal-evidence-log.md index 8b931cf..c92be26 100644 --- a/docs/media-removal-evidence-log.md +++ b/docs/media-removal-evidence-log.md @@ -274,3 +274,28 @@ In Wave 9 (2026-11-22, `v0.70.0`): stamped directly at 48 kHz without 16 kHz downsampling): before `mean_detect_prob=0.999974` (`frac=1.0`); after `DAC q=3` `0.0140` (`frac=0.0024`), and with `preserve_hf_hz=14000` `0.0139` (`frac=0.0008`, lower `RMS err 0.05277 -> 0.04990`). + +In Wave 11 (2026-11-22, `v0.73.0`): +- **Live Google Gemini SynthID oracle checks (`gemini.google.com/u/1/app`, `2/2` `not_detected`)**: + - `higgsfield-veo-3-1-lite_dac_hf14k_v071.wav` + (`sha256:94215d0981e47778dc38db06aae9c4cbde2627e972fedeea691c15a72cf11f0b`, + `DAC 44.1 kHz` `q=3` + `preserve_hf_hz=14000.0`, `quality_passed=True`): + `"This audio file does not contain a SynthID watermark indicating it was made with Google AI."` + Combined with the prior `synthid.com` check on `google-gemini-omni-flash-api_dac_hf14k.wav`, + `DAC + preserve_hf_hz=14000.0` is now **`2/2` `not_detected`** on live Google SynthID + oracles and promoted to the default for `DAC` on `>= 44.1 kHz` tracks. + - `higgsfield-veo-3-1-lite_2d_synthid_v071_silent.mp4` + (`sha256:2d557ef65283020babe853065675e001344bb610ad1eb4aaa6157f84c6799d62`, + `v0.70.0+` 2D SynthID `temporal_stabilize=True` + CIE Lab low-frequency color anchoring): + `"No SynthID watermark from Google AI was detected in this video, and no valid C2PA Content Credentials were found."` +- **Unified containers and pruned obsolete experimental audio backends**: + - Removed obsolete experimental audio methods (`bigvgan`, `mimi`, `focalcodec`) and + the terminated `silentcipher16` scheme; retained production `spectral`, `encodec`, + `combined`, `dac`, and `snac`. + - Unified all video pipelines (`seedance`, `wan21-synthid`, `wan21-seedance`, `synthid`, + `visible`, `erase`, `video audio`) to accept all seven video containers (`.mp4`, `.mov`, + `.m4v`, `.mkv`, `.webm`, `.avi`, `.flv`), unified all nine audio formats (`.wav`, `.flac`, + `.mp3`, `.m4a`, `.ogg`, `.oga`, `.opus`, `.aac`, `.mka`) on both input and output, and + removed artificial resolution/duration hard caps in `video_wan.py` (keeping explicit + opt-in worker guardrails `max_duration_seconds` / `max_frame_pixels` defaulting to `None`). + diff --git a/docs/module-internals.md b/docs/module-internals.md index 207046f..97a8275 100644 --- a/docs/module-internals.md +++ b/docs/module-internals.md @@ -231,10 +231,7 @@ the delivered candidate, rather than before encoding. ffprobe (falling back to `video_tools.find_video_tool` from `portable-ffmpeg-full` when system `PATH` lacks them, shared with `_internal/audio_creation.py`), closes producers and child processes on failure, -and writes atomic `.wav`, `.flac`, `.mp3` (`libmp3lame` 256 kbps CBR + Xing header), `.m4a` (`aac` 192 kbps + faststart), `.ogg`, or `.opus` (`libopus` 192 kbps; RFC 7845 48 kHz resampled back to `info.sample_rate` during `audio_quality.measure_fidelity`) outputs. BigVGAN, Mimi, and FocalCodec WAV outputs select the deterministic bitexact short-RIFF -writer, omitting encoder tags and RF64 reserve padding. Its size guard runs -before scanning or encoding a large input view. Other methods retain the -default RF64-capable writer; FLAC remains a separate encoding and verdict scope. +and writes atomic `.wav`, `.flac`, `.mp3` (`libmp3lame` 256 kbps CBR + Xing header), `.m4a` (`aac` 192 kbps + faststart), `.ogg`, `.oga`, `.opus` (`libopus` 192 kbps; RFC 7845 48 kHz resampled back to `info.sample_rate` during `audio_quality.measure_fidelity`), `.aac` (`aac` 192 kbps ADTS), or `.mka` (`flac` in Matroska) outputs. WAV outputs default to the RF64-capable writer; FLAC/MKA remain separate encoding and verdict scopes. `_internal/audio_spectral.py` applies the fixed zero-phase SOS profile with neighboring context at streaming boundaries. `_internal/audioseal.py` owns the hash-pinned open-model loader and decoder math; the development @@ -275,86 +272,39 @@ supports `stereo_mode="ms"` Mid/Side resynthesis on 2-channel inputs (used by `a model/resampler padding to retain native frame counts. This implementation is separate from development studies using the original EnCodec package. -`_internal/audio_vocoder.py` implements the separately selected experimental -BigVGAN full-track profile. `_bigvgan_network.py` contains the lazy inference -architecture; upstream license texts and notices ship in `licenses/bigvgan/`. -Configuration and weights are revision/hash pinned, loaded with weights-only -strict state matching. `_internal/audio_resampling.py` preserves the rational -native half-open sample grid across the 44.1 kHz model clock and explicit model -context padding. Stereo uses raw mid/side; mono is independent. Public audio -and selected-video-track processing share this profile, its explicit device, -30-second/sample-value memory bounds, and existing saved-output local decoder -gates. It is excluded from `auto`; no clipping, normalization, chunk seams, -global Torch configuration changes, or device fallback are added. Numerical -parity is distinct from perceptual quality and provider verification. - -`_internal/audio_mimi.py` uses the built-in Transformers Mimi architecture with -revision/hash-checked configuration and safetensors, strict complete loading, -fixed 32 quantizers and disabled inference caches. CPU FP32 mono/stereo passes -remain optional; stereo defaults to raw mid/side. The rational resampler maps -the exact native duration to 24 kHz and back, without external model padding. -The official forward method owns decoder-excess prefix selection and must -return the requested model-grid count. No clipping, normalization or alignment -is added. Its weight attribution is in `licenses/mimi/NOTICE.txt`. Public audio -and selected-video-track routes expose it only as an explicit experimental -method, with the shared full-track bounds and existing saved-output decoder -gates. Local compatibility and numerical parity do not certify SynthID or -general voice fidelity. - -`_internal/audio_focalcodec.py` and `_internal/_focalcodec_network.py` implement -the separately selected experimental FocalCodec continuous feature-to-Vocos -profile (`lucadellalib/focalcodec_50hz@d6d6d9524e52155c85193c2c3b8da1cf8842f019`, -matching upstream `v0.0.1` `cad8bf81d70875f756770449c34909d8b0951642`, -Apache-2.0 text and third-party notices in `licenses/focalcodec/`). Config and -safetensors are revision/hash-checked and strictly loaded across all 355 model -keys without importing unused `knn` conversion dependencies. Inference runs in -CPU FP32 without binary spherical quantization (`toks_to_feats(feats_to_toks(...))` -bypassed in favor of continuous 6-layer WavLM features decoded by FocalDecoder -and Vocos). `_internal/audio_resampling.py` maps the exact native duration to -the 16 kHz model grid and back with explicit symmetric `(40, 40)` WavLM context -samples (`RF=400`, `hop=320`) and raw mid/side stereo; non-multiple frame tails -pad on the right before cropping back to the exact core sample count. -`resynthesize_conditioned` preconditions the 1.0-1.5 kHz band, runs FocalCodec -resynthesis, restores complementary zero-phase Butterworth sub-band 35 Hz -envelopes (`[0.0, 2.5]` gain clamp), and applies a smooth `tanh` soft-knee peak -ceiling (`min(max(source_peak, 0.25), 0.96)` when `source_peak <= 1.0`) so -constructive random-phase sub-band summation cannot push lossy MP3/AAC -reconstruction past the quality gate. The route remains excluded -from `auto` and enforces the saved-output decoder gate unless explicitly forced. - -`_internal/audio_dac.py` implements the separately selected experimental 44.1 kHz +`_internal/audio_dac.py` implements the 44.1 kHz Descript Audio Codec profile (`descript/dac_44khz@c1bc521685adf9cfe247bc39a5ca58917eda1ac4`, MIT weights attributed in `licenses/dac/NOTICE.txt`) using built-in -`transformers.DacModel` in FP32 on the explicit vocoder device (CPU default; -`mps` or `cuda` only when available, never a silent fallback; EnCodec takes the -same device) with SHA-256-verified configuration and -safetensors, fixed `n_quantizers=3`, rational half-open resampling around the -44.1 kHz hop-512 grid, raw mid/side stereo decomposition (skipping silent Side -stems below `1e-5` RMS), stem-level RMS restoration, and `0.999` peak ceiling. +`transformers.DacModel` in FP32 on the selected vocoder device (`auto` resolves +to CUDA/MPS when available, else CPU; EnCodec takes the same device) with +SHA-256-verified configuration and safetensors, fixed `n_quantizers=3`, default +`preserve_hf_hz=14000.0` on `>= 44.1 kHz` tracks, rational half-open resampling +around the 44.1 kHz hop-512 grid, raw mid/side stereo decomposition (skipping +silent Side stems below `1e-5` RMS), stem-level RMS restoration with quiet-stem +gain staging, and `0.999` peak ceiling. It preserves full `22.05 kHz` stereo bandwidth without adding lockfile packages, runs single-pass resynthesis up to 30 seconds and raised-cosine overlap-window -streaming (`_stream_neural_track`, shared with `FocalCodec`) on longer audio, -is selected by `adaptive_auto_profiles` only for a vendor cohort (explicit or from -pre-strip metadata), and enforces the saved-output decoder gate unless -explicitly forced. DAC and EnCodec also accept a tagged 5.1 or 7.1 layout: +streaming (`_stream_neural_track`) on longer audio, +is selected by `adaptive_auto_profiles` for wideband AI vendor cohorts (explicit +or from pre-strip metadata), and enforces the saved-output decoder gate unless +explicitly forced. DAC, SNAC, and EnCodec also accept a tagged 5.1 or 7.1 layout: `_transform_surround_stems` runs the model on FL/FR, the center, and each surround pair as mid/side stems and only low-passes the LFE channel below -120 Hz (`test_surround_5_1_stem_processing_preserves_channels_and_lowpasses_lfe`); -BigVGAN, Mimi and FocalCodec stay mono/stereo. +120 Hz (`test_surround_5_1_stem_processing_preserves_channels_and_lowpasses_lfe`). `_internal/audio_snac.py` and `_internal/_snac_network.py` implement the -separately selected experimental 44.1 kHz Multi-Scale Neural Audio Codec profile +44.1 kHz Multi-Scale Neural Audio Codec profile (`hubertsiuzdak/snac_44khz@873ebef9718b89660340c6f55a2b515e98cfa1d9`, MIT weights and adaptation notices in `licenses/snac/`) via a pure-PyTorch lazy builder with SHA-256-verified configuration and 286-key checkpoint (`weights_only=True`), post-load weight-norm fusion, fixed `n_quantizers=3` (`vq_strides` `8, 4, 2`, dropping the finest `stride=1` residual codebook where `Perth` survives), rational half-open resampling around the 44.1 kHz hop-3072 grid, raw mid/side stereo and -`5.1`/`7.1` surround stem routing, and overlap-window streaming on `cpu`, `mps`, -or `cuda`. +`5.1`/`7.1` surround stem routing, and overlap-window streaming on `auto`, `cpu`, +`mps`, or `cuda`. The default `auto` sequence is fixed by requested scheme: spectral then combined -for AudioSeal and Perth v1, neural then combined for WavMark and both experimental SilentCipher receivers, combined for all. Inspection +for AudioSeal and Perth v1, neural then combined for WavMark and SilentCipher-44k, combined for all. Inspection of the source is reused across candidates. Failed intermediate candidates are discarded before trying the next profile; only a verified candidate or an explicitly forced final candidate can be published. Missing fallback dependencies @@ -385,20 +335,6 @@ decoder clock independently of source geometry, including for 16 kHz sources. This route excludes the 16 kHz model, whose SDK byte framing is incompatible; see [the artifact analysis](audio-video-removal.md#experimental-silentcipher-44k-receiver). -`_internal/silentcipher16.py` is the separate `silentcipher16` receiver for a terminated -eight-symbol candidate, with seven ternary payload symbols rather than bytes. -It pins the released 16 kHz artifacts, uses four decoder classes and a 512-bin -message band, and shares safe checkpoint loading with the 44.1 kHz receiver. -The network factory preserves the 44.1 kHz defaults while accepting the 16 kHz -shape and FFT settings. The candidate requires a single terminator, three -complete repetitions, agreement at least 0.9, and all 103 phase-grid positions -for a negative. Silent inputs and invalid model values remain unverified; -only device failures can retry CPU. `audio.py`, the CLI, and MCP select it -explicitly or through `all`, using the same `audio-silentcipher` extra. Reports -record a 16 kHz decoder clock independently of native source geometry. -Its auto-processing order is neural then combined, with the existing saved-file -and final-mux gates. SDK byte framing and the general 32-bit profile remain unqualified. - `_internal/audio_quality.py` shares saved-file fidelity, model-free `audio_quality_passed` gating (method-aware SNR, clipping-delta, global silent-drop, 1-second active-window `worst_window_rms_ratio` in `[0.005, 4.0]`, and stereo @@ -808,20 +744,23 @@ lists are read only for an actual repair; source and duration-only probes read stream fields. The engine checks the saved output clock and decoded frame count before atomic publication, and measures PSNR/flow-aligned temporal residual at delivered geometry. Encoded guides and masters are task-owned temporary files, with bounded pixel batches. -The profile accepts SDR 8-bit MP4 with even dimensions and handles visible -labels as a separate input-preparation concern. +The profile accepts SDR 8-bit and 10-bit HEVC/HDR video across all 7 containers +(`.mp4`, `.mov`, `.m4v`, `.mkv`, `.webm`, `.avi`, `.flv`) with even dimensions +and handles visible labels as a separate input-preparation concern. [`video_wan.py`](../src/remove_ai_watermarks/video_wan.py) packages the optional -3D causal video diffusion profiles (`wan21-synthid-experimental` at -`strength=0.38` and `wan21-seedance-experimental` at `strength=0.12` on BF16 NVIDIA CUDA and explicit Apple Silicon `mps`), exposed -through `remove_video_wan_experimental` and the shared `profile` / -`invisible_profile` selectors (`VideoWanExperimentalResult`, which carries -explicit `strength` alongside the compatible `noise_std` mirror). It verifies -hardware BF16 NVIDIA CUDA capability (`torch.version.hip` excluded, -`torch.cuda.is_bf16_supported(including_emulation=False)`) or explicit `mps` availability and enforces -`WAN21_MAX_FRAME_PIXELS` (`3840 * 2160`, using 1080p-guided high-frequency texture restoration above `WAN21_NATIVE_MAX_PIXELS = 1920 * 1080`) and `WAN21_MAX_TOTAL_PIXEL_FRAMES` -(`7200 * 1920 * 1080`, 5 minutes at 1080p24) before frame decoding, loads pinned -Apache-2.0 `Wan-AI/Wan2.1-T2V-1.3B-Diffusers@0fad780a534b6463e45facd96134c9f345acfa5b` +3D causal video diffusion profiles (`wan21-synthid` at `strength=0.38` and +`wan21-seedance` at `strength=0.12`, with legacy `*-experimental` aliases, on +BF16 NVIDIA CUDA and explicit Apple Silicon `mps`), exposed through +`remove_video_wan` (alias `remove_video_wan_experimental`) and the shared +`profile` / `invisible_profile` selectors (`VideoWanExperimentalResult`, which +carries explicit `strength` alongside the compatible `noise_std` mirror). It +verifies hardware BF16 NVIDIA CUDA capability (`torch.version.hip` excluded, +`torch.cuda.is_bf16_supported(including_emulation=False)`) or explicit `mps` +availability, uses 1080p-guided high-frequency texture restoration above +`WAN21_NATIVE_MAX_PIXELS = 1920 * 1080` with no hard frame-area or duration cap, +loads pinned Apache-2.0 +`Wan-AI/Wan2.1-T2V-1.3B-Diffusers@0fad780a534b6463e45facd96134c9f345acfa5b` (`licenses/wan/NOTICE.txt`) with an FP32 tiled/sliced `AutoencoderKLWan`, BF16/FP16 `WanVideoToVideoPipeline`, and `UniPCMultistepScheduler(flow_shift=3.0, 20 steps, guidance_scale=1.0)`, pre-encodes `WAN21_DEFAULT_PROMPT` on CPU into cached @@ -833,14 +772,12 @@ raised-cosine temporal crossfades with symmetric 16-pixel reflection padding and the static neutral prompt embedding on disk via `_wan_prompt_cache_path` so `UMT5-XXL` is not downloaded or loaded on warm cache hits) without buffering the full decoded video in host RAM. `WAN_SUPPORTED_EXTENSIONS` -covers `.mp4`, `.mov`, and `.m4v`. `video.py` also exposes -`profile="auto"`, routing eligible ByteDance/Seedance MP4, MOV, and M4V clips (`WAN21_AUTO_MAX_FRAME_PIXELS = 3840 * 2160` -and `WAN21_MIN_CUDA_VRAM_BYTES = 8 GiB`, stepping down to `WAN21_MPS_CHUNK_FRAMES = 33` / `WAN21_MPS_OVERLAP_FRAMES = 9` on `mps` or `WAN21_COMPACT_CHUNK_FRAMES = 81` on `1080p` or `< 16 GiB` CUDA, and passing float32 tensors directly for 10-bit/16-bit sources) to `wan21-seedance-experimental` on BF16 CUDA -(`seedance-experimental` fallback on CPU/MPS MP4, which streams SD-VAE guides in memory without an intermediate lossy `guide.mp4`, applies guide-resolution `iter_stabilized_regenerated_frames` plus ultra-low-frequency `anchor_low_freq_color` in CIE Lab before sigma-1 texture restoration, or `synthid` on MOV/M4V/MKV/WebM or when the auto Wan budget is -exceeded) and other eligible SDR 8-bit MP4, MOV, and M4V clips to `wan21-synthid-experimental` on BF16 CUDA -(`synthid` fallback otherwise, with `temporal_stabilize=True` and `anchor_low_freq_color` enabled by default). The invisible stage of `remove_video_all` -accepts `_REGENERATED_VIDEO_EXTENSIONS` (MP4, MOV, M4V, `.mkv`, and `.webm`); MKV and WebM -sources never qualify for Wan, so `auto` resolves them to `synthid`. Coverage in +and `_REGENERATED_VIDEO_EXTENSIONS` both cover all 7 video containers (`.mp4`, +`.mov`, `.m4v`, `.mkv`, `.webm`, `.avi`, `.flv`). `video.py` also exposes +`profile="auto"`, routing eligible ByteDance/Seedance clips +(`WAN21_MIN_CUDA_VRAM_BYTES = 8 GiB`, stepping down to `WAN21_MPS_CHUNK_FRAMES = 33` / `WAN21_MPS_OVERLAP_FRAMES = 9` on `mps` or `WAN21_COMPACT_CHUNK_FRAMES = 81` on `1080p` or `< 16 GiB` CUDA, and passing float32 tensors directly for 10-bit/16-bit sources) to `wan21-seedance` on BF16 CUDA +(`seedance` fallback on CPU/MPS, which streams SD-VAE guides in memory without an intermediate lossy `guide.mp4`, applies guide-resolution `iter_stabilized_regenerated_frames` plus ultra-low-frequency `anchor_low_freq_color` in CIE Lab before sigma-1 texture restoration) and other eligible clips to `wan21-synthid` on BF16 CUDA +(`synthid` fallback otherwise, with `temporal_stabilize=True` and `anchor_low_freq_color` enabled by default). Coverage in `tests/test_video_seedance.py` includes source-detail separation, quantization, VFR/nonzero-start/audio-tail preservation, and failure-before-publication. diff --git a/docs/python-api.md b/docs/python-api.md index a6ecdec..4065ad8 100644 --- a/docs/python-api.md +++ b/docs/python-api.md @@ -554,7 +554,7 @@ multichannel inputs also get a mono-downmix check. For validated 24 and 48 kHz sources, AudioSeal checks both 16 kHz and the original sample clock, with `AudioDetection.decoder_sample_rate` identifying each receiver. This field is also set for the native OpenVoice default-signature receiver and is 44100 for -`scheme="silentcipher"` and 16000 for `scheme="silentcipher16"`, regardless +`scheme="silentcipher"`, regardless of the source rate; it is `None` for standard synchronized WavMark and Perth. Other AudioSeal native clocks are outside calibrated coverage @@ -564,9 +564,8 @@ including AudioSeal windows. Status is `detected`, `not_detected`, or `unverified`, scoped to the pinned open model. Missing explicitly requested decoders, failed checks, and bounded whole-clip checks never become negatives. Pass `scheme="auto"` to scan every *installed* non-experimental compatible public decoder (`audioseal`, `wavmark`, `perth`) without failing when an optional decoder extra is absent or a clip is shorter than WavMark's 1-second minimum window, `scheme="wavmark"` for the pinned public WavMark model, `scheme="perth"` for public Perth v1, `scheme="silentcipher"` for the experimental -SilentCipher-44k receiver, `scheme="silentcipher16"` for the experimental -terminated eight-symbol 16k pattern, or `scheme="all"` -for all named packaged decoders (including both experimental SilentCipher receivers). The default on `identify_audio` and `remove_audio_invisible` is `"audioseal"`; `remove_audio_all` and `remove_audio_batch` default to `scheme="auto"`. WavMark also +SilentCipher-44k receiver, or `scheme="all"` +for all named packaged decoders (including the experimental SilentCipher-44k receiver). The default on `identify_audio` and `remove_audio_invisible` is `"audioseal"`; `remove_audio_all` and `remove_audio_batch` default to `scheme="auto"`. WavMark also checks the published OpenVoice default message at fixed native offsets. Those readings have `framing="openvoice-default"`, fragment matches, and adjusted binomial-tail diagnostics; they do not identify a provider or cover custom @@ -575,30 +574,19 @@ models keep a combined result unverified. WavMark windows include valid endpoints and exactly one second; a shorter source stays unverified. Its readings hold recovered payload bits and start offsets at the model sample rate. SilentCipher-44k reads native-rate input through its own resampler and checks -three-second windows. A 16 kHz source still uses the 44.1 kHz model; the -incompatible published 16 kHz model is outside this check. Its reading includes the accepted five-byte payload, symbol +three-second windows. A 16 kHz source still uses the 44.1 kHz model. Its reading includes the accepted five-byte payload, symbol consistency, phase offset, phase count, and actual device. The project receiver requires consistency at least 0.9 and checks all phases before a negative. A source shorter than three seconds stays unverified. Symbol consistency is agreement, not watermark probability; on a negative it includes invalid framing hypotheses and can still be high. -`silentcipher16` reports `SilentCipher16Reading.payload_symbols`, a tuple of -seven ternary symbols rather than bytes, with `framing="terminated8"`. -This receiver pins the released 16 kHz -model but qualifies only the terminated eight-symbol pattern, with three-second -windows, at least three repetitions, agreement at least 0.9, and all 103 phase-grid -positions before a negative. It resamples inputs to 16 kHz internally. Source -rate, channels, and frame bounds remain independent of this decoder clock. -The incompatible SDK byte API, general 32-bit profile, and deployed-provider -compatibility remain unqualified. `all` requests both SilentCipher receivers. - `remove_audio_invisible(source, output, force=False, verify=True, stream=0)` selects an adaptive minimal-distortion processing sequence. By default it skips without a compatible positive source signal and publishes only a fully checked negative saved output. `AudioVerificationIncomplete` exposes `before` and `after` on rejection and preserves an existing output. `force=True` permits unverified or still-positive -results. `verify=False` requires `force=True`, `allow_unverified=True`, or an explicit `vendor`. Outputs accept `.wav`, `.flac`, `.mp3` (`libmp3lame` 256 kbps CBR with Xing header), `.m4a` (`aac` 192 kbps with faststart), `.ogg`, and `.opus` (`libopus` 192 kbps); AI metadata is +results. `verify=False` requires `force=True`, `allow_unverified=True`, or an explicit `vendor`. Outputs accept `.wav`, `.flac`, `.mp3` (`libmp3lame` 256 kbps CBR with Xing header), `.m4a` (`aac` 192 kbps with faststart), `.ogg`, `.oga`, `.opus` (`libopus` 192 kbps), `.aac` (`aac` 192 kbps ADTS), and `.mka` (`flac` in Matroska); AI metadata is discarded. The source must stay unchanged during processing. `inspect_audio_metadata(source)` returns `AudioMetadataReport`, and `remove_audio_metadata(source, output=None, *, keep_standard=True)` strips AI creation tags and C2PA manifests without re-encoding audio frames (`AudioMetadataResult`). `remove_audio_all(source, output=None, *, include_invisible=False, scheme="auto", method="auto", ...)` returns `AudioAllResult`, always writing a metadata-cleaned output (`_clean` by default) and optionally cleaning compatible waveform watermarks when `include_invisible=True`. `remove_audio_batch(input_dir, output_dir=None, *, mode="all", include_invisible=False, ...)` runs sequentially over a directory and returns `AudioBatchSummary` of `AudioBatchItem` rows. @@ -625,47 +613,11 @@ the applied profile. Neural resynthesis can alter speech timbre and music; it retains the same strict saved-file verification policy, and 2-channel EnCodec passes operate in Mid/Side (`M/S`) space to preserve stereo phantom-center coherence. Auto tries spectral then combined for AudioSeal and Perth v1, neural then combined for WavMark and both experimental SilentCipher receivers, routes ElevenLabs and Google SynthID metadata-identified mono, stereo, or tagged 5.1/7.1 audio to `dac` (falling back to `encodec`/`combined` when `dac` is absent) instead of `spectral`, and adapts to positively detected schemes under `scheme="auto"` or `"all"` before falling back to `combined`. A missing required neural fallback raises without publishing output. -Both functions also accept explicit `method="bigvgan"` with the `audio-vocoder` -extra and `vocoder_device="cpu"`, `"mps"`, or `"cuda"`. This experimental pinned -full-track mel-vocoder accepts mono/stereo tracks up to 30 seconds and 16 million -sample values. It retains the native rational sample grid and uses raw mid/side -for stereo, without normalization, extra clipping, chunking, or device fallback. -A non-CPU `vocoder_device` also applies to `dac`, `encodec`, `combined`, and -`auto`; it is rejected with `spectral`, `mimi`, or `focalcodec`. EnCodec bandwidth does not apply. `auto` does not -select BigVGAN. Local source/saved-output decoder gates remain mandatory unless -explicitly forced; they cannot certify SynthID or transfer a provider verdict -from another file. CUDA and short-signal perceptual quality remain unqualified. -BigVGAN WAV outputs use bitexact short-RIFF serialization without an encoder tag -or RF64 reserve padding. This enables reproducible file hashes for unchanged -PCM and encoding, not a built-in provider verifier. FLAC and CPU/MPS differences -remain separate exact-file scopes. - -Explicit `method="mimi"` uses the `audio-codec` extra and fixed CPU FP32 default -32-quantizer Mimi. It shares the full-track duration/sample-value bounds and -known mono/stereo layout checks, uses raw mid/side for stereo, and preserves the -native half-open sample grid around an internal 24 kHz codec. The model owns -its right-end excess and documented input-length prefix selection; no external -padding, alignment or normalization is added. Its WAV serialization is bitexact. -EnCodec bandwidth is ignored and `vocoder_device` must remain `"cpu"`. `auto` -does not select it. Results still cover only the requested local decoders, -with quality measured separately; native-provider candidates are not certified. - -Explicit `method="focalcodec"` uses the `audio-codec` extra and fixed CPU FP32 -continuous 6-layer WavLM feature-to-Vocos resynthesis (`lucadellalib/focalcodec_50hz` -at revision `d6d6d9524e52155c85193c2c3b8da1cf8842f019`, bypassing binary -spherical quantization). It shares the full-track duration/sample-value bounds, -known mono/stereo layout checks, raw mid/side stereo, exact rational resampling -around an internal 16 kHz grid (`8 kHz` ceiling) with symmetric `(40, 40)` -WavLM context, smooth source-activity pause conditioning (`resynthesize_conditioned`, -`-42 dBFS` active speech / `-50 dBFS` quiet intervals), and bitexact WAV -serialization. EnCodec bandwidth is ignored, `vocoder_device` must remain `"cpu"`, -and `auto` never selects it. Saved-output local decoder checks remain mandatory -unless explicitly forced; native-provider candidates remain unverified. - Explicit `method="dac"` uses the `audio-codec` extra and fixed FP32 3-codebook 44.1 kHz Descript Audio Codec (`descript/dac_44khz` at revision `c1bc521685adf9cfe247bc39a5ca58917eda1ac4`, MIT weights) on `vocoder_device` -(`"cpu"`, `"mps"`, or `"cuda"`). It supports mono, raw mid/side stereo with stem +(`"auto"`, `"cpu"`, `"mps"`, or `"cuda"`), defaulting `preserve_hf_hz=14000.0` +on `>= 44.1 kHz` tracks. It supports mono, raw mid/side stereo with stem RMS preservation, and tagged `5.1` / `7.1` surround stem decomposition (`FL/FR` M/S, `FC` mono, `<120 Hz` Butterworth LFE, surround M/S pairs), rational half-open resampling around 44.1 kHz (preserving full 22.05 kHz bandwidth), and @@ -944,25 +896,25 @@ SynthID remains the default. On hosts with a hardware BF16-capable NVIDIA CUDA GPU (Ampere or newer; ROCm and emulated BF16 are excluded), or with explicit `device="mps"` on Apple Silicon -(FP16 transformer; `profile="auto"` never selects MPS), `remove_video_wan_experimental` -(and `profile="auto"`, `"wan21-synthid-experimental"`, or -`"wan21-seedance-experimental"` in `remove_video_invisible`, `remove_video_all`, -and `remove_video_batch`) runs pinned Apache-2.0 3D `Wan 2.1` +(FP16 transformer; `profile="auto"` never selects MPS), `remove_video_wan` +(legacy alias `remove_video_wan_experimental`, and `profile="auto"`, +`"wan21-synthid"`, or `"wan21-seedance"` in `remove_video_invisible`, +`remove_video_all`, and `remove_video_batch`) runs pinned Apache-2.0 3D `Wan 2.1` (`Wan-AI/Wan2.1-T2V-1.3B-Diffusers` at `0fad780a534b6463e45facd96134c9f345acfa5b`) -at native resolution and exact frame timestamps on SDR 8-bit MP4, MOV, and M4V clips within -`WAN21_MAX_FRAME_PIXELS` (`3840 * 2160`, using 1080p-guided texture restoration -above `1920 * 1080`) and `WAN21_MAX_TOTAL_PIXEL_FRAMES` -(`7200 * 1920 * 1080`, streaming clips exceeding `chunk_frames=193` across -`overlap_frames=17` raised-cosine 3D causal windows directly to the encoder and -pre-encoding `prompt_embeds` once so the T5 text encoder is freed before 3D -denoising), returning -`VideoWanExperimentalResult` (which exposes `strength` alongside the compatible -`noise_std` mirror). `profile="auto"` selects `wan21-seedance-experimental` on -eligible BF16 CUDA MP4, MOV, and M4V sources (`<= 1920x1080` frame area and `>= 8 GiB` total VRAM, stepping down to 81-frame chunks on 1080p or `< 16 GiB` CUDA and skipping `UMT5-XXL` when the static prompt embedding is cached locally; -`seedance-experimental` fallback on CPU/MPS MP4, or `synthid` on MOV/M4V/MKV/WebM or when the auto Wan budget is -exceeded) when ByteDance/Seedance metadata or visible marks are present, and -`wan21-synthid-experimental` (`synthid` fallback) otherwise. `wan21-synthid-experimental` uses `strength=0.38` -and `wan21-seedance-experimental` uses `strength=0.12`. Both accept +at native resolution and exact frame timestamps on SDR 8-bit and 10-bit HDR +clips across all 7 supported containers (`.mp4`, `.mov`, `.m4v`, `.mkv`, +`.webm`, `.avi`, `.flv`), using 1080p-guided texture restoration above +`1920 * 1080` and streaming clips exceeding `chunk_frames=193` across +`overlap_frames=17` raised-cosine 3D causal windows directly to the encoder +(pre-encoding `prompt_embeds` once so the T5 text encoder is freed before 3D +denoising), returning `VideoWanExperimentalResult` (which exposes `strength` +alongside the compatible `noise_std` mirror). `profile="auto"` selects +`wan21-seedance` on eligible BF16 CUDA sources (`>= 8 GiB` total VRAM, stepping +down to 81-frame chunks on 1080p or `< 16 GiB` CUDA and skipping `UMT5-XXL` when +the static prompt embedding is cached locally; `seedance` fallback on CPU/MPS) +when ByteDance/Seedance metadata or visible marks are present, and +`wan21-synthid` (`synthid` fallback) otherwise. `wan21-synthid` uses `strength=0.38` +and `wan21-seedance` uses `strength=0.12`. Both accept `quality="delivery"` or `"master"` and `seed`, reuse one loaded pipeline across batch items, and perform no runtime oracle verification. `VideoAllResult` also records `audio_verification_scope` and `audio_quality_passed` when diff --git a/docs/supported-signals.md b/docs/supported-signals.md index 83b17ed..7940ec9 100644 --- a/docs/supported-signals.md +++ b/docs/supported-signals.md @@ -222,16 +222,12 @@ fixed native offsets, alongside its synchronized public-model scan. This signature does not cover custom messages or shifted/resampled framing, and its binomial-tail diagnostic is not a calibrated false-positive probability. They provide -streaming spectral, neural-codec, and combined processing, plus explicit -experimental full-track BigVGAN, Mimi, and FocalCodec profiles. Mimi uses fixed -CPU FP32 and an internal 24 kHz grid; FocalCodec uses fixed CPU FP32 continuous -6-layer WavLM-to-Vocos resynthesis on an internal 16 kHz grid (`8 kHz` ceiling); -BigVGAN has an explicit device selector. All three use -bounded mono/stereo processing, preserve the native sample grid and expose -quality limitations separately. The 44.1 kHz DAC codec profile also handles -tagged 5.1/7.1 surround and is what `auto` selects when pre-strip metadata or an -explicit audio vendor names ElevenLabs, Google SynthID, or another wideband AI -audio cohort. None implements a SynthID decoder. +streaming spectral, neural-codec (EnCodec, 44.1 kHz DAC with default +`preserve_hf_hz=14000.0` on `>= 44.1 kHz` tracks, and 44.1 kHz SNAC), and +combined processing. The 44.1 kHz DAC codec profile handles mono, raw mid/side +stereo, and tagged 5.1/7.1 surround and is what `auto` selects when pre-strip +metadata or an explicit audio vendor names ElevenLabs, Google SynthID, or +another wideband AI audio cohort. None implements a SynthID decoder. Default removal requires a source-positive and saved-output-negative check; resistant and incomplete candidates are rejected. This does not establish compatibility with proprietary @@ -244,14 +240,6 @@ identify Chatterbox. This does not certify proprietary PerTh v2. SilentCipher-44 `audio-silentcipher`, with three-second windows and a project-defined repeated-symbol threshold. Neither its negative nor loss of a fixed message certifies complete erasure. Reports identify its 44.1 kHz decoder clock separately from the source rate. -The published 16 kHz model has incompatible SDK byte framing and is outside -this receiver, including when the input itself is 16 kHz. -The separate `--scheme silentcipher16` route checks an experimental terminated -eight-symbol pattern with the pinned 16 kHz model and the same `audio-silentcipher` -extra. It labels readings `framing="terminated8"` and reports seven ternary -`payload_symbols`, not bytes, and a 16 kHz decoder -clock. `all` includes both receivers. The SDK byte API and general 32-bit profile -remain unqualified; a negative does not rule out other framing or deployed marks. Negative results cover the requested decoder checks; they do not certify erasure of every residual payload bit. See [audio coverage and local results](audio-video-removal.md). @@ -376,7 +364,7 @@ and `chroma-zimage` at `0.50`: `0/18` detected) and already cleared `6/6` on resolution-adaptive `qwen-zimage` default (`0.090-0.099`) provides a 3x safety margin with no separate vendor strength floor needed. -For MP4, MOV, and M4V, `video invisible` or the explicit +For `.mp4`, `.mov`, `.m4v`, `.mkv`, `.webm`, `.avi`, and `.flv`, `video invisible` or the explicit `video all --invisible` option can regenerate the video through a VAE and strip source metadata. The shipped profile is oracle-certified for SynthID, but it is not a local decoder. A fresh source-positive, output-negative pair from Gemini's built-in diff --git a/pyproject.toml b/pyproject.toml index 9f9bf85..423716f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,8 +4,8 @@ # 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.72.0" -description = "AI watermark remover for visible, invisible, and provenance marks in images and video" +version = "0.73.0" +description = "AI watermark remover for visible, invisible, and provenance marks in images, video, audio, and text" readme = "README.md" requires-python = ">=3.11,<3.15" license = {text = "Apache-2.0"} @@ -147,13 +147,6 @@ audio-codec = [ "safetensors", "huggingface-hub>=0.20.0,<2", ] -# Optional pinned full-track mel-vocoder, independent of watermark decoders. -audio-vocoder = [ - "remove-ai-watermarks[audio]", - "torch>=2.6", - "librosa>=0.10", - "huggingface-hub>=0.20.0,<2", -] # Open DWT-DCT watermarks used by Stable Diffusion / SDXL / FLUX. The in-tree # decoder avoids the upstream invisible-watermark package's mandatory torch and # non-headless OpenCV dependencies. @@ -286,7 +279,7 @@ dev = [ ] # ``qwen-zimage`` already pulls ``diffusion``; naming both would suggest diffusion is # independently sufficient for a removal, which it is not. -all = ["remove-ai-watermarks[video,video-detect,heif,detect,trustmark,text-restoration,migan,source-classify,audio-detect,audio-codec,audio-vocoder,audio-wavmark,audio-perth,audio-silentcipher,text,text-mlx]"] +all = ["remove-ai-watermarks[video,video-detect,heif,detect,trustmark,text-restoration,migan,source-classify,audio-detect,audio-codec,audio-wavmark,audio-perth,audio-silentcipher,text,text-mlx]"] [project.scripts] remove-ai-watermarks = "remove_ai_watermarks.cli:main" diff --git a/scripts/media_removal_benchmark.py b/scripts/media_removal_benchmark.py index d6379b2..73322bc 100644 --- a/scripts/media_removal_benchmark.py +++ b/scripts/media_removal_benchmark.py @@ -241,7 +241,7 @@ def build_builtin_suite(work_dir: Path, *, strict: bool = False) -> Path: import numpy as np import soundfile as sf - from remove_ai_watermarks._internal import audio_dac, audio_focalcodec, audio_snac, audioseal, perth, wavmark + from remove_ai_watermarks._internal import audio_dac, audio_snac, audioseal, perth, wavmark from remove_ai_watermarks.video_decode import open_video_capture from remove_ai_watermarks.video_encoding import ( finish_raw_video_encoder, @@ -483,7 +483,7 @@ def build_builtin_suite(work_dir: Path, *, strict: bool = False) -> Path: sf.write(wm_stereo_p, np.column_stack((wm_marked, wm_marked_r)), 16000, subtype="FLOAT") add_row("wavmark-stereo-ms-marked", "audio_invisible", "wavmark", wm_stereo_p, ".wav", "verified_removed") - # 3. Perth 16 kHz (both auto and conditioned focalcodec when cached) + # 3. Perth 16 kHz (both auto and DAC when cached) if perth.available(): p_model = perth.load_model() p_clean = _synthetic_speechlike_carrier(16000, 3.0, seed=301) @@ -494,27 +494,6 @@ def build_builtin_suite(work_dir: Path, *, strict: bool = False) -> Path: sf.write(p_marked_p, p_marked, 16000, subtype="FLOAT") add_row("perth-clean", "audio_invisible", "perth", p_clean_p, ".wav", "skipped_clean") add_row("perth-marked-auto", "audio_invisible", "perth", p_marked_p, ".wav", "verified_removed") - if audio_focalcodec.is_available(): - try: - from huggingface_hub import hf_hub_download - - hf_hub_download( - repo_id=audio_focalcodec.MODEL_REPOSITORY, - filename=audio_focalcodec.CHECKPOINT_FILENAME, - revision=audio_focalcodec.MODEL_REVISION, - local_files_only=True, - ) - add_row( - "perth-marked-focalcodec", - "audio_invisible", - "perth", - p_marked_p, - ".wav", - "verified_removed", - method="focalcodec", - ) - except Exception: - log.info("Skipping optional focalcodec builtin case because weights are not cached locally") if audio_dac.is_available(): try: from huggingface_hub import hf_hub_download diff --git a/server.json b/server.json index ea4d350..efdfd7d 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, audio, and text.", - "version": "0.72.0", + "version": "0.73.0", "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.72.0", + "version": "0.73.0", "runtimeHint": "uvx", "transport": { "type": "stdio" diff --git a/skills/remove-ai-watermarks/SKILL.md b/skills/remove-ai-watermarks/SKILL.md index 4799f8d..58c2e62 100644 --- a/skills/remove-ai-watermarks/SKILL.md +++ b/skills/remove-ai-watermarks/SKILL.md @@ -137,10 +137,10 @@ Default: inspect first. | Known visible AI label on video | `video visible` or `video all` | `video_visible=needs_video_extra`, `needs_ffmpeg`, or `unverified` | | Invisible image / image SynthID | `invisible` | `invisible_images=unavailable_no_cuda` | | Owned Seedance video | `all ` or `video all --invisible` (default `--profile auto` routes ByteDance/Seedance 8-bit SDR and 10-bit HEVC/HDR clips automatically to `wan21-seedance` on BF16 NVIDIA CUDA or `seedance` on CPU/MPS MP4) | `video,diffusion` required; `wan21-*` also requires CUDA | -| Video SynthID | `all `, `video invisible`, or `video all --invisible` (default `--profile auto` selects `wan21-synthid` on BF16 NVIDIA CUDA for eligible `<= 1920x1080` MP4/MOV/M4V clips with `>= 8 GiB` VRAM, or 2D `synthid` fallback otherwise; Google SynthID audio tracks auto-route to `dac` when metadata identifies Google) | `video_invisible=needs_video_and_diffusion_extras`, `needs_ffmpeg`, or `unverified` | +| Video SynthID | `all `, `video invisible`, or `video all --invisible` (default `--profile auto` selects `wan21-synthid` on BF16 NVIDIA CUDA for eligible `.mp4`/`.mov`/`.m4v`/`.mkv`/`.webm`/`.avi`/`.flv` clips, or 2D `synthid` fallback otherwise; Google SynthID audio tracks auto-route to `dac` when metadata identifies Google) | `video_invisible=needs_video_and_diffusion_extras`, `needs_ffmpeg`, or `unverified` | | Public VideoSeal, PixelSeal, or ChunkySeal with an independent encoder message | `video message identify` then `video message remove` (`video message detect` for a blind public-model presence check) | requires `video-detect`, plus `diffusion` for VAE; no AI-origin verdict | | Inspect audio | `audio identify` | use `--no-invisible` for metadata-only inspection; ffmpeg and ffprobe are required | -| Compatible public AudioSeal, WavMark, Perth v1, or experimental SilentCipher audio patterns | `audio invisible` or `audio all --invisible` (`--scheme auto`, `audioseal`, `wavmark`, `perth`, `silentcipher`, or `silentcipher16`) | install `audio-detect`, `audio-wavmark`, `audio-perth`, or `audio-silentcipher` for verification; `audio_stack` only checks the CPU processor | +| Compatible public AudioSeal, WavMark, Perth v1, or experimental SilentCipher audio patterns | `audio invisible` or `audio all --invisible` (`--scheme auto`, `audioseal`, `wavmark`, `perth`, `silentcipher`, or `all`) | install `audio-detect`, `audio-wavmark`, `audio-perth`, or `audio-silentcipher` for verification; `audio_stack` only checks the CPU processor | | Everything on an audio file | `audio all` (add `--invisible` for compatible waveform watermarks) | needs ffmpeg and ffprobe; add decoder extras for `--invisible` | | Text token watermark / full text clean | `text invisible` or `text all` | `text invisible` and `text all --invisible` need `text` for Transformers (`diffusion` remains compatible), or `text-mlx` with an explicit Apple silicon MLX checkpoint; see the Text section of `references/commands.md` | | Everything on an image | `all` | `image_all=do_not_run_writes_nothing` | @@ -161,7 +161,7 @@ Audio defaults require a compatible source positive and a fully negative saved output. Inspect first. `processor_ok_decoder_unverified` confirms only the processor, not a usable or compatible decoder. Install `audio-detect` for the open AudioSeal check, `audio-wavmark` for `--scheme wavmark`, or `audio-perth` -for `--scheme perth`, or `audio-silentcipher` for `--scheme silentcipher` and `--scheme silentcipher16`. `--scheme all` +for `--scheme perth`, or `audio-silentcipher` for `--scheme silentcipher`. `--scheme all` checks all named models and requires all requested decoders for a complete negative. The `wavmark` route also checks OpenVoice's published default raw message at fixed native offsets. JSON labels it `framing="openvoice-default"`; custom @@ -173,36 +173,19 @@ Other voices, forks, and hosted PerTh v2 need separate qualification; a PerTh response alone does not attribute a file to Chatterbox. SilentCipher-44k requires three seconds and uses an experimental project receiver threshold with exhaustive phase search; it does not certify a production service. -Its `decoder_sample_rate` is 44100 regardless of input rate. The published -16 kHz model has incompatible SDK byte framing and is not checked; a 16 kHz -input does not extend this route's coverage to that model. -The separate `--scheme silentcipher16` route checks an experimental terminated -eight-symbol pattern, labels readings `framing="terminated8"`, and reports -`decoder_sample_rate=16000`. Its seven ternary -`payload_symbols` are not bytes. The SDK byte API and general 32-bit profile -remain unqualified. `all` includes both receivers. Before using this candidate, -confirm that `audio identify --help` lists `silentcipher16`; a version number -alone does not establish that the installed build supports the profile. +Its `decoder_sample_rate` is 44100 regardless of input rate. An unverified report never means clean. Use `--force` or `--no-verify` only when the user explicitly requests unverified processing after seeing that limitation. The fixed spectral filter changes audible content and can fail. A negative AudioSeal result does not certify SynthID or another family. Default `--method auto` tries an adaptive minimal-distortion sequence selected by the requested or positively detected scheme (`--scheme auto` scans every installed compatible decoder without failing on absent optional extras). -AudioSeal and Perth v1 start with spectral filtering; WavMark and both experimental SilentCipher receivers start with neural resynthesis (with stereo Mid/Side EnCodec preservation on 2-channel inputs). Outputs support `.wav`, `.flac`, `.mp3`, `.m4a`, `.ogg`, and `.opus` with saved-file verification. -Explicit `--method bigvgan` is a separate experimental full-track mono/stereo -profile requiring `audio-vocoder`; `--vocoder-device` chooses CPU, MPS, or CUDA. -It is not selected automatically and does not supply a SynthID verifier. -Explicit `--method mimi` uses the separate experimental CPU FP32 Mimi codec -with fixed 32 quantizers and the `audio-codec` extra. Explicit -`--method focalcodec` uses the separate experimental CPU FP32 FocalCodec 50 Hz -conditioned continuous-feature profile (`audio-codec` extra, Apache-2.0 weights). -Explicit `--method dac` uses the separate experimental FP32 44.1 kHz DAC -3-codebook codec (`audio-codec` extra, MIT weights; CPU by default, `mps` or -`cuda` via `--vocoder-device`). All three share the raw mid/side route and -saved-output gates (`mimi` and `focalcodec` are excluded from `auto`; `dac` is -selected by `auto` only when pre-strip metadata identifies ElevenLabs or Google -SynthID, or `--vendor` names a cohort), and none checks SynthID. Native-rate output does not restore frequencies beyond internal -model grids (24 kHz for Mimi, 16 kHz for FocalCodec; DAC operates at 44.1 kHz). +AudioSeal and Perth v1 start with spectral filtering; WavMark and SilentCipher start with neural resynthesis (with stereo Mid/Side EnCodec preservation on 2-channel inputs). Outputs support `.wav`, `.flac`, `.mp3`, `.m4a`, `.ogg`, `.oga`, `.opus`, `.aac`, and `.mka` with saved-file verification. +Explicit `--method dac` uses the FP32 44.1 kHz DAC 3-codebook codec (`audio-codec` +extra, MIT weights; auto-accelerated on CUDA/MPS, or controlled via +`--vocoder-device`) with default `preserve_hf_hz=14000.0` on `>= 44.1 kHz` tracks. +Explicit `--method snac` uses the 44.1 kHz multi-scale SNAC codec (`audio-codec` +extra). `auto` routes ElevenLabs and Google SynthID metadata to `dac` (or when +`--vendor` names a cohort); neither supplies a local SynthID verifier. Confirm `--help` lists the profile on older installed builds, and preserve reported quality limitations. The fallback combines both. EnCodec profiles need `audio-codec`; a missing diff --git a/skills/remove-ai-watermarks/references/commands.md b/skills/remove-ai-watermarks/references/commands.md index 706add2..43dbee0 100644 --- a/skills/remove-ai-watermarks/references/commands.md +++ b/skills/remove-ai-watermarks/references/commands.md @@ -166,46 +166,40 @@ that order and co-selects spatially disjoint vendor-compatible marks (such as `j a trailing static AI outro card, and `--track` on `erase` or `video erase` to track moving user-specified `--region` boxes across frames. -`video invisible` and `video all --invisible` accept MP4, MOV, M4V, MKV, and WebM. +`video invisible` and `video all --invisible` accept MP4, MOV, M4V, MKV, WebM, AVI, and FLV. That is the default SynthID profile. It is lossy; its shipped noise profile -is pinned, so do not lower it. Motion-compensated `--temporal-stabilize` is enabled by default (`--no-temporal-stabilize` disables it), and `--keep-fps` preserves the native source frame rate instead of resampling to 12 fps. On `video all` and `video batch`, `--audio-invisible` (`--audio-scheme`, `--audio-method`, `--audio-stream`, `--audio-allow-unverified`, `--audio-allow-positive`, `--audio-allow-quality-override`, or alias `--audio-force`) inspects and cleans compatible watermarked audio tracks in the same pipeline (since CLI 0.63.0). For proprietary audio marks with no local public decoder (such as short Veo/Gemini SynthID or ElevenLabs audio), pass `--audio-allow-unverified` (`--audio-invisible --audio-method dac --audio-allow-unverified`, or `--audio-method auto` when ElevenLabs/Google SynthID C2PA metadata is present), which processes unverified audio while keeping the SNR/RMS/window integrity gate active (`--audio-force` also enables `--audio-allow-positive` and `--audio-allow-quality-override`; `--audio-method auto` without vendor metadata or a positive public decoder runs `spectral` only, and `focalcodec` failed on a held-out 10 s Gemini audio track). +is pinned, so do not lower it. Motion-compensated `--temporal-stabilize` is enabled by default (`--no-temporal-stabilize` disables it), and `--keep-fps` preserves the native source frame rate instead of resampling to 12 fps. On `video all` and `video batch`, `--audio-invisible` (`--audio-scheme`, `--audio-method`, `--audio-stream`, `--audio-allow-unverified`, `--audio-allow-positive`, `--audio-allow-quality-override`, or alias `--audio-force`) inspects and cleans compatible watermarked audio tracks in the same pipeline (since CLI 0.63.0). For proprietary audio marks with no local public decoder (such as short Veo/Gemini SynthID or ElevenLabs audio), pass `--audio-allow-unverified` (`--audio-invisible --audio-method dac --audio-allow-unverified`, or `--audio-method auto` when ElevenLabs/Google SynthID C2PA metadata is present), which processes unverified audio while keeping the SNR/RMS/window integrity gate active (`--audio-force` also enables `--audio-allow-positive` and `--audio-allow-quality-override`; `--audio-method auto` without vendor metadata or a positive public decoder runs `spectral` only). -For an owned Seedance MP4, explicitly opt into the experimental fixed recipe -(since CLI 0.56.0): +For an owned Seedance video, `--profile auto` routes ByteDance/Seedance clips automatically, or opt in explicitly with `--profile seedance` (legacy alias `seedance-experimental`): ```bash -remove-ai-watermarks video all input.mp4 -o clean.mp4 --invisible --profile seedance-experimental -remove-ai-watermarks video invisible label-cleaned.mp4 -o clean.mp4 --profile seedance-experimental -remove-ai-watermarks video batch ./videos --invisible --profile seedance-experimental +remove-ai-watermarks video all input.mp4 -o clean.mp4 --invisible --profile seedance +remove-ai-watermarks video invisible label-cleaned.mp4 -o clean.mp4 --profile seedance +remove-ai-watermarks video batch ./videos --invisible --profile seedance ``` -Seedance requires SDR 8-bit MP4 with even dimensions. `--quality delivery` -(default) writes H.264 High CRF18; `--quality master` retains a larger +Seedance accepts SDR 8-bit and 10-bit HEVC/HDR across all 7 containers (`.mp4`, `.mov`, `.m4v`, `.mkv`, `.webm`, `.avi`, `.flv`) with even dimensions. `--quality delivery` +(default) writes H.264/H.265 CRF18; `--quality master` retains a larger lossless-coded master. Leave SynthID tuning flags at their defaults; nondefault values are rejected for this fixed recipe. All/batch requires `--invisible` with this profile. Only all mode runs the supported visible stage first; -unhandled visible overlays need separate preparation. The experiment has +unhandled visible overlays need separate preparation. The profile has matched-control CapCut evidence but performs no per-file detector request. -These profile options require a build containing the experimental Seedance -integration; verify `video all --help` before using them. On machines with a hardware BF16-capable NVIDIA CUDA GPU (Ampere or newer; ROCm -and pre-Ampere emulation are excluded), two additional -experimental 3D video diffusion profiles preserve native resolution and frame -rate on SDR 8-bit MP4, MOV, and M4V clips within the conservative decoded-frame budget -(`<= 1920x1080` frame area and `<= 552,960,000` decoded pixel-frames, streaming -clips over 193 frames via overlapping 3D causal windows, since CLI 0.63.0), and -`--profile auto` (the default on `video all`, `video batch`, `video invisible`, -and `clean`) automatically routes eligible ByteDance/Seedance MP4, MOV, and M4V clips -(`<= 1920x1080` frame area and `>= 8 GiB` total GPU VRAM, stepping down from 193-frame to 81-frame chunks on 1080p or `< 16 GiB` CUDA) to -`wan21-seedance-experimental` on BF16 CUDA (`seedance-experimental` fallback on -CPU/MPS MP4, or `synthid` on MOV/M4V/MKV/WebM or over budget) and other eligible SDR 8-bit MP4, MOV, and M4V clips to `wan21-synthid-experimental` +and pre-Ampere emulation are excluded) or explicit Apple Silicon `--device mps`, two +3D video diffusion profiles (`wan21-synthid` and `wan21-seedance`; legacy aliases `wan21-synthid-experimental`, `wan21-seedance-experimental`) preserve native resolution and frame +rate on SDR 8-bit and 10-bit HDR clips across all 7 containers (using 1080p-guided high-frequency texture restoration above `1920x1080` and streaming +clips over 193 frames via overlapping 3D causal windows), and +`--profile auto` (the default on `all`, `video all`, `video batch`, and `video invisible`) automatically routes eligible ByteDance/Seedance clips +(`>= 8 GiB` total GPU VRAM on BF16 CUDA, stepping down from 193-frame to 81-frame chunks on 1080p or `< 16 GiB` CUDA) to +`wan21-seedance` on BF16 CUDA (`seedance` fallback on CPU/MPS) and other eligible clips to `wan21-synthid` on BF16 CUDA (`synthid` fallback otherwise): ```bash remove-ai-watermarks video all input.mp4 -o clean.mp4 --invisible --profile auto -remove-ai-watermarks video all input.mp4 -o clean.mp4 --invisible --profile wan21-synthid-experimental -remove-ai-watermarks video all input.mp4 -o clean.mp4 --invisible --profile wan21-seedance-experimental +remove-ai-watermarks video all input.mp4 -o clean.mp4 --invisible --profile wan21-synthid +remove-ai-watermarks video all input.mp4 -o clean.mp4 --invisible --profile wan21-seedance ``` Both `wan21-*` profiles use pinned Apache-2.0 `Wan-AI/Wan2.1-T2V-1.3B-Diffusers` @@ -237,72 +231,35 @@ remove-ai-watermarks audio batch ./tracks -o ./tracks_clean --mode all --invisib `audio identify` and `audio invisible` accept `--stream N`, a zero-based audio-track ordinal (`audio identify` also emits `recommended_recipe` when AI metadata or a compatible watermark signal is found). `audio metadata` checks (`--check`) or strips (`--remove`) AI metadata via stream-copy remuxing (`--keep-standard/--remove-all`, `-o`). `audio all` strips AI metadata and, with `--invisible`, removes compatible waveform watermarks (`--scheme auto` default, writing a metadata-cleaned passthrough when no positive compatible watermark is detected). `audio batch` runs `--mode [all|metadata]` across a directory (`-o` / `--output-dir`). Inspection without models needs ffmpeg and ffprobe. `--scheme audioseal` (default on `identify`/`invisible`) needs -`audio-detect`; `--scheme auto` scans every installed compatible decoder without failing on absent optional extras; `--scheme wavmark` needs `audio-wavmark`; `--scheme perth` needs `audio-perth`; `--scheme silentcipher` and `--scheme silentcipher16` need `audio-silentcipher`; `--scheme all` checks +`audio-detect`; `--scheme auto` scans every installed compatible decoder without failing on absent optional extras; `--scheme wavmark` needs `audio-wavmark`; `--scheme perth` needs `audio-perth`; `--scheme silentcipher` needs `audio-silentcipher`; `--scheme all` checks all named models and needs all named decoder extras. WavMark also checks the published OpenVoice default raw framing at native samples 0 and 32000. JSON labels it `framing="openvoice-default"` with its native `decoder_sample_rate`. -`silentcipher` reports `decoder_sample_rate=44100` regardless of input rate; -the 16 kHz model is outside that route. The separate `silentcipher16` route -checks only an experimental terminated eight-symbol pattern, with -`decoder_sample_rate=16000`, `framing="terminated8"`, and seven ternary -`payload_symbols`, not bytes. -The SDK byte API and general 32-bit profile remain unqualified. `all` includes -both receivers; missing requested checks keep the combined result unverified. +`silentcipher` reports `decoder_sample_rate=44100` regardless of input rate. For OpenVoice, custom messages and shifted/resampled framing remain outside the receiver; its binomial-tail diagnostic is not a calibrated false-positive probability. For validated 24 and 48 kHz sources, AudioSeal checks the resampled 16 kHz and native sample clocks independently; other native clocks are not added automatically. JSON `decoder_sample_rate` identifies each AudioSeal receiver; a verified negative requires both clocks to be negative. Removal requires a compatible source positive and a fully negative saved output. No positive source exits 2 without writing. -Rejected verification exits 1 and preserves an existing output. `.wav`, `.flac`, `.mp3`, `.m4a`, `.ogg`, and `.opus` +Rejected verification exits 1 and preserves an existing output. `.wav`, `.flac`, `.mp3`, `.m4a`, `.ogg`, `.oga`, `.opus`, `.aac`, and `.mka` outputs preserve channels and sample clock (Opus codes internally at 48 kHz and resamples back during fidelity checks), with AI metadata discarded and saved-file decoder verification enforced after encoding. The spectral profile changes audible content and can fail. `--method auto` (default) tries spectral filtering then combined filtering and -neural resynthesis for AudioSeal and Perth v1, neural then combined for WavMark and both experimental SilentCipher receivers (using Mid/Side stereo on 2-channel EnCodec passes), routes mono, stereo, or tagged 5.1/7.1 audio carrying ElevenLabs metadata to `dac` (or `encodec`/`combined` when `dac` is absent) and Google SynthID metadata exclusively to `dac`/`combined` (failing closed rather than falling back to `encodec` when `dac` is absent or the layout is unsupported) instead of `spectral`, and adapts to positively detected schemes under `--scheme auto` or `all` before falling back to `combined`. Each candidate must pass the saved-output gate before publication. -`--method spectral`, `encodec`, or `combined` fixes one profile. Neural profiles +neural resynthesis for AudioSeal and Perth v1, neural then combined for WavMark and SilentCipher (using Mid/Side stereo on 2-channel EnCodec passes), routes mono, stereo, or tagged 5.1/7.1 audio carrying ElevenLabs metadata to `dac` (or `encodec`/`combined` when `dac` is absent) and Google SynthID metadata exclusively to `dac`/`combined` (failing closed rather than falling back to `encodec` when `dac` is absent or the layout is unsupported) instead of `spectral`, and adapts to positively detected schemes under `--scheme auto` or `all` before falling back to `combined`. Each candidate must pass the saved-output gate before publication. +`--method spectral`, `encodec`, `combined`, `dac`, or `snac` fixes one profile. Neural profiles need `audio-codec`; a missing required fallback fails without replacing output. -`--bandwidth` accepts `6`, `12`, or `24` kbps, default `24`, for neural profiles. +`--bandwidth` accepts `6`, `12`, or `24` kbps, default `24`, for EnCodec profiles. Keep the requested decoder extras for verification. Neural processing changes speech timbre or music and can retain a watermark. Whole-clip and window checks must both pass; a negative whole-clip result alone is insufficient. These options also apply to `video audio` and its MCP tool. -`--method bigvgan` selects a separate experimental pinned full-track mel-vocoder -and requires `audio-vocoder`. It accepts mono/stereo, at most 30 seconds and -16 million sample values, with raw mid/side stereo and exact native sample counts. -`--vocoder-device cpu` (default), `mps`, or `cuda` explicitly selects inference; -non-CPU values require this method. No chunking or automatic fallback is used. -EnCodec bandwidth does not apply. `auto` never selects this method. Keep the -requested compatible decoder extras and verification gates. They do not check -Google SynthID; external provider observations remain file-hash scoped. - -`--method mimi` selects a separate experimental Mimi codec, fixed at its default -32 quantizers on CPU FP32 with the `audio-codec` extra. It shares the mono/stereo -full-track bounds, raw mid/side processing, bitexact WAV encoding and native -half-open sample grid. The internal codec rate is 24 kHz; output at a higher -native rate does not restore its missing bandwidth. Keep `--vocoder-device cpu`; -EnCodec bandwidth does not apply. Auto selection excludes this method. Apply -the same requested decoder checks and report quality separately. Local Perth -success does not verify a native-provider watermark, words, or voice on new files. - -`--method focalcodec` selects a separate experimental 50 Hz FocalCodec -continuous-feature profile (`WavLM` 6-layer encoder to `Vocos` ISTFT decoder) on -CPU FP32 with the `audio-codec` extra. It runs single-pass resynthesis up to -30 seconds and raised-cosine overlap-window streaming on longer mono/stereo -audio (`> 30 s`), preserving raw mid/side stereo, bitexact WAV encoding, and a -rational half-open native clock (`16 kHz` internal grid, `8 kHz` Nyquist ceiling), with -smooth source-activity conditioning (`resynthesize_conditioned`) that preserves -quiet pause intervals where unconditioned Vocos phase randomization could -cross-react with magnitude-domain Perth windows. Keep `--vocoder-device cpu`; -EnCodec bandwidth does not apply, and `auto` excludes this method. Default -verification still requires a clean saved-output check before publication and -reports `quality_passed`. - `--method dac` selects the 44.1 kHz Descript Audio Codec profile (`descript/dac_44khz`, MIT weights) fixed at 3 codebooks on FP32 with the `audio-codec` extra (since CLI 0.63.0). It runs single-pass resynthesis up to 30 seconds and raised-cosine overlap-window streaming on longer audio (`> 30 s`), supporting mono, raw mid/side stereo, and tagged `5.1`/`7.1` surround stem decomposition with `<120 Hz` LFE filtering while preserving full 22.05 kHz -bandwidth. `--vocoder-device` accepts `cpu` (default), `mps`, or `cuda`; EnCodec +bandwidth (defaulting `preserve_hf_hz=14000.0` on `>= 44.1 kHz` tracks). `--vocoder-device` accepts `auto` (default), `cpu`, `mps`, or `cuda`; EnCodec bandwidth does not apply, and `auto` selects `dac` when pre-strip metadata or an explicit `--vendor` cohort identifies a wideband AI audio generator. @@ -311,7 +268,7 @@ explicit `--vendor` cohort identifies a wideband AI audio generator. (strides 8, 4, 2) on FP32 with the `audio-codec` extra. Like `dac`, it runs single-pass resynthesis up to 30 seconds and overlap-window streaming on longer audio (`> 30 s`), supporting mono, raw mid/side stereo, and tagged `5.1`/`7.1` -surround stems on `--vocoder-device [cpu|mps|cuda]`; `auto` excludes `snac`. +surround stems on `--vocoder-device [auto|cpu|mps|cuda]`; `auto` excludes `snac`. `--allow-unverified` permits processing without a local source-positive decoder match (or with `--no-verify`) while keeping the audio SNR/RMS/window integrity gate active (`--allow-positive` permits a still-positive final candidate; `--allow-quality-override` overrides the integrity gate; `--force` enables all three). `--method spectral --allow-unverified --no-verify` only needs the `audio` extra. Other @@ -362,8 +319,8 @@ Emoji `U+200D` ZWJ sequences. Without `-o`, `text` commands write tags, and Markdown headings verbatim and regenerate unlocked prose spans with an unwatermarked local causal LM (default Transformers backend, `text` extra; `diffusion` remains compatible). -Since CLI 0.63.0, both regeneration commands accept `--rewriter-model` and -`--rewriter-backend transformers|mlx`. For local Apple silicon MLX checkpoints, +Since CLI 0.63.0, both regeneration commands accept `--rewriter-model`, +`--rewriter-backend transformers|mlx|ollama`, `--ollama-url`, and `--strict-residual`. For local Apple silicon MLX checkpoints, install `text-mlx` and pass `--rewriter-backend mlx --rewriter-model /path/to/checkpoint`. `text all` requires `--invisible` with these options. The MLX backend uses the same acceptance guards diff --git a/skills/remove-ai-watermarks/references/install.md b/skills/remove-ai-watermarks/references/install.md index 176ed40..5641ee2 100644 --- a/skills/remove-ai-watermarks/references/install.md +++ b/skills/remove-ai-watermarks/references/install.md @@ -84,22 +84,18 @@ ffmpeg is missing, or the user asked about Homebrew, pipx, or pip. | Text regeneration with an explicit MLX checkpoint on Apple silicon | `text-mlx` | | Image identify, `visible`, `erase` | `visible` | | HEIC / HEIF / AVIF pixels | add `heif` | -| Public known-message VideoSeal/PixelSeal | `video-detect`, plus `diffusion` for VAE, ffmpeg and ffprobe | +| Public known-message VideoSeal/PixelSeal/ChunkySeal | `video-detect`, plus `diffusion` for VAE, ffmpeg and ffprobe | | Audio metadata inspection (`--no-invisible`) | no extra, plus ffmpeg and ffprobe | | CPU audio processing without verification | `audio`, plus ffmpeg and ffprobe | -| Neural audio resynthesis (`--method encodec`, `combined`, or an automatic neural profile) | add `audio-codec`; retain the decoder extra for verification | -| Experimental Mimi codec (`--method mimi`) | add `audio-codec`; fixed CPU FP32 and 32 quantizers; retain the decoder extra; model weights CC-BY-4.0 | -| Experimental FocalCodec continuous features (`--method focalcodec`) | add `audio-codec`; fixed CPU FP32 50 Hz WavLM-to-Vocos profile; retain the decoder extra; model weights Apache-2.0 | -| Experimental 44.1 kHz DAC codec (`--method dac`) | add `audio-codec`; FP32 with 3 codebooks, CPU by default, MPS or CUDA through the vocoder device option; retain the decoder extra; model weights MIT | -| Experimental full-track mel-vocoder (`--method bigvgan`) | add `audio-vocoder`; retain the decoder extra for verification; mono/stereo up to 30 seconds | +| Neural audio resynthesis (`--method encodec`, `combined`, `dac`, `snac`, or an automatic neural profile) | add `audio-codec`; auto-accelerated on CUDA/MPS; retain the decoder extra for verification | | Compatible open AudioSeal checks and verified audio processing | `audio-detect`, plus ffmpeg and ffprobe | -| Experimental SilentCipher-44k (`--scheme silentcipher`) and terminated 16k pattern (`--scheme silentcipher16`) | `audio-silentcipher`, plus ffmpeg and ffprobe; minimum three seconds, complete documented phase grid; neural removal also needs `audio-codec` | +| Experimental SilentCipher-44k (`--scheme silentcipher`) | `audio-silentcipher`, plus ffmpeg and ffprobe; minimum three seconds, complete documented phase grid; neural removal also needs `audio-codec` | | Public Perth v1 checks (`--scheme perth`) | `audio-perth`, plus ffmpeg and ffprobe | | Public WavMark checks (`--scheme wavmark`) | `audio-wavmark`, plus ffmpeg and ffprobe; neural removal also needs `audio-codec` | | Audio-only processing inside video (`video audio`) | Same audio extras, no `video` extra | | Video identify / visible / all / batch | `video` (includes FFmpeg and ffprobe) | -| Experimental Seedance video (`--profile seedance-experimental`) | `video,diffusion` (includes FFmpeg and ffprobe) | -| Experimental CUDA Wan 2.1 video (`--profile wan21-synthid-experimental`, `--profile wan21-seedance-experimental`) | `video,diffusion`, plus NVIDIA CUDA (Apache-2.0 weights) | +| Seedance video (`--profile seedance`) | `video,diffusion` (includes FFmpeg and ffprobe) | +| 3D Wan 2.1 video (`--profile wan21-synthid`, `--profile wan21-seedance`) | `video,diffusion`, plus NVIDIA CUDA or explicit Apple Silicon MPS (Apache-2.0 weights) | | Video SynthID (`video invisible`) | `video,diffusion` (includes FFmpeg and ffprobe) | | Invisible images | `qwen-zimage`, plus NVIDIA CUDA | | Learned image/video fill | add `migan` or `lama` | diff --git a/skills/remove-ai-watermarks/scripts/probe.py b/skills/remove-ai-watermarks/scripts/probe.py index 103f290..0448d7d 100644 --- a/skills/remove-ai-watermarks/scripts/probe.py +++ b/skills/remove-ai-watermarks/scripts/probe.py @@ -29,14 +29,16 @@ _GPU_MARKERS = ("GPU ", "gpu:") # 0.64.0 adds `video erase`, `video message detect`, the chunkyseal scheme, and # audio --vendor/--audio-vendor cohorts; # 0.63.0 added audio commands, text --allow-partial/--rewriter-backend/--rewriter-model -# (text-mlx), video message, --profile auto/wan21-*, and --method dac/focalcodec; +# (text-mlx), video message, --profile auto/wan21-*, and --method dac/snac; # 0.48.0 added `classify-source`; 0.39.0 added the `liblib_pill` mark and `auto` # routing OpenAI provenance to qwen-zimage (`--pipeline auto` 0.36.0; # chroma-zimage and the doubao video mark 0.35.0; the `microsoft` mark 0.34.0; # `--vendor` 0.32.0), and a stale floor told an agent its CLI was current right -# before it typed a value that build rejects. tests/test_agent_skill.py pins it +# 0.73.0 unified all 7 video containers and 9 audio output formats, pruned +# obsolete experimental audio backends, and promoted non-experimental video +# profile names across skill references. tests/test_agent_skill.py pins it # against the package version and against every "(since CLI X.Y.Z)" annotation. -MIN_CLI_VERSION = (0, 68, 0) +MIN_CLI_VERSION = (0, 73, 0) # Markers a build without the pixel stack prints. The first is the current CLI's own # install hint; the rest are what older builds emit before the guard existed, and the # legacy Homebrew installs can still contain such a build. diff --git a/src/remove_ai_watermarks/__init__.py b/src/remove_ai_watermarks/__init__.py index 0660e61..4c72c73 100644 --- a/src/remove_ai_watermarks/__init__.py +++ b/src/remove_ai_watermarks/__init__.py @@ -13,8 +13,8 @@ High-level API (lazy, so ``import remove_ai_watermarks`` stays cheap):: raiw.remove_video_batch("videos", "videos_clean") # complete per-file results raiw.remove_video_metadata("in.mp4", "out.mp4") # verified metadata strip raiw.remove_video_invisible("in.mp4", "out.mp4") # calibrated video-pixel regeneration - raiw.remove_video_seedance_experimental("in.mp4", "out.mp4") # opt-in Seedance experiment - raiw.remove_video_wan_experimental("in.mp4", "out.mp4") # opt-in CUDA 3D Wan 2.1 experiment + raiw.remove_video_seedance("in.mp4", "out.mp4") # Seedance video regeneration + raiw.remove_video_wan("in.mp4", "out.mp4") # 3D Wan 2.1 video regeneration (CUDA/MPS) raiw.remove_video_visible("in.mp4", "out.mp4") # stable visible video-mark removal raiw.identify_audio("in.wav", scheme="auto") # -> AudioProvenanceReport raiw.inspect_audio_metadata("in.mp3") # -> AudioMetadataReport @@ -46,7 +46,7 @@ _os.environ.setdefault("TRANSFORMERS_VERBOSITY", "error") _warnings.filterwarnings("ignore", message=r".*ImageProcessorFast.*") -__version__ = "0.72.0" +__version__ = "0.73.0" __all__ = [ "AudioAllResult", diff --git a/src/remove_ai_watermarks/_internal/_bigvgan_network.py b/src/remove_ai_watermarks/_internal/_bigvgan_network.py deleted file mode 100644 index 75d8436..0000000 --- a/src/remove_ai_watermarks/_internal/_bigvgan_network.py +++ /dev/null @@ -1,204 +0,0 @@ -"""Lazy inference-only adaptation of NVIDIA BigVGAN at 7d2b454564a6c7d014227f635b7423881f14bdac. - -Copyright (c) 2024 NVIDIA CORPORATION, MIT. SnakeBeta derives from Edward -Dixon's MIT implementation. Alias-free activation derives from alias-free-torch -(Apache-2.0), including Alexandre Defossez's MIT Julius filter design. -Exact license texts and modification/source notices: licenses/bigvgan/. - -Modified for this package: lazy imports/builders, only AMPBlock1/SnakeBeta and -pure Torch inference, no training initialization, plotting, CUDA extension or -Hub mixin. Parameter/buffer names and inference mathematics are preserved. -The model's own final clamp is retained; callers must not add output clipping. -""" - -from __future__ import annotations - -import math -from importlib import import_module -from typing import Any - - -def build_generator(config: dict[str, Any]) -> Any: - """Build the checkpoint-compatible inference network without loading files.""" - torch = import_module("torch") - nn = torch.nn - functional = torch.nn.functional - weight_norm = torch.nn.utils.weight_norm - remove_weight_norm = torch.nn.utils.remove_weight_norm - if config["resblock"] != "1" or config["activation"] != "snakebeta" or not config["snake_logscale"]: - raise ValueError("Only the pinned AMPBlock1/SnakeBeta log-scale architecture is supported") - - # Apache-2.0 alias-free-torch, with the MIT Julius low-pass filter design. - def kaiser_filter(cutoff: float, half_width: float, kernel_size: int) -> Any: - half_size = kernel_size // 2 - attenuation = 2.285 * (half_size - 1) * math.pi * (4 * half_width) + 7.95 - if attenuation > 50: - beta = 0.1102 * (attenuation - 8.7) - elif attenuation >= 21: - beta = 0.5842 * (attenuation - 21) ** 0.4 + 0.07886 * (attenuation - 21) - else: - beta = 0.0 - window = torch.kaiser_window(kernel_size, beta=beta, periodic=False) - time = torch.arange(-half_size, half_size) + 0.5 - kernel = 2 * cutoff * window * torch.sinc(2 * cutoff * time) - kernel /= kernel.sum() - return kernel.view(1, 1, kernel_size) - - class LowPassFilter1d(nn.Module): - def __init__(self) -> None: - nn.Module.__init__(self) - self.register_buffer("filter", kaiser_filter(0.25, 0.3, 12)) - - def forward(self, x: Any) -> Any: - channels = x.shape[1] - x = functional.pad(x, (5, 6), mode="replicate") - return functional.conv1d(x, self.filter.expand(channels, -1, -1), stride=2, groups=channels) - - class UpSample1d(nn.Module): - def __init__(self) -> None: - nn.Module.__init__(self) - self.register_buffer("filter", kaiser_filter(0.25, 0.3, 12)) - - def forward(self, x: Any) -> Any: - channels = x.shape[1] - x = functional.pad(x, (5, 5), mode="replicate") - x = 2 * functional.conv_transpose1d(x, self.filter.expand(channels, -1, -1), stride=2, groups=channels) - return x[..., 15:-15] - - class DownSample1d(nn.Module): - def __init__(self) -> None: - nn.Module.__init__(self) - self.lowpass = LowPassFilter1d() - - def forward(self, x: Any) -> Any: - return self.lowpass(x) - - # MIT Edward Dixon / NVIDIA SnakeBeta, fixed log-scale parameterization. - class SnakeBeta(nn.Module): - def __init__(self, channels: int) -> None: - nn.Module.__init__(self) - self.alpha = nn.Parameter(torch.zeros(channels)) - self.beta = nn.Parameter(torch.zeros(channels)) - - def forward(self, x: Any) -> Any: - alpha = torch.exp(self.alpha.unsqueeze(0).unsqueeze(-1)) - beta = torch.exp(self.beta.unsqueeze(0).unsqueeze(-1)) - return x + (1.0 / (beta + 1e-9)) * torch.pow(torch.sin(x * alpha), 2) - - # Apache-2.0 alias-free-torch composition. - class Activation1d(nn.Module): - def __init__(self, channels: int) -> None: - nn.Module.__init__(self) - self.act = SnakeBeta(channels) - self.upsample = UpSample1d() - self.downsample = DownSample1d() - - def forward(self, x: Any) -> Any: - return self.downsample(self.act(self.upsample(x))) - - # NVIDIA MIT AMPBlock1 and generator. - class AMPBlock1(nn.Module): - def __init__(self, channels: int, kernel: int, dilation: list[int]) -> None: - nn.Module.__init__(self) - self.convs1 = nn.ModuleList( - [ - weight_norm(nn.Conv1d(channels, channels, kernel, 1, dilation=d, padding=(kernel * d - d) // 2)) - for d in dilation - ] - ) - self.convs2 = nn.ModuleList( - [ - weight_norm(nn.Conv1d(channels, channels, kernel, 1, dilation=1, padding=(kernel - 1) // 2)) - for _ in dilation - ] - ) - self.activations = nn.ModuleList([Activation1d(channels) for _ in range(2 * len(dilation))]) - - def forward(self, x: Any) -> Any: - for c1, c2, a1, a2 in zip( - self.convs1, self.convs2, self.activations[::2], self.activations[1::2], strict=True - ): - x = c2(a2(c1(a1(x)))) + x - return x - - def remove_weight_norm(self) -> None: - for layer in [*self.convs1, *self.convs2]: - remove_weight_norm(layer) - - class BigVGAN(nn.Module): - def __init__(self) -> None: - nn.Module.__init__(self) - initial = config["upsample_initial_channel"] - self.num_kernels = len(config["resblock_kernel_sizes"]) - self.conv_pre = weight_norm(nn.Conv1d(config["num_mels"], initial, 7, 1, padding=3)) - self.ups = nn.ModuleList() - self.resblocks = nn.ModuleList() - for index, (rate, kernel) in enumerate( - zip(config["upsample_rates"], config["upsample_kernel_sizes"], strict=True) - ): - channels = initial // (2 ** (index + 1)) - self.ups.append( - nn.ModuleList( - [ - weight_norm( - nn.ConvTranspose1d( - initial // (2**index), channels, kernel, rate, padding=(kernel - rate) // 2 - ) - ) - ] - ) - ) - for res_kernel, dilation in zip( - config["resblock_kernel_sizes"], config["resblock_dilation_sizes"], strict=True - ): - self.resblocks.append(AMPBlock1(channels, res_kernel, dilation)) - channels = initial // (2 ** len(config["upsample_rates"])) - self.activation_post = Activation1d(channels) - self.conv_post = weight_norm(nn.Conv1d(channels, 1, 7, 1, padding=3, bias=config["use_bias_at_final"])) - - def forward(self, x: Any) -> Any: - x = self.conv_pre(x) - for index, upsamplers in enumerate(self.ups): - for upsampler in upsamplers: - x = upsampler(x) - combined = self.resblocks[index * self.num_kernels](x) - for offset in range(1, self.num_kernels): - combined += self.resblocks[index * self.num_kernels + offset](x) - x = combined / self.num_kernels - x = self.conv_post(self.activation_post(x)) - return torch.tanh(x) if config["use_tanh_at_final"] else torch.clamp(x, min=-1.0, max=1.0) - - def remove_weight_norm(self) -> None: - for upsamplers in self.ups: - for layer in upsamplers: - remove_weight_norm(layer) - for block in self.resblocks: - block.remove_weight_norm() - remove_weight_norm(self.conv_pre) - remove_weight_norm(self.conv_post) - - return BigVGAN() - - -def mel_spectrogram(samples: Any) -> Any: - """Pinned NVIDIA mel frontend, evaluated in FP32 on CPU like qualification.""" - torch = import_module("torch") - librosa = import_module("librosa") - y = torch.as_tensor(samples, dtype=torch.float32, device="cpu").unsqueeze(0) - basis = torch.from_numpy(librosa.filters.mel(sr=44100, n_fft=2048, n_mels=128, fmin=0, fmax=None)).float() - window = torch.hann_window(2048, dtype=torch.float32, device="cpu") - y = torch.nn.functional.pad(y.unsqueeze(1), (768, 768), mode="reflect").squeeze(1) - spec = torch.stft( - y, - 2048, - hop_length=512, - win_length=2048, - window=window, - center=False, - pad_mode="reflect", - normalized=False, - onesided=True, - return_complex=True, - ) - magnitude = torch.sqrt(torch.view_as_real(spec).pow(2).sum(-1) + 1e-9) - return torch.log(torch.clamp(torch.matmul(basis, magnitude), min=1e-5)) diff --git a/src/remove_ai_watermarks/_internal/_focalcodec_network.py b/src/remove_ai_watermarks/_internal/_focalcodec_network.py deleted file mode 100644 index 7b376ef..0000000 --- a/src/remove_ai_watermarks/_internal/_focalcodec_network.py +++ /dev/null @@ -1,558 +0,0 @@ -"""Lazy inference-only adaptation of FocalCodec v0.0.1 (cad8bf81d70875f756770449c34909d8b0951642). - -Copyright 2025 Luca Della Libera, Apache-2.0. Submodules derive from Hugging Face -Transformers (Apache-2.0), Microsoft WavLM and FocalNet (MIT), Charactr Vocos -(MIT), and Phil Wang's lookup-free quantization (MIT). Exact license texts and -modification notices ship in licenses/focalcodec/. - -Modified for this package: lazy Torch imports/builders, strict 355-key state -verification across all five checkpoint submodules without weight remapping or -remote code execution, and continuous WavLM-to-Vocos feature resynthesis. JIT -exports, Hub download helpers, demo/test harnesses, and the unused kNN matcher -(bshall/knn-vc) are omitted. -""" - -from __future__ import annotations - -import math -from importlib import import_module -from typing import Any - - -def build_focalcodec(config: dict[str, Any]) -> Any: - """Instantiate the pinned v0.0.1 FocalCodec architecture without loading files.""" - torch: Any = import_module("torch") - nn: Any = torch.nn - functional: Any = torch.nn.functional - - expected_names = { - "encoder_name": "WavLM", - "compressor_name": "FocalEncoder", - "quantizer_name": "BinarySphericalQuantizer", - "decompressor_name": "FocalDecoder", - "decoder_name": "Vocos", - } - if any(config.get(key) != value for key, value in expected_names.items()): - raise ValueError("Only the pinned WavLM/FocalNet/BSQ/Vocos FocalCodec architecture is supported") - - class Fp32LayerNorm(nn.LayerNorm): - def forward(self, x: Any) -> Any: - weight = self.weight.float() if self.weight is not None else None - bias = self.bias.float() if self.bias is not None else None - out = functional.layer_norm(x.float(), self.normalized_shape, weight, bias, self.eps) - return out.type_as(x) - - class ConvBlock(nn.Module): - def __init__( - self, - input_dim: int, - output_dim: int, - kernel_size: int, - stride: int, - bias: bool = False, - dropout: float = 0.0, - ) -> None: - nn.Module.__init__(self) - self.conv = nn.Conv1d(input_dim, output_dim, kernel_size, stride, bias=bias) - self.dropout = nn.Dropout(dropout) - self.norm = Fp32LayerNorm(output_dim, elementwise_affine=True) - self.activation = nn.GELU() - - def forward(self, x: Any) -> Any: - out = self.dropout(self.conv(x)) - out = self.norm(out.movedim(-1, -2)).movedim(-1, -2) - return self.activation(out) - - class SamePad(nn.Module): - def __init__(self, kernel_size: int, causal: bool = False) -> None: - nn.Module.__init__(self) - self.remove = (kernel_size - 1) if causal else (1 if kernel_size % 2 == 0 else 0) - - def forward(self, x: Any) -> Any: - return x[..., : -self.remove] if self.remove > 0 else x - - class PositionalConvEmbedding(nn.Module): - def __init__(self, dim: int, kernel_size: int, groups: int) -> None: - nn.Module.__init__(self) - self.conv = nn.Conv1d(dim, dim, kernel_size=kernel_size, padding=kernel_size // 2, groups=groups) - self.padding = SamePad(kernel_size) - self.activation = nn.GELU() - - def forward(self, x: Any) -> Any: - out = self.padding(self.conv(x.movedim(-1, -2))) - return self.activation(out).movedim(-1, -2) - - class MultiHeadAttention(nn.Module): - def __init__(self, dim: int, num_heads: int, dropout: float = 0.0) -> None: - nn.Module.__init__(self) - self.num_heads = num_heads - self.dropout = dropout - head_dim = dim // num_heads - self.k_proj = nn.Linear(dim, dim) - self.v_proj = nn.Linear(dim, dim) - self.q_proj = nn.Linear(dim, dim) - self.out_proj = nn.Linear(dim, dim) - self.gru_rel_pos_linear = nn.Linear(head_dim, 8) - self.gru_rel_pos_const = nn.Parameter(torch.ones(1, num_heads, 1, 1)) - - def forward(self, x: Any, position_bias: Any) -> Any: - batch, steps, _ = x.shape - gated = x.reshape((*x.shape[:-1], self.num_heads, -1)).movedim(-3, -2) - rel_proj = self.gru_rel_pos_linear(gated).reshape((*gated.shape[:-1], 2, 4)).sum(dim=-1) - gate_a, gate_b = rel_proj.sigmoid().chunk(2, dim=-1) - gated_bias = (gate_a * (gate_b * self.gru_rel_pos_const - 1.0) + 2.0) * position_bias - qs = self.q_proj(x).reshape(batch, steps, self.num_heads, -1).movedim(-3, -2) - ks = self.k_proj(x).reshape(batch, steps, self.num_heads, -1).movedim(-3, -2) - vs = self.v_proj(x).reshape(batch, steps, self.num_heads, -1).movedim(-3, -2) - out = functional.scaled_dot_product_attention( - qs, - ks.type_as(qs), - vs.type_as(qs), - attn_mask=gated_bias.type_as(qs), - dropout_p=0.0, - ) - return self.out_proj(out.movedim(1, 2).contiguous().reshape(batch, steps, -1)) - - class FeedForward(nn.Module): - def __init__(self, dim: int, ffn_dim: int, dropout: float = 0.0) -> None: - nn.Module.__init__(self) - self.in_proj = nn.Linear(dim, ffn_dim) - self.activation = nn.GELU() - self.dropout = nn.Dropout(dropout) - self.out_proj = nn.Linear(ffn_dim, dim) - - def forward(self, x: Any) -> Any: - out = self.dropout(self.activation(self.in_proj(x))) - return self.dropout(self.out_proj(out)) - - class TransformerLayer(nn.Module): - def __init__(self, dim: int, ffn_dim: int, num_heads: int, dropout: float = 0.0) -> None: - nn.Module.__init__(self) - self.attention_norm = nn.LayerNorm(dim) - self.attention = MultiHeadAttention(dim, num_heads, dropout) - self.dropout = nn.Dropout(dropout) - self.feed_forward_norm = nn.LayerNorm(dim) - self.feed_forward = FeedForward(dim, ffn_dim, dropout) - - def forward(self, x: Any, position_bias: Any) -> Any: - out = x + self.dropout(self.attention(self.attention_norm(x), position_bias)) - return out + self.feed_forward(self.feed_forward_norm(out)) - - class TransformerEncoder(nn.Module): - def __init__( - self, - num_layers: int, - dim: int, - ffn_dim: int, - num_heads: int, - num_buckets: int, - max_distance: int, - dropout: float, - conv_pos: int, - conv_pos_groups: int, - ) -> None: - nn.Module.__init__(self) - self._num_buckets = num_buckets // 2 - self._num_buckets_minus_one = self._num_buckets - 1 - self._max_exact = self._num_buckets // 2 - self._num_buckets_minus_max_exact = self._num_buckets - self._max_exact - self._log_max_distance_over_max_exact = math.log(max_distance / self._max_exact) - self.positional_embedding = PositionalConvEmbedding(dim, conv_pos, conv_pos_groups) - self.relative_embedding = nn.Embedding(num_buckets, num_heads) - self.layers = nn.ModuleList( - TransformerLayer(dim=dim, ffn_dim=ffn_dim, num_heads=num_heads, dropout=dropout) - for _ in range(num_layers) - ) - self.dropout = nn.Dropout(dropout) - self.norm = nn.LayerNorm(dim) - - def _relative_positions_bucket(self, relative_positions: Any) -> Any: - buckets = (relative_positions > 0).to(torch.long) * self._num_buckets - abs_pos = relative_positions.abs() - is_small = abs_pos < self._max_exact - large = (abs_pos.float() / self._max_exact).log() / self._log_max_distance_over_max_exact - large = (large * self._num_buckets_minus_max_exact + self._max_exact).to(torch.long) - large = large.clamp(max=self._num_buckets_minus_one) - return buckets + torch.where(is_small, abs_pos, large) - - def _compute_bias(self, length: int) -> Any: - ctx = torch.arange(length, dtype=torch.long)[:, None] - mem = torch.arange(length, dtype=torch.long)[None, :] - buckets = self._relative_positions_bucket(mem - ctx).to(self.relative_embedding.weight.device) - return self.relative_embedding(buckets).movedim(-1, 0) - - def forward(self, x: Any, output_norm: bool = False) -> Any: - steps = int(x.shape[1]) - out = self.dropout(x + self.positional_embedding(x)) - position_bias = self._compute_bias(steps)[:, -steps:].type_as(out) - for layer in self.layers: - out = layer(out, position_bias) - return self.norm(out) if output_norm else out - - class FeatureExtractor(nn.Module): - def __init__( - self, - input_dim: int, - hidden_dims: list[int] | tuple[int, ...], - kernel_sizes: list[int] | tuple[int, ...], - strides: list[int] | tuple[int, ...], - dropout: float = 0.0, - ) -> None: - nn.Module.__init__(self) - self.layers = nn.ModuleList() - cur = input_dim - for hidden_dim, kernel_size, stride in zip(hidden_dims, kernel_sizes, strides, strict=True): - self.layers.append(ConvBlock(cur, hidden_dim, kernel_size, stride, False, dropout)) - cur = hidden_dim - - def forward(self, x: Any) -> Any: - out = x.movedim(-1, -2) - for layer in self.layers: - out = layer(out) - return out.movedim(-2, -1) - - class WavLM(nn.Module): - def __init__( - self, - hidden_dims: list[int] | tuple[int, ...], - kernel_sizes: list[int] | tuple[int, ...], - strides: list[int] | tuple[int, ...], - num_layers: int, - dim: int, - ffn_dim: int, - num_heads: int, - num_buckets: int, - max_distance: int, - dropout: float, - conv_pos: int, - conv_pos_groups: int, - ) -> None: - nn.Module.__init__(self) - self.feature_extractor = FeatureExtractor(1, hidden_dims, kernel_sizes, strides, dropout) - self.norm = nn.LayerNorm(hidden_dims[-1]) - self.feature_proj = nn.Linear(hidden_dims[-1], dim) - self.dropout = nn.Dropout(dropout) - self.encoder = TransformerEncoder( - num_layers=num_layers, - dim=dim, - ffn_dim=ffn_dim, - num_heads=num_heads, - num_buckets=num_buckets, - max_distance=max_distance, - dropout=dropout, - conv_pos=conv_pos, - conv_pos_groups=conv_pos_groups, - ) - - def forward(self, x: Any) -> Any: - out = self.feature_extractor(x[..., None]) - out = self.dropout(self.feature_proj(self.norm(out))) - return self.encoder(out, output_norm=False) - - class FocalModulation(nn.Module): - def __init__( - self, - dim: int, - focal_window: int, - focal_level: int, - focal_factor: int, - dropout: float, - use_post_norm: bool, - normalize_modulator: bool, - ) -> None: - nn.Module.__init__(self) - self.dim = dim - self.focal_level = focal_level - self.use_post_norm = use_post_norm - self.normalize_modulator = normalize_modulator - self.in_proj = nn.Linear(dim, 2 * dim + focal_level + 1) - self.layers = nn.ModuleList() - self.activation = nn.GELU() - self.context_proj = nn.Conv1d(dim, dim, kernel_size=1, stride=1) - self.out_proj = nn.Linear(dim, dim) - self.dropout = nn.Dropout(dropout) - for level in range(focal_level): - kernel_size = focal_factor * level + focal_window - self.layers.append( - nn.Sequential( - nn.Conv1d(dim, dim, kernel_size=kernel_size, stride=1, groups=dim, padding=kernel_size // 2), - nn.GELU(), - ) - ) - self.norm = nn.LayerNorm(dim) if use_post_norm else nn.Identity() - - class FocalBlock(nn.Module): - def __init__( - self, - dim: int, - ffn_dim: int, - focal_window: int, - focal_level: int, - focal_factor: int, - dropout: float, - use_post_norm: bool, - use_layerscale: bool, - layerscale_init: float, - normalize_modulator: bool, - ) -> None: - nn.Module.__init__(self) - self.modulation_norm = nn.LayerNorm(dim) - self.modulation = FocalModulation( - dim=dim, - focal_window=focal_window, - focal_level=focal_level, - focal_factor=focal_factor, - dropout=dropout, - use_post_norm=use_post_norm, - normalize_modulator=normalize_modulator, - ) - self.feed_forward_norm = nn.LayerNorm(dim) - self.feed_forward = FeedForward(dim, ffn_dim, dropout) - if use_layerscale: - self.modulation_gamma = nn.Parameter(torch.full((dim,), layerscale_init)) - self.feed_forward_gamma = nn.Parameter(torch.full((dim,), layerscale_init)) - - class Snake1d(nn.Module): - def __init__(self, dim: int) -> None: - nn.Module.__init__(self) - self.alpha = nn.Parameter(torch.ones(dim, 1)) - - class DownScale(nn.Module): - def __init__(self, input_dim: int, output_dim: int, kernel_size: int, stride: int) -> None: - nn.Module.__init__(self) - self.downscale = nn.Conv1d(input_dim, output_dim, kernel_size, stride) - self.activation = Snake1d(output_dim) - - class UpScale(nn.Module): - def __init__(self, input_dim: int, output_dim: int, kernel_size: int, stride: int) -> None: - nn.Module.__init__(self) - self.activation = Snake1d(input_dim) - self.upscale = nn.ConvTranspose1d(input_dim, output_dim, kernel_size=kernel_size, stride=stride) - - class FocalEncoder(nn.Module): - def __init__( - self, - input_dim: int, - output_dim: int, - hidden_dims: list[int] | tuple[int, ...], - downscale_factors: list[int] | tuple[int, ...], - focal_window: int, - focal_level: int, - focal_factor: int, - dropout: float, - use_post_norm: bool, - use_layerscale: bool, - layerscale_init: float, - normalize_modulator: bool, - ) -> None: - nn.Module.__init__(self) - self.layers = nn.ModuleList() - cur = input_dim - for hidden_dim, factor in zip(hidden_dims, downscale_factors, strict=True): - self.layers.append( - nn.Sequential( - DownScale(cur, hidden_dim, factor, factor), - FocalBlock( - hidden_dim, - hidden_dim * 4, - focal_window, - focal_level, - focal_factor, - dropout, - use_post_norm, - use_layerscale, - layerscale_init, - normalize_modulator, - ), - ) - ) - cur = hidden_dim - self.dropout = nn.Dropout(dropout) - self.out_proj = nn.Linear(cur, output_dim) - - class FocalDecoder(nn.Module): - def __init__( - self, - input_dim: int, - output_dim: int, - hidden_dims: list[int] | tuple[int, ...], - upscale_factors: list[int] | tuple[int, ...], - focal_window: int, - focal_level: int, - focal_factor: int, - dropout: float, - use_post_norm: bool, - use_layerscale: bool, - layerscale_init: float, - normalize_modulator: bool, - ) -> None: - nn.Module.__init__(self) - dims = (*tuple(hidden_dims), output_dim) - cur = dims[0] - self.in_proj = nn.Linear(input_dim, cur) - self.dropout = nn.Dropout(dropout) - self.layers = nn.ModuleList() - for hidden_dim, factor in zip(dims[1:], upscale_factors, strict=True): - self.layers.append( - nn.Sequential( - FocalBlock( - cur, - cur * 4, - focal_window, - focal_level, - focal_factor, - dropout, - use_post_norm, - use_layerscale, - layerscale_init, - normalize_modulator, - ), - UpScale(cur, hidden_dim, factor, factor), - ) - ) - cur = hidden_dim - - class BinarySphericalQuantizer(nn.Module): - def __init__(self, codebook_size: int = 8192) -> None: - nn.Module.__init__(self) - dim = int(math.log2(codebook_size)) - codebook_value = 1 / math.sqrt(dim) - self.register_buffer("mask", 2 ** torch.arange(dim - 1, -1, -1)) - all_codes = torch.arange(codebook_size) - bits = ((all_codes[..., None].int() & self.mask) != 0).float() - self.register_buffer("codebook", ((bits * 2 - 1) * codebook_value).float(), persistent=False) - - class ConvNeXtBlock(nn.Module): - def __init__( - self, - dim: int, - ffn_dim: int, - kernel_size: int, - padding: int, - layerscale_init: float | None, - ) -> None: - nn.Module.__init__(self) - self.dwconv = nn.Conv1d(dim, dim, kernel_size, padding=padding, groups=dim) - self.norm = nn.LayerNorm(dim, eps=1e-6) - self.pwconv1 = nn.Linear(dim, ffn_dim) - self.activation = nn.GELU() - self.pwconv2 = nn.Linear(ffn_dim, dim) - self.gamma = nn.Parameter(torch.full((dim,), layerscale_init)) if layerscale_init is not None else None - - def forward(self, x: Any) -> Any: - out = self.norm(self.dwconv(x).movedim(-1, -2)) - out = self.pwconv2(self.activation(self.pwconv1(out))) - if self.gamma is not None: - out = self.gamma * out - return x + out.movedim(-1, -2) - - class ISTFT(nn.Module): - def __init__(self, n_fft: int, hop_length: int, win_length: int) -> None: - nn.Module.__init__(self) - self.n_fft = n_fft - self.hop_length = hop_length - self.win_length = win_length - self.pad = (win_length - hop_length) // 2 - self.register_buffer("window", torch.hann_window(win_length), persistent=False) - - def forward(self, spec: Any) -> Any: - ifft = torch.fft.irfft(spec, self.n_fft, dim=1, norm="backward") * self.window[None, :, None] - frames = int(spec.shape[-1]) - output_size = (frames - 1) * self.hop_length + self.win_length - out = functional.fold( - ifft, - output_size=(1, output_size), - kernel_size=(1, self.win_length), - stride=(1, self.hop_length), - )[:, 0, 0, self.pad : -self.pad] - window_sq = (self.window**2).expand(1, frames, -1).movedim(-1, -2) - envelope = functional.fold( - window_sq, - output_size=(1, output_size), - kernel_size=(1, self.win_length), - stride=(1, self.hop_length), - ).squeeze()[self.pad : -self.pad] - return out / envelope - - class VocosBackbone(nn.Module): - def __init__( - self, - input_channels: int, - num_layers: int, - dim: int, - ffn_dim: int, - kernel_size: int = 7, - padding: int = 3, - layerscale_init: float | None = None, - ) -> None: - nn.Module.__init__(self) - scale = 1 / num_layers if layerscale_init is None else layerscale_init - self.embedding = nn.Conv1d(input_channels, dim, kernel_size, padding=padding) - self.input_norm = nn.LayerNorm(dim, eps=1e-6) - self.layers = nn.ModuleList( - ConvNeXtBlock(dim, ffn_dim, kernel_size, padding, scale) for _ in range(num_layers) - ) - self.output_norm = nn.LayerNorm(dim, eps=1e-6) - - def forward(self, x: Any) -> Any: - out = self.input_norm(self.embedding(x).movedim(-1, -2)).movedim(-1, -2) - for layer in self.layers: - out = layer(out) - return self.output_norm(out.movedim(-1, -2)).movedim(-1, -2) - - class ISTFTHead(nn.Module): - def __init__(self, dim: int, n_fft: int, hop_length: int) -> None: - nn.Module.__init__(self) - self.proj = nn.Linear(dim, n_fft + 2) - self.istft = ISTFT(n_fft=n_fft, hop_length=hop_length, win_length=n_fft) - - def forward(self, x: Any) -> Any: - mag, phase = self.proj(x.movedim(-1, -2)).movedim(-1, -2).chunk(2, dim=-2) - mag = mag.exp().clamp(max=1e2) - spec = mag * torch.complex(phase.cos(), phase.sin()) - return self.istft(spec) - - class Vocos(nn.Module): - def __init__( - self, - input_channels: int, - num_layers: int, - dim: int, - ffn_dim: int, - kernel_size: int = 7, - padding: int = 3, - layerscale_init: float | None = None, - n_fft: int = 1024, - hop_length: int = 320, - ) -> None: - nn.Module.__init__(self) - self.backbone = VocosBackbone( - input_channels=input_channels, - num_layers=num_layers, - dim=dim, - ffn_dim=ffn_dim, - kernel_size=kernel_size, - padding=padding, - layerscale_init=layerscale_init, - ) - self.head = ISTFTHead(dim, n_fft, hop_length) - - def forward(self, x: Any) -> Any: - return self.head(self.backbone(x.movedim(-1, -2))) - - class FocalCodecModel(nn.Module): - sample_rate = 16000 - - def __init__(self) -> None: - nn.Module.__init__(self) - self.encoder = WavLM(**config["encoder_config"]) - self.compressor = FocalEncoder(**config["compressor_config"]) - self.quantizer = BinarySphericalQuantizer(**config["quantizer_config"]) - self.decompressor = FocalDecoder(**config["decompressor_config"]) - self.decoder = Vocos(**config["decoder_config"]) - - def resynthesize_features(self, padded_wave_16k: Any) -> Any: - """Encode continuous 50 Hz WavLM features and synthesize via Vocos.""" - return self.decoder(self.encoder(padded_wave_16k)) - - return FocalCodecModel() diff --git a/src/remove_ai_watermarks/_internal/audio_focalcodec.py b/src/remove_ai_watermarks/_internal/audio_focalcodec.py deleted file mode 100644 index f3a29ea..0000000 --- a/src/remove_ai_watermarks/_internal/audio_focalcodec.py +++ /dev/null @@ -1,303 +0,0 @@ -"""Internal full-track FocalCodec continuous-feature resynthesis on CPU FP32. - -Weights are optional, downloaded separately under Apache-2.0. See -licenses/focalcodec/. The 16 kHz model cannot preserve the source band above -8 kHz, and Vocos STFT synthesis does not preserve carrier waveform phase or -guarantee provider-watermark removal on arbitrary inputs. -""" - -from __future__ import annotations - -import json -import logging -import threading -from functools import lru_cache -from importlib import import_module -from pathlib import Path -from typing import Any, cast - -from remove_ai_watermarks._internal import audio_resampling as src -from remove_ai_watermarks._internal import audio_spectral -from remove_ai_watermarks._internal._focalcodec_network import build_focalcodec -from remove_ai_watermarks._internal.audio_quality import sha256_file -from remove_ai_watermarks.optional_deps import module_available - -log = logging.getLogger(__name__) -MODEL_REPOSITORY = "lucadellalib/focalcodec_50hz" -MODEL_REVISION = "d6d6d9524e52155c85193c2c3b8da1cf8842f019" -SOURCE_REVISION = "cad8bf81d70875f756770449c34909d8b0951642" -CHECKPOINT_FILENAME = "model.safetensors" -CHECKPOINT_SHA256 = "2700a916ca8d1c11a899995ef8d451ee53a481486650c4b78cd96feff9ac77f0" -CONFIG_SHA256 = "fc5d9ec56ce795ffeb889e4209b10f8b40a95b9e821662b09d39bf31a4429bd0" -EXPECTED_STATE_KEY_COUNT = 355 -WAVLM_CONTEXT_EACH = 40 -_MODEL_LOCK = threading.RLock() - -_EXPECTED_CONFIG: dict[str, Any] = { - "encoder_name": "WavLM", - "encoder_config": { - "hidden_dims": [512, 512, 512, 512, 512, 512, 512], - "kernel_sizes": [10, 3, 3, 3, 3, 2, 2], - "strides": [5, 2, 2, 2, 2, 2, 2], - "num_layers": 6, - "dim": 1024, - "ffn_dim": 4096, - "num_heads": 16, - "num_buckets": 320, - "max_distance": 800, - "dropout": 0.0, - "conv_pos": 128, - "conv_pos_groups": 16, - }, - "compressor_name": "FocalEncoder", - "compressor_config": { - "input_dim": 1024, - "output_dim": 13, - "hidden_dims": [1024, 512, 256], - "downscale_factors": [1, 1, 1], - "focal_window": 7, - "focal_level": 2, - "focal_factor": 2, - "dropout": 0.0, - "use_post_norm": False, - "use_layerscale": False, - "layerscale_init": 0.0001, - "normalize_modulator": False, - }, - "quantizer_name": "BinarySphericalQuantizer", - "quantizer_config": {"codebook_size": 8192}, - "decompressor_name": "FocalDecoder", - "decompressor_config": { - "input_dim": 13, - "output_dim": 1024, - "hidden_dims": [256, 512, 1024], - "upscale_factors": [1, 1, 1], - "focal_window": 7, - "focal_level": 2, - "focal_factor": 2, - "dropout": 0.0, - "use_post_norm": False, - "use_layerscale": False, - "layerscale_init": 0.0001, - "normalize_modulator": False, - }, - "decoder_name": "Vocos", - "decoder_config": { - "input_channels": 1024, - "num_layers": 8, - "dim": 512, - "ffn_dim": 1536, - "kernel_size": 7, - "padding": 3, - "layerscale_init": None, - "n_fft": 1024, - "hop_length": 320, - }, -} - - -def is_available() -> bool: - """Inspect optional dependencies without importing them or fetching weights.""" - return all(module_available(name) for name in ("numpy", "scipy", "torch", "huggingface_hub", "safetensors")) - - -def _check_config(config: Any) -> None: - if config != _EXPECTED_CONFIG: - raise RuntimeError("Pinned FocalCodec configuration does not match the fixed inference profile") - - -@lru_cache(maxsize=2) -def load_pinned_model(*, local_files_only: bool = True) -> Any: - """Load the pinned FocalCodec 50 Hz checkpoint on CPU FP32 after hash checks.""" - if not is_available(): - raise ImportError("FocalCodec requires numpy, scipy, torch, huggingface_hub, and safetensors") - hub = import_module("huggingface_hub") - paths: dict[str, Path] = {} - for filename, expected in (("config.json", CONFIG_SHA256), (CHECKPOINT_FILENAME, CHECKPOINT_SHA256)): - path = Path( - hub.hf_hub_download( - repo_id=MODEL_REPOSITORY, - filename=filename, - revision=MODEL_REVISION, - local_files_only=local_files_only, - ) - ) - if sha256_file(path) != expected: - raise RuntimeError(f"Pinned FocalCodec checkpoint digest mismatch for {filename}") - paths[filename] = path - if paths["config.json"].parent != paths[CHECKPOINT_FILENAME].parent: - raise RuntimeError("Pinned FocalCodec artifacts must share one snapshot directory") - config = json.loads(paths["config.json"].read_text(encoding="utf-8")) - _check_config(config) - safetensors_torch = import_module("safetensors.torch") - raw_state = safetensors_torch.load_file(str(paths[CHECKPOINT_FILENAME]), device="cpu") - if not isinstance(raw_state, dict): - raise RuntimeError("Pinned FocalCodec checkpoint did not contain a state dictionary") - state = cast("dict[str, Any]", raw_state) - if len(state) != EXPECTED_STATE_KEY_COUNT: - raise RuntimeError("Pinned FocalCodec checkpoint did not contain the expected 355 state keys") - model = build_focalcodec(config) - incompatible = model.load_state_dict(state, strict=True) - if getattr(incompatible, "missing_keys", ()) or getattr(incompatible, "unexpected_keys", ()): - raise RuntimeError(f"Pinned FocalCodec checkpoint did not load completely: {incompatible}") - model = model.to("cpu").float().train(False).requires_grad_(False) - log.info("Loaded pinned FocalCodec %s@%s on CPU (FP32, continuous features)", MODEL_REPOSITORY, MODEL_REVISION) - return model - - -def _prepare_input(samples: Any, sample_rate: int) -> tuple[Any, src.RationalClock]: - np = import_module("numpy") - value = np.asarray(samples) - if value.ndim != 2 or not value.shape[0] or value.shape[1] not in (1, 2) or value.dtype.kind != "f": - raise ValueError("FocalCodec expects a nonempty floating (frames, 1 or 2 channels) matrix") - clock = src.RationalClock(int(value.shape[0]), sample_rate, model_rate=16000, hop=320, minimum_model_frames=320) - if not np.isfinite(value).all(): - raise ValueError("FocalCodec input must be finite") - value_f32 = np.asarray(value, dtype=np.float32) - if not np.isfinite(value_f32).all(): - raise ValueError("FocalCodec input must be finite in float32") - return value_f32, clock - - -def resynthesize(samples: Any, sample_rate: int, *, stereo_mode: str = "ms", local_files_only: bool = True) -> Any: - """Return full native mono/stereo samples without gain, clipping, or lag repair. - - Uses the 16 kHz model grid (hop 320, minimum 320 samples) with right - reflection to a complete 50 Hz frame boundary when needed, plus symmetric - (40, 40) receptive-field context before WavLM feature extraction so every - 320-sample hop frame produces one feature vector without dropping tails. - Stereo defaults to raw mid/side; each channel runs in its own single-item - batch so mono and stereo share identical numerical behavior. - """ - if not is_available(): - raise ImportError("FocalCodec requires numpy, scipy, torch, huggingface_hub, and safetensors") - if stereo_mode not in {"ms", "lr"}: - raise ValueError("FocalCodec stereo mode must be ms or lr") - np = import_module("numpy") - torch = import_module("torch") - functional = torch.nn.functional - value, clock = _prepare_input(samples, sample_rate) - prepared = src.forward(value, clock) - mid_side = value.shape[1] == 2 and stereo_mode == "ms" - if mid_side: - prepared = np.column_stack(((prepared[:, 0] + prepared[:, 1]) / 2, (prepared[:, 0] - prepared[:, 1]) / 2)) - if not np.isfinite(prepared).all(): - raise ValueError("FocalCodec prepared input must be finite") - padded = src.pad_model(prepared, clock) - reconstructed_channels: list[Any] = [] - with _MODEL_LOCK, torch.inference_mode(): - model = load_pinned_model(local_files_only=local_files_only) - for channel in range(value.shape[1]): - wave = torch.from_numpy(np.ascontiguousarray(padded[:, channel]))[None] - context_wave = functional.pad(wave, (WAVLM_CONTEXT_EACH, WAVLM_CONTEXT_EACH)) - output = model.resynthesize_features(context_wave) - if tuple(output.shape) != (1, clock.padded_frames): - raise RuntimeError("FocalCodec returned incorrect model sample geometry") - decoded = output[0].detach().to(device="cpu", dtype=torch.float32).numpy() - if not np.isfinite(decoded).all(): - raise RuntimeError("FocalCodec returned nonfinite samples") - reconstructed_channels.append(src.unpad_model(decoded, clock)) - reconstructed = np.column_stack(reconstructed_channels) - if mid_side: - reconstructed = np.column_stack( - (reconstructed[:, 0] + reconstructed[:, 1], reconstructed[:, 0] - reconstructed[:, 1]) - ) - delivered = src.inverse(reconstructed, clock) - if delivered.shape != value.shape or not np.isfinite(delivered).all(): - raise RuntimeError("FocalCodec returned invalid native sample geometry or values") - return np.asarray(delivered, dtype=np.float32) - - -_ENVELOPE_CUTS_HZ: tuple[float, ...] = (200.0, 400.0, 800.0, 1600.0, 3200.0, 6400.0) -_ENVELOPE_LOWPASS_HZ: float = 35.0 -_ENVELOPE_MAX_GAIN: float = 2.5 - - -def resynthesize_conditioned( - samples: Any, - sample_rate: int, - *, - stereo_mode: str = "ms", - local_files_only: bool = True, -) -> Any: - """Precondition the mid-band mark region, resynthesize, and restore sub-band envelopes. - - 1. Applies the calibrated 1.0-1.5 kHz zero-phase band-stop when ``sample_rate`` - supports it so the WavLM encoder does not encode mid-band watermark - modulation into its continuous 50 Hz features. - 2. Runs full-track FocalCodec continuous-feature resynthesis. - 3. Restores complementary zero-phase Butterworth sub-band 35 Hz envelopes from - the original waveform (clamped to ``[0.0, 2.5]``), suppressing idle vocoder - pause hiss while preserving speech formant balance and 10 ms sub-window - envelope timing. - """ - if not is_available(): - raise ImportError("FocalCodec requires numpy, scipy, torch, huggingface_hub, and safetensors") - np = import_module("numpy") - signal = import_module("scipy.signal") - - source_f32, _ = _prepare_input(samples, sample_rate) - - if sample_rate > int(2 * audio_spectral.BAND_HZ[1]) and source_f32.shape[0] > 1: - preconditioned = np.concatenate( - list(audio_spectral.filter_audio_chunks((source_f32,), sample_rate)), - axis=0, - ).astype(np.float32, copy=False) - else: - preconditioned = source_f32 - - import inspect - - resynth_kwargs: dict[str, Any] = {"local_files_only": local_files_only} - if "stereo_mode" in inspect.signature(resynthesize).parameters: - resynth_kwargs["stereo_mode"] = stereo_mode - raw = np.asarray(resynthesize(preconditioned, sample_rate, **resynth_kwargs), dtype=np.float32) - if raw.shape != source_f32.shape or not np.isfinite(raw).all(): - raise RuntimeError("FocalCodec returned invalid native sample geometry or values") - if source_f32.shape[0] <= 2 or sample_rate <= int(2 * _ENVELOPE_LOWPASS_HZ): - return raw - - x64 = source_f32.astype(np.float64) - y64 = raw.astype(np.float64) - valid_cuts = [cut for cut in _ENVELOPE_CUTS_HZ if cut < 0.47 * sample_rate] - env_sos = np.asarray( - signal.butter(2, _ENVELOPE_LOWPASS_HZ, btype="lowpass", fs=sample_rate, output="sos"), - dtype=np.float64, - ) - pad_env = min(3 * (2 * len(env_sos) + 1), len(x64) - 1) - x_prev = np.zeros_like(x64) - y_prev = np.zeros_like(y64) - out = np.zeros_like(y64) - - for cut in [*valid_cuts, None]: - if cut is not None: - sos = np.asarray(signal.butter(4, cut, btype="lowpass", fs=sample_rate, output="sos"), dtype=np.float64) - pad_lp = min(3 * (2 * len(sos) + 1), len(x64) - 1) - x_lp = np.asarray(signal.sosfiltfilt(sos, x64, axis=0, padlen=pad_lp), dtype=np.float64) - y_lp = np.asarray(signal.sosfiltfilt(sos, y64, axis=0, padlen=pad_lp), dtype=np.float64) - xb = x_lp - x_prev - yb = y_lp - y_prev - x_prev = x_lp - y_prev = y_lp - else: - xb = x64 - x_prev - yb = y64 - y_prev - xe = np.sqrt(np.maximum(signal.sosfiltfilt(env_sos, xb * xb, axis=0, padlen=pad_env), 0.0) + 1e-14) - ye = np.sqrt(np.maximum(signal.sosfiltfilt(env_sos, yb * yb, axis=0, padlen=pad_env), 0.0) + 1e-14) - gain = np.clip(xe / ye, 0.0, _ENVELOPE_MAX_GAIN) - out += gain * yb - - src_peak = max(abs(float(x64.min())), abs(float(x64.max()))) - out_peak = max(abs(float(out.min())), abs(float(out.max()))) - ceiling = min(max(src_peak, 0.25), 0.96) if src_peak <= 1.0 else src_peak - if out_peak > ceiling > 0.0: - knee = 0.85 * ceiling - headroom = ceiling - knee - over = (out > knee) | (out < -knee) - vals = out[over] - out[over] = np.sign(vals) * (knee + headroom * np.tanh((np.abs(vals) - knee) / headroom)) - - delivered_cond = np.asarray(out, dtype=np.float32) - if delivered_cond.shape != source_f32.shape or not np.isfinite(delivered_cond).all(): - raise RuntimeError("FocalCodec envelope conditioning produced nonfinite samples") - return delivered_cond diff --git a/src/remove_ai_watermarks/_internal/audio_io.py b/src/remove_ai_watermarks/_internal/audio_io.py index 1be830e..dd76383 100644 --- a/src/remove_ai_watermarks/_internal/audio_io.py +++ b/src/remove_ai_watermarks/_internal/audio_io.py @@ -230,28 +230,35 @@ def _source_pcm_bit_depth(info: AudioStreamInfo) -> int | None: return None +_FLAC_CONTAINERS: frozenset[str] = frozenset({".flac", ".mka"}) + + def _audio_codec_args(suffix: str, info: AudioStreamInfo, *, bitexact: bool) -> list[str]: + from remove_ai_watermarks._internal.constants import AUDIO_OPUS_EXTENSIONS + pcm_depth = None if bitexact else _source_pcm_bit_depth(info) if suffix == ".wav": wav_codec = {16: "pcm_s16le", 24: "pcm_s24le"}.get(pcm_depth or 32, "pcm_f32le") return ["-c:a", wav_codec, "-rf64", "never" if bitexact else "auto"] - if suffix == ".flac": + if suffix in _FLAC_CONTAINERS: if pcm_depth == 16: return ["-c:a", "flac", "-sample_fmt", "s16"] return ["-c:a", "flac", "-sample_fmt", "s32"] if suffix == ".m4a": return ["-c:a", "aac", "-b:a", "192k", "-movflags", "+faststart"] + if suffix == ".aac": + return ["-c:a", "aac", "-b:a", "192k"] if suffix == ".mp3": if info.channels not in (1, 2): - raise ValueError("MP3 output supports mono or stereo; use WAV, FLAC, or M4A") + raise ValueError("MP3 output supports mono or stereo; use WAV, FLAC, MKA, or M4A") if info.sample_rate not in _MP3_RATES: - raise ValueError(f"MP3 output does not support {info.sample_rate} Hz; use WAV, FLAC, or M4A") + raise ValueError(f"MP3 output does not support {info.sample_rate} Hz; use WAV, FLAC, MKA, or M4A") return ["-c:a", "libmp3lame", "-b:a", "256k", "-write_xing", "1"] - if suffix in {".ogg", ".opus"}: + if suffix in AUDIO_OPUS_EXTENSIONS: if info.channels not in (1, 2): - raise ValueError("Opus/Ogg output supports mono or stereo; use WAV, FLAC, or M4A") + raise ValueError("Opus/Ogg output supports mono or stereo; use WAV, FLAC, MKA, or M4A") return ["-c:a", "libopus", "-b:a", "192k"] - raise ValueError("Audio sample output must be WAV, FLAC, MP3, M4A, OGG, or OPUS") + raise ValueError("Audio sample output must be WAV, FLAC, MP3, M4A, OGG, OGA, OPUS, AAC, or MKA") def write_audio( @@ -316,8 +323,8 @@ def write_audio( raise ValueError("Bitexact WAV exceeds the short RIFF size bound; use the default RF64 writer") if not np.isfinite(frames).all(): raise ValueError("Audio samples must be finite") - if suffix == ".flac" and frames.size and (float(frames.min()) < -1 or float(frames.max()) > 1): - raise ValueError("FLAC cannot preserve samples outside [-1, 1]; use floating-point WAV") + if suffix in _FLAC_CONTAINERS and frames.size and (float(frames.min()) < -1 or float(frames.max()) > 1): + raise ValueError("FLAC/MKA cannot preserve samples outside [-1, 1]; use floating-point WAV") process.stdin.write(np.ascontiguousarray(frames).tobytes()) count += len(frames) if count == 0 or (expected_frames is not None and count != expected_frames): @@ -325,12 +332,14 @@ def write_audio( process.stdin.close() finish_process(process, stderr, command) delivered = probe_audio(staged) - expected_sr = 48000 if suffix in {".ogg", ".opus"} else info.sample_rate + from remove_ai_watermarks._internal.constants import AUDIO_OPUS_EXTENSIONS + + expected_sr = 48000 if suffix in AUDIO_OPUS_EXTENSIONS else info.sample_rate if (delivered.sample_rate, delivered.channels) != (expected_sr, info.channels): raise RuntimeError("Audio encoder changed the sample rate or channel count") if ( info.channel_layout - and suffix in {".wav", ".flac", ".m4a"} + and suffix in {".wav", ".flac", ".m4a", ".mka"} and delivered.channel_layout != info.channel_layout ): raise RuntimeError("Audio encoder changed the channel layout") diff --git a/src/remove_ai_watermarks/_internal/audio_mimi.py b/src/remove_ai_watermarks/_internal/audio_mimi.py deleted file mode 100644 index c1fe78e..0000000 --- a/src/remove_ai_watermarks/_internal/audio_mimi.py +++ /dev/null @@ -1,139 +0,0 @@ -"""Internal full-track Mimi codec; no provider-removal or voice-identity guarantee. - -Weights are optional, downloaded separately under CC-BY-4.0. See licenses/mimi/. -The 24 kHz model cannot preserve the source band above 12 kHz. -""" - -from __future__ import annotations - -import importlib.util -import logging -import threading -from functools import lru_cache -from importlib import import_module -from pathlib import Path -from typing import Any - -from remove_ai_watermarks._internal import audio_resampling as src -from remove_ai_watermarks._internal.audio_quality import sha256_file - -log = logging.getLogger(__name__) -MODEL_REPOSITORY = "kyutai/mimi" -MODEL_REVISION = "89091b3e466eb6a9d11e537bf26b144f194978f7" -CHECKPOINT_FILENAME = "model.safetensors" -CHECKPOINT_SHA256 = "bac7e85083dcded655d24eaadde7e6eea34c0da1b35fa2d284e641bd2b942a5e" -CONFIG_SHA256 = "aca6f44b04f7bc2e7466b71597d2d51e463ed1cf3cd7025d8848595580546c36" -_MODEL_LOCK = threading.RLock() - - -def is_available() -> bool: - """Inspect optional dependencies without importing them or fetching weights.""" - return all( - importlib.util.find_spec(name) is not None - for name in ("numpy", "scipy", "torch", "transformers", "huggingface_hub", "safetensors") - ) - - -def _check_config(config: Any) -> None: - expected = { - "model_type": "mimi", - "sampling_rate": 24000, - "audio_channels": 1, - "num_quantizers": 32, - "use_cache": False, - "normalize": False, - "use_causal_conv": True, - "trim_right_ratio": 1.0, - } - if any(getattr(config, name, None) != value for name, value in expected.items()): - raise RuntimeError("Pinned Mimi configuration does not match the fixed inference profile") - - -@lru_cache(maxsize=2) -def load_pinned_model(*, local_files_only: bool = True) -> Any: - """Load built-in Transformers Mimi on CPU after checking both artifact hashes.""" - if not is_available(): - raise ImportError("Mimi requires numpy, scipy, torch, transformers, huggingface_hub, and safetensors") - hub = import_module("huggingface_hub") - paths: dict[str, Path] = {} - for filename, expected in (("config.json", CONFIG_SHA256), (CHECKPOINT_FILENAME, CHECKPOINT_SHA256)): - path = Path( - hub.hf_hub_download( - repo_id=MODEL_REPOSITORY, - filename=filename, - revision=MODEL_REVISION, - local_files_only=local_files_only, - ) - ) - if sha256_file(path) != expected: - raise RuntimeError(f"Pinned Mimi checkpoint digest mismatch for {filename}") - paths[filename] = path - if paths["config.json"].parent != paths[CHECKPOINT_FILENAME].parent: - raise RuntimeError("Pinned Mimi artifacts must share one snapshot directory") - torch = import_module("torch") - transformers = import_module("transformers") - config = transformers.MimiConfig.from_pretrained(str(paths["config.json"].parent), local_files_only=True) - _check_config(config) - model, loading = transformers.MimiModel.from_pretrained( - str(paths[CHECKPOINT_FILENAME].parent), - config=config, - local_files_only=True, - use_safetensors=True, - trust_remote_code=False, - dtype=torch.float32, - output_loading_info=True, - ) - if any(loading.get(key) for key in ("missing_keys", "unexpected_keys", "mismatched_keys", "error_msgs")): - raise RuntimeError(f"Pinned Mimi checkpoint did not load completely: {loading}") - _check_config(model.config) - log.info("Loaded pinned Mimi %s@%s on CPU (FP32, 32 quantizers)", MODEL_REPOSITORY, MODEL_REVISION) - return model.to("cpu").train(False) - - -def resynthesize(samples: Any, sample_rate: int, *, stereo_mode: str = "ms", local_files_only: bool = True) -> Any: - """Return full native mono/stereo samples without gain, clipping, or lag repair. - - Stereo defaults to raw mid/side; independent L/R is an internal comparison. - The official forward removes its own decoder's right excess using the input - mask. No external padding or chunking is applied. Exact counts are not proof - of learned phase preservation, speaker identity, or watermark removal. - """ - if not is_available(): - raise ImportError("Mimi requires the optional numerical and Transformers codec dependencies") - if stereo_mode not in {"ms", "lr"}: - raise ValueError("Mimi stereo mode must be ms or lr") - np = import_module("numpy") - torch = import_module("torch") - value = np.asarray(samples) - if value.ndim != 2 or not value.shape[0] or value.shape[1] not in (1, 2) or value.dtype.kind != "f": - raise ValueError("Mimi expects a nonempty floating (frames, 1 or 2 channels) matrix") - clock = src.RationalClock(int(value.shape[0]), sample_rate, model_rate=24000, hop=1, minimum_model_frames=1) - if not np.isfinite(value).all(): - raise ValueError("Mimi input must be finite") - value = np.asarray(value, dtype=np.float32) - if not np.isfinite(value).all(): - raise ValueError("Mimi input must be finite in float32") - prepared = src.forward(value, clock) - mid_side = value.shape[1] == 2 and stereo_mode == "ms" - if mid_side: - prepared = np.column_stack(((prepared[:, 0] + prepared[:, 1]) / 2, (prepared[:, 0] - prepared[:, 1]) / 2)) - if not np.isfinite(prepared).all(): - raise ValueError("Mimi prepared input must be finite") - with _MODEL_LOCK, torch.inference_mode(): - model = load_pinned_model(local_files_only=local_files_only) - inputs = torch.from_numpy(np.ascontiguousarray(prepared.T)).unsqueeze(1) - mask = torch.ones_like(inputs, dtype=torch.bool) - output = model(inputs, padding_mask=mask).audio_values - if tuple(output.shape) != (value.shape[1], 1, clock.model_frames): - raise RuntimeError("Mimi returned incorrect model sample geometry") - reconstructed = output[:, 0, :].cpu().numpy().T - if not np.isfinite(reconstructed).all(): - raise RuntimeError("Mimi returned nonfinite samples") - if mid_side: - reconstructed = np.column_stack( - (reconstructed[:, 0] + reconstructed[:, 1], reconstructed[:, 0] - reconstructed[:, 1]) - ) - delivered = src.inverse(reconstructed, clock) - if delivered.shape != value.shape or not np.isfinite(delivered).all(): - raise RuntimeError("Mimi returned invalid native sample geometry or values") - return delivered diff --git a/src/remove_ai_watermarks/_internal/audio_quality.py b/src/remove_ai_watermarks/_internal/audio_quality.py index d9968d7..9284980 100644 --- a/src/remove_ai_watermarks/_internal/audio_quality.py +++ b/src/remove_ai_watermarks/_internal/audio_quality.py @@ -10,7 +10,7 @@ from math import isfinite, log10, sqrt from typing import TYPE_CHECKING, Any from remove_ai_watermarks._internal import audio_io -from remove_ai_watermarks._internal.constants import AUDIO_LOSSY_OUTPUT_EXTENSIONS +from remove_ai_watermarks._internal.constants import AUDIO_LOSSY_OUTPUT_EXTENSIONS, AUDIO_OPUS_EXTENSIONS if TYPE_CHECKING: from collections.abc import Generator, Iterator @@ -108,8 +108,8 @@ def _opus_aligned_decode_info( strict_geometry: bool = False, ) -> tuple[audio_io.AudioStreamInfo, bool]: suffix = output.suffix.lower() - opus_clock = suffix in {".ogg", ".opus"} delivered = delivered_info if delivered_info is not None else audio_io.probe_audio(output, stream=stream) + opus_clock = suffix in AUDIO_OPUS_EXTENSIONS or delivered.codec == "opus" if strict_geometry: expected_sr = 48000 if opus_clock else info.sample_rate if (delivered.channels, delivered.sample_rate) != (info.channels, expected_sr): @@ -156,9 +156,11 @@ def measure_fidelity(source: Path, info: audio_io.AudioStreamInfo, output: Path, import numpy as np decode_info, opus_clock = _opus_aligned_decode_info(info, output, stream=stream, strict_geometry=True) + adts_padding = output.suffix.lower() == ".aac" + relaxed_len = opus_clock or adts_padding power = output_power = residual = max_error = peak = source_peak = 0.0 count = above = source_above = 0 - tail_slack = max(2, info.sample_rate // 100) if opus_clock else 0 + tail_slack = max(2, info.sample_rate // 100) if opus_clock else (4096 if adts_padding else 0) total_before = total_after = 0 win_target = max(1, info.sample_rate) win_min_tail = max(1, win_target // 4) @@ -201,7 +203,7 @@ def measure_fidelity(source: Path, info: audio_io.AudioStreamInfo, output: Path, total_before += len(before) if after is not None: total_after += len(after) - if not opus_clock: + if not relaxed_len: if before is None or after is None or before.shape != after.shape: raise RuntimeError("Delivered audio changed the decoded sample-frame count") pair_len = len(before) @@ -254,7 +256,7 @@ def measure_fidelity(source: Path, info: audio_io.AudioStreamInfo, output: Path, flush_window() if win_frames >= win_min_tail or (min_win_ratio is None and win_frames > 0): flush_window() - if opus_clock: + if relaxed_len: for extra_b in left: total_before += len(extra_b) for extra_a in right: diff --git a/src/remove_ai_watermarks/_internal/audio_vocoder.py b/src/remove_ai_watermarks/_internal/audio_vocoder.py deleted file mode 100644 index 0b3e2f5..0000000 --- a/src/remove_ai_watermarks/_internal/audio_vocoder.py +++ /dev/null @@ -1,137 +0,0 @@ -"""Optional pinned BigVGAN full-track FP32 resynthesis, with exact native clocks. - -This is a signal transform, not a watermark detector or a removal guarantee. -Stereo uses raw mid/side; mono uses one independent model pass. Other channel -layouts require separate qualification. No normalization, additional output clipping, -alignment, streaming, or automatic device fallback is performed. -""" - -from __future__ import annotations - -import hashlib -import importlib.util -import json -import logging -from functools import lru_cache -from importlib import import_module -from pathlib import Path -from typing import Any - -from remove_ai_watermarks._internal import audio_resampling as src -from remove_ai_watermarks._internal._bigvgan_network import build_generator, mel_spectrogram - -log = logging.getLogger(__name__) -MODEL_REPOSITORY = "nvidia/bigvgan_v2_44khz_128band_512x" -MODEL_REVISION = "95a9d1dcb12906c03edd938d77b9333d6ded7dfb" -SOURCE_REVISION = "7d2b454564a6c7d014227f635b7423881f14bdac" -CHECKPOINT_FILENAME = "bigvgan_generator.pt" -CHECKPOINT_SHA256 = "d9fe7ec6bd0b44ed9d66973d5012d8181c1570b01e5c72df51973e241dccd357" -CONFIG_SHA256 = "65b7f487bfaf15256056a75f6667ef5f640214c981922a111927873705ea4ddb" - - -def is_available() -> bool: - """Check optional dependencies without importing numerical runtimes.""" - return all( - importlib.util.find_spec(name) is not None for name in ("numpy", "scipy", "torch", "librosa", "huggingface_hub") - ) - - -def _verify_digest(path: Path, expected: str, label: str) -> None: - with path.open("rb") as stream: - actual = hashlib.file_digest(stream, "sha256").hexdigest() - if actual != expected: - raise RuntimeError(f"BigVGAN {label} digest mismatch: expected {expected}, got {actual}") - - -@lru_cache(maxsize=1) -def load_pinned_model(device: str = "cpu", *, local_files_only: bool = True) -> Any: - """Load only verified config/weights, with no downloaded Python execution. - - Cached artifacts are required by default. Explicit local_files_only=False - permits Hugging Face's pinned artifact download, never remote source code. - The cached in-memory model is reused without moving it between devices. - """ - if device not in ("cpu", "mps", "cuda"): - raise ValueError("BigVGAN device must be cpu, mps, or cuda") - if not is_available(): - raise RuntimeError("BigVGAN requires numpy, scipy, torch, librosa, and huggingface_hub") - torch = import_module("torch") - if device == "mps" and not torch.backends.mps.is_available(): - raise RuntimeError("Requested BigVGAN MPS device is unavailable") - if device == "cuda" and not torch.cuda.is_available(): - raise RuntimeError("Requested BigVGAN CUDA device is unavailable") - hub = import_module("huggingface_hub") - paths: dict[str, Path] = {} - for filename, digest in (("config.json", CONFIG_SHA256), (CHECKPOINT_FILENAME, CHECKPOINT_SHA256)): - path = Path( - hub.hf_hub_download( - repo_id=MODEL_REPOSITORY, - filename=filename, - revision=MODEL_REVISION, - local_files_only=local_files_only, - ) - ) - _verify_digest(path, digest, filename) - paths[filename] = path - config = json.loads(paths["config.json"].read_text(encoding="utf-8")) - model = build_generator(config) - payload = torch.load(paths[CHECKPOINT_FILENAME], map_location="cpu", weights_only=True) - if not isinstance(payload, dict) or "generator" not in payload: - raise RuntimeError("BigVGAN checkpoint has no generator state") - model.load_state_dict(payload["generator"], strict=True) - model.remove_weight_norm() - model.train(False).requires_grad_(False).float().to(device) - log.info("Loaded pinned BigVGAN %s@%s on %s (FP32)", MODEL_REPOSITORY, MODEL_REVISION, device) - return model - - -def resynthesize( - samples: Any, - sample_rate: int, - *, - device: str = "cpu", - local_files_only: bool = True, -) -> Any: - """Resynthesize a finite floating (frames, 1|2) matrix on its native grid. - - Full arrays are intentional: chunk boundaries require separate audio and - watermark qualification. Memory exhaustion fails rather than switching - device or silently chunking. FP32 MPS is numerically, not bitwise, CPU-like. - The generator retains its trained architecture's own final [-1, 1] clamp; - reconstructed L/R may exceed that range and is returned without clipping. - """ - if not is_available(): - raise RuntimeError("BigVGAN requires numpy, scipy, torch, librosa, and huggingface_hub") - np = import_module("numpy") - torch = import_module("torch") - value = np.asarray(samples) - if value.ndim != 2 or value.shape[0] == 0 or value.shape[1] not in (1, 2) or value.dtype.kind != "f": - raise ValueError("BigVGAN expects a nonempty floating (frames, 1 or 2 channels) matrix") - clock = src.RationalClock(int(value.shape[0]), sample_rate) - if not np.isfinite(value).all(): - raise ValueError("BigVGAN input must be finite") - value = np.asarray(value, dtype=np.float32) - if not np.isfinite(value).all(): - raise ValueError("BigVGAN input must be finite in float32") - if value.shape[1] == 2: - value = np.column_stack(((value[:, 0] + value[:, 1]) / 2, (value[:, 0] - value[:, 1]) / 2)) - prepared = src.pad_model(src.forward(value, clock), clock) - model = load_pinned_model(device, local_files_only=local_files_only) - output_channels: list[Any] = [] - with torch.inference_mode(): - for channel in range(value.shape[1]): - mel = mel_spectrogram(np.ascontiguousarray(prepared[:, channel])) - output = model(mel.to(device=device, dtype=torch.float32)) - if tuple(output.shape) != (1, 1, clock.padded_frames): - raise RuntimeError(f"BigVGAN returned unexpected shape {tuple(output.shape)}") - decoded = output[0, 0].detach().to(device="cpu", dtype=torch.float32).numpy() - if not np.isfinite(decoded).all(): - raise RuntimeError("BigVGAN returned nonfinite samples") - output_channels.append(src.inverse(src.unpad_model(decoded, clock), clock)) - result = np.column_stack(output_channels) - if result.shape[1] == 2: - mid, side = result[:, 0], result[:, 1] - result = np.column_stack((mid + side, mid - side)) - if result.shape != (clock.native_frames, value.shape[1]) or not np.isfinite(result).all(): - raise RuntimeError("BigVGAN returned invalid native-grid output") - return np.asarray(result, dtype=np.float32) diff --git a/src/remove_ai_watermarks/_internal/constants.py b/src/remove_ai_watermarks/_internal/constants.py index 2da3a26..463ade0 100644 --- a/src/remove_ai_watermarks/_internal/constants.py +++ b/src/remove_ai_watermarks/_internal/constants.py @@ -7,9 +7,9 @@ from typing import Literal, get_args from remove_ai_watermarks._internal._generated_c2pa_soft_bindings import C2PA_SOFT_BINDING_ROWS -AudioScheme = Literal["audioseal", "wavmark", "perth", "silentcipher", "silentcipher16", "all", "auto"] -AudioProfile = Literal["spectral", "encodec", "combined", "bigvgan", "mimi", "focalcodec", "dac", "snac"] -AudioMethod = Literal["auto", "spectral", "encodec", "combined", "bigvgan", "mimi", "focalcodec", "dac", "snac"] +AudioScheme = Literal["audioseal", "wavmark", "perth", "silentcipher", "all", "auto"] +AudioProfile = Literal["spectral", "encodec", "combined", "dac", "snac"] +AudioMethod = Literal["auto", "spectral", "encodec", "combined", "dac", "snac"] AudioVendor = Literal[ "auto", "google", @@ -28,7 +28,6 @@ AUDIO_SCHEMES: tuple[AudioScheme, ...] = ( "wavmark", "perth", "silentcipher", - "silentcipher16", "all", "auto", ) @@ -36,9 +35,6 @@ AUDIO_PROFILES: tuple[AudioProfile, ...] = ( "spectral", "encodec", "combined", - "bigvgan", - "mimi", - "focalcodec", "dac", "snac", ) @@ -47,10 +43,12 @@ AudioDevice = Literal["auto", "cpu", "mps", "cuda"] AUDIO_VOCODER_DEVICES: tuple[AudioDevice, ...] = ("auto", "cpu", "mps", "cuda") AUDIO_BANDWIDTHS_KBPS: tuple[int, ...] = (6, 12, 24) AUDIO_EXTENSIONS: tuple[str, ...] = (".wav", ".flac", ".mp3", ".m4a", ".ogg", ".oga", ".opus", ".aac", ".mka") -AUDIO_OUTPUT_EXTENSIONS: tuple[str, ...] = (".wav", ".flac", ".mp3", ".m4a", ".ogg", ".opus") -AUDIO_LOSSY_OUTPUT_EXTENSIONS: frozenset[str] = frozenset({".mp3", ".m4a", ".ogg", ".opus"}) +AUDIO_OUTPUT_EXTENSIONS: tuple[str, ...] = AUDIO_EXTENSIONS +AUDIO_OPUS_EXTENSIONS: frozenset[str] = frozenset({".ogg", ".oga", ".opus"}) +AUDIO_LOSSY_OUTPUT_EXTENSIONS: frozenset[str] = frozenset({".mp3", ".m4a", *AUDIO_OPUS_EXTENSIONS, ".aac"}) ISOBMFF_VIDEO_EXTENSIONS: frozenset[str] = frozenset({".mp4", ".mov", ".m4v"}) +VIDEO_EXTENSIONS: frozenset[str] = frozenset({*ISOBMFF_VIDEO_EXTENSIONS, ".mkv", ".webm", ".avi", ".flv"}) WanExperimentalProfile = Literal[ "wan21-synthid", @@ -64,7 +62,7 @@ WAN_EXPERIMENTAL_PROFILES: tuple[WanExperimentalProfile, ...] = ( "wan21-synthid-experimental", "wan21-seedance-experimental", ) -WAN_SUPPORTED_EXTENSIONS: frozenset[str] = ISOBMFF_VIDEO_EXTENSIONS +WAN_SUPPORTED_EXTENSIONS: frozenset[str] = VIDEO_EXTENSIONS VideoInvisibleProfile = Literal[ "auto", "synthid", diff --git a/src/remove_ai_watermarks/_internal/licenses/bigvgan/Alias-free-Apache-2.0.txt b/src/remove_ai_watermarks/_internal/licenses/bigvgan/Alias-free-Apache-2.0.txt deleted file mode 100644 index 56ee3c8..0000000 --- a/src/remove_ai_watermarks/_internal/licenses/bigvgan/Alias-free-Apache-2.0.txt +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. \ No newline at end of file diff --git a/src/remove_ai_watermarks/_internal/licenses/bigvgan/HiFiGAN-MIT.txt b/src/remove_ai_watermarks/_internal/licenses/bigvgan/HiFiGAN-MIT.txt deleted file mode 100644 index 5afae39..0000000 --- a/src/remove_ai_watermarks/_internal/licenses/bigvgan/HiFiGAN-MIT.txt +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2020 Jungil Kong - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file diff --git a/src/remove_ai_watermarks/_internal/licenses/bigvgan/Julius-MIT.txt b/src/remove_ai_watermarks/_internal/licenses/bigvgan/Julius-MIT.txt deleted file mode 100644 index 01ae553..0000000 --- a/src/remove_ai_watermarks/_internal/licenses/bigvgan/Julius-MIT.txt +++ /dev/null @@ -1,16 +0,0 @@ -Copyright 2020 Alexandre Défossez - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and -associated documentation files (the "Software"), to deal in the Software without restriction, -including without limitation the rights to use, copy, modify, merge, publish, distribute, -sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or -substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT -NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/src/remove_ai_watermarks/_internal/licenses/bigvgan/NOTICE.txt b/src/remove_ai_watermarks/_internal/licenses/bigvgan/NOTICE.txt deleted file mode 100644 index 3f0783e..0000000 --- a/src/remove_ai_watermarks/_internal/licenses/bigvgan/NOTICE.txt +++ /dev/null @@ -1,31 +0,0 @@ -BigVGAN inference adaptation - -Source: https://github.com/NVIDIA/BigVGAN -Source revision: 7d2b454564a6c7d014227f635b7423881f14bdac -Model: nvidia/bigvgan_v2_44khz_128band_512x -Model revision: 95a9d1dcb12906c03edd938d77b9333d6ded7dfb - -Copyright (c) 2024 NVIDIA CORPORATION. -BigVGAN generator and mel frontend: MIT (NVIDIA-MIT.txt). -HiFi-GAN generator ancestry: Copyright (c) 2020 Jungil Kong, -MIT (HiFiGAN-MIT.txt). -Snake activation ancestry: Copyright (c) 2020 Edward Dixon, -MIT (Snake-MIT.txt), https://github.com/EdwardDixon/snake. -Alias-free activation/filter/resampling: Apache License 2.0 -(Alias-free-Apache-2.0.txt), https://github.com/junjun3518/alias-free-torch. -Julius low-pass filter design included in the alias-free code: -Copyright 2020 Alexandre Defossez, MIT (Julius-MIT.txt), -https://github.com/adefossez/julius. - -Modified files: _bigvgan_network.py adapts portions of bigvgan.py, -activations.py, meldataset.py and alias_free_activation/torch/{act,filter,resample}.py. -Changes: lazy imports and nested builders, fixed inference-only AMPBlock1, -log-scale SnakeBeta and fixed ratio-two alias-free filters; training-only -initialization, unused architectures, old sinc fallback, plotting, Hub mixin, -CUDA extensions and console output removed. Parameter/buffer names and -inference calculations are retained. Mel calculations run in FP32 on CPU. -Audio clock handling and raw mid/side composition are package additions. - -The Apache-licensed portions remain Apache-2.0, not MIT. License files are -copied verbatim from the pinned upstream LICENSE and incl_licenses files. -No separate upstream NOTICE file was present in the retained source tree. diff --git a/src/remove_ai_watermarks/_internal/licenses/bigvgan/NVIDIA-MIT.txt b/src/remove_ai_watermarks/_internal/licenses/bigvgan/NVIDIA-MIT.txt deleted file mode 100644 index 4c78361..0000000 --- a/src/remove_ai_watermarks/_internal/licenses/bigvgan/NVIDIA-MIT.txt +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2024 NVIDIA CORPORATION. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/src/remove_ai_watermarks/_internal/licenses/bigvgan/Snake-MIT.txt b/src/remove_ai_watermarks/_internal/licenses/bigvgan/Snake-MIT.txt deleted file mode 100644 index 322b758..0000000 --- a/src/remove_ai_watermarks/_internal/licenses/bigvgan/Snake-MIT.txt +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2020 Edward Dixon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file diff --git a/src/remove_ai_watermarks/_internal/licenses/focalcodec/Apache-2.0.txt b/src/remove_ai_watermarks/_internal/licenses/focalcodec/Apache-2.0.txt deleted file mode 100644 index 3a504e7..0000000 --- a/src/remove_ai_watermarks/_internal/licenses/focalcodec/Apache-2.0.txt +++ /dev/null @@ -1,190 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - Copyright 2025 Luca Della Libera. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - https://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. \ No newline at end of file diff --git a/src/remove_ai_watermarks/_internal/licenses/focalcodec/NOTICE.txt b/src/remove_ai_watermarks/_internal/licenses/focalcodec/NOTICE.txt deleted file mode 100644 index 53fe05f..0000000 --- a/src/remove_ai_watermarks/_internal/licenses/focalcodec/NOTICE.txt +++ /dev/null @@ -1,151 +0,0 @@ -FocalCodec inference adaptation - -Source: https://github.com/lucadellalib/focalcodec -Source revision: cad8bf81d70875f756770449c34909d8b0951642 (v0.0.1) -Model: https://huggingface.co/lucadellalib/focalcodec_50hz -Model revision: d6d6d9524e52155c85193c2c3b8da1cf8842f019 - -Copyright 2025 Luca Della Libera. -Source and checkpoint license: Apache License 2.0 (Apache-2.0.txt). -The checkpoint is downloaded separately on demand, not bundled in this package. -Model availability does not establish watermark removal or voice preservation. - -Modified files: _focalcodec_network.py adapts portions of focalcodec/{codec, -wavlm,focalnet,bsq,vocos}.py from v0.0.1 so the pinned separate-QKV checkpoint -loads strictly without remapping or remote code execution. -Changes: lazy Torch imports and nested inference builders, fixed continuous -feature resynthesis (WavLM 6-layer encoder to Vocos ISTFT decoder) alongside -strict 355-key state verification across all five checkpoint submodules; JIT -exports, Hub download helpers, demo/test harnesses, and the unused kNN voice -conversion matcher (upstream NOTICE item 2, bshall/knn-vc) are omitted. -Symmetric (40, 40) WavLM receptive-field context, rational half-open clocks, -and raw mid/side stereo composition are package additions in audio_focalcodec.py. - -Applicable upstream third-party attribution notices from v0.0.1 NOTICE: - -------------------------------------------------------------------------------- -1. Code in focalcodec/bsq.py adapted from: - https://github.com/lucidrains/vector-quantize-pytorch/blob/3e4ce165774d3f5944f12ffb5ccd02848bb38df6/vector_quantize_pytorch/lookup_free_quantization.py - -MIT License - -Copyright (c) 2020 Phil Wang - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - -------------------------------------------------------------------------------- -2. Code in {focalcodec/focalnet.py, focalcodec/wavlm.py} adapted from: - https://github.com/huggingface/transformers/blob/v4.46.2/src/transformers/models/focalnet/modeling_focalnet.py - https://github.com/huggingface/transformers/blob/v4.46.2/src/transformers/models/wavlm/modeling_wavlm.py - -Copyright 2018- The Hugging Face team. All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. - -------------------------------------------------------------------------------- -3. Code in focalcodec/focalnet.py adapted from: - https://github.com/microsoft/FocalNet/blob/v1.0.1/classification/focalnet.py - -MIT License - -Copyright (c) Microsoft Corporation. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE - -------------------------------------------------------------------------------- -4. Code in focalcodec/vocos.py adapted from: - https://github.com/gemelo-ai/vocos/tree/v0.1.0/vocos/heads.py - https://github.com/gemelo-ai/vocos/tree/v0.1.0/vocos/models.py - https://github.com/gemelo-ai/vocos/tree/v0.1.0/vocos/modules.py - https://github.com/gemelo-ai/vocos/tree/v0.1.0/vocos/spectral_ops.py - -MIT License - -Copyright (c) 2023 Charactr Inc. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - -------------------------------------------------------------------------------- -5. Code in focalcodec/wavlm.py adapted from: - https://github.com/microsoft/unilm/blob/2d5b25f7cecc4ab4ad44f65de5899ef6aa8c53f5/wavlm/WavLM.py - https://github.com/microsoft/unilm/blob/2d5b25f7cecc4ab4ad44f65de5899ef6aa8c53f5/wavlm/modules.py - -The MIT License (MIT) - -Copyright (c) Microsoft Corporation - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/src/remove_ai_watermarks/_internal/licenses/mimi/NOTICE.txt b/src/remove_ai_watermarks/_internal/licenses/mimi/NOTICE.txt deleted file mode 100644 index e35d305..0000000 --- a/src/remove_ai_watermarks/_internal/licenses/mimi/NOTICE.txt +++ /dev/null @@ -1,18 +0,0 @@ -Mimi optional model attribution - -Mimi was developed by Kyutai. Model card authors: Alexandre Defossez, -Laurent Mazare, Manu Orsini, Amelie Royer, Patrick Perez, Herve Jegou, -Edouard Grave, Neil Zeghidour, and Yoach Lacombe. -Model: https://huggingface.co/kyutai/mimi -Revision: 89091b3e466eb6a9d11e537bf26b144f194978f7 -Weights license: Creative Commons Attribution 4.0 International (CC-BY-4.0). -https://creativecommons.org/licenses/by/4.0/ -The checkpoint is downloaded separately, not bundled or modified here. -Retain this attribution and the license link when redistributing the weights. -No endorsement by Kyutai is implied. - -Runtime implementation: Hugging Face Transformers MimiModel, Apache-2.0. -https://github.com/huggingface/transformers/tree/main/src/transformers/models/mimi -This wrapper uses the built-in implementation, fixed default 32 quantizers, -CPU float32, rational native clocks, and optional raw mid/side mapping. -Model availability does not establish watermark removal or voice preservation. diff --git a/src/remove_ai_watermarks/_internal/silentcipher16.py b/src/remove_ai_watermarks/_internal/silentcipher16.py deleted file mode 100644 index ccda588..0000000 --- a/src/remove_ai_watermarks/_internal/silentcipher16.py +++ /dev/null @@ -1,140 +0,0 @@ -"""Experimental SilentCipher-16k receiver for a terminated eight-symbol pattern. - -This profile accepts seven ternary payload symbols and one zero terminator. -It is not the published SDK byte API or the paper's general 32-bit profile. -The public API and CLI select this profile explicitly as ``silentcipher16``. -""" - -from __future__ import annotations - -import logging -from dataclasses import dataclass -from functools import lru_cache -from importlib import import_module -from typing import TYPE_CHECKING, Any, Literal - -from remove_ai_watermarks._internal import silentcipher as base - -if TYPE_CHECKING: - from numpy.typing import NDArray - -log = logging.getLogger(__name__) -MODEL_FILES = { - "16_khz/97561_iteration/dec_m_0.ckpt": "bf443c7298f6994284082c0039bf824c70560cd437869bf6f2643b1482fcba71", - "16_khz/97561_iteration/hparams.yaml": "e4c25258e2789aa30f7e31486df8d9e491eed78c3a2eeed45a59f2a2cb3560f9", -} -SAMPLE_RATE = 16000 -WINDOW_SECONDS = 3 -MIN_READ_SAMPLES = SAMPLE_RATE * WINDOW_SECONDS -PERIOD = 8 -MIN_CYCLES = 3 -THRESHOLD = 0.9 -HOP_LENGTH = 1024 -PHASE_STEP = 10 - - -@dataclass(frozen=True) -class SilentCipher16Reading: - """Recovered ternary symbols, or a negative for this experimental pattern. - - These symbols are not bytes. Agreement is not a watermark probability; - the diagnostic maximum includes invalid framing hypotheses on a negative. - """ - - payload_symbols: tuple[int, ...] | None - symbol_consistency: float - phase_offset: int | None - phases_checked: int - device: str - framing: Literal["terminated8"] = "terminated8" - - @property - def detected(self) -> bool: - return self.payload_symbols is not None - - -def is_available() -> bool: - return base.is_available() - - -@lru_cache(maxsize=3) -def load_model(device: str | None = None) -> base.DecoderModel: - if not is_available(): - raise ImportError("SilentCipher requires remove-ai-watermarks[audio-silentcipher]") - return base.load_decoder( - base.download_pinned_files(MODEL_FILES), - "16_khz/97561_iteration/dec_m_0.ckpt", - device, - message_dim=4, - message_band_size=512, - n_fft=2048, - ) - - -def _decode_sequence(raw: NDArray[Any]) -> tuple[tuple[int, ...] | None, float]: - import numpy as np - - stats = import_module("scipy.stats") - scores = np.asarray(raw) - if scores.ndim != 2 or scores.shape[0] != 4 or not np.isfinite(scores).all(): - raise base.ModelCheckError("SilentCipher-16k returned invalid raw neural values") - length = scores.shape[1] // PERIOD * PERIOD - if length < PERIOD * MIN_CYCLES: - raise base.ModelCheckError("SilentCipher-16k returned too few complete message repetitions") - predicted = np.argmax(scores, axis=0)[:length].reshape(-1, PERIOD) - symbols = np.asarray(stats.mode(predicted, axis=0, keepdims=False).mode, dtype=np.int64) - consistency = float(np.asarray(predicted == symbols[None], dtype=np.float64).mean()) - zeros = np.flatnonzero(symbols == 0) - if len(zeros) != 1: - return None, consistency - end = int(zeros[0]) - letters = np.concatenate([symbols[end + 1 :], symbols[:end]]) - 1 - return tuple(int(value) for value in letters), consistency - - -def _read_native(model: base.DecoderModel, samples: NDArray[Any]) -> SilentCipher16Reading: - import numpy as np - - from remove_ai_watermarks._internal._silentcipher_network import magnitude - - torch = import_module("torch") - power = np.mean(samples**2) - if not np.isfinite(power) or power <= 0: - raise base.ModelCheckError("SilentCipher-16k cannot normalize silent or invalid input power") - values = samples * np.sqrt(0.002837200844477648 / power) - signal = torch.from_numpy(values.copy()).unsqueeze(0).to(dtype=torch.float32, device=model.device) - best, checked = 0.0, 0 - with base.MODEL_LOCK, torch.inference_mode(): - for shift in range(0, HOP_LENGTH, PHASE_STEP): - carrier = magnitude(signal[:, shift:], model.window, n_fft=2048, hop_length=HOP_LENGTH) - raw = model.decoder(carrier[:, None]) - if tuple(raw.shape[:3]) != (1, 1, 4): - raise base.ModelCheckError("SilentCipher-16k returned an invalid neural output shape") - payload, consistency = _decode_sequence(raw[0, 0].detach().cpu().numpy()) - checked += 1 - best = max(best, consistency) - if payload is not None and consistency >= THRESHOLD: - return SilentCipher16Reading(payload, consistency, shift, checked, model.device) - return SilentCipher16Reading(None, best, None, checked, model.device) - - -def read(model: base.DecoderModel, samples: object, *, sample_rate: int = SAMPLE_RATE) -> SilentCipher16Reading: - import numpy as np - - array = np.asarray(samples, dtype=np.float32) - if array.ndim != 1 or sample_rate <= 0 or len(array) < WINDOW_SECONDS * sample_rate or not np.isfinite(array).all(): - raise ValueError("SilentCipher-16k requires at least three seconds of finite mono audio") - if sample_rate != SAMPLE_RATE: - librosa = import_module("librosa") - array = np.asarray(librosa.resample(array, orig_sr=sample_rate, target_sr=SAMPLE_RATE), dtype=np.float32) - if len(array) < MIN_READ_SAMPLES or not np.isfinite(array).all(): - raise RuntimeError("SilentCipher-16k resampling returned invalid samples") - try: - return _read_native(model, array) - except base.ModelCheckError: - raise - except RuntimeError as exc: - if model.device == "cpu": - raise - log.warning("SilentCipher-16k %s check failed; retrying on CPU: %s", model.device, exc) - return _read_native(load_model("cpu"), array) diff --git a/src/remove_ai_watermarks/audio.py b/src/remove_ai_watermarks/audio.py index d30cff8..39cfbd2 100644 --- a/src/remove_ai_watermarks/audio.py +++ b/src/remove_ai_watermarks/audio.py @@ -14,16 +14,12 @@ from remove_ai_watermarks import metadata from remove_ai_watermarks._internal import ( audio_codec, audio_dac, - audio_focalcodec, audio_io, - audio_mimi, audio_snac, audio_spectral, - audio_vocoder, audioseal, perth, silentcipher, - silentcipher16, wavmark, ) from remove_ai_watermarks._internal.audio_quality import ( @@ -64,14 +60,13 @@ from remove_ai_watermarks._internal.constants import ( log = logging.getLogger(__name__) AudioWatermarkStatus = Literal["detected", "not_detected", "unverified"] -_NAMED_SCHEMES = ("audioseal", "wavmark", "perth", "silentcipher", "silentcipher16") +_NAMED_SCHEMES = ("audioseal", "wavmark", "perth", "silentcipher") _AUTO_SCHEMES = ("audioseal", "wavmark", "perth") _AUTO_PROFILES: dict[AudioScheme, tuple[AudioProfile, ...]] = { "audioseal": ("spectral", "combined"), "wavmark": ("encodec", "combined"), "perth": ("spectral", "combined"), "silentcipher": ("encodec", "combined"), - "silentcipher16": ("encodec", "combined"), "all": ("combined",), "auto": ("spectral", "combined"), } @@ -81,7 +76,6 @@ AudioModelReading = ( | wavmark.WavMarkSignatureReading | perth.PerthReading | silentcipher.SilentCipherReading - | silentcipher16.SilentCipher16Reading ) _MAX_WHOLE_SECONDS = 30 _MAX_WHOLE_VALUES = 16_000_000 @@ -282,10 +276,9 @@ def _model_samples(samples: NDArray[Any], sample_rate: int) -> NDArray[Any]: def _read_model( model: Any, samples: NDArray[Any], rate: int, scheme: str, *, native_audioseal: bool = False ) -> tuple[AudioModelReading | None, str | None, bool]: - if scheme in {"silentcipher", "silentcipher16"}: - backend = silentcipher16 if scheme == "silentcipher16" else silentcipher + if scheme == "silentcipher": try: - return backend.read(model, samples, sample_rate=rate), None, False + return silentcipher.read(model, samples, sample_rate=rate), None, False except (RuntimeError, ValueError) as exc: log.warning( "SilentCipher check failed: scheme=%s sample_rate=%s sample_count=%s error=%s", @@ -398,7 +391,6 @@ def _scan_audio_at_clock( "wavmark": wavmark.load_model, "perth": perth.load_model, "silentcipher": silentcipher.load_model, - "silentcipher16": silentcipher16.load_model, }[scheme] model = loader() channels: list[int | Literal["mix"]] = list(range(info.channels)) @@ -408,8 +400,7 @@ def _scan_audio_at_clock( segments: dict[int | Literal["mix"], list[AudioWindowReading]] = {channel: [] for channel in channels} count = 0 previous = np.empty((0, info.channels), dtype=np.float32) - window_seconds = {"silentcipher": silentcipher.WINDOW_SECONDS, "silentcipher16": silentcipher16.WINDOW_SECONDS} - window_frames = info.sample_rate * window_seconds.get(scheme, 1) + window_frames = info.sample_rate * (silentcipher.WINDOW_SECONDS if scheme == "silentcipher" else 1) max_segment_frames = min( _MAX_WHOLE_SECONDS * info.sample_rate, max(window_frames, _MAX_WHOLE_VALUES // max(1, info.channels)), @@ -482,8 +473,6 @@ def _scan_audio_at_clock( decoder_rate = info.sample_rate if native_audioseal else audioseal.SAMPLE_RATE elif scheme == "silentcipher": decoder_rate = silentcipher.SAMPLE_RATE - elif scheme == "silentcipher16": - decoder_rate = silentcipher16.SAMPLE_RATE detections.append( AudioDetection( scheme, @@ -510,18 +499,7 @@ def _scan_audio_at_clock( "A matching public-model mark does not identify LTX." ) elif scheme == "silentcipher": - caveats.append( - "SilentCipher checks use the pinned 44.1 kHz model, including for 16 kHz input audio. " - "This receiver excludes the 16 kHz model. Separate silentcipher16 checks cover only an experimental " - "terminated eight-symbol pattern, not the incompatible SDK byte API or general 32-bit framing." - ) - elif scheme == "silentcipher16": - caveats.append( - "SilentCipher-16k checks cover only an experimental terminated eight-symbol pattern. " - "payload_symbols contains seven ternary symbols, not bytes. The SDK byte API and general 32-bit " - "profile remain unqualified. Known-message recovery failed on exploratory tone and noise carriers. " - "A negative does not rule out other framing or certify erasure of every residual payload bit." - ) + caveats.append("SilentCipher checks use the pinned 44.1 kHz model, including for 16 kHz input audio.") if multi_segment: caveats.append("Long-clip decoding used bounded overlapping segments alongside all sample windows.") if any( @@ -590,18 +568,14 @@ def resolve_audio_device( """Resolve ``auto`` to the fastest verified accelerator for neural audio codecs.""" if requested != "auto": return requested - if method in {"spectral", "mimi", "focalcodec"}: + if method == "spectral": return "cpu" try: import torch if torch.cuda.is_available(): return "cuda" - if ( - method in {"dac", "snac", "bigvgan"} - and hasattr(torch.backends, "mps") - and torch.backends.mps.is_available() - ): + if method in {"dac", "snac"} and hasattr(torch.backends, "mps") and torch.backends.mps.is_available(): return "mps" except Exception: return "cpu" @@ -648,7 +622,7 @@ def identify_audio( scans every installed compatible decoder without requiring absent optional extras. """ if scheme not in _AUTO_PROFILES: - raise ValueError("Audio scheme must be audioseal, wavmark, perth, silentcipher, silentcipher16, all, or auto") + raise ValueError("Audio scheme must be audioseal, wavmark, perth, silentcipher, all, or auto") path, info = _source(source, stream) digest = sha256_file(path) markers = dict(_metadata_markers) if _metadata_markers is not None else metadata.get_ai_metadata(path) @@ -659,14 +633,12 @@ def identify_audio( "wavmark": wavmark.is_available, "perth": perth.is_available, "silentcipher": silentcipher.is_available, - "silentcipher16": silentcipher16.is_available, } extras = { "audioseal": "audio-detect", "wavmark": "audio-wavmark", "perth": "audio-perth", "silentcipher": "audio-silentcipher", - "silentcipher16": "audio-silentcipher", } if not check_invisible: caveats.append("Audio watermark decoding was skipped.") @@ -761,13 +733,7 @@ def verification_outcome(before: AudioProvenanceReport, after: AudioProvenanceRe def _require_base_audio_runtime(method: str) -> None: if not audio_io.is_available() or not audio_spectral.is_available(): - extra = ( - "audio-vocoder" - if method == "bigvgan" - else "audio-codec" - if method in {"mimi", "focalcodec", "dac", "snac"} - else "audio" - ) + extra = "audio-codec" if method in {"dac", "snac"} else "audio" raise ImportError(f"Audio processing requires 'remove-ai-watermarks[{extra}]' and ffmpeg") @@ -775,22 +741,16 @@ def require_audio_profile_runtime(method: AudioProfile) -> None: """Ensure runtime dependencies for a concrete audio processing profile are installed.""" if method in {"encodec", "combined"} and not audio_codec.is_available(): raise ImportError("Neural audio processing requires remove-ai-watermarks[audio-codec]") - if method == "mimi" and not audio_mimi.is_available(): - raise ImportError("Mimi processing requires remove-ai-watermarks[audio-codec]") - if method == "focalcodec" and not audio_focalcodec.is_available(): - raise ImportError("FocalCodec processing requires remove-ai-watermarks[audio-codec]") if method == "dac" and not audio_dac.is_available(): raise ImportError("DAC processing requires remove-ai-watermarks[audio-codec]") if method == "snac" and not audio_snac.is_available(): raise ImportError("SNAC processing requires remove-ai-watermarks[audio-codec]") - if method == "bigvgan" and not audio_vocoder.is_available(): - raise ImportError("BigVGAN processing requires remove-ai-watermarks[audio-vocoder]") _require_base_audio_runtime(method) _SURROUND_51_LAYOUTS: frozenset[str] = frozenset({"5.1", "5.1(side)"}) _SURROUND_71_LAYOUTS: frozenset[str] = frozenset({"7.1", "7.1(wide)", "7.1(wide-side)"}) -_RAW_CODEC_PROFILES: frozenset[str] = frozenset({"bigvgan", "mimi", "focalcodec", "dac", "snac"}) +_RAW_CODEC_PROFILES: frozenset[str] = frozenset({"dac", "snac"}) def _is_mono_or_stereo(info: audio_io.AudioStreamInfo) -> bool: @@ -804,19 +764,11 @@ def _is_tagged_surround(info: audio_io.AudioStreamInfo) -> bool: def validate_audio_stream_for_profile(info: audio_io.AudioStreamInfo, method: AudioProfile) -> None: - """Validate channel layout and bounded full-track limits for a selected audio profile.""" + """Validate channel layout for a selected audio profile.""" if method in {"dac", "snac"}: label = "DAC" if method == "dac" else "SNAC" if not (_is_mono_or_stereo(info) or _is_tagged_surround(info)): raise ValueError(f"{label} requires a mono or stereo (or tagged 5.1/7.1) channel layout") - elif method in {"bigvgan", "mimi", "focalcodec"} and not _is_mono_or_stereo(info): - label = {"bigvgan": "BigVGAN", "mimi": "Mimi", "focalcodec": "FocalCodec"}[method] - raise ValueError(f"{label} requires a mono or stereo channel layout") - if method in {"bigvgan", "mimi"} and info.duration is not None: - label = "BigVGAN" if method == "bigvgan" else "Mimi" - est_frames = int(info.duration * info.sample_rate) - if est_frames > _MAX_WHOLE_SECONDS * info.sample_rate or est_frames * info.channels > _MAX_WHOLE_VALUES: - raise ValueError(f"{label} full-track processing is limited to 30 seconds and 16000000 sample values") def normalize_audio_vendor(vendor: str | None) -> str | None: @@ -857,7 +809,7 @@ def adaptive_auto_profiles( detected = {item.scheme for item in before.detections if item.status == "detected"} if detected and detected <= {"audioseal", "perth"}: return ("spectral", "combined") - if detected and detected <= {"wavmark", "silentcipher", "silentcipher16"}: + if detected and detected <= {"wavmark", "silentcipher"}: return ("encodec", "combined") return ("combined",) @@ -896,15 +848,13 @@ def validate_audio_arguments( if not verify and not (force or allow_unverified or explicit_vendor is not None): raise ValueError("Disabling verification requires force=True or allow_unverified=True") if method not in AUDIO_METHODS: - raise ValueError( - "Audio method must be auto, spectral, encodec, combined, bigvgan, mimi, focalcodec, dac, or snac" - ) + raise ValueError("Audio method must be auto, spectral, encodec, combined, dac, or snac") if vocoder_device not in AUDIO_VOCODER_DEVICES: raise ValueError("Vocoder device must be auto, cpu, mps, or cuda") - if vocoder_device not in {"auto", "cpu"} and method in {"spectral", "mimi", "focalcodec"}: - raise ValueError("A non-CPU vocoder device requires method=bigvgan, dac, snac, encodec, combined, or auto") + if vocoder_device not in {"auto", "cpu"} and method == "spectral": + raise ValueError("A non-CPU vocoder device requires method=dac, snac, encodec, combined, or auto") if scheme not in _AUTO_PROFILES: - raise ValueError("Audio scheme must be audioseal, wavmark, perth, silentcipher, silentcipher16, all, or auto") + raise ValueError("Audio scheme must be audioseal, wavmark, perth, silentcipher, all, or auto") if method in {"auto", "encodec", "combined"} and bandwidth_kbps not in AUDIO_BANDWIDTHS_KBPS: raise ValueError("EnCodec bandwidth must be 6, 12, or 24 kbps") return _AUTO_PROFILES[scheme] if method == "auto" else (method,) @@ -964,15 +914,12 @@ def remove_audio_invisible( while keeping positive-detection and quality gates active; ``allow_positive=True`` permits a still-positive output; ``allow_quality_override=True`` overrides a failed integrity gate; ``force=True`` remains an alias enabling all three. - Output files (.wav, .flac, .mp3, .m4a, .ogg, .opus) discard metadata and - preserve channel geometry. - Explicit bigvgan, mimi, and focalcodec are experimental bounded full-track - raw M/S profiles, excluded from auto; dac is selected by auto only when - pre-strip metadata identifies ElevenLabs or Google SynthID. None supplies a - SynthID verifier. Mimi, FocalCodec, and DAC use CPU float32 (fixed - 32-quantizer Mimi; conditioned 50 Hz WavLM-to-Vocos FocalCodec; 3-codebook - 44.1 kHz DAC); BigVGAN retains its selected device. Codec reconstruction - does not guarantee voice identity. + Output files (.wav, .flac, .mp3, .m4a, .ogg, .oga, .opus, .aac, .mka) + discard metadata and preserve channel geometry. + Auto routes ElevenLabs and Google SynthID metadata to DAC (44.1 kHz, + 3-codebook, with default 14 kHz high-frequency preservation on >= 44.1 kHz + tracks) and falls back to SNAC/EnCodec/spectral as configured. Codec + reconstruction does not guarantee voice identity. """ explicit_vendor = _normalize_audio_vendor(vendor) eff_allow_unverified = allow_unverified or explicit_vendor is not None @@ -1096,7 +1043,7 @@ def _remove_audio_profile( if not verify and not eff_unverified: raise ValueError("Disabling verification requires force=True or allow_unverified=True") if method not in AUDIO_PROFILES: - raise ValueError("Audio method must be spectral, encodec, combined, bigvgan, mimi, focalcodec, dac, or snac") + raise ValueError("Audio method must be spectral, encodec, combined, dac, or snac") neural = method in {"encodec", "combined"} if neural and bandwidth_kbps not in AUDIO_BANDWIDTHS_KBPS: raise ValueError("EnCodec bandwidth must be 6, 12, or 24 kbps") @@ -1184,15 +1131,10 @@ def _remove_audio_profile( stereo_mode=stereo_mode, device=resolved_device, ) - if method == "bigvgan": - transformed = _vocode_full_track(transformed, before.stream.sample_rate, resolved_device) - if method == "mimi": - transformed = _mimi_full_track(transformed, before.stream.sample_rate) - if method == "focalcodec": - transformed = _focalcodec_full_track(transformed, before.stream.sample_rate) if method == "dac": + eff_hf = 14000.0 if (preserve_hf_hz is None and before.stream.sample_rate >= 44100) else preserve_hf_hz transformed = _dac_full_track( - transformed, before.stream.sample_rate, resolved_device, preserve_hf_hz=preserve_hf_hz + transformed, before.stream.sample_rate, resolved_device, preserve_hf_hz=eff_hf ) if method == "snac": transformed = _snac_full_track( @@ -1264,30 +1206,6 @@ missing_decoder_reason = _missing_decoder_reason remove_audio_profile = _remove_audio_profile -def _vocode_full_track( - chunks: Iterator[NDArray[Any]], sample_rate: int, device: Literal["cpu", "mps", "cuda"] -) -> Iterator[NDArray[Any]]: - """Use the bounded collector without changing BigVGAN math or arguments.""" - samples = _collect_full_track(chunks, sample_rate, "BigVGAN") - yield audio_vocoder.resynthesize(samples, sample_rate, device=device, local_files_only=False) - - -def _mimi_full_track(chunks: Iterator[NDArray[Any]], sample_rate: int) -> Iterator[NDArray[Any]]: - """Apply the explicit experimental CPU Mimi profile to one complete track.""" - samples = _collect_full_track(chunks, sample_rate, "Mimi") - yield audio_mimi.resynthesize(samples, sample_rate, local_files_only=False) - - -def _focalcodec_full_track(chunks: Iterator[NDArray[Any]], sample_rate: int) -> Iterator[NDArray[Any]]: - """Apply the explicit experimental CPU FocalCodec feature profile across short or long tracks.""" - yield from _stream_neural_track( - chunks, - sample_rate, - "FocalCodec", - lambda samples: audio_focalcodec.resynthesize_conditioned(samples, sample_rate, local_files_only=False), - ) - - def _lowpass_lfe_channel(lfe: NDArray[Any], sample_rate: int) -> NDArray[Any]: """Strip out-of-band watermark energy (>120 Hz) from LFE while preserving subwoofer bass.""" import numpy as np @@ -1436,7 +1354,8 @@ def _stream_neural_track( eof = True return False if chunk.ndim != 2 or chunk.shape[1] not in allowed_channels: - raise ValueError(f"{label} processing requires mono or stereo") + expected = "mono, stereo, 5.1, or 7.1" if allow_surround else "mono or stereo" + raise ValueError(f"{label} processing requires {expected}") if channels is None: channels = int(chunk.shape[1]) elif int(chunk.shape[1]) != channels: @@ -1513,29 +1432,6 @@ def _stream_neural_track( close() -def _collect_full_track(chunks: Iterator[NDArray[Any]], sample_rate: int, label: str) -> NDArray[Any]: - """Bound full-track inference and close the producer before invoking a model.""" - import numpy as np - - collected: list[NDArray[Any]] = [] - count = 0 - try: - for chunk in chunks: - count += len(chunk) - if count > _MAX_WHOLE_SECONDS * sample_rate or count * chunk.shape[1] > _MAX_WHOLE_VALUES: - raise ValueError(f"{label} full-track processing is limited to 30 seconds and 16000000 sample values") - if chunk.shape[1] not in (1, 2): - raise ValueError(f"{label} full-track processing requires mono or stereo") - collected.append(chunk) - finally: - close = getattr(chunks, "close", None) - if callable(close): - close() - if not collected: - raise ValueError(f"{label} requires nonempty audio") - return np.concatenate(collected, axis=0) - - def _audio_source(source: str | Path) -> Path: path = Path(source).expanduser() if not path.exists(): diff --git a/src/remove_ai_watermarks/cli.py b/src/remove_ai_watermarks/cli.py index 6894bd2..277eaca 100644 --- a/src/remove_ai_watermarks/cli.py +++ b/src/remove_ai_watermarks/cli.py @@ -1273,7 +1273,7 @@ def _audio_method_options(func: Any) -> Any: type=click.Choice(list(AUDIO_VOCODER_DEVICES)), default=AUDIO_VOCODER_DEVICES[0], show_default=True, - help="Neural audio inference device for BigVGAN, DAC, EnCodec, and combined; CPU-only profiles require cpu.", + help="Neural audio inference device for DAC, SNAC, EnCodec, and combined; spectral requires cpu.", )(func) func = click.option( "--bandwidth", @@ -1288,8 +1288,8 @@ def _audio_method_options(func: Any) -> Any: default=AUDIO_METHODS[0], show_default=True, help=( - "Select automatically, or choose spectral, EnCodec, combined, or full-track " - "BigVGAN, experimental CPU Mimi / CPU FocalCodec, or 44.1 kHz DAC (no SynthID decoder)." + "Select automatically, or choose spectral, EnCodec, combined, 44.1 kHz DAC, " + "or 44.1 kHz SNAC (fast on Apple Silicon MPS)." ), )(func) @@ -1341,9 +1341,8 @@ def _audio_check_label(scheme: str) -> str: "audioseal": "open AudioSeal", "wavmark": "public WavMark", "perth": "public Perth v1", - "silentcipher": "public SilentCipher-44k experimental receiver", - "silentcipher16": "public SilentCipher-16k experimental terminated pattern", - "all": "AudioSeal, WavMark, Perth v1, SilentCipher-44k, and the SilentCipher-16k terminated pattern", + "silentcipher": "public SilentCipher-44k", + "all": "AudioSeal, WavMark, Perth v1, and SilentCipher-44k", "auto": "installed compatible public audio watermark", }[scheme] @@ -1455,7 +1454,7 @@ def cmd_audio_metadata( "-o", "--output", type=click.Path(dir_okay=False, path_type=Path), - help="Output WAV, FLAC, MP3, M4A, OGG, or Opus, default SOURCE_processed.wav.", + help="Output WAV, FLAC, MP3, M4A, OGG, OGA, Opus, AAC, or MKA, default SOURCE_processed.wav.", ) @click.option( "--force", @@ -1955,7 +1954,12 @@ def cmd_video_message_detect( @cmd_video_message.command("remove") @_video_message_options @click.argument("source", type=click.Path(exists=True, dir_okay=False, path_type=Path)) -@click.option("-o", "--output", type=click.Path(dir_okay=False, path_type=Path), help="Output MP4, MOV, or M4V.") +@click.option( + "-o", + "--output", + type=click.Path(dir_okay=False, path_type=Path), + help="Output MP4, MOV, M4V, MKV, WebM, AVI, or FLV.", +) @click.option( "--method", type=click.Choice(list(VIDEO_MESSAGE_METHODS)), @@ -3005,14 +3009,14 @@ def cmd_text_invisible( @click.option("--strict-residual", is_flag=True, help="With Ollama, regenerate retained sentences in a second pass.") def cmd_text_all( source: Path, - output: Path | None, - invisible: bool, - seed: int, - allow_partial: bool, - rewriter_backend: _TextBackend, - rewriter_model: str | None, - ollama_url: str | None, - strict_residual: bool, + output: Path | None = None, + invisible: bool = False, + seed: int = 0, + allow_partial: bool = False, + rewriter_backend: _TextBackend = "transformers", + rewriter_model: str | None = None, + ollama_url: str | None = None, + strict_residual: bool = False, ) -> None: """Strip deterministic text provenance and optionally regenerate prose spans.""" from remove_ai_watermarks.text import remove_text_all @@ -3098,7 +3102,7 @@ def cmd_identify(ctx: click.Context, source: Path, no_visible: bool, as_json: bo ctx.invoke( cmd_audio_identify, source=source, - check_invisible=not no_visible, + no_invisible=no_visible, stream=0, as_json=as_json, scheme="auto", @@ -3224,9 +3228,8 @@ def _resolve_preset( backend: str, ) -> tuple[bool, str, bool]: eff_force = force or preset == "deep-clean" - eff_backend = "auto" if preset in {"balanced", "deep-clean"} and backend == "cv2" else backend lossless_only = preset == "lossless-fast" and not force - return eff_force, eff_backend, lossless_only + return eff_force, backend, lossless_only # ── Combined "all" mode ── diff --git a/src/remove_ai_watermarks/mcp_server.py b/src/remove_ai_watermarks/mcp_server.py index d64790d..7f9ec62 100644 --- a/src/remove_ai_watermarks/mcp_server.py +++ b/src/remove_ai_watermarks/mcp_server.py @@ -162,7 +162,7 @@ for _name, _description, _options in ( ), ( "audio_invisible", - "Process one audio track to WAV, FLAC, MP3, M4A, OGG, or Opus. Default publication requires " + "Process one audio track to WAV, FLAC, MP3, M4A, OGG, OGA, Opus, AAC, or MKA. Default publication requires " "a compatible source positive under the requested models and a fully negative saved output. " "Force permits explicitly unverified results.", {}, @@ -199,10 +199,7 @@ for _name, _description, _options in ( "type": "string", "enum": list(AUDIO_METHODS), "default": AUDIO_METHODS[0], - "description": ( - "SNAC, Mimi, FocalCodec, DAC, and BigVGAN are explicit full-track neural-codec profiles, " - "not SynthID decoders." - ), + "description": ("DAC and SNAC are explicit 44.1 kHz neural-codec profiles, not SynthID decoders."), }, "vocoder_device": { "type": "string", diff --git a/src/remove_ai_watermarks/video.py b/src/remove_ai_watermarks/video.py index f2a8601..77abd42 100644 --- a/src/remove_ai_watermarks/video.py +++ b/src/remove_ai_watermarks/video.py @@ -17,6 +17,7 @@ from typing import TYPE_CHECKING, Any, Literal, cast from remove_ai_watermarks._internal.constants import ( ISOBMFF_VIDEO_EXTENSIONS, + VIDEO_EXTENSIONS, VIDEO_INVISIBLE_PROFILES, VIDEO_PROFILE_ALIASES, WAN_EXPERIMENTAL_PROFILES, @@ -47,7 +48,8 @@ if TYPE_CHECKING: from remove_ai_watermarks.video_visible import VideoScan from remove_ai_watermarks.video_wan import VideoWanRuntime -VIDEO_EXTENSIONS: frozenset[str] = frozenset({".mp4", ".mov", ".m4v", ".webm", ".mkv", ".avi", ".flv"}) +# Re-exported from _internal.constants for callers importing VIDEO_EXTENSIONS from video. +_VIDEO_EXTENSIONS_EXPORT: frozenset[str] = VIDEO_EXTENSIONS VIDEO_VISIBLE_MARKS = ( "sora", "veo", @@ -73,9 +75,8 @@ _ISOBMFF_VIDEO_EXTENSIONS: frozenset[str] = ISOBMFF_VIDEO_EXTENSIONS _EBML_VIDEO_EXTENSIONS: frozenset[str] = frozenset({".webm", ".mkv"}) _RIFF_VIDEO_EXTENSIONS: frozenset[str] = frozenset({".avi"}) _FLV_VIDEO_EXTENSIONS: frozenset[str] = frozenset({".flv"}) -_REGENERATED_VIDEO_EXTENSIONS: frozenset[str] = frozenset({*_ISOBMFF_VIDEO_EXTENSIONS, ".mkv", ".webm"}) +_REGENERATED_VIDEO_EXTENSIONS: frozenset[str] = VIDEO_EXTENSIONS _EXPECTED_REGENERATED_VIDEO_EXTENSIONS = ", ".join(sorted(_REGENERATED_VIDEO_EXTENSIONS)) -_EXPECTED_WAN_VIDEO_EXTENSIONS = ", ".join(sorted(_ISOBMFF_VIDEO_EXTENSIONS)) def _require_video_runtime() -> None: @@ -1237,7 +1238,7 @@ def _resolve_video_invisible_profile( from remove_ai_watermarks import video_wan can_wan = video_wan.can_run_wan_on_source(source_path, device=device, runtime=runtime, for_auto=True) - if not can_wan and (seed != 0 or source_path.suffix.lower() != ".mp4"): + if not can_wan and seed != 0: resolved = "synthid" else: from remove_ai_watermarks.metadata import get_ai_metadata @@ -1476,21 +1477,8 @@ def remove_video_all( ) explicit_invisible = include_invisible is True auto_invisible = include_invisible == "auto" - norm_invisible_profile = _normalize_video_profile(invisible_profile) - if ( - explicit_invisible - and norm_invisible_profile == "seedance-experimental" - and source_path.suffix.lower() != ".mp4" - ): - raise ValueError("Seedance processing requires MP4 input") - if ( - explicit_invisible - and norm_invisible_profile in WAN_EXPERIMENTAL_PROFILES - and source_path.suffix.lower() not in _ISOBMFF_VIDEO_EXTENSIONS - ): - raise ValueError(f"Wan 2.1 processing requires one of: {_EXPECTED_WAN_VIDEO_EXTENSIONS}") if explicit_invisible and source_path.suffix.lower() not in _REGENERATED_VIDEO_EXTENSIONS: - raise ValueError(f"Video SynthID regeneration requires one of: {_EXPECTED_REGENERATED_VIDEO_EXTENSIONS}") + raise ValueError(f"Video invisible regeneration requires one of: {_EXPECTED_REGENERATED_VIDEO_EXTENSIONS}") from remove_ai_watermarks.audio import normalize_audio_vendor preflight_befores: tuple[AudioProvenanceReport, ...] = () @@ -2048,13 +2036,7 @@ def remove_video_batch( else: norm_prof = _normalize_video_profile(invisible_profile) needs_wan = norm_prof in WAN_EXPERIMENTAL_PROFILES - if norm_prof == "seedance-experimental": - allowed_exts = {".mp4"} - elif needs_wan: - allowed_exts = _ISOBMFF_VIDEO_EXTENSIONS - else: - allowed_exts = _REGENERATED_VIDEO_EXTENSIONS - if source_path.suffix.lower() in allowed_exts: + if source_path.suffix.lower() in _REGENERATED_VIDEO_EXTENSIONS: selected_runtime = _get_batch_runtime("wan" if needs_wan else "vae") all_result = remove_video_all( source_path, @@ -2311,8 +2293,8 @@ def remove_video_seedance_experimental( from remove_ai_watermarks.metadata import get_ai_metadata source_path = _video_source(source) - if source_path.suffix.lower() != ".mp4": - raise ValueError("Experimental Seedance processing requires MP4 input") + if source_path.suffix.lower() not in _REGENERATED_VIDEO_EXTENSIONS: + raise ValueError(f"Seedance processing requires one of: {_EXPECTED_REGENERATED_VIDEO_EXTENSIONS}") if quality not in {"delivery", "master"}: raise ValueError("quality must be delivery or master") _require_video_runtime() @@ -2360,8 +2342,8 @@ def remove_video_wan_experimental( from remove_ai_watermarks.metadata import get_ai_metadata source_path = _video_source(source) - if source_path.suffix.lower() not in _ISOBMFF_VIDEO_EXTENSIONS: - raise ValueError(f"Experimental Wan 2.1 processing requires one of: {_EXPECTED_WAN_VIDEO_EXTENSIONS}") + if source_path.suffix.lower() not in _REGENERATED_VIDEO_EXTENSIONS: + raise ValueError(f"Wan 2.1 processing requires one of: {_EXPECTED_REGENERATED_VIDEO_EXTENSIONS}") if profile not in WAN_EXPERIMENTAL_PROFILES: raise ValueError("profile must be wan21-synthid-experimental or wan21-seedance-experimental") if quality not in {"delivery", "master"}: diff --git a/src/remove_ai_watermarks/video_audio.py b/src/remove_ai_watermarks/video_audio.py index 6614176..66e8582 100644 --- a/src/remove_ai_watermarks/video_audio.py +++ b/src/remove_ai_watermarks/video_audio.py @@ -276,10 +276,10 @@ def remove_video_audio( if out_ext not in {".mkv", ".mov", ".mp4", ".m4v", ".webm"}: raise ValueError("Audio-only video output must be MKV, MOV, MP4, M4V, or WebM") lossy = out_ext in {".mp4", ".m4v", ".webm"} - codec_label = "Opus/Vorbis" if out_ext == ".webm" else "AAC" + codec_label = "Opus" if out_ext == ".webm" else "AAC" caveats = ( *_CAVEATS, - f"The selected track uses lossy {codec_label} with a target bitrate of 192 kbps; " + f"The selected track uses lossy {codec_label} (160k mono / 256k stereo+); " "verification and fidelity cover the delivered decoded audio." if lossy else _PCM_CAVEAT, @@ -387,10 +387,7 @@ def remove_video_audio( flags = "+".join(k for k, v in s.get("disposition", {}).items() if v) or "0" command.extend([f"-disposition:{s['index']}", flags]) command.extend([f"-map_metadata:s:{s['index']}", f"0:s:{s['index']}"]) - webm_audio_codec = ( - "libopus" if info.sample_rate in {8000, 12000, 16000, 24000, 48000} else "libvorbis" - ) - target_audio_codec = webm_audio_codec if out_ext == ".webm" else ("aac" if lossy else "pcm_f32le") + target_audio_codec = "libopus" if out_ext == ".webm" else ("aac" if lossy else "pcm_f32le") command.extend( [ "-c", @@ -427,8 +424,15 @@ def remove_video_audio( ): raise RuntimeError("Audio processing changed stream language or disposition") output_tick = Fraction(delivered_streams[info.index]["time_base"]) - delivered_start, delivered_count = _timeline(staged, info.index, info.sample_rate, output_tick) - if count != delivered_count or abs(start - delivered_start) > output_tick: + delivered_rate = int(delivered_streams[info.index]["sample_rate"]) + delivered_start, delivered_count = _timeline(staged, info.index, delivered_rate, output_tick) + if target_audio_codec == "libopus": + expected_count = round(count * delivered_rate / info.sample_rate) + count_slack = max(2, delivered_rate // 100) + bad_count = abs(delivered_count - expected_count) > count_slack + else: + bad_count = count != delivered_count + if bad_count or abs(start - delivered_start) > output_tick: raise RuntimeError("Mux changed the selected audio timeline") after = audio.identify_audio(staged, check_invisible=verify, stream=stream, scheme=scheme) verified = audio.verification_outcome(before, after) @@ -858,7 +862,8 @@ def remove_video_audio_all_streams( verified=verified, quality_ok=q_ok, force=force, - allow_unverified=allow_unverified, + allow_unverified=eff_allow_unverified + or audio.should_auto_scrub_audio(before_rep, method=method, explicit_vendor=explicit_vendor), allow_positive=allow_positive, allow_quality_override=allow_quality_override, ) diff --git a/src/remove_ai_watermarks/video_encoding.py b/src/remove_ai_watermarks/video_encoding.py index 66aae1c..b093ef7 100644 --- a/src/remove_ai_watermarks/video_encoding.py +++ b/src/remove_ai_watermarks/video_encoding.py @@ -496,6 +496,11 @@ def _profile_args(profile: VideoEncodeProfile) -> list[str]: return args +def container_format_args(suffix: str) -> list[str]: + """Return explicit ffmpeg muxer format flags when extension auto-detection is restrictive.""" + return ["-f", "mp4"] if suffix.lower() == ".m4v" else [] + + def raw_video_command( output: Path, *, @@ -552,6 +557,7 @@ def raw_video_command( numerator, denominator = (int(part) for part in profile.time_base.split("/", 1)) if numerator == 1: command.extend(["-video_track_timescale", str(denominator)]) + command.extend(container_format_args(output.suffix)) command.append(str(output)) return command @@ -593,6 +599,7 @@ def mux_encoded_video( command.extend(["-avoid_negative_ts", "disabled"]) if output.suffix.lower() in {".mp4", ".mov", ".m4v"}: command.extend(["-movflags", "+faststart"]) + command.extend(container_format_args(output.suffix)) command.append(str(output)) with tempfile.TemporaryFile(mode="w+b") as stderr_buffer: result = subprocess.run( # noqa: S603 diff --git a/src/remove_ai_watermarks/video_messages.py b/src/remove_ai_watermarks/video_messages.py index 916dbe7..2428578 100644 --- a/src/remove_ai_watermarks/video_messages.py +++ b/src/remove_ai_watermarks/video_messages.py @@ -455,8 +455,10 @@ def remove_video_message( target = Path(output).expanduser() if target.resolve() == original or (target.exists() and original.exists() and target.samefile(original)): raise ValueError("Video output must differ from the source") - if target.suffix.lower() not in {".mp4", ".mov", ".m4v", ".mkv", ".webm"}: - raise ValueError("Video message outputs must be MP4, MOV, M4V, MKV, or WebM") + from remove_ai_watermarks._internal.constants import VIDEO_EXTENSIONS + + if target.suffix.lower() not in VIDEO_EXTENSIONS: + raise ValueError("Video message outputs must be MP4, MOV, M4V, MKV, WebM, AVI, or FLV") before = identify_video_message(original, reference_hex=reference_hex, scheme=scheme, check_message=verify) if before.status != "matched" and not force: return VideoMessageRemovalResult(original, None, before, None, None, True) diff --git a/src/remove_ai_watermarks/video_seedance.py b/src/remove_ai_watermarks/video_seedance.py index 130fd58..22e9620 100644 --- a/src/remove_ai_watermarks/video_seedance.py +++ b/src/remove_ai_watermarks/video_seedance.py @@ -23,6 +23,7 @@ from typing import TYPE_CHECKING, Any, Literal import cv2 import numpy as np +from remove_ai_watermarks._internal.constants import ISOBMFF_VIDEO_EXTENSIONS from remove_ai_watermarks.video_decode import open_video_capture, open_video_capture_16bit from remove_ai_watermarks.video_encoding import ( HIGH_BIT_DEPTH_PIXEL_FORMATS, @@ -135,7 +136,10 @@ def _match_video_end(encoded: Path, source: Path) -> None: repair = video_end_repair(original, _clock(encoded, include_packets=True)) ffmpeg = require_video_tool("ffmpeg") with TemporaryDirectory(prefix="seedance-clock-", dir=encoded.parent) as directory: - retimed = Path(directory) / "retimed.mp4" + suffix = encoded.suffix.lower() + retimed = Path(directory) / f"retimed{suffix}" + from remove_ai_watermarks.video_encoding import container_format_args + _run_command( [ ffmpeg, @@ -156,6 +160,7 @@ def _match_video_end(encoded: Path, source: Path) -> None: "disabled", "-movflags", "+faststart", + *container_format_args(suffix), str(retimed), ] ) @@ -221,10 +226,13 @@ def _encode_frames( writer.write(frame, timestamp) writer.close() writer = None - finish_raw_video_encoder(encoder, encoded, operation="Experimental Seedance encode") - _match_video_end(encoded, source) + finish_raw_video_encoder(encoder, encoded, operation="Seedance encode") + is_isobmff = output.suffix.lower() in ISOBMFF_VIDEO_EXTENSIONS + if is_isobmff: + _match_video_end(encoded, source) mux_encoded_video(encoded, source, temporary, strip_metadata=True, copy_input_timestamps=True) - _match_video_end(temporary, source) + if is_isobmff: + _match_video_end(temporary, source) except Exception: if writer is not None: with suppress(Exception): @@ -290,8 +298,11 @@ def _encode_delivery(master: Path, source: Path, output: Path) -> None: "-fps_mode", "passthrough", ] - if time_base.numerator == 1: + is_isobmff = output.suffix.lower() in ISOBMFF_VIDEO_EXTENSIONS + if is_isobmff and time_base.numerator == 1: command.extend(["-video_track_timescale", str(time_base.denominator)]) + from remove_ai_watermarks.video_encoding import container_format_args + command.extend( [ "-avoid_negative_ts", @@ -300,13 +311,14 @@ def _encode_delivery(master: Path, source: Path, output: Path) -> None: "-1", "-map_chapters", "-1", - "-movflags", - "+faststart", + *(["-movflags", "+faststart"] if is_isobmff else []), + *container_format_args(output.suffix), str(output), ] ) _run_command(command) - _match_video_end(output, source) + if is_isobmff: + _match_video_end(output, source) def _measure(source: Path, output: Path, fps: float, count: int, *, high_depth: bool = False) -> RegenerationMetrics: @@ -320,22 +332,28 @@ def _measure(source: Path, output: Path, fps: float, count: int, *, high_depth: width, height, _ = probe_video_geometry(source) src_iter = _frames(source, high_depth=high_depth, width=width, height=height) out_iter = _frames(output, high_depth=high_depth, width=width, height=height) - for original, delivered in zip(src_iter, out_iter, strict=True): - if original.shape != delivered.shape: - raise RuntimeError("Experimental Seedance output geometry changed") - difference = original.astype(np.float64) - delivered.astype(np.float64) - squared_error += float(np.sum(difference * difference)) - pixels += original.size - orig_u8 = (original >> 8).astype(np.uint8) if original.dtype == np.uint16 else original - deliv_u8 = (delivered >> 8).astype(np.uint8) if delivered.dtype == np.uint16 else delivered - current = cv2.cvtColor(orig_u8, cv2.COLOR_BGR2GRAY).astype(np.float32) - current_output = cv2.cvtColor(deliv_u8, cv2.COLOR_BGR2GRAY).astype(np.float32) - if previous is not None and previous_output is not None: - maps = _backward_map(current, previous) - baseline += _motion_residual(current, previous, maps) - residual += _motion_residual(current_output, previous_output, maps) - previous, previous_output = current, current_output - frames += 1 + try: + for original, delivered in zip(src_iter, out_iter, strict=True): + if original.shape != delivered.shape: + raise RuntimeError("Experimental Seedance output geometry changed") + difference = original.astype(np.float64) - delivered.astype(np.float64) + squared_error += float(np.sum(difference * difference)) + pixels += original.size + orig_u8 = (original >> 8).astype(np.uint8) if original.dtype == np.uint16 else original + deliv_u8 = (delivered >> 8).astype(np.uint8) if delivered.dtype == np.uint16 else delivered + current = cv2.cvtColor(orig_u8, cv2.COLOR_BGR2GRAY).astype(np.float32) + current_output = cv2.cvtColor(deliv_u8, cv2.COLOR_BGR2GRAY).astype(np.float32) + if previous is not None and previous_output is not None: + maps = _backward_map(current, previous) + baseline += _motion_residual(current, previous, maps) + residual += _motion_residual(current_output, previous_output, maps) + previous, previous_output = current, current_output + frames += 1 + finally: + for it in (src_iter, out_iter): + close = getattr(it, "close", None) + if callable(close): + close() if frames != count: raise RuntimeError("Experimental Seedance decoded frame count changed") mse = squared_error / pixels @@ -377,6 +395,18 @@ def validate_experimental_mp4_source( return width, height, fps, active_timestamps +def _verify_isobmff_timing(source: Path, staged: Path, timestamps: tuple[float, ...], label: str) -> None: + """Verify exact timestamps and terminal duration for ISOBMFF containers.""" + if staged.suffix.lower() not in ISOBMFF_VIDEO_EXTENSIONS: + return + if probe_video_timestamps(staged) != timestamps: + raise RuntimeError(f"{label} output timestamps changed") + staged_dur = float(_clock(staged)["streams"][0]["duration"]) + source_dur = float(_clock(source)["streams"][0]["duration"]) + if abs(staged_dur - source_dur) > 0.000002: + raise RuntimeError(f"{label} output duration changed") + + def _finalize_experimental_output( frames: Iterable[NDArray[Any]], source: Path, @@ -395,12 +425,7 @@ def _finalize_experimental_output( _encode_delivery(master, source, staged) else: master.replace(staged) - if probe_video_timestamps(staged) != timestamps: - raise RuntimeError(f"{label} output timestamps changed") - staged_dur = float(_clock(staged)["streams"][0]["duration"]) - source_dur = float(_clock(source)["streams"][0]["duration"]) - if abs(staged_dur - source_dur) > 0.000002: - raise RuntimeError(f"{label} output duration changed") + _verify_isobmff_timing(source, staged, timestamps, label) return _measure(source, staged, fps, len(timestamps), high_depth=high_depth) @@ -439,7 +464,7 @@ def regenerate_seedance_experimental( atomic_video_output(output) as staged, TemporaryDirectory(prefix="seedance-experimental-", dir=output.parent) as directory, ): - master = Path(directory) / "master.mp4" + master = Path(directory) / f"master{source.suffix.lower()}" owned_runtime = runtime is None active_runtime = runtime or load_video_vae_runtime(model="stabilityai/sd-vae-ft-mse", device=device) guide_size = _fit_size(width, height, 512) diff --git a/src/remove_ai_watermarks/video_wan.py b/src/remove_ai_watermarks/video_wan.py index 6321ff5..60bc4c9 100644 --- a/src/remove_ai_watermarks/video_wan.py +++ b/src/remove_ai_watermarks/video_wan.py @@ -30,11 +30,9 @@ from remove_ai_watermarks.video_encoding import ( HIGH_BIT_DEPTH_PIXEL_FORMATS, atomic_video_output, probe_video_encode_profile, - probe_video_timestamps, ) from remove_ai_watermarks.video_seedance import ( SeedanceQuality, - _clock, _encode_frames, _frames, _measure, @@ -66,9 +64,6 @@ WAN21_MPS_CHUNK_FRAMES = 33 WAN21_DEFAULT_OVERLAP_FRAMES = 17 WAN21_MPS_OVERLAP_FRAMES = 9 WAN21_NATIVE_MAX_PIXELS = 1920 * 1080 -WAN21_AUTO_MAX_FRAME_PIXELS = 3840 * 2160 -WAN21_MAX_FRAME_PIXELS = 3840 * 2160 -WAN21_MAX_TOTAL_PIXEL_FRAMES = 7200 * 1920 * 1080 WAN21_MIN_CUDA_VRAM_BYTES = 8 * 1024**3 WAN21_HIGH_VRAM_BYTES = 16 * 1024**3 WAN21_DEFAULT_PROMPT = "High fidelity natural video, sharp details, accurate motion, clean cinematic lighting." @@ -282,21 +277,6 @@ def _validate_wan_window_args(chunk_frames: int, overlap_frames: int) -> None: raise ValueError("overlap_frames must satisfy 0 <= overlap_frames < chunk_frames") -def _validate_wan_source_budget(width: int, height: int, frame_count: int) -> None: - """Enforce conservative spatial and total-frame limits before decoding.""" - frame_pixels = width * height - if frame_pixels > WAN21_MAX_FRAME_PIXELS: - raise ValueError( - f"Experimental Wan 2.1 processing requires frame area <= {WAN21_MAX_FRAME_PIXELS} pixels " - f"(got {width}x{height})" - ) - if frame_pixels * frame_count > WAN21_MAX_TOTAL_PIXEL_FRAMES: - raise ValueError( - f"Experimental Wan 2.1 host-memory budget exceeded: {frame_count} frames at {width}x{height} " - f"exceeds {WAN21_MAX_TOTAL_PIXEL_FRAMES} pixel-frames" - ) - - def can_run_wan_on_source( source: Path, *, @@ -324,7 +304,7 @@ def can_run_wan_on_source( except Exception: return False try: - width, height, _fps, timestamps = validate_experimental_mp4_source( + validate_experimental_mp4_source( source, label="Experimental Wan 2.1 processing", encode_profile=probe_video_encode_profile(source), @@ -332,13 +312,6 @@ def can_run_wan_on_source( ) except Exception: return False - if for_auto and width * height > WAN21_AUTO_MAX_FRAME_PIXELS: - return False - try: - _validate_wan_source_budget(width, height, len(timestamps)) - except ValueError as exc: - log.warning("Wan 2.1 eligibility skipped for %s (%s); auto profile will use 2D fallback", source.name, exc) - return False return True @@ -552,14 +525,11 @@ def _finalize_wan_output( high_depth: bool = False, ) -> RegenerationMetrics: """Encode Wan 2.1 frames directly to delivery (CRF 18) or master (CRF 0) in a single pass.""" + from remove_ai_watermarks.video_seedance import _verify_isobmff_timing + target_crf = 18 if quality == "delivery" else 0 _encode_frames(frames, source, staged, fps, timestamps, crf=target_crf) - if probe_video_timestamps(staged) != timestamps: - raise RuntimeError("Experimental Wan 2.1 output timestamps changed") - staged_dur = float(_clock(staged)["streams"][0]["duration"]) - source_dur = float(_clock(source)["streams"][0]["duration"]) - if abs(staged_dur - source_dur) > 0.000002: - raise RuntimeError("Experimental Wan 2.1 output duration changed") + _verify_isobmff_timing(source, staged, timestamps, "Wan 2.1") return _measure(source, staged, fps, len(timestamps), high_depth=high_depth) @@ -599,7 +569,6 @@ def regenerate_wan_experimental( encode_profile=encode_profile, allow_high_depth=True, ) - _validate_wan_source_budget(width, height, len(timestamps)) if runtime is None and not is_available(): raise RuntimeError("Wan 2.1 video processing requires 'remove-ai-watermarks[video,diffusion]'") if runtime is None: diff --git a/tests/test_audio.py b/tests/test_audio.py index 7db9b17..3ad7c0f 100644 --- a/tests/test_audio.py +++ b/tests/test_audio.py @@ -54,68 +54,48 @@ def test_missing_optional_decoder_reports_unverified(tmp_path, monkeypatch): assert report.stream.channels == 2 -def test_bigvgan_delivery_routes_full_track_and_preserves_unverified_scope(tmp_path, monkeypatch): +def test_dac_delivery_routes_full_track_and_preserves_unverified_scope(tmp_path, monkeypatch): from remove_ai_watermarks import audio calls = [] - def process(samples, sample_rate, *, device, local_files_only): + def process(samples, sample_rate, *, device="cpu", local_files_only=False): calls.append((samples.shape, sample_rate, device, local_files_only)) return samples * 0.5 - monkeypatch.setattr(audio.audio_vocoder, "is_available", lambda: True) - monkeypatch.setattr(audio.audio_vocoder, "resynthesize", process) + monkeypatch.setattr(audio.audio_dac, "is_available", lambda: True) + monkeypatch.setattr(audio.audio_dac, "resynthesize", process) result = audio.remove_audio_invisible( _source(tmp_path, frames=16001), - tmp_path / "vocoder.wav", - method="bigvgan", + tmp_path / "dac.wav", + method="dac", vocoder_device="mps", force=True, verify=False, ) assert calls == [((16001, 2), 16000, "mps", False)] - assert result.method == "bigvgan" + assert result.method == "dac" assert result.bandwidth_kbps is None assert result.verified_removed is None assert result.fidelity.frames == 16001 assert result.fidelity.snr_db == pytest.approx(6.0206, abs=0.001) - assert b"Lavf" not in result.output.read_bytes() -def test_bigvgan_still_positive_does_not_replace_output(tmp_path, monkeypatch): +def test_dac_still_positive_does_not_replace_output(tmp_path, monkeypatch): from remove_ai_watermarks import audio _spectral_detector(monkeypatch, resistant=True) - monkeypatch.setattr(audio.audio_vocoder, "is_available", lambda: True) - monkeypatch.setattr(audio.audio_vocoder, "resynthesize", lambda samples, *a, **kw: samples * 0.5) + monkeypatch.setattr(audio.audio_dac, "is_available", lambda: True) + monkeypatch.setattr(audio.audio_dac, "resynthesize", lambda samples, *a, **kw: samples * 0.5) output = tmp_path / "protected.wav" output.write_bytes(b"previous output") with pytest.raises(audio.AudioVerificationIncomplete): - audio.remove_audio_invisible(_source(tmp_path), output, method="bigvgan") + audio.remove_audio_invisible(_source(tmp_path), output, method="dac") assert output.read_bytes() == b"previous output" -@pytest.mark.parametrize("channels", [1, 2]) -def test_bigvgan_full_track_limit_stops_and_closes_before_model(monkeypatch, channels): - from remove_ai_watermarks import audio - - closed = [] - monkeypatch.setattr(audio.audio_vocoder, "resynthesize", lambda *a, **kw: pytest.fail("model must not run")) - - def chunks(): - try: - yield np.zeros((299, channels), dtype=np.float32) - yield np.zeros((2, channels), dtype=np.float32) - finally: - closed.append(True) - - with pytest.raises(ValueError, match="30 seconds"): - list(audio._vocode_full_track(chunks(), 10, "cpu")) - assert closed == [True] - - -def test_bigvgan_rejects_two_channels_that_are_not_a_stereo_pair(tmp_path, monkeypatch): +def test_dac_rejects_two_channels_that_are_not_a_stereo_pair(tmp_path, monkeypatch): from dataclasses import replace from remove_ai_watermarks import audio @@ -124,33 +104,31 @@ def test_bigvgan_rejects_two_channels_that_are_not_a_stereo_pair(tmp_path, monke before = audio.identify_audio(source, check_invisible=False) before = replace(before, stream=replace(before.stream, channel_layout="2 channels (FC+LFE)")) monkeypatch.setattr(audio, "identify_audio", lambda *a, **kw: before) - monkeypatch.setattr(audio.audio_vocoder, "is_available", lambda: True) - monkeypatch.setattr(audio.audio_vocoder, "resynthesize", lambda *a, **kw: pytest.fail("model must not run")) + monkeypatch.setattr(audio.audio_dac, "is_available", lambda: True) + monkeypatch.setattr(audio.audio_dac, "resynthesize", lambda *a, **kw: pytest.fail("model must not run")) output = tmp_path / "protected.wav" output.write_bytes(b"previous output") - with pytest.raises(ValueError, match="mono or stereo channel layout"): - audio.remove_audio_invisible(source, output, method="bigvgan", force=True, verify=False) + with pytest.raises(ValueError, match="channel layout"): + audio.remove_audio_invisible(source, output, method="dac", force=True, verify=False) assert output.read_bytes() == b"previous output" -def test_bigvgan_missing_base_stack_names_the_complete_processing_extra(tmp_path, monkeypatch): +def test_dac_missing_base_stack_names_the_complete_processing_extra(tmp_path, monkeypatch): from remove_ai_watermarks import audio monkeypatch.setattr(audio.audio_io, "is_available", lambda: False) - with pytest.raises(ImportError, match="audio-vocoder"): - audio.remove_audio_invisible( - _source(tmp_path), tmp_path / "out.wav", method="bigvgan", force=True, verify=False - ) + with pytest.raises(ImportError, match="audio-codec"): + audio.remove_audio_invisible(_source(tmp_path), tmp_path / "out.wav", method="dac", force=True, verify=False) -def test_bigvgan_missing_stack_preserves_existing_output(tmp_path, monkeypatch): +def test_dac_missing_stack_preserves_existing_output(tmp_path, monkeypatch): from remove_ai_watermarks import audio - monkeypatch.setattr(audio.audio_vocoder, "is_available", lambda: False) + monkeypatch.setattr(audio.audio_dac, "is_available", lambda: False) output = tmp_path / "protected.wav" output.write_bytes(b"previous output") - with pytest.raises(ImportError, match="audio-vocoder"): - audio.remove_audio_invisible(_source(tmp_path), output, method="bigvgan", force=True, verify=False) + with pytest.raises(ImportError, match="audio-codec"): + audio.remove_audio_invisible(_source(tmp_path), output, method="dac", force=True, verify=False) assert output.read_bytes() == b"previous output" @@ -253,7 +231,6 @@ def test_all_schemes_cannot_be_negative_with_an_unavailable_decoder(tmp_path, mo monkeypatch.setattr(audio.wavmark, "is_available", lambda: False) monkeypatch.setattr(audio.perth, "is_available", lambda: False) monkeypatch.setattr(audio.silentcipher, "is_available", lambda: False) - monkeypatch.setattr(audio.silentcipher16, "is_available", lambda: False) output = tmp_path / "processed.wav" output.write_bytes(b"existing output") with pytest.raises(audio.AudioVerificationIncomplete) as caught: @@ -266,53 +243,11 @@ def test_all_schemes_cannot_be_negative_with_an_unavailable_decoder(tmp_path, mo "wavmark", "perth", "silentcipher", - "silentcipher16", ] assert output.read_bytes() == b"existing output" -@pytest.mark.parametrize("rate", [16000, 44100, 48000]) -def test_silentcipher16_delivery_checks_native_windows_and_reports_ternary_symbols(tmp_path, monkeypatch, rate): - from remove_ai_watermarks import audio - from remove_ai_watermarks._internal import silentcipher16 - - lengths = [] - - def read(_model, samples, *, sample_rate): - assert sample_rate == rate - lengths.append(len(samples)) - assert len(samples) >= 3 * rate - t = np.arange(len(samples)) / rate - found = abs(2 * np.mean(samples * np.exp(-2j * np.pi * 1250 * t))) > 0.01 - return silentcipher16.SilentCipher16Reading( - (0, 1, 2, 0, 2, 1, 0) if found else None, float(found), 0, 103, "cpu" - ) - - monkeypatch.setattr(silentcipher16, "is_available", lambda: True) - monkeypatch.setattr(silentcipher16, "load_model", object) - monkeypatch.setattr(silentcipher16, "read", read) - result = audio.remove_audio_invisible( - _source(tmp_path, frames=3 * rate + 31, rate=rate), - tmp_path / "processed.wav", - scheme="silentcipher16", - method="spectral", - ) - assert result.verified_removed is True - assert result.verification_scope == ("silentcipher16",) - assert result.before.detections[0].whole_clip.payload_symbols == (0, 1, 2, 0, 2, 1, 0) - assert result.before.detections[0].whole_clip.framing == "terminated8" - assert result.after.stream.sample_rate == rate - assert result.fidelity.frames == 3 * rate + 31 - for detection in result.after.detections: - assert detection.whole_clip.framing == "terminated8" - assert detection.scheme == "silentcipher16" - assert detection.decoder_sample_rate == 16000 - assert detection.windows[-1].start_frame == 31 - assert detection.windows[-1].end_frame == 3 * rate + 31 - assert min(lengths) == 3 * rate - - -def test_all_requires_silentcipher16_even_when_every_other_receiver_is_negative(tmp_path, monkeypatch): +def test_all_requires_silentcipher_even_when_every_other_receiver_is_negative(tmp_path, monkeypatch): from remove_ai_watermarks import audio _spectral_detector(monkeypatch) @@ -324,21 +259,20 @@ def test_all_requires_silentcipher16_even_when_every_other_receiver_is_negative( reading = { "wavmark": audio.wavmark.WavMarkReading(None, ()), "perth": audio.perth.PerthReading(0.0), - "silentcipher": audio.silentcipher.SilentCipherReading(None, 0.4, None, 205, "cpu"), }[scheme] window = audio.AudioWindowReading(0, 3 * info.sample_rate, reading) return (audio.AudioDetection(scheme, 0, "not_detected", reading, (window,)),), () monkeypatch.setattr(audio, "_scan_audio", scan) - for backend in [audio.wavmark, audio.perth, audio.silentcipher]: + for backend in [audio.wavmark, audio.perth]: monkeypatch.setattr(backend, "is_available", lambda: True) - monkeypatch.setattr(audio.silentcipher16, "is_available", lambda: False) + monkeypatch.setattr(audio.silentcipher, "is_available", lambda: False) output = tmp_path / "processed.wav" output.write_bytes(b"existing output") with pytest.raises(audio.AudioVerificationIncomplete) as caught: audio.remove_audio_invisible(_source(tmp_path, frames=48000), output, scheme="all", method="spectral") assert caught.value.after.watermark_status == "unverified" - assert caught.value.after.detections[-1].scheme == "silentcipher16" + assert caught.value.after.detections[-1].scheme == "silentcipher" assert caught.value.after.detections[-1].status == "unverified" assert output.read_bytes() == b"existing output" @@ -532,178 +466,13 @@ def test_short_silentcipher_source_stays_unverified_and_preserves_output(tmp_pat assert output.read_bytes() == b"existing" -def test_mimi_delivery_routes_full_track_and_preserves_unverified_scope(tmp_path, monkeypatch): - from remove_ai_watermarks import audio - - calls = [] - - def process(samples, sample_rate, *, local_files_only): - calls.append((samples.shape, sample_rate, "cpu", local_files_only)) - return samples * 0.5 - - monkeypatch.setattr(audio.audio_mimi, "is_available", lambda: True) - monkeypatch.setattr(audio.audio_mimi, "resynthesize", process) - result = audio.remove_audio_invisible( - _source(tmp_path, frames=16001), - tmp_path / "vocoder.wav", - method="mimi", - vocoder_device="cpu", - force=True, - verify=False, - ) - assert calls == [((16001, 2), 16000, "cpu", False)] - assert result.method == "mimi" - assert result.bandwidth_kbps is None - assert result.verified_removed is None - assert result.fidelity.frames == 16001 - assert result.fidelity.snr_db == pytest.approx(6.0206, abs=0.001) - - assert b"Lavf" not in result.output.read_bytes() - - -def test_mimi_still_positive_does_not_replace_output(tmp_path, monkeypatch): - from remove_ai_watermarks import audio - - _spectral_detector(monkeypatch, resistant=True) - monkeypatch.setattr(audio.audio_mimi, "is_available", lambda: True) - monkeypatch.setattr(audio.audio_mimi, "resynthesize", lambda samples, *a, **kw: samples * 0.5) - output = tmp_path / "protected.wav" - output.write_bytes(b"previous output") - with pytest.raises(audio.AudioVerificationIncomplete): - audio.remove_audio_invisible(_source(tmp_path), output, method="mimi") - assert output.read_bytes() == b"previous output" - - -def test_mimi_rejects_two_channels_that_are_not_a_stereo_pair(tmp_path, monkeypatch): - from dataclasses import replace - - from remove_ai_watermarks import audio - - source = _source(tmp_path) - before = audio.identify_audio(source, check_invisible=False) - before = replace(before, stream=replace(before.stream, channel_layout="2 channels (FC+LFE)")) - monkeypatch.setattr(audio, "identify_audio", lambda *a, **kw: before) - monkeypatch.setattr(audio.audio_mimi, "is_available", lambda: True) - monkeypatch.setattr(audio.audio_mimi, "resynthesize", lambda *a, **kw: pytest.fail("model must not run")) - output = tmp_path / "protected.wav" - output.write_bytes(b"previous output") - with pytest.raises(ValueError, match="mono or stereo channel layout"): - audio.remove_audio_invisible(source, output, method="mimi", force=True, verify=False) - assert output.read_bytes() == b"previous output" - - -def test_mimi_missing_base_stack_names_the_complete_processing_extra(tmp_path, monkeypatch): - from remove_ai_watermarks import audio - - monkeypatch.setattr(audio.audio_io, "is_available", lambda: False) - with pytest.raises(ImportError, match="audio-codec"): - audio.remove_audio_invisible(_source(tmp_path), tmp_path / "out.wav", method="mimi", force=True, verify=False) - - -def test_mimi_missing_stack_preserves_existing_output(tmp_path, monkeypatch): - from remove_ai_watermarks import audio - - monkeypatch.setattr(audio.audio_mimi, "is_available", lambda: False) - output = tmp_path / "protected.wav" - output.write_bytes(b"previous output") - with pytest.raises(ImportError, match="audio-codec"): - audio.remove_audio_invisible(_source(tmp_path), output, method="mimi", force=True, verify=False) - assert output.read_bytes() == b"previous output" - - -@pytest.mark.parametrize("limit", ["seconds", "values"]) -def test_mimi_full_track_limit_closes_before_model(monkeypatch, limit): - from remove_ai_watermarks import audio - - closed = [] - monkeypatch.setattr(audio.audio_mimi, "resynthesize", lambda *a, **k: pytest.fail("model must not run")) - if limit == "values": - monkeypatch.setattr(audio, "_MAX_WHOLE_VALUES", 4) - - def chunks(): - try: - yield np.zeros((301 if limit == "seconds" else 3, 2), dtype=np.float32) - finally: - closed.append(True) - - with pytest.raises(ValueError, match="30 seconds and 16000000"): - list(audio._mimi_full_track(chunks(), 10)) - assert closed == [True] - - -def test_mimi_is_explicit_cpu_only_and_not_in_auto(tmp_path): - from remove_ai_watermarks import audio - - assert all("mimi" not in profiles for profiles in audio._AUTO_PROFILES.values()) - assert all("focalcodec" not in profiles for profiles in audio._AUTO_PROFILES.values()) - with pytest.raises(ValueError, match="requires method=bigvgan"): - audio.remove_audio_invisible(_source(tmp_path), tmp_path / "out.wav", method="mimi", vocoder_device="mps") - with pytest.raises(ValueError, match="requires method=bigvgan"): - audio.remove_audio_invisible(_source(tmp_path), tmp_path / "out.wav", method="focalcodec", vocoder_device="mps") - - -def test_focalcodec_delivery_and_still_positive_safeguard(tmp_path, monkeypatch): - from remove_ai_watermarks import audio - - calls = [] - - def process(samples, sample_rate, *, local_files_only): - calls.append((samples.shape, sample_rate, local_files_only)) - return samples * 0.5 - - monkeypatch.setattr(audio.audio_focalcodec, "is_available", lambda: True) - monkeypatch.setattr(audio.audio_focalcodec, "resynthesize", process) - result = audio.remove_audio_invisible( - _source(tmp_path, frames=16001), - tmp_path / "focal.wav", - method="focalcodec", - vocoder_device="cpu", - force=True, - verify=False, - ) - assert calls == [((16001, 2), 16000, False)] - assert result.method == "focalcodec" - assert result.bandwidth_kbps is None - assert result.verified_removed is None - assert result.fidelity.frames == 16001 - assert b"Lavf" not in result.output.read_bytes() - - _spectral_detector(monkeypatch, resistant=True) - protected = tmp_path / "protected_focal.wav" - protected.write_bytes(b"previous output") - with pytest.raises(audio.AudioVerificationIncomplete): - audio.remove_audio_invisible(_source(tmp_path), protected, method="focalcodec") - assert protected.read_bytes() == b"previous output" - - -def test_focalcodec_missing_stack_and_channel_layout_guards(tmp_path, monkeypatch): - from dataclasses import replace - - from remove_ai_watermarks import audio - - monkeypatch.setattr(audio.audio_focalcodec, "is_available", lambda: False) - with pytest.raises(ImportError, match="audio-codec"): - audio.remove_audio_invisible( - _source(tmp_path), tmp_path / "out.wav", method="focalcodec", force=True, verify=False - ) - - source = _source(tmp_path) - before = audio.identify_audio(source, check_invisible=False) - before = replace(before, stream=replace(before.stream, channel_layout="2 channels (FC+LFE)")) - monkeypatch.setattr(audio, "identify_audio", lambda *a, **kw: before) - monkeypatch.setattr(audio.audio_focalcodec, "is_available", lambda: True) - monkeypatch.setattr(audio.audio_focalcodec, "resynthesize", lambda *a, **kw: pytest.fail("model must not run")) - with pytest.raises(ValueError, match="FocalCodec requires a mono or stereo channel layout"): - audio.remove_audio_invisible(source, tmp_path / "out.wav", method="focalcodec", force=True, verify=False) - - -def test_mimi_source_change_rejected_after_resynthesis(tmp_path, monkeypatch): +def test_dac_source_change_rejected_after_resynthesis(tmp_path, monkeypatch): from remove_ai_watermarks import audio source = _source(tmp_path) output = tmp_path / "protected.wav" output.write_bytes(b"existing output") - monkeypatch.setattr(audio.audio_mimi, "is_available", lambda: True) + monkeypatch.setattr(audio.audio_dac, "is_available", lambda: True) def process(samples, *a, **kw): data = bytearray(source.read_bytes()) @@ -711,17 +480,17 @@ def test_mimi_source_change_rejected_after_resynthesis(tmp_path, monkeypatch): source.write_bytes(data) return samples - monkeypatch.setattr(audio.audio_mimi, "resynthesize", process) + monkeypatch.setattr(audio.audio_dac, "resynthesize", process) with pytest.raises(RuntimeError, match="source changed"): - audio.remove_audio_invisible(source, output, method="mimi", force=True, verify=False) + audio.remove_audio_invisible(source, output, method="dac", force=True, verify=False) assert output.read_bytes() == b"existing output" -def test_mimi_flac_uses_separate_non_bitexact_encoding(tmp_path, monkeypatch): +def test_dac_flac_uses_separate_non_bitexact_encoding(tmp_path, monkeypatch): from remove_ai_watermarks import audio - monkeypatch.setattr(audio.audio_mimi, "is_available", lambda: True) - monkeypatch.setattr(audio.audio_mimi, "resynthesize", lambda samples, *a, **k: samples) + monkeypatch.setattr(audio.audio_dac, "is_available", lambda: True) + monkeypatch.setattr(audio.audio_dac, "resynthesize", lambda samples, *a, **k: samples) real = audio.audio_io.write_audio calls = [] @@ -731,7 +500,7 @@ def test_mimi_flac_uses_separate_non_bitexact_encoding(tmp_path, monkeypatch): monkeypatch.setattr(audio.audio_io, "write_audio", write) result = audio.remove_audio_invisible( - _source(tmp_path), tmp_path / "mimi.flac", method="mimi", force=True, verify=False + _source(tmp_path), tmp_path / "dac.flac", method="dac", force=True, verify=False ) assert calls == [(".flac", False)] assert result.frames_processed == 16000 @@ -776,13 +545,13 @@ def test_audio_quality_gate_rejects_silent_erasure_and_clipping_unless_forced(tm protected = tmp_path / "protected.wav" protected.write_bytes(b"existing output") - monkeypatch.setattr(audio.audio_mimi, "is_available", lambda: True) - monkeypatch.setattr(audio.audio_mimi, "resynthesize", lambda samples, *a, **k: np.zeros_like(samples)) + monkeypatch.setattr(audio.audio_dac, "is_available", lambda: True) + monkeypatch.setattr(audio.audio_dac, "resynthesize", lambda samples, *a, **k: np.zeros_like(samples)) with pytest.raises(audio.AudioVerificationIncomplete, match="quality gate"): - audio.remove_audio_invisible(source, protected, method="mimi") + audio.remove_audio_invisible(source, protected, method="dac") assert protected.read_bytes() == b"existing output" - forced_silent = audio.remove_audio_invisible(source, tmp_path / "forced_silent.wav", method="mimi", force=True) + forced_silent = audio.remove_audio_invisible(source, tmp_path / "forced_silent.wav", method="dac", force=True) assert forced_silent.verified_removed is True assert forced_silent.quality_passed is False @@ -799,12 +568,12 @@ def test_audio_quality_gate_rejects_silent_erasure_and_clipping_unless_forced(tm expected_frames=src_pcm.shape[0], ) monkeypatch.setattr( - audio.audio_mimi, + audio.audio_dac, "resynthesize", lambda samples, rate, *a, **k: next(audio.audio_spectral.filter_audio_chunks(iter([samples]), rate)) * 8.0, ) with pytest.raises(audio.AudioVerificationIncomplete, match="quality gate"): - audio.remove_audio_invisible(float_source, protected, method="mimi") + audio.remove_audio_invisible(float_source, protected, method="dac") assert protected.read_bytes() == b"existing output" @@ -812,7 +581,7 @@ def test_missing_decoder_under_all_names_install_extra(tmp_path, monkeypatch): from remove_ai_watermarks import audio _spectral_detector(monkeypatch) - for backend in (audio.wavmark, audio.silentcipher, audio.silentcipher16): + for backend in (audio.wavmark, audio.silentcipher): monkeypatch.setattr(backend, "is_available", lambda: False) monkeypatch.setattr(audio.perth, "is_available", lambda: False) with pytest.raises(audio.AudioVerificationIncomplete, match=r"remove-ai-watermarks\[audio-perth\]"): @@ -823,7 +592,7 @@ def test_scheme_auto_scans_installed_decoders_and_selects_adaptive_minimal_profi from remove_ai_watermarks import audio _spectral_detector(monkeypatch) - for backend in (audio.wavmark, audio.perth, audio.silentcipher, audio.silentcipher16): + for backend in (audio.wavmark, audio.perth, audio.silentcipher): monkeypatch.setattr(backend, "is_available", lambda: False) # Unlike scheme="all" (which marks missing optional decoders as unverified), @@ -875,7 +644,7 @@ def test_audio_metadata_all_and_batch_suites(tmp_path, monkeypatch): from remove_ai_watermarks._internal import audio_io _spectral_detector(monkeypatch) - for backend in (audio.wavmark, audio.perth, audio.silentcipher, audio.silentcipher16): + for backend in (audio.wavmark, audio.perth, audio.silentcipher): monkeypatch.setattr(backend, "is_available", lambda: False) marked_wav = _source(tmp_path) @@ -947,17 +716,11 @@ def test_auto_scheme_skips_experimental_silentcipher_and_short_clip_wavmark_unve monkeypatch.setattr(audio.wavmark, "load_model", object) monkeypatch.setattr(audio.perth, "is_available", lambda: False) monkeypatch.setattr(audio.silentcipher, "is_available", lambda: True) - monkeypatch.setattr(audio.silentcipher16, "is_available", lambda: True) monkeypatch.setattr( audio.silentcipher, "load_model", lambda *_a, **_k: (_ for _ in ()).throw(AssertionError("experimental silentcipher must not run under auto")), ) - monkeypatch.setattr( - audio.silentcipher16, - "load_model", - lambda *_a, **_k: (_ for _ in ()).throw(AssertionError("experimental silentcipher16 must not run under auto")), - ) short_wav = _source(tmp_path, frames=12800) # 0.8s < 1.0s WavMark minimum window res = audio.remove_audio_invisible(short_wav, tmp_path / "short_clean.wav", scheme="auto") diff --git a/tests/test_audio_cli.py b/tests/test_audio_cli.py index f8d3209..f4b93ec 100644 --- a/tests/test_audio_cli.py +++ b/tests/test_audio_cli.py @@ -61,17 +61,17 @@ def test_forced_unverified_processing_has_a_structured_result(tmp_path): assert output.is_file() -def test_bigvgan_cli_routes_device_and_retains_unverified_report(tmp_path, monkeypatch): +def test_dac_cli_routes_device_and_retains_unverified_report(tmp_path, monkeypatch): from remove_ai_watermarks import audio calls = [] - monkeypatch.setattr(audio.audio_vocoder, "is_available", lambda: True) + monkeypatch.setattr(audio.audio_dac, "is_available", lambda: True) - def process(samples, rate, *, device, local_files_only): + def process(samples, rate, *, device="cpu", local_files_only=False): calls.append((samples.shape, rate, device, local_files_only)) return samples - monkeypatch.setattr(audio.audio_vocoder, "resynthesize", process) + monkeypatch.setattr(audio.audio_dac, "resynthesize", process) result = CliRunner().invoke( main, [ @@ -79,7 +79,7 @@ def test_bigvgan_cli_routes_device_and_retains_unverified_report(tmp_path, monke "invisible", str(_source(tmp_path)), "--method", - "bigvgan", + "dac", "--vocoder-device", "mps", "--force", @@ -90,7 +90,7 @@ def test_bigvgan_cli_routes_device_and_retains_unverified_report(tmp_path, monke assert result.exit_code == 0, result.output assert calls == [((16000, 1), 16000, "mps", False)] report = json.loads(result.output) - assert report["method"] == "bigvgan" + assert report["method"] == "dac" assert report["vocoder_device"] == "mps" assert report["verified_removed"] is None @@ -154,105 +154,38 @@ def test_codec_method_reports_its_missing_extra(tmp_path, monkeypatch): assert not output.exists() -@pytest.mark.parametrize("scheme", ["silentcipher", "silentcipher16"]) -def test_silentcipher_selection_keeps_a_short_source_unverified(tmp_path, monkeypatch, scheme): - from remove_ai_watermarks._internal import silentcipher, silentcipher16 +def test_silentcipher_selection_keeps_a_short_source_unverified(tmp_path, monkeypatch): + from remove_ai_watermarks._internal import silentcipher - backend = silentcipher16 if scheme == "silentcipher16" else silentcipher - monkeypatch.setattr(backend, "is_available", lambda: True) - monkeypatch.setattr(backend, "load_model", object) - result = CliRunner().invoke(main, ["audio", "identify", str(_source(tmp_path)), "--scheme", scheme, "--json"]) + monkeypatch.setattr(silentcipher, "is_available", lambda: True) + monkeypatch.setattr(silentcipher, "load_model", object) + result = CliRunner().invoke( + main, ["audio", "identify", str(_source(tmp_path)), "--scheme", "silentcipher", "--json"] + ) assert result.exit_code == 0, result.output report = json.loads(result.output) assert report["watermark_status"] == "unverified" - assert report["detections"][0]["scheme"] == scheme - if scheme == "silentcipher16": - assert report["detections"][0]["decoder_sample_rate"] == 16000 + assert report["detections"][0]["scheme"] == "silentcipher" assert "three seconds" in report["detections"][0]["whole_clip_error"] -def test_mimi_cli_routes_device_and_retains_unverified_report(tmp_path, monkeypatch): - from remove_ai_watermarks import audio - - calls = [] - monkeypatch.setattr(audio.audio_mimi, "is_available", lambda: True) - - def process(samples, rate, *, local_files_only): - calls.append((samples.shape, rate, "cpu", local_files_only)) - return samples - - monkeypatch.setattr(audio.audio_mimi, "resynthesize", process) - result = CliRunner().invoke( - main, - [ - "audio", - "invisible", - str(_source(tmp_path)), - "--method", - "mimi", - "--vocoder-device", - "cpu", - "--force", - "--no-verify", - "--json", - ], - ) - assert result.exit_code == 0, result.output - assert calls == [((16000, 1), 16000, "cpu", False)] - report = json.loads(result.output) - assert report["method"] == "mimi" - assert report["vocoder_device"] == "cpu" - assert report["verified_removed"] is None - - -def test_focalcodec_cli_routes_device_and_retains_unverified_report(tmp_path, monkeypatch): - from remove_ai_watermarks import audio - - calls = [] - monkeypatch.setattr(audio.audio_focalcodec, "is_available", lambda: True) - - def process(samples, rate, *, local_files_only): - calls.append((samples.shape, rate, "cpu", local_files_only)) - return samples - - monkeypatch.setattr(audio.audio_focalcodec, "resynthesize", process) - result = CliRunner().invoke( - main, - [ - "audio", - "invisible", - str(_source(tmp_path)), - "--method", - "focalcodec", - "--vocoder-device", - "cpu", - "--force", - "--no-verify", - "--json", - ], - ) - assert result.exit_code == 0, result.output - assert calls == [((16000, 1), 16000, "cpu", False)] - report = json.loads(result.output) - assert report["method"] == "focalcodec" - assert report["vocoder_device"] == "cpu" - assert report["verified_removed"] is None - - -def test_mimi_choices_align_cli_shared_catalog_and_legacy_mcp(): +def test_audio_method_choices_align_cli_shared_catalog_and_legacy_mcp(): from remove_ai_watermarks import integration, mcp_server operations = integration.operation_catalog() for name in ["cli_audio_invisible", "cli_video_audio"]: operation = next(o for o in operations if o["id"] == name) method = next(p for p in operation["parameters"] if p["name"] == "method") - assert "mimi" in method["schema"]["enum"] - assert "focalcodec" in method["schema"]["enum"] - assert "experimental" in method["schema"]["description"] + assert "dac" in method["schema"]["enum"] + assert "snac" in method["schema"]["enum"] + assert "mimi" not in method["schema"]["enum"] + assert "focalcodec" not in method["schema"]["enum"] + assert "bigvgan" not in method["schema"]["enum"] for name in ["audio_invisible", "video_audio"]: tool = next(t for t in mcp_server.TOOLS if t["name"] == name) - assert "mimi" in tool["inputSchema"]["properties"]["method"]["enum"] - assert "focalcodec" in tool["inputSchema"]["properties"]["method"]["enum"] + assert "dac" in tool["inputSchema"]["properties"]["method"]["enum"] + assert "snac" in tool["inputSchema"]["properties"]["method"]["enum"] + assert "mimi" not in tool["inputSchema"]["properties"]["method"]["enum"] def test_audio_metadata_all_and_batch_cli_commands(tmp_path, monkeypatch): @@ -261,7 +194,7 @@ def test_audio_metadata_all_and_batch_cli_commands(tmp_path, monkeypatch): from remove_ai_watermarks import audio from remove_ai_watermarks._internal import audio_io - for backend in (audio.wavmark, audio.perth, audio.silentcipher, audio.silentcipher16): + for backend in (audio.wavmark, audio.perth, audio.silentcipher): monkeypatch.setattr(backend, "is_available", lambda: False) monkeypatch.setattr(audio.audioseal, "available", lambda: False) diff --git a/tests/test_audio_dac.py b/tests/test_audio_dac.py index 0dd0c21..36ffe5d 100644 --- a/tests/test_audio_dac.py +++ b/tests/test_audio_dac.py @@ -224,12 +224,12 @@ def test_cli_and_api_wire_dac_method(tmp_path, monkeypatch): wav.writeframes(np.column_stack((pcm, pcm)).tobytes()) assert all("dac" not in profiles for profiles in audio._AUTO_PROFILES.values()) - with pytest.raises(ValueError, match="method=bigvgan"): + with pytest.raises(ValueError, match="method=dac"): audio.remove_audio_invisible(source, tmp_path / "out.wav", method="spectral", vocoder_device="mps") seen = [] - def fake_resynth(samples, sample_rate, *, local_files_only=False, device="cpu"): + def fake_resynth(samples, sample_rate, *, local_files_only=False, device="cpu", preserve_hf_hz=None): seen.append((samples.shape, sample_rate, local_files_only, device)) return samples @@ -271,7 +271,7 @@ def test_cli_and_api_wire_dac_method(tmp_path, monkeypatch): assert out.is_file() -@pytest.mark.parametrize("method", ["dac", "focalcodec"]) +@pytest.mark.parametrize("method", ["dac", "snac"]) def test_long_audio_streams_via_raised_cosine_overlap_windows_preserving_exact_frames(monkeypatch, method): sr = 1000 total_frames = 47503 # 47.503 s > 30 s whole-track limit @@ -290,8 +290,8 @@ def test_long_audio_streams_via_raised_cosine_overlap_windows_preserving_exact_f monkeypatch.setattr(audio.audio_dac, "resynthesize", fake_resynth) runner = audio._dac_full_track else: - monkeypatch.setattr(audio.audio_focalcodec, "resynthesize_conditioned", fake_resynth) - runner = audio._focalcodec_full_track + monkeypatch.setattr(audio.audio_snac, "resynthesize", fake_resynth) + runner = audio._snac_full_track closed: list[bool] = [] diff --git a/tests/test_audio_focalcodec.py b/tests/test_audio_focalcodec.py deleted file mode 100644 index 5ab39f3..0000000 --- a/tests/test_audio_focalcodec.py +++ /dev/null @@ -1,418 +0,0 @@ -"""Pinned FocalCodec loading, architecture, and native clock geometry tests.""" - -from __future__ import annotations - -import hashlib -import json -import subprocess -import sys -from pathlib import Path -from types import SimpleNamespace - -import numpy as np -import pytest - -from remove_ai_watermarks._internal import _focalcodec_network as network -from remove_ai_watermarks._internal import audio_focalcodec as focal -from remove_ai_watermarks._internal import audio_resampling as src - - -@pytest.fixture(autouse=True) -def clear_cache(): - focal.load_pinned_model.cache_clear() - yield - focal.load_pinned_model.cache_clear() - - -def test_import_is_optional_stack_pure(): - root = Path(__file__).resolve().parents[1] / "src" - script = ( - f"import sys; sys.path.insert(0, {str(root)!r}); " - "import remove_ai_watermarks._internal._focalcodec_network; " - "import remove_ai_watermarks._internal.audio_focalcodec; " - "assert not {'torch','numpy','scipy','huggingface_hub','safetensors'}.intersection(sys.modules)" - ) - subprocess.run([sys.executable, "-I", "-c", script], check=True) # noqa: S603 - fixed local interpreter and test code - - -def test_missing_dependencies(monkeypatch): - import importlib.util - - monkeypatch.setattr(importlib.util, "find_spec", lambda name: None) - assert not focal.is_available() - with pytest.raises(ImportError, match="FocalCodec requires"): - focal.load_pinned_model() - with pytest.raises(ImportError, match="FocalCodec requires"): - focal.resynthesize(np.zeros((3, 1)), 24000) - - -def _fake(monkeypatch, fault=None): - torch = pytest.importorskip("torch") - calls = [] - - class Model: - def resynthesize_features(self, context_wave): - calls.append(context_wave.numpy().copy()) - c = focal.WAVLM_CONTEXT_EACH - assert np.all(context_wave[:, :c].numpy() == 0.0) - assert np.all(context_wave[:, -c:].numpy() == 0.0) - core = context_wave[:, c:-c].clone() - if fault == "short": - core = core[:, :-1] - if fault == "long": - core = torch.cat((core, core[:, :1]), dim=-1) - if fault == "nan": - core[:] = float("nan") - return core - - monkeypatch.setattr(focal, "is_available", lambda: True) - monkeypatch.setattr(focal, "load_pinned_model", lambda **kw: Model()) - return calls - - -@pytest.mark.parametrize(("mode", "channels"), [("ms", 2), ("lr", 2), ("ms", 1)]) -def test_identity_keeps_raw_gain_channel_mapping_and_symmetric_context(monkeypatch, mode, channels): - calls = _fake(monkeypatch) - x = np.tile(np.array([[1.5, -0.5], [-0.75, 0.25], [0.5, 0.5], [0.0, 0.25]], dtype=np.float32), (80, 1))[ - :, :channels - ] - before = x.copy() - y = focal.resynthesize(x, 16000, stereo_mode=mode) - np.testing.assert_array_equal(y, x) - np.testing.assert_array_equal(x, before) - assert len(calls) == channels - expected = ( - x if mode == "lr" or channels == 1 else np.column_stack(((x[:, 0] + x[:, 1]) / 2, (x[:, 0] - x[:, 1]) / 2)) - ) - c = focal.WAVLM_CONTEXT_EACH - for ch in range(channels): - assert calls[ch].shape == (1, 320 + 2 * c) - np.testing.assert_array_equal(calls[ch][0, c:-c], expected[:, ch]) - - -@pytest.mark.parametrize(("n", "rate"), [(480241, 48000), (4411, 44100), (17, 16000), (1, 48000)]) -def test_fractional_clock_pads_hop_frames_and_returns_exact_native_grid(monkeypatch, n, rate): - calls = _fake(monkeypatch) - x = np.zeros((n, 1), dtype=np.float32) - x[0] = 0.25 - x[-1] = 0.5 - clock = src.RationalClock(n, rate, model_rate=16000, hop=320, minimum_model_frames=320) - y = focal.resynthesize(x, rate) - assert calls[0].shape == (1, clock.padded_frames + 2 * focal.WAVLM_CONTEXT_EACH) - np.testing.assert_array_equal(y, src.inverse(src.forward(x, clock), clock)) - assert y.shape == x.shape - - -@pytest.mark.parametrize("fault", ["short", "long", "nan"]) -def test_model_faults_are_not_repaired(monkeypatch, fault): - _fake(monkeypatch, fault) - with pytest.raises(RuntimeError, match="FocalCodec returned"): - focal.resynthesize(np.ones((320, 2), np.float32), 16000) - - -@pytest.mark.parametrize( - "x", - [ - np.zeros(3), - np.zeros((0, 1)), - np.zeros((3, 3)), - np.zeros((3, 1), dtype=int), - np.array([[np.nan]]), - np.array([[np.inf]]), - ], -) -def test_input_geometry_and_values_rejected(monkeypatch, x): - _fake(monkeypatch) - with pytest.raises(ValueError, match="FocalCodec"): - focal.resynthesize(x, 24000) - - -@pytest.mark.parametrize("rate", [0, -1, True, 24000.0]) -def test_invalid_native_rate(monkeypatch, rate): - _fake(monkeypatch) - with pytest.raises(ValueError, match="positive integer"): - focal.resynthesize(np.ones((3, 1)), rate) - - -def test_unknown_stereo_mode(monkeypatch): - _fake(monkeypatch) - with pytest.raises(ValueError, match="stereo mode"): - focal.resynthesize(np.ones((3, 2)), 24000, stereo_mode="normalize") - - -def _loader( - tmp_path, - monkeypatch, - *, - bad_config=False, - key_count=focal.EXPECTED_STATE_KEY_COUNT, - missing=(), - unexpected=(), - split_dirs=False, -): - pytest.importorskip("torch") - cfg_dir = tmp_path / ("a" if split_dirs else "snap") - ckpt_dir = tmp_path / ("b" if split_dirs else "snap") - cfg_dir.mkdir(parents=True, exist_ok=True) - ckpt_dir.mkdir(parents=True, exist_ok=True) - config_payload = dict(focal._EXPECTED_CONFIG) - if bad_config: - config_payload = {**config_payload, "quantizer_config": {"codebook_size": 1024}} - paths = { - "config.json": cfg_dir / "config.json", - focal.CHECKPOINT_FILENAME: ckpt_dir / focal.CHECKPOINT_FILENAME, - } - paths["config.json"].write_text(json.dumps(config_payload), encoding="utf-8") - paths[focal.CHECKPOINT_FILENAME].write_bytes(b"safetensors-placeholder") - monkeypatch.setattr(focal, "CONFIG_SHA256", hashlib.sha256(paths["config.json"].read_bytes()).hexdigest()) - monkeypatch.setattr( - focal, "CHECKPOINT_SHA256", hashlib.sha256(paths[focal.CHECKPOINT_FILENAME].read_bytes()).hexdigest() - ) - monkeypatch.setattr(focal, "is_available", lambda: True) - built = [] - - def download(**kw): - assert kw["repo_id"] == focal.MODEL_REPOSITORY - assert kw["revision"] == focal.MODEL_REVISION - assert kw["local_files_only"] is True - return str(paths[kw["filename"]]) - - class Model: - def load_state_dict(self, state, *, strict): - assert strict is True - built.append(len(state)) - return SimpleNamespace(missing_keys=list(missing), unexpected_keys=list(unexpected)) - - def to(self, device): - assert device == "cpu" - return self - - def float(self): - return self - - def train(self, mode): - assert mode is False - return self - - def requires_grad_(self, flag): - assert flag is False - return self - - monkeypatch.setitem(sys.modules, "huggingface_hub", SimpleNamespace(hf_hub_download=download)) - monkeypatch.setitem( - sys.modules, - "safetensors.torch", - SimpleNamespace(load_file=lambda p, device: {f"k{i}": i for i in range(key_count)}), - ) - monkeypatch.setattr(focal, "build_focalcodec", lambda cfg: Model()) - return paths, built - - -def test_safe_cpu_safetensors_loading(tmp_path, monkeypatch): - _, built = _loader(tmp_path, monkeypatch) - focal.load_pinned_model() - assert built == [focal.EXPECTED_STATE_KEY_COUNT] - - -@pytest.mark.parametrize("filename", ["config.json", focal.CHECKPOINT_FILENAME]) -def test_bad_hash_stops_before_model_load(tmp_path, monkeypatch, filename): - paths, built = _loader(tmp_path, monkeypatch) - paths[filename].write_bytes(b"tampered") - with pytest.raises(RuntimeError, match="digest mismatch"): - focal.load_pinned_model() - assert not built - - -def test_mismatched_snapshot_parent_rejected(tmp_path, monkeypatch): - _, built = _loader(tmp_path, monkeypatch, split_dirs=True) - with pytest.raises(RuntimeError, match="one snapshot directory"): - focal.load_pinned_model() - assert not built - - -def test_wrong_profile_stops_before_model_load(tmp_path, monkeypatch): - _, built = _loader(tmp_path, monkeypatch, bad_config=True) - with pytest.raises(RuntimeError, match="configuration"): - focal.load_pinned_model() - assert not built - - -def test_wrong_state_key_count_rejected(tmp_path, monkeypatch): - _, built = _loader(tmp_path, monkeypatch, key_count=354) - with pytest.raises(RuntimeError, match="355 state keys"): - focal.load_pinned_model() - assert not built - - -@pytest.mark.parametrize(("missing", "unexpected"), [(["enc.w"], []), ([], ["extra.w"])]) -def test_incomplete_state_load_rejected(tmp_path, monkeypatch, missing, unexpected): - _loader(tmp_path, monkeypatch, missing=missing, unexpected=unexpected) - with pytest.raises(RuntimeError, match="did not load completely"): - focal.load_pinned_model() - - -def test_build_focalcodec_architecture_forward_and_validation(): - torch = pytest.importorskip("torch") - bad = {**focal._EXPECTED_CONFIG, "decoder_name": "UnknownVocoder"} - with pytest.raises(ValueError, match="Only the pinned"): - network.build_focalcodec(bad) - - tiny_cfg = { - "encoder_name": "WavLM", - "encoder_config": { - "hidden_dims": [16, 16], - "kernel_sizes": [10, 3], - "strides": [5, 2], - "num_layers": 1, - "dim": 32, - "ffn_dim": 64, - "num_heads": 4, - "num_buckets": 32, - "max_distance": 64, - "dropout": 0.0, - "conv_pos": 8, - "conv_pos_groups": 4, - }, - "compressor_name": "FocalEncoder", - "compressor_config": { - "input_dim": 32, - "output_dim": 4, - "hidden_dims": [32, 16], - "downscale_factors": [1, 1], - "focal_window": 3, - "focal_level": 2, - "focal_factor": 2, - "dropout": 0.0, - "use_post_norm": False, - "use_layerscale": False, - "layerscale_init": 0.0001, - "normalize_modulator": False, - }, - "quantizer_name": "BinarySphericalQuantizer", - "quantizer_config": {"codebook_size": 16}, - "decompressor_name": "FocalDecoder", - "decompressor_config": { - "input_dim": 4, - "output_dim": 32, - "hidden_dims": [16, 32], - "upscale_factors": [1, 1], - "focal_window": 3, - "focal_level": 2, - "focal_factor": 2, - "dropout": 0.0, - "use_post_norm": False, - "use_layerscale": False, - "layerscale_init": 0.0001, - "normalize_modulator": False, - }, - "decoder_name": "Vocos", - "decoder_config": { - "input_channels": 32, - "num_layers": 1, - "dim": 16, - "ffn_dim": 32, - "kernel_size": 3, - "padding": 1, - "layerscale_init": None, - "n_fft": 32, - "hop_length": 10, - }, - } - model = network.build_focalcodec(tiny_cfg).train(False) - # Receptive field of [k=10,s=5] -> [k=3,s=2] is 10 + 5*(3-1) = 20, total stride 10; - # 30 core samples + (5, 5) symmetric context = 40 -> 3 frames -> 30 output samples. - with torch.inference_mode(): - wave = torch.linspace(-0.25, 0.25, 40, dtype=torch.float32)[None] - out = model.resynthesize_features(wave) - assert tuple(out.shape) == (1, 30) - assert torch.isfinite(out).all() - - -def test_pinned_architecture_exact_355_state_keys(): - pytest.importorskip("torch") - model = network.build_focalcodec(focal._EXPECTED_CONFIG) - assert len(model.state_dict()) == focal.EXPECTED_STATE_KEY_COUNT - - -def test_cached_pinned_checkpoint_end_to_end_when_present(): - if not focal.is_available(): - pytest.skip("Optional FocalCodec dependencies unavailable") - try: - focal.load_pinned_model(local_files_only=True) - except Exception as exc: # pragma: no cover - CI lacks cached model weights - if "LocalEntryNotFoundError" in type(exc).__name__ or "Cannot find the requested files" in str(exc): - pytest.skip("Pinned FocalCodec snapshot not cached locally") - raise - t = np.linspace(0.0, 0.2, 4800, endpoint=False, dtype=np.float32) - wave = (0.15 * np.sin(2 * np.pi * 220.0 * t))[:, None] - out = focal.resynthesize(wave, 24000, local_files_only=True) - assert out.shape == (4800, 1) - assert out.dtype == np.float32 - assert np.isfinite(out).all() - - -def test_resynthesize_conditioned_preconditions_midband_and_restores_subband_envelopes(monkeypatch): - monkeypatch.setattr(focal, "is_available", lambda: True) - seen_inputs = [] - - def fake_resynthesize(samples, sample_rate, *, stereo_mode="ms", local_files_only=True): - assert stereo_mode == "ms" - seen_inputs.append((samples.copy(), sample_rate, local_files_only)) - # Simulate Vocos 50 Hz codec attenuating 300 Hz speech band by 0.5x and generating slight pause hiss. - out = samples * 0.5 - out[-2400:] += 0.02 - return out - - monkeypatch.setattr(focal, "resynthesize", fake_resynthesize) - sr = 24000 - t = np.arange(sr, dtype=np.float32) / sr - carrier = np.zeros((sr, 2), dtype=np.float32) - # Active speech-band carrier in first 0.8s + 1250 Hz Perth-band tone; silence in final 0.2s. - carrier[:19200, 0] = 0.25 * np.sin(2 * np.pi * 300.0 * t[:19200]) + 0.10 * np.sin(2 * np.pi * 1250.0 * t[:19200]) - carrier[:19200, 1] = 0.20 * np.sin(2 * np.pi * 300.0 * t[:19200]) - - delivered = focal.resynthesize_conditioned(carrier, sr, local_files_only=False) - assert delivered.shape == (sr, 2) - assert delivered.dtype == np.float32 - assert np.isfinite(delivered).all() - assert len(seen_inputs) == 1 - pre_input, seen_sr, seen_local = seen_inputs[0] - assert seen_sr == sr - assert seen_local is False - # 1250 Hz mark band must be strongly notched before reaching FocalCodec encoder. - spec_src = np.abs(np.fft.rfft(carrier[:19200, 0])) - spec_pre = np.abs(np.fft.rfft(pre_input[:19200, 0])) - freqs = np.fft.rfftfreq(19200, d=1.0 / sr) - idx_1250 = int(np.argmin(np.abs(freqs - 1250.0))) - assert spec_pre[idx_1250] < spec_src[idx_1250] * 0.05 - # Active 300 Hz speech band energy is restored close to source despite 0.5x codec attenuation, - # while trailing silence hiss (0.02) is suppressed toward zero. - rms_src_active = float(np.sqrt(np.mean(carrier[2400:16800, 1] ** 2))) - rms_out_active = float(np.sqrt(np.mean(delivered[2400:16800, 1] ** 2))) - assert abs(20.0 * np.log10(rms_out_active / rms_src_active)) < 0.5 - assert float(np.sqrt(np.mean(delivered[-1200:, 0] ** 2))) < 0.001 - - -def test_resynthesize_conditioned_soft_knee_bounds_constructive_subband_spikes(monkeypatch): - pytest.importorskip("scipy") - monkeypatch.setattr(focal, "is_available", lambda: True) - - sr = 24000 - t = np.arange(sr, dtype=np.float32) / sr - # Source peak stays comfortably under full scale (~0.86), mimicking ElevenLabs speech dynamics. - source = ( - 0.45 * np.sin(2 * np.pi * 240.0 * t) - + 0.25 * np.sin(2 * np.pi * 900.0 * t) - + 0.16 * np.sin(2 * np.pi * 2600.0 * t) - ).astype(np.float32)[:, None] - - def fake_resynthesize_spiky(samples, sample_rate, *, stereo_mode="ms", local_files_only=True): - # Attenuated steady body (triggering 2.5x subband boost) with constructive phase spike at mid-clip - out = samples * 0.42 - out[11995:12005, 0] = 0.65 - return out - - monkeypatch.setattr(focal, "resynthesize", fake_resynthesize_spiky) - delivered = focal.resynthesize_conditioned(source, sr, local_files_only=False) - assert float(np.max(np.abs(delivered))) <= 0.98 - assert int(np.count_nonzero(np.abs(delivered) > 1.0)) == 0 diff --git a/tests/test_audio_mimi.py b/tests/test_audio_mimi.py deleted file mode 100644 index 6c48240..0000000 --- a/tests/test_audio_mimi.py +++ /dev/null @@ -1,219 +0,0 @@ -"""Pinned Mimi loading and native geometry, without downloading model weights.""" - -from __future__ import annotations - -import hashlib -import subprocess -import sys -from pathlib import Path -from types import SimpleNamespace - -import numpy as np -import pytest - -from remove_ai_watermarks._internal import audio_mimi as mimi -from remove_ai_watermarks._internal import audio_resampling as src - - -@pytest.fixture(autouse=True) -def clear_cache(): - mimi.load_pinned_model.cache_clear() - yield - mimi.load_pinned_model.cache_clear() - - -def test_import_is_optional_stack_pure(): - root = Path(__file__).resolve().parents[1] / "src" - script = f"import sys; sys.path.insert(0, {str(root)!r}); import remove_ai_watermarks._internal.audio_mimi; " - script += ( - "assert not {'torch','numpy','scipy','transformers','huggingface_hub','safetensors'}.intersection(sys.modules)" - ) - subprocess.run([sys.executable, "-I", "-c", script], check=True) # noqa: S603 - fixed local interpreter and test code - - -def test_missing_dependencies(monkeypatch): - monkeypatch.setattr(mimi.importlib.util, "find_spec", lambda name: None) - assert not mimi.is_available() - with pytest.raises(ImportError): - mimi.load_pinned_model() - with pytest.raises(ImportError): - mimi.resynthesize(np.zeros((3, 1)), 24000) - - -def _fake(monkeypatch, fault=None): - torch = pytest.importorskip("torch") - calls = [] - - class Model: - def __call__(self, value, *, padding_mask): - calls.append(value.numpy().copy()) - assert padding_mask.shape == value.shape - assert padding_mask.all() - result = value.clone() - if fault == "short": - result = result[..., :-1] - if fault == "long": - result = torch.cat((result, result[..., :1]), dim=-1) - if fault == "channels": - result = result[:0] - if fault == "nan": - result[:] = float("nan") - return SimpleNamespace(audio_values=result) - - monkeypatch.setattr(mimi, "is_available", lambda: True) - monkeypatch.setattr(mimi, "load_pinned_model", lambda **kw: Model()) - return calls - - -@pytest.mark.parametrize(("mode", "channels"), [("ms", 2), ("lr", 2), ("ms", 1)]) -def test_identity_keeps_raw_gain_and_channel_mapping(monkeypatch, mode, channels): - calls = _fake(monkeypatch) - x = np.array([[1.5, -0.5], [-0.75, 0.25], [0.5, 0.5]], dtype=np.float32)[:, :channels] - before = x.copy() - y = mimi.resynthesize(x, 24000, stereo_mode=mode) - np.testing.assert_array_equal(y, x) - np.testing.assert_array_equal(x, before) - expected = ( - x if mode == "lr" or channels == 1 else np.column_stack(((x[:, 0] + x[:, 1]) / 2, (x[:, 0] - x[:, 1]) / 2)) - ) - np.testing.assert_array_equal(calls[0][:, 0, :].T, expected) - - -@pytest.mark.parametrize(("n", "rate"), [(480241, 48000), (4411, 44100), (17, 16000), (1, 48000)]) -def test_fractional_clock_no_external_model_padding(monkeypatch, n, rate): - calls = _fake(monkeypatch) - x = np.zeros((n, 1), dtype=np.float32) - x[0] = 0.25 - x[-1] = 0.5 - clock = src.RationalClock(n, rate, 24000, 1, 1) - y = mimi.resynthesize(x, rate) - assert calls[0].shape == (1, 1, clock.model_frames) - np.testing.assert_array_equal(y, src.inverse(src.forward(x, clock), clock)) - assert y.shape == x.shape - - -@pytest.mark.parametrize("fault", ["short", "long", "channels", "nan"]) -def test_model_faults_are_not_repaired(monkeypatch, fault): - _fake(monkeypatch, fault) - with pytest.raises(RuntimeError, match="Mimi returned"): - mimi.resynthesize(np.ones((9, 2), np.float32), 24000) - - -@pytest.mark.parametrize( - "x", - [ - np.zeros(3), - np.zeros((0, 1)), - np.zeros((3, 3)), - np.zeros((3, 1), dtype=int), - np.array([[np.nan]]), - np.array([[np.inf]]), - ], -) -def test_input_geometry_and_values_rejected(monkeypatch, x): - _fake(monkeypatch) - with pytest.raises(ValueError, match="Mimi"): - mimi.resynthesize(x, 24000) - - -@pytest.mark.parametrize("rate", [0, -1, True, 24000.0]) -def test_invalid_native_rate(monkeypatch, rate): - _fake(monkeypatch) - with pytest.raises(ValueError, match="positive integer"): - mimi.resynthesize(np.ones((3, 1)), rate) - - -def test_unknown_stereo_mode(monkeypatch): - _fake(monkeypatch) - with pytest.raises(ValueError, match="stereo mode"): - mimi.resynthesize(np.ones((3, 2)), 24000, stereo_mode="normalize") - - -def _loader(tmp_path, monkeypatch, *, bad_config=False, loading=None): - torch = pytest.importorskip("torch") - paths = {"config.json": tmp_path / "config.json", mimi.CHECKPOINT_FILENAME: tmp_path / mimi.CHECKPOINT_FILENAME} - for p in paths.values(): - p.write_bytes(p.name.encode()) - monkeypatch.setattr(mimi, "CONFIG_SHA256", hashlib.sha256(paths["config.json"].read_bytes()).hexdigest()) - monkeypatch.setattr( - mimi, "CHECKPOINT_SHA256", hashlib.sha256(paths[mimi.CHECKPOINT_FILENAME].read_bytes()).hexdigest() - ) - monkeypatch.setattr(mimi, "is_available", lambda: True) - config = SimpleNamespace( - model_type="mimi", - sampling_rate=24000, - audio_channels=1, - num_quantizers=8 if bad_config else 32, - use_cache=False, - normalize=False, - use_causal_conv=True, - trim_right_ratio=1.0, - ) - calls = [] - - def download(**kw): - assert kw["repo_id"] == mimi.MODEL_REPOSITORY - assert kw["revision"] == mimi.MODEL_REVISION - assert kw["local_files_only"] is True - return str(paths[kw["filename"]]) - - class Model: - def __init__(self): - self.config = config - - def to(self, device): - assert device == "cpu" - return self - - def train(self, mode): - assert mode is False - return self - - def load(path, **kw): - calls.append(kw) - assert kw["use_safetensors"] is True - assert kw["trust_remote_code"] is False - assert kw["local_files_only"] is True - assert kw["output_loading_info"] is True - assert kw["dtype"] is torch.float32 - return Model(), loading or {} - - monkeypatch.setitem(sys.modules, "huggingface_hub", SimpleNamespace(hf_hub_download=download)) - monkeypatch.setitem( - sys.modules, - "transformers", - SimpleNamespace( - MimiConfig=SimpleNamespace(from_pretrained=lambda *a, **k: config), - MimiModel=SimpleNamespace(from_pretrained=load), - ), - ) - return paths, calls - - -def test_safe_builtin_cpu_loading(tmp_path, monkeypatch): - _, calls = _loader(tmp_path, monkeypatch) - assert mimi.load_pinned_model().config.num_quantizers == 32 - assert len(calls) == 1 - - -@pytest.mark.parametrize("filename", ["config.json", mimi.CHECKPOINT_FILENAME]) -def test_bad_hash_stops_before_model_load(tmp_path, monkeypatch, filename): - paths, calls = _loader(tmp_path, monkeypatch) - paths[filename].write_bytes(b"tampered") - with pytest.raises(RuntimeError, match="digest mismatch"): - mimi.load_pinned_model() - assert not calls - - -def test_wrong_profile_stops_before_model_load(tmp_path, monkeypatch): - _, calls = _loader(tmp_path, monkeypatch, bad_config=True) - with pytest.raises(RuntimeError, match="configuration"): - mimi.load_pinned_model() - assert not calls - - -@pytest.mark.parametrize("key", ["missing_keys", "unexpected_keys", "mismatched_keys", "error_msgs"]) -def test_incomplete_load_rejected(tmp_path, monkeypatch, key): - _loader(tmp_path, monkeypatch, loading={key: ["fault"]}) - with pytest.raises(RuntimeError, match="did not load completely"): - mimi.load_pinned_model() diff --git a/tests/test_audio_vocoder.py b/tests/test_audio_vocoder.py deleted file mode 100644 index 57e8aea..0000000 --- a/tests/test_audio_vocoder.py +++ /dev/null @@ -1,174 +0,0 @@ -"""Pinned loading and full-track semantics with in-memory models, no downloads.""" - -import hashlib -import json -import subprocess -import sys -from pathlib import Path -from types import SimpleNamespace - -import numpy as np -import pytest - -from remove_ai_watermarks._internal import audio_resampling as src -from remove_ai_watermarks._internal import audio_vocoder as vocoder - - -def _identity_model(monkeypatch, fault=None): - torch = pytest.importorskip("torch") - calls = [] - - def model(value): - calls.append(value.clone()) - result = value.unsqueeze(1) - if fault == "short": - return result[..., :-1] - if fault == "nonfinite": - return result * float("nan") - return result - - monkeypatch.setattr(vocoder, "is_available", lambda: True) - monkeypatch.setattr(vocoder, "load_pinned_model", lambda *a, **kw: model) - monkeypatch.setattr(vocoder, "mel_spectrogram", lambda a: torch.from_numpy(a).unsqueeze(0)) - return calls - - -@pytest.mark.parametrize("channels", [1, 2]) -@pytest.mark.parametrize("frames", [1, 2, 160, 1115, 480240]) -def test_identity_model_retains_native_grid_and_raw_mid_side(monkeypatch, frames, channels): - calls = _identity_model(monkeypatch) - value = np.random.default_rng(31).normal(size=(frames, channels)).astype(np.float32) * 2 - result = vocoder.resynthesize(value, 48000) - clock = src.RationalClock(frames, 48000) - reference = src.inverse(src.forward(value, clock), clock) - np.testing.assert_allclose(result, reference, rtol=3e-5, atol=3e-6) - assert result.shape == value.shape - assert result.dtype == np.float32 - assert len(calls) == channels - if channels == 2: - mid = (value[:, 0] + value[:, 1]) / 2 - side = (value[:, 0] - value[:, 1]) / 2 - for call, expected in zip(calls, (mid, side), strict=True): - np.testing.assert_array_equal(call.numpy()[0], src.pad_model(src.forward(expected, clock), clock)) - if frames > 100: - assert np.max(np.abs(result)) > 1 # No additional clipping or normalization. - - -@pytest.mark.parametrize("fault", ["short", "nonfinite"]) -def test_invalid_model_output_rejected(monkeypatch, fault): - _identity_model(monkeypatch, fault) - with pytest.raises(RuntimeError, match="BigVGAN returned"): - vocoder.resynthesize(np.ones((1024, 2), dtype=np.float32), 48000) - - -@pytest.mark.parametrize( - "value", - [ - np.zeros(5), - np.zeros((0, 1)), - np.zeros((5, 3)), - np.zeros((5, 1), dtype=np.int16), - np.full((5, 1), np.nan), - np.full((5, 1), np.inf), - ], -) -def test_bad_source_fails_before_model_load(monkeypatch, value): - monkeypatch.setattr(vocoder, "is_available", lambda: True) - monkeypatch.setattr(vocoder, "load_pinned_model", lambda *a, **kw: pytest.fail("Loaded invalid source")) - with pytest.raises(ValueError, match="BigVGAN"): - vocoder.resynthesize(value, 48000) - - -def test_import_does_not_load_optional_runtimes(): - root = Path(__file__).resolve().parents[1] / "src" - code = f""" -import sys -sys.path.insert(0, {str(root)!r}) -from remove_ai_watermarks._internal import audio_vocoder, audio_resampling, _bigvgan_network -assert not any(name in sys.modules for name in ('numpy', 'scipy', 'torch', 'librosa', 'huggingface_hub')) -""" - completed = subprocess.run([sys.executable, "-I", "-c", code], capture_output=True, text=True, check=False) # noqa: S603 - assert completed.returncode == 0, completed.stderr - - -def test_missing_dependencies_fail_before_import(monkeypatch): - vocoder.load_pinned_model.cache_clear() - monkeypatch.setattr(vocoder.importlib.util, "find_spec", lambda name: None) - assert not vocoder.is_available() - with pytest.raises(RuntimeError, match="requires numpy"): - vocoder.load_pinned_model() - - -def _loading_fixture(tmp_path, monkeypatch): - torch = pytest.importorskip("torch") - vocoder.load_pinned_model.cache_clear() - config = tmp_path / "config.json" - config.write_text(json.dumps({"fixture": True})) - checkpoint = tmp_path / vocoder.CHECKPOINT_FILENAME - torch.save({"generator": {"weight": torch.ones(1, 1)}}, checkpoint) - monkeypatch.setattr(vocoder, "CONFIG_SHA256", hashlib.sha256(config.read_bytes()).hexdigest()) - monkeypatch.setattr(vocoder, "CHECKPOINT_SHA256", hashlib.sha256(checkpoint.read_bytes()).hexdigest()) - requests = [] - - def download(**kwargs): - requests.append(kwargs) - return str(tmp_path / kwargs["filename"]) - - monkeypatch.setitem(sys.modules, "huggingface_hub", SimpleNamespace(hf_hub_download=download)) - monkeypatch.setattr(vocoder, "is_available", lambda: True) - return torch, config, checkpoint, requests - - -@pytest.mark.parametrize("artifact", ["config", "checkpoint"]) -def test_wrong_digest_rejected_before_deserialization(tmp_path, monkeypatch, artifact): - torch, config, checkpoint, _ = _loading_fixture(tmp_path, monkeypatch) - (config if artifact == "config" else checkpoint).write_bytes(b"wrong bytes") - monkeypatch.setattr(torch, "load", lambda *a, **kw: pytest.fail("Deserialized wrong digest")) - monkeypatch.setattr(vocoder, "build_generator", lambda *a: pytest.fail("Built before checking both hashes")) - with pytest.raises(RuntimeError, match="digest mismatch"): - vocoder.load_pinned_model() - - -def test_incomplete_checkpoint_fails_before_weight_norm_removal(tmp_path, monkeypatch): - torch, _, _, _ = _loading_fixture(tmp_path, monkeypatch) - model = torch.nn.Linear(1, 1) # Missing bias in the saved state. - model.remove_weight_norm = lambda: pytest.fail("Removed weight norm before strict state check") - monkeypatch.setattr(vocoder, "build_generator", lambda config: model) - with pytest.raises(RuntimeError, match="Missing key"): - vocoder.load_pinned_model() - - -def test_weights_only_strict_loading_then_weight_norm_removal(tmp_path, monkeypatch): - torch, _, _, requests = _loading_fixture(tmp_path, monkeypatch) - events = [] - original_load = torch.load - - def load(*args, **kwargs): - assert kwargs == {"map_location": "cpu", "weights_only": True} - events.append("weights_only") - return original_load(*args, **kwargs) - - class Model(torch.nn.Linear): - def load_state_dict(self, state, strict=True): - assert strict is True - events.append("strict") - return super().load_state_dict(state, strict=strict) - - def remove_weight_norm(self): - events.append("remove") - - monkeypatch.setattr(torch, "load", load) - monkeypatch.setattr(vocoder, "build_generator", lambda config: Model(1, 1, bias=False)) - model = vocoder.load_pinned_model() - assert events == ["weights_only", "strict", "remove"] - assert not model.training - assert not model.weight.requires_grad - assert model.weight.dtype == torch.float32 - assert all(r["revision"] == vocoder.MODEL_REVISION and r["local_files_only"] is True for r in requests) - vocoder.load_pinned_model.cache_clear() - - -@pytest.mark.parametrize("device", ["auto", "gpu", "cpu:1"]) -def test_unknown_device_is_rejected(device): - with pytest.raises(ValueError, match="device"): - vocoder.load_pinned_model(device) diff --git a/tests/test_av_wave10_prod.py b/tests/test_av_wave10_prod.py index 41c2774..f434269 100644 --- a/tests/test_av_wave10_prod.py +++ b/tests/test_av_wave10_prod.py @@ -46,13 +46,15 @@ def _make_mp4(path: Path, *, width: int = 64, height: int = 48, fps: int = 12, d def test_wan21_4k_guided_window_preserves_4k_resolution_and_detail() -> None: pytest.importorskip("torch") - assert video_wan.WAN21_MAX_FRAME_PIXELS == 3840 * 2160 assert video_wan._wan_guide_size(1920, 1080) is None guide_size = video_wan._wan_guide_size(3840, 2160) assert guide_size is not None assert guide_size[0] * guide_size[1] <= video_wan.WAN21_NATIVE_MAX_PIXELS assert guide_size[0] % 16 == 0 assert guide_size[1] % 16 == 0 + guide_8k = video_wan._wan_guide_size(7680, 4320) + assert guide_8k is not None + assert guide_8k[0] * guide_8k[1] <= video_wan.WAN21_NATIVE_MAX_PIXELS seen_sizes: list[tuple[int, int]] = [] diff --git a/tests/test_av_wave11_v073.py b/tests/test_av_wave11_v073.py new file mode 100644 index 0000000..57f41a1 --- /dev/null +++ b/tests/test_av_wave11_v073.py @@ -0,0 +1,161 @@ +"""Tests for v0.72.0 unified container/format support, DAC default HF preservation, and pruned experimental backends.""" + +from __future__ import annotations + +import shutil +import wave +from typing import TYPE_CHECKING + +import pytest + +if TYPE_CHECKING: + from pathlib import Path + + +def _write_wav(path: Path, *, sample_rate: int = 44100, seconds: float = 0.5, channels: int = 1) -> Path: + import math + import struct + + n_frames = int(sample_rate * seconds) + samples = [] + for i in range(n_frames): + val = int(12000 * math.sin(2.0 * math.pi * 440.0 * i / sample_rate)) + for _ in range(channels): + samples.append(val) + with wave.open(str(path), "wb") as wf: + wf.setnchannels(channels) + wf.setsampwidth(2) + wf.setframerate(sample_rate) + wf.writeframes(struct.pack(f"<{len(samples)}h", *samples)) + return path + + +@pytest.mark.parametrize("method", ["bigvgan", "mimi", "focalcodec"]) +def test_removed_experimental_audio_methods_are_rejected(tmp_path: Path, method: str) -> None: + from remove_ai_watermarks import audio + + source = _write_wav(tmp_path / "src.wav", sample_rate=16000) + with pytest.raises(ValueError, match="Audio method must be"): + audio.remove_audio_invisible(source, tmp_path / "out.wav", method=method, force=True, verify=False) # type: ignore[arg-type] + + +def test_removed_silentcipher16_scheme_is_rejected(tmp_path: Path) -> None: + from remove_ai_watermarks import audio + + source = _write_wav(tmp_path / "src.wav", sample_rate=16000) + with pytest.raises(ValueError, match="Audio scheme must be"): + audio.identify_audio(source, scheme="silentcipher16") # type: ignore[arg-type] + + +@pytest.mark.parametrize("suffix", [".aac", ".oga", ".mka"]) +def test_unified_audio_output_formats_encode_and_probe(tmp_path: Path, suffix: str) -> None: + pytest.importorskip("numpy") + pytest.importorskip("scipy") + if shutil.which("ffmpeg") is None or shutil.which("ffprobe") is None: + pytest.skip("ffmpeg/ffprobe required") + + from remove_ai_watermarks import audio + + source = _write_wav(tmp_path / "src.wav", sample_rate=44100, seconds=0.4, channels=2) + output = tmp_path / f"clean{suffix}" + result = audio.remove_audio_invisible(source, output, method="spectral", force=True, verify=False) + assert result.output == output + assert output.is_file() + assert result.after is not None + assert result.after.stream.channels == 2 + assert result.frames_processed > 0 + + +def test_dac_defaults_preserve_hf_14khz_on_44k_and_leaves_16k_none(tmp_path: Path, monkeypatch) -> None: + pytest.importorskip("numpy") + pytest.importorskip("scipy") + if shutil.which("ffmpeg") is None or shutil.which("ffprobe") is None: + pytest.skip("ffmpeg/ffprobe required") + + from remove_ai_watermarks import audio + + seen: list[tuple[int, float | None]] = [] + + def fake_dac(samples, sample_rate, *, local_files_only=False, device="cpu", preserve_hf_hz=None): + seen.append((sample_rate, preserve_hf_hz)) + return samples + + monkeypatch.setattr(audio.audio_dac, "is_available", lambda: True) + monkeypatch.setattr(audio.audio_dac, "resynthesize", fake_dac) + + src_44k = _write_wav(tmp_path / "src44.wav", sample_rate=44100, seconds=0.3, channels=1) + audio.remove_audio_invisible(src_44k, tmp_path / "out44_default.wav", method="dac", force=True, verify=False) + audio.remove_audio_invisible( + src_44k, tmp_path / "out44_custom.wav", method="dac", preserve_hf_hz=12000.0, force=True, verify=False + ) + src_16k = _write_wav(tmp_path / "src16.wav", sample_rate=16000, seconds=0.3, channels=1) + audio.remove_audio_invisible(src_16k, tmp_path / "out16_default.wav", method="dac", force=True, verify=False) + + assert seen == [(44100, 14000.0), (44100, 12000.0), (16000, None)] + + +def test_unified_video_container_constants_match_all_pipelines() -> None: + from remove_ai_watermarks._internal.constants import ( + AUDIO_EXTENSIONS, + AUDIO_OUTPUT_EXTENSIONS, + WAN_SUPPORTED_EXTENSIONS, + ) + from remove_ai_watermarks.video import _REGENERATED_VIDEO_EXTENSIONS, VIDEO_EXTENSIONS + + assert WAN_SUPPORTED_EXTENSIONS == VIDEO_EXTENSIONS == _REGENERATED_VIDEO_EXTENSIONS + assert AUDIO_OUTPUT_EXTENSIONS == AUDIO_EXTENSIONS + for ext in (".mp4", ".mov", ".m4v", ".mkv", ".webm", ".avi", ".flv"): + assert ext in WAN_SUPPORTED_EXTENSIONS + for ext in (".wav", ".flac", ".mp3", ".m4a", ".ogg", ".oga", ".opus", ".aac", ".mka"): + assert ext in AUDIO_OUTPUT_EXTENSIONS + + +def test_top_level_identify_audio_and_all_text_cli_dispatch(tmp_path: Path) -> None: + from click.testing import CliRunner + + from remove_ai_watermarks.cli import main + + wav_src = _write_wav(tmp_path / "clip.wav", sample_rate=16000, seconds=0.2) + if shutil.which("ffprobe") is not None: + res_audio = CliRunner().invoke(main, ["identify", str(wav_src), "--no-visible", "--json"]) + assert res_audio.exit_code == 0, res_audio.output + + md_src = tmp_path / "note.md" + md_src.write_text("# Title\n\nPlain text without watermarks.\n", encoding="utf-8") + md_out = tmp_path / "note_clean.md" + res_text = CliRunner().invoke(main, ["all", str(md_src), "-o", str(md_out)]) + assert res_text.exit_code in (0, 2), res_text.output + + +def test_m4v_10bit_hdr_raw_video_command_uses_mp4_muxer(tmp_path: Path) -> None: + from remove_ai_watermarks.video_encoding import VideoEncodeProfile, raw_video_command + + if shutil.which("ffmpeg") is None: + pytest.skip("ffmpeg required") + prof = VideoEncodeProfile(pixel_format="yuv420p10le", component_depth=10) + cmd = raw_video_command(tmp_path / "out.m4v", width=64, height=64, fps=24.0, crf=18, profile=prof) + assert cmd[-3:-1] == ["-f", "mp4"] + + +def test_resolve_preset_preserves_explicit_cv2_backend() -> None: + from remove_ai_watermarks.cli import _resolve_preset + + _eff_force, eff_backend, _lossless = _resolve_preset("balanced", force=False, backend="cv2") + assert eff_backend == "cv2" + + +def test_truncated_aac_output_is_rejected_by_measure_fidelity(tmp_path: Path) -> None: + pytest.importorskip("numpy") + if shutil.which("ffmpeg") is None or shutil.which("ffprobe") is None: + pytest.skip("ffmpeg/ffprobe required") + + from remove_ai_watermarks._internal import audio_io, audio_quality + + src = _write_wav(tmp_path / "long.wav", sample_rate=44100, seconds=1.0, channels=1) + short = _write_wav(tmp_path / "short.wav", sample_rate=44100, seconds=0.2, channels=1) + src_info = audio_io.probe_audio(src) + short_info = audio_io.probe_audio(short) + trunc_aac = tmp_path / "trunc.aac" + audio_io.write_audio(short_info, trunc_aac, audio_io.read_audio(short, short_info)) + with pytest.raises(RuntimeError, match="decoded sample-frame count"): + audio_quality.measure_fidelity(src, src_info, trunc_aac) diff --git a/tests/test_av_wave5a_features.py b/tests/test_av_wave5a_features.py index 3589641..51b44c7 100644 --- a/tests/test_av_wave5a_features.py +++ b/tests/test_av_wave5a_features.py @@ -373,5 +373,5 @@ def test_video_messages_accepts_mkv_and_webm_suffix(tmp_path: Path) -> None: src = tmp_path / "clip.mp4" src.write_bytes(b"") - with pytest.raises(ValueError, match="MP4, MOV, M4V, MKV, or WebM"): - video_messages.remove_video_message(src, tmp_path / "out.avi", reference_hex="0" * 64) + with pytest.raises(ValueError, match="MP4, MOV, M4V, MKV, WebM, AVI, or FLV"): + video_messages.remove_video_message(src, tmp_path / "out.wmv", reference_hex="0" * 64) diff --git a/tests/test_av_wave8_features.py b/tests/test_av_wave8_features.py index 2f58c8e..2901280 100644 --- a/tests/test_av_wave8_features.py +++ b/tests/test_av_wave8_features.py @@ -96,8 +96,7 @@ def test_audio_auto_scrub_restricts_to_certified_vendors_and_resolves_device( # CPU-only profiles always resolve "auto" to "cpu" assert audio.resolve_audio_device("auto", "spectral") == "cpu" - assert audio.resolve_audio_device("auto", "mimi") == "cpu" - assert audio.resolve_audio_device("auto", "focalcodec") == "cpu" + assert audio.resolve_audio_device("auto", "spectral") == "cpu" assert audio.resolve_audio_device("cpu", "dac") == "cpu" assert audio.resolve_audio_device("auto", "dac") in {"cpu", "mps", "cuda"} diff --git a/tests/test_codex_plugin.py b/tests/test_codex_plugin.py index 9c36f8d..f019e9f 100644 --- a/tests/test_codex_plugin.py +++ b/tests/test_codex_plugin.py @@ -71,5 +71,9 @@ def test_no_tracked_code_matches_the_scanner_dynamic_execution_rule() -> None: ).stdout.split() assert tracked rule = re.compile(r"\beval\s*\(") - offenders = [name for name in tracked if rule.search((ROOT / name).read_text(encoding="utf-8", errors="ignore"))] + offenders = [ + name + for name in tracked + if (ROOT / name).is_file() and rule.search((ROOT / name).read_text(encoding="utf-8", errors="ignore")) + ] assert offenders == [] diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index d9a8cfb..e808eee 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -67,16 +67,16 @@ def test_audio_tools_reject_invalid_track_ordinals(stream): @pytest.mark.parametrize("tool", ["audio_identify", "audio_invisible", "video_audio"]) -def test_audio_tools_preserve_explicit_silentcipher16_scope(tool): +def test_audio_tools_preserve_explicit_silentcipher_scope(tool): runner = _Recorder(stdout="{}") - arguments = {"path": "clip.mkv" if tool == "video_audio" else "speech.wav", "scheme": "silentcipher16"} + arguments = {"path": "clip.mkv" if tool == "video_audio" else "speech.wav", "scheme": "silentcipher"} if tool != "audio_identify": arguments["output"] = "processed.mkv" if tool == "video_audio" else "processed.wav" result = mcp_server.call_tool(tool, arguments, runner) assert result.get("isError") is not True assert len(runner.calls) == 1 command = runner.calls[0] - assert command[command.index("--scheme") + 1] == "silentcipher16" + assert command[command.index("--scheme") + 1] == "silentcipher" def test_audio_tool_refuses_source_output(): @@ -125,18 +125,18 @@ def test_neural_audio_options_are_forwarded_to_the_cli(): assert runner.calls[0][-6:] == ["--method", "encodec", "--bandwidth", "6", "--", "input.wav"] -def test_bigvgan_audio_options_reach_legacy_and_catalog_mcp(): +def test_dac_audio_options_reach_legacy_and_catalog_mcp(): runner = _Recorder(stdout="{}") result = mcp_server.call_tool( - "audio_invisible", {"path": "input.wav", "method": "bigvgan", "vocoder_device": "mps"}, runner + "audio_invisible", {"path": "input.wav", "method": "dac", "vocoder_device": "mps"}, runner ) assert result["isError"] is False - assert runner.calls[0][-6:] == ["--method", "bigvgan", "--vocoder-device", "mps", "--", "input.wav"] + assert runner.calls[0][-6:] == ["--method", "dac", "--vocoder-device", "mps", "--", "input.wav"] from remove_ai_watermarks.integration import operation_catalog, plan_operation operation = next(item for item in operation_catalog() if item["id"] == "cli_video_audio") - args, _ = plan_operation(operation, {"source": "input.mp4", "method": "bigvgan", "vocoder_device": "mps"}) - assert args[args.index("--method") + 1] == "bigvgan" + args, _ = plan_operation(operation, {"source": "input.mp4", "method": "dac", "vocoder_device": "mps"}) + assert args[args.index("--method") + 1] == "dac" assert args[args.index("--vocoder-device") + 1] == "mps" @@ -437,7 +437,6 @@ def test_legacy_audio_and_video_message_tools_stay_in_lockstep_with_cli_catalog_ "wavmark", "perth", "silentcipher", - "silentcipher16", "all", "auto", ) @@ -446,9 +445,6 @@ def test_legacy_audio_and_video_message_tools_stay_in_lockstep_with_cli_catalog_ "spectral", "encodec", "combined", - "bigvgan", - "mimi", - "focalcodec", "dac", "snac", ) diff --git a/tests/test_media_removal_benchmark.py b/tests/test_media_removal_benchmark.py index 683a439..2733f0d 100644 --- a/tests/test_media_removal_benchmark.py +++ b/tests/test_media_removal_benchmark.py @@ -494,7 +494,7 @@ def test_perceptual_audio_metrics_phase_invariance_and_markdown_rendering( shutil.copyfile(inv_wav, out) return SimpleNamespace( output=out, - method="focalcodec", + method="dac", before=SimpleNamespace(watermark_status="detected"), after=SimpleNamespace(watermark_status="not_detected"), skipped=False, @@ -512,7 +512,7 @@ def test_perceptual_audio_metrics_phase_invariance_and_markdown_rendering( source_sha256=sha256_file(src_wav), output_suffix=".wav", expected_outcome="verified_removed", - method="focalcodec", + method="dac", ) delivered_dir = tmp_path / "delivered" delivered_dir.mkdir() diff --git a/tests/test_silentcipher16_runtime.py b/tests/test_silentcipher16_runtime.py deleted file mode 100644 index dba579c..0000000 --- a/tests/test_silentcipher16_runtime.py +++ /dev/null @@ -1,120 +0,0 @@ -"""Receiver guards for the experimental terminated eight-symbol profile.""" - -from types import SimpleNamespace - -import numpy as np -import pytest - -from remove_ai_watermarks._internal import silentcipher16 - - -def _raw(payload=(0, 1, 2, 0, 2, 1, 0), cycles=4): - symbols = [value + 1 for value in payload] + [0] - return np.eye(4, dtype=np.float32)[np.tile(symbols, cycles)].T - - -@pytest.mark.parametrize("payload", [(0,) * 7, (2,) * 7, (0, 1, 2, 0, 2, 1, 0)]) -def test_symbols_are_canonical_and_never_truncated_into_bytes(payload): - for offset in range(8): - found, agreement = silentcipher16._decode_sequence(np.roll(_raw(payload), offset, axis=1)) - assert found == payload - assert agreement == 1 - - -@pytest.mark.parametrize("symbol", range(4)) -def test_constant_class_bias_is_not_a_valid_frame(symbol): - raw = np.eye(4, dtype=np.float32)[np.full(32, symbol)].T - assert silentcipher16._decode_sequence(raw)[0] is None - - -def test_multiple_terminators_are_not_a_valid_frame(): - labels = _raw().argmax(axis=0) - labels[::8] = 0 - assert silentcipher16._decode_sequence(np.eye(4, dtype=np.float32)[labels].T)[0] is None - - -@pytest.mark.parametrize("fault", ["nan", "shape", "short"]) -def test_bad_neural_values_and_incomplete_repetitions_remain_unverified(fault): - raw = _raw() - if fault == "nan": - raw[0, 0] = np.nan - elif fault == "shape": - raw = raw[:3] - else: - raw = raw[:, :23] - with pytest.raises(RuntimeError): - silentcipher16._decode_sequence(raw) - - -def _model(monkeypatch, outputs, hop=30): - torch = pytest.importorskip("torch") - from remove_ai_watermarks._internal import _silentcipher_network - - iterator = iter(outputs) - monkeypatch.setattr(silentcipher16, "HOP_LENGTH", hop) - monkeypatch.setattr(_silentcipher_network, "magnitude", lambda samples, window, **kwargs: samples) - return silentcipher16.base.DecoderModel(lambda _: torch.from_numpy(next(iterator))[None, None], None, "cpu") - - -def test_invalid_strong_phase_cannot_hide_a_valid_foreign_message(monkeypatch): - bias = np.eye(4, dtype=np.float32)[np.ones(32, dtype=int)].T - expected = (2, 1, 0, 2, 1, 0, 2) - model = _model(monkeypatch, [bias, _raw(expected), bias]) - result = silentcipher16.read(model, np.ones(48000)) - assert result.payload_symbols == expected - assert result.phase_offset == 10 - assert result.phases_checked == 2 - - -def test_negative_requires_every_phase_in_the_grid(monkeypatch): - bias = np.eye(4, dtype=np.float32)[np.ones(32, dtype=int)].T - result = silentcipher16.read(_model(monkeypatch, [bias] * 3), np.ones(48000)) - assert not result.detected - assert result.phases_checked == 3 - assert result.symbol_consistency == 1 - - -@pytest.mark.parametrize(("errors", "detected"), [(8, True), (9, False)]) -def test_agreement_threshold_is_applied_to_valid_framing(monkeypatch, errors, detected): - labels = _raw(cycles=10).argmax(axis=0) - indexes = [*(np.arange(8) * 9), 8] - for index in indexes[:errors]: - labels[index] = (labels[index] + 1) % 4 - raw = np.eye(4, dtype=np.float32)[labels].T - result = silentcipher16.read(_model(monkeypatch, [raw], hop=10), np.ones(48000)) - assert result.detected is detected - assert result.symbol_consistency == pytest.approx(1 - errors / 80) - - -def test_numeric_failure_never_becomes_a_cpu_negative(monkeypatch): - def fail(*args): - raise silentcipher16.base.ModelCheckError("invalid numerics") - - monkeypatch.setattr(silentcipher16, "_read_native", fail) - monkeypatch.setattr(silentcipher16, "load_model", lambda *_: pytest.fail("Unexpected CPU fallback")) - with pytest.raises(RuntimeError, match="invalid numerics"): - silentcipher16.read(SimpleNamespace(device="mps"), np.ones(48000)) - - -def test_device_failure_retries_cpu_and_reports_actual_device(monkeypatch): - calls = [] - - def read(model, samples): - calls.append(model.device) - if model.device == "mps": - raise RuntimeError("unsupported device operation") - return silentcipher16.SilentCipher16Reading(None, 0.4, None, 103, "cpu") - - monkeypatch.setattr(silentcipher16, "_read_native", read) - monkeypatch.setattr(silentcipher16, "load_model", lambda device: SimpleNamespace(device=device)) - result = silentcipher16.read(SimpleNamespace(device="mps"), np.ones(48000)) - assert result.device == "cpu" - assert calls == ["mps", "cpu"] - - -def test_short_or_silent_input_is_not_absence(): - model = SimpleNamespace(device="cpu") - with pytest.raises(ValueError, match="three seconds"): - silentcipher16.read(model, np.ones(47999)) - with pytest.raises(RuntimeError, match="silent"): - silentcipher16.read(model, np.zeros(48000)) diff --git a/tests/test_video.py b/tests/test_video.py index 625f8a9..d3e9ae8 100644 --- a/tests/test_video.py +++ b/tests/test_video.py @@ -1561,14 +1561,15 @@ class TestVideoAllApi: from remove_ai_watermarks import video from remove_ai_watermarks.video import remove_video_all - source = _video_with_tc260_avi(tmp_path / "source.avi") + source = tmp_path / "source.wmv" + source.write_bytes(b"\x30\x26\xb2\x75\x8e\x66\xcf\x11") monkeypatch.setattr( video, "remove_video_visible", lambda *_args, **_kwargs: pytest.fail("visible scan must not start"), ) - with pytest.raises(ValueError, match="requires one of"): + with pytest.raises(ValueError, match="Unsupported video format"): remove_video_all(source, include_invisible=True) @@ -2002,12 +2003,13 @@ class TestVideoInvisibleApi: assert result.output == tmp_path / "source_clean.mp4" - def test_rejects_avi_regeneration(self, tmp_path: Path): + def test_rejects_unsupported_container_regeneration(self, tmp_path: Path): from remove_ai_watermarks.video import remove_video_invisible - source = _video_with_tc260_avi(tmp_path / "source.avi") + source = tmp_path / "source.wmv" + source.write_bytes(b"\x30\x26\xb2\x75\x8e\x66\xcf\x11") - with pytest.raises(ValueError, match="requires one of"): + with pytest.raises(ValueError, match="Unsupported video format"): remove_video_invisible(source) @@ -4291,10 +4293,10 @@ class TestVideoInvisibleStabilizeKeepFpsAndFourLayerAll: res_silent = remove_video_all(source, out_silent, include_audio_invisible=True) assert res_silent.audio == VideoAudioStatus(stream_action="absent", watermark_status="unverified") - # 2. Preflight must reject unsupported 5.1 layout or >30s BigVGAN BEFORE remove_video_visible runs + # 2. Preflight must reject unsupported 4-channel quad layout BEFORE remove_video_visible runs visible_calls.clear() monkeypatch.undo() - monkeypatch.setattr(audio.audio_vocoder, "is_available", lambda: True) + monkeypatch.setattr(audio.audio_dac, "is_available", lambda: True) monkeypatch.setattr( video, "remove_video_visible", @@ -4309,8 +4311,8 @@ class TestVideoInvisibleStabilizeKeepFpsAndFourLayerAll: "index": 1, "codec_type": "audio", "sample_rate": "48000", - "channels": 6, - "channel_layout": "5.1(side)", + "channels": 4, + "channel_layout": "quad", "duration": "5.0", }, ], @@ -4320,7 +4322,7 @@ class TestVideoInvisibleStabilizeKeepFpsAndFourLayerAll: source, tmp_path / "surround_fail.mp4", include_audio_invisible=True, - audio_method="bigvgan", + audio_method="dac", audio_force=True, ) assert visible_calls == [] diff --git a/tests/test_video_audio.py b/tests/test_video_audio.py index 2052996..f4306e0 100644 --- a/tests/test_video_audio.py +++ b/tests/test_video_audio.py @@ -99,29 +99,29 @@ def test_video_audio_verifies_actual_mux_and_keeps_other_tracks(tmp_path, monkey assert tracks[2]["disposition"]["default"] == tracks[2]["disposition"]["original"] == 1 -def test_bigvgan_selected_track_routes_device_and_checks_final_mux(tmp_path, monkeypatch): +def test_dac_selected_track_routes_device_and_checks_final_mux(tmp_path, monkeypatch): from remove_ai_watermarks import audio from remove_ai_watermarks.video_audio import remove_video_audio calls = [] - monkeypatch.setattr(audio.audio_vocoder, "is_available", lambda: True) + monkeypatch.setattr(audio.audio_dac, "is_available", lambda: True) - def process(samples, rate, *, device, local_files_only): + def process(samples, rate, *, device="cpu", local_files_only=False): calls.append((samples.shape, rate, device, local_files_only)) return samples * 0.5 - monkeypatch.setattr(audio.audio_vocoder, "resynthesize", process) + monkeypatch.setattr(audio.audio_dac, "resynthesize", process) result = remove_video_audio( _video(tmp_path), - tmp_path / "vocoder.mkv", + tmp_path / "dac.mkv", stream=1, - method="bigvgan", + method="dac", vocoder_device="mps", force=True, verify=False, ) assert calls == [((24031, 2), 16000, "mps", False)] - assert result.method == "bigvgan" + assert result.method == "dac" assert result.vocoder_device == "mps" assert result.verified_removed is None assert result.unchanged_streams == (0, 1) @@ -254,72 +254,13 @@ def test_corrupted_mux_is_rejected_atomically(tmp_path, monkeypatch, fault): assert output.read_bytes() == b"existing output" -def test_mimi_selected_track_routes_device_and_checks_final_mux(tmp_path, monkeypatch): - from remove_ai_watermarks import audio - from remove_ai_watermarks.video_audio import remove_video_audio - - calls = [] - monkeypatch.setattr(audio.audio_mimi, "is_available", lambda: True) - - def process(samples, rate, *, local_files_only): - calls.append((samples.shape, rate, "cpu", local_files_only)) - return samples * 0.5 - - monkeypatch.setattr(audio.audio_mimi, "resynthesize", process) - result = remove_video_audio( - _video(tmp_path), - tmp_path / "vocoder.mkv", - stream=1, - method="mimi", - vocoder_device="cpu", - force=True, - verify=False, - ) - assert calls == [((24031, 2), 16000, "cpu", False)] - assert result.method == "mimi" - assert result.vocoder_device == "cpu" - assert result.verified_removed is None - assert result.unchanged_streams == (0, 1) - assert result.fidelity.frames == 24031 - assert result.fidelity.snr_db == pytest.approx(6.0206, abs=0.001) - - -def test_focalcodec_selected_track_routes_device_and_checks_final_mux(tmp_path, monkeypatch): - from remove_ai_watermarks import audio - from remove_ai_watermarks.video_audio import remove_video_audio - - calls = [] - monkeypatch.setattr(audio.audio_focalcodec, "is_available", lambda: True) - - def process(samples, rate, *, local_files_only): - calls.append((samples.shape, rate, local_files_only)) - return samples * 0.5 - - monkeypatch.setattr(audio.audio_focalcodec, "resynthesize", process) - result = remove_video_audio( - _video(tmp_path), - tmp_path / "focal.mkv", - stream=1, - method="focalcodec", - vocoder_device="cpu", - force=True, - verify=False, - ) - assert calls == [((24031, 2), 16000, False)] - assert result.method == "focalcodec" - assert result.vocoder_device == "cpu" - assert result.verified_removed is None - assert result.unchanged_streams == (0, 1) - assert result.fidelity.frames == 24031 - - -def test_mimi_final_mux_positive_rejected_after_negative_intermediate(tmp_path, monkeypatch): +def test_dac_final_mux_positive_rejected_after_negative_intermediate(tmp_path, monkeypatch): from remove_ai_watermarks import audio from remove_ai_watermarks.video_audio import remove_video_audio _spectral_detector(monkeypatch) - monkeypatch.setattr(audio.audio_mimi, "is_available", lambda: True) - monkeypatch.setattr(audio.audio_mimi, "resynthesize", lambda x, *a, **k: x * 0.01) + monkeypatch.setattr(audio.audio_dac, "is_available", lambda: True) + monkeypatch.setattr(audio.audio_dac, "resynthesize", lambda x, *a, **k: x * 0.01) real = audio.identify_audio checked = [] @@ -334,7 +275,7 @@ def test_mimi_final_mux_positive_rejected_after_negative_intermediate(tmp_path, output = tmp_path / "processed.mkv" output.write_bytes(b"existing output") with pytest.raises(audio.AudioVerificationIncomplete): - remove_video_audio(_video(tmp_path), output, method="mimi", stream=1) + remove_video_audio(_video(tmp_path), output, method="dac", stream=1) assert checked == ["not_detected"] assert output.read_bytes() == b"existing output" @@ -343,8 +284,8 @@ def test_mp4_aac_preserves_odd_sample_count_and_other_tracks(tmp_path, monkeypat from remove_ai_watermarks import audio, video_audio _spectral_detector(monkeypatch) - monkeypatch.setattr(audio.audio_mimi, "is_available", lambda: True) - monkeypatch.setattr(audio.audio_mimi, "resynthesize", lambda x, *a, **k: x * 0.01) + monkeypatch.setattr(audio.audio_dac, "is_available", lambda: True) + monkeypatch.setattr(audio.audio_dac, "resynthesize", lambda x, *a, **k: x * 0.01) source = _video( tmp_path, audio_codec="aac", @@ -364,7 +305,7 @@ def test_mp4_aac_preserves_odd_sample_count_and_other_tracks(tmp_path, monkeypat monkeypatch.setattr(video_audio.subprocess, "Popen", capture) output = tmp_path / "processed.mp4" - result = video_audio.remove_video_audio(source, output, stream=1, method="mimi") + result = video_audio.remove_video_audio(source, output, stream=1, method="dac") assert result.verified_removed is True assert result.frames_processed == result.fidelity.frames == 24031 assert result.source_audio_start == result.output_audio_start @@ -540,16 +481,16 @@ def test_video_audio_quality_gate_rejects_silent_erasure_unless_forced(tmp_path, from remove_ai_watermarks import audio, video_audio _spectral_detector(monkeypatch) - monkeypatch.setattr(audio.audio_mimi, "is_available", lambda: True) - monkeypatch.setattr(audio.audio_mimi, "resynthesize", lambda samples, *a, **k: np.zeros_like(samples)) + monkeypatch.setattr(audio.audio_dac, "is_available", lambda: True) + monkeypatch.setattr(audio.audio_dac, "resynthesize", lambda samples, *a, **k: np.zeros_like(samples)) source = _video(tmp_path) output = tmp_path / "processed.mkv" output.write_bytes(b"existing output") with pytest.raises(audio.AudioVerificationIncomplete, match="quality gate"): - video_audio.remove_video_audio(source, output, stream=1, method="mimi") + video_audio.remove_video_audio(source, output, stream=1, method="dac") assert output.read_bytes() == b"existing output" - forced = video_audio.remove_video_audio(source, output, stream=1, method="mimi", force=True) + forced = video_audio.remove_video_audio(source, output, stream=1, method="dac", force=True) assert forced.verified_removed is True assert forced.quality_passed is False @@ -561,7 +502,7 @@ def test_remove_video_audio_all_streams_cleans_multiple_tracks_and_cli_all_strea from remove_ai_watermarks.cli import main _spectral_detector(monkeypatch) - for backend in (audio.wavmark, audio.perth, audio.silentcipher, audio.silentcipher16): + for backend in (audio.wavmark, audio.perth, audio.silentcipher): monkeypatch.setattr(backend, "is_available", lambda: False) source = _video(tmp_path, first_offset=0, selected_offset=0) @@ -605,7 +546,7 @@ def test_remove_video_audio_all_streams_preserves_existing_destination_on_late_f from remove_ai_watermarks import audio, video_audio _spectral_detector(monkeypatch) - for backend in (audio.wavmark, audio.perth, audio.silentcipher, audio.silentcipher16): + for backend in (audio.wavmark, audio.perth, audio.silentcipher): monkeypatch.setattr(backend, "is_available", lambda: False) source = _video(tmp_path, first_offset=0, selected_offset=0) @@ -672,7 +613,7 @@ def test_remove_video_audio_all_streams_unverified_unprocessed_track_blocks_aggr from remove_ai_watermarks import audio, video_audio _spectral_detector(monkeypatch) - for backend in (audio.wavmark, audio.perth, audio.silentcipher, audio.silentcipher16): + for backend in (audio.wavmark, audio.perth, audio.silentcipher): monkeypatch.setattr(backend, "is_available", lambda: False) source = _video(tmp_path, first_offset=0, selected_offset=0) @@ -709,7 +650,7 @@ def test_preflight_untagged_stereo_post_fidelity_hash_and_selected_stream_ordina from remove_ai_watermarks import audio, video_audio _spectral_detector(monkeypatch) - for backend in (audio.wavmark, audio.perth, audio.silentcipher, audio.silentcipher16): + for backend in (audio.wavmark, audio.perth, audio.silentcipher): monkeypatch.setattr(backend, "is_available", lambda: False) # 1. Forced preflight accepts untagged 2-channel PCM stereo in MKV (where raw channel_layout is omitted) diff --git a/tests/test_video_seedance.py b/tests/test_video_seedance.py index 441da8f..7cb275d 100644 --- a/tests/test_video_seedance.py +++ b/tests/test_video_seedance.py @@ -85,9 +85,9 @@ def test_rejects_in_place_processing_and_other_containers(tmp_path): with pytest.raises(ValueError, match="distinct output"): raiw.remove_video_seedance_experimental(source, source) assert source.read_bytes() == payload - other = tmp_path / "owned.mov" - other.write_bytes(payload) - with pytest.raises(ValueError, match="MP4 input"): + other = tmp_path / "owned.wmv" + other.write_bytes(b"\x30\x26\xb2\x75\x8e\x66\xcf\x11") + with pytest.raises(ValueError, match="Unsupported video format"): raiw.remove_video_seedance_experimental(other) @@ -343,13 +343,13 @@ def test_invalid_pipeline_profile_options_fail_before_visible_stage(tmp_path, mo assert output.read_bytes() == b"previous output" -def test_seedance_batch_reuses_runtime_and_rejects_other_containers(tmp_path, monkeypatch): +def test_seedance_batch_reuses_runtime_across_supported_containers(tmp_path, monkeypatch): from remove_ai_watermarks import video, video_invisible directory = tmp_path / "videos" directory.mkdir() payload = b"\x00\x00\x00\x18ftypmp42\x00\x00\x00\x00mp42isom" - for name in ("one.mp4", "two.mp4", "unsupported.mov"): + for name in ("one.mp4", "two.mp4", "three.mov"): (directory / name).write_bytes(payload) runtime = SimpleNamespace(model="stabilityai/sd-vae-ft-mse", requested_device="cpu") loaded, used = [], [] @@ -375,12 +375,11 @@ def test_seedance_batch_reuses_runtime_and_rejects_other_containers(tmp_path, mo invisible_profile="seedance-experimental", device="cpu", ) - assert result.processed == 2 - assert result.failed == 1 + assert result.processed == 3 + assert result.failed == 0 assert loaded == [{"model": "stabilityai/sd-vae-ft-mse", "device": "cpu"}] - assert used == [{"device": "cpu", "quality": "delivery", "runtime": runtime}] * 2 - assert "MP4 input" in result.items[-1].error - assert not (result.output_directory / "unsupported.mov").exists() + assert used == [{"device": "cpu", "quality": "delivery", "runtime": runtime}] * 3 + assert (result.output_directory / "three.mov").exists() @pytest.mark.parametrize("command", ["invisible", "all", "batch"]) diff --git a/tests/test_video_wan.py b/tests/test_video_wan.py index 8228e0d..07d412d 100644 --- a/tests/test_video_wan.py +++ b/tests/test_video_wan.py @@ -168,9 +168,9 @@ def test_validation_rejects_hdr_odd_dims_wrong_runtime_and_2d_vae_flags(tmp_path invisible_profile="wan21-synthid-experimental", long_side=768, ) - other = tmp_path / "owned.webm" - other.write_bytes(b"\x1a\x45\xdf\xa3\x87\x42\x82\x84webm") - with pytest.raises(ValueError, match=r"requires one of: \.m4v, \.mov, \.mp4"): + other = tmp_path / "owned.wmv" + other.write_bytes(b"\x30\x26\xb2\x75\x8e\x66\xcf\x11") + with pytest.raises(ValueError, match=r"Unsupported video format"): raiw.remove_video_wan_experimental(other) bad_runtime = wan.VideoWanRuntime( @@ -240,7 +240,7 @@ def test_cli_routes_wan21_profiles_and_prints_experimental_label(tmp_path, monke assert "calibrated SynthID" not in res.output -def test_wan_batch_reuses_wan_runtime_across_isobmff_items(tmp_path, monkeypatch): +def test_wan_batch_reuses_wan_runtime_across_supported_containers(tmp_path, monkeypatch): directory = tmp_path / "clips" directory.mkdir() payload = b"\x00\x00\x00\x18ftypmp42\x00\x00\x00\x00mp42isom" @@ -277,8 +277,8 @@ def test_wan_batch_reuses_wan_runtime_across_isobmff_items(tmp_path, monkeypatch seed=5, device="cuda", ) - assert batch_res.processed == 3 - assert batch_res.failed == 1 + assert batch_res.processed == 4 + assert batch_res.failed == 0 assert loaded == [{"device": "cuda"}] assert ( used @@ -293,9 +293,8 @@ def test_wan_batch_reuses_wan_runtime_across_isobmff_items(tmp_path, monkeypatch "runtime": runtime, } ] - * 3 + * 4 ) - assert "requires one of: .m4v, .mov, .mp4" in (batch_res.items[-1].error or "") def test_pad_and_run_wan_sliding_windows_crossfade_long_clips_smoothly(): @@ -438,20 +437,15 @@ def test_wan_preflight_budget_bf16_guard_and_strength_field(tmp_path, monkeypatc wan.resolve_wan_device("auto") monkeypatch.setattr(torch.version, "hip", None, raising=False) - # 2. Frame-pixel / host-RAM budget & VRAM floor & 4K cap (>4K rejected) - frames_decoded = [] - monkeypatch.setattr(wan, "_frames", lambda p: (frames_decoded.append(p), iter(()))[1]) + # 2. High-res (8K) and 1080p clips are accepted (1080p-guided restoration removes artificial >4K/duration caps) monkeypatch.setattr( wan, "validate_experimental_mp4_source", - lambda *_a, **_k: (7680, 4320, 24.0, tuple(range(10))), + lambda *_a, **_k: (7680, 4320, 24.0, tuple(range(10000))), ) - with pytest.raises(ValueError, match="frame area"): - wan.regenerate_wan_experimental(source, output) - assert frames_decoded == [] - assert wan.can_run_wan_on_source(source, device="auto") is False + assert wan.can_run_wan_on_source(source, device="auto", for_auto=True) is True + assert wan.can_run_wan_on_source(source, device="auto", for_auto=False) is True - # 1080p and 4K UHD are accepted for both auto and explicit wan21-* within total budget, while >4K is rejected monkeypatch.setattr( wan, "validate_experimental_mp4_source", diff --git a/uv.lock b/uv.lock index 248e42a..40962f9 100644 --- a/uv.lock +++ b/uv.lock @@ -3890,7 +3890,7 @@ wheels = [ [[package]] name = "remove-ai-watermarks" -version = "0.72.0" +version = "0.73.0" source = { editable = "." } dependencies = [ { name = "c2pa-python" }, @@ -3979,15 +3979,6 @@ audio-silentcipher = [ { name = "scipy", version = "1.18.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, { name = "torch" }, ] -audio-vocoder = [ - { name = "huggingface-hub" }, - { name = "librosa", version = "0.11.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, - { name = "librosa", version = "1.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, - { name = "numpy" }, - { name = "scipy", version = "1.17.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, - { name = "scipy", version = "1.18.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, - { name = "torch" }, -] audio-wavmark = [ { name = "huggingface-hub" }, { name = "numpy" }, @@ -4155,7 +4146,6 @@ requires-dist = [ { name = "huggingface-hub", marker = "extra == 'audio-codec'", specifier = ">=0.20.0,<2" }, { name = "huggingface-hub", marker = "extra == 'audio-detect'", specifier = ">=0.20.0,<2" }, { name = "huggingface-hub", marker = "extra == 'audio-silentcipher'", specifier = ">=0.20.0,<2" }, - { name = "huggingface-hub", marker = "extra == 'audio-vocoder'", specifier = ">=0.20.0,<2" }, { name = "huggingface-hub", marker = "extra == 'audio-wavmark'", specifier = ">=0.20.0,<2" }, { name = "huggingface-hub", marker = "extra == 'dev'", specifier = ">=0.20.0,<2" }, { name = "huggingface-hub", marker = "extra == 'lama'", specifier = ">=0.20.0,<2" }, @@ -4165,7 +4155,6 @@ requires-dist = [ { name = "invisible-watermark", marker = "extra == 'dev'", specifier = ">=0.2.0" }, { name = "librosa", marker = "extra == 'audio-perth'", specifier = ">=0.10" }, { name = "librosa", marker = "extra == 'audio-silentcipher'", specifier = ">=0.10" }, - { name = "librosa", marker = "extra == 'audio-vocoder'", specifier = ">=0.10" }, { name = "lpips", marker = "extra == 'qwen-zimage'", specifier = "==0.1.4" }, { name = "mcp", marker = "extra == 'dev'", specifier = ">=2.3,<3" }, { name = "mlx-lm", marker = "platform_machine == 'arm64' and sys_platform == 'darwin' and extra == 'text-mlx'", specifier = ">=0.32.2" }, @@ -4202,7 +4191,6 @@ requires-dist = [ { name = "remove-ai-watermarks", extras = ["audio"], marker = "extra == 'audio-detect'" }, { name = "remove-ai-watermarks", extras = ["audio"], marker = "extra == 'audio-perth'" }, { name = "remove-ai-watermarks", extras = ["audio"], marker = "extra == 'audio-silentcipher'" }, - { name = "remove-ai-watermarks", extras = ["audio"], marker = "extra == 'audio-vocoder'" }, { name = "remove-ai-watermarks", extras = ["audio"], marker = "extra == 'audio-wavmark'" }, { name = "remove-ai-watermarks", extras = ["audio-detect"], marker = "extra == 'dev'" }, { name = "remove-ai-watermarks", extras = ["detect"], marker = "extra == 'dev'" }, @@ -4215,7 +4203,7 @@ requires-dist = [ { name = "remove-ai-watermarks", extras = ["text-api"], marker = "extra == 'dev'" }, { name = "remove-ai-watermarks", extras = ["video"], marker = "extra == 'dev'" }, { name = "remove-ai-watermarks", extras = ["video"], marker = "extra == 'video-detect'" }, - { name = "remove-ai-watermarks", extras = ["video", "video-detect", "heif", "detect", "trustmark", "text-restoration", "migan", "source-classify", "audio-detect", "audio-codec", "audio-vocoder", "audio-wavmark", "audio-perth", "audio-silentcipher", "text", "text-mlx"], marker = "extra == 'all'" }, + { name = "remove-ai-watermarks", extras = ["video", "video-detect", "heif", "detect", "trustmark", "text-restoration", "migan", "source-classify", "audio-detect", "audio-codec", "audio-wavmark", "audio-perth", "audio-silentcipher", "text", "text-mlx"], marker = "extra == 'all'" }, { name = "remove-ai-watermarks", extras = ["visible"], marker = "extra == 'lama'" }, { name = "remove-ai-watermarks", extras = ["visible"], marker = "extra == 'migan'" }, { name = "remove-ai-watermarks", extras = ["visible"], marker = "extra == 'video'" }, @@ -4232,7 +4220,6 @@ requires-dist = [ { name = "torch", marker = "extra == 'audio-codec'", specifier = ">=2.0.0" }, { name = "torch", marker = "extra == 'audio-perth'", specifier = ">=2.0.0" }, { name = "torch", marker = "extra == 'audio-silentcipher'", specifier = ">=2.6" }, - { name = "torch", marker = "extra == 'audio-vocoder'", specifier = ">=2.6" }, { name = "torch", marker = "extra == 'diffusion'", specifier = ">=2.0.0" }, { name = "torch", marker = "extra == 'text'", specifier = ">=2.0.0" }, { name = "torch", marker = "extra == 'video-detect'", specifier = ">=2.6" }, @@ -4244,7 +4231,7 @@ requires-dist = [ { name = "trustmark", marker = "extra == 'trustmark'", specifier = ">=0.9.2" }, { name = "wavmark", marker = "extra == 'audio-wavmark'", specifier = "==0.0.3" }, ] -provides-extras = ["text", "text-api", "text-mlx", "pixels", "heif", "visible", "video", "video-detect", "audio", "audio-detect", "audio-wavmark", "audio-perth", "audio-silentcipher", "audio-codec", "audio-vocoder", "detect", "diffusion", "qwen-zimage", "text-restoration", "text-draft", "trustmark", "source-classify", "lama", "migan", "dev", "all"] +provides-extras = ["text", "text-api", "text-mlx", "pixels", "heif", "visible", "video", "video-detect", "audio", "audio-detect", "audio-wavmark", "audio-perth", "audio-silentcipher", "audio-codec", "detect", "diffusion", "qwen-zimage", "text-restoration", "text-draft", "trustmark", "source-classify", "lama", "migan", "dev", "all"] [[package]] name = "requests"