Interactive
Interactive¶
- start(package_manager: Literal['npm', 'bun'] = 'npm', shareable: bool = False, subdomain: str = 'app', api_server_name: str = '127.0.0.1', api_port: int = 5000, frontend_port: int = 8000, dev: bool = False, skip_build: bool = True) Tuple[meerkat.state.APIInfo, meerkat.state.FrontendInfo] ¶
Start a Meerkat interactive server.
- Parameters
package_manager (str) – the frontend package_manager to use. Defaults to “npm”.
shareable (bool) – whether to share the interface at a publicly accesible link. This feature works by establishing a reverse SSH tunnel to a Meerkat server. Do not use this feature with private data. In order to use this feature, you will need an SSH key for the server. If you already have one, add it to the file at f”{config.system.ssh_identity_file}, or set the option mk.config.system.ssh_identity_file to the file where they are stored. If you don’t yet have a key, you can request access by emailing eyuboglu@stanford.edu. Remember to ensure after downloading it that the identity file is read/write only by the user (e.g. with chmod 600 path/to/id_file). See subdomain arg for controlling the domain name of the shared link. Defaults to False.
subdomain (str) – the subdomain to use for the shared link. For example, if subdomain=”myinterface”, then the shareable link will have the domain myinterface.meerkat.wiki. Defaults to None, in which case a random subdomain will be generated.
api_server_name (str) – the name of the API server. Defaults to “localhost”.
api_port (int) – the port to use for the Meerkat API server. Defaults to 5000.
frontend_port (int) – the port to use for the Meerkat Vite server. Defaults to 8000.
dev (bool) – whether to run in development mode. Defaults to True.
- Returns
- A tuple containing the APIInfo and
FrontendInfo objects.
- Return type
Tuple[APIInfo, FrontendInfo]
- class BaseComponent(**kwargs)¶
- property frontend¶
Returns a Pydantic model that can be should be sent to the frontend.
These models are typically named <something>Frontend (e.g. ComponentFrontend, StoreFrontend).
- property virtual_props¶
Props, and all events (as_*) as props.
- class Component(**kwargs)¶
Component with simple defaults.
- class Page(component: meerkat.interactive.app.src.lib.component.abstract.BaseComponent, id: str, name: str = 'Page', height: str = '100%', width: str = '100%', progress: bool = False)¶
- class Store(wrapped: meerkat.interactive.graph.store.T, backend_only: bool = False)¶
-
- property frontend¶
Returns a Pydantic model that can be should be sent to the frontend.
These models are typically named <something>Frontend (e.g. ComponentFrontend, StoreFrontend).
- set(new_value: meerkat.interactive.graph.store.T) None ¶
Set the value of the store.
This will trigger any reactive functions that depend on this store.
- Parameters
new_value (T) – The new value of the store.
- Returns
None
Note
Even if the new_value is the same as the current value, this will still trigger any reactive functions that depend on this store. To avoid this, check for equality before calling this method.
- class Endpoint(fn: Optional[Callable] = None, prefix: Optional[Union[str, fastapi.routing.APIRouter]] = None, route: Optional[str] = None)¶
- property frontend¶
Returns a Pydantic model that can be should be sent to the frontend.
These models are typically named <something>Frontend (e.g. ComponentFrontend, StoreFrontend).
- run(*args, **kwargs) Any ¶
Actually run the endpoint function fn.
- Parameters
*args – Positional arguments to pass to fn.
**kwargs – Keyword arguments to pass to fn.
- Returns
The return value of fn.
- compose(fn: Union[meerkat.interactive.endpoint.Endpoint, Callable]) meerkat.interactive.endpoint.Endpoint ¶
Create a new Endpoint that applies fn to the return value of this Endpoint. Effectively equivalent to fn(self.fn(*args, **kwargs)).
If the return value is None and fn doesn’t take any inputs, then fn will be called with no arguments.
- endpoint(fn: Optional[Callable] = None, prefix: Optional[Union[str, fastapi.routing.APIRouter]] = None, route: Optional[str] = None, method: str = 'POST') meerkat.interactive.endpoint.Endpoint ¶
Decorator to mark a function as an endpoint.
- An endpoint is a function that can be called to
update the value of a Store (e.g. incrementing a counter)
update a DataFrame (e.g. adding a new row)
run a computation and return its result to the frontend
- run a function in response to a frontend event (e.g. button
click)
Endpoints differ from reactive functions in that they are not automatically triggered by changes in their inputs. Instead, they are triggered by explicit calls to the endpoint function.
The Store and DataFrame objects that are modified inside the endpoint function will automatically trigger reactive functions that depend on them.
@endpoint def increment(count: Store, step: int = 1): count.set(count + step) # ^ update the count Store, which will trigger operations # that depend on it # Create a button that calls the increment endpoint counter = Store(0) button = Button(on_click=increment(counter)) # ^ read this as: call the increment endpoint with the `counter` # Store when the button is clicked
- Parameters
fn – The function to decorate.
prefix – The prefix to add to the route. If a string, it will be prepended to the route. If an APIRouter, the route will be added to the router.
route – The route to add to the endpoint. If not specified, the route will be the name of the function.
method – The HTTP method to use for the endpoint. Defaults to “POST”.
- Returns
The decorated function, as an Endpoint object.
- endpoints(cls: Optional[type] = None, prefix: Optional[str] = None)¶
Decorator to mark a class as containing a collection of endpoints. All instance methods in the marked class will be converted to endpoints.
This decorator is useful when you want to create a class that contains some logical state variables (e.g. a Counter class), along with methods to manipulate the values of those variables (e.g. increment or decrement the counter).
- make_endpoint(endpoint_or_fn: Optional[Union[Callable, meerkat.interactive.endpoint.Endpoint]]) meerkat.interactive.endpoint.Endpoint ¶
Make an Endpoint.
- reactive(fn: Optional[Callable] = None, nested_return: bool = False, skip_fn: Optional[Callable[[...], bool]] = None, backend_only: bool = False) Callable ¶
Internal decorator that is used to mark a function as reactive. This is only meant for internal use, and users should use the
react()
decorator instead.Functions decorated with this will create nodes in the operation graph, which are executed whenever their inputs are modified.
A basic example that adds two numbers:
@reactive def add(a: int, b: int) -> int: return a + b a = Store(1) b = Store(2) c = add(a, b)
When either a or b is modified, the add function will be called again with the new values of a and b.
A more complex example that concatenates two mk.DataFrame objects:
@reactive def concat(df1: mk.DataFrame, df2: mk.DataFrame) -> mk.DataFrame: return mk.concat([df1, df2]) df1 = mk.DataFrame(...) df2 = mk.DataFrame(...) df3 = concat(df1, df2)
- Parameters
fn – See
react()
.nested_return – See
react()
.skip_fn – See
react()
.
- Returns
See
react()
.
- class unmarked¶
A context manager and decorator that forces all objects within it to behave as if they are not marked. This means that any functions (reactive or not) called with those objects will never be rerun.
Effectively, functions (by decoration) or blocks of code (with the context manager) behave as if they are not reactive.
Examples:
Consider the following function:
>>> @reactive ... def f(x): ... return x + 1
If we call f with a marked object, then it will be rerun if the object changes:
>>> x = mark(1) >>> f(x) # f is rerun when x changes
Now, suppose we call f inside another function g that is not reactive:
>>> def g(x): ... out = f(x) ... return out
If we call g with a marked object, then the out variable will be recomputed if the object changes. Even though g is not reactive, f is, and f is called within g with a marked object.
Sometimes, this might be what we want. However, sometimes we want to ensure that a function or block of code behaves as if it is not reactive.
For this behavior, we can use the unmarked context manager:
>>> with unmarked(): ... g(x) # g and nothing in g is rerun when x changes
Or, we can use the unmarked decorator:
>>> @unmarked ... def g(x): ... out = f(x) ... return out
In both cases, the out variable will not be recomputed if the object changes, even though f is reactive.
- is_unmarked_context() bool ¶
Whether the code is in an unmarked context.
- Returns
True if the code is in an unmarked context.
- Return type
- mark(input: meerkat.interactive.graph.marking.T) meerkat.interactive.graph.marking.T ¶
Mark an object.
If the input is an object, then the object will become reactive: all of its methods and properties will become reactive. It will be returned as a Store object.
- Parameters
input – Any object to mark.
- Returns
A reactive function or object.
Examples:
Use mark on primitive types:
>>> x = mark(1) >>> # x is now a `Store` object
Use mark on complex types:
>>> x = mark([1, 2, 3])
Use mark on instances of classes:
>>> import pandas as pd >>> df = pd.DataFrame({"a": [1, 2, 3]}) >>> x: Store = mark(df) >>> y = x.head()
>>> class Foo: ... def __init__(self, x): ... self.x = x ... def __call__(self): ... return self.x + 1 >>> f = Foo(1) >>> x = mark(f)
Use mark on functions:
>>> aggregation = mark(mean)
- class DataFrameModification(*, id: str, scope: List[str], type: str = 'ref')¶
- property node: Node¶
The Reference or Store node that this modification is for.
- class Modification(*, id: str)¶
Base class for modifications.
Modifications are used to track changes to Reference and Store nodes in the graph.
- property node¶
The Reference or Store node that this modification is for.
- add_to_queue()¶
Add this modification to the queue.
- class State(prefix=None, *args, **kwargs)¶
- class ChangeList(df: DataFrame, v1_column: str, v2_column: str, label_column: str, main_column: str, embed_column: str, repo_path: str, tag_columns: List[str] = None, metric: str = 'Accuracy', v1_name: str = None, v2_name: str = None, code_control: bool = False)¶
- class FMFilter(df=<class 'meerkat.dataframe.DataFrame'>, on_run: meerkat.interactive.endpoint.Endpoint = None, manifest_session=None)¶
- print(*objects: Any, sep: str = ' ', end: str = '\n', file: Optional[IO[str]] = None, flush: bool = False) None ¶
Print object(s) supplied via positional arguments. This function has an identical signature to the built-in print. For more advanced features, see the
Console
class.- Parameters
sep (str, optional) – Separator between printed objects. Defaults to ” “.
end (str, optional) – Character to write at end of output. Defaults to “\n”.
file (IO[str], optional) – File to write to, or None for stdout. Defaults to None.
flush (bool, optional) – Has no effect as Rich always flushes output. Defaults to False.
- class Button(*, title: str, icon: str = None, classes: str = 'bg-slate-100 py-1 rounded-md flex flex-col hover:bg-slate-200', on_click: meerkat.interactive.endpoint.EndpointProperty[meerkat.interactive.event.EventInterface] = None, **kwargs)¶
- class Caption(text: str, *, classes: str = '', body: str, base_url: Optional[str] = None, breaks: bool = True, gfm: bool = True, header_ids: bool = True, header_prefix: str = '', lang_prefix: str = 'language-', mangle: bool = True, pedantic: bool = False, sanitize: bool = False, silent: bool = False, smartypants: bool = False, xhtml: bool = False, **kwargs)¶
Display caption text in a smaller, gray font size.
Use this component for explanatory text that is not the main body of a section. This will place the text in a <p> tag.
- Default Tailwind classes:
text-sm text-gray-400
- class Carousel(df: meerkat.dataframe.DataFrame, *, main_column: str)¶
- class Chat(*, df: meerkat.dataframe.DataFrame, img_chatbot: str = 'http://placekitten.com/200/300', img_user: str = 'http://placekitten.com/200/300', on_send: Optional[meerkat.interactive.endpoint.Endpoint[meerkat.interactive.app.src.lib.component.core.chat.OnSendChat]] = None, **kwargs)¶
A chat component.
- Parameters
df (DataFrame) – The dataframe to sync with the chat. It must have the following columns: message (str): The message to display. name (str): The name of the sender. time (str): The time the message was sent. sender (str): The sender of the message. Must be either “user” or “chatbot”.
imgChatbot (str) – The image to display for the chatbot, as a URL.
imgUser (str) – The image to display for the user, as a URL.
on_send –
The Endpoint to call when a message is sent. It must have the following signature:
(message: str)
- with
message (str): The message sent by the user.
- class Checkbox(*, checked: bool = False, disabled: bool = False, color: Literal['blue', 'red', 'green', 'purple', 'teal', 'yellow', 'orange'] = 'purple', classes: str = '', on_change: Optional[meerkat.interactive.endpoint.Endpoint] = None, **kwargs)¶
- class Code(*, body: str, theme: str = 'okaidia', background: str = 'bg-slate-800', language: str = 'python', classes: str = '', **kwargs)¶
- class CodeCell(code: str = 'df', on_run: meerkat.interactive.endpoint.Endpoint = None)¶
- class Document(*, df: meerkat.dataframe.DataFrame, text_column: str, paragraph_column: Optional[str] = None, label_column: Optional[str] = None, id_column: Optional[str] = None, **kwargs)¶
- classmethod events()¶
Built-in mutable sequence.
If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified.
- class Editor(*, code: str = '', title: str = 'Code Editor', on_run: meerkat.interactive.endpoint.EndpointProperty[meerkat.interactive.app.src.lib.component.core.editor.OnRunEditor] = None, **kwargs)¶
- class FileUpload(*, files: list = [], filenames: list = [], contents: list = [], classes: Optional[str] = None, webkitdirectory: bool = False, directory: bool = False, multiple: bool = False, on_upload: meerkat.interactive.endpoint.Endpoint[meerkat.interactive.app.src.lib.component.core.fileupload.OnUploadFileUpload] = None, **kwargs)¶
- class Filter(df: meerkat.dataframe.DataFrame = None, *, criteria: List[meerkat.interactive.app.src.lib.component.core.filter.FilterCriterion] = [], operations: List[str] = ['==', '!=', '>', '<', '>=', '<=', 'in', 'not in', 'contains'], title: str = 'Filter', classes: str = '')¶
- class Gallery(df: meerkat.dataframe.DataFrame, *, main_column: str = None, tag_columns: List[str] = None, selected: List[int] = [], allow_selection: bool = False, cell_size: int = 24, per_page: int = 20, page: int = 0)¶
- class Header(text: str, *, classes: str = '', body: str, base_url: Optional[str] = None, breaks: bool = True, gfm: bool = True, header_ids: bool = True, header_prefix: str = '', lang_prefix: str = 'language-', mangle: bool = True, pedantic: bool = False, sanitize: bool = False, silent: bool = False, smartypants: bool = False, xhtml: bool = False, **kwargs)¶
Display header text.
Use this component for the main header of a section. This will place the text in an <h2> tag.
- class Image(*, data: str, classes: str = '', enable_zoom: bool = False, enable_pan: bool = False, **kwargs)¶
- class ImageAnnotator(data, *, categories=None, segmentations=None, points=None, boxes=None, opacity: float = 0.85, selected_category: str = '', on_add_category: meerkat.interactive.endpoint.EndpointProperty[meerkat.interactive.app.src.lib.component.core.image_annotator.AddCategoryInterface] = None, on_add_box: meerkat.interactive.endpoint.EndpointProperty[meerkat.interactive.app.src.lib.component.core.image_annotator.AddBoxInterface] = None, on_add_point: meerkat.interactive.endpoint.EndpointProperty[meerkat.interactive.app.src.lib.component.core.image_annotator.AddPointInterface] = None)¶
- class Icon(*, data: str = '', name: str = 'Globe2', fill: Optional[str] = None, size: int = 16, **kwargs)¶
- class Json(*, body: dict, padding: float = 2.0, classes: str = '', **kwargs)¶
Render a JSON object as a collapsible tree.
- class Markdown(body: str, *, classes: str = '', base_url: Optional[str] = None, breaks: bool = True, gfm: bool = True, header_ids: bool = True, header_prefix: str = '', lang_prefix: str = 'language-', mangle: bool = True, pedantic: bool = False, sanitize: bool = False, silent: bool = False, smartypants: bool = False, xhtml: bool = False)¶
- class Match(df: meerkat.dataframe.DataFrame = None, *, against: str, text: str = '', encoder: Union[str, Encoder] = 'clip', title: str = 'Match', enable_selection: bool = False, reset_criterion: bool = False, on_match: meerkat.interactive.endpoint.EndpointProperty = None, get_match_schema: meerkat.interactive.endpoint.EndpointProperty = None, on_clickminus: meerkat.interactive.endpoint.Endpoint = None, on_unclickminus: meerkat.interactive.endpoint.Endpoint = None, on_clickplus: meerkat.interactive.endpoint.Endpoint = None, on_unclickplus: meerkat.interactive.endpoint.Endpoint = None, on_reset: meerkat.interactive.endpoint.Endpoint = None)¶
- class MedicalImage(*, data: List[str], classes: str = '', show_toolbar: bool = False, dim: int, segmentation_column: str = '', on_fetch: meerkat.interactive.endpoint.EndpointProperty[meerkat.interactive.app.src.lib.component.core.medimage.OnFetchInterface], cell_info: Any = None, **kwargs)¶
A component for displaying medical images.
- Parameters
data – An array of base64 encoded images.
classes – A string of classes to apply to the component.
show_toolbar – Whether to show the toolbar.
on_fetch – An endpoint to call when the component needs to fetch data.
- class MultiSelect(*, choices: meerkat.interactive.graph.store.Store[list], selected: meerkat.interactive.graph.store.Store[list] = None, gui_type: str = 'multiselect', title: str = None, **kwargs)¶
- class Radio(*, name: str, value: str = '', disabled: bool = False, color: Literal['blue', 'red', 'green', 'purple', 'teal', 'yellow', 'orange'] = 'purple', classes: str = 'bg-violet-50 p-2 rounded-lg w-fit', on_change: Optional[meerkat.interactive.endpoint.Endpoint[meerkat.interactive.app.src.lib.component.core.radio.OnChangeRadio]] = None, **kwargs)¶
A single radio button.
If you just want a basic group of radio buttons, use the RadioGroup component instead. Use this component only if you want to customize the layout of a group of radio buttons.
For more advanced use cases, we recommend either using the basic HTML radio button element and styling it yourself with Tailwind, or using the Flowbite Radio component.
- Parameters
name (str) – The name of this radio button. Assign the same name to multiple radio buttons to group them together.
value (str) – The value associated with this radio button.
disabled (bool) – Whether this radio button is disabled.
color (Literal['blue', 'red', 'green', 'purple', 'teal', 'yellow', 'orange']) – The color of this radio button.
classes (str) – The Tailwind classes to apply to the component.
on_change –
The Endpoint to call when this radio button is selected. It must have the following signature:
(index: int)
- with
index (int): The index of the selected radio button.
- class RadioGroup(*, values: List[str], selected: Optional[int] = None, disabled: bool = False, horizontal: bool = True, color: Literal['blue', 'red', 'green', 'purple', 'teal', 'yellow', 'orange'] = 'purple', classes: str = 'bg-violet-50 p-2 rounded-lg w-fit', on_change: Optional[meerkat.interactive.endpoint.Endpoint[meerkat.interactive.app.src.lib.component.core.radio.OnChangeRadioGroup]] = None, **kwargs)¶
A basic group of radio buttons.
- Parameters
values (List[str]) – The values associated with each radio button. The number of radio buttons will be the length of this list.
selected (Optional[int]) – The index of the selected radio button (0-indexed). If None, no radio button will be preselected by default.
disabled (bool) – Whether this radio group is disabled. If True, all radio buttons will be disabled and the user will not be able to select any of them.
horizontal (bool) – Whether to display the radio buttons horizontally. Defaults to True.
color (Literal['blue', 'red', 'green', 'purple', 'teal', 'yellow', 'orange']) – The color of the radio buttons.
classes (str) – The Tailwind classes to apply to the component.
on_change –
The Endpoint to call when the selected radio button changes. It must have the following signature:
(index: int)
- with
index (int): The index of the selected radio button.
- class RawHTML(*, html: str, view: str = 'full', sanitize: bool = True, classes: bool = 'rounded-md shadow-md', **kwargs)¶
- class Number(*, data: Any = None, dtype: str = 'auto', precision: int = 3, percentage: bool = False, classes: str = '', editable: bool = False, **kwargs)¶
- class NumberInput(value: Union[int, float], *, placeholder: str = 'Enter a number...', debounceTimer: int = 150, classes: str = 'grow h-10 px-3 rounded-md shadow-md my-1 border-gray-400', on_blur: Optional[meerkat.interactive.endpoint.Endpoint[meerkat.interactive.app.src.lib.component.core.numberinput.OnBlurNumberInput]] = None, on_keyenter: Optional[meerkat.interactive.endpoint.Endpoint[meerkat.interactive.app.src.lib.component.core.numberinput.OnKeyEnterNumberInput]] = None)¶
- class Select(values: List[Any], *, labels: List[str] = None, value: Any = None, disabled: bool = False, classes: str = '', on_change: Optional[meerkat.interactive.endpoint.Endpoint[meerkat.interactive.app.src.lib.component.core.select.OnChangeSelect]] = None)¶
A selection dropdown that can be used to select a single value from a list of options.
- Parameters
values (List[Any]) – A list of values to select from.
labels (List[str]) – A list of labels to display for each value.
value (Any) – The selected value.
disabled (bool) – Whether the select is disabled.
classes (str) – The Tailwind classes to apply to the select.
on_change –
The Endpoint to call when the selected value changes. It must have the following signature:
(value: Union[str, int, float, bool, None])
- with
value (Union[str, int, float, bool, None]): The value of the selected radio button.
- class SliceByCards(sliceby: meerkat.ops.sliceby.sliceby.SliceBy, main_column: str, tag_columns: List[str] = None, aggregations: Dict[str, Callable[[DataFrame], Union[int, float, str]]] = None, df: meerkat.dataframe.DataFrame = None)¶
- class Slider(*, value: Union[float, int] = 0.0, min: Union[float, int] = 0.0, max: Union[float, int] = 100.0, step: Union[float, int] = 1.0, disabled: bool = False, classes: str = 'bg-violet-50 px-4 py-1 rounded-lg', on_change: Optional[meerkat.interactive.endpoint.Endpoint[meerkat.interactive.app.src.lib.component.core.slider.OnChangeSlider]] = None, **kwargs)¶
A slider that allows the user to select a value from a range.
- Parameters
value – The current value of the slider.
min – The minimum value of the slider.
max – The maximum value of the slider.
step – The step size of the slider.
disabled – Whether the slider is disabled.
classes – The Tailwind classes to apply to the component.
- class Sort(df: meerkat.dataframe.DataFrame, *, criteria: List[meerkat.interactive.app.src.lib.component.core.sort.SortCriterion] = [], title: str = 'Sort', classes: str = '')¶
- class Subheader(text: str, *, classes: str = '', body: str, base_url: Optional[str] = None, breaks: bool = True, gfm: bool = True, header_ids: bool = True, header_prefix: str = '', lang_prefix: str = 'language-', mangle: bool = True, pedantic: bool = False, sanitize: bool = False, silent: bool = False, smartypants: bool = False, xhtml: bool = False, **kwargs)¶
Display subheader text.
Use this component for the subheader of a section. This will place the text in an <h3> tag.
- class Table(df: meerkat.dataframe.DataFrame, *, selected: List[int] = [], single_select: bool = False, classes: str = 'h-fit', on_edit: meerkat.interactive.endpoint.EndpointProperty = None, on_select: meerkat.interactive.endpoint.EndpointProperty = None)¶
- class Tabs(*, tabs: Union[Mapping[str, meerkat.interactive.app.src.lib.component.abstract.BaseComponent], Sequence[meerkat.interactive.app.src.lib.component.core.tabs.Tab]], **kwargs)¶
- class Textbox(text: str = '', *, placeholder: str = 'Write some text...', debounce_timer: int = 150, classes: str = 'grow h-10 px-3 rounded-md shadow-md my-1 border-gray-400', on_blur: Optional[meerkat.interactive.endpoint.Endpoint[meerkat.interactive.app.src.lib.component.core.textbox.OnBlurTextbox]] = None, on_keyenter: Optional[meerkat.interactive.endpoint.Endpoint[meerkat.interactive.app.src.lib.component.core.textbox.OnKeyEnterTextbox]] = None)¶
- class Title(text: str, *, classes: str = '', body: str, base_url: Optional[str] = None, breaks: bool = True, gfm: bool = True, header_ids: bool = True, header_prefix: str = '', lang_prefix: str = 'language-', mangle: bool = True, pedantic: bool = False, sanitize: bool = False, silent: bool = False, smartypants: bool = False, xhtml: bool = False, **kwargs)¶
Display title text.
Use this component for the main title of a page. This will place the text in an <h1> tag.
- class Toggle(*, value: bool = False, on_change: meerkat.interactive.endpoint.Endpoint[meerkat.interactive.app.src.lib.component.core.toggle.OnChangeToggle] = None, **kwargs)¶