humanbaselines 0.1.0__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.
@@ -0,0 +1,87 @@
1
+ name: release
2
+
3
+ # Publishes a version to PyPI via Trusted Publishing (OIDC — no stored tokens).
4
+ # Triggered two ways:
5
+ # - workflow_dispatch: manual, with an explicit `version` input.
6
+ # - repository_dispatch (event_type: ui-version): fired by the upstream app's
7
+ # sync workflow when the canonical product version changes; the version is
8
+ # carried in client_payload.version.
9
+ # The version is the canonical product version (the app's root package.json), so
10
+ # the client always ships in lockstep with the UI it documents.
11
+
12
+ on:
13
+ workflow_dispatch:
14
+ inputs:
15
+ version:
16
+ description: "Version to release (e.g. 0.1.0)"
17
+ required: true
18
+ type: string
19
+ repository_dispatch:
20
+ types: [ui-version]
21
+
22
+ concurrency:
23
+ group: release
24
+ cancel-in-progress: false
25
+
26
+ jobs:
27
+ release:
28
+ runs-on: ubuntu-latest
29
+ environment: pypi
30
+ permissions:
31
+ id-token: write # OIDC for PyPI Trusted Publishing
32
+ contents: write # commit the version bump + push the tag/release
33
+ steps:
34
+ - uses: actions/checkout@v4
35
+
36
+ - name: Resolve version
37
+ id: v
38
+ run: |
39
+ if [ "${{ github.event_name }}" = "repository_dispatch" ]; then
40
+ VERSION="${{ github.event.client_payload.version }}"
41
+ else
42
+ VERSION="${{ github.event.inputs.version }}"
43
+ fi
44
+ VERSION="${VERSION#v}"
45
+ if [ -z "$VERSION" ]; then echo "no version supplied" >&2; exit 1; fi
46
+ echo "version=$VERSION" >> "$GITHUB_OUTPUT"
47
+ echo "Releasing version $VERSION"
48
+
49
+ - uses: actions/setup-python@v5
50
+ with:
51
+ python-version: "3.12"
52
+
53
+ - name: Bump __version__ and commit
54
+ env:
55
+ VERSION: ${{ steps.v.outputs.version }}
56
+ run: |
57
+ sed -i 's/^__version__ = .*/__version__ = "'"$VERSION"'"/' src/humanbaselines/__init__.py
58
+ grep '^__version__' src/humanbaselines/__init__.py
59
+ git config user.name "github-actions[bot]"
60
+ git config user.email "github-actions[bot]@users.noreply.github.com"
61
+ if git diff --quiet; then
62
+ echo "version already $VERSION; no bump commit"
63
+ else
64
+ git commit -am "Release v$VERSION"
65
+ git push
66
+ fi
67
+
68
+ - name: Tag and GitHub Release
69
+ env:
70
+ VERSION: ${{ steps.v.outputs.version }}
71
+ GH_TOKEN: ${{ github.token }}
72
+ run: |
73
+ if git ls-remote --exit-code --tags origin "refs/tags/v$VERSION" >/dev/null 2>&1; then
74
+ echo "tag v$VERSION already exists; skipping release creation"
75
+ else
76
+ gh release create "v$VERSION" --title "v$VERSION" --generate-notes --target "$(git rev-parse HEAD)"
77
+ fi
78
+
79
+ - name: Build
80
+ run: |
81
+ pip install build
82
+ python -m build
83
+
84
+ - name: Publish to PyPI
85
+ uses: pypa/gh-action-pypi-publish@release/v1
86
+ with:
87
+ skip-existing: true
@@ -0,0 +1,24 @@
1
+ name: test
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+ workflow_dispatch:
8
+
9
+ jobs:
10
+ test:
11
+ runs-on: ubuntu-latest
12
+ strategy:
13
+ fail-fast: false
14
+ matrix:
15
+ python-version: ["3.10", "3.11", "3.12"]
16
+ steps:
17
+ - uses: actions/checkout@v4
18
+ - uses: actions/setup-python@v5
19
+ with:
20
+ python-version: ${{ matrix.python-version }}
21
+ - name: Install
22
+ run: pip install -e '.[dev]'
23
+ - name: Test
24
+ run: pytest -q
@@ -0,0 +1,9 @@
1
+ # Generated by the example scripts (bound_config.py / from_file.py).
2
+ examples/*.json
3
+
4
+ # Build artifacts
5
+ dist/
6
+ *.egg-info/
7
+ __pycache__/
8
+ *.pyc
9
+ .pytest_cache/
@@ -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.
@@ -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.