civicbench 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
civicbench/__init__.py ADDED
@@ -0,0 +1,29 @@
1
+ """CivicBench: load the benchmark and attack your own video detector with the paper's protocol.
2
+
3
+ A detector is any callable ``detector(x) -> score``:
4
+
5
+ * ``x``: float32 torch tensor ``[T, 3, H, W]`` in [0, 1], RGB; the official input is
6
+ ``[11, 3, 512, 512]`` (11 frames of 512 x 512);
7
+ * ``score``: one scalar (float, 0-d or 1-element tensor), higher = more likely generated; a clip is
8
+ flagged when ``score >= tau``.
9
+
10
+ Gradient attacks (PGD, APGD) need the score to be differentiable in ``x``; Square needs scores only.
11
+
12
+ import civicbench
13
+ clips = civicbench.load("path/to/civicbench/parquet") # or a Hugging Face repo id
14
+ table = civicbench.evaluate(my_detector, clips) # Table-2 columns, printed
15
+ r = civicbench.attack(my_detector, frames_u8, tau, "evasion") # one clip, budgets 1, 2, 4
16
+ civicbench.predict_survival([r, ...], budget=4, probe_budget=1)
17
+ """
18
+ from civicbench.attacks import DEFAULT_ATTACKS, FAMILIES
19
+ from civicbench.core import DEFAULT_BUDGETS, AttackResult, attack, evaluate, format_summary, score, seed_for
20
+ from civicbench.data import DEFAULT_REPO, Clip, ClipSet, load
21
+ from civicbench.frames import realize, to_tensor
22
+ from civicbench.margin import margin_reach, predict_survival
23
+ from civicbench.metrics import auc, threshold_at_fpr
24
+
25
+ __version__ = "0.1.0"
26
+
27
+ __all__ = ["load", "attack", "evaluate", "predict_survival", "margin_reach", "score", "threshold_at_fpr", "auc",
28
+ "AttackResult", "Clip", "ClipSet", "DEFAULT_REPO", "DEFAULT_BUDGETS", "DEFAULT_ATTACKS", "FAMILIES",
29
+ "format_summary", "seed_for", "realize", "to_tensor", "__version__"]
civicbench/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from civicbench.cli import main
4
+
5
+ sys.exit(main())
@@ -0,0 +1,256 @@
1
+ """One quiet, live progress line for long steps (load, attack, evaluate, CLI).
2
+
3
+ * On a terminal: ONE line redrawn in place, shown only once a step has lasted ``delay`` seconds
4
+ (default 2), with a spinner, a block bar, percent, done/total, elapsed time, ETA and a short
5
+ live status. It ends with one summary line. ``rich`` draws it when importable (extra
6
+ ``civicbench[fancy]``); otherwise a built-in fallback does, with no extra dependency.
7
+ * Not a terminal (e.g. cluster logs): one compact line at coarse milestones only, every 10% of
8
+ the work or every ``log_every`` seconds (default 300), whichever is rarer, then the summary line.
9
+ * ``quiet=True`` prints nothing. ``NO_COLOR`` (any value) turns colors off.
10
+ * While a progress line is live, progress objects created inside it (an attack inside evaluate,
11
+ the clip loader it reads from) stay silent, so there is never more than one line.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import math
16
+ import os
17
+ import re
18
+ import shutil
19
+ import sys
20
+ import threading
21
+ import time
22
+ from typing import Optional
23
+
24
+ SPINNER = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"
25
+ EIGHTHS = " ▏▎▍▌▋▊▉"
26
+ _ACTIVE = [0] # live progress objects (nesting depth)
27
+ _LOCK = threading.Lock()
28
+
29
+
30
+ def fmt_time(s: Optional[float]) -> str:
31
+ if s is None or not math.isfinite(s):
32
+ return "--:--"
33
+ s = int(round(s))
34
+ h, rem = divmod(s, 3600)
35
+ m, sec = divmod(rem, 60)
36
+ return f"{h}:{m:02d}:{sec:02d}" if h else f"{m}:{sec:02d}"
37
+
38
+
39
+ def block_bar(frac: float, width: int = 20) -> str:
40
+ """``▕████▌ ▏``: a bar of ``width`` cells with eighth-cell resolution."""
41
+ frac = min(max(frac, 0.0), 1.0)
42
+ eighths = int(round(frac * width * 8))
43
+ full, part = divmod(eighths, 8)
44
+ body = "█" * full + (EIGHTHS[part] if part and full < width else "")
45
+ return "▕" + body.ljust(width) + "▏"
46
+
47
+
48
+ def _rich_available() -> bool:
49
+ try:
50
+ import rich.live # noqa: F401
51
+ return True
52
+ except Exception:
53
+ return False
54
+
55
+
56
+ class Progress:
57
+ """``with Progress(total, "evaluate", unit="clips") as p: ... p.update(1, status="...")``."""
58
+
59
+ def __init__(self, total: Optional[int], desc: str = "", unit: str = "steps", quiet: bool = False,
60
+ stream=None, delay: float = 2.0, log_every: float = 300.0, backend: Optional[str] = None,
61
+ clock=time.monotonic, refresh: float = 0.1):
62
+ self.total, self.desc, self.unit = (int(total) if total is not None else None), desc, unit
63
+ self.stream = stream if stream is not None else sys.stdout
64
+ self.delay, self.log_every, self.clock, self.refresh = delay, log_every, clock, refresh
65
+ self.done, self.status, self.extra = 0, "", ""
66
+ self.t0 = clock()
67
+ self.nested = _ACTIVE[0] > 0
68
+ self.quiet = quiet or self.nested
69
+ tty = bool(getattr(self.stream, "isatty", lambda: False)())
70
+ if backend is None:
71
+ backend = ("rich" if _rich_available() else "plain") if tty else "log"
72
+ self.backend = backend
73
+ self.color = "NO_COLOR" not in os.environ and os.environ.get("TERM") != "dumb"
74
+ self.shown, self.closed, self._frame = False, False, 0
75
+ self._last_log_t, self._last_log_frac = self.t0, 0.0
76
+ self._rich = self._task = None
77
+ self._thread = None
78
+ self._stop = threading.Event()
79
+ if not self.quiet:
80
+ with _LOCK:
81
+ _ACTIVE[0] += 1
82
+ if self.backend in ("plain", "rich"):
83
+ self._thread = threading.Thread(target=self._tick, daemon=True)
84
+ self._thread.start()
85
+
86
+ # ---- public ---------------------------------------------------------------------------
87
+ def update(self, n: int = 1, status: Optional[str] = None, extra: Optional[str] = None) -> None:
88
+ self.done += n
89
+ if status is not None:
90
+ self.status = status
91
+ if extra is not None:
92
+ self.extra = extra
93
+ if self.quiet:
94
+ return
95
+ if self.backend == "log":
96
+ self._maybe_log()
97
+ elif self.backend == "rich" and self._rich is not None:
98
+ self._rich_update()
99
+
100
+ def set_status(self, status: str, extra: Optional[str] = None) -> None:
101
+ self.update(0, status=status, extra=extra)
102
+
103
+ def close(self, summary: Optional[str] = None, force: bool = False) -> None:
104
+ """Remove the live line and print one summary line (if the step was long enough, or ``force``)."""
105
+ if self.closed:
106
+ return
107
+ self.closed = True
108
+ if self.quiet:
109
+ return
110
+ self._stop.set()
111
+ if self._thread is not None:
112
+ self._thread.join(timeout=1.0)
113
+ with _LOCK:
114
+ _ACTIVE[0] -= 1
115
+ elapsed = self.clock() - self.t0
116
+ if summary is None:
117
+ summary = (f"{self.desc}: {self.done}" + (f"/{self.total}" if self.total is not None else "")
118
+ + f" {self.unit} in {fmt_time(elapsed)}" + (f" · {self.extra}" if self.extra else ""))
119
+ long_enough = force or self.shown or elapsed >= self.delay
120
+ if self.backend == "rich":
121
+ if self._rich is not None:
122
+ self._rich.stop()
123
+ if long_enough:
124
+ self._console().print(summary, highlight=False, markup=False)
125
+ elif self.backend == "plain":
126
+ if self.shown:
127
+ self.stream.write("\r\033[K")
128
+ if long_enough:
129
+ self.stream.write(summary + "\n")
130
+ self.stream.flush()
131
+ elif long_enough:
132
+ self.stream.write(summary + "\n")
133
+ self.stream.flush()
134
+
135
+ def __enter__(self):
136
+ return self
137
+
138
+ def __exit__(self, *exc):
139
+ self.close()
140
+ return False
141
+
142
+ # ---- rendering ------------------------------------------------------------------------
143
+ def _frac(self) -> Optional[float]:
144
+ return min(self.done / self.total, 1.0) if self.total else None
145
+
146
+ def _eta(self, elapsed: float) -> Optional[float]:
147
+ if not self.total or self.done <= 0:
148
+ return None
149
+ return elapsed / self.done * max(self.total - self.done, 0)
150
+
151
+ def line(self, width: Optional[int] = None) -> str:
152
+ width = width or shutil.get_terminal_size((100, 20)).columns
153
+ wide = width >= 110 # narrow terminals get a shorter bar and time field
154
+ elapsed = self.clock() - self.t0
155
+ frac = self._frac()
156
+ spin = SPINNER[self._frame % len(SPINNER)]
157
+ parts = [f"{spin} {self.desc}"]
158
+ if frac is not None:
159
+ bar = block_bar(frac, 20 if wide else 12)
160
+ if self.color:
161
+ bar = "\033[36m" + bar + "\033[0m"
162
+ parts.append(f"{bar} {100 * frac:3.0f}% {self.done}/{self.total} {self.unit}")
163
+ else:
164
+ parts.append(f"{self.done} {self.unit}")
165
+ eta = fmt_time(self._eta(elapsed))
166
+ parts.append(f"{fmt_time(elapsed)} elapsed · ETA {eta}" if wide else f"{fmt_time(elapsed)} · ETA {eta}")
167
+ if self.status:
168
+ parts.append(self.status)
169
+ if self.extra:
170
+ parts.append(self.extra)
171
+ text = " · ".join(parts[:1]) + " " + " · ".join(parts[1:])
172
+ return _truncate(text, max(width - 1, 20))
173
+
174
+ def _tick(self) -> None:
175
+ while not self._stop.wait(self.refresh):
176
+ if self.clock() - self.t0 < self.delay:
177
+ continue
178
+ if self.backend == "rich":
179
+ if self._rich is None:
180
+ self._rich_start()
181
+ else:
182
+ self._rich_update()
183
+ continue
184
+ self._frame += 1
185
+ self.shown = True
186
+ try:
187
+ self.stream.write("\r" + self.line() + "\033[K")
188
+ self.stream.flush()
189
+ except Exception:
190
+ return
191
+
192
+ def _maybe_log(self) -> None:
193
+ now = self.clock()
194
+ if now - self._last_log_t < max(self.log_every, self.delay):
195
+ return
196
+ frac = self._frac()
197
+ if frac is not None:
198
+ if frac >= 1.0 or frac < self._last_log_frac + 0.1 - 1e-12:
199
+ return
200
+ self._last_log_frac = math.floor(frac * 10 + 1e-9) / 10
201
+ self._last_log_t = now
202
+ elapsed = now - self.t0
203
+ pct = f" {100 * frac:.0f}%" if frac is not None else ""
204
+ tot = f"/{self.total}" if self.total is not None else ""
205
+ msg = (f"[{self.desc}]{pct} {self.done}{tot} {self.unit} · {fmt_time(elapsed)} elapsed · "
206
+ f"ETA {fmt_time(self._eta(elapsed))}" + (f" · {self.status}" if self.status else "")
207
+ + (f" · {self.extra}" if self.extra else ""))
208
+ self.shown = True
209
+ self.stream.write(msg + "\n")
210
+ self.stream.flush()
211
+
212
+ # ---- rich backend -----------------------------------------------------------------------
213
+ def _console(self):
214
+ from rich.console import Console
215
+ if not hasattr(self, "_con"):
216
+ self._con = Console(file=self.stream, no_color="NO_COLOR" in os.environ)
217
+ return self._con
218
+
219
+ def _rich_start(self) -> None:
220
+ """rich draws the same line through a transient Live display (cursor handling, resize, NO_COLOR)."""
221
+ from rich.live import Live
222
+ from rich.text import Text
223
+ con = self._console()
224
+
225
+ def render():
226
+ self._frame += 1
227
+ return Text.from_ansi(self.line(width=con.width), no_wrap=True, overflow="ellipsis")
228
+ self._rich = Live(get_renderable=render, console=con, transient=True, refresh_per_second=1 / self.refresh)
229
+ self._rich.start()
230
+ self.shown = True
231
+
232
+ def _rich_update(self) -> None:
233
+ pass # Live redraws on its own refresh thread
234
+
235
+
236
+ _ANSI = re.compile(r"\033\[[0-9;]*m")
237
+
238
+
239
+ def _truncate(text: str, width: int) -> str:
240
+ """Cut ``text`` to at most ``width`` visible characters (ANSI color codes do not count)."""
241
+ if len(_ANSI.sub("", text)) <= width:
242
+ return text
243
+ out, vis, pos = [], 0, 0
244
+ for m in _ANSI.finditer(text):
245
+ chunk = text[pos:m.start()]
246
+ take = chunk[:max(width - 1 - vis, 0)]
247
+ out.append(take)
248
+ vis += len(take)
249
+ out.append(m.group())
250
+ pos = m.end()
251
+ tail = text[pos:]
252
+ out.append(tail[:max(width - 1 - vis, 0)])
253
+ return "".join(out) + "…" + ("\033[0m" if _ANSI.search(text) else "")
254
+
255
+
256
+ __all__ = ["Progress", "block_bar", "fmt_time"]
civicbench/attacks.py ADDED
@@ -0,0 +1,220 @@
1
+ """The attacks of the CivicBench protocol, each behind one signature ``run(target, eps, rng) -> Result``.
2
+
3
+ All attacks MINIMIZE the target's score (``Target`` negates it for framing) inside the l_inf ball
4
+ of radius ``eps`` (in [0, 1] units; ``eps = b / 255`` for a budget of ``b`` gray levels), and stop
5
+ at the first REALIZED success: a candidate rounded to 8 bits whose score is below the target's
6
+ threshold.
7
+
8
+ * PGD: 100 steps of size eps / 4 along the sign of the gradient, one restart from the clean clip,
9
+ the realized score checked every 10 steps and after the last step (10 checks).
10
+ * APGD (Croce & Hein, ICML 2020): 100 iterations x 5 restarts, momentum 0.75, step 2 eps halved at
11
+ the checkpoints when progress stalls (rho = 0.75), restart from the best point; the loss is the
12
+ score itself. Restart 0 starts at the clean clip, later restarts uniformly at random in the
13
+ ball. The realized score of the best iterate is checked every 10 iterations (50 checks).
14
+ * Square (Andriushchenko et al., ECCV 2020), video variant: each query sets a square patch of ONE
15
+ random frame to x0 +/- eps (independent sign per channel) and keeps the change if the score
16
+ drops; the patch area follows Square's schedule p(i) with p_init = 0.2. No stripe
17
+ initialization. 1,000 queries per budget.
18
+ * SimBA-DCT (Guo et al., ICML 2019), l_inf variant: walks low-frequency 2-D DCT directions of
19
+ single frames and channels (scaled to max-abs 1, step eps), trying -q then +q and keeping
20
+ improvements. 1,000 queries per budget. Not part of the default set (the protocol uses it only
21
+ for motion-vector detectors).
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import math
26
+ from dataclasses import dataclass, field
27
+ from typing import Optional
28
+
29
+ import numpy as np
30
+
31
+
32
+ @dataclass
33
+ class Result:
34
+ evaded: bool
35
+ score: float # realized score of the returned clip (lowest seen if not successful)
36
+ queries: int # realized queries spent by this run
37
+ x: Optional[object] = None # float clip [T, 3, H, W] (the successful one, else the best seen)
38
+ extra: dict = field(default_factory=dict)
39
+
40
+
41
+ def project(x, x0, eps: float):
42
+ """Project onto the l_inf ball of radius eps around x0, intersected with [0, 1]."""
43
+ return x.clamp(min=x0 - eps, max=x0 + eps).clamp_(0.0, 1.0)
44
+
45
+
46
+ # ---- first order ---------------------------------------------------------------------------
47
+ def _start(target, eps, restart, rng):
48
+ x0 = target.x0
49
+ if restart == 0:
50
+ return x0.clone()
51
+ torch = target._torch
52
+ gen = torch.Generator(device="cpu").manual_seed(int(rng.integers(2**31)))
53
+ u = (torch.rand(tuple(x0.shape), generator=gen) * 2 - 1).to(x0.device) * eps
54
+ return project(x0 + u, x0, eps)
55
+
56
+
57
+ def pgd(target, eps: float, steps: int = 100, restarts: int = 1, step_size: float = None,
58
+ check_every: int = 10, eot: int = 0, eot_sigma: float = 1 / 255, rng=None) -> Result:
59
+ rng = rng or np.random.default_rng(0)
60
+ alpha = step_size if step_size is not None else eps / 4
61
+ q0, best = target.queries, Result(False, math.inf, 0)
62
+ for r in range(restarts):
63
+ x = _start(target, eps, r, rng)
64
+ for i in range(1, steps + 1):
65
+ g = target.grad(x, eot=eot, eot_sigma=eot_sigma, rng=rng)
66
+ x = project(x - alpha * g.sign(), target.x0, eps)
67
+ if i % check_every == 0 or i == steps:
68
+ s = target.score(x)
69
+ if s < best.score:
70
+ best = Result(False, s, 0, x.clone())
71
+ if s < target.tau:
72
+ return Result(True, s, target.queries - q0, x.clone(), {"restart": r, "step": i})
73
+ best.queries = target.queries - q0
74
+ return best
75
+
76
+
77
+ def _checkpoints(steps: int):
78
+ p = [0.0, 0.22]
79
+ while p[-1] < 1:
80
+ p.append(p[-1] + max(p[-1] - p[-2] - 0.03, 0.06))
81
+ return sorted({int(math.ceil(q * steps)) for q in p[1:] if q <= 1})
82
+
83
+
84
+ def apgd(target, eps: float, steps: int = 100, restarts: int = 5, check_every: int = 10,
85
+ eot: int = 0, eot_sigma: float = 1 / 255, rng=None, rho: float = 0.75,
86
+ alpha: float = 0.75) -> Result:
87
+ rng = rng or np.random.default_rng(0)
88
+ torch = target._torch
89
+ x0 = target.x0
90
+ q0, best = target.queries, Result(False, math.inf, 0)
91
+
92
+ def loss(x):
93
+ with torch.no_grad():
94
+ return float(target.differentiable_score(x.unsqueeze(0))[0])
95
+
96
+ checks = _checkpoints(steps)
97
+ for r in range(restarts):
98
+ x_prev = _start(target, eps, r, rng)
99
+ f_prev = loss(x_prev)
100
+ eta = 2 * eps
101
+ x = project(x_prev - eta * target.grad(x_prev, eot, eot_sigma, rng).sign(), x0, eps)
102
+ f_x = loss(x)
103
+ x_best, f_best = (x, f_x) if f_x < f_prev else (x_prev, f_prev)
104
+ last_check, n_improved, eta_at_check, f_best_at_check = 0, int(f_x < f_prev), eta, f_best
105
+ for k in range(1, steps):
106
+ z = project(x - eta * target.grad(x, eot, eot_sigma, rng).sign(), x0, eps)
107
+ x_new = project(x + alpha * (z - x) + (1 - alpha) * (x - x_prev), x0, eps)
108
+ f_new = loss(x_new)
109
+ n_improved += int(f_new < f_x)
110
+ x_prev, x, f_x = x, x_new, f_new
111
+ if f_new < f_best:
112
+ x_best, f_best = x_new.clone(), f_new
113
+ if (k + 1) % check_every == 0 or k == steps - 1:
114
+ s = target.score(x_best)
115
+ if s < best.score:
116
+ best = Result(False, s, 0, x_best.clone())
117
+ if s < target.tau:
118
+ return Result(True, s, target.queries - q0, x_best.clone(), {"restart": r, "step": k + 1})
119
+ if k + 1 in checks:
120
+ window = k + 1 - last_check
121
+ stalled = n_improved < rho * window
122
+ frozen = eta == eta_at_check and f_best == f_best_at_check
123
+ if stalled or frozen:
124
+ eta /= 2
125
+ x = x_best.clone()
126
+ last_check, n_improved, eta_at_check, f_best_at_check = k + 1, 0, eta, f_best
127
+ best.queries = target.queries - q0
128
+ return best
129
+
130
+
131
+ # ---- zeroth order (scores only) ------------------------------------------------------------
132
+ def square_schedule(p_init: float, i: int, n_queries: int) -> float:
133
+ it = int(i / max(n_queries, 1) * 10000)
134
+ for bound, div in ((10, 1), (50, 2), (200, 4), (500, 8), (1000, 16), (2000, 32), (4000, 64),
135
+ (6000, 128), (8000, 256)):
136
+ if it <= bound:
137
+ return p_init / div
138
+ return p_init / 512
139
+
140
+
141
+ def square(target, eps: float, n_queries: int = 1000, p_init: float = 0.2, rng=None) -> Result:
142
+ rng = rng or np.random.default_rng(0)
143
+ torch = target._torch
144
+ x0 = target.x0
145
+ t_len, ch, h, w = x0.shape
146
+ q0 = target.queries
147
+ x_best, s_best = x0.clone(), target.score(x0)
148
+ if s_best < target.tau:
149
+ return Result(True, s_best, target.queries - q0, x_best)
150
+ while target.queries - q0 < n_queries:
151
+ i = target.queries - q0
152
+ side = int(round(math.sqrt(square_schedule(p_init, i, n_queries) * h * w)))
153
+ side = min(max(side, 1), h - 1, w - 1)
154
+ t = int(rng.integers(t_len))
155
+ r, c = int(rng.integers(0, h - side)), int(rng.integers(0, w - side))
156
+ signs = torch.from_numpy(rng.choice([-1.0, 1.0], size=(ch, 1, 1))).to(x0)
157
+ x_new = x_best.clone()
158
+ x_new[t, :, r:r + side, c:c + side] = (x0[t, :, r:r + side, c:c + side] + eps * signs).clamp(0, 1)
159
+ s_new = target.score(x_new)
160
+ if s_new < s_best:
161
+ x_best, s_best = x_new, s_new
162
+ if s_best < target.tau:
163
+ return Result(True, s_best, target.queries - q0, x_best)
164
+ return Result(False, s_best, target.queries - q0, x_best)
165
+
166
+
167
+ def dct_basis(h: int, w: int, u: int, v: int, device=None):
168
+ import torch
169
+ y = torch.arange(h, dtype=torch.float32, device=device)
170
+ x = torch.arange(w, dtype=torch.float32, device=device)
171
+ by = torch.cos(math.pi * (2 * y + 1) * u / (2 * h))
172
+ bx = torch.cos(math.pi * (2 * x + 1) * v / (2 * w))
173
+ return by[:, None] * bx[None, :] # max |.| = 1
174
+
175
+
176
+ def simba_dct(target, eps: float, n_queries: int = 1000, freq_frac: float = 1 / 8, rng=None) -> Result:
177
+ rng = rng or np.random.default_rng(0)
178
+ x0 = target.x0
179
+ t_len, ch, h, w = x0.shape
180
+ nu, nv = max(1, int(h * freq_frac)), max(1, int(w * freq_frac))
181
+ q0 = target.queries
182
+ x, s = x0.clone(), target.score(x0)
183
+ if s < target.tau:
184
+ return Result(True, s, target.queries - q0, x)
185
+ order = rng.permutation(t_len * ch * nu * nv)
186
+ k = 0
187
+ while target.queries - q0 < n_queries:
188
+ idx = int(order[k % len(order)])
189
+ k += 1
190
+ t, rem = divmod(idx, ch * nu * nv)
191
+ c, rem = divmod(rem, nu * nv)
192
+ u, v = divmod(rem, nv)
193
+ q = dct_basis(h, w, u, v, device=x0.device) * eps
194
+ for sgn in (-1.0, 1.0):
195
+ if target.queries - q0 >= n_queries:
196
+ break
197
+ x_try = x.clone()
198
+ x_try[t, c] = x_try[t, c] + sgn * q
199
+ x_try = project(x_try, x0, eps)
200
+ s_try = target.score(x_try)
201
+ if s_try < s:
202
+ x, s = x_try, s_try
203
+ if s < target.tau:
204
+ return Result(True, s, target.queries - q0, x)
205
+ break
206
+ return Result(False, s, target.queries - q0, x)
207
+
208
+
209
+ # ---- the protocol's settings ---------------------------------------------------------------
210
+ FAMILIES = {
211
+ "pgd": lambda target, eps, rng=None: pgd(target, eps, steps=100, restarts=1, rng=rng),
212
+ "apgd": lambda target, eps, rng=None: apgd(target, eps, steps=100, restarts=5, rng=rng),
213
+ "square": lambda target, eps, rng=None: square(target, eps, n_queries=1000, rng=rng),
214
+ "simba": lambda target, eps, rng=None: simba_dct(target, eps, n_queries=1000, rng=rng),
215
+ }
216
+ GRADIENT_ATTACKS = ("pgd", "apgd")
217
+ DEFAULT_ATTACKS = ("pgd", "apgd", "square")
218
+
219
+ __all__ = ["Result", "project", "pgd", "apgd", "square", "square_schedule", "simba_dct", "dct_basis",
220
+ "FAMILIES", "GRADIENT_ATTACKS", "DEFAULT_ATTACKS"]
civicbench/cli.py ADDED
@@ -0,0 +1,95 @@
1
+ """Command line: ``civicbench evaluate --detector module:factory --data PATH_OR_REPO [...]``.
2
+
3
+ ``module:factory`` names a callable that BUILDS the detector: it is imported (the current
4
+ directory is on the import path), called with the keyword arguments of ``--factory-kwargs``
5
+ (JSON), and must return the detector callable (see ``civicbench.attack``).
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import importlib
11
+ import json
12
+ import math
13
+ import os
14
+ import sys
15
+
16
+
17
+ def build_detector(spec: str, kwargs: dict):
18
+ if ":" not in spec:
19
+ raise SystemExit(f"--detector must look like module:factory, got {spec!r}")
20
+ mod_name, attr = spec.split(":", 1)
21
+ if os.getcwd() not in sys.path:
22
+ sys.path.insert(0, os.getcwd())
23
+ obj = importlib.import_module(mod_name)
24
+ for part in attr.split("."):
25
+ obj = getattr(obj, part)
26
+ det = obj(**kwargs)
27
+ if not callable(det):
28
+ raise SystemExit(f"{spec} returned {type(det).__name__}, which is not callable")
29
+ if hasattr(det, "eval") and callable(det.eval):
30
+ det.eval()
31
+ return det
32
+
33
+
34
+ def _ints(s: str):
35
+ try:
36
+ return tuple(int(x) for x in s.split(",") if x.strip())
37
+ except ValueError:
38
+ raise argparse.ArgumentTypeError(f"expected comma-separated integers, got {s!r}") from None
39
+
40
+
41
+ def _jsonable(o):
42
+ if isinstance(o, dict):
43
+ return {str(k): _jsonable(v) for k, v in o.items()}
44
+ if isinstance(o, (list, tuple)):
45
+ return [_jsonable(v) for v in o]
46
+ if isinstance(o, float) and not math.isfinite(o):
47
+ return None
48
+ if hasattr(o, "item") and not isinstance(o, (str, bytes)):
49
+ return _jsonable(o.item())
50
+ return o
51
+
52
+
53
+ def main(argv=None) -> int:
54
+ import civicbench
55
+ p = argparse.ArgumentParser(prog="civicbench", description="Evaluate a video detector on CivicBench.")
56
+ p.add_argument("--version", action="version", version=f"civicbench {civicbench.__version__}")
57
+ sub = p.add_subparsers(dest="cmd", required=True)
58
+ e = sub.add_parser("evaluate", help="clean AUC/TPR and attacked rates (the paper's CivicBench table)")
59
+ e.add_argument("--detector", required=True, help="module:factory returning the detector callable")
60
+ e.add_argument("--factory-kwargs", default="{}", help="JSON keyword arguments for the factory")
61
+ e.add_argument("--data", nargs="+", default=None,
62
+ help="Hugging Face repo id(s) or local parquet directories/files (real and generated)")
63
+ e.add_argument("--split", default="test")
64
+ e.add_argument("--limit", type=int, default=None, help="read at most this many clips (per run, for smoke tests)")
65
+ e.add_argument("--fpr", type=float, default=0.05)
66
+ e.add_argument("--strict-fpr", type=float, default=0.01, help="threshold framing attacks aim at")
67
+ e.add_argument("--budgets", type=_ints, default=(1, 2, 4), help="gray levels, e.g. 1,2,4,8,16 (default 1,2,4)")
68
+ e.add_argument("--attacks", default="pgd,apgd,square", help="comma list from: " + ",".join(civicbench.FAMILIES))
69
+ e.add_argument("--n-evasion", type=int, default=None)
70
+ e.add_argument("--n-framing", type=int, default=None)
71
+ e.add_argument("--evasion-per-generator", type=int, default=None)
72
+ e.add_argument("--seed", type=int, default=None, help="default: the paper's per-clip seeds")
73
+ e.add_argument("--survival-budget", type=int, default=None)
74
+ e.add_argument("--survival-probe", type=int, default=None)
75
+ e.add_argument("--device", default=None)
76
+ e.add_argument("--no-verify", action="store_true", help="skip the frames_sha256 check")
77
+ e.add_argument("--out", default=None, help="write the full result (per-clip records included) as JSON")
78
+ e.add_argument("--quiet", action="store_true", help="no progress line and no summary table")
79
+ a = p.parse_args(argv)
80
+
81
+ det = build_detector(a.detector, json.loads(a.factory_kwargs))
82
+ clips = civicbench.load(a.data, split=a.split, limit=a.limit, verify=not a.no_verify, quiet=a.quiet)
83
+ res = civicbench.evaluate(det, clips, fpr=a.fpr, strict_fpr=a.strict_fpr, budgets=a.budgets,
84
+ attacks=tuple(x for x in a.attacks.split(",") if x), n_evasion=a.n_evasion,
85
+ n_framing=a.n_framing, evasion_per_generator=a.evasion_per_generator, seed=a.seed,
86
+ device=a.device, survival_budget=a.survival_budget, survival_probe=a.survival_probe,
87
+ quiet=a.quiet)
88
+ if a.out:
89
+ with open(a.out, "w") as f:
90
+ json.dump(_jsonable(res), f, indent=1)
91
+ return 0
92
+
93
+
94
+ if __name__ == "__main__":
95
+ sys.exit(main())