Module

pixano.datasets.dataset

Classes

class

Dataset

The Pixano Dataset. It is a collection of tables that can be queried and manipulated with LanceDB. Tables are defined by the :class:`DatasetInfo` ``tables`` mapping, which maps table names to :class:`LanceModel` schema classes. The main table is always named ``"records"`` and its schema must inherit from :class:`Record`. All auxiliary tables must have schemas that inherit from :class:`RecordComponent`. Attributes: path: Path to the dataset. info: Dataset info (including table→schema mapping). features_values: Dataset features values. stats: Dataset statistics. thumbnail: Dataset thumbnail base 64 URL.

Attributes

Name Type Default Description
FILTER_INDEX_COLUMNS dict[str, str] {'id': 'BTREE', 'record_id': 'BTREE', 'entity_id': 'BTREE', 'view_id': 'BTREE', 'frame_id': 'BTREE', 'tracklet_id': 'BTREE', 'frame_index': 'BTREE', 'logical_name': 'BITMAP', 'split': 'BITMAP', 'status': 'BITMAP', 'source_type': 'BITMAP'}
features_values — DatasetFeaturesValues.from_json(self._features_values_file)
id str — Return the dataset ID.
info DatasetInfo DatasetInfo.from_json(self._info_file)
num_rows int — Return the number of rows in the record table. Returns: Number of rows.
path Path path
previews_path — self.path / self._PREVIEWS_PATH
stats list[DatasetStatistic] DatasetStatistic.from_json(self._stat_file) if self._stat_file.is_file() else []
thumbnail Path self._thumb_file

Methods

__init__ (path)

Initialize the dataset. Args: path: Path to the dataset.

Parameter Type Default
path Path —
add_constraint (table, field_name, values, restricted)

Add or replace a constraint. Args: table: Table name. field_name: Name of the field to constrain. values: List of allowed values. restricted: True if no other values are allowed.

Parameter Type Default
table TableName —
field_name str —
values List[Union[int, float, str, bool]] —
restricted bool True
add_data (table_name, data, ignore_integrity_checks, raise_or_warn) → list[LanceModel]

Add data to a table. Args: table_name: Table name. data: Data to add. ignore_integrity_checks: List of integrity checks to ignore. raise_or_warn: Whether to raise or warn on integrity errors. Returns: The added data.

Parameter Type Default
table_name str —
data list[LanceModel] —
ignore_integrity_checks list[IntegrityCheck] | None None
raise_or_warn Literal['raise', 'warn', 'none'] 'raise'
add_record_embeddings (rows) → None

Append rows to the record-embedding table (plain float vectors, no model). Args: rows: Dicts with at least ``record_id`` and ``vector``; ``id``/``view_id`` optional.

Parameter Type Default
rows list[dict[str, Any]] —
add_records (data, check_integrity, stamp_timestamps) → None

Insert rows into multiple tables in a single call. Accepts the same ``dict[str, LanceModel | list[LanceModel]]`` format yielded by :meth:`DatasetBuilder.generate_data`. Tables are flushed in dependency order (source -> record -> view -> entity -> entity_dynamic_state -> annotation -> embedding) so that foreign-key constraints are satisfied. Args: data: Mapping of table name to one or more rows to insert. ``None`` or empty-list values are silently skipped. check_integrity: Integrity-check mode. ``"raise"`` (default) aborts on the first error, ``"warn"`` emits warnings, ``"none"`` skips validation. stamp_timestamps: Overwrite ``created_at``/``updated_at`` with now (default). Importers pass ``False`` so explicitly provided timestamps (e.g. a re-imported export) survive; rows without explicit values keep their construction-time defaults, which are equally "now".

Parameter Type Default
data dict[str, LanceModel | list[LanceModel]] —
check_integrity Literal['raise', 'warn', 'none'] 'raise'
stamp_timestamps bool True
build_record_embedding_index () → None

Build the vector + record_id indexes on the record-embedding table. The vector (ANN) index needs enough rows to train; when there are too few, it is skipped and search falls back to an exact brute-force scan (still correct).

compute_view_embeddings (table_name, data) → None

Compute the view embeddings via the embedding function stored in the table metadata. Args: table_name: Table name containing the view embeddings. data: Data to compute. Dictionary representing a view embedding without the vector field.

Parameter Type Default
table_name str —
data list[dict] —
count_rows_where (table_name, where) → int

