#!/usr/bin/env python3 """ clair_suite — Command-line interface for the CLIR-Suite public API. A single-file CLI for researchers who'd rather type than open a browser. Standard library only — no `pip install` needed. Tested on Python 3.9+. USAGE clair_suite benchmarks List benchmarks clair_suite example Print example submission JSON clair_suite leaderboard [--track defense] Show approved entries clair_suite evaluate Score a single submission clair_suite significance f1.json f2.json … Inter-system analysis (2-8 files) clair_suite run Show full report for one run OPTIONS --api-url URL Override the API host (default: $CLAIR_SUITE_API_URL or http://localhost:7860) --track {clarification, defense} For leaderboard and significance commands --n-iter N Bootstrap/randomization iterations for significance (default 10000, range 100-50000) --json Print raw JSON instead of formatted tables --quiet Suppress headers / interpretation text EXAMPLES # Pull current Pacific leaderboard clair_suite leaderboard pacific # Score a submission clair_suite evaluate pacific predictions.json # Compare four systems clair_suite significance pacific sys_a.json sys_b.json sys_c.json sys_d.json # Pipe a run report through jq clair_suite run abc123def --json | jq '.review' This file is intentionally one file with no dependencies so it can be pasted into a Colab notebook, copied to a server, or installed with a single curl + chmod. The price is some duplication with the server's internal types — kept synchronised by the OpenAPI spec at /openapi.json. """ from __future__ import annotations import argparse import json import mimetypes import os import sys import uuid from typing import Any from urllib import error as urlerror from urllib import request as urlrequest # Default API URL: env var first (so a wrapper script can pin this for # a team), then localhost for development. Most researchers will want # to point this at their HF Space (e.g. https://alice-clair-suite.hf.space). DEFAULT_API_URL = os.environ.get("CLAIR_SUITE_API_URL", "http://localhost:7860") # ────────────────────────────────────────────────────────────────────── # HTTP helpers — stdlib only # ────────────────────────────────────────────────────────────────────── def _get(api_url: str, path: str) -> Any: """GET , parse JSON, return the body. Raise on non-2xx.""" url = api_url.rstrip("/") + path req = urlrequest.Request(url, headers={"Accept": "application/json"}) try: with urlrequest.urlopen(req, timeout=30) as resp: return json.loads(resp.read()) except urlerror.HTTPError as e: body = e.read().decode("utf-8", errors="replace") _die(f"HTTP {e.code} from {url}\n{body}") except urlerror.URLError as e: _die(f"Couldn't reach {url}: {e.reason}\n" f"Set --api-url or $CLAIR_SUITE_API_URL to point at the right host.") def _post_multipart(api_url: str, path: str, fields: dict, files: list[tuple[str, str]]) -> Any: """POST multipart/form-data. `files` is a list of (form_field, path) pairs. Implemented by hand so we don't take a `requests` dependency — the whole point of this CLI is no installs. The boundary handling here follows RFC 7578. """ url = api_url.rstrip("/") + path boundary = f"----clair-suite-{uuid.uuid4().hex}" body = bytearray() for name, value in fields.items(): body += f"--{boundary}\r\n".encode() body += f'Content-Disposition: form-data; name="{name}"\r\n\r\n'.encode() body += f"{value}\r\n".encode() for name, fpath in files: if not os.path.exists(fpath): _die(f"File not found: {fpath}") mime = mimetypes.guess_type(fpath)[0] or "application/octet-stream" with open(fpath, "rb") as fh: data = fh.read() body += f"--{boundary}\r\n".encode() body += ( f'Content-Disposition: form-data; name="{name}"; ' f'filename="{os.path.basename(fpath)}"\r\n' f"Content-Type: {mime}\r\n\r\n" ).encode() body += data + b"\r\n" body += f"--{boundary}--\r\n".encode() req = urlrequest.Request( url, data=bytes(body), method="POST", headers={ "Content-Type": f"multipart/form-data; boundary={boundary}", "Accept": "application/json", }, ) try: with urlrequest.urlopen(req, timeout=300) as resp: return json.loads(resp.read()) except urlerror.HTTPError as e: body = e.read().decode("utf-8", errors="replace") # Rate-limit responses are common at this scale — surface them # readably instead of dumping a JSON blob. if e.code == 429: _die("Rate limit hit (HTTP 429). Wait until the hour resets, " "or sign in via the web UI to get an identity-keyed quota.") _die(f"HTTP {e.code} from {url}\n{body}") except urlerror.URLError as e: _die(f"Couldn't reach {url}: {e.reason}") def _die(msg: str, code: int = 1) -> None: print(msg, file=sys.stderr) sys.exit(code) # ────────────────────────────────────────────────────────────────────── # Pretty-printing for terminals (no plotting; no third-party deps) # ────────────────────────────────────────────────────────────────────── def _table(headers: list[str], rows: list[list[str]]) -> None: """ASCII table. Right-aligns numeric-looking columns automatically.""" if not rows: print(" (no rows)") return widths = [len(h) for h in headers] for r in rows: for i, cell in enumerate(r): widths[i] = max(widths[i], len(str(cell))) # Auto-detect numeric columns by checking whether every cell parses. def is_num(s: str) -> bool: try: float(s.replace("+", "").replace("%", "").replace("−", "-").strip()) return True except (ValueError, AttributeError): return False numeric = [all(is_num(str(r[i])) for r in rows) for i in range(len(headers))] sep = " ".join("-" * w for w in widths) print(" ".join(h.ljust(w) for h, w in zip(headers, widths))) print(sep) for r in rows: cells = [] for i, cell in enumerate(r): s = str(cell) cells.append(s.rjust(widths[i]) if numeric[i] else s.ljust(widths[i])) print(" ".join(cells)) def _fmt_pct(x: float | None) -> str: if x is None: return "—" return f"{x * 100:.1f}%" def _fmt_p(p: float) -> str: """Format a p-value with significance stars.""" star = "***" if p < 0.001 else "**" if p < 0.01 else "*" if p < 0.05 else "ns" return f"{p:.4f} {star}" # ────────────────────────────────────────────────────────────────────── # Commands # ────────────────────────────────────────────────────────────────────── def cmd_benchmarks(args): data = _get(args.api_url, "/api/v1/benchmarks") if args.json: print(json.dumps(data, indent=2)) return rows = [ [ b["name"], b.get("display_name", "—"), str(b.get("num_classes_default", "—")), "yes" if b.get("per_turn_default") else "no", (b.get("description") or "")[:60] + ("…" if len(b.get("description") or "") > 60 else ""), ] for b in data ] _table(["name", "display", "n_classes", "per_turn", "description"], rows) def cmd_example(args): data = _get(args.api_url, f"/api/v1/benchmarks/{args.benchmark}/example-submission") if args.json or args.quiet: # Pretty-print the submission shape only; researchers usually want # to redirect this into a file as a template. print(json.dumps(data["submission"], indent=2)) return print(f"# Example submission for benchmark: {data['benchmark']}") print(f"# per_turn_default = {data['per_turn_default']}, " f"num_classes_default = {data['num_classes_default']}") print() print(json.dumps(data["submission"], indent=2)) print() print("# Schema notes:") for line in (data.get("schema_notes") or "").split(". "): if line.strip(): print(f"# - {line.strip()}.") def cmd_leaderboard(args): data = _get(args.api_url, f"/api/v1/leaderboard/{args.benchmark}?track={args.track}") if args.json: print(json.dumps(data, indent=2)) return entries = data.get("entries", []) if not args.quiet: print(f"Leaderboard — {data['benchmark']} ({data['track']})") if not entries: print(" (no approved entries yet)") return if args.track == "defense": rows = [ [ e["rank"], e["team"], e["model"], _fmt_pct(e.get("det_f1")), _fmt_pct(e.get("det_precision")), _fmt_pct(e.get("det_recall")), _fmt_pct(e.get("asr")), e["id"][:8], ] for e in entries ] _table( ["rank", "team", "model", "det F1", "precision", "recall", "ASR ↓", "run_id"], rows, ) else: rows = [ [ e["rank"], e["team"], e["model"], _fmt_pct(e.get("f1_weighted")), _fmt_pct(e.get("f1_macro")), _fmt_pct(e.get("accuracy")), e["id"][:8], ] for e in entries ] _table( ["rank", "team", "model", "F1 (w)", "F1 (m)", "accuracy", "run_id"], rows, ) def cmd_evaluate(args): data = _post_multipart( args.api_url, "/api/v1/evaluate", fields={"benchmark": args.benchmark}, files=[("file", args.file)], ) if args.json: print(json.dumps(data, indent=2)) return if not args.quiet: print(f"Run ID: {data.get('run_id')}") print(f"Status: {data.get('status', 'scored')}") clar = data.get("clarification") or {} print() print("Clarification metrics") rows = [ ["F1 weighted", _fmt_pct(clar.get("f1_weighted"))], ["F1 macro", _fmt_pct(clar.get("f1_macro"))], ["Accuracy", _fmt_pct(clar.get("accuracy"))], ["Precision (w)", _fmt_pct(clar.get("precision_w"))], ["Recall (w)", _fmt_pct(clar.get("recall_w"))], ] _table(["metric", "value"], rows) report = data.get("classification_report") or {} if report: print() print("Per-class report") class_rows = [] for k, v in report.items(): if k == "accuracy" or not isinstance(v, dict): continue class_rows.append([ k, _fmt_pct(v.get("precision")), _fmt_pct(v.get("recall")), _fmt_pct(v.get("f1-score")), int(v.get("support", 0)), ]) _table(["class", "precision", "recall", "F1", "support"], class_rows) defense = data.get("defense") if defense: print() print("Defense detection") _table( ["metric", "value"], [ ["Detect F1", _fmt_pct(defense.get("f1"))], ["Precision", _fmt_pct(defense.get("precision"))], ["Recall", _fmt_pct(defense.get("recall"))], ["ASR ↓", _fmt_pct(defense.get("asr"))], ["TP / FP / FN / TN", f"{defense.get('tp')} / {defense.get('fp')} / " f"{defense.get('fn')} / {defense.get('tn')}"], ], ) def cmd_significance(args): if len(args.files) < 2: _die("Need at least 2 prediction files for significance analysis.") data = _post_multipart( args.api_url, "/api/v1/significance", fields={ "benchmark": args.benchmark, "track": args.track, "n_iter": str(args.n_iter), }, files=[("files", f) for f in args.files], ) if args.json: print(json.dumps(data, indent=2)) return if not args.quiet: print(f"Inter-system analysis — {data['benchmark']} · {data['track']}") print(f"{data['n_systems']} systems · {data['n_queries']} matched queries · " f"n_iter = {data['n_iter']}") print() # Per-system summary print("Per-system metric") rows = [ [name, _fmt_pct(s["mean"]), f"±{s['std']*100:.1f}%", _fmt_pct(s.get("coverage"))] for name, s in sorted( data["systems"].items(), key=lambda kv: -kv[1]["mean"] ) ] _table(["system", "mean", "std", "coverage"], rows) # Omnibus print() fr = data["friedman"] if fr.get("applicable"): sig = "***" if fr["p_value"] < 0.001 else "**" if fr["p_value"] < 0.01 else "*" if fr["p_value"] < 0.05 else "ns" print(f"Friedman omnibus: χ² = {fr['chi2']:.2f}, p = {fr['p_value']:.4f} {sig}") else: print(f"Friedman omnibus: {fr.get('note', 'not applicable')}") # Pairwise print() print("Pairwise significance (t-test / Wilcoxon / randomization / bootstrap)") rows = [] for key, r in data["pairwise"].items(): rows.append([ f"{r['system_a']} vs {r['system_b']}", f"{r['mean_diff']:+.3f}", _fmt_p(r["p_ttest"]), _fmt_p(r["p_wilcoxon"]), _fmt_p(r["p_randomization"]), _fmt_p(r["p_bootstrap"]), ]) _table(["pair", "Δ mean", "t-test", "Wilcoxon", "Rand.", "Boot."], rows) # Agreement print() agree = data["agreement"] print(f"Inter-system agreement: Fleiss' κ = {agree['fleiss_kappa']:.3f}, " f"Kendall's W = {agree['kendalls_w']:.3f}") rows = [ [ f"{r['system_a']} vs {r['system_b']}", f"{r['cohen_kappa']:+.3f}", ] for r in agree["pairwise_cohen_kappa"].values() ] if rows: _table(["pair", "Cohen's κ"], rows) # NLL efficiency print() nll = data["nll_efficiency"] print(f"Normalized NLL efficiency (η = 1 − NLL/H(label), H = {nll['h_label']:.3f})") rows = [ [ name, f"{d['efficiency']:+.3f}", f"{d['nll']:.3f}", "self" if d.get("confidence_source") == "self_reported" else "default", ] for name, d in sorted( nll["systems"].items(), key=lambda kv: -kv[1]["efficiency"] ) ] _table(["system", "η", "NLL", "conf"], rows) # Interpretation paragraphs if not args.quiet and data.get("interpretation"): print() print("─── Interpretation " + "─" * 60) for p in data["interpretation"]: print() print(f" {p['heading']}:") # Word-wrap to ~72 chars for terminal readability body = p["body"].replace("**", "") words = body.split() line = " " for w in words: if len(line) + len(w) + 1 > 76: print(line) line = " " + w else: line += (" " if line.strip() else "") + w if line.strip(): print(line) def cmd_run(args): data = _get(args.api_url, f"/api/v1/runs/{args.run_id}") if args.json: print(json.dumps(data, indent=2)) return print(f"Run {data.get('id', args.run_id)[:12]}") print(f" team: {data.get('team')}") print(f" model: {data.get('model')}") print(f" method: {data.get('method')}") print(f" benchmark: {data.get('benchmark')}") print(f" status: {data.get('status')}") review = data.get("review") if review: print() print(f"Review by {review['admin_username']} — {review['status']}") if review.get("comment"): print(f" comment: {review['comment']}") # ────────────────────────────────────────────────────────────────────── # Argparse plumbing # ────────────────────────────────────────────────────────────────────── def main(argv=None): parser = argparse.ArgumentParser( prog="clair_suite", description="Command-line interface for the CLIR-Suite public API.", ) # The three global flags live on the top-level parser, so users can # type them BEFORE the subcommand (`clair_suite --api-url X evaluate ...`). # They're also added to a `common` parent below so they ALSO work # AFTER the subcommand (`clair_suite evaluate ... --api-url X`). # Both placements are idiomatic in different tools; we accept both. parser.add_argument("--api-url", default=DEFAULT_API_URL, help=f"API host (default: {DEFAULT_API_URL})") parser.add_argument("--json", action="store_true", default=False, help="Print raw JSON instead of formatted tables") parser.add_argument("--quiet", action="store_true", default=False, help="Suppress headers / interpretation text") common = argparse.ArgumentParser(add_help=False) common.add_argument("--api-url", default=argparse.SUPPRESS, help=argparse.SUPPRESS) common.add_argument("--json", action="store_true", default=argparse.SUPPRESS, help=argparse.SUPPRESS) common.add_argument("--quiet", action="store_true", default=argparse.SUPPRESS, help=argparse.SUPPRESS) sub = parser.add_subparsers(dest="cmd", required=True) p = sub.add_parser("benchmarks", help="List registered benchmarks", parents=[common]) p.set_defaults(func=cmd_benchmarks) p = sub.add_parser("example", help="Print example submission JSON", parents=[common]) p.add_argument("benchmark") p.set_defaults(func=cmd_example) p = sub.add_parser("leaderboard", help="Show approved leaderboard entries", parents=[common]) p.add_argument("benchmark") p.add_argument("--track", choices=["clarification", "defense"], default="clarification") p.set_defaults(func=cmd_leaderboard) p = sub.add_parser("evaluate", help="Score a single prediction file", parents=[common]) p.add_argument("benchmark") p.add_argument("file") p.set_defaults(func=cmd_evaluate) p = sub.add_parser("significance", help="Inter-system significance analysis", parents=[common]) p.add_argument("benchmark") p.add_argument("files", nargs="+", help="2-8 prediction JSON files") p.add_argument("--track", choices=["clarification", "defense"], default="clarification") p.add_argument("--n-iter", type=int, default=10_000, help="Bootstrap / randomization iterations (100-50000)") p.set_defaults(func=cmd_significance) p = sub.add_parser("run", help="Show full report for a run_id", parents=[common]) p.add_argument("run_id") p.set_defaults(func=cmd_run) args = parser.parse_args(argv) try: args.func(args) except BrokenPipeError: # Reader closed the pipe (e.g. `clair_suite ... | head`); shut # down without dumping a traceback. try: sys.stdout.close() except Exception: pass sys.exit(0) if __name__ == "__main__": main()