persado-benchmark 0.7.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.
@@ -0,0 +1,3 @@
1
+ """persado-benchmark: test a marketing-performance predictor on your own A/B tests, blind."""
2
+
3
+ __version__ = "0.7.0"
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,458 @@
1
+ """Command line: persado-benchmark run | predict | evaluate | inspect | prompt | template | sources | demo"""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ import sys
7
+ from datetime import datetime, timezone
8
+ from pathlib import Path
9
+ from typing import Optional
10
+
11
+ from . import __version__, demo as demo_mod, harness, output, report, scorers as sc
12
+ from .data import METRICS, SOURCES, DataError, Dataset, load
13
+
14
+
15
+ def _data_args(p):
16
+ p.add_argument("file", help="your A/B tests: .csv, .tsv, .json, .jsonl, or the "
17
+ "Persado model-evaluation workbook (.xlsx)")
18
+ p.add_argument("--source", default="generic", choices=list(SOURCES),
19
+ help="optional: column names of a specific platform's export. "
20
+ "The default reads a file from any tool")
21
+ p.add_argument("--sheet", help="sheet to read from an .xlsx file")
22
+ p.add_argument("--metric", default="click", choices=list(METRICS),
23
+ help="outcome that defines the winner (default: click)")
24
+ p.add_argument("--map", action="append", default=[], metavar="FIELD=COLUMN",
25
+ help="override a column, e.g. --map experiment=\"Test Name\"")
26
+ p.add_argument("--min-trials", type=float, default=0, metavar="N",
27
+ help="set aside tests where a variant had fewer than N deliveries")
28
+ p.add_argument("--channel", help="channel for all rows if the file has no channel column")
29
+ p.add_argument("--industry",
30
+ help="industry for all rows if the file has no such column. It changes "
31
+ "Persado's score, so give the industry the copy was written for")
32
+ p.add_argument("--account", metavar="BRAND",
33
+ help="brand name for all rows if the file has no account column; "
34
+ "Persado's API requires one. It changes the score only for a "
35
+ "brand Persado already works with, so use the real name")
36
+ p.add_argument("--country", metavar="CODE",
37
+ help="country the copy ran in, as a two-letter code, for all rows if "
38
+ "the file has no country column (default: US)")
39
+ p.add_argument("--language", metavar="CODE",
40
+ help="language of the copy, as a two-letter code, for all rows if the "
41
+ "file has no language column (default: en for US; for another "
42
+ "country, Persado uses that country's language)")
43
+ p.add_argument("--limit", type=int, help="only use the first N experiments")
44
+
45
+
46
+ def _score_args(p):
47
+ p.add_argument("--scorer", default="persado", metavar="SPEC",
48
+ help="model under test (default: persado). Specs: persado, "
49
+ "column:<header>, py:<module-or-file>:<func>, cmd:<command>, "
50
+ "llm:<model>, reply:<file>, workbook, length, random")
51
+ p.add_argument("--baseline", action="append", default=[], metavar="NAME=SPEC",
52
+ help="model to compare against, e.g. --baseline internal=column:model_score")
53
+ p.add_argument("--runs", type=int, default=5,
54
+ help="score each test N times to measure ranking stability (default: 5)")
55
+ p.add_argument("--llm-prompt", metavar="FILE",
56
+ help="use your own prompt template for llm: baselines")
57
+ p.add_argument("--concurrency", type=int, default=1,
58
+ help="calls to Persado in flight at once (default: 1); the "
59
+ "key's rate limit sets the pace, so more rarely helps")
60
+ p.add_argument("--cache-dir", default=".persado-benchmark/cache")
61
+ p.add_argument("--no-cache", action="store_true")
62
+
63
+
64
+ def _eval_args(p):
65
+ p.add_argument("--top-k", type=int, default=2)
66
+ p.add_argument("--alpha", type=float, default=0.05,
67
+ help="significance level for the 'decisive tests' subset")
68
+ p.add_argument("--bootstrap", type=int, default=1000, help="bootstrap resamples")
69
+ p.add_argument("--seed", type=int, default=7)
70
+
71
+
72
+ def _out_arg(p):
73
+ p.add_argument("--out", help="output directory (default: runs/<timestamp>)")
74
+
75
+
76
+ def _out_dir(args) -> Path:
77
+ return Path(args.out or Path("runs") / datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S"))
78
+
79
+
80
+ def _load(args, need_outcomes=True) -> Dataset:
81
+ overrides = {}
82
+ for item in args.map:
83
+ f, sep, col = item.partition("=")
84
+ if not sep:
85
+ raise DataError(f"--map expects FIELD=COLUMN, got '{item}'")
86
+ overrides[f.strip()] = col.strip()
87
+ return load(args.file, args.source, args.metric, overrides, args.min_trials,
88
+ need_outcomes, args.channel, args.industry,
89
+ getattr(args, "account", None), args.limit, args.sheet,
90
+ default_country=getattr(args, "country", None),
91
+ default_language=getattr(args, "language", None))
92
+
93
+
94
+ def _no_experiments(ds: Dataset):
95
+ lines = [f"No usable A/B tests found in {ds.rows_read:,} rows."]
96
+ lines += [f" {n:,} × {reason}" for reason, n in ds.set_aside.items()]
97
+ lines.append("Run `persado-benchmark inspect <file>` to see how columns were matched.")
98
+ raise DataError("\n".join(lines))
99
+
100
+
101
+ def _build_scorers(args, ds: Dataset):
102
+ cache = None if args.no_cache else args.cache_dir
103
+ template = Path(args.llm_prompt).read_text(encoding="utf-8") if args.llm_prompt else None
104
+ kw = dict(channel=args.channel, industry=args.industry, account=args.account,
105
+ country=args.country, language=args.language,
106
+ cache_dir=cache, seed=args.seed, llm_prompt=template)
107
+ out = [sc.build(args.scorer, ds, **kw)]
108
+ for item in args.baseline:
109
+ name, sep, spec = item.partition("=")
110
+ if not sep or ":" in name:
111
+ name, spec = None, item
112
+ out.append(sc.build(spec, ds, name=name, **kw))
113
+ names = [s.name for s in out]
114
+ if len(set(names)) != len(names):
115
+ raise sc.ScorerError(f"Scorer names must be unique: {names}. Use NAME=SPEC.")
116
+ _require_brand(ds, out)
117
+ return out
118
+
119
+
120
+ def _concurrency(args) -> Optional[int]:
121
+ """Calls in flight at once, as the run actually paced them.
122
+
123
+ Only scorers that go over the network are paced, so a run with none
124
+ records nothing: there was no pacing to describe. A networked run records
125
+ its pacing even at one call at a time, which it used to leave out. When a
126
+ rate limit is what failed a run, this is the first thing to look at.
127
+ """
128
+ used = getattr(args, "workers_used", {})
129
+ return max(used.values()) if getattr(args, "network", False) and used else None
130
+
131
+
132
+ def _meta(ds: Dataset, lock, failures, runs, args=None, **extra) -> dict:
133
+ meta = {"source": SOURCES[ds.source]["label"], "metric": METRICS[ds.metric][0],
134
+ "accounts": ds.accounts,
135
+ "lock": lock, "set_aside": dict(ds.set_aside), "runs": runs if runs > 1 else None,
136
+ "concurrency": _concurrency(args) if args is not None else None,
137
+ "rate_limited": _rate_limited(args) if args is not None else None,
138
+ "failures": {n: (len(f), next(iter(f.values()))[:300])
139
+ for n, f in failures.items() if f}}
140
+ meta.update(extra)
141
+ return meta
142
+
143
+
144
+ def _finish(result, meta, out: Path):
145
+ text = report.render(result, meta)
146
+ (out / "results.json").write_text(json.dumps({"meta": meta, "result": result}, indent=2))
147
+ (out / "report.md").write_text(report.render(result, meta, markdown=True))
148
+ print(text)
149
+ print(f"Saved: {out}/report.md, results.json, predictions.jsonl, lock.json")
150
+
151
+
152
+ def _require_brand(ds: Dataset, scorer_list):
153
+ """Refuse, before any call, a Persado run with tests that have no brand.
154
+
155
+ The API needs account.name for every request. Left to the scorer, each such
156
+ test failed on its own: a small file ran to an empty report and exit 0,
157
+ and a file with some blank account cells quietly lost those tests from the
158
+ headline, mentioned only under scorer errors. A missing brand is a problem
159
+ with the input, so it is reported as one, up front, with the tests named.
160
+ """
161
+ for s in scorer_list:
162
+ inner = getattr(s, "inner", s)
163
+ if not isinstance(inner, sc.PersadoScorer) or inner.account:
164
+ continue
165
+ missing = [e.id for e in ds.experiments if not e.account]
166
+ if not missing:
167
+ continue
168
+ shown = ", ".join(missing[:5]) + (" …" if len(missing) > 5 else "")
169
+ where = ("their account cell is blank" if "account" in ds.mapping
170
+ else "the file has no account column")
171
+ raise DataError(
172
+ f"{len(missing):,} of {len(ds.experiments):,} tests have no brand "
173
+ f"({where}): {shown}\n"
174
+ f"Persado's API refuses a request without account.name. Pass --account "
175
+ f"\"Brand\" for the whole file (it fills blank cells too), or fill the "
176
+ f"account column.")
177
+
178
+
179
+ def _rate_limited(args) -> Optional[dict]:
180
+ """How often the API said rate_limited during scoring, and the time it cost.
181
+
182
+ Recorded beside the concurrency because the two answer one question: was
183
+ the run paced right for the key? A run with no network scorer has no
184
+ pacing, and records nothing.
185
+ """
186
+ return getattr(args, "rate_limited", None) if getattr(args, "network", False) else None
187
+
188
+
189
+ def _score_and_lock(ds: Dataset, scorer_list, args, out: Path, extra: dict):
190
+ args.workers_used = {}
191
+ args.network = any(getattr(s, "inner", s).cacheable for s in scorer_list)
192
+ sc.RATE_LIMIT.reset()
193
+ try:
194
+ preds, failures = harness.score_all(ds.experiments, scorer_list, args.runs,
195
+ args.concurrency,
196
+ workers_used=args.workers_used)
197
+ except sc.QuotaExhausted as e:
198
+ cached = not getattr(args, "no_cache", True)
199
+ tail = ("Scores already received are cached, so a rerun with a key that has "
200
+ "run units left does not pay for them again." if cached else
201
+ "Nothing was cached (--no-cache), so a rerun pays for every test again.")
202
+ raise sc.QuotaExhausted(f"{e} {tail}") from None
203
+ finally:
204
+ # Printed even when scoring fails: a run stopped by the quota or the
205
+ # rate limit is exactly the one whose pacing needs explaining.
206
+ args.rate_limited = sc.RATE_LIMIT.stats()
207
+ if args.rate_limited["responses"]:
208
+ print(f"Rate limited {report.times(args.rate_limited['responses'])}; "
209
+ f"the run paused {args.rate_limited['paused_seconds']:g}s in all "
210
+ f"at {report.calls_at_a_time(args.concurrency)}.", file=sys.stderr)
211
+ scored_as = {s.name: s.scored_as(ds.experiments) for s in scorer_list}
212
+ scored_as = {n: c for n, c in scored_as.items() if c}
213
+ if scored_as:
214
+ extra = {**extra, "scored_as": scored_as}
215
+ lock = harness.write_predictions(out, ds.experiments, preds, extra)
216
+ from_file = {s.name for s in scorer_list
217
+ if isinstance(getattr(s, "inner", s), (sc.ColumnScorer, sc.WorkbookScorer))}
218
+ _write_scored(ds, {n: p for n, p in preds.items() if n not in from_file}, out)
219
+ return preds, failures, lock
220
+
221
+
222
+ def _write_scored(ds: Dataset, preds, out: Path):
223
+ """The input file again, with each scorer's score beside each message.
224
+
225
+ Written after the lock, and a convenience only: a copy that cannot be
226
+ written is reported, and the locked predictions stand. Scores that came
227
+ from the file itself are not written back, so a run with only those
228
+ writes no copy.
229
+ """
230
+ if not preds:
231
+ return
232
+ try:
233
+ path, what = output.write_scored(ds, preds, out)
234
+ except Exception as e: # a convenience copy must not sink a locked run
235
+ print(f"warning: could not write the scored copy of {ds.path.name}: {e}",
236
+ file=sys.stderr)
237
+ return
238
+ print(f"Scored copy: {path} ({what})", file=sys.stderr)
239
+
240
+
241
+ def _evaluate(ds_ids, outcomes, preds, args):
242
+ return harness.evaluate(ds_ids, outcomes, preds, args.top_k, args.alpha,
243
+ args.bootstrap, args.seed)
244
+
245
+
246
+ def cmd_run(args):
247
+ ds = _load(args)
248
+ if not ds.experiments:
249
+ _no_experiments(ds)
250
+ sealed = harness.SealedOutcomes(ds.outcomes)
251
+ ds.outcomes = {} # from here on, results exist only inside `sealed`
252
+ scorer_list = _build_scorers(args, ds)
253
+ out = _out_dir(args)
254
+ print(f"Scoring {len(ds.experiments):,} experiments blind "
255
+ f"({ds.n_variants:,} variants)…", file=sys.stderr)
256
+ preds, failures, lock = _score_and_lock(
257
+ ds, scorer_list, args, out, {"mode": "run", "outcomes_sha256": sealed.sha256})
258
+ outcomes = sealed.reveal(lock)
259
+ result = _evaluate({e.id: [v.id for v in e.variants] for e in ds.experiments},
260
+ outcomes, preds, args)
261
+ _finish(result, _meta(ds, lock, failures, args.runs, args), out)
262
+
263
+
264
+ def cmd_predict(args):
265
+ ds = _load(args, need_outcomes=False)
266
+ if not ds.experiments:
267
+ _no_experiments(ds)
268
+ leaked = [ds.mapping[f] for f in ("successes", "rate") if f in ds.mapping]
269
+ if leaked:
270
+ print(f"note: this file still has outcome columns ({', '.join(leaked)}). They are "
271
+ f"never sent to a scorer, but for a strict blind test delete them first.",
272
+ file=sys.stderr)
273
+ scorer_list = _build_scorers(args, ds)
274
+ out = _out_dir(args)
275
+ preds, failures, lock = _score_and_lock(ds, scorer_list, args, out, {"mode": "predict"})
276
+ for name, f in failures.items():
277
+ if f:
278
+ print(f"warning: {name} failed on {len(f):,} experiments", file=sys.stderr)
279
+ print(f"Locked predictions for {len(ds.experiments):,} experiments "
280
+ f"(sha256 {lock['predictions_sha256'][:12]}…) in {out}")
281
+ print(f"Next: persado-benchmark evaluate {out} <file-with-outcomes>")
282
+
283
+
284
+ def cmd_evaluate(args):
285
+ lock, preds, variant_ids = harness.read_predictions(args.run_dir)
286
+ ds = _load(args)
287
+ result = _evaluate(variant_ids, ds.outcomes, preds, args)
288
+ if result["experiments"] == 0:
289
+ raise DataError("None of the predicted experiments could be matched to outcomes. "
290
+ "Use the same --source / --map options as for `predict`.")
291
+ _finish(result, _meta(ds, lock, {}, 1), Path(args.run_dir))
292
+
293
+
294
+ def cmd_inspect(args):
295
+ ds = _load(args, need_outcomes=False)
296
+ print(f"File: {args.file} ({ds.rows_read:,} rows, {ds.layout} layout)")
297
+ print(f"Source: {SOURCES[ds.source]['label']}")
298
+ print("Columns matched:")
299
+ for f, col in ds.mapping.items():
300
+ shown = {"__row": "(row number)", "__variant": "(column suffix)"}.get(
301
+ col, col.replace("__", "wide: "))
302
+ print(f" {f:<11} ← {shown}")
303
+ has = "successes" in ds.mapping and ("delivered" in ds.mapping or "sent" in ds.mapping)
304
+ if has:
305
+ print(f"Outcome: {METRICS[ds.metric][0]} from counts (significance test available)")
306
+ elif "rate" in ds.mapping:
307
+ print(f"Outcome: {METRICS[ds.metric][0]} from a rate column (no counts, so no "
308
+ f"'decisive tests' subset)")
309
+ else:
310
+ print("Outcome: none found - fine for `predict`, required for `run` and `evaluate`")
311
+ print(f"A/B tests found: {len(ds.experiments):,} ({ds.n_variants:,} variants) "
312
+ f"out of {ds.groups_seen:,} groups")
313
+ for reason, n in ds.set_aside.items():
314
+ print(f" set aside: {n:,} × {reason}")
315
+ if has or "rate" in ds.mapping:
316
+ full = _load(args)
317
+ print(f"With outcomes applied: {len(full.experiments):,} qualifying tests")
318
+ for reason, n in full.set_aside.items():
319
+ if reason not in ds.set_aside:
320
+ print(f" set aside: {n:,} × {reason}")
321
+ for e in ds.experiments[:2]:
322
+ print(f"\nExample - what a scorer sees for '{e.id}':")
323
+ for v in e.variants:
324
+ print(f" [{v.id}] {v.text[:90]}")
325
+
326
+
327
+ def cmd_sources(args):
328
+ for key, s in SOURCES.items():
329
+ print(f"{key:<11} {s['label']}\n{'':<11} {s['export']}\n")
330
+ print("The platform presets are conveniences. Messages from any tool work with the "
331
+ "default,\nand --map FIELD=COLUMN handles any other column names.")
332
+
333
+
334
+ TEMPLATE_ROWS = [
335
+ ["campaign", "message", "unique_clicks", "delivered"],
336
+ ["Spring sale reminder", "Your spring picks are 20% off until Sunday", "", ""],
337
+ ["Spring sale reminder", "Last call: 20% off ends Sunday", "", ""],
338
+ ["Welcome email", "Welcome! Here is what to do first", "", ""],
339
+ ["Welcome email", "You're in. Start with these three things", "", ""],
340
+ ]
341
+
342
+
343
+ def cmd_template(args):
344
+ import csv
345
+ path = Path(args.out or "ab_tests.csv")
346
+ if path.exists():
347
+ raise DataError(f"{path} already exists.")
348
+ with path.open("w", newline="", encoding="utf-8") as f:
349
+ csv.writer(f).writerows(TEMPLATE_ROWS)
350
+ print(f"Wrote {path}. Replace the example rows with your own A/B tests:\n"
351
+ " campaign same name on every message of one test\n"
352
+ " message the text that was sent\n"
353
+ " unique_clicks result per message (or conversions with --metric conversion)\n"
354
+ " delivered messages delivered, or impressions\n"
355
+ "About 50 tests is a good starting set. Then: persado-benchmark run " + str(path))
356
+
357
+
358
+ def cmd_prompt(args):
359
+ from . import prompts
360
+ ds = _load(args, need_outcomes=False)
361
+ if not ds.experiments:
362
+ _no_experiments(ds)
363
+ template = (Path(args.llm_prompt).read_text(encoding="utf-8")
364
+ if args.llm_prompt else prompts.TEMPLATE)
365
+ out = Path(args.out or "llm_prompts")
366
+ out.mkdir(parents=True, exist_ok=True)
367
+ batches = [ds.experiments[i:i + args.batch]
368
+ for i in range(0, len(ds.experiments), args.batch)]
369
+ for i, batch in enumerate(batches, 1):
370
+ (out / f"prompt_{i:02d}.txt").write_text(
371
+ prompts.render_batch(batch, ds.metric, template), encoding="utf-8")
372
+ print(f"Wrote {len(batches)} prompt file(s) to {out}/ covering "
373
+ f"{len(ds.experiments):,} tests. They contain messages only, no results.\n"
374
+ f"1. Paste each prompt into a new chat with the assistant you want to compare.\n"
375
+ f"2. Save all replies into one text file, e.g. {out}/replies.txt\n"
376
+ f"3. persado-benchmark run {args.file} --baseline LLM=reply:{out}/replies.txt\n"
377
+ f"For ranking stability, repeat steps 1-2 in fresh chats and pass the files "
378
+ f"comma separated.")
379
+
380
+
381
+ def cmd_demo(args):
382
+ out = _out_dir(args)
383
+ csv_path = out / "demo_klaviyo_style_export.csv"
384
+ quality = demo_mod.generate(csv_path, args.tests, args.seed)
385
+ ds = load(csv_path, "klaviyo", "click")
386
+ sealed = harness.SealedOutcomes(ds.outcomes)
387
+ ds.outcomes = {}
388
+ scorer_list = [demo_mod.SimulatedScorer("simulated-strong", quality, 0.12, 1),
389
+ demo_mod.SimulatedScorer("simulated-weak", quality, 0.60, 2),
390
+ sc.LengthScorer()]
391
+ args.runs, args.concurrency = 1, 1
392
+ ds.experiments = ds.experiments[:args.tests]
393
+ preds, failures, lock = _score_and_lock(
394
+ ds, scorer_list, args, out, {"mode": "demo", "outcomes_sha256": sealed.sha256})
395
+ result = _evaluate({e.id: [v.id for v in e.variants] for e in ds.experiments},
396
+ sealed.reveal(lock), preds, args)
397
+ _finish(result, _meta(
398
+ ds, lock, failures, 1, args, title="BENCHMARK DEMO (SYNTHETIC DATA)",
399
+ banner="Simulated A/B tests and simulated scorers. These numbers show how the "
400
+ "harness works;\nthey are not results for Persado or any real model."), out)
401
+ print(f"Sample export to copy the format from: {csv_path}")
402
+
403
+
404
+ def main(argv=None) -> int:
405
+ ap = argparse.ArgumentParser(
406
+ prog="persado-benchmark",
407
+ description="Test a marketing-performance predictor on your own A/B tests, blind.")
408
+ ap.add_argument("--version", action="version", version=__version__)
409
+ sub = ap.add_subparsers(dest="cmd", required=True)
410
+
411
+ p = sub.add_parser("run", help="score blind, lock, reveal outcomes, report")
412
+ _data_args(p); _score_args(p); _eval_args(p); _out_arg(p)
413
+ p.set_defaults(fn=cmd_run)
414
+
415
+ p = sub.add_parser("predict", help="step 1 of 2: score a file that has no outcomes in it")
416
+ _data_args(p); _score_args(p); _out_arg(p)
417
+ p.add_argument("--seed", type=int, default=7)
418
+ p.set_defaults(fn=cmd_predict)
419
+
420
+ p = sub.add_parser("evaluate", help="step 2 of 2: compare locked predictions to outcomes")
421
+ p.add_argument("run_dir", help="directory written by `predict`")
422
+ _data_args(p); _eval_args(p)
423
+ p.set_defaults(fn=cmd_evaluate)
424
+
425
+ p = sub.add_parser("inspect", help="show how a file is read; calls no API")
426
+ _data_args(p)
427
+ p.set_defaults(fn=cmd_inspect)
428
+
429
+ p = sub.add_parser("prompt", help="write paste-ready prompts to test a chat LLM, no API")
430
+ _data_args(p)
431
+ p.add_argument("--batch", type=int, default=10, help="tests per prompt (default: 10)")
432
+ p.add_argument("--llm-prompt", metavar="FILE", help="use your own prompt template")
433
+ p.add_argument("--out", help="output directory (default: llm_prompts)")
434
+ p.set_defaults(fn=cmd_prompt)
435
+
436
+ p = sub.add_parser("template", help="write a blank CSV to fill in from any tool")
437
+ p.add_argument("--out", help="file to write (default: ab_tests.csv)")
438
+ p.set_defaults(fn=cmd_template)
439
+
440
+ p = sub.add_parser("sources", help="list optional platform presets")
441
+ p.set_defaults(fn=cmd_sources)
442
+
443
+ p = sub.add_parser("demo", help="run on synthetic data, no API key needed")
444
+ p.add_argument("--tests", type=int, default=50)
445
+ _eval_args(p); _out_arg(p)
446
+ p.set_defaults(fn=cmd_demo)
447
+
448
+ args = ap.parse_args(argv)
449
+ try:
450
+ args.fn(args)
451
+ except (DataError, sc.ScorerError, harness.ProtocolError) as e:
452
+ print(f"error: {e}", file=sys.stderr)
453
+ return 2
454
+ return 0
455
+
456
+
457
+ if __name__ == "__main__":
458
+ raise SystemExit(main())