Skip to content

API Reference

Models

backseat_driver.models.scene

Camera

Bases: StrEnum

The six cameras on a nuScenes vehicle, front-centre first then clockwise.

Source code in backseat_driver/models/scene.py
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Camera(StrEnum):
    """The six cameras on a nuScenes vehicle, front-centre first then clockwise."""

    FRONT = "front"
    FRONT_RIGHT = "front_right"
    BACK_RIGHT = "back_right"
    BACK = "back"
    BACK_LEFT = "back_left"
    FRONT_LEFT = "front_left"

    @property
    def channel(self) -> str:
        """The name nuScenes gives this camera, e.g. `CAM_FRONT`."""
        return f"CAM_{self.name}"

channel property

The name nuScenes gives this camera, e.g. CAM_FRONT.

SceneDescription

Bases: SceneKeyframe

A scene keyframe plus the natural-language description a VLM produced for it.

Source code in backseat_driver/models/scene.py
33
34
35
36
37
38
class SceneDescription(SceneKeyframe):
    """A scene keyframe plus the natural-language description a VLM produced for it."""

    description: str
    model_name: str
    generated_at: datetime = Field(default_factory=lambda: datetime.now(UTC))

SceneKeyframe

Bases: BaseModel

A single representative image picked to stand in for a whole scene.

Source code in backseat_driver/models/scene.py
23
24
25
26
27
28
29
30
class SceneKeyframe(BaseModel):
    """A single representative image picked to stand in for a whole scene."""

    scene_token: str
    scene_name: str
    camera_channel: str
    image_path: str
    reference_description: str | None = None  # nuScenes' own human-written scene label, used to score models

backseat_driver.models.job

DeadLetter

Bases: BaseModel

A task that ran out of retries, kept whole so it can be inspected or re-enqueued; the job only records why.

Source code in backseat_driver/models/job.py
36
37
38
39
40
41
42
class DeadLetter(BaseModel):
    """A task that ran out of retries, kept whole so it can be inspected or re-enqueued; the job only records why."""

    task: Literal["ingest", "caption"]
    payload: dict[str, Any]
    error: str
    failed_at: datetime

Job

Bases: JobReference

A request to describe every scene of the dataset, with its current progress.

Source code in backseat_driver/models/job.py
25
26
27
28
29
30
31
32
33
class Job(JobReference):
    """A request to describe every scene of the dataset, with its current progress."""

    state: JobState
    max_scenes: int | None  # counts scenes, however many cameras each has
    expected_scenes: int | None  # descriptions to produce: one per scene and camera
    completed_scenes: int  # descriptions recorded so far
    created_at: datetime
    error: str | None = None

JobDeadLetter

Bases: DeadLetter

A dead letter listed across jobs, so it says which job it belongs to.

Source code in backseat_driver/models/job.py
45
46
47
48
class JobDeadLetter(DeadLetter):
    """A dead letter listed across jobs, so it says which job it belongs to."""

    job_id: UUID | None  # None for a task whose payload named no job

JobReference

Bases: BaseModel

What ties a job's row, its queue messages and every worker log line together.

Source code in backseat_driver/models/job.py
 9
10
11
12
13
class JobReference(BaseModel):
    """What ties a job's row, its queue messages and every worker log line together."""

    job_id: UUID
    transaction_id: str  # correlates the API request, the job row, every queue message and worker log line

JobState

Bases: StrEnum

Lifecycle of a job, derived from scene counts and the recorded error rather than stored.

Source code in backseat_driver/models/job.py
16
17
18
19
20
21
22
class JobState(StrEnum):
    """Lifecycle of a job, derived from scene counts and the recorded error rather than stored."""

    PENDING = "pending"  # ingest hasn't reported how many scenes there are yet
    RUNNING = "running"
    COMPLETED = "completed"
    FAILED = "failed"  # a task ran out of retries (or the job could not be enqueued); `Job.error` says why

backseat_driver.models.tasks

CaptionTask

Bases: JobReference

Queue message: caption one scene's keyframe on behalf of a job.

Source code in backseat_driver/models/tasks.py
11
12
13
14
15
class CaptionTask(JobReference):
    """Queue message: caption one scene's keyframe on behalf of a job."""

    keyframe: SceneKeyframe
    image_uri: str  # where the image bytes are; the keyframe's `image_path` is only the key they are stored under

IngestTask

Bases: JobReference

Queue message: load the dataset and fan out one CaptionTask per keyframe (scene and camera).

