#!/usr/bin/env python3 """run_competitors.py - re-runs the WAM and TrustMark rows of README.md on this folder's photos and attacks, and compares every value with sets//results/rivals.csv. Each method marks each set's ORIGINALS (rebuilt from the public datasets by scripts/prep.py: run scripts/download_sources.sh first) with its own message (bits_for below: the benchmark's message for that photo), merging its watermark into the full-size photo BICUBIC (the SynthID-Image paper's choice); the folder's transforms.py attacks the marked copy and the unmarked original with the same seeds as the Vereye copies; every copy - marked AND unmarked - is decoded against the photo's own message. Scores: WAM's bit accuracy and its own detection (mask) score; TrustMark's data-bit accuracy after its error correction, its raw 100-bit accuracy before it, and its presence flag. Then: python3 scripts/score.py on a copy of the folder whose rivals.csv is this script's output gives the README's rival rows. The exact versions used: torch 2.14.1 (CPU), torchvision 0.29.1, trustmark 0.9.2 (its Q models: decoder_Q.ckpt SHA-256 e3d9cea5406a26590735719f8f15cb10802b11852ae69047eaf4cf17214df781, encoder_Q.ckpt dc382c3f6b4fd568b27d6fbb763d6ffc2d2587126d84afe9d5ee95b4c5d99826), Watermark Anything at commit 2c08af04d037d5667c02f6ddebbda9ff04581c3e with checkpoints/wam_mit.pth SHA-256 90ef232384e023bd63245eb0c131abd69d2afc7b8f17a71ccedceb542bf009e2. Our published rival rows came from a batched run of the same arithmetic (many copies per network pass; checked equal to this per-image decode on 12 copies, marked and unmarked, WAM and TrustMark). pip install -r requirements.txt torch==2.14.1 torchvision==0.29.1 trustmark==0.9.2 omegaconf git clone https://github.com/facebookresearch/watermark-anything && git -C watermark-anything checkout 2c08af04d037d5667c02f6ddebbda9ff04581c3e python3 scripts/run_competitors.py --sources DIR --set heldout-coco-val2017-512 --method trustmark --photos 000000570448,000000570456 python3 scripts/run_competitors.py --sources DIR --set heldout-coco-val2017-512 --method wam --wam-code watermark-anything The output (rerun--.csv) is written to the CURRENT directory, never into this folder.""" import argparse, csv, hashlib, io, json, os, sys import numpy as np from PIL import Image HERE = os.path.dirname(os.path.abspath(__file__)); KIT = os.path.dirname(HERE); sys.path.insert(0, HERE) import transforms as K, prep # noqa: E402 def bits_for(img_id, n, salt): h = hashlib.sha256(f'{salt}:{img_id}'.encode()).digest() * 4 return [(h[i // 8] >> (i % 8)) & 1 for i in range(n)] class TrustMarkQ: salt = 'tm' def __init__(self, _): import torch; torch.set_num_threads(4) from trustmark import TrustMark self.tm = TrustMark(verbose=False, model_type='Q', encoding_type=TrustMark.Encoding.BCH_5); self.n = self.tm.schemaCapacity() def embed(self, im, bits): s = ''.join(map(str, bits)); self.cw = np.asarray(self.tm.ecc.encode_binary([s])).ravel().astype(int) return self.tm.encode(im, s, MODE='binary', WM_MERGE='bicubic') def decode(self, im, bits): import torch from torchvision import transforms as TV secret, present, _ = self.tm.decode(im, MODE='binary'); got = [int(c) for c in secret][:self.n] if secret else [] r = self.tm.model_resolution_dec; x = TV.ToTensor()(self.tm.get_the_image_for_processing(im).resize((r, r), Image.BILINEAR)).unsqueeze(0) * 2.0 - 1.0 with torch.no_grad(): raw = (self.tm.decoder.decoder(x) > 0).cpu().numpy().ravel().astype(int) return {'bitacc': acc(got, bits), 'rawacc': float(np.mean(raw[:len(self.cw)] == self.cw)), 'mask': '', 'present': bool(present), 'ident': bool(present and got == bits)} class WAM: salt = 'wam' def __init__(self, code): import torch, omegaconf; torch.set_num_threads(4); sys.path.insert(0, code); cwd = os.getcwd(); os.chdir(code) try: from watermark_anything.models import Wam, build_embedder, build_extractor from watermark_anything.augmentation.augmenter import Augmenter from watermark_anything.data.transforms import default_transform, normalize_img, unnormalize_img from watermark_anything.modules.jnd import JND from watermark_anything.data.metrics import msg_predict_inference a = argparse.Namespace(**json.load(open('checkpoints/params.json'))) emb = omegaconf.OmegaConf.load(a.embedder_config)[a.embedder_model]; ext = omegaconf.OmegaConf.load(a.extractor_config) att = JND(**omegaconf.OmegaConf.load(a.attenuation_config)[a.attenuation], preprocess=unnormalize_img, postprocess=normalize_img) self.wam = Wam(build_embedder(a.embedder_model, emb, a.nbits), build_extractor(ext.model, ext[a.extractor_model], a.img_size, a.nbits), Augmenter(**omegaconf.OmegaConf.load(a.augmentation_config)), att, a.scaling_w, a.scaling_i) self.wam.load_state_dict(torch.load('checkpoints/wam_mit.pth', map_location='cpu')); self.wam.eval() finally: os.chdir(cwd) self.torch, self.T, self.unnorm, self.predict, self.n = torch, default_transform, unnormalize_img, msg_predict_inference, a.nbits def embed(self, im, bits): from torchvision import transforms as TV with self.torch.no_grad(): x = self.T(im).unsqueeze(0); h = self.wam.img_size_extractor r = TV.Resize((h, h), interpolation=TV.InterpolationMode.BILINEAR)(x) if x.shape[-2:] != (h, h) else x pw = self.wam.embedder(r, self.torch.tensor(bits, dtype=self.torch.float32).unsqueeze(0)) if x.shape[-2:] != (h, h): pw = TV.Resize(x.shape[-2:], interpolation=TV.InterpolationMode.BICUBIC, antialias=True)(pw) return Image.fromarray(self.unnorm(self.wam.blend(x, pw)[0]).clamp(0, 1).mul(255).round().byte().permute(1, 2, 0).numpy()) def decode(self, im, bits): F = self.torch.nn.functional with self.torch.no_grad(): p = self.wam.detect(self.T(im).unsqueeze(0))['preds']; m = F.sigmoid(p[:, 0:1]); got = [int(x) for x in self.predict(p[:, 1:], m).float()[0].tolist()] return {'bitacc': acc(got, bits), 'rawacc': '', 'mask': float(m.mean()), 'present': '', 'ident': got == bits} def png(im): b = io.BytesIO(); im.save(b, 'PNG', compress_level=1); b.seek(0); return Image.open(b).convert('RGB') # lossless, as the benchmark kept them def acc(got, ref): return sum(int(a == b) for a, b in zip(got, ref)) / len(ref) if len(got) == len(ref) else 0.0 if __name__ == '__main__': ap = argparse.ArgumentParser(); ap.add_argument('--sources', required=True); ap.add_argument('--set', required=True) ap.add_argument('--method', choices=['wam', 'trustmark'], required=True); ap.add_argument('--wam-code', default='watermark-anything'); ap.add_argument('--photos'); a = ap.parse_args() D = os.path.join(KIT, 'sets', a.set); K.S = json.load(open(os.path.join(D, 'set.json')))['size']; M = (WAM if a.method == 'wam' else TrustMarkQ)(a.wam_code) photos = sorted(os.listdir(os.path.join(D, 'photos'))) if a.photos: photos = [p for p in photos if p in set(a.photos.split(','))] pub = {(r['photo'], r['transformation'], r['mode'], r['marked']): r for r in csv.DictReader(open(os.path.join(D, 'results', 'rivals.csv'), newline='')) if r['method'] == a.method} out = os.path.abspath(f'rerun-{a.method}-{a.set}.csv'); rows = []; same = diff = 0; TMP = __import__('tempfile').mkdtemp() for p in photos: info = json.load(open(os.path.join(D, 'photos', p, 'info.json'))); orig = prep.prep(os.path.join(a.sources, info['source_file']['file']), os.path.join(TMP, f'{p}.png'), K.S) os.remove(os.path.join(TMP, f'{p}.png')); bits = bits_for(p, M.n, M.salt); marked = png(M.embed(orig, bits)) for n in K.T: for md in ('random', 'worst'): for mk, src in ((1, marked), (0, orig)): im, _ = K.apply(n, md, src, K.seed_of(p, n, md)); r = {'set': a.set, 'method': a.method, 'photo': p, 'transformation': n, 'mode': md, 'group': K.T[n][0], 'marked': mk, **M.decode(png(im), bits)} rows.append(r); q = pub.get((p, n, md, str(mk))) if q: ok = abs(float(q['bitacc'] or 0) - float(r['bitacc'] or 0)) < 1e-9; same += ok; diff += not ok print(f'{p} done', flush=True) with open(out, 'w', newline='') as f: w = csv.DictWriter(f, list(rows[0])); w.writeheader(); w.writerows(rows) print(f'{len(rows)} copies scored -> {out}; bit accuracy equal to results/rivals.csv on {same} of {same + diff} copies')