errorbars 0.2.0__tar.gz → 0.2.2__tar.gz

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.
@@ -20,3 +20,4 @@ npm-debug.log*
20
20
  .DS_Store
21
21
  *.swp
22
22
  web/*.tsbuildinfo
23
+ .venv-minimums/
@@ -2,6 +2,52 @@
2
2
 
3
3
  All notable changes to this project are documented in this file.
4
4
 
5
+ ## [0.2.2] - 2026-10-02
6
+
7
+ Files and pipes as Windows and spreadsheets make them.
8
+
9
+ ### Fixed
10
+
11
+ - A CSV saved from a spreadsheet. Excel's "CSV UTF-8" starts with a byte-order
12
+ mark, which became part of the first column's name: "missing required column
13
+ 'question_id' in row 1" for a file that has it. A spreadsheet in a locale
14
+ whose decimal mark is the comma writes semicolons between the fields and
15
+ `0,75` for a score, which failed the same way. The mark is skipped, the
16
+ delimiter (comma, semicolon or tab) is the one that splits the header into
17
+ the required columns, and decimal commas are read when the delimiter is not
18
+ the comma.
19
+ - That error now lists the columns the file does have.
20
+ - Output written to a pipe or a file is UTF-8. Before 3.15, Python on Windows
21
+ gives a redirected stdout the system's code page, so
22
+ `errorbars leaderboard scores.csv > table.txt` with a model name outside it
23
+ stopped with "'charmap' codec can't encode characters". (Reproduced on Linux
24
+ by giving the pipe cp1252 with `PYTHONIOENCODING`; the test does the same.)
25
+
26
+ ## [0.2.1] - 2026-10-02
27
+
28
+ What the table commands print, checked the way their output is read: after `pip install
29
+ errorbars`, in a CI log, and with the model names harnesses produce.
30
+
31
+ ### Fixed
32
+
33
+ - `pip install errorbars` gives a working command line. `rich` is an extra, and without it
34
+ `summarize`, `compare`, `leaderboard` and `power` stopped with "rich is required for table
35
+ output". They print the same rows as aligned plain text now; `errorbars[cli]` still gives the
36
+ `rich` tables.
37
+ - Model names are printed whole. Written to a pipe (a CI log, a file), tables were laid out 80
38
+ columns wide and every cell cut to fit: lm-eval's `meta-llama__Llama-3.1-8B-Instruct` and
39
+ `meta-llama__Llama-3.1-70B-Instruct` were both `meta-llam…` in the pairwise table, and the
40
+ column headings were cut too. A pipe gets the table at its full width; a terminal too narrow
41
+ for it folds the names onto more lines and keeps the numbers on one.
42
+ - Model names are printed as they are. `rich` read `[q4_k_m]` in a name as style markup and
43
+ dropped it, and a name holding something like `[/b]` ended the command with a `MarkupError`
44
+ traceback. Nothing from the data is parsed as markup or as an emoji code any more.
45
+ - The message for a missing `inspect-ai` names the extra (`pip install "errorbars[inspect]"`),
46
+ which also carries the pins inspect-ai needs to import.
47
+ - The strict type check passes on Python 3.10 (an array annotation was only complete on the
48
+ numpy releases that need 3.11), and the test for importing an Inspect log is skipped without
49
+ inspect-ai, like the rest.
50
+
5
51
  ## [0.2.0] - 2026-10-01
6
52
 
7
53
  A harness writes one log per model, and every command took exactly one file. Asking whether
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: errorbars
3
- Version: 0.2.0
3
+ Version: 0.2.2
4
4
  Summary: Error bars for LLM evals: standard errors, clustering, paired comparisons, leaderboards, and power analysis.
5
5
  Project-URL: Homepage, https://antonsoo.github.io/errorbars/
6
6
  Project-URL: Repository, https://github.com/antonsoo/errorbars
@@ -70,7 +70,7 @@ as a win. The full walkthrough, with every number copied from a real command, is
70
70
  ## Quickstart
71
71
 
72
72
  ```bash
73
- pip install "errorbars[cli]"
73
+ pip install errorbars
74
74
  errorbars power --delta 0.03 --baseline 0.5
75
75
  ```
76
76
 
@@ -101,8 +101,10 @@ errorbars leaderboard examples/data/reading_comprehension.csv
101
101
  - **`power`** — number of questions needed to detect an effect δ at a given α and power, or the
102
102
  minimum detectable effect for a given n, accounting for pairing correlation, repeated sampling,
103
103
  and cluster design effect.
104
- - **CLI** — `errorbars summarize|compare|leaderboard|power|import`, `rich` tables by default,
105
- `--json` for scripting.
104
+ - **CLI** — `errorbars summarize|compare|leaderboard|power|import`. Tables are plain aligned text
105
+ on a bare install (numpy is the only dependency) and `rich` tables with
106
+ `pip install "errorbars[cli]"`; either way a model name is printed whole, and a table written to
107
+ a pipe is as wide as it needs to be. `--json` for scripting.
106
108
  - **Reads what harnesses write** — a harness leaves one log per model, so every command takes
107
109
  one or more files or directories and reads each as what it is: lm-evaluation-harness
108
110
  `--log_samples` output, Inspect AI `.eval` logs, or the CSV/JSONL format below.
@@ -32,7 +32,7 @@ as a win. The full walkthrough, with every number copied from a real command, is
32
32
  ## Quickstart
33
33
 
34
34
  ```bash
35
- pip install "errorbars[cli]"
35
+ pip install errorbars
36
36
  errorbars power --delta 0.03 --baseline 0.5
37
37
  ```
38
38
 
@@ -63,8 +63,10 @@ errorbars leaderboard examples/data/reading_comprehension.csv
63
63
  - **`power`** — number of questions needed to detect an effect δ at a given α and power, or the
64
64
  minimum detectable effect for a given n, accounting for pairing correlation, repeated sampling,
65
65
  and cluster design effect.
66
- - **CLI** — `errorbars summarize|compare|leaderboard|power|import`, `rich` tables by default,
67
- `--json` for scripting.
66
+ - **CLI** — `errorbars summarize|compare|leaderboard|power|import`. Tables are plain aligned text
67
+ on a bare install (numpy is the only dependency) and `rich` tables with
68
+ `pip install "errorbars[cli]"`; either way a model name is printed whole, and a table written to
69
+ a pipe is as wide as it needs to be. `--json` for scripting.
68
70
  - **Reads what harnesses write** — a harness leaves one log per model, so every command takes
69
71
  one or more files or directories and reads each as what it is: lm-evaluation-harness
70
72
  `--log_samples` output, Inspect AI `.eval` logs, or the CSV/JSONL format below.
@@ -32,7 +32,7 @@ include = ["/src", "/docs/*.md", "/README.md", "/CHANGELOG.md", "/LICENSE*", "/p
32
32
 
33
33
  [project]
34
34
  name = "errorbars"
35
- version = "0.2.0"
35
+ version = "0.2.2"
36
36
  description = "Error bars for LLM evals: standard errors, clustering, paired comparisons, leaderboards, and power analysis."
37
37
  dynamic = ["readme"]
38
38
  license = "MIT"
@@ -13,7 +13,7 @@ from errorbars.stats import (
13
13
  within_between_variance,
14
14
  )
15
15
 
16
- __version__ = "0.2.0"
16
+ __version__ = "0.2.2"
17
17
 
18
18
  __all__ = [
19
19
  "__version__",
@@ -0,0 +1,112 @@
1
+ """Tables for the terminal: rich's when it is installed, aligned plain text when it isn't.
2
+
3
+ The commands build a :class:`Table` and hand it to an :class:`Output`. What reaches the
4
+ terminal follows three rules, each of which the first version of this broke:
5
+
6
+ - A plain ``pip install errorbars`` prints tables. ``rich`` is an extra, and without it the
7
+ commands used to stop and ask for it; now they print the same rows as aligned text.
8
+ - A name is printed as it is. Model names come from the data (``org__model[q4_k_m]``,
9
+ ``model:100:latest``), and rich reads ``[...]`` as style markup and ``:name:`` as an emoji,
10
+ so a name lost its brackets or raised ``MarkupError``. Nothing here is parsed as markup.
11
+ - A name is printed whole. Written to a pipe (a CI log, a file), rich lays tables out 80
12
+ columns wide and cuts each cell to fit, which left two models of one organisation with the
13
+ same visible name. A pipe gets the table at its full width, and a terminal too narrow for
14
+ it gets the long cells folded onto more lines.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from dataclasses import dataclass, field
20
+ from typing import Literal
21
+
22
+ try:
23
+ from rich.console import Console
24
+ from rich.table import Table as RichTable
25
+
26
+ HAS_RICH = True
27
+ except ImportError: # pragma: no cover - exercised by the test that hides rich
28
+ HAS_RICH = False
29
+
30
+ __all__ = ["HAS_RICH", "Output", "Table"]
31
+
32
+ Justify = Literal["left", "right"]
33
+
34
+ _UNBOUNDED = 100_000
35
+
36
+
37
+ @dataclass
38
+ class Table:
39
+ """A titled table of text cells."""
40
+
41
+ title: str
42
+ header_style: str = "bold cyan"
43
+ columns: list[tuple[str, Justify]] = field(default_factory=list)
44
+ rows: list[tuple[str, ...]] = field(default_factory=list)
45
+
46
+ def add_column(self, header: str, justify: Justify = "left") -> None:
47
+ self.columns.append((header, justify))
48
+
49
+ def add_row(self, *cells: str) -> None:
50
+ self.rows.append(tuple(cells))
51
+
52
+
53
+ def plain_table(table: Table) -> str:
54
+ """The table as aligned text: a title, a header, a rule, a line per row."""
55
+ headers = [header for header, _ in table.columns]
56
+ widths = [
57
+ max(len(header), *(len(row[i]) for row in table.rows)) if table.rows else len(header)
58
+ for i, header in enumerate(headers)
59
+ ]
60
+
61
+ def line(cells: tuple[str, ...] | list[str]) -> str:
62
+ padded = [
63
+ cell.rjust(width) if justify == "right" else cell.ljust(width)
64
+ for cell, width, (_, justify) in zip(cells, widths, table.columns, strict=True)
65
+ ]
66
+ return " ".join(padded).rstrip()
67
+
68
+ lines = [table.title, line(headers), " ".join("-" * width for width in widths)]
69
+ lines.extend(line(row) for row in table.rows)
70
+ return "\n".join(lines)
71
+
72
+
73
+ class Output:
74
+ """Where a command's tables and notes go: standard output, through rich if it is there."""
75
+
76
+ def __init__(self, *, use_rich: bool | None = None) -> None:
77
+ self._rich = HAS_RICH if use_rich is None else use_rich and HAS_RICH
78
+ self._first = True
79
+
80
+ def _console(self, width: int | None = None) -> Console:
81
+ # No markup, no emoji codes, no highlighting: every string is data.
82
+ return Console(markup=False, emoji=False, highlight=False, width=width)
83
+
84
+ def table(self, table: Table) -> None:
85
+ if not self._rich:
86
+ if not self._first:
87
+ print()
88
+ self._first = False
89
+ print(plain_table(table))
90
+ return
91
+ rendered = RichTable(title=table.title, header_style=table.header_style)
92
+ for header, justify in table.columns:
93
+ # "fold" wraps a cell that doesn't fit; the default ("ellipsis") cuts it. Numbers
94
+ # stay on one line, so it is the names that give way in a narrow terminal.
95
+ rendered.add_column(header, justify=justify, overflow="fold", no_wrap=justify == "right")
96
+ for row in table.rows:
97
+ rendered.add_row(*row)
98
+ console = self._console()
99
+ if not console.is_terminal:
100
+ # Nobody is there to resize a pipe: give the table the width it asks for. (A
101
+ # console measures a table as no wider than itself, so ask a very wide one.)
102
+ needed = self._console(width=_UNBOUNDED).measure(rendered).maximum
103
+ if needed > console.width:
104
+ console = self._console(width=needed)
105
+ console.print(rendered)
106
+ self._first = False
107
+
108
+ def note(self, text: str, style: str | None = None) -> None:
109
+ if self._rich:
110
+ self._console().print(text, style=style)
111
+ else:
112
+ print(text)
@@ -42,7 +42,8 @@ def load_inspect_log(path: str | Path, scorer: str | None = None) -> EvalData:
42
42
  from inspect_ai.scorer import value_to_float
43
43
  except ImportError as exc: # pragma: no cover - exercised only without the extra
44
44
  raise ImportError(
45
- "load_inspect_log requires inspect-ai (the 'inspect' extra): pip install inspect-ai"
45
+ "reading an Inspect log needs inspect-ai, which the 'inspect' extra installs: "
46
+ 'pip install "errorbars[inspect]"'
46
47
  ) from exc
47
48
 
48
49
  try:
@@ -91,7 +91,7 @@ def infer_model_name(path: str | Path) -> str | None:
91
91
  candidates = others
92
92
  for candidate in candidates:
93
93
  try:
94
- with open(candidate, encoding="utf-8") as f:
94
+ with open(candidate, encoding="utf-8-sig") as f:
95
95
  results = json.load(f)
96
96
  except (OSError, ValueError):
97
97
  continue
@@ -137,7 +137,7 @@ def load_lm_eval_samples(
137
137
 
138
138
  records: list[tuple[int, dict[str, object]]] = []
139
139
  filters: dict[str, None] = {} # in order of first appearance
140
- with open(path, encoding="utf-8") as f:
140
+ with open(path, encoding="utf-8-sig") as f:
141
141
  for lineno, raw_line in enumerate(f, start=1):
142
142
  line = raw_line.strip()
143
143
  if not line:
@@ -9,6 +9,7 @@ from pathlib import Path
9
9
  from typing import Any
10
10
 
11
11
  from errorbars import __version__
12
+ from errorbars._tables import Output, Table
12
13
  from errorbars.compare import paired_compare
13
14
  from errorbars.inputs import load_inputs
14
15
  from errorbars.io import ColumnMap, EvalData, write_csv
@@ -17,14 +18,6 @@ from errorbars.plot import forest_plot_svg
17
18
  from errorbars.power import minimum_detectable_effect, questions_needed
18
19
  from errorbars.stats import bootstrap_ci, is_binary, mean_ci_clt, wilson_ci
19
20
 
20
- try:
21
- from rich.console import Console
22
- from rich.table import Table
23
-
24
- _HAS_RICH = True
25
- except ImportError: # pragma: no cover
26
- _HAS_RICH = False
27
-
28
21
 
29
22
  def _require_models(data: EvalData, *names: str) -> None:
30
23
  known = data.models()
@@ -96,12 +89,6 @@ def _print_json(obj: Any) -> None:
96
89
  print(json.dumps(obj, indent=2, default=str))
97
90
 
98
91
 
99
- def _console() -> Console:
100
- if not _HAS_RICH:
101
- raise SystemExit("error: rich is required for table output; install errorbars[cli] or use --json")
102
- return Console()
103
-
104
-
105
92
  def _has_clusters(data: EvalData) -> bool:
106
93
  """True when the data groups questions: some cluster id that isn't its question's own id,
107
94
  which is what a file without a cluster column is filled with."""
@@ -180,8 +167,8 @@ def cmd_summarize(args: argparse.Namespace) -> None:
180
167
  _print_json(result)
181
168
  return
182
169
 
183
- console = _console()
184
- table = Table(title=f"summarize: {result['model']}", show_header=True, header_style="bold cyan")
170
+ out = Output()
171
+ table = Table(title=f"summarize: {result['model']}")
185
172
  table.add_column("metric")
186
173
  table.add_column("value", justify="right")
187
174
  table.add_row("n", str(est.n))
@@ -189,7 +176,7 @@ def cmd_summarize(args: argparse.Namespace) -> None:
189
176
  table.add_row("SE", f"{est.se:.4f}")
190
177
  table.add_row(f"{int(args.confidence * 100)}% CI", f"[{est.ci_low:.4f}, {est.ci_high:.4f}]")
191
178
  table.add_row("method", est.method)
192
- console.print(table)
179
+ out.table(table)
193
180
  if cluster_info:
194
181
  ct = Table(title="clustering diagnostics", header_style="bold magenta")
195
182
  ct.add_column("metric")
@@ -202,14 +189,14 @@ def cmd_summarize(args: argparse.Namespace) -> None:
202
189
  "clustered CI",
203
190
  f"[{cluster_info['clustered_ci_low']:.4f}, {cluster_info['clustered_ci_high']:.4f}]",
204
191
  )
205
- console.print(ct)
192
+ out.table(ct)
206
193
  if within_between:
207
194
  wt = Table(title="within/between-question variance", header_style="bold magenta")
208
195
  wt.add_column("component")
209
196
  wt.add_column("variance", justify="right")
210
197
  wt.add_row("within-question (sampling noise)", f"{within_between['var_within']:.4f}")
211
198
  wt.add_row("between-question (item difficulty)", f"{within_between['var_between']:.4f}")
212
- console.print(wt)
199
+ out.table(wt)
213
200
 
214
201
 
215
202
  def _models_to_compare(data: EvalData, model_a: str | None, model_b: str | None) -> tuple[str, str]:
@@ -262,8 +249,8 @@ def cmd_compare(args: argparse.Namespace) -> None:
262
249
  )
263
250
  return
264
251
 
265
- console = _console()
266
- table = Table(title=f"compare: {args.model_a} vs {args.model_b}", header_style="bold cyan")
252
+ out = Output()
253
+ table = Table(title=f"compare: {args.model_a} vs {args.model_b}")
267
254
  table.add_column("metric")
268
255
  table.add_column("value", justify="right")
269
256
  table.add_row("n (shared questions)", str(comp.n))
@@ -290,7 +277,7 @@ def cmd_compare(args: argparse.Namespace) -> None:
290
277
  f"{comp.mcnemar.n01} / {comp.mcnemar.n10}",
291
278
  )
292
279
  table.add_row("McNemar exact p-value", f"{comp.mcnemar.p_value:.4g}")
293
- console.print(table)
280
+ out.table(table)
294
281
 
295
282
 
296
283
  def cmd_leaderboard(args: argparse.Namespace) -> None:
@@ -306,8 +293,8 @@ def cmd_leaderboard(args: argparse.Namespace) -> None:
306
293
  _print_json(lb.as_dict())
307
294
  return
308
295
 
309
- console = _console()
310
- table = Table(title="leaderboard", header_style="bold cyan")
296
+ out = Output()
297
+ table = Table(title="leaderboard")
311
298
  table.add_column("rank", justify="right")
312
299
  table.add_column("model")
313
300
  table.add_column("mean", justify="right")
@@ -328,10 +315,11 @@ def cmd_leaderboard(args: argparse.Namespace) -> None:
328
315
  str(e.n),
329
316
  letter_of.get(e.model, ""),
330
317
  )
331
- console.print(table)
332
- console.print(
333
- "[dim]Models sharing a group letter are not statistically distinguishable "
334
- f"(Holm-corrected paired test, alpha={args.alpha}).[/dim]"
318
+ out.table(table)
319
+ out.note(
320
+ "Models sharing a group letter are not statistically distinguishable "
321
+ f"(Holm-corrected paired test, alpha={args.alpha}).",
322
+ style="dim",
335
323
  )
336
324
 
337
325
  pt = Table(title="pairwise paired tests (Holm-corrected)", header_style="bold magenta")
@@ -351,15 +339,17 @@ def cmd_leaderboard(args: argparse.Namespace) -> None:
351
339
  f"{pr.p_holm:.4g}",
352
340
  sig,
353
341
  )
354
- console.print(pt)
355
- console.print(
356
- "[dim]'p (used, Holm)' is the cluster-robust paired p-value (when clusters are "
357
- "present) after Holm correction across all pairs; otherwise the unclustered paired p-value.[/dim]"
342
+ out.table(pt)
343
+ out.note(
344
+ "'p (used, Holm)' is the cluster-robust paired p-value (when clusters are "
345
+ "present) after Holm correction across all pairs; otherwise the unclustered paired p-value.",
346
+ style="dim",
358
347
  )
359
348
  if len(question_sets) > 1:
360
- console.print(
361
- "[yellow]The models were not scored on the same questions. Each mean is over that "
362
- "model's own questions; each paired test uses the questions its two models share.[/yellow]"
349
+ out.note(
350
+ "The models were not scored on the same questions. Each mean is over that "
351
+ "model's own questions; each paired test uses the questions its two models share.",
352
+ style="yellow",
363
353
  )
364
354
 
365
355
 
@@ -385,8 +375,8 @@ def cmd_power(args: argparse.Namespace) -> None:
385
375
  if args.json:
386
376
  _print_json(payload)
387
377
  return
388
- console = _console()
389
- table = Table(title="power: questions needed", header_style="bold cyan")
378
+ out = Output()
379
+ table = Table(title="power: questions needed")
390
380
  table.add_column("input")
391
381
  table.add_column("value", justify="right")
392
382
  table.add_row("delta", f"{args.delta}")
@@ -395,16 +385,16 @@ def cmd_power(args: argparse.Namespace) -> None:
395
385
  table.add_row("rho (paired correlation)", f"{args.rho}")
396
386
  table.add_row("samples/question", str(args.samples_per_question))
397
387
  table.add_row("cluster design effect", f"{args.cluster_deff}")
398
- console.print(table)
399
- console.print(f"[bold green]Questions needed: {result.n_questions}[/bold green]")
388
+ out.table(table)
389
+ out.note(f"Questions needed: {result.n_questions}", style="bold green")
400
390
  else:
401
391
  mde = minimum_detectable_effect(n_questions=args.n, **kwargs)
402
392
  payload = {"n_questions": args.n, "mde": mde, **{k: v for k, v in kwargs.items()}}
403
393
  if args.json:
404
394
  _print_json(payload)
405
395
  return
406
- console = _console()
407
- console.print(f"[bold green]Minimum detectable effect at n={args.n}: {mde:.4f}[/bold green]")
396
+ out = Output()
397
+ out.note(f"Minimum detectable effect at n={args.n}: {mde:.4f}", style="bold green")
408
398
 
409
399
 
410
400
  def cmd_import(args: argparse.Namespace) -> None:
@@ -486,9 +476,27 @@ def build_parser() -> argparse.ArgumentParser:
486
476
  return parser
487
477
 
488
478
 
479
+ def _text_streams() -> None:
480
+ """Make stdout and stderr able to carry any text.
481
+
482
+ A pipe or a file gets UTF-8: before 3.15, Python on Windows gives it the system's code
483
+ page, where a model name outside it raised ``UnicodeEncodeError``. A terminal keeps its own encoding
484
+ and shows a character it cannot encode as an escape.
485
+ """
486
+ for stream in (sys.stdout, sys.stderr):
487
+ reconfigure = getattr(stream, "reconfigure", None)
488
+ if reconfigure is None: # replaced by something that isn't a text file
489
+ continue
490
+ if stream.isatty():
491
+ reconfigure(errors="backslashreplace")
492
+ else:
493
+ reconfigure(encoding="utf-8")
494
+
495
+
489
496
  def main(argv: list[str] | None = None) -> None:
490
497
  parser = build_parser()
491
498
  args = parser.parse_args(argv)
499
+ _text_streams()
492
500
  try:
493
501
  args.func(args)
494
502
  except UnicodeDecodeError as exc:
@@ -63,7 +63,7 @@ def split_spec(spec: str) -> tuple[str | None, Path]:
63
63
 
64
64
 
65
65
  def _first_record(path: Path) -> object:
66
- with open(path, encoding="utf-8") as f:
66
+ with open(path, encoding="utf-8-sig") as f:
67
67
  for line in f:
68
68
  line = line.strip()
69
69
  if line:
@@ -11,6 +11,7 @@ from __future__ import annotations
11
11
  import csv
12
12
  import json
13
13
  import math
14
+ import re
14
15
  from collections.abc import Iterable
15
16
  from dataclasses import dataclass, field
16
17
  from pathlib import Path
@@ -166,6 +167,14 @@ def _label(row: Any, column: str, n: int) -> str:
166
167
  return str(value)
167
168
 
168
169
 
170
+ def _names(row: dict[str, Any]) -> str:
171
+ """A row's field names for an error message: the first ten, each cut to a readable length."""
172
+ names = [str(name) for name in row]
173
+ shown = [name if len(name) <= 40 else name[:39] + "\u2026" for name in names[:10]]
174
+ more = f", and {len(names) - 10} more" if len(names) > 10 else ""
175
+ return (", ".join(shown) + more) or "no fields"
176
+
177
+
169
178
  def _from_records(records: Iterable[dict[str, Any]], columns: ColumnMap) -> EvalData:
170
179
  question_id: list[str] = []
171
180
  model: list[str] = []
@@ -184,12 +193,11 @@ def _from_records(records: Iterable[dict[str, Any]], columns: ColumnMap) -> Eval
184
193
  raise ValueError(
185
194
  f"row {n}: more fields than the header has columns (an unquoted comma in a value?)"
186
195
  )
187
- if columns.question_id not in row:
188
- raise ValueError(f"missing required column '{columns.question_id}' in row {n}")
189
- if columns.model not in row:
190
- raise ValueError(f"missing required column '{columns.model}' in row {n}")
191
- if columns.score not in row:
192
- raise ValueError(f"missing required column '{columns.score}' in row {n}")
196
+ for required in (columns.question_id, columns.model, columns.score):
197
+ if required not in row:
198
+ raise ValueError(
199
+ f"missing required column '{required}' in row {n} (it has: {_names(row)})"
200
+ )
193
201
  question_id.append(_label(row, columns.question_id, n))
194
202
  model.append(_label(row, columns.model, n))
195
203
  score.append(_coerce_score(row[columns.score], n))
@@ -214,21 +222,60 @@ def _from_records(records: Iterable[dict[str, Any]], columns: ColumnMap) -> Eval
214
222
  return EvalData(question_id, model, score, cluster_id, sample, columns)
215
223
 
216
224
 
225
+ def _delimiter(header: str, columns: ColumnMap) -> str:
226
+ """The delimiter the header was written with.
227
+
228
+ A spreadsheet saves "CSV" with the list separator of its locale: a semicolon wherever the
229
+ decimal mark is a comma (most of Europe), sometimes a tab. The header settles it: the
230
+ delimiter is the one that splits it into the columns being looked for.
231
+ """
232
+ wanted = {columns.question_id, columns.model, columns.score}
233
+ for delimiter in (",", ";", "\t"):
234
+ names = {name.strip() for name in next(csv.reader([header], delimiter=delimiter), [])}
235
+ if wanted <= names:
236
+ return delimiter
237
+ return ","
238
+
239
+
240
+ _DECIMAL_COMMA = re.compile(r"[+-]?\d+,\d+(?:[eE][+-]?\d+)?")
241
+
242
+
243
+ def _decimal_commas(records: Iterable[dict[str, Any]], score: str) -> Iterable[dict[str, Any]]:
244
+ """Scores written ``0,75`` in a file whose delimiter is not the comma."""
245
+ for row in records:
246
+ value = row.get(score)
247
+ if isinstance(value, str) and _DECIMAL_COMMA.fullmatch(value.strip()):
248
+ row[score] = value.strip().replace(",", ".")
249
+ yield row
250
+
251
+
217
252
  def load_csv(path: str | Path, columns: ColumnMap | None = None) -> EvalData:
218
- """Load per-item scores from a CSV file."""
253
+ """Load per-item scores from a CSV file.
254
+
255
+ Read as a spreadsheet writes it too: with a byte-order mark ("CSV UTF-8" in Excel), with
256
+ semicolons or tabs between the fields, and with decimal commas when the delimiter is not
257
+ the comma.
258
+ """
219
259
  columns = columns or ColumnMap()
220
- with open(path, newline="", encoding="utf-8") as f:
221
- reader = csv.DictReader(f)
260
+ with open(path, newline="", encoding="utf-8-sig") as f:
261
+ header = f.readline()
262
+ f.seek(0)
263
+ delimiter = _delimiter(header, columns)
264
+ reader = csv.DictReader(f, delimiter=delimiter)
222
265
  if reader.fieldnames is None:
223
266
  raise ValueError(f"{path}: empty or headerless CSV")
224
- return _from_records(reader, columns)
267
+ reader.fieldnames = [name.strip() for name in reader.fieldnames]
268
+ records: Iterable[dict[str, Any]] = reader
269
+ if delimiter != ",":
270
+ records = _decimal_commas(reader, columns.score)
271
+ return _from_records(records, columns)
225
272
 
226
273
 
227
274
  def load_jsonl(path: str | Path, columns: ColumnMap | None = None) -> EvalData:
228
275
  """Load per-item scores from a JSON Lines file (one record per line)."""
229
276
  columns = columns or ColumnMap()
230
277
  records: list[dict[str, Any]] = []
231
- with open(path, encoding="utf-8") as f:
278
+ with open(path, encoding="utf-8-sig") as f:
232
279
  for lineno, line in enumerate(f, start=1):
233
280
  line = line.strip()
234
281
  if not line:
@@ -10,9 +10,10 @@ from __future__ import annotations
10
10
  import math
11
11
  from dataclasses import dataclass
12
12
  from statistics import NormalDist
13
+ from typing import Any
13
14
 
14
15
  import numpy as np
15
- from numpy.typing import ArrayLike
16
+ from numpy.typing import ArrayLike, NDArray
16
17
 
17
18
  __all__ = [
18
19
  "MeanEstimate",
@@ -225,7 +226,7 @@ class ClusterDiagnostics:
225
226
  }
226
227
 
227
228
 
228
- def _group_by(values: np.ndarray, clusters: np.ndarray) -> list[np.ndarray]:
229
+ def _group_by(values: NDArray[np.float64], clusters: NDArray[Any]) -> list[NDArray[np.float64]]:
229
230
  order = np.argsort(clusters, kind="stable")
230
231
  values_sorted = values[order]
231
232
  clusters_sorted = clusters[order]
File without changes
File without changes