Count rows in a table, optionally filtered by a WHERE clause. Uses LanceDB native count_rows() which avoids full table materialization. Args: table_name: Table name. where: Optional WHERE clause to filter rows. Returns: Number of matching rows.

Parameter Type Default
table_name str SchemaGroup.RECORD.value
where str | None None
create (path, info) → 'Dataset'

Create a new dataset on disk. This initialises the directory structure, writes ``info.json`` and ``features_values.json``, creates the LanceDB database with empty tables for every entry in ``info.tables`` and returns the opened :class:`Dataset`. Args: path: Directory where the dataset will be stored. The directory is created (with parents) and **must not already exist**. info: Dataset information including the ``tables`` mapping. If ``info.id`` is empty, a random ID is generated automatically. Returns: The newly created dataset. Raises: FileExistsError: If ``path`` already exists. ValueError: If ``info.tables`` is empty or invalid.

Parameter Type Default
path Path —
info DatasetInfo —
create_record_embedding_table (dim, model_id, metric, source_view, index_type) → None

Create (or replace) the record-embedding table and persist its sidecar descriptor. Args: dim: Embedding dimensionality. model_id: Identifier of the model that produced the vectors. metric: Distance metric (``cosine``/``l2``/``dot``). source_view: Logical view the embeddings were computed from. index_type: LanceDB vector index type to build once populated.

Parameter Type Default
dim int —
model_id str —
metric str 'cosine'
source_view str 'image'
index_type str 'IVF_PQ'
create_scalar_indexes (columns, tables) → None

Create scalar indexes on the given columns of the given tables. Idempotent: columns that are already indexed or absent from a table's schema are skipped. Indexes make ``merge_insert``, foreign-key lookups, export paging, and filtered pagination scale past full-table scans. Args: columns: Column names to index where present. Defaults to the standard filter columns (``FILTER_INDEX_COLUMNS``). tables: Table names to index. Defaults to every dataset table.

Parameter Type Default
columns Sequence[str] | None None
tables Sequence[str] | None None
create_table (name, schema, data, mode, exist_ok, on_bad_vectors, fill_value) → LanceTable

Add a table to the dataset. Args: name: Table name. schema: Table schema (must be a LanceModel subclass). data: Table data. mode: Table mode ('create', 'overwrite'). exist_ok: If True, do not raise an error if the table already exists. on_bad_vectors: Raise an error, drop or fill bad vectors ("error", "drop", "fill"). fill_value: Value to fill bad vectors. Returns: The table created.

Parameter Type Default
name str —
schema type[LanceModel] —
data DATA | None None
mode str 'create'
exist_ok bool False
on_bad_vectors str 'error'
fill_value float 0.0
delete_data (table_name, ids) → list[str]

Delete data from a table. Args: table_name: Table name. ids: Ids to delete. Returns: The list of ids not found.

Parameter Type Default
table_name str —
ids list[str] —
delete_records (ids) → list[str]

Delete records and all associated data across all tables. Cascading deletion: deletes from the record table first, then from all auxiliary tables where ``record_id`` matches the given ids. Args: ids: Record ids to delete. Returns: The list of ids not found in the record table.

Parameter Type Default
ids list[str] —
drop_record_embeddings () → None

Delete the record-embedding table and its sidecar descriptor. Safe on missing/corrupt tables; used by force-recompute to escape states where the sidecar advertises embeddings whose table is broken.

find (id, directory) → 'Dataset'

Find a Dataset in a directory. Args: id: Dataset ID to find. directory: Directory to search in. Returns: The found dataset.

Parameter Type Default
id str —
directory Path —
find_ids_in_table (table_name, ids) → dict[str, bool]

Search ids in a table. Args: table_name: Table name. ids: Ids to find. Returns: Dictionary of ids found. Keys are the ids and values are True if found.

Parameter Type Default
table_name str —
ids set[str] —
generate_preview () → str

Generate a preview for the dataset. It samples images from the dataset, creates a mosaic and saves it to the previews directory. Only images with embedded blob data are used. Returns: The preview base64 string.

get_all_ids (table_name, sortcol, order, where) → list[str]

Get all the ids from a table. Args: table_name: table to look for ids. sortcol: column to order by. order: sort order (asc or desc). where: where clause to filter ids. Returns: list of the ids.

Parameter Type Default
table_name str SchemaGroup.RECORD.value
sortcol str | None None
order str | None None
where str | None None
get_conversation (table_name, conversation_id) → Conversation | None

Read one conversation aggregate from a messages table. Args: table_name: The messages table name. conversation_id: The conversation ID. Returns: The conversation or None if not found.