Source code in backseat_driver/models/tasks.py
5
6
7
8
class IngestTask(JobReference):
    """Queue message: load the dataset and fan out one CaptionTask per keyframe (scene and camera)."""

    max_scenes: int | None = None  # counts scenes, not keyframes

Read

backseat_driver.read

Stage 1, read: get the scenes and their images.

SceneLoader turns a dataset into SceneKeyframes and ImageStore hands out an image's bytes. This package holds the simple core, a loader and a store that read a dataset on local disk. read/s3/ is the layer that puts the dataset in an S3-compatible bucket instead, for workers that share no disk.

Process

backseat_driver.process

Stage 2, process: caption a keyframe image with a vision-language model.

The Captioner port, built from a CaptionBackend (where inference runs) plus a CaptionModel (which model and prompt). The monolith calls it in-process; the distributed caption worker calls the same class once per queue task.

Write

backseat_driver.write

Stage 3, write: persist the SceneDescriptions.

describe (one process)   list[SceneDescription] ──▶ json_writer.write_json ──▶ output/*.json
workers (many machines)  one SceneDescription   ──▶ transport.job_store    ──▶ SQLite / Postgres

The two are different contracts: a batch written once at the end, and results recorded one by one. The second also carries the completion rule, since the job record says how many results to expect. It is part of the seam, so it lives in transport/job_store/, over the database in write/job_store/. show/ reads either and is not part of this stage.

Pipeline

backseat_driver.pipeline

The whole program in one place: read the scenes, process each image, write the descriptions.

keyframes = await loader.load_keyframes()           # read    (backseat_driver.read)
descriptions = [await describe_keyframe(...) ...]   # process (backseat_driver.process)
write_json(descriptions, path)                      # write   (backseat_driver.write), done by the caller

ScenePipeline runs the first two in one process; the describe command adds the third. The distributed layer splits the same steps across queues instead of changing them: IngestWorker is the read step, CaptionWorker calls describe_keyframe (the process step) once per task, and the job store is the write step.

The loader and captioner are abstract ports, so the pipeline is unit-testable with fakes and never imports nuscenes-devkit, transformers, or torch directly.

ScenePipeline

Runs the loader → captioner pipeline over every scene in the dataset.

Source code in backseat_driver/pipeline.py
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
class ScenePipeline:
    """Runs the loader → captioner pipeline over every scene in the dataset."""

    def __init__(self, loader: SceneLoader, captioner: Captioner, images: ImageStore, batch_size: int = 1) -> None:
        if batch_size < 1:
            raise ValueError(f"batch_size must be at least 1, got {batch_size}")
        self._loader = loader
        self._captioner = captioner
        self._images = images
        self._batch_size = batch_size

    async def run(
        self, max_scenes: int | None = None, on_progress: ProgressCallback | None = None
    ) -> list[SceneDescription]:
        """Progress is reported once per batch, with the batch's first keyframe, before the batch is captioned."""
        if max_scenes is not None and max_scenes < 1:
            raise ValueError(f"max_scenes must be at least 1, got {max_scenes}")
        # Loading the model and reading the scenes both take seconds and need nothing from each other.
        _, all_keyframes = await asyncio.gather(self._captioner.load(), self._loader.load_keyframes())
        keyframes = first_scenes(all_keyframes, max_scenes)

        descriptions: list[SceneDescription] = []
        for start in range(0, len(keyframes), self._batch_size):
            batch = keyframes[start : start + self._batch_size]
            if on_progress:
                on_progress(start + 1, len(keyframes), batch[0])
            async with AsyncExitStack() as copies:
                local_paths = [
                    str(await copies.enter_async_context(self._images.local_copy(self._images.uri_for(k.image_path))))
                    for k in batch
                ]
                descriptions.extend(await describe_keyframes(batch, self._captioner, local_paths))
        return descriptions

run(max_scenes=None, on_progress=None) async

Progress is reported once per batch, with the batch's first keyframe, before the batch is captioned.

Source code in backseat_driver/pipeline.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
async def run(
    self, max_scenes: int | None = None, on_progress: ProgressCallback | None = None
) -> list[SceneDescription]:
    """Progress is reported once per batch, with the batch's first keyframe, before the batch is captioned."""
    if max_scenes is not None and max_scenes < 1:
        raise ValueError(f"max_scenes must be at least 1, got {max_scenes}")
    # Loading the model and reading the scenes both take seconds and need nothing from each other.
    _, all_keyframes = await asyncio.gather(self._captioner.load(), self._loader.load_keyframes())
    keyframes = first_scenes(all_keyframes, max_scenes)

    descriptions: list[SceneDescription] = []
    for start in range(0, len(keyframes), self._batch_size):
        batch = keyframes[start : start + self._batch_size]
        if on_progress:
            on_progress(start + 1, len(keyframes), batch[0])
        async with AsyncExitStack() as copies:
            local_paths = [
                str(await copies.enter_async_context(self._images.local_copy(self._images.uri_for(k.image_path))))
                for k in batch
            ]
            descriptions.extend(await describe_keyframes(batch, self._captioner, local_paths))
    return descriptions

describe_keyframe(keyframe, captioner, local_path) async

Caption the file at local_path as the keyframe's scene. Shared by the batch pipeline and the caption worker.

The file to read is separate from keyframe.image_path, which is what the description records: the image is captioned from a local copy, but the result still names it by its dataset key.

Source code in backseat_driver/pipeline.py
29
30
31
32
33
34
35
async def describe_keyframe(keyframe: SceneKeyframe, captioner: Captioner, local_path: str) -> SceneDescription:
    """Caption the file at `local_path` as the keyframe's scene. Shared by the batch pipeline and the caption worker.

    The file to read is separate from `keyframe.image_path`, which is what the description records: the image is
    captioned from a local copy, but the result still names it by its dataset key.
    """
    return _describe(keyframe, await captioner.caption(local_path), captioner.model_name)

describe_keyframes(keyframes, captioner, local_paths) async

describe_keyframe for several keyframes at once, so the captioner can run them together.

Source code in backseat_driver/pipeline.py
38
39
40
41
42
43
44
45
46
47
48
async def describe_keyframes(
    keyframes: Sequence[SceneKeyframe], captioner: Captioner, local_paths: Sequence[str]
) -> list[SceneDescription]:
    """`describe_keyframe` for several keyframes at once, so the captioner can run them together."""
    if len(keyframes) != len(local_paths):
        raise ValueError(f"got {len(local_paths)} local paths for {len(keyframes)} keyframes")
    captions = await captioner.caption_many(local_paths)
    return [
        _describe(keyframe, caption, captioner.model_name)
        for keyframe, caption in zip(keyframes, captions, strict=True)
    ]

first_scenes(keyframes, max_scenes)

The keyframes of the first max_scenes scenes, in their original order; all of them when max_scenes is None.

Counts scenes, not keyframes: a multi-camera run has several keyframes per scene. Shared by the batch pipeline and the ingest worker, so max_scenes means the same in both.

Source code in backseat_driver/pipeline.py
63
64
65
66
67
68
69
70
71
72
def first_scenes(keyframes: list[SceneKeyframe], max_scenes: int | None) -> list[SceneKeyframe]:
    """The keyframes of the first `max_scenes` scenes, in their original order; all of them when `max_scenes` is None.

    Counts scenes, not keyframes: a multi-camera run has several keyframes per scene. Shared by the batch pipeline and
    the ingest worker, so `max_scenes` means the same in both.
    """
    if max_scenes is None:
        return keyframes
    kept = set(islice(dict.fromkeys(k.scene_token for k in keyframes), max_scenes))
    return [k for k in keyframes if k.scene_token in kept]

Transport

backseat_driver.transport

The seam between read and process: a queue, and the two workers at its ends.

Without it (describe) the program is one function call:

read ──────────────────────────▶ process ──▶ write

With it, the same steps become tasks. IngestWorker is the read step turned into a producer and CaptionWorker is the process and write steps run once per task:

read ──▶ IngestWorker ══ queue ══▶ CaptionWorker ──▶ write
                      (this package)

The queue is a JobQueue. InProcessJobQueue keeps both ends in one process on one thread (the API monolith, so just dev needs no broker). CeleryJobQueue puts RabbitMQ between them so the ends run on different machines.

Tasks finish one at a time, so the seam also brings a JobStore (job_store/, in this package): one row per description plus the job's expected count, which is how a job knows it is done. It is a SQLite file in the monolith and Postgres across machines. Only crossing machines needs read/s3/, because the workers then share no disk.

Show

backseat_driver.show

Showing the results: a separate role from describing.

Reads SceneDescriptions (from JSON files or the API's jobs), scores them and renders the model-comparison page. Nothing here runs a model or reads the dataset.

Config

backseat_driver.config

Settings

Bases: BaseSettings

Source code in backseat_driver/config.py
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
class Settings(BaseSettings):
    model_config = SettingsConfigDict(
        env_file=".env",
        env_prefix="BACKSEAT_DRIVER_",
        extra="ignore",
    )

    api_host: str = "127.0.0.1"
    api_port: int = 8080
    # Origins allowed to call the API from a browser; left empty, it is derived from the UI address below.
    cors_origins: list[str] = []
    log_format: Literal["colored", "json"] = "colored"

    # Model-comparison UI (`just ui`, `fastapi run backseat_driver/show/ui_server.py`)
    ui_host: str = "127.0.0.1"
    ui_port: int = 8081
    # Also show the API's completed jobs (re-read on every page load, newest per model), besides the result files.
    ui_all_jobs: bool = False
    # Where the browser reaches the API for the live-inference card, if not api_url (e.g. a port-forward).
    ui_public_api_url: str | None = None

    # nuScenes dataset: the dataroot is a cache, filled from nuscenes_url when <dataroot>/<version> is missing
    nuscenes_dataroot: str = "data/sets/nuscenes"
    nuscenes_version: str = "v1.0-mini"
    nuscenes_url: str = "https://d36yt3mvayqw5m.cloudfront.net/public/v1.0/v1.0-mini.tgz"
    camera_channel: str = "CAM_FRONT"

    # VLM captioning
    vlm_backend: VlmBackend = VlmBackend.HUGGINGFACE
    vlm_model_name: str | None = None
    ollama_model_name: str | None = None
    ollama_url: str = "http://localhost:11434"
    anthropic_model_name: str | None = None
    anthropic_api_key: SecretStr | None = None
    # Images `describe` captions together: one forward pass for HuggingFace, concurrent requests for Anthropic. 1 turns
    # batching off.
    caption_batch_size: int = Field(default=8, ge=1)

    # Where the monolith keeps its jobs (a SQLite file), so they survive a restart and the report UI can list them.
    # Distributed mode uses `database_url` instead.
    jobs_db_path: str = "output/jobs.db"

    # How the API runs `/jobs`. Monolith by default so local dev needs nothing else running; docker compose
    # sets `distributed`.
    mode: RunMode = RunMode.MONOLITH

    # Distributed mode only (API + queue workers)
    rabbitmq_url: str = "amqp://guest:guest@localhost:5672/"
    database_url: str = "postgresql+psycopg://backseat_driver:backseat_driver@localhost:5432/backseat_driver"
    # Where the dataset lives for the distributed workers and API (S3-compatible; credentials via the AWS_* variables).
    # Required when `mode` is distributed (checked below) and unused by the monolith, hence no default. The endpoint is
    # only for S3-compatible stores that are not AWS.
    dataset_bucket: str | None = None
    s3_endpoint_url: str | None = None

    # Pipeline output: `describe` writes <output_dir>/<backend>__<model>.json unless told otherwise
    output_dir: str = "output"

    def model_name_for(self, backend: VlmBackend | None = None, model_name: str | None = None) -> str:
        """The model that `backend` (default: the configured one) runs; `model_name` overrides the configured one."""
        backend = backend or self.vlm_backend
        if model_name:
            return model_name
        if backend is VlmBackend.HUGGINGFACE:
            configured, variable = self.vlm_model_name, "BACKSEAT_DRIVER_VLM_MODEL_NAME"
        elif backend is VlmBackend.OLLAMA:
            configured, variable = self.ollama_model_name, "BACKSEAT_DRIVER_OLLAMA_MODEL_NAME"
        elif backend is VlmBackend.ANTHROPIC:
            configured, variable = self.anthropic_model_name, "BACKSEAT_DRIVER_ANTHROPIC_MODEL_NAME"
        else:
            raise ValueError(f"Unknown captioner backend {backend!r}")
        if not configured:
            raise ValueError(f"No model chosen for the {backend.value} backend: pass --model or set {variable}")
        return configured

    def output_path_for(self, backend: VlmBackend | None = None, model_name: str | None = None) -> str:
        """Default result file for a backend/model pair, so runs of different models never overwrite each other."""
        backend = backend or self.vlm_backend
        # Model names contain "/" and ":" (e.g. "Salesforce/blip-...", "llava:13b"), which are unsafe in filenames.
        slug = re.sub(r"[^A-Za-z0-9._-]+", "-", self.model_name_for(backend, model_name)).strip("-")
        return f"{self.output_dir}/{backend.value}__{slug}.json"

    @model_validator(mode="after")
    def _distributed_needs_a_dataset_bucket(self) -> Self:
        if self.mode is RunMode.DISTRIBUTED and not self.dataset_bucket:
            raise ValueError("BACKSEAT_DRIVER_DATASET_BUCKET must be set when BACKSEAT_DRIVER_MODE is distributed")
        return self

    @model_validator(mode="after")
    def _default_cors_origins(self) -> Self:
        if not self.cors_origins:
            hosts = dict.fromkeys(["127.0.0.1", "localhost", self.ui_host])
            self.cors_origins = [f"http://{host}:{self.ui_port}" for host in hosts]
        return self

    @computed_field  # type: ignore[prop-decorator]
    @property
    def api_url(self) -> str:
        return f"http://{self.api_host}:{self.api_port}"

model_name_for(backend=None, model_name=None)

The model that backend (default: the configured one) runs; model_name overrides the configured one.

Source code in backseat_driver/config.py
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
def model_name_for(self, backend: VlmBackend | None = None, model_name: str | None = None) -> str:
    """The model that `backend` (default: the configured one) runs; `model_name` overrides the configured one."""
    backend = backend or self.vlm_backend
    if model_name:
        return model_name
    if backend is VlmBackend.HUGGINGFACE:
        configured, variable = self.vlm_model_name, "BACKSEAT_DRIVER_VLM_MODEL_NAME"
    elif backend is VlmBackend.OLLAMA:
        configured, variable = self.ollama_model_name, "BACKSEAT_DRIVER_OLLAMA_MODEL_NAME"
    elif backend is VlmBackend.ANTHROPIC:
        configured, variable = self.anthropic_model_name, "BACKSEAT_DRIVER_ANTHROPIC_MODEL_NAME"
    else:
        raise ValueError(f"Unknown captioner backend {backend!r}")
    if not configured:
        raise ValueError(f"No model chosen for the {backend.value} backend: pass --model or set {variable}")
    return configured

output_path_for(backend=None, model_name=None)

Default result file for a backend/model pair, so runs of different models never overwrite each other.

Source code in backseat_driver/config.py
 96
 97
 98
 99
100
101
def output_path_for(self, backend: VlmBackend | None = None, model_name: str | None = None) -> str:
    """Default result file for a backend/model pair, so runs of different models never overwrite each other."""
    backend = backend or self.vlm_backend
    # Model names contain "/" and ":" (e.g. "Salesforce/blip-...", "llava:13b"), which are unsafe in filenames.
    slug = re.sub(r"[^A-Za-z0-9._-]+", "-", self.model_name_for(backend, model_name)).strip("-")
    return f"{self.output_dir}/{backend.value}__{slug}.json"

Logger

backseat_driver.logger

HTTP API

backseat_driver.api.app

create_app(settings, build_http=build_http_client)

Build the service for settings; tests build their own with dependency_overrides instead of patching.

Source code in backseat_driver/api/app.py
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
def create_app(settings: Settings, build_http: Callable[[], HttpClient] = build_http_client) -> FastAPI:
    """Build the service for `settings`; tests build their own with `dependency_overrides` instead of patching."""

    @asynccontextmanager
    async def lifespan(app: FastAPI) -> AsyncGenerator[None]:
        setup_logging(LogFormat(settings.log_format), service="api")

        http = build_http()
        captioner = build_captioner(settings, http)
        # The bucket in distributed mode, the local dataroot otherwise; a distributed API without a bucket fails here.
        image_store = build_image_store(settings)
        # In distributed mode neither client connects until first use, so startup never blocks on the broker
        # or database; /ready reports whether they are reachable.
        job_queue, job_store = await build_job_backend(settings, captioner, image_store)
        # The queue closes first, as its consumer uses the store and the captioner, whose calls use the HTTP client;
        # each still closes if one before it raises.
        async with aclosing(http), aclosing(job_store), aclosing(job_queue):
            app.state.services = AppState(settings, captioner, image_store, job_queue, job_store)

            logger.bind(api_url=settings.api_url, mode=settings.mode).info("startup complete")
            yield
        logger.info("shutdown")

    app = FastAPI(title="Backseat Driver", lifespan=lifespan)
    app.add_middleware(RequestIDMiddleware)
    app.add_middleware(CORSMiddleware, allow_origins=settings.cors_origins, allow_methods=["GET", "POST"])
    app.add_exception_handler(BackseatDriverError, backseat_driver_error_handler)  # type: ignore
    app.add_exception_handler(APIError, api_error_handler)  # type: ignore
    app.add_exception_handler(Exception, unhandled_exception_handler)
    app.include_router(health_router)
    app.include_router(describe_router)
    app.include_router(jobs_router)
    app.include_router(images_router)
    return app