Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat([issue-1764]): adversarial-jamming SynthID-disruption experiment + research note

[._.]/ Adam Eivy23004c6b4bde
diff --git a/docs/plans/2026-07-18-synthid-adversarial-jamming-experiment.md b/docs/plans/2026-07-18-synthid-adversarial-jamming-experiment.md
new file mode 100644
index 0000000000..c033cdc1da
--- /dev/null
+++ b/docs/plans/2026-07-18-synthid-adversarial-jamming-experiment.md
@@ -0,0 +1,188 @@
+# Adversarial jamming as a quality-preserving SynthID-disruption vector — experiment
+
+**Date:** 2026-07-18 · **Area:** `server/lib/imageClean.js`, `server/services/imageGen/regen.js` (context only — nothing shipped) · **Issue:** #1764 · **Lineage:** #912, #970, #1763; builds on `docs/plans/2026-06-05-synthid-removal-eval.md`
+
+Research record for a **scientific-curiosity experiment** (not a product commitment):
+can *adversarial jamming* — low-amplitude structured perturbation aimed at the
+frequency band an invisible watermark rides in — push a detector's correlation
+below threshold with **less** image degradation than a diffusion (VAE) round-trip?
+The hope was that light, frequency-targeted perturbation preserves quality —
+especially **text glyphs** (the comic-dialog problem from #1763) — better than a
+heavier diffusion pass.
+
+## Bottom line (read this first)
+
+- **Recommendation: do NOT promote any jamming stage into the real pipeline yet.**
+ The shipped VAE regen (`regen.js`) remains the honest defeat path.
+- The experiment *does* show the **mechanism is promising**: on a synthetic
+ phase-carrying band watermark, **FFT phase perturbation** is a high-fidelity
+ disruptor — ~55% detection-margin removal at **PSNR 22.4 dB with 90% of text
+ edge-energy preserved**, where a blur/diffusion proxy reaching similar
+ disruption **destroys text** (edge-energy retention ~0.02) at lower PSNR.
+- **But the result cannot transfer to real SynthID**, and we have direct evidence
+ of that: the one stage we *can* cross-check against prior real-SynthID findings —
+ **resize-squeeze** — behaves **oppositely** on the proxy (near-useless here) vs.
+ real SynthID (a known-good cheap defeat, #970), because our proxy mark is
+ resolution-independent while SynthID's carriers are resolution-dependent. That
+ contradiction is the proof that proxy-oracle numbers describe *frontier shape*,
+ not real-SynthID effectiveness.
+- Per the issue's **honesty guardrail**: no UI copy, changelog, or docs may claim
+ guaranteed (or even measured) SynthID removal from this work. Language stays at
+ "disrupt / best-effort / experimental."
+
+## The hard constraint (why this is measured by proxy)
+
+Google's SynthID Detector is limited-access with **no public API and no open image
+detector** (Google open-sourced SynthID-*Text*, not the image model). So we have
+**no oracle** to confirm any jam actually cleared real SynthID. We can measure
+*fidelity* (PSNR, text legibility) directly, but *disruption* of real SynthID is
+unmeasurable here.
+
+To still get a disruption signal — not just a fidelity signal — the experiment
+stands up its **own synthetic watermark + matched-filter detector as a proxy
+oracle**:
+
+- **Mark:** a zero-mean pseudorandom field, band-limited to a mid-frequency
+ annulus (0.14–0.34 of Nyquist), added at low amplitude to luminance. This is a
+ classic **linear spread-spectrum** watermark whose energy sits in a known
+ frequency band — deliberately chosen to *model the one property the eval doc
+ attributes to SynthID* ("invisible carriers at resolution-dependent FFT bins").
+- **Detector:** matched filter (band-pass the candidate, correlate against the
+ known field), reported as a **z-score** against a null distribution of random
+ rotations. `z(clean)=0.79`, `z(watermarked)=14.67` → detection margin **13.88**.
+
+**What the proxy is NOT:** SynthID's real carrier is proprietary and almost
+certainly a *learned, non-linear, per-pixel* signal — not a simple linear
+phase-carrying band mark. So results characterize the **shape** of the
+jamming↔fidelity↔text frontier and confirm mechanism plausibility; they are not
+effectiveness claims against SynthID.
+
+## Method
+
+`scripts/experiments/synthid_jamming_eval.py` (self-contained; numpy + pillow, no
+GPU/torch/network; fixed seeds → bit-reproducible). It:
+
+1. Renders a **fully synthetic** 512² test image (no real user images / no PII):
+ smooth gradient + radial low-freq structure + photo-like grain + hard
+ rectangle edges + rendered text incl. a digit row — so we measure both global
+ fidelity and glyph preservation.
+2. Embeds the synthetic mark and records the proxy-oracle baseline.
+3. Sweeps four disruption stages over increasing strength, measuring per config:
+ - **z_after** — residual detector z-score (higher = still detected)
+ - **disruption %** — fraction of the 13.88 detection margin removed
+ - **PSNR (dB)** vs the watermarked source (global fidelity)
+ - **text_legibility** — retained high-freq edge energy in the text band
+ (1.0 = glyphs fully preserved; the #1763 concern)
+
+Stages:
+
+| Stage | What it models |
+|---|---|
+| `fft_band_noise` | Additive structured noise confined to the mark's band (issue idea #1). |
+| `fft_phase_perturb` | Randomize phase within the band, keep magnitude (the reverse-SynthID "FFT phase subtraction" family we skipped in #970). |
+| `resize_squeeze` | Downscale→upscale — the CPU-cheap resolution-shift stage PortOS already ships (`REGEN_SQUEEZE_FACTOR`, #970). Baseline. |
+| `diffusion_proxy` | Gaussian-blur round-trip as a **conservative** CPU stand-in for a low-strength VAE img2img pass. A real VAE *redraws* texture instead of blurring, so this *overstates* diffusion's fidelity cost on smooth/text regions — treat it as a pessimistic fidelity bound, not a faithful diffusion model. |
+
+## Results
+
+Proxy oracle: `z(clean)=0.79 z(watermarked)=14.67 margin=13.88 band=[0.14, 0.34]`
+
+```
+stage param z_after disrupt% PSNR dB text_leg
+---------------------------------------------------------------
+fft_band_noise 0.5 14.67 0.0 54.15 1.000
+fft_band_noise 1.0 14.66 0.1 48.13 1.001
+fft_band_noise 2.0 14.61 0.4 42.11 1.002
+fft_band_noise 3.5 14.49 1.3 37.25 1.006
+fft_band_noise 5.0 14.31 2.6 34.15 1.012
+
+fft_phase_perturb 0.15 13.93 5.3 31.60 0.980
+fft_phase_perturb 0.3 11.61 22.0 25.96 0.943
+fft_phase_perturb 0.5 6.98 55.3 22.40 0.900
+fft_phase_perturb 0.75 2.16 90.1 20.52 0.888
+fft_phase_perturb 1.0 1.05 98.1 20.08 0.889
+
+resize_squeeze 0.92 14.63 0.3 30.57 0.624
+resize_squeeze 0.85 14.54 0.9 29.41 0.567
+resize_squeeze 0.75 14.48 1.3 27.77 0.486
+resize_squeeze 0.6 14.26 2.9 25.65 0.378
+resize_squeeze 0.5 14.25 3.0 24.20 0.297
+
+diffusion_proxy 0.6 14.35 2.3 28.15 0.380
+diffusion_proxy 0.9 13.86 5.8 24.13 0.193
+diffusion_proxy 1.3 12.85 13.1 21.97 0.095
+diffusion_proxy 1.8 11.06 26.0 20.56 0.044
+diffusion_proxy 2.5 8.11 47.2 19.49 0.019
+```
+
+## Findings
+
+1. **Phase perturbation dominates the frontier (for a phase-carrying mark).** At
+ equal ~50% disruption, `fft_phase_perturb` (0.5) gives **PSNR 22.4 / text 0.90**
+ while `diffusion_proxy` (2.5) gives **PSNR 19.5 / text 0.019** — phase-perturb
+ is strictly better on *both* fidelity axes, and the text gap is enormous.
+ Randomizing phase in the carrier band destroys the matched-filter correlation
+ (which depends on phase alignment) while leaving broadband glyph edges largely
+ intact. This is the experiment's positive result — it validates the *idea* that
+ frequency-targeted perturbation can beat diffusion on the quality frontier.
+
+2. **"Inject noise in the band" (the issue's first idea) is the weakest vector.**
+ `fft_band_noise` barely moves the detector (2.6% even at amp 5.0). A matched
+ filter rejects energy that is *uncorrelated* with the known pattern, so adding
+ fresh random noise in the same band mostly averages out. Only perturbing the
+ *existing* signal the mark rides in (its phase) disrupts detection efficiently.
+ Useful negative result: additive band jamming is a dead end against a
+ correlation detector.
+
+3. **The proxy does NOT transfer — and we can prove it.** `resize_squeeze` is a
+ known-good cheap SynthID defeat (#970, because SynthID carriers move with
+ resolution) yet is near-useless here (≤3% disruption) — because our synthetic
+ mark is resolution-*independent*. Same stage, opposite verdict on proxy vs.
+ real SynthID. This is direct evidence that the phase-perturbation win above
+ **may or may not** hold against real SynthID: if SynthID's carrier is not a
+ linear phase-encoded band signal, phase randomization could do nothing to it.
+
+4. **The diffusion-proxy text collapse is real-world-relevant even discounted.**
+ Blur is a pessimistic stand-in, but the *direction* — heavier disruption ⇒
+ worse text — matches the shipped-pipeline motivation for keeping denoise low
+ and offering an ignore-zone (#1763). It reinforces "don't crank diffusion
+ strength for text-bearing images," independent of jamming.
+
+## Considered, NOT pursued
+
+- **FFT phase *subtraction* (estimate + subtract the watermark's phase signature)**
+ rather than randomization — the literal reverse-SynthID stage. Skipped because
+ estimating a *specific* mark's phase requires knowing the mark (we don't, for
+ real SynthID) or a clean reference (we don't have one at clean-time). Phase
+ *randomization* is the key-free version and is what we measured.
+- **Wiring a jamming stage behind a flag in `imageClean.js`.** Deliberately not
+ done: with no oracle and a proxy that demonstrably doesn't transfer, shipping
+ even a flagged stage would invite "SynthID removed" expectations the honesty
+ guardrail forbids. The script stays a standalone research artifact.
+- **Real-image corpus / SSIM / LPIPS.** Overkill for a mechanism-plausibility
+ probe with an unfaithful proxy oracle; the synthetic image + PSNR + edge-energy
+ legibility proxy answer the frontier-shape question at a fraction of the cost.
+
+## Recommendation & reopen criteria
+
+**Keep jamming experimental and unshipped.** Continue to rely on the VAE regen as
+the honest, hardware-gated defeat path. Revisit promotion **only if** one of these
+changes:
+
+1. **Detector access** — a public/limited SynthID Detector API, or a validated
+ open detector, appears. Then re-run this frontier against *real* SynthID (swap
+ the proxy oracle for the real one) before trusting any transfer.
+2. **Carrier evidence** — credible public analysis shows SynthID's image carrier
+ *is* phase-encoded in a recoverable band, making phase perturbation a
+ principled (not just proxy-plausible) attack.
+
+Until then: no jamming stage, no removal claims, "disrupt / best-effort /
+experimental" language only.
+
+## Reproduce
+
+```bash
+python3 -m venv /tmp/jam-venv && /tmp/jam-venv/bin/pip install numpy pillow
+/tmp/jam-venv/bin/python scripts/experiments/synthid_jamming_eval.py # table
+/tmp/jam-venv/bin/python scripts/experiments/synthid_jamming_eval.py --json # machine-readable
+```
diff --git a/scripts/experiments/synthid_jamming_eval.py b/scripts/experiments/synthid_jamming_eval.py
new file mode 100644
index 0000000000..bbe4dee4ae
--- /dev/null
+++ b/scripts/experiments/synthid_jamming_eval.py
@@ -0,0 +1,302 @@
+#!/usr/bin/env python3
+"""
+Adversarial-jamming SynthID-disruption experiment (issue #1764).
+
+STATUS: experimental / research-only. NOT wired into the PortOS image-cleaner
+pipeline (`server/lib/imageClean.js`, `server/services/imageGen/regen.js`). Run
+standalone to reproduce the measurements recorded in
+`docs/plans/2026-07-18-synthid-adversarial-jamming-experiment.md`.
+
+WHAT THIS DOES / WHAT IT CANNOT DO
+----------------------------------
+The motivating question (issue #1764): can *adversarial jamming* — low-amplitude
+structured noise / phase perturbation aimed at the frequency bands an invisible
+watermark rides in — knock a detector's correlation below threshold with LESS
+image degradation than a diffusion (VAE) round-trip?
+
+Hard constraint (from `docs/plans/2026-06-05-synthid-removal-eval.md`): Google's
+SynthID Detector is limited-access with NO public API, so we have NO oracle for
+real SynthID. We therefore CANNOT measure disruption of real SynthID here.
+
+To still get a *disruption* signal (not just a fidelity signal), this script
+stands up its own **synthetic spread-spectrum watermark** with a matched-filter
+detector as a PROXY ORACLE. It is a mid-frequency-band linear spread-spectrum
+mark — a classic, well-understood robust watermark — NOT SynthID. SynthID's real
+carrier is a proprietary, likely learned per-pixel signal. So the numbers here
+characterize the SHAPE of the jamming-vs-fidelity frontier and confirm mechanism
+plausibility; they do NOT transfer as effectiveness claims against real SynthID.
+Keep that caveat attached to every result. (This is the same "no detector-verified
+claims" honesty guardrail the issue mandates.)
+
+Metrics per processed image:
+ - detector z-score : proxy-oracle correlation of the mark (higher = still detected)
+ - disruption % : how much of the watermark's detection margin was removed
+ - PSNR (dB) : global fidelity vs the watermarked source (higher = better)
+ - text-legibility : retained high-frequency edge energy in the text band
+ (higher = glyphs better preserved) — the #1763 comic-dialog concern
+
+Dependencies: numpy, pillow. No GPU, no torch, no network.
+"""
+
+import argparse
+import json
+import sys
+
+import numpy as np
+from PIL import Image, ImageDraw, ImageFont
+
+RNG_SEED = 20260718 # fixed so runs are reproducible
+WM_SEED = 0xC0FFEE # synthetic-watermark key (proxy oracle)
+BAND_LO, BAND_HI = 0.14, 0.34 # annular mid-frequency band (fraction of Nyquist)
+
+
+# ----------------------------------------------------------------------------
+# Test image — fully synthetic (no real user images / no PII). A mix of smooth
+# gradients, photo-like textured noise, hard geometric edges, and rendered text
+# so we can measure BOTH global fidelity and text-glyph preservation.
+# ----------------------------------------------------------------------------
+def make_test_image(size=512):
+ rng = np.random.default_rng(RNG_SEED)
+ yy, xx = np.mgrid[0:size, 0:size].astype(np.float64)
+ grad = (xx / size) * 180 + (yy / size) * 40 # smooth gradient
+ radial = 60 * np.cos(np.hypot(xx - size / 2, yy - size / 2) / 22) # low-freq structure
+ texture = rng.normal(0, 12, (size, size)) # photo-like grain
+ base = np.clip(grad + radial + texture + 30, 0, 255)
+
+ img = Image.fromarray(base.astype(np.uint8)).convert("RGB")
+ draw = ImageDraw.Draw(img)
+ # Hard edges (frequency content across the spectrum)
+ for i in range(4):
+ draw.rectangle([40 + i * 90, 40, 90 + i * 90, 470], outline=(255, 255, 255), width=2)
+ # Rendered text — the comic-dialog legibility case from #1763
+ try:
+ font = ImageFont.truetype("/System/Library/Fonts/Supplemental/Arial.ttf", 34)
+ except OSError:
+ font = ImageFont.load_default()
+ for row, txt in enumerate(["QUALITY", "vs", "DISRUPTION", "0123456789"]):
+ draw.text((60, 120 + row * 70), txt, fill=(255, 255, 255), font=font)
+ return np.asarray(img.convert("L"), dtype=np.float64)
+
+
+def luminance(a):
+ return a
+
+
+# ----------------------------------------------------------------------------
+# Synthetic spread-spectrum watermark + matched-filter detector (PROXY ORACLE).
+# The mark is a zero-mean pseudorandom field, band-limited to a mid-frequency
+# annulus, added at low amplitude. Detection correlates the band-passed candidate
+# against the known field and reports a z-score (0 ~= not present).
+# ----------------------------------------------------------------------------
+def _annulus_mask(shape, lo=BAND_LO, hi=BAND_HI):
+ h, w = shape
+ fy = np.fft.fftfreq(h)[:, None]
+ fx = np.fft.fftfreq(w)[None, :]
+ r = np.hypot(fy, fx) / 0.5 # normalize so Nyquist -> 1.0
+ return (r >= lo) & (r <= hi)
+
+
+def watermark_field(shape):
+ rng = np.random.default_rng(WM_SEED)
+ noise = rng.standard_normal(shape)
+ F = np.fft.fft2(noise)
+ F[~_annulus_mask(shape)] = 0.0 # keep only the mid-frequency band
+ field = np.real(np.fft.ifft2(F))
+ field -= field.mean()
+ field /= (field.std() + 1e-9)
+ return field
+
+
+def embed_watermark(img, alpha=2.2):
+ return img + alpha * watermark_field(img.shape)
+
+
+def _bandpass(img):
+ F = np.fft.fft2(img - img.mean())
+ F[~_annulus_mask(img.shape)] = 0.0
+ return np.real(np.fft.ifft2(F))
+
+
+def detect_zscore(candidate, field):
+ """Matched-filter z-score of the mark in `candidate`.
+
+ Correlate the band-passed candidate against the known field, normalized by a
+ null distribution built from many random rotations of the field. High z =>
+ the watermark is still detectable.
+ """
+ bp = _bandpass(candidate)
+ bp = (bp - bp.mean()) / (bp.std() + 1e-9)
+ f = (field - field.mean()) / (field.std() + 1e-9)
+ obs = float(np.mean(bp * f))
+ rng = np.random.default_rng(RNG_SEED + 7)
+ null = []
+ flat = f.ravel()
+ n = flat.size
+ for _ in range(200):
+ shift = int(rng.integers(1, n - 1))
+ null.append(float(np.mean(bp.ravel() * np.roll(flat, shift))))
+ null = np.asarray(null)
+ return (obs - null.mean()) / (null.std() + 1e-9)
+
+
+# ----------------------------------------------------------------------------
+# Fidelity metrics
+# ----------------------------------------------------------------------------
+def psnr(a, b):
+ mse = float(np.mean((a - b) ** 2))
+ if mse <= 1e-12:
+ return 99.0
+ return 10.0 * np.log10((255.0 ** 2) / mse)
+
+
+def text_legibility(ref, cand):
+ """Retained high-frequency edge energy in the text band (rows 110..400).
+
+ Ratio of candidate gradient energy to reference gradient energy in the text
+ region, clipped to [0, 1.2]. 1.0 = glyph edges fully preserved; lower = the
+ process softened the text. Sensitive to blur (diffusion/roundtrip proxies)
+ and to spatial resampling (resize-squeeze).
+ """
+ def edge_energy(a):
+ crop = a[110:400, 40:472]
+ gx = np.diff(crop, axis=1)
+ gy = np.diff(crop, axis=0)
+ return float(np.mean(gx ** 2) + np.mean(gy ** 2))
+ e_ref = edge_energy(ref)
+ e_cand = edge_energy(cand)
+ return min(1.2, e_cand / (e_ref + 1e-9))
+
+
+# ----------------------------------------------------------------------------
+# Disruption stages under test
+# ----------------------------------------------------------------------------
+def jam_fft_band_noise(img, amp):
+ """Additive structured noise confined to the watermark's FFT band."""
+ rng = np.random.default_rng(RNG_SEED + 101)
+ noise = rng.standard_normal(img.shape)
+ F = np.fft.fft2(noise)
+ F[~_annulus_mask(img.shape)] = 0.0
+ band = np.real(np.fft.ifft2(F))
+ band /= (band.std() + 1e-9)
+ return img + amp * band
+
+
+def jam_fft_phase_perturb(img, amp):
+ """Randomize phase within the watermark band, keep magnitude (reverse-SynthID
+ 'phase subtraction' family). `amp` in [0,1] blends toward fully random phase."""
+ rng = np.random.default_rng(RNG_SEED + 202)
+ F = np.fft.fft2(img)
+ mask = _annulus_mask(img.shape)
+ mag = np.abs(F)
+ phase = np.angle(F)
+ rand_phase = rng.uniform(-np.pi, np.pi, img.shape)
+ new_phase = phase.copy()
+ new_phase[mask] = (1 - amp) * phase[mask] + amp * rand_phase[mask]
+ F2 = mag * np.exp(1j * new_phase)
+ return np.real(np.fft.ifft2(F2))
+
+
+def spatial_resize_squeeze(img, factor):
+ """Downscale by `factor` then back — the CPU-cheap resolution-shift defeat
+ stage PortOS already ships (REGEN_SQUEEZE_FACTOR, #970). Baseline to beat."""
+ h, w = img.shape
+ im = Image.fromarray(np.clip(img, 0, 255).astype(np.uint8))
+ small = im.resize((max(1, int(w * factor)), max(1, int(h * factor))), Image.LANCZOS)
+ back = small.resize((w, h), Image.LANCZOS)
+ return np.asarray(back, dtype=np.float64)
+
+
+def diffusion_roundtrip_proxy(img, sigma):
+ """Gaussian-blur round-trip as a CPU stand-in for a low-strength VAE/diffusion
+ img2img pass. A real VAE resample redraws texture rather than blurring, so
+ this OVERSTATES diffusion's fidelity cost on smooth regions and text — treat
+ it as a conservative (pessimistic) fidelity bound for the diffusion path, not
+ a faithful diffusion model."""
+ from math import ceil
+ radius = max(1, int(ceil(sigma * 3)))
+ ax = np.arange(-radius, radius + 1)
+ k = np.exp(-(ax ** 2) / (2 * sigma ** 2))
+ k /= k.sum()
+ blurred = img.copy()
+ blurred = np.apply_along_axis(lambda m: np.convolve(m, k, mode="same"), 0, blurred)
+ blurred = np.apply_along_axis(lambda m: np.convolve(m, k, mode="same"), 1, blurred)
+ return blurred
+
+
+# ----------------------------------------------------------------------------
+# Sweep driver
+# ----------------------------------------------------------------------------
+STAGES = {
+ "fft_band_noise": (jam_fft_band_noise, [0.5, 1.0, 2.0, 3.5, 5.0]),
+ "fft_phase_perturb": (jam_fft_phase_perturb, [0.15, 0.3, 0.5, 0.75, 1.0]),
+ "resize_squeeze": (spatial_resize_squeeze, [0.92, 0.85, 0.75, 0.6, 0.5]),
+ "diffusion_proxy": (diffusion_roundtrip_proxy, [0.6, 0.9, 1.3, 1.8, 2.5]),
+}
+
+
+def run(size=512, alpha=2.2):
+ clean = make_test_image(size)
+ field = watermark_field(clean.shape)
+ wm = embed_watermark(clean, alpha=alpha)
+
+ z_clean = detect_zscore(clean, field) # baseline: no mark
+ z_wm = detect_zscore(wm, field) # baseline: mark present
+ margin = z_wm - z_clean
+
+ rows = []
+ for name, (fn, params) in STAGES.items():
+ for p in params:
+ out = fn(wm, p)
+ z = detect_zscore(out, field)
+ disruption = max(0.0, min(1.0, (z_wm - z) / (margin + 1e-9)))
+ rows.append({
+ "stage": name,
+ "param": p,
+ "z_after": round(z, 2),
+ "disruption_pct": round(100 * disruption, 1),
+ "psnr_db": round(psnr(wm, out), 2),
+ "text_legibility": round(text_legibility(wm, out), 3),
+ })
+ return {
+ "meta": {
+ "size": size, "alpha": alpha,
+ "z_clean": round(z_clean, 2), "z_watermarked": round(z_wm, 2),
+ "detection_margin": round(margin, 2),
+ "band": [BAND_LO, BAND_HI],
+ },
+ "results": rows,
+ }
+
+
+def print_table(out):
+ m = out["meta"]
+ print(f"# Synthetic proxy-oracle: z(clean)={m['z_clean']} z(watermarked)={m['z_watermarked']} "
+ f"margin={m['detection_margin']} band={m['band']}\n")
+ hdr = f"{'stage':<18}{'param':>7}{'z_after':>9}{'disrupt%':>10}{'PSNR dB':>9}{'text_leg':>10}"
+ print(hdr)
+ print("-" * len(hdr))
+ last = None
+ for r in out["results"]:
+ if last and last != r["stage"]:
+ print()
+ print(f"{r['stage']:<18}{r['param']:>7}{r['z_after']:>9}{r['disruption_pct']:>10}"
+ f"{r['psnr_db']:>9}{r['text_legibility']:>10}")
+ last = r["stage"]
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__)
+ ap.add_argument("--size", type=int, default=512)
+ ap.add_argument("--alpha", type=float, default=2.2, help="watermark embed strength")
+ ap.add_argument("--json", action="store_true", help="emit JSON instead of a table")
+ args = ap.parse_args()
+ out = run(size=args.size, alpha=args.alpha)
+ if args.json:
+ json.dump(out, sys.stdout, indent=2)
+ print()
+ else:
+ print_table(out)
+
+
+if __name__ == "__main__":
+ main()