rovidence-eval 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.
@@ -0,0 +1,42 @@
1
+ """rovidence-eval: vendor-neutral robot pilot acceptance checks, using Rovidence's published methodology."""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ from .calculator import Baseline, Costs, Metrics, PilotInputs, compute_metrics, js_round, sum_inputs # noqa: E402
6
+ from .csvlog import CSV_COLUMNS, OPTIONAL_COLUMNS, aggregate_weeks, parse_pilot_csv # noqa: E402
7
+ from .evaluator import ( # noqa: E402
8
+ GATE_DEFS,
9
+ PilotDataError,
10
+ evaluate_csv_text,
11
+ evaluate_gates,
12
+ evaluate_pilot_csv,
13
+ evaluate_rows,
14
+ load_config,
15
+ verdict_for,
16
+ )
17
+ from .schemas import PilotConfig, PilotReport # noqa: E402
18
+
19
+ __all__ = [
20
+ "__version__",
21
+ "Baseline",
22
+ "Costs",
23
+ "Metrics",
24
+ "PilotInputs",
25
+ "compute_metrics",
26
+ "js_round",
27
+ "sum_inputs",
28
+ "CSV_COLUMNS",
29
+ "OPTIONAL_COLUMNS",
30
+ "aggregate_weeks",
31
+ "parse_pilot_csv",
32
+ "GATE_DEFS",
33
+ "PilotDataError",
34
+ "evaluate_csv_text",
35
+ "evaluate_gates",
36
+ "evaluate_pilot_csv",
37
+ "evaluate_rows",
38
+ "load_config",
39
+ "verdict_for",
40
+ "PilotConfig",
41
+ "PilotReport",
42
+ ]
@@ -0,0 +1,296 @@
1
+ """Deterministic KPI maths: a line-for-line port of rovidence.com's metric engine.
2
+
3
+ Every formula here matches ``src/lib/metrics.ts`` in the Rovidence app and the public
4
+ methodology page (https://rovidence.com/methodology), so a pilot evaluated with this
5
+ package gives the same numbers as the Rovidence scorecard and report.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import math
11
+ from dataclasses import dataclass, field
12
+ from typing import Dict, Iterable, List, Optional
13
+
14
+ FAILURE_CAUSES = ("mechanical", "software", "connectivity", "thermal", "charging", "operator_override")
15
+ INTERVENTION_CAUSES = ("rescue", "exception_handling", "restock_support", "other")
16
+
17
+ CAUSE_LABELS: Dict[str, str] = {
18
+ "mechanical": "Mechanical",
19
+ "software": "Software",
20
+ "connectivity": "Connectivity",
21
+ "thermal": "Thermal faults",
22
+ "charging": "Charging",
23
+ "operator_override": "Operator override",
24
+ "rescue": "Rescue (stuck / lost robot)",
25
+ "exception_handling": "Exception handling (damaged / unreadable items)",
26
+ "restock_support": "Restock support",
27
+ "other": "Other",
28
+ }
29
+
30
+ DAYS_PER_MONTH = 30.4375
31
+ DEFAULT_MINUTES_PER_INTERVENTION = 2.0
32
+ DEFAULT_FTE_HOURS_PER_WEEK = 37.5
33
+
34
+ CauseCounts = Dict[str, float]
35
+
36
+
37
+ def js_round(value: float, dp: int = 0) -> float:
38
+ """Round like JavaScript's ``Math.round(v * 10**dp) / 10**dp`` (halves go up, toward +infinity).
39
+
40
+ Python's built-in ``round`` uses banker's rounding, which would make a gate pass here
41
+ and miss on rovidence.com for values that sit exactly on a half.
42
+ """
43
+ f = 10 ** dp
44
+ x = value * f
45
+ floor = math.floor(x)
46
+ return (floor + 1 if x - floor >= 0.5 else floor) / f
47
+
48
+
49
+ def _n(v: Optional[float]) -> float:
50
+ return v if _has(v) else 0.0
51
+
52
+
53
+ def _has(v: Optional[float]) -> bool:
54
+ return isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v)
55
+
56
+
57
+ @dataclass
58
+ class PilotInputs:
59
+ """Raw pilot inputs: one row, one week, or a sum of weeks. Fleet totals."""
60
+
61
+ operating_hours: float = 0.0 # required (scheduled) robot operating hours
62
+ assigned_tasks: float = 0.0
63
+ completed_tasks: float = 0.0
64
+ failures: float = 0.0
65
+ failure_causes: CauseCounts = field(default_factory=dict)
66
+ downtime_minutes: float = 0.0 # failure / stoppage downtime
67
+ repair_minutes: float = 0.0
68
+ interventions: float = 0.0
69
+ intervention_causes: CauseCounts = field(default_factory=dict)
70
+ charging_events: float = 0.0
71
+ charging_minutes_lost: float = 0.0
72
+ safety_events: float = 0.0
73
+ safety_check_downtime: float = 0.0 # minutes
74
+ support_labor_hours: float = 0.0
75
+
76
+
77
+ NUMERIC_FIELDS = (
78
+ "operating_hours", "assigned_tasks", "completed_tasks", "failures", "downtime_minutes", "repair_minutes",
79
+ "interventions", "charging_events", "charging_minutes_lost", "safety_events", "safety_check_downtime",
80
+ "support_labor_hours",
81
+ )
82
+
83
+
84
+ @dataclass
85
+ class Baseline:
86
+ manual_throughput_per_hour: Optional[float] = None # tasks per labour hour, manual process
87
+ error_rate_pct: Optional[float] = None
88
+ labor_hours_per_shift: Optional[float] = None
89
+ cycle_time_sec: Optional[float] = None
90
+ minutes_per_intervention: Optional[float] = None # operator time per intervention (default 2)
91
+ fte_hours_per_week: Optional[float] = None # hours in one full-time role (default 37.5)
92
+
93
+
94
+ @dataclass
95
+ class Costs:
96
+ robot_monthly_cost: Optional[float] = None # fleet lease / RaaS fee or capex amortisation, per month
97
+ integration_cost: Optional[float] = None # one-off
98
+ integration_amort_months: Optional[float] = None
99
+ maintenance_monthly: Optional[float] = None
100
+ labor_rate: Optional[float] = None # per hour, fully loaded
101
+ total_investment: Optional[float] = None # upfront, used for payback
102
+
103
+
104
+ @dataclass
105
+ class Metrics:
106
+ period_days: float
107
+ months: float
108
+ operating_hours: float
109
+ failures: float
110
+ uptime_hours: float
111
+ availability: Optional[float] # 0–1
112
+ mtbf: Optional[float] # hours
113
+ mttr: Optional[float] # minutes
114
+ mission_success: Optional[float] # 0–1
115
+ intervention_rate: Optional[float] # per 1,000 completed tasks
116
+ cost_per_task: Optional[float]
117
+ payback_months: Optional[float]
118
+ monthly_cost: Optional[float]
119
+ monthly_baseline_labor_cost: Optional[float]
120
+ monthly_benefit: Optional[float]
121
+ support_labor_cost: Optional[float]
122
+ lost_hours: Dict[str, float]
123
+
124
+
125
+ def add_causes(a: CauseCounts, b: CauseCounts) -> CauseCounts:
126
+ out = dict(a)
127
+ for k, v in b.items():
128
+ out[k] = out.get(k, 0) + _n(v)
129
+ return out
130
+
131
+
132
+ def sum_inputs(rows: Iterable[PilotInputs]) -> PilotInputs:
133
+ acc = PilotInputs()
134
+ for r in rows:
135
+ acc = PilotInputs(
136
+ **{f: getattr(acc, f) + _n(getattr(r, f)) for f in NUMERIC_FIELDS},
137
+ failure_causes=add_causes(acc.failure_causes, r.failure_causes or {}),
138
+ intervention_causes=add_causes(acc.intervention_causes, r.intervention_causes or {}),
139
+ )
140
+ return acc
141
+
142
+
143
+ def compute_metrics(inp: PilotInputs, costs: Costs, baseline: Baseline, period_days: float) -> Metrics:
144
+ """Compute Rovidence metrics for a period of ``period_days`` calendar days."""
145
+ months = period_days / DAYS_PER_MONTH
146
+ lost = {
147
+ "downtime": _n(inp.downtime_minutes) / 60,
148
+ "charging": _n(inp.charging_minutes_lost) / 60,
149
+ "safety_checks": _n(inp.safety_check_downtime) / 60,
150
+ }
151
+ uptime = max(0.0, inp.operating_hours - lost["downtime"] - lost["charging"] - lost["safety_checks"])
152
+ availability = uptime / inp.operating_hours if inp.operating_hours > 0 else None
153
+ mtbf = inp.operating_hours / inp.failures if inp.failures > 0 else None
154
+ mttr = inp.repair_minutes / inp.failures if inp.failures > 0 else None
155
+ mission_success = inp.completed_tasks / inp.assigned_tasks if inp.assigned_tasks > 0 else None
156
+ intervention_rate = inp.interventions / (inp.completed_tasks / 1000) if inp.completed_tasks > 0 else None
157
+
158
+ costs_known = _has(costs.robot_monthly_cost) and _has(costs.labor_rate)
159
+ support_labor_cost = inp.support_labor_hours * costs.labor_rate if _has(costs.labor_rate) else None
160
+ monthly_cost: Optional[float] = None
161
+ if costs_known and months > 0:
162
+ integration_monthly = (
163
+ costs.integration_cost / _n(costs.integration_amort_months)
164
+ if _has(costs.integration_cost) and _n(costs.integration_amort_months) > 0
165
+ else 0.0
166
+ )
167
+ monthly_cost = (
168
+ _n(costs.robot_monthly_cost) + integration_monthly + _n(costs.maintenance_monthly) + _n(support_labor_cost) / months
169
+ )
170
+ cost_per_task = (monthly_cost * months) / inp.completed_tasks if monthly_cost is not None and inp.completed_tasks > 0 else None
171
+
172
+ monthly_baseline: Optional[float] = None
173
+ monthly_benefit: Optional[float] = None
174
+ payback: Optional[float] = None
175
+ if monthly_cost is not None and _n(baseline.manual_throughput_per_hour) > 0 and _has(costs.labor_rate) and months > 0:
176
+ manual_hours = inp.completed_tasks / _n(baseline.manual_throughput_per_hour)
177
+ monthly_baseline = (manual_hours * costs.labor_rate) / months
178
+ monthly_benefit = monthly_baseline - monthly_cost
179
+ if _has(costs.total_investment) and monthly_benefit > 0:
180
+ payback = costs.total_investment / monthly_benefit
181
+
182
+ return Metrics(
183
+ period_days=period_days,
184
+ months=months,
185
+ operating_hours=inp.operating_hours,
186
+ failures=inp.failures,
187
+ uptime_hours=uptime,
188
+ availability=availability,
189
+ mtbf=mtbf,
190
+ mttr=mttr,
191
+ mission_success=mission_success,
192
+ intervention_rate=intervention_rate,
193
+ cost_per_task=cost_per_task,
194
+ payback_months=payback,
195
+ monthly_cost=monthly_cost,
196
+ monthly_baseline_labor_cost=monthly_baseline,
197
+ monthly_benefit=monthly_benefit,
198
+ support_labor_cost=support_labor_cost,
199
+ lost_hours=lost,
200
+ )
201
+
202
+
203
+ @dataclass
204
+ class InterventionBurden:
205
+ minutes_per_intervention: float
206
+ fte_hours_per_week: float
207
+ hours: float
208
+ weeks: int
209
+ fte_share: float
210
+
211
+
212
+ def intervention_burden(interventions: float, weeks: int, baseline: Baseline) -> Optional[InterventionBurden]:
213
+ """Interventions in human terms: operator hours, and the share of a full-time role they represent."""
214
+ if not interventions or not weeks:
215
+ return None
216
+ mpi = baseline.minutes_per_intervention if _has(baseline.minutes_per_intervention) and baseline.minutes_per_intervention > 0 else DEFAULT_MINUTES_PER_INTERVENTION
217
+ fte = baseline.fte_hours_per_week if _has(baseline.fte_hours_per_week) and baseline.fte_hours_per_week > 0 else DEFAULT_FTE_HOURS_PER_WEEK
218
+ hours = (interventions * mpi) / 60
219
+ return InterventionBurden(mpi, fte, hours, weeks, hours / (fte * weeks))
220
+
221
+
222
+ def _fmt_gb(v: float, max_dp: int = 3) -> str:
223
+ """Format like ``Number.toLocaleString("en-GB")``: thousands commas, up to 3 decimals, no trailing zeros."""
224
+ s = f"{js_round(v, max_dp):,.{max_dp}f}".rstrip("0").rstrip(".")
225
+ return s
226
+
227
+
228
+ def describe_burden(b: InterventionBurden) -> str:
229
+ mins = str(int(b.minutes_per_intervention)) if float(b.minutes_per_intervention).is_integer() else f"{b.minutes_per_intervention:.1f}"
230
+ hrs = _fmt_gb(js_round(b.hours))
231
+ share10 = js_round(b.fte_share * 10) / 10
232
+ if b.fte_share >= 0.95:
233
+ role = f"roughly {_fmt_gb(share10)} full-time role{'' if share10 == 1 else 's'}"
234
+ else:
235
+ role = f"roughly {max(1, int(js_round(b.fte_share * 100)))}% of a full-time role"
236
+ return (
237
+ f"At ~{mins} minute{'' if mins == '1' else 's'} per intervention, that's ~{hrs} hours of operator time over "
238
+ f"{b.weeks} week{'' if b.weeks == 1 else 's'} — {role} shifted onto your floor team."
239
+ )
240
+
241
+
242
+ def top_cause(causes: CauseCounts) -> Optional[dict]:
243
+ entries = [(k, v) for k, v in causes.items() if v > 0]
244
+ total = sum(v for _, v in entries)
245
+ if not total:
246
+ return None
247
+ entries.sort(key=lambda kv: -kv[1]) # stable, like Array.prototype.sort
248
+ k, v = entries[0]
249
+ return {"cause": k, "label": CAUSE_LABELS.get(k, k.replace("_", " ")), "count": v, "share": v / total, "total": total}
250
+
251
+
252
+ def breakdown(causes: CauseCounts) -> List[dict]:
253
+ total = sum(causes.values())
254
+ entries = sorted(((k, v) for k, v in causes.items() if v > 0), key=lambda kv: -kv[1])
255
+ return [
256
+ {"cause": k, "label": CAUSE_LABELS.get(k, k.replace("_", " ")), "count": v, "share": (v / total if total else 0)}
257
+ for k, v in entries
258
+ ]
259
+
260
+
261
+ def temp_band(avg_temp: Optional[float]) -> str:
262
+ if not _has(avg_temp):
263
+ return "Unknown"
264
+ if avg_temp < 25:
265
+ return "<25°C"
266
+ if avg_temp <= 30:
267
+ return "25–30°C"
268
+ return ">30°C"
269
+
270
+
271
+ METHODOLOGY = [
272
+ {
273
+ "metric": "Availability",
274
+ "formula": "uptime ÷ required operating time, where uptime = operating hours − downtime − charging time lost − safety-check downtime",
275
+ "note": "Exclusions: none. Charging and scheduled safety checks count against availability because the robot cannot work during them.",
276
+ },
277
+ {
278
+ "metric": "MTBF",
279
+ "formula": "operating hours ÷ number of failures",
280
+ "note": "Operating hours are fleet robot-hours of required operation. With no failures, MTBF is reported as at least the failure-free operating hours, and passes its gate once those hours reach it.",
281
+ },
282
+ {"metric": "MTTR", "formula": "total repair minutes ÷ number of failures", "note": "With no failures there is nothing to repair, and the MTTR gate passes."},
283
+ {"metric": "Mission success", "formula": "completed tasks ÷ assigned tasks"},
284
+ {"metric": "Intervention rate", "formula": "interventions ÷ (completed tasks ÷ 1,000)"},
285
+ {
286
+ "metric": "Cost per task",
287
+ "formula": "(robot cost + integration amortization + maintenance + support labour cost) ÷ completed tasks, over the measured period",
288
+ "note": "Support labour cost = support labour hours × fully loaded labour rate. Each week carries 7 days of cost, except a first or last week the pilot only partly covered.",
289
+ },
290
+ {
291
+ "metric": "Payback",
292
+ "formula": "total investment ÷ monthly measured benefit, where benefit = baseline labour cost for the same completed tasks − current total monthly cost",
293
+ "note": "Baseline labour cost = completed tasks ÷ manual throughput per labour hour × labour rate.",
294
+ },
295
+ ]
296
+
rovidence_eval/cli.py ADDED
@@ -0,0 +1,330 @@
1
+ """rovidence-eval command line: init, run, verify, push, schema."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import sys
8
+ import urllib.error
9
+ import urllib.request
10
+ from enum import Enum
11
+ from importlib import resources
12
+ from pathlib import Path
13
+ from typing import List, Optional
14
+
15
+ import typer
16
+ from pydantic import ValidationError
17
+ from rich.console import Console
18
+
19
+ from . import __version__
20
+ from .csvlog import CSV_COLUMNS, COLUMN_HELP, OPTIONAL_COLUMNS, parse_pilot_csv, rows_to_csv
21
+ from .evaluator import PilotDataError, evaluate_csv_text, load_config, report_digest, _canonical
22
+ from .report import render_table, to_json, to_markdown
23
+ from .schemas import PilotConfig, PilotReport
24
+
25
+ EXIT_GO, EXIT_NO_GO, EXIT_CONDITIONAL, EXIT_BAD_DATA, EXIT_NO_GATES, EXIT_USAGE = 0, 1, 2, 3, 4, 64
26
+ VERDICT_EXIT = {"GO": EXIT_GO, "NO_GO": EXIT_NO_GO, "CONDITIONAL_GO": EXIT_CONDITIONAL}
27
+ WEB_TOOL = "https://rovidence.com/tools/robot-pilot-evaluator"
28
+ DEFAULT_GATES = "acceptance_gates.yaml"
29
+ PUSH_MAX_ROWS = 250
30
+
31
+ app = typer.Typer(
32
+ add_completion=False,
33
+ no_args_is_help=True,
34
+ rich_markup_mode=None,
35
+ help=(
36
+ "Score a robot pilot against its acceptance gates using Rovidence's published methodology.\n\n"
37
+ f"Exit codes for `run`: 0 GO, 2 CONDITIONAL GO, 1 NO-GO, 3 invalid data, 4 no gates.\n\nPrefer a browser? {WEB_TOOL}"
38
+ ),
39
+ )
40
+ out = Console()
41
+ err = Console(stderr=True)
42
+
43
+
44
+ class Format(str, Enum):
45
+ table = "table"
46
+ json = "json"
47
+ markdown = "markdown"
48
+
49
+
50
+ def _version(value: bool) -> None:
51
+ if value:
52
+ out.print(f"rovidence-eval {__version__}")
53
+ raise typer.Exit()
54
+
55
+
56
+ @app.callback()
57
+ def _main(version: bool = typer.Option(False, "--version", callback=_version, is_eager=True, help="Show the version and exit.")) -> None:
58
+ pass
59
+
60
+
61
+ def _read_log(log: str) -> bytes:
62
+ if log == "-":
63
+ return sys.stdin.buffer.read()
64
+ p = Path(log)
65
+ if not p.is_file():
66
+ err.print(f"[red]No such file:[/red] {log}")
67
+ raise typer.Exit(EXIT_USAGE)
68
+ return p.read_bytes()
69
+
70
+
71
+ def _load_config(gates: Optional[Path]) -> PilotConfig:
72
+ path = gates
73
+ if path is None and Path(DEFAULT_GATES).is_file():
74
+ path = Path(DEFAULT_GATES)
75
+ if path is None:
76
+ return PilotConfig()
77
+ if not path.is_file():
78
+ err.print(f"[red]No such file:[/red] {path}")
79
+ raise typer.Exit(EXIT_USAGE)
80
+ try:
81
+ return load_config(path)
82
+ except ValidationError as e:
83
+ err.print(f"[red]{path} is not a valid pilot config:[/red]")
84
+ for x in e.errors():
85
+ loc = ".".join(str(p) for p in x["loc"])
86
+ hint = " (unknown key — check the spelling; `rovidence-eval schema config` lists every key)" if x["type"] == "extra_forbidden" else ""
87
+ err.print(f" {loc}: {x['msg']}{hint}")
88
+ raise typer.Exit(EXIT_BAD_DATA)
89
+ except Exception as e: # YAML/JSON syntax
90
+ err.print(f"[red]Could not read {path}:[/red] {e}")
91
+ raise typer.Exit(EXIT_BAD_DATA)
92
+
93
+
94
+ def _print_data_errors(e: PilotDataError, source: str) -> None:
95
+ err.print(f"[red]{source} failed validation ({len(e.errors)} problem{'s' if len(e.errors) != 1 else ''}). Nothing was evaluated.[/red]")
96
+ for line in e.errors[:50]:
97
+ err.print(f" {line}", highlight=False)
98
+ if len(e.errors) > 50:
99
+ err.print(f" … and {len(e.errors) - 50} more")
100
+ if e.result.missing_columns:
101
+ err.print("Run `rovidence-eval schema columns` to see the expected columns.")
102
+
103
+
104
+ @app.command()
105
+ def run(
106
+ log: str = typer.Argument(..., help="Pilot log CSV (one row per shift or day). Use - for stdin."),
107
+ gates: Optional[Path] = typer.Option(None, "--gates", "-g", help=f"Pilot config YAML/JSON. Defaults to ./{DEFAULT_GATES} if present."),
108
+ fmt: Format = typer.Option(Format.table, "--format", "-f", help="Output on stdout."),
109
+ out_path: Optional[Path] = typer.Option(None, "--out", "-o", help="Also write the report to a file: .md for Markdown, anything else JSON."),
110
+ weeks: bool = typer.Option(False, "--weeks", "-w", help="Show the week-by-week table (table format)."),
111
+ ) -> None:
112
+ """Evaluate a pilot log against its acceptance gates and print a Go/No-Go scorecard."""
113
+ raw = _read_log(log)
114
+ config = _load_config(gates)
115
+ try:
116
+ report = evaluate_csv_text(raw.decode("utf-8-sig"), config, input_bytes=raw)
117
+ except UnicodeDecodeError:
118
+ err.print("[red]The log isn't UTF-8 text. Export it from Excel as 'CSV UTF-8'.[/red]")
119
+ raise typer.Exit(EXIT_BAD_DATA)
120
+ except PilotDataError as e:
121
+ _print_data_errors(e, "stdin" if log == "-" else log)
122
+ raise typer.Exit(EXIT_BAD_DATA)
123
+
124
+ if fmt is Format.json:
125
+ sys.stdout.write(to_json(report))
126
+ elif fmt is Format.markdown:
127
+ sys.stdout.write(to_markdown(report))
128
+ else:
129
+ render_table(report, out, show_weeks=weeks)
130
+ if out_path:
131
+ out_path.write_text(to_markdown(report) if out_path.suffix.lower() in (".md", ".markdown") else to_json(report), encoding="utf-8")
132
+ err.print(f"Report written to {out_path}", style="dim")
133
+ global _verdict_exit
134
+ _verdict_exit = True
135
+ if report.verdict is None:
136
+ raise typer.Exit(EXIT_NO_GATES)
137
+ raise typer.Exit(VERDICT_EXIT[report.verdict])
138
+
139
+
140
+ @app.command()
141
+ def init(
142
+ directory: Path = typer.Argument(Path("."), help="Where to write the files."),
143
+ blank: bool = typer.Option(False, "--blank", help="Write an empty log template and gates skeleton instead of the sample pilot."),
144
+ force: bool = typer.Option(False, "--force", help="Overwrite existing files."),
145
+ ) -> None:
146
+ """Write a starter acceptance_gates.yaml and pilot log CSV."""
147
+ directory.mkdir(parents=True, exist_ok=True)
148
+ files = {
149
+ DEFAULT_GATES: _resource("blank_gates.yaml" if blank else "acceptance_gates.yaml"),
150
+ "pilot_log.csv" if blank else "sample_pilot_log.csv": ",".join([*CSV_COLUMNS, *OPTIONAL_COLUMNS]) + "\n" if blank else _resource("sample_pilot_log.csv"),
151
+ }
152
+ for name, content in files.items():
153
+ p = directory / name
154
+ if p.exists() and not force:
155
+ err.print(f"[yellow]Skipped {p}: it already exists (use --force to overwrite).[/yellow]")
156
+ continue
157
+ p.write_text(content, encoding="utf-8")
158
+ out.print(f"Wrote {p}")
159
+ if not blank:
160
+ out.print("\nTry it: rovidence-eval run sample_pilot_log.csv --gates acceptance_gates.yaml")
161
+ out.print("The sample is generated demo data for a 12-week AMR pilot (it reproduces rovidence.com/sample-report).", style="dim")
162
+
163
+
164
+ def _resource(name: str) -> str:
165
+ return resources.files("rovidence_eval").joinpath("data").joinpath(name).read_text(encoding="utf-8")
166
+
167
+
168
+ @app.command()
169
+ def verify(
170
+ report_path: Path = typer.Argument(..., help="A JSON report written by `run --out` or the web tool."),
171
+ log: Optional[str] = typer.Option(None, "--log", "-l", help="The pilot log the report claims to be built from."),
172
+ gates: Optional[Path] = typer.Option(None, "--gates", "-g", help="Config to re-run with. Defaults to the config embedded in the report."),
173
+ ) -> None:
174
+ """Check a report hasn't been edited, and (with --log) that it reproduces from the log."""
175
+ try:
176
+ raw_json = json.loads(report_path.read_text(encoding="utf-8"))
177
+ report = PilotReport.model_validate(raw_json)
178
+ except Exception as e:
179
+ err.print(f"[red]Not a rovidence-eval report:[/red] {e}")
180
+ raise typer.Exit(EXIT_BAD_DATA)
181
+ ok = True
182
+ if not report.integrity or report.integrity.report_sha256 != report_digest(raw_json):
183
+ err.print("[red]✗ Report hash does not match its contents: the report was edited after it was generated.[/red]")
184
+ ok = False
185
+ else:
186
+ out.print("✓ Report hash matches its contents.")
187
+ embedded_config = PilotConfig.model_validate(report.config)
188
+ expected_config_hash = hashlib.sha256(_canonical(embedded_config.model_dump(mode="json"))).hexdigest()
189
+ if not report.integrity or report.integrity.config_sha256 != expected_config_hash:
190
+ err.print("[red]✗ Config hash does not match the report's config.[/red]")
191
+ ok = False
192
+ if log:
193
+ raw = _read_log(log)
194
+ if report.integrity and report.integrity.input_sha256 and report.integrity.input_sha256 != hashlib.sha256(raw).hexdigest():
195
+ err.print("[red]✗ The log's SHA-256 differs from the one in the report: this is not the same file.[/red]")
196
+ ok = False
197
+ config = _load_config(gates) if gates else PilotConfig.model_validate(report.config)
198
+ try:
199
+ again = evaluate_csv_text(raw.decode("utf-8-sig"), config, input_bytes=raw)
200
+ except PilotDataError as e:
201
+ _print_data_errors(e, log)
202
+ raise typer.Exit(EXIT_BAD_DATA)
203
+ original = report.model_dump(mode="json", by_alias=True)
204
+ reproduced = again.model_dump(mode="json", by_alias=True)
205
+ # These describe the producer, not the evaluated pilot. All other fields must reproduce.
206
+ excluded = {"tool", "generated_at", "evidence_note", "integrity"}
207
+ differences = [key for key in original if key not in excluded and original[key] != reproduced[key]]
208
+ if not differences:
209
+ out.print(f"✓ Re-running the log gives the same verdict ({again.verdict_label}) and all calculated report results.")
210
+ else:
211
+ err.print(f"[red]✗ Re-running the log differs in: {', '.join(differences)}.[/red]")
212
+ ok = False
213
+ raise typer.Exit(0 if ok else 1)
214
+
215
+
216
+ @app.command()
217
+ def push(
218
+ log: str = typer.Argument(..., help="Pilot log CSV to send to your Rovidence evaluation."),
219
+ api_key: Optional[str] = typer.Option(None, "--api-key", envvar="ROVIDENCE_API_KEY", help="Evaluation API key (or set ROVIDENCE_API_KEY)."),
220
+ url: str = typer.Option("https://rovidence.com", "--url", envvar="ROVIDENCE_URL", help="Rovidence base URL."),
221
+ mapping: Optional[str] = typer.Option(None, "--mapping", help="Name of a column mapping saved in Rovidence; sends the file as-is."),
222
+ dry_run: bool = typer.Option(False, "--dry-run", help="Validate and show what would be sent, without sending."),
223
+ ) -> None:
224
+ """Send pilot rows to a private Rovidence evaluation via the upload API.
225
+
226
+ Rows go to the one evaluation the key belongs to; nothing is published. Create a key on the
227
+ evaluation's scorecard page. Resending the same rows is safe (same date and shift replaces).
228
+ """
229
+ raw = _read_log(log)
230
+ text = raw.decode("utf-8-sig")
231
+ if mapping:
232
+ lines = text.strip().splitlines()
233
+ header, body = lines[0], [x for x in lines[1:] if x.strip()]
234
+ chunks = ["\n".join([header, *body[i : i + PUSH_MAX_ROWS]]) + "\n" for i in range(0, len(body), PUSH_MAX_ROWS)]
235
+ else:
236
+ parsed = parse_pilot_csv(text)
237
+ if not parsed.ok or not parsed.rows:
238
+ if parsed.ok:
239
+ parsed.errors.append("No data rows.")
240
+ _print_data_errors(PilotDataError(parsed), log)
241
+ raise typer.Exit(EXIT_BAD_DATA)
242
+ chunks = [rows_to_csv(parsed.rows[i : i + PUSH_MAX_ROWS]) for i in range(0, len(parsed.rows), PUSH_MAX_ROWS)]
243
+ endpoint = url.rstrip("/") + "/api/v1/pilot-data"
244
+ out.print(f"{len(chunks)} request{'s' if len(chunks) != 1 else ''} to {endpoint}")
245
+ if dry_run:
246
+ raise typer.Exit(0)
247
+ if not api_key:
248
+ err.print("[red]No API key. Pass --api-key or set ROVIDENCE_API_KEY.[/red]")
249
+ raise typer.Exit(EXIT_USAGE)
250
+ for i, chunk in enumerate(chunks, 1):
251
+ headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "text/csv", "X-Source-System": f"rovidence-eval/{__version__}"}
252
+ if mapping:
253
+ headers["X-Rovidence-Mapping"] = mapping
254
+ req = urllib.request.Request(endpoint, data=chunk.encode("utf-8"), headers=headers, method="POST")
255
+ try:
256
+ with urllib.request.urlopen(req, timeout=60) as resp:
257
+ body = json.loads(resp.read().decode("utf-8") or "{}")
258
+ except urllib.error.HTTPError as e:
259
+ try:
260
+ body = json.loads(e.read().decode("utf-8") or "{}")
261
+ except ValueError:
262
+ body = {}
263
+ err.print(f"[red]Request {i} rejected ({e.code}): {body.get('error', e.reason)}[/red]")
264
+ for d in body.get("details", []):
265
+ err.print(f" {d}")
266
+ raise typer.Exit(1)
267
+ except urllib.error.URLError as e:
268
+ err.print(f"[red]Could not reach {endpoint}: {e.reason}[/red]")
269
+ raise typer.Exit(1)
270
+ out.print(f" {i}/{len(chunks)}: stored {body.get('rowsStored')} rows; weeks updated {body.get('weeksUpdated')}")
271
+
272
+
273
+ class SchemaKind(str, Enum):
274
+ config = "config"
275
+ columns = "columns"
276
+ report = "report"
277
+
278
+
279
+ @app.command()
280
+ def schema(kind: SchemaKind = typer.Argument(SchemaKind.columns, help="columns (the CSV), config (acceptance_gates.yaml) or report (JSON output).")) -> None:
281
+ """Print the JSON Schema for the pilot log columns, the config, or the report."""
282
+ if kind is SchemaKind.config:
283
+ doc = PilotConfig.model_json_schema(by_alias=False)
284
+ elif kind is SchemaKind.report:
285
+ doc = PilotReport.model_json_schema(by_alias=True)
286
+ else:
287
+ doc = log_row_schema()
288
+ sys.stdout.write(json.dumps(doc, indent=2, ensure_ascii=False) + "\n")
289
+
290
+
291
+ def log_row_schema() -> dict:
292
+ integer = {"assigned_tasks", "completed_tasks", "failures", "interventions", "charging_events", "safety_events"}
293
+ props = {}
294
+ for c in [*CSV_COLUMNS, *OPTIONAL_COLUMNS]:
295
+ if c == "date":
296
+ props[c] = {"type": "string", "format": "date", "description": COLUMN_HELP[c]}
297
+ elif c in ("shift", "failure_causes", "intervention_causes"):
298
+ props[c] = {"type": "string", "description": COLUMN_HELP[c]}
299
+ elif c == "ambient_temp_c":
300
+ props[c] = {"type": ["number", "null"], "description": COLUMN_HELP[c]}
301
+ else:
302
+ props[c] = {"type": "integer" if c in integer else "number", "minimum": 0, "description": COLUMN_HELP[c]}
303
+ props["operating_hours"]["exclusiveMinimum"] = 0
304
+ props["operating_hours"].pop("minimum")
305
+ return {
306
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
307
+ "title": "Rovidence pilot log row",
308
+ "description": "One row of a pilot log CSV: one shift or one day, fleet totals. Same format as the Rovidence scorecard import.",
309
+ "type": "object",
310
+ "required": list(CSV_COLUMNS),
311
+ "properties": props,
312
+ }
313
+
314
+
315
+ _verdict_exit = False
316
+
317
+
318
+ def main(argv: Optional[List[str]] = None) -> None:
319
+ """Entry point. Command-line usage errors exit 64, so they never look like CONDITIONAL GO (2)."""
320
+ try:
321
+ app(args=argv, prog_name="rovidence-eval")
322
+ except SystemExit as e:
323
+ code = e.code if isinstance(e.code, int) else (0 if e.code is None else 1)
324
+ if code == 2 and not _verdict_exit:
325
+ code = EXIT_USAGE
326
+ sys.exit(code)
327
+
328
+
329
+ if __name__ == "__main__": # pragma: no cover
330
+ main()