pairsort 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.
pairsort/__init__.py ADDED
@@ -0,0 +1,57 @@
1
+ """pairsort — rank anything with AI judges.
2
+
3
+ import pairsort
4
+ result = pairsort.sort(["idea one", "idea two", "idea three"], "Which idea has more impact?")
5
+ result.sorted # best first
6
+ pairsort.compare("draft A", "draft B", "Which is clearer?") # -> P(A is better)
7
+ pairsort.sorter().by("Which is clearer?").judge("llm").budget(60).meta().sort(items) # builder
8
+
9
+ PKPD pairwise sorting on Jev-style judges.
10
+
11
+ Sort anything by asking a calibrated judge many small pairwise questions
12
+ ("which of A or B has stronger evidence?"), coupling the pairwise posteriors
13
+ into global posteriors (Price–Knerr–Personnaz–Dreyfus 1994, Eq. 7, or
14
+ Bradley–Terry), and blending several dimensions — optionally with the judge
15
+ itself as meta-judge and referee.
16
+ """
17
+
18
+ from .api import FunctionJudge, Sorter, as_dimensions, as_items, as_judge, compare, sort, sorter
19
+ from .backends import Choice, JudgeBackend, make_backend
20
+ from .blend import LinearBlend
21
+ from .calibrate import Profile, apply_temperature, ece, fit_temperature
22
+ from .couple import Coupled, bradley_terry, couple, pkpd
23
+ from .pairwise import PairwiseMatrix, clip, symmetrize
24
+ from .sorter import PAPER_DIMENSIONS, Dimension, Item, PairSorter, SortResult
25
+
26
+ __version__ = "0.1.0"
27
+
28
+ __all__ = [
29
+ "sort",
30
+ "compare",
31
+ "sorter",
32
+ "Sorter",
33
+ "FunctionJudge",
34
+ "as_dimensions",
35
+ "as_items",
36
+ "as_judge",
37
+ "Choice",
38
+ "JudgeBackend",
39
+ "make_backend",
40
+ "LinearBlend",
41
+ "Profile",
42
+ "apply_temperature",
43
+ "ece",
44
+ "fit_temperature",
45
+ "Coupled",
46
+ "bradley_terry",
47
+ "couple",
48
+ "pkpd",
49
+ "PairwiseMatrix",
50
+ "clip",
51
+ "symmetrize",
52
+ "PAPER_DIMENSIONS",
53
+ "Dimension",
54
+ "Item",
55
+ "PairSorter",
56
+ "SortResult",
57
+ ]
pairsort/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
pairsort/agreement.py ADDED
@@ -0,0 +1,312 @@
1
+ """Human-vs-judge agreement from pairwise ballots.
2
+
3
+ Visitors of the Summary Showdown site judge pairs of summaries themselves
4
+ (A / B / skip on one dimension at a time). Their ballots come back as JSON —
5
+ attached to a GitHub issue created from the ``human-ballot`` template, or as
6
+ files — and this module turns them into the **human-agreement graph**:
7
+
8
+ * per-judge **agreement rate** with humans (with a 95% Wilson interval),
9
+ * per-judge **Cohen's kappa** (agreement corrected for chance and for a
10
+ judge's or voter's tendency to favour one slot),
11
+ * **rank correlation** (Kendall tau, Spearman) between the Bradley–Terry
12
+ ranking fit to *human* votes and each judge's ranking,
13
+ * the same, judge-vs-judge, as a baseline.
14
+
15
+ A judge's pick on any pair is read from its coupled ranking:
16
+ ``P(a beats b) = sigmoid(log_strength[a] - log_strength[b])`` — so a judge
17
+ "votes" on every pair a human saw, even pairs it never compared directly.
18
+
19
+ Ballot format (``v`` = 1)::
20
+
21
+ {"v": 1, "ballot_id": "...", "created": "2026-09-22T...Z", "site_version": "...",
22
+ "votes": [{"a": "S1A2B3", "b": "S4C5D6", "dim": "accuracy", "pick": "A", "ms": 5120}, ...]}
23
+
24
+ ``pick`` is ``"A"`` (the summary shown first/left), ``"B"`` or ``"skip"``.
25
+
26
+ CLI::
27
+
28
+ pairsort agreement --judges docs/data/showdown.json --github ericflo/pairsort \\
29
+ --out docs/data/agreement.json
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import glob
35
+ import json
36
+ import math
37
+ import re
38
+ import subprocess
39
+ from dataclasses import dataclass
40
+ from pathlib import Path
41
+
42
+ import numpy as np
43
+
44
+ from .couple import bradley_terry
45
+ from .metrics import kendall_tau, spearman
46
+ from .pairwise import PairwiseMatrix
47
+
48
+ _JSON_BLOCK = re.compile(r"```(?:json)?\s*(\{.*?\})\s*```", re.S)
49
+
50
+
51
+ # ----------------------------------------------------------------------------
52
+ # ballots
53
+
54
+
55
+ @dataclass
56
+ class Vote:
57
+ ballot: str
58
+ a: str
59
+ b: str
60
+ dim: str
61
+ a_wins: bool
62
+
63
+
64
+ def parse_ballot(text: str) -> dict | None:
65
+ """Parse a ballot from raw JSON or from a markdown body with a ```json block."""
66
+ text = text.strip()
67
+ for cand in [text] + [m.group(1) for m in _JSON_BLOCK.finditer(text)]:
68
+ try:
69
+ obj = json.loads(cand)
70
+ except (ValueError, TypeError):
71
+ continue
72
+ if isinstance(obj, dict) and isinstance(obj.get("votes"), list):
73
+ return obj
74
+ return None
75
+
76
+
77
+ def ballots_from_files(patterns) -> list[dict]:
78
+ out = []
79
+ for pat in patterns:
80
+ for path in sorted(glob.glob(pat)):
81
+ b = parse_ballot(Path(path).read_text())
82
+ if b:
83
+ b.setdefault("ballot_id", Path(path).stem)
84
+ out.append(b)
85
+ return out
86
+
87
+
88
+ def ballots_from_github(repo: str, label: str = "human-ballot", limit: int = 1000) -> list[dict]:
89
+ """Read ballots from issues with ``label`` (open or closed) using the gh CLI."""
90
+ raw = subprocess.run(
91
+ ["gh", "issue", "list", "--repo", repo, "--label", label, "--state", "all", "--limit", str(limit),
92
+ "--json", "number,body,author,createdAt"],
93
+ check=True, capture_output=True, text=True,
94
+ ).stdout
95
+ out = []
96
+ for issue in json.loads(raw):
97
+ b = parse_ballot(issue.get("body") or "")
98
+ if b:
99
+ b.setdefault("ballot_id", f"issue-{issue['number']}")
100
+ b["source"] = f"{repo}#{issue['number']}"
101
+ out.append(b)
102
+ return out
103
+
104
+
105
+ def votes_from_ballots(ballots: list[dict], valid_ids: set[str] | None = None, dims: set[str] | None = None) -> list[Vote]:
106
+ """Flatten ballots into decisive votes; drops skips, unknown ids and duplicate ballots."""
107
+ seen, out = set(), []
108
+ for b in ballots:
109
+ bid = str(b.get("ballot_id") or id(b))
110
+ if bid in seen:
111
+ continue
112
+ seen.add(bid)
113
+ for v in b.get("votes", []):
114
+ pick = str(v.get("pick", "")).upper()
115
+ if pick not in ("A", "B"):
116
+ continue
117
+ a, bb, d = str(v.get("a")), str(v.get("b")), str(v.get("dim"))
118
+ if a == bb or (valid_ids and (a not in valid_ids or bb not in valid_ids)) or (dims and d not in dims):
119
+ continue
120
+ out.append(Vote(bid, a, bb, d, pick == "A"))
121
+ return out
122
+
123
+
124
+ # ----------------------------------------------------------------------------
125
+ # statistics
126
+
127
+
128
+ def wilson(k: int, n: int, z: float = 1.96) -> tuple[float, float]:
129
+ if n == 0:
130
+ return (float("nan"), float("nan"))
131
+ p = k / n
132
+ den = 1 + z * z / n
133
+ c = (p + z * z / (2 * n)) / den
134
+ h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / den
135
+ return (max(0.0, c - h), min(1.0, c + h))
136
+
137
+
138
+ def cohen_kappa(x, y) -> float:
139
+ """Cohen's kappa for two binary raters."""
140
+ x, y = np.asarray(x, dtype=bool), np.asarray(y, dtype=bool)
141
+ if len(x) == 0:
142
+ return float("nan")
143
+ po = float(np.mean(x == y))
144
+ px, py = x.mean(), y.mean()
145
+ pe = px * py + (1 - px) * (1 - py)
146
+ return float((po - pe) / (1 - pe)) if pe < 1 else float("nan")
147
+
148
+
149
+ def judge_prob(judge: dict, dim: str, a: str, b: str) -> float | None:
150
+ """P(a beats b) from a judge's per-dimension log-strengths (or its 'overall')."""
151
+ ls = judge["log_strength"].get(dim) or judge["log_strength"].get("overall")
152
+ if ls is None or a not in ls or b not in ls:
153
+ return None
154
+ return 1.0 / (1.0 + math.exp(-(ls[a] - ls[b])))
155
+
156
+
157
+ def human_bt(votes: list[Vote], ids: list[str]):
158
+ """Bradley–Terry fit to human votes over ``ids`` (light prior)."""
159
+ idx = {s: n for n, s in enumerate(ids)}
160
+ m = PairwiseMatrix(len(ids))
161
+ for v in votes:
162
+ m.add(idx[v.a], idx[v.b], 1.0 if v.a_wins else 0.0)
163
+ return bradley_terry(m, prior=0.5), m
164
+
165
+
166
+ def agreement_report(judges: dict[str, dict], votes: list[Vote], min_votes_for_rank: int = 2) -> dict:
167
+ """Everything the site's agreement section shows.
168
+
169
+ ``judges``: {name: {"log_strength": {dim: {item_id: float}}, ...}}.
170
+ """
171
+ out = {"n_votes": len(votes), "n_ballots": len({v.ballot for v in votes}), "judges": {}, "by_dim": {},
172
+ "judge_vs_judge": {}}
173
+ dims = sorted({v.dim for v in votes})
174
+ human = np.array([v.a_wins for v in votes], dtype=bool)
175
+ for name, j in judges.items():
176
+ probs = [judge_prob(j, v.dim, v.a, v.b) for v in votes]
177
+ mask = np.array([p is not None for p in probs])
178
+ jp = np.array([p if p is not None else 0.5 for p in probs])
179
+ jpick = jp > 0.5
180
+ n = int(mask.sum())
181
+ k = int((jpick[mask] == human[mask]).sum())
182
+ lo, hi = wilson(k, n)
183
+ ll = float(-np.mean(np.log(np.clip(np.where(human[mask], jp[mask], 1 - jp[mask]), 1e-6, 1)))) if n else float("nan")
184
+ row = {"votes": n, "agree": k, "agreement": k / n if n else float("nan"), "ci95": [lo, hi],
185
+ "kappa": cohen_kappa(human[mask], jpick[mask]), "log_loss": ll, "per_dim": {}}
186
+ for d in dims:
187
+ sel = mask & np.array([v.dim == d for v in votes])
188
+ nd = int(sel.sum())
189
+ kd = int((jpick[sel] == human[sel]).sum())
190
+ row["per_dim"][d] = {"votes": nd, "agreement": kd / nd if nd else float("nan"),
191
+ "kappa": cohen_kappa(human[sel], jpick[sel])}
192
+ # ranking correlation: human BT over items with enough votes vs the judge's ranking
193
+ taus = {}
194
+ for d in dims + ["pooled"]:
195
+ dv = [v for v in votes if d == "pooled" or v.dim == d]
196
+ counts: dict[str, int] = {}
197
+ for v in dv:
198
+ counts[v.a] = counts.get(v.a, 0) + 1
199
+ counts[v.b] = counts.get(v.b, 0) + 1
200
+ ids = sorted(s for s, c in counts.items() if c >= min_votes_for_rank)
201
+ ls = j["log_strength"].get("overall" if d == "pooled" else d) or j["log_strength"].get("overall")
202
+ ids = [s for s in ids if ls and s in ls]
203
+ dv = [v for v in dv if v.a in ids and v.b in ids]
204
+ if len(ids) < 3 or not dv:
205
+ continue
206
+ c, _ = human_bt(dv, ids)
207
+ jl = np.array([ls[s] for s in ids])
208
+ taus[d] = {"items": len(ids), "kendall_tau": kendall_tau(c.log_strength, jl),
209
+ "spearman": spearman(c.log_strength, jl)}
210
+ row["rank_correlation"] = taus
211
+ out["judges"][name] = row
212
+ for d in dims:
213
+ out["by_dim"][d] = sum(1 for v in votes if v.dim == d)
214
+ names = list(judges)
215
+ for x in names:
216
+ for y in names:
217
+ if x >= y:
218
+ continue
219
+ px = [judge_prob(judges[x], v.dim, v.a, v.b) for v in votes]
220
+ py = [judge_prob(judges[y], v.dim, v.a, v.b) for v in votes]
221
+ pairs = [(p > 0.5, q > 0.5) for p, q in zip(px, py) if p is not None and q is not None]
222
+ if pairs:
223
+ a_, b_ = zip(*pairs)
224
+ out["judge_vs_judge"][f"{x} | {y}"] = {"agreement": float(np.mean(np.array(a_) == np.array(b_))),
225
+ "kappa": cohen_kappa(a_, b_), "votes": len(pairs)}
226
+ ranked = sorted(out["judges"].items(), key=lambda kv: -(kv[1]["agreement"] if kv[1]["votes"] else -1))
227
+ out["leaderboard"] = [{"judge": k, **{f: v[f] for f in ("votes", "agreement", "ci95", "kappa")}} for k, v in ranked]
228
+ return out
229
+
230
+
231
+ def plot_agreement(report: dict, path) -> None:
232
+ """Bar chart of per-judge agreement with humans (95% Wilson CI) + kappa labels."""
233
+ import matplotlib
234
+
235
+ matplotlib.use("Agg")
236
+ import matplotlib.pyplot as plt
237
+
238
+ rows = [r for r in report["leaderboard"] if r["votes"]]
239
+ if not rows:
240
+ return
241
+ fig, ax = plt.subplots(figsize=(8, 0.55 * len(rows) + 1.6), facecolor="#fcfcfb")
242
+ ax.set_facecolor("#fcfcfb")
243
+ y = np.arange(len(rows))[::-1]
244
+ ag = [r["agreement"] for r in rows]
245
+ lo = [max(0.0, r["agreement"] - r["ci95"][0]) for r in rows]
246
+ hi = [max(0.0, r["ci95"][1] - r["agreement"]) for r in rows]
247
+ ax.barh(y, ag, height=0.6, color="#2a78d6", zorder=3)
248
+ ax.errorbar(ag, y, xerr=[lo, hi], fmt="none", ecolor="#0b0b0b", elinewidth=1.2, capsize=3, zorder=4)
249
+ ax.axvline(0.5, color="#8a8984", ls=(0, (4, 4)), lw=1)
250
+ ax.set_yticks(y, [r["judge"] for r in rows])
251
+ for yy, r in zip(y, rows):
252
+ ax.text(min(r["ci95"][1] + 0.01, 0.98), yy, f"{r['agreement']:.0%} κ={r['kappa']:.2f} n={r['votes']}",
253
+ va="center", fontsize=9, color="#0b0b0b")
254
+ ax.set_xlim(0, 1)
255
+ ax.set_xlabel("agreement with human votes (95% CI)")
256
+ ax.set_title(f"Which judge agrees with humans? ({report['n_votes']} votes, {report['n_ballots']} ballots)",
257
+ loc="left", fontweight="bold")
258
+ fig.text(0.01, -0.02, "GROUND TRUTH · human picks from ballots submitted by self-selected site visitors "
259
+ "(not experts); a judge's pick = the sign of its coupled ranking on that pair.",
260
+ fontsize=8.5, va="top", bbox={"boxstyle": "round,pad=0.4", "fc": "#fff7e6", "ec": "#eda100"})
261
+ for s in ("top", "right"):
262
+ ax.spines[s].set_visible(False)
263
+ ax.grid(axis="x", color="#e6e5e0")
264
+ fig.savefig(path, bbox_inches="tight", dpi=160)
265
+ plt.close(fig)
266
+
267
+
268
+ def _finite(obj):
269
+ """Replace NaN/inf with None so browsers can JSON.parse the report."""
270
+ if isinstance(obj, float):
271
+ return obj if math.isfinite(obj) else None
272
+ if isinstance(obj, dict):
273
+ return {k: _finite(v) for k, v in obj.items()}
274
+ if isinstance(obj, (list, tuple)):
275
+ return [_finite(v) for v in obj]
276
+ return obj
277
+
278
+
279
+ def main(argv=None) -> int:
280
+ import argparse
281
+
282
+ ap = argparse.ArgumentParser(prog="pairsort agreement", description="Human-vs-judge agreement from pairwise ballots")
283
+ ap.add_argument("--judges", default="docs/data/showdown.json", help="site data file with each judge's log-strengths")
284
+ ap.add_argument("--ballots", nargs="*", default=[], help="ballot JSON files / globs")
285
+ ap.add_argument("--github", help="owner/repo to read `human-ballot` issues from (needs gh)")
286
+ ap.add_argument("--out", default="docs/data/agreement.json")
287
+ ap.add_argument("--figure", default="docs/figures/agreement.png")
288
+ args = ap.parse_args(argv)
289
+ site = json.loads(Path(args.judges).read_text())
290
+ judges = site["judges"]
291
+ ballots = ballots_from_files(args.ballots)
292
+ if args.github:
293
+ ballots += ballots_from_github(args.github)
294
+ ids = {s["id"] for s in site["summaries"]}
295
+ votes = votes_from_ballots(ballots, valid_ids=ids, dims={d["name"] for d in site["dimensions"]})
296
+ rep = agreement_report(judges, votes)
297
+ Path(args.out).parent.mkdir(parents=True, exist_ok=True)
298
+ Path(args.out).write_text(json.dumps(_finite(rep), indent=1) + "\n")
299
+ if rep["n_votes"]:
300
+ Path(args.figure).parent.mkdir(parents=True, exist_ok=True)
301
+ plot_agreement(rep, args.figure)
302
+ print(f"{rep['n_ballots']} ballots, {rep['n_votes']} decisive votes")
303
+ for r in rep["leaderboard"]:
304
+ if r["votes"]:
305
+ print(f" {r['judge']:<34} agreement {r['agreement']:.1%} (95% CI {r['ci95'][0]:.0%}-{r['ci95'][1]:.0%}) "
306
+ f"kappa {r['kappa']:.2f} n={r['votes']}")
307
+ print(f"wrote {args.out}")
308
+ return 0
309
+
310
+
311
+ if __name__ == "__main__":
312
+ raise SystemExit(main())
pairsort/api.py ADDED
@@ -0,0 +1,296 @@
1
+ """The easy front door: ``pairsort.sort``, ``pairsort.compare`` and ``pairsort.sorter()``.
2
+
3
+ import pairsort
4
+
5
+ best = pairsort.sort(["idea one", "idea two", "idea three"], "Which idea has more impact?")
6
+ best.sorted # the same strings, best first
7
+ best.top(2) # the two best
8
+ best.scores # {id: posterior}
9
+
10
+ Everything is optional except the items and at least one question. Questions can be a string, a list of strings,
11
+ ``{"name": "question"}``, dicts, :class:`Dimension` objects or a preset name. Judges can be ``None`` (Jev via
12
+ OpenRouter, falling back to an LLM judge), a spec string (``"llm:openai/gpt-5.6-luna"``), a
13
+ :class:`~pairsort.backends.JudgeBackend`, or any plain function ``f(question, a, b) -> P(a is better)``.
14
+
15
+ Nothing here hides power: every keyword of :class:`~pairsort.sorter.PairSorter` is accepted too, and
16
+ ``pairsort.sorter()`` is a fluent builder over the same options.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import inspect
22
+ import os
23
+ import re
24
+ import sys
25
+ import warnings
26
+ from pathlib import Path
27
+ from typing import Any, Callable, Iterable
28
+
29
+ import numpy as np
30
+
31
+ from .backends import Choice, JudgeBackend, make_backend
32
+ from .sorter import PRESETS, Dimension, Item, PairSorter, SortResult
33
+
34
+ __all__ = ["sort", "compare", "sorter", "as_dimensions", "as_items", "as_judge", "FunctionJudge", "Sorter"]
35
+
36
+ _STOP = set("""which what who whose whom is are was were be been would will could should can do does did the a an of
37
+ for to in on at by with from than that this these those it its more most less least better best worse worst one two
38
+ item items option options thing things summary summaries answer answers text texts has have having make makes
39
+ likely probably really very your you i we they them their our""".split())
40
+
41
+
42
+ # --------------------------------------------------------------------------------------------- normalizers
43
+ def _slug(question: str) -> str:
44
+ words = [w for w in re.findall(r"[a-z0-9]+", question.lower()) if w not in _STOP]
45
+ return "_".join(words[:2]) or "quality"
46
+
47
+
48
+ def as_dimensions(by) -> list[Dimension]:
49
+ """Anything question-like -> a list of Dimension (names auto-generated and de-duplicated)."""
50
+ if by is None:
51
+ raise ValueError('say what to sort by, e.g. pairsort.sort(items, "Which is clearer?")')
52
+ if isinstance(by, Dimension):
53
+ by = [by]
54
+ elif isinstance(by, str):
55
+ if by in PRESETS:
56
+ return list(PRESETS[by])
57
+ by = [by]
58
+ elif isinstance(by, dict) and not {"question"} <= set(by):
59
+ by = [Dimension(name, q) if isinstance(q, str) else _dim_from_dict({"name": name, **q}) for name, q in by.items()]
60
+ elif isinstance(by, dict):
61
+ by = [by]
62
+ out: list[Dimension] = []
63
+ for d in by:
64
+ if isinstance(d, Dimension):
65
+ out.append(d)
66
+ elif isinstance(d, str):
67
+ out.append(Dimension(_slug(d), d))
68
+ elif isinstance(d, dict):
69
+ out.append(_dim_from_dict(d))
70
+ elif isinstance(d, (tuple, list)) and len(d) in (2, 3):
71
+ out.append(Dimension(*d))
72
+ else:
73
+ raise TypeError(f"can't turn {d!r} into a question")
74
+ seen: dict[str, int] = {}
75
+ for d in out: # unique names
76
+ if d.name in seen:
77
+ seen[d.name] += 1
78
+ d.name = f"{d.name}_{seen[d.name]}"
79
+ else:
80
+ seen[d.name] = 1
81
+ return out
82
+
83
+
84
+ def _dim_from_dict(d: dict) -> Dimension:
85
+ q = d.get("question") or d.get("q")
86
+ if not q:
87
+ raise ValueError(f"dimension dict needs a 'question': {d!r}")
88
+ return Dimension(d.get("name") or _slug(q), q, d.get("guidance", ""), d.get("context"))
89
+
90
+
91
+ def as_items(items) -> tuple[list[Item], list[Any], dict]:
92
+ """Anything item-like -> (Items, the original objects, extra) — extra carries e.g. a file's ``objective``.
93
+
94
+ Accepts a list of strings, a list of dicts (``id``/``text`` or ``title``/``abstract``/``body``), a dict
95
+ ``{id: text}``, a list of Items, or a path to a .txt/.json/.jsonl/.csv file.
96
+ """
97
+ from .io import _item_from, load_items
98
+
99
+ extra: dict = {}
100
+ if isinstance(items, (str, os.PathLike)) and Path(items).exists():
101
+ its, extra = load_items(items)
102
+ return its, [it.text for it in its], extra
103
+ if isinstance(items, str):
104
+ raise ValueError(f"{items!r} is not a file; pass a list of items")
105
+ if isinstance(items, dict):
106
+ pairs = list(items.items())
107
+ return [Item(str(k), str(v)) for k, v in pairs], [v for _, v in pairs], extra
108
+ originals = list(items)
109
+ out = []
110
+ for n, it in enumerate(originals):
111
+ if isinstance(it, Item):
112
+ out.append(it)
113
+ elif isinstance(it, dict):
114
+ out.append(_item_from(it, n))
115
+ else:
116
+ out.append(Item(f"item{n + 1}", str(it)))
117
+ ids = [it.id for it in out]
118
+ if len(set(ids)) != len(ids):
119
+ raise ValueError("item ids must be unique")
120
+ return out, originals, extra
121
+
122
+
123
+ class FunctionJudge(JudgeBackend):
124
+ """Turn a plain function into a judge.
125
+
126
+ ``fn(question, a, b)`` returns P(a is better) as a float, or ``"A"``/``"B"``, or a bool (True = a). If the
127
+ function also takes a ``context`` argument it receives the objective / per-question context.
128
+ """
129
+
130
+ name = "function"
131
+ max_concurrency = 8
132
+
133
+ def __init__(self, fn: Callable, name: str | None = None, cache_dir=None):
134
+ super().__init__(cache_dir=cache_dir)
135
+ self.fn = fn
136
+ self.name = name or f"function:{getattr(fn, '__name__', 'judge')}"
137
+ try:
138
+ self._ctx = "context" in inspect.signature(fn).parameters
139
+ except (TypeError, ValueError):
140
+ self._ctx = False
141
+
142
+ def _answer(self, state, questions):
143
+ out = {}
144
+ for key, q in questions.items():
145
+ opts = list(q.options)
146
+ if len(opts) != 2:
147
+ raise NotImplementedError("function judges answer two-option questions; leave fusion='linear'")
148
+ a, b = (q.options[o] for o in opts)
149
+ a, b = (re.sub(r"^\[[^\]]+\]\s*", "", str(x)) for x in (a, b)) # drop the "[id] " tag
150
+ instr = q.instructions if isinstance(q.instructions, str) else str(q.instructions)
151
+ question = instr.split("\n")[0]
152
+ r = self.fn(question, a, b, context=state) if self._ctx else self.fn(question, a, b)
153
+ if isinstance(r, str):
154
+ p = 1.0 if r.strip().upper().startswith("A") else 0.0
155
+ elif isinstance(r, (bool, np.bool_)):
156
+ p = 1.0 if r else 0.0
157
+ else:
158
+ p = float(r)
159
+ p = min(max(p, 0.0), 1.0)
160
+ out[key] = {opts[0]: p, opts[1]: 1 - p}
161
+ self.usage.add(requests=1)
162
+ return out
163
+
164
+
165
+ def _warn(err: str) -> None:
166
+ warnings.warn(f"Jev via OpenRouter is unavailable ({err[:160]}); using the generic LLM judge. "
167
+ f"Pass judge='llm' to silence this, or allow the TypeSafe provider on OpenRouter.", stacklevel=4)
168
+
169
+
170
+ def as_judge(judge=None, *, model: str | None = None, cache: str | os.PathLike | None | bool = True) -> JudgeBackend:
171
+ """None -> Jev via OpenRouter (falls back to an LLM judge); str -> backend spec; callable -> FunctionJudge."""
172
+ cache_dir = (os.environ.get("PAIRSORT_CACHE", ".pairsort_cache") if cache is True else (cache or None))
173
+ if isinstance(judge, JudgeBackend):
174
+ return judge
175
+ if judge is None:
176
+ judge = "openrouter"
177
+ if isinstance(judge, str):
178
+ if not os.environ.get("OPENROUTER_API_KEY") and judge.split(":")[0] in ("openrouter", "llm", "jev-openrouter"):
179
+ raise RuntimeError("set OPENROUTER_API_KEY (or pass judge=<your function> / another backend)")
180
+ return make_backend(judge, model=model, cache_dir=cache_dir, warn=_warn)
181
+ if callable(judge):
182
+ return FunctionJudge(judge)
183
+ raise TypeError(f"can't use {judge!r} as a judge")
184
+
185
+
186
+ # --------------------------------------------------------------------------------------------- one-liners
187
+ def sort(items, by=None, *, judge=None, objective: str | None = None, budget: int | None = None,
188
+ model: str | None = None, verbose: bool = False, cache=True, **options) -> SortResult:
189
+ """Rank ``items`` by one or more pairwise questions. Returns a :class:`SortResult`.
190
+
191
+ items list of strings / dicts / Items, a ``{id: text}`` dict, or a path to a file
192
+ by a question string, a list of them, ``{name: question}``, dicts, Dimensions, or a preset (``"papers"``)
193
+ judge None (Jev via OpenRouter), a spec like ``"llm:deepseek/deepseek-v4.1-flash"``, a backend, or a function
194
+ objective context every judgment sees ("Pick talks for a beginner audience")
195
+ budget max pairs to compare (default: all pairs up to 12 items, else ~K·log2 K with adaptive stopping)
196
+ options any other :class:`PairSorter` keyword (pair_strategy, fusion, coupling, profile, seed, ...)
197
+ """
198
+ its, originals, extra = as_items(items)
199
+ if by is None:
200
+ by = extra.get("questions") or extra.get("dimensions") or extra.get("preset")
201
+ dims = as_dimensions(by)
202
+ sorter_ = PairSorter(as_judge(judge, model=model, cache=cache), dims,
203
+ objective if objective is not None else extra.get("objective", ""),
204
+ max_pairs=options.pop("max_pairs", budget),
205
+ progress=options.pop("progress", (lambda m: print(f"· {m}", file=sys.stderr)) if verbose else None),
206
+ **options)
207
+ res = sorter_.sort(its)
208
+ res.originals = originals
209
+ return res
210
+
211
+
212
+ def compare(a, b, question: str = "Which is better?", *, judge=None, objective: str = "", model: str | None = None,
213
+ cache=True) -> float:
214
+ """P(``a`` is better than ``b``), asked in both orders and averaged (position bias cancels)."""
215
+ j = as_judge(judge, model=model, cache=cache)
216
+ from .pairwise import symmetrize
217
+
218
+ ab = j.judge(objective, question, [str(a), str(b)])
219
+ ba = j.judge(objective, question, [str(b), str(a)])
220
+ return float(symmetrize(ab[0], ba[0]))
221
+
222
+
223
+ # --------------------------------------------------------------------------------------------- builder
224
+ class Sorter:
225
+ """Fluent builder: ``pairsort.sorter().by("Which is clearer?").judge("llm").budget(60).sort(items)``.
226
+
227
+ Every method returns the builder; ``.sort(items)`` runs it. Any :class:`PairSorter` option is reachable through
228
+ a named method or ``.option(name=value)``.
229
+ """
230
+
231
+ def __init__(self):
232
+ self._dims: list = []
233
+ self._judge = None
234
+ self._model = None
235
+ self._opts: dict = {}
236
+ self._cache = True
237
+
238
+ def by(self, *questions, **named) -> "Sorter":
239
+ """Add questions: strings, Dimensions, dicts, or ``name="question"`` keywords."""
240
+ for q in questions:
241
+ self._dims += as_dimensions(q)
242
+ for name, q in named.items():
243
+ self._dims.append(Dimension(name, q))
244
+ return self
245
+
246
+ def ask(self, question: str, name: str | None = None, guidance: str = "", context=None) -> "Sorter":
247
+ self._dims.append(Dimension(name or _slug(question), question, guidance, context))
248
+ return self
249
+
250
+ def judge(self, judge=None, model: str | None = None) -> "Sorter":
251
+ self._judge, self._model = judge, model
252
+ return self
253
+
254
+ def objective(self, text: str) -> "Sorter":
255
+ return self.option(objective=text)
256
+
257
+ def budget(self, max_pairs: int) -> "Sorter":
258
+ return self.option(max_pairs=max_pairs)
259
+
260
+ def strategy(self, name: str) -> "Sorter":
261
+ return self.option(pair_strategy=name)
262
+
263
+ def adaptive(self, on: bool = True, tau_threshold: float | None = None, patience: int | None = None) -> "Sorter":
264
+ kw = {"adaptive": on}
265
+ if tau_threshold is not None:
266
+ kw["tau_threshold"] = tau_threshold
267
+ if patience is not None:
268
+ kw["patience"] = patience
269
+ return self.option(**kw)
270
+
271
+ def meta(self, pairwise: bool = False) -> "Sorter":
272
+ """Use the judge again as a meta-judge over the top items (and on close pairs if ``pairwise``)."""
273
+ return self.option(fusion="linear+meta" + ("+pairwise" if pairwise else ""))
274
+
275
+ def calibrated(self, profile) -> "Sorter":
276
+ from .calibrate import Profile
277
+
278
+ return self.option(profile=Profile.load(profile) if isinstance(profile, (str, os.PathLike)) else profile)
279
+
280
+ def verbose(self, on: bool = True) -> "Sorter":
281
+ return self.option(verbose=on)
282
+
283
+ def no_cache(self) -> "Sorter":
284
+ self._cache = False
285
+ return self
286
+
287
+ def option(self, **kw) -> "Sorter":
288
+ self._opts.update(kw)
289
+ return self
290
+
291
+ def sort(self, items) -> SortResult:
292
+ return sort(items, self._dims or None, judge=self._judge, model=self._model, cache=self._cache, **self._opts)
293
+
294
+
295
+ def sorter() -> Sorter:
296
+ return Sorter()