Python client for the Human Crash Baselines API — human-driver crash-rate baselines by region, route, and filter.
Project description
humanbaselines
Python client for the Human Crash Baselines API — typed access to human-driver crash-rate baselines by region, route, and filter.
It wraps the /v1 REST API: construct a client with your key, call typed methods,
get typed results back (no hand-built JSON, no remembering the auth header).
Install
pip install humanbaselines
Or install the latest from source:
pip install "git+https://github.com/valgorithmic/humanbaselines.git"
# or, from a checkout:
pip install .
Quickstart
from humanbaselines import HumanBaselines
hb = HumanBaselines(api_key="hbk_...") # or set HUMANBASELINES_API_KEY
# Geofence crash rate (kwargs are validated client-side):
r = hb.compute(county="travis", outcome="police_reported", ego_vehicle=["cars", "light_trucks"])
print(r.rate, r.rate_low, r.rate_high) # 4.055 4.0 4.1
print(r.N, r.D_miles, len(r.cells)) # 24617.0 6.07e9 1795
# Discover valid filters + defaults at runtime:
for f in hb.filters().modes["geofence"]:
print(f.id, "→", [o.id for o in f.options], "default:", f.default)
# Which regions / modes are available:
hb.regions()
Filters
Pass filters three ways — keyword args (simplest), a typed Selections model,
or a plain dict. All are validated before the request, so a bad value fails
fast locally:
from humanbaselines import GeofenceSelections, Outcome
hb.compute(outcome="fatal", road_type=["interstate"]) # kwargs
hb.compute(selections=GeofenceSelections(outcome=Outcome.fatal)) # typed model
hb.compute(selections={"outcome": "fatal"}) # dict
Omitted filters fall back to the API's defaults (these reproduce the web UI's headline numbers).
Binding a baseline definition
The filter selections are really a methodological definition — what counts as a crash and what you're baselining against. Bind that definition to the client once and every call inherits it; per-call args override individual fields:
hb = HumanBaselines(api_key="hbk_...", config={
"county": "travis",
"outcome": "fatal",
"ego_vehicle": ["cars", "light_trucks"],
})
hb.compute().rate # uses the bound definition
hb.compute(weather=["rain"]).rate # override just one field for this call
hb.config() # full effective config (bound + every default)
hb.changes() # only the settings that differ from the defaults
config(mode="geofence") and changes(mode="geofence") take an optional mode
(each mode exposes different fields). config() is the complete definition a
compute call would use; changes() is just your deviations from the defaults.
The bound config is validated when you create the client (unknown fields or bad
values raise immediately). It applies to all modes — each compute mode uses
the subset of fields it understands (e.g. road_type only affects geofence,
ci_method only affects route/depot), so you can keep one definition across
modes.
Derive variants immutably, and version definitions as JSON:
strict = hb.with_config(under_reporting="adjusted") # new client; hb is unchanged
hb.save_config("odd_fatal_cars.json") # full config snapshot (check into a repo, share, diff)
# Load it back — pass the path straight to the constructor:
hb2 = HumanBaselines(api_key="hbk_...", config="odd_fatal_cars.json")
# (HumanBaselines.from_config(path, api_key=...) is an equivalent, explicit alias.)
Route & depot modes
Available for route/depot-capable regions — travis, ca_interstates, and
sw_interstates (check hb.regions()). Route/depot count Class-8 combination
trucks, so ego_vehicle defaults to ["combination"] in these modes.
hb.compute_route(segment_ids=[("I-35", 250), ("I-35", 251)], ego_vehicle=["combination"])
hb.compute_depot_route(
depot_a=(30.25, -97.75), # (lat, lon)
depot_b=(30.40, -97.70),
ci_method="fay_feuer",
)
Errors
Non-2xx responses raise typed exceptions you can catch:
from humanbaselines import AuthenticationError, ValidationError, ServiceUnavailableError
try:
hb.compute(outcome="fatal")
except AuthenticationError: # 401 — bad/missing key
...
except ValidationError as e: # 422 — e.errors has the field-level detail
print(e.errors)
except ServiceUnavailableError: # 503 — service warming up (auto-retried first)
...
All inherit from HumanBaselinesError. The base APIError carries .status_code
and .body.
Configuration
| arg | default | notes |
|---|---|---|
api_key |
$HUMANBASELINES_API_KEY |
sent as X-API-Key |
base_url |
https://humanbaselines.com |
proxies /v1/*; use the Cloud Run URL for /health |
timeout |
30 |
seconds per request |
max_retries |
2 |
exponential backoff on 502/503/504 (handles cold-start warm-up) |
HumanBaselines is also a context manager (with HumanBaselines(...) as hb:).
Notes
- The typed models in
_generated.pyare generated from the server's OpenAPI schema — the server's Pydantic models are the single source of truth, so the client can't drift from the API.GET /v1/filtersis the authoritative runtime source for valid values and defaults. - Interactive API docs: the
/docspage on the API host.
Development
pip install -e '.[dev]'
pytest -q # mocked tests
HUMANBASELINES_API_KEY=hbk_... pytest -q # also runs the live smoke test
python -m build # build wheel + sdist into dist/
Regenerating models after an API change
src/humanbaselines/_generated.py is generated — never hand-edit it. When the
API contract changes, regenerate from the live OpenAPI schema:
python scripts/regenerate_models.py
# point at a different host (e.g. local dev server):
python scripts/regenerate_models.py --url http://localhost:8000
This fetches <host>/openapi.json (default https://humanbaselines.com) and runs
datamodel-code-generator. Output is deterministic (no timestamps), so a clean
git diff means the client is in sync with the API.
Releases are automated: a version bump in the upstream app dispatches a release here, which tags
v<version>and publishes to PyPI via Trusted Publishing.
License
Apache-2.0 © Valgorithmic, Inc.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file humanbaselines-0.1.0.tar.gz.
File metadata
- Download URL: humanbaselines-0.1.0.tar.gz
- Upload date:
- Size: 21.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
65e64fc17d26fdc4af25cbd21b4ec7462a5398a131670dbec82e190455bf3929
|
|
| MD5 |
56be93a955cf24359d5cd53256efc509
|
|
| BLAKE2b-256 |
3ebc8aa290de6c80b89553318152a1534131f67a7d3f7dd29aa88787e32f7c41
|
Provenance
The following attestation bundles were made for humanbaselines-0.1.0.tar.gz:
Publisher:
release.yml on valgorithmic/humanbaselines
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
humanbaselines-0.1.0.tar.gz -
Subject digest:
65e64fc17d26fdc4af25cbd21b4ec7462a5398a131670dbec82e190455bf3929 - Sigstore transparency entry: 1855032211
- Sigstore integration time:
-
Permalink:
valgorithmic/humanbaselines@da3ad3cf15a3a2eff5efe19eda27c99ba5719809 -
Branch / Tag:
refs/heads/main - Owner: https://github.com/valgorithmic
-
Access:
private
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@da3ad3cf15a3a2eff5efe19eda27c99ba5719809 -
Trigger Event:
workflow_dispatch
-
Statement type:
File details
Details for the file humanbaselines-0.1.0-py3-none-any.whl.
File metadata
- Download URL: humanbaselines-0.1.0-py3-none-any.whl
- Upload date:
- Size: 18.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
dd58879330fcd851628a5df8be0ebf9a7a3f228e816c0ee8c64b609974b5c565
|
|
| MD5 |
0f58b28abee4347301708db8e1f39e0f
|
|
| BLAKE2b-256 |
8d4be5ca791a2976f1157b6bd98af22e42281d51ecc0a9917570da91bbd7439d
|
Provenance
The following attestation bundles were made for humanbaselines-0.1.0-py3-none-any.whl:
Publisher:
release.yml on valgorithmic/humanbaselines
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
humanbaselines-0.1.0-py3-none-any.whl -
Subject digest:
dd58879330fcd851628a5df8be0ebf9a7a3f228e816c0ee8c64b609974b5c565 - Sigstore transparency entry: 1855032256
- Sigstore integration time:
-
Permalink:
valgorithmic/humanbaselines@da3ad3cf15a3a2eff5efe19eda27c99ba5719809 -
Branch / Tag:
refs/heads/main - Owner: https://github.com/valgorithmic
-
Access:
private
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@da3ad3cf15a3a2eff5efe19eda27c99ba5719809 -
Trigger Event:
workflow_dispatch
-
Statement type: