### Install Project Dependencies Source: https://github.com/aloshdenny/reverse-synthid/blob/main/README.md Clone the repository, set up a virtual environment, and install required Python packages. Ensure you install PyTorch and related libraries for the VAE stage. ```bash git clone https://github.com/aloshdenny/reverse-SynthID.git cd reverse-SynthID python -m venv venv source venv/bin/activate # Windows: venv\Scripts\activate pip install -r requirements.txt # For Round-06 VAE stage: pip install torch diffusers safetensors accelerate ``` -------------------------------- ### Install Dependencies Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/api-reference-vae-regen.md Installs the necessary Python packages for the VAE module. This command should be run in your environment. ```bash pip install torch diffusers safetensors accelerate ``` -------------------------------- ### Download Reference Images with Hugging Face Hub Source: https://github.com/aloshdenny/reverse-synthid/blob/main/README.md Use these commands to download all or specific folders of reference images from the Hugging Face dataset. Ensure you have the huggingface_hub library installed. ```bash pip install huggingface_hub ``` ```python python scripts/download_images.py # download all ``` ```python python scripts/download_images.py gemini_black # download specific folder ``` -------------------------------- ### Example: Iterating Through Applied Stages Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/types.md Shows how to iterate through the 'stages_applied' attribute of a result object and print each stage description. ```python for stage in result.stages_applied: print(f" + {stage}") ``` -------------------------------- ### Example: Extracting Noise with RobustSynthIDExtractor Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/types.md Demonstrates how to use the RobustSynthIDExtractor to extract noise from an RGB image. The extracted noise contains the watermark signal and can be analyzed for its statistical properties. ```python from src.extraction.robust_extractor import RobustSynthIDExtractor extractor = RobustSynthIDExtractor() noise = extractor.extract_noise_fused(image_rgb) # Watermark signal is embedded in this noise print(f"Noise stats: mean={noise.mean():.4f}, std={noise.std():.4f}") ``` -------------------------------- ### Robust Extractor CLI Detection Example Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/api-reference-robust-extractor.md An example of how to use the robust extractor CLI to detect an image, including specifying a codebook path. ```bash python src/extraction/robust_extractor.py detect image.png \ --codebook artifacts/codebook/robust_codebook.pkl ``` -------------------------------- ### Bypass V4 File Method Example Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/api-reference-synthid-bypass-v4.md Reads an image from a file, dissolves the SynthID watermark, and writes the result to an output file. Supports different strength presets and model hints. ```python result = b.bypass_v4_file( 'input.png', 'output.png', cb, strength='final', model='nano-banana-pro-preview' ) ``` -------------------------------- ### Bypass V4 Method Example Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/api-reference-synthid-bypass-v4.md Dissolves a SynthID watermark from an image using cross-color consensus FFT subtraction. Requires a loaded SpectralCodebookV4 and specifies bypass strength and model. ```python from synthid_bypass_v4 import SynthIDBypassV4, SpectralCodebookV4 cb = SpectralCodebookV4() cb.load('artifacts/spectral_codebook_v4.npz') b = SynthIDBypassV4() result = b.bypass_v4( image_rgb, cb, strength='moderate', model='gemini-3.1-flash-image-preview' ) print(f"PSNR: {result.psnr:.1f} dB, SSIM: {result.ssim:.3f}") print(f"Stages: {result.stages_applied}") ``` -------------------------------- ### BypassResult Usage Example Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/types.md Demonstrates how to use the `BypassResult` object after a bypass operation. Checks for success, saves the cleaned image, and prints quality metrics and applied stages. ```python result: BypassResult = bypass.bypass_v4(image, codebook, strength='moderate') if result.success: cv2.imwrite('output.png', cv2.cvtColor(result.cleaned_image, cv2.COLOR_RGB2BGR)) print(f"PSNR: {result.psnr:.1f} dB, SSIM: {result.ssim:.3f}") print(f"Stages: {', '.join(result.stages_applied)}") ``` -------------------------------- ### DetectionResult Usage Example Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/types.md Shows how to interpret the `DetectionResult` from a watermark detection function. It checks the `is_watermarked` flag and prints confidence and phase match details if a watermark is detected. ```python result: DetectionResult = extractor.detect_array(image_rgb) if result.is_watermarked: print(f"Watermarked with {result.confidence:.1%} confidence") print(f"Phase match: {result.phase_match:.3f}") else: print("No watermark detected") ``` -------------------------------- ### VAE Roundtrip Error Handling Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/api-reference-vae-regen.md Provides an example of how to handle potential `RuntimeError` exceptions during VAE operations. This includes missing dependencies and CUDA Out Of Memory (OOM) errors. ```python try: result = vae_roundtrip(image) except RuntimeError as e: # Missing torch/diffusers print("Install via: pip install torch diffusers safetensors accelerate") except RuntimeError as e: # CUDA OOM — will auto-fallback to tiled encode if available pass ``` -------------------------------- ### Get Best Matching Profile (Python) Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/api-reference-synthid-bypass-v4.md Retrieves the best matching profile for a given image height and width, with an optional model hint. It prioritizes exact matches and falls back to the closest available profile. ```python cb = SpectralCodebookV4() cb.load('artifacts/spectral_codebook_v4.npz') profile, key, exact = cb.get_profile(1024, 1024, model='gemini-3.1-flash-image-preview') print(f"Using profile: {key[0]}/{key[1]}x{key[2]}, exact match: {exact}") ``` -------------------------------- ### Bypass Result Analysis Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/types.md Example of how to analyze the detection results before and after a bypass operation to measure watermark reduction. Requires a BypassResult object. ```python result: BypassResult = bypass.bypass_v4_final(image, codebook) if result.detection_before and result.detection_after: before_conf = result.detection_before['confidence'] after_conf = result.detection_after['confidence'] reduction = before_conf - after_conf print(f"Confidence drop: {reduction:.3f} ({reduction/before_conf:.1%})") ``` -------------------------------- ### Load Stable Diffusion VAE Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/api-reference-vae-regen.md Lazily loads and caches the Stable Diffusion VAE model. Specify the model ID, device, and data type. Returns the VAE module and the selected device string. Requires PyTorch and Diffusers to be installed. ```python from src.extraction.vae_regen import load_vae vae, device = load_vae(device='cuda', dtype='float16') print(f"VAE loaded on {device}") ``` -------------------------------- ### Initialize SpectralCodebookV4 Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/api-reference-synthid-bypass-v4.md Creates an empty SpectralCodebookV4 instance. Profiles are added later using build_from_hierarchical_dataset() or load(). ```python SpectralCodebookV4() ``` -------------------------------- ### Verify Dataset Structure for Codebook Building Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/errors.md Illustrates the expected directory structure for building a codebook using `build_from_hierarchical_dataset`. Ensure your dataset follows the pattern of {model}/{color}/{HxW}/*.png to avoid 'No usable buckets' errors. ```text reverse-synthid-dataset/ ├── gemini-3.1-flash-image-preview/ │ ├── black/ │ │ ├── 1024x1024/ │ │ │ ├── img_001.png │ │ │ └── ... │ │ └── 512x512/ │ └── white/ │ ├── 1024x1024/ │ └── ... └── nano-banana-pro-preview/ └── ... ``` -------------------------------- ### Loading and Using SpectralCodebookV4 Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/types.md Demonstrates how to load a SpectralCodebookV4 from a file and retrieve a spectral profile for a given resolution and model. It then prints the key, color names, and shape of the consensus coherence. ```python cb = SpectralCodebookV4() cb.load('artifacts/spectral_codebook_v4.npz') profile, key, exact = cb.get_profile(1024, 1024, model='gemini-3.1-flash-image-preview') print(f"Profile: {key[0]}/{key[1]}x{key[2]}") print(f"Colors: {profile.color_names}") print(f"Consensus coherence shape: {profile.consensus_coherence.shape}") ``` -------------------------------- ### Create SpectralCodebook Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/api-reference-synthid-bypass-v3.md Instantiates an empty `SpectralCodebook`. Profiles can be loaded later using the `load()` method or built through analysis. ```python SpectralCodebook() ``` -------------------------------- ### SpectralCodebook Constructor Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/api-reference-synthid-bypass-v3.md Initializes an empty SpectralCodebook. Profiles can be loaded later or built through analysis. ```APIDOC ## SpectralCodebook() ### Description Creates an empty codebook. Profiles loaded via `load()` or built via analysis. ### Constructor ```python SpectralCodebook() ``` ``` -------------------------------- ### SpectralCodebookV4 Constructor Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/api-reference-synthid-bypass-v4.md Initializes an empty SpectralCodebookV4 object. Profiles can be added later using build_from_hierarchical_dataset() or load(). ```APIDOC ## SpectralCodebookV4() ### Description Creates an empty codebook. Profiles are added via `build_from_hierarchical_dataset()` or `load()`. ### Method ```python SpectralCodebookV4() ``` ``` -------------------------------- ### Instantiate RobustSynthIDExtractor Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/api-reference-robust-extractor.md Initialize the RobustSynthIDExtractor with custom scales and a codebook path. Ensure the codebook path points to a valid .pkl file. ```python from src.extraction.robust_extractor import RobustSynthIDExtractor extractor = RobustSynthIDExtractor( scales=[512, 1024], codebook_path='artifacts/codebook/robust_codebook.pkl' ) ``` -------------------------------- ### Initialize RobustSynthIDExtractor Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/configuration.md Configure the RobustSynthIDExtractor with parameters for multi-scale analysis, wavelet families, number of carriers to track, and the path to the codebook. ```python extractor = RobustSynthIDExtractor( scales=[256, 512, 1024], # Multi-scale analysis at these sizes wavelets=['db4', 'sym8', 'coif3'], # Wavelet families for denoising n_carriers=100, # Top carriers to track codebook_path='artifacts/codebook/robust_codebook.pkl' # Optional codebook ) ``` -------------------------------- ### SynthID Blog Pure Preset Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/configuration.md Pure blog-universal carriers configuration. Sets magnitude cap, removal, passes, harvest K, consensus floor, PSNR floor, and phase source. ```json { "mag_cap": 0.30, "removal": 0.95, "passes": 1, "harvest_k": 64, "consensus_floor": 0.55, "psnr_floor": 40.0, "phase_source": "codebook" } ``` -------------------------------- ### Correct ValueError: Image Shape Incorrect Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/errors.md Ensure input images are in HxWx3 RGB uint8 format before passing them to VAE or bypass functions. This example shows conversions from grayscale, RGBA, and BGR formats. ```python vae_roundtrip(image_2d) # ValueError: Expected HxWx3 RGB uint8 vae_roundtrip(image_rgba) # ValueError: Expected HxWx3, got HxWx4 ``` ```python import cv2 # From grayscale gray = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY) rgb = cv2.cvtColor(gray, cv2.COLOR_GRAY2RGB) # From RGBA rgba = cv2.imread('img.png', cv2.IMREAD_UNCHANGED) rgb = cv2.cvtColor(rgba, cv2.COLOR_RGBA2RGB) # From BGR (OpenCV default) rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB) # Ensure uint8 rgb = rgb.astype(np.uint8) # Now use result = vae_roundtrip(rgb) ``` -------------------------------- ### Fix RuntimeError: Missing Dependencies Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/errors.md Install required Python packages like torch and diffusers to resolve missing dependency errors when using VAE functions. Alternatively, use pipelines that can bypass the VAE stage if dependencies are not met. ```python from src.extraction.vae_regen import vae_roundtrip result = vae_roundtrip(image) # RuntimeError ``` ```bash pip install torch diffusers safetensors accelerate ``` ```python result = b.bypass_v4_final(image, codebook) # Skips VAE stage if not installed ``` -------------------------------- ### V3 Pipeline Stages Source: https://github.com/aloshdenny/reverse-synthid/blob/main/README.md Illustrates the V3 pipeline for watermark bypass, including FFT-domain and spatial-domain subtraction paths. ```text Input Image (any resolution) │ ▼ codebook.get_profile(H, W) ──► exact match? ──► FFT-domain subtraction │ (fast path) └─ no exact match ──────► spatial-domain resize + subtraction (fallback path) │ ▼ Multi-pass iterative subtraction (aggressive → moderate → gentle) │ ▼ Anti-alias → Output ``` -------------------------------- ### VAE Integration in bypass_v4_final() Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/api-reference-vae-regen.md Demonstrates how to use the VAE stage within the `bypass_v4_final` pipeline. Ensure `SynthIDBypassV4` is imported. ```python from src.extraction.synthid_bypass_v4 import SynthIDBypassV4 b = SynthIDBypassV4() result = b.bypass_v4_final( image_rgb, codebook, strength='final' # Includes VAE as stage 1 ) ``` -------------------------------- ### Load Codebook and Custom Configuration Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/configuration.md Demonstrates loading a spectral codebook and defining a custom configuration dictionary for aggressive watermarking removal with tight PSNR control. This is for lower-level API usage. ```python from src.extraction.synthid_bypass_v4 import SynthIDBypassV4, SpectralCodebookV4 # Load codebook cb = SpectralCodebookV4() cb.load('artifacts/spectral_codebook_v4.npz') # Create custom configuration for aggressive removal with tight PSNR control custom_config = { "removal": 0.98, "tau": 0.45, "mag_cap": 0.90, "dc_radius": 20, "psnr_floor": 35.0, "passes": 3 } # Manually apply using lower-level API bypass = SynthIDBypassV4() # For preset-based use, substitute in the class dict # (higher-level entry point uses SynthIDBypassV4.STRENGTH_PRESETS) ``` -------------------------------- ### Build Codebook from Hierarchical Dataset (Python) Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/api-reference-synthid-bypass-v4.md Constructs SynthID profiles by scanning a hierarchical dataset. Specify models and colors to include, and set minimum reference counts per color and consensus colors for profile creation. An optional cap can be set per bucket. ```python cb = SpectralCodebookV4() cb.build_from_hierarchical_dataset( root='/path/to/reverse-synthid-dataset', models=['gemini-3.1-flash-image-preview', 'nano-banana-pro-preview'], min_refs_per_color=5, min_consensus_colors=4 ) ``` -------------------------------- ### Build Codebook from Dataset Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/README.md Builds a SpectralCodebookV4 from a dataset. Configure with dataset root, minimum references per color, and minimum consensus colors. Union profiles are added before saving. ```python cb = SpectralCodebookV4() cb.build_from_hierarchical_dataset( root='/path/to/reverse-synthid-dataset', min_refs_per_color=5, min_consensus_colors=4 ) cb.add_union_profiles() cb.save('artifacts/spectral_codebook_v4.npz') ``` -------------------------------- ### Run V3 Bypass (CLI) Source: https://github.com/aloshdenny/reverse-synthid/blob/main/README.md Execute the V3 bypass from the command line interface. Specify input and output files, the codebook path, and the desired strength. ```bash python src/extraction/synthid_bypass.py bypass input.png output.png \ --codebook artifacts/spectral_codebook_v3.npz \ --strength aggressive ``` -------------------------------- ### Load SpectralCodebook Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/api-reference-synthid-bypass-v3.md Loads a pre-built spectral codebook from a file. Supported formats include `.npz` and `.pkl`. Ensure the path points to a valid codebook file. ```python from src.extraction.synthid_bypass import SpectralCodebook codebook = SpectralCodebook() codebook.load('artifacts/spectral_codebook_v3.npz') ``` -------------------------------- ### Build Spectral Codebook Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/README.md This script builds a spectral codebook from a dataset. Ensure the root path points to your dataset and specify the output artifact path. ```bash python scripts/build_codebook_v4.py \ --root /path/to/reverse-synthid-dataset \ --output artifacts/spectral_codebook_v4.npz ``` -------------------------------- ### SynthID Blog Plus Preset Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/configuration.md Blog-universal carriers with harvested and JPEG processing. Includes post-JPEG quality and noise sigma. ```json { "mag_cap": 0.33, "removal": 1.00, "passes": 1, "harvest_k": 96, "consensus_floor": 0.50, "psnr_floor": 38.0, "phase_source": "codebook", "post_jpeg_q": 92, "post_noise_sigma": 0.3 } ``` -------------------------------- ### Initialize SynthIDBypass Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/api-reference-synthid-bypass-v3.md Initializes the `SynthIDBypass` pipeline. You can specify the number of bypass iterations and an optional extractor for verification. ```python SynthIDBypass(iterations: int = 3, extractor=None) ``` -------------------------------- ### SynthID Blog Combo Preset Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/configuration.md Full stack blog configuration including harvested, FFT, JPEG, and bilateral filtering. Adjusts multiple parameters for advanced processing. ```json { "mag_cap": 0.35, "removal": 1.00, "passes": 2, "harvest_k": 128, "consensus_floor": 0.45, "psnr_floor": 36.0, "phase_source": "codebook", "post_jpeg_q": 90, "post_noise_sigma": 0.5, "post_bilateral_d": 3, "post_bilateral_sigma": 8.0 } ``` -------------------------------- ### build_from_hierarchical_dataset Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/api-reference-synthid-bypass-v4.md Builds profiles by walking a dataset directory structured as `root/{model}/{color}/{HxW}/*.png`. Allows filtering by models and colors, and setting minimum reference counts and consensus colors. ```APIDOC ## build_from_hierarchical_dataset(root: str, models: Optional[List[str]] = None, colors: Optional[List[str]] = None, min_refs_per_color: int = 3, min_consensus_colors: int = 3, max_per_bucket: Optional[int] = None, verbose: bool = True) ### Description Walk `root/{model}/{color}/{HxW}/*.png` and build profiles. ### Parameters #### Path Parameters - **root** (str) - Required - Dataset root directory - **models** (List[str]) - Optional - Model subdirs to include. Auto-detected if None - **colors** (List[str]) - Optional - Colors to consider. Defaults to `ALL_COLORS` (black, white, blue, green, red, gray, diverse, gradient) - **min_refs_per_color** (int) - Optional - Default: 3 - Skip buckets with fewer images than this - **min_consensus_colors** (int) - Optional - Default: 3 - Minimum colors needed to create a profile at each resolution - **max_per_bucket** (int) - Optional - Optional cap per `(color, resolution)` bucket - **verbose** (bool) - Optional - Default: True - Print progress ### Example ```python cb = SpectralCodebookV4() cb.build_from_hierarchical_dataset( root='/path/to/reverse-synthid-dataset', models=['gemini-3.1-flash-image-preview', 'nano-banana-pro-preview'], min_refs_per_color=5, min_consensus_colors=4 ) ``` ``` -------------------------------- ### Build Spectral Codebook Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/configuration.md Build a spectral codebook from a hierarchical dataset. Configure parameters such as the root directory, color settings, minimum references per color, minimum consensus colors, and image capping per bucket. ```python cb.build_from_hierarchical_dataset( root='/path/to/dataset', # Root directory models=None, # Auto-detect or specify colors=None, # Defaults to ALL_COLORS min_refs_per_color=3, # Minimum images per (color, res) min_consensus_colors=3, # Minimum colors for profile creation max_per_bucket=None, # Cap images per bucket verbose=True ) ``` -------------------------------- ### Initialize SynthIDBypassV4 Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/api-reference-synthid-bypass-v4.md Constructs a SynthIDBypassV4 object. An optional extractor can be provided for before/after verification. ```python from synthid_bypass_v4 import SynthIDBypassV4 b = SynthIDBypassV4(extractor=None) ``` -------------------------------- ### Initialize RobustSynthIDExtractor with Valid Codebook Path Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/errors.md Prevent FileNotFoundError during RobustSynthIDExtractor initialization by providing a valid, existing path to the codebook file. If the path is invalid, initialize without a codebook and build it later. ```python extractor = RobustSynthIDExtractor( codebook_path='nonexistent.pkl' # FileNotFoundError ) ``` ```python import os path = 'artifacts/codebook/robust_codebook.pkl' if os.path.exists(path): extractor = RobustSynthIDExtractor(codebook_path=path) else: extractor = RobustSynthIDExtractor() # Create without codebook # Build one later via extract_codebook() ``` -------------------------------- ### RobustSynthIDExtractor Constructor Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/api-reference-robust-extractor.md Initializes the RobustSynthIDExtractor with configurable parameters for multi-scale analysis, denoising, and carrier frequency detection. ```APIDOC ## RobustSynthIDExtractor Constructor ### Description Initializes the RobustSynthIDExtractor with configurable parameters for multi-scale analysis, denoising, and carrier frequency detection. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Signature ```python RobustSynthIDExtractor( scales: List[int] = [256, 512, 1024], wavelets: List[str] = ['db4', 'sym8', 'coif3'], n_carriers: int = 100, codebook_path: Optional[str] = None ) ``` ### Parameters - **scales** (List[int]) - Optional - Image scales for multi-scale analysis. Defaults to `[256, 512, 1024]`. - **wavelets** (List[str]) - Optional - Wavelet families for denoising. Defaults to `['db4', 'sym8', 'coif3']`. - **n_carriers** (int) - Optional - Number of carrier frequencies to track. Defaults to `100`. - **codebook_path** (str) - Optional - Path to pre-extracted codebook (`.pkl`). Defaults to `None`. ### Example ```python from src.extraction.robust_extractor import RobustSynthIDExtractor extractor = RobustSynthIDExtractor( scales=[512, 1024], codebook_path='artifacts/codebook/robust_codebook.pkl' ) ``` ``` -------------------------------- ### Run V3 Bypass (Python API) Source: https://github.com/aloshdenny/reverse-synthid/blob/main/README.md Utilize the SynthIDBypass class for the V3 bypass. Load the spectral codebook and provide the image data. The 'strength' parameter controls the bypass intensity. ```python from src.extraction.synthid_bypass import SynthIDBypass, SpectralCodebook codebook = SpectralCodebook() codebook.load('artifacts/spectral_codebook_v3.npz') bypass = SynthIDBypass() result = bypass.bypass_v3(image_rgb, codebook, strength='aggressive') print(f"PSNR: {result.psnr:.1f} dB") print(f"Profile used: {result.details['profile_resolution']}") ``` -------------------------------- ### Calibrate Codebook from Feedback Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/README.md Calibrate an existing spectral codebook using manual feedback. Provide the current codebook, feedback file, and desired output path for the calibrated codebook. ```bash python scripts/calibrate_from_feedback.py \ --codebook artifacts/spectral_codebook_v4.npz \ --feedback manual_feedback.json \ --output artifacts/spectral_codebook_v4_calibrated.npz ``` -------------------------------- ### SpectralCodebook.load Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/api-reference-synthid-bypass-v3.md Loads a spectral codebook from a specified file path. ```APIDOC ## SpectralCodebook.load(path: str) -> None ### Description Load codebook from file (`.npz` or `.pkl`). ### Parameters #### Path Parameters - **path** (str) - Required - Codebook file path ### Example ```python from src.extraction.synthid_bypass import SpectralCodebook codebook = SpectralCodebook() codebook.load('artifacts/spectral_codebook_v3.npz') ``` ``` -------------------------------- ### SynthID Regen Combo Preset Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/configuration.md Full stack configuration including VAE, geometry, FFT, and JPEG. Includes residual processing parameters. ```json { "vae_strength": 1.0, "psnr_floor": 16.0, "geo_rotation_deg": 0.5, "geo_zoom": 0.015, "geo_translate_px": 1, "do_residual": True, "residual_mag_cap": 0.35, "residual_removal": 1.00, "residual_harvest_k": 96, "residual_consensus_floor": 0.50, "residual_denoise_h": 10.0, "post_jpeg_q": 90, "post_noise_sigma": 0.5, "post_bilateral_d": 0 } ``` -------------------------------- ### load Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/api-reference-synthid-bypass-v4.md Loads a V4 codebook from a `.npz` file. This method supports various format versions, including the current compressed sparse format. ```APIDOC ## load(path: str) ### Description Load a V4 codebook `.npz`. Handles format versions 4–5 (float16/uint8 uncompressed through current int8/uint8 compressed sparse format). ### Parameters #### Path Parameters - **path** (str) - Required - Input `.npz` file path ### Throws `ValueError` if format version < 4. ### Example ```python cb = SpectralCodebookV4() cb.load('artifacts/spectral_codebook_v4.npz') print(f"Loaded {len(cb.keys)} profiles") ``` ``` -------------------------------- ### Device Selection Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/api-reference-vae-regen.md Selects the appropriate device for computation, prioritizing explicit preferences, CUDA, MPS, and finally CPU. ```APIDOC ## _select_device(prefer: Optional[str] = None) -> str ### Description Pick device in priority order: explicit preference → CUDA → MPS (Apple Silicon) → CPU. ### Parameters #### Query Parameters - **prefer** (str) - Optional - Explicit device: `'cuda'`, `'mps'`, `'cpu'` ### Returns Device string ready for PyTorch. ### Example ```python device = _select_device(prefer='cuda') # Returns 'cuda' if available, else 'cpu' ``` ``` -------------------------------- ### Load V4 Codebook (Python) Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/api-reference-synthid-bypass-v4.md Loads a V4 codebook from a specified `.npz` file path. This method supports various format versions and will throw a ValueError for versions older than 4. ```python cb = SpectralCodebookV4() cb.load('artifacts/spectral_codebook_v4.npz') print(f"Loaded {len(cb.keys)} profiles") ``` -------------------------------- ### Padding Utilities Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/api-reference-vae-regen.md Provides utility functions for padding and unpadding NumPy arrays, specifically for image dimensions to be multiples of 8, as required by the VAE. ```APIDOC ## _pad_to_multiple(arr: np.ndarray, mult: int = 8) -> Tuple[np.ndarray, Tuple[int, int, int, int]] ### Description Reflect-pad HxWxC image so H, W are multiples of `mult`. VAE requires 8-multiple dimensions. ### Parameters #### Path Parameters - **arr** (np.ndarray) - Required - Input array HxWxC - **mult** (int) - Optional - Multiple to pad to ### Returns Tuple of `(padded_array, (top, bottom, left, right))`. ### Example ```python padded, pads = _pad_to_multiple(image, mult=8) # Pad to 8-multiple dimensions ``` ``` ```APIDOC ## _unpad(arr: np.ndarray, pads: Tuple[int, int, int, int]) -> np.ndarray ### Description Remove padding applied by `_pad_to_multiple()`. ### Parameters #### Path Parameters - **arr** (np.ndarray) - Required - Padded array - **pads** (Tuple[int, int, int, int]) - Required - Pad amounts `(top, bottom, left, right)` ### Returns Un-padded array. ``` -------------------------------- ### save Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/api-reference-synthid-bypass-v4.md Saves all generated profiles to a compressed `.npz` file. It utilizes LZMA compression and sparse zeroing for efficient storage. ```APIDOC ## save(path: str) ### Description Save all profiles to compressed `.npz`. Uses LZMA compression with sparse zeroing for ~220 MB on a 14-profile codebook across 2 models × 7 resolutions. ### Parameters #### Path Parameters - **path** (str) - Required - Output `.npz` file path ### Format details Bins where consensus coherence < 0.55 are zeroed before saving; phase stored as `int8` (±1.4° error); magnitude as `uint8` log2-transformed; carrier weights as `uint8` (×255). ### Example ```python cb.save('artifacts/spectral_codebook_v4.npz') ``` ``` -------------------------------- ### SynthID Encoder and Decoder Process Source: https://github.com/aloshdenny/reverse-synthid/blob/main/README.md This diagram outlines the high-level steps involved in SynthID's encoding (within Gemini) and decoding (within Google) processes. The encoder selects frequencies, assigns phases, adds noise, and embeds an imperceptible watermark. The decoder extracts noise, uses FFT to check phases at carrier frequencies, and determines if the image is watermarked. ```text ┌──────────────────────────────────────────────────────────────┐ │ SynthID Encoder (in Gemini) │ ├──────────────────────────────────────────────────────────────┤ │ 1. Select resolution-dependent carrier frequencies │ │ 2. Assign fixed phase values to each carrier │ │ 3. Neural encoder adds learned noise pattern to image │ │ 4. Watermark is imperceptible — spread across spectrum │ ├──────────────────────────────────────────────────────────────┤ │ SynthID Decoder (in Google) │ ├──────────────────────────────────────────────────────────────┤ │ 1. Extract noise residual (wavelet denoising) │ │ 2. FFT → check phase at known carrier frequencies │ │ 3. If phases match expected values → Watermarked │ └──────────────────────────────────────────────────────────────┘ ``` -------------------------------- ### load_codebook Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/api-reference-robust-extractor.md Loads a pre-extracted codebook from a specified file path. It supports auto-detection of `.pkl` files even when a `.npz` path is provided. ```APIDOC ## load_codebook ### Description Loads a pre-extracted codebook from a specified file path. It supports auto-detection of `.pkl` files even when a `.npz` path is provided. ### Method `load_codebook(path: str) -> None` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **path** (str) - Required - Path to `.pkl` codebook file. ### Throws - `FileNotFoundError`: If the path doesn't exist or the `.npz` file lacks a companion `.pkl`. ### Example ```python extractor.load_codebook('artifacts/codebook/robust_codebook.pkl') ``` ``` -------------------------------- ### Handle ValueError: Codebook has no profiles Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/errors.md This error occurs when `get_profile()` is called on an empty `SpectralCodebookV4` instance. Load the codebook before attempting to retrieve profiles. ```python cb = SpectralCodebookV4() profile, key, exact = cb.get_profile(1024, 1024) # ValueError ``` ```python cb = SpectralCodebookV4() cb.load('artifacts/spectral_codebook_v4.npz') # Load before use profile, key, exact = cb.get_profile(1024, 1024) ``` -------------------------------- ### Apply SynthID for Consumer Images Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/configuration.md Applies SynthID with the 'final' strength preset, suitable for consumer images where high fidelity is prioritized. This uses a 1-pass VAE and a PSNR floor of 14 dB. ```python bypass.bypass_v4_final(image, codebook, strength='final') ``` -------------------------------- ### Apply SynthID for Archive/Dataset Cleanup Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/configuration.md Applies SynthID with the 'moderate' strength preset, offering a balanced approach for archive or dataset cleanup. It uses 2-pass spectral subtraction and a PSNR floor of 42 dB. ```python bypass.bypass_v4(image, codebook, strength='moderate') ``` -------------------------------- ### SynthID Regen Plus Preset Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/configuration.md Combines VAE with CombinationWorst geometry. Adjusts PSNR floor and geometry parameters. ```json { "vae_strength": 1.0, "psnr_floor": 18.0, "geo_rotation_deg": 0.4, "geo_zoom": 0.012, "geo_translate_px": 1 } ``` -------------------------------- ### Stage Applied String Format Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/types.md Represents a human-readable description of each processing stage applied. The format includes the stage name, its parameters, and performance metrics like PSNR. ```python str # Format: "stage_name(key=value,...)pass_idx(metric=value,...)" ``` ```text "vae_pass_0(psnr=25.3)" "elastic(a=1.80,s=56.0)(psnr=24.8)" "pass_0(psnr=34.5)" "anti_alias" "jpeg(q=92)" "post_bilateral_d(sigma=10.0)" "geometric_combo(rot=0.3°,zoom=0.008)" ``` -------------------------------- ### SynthIDBypass Constructor Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/api-reference-synthid-bypass-v3.md Initializes the SynthIDBypass pipeline for removing SynthID watermarks. ```APIDOC ## SynthIDBypass(iterations: int = 3, extractor=None) ### Description Remove SynthID watermarks using multi-stage signal processing pipeline. ### Parameters #### Path Parameters - **iterations** (int) - Optional - Number of bypass passes. Defaults to 3. - **extractor** (RobustSynthIDExtractor) - Optional - Optional detector for verification. ``` -------------------------------- ### Load Codebook for RobustSynthIDExtractor Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/api-reference-robust-extractor.md Load a pre-extracted codebook into the extractor. This method supports loading from .pkl files and will attempt to find a companion .pkl if a .npz path is provided. ```python extractor.load_codebook('artifacts/codebook/robust_codebook.pkl') ``` -------------------------------- ### Select Device for PyTorch Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/api-reference-vae-regen.md Selects the appropriate device (CUDA, MPS, or CPU) for PyTorch operations. Prioritizes explicit preference, then CUDA, then MPS, falling back to CPU. ```python device = _select_device(prefer='cuda') # Returns 'cuda' if available, else 'cpu' ``` -------------------------------- ### get_profile Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/api-reference-synthid-bypass-v4.md Retrieves the best-matching profile for a given image height (h) and width (w), with an optional model hint. It prioritizes exact matches and falls back to similar resolutions or aspect ratios. ```APIDOC ## get_profile(h: int, w: int, model: Optional[str] = None) ### Description Best-matching profile for `(H, W)` and optional `model`. Prefers exact `(model, H, W)` match; falls back to any model at same resolution, then closest aspect ratio. ### Parameters #### Path Parameters - **h** (int) - Required - Target image height in pixels - **w** (int) - Required - Target image width in pixels - **model** (str) - Optional - Optional model hint (e.g. `gemini-3.1-flash-image-preview`). If None, searches all models ### Returns Tuple of `(profile, (model, H, W), exact_match)` where `exact_match` is boolean. ### Example ```python cb = SpectralCodebookV4() cb.load('artifacts/spectral_codebook_v4.npz') profile, key, exact = cb.get_profile(1024, 1024, model='gemini-3.1-flash-image-preview') print(f"Using profile: {key[0]}/{key[1]}x{key[2]}, exact match: {exact}") ``` ``` -------------------------------- ### SpectralCodebook.get_profile Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/api-reference-synthid-bypass-v3.md Retrieves the best-matching spectral profile for a given image height and width. ```APIDOC ## SpectralCodebook.get_profile(h: int, w: int) -> Tuple[np.ndarray, np.ndarray, bool] ### Description Get best-matching profile for `(H, W)`. ### Parameters #### Path Parameters - **h** (int) - Required - Target height - **w** (int) - Required - Target width ### Returns - **carrier_phase** (np.ndarray) - The carrier phase component of the profile. - **carrier_magnitude** (np.ndarray) - The carrier magnitude component of the profile. - **exact_match** (bool) - Indicates if an exact match was found. ``` -------------------------------- ### VAE Image Roundtrip with Blending Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/api-reference-vae-regen.md Performs a VAE image roundtrip with adjustable blending between the reconstructed image and the original. Strength controls the blend; higher values mean more reconstruction. `blend_with_original` offers an alternative semantic for blending. ```python # Pure reconstruction (may show more VAE artifacts) pure = vae_roundtrip(image_uint8, strength=1.0) # 80% reconstruction + 20% original (preserves some original structure) blended = vae_roundtrip(image_uint8, strength=0.8) # Using blend_with_original semantics (equivalent to strength=0.7) blended_alt = vae_roundtrip(image_uint8, blend_with_original=0.3) ``` -------------------------------- ### Apply Universal Bypass v4 Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/api-reference-synthid-bypass-v4.md Utilizes native-resolution absolute-bin subtraction with fixed offsets. Strength presets determine whether to use codebook phase ('blog_') or image's own denoise-residual phase ('residual_'). ```python result = b.bypass_v4_universal(image_rgb, cb, strength='blog_pure') ``` -------------------------------- ### Run Batch Processing Workflow Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/README.md Use this command to process a directory of watermarked images and save the cleaned output. Specify input/output paths and the codebook artifact. ```bash python scripts/dissolve_batch.py \ --input ./watermarked_images/ \ --output ./cleaned_images/ \ --codebook artifacts/spectral_codebook_v4.npz \ --model gemini-3.1-flash-image-preview \ --strengths final nuke ``` -------------------------------- ### Handle SpectralCodebook Loading Errors Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/errors.md Catch ValueError when a SpectralCodebook file is not found or not readable. Ensure the file exists and is accessible before attempting to load. ```python codebook = SpectralCodebook() codebook.load('nonexistent.npz') # ValueError ``` ```python import os path = 'artifacts/spectral_codebook_v3.npz' if not os.path.exists(path): print(f"Codebook not found: {path}") else: codebook = SpectralCodebook() codebook.load(path) ``` -------------------------------- ### SpectralCodebook Class Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/INDEX.md Legacy SpectralCodebook class for loading and saving spectral data. ```APIDOC ### **V3 (Legacy):** #### `SpectralCodebook` ##### Description Legacy SpectralCodebook class supporting load and save operations. ``` -------------------------------- ### Load and Detect with V4 Codebook Source: https://github.com/aloshdenny/reverse-synthid/blob/main/README.md Loads the V4 spectral codebook and uses the RobustSynthIDExtractor to detect watermarking from an image. Useful for sanity-checking bypass outputs against the codebook's consensus. ```python from robust_extractor import RobustSynthIDExtractor from synthid_bypass_v4 import SpectralCodebookV4 cb = SpectralCodebookV4() cb.load('artifacts/spectral_codebook_v4.npz') ext = RobustSynthIDExtractor() result = ext.detect_from_v4_codebook(image_rgb, cb, model='nano-banana-pro-preview') print(result.is_watermarked, result.confidence, result.phase_match) ``` -------------------------------- ### VAE Roundtrip Configuration Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/configuration.md Perform a VAE roundtrip operation on an image. Configure the strength of the VAE effect, the computation device, blending with the original image, and the specific VAE model ID. ```python result = vae_roundtrip( image_uint8, strength=1.0, # 1.0 = pure VAE, 0.7 = blend 70/30 device='cuda', # cuda, mps, cpu blend_with_original=0.0, # Alias for (1.0 - strength) model_id='stabilityai/sd-vae-ft-mse' # HF model ID ) ``` -------------------------------- ### VAE Loading Source: https://github.com/aloshdenny/reverse-synthid/blob/main/_autodocs/api-reference-vae-regen.md Lazy-loads and caches the Stable Diffusion VAE as a singleton. Supports different model IDs, devices, and data types. ```APIDOC ## load_vae(model_id: str = "stabilityai/sd-vae-ft-mse", device: Optional[str] = None, dtype: str = "float32") -> Tuple[torch.nn.Module, str] ### Description Lazy-load and cache the SD-VAE as a singleton. Returns `(vae, device_str)`. ### Parameters #### Query Parameters - **model_id** (str) - Optional - HuggingFace model ID. `sd-vae-ft-mse` (fast) or SDXL variants - **device** (str) - Optional - Device override. Auto-selected if None - **dtype** (str) - Optional - Precision: `'float32'`, `'float16'`, `'bfloat16'`. MPS forces float32 ### Returns Tuple of `(vae_module, device_str)`. ### Throws `RuntimeError` if torch/diffusers not installed. ### Example ```python from src.extraction.vae_regen import load_vae vae, device = load_vae(device='cuda', dtype='float16') print(f"VAE loaded on {device}") ``` ```