humanbaselines 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,89 @@
1
+ """humanbaselines — Python client for the Human Crash Baselines API.
2
+
3
+ >>> from humanbaselines import HumanBaselines
4
+ >>> hb = HumanBaselines(api_key="hbk_...") # or env HUMANBASELINES_API_KEY
5
+ >>> hb.compute(outcome="police_reported").rate
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ __version__ = "0.1.0"
11
+
12
+ from .client import HumanBaselines
13
+ from .exceptions import (
14
+ APIError,
15
+ AuthenticationError,
16
+ HumanBaselinesError,
17
+ NotFoundError,
18
+ ServiceUnavailableError,
19
+ ValidationError,
20
+ )
21
+ from .models import (
22
+ CiMethod,
23
+ ComputeResult,
24
+ DepotComputeResult,
25
+ DepotPin,
26
+ DepotSelections,
27
+ DriverImpairment,
28
+ FilterDef,
29
+ FilterOption,
30
+ FiltersResponse,
31
+ GeofenceSelections,
32
+ InTransport,
33
+ LightFilter,
34
+ MultiplierVmt,
35
+ Outcome,
36
+ PerCellResult,
37
+ PerSegmentResult,
38
+ RegionInfo,
39
+ RegionsResponse,
40
+ RoadGroup,
41
+ RoboTaxiWeighting,
42
+ RouteComputeResult,
43
+ RouteSelections,
44
+ Tier3Mode,
45
+ UnderReporting,
46
+ VehicleClass,
47
+ WeatherFilter,
48
+ )
49
+
50
+ __all__ = [
51
+ "__version__",
52
+ "HumanBaselines",
53
+ # exceptions
54
+ "HumanBaselinesError",
55
+ "APIError",
56
+ "AuthenticationError",
57
+ "ValidationError",
58
+ "NotFoundError",
59
+ "ServiceUnavailableError",
60
+ # request models
61
+ "GeofenceSelections",
62
+ "RouteSelections",
63
+ "DepotSelections",
64
+ "DepotPin",
65
+ # response models
66
+ "ComputeResult",
67
+ "PerCellResult",
68
+ "RouteComputeResult",
69
+ "PerSegmentResult",
70
+ "DepotComputeResult",
71
+ "FiltersResponse",
72
+ "FilterDef",
73
+ "FilterOption",
74
+ "RegionsResponse",
75
+ "RegionInfo",
76
+ # enums
77
+ "Outcome",
78
+ "VehicleClass",
79
+ "RoadGroup",
80
+ "Tier3Mode",
81
+ "InTransport",
82
+ "RoboTaxiWeighting",
83
+ "MultiplierVmt",
84
+ "UnderReporting",
85
+ "WeatherFilter",
86
+ "LightFilter",
87
+ "DriverImpairment",
88
+ "CiMethod",
89
+ ]
@@ -0,0 +1,322 @@
1
+ # AUTO-GENERATED -- DO NOT EDIT.
2
+ # Generated from the live Human Crash Baselines OpenAPI schema by
3
+ # scripts/regenerate_models.py.
4
+ # Re-run that script after any API contract change.
5
+
6
+ # generated by datamodel-codegen:
7
+ # filename: humanbaselines_openapi.json
8
+
9
+ from __future__ import annotations
10
+
11
+ from enum import Enum
12
+ from typing import Any
13
+
14
+ from pydantic import BaseModel, ConfigDict, Field, RootModel
15
+
16
+
17
+ class AccessLogRequest(BaseModel):
18
+ email: str = Field(..., title='Email')
19
+ allowed: bool = Field(..., title='Allowed')
20
+
21
+
22
+ class CiMethod(Enum):
23
+ fay_feuer = 'fay_feuer'
24
+ empirical_bayes = 'empirical_bayes'
25
+
26
+
27
+ class ComputeRequest(BaseModel):
28
+ county: str = Field('travis', title='County')
29
+ selections: dict[str, Any] | None = Field(None, title='Selections')
30
+ cell_filter: list[str] | None = Field(None, title='Cell Filter')
31
+
32
+
33
+ class SegmentId(RootModel[tuple[str, int]]):
34
+ root: tuple[str, int] = Field(..., max_length=2, min_length=2)
35
+
36
+
37
+ class ComputeRouteRequest(BaseModel):
38
+ county: str = Field('travis', title='County')
39
+ segment_ids: list[SegmentId] = Field(..., title='Segment Ids')
40
+ selections: dict[str, Any] | None = Field(None, title='Selections')
41
+
42
+
43
+ class DenominatorVmt(Enum):
44
+ calibrated = 'calibrated'
45
+ hpms = 'hpms'
46
+
47
+
48
+ class DepotComputeResult(BaseModel):
49
+ model_config = ConfigDict(
50
+ extra='allow',
51
+ )
52
+
53
+
54
+ class DepotPin(BaseModel):
55
+ lat: float = Field(..., title='Lat')
56
+ lon: float = Field(..., title='Lon')
57
+
58
+
59
+ class DriverImpairment(Enum):
60
+ any = 'any'
61
+ exclude_impaired = 'exclude_impaired'
62
+ impaired_only = 'impaired_only'
63
+
64
+
65
+ class FilterOption(BaseModel):
66
+ id: str = Field(..., title='Id')
67
+ label: str = Field(..., title='Label')
68
+
69
+
70
+ class InTransport(Enum):
71
+ in_transport = 'in_transport'
72
+ include_all = 'include_all'
73
+
74
+
75
+ class LightFilter(Enum):
76
+ any = 'any'
77
+ daylight = 'daylight'
78
+ dawn_dusk = 'dawn_dusk'
79
+ dark = 'dark'
80
+
81
+
82
+ class MultiplierVmt(Enum):
83
+ calibrated = 'calibrated'
84
+ hpms = 'hpms'
85
+
86
+
87
+ class Outcome(Enum):
88
+ police_reported = 'police_reported'
89
+ observed_any_injury = 'observed_any_injury'
90
+ airbag = 'airbag'
91
+ ego_airbag = 'ego_airbag'
92
+ ka = 'ka'
93
+ fatal = 'fatal'
94
+
95
+
96
+ class PerCellResult(BaseModel):
97
+ model_config = ConfigDict(
98
+ extra='allow',
99
+ )
100
+ s2_cell: str = Field(..., title='S2 Cell')
101
+ count: float = Field(..., title='Count')
102
+ vmt: float = Field(..., title='Vmt')
103
+ mult_contrib: float = Field(0.0, title='Mult Contrib')
104
+
105
+
106
+ class PerSegmentResult(BaseModel):
107
+ model_config = ConfigDict(
108
+ extra='allow',
109
+ )
110
+ route: str = Field(..., title='Route')
111
+ milepost: int = Field(..., title='Milepost')
112
+ count: float = Field(..., title='Count')
113
+ vmt: float = Field(..., title='Vmt')
114
+ length_mi: float = Field(..., title='Length Mi')
115
+
116
+
117
+ class RegionInfo(BaseModel):
118
+ county: str = Field(..., title='County')
119
+ modes: list[str] = Field(..., title='Modes')
120
+
121
+
122
+ class RegionsResponse(BaseModel):
123
+ regions: list[RegionInfo] = Field(..., title='Regions')
124
+ default_county: str = Field('travis', title='Default County')
125
+
126
+
127
+ class RoadGroup(Enum):
128
+ interstate = 'interstate'
129
+ other_freeway = 'other_freeway'
130
+ arterial = 'arterial'
131
+ collector_local = 'collector_local'
132
+
133
+
134
+ class RoboTaxiWeighting(Enum):
135
+ county_wide = 'county_wide'
136
+ operator_weighted = 'operator_weighted'
137
+
138
+
139
+ class RouteComputeResult(BaseModel):
140
+ model_config = ConfigDict(
141
+ extra='allow',
142
+ )
143
+ N: float = Field(..., title='N')
144
+ trip_miles: float = Field(..., title='Trip Miles')
145
+ rate: float = Field(..., title='Rate')
146
+ rate_low: float | None = Field(None, title='Rate Low')
147
+ rate_high: float | None = Field(None, title='Rate High')
148
+ variance: float | None = Field(None, title='Variance')
149
+ segments: list[PerSegmentResult] | None = Field(None, title='Segments')
150
+
151
+
152
+ class Tier3Mode(Enum):
153
+ marginal = 'marginal'
154
+ none = 'none'
155
+ all = 'all'
156
+
157
+
158
+ class UnderReporting(Enum):
159
+ none = 'none'
160
+ adjusted = 'adjusted'
161
+
162
+
163
+ class ValidationError(BaseModel):
164
+ loc: list[str | int] = Field(..., title='Location')
165
+ msg: str = Field(..., title='Message')
166
+ type: str = Field(..., title='Error Type')
167
+ input: Any | None = Field(None, title='Input')
168
+ ctx: dict[str, Any] | None = Field(None, title='Context')
169
+
170
+
171
+ class VehicleClass(Enum):
172
+ cars = 'cars'
173
+ light_trucks = 'light_trucks'
174
+ heavy_trucks = 'heavy_trucks'
175
+ motorcycles = 'motorcycles'
176
+ buses = 'buses'
177
+ other = 'other'
178
+
179
+
180
+ class WeatherFilter(Enum):
181
+ any = 'any'
182
+ dry = 'dry'
183
+ rain = 'rain'
184
+ fog = 'fog'
185
+ winter_storm = 'winter_storm'
186
+
187
+
188
+ class ComputeDepotRouteRequest(BaseModel):
189
+ county: str = Field('travis', title='County')
190
+ depot_a: DepotPin
191
+ depot_b: DepotPin
192
+ selections: dict[str, Any] | None = Field(None, title='Selections')
193
+
194
+
195
+ class ComputeResult(BaseModel):
196
+ model_config = ConfigDict(
197
+ extra='allow',
198
+ )
199
+ N: float = Field(..., title='N')
200
+ D_miles: float = Field(..., title='D Miles')
201
+ D_billions: float = Field(..., title='D Billions')
202
+ rate: float = Field(..., title='Rate')
203
+ rate_low: float | None = Field(None, title='Rate Low')
204
+ rate_high: float | None = Field(None, title='Rate High')
205
+ rate_non_dyn: float = Field(..., title='Rate Non Dyn')
206
+ rate_dyn: float | None = Field(None, title='Rate Dyn')
207
+ multiplier: float | None = Field(None, title='Multiplier')
208
+ cells: list[PerCellResult] | None = Field(None, title='Cells')
209
+
210
+
211
+ class DepotSelections(BaseModel):
212
+ model_config = ConfigDict(
213
+ extra='forbid',
214
+ )
215
+ outcome: Outcome = 'police_reported'
216
+ severity: int = Field(1, ge=1, le=7, title='Severity')
217
+ ego_vehicle: list[VehicleClass] | VehicleClass = Field(
218
+ ['combination'], title='Ego Vehicle'
219
+ )
220
+ unresolved_nfs: Tier3Mode = 'marginal'
221
+ in_transport: InTransport = 'in_transport'
222
+ weather: list[WeatherFilter] | WeatherFilter = Field(
223
+ ['dry', 'rain', 'fog'], title='Weather'
224
+ )
225
+ light_condition: list[LightFilter] | LightFilter = Field(
226
+ 'any', title='Light Condition'
227
+ )
228
+ driver_impairment: DriverImpairment = 'any'
229
+ under_reporting: UnderReporting = 'none'
230
+ ci_method: CiMethod = 'empirical_bayes'
231
+
232
+
233
+ class FilterDef(BaseModel):
234
+ model_config = ConfigDict(
235
+ extra='allow',
236
+ )
237
+ id: str = Field(..., title='Id')
238
+ label: str = Field(..., title='Label')
239
+ affects: str = Field(..., title='Affects')
240
+ multiselect: bool = Field(..., title='Multiselect')
241
+ description: str = Field(..., title='Description')
242
+ options: list[FilterOption] = Field(..., title='Options')
243
+ default: Any | None = Field(None, title='Default')
244
+
245
+
246
+ class FiltersResponse(BaseModel):
247
+ modes: dict[str, list[FilterDef]] = Field(..., title='Modes')
248
+
249
+
250
+ class GeofenceSelections(BaseModel):
251
+ model_config = ConfigDict(
252
+ extra='forbid',
253
+ )
254
+ outcome: Outcome = 'police_reported'
255
+ severity: int = Field(1, ge=1, le=7, title='Severity')
256
+ ego_vehicle: list[VehicleClass] | VehicleClass = Field(
257
+ ['cars', 'light_trucks'], title='Ego Vehicle'
258
+ )
259
+ unresolved_nfs: Tier3Mode = 'marginal'
260
+ in_transport: InTransport = 'in_transport'
261
+ road_type: list[RoadGroup] | RoadGroup = Field(
262
+ ['arterial', 'collector_local'], title='Road Type'
263
+ )
264
+ robo_taxi_weighting: RoboTaxiWeighting = 'county_wide'
265
+ multiplier_vmt: MultiplierVmt = 'calibrated'
266
+ denominator_vmt: DenominatorVmt = 'calibrated'
267
+ under_reporting: UnderReporting = 'none'
268
+ weather: list[WeatherFilter] | WeatherFilter = Field(
269
+ ['dry', 'rain', 'fog'], title='Weather'
270
+ )
271
+ light_condition: list[LightFilter] | LightFilter = Field(
272
+ 'any', title='Light Condition'
273
+ )
274
+ crash_year: list[int] | int = Field([2022], title='Crash Year')
275
+
276
+
277
+ class HTTPValidationError(BaseModel):
278
+ detail: list[ValidationError] | None = Field(None, title='Detail')
279
+
280
+
281
+ class RouteSelections(BaseModel):
282
+ model_config = ConfigDict(
283
+ extra='forbid',
284
+ )
285
+ outcome: Outcome = 'police_reported'
286
+ severity: int = Field(1, ge=1, le=7, title='Severity')
287
+ ego_vehicle: list[VehicleClass] | VehicleClass = Field(
288
+ ['combination'], title='Ego Vehicle'
289
+ )
290
+ unresolved_nfs: Tier3Mode = 'marginal'
291
+ in_transport: InTransport = 'in_transport'
292
+ weather: list[WeatherFilter] | WeatherFilter = Field(
293
+ ['dry', 'rain', 'fog'], title='Weather'
294
+ )
295
+ light_condition: list[LightFilter] | LightFilter = Field(
296
+ 'any', title='Light Condition'
297
+ )
298
+ driver_impairment: DriverImpairment = 'any'
299
+ under_reporting: UnderReporting = 'none'
300
+ ci_method: CiMethod = 'fay_feuer'
301
+
302
+
303
+ class V1ComputeRequest(BaseModel):
304
+ county: str = Field('travis', title='County')
305
+ selections: GeofenceSelections | None = None
306
+
307
+
308
+ class V1DepotRequest(BaseModel):
309
+ county: str = Field('travis', title='County')
310
+ depot_a: DepotPin
311
+ depot_b: DepotPin
312
+ selections: DepotSelections | None = None
313
+
314
+
315
+ class V1RouteRequest(BaseModel):
316
+ county: str = Field('travis', title='County')
317
+ segment_ids: list[SegmentId] = Field(
318
+ ...,
319
+ description='Ordered [route, milepost] pairs, e.g. [["I-35", 250], ["I-35", 251]].',
320
+ title='Segment Ids',
321
+ )
322
+ selections: RouteSelections | None = None
@@ -0,0 +1,351 @@
1
+ """Synchronous client for the Human Crash Baselines API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ import requests
11
+ from requests.adapters import HTTPAdapter
12
+ from urllib3.util.retry import Retry
13
+
14
+ from .exceptions import (
15
+ APIError,
16
+ AuthenticationError,
17
+ NotFoundError,
18
+ ServiceUnavailableError,
19
+ ValidationError,
20
+ )
21
+ from .models import (
22
+ DEFAULT_COUNTY,
23
+ ComputeResult,
24
+ DepotComputeResult,
25
+ DepotPin,
26
+ DepotSelections,
27
+ FiltersResponse,
28
+ GeofenceSelections,
29
+ RegionsResponse,
30
+ RouteComputeResult,
31
+ RouteSelections,
32
+ )
33
+
34
+ DEFAULT_BASE_URL = "https://humanbaselines.com"
35
+
36
+ # tuple/list of (lat, lon), a DepotPin, or a {"lat","lon"} dict
37
+ PinLike = tuple[float, float] | list[float] | DepotPin | dict
38
+
39
+ _MODE_MODELS = {
40
+ "geofence": GeofenceSelections,
41
+ "route": RouteSelections,
42
+ "depot": DepotSelections,
43
+ }
44
+ # Every valid key a bound config may carry: "county" plus the union of all
45
+ # modes' selection fields.
46
+ _KNOWN_CONFIG_KEYS = {"county"} | {
47
+ f for m in _MODE_MODELS.values() for f in m.model_fields
48
+ }
49
+
50
+
51
+ class HumanBaselines:
52
+ """Client for the Human Crash Baselines `/v1` API.
53
+
54
+ >>> hb = HumanBaselines(api_key="hbk_...") # or env HUMANBASELINES_API_KEY
55
+ >>> hb.compute(outcome="police_reported").rate
56
+ 4.05
57
+ >>> hb.filters().modes.keys()
58
+ dict_keys(['geofence', 'route', 'depot'])
59
+
60
+ Args:
61
+ api_key: your API key. Falls back to the ``HUMANBASELINES_API_KEY``
62
+ env var. Sent as the ``X-API-Key`` header.
63
+ base_url: API host. Defaults to https://humanbaselines.com (which
64
+ proxies ``/v1/*``). Point at the Cloud Run URL for non-/v1
65
+ paths like ``/health``.
66
+ timeout: per-request timeout in seconds.
67
+ max_retries: automatic retries for transient 5xx / 503 warm-up, with
68
+ exponential backoff.
69
+ session: bring your own ``requests.Session`` (otherwise one is made).
70
+ config: a baseline definition bound to this client — a dict of
71
+ ``"county"`` plus any filter fields, OR a path to a JSON file
72
+ written by ``save_config`` (a ``"mode"`` key is ignored).
73
+ Every ``compute*`` call inherits it (each mode uses the
74
+ subset of fields it understands); per-call args override it.
75
+ Validated here, so bad fields/values fail fast.
76
+ """
77
+
78
+ def __init__(
79
+ self,
80
+ api_key: str | None = None,
81
+ *,
82
+ base_url: str = DEFAULT_BASE_URL,
83
+ timeout: float = 30.0,
84
+ max_retries: int = 2,
85
+ session: requests.Session | None = None,
86
+ config: dict | str | Path | None = None,
87
+ ):
88
+ api_key = api_key or os.environ.get("HUMANBASELINES_API_KEY")
89
+ if not api_key:
90
+ raise ValueError(
91
+ "API key required: pass api_key=... or set HUMANBASELINES_API_KEY."
92
+ )
93
+ # Retained so with_config() can rebuild a sibling client.
94
+ self._api_key = api_key
95
+ self._base_url = base_url
96
+ self._timeout = timeout
97
+ self._max_retries = max_retries
98
+
99
+ self._root = base_url.rstrip("/")
100
+ self._v1 = f"{self._root}/v1"
101
+ self._config = self._validate_config(self._load_config(config))
102
+
103
+ self._session = session or requests.Session()
104
+ self._session.headers.update({"X-API-Key": api_key})
105
+ retry = Retry(
106
+ total=max_retries,
107
+ backoff_factor=0.5,
108
+ status_forcelist=(502, 503, 504),
109
+ allowed_methods=frozenset(["GET", "POST"]),
110
+ raise_on_status=False,
111
+ )
112
+ adapter = HTTPAdapter(max_retries=retry)
113
+ self._session.mount("https://", adapter)
114
+ self._session.mount("http://", adapter)
115
+
116
+ @staticmethod
117
+ def _load_config(config: dict | str | Path | None) -> dict:
118
+ """Normalize the `config=` argument into a plain dict. Accepts a dict, a
119
+ path to a JSON file (written by save_config), or None. A top-level
120
+ ``"mode"`` key (save_config metadata) is stripped."""
121
+ if config is None:
122
+ return {}
123
+ if isinstance(config, (str, Path)):
124
+ config = json.loads(Path(config).read_text())
125
+ if not isinstance(config, dict):
126
+ raise TypeError(f"config must be a dict, path, or None (got {type(config).__name__})")
127
+ return {k: v for k, v in config.items() if k != "mode"}
128
+
129
+ @staticmethod
130
+ def _validate_config(config: dict) -> dict:
131
+ """Validate a bound config: known field names + valid values. County is
132
+ allowed but not value-checked here (the server resolves it)."""
133
+ unknown = set(config) - _KNOWN_CONFIG_KEYS
134
+ if unknown:
135
+ raise ValueError(
136
+ f"unknown config field(s): {sorted(unknown)}. "
137
+ f"Valid keys: {sorted(_KNOWN_CONFIG_KEYS)}"
138
+ )
139
+ # Value-check each field by building the mode model(s) that own it.
140
+ for mode, model in _MODE_MODELS.items():
141
+ subset = {k: v for k, v in config.items() if k in model.model_fields}
142
+ if subset:
143
+ model(**subset) # raises on a bad value
144
+ return dict(config)
145
+
146
+ # -- transport ----------------------------------------------------------
147
+
148
+ def _request(self, method: str, path: str, *, versioned: bool = True,
149
+ json: Any = None, params: Any = None) -> Any:
150
+ base = self._v1 if versioned else self._root
151
+ resp = self._session.request(method, base + path, json=json,
152
+ params=params, timeout=self._timeout)
153
+ self._raise_for_status(resp)
154
+ try:
155
+ return resp.json()
156
+ except ValueError:
157
+ raise APIError(
158
+ f"expected JSON from {path} but got "
159
+ f"{resp.headers.get('content-type')!r}. If base_url is "
160
+ "humanbaselines.com, only /v1/* is proxied there — use the "
161
+ "Cloud Run URL for non-/v1 paths like /health.",
162
+ status_code=resp.status_code, body=resp.text[:200],
163
+ )
164
+
165
+ @staticmethod
166
+ def _raise_for_status(resp: requests.Response) -> None:
167
+ if resp.ok:
168
+ return
169
+ try:
170
+ body: Any = resp.json()
171
+ except ValueError:
172
+ body = resp.text
173
+ detail = body.get("detail") if isinstance(body, dict) else body
174
+ msg = f"{resp.status_code} {resp.reason}: {detail}"
175
+ exc = {
176
+ 401: AuthenticationError,
177
+ 422: ValidationError,
178
+ 404: NotFoundError,
179
+ 503: ServiceUnavailableError,
180
+ }.get(resp.status_code, APIError)
181
+ raise exc(msg, status_code=resp.status_code, body=body)
182
+
183
+ def _overrides(self, model_cls, selections, filters: dict) -> dict:
184
+ """Per-call overrides as a plain dict: kwargs, a dict, or a model's
185
+ *explicitly-set* fields (so a model's own defaults don't clobber the
186
+ bound config)."""
187
+ if selections is not None and filters:
188
+ raise TypeError("pass either `selections` or filter kwargs, not both")
189
+ if selections is None:
190
+ return dict(filters)
191
+ if isinstance(selections, dict):
192
+ return dict(selections)
193
+ if isinstance(selections, model_cls):
194
+ return selections.model_dump(exclude_unset=True)
195
+ raise TypeError(
196
+ f"selections must be a {model_cls.__name__}, dict, or omitted "
197
+ f"(got {type(selections).__name__})"
198
+ )
199
+
200
+ def _resolve_selections(self, model_cls, selections, filters: dict) -> dict:
201
+ """Merge the bound config (subset valid for this mode) under the per-call
202
+ overrides, validate via the mode model, and serialize for the wire."""
203
+ bound = {k: v for k, v in self._config.items() if k in model_cls.model_fields}
204
+ overrides = self._overrides(model_cls, selections, filters)
205
+ # extra="forbid" keeps per-call overrides strict (a bad/foreign field
206
+ # errors); bound fields were already filtered to this mode.
207
+ model = model_cls(**{**bound, **overrides})
208
+ # mode="json" coerces enums to strings; warnings=False silences the
209
+ # str-vs-Enum default notice (generated defaults are strings, emitted
210
+ # value is correct).
211
+ return model.model_dump(mode="json", exclude_none=True, warnings=False)
212
+
213
+ def _county(self, county: str | None) -> str:
214
+ """Per-call county wins, else the bound config's, else the default."""
215
+ return county or self._config.get("county") or DEFAULT_COUNTY
216
+
217
+ @staticmethod
218
+ def _pin(p: PinLike) -> dict:
219
+ if isinstance(p, DepotPin):
220
+ return p.model_dump()
221
+ if isinstance(p, dict):
222
+ return DepotPin(**p).model_dump()
223
+ lat, lon = p # (lat, lon) tuple/list
224
+ return {"lat": float(lat), "lon": float(lon)}
225
+
226
+ # -- discovery ----------------------------------------------------------
227
+
228
+ def filters(self) -> FiltersResponse:
229
+ """Catalog of every filter, its valid options, and per-mode defaults."""
230
+ return FiltersResponse.model_validate(self._request("GET", "/filters"))
231
+
232
+ def regions(self) -> RegionsResponse:
233
+ """Counties available on the server and which compute modes each supports."""
234
+ return RegionsResponse.model_validate(self._request("GET", "/regions"))
235
+
236
+ def manifest(self) -> dict:
237
+ """Dataset metadata (schema version, row counts, availability)."""
238
+ return self._request("GET", "/manifest")
239
+
240
+ def health(self) -> dict:
241
+ """Service status, e.g. ``{"status": "ready"}``.
242
+
243
+ Hits the unversioned ``/health`` endpoint, which is NOT proxied by
244
+ humanbaselines.com — use a Cloud Run ``base_url`` for this call.
245
+ """
246
+ return self._request("GET", "/health", versioned=False)
247
+
248
+ # -- compute ------------------------------------------------------------
249
+
250
+ def compute(self, selections: GeofenceSelections | dict | None = None, *,
251
+ county: str | None = None, **filters) -> ComputeResult:
252
+ """Geofence (S2-cell) crash rate. Inherits the bound config; per-call
253
+ args override it."""
254
+ sel = self._resolve_selections(GeofenceSelections, selections, filters)
255
+ data = self._request("POST", "/compute",
256
+ json={"county": self._county(county), "selections": sel})
257
+ return ComputeResult.model_validate(data)
258
+
259
+ def compute_route(self, segment_ids: list[tuple[str, int]],
260
+ selections: RouteSelections | dict | None = None, *,
261
+ county: str | None = None, **filters) -> RouteComputeResult:
262
+ """Crash rate over a sequence of interstate (route, milepost) segments.
263
+ For route-capable regions (``travis``, ``ca_interstates``,
264
+ ``sw_interstates`` — see ``regions()``). Inherits the bound config;
265
+ per-call args override it."""
266
+ sel = self._resolve_selections(RouteSelections, selections, filters)
267
+ data = self._request("POST", "/compute/route", json={
268
+ "county": self._county(county),
269
+ "segment_ids": [list(s) for s in segment_ids],
270
+ "selections": sel,
271
+ })
272
+ return RouteComputeResult.model_validate(data)
273
+
274
+ def compute_depot_route(self, depot_a: PinLike, depot_b: PinLike,
275
+ selections: DepotSelections | dict | None = None, *,
276
+ county: str | None = None, **filters) -> DepotComputeResult:
277
+ """Full depot-to-depot trip rate (access + interstate + access legs).
278
+ For depot-capable regions (``travis``, ``ca_interstates``,
279
+ ``sw_interstates`` — see ``regions()``). Pins are (lat, lon) tuples,
280
+ DepotPins, or dicts. Inherits the bound config; per-call args override it."""
281
+ sel = self._resolve_selections(DepotSelections, selections, filters)
282
+ data = self._request("POST", "/compute/depot-route", json={
283
+ "county": self._county(county),
284
+ "depot_a": self._pin(depot_a),
285
+ "depot_b": self._pin(depot_b),
286
+ "selections": sel,
287
+ })
288
+ return DepotComputeResult.model_validate(data)
289
+
290
+ # -- bound config (the baseline "definition") ---------------------------
291
+
292
+ def config(self, mode: str = "geofence") -> dict:
293
+ """The full effective config for a mode — your bound values plus every
294
+ default filled in, with county. This is the complete definition a
295
+ compute call in this mode would use."""
296
+ if mode not in _MODE_MODELS:
297
+ raise ValueError(f"unknown mode {mode!r}; choose from {sorted(_MODE_MODELS)}")
298
+ model_cls = _MODE_MODELS[mode]
299
+ bound = {k: v for k, v in self._config.items() if k in model_cls.model_fields}
300
+ sel = model_cls(**bound).model_dump(mode="json", warnings=False)
301
+ return {"county": self._county(None), **sel}
302
+
303
+ def changes(self, mode: str = "geofence") -> dict:
304
+ """Only the settings that differ from this mode's defaults (the
305
+ deviations), including county if you've changed it."""
306
+ full = self.config(mode)
307
+ defaults = _MODE_MODELS[mode]().model_dump(mode="json", warnings=False)
308
+ defaults["county"] = DEFAULT_COUNTY
309
+ return {k: v for k, v in full.items() if v != defaults.get(k)}
310
+
311
+ def with_config(self, config: dict | None = None, **fields) -> "HumanBaselines":
312
+ """Return a NEW client with the bound config updated (this one is left
313
+ unchanged). Per-field merge: ``{**current, **config, **fields}``. The
314
+ underlying HTTP session is shared."""
315
+ merged = {**self._config, **(config or {}), **fields}
316
+ return HumanBaselines(
317
+ self._api_key, base_url=self._base_url, timeout=self._timeout,
318
+ max_retries=self._max_retries, session=self._session, config=merged,
319
+ )
320
+
321
+ def save_config(self, path: str | Path, mode: str = "geofence") -> None:
322
+ """Write the FULL effective config (every default filled in) to a JSON
323
+ file — a complete, self-documenting snapshot of the definition, not just
324
+ the deviations. A top-level ``"mode"`` key records which mode's field set
325
+ it captures. Defaults to geofence; pass ``mode`` for route/depot. Reload
326
+ with ``from_config``."""
327
+ payload = {"mode": mode, **self.config(mode)}
328
+ Path(path).write_text(json.dumps(payload, indent=2) + "\n")
329
+
330
+ @classmethod
331
+ def from_config(cls, source: str | Path | dict, api_key: str | None = None,
332
+ **client_kwargs) -> "HumanBaselines":
333
+ """Explicit alternative constructor from a saved definition (path or
334
+ dict). Equivalent to ``HumanBaselines(api_key, config=source)`` — the
335
+ constructor accepts a path directly — kept for readable intent."""
336
+ return cls(api_key, config=source, **client_kwargs)
337
+
338
+ # -- lifecycle ----------------------------------------------------------
339
+
340
+ def close(self) -> None:
341
+ self._session.close()
342
+
343
+ def __enter__(self) -> "HumanBaselines":
344
+ return self
345
+
346
+ def __exit__(self, *exc) -> None:
347
+ self.close()
348
+
349
+ def __repr__(self) -> str:
350
+ cfg = f", config={self._config}" if self._config else ""
351
+ return f"HumanBaselines(base_url={self._root!r}{cfg})"
@@ -0,0 +1,54 @@
1
+ """Typed exception hierarchy for the Human Crash Baselines client.
2
+
3
+ Every non-2xx response is mapped to one of these by status code, so callers can
4
+ catch the specific failure they care about (auth vs. validation vs. warm-up)
5
+ rather than parsing HTTP codes themselves.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any
11
+
12
+
13
+ class HumanBaselinesError(Exception):
14
+ """Base class for all client errors."""
15
+
16
+
17
+ class APIError(HumanBaselinesError):
18
+ """A non-2xx HTTP response that isn't covered by a more specific subclass.
19
+
20
+ Carries the HTTP `status_code` and the parsed/raw response `body`.
21
+ """
22
+
23
+ def __init__(self, message: str, *, status_code: int | None = None, body: Any = None):
24
+ super().__init__(message)
25
+ self.status_code = status_code
26
+ self.body = body
27
+
28
+
29
+ class AuthenticationError(APIError):
30
+ """401 — missing or invalid API key."""
31
+
32
+
33
+ class ValidationError(APIError):
34
+ """422 — the request failed server-side validation.
35
+
36
+ `errors` holds the server's field-level detail (FastAPI's `detail` list)
37
+ when present, so callers can see exactly which filter was rejected.
38
+ """
39
+
40
+ def __init__(self, message: str, *, status_code: int | None = None, body: Any = None):
41
+ super().__init__(message, status_code=status_code, body=body)
42
+ self.errors = body.get("detail") if isinstance(body, dict) else None
43
+
44
+
45
+ class NotFoundError(APIError):
46
+ """404 — unknown route, or a county/resource that isn't loaded."""
47
+
48
+
49
+ class ServiceUnavailableError(APIError):
50
+ """503 — the service is warming up (caches loading) or temporarily down.
51
+
52
+ The client retries these automatically before giving up; if you see this,
53
+ the retries were exhausted.
54
+ """
@@ -0,0 +1,79 @@
1
+ """Public model surface for the Human Crash Baselines client.
2
+
3
+ The types are GENERATED from the server's OpenAPI schema into `_generated.py`
4
+ (do not edit that file by hand). The server's Pydantic models
5
+ (`data-prep/server/schemas.py` + `catalog.py`) are the single source of truth;
6
+ regenerate with `scripts/regenerate_models.py` after any API change. At runtime,
7
+ `HumanBaselines.filters()` returns the live catalog of valid values + defaults.
8
+
9
+ This module just re-exports the generated names the client and public API use
10
+ (notably NOT the generated `ValidationError`/`HTTPValidationError` models, which
11
+ would collide with the client's `ValidationError` *exception*).
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from ._generated import ( # noqa: F401
17
+ CiMethod,
18
+ ComputeResult,
19
+ DepotComputeResult,
20
+ DepotPin,
21
+ DepotSelections,
22
+ DriverImpairment,
23
+ FilterDef,
24
+ FilterOption,
25
+ FiltersResponse,
26
+ GeofenceSelections,
27
+ InTransport,
28
+ LightFilter,
29
+ MultiplierVmt,
30
+ Outcome,
31
+ PerCellResult,
32
+ PerSegmentResult,
33
+ RegionInfo,
34
+ RegionsResponse,
35
+ RoadGroup,
36
+ RoboTaxiWeighting,
37
+ RouteComputeResult,
38
+ RouteSelections,
39
+ Tier3Mode,
40
+ UnderReporting,
41
+ VehicleClass,
42
+ WeatherFilter,
43
+ )
44
+
45
+ # Client-side constant (not part of the wire schema).
46
+ DEFAULT_COUNTY = "travis"
47
+
48
+ __all__ = [
49
+ "DEFAULT_COUNTY",
50
+ # request models
51
+ "GeofenceSelections",
52
+ "RouteSelections",
53
+ "DepotSelections",
54
+ "DepotPin",
55
+ # response models
56
+ "ComputeResult",
57
+ "PerCellResult",
58
+ "RouteComputeResult",
59
+ "PerSegmentResult",
60
+ "DepotComputeResult",
61
+ "FiltersResponse",
62
+ "FilterDef",
63
+ "FilterOption",
64
+ "RegionsResponse",
65
+ "RegionInfo",
66
+ # enums
67
+ "Outcome",
68
+ "VehicleClass",
69
+ "RoadGroup",
70
+ "Tier3Mode",
71
+ "InTransport",
72
+ "RoboTaxiWeighting",
73
+ "MultiplierVmt",
74
+ "WeatherFilter",
75
+ "LightFilter",
76
+ "DriverImpairment",
77
+ "UnderReporting",
78
+ "CiMethod",
79
+ ]
@@ -0,0 +1,217 @@
1
+ Metadata-Version: 2.4
2
+ Name: humanbaselines
3
+ Version: 0.1.0
4
+ Summary: Python client for the Human Crash Baselines API — human-driver crash-rate baselines by region, route, and filter.
5
+ Project-URL: Homepage, https://humanbaselines.com
6
+ Project-URL: Documentation, https://human-baseline-api-yz2u5f75wa-uc.a.run.app/docs
7
+ Project-URL: Repository, https://github.com/valgorithmic/humanbaselines
8
+ Project-URL: Issues, https://github.com/valgorithmic/humanbaselines/issues
9
+ Author: Valgorithmic, Inc.
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: api-client,autonomous-vehicles,baseline,crash,safety
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: Science/Research
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Topic :: Scientific/Engineering
21
+ Requires-Python: >=3.10
22
+ Requires-Dist: pydantic>=2.9
23
+ Requires-Dist: requests>=2.31
24
+ Provides-Extra: dev
25
+ Requires-Dist: black; extra == 'dev'
26
+ Requires-Dist: datamodel-code-generator>=0.25; extra == 'dev'
27
+ Requires-Dist: isort; extra == 'dev'
28
+ Requires-Dist: pytest>=7; extra == 'dev'
29
+ Requires-Dist: responses>=0.25; extra == 'dev'
30
+ Description-Content-Type: text/markdown
31
+
32
+ # humanbaselines
33
+
34
+ Python client for the **Human Crash Baselines API** — typed access to human-driver
35
+ crash-rate baselines by region, route, and filter.
36
+
37
+ It wraps the `/v1` REST API: construct a client with your key, call typed methods,
38
+ get typed results back (no hand-built JSON, no remembering the auth header).
39
+
40
+ ## Install
41
+
42
+ ```bash
43
+ pip install humanbaselines
44
+ ```
45
+
46
+ Or install the latest from source:
47
+
48
+ ```bash
49
+ pip install "git+https://github.com/valgorithmic/humanbaselines.git"
50
+ # or, from a checkout:
51
+ pip install .
52
+ ```
53
+
54
+ ## Quickstart
55
+
56
+ ```python
57
+ from humanbaselines import HumanBaselines
58
+
59
+ hb = HumanBaselines(api_key="hbk_...") # or set HUMANBASELINES_API_KEY
60
+
61
+ # Geofence crash rate (kwargs are validated client-side):
62
+ r = hb.compute(county="travis", outcome="police_reported", ego_vehicle=["cars", "light_trucks"])
63
+ print(r.rate, r.rate_low, r.rate_high) # 4.055 4.0 4.1
64
+ print(r.N, r.D_miles, len(r.cells)) # 24617.0 6.07e9 1795
65
+
66
+ # Discover valid filters + defaults at runtime:
67
+ for f in hb.filters().modes["geofence"]:
68
+ print(f.id, "→", [o.id for o in f.options], "default:", f.default)
69
+
70
+ # Which regions / modes are available:
71
+ hb.regions()
72
+ ```
73
+
74
+ ### Filters
75
+
76
+ Pass filters three ways — keyword args (simplest), a typed `Selections` model,
77
+ or a plain dict. All are validated **before** the request, so a bad value fails
78
+ fast locally:
79
+
80
+ ```python
81
+ from humanbaselines import GeofenceSelections, Outcome
82
+
83
+ hb.compute(outcome="fatal", road_type=["interstate"]) # kwargs
84
+ hb.compute(selections=GeofenceSelections(outcome=Outcome.fatal)) # typed model
85
+ hb.compute(selections={"outcome": "fatal"}) # dict
86
+ ```
87
+
88
+ Omitted filters fall back to the API's defaults (these reproduce the web UI's
89
+ headline numbers).
90
+
91
+ ### Binding a baseline definition
92
+
93
+ The filter selections are really a *methodological definition* — what counts as
94
+ a crash and what you're baselining against. Bind that definition to the client
95
+ once and every call inherits it; per-call args override individual fields:
96
+
97
+ ```python
98
+ hb = HumanBaselines(api_key="hbk_...", config={
99
+ "county": "travis",
100
+ "outcome": "fatal",
101
+ "ego_vehicle": ["cars", "light_trucks"],
102
+ })
103
+
104
+ hb.compute().rate # uses the bound definition
105
+ hb.compute(weather=["rain"]).rate # override just one field for this call
106
+
107
+ hb.config() # full effective config (bound + every default)
108
+ hb.changes() # only the settings that differ from the defaults
109
+ ```
110
+
111
+ `config(mode="geofence")` and `changes(mode="geofence")` take an optional mode
112
+ (each mode exposes different fields). `config()` is the complete definition a
113
+ compute call would use; `changes()` is just your deviations from the defaults.
114
+
115
+ The bound config is validated when you create the client (unknown fields or bad
116
+ values raise immediately). It applies to **all modes** — each compute mode uses
117
+ the subset of fields it understands (e.g. `road_type` only affects geofence,
118
+ `ci_method` only affects route/depot), so you can keep one definition across
119
+ modes.
120
+
121
+ Derive variants immutably, and version definitions as JSON:
122
+
123
+ ```python
124
+ strict = hb.with_config(under_reporting="adjusted") # new client; hb is unchanged
125
+
126
+ hb.save_config("odd_fatal_cars.json") # full config snapshot (check into a repo, share, diff)
127
+
128
+ # Load it back — pass the path straight to the constructor:
129
+ hb2 = HumanBaselines(api_key="hbk_...", config="odd_fatal_cars.json")
130
+ # (HumanBaselines.from_config(path, api_key=...) is an equivalent, explicit alias.)
131
+ ```
132
+
133
+ ### Route & depot modes
134
+
135
+ Available for route/depot-capable regions — `travis`, `ca_interstates`, and
136
+ `sw_interstates` (check `hb.regions()`). Route/depot count Class-8 combination
137
+ trucks, so `ego_vehicle` defaults to `["combination"]` in these modes.
138
+
139
+ ```python
140
+ hb.compute_route(segment_ids=[("I-35", 250), ("I-35", 251)], ego_vehicle=["combination"])
141
+
142
+ hb.compute_depot_route(
143
+ depot_a=(30.25, -97.75), # (lat, lon)
144
+ depot_b=(30.40, -97.70),
145
+ ci_method="fay_feuer",
146
+ )
147
+ ```
148
+
149
+ ## Errors
150
+
151
+ Non-2xx responses raise typed exceptions you can catch:
152
+
153
+ ```python
154
+ from humanbaselines import AuthenticationError, ValidationError, ServiceUnavailableError
155
+
156
+ try:
157
+ hb.compute(outcome="fatal")
158
+ except AuthenticationError: # 401 — bad/missing key
159
+ ...
160
+ except ValidationError as e: # 422 — e.errors has the field-level detail
161
+ print(e.errors)
162
+ except ServiceUnavailableError: # 503 — service warming up (auto-retried first)
163
+ ...
164
+ ```
165
+
166
+ All inherit from `HumanBaselinesError`. The base `APIError` carries `.status_code`
167
+ and `.body`.
168
+
169
+ ## Configuration
170
+
171
+ | arg | default | notes |
172
+ |---|---|---|
173
+ | `api_key` | `$HUMANBASELINES_API_KEY` | sent as `X-API-Key` |
174
+ | `base_url` | `https://humanbaselines.com` | proxies `/v1/*`; use the Cloud Run URL for `/health` |
175
+ | `timeout` | `30` | seconds per request |
176
+ | `max_retries` | `2` | exponential backoff on 502/503/504 (handles cold-start warm-up) |
177
+
178
+ `HumanBaselines` is also a context manager (`with HumanBaselines(...) as hb:`).
179
+
180
+ ## Notes
181
+
182
+ - The typed models in `_generated.py` are **generated from the server's OpenAPI
183
+ schema** — the server's Pydantic models are the single source of truth, so the
184
+ client can't drift from the API. `GET /v1/filters` is the authoritative
185
+ runtime source for valid values and defaults.
186
+ - Interactive API docs: the `/docs` page on the API host.
187
+
188
+ ## Development
189
+
190
+ ```bash
191
+ pip install -e '.[dev]'
192
+ pytest -q # mocked tests
193
+ HUMANBASELINES_API_KEY=hbk_... pytest -q # also runs the live smoke test
194
+ python -m build # build wheel + sdist into dist/
195
+ ```
196
+
197
+ ### Regenerating models after an API change
198
+
199
+ `src/humanbaselines/_generated.py` is generated — never hand-edit it. When the
200
+ API contract changes, regenerate from the live OpenAPI schema:
201
+
202
+ ```bash
203
+ python scripts/regenerate_models.py
204
+ # point at a different host (e.g. local dev server):
205
+ python scripts/regenerate_models.py --url http://localhost:8000
206
+ ```
207
+
208
+ This fetches `<host>/openapi.json` (default `https://humanbaselines.com`) and runs
209
+ `datamodel-code-generator`. Output is deterministic (no timestamps), so a clean
210
+ `git diff` means the client is in sync with the API.
211
+
212
+ > Releases are automated: a version bump in the upstream app dispatches a release
213
+ > here, which tags `v<version>` and publishes to PyPI via Trusted Publishing.
214
+
215
+ ## License
216
+
217
+ Apache-2.0 © Valgorithmic, Inc.
@@ -0,0 +1,9 @@
1
+ humanbaselines/__init__.py,sha256=YGSflu-H3u-yFcA6IXSXcXpSuDbeZkA8JCBZ-FvLudY,1838
2
+ humanbaselines/_generated.py,sha256=Dm8k72efzZbAZ2dppygxKpPr7X4UUVHOAL9gqskKDuo,9288
3
+ humanbaselines/client.py,sha256=o5dIMCRnzrhOwdmY7-xgdyYhCOceo56r1bXR7EkUzAc,15406
4
+ humanbaselines/exceptions.py,sha256=BayZg5_90puqMw6uqGe4Ye93kZpU5wgoiFHyKMb2Rtc,1726
5
+ humanbaselines/models.py,sha256=Ii3Hk5tvoAeN3Pb9uzIX9ejk9Mn9IFUU5NAEyz7gna4,1957
6
+ humanbaselines-0.1.0.dist-info/METADATA,sha256=U8UQnS1N3l7qBVaBwKjaX4hYBnMy8K7zrFM4D8ExUjY,7792
7
+ humanbaselines-0.1.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
8
+ humanbaselines-0.1.0.dist-info/licenses/LICENSE,sha256=4WsjIy3F9zrydiFym1_-cMYcAirPXlB6BJUOiY1ZT_c,10339
9
+ humanbaselines-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.30.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,184 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship made available under
36
+ the License, as indicated by a copyright notice that is included in
37
+ or attached to the work (an example is provided in the Appendix below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other transformations
42
+ represent, as a whole, an original work of authorship. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and Derivative Works thereof.
46
+
47
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
48
+ in the Work by the copyright owner or by an individual or Legal Entity
49
+ authorized to submit on behalf of the copyright owner. For the purposes
50
+ of this definition, "submitted" means any form of electronic, verbal, or
51
+ written communication sent to the Licensor or its representatives,
52
+ including but not limited to communication on electronic mailing lists,
53
+ source code control systems, and issue tracking systems that are managed
54
+ by, or on behalf of, the Licensor for the purpose of discussing and
55
+ improving the Work, but excluding communication that is conspicuously
56
+ marked or designated in writing by the copyright owner as "Not a
57
+ Contribution."
58
+
59
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
60
+ whom a Contribution has been received by the Licensor and included
61
+ within the Work.
62
+
63
+ 2. Grant of Copyright License. Subject to the terms and conditions of
64
+ this License, each Contributor hereby grants to You a perpetual,
65
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
66
+ copyright license to reproduce, prepare Derivative Works of,
67
+ publicly display, publicly perform, sublicense, and distribute the
68
+ Work and such Derivative Works in Source or Object form.
69
+
70
+ 3. Grant of Patent License. Subject to the terms and conditions of
71
+ this License, each Contributor hereby grants to You a perpetual,
72
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
73
+ (except as stated in this section) patent license to make, have made,
74
+ use, offer to sell, sell, import, and otherwise transfer the Work,
75
+ where such license applies only to those patent claims licensable
76
+ by such Contributor that are necessarily infringed by their
77
+ Contribution(s) alone or by the combination of their Contribution(s)
78
+ with the Work to which such Contribution(s) was submitted. If You
79
+ institute patent litigation against any entity (including a
80
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
81
+ or a Contribution incorporated within the Work constitutes direct
82
+ or contributory patent infringement, then any patent licenses
83
+ granted to You under this License for that Work shall terminate
84
+ as of the date such litigation is filed.
85
+
86
+ 4. Redistribution. You may reproduce and distribute copies of the
87
+ Work or Derivative Works thereof in any medium, with or without
88
+ modifications, and in Source or Object form, provided that You
89
+ meet the following conditions:
90
+
91
+ (a) You must give any other recipients of the Work or Derivative
92
+ Works a copy of this License; and
93
+
94
+ (b) You must cause any modified files to carry prominent notices
95
+ stating that You changed the files; and
96
+
97
+ (c) You must retain, in the Source form of any Derivative Works
98
+ that You distribute, all copyright, patent, trademark, and
99
+ attribution notices from the Source form of the Work,
100
+ excluding those notices that do not pertain to any part of
101
+ the Derivative Works; and
102
+
103
+ (d) If the Work includes a "NOTICE" text file as part of its
104
+ distribution, You must include a readable copy of the
105
+ attribution notices contained within such NOTICE file, in
106
+ at least one of the following places: within a NOTICE text
107
+ file distributed as part of the Derivative Works; within
108
+ the Source form or documentation, if provided along with the
109
+ Derivative Works; or, within a display generated by the
110
+ Derivative Works, if and wherever such third-party notices
111
+ normally appear. The contents of the NOTICE file are for
112
+ informational purposes only and do not modify the License.
113
+ You may add Your own attribution notices within Derivative
114
+ Works that You distribute, alongside or as an addendum to
115
+ the NOTICE text from the Work, provided that such additional
116
+ attribution notices cannot be construed as modifying the License.
117
+
118
+ You may add Your own license statement for Your modifications and
119
+ may provide additional grant of rights to use, copy, modify, merge,
120
+ publish, distribute, sublicense, and/or sell copies of the
121
+ Derivative Works, and to permit persons to whom the Derivative Works
122
+ is furnished to do so, subject to the following conditions:
123
+
124
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
125
+ any Contribution intentionally submitted for inclusion in the Work
126
+ by You to the Licensor shall be under the terms and conditions of
127
+ this License, without any additional terms or conditions.
128
+ Notwithstanding the above, nothing herein shall supersede or modify
129
+ the terms of any separate license agreement you may have executed
130
+ with Licensor regarding such Contributions.
131
+
132
+ 6. Trademarks. This License does not grant permission to use the trade
133
+ names, trademarks, service marks, or product names of the Licensor,
134
+ except as required for reasonable and customary use in describing the
135
+ origin of the Work and reproducing the content of the NOTICE file.
136
+
137
+ 7. Disclaimer of Warranty. Unless required by applicable law or
138
+ agreed to in writing, Licensor provides the Work (and each
139
+ Contributor provides its Contributions) on an "AS IS" BASIS,
140
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
141
+ implied, including, without limitation, any warranties or conditions
142
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
143
+ PARTICULAR PURPOSE. You are solely responsible for determining the
144
+ appropriateness of using or reproducing the Work and assume any
145
+ risks associated with Your exercise of permissions under this License.
146
+
147
+ 8. Limitation of Liability. In no event and under no legal theory,
148
+ whether in tort (including negligence), contract, or otherwise,
149
+ unless required by applicable law (such as deliberate and grossly
150
+ negligent acts) or agreed to in writing, shall any Contributor be
151
+ liable to You for damages, including any direct, indirect, special,
152
+ incidental, or exemplary damages of any character arising as a
153
+ result of this License or out of the use or inability to use the
154
+ Work (including but not limited to damages for loss of goodwill,
155
+ work stoppage, computer failure or malfunction, or all other
156
+ commercial damages or losses), even if such Contributor has been
157
+ advised of the possibility of such damages.
158
+
159
+ 9. Accepting Warranty or Additional Liability. While redistributing
160
+ the Work or Derivative Works thereof, You may offer, and charge a
161
+ fee for, acceptance of support, warranty, indemnity, or other
162
+ liability obligations and/or rights consistent with this License.
163
+ However, in accepting such obligations, You may offer such obligations
164
+ only on Your own behalf and on Your sole responsibility, not on behalf
165
+ of any other Contributor, and only if You agree to indemnify,
166
+ defend, and hold each Contributor harmless for any liability
167
+ incurred by, or claims asserted against, such Contributor by reason
168
+ of your accepting any such warranty or additional liability.
169
+
170
+ END OF TERMS AND CONDITIONS
171
+
172
+ Copyright 2026 Valgorithmic, Inc. (d.b.a. Valgo)
173
+
174
+ Licensed under the Apache License, Version 2.0 (the "License");
175
+ you may not use this file except in compliance with the License.
176
+ You may obtain a copy of the License at
177
+
178
+ http://www.apache.org/licenses/LICENSE-2.0
179
+
180
+ Unless required by applicable law or agreed to in writing, software
181
+ distributed under the License is distributed on an "AS IS" BASIS,
182
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
183
+ See the License for the specific language governing permissions and
184
+ limitations under the License.