Parameter Type Default
table_name str —
conversation_id str —
get_conversations (table_name, record_id, entity_id, view_id, source_type, where, limit, skip) → tuple[list[Conversation], int]

Read paginated conversation aggregates from a messages table. Args: table_name: The messages table name. record_id: Filter by record ID. entity_id: Filter by entity ID. view_id: Filter by view ID. source_type: Filter by source type. where: Additional WHERE clause. limit: Maximum conversations to return. skip: Number of conversations to skip. Returns: Tuple of (conversations, total_count).

Parameter Type Default
table_name str —
record_id str | None None
entity_id str | None None
view_id str | None None
source_type str | None None
where str | None None
limit int | None 100
skip int 0
get_data (table_name, ids, limit, skip, where, record_ids, sortcol, order, force_full_scan) → list[LanceModel] | LanceModel | None

Read data from a table. Data can be filtered by ids, record ids, where clause, or limit and skip. Args: table_name: Table name. ids: ids to read. limit: Amount of rows to read. If not set, will default to table size. skip: The number of rows to skip. where: Where clause. record_ids: Record ids to filter by (filters on ``record_id`` column). sortcol: column to order by. order: sort order (asc or desc). force_full_scan: Force the safe full-scan-then-slice path (for a ``where`` using an operator a scalar index can't serve, e.g. ``!=`` or ``LIKE``). See `TableQueryBuilder.force_full_scan`. Returns: List of values.

Parameter Type Default
table_name str —
ids list[str] | str | None None
limit int | None None
skip int 0
where str | None None
record_ids list[str] | None None
sortcol str | None None
order str | None None
force_full_scan bool False
get_neighbors (record_id, table_name, where, sortcol, order) → dict[str, Any]

Locate a record within a filtered, sorted result set and its neighbors. Powers item-to-item navigation in the explorer: given the same filter and sort the table view uses, return the ids immediately before and after ``record_id`` and its 1-based position, so previous/next stay inside the current result set instead of walking the whole dataset. The scan projects only the ``id`` column (ordered with an ``id`` tie-break for a stable order) and returns a tiny payload. For a record that is not in the filtered set, ``prev``/``next``/``position`` are ``None``. Args: record_id: The record to locate. table_name: Table to navigate (defaults to the record table). where: Where clause matching the explorer's active filter. sortcol: Column to order by (defaults to ``id``). order: Sort order, ``"asc"`` or ``"desc"`` (defaults to ``"asc"``). Returns: ``{"prev": str | None, "next": str | None, "position": int | None, "total": int}``.

Parameter Type Default
record_id str —
table_name str SchemaGroup.RECORD.value
where str | None None
sortcol str | None None
order str | None None
get_records (ids, limit, skip) → list[Record] | Record | None

Read records from the record table. Args: ids: Record ids to read. limit: Amount of records to read. skip: The number of records to skip. Returns: List of records, a single record, or None.

Parameter Type Default
ids list[str] | str | None None
limit int | None None
skip int 0
get_splits_count () → list[SplitStatusCount]

Get record counts grouped by split and status. Opens the record table as PyArrow, groups by ``["split", "status"]`` and aggregates counts. If the ``status`` column does not exist the table is old-schema and an empty list is returned for backward compatibility. Returns: List of SplitStatusCount sorted by split asc then status asc.

get_temporal_view_batch (table_name, record_id, view_name, start_frame, batch_size) → list[tuple[int, bytes, str]]

Load one ordered batch of temporal view frames with their binary payloads. Returns a list of ``(frame_index, blob_bytes, format_string)`` tuples, reading from the embedded ``raw_bytes`` column. Args: table_name: View table name containing temporal frames. record_id: The record ID to filter by. view_name: Optional logical view name to filter by. start_frame: Starting frame index. batch_size: Number of frames to load. Returns: List of (frame_index, blob_bytes, format) tuples.

Parameter Type Default
table_name str —
record_id str —
view_name str | None None
start_frame int 0
batch_size int 100
get_view_binary (table_name, row_id) → tuple[bytes, str] | None

Load binary content for a single view row. Returns the embedded blob data and inferred format. Args: table_name: View table name. row_id: The row ID. Returns: Tuple of (blob_bytes, format_string) or None if not found.

Parameter Type Default
table_name str —
row_id str —
has_record_embeddings () → bool

Whether this dataset has a computed record-embedding table.

invalidate_caches (dataset_id) → None

Notify registered caches that a dataset changed on disk (e.g. after an import).

Parameter Type Default
dataset_id str —
list (directory) → list[DatasetInfo]

List the datasets information in directory. Args: directory: Directory to search in. Returns: List of dataset infos.

Parameter Type Default
directory Path —
merge_records (data, check_integrity, known_ids) → dict[str, int]

Upsert rows into multiple tables in a single call. The multi-table counterpart of :meth:`update_data` and the idempotent counterpart of :meth:`add_records`: rows whose ``id`` already exists are updated, new ids are inserted, so re-running the same payload converges instead of duplicating. Tables are processed in FK dependency order (record → view → entity → … → annotation). Args: data: Mapping of table name to one or more rows, or to an Arrow ``RecordBatch``/``Table``. Arrow payloads currently require ``check_integrity="none"`` — vectorized Arrow integrity checks land with the import engine (spec §8); missing ``created_at``/``updated_at`` columns are appended to Arrow payloads so the LanceDB schema cast cannot fail on them. check_integrity: Integrity-check mode for row payloads. Uniqueness against already-stored ids is intentionally not enforced (existing ids are updates by design); in-batch duplicates, missing ids, and foreign keys are checked. known_ids: Optional ``table → ids`` mapping (e.g. an import engine's id ledger) used to resolve foreign keys without DB lookups. Returns: Mapping of table name to number of rows upserted.

Parameter Type Default
data dict[str, LanceModel | list[LanceModel] | pa.RecordBatch | pa.Table] —
check_integrity Literal['raise', 'warn', 'none'] 'raise'
known_ids dict[str, set[str]] | None None
open_table (name) → LanceTable

Open a dataset table with LanceDB. Hold :meth:`write_lock` when mutating the returned LanceDB handle so local imports and rollback cannot run concurrently with that mutation. Args: name: Name of the table to open. Returns: Dataset table.

Parameter Type Default
name str —
open_tables (names, exclude_embeddings) → dict[str, LanceTable]

Open the dataset tables with LanceDB. Args: names: Table names to open. If None, open all tables. exclude_embeddings: Whether to exclude embedding tables from the list. Returns: Dataset tables.

Parameter Type Default
names list[str] | None None
exclude_embeddings bool True
record_embedding_health () → dict[str, Any]

Cheap health check of the record-embedding storage. The sidecar alone advertises semantic search; the physical LanceDB table is only touched at query time, so a crashed job or external deletion can leave the feature advertised but broken. This inspects metadata only (no vector scan). Returns: ``{"status", "model_id", "dim", "rows", "records", "detail"}`` where status is one of ``absent`` (no sidecar), ``missing_table``, ``empty``, ``dim_mismatch``, ``corrupt``, ``partial`` (fewer vectors than records) or ``ready``.

record_embedding_space () → dict[str, Any] | None

Return the record-embedding space descriptor (model, dim, metric), or None.

register_cache_invalidation_hook (hook) → None

Register a callable invoked with a dataset id when its caches must be dropped.

Parameter Type Default
hook Callable[[str], None] —
search_records (query_vector, k, record_id_filter) → tuple[list[LanceModel], list[float]]

Rank records by similarity of their embedding to ``query_vector``. Args: query_vector: The query embedding (same space/dim as the stored vectors). k: Maximum number of records to return. record_id_filter: Optional record-id allowlist applied as a vector-search prefilter. Returns: A tuple of ``(records, distances)`` ordered by increasing distance.

Parameter Type Default
query_vector Sequence[float] —
k int —
record_id_filter list[str] | None None
update_data (table_name, data, return_separately, ignore_integrity_checks, raise_or_warn) → list[LanceModel] | tuple[list[LanceModel], list[LanceModel]]

Update data in a table (upsert). Args: table_name: Table name. data: Data to update. return_separately: Whether to return separately added and updated data. ignore_integrity_checks: List of integrity checks to ignore. raise_or_warn: Whether to raise or warn on integrity errors. Returns: If ``return_separately`` is True, returns (updated_data, added_data). Otherwise, returns the full data list.

Parameter Type Default
table_name str —
data list[LanceModel] —
return_separately bool False
ignore_integrity_checks list[IntegrityCheck] | None None
raise_or_warn Literal['raise', 'warn', 'none'] 'raise'
write_lock ()

Protect a mutation and refresh cached handles before its integrity reads. Callers performing read/modify/write operations may hold this context around several Dataset methods; nesting in the same thread is safe.

Esc