Skip to content

DataWidgetFactory

DataWidgetFactory builds the widgets of a view from a Store. Its widgets read the rows of the Store, save the edits to it, and share the selected rows: selecting a note in a table shows its text in a text widget and its fields in a form. Review entities builds a first view with it.

from metanno import DataRelation, DataWidgetFactory

factory = DataWidgetFactory(
    store, relations=[DataRelation("notes", "entities", on="note_id")]
)

relations links the tables of the Store, here the entities to their note, see Annotate across levels.

Widgets

Method Shows Used in
create_table_widget the rows of a table, to filter, sort and edit Annotate a table
create_text_widget the text of the selected row with its entities highlighted, and a toolbar of labels Review entities
create_form_widget the fields of the selected row, with buttons to go to the previous or next row Design your view
create_selected_field_view one field of the selected row, such as the ID of a note above its text Design your view
create_pdf_widget the PDF of the selected row, in the PDF viewer of the browser see below
create_status_bar the last edit Python refused, and whether the view is connected to Python Design your view

Tables, texts and forms take a fields list, which picks the columns to show and how to edit them, see Choose how each field is shown.

The PDF widget asks a Python function for the document of the selected row, for instance to show the original report next to its extracted text. The function receives the row and returns the PDF as bytes, after converting other formats, such as scans, if needed:

from pathlib import Path


def load_report(note):
    """
    Read the PDF of a note from the folder of the original reports
    """
    return Path(f"reports/{note['note_id']}.pdf").read_bytes()


pdf = factory.create_pdf_widget(
    store_key="notes", primary_key="note_id", loader=load_report
)

Behavior in the interface

The widgets behave the same way in every view:

  • a checkbox or a choice is saved as soon as it is clicked, a text field when you press Enter or click elsewhere, while Esc, or selecting another row, cancels it
  • when several rows are selected, changing a field changes it for all of them, as one edit
  • Ctrl+Z undoes the last change made in the view and Ctrl+Y or Ctrl+Shift+Z redoes it, with Cmd on a Mac, while inside a text field these keys undo the typing
  • when Python refuses an edit, for instance because someone else changed the same cell, the field shows why. A Metanno tab shows the last refusal under the view, add create_status_bar to views shown in a notebook or a web app
  • the text widget shows the document of the selected row, or with docs_mode="selected" every selected document, and with docs_mode="all" all the documents of the table, or those under the selected parent row of a related table
  • a table related to other tables by DataRelation shows the rows under the selected row of one of them, chosen above it among those with a selected row, e.g. All, Patient and Stay for notes. While no stay is selected, the notes of the selected patient show. Clicking a note selects and scrolls to its stay and its patient in their tables, which then show the stays of that patient, while the notes stay shown until Stay is clicked

Reference

Build tables, forms and annotation views that share a PRET Store.

Widgets created by this factory edit the same data and share row selection. The factory keeps selection separately from the data so navigation does not enter the data undo history.

Parameters

PARAMETER DESCRIPTION
data

Existing PRET Store, or initial mapping of row lists and DataFrames

TYPE: Union[Store, Dict[str, Any], Callable[[], Dict]]

sync

Used when creating a Store from initial data. False or None keeps edits in the browser. True synchronizes with Python without saving to disk. A file path also saves edits and lets other Python processes open the same Store

TYPE: Optional[Union[bool, str, PathLike]] DEFAULT: None

relations

Parent and child columns used to filter linked tables

TYPE: Sequence[DataRelation] DEFAULT: ()

read_only

Disable mutations from these widgets without changing notebook access to the Store

TYPE: bool DEFAULT: False

create_table_widget [source]

Create a Table widget bound to a store entry. Field metadata is inferred from the underlying data, with optional callbacks for selection changes, hover, and cell content clicks. An imperative handle can be exposed for scrolling and filtering.

Parameters

PARAMETER DESCRIPTION
store_key

Key pointing to the list-like store to render.

TYPE: Any

primary_key

Column identifying rows, shared selections store its values. Required for lists of rows, with None a DataFrame table clears its selection when its rows change.

TYPE: str | None

fields

Field metadata used for rendering and editing. Expects:

  • key: Field key.
  • name: Field display name.
  • kind: Field data kind:

    • "text": Plain text.
    • "boolean": Boolean values.
    • "hyperlink": Clickable hyperlink.
    • "select"/"radio"/"autocomplete": Multi choice selection.
  • options: If present, a dropdown/autocomplete will be used with the provided options (can also be a function that takes the selected sample as input and returns options).

  • editable: If True, cells in this column are editable.
  • filterable: If False, no filter control will be rendered.

TYPE: Sequence[FieldSpec]

style

Inline style of the table container, which fills its parent unless these keys override it, e.g. a fixed height in a notebook output.

TYPE: Dict[str, Any] | None DEFAULT: None

handle

Imperative handle exposing helpers :

  • scroll_to_row_id(row_id): Scroll to the row with the given primary key
  • scroll_to_row_idx(row_idx): Scroll to the specified row index.
  • select_row_id(row_id): Select the row with the given primary key, as a click on it would.
  • set_filter(col, value): Apply a filter on the given column.
  • get_filters(): Retrieve the current filter mapping.
  • clear_filters(): Clear all active filters.
  • set_highlighted(row_ids): Highlight the specified rows by their IDs.
  • get_adjacent_row_id(current_row_id, delta): Retrieve the next/previous row ID within the filtered view, wrapping around.
  • get_adjacent_row_idx(current_row_idx, delta): Retrieve the next/previous row index within the filtered view, wrapping around.

TYPE: RefType[TableWidgetHandle] | None DEFAULT: None

accept_related_filter_keys

Controls whether this table accepts filters broadcast by other views when the factory declares no relation for them, tables linked by a DataRelation follow the selection of their parent instead. True accepts all incoming filters, False accepts none, and a sequence restricts accepted filter keys.

TYPE: bool | Sequence[str] DEFAULT: True

on_selection_change

Called when focus moves inside the table.

  • row_id: Primary key of the focused row.
  • row_idx: Index of the focused row.
  • col: Field key receiving focus.
  • mode: Interaction mode, such as "EDIT" or "SELECT".
  • cause: What triggered the move (e.g. "key", "mouse").
  • ranges: Row ranges selected by range selection.

TYPE: Callable | None DEFAULT: None

on_mouse_hover_row

Called when the mouse hovers over a row.

  • row_id: Primary key for that row.
  • row_idx: Index of the row under the pointer.
  • modkeys: Pressed modifier keys during the hover.

TYPE: Callable[[Any, int, List[str]], None] | None DEFAULT: None

on_click_cell_content

Called when hyperlink-like content inside a cell is clicked.

  • row_id: Primary key of the clicked row.
  • row_idx: Index of the clicked row.
  • col: Field key containing the clickable content.
  • value: Value associated with the clicked cell.

TYPE: Callable[[Any, int, str, Any], None] | None DEFAULT: None

source_requery

Show an action for fetching the DataFrame source again.

TYPE: bool DEFAULT: False

include_unconfigured_columns

Show columns missing from fields without allowing edits to them.

TYPE: bool DEFAULT: False

follow_parent_selection

For the child of a working_set DataRelation, start with only the rows under the selected parent row shown, instead of every row. Choices above a related table pick the ancestor to follow among those with a selected row, e.g. All, Patient and Stay for notes under stays under patients, or All and Patient while no stay is selected. Without a selected row of the chosen ancestor, the table follows the nearest selected one above it. An ancestor row selected by clicking a row of this table is only followed once chosen, so the rows shown stay. These choices only change what the table shows, not the rows loaded for other widgets. The child of a selection DataRelation always follows an ancestor.

TYPE: bool DEFAULT: False

parent_row_name

Name of one row of the parent table, e.g. "stay", in the choices of this table and of the tables below it. Defaults to the Store key of the parent table.

TYPE: str | None DEFAULT: None

default_sort

Columns ordering the rows whenever the user has not sorted the table by a column header, when it opens and after Clear sort, e.g. ["note_id", "begin"] for the entities of each note in text order, or [("score", "desc")] for the highest scores of every row shown first. A header sort replaces this order while it is active.

TYPE: Sequence[str | Tuple[str, str]] | None DEFAULT: None

RETURNS DESCRIPTION
Renderable

A Pret component instance rendering the configured table.

create_text_widget [source]

Build a text annotation widget that pairs a text store with a spans store. Provides toolbar buttons for creating spans, keyboard navigation between documents, and callbacks for hover and click events.

Parameters

PARAMETER DESCRIPTION
store_text_key

Key pointing to the store containing documents.

TYPE: Any

store_spans_key

Key pointing to the store containing span annotations. If None, an empty store is created and managed locally, e.g. to only show the text of DataFrame rows.

TYPE: Any DEFAULT: None

text_key

Field name holding the raw text to annotate.

TYPE: str

text_primary_key

Field name that uniquely identifies each text document.

TYPE: str

spans_primary_key

Field name that uniquely identifies each span, required with store_spans_key.

TYPE: str | None DEFAULT: None

fields

Field metadata for span fields, used in the inline editor.

TYPE: Sequence[FieldSpec] DEFAULT: ()

begin_key

Field name for span start offsets.

TYPE: str DEFAULT: 'begin'

end_key

Field name for span end offsets.

TYPE: str DEFAULT: 'end'

style_key

Field name for span styling configuration key. Spans without it use the style of their button_key value when it is a key of labels, otherwise the first label.

TYPE: str DEFAULT: 'style'

label_key

Field name for span display label.

TYPE: str DEFAULT: 'label'

label_formatter

Optional function used to compute the rendered label text for each span. It receives the full span dictionary and should return a string.

If left as None, the uppercased label_key field will be used.

TYPE: Callable[[Dict[str, Any]], str] | None DEFAULT: None

button_key

Field name that annotation buttons will update.

TYPE: str DEFAULT: 'label'

labels

Mapping of label name to styling config (e.g. color, shortcut).

TYPE: Dict[str, Dict[str, Any]] DEFAULT: None

style

Inline style overrides for the text widget wrapper and content panes.

TYPE: Dict[str, Any] | None DEFAULT: None

handle

Imperative handle exposing helpers:

  • scroll_to_span(span_id): Scroll to the specified span.
  • set_doc_idx(doc_idx): Select the document at this position among all documents.
  • get_doc_idx(): Retrieve the position of the active document among all documents.
  • set_highlighted_spans(span_ids): Highlight the specified spans.
  • set_selected_span(span_id): Set the currently selected span.

TYPE: RefType[TextWidgetHandle] | None DEFAULT: None

on_change_text_id

Called when navigation changes the active document.

  • doc_id: Identifier of the newly active document.

TYPE: Callable[[Any], None] | None DEFAULT: None

on_add_span

Called after new spans are created from the current selection.

  • span_ids: List of identifiers for the newly created spans.

TYPE: Callable[[List[str]], None] | None DEFAULT: None

on_hover_spans

Called whenever spans are hovered.

  • span_ids: List of identifiers for the currently hovered spans.
  • mod_keys: Modifier keys pressed during the hover.

TYPE: Callable[[List[str], List[str]], None] | None DEFAULT: None

on_click_span

Called when a span is clicked.

  • span_id: Identifier of the clicked span.
  • mod_keys: Modifier keys pressed during the click.

TYPE: Callable[[str, List[str]], None] | None DEFAULT: None

on_select_text

Called when the text selected in a document changes, including when it is cleared.

  • doc_id: Identifier of the document.
  • ranges: Selected {"begin", "end"} offsets, empty when the selection is cleared.
  • text: Text of the first range, empty when the selection is cleared.

TYPE: Callable[[Any, List[Dict[str, int]], str], None] | None DEFAULT: None

docs_mode

Controls which documents are displayed:

  • "lead": show only the lead selected document.
  • "selected": show every selected document.
  • "all": show every document from the current store. Documents of a DataFrame that is the child of a DataRelation show only the documents under the selected parent row, or under the nearest selected ancestor when no parent row is selected, e.g. the notes of a patient.

TYPE: Literal['lead', 'selected', 'all'] DEFAULT: 'lead'

container_renderer

Optional callback used to wrap each rendered document. It receives (row, component, shared_toolbar) and may also accept optional keyword arguments note_idx and note_count. It should return a renderable. By default, documents are wrapped as div(component).

TYPE: Callable[[Dict[str, Any], Renderable, Optional[Renderable]], Renderable] | None DEFAULT: None

RETURNS DESCRIPTION
Tuple[Renderable, Renderable]

A pair of Pret components: the toolbar widget and the text widget.

create_form_widget [source]

Render a single record from a store as a classic form with text, select, and boolean inputs. The current row can be changed via the imperative handle to keep multiple widgets in sync. When multiple rows are selected in a linked table, fields show mixed values and edits are applied to every selected row.

Parameters

PARAMETER DESCRIPTION
store_key

Key pointing to the collection to edit

TYPE: Any

primary_key

Field name that uniquely identifies each row (primary key)

TYPE: str

fields

Field metadata used for rendering and editing:

  • key: Field key
  • name: Field display name
  • kind: Field data kind:

    • "text": single-line text input
    • "select": dropdown select input
    • "autocomplete": autocomplete text input
    • "radio": radio button group
    • "boolean": checkbox input
  • editable: If False, the field will be read-only

  • options: If present, a dropdown/autocomplete/radio will be used

An empty list shows every column of a DataFrame, editable when the DataFrame is

TYPE: Sequence[FieldSpec]

style

Inline style overrides for the wrapping container, which has an 8px padding by default

TYPE: Dict[str, Any] | None DEFAULT: None

min_input_width

Minimum width applied to each input control

TYPE: str | None DEFAULT: None

add_navigation_buttons

Whether to display previous/next navigation buttons

TYPE: bool DEFAULT: False

allow_delete

Show a button that deletes the selected rows in one Store action

TYPE: bool DEFAULT: False

handle

Imperative handle exposing helpers:

  • set_row_idx(row_idx): Select the row at this position among all rows
  • get_row_idx(): Retrieve the position of the current row among all rows

TYPE: RefType[FormWidgetHandle] | None DEFAULT: None

RETURNS DESCRIPTION
Renderable

A Pret component instance rendering the editable form

create_selected_field_view [source]

Render a single field from the currently selected row in a store.

Parameters

PARAMETER DESCRIPTION
store_key

Key pointing to the collection to display

TYPE: Any

shown_key

Field key to show from the current row

TYPE: Any

fallback

Value returned when no row is available

TYPE: str | None DEFAULT: ''

RETURNS DESCRIPTION
Renderable

Pret component instance displaying the selected field value

create_pdf_widget [source]

Show the PDF of the lead selected row of a collection in the browser PDF viewer, e.g. beside a documents table.

Parameters

PARAMETER DESCRIPTION
store_key

Key of the collection or DataFrame whose selected row is shown

TYPE: Any

primary_key

Field identifying the rows, as in the table showing them

TYPE: str

loader

Called in Python with the selected row, returns the PDF bytes, e.g. read from a folder of downloaded files. Other formats, such as scans or DOCX files, can be converted to PDF there.

TYPE: Callable[[Any], bytes]

style

Inline style of the container, which fills its parent unless these keys override it

TYPE: Dict[str, Any] | None DEFAULT: None

RETURNS DESCRIPTION
Renderable

A Pret component showing the PDF, or a loading, empty or error message

create_status_bar [source]

Return a bar showing the last rejected edit or undo of the Store and its connection to Python, place it below the widgets of a notebook output or an app. Factory widgets do not show Store errors themselves

Parameters

PARAMETER DESCRIPTION
show_connection

Also show whether the Store is connected, disconnected or offline

TYPE: bool DEFAULT